@maucwerk/glimmer 0.0.0-stage → 1.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +43 -0
- package/README.md +888 -2
- package/dist/components/__edge_decorator.d.ts +36 -0
- package/dist/components/conditional_lines/conditional_edges_geometry.d.ts +7 -0
- package/dist/components/conditional_lines/conditional_line_segments_geometry.d.ts +24 -0
- package/dist/components/conditional_lines/outside_edges_geometry.d.ts +7 -0
- package/dist/components/glimmer_viewer.d.ts +9 -0
- package/dist/environment/environment.d.ts +42 -0
- package/dist/environment/index.d.ts +2 -0
- package/dist/environment/sun.d.ts +21 -0
- package/dist/gizmos/index.d.ts +4 -0
- package/dist/gizmos/move_gizmo.d.ts +89 -0
- package/dist/gizmos/rotate_gizmo.d.ts +86 -0
- package/dist/gizmos/section_box_gizmo.d.ts +91 -0
- package/dist/gizmos/section_box_manager.d.ts +82 -0
- package/dist/glimmer.d.ts +26 -0
- package/dist/index.d.ts +13 -0
- package/dist/main.d.ts +1 -0
- package/dist/model/index.d.ts +3 -0
- package/dist/model/model.d.ts +88 -0
- package/dist/model/model_loader.d.ts +9 -0
- package/dist/model/model_manager.d.ts +55 -0
- package/dist/outline/index.d.ts +2 -0
- package/dist/outline/outline_material.d.ts +13 -0
- package/dist/outline/outline_mesh.d.ts +10 -0
- package/dist/section/index.d.ts +3 -0
- package/dist/section/plane_handle.d.ts +39 -0
- package/dist/section/section_box.d.ts +78 -0
- package/dist/section/section_cap.d.ts +15 -0
- package/dist/settings/index.d.ts +2 -0
- package/dist/settings/schema.d.ts +353 -0
- package/dist/settings/settings.d.ts +20 -0
- package/dist/shaders/colored_shadow_material.d.ts +7 -0
- package/dist/shaders/conditional_edges_shader.d.ts +16 -0
- package/dist/shaders/conditional_line_material.d.ts +16 -0
- package/dist/story/anchor_marker.d.ts +74 -0
- package/dist/story/anchor_marker_manager.d.ts +102 -0
- package/dist/story/annotation_2d_renderer.d.ts +24 -0
- package/dist/story/annotation_3d_renderer.d.ts +29 -0
- package/dist/story/annotation_renderer.d.ts +35 -0
- package/dist/story/index.d.ts +7 -0
- package/dist/story/schema.d.ts +1154 -0
- package/dist/story/slide_transition_manager.d.ts +30 -0
- package/dist/story/story_manager.d.ts +170 -0
- package/dist/story/trigger_manager.d.ts +43 -0
- package/dist/utils/constants.d.ts +6 -0
- package/dist/utils/cursor_3d.d.ts +48 -0
- package/dist/utils/error.d.ts +54 -0
- package/dist/utils/index.d.ts +4 -0
- package/dist/utils/log.d.ts +8 -0
- package/dist/utils/utils.d.ts +2 -0
- package/dist/viewer/index.d.ts +1 -0
- package/dist/viewer/orbit_controller.d.ts +62 -0
- package/dist/viewer/raycast_helper.d.ts +37 -0
- package/dist/viewer/viewer.d.ts +141 -0
- package/dist/vite/glimmer.mjs +11522 -0
- package/dist/vite/glimmer.umd.js +914 -0
- package/package.json +64 -4
|
@@ -0,0 +1,914 @@
|
|
|
1
|
+
(function(te,u){typeof exports=="object"&&typeof module<"u"?u(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],u):(te=typeof globalThis<"u"?globalThis:te||self,u(te.Glimmer={},te.THREE))})(this,function(te,u){"use strict";var pl=Object.defineProperty;var ml=(te,u,vt)=>u in te?pl(te,u,{enumerable:!0,configurable:!0,writable:!0,value:vt}):te[u]=vt;var g=(te,u,vt)=>ml(te,typeof u!="symbol"?u+"":u,vt);function vt(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const _=vt(u);var J;(function(r){r.assertEqual=s=>s;function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{const i={};for(const o of s)i[o]=o;return i},r.getValidEnumValues=s=>{const i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(const a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(const o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(J||(J={}));var Yn;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Yn||(Yn={}));const D=J.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ke=r=>{switch(typeof r){case"undefined":return D.undefined;case"string":return D.string;case"number":return isNaN(r)?D.nan:D.number;case"boolean":return D.boolean;case"function":return D.function;case"bigint":return D.bigint;case"symbol":return D.symbol;case"object":return Array.isArray(r)?D.array:r===null?D.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?D.promise:typeof Map<"u"&&r instanceof Map?D.map:typeof Set<"u"&&r instanceof Set?D.set:typeof Date<"u"&&r instanceof Date?D.date:D.object;default:return D.unknown}},A=J.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Sr=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class De extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,c=0;for(;c<o.path.length;){const l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof De))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,J.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}De.create=r=>new De(r);const xt=(r,e)=>{let t;switch(r.code){case A.invalid_type:r.received===D.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case A.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,J.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:t=`Unrecognized key(s) in object: ${J.joinValues(r.keys,", ")}`;break;case A.invalid_union:t="Invalid input";break;case A.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${J.joinValues(r.options)}`;break;case A.invalid_enum_value:t=`Invalid enum value. Expected ${J.joinValues(r.options)}, received '${r.received}'`;break;case A.invalid_arguments:t="Invalid function arguments";break;case A.invalid_return_type:t="Invalid function return type";break;case A.invalid_date:t="Invalid date";break;case A.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:J.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case A.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case A.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case A.custom:t="Invalid input";break;case A.invalid_intersection_types:t="Intersection results could not be merged";break;case A.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case A.not_finite:t="Number must be finite";break;default:t=e.defaultError,J.assertNever(r)}return{message:t}};let Xs=xt;function Tr(r){Xs=r}function _n(){return Xs}const gn=r=>{const{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="";const c=n.filter(l=>!!l).slice().reverse();for(const l of c)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}},Mr=[];function O(r,e){const t=_n(),n=gn({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===xt?void 0:xt].filter(s=>!!s)});r.common.issues.push(n)}class ye{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const s of t){if(s.status==="aborted")return V;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const s of t){const i=await s.key,o=await s.value;n.push({key:i,value:o})}return ye.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const s of t){const{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return V;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}}const V=Object.freeze({status:"aborted"}),bt=r=>({status:"dirty",value:r}),be=r=>({status:"valid",value:r}),qn=r=>r.status==="aborted",Hn=r=>r.status==="dirty",lt=r=>r.status==="valid",Ft=r=>typeof Promise<"u"&&r instanceof Promise;function yn(r,e,t,n){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function $s(r,e,t,n,s){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}typeof SuppressedError=="function"&&SuppressedError;var P;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(P||(P={}));var jt,Bt;class je{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ks=(r,e)=>{if(lt(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new De(r.common.issues);return this._error=t,this._error}}};function X(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{var c,l;const{message:d}=r;return o.code==="invalid_enum_value"?{message:d??a.defaultError}:typeof a.data>"u"?{message:(c=d??n)!==null&&c!==void 0?c:a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:(l=d??t)!==null&&l!==void 0?l:a.defaultError}},description:s}}class K{get description(){return this._def.description}_getType(e){return Ke(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ye,ctx:{common:e.parent.common,data:e.data,parsedType:Ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Ft(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;const s={common:{issues:[],async:(n=t==null?void 0:t.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ke(e)},i=this._parseSync({data:e,path:s.path,parent:s});return Ks(s,i)}"~validate"(e){var t,n;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ke(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:s});return lt(i)?{value:i.value}:{issues:s.common.issues}}catch(i){!((n=(t=i==null?void 0:i.message)===null||t===void 0?void 0:t.toLowerCase())===null||n===void 0)&&n.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:s}).then(i=>lt(i)?{value:i.value}:{issues:s.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ke(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Ft(s)?s:Promise.resolve(s));return Ks(n,i)}refine(e,t){const n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{const o=e(s),a=()=>i.addIssue({code:A.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new ze({schema:this,typeName:B.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ve.create(this,this._def)}nullable(){return ot.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Re.create(this)}promise(){return Tt.create(this,this._def)}or(e){return Wt.create([this,e],this._def)}and(e){return Xt.create(this,e,this._def)}transform(e){return new ze({...X(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Ht({...X(this._def),innerType:this,defaultValue:t,typeName:B.ZodDefault})}brand(){return new es({typeName:B.ZodBranded,type:this,...X(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Jt({...X(this._def),innerType:this,catchValue:t,typeName:B.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Qt.create(this,e)}readonly(){return en.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Lr=/^c[^\s-]{8,}$/i,Cr=/^[0-9a-z]+$/,Or=/^[0-9A-HJKMNP-TV-Z]{26}$/i,kr=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Dr=/^[a-z0-9_-]{21}$/i,Ir=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Er=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Nr=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Jn;const Rr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,zr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ur=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Fr=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,jr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Br=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ys="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Vr=new RegExp(`^${Ys}$`);function qs(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Gr(r){return new RegExp(`^${qs(r)}$`)}function Hs(r){let e=`${Ys}T${qs(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Zr(r,e){return!!((e==="v4"||!e)&&Rr.test(r)||(e==="v6"||!e)&&Ur.test(r))}function Wr(r,e){if(!Ir.test(r))return!1;try{const[t]=r.split("."),n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||!s.typ||!s.alg||e&&s.alg!==e)}catch{return!1}}function Xr(r,e){return!!((e==="v4"||!e)&&zr.test(r)||(e==="v6"||!e)&&Fr.test(r))}class Pe extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==D.string){const i=this._getOrReturnCtx(e);return O(i,{code:A.invalid_type,expected:D.string,received:i.parsedType}),V}const n=new ye;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),O(s,{code:A.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),O(s,{code:A.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?O(s,{code:A.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&O(s,{code:A.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Nr.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"email",code:A.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Jn||(Jn=new RegExp(Pr,"u")),Jn.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"emoji",code:A.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")kr.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"uuid",code:A.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Dr.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"nanoid",code:A.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Lr.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"cuid",code:A.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Cr.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"cuid2",code:A.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Or.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"ulid",code:A.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),O(s,{validation:"url",code:A.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"regex",code:A.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),O(s,{code:A.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),O(s,{code:A.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),O(s,{code:A.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Hs(i).test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{code:A.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Vr.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{code:A.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Gr(i).test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{code:A.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Er.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"duration",code:A.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Zr(e.data,i.version)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"ip",code:A.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Wr(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"jwt",code:A.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Xr(e.data,i.version)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"cidr",code:A.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?jr.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"base64",code:A.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Br.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"base64url",code:A.invalid_string,message:i.message}),n.dirty()):J.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:A.invalid_string,...P.errToObj(n)})}_addCheck(e){return new Pe({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...P.errToObj(e)})}url(e){return this._addCheck({kind:"url",...P.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...P.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...P.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...P.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...P.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...P.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...P.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...P.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...P.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...P.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...P.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...P.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...P.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...P.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...P.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...P.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...P.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...P.errToObj(t)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new Pe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Pe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Pe({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Pe.create=r=>{var e;return new Pe({checks:[],typeName:B.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...X(r)})};function $r(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=parseInt(r.toFixed(s).replace(".","")),o=parseInt(e.toFixed(s).replace(".",""));return i%o/Math.pow(10,s)}class st extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==D.number){const i=this._getOrReturnCtx(e);return O(i,{code:A.invalid_type,expected:D.number,received:i.parsedType}),V}let n;const s=new ye;for(const i of this._def.checks)i.kind==="int"?J.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),O(n,{code:A.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),O(n,{code:A.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),O(n,{code:A.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?$r(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),O(n,{code:A.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),O(n,{code:A.not_finite,message:i.message}),s.dirty()):J.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,P.toString(t))}gt(e,t){return this.setLimit("min",e,!1,P.toString(t))}lte(e,t){return this.setLimit("max",e,!0,P.toString(t))}lt(e,t){return this.setLimit("max",e,!1,P.toString(t))}setLimit(e,t,n,s){return new st({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new st({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:P.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:P.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&J.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}st.create=r=>new st({checks:[],typeName:B.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...X(r)});class it extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==D.bigint)return this._getInvalidInput(e);let n;const s=new ye;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),O(n,{code:A.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),O(n,{code:A.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),O(n,{code:A.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):J.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return O(t,{code:A.invalid_type,expected:D.bigint,received:t.parsedType}),V}gte(e,t){return this.setLimit("min",e,!0,P.toString(t))}gt(e,t){return this.setLimit("min",e,!1,P.toString(t))}lte(e,t){return this.setLimit("max",e,!0,P.toString(t))}lt(e,t){return this.setLimit("max",e,!1,P.toString(t))}setLimit(e,t,n,s){return new it({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new it({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}it.create=r=>{var e;return new it({checks:[],typeName:B.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...X(r)})};class Vt extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==D.boolean){const n=this._getOrReturnCtx(e);return O(n,{code:A.invalid_type,expected:D.boolean,received:n.parsedType}),V}return be(e.data)}}Vt.create=r=>new Vt({typeName:B.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...X(r)});class dt extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==D.date){const i=this._getOrReturnCtx(e);return O(i,{code:A.invalid_type,expected:D.date,received:i.parsedType}),V}if(isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return O(i,{code:A.invalid_date}),V}const n=new ye;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),O(s,{code:A.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),O(s,{code:A.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):J.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new dt({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:P.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:P.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}dt.create=r=>new dt({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:B.ZodDate,...X(r)});class vn extends K{_parse(e){if(this._getType(e)!==D.symbol){const n=this._getOrReturnCtx(e);return O(n,{code:A.invalid_type,expected:D.symbol,received:n.parsedType}),V}return be(e.data)}}vn.create=r=>new vn({typeName:B.ZodSymbol,...X(r)});class Gt extends K{_parse(e){if(this._getType(e)!==D.undefined){const n=this._getOrReturnCtx(e);return O(n,{code:A.invalid_type,expected:D.undefined,received:n.parsedType}),V}return be(e.data)}}Gt.create=r=>new Gt({typeName:B.ZodUndefined,...X(r)});class Zt extends K{_parse(e){if(this._getType(e)!==D.null){const n=this._getOrReturnCtx(e);return O(n,{code:A.invalid_type,expected:D.null,received:n.parsedType}),V}return be(e.data)}}Zt.create=r=>new Zt({typeName:B.ZodNull,...X(r)});class wt extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return be(e.data)}}wt.create=r=>new wt({typeName:B.ZodAny,...X(r)});class ut extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return be(e.data)}}ut.create=r=>new ut({typeName:B.ZodUnknown,...X(r)});class Ye extends K{_parse(e){const t=this._getOrReturnCtx(e);return O(t,{code:A.invalid_type,expected:D.never,received:t.parsedType}),V}}Ye.create=r=>new Ye({typeName:B.ZodNever,...X(r)});class xn extends K{_parse(e){if(this._getType(e)!==D.undefined){const n=this._getOrReturnCtx(e);return O(n,{code:A.invalid_type,expected:D.void,received:n.parsedType}),V}return be(e.data)}}xn.create=r=>new xn({typeName:B.ZodVoid,...X(r)});class Re extends K{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==D.array)return O(t,{code:A.invalid_type,expected:D.array,received:t.parsedType}),V;if(s.exactLength!==null){const o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&(O(t,{code:o?A.too_big:A.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(O(t,{code:A.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(O(t,{code:A.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new je(t,o,t.path,a)))).then(o=>ye.mergeArray(n,o));const i=[...t.data].map((o,a)=>s.type._parseSync(new je(t,o,t.path,a)));return ye.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new Re({...this._def,minLength:{value:e,message:P.toString(t)}})}max(e,t){return new Re({...this._def,maxLength:{value:e,message:P.toString(t)}})}length(e,t){return new Re({...this._def,exactLength:{value:e,message:P.toString(t)}})}nonempty(e){return this.min(1,e)}}Re.create=(r,e)=>new Re({type:r,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...X(e)});function At(r){if(r instanceof re){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=Ve.create(At(n))}return new re({...r._def,shape:()=>e})}else return r instanceof Re?new Re({...r._def,type:At(r.element)}):r instanceof Ve?Ve.create(At(r.unwrap())):r instanceof ot?ot.create(At(r.unwrap())):r instanceof Be?Be.create(r.items.map(e=>At(e))):r}class re extends K{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=J.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==D.object){const l=this._getOrReturnCtx(e);return O(l,{code:A.invalid_type,expected:D.object,received:l.parsedType}),V}const{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ye&&this._def.unknownKeys==="strip"))for(const l in s.data)o.includes(l)||a.push(l);const c=[];for(const l of o){const d=i[l],h=s.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new je(s,h,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof Ye){const l=this._def.unknownKeys;if(l==="passthrough")for(const d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")a.length>0&&(O(s,{code:A.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const d of a){const h=s.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new je(s,h,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const d of c){const h=await d.key,f=await d.value;l.push({key:h,value:f,alwaysSet:d.alwaysSet})}return l}).then(l=>ye.mergeObjectSync(n,l)):ye.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return P.errToObj,new re({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var s,i,o,a;const c=(o=(i=(s=this._def).errorMap)===null||i===void 0?void 0:i.call(s,t,n).message)!==null&&o!==void 0?o:n.defaultError;return t.code==="unrecognized_keys"?{message:(a=P.errToObj(e).message)!==null&&a!==void 0?a:c}:{message:c}}}:{}})}strip(){return new re({...this._def,unknownKeys:"strip"})}passthrough(){return new re({...this._def,unknownKeys:"passthrough"})}extend(e){return new re({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new re({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:B.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new re({...this._def,catchall:e})}pick(e){const t={};return J.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new re({...this._def,shape:()=>t})}omit(e){const t={};return J.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new re({...this._def,shape:()=>t})}deepPartial(){return At(this)}partial(e){const t={};return J.objectKeys(this.shape).forEach(n=>{const s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}),new re({...this._def,shape:()=>t})}required(e){const t={};return J.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Ve;)i=i._def.innerType;t[n]=i}}),new re({...this._def,shape:()=>t})}keyof(){return Js(J.objectKeys(this.shape))}}re.create=(r,e)=>new re({shape:()=>r,unknownKeys:"strip",catchall:Ye.create(),typeName:B.ZodObject,...X(e)}),re.strictCreate=(r,e)=>new re({shape:()=>r,unknownKeys:"strict",catchall:Ye.create(),typeName:B.ZodObject,...X(e)}),re.lazycreate=(r,e)=>new re({shape:r,unknownKeys:"strip",catchall:Ye.create(),typeName:B.ZodObject,...X(e)});class Wt extends K{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new De(a.ctx.common.issues));return O(t,{code:A.invalid_union,unionErrors:o}),V}if(t.common.async)return Promise.all(n.map(async i=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i;const o=[];for(const c of n){const l={...t,common:{...t.common,issues:[]},parent:null},d=c._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(c=>new De(c));return O(t,{code:A.invalid_union,unionErrors:a}),V}}get options(){return this._def.options}}Wt.create=(r,e)=>new Wt({options:r,typeName:B.ZodUnion,...X(e)});const qe=r=>r instanceof Kt?qe(r.schema):r instanceof ze?qe(r.innerType()):r instanceof Yt?[r.value]:r instanceof rt?r.options:r instanceof qt?J.objectValues(r.enum):r instanceof Ht?qe(r._def.innerType):r instanceof Gt?[void 0]:r instanceof Zt?[null]:r instanceof Ve?[void 0,...qe(r.unwrap())]:r instanceof ot?[null,...qe(r.unwrap())]:r instanceof es||r instanceof en?qe(r.unwrap()):r instanceof Jt?qe(r._def.innerType):[];class bn extends K{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==D.object)return O(t,{code:A.invalid_type,expected:D.object,received:t.parsedType}),V;const n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(O(t,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),V)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const s=new Map;for(const i of t){const o=qe(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new bn({typeName:B.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...X(n)})}}function Qn(r,e){const t=Ke(r),n=Ke(e);if(r===e)return{valid:!0,data:r};if(t===D.object&&n===D.object){const s=J.objectKeys(e),i=J.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(const a of i){const c=Qn(r[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(t===D.array&&n===D.array){if(r.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<r.length;i++){const o=r[i],a=e[i],c=Qn(o,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===D.date&&n===D.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class Xt extends K{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if(qn(i)||qn(o))return V;const a=Qn(i.value,o.value);return a.valid?((Hn(i)||Hn(o))&&t.dirty(),{status:t.value,value:a.data}):(O(n,{code:A.invalid_intersection_types}),V)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Xt.create=(r,e,t)=>new Xt({left:r,right:e,typeName:B.ZodIntersection,...X(t)});class Be extends K{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==D.array)return O(n,{code:A.invalid_type,expected:D.array,received:n.parsedType}),V;if(n.data.length<this._def.items.length)return O(n,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),V;!this._def.rest&&n.data.length>this._def.items.length&&(O(n,{code:A.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...n.data].map((o,a)=>{const c=this._def.items[a]||this._def.rest;return c?c._parse(new je(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>ye.mergeArray(t,o)):ye.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new Be({...this._def,rest:e})}}Be.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Be({items:r,typeName:B.ZodTuple,rest:null,...X(e)})};class $t extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==D.object)return O(n,{code:A.invalid_type,expected:D.object,received:n.parsedType}),V;const s=[],i=this._def.keyType,o=this._def.valueType;for(const a in n.data)s.push({key:i._parse(new je(n,a,n.path,a)),value:o._parse(new je(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ye.mergeObjectAsync(t,s):ye.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof K?new $t({keyType:e,valueType:t,typeName:B.ZodRecord,...X(n)}):new $t({keyType:Pe.create(),valueType:e,typeName:B.ZodRecord,...X(t)})}}class wn extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==D.map)return O(n,{code:A.invalid_type,expected:D.map,received:n.parsedType}),V;const s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,c],l)=>({key:s._parse(new je(n,a,n.path,[l,"key"])),value:i._parse(new je(n,c,n.path,[l,"value"]))}));if(n.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const c of o){const l=await c.key,d=await c.value;if(l.status==="aborted"||d.status==="aborted")return V;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}})}else{const a=new Map;for(const c of o){const l=c.key,d=c.value;if(l.status==="aborted"||d.status==="aborted")return V;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}}}}wn.create=(r,e,t)=>new wn({valueType:e,keyType:r,typeName:B.ZodMap,...X(t)});class ht extends K{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==D.set)return O(n,{code:A.invalid_type,expected:D.set,received:n.parsedType}),V;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(O(n,{code:A.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(O(n,{code:A.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const i=this._def.valueType;function o(c){const l=new Set;for(const d of c){if(d.status==="aborted")return V;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}const a=[...n.data.values()].map((c,l)=>i._parse(new je(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,t){return new ht({...this._def,minSize:{value:e,message:P.toString(t)}})}max(e,t){return new ht({...this._def,maxSize:{value:e,message:P.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ht.create=(r,e)=>new ht({valueType:r,minSize:null,maxSize:null,typeName:B.ZodSet,...X(e)});class St extends K{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==D.function)return O(t,{code:A.invalid_type,expected:D.function,received:t.parsedType}),V;function n(a,c){return gn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,_n(),xt].filter(l=>!!l),issueData:{code:A.invalid_arguments,argumentsError:c}})}function s(a,c){return gn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,_n(),xt].filter(l=>!!l),issueData:{code:A.invalid_return_type,returnTypeError:c}})}const i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Tt){const a=this;return be(async function(...c){const l=new De([]),d=await a._def.args.parseAsync(c,i).catch(m=>{throw l.addIssue(n(c,m)),l}),h=await Reflect.apply(o,this,d);return await a._def.returns._def.type.parseAsync(h,i).catch(m=>{throw l.addIssue(s(h,m)),l})})}else{const a=this;return be(function(...c){const l=a._def.args.safeParse(c,i);if(!l.success)throw new De([n(c,l.error)]);const d=Reflect.apply(o,this,l.data),h=a._def.returns.safeParse(d,i);if(!h.success)throw new De([s(d,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new St({...this._def,args:Be.create(e).rest(ut.create())})}returns(e){return new St({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new St({args:e||Be.create([]).rest(ut.create()),returns:t||ut.create(),typeName:B.ZodFunction,...X(n)})}}class Kt extends K{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Kt.create=(r,e)=>new Kt({getter:r,typeName:B.ZodLazy,...X(e)});class Yt extends K{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return O(t,{received:t.data,code:A.invalid_literal,expected:this._def.value}),V}return{status:"valid",value:e.data}}get value(){return this._def.value}}Yt.create=(r,e)=>new Yt({value:r,typeName:B.ZodLiteral,...X(e)});function Js(r,e){return new rt({values:r,typeName:B.ZodEnum,...X(e)})}class rt extends K{constructor(){super(...arguments),jt.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return O(t,{expected:J.joinValues(n),received:t.parsedType,code:A.invalid_type}),V}if(yn(this,jt)||$s(this,jt,new Set(this._def.values)),!yn(this,jt).has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return O(t,{received:t.data,code:A.invalid_enum_value,options:n}),V}return be(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return rt.create(e,{...this._def,...t})}exclude(e,t=this._def){return rt.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}jt=new WeakMap,rt.create=Js;class qt extends K{constructor(){super(...arguments),Bt.set(this,void 0)}_parse(e){const t=J.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==D.string&&n.parsedType!==D.number){const s=J.objectValues(t);return O(n,{expected:J.joinValues(s),received:n.parsedType,code:A.invalid_type}),V}if(yn(this,Bt)||$s(this,Bt,new Set(J.getValidEnumValues(this._def.values))),!yn(this,Bt).has(e.data)){const s=J.objectValues(t);return O(n,{received:n.data,code:A.invalid_enum_value,options:s}),V}return be(e.data)}get enum(){return this._def.values}}Bt=new WeakMap,qt.create=(r,e)=>new qt({values:r,typeName:B.ZodNativeEnum,...X(e)});class Tt extends K{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==D.promise&&t.common.async===!1)return O(t,{code:A.invalid_type,expected:D.promise,received:t.parsedType}),V;const n=t.parsedType===D.promise?t.data:Promise.resolve(t.data);return be(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Tt.create=(r,e)=>new Tt({type:r,typeName:B.ZodPromise,...X(e)});class ze extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{O(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return V;const c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?V:c.status==="dirty"||t.value==="dirty"?bt(c.value):c});{if(t.value==="aborted")return V;const a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?V:a.status==="dirty"||t.value==="dirty"?bt(a.value):a}}if(s.type==="refinement"){const o=a=>{const c=s.refinement(a,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?V:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?V:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!lt(o))return o;const a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>lt(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):o);J.assertNever(s)}}ze.create=(r,e,t)=>new ze({schema:r,typeName:B.ZodEffects,effect:e,...X(t)}),ze.createWithPreprocess=(r,e,t)=>new ze({schema:e,effect:{type:"preprocess",transform:r},typeName:B.ZodEffects,...X(t)});class Ve extends K{_parse(e){return this._getType(e)===D.undefined?be(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ve.create=(r,e)=>new Ve({innerType:r,typeName:B.ZodOptional,...X(e)});class ot extends K{_parse(e){return this._getType(e)===D.null?be(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ot.create=(r,e)=>new ot({innerType:r,typeName:B.ZodNullable,...X(e)});class Ht extends K{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===D.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ht.create=(r,e)=>new Ht({innerType:r,typeName:B.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});class Jt extends K{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ft(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new De(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new De(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Jt.create=(r,e)=>new Jt({innerType:r,typeName:B.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});class An extends K{_parse(e){if(this._getType(e)!==D.nan){const n=this._getOrReturnCtx(e);return O(n,{code:A.invalid_type,expected:D.nan,received:n.parsedType}),V}return{status:"valid",value:e.data}}}An.create=r=>new An({typeName:B.ZodNaN,...X(r)});const Kr=Symbol("zod_brand");class es extends K{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class Qt extends K{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?V:i.status==="dirty"?(t.dirty(),bt(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?V:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new Qt({in:e,out:t,typeName:B.ZodPipeline})}}class en extends K{_parse(e){const t=this._def.innerType._parse(e),n=s=>(lt(s)&&(s.value=Object.freeze(s.value)),s);return Ft(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}}en.create=(r,e)=>new en({innerType:r,typeName:B.ZodReadonly,...X(e)});function Qs(r,e){const t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function ei(r,e={},t){return r?wt.create().superRefine((n,s)=>{var i,o;const a=r(n);if(a instanceof Promise)return a.then(c=>{var l,d;if(!c){const h=Qs(e,n),f=(d=(l=h.fatal)!==null&&l!==void 0?l:t)!==null&&d!==void 0?d:!0;s.addIssue({code:"custom",...h,fatal:f})}});if(!a){const c=Qs(e,n),l=(o=(i=c.fatal)!==null&&i!==void 0?i:t)!==null&&o!==void 0?o:!0;s.addIssue({code:"custom",...c,fatal:l})}}):wt.create()}const Yr={object:re.lazycreate};var B;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(B||(B={}));const qr=(r,e={message:`Input not instance of ${r.name}`})=>ei(t=>t instanceof r,e),ti=Pe.create,ni=st.create,Hr=An.create,Jr=it.create,si=Vt.create,Qr=dt.create,eo=vn.create,to=Gt.create,no=Zt.create,so=wt.create,io=ut.create,ro=Ye.create,oo=xn.create,ao=Re.create,co=re.create,lo=re.strictCreate,uo=Wt.create,ho=bn.create,fo=Xt.create,po=Be.create,mo=$t.create,_o=wn.create,go=ht.create,yo=St.create,vo=Kt.create,xo=Yt.create,bo=rt.create,wo=qt.create,Ao=Tt.create,ii=ze.create,So=Ve.create,To=ot.create,Mo=ze.createWithPreprocess,Lo=Qt.create;var S=Object.freeze({__proto__:null,defaultErrorMap:xt,setErrorMap:Tr,getErrorMap:_n,makeIssue:gn,EMPTY_PATH:Mr,addIssueToContext:O,ParseStatus:ye,INVALID:V,DIRTY:bt,OK:be,isAborted:qn,isDirty:Hn,isValid:lt,isAsync:Ft,get util(){return J},get objectUtil(){return Yn},ZodParsedType:D,getParsedType:Ke,ZodType:K,datetimeRegex:Hs,ZodString:Pe,ZodNumber:st,ZodBigInt:it,ZodBoolean:Vt,ZodDate:dt,ZodSymbol:vn,ZodUndefined:Gt,ZodNull:Zt,ZodAny:wt,ZodUnknown:ut,ZodNever:Ye,ZodVoid:xn,ZodArray:Re,ZodObject:re,ZodUnion:Wt,ZodDiscriminatedUnion:bn,ZodIntersection:Xt,ZodTuple:Be,ZodRecord:$t,ZodMap:wn,ZodSet:ht,ZodFunction:St,ZodLazy:Kt,ZodLiteral:Yt,ZodEnum:rt,ZodNativeEnum:qt,ZodPromise:Tt,ZodEffects:ze,ZodTransformer:ze,ZodOptional:Ve,ZodNullable:ot,ZodDefault:Ht,ZodCatch:Jt,ZodNaN:An,BRAND:Kr,ZodBranded:es,ZodPipeline:Qt,ZodReadonly:en,custom:ei,Schema:K,ZodSchema:K,late:Yr,get ZodFirstPartyTypeKind(){return B},coerce:{string:r=>Pe.create({...r,coerce:!0}),number:r=>st.create({...r,coerce:!0}),boolean:r=>Vt.create({...r,coerce:!0}),bigint:r=>it.create({...r,coerce:!0}),date:r=>dt.create({...r,coerce:!0})},any:so,array:ao,bigint:Jr,boolean:si,date:Qr,discriminatedUnion:ho,effect:ii,enum:bo,function:yo,instanceof:qr,intersection:fo,lazy:vo,literal:xo,map:_o,nan:Hr,nativeEnum:wo,never:ro,null:no,nullable:To,number:ni,object:co,oboolean:()=>si().optional(),onumber:()=>ni().optional(),optional:So,ostring:()=>ti().optional(),pipeline:Lo,preprocess:Mo,promise:Ao,record:mo,set:go,strictObject:lo,string:ti,symbol:eo,transformer:ii,tuple:po,undefined:to,union:uo,unknown:io,void:oo,NEVER:V,ZodIssueCode:A,quotelessJson:Sr,ZodError:De});const Co=S.object({color:S.number().default(16711680),intensity:S.number().default(1),position:S.tuple([S.number(),S.number(),S.number()]).default([10,10,10]),shadow:S.boolean().default(!0)}),Oo=S.object({type:S.enum(["sky","hdr","ultra","room","none"]).default("none"),url:S.string().optional(),sun:Co.optional(),transparent:S.boolean().default(!1)}),ko=S.object({url:S.string(),color:S.number().optional(),shadow:S.boolean().default(!1),visible:S.boolean().default(!0).optional(),position:S.tuple([S.number(),S.number(),S.number()]).optional(),rotation:S.tuple([S.number(),S.number(),S.number()]).optional(),scale:S.union([S.number(),S.tuple([S.number(),S.number(),S.number()])]).default(1).optional(),conditional_edges:S.object({color:S.number().optional(),line_width:S.number().optional(),threshold_angle:S.number().optional()}).optional(),threshold_edges:S.object({color:S.number().optional(),line_width:S.number().optional(),threshold_angle:S.number().optional()}).optional(),frame_object:S.object({fit_offset:S.number().optional(),height_offset:S.number().optional()}).optional()}),Sn=S.object({environment:Oo.default({type:"none"}),models:S.array(ko).default([])});let ri="info";const oi={silent:0,error:1,warn:2,info:3,debug:4};function Tn(r){return oi[r]<=oi[ri]&&ri!=="silent"}const G={error:(...r)=>Tn("error")&&console.error("[glimmer]",...r),warn:(...r)=>Tn("warn")&&console.warn("[glimmer]",...r),info:(...r)=>Tn("info")&&console.log("[glimmer]",...r),debug:(...r)=>Tn("debug")&&console.log("[glimmer:debug]",...r)},Xe=class Xe extends EventTarget{constructor(t){super();g(this,"settings");try{const n=Sn.parse({}),s={...n,...t,environment:{...n.environment,...t.environment||{}},models:t.models||n.models};this.settings=Sn.parse(s),G.info("Settings initialized:",this.settings)}catch(n){throw G.error("Error initializing settings:",n),n}}static use(t={}){return Xe.instance?Xe.instance.update(t):Xe.instance=new Xe(t),Xe.instance}static reset(){Xe.instance&&(Xe.instance=void 0)}get(t){return this.settings[t]}update(t){const n=Sn.parse({...this.settings,...t,environment:{...this.settings.environment,...t.environment||{}},models:t.models!==void 0?t.models:this.settings.models});this.settings=n,G.info("Settings updated:",this.settings);const s=new CustomEvent("update",{detail:this.settings});this.dispatchEvent(s)}export(){return JSON.stringify(this.settings,null,2)}import(t){try{const n=JSON.parse(t);this.update(n)}catch(n){G.error("Failed to import settings:",n)}}async load_from_url(t){try{const n=await fetch(t);if(!n.ok)throw new Error(`Failed to fetch JSON from URL: ${n.statusText}`);const s=await n.json();this.update(s),G.info("Settings loaded successfully from URL:",t)}catch(n){G.error("Error loading settings from URL:",n)}}};g(Xe,"instance");let Mn=Xe;const ai={type:"change"},ts={type:"start"},ci={type:"end"},Ln=new u.Ray,li=new u.Plane,Do=Math.cos(70*u.MathUtils.DEG2RAD),le=new u.Vector3,Me=2*Math.PI,ne={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},ns=1e-6;class Io extends u.Controls{constructor(e,t=null){super(e,t),this.state=ne.NONE,this.target=new u.Vector3,this.cursor=new u.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:u.MOUSE.ROTATE,MIDDLE:u.MOUSE.DOLLY,RIGHT:u.MOUSE.PAN},this.touches={ONE:u.TOUCH.ROTATE,TWO:u.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new u.Vector3,this._lastQuaternion=new u.Quaternion,this._lastTargetPosition=new u.Vector3,this._quat=new u.Quaternion().setFromUnitVectors(e.up,new u.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new u.Spherical,this._sphericalDelta=new u.Spherical,this._scale=1,this._panOffset=new u.Vector3,this._rotateStart=new u.Vector2,this._rotateEnd=new u.Vector2,this._rotateDelta=new u.Vector2,this._panStart=new u.Vector2,this._panEnd=new u.Vector2,this._panDelta=new u.Vector2,this._dollyStart=new u.Vector2,this._dollyEnd=new u.Vector2,this._dollyDelta=new u.Vector2,this._dollyDirection=new u.Vector3,this._mouse=new u.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=No.bind(this),this._onPointerDown=Eo.bind(this),this._onPointerUp=Po.bind(this),this._onContextMenu=Vo.bind(this),this._onMouseWheel=Uo.bind(this),this._onKeyDown=Fo.bind(this),this._onTouchStart=jo.bind(this),this._onTouchMove=Bo.bind(this),this._onMouseDown=Ro.bind(this),this._onMouseMove=zo.bind(this),this._interceptControlDown=Go.bind(this),this._interceptControlUp=Zo.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(ai),this.update(),this.state=ne.NONE}update(e=null){const t=this.object.position;le.copy(t).sub(this.target),le.applyQuaternion(this._quat),this._spherical.setFromVector3(le),this.autoRotate&&this.state===ne.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=Me:n>Math.PI&&(n-=Me),s<-Math.PI?s+=Me:s>Math.PI&&(s-=Me),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let i=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),i=o!=this._spherical.radius}if(le.setFromSpherical(this._spherical),le.applyQuaternion(this._quatInverse),t.copy(this.target).add(le),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let o=null;if(this.object.isPerspectiveCamera){const a=le.length();o=this._clampDistance(a*this._scale);const c=a-o;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),i=!!c}else if(this.object.isOrthographicCamera){const a=new u.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),i=c!==this.object.zoom;const l=new u.Vector3(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(a),this.object.updateMatrixWorld(),o=le.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(Ln.origin.copy(this.object.position),Ln.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Ln.direction))<Do?this.object.lookAt(this.target):(li.setFromNormalAndCoplanarPoint(this.object.up,this.target),Ln.intersectPlane(li,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),i=!0)}return this._scale=1,this._performCursorZoom=!1,i||this._lastPosition.distanceToSquared(this.object.position)>ns||8*(1-this._lastQuaternion.dot(this.object.quaternion))>ns||this._lastTargetPosition.distanceToSquared(this.target)>ns?(this.dispatchEvent(ai),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Me/60*this.autoRotateSpeed*e:Me/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){le.setFromMatrixColumn(t,0),le.multiplyScalar(-e),this._panOffset.add(le)}_panUp(e,t){this.screenSpacePanning===!0?le.setFromMatrixColumn(t,1):(le.setFromMatrixColumn(t,0),le.crossVectors(this.object.up,le)),le.multiplyScalar(e),this._panOffset.add(le)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;le.copy(s).sub(this.target);let i=le.length();i*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*i/n.clientHeight,this.object.matrix),this._panUp(2*t*i/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),s=e-n.left,i=t-n.top,o=n.width,a=n.height;this._mouse.x=s/o*2-1,this._mouse.y=-(i/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Me*this._rotateDelta.x/t.clientHeight),this._rotateUp(Me*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Me*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-Me*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(Me*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-Me*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,i=Math.sqrt(n*n+s*s);this._dollyStart.set(0,i)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),s=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._rotateEnd.set(s,i)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Me*this._rotateDelta.x/t.clientHeight),this._rotateUp(Me*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,i=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,i),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(o,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new u.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function Eo(r){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(r.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(r)&&(this._addPointer(r),r.pointerType==="touch"?this._onTouchStart(r):this._onMouseDown(r)))}function No(r){this.enabled!==!1&&(r.pointerType==="touch"?this._onTouchMove(r):this._onMouseMove(r))}function Po(r){switch(this._removePointer(r),this._pointers.length){case 0:this.domElement.releasePointerCapture(r.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(ci),this.state=ne.NONE;break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function Ro(r){let e;switch(r.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case u.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(r),this.state=ne.DOLLY;break;case u.MOUSE.ROTATE:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=ne.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=ne.ROTATE}break;case u.MOUSE.PAN:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=ne.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=ne.PAN}break;default:this.state=ne.NONE}this.state!==ne.NONE&&this.dispatchEvent(ts)}function zo(r){switch(this.state){case ne.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(r);break;case ne.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(r);break;case ne.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(r);break}}function Uo(r){this.enabled===!1||this.enableZoom===!1||this.state!==ne.NONE||(r.preventDefault(),this.dispatchEvent(ts),this._handleMouseWheel(this._customWheelEvent(r)),this.dispatchEvent(ci))}function Fo(r){this.enabled!==!1&&this._handleKeyDown(r)}function jo(r){switch(this._trackPointer(r),this._pointers.length){case 1:switch(this.touches.ONE){case u.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(r),this.state=ne.TOUCH_ROTATE;break;case u.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(r),this.state=ne.TOUCH_PAN;break;default:this.state=ne.NONE}break;case 2:switch(this.touches.TWO){case u.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(r),this.state=ne.TOUCH_DOLLY_PAN;break;case u.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(r),this.state=ne.TOUCH_DOLLY_ROTATE;break;default:this.state=ne.NONE}break;default:this.state=ne.NONE}this.state!==ne.NONE&&this.dispatchEvent(ts)}function Bo(r){switch(this._trackPointer(r),this.state){case ne.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(r),this.update();break;case ne.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(r),this.update();break;case ne.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(r),this.update();break;case ne.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(r),this.update();break;default:this.state=ne.NONE}}function Vo(r){this.enabled!==!1&&r.preventDefault()}function Go(r){r.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Zo(r){r.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class Wo{constructor(e){g(this,"group");g(this,"sphere");g(this,"arrow");g(this,"scene");g(this,"is_enabled",!1);g(this,"SPHERE_RADIUS",.1);g(this,"ARROW_LENGTH",.5);g(this,"ARROW_HEAD_LENGTH",.15);g(this,"ARROW_HEAD_WIDTH",.1);this.scene=e,this.group=new _.Group,this.group.name="cursor_3d",this.group.visible=!1;const t=new _.SphereGeometry(this.SPHERE_RADIUS,16,16),n=new _.MeshBasicMaterial({color:65280,transparent:!0,opacity:.7,depthTest:!1});this.sphere=new _.Mesh(t,n),this.group.add(this.sphere),this.arrow=new _.ArrowHelper(new _.Vector3(0,1,0),new _.Vector3(0,0,0),this.ARROW_LENGTH,65280,this.ARROW_HEAD_LENGTH,this.ARROW_HEAD_WIDTH),this.group.add(this.arrow),this.scene.add(this.group)}enable(){this.is_enabled=!0,this.group.visible=!0}disable(){this.is_enabled=!1,this.group.visible=!1}get enabled(){return this.is_enabled}update(e){if(!e||!this.is_enabled){this.group.visible=!1;return}if(this.group.visible=!0,this.sphere.position.copy(e.point),this.arrow.position.copy(e.point),e.face&&e.face.normal){const t=e.face.normal.clone(),n=e.object;n.matrixWorld&&t.transformDirection(n.matrixWorld),this.arrow.setDirection(t)}}set_color(e){this.sphere.material.color.setHex(e),this.arrow.setColor(e)}dispose(){this.scene.remove(this.group),this.sphere.geometry.dispose(),this.sphere.material.dispose(),this.arrow.dispose()}}class Xo extends EventTarget{constructor(t,n,s,i){super();g(this,"camera");g(this,"controls");g(this,"renderer");g(this,"scene");g(this,"_orbit_animation_id");g(this,"_orbit_restart_timeout_id");g(this,"_orbit_duration_seconds",45);g(this,"_orbit_clockwise",!0);g(this,"_auto_restart_enabled",!0);this.camera=t,this.controls=n,this.renderer=s,this.scene=i}start_animation(t,n,s=1){t||(t=30),this._orbit_duration_seconds=t,n===void 0&&(n=!0),this._orbit_clockwise=n,this.stop_animation();const i=t??this._orbit_duration_seconds,o=n??this._orbit_clockwise,a=this.camera.position.clone(),c=this.controls.target.clone(),l=c.clone();l.y=a.y;const d=a.distanceTo(l),h=Math.PI*2,f=performance.now(),m=a.x-l.x,y=a.z-l.z,v=Math.atan2(y,m),b=T=>1-Math.cos(T*Math.PI/2),w=T=>{const M=(T-f)/1e3;let x=0;M<s?x=b(M/s)*s:x=M-s+b(1)*s;const z=x%i/i,Z=v+(o?-1:1)*z*h,j=l.x+Math.cos(Z)*d,k=l.z+Math.sin(Z)*d,C=new _.Vector3(j,a.y,k);this.camera.position.copy(C),this.camera.lookAt(c),this.controls.target.copy(c),this.renderer.render(this.scene,this.camera),this._orbit_animation_id=requestAnimationFrame(w)};this._orbit_animation_id=requestAnimationFrame(w)}stop_animation(){this._orbit_animation_id&&(cancelAnimationFrame(this._orbit_animation_id),this._orbit_animation_id=void 0)}schedule_restart(t=5e3){this._auto_restart_enabled&&(this._orbit_restart_timeout_id&&clearTimeout(this._orbit_restart_timeout_id),this._orbit_restart_timeout_id=window.setTimeout(()=>{this.start_animation(this._orbit_duration_seconds,this._orbit_clockwise)},t))}set_auto_restart(t){this._auto_restart_enabled=t,!t&&this._orbit_restart_timeout_id&&(clearTimeout(this._orbit_restart_timeout_id),this._orbit_restart_timeout_id=void 0)}setup_user_override(){this.controls.addEventListener("start",()=>{this.stop_animation(),this._orbit_restart_timeout_id&&(clearTimeout(this._orbit_restart_timeout_id),this._orbit_restart_timeout_id=void 0),this.dispatchEvent(new CustomEvent("orbitstart",{detail:{}}))}),this.controls.addEventListener("end",()=>{this._auto_restart_enabled&&this.schedule_restart(),this.dispatchEvent(new CustomEvent("orbitstop",{detail:{}}))})}dispose(){this.stop_animation(),this._orbit_restart_timeout_id&&(clearTimeout(this._orbit_restart_timeout_id),this._orbit_restart_timeout_id=void 0)}}class $o{constructor(e,t,n){g(this,"raycaster");g(this,"camera");g(this,"canvas");g(this,"default_targets");this.raycaster=new _.Raycaster,this.camera=e,this.canvas=t,this.default_targets=n}raycast_from_event(e,t,n=!0){const s=this.canvas.getBoundingClientRect(),i=new _.Vector2;i.x=(e.clientX-s.left)/s.width*2-1,i.y=-((e.clientY-s.top)/s.height)*2+1,this.raycaster.setFromCamera(i,this.camera);const o=t??this.default_targets,a=this.raycaster.intersectObjects(o,!0);if(n){const c=a.filter(l=>l.object.isMesh);return c.length>0?c[0]:null}return a.length>0?a[0]:null}get_raycaster(){return this.raycaster}}class di extends EventTarget{constructor(t,n){super();g(this,"settings");g(this,"scene");g(this,"camera");g(this,"renderer");g(this,"controls");g(this,"container");g(this,"orbit_controller");g(this,"raycast_helper");g(this,"_resize_handler",()=>this.onWindowResize());g(this,"clock",new _.Clock);g(this,"animation_callbacks",new Set);g(this,"animation_mixers",new Set);g(this,"cursor_3d");g(this,"_cursor_3d_mouse_handler");g(this,"_resolution_materials",new Set);g(this,"animate",()=>{requestAnimationFrame(this.animate);const t=this.clock.getDelta();this.update_animation_mixers(t),this.execute_animation_callbacks(t);for(const n of this._resolution_materials)try{if(n.resolution)this.renderer.getSize(n.resolution),n.resolution.multiplyScalar(window.devicePixelRatio);else if(n.uniforms&&n.uniforms.resolution&&n.uniforms.resolution.value){const s=n.uniforms.resolution.value;this.renderer.getSize(s),s.multiplyScalar(window.devicePixelRatio)}}catch{this._resolution_materials.delete(n)}this.controls.update(),this.renderer.render(this.scene,this.camera)});this.scene=new _.Scene,this.settings=n,this.container=t,this.renderer=new _.WebGLRenderer({antialias:!0}),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.toneMapping=_.ACESFilmicToneMapping,this.renderer.outputColorSpace=_.SRGBColorSpace,this.container.appendChild(this.renderer.domElement);const s=t.clientWidth/t.clientHeight;this.camera=new _.PerspectiveCamera(75,s,.1,1e3),this.camera.position.set(0,2,5),this.controls=new Io(this.camera,this.renderer.domElement),this.controls.enableDamping=!1,this.orbit_controller=new Xo(this.camera,this.controls,this.renderer,this.scene),this.raycast_helper=new $o(this.camera,this.renderer.domElement,this.scene.children),this._setup_orbit_animation_user_override(),window.addEventListener("resize",this._resize_handler),this.animate(),G.info("Viewer: Initializing...")}register_animation_mixer(t){this.animation_mixers.add(t)}unregister_animation_mixer(t){this.animation_mixers.delete(t)}update_animation_mixers(t){for(const n of this.animation_mixers)n.update(t)}register_animation_callback(t){this.animation_callbacks.add(t)}unregister_animation_callback(t){this.animation_callbacks.delete(t)}execute_animation_callbacks(t){for(const n of this.animation_callbacks)n(t)}onWindowResize(){const t=this.container.clientWidth,n=this.container.clientHeight;this.camera.aspect=t/n,this.camera.updateProjectionMatrix(),this.renderer.setSize(t,n),this.dispatchEvent(new CustomEvent("resize",{detail:{width:t,height:n}}))}register_resolution_material(t){t&&(t.resolution||t.uniforms&&t.uniforms.resolution)&&this._resolution_materials.add(t)}unregister_resolution_material(t){this._resolution_materials.delete(t)}frame_object(t,n=.2,s=1){n=n+1;const i=new _.Box3().setFromObject(t),o=i.getSize(new _.Vector3),a=i.getCenter(new _.Vector3);this.controls.target.copy(a),this.controls.update();const l=Math.max(o.x,o.y,o.z)/(2*Math.atan(Math.PI*this.camera.fov/360)),d=l/this.camera.aspect,h=n*Math.max(l,d),f=this.camera.position.clone().sub(this.controls.target).normalize();this.camera.position.copy(a).add(f.multiplyScalar(h)),this.camera.position.y=a.y+s,this.camera.near=h/100,this.camera.far=h*100,this.camera.updateProjectionMatrix(),this.renderer.render(this.scene,this.camera)}start_camera_orbit_animation(t,n,s=1){this.orbit_controller.start_animation(t,n,s)}stop_camera_orbit_animation(){this.orbit_controller.stop_animation()}set_auto_orbit(t){this.orbit_controller.set_auto_restart(t)}schedule_camera_orbit_restart(t=5e3){this.orbit_controller.schedule_restart(t)}_setup_orbit_animation_user_override(){this.orbit_controller.setup_user_override(),this.orbit_controller.addEventListener("orbitstart",()=>{this.dispatchEvent(new CustomEvent("orbitstart",{detail:{}}))}),this.orbit_controller.addEventListener("orbitstop",()=>{this.dispatchEvent(new CustomEvent("orbitstop",{detail:{}}))}),this.controls.addEventListener("change",()=>{this.dispatchEvent(new CustomEvent("camerachange",{detail:{position:this.camera.position.clone(),target:this.controls.target.clone()}}))})}raycast_from_event(t,n){return this.raycast_helper.raycast_from_event(t,n,!0)}enable_3d_cursor(t){this.cursor_3d||(this.cursor_3d=new Wo(this.scene)),this.cursor_3d.enable(),this._cursor_3d_mouse_handler=n=>{var i;const s=this.raycast_from_event(n,t);(i=this.cursor_3d)==null||i.update(s)},this.renderer.domElement.addEventListener("mousemove",this._cursor_3d_mouse_handler)}disable_3d_cursor(){this.cursor_3d&&this.cursor_3d.disable(),this._cursor_3d_mouse_handler&&(this.renderer.domElement.removeEventListener("mousemove",this._cursor_3d_mouse_handler),this._cursor_3d_mouse_handler=void 0)}update_3d_cursor(t,n){var i;if(!((i=this.cursor_3d)!=null&&i.enabled))return;const s=this.raycast_from_event(t,n);this.cursor_3d.update(s)}get_3d_cursor(){return this.cursor_3d}dispose(){this.orbit_controller.dispose(),this.disable_3d_cursor(),this.cursor_3d&&(this.cursor_3d.dispose(),this.cursor_3d=void 0),window.removeEventListener("resize",this._resize_handler),this.animation_mixers.clear(),this.animation_callbacks.clear(),this.renderer.dispose(),this.renderer.domElement&&this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this._resolution_materials.clear()}}class Ko extends u.DataTextureLoader{constructor(e){super(e),this.type=u.HalfFloatType}parse(e){const o=function(k,C){switch(k){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(C||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(C||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(C||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(C||""))}},d=`
|
|
2
|
+
`,h=function(k,C,I){C=C||1024;let W=k.pos,$=-1,E=0,ee="",Y=String.fromCharCode.apply(null,new Uint16Array(k.subarray(W,W+128)));for(;0>($=Y.indexOf(d))&&E<C&&W<k.byteLength;)ee+=Y,E+=Y.length,W+=128,Y+=String.fromCharCode.apply(null,new Uint16Array(k.subarray(W,W+128)));return-1<$?(k.pos+=E+$+1,ee+Y.slice(0,$)):!1},f=function(k){const C=/^#\?(\S+)/,I=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,R=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,W=/^\s*FORMAT=(\S+)\s*$/,$=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,E={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let ee,Y;for((k.pos>=k.byteLength||!(ee=h(k)))&&o(1,"no header found"),(Y=ee.match(C))||o(3,"bad initial token"),E.valid|=1,E.programtype=Y[1],E.string+=ee+`
|
|
3
|
+
`;ee=h(k),ee!==!1;){if(E.string+=ee+`
|
|
4
|
+
`,ee.charAt(0)==="#"){E.comments+=ee+`
|
|
5
|
+
`;continue}if((Y=ee.match(I))&&(E.gamma=parseFloat(Y[1])),(Y=ee.match(R))&&(E.exposure=parseFloat(Y[1])),(Y=ee.match(W))&&(E.valid|=2,E.format=Y[1]),(Y=ee.match($))&&(E.valid|=4,E.height=parseInt(Y[1],10),E.width=parseInt(Y[2],10)),E.valid&2&&E.valid&4)break}return E.valid&2||o(3,"missing format specifier"),E.valid&4||o(3,"missing image size specifier"),E},m=function(k,C,I){const R=C;if(R<8||R>32767||k[0]!==2||k[1]!==2||k[2]&128)return new Uint8Array(k);R!==(k[2]<<8|k[3])&&o(3,"wrong scanline width");const W=new Uint8Array(4*C*I);W.length||o(4,"unable to allocate buffer space");let $=0,E=0;const ee=4*R,Y=new Uint8Array(4),Te=new Uint8Array(ee);let de=I;for(;de>0&&E<k.byteLength;){E+4>k.byteLength&&o(1),Y[0]=k[E++],Y[1]=k[E++],Y[2]=k[E++],Y[3]=k[E++],(Y[0]!=2||Y[1]!=2||(Y[2]<<8|Y[3])!=R)&&o(3,"bad rgbe scanline format");let Fe=0,Ce;for(;Fe<ee&&E<k.byteLength;){Ce=k[E++];const _e=Ce>128;if(_e&&(Ce-=128),(Ce===0||Fe+Ce>ee)&&o(3,"bad scanline data"),_e){const Q=k[E++];for(let ct=0;ct<Ce;ct++)Te[Fe++]=Q}else Te.set(k.subarray(E,E+Ce),Fe),Fe+=Ce,E+=Ce}const se=R;for(let _e=0;_e<se;_e++){let Q=0;W[$]=Te[_e+Q],Q+=R,W[$+1]=Te[_e+Q],Q+=R,W[$+2]=Te[_e+Q],Q+=R,W[$+3]=Te[_e+Q],$+=4}de--}return W},y=function(k,C,I,R){const W=k[C+3],$=Math.pow(2,W-128)/255;I[R+0]=k[C+0]*$,I[R+1]=k[C+1]*$,I[R+2]=k[C+2]*$,I[R+3]=1},v=function(k,C,I,R){const W=k[C+3],$=Math.pow(2,W-128)/255;I[R+0]=u.DataUtils.toHalfFloat(Math.min(k[C+0]*$,65504)),I[R+1]=u.DataUtils.toHalfFloat(Math.min(k[C+1]*$,65504)),I[R+2]=u.DataUtils.toHalfFloat(Math.min(k[C+2]*$,65504)),I[R+3]=u.DataUtils.toHalfFloat(1)},b=new Uint8Array(e);b.pos=0;const w=f(b),T=w.width,M=w.height,x=m(b.subarray(b.pos),T,M);let z,Z,j;switch(this.type){case u.FloatType:j=x.length/4;const k=new Float32Array(j*4);for(let I=0;I<j;I++)y(x,I*4,k,I*4);z=k,Z=u.FloatType;break;case u.HalfFloatType:j=x.length/4;const C=new Uint16Array(j*4);for(let I=0;I<j;I++)v(x,I*4,C,I*4);z=C,Z=u.HalfFloatType;break;default:throw new Error("THREE.RGBELoader: Unsupported type: "+this.type)}return{width:T,height:M,data:z,header:w.string,gamma:w.gamma,exposure:w.exposure,type:Z}}setDataType(e){return this.type=e,this}load(e,t,n,s){function i(o,a){switch(o.type){case u.FloatType:case u.HalfFloatType:o.colorSpace=u.LinearSRGBColorSpace,o.minFilter=u.LinearFilter,o.magFilter=u.LinearFilter,o.generateMipmaps=!1,o.flipY=!0;break}t&&t(o,a)}return super.load(e,i,n,s)}}const Yo=Array(1024).fill(0).map((r,e)=>Math.pow(e/255*.9478672986+.0521327014,2.4));class qo extends u.Loader{constructor(e){super(e),this.type=u.HalfFloatType}setDataType(e){return this.type=e,this}parse(e,t){const n={version:null,baseRenditionIsHDR:null,gainMapMin:null,gainMapMax:null,gamma:null,offsetSDR:null,offsetHDR:null,hdrCapacityMin:null,hdrCapacityMax:null},s=new TextDecoder,i=new DataView(e);let o=0;const a=[];for(;o<i.byteLength;){const d=i.getUint8(o);if(d===255){const h=i.getUint8(o+1);[216,224,225,226].includes(h)?(a.push({sectionType:h,section:[d,h],sectionOffset:o+2}),o+=2):(a[a.length-1].section.push(d,h),o+=2)}else a[a.length-1].section.push(d),o++}let c,l;for(let d=0;d<a.length;d++){const{sectionType:h,section:f,sectionOffset:m}=a[d];if(h!==224){if(h===225)this._parseXMPMetadata(s.decode(new Uint8Array(f)),n);else if(h===226){const y=new DataView(new Uint8Array(f.slice(2)).buffer);if(y.getUint32(2,!1)===1297106432){const b=y.getUint32(6)===1229531648,w=60,T=y.getUint32(w,b),M=y.getUint32(w+4,b),x=y.getUint32(w+16,b),z=y.getUint32(w+20,b)+m+6;c=new Uint8Array(i.buffer,M,T),l=new Uint8Array(i.buffer,z,x)}}}}if(!n.version)throw new Error("THREE.UltraHDRLoader: Not a valid UltraHDR image");if(c&&l)this._applyGainmapToSDR(n,c,l,(d,h,f)=>{t({width:h,height:f,data:d,format:u.RGBAFormat,type:this.type})},d=>{throw new Error(d)});else throw new Error("THREE.UltraHDRLoader: Could not parse UltraHDR images")}load(e,t,n,s){const i=new u.DataTexture(this.type===u.HalfFloatType?new Uint16Array:new Float32Array,0,0,u.RGBAFormat,this.type,u.UVMapping,u.ClampToEdgeWrapping,u.ClampToEdgeWrapping,u.LinearFilter,u.LinearMipMapLinearFilter,1,u.LinearSRGBColorSpace);i.generateMipmaps=!0,i.flipY=!0;const o=new u.FileLoader(this.manager);return o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setPath(this.path),o.setWithCredentials(this.withCredentials),o.load(e,a=>{try{this.parse(a,c=>{i.image={data:c.data,width:c.width,height:c.height},i.needsUpdate=!0,t&&t(i,c)})}catch(c){s&&s(c),console.error(c)}},n,s),i}_parseXMPMetadata(e,t){const s=new DOMParser().parseFromString(e.substring(e.indexOf("<"),e.lastIndexOf(">")+1),"text/xml"),[i]=s.getElementsByTagName("Container:Directory");if(!i){const[o]=s.getElementsByTagName("rdf:Description");t.version=o.getAttribute("hdrgm:Version"),t.baseRenditionIsHDR=o.getAttribute("hdrgm:BaseRenditionIsHDR")==="True",t.gainMapMin=parseFloat(o.getAttribute("hdrgm:GainMapMin")||0),t.gainMapMax=parseFloat(o.getAttribute("hdrgm:GainMapMax")||1),t.gamma=parseFloat(o.getAttribute("hdrgm:Gamma")||1),t.offsetSDR=parseFloat(o.getAttribute("hdrgm:OffsetSDR")/(1/64)),t.offsetHDR=parseFloat(o.getAttribute("hdrgm:OffsetHDR")/(1/64)),t.hdrCapacityMin=parseFloat(o.getAttribute("hdrgm:HDRCapacityMin")||0),t.hdrCapacityMax=parseFloat(o.getAttribute("hdrgm:HDRCapacityMax")||1)}}_srgbToLinear(e){return e/255<.04045?e/255*.0773993808:e<1024?Yo[~~e]:Math.pow(e/255*.9478672986+.0521327014,2.4)}_applyGainmapToSDR(e,t,n,s,i){const o=a=>new Promise((c,l)=>{const d=document.createElement("img");d.onload=()=>{const h={width:d.naturalWidth,height:d.naturalHeight,source:d};URL.revokeObjectURL(d.src),c(h)},d.onerror=()=>{URL.revokeObjectURL(d.src),l()},d.src=URL.createObjectURL(new Blob([a],{type:"image/jpeg"}))});Promise.all([o(t),o(n)]).then(([a,c])=>{const l=a.width/a.height,d=c.width/c.height;if(l!==d){i("THREE.UltraHDRLoader Error: Aspect ratio mismatch between SDR and Gainmap images");return}const h=document.createElement("canvas"),f=h.getContext("2d",{willReadFrequently:!0,colorSpace:"srgb"});h.width=a.width,h.height=a.height,f.drawImage(c.source,0,0,c.width,c.height,0,0,a.width,a.height);const m=f.getImageData(0,0,a.width,a.height,{colorSpace:"srgb"});f.drawImage(a.source,0,0);const y=f.getImageData(0,0,a.width,a.height,{colorSpace:"srgb"});let v;this.type===u.HalfFloatType?v=new Uint16Array(y.data.length).fill(23544):v=new Float32Array(y.data.length).fill(255);const b=Math.sqrt(Math.pow(1.8,e.hdrCapacityMax)),w=(Math.log2(b)-e.hdrCapacityMin)/(e.hdrCapacityMax-e.hdrCapacityMin),T=Math.min(Math.max(w,0),1),M=e.gamma===1;for(let x=0;x<y.data.length;x+=4){const z=x/4%a.width,Z=Math.floor(x/4/a.width);for(let j=0;j<3;j++){const k=y.data[x+j],C=(Z*a.width+z)*4+j,I=m.data[C]/255,R=M?I:Math.pow(I,1/e.gamma),W=e.gainMapMin*(1-R)+e.gainMapMax*R,$=(k+e.offsetSDR)*(W*T===0?1:Math.pow(2,W*T))-e.offsetHDR,E=Math.min(Math.max(this._srgbToLinear($),0),65504);v[x+j]=this.type===u.HalfFloatType?u.DataUtils.toHalfFloat(E):E}}s(v,a.width,a.height)}).catch(()=>{throw new Error("THREE.UltraHDRLoader Error: Could not parse UltraHDR images")})}}class Cn extends u.Mesh{constructor(){const e=Cn.SkyShader,t=new u.ShaderMaterial({name:e.name,uniforms:u.UniformsUtils.clone(e.uniforms),vertexShader:e.vertexShader,fragmentShader:e.fragmentShader,side:u.BackSide,depthWrite:!1});super(new u.BoxGeometry(1,1,1),t),this.isSky=!0}}Cn.SkyShader={name:"SkyShader",uniforms:{turbidity:{value:2},rayleigh:{value:1},mieCoefficient:{value:.005},mieDirectionalG:{value:.8},sunPosition:{value:new u.Vector3},up:{value:new u.Vector3(0,1,0)}},vertexShader:`
|
|
6
|
+
uniform vec3 sunPosition;
|
|
7
|
+
uniform float rayleigh;
|
|
8
|
+
uniform float turbidity;
|
|
9
|
+
uniform float mieCoefficient;
|
|
10
|
+
uniform vec3 up;
|
|
11
|
+
|
|
12
|
+
varying vec3 vWorldPosition;
|
|
13
|
+
varying vec3 vSunDirection;
|
|
14
|
+
varying float vSunfade;
|
|
15
|
+
varying vec3 vBetaR;
|
|
16
|
+
varying vec3 vBetaM;
|
|
17
|
+
varying float vSunE;
|
|
18
|
+
|
|
19
|
+
// constants for atmospheric scattering
|
|
20
|
+
const float e = 2.71828182845904523536028747135266249775724709369995957;
|
|
21
|
+
const float pi = 3.141592653589793238462643383279502884197169;
|
|
22
|
+
|
|
23
|
+
// wavelength of used primaries, according to preetham
|
|
24
|
+
const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 );
|
|
25
|
+
// this pre-calculation replaces older TotalRayleigh(vec3 lambda) function:
|
|
26
|
+
// (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))
|
|
27
|
+
const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 );
|
|
28
|
+
|
|
29
|
+
// mie stuff
|
|
30
|
+
// K coefficient for the primaries
|
|
31
|
+
const float v = 4.0;
|
|
32
|
+
const vec3 K = vec3( 0.686, 0.678, 0.666 );
|
|
33
|
+
// MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K
|
|
34
|
+
const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 );
|
|
35
|
+
|
|
36
|
+
// earth shadow hack
|
|
37
|
+
// cutoffAngle = pi / 1.95;
|
|
38
|
+
const float cutoffAngle = 1.6110731556870734;
|
|
39
|
+
const float steepness = 1.5;
|
|
40
|
+
const float EE = 1000.0;
|
|
41
|
+
|
|
42
|
+
float sunIntensity( float zenithAngleCos ) {
|
|
43
|
+
zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 );
|
|
44
|
+
return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) );
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
vec3 totalMie( float T ) {
|
|
48
|
+
float c = ( 0.2 * T ) * 10E-18;
|
|
49
|
+
return 0.434 * c * MieConst;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
void main() {
|
|
53
|
+
|
|
54
|
+
vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
|
|
55
|
+
vWorldPosition = worldPosition.xyz;
|
|
56
|
+
|
|
57
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
58
|
+
gl_Position.z = gl_Position.w; // set z to camera.far
|
|
59
|
+
|
|
60
|
+
vSunDirection = normalize( sunPosition );
|
|
61
|
+
|
|
62
|
+
vSunE = sunIntensity( dot( vSunDirection, up ) );
|
|
63
|
+
|
|
64
|
+
vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 );
|
|
65
|
+
|
|
66
|
+
float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) );
|
|
67
|
+
|
|
68
|
+
// extinction (absorption + out scattering)
|
|
69
|
+
// rayleigh coefficients
|
|
70
|
+
vBetaR = totalRayleigh * rayleighCoefficient;
|
|
71
|
+
|
|
72
|
+
// mie coefficients
|
|
73
|
+
vBetaM = totalMie( turbidity ) * mieCoefficient;
|
|
74
|
+
|
|
75
|
+
}`,fragmentShader:`
|
|
76
|
+
varying vec3 vWorldPosition;
|
|
77
|
+
varying vec3 vSunDirection;
|
|
78
|
+
varying float vSunfade;
|
|
79
|
+
varying vec3 vBetaR;
|
|
80
|
+
varying vec3 vBetaM;
|
|
81
|
+
varying float vSunE;
|
|
82
|
+
|
|
83
|
+
uniform float mieDirectionalG;
|
|
84
|
+
uniform vec3 up;
|
|
85
|
+
|
|
86
|
+
// constants for atmospheric scattering
|
|
87
|
+
const float pi = 3.141592653589793238462643383279502884197169;
|
|
88
|
+
|
|
89
|
+
const float n = 1.0003; // refractive index of air
|
|
90
|
+
const float N = 2.545E25; // number of molecules per unit volume for air at 288.15K and 1013mb (sea level -45 celsius)
|
|
91
|
+
|
|
92
|
+
// optical length at zenith for molecules
|
|
93
|
+
const float rayleighZenithLength = 8.4E3;
|
|
94
|
+
const float mieZenithLength = 1.25E3;
|
|
95
|
+
// 66 arc seconds -> degrees, and the cosine of that
|
|
96
|
+
const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324;
|
|
97
|
+
|
|
98
|
+
// 3.0 / ( 16.0 * pi )
|
|
99
|
+
const float THREE_OVER_SIXTEENPI = 0.05968310365946075;
|
|
100
|
+
// 1.0 / ( 4.0 * pi )
|
|
101
|
+
const float ONE_OVER_FOURPI = 0.07957747154594767;
|
|
102
|
+
|
|
103
|
+
float rayleighPhase( float cosTheta ) {
|
|
104
|
+
return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) );
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
float hgPhase( float cosTheta, float g ) {
|
|
108
|
+
float g2 = pow( g, 2.0 );
|
|
109
|
+
float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 );
|
|
110
|
+
return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse );
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
void main() {
|
|
114
|
+
|
|
115
|
+
vec3 direction = normalize( vWorldPosition - cameraPosition );
|
|
116
|
+
|
|
117
|
+
// optical length
|
|
118
|
+
// cutoff angle at 90 to avoid singularity in next formula.
|
|
119
|
+
float zenithAngle = acos( max( 0.0, dot( up, direction ) ) );
|
|
120
|
+
float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) );
|
|
121
|
+
float sR = rayleighZenithLength * inverse;
|
|
122
|
+
float sM = mieZenithLength * inverse;
|
|
123
|
+
|
|
124
|
+
// combined extinction factor
|
|
125
|
+
vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) );
|
|
126
|
+
|
|
127
|
+
// in scattering
|
|
128
|
+
float cosTheta = dot( direction, vSunDirection );
|
|
129
|
+
|
|
130
|
+
float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 );
|
|
131
|
+
vec3 betaRTheta = vBetaR * rPhase;
|
|
132
|
+
|
|
133
|
+
float mPhase = hgPhase( cosTheta, mieDirectionalG );
|
|
134
|
+
vec3 betaMTheta = vBetaM * mPhase;
|
|
135
|
+
|
|
136
|
+
vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) );
|
|
137
|
+
Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) );
|
|
138
|
+
|
|
139
|
+
// nightsky
|
|
140
|
+
float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2]
|
|
141
|
+
float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2]
|
|
142
|
+
vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 );
|
|
143
|
+
vec3 L0 = vec3( 0.1 ) * Fex;
|
|
144
|
+
|
|
145
|
+
// composition + solar disc
|
|
146
|
+
float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta );
|
|
147
|
+
L0 += ( vSunE * 19000.0 * Fex ) * sundisk;
|
|
148
|
+
|
|
149
|
+
vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 );
|
|
150
|
+
|
|
151
|
+
vec3 retColor = pow( texColor, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) );
|
|
152
|
+
|
|
153
|
+
gl_FragColor = vec4( retColor, 1.0 );
|
|
154
|
+
|
|
155
|
+
#include <tonemapping_fragment>
|
|
156
|
+
#include <colorspace_fragment>
|
|
157
|
+
|
|
158
|
+
}`};class Ho extends u.Scene{constructor(){super();const e=new u.BoxGeometry;e.deleteAttribute("uv");const t=new u.MeshStandardMaterial({side:u.BackSide}),n=new u.MeshStandardMaterial,s=new u.PointLight(16777215,900,28,2);s.position.set(.418,16.199,.3),this.add(s);const i=new u.Mesh(e,t);i.position.set(-.757,13.219,.717),i.scale.set(31.713,28.305,28.591),this.add(i);const o=new u.Mesh(e,n);o.position.set(-10.906,2.009,1.846),o.rotation.set(0,-.195,0),o.scale.set(2.328,7.905,4.651),this.add(o);const a=new u.Mesh(e,n);a.position.set(-5.607,-.754,-.758),a.rotation.set(0,.994,0),a.scale.set(1.97,1.534,3.955),this.add(a);const c=new u.Mesh(e,n);c.position.set(6.167,.857,7.803),c.rotation.set(0,.561,0),c.scale.set(3.927,6.285,3.687),this.add(c);const l=new u.Mesh(e,n);l.position.set(-2.017,.018,6.124),l.rotation.set(0,.333,0),l.scale.set(2.002,4.566,2.064),this.add(l);const d=new u.Mesh(e,n);d.position.set(2.291,-.756,-2.621),d.rotation.set(0,-.286,0),d.scale.set(1.546,1.552,1.496),this.add(d);const h=new u.Mesh(e,n);h.position.set(-2.193,-.369,-5.547),h.rotation.set(0,.516,0),h.scale.set(3.875,3.487,2.986),this.add(h);const f=new u.Mesh(e,Mt(50));f.position.set(-16.116,14.37,8.208),f.scale.set(.1,2.428,2.739),this.add(f);const m=new u.Mesh(e,Mt(50));m.position.set(-16.109,18.021,-8.207),m.scale.set(.1,2.425,2.751),this.add(m);const y=new u.Mesh(e,Mt(17));y.position.set(14.904,12.198,-1.832),y.scale.set(.15,4.265,6.331),this.add(y);const v=new u.Mesh(e,Mt(43));v.position.set(-.462,8.89,14.52),v.scale.set(4.38,5.441,.088),this.add(v);const b=new u.Mesh(e,Mt(20));b.position.set(3.235,11.486,-12.541),b.scale.set(2.5,2,.1),this.add(b);const w=new u.Mesh(e,Mt(100));w.position.set(0,20,0),w.scale.set(1,.1,1),this.add(w)}dispose(){const e=new Set;this.traverse(t=>{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(const t of e)t.dispose()}}function Mt(r){const e=new u.MeshBasicMaterial;return e.color.setScalar(r),e}class ve extends Error{constructor(e,t,n,s){super(e),this.component=t,this.code=n,this.details=s,this.name="GlimmerError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,ve)}toJSON(){return{name:this.name,message:this.message,component:this.component,code:this.code,details:this.details,stack:this.stack}}toString(){return`${this.name} [${this.component}:${this.code}]: ${this.message}`}}const Le={INITIALIZATION_FAILED:"INITIALIZATION_FAILED",HDR_LOAD_FAILED:"HDR_LOAD_FAILED",ENVIRONMENT_UPDATE_FAILED:"ENVIRONMENT_UPDATE_FAILED",MODEL_LOAD_FAILED:"MODEL_LOAD_FAILED",MODEL_NOT_FOUND:"MODEL_NOT_FOUND",INVALID_STORY_JSON:"INVALID_STORY_JSON",INVALID_SLIDE_INDEX:"INVALID_SLIDE_INDEX"};class ui extends EventTarget{constructor(t,n){super();g(this,"settings");g(this,"renderer");g(this,"scene");g(this,"viewer");g(this,"ready");g(this,"texture",null);g(this,"ambient",null);g(this,"room",null);g(this,"env_map",null);g(this,"sky",null);g(this,"Sun",null);this.viewer=t,this.settings=n,this.renderer=t.renderer,this.scene=t.scene,this.settings.addEventListener("update",s=>{const i=s.detail;this.update(i.environment)}),this.ready=this.update(this.settings.get("environment"))}async update(t){G.info("Updating environment settings:",t);const{type:n,url:s}=t;this.dispatchEvent(new CustomEvent("loading",{detail:{type:n,url:s}}));try{if(n==="hdr"||n==="ultra"){if(this.clear_environment(),!s)return;await this.set_hdr_environment(s,n==="ultra")}else n==="sky"?(this.clear_environment(),this.set_sky_environment()):n==="room"?(this.clear_environment(),this.set_room_environment()):n==="none"?(this.clear_environment(),this.set_color_environment()):this.clear_environment();this.dispatchEvent(new CustomEvent("loaded",{detail:{type:n,url:s}}))}catch(i){G.error("Error updating environment:",i),this.clear_environment(),this.set_color_environment();const o=new ve(`Failed to update environment: ${i instanceof Error?i.message:i}`,"Environment",Le.ENVIRONMENT_UPDATE_FAILED,{type:n,url:s,error:i});throw this.dispatchEvent(new CustomEvent("error",{detail:{error:o}})),o}}clear_environment(){this.scene.background=null,this.scene.environment=null,this.sky=null,this.texture=null}set_sky_environment(){const t=new Cn;t.scale.setScalar(45e4);const n=_.MathUtils.degToRad(90),s=_.MathUtils.degToRad(180),i=new _.Vector3().setFromSphericalCoords(1,n,s);t.material.uniforms.sunPosition.value=i,this.sky=t,this.scene.add(this.sky)}set_room_environment(){const t=new Ho,s=new _.PMREMGenerator(this.renderer).fromScene(t).texture;this.scene.background=s,this.scene.environment=s}set_color_environment(t=16777215){this.scene.background=new _.Color(t)}async set_hdr_environment(t,n=!1){const s=new _.PMREMGenerator(this.renderer);s.compileEquirectangularShader();const i=n?new qo:new Ko;await new Promise((o,a)=>{i.load(t,c=>{try{this.texture=c;const l=s.fromEquirectangular(c).texture;this.scene.background=l,this.scene.environment=l,c.dispose(),s.dispose(),this.dispatchEvent(new CustomEvent("textureloaded",{detail:{texture:c}})),this.settings.dispatchEvent(new CustomEvent("environmentTextureLoaded",{detail:{texture:c}})),o()}catch(l){a(l)}},void 0,c=>{G.error("Error loading HDR texture:",c),a(new ve(`Failed to load HDR texture from ${t}`,"Environment",Le.HDR_LOAD_FAILED,{url:t,ultra:n,error:c}))})})}set_ambient_lighting(t=14544639,n=2){this.ambient=new _.AmbientLight(t,n),this.scene.add(this.ambient)}dispose(){var t,n;this.clear_environment(),this.ambient&&(this.scene.remove(this.ambient),(n=(t=this.ambient).dispose)==null||n.call(t),this.ambient=null),this.env_map&&(this.env_map.dispose(),this.env_map=null),this.texture&&(this.texture.dispose(),this.texture=null),this.sky&&(this.scene.remove(this.sky),this.sky=null)}}function hi(r){const t=new _.Box3().setFromObject(r).getSize(new _.Vector3);return Math.max(10,Math.max(t.x,t.y,t.z))}const Jo=512,Qo=100,ea=30,ta=-.001,na=3,sa=16;class fi{constructor(e,t,n,s){g(this,"viewer");g(this,"scene");g(this,"settings");g(this,"sun_settings");g(this,"model_manager");g(this,"sun",null);g(this,"environment");this.viewer=e,this.scene=e.scene,this.settings=t,this.environment=n,this.model_manager=s,this.sun_settings=this.settings.get("environment").sun,this.settings.addEventListener("update",i=>{const o=i.detail;this.sun_settings=o.environment.sun,this.update()}),this.settings.addEventListener("environmentTextureLoaded",i=>{const o=i.detail.texture;if(this.environment.texture=o,this.sun&&this.sun_settings){const a=this._infer_sun_position_from_env_map();G.debug("Texture loaded event call; inferred Sun position from env map:",a),this.sun_settings.position=[a.x,a.y,a.z],this.update()}}),this.update()}update(){if(!this.sun_settings){this.sun&&(this.scene.remove(this.sun),this.sun=null);return}this.model_manager.ready.then(()=>{if(this.sun_settings){const e=this._infer_sun_position_from_env_map();G.debug("Inferred Sun position from env map:",e),this.sun_settings.position=[e.x,e.y,e.z],this.sun_create()}})}sun_fit_object(e=this.scene){const t=hi(e);let n=new _.Vector3(0,1,0).normalize();n=n.multiplyScalar(t*2),this.sun&&(n=this.sun.position.clone())}sun_fit_shadow(){const e=new _.Object3D;if(!this.model_manager){G.warn("No model manager found.");return}for(const o of this.model_manager.models.values())o.settings.shadow&&e.add(o.group.clone());e.children.length===0&&G.warn("No models with shadows found to fit shadow map."),G.debug("Models in fit_object:",e);const t=hi(e),n=Jo,s=Math.ceil(t/Qo),i=Math.min(Math.pow(2,Math.ceil(Math.log2(n*s))),this.viewer.renderer.capabilities.maxTextureSize);if(G.debug("Shadow map size:",i),this.sun){this.sun.shadow.mapSize.width=i,this.sun.shadow.mapSize.height=i;const o=ea;this.sun.shadow.camera.left=-(t/2+o),this.sun.shadow.camera.right=t/2+o,this.sun.shadow.camera.top=t/2+o,this.sun.shadow.camera.bottom=-(t/2+o),this.sun.shadow.camera.near=.1,this.sun.shadow.camera.far=t*2,this.sun.shadow.bias=ta,this.sun.shadow.radius=na,this.sun.shadow.blurSamples=sa,G.info(`Recreated sun with shadow map size: ${i}x${i}`)}}sun_create(){if(!this.sun_settings)return;this.sun&&(this.scene.remove(this.sun),this.sun.dispose(),this.sun=null);const e=this.sun_settings.color,t=this.sun_settings.intensity;this.sun=new _.DirectionalLight(e,t),this.sun_settings.shadow&&(this.viewer.renderer.shadowMap.enabled=!0,this.sun.castShadow=!0,this.sun_fit_shadow()),this.sun.position.set(this.sun_settings.position[0],this.sun_settings.position[1],this.sun_settings.position[2]),this.scene.add(this.sun)}_infer_sun_position_from_env_map(){if(!this.environment)return G.warn("No environment map available."),new _.Vector3(0,1,0).normalize();if(!this.environment.texture||!this.environment.texture.image)return G.warn("No environment map texture found."),new _.Vector3(0,1,0).normalize();const e=this.environment.texture,t=e.image.width,n=e.image.height,s=e.image.data;let i=0;const o=[];for(let f=0;f<s.length;f+=4){const m=s[f],y=s[f+1],v=s[f+2],b=.2126*m+.7152*y+.0722*v;if(b>i){i=b,o.length=0;const w=f/4;o.push({x:w%t,y:Math.floor(w/t)})}else if(b===i){const w=f/4;o.push({x:w%t,y:Math.floor(w/t)})}}let a=0,c=0;o.forEach(f=>{a+=f.x,c+=f.y}),a/=o.length,c/=o.length;let l=a/t*2*Math.PI;l=(l+Math.PI)%(2*Math.PI);const d=c/n*Math.PI,h=new _.Vector3(Math.sin(d)*Math.cos(l),Math.cos(d),Math.sin(d)*Math.sin(l));return h.normalize(),h.multiplyScalar(100)}dispose(){var e,t;this.sun&&(this.scene.remove(this.sun),(t=(e=this.sun).dispose)==null||t.call(e),this.sun=null)}}const he=[];for(let r=0;r<256;++r)he.push((r+256).toString(16).slice(1));function ia(r,e=0){return(he[r[e+0]]+he[r[e+1]]+he[r[e+2]]+he[r[e+3]]+"-"+he[r[e+4]]+he[r[e+5]]+"-"+he[r[e+6]]+he[r[e+7]]+"-"+he[r[e+8]]+he[r[e+9]]+"-"+he[r[e+10]]+he[r[e+11]]+he[r[e+12]]+he[r[e+13]]+he[r[e+14]]+he[r[e+15]]).toLowerCase()}let ss;const ra=new Uint8Array(16);function oa(){if(!ss){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ss=crypto.getRandomValues.bind(crypto)}return ss(ra)}const pi={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function aa(r,e,t){var s;if(pi.randomUUID&&!r)return pi.randomUUID();r=r||{};const n=r.random??((s=r.rng)==null?void 0:s.call(r))??oa();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,ia(n)}function ca(r,e=1e-4){e=Math.max(e,Number.EPSILON);const t={},n=r.getIndex(),s=r.getAttribute("position"),i=n?n.count:s.count;let o=0;const a=Object.keys(r.attributes),c={},l={},d=[],h=["getX","getY","getZ","getW"],f=["setX","setY","setZ","setW"];for(let T=0,M=a.length;T<M;T++){const x=a[T],z=r.attributes[x];c[x]=new z.constructor(new z.array.constructor(z.count*z.itemSize),z.itemSize,z.normalized);const Z=r.morphAttributes[x];Z&&(l[x]||(l[x]=[]),Z.forEach((j,k)=>{const C=new j.array.constructor(j.count*j.itemSize);l[x][k]=new j.constructor(C,j.itemSize,j.normalized)}))}const m=e*.5,y=Math.log10(1/e),v=Math.pow(10,y),b=m*v;for(let T=0;T<i;T++){const M=n?n.getX(T):T;let x="";for(let z=0,Z=a.length;z<Z;z++){const j=a[z],k=r.getAttribute(j),C=k.itemSize;for(let I=0;I<C;I++)x+=`${~~(k[h[I]](M)*v+b)},`}if(x in t)d.push(t[x]);else{for(let z=0,Z=a.length;z<Z;z++){const j=a[z],k=r.getAttribute(j),C=r.morphAttributes[j],I=k.itemSize,R=c[j],W=l[j];for(let $=0;$<I;$++){const E=h[$],ee=f[$];if(R[ee](o,k[E](M)),C)for(let Y=0,Te=C.length;Y<Te;Y++)W[Y][ee](o,C[Y][E](M))}}t[x]=o,d.push(o),o++}}const w=r.clone();for(const T in r.attributes){const M=c[T];if(w.setAttribute(T,new M.constructor(M.array.slice(0,o*M.itemSize),M.itemSize,M.normalized)),T in l)for(let x=0;x<l[T].length;x++){const z=l[T][x];w.morphAttributes[T][x]=new z.constructor(z.array.slice(0,o*z.itemSize),z.itemSize,z.normalized)}}return w.setIndex(d),w}function mi(r,e){if(e===u.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),r;if(e===u.TriangleFanDrawMode||e===u.TriangleStripDrawMode){let t=r.getIndex();if(t===null){const o=[],a=r.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)o.push(c);r.setIndex(o),t=r.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),r}const n=t.count-2,s=[];if(e===u.TriangleFanDrawMode)for(let o=1;o<=n;o++)s.push(t.getX(0)),s.push(t.getX(o)),s.push(t.getX(o+1));else for(let o=0;o<n;o++)o%2===0?(s.push(t.getX(o)),s.push(t.getX(o+1)),s.push(t.getX(o+2))):(s.push(t.getX(o+2)),s.push(t.getX(o+1)),s.push(t.getX(o)));s.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const i=r.clone();return i.setIndex(s),i.clearGroups(),i}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),r}const _i=new u.Box3,On=new u.Vector3;class is extends u.InstancedBufferGeometry{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type="LineSegmentsGeometry";const e=[-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],t=[-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],n=[0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5];this.setIndex(n),this.setAttribute("position",new u.Float32BufferAttribute(e,3)),this.setAttribute("uv",new u.Float32BufferAttribute(t,2))}applyMatrix4(e){const t=this.attributes.instanceStart,n=this.attributes.instanceEnd;return t!==void 0&&(t.applyMatrix4(e),n.applyMatrix4(e),t.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}setPositions(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));const n=new u.InstancedInterleavedBuffer(t,6,1);return this.setAttribute("instanceStart",new u.InterleavedBufferAttribute(n,3,0)),this.setAttribute("instanceEnd",new u.InterleavedBufferAttribute(n,3,3)),this.instanceCount=this.attributes.instanceStart.count,this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));const n=new u.InstancedInterleavedBuffer(t,6,1);return this.setAttribute("instanceColorStart",new u.InterleavedBufferAttribute(n,3,0)),this.setAttribute("instanceColorEnd",new u.InterleavedBufferAttribute(n,3,3)),this}fromWireframeGeometry(e){return this.setPositions(e.attributes.position.array),this}fromEdgesGeometry(e){return this.setPositions(e.attributes.position.array),this}fromMesh(e){return this.fromWireframeGeometry(new u.WireframeGeometry(e.geometry)),this}fromLineSegments(e){const t=e.geometry;return this.setPositions(t.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new u.Box3);const e=this.attributes.instanceStart,t=this.attributes.instanceEnd;e!==void 0&&t!==void 0&&(this.boundingBox.setFromBufferAttribute(e),_i.setFromBufferAttribute(t),this.boundingBox.union(_i))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new u.Sphere),this.boundingBox===null&&this.computeBoundingBox();const e=this.attributes.instanceStart,t=this.attributes.instanceEnd;if(e!==void 0&&t!==void 0){const n=this.boundingSphere.center;this.boundingBox.getCenter(n);let s=0;for(let i=0,o=e.count;i<o;i++)On.fromBufferAttribute(e,i),s=Math.max(s,n.distanceToSquared(On)),On.fromBufferAttribute(t,i),s=Math.max(s,n.distanceToSquared(On));this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&console.error("THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.",this)}}toJSON(){}}u.UniformsLib.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new u.Vector2(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},u.ShaderLib.line={uniforms:u.UniformsUtils.merge([u.UniformsLib.common,u.UniformsLib.fog,u.UniformsLib.line]),vertexShader:`
|
|
159
|
+
#include <common>
|
|
160
|
+
#include <color_pars_vertex>
|
|
161
|
+
#include <fog_pars_vertex>
|
|
162
|
+
#include <logdepthbuf_pars_vertex>
|
|
163
|
+
#include <clipping_planes_pars_vertex>
|
|
164
|
+
|
|
165
|
+
uniform float linewidth;
|
|
166
|
+
uniform vec2 resolution;
|
|
167
|
+
|
|
168
|
+
attribute vec3 instanceStart;
|
|
169
|
+
attribute vec3 instanceEnd;
|
|
170
|
+
|
|
171
|
+
attribute vec3 instanceColorStart;
|
|
172
|
+
attribute vec3 instanceColorEnd;
|
|
173
|
+
|
|
174
|
+
#ifdef WORLD_UNITS
|
|
175
|
+
|
|
176
|
+
varying vec4 worldPos;
|
|
177
|
+
varying vec3 worldStart;
|
|
178
|
+
varying vec3 worldEnd;
|
|
179
|
+
|
|
180
|
+
#ifdef USE_DASH
|
|
181
|
+
|
|
182
|
+
varying vec2 vUv;
|
|
183
|
+
|
|
184
|
+
#endif
|
|
185
|
+
|
|
186
|
+
#else
|
|
187
|
+
|
|
188
|
+
varying vec2 vUv;
|
|
189
|
+
|
|
190
|
+
#endif
|
|
191
|
+
|
|
192
|
+
#ifdef USE_DASH
|
|
193
|
+
|
|
194
|
+
uniform float dashScale;
|
|
195
|
+
attribute float instanceDistanceStart;
|
|
196
|
+
attribute float instanceDistanceEnd;
|
|
197
|
+
varying float vLineDistance;
|
|
198
|
+
|
|
199
|
+
#endif
|
|
200
|
+
|
|
201
|
+
void trimSegment( const in vec4 start, inout vec4 end ) {
|
|
202
|
+
|
|
203
|
+
// trim end segment so it terminates between the camera plane and the near plane
|
|
204
|
+
|
|
205
|
+
// conservative estimate of the near plane
|
|
206
|
+
float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
|
|
207
|
+
float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
|
|
208
|
+
float nearEstimate = - 0.5 * b / a;
|
|
209
|
+
|
|
210
|
+
float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
|
|
211
|
+
|
|
212
|
+
end.xyz = mix( start.xyz, end.xyz, alpha );
|
|
213
|
+
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
void main() {
|
|
217
|
+
|
|
218
|
+
#ifdef USE_COLOR
|
|
219
|
+
|
|
220
|
+
vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
|
|
221
|
+
|
|
222
|
+
#endif
|
|
223
|
+
|
|
224
|
+
#ifdef USE_DASH
|
|
225
|
+
|
|
226
|
+
vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
|
|
227
|
+
vUv = uv;
|
|
228
|
+
|
|
229
|
+
#endif
|
|
230
|
+
|
|
231
|
+
float aspect = resolution.x / resolution.y;
|
|
232
|
+
|
|
233
|
+
// camera space
|
|
234
|
+
vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
|
|
235
|
+
vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
|
|
236
|
+
|
|
237
|
+
#ifdef WORLD_UNITS
|
|
238
|
+
|
|
239
|
+
worldStart = start.xyz;
|
|
240
|
+
worldEnd = end.xyz;
|
|
241
|
+
|
|
242
|
+
#else
|
|
243
|
+
|
|
244
|
+
vUv = uv;
|
|
245
|
+
|
|
246
|
+
#endif
|
|
247
|
+
|
|
248
|
+
// special case for perspective projection, and segments that terminate either in, or behind, the camera plane
|
|
249
|
+
// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
|
|
250
|
+
// but we need to perform ndc-space calculations in the shader, so we must address this issue directly
|
|
251
|
+
// perhaps there is a more elegant solution -- WestLangley
|
|
252
|
+
|
|
253
|
+
bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
|
|
254
|
+
|
|
255
|
+
if ( perspective ) {
|
|
256
|
+
|
|
257
|
+
if ( start.z < 0.0 && end.z >= 0.0 ) {
|
|
258
|
+
|
|
259
|
+
trimSegment( start, end );
|
|
260
|
+
|
|
261
|
+
} else if ( end.z < 0.0 && start.z >= 0.0 ) {
|
|
262
|
+
|
|
263
|
+
trimSegment( end, start );
|
|
264
|
+
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// clip space
|
|
270
|
+
vec4 clipStart = projectionMatrix * start;
|
|
271
|
+
vec4 clipEnd = projectionMatrix * end;
|
|
272
|
+
|
|
273
|
+
// ndc space
|
|
274
|
+
vec3 ndcStart = clipStart.xyz / clipStart.w;
|
|
275
|
+
vec3 ndcEnd = clipEnd.xyz / clipEnd.w;
|
|
276
|
+
|
|
277
|
+
// direction
|
|
278
|
+
vec2 dir = ndcEnd.xy - ndcStart.xy;
|
|
279
|
+
|
|
280
|
+
// account for clip-space aspect ratio
|
|
281
|
+
dir.x *= aspect;
|
|
282
|
+
dir = normalize( dir );
|
|
283
|
+
|
|
284
|
+
#ifdef WORLD_UNITS
|
|
285
|
+
|
|
286
|
+
vec3 worldDir = normalize( end.xyz - start.xyz );
|
|
287
|
+
vec3 tmpFwd = normalize( mix( start.xyz, end.xyz, 0.5 ) );
|
|
288
|
+
vec3 worldUp = normalize( cross( worldDir, tmpFwd ) );
|
|
289
|
+
vec3 worldFwd = cross( worldDir, worldUp );
|
|
290
|
+
worldPos = position.y < 0.5 ? start: end;
|
|
291
|
+
|
|
292
|
+
// height offset
|
|
293
|
+
float hw = linewidth * 0.5;
|
|
294
|
+
worldPos.xyz += position.x < 0.0 ? hw * worldUp : - hw * worldUp;
|
|
295
|
+
|
|
296
|
+
// don't extend the line if we're rendering dashes because we
|
|
297
|
+
// won't be rendering the endcaps
|
|
298
|
+
#ifndef USE_DASH
|
|
299
|
+
|
|
300
|
+
// cap extension
|
|
301
|
+
worldPos.xyz += position.y < 0.5 ? - hw * worldDir : hw * worldDir;
|
|
302
|
+
|
|
303
|
+
// add width to the box
|
|
304
|
+
worldPos.xyz += worldFwd * hw;
|
|
305
|
+
|
|
306
|
+
// endcaps
|
|
307
|
+
if ( position.y > 1.0 || position.y < 0.0 ) {
|
|
308
|
+
|
|
309
|
+
worldPos.xyz -= worldFwd * 2.0 * hw;
|
|
310
|
+
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
#endif
|
|
314
|
+
|
|
315
|
+
// project the worldpos
|
|
316
|
+
vec4 clip = projectionMatrix * worldPos;
|
|
317
|
+
|
|
318
|
+
// shift the depth of the projected points so the line
|
|
319
|
+
// segments overlap neatly
|
|
320
|
+
vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
|
|
321
|
+
clip.z = clipPose.z * clip.w;
|
|
322
|
+
|
|
323
|
+
#else
|
|
324
|
+
|
|
325
|
+
vec2 offset = vec2( dir.y, - dir.x );
|
|
326
|
+
// undo aspect ratio adjustment
|
|
327
|
+
dir.x /= aspect;
|
|
328
|
+
offset.x /= aspect;
|
|
329
|
+
|
|
330
|
+
// sign flip
|
|
331
|
+
if ( position.x < 0.0 ) offset *= - 1.0;
|
|
332
|
+
|
|
333
|
+
// endcaps
|
|
334
|
+
if ( position.y < 0.0 ) {
|
|
335
|
+
|
|
336
|
+
offset += - dir;
|
|
337
|
+
|
|
338
|
+
} else if ( position.y > 1.0 ) {
|
|
339
|
+
|
|
340
|
+
offset += dir;
|
|
341
|
+
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// adjust for linewidth
|
|
345
|
+
offset *= linewidth;
|
|
346
|
+
|
|
347
|
+
// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
|
|
348
|
+
offset /= resolution.y;
|
|
349
|
+
|
|
350
|
+
// select end
|
|
351
|
+
vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
|
|
352
|
+
|
|
353
|
+
// back to clip space
|
|
354
|
+
offset *= clip.w;
|
|
355
|
+
|
|
356
|
+
clip.xy += offset;
|
|
357
|
+
|
|
358
|
+
#endif
|
|
359
|
+
|
|
360
|
+
gl_Position = clip;
|
|
361
|
+
|
|
362
|
+
vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
|
|
363
|
+
|
|
364
|
+
#include <logdepthbuf_vertex>
|
|
365
|
+
#include <clipping_planes_vertex>
|
|
366
|
+
#include <fog_vertex>
|
|
367
|
+
|
|
368
|
+
}
|
|
369
|
+
`,fragmentShader:`
|
|
370
|
+
uniform vec3 diffuse;
|
|
371
|
+
uniform float opacity;
|
|
372
|
+
uniform float linewidth;
|
|
373
|
+
|
|
374
|
+
#ifdef USE_DASH
|
|
375
|
+
|
|
376
|
+
uniform float dashOffset;
|
|
377
|
+
uniform float dashSize;
|
|
378
|
+
uniform float gapSize;
|
|
379
|
+
|
|
380
|
+
#endif
|
|
381
|
+
|
|
382
|
+
varying float vLineDistance;
|
|
383
|
+
|
|
384
|
+
#ifdef WORLD_UNITS
|
|
385
|
+
|
|
386
|
+
varying vec4 worldPos;
|
|
387
|
+
varying vec3 worldStart;
|
|
388
|
+
varying vec3 worldEnd;
|
|
389
|
+
|
|
390
|
+
#ifdef USE_DASH
|
|
391
|
+
|
|
392
|
+
varying vec2 vUv;
|
|
393
|
+
|
|
394
|
+
#endif
|
|
395
|
+
|
|
396
|
+
#else
|
|
397
|
+
|
|
398
|
+
varying vec2 vUv;
|
|
399
|
+
|
|
400
|
+
#endif
|
|
401
|
+
|
|
402
|
+
#include <common>
|
|
403
|
+
#include <color_pars_fragment>
|
|
404
|
+
#include <fog_pars_fragment>
|
|
405
|
+
#include <logdepthbuf_pars_fragment>
|
|
406
|
+
#include <clipping_planes_pars_fragment>
|
|
407
|
+
|
|
408
|
+
vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
|
|
409
|
+
|
|
410
|
+
float mua;
|
|
411
|
+
float mub;
|
|
412
|
+
|
|
413
|
+
vec3 p13 = p1 - p3;
|
|
414
|
+
vec3 p43 = p4 - p3;
|
|
415
|
+
|
|
416
|
+
vec3 p21 = p2 - p1;
|
|
417
|
+
|
|
418
|
+
float d1343 = dot( p13, p43 );
|
|
419
|
+
float d4321 = dot( p43, p21 );
|
|
420
|
+
float d1321 = dot( p13, p21 );
|
|
421
|
+
float d4343 = dot( p43, p43 );
|
|
422
|
+
float d2121 = dot( p21, p21 );
|
|
423
|
+
|
|
424
|
+
float denom = d2121 * d4343 - d4321 * d4321;
|
|
425
|
+
|
|
426
|
+
float numer = d1343 * d4321 - d1321 * d4343;
|
|
427
|
+
|
|
428
|
+
mua = numer / denom;
|
|
429
|
+
mua = clamp( mua, 0.0, 1.0 );
|
|
430
|
+
mub = ( d1343 + d4321 * ( mua ) ) / d4343;
|
|
431
|
+
mub = clamp( mub, 0.0, 1.0 );
|
|
432
|
+
|
|
433
|
+
return vec2( mua, mub );
|
|
434
|
+
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
void main() {
|
|
438
|
+
|
|
439
|
+
#include <clipping_planes_fragment>
|
|
440
|
+
|
|
441
|
+
#ifdef USE_DASH
|
|
442
|
+
|
|
443
|
+
if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
|
|
444
|
+
|
|
445
|
+
if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
|
|
446
|
+
|
|
447
|
+
#endif
|
|
448
|
+
|
|
449
|
+
float alpha = opacity;
|
|
450
|
+
|
|
451
|
+
#ifdef WORLD_UNITS
|
|
452
|
+
|
|
453
|
+
// Find the closest points on the view ray and the line segment
|
|
454
|
+
vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
|
|
455
|
+
vec3 lineDir = worldEnd - worldStart;
|
|
456
|
+
vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );
|
|
457
|
+
|
|
458
|
+
vec3 p1 = worldStart + lineDir * params.x;
|
|
459
|
+
vec3 p2 = rayEnd * params.y;
|
|
460
|
+
vec3 delta = p1 - p2;
|
|
461
|
+
float len = length( delta );
|
|
462
|
+
float norm = len / linewidth;
|
|
463
|
+
|
|
464
|
+
#ifndef USE_DASH
|
|
465
|
+
|
|
466
|
+
#ifdef USE_ALPHA_TO_COVERAGE
|
|
467
|
+
|
|
468
|
+
float dnorm = fwidth( norm );
|
|
469
|
+
alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );
|
|
470
|
+
|
|
471
|
+
#else
|
|
472
|
+
|
|
473
|
+
if ( norm > 0.5 ) {
|
|
474
|
+
|
|
475
|
+
discard;
|
|
476
|
+
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
#endif
|
|
480
|
+
|
|
481
|
+
#endif
|
|
482
|
+
|
|
483
|
+
#else
|
|
484
|
+
|
|
485
|
+
#ifdef USE_ALPHA_TO_COVERAGE
|
|
486
|
+
|
|
487
|
+
// artifacts appear on some hardware if a derivative is taken within a conditional
|
|
488
|
+
float a = vUv.x;
|
|
489
|
+
float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
|
|
490
|
+
float len2 = a * a + b * b;
|
|
491
|
+
float dlen = fwidth( len2 );
|
|
492
|
+
|
|
493
|
+
if ( abs( vUv.y ) > 1.0 ) {
|
|
494
|
+
|
|
495
|
+
alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );
|
|
496
|
+
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
#else
|
|
500
|
+
|
|
501
|
+
if ( abs( vUv.y ) > 1.0 ) {
|
|
502
|
+
|
|
503
|
+
float a = vUv.x;
|
|
504
|
+
float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
|
|
505
|
+
float len2 = a * a + b * b;
|
|
506
|
+
|
|
507
|
+
if ( len2 > 1.0 ) discard;
|
|
508
|
+
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
#endif
|
|
512
|
+
|
|
513
|
+
#endif
|
|
514
|
+
|
|
515
|
+
vec4 diffuseColor = vec4( diffuse, alpha );
|
|
516
|
+
|
|
517
|
+
#include <logdepthbuf_fragment>
|
|
518
|
+
#include <color_fragment>
|
|
519
|
+
|
|
520
|
+
gl_FragColor = vec4( diffuseColor.rgb, alpha );
|
|
521
|
+
|
|
522
|
+
#include <tonemapping_fragment>
|
|
523
|
+
#include <colorspace_fragment>
|
|
524
|
+
#include <fog_fragment>
|
|
525
|
+
#include <premultiplied_alpha_fragment>
|
|
526
|
+
|
|
527
|
+
}
|
|
528
|
+
`};class gi extends u.ShaderMaterial{constructor(e){super({type:"LineMaterial",uniforms:u.UniformsUtils.clone(u.ShaderLib.line.uniforms),vertexShader:u.ShaderLib.line.vertexShader,fragmentShader:u.ShaderLib.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(e){e===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return"USE_DASH"in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?this.defines.USE_ALPHA_TO_COVERAGE="":delete this.defines.USE_ALPHA_TO_COVERAGE)}}const rs=new u.Vector4,yi=new u.Vector3,vi=new u.Vector3,fe=new u.Vector4,pe=new u.Vector4,Ge=new u.Vector4,os=new u.Vector3,as=new u.Matrix4,me=new u.Line3,xi=new u.Vector3,kn=new u.Box3,Dn=new u.Sphere,Ze=new u.Vector4;let We,ft;function bi(r,e,t){return Ze.set(0,0,-e,1).applyMatrix4(r.projectionMatrix),Ze.multiplyScalar(1/Ze.w),Ze.x=ft/t.width,Ze.y=ft/t.height,Ze.applyMatrix4(r.projectionMatrixInverse),Ze.multiplyScalar(1/Ze.w),Math.abs(Math.max(Ze.x,Ze.y))}function la(r,e){const t=r.matrixWorld,n=r.geometry,s=n.attributes.instanceStart,i=n.attributes.instanceEnd,o=Math.min(n.instanceCount,s.count);for(let a=0,c=o;a<c;a++){me.start.fromBufferAttribute(s,a),me.end.fromBufferAttribute(i,a),me.applyMatrix4(t);const l=new u.Vector3,d=new u.Vector3;We.distanceSqToSegment(me.start,me.end,d,l),d.distanceTo(l)<ft*.5&&e.push({point:d,pointOnLine:l,distance:We.origin.distanceTo(d),object:r,face:null,faceIndex:a,uv:null,uv1:null})}}function da(r,e,t){const n=e.projectionMatrix,i=r.material.resolution,o=r.matrixWorld,a=r.geometry,c=a.attributes.instanceStart,l=a.attributes.instanceEnd,d=Math.min(a.instanceCount,c.count),h=-e.near;We.at(1,Ge),Ge.w=1,Ge.applyMatrix4(e.matrixWorldInverse),Ge.applyMatrix4(n),Ge.multiplyScalar(1/Ge.w),Ge.x*=i.x/2,Ge.y*=i.y/2,Ge.z=0,os.copy(Ge),as.multiplyMatrices(e.matrixWorldInverse,o);for(let f=0,m=d;f<m;f++){if(fe.fromBufferAttribute(c,f),pe.fromBufferAttribute(l,f),fe.w=1,pe.w=1,fe.applyMatrix4(as),pe.applyMatrix4(as),fe.z>h&&pe.z>h)continue;if(fe.z>h){const M=fe.z-pe.z,x=(fe.z-h)/M;fe.lerp(pe,x)}else if(pe.z>h){const M=pe.z-fe.z,x=(pe.z-h)/M;pe.lerp(fe,x)}fe.applyMatrix4(n),pe.applyMatrix4(n),fe.multiplyScalar(1/fe.w),pe.multiplyScalar(1/pe.w),fe.x*=i.x/2,fe.y*=i.y/2,pe.x*=i.x/2,pe.y*=i.y/2,me.start.copy(fe),me.start.z=0,me.end.copy(pe),me.end.z=0;const v=me.closestPointToPointParameter(os,!0);me.at(v,xi);const b=u.MathUtils.lerp(fe.z,pe.z,v),w=b>=-1&&b<=1,T=os.distanceTo(xi)<ft*.5;if(w&&T){me.start.fromBufferAttribute(c,f),me.end.fromBufferAttribute(l,f),me.start.applyMatrix4(o),me.end.applyMatrix4(o);const M=new u.Vector3,x=new u.Vector3;We.distanceSqToSegment(me.start,me.end,x,M),t.push({point:x,pointOnLine:M,distance:We.origin.distanceTo(x),object:r,face:null,faceIndex:f,uv:null,uv1:null})}}}class wi extends u.Mesh{constructor(e=new is,t=new gi({color:Math.random()*16777215})){super(e,t),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const e=this.geometry,t=e.attributes.instanceStart,n=e.attributes.instanceEnd,s=new Float32Array(2*t.count);for(let o=0,a=0,c=t.count;o<c;o++,a+=2)yi.fromBufferAttribute(t,o),vi.fromBufferAttribute(n,o),s[a]=a===0?0:s[a-1],s[a+1]=s[a]+yi.distanceTo(vi);const i=new u.InstancedInterleavedBuffer(s,2,1);return e.setAttribute("instanceDistanceStart",new u.InterleavedBufferAttribute(i,1,0)),e.setAttribute("instanceDistanceEnd",new u.InterleavedBufferAttribute(i,1,1)),this}raycast(e,t){const n=this.material.worldUnits,s=e.camera;s===null&&!n&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');const i=e.params.Line2!==void 0&&e.params.Line2.threshold||0;We=e.ray;const o=this.matrixWorld,a=this.geometry,c=this.material;ft=c.linewidth+i,a.boundingSphere===null&&a.computeBoundingSphere(),Dn.copy(a.boundingSphere).applyMatrix4(o);let l;if(n)l=ft*.5;else{const h=Math.max(s.near,Dn.distanceToPoint(We.origin));l=bi(s,h,c.resolution)}if(Dn.radius+=l,We.intersectsSphere(Dn)===!1)return;a.boundingBox===null&&a.computeBoundingBox(),kn.copy(a.boundingBox).applyMatrix4(o);let d;if(n)d=ft*.5;else{const h=Math.max(s.near,kn.distanceToPoint(We.origin));d=bi(s,h,c.resolution)}kn.expandByScalar(d),We.intersectsBox(kn)!==!1&&(n?la(this,t):da(this,s,t))}onBeforeRender(e){const t=this.material.uniforms;t&&t.resolution&&(e.getViewport(rs),this.material.uniforms.resolution.value.set(rs.z,rs.w))}}class Ai extends _.BufferGeometry{constructor(e,t=4){super();const n={},s=e.attributes.position;let i;if(e.index)i=e.index;else{const M=new Array(s.count).fill(0).map((x,z)=>z);i=new _.BufferAttribute(new Uint32Array(M),1,!1)}for(let M=0,x=i.count;M<x;M+=3){const z=[i.getX(M+0),i.getX(M+1),i.getX(M+2)];for(let Z=0;Z<3;Z++){const j=z[Z],k=z[(Z+1)%3],C=`${j}_${k}`,I=`${k}_${j}`;I in n?(n[I].controlIndex1=z[(Z+2)%3],n[I].tri1=M/3):n[C]={index0:j,index1:k,controlIndex0:z[(Z+2)%3],controlIndex1:null,tri0:M/3,tri1:null}}}const o=[],a=[],c=[],l=[],d=new _.Triangle,h=new _.Triangle,f=new _.Vector3,m=new _.Vector3,y=new _.Vector3,v=new _.Vector3,b=new _.Vector3,w=new _.Vector3,T=new _.Vector3;for(const M in n){const{index0:x,index1:z,controlIndex0:Z,controlIndex1:j,tri0:k,tri1:C}=n[M];if(j===null)continue;d.a.fromBufferAttribute(s,i.getX(k*3+0)),d.b.fromBufferAttribute(s,i.getX(k*3+1)),d.c.fromBufferAttribute(s,i.getX(k*3+2)),h.a.fromBufferAttribute(s,i.getX(C*3+0)),h.b.fromBufferAttribute(s,i.getX(C*3+1)),h.c.fromBufferAttribute(s,i.getX(C*3+2)),d.getNormal(f).normalize(),h.getNormal(m).normalize();const I=Math.cos(_.MathUtils.degToRad(t));f.dot(m)>I||(y.fromBufferAttribute(s,x),v.fromBufferAttribute(s,z),b.subVectors(y,v),w.fromBufferAttribute(s,Z),T.fromBufferAttribute(s,j),o.push(y.x,y.y,y.z),a.push(b.x,b.y,b.z),c.push(w.x,w.y,w.z),l.push(T.x,T.y,T.z),o.push(v.x,v.y,v.z),a.push(b.x,b.y,b.z),c.push(w.x,w.y,w.z),l.push(T.x,T.y,T.z))}this.setAttribute("position",new _.BufferAttribute(new Float32Array(o),3,!1)),this.setAttribute("direction",new _.BufferAttribute(new Float32Array(a),3,!1)),this.setAttribute("control0",new _.BufferAttribute(new Float32Array(c),3,!1)),this.setAttribute("control1",new _.BufferAttribute(new Float32Array(l),3,!1))}}class ua extends is{from_conditional_edges_geometry(e){super.fromEdgesGeometry(e);const{direction:t,control0:n,control1:s}=e.attributes;return this.setAttribute("direction",new _.InterleavedBufferAttribute(new _.InstancedInterleavedBuffer(t.array,6,1),3,0)),this.setAttribute("control0",new _.InterleavedBufferAttribute(new _.InstancedInterleavedBuffer(n.array,6,1),3,0)),this.setAttribute("control1",new _.InterleavedBufferAttribute(new _.InstancedInterleavedBuffer(s.array,6,1),3,0)),this}}const ha={uniforms:{diffuse:{value:new _.Color},opacity:{value:1}},vertexShader:`
|
|
529
|
+
attribute vec3 control0;
|
|
530
|
+
attribute vec3 control1;
|
|
531
|
+
attribute vec3 direction;
|
|
532
|
+
|
|
533
|
+
#include <common>
|
|
534
|
+
#include <color_pars_vertex>
|
|
535
|
+
#include <fog_pars_vertex>
|
|
536
|
+
#include <logdepthbuf_pars_vertex>
|
|
537
|
+
#include <clipping_planes_pars_vertex>
|
|
538
|
+
void main() {
|
|
539
|
+
|
|
540
|
+
#include <color_vertex>
|
|
541
|
+
|
|
542
|
+
vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
|
|
543
|
+
gl_Position = projectionMatrix * mvPosition;
|
|
544
|
+
|
|
545
|
+
// Transform the line segment ends and control points into camera clip space
|
|
546
|
+
vec4 c0 = projectionMatrix * modelViewMatrix * vec4( control0, 1.0 );
|
|
547
|
+
vec4 c1 = projectionMatrix * modelViewMatrix * vec4( control1, 1.0 );
|
|
548
|
+
vec4 p0 = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
549
|
+
vec4 p1 = projectionMatrix * modelViewMatrix * vec4( position + direction, 1.0 );
|
|
550
|
+
|
|
551
|
+
c0 /= c0.w;
|
|
552
|
+
c1 /= c1.w;
|
|
553
|
+
p0 /= p0.w;
|
|
554
|
+
p1 /= p1.w;
|
|
555
|
+
|
|
556
|
+
// Get the direction of the segment and an orthogonal vector
|
|
557
|
+
vec2 dir = p1.xy - p0.xy;
|
|
558
|
+
vec2 norm = vec2( -dir.y, dir.x );
|
|
559
|
+
|
|
560
|
+
// Get control point directions from the line
|
|
561
|
+
vec2 c0dir = c0.xy - p1.xy;
|
|
562
|
+
vec2 c1dir = c1.xy - p1.xy;
|
|
563
|
+
|
|
564
|
+
// If the vectors to the controls points are pointed in different directions away
|
|
565
|
+
// from the line segment then the line should not be drawn.
|
|
566
|
+
float d0 = dot( normalize( norm ), normalize( c0dir ) );
|
|
567
|
+
float d1 = dot( normalize( norm ), normalize( c1dir ) );
|
|
568
|
+
|
|
569
|
+
float discardFlag = float( sign( d0 ) != sign( d1 ) );
|
|
570
|
+
gl_Position = discardFlag > 0.5 ? c0 : gl_Position;
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
#include <logdepthbuf_vertex>
|
|
574
|
+
#include <clipping_planes_vertex>
|
|
575
|
+
#include <fog_vertex>
|
|
576
|
+
|
|
577
|
+
}
|
|
578
|
+
`,fragmentShader:`
|
|
579
|
+
uniform vec3 diffuse;
|
|
580
|
+
uniform float opacity;
|
|
581
|
+
|
|
582
|
+
#include <common>
|
|
583
|
+
#include <color_pars_fragment>
|
|
584
|
+
#include <fog_pars_fragment>
|
|
585
|
+
#include <logdepthbuf_pars_fragment>
|
|
586
|
+
#include <clipping_planes_pars_fragment>
|
|
587
|
+
void main() {
|
|
588
|
+
|
|
589
|
+
#include <clipping_planes_fragment>
|
|
590
|
+
|
|
591
|
+
vec3 outgoingLight = vec3( 0.0 );
|
|
592
|
+
vec4 diffuseColor = vec4( diffuse, opacity );
|
|
593
|
+
|
|
594
|
+
#include <logdepthbuf_fragment>
|
|
595
|
+
#include <color_fragment>
|
|
596
|
+
|
|
597
|
+
outgoingLight = diffuseColor.rgb; // simple shader
|
|
598
|
+
gl_FragColor = vec4( outgoingLight, diffuseColor.a );
|
|
599
|
+
|
|
600
|
+
#include <tonemapping_fragment>
|
|
601
|
+
#include <fog_fragment>
|
|
602
|
+
#include <premultiplied_alpha_fragment>
|
|
603
|
+
|
|
604
|
+
}
|
|
605
|
+
`},fa=`
|
|
606
|
+
#include <common>
|
|
607
|
+
#include <color_pars_vertex>
|
|
608
|
+
#include <fog_pars_vertex>
|
|
609
|
+
#include <logdepthbuf_pars_vertex>
|
|
610
|
+
#include <clipping_planes_pars_vertex>
|
|
611
|
+
|
|
612
|
+
uniform float linewidth;
|
|
613
|
+
uniform vec2 resolution;
|
|
614
|
+
|
|
615
|
+
attribute vec3 control0;
|
|
616
|
+
attribute vec3 control1;
|
|
617
|
+
attribute vec3 direction;
|
|
618
|
+
|
|
619
|
+
attribute vec3 instanceStart;
|
|
620
|
+
attribute vec3 instanceEnd;
|
|
621
|
+
|
|
622
|
+
attribute vec3 instanceColorStart;
|
|
623
|
+
attribute vec3 instanceColorEnd;
|
|
624
|
+
|
|
625
|
+
varying vec2 vUv;
|
|
626
|
+
|
|
627
|
+
#ifdef USE_DASH
|
|
628
|
+
|
|
629
|
+
uniform float dashScale;
|
|
630
|
+
attribute float instanceDistanceStart;
|
|
631
|
+
attribute float instanceDistanceEnd;
|
|
632
|
+
varying float vLineDistance;
|
|
633
|
+
|
|
634
|
+
#endif
|
|
635
|
+
|
|
636
|
+
void trimSegment( const in vec4 start, inout vec4 end ) {
|
|
637
|
+
|
|
638
|
+
// trim end segment so it terminates between the camera plane and the near plane
|
|
639
|
+
|
|
640
|
+
// conservative estimate of the near plane
|
|
641
|
+
float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
|
|
642
|
+
float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
|
|
643
|
+
float nearEstimate = - 0.5 * b / a;
|
|
644
|
+
|
|
645
|
+
float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
|
|
646
|
+
|
|
647
|
+
end.xyz = mix( start.xyz, end.xyz, alpha );
|
|
648
|
+
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
void main() {
|
|
652
|
+
|
|
653
|
+
#ifdef USE_COLOR
|
|
654
|
+
|
|
655
|
+
vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
|
|
656
|
+
|
|
657
|
+
#endif
|
|
658
|
+
|
|
659
|
+
#ifdef USE_DASH
|
|
660
|
+
|
|
661
|
+
vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
|
|
662
|
+
|
|
663
|
+
#endif
|
|
664
|
+
|
|
665
|
+
float aspect = resolution.x / resolution.y;
|
|
666
|
+
|
|
667
|
+
vUv = uv;
|
|
668
|
+
|
|
669
|
+
// camera space
|
|
670
|
+
vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
|
|
671
|
+
vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
|
|
672
|
+
|
|
673
|
+
// special case for perspective projection, and segments that terminate either in, or behind, the camera plane
|
|
674
|
+
// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
|
|
675
|
+
// but we need to perform ndc-space calculations in the shader, so we must address this issue directly
|
|
676
|
+
// perhaps there is a more elegant solution -- WestLangley
|
|
677
|
+
|
|
678
|
+
bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
|
|
679
|
+
|
|
680
|
+
if ( perspective ) {
|
|
681
|
+
|
|
682
|
+
if ( start.z < 0.0 && end.z >= 0.0 ) {
|
|
683
|
+
|
|
684
|
+
trimSegment( start, end );
|
|
685
|
+
|
|
686
|
+
} else if ( end.z < 0.0 && start.z >= 0.0 ) {
|
|
687
|
+
|
|
688
|
+
trimSegment( end, start );
|
|
689
|
+
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
// clip space
|
|
695
|
+
vec4 clipStart = projectionMatrix * start;
|
|
696
|
+
vec4 clipEnd = projectionMatrix * end;
|
|
697
|
+
|
|
698
|
+
// ndc space
|
|
699
|
+
vec2 ndcStart = clipStart.xy / clipStart.w;
|
|
700
|
+
vec2 ndcEnd = clipEnd.xy / clipEnd.w;
|
|
701
|
+
|
|
702
|
+
// direction
|
|
703
|
+
vec2 dir = ndcEnd - ndcStart;
|
|
704
|
+
|
|
705
|
+
// account for clip-space aspect ratio
|
|
706
|
+
dir.x *= aspect;
|
|
707
|
+
dir = normalize( dir );
|
|
708
|
+
|
|
709
|
+
// perpendicular to dir
|
|
710
|
+
vec2 offset = vec2( dir.y, - dir.x );
|
|
711
|
+
|
|
712
|
+
// undo aspect ratio adjustment
|
|
713
|
+
dir.x /= aspect;
|
|
714
|
+
offset.x /= aspect;
|
|
715
|
+
|
|
716
|
+
// sign flip
|
|
717
|
+
if ( position.x < 0.0 ) offset *= - 1.0;
|
|
718
|
+
|
|
719
|
+
// endcaps
|
|
720
|
+
if ( position.y < 0.0 ) {
|
|
721
|
+
|
|
722
|
+
offset += - dir;
|
|
723
|
+
|
|
724
|
+
} else if ( position.y > 1.0 ) {
|
|
725
|
+
|
|
726
|
+
offset += dir;
|
|
727
|
+
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
// adjust for linewidth
|
|
731
|
+
offset *= linewidth;
|
|
732
|
+
|
|
733
|
+
// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
|
|
734
|
+
offset /= resolution.y;
|
|
735
|
+
|
|
736
|
+
// select end
|
|
737
|
+
vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
|
|
738
|
+
|
|
739
|
+
// back to clip space
|
|
740
|
+
offset *= clip.w;
|
|
741
|
+
|
|
742
|
+
clip.xy += offset;
|
|
743
|
+
|
|
744
|
+
gl_Position = clip;
|
|
745
|
+
|
|
746
|
+
vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
|
|
747
|
+
|
|
748
|
+
#include <logdepthbuf_vertex>
|
|
749
|
+
#include <clipping_planes_vertex>
|
|
750
|
+
#include <fog_vertex>
|
|
751
|
+
|
|
752
|
+
// conditional logic
|
|
753
|
+
// Transform the line segment ends and control points into camera clip space
|
|
754
|
+
vec4 c0 = projectionMatrix * modelViewMatrix * vec4( control0, 1.0 );
|
|
755
|
+
vec4 c1 = projectionMatrix * modelViewMatrix * vec4( control1, 1.0 );
|
|
756
|
+
vec4 p0 = projectionMatrix * modelViewMatrix * vec4( instanceStart, 1.0 );
|
|
757
|
+
vec4 p1 = projectionMatrix * modelViewMatrix * vec4( instanceStart + direction, 1.0 );
|
|
758
|
+
|
|
759
|
+
c0 /= c0.w;
|
|
760
|
+
c1 /= c1.w;
|
|
761
|
+
p0 /= p0.w;
|
|
762
|
+
p1 /= p1.w;
|
|
763
|
+
|
|
764
|
+
// Get the direction of the segment and an orthogonal vector
|
|
765
|
+
vec2 segDir = p1.xy - p0.xy;
|
|
766
|
+
vec2 norm = vec2( - segDir.y, segDir.x );
|
|
767
|
+
|
|
768
|
+
// Get control point directions from the line
|
|
769
|
+
vec2 c0dir = c0.xy - p1.xy;
|
|
770
|
+
vec2 c1dir = c1.xy - p1.xy;
|
|
771
|
+
|
|
772
|
+
// If the vectors to the controls points are pointed in different directions away
|
|
773
|
+
// from the line segment then the line should not be drawn.
|
|
774
|
+
float d0 = dot( normalize( norm ), normalize( c0dir ) );
|
|
775
|
+
float d1 = dot( normalize( norm ), normalize( c1dir ) );
|
|
776
|
+
float discardFlag = float( sign( d0 ) != sign( d1 ) );
|
|
777
|
+
gl_Position = discardFlag > 0.5 ? c0 : gl_Position;
|
|
778
|
+
// end conditional line logic
|
|
779
|
+
|
|
780
|
+
}
|
|
781
|
+
`,pa=`
|
|
782
|
+
uniform vec3 diffuse;
|
|
783
|
+
uniform float opacity;
|
|
784
|
+
|
|
785
|
+
#ifdef USE_DASH
|
|
786
|
+
|
|
787
|
+
uniform float dashSize;
|
|
788
|
+
uniform float gapSize;
|
|
789
|
+
|
|
790
|
+
#endif
|
|
791
|
+
|
|
792
|
+
varying float vLineDistance;
|
|
793
|
+
|
|
794
|
+
#include <common>
|
|
795
|
+
#include <color_pars_fragment>
|
|
796
|
+
#include <fog_pars_fragment>
|
|
797
|
+
#include <logdepthbuf_pars_fragment>
|
|
798
|
+
#include <clipping_planes_pars_fragment>
|
|
799
|
+
|
|
800
|
+
varying vec2 vUv;
|
|
801
|
+
|
|
802
|
+
void main() {
|
|
803
|
+
|
|
804
|
+
#include <clipping_planes_fragment>
|
|
805
|
+
|
|
806
|
+
#ifdef USE_DASH
|
|
807
|
+
|
|
808
|
+
if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
|
|
809
|
+
|
|
810
|
+
if ( mod( vLineDistance, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
|
|
811
|
+
|
|
812
|
+
#endif
|
|
813
|
+
|
|
814
|
+
if ( abs( vUv.y ) > 1.0 ) {
|
|
815
|
+
|
|
816
|
+
float a = vUv.x;
|
|
817
|
+
float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
|
|
818
|
+
float len2 = a * a + b * b;
|
|
819
|
+
|
|
820
|
+
if ( len2 > 1.0 ) discard;
|
|
821
|
+
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
vec4 diffuseColor = vec4( diffuse, opacity );
|
|
825
|
+
|
|
826
|
+
#include <logdepthbuf_fragment>
|
|
827
|
+
#include <color_fragment>
|
|
828
|
+
|
|
829
|
+
gl_FragColor = vec4( diffuseColor.rgb, diffuseColor.a );
|
|
830
|
+
|
|
831
|
+
#include <tonemapping_fragment>
|
|
832
|
+
#include <fog_fragment>
|
|
833
|
+
#include <premultiplied_alpha_fragment>
|
|
834
|
+
|
|
835
|
+
}
|
|
836
|
+
`,ma={linewidth:{value:1},resolution:{value:new _.Vector2(1,1)},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1},opacity:{value:1}},cs={uniforms:_.UniformsUtils.merge([_.UniformsLib.common,_.UniformsLib.fog,ma]),vertexShader:fa,fragmentShader:pa};class _a extends _.ShaderMaterial{constructor(t){super({uniforms:_.UniformsUtils.clone(cs.uniforms),vertexShader:cs.vertexShader,fragmentShader:cs.fragmentShader,clipping:!0});g(this,"dashed");g(this,"isConditionalLineMaterial",!0);this.dashed=!1,Object.defineProperties(this,{color:{enumerable:!0,get:()=>this.uniforms.diffuse.value,set:n=>{this.uniforms.diffuse.value=new _.Color(n)}},linewidth:{enumerable:!0,get:()=>this.uniforms.linewidth.value,set:n=>{this.uniforms.linewidth.value=n}},dashScale:{enumerable:!0,get:()=>this.uniforms.dashScale.value,set:n=>{this.uniforms.dashScale.value=n}},dashSize:{enumerable:!0,get:()=>this.uniforms.dashSize.value,set:n=>{this.uniforms.dashSize.value=n}},gapSize:{enumerable:!0,get:()=>this.uniforms.gapSize.value,set:n=>{this.uniforms.gapSize.value=n}},opacity:{enumerable:!0,get:()=>this.uniforms.opacity.value,set:n=>{this.uniforms.opacity.value=n}},resolution:{enumerable:!0,get:()=>this.uniforms.resolution.value,set:n=>{this.uniforms.resolution.value.copy(n)}}}),this.setValues(t)}}class Si{constructor(e,t,n,s){g(this,"group");g(this,"loader");g(this,"viewer");g(this,"scene");g(this,"settings");this.group=new _.Group,s?this.group.name=s:this.group.name=aa(),this.viewer=e,this.scene=e.scene,this.loader=t,this.settings=n}async load(){try{const e=this.settings.url;if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid model URL: URL must be a non-empty string");const t=await this.loader.load_gltf(e);if(!t||!t.scene)throw new Error("Invalid GLTF data: no scene found");const n=t.animations;if(this.group=t.scene,this.group.name=e,this.scene.add(this.group),n&&n.length){const s=new _.AnimationMixer(t.scene);for(const i of n)s.clipAction(i).play();this.viewer.register_animation_mixer(s)}return this.settings.color&&this.set_color(this.settings.color),this.settings.visible!==void 0&&this.set_visible(this.settings.visible),(this.settings.position||this.settings.rotation||this.settings.scale!==void 0)&&this.set_transform({position:this.settings.position,rotation:this.settings.rotation,scale:this.settings.scale}),this.settings.conditional_edges&&this.add_conditional_edges(this.settings.conditional_edges.color??0,this.settings.conditional_edges.line_width??1,this.settings.conditional_edges.threshold_angle??1),this.settings.threshold_edges&&this.add_threshold_edges(this.settings.threshold_edges.threshold_angle??60,this.settings.threshold_edges.color??0,this.settings.threshold_edges.line_width??1),this.settings.frame_object&&this.viewer.frame_object(this.group,this.settings.frame_object.fit_offset??1,this.settings.frame_object.height_offset??0),t.scene.traverse(s=>{if(s.isMesh){const i=s;i.castShadow=!0,i.receiveShadow=!0}}),this}catch(e){throw this.scene.remove(this.group),new Error(`Failed to load model: ${e instanceof Error?e.message:e}`)}}add_threshold_edges(e=60,t=0,n=1){this._remove_group_by_user_data("is_threshold_edge");const s=[];this.group.traverse(i=>{if(!i.userData.is_threshold_edge&&!i.userData.is_conditional_edge&&i.isMesh){if(!i.name||i.name.trim()==="")return;const o=this._bake_mesh(i),a=this._generate_threshold_edges(o,e,t,n);a&&s.push({mesh:i,threshold_edges:a})}}),s.forEach(i=>{i.mesh.renderOrder=0,i.threshold_edges.renderOrder=1,i.mesh.add(i.threshold_edges)})}add_conditional_edges(e=0,t=1,n=1){this._remove_group_by_user_data("is_conditional_edge");const s=[];this.group.traverse(i=>{if(i.isMesh){const o=this._bake_mesh(i),a=i,c=this._generate_conditional_thick_edges(o,e,t,n);s.push({mesh:a,conditional_edges:c})}}),s.forEach(i=>{i.mesh.renderOrder=0,i.conditional_edges.renderOrder=1,i.mesh.add(i.conditional_edges)})}set_color(e){this.group.traverse(t=>{if(t.isMesh){const n=t;n.material.color&&n.material.color.set(e)}})}set_visible(e){this.group.visible=e}set_transform(e){e.position&&this.group.position.set(e.position[0],e.position[1],e.position[2]),e.rotation&&this.group.rotation.set(e.rotation[0],e.rotation[1],e.rotation[2]),e.scale!==void 0&&(typeof e.scale=="number"?this.group.scale.set(e.scale,e.scale,e.scale):this.group.scale.set(e.scale[0],e.scale[1],e.scale[2]))}get_transform(){return{position:[this.group.position.x,this.group.position.y,this.group.position.z],rotation:[this.group.rotation.x,this.group.rotation.y,this.group.rotation.z],scale:[this.group.scale.x,this.group.scale.y,this.group.scale.z]}}set_threshold_edge_line_width(e){this.group.traverse(t=>{t.userData.is_threshold_edge&&t.traverse(n=>{if("material"in n){const s=n.material;s&&s.linewidth!==void 0&&(s.linewidth=e)}})})}set_conditional_edge_line_width(e){this.group.traverse(t=>{t.userData.is_conditional_edge&&t.traverse(n=>{if("material"in n){const s=n.material;s&&s.linewidth!==void 0&&(s.linewidth=e)}})})}remove(){this.scene.remove(this.group),this.group.traverse(e=>{var n,s;const t=e.material;t&&((s=(n=this.viewer).unregister_resolution_material)==null||s.call(n,t))}),this._dispose_group(this.group),this._remove_group_by_user_data("is_conditional_edge"),this._remove_group_by_user_data("is_threshold_edge")}_dispose_group(e){e.traverse(t=>{if(t.isMesh){const n=t;n.geometry&&n.geometry.dispose(),Array.isArray(n.material)?n.material.forEach(s=>this._dispose_material(s)):n.material&&this._dispose_material(n.material)}if(t.isLineSegments){const n=t;n.geometry&&n.geometry.dispose(),Array.isArray(n.material)?n.material.forEach(s=>this._dispose_material(s)):n.material&&this._dispose_material(n.material)}})}_remove_group_by_user_data(e){const t=[];this.group.traverse(n=>{n.userData[e]&&n.parent&&t.push(n)}),t.forEach(n=>{n.parent.remove(n),this._dispose_group(n)})}_bake_mesh(e){const t=e.geometry.clone().toNonIndexed();["normal","uv","uv2"].forEach(i=>t.deleteAttribute(i));const n=ca(t);return new _.Mesh(n)}_dispose_material(e){for(const t in e){const n=e[t];n&&n.isTexture&&n.dispose()}e.dispose()}_generate_threshold_edges(e,t,n,s=1){var i,o;if(e.geometry&&e.geometry.attributes&&e.geometry.attributes.position&&e.geometry.attributes.position.count>0){const a=new _.EdgesGeometry(e.geometry,t),c=new is().fromEdgesGeometry(a),l=new gi({color:n,linewidth:s});(o=(i=this.viewer).register_resolution_material)==null||o.call(i,l);const d=new wi(c,l);return d.userData.is_threshold_edge=!0,d}}_generate_conditional_thick_edges(e,t,n=1,s=2){var d,h;const i=new _.Group,o=new Ai(e.geometry,s),a=new ua().from_conditional_edges_geometry(o),c=new _a({color:t,linewidth:n});(h=(d=this.viewer).register_resolution_material)==null||h.call(d,c);const l=new wi(a,c);return i.add(l),i.userData.is_conditional_edge=!0,i}_generate_conditional_thin_edges(e,t,n=2){const s=new _.Group,i=new Ai(e.geometry,n),o=new _.ShaderMaterial(ha);o.uniforms.diffuse.value.set(t);const a=new _.LineSegments(i,o);return s.add(a),s}dispose(){this.remove()}}class ga extends u.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new wa(t)}),this.register(function(t){return new Aa(t)}),this.register(function(t){return new Ia(t)}),this.register(function(t){return new Ea(t)}),this.register(function(t){return new Na(t)}),this.register(function(t){return new Ta(t)}),this.register(function(t){return new Ma(t)}),this.register(function(t){return new La(t)}),this.register(function(t){return new Ca(t)}),this.register(function(t){return new ba(t)}),this.register(function(t){return new Oa(t)}),this.register(function(t){return new Sa(t)}),this.register(function(t){return new Da(t)}),this.register(function(t){return new ka(t)}),this.register(function(t){return new va(t)}),this.register(function(t){return new Pa(t)}),this.register(function(t){return new Ra(t)})}load(e,t,n,s){const i=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const l=u.LoaderUtils.extractUrlBase(e);o=u.LoaderUtils.resolveURL(l,this.path)}else o=u.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(l){s?s(l):console.error(l),i.manager.itemError(e),i.manager.itemEnd(e)},c=new u.FileLoader(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(l){try{i.parse(l,o,function(d){t(d),i.manager.itemEnd(e)},a)}catch(d){a(d)}},n,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,s){let i;const o={},a={},c=new TextDecoder;if(typeof e=="string")i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===Ti){try{o[q.KHR_BINARY_GLTF]=new za(e)}catch(h){s&&s(h);return}i=JSON.parse(o[q.KHR_BINARY_GLTF].content)}else i=JSON.parse(c.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const l=new qa(i,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const h=this.pluginCallbacks[d](l);h.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[h.name]=h,o[h.name]=!0}if(i.extensionsUsed)for(let d=0;d<i.extensionsUsed.length;++d){const h=i.extensionsUsed[d],f=i.extensionsRequired||[];switch(h){case q.KHR_MATERIALS_UNLIT:o[h]=new xa;break;case q.KHR_DRACO_MESH_COMPRESSION:o[h]=new Ua(i,this.dracoLoader);break;case q.KHR_TEXTURE_TRANSFORM:o[h]=new Fa;break;case q.KHR_MESH_QUANTIZATION:o[h]=new ja;break;default:f.indexOf(h)>=0&&a[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}l.setExtensions(o),l.setPlugins(a),l.parse(n,s)}parseAsync(e,t){const n=this;return new Promise(function(s,i){n.parse(e,t,s,i)})}}function ya(){let r={};return{get:function(e){return r[e]},add:function(e,t){r[e]=t},remove:function(e){delete r[e]},removeAll:function(){r={}}}}const q={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class va{constructor(e){this.parser=e,this.name=q.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,s=t.length;n<s;n++){const i=t[n];i.extensions&&i.extensions[this.name]&&i.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,i.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let s=t.cache.get(n);if(s)return s;const i=t.json,c=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e];let l;const d=new u.Color(16777215);c.color!==void 0&&d.setRGB(c.color[0],c.color[1],c.color[2],u.LinearSRGBColorSpace);const h=c.range!==void 0?c.range:0;switch(c.type){case"directional":l=new u.DirectionalLight(d),l.target.position.set(0,0,-1),l.add(l.target);break;case"point":l=new u.PointLight(d),l.distance=h;break;case"spot":l=new u.SpotLight(d),l.distance=h,c.spot=c.spot||{},c.spot.innerConeAngle=c.spot.innerConeAngle!==void 0?c.spot.innerConeAngle:0,c.spot.outerConeAngle=c.spot.outerConeAngle!==void 0?c.spot.outerConeAngle:Math.PI/4,l.angle=c.spot.outerConeAngle,l.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,l.target.position.set(0,0,-1),l.add(l.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return l.position.set(0,0,0),He(l,c),c.intensity!==void 0&&(l.intensity=c.intensity),l.name=t.createUniqueName(c.name||"light_"+e),s=Promise.resolve(l),t.cache.add(n,s),s}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,i=n.json.nodes[e],a=(i.extensions&&i.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(c){return n._getNodeRef(t.cache,a,c)})}}class xa{constructor(){this.name=q.KHR_MATERIALS_UNLIT}getMaterialType(){return u.MeshBasicMaterial}extendParams(e,t,n){const s=[];e.color=new u.Color(1,1,1),e.opacity=1;const i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){const o=i.baseColorFactor;e.color.setRGB(o[0],o[1],o[2],u.LinearSRGBColorSpace),e.opacity=o[3]}i.baseColorTexture!==void 0&&s.push(n.assignTexture(e,"map",i.baseColorTexture,u.SRGBColorSpace))}return Promise.all(s)}}class ba{constructor(e){this.parser=e,this.name=q.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=s.extensions[this.name].emissiveStrength;return i!==void 0&&(t.emissiveIntensity=i),Promise.resolve()}}class wa{constructor(e){this.parser=e,this.name=q.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],o=s.extensions[this.name];if(o.clearcoatFactor!==void 0&&(t.clearcoat=o.clearcoatFactor),o.clearcoatTexture!==void 0&&i.push(n.assignTexture(t,"clearcoatMap",o.clearcoatTexture)),o.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=o.clearcoatRoughnessFactor),o.clearcoatRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"clearcoatRoughnessMap",o.clearcoatRoughnessTexture)),o.clearcoatNormalTexture!==void 0&&(i.push(n.assignTexture(t,"clearcoatNormalMap",o.clearcoatNormalTexture)),o.clearcoatNormalTexture.scale!==void 0)){const a=o.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new u.Vector2(a,a)}return Promise.all(i)}}class Aa{constructor(e){this.parser=e,this.name=q.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=s.extensions[this.name];return t.dispersion=i.dispersion!==void 0?i.dispersion:0,Promise.resolve()}}class Sa{constructor(e){this.parser=e,this.name=q.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],o=s.extensions[this.name];return o.iridescenceFactor!==void 0&&(t.iridescence=o.iridescenceFactor),o.iridescenceTexture!==void 0&&i.push(n.assignTexture(t,"iridescenceMap",o.iridescenceTexture)),o.iridescenceIor!==void 0&&(t.iridescenceIOR=o.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),o.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=o.iridescenceThicknessMinimum),o.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=o.iridescenceThicknessMaximum),o.iridescenceThicknessTexture!==void 0&&i.push(n.assignTexture(t,"iridescenceThicknessMap",o.iridescenceThicknessTexture)),Promise.all(i)}}class Ta{constructor(e){this.parser=e,this.name=q.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[];t.sheenColor=new u.Color(0,0,0),t.sheenRoughness=0,t.sheen=1;const o=s.extensions[this.name];if(o.sheenColorFactor!==void 0){const a=o.sheenColorFactor;t.sheenColor.setRGB(a[0],a[1],a[2],u.LinearSRGBColorSpace)}return o.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=o.sheenRoughnessFactor),o.sheenColorTexture!==void 0&&i.push(n.assignTexture(t,"sheenColorMap",o.sheenColorTexture,u.SRGBColorSpace)),o.sheenRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"sheenRoughnessMap",o.sheenRoughnessTexture)),Promise.all(i)}}class Ma{constructor(e){this.parser=e,this.name=q.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],o=s.extensions[this.name];return o.transmissionFactor!==void 0&&(t.transmission=o.transmissionFactor),o.transmissionTexture!==void 0&&i.push(n.assignTexture(t,"transmissionMap",o.transmissionTexture)),Promise.all(i)}}class La{constructor(e){this.parser=e,this.name=q.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],o=s.extensions[this.name];t.thickness=o.thicknessFactor!==void 0?o.thicknessFactor:0,o.thicknessTexture!==void 0&&i.push(n.assignTexture(t,"thicknessMap",o.thicknessTexture)),t.attenuationDistance=o.attenuationDistance||1/0;const a=o.attenuationColor||[1,1,1];return t.attenuationColor=new u.Color().setRGB(a[0],a[1],a[2],u.LinearSRGBColorSpace),Promise.all(i)}}class Ca{constructor(e){this.parser=e,this.name=q.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=s.extensions[this.name];return t.ior=i.ior!==void 0?i.ior:1.5,Promise.resolve()}}class Oa{constructor(e){this.parser=e,this.name=q.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],o=s.extensions[this.name];t.specularIntensity=o.specularFactor!==void 0?o.specularFactor:1,o.specularTexture!==void 0&&i.push(n.assignTexture(t,"specularIntensityMap",o.specularTexture));const a=o.specularColorFactor||[1,1,1];return t.specularColor=new u.Color().setRGB(a[0],a[1],a[2],u.LinearSRGBColorSpace),o.specularColorTexture!==void 0&&i.push(n.assignTexture(t,"specularColorMap",o.specularColorTexture,u.SRGBColorSpace)),Promise.all(i)}}class ka{constructor(e){this.parser=e,this.name=q.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],o=s.extensions[this.name];return t.bumpScale=o.bumpFactor!==void 0?o.bumpFactor:1,o.bumpTexture!==void 0&&i.push(n.assignTexture(t,"bumpMap",o.bumpTexture)),Promise.all(i)}}class Da{constructor(e){this.parser=e,this.name=q.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],o=s.extensions[this.name];return o.anisotropyStrength!==void 0&&(t.anisotropy=o.anisotropyStrength),o.anisotropyRotation!==void 0&&(t.anisotropyRotation=o.anisotropyRotation),o.anisotropyTexture!==void 0&&i.push(n.assignTexture(t,"anisotropyMap",o.anisotropyTexture)),Promise.all(i)}}class Ia{constructor(e){this.parser=e,this.name=q.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,s=n.textures[e];if(!s.extensions||!s.extensions[this.name])return null;const i=s.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,i.source,o)}}class Ea{constructor(e){this.parser=e,this.name=q.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const t=this.name,n=this.parser,s=n.json,i=s.textures[e];if(!i.extensions||!i.extensions[t])return null;const o=i.extensions[t],a=s.images[o.source];let c=n.textureLoader;if(a.uri){const l=n.options.manager.getHandler(a.uri);l!==null&&(c=l)}return this.detectSupport().then(function(l){if(l)return n.loadTextureImage(e,o.source,c);if(s.extensionsRequired&&s.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class Na{constructor(e){this.parser=e,this.name=q.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const t=this.name,n=this.parser,s=n.json,i=s.textures[e];if(!i.extensions||!i.extensions[t])return null;const o=i.extensions[t],a=s.images[o.source];let c=n.textureLoader;if(a.uri){const l=n.options.manager.getHandler(a.uri);l!==null&&(c=l)}return this.detectSupport().then(function(l){if(l)return n.loadTextureImage(e,o.source,c);if(s.extensionsRequired&&s.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class Pa{constructor(e){this.name=q.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const s=n.extensions[this.name],i=this.parser.getDependency("buffer",s.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return i.then(function(a){const c=s.byteOffset||0,l=s.byteLength||0,d=s.count,h=s.byteStride,f=new Uint8Array(a,c,l);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(d,h,f,s.mode,s.filter).then(function(m){return m.buffer}):o.ready.then(function(){const m=new ArrayBuffer(d*h);return o.decodeGltfBuffer(new Uint8Array(m),d,h,f,s.mode,s.filter),m})})}else return null}}class Ra{constructor(e){this.name=q.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const s=t.meshes[n.mesh];for(const l of s.primitives)if(l.mode!==Ee.TRIANGLES&&l.mode!==Ee.TRIANGLE_STRIP&&l.mode!==Ee.TRIANGLE_FAN&&l.mode!==void 0)return null;const o=n.extensions[this.name].attributes,a=[],c={};for(const l in o)a.push(this.parser.getDependency("accessor",o[l]).then(d=>(c[l]=d,c[l])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(l=>{const d=l.pop(),h=d.isGroup?d.children:[d],f=l[0].count,m=[];for(const y of h){const v=new u.Matrix4,b=new u.Vector3,w=new u.Quaternion,T=new u.Vector3(1,1,1),M=new u.InstancedMesh(y.geometry,y.material,f);for(let x=0;x<f;x++)c.TRANSLATION&&b.fromBufferAttribute(c.TRANSLATION,x),c.ROTATION&&w.fromBufferAttribute(c.ROTATION,x),c.SCALE&&T.fromBufferAttribute(c.SCALE,x),M.setMatrixAt(x,v.compose(b,w,T));for(const x in c)if(x==="_COLOR_0"){const z=c[x];M.instanceColor=new u.InstancedBufferAttribute(z.array,z.itemSize,z.normalized)}else x!=="TRANSLATION"&&x!=="ROTATION"&&x!=="SCALE"&&y.geometry.setAttribute(x,c[x]);u.Object3D.prototype.copy.call(M,y),this.parser.assignFinalMaterial(M),m.push(M)}return d.isGroup?(d.clear(),d.add(...m),d):m[0]}))}}const Ti="glTF",tn=12,Mi={JSON:1313821514,BIN:5130562};class za{constructor(e){this.name=q.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,tn),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Ti)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-tn,i=new DataView(e,tn);let o=0;for(;o<s;){const a=i.getUint32(o,!0);o+=4;const c=i.getUint32(o,!0);if(o+=4,c===Mi.JSON){const l=new Uint8Array(e,tn+o,a);this.content=n.decode(l)}else if(c===Mi.BIN){const l=tn+o;this.body=e.slice(l,l+a)}o+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Ua{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=q.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,s=this.dracoLoader,i=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,a={},c={},l={};for(const d in o){const h=ds[d]||d.toLowerCase();a[h]=o[d]}for(const d in e.attributes){const h=ds[d]||d.toLowerCase();if(o[d]!==void 0){const f=n.accessors[e.attributes[d]],m=Lt[f.componentType];l[h]=m.name,c[h]=f.normalized===!0}}return t.getDependency("bufferView",i).then(function(d){return new Promise(function(h,f){s.decodeDracoFile(d,function(m){for(const y in m.attributes){const v=m.attributes[y],b=c[y];b!==void 0&&(v.normalized=b)}h(m)},a,l,u.LinearSRGBColorSpace,f)})})}}class Fa{constructor(){this.name=q.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class ja{constructor(){this.name=q.KHR_MESH_QUANTIZATION}}class Li extends u.Interpolant{constructor(e,t,n,s){super(e,t,n,s)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,s=this.valueSize,i=e*s*3+s;for(let o=0;o!==s;o++)t[o]=n[i+o];return t}interpolate_(e,t,n,s){const i=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=a*2,l=a*3,d=s-t,h=(n-t)/d,f=h*h,m=f*h,y=e*l,v=y-l,b=-2*m+3*f,w=m-f,T=1-b,M=w-f+h;for(let x=0;x!==a;x++){const z=o[v+x+a],Z=o[v+x+c]*d,j=o[y+x+a],k=o[y+x]*d;i[x]=T*z+M*Z+b*j+w*k}return i}}const Ba=new u.Quaternion;class Va extends Li{interpolate_(e,t,n,s){const i=super.interpolate_(e,t,n,s);return Ba.fromArray(i).normalize().toArray(i),i}}const Ee={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Lt={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Ci={9728:u.NearestFilter,9729:u.LinearFilter,9984:u.NearestMipmapNearestFilter,9985:u.LinearMipmapNearestFilter,9986:u.NearestMipmapLinearFilter,9987:u.LinearMipmapLinearFilter},Oi={33071:u.ClampToEdgeWrapping,33648:u.MirroredRepeatWrapping,10497:u.RepeatWrapping},ls={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},ds={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},at={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Ga={CUBICSPLINE:void 0,LINEAR:u.InterpolateLinear,STEP:u.InterpolateDiscrete},us={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function Za(r){return r.DefaultMaterial===void 0&&(r.DefaultMaterial=new u.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:u.FrontSide})),r.DefaultMaterial}function pt(r,e,t){for(const n in t.extensions)r[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function He(r,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(r.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function Wa(r,e,t){let n=!1,s=!1,i=!1;for(let l=0,d=e.length;l<d;l++){const h=e[l];if(h.POSITION!==void 0&&(n=!0),h.NORMAL!==void 0&&(s=!0),h.COLOR_0!==void 0&&(i=!0),n&&s&&i)break}if(!n&&!s&&!i)return Promise.resolve(r);const o=[],a=[],c=[];for(let l=0,d=e.length;l<d;l++){const h=e[l];if(n){const f=h.POSITION!==void 0?t.getDependency("accessor",h.POSITION):r.attributes.position;o.push(f)}if(s){const f=h.NORMAL!==void 0?t.getDependency("accessor",h.NORMAL):r.attributes.normal;a.push(f)}if(i){const f=h.COLOR_0!==void 0?t.getDependency("accessor",h.COLOR_0):r.attributes.color;c.push(f)}}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c)]).then(function(l){const d=l[0],h=l[1],f=l[2];return n&&(r.morphAttributes.position=d),s&&(r.morphAttributes.normal=h),i&&(r.morphAttributes.color=f),r.morphTargetsRelative=!0,r})}function Xa(r,e){if(r.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)r.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(r.morphTargetInfluences.length===t.length){r.morphTargetDictionary={};for(let n=0,s=t.length;n<s;n++)r.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function $a(r){let e;const t=r.extensions&&r.extensions[q.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+hs(t.attributes):e=r.indices+":"+hs(r.attributes)+":"+r.mode,r.targets!==void 0)for(let n=0,s=r.targets.length;n<s;n++)e+=":"+hs(r.targets[n]);return e}function hs(r){let e="";const t=Object.keys(r).sort();for(let n=0,s=t.length;n<s;n++)e+=t[n]+":"+r[t[n]]+";";return e}function fs(r){switch(r){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function Ka(r){return r.search(/\.jpe?g($|\?)/i)>0||r.search(/^data\:image\/jpeg/)===0?"image/jpeg":r.search(/\.webp($|\?)/i)>0||r.search(/^data\:image\/webp/)===0?"image/webp":r.search(/\.ktx2($|\?)/i)>0||r.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const Ya=new u.Matrix4;class qa{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new ya,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,s=-1,i=!1,o=-1;if(typeof navigator<"u"){const a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;const c=a.match(/Version\/(\d+)/);s=n&&c?parseInt(c[1],10):-1,i=a.indexOf("Firefox")>-1,o=i?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&s<17||i&&o<98?this.textureLoader=new u.TextureLoader(this.options.manager):this.textureLoader=new u.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new u.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,s=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){const a={scene:o[0][s.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:s.asset,parser:n,userData:{}};return pt(i,a,s),He(a,s),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(a)})).then(function(){for(const c of a.scenes)c.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let s=0,i=t.length;s<i;s++){const o=t[s].joints;for(let a=0,c=o.length;a<c;a++)e[o[a]].isBone=!0}for(let s=0,i=e.length;s<i;s++){const o=e[s];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(n[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const s=n.clone(),i=(o,a)=>{const c=this.associations.get(o);c!=null&&this.associations.set(a,c);for(const[l,d]of o.children.entries())i(d,a.children[l])};return i(n,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const s=e(t[n]);if(s)return s}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let s=0;s<t.length;s++){const i=e(t[s]);i&&n.push(i)}return n}getDependency(e,t){const n=e+":"+t;let s=this.cache.get(n);if(!s){switch(e){case"scene":s=this.loadScene(t);break;case"node":s=this._invokeOne(function(i){return i.loadNode&&i.loadNode(t)});break;case"mesh":s=this._invokeOne(function(i){return i.loadMesh&&i.loadMesh(t)});break;case"accessor":s=this.loadAccessor(t);break;case"bufferView":s=this._invokeOne(function(i){return i.loadBufferView&&i.loadBufferView(t)});break;case"buffer":s=this.loadBuffer(t);break;case"material":s=this._invokeOne(function(i){return i.loadMaterial&&i.loadMaterial(t)});break;case"texture":s=this._invokeOne(function(i){return i.loadTexture&&i.loadTexture(t)});break;case"skin":s=this.loadSkin(t);break;case"animation":s=this._invokeOne(function(i){return i.loadAnimation&&i.loadAnimation(t)});break;case"camera":s=this.loadCamera(t);break;default:if(s=this._invokeOne(function(i){return i!=this&&i.getDependency&&i.getDependency(e,t)}),!s)throw new Error("Unknown type: "+e);break}this.cache.add(n,s)}return s}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,s=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(s.map(function(i,o){return n.getDependency(e,o)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[q.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(i,o){n.load(u.LoaderUtils.resolveURL(t.uri,s.path),i,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const s=t.byteLength||0,i=t.byteOffset||0;return n.slice(i,i+s)})}loadAccessor(e){const t=this,n=this.json,s=this.json.accessors[e];if(s.bufferView===void 0&&s.sparse===void 0){const o=ls[s.type],a=Lt[s.componentType],c=s.normalized===!0,l=new a(s.count*o);return Promise.resolve(new u.BufferAttribute(l,o,c))}const i=[];return s.bufferView!==void 0?i.push(this.getDependency("bufferView",s.bufferView)):i.push(null),s.sparse!==void 0&&(i.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),i.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(i).then(function(o){const a=o[0],c=ls[s.type],l=Lt[s.componentType],d=l.BYTES_PER_ELEMENT,h=d*c,f=s.byteOffset||0,m=s.bufferView!==void 0?n.bufferViews[s.bufferView].byteStride:void 0,y=s.normalized===!0;let v,b;if(m&&m!==h){const w=Math.floor(f/m),T="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+w+":"+s.count;let M=t.cache.get(T);M||(v=new l(a,w*m,s.count*m/d),M=new u.InterleavedBuffer(v,m/d),t.cache.add(T,M)),b=new u.InterleavedBufferAttribute(M,c,f%m/d,y)}else a===null?v=new l(s.count*c):v=new l(a,f,s.count*c),b=new u.BufferAttribute(v,c,y);if(s.sparse!==void 0){const w=ls.SCALAR,T=Lt[s.sparse.indices.componentType],M=s.sparse.indices.byteOffset||0,x=s.sparse.values.byteOffset||0,z=new T(o[1],M,s.sparse.count*w),Z=new l(o[2],x,s.sparse.count*c);a!==null&&(b=new u.BufferAttribute(b.array.slice(),b.itemSize,b.normalized)),b.normalized=!1;for(let j=0,k=z.length;j<k;j++){const C=z[j];if(b.setX(C,Z[j*c]),c>=2&&b.setY(C,Z[j*c+1]),c>=3&&b.setZ(C,Z[j*c+2]),c>=4&&b.setW(C,Z[j*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}b.normalized=y}return b})}loadTexture(e){const t=this.json,n=this.options,i=t.textures[e].source,o=t.images[i];let a=this.textureLoader;if(o.uri){const c=n.manager.getHandler(o.uri);c!==null&&(a=c)}return this.loadTextureImage(e,i,a)}loadTextureImage(e,t,n){const s=this,i=this.json,o=i.textures[e],a=i.images[t],c=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[c])return this.textureCache[c];const l=this.loadImageSource(t,n).then(function(d){d.flipY=!1,d.name=o.name||a.name||"",d.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(d.name=a.uri);const f=(i.samplers||{})[o.sampler]||{};return d.magFilter=Ci[f.magFilter]||u.LinearFilter,d.minFilter=Ci[f.minFilter]||u.LinearMipmapLinearFilter,d.wrapS=Oi[f.wrapS]||u.RepeatWrapping,d.wrapT=Oi[f.wrapT]||u.RepeatWrapping,d.generateMipmaps=!d.isCompressedTexture&&d.minFilter!==u.NearestFilter&&d.minFilter!==u.LinearFilter,s.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[c]=l,l}loadImageSource(e,t){const n=this,s=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());const o=s.images[e],a=self.URL||self.webkitURL;let c=o.uri||"",l=!1;if(o.bufferView!==void 0)c=n.getDependency("bufferView",o.bufferView).then(function(h){l=!0;const f=new Blob([h],{type:o.mimeType});return c=a.createObjectURL(f),c});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const d=Promise.resolve(c).then(function(h){return new Promise(function(f,m){let y=f;t.isImageBitmapLoader===!0&&(y=function(v){const b=new u.Texture(v);b.needsUpdate=!0,f(b)}),t.load(u.LoaderUtils.resolveURL(h,i.path),y,void 0,m)})}).then(function(h){return l===!0&&a.revokeObjectURL(c),He(h,o),h.userData.mimeType=o.mimeType||Ka(o.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),h});return this.sourceCache[e]=d,d}assignTexture(e,t,n,s){const i=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),i.extensions[q.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[q.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const c=i.associations.get(o);o=i.extensions[q.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),i.associations.set(o,c)}}return s!==void 0&&(o.colorSpace=s),e[t]=o,o})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const s=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+n.uuid;let c=this.cache.get(a);c||(c=new u.PointsMaterial,u.Material.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(a,c)),n=c}else if(e.isLine){const a="LineBasicMaterial:"+n.uuid;let c=this.cache.get(a);c||(c=new u.LineBasicMaterial,u.Material.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(a,c)),n=c}if(s||i||o){let a="ClonedMaterial:"+n.uuid+":";s&&(a+="derivative-tangents:"),i&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let c=this.cache.get(a);c||(c=n.clone(),i&&(c.vertexColors=!0),o&&(c.flatShading=!0),s&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(a,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return u.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,s=this.extensions,i=n.materials[e];let o;const a={},c=i.extensions||{},l=[];if(c[q.KHR_MATERIALS_UNLIT]){const h=s[q.KHR_MATERIALS_UNLIT];o=h.getMaterialType(),l.push(h.extendParams(a,i,t))}else{const h=i.pbrMetallicRoughness||{};if(a.color=new u.Color(1,1,1),a.opacity=1,Array.isArray(h.baseColorFactor)){const f=h.baseColorFactor;a.color.setRGB(f[0],f[1],f[2],u.LinearSRGBColorSpace),a.opacity=f[3]}h.baseColorTexture!==void 0&&l.push(t.assignTexture(a,"map",h.baseColorTexture,u.SRGBColorSpace)),a.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,a.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(l.push(t.assignTexture(a,"metalnessMap",h.metallicRoughnessTexture)),l.push(t.assignTexture(a,"roughnessMap",h.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),l.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,a)})))}i.doubleSided===!0&&(a.side=u.DoubleSide);const d=i.alphaMode||us.OPAQUE;if(d===us.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,d===us.MASK&&(a.alphaTest=i.alphaCutoff!==void 0?i.alphaCutoff:.5)),i.normalTexture!==void 0&&o!==u.MeshBasicMaterial&&(l.push(t.assignTexture(a,"normalMap",i.normalTexture)),a.normalScale=new u.Vector2(1,1),i.normalTexture.scale!==void 0)){const h=i.normalTexture.scale;a.normalScale.set(h,h)}if(i.occlusionTexture!==void 0&&o!==u.MeshBasicMaterial&&(l.push(t.assignTexture(a,"aoMap",i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&o!==u.MeshBasicMaterial){const h=i.emissiveFactor;a.emissive=new u.Color().setRGB(h[0],h[1],h[2],u.LinearSRGBColorSpace)}return i.emissiveTexture!==void 0&&o!==u.MeshBasicMaterial&&l.push(t.assignTexture(a,"emissiveMap",i.emissiveTexture,u.SRGBColorSpace)),Promise.all(l).then(function(){const h=new o(a);return i.name&&(h.name=i.name),He(h,i),t.associations.set(h,{materials:e}),i.extensions&&pt(s,h,i),h})}createUniqueName(e){const t=u.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,s=this.primitiveCache;function i(a){return n[q.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(c){return ki(c,a,t)})}const o=[];for(let a=0,c=e.length;a<c;a++){const l=e[a],d=$a(l),h=s[d];if(h)o.push(h.promise);else{let f;l.extensions&&l.extensions[q.KHR_DRACO_MESH_COMPRESSION]?f=i(l):f=ki(new u.BufferGeometry,l,t),s[d]={primitive:l,promise:f},o.push(f)}}return Promise.all(o)}loadMesh(e){const t=this,n=this.json,s=this.extensions,i=n.meshes[e],o=i.primitives,a=[];for(let c=0,l=o.length;c<l;c++){const d=o[c].material===void 0?Za(this.cache):this.getDependency("material",o[c].material);a.push(d)}return a.push(t.loadGeometries(o)),Promise.all(a).then(function(c){const l=c.slice(0,c.length-1),d=c[c.length-1],h=[];for(let m=0,y=d.length;m<y;m++){const v=d[m],b=o[m];let w;const T=l[m];if(b.mode===Ee.TRIANGLES||b.mode===Ee.TRIANGLE_STRIP||b.mode===Ee.TRIANGLE_FAN||b.mode===void 0)w=i.isSkinnedMesh===!0?new u.SkinnedMesh(v,T):new u.Mesh(v,T),w.isSkinnedMesh===!0&&w.normalizeSkinWeights(),b.mode===Ee.TRIANGLE_STRIP?w.geometry=mi(w.geometry,u.TriangleStripDrawMode):b.mode===Ee.TRIANGLE_FAN&&(w.geometry=mi(w.geometry,u.TriangleFanDrawMode));else if(b.mode===Ee.LINES)w=new u.LineSegments(v,T);else if(b.mode===Ee.LINE_STRIP)w=new u.Line(v,T);else if(b.mode===Ee.LINE_LOOP)w=new u.LineLoop(v,T);else if(b.mode===Ee.POINTS)w=new u.Points(v,T);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+b.mode);Object.keys(w.geometry.morphAttributes).length>0&&Xa(w,i),w.name=t.createUniqueName(i.name||"mesh_"+e),He(w,i),b.extensions&&pt(s,w,b),t.assignFinalMaterial(w),h.push(w)}for(let m=0,y=h.length;m<y;m++)t.associations.set(h[m],{meshes:e,primitives:m});if(h.length===1)return i.extensions&&pt(s,h[0],i),h[0];const f=new u.Group;i.extensions&&pt(s,f,i),t.associations.set(f,{meshes:e});for(let m=0,y=h.length;m<y;m++)f.add(h[m]);return f})}loadCamera(e){let t;const n=this.json.cameras[e],s=n[n.type];if(!s){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new u.PerspectiveCamera(u.MathUtils.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):n.type==="orthographic"&&(t=new u.OrthographicCamera(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),He(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let s=0,i=t.joints.length;s<i;s++)n.push(this._loadNodeShallow(t.joints[s]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(s){const i=s.pop(),o=s,a=[],c=[];for(let l=0,d=o.length;l<d;l++){const h=o[l];if(h){a.push(h);const f=new u.Matrix4;i!==null&&f.fromArray(i.array,l*16),c.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[l])}return new u.Skeleton(a,c)})}loadAnimation(e){const t=this.json,n=this,s=t.animations[e],i=s.name?s.name:"animation_"+e,o=[],a=[],c=[],l=[],d=[];for(let h=0,f=s.channels.length;h<f;h++){const m=s.channels[h],y=s.samplers[m.sampler],v=m.target,b=v.node,w=s.parameters!==void 0?s.parameters[y.input]:y.input,T=s.parameters!==void 0?s.parameters[y.output]:y.output;v.node!==void 0&&(o.push(this.getDependency("node",b)),a.push(this.getDependency("accessor",w)),c.push(this.getDependency("accessor",T)),l.push(y),d.push(v))}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c),Promise.all(l),Promise.all(d)]).then(function(h){const f=h[0],m=h[1],y=h[2],v=h[3],b=h[4],w=[];for(let T=0,M=f.length;T<M;T++){const x=f[T],z=m[T],Z=y[T],j=v[T],k=b[T];if(x===void 0)continue;x.updateMatrix&&x.updateMatrix();const C=n._createAnimationTracks(x,z,Z,j,k);if(C)for(let I=0;I<C.length;I++)w.push(C[I])}return new u.AnimationClip(i,void 0,w)})}createNodeMesh(e){const t=this.json,n=this,s=t.nodes[e];return s.mesh===void 0?null:n.getDependency("mesh",s.mesh).then(function(i){const o=n._getNodeRef(n.meshCache,s.mesh,i);return s.weights!==void 0&&o.traverse(function(a){if(a.isMesh)for(let c=0,l=s.weights.length;c<l;c++)a.morphTargetInfluences[c]=s.weights[c]}),o})}loadNode(e){const t=this.json,n=this,s=t.nodes[e],i=n._loadNodeShallow(e),o=[],a=s.children||[];for(let l=0,d=a.length;l<d;l++)o.push(n.getDependency("node",a[l]));const c=s.skin===void 0?Promise.resolve(null):n.getDependency("skin",s.skin);return Promise.all([i,Promise.all(o),c]).then(function(l){const d=l[0],h=l[1],f=l[2];f!==null&&d.traverse(function(m){m.isSkinnedMesh&&m.bind(f,Ya)});for(let m=0,y=h.length;m<y;m++)d.add(h[m]);return d})}_loadNodeShallow(e){const t=this.json,n=this.extensions,s=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const i=t.nodes[e],o=i.name?s.createUniqueName(i.name):"",a=[],c=s._invokeOne(function(l){return l.createNodeMesh&&l.createNodeMesh(e)});return c&&a.push(c),i.camera!==void 0&&a.push(s.getDependency("camera",i.camera).then(function(l){return s._getNodeRef(s.cameraCache,i.camera,l)})),s._invokeAll(function(l){return l.createNodeAttachment&&l.createNodeAttachment(e)}).forEach(function(l){a.push(l)}),this.nodeCache[e]=Promise.all(a).then(function(l){let d;if(i.isBone===!0?d=new u.Bone:l.length>1?d=new u.Group:l.length===1?d=l[0]:d=new u.Object3D,d!==l[0])for(let h=0,f=l.length;h<f;h++)d.add(l[h]);if(i.name&&(d.userData.name=i.name,d.name=o),He(d,i),i.extensions&&pt(n,d,i),i.matrix!==void 0){const h=new u.Matrix4;h.fromArray(i.matrix),d.applyMatrix4(h)}else i.translation!==void 0&&d.position.fromArray(i.translation),i.rotation!==void 0&&d.quaternion.fromArray(i.rotation),i.scale!==void 0&&d.scale.fromArray(i.scale);return s.associations.has(d)||s.associations.set(d,{}),s.associations.get(d).nodes=e,d}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],s=this,i=new u.Group;n.name&&(i.name=s.createUniqueName(n.name)),He(i,n),n.extensions&&pt(t,i,n);const o=n.nodes||[],a=[];for(let c=0,l=o.length;c<l;c++)a.push(s.getDependency("node",o[c]));return Promise.all(a).then(function(c){for(let d=0,h=c.length;d<h;d++)i.add(c[d]);const l=d=>{const h=new Map;for(const[f,m]of s.associations)(f instanceof u.Material||f instanceof u.Texture)&&h.set(f,m);return d.traverse(f=>{const m=s.associations.get(f);m!=null&&h.set(f,m)}),h};return s.associations=l(i),i})}_createAnimationTracks(e,t,n,s,i){const o=[],a=e.name?e.name:e.uuid,c=[];at[i.path]===at.weights?e.traverse(function(f){f.morphTargetInfluences&&c.push(f.name?f.name:f.uuid)}):c.push(a);let l;switch(at[i.path]){case at.weights:l=u.NumberKeyframeTrack;break;case at.rotation:l=u.QuaternionKeyframeTrack;break;case at.translation:case at.scale:l=u.VectorKeyframeTrack;break;default:switch(n.itemSize){case 1:l=u.NumberKeyframeTrack;break;case 2:case 3:default:l=u.VectorKeyframeTrack;break}break}const d=s.interpolation!==void 0?Ga[s.interpolation]:u.InterpolateLinear,h=this._getArrayFromAccessor(n);for(let f=0,m=c.length;f<m;f++){const y=new l(c[f]+"."+at[i.path],t.array,h,d);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(y),o.push(y)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=fs(t.constructor),s=new Float32Array(t.length);for(let i=0,o=t.length;i<o;i++)s[i]=t[i]*n;t=s}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const s=this instanceof u.QuaternionKeyframeTrack?Va:Li;return new s(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Ha(r,e,t){const n=e.attributes,s=new u.Box3;if(n.POSITION!==void 0){const a=t.json.accessors[n.POSITION],c=a.min,l=a.max;if(c!==void 0&&l!==void 0){if(s.set(new u.Vector3(c[0],c[1],c[2]),new u.Vector3(l[0],l[1],l[2])),a.normalized){const d=fs(Lt[a.componentType]);s.min.multiplyScalar(d),s.max.multiplyScalar(d)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const i=e.targets;if(i!==void 0){const a=new u.Vector3,c=new u.Vector3;for(let l=0,d=i.length;l<d;l++){const h=i[l];if(h.POSITION!==void 0){const f=t.json.accessors[h.POSITION],m=f.min,y=f.max;if(m!==void 0&&y!==void 0){if(c.setX(Math.max(Math.abs(m[0]),Math.abs(y[0]))),c.setY(Math.max(Math.abs(m[1]),Math.abs(y[1]))),c.setZ(Math.max(Math.abs(m[2]),Math.abs(y[2]))),f.normalized){const v=fs(Lt[f.componentType]);c.multiplyScalar(v)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(a)}r.boundingBox=s;const o=new u.Sphere;s.getCenter(o.center),o.radius=s.min.distanceTo(s.max)/2,r.boundingSphere=o}function ki(r,e,t){const n=e.attributes,s=[];function i(o,a){return t.getDependency("accessor",o).then(function(c){r.setAttribute(a,c)})}for(const o in n){const a=ds[o]||o.toLowerCase();a in r.attributes||s.push(i(n[o],a))}if(e.indices!==void 0&&!r.index){const o=t.getDependency("accessor",e.indices).then(function(a){r.setIndex(a)});s.push(o)}return u.ColorManagement.workingColorSpace!==u.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${u.ColorManagement.workingColorSpace}" not supported.`),He(r,e),Ha(r,e,t),Promise.all(s).then(function(){return e.targets!==void 0?Wa(r,e.targets,t):r})}const ps=new WeakMap;class Ja extends u.Loader{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,n,s){const i=new u.FileLoader(this.manager);i.setPath(this.path),i.setResponseType("arraybuffer"),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,o=>{this.parse(o,t,s)},n,s)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,u.SRGBColorSpace,n).catch(n)}decodeDracoFile(e,t,n,s,i=u.LinearSRGBColorSpace,o=()=>{}){const a={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:i};return this.decodeGeometry(e,a).then(t).catch(o)}decodeGeometry(e,t){const n=JSON.stringify(t);if(ps.has(e)){const c=ps.get(e);if(c.key===n)return c.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let s;const i=this.workerNextTaskID++,o=e.byteLength,a=this._getWorker(i,o).then(c=>(s=c,new Promise((l,d)=>{s._callbacks[i]={resolve:l,reject:d},s.postMessage({type:"decode",id:i,taskConfig:t,buffer:e},[e])}))).then(c=>this._createGeometry(c.geometry));return a.catch(()=>!0).then(()=>{s&&i&&this._releaseTask(s,i)}),ps.set(e,{key:n,promise:a}),a}_createGeometry(e){const t=new u.BufferGeometry;e.index&&t.setIndex(new u.BufferAttribute(e.index.array,1));for(let n=0;n<e.attributes.length;n++){const s=e.attributes[n],i=s.name,o=s.array,a=s.itemSize,c=new u.BufferAttribute(o,a);i==="color"&&(this._assignVertexColorSpace(c,s.vertexColorSpace),c.normalized=!(o instanceof Float32Array)),t.setAttribute(i,c)}return t}_assignVertexColorSpace(e,t){if(t!==u.SRGBColorSpace)return;const n=new u.Color;for(let s=0,i=e.count;s<i;s++)n.fromBufferAttribute(e,s),u.ColorManagement.toWorkingColorSpace(n,u.SRGBColorSpace),e.setXYZ(s,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new u.FileLoader(this.manager);return n.setPath(this.decoderPath),n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise((s,i)=>{n.load(e,s,void 0,i)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(n=>{const s=n[0];e||(this.decoderConfig.wasmBinary=n[1]);const i=Qa.toString(),o=["/* draco decoder */",s,"","/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join(`
|
|
837
|
+
`);this.workerSourceURL=URL.createObjectURL(new Blob([o]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const s=new Worker(this.workerSourceURL);s._callbacks={},s._taskCosts={},s._taskLoad=0,s.postMessage({type:"init",decoderConfig:this.decoderConfig}),s.onmessage=function(i){const o=i.data;switch(o.type){case"decode":s._callbacks[o.id].resolve(o);break;case"error":s._callbacks[o.id].reject(o);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+o.type+'"')}},this.workerPool.push(s)}else this.workerPool.sort(function(s,i){return s._taskLoad>i._taskLoad?-1:1});const n=this.workerPool[this.workerPool.length-1];return n._taskCosts[e]=t,n._taskLoad+=t,n})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this.workerSourceURL!==""&&URL.revokeObjectURL(this.workerSourceURL),this}}function Qa(){let r,e;onmessage=function(o){const a=o.data;switch(a.type){case"init":r=a.decoderConfig,e=new Promise(function(d){r.onModuleLoaded=function(h){d({draco:h})},DracoDecoderModule(r)});break;case"decode":const c=a.buffer,l=a.taskConfig;e.then(d=>{const h=d.draco,f=new h.Decoder;try{const m=t(h,f,new Int8Array(c),l),y=m.attributes.map(v=>v.array.buffer);m.index&&y.push(m.index.array.buffer),self.postMessage({type:"decode",id:a.id,geometry:m},y)}catch(m){console.error(m),self.postMessage({type:"error",id:a.id,error:m.message})}finally{h.destroy(f)}});break}};function t(o,a,c,l){const d=l.attributeIDs,h=l.attributeTypes;let f,m;const y=a.GetEncodedGeometryType(c);if(y===o.TRIANGULAR_MESH)f=new o.Mesh,m=a.DecodeArrayToMesh(c,c.byteLength,f);else if(y===o.POINT_CLOUD)f=new o.PointCloud,m=a.DecodeArrayToPointCloud(c,c.byteLength,f);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!m.ok()||f.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+m.error_msg());const v={index:null,attributes:[]};for(const b in d){const w=self[h[b]];let T,M;if(l.useUniqueIDs)M=d[b],T=a.GetAttributeByUniqueId(f,M);else{if(M=a.GetAttributeId(f,o[d[b]]),M===-1)continue;T=a.GetAttribute(f,M)}const x=s(o,a,f,b,w,T);b==="color"&&(x.vertexColorSpace=l.vertexColorSpace),v.attributes.push(x)}return y===o.TRIANGULAR_MESH&&(v.index=n(o,a,f)),o.destroy(f),v}function n(o,a,c){const d=c.num_faces()*3,h=d*4,f=o._malloc(h);a.GetTrianglesUInt32Array(c,h,f);const m=new Uint32Array(o.HEAPF32.buffer,f,d).slice();return o._free(f),{array:m,itemSize:1}}function s(o,a,c,l,d,h){const f=h.num_components(),y=c.num_points()*f,v=y*d.BYTES_PER_ELEMENT,b=i(o,d),w=o._malloc(v);a.GetAttributeDataArrayForAllPoints(c,h,b,v,w);const T=new d(o.HEAPF32.buffer,w,y).slice();return o._free(w),{name:l,array:T,itemSize:f}}function i(o,a){switch(a){case Float32Array:return o.DT_FLOAT32;case Int8Array:return o.DT_INT8;case Int16Array:return o.DT_INT16;case Int32Array:return o.DT_INT32;case Uint8Array:return o.DT_UINT8;case Uint16Array:return o.DT_UINT16;case Uint32Array:return o.DT_UINT32}}}class ec{constructor(e){g(this,"gltf_loader");e||(e="/examples/jsm/libs/draco/gltf/");const t=new Ja;e&&t.setDecoderPath(e),this.gltf_loader=new ga,this.gltf_loader.setDRACOLoader(t)}load_gltf(e){return new Promise((t,n)=>{this.gltf_loader.load(e,s=>{t(s)},void 0,s=>{n(new ve(`Failed to load model from ${e}`,"ModelLoader",Le.MODEL_LOAD_FAILED,{url:e,error:s}))})})}}class Di extends EventTarget{constructor(t,n){super();g(this,"ready");g(this,"models",new Map);g(this,"loader");g(this,"viewer");g(this,"settings");this.viewer=t,this.loader=new ec,this.settings=n,this.settings.addEventListener("update",s=>{const i=s.detail;i.models&&this.update_models(i.models)}),this.ready=this.init()}async init(){G.info("Initializing ModelManager...");const t=this.settings.get("models");G.info("Loading models:",t),await this.update_models(t)}async update_models(t){try{const n=new Set(t.map(i=>i.url)),s=new Set(this.models.keys());for(const i of s)n.has(i)||this.remove_model(i);for(const i of t)this.models.has(i.url)?this.update_model(this.models.get(i.url),i):await this.load_model(i)}catch(n){throw G.error("Error updating models:",n),new Error(`Failed to update models: ${n instanceof Error?n.message:n}`)}}async load_model(t){try{this.dispatchEvent(new CustomEvent("loading",{detail:{url:t.url}}));const n=new Si(this.viewer,this.loader,t);await n.load(),this.models.set(t.url,n),this.dispatchEvent(new CustomEvent("loaded",{detail:{url:t.url,model:n}})),this.dispatchEvent(new CustomEvent("modeladded",{detail:{url:t.url,model:n}}))}catch(n){throw G.error(`Failed to load model from ${t.url}:`,n),new Error(`Failed to load model from ${t.url}: ${n instanceof Error?n.message:n}`)}}update_model(t,n){n.visible!==void 0&&t.set_visible(n.visible),(n.position||n.rotation||n.scale!==void 0)&&t.set_transform({position:n.position,rotation:n.rotation,scale:n.scale}),n.color&&t.set_color(n.color),n.conditional_edges&&t.add_conditional_edges(n.conditional_edges.color??0,n.conditional_edges.line_width??1,n.conditional_edges.threshold_angle??1),n.threshold_edges&&t.add_threshold_edges(n.threshold_edges.threshold_angle??60,n.threshold_edges.color??0,n.threshold_edges.line_width??1),this.dispatchEvent(new CustomEvent("modelupdated",{detail:{url:n.url,model:t}}))}remove_model(t){const n=this.models.get(t);n&&(n.remove(),this.models.delete(t),this.dispatchEvent(new CustomEvent("modelremoved",{detail:{url:t}})))}dispose(){for(const t of this.models.values())try{t&&typeof t.remove=="function"&&t.remove()}catch(n){G.error("Error disposing model:",n)}this.models.clear()}}class tc extends EventTarget{constructor(t,n){super();g(this,"settings");g(this,"viewer");g(this,"environment");g(this,"sun");g(this,"model_manager");this.settings=Mn.use(n),this.viewer=new di(t,this.settings),this.environment=new ui(this.viewer,this.settings),this.model_manager=new Di(this.viewer,this.settings),this.sun=new fi(this.viewer,this.settings,this.environment,this.model_manager),this.settings.addEventListener("update",s=>{const i=s.detail;this.environment.update(i.environment)})}async initialize(){try{await this.environment.ready,await this.model_manager.ready,this.sun.update(),this.dispatchEvent(new CustomEvent("ready",{detail:{}}))}catch(t){const n=new ve(`Failed to initialize Glimmer: ${t instanceof Error?t.message:t}`,"Glimmer",Le.INITIALIZATION_FAILED,{error:t});throw this.dispatchEvent(new CustomEvent("error",{detail:{error:n}})),n}}dispose(){var t,n,s,i;(t=this.sun)==null||t.dispose(),(n=this.environment)==null||n.dispose(),(s=this.model_manager)==null||s.dispose(),(i=this.viewer)==null||i.dispose(),this.dispatchEvent(new CustomEvent("dispose",{detail:{}}))}}const nc=S.object({type:S.enum(["2d","3d"]),position:S.tuple([S.number(),S.number(),S.number()]),content:S.string(),style:S.record(S.string()).optional(),anchor:S.object({model_url:S.string(),local_position:S.tuple([S.number(),S.number(),S.number()])}).optional()}),sc=S.object({min:S.object({x:S.number(),y:S.number(),z:S.number()}),max:S.object({x:S.number(),y:S.number(),z:S.number()})}),In=S.object({id:S.string(),title:S.string().optional(),description:S.string().optional(),settings:Sn.partial(),camera:S.object({position:S.tuple([S.number(),S.number(),S.number()]),target:S.tuple([S.number(),S.number(),S.number()])}),annotations:S.array(nc).optional(),section_box:sc.optional(),section_box_enabled:S.boolean().optional().default(!1)}),ic=S.object({duration:S.number().default(1e3),easing:S.string().default("linear")}),En=S.object({version:S.string().default("1.0.0"),title:S.string(),description:S.string().optional(),slides:S.array(In).min(1,"Story must have at least one slide"),transition:ic.optional()});/*! @license DOMPurify 3.3.0 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.0/LICENSE */const{entries:Ii,setPrototypeOf:Ei,isFrozen:rc,getPrototypeOf:oc,getOwnPropertyDescriptor:ac}=Object;let{freeze:we,seal:Ne,create:ms}=Object,{apply:_s,construct:gs}=typeof Reflect<"u"&&Reflect;we||(we=function(e){return e}),Ne||(Ne=function(e){return e}),_s||(_s=function(e,t){for(var n=arguments.length,s=new Array(n>2?n-2:0),i=2;i<n;i++)s[i-2]=arguments[i];return e.apply(t,s)}),gs||(gs=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return new e(...n)});const Nn=Se(Array.prototype.forEach),cc=Se(Array.prototype.lastIndexOf),Ni=Se(Array.prototype.pop),nn=Se(Array.prototype.push),lc=Se(Array.prototype.splice),Pn=Se(String.prototype.toLowerCase),ys=Se(String.prototype.toString),vs=Se(String.prototype.match),sn=Se(String.prototype.replace),dc=Se(String.prototype.indexOf),uc=Se(String.prototype.trim),Ue=Se(Object.prototype.hasOwnProperty),Ae=Se(RegExp.prototype.test),rn=hc(TypeError);function Se(r){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return _s(r,e,n)}}function hc(r){return function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return gs(r,t)}}function H(r,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Pn;Ei&&Ei(r,null);let n=e.length;for(;n--;){let s=e[n];if(typeof s=="string"){const i=t(s);i!==s&&(rc(e)||(e[n]=i),s=i)}r[s]=!0}return r}function fc(r){for(let e=0;e<r.length;e++)Ue(r,e)||(r[e]=null);return r}function Je(r){const e=ms(null);for(const[t,n]of Ii(r))Ue(r,t)&&(Array.isArray(n)?e[t]=fc(n):n&&typeof n=="object"&&n.constructor===Object?e[t]=Je(n):e[t]=n);return e}function on(r,e){for(;r!==null;){const n=ac(r,e);if(n){if(n.get)return Se(n.get);if(typeof n.value=="function")return Se(n.value)}r=oc(r)}function t(){return null}return t}const Pi=we(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),xs=we(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),bs=we(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),pc=we(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),ws=we(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),mc=we(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Ri=we(["#text"]),zi=we(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),As=we(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Ui=we(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Rn=we(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),_c=Ne(/\{\{[\w\W]*|[\w\W]*\}\}/gm),gc=Ne(/<%[\w\W]*|[\w\W]*%>/gm),yc=Ne(/\$\{[\w\W]*/gm),vc=Ne(/^data-[\-\w.\u00B7-\uFFFF]+$/),xc=Ne(/^aria-[\-\w]+$/),Fi=Ne(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),bc=Ne(/^(?:\w+script|data):/i),wc=Ne(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ji=Ne(/^html$/i),Ac=Ne(/^[a-z][.\w]*(-[.\w]+)+$/i);var Bi=Object.freeze({__proto__:null,ARIA_ATTR:xc,ATTR_WHITESPACE:wc,CUSTOM_ELEMENT:Ac,DATA_ATTR:vc,DOCTYPE_NAME:ji,ERB_EXPR:gc,IS_ALLOWED_URI:Fi,IS_SCRIPT_OR_DATA:bc,MUSTACHE_EXPR:_c,TMPLIT_EXPR:yc});const an={element:1,text:3,progressingInstruction:7,comment:8,document:9},Sc=function(){return typeof window>"u"?null:window},Tc=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null;const s="data-tt-policy-suffix";t&&t.hasAttribute(s)&&(n=t.getAttribute(s));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},Vi=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Gi(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Sc();const e=F=>Gi(F);if(e.version="3.3.0",e.removed=[],!r||!r.document||r.document.nodeType!==an.document||!r.Element)return e.isSupported=!1,e;let{document:t}=r;const n=t,s=n.currentScript,{DocumentFragment:i,HTMLTemplateElement:o,Node:a,Element:c,NodeFilter:l,NamedNodeMap:d=r.NamedNodeMap||r.MozNamedAttrMap,HTMLFormElement:h,DOMParser:f,trustedTypes:m}=r,y=c.prototype,v=on(y,"cloneNode"),b=on(y,"remove"),w=on(y,"nextSibling"),T=on(y,"childNodes"),M=on(y,"parentNode");if(typeof o=="function"){const F=t.createElement("template");F.content&&F.content.ownerDocument&&(t=F.content.ownerDocument)}let x,z="";const{implementation:Z,createNodeIterator:j,createDocumentFragment:k,getElementsByTagName:C}=t,{importNode:I}=n;let R=Vi();e.isSupported=typeof Ii=="function"&&typeof M=="function"&&Z&&Z.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:W,ERB_EXPR:$,TMPLIT_EXPR:E,DATA_ATTR:ee,ARIA_ATTR:Y,IS_SCRIPT_OR_DATA:Te,ATTR_WHITESPACE:de,CUSTOM_ELEMENT:Fe}=Bi;let{IS_ALLOWED_URI:Ce}=Bi,se=null;const _e=H({},[...Pi,...xs,...bs,...ws,...Ri]);let Q=null;const ct=H({},[...zi,...As,...Ui,...Rn]);let U=Object.seal(ms(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Oe=null,Dt=null;const Qe=Object.seal(ms(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Ps=!0,Rs=!0,ir=!1,rr=!0,It=!1,Vn=!0,gt=!1,zs=!1,Us=!1,Et=!1,Gn=!1,Zn=!1,or=!0,ar=!1;const ol="user-content-";let Fs=!0,pn=!1,Nt={},Pt=null;const cr=H({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let lr=null;const dr=H({},["audio","video","img","source","image","track"]);let js=null;const ur=H({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Wn="http://www.w3.org/1998/Math/MathML",Xn="http://www.w3.org/2000/svg",et="http://www.w3.org/1999/xhtml";let Rt=et,Bs=!1,Vs=null;const al=H({},[Wn,Xn,et],ys);let $n=H({},["mi","mo","mn","ms","mtext"]),Kn=H({},["annotation-xml"]);const cl=H({},["title","style","font","a","script"]);let mn=null;const ll=["application/xhtml+xml","text/html"],dl="text/html";let ue=null,zt=null;const ul=t.createElement("form"),hr=function(p){return p instanceof RegExp||p instanceof Function},Gs=function(){let p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(zt&&zt===p)){if((!p||typeof p!="object")&&(p={}),p=Je(p),mn=ll.indexOf(p.PARSER_MEDIA_TYPE)===-1?dl:p.PARSER_MEDIA_TYPE,ue=mn==="application/xhtml+xml"?ys:Pn,se=Ue(p,"ALLOWED_TAGS")?H({},p.ALLOWED_TAGS,ue):_e,Q=Ue(p,"ALLOWED_ATTR")?H({},p.ALLOWED_ATTR,ue):ct,Vs=Ue(p,"ALLOWED_NAMESPACES")?H({},p.ALLOWED_NAMESPACES,ys):al,js=Ue(p,"ADD_URI_SAFE_ATTR")?H(Je(ur),p.ADD_URI_SAFE_ATTR,ue):ur,lr=Ue(p,"ADD_DATA_URI_TAGS")?H(Je(dr),p.ADD_DATA_URI_TAGS,ue):dr,Pt=Ue(p,"FORBID_CONTENTS")?H({},p.FORBID_CONTENTS,ue):cr,Oe=Ue(p,"FORBID_TAGS")?H({},p.FORBID_TAGS,ue):Je({}),Dt=Ue(p,"FORBID_ATTR")?H({},p.FORBID_ATTR,ue):Je({}),Nt=Ue(p,"USE_PROFILES")?p.USE_PROFILES:!1,Ps=p.ALLOW_ARIA_ATTR!==!1,Rs=p.ALLOW_DATA_ATTR!==!1,ir=p.ALLOW_UNKNOWN_PROTOCOLS||!1,rr=p.ALLOW_SELF_CLOSE_IN_ATTR!==!1,It=p.SAFE_FOR_TEMPLATES||!1,Vn=p.SAFE_FOR_XML!==!1,gt=p.WHOLE_DOCUMENT||!1,Et=p.RETURN_DOM||!1,Gn=p.RETURN_DOM_FRAGMENT||!1,Zn=p.RETURN_TRUSTED_TYPE||!1,Us=p.FORCE_BODY||!1,or=p.SANITIZE_DOM!==!1,ar=p.SANITIZE_NAMED_PROPS||!1,Fs=p.KEEP_CONTENT!==!1,pn=p.IN_PLACE||!1,Ce=p.ALLOWED_URI_REGEXP||Fi,Rt=p.NAMESPACE||et,$n=p.MATHML_TEXT_INTEGRATION_POINTS||$n,Kn=p.HTML_INTEGRATION_POINTS||Kn,U=p.CUSTOM_ELEMENT_HANDLING||{},p.CUSTOM_ELEMENT_HANDLING&&hr(p.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(U.tagNameCheck=p.CUSTOM_ELEMENT_HANDLING.tagNameCheck),p.CUSTOM_ELEMENT_HANDLING&&hr(p.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(U.attributeNameCheck=p.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),p.CUSTOM_ELEMENT_HANDLING&&typeof p.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(U.allowCustomizedBuiltInElements=p.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),It&&(Rs=!1),Gn&&(Et=!0),Nt&&(se=H({},Ri),Q=[],Nt.html===!0&&(H(se,Pi),H(Q,zi)),Nt.svg===!0&&(H(se,xs),H(Q,As),H(Q,Rn)),Nt.svgFilters===!0&&(H(se,bs),H(Q,As),H(Q,Rn)),Nt.mathMl===!0&&(H(se,ws),H(Q,Ui),H(Q,Rn))),p.ADD_TAGS&&(typeof p.ADD_TAGS=="function"?Qe.tagCheck=p.ADD_TAGS:(se===_e&&(se=Je(se)),H(se,p.ADD_TAGS,ue))),p.ADD_ATTR&&(typeof p.ADD_ATTR=="function"?Qe.attributeCheck=p.ADD_ATTR:(Q===ct&&(Q=Je(Q)),H(Q,p.ADD_ATTR,ue))),p.ADD_URI_SAFE_ATTR&&H(js,p.ADD_URI_SAFE_ATTR,ue),p.FORBID_CONTENTS&&(Pt===cr&&(Pt=Je(Pt)),H(Pt,p.FORBID_CONTENTS,ue)),Fs&&(se["#text"]=!0),gt&&H(se,["html","head","body"]),se.table&&(H(se,["tbody"]),delete Oe.tbody),p.TRUSTED_TYPES_POLICY){if(typeof p.TRUSTED_TYPES_POLICY.createHTML!="function")throw rn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof p.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw rn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');x=p.TRUSTED_TYPES_POLICY,z=x.createHTML("")}else x===void 0&&(x=Tc(m,s)),x!==null&&typeof z=="string"&&(z=x.createHTML(""));we&&we(p),zt=p}},fr=H({},[...xs,...bs,...pc]),pr=H({},[...ws,...mc]),hl=function(p){let L=M(p);(!L||!L.tagName)&&(L={namespaceURI:Rt,tagName:"template"});const N=Pn(p.tagName),ie=Pn(L.tagName);return Vs[p.namespaceURI]?p.namespaceURI===Xn?L.namespaceURI===et?N==="svg":L.namespaceURI===Wn?N==="svg"&&(ie==="annotation-xml"||$n[ie]):!!fr[N]:p.namespaceURI===Wn?L.namespaceURI===et?N==="math":L.namespaceURI===Xn?N==="math"&&Kn[ie]:!!pr[N]:p.namespaceURI===et?L.namespaceURI===Xn&&!Kn[ie]||L.namespaceURI===Wn&&!$n[ie]?!1:!pr[N]&&(cl[N]||!fr[N]):!!(mn==="application/xhtml+xml"&&Vs[p.namespaceURI]):!1},$e=function(p){nn(e.removed,{element:p});try{M(p).removeChild(p)}catch{b(p)}},yt=function(p,L){try{nn(e.removed,{attribute:L.getAttributeNode(p),from:L})}catch{nn(e.removed,{attribute:null,from:L})}if(L.removeAttribute(p),p==="is")if(Et||Gn)try{$e(L)}catch{}else try{L.setAttribute(p,"")}catch{}},mr=function(p){let L=null,N=null;if(Us)p="<remove></remove>"+p;else{const ce=vs(p,/^[\r\n\t ]+/);N=ce&&ce[0]}mn==="application/xhtml+xml"&&Rt===et&&(p='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+p+"</body></html>");const ie=x?x.createHTML(p):p;if(Rt===et)try{L=new f().parseFromString(ie,mn)}catch{}if(!L||!L.documentElement){L=Z.createDocument(Rt,"template",null);try{L.documentElement.innerHTML=Bs?z:ie}catch{}}const xe=L.body||L.documentElement;return p&&N&&xe.insertBefore(t.createTextNode(N),xe.childNodes[0]||null),Rt===et?C.call(L,gt?"html":"body")[0]:gt?L.documentElement:xe},_r=function(p){return j.call(p.ownerDocument||p,p,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Zs=function(p){return p instanceof h&&(typeof p.nodeName!="string"||typeof p.textContent!="string"||typeof p.removeChild!="function"||!(p.attributes instanceof d)||typeof p.removeAttribute!="function"||typeof p.setAttribute!="function"||typeof p.namespaceURI!="string"||typeof p.insertBefore!="function"||typeof p.hasChildNodes!="function")},gr=function(p){return typeof a=="function"&&p instanceof a};function tt(F,p,L){Nn(F,N=>{N.call(e,p,L,zt)})}const yr=function(p){let L=null;if(tt(R.beforeSanitizeElements,p,null),Zs(p))return $e(p),!0;const N=ue(p.nodeName);if(tt(R.uponSanitizeElement,p,{tagName:N,allowedTags:se}),Vn&&p.hasChildNodes()&&!gr(p.firstElementChild)&&Ae(/<[/\w!]/g,p.innerHTML)&&Ae(/<[/\w!]/g,p.textContent)||p.nodeType===an.progressingInstruction||Vn&&p.nodeType===an.comment&&Ae(/<[/\w]/g,p.data))return $e(p),!0;if(!(Qe.tagCheck instanceof Function&&Qe.tagCheck(N))&&(!se[N]||Oe[N])){if(!Oe[N]&&xr(N)&&(U.tagNameCheck instanceof RegExp&&Ae(U.tagNameCheck,N)||U.tagNameCheck instanceof Function&&U.tagNameCheck(N)))return!1;if(Fs&&!Pt[N]){const ie=M(p)||p.parentNode,xe=T(p)||p.childNodes;if(xe&&ie){const ce=xe.length;for(let ke=ce-1;ke>=0;--ke){const nt=v(xe[ke],!0);nt.__removalCount=(p.__removalCount||0)+1,ie.insertBefore(nt,w(p))}}}return $e(p),!0}return p instanceof c&&!hl(p)||(N==="noscript"||N==="noembed"||N==="noframes")&&Ae(/<\/no(script|embed|frames)/i,p.innerHTML)?($e(p),!0):(It&&p.nodeType===an.text&&(L=p.textContent,Nn([W,$,E],ie=>{L=sn(L,ie," ")}),p.textContent!==L&&(nn(e.removed,{element:p.cloneNode()}),p.textContent=L)),tt(R.afterSanitizeElements,p,null),!1)},vr=function(p,L,N){if(or&&(L==="id"||L==="name")&&(N in t||N in ul))return!1;if(!(Rs&&!Dt[L]&&Ae(ee,L))){if(!(Ps&&Ae(Y,L))){if(!(Qe.attributeCheck instanceof Function&&Qe.attributeCheck(L,p))){if(!Q[L]||Dt[L]){if(!(xr(p)&&(U.tagNameCheck instanceof RegExp&&Ae(U.tagNameCheck,p)||U.tagNameCheck instanceof Function&&U.tagNameCheck(p))&&(U.attributeNameCheck instanceof RegExp&&Ae(U.attributeNameCheck,L)||U.attributeNameCheck instanceof Function&&U.attributeNameCheck(L,p))||L==="is"&&U.allowCustomizedBuiltInElements&&(U.tagNameCheck instanceof RegExp&&Ae(U.tagNameCheck,N)||U.tagNameCheck instanceof Function&&U.tagNameCheck(N))))return!1}else if(!js[L]){if(!Ae(Ce,sn(N,de,""))){if(!((L==="src"||L==="xlink:href"||L==="href")&&p!=="script"&&dc(N,"data:")===0&&lr[p])){if(!(ir&&!Ae(Te,sn(N,de,"")))){if(N)return!1}}}}}}}return!0},xr=function(p){return p!=="annotation-xml"&&vs(p,Fe)},br=function(p){tt(R.beforeSanitizeAttributes,p,null);const{attributes:L}=p;if(!L||Zs(p))return;const N={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Q,forceKeepAttr:void 0};let ie=L.length;for(;ie--;){const xe=L[ie],{name:ce,namespaceURI:ke,value:nt}=xe,Ut=ue(ce),Ws=nt;let ge=ce==="value"?Ws:uc(Ws);if(N.attrName=Ut,N.attrValue=ge,N.keepAttr=!0,N.forceKeepAttr=void 0,tt(R.uponSanitizeAttribute,p,N),ge=N.attrValue,ar&&(Ut==="id"||Ut==="name")&&(yt(ce,p),ge=ol+ge),Vn&&Ae(/((--!?|])>)|<\/(style|title|textarea)/i,ge)){yt(ce,p);continue}if(Ut==="attributename"&&vs(ge,"href")){yt(ce,p);continue}if(N.forceKeepAttr)continue;if(!N.keepAttr){yt(ce,p);continue}if(!rr&&Ae(/\/>/i,ge)){yt(ce,p);continue}It&&Nn([W,$,E],Ar=>{ge=sn(ge,Ar," ")});const wr=ue(p.nodeName);if(!vr(wr,Ut,ge)){yt(ce,p);continue}if(x&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!ke)switch(m.getAttributeType(wr,Ut)){case"TrustedHTML":{ge=x.createHTML(ge);break}case"TrustedScriptURL":{ge=x.createScriptURL(ge);break}}if(ge!==Ws)try{ke?p.setAttributeNS(ke,ce,ge):p.setAttribute(ce,ge),Zs(p)?$e(p):Ni(e.removed)}catch{yt(ce,p)}}tt(R.afterSanitizeAttributes,p,null)},fl=function F(p){let L=null;const N=_r(p);for(tt(R.beforeSanitizeShadowDOM,p,null);L=N.nextNode();)tt(R.uponSanitizeShadowNode,L,null),yr(L),br(L),L.content instanceof i&&F(L.content);tt(R.afterSanitizeShadowDOM,p,null)};return e.sanitize=function(F){let p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},L=null,N=null,ie=null,xe=null;if(Bs=!F,Bs&&(F="<!-->"),typeof F!="string"&&!gr(F))if(typeof F.toString=="function"){if(F=F.toString(),typeof F!="string")throw rn("dirty is not a string, aborting")}else throw rn("toString is not a function");if(!e.isSupported)return F;if(zs||Gs(p),e.removed=[],typeof F=="string"&&(pn=!1),pn){if(F.nodeName){const nt=ue(F.nodeName);if(!se[nt]||Oe[nt])throw rn("root node is forbidden and cannot be sanitized in-place")}}else if(F instanceof a)L=mr("<!---->"),N=L.ownerDocument.importNode(F,!0),N.nodeType===an.element&&N.nodeName==="BODY"||N.nodeName==="HTML"?L=N:L.appendChild(N);else{if(!Et&&!It&&!gt&&F.indexOf("<")===-1)return x&&Zn?x.createHTML(F):F;if(L=mr(F),!L)return Et?null:Zn?z:""}L&&Us&&$e(L.firstChild);const ce=_r(pn?F:L);for(;ie=ce.nextNode();)yr(ie),br(ie),ie.content instanceof i&&fl(ie.content);if(pn)return F;if(Et){if(Gn)for(xe=k.call(L.ownerDocument);L.firstChild;)xe.appendChild(L.firstChild);else xe=L;return(Q.shadowroot||Q.shadowrootmode)&&(xe=I.call(n,xe,!0)),xe}let ke=gt?L.outerHTML:L.innerHTML;return gt&&se["!doctype"]&&L.ownerDocument&&L.ownerDocument.doctype&&L.ownerDocument.doctype.name&&Ae(ji,L.ownerDocument.doctype.name)&&(ke="<!DOCTYPE "+L.ownerDocument.doctype.name+`>
|
|
838
|
+
`+ke),It&&Nn([W,$,E],nt=>{ke=sn(ke,nt," ")}),x&&Zn?x.createHTML(ke):ke},e.setConfig=function(){let F=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Gs(F),zs=!0},e.clearConfig=function(){zt=null,zs=!1},e.isValidAttribute=function(F,p,L){zt||Gs({});const N=ue(F),ie=ue(p);return vr(N,ie,L)},e.addHook=function(F,p){typeof p=="function"&&nn(R[F],p)},e.removeHook=function(F,p){if(p!==void 0){const L=cc(R[F],p);return L===-1?void 0:lc(R[F],L,1)[0]}return Ni(R[F])},e.removeHooks=function(F){R[F]=[]},e.removeAllHooks=function(){R=Vi()},e}var Mc=Gi();class Lc{constructor(e){g(this,"container");g(this,"elements",[]);this.container=e.container}render(e){const t=document.createElement("div");t.className="glimmer-annotation-2d",t.innerHTML=Mc.sanitize(e.content),t.style.position="absolute",t.style.pointerEvents="auto",t.style.left=`${e.position[0]}%`,t.style.top=`${e.position[1]}%`,t.style.transform="translate(-50%, -50%)",e.style&&Object.assign(t.style,e.style),this.container.appendChild(t),this.elements.push(t)}clear(){this.container.innerHTML="",this.elements=[]}dispose(){this.clear()}}class Cc{constructor(e){g(this,"group");g(this,"sprites",[]);this.group=new _.Group,this.group.name=e.group_name??"story-annotations",e.scene.add(this.group)}render(e){const t=document.createElement("canvas"),n=t.getContext("2d");if(!n)return;t.width=512,t.height=128,n.fillStyle="rgba(0, 0, 0, 0.7)",n.fillRect(0,0,t.width,t.height),n.font="32px Inter, -apple-system, BlinkMacSystemFont, Arial, sans-serif",n.fillStyle="white",n.textAlign="center",n.textBaseline="middle",n.fillText(e.content,t.width/2,t.height/2);const s=new _.CanvasTexture(t),i=new _.SpriteMaterial({map:s}),o=new _.Sprite(i);o.position.set(...e.position),o.scale.set(4,1,1),this.group.add(o),this.sprites.push(o)}clear(){for(;this.group.children.length>0;){const e=this.group.children[0];if(this.group.remove(e),e.isSprite){const t=e;t.material.dispose(),t.material.map&&t.material.map.dispose()}}this.sprites=[]}dispose(){this.clear(),this.group.parent&&this.group.parent.remove(this.group)}get_group(){return this.group}}class Oc{constructor(){g(this,"triggers",new Map);g(this,"handlers",new Map)}register(e,t,n){this.triggers.has(e)||this.triggers.set(e,new Set),this.triggers.get(e).add(t),this.handlers.set(t,n),this._bind(t,n),G.info(`Registered ${e} trigger:`,t)}unregister(e){const t=this.handlers.get(e);if(t){this._unbind(e,t),this.handlers.delete(e);for(const[,n]of this.triggers.entries())n.delete(e)}}unregister_type(e){const t=this.triggers.get(e);if(t){for(const n of t){const s=this.handlers.get(n);s&&(this._unbind(n,s),this.handlers.delete(n))}this.triggers.delete(e)}}dispose(){for(const[e,t]of this.handlers.entries())this._unbind(e,t);this.handlers.clear(),this.triggers.clear()}get_triggers(e){return this.triggers.get(e)||new Set}_bind(e,t){typeof e=="string"?window.addEventListener(e,t):e.addEventListener("click",t)}_unbind(e,t){typeof e=="string"?window.removeEventListener(e,t):e.removeEventListener("click",t)}}class kc extends EventTarget{constructor(t,n){super();g(this,"camera");g(this,"controls");this.camera=t,this.controls=n}set_camera(t){this.camera.position.set(...t.position),this.controls.target.set(...t.target),this.controls.update()}transition_to_slide(t){this.dispatchEvent(new CustomEvent("transitionstart",{detail:{slide:t}})),this.set_camera(t.camera),this.dispatchEvent(new CustomEvent("transitionend",{detail:{slide:t}}))}}class Zi{constructor(e,t){g(this,"mesh");g(this,"axis");g(this,"side");this.axis=e,this.side=t,this.mesh=this.create_gizmo()}create_gizmo(){const e=new _.ConeGeometry(.15,.4,8),t=new _.MeshBasicMaterial({color:this.get_axis_color(),transparent:!0,opacity:.8,depthTest:!1,depthWrite:!1}),n=new _.Mesh(e,t);return n.renderOrder=999,n}get_axis_color(){switch(this.axis){case"x":return 16711680;case"y":return 65280;case"z":return 255}}update_from_bounds(e){const t=new _.Vector3;e.getCenter(t);const n=new _.Vector3;this.axis==="x"?(n.x=this.side==="min"?e.min.x:e.max.x,n.y=t.y,n.z=t.z):this.axis==="y"?(n.x=t.x,n.y=this.side==="min"?e.min.y:e.max.y,n.z=t.z):(n.x=t.x,n.y=t.y,n.z=this.side==="min"?e.min.z:e.max.z),this.mesh.position.copy(n);const s=this.get_normal();this.mesh.quaternion.setFromUnitVectors(new _.Vector3(0,1,0),s)}get_normal(){const e=this.side==="min"?-1:1;return this.axis==="x"?new _.Vector3(e,0,0):this.axis==="y"?new _.Vector3(0,e,0):new _.Vector3(0,0,e)}project_delta(e){return e[this.axis]}set_hover(e){const t=this.mesh.material;t.opacity=e?1:.8}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}}class Wi extends EventTarget{constructor(t){super();g(this,"bounds");g(this,"box_helper");g(this,"plane_handles",[]);g(this,"edit_mode",!1);g(this,"active_handle");g(this,"drag_start_value",0);g(this,"drag_start_mouse",new _.Vector2);g(this,"orbit_controls");g(this,"event_listeners",[]);t instanceof _.Box3?this.bounds=t.clone():t?this.bounds=new _.Box3(new _.Vector3(t.min.x,t.min.y,t.min.z),new _.Vector3(t.max.x,t.max.y,t.max.z)):this.bounds=new _.Box3}fit_to_model(t){this.bounds.setFromObject(t),this.update_helpers(),this.emit_bounds_changed()}fit_to_objects(t){this.bounds.makeEmpty(),t.forEach(n=>{this.bounds.expandByObject(n)}),this.update_helpers(),this.emit_bounds_changed()}finalize(t){return this.exit_edit_mode(t),this.get_bounds()}enter_edit_mode(t,n,s,i){if(this.edit_mode){console.warn("Already in edit mode");return}this.edit_mode=!0,this.orbit_controls=i,this.box_helper=new _.Box3Helper(this.bounds,16739179),t.add(this.box_helper),[["x","min"],["x","max"],["y","min"],["y","max"],["z","min"],["z","max"]].forEach(([a,c])=>{const l=new Zi(a,c);l.update_from_bounds(this.bounds),this.plane_handles.push(l),t.add(l.mesh)}),this.setup_interactions(n,s)}exit_edit_mode(t){this.edit_mode&&(this.edit_mode=!1,this.box_helper&&(t.remove(this.box_helper),this.box_helper=void 0),this.plane_handles.forEach(n=>{t.remove(n.mesh),n.dispose()}),this.plane_handles=[],this.event_listeners.forEach(({element:n,type:s,handler:i})=>{n.removeEventListener(s,i)}),this.event_listeners=[])}get_bounds(){return{min:{x:this.bounds.min.x,y:this.bounds.min.y,z:this.bounds.min.z},max:{x:this.bounds.max.x,y:this.bounds.max.y,z:this.bounds.max.z}}}set_bounds(t){this.bounds.min.set(t.min.x,t.min.y,t.min.z),this.bounds.max.set(t.max.x,t.max.y,t.max.z),this.update_helpers(),this.emit_bounds_changed()}get_box3(){return this.bounds.clone()}get is_editing(){return this.edit_mode}setup_interactions(t,n){const s=new _.Raycaster,i=new _.Vector2,o=l=>{if(!this.edit_mode)return;const d=n.getBoundingClientRect();i.x=(l.clientX-d.left)/d.width*2-1,i.y=-((l.clientY-d.top)/d.height)*2+1,s.setFromCamera(i,t);const h=this.plane_handles.map(m=>m.mesh),f=s.intersectObjects(h);if(f.length>0&&(this.active_handle=this.plane_handles.find(m=>m.mesh===f[0].object),this.active_handle)){const m=this.active_handle.axis,y=this.active_handle.side;this.drag_start_value=this.bounds[y][m],this.drag_start_mouse.copy(i),n.style.cursor="grabbing",this.orbit_controls&&(this.orbit_controls.enabled=!1)}},a=l=>{if(!this.edit_mode)return;const d=n.getBoundingClientRect();if(i.x=(l.clientX-d.left)/d.width*2-1,i.y=-((l.clientY-d.top)/d.height)*2+1,this.active_handle){const h=new _.Vector2;h.subVectors(i,this.drag_start_mouse);const f=this.active_handle.axis,m=this.active_handle.side,y=10,v=f==="x"?h.x*y:f==="y"?h.y*y:-h.y*y,b=this.drag_start_value+v;this.bounds[m][f]=b,m==="min"&&this.bounds.min[f]>this.bounds.max[f]?this.bounds.min[f]=this.bounds.max[f]-.1:m==="max"&&this.bounds.max[f]<this.bounds.min[f]&&(this.bounds.max[f]=this.bounds.min[f]+.1),this.update_helpers(),this.emit_bounds_changed()}else{s.setFromCamera(i,t);const h=this.plane_handles.map(m=>m.mesh),f=s.intersectObjects(h);this.plane_handles.forEach(m=>{const y=f.length>0&&m.mesh===f[0].object;m.set_hover(y)}),n.style.cursor=f.length>0?"grab":"default"}},c=()=>{this.active_handle&&(this.active_handle=void 0,this.orbit_controls&&(this.orbit_controls.enabled=!0))};this.event_listeners.push({element:n,type:"pointerdown",handler:o},{element:n,type:"pointermove",handler:a},{element:n,type:"pointerup",handler:c}),n.addEventListener("pointerdown",o),n.addEventListener("pointermove",a),n.addEventListener("pointerup",c)}update_helpers(){this.box_helper&&this.box_helper.box.copy(this.bounds),this.plane_handles.forEach(t=>{t.update_from_bounds(this.bounds)})}emit_bounds_changed(){this.dispatchEvent(new CustomEvent("boundschanged",{detail:{bounds:this.get_bounds()}}))}dispose(){this.plane_handles.forEach(t=>t.dispose()),this.plane_handles=[],this.box_helper=void 0,this.event_listeners.length>0&&(this.event_listeners.forEach(({element:t,type:n,handler:s})=>{t.removeEventListener(n,s)}),this.event_listeners=[])}}const Xi=8,Dc=`
|
|
839
|
+
attribute vec3 aN0;
|
|
840
|
+
attribute vec3 aN1;
|
|
841
|
+
attribute vec4 aOtherVert;
|
|
842
|
+
uniform float uAngleThresh;
|
|
843
|
+
uniform int uOutline;
|
|
844
|
+
|
|
845
|
+
varying vec3 vWorldPos;
|
|
846
|
+
|
|
847
|
+
void main() {
|
|
848
|
+
vec4 worldPos = modelMatrix * vec4(position, 1.);
|
|
849
|
+
vec4 mvPosition = viewMatrix * worldPos;
|
|
850
|
+
gl_Position = projectionMatrix * mvPosition;
|
|
851
|
+
gl_Position.z -= 0.001;
|
|
852
|
+
|
|
853
|
+
vWorldPos = worldPos.xyz;
|
|
854
|
+
|
|
855
|
+
vec3 viewDir = normalize(-mvPosition.xyz);
|
|
856
|
+
|
|
857
|
+
float l0 = length(aN0);
|
|
858
|
+
float l1 = length(aN1);
|
|
859
|
+
|
|
860
|
+
if (l0 * l1 < 0.0001) return;
|
|
861
|
+
|
|
862
|
+
float dd = dot(normalize(aN0), normalize(aN1));
|
|
863
|
+
if (acos(dd) > uAngleThresh) return;
|
|
864
|
+
|
|
865
|
+
bool isOther = aOtherVert.w > 0.5;
|
|
866
|
+
vec3 a;
|
|
867
|
+
vec3 b;
|
|
868
|
+
|
|
869
|
+
if (isOther) {
|
|
870
|
+
a = aOtherVert.xyz;
|
|
871
|
+
b = position;
|
|
872
|
+
} else {
|
|
873
|
+
a = position;
|
|
874
|
+
b = aOtherVert.xyz;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
vec3 ld = normalize(b - a);
|
|
878
|
+
vec3 camToEdge = cameraPosition - a;
|
|
879
|
+
float f = dot(camToEdge, ld);
|
|
880
|
+
vec3 p = a + ld * f;
|
|
881
|
+
p = normalize(p - cameraPosition);
|
|
882
|
+
|
|
883
|
+
vec3 vN0 = (modelViewMatrix * vec4(aN0, 0.)).xyz;
|
|
884
|
+
vec3 vN1 = (modelViewMatrix * vec4(aN1, 0.)).xyz;
|
|
885
|
+
|
|
886
|
+
bool outline = sign(dot(vN0, viewDir)) * sign(dot(vN1, viewDir)) < 0.;
|
|
887
|
+
|
|
888
|
+
if (uOutline == 1 && outline) return;
|
|
889
|
+
|
|
890
|
+
gl_Position.z = -2000.;
|
|
891
|
+
}
|
|
892
|
+
`,Ic=`
|
|
893
|
+
uniform vec3 uColor;
|
|
894
|
+
uniform int uClipPlaneCount;
|
|
895
|
+
uniform vec4 uClipPlanes[8];
|
|
896
|
+
|
|
897
|
+
varying vec3 vWorldPos;
|
|
898
|
+
|
|
899
|
+
void main() {
|
|
900
|
+
for (int i = 0; i < 8; i++) {
|
|
901
|
+
if (i >= uClipPlaneCount) break;
|
|
902
|
+
if (dot(vWorldPos, uClipPlanes[i].xyz) + uClipPlanes[i].w < 0.0) discard;
|
|
903
|
+
}
|
|
904
|
+
gl_FragColor = vec4(uColor, 1.);
|
|
905
|
+
}
|
|
906
|
+
`;class zn extends u.ShaderMaterial{constructor(e=0,t=!0,n="#000000"){super({vertexShader:Dc,fragmentShader:Ic,uniforms:{uAngleThresh:{value:0},uOutline:{value:Number(t)},uColor:{value:new u.Color(n)},uClipPlaneCount:{value:0},uClipPlanes:{value:new Float32Array(Xi*4)}}}),this.angle_threshold=e}set angle_threshold(e){this.uniforms.uAngleThresh.value=e/180*Math.PI%Math.PI}get angle_threshold(){return this.uniforms.uAngleThresh.value*180/Math.PI}set outline(e){this.uniforms.uOutline.value=Number(e)}get outline(){return!!this.uniforms.uOutline.value}get outline_color(){return this.uniforms.uColor.value}set_clip_planes(e){const t=this.uniforms.uClipPlanes,n=this.uniforms.uClipPlaneCount;if(!t||!n)return;const s=t.value,i=Math.min(e.length,Xi);n.value=i;for(let o=0;o<i;o++){const a=e[o],c=o*4;s[c]=a.normal[0],s[c+1]=a.normal[1],s[c+2]=a.normal[2],s[c+3]=a.constant}}}const Ss=1e3;class $i extends u.LineSegments{constructor(e,t=new zn){super(new u.BufferGeometry,t),this.extract_geometry(e.geometry)}extract_geometry(e){const{v_array:t,n0_array:n,n1_array:s,other_vert_array:i}=e.index?this.extract_indexed(e):this.extract_soup(),o=this.geometry;o.setAttribute("position",new u.BufferAttribute(new Float32Array(t),3)),o.setAttribute("aN0",new u.BufferAttribute(new Float32Array(n),3)),o.setAttribute("aN1",new u.BufferAttribute(new Float32Array(s),3)),o.setAttribute("aOtherVert",new u.BufferAttribute(new Float32Array(i),4))}extract_indexed(e){const{welded_indices:t,welded_vertices:n}=this.weld_indexed(e.index,e.attributes.position),s=this.extract_edges_from_index(t,n),i=[],o=[],a=[],c=[];for(const{a:l,b:d,n0:h,n1:f}of s){const m=y=>{const v=y*3;o.push(h.x,h.y,h.z),a.push(f.x,f.y,f.z),i.push(n[v],n[v+1],n[v+2])};m(l),m(d),c.push(n[d*3],n[d*3+1],n[d*3+2],0),c.push(n[l*3],n[l*3+1],n[l*3+2],1)}return{v_array:i,n0_array:o,n1_array:a,other_vert_array:c}}weld_indexed(e,t){const n={},s={},i=[],o=[];for(let a=0,c=0;a<t.count;a++){const l=a*3,d=[Math.round(t.array[l]*Ss),Math.round(t.array[l+1]*Ss),Math.round(t.array[l+2]*Ss)].join(":");n[d]===void 0&&(n[d]=c++,i.push(t.array[l],t.array[l+1],t.array[l+2])),s[a]=n[d]}for(let a=0;a<e.count;a+=3)for(let c=0;c<3;c++){const l=e.array[a+c];o.push(s[l])}return{welded_vertices:i,welded_indices:o}}extract_edges_from_index(e,t){var h,f;const n=[],s=new u.Vector3,i=new u.Vector3,o=new u.Vector3;for(let m=0;m<e.length;m+=3){const y=new u.Vector3;s.fromArray(t,e[m]*3),i.fromArray(t,e[m+1]*3),o.fromArray(t,e[m+2]*3),y.crossVectors(i.clone().sub(s),o.clone().sub(s)),n.push(y.normalize())}const a={},c=[];for(let m=0;m<e.length/3;m++){const y=m*3;for(let v=0;v<3;v++){const b=(v+1)%3,w=e[y+v],T=e[y+b];a[w]||(a[w]={}),a[w][T]=m,c.push([w,T])}}const l=[],d={};for(const[m,y]of c){if(d[m]||(d[m]={}),d[y]||(d[y]={}),d[m][y])continue;const v=(h=a[m])==null?void 0:h[y],b=(f=a[y])==null?void 0:f[m],w=v!==void 0?n[v]:new u.Vector3,T=b!==void 0?n[b]:new u.Vector3;l.push({a:m,b:y,n0:w,n1:T}),d[m][y]=!0,d[y][m]=!0}return l}extract_soup(){return{v_array:[],n0_array:[],n1_array:[],other_vert_array:[]}}}const cn=new Set;let Ts=!1;function Ec(r,e,t=2){const n=e&&e.length,s=n?e[0]*t:r.length;cn.size&&cn.clear();let i=Ki(r,0,s,t,!0);const o=[];if(!i||i.next===i.prev)return o;let a=0,c=0,l=0;if(n&&(i=Uc(r,e,i,t)),r.length>80*t){a=r[0],c=r[1];let d=a,h=c;for(let f=t;f<s;f+=t){const m=r[f],y=r[f+1];m<a&&(a=m),y<c&&(c=y),m>d&&(d=m),y>h&&(h=y)}l=Math.max(d-a,h-c),l=l!==0?32767/l:0}return Ms(i,o,a,c,l),o}function Ki(r,e,t,n,s){let i=null;if(s===Hc(r,e,t,n)>0)for(let o=e;o<t;o+=n)i=tr(o/n|0,r[o],r[o+1],i);else for(let o=t-n;o>=e;o-=n)i=tr(o/n|0,r[o],r[o+1],i);return i&&un(i,i.next)&&(fn(i),i=i.next),i}function mt(r,e=r){const t=e===r;let n=r,s;do s=!1,n!==n.next&&(cn.size===0||!cn.has(n))&&(un(n,n.next)||ae(n.prev,n,n.next)===0)?((t||n===e)&&(e=n.prev),Ts=!0,fn(n),n=n.prev,s=!0):(t||n!==e)&&(n=n.next,s=!t);while(s||n!==e);return e}function Ms(r,e,t,n,s){s&&Wc(r,t,n,s);let i=r,o=!1;for(;r.prev!==r.next;){const a=r.prev,c=r.next;if(ae(a,r,c)<0&&(s?Pc(r,t,n,s):Nc(r))){e.push(a.i,r.i,c.i),fn(r),r=c,i=c;continue}if(r=c,r===i){if(Ts=!1,r=mt(r),Ts){i=r;continue}if(!o){r=Rc(r,e),i=r,o=!0;continue}zc(r,e,t,n,s);break}}}function Nc(r){const e=r.prev,t=r,n=r.next,s=e.x,i=t.x,o=n.x,a=e.y,c=t.y,l=n.y,d=Math.min(s,i,o),h=Math.min(a,c,l),f=Math.max(s,i,o),m=Math.max(a,c,l);let y=n.next;for(;y!==e;){if(y.x>=d&&y.x<=f&&y.y>=h&&y.y<=m&&!(s===y.x&&a===y.y)&&jn(s,a,i,c,o,l,y.x,y.y)&&ae(y.prev,y,y.next)>=0)return!1;y=y.next}return!0}function Pc(r,e,t,n){const s=r.prev,i=r,o=r.next,a=s.x,c=i.x,l=o.x,d=s.y,h=i.y,f=o.y,m=Math.min(a,c,l),y=Math.min(d,h,f),v=Math.max(a,c,l),b=Math.max(d,h,f),w=ks(m,y,e,t,n),T=ks(v,b,e,t,n);let M=r.prevZ;for(;M&&M.z>=w;){if(M.x>=m&&M.x<=v&&M.y>=y&&M.y<=b&&M!==o&&!(a===M.x&&d===M.y)&&jn(a,d,c,h,l,f,M.x,M.y)&&ae(M.prev,M,M.next)>=0)return!1;M=M.prevZ}let x=r.nextZ;for(;x&&x.z<=T;){if(x.x>=m&&x.x<=v&&x.y>=y&&x.y<=b&&x!==o&&!(a===x.x&&d===x.y)&&jn(a,d,c,h,l,f,x.x,x.y)&&ae(x.prev,x,x.next)>=0)return!1;x=x.nextZ}return!0}function Rc(r,e){let t=r,n=!1;do{const s=t.prev,i=t.next.next;Qi(s,t,t.next,i,!1)&&hn(s,i)&&hn(i,s)&&(e.push(s.i,t.i,i.i),fn(t),fn(t.next),t=r=i,n=!0),t=t.next}while(t!==r);return n?mt(t):t}function zc(r,e,t,n,s){let i=r;do{let o=i.next.next;for(;o!==i.prev;){if(i.i!==o.i&&Kc(i,o)){let a=er(i,o);i=mt(i,i.next),a=mt(a,a.next),Ms(i,e,t,n,s),Ms(a,e,t,n,s);return}o=o.next}i=i.next}while(i!==r)}let Ls=!1;function Uc(r,e,t,n){const s=[];for(let i=0,o=e.length;i<o;i++){const a=e[i]*n,c=i<o-1?e[i+1]*n:r.length,l=Ki(r,a,c,n,!1);l===l.next&&cn.add(l),s.push($c(l))}s.sort(Fc),Bc(r.length/n,e.length),qi(t,t),Ls=!0;for(let i=0;i<s.length;i++)t=jc(s[i],t);return Ls=!1,mt(t)}function Fc(r,e){return r.x-e.x||r.y-e.y||(r.next.y-r.y)/(r.next.x-r.x)-(e.next.y-e.y)/(e.next.x-e.x)}function jc(r,e){const t=Gc(r,e);if(!t)return e;const n=er(t,r),s=n.next;return qi(t,s.next),mt(n,n.next),mt(t,t.next)}const Yi=16;let oe=new Float64Array(0),Un=0;const Cs=[],Os=[];function Bc(r,e){const t=Math.ceil((r+2*e)/Yi)+e+2;oe.length<t*4&&(oe=new Float64Array(t*4)),Un=0}function qi(r,e){let t=r;do{const n=Un++;Cs[n]=t;let s=t.x,i=t.y,o=t.x,a=t.y,c=0;do{const d=t.next;t.z=n,d.x<s&&(s=d.x),d.x>o&&(o=d.x),d.y<i&&(i=d.y),d.y>a&&(a=d.y),t=d}while(++c<Yi&&t!==e);Os[n]=t;const l=n*4;oe[l]=s,oe[l+1]=i,oe[l+2]=o,oe[l+3]=a}while(t!==e)}function Vc(r,e){const t=r.z*4;e.x<oe[t]&&(oe[t]=e.x),e.y<oe[t+1]&&(oe[t+1]=e.y),e.x>oe[t+2]&&(oe[t+2]=e.x),e.y>oe[t+3]&&(oe[t+3]=e.y)}function Hi(r){let e=Os[r];for(;e.prev.next!==e;)e=e.next;return Os[r]=e,e}function Ji(r){let e=Cs[r];for(;e.prev.next!==e;)e=e.next;return Cs[r]=e,e}function Gc(r,e){let t=e;const n=r.x,s=r.y;let i=-1/0,o;if(un(r,t))return t;for(let f=0,m=0;f<Un;f++,m+=4){if(s<oe[m+1]||s>oe[m+3]||oe[m]>n||oe[m+2]<=i)continue;const y=Hi(f);t=Ji(f);do{if(t.prev.next===t){if(un(r,t.next))return t.next;if(s<=t.y&&s>=t.next.y&&t.next.y!==t.y){const v=t.x+(s-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(v<=n&&v>i&&(i=v,o=t.x<t.next.x?t:t.next,v===n))return o}}t=t.next}while(t!==y)}if(!o)return null;const a=o.x,c=o.y,l=Math.min(s,c),d=Math.max(s,c);let h=1/0;for(let f=0,m=0;f<Un;f++,m+=4){if(oe[m+2]<a||oe[m]>n||oe[m+3]<l||oe[m+1]>d)continue;const y=Hi(f);t=Ji(f);do{if(t.prev.next===t&&n>=t.x&&t.x>=a&&n!==t.x&&jn(s<c?n:i,s,a,c,s<c?i:n,s,t.x,t.y)){const v=Math.abs(s-t.y)/(n-t.x);(hn(t,r)||t.y===s&&t.next.y===s&&t.next.x>n)&&(v<h||v===h&&(t.x>o.x||t.x===o.x&&Zc(o,t)))&&(o=t,h=v)}t=t.next}while(t!==y)}return o}function Zc(r,e){return ae(r.prev,r,e.prev)<0&&ae(e.next,r,r.next)<0}const Ie=[];let Ct=[],_t=new Uint32Array(0),ln=new Uint32Array(0);const dn=new Uint32Array(256);function Wc(r,e,t,n){let s=r,i=0;do s.z=ks(s.x,s.y,e,t,n),Ie[i++]=s,s=s.next;while(s!==r);Xc(i);let o=null;for(let a=0;a<i;a++){const c=Ie[a];c.prevZ=o,o&&(o.nextZ=c),o=c}o.nextZ=null,Ie.fill(null,0,i),Ct.fill(null,0,i)}function Xc(r){if(r<=32){for(let e=1;e<r;e++){const t=Ie[e],n=t.z;let s=e-1;for(;s>=0&&Ie[s].z>n;)Ie[s+1]=Ie[s],s--;Ie[s+1]=t}return}_t.length<r&&(_t=new Uint32Array(r),ln=new Uint32Array(r),Ct=new Array(r));for(let e=0;e<r;e++)_t[e]=Ie[e].z;Fn(r,Ie,_t,Ct,ln,0),Fn(r,Ct,ln,Ie,_t,8),Fn(r,Ie,_t,Ct,ln,16),Fn(r,Ct,ln,Ie,_t,24)}function Fn(r,e,t,n,s,i){dn.fill(0);for(let a=0;a<r;a++)dn[t[a]>>>i&255]++;let o=0;for(let a=0;a<256;a++){const c=dn[a];dn[a]=o,o+=c}for(let a=0;a<r;a++){const c=t[a],l=dn[c>>>i&255]++;n[l]=e[a],s[l]=c}}function ks(r,e,t,n,s){return r=(r-t)*s|0,e=(e-n)*s|0,r=(r|r<<8)&16711935,r=(r|r<<4)&252645135,r=(r|r<<2)&858993459,r=(r|r<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,r|e<<1}function $c(r){let e=r,t=r;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==r);return t}function jn(r,e,t,n,s,i,o,a){return(s-o)*(e-a)>=(r-o)*(i-a)&&(r-o)*(n-a)>=(t-o)*(e-a)&&(t-o)*(i-a)>=(s-o)*(n-a)}function Kc(r,e){const t=un(r,e)&&ae(r.prev,r,r.next)>0&&ae(e.prev,e,e.next)>0;return r.next.i!==e.i&&(t||hn(r,e)&&hn(e,r)&&(ae(r.prev,r,e.prev)!==0||ae(r,e.prev,e)!==0))&&!Yc(r,e)&&(t||qc(r,e))}function ae(r,e,t){return(e.y-r.y)*(t.x-e.x)-(e.x-r.x)*(t.y-e.y)}function un(r,e){return r.x===e.x&&r.y===e.y}function Qi(r,e,t,n,s=!0){const i=ae(r,e,t),o=ae(r,e,n),a=ae(t,n,r),c=ae(t,n,e);return(i>0&&o<0||i<0&&o>0)&&(a>0&&c<0||a<0&&c>0)?!0:s?!!(i===0&&Bn(r,t,e)||o===0&&Bn(r,n,e)||a===0&&Bn(t,r,n)||c===0&&Bn(t,e,n)):!1}function Bn(r,e,t){return e.x<=Math.max(r.x,t.x)&&e.x>=Math.min(r.x,t.x)&&e.y<=Math.max(r.y,t.y)&&e.y>=Math.min(r.y,t.y)}function Yc(r,e){const t=Math.min(r.x,e.x),n=Math.max(r.x,e.x),s=Math.min(r.y,e.y),i=Math.max(r.y,e.y);let o=r;do{const a=o.next;if(o.x>n&&a.x>n||o.x<t&&a.x<t||o.y>i&&a.y>i||o.y<s&&a.y<s){o=a;continue}if(o.i!==r.i&&a.i!==r.i&&o.i!==e.i&&a.i!==e.i&&Qi(o,a,r,e))return!0;o=a}while(o!==r);return!1}function hn(r,e){return ae(r.prev,r,r.next)<0?ae(r,e,r.next)>=0&&ae(r,r.prev,e)>=0:ae(r,e,r.prev)<0||ae(r,r.next,e)<0}function qc(r,e){let t=r,n=!1;const s=(r.x+e.x)/2,i=(r.y+e.y)/2;do{const o=t.next;t.y>i!=o.y>i&&s<(o.x-t.x)*(i-t.y)/(o.y-t.y)+t.x&&(n=!n),t=o}while(t!==r);return n}function er(r,e){const t=Ds(r.i,r.x,r.y),n=Ds(e.i,e.x,e.y),s=r.next,i=e.prev;return r.next=e,e.prev=r,t.next=s,s.prev=t,n.next=t,t.prev=n,i.next=n,n.prev=i,n}function tr(r,e,t,n){const s=Ds(r,e,t);return n?(s.next=n.next,s.prev=n,n.next.prev=s,n.next=s):(s.prev=s,s.next=s),s}function fn(r){r.next.prev=r.prev,r.prev.next=r.next,r.prevZ&&(r.prevZ.nextZ=r.nextZ),r.nextZ&&(r.nextZ.prevZ=r.prevZ),Ls&&Vc(r.prev,r.next)}function Ds(r,e,t){return{i:r,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null}}function Hc(r,e,t,n){let s=0;for(let i=e,o=t-n;i<t;i+=n)s+=(r[o]-r[i])*(r[i+1]+r[o+1]),o=i;return s}function Jc(r,e){const t=[],n=i=>{for(let o=0;o<t.length;o++)if(t[o].distanceTo(i)<=e)return o;return t.push(i.clone()),t.length-1},s=[];for(const[i,o]of r){const a=n(i),c=n(o);a!==c&&s.push([t[a],t[c]])}return{segments:s,points:t}}function Is(r){let e=0;for(let t=0;t<r.length;t++){const n=(t+1)%r.length;e+=r[t].x*r[n].y,e-=r[n].x*r[t].y}return e/2}function Qc(r,e,t=1e-9){let n=!1;const s=r.x,i=r.y;for(let o=0,a=e.length-1;o<e.length;a=o++){const c=e[o].x,l=e[o].y,d=e[a].x,h=e[a].y;if(Math.abs((d-c)*(i-l)-(h-l)*(s-c))<t&&s>=Math.min(c,d)-t&&s<=Math.max(c,d)+t&&i>=Math.min(l,h)-t&&i<=Math.max(l,h)+t)return!0;l>i!=h>i&&s<(d-c)*(i-l)/(h-l)+c&&(n=!n)}return n}function el(r,e){const t=r.reduce((s,i)=>s+i.x,0)/r.length,n=r.reduce((s,i)=>s+i.y,0)/r.length;return Qc(new _.Vector2(t,n),e)}function tl(r,e){if(r.length<3)return[];const{points:t,segments:n}=Jc(r,e);if(n.length<3)return[];const s=Array.from({length:t.length},()=>[]),i=(l,d)=>l<d?`${l},${d}`:`${d},${l}`,o=new Set;for(const[l,d]of n){const h=t.indexOf(l),f=t.indexOf(d);if(h===-1||f===-1||h===f)continue;const m=i(h,f);o.has(m)||(o.add(m),s[h].push(f),s[f].push(h))}const a=new Set,c=[];for(let l=0;l<t.length;l++)for(;;){let d=-1;for(const v of s[l]){const b=i(l,v);if(!a.has(b)){d=v;break}}if(d===-1)break;const h=[l];let f=l,m=-1,y=d;for(;;){const v=i(f,y);if(a.add(v),y===l){h.length>=3&&c.push(h);break}h.push(y),m=f,f=y;let b=!1;for(const w of s[f]){if(w===m)continue;const T=i(f,w);if(!a.has(T)){y=w,b=!0;break}}if(!b||h.length>t.length+5)break}}return c.map(l=>l.map(d=>t[d]))}function nl(r,e,t,n){let s=r.distanceToPoint(e),i=r.distanceToPoint(t),o=r.distanceToPoint(n);const a=1e-10;if(Math.abs(s)<a&&(s=0),Math.abs(i)<a&&(i=0),Math.abs(o)<a&&(o=0),s>=0==i>=0&&s>=0==o>=0)return null;const c=[],l=(h,f,m,y)=>{if(m===0){c.push(h.clone());return}if(y===0){c.push(f.clone());return}if(m>0!=y>0){const v=m/(m-y);c.push(new _.Vector3().copy(h).addScaledVector(new _.Vector3().copy(f).sub(h),v))}};if(l(e,t,s,i),l(t,n,i,o),l(n,e,o,s),c.length<2)return null;const d=[];for(const h of c)d.every(f=>f.distanceTo(h)>=a)&&d.push(h);return d.length>=2?[d[0],d[1]]:null}function sl(r){r.traverse(e=>{var t;if(e.isMesh||e.isLine){const n=e;if((t=n.geometry)==null||t.dispose(),n.material){const s=n.material;if(Array.isArray(s))for(const i of s)i.dispose();else s.dispose()}}})}function il(r,e,t){const n=(t==null?void 0:t.epsilon)??.001,s=(t==null?void 0:t.color)??16737792,i=(t==null?void 0:t.side)??_.DoubleSide,o=(t==null?void 0:t.polygon_offset)??!0,a=(t==null?void 0:t.polygon_offset_factor)??-1,c=(t==null?void 0:t.polygon_offset_units)??-1,l=[];r.traverse(C=>{const I=C;if(!I.isMesh||!I.visible||!I.geometry.index||!I.geometry.attributes.position)return;const R=I.geometry.attributes.position,W=I.geometry.index,$=I.matrixWorld;for(let E=0;E<W.count;E+=3){const ee=new _.Vector3(R.getX(W.getX(E)),R.getY(W.getX(E)),R.getZ(W.getX(E))).applyMatrix4($),Y=new _.Vector3(R.getX(W.getX(E+1)),R.getY(W.getX(E+1)),R.getZ(W.getX(E+1))).applyMatrix4($),Te=new _.Vector3(R.getX(W.getX(E+2)),R.getY(W.getX(E+2)),R.getZ(W.getX(E+2))).applyMatrix4($),de=nl(e,ee,Y,Te);de&&l.push(de)}});const d=tl(l,n);if(d.length===0)return null;const h=new _.Vector3(0,1,0),f=new _.Vector3(1,0,0),m=new _.Vector3().crossVectors(e.normal,Math.abs(e.normal.dot(h))<.9?h:f).normalize(),y=new _.Vector3().crossVectors(e.normal,m).normalize(),v=C=>C.map(I=>new _.Vector2(I.dot(m),I.dot(y))),b=d.map(v),w=b.map((C,I)=>({i:I,area:Math.abs(Is(C))})).sort((C,I)=>I.area-C.area).map(C=>C.i),T=w.map(C=>d[C]),M=w.map(C=>b[C]),x=(t==null?void 0:t.plane_offset)??1e-4,z=e.normal.clone().multiplyScalar(x),Z=[],j=new Array(T.length).fill(!1);for(let C=0;C<T.length;C++){if(j[C])continue;const I=T[C],R=M[C],W=[],$=[];for(let U=C+1;U<T.length;U++)!j[U]&&el(M[U],R)&&(W.push(T[U]),$.push(M[U]),j[U]=!0);j[C]=!0,Is(R)<0&&(R.reverse(),I.reverse());for(let U=0;U<$.length;U++)Is($[U])>0&&($[U].reverse(),W[U].reverse());const E=[...R,...$.flat()],ee=[];for(const U of E)ee.push(U.x,U.y);const Y=[];let Te=R.length;for(const U of $)Y.push(Te),Te+=U.length;const de=Ec(ee,Y.length>0?Y:void 0,2);if(!de||de.length<3)continue;const Fe=[];for(let U=0;U<de.length;U+=3){const Oe=E[de[U]],Dt=E[de[U+1]],Qe=E[de[U+2]];Math.abs((Dt.x-Oe.x)*(Qe.y-Oe.y)-(Dt.y-Oe.y)*(Qe.x-Oe.x))>1e-10&&Fe.push(de[U],de[U+1],de[U+2])}if(Fe.length<3)continue;const Ce=Fe,se=[...I,...W.flat()],_e=new Float32Array(se.length*3);for(let U=0;U<se.length;U++){const Oe=se[U].clone().add(z);_e[U*3]=Oe.x,_e[U*3+1]=Oe.y,_e[U*3+2]=Oe.z}const Q=new _.BufferGeometry;Q.setAttribute("position",new _.BufferAttribute(_e,3)),Q.setIndex(new _.BufferAttribute(new Uint16Array(Ce),1));const ct=new _.MeshBasicMaterial({color:s,side:i,polygonOffset:o,polygonOffsetFactor:a,polygonOffsetUnits:c});t!=null&&t.clipping_planes&&(ct.clippingPlanes=t.clipping_planes),Z.push(new _.Mesh(Q,ct))}if(Z.length===0)return null;if(Z.length===1)return Z[0];const k=new _.Group;for(const C of Z)k.add(C);return k}class nr extends EventTarget{constructor(t){super();g(this,"bounds");g(this,"planes",[]);g(this,"wireframe",null);g(this,"faces",[]);g(this,"caps",[]);g(this,"outline_meshes",[]);g(this,"enabled",!1);g(this,"hidden",!1);g(this,"scene");g(this,"renderer");g(this,"model");g(this,"camera");g(this,"dom_element");g(this,"orbit_controls");g(this,"drag_face",null);g(this,"drag_plane",new _.Plane);g(this,"drag_start",new _.Vector3);g(this,"bound_handlers",[]);g(this,"cap_color",16737792);g(this,"outline_active",!0);t?this.bounds=new _.Box3(new _.Vector3(t.min.x,t.min.y,t.min.z),new _.Vector3(t.max.x,t.max.y,t.max.z)):this.bounds=new _.Box3}get_bounds(){return{min:{x:this.bounds.min.x,y:this.bounds.min.y,z:this.bounds.min.z},max:{x:this.bounds.max.x,y:this.bounds.max.y,z:this.bounds.max.z}}}set_bounds(t){this.bounds.min.set(t.min.x,t.min.y,t.min.z),this.bounds.max.set(t.max.x,t.max.y,t.max.z),this.enabled?this.rebuild():this.update_helpers(),this.emit_bounds_changed()}get_box3(){return this.bounds.clone()}get_planes(){return this.planes.length>0?[...this.planes]:this.bounds.isEmpty()?[]:this.build_planes()}is_enabled(){return this.enabled}fit_to_model(t){this.bounds.setFromObject(t),this.update_helpers(),this.emit_bounds_changed()}set_cap_color(t){this.cap_color=t,this.enabled&&this.rebuild()}set_outline_active(t){this.outline_active=t;for(const n of this.outline_meshes)n.visible=t}enable(t,n,s,i){(i==null?void 0:i.cap_color)!==void 0&&(this.cap_color=i.cap_color),this.scene=t,this.renderer=n,this.model=s,this.bounds.isEmpty()&&this.bounds.setFromObject(s),!this.bounds.isEmpty()&&(n.localClippingEnabled=!0,this.update_clipping(),this.build_visuals(),this.build_caps(),this.hidden=!1,this.enabled=!0)}disable(){this.enabled&&(this.renderer&&(this.renderer.localClippingEnabled=!1),this.clear_model_clipping(),this.sync_outline_clipping([]),this.remove_visuals(),this.clear_caps(),this.planes=[],this.drag_face=null,this.enabled=!1,this.hidden=!1)}toggle_visibility(){this.hidden=!this.hidden,this.set_visible(!this.hidden)}set_visible(t){this.wireframe&&(this.wireframe.visible=t);for(const n of this.faces)n.visible=t}enter_edit_mode(t,n,s,i){this.scene=t,this.camera=n,this.dom_element=s,this.orbit_controls=i,this.build_visuals(),this.setup_interactions()}exit_edit_mode(t){this.remove_listeners(),this.drag_face=null,this.orbit_controls&&(this.orbit_controls.enabled=!0),this.enabled?this.build_visuals():this.remove_visuals()}dispose(){this.remove_listeners(),this.remove_visuals(),this.clear_caps(),this.bounds.makeEmpty(),this.planes=[],this.enabled=!1}build_planes(){const t=this.bounds.min,n=this.bounds.max;return[new _.Plane(new _.Vector3(-1,0,0),n.x),new _.Plane(new _.Vector3(1,0,0),-t.x),new _.Plane(new _.Vector3(0,-1,0),n.y),new _.Plane(new _.Vector3(0,1,0),-t.y),new _.Plane(new _.Vector3(0,0,-1),n.z),new _.Plane(new _.Vector3(0,0,1),-t.z)]}update_clipping(){this.planes=this.build_planes(),this.model&&(this.model.traverse(t=>{if(!t.isMesh)return;const n=t,s=Array.isArray(n.material)?n.material:[n.material];for(const i of s)i.clippingPlanes=this.planes,i.clipShadows=!0,i.needsUpdate=!0}),this.sync_outline_clipping(this.planes))}clear_model_clipping(){this.model&&this.model.traverse(t=>{if(!t.isMesh)return;const n=t,s=Array.isArray(n.material)?n.material:[n.material];for(const i of s)i.clippingPlanes=[],i.needsUpdate=!0})}build_visuals(){if(!this.scene)return;this.remove_visuals();const t=new _.Vector3().subVectors(this.bounds.max,this.bounds.min);if(t.x<=0||t.y<=0||t.z<=0)return;const n=(this.bounds.min.x+this.bounds.max.x)/2,s=(this.bounds.min.y+this.bounds.max.y)/2,i=(this.bounds.min.z+this.bounds.max.z)/2,o=new _.BoxGeometry(t.x,t.y,t.z);this.wireframe=new _.LineSegments(new _.EdgesGeometry(o),new _.LineBasicMaterial({color:13395456,transparent:!0,opacity:.5})),this.wireframe.position.set(n,s,i),this.scene.add(this.wireframe);const a=new _.MeshBasicMaterial({color:16737792,transparent:!0,opacity:.04,side:_.DoubleSide,depthWrite:!1}),c=[{size:[t.x,t.y],pos:[n,s,this.bounds.min.z],rot:[0,0,0],axis:"z",sign:-1},{size:[t.x,t.y],pos:[n,s,this.bounds.max.z],rot:[0,Math.PI,0],axis:"z",sign:1},{size:[t.z,t.y],pos:[this.bounds.min.x,s,i],rot:[0,Math.PI/2,0],axis:"x",sign:-1},{size:[t.z,t.y],pos:[this.bounds.max.x,s,i],rot:[0,-Math.PI/2,0],axis:"x",sign:1},{size:[t.x,t.z],pos:[n,this.bounds.min.y,i],rot:[-Math.PI/2,0,0],axis:"y",sign:-1},{size:[t.x,t.z],pos:[n,this.bounds.max.y,i],rot:[Math.PI/2,0,0],axis:"y",sign:1}];for(const l of c){const d=new _.Mesh(new _.PlaneGeometry(l.size[0],l.size[1]),a);d.position.set(l.pos[0],l.pos[1],l.pos[2]),d.rotation.set(l.rot[0],l.rot[1],l.rot[2]),d.userData={type:"section-face",axis:l.axis,sign:l.sign},this.scene.add(d),this.faces.push(d)}this.set_visible(!this.hidden)}build_caps(){if(!this.scene||!this.model)return;this.clear_caps();const t=this.model;for(const n of this.build_planes()){const s=il(t,n,{color:this.cap_color,clipping_planes:this.planes});s&&(this.scene.add(s),this.build_cap_outlines(s),this.caps.push(s))}}rebuild(){this.update_clipping(),this.build_visuals(),this.build_caps(),this.emit_bounds_changed()}build_cap_outlines(t){t.traverse(n=>{if(!n.isMesh)return;const s=n;if(!s.geometry||!s.geometry.index)return;const i=new $i(s,new zn(20,!0,"#222222"));i.visible=this.outline_active,this.outline_meshes.push(i),s.add(i)})}remove_outlines_for_group(t){const n=new Set;for(const s of t)s.traverse(i=>n.add(i.id));this.outline_meshes=this.outline_meshes.filter(s=>{if(s.parent&&n.has(s.parent.id)){s.parent.remove(s),s.geometry.dispose();const i=s.material;if(Array.isArray(i))for(const o of i)o.dispose();else i.dispose();return!1}return!0})}sync_outline_clipping(t){const n=t.map(s=>({normal:[s.normal.x,s.normal.y,s.normal.z],constant:s.constant}));for(const s of this.outline_meshes){const i=s.material;!Array.isArray(i)&&i instanceof zn&&i.set_clip_planes(n)}}clear_caps(){if(!this.scene){this.caps=[];return}this.remove_outlines_for_group(this.caps);for(const t of this.caps)this.scene.remove(t),sl(t);this.caps=[]}remove_visuals(){if(!this.scene){this.wireframe=null,this.faces=[];return}this.wireframe&&(this.scene.remove(this.wireframe),this.wireframe.geometry.dispose(),this.wireframe.material.dispose(),this.wireframe=null);for(const t of this.faces)this.scene.remove(t),t.geometry.dispose();this.faces=[]}update_helpers(){this.build_visuals()}emit_bounds_changed(){this.dispatchEvent(new CustomEvent("boundschanged",{detail:{bounds:this.get_bounds()}}))}hit_face(t){const n=t.intersectObjects(this.faces);return n.length>0&&n[0]?n[0].object:null}setup_interactions(){if(!this.camera||!this.dom_element)return;this.remove_listeners();const t=this.camera,n=this.dom_element,s=new _.Raycaster,i=new _.Vector2,o=d=>{const h=n.getBoundingClientRect();i.x=(d.clientX-h.left)/h.width*2-1,i.y=-((d.clientY-h.top)/h.height)*2+1},a=d=>{o(d),s.setFromCamera(i,t);const h=this.hit_face(s);h&&(this.drag_face=h,this.orbit_controls&&(this.orbit_controls.enabled=!1),n.style.cursor="grabbing",s.setFromCamera(i,t),this.drag_plane.setFromNormalAndCoplanarPoint(t.getWorldDirection(new _.Vector3),h.position),this.drag_start.copy(h.position),d.stopPropagation())},c=d=>{if(!this.drag_face)return;o(d),s.setFromCamera(i,t);const h=new _.Vector3;if(!s.ray.intersectPlane(this.drag_plane,h))return;const f=new _.Vector3().copy(h).sub(this.drag_start),m=this.drag_face.userData.axis,y=this.drag_face.userData.sign,v=m==="x"?0:m==="y"?1:2,b=f.getComponent(v),w=this.bounds.min,T=this.bounds.max;y===-1?w.setComponent(v,Math.min(w.getComponent(v)+b,T.getComponent(v))):T.setComponent(v,Math.max(T.getComponent(v)+b,w.getComponent(v))),this.drag_start.copy(h),this.rebuild()},l=()=>{this.drag_face&&(this.drag_face=null,n.style.cursor="default",this.orbit_controls&&(this.orbit_controls.enabled=!0))};this.bound_handlers=[{el:n,type:"pointerdown",fn:a},{el:n,type:"pointermove",fn:c},{el:n,type:"pointerup",fn:l}];for(const d of this.bound_handlers)d.el.addEventListener(d.type,d.fn)}remove_listeners(){for(const t of this.bound_handlers)t.el.removeEventListener(t.type,t.fn);this.bound_handlers=[]}}class sr extends EventTarget{constructor(t){super();g(this,"viewer");g(this,"gizmo");g(this,"section_box");g(this,"sectioned_model");this.viewer=t,this.section_box=new nr}create_for_model(t){this.gizmo&&this.dispose_gizmo(),this.gizmo=new Wi,this.gizmo.fit_to_model(t.group),this.gizmo.enter_edit_mode(this.viewer.scene,this.viewer.camera,this.viewer.renderer.domElement,this.viewer.controls),this.gizmo.addEventListener("boundschanged",n=>{this.dispatchEvent(new CustomEvent("boundschanged",{detail:n.detail}))}),this.dispatchEvent(new CustomEvent("editstart",{detail:{bounds:this.gizmo.get_bounds()}})),G.info("Section box edit mode started")}apply_to_model(t,n){var i,o;const s=n??((i=this.gizmo)==null?void 0:i.get_bounds());if(!s)throw new Error("No section box bounds available");this.clear_result(),this.section_box.set_bounds(s),this.section_box.enable(this.viewer.scene,this.viewer.renderer,t.group),this.sectioned_model=t,(o=this.gizmo)==null||o.addEventListener("boundschanged",a=>{const c=a.detail.bounds;this.section_box.set_bounds(c)}),this.dispatchEvent(new CustomEvent("applied",{detail:{bounds:s}})),G.info("Section box applied to model")}finalize(){if(!this.gizmo)return G.warn("No active gizmo to finalize"),null;const t=this.gizmo.get_bounds();return this.gizmo.exit_edit_mode(this.viewer.scene),this.dispatchEvent(new CustomEvent("editend",{detail:{bounds:t}})),G.info("Section box edit mode ended"),t}clear_result(){this.section_box.disable(),this.sectioned_model=void 0}get_bounds(){var t;return((t=this.gizmo)==null?void 0:t.get_bounds())??null}get is_editing(){return this.gizmo!==void 0&&this.gizmo.is_editing}dispose(){this.dispose_gizmo(),this.clear_result(),this.section_box.dispose()}dispose_gizmo(){this.gizmo&&(this.gizmo.exit_edit_mode(this.viewer.scene),this.gizmo.dispose(),this.gizmo=void 0)}}class rl extends EventTarget{constructor(t,n){super();g(this,"glimmer");g(this,"story");g(this,"current_index",0);g(this,"annotation_container");g(this,"annotation_2d_renderer");g(this,"annotation_3d_renderer");g(this,"trigger_manager");g(this,"transition_manager");g(this,"section_box_manager");if(this.glimmer=t,typeof n=="string")try{const s=JSON.parse(n);this.story=En.parse(s)}catch(s){throw G.error("Failed to parse story JSON:",s),new ve(`Invalid story JSON: ${s instanceof Error?s.message:s}`,"StoryManager",Le.INVALID_STORY_JSON,{error:s})}else this.story=En.parse(n);G.info("StoryManager initialized with story:",this.story.title),this.glimmer.viewer.stop_camera_orbit_animation(),this.annotation_container=this._create_annotation_container(),this.annotation_2d_renderer=new Lc({container:this.annotation_container}),this.annotation_3d_renderer=new Cc({scene:this.glimmer.viewer.scene,group_name:"story-annotations"}),this.trigger_manager=new Oc,this.transition_manager=new kc(this.glimmer.viewer.camera,this.glimmer.viewer.controls),this.section_box_manager=new sr(this.glimmer.viewer),this.goto(0)}next(){this.current_index<this.story.slides.length-1?this.goto(this.current_index+1):G.info("Already at last slide")}prev(){this.current_index>0?this.goto(this.current_index-1):G.info("Already at first slide")}home(){this.goto(0)}goto(t){if(t<0||t>=this.story.slides.length){G.error(`Invalid slide index: ${t}. Valid range: 0-${this.story.slides.length-1}`);return}const n=this.story.slides[t],s=this.current_index;this.current_index=t,G.info(`Navigating to slide ${t}: ${n.title||n.id}`),n.settings&&this.glimmer.settings.update(n.settings),this.transition_manager.transition_to_slide(n),this._apply_section_box(n),this._render_annotations(n.annotations||[]),this.dispatchEvent(new CustomEvent("slidechange",{detail:{index:this.current_index,prev_index:s,slide:n,total:this.story.slides.length}}))}register_forward(t){this.trigger_manager.register("forward",t,()=>this.next())}register_backward(t){this.trigger_manager.register("backward",t,()=>this.prev())}register_home(t){this.trigger_manager.register("home",t,()=>this.home())}get current_slide_index(){return this.current_index}get current_slide(){return this.story.slides[this.current_index]}get total_slides(){return this.story.slides.length}get story_info(){return{version:this.story.version,title:this.story.title,description:this.story.description}}capture_current_state(t,n){const s=this.glimmer.viewer.camera,i=this.glimmer.viewer.controls.target,o={id:t,title:n,settings:JSON.parse(this.glimmer.settings.export()),camera:{position:[s.position.x,s.position.y,s.position.z],target:[i.x,i.y,i.z]},section_box_enabled:!1},a=this.section_box_manager.get_bounds();return a&&(o.section_box=a,o.section_box_enabled=!0),In.parse(o)}export_story(){return JSON.stringify(this.story,null,2)}add_slide(t,n){const s=In.parse(t),i=n!==void 0?Math.max(0,Math.min(n,this.story.slides.length)):this.story.slides.length;return this.story.slides.splice(i,0,s),G.info(`Added slide "${s.id}" at index ${i}`),this._emit_story_change("add",i),i}update_slide(t,n){if(t<0||t>=this.story.slides.length)throw new ve(`Invalid slide index: ${t}. Valid range: 0-${this.story.slides.length-1}`,"StoryManager",Le.INVALID_STORY_JSON);const s={...this.story.slides[t],...n},i=In.parse(s);this.story.slides[t]=i,G.info(`Updated slide at index ${t}: "${i.id}"`),this._emit_story_change("update",t),t===this.current_index&&this.goto(t)}delete_slide(t){if(this.story.slides.length<=1)throw new ve("Cannot delete the last slide. Story must have at least one slide.","StoryManager",Le.INVALID_STORY_JSON);if(t<0||t>=this.story.slides.length)throw new ve(`Invalid slide index: ${t}. Valid range: 0-${this.story.slides.length-1}`,"StoryManager",Le.INVALID_STORY_JSON);const n=this.story.slides[t];this.story.slides.splice(t,1),G.info(`Deleted slide at index ${t}: "${n.id}"`),this.current_index>=this.story.slides.length&&(this.current_index=this.story.slides.length-1),this._emit_story_change("delete",t),this.goto(this.current_index)}reorder_slides(t,n){if(t<0||t>=this.story.slides.length)throw new ve(`Invalid from_index: ${t}. Valid range: 0-${this.story.slides.length-1}`,"StoryManager",Le.INVALID_STORY_JSON);if(n<0||n>=this.story.slides.length)throw new ve(`Invalid to_index: ${n}. Valid range: 0-${this.story.slides.length-1}`,"StoryManager",Le.INVALID_STORY_JSON);if(t===n)return;const[s]=this.story.slides.splice(t,1);this.story.slides.splice(n,0,s),G.info(`Reordered slide "${s.id}" from index ${t} to ${n}`),this.current_index===t?this.current_index=n:t<this.current_index&&n>=this.current_index?this.current_index--:t>this.current_index&&n<=this.current_index&&this.current_index++,this._emit_story_change("reorder",t)}replace_story(t){if(typeof t=="string")try{const n=JSON.parse(t);this.story=En.parse(n)}catch(n){throw new ve(`Invalid story JSON: ${n instanceof Error?n.message:n}`,"StoryManager",Le.INVALID_STORY_JSON,{error:n})}else this.story=En.parse(t);G.info("Story replaced:",this.story.title),this.current_index=0,this.goto(0),this._emit_story_change("replace",0)}add_annotation_anchor(t,n,s){const i=this.story.slides[this.current_index];if(!i.annotations||t>=i.annotations.length)throw new ve(`Annotation index ${t} out of range`,"StoryManager.add_annotation_anchor",Le.INVALID_SLIDE_INDEX);i.annotations[t].anchor={model_url:n,local_position:s},this._render_annotations(i.annotations),this._emit_story_change("update",this.current_index)}remove_annotation_anchor(t){const n=this.story.slides[this.current_index];if(!n.annotations||t>=n.annotations.length)throw new ve(`Annotation index ${t} out of range`,"StoryManager.remove_annotation_anchor",Le.INVALID_SLIDE_INDEX);delete n.annotations[t].anchor,this._render_annotations(n.annotations),this._emit_story_change("update",this.current_index)}get_anchored_annotations(){const t=this.story.slides[this.current_index];return t.annotations?t.annotations.map((n,s)=>({index:s,annotation:n})).filter(n=>n.annotation.anchor!==void 0):[]}enter_section_box_edit_mode(){const n=Array.from(this.glimmer.model_manager.models.values())[0];if(!n)throw new ve("No model loaded. Cannot enter section box edit mode.","StoryManager.enter_section_box_edit_mode",Le.MODEL_NOT_FOUND);this.section_box_manager.create_for_model(n)}exit_section_box_edit_mode(){const t=this.section_box_manager.finalize();if(!t){G.warn("Section box edit mode not active");return}const n=this.story.slides[this.current_index];n.section_box=t,n.section_box_enabled=!0,this._emit_story_change("update",this.current_index),this._apply_section_box(n),G.info("Exited section box edit mode and saved to slide")}clear_section_box(){const t=this.story.slides[this.current_index];delete t.section_box,t.section_box_enabled=!1,this.section_box_manager.clear_result(),this._emit_story_change("update",this.current_index),G.info("Cleared section box from current slide")}dispose(){G.info("Disposing StoryManager"),this.glimmer.viewer.stop_camera_orbit_animation(),this.trigger_manager.dispose(),this.annotation_container.remove(),this.annotation_2d_renderer.dispose(),this.annotation_3d_renderer.dispose(),this.section_box_manager.dispose()}_apply_section_box(t){if(this.section_box_manager.clear_result(),!t.section_box_enabled||!t.section_box)return;const s=Array.from(this.glimmer.model_manager.models.values())[0];if(!s){G.warn("No model loaded for section box");return}try{this.section_box_manager.apply_to_model(s,t.section_box),G.info("Applied section box to model")}catch(i){G.error("Failed to apply section box:",i)}}_render_annotations(t){this.annotation_2d_renderer.clear(),this.annotation_3d_renderer.clear(),t.forEach(n=>{n.type==="2d"?this.annotation_2d_renderer.render(n):n.type==="3d"&&this.annotation_3d_renderer.render(n)})}_create_annotation_container(){const t=document.createElement("div");t.className="glimmer-annotations",t.style.cssText=`
|
|
907
|
+
position: absolute;
|
|
908
|
+
top: 0;
|
|
909
|
+
left: 0;
|
|
910
|
+
width: 100%;
|
|
911
|
+
height: 100%;
|
|
912
|
+
pointer-events: none;
|
|
913
|
+
z-index: 1000;
|
|
914
|
+
`;const n=this.glimmer.viewer.renderer.domElement.parentElement;return n&&(n.style.position="relative",n.appendChild(t)),t}_emit_story_change(t,n){this.dispatchEvent(new CustomEvent("storychange",{detail:{action:t,slides:this.story.slides,affected_index:n,total:this.story.slides.length}}))}}const Ot=class Ot extends EventTarget{constructor(){super();g(this,"target_object");g(this,"gizmo_group");g(this,"axis_arrows",new Map);g(this,"enabled",!1);g(this,"active_axis");g(this,"drag_start_position",new _.Vector3);g(this,"drag_start_intersection",new _.Vector3);g(this,"drag_start_mouse",new _.Vector2);g(this,"camera");g(this,"dom_element");g(this,"plane_normal",new _.Vector3);g(this,"plane",new _.Plane);g(this,"raycaster",new _.Raycaster);g(this,"orbit_controls");g(this,"event_listeners",[]);this.gizmo_group=new _.Group,this.gizmo_group.name="MoveGizmo",this.create_gizmo()}create_gizmo(){[{name:"x",color:Ot.AXIS_COLORS.x},{name:"y",color:Ot.AXIS_COLORS.y},{name:"z",color:Ot.AXIS_COLORS.z}].forEach(({name:a,color:c})=>{const l=new _.Group;l.name=`axis_${a}`;const d=new _.CylinderGeometry(.02,.02,1,8),h=new _.MeshBasicMaterial({color:c,toneMapped:!1,depthTest:!1,depthWrite:!1}),f=new _.Mesh(d,h);f.renderOrder=999;const m=new _.ConeGeometry(.05,.2,8),y=new _.MeshBasicMaterial({color:c,toneMapped:!1,depthTest:!1,depthWrite:!1}),v=new _.Mesh(m,y);v.renderOrder=999,a==="x"?(f.rotation.z=-Math.PI/2,f.position.x=1/2,v.rotation.z=-Math.PI/2,v.position.x=1+.2/2):a==="y"?(f.position.y=1/2,v.position.y=1+.2/2):a==="z"&&(f.rotation.x=Math.PI/2,f.position.z=1/2,v.rotation.x=Math.PI/2,v.position.z=1+.2/2),l.add(f),l.add(v),l.userData.axis=a,this.axis_arrows.set(a,l),this.gizmo_group.add(l)})}attach(t){if(this.target_object=t,t.parent){const n=new _.Vector3;t.getWorldPosition(n),this.gizmo_group.position.copy(n)}}detach(){this.target_object=void 0}enable(t,n,s,i){if(this.enabled){console.warn("MoveGizmo already enabled");return}this.enabled=!0,this.camera=n,this.dom_element=s,this.orbit_controls=i,t.add(this.gizmo_group);const o=this.on_mouse_down.bind(this),a=this.on_mouse_move.bind(this),c=this.on_mouse_up.bind(this);s.addEventListener("mousedown",o),s.addEventListener("mousemove",a),s.addEventListener("mouseup",c),this.event_listeners.push({element:s,type:"mousedown",handler:o},{element:s,type:"mousemove",handler:a},{element:s,type:"mouseup",handler:c})}disable(t){this.enabled&&(this.enabled=!1,this.active_axis=void 0,t.remove(this.gizmo_group),this.event_listeners.forEach(({element:n,type:s,handler:i})=>{n.removeEventListener(s,i)}),this.event_listeners=[],this.orbit_controls&&(this.orbit_controls.enabled=!0))}update(){if(!this.target_object)return;const t=new _.Vector3;this.target_object.getWorldPosition(t),this.gizmo_group.position.copy(t)}on_mouse_down(t){var o;if(!this.camera||!this.dom_element||!this.target_object)return;const n=this.dom_element.getBoundingClientRect(),s=new _.Vector2;s.x=(t.clientX-n.left)/n.width*2-1,s.y=-((t.clientY-n.top)/n.height)*2+1,this.raycaster.setFromCamera(s,this.camera);const i=this.raycaster.intersectObjects(this.gizmo_group.children,!0);if(i.length>0){let a=(o=i[0].object.parent)==null?void 0:o.userData.axis;if(a||(a=i[0].object.userData.axis),a){this.active_axis=a,this.drag_start_mouse.set(s.x,s.y),this.drag_start_position.copy(this.target_object.position),this.setup_drag_plane(a),this.raycaster.setFromCamera(s,this.camera);const c=new _.Vector3;this.raycaster.ray.intersectPlane(this.plane,c),c&&this.drag_start_intersection.copy(c),this.orbit_controls&&(this.orbit_controls.enabled=!1),this.dispatchEvent(new CustomEvent("movestart",{detail:{object:this.target_object,axis:a}})),t.stopPropagation()}}}setup_drag_plane(t){if(!this.camera||!this.target_object)return;const n=new _.Vector3;this.camera.getWorldDirection(n),t==="x"?this.plane_normal.set(0,n.y,n.z).normalize():t==="y"?this.plane_normal.set(n.x,0,n.z).normalize():t==="z"&&this.plane_normal.set(n.x,n.y,0).normalize(),this.plane.setFromNormalAndCoplanarPoint(this.plane_normal,this.gizmo_group.position)}on_mouse_move(t){if(!this.active_axis||!this.camera||!this.dom_element||!this.target_object)return;const n=this.dom_element.getBoundingClientRect(),s=new _.Vector2;s.x=(t.clientX-n.left)/n.width*2-1,s.y=-((t.clientY-n.top)/n.height)*2+1,this.raycaster.setFromCamera(s,this.camera);const i=new _.Vector3;if(this.raycaster.ray.intersectPlane(this.plane,i),i){const o=i.clone().sub(this.drag_start_intersection),a=new _.Vector3;this.active_axis==="x"?a.set(o.x,0,0):this.active_axis==="y"?a.set(0,o.y,0):this.active_axis==="z"&&a.set(0,0,o.z);const c=this.drag_start_position.clone().add(a);this.target_object.position.copy(c),this.update(),this.dispatchEvent(new CustomEvent("move",{detail:{object:this.target_object,position:c.clone(),delta:a.clone()}}))}t.stopPropagation()}on_mouse_up(t){!this.active_axis||!this.target_object||(this.orbit_controls&&(this.orbit_controls.enabled=!0),this.dispatchEvent(new CustomEvent("moveend",{detail:{object:this.target_object,position:this.target_object.position.clone()}})),this.active_axis=void 0,t.stopPropagation())}dispose(){this.axis_arrows.forEach(t=>{t.traverse(n=>{if(n.isMesh){const s=n;s.geometry.dispose(),Array.isArray(s.material)?s.material.forEach(i=>i.dispose()):s.material.dispose()}})}),this.axis_arrows.clear()}};g(Ot,"AXIS_COLORS",{x:16711680,y:65280,z:255});let Es=Ot;const kt=class kt extends EventTarget{constructor(){super();g(this,"target_object");g(this,"gizmo_group");g(this,"axis_rings",new Map);g(this,"enabled",!1);g(this,"active_axis");g(this,"drag_start_rotation",new _.Euler);g(this,"drag_start_angle",0);g(this,"camera");g(this,"dom_element");g(this,"raycaster",new _.Raycaster);g(this,"orbit_controls");g(this,"event_listeners",[]);this.gizmo_group=new _.Group,this.gizmo_group.name="RotateGizmo",this.create_gizmo()}create_gizmo(){[{name:"x",color:kt.AXIS_COLORS.x,rotation:new _.Euler(0,Math.PI/2,0)},{name:"y",color:kt.AXIS_COLORS.y,rotation:new _.Euler(Math.PI/2,0,0)},{name:"z",color:kt.AXIS_COLORS.z,rotation:new _.Euler(0,0,0)}].forEach(({name:o,color:a,rotation:c})=>{const l=new _.TorusGeometry(1,.02,16,64),d=new _.MeshBasicMaterial({color:a,toneMapped:!1,transparent:!0,opacity:.8,depthTest:!1,depthWrite:!1}),h=new _.Mesh(l,d);h.rotation.copy(c),h.name=`axis_${o}`,h.userData.axis=o,h.renderOrder=999,this.axis_rings.set(o,h),this.gizmo_group.add(h)})}attach(t){if(this.target_object=t,t.parent){const n=new _.Vector3;t.getWorldPosition(n),this.gizmo_group.position.copy(n)}}detach(){this.target_object=void 0}enable(t,n,s,i){if(this.enabled){console.warn("RotateGizmo already enabled");return}this.enabled=!0,this.camera=n,this.dom_element=s,this.orbit_controls=i,t.add(this.gizmo_group);const o=this.on_mouse_down.bind(this),a=this.on_mouse_move.bind(this),c=this.on_mouse_up.bind(this);s.addEventListener("mousedown",o),s.addEventListener("mousemove",a),s.addEventListener("mouseup",c),this.event_listeners.push({element:s,type:"mousedown",handler:o},{element:s,type:"mousemove",handler:a},{element:s,type:"mouseup",handler:c})}disable(t){this.enabled&&(this.enabled=!1,this.active_axis=void 0,t.remove(this.gizmo_group),this.event_listeners.forEach(({element:n,type:s,handler:i})=>{n.removeEventListener(s,i)}),this.event_listeners=[],this.orbit_controls&&(this.orbit_controls.enabled=!0))}update(){if(!this.target_object)return;const t=new _.Vector3;this.target_object.getWorldPosition(t),this.gizmo_group.position.copy(t)}on_mouse_down(t){if(!this.camera||!this.dom_element||!this.target_object)return;const n=this.dom_element.getBoundingClientRect(),s=new _.Vector2;s.x=(t.clientX-n.left)/n.width*2-1,s.y=-((t.clientY-n.top)/n.height)*2+1,this.raycaster.setFromCamera(s,this.camera);const i=this.raycaster.intersectObjects(this.gizmo_group.children,!0);if(i.length>0){const o=i[0].object.userData.axis;if(o){this.active_axis=o,this.drag_start_rotation.copy(this.target_object.rotation),this.drag_start_angle=this.get_mouse_angle(s,o),this.orbit_controls&&(this.orbit_controls.enabled=!1);const a=this.axis_rings.get(o);a&&(a.material.opacity=1),this.dispatchEvent(new CustomEvent("rotatestart",{detail:{object:this.target_object,axis:o}})),t.stopPropagation()}}}get_mouse_angle(t,n){if(!this.camera)return 0;this.raycaster.setFromCamera(t,this.camera);const s=new _.Vector3;this.camera.getWorldDirection(s);let i=new _.Vector3;n==="x"?i.set(1,0,0):n==="y"?i.set(0,1,0):n==="z"&&i.set(0,0,1);const o=new _.Plane;o.setFromNormalAndCoplanarPoint(i,this.gizmo_group.position);const a=new _.Vector3;if(this.raycaster.ray.intersectPlane(o,a),a){const c=a.clone().sub(this.gizmo_group.position);return n==="x"?Math.atan2(c.z,c.y):n==="y"?Math.atan2(c.x,c.z):Math.atan2(c.y,c.x)}return 0}on_mouse_move(t){if(!this.active_axis||!this.camera||!this.dom_element||!this.target_object)return;const n=this.dom_element.getBoundingClientRect(),s=new _.Vector2;s.x=(t.clientX-n.left)/n.width*2-1,s.y=-((t.clientY-n.top)/n.height)*2+1;const o=this.get_mouse_angle(s,this.active_axis)-this.drag_start_angle,a=this.drag_start_rotation.clone();this.active_axis==="x"?a.x+=o:this.active_axis==="y"?a.y+=o:this.active_axis==="z"&&(a.z+=o),this.target_object.rotation.copy(a),this.dispatchEvent(new CustomEvent("rotate",{detail:{object:this.target_object,rotation:a.clone(),delta:o}})),t.stopPropagation()}on_mouse_up(t){if(!this.active_axis||!this.target_object)return;const n=this.axis_rings.get(this.active_axis);n&&(n.material.opacity=.8),this.orbit_controls&&(this.orbit_controls.enabled=!0),this.dispatchEvent(new CustomEvent("rotateend",{detail:{object:this.target_object,rotation:this.target_object.rotation.clone()}})),this.active_axis=void 0,t.stopPropagation()}dispose(){this.axis_rings.forEach(t=>{t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(n=>n.dispose()):t.material.dispose()}),this.axis_rings.clear()}};g(kt,"AXIS_COLORS",{x:16711680,y:65280,z:255});let Ns=kt;te.Environment=ui,te.Glimmer=tc,te.Model=Si,te.ModelManager=Di,te.MoveGizmo=Es,te.OutlineMaterial=zn,te.OutlineMesh=$i,te.PlaneHandle=Zi,te.RotateGizmo=Ns,te.SectionBox=nr,te.SectionBoxGizmo=Wi,te.SectionBoxManager=sr,te.Settings=Mn,te.StoryManager=rl,te.Sun=fi,te.Viewer=di,Object.defineProperty(te,Symbol.toStringTag,{value:"Module"})});
|