(function(da){function aa(){this.code="function update(dt) {\n\n}";this.exported_callbacks=[];this.extracode="";this.extra_methods=null}function Na(a){return Na.get(a)}function qb(a){this.dependency_blocks=[];this.flag_id=-1;this.flag_mask=0;this.events=null;if(!a)throw"ShaderBlock must have a name";if(-1!=a.indexOf(" "))throw"ShaderBlock name cannot have spaces: "+a;this.name=a;this.code_map=new Map;this.context_macros=null}function ka(a){this.code=a;this.blocks=[];this.pragmas={};this.uniforms=
{};this.attributes={};this.includes={};this.snippets={};this.shader_blocks={};this.is_dynamic=!1;a&&this.parse()}function B(a){this.uid=d.generateUId("MAT-");this._must_update=!0;this._index=-1;this._local_id=B.last_index++;this._last_frame_update=-1;this._color=new Float32Array([1,1,1,1]);this._queue=d.RenderQueue.DEFAULT;this._render_state=new d.RenderState;this._light_mode=d.Material.NO_LIGHTS;this.uvs_matrix=new Float32Array([1,0,0,0,1,0,0,0,1]);this.textures={};this.flags={cast_shadows:!0,receive_shadows:!0,
ignore_frustum:!1};Object.defineProperty(this,"color",{get:function(){return this._color.subarray(0,3)},set:function(a){vec3.copy(this._color,a)},enumerable:!0});Object.defineProperty(this,"opacity",{get:function(){return this._color[3]},set:function(a){this._color[3]=a},enumerable:!0});Object.defineProperty(this,"queue",{get:function(){return this._queue},set:function(a){!isNaN(a)&&isNumber(a)&&(this._queue=a)},enumerable:!0});Object.defineProperty(this,"render_state",{get:function(){return this._render_state},
set:function(a){if(a)for(var c in a)this._render_state[c]=a[c]},enumerable:!0});a&&this.configure(a)}function K(a){B.call(this,null);this._shader="";this._shader_version=-1;this._shader_flags=0;this._shader_code=null;this._uniforms={};this._samplers=[];this._properties=[];this._properties_by_name={};this._passes={};this._light_mode=0;this._primitive=-1;this._allows_instancing=!1;this._version=-1;a&&this.configure(a)}function J(a){K.call(this,null);this.blend_mode=d.Blend.NORMAL;this.createProperty("diffuse",
new Float32Array([1,1,1]),"color");this.createProperty("ambient",new Float32Array([1,1,1]),"color");this.createProperty("emissive",new Float32Array([0,0,0,0]),"color");this._specular_data=vec4.fromValues(0.1,10,0,0);this.specular_on_alpha=this.specular_on_top=!1;this.reflection_factor=this.backlight_factor=0;this.reflection_fresnel=1;this.reflection_specular=!1;this.createProperty("velvet",new Float32Array([0.5,0.5,0.5]),"color");this.velvet_exp=0;this.velvet_additive=!1;this._velvet_info=vec4.create();
this._detail=new Float32Array([0,10,10]);this.normalmap_factor=1;this.normalmap_tangent=!0;this.bumpmap_factor=1;this.displacementmap_factor=0.1;this._texture_settings=new Uint8Array(9);this.use_scene_ambient=!0;this.createProperty("extra",new Float32Array([1,1,1,1]),"color");this.flags={alpha_test:!1,alpha_test_shadows:!1,two_sided:!1,flip_normals:!1,depth_test:!0,depth_write:!0,ignore_lights:!1,cast_shadows:!0,receive_shadows:!0,ignore_frustum:!1};this._uniforms={u_material_color:this._color,u_ambient_color:this._ambient,
u_emissive_color:this._emissive,u_specular:this._specular_data,u_reflection_info:vec2.create(),u_velvet_info:vec4.create(),u_normal_info:vec2.create(),u_detail_info:this._detail,u_texture_matrix:this.uvs_matrix,u_extra_color:this._extra,u_texture_settings:this._texture_settings};this._samplers=[];this.needsUpdate=this._allows_instancing=!0;a&&this.configure(a)}function ua(a){B.call(this,null);this.shader_name="surface";this.blend_mode=d.Blend.NORMAL;this._light_mode=1;this.flags={alpha_test:!1,alpha_test_shadows:!1,
two_sided:!1,flip_normals:!1,depth_test:!0,depth_write:!0,ignore_lights:!1,cast_shadows:!0,receive_shadows:!0,ignore_frustum:!1};this._code="void surf(in Input IN, inout SurfaceOutput o) {\n\to.Albedo = vec3(1.0) * IN.color.xyz;\n\to.Normal = IN.worldNormal;\n\to.Emission = vec3(0.0);\n\to.Specular = 1.0;\n\to.Gloss = 40.0;\n\to.Reflectivity = max(0.0, 0.5 - dot(IN.viewDir,o.Normal));\n\to.Alpha = IN.color.a;\n}\n";this._uniforms={};this._samplers=[];this._mustUpdate=!1;this.properties=[];a&&this.configure(a);
this.computeCode()}function ra(a){K.call(this,null);this.blend_mode=d.Blend.NORMAL;this._shader=this._filename="";this._shader_version=-1;this._shader_flags=0;this._graphcode=null;this._uniforms={};this._samplers=[];this._properties=[];this._properties_by_name={};this._passes={};this._light_mode=B.ONE_LIGHT;this._primitive=-1;this._allows_instancing=!1;this._shader_version=this._version=-1;this._loading=!1;a&&this.configure(a)}function Ca(){this._components=[]}function oa(){}function Oa(a){a&&this.configure(a)}
function ac(){this._last_serialization=null;this._comp_class=""}function Ha(){this._data=this.remotepath=this.fullpath=this.filename=null}function X(a){this.name="";this.takes={};a&&this.configure(a)}function Ia(a){this.name=null;this.tracks=[];this.duration=d.Animation.DEFAULT_DURATION;a&&this.configure(a)}function R(a){this.enabled=!0;this.name="";this._type_index=this._type=null;this.interpolation=d.NONE;this.packed_data=this.looped=!1;this.value_size=0;this.data_table=this.data=null;Object.defineProperty(this,
"_property",{value:"",enumerable:!1,writable:!0});Object.defineProperty(this,"_property_path",{value:[],enumerable:!1,writable:!0});a&&this.configure(a)}function mc(a,b,c){return a*(1-c)+b*c}function na(){this.bones=[];this.global_bone_matrices=[];this.bones_by_name=new Map}function Ab(){this.name="";this.model=mat4.create();this.parent=-1;this.num_children=this.layer=0;this.children=new Int8Array(16)}function rb(){this.skeleton=new na;this.num_keyframes=this.num_animated_bones=this.samples_per_second=
this.duration=0;this.bones_map=new Uint8Array(64);this.keyframes=null}function ia(a){this.resource_names=[];this.metadata=null;this._data={};this._resources_data={};a&&this.configure(a)}function la(a,b){this.filename=b||null;this.fullpath=b||null;this.resource_names=[];this.prefab_data=this.prefab_json=null;this._resources_data={};a&&this.configure(a)}function ea(a){this._code=null;this._functions={};this._global_uniforms={};this._code_parts={};this._subfiles={};this._compiled_shaders={};this._shaderblock_flags_num=
0;this._shaderblock_flags={};this._version=0;a&&(this.code=a)}function Aa(a){this._data={object_class:"GraphCode"};this._modified=!1;this._graph=new LiteGraph.LGraph;this._graph._graphcode=this;this.extra={type:Aa.LOGIC_GRAPH};this._version=0;a&&this.setData(a,!0)}function xa(){this.points=[];this.closed=!1;this.type=d.LINEAR}function Y(a){this.apply_fxaa=!1;this.filter=!0;this.fx=[];this._uniforms={u_aspect:1,u_viewport:vec2.create(),u_iviewport:vec2.create(),u_texture:0,u_depth_texture:1,u_random:vec2.create()};
this._passes=null;this._must_update_passes=!0;a&&this.configure(a)}function Fb(){this.active_entries=[]}function Bb(){this.time=0;this.weight=1;this._take_name=this._animation_name=this._animation_take=null;this._last_time=0;this._must_update=!1}function sb(){this.size=1E5;this.root=[];this.objects_cell_by_id=new WeakMap}function Ta(a){this.renderer_name=null;this.default_shadowmap_resolution=d.RenderSettings.default_shadowmap_resolution;this.keep_viewport=this.ignore_clear=this.ignore_viewports=
!1;this.update_shadowmaps=this.shadows_enabled=!0;this.lights_disabled=this.force_wireframe=this.update_all_shadowmaps=!1;this.quality=Ta.AUTO_QUALITY;this.render_helpers=this.render_gui=this.render_fx=this.render_all_cameras=!0;this.layers=255;this.z_pass=!1;this.in_player=this.frustum_culling=!0;a&&this.configure(a)}function A(a){this._data=new Uint32Array(25);this.init();a&&this.configure(a)}function gb(){this.shader=null;this.uniforms_containers=[];this.index_buffer=this.vertex_buffers=null;this.primitive=
this.offset_range=this.offset_start=-1;this.renderState=null}function ja(a,b){this.uid=d.generateUId("RINS");this.layers=3;this.version=this.index=-1;this.vertex_buffers={};this.wireframe_index_buffer=this.index_buffer=null;this.range=new Int32Array([0,-1]);this.primitive=GL.TRIANGLES;this.collision_mesh=this.mesh=this.transform=null;this.node=a;this.component=b;this.priority=10;this.sort_mode=ja.NO_SORT;this.matrix=mat4.create();this.normal_matrix=mat4.create();this.position=vec3.create();this.oobb=
BBox.create();this.aabb=BBox.create();this.center=BBox.getCenter(this.aabb);this.material=null;this.use_bounding=!0;this.uniforms={};this.samplers=[];this.instanced_models=[];this.shader_block_flags=0;this.shader_blocks=[];this.picking_node=null;this._camera_visibility=0;this._is_visible=!1;this._dist=0;this._nearest_reflection_probe=null}function P(a){this.height=this.width=0;this.precision=P.DEFAULT_PRECISION;this.filter_texture=!0;this.format=GL.RGB;this.use_depth_texture=!0;this.use_stencil_buffer=
!1;this.num_extra_textures=0;this.name=null;this.clone_after_unbind=this.adjust_aspect=this.generate_mipmaps=!1;this._depth_texture=this._color_texture=this._fbo=null;this._textures=[];this._cloned_textures=null;this._version=1;this._minFilter=gl.NEAREST;a&&this.configure(a)}function Ba(a){this.sort_mode=a||d.RenderQueue.NO_SORT;this.instances=[]}function Xa(){this.debug_points=[];this._points=[];this._points_color=[];this._points_nodepth=[];this._points_color_nodepth=[];this._lines=[];this._lines_color=
[];this._names=[];this.grid_texture_url="imgs/grid.png";this.camera2D=new d.Camera({eye:[0,0,0],center:[0,0,-1]});this.createMeshes();this.colors={selected:vec4.fromValues(1,1,1,1),node:vec4.fromValues(1,0.5,0,1),bone:vec4.fromValues(1,0,0.5,1)};this.settings={render_grid:!0,grid_scale:1,grid_alpha:0.5,grid_plane:"xz",render_names:!1,render_skeletons:!0,render_tree:!1,render_components:!0,render_null_nodes:!0,render_axis:!1,render_colliders:!0,render_paths:!0,render_origin:!0,render_colliders_aabb:!1};
this._in_scene=!1}function sa(a){this.light=a;this.resolution=512;this.bias=0;this.format=GL.DEPTH_COMPONENT;this.layers=255;this.fbo=this.texture=null;this.shadow_params=vec4.create();this.reverse_faces=!1}function bc(a,b,c,e,g,d){this.position=vec3.create();c&&this.position.set(c);this.node=a||null;this.instance=b||null;this.distance=e||0;this.normal=g;this.hit=d}function Wa(a,b){this.uid=d.generateUId("PHSX");this.layers=3;this.type=Wa.BOX;this.mesh=null;this.node=a;this.component=b;this.matrix=
mat4.create();this.center=vec3.create();this.oobb=BBox.create();this.aabb=BBox.create()}function r(a){this._data=new Float32Array(10);this._position=this._data.subarray(0,3);this._rotation=this._data.subarray(3,7);quat.identity(this._rotation);this._scaling=this._data.subarray(7,10);this._scaling[0]=this._scaling[1]=this._scaling[2]=1;this._local_matrix=mat4.create();this._global_matrix=mat4.create();this._parent=this._root=this._uid=null;this._must_update=!1;this._version=0;a&&this.configure(a)}
function w(a){this.enabled=!0;this.layers=3;this.clear_depth=this.clear_color=!0;this._type=w.PERSPECTIVE;this._eye=vec3.clone(w.DEFAULT_EYE);this._center=vec3.clone(w.DEFAULT_CENTER);this._up=vec3.clone(w.DEFAULT_UP);this._global_eye=vec3.clone(this._eye);this._global_center=vec3.clone(this._center);this._global_up=vec3.clone(this._up);this._global_front=vec3.create();vec3.sub(this._global_front,this._global_center,this._global_eye);vec3.normalize(this._global_front,this._global_front);this._near=
0.1;this._far=1E3;this._ortho=new Float32Array([-1,1,-1,1]);this._aspect=1;this._fov=45;this._frustum_size=50;this._final_aspect=1;this._viewport=new Float32Array([0,0,1,1]);this._viewport_in_pixels=vec4.create();this._last_viewport_in_pixels=vec4.create();this._background_color=vec4.fromValues(0,0,0,1);this._use_custom_projection_matrix=!1;this.overwrite_material=null;this._view_matrix=mat4.create();this._projection_matrix=mat4.create();this._viewprojection_matrix=mat4.create();this._model_matrix=
mat4.create();this._previous_viewprojection_matrix=mat4.create();this._must_update_projection_matrix=this._must_update_view_matrix=!0;this._rendering_index=-1;this._frame=null;this.show_frame=!0;a&&this.configure(a);this._uniforms={u_view:this._view_matrix,u_viewprojection:this._viewprojection_matrix,u_camera_eye:this._global_eye,u_camera_front:this._global_front,u_camera_planes:vec2.fromValues(this.near,this.far),u_camera_perspective:vec3.create(),u_background_color:this._background_color,u_previous_viewprojection:this._previous_viewprojection_matrix};
this._frustum_planes=this.updateFrustumPlanes();this.updateMatrices()}function ya(a){this.enabled=!0;this.fx=new d.FXStack(a?a.fx:null);this.frame=new d.RenderFrameContext;this.frame.use_depth_texture=!0;this.use_antialiasing=!1;this.shader_material=null;a&&this.configure(a)}function Ja(a){this.enabled=!0;this.fx=new d.FXStack(a?a.fx:null);this.frame=new d.RenderFrameContext;this.frame.use_depth_texture=!0;this.use_antialiasing=!1;this.shader_material=null;a&&this.configure(a)}function x(a){this._position=
vec3.create();this._target=vec3.fromValues(0,0,1);this._up=vec3.fromValues(0,1,0);this.enabled=!0;this.shadows_layers=this.illuminated_layers=255;this.near=1;this.far=500;this.angle=45;this.angle_end=60;this.constant_diffuse=!1;this.use_specular=!0;this.att_start=0;this.att_end=1E3;this.attenuation_type=x.RANGE_ATTENUATION;this.offset=0;this._spot_cone=!0;this.projective_texture=null;this._attenuation_info=new Float32Array([this.att_start,this.att_end,this.attenuation_type,0]);this.use_target=!1;
this._color=vec3.fromValues(1,1,1);this.intensity=1;this._type=x.OMNI;this.frustum_size=50;this.precompute_static_shadowmap=this.cast_shadows=!1;this.shadow_bias=0.05;this.shadowmap_resolution=0;this._update_shadowmap_render_settings=this._shadowmap=null;this._light_matrix=mat4.create();this.extra_texture=null;this._front=vec3.clone(d.FRONT);this._right=vec3.clone(d.RIGHT);this._top=vec3.clone(d.TOP);this._samplers=[];this._uniforms={u_light_info:vec4.fromValues(this._type,this._spot_cone?1:0,0,0),
u_light_front:this._front,u_light_angle:vec4.fromValues(this.angle*DEG2RAD,this.angle_end*DEG2RAD,Math.cos(this.angle*DEG2RAD*0.5),Math.cos(this.angle_end*DEG2RAD*0.5)),u_light_position:this._position,u_light_color:vec3.create(),u_light_att:this._attenuation_info,u_light_offset:this.offset,u_light_extra:vec4.create(),u_light_matrix:this._light_matrix};a&&this.configure(a)}function V(a){this._enabled=!0;this._lod_mesh=this._mesh=null;this._submesh_id=-1;this._material=null;this._primitive=-1;this._must_update_static=
!0;this._transform_version=-1;this.use_submaterials=!1;this.submaterials=[];a&&this.configure(a);this._RI=new d.RenderInstance(null,this);this._is_attached=!1}function z(a){this.enabled=!0;this.mode=z.AUTOMATIC;this.delta_meshes=!1;this.morph_targets=[];da.gl&&(void 0===z.max_supported_vertex_attribs&&(z.max_supported_vertex_attribs=gl.getParameter(gl.MAX_VERTEX_ATTRIBS)),void 0===z.max_supported_morph_targets_using_streams&&(z.max_supported_morph_targets_using_streams=(gl.getParameter(gl.MAX_VERTEX_ATTRIBS)-
6)/2));this._stream_weights=new Float32Array(4);this._uniforms={u_morph_weights:this._stream_weights,u_morph_info:0};a&&this.configure(a)}function L(a){this.search_bones_in_parent=this.enabled=!0;this.skeleton_root_node=null;this.cpu_skinning=!1;this.ignore_transform=!0;this._last_bones=this._mesh=null;this._ris_skinned=[];this._skeleton=null;!L._initialized&&da.gl&&(L.num_supported_uniforms=gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS),L.num_supported_textures=gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),
L.num_supported_uniforms<3*L.MAX_BONES&&0==L.num_supported_textures&&(L.gpu_skinning_supported=!1),L._initialized=!0);a&&this.configure(a)}function Ya(a){this.enabled=!0;this.svg=null;a&&this.configure(a);this._RI=new d.RenderInstance(null,this);this._svg_data=this._mesh=null}function Da(a){this.enabled=!0;this.material=this.texture=null;this._intensity=1;this.use_environment=!0;this._bake_to_cubemap=this.gamma=!1;a&&this.configure(a)}function ab(a){this.enabled=!0;this.texture=null;this.createProperty("color",
vec3.fromValues(1,1,1),"color");this.opacity=1;this.blend_mode=bb.NORMAL;this.material_name=null;a&&this.configure(a)}function Ea(a){this.enabled=!0;this.shape=1;this.mesh=null;this.size=vec3.fromValues(0.5,0.5,0.5);this.center=vec3.create();this.use_mesh_bounding=!1;a&&this.configure(a)}function Sa(a){this._properties=[];this._properties_by_name={};a&&this.configure(a)}function Pa(a){this.enabled=!0;this.texture=null;this.blend_mode=d.Blend.ALPHA;this._size=vec2.fromValues(100,100);this.frame=null;
this.flip_x=!1;this.filtering=!0;this._area=vec4.fromValues(0,0,1,1);this._atlas_component=this._atlas=null;a&&this.configure(a)}function Fa(a){this.enabled=!0;this.texture=null;this.areas=[];this._sprites=[];this._max_sprites=256;a&&this.configure(a)}function E(a){this.include_lights=this.include_cameras=this.include_instances=this.enabled=!0;this._frame_fx_binded=this._frame_fx=!1;this.send_events=!0;this._scene_path=null;this._scene_is_ready=!1;d.Scene&&(this._scene=new d.Scene,this._scene.root.removeAllComponents(),
LEvent.bind(this._scene,"requestFrame",function(){this._root.scene&&this._root.scene.requestFrame()},this));a&&this.configure(a)}function Qa(a){this.in_editor=this.enabled=!0;this.in_player=!1;this.type=Qa.CIRCLE;this.color=[1,1,1,1];this.size=1;this.fill=!1;this.vertical=this.always_on_top=!0;this._is_visible=!1;a&&this.configure(a)}function Ka(a){this.text="";this.notes=[];this._screen_pos=vec3.create();this._selected=null;this.configure(a)}function Gb(a){this.enabled=!0;this.speed=10;this.axis=
[0,1,0];this.local_space=!0;this.swing=!1;this.swing_amplitude=45;a&&this.configure(a)}function D(a){this.enabled=!0;this.no_button_action=D.NONE;this.left_button_action=D.ORBIT;this.middle_button_action=this.right_button_action=D.PAN;this.mouse_wheel_action=D.CHANGE_DISTANCE;this.lock_mouse=this.keyboard_walk_plane=this.keyboard_walk=!1;this.rot_speed=1;this.walk_speed=10;this.wheel_speed=1;this.render_crosshair=this.smooth=!1;this._moving=vec3.fromValues(0,0,0);this._collision_none=vec3.create();
this._collision_left=vec3.create();this._collision_middle=vec3.create();this._collision_right=vec3.create();this._dragging=!1;this._camera=null;this.configure(a)}function cb(a){this.enabled=!0;this.use_global_up_for_yaw=this.on_node_clicked=!1;this.rot_speed=[1,1];a&&this.configure(a)}function Q(a){this.enabled=!0;this.node_id=null;this.cylindrical=this.face_camera=!1;this.front=Q.NEGZ;this.up=Q.POSY;this._global_position=vec3.create();this._target_position=vec3.create();a&&this.configure(a)}function Ra(a){this.enabled=
!0;this.start=100;this.end=1E3;this.density=0.001;this.type=Ra.LINEAR;this.color=vec3.fromValues(0.5,0.5,0.5);this._uniforms={u_fog_info:vec3.create(),u_fog_color:this.color};a&&this.configure(a)}function Hb(a){this.node_uid="";this.follow_camera=this.fixed_y=!1;a&&this.configure(a)}function I(a){this.enabled=!0;this._subdivisions=this._size=10;this._geometry=I.CUBE;this._custom_mesh=null;this._primitive=-1;this._point_size=0.1;this._version=1;this._mesh=null;this._mesh_version=0;a&&this.configure(a)}
function La(a){this.createProperty("ambient_color",La.DEFAULT_AMBIENT_COLOR,"color");this._render_settings=null;this._textures={};this._irradiance=null;a&&this.configure(a)}function ga(a){this.enabled=!0;this.force_redraw=this.from_file=!1;this._graph_properties=this._graphcode=this._filename=this.title=null;this.on_event="update";if("undefined"==typeof LiteGraph)return console.error("Cannot use GraphComponent if LiteGraph is not installed");this._graph_version=-1;this._graph=new LGraph;this._graph.getScene=
function(){return this._scene||d.GlobalScene};this._graph._scenenode=null;this._loading=!1;a?this.configure(a):this.from_file||(a=this._default_node=LiteGraph.createNode("scene/node"),this._graph.add(a));LEvent.bind(this,"trigger",this.trigger,this)}function ca(a){this.enabled=!0;this.frame=new d.RenderFrameContext;this.use_node_camera=this.use_antialiasing=!1;this.title=null;if("undefined"==typeof LGraphTexture)return console.error("Cannot use FXGraphComponent if LiteGraph is not installed");this._graph=
new LGraph;this._graph.getScene=function(){return this._scene};this._graph.component=this;a?this.configure(a):(this._graph_frame_node=LiteGraph.createNode("scene/frame","Rendered Frame"),this._graph_frame_node.ignore_remove=!0,this._graph_frame_node.ignore_rename=!0,this._graph.add(this._graph_frame_node),this._graph_viewport_node=LiteGraph.createNode("texture/toviewport","Viewport"),this._graph_viewport_node.pos[0]=500,this._graph_viewport_node.properties.disable_alpha=!0,this._graph.add(this._graph_viewport_node),
this._graph_frame_node.connect(0,this._graph_viewport_node));null==ca.high_precision_format&&da.gl&&(ca.high_precision_format=gl.half_float_ext?gl.HALF_FLOAT_OES:gl.float_ext?gl.FLOAT:gl.UNSIGNED_BYTE)}function Lb(){this.id=0;this._pos=vec3.fromValues(0,0,0);this._vel=vec3.fromValues(0,0,0);this.life=1;this.angle=0;this.size=1;this.rot=0}function W(a){this.enabled=!0;this.max_particles=1024;this.warm_up_time=0;this.point_particles=!1;this.emissor_type=W.BOX_EMISSOR;this.emissor_rate=5;this.emissor_size=
vec3.fromValues(10,10,10);this.emissor_mesh=null;this.particle_life=5;this.particle_speed=10;this.particle_size=5;this.particle_rotation=0;this.particle_size_curve=[[1,1]];this._particle_start_color=vec3.fromValues(1,1,1);this._particle_end_color=vec3.fromValues(1,1,1);this.particle_opacity_curve=[[0.5,1]];this.texture_grid_size=1;this.physics_gravity=[0,0,0];this.physics_friction=0;this.opacity=1;this.additive_blending=!1;this.texture=null;this.animation_fps=1;this.premultiplied_alpha=this.independent_color=
this.loop_animation=this.animated_texture=this.use_node_material=this.soft_particles=!1;this.align_with_camera=!0;this.follow_emitter=this.align_always=!1;this.sort_in_z=!0;this.ignore_lights=this.stop_update=!1;this.onUpdateParticle=this.onCreateParticle=null;a&&this.configure(a);"number"==typeof this.emissor_size&&(this.emissor_size=[this.emissor_size,this.emissor_size,this.emissor_size]);this._emissor_pos=vec3.create();this._particles=[];this._visible_particles=this._remining_dt=0;this._min_particle_size=
0.001;this._last_id=0;da.gl&&this.createMesh()}function hb(a){this.className=this.text="";this.use_html=!1;this._world_pos=vec3.create();this._screen_pos=vec3.create();this.configure(a)}function ha(a){this.enabled=!0;this.max_points=1024;this.mesh=null;this._points=[];this.texture_grid_size=this.size=1;this.texture=null;this.global_opacity=1;this.color=vec3.fromValues(1,1,1);this.sort_in_z=this.in_world_coordinates=this.premultiplied_alpha=this.use_node_material=this.additive_blending=!1;this.serialize_points=
!0;a&&this.configure(a);this._last_id=0;da.gl&&this.createMesh()}function Ga(a){this.enabled=!0;this.max_lines=1024;this._lines=[];this.global_opacity=1;this.color=vec3.fromValues(1,1,1);this.in_world_coordinates=this.use_node_material=!1;a&&this.configure(a);this._last_id=0;da.gl&&this.createMesh()}function N(a){this.enabled=!0;this._animation="";this._take="default";this.root_node="@";this.playback_speed=1;this.mode=N.LOOP;this.playing=!0;this.blend_time=this.current_time=0;this.onApplySample=this.onPreApply=
this.range=null;this._last_time=0;this._use_blend_animation=!1;this._blend_take=this._blend_animation=null;this._blend_remaining_time=this._blend_current_time=0;this._blend_updated_frame=-1;this.disabled_tracks={};a&&this.configure(a)}function T(a){this.enabled=!0;this.animation="";this.playback_speed=1;this._skeleton=new d.Skeleton;this.mode=T.LOOP;this.playing=!0;this.current_time=0;this.range=null;this.interpolate=!0;a&&this.configure(a)}function ib(a){this.enabled=!0;this.texture_size=512;this.clip_offset=
0.5;this.texture_name="";this.all_cameras=!1;this.blur=0;this.use_mesh_info=this.generate_mipmaps=!1;this.offset=vec3.create();this.skip_if_node_not_visible=this.ignore_this_mesh=!0;this.high_precision=!1;this.refresh_rate=1;this.layers=255;this._clipping_plane=vec4.create();this._textures={};a&&this.configure(a)}function ba(a){this._enabled=!0;this.texture_size=512;this.high_precision=!1;this.texture_name="";this.generate_irradiance=!0;this.generate_mipmaps=!1;this.refresh_rate=0;this.layers=255;
this.near=0.1;this.far=1E3;this.background_color=vec4.create();this._position=vec3.create();this._current=vec3.create();this._version=-1;this._texture=null;this._irradiance_shs=new Float32Array(27);this._tex_id=":probe_"+ba.last_id;ba.last_id++;this._must_update=this._registered=!1;a&&this.configure(a)}function F(a){this.enabled=!0;this.size=vec3.fromValues(10,10,10);this.subdivisions=new Uint8Array([4,1,4]);this.layers=255;this.force_two_sided=!1;this.near=0.1;this.far=1E3;this.debug=this.sampling_distance=
0;this.background_color=vec4.create();this.intensity_color=vec3.fromValues(1,1,1);this.mode=F.VERTEX_MODE;this._irradiance_cubemaps=[];this._irradiance_shs=[];this._irradiance_matrix=mat4.create();this._irradiance_subdivisions=vec3.clone(this.subdivisions);this._sh_texture=null;this._uniforms={irradiance_texture:d.Renderer.IRRADIANCE_TEXTURE_SLOT,u_irradiance_subdivisions:this._irradiance_subdivisions,u_irradiance_color:this.intensity_color,u_irradiance_imatrix:mat4.create(),u_irradiance_distance:0};
this._samplers=[];this.onRecomputingFinished=this.onComputedSphericalHarmonics=this.onPreprocessCubemap=this.onRecomputingIrradiance=null;this.cache_filename="";this._cache_resource=null;a&&(this.configure(a),a.uid&&!this.cache_filename&&(this.cache_filename="IR_cache_"+a.uid.substr(1)+".bin"))}function nc(a,b,c){var e=b||128,g=c||4,d=[];a.forEach(function(a,b){for(var c=[],g=0;g<e;g++)for(var h=0;h<e;h++){var k=2*g/(e-1)-1,t=[];vec3.scale(t,cc[b][0],2*h/(e-1)-1);var u=[];vec3.scale(u,cc[b][1],k);
var k=cc[b][2],H=[];vec3.add(H,t,u);vec3.add(H,H,k);vec3.normalize(H,H);c.push(H)}d.push(c)});var h=[new Float32Array(3),new Float32Array(3),new Float32Array(3),new Float32Array(3),new Float32Array(3),new Float32Array(3),new Float32Array(3),new Float32Array(3),new Float32Array(3)],k=0;a.forEach(function(a,b){var c=!0,m=!0;"[object Float32Array]"===Object.prototype.toString.call(a)&&(m=c=!1);for(var q=0;q<e;q++)for(var s=0;s<e;s++){var t=d[b][q*e+s],u,H=2*(s+0.5)/e-1,G=2*(q+0.5)/e-1,Z=1/e,M=1/e;u=
H-Z;var v=G-M,H=H+Z,G=G+M;u=Mb(u,v)-Mb(u,G)-Mb(H,v)+Mb(H,G);for(var v=4*u/17,G=8*u/17,M=15*u/17,H=5*u/68,Z=15*u/68,w=t[0],y=t[1],t=t[2],r=0;3>r;r++){var x=a[q*e*g+s*g+r];m&&(x/=255);c&&(x=Math.pow(x,2.2));h[0][r]+=x*v;h[1][r]+=x*G*y;h[2][r]+=x*G*t;h[3][r]+=x*G*w;h[4][r]+=x*M*w*y;h[5][r]+=x*M*y*t;h[6][r]+=x*H*(3*t*t-1);h[7][r]+=x*M*w*t;h[8][r]+=x*Z*(w*w-y*y);k+=u}}});a=new Float32Array(3*h.length);for(b=0;b<h.length;b++)a[3*b]=h[b][0]*=4*Math.PI/k,a[3*b+1]=h[b][1]*=4*Math.PI/k,a[3*b+2]=h[b][2]*=4*
Math.PI/k;return a}function Mb(a,b){return Math.atan2(a*b,Math.sqrt(a*a+b*b+1))}function v(a){this.enabled=!0;this.code=this.constructor.templates.script;this._blocked_functions=new Set;this._name="";this._script=new aa;this._script.extra_methods={getComponent:function(a,c){return arguments.length?this._root?this._root.getComponent(a,c):null:this}.bind(this),getLocator:function(){return this.getComponent().getLocator()+"/context"},createProperty:d.BaseComponent.prototype.createProperty,createAction:d.BaseComponent.prototype.createAction,
bind:d.BaseComponent.prototype.bind,unbind:d.BaseComponent.prototype.unbind,trigger:function(a,c){return LEvent.trigger(this,a,c)}.bind(this),unbindAll:d.BaseComponent.prototype.unbindAll};this._script.onerror=this.onError.bind(this);this._script.exported_functions=[];this._breakpoints=this._last_error=null;a&&this.configure(a)}function va(a){this.enabled=!0;this._name=this._filename="";this._script=new aa;this._blocked_functions=new Set;this._script.extra_methods={getComponent:function(){return this}.bind(this),
getLocator:function(){return this.getComponent().getLocator()+"/context"},createProperty:d.BaseComponent.prototype.createProperty,createAction:d.BaseComponent.prototype.createAction,bind:d.BaseComponent.prototype.bind,unbind:d.BaseComponent.prototype.unbind,unbindAll:d.BaseComponent.prototype.unbindAll};this._script.onerror=this.onError.bind(this);this._script.exported_functions=[];this._last_error=null;a&&this.configure(a)}function U(a){this.enabled=!0;this.mode=U.GRID_MODE;this.createProperty("count",
vec3.fromValues(10,1,1));this.createProperty("size",vec3.fromValues(100,100,100));this.material=this.lod_mesh=this.mesh=null;this._custom_matrices=[];a&&this.configure(a);U._identity||(U._identity=mat4.create())}function pa(a){this.only_internal_nodes=this.enabled=!0;this.base_nodes=[];this.poses=[];this._poses_by_name={};a&&this.configure(a)}function qa(a){this.enabled=!0;this._render_in_viewport=!1;this.path=new d.Path;this._must_update=!1;this._subdivisions=20;this.preserve_tangents=!0;a&&this.configure(a);
this._max_points=1024;this._range=0;this._middle_points=new Float32Array(3072)}function jb(a){this.enabled=!0;this.spline="";this.factor=0;this._last_position=vec3.create();this._last_position_inc=vec3.create();this._last_rotation=quat.create();a&&this.configure(a)}function $(a){this.enabled=!0;this.mode=1;this.height=this.width=512;this.texture_name=":canvas3D";this.input_active=this.visible=!0;this.generate_mipmaps=this.use_node_material=!1;this.max_interactive_distance=100;this.high_precision=
!1;this.opacity=1;this._skip_backside=this._clear_buffer=!0;this._standard_material=this._RI=this._fbo=this._texture=null;this._mouse=vec3.create();this._is_mouse_inside=!1;this._local_mouse={mousex:0,mousey:0,buttons:0};this._local_mouse_click={mousex:0,mousey:0};a&&this.configure(a)}function S(a){this._enabled=!0;this._video=document.createElement("video");this._video.muted=!1;this._video.autoplay=!1;this.bindVideoEvents(this._video);this._autoplay=!0;this.generate_mipmaps=!1;this._src="";this._url_loading=
null;this.texture_name=":video";this.render_mode=!0;this._playback_rate=1;this._ignore_proxy=!1;this._texture=null;a&&this.configure(a)}function za(a){this.enabled=!0;this.mode=za.PICKING;this.layers=3;this._last_collision=null;a&&this.configure(a)}function C(){this.uid=d.generateUId("TREE-");this._state=d.STOPPED;this._root=new d.SceneNode("root");this._root.removeAllComponents();this._root._is_root=!0;this._root._in_tree=this;this._nodes=[this._root];this._nodes_by_name={root:this._root};this._nodes_by_uid=
{};this._nodes_by_uid[this._root.uid]=this._root;this._components_by_uid={};this._uniforms={};this._instances=[];this._lights=[];this._cameras=[];this._colliders=[];this._reflection_probes=[];this.external_repository=null;this._spatial_container=new d.SpatialContainer;this.external_scripts=[];this.global_scripts=[];this.preloaded_resources={};this.animation=null;this._local_resources={};this.texture_atlas=null;this.layer_names=["main","secondary"];LEvent.bind(this,"treeItemAdded",this.onNodeAdded,
this);LEvent.bind(this,"treeItemRemoved",this.onNodeRemoved,this);this._shaderblock_info=null;this.init()}function O(a){a&&a.constructor!==String&&(a=null,console.warn("SceneNode constructor first parameter must be a String with the name"));this._name=a||"node_"+(1E4*Math.random()).toFixed(0);this._uid=d.generateUId("NODE-");this._classList={};this.layers=3;this._material=this._prefab=this.node_type=null;this._components=[];this._in_tree=this._children=this._parentNode=null;this._instances=[];this.flags=
{visible:!0,is_static:!1,selectable:!0,locked:!1};this.init(!1,!0)}function ma(a){this.options=a=a||{};if(!a.canvas){var b=a.container;a.container_id&&(b=document.getElementById(a.container_id));b||(console.log("No container specified in LS.Player, using BODY as container"),b=document.body);var c=document.createElement("canvas");c.width=b.offsetWidth;c.height=b.offsetHeight;c.width||(c.width=a.width||1);c.height||(c.height=a.height||1);b.appendChild(c);a.canvas=c}this.skip_play_button=this.autoplay=
this.debug=!1;this.gl=GL.create(a);this.canvas=this.gl.canvas;this.render_settings=new d.RenderSettings;this.scene=d.GlobalScene;this._file_drop_enabled=!1;d.Shaders.init();this.renderer=a.renderer||d.Renderer;this.renderer.init();this.state=d.Player.STOPPED;if(this.gl.ondraw)throw"There is already a litegl attached to this context";this.configure(a);this.gl.ondraw=d.Player.prototype._ondraw.bind(this);this.gl.onupdate=d.Player.prototype._onupdate.bind(this);b=d.Player.prototype._onmouse.bind(this);
this.gl.onmousedown=b;this.gl.onmousemove=b;this.gl.onmouseup=b;this.gl.onmousewheel=b;b=d.Player.prototype._onkey.bind(this);this.gl.onkeydown=b;this.gl.onkeyup=b;b=d.Player.prototype._ontouch.bind(this);this.gl.ontouch=b;b=d.Player.prototype._ongamepad.bind(this);this.gl.ongamepadconnected=b;this.gl.ongamepaddisconnected=b;this.gl.ongamepadButtonDown=b;this.gl.ongamepadButtonUp=b;gl.captureMouse(!a.ignore_scroll);gl.captureKeys(!0);gl.captureTouch(!a.ignore_touch);gl.captureGamepads(!0);d.Input&&
d.Input.init();!1!==a.enableFileDrop&&this.setFileDrop(!0);gl.animate()}(function(a){function b(){}b.classes={};b.HEADER_SIZE=64;b.FOUR_CC="WBIN";b.VERSION=0.3;b.CLASSNAME_SIZE=32;b.LUMPNAME_SIZE=54;b.LUMPHEADER_SIZE=10+b.LUMPNAME_SIZE;b.CODES={ArrayBuffer:"AB",Int8Array:"I1",Uint8Array:"i1",Int16Array:"I2",Uint16Array:"i2",Int32Array:"I4",Uint32Array:"i4",Float32Array:"F4",Float64Array:"F8",Object:"OB",WideObject:"WO",String:"ST",WideString:"WS",Number:"NU","null":"00"};b.REVERSE_CODES={};for(var c in b.CODES)b.REVERSE_CODES[b.CODES[c]]=
c;b.FULL_BINARY=1;b.isWBin=function(a){a=a.subarray(0,4);for(var c=0;c<a.length;c++)if(0!=a[c]&&a[c]!=b.FOUR_CC.charCodeAt(c))return!1;return!0};b.create=function(a,c){if(!a)throw"WBin null origin passed";var d=new Uint8Array([0,0]),h=new Uint8Array((new Float32Array([b.VERSION])).buffer);c=c||"";if(a.toBinary){var k=a.toBinary();if(!k)return null;if(k.constructor==ArrayBuffer){d[0]|=b.FULL_BINARY;var l=b.getObjectClassName(a),n=new Uint8Array(b.HEADER_SIZE+k.length);n.set(b.stringToUint8Array(b.FOUR_CC));
n.set(h,4);n.set(d,8);n.set(b.stringToUint8Array(l,b.CLASSNAME_SIZE),14);n.set(k,b.HEADER_SIZE);return n}a=k}var p=b.HEADER_SIZE,k=[],m=0,q;for(q in a)if(n=a[q],null!=n){if(n.constructor===Blob||n.constructor===File)throw"Wbin does not allow Blobs or Files as data to store, conver to ArrayBuffer";l=b.getObjectClassName(n);(l=b.CODES[l])||(l="OB");"NU"==l?n=new Float64Array([n]):"OB"==l&&(n=JSON.stringify(n));var s=0;n&&n.constructor==String&&(n=b.stringToTypedArray(n),n.constructor===Uint16Array&&
(l="OB"==l?"WO":"WS"));if(n.buffer&&n.buffer.constructor==ArrayBuffer)n=new Uint8Array(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),s=n.byteLength;else if(n.constructor==ArrayBuffer)s=n.byteLength;else throw"WBin: cannot be anything different to ArrayBuffer";var t=q.substring(0,b.LUMPNAME_SIZE);t.length<q.length&&console.error("Lump name is too long (max is "+b.LUMPNAME_SIZE+"), it has been cut down, this could lead to an error in the future");k.push({code:l,name:t,data:n,start:m,size:s});
m+=s;p+=b.LUMPHEADER_SIZE+s}n=new Uint8Array(p);n.set(b.stringToUint8Array(b.FOUR_CC));n.set(h,4);n.set(d,8);n.set(new Uint8Array((new Uint16Array([k.length])).buffer),10);c&&n.set(b.stringToUint8Array(c,b.CLASSNAME_SIZE),12);var d=b.HEADER_SIZE+k.length*b.LUMPHEADER_SIZE,h=b.HEADER_SIZE,u;for(u in k)q=k[u],p=new Uint8Array(b.LUMPHEADER_SIZE),p.set(new Uint8Array((new Uint32Array([q.start])).buffer),0),p.set(new Uint8Array((new Uint32Array([q.size])).buffer),4),p.set(b.stringToUint8Array(q.code,2),
8),p.set(b.stringToUint8Array(q.name,b.LUMPNAME_SIZE),10),n.set(p,h),h+=b.LUMPHEADER_SIZE,p=new Uint8Array(q.data),n.set(p,d+q.start);return n};b.load=function(a,c,d){if(!a||a.constructor!==Uint8Array&&a.constructor!==ArrayBuffer)throw"WBin data must be ArrayBuffer or Uint8Array";a=new Uint8Array(a);var h=b.getHeaderInfo(a);if(!h)return console.error("Wrong WBin Header"),null;h.version>(new Float32Array([b.VERSION]))[0]&&console.log("ALERT: WBin version is higher that code version");a=null;for(var k in h.lumps){a||
(a={});var l=h.lumps[k],n=h.lump_data.subarray(l.start,l.start+l.size);if(l.size!=n.length)throw"WBin: incorrect wbin lump size";var p=null,m=b.REVERSE_CODES[l.code];if(!m)throw"WBin: Incorrect data code";switch(m){case "null":break;case "WideString":n=new Uint16Array((new Uint8Array(n)).buffer);case "String":p=b.TypedArrayToString(n);break;case "Number":p=0.3>h.version?parseFloat(b.TypedArrayToString(n)):(new Float64Array(n.buffer))[0];break;case "WideObject":n=new Uint16Array((new Uint8Array(n)).buffer);
case "Object":(n=b.TypedArrayToString(n))?p=JSON.parse(n):console.warn('WBIN: lump "'+l.name+'" string is empty, skipping.');break;case "ArrayBuffer":p=(new Uint8Array(n)).buffer;break;default:n=new Uint8Array(n);p=b.classes[m]||window[m];if(!p)throw"WBin referenced class not found: "+m;if(0!=n.length/p.BYTES_PER_ELEMENT%1)throw"WBin: size do not match type";p=new p(n.buffer)}a[l.name]=p}if(!c&&h.classname){if((p=b.classes[h.classname]||window[h.classname])&&p.fromBinary)return p.fromBinary(a,d);
if(p&&p.prototype.fromBinary)return c=new p,c.fromBinary(a,d),c;a["@classname"]=h.classname}return a};b.getHeaderInfo=function(a){for(var c=a.subarray(0,4),d=0;d<c.length;d++)if(0!=c[d]&&c[d]!=b.FOUR_CC.charCodeAt(d))return null;for(var c=b.readFloat32(a,4),h=new Uint8Array(a.subarray(8,10)),k=b.readUint16(a,10),l=b.TypedArrayToString(a.subarray(12,12+b.CLASSNAME_SIZE)),n=[],d=0;d<k;++d){var p=b.HEADER_SIZE+d*b.LUMPHEADER_SIZE,p=a.subarray(p,p+b.LUMPHEADER_SIZE),m={};m.start=b.readUint32(p,0);m.size=
b.readUint32(p,4);m.code=b.TypedArrayToString(p.subarray(8,10));m.name=b.TypedArrayToString(p.subarray(10));n.push(m)}a=a.subarray(b.HEADER_SIZE+k*b.LUMPHEADER_SIZE);return{version:c,flags:h,classname:l,numlumps:k,lumps:n,lump_data:a}};b.getObjectClassName=function(a){if(a&&a.constructor&&a.constructor.toString&&(a=a.constructor.toString().match(/function\s*(\w+)/))&&2==a.length)return a[1]};b.stringToUint8Array=function(a,b){for(var c=new Uint8Array(b?b:a.length),d=!1,k=0;k<a.length;k++){var l=a.charCodeAt(k);
255<l&&(d=!0);c[k]=l}d&&console.warn("WBin: there are characters in the string that cannot be encoded in 1 byte.");return c};b.TypedArrayToString=function(a,b){for(var c="",d=0;d<a.length;d++)if(0!=a[d]||b)c+=String.fromCharCode(a[d]);else break;return c};b.stringToTypedArray=function(a,b){for(var c=new Uint8Array(b?b:a.length),d=!1,k=0;k<a.length;k++){var l=a.charCodeAt(k);255<l&&(d=!0);c[k]=l}if(!d)return c;c=new Uint16Array(b?b:a.length);for(k=0;k<a.length;k++)l=a.charCodeAt(k),c[k]=l;return c};
b.readUint16=function(a,b){return(new DataView(a.buffer,a.byteOffset)).getUint16(b,!0)};b.readUint32=function(a,b){return(new DataView(a.buffer,a.byteOffset)).getUint32(b,!0)};b.readFloat32=function(a,b){return(new DataView(a.buffer,a.byteOffset)).getFloat32(b,!0)};a.WBin=b})("undefined"!=typeof da?da:this);aa.onerror=null;aa.eval=function(a,b){return eval("(function("+a+"){\n"+b+"\n})")};aa.catch_exceptions=!1;aa.show_errors_in_console=!0;aa.prototype.compile=function(a,b){var c=[],e=[];if(a)for(var d in a)c.push(d),
e.push(a[d]);var c=c.join(","),f=this.code,f=aa.expandCode(f),h="";for(d in this.exported_callbacks)var k=this.exported_callbacks[d],h=h+("\tif(typeof("+k+") != 'undefined' && "+k+' != window["'+k+'"] ) this.'+k+" = "+k+";\n");this._last_executed_code=f+=h;h=this._context;if(aa.catch_exceptions)try{this._class=new Function(c,f),n=aa.applyToConstructor(this._class,e,this.extra_methods),this._context=new n}catch(l){this._class||console.error("Parsing error in script\n"+l);this._context=this._class=
null;aa.show_errors_in_console&&(c=aa.computeLineFromError(l),console.error("Error in script\n"+l),console.groupCollapsed?(console.groupCollapsed("Error line: "+c+" Watch code"),aa.showCodeInConsole(this._last_executed_code,c),console.groupEnd()):console.error("Error line: "+c));if(this.onerror)this.onerror(l,this._last_executed_code);if(aa.onerror)aa.onerror(l,this._last_executed_code,this);return!1}else{this._class=new Function(c,f);var n=aa.applyToConstructor(this._class,e,this.extra_methods);
this._context=new n}if(b&&h)for(d in h)void 0===this._context[d]||!h[d]||h[d].constructor===Function||this._context[d]&&this._context[d].constructor===Function||(this._context[d]=h[d]);return!0};aa.prototype.hasMethod=function(a){return this._context&&this._context[a]&&"function"==typeof this._context[a]?!0:!1};aa.prototype.callMethod=function(a,b,c,e){if(this._context&&this._context[a]){if(!aa.catch_exceptions)return b&&b.constructor===Array&&c?this._context[a].apply(this._context,b):this._context[a].call(this._context,
b);try{return b&&b.constructor===Array&&c?this._context[a].apply(this._context,b):this._context[a].call(this._context,b)}catch(d){if(b=aa.computeLineFromError(d),c="",e&&e.toInfoString&&(c=" from "+e.toInfoString()),console.error("Error from function "+a+c+": ",d.toString()),console.groupCollapsed?(console.groupCollapsed("Error line: "+b+" Watch code"),aa.showCodeInConsole(this._last_executed_code,b),console.groupEnd()):console.error("Error line: "+b),this.onerror)this.onerror({error:d,msg:d.toString(),
line:b,lscript:this,code:this._last_executed_code,method_name:a})}}};aa.applyToConstructor=function(a,b,c){b=[null].concat(b);if(c)for(var e in c)Object.defineProperty(a.prototype,e,{value:c[e],enumerable:!0});return a.bind.apply(a,b)};aa.showCodeInConsole=function(a,b){if(a)for(var c=a.split("\n"),e=0;e<c.length;e++)e==b?console.log("%c "+e+". "+c[e],"background-color: #A33; color: #FAA;"):console.log("%c "+e+". ","display: inline-block; width: 40px; background-color:#999; color: white;",c[e])};
aa.cleanCode=function(a){if(!a)return"";a=a.replace(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/g,"");a=a.split("\n");for(var b=[],c=0;c<a.length;++c){var e=a[c],d=e.indexOf("//");-1!=d&&-1==e.substr(0,d).indexOf('"')&&(e=e.substr(0,d));e=e.trim();e.length&&b.push(e)}return b.join("\n")};aa.expandCode=function(a){if(!a)return"";if(-1!=a.indexOf("'''")){var b=a.split("'''");a="";for(var c=0;c<b.length;c++)a=0==c%2?a+b[c]:a+('"'+b[c].split("\n").join("\\n\\\n")+'"')}for(var b=a.split("\n"),e=!1,c=0;c<
b.length;++c){var g=b[c].trim(),f=g.indexOf(" "),f=g.substr(0,f);if("public"==f||"private"==f||"hidden"==f)if(f=g.indexOf("//"),-1!=f&&(g=g.substr(0,f)),f=g.lastIndexOf(";"),-1!=f&&(g=g.substr(0,f)),"var"==g.split(" ")[1]){var h=g,g=null,f="undefined",k=h.indexOf("=");-1!=k&&(f=h.substr(k+1).trim(),h=h.substr(0,k).trim());k=h.indexOf(":");-1!=k&&(g=h.substr(k+1).trim(),h=h.substr(0,k).trim());h=h.split(" ");if(k=h[2]){e={};if(g){var l=g.indexOf("[]");-1!=l?(e.type=d.TYPES.ARRAY,e.data_type=g.substr(0,
l),f&&"undefined"!==f||(f="[]")):e.type=g;if(d.Components[g])e.component_class=g,e.type=d.TYPES.COMPONENT,f||(f="null");else if(d.ResourceClasses[g])e.resource_classname=g,e.type=d.TYPES.RESOURCE,f||(f="null");else if("int"==g||"integer"==g)e.step=1,e.type=d.TYPES.NUMBER,f||(f=0)}if("private"==h[0]||"hidden"==h[0])e.widget="null";b[c]="this.createProperty('"+k+"',"+f+", "+JSON.stringify(e)+" );";e=!0}}}e&&(a=b.join("\n"));return a};aa.computeLineFromError=function(a){if(void 0!==a.lineNumber)return a.lineNumber;
if(a.stack){a=a.stack.split("\n")[1].trim();if(-1!=a.indexOf("(native)"))return-1;var b=a.split(" "),c=a.lastIndexOf(":"),e=a.lastIndexOf(":",c-1),e=parseInt(a.substr(e+1,c-e-1));parseInt(a.substr(c+1,a.length-2-c));if("Object.CodingModule.eval"==b[1])return-1;if(-1!=a.indexOf("LScript")||-1!=a.indexOf("<anonymous>"))e-=3;return e}return-1};da.LScript=aa;Uint8Array.prototype.toJSON||[Uint8Array,Int8Array,Uint16Array,Int16Array,Uint32Array,Int32Array,Float32Array,Float64Array].forEach(function(a){a.prototype.toJSON=
function(){return Array.prototype.slice.call(this)}});"undefined"===typeof GL&&console.error("LiteScene requires to include LiteGL first. More info: https://github.com/jagenjo/litegl.js");var d={ResourcesManager:null,Picking:null,Player:null,GUI:null,Network:null,Input:null,Renderer:null,Physics:null,ShadersManager:null,Formats:null,Tween:null,Classes:{},ResourceClasses:{},ResourceClasses_by_extension:{},Globals:{},Components:{},MaterialClasses:{},_last_uid:1,_uid_prefix:"@",debug:!1,allow_static:!0,
allow_scripts:!0,_gui_element:null,_gui_style:null,generateUId:function(a,b){b=b||"";var c=this._uid_prefix+(a||"")+(window.navigator.userAgent.hashCode()%16777216).toString(16)+"-",c=c+((GL.getTime()|0).toString(16)+"-"),c=c+(Math.floor(16777216*(1+Math.random())).toString(16)+"-"),c=c+(this._last_uid++).toString(16);return c+b},validateName:function(a){return a.match(/^[a-z\s0-9-_.]+$/i)},valid_property_types:"String Number Boolean color vec2 vec3 vec4 quat mat3 mat4 Resource Animation Texture Prefab Mesh ShaderCode node component".split(" "),
validatePropertyType:function(a){return-1==this.valid_property_types.indexOf(a)?(console.error(a+" is not a valid property value type."),!1):!0},_catch_exceptions:!1,registerComponent:function(a,b){var c=d.getClassName(a);if(b&&b.constructor!==String)throw"old_classname must be null or a String";this.Components[c]=a;a.is_component=!0;a.resource_type="Component";!!a.prototype.onAddedToNode==!!a.prototype.onRemovedFromNode&&!!a.prototype.onAddedToScene==!!a.prototype.onRemovedFromScene||console.warn("%c Component "+
c+" could have a bug, check events: "+c,"font-size: 2em");a.prototype.getResources&&!a.prototype.onResourceRenamed&&console.warn("%c Component "+c+" could have a bug, it uses resources but doesnt implement onResourceRenamed, this could lead to problems when resources are renamed.","font-size: 1.2em");a.actions||(a.actions={});d.extendClass(a,d.BaseComponent);Oa.addExtraMethods(a);d.debug&&((new a).serialize().object_class||console.warn("%c Component "+c+" could have a bug, serialize() method has object_class missing.",
"font-size: 1.2em"));LEvent.trigger(d,"component_registered",a);d.GlobalScene&&(this.replaceComponentClass(d.GlobalScene,b||c,c),b!=c&&this.unregisterComponent(b))},unregisterComponent:function(a){this.Components[a]&&delete this.Components[a]},isClassComponent:function(a){a=this.getClassName(a);return!!this.Components[a]},replaceComponentClass:function(a,b,c){var e=c.constructor===String?d.Components[c]:c;if(!e)return 0;var g=null;b.constructor===String&&(g=d.Components[b])&&(b=d.getClassName(g));
for(var f=g=0;f<a._nodes.length;++f)for(var h=a._nodes[f],k=0;k<h._components.length;++k){var l=h._components[k],n=l.constructor===d.MissingComponent?l._comp_class:d.getObjectClassName(l);if(l.constructor!==e&&(n==b||n==c)){n=l.serialize();h.removeComponent(l);l=null;try{l=new e}catch(p){console.error("Error in replacement component constructor");console.error(p);continue}h.addComponent(l,k<h._components.length?k:void 0);l.configure(n);g++}}return g},registerResourceClass:function(a){var b=d.getClassName(a);
this.ResourceClasses[b]=a;this.Classes[b]=a;a.is_resource=!0;a.EXTENSION&&(this.ResourceClasses_by_extension[a.EXTENSION.toLowerCase()]=a);a.FORMAT&&(a.FORMAT.extension&&(this.ResourceClasses_by_extension[a.FORMAT.extension.toLowerCase()]=a,a.EXTENSION=a.FORMAT.extension),a.FORMAT.resource_ctor=a,a.FORMAT.resource=d.getClassName(a),d.Formats&&(d.Formats.supported[a.FORMAT.extension.toLowerCase()]=a.FORMAT))},coroutines:{},addWaitingCoroutine:function(a,b){b=b||"render";var c=this.coroutines[b];c||
(c=this.coroutines[b]=[]);c.push(a)},triggerCoroutines:function(a,b){var c=this.coroutines[a||"render"];if(c){for(var e=0;e<c.length;++e)d.safeCall(c[e],b);c.length=0}},createCoroutine:function(a){return new Promise(function(b){d.addWaitingCoroutine(b,a)})},sleep:function(a){return new Promise(function(b){setTimeout(b,a)})},nextFrame:function(a){a||d.GlobalScene.requestFrame();return new Promise(function(a){d.addWaitingCoroutine(a,"render")})},safeCall:function(a,b,c){if(!d.catch_exceptions)return c?
a.apply(c,b):a(b);try{return a.apply(c,b)}catch(e){LEvent.trigger(d,"exception",e),console.error(e.stack)}},setTimeout:function(a,b){if(!d.catch_exceptions)return setTimeout(a,b);try{return setTimeout(a,b)}catch(c){LEvent.trigger(d,"exception",c)}},setInterval:function(a,b){if(!d.catch_exceptions)return setInterval(a,b);try{return setInterval(a,b)}catch(c){LEvent.trigger(d,"exception",c)}},extendClass:function(a,b){for(var c in b)a.hasOwnProperty(c)||(a[c]=b[c]);if(b.prototype)for(c in b.prototype)b.prototype.hasOwnProperty(c)&&
!a.prototype.hasOwnProperty(c)&&(b.prototype.__lookupGetter__(c)?a.prototype.__defineGetter__(c,b.prototype.__lookupGetter__(c)):a.prototype[c]=b.prototype[c],b.prototype.__lookupSetter__(c)&&a.prototype.__defineSetter__(c,b.prototype.__lookupSetter__(c)))},cloneObject:function(a,b,c,e,g){if(void 0!==a){if(null===a)return null;switch(a.constructor){case String:case Number:case Boolean:return a}if(a.constructor.BYTES_PER_ELEMENT){if(!b)return new a.constructor(a);if(b.set)b.set(a);else if(b.construtor===
Array)for(var f=0;f<a.length;++f)b[f]=a[f];else throw"cloneObject: target has no set method";return b}var h=b;if(void 0===h||null===h)h=a.constructor===Array?[]:{};for(f in a)if("@"!=f[0]&&"_"!=f[0]&&"jQuery"!=f.substr(0,6)&&(!e||b.hasOwnProperty(f)||b.__proto__.hasOwnProperty(f))){var k=a[f];if(null==k)h[f]=null;else if(!isFunction(k))if(k.constructor===File)h[f]=null;else if(k.constructor===Number||k.constructor===String||k.constructor===Boolean)h[f]=k;else if(k.buffer&&k.byteLength&&k.buffer.constructor===
ArrayBuffer)h[f]&&k&&e?h[f].length==k.length&&h[f].set(k):h[f]=new k.constructor(k);else if(k.constructor===Array)if(h[f]&&h[f].set&&h[f].length>=k.length)h[f].set(k);else if(g&&b&&"@ENC"==k[0]){var l=d.decodeObject(k);(h[f]=l)||(d._pending_encoded_objects?d._pending_encoded_objects.push([h,f,k]):console.warn("Object UID referencing object not found in the scene:",k[2]))}else h[f]=d.cloneObject(k);else if(k.constructor.is_resource)console.error("Resources cannot be saved as a property of a component nor script, they must be saved individually as files in the file system. If assigning them to a component/script use private variables (name start with underscore) to avoid being serialized.");
else if(g&&!b)h[f]=d.encodeObject(k);else if(k.constructor===Object||b||k.toJSON)if(k.toJSON)h[f]=k.toJSON();else if(c)h[f]=d.cloneObject(k,null,!0);else if(k.constructor!==Object&&d.Classes[d.getObjectClassName(k)]&&console.warn("Cannot clone internal classes:",d.getObjectClassName(k)," When serializing an object I found a var with a class that doesnt support serialization. If this var shouldnt be serialized start the name with underscore.'"),d.catch_exceptions)try{h[f]=JSON.parse(JSON.stringify(k))}catch(n){console.error(n)}else h[f]=
JSON.parse(JSON.stringify(k));else console.warn("Cannot clone internal classes:",d.getObjectClassName(k)," When serializing an object I found a var with a class that doesnt support serialization. If this var shouldnt be serialized start the name with underscore.'")}return h}},encodeObject:function(a){if(!a||a.constructor===Number||a.constructor===String||a.constructor===Boolean||a.constructor===Object)return a;if(a.constructor.is_component&&a._root)return["@ENC",d.TYPES.COMPONENT,a.getLocator(),d.getObjectClassName(a)];
if(a.constructor==d.SceneNode&&a._in_tree)return["@ENC",d.TYPES.SCENENODE,a.uid];if(a.constructor==d.Scene)return["@ENC",d.TYPES.SCENE,a.fullpath];if(a.serialize||a.toJSON)return["@ENC",d.TYPES.OBJECT,a.serialize?a.serialize():a.toJSON(),d.getObjectClassName(a)];console.warn("Cannot clone internal classes:",d.getObjectClassName(a)," When serializing an object I found a property with a class that doesnt support serialization. If this property shouldn't be serialized start the name with underscore.'");
return null},decodeObject:function(a){if(!a||a.constructor!==Array||"@ENC"!=a[0])return null;switch(a[1]){case d.TYPES.COMPONENT:case "node":case d.TYPES.SCENENODE:return(a=Na.get(a[2]))?a:null;case d.TYPES.SCENE:return null;default:if(!a[2]||!a[2].object_class)return null;var b=d.Classes[a[2].object_class];if(!b)return null;b=new b;b.configure(a[2]);return b}},resolvePendingEncodedObjects:function(){if(d._pending_encoded_objects){for(var a=0;a<d._pending_encoded_objects.length;++a){var b=d._pending_encoded_objects[a],
c=d.decodeObject(b[2]);c?b[0][b[1]]=c:console.warn("Decoded object not found when configuring from JSON")}d._pending_encoded_objects=null}else console.warn("no pending enconded objects")},clearUIds:function(a,b){b=b||{};a.uid&&(b[a.uid]=a,delete a.uid);a.material&&a.material.uid&&(b[a.material.uid]=a.material,delete a.material.uid);var c=a.components;!c&&a.getComponents&&(c=a.getComponents());if(c){if(c)for(var e in c){var g=c[e];g[1].uid&&(b[g[1].uid]=g[1],delete g[1].uid);g[1]._uid&&(b[g[1]._uid]=
g[1],delete g[1]._uid)}c=a.children;!c&&a.getChildren&&(c=a.getChildren());if(c){for(e in c)d.clearUIds(c[e],b);return b}}},getObjectClassName:function(a){if(a){if(a.constructor.fullname)return a.constructor.fullname;if(a.constructor.name)return a.constructor.name;if((a=a.constructor.toString().match(/function\s*(\w+)/))&&2==a.length)return a[1]}},getClassName:function(a){if(a){if(a.name)return a.name;if(a.toString&&(a=a.toString().match(/function\s*(\w+)/))&&2==a.length)return a[1]}},getObjectProperties:function(a){if(a.getPropertiesInfo)return a.getPropertiesInfo();
var b=a.constructor;if(b.properties)return b.properties;var c={},e;for(e in a)if("_"!=e[0]&&"@"!=e[0]&&"jQuery"!=e.substr(0,6)){if(b!=Object){var g=b["@"+e];if(g&&g.type){c[e]=g.type;continue}}g=a[e];null==g?c[e]=null:isFunction(g)||(c[e]=g.constructor===Boolean?d.TYPES.BOOLEAN:g.constructor===Number?d.TYPES.NUMBER:g.constructor===String?d.TYPES.STRING:g.buffer&&g.buffer.constructor===ArrayBuffer?2==g.length?d.TYPES.VEC2:3==g.length?d.TYPES.VEC3:4==g.length?d.TYPES.VEC4:9==g.length?d.TYPES.MAT3:16==
g.length?d.TYPES.MAT4:0:0)}return c},setObjectProperty:function(a,b,c){if(a.setProperty)return a.setProperty(b,c);a[b]=c;if(a.onPropertyChanged)a.onPropertyChanged(b,c)},registerMaterialClass:function(a){var b=d.getClassName(a);this.MaterialClasses[b]=a;this.Classes[b]=a;d.extendClass(a,B);LEvent.trigger(d,"materialclass_registered",a);a.resource_type="Material";a.is_material=!0},getScript:function(a){return(a=d.Script.active_scripts[a])?a.context:null},dispatchCodeError:function(a,b,c,e){a={error:a,
line:b,resource:c,extra:e};console.error(a);LEvent.trigger(this,"code_error",a)},convertToString:function(a){if(!a)return"";if(a.constructor===String)return a;if(a.constructor===Object)return JSON.stringify(object.serialize?object.serialize():object);a.constructor===ArrayBuffer&&(a=new Uint8Array(a));return String.fromCharCode.apply(null,a)},checkLocatorBelongsToPrefab:function(a,b){b=b||d.GlobalScene.root;var c=a.split("/");return c.length?(c=Na.get(c[0],b))?c.insidePrefab():null:null},convertLocatorFromUIDsToName:function(a,
b,c){c=c||d.GlobalScene.root;a=a.split("/");if(!a.length||a[0][0]!==d._uid_prefix&&(1==a.length||a[1][0]!==d._uid_prefix))return null;c=Na.get(a[0],c);if(!c)return console.warn("getIDasName: node not found in LS.GlobalScene: "+a[0]),!1;if(!c.name)return console.warn("getIDasName: node without name?"),!1;if(1<a.length&&a[1][0]==d._uid_prefix){var e=d.GlobalScene.findComponentByUId(a[1]);if(e){var g=e.constructor.name;if("Script"==g||"ScriptFromFile"==g)g=e.name,"unnamed"==g&&(console.error("converting component UIDs to component name, but property belongs to a Script without name. You must name the script to avoid errors."),
g=e.constructor.name);a[1]=g}}a=a.concat();a[0]=b?c.name:c.fullname;return a.join("/")},reset:function(){d.GlobalScene.clear();d.ResourcesManager.reset();LEvent.trigger(d,"reset")},log:function(){console.log.apply(console,arguments)},stringToValue:function(a){var b=a;try{b=JSON.parse(a)}catch(c){console.error("Not a valid value: "+a)}return b},isValueOfType:function(a,b){if(null===a||void 0===a){switch(b){case "float":case "sampler2D":case "samplerCube":case d.TYPES.NUMBER:case d.TYPES.VEC2:case d.TYPES.VEC3:case d.TYPES.VEC4:case d.TYPES.COLOR:case d.TYPES.COLOR4:case "mat3":case "mat4":return!1}return!0}switch(b){case "float":case "sampler2D":case "samplerCube":case d.TYPES.NUMBER:return isNumber(a);
case d.TYPES.VEC2:return 2===a.length;case d.TYPES.VEC3:return 3===a.length;case d.TYPES.VEC4:return 4===a.length;case d.TYPES.COLOR:return 3===a.length;case d.TYPES.COLOR4:return 4===a.length;case "mat3":return 9===a.length;case "mat4":return 16===a.length}return!0},queryString:function(){for(var a={},b=window.location.search.substring(1).split("&"),c=0;c<b.length;c++){var e=b[c].split("=");if("undefined"===typeof a[e[0]])a[e[0]]=decodeURIComponent(e[1]);else if("string"===typeof a[e[0]]){var d=
[a[e[0]],decodeURIComponent(e[1])];a[e[0]]=d}else a[e[0]].push(decodeURIComponent(e[1]))}return a}(),downloadFile:function(a,b,c){if(b){c||(c=b.constructor===String?"text/plain":"application/octet-stream");var e=null,e=b.constructor!==File&&b.constructor!==Blob?new Blob([b],{type:c}):b,d=URL.createObjectURL(e);b=document.createElement("a");b.setAttribute("href",d);b.setAttribute("download",a);b.style.display="none";document.body.appendChild(b);b.click();document.body.removeChild(b);setTimeout(function(){URL.revokeObjectURL(d)},
6E4)}else console.warn("No file provided to download")}};Object.defineProperty(d,"catch_exceptions",{set:function(a){this._catch_exceptions=a;aa.catch_exceptions=a;aa.catch_important_exceptions=a},get:function(){return this._catch_exceptions},enumerable:!0});Object.defineProperty(d,"block_scripts",{set:function(a){d._block_scripts=a;aa.block_execution=a},get:function(){return!!d._block_scripts},enumerable:!0});d.Classes.WBin=d.WBin=da.WBin=WBin;Na.set=function(a,b,c,e){e=e||d.GlobalScene;if(!c)e.setPropertyValue(a,
b);else if(c.constructor===d.SceneNode)return a=a.split("/"),(c=c.findNodeByUId(a[0]))?c.setPropertyValueFromPath(a.slice(1),b):null;e.requestFrame()};Na.get=function(a,b,c){if(!a)return null;c=c||d.GlobalScene;var e;if(!b)e=c.getPropertyInfo(a);else if(b.constructor===d.SceneNode){a=a.split("/");b=b.findNodeByUId(a[0]);if(!b)return null;e=b.getPropertyInfoFromPath(a.slice(1))}return e?e.value:null};Na.shortify=function(a,b){if(a){var c=a.split("/"),e=null;if(c[0][0]!=d._uid_prefix)return a;b=b||
d.GlobalScene;e=b._nodes_by_uid[c[0]];if(!e)return a;c[0]=e.getPathName();c[1]&&c[1][0]==d._uid_prefix&&(e=e.getComponentByUId(c[1]))&&(c[1]=d.getObjectClassName(e));return c.join("/")}};Na.setFromInfo=function(a,b){if(a&&a.target){var c=a.target;if(c.setPropertyValue&&!0===c.setPropertyValue(a.name,b))return c;void 0!==c[a.name]&&(c[a.name]=b)}};Na.getFromInfo=function(a){if(a&&a.target){var b=a.target;a=a.name;var c=void 0;b.getPropertyValue&&(c=b.getPropertyValue(a));return void 0===c&&void 0===
b[a]?null:void 0!==c?c:b[a]}};da.GL&&(GL.Mesh.EXTENSION="wbin",GL.Texture.EXTENSION="png",d.registerResourceClass(GL.Mesh),d.registerResourceClass(GL.Texture),d.Mesh=GL.Mesh,d.Texture=GL.Texture,d.Buffer=GL.Buffer);da.LSQ=Na;if("undefined"==typeof GL)throw"LiteSCENE requires to have litegl.js included before litescene.js";var bb={AUTOMATIC:1,NORMAL:2,ALPHA:3,ADD:4,MULTIPLY:5,SCREEN:6,CUSTOM:7};d.Blend=bb;d.BlendFunctions={};d.BlendFunctions[bb.AUTOMATIC]=[GL.ONE,GL.ZERO];d.BlendFunctions[bb.NORMAL]=
[GL.ONE,GL.ZERO];d.BlendFunctions[bb.ALPHA]=[GL.SRC_ALPHA,GL.ONE_MINUS_SRC_ALPHA];d.BlendFunctions[bb.ADD]=[GL.SRC_ALPHA,GL.ONE];d.BlendFunctions[bb.MULTIPLY]=[GL.DST_COLOR,GL.ONE_MINUS_SRC_ALPHA];d.BlendFunctions[bb.SCREEN]=[GL.SRC_ALPHA,GL.ONE];d.BlendFunctions[bb.CUSTOM]=[GL.SRC_ALPHA,GL.ONE_MINUS_SRC_ALPHA];d.NONE=0;d.LINEAR=1;d.TRIGONOMETRIC=2;d.CUBIC=3;d.SPLINE=4;d.BEZIER=5;d.HERMITE=6;d.STOPPED=0;d.PLAYING=1;d.PAUSED=2;d.LOADING=3;d.RUNNING=1;d.ZEROS=vec3.create();d.ZEROS4=vec4.create();d.ONES=
vec3.fromValues(1,1,1);d.TOP=vec3.fromValues(0,1,0);d.BOTTOM=vec3.fromValues(0,-1,0);d.RIGHT=vec3.fromValues(1,0,0);d.LEFT=vec3.fromValues(-1,0,0);d.FRONT=vec3.fromValues(0,0,-1);d.BACK=vec3.fromValues(0,0,1);d.IDENTITY=mat4.create();d.QUAT_IDENTITY=quat.create();d.WHITE=d.ONES;d.BLACK=d.ZEROS;d.POSX=1;d.POSY=2;d.POSZ=3;d.NEGX=4;d.NEGY=5;d.NEGZ=6;d.TYPES={BOOLEAN:"boolean",NUMBER:"number",STRING:"string",VEC2:"vec2",VEC3:"vec3",VEC4:"vec4",COLOR:"color",COLOR4:"color4",EVENT:"event",RESOURCE:"resource",
TEXTURE:"texture",MESH:"mesh",OBJECT:"object",SCENE:"scene",NODE:"node",SCENENODE:"node",SCENENODE_ID:"node_id",COMPONENT:"component",COMPONENT_ID:"component_id",MATERIAL:"material",ANIMATION:"animation",ARRAY:"array",QUAT:"quat",TRANS10:"trans10",POSITION:"position"};d.TYPES_INDEX={};var dc=0,Nb;for(Nb in d.TYPES)d.TYPES_INDEX[d.TYPES[Nb]]=dc,d.TYPES_INDEX[d.TYPES[Nb].toUpperCase()]=dc,dc++;d.RESOURCE_TYPES={};d.RESOURCE_TYPES[d.TYPES.RESOURCE]=!0;d.RESOURCE_TYPES[d.TYPES.TEXTURE]=!0;d.RESOURCE_TYPES[d.TYPES.MESH]=
!0;d.RESOURCE_TYPES[d.TYPES.ANIMATION]=!0;var y=d.EVENT={};d.Ray=GL.Ray;d.Network={default_dataType:"arraybuffer",protocol:null,withCredentials:!1,request:function(a){if("string"===typeof a)throw"LS.Network.request expects object, not string. Use LS.Network.requestText or LS.Network.requestJSON";var b=a.url;a.use_proxy&&(b=d.ResourcesManager.getFullURL(b));null===this.protocol&&(this.protocol=d.ResourcesManager.getProtocol(location.href));var c=d.ResourcesManager.getProtocol(b);"https"==this.protocol&&
c&&"https"!=c&&(b="https"+b.substr(b.indexOf(":")));c=a.dataType||this.default_dataType;if("json"==c)c="text";else if("xml"==c)c="text";else if("binary"==c)c="arraybuffer",a.mimeType="application/octet-stream";else if("image"==c)return c=new Image,c.onload=function(){a.success&&a.success.call(this)},c.onerror=a.error,c.src=b,c;var e=new XMLHttpRequest;e.open(a.method||(a.data?"POST":"GET"),b,!0);e.withCredentials=this.withCredentials;void 0!==a.withCredentials&&(e.withCredentials=a.withCredentials);
c&&(e.responseType=c);a.mimeType&&e.overrideMimeType(a.mimeType);a.nocache&&e.setRequestHeader("Cache-Control","no-cache");e.onload=function(c){c=this.response;if(this.status&&200!=this.status)c="Error "+this.status,a.error&&a.error(c);else{if("json"==a.dataType)try{c=JSON.parse(c)}catch(f){a.error&&a.error(f)}else if("xml"==a.dataType)try{c=(new DOMParser).parseFromString(c,"text/xml")}catch(h){a.error&&a.error(h)}else"blob"==a.dataType&&(c.name=d.ResourcesManager.getFilename(b));if(d.catch_errors)try{a.success&&
a.success.call(this,c,a.url),LEvent.trigger(e,"done",c)}catch(k){LEvent.trigger(d,"code_error",k)}else a.success&&a.success.call(this,c,a.url),LEvent.trigger(e,"done",c)}};e.onerror=function(b){a.error&&a.error(b);LEvent.trigger(this,"fail",b)};a.uploadProgress&&e.upload.addEventListener("progress",function(b){var c=0;b.lengthComputable&&(c=b.loaded/b.total);a.uploadProgress(b,c)},!1);a.progress&&e.addEventListener("progress",function(b){var c=0;b.lengthComputable&&(c=b.loaded/b.total);a.progress(b,
c)});e.send(a.data);return e},requestText:function(a,b,c,e){"function"==typeof b&&(e=c,c=b);return d.Network.request({url:a,dataType:"text",success:c,error:e})},requestJSON:function(a,b,c,e){"function"==typeof b&&(e=c,c=b,b=null);return d.Network.request({url:a,data:b,dataType:"json",success:c,error:e})},requestFile:function(a,b,c,e,g){"function"==typeof b&&(e=c,c=b,b=null);return d.Network.request({url:a,dataType:g?"blob":"binary",data:b,success:c,error:e})},requestScript:function(a,b,c,e){if(!a)throw"No url";
if(d._block_scripts)console.error("Safety: LS.block_scripts enabled, cannot request script");else{a.constructor===String&&(a=[a]);var g=a.length,f;for(f in a){var h=document.createElement("script");h.num=f;h.type="text/javascript";h.src=a[f];h.async=!1;h.charset="UTF-8";h.onload=function(a){g--;g?e&&e(this.src,this.num):b&&b()};c&&(h.onerror=function(a){c(a,this.src,this.num)});document.getElementsByTagName("head")[0].appendChild(h)}}},requestFont:function(a,b){if(!a||!b)throw"LS.Network.requestFont: Wrong font name or url";
var c=this._loaded_fonts;c||(c=this._loaded_fonts={});if(c[a]!=b){c[a]=b;var e=document.getElementById("ls_fonts");e||(e=document.createElement("style"),e.id="ls_fonts",e.setAttribute("type","text/css"),document.head.appendChild(e));var d="",f;for(f in c)b=c[f],d+='@font-face {\n\tfont-family: "'+f+"\";\n\tsrc: url('"+b+"');\n}\n";e.innerHTML=d}}};Object.defineProperty(MouseEvent.prototype,"getRay",{value:function(){var a=d.Renderer.getCameraAtPosition(this.mousex,this.mousey,d.Renderer._visible_cameras);
return a?a.getRay(this.mousex,this.mousey):null},enumerable:!1});d.Input={mapping:{A_BUTTON:0,B_BUTTON:1,X_BUTTON:2,Y_BUTTON:3,LB_BUTTON:4,RB_BUTTON:5,BACK_BUTTON:6,START_BUTTON:7,LS_BUTTON:8,RS_BUTTON:9,LX:0,LY:1,RX:2,RY:3,TRIGGERS:4,LEFT_TRIGGER:4,RIGHT_TRIGGER:5,JUMP:0,FIRE:1,LEFT:0,MIDDLE:1,RIGHT:2},LEFT_MOUSE_BUTTON:1,MIDDLE_MOUSE_BUTTON:2,RIGHT_MOUSE_BUTTON:3,Keyboard:[],Keyboard_previous:[],Mouse:{},Gamepads:[],last_mouse:null,last_click:null,current_click:null,current_key:null,keys_buffer:[],
_last_frame:-1,init:function(){this.Keyboard=gl.keys;this.Mouse=gl.mouse;this.Gamepads=gl.getGamepads()},reset:function(){this.Gamepads=gl.gamepads=[]},update:function(){for(var a=0,b=this.Keyboard.length;a<b;++a)this.Keyboard_previous[a]=this.Keyboard[a];this.Mouse.last_buttons=this.Mouse.buttons;this.Gamepads=gl.getGamepads()},isKeyPressed:function(a){return!!this.Keyboard[a]},wasKeyPressed:function(a){return this.Keyboard[a]&&!this.Keyboard_previous[a]},isMouseButtonPressed:function(a){var b=0,
b=a&&a.constructor===String?this.mapping[a]:a;return void 0===a?!1:this.Mouse.isButtonPressed(b)},wasMouseButtonPressed:function(a){var b=0,b=a&&a.constructor===String?this.mapping[a]:a;return void 0===a?!1:this.Mouse.wasButtonPressed(b)},lockMouse:function(a){a?gl.canvas.requestPointerLock():document.exitPointerLock()},isMouseLocked:function(){return!!document.pointerLockElement},onMouse:function(a){this.last_mouse=a;this.isMouseLocked()&&(a.canvasx=a.mousex=0.5*gl.canvas.width|0,a.canvasy=a.mousey=
0.5*gl.canvas.height|0);this.Mouse.x=this.Mouse.mousex=a.mousex;this.Mouse.y=this.Mouse.mousey=a.mousey;this.Mouse.canvasx=a.canvasx;this.Mouse.canvasy=a.canvasy;"mousedown"==a.type?(this.current_click=a,d.triggerCoroutines("click",a)):"mouseup"==a.type&&(this.current_click=null);return d.GUI.testEventInBlockedArea(a)},onKey:function(a){"keydown"==a.type?(this.current_key=a,d.Renderer._frame!=this._last_frame&&(this.keys_buffer.length=0,d.Renderer._frame=this._last_frame),10>this.keys_buffer.length&&
this.keys_buffer.push(a)):this.current_key=null},isMouseInRect:function(a,b,c,e,d){return this.Mouse.isInsideRect(a,b,c,e,d)},isEventInRect:function(a,b,c){var e=null!=a.mousex?a.mousex:a.x;a=null!=a.mousey?a.mousey:a.y;c&&(e-=c[0],a-=c[1]);return e>=b[0]&&e<b[0]+b[2]&&a>=b[1]&&a<b[1]+b[3]},getAxis:function(a){if("vertical"==a){if(this.isKeyPressed(38)||this.isKeyPressed("W"))return 1;if(this.isKeyPressed(40)||this.isKeyPressed("S"))return-1}else if("horizontal"==a){if(this.isKeyPressed(37)||this.isKeyPressed("A"))return-1;
if(this.isKeyPressed(39)||this.isKeyPressed("D"))return 1}var b=this.Gamepads[0];if(b){if("horizontal"==a)return b.axes[0];if("vertical"==a)return b.axes[1]}return 0},getGamepad:function(a){return this.Gamepads[a||0]},getGamepadAxis:function(a,b,c){a=this.Gamepads[a];if(!a)return 0;var e=0,e=b&&b.constructor===String?this.mapping[b]:b;if(void 0===e)return 0;b=a.axes[e];return!c&&-0.1<b&&0.1>b?0:b},isGamepadButtonPressed:function(a,b){var c=this.Gamepads[a];if(!c)return null;var e=0,e=b&&b.constructor===
String?this.mapping[b]:b;return void 0===e?0:(c=c.buttons[e])&&c.pressed},mouseClick:function(){return new Promise(function(a){d.addWaitingCoroutine(a,"click")})}};var db={_root:null,_allow_change_cursor:!0,_is_on_top_of_immediate_widget:!1,defaultGUIStyle:{font:"Arial",color:"#FFF",colorTextOver:"#FFF",backgroundColor:"#333",backgroundColorOver:"#AAA",selected:"#AAF",unselected:"#AAA",outline:"#000",margin:0.2},GUIStyle:null,_style_stack:[],_offset:[0,0],_gui_areas:{data:new Float32Array(1024),offset:0},
_ctx:null,pressed_enter:!1,getHTMLRoot:function(){if(this._root)return!this._root.parentNode&&gl.canvas.parentNode&&gl.canvas.parentNode.appendChild(a),this._root;d.GlobalScene._state!=d.PLAYING&&console.warn("GUI element created before the scene is playing will be deleted once the app starts. Only create the GUI elements from onStart or after, otherwise the GUI elements will be lost.");var a=document.createElement("div");a.className="litescene-gui";a.style.position="absolute";a.style.top="0";a.style.left=
"0";a.style.color="#999";a.style.font="20px Arial";a.style.width="100%";a.style.height="100%";a.style.overflow="hidden";a.style.pointerEvents="none";if(!this._style){var b=this._style=document.createElement("style");b.appendChild(document.createTextNode(""));document.head.appendChild(b);b.sheet.insertRule(".litescene-gui button, .litescene-gui input { pointer-events: auto; }",0)}gl.canvas.parentNode.appendChild(a);return this._root=a},createElement:function(a,b){var c=document.createElement(a||"div");
c.style.pointerEvents="auto";return this.attach(c,b)},attach:function(a,b){if(a){a.style.position="absolute";b=b||"none";switch(b){case "bottom":case "bottom-left":a.style.bottom="0";a.style.left="0";break;case "bottom-right":a.style.bottom="0";a.style.right="0";break;case "bottom-middle":a.style.bottom="0";a.style.width="50%";a.style.margin="0 auto";break;case "right":case "top-right":a.style.top="0";a.style.right="0";break;case "top-middle":a.style.top="0";a.style.width="50%";a.style.margin="0 auto";
break;case "left":case "top":case "top-left":a.style.top="0";a.style.left="0";break;case "none":break;default:console.warn("invalid GUI anchor position: ",b)}this.getHTMLRoot().appendChild(a);return a}console.error("attachToGUI: element cannot be null")},detach:function(a){a&&a.parentNode&&a.parentNode.removeChild(a)},reset:function(){this._root&&(this._root.parentNode&&this._root.parentNode.removeChild(this._root),this._root=null,this._style&&(this._style.parentNode.removeChild(this._style),this._style=
null))},showHTML:function(){this._root&&(this._root.style.display="")},hideHTML:function(){this._root&&(this._root.style.display="none")},loadHTML:function(a,b){d.ResourcesManager.load(a,function(a){var e=d.GUI.getHTMLRoot(),g=a.getAsHTML();g?(g.style.pointerEvents="none",g.style.width="100%",g.style.height="100%",e.appendChild(g),d.GUI.replaceHTMLSources(e),b&&b(g,a)):console.error("html resource is not a string")})},replaceHTMLSources:function(a){a=a.querySelectorAll("*[src]");for(var b=0;b<a.length;++b){var c=
a[b],e=c.getAttribute("src");if(e&&"@"==e[0]){var e=e.substr(1),g=d.ResourcesManager.getResource(e),e=g&&g._local_url?g._local_url:d.ResourcesManager.getFullURL(e);c.setAttribute("src",e)}}},ResetImmediateGUI:function(a){this._is_on_top_of_immediate_widget=!1;this.setCursor(null);this.pressed_enter=!1;this._offset[0]=0;this._offset[1]=0;this._gui_areas.offset=0;this._ctx=gl;this.GUIStyle=this.defaultGUIStyle;this._style_stack.length=0;a||d.GlobalScene.requestFrame()},blockEventArea:function(a){var b=
this._gui_areas.data,c=this._gui_areas.offset;c>b.length||(b[c]=a[0]+this._offset[0],b[c+1]=a[1]+this._offset[1],b[c+2]=a[2],b[c+3]=a[3],this._gui_areas.offset+=4,this._gui_areas.offset>=b.length&&24576>b.length&&(this._gui_areas.data=new Float32Array(2*b.length),this._gui_areas.data.set(b)))},testEventInBlockedArea:function(a){if("mousedown"!=a.type)return!1;for(var b=this._gui_areas.data,c=0;c<this._gui_areas.offset;c+=4)if(a.mousex>=b[c]&&a.mousex<b[c]+b[c+2]&&a.mousey>=b[c+1]&&a.mousey<b[c+1]+
b[c+3])return!0;return!1},Box:function(a,b){if(!a)throw"No area";this.blockEventArea(a);var c=gl;c.fillStyle=b||"#333";c.fillRect(a[0]+this._offset[0],a[1]+this._offset[1],a[2],a[3])},Label:function(a,b){if(!a)throw"No area";if(null!=b){var c=this._ctx;b.constructor===GL.Texture?(c.constructor===CanvasRenderingContext2D&&(b=!b.data||b.data.constructor!==HTMLImageElement&&b.data.constructor!==Image?null:b.data),b&&c.drawImage(b,a[0]+this._offset[0],a[1]+this._offset[1],a[2],a[3])):b.constructor===
HTMLImageElement||b.constructor===Image?c.constructor===CanvasRenderingContext2D&&c.drawImage(b,a[0]+this._offset[0],a[1]+this._offset[1],a[2],a[3]):(b.constructor===Number?b=b.toFixed(3):b.constructor!==String&&(b=String(b)),c.fillStyle=this.GUIStyle.color,c.font=(0.75*a[3]).toFixed(0)+"px "+this.GUIStyle.font,c.textAlign="left",c.fillText(b,a[0]+0.2*a[3]+this._offset[0],a[1]+0.75*a[3]+this._offset[1]))}},ClickArea:function(a){if(!a)throw"No area";this.blockEventArea(a);d.Input.isEventInRect(d.Input.Mouse,
a,this._offset)&&(this._is_on_top_of_immediate_widget=!0,this.setCursor("pointer"));var b=d.Input.current_click,c=!1;b&&(c=d.Input.isEventInRect(b,a,this._offset))&&(d.Input.current_click=!1);return c},Button:function(a,b,c){if(!a)throw"No area";this.blockEventArea(a);var e=this._ctx,g=d.Input.isEventInRect(d.Input.Mouse,a,this._offset);g&&(this._is_on_top_of_immediate_widget=!0,this.setCursor("pointer"));var f=d.Input.current_click,h=!1;f&&(h=d.Input.isEventInRect(f,a,this._offset))&&(d.Input.current_click=
!1);if(null==b)return h;b.constructor===String&&(e.fillStyle=h?"#FFF":g?this.GUIStyle.backgroundColorOver:this.GUIStyle.backgroundColor,e.fillRect(a[0]+this._offset[0],a[1]+this._offset[1],a[2],a[3]));b.constructor===GL.Texture?(g&&c&&c.constructor===GL.Texture&&(b=c),e.drawImage(b,a[0]+this._offset[0],a[1]+this._offset[0],a[2],a[3])):b.constructor===String&&(e.fillStyle=g?this.GUIStyle.colorTextOver:this.GUIStyle.color,e.font=(0.75*a[3]).toFixed(0)+"px "+this.GUIStyle.font,e.textAlign="center",e.fillText(b,
a[0]+0.5*a[2]+this._offset[0],a[1]+0.75*a[3]+this._offset[1]),e.textAlign="left");return h},Toolbar:function(a,b,c){if(!a)throw"No area";if(!c||c.constructor!==Array)throw"No options";this.blockEventArea(a);var e=this._ctx;d.Input.isEventInRect(d.Input.Mouse,a,this._offset)&&(this._is_on_top_of_immediate_widget=!0,this.setCursor("pointer"));var g=d.Input.current_click,f=c.length,h=a[0],k=a[2];a[2]=k/f;for(var l=0;l<f;++l){var n=c[l],p=b==l,m=!1;a[0]=h+a[2]*l;g&&(m=d.Input.isEventInRect(g,a,this._offset))&&
(b=l,p=!0,d.Input.current_click=!1);n&&n.constructor!==String||(e.fillStyle=p?this.GUIStyle.backgroundColorOver:this.GUIStyle.backgroundColor,e.fillRect(a[0]+this._offset[0],a[1]+this._offset[1],a[2],a[3]));n&&(n.constructor===GL.Texture?(p||(e.globalAlpha=0.5),e.drawImage(n,a[0]+this._offset[0],a[1]+this._offset[1],a[2],a[3]),e.globalAlpha=1):n.constructor===String&&(e.fillStyle=this.GUIStyle.color,e.font=(0.75*a[3]).toFixed(0)+"px "+this.GUIStyle.font,e.textAlign="center",e.fillText(n,a[0]+0.5*
a[2]+this._offset[0],a[1]+0.75*a[3]+this._offset[1]),e.textAlign="left"))}a[0]=h;a[2]=k;return b},Toggle:function(a,b,c,e,g){if(!a)throw"No area";b=!!b;this.blockEventArea(a);var f=this._ctx;d.Input.isEventInRect(d.Input.Mouse,a,this._offset)&&(this._is_on_top_of_immediate_widget=!0,this.setCursor("pointer"));var h=d.Input.current_click,k=!1;h&&(k=d.Input.isEventInRect(h,a,this._offset))&&(d.Input.current_click=!1);h=0.2*a[3];if(c)if(c.constructor===GL.Texture)g=c,!b&&e&&e.constructor===GL.Texture&&
(g=e),f.drawImage(g,a[0]+this._offset[0],a[1]+this._offset[1],a[2],a[3]);else if(c.constructor===String){f.fillStyle=this.GUIStyle.color;f.font=(0.75*a[3]).toFixed(0)+"px "+this.GUIStyle.font;f.textAlign="left";f.fillText(c,a[0]+h+this._offset[0],a[1]+0.75*a[3]+this._offset[1]);e=0.6*a[3];f.fillStyle=this.GUIStyle.backgroundColor;c=a[0]+a[2]-1.5*h-e+this._offset[0];var l=a[1]+0.5*h+this._offset[1];g?f.fillCircle(c,l,a[3]-h):f.fillRect(c,l,e+h,a[3]-h);f.fillStyle=b?this.GUIStyle.selected:"#000";g?
f.fillCircle(a[0]+a[2]-h-e+this._offset[0],a[1]+h+this._offset[1],a[3]-2*h):f.fillRect(a[0]+a[2]-h-e+this._offset[0],a[1]+h+this._offset[1],e,a[3]-2*h)}return k?!b:b},TextField:function(a,b,c,e){if(!a)throw"No area";this.blockEventArea(a);b=void 0===b?"":String(b);c=c||1024;var g=this._ctx;d.Input.isEventInRect(d.Input.Mouse,a,this._offset)&&(this._is_on_top_of_immediate_widget=!0,this.setCursor("pointer"));var f=d.Input.current_click,h=!1;f&&(h=d.Input.isEventInRect(f,a,this._offset))&&(d.Input.current_click=
null,d.Input.last_click=f);f=!1;d.Input.last_click&&d.Input.isEventInRect(d.Input.last_click,a,this._offset)&&(f=!0);this.pressed_enter=!1;if(f){for(var k=d.Input.keys_buffer,h=0;h<k.length;++h){var l=k[h];switch(l.keyCode){case 8:b=b.substr(0,b.length-1);break;case 13:this.pressed_enter=!0;break;case 32:b.length<c&&(b+=" ");break;default:b.length<c&&l.key&&1==l.key.length&&(b+=l.key)}}k.length=0;d.Input.current_key=null}h=0.02*a[3];c=0.2*a[3];g.fillStyle=this.GUIStyle.backgroundColor;g.fillRect(a[0]+
this._offset[0],a[1]+this._offset[1],a[2],a[3]);g.fillStyle="#000";g.fillRect(a[0]+h+this._offset[0],a[1]+h+this._offset[1],a[2]-2*h,a[3]-2*h);g.fillStyle=this.GUIStyle.color;g.font=(0.75*a[3]).toFixed(0)+"px "+this.GUIStyle.font;g.textAlign="left";k="";f&&0==(0.002*getTime()|0)%2&&(k="|");f=b;if(e)for(f="",h=0;h<b.length;++h)f+="*";g.fillText(f+k,a[0]+2*c+this._offset[0],a[1]+0.75*a[3]+this._offset[1]);return b},HorizontalSlider:function(a,b,c,e,g){if(!a)throw"No area";this.blockEventArea(a);void 0===
c&&(c=0);void 0===e&&(e=1);b=Number(b);c=Number(c);e=Number(e);var f=this._ctx,h=d.Input.isEventInRect(d.Input.Mouse,a,this._offset);h&&(this._is_on_top_of_immediate_widget=!0,this.setCursor("pointer"));var k=d.Input.current_click,l=!1;e-=c;var n=(b-c)/e;0>n&&(n=0);1<n&&(n=1);var p=a[3]*this.GUIStyle.margin;k&&(l=d.Input.isEventInRect(k,a,this._offset))&&(n=(d.Input.Mouse.x-this._offset[0]-(a[0]+p))/(a[2]-2*p),0>n&&(n=0),1<n&&(n=1),b=n*e+c);f.fillStyle=this.GUIStyle.backgroundColor;f.fillRect(a[0]+
this._offset[0],a[1]+this._offset[1],a[2],a[3]);f.fillStyle=h?this.GUIStyle.selected:this.GUIStyle.unselected;f.fillRect(a[0]+p+this._offset[0],a[1]+p+this._offset[1],Math.max(2,(a[2]-2*p)*n),a[3]-2*p);g&&(f.textAlign="center",f.fillStyle=this.GUIStyle.color,f.font=(0.5*a[3]).toFixed(0)+"px "+this.GUIStyle.font,f.fillText(b.toFixed(2),a[0]+0.5*a[2]+this._offset[0],a[1]+0.7*a[3]+this._offset[1]),f.textAlign="left");return b},VerticalSlider:function(a,b,c,e){if(!a)throw"No area";this.blockEventArea(a);
b=Number(b);void 0===c&&(c=0);void 0===e&&(e=1);c=Number(c);e=Number(e);var g=this._ctx,f=d.Input.isEventInRect(d.Input.Mouse,a,this._offset);f&&(this._is_on_top_of_immediate_widget=!0,this.setCursor("pointer"));var h=d.Input.current_click,k=!1,l=e-c,n=(b-c)/l;0>n&&(n=0);1<n&&(n=1);e=a[2]*this.GUIStyle.margin;h&&(k=d.Input.isEventInRect(h,a,this._offset))&&(n=(d.Input.Mouse.y-this._offset[1]-(a[1]+e))/(a[3]-2*e),0>n&&(n=0),1<n&&(n=1),n=1-n,b=n*l+c);g.fillStyle=this.GUIStyle.backgroundColor;g.fillRect(a[0]+
this._offset[0],a[1]+this._offset[1],a[2],a[3]);g.fillStyle=f?this.GUIStyle.selected:this.GUIStyle.unselected;c=Math.max(2,(a[3]-2*e)*n);g.fillRect(a[0]+e+this._offset[0],a[1]+a[3]-c-e+this._offset[1],a[2]-2*e,c);return b},Knob:function(a,b,c,e,g,f){if(!a)throw"No area";this.blockEventArea(a);b=Number(b);void 0===c&&(c=0);void 0===e&&(e=1);g=g||0;c=Number(c);e=Number(e);var h=this._ctx,k=d.Input.isEventInRect(d.Input.Mouse,a,this._offset);k&&(this._is_on_top_of_immediate_widget=!0,this.setCursor("pointer"));
var l=d.Input.current_click,n=!1,p=e-c;e=(b-c)/p;0>e&&(e=0);1<e&&(e=1);var m=0.75*-Math.PI,q=1.5*Math.PI;l&&(n=d.Input.isEventInRect(l,a,this._offset))&&(e=(Math.atan2(d.Input.Mouse.x-(a[0]+0.5*a[2])-this._offset[0],-(d.Input.Mouse.y-(a[1]+0.5*a[3])-this._offset[1]))-m)/q,0>e&&(e=0),1<e&&(e=1),b=e*p+c);g&&(e=Math.round(e*g)/g);void 0!==f?null!==f&&(c=null,f.constructor===GL.Texture?(h.constructor===CanvasRenderingContext2D&&(f=!f.data||f.data.constructor!==HTMLImageElement&&f.data.constructor!==Image?
null:f.data),f&&(c=f)):f.constructor!==HTMLImageElement&&f.constructor!==Image||h.constructor!==CanvasRenderingContext2D||(c=f),c&&(h.save(),h.translate(a[0]+0.5*a[2]+this._offset[0],a[1]+0.5*a[3]+this._offset[1]),h.rotate(e*q+m),h.scale(a[3]/c.height,a[3]/c.height),h.drawImage(c,0.5*-c.width,0.5*-c.height),h.restore())):(h.strokeStyle=this.GUIStyle.outline,h.fillStyle=this.GUIStyle.backgroundColor,h.beginPath(),h.arc(a[0]+0.5*a[2]+this._offset[0],a[1]+0.5*a[3]+this._offset[1],0.45*a[3],0,2*Math.PI,
!1),h.fill(),h.stroke(),h.lineWidth=0.1*a[3],h.strokeStyle=k?this.GUIStyle.selected:this.GUIStyle.unselected,h.beginPath(),m=1.25*-Math.PI,h.arc(a[0]+0.5*a[2]+this._offset[0],a[1]+0.5*a[3]+this._offset[1],0.35*a[3],m,m+Math.max(DEG2RAD,q*e),!1),h.stroke(),h.lineWidth=1);return b},DragArea:function(a,b){if(!a)throw"No area";if(!b)throw"No value";this.blockEventArea(a);d.Input.isEventInRect(d.Input.Mouse,a,this._offset)&&(this._is_on_top_of_immediate_widget=!0,this.setCursor("pointer"));var c=d.Input.current_click,
e=!1;c&&(e=d.Input.isEventInRect(c,a,this._offset))&&(d.Input.current_click=null,d.Input.last_click=c);d.Input.last_click&&d.Input.isEventInRect(d.Input.last_click,a,this._offset)&&d.Input.Mouse.dragging&&(b[0]+=d.Input.Mouse.deltax||0,b[1]+=d.Input.Mouse.deltay||0);return b},pushStyle:function(){var a=d.cloneObject(this.GUIStyle);this._style_stack.push(this.GUIStyle);this.GUIStyle=a},popStyle:function(){this._style_stack.length&&(this.GUIStyle=this._style_stack.pop())},setCursor:function(a){this._allow_change_cursor&&
(gl.canvas.style.cursor=a||"")}};Object.defineProperty(db,"GUIOffset",{set:function(a){!a.length||2>a.length||(this._offset[0]=a[0],this._offset[1]=a[1])},get:function(){return this._offset},enumerable:!0});db.show=db.showHTML;db.hide=db.hideHTML;db.load=db.loadHTML;db.getRoot=function(){console.warn("LS.GUI.getRoot() deprecated, use LS.GUI.getHTMLRoot() instead.");return d.GUI.getHTMLRoot()};d.GUI=db;var Ob={path:"",proxy:"",ignore_cache:!1,free_data:!1,keep_files:!1,keep_urls:!1,allow_base_files:!1,
scene_external_repository:null,resources:{},meshes:{},textures:{},materials:{},materials_by_uid:{},resources_not_found:{},resources_being_loaded:{},resources_being_processed:{},resources_renamed_recently:{},num_resources_being_loaded:0,MAX_TEXTURE_SIZE:4096,resource_pre_callbacks:{},resource_post_callbacks:{},resource_once_callbacks:{},virtual_file_systems:{},skip_proxy_extensions:["mp3","wav","ogg"],force_nocache_extensions:["js","glsl","json"],nocache_files:{},valid_resource_name_reg:/^[A-Za-z\d\s\/\_\-\.]+$/,
getNoCache:function(a){return this.ignore_cache||a?"nocache="+getTime()+Math.floor(1E3*Math.random()):""},reset:function(){this.resources={};this.meshes={};this.textures={};this.materials={};this.materials_by_uid={};this.scene_external_repository=null},registerResourcePreProcessor:function(a,b,c,e){if(a){a=a.split(",");for(var d in a)c=a[d].toLowerCase(),this.resource_pre_callbacks[c]=b}},registerResourcePostProcessor:function(a,b){this.resource_post_callbacks[a]=b},getExtension:function(a,b){if(!a)return"";
var c=a.indexOf("?");-1!=c&&(a=a.substr(0,c));c=b?a.indexOf("."):a.lastIndexOf(".");return-1==c?"":a.substr(c+1).toLowerCase().trim()},removeExtension:function(a,b){if(!a)return"";var c=a.indexOf("?");-1!=c&&(a=a.substr(0,c));c=b?a.indexOf("."):a.lastIndexOf(".");return-1==c?a:a.substr(0,c)},replaceExtension:function(a,b){if(!a)return"";b=b||"";var c=this.getFolder(a),e=this.getFilename(a);return this.cleanFullpath((c?c+"/":"")+e+"."+b)},getFilename:function(a){if(!a)return"";var b=a.lastIndexOf("/"),
c=a.lastIndexOf("?"),c=(-1==c?a.length:c-1)-b;return a.substr(b+1,c)},getFolder:function(a){if(!a)return"";var b=a.lastIndexOf("/");return a.substr(0,b)},getBasename:function(a){if(!a)return"";a=this.getFilename(a);var b=a.indexOf(".");return-1==b?a:a.substr(0,b)},getProtocol:function(a){if(!a)return"";var b=a.substr(0,10).indexOf(":"),c="";-1!=b&&(c=a.substr(0,b));return c},cleanFullpath:function(a){return a?-1==a.indexOf("//")?47==a.charCodeAt(0)?a.substr(1):a:-1==a.indexOf("://")?a.split("/").filter(function(a){return!!a}).join("/"):
a:""},loadResources:function(a,b){if(a){if(a.constructor===Array)for(var c=0;c<a.length;++c){var e=a[c];e&&":"!=e[0]&&"_"!=e[0]&&this.load(e,b)}else for(c in a)c&&":"!=c[0]&&"_"!=c[0]&&this.load(c,b);this._total_resources_to_load=this.num_resources_being_loaded;LEvent.trigger(this,"start_loading_resources",this._total_resources_to_load);this._total_resources_to_load||LEvent.trigger(this,"end_loading_resources");return this._total_resources_to_load}},setPath:function(a){this.path=a},setProxy:function(a){a?
(-1!=a.indexOf("@")?this.proxy=location.protocol+"//"+a.replace("@",window.location.host):this.proxy=a,"undefined"!==typeof LiteGraph&&(LiteGraph.proxy=this.proxy)):this.proxy=null},getFullURL:function(a,b){if(!a)return null;var c=a.substr(0,10).indexOf(":"),e="";-1!=c&&(e=a.substr(0,c));var d=this.path;this.scene_external_repository&&(d=this.scene_external_repository);b&&b.force_local_url&&(d=".");b&&b.external_repository&&(d=b.external_repository);if(e)switch(e){case "http":case "https":return c=
this.getExtension(a).toLowerCase(),this.proxy&&-1==this.skip_proxy_extensions.indexOf(c)&&(!b||b&&!b.ignore_proxy)?this.proxy+a:a;case "blob":return a;case "":return a;default:return":"==a[0]||"_"==a[0]?a:(this.virtual_file_systems[e]||d)+"/"+a.substr(c+1)}else return d+"/"+a},registerFileSystem:function(a,b){this.virtual_file_systems[a]=b},getResource:function(a,b){if(!a)return null;a=this.cleanFullpath(a);if(!b)return this.resources[a];var c=this.resources[a];return c&&c.constructor===b?c:null},
getResourceType:function(a){return a?a.object_class?a.object_class:a.constructor.resource_type?a.constructor.resource_type:d.getObjectClassName(a):null},getResourcesData:function(a,b){if(a.constructor!==Array)return console.error("getResourcesData expects Array"),null;for(var c={},e=0;e<a.length;++e){var g=a[e],f=d.ResourcesManager.resources[g];if(f){var h=null;if(h=f._original_data?f._original_data:d.Resource.getDataToStore(f).data){if(h.constructor===Blob||h.constructor===File){if(!(b||h.data&&
h.data.constructor===ArrayBuffer)){console.warn("Not support to store File or Blob, please, use ArrayBuffer");continue}h=h.data}c[g]=h}else console.warn("Wrong data in resource")}}return c},createResource:function(a,b,c){var e=null,e=this.getExtension(a),g=null;e&&(g=d.Formats.supported[e]);g&&g.resourceClass?e=new g.resourceClass:(e=this.resources[a])&&e.constructor===d.Resource?(delete e._original_data,delete e._original_file,e._modified=!1):e=new d.Resource;if(b)if(e.setData)e.setData(b,!0);else if(e.fromData)e.fromData(b);
else throw"Resource without setData, cannot assign";c&&d.ResourcesManager.registerResource(a,e);return e},resourceModified:function(a){if(a)if(a.constructor===String)console.warn("resourceModified parameter must be a resource, not a string");else{delete a._original_data;delete a._original_file;a._version=(a._version||0)+1;a.remotepath&&(a._modified=!0);LEvent.trigger(this,"resource_modified",a);if(a.from_pack&&a.from_pack.constructor===String){var b=d.ResourcesManager.getResource(a.from_pack);b&&
this.resourceModified(b)}a.from_prefab&&a.from_prefab.constructor===String&&(a=d.ResourcesManager.getResource(a.from_prefab))&&this.resourceModified(a)}},resourceSaved:function(a){a&&(delete a._modified,a.remotepath=a.fullpath,LEvent.trigger(this,"resource_saved",a))},load:function(a,b,c,e,g){if(!a)return console.error("LS.ResourcesManager.load requires url");b&&b.constructor===Function&&!c&&(c=b,b=null);var f=this.resources[a];if(null!=f&&!(f.is_preview||b&&b.force||e))return c&&c(f,a),!0;b=b||{};
e=this.getExtension(a);if(!e&&!this.resources[a])return console.warn("Cannot load a file without extension: "+a),!1;if(!this.resources_not_found[a])if(this.resources_being_loaded[a])c&&this.resources_being_loaded[a].push({options:b,callback:c});else if(!this.resources_being_processed[a]){if(this.allow_base_files||-1!=a.indexOf("/")){this.resources_being_loaded[a]=[{options:b,callback:c}];LEvent.trigger(d.ResourcesManager,"resource_loading",a);this.num_resources_being_loaded++;f=this.getFullURL(a);
(c=d.Formats.getFileFormatInfo(e))&&c.has_preview&&!b.is_preview&&LEvent.trigger(this,"load_resource_preview",a);f={url:f,success:function(c){d.ResourcesManager.processResource(a,c,b,d.ResourcesManager._resourceLoadedEnd,!0)},error:function(b){d.ResourcesManager._resourceLoadedError(a,b);g&&g(a)},progress:function(b){var c=0;b.total&&(c=b.loaded/b.total);LEvent.hasBind(d.ResourcesManager,"resource_loading_progress")&&LEvent.trigger(d.ResourcesManager,"resource_loading_progress",{url:a,event:b,progress:c});
LEvent.hasBind(d.ResourcesManager,"loading_resources_progress")&&LEvent.trigger(d.ResourcesManager,"loading_resources_progress",1-(d.ResourcesManager.num_resources_being_loaded-c)/d.ResourcesManager._total_resources_to_load)}};f.nocache=this.ignore_cache||-1!=this.force_nocache_extensions.indexOf[e]||this.nocache_files[a];if(c=d.Formats.supported[e])c.dataType&&(f.dataType=c.dataType),c.mimeType&&(f.mimeType=c.mimeType),c["native"]&&(f.dataType=null);d.Network.request(f);return!1}this._parsing_local_file||
console.warn("Cannot load resource, filename has no folder and LS.ResourcesManager.allow_base_files is set to false: ",a)}},processResource:function(a,b,c,e,g){if((c=c||{})&&c.constructor!==Object)throw"processResource options must be object";if(null===b||void 0===b)throw"No data found when processing resource: "+a;var f=null,h=this.getExtension(a),k=null;h&&(k=d.Formats.supported[h]);var l=function(a,c,f){c?(k&&k.convert_to&&h!=k.convert_to&&(a+="."+k.convert_to,c.filename+="."+k.convert_to,c.fullpath&&
(c.fullpath+="."+k.convert_to),f.filename&&(f.filename+="."+k.convert_to)),d.ResourcesManager.processFinalResource(a,c,f,e,g),!d.ResourcesManager.keep_files||b.constructor!=ArrayBuffer&&b.constructor!=String||c._original_data||c._original_file||h!=d.ResourcesManager.getExtension(c.filename)||(c._original_data=b)):d.ResourcesManager._resourceLoadedEnd(a,null)};this.resources_being_processed[a]=!0;if(!h)return this.processDataResource(a,b,c,l);if(f=this.resource_pre_callbacks[h.toLowerCase()])f=f(a,
b,c,l),!0!==f&&(f?l(a,f,c):(console.warn("resource preprocessor_callback returned null"),this._resourceLoadedError(a,"Resource couldn't be processed")));else if(k&&(k.type||k.parse)){f=null;switch(k.type){case "scene":f=d.ResourcesManager.processScene(a,b,c,l);break;case "mesh":f=d.ResourcesManager.processTextMesh(a,b,c,l);break;case "texture":case "image":f=d.ResourcesManager.processImage(a,b,c,l);break;default:k.parse?(f=k.parse(b))&&l(a,f,c):console.warn("Format Info without parse function")}f&&
!0!==f&&l(a,f,c)}else if(k&&k.resource_ctor)f=new k.resource_ctor,f.fromData?f.fromData(b):f.configure?f.configure(JSON.parse(b)):console.error("Resource Class doesnt have a function to process data after loading: ",k.ctor.name),f&&!0!==f&&l(a,f,c);else if(f=d.ResourcesManager.createResource(a,b))f.filename=f.fullpath=a,l(a,f,c)},processFinalResource:function(a,b,c,e,g){if(!b||b.constructor===String)return d.ResourcesManager._resourceLoadedError(a,"error processing the resource");b.filename=a;c.filename&&
(b.filename=c.filename);c.is_local?a=b.fullpath=b.filename:b.fullpath=a;c.from_prefab&&(b.from_prefab=c.from_prefab);c.from_pack&&(b.from_pack=c.from_pack);g&&(b.remotepath=a);c.is_preview&&(b.is_preview=!0);d.ResourcesManager.resources_being_processed[a]&&delete d.ResourcesManager.resources_being_processed[a];b.getResources&&d.ResourcesManager.loadResources(b.getResources({}));d.ResourcesManager.registerResource(a,b);c.preview_of&&d.ResourcesManager.registerResource(c.preview_of,b);e&&e(a,b,c)},
registerResource:function(a,b){if(!a||!b)throw"registerResource missing filename or resource";":"!=a[0]&&!1==this.valid_resource_name_reg.test(a)&&"http"!=a.substr(0,4)&&console.warn("invalid filename for resource: ",a);a=this.cleanFullpath(a);if(!(this.resources[a]===b||b.is_preview&&this.resources[a])){b.filename=a;b.object_class||(b.object_class=d.getObjectClassName(b));var c=b.object_class;b.constructor.resource_type&&(c=b.constructor.resource_type);this.resources[a]=b;(c=this.resource_post_callbacks[c])&&
c(a,b);b.is_preview||LEvent.trigger(this,"resource_registered",b);d.GlobalScene.requestFrame()}},unregisterResource:function(a){var b=this.resources[a];if(!b)return!1;delete this.resources[a];this.meshes[a]&&delete this.meshes[a];this.textures[a]&&delete this.textures[a];this.materials[a]&&delete this.materials[a];b.constructor!==d.Pack&&b.constructor!==d.Prefab||b.setResourcesLink(null);LEvent.trigger(this,"resource_unregistered",b);d.GlobalScene.requestFrame();return!0},getURLasFile:function(a,
b){var c=new XMLHttpRequest;c.open("GET",this.getFullURL(a),!0);c.responseType="blob";c.onload=function(e){e=c.response;b&&b(e,a)};c.send()},renameResource:function(a,b,c){var e=this.resources[a];if(!e)return!1;this.resources[b]&&console.warn("There is a resource already with this name, overwritting it: "+b);e.filename=b;e.fullpath&&(e.fullpath=b);this.resources[b]=e;delete this.resources[a];c||d.GlobalScene.sendResourceRenamedEvent(a,b,e);for(var g in this.resources){var f=this.resources[g];f!=e&&
f.onResourceRenamed&&f.onResourceRenamed(a,b,e)&&this.resourceModified(f)}this.meshes[a]&&(delete this.meshes[a],this.meshes[b]=e);this.textures[a]&&(delete this.textures[a],this.textures[b]=e);this.materials[a]&&(delete this.materials[a],this.materials[b]=e);this.resources_renamed_recently[a]=b;c||LEvent.trigger(d.ResourcesManager,"resource_renamed",[a,b,e]);return!0},isLoading:function(a){return a?this.resources_being_loaded[a]||this.resources_being_processed[a]?!0:!1:0<this.num_resources_being_loaded},
clearNotFoundResources:function(){this.resources_not_found={}},computeImageMetadata:function(a){return{width:a.width,height:a.height}},getMesh:function(a){return a?a.constructor===String?this.meshes[a]:a.constructor===GL.Mesh?a:null:null},getTexture:function(a){return a?a.constructor===String?this.textures[a]:a.constructor===GL.Texture?a:null:null},getMaterial:function(a){if(a)return"@"==a[0]?this.materials_by_uid[a]:this.materials[a]},onceLoaded:function(a,b){var c=this.resource_once_callbacks[a];
if(!c)this.resource_once_callbacks[a]=[b];else if(-1==c.indexOf(b))return c.push(b),c.length-1},cancelOnceLoaded:function(a,b){var c=this.resource_once_callbacks[a];c&&(c[b]=null)},_resourceLoadedEnd:function(a,b){d.ResourcesManager.debug&&console.log("RES: "+a+" ---\x3e "+d.ResourcesManager.num_resources_being_loaded);if(b){var c=d.ResourcesManager.resources_being_loaded[a];if(c)for(var e=0;e<c.length;++e)null!=c[e].callback&&c[e].callback(b,a);if(c=d.ResourcesManager.resource_once_callbacks[a]){for(e=
0;e<c.length;++e)if(c[e])c[e](a,b);delete d.ResourcesManager.resource_once_callbacks[a]}}d.ResourcesManager.resources_being_loaded[a]&&(delete d.ResourcesManager.resources_being_loaded[a],d.ResourcesManager.num_resources_being_loaded--,b?LEvent.trigger(d.ResourcesManager,"resource_loaded",a):LEvent.trigger(d.ResourcesManager,"resource_problem_loading",a),LEvent.trigger(d.ResourcesManager,"loading_resources_progress",1-d.ResourcesManager.num_resources_being_loaded/d.ResourcesManager._total_resources_to_load),
0==d.ResourcesManager.num_resources_being_loaded&&(LEvent.trigger(d.ResourcesManager,"end_loading_resources",!0),d.ResourcesManager._total_resources_to_load=0));d.GlobalScene.requestFrame()},_resourceLoadedError:function(a,b){console.log("Error loading "+a);delete d.ResourcesManager.resources_being_loaded[a];delete d.ResourcesManager.resource_once_callbacks[a];d.ResourcesManager.resources_not_found[a]=!0;LEvent.trigger(d.ResourcesManager,"resource_not_found",a);d.ResourcesManager.num_resources_being_loaded--;
0==d.ResourcesManager.num_resources_being_loaded&&LEvent.trigger(d.ResourcesManager,"end_loading_resources",!1)}};d.RM=d.ResourcesManager=Ob;d.getTexture=function(a){return d.ResourcesManager.getTexture(a)};d.ResourcesManager.registerResourcePreProcessor("wbin",function(a,b,c){if(b.constructor===Object&&b.object_class){if(d.Classes[b.object_class]){if((c=d.Classes[b.object_class]||window[b.object_class])&&c.fromBinary)return c.fromBinary(b,a);c&&c.prototype.fromBinary&&(b=new c,b.fromBinary(object,
a))}return b}return WBin.load(b,!1,a)},"binary");d.ResourcesManager.registerResourcePreProcessor("json",function(a,b,c){c=b;if(b.constructor===String)try{b=JSON.parse(b)}catch(e){return console.error("invalid JSON"),null}c=b.object_class||b.object_type;!c&&b.material_class&&(c=b.material_class);if(!c){var g=d.ResourcesManager.getExtension(a,!0);(g=d.ResourceClasses_by_extension[g])&&(c=d.getClassName(g))}if(c&&!b.is_data)if(g=d.Classes[c]||window[c])g.prototype.configure?(c=new g,c.configure(b)):
c=new g(b);else return console.error("JSON object_class class not found: "+c),null;else c=new d.Resource,c.filename=a,c._data=b,c.type="json",c.category="json";return c});d.ResourcesManager.registerResourcePreProcessor("zip",function(a,b,c){if(!da.JSZip)throw"JSZip not found. To use ZIPs you must have the JSZip.js library included in the website.";(new JSZip).loadAsync(b).then(function(a){a.forEach(function(a,b){if(!b.dir){var e=d.ResourcesManager.getExtension(a),e=d.Formats.supported[e];b.async(e&&
"text"==e.dataType?"string":"arraybuffer").then(function(b){"scene.json"!=a||c&&c.to_memory?d.ResourcesManager.processResource(a,b):d.GlobalScene.configure(JSON.parse(b))})}})});return!0},"binary");d.ResourcesManager.processDataResource=function(a,b,c,e){b.constructor===String&&(b=JSON.parse(b));if(b.constructor==ArrayBuffer){if(!b.byteLength)return console.warn("Empty WBin?"),null;f=WBin.load(b);e&&e(a,f,c);return f}var g=b.object_class;if(g&&d.Classes[g]){var f=null;d.Classes[g].prototype.configure?
(f=new d.Classes[g],f.configure(b)):f=new d.Classes[g](b);e&&e(a,f,c);return f}console.warn("Resource Class name unknown: "+g);return!1};d.ResourcesManager.processImage=function(a,b,c,e){function g(g){g&&d.ResourcesManager.keep_files&&(g._original_data=b);d.ResourcesManager.keep_urls?g._local_url=k:URL.revokeObjectURL(k);e&&e(a,g,c)}var f=d.ResourcesManager.getExtension(a),h="application/octet-stream";if("jpg"==f||"jpeg"==f)h="image/jpg";else if("webp"==f)h="image/webp";else if("gif"==f)h="image/gif";
else if("png"==f)h="image/png";else if(f=d.Formats.supported[f],f.mimetype)h=f.mimetype;else{f=this.processImageNonNative(a,b,c);g(f);return}var f=new Blob([b],{type:h}),k=URL.createObjectURL(f),f=new Image;f.src=k;f.real_filename=a;f.onload=function(){var a=d.ResourcesManager.processTexture(this.real_filename,this,c);g(a)};f.onerror=function(b){URL.revokeObjectURL(k);e&&e(a,null,c);console.error("Error while loading image, file is not native image format: "+a)};return!0};d.ResourcesManager.processImageNonNative=
function(a,b,c){b=(new Uint8Array(b)).buffer;c=d.Formats.parse(a,b,c);return c?c.constructor==GL.Texture?(c.filename=a,c._original_data=b,c):c=d.ResourcesManager.processTexture(a,c):(console.error("Cannot parse image format"),null)};d.ResourcesManager.processTexture=function(a,b,c){if(b.width==b.height/6||-1!=a.indexOf("CUBECROSS"))c={wrapS:gl.MIRROR,wrapT:gl.MIRROR,magFilter:gl.LINEAR,minFilter:gl.LINEAR_MIPMAP_LINEAR},-1!=a.indexOf("CUBECROSSL")&&(c.is_cross=1),c=GL.Texture.cubemapFromImage(b,c);
else{c=gl.LINEAR;var e=gl.REPEAT,d=gl.LINEAR_MIPMAP_LINEAR;isPowerOfTwo(b.width)&&isPowerOfTwo(b.height)||(d=gl.LINEAR,e=gl.CLAMP_TO_EDGE);c=b.pixels?GL.Texture.fromMemory(b.width,b.height,b.pixels,{format:24==b.bpp?gl.RGB:gl.RGBA,no_flip:b.flipY,wrapS:e,wrapT:e,magFilter:c,minFilter:d}):GL.Texture.fromImage(b,{format:gl.RGBA,wrapS:e,wrapT:e,magFilter:c,minFilter:d})}if(c)return c.img=b,c.filename=a,c.generateMetadata(),c};d.ResourcesManager.processTextMesh=function(a,b,c){b=d.Formats.parse(a,b,c);
return null==b?(console.error("Error parsing mesh: "+a),null):GL.Mesh.load(b)};d.ResourcesManager.processScene=function(a,b,c){b=d.Formats.parse(a,b,c);if(null==b)return console.error("Error parsing scene: "+a),null;if(b&&b.constructor===d.Scene)throw"processScene must receive object, no Scene";if(!b.root)throw"this is not an scene, root property missing";d.ResourcesManager._parsing_local_file=!0;for(var e in b.meshes)d.ResourcesManager.processResource(e,b.meshes[e]);for(e in b.resources)d.ResourcesManager.processResource(e,
b.resources[e]);for(e in b.materials)d.ResourcesManager.processResource(e,b.materials[e]);a=new d.SceneNode;a.configure(b.root);c&&c.filename&&"json"!=d.RM.getExtension(c.filename)&&(c.filename+=".json");d.ResourcesManager._parsing_local_file=!1;return a};d.ResourcesManager.loadTextureAtlas=function(a,b,c){var e=new Image;e.src=this.getFullURL(a.filename);e.onload=function(){var e=a.thumbnail_size,f=document.createElement("canvas");f.width=e;f.height=e;var e=f.getContext("2d"),h;for(h in a.textures){var k=
a.textures[h];e.clearRect(0,0,f.width,f.height);e.drawImage(this,-k.pos[0],-k.pos[1]);var l=GL.Texture.fromImage(f,{format:GL.RGBA,magFilter:gl.LINEAR,minFilter:gl.LINEAR_MIPMAP_LINEAR,wrap:gl.REPEAT});c||(l.is_preview=!0);d.ResourcesManager.registerResource(k.name,l)}d.GlobalScene.requestFrame();b&&b()}};d.ResourcesManager.registerResourcePostProcessor("Mesh",function(a,b){b.object_class="Mesh";b.metadata&&(b.metadata={},b.generateMetadata());if(!b.bounding||b.bounding.length!=BBox.data_length||
b.info&&b.info.groups&&b.info.groups.length&&!b.info.groups[0].bounding)b.bounding=null,b.updateBoundingBox();b.getBuffer("normals")||b.computeNormals();d.ResourcesManager.free_data&&b.freeData();d.ResourcesManager.meshes[a]=b});d.ResourcesManager.registerResourcePostProcessor("Texture",function(a,b){d.ResourcesManager.textures[a]=b});d.ResourcesManager.registerResourcePostProcessor("Material",function(a,b){d.ResourcesManager.materials[a]=b;d.ResourcesManager.materials_by_uid[b.uid]=b;b.prepare&&
b.prepare(d.GlobalScene)});d.ResourcesManager.registerResourcePostProcessor("Pack",function(a,b){b.flagResources()});d.ResourcesManager.registerResourcePostProcessor("Prefab",function(a,b){b.applyToNodes()});d.ResourcesManager.registerResourcePostProcessor("ShaderCode",function(a,b){b.applyToMaterials()});GL.Mesh.load_priority=-10;var wc={snippets:{},shader_blocks_by_id:new Map,shader_blocks:[],num_shaderblocks:0,global_extra_shader_code:"",dump_compile_errors:!0,on_compile_error:null,init:function(a,
b){var c=[];c.push(["STANDARD_DERIVATIVES","OES_standard_derivatives","#extension GL_OES_standard_derivatives : enable"]);c.push(["DRAW_BUFFERS","WEBGL_draw_buffers"]);this.global_extra_shader_code=String.fromCharCode(10)+"#define WEBGL_VERSION "+gl.webgl_version+"\n";for(var e in c){var d=c[e];if(2==gl.webgl_version||gl.extensions[d[1]])this.global_extra_shader_code+="#define "+d[0]+"\n",1==gl.webgl_version&&d[2]&&(this.global_extra_shader_code+=d[2]+"\n")}},reloadShaders:function(a){},compile:function(a,
b,c){if(!c)throw"compileShader must have a name specified";if(!gl)return null;var e=null;try{a=this.global_extra_shader_code+a;b=this.global_extra_shader_code+b;var d=this.compiled_shaders[c+":VS"];d||(d=this.compiled_shaders[c+":VS"]=GL.Shader.compileSource(gl.VERTEX_SHADER,a));var f=this.compiled_shaders[c+":FS"];f||(f=this.compiled_shaders[c+":FS"]=GL.Shader.compileSource(gl.FRAGMENT_SHADER,b));var h=getTime(),e=new GL.Shader(d,f);this.debug&&console.log("Shader compile time: ",(getTime()-h).toFixed(3),
"ms");e.name=c}catch(k){this.dump_compile_errors&&(this.dumpShaderError(c,k,a,b),this.dump_compile_errors=!1);if(this.on_compile_error)this.on_compile_error(k);return null}return e},clearShaderCodeCache:function(){var a=[],b=d.StandardMaterial.shader_codes,c;for(c in b)a.push(b[c]);b=d.ResourcesManager.resources;for(c in b)b[c].constructor===d.ShaderCode&&a.push(b[c]);for(c in a)a[c].clearCache()},dumpShaderError:function(a,b,c,e){console.error("Error compiling shader: "+a);console.log(b);console.groupCollapsed("Vertex Shader Code");
a=c.split("\n");for(var d in a)console.log(d+": "+a[d]);console.groupEnd();console.groupCollapsed("Fragment Shader Code");a=e.split("\n");for(d in a)console.log(d+": "+a[d]);console.groupEnd()},registerSnippet:function(a,b){this.snippets[a]={id:a,code:b}},getSnippet:function(a){return this.snippets[a]},registerShaderBlock:function(a,b,c){var e=-1;!c&&this.shader_blocks_by_id.get(a)?(console.warn("There is already a ShaderBlock with that name, replacing it: ",a),e=this.shader_blocks_by_id.get(a).flag_id,
this.clearShaderCodeCache()):e=this.num_shaderblocks++;64<=e&&console.warn("Too many shaderblocks registered, not enought bits in a 64bits variable");b.flag_id=e;b.flag_mask=1<<e;this.shader_blocks_by_id.set(a,b);this.shader_blocks[e]=b},getShaderBlock:function(a){return a.constructor===String?this.shader_blocks_by_id.get(a):this.shader_blocks[a]},common_vscode:"\n\t\tprecision mediump float;\n\t\tattribute vec3 a_vertex;\n\t\tattribute vec3 a_normal;\n\t\tattribute vec2 a_coord;\n\t\tuniform mat4 u_model;\n\t\tuniform mat4 u_viewprojection;\n\t",
common_fscode:"\n\t\tprecision mediump float;\n\t"};d.Shaders=wc;qb.prototype.defineContextMacros=function(a){this.context_macros=a};qb.prototype.addCode=function(a,b,c,e){c=c||"";b={enabled:new d.GLSLCode(b||""),disabled:new d.GLSLCode(c),macros:e};this.code_map.set(a,b)};qb.prototype.bindEvent=function(a,b){this.events||(this.events={});this.events[a]=b};qb.prototype.getFinalCode=function(a,b,c){b=b||0;var e=this.code_map.get(a);if(!e)return null;a=(b&this.flag_mask?e.enabled:e.disabled).getFinalCode(a,
b,c);if(e.macros){b="";for(var d in e.macros)b+="#define "+d+e.macros[d]+"\n";a=b+a}return a};qb.prototype.register=function(a){d.Shaders.registerShaderBlock(this.name,this,a)};qb.prototype.checkDependencies=function(a){};d.ShaderBlock=qb;d.GLSLCode=ka;ka.pragma_methods={};ka.CODE=1;ka.PRAGMA=2;ka.INCLUDE=1;ka.SHADERBLOCK=2;ka.SNIPPET=3;ka.EVENT=4;ka.prototype.parse=function(){var a=this.code.replace(/(\/\*([\s\S]*?)\*\/)|(\/\/(.*)$)/gm,"");this.fragments=[];this.pragmas={};this.uniforms={};this.streams=
{};this.includes={};this.snippets={};this.shader_blocks={};this.is_dynamic=!1;for(var b=[],a=a.split("\n"),c=0;c<a.length;c++){var e=a[c].trim();if(e.length)if("#"!=e[0]){var g=e.split(" ");if("uniform"==g[0]){var f=g[2].split(";");this.uniforms[f[0]]=g[1]}else"attribute"==g[0]&&(f=g[2].split(";"),this.attributes[f[0]]=g[1]);b.push(e)}else if(g=e.split(" "),"#pragma"==g[0]){f=b.join("\n");f.trim()&&this.fragments.push({type:ka.CODE,code:f});this.is_dynamic=!0;this.pragmas[g[2]]=!0;f=g[1];b.length=
0;var e={type:ka.PRAGMA,line:e,action:f,param:g[2]},h=d.GLSLCode.pragma_methods[f];h&&h.parse?!1!==h.parse.call(this,e,g)&&this.fragments.push(e):console.warn("#pragma action unknown: ",f)}else b.push(e)}b.length&&(f=b.join("\n"),f.trim()&&this.fragments.push({type:ka.CODE,code:f}));return!0};ka.prototype.getFinalCode=function(a,b,c){if(!this.is_dynamic)return this.code;var e="";c=c||{};for(var d=this.fragments,f=0;f<d.length;++f){var h=d[f];if(h.type===ka.CODE)e+=h.code;else{var k=ka.pragma_methods[h.action];
k&&k.getCode?(h=k.getCode.call(this,a,h,b,c))&&(e+=h):e+="\n"}}return e};ka.pragma_methods.include={parse:function(a,b){if(!b[2])return console.error("shader include without path"),!1;a.action_type=ka.INCLUDE;var c=b[2].substr(1,b[2].length-2).split(":"),e=c[1];a.include=c[0];a.include_subfile=e;this.includes[a.include]=!0},getCode:function(a,b,c,e){a="";a=b.include;if(d.ResourcesManager.getExtension(a)){c=d.ResourcesManager.getResource(a,d.ShaderCode);if(!c)return d.ResourcesManager.load(a),null;
if(b.include_subfile){b=c._subfiles[b.include_subfile];if(void 0===b)return null;a="\n"+b+"\n"}else a="\n"+c._subfiles[""]+"\n"}else{b=d.Shaders.getSnippet(a);if(!b)return null;a="\n"+b.code+"\n"}return a}};ka.pragma_methods.define={parse:function(a,b){var c=b[2],e=b[3];if(!c||!e)return console.error("#pragma define missing parameters"),!1;a.define=[c,e.substr(1,e.length-2)]},getCode:function(a,b,c,e){e[b.define[0]]=b.define[1]}};ka.pragma_methods.shaderblock={parse:function(a,b){if(!b[2])return console.error("#pragma shaderblock without name"),
!1;a.action_type=ka.SHADERBLOCK;var c=b[2];'"'==c[0]?(a.shader_block=[1,c.substr(1,c.length-2)],this.shader_blocks[a.shader_block[1]]=!0):(a.shader_block=[2,c],b[3]&&(a.shader_block.push(b[3].substr(1,b[3].length-2)),this.shader_blocks[a.shader_block[2]]=!0))},getCode:function(a,b,c,e){var g=b.shader_block[1];if(2==b.shader_block[0]&&(g=e[g]?e[g]:b.shader_block[2],!g))return console.error("ShaderBlock: no context var found: "+g),null;g=d.Shaders.getShaderBlock(g);if(!g)return null;b="\n";g.flag_mask&
c&&(b="\n#define BLOCK_"+g.name.toUpperCase()+"\n");(a=g.getFinalCode(a,c,e))&&(b+=a+"\n");return b}};ka.pragma_methods.snippet={parse:function(a,b){if(!b[2])return console.error("#pragma snippet without name"),!1;a.action_type=ka.SNIPPET;var c=b[2].substr(1,b[2].length-2);a.snippet=c;this.snippets[c]=!0},getCode:function(a,b,c,e){a=d.Shaders.getSnippet(b.snippet);return a?"\n"+a.code+"\n":(console.error("ShaderCode uses unknown Snippet: ",b.snippet),null)}};ka.pragma_methods.event={parse:function(a,
b){if(!b[2])return console.error("#pragma event without name"),!1;a.action_type=ka.EVENT;var c=b[2].substr(1,b[2].length-2);a.event=c},getCode:function(a,b,c,e){a="\n";e=0;for(var g=d.Shaders.shader_blocks.length;e<g;++e){var f=d.Shaders.shader_blocks[e];c&f.flag_mask&&f.events&&(f=f.events[b.event])&&(a+=f+"\n")}return a}};ka.breakLines=function(a){for(var b=[],c=0;c<a.length;c++){var e=a[c].trim();if(e){var d=e.lastIndexOf(";");if(-1==d||d==a.length-1)b.push(e);else for(e=e.split(";"),d=0;d<e.length;++d)e[d]&&
b.push(e[d]+";")}}return b};d.Shaders.registerSnippet("input","\n\t\t\t//used to store topology input information\n\t\t\tstruct Input {\n\t\t\t\tvec4 color;\n\t\t\t\tvec3 vertex;\n\t\t\t\tvec3 normal;\n\t\t\t\tvec2 uv;\n\t\t\t\tvec2 uv1;\n\t\t\t\t\n\t\t\t\tvec3 camPos;\n\t\t\t\tvec3 viewDir;\n\t\t\t\tvec3 worldPos;\n\t\t\t\tvec3 worldNormal;\n\t\t\t\tvec4 screenPos;\n\t\t\t};\n\t\t\t\n\t\t\tInput getInput()\n\t\t\t{\n\t\t\t\tInput IN;\n\t\t\t\tIN.color = vec4(1.0);\n\t\t\t\tIN.vertex = v_pos;\n\t\t\t\tIN.normal = v_normal;\n\t\t\t\tIN.uv = v_uvs;\n\t\t\t\tIN.uv1 = IN.uv;\n\t\t\t\t\n\t\t\t\tIN.camPos = u_camera_eye;\n\t\t\t\tIN.viewDir = normalize(u_camera_eye - v_pos);\n\t\t\t\tIN.worldPos = v_pos;\n\t\t\t\tIN.worldNormal = normalize(v_normal);\n\t\t\t\t//IN.screenPos = vec4( (v_screenpos.xy / v_screenpos.w) * 0.5 + vec2(0.5), v_screenpos.zw );  //sometimes we need also z and w, thats why we pass all\n\t\t\t\tIN.screenPos = vec4( (gl_FragCoord.xy / gl_FragCoord.w) * 0.5 + vec2(0.5), gl_FragCoord.zw );  //sometimes we need also z and w, thats why we pass all\n\t\t\t\treturn IN;\n\t\t\t}\n\t");
d.Shaders.registerSnippet("structs","\n\t\t\t//used to store topology input information\n\t\t\tstruct Input {\n\t\t\t\tvec4 color;\n\t\t\t\tvec3 vertex;\n\t\t\t\tvec3 normal;\n\t\t\t\tvec2 uv;\n\t\t\t\tvec2 uv1;\n\t\t\t\t\n\t\t\t\tvec3 camPos;\n\t\t\t\tvec3 viewDir;\n\t\t\t\tvec3 worldPos;\n\t\t\t\tvec3 worldNormal;\n\t\t\t\tvec4 screenPos;\n\t\t\t};\n\t\t\t\n\t\t\t//used to store surface shading properties\n\t\t\tstruct SurfaceOutput {\n\t\t\t\tvec3 Albedo;\n\t\t\t\tvec3 Normal; //separated in case there is a normal map\n\t\t\t\tvec3 Emission;\n\t\t\t\tvec3 Ambient;\n\t\t\t\tfloat Specular;\n\t\t\t\tfloat Gloss;\n\t\t\t\tfloat Alpha;\n\t\t\t\tfloat Reflectivity;\n\t\t\t\tvec4 Extra; //for special purposes\n\t\t\t};\n\t\t\t\n\t\t\t//used to store light contribution\n\t\t\t//CAREFUL: this one is different than \n\t\t\tstruct FinalLight {\n\t\t\t\tvec3 Color;\n\t\t\t\tvec3 Ambient;\n\t\t\t\tfloat Diffuse; //NdotL\n\t\t\t\tfloat Specular; //RdotL\n\t\t\t\tvec3 Emission;\n\t\t\t\tvec3 Reflection;\n\t\t\t\tfloat Attenuation;\n\t\t\t\tfloat Shadow; //1.0 means fully lit\n\t\t\t};\n\t");
d.Shaders.registerSnippet("spotFalloff","\n\t\t\tfloat spotFalloff(vec3 spotDir, vec3 lightDir, float angle_phi, float angle_theta)\n\t\t\t{\n\t\t\t\tfloat sqlen = dot(lightDir,lightDir);\n\t\t\t\tfloat atten = 1.0;\n\t\t\t\t\n\t\t\t\tvec4 spotParams = vec4( angle_phi, angle_theta, 1.0, 0.0 );\n\t\t\t\tspotParams.w = 1.0 / (spotParams.x-spotParams.y);\n\t\t\t\t\n\t\t\t\tvec3 dirUnit = lightDir * sqrt(sqlen); //we asume they are normalized\n\t\t\t\tfloat spotDot = dot(spotDir, -dirUnit);\n\t\t\t\tif (spotDot <= spotParams.y)// spotDot <= cos phi/2\n\t\t\t\t\treturn 0.0;\n\t\t\t\telse if (spotDot > spotParams.x) // spotDot > cos theta/2\n\t\t\t\t\treturn 1.0;\n\t\t\t\t\n\t\t\t\t// vertex lies somewhere beyond the two regions\n\t\t\t\tfloat ifallof = pow( (spotDot-spotParams.y)*spotParams.w,spotParams.z );\n\t\t\t\treturn ifallof;\n\t\t\t}\n\t");
d.Shaders.registerSnippet("getFlatNormal","\n\t\t\t#ifdef STANDARD_DERIVATIVES\n\t\t\t\tvec3 getFlatNormal(vec3 pos)\n\t\t\t\t{\n\t\t\t\t\tvec3 A = dFdx( pos );\n\t\t\t\t\tvec3 B = dFdy( pos );\n\t\t\t\t\treturn normalize( cross(A,B) );\n\t\t\t\t}\n\t\t\t#else\n\t\t\t\tvec3 getFlatNormal(vec3 pos)\n\t\t\t\t{\n\t\t\t\t\treturn vec3(0.0);\n\t\t\t\t}\n\t\t\t#endif\n\t");d.Shaders.registerSnippet("PackDepth32","\n\t\t\t\n\t\t\tfloat linearDepth(float z, float near, float far)\n\t\t\t{\n\t\t\t\treturn (z - near) / (far - near);\n\t\t\t}\n\t\t\tfloat linearDepthNormalized(float z, float near, float far)\n\t\t\t{\n\t\t\t\tfloat z_n = 2.0 * z - 1.0;\n\t\t\t\treturn 2.0 * near * far / (far + near - z_n * (far - near));\n\t\t\t}\n\t\t\t\n\t\t\t//packs depth normalized \n\t\t\tvec4 PackDepth32(float depth)\n\t\t\t{\n\t\t\t  const vec4 bitShift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );\n\t\t\t  const vec4 bitMask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );\n\t\t\t  vec4 comp = fract(depth * bitShift);\n\t\t\t  comp -= comp.xxyz * bitMask;\n\t\t\t  return comp;\n\t\t\t}\n");
d.Shaders.registerSnippet("perturbNormal","\n\t\t\t\tmat3 cotangent_frame(vec3 N, vec3 p, vec2 uv)\n\t\t\t\t{\n\t\t\t\t\t// get edge vectors of the pixel triangle\n\t\t\t\t\t#ifdef STANDARD_DERIVATIVES\n\t\t\t\t\t\n\t\t\t\t\tvec3 dp1 = dFdx( p );\n\t\t\t\t\tvec3 dp2 = dFdy( p );\n\t\t\t\t\tvec2 duv1 = dFdx( uv );\n\t\t\t\t\tvec2 duv2 = dFdy( uv );\n\t\t\t\t\t\n\t\t\t\t\t// solve the linear system\n\t\t\t\t\tvec3 dp2perp = cross( dp2, N );\n\t\t\t\t\tvec3 dp1perp = cross( N, dp1 );\n\t\t\t\t\tvec3 T = dp2perp * duv1.x + dp1perp * duv2.x;\n\t\t\t\t\tvec3 B = dp2perp * duv1.y + dp1perp * duv2.y;\n\t\t\t\t\t#else\n\t\t\t\t\tvec3 T = vec3(1.0,0.0,0.0); //this is wrong but its a fake solution\n\t\t\t\t\tvec3 B = cross(N,T);\n\t\t\t\t\tT = cross(B,N);\n\t\t\t\t\t#endif\n\t\t\t\t\t \n\t\t\t\t\t// construct a scale-invariant frame \n\t\t\t\t\tfloat invmax = inversesqrt( max( dot(T,T), dot(B,B) ) );\n\t\t\t\t\treturn mat3( T * invmax, B * invmax, N );\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvec3 perturbNormal( vec3 N, vec3 V, vec2 texcoord, vec3 normal_pixel )\n\t\t\t\t{\n\t\t\t\t\t#ifdef USE_POINTS\n\t\t\t\t\t\treturn N;\n\t\t\t\t\t#endif\n\t\t\t\t\t\n\t\t\t\t\t// assume N, the interpolated vertex normal and \n\t\t\t\t\t// V, the view vector (vertex to eye)\n\t\t\t\t\t//vec3 normal_pixel = texture2D(normalmap, texcoord ).xyz;\n\t\t\t\t\tnormal_pixel = normal_pixel * 255./127. - 128./127.;\n\t\t\t\t\tmat3 TBN = cotangent_frame(N, V, texcoord);\n\t\t\t\t\treturn normalize(TBN * normal_pixel);\n\t\t\t\t}\n\t\t");
d.Shaders.registerSnippet("bumpNormal","\n\t\t\t\t\n\t\t\t\t// Calculate the surface normal using screen-space partial derivatives of the height field\n\t\t\t\tvec3 bumpNormal(vec3 position, vec3 normal, sampler2D texture, vec2 uvs, float factor)\n\t\t\t\t{\n\t\t\t\t#ifdef STANDARD_DERIVATIVES\n\t\t\t        vec3 dpdx = dFdx(position);\n\t\t\t        vec3 dpdy = dFdy(position);\n\t\t\t\t\tvec3 r1 = cross(dpdy, normal);\n\t\t\t\t\tvec3 r2 = cross(normal, dpdx);\n\t\t\t\t\t\n\t\t\t\t\tvec2 dtdx = dFdx(uvs) * factor;\n\t\t\t\t\tvec2 dtdy = dFdy(uvs) * factor;\n\t\t\t\t\t\n\t\t\t        float h = texture2D( texture,  uvs ).r;\n\t\t\t        float hdx = texture2D( texture,  uvs + dtdx ).r;\n\t\t\t        float hdy = texture2D( texture,  uvs + dtdy ).r;\n\t\t\t\t\t\n\t\t\t\t\treturn normalize(normal + (r1 * (hdx - h) - r2 * (hdy - h)) / dot(dpdx, r1));\n\t\t\t\t#else\n\t\t\t\t\treturn normal;\n\t\t\t\t#endif\n\t\t\t\t}\n\t\t");
d.Shaders.registerSnippet("testClippingPlane","\n\t\t\tfloat testClippingPlane(vec4 plane, vec3 p)\n\t\t\t{\n\t\t\t\tif(plane.x == 0.0 && plane.y == 0.0 && plane.z == 0.0)\n\t\t\t\t\treturn 0.0;\n\t\t\t\treturn (dot(plane.xyz, p) - plane.w) / dot(plane.xyz,plane.xyz);\n\t\t\t}\n\t");d.Shaders.registerSnippet("computePointSize","\n\t\t\tfloat computePointSize(float radius, float w)\n\t\t\t{\n\t\t\t\tif(radius < 0.0)\n\t\t\t\t\treturn -radius;\n\t\t\t\treturn u_viewport.w * u_camera_perspective.z * radius / w;\n\t\t\t}\n\t");
var oc=d.Shaders.firstpass_block=new d.ShaderBlock("firstPass");oc.addCode(GL.FRAGMENT_SHADER,"","");oc.register();var pc=d.Shaders.lastpass_block=new d.ShaderBlock("lastPass");pc.addCode(GL.FRAGMENT_SHADER,"","");pc.register();(d.Shaders.vertex_color_block=new d.ShaderBlock("vertex_color")).register();(d.Shaders.coord1_block=new d.ShaderBlock("coord1")).register();var qc=d.Shaders.normalbuffer_block=new d.ShaderBlock("normalBuffer");qc.addCode(GL.FRAGMENT_SHADER,"","");qc.register();d.Formats={supported:{},
safe_parsing:!1,merge_smoothgroups:!1,addSupportedFormat:function(a,b){a.constructor===String&&(a=a.split(","));for(var c=0;c<a.length;++c){var e=a[c].toLowerCase();this.supported[e]&&console.warn("There is already another parser associated to this extension: "+e);this.supported[e]=b}},parse:function(a,b,c){c=c||{};var e=this.getFileFormatInfo(a);if(!e)return null;e.extension=c.extension?c.extension:d.ResourcesManager.getExtension(a);var g=this.supported[e.extension];if(!g||!g.parse)return console.error("Parser Error: No parser found for "+
e.extension+" format"),null;e=null;if(this.safe_parsing)try{e=g.parse(b,c,a)}catch(f){return console.error("Error parsing content",f),null}else e=g.parse(b,c,a);e&&(e.name=a);return e},TEXT_FORMAT:"text",JSON_FORMAT:"json",XML_FORMAT:"xml",BINARY_FORMAT:"binary",MESH_DATA:"MESH",IMAGE_DATA:"IMAGE",NONATIVE_IMAGE_DATA:"NONATIVE_IMAGE",SCENE_DATA:"SCENE",GENERIC_DATA:"GENERIC",getFileFormatInfo:function(a){a=a.substr(a.lastIndexOf(".")+1).toLowerCase();return this.supported[a]},guessType:function(a){if(!a)return null;
a=d.RM.getExtension(a).toLowerCase();return(a=this.supported[a])?a.resource:null},convertToDataURL:function(a){var b=document.createElement("canvas");b.width=a.width;b.height=a.height;var c=b.getContext("2d"),e=c.createImageData(a.width,a.height);if(3==a.bytesPerPixel)for(var d=0;d<b.width;++d)for(var f=0;f<b.height;++f){var h=f*b.width*4+4*d,k=(b.height-f-1)*b.width*3+3*d;e.data[h+2]=a.pixels[k];e.data[h+1]=a.pixels[k+1];e.data[h+0]=a.pixels[k+2];e.data[h+3]=255}else for(d=0;d<b.width;++d)for(f=
0;f<b.height;++f)h=f*b.width*4+4*d,k=(b.height-f-1)*b.width*4+4*d,e.data[h+0]=a.pixels[k+2],e.data[h+1]=a.pixels[k+1],e.data[h+2]=a.pixels[k+0],e.data[h+3]=a.pixels[k+3];c.putImageData(e,0,0);a.dataurl=b.toDataURL("image/png");return a.dataurl},computeMeshBounding:function(a){for(var b=[a[0],a[1],a[2]],c=[a[0],a[1],a[2]],e=0;e<a.length;e+=3){var d=[a[e],a[e+1],a[e+2]];d[0]<b[0]?b[0]=d[0]:d[0]>c[0]&&(c[0]=d[0]);d[1]<b[1]?b[1]=d[1]:d[1]>c[1]&&(c[1]=d[1]);d[2]<b[2]?b[2]=d[2]:d[2]>c[2]&&(c[2]=d[2])}a=
[0.5*(b[0]+c[0]),0.5*(b[1]+c[1]),0.5*(b[2]+c[2])];b=[b[0]-a[0],b[1]-a[1],b[2]-a[2]];return BBox.setCenterHalfsize(BBox.create(),a,b)}};d.Formats.addSupportedFormat("png,jpg,jpeg,webp,bmp,gif",{"native":!0,dataType:"arraybuffer",resource:"Texture",resourceClass:GL.Texture,has_preview:!0,type:"image"});d.Formats.addSupportedFormat("wbin",{dataType:"arraybuffer"});d.Formats.addSupportedFormat("json,js,txt,html,css,csv",{dataType:"text"});d.Formats.addSupportedFormat("glsl",{dataType:"text",resource:"ShaderCode",
resourceClass:d.ShaderCode});d.Formats.addSupportedFormat("zip",{dataType:"arraybuffer"});WBin.classes=d.Classes;d.Formats.addSupportedFormat("mesh",{extension:"mesh",type:"mesh",resource:"Mesh",format:"text",dataType:"text",parse:function(a,b){b=b||{};var c=(0,GL.Mesh.parsers.mesh)(a,b);(0==c.bounding.radius||isNaN(c.bounding.radius))&&console.log("no radius found in mesh");return c}});GL.Mesh.prototype.convertBoneNames=function(a,b){if(!this.bones||!this.bones.length)return 0;a=a||d.GlobalScene;
a.constructor==d.Scene&&(a=a.root);if(!a.findNode)return console.error("convertBoneNames first parameter must be node or scene"),0;for(var c=!1,e=0;e<this.bones.length;++e){var g=this.bones[e],f=g[0];if(b)f[0]!=d._uid_prefix&&((h=a.findNode(f))?(g[0]=h.uid,c=!0):console.warn("Bone node not found: "+f));else if(f[0]==d._uid_prefix){var h=a.findNode(f);h?(g[0]=h.name,c=!0):console.warn("Bone node not found: "+f)}}c&&d.RM.resourceModified(this)};B["@color"]={type:"color"};B.icon="mini-icon-material.png";
B.last_index=0;B.NO_LIGHTS=0;B.ONE_LIGHT=1;B.SEVERAL_LIGHTS=2;B.EXTENSION="json";B.COLOR="color";B.OPACITY="opacity";B.SPECULAR_FACTOR="specular_factor";B.SPECULAR_GLOSS="specular_gloss";B.OPACITY_TEXTURE="opacity";B.COLOR_TEXTURE="color";B.AMBIENT_TEXTURE="ambient";B.SPECULAR_TEXTURE="specular";B.EMISSIVE_TEXTURE="emissive";B.ENVIRONMENT_TEXTURE="environment";B.IRRADIANCE_TEXTURE="irradiance";B.COORDS_UV0=0;B.COORDS_UV1=1;B.COORDS_UV0_TRANSFORMED=2;B.COORDS_UV1_TRANSFORMED=3;B.TEXTURE_COORDINATES=
{uv0:B.COORDS_UV0,uv1:B.COORDS_UV1,uv0_transformed:B.COORDS_UV0_TRANSFORMED,uv1_transformed:B.COORDS_UV1_TRANSFORMED};B.available_shaders="default global lowglobal phong_texture flat normal phong flat_texture cell_outline".split(" ");B.prototype.fillUniforms=function(a,b){var c={},e=[];c.u_material_color=this._color;c.u_ambient_color=a.info?a.info.ambient_color:d.ONES;c.u_texture_matrix=this.uvs_matrix;c.u_specular=vec2.create([1,50]);var g=c.u_reflection=0,f;for(f in this.textures){var h=this.getTextureSampler(f);
if(h){var k=B.getTextureFromSampler(h);k&&(e[g]=h,c[f+(k.texture_type==gl.TEXTURE_2D?"_texture":"_cubemap")]=g,g++)}}for(f in this.extra_uniforms)c[f]=this.extra_uniforms[f];this._uniforms=c;this._samplers=e};B.prototype.configure=function(a){for(var b in a)"function"!==typeof a[b]&&!this.setProperty(b,a[b])&&d.debug&&console.warn("Material property not assigned: "+b)};B.prototype.serialize=function(a){var b=d.cloneObject(this);delete b.filename;delete b.fullpath;delete b.remotepath;b.material_class=
d.getObjectClassName(this);a&&(delete b.render_state,delete b.flags,b.uvs_matrix&&b.uvs_matrix.equal([1,0,0,0,1,0,0,0,1])&&delete b.uvs_matrix);return b};B.prototype.clone=function(){var a=this.serialize();a.uid&&delete a.uid;return new this.constructor(JSON.parse(JSON.stringify(a)))};B.prototype.loadAndSetTexture=function(a,b,c){c=c||{};var e=this;if(b&&b.constructor===String)":"!=b[0]?d.ResourcesManager.load(b,c,function(b){e.setTexture(a,b);if(c.on_complete)c.on_complete()}):this.setTexture(a,
b);else if(this.setTexture(a,b),c.on_complete)c.on_complete()};B.prototype.getPropertiesInfo=function(){var a={color:"vec3",opacity:"number",uvs_matrix:"mat3"},b=this.getTextureChannels(),c;for(c in b)a["tex_"+b[c]]="Texture";return a};B.prototype.getProperty=function(a){return"tex_"==a.substr(0,4)?this.textures[a.substr(4)]:this[a]};B.prototype.setProperty=function(a,b){if(void 0!==b){if("tex_"==a.substr(0,4))return(!b||b.constructor!==String&&b.constructor!==GL.Texture)&&b||this.setTexture(a.substr(4),
b),!0;switch(a){case "queue":case "opacity":null!==b&&b.constructor===Number&&(this[a]=b);break;case "uid":this[a]=b;break;case "uvs_matrix":case "color":this[a].length==b.length&&this[a].set(b);break;case "textures":for(var c in b){var e=b[c];e&&e.constructor===String&&(e={texture:e,uvs:0,wrap:0,minFilter:0,magFilter:0});e._must_update=!0;this.textures[c]=e;null!=e.uvs&&e.uvs.constructor===String&&(e.uvs=0);this.textures[c]&&this.textures[c].texture&&(this.textures[c].texture=d.ResourcesManager.cleanFullpath(this.textures[c].texture))}break;
case "flags":for(c in b)this.flags[c]=b[c];break;case "transparency":this.opacity=1-b;break;case "render_state":this._render_state.configure(b);break;case "material_class":case "object_type":break;default:return!1}return!0}};B.prototype.setPropertyValueFromPath=function(a,b,c){c=c||0;a.length<c+1||this.setProperty(a[c],b)};B.prototype.getPropertyInfoFromPath=function(a){if(!(1>a.length)){a=a[0];var b=null;switch(a){case "queue":case "opacity":case "transparency":b="number";break;case "uvs_matrix":b=
"mat3";break;case "color":b="vec3";break;case "textures":b="Texture";break;default:return null}return{node:this._root,target:this,name:a,value:this[a],type:b}}};B.prototype.getTextureChannels=function(){return[]};B.prototype.setTexture=function(a,b,c){if(!a)throw"Material.prototype.setTexture channel must be specified";if(b){b.constructor===String&&(b=d.ResourcesManager.cleanFullpath(b));var e=this.textures[a];if(e)if(e.texture!=b||c)e.texture=b;else return e;else this.textures[a]=e={texture:b,uvs:0,
wrap:0,minFilter:0,magFilter:0,missing:"white"};if(c)for(var g in c)e[g]=c[g];e._must_update=!0;b.constructor===String&&":"!=b[0]&&d.ResourcesManager.load(b);return e}delete this.textures[a]};B.prototype.setTextureProperty=function(a,b,c){var e=this.textures[a];e?e[b]=c:"texture"==b&&(this.textures[a]={texture:c,uvs:0,wrap:0,minFilter:0,magFilter:0})};B.prototype.getTexture=function(a){a=a||B.COLOR_TEXTURE;a=this.textures[a];return a?a.constructor===String?d.ResourcesManager.textures[a]:(a=a.texture)?
a.constructor===String?d.ResourcesManager.textures[a]:a.constructor==Texture?a:null:null:null};B.prototype.getTextureSampler=function(a){return this.textures[a]};B.getTextureFromSampler=function(a){a=a.constructor===String?a:a.texture;if(!a)return null;a.constructor===String&&(a=d.ResourcesManager.textures[a]);return a&&a.constructor==GL.Texture?a:null};B.prototype.setTextureSampler=function(a,b){if(!a)throw"Cannot call Material setTextureSampler without channel";b?this.textures[a]=b:delete this.textures[a]};
B.prototype.getResources=function(a){for(var b in this.textures){var c=this.textures[b];c&&"string"==typeof c.texture&&(a[c.texture]=GL.Texture)}return a};B.prototype.onResourceRenamed=function(a,b,c){c=!1;for(var e in this.textures){var d=this.textures[e];d&&d.texture==a&&(d.texture=b,c=!0)}return c};B.prototype.loadTextures=function(){var a=this.getResources({}),b;for(b in a)d.ResourcesManager.load(b)};B.prototype.registerMaterial=function(a){this.name=a;d.ResourcesManager.registerResource(a,this);
this.material=a};B.prototype.getCategory=function(){return this.category||"Material"};B.prototype.getLocator=function(){return this._root?this._root.uid+"/material":this.uid};B.prototype.assignToNode=function(a){if(!a)return!1;var b=this.fullpath||this.filename;a.material=b?b:this;return!0};B.prototype.createProperty=function(a,b,c,e){c&&(d.validatePropertyType(c),this.constructor["@"+a]={type:c});e&&(this.constructor["@"+a]||(this.constructor["@"+a]={}),d.cloneObject(e,this.constructor["@"+a]));
null!=b&&(b.constructor===Number||b.constructor===String||b.constructor===Boolean?this[a]=b:b.constructor===Float32Array&&(c="_"+a,b=new Float32Array(b),this[c]=b,Object.defineProperty(this,a,{get:function(){return b},set:function(a){b.set(a)},enumerable:!0,configurable:!0})))};B.prototype.prepare=function(a){this._uniforms||(this._uniforms={},this._samplers=[]);if(this.onPrepare)this.onPrepare(a);this.fillUniforms(a)};B.prototype.getShader=function(a){a=B._shader_color;a||(a=B._shader_color=new GL.Shader(d.Shaders.common_vscode+
"void main(){ vec4 vertex = u_model * a_vertex;\ngl_Position = u_viewprojection * vertex;\n }",d.Shaders.common_vscode+"uniform vec4 u_color;\n\void main(){ gl_FragColor = u_color;\n }"));return a};B.prototype.renderInstance=function(a,b,c){b=d.Renderer;var e=d.Renderer._current_camera,g=d.Renderer._current_scene,f=d.Renderer._render_uniforms;f.u_model=a.matrix;f.u_normal_model=a.normal_matrix;this._render_state.enable();d.Renderer.bindSamplers(this._samplers);if(this.onRenderInstance)this.onRenderInstance(a);
c=shader_code.getShader(c.name);if(!c)return!1;c.uniformsArray([g._uniforms,e._uniforms,f,this._uniforms,a.uniforms]);a.render(c,-1!=this._primitive?this._primitive:void 0);b._rendercalls+=1;return!0};d.registerResourceClass(B);d.Material=B;Object.defineProperty(K.prototype,"shader",{enumerable:!0,get:function(){return this._shader},set:function(a){a&&(a=d.ResourcesManager.cleanFullpath(a));this._shader!=a&&(this._shader_code=null,this._shader=a,this.processShaderCode())}});Object.defineProperty(K.prototype,
"shader_code",{enumerable:!1,get:function(){return this._shader_code},set:function(a){this._shader=null;this._shader_code=a;this.processShaderCode()}});Object.defineProperty(K.prototype,"properties",{enumerable:!0,get:function(){return this._properties},set:function(a){if(a){this._properties=a;this._properties_by_name={};for(var b in this._properties)a=this._properties[b],this._properties_by_name[a.name]=a}}});Object.defineProperty(K.prototype,"enableLights",{enumerable:!0,get:function(){return 0!=
this._light_mode},set:function(a){this._light_mode=a?1:0}});Object.defineProperty(K.prototype,"version",{enumerable:!1,get:function(){return this._version},set:function(a){console.error("version cannot be set manually")}});K.prototype.addPass=function(a,b,c,e){this._passes[a]={vertex:b,fragment:c,macros:e}};K.prototype.prepare=function(a){this.fillUniforms();if(this.onPrepare)this.onPrepare(a)};K.prototype.fillUniforms=function(){var a=this._samplers;a.length=0;this._uniforms.u_material_color=this._color;
for(var b=0;b<this._properties.length;++b){var c=this._properties[b];c.internal||(c.is_texture?(this._uniforms[c.uniform]=a.length,c.value?a.push(c.value):a.push(" ")):this._uniforms[c.uniform]=c.value)}};K.prototype.setProperty=function(a,b){if(B.prototype.setProperty.call(this,a,b))return!0;if("shader"==a)this.shader=b;else if("properties"==a){this.properties.length=0;this._properties_by_name={};for(var c=0;c<b.length;++c){var e=b[c];e.is_texture&&e.value&&e.value.constructor===String&&(e.value=
{texture:e.value});this.properties[c]=e;this._properties_by_name[e.name]=e}}else if(this._properties_by_name[a])e=this._properties_by_name[a],e.value&&e.value.constructor!==String&&e.value.length?e.value.set(b):e.value=b;else return!1;return!0};K.prototype.processShaderCode=function(){if(!this._shader_code&&!this._shader)return this._properties.length=0,this._properties_by_name={},this._passes={},this._samplers.length=0,!1;var a=this._shader_code;!a&&this._shader&&(a=d.ResourcesManager.getResource(this.shader));
if(!a||a.constructor!==d.ShaderCode)return!1;var b=this._properties_by_name;this._properties.length=0;this._properties_by_name={};this._passes={};this._light_mode=this._samplers.length=0;this._primitive=-1;this._queue=d.RenderQueue.GEOMETRY;this._render_state.init();for(var c in this)this.hasOwnProperty(c)&&this[c]&&this[c].constructor===Function&&delete this[c];if(a._functions.init)if(d.catch_exceptions)try{a._functions.init.call(this)}catch(e){d.dispatchCodeError(e)}else a._functions.init.call(this);
for(c in a._global_uniforms){var g=a._global_uniforms[c];g.disabled||this.createUniform(g.name,g.uniform,g.type,g.value,g.options)}this._shader_version=a._version;this._version++;this.assignOldProperties(b)};K.prototype.assignOldProperties=function(a){var b=null,c=this.getShaderCode();c&&(b=c.getShader());for(c=0;c<this._properties.length;++c){var e=this._properties[c];if(a[e.name]){var d=a[e.name];if(void 0!==d.value){if(!d.internal&&b&&!e.is_texture){var f=b.uniformInfo[e.uniform];if(!f)continue;
if(void 0!==e.value&&!GL.Shader.validateValue(e.value,f)){e.value=void 0;continue}}e.value&&e.value.set?d.value&&d.value.length&&e.value.length&&d.value.length<=e.value.length?e.value.set(d.value):e.value=d.value:e.value=d.value}}}};K.nolights_vec4=new Float32Array([0,0,0,1]);K.prototype.renderInstance=function(a,b,c){var e=this.getShaderCode(a,b,c);if(!e||e.constructor!==d.ShaderCode)return!0;e._version!==this._shader_version&&this.processShaderCode&&this.processShaderCode();var g=d.Renderer,f=d.Renderer._current_camera,
h=d.Renderer._current_scene,k=d.Renderer._uniforms;k.u_model=a.matrix;k.u_normal_model=a.normal_matrix;var l=a.computeShaderBlockFlags(),n=d.Renderer._global_shader_blocks_flags;if(c==tb){var n=n|d.ShaderMaterial.reflection_block.flag_mask,p=this.textures.environment,p=p&&p.texture?p.texture:null;p||(d.Renderer._global_textures.environment&&(p=d.Renderer._global_textures.environment),a._nearest_reflection_probe&&a._nearest_reflection_probe._texture&&(p=a._nearest_reflection_probe._tex_id));if(p)var m=
d.ResourcesManager.textures[p],n=m&&m.texture_type==GL.TEXTURE_2D?m._is_planar?n|Pb.flag_mask:n|Qb.flag_mask:n|Rb.flag_mask;this._samplers[d.Renderer.ENVIRONMENT_TEXTURE_SLOT]=p}else this._samplers[d.Renderer.ENVIRONMENT_TEXTURE_SLOT]=null;this._render_state.enable(b);d.Renderer.bindSamplers(this._samplers);d.Renderer.bindSamplers(a.samplers);a.vertex_buffers.colors&&(l|=d.Shaders.vertex_color_block.flag_mask);a.vertex_buffers.coords1&&(l|=d.Shaders.coord1_block.flag_mask);if(this.onRenderInstance)this.onRenderInstance(a);
if(c==ec){l|=d.Shaders.firstpass_block.flag_mask;l|=d.Shaders.lastpass_block.flag_mask;l=e.getShader(c.name,l);if(!l)return!1;l.uniformsArray([h._uniforms,f._uniforms,k,this._uniforms,a.uniforms]);gl.disable(gl.BLEND);a.render(l,-1!=this._primitive?this._primitive:void 0);g._rendercalls+=1;return!0}p=null;(m=c!=tb||b.lights_disabled||this._light_mode===B.NO_LIGHTS)||(p=d.Renderer.getNearLights(a));d.Renderer._use_normalbuffer&&(l|=d.Shaders.normalbuffer_block.flag_mask);if(!p||0==p.length||m){m||
(l|=n);l|=d.Shaders.firstpass_block.flag_mask;l|=d.Shaders.lastpass_block.flag_mask;l=e.getShader(null,l);if(!l)return!1;l.uniformsArray([h._uniforms,f._uniforms,k,this._uniforms,a.uniforms]);l.setUniform("u_light_info",K.nolights_vec4);m&&l.setUniform("u_ambient_light",d.ONES);a.render(l,-1!=this._primitive?this._primitive:void 0);g._rendercalls+=1;return!0}for(var m=l,f=[h._uniforms,f._uniforms,k,null,this._uniforms,a.uniforms],h=null,k=0,q=p.length;k<q;++k){var s=p[k],l=s.applyShaderBlockFlags(m,
c,b),l=l|n;0==k&&(l|=d.Shaders.firstpass_block.flag_mask);k==q-1&&(l|=d.Shaders.lastpass_block.flag_mask);(l=e.getShader(null,l))?(d.Renderer.bindSamplers(s._samplers),s._uniforms.u_light_info[2]=k,s._uniforms.u_light_info[3]=p.length,f[3]=s._uniforms,h!=l?l.uniformsArray(f):l.uniforms(s._uniforms),h=l,1==k&&(gl.depthMask(!1),gl.depthFunc(gl.EQUAL),gl.enable(gl.BLEND),gl.blendFunc(gl.SRC_ALPHA,gl.ONE)),a.render(l,-1!=this._primitive?this._primitive:void 0),g._rendercalls+=1):console.warn("material without pass: "+
c.name)}gl.disable(gl.BLEND);gl.depthMask(!0);gl.depthFunc(gl.LESS);return!0};K.prototype.renderPickingInstance=function(a,b,c){var e=this.getShaderCode(a,b,c);if(e&&e.constructor===d.ShaderCode){var g=d.Renderer,f=d.Renderer._current_camera,h=a.node,k=d.Renderer._uniforms;k.u_model=a.matrix;k.u_normal_model=a.normal_matrix;var l=a.computeShaderBlockFlags();this._render_state.enable(b);d.Renderer.bindSamplers(this._samplers);d.Renderer.bindSamplers(a.samplers);b=e.getShader(c.name,l);if(!b&&(e=d.ShaderMaterial.getDefaultPickingShaderCode(),
b=e.getShader(c.name,l),!b))return!1;b.uniformsArray([f._uniforms,k,this._uniforms,a.uniforms]);c=d.Picking.getNextPickingColor(a.picking_node||h);b.setUniform("u_material_color",c);a.render(b,-1!=this._primitive?this._primitive:void 0);g._rendercalls+=1;gl.disable(gl.BLEND);gl.depthMask(!0);gl.depthFunc(gl.LESS);return!0}};K.prototype.getTextureChannels=function(){var a=[],b;for(b in this._properties){var c=this._properties[b];c.is_texture&&a.push(c.name)}return a};K.prototype.getResources=function(a){this.shader&&
(a[this.shader]=d.ShaderCode);for(var b in this._properties){var c=this._properties[b];if(c.value&&c.is_texture&&c.value){var e=null;(e=c.value.texture?c.value.texture:a[c.value])&&e.constructor===String&&(a[e]=GL.Texture)}}return a};K.prototype.getPropertyInfoFromPath=function(a){if(!(1>a.length)){var b=B.prototype.getPropertyInfoFromPath.call(this,a);if(b)return b;a=a[0];for(var b=0,c=this.properties.length;b<c;++b){var e=this.properties[b];if(e.name==a)return{node:this._root,target:this,name:e.name,
value:e.value,type:e.type}}}};K.prototype.getShaderCode=function(a,b,c){a=this._shader_code||d.ResourcesManager.getResource(this._shader);if(!a||a.constructor!==d.ShaderCode)return null;a._version!==this._shader_version&&this.processShaderCode&&(a._version=this._shader_version,this.processShaderCode());return a};K.prototype.applyToTexture=function(a,b){if(!this.shader||!a)return!1;var c=this.getShaderCode();if(!c)return!1;var e=c.getShader("fx");if(!e)return!1;this.fillUniforms();this._uniforms.u_time=
d.GlobalScene._time;this._uniforms.u_viewport=gl.viewport_data;d.Renderer.bindSamplers(this._samplers);gl.disable(gl.DEPTH_TEST);gl.disable(gl.CULL_FACE);b?b.drawTo(function(){a.toViewport(e,this._uniforms)}):a.toViewport(e,this._uniforms)};K.prototype.createUniform=function(a,b,c,e,d){if(!a||!b)throw"parameter missing in createUniform";c=c||"Number";if(c.constructor!==String)throw"type must be string";if((e=e||0)&&e.length)e=new Float32Array(e);else switch(c){case "vec2":e=vec2.create();break;case "color":case "vec3":e=
vec3.create();break;case "color4":case "vec4":e=vec4.create();break;case "mat3":e=mat3.create();break;case "mat4":e=mat4.create()}b={name:a,uniform:b,value:e,type:c,is_texture:0};if("texture"==c.toLowerCase()||"sampler2D"==c||"samplerCube"==c||"sampler"==c)b.is_texture="samplerCube"==c?2:1;b.is_texture&&(b.sampler={},b.type="sampler",b.sampler_slot=this._samplers.length,this._samplers.push(b.sampler));if(d)for(var f in d)b[f]=d[f];this._properties.push(b);this._properties_by_name[a]=b};K.prototype.createSampler=
function(a,b,c,e){if(!a||!b)throw"parameter missing in createSampler";var d="sampler";c&&c.type&&(d=c.type);var f=null;if(this._properties_by_name[a]){var h=this._properties_by_name[a];h.type==d&&h.value&&(f=h.value)}f||(f={texture:e});b={name:a,uniform:b,value:f,type:d,is_texture:1,sampler_slot:-1};if(c){c.filter&&(f.magFilter=c.filter,f.minFilter=c.filter,delete c.filter);c.wrap&&(f.wrapS=c.wrap,f.wrapT=c.wrap,delete c.wrap);for(var k in c)f[k]=c[k]}b.sampler_slot=this._samplers.length;this._properties.push(b);
this._properties_by_name[a]=b;this._samplers.push(b.value)};K.prototype.createProperty=function(a,b,c,e){var d=this._properties_by_name[a];if(!d||d.type!=c){d={name:a,type:c,internal:!0,value:b};if(e)for(var f in e)d[f]=e[f];this._properties.push(d);this._properties_by_name[a]=d;Object.defineProperty(this,a,{get:function(){var b=this._properties_by_name[a];if(b)return b.value},set:function(b){var c=this._properties_by_name[a];c&&(c.value&&c.value.set?c.value.set(b):c.value=b)},enumerable:!1,configurable:!0})}};
K.prototype.onResourceRenamed=function(a,b,c){c=B.prototype.onResourceRenamed.call(this,a,b,c);this.shader==a&&(this.shader=b,c=!0);for(var e=0;e<this._properties.length;++e){var d=this._properties[e];!d.internal&&d.is_texture&&d.value&&d.value.texture==a&&(d.value.texture=b,c=!0)}return c};K.getDefaultPickingShaderCode=function(){if(K.default_picking_shader_code)return K.default_picking_shader_code;var a=new d.ShaderCode;a.code=d.ShaderCode.flat_code;return K.default_picking_shader_code=a};d.registerMaterialClass(K);
d.ShaderMaterial=K;Object.defineProperty(J.prototype,"detail_factor",{get:function(){return this._detail[0]},set:function(a){this._detail[0]=a},enumerable:!0});Object.defineProperty(J.prototype,"detail_scale",{get:function(){return this._detail.subarray(1,3)},set:function(a){this._detail[1]=a[0];this._detail[2]=a[1]},enumerable:!0});Object.defineProperty(J.prototype,"emissive_extra",{get:function(){return this._emissive[3]},set:function(a){this._emissive[3]=a},enumerable:!0});Object.defineProperty(J.prototype,
"specular_factor",{get:function(){return this._specular_data[0]},set:function(a){null!=a&&a.constructor===Number&&(this._specular_data[0]=a)},enumerable:!0});Object.defineProperty(J.prototype,"specular_gloss",{get:function(){return this._specular_data[1]},set:function(a){this._specular_data[1]=a},enumerable:!0});J["@blend_mode"]={type:"enum",values:d.Blend};J.actions={};J.DETAIL_TEXTURE="detail";J.NORMAL_TEXTURE="normal";J.DISPLACEMENT_TEXTURE="displacement";J.BUMP_TEXTURE="bump";J.REFLECTIVITY_TEXTURE=
"reflectivity";J.EXTRA_TEXTURE="extra";J.IRRADIANCE_TEXTURE="irradiance";J.TEXTURES_INDEX={color:0,opacity:1,ambient:2,specular:3,emissive:4,detail:5,normal:6,displacement:7,bump:8,reflectivity:9,extra:10,environment:11};J.prototype.renderInstance=K.prototype.renderInstance;J.prototype.renderShadowInstance=K.prototype.renderShadowInstance;J.prototype.renderPickingInstance=K.prototype.renderPickingInstance;J.prototype.prepare=function(a){var b=this.flags,c=this._render_state;this._texture_settings||
(this._texture_settings=this._uniforms.u_texture_settings=new Uint8Array(9));c.cull_face=!b.two_sided;c.front_face=b.flip_normals?GL.CW:GL.CCW;c.depth_test=b.depth_test;c.depth_mask=b.depth_write;c.blend=this.blend_mode!=d.Blend.NORMAL;this.blend_mode!=d.Blend.NORMAL&&(b=d.BlendFunctions[this.blend_mode])&&(c.blendFunc0=b[0],c.blendFunc1=b[1]);for(var e in this.textures)if(c=this.textures[e])null==c.index&&(c.index=J.TEXTURES_INDEX[e]),this._texture_settings[c.index]=c.uvs;this._light_mode=this.flags.ignore_lights?
B.NO_LIGHTS:1;this.fillUniforms(a)};J.FLAGS={COLOR_TEXTURE:2,OPACITY_TEXTURE:4,SPECULAR_TEXTURE:8,REFLECTIVITY_TEXTURE:16,AMBIENT_TEXTURE:32,EMISSIVE_TEXTURE:64,DETAIL_TEXTURE:128,NORMAL_TEXTURE:256,DISPLACEMENT_TEXTURE:512,EXTRA_TEXTURE:1024,ENVIRONMENT_TEXTURE:2048,ENVIRONMENT_CUBEMAP:4096,IRRADIANCE_CUBEMAP:8192,DEGAMMA_COLOR:67108864,SPEC_ON_ALPHA:134217728,SPEC_ON_TOP:268435456,ALPHA_TEST:536870912};J.shader_codes={};J.prototype.getShaderCode=function(a,b,c){c=J.FLAGS;a=0;this.textures.color&&
(a|=c.COLOR_TEXTURE,this.textures.color.degamma&&(a|=c.DEGAMMA_COLOR));this.textures.opacity&&(a|=c.OPACITY_TEXTURE);this.textures.displacement&&(a|=c.DISPLACEMENT_TEXTURE);this.textures.normal&&(a|=c.NORMAL_TEXTURE);this.textures.specular&&(a|=c.SPECULAR_TEXTURE);0<this.reflection_factor&&this.textures.reflectivity&&(a|=c.REFLECTIVITY_TEXTURE);this.textures.emissive&&(a|=c.EMISSIVE_TEXTURE);this.textures.ambient&&(a|=c.AMBIENT_TEXTURE);this.textures.detail&&(a|=c.DETAIL_TEXTURE);this.textures.extra&&
(a|=c.EXTRA_TEXTURE);this.specular_on_alpha&&(a|=c.SPEC_ON_ALPHA);this.specular_on_top&&(a|=c.SPEC_ON_TOP);this.flags.alpha_test&&(a|=c.ALPHA_TEST);var e=d.StandardMaterial.shader_codes[a];if(e)return e;b={vs_local:"",fs:"",fs_shadows:""};a&c.DISPLACEMENT_TEXTURE&&(b.vs_local+="\tvertex4.xyz += v_normal * texture2D( displacement_texture, v_uvs ).x * u_displacementmap_factor;\n");b.fs+="\n\tuvs[0] = IN.uv;\n\tuvs[1] = IN.uv1;\n\tuvs[2] = (u_texture_matrix * vec3(uvs[0],1.0)).xy;\n\t#ifdef COORD1_BLOCK\n\t\tuvs[3] = (vec3(uvs[1],1.0) * u_texture_matrix).xy;\n\t#else\n\t\tuvs[3] = uvs[2];\n\t#endif\n";
b.fs_shadows+="\n\tuvs[0] = IN.uv;\n\tuvs[1] = IN.uv1;\n\tuvs[2] = (u_texture_matrix * vec3(uvs[0],1.0)).xy;\n\t#ifdef COORD1_BLOCK\n\t\tuvs[3] = (vec3(uvs[1],1.0) * u_texture_matrix).xy;\n\t#else\n\t\tuvs[3] = uvs[2];\n\t#endif\n";a&c.NORMAL_TEXTURE&&(b.fs+="vec2 normal_uv = getUVs( u_texture_settings["+J.TEXTURES_INDEX.normal+"]);\n\t\tvec3 normal_pixel = texture2D( normal_texture, normal_uv ).xyz;\n\t\tif( u_normal_info.y > 0.0 )\n\t\t{\n\t\t\tnormal_pixel.xy = vec2(1.0) - normal_pixel.xy;\n\t\t\tnormal_pixel = normalize( perturbNormal( IN.worldNormal, IN.viewDir, normal_uv, normal_pixel ));\n\t\t}\n\t\telse\n\t\t\tnormal_pixel = normal_pixel * 2.0 - vec3(1.0);\n\t\to.Normal = normalize( mix( o.Normal, normal_pixel, u_normal_info.x ) );\n");
a&c.COLOR_TEXTURE&&(e="\tvec4 tex_color = texture2D( color_texture, getUVs( u_texture_settings["+J.TEXTURES_INDEX.color+"] ) );\n",b.fs+=e,b.fs_shadows+=e,a&c.DEGAMMA_COLOR&&(b.fs+="\ttex_color.xyz = pow( tex_color.xyz, vec3(2.0) );\n"),e="\to.Albedo *= tex_color.xyz;\n\to.Alpha *= tex_color.w;\n",b.fs+=e,b.fs_shadows+=e);a&c.OPACITY_TEXTURE&&(e="\to.Alpha *= texture2D( opacity_texture, getUVs( u_texture_settings["+J.TEXTURES_INDEX.opacity+"]) ).x;\n",b.fs+=e,b.fs_shadows+=e);a&c.SPECULAR_TEXTURE&&
(b.fs+="\tvec4 spec_info = texture2D( specular_texture, getUVs( u_texture_settings["+J.TEXTURES_INDEX.specular+"]) );\n\to.Specular *= spec_info.x;\n\to.Gloss *= spec_info.y;\n");a&c.REFLECTIVITY_TEXTURE&&(b.fs+="\to.Reflectivity *= texture2D( reflectivity_texture, getUVs( u_texture_settings["+J.TEXTURES_INDEX.reflectivity+"]) ).x;\n");a&c.EMISSIVE_TEXTURE&&(b.fs+="\to.Emission *= texture2D( emissive_texture, getUVs( u_texture_settings["+J.TEXTURES_INDEX.emissive+"]) ).xyz;\n");a&c.AMBIENT_TEXTURE&&
(b.fs+="\to.Ambient *= texture2D( ambient_texture, getUVs( u_texture_settings["+J.TEXTURES_INDEX.ambient+"]) ).xyz;\n");a&c.DETAIL_TEXTURE&&(b.fs+="\to.Albedo += (texture2D( detail_texture, getUVs( u_texture_settings["+J.TEXTURES_INDEX.detail+"]) * u_detail_info.yz).xyz - vec3(0.5)) * u_detail_info.x;\n");a&c.EXTRA_TEXTURE&&(b.fs+="\tif(u_light_info.z == 0.0) o.Extra = u_extra_color * texture2D( extra_texture, getUVs( u_texture_settings["+J.TEXTURES_INDEX.extra+"] ) );\n");a&c.ALPHA_TEST&&(e="\tif(o.Alpha < 0.01) discard;\n",
b.fs+=e,b.fs_shadows+=e);a&c.SPEC_ON_TOP&&(b.fs+="\t#define SPEC_ON_TOP\n");a&c.SPEC_ON_ALPHA&&(b.fs+="\t#define SPEC_ON_ALPHA\n");e=new d.ShaderCode;c=J.code_template;if(J.onShaderCode)J.onShaderCode(b,this,a);e.code=ea.replaceCode(c,b);return d.StandardMaterial.shader_codes[a]=e};J.prototype.fillUniforms=function(a,b){var c=this._uniforms;c.u_reflection_info[0]=this.reflection_factor;c.u_reflection_info[1]=this.reflection_fresnel;c.u_backlight_factor=this.backlight_factor;c.u_normal_info[0]=this.normalmap_factor;
c.u_normal_info[1]=this.normalmap_tangent?1:0;c.u_displacementmap_factor=this.displacementmap_factor;c.u_velvet_info.set(this._velvet);c.u_velvet_info[3]=this.velvet_additive?this.velvet_exp:-this.velvet_exp;var e=0,g=this._samplers;g.length=0;for(var f in this.textures){var h=this.getTextureSampler(f);if(h){var k=h.texture;if(k){if(k.constructor===String)k=d.ResourcesManager.textures[k];else if(k.constructor!=Texture)continue;k||(h={texture:":missing"});k=e;"environment"==f?k=d.Renderer.ENVIRONMENT_TEXTURE_SLOT:
"irradiance"==f?k=d.Renderer.IRRADIANCE_TEXTURE_SLOT:e++;g[k]=h;c[f+"_texture"]=k}}}};J.prototype.getTextureChannels=function(){return[B.COLOR_TEXTURE,B.OPACITY_TEXTURE,B.AMBIENT_TEXTURE,B.SPECULAR_TEXTURE,B.EMISSIVE_TEXTURE,J.DETAIL_TEXTURE,J.NORMAL_TEXTURE,J.DISPLACEMENT_TEXTURE,J.BUMP_TEXTURE,J.REFLECTIVITY_TEXTURE,J.EXTRA_TEXTURE,B.ENVIRONMENT_TEXTURE,J.IRRADIANCE_TEXTURE]};J.prototype.setProperty=function(a,b){if(B.prototype.setProperty.call(this,a,b))return!0;switch(a){case "render_state":case "specular_factor":case "specular_gloss":case "backlight_factor":case "reflection_factor":case "reflection_fresnel":case "velvet_exp":case "velvet_additive":case "normalmap_tangent":case "normalmap_factor":case "bumpmap_factor":case "displacementmap_factor":case "detail_factor":case "emissive_extra":case "shader_name":case "specular_on_top":case "specular_on_alpha":case "normalmap_tangent":case "reflection_specular":case "use_scene_ambient":case "blend_mode":null!==
b&&(this[a]=b);break;case "flags":if(b)for(var c in b)this.flags[c]=b[c];break;case "ambient":case "emissive":case "velvet":case "extra":case "detail_scale":this[a].length>=b.length&&this[a].set(b);break;default:return!1}return!0};J.prototype.getPropertiesInfo=function(){var a=B.prototype.getPropertiesInfo.call(this);a.merge({shader_name:d.TYPES.STRING,blend_mode:d.TYPES.NUMBER,specular_factor:d.TYPES.NUMBER,specular_gloss:d.TYPES.NUMBER,backlight_factor:d.TYPES.NUMBER,reflection_factor:d.TYPES.NUMBER,
reflection_fresnel:d.TYPES.NUMBER,velvet_exp:d.TYPES.NUMBER,normalmap_factor:d.TYPES.NUMBER,bumpmap_factor:d.TYPES.NUMBER,displacementmap_factor:d.TYPES.NUMBER,emissive_extra:d.TYPES.NUMBER,ambient:d.TYPES.VEC3,emissive:d.TYPES.VEC3,velvet:d.TYPES.VEC3,extra:d.TYPES.VEC4,detail_factor:d.TYPES.NUMBER,detail_scale:d.TYPES.VEC2,specular_on_top:d.TYPES.BOOLEAN,normalmap_tangent:d.TYPES.BOOLEAN,reflection_specular:d.TYPES.BOOLEAN,use_scene_ambient:d.TYPES.BOOLEAN,velvet_additive:d.TYPES.BOOLEAN});return a};
J.prototype.getPropertyInfoFromPath=function(a){if(!(1>a.length)){var b=B.prototype.getPropertyInfoFromPath.call(this,a);if(b)return b;a=a[0];switch(a){case "blend_mode":case "backlight_factor":case "reflection_factor":case "reflection_fresnel":case "velvet_exp":case "normalmap_factor":case "bumpmap_factor":case "displacementmap_factor":case "emissive_extra":case "detail_factor":b=d.TYPES.NUMBER;break;case "extra":b=d.TYPES.VEC4;break;case "ambient":case "emissive":case "velvet":b=d.TYPES.VEC3;break;
case "detail_scale":b=d.TYPES.VEC2;break;case "specular_on_top":case "specular_on_alpha":case "normalmap_tangent":case "reflection_specular":case "use_scene_ambient":case "velvet_additive":b=d.TYPES.BOOLEAN;break;default:return null}return{node:this._root,target:this,name:a,value:this[a],type:b}}};J.clearShadersCache=function(){d.log("StandardMaterial ShaderCode cache cleared");J.shader_codes={}};d.registerMaterialClass(J);d.StandardMaterial=J;d.Classes.newStandardMaterial=J;J.code_template='\n\n\n\\color.vs\n\nprecision mediump float;\n//global defines from blocks\n#pragma shaderblock "vertex_color"\n#pragma shaderblock "coord1"\n\nattribute vec3 a_vertex;\nattribute vec3 a_normal;\nattribute vec2 a_coord;\n#ifdef BLOCK_COORD1\n\tattribute vec2 a_coord1;\n\tvarying vec2 v_uvs1;\n#endif\n#ifdef BLOCK_VERTEX_COLOR\n\tattribute vec4 a_color;\n\tvarying vec4 v_vertex_color;\n#endif\n\n//varyings\nvarying vec3 v_pos;\nvarying vec3 v_normal;\nvarying vec2 v_uvs;\nvarying vec3 v_local_pos;\nvarying vec3 v_local_normal;\n\n//matrices\n#ifdef BLOCK_INSTANCING\n\tattribute mat4 u_model;\n#else\n\tuniform mat4 u_model;\n#endif\nuniform mat4 u_normal_model;\nuniform mat4 u_view;\nuniform mat4 u_viewprojection;\n//material\nuniform float u_displacementmap_factor;\nuniform sampler2D displacement_texture;\n\n//globals\nuniform float u_time;\nuniform vec4 u_viewport;\nuniform float u_point_size;\n\n#pragma shaderblock "light"\n#pragma shaderblock "morphing"\n#pragma shaderblock "skinning"\n\n//camera\nuniform vec3 u_camera_eye;\nuniform vec2 u_camera_planes;\n\n#pragma event "vs_functions"\n\n//special cases\n{{vs_out}}\n\nvoid main() {\n\t\n\tvec4 vertex4 = vec4(a_vertex,1.0);\n\tv_local_pos = a_vertex;\n\tv_local_normal = a_normal;\n\tv_normal = a_normal;\n\tv_uvs = a_coord;\n\t#ifdef BLOCK_COORD1\n\t\tv_uvs1 = a_coord1;\n\t#endif\n\t#ifdef BLOCK_VERTEX_COLOR\n\t\tv_vertex_color = a_color;\n\t#endif\n\t\n\t//local deforms\n\t{{vs_local}}\n\tapplyMorphing( vertex4, v_normal );\n\tapplySkinning( vertex4, v_normal );\n\t\n\t//vertex\n\tv_pos = (u_model * vertex4).xyz;\n\t\n\tapplyLight(v_pos);\n\t\n\t//normal\n\t#ifdef SHADERBLOCK_INSTANCING\n\t\tv_normal = (u_model * vec4(v_normal,0.0)).xyz;\n\t#else\n\t\tv_normal = (u_normal_model * vec4(v_normal,0.0)).xyz;\n\t#endif\n\t//world deform\n\t{{vs_global}}\n\t\n\t#pragma event "vs_final_pass"\n\t\n\tgl_Position = u_viewprojection * vec4(v_pos,1.0);\n\tgl_PointSize = u_point_size;\n\t#pragma event "vs_final"\n}\n\n\\color.fs\n\n#ifdef DRAW_BUFFERS\n\t#extension GL_EXT_draw_buffers : require \n#endif\n\nprecision mediump float;\n\n//global defines from blocks\n#pragma shaderblock "vertex_color"\n#pragma shaderblock "coord1"\n//#pragma shaderblock "firstPass"\n//#pragma shaderblock "lastPass"\n\n//varyings\nvarying vec3 v_pos;\nvarying vec3 v_normal;\nvarying vec2 v_uvs;\nvarying vec3 v_local_pos;\nvarying vec3 v_local_normal;\n#ifdef BLOCK_COORD1\n\tvarying vec2 v_uvs1;\n#endif\n#ifdef BLOCK_VERTEX_COLOR\n\tvarying vec4 v_vertex_color;\n#endif\n\n//globals\nuniform vec4 u_viewport;\nuniform mat4 u_view;\nuniform vec3 u_camera_eye;\nuniform vec4 u_clipping_plane;\nuniform vec4 u_background_color;\nuniform vec4 u_material_color;\n\nuniform vec3 u_ambient_color;\nuniform vec4 u_emissive_color;\nuniform vec4 u_specular;\nuniform vec2 u_reflection_info;\nuniform vec4 u_velvet_info;\nuniform vec2 u_normal_info;\nuniform vec3 u_detail_info;\nuniform mat3 u_texture_matrix;\nuniform vec4 u_extra_color;\nuniform float u_backlight_factor;\n\nuniform sampler2D color_texture;\nuniform sampler2D opacity_texture;\nuniform sampler2D specular_texture;\nuniform sampler2D ambient_texture;\nuniform sampler2D emissive_texture;\nuniform sampler2D reflectivity_texture;\nuniform sampler2D detail_texture;\nuniform sampler2D normal_texture;\nuniform sampler2D extra_texture;\n\n\n#pragma shaderblock "light"\n#pragma shaderblock "light_texture"\n#pragma shaderblock "applyReflection"\n#pragma shaderblock "normalBuffer"\n\n#pragma snippet "perturbNormal"\n\n#pragma shaderblock "extraBuffers"\n\n\nuniform int u_texture_settings[11];\n\nvec2 uvs[4];\nvec2 getUVs(int index)\n{\n\tif(index == 0)\n\t\treturn uvs[0];\n\tif(index == 1)\n\t\treturn uvs[1];\n\tif(index == 2)\n\t\treturn uvs[2];\n\tif(index == 3)\n\t\treturn uvs[3];\n\treturn uvs[0];\n}\n\n\nvoid surf(in Input IN, out SurfaceOutput o)\n{\n\to.Albedo = u_material_color.xyz;\n\to.Alpha = u_material_color.a;\n\t#ifdef BLOCK_VERTEX_COLOR\n\to.Albedo *= IN.color.xyz;\n\to.Alpha *= IN.color.a;\n\t#endif\n\to.Normal = normalize( v_normal );\n\to.Specular = u_specular.x;\n\to.Gloss = u_specular.y;\n\to.Ambient = u_ambient_color;\n\to.Emission = u_emissive_color.xyz;\n\to.Reflectivity = u_reflection_info.x;\n\to.Extra = u_extra_color;\n\t\n\t{{fs}}\n\t\n\tif(u_velvet_info.w > 0.0)\n\t\to.Albedo += u_velvet_info.xyz * ( 1.0 - pow( max(0.0, dot( IN.viewDir, o.Normal )), u_velvet_info.w ));\n\telse if(u_velvet_info.w < 0.0)\n\t\to.Albedo = mix( o.Albedo, u_velvet_info.xyz, 1.0 - pow( max(0.0, dot( IN.viewDir, o.Normal )), abs(u_velvet_info.w) ) );\n\tif(u_emissive_color.w > 0.0)\n\t\to.Emission *= o.Albedo;\n\to.Reflectivity *= max(0.0, pow( 1.0 - clamp(0.0, dot(IN.viewDir,o.Normal),1.0), u_reflection_info.y ));\n}\n\n#pragma event "fs_functions"\n#pragma snippet "testClippingPlane"\n\n{{fs_out}}\n\nvoid main() {\n\tInput IN = getInput();\n\tif(testClippingPlane(u_clipping_plane,IN.worldPos) < 0.0)\n\t\tdiscard;\n\t\n\tIN.vertex = v_local_pos;\n\tIN.normal = v_local_normal;\n\tSurfaceOutput o = getSurfaceOutput();\n\t#ifdef BLOCK_VERTEX_COLOR\n\t\tIN.color = v_vertex_color;\n\t#endif\n\t#ifdef BLOCK_COORD1\n\t\tIN.uv1 = v_uvs1;\n\t#endif\n\tsurf(IN,o);\n\tLight LIGHT = getLight();\n\tapplyLightTexture( IN, LIGHT );\n\tif( !gl_FrontFacing )\n\t\to.Normal *= -1.0;\n\tFinalLight FINALLIGHT = computeLight( o, IN, LIGHT );\n\tFINALLIGHT.Diffuse += u_backlight_factor * max(0.0, dot(FINALLIGHT.Vector, -o.Normal));\n\tvec4 final_color = vec4( 0.0,0.0,0.0, o.Alpha );\n\t#ifdef SPEC_ON_ALPHA\n\t\tfinal_color.a += FINALLIGHT.Specular;\n\t#endif\n\t#ifdef SPEC_ON_TOP\n\t\tfloat specular = FINALLIGHT.Specular;\n\t\tFINALLIGHT.Specular = 0.0;\n\t#endif\n\tfinal_color.xyz = applyLight( o, FINALLIGHT );\n\t#ifdef SPEC_ON_TOP\n\t\tfinal_color.xyz += specular * LIGHT.Color * FINALLIGHT.Shadow;\n\t#endif\n\tfinal_color = applyReflection( IN, o, final_color );\n\t#pragma event "fs_final_pass"\n\t{{fs_encode}}\n\t#ifdef DRAW_BUFFERS\n\t  gl_FragData[0] = final_color;\n\t  #ifdef BLOCK_FIRSTPASS\n\t\t  #ifdef BLOCK_NORMALBUFFER\n\t\t\t  gl_FragData[1] = vec4( o.Normal * 0.5 + vec3(0.5), 1.0 );\n\t\t  #else\n\t\t\t  gl_FragData[1] = o.Extra;\n\t\t  #endif\n\t  #else\n\t\t  gl_FragData[1] = vec4(0.0);\n\t #endif\n\t#else\n\t  gl_FragColor = final_color;\n\t#endif\n\t#pragma event "fs_final"\n}\n\n\\shadow.vs\n\nprecision mediump float;\nattribute vec3 a_vertex;\nattribute vec3 a_normal;\nattribute vec2 a_coord;\nvarying vec3 v_local_pos;\nvarying vec3 v_local_normal;\n\n//varyings\nvarying vec3 v_pos;\nvarying vec3 v_normal;\nvarying vec2 v_uvs;\nvarying vec4 v_screenpos;\n\n//matrices\n#ifdef BLOCK_INSTANCING\n\tattribute mat4 u_model;\n#else\n\tuniform mat4 u_model;\n#endif\nuniform mat4 u_normal_model;\nuniform mat4 u_view;\nuniform mat4 u_viewprojection;\n//material\nuniform float u_displacementmap_factor;\nuniform sampler2D displacement_texture;\n\n//globals\nuniform float u_time;\nuniform vec4 u_viewport;\nuniform float u_point_size;\n\n#pragma shaderblock "light"\n#pragma shaderblock "morphing"\n#pragma shaderblock "skinning"\n\n//camera\nuniform vec3 u_camera_eye;\nuniform vec2 u_camera_planes;\n\n{{vs_out}}\n\nvoid main() {\n\t\n\tvec4 vertex4 = vec4(a_vertex,1.0);\n\tv_local_pos = a_vertex;\n\tv_local_normal = a_normal;\n\tv_normal = a_normal;\n\tv_uvs = a_coord;\n  \n  //deforms\n  {{vs_local}}\n  applyMorphing( vertex4, v_normal );\n  applySkinning( vertex4, v_normal );\n\t\n\t//vertex\n\tv_pos = (u_model * vertex4).xyz;\n  \n  applyLight(v_pos);\n  \n\t//normal\n\t#ifdef SHADERBLOCK_INSTANCING\n\t\tv_normal = (u_model * vec4(v_normal,0.0)).xyz;\n\t#else\n\t\tv_normal = (u_normal_model * vec4(v_normal,0.0)).xyz;\n\t#endif\n\t{{vs_global}}\n\tv_screenpos = u_viewprojection * vec4(v_pos,1.0);\n\tgl_Position = v_screenpos;\n}\n\\shadow.fs\n\nprecision mediump float;\n\n//varyings\nvarying vec3 v_pos;\nvarying vec3 v_normal;\nvarying vec2 v_uvs;\nvarying vec4 v_screenpos;\nvarying vec3 v_local_pos;\nvarying vec3 v_local_normal;\n\n//globals\nuniform vec3 u_camera_eye;\nuniform vec2 u_camera_planes;\nuniform vec4 u_clipping_plane;\nuniform vec4 u_material_color;\n\nuniform mat3 u_texture_matrix;\n\n\nuniform int u_texture_settings[11];\n\nvec2 uvs[4];\nvec2 getUVs(int index)\n{\n\tif(index == 0)\n\t\treturn uvs[0];\n\tif(index == 1)\n\t\treturn uvs[1];\n\tif(index == 2)\n\t\treturn uvs[2];\n\tif(index == 3)\n\t\treturn uvs[3];\n\treturn uvs[0];\n}\n\n\n\nuniform sampler2D color_texture;\nuniform sampler2D opacity_texture;\n\n#pragma snippet "input"\n#pragma snippet "surface"\n#pragma snippet "PackDepth32"\n\nvoid surf(in Input IN, out SurfaceOutput o)\n{\n\to.Albedo = u_material_color.xyz;\n\to.Alpha = u_material_color.a;\n\t\n\t{{fs_shadows}}\n}\n\n{{fs_shadow_out}}\n\nvoid main() {\n\tInput IN = getInput();\n\tIN.vertex = v_local_pos;\n\tIN.normal = v_local_normal;\n\tSurfaceOutput o = getSurfaceOutput();\n\tsurf(IN,o);\n\t//float depth = length( IN.worldPos - u_camera_eye );\n\t//depth = linearDepth( depth, u_camera_planes.x, u_camera_planes.y );\n\tfloat depth = (v_screenpos.z / v_screenpos.w) * 0.5 + 0.5;\n\t//depth = linearDepthNormalized( depth, u_camera_planes.x, u_camera_planes.y );\n\tvec4 final_color;\n\tfinal_color = PackDepth32(depth);\n\t{{fs_shadow_encode}}\n\tgl_FragColor = final_color;\n}\n\\picking.vs\n\nprecision mediump float;\nattribute vec3 a_vertex;\nattribute vec3 a_normal;\nattribute vec2 a_coord;\n#ifdef VERTEX_COLOR_BLOCK\n\tattribute vec4 a_color;\n#endif\n\n//varyings\nvarying vec3 v_pos;\nvarying vec3 v_normal;\nvarying vec2 v_uvs;\nvarying vec3 v_local_pos;\nvarying vec3 v_local_normal;\n\n//matrices\n#ifdef BLOCK_INSTANCING\n\tattribute mat4 u_model;\n#else\n\tuniform mat4 u_model;\n#endif\nuniform mat4 u_normal_model;\nuniform mat4 u_view;\nuniform mat4 u_viewprojection;\n//material\nuniform float u_displacementmap_factor;\nuniform sampler2D displacement_texture;\n\n//globals\nuniform float u_time;\nuniform vec4 u_viewport;\nuniform float u_point_size;\n\n#pragma shaderblock "light"\n#pragma shaderblock "morphing"\n#pragma shaderblock "skinning"\n\n//camera\nuniform vec3 u_camera_eye;\n\n{{vs_out}}\n\n#pragma event "vs_functions"\n\nvoid main() {\n\t\n\tvec4 vertex4 = vec4(a_vertex,1.0);\n\tv_local_pos = a_vertex;\n\tv_local_normal = a_normal;\n\tv_normal = a_normal;\n\tv_uvs = a_coord;\n  \n  //deforms\n  {{vs_local}}\n  applyMorphing( vertex4, v_normal );\n  applySkinning( vertex4, v_normal );\n\t\n\t//vertex\n\tv_pos = (u_model * vertex4).xyz;\n  \n  applyLight(v_pos);\n  \n\t//normal\n\t#ifdef SHADERBLOCK_INSTANCING\n\t\tv_normal = (u_model * vec4(v_normal,0.0)).xyz;\n\t#else\n\t\tv_normal = (u_normal_model * vec4(v_normal,0.0)).xyz;\n\t#endif\n  {{vs_global}}\n\tgl_Position = u_viewprojection * vec4(v_pos,1.0);\n\t#pragma event "vs_final"\n}\n\\picking.fs\n\tprecision mediump float;\n\tuniform vec4 u_material_color;\n\tvoid main() {\n\t\tgl_FragColor = u_material_color;\n\t}\n';
ua.prototype.prepare=J.prototype.prepare;ua.icon="mini-icon-material.png";ua.prototype.onCodeChange=function(){this._mustUpdate=!0};Object.defineProperty(ua.prototype,"code",{enumerable:!0,get:function(){return this._code},set:function(a){this._code=String(a);this._mustUpdate=!0}});ua.prototype.getCode=function(){return this._code};ua.prototype.computeCode=function(){for(var a="",b=0,c=this.properties.length;b<c;++b){var e="uniform ",g=this.properties[b];switch(g.type){case "number":e+="float ";break;
case "vec2":e+="vec2 ";break;case "color":case "vec3":e+="vec3 ";break;case "color4":case "vec4":e+="vec4 ";break;case "sampler":case "texture":e+="sampler2D ";break;case "cubemap":e+="samplerCube ";break;default:continue}e+=g.name+";\n";a+=e}this.surf_code=a+"\n"+this._code;a=d.ShaderCode.replaceCode(d.SurfaceMaterial.code_template,{fs_out:this.surf_code});this._shadercode||(this._shadercode=new d.ShaderCode);this._shadercode.code=a;this._mustUpdate=!1};ua.prototype.renderInstance=K.prototype.renderInstance;
ua.prototype.getShaderCode=function(a,b,c){this._shadercode&&!this._mustUpdate||this.computeCode();return this._shadercode};ua.prototype.fillUniforms=function(a,b){for(var c=this._samplers,e=c.length=0,d=0,f=this.properties.length;d<f;++d){var h=this.properties[d];"texture"==h.type||"cubemap"==h.type||"sampler"==h.type?(c[e]=h.value,this._uniforms[h.name]=e,e++):this._uniforms[h.name]=h.value}this._uniforms.u_material_color=this._color};ua.prototype.configure=function(a){void 0!==a.flags&&a.flags.constructor===
Number&&delete a.flags;B.prototype.configure.call(this,a);a.properties&&(this.properties=d.cloneObject(a.properties));this.computeCode()};ua.prototype.getPropertiesInfo=function(){var a={color:d.TYPES.VEC3,opacity:d.TYPES.NUMBER,shader_name:d.TYPES.STRING,blend_mode:d.TYPES.NUMBER,code:d.TYPES.STRING},b;for(b in this.properties){var c=this.properties[b];a[c.name]=c.type}return a};ua.prototype.onResourceRenamed=function(a,b,c){B.prototype.onResourceRenamed.call(this,a,b,c);c=0;for(var e=this.properties.length;c<
e;++c){var d=this.properties[c];d.value==a&&(d.value=b)}};ua.prototype.getProperty=function(a){if(this[a])return this[a];if("tex_"==a.substr(0,4))return(a=this.textures[a.substr(4)])?a.texture:null;for(var b=0,c=this.properties.length;b<c;++b){var e=this.properties[b];if(e.name==a)return e.value}return null};ua.prototype.setProperty=function(a,b){if(B.prototype.setProperty.call(this,a,b))return!0;"shader_name"==a&&(this.shader_name=b);for(var c=0,e=this.properties.length;c<e;++c){var d=this.properties[c];
if(d.name==a)return d.value=b,!0}if(void 0!==this[a])this[a]=b;else return!1;return!0};ua.prototype.getPropertyInfoFromPath=function(a){if(!(1>a.length)){var b=B.prototype.getPropertyInfoFromPath.call(this,a);if(b)return b;a=a[0];for(var b=0,c=this.properties.length;b<c;++b){var e=this.properties[b];if(e.name==a)return{node:this._root,target:this,name:e.name,value:e.value,type:e.type}}}};ua.prototype.getTextureChannels=function(){for(var a=[],b=0,c=this.properties.length;b<c;++b){var e=this.properties[b];
"texture"!=e.type&&"cubemap"!=e.type&&"sampler"!=e.type||a.push(e.name)}return a};ua.prototype.setTexture=function(a,b,c){if(!a)throw"SurfaceMaterial.prototype.setTexture channel must be specified";var e=null;if("environment"==a)return B.prototype.setTexture.call(this,a,b,c);for(var g=0;g<this.properties.length;++g){var f=this.properties[g];if("texture"==f.type||"cubemap"==f.type||"sampler"==f.type)if(!a||f.name==a){(e=this.textures[a])||(e=this.textures[a]={texture:b,uvs:"0",wrap:0,minFilter:0,magFilter:0});
if(c)for(g in c)e[g]=c[g];f.value="sampler"==f.type?e:b;break}}b&&b.constructor==String&&":"!=b[0]&&d.ResourcesManager.load(b);return e};ua.prototype.getResources=function(a){for(var b=0,c=this.properties.length;b<c;++b){var e=this.properties[b];"texture"!=e.type&&"cubemap"!=e.type&&"sampler"!=e.type||!e.value||(e="sampler"==e.type?e.value.texture:e.value,"string"==typeof e&&(a[e]=GL.Texture))}return a};d.registerMaterialClass(ua);d.SurfaceMaterial=ua;ua.code_template='\n\n\n\\color.vs\n\nprecision mediump float;\nattribute vec3 a_vertex;\nattribute vec3 a_normal;\nattribute vec2 a_coord;\n#pragma shaderblock "vertex_color"\n#pragma shaderblock "coord1"\n#ifdef BLOCK_COORD1\n\tattribute vec2 a_coord1;\n\tvarying vec2 v_uvs1;\n#endif\n#ifdef BLOCK_VERTEX_COLOR\n\tattribute vec4 a_color;\n\tvarying vec4 v_vertex_color;\n#endif\n\n//varyings\nvarying vec3 v_pos;\nvarying vec3 v_normal;\nvarying vec2 v_uvs;\nvarying vec3 v_local_pos;\nvarying vec3 v_local_normal;\n\n//matrices\nuniform mat4 u_model;\nuniform mat4 u_normal_model;\nuniform mat4 u_view;\nuniform mat4 u_viewprojection;\n\n//globals\nuniform float u_time;\nuniform vec4 u_viewport;\nuniform float u_point_size;\n\n#pragma shaderblock "light"\n#pragma shaderblock "morphing"\n#pragma shaderblock "skinning"\n\n//camera\nuniform vec3 u_camera_eye;\n{{vs_out}}\nvoid main() {\n\t\n\tvec4 vertex4 = vec4(a_vertex,1.0);\n\tv_local_pos = a_vertex;\n\tv_local_normal = a_normal;\n\tv_normal = a_normal;\n\tv_uvs = a_coord;\n\t#ifdef BLOCK_COORD1\n\t\tv_uvs1 = a_coord1;\n\t#endif\n\t#ifdef BLOCK_VERTEX_COLOR\n\t\tv_vertex_color = a_color;\n\t#endif\n  \n  //deforms\n  {{vs_local}}\n  applyMorphing( vertex4, v_normal );\n  applySkinning( vertex4, v_normal );\n\t\n\t//vertex\n\tv_pos = (u_model * vertex4).xyz;\n  \n  applyLight(v_pos);\n  \n\t//normal\n\tv_normal = (u_normal_model * vec4(v_normal,0.0)).xyz;\n    {{vs_global}}\n\tgl_Position = u_viewprojection * vec4(v_pos,1.0);\n}\n\n\\color.fs\n\nprecision mediump float;\n\n//varyings\nvarying vec3 v_pos;\nvarying vec3 v_normal;\nvarying vec3 v_local_pos;\nvarying vec3 v_local_normal;\nvarying vec2 v_uvs;\n#pragma shaderblock "vertex_color"\n#pragma shaderblock "coord1"\n#ifdef BLOCK_COORD1\n\tvarying vec2 v_uvs1;\n#endif\n#ifdef BLOCK_VERTEX_COLOR\n\tvarying vec4 v_vertex_color;\n#endif\n\n//globals\nuniform vec3 u_camera_eye;\nuniform vec4 u_clipping_plane;\nuniform float u_time;\nuniform vec4 u_background_color;\nuniform vec4 u_material_color;\n\n#pragma shaderblock "light"\n#pragma shaderblock "applyReflection"\n\n#pragma snippet "perturbNormal"\n#pragma snippet "testClippingPlane"\n\n{{fs_out}}\n\nvoid main() {\n\tInput IN = getInput();\n\tif(testClippingPlane(u_clipping_plane,IN.worldPos) < 0.0)\n\t\tdiscard;\n\t\n\tIN.vertex = v_local_pos;\n\tIN.normal = v_local_normal;\n\t#ifdef BLOCK_VERTEX_COLOR\n\t\tIN.color = v_vertex_color;\n\t#endif\n\t#ifdef BLOCK_COORD1\n\t\tIN.uv1 = v_uvs1;\n\t#endif\n\tSurfaceOutput o = getSurfaceOutput();\n\tsurf(IN,o);\n\tvec4 final_color = vec4(0.0);\n\tLight LIGHT = getLight();\n\tFinalLight final_light = computeLight( o, IN, LIGHT );\n\tfinal_color.xyz = applyLight( o, final_light );\n\tfinal_color.a = o.Alpha;\n\tif( o.Reflectivity > 0.0 )\n\t\tfinal_color = applyReflection( IN, o, final_color );\n\t\n\tgl_FragColor = final_color;\n}\n\n\\shadow.vs\n\nprecision mediump float;\nattribute vec3 a_vertex;\nattribute vec3 a_normal;\nattribute vec2 a_coord;\n#ifdef USE_COLORS\nattribute vec4 a_color;\n#endif\n\n//varyings\nvarying vec3 v_pos;\nvarying vec3 v_normal;\nvarying vec3 v_local_pos;\nvarying vec3 v_local_normal;\nvarying vec2 v_uvs;\n\n//matrices\nuniform mat4 u_model;\nuniform mat4 u_normal_model;\nuniform mat4 u_view;\nuniform mat4 u_viewprojection;\n\n//globals\nuniform float u_time;\nuniform vec4 u_viewport;\nuniform float u_point_size;\n\n#pragma shaderblock "light"\n#pragma shaderblock "morphing"\n#pragma shaderblock "skinning"\n\n//camera\nuniform vec3 u_camera_eye;\n{{vs_out}}\nvoid main() {\n\t\n\tvec4 vertex4 = vec4(a_vertex,1.0);\n\tv_local_pos = a_vertex;\n\tv_local_normal = a_normal;\n\tv_normal = a_normal;\n\tv_uvs = a_coord;\n  \n  //deforms\n  {{vs_local}}\n  applyMorphing( vertex4, v_normal );\n  applySkinning( vertex4, v_normal );\n\t\n\t//vertex\n\tv_pos = (u_model * vertex4).xyz;\n  \n  applyLight(v_pos);\n  \n\t//normal\n\tv_normal = (u_normal_model * vec4(v_normal,0.0)).xyz;\n    {{vs_global}}\n\tgl_Position = u_viewprojection * vec4(v_pos,1.0);\n}\n\\shadow.fs\n\nprecision mediump float;\n\n//varyings\nvarying vec3 v_pos;\nvarying vec3 v_normal;\nvarying vec2 v_uvs;\nvarying vec3 v_local_pos;\nvarying vec3 v_local_normal;\n\n//globals\nuniform vec3 u_camera_eye;\nuniform vec4 u_clipping_plane;\nuniform vec4 u_material_color;\n\nuniform mat3 u_texture_matrix;\n\n#pragma snippet "input"\n#pragma snippet "surface"\n#pragma snippet "perturbNormal"\n#define SHADOWMAP\n\n{{fs_out}}\n\nvoid main() {\n\tInput IN = getInput();\n\tIN.vertex = v_local_pos;\n\tIN.normal = v_local_normal;\n\tSurfaceOutput o = getSurfaceOutput();\n\tsurf(IN,o);\n\tgl_FragColor = vec4(o.Albedo,o.Alpha);\n}\n';
ra.icon="mini-icon-graph.png";ra["@filename"]={type:"resource",data_type:"graph"};ra.prototype.renderInstance=K.prototype.renderInstance;ra.prototype.renderShadowInstance=K.prototype.renderShadowInstance;ra.prototype.renderPickingInstance=K.prototype.renderPickingInstance;Object.defineProperty(ra.prototype,"filename",{enumerable:!1,get:function(){return this._filename},set:function(a){this._filename!=a&&(a&&(a=d.ResourcesManager.cleanFullpath(a)),this._filename=a,this._loading=!1,this.processGraph())}});
Object.defineProperty(ra.prototype,"graphcode",{enumerable:!1,get:function(){return this._graphcode},set:function(a){this._loading=!1;this._filename=(this._graphcode=a)?this._graphcode.fullpath||this._graphcode.filename:null;this.processGraph()}});Object.defineProperty(ra.prototype,"graph",{enumerable:!1,get:function(){return this._graphcode?this._graphcode.graph:null},set:function(a){throw"graph cannot be set to a material, you must assign a graphcode instead";}});ra.shader_codes={};ra.prototype.getShaderCode=
function(a,b,c){return this._graphcode&&this._graphcode.getShaderCode?this._graphcode.getShaderCode():null};ra.prototype.getResources=function(a){if(!this._graphcode)return a;a[this.filename]=!0;this._graphcode&&this._graphcode.graph.sendEventToAllNodes("getResources",a);return a};ra.prototype.serialize=function(){return{uid:this.uid,material_class:d.getObjectClassName(this),filename:this.filename,properties:null}};ra.prototype.configure=function(a){d.cloneObject(a,this);this.processGraph()};ra.prototype.processGraph=
function(a,b){if(this._filename){var c=this;this._graphcode=d.ResourcesManager.getResource(this._filename);this._graphcode||this._loading||(this._loading=!0,d.ResourcesManager.load(this._filename,null,function(a,d){this._loading=!1;d==c.filename&&(a&&a.type==Aa.SHADER_GRAPH?c._graphcode=a:console.error("Shader Graph not found or now a Shader Graph"),b&&b(c))}))}else this._graphcode=null};ra.prototype.getProperties=function(){var a={color:"vec3",opacity:"number",shader_name:"string",blend_mode:"number",
code:"string"},b;for(b in this.properties){var c=this.properties[b];a[c.name]=c.type}return a};ra.prototype.onResourceRenamed=function(a,b,c){B.prototype.onResourceRenamed.call(this,a,b,c);for(var e in this.properties)c=this.properties[e],c.value==a&&(c.value=b)};ra.prototype.getProperty=function(a){if(this[a])return this[a];if("tex_"==a.substr(0,4))return this.textures[a.substr(4)];for(var b in this.properties){var c=this.properties[b];if(c.name==a)return c.value}return null};ra.prototype.setProperty=
function(a,b){if(B.prototype.setProperty.call(this,a,b))return!0;for(var c in this.properties){var e=this.properties[c];if(e.name==a)return e.value=b,!0}return!1};ra.prototype.getTextureChannels=function(){var a=[],b;for(b in this.properties){var c=this.properties[b];"texture"!=c.type&&"cubemap"!=c.type||a.push(c.name)}return a};ra.prototype.setTexture=function(a,b,c){for(var e in this.properties)if(c=this.properties[e],"texture"==c.type||"cubemap"==c.type)if(!b||c.name==b)if(c.value=a,this.textures&&
(this.textures[b]=a),!b)break;a&&a.constructor==String&&":"!=a[0]&&Ob.load(a)};d.registerMaterialClass(ra);d.GraphMaterial=ra;Ca.prototype.configureComponents=function(a){if(a.components){for(var b=[],c=0,e=a.components.length;c<e;++c){var g=a.components[c],f=g[0],h=null;"Transform"==f&&0==c&&this.transform?h=this.transform:(h=d.Components[f],h||(console.error("Unknown component found: "+f),h=d.MissingComponent),h=new h,this.addComponent(h),h.constructor===d.MissingComponent&&(h._comp_class=f));b.push(h,
g[1]);h.constructor===d.Components.ScriptFromFile&&(h._filename=g[1].filename);g[1].editor&&(h._editor=g[1].editor);g[1].uid&&g[1].uid!==h.uid&&(h.uid=g[1].uid)}c=0;for(e=b.length;c<e;c+=2)b[c].configure(b[c+1])}};Ca.prototype.serializeComponents=function(a,b){if(this._components){a.components=[];for(var c=0,e=this._components.length;c<e;++c){var g=this._components[c];if(g.serialize&&!g.skip_serialize){var f=g.serialize(b);g._editor&&!b&&(f.editor=g._editor);g.hasOwnProperty("_uid")&&!f.uid&&(f.uid=
g.uid);var h=null,h=g.constructor===d.MissingComponent?g._comp_class:d.getObjectClassName(g);d.debug&&h!=f.object_class&&console.warn("Component serialize without object_class: ",h);f.object_class||(f.object_class=h);a.components.push([h,f])}}}};Ca.prototype.getComponents=function(a){if(a){var b=[];a.constructor===String&&(a=d.Components[a]);for(var c=0,e=this._components.length;c<e;++c){var g=this._components[c];g.constructor===a&&b.push(g)}return b}return this._components};Ca.prototype.addComponent=
function(a,b){if(!a)throw"addComponent cannot receive null";if(a.constructor===String&&(a=d.Components[a],!a))throw"component class not found: "+a;a.is_component&&(a=new a);a._root=this;a.uid||(a.uid=d.generateUId("COMP-"));if(a.onAddedToNode)a.onAddedToNode(this);if(this._in_tree&&(a.uid?this._in_tree._components_by_uid[a.uid]=a:console.warn("component without uid?",a),a.onAddedToScene))a.onAddedToScene(this.constructor==d.Scene?this:this._in_tree);this._components||Object.defineProperty(this,"_components",
{value:[],enumerable:!1});if(-1!=this._components.indexOf(a))throw"inserting the same component twice";void 0!==b&&b<=this._components.length?this._components.splice(b,0,a):this._components.push(a);LEvent.trigger(this,"componentAdded",a);return a};Ca.prototype.removeComponent=function(a){if(!a)throw"removeComponent cannot receive null";a._root=null;if(a.onRemovedFromNode)a.onRemovedFromNode(this);if(this._in_tree&&(delete this._in_tree._components_by_uid[a.uid],a.onRemovedFromScene))a.onRemovedFromScene(this._in_tree);
LEvent.unbindAll(this,a);var b=this._components.indexOf(a);-1!=b?this._components.splice(b,1):console.warn("removeComponent: Component not found in node");LEvent.trigger(this,"componentRemoved",a)};Ca.prototype.removeAllComponents=function(){for(;this._components.length;)this.removeComponent(this._components[0])};Ca.prototype.hasComponent=function(a){if(!this._components||a.constructor===String&&(a=d.Components[a],!a))return!1;for(var b=0,c=this._components.length;b<c;++b)if(this._components[b].constructor===
a)return!0;return!1};Ca.prototype.getComponent=function(a,b){if(!this._components||!a)return null;if(a.constructor===String){if("_"==a[0]){a=a.substr(1);for(var c=0,e=this._components.length;c<e;++c)if(this._components[c].name==a)if(void 0!==b&&0<b)b--;else return this._components[c];return!1}a=d.Components[a];if(!a)return}c=0;for(e=this._components.length;c<e;++c)if(this._components[c].constructor===a)if(void 0!==b&&0<b)b--;else return this._components[c];return null};Ca.prototype.getComponentByUId=
function(a){if(!this._components)return null;for(var b=0,c=this._components.length;b<c;++b)if(this._components[b].uid==a)return this._components[b];return null};Ca.prototype.getIndexOfComponent=function(a){return this._components?this._components.indexOf(a):-1};Ca.prototype.getComponentByIndex=function(a){return this._components?this._components[a]:null};Ca.prototype.findComponents=function(a,b){b=b||[];if(!a)return b;a.constructor===String&&(a=d.Components[a]);if(!a)return b;for(var c=0;c<this._components.length;++c){var e=
this._components[c];e&&e.constructor===a&&b.push(e)}if(this._children)for(c=0;c<this._children.length;++c)this._children[c].findComponents(a,b);return b};Ca.prototype.setComponentIndex=function(a,b){if(!this._components)return null;0>b&&(b=0);var c=this._components.indexOf(a);-1!=c&&(this._components.splice(c,1),b>=this._components.length?this._components.push(a):this._components.splice(b,0,a))};Ca.prototype.requireComponent=function(a,b){if(!a)throw"no component class specified";if(a.constructor===
String&&(a=d.Components[a],!a))return console.error("component class not found:",a),null;for(var c=this._components.length,e=0;e<c;++e)if(this._components[e].constructor===a)return this._components[e];e=new a;this.addComponent(e,c);b&&e.configure(b);return e};Ca.prototype.requireScript=function(a){if(!a)throw"no url specified";var b=d.Components.ScriptFromFile;a=d.ResourcesManager.cleanFullpath(a);for(var c=this._components.length,e=0;e<c;++e){var g=this._components[e];if(g.constructor===b&&g._filename==
a)return g}b=new b;b.filename=a;this.addComponent(b,c);return b};Ca.prototype.processActionInComponents=function(a,b,c){if(this._components&&this._components.length)for(var e=0,d=this._components.length;e<d;++e){var f=this._components[e];f[a]&&f[a].constructor===Function?b&&b.constructor===Array?f[a].apply(f,b):f[a].call(f,b):c||f._script&&f._script.callMethod(a,b,!0)}};Ca.prototype.broadcastMessage=function(a,b){this.processActionInComponents(a,b);if(this._children&&this._children.length)for(var c=
0,e=this._children.length;c<e;++c)this._children[c].broadcastMessage(a,b)};oa.prototype.compositeCtor=function(){this._in_tree=this._children=this._parentNode=null};oa.prototype.addChild=function(a,b,c){function e(a){if(a._children)for(var b in a._children){var c=a._children[b];c._in_tree||(LEvent.trigger(f,"treeItemAdded",c),c._in_tree=f);e(c)}}if(!a)throw"cannot addChild of null";if(a.constructor!==this.constructor)throw"added child must be of the same type";for(var d=this;d._parentNode;){if(d==
a)return console.error("addChild: Cannot insert a node as his own child"),!1;d=d._parentNode}a._parentNode&&a._parentNode==this._parentNode&&void 0!==b&&this._parentNode._children.indexOf(a)<b&&b--;a._parentNode&&a._parentNode.removeChild(a,c);a._parentNode=this;this._children?void 0==b?this._children.push(a):this._children.splice(b,0,a):this._children=[a];var f=this._in_tree;if(f&&a._in_tree&&a._in_tree!=f)throw"Cannot add a node that belongs to another scene tree";a._in_tree=f;this._onChildAdded&&
this._onChildAdded(a,c);LEvent.trigger(this,"childAdded",a);f&&(LEvent.trigger(f,"treeItemAdded",a),e(a))};oa.prototype.removeChild=function(a,b,c){function e(a){if(a._children)for(var b=0,c=a._children.length;b<c;++b){var d=a._children[b];d._in_tree&&(LEvent.trigger(d._in_tree,"treeItemRemoved",d),d._in_tree=null);e(d)}}if(!a)throw"cannot removeChild of null";if(!this._children||a._parentNode!=this||a._parentNode!=this)return!1;var d=this._children.indexOf(a);if(-1==d)return!1;this._children.splice(d,
1);this._onChildRemoved&&this._onChildRemoved(a,b,c);LEvent.trigger(this,"childRemoved",a);a._in_tree&&(LEvent.trigger(a._in_tree,"treeItemRemoved",a),e(a));a._in_tree=null;return!0};oa.prototype.removeAllChildren=function(a,b){if(this._children)for(;this._children.length;)this.removeChild(this._children[0],a,b)};oa.prototype.serializeChildren=function(a){var b=[];if(this._children)for(var c in this._children)b.push(this._children[c].serialize(!1,a));return b};oa.prototype.configureChildren=function(a){if(a.children)for(var b=
0;b<a.children.length;++b){var c=a.children[b],e=new this.constructor(c.id);c.uid&&(e.uid=c.uid);c.editor&&(e._editor=c.editor);this.addChild(e);e.configure(c)}};oa.prototype.getParent=function(){return this._parentNode};oa.prototype.getChildren=function(){return this._children||[]};oa.prototype.getChildIndex=function(a){return this._children?this._children.indexOf(a):-1};oa.prototype.getChildByIndex=function(a){return this._children&&this._children.length>a?this._children[a]:null};oa.prototype.getChildByName=
function(a){if(!this._children)return null;for(var b=0;b<this._children.length;++b)if(this._children[b].name==a)return this._children[b];return null};oa.prototype.getPathName=function(){if(!this._in_tree)return null;if(this===this._in_tree.root)return"";for(var a=this.name,b=this._parentNode;b;){if(b===this._in_tree.root)return a;a=b.name+"|"+a;b=b._parentNode}return null};Object.defineProperty(oa.prototype,"childNodes",{enumerable:!0,get:function(){return this._children||[]},set:function(a){}});
Object.defineProperty(oa.prototype,"parentNode",{enumerable:!0,get:function(){return this._parentNode},set:function(a){}});Object.defineProperty(oa.prototype,"scene",{enumerable:!0,get:function(){return this._in_tree},set:function(a){throw"Scene cannot be set, you must use addChild in parent";}});oa.prototype.getAncestors=function(a){var b=[],c=this._parentNode;for(a&&b.push(this);c;)b.push(c),c=c._parentNode;return b};oa.prototype.getDescendants=function(){if(!this._children||0==this._children.length)return[];
for(var a=this._children.concat(),b=0;b<this._children.length;++b)a=a.concat(this._children[b].getDescendants());return a};oa.prototype.moveBefore=function(a){if(!this._parentNode||a&&this._parentNode!==a._parentNode)return-1;var b=this._parentNode._children,c=b.indexOf(this);if(-1==c)throw"moveBefore node not found in parent, this is impossible";var e=c-1;if(a){e=b.indexOf(a);if(-1==e)return-1;e-=1}if(c==e||0>e)return e;b.splice(c,1);e>c&&(e-=1);b.splice(e,0,this);LEvent.trigger(this._in_tree,"node_rearranged",
this);return e};oa.prototype.moveAfter=function(a){if(!this._parentNode||a&&this._parentNode!==a._parentNode)return-1;var b=this._parentNode._children,c=b.indexOf(this);if(-1==c)throw"moveBefore node not found in parent, this is impossible";var e=c+1;if(a){e=b.indexOf(a);if(-1==e)return-1;e+=1}if(c==e||e>=b.length)return e;b.splice(c,1);e>c&&(e-=1);b.splice(e,0,this);LEvent.trigger(this._in_tree,"node_rearranged",this);return e};oa.prototype.findNode=function(a){return""==a?this:a?a.charAt(0)!=d._uid_prefix?
this.findNodeByName(a):this.findNodeByUId(a):null};oa.prototype.findNodeByName=function(a){if(!a)return null;if(this.name==a)return this;var b=this._children;if(b)for(var c=0,e=b.length;c<e;++c){var d=b[c];if(d.name==a||d._children&&(d=d.findNodeByName(a)))return d}return null};oa.prototype.findNodeByUId=function(a){if(!a)return null;if(this.uid==a)return this;var b=this._children;if(b)for(var c=0;c<b.length;++c){var e=b[c];if(e.uid==a||e._children&&(e=e.findNodeByUId(a)))return e}return null};oa.prototype.getHierarchyLevel=
function(){return this._parentNode?this._parentNode.getHierarchyLevel()+1:0};Oa.prototype.getRootNode=function(){return this._root};Oa.prototype.configure=function(a){if(a&&(a.uid&&(this.uid=a.uid),d.cloneObject(a,this,!1,!0),this.onConfigure))this.onConfigure(a)};Oa.prototype.serialize=function(){var a=d.cloneObject(this,null,!1,!1,!0);this.uid&&(a.uid=this.uid);a.object_class||(a.object_class=d.getObjectClassName(this));if(this.onSerialize)this.onSerialize(a);return a};Oa.prototype.clone=function(){var a=
this.serialize();a.uid=null;return new this.constructor(a)};Oa.prototype.createProperty=function(a,b,c,e,g){if(void 0===this[a]){if(c){if("String"==c||"Number"==c||"Boolean"==c)console.warn("createProperty: Basic types must be in lowercase -> "+c),c=c.toLowerCase();this.constructor["@"+a]="object"==typeof c?c:{type:c};if(c==d.TYPES.COMPONENT||d.Components[c]||c.constructor.is_component||c.type==d.TYPES.COMPONENT){var f="_"+a;Object.defineProperty(this,a,{get:function(){return this[f]?Na.get(this[f],
null,this._root&&this._root.scene?this._root._in_tree:d.GlobalScene):null},set:function(a){this[f]=a?a.constructor===String?a:a.uid:a},enumerable:!0});if(d.Components[c]||c.constructor.is_component)c={type:d.TYPES.COMPONENT,component_class:c.constructor===String?c:d.getClassName(c)};this.constructor["@"+a]="object"==typeof c?c:{type:c};return}}null!==b&&void 0!==b&&b.constructor!==Number&&b.constructor!==String&&b.constructor!==Boolean||e||g?(f="_"+a,Object.hasOwnProperty(this,f)||(c=this,b&&b.constructor===
Float32Array?(b=new Float32Array(b),this[f]=b,Object.defineProperty(c,a,{get:g||function(){return b},set:e||function(a){b.set(a)},enumerable:!0})):(Object.defineProperty(c,f,{value:b,enumerable:!1,writable:!0}),Object.defineProperty(c,a,{get:g||function(){return this[f]},set:e||function(a){this[f]=a},enumerable:!0})))):this[a]=b}};Oa.prototype.createAction=function(a,b,c){b||console.error("action '"+a+"' with no callback associated. Remember to create the action after the callback is defined.");var e=
a.replace(/ /gi,"_");this[e]=b;this.constructor["@"+e]=c||{type:"function",button_text:a,widget:"button",callback:b}};Oa.prototype.getLocator=function(a){return this._root?a?(void 0===this[a]&&console.warn("No property found in this component with that name:",a),this._root.uid+"/"+this.uid+"/"+a):this._root.uid+"/"+this.uid:""};Oa.prototype.getPropertyInfoFromPath=function(a){if(!a.length)return null;var b,c=a[0];this.getPropertyValue&&(b=this.getPropertyValue(c));if(void 0===b&&1<a.length&&this[c]&&
this[c].getPropertyInfoFromPath&&(a=this[c].getPropertyInfoFromPath(a.slice(1))))return a.node=this.root,a;if(void 0===b&&Object.hasOwnProperty(this,c))return null;b=void 0!==b?b:this[c];a=this.constructor["@"+c];var e="";a&&(e=a.type);e||null===b||void 0===b||(b.constructor===String?e="string":b.constructor===Boolean?e="boolean":b.length?e="vec"+b.length:b.constructor===Number&&(e="number"));return{node:this.root,target:this,name:c,value:b,type:e}};Oa.prototype.broadcastMessage=function(a,b){var c=
this._root;c&&c.broadcastMessage(a,b)};Oa.prototype.getComponent=function(a){return this._root?this._root.getComponent(a):null};Oa.prototype.bind=function(a,b,c){if(3<arguments.length)console.error("Component.bind cannot use a fourth parameter, all callbacks will be binded to the component");else if(a){if(c)return this.__targeted_instances||Object.defineProperty(this,"__targeted_instances",{value:[],enumerable:!1,writable:!0}),-1==this.__targeted_instances.indexOf(a)&&this.__targeted_instances.push(a),
LEvent.bind(a,b,c,this);console.error("You cannot bind a method before defining it.")}else console.error("Cannot bind to null.")};Oa.prototype.unbind=function(a,b,c){b=LEvent.unbind(a,b,c,this);if(this.__targeted_instances){if(!LEvent.hasBindTo(a,this))return b;a=this.__targeted_instances.indexOf(a);-1==a&&this.__targeted_instances.splice(a,1);0==this.__targeted_instances.length&&delete this.__targeted_instances}return b};Oa.prototype.unbindAll=function(){if(this.__targeted_instances){for(var a=0;a<
this.__targeted_instances.length;++a)LEvent.unbindAll(this.__targeted_instances[a],this);this.__targeted_instances=null}};Oa.addExtraMethods=function(a){Object.defineProperty(a.prototype,"uid",{set:function(a){a&&(a[0]!=d._uid_prefix&&(console.warn("Invalid UID, renaming it to: "+a),a=d._uid_prefix+a),a!=this._uid&&(this._uid=a))},get:function(){return this._uid},enumerable:!1});Object.defineProperty(a.prototype,"root",{set:function(a){throw"root cannot be set, call addComponent to the root";},get:function(){return this._root},
enumerable:!1});Object.defineProperty(a.prototype,"parentNode",{set:function(){throw"parentNode cannot be set, call addComponent to the parentNode";},get:function(){return this._root},enumerable:!1})};d.BaseComponent=Oa;ac.prototype.configure=function(a){this.uid=a.uid;this._last_serialization=a};ac.prototype.serialize=function(){return this._last_serialization};d.MissingComponent=ac;Object.defineProperty(Ha.prototype,"data",{set:function(a){this._data=a;this._modified=!0},get:function(){return this._data},
enumerable:!0});Ha.prototype.register=function(){d.ResourcesManager.registerResource(this.fullpath||this.filename,this)};Ha.prototype.rename=function(a){d.ResourcesManager.renameResource(this.fullpath||this.filename,a)};Object.defineProperty(Ha.prototype,"uid",{get:function(){return this.fullpath||this.filename},set:function(a){},enumerable:!0});Ha.getDataToStore=function(a,b){var c=null,e="text",d="";a.getDataToStore?(c=a.getDataToStore())&&c.constructor==ArrayBuffer&&(e="binary"):a._original_file?
((c=a._original_file)&&c.constructor!==File&&c.constructor!==Blob&&console.warn("Resource._original_file is not File or Blob"),e="file"):a._original_data?(c=a._original_data)&&c.constructor===ArrayBuffer&&(e="binary"):a.toBinary?(c=a.constructor===GL.Texture?a.toBinary(!0):a.toBinary(),e="binary",d=a.constructor.binary_extension?a.constructor.binary_extension:"wbin"):a.toBlob&&b?(c=a.toBlob(),e="file"):a.toBase64?(c=a.toBase64(),e="base64"):a.serialize?(c=a.serialize(),delete c.filename,delete c.fullpath,
delete c.remotepath,delete c.preview_url,c=JSON.stringify(c)):c=a.data?a.data:JSON.stringify(a);c.buffer&&c.buffer.constructor==ArrayBuffer&&(c=c.buffer);return{data:c,encoding:e,extension:d}};Ha.prototype.getData=function(){return this._data};Ha.prototype.setData=function(a,b){this._original_data&&(this._original_data=null);this._data=a;b||(this._modified=!0)};Ha.prototype.getDataToStore=function(){var a=this.data||"";a.constructor===Object&&(a=JSON.stringify(a));return a};Ha.prototype.clone=function(){var a=
new d.Resource;a._data=this._data;return a};Ha.prototype.getCategory=function(){return"js"==d.ResourcesManager.getExtension(this.fullpath||this.filename)?"Script":"Data"};Ha.prototype.assignToNode=function(a){if(!a)return!1;var b=this.fullpath||this.filename;"Script"==this.getCategory()&&(b=new d.Components.ScriptFromFile({filename:b}),a.addComponent(b));return!0};Ha.prototype.getAsSubfiles=function(){return this._data?GL.processFileAtlas(this._data):null};Ha.prototype.getAsHTML=function(){if(!this._data||
this._data.constructor!==String)return null;var a=document.createElement("div");a.innerHTML=this._data;return a};Ha.prototype.hasEditableText=function(){return this._data&&this._data.constructor===String};Ha.hasPreview=!1;d.Resource=Ha;d.registerResourceClass(Ha);d.Classes.Animation=d.Animation=X;X.EXTENSION="wbin";X.DEFAULT_SCENE_NAME="@scene";X.DEFAULT_DURATION=10;X.prototype.createTake=function(a,b){if(!a)throw"Animation Take name missing";var c=new X.Take;c.name=a;c.duration=b;void 0===b&&(c.duration=
X.DEFAULT_DURATION);this.addTake(c);return c};X.prototype.addTake=function(a){return this.takes[a.name]=a};X.prototype.getTake=function(a){return this.takes[a]};X.prototype.renameTake=function(a,b){var c=this.takes[a];c&&(delete this.takes[a],c.name=b,this.takes[b]=c,LEvent.trigger(this,"take_renamed",[a,b]))};X.prototype.removeTake=function(a){this.takes[a]&&(delete this.takes[a],LEvent.trigger(this,"take_removed",a))};X.prototype.getNumTakes=function(){var a=0,b;for(b in this.takes)a++;return a};
X.prototype.addTrackToTake=function(a,b){var c=this.takes[a];c||(c=this.createTake(a));c.addTrack(b)};X.prototype.configure=function(a){a.name&&(this.name=a.name);if(a.takes){var b=0;this.takes={};for(var c in a.takes){var e=new d.Animation.Take(a.takes[c]);e.name?(this.addTake(e),e.loadResources()):console.warn("Take without name");b++}b||this.createTake("default",d.Animation.DEFAULT_DURATION)}};X.prototype.serialize=function(){return d.cloneObject(this,null,!0)};X.fromBinary=function(a){a.constructor==
ArrayBuffer&&(a=WBin.load(a,!0));var b=a["@json"];b||(b=a);for(var c in b.takes){var e=b.takes[c],g;for(g in e.tracks){var f=e.tracks[g],h="@take_"+c+"_track_"+g;a[h]&&(f.data=a[h])}}return new d.Animation(b)};X.prototype.toBinary=function(){var a={},b=[],c;for(c in this.takes){var e=this.takes[c],g;for(g in e.tracks){var f=e.tracks[g];f.packData();if(f.packed_data){var h=f.data,k="@take_"+c+"_track_"+g;a[k]=h;f.data=null;b.push(h)}}}a["@json"]=d.cloneObject(this,null,!0);b=WBin.create(a,"Animation");
for(c in this.takes)for(g in e=this.takes[c],e.tracks)f=e.tracks[g],k="@take_"+c+"_track_"+g,a[k]&&(f.data=a[k]);return b};X.prototype.convertNamesToIDs=function(a,b){var c=0,e;for(e in this.takes)c+=this.takes[e].convertNamesToIDs(a,b);return c};X.prototype.convertIDsToNames=function(a,b){var c=0,e;for(e in this.takes)c+=this.takes[e].convertIDsToNames(a,b);return c};X.prototype.setTracksPacking=function(a){var b=0,c;for(c in this.takes)b+=this.takes[c].setTracksPacking(a);return b};X.prototype.optimizeTracks=
function(){var a=0,b;for(b in this.takes)a+=this.takes[b].optimizeTracks();return a};X.prototype.assignToNode=function(a){var b=a.getComponent(d.Components.PlayAnimation);b||(b=a.addComponent(d.Components.PlayAnimation));b.animation=this.fullpath||this.filename};Ia.prototype.configure=function(a){a.name&&(this.name=a.name);if(a.tracks){this.tracks=[];for(var b in a.tracks){var c=new d.Animation.Track(a.tracks[b]);this.addTrack(c)}}a.duration&&(this.duration=a.duration)};Ia.prototype.serialize=Ia.prototype.toJSON=
function(){return d.cloneObject(this,null,!0)};Ia.prototype.createTrack=function(a){if(!a)throw"Data missing when creating track";var b=this.getTrack(a.property);if(b)return b;b=new d.Animation.Track(a);this.addTrack(b);return b};Ia.prototype.applyTracks=function(a,b,c,e,g,f,h,k){g=g||d.GlobalScene;if(0!==f){f=f||1;for(var l=0;l<this.tracks.length;++l){var n=this.tracks[l];if(!1!==n.enabled&&n.data&&(!h||!1!==h(n,a,e,f)))if(n._type_index==R.EVENT){var p=n.getKeyframeByTime(a);if(!p||p[0]<b||p[0]>
a)break;n=g.getPropertyInfoFromPath(n._property_path);if(!n)break;var m=p[1];1==m[2]?n.node&&n.target&&n.target[m[0]]&&n.target[m[0]].call(n.target,m[1]):n.target?LEvent.trigger(n.target,p[1],p[1][1]):n.node&&LEvent.trigger(n.node,p[1][0],p[1][1])}else p=n.getSample(a,!c),1!==f&&(m=g.getPropertyValueFromPath(n._property_path,p,e,0),p=d.Animation.interpolateLinear(p,m,f,null,n._type,n.value_size,n)),void 0===p||k&&!1===k(n,p,e,f)||(n._target=g.setPropertyValueFromPath(n._property_path,p,e,0))}}};Ia.prototype.addTrack=
function(a){this.tracks.push(a)};Ia.prototype.getTrack=function(a){for(var b=0;b<this.tracks.length;++b)if(this.tracks[b].property==a)return this.tracks[b];return null};Ia.prototype.removeTrack=function(a){for(var b=0;b<this.tracks.length;++b)if(this.tracks[b]==a){this.tracks.splice(b,1);break}};Ia.prototype.getPropertiesSample=function(a,b){b=b||[];for(var c=0;c<this.tracks.length;++c){var e=this.tracks[c],d=e.getSample(a);b.push([e.property,d])}return b};Ia.prototype.actionPerSample=function(a,
b,c){for(var e=0;e<this.tracks.length;++e){var d=this.tracks[e],f=d.getSample(a,!0);c.disabled_tracks&&c.disabled_tracks[d.property]||b(d.property,f,c)}};Ia.prototype.loadResources=function(){for(var a=0;a<this.tracks.length;++a){var b=this.tracks[a];if("texture"==b._type)for(var c=b.getNumberOfKeyframes(),e=0;e<c;++e){var g=b.getKeyframe(e);g&&g[1]&&":"!=g[1][0]&&d.ResourcesManager.load(g[1])}}};Ia.prototype.convertNamesToIDs=function(a,b){for(var c=0,e=0;e<this.tracks.length;++e)c+=this.tracks[e].convertNameToID(a,
b);return c};Ia.prototype.convertIDsToNames=function(a,b){for(var c=0,e=0;e<this.tracks.length;++e)c+=this.tracks[e].convertIDtoName(a,b);return c};Ia.prototype.setTracksPacking=function(a){for(var b=0,c=0;c<this.tracks.length;++c){var e=this.tracks[c];e.packed_data!=a&&(a?e.packData():e.unpackData(),b+=1)}return b};Ia.prototype.optimizeTracks=function(){var a=0;new Float32Array(10);for(var b=0;b<this.tracks.length;++b)this.tracks[b].convertToTrans10()&&(a+=1);return a};Ia.prototype.setInterpolationToAllTracks=
function(a){for(var b=0,c=0;c<this.tracks.length;++c){var e=this.tracks[c];e.interpolation!=a&&(e.interpolation=a,b+=1)}return b};X.Take=Ia;X.Track=R;R.FRAMERATE=30;R.QUAT=d.TYPES_INDEX.quat;R.TRANS10=d.TYPES_INDEX.trans10;R.EVENT=d.TYPES_INDEX.event;Object.defineProperty(R.prototype,"property",{set:function(a){this._property=a.trim();this._property_path=this._property.split("/")},get:function(){return this._property},enumerable:!0});Object.defineProperty(R.prototype,"type",{set:function(a){this._type=
a;this._type_index=d.TYPES_INDEX[a]},get:function(){return this._type},enumerable:!0});R.prototype.configure=function(a){a.property||console.warn("Track with property name");void 0!==a.enabled&&(this.enabled=a.enabled);a.name&&(this.name=a.name);a.property&&(this.property=a.property);a.type&&(this.type=a.type);a.looped&&(this.looped=a.looped);this.interpolation=void 0!==a.interpolation?a.interpolation:d.LINEAR;a.data_table&&(this.data_table=a.data_table);a.value_size&&(this.value_size=a.value_size);
a.data&&(this.data=a.data,this.packed_data=void 0===a.packed_data&&this.data.constructor!==Array?!0:!!a.packed_data,a.data.constructor==Array&&this.packed_data&&(this.data=new Float32Array(a.data)));a.interpolation&&!this.value_size&&(a.interpolation=d.NONE)};R.prototype.serialize=function(){var a={enabled:this.enabled,name:this.name,property:this.property,type:this._type,interpolation:this.interpolation,looped:this.looped,value_size:this.value_size,packed_data:this.packed_data,data_table:this.data_table};
this.data&&(1>=this.value_size?a.data=this.data.concat?this.data.concat():new this.data.constructor(a.data):(this.packData(),a.data=new Float32Array(this.data),a.packed_data=this.packed_data));return a};R.prototype.toJSON=R.prototype.serialize;R.prototype.clear=function(){this.data=[];this.packed_data=!1};R.prototype.getIDasName=function(a,b){return this._property_path&&this._property_path.length?d.convertLocatorFromUIDsToName(this._property,a,b):null};R.prototype.convertNameToID=function(a){if(this._property_path[0][0]===
d._uid_prefix)return!1;a=Na.get(this._property_path[0],a);if(!a)return!1;this._property_path[0]=a.uid;1<this._property_path.length&&(a=a.getComponent(this._property_path[1]))&&(this._property_path[1]=a.uid);this._property=this._property_path.join("/");return!0};R.prototype.convertIDtoName=function(a,b){var c=this.getIDasName(a,b);if(!c)return!1;this._property=c;this._property_path=this._property.split("/");return!0};R.prototype.convertToTrans10=function(){if(16!=this.value_size)return!1;this.packed_data||
this.packData();var a=this.property.split("/");if("matrix"!=a[a.length-1])return!1;a[a.length-1]="Transform/data";this.property=a.join("/");this.type="trans10";this.value_size=10;for(var a=new Float32Array(10),b=this.data,c=b.length/17,e=0;e<c;++e){var g=b.subarray(17*e+1,17*e+17);d.Transform.fromMatrix4ToTransformData(g,a);b[11*e]=b[17*e];b.set(a,11*e+1)}this.data=new Float32Array(b.subarray(0,11*c));return!0};R.prototype.addKeyframeFromCurrent=function(a,b){b=b||d.GlobalScene;var c=b.getPropertyInfoFromPath(this._property_path);
return c?this.addKeyframe(a,c.value):null};R.prototype.addKeyframe=function(a,b,c){1<this.value_size&&(b=new Float32Array(b));this.packed_data&&this.unpackData();this.data||(this.data=[]);for(var e=0;e<this.data.length;++e)if(!(this.data[e][0]<a))return this.data[e][0]!=a||c?this.data.splice(e,0,[a,b]):this.data[e][1]=b,e;this.data.push([a,b]);return this.data.length-1};R.prototype.getKeyframe=function(a){return 0>a||a>=this.data.length?(console.warn("keyframe index out of bounds"),null):this.packed_data?
(a*=1+this.value_size,a>this.data.length-this.value_size?null:[this.data[a],this.data.subarray(a+1,a+this.value_size+1)]):this.data[a]};R.prototype.getKeyframeByTime=function(a){a=this.findTimeIndex(a);if(-1!=a)return this.getKeyframe(a)};R.prototype.moveKeyframe=function(a,b){if(this.packed_data)return console.warn("Cannot move keyframes if packed"),-1;if(0>a||a>=this.data.length)return console.warn("keyframe index out of bounds"),-1;var c=this.findTimeIndex(b),e=this.data[a],d=e[0];if(d==b)return a;
e[0]=b;d>b&&(c+=1);if(a==c)return a;this.data.splice(a,1);a=this.addKeyframe(e[0],e[1],!0);this.sortKeyframes();return a};R.prototype.sortKeyframes=function(){this.packed_data&&(this.unpackData(),this.sortKeyframes(),this.packData());this.data.sort(function(a,b){return a[0]-b[0]})};R.prototype.removeKeyframe=function(a){this.packed_data&&this.unpackData();0>a||a>=this.data.length?console.warn("keyframe index out of bounds"):this.data.splice(a,1)};R.prototype.getNumberOfKeyframes=function(){return this.data&&
0!=this.data.length?this.packed_data?this.data.length/(1+this.value_size):this.data.length:0};R.prototype.computeDuration=function(){if(!this.data||0==this.data.length)return 0;if(this.packed_data){var a=this.data[this.data.length-2-this.value_size];return this.duration=a}return(a=this.data[this.data.length-1])?a[0]:0};R.prototype.isInterpolable=function(){return 0<this.value_size||d.Interpolators[this._type]?!0:!1};R.prototype.packData=function(){if(!this.data||0==this.data.length)return 0;if(!this.packed_data&&
0!=this.value_size){for(var a=this.value_size+1,b=this.data,c=new Float32Array(b.length*a),e=0;e<b.length;++e)c[e*a]=b[e][0],1==this.value_size?c[e*a+1]=b[e][1]:c.set(b[e][1],e*a+1);this.data=c;this.packed_data=!0}};R.prototype.unpackData=function(){if(!this.data||0==this.data.length)return 0;if(this.packed_data){for(var a=this.value_size+1,b=this.data,c=Array(b.length/a),e=0;e<b.length;e+=a)c[e/a]=[b[e],b.subarray(e+1,e+a)];this.data=c;this.packed_data=!1}};R.prototype.findTimeIndex=function(a){var b=
this.data;if(!b||0==b.length)return-1;if(this.packed_data){var c=this.value_size+1,e=b.length/c,d=0,f=0,h=e;if(0==e)return-1;if(1==e)return 0;if(b[(h-1)*c]<a)return h-1;for(;h>=d;){f=0.5*(h+d)|0;e=b[f*c];if(e==a)break;if(d==h-1)return d;e<a?d=f:h=f}return f}e=b.length;f=d=0;h=e;if(0==e)return-1;if(1==e)return 0;if(b[h-1][0]<a)return h-1;for(;h>=d;){f=0.5*(h+d)|0;e=b[f][0];if(e==a)break;if(d==h-1)return d;e<a?d=f:h=f}return f};R.prototype.getSample=function(a,b,c){return this.data&&0!==this.data.length?
this.packed_data?this.getSamplePacked(a,b,c):this.getSampleUnpacked(a,b,c):void 0};R.prototype.getSampleUnpacked=function(a,b,c){a=Math.clamp(a,0,this.duration);var e=this.findTimeIndex(a);-1===e&&(e=0);var g=e,f=e+1,h=this.data,k=this.value_size;b=b&&this.interpolation&&(0<this.value_size||d.Interpolators[this._type]);if(!b||1==h.length||f==h.length||0==g&&this.data[0][0]>a)return this.data[e][1];b=h[g];f=h[f];a=(f[0]-a)/(f[0]-b[0]);1<k&&(c=c||this._result,c&&c.length==k||(c=this._result=new Float32Array(k)));
if(this.interpolation===d.LINEAR)return 1==k?b[1]*a+f[1]*(1-a):d.Animation.interpolateLinear(b[1],f[1],a,c,this._type,k,this);if(this.interpolation===d.CUBIC){if(0===k&&d.Interpolators[this._type])return this._last_value=c=(0,d.Interpolators[this._type])(b[1],f[1],a,this._last_value);g=0<e?h[e-1]:b;e=e<h.length-2?h[e+2]:f;if(1===k)return X.EvaluateHermiteSpline(b[1],f[1],g[1],e[1],1-a);c=X.EvaluateHermiteSplineVector(b[1],f[1],g[1],e[1],1-a,c);this._type_index==R.QUAT?(quat.slerp(c,f[1],b[1],a),quat.normalize(c,
c)):this._type_index==R.TRANS10&&(k=c.subarray(3,7),e=b[1].subarray(3,7),h=f[1].subarray(3,7),quat.slerp(k,h,e,a),quat.normalize(k,k));return c}return null};R.prototype.getSamplePacked=function(a,b,c){a=Math.clamp(a,0,this.duration);var e=this.findTimeIndex(a);-1==e&&(e=0);var g=this.value_size,f=g+1,h=e,k=e+1,l=this.data,n=l.length/f;b=b&&this.interpolation&&(0<g||d.Interpolators[this._type]);if(!b||1==n||k==n||0==h&&this.data[0]>a)return this.getKeyframe(e)[1];1<g&&(c=c||this._result,c&&c.length==
g||(c=this._result=new Float32Array(g)));h=l.subarray(h*f,(h+1)*f);b=l.subarray(k*f,(k+1)*f);a=(b[0]-a)/(b[0]-h[0]);if(this.interpolation===d.LINEAR){if(1==g)return h[1]*a+b[1]*(1-a);f=h.subarray(1,g+1);b=b.subarray(1,g+1);return d.Animation.interpolateLinear(f,b,a,c,this._type,g,this)}if(this.interpolation===d.CUBIC){if(0===g)return h[1];e=0<e?l.subarray((e-1)*f,e*f):h;k=k<n-1?l.subarray((k+1)*f,(k+2)*f):b;if(1===g)return X.EvaluateHermiteSpline(h[1],b[1],e[1],k[1],1-a);g=h.subarray(1,f);b=b.subarray(1,
f);c=X.EvaluateHermiteSplineVector(g,b,e.subarray(1,f),k.subarray(1,f),1-a,c);this._type_index==R.QUAT?(quat.slerp(c,b,g,a),quat.normalize(c,c)):this._type_index==R.TRANS10&&(f=c.subarray(3,7),g=g.subarray(3,7),b=b.subarray(3,7),quat.slerp(f,b,g,a),quat.normalize(f,f));return c}return null};R.prototype.getPropertyInfo=function(a){a=a||d.GlobalScene;return a.getPropertyInfo(this.property)};R.prototype.getPropertyNode=function(a){return(a||d.GlobalScene).getNode(this.property.split("/")[0])};R.prototype.getSampledData=
function(a,b,c){b=(b-a)/c;if(0>=b)return null;for(var e=[],d=0;d<c;++d){var f=this.getSample(d*b+a,!0);1<this.value_size&&(f=new f.constructor(f));e.push(f)}return e};X.interpolateLinear=function(a,b,c,e,g,f,h){if(1==f)return a*c+b*(1-c);if(d.Interpolators[g])return c=(0,d.Interpolators[g])(a,b,c,h._last_v),h._last_v=c;e=e||h._result;e&&e.length==f||(e=h._result=new Float32Array(f));switch(d.TYPES_INDEX[g]){case R.QUAT:quat.slerp(e,b,a,c);quat.normalize(e,e);break;case R.TRANS10:for(h=0;3>h;h++)e[h]=
a[h]*c+b[h]*(1-c);for(h=7;10>h;h++)e[h]=a[h]*c+b[h]*(1-c);a=a.subarray(3,7);b=b.subarray(3,7);f=e.subarray(3,7);quat.slerp(f,b,a,c);quat.normalize(f,f);break;default:for(h=0;h<f;h++)e[h]=a[h]*c+b[h]*(1-c)}return e};X.EvaluateHermiteSpline=function(a,b,c,e,d){var f=d*d,h=f*d;return(2*h-3*f+1)*a+(-2*h+3*f)*b+(h-2*f+d)*(b-c)+(h-f)*(e-a)};X.EvaluateHermiteSplineVector=function(a,b,c,e,d,f){f=f||new Float32Array(f.length);var h=d*d,k=h*d,l=2*k-3*h+1,n=-2*k+3*h;d=k-2*h+d;for(var h=k-h,k=0,p=f.length;k<
p;++k)f[k]=l*a[k]+n*b[k]+d*(b[k]-c[k])+h*(e[k]-a[k]);return f};d.registerResourceClass(X);d.Interpolators={};d.Interpolators.texture=function(a,b,c,e){var g=a?d.getTexture(a):null,f=b?d.getTexture(b):null;a&&!g&&":"!=a[0]&&d.ResourcesManager.load(a);b&&!f&&":"!=b[0]&&d.ResourcesManager.load(b);a=g||f;(b=gl.textures[":black"])||(b=gl.textures[":black"]=new GL.Texture(1,1,{format:gl.RGB,pixel_data:[0,0,0],filter:gl.NEAREST}));if(!a)return b;var h=a?a.width:256,k=a?a.height:256;g||(g=b);f||(f=b);e&&
e.width==h&&e.height==k&&e.format==a.format||(e=new GL.Texture(h,k,{format:a.format,type:a.type,filter:gl.LINEAR}));var l=gl.shaders[":interpolate_texture"];l||(l=gl.shaders[":interpolate_texture"]=GL.Shader.createFX("color = mix( texture2D( u_texture_b, uv ), color , u_factor );","uniform sampler2D u_texture_b; uniform float u_factor;"));gl.disable(gl.DEPTH_TEST);e.drawTo(function(){gl.clearColor(0,0,0,0);gl.clear(gl.COLOR_BUFFER_BIT);f.bind(1);g.toViewport(l,{u_texture_b:1,u_factor:c})});return e};
Math.lerp||(Math.lerp=mc);Ab.prototype.serialize=function(){return{name:this.name,model:typedArrayToArray(this.model),parent:this.parent,layer:this.layer,children:this.num_children?typedArrayToArray(this.children.subarray(0,this.num_children)):null}};Ab.prototype.configure=function(a){this.name=a.name;this.model.set(a.model);this.parent=a.parent;this.layer=a.layer;this.num_children=0;a.children&&(this.children.set(a.children),this.num_children=a.children.constructor===Array?a.children.length:a.num_children)};
Ab.prototype.copyFrom=Ab.prototype.configure;na.Bone=Ab;na.prototype.applyTransformToBones=function(a,b){var c=this.getBone(a);c&&mat4.multiply(c.model,c.model,b)};na.prototype.getBone=function(a){return this.bones[this.bones_by_name.get(a)]};na.identity=mat4.create();na.prototype.getBoneMatrix=function(a,b){void 0===b&&(b=!0);var c=this.bones_by_name.get(a);return void 0===c?na.identity:b?this.bones[c].model:this.global_bone_matrices[c]};na.temp_mat4=mat4.create();na.temp_mat43=na.temp_mat4.subarray(0,
12);na.prototype.computeFinalBoneMatrices=function(a,b,c){if(!this.bones.length||!b||!b.bones)return a||[];this.updateGlobalMatrices();var e=c?12*b.bones.length:16*b.bones.length;a&&a.length==e||(a=new Float32Array(e));if(c){var d=na.temp_mat4,d=na.temp_mat43;for(c=0;c<b.bones.length;++c)e=b.bones[c],mat4.multiply(temp_mat4,this.getBoneMatrix(e[0],!1),e[1]),mat4.transpose(temp_mat4,temp_mat4),a.set(d,12*c)}else for(c=0;c<b.bones.length;++c)e=b.bones[c],d=a.subarray(16*c,16*c+16),mat4.multiply(d,this.getBoneMatrix(e[0],
!1),e[1]);return a};na.prototype.computeFinalBoneMatricesAsArray=function(a,b,c){if(!this.bones.length||!b||!b.bones)return a||[];this.updateGlobalMatrices();a=a||[];a.length=b.bones.length;for(var e=0;e<b.bones.length;++e){var d=b.bones[e];a[e]||(a[e]=mat4.create());var f=a[e];mat4.multiply(f,this.getBoneMatrix(d[0],!1),d[1]);b.bind_matrix&&mat4.multiply(f,f,b.bind_matrix);c&&mat4.multiply(f,c,f)}return a};na.prototype.updateGlobalMatrices=function(){var a=this.bones;if(a.length){var b=this.bones.length;
this.global_bone_matrices[0].set(a[0].model);for(var c=1;c<b;++c){var e=a[c];mat4.multiply(this.global_bone_matrices[c],this.global_bone_matrices[e.parent],e.model)}}};na.prototype.assignLayer=function(a,b){};na.prototype.getVertices=function(){if(!this.bones.length)return null;var a=6*(this.bones.length-1);this._vertices&&this._vertices.length==a||(this._vertices=new Float32Array(a));for(var a=this._vertices,b=0;b<this.bones.length-1;++b){var c=this.global_bone_matrices[this.bones[b+1].parent],e=
this.global_bone_matrices[b+1],d=a.subarray(6*b,6*b+3),f=a.subarray(6*b+3,6*b+6);mat4.getTranslation(d,e);mat4.getTranslation(f,c)}return a};na.prototype.resizeBones=function(a){if(this.bones.length!=a)if(this.bones.length>a)this.bones.length=a,this.global_bone_matrices.length=a;else{var b=this.bones.length;for(this.bones.length=a;b<a;++b)this.bones[b]=new Ab,this.global_bone_matrices[b]=mat4.create()}};na.prototype.copyFrom=function(a){this.resizeBones(a.bones.length);for(var b=0;b<a.bones.length;++b)this.bones[b].copyFrom(a.bones[b]),
this.global_bone_matrices[b].set(a.global_bone_matrices[b]);this.bones_by_name=new Map(a.bones_by_name)};na.prototype.serialize=function(){for(var a={bones:[],bone_names:{}},b=0;b<this.bones.length;++b)a.bones.push(this.bones[b].serialize());return a};na.prototype.configure=function(a){this.resizeBones(a.bones.length);a.bones_by_name?this.bones_by_name=new Map(a.bones_by_name):this.bones_by_name.clear();for(var b=0;b<a.bones.length;++b)this.bones[b].copyFrom(a.bones[b]),a.global_bone_matrices?this.global_bone_matrices[b].set(a.global_bone_matrices[b]):
this.bones_by_name[this.bones[b].name]=b};var kb=vec3.create();na.blend=function(a,b,c,e,d,f){if(a.bones.length!=b.bones.length)console.error("skeleton must contain the same number of bones");else{c=Math.clamp(c,0,1);if(255==d){if(0==c){if(e==a)return;e.copyFrom(a);return}if(1==c){e.copyFrom(b);return}}if(e!=a){e.bones.length=a.bones.length;for(d=0;d<e.bones.length;++d)(b=e.bones[d])||(b=new na.Bone),b.copyFrom(a.bones[d]);e.bones_by_name=new Map(a.bones_by_name)}for(d=0;d<e.bones.length;++d){for(var h=
e.bones[d],k=a.bones[d],l=b.bones[d],n=0;16>n;++n)h.model[n]=Math.lerp(k.model[n],l.model[n],c);if(!f)for(h=h.model,n=0;3>n;++n)kb[0]=h[0+n],kb[1]=h[4+n],kb[2]=h[8+n],vec3.normalize(kb,kb),h[0+n]=kb[0],h[4+n]=kb[1],h[8+n]=kb[2]}}};na.shader_code="\n\tattribute vec4 a_bone_indices;\n\tattribute vec4 a_weights;\n\tuniform mat4 u_bones[64];\n\tvoid computeSkinning(inout vec3 vertex, inout vec3 normal)\n\t{\n\t\tvec4 v = vec4(vertex,1.0);\n\t\tvertex = (u_bones[int(a_bone_indices.x)] * a_weights.x * v + \n\t\t\t\tu_bones[int(a_bone_indices.y)] * a_weights.y * v + \n\t\t\t\tu_bones[int(a_bone_indices.z)] * a_weights.z * v + \n\t\t\t\tu_bones[int(a_bone_indices.w)] * a_weights.w * v).xyz;\n\t\tvec4 N = vec4(normal,0.0);\n\t\tnormal =\t(u_bones[int(a_bone_indices.x)] * a_weights.x * N + \n\t\t\t\tu_bones[int(a_bone_indices.y)] * a_weights.y * N + \n\t\t\t\tu_bones[int(a_bone_indices.z)] * a_weights.z * N + \n\t\t\t\tu_bones[int(a_bone_indices.w)] * a_weights.w * N).xyz;\n\t\tnormal = normalize(normal);\n\t}\n";
rb.FORMAT={extension:"skanim",dataType:"text"};rb.prototype.assignTime=function(a,b,c,e){if(this.duration){b||void 0===b?(a%=this.duration,0>a&&(a=this.duration+a)):a=Math.clamp(a,0,this.duration-1/this.samples_per_second);void 0===c&&(c=!0);a*=this.samples_per_second;var d=Math.floor(a),f=(d+1)%this.num_keyframes,d=d%this.num_keyframes;a-=Math.floor(a);b=this.num_animated_bones;e=16*b;for(var d=d*e,f=f*e,h=this.skeleton,k=this.keyframes,l=this.bones_map,n=0;n<b;++n){var p=h.bones[l[n]];e=16*n;if(c)for(var m=
0;16>m;++m)p.model[m]=mc(k[d+e+m],k[f+e+m],a);else p.model.set(k.subarray(d+e,d+e+16))}}};rb.prototype.resize=function(a,b){this.num_keyframes=a;this.num_animated_bones=b;this.keyframes=new Float32Array(a*b*16)};rb.prototype.fromData=function(a){a=a.split("\n");var b=a[0].split(",");this.duration=Number(b[0]);this.samples_per_second=Number(b[1]);this.num_keyframes=Number(b[2]);this.skeleton.resizeBones(Number(b[3]));for(var b=0,c=1;c<a.length;++c){var e=a[c],d=e[0],e=e.substr(1).split(",");if("B"==
d){var f=Number(e[0]),h=this.skeleton.bones[f];h.name=e[1];h.parent=Number(e[2]);for(d=0;16>d;++d)h.model[d]=Number(e[3+d]);-1!=h.parent&&(e=this.skeleton.bones[h.parent],16<=e.num_children?console.warn("too many child bones, max is 16"):e.children[e.num_children++]=f);this.skeleton.bones_by_name.set(h.name,f)}else if("@"==d){this.num_animated_bones=Number(e[0]);for(d=0;d<this.num_animated_bones;++d)this.bones_map[d]=Number(e[d+1]);this.resize(this.num_keyframes,this.num_animated_bones)}else if("K"==
d){f=b*this.num_animated_bones*16;d=0;for(h=16*this.num_animated_bones;d<h;++d)this.keyframes[f+d]=Number(e[d+1]);b++}else break}this.assignTime(0,!1,!1)};rb.prototype.toData=function(){console.error("no toData in Skeletal Animation");return""};"undefined"!=typeof d&&(d.Skeleton=na,d.Classes.SkeletalAnimation=d.SkeletalAnimation=rb,d.registerResourceClass(rb));ia.version="0.2";ia.EXTENSION="wbin";ia.prototype.configure=function(a){this._data=d.cloneObject(a);this.resource_names=a["@resource_names"];
this._resources_data={};if(this.resource_names){delete this._data["@resource_names"];for(var b in this.resource_names)this._resources_data[this.resource_names[b]]=a["@RES_"+b],delete this._data["@RES_"+b]}this.processResources()};Object.defineProperty(ia.prototype,"bindata",{set:function(a){throw"Pack bindata cannot be assigned";},get:function(){this._original_data||(this._original_data=d.Pack.packResources(this.resource_names,this._data));return this._original_data},enumerable:!0});ia.fromBinary=
function(a){a.constructor==ArrayBuffer&&(a=WBin.load(a,!0));return new d.Pack(a)};ia.prototype.processResources=function(){if(this.resource_names){for(var a=this.fullpath||this.filename,b=0;b<this.resource_names.length;++b){var c=this.resource_names[b];d.ResourcesManager.resources[c]||(d.ResourcesManager.resources_being_processed[c]=!0)}for(b=0;b<this.resource_names.length;++b)if(c=this.resource_names[b],!d.ResourcesManager.resources[c]){var e=this._resources_data[c];e?d.ResourcesManager.processResource(c,
e,{is_local:!0,from_pack:a}):console.warn("resource data in Pack is undefined, skipping it:"+c)}}};ia.prototype.setResources=function(a,b){this.resource_names=[];this._resources_data={};for(var c=this.fullpath||this.filename,e=0;e<a.length;++e){var g=a[e];if(-1==this.resource_names.indexOf(g)){var f=d.ResourcesManager.resources[g];f&&(b&&(f.from_pack=c),this.resource_names.push(g))}}this._original_data=d.Pack.packResources(a,this.getBaseData());this._modified=!0};ia.prototype.getBaseData=function(){return{"@metadata":this.metadata,
"@version":d.Pack.version}};ia.prototype.setResourcesLink=function(a){for(var b=0;b<this.resource_names.length;++b){var c=d.ResourcesManager.resources[this.resource_names[b]];c&&(a?c.from_pack=a:delete c.from_pack)}};ia.prototype.addResources=function(a,b){a&&(a.constructor!==Array&&(a=[a]),this.setResources(this.resource_names.concat(a),b))};ia.prototype.addResource=function(a){a=d.ResourcesManager.cleanFullpath(a);-1==this.resource_names.indexOf(a)&&this.resource_names.push(a)};ia.prototype.removeResource=
function(a){a=d.ResourcesManager.cleanFullpath(a);a=this.resource_names.indexOf(a);-1!=a&&this.resource_names.splice(a,1)};ia.createPack=function(a,b,c,e){if(a){if(!b||b.constructor!==Array)throw"Pack.createPack resources must be array with names";if(c&&c.constructor!==Object)throw"Pack.createPack extra_data must be an object with the chunks to store";a=a.replace(/ /gi,"_");var g=new d.Pack;g.filename=a+".wbin";c&&(g._data=c);g.resource_names=b;for(a=0;a<b.length;++a){var f=d.ResourcesManager.resources[b[a]];
f&&e&&(f.from_pack=g.filename)}this.metadata=c;b=d.Pack.packResources(b,g.getBaseData());g._original_data=b;return g}};ia.packResources=function(a,b){for(var c=b||{},e=[],g=0;g<a.length;++g){var f=a[g],h=d.ResourcesManager.resources[f];if(h){var k=null;if(k=h._original_data?h._original_data:d.Resource.getDataToStore(h).data){if(k.constructor===Blob||k.constructor===File){if(!k.data||k.data.constructor!==ArrayBuffer){console.warn("WBin does not support to store File or Blob, please, use ArrayBuffer");
continue}k=k.data}c["@RES_"+e.length]=k;e.push(f)}else console.warn("Wrong data in resource")}}c["@resource_names"]=e;return WBin.create(c,"Pack")};ia.prototype.flagResources=function(){if(this.resource_names)for(var a=0;a<this.resource_names.length;++a){var b=d.ResourcesManager.resources[this.resource_names[a]];b&&(b.from_pack=this.fullpath||this.filename)}};ia.prototype.getDataToStore=function(){return d.Pack.packResources(this.resource_names,this.getBaseData())};ia.prototype.checkResourceNames=
function(){if(!this.resource_names)return 0;for(var a=0,b=0;b<this.resource_names.length;++b){var c=this.resource_names[b],e=c,g=d.ResourcesManager.resources[c];if(g){!1==d.ResourcesManager.valid_resource_name_reg.test(c)&&(console.warn("Invalid filename in pack/prefab: ",c),c=c.replace(/[^a-zA-Z0-9-_\.\/]/g,"_"));var f=d.ResourcesManager.getExtension(c);f||((f=g.constructor.EXTENSION)?c=c+"."+f:console.warn("Resource without extension and not known default extension: ",c,g.constructor.name));e!=
c&&(this.resource_names[b]=c,d.ResourcesManager.renameResource(e,c),a++)}}a&&d.ResourcesManager.resourceModified(this);return a};ia.prototype.onResourceRenamed=function(a,b,c){this.resource_names&&(a=this.resource_names[a],-1!=a&&(this.resource_names[a]=b,d.ResourcesManager.resourceModified(this)))};ia.prototype.containsResources=function(){return this.resource_names&&0<this.resource_names.length?!0:!1};ia.prototype.getSizeInBytes=function(){return this._original_data?this._original_data.byteLength:
0};d.Pack=ia;d.registerResourceClass(ia);la.version="0.2";la.EXTENSION="wbin";la.prototype.setData=function(a){a&&a.constructor===d.SceneNode&&(a=a.serialize());a.object_class="SceneNode";this.prefab_data=a;this.prefab_json=JSON.stringify(a)};la.prototype.configure=function(a){if(!a)throw"No prefab data found";if(a.hasOwnProperty("prefab_data"))this.prefab_data=a.prefab_data,this.prefab_json=a.prefab_json||JSON.stringify(this.prefab_data);else{var b=a["@json"];if(!b){console.warn("No JSON found in prefab");
return}var c=a["@version"];this.prefab_json=b;this.prefab_data=JSON.parse(b)}this.resource_names=a["@resources_name"]||a.resource_names||[];var b={},e;for(e in this.resource_names)b[this.resource_names[e]]=c?a["@RES_"+e]:a[this.resource_names[e]];this._resources_data=b;this.processResources()};la.fromBinary=function(a,b){a.constructor==ArrayBuffer&&(a=WBin.load(a,!0));return new d.Prefab(a,b)};la.prototype.processResources=function(){if(this._resources_data){var a=this.fullpath||this.filename,b=this._resources_data,
c;for(c in b)d.ResourcesManager.resources[c]||(d.ResourcesManager.resources_being_processed[c]=!0);for(c in b)if(!d.ResourcesManager.resources[c]){var e=b[c];e?d.ResourcesManager.processResource(c,e,{is_local:!0,from_prefab:a}):console.warn("resource data in prefab is undefined, skipping it:"+c)}}};la.prototype.createObject=function(){if(!this.prefab_json)throw"No prefab_json data found";var a=JSON.parse(this.prefab_json);if(!a)return console.error("Prefab data is null"),null;var b=new d.SceneNode;
b.configure(a);d.ResourcesManager.loadResources(b.getResources({},!0));this.fullpath&&(b.prefab=this.fullpath);return b};la.prototype.addResource=function(a){a=d.ResourcesManager.cleanFullpath(a);-1==this.resource_names.indexOf(a)&&this.resource_names.push(a)};la.prototype.removeResource=function(a){a=d.ResourcesManager.cleanFullpath(a);a=this.resource_names.indexOf(a);-1!=a&&this.resource_names.splice(a,1)};la.createPrefab=function(a,b,c){if(a){if(!b)throw"No node_data in prefab";a=a.replace(/ /gi,
"_");c=c||[];var e=new d.Prefab;"wbin"!=d.ResourcesManager.getExtension(a)&&(a+=".wbin");e.filename=a;e.resource_names=c;e.setData(b);a=d.Prefab.packResources(c,{"@json":e.prefab_json,"@version":la.version},this);e._original_data=a;return e}};la.packResources=function(a,b,c){b=b||{};c=[];if(a&&a.length)for(var e=0;e<a.length;++e){var g=a[e],f=d.ResourcesManager.resources[g];if(f){var h=null;if(f._original_data)h=f._original_data;else{h=d.Resource.getDataToStore(f);if(!h){console.warn("Data to store from resource is null, skipping: ",
g);continue}if(h.extension&&h.extension!=d.ResourcesManager.getExtension(g)){console.warn("The resource extension has changed while saving, this could lead to problems: ",g,h.extension);var k=g,g=g+"."+h.extension;a[e]=g;d.GlobalScene.sendResourceRenamedEvent(k,g,f)}h=h.data}h?h.constructor===Blob||h.constructor===File?console.warn("WBin does not support to store File or Blob, please convert to ArrayBuffer using FileReader"):(b["@RES_"+c.length]=h,c.push(g)):console.warn("Wrong data in resource")}}b["@resources_name"]=
c;return WBin.create(b,"Prefab")};la.prototype.updateFromNode=function(a,b){var c=a.serialize(!0);b&&d.clearUIds(c);this.prefab_data=c;this.prefab_json=JSON.stringify(c)};la.prototype.flagResources=function(){if(this.resource_names)for(var a=0;a<this.resource_names.length;++a){var b=d.ResourcesManager.resources[this.resource_names[a]];b&&(b.from_prefab=this.fullpath||this.filename)}};la.prototype.setResourcesLink=function(a){if(this.resource_names)for(var b=0;b<this.resource_names.length;++b){var c=
d.ResourcesManager.resources[this.resource_names[b]];c&&(a?c.from_prefab=a:delete c.from_prefab)}};la.prototype.applyToNodes=function(a){a=a||d.GlobalScene;for(var b=this.fullpath||this.filename,c=0;c<a._nodes.length;++c){var e=a._nodes[c];e.prefab==b&&e.reloadFromPrefab()}};la.prototype.getDataToStore=function(){this.prefab_json=JSON.stringify(this.prefab_data);var a=this.fullpath||this.filename;return this.resource_names&&this.resource_names.length||!a||"json"!=d.RM.getExtension(a)?d.Prefab.packResources(this.resource_names,
this.getBaseData(),this):JSON.stringify({object_class:d.getObjectClassName(this),"@json":this.prefab_json})};la.prototype.getBaseData=function(){return{"@json":this.prefab_json,"@version":d.Prefab.version}};la.prototype.recomputeData=function(){var a=this.getDataToStore();a&&(this._original_data=a.buffer)};la.prototype.containsResources=ia.prototype.containsResources;la.prototype.onResourceRenamed=ia.prototype.onResourceRenamed;la.prototype.checkResourceNames=ia.prototype.checkResourceNames;la.prototype.setResources=
ia.prototype.setResources;la.prototype.getSizeInBytes=ia.prototype.getSizeInBytes;d.Prefab=la;d.registerResourceClass(la);ea.help_url="https://github.com/jagenjo/litescene.js/blob/master/guides/shaders.md";ea.CODE=1;ea.PRAGMA=2;ea.INCLUDE=1;ea.SHADERBLOCK=2;ea.SNIPPET=3;ea.EXTENSION="glsl";Object.defineProperty(ea.prototype,"code",{enumerable:!0,get:function(){return this._code},set:function(a){this._code!=a&&(this._code=a,this.processCode())}});Object.defineProperty(ea.prototype,"version",{enumerable:!1,
get:function(){return this._version},set:function(a){console.error("version cannot be set manually")}});ea.prototype.processCode=function(){this._global_uniforms={};this._code_parts={};this._compiled_shaders={};this._functions={};this._shaderblock_flags_num=0;this._shaderblock_flags={};this._shaderblock_vars=null;this._has_error=!1;var a=GL.processFileAtlas(this._code);this._subfiles=a;var b=0,c=null,e;for(e in a){var g=e,f=a[e];b++;if(g)if("js"==g)c=f;else if("uniforms"==g)for(var g=f.split("/n"),
h=0;h<g.length;++h){var k=g[h].trim(),l=k.split(" "),f=l[0],n=l[1],p=l[2],l=l[3];void 0!==l&&(l=d.stringToValue(l));var m=null,q=k.indexOf("{");-1!=q&&(m=d.stringToValue(k.substr(q)));this._global_uniforms[f]={name:f,uniform:n,type:p,value:l,options:m}}else if(n=d.ResourcesManager.removeExtension(g),"default"==n&&(n="color"),g=d.ResourcesManager.getExtension(g),"vs"==g||"fs"==g){(k=this._code_parts[n])||(k=this._code_parts[n]={});f=new ka(f);for(h in f.blocks)(n=f.blocks[h])&&n.type==ea.PRAGMA&&(n.shader_block_flag=
this._shaderblock_flags_num,this._shaderblock_flags[n.shader_block]=n.shader_block_flag,this._shaderblock_flags_num+=1);k[g]=f}}if(a=this.getShader()){if(c&&(c=d.ShaderCode.removeComments(c)))if(d.catch_exceptions)try{this._functions.init=new Function(c)}catch(s){d.dispatchCodeError(s,aa.computeLineFromError(s),this)}else this._functions.init=new Function(c);this.validatePublicUniforms(a);LEvent.trigger(d.ShaderCode,"modified",this);this._version+=1}};ea.prototype.setData=function(a,b){this.code=
a;b||(this._modified=!0)};ea.prototype.getData=function(){return this._code};ea.prototype.getDataToStore=function(){return this._code};ea.prototype.getShader=function(a,b){if(this._has_error)return null;a=a||"color";b=b||0;var c=this._compiled_shaders[a];if(c){var e=c.get(b);if(e)return e}e=this._code_parts[a];if(!e)return null;for(var c={},g=0,f=d.Shaders.shader_blocks.length;g<f;++g)if(b&1<<g){var h=d.Shaders.shader_blocks[g];if(h&&h.context_macros)for(var k in h.context_macros)c[k]=h.context_macros[k]}k=
null;if("fx"==a)k=GL.Shader.SCREEN_VERTEX_SHADER;else if(e.vs)k=e.vs.getFinalCode(GL.VERTEX_SHADER,b,c);else return null;if(e.fs){f=e.fs.getFinalCode(GL.FRAGMENT_SHADER,b,c);if(!k||!f)return this._has_error=!0,null;k=d.Shaders.global_extra_shader_code+k;f=d.Shaders.global_extra_shader_code+f;e=this.compileShader(k,f);if(!e)return null;if(d.debug){for(var l=[],g=0;g<d.Shaders.num_shaderblocks;++g)b&1<<g&&(h=d.Shaders.shader_blocks[g])&&l.push(h);e._shadercode_info={vs:k,fs:f,context:c,blocks:l,flags:b}}this._compiled_shaders[a]||
(this._compiled_shaders[a]=new Map);this._compiled_shaders[a].set(b,e);return e}};ea.prototype.compileShader=function(a,b){if(this._has_error)return null;d.Debug&&(console.log("Shader Compiled: ",this.fullpath||this.filename),console.groupCollapsed("VS shader"),console.log(a),console.groupEnd(),console.groupCollapsed("FS shader"),console.log(b),console.groupEnd());if(d.catch_exceptions)try{return new GL.Shader(a,b)}catch(c){this._has_error=!0;d.Shaders.dumpShaderError(this.filename,c,a,b);var e=GL.Shader.parseError(c,
a,b),g=this._code.split("\n"),f=-1;if(e.line_code){e=e.line_code.trim();for(f=0;f<g.length;++f)g[f]=g[f].trim();f=g.indexOf(e)}d.dispatchCodeError(c,f,this,"shader")}else return new GL.Shader(a,b);return null};ea.prototype.clearCache=function(){this._compiled_shaders={}};ea.prototype.validatePublicUniforms=function(a){if(!a)throw"ShaderCode: Shader cannot be null";for(var b in this._global_uniforms)a.uniformInfo[this._global_uniforms[b].uniform]||(info.disabled=!0)};ea.prototype.register=function(){d.ResourcesManager.registerResource(this.fullpath||
this.filename,this)};ea.prototype.applyToMaterials=function(a){a=a||d.GlobalScene;var b=this.fullpath||this.filename,c;for(c in d.ResourcesManager.resources){var e=d.ResourcesManager.resources[c];e.constructor===d.ShaderMaterial&&e._shader==b&&e.processShaderCode()}a=a.getNodes();for(c=0;c<a.length;++c)e=a[c],e.material&&e.material.constructor===d.ShaderMaterial&&e.material._shader==b&&e.material.processShaderCode()};ea.prototype.hasEditableText=function(){return!0};ea.removeComments=function(a){return a.replace(/(\/\*([\s\S]*?)\*\/)|(\/\/(.*)$)/gm,
"")};ea.replaceCode=function(a,b){return a.replace(/\{\{[a-zA-Z0-9_]*\}\}/g,function(a){a=a.replace(/[\{\}]/g,"");return b[a]||""})};ea.parseShaderLab=function(a){var b={},c=b,e=[],d=[],f=0,h="";a=ea.removeComments(a).split("\n");for(var k=0;k<a.length;++k){var l=a[k].trim(),n=l.match(/[^\s"]+|"([^"]*)"/gi);if(n)if(0!=f){var p=n[0].trim();"ENDGLSL"==p||"ENDCG"==p?(f=0,c.codetype=f,c.code=h,h=""):h+=l+"\n"}else for(l=0;l<n.length;++l)if(p=n[l],"{"==p)p={name:e[0],params:e.slice(1).join(" "),content:{}},
c[p.name]=p,e=[],d.push(c),c=p.content;else if("}"==p){if(0==d.length)return console.error("error parsing ShaderLab code, the number of { do not matches the }"),null;e.length&&(c[e[0]]=e.join(" "),e=[]);c=d.pop()}else"{}"==p?(p={name:e[0],params:e.slice(1).join(" "),content:{}},c[p.name]=p,e=[]):"GLSLPROGRAM"==p||"CGPROGRAM"==p?(f="GLSLPROGRAM"==p?1:2,h=""):e.push(p)}return b};ea.flat_code="\\color.vs\n\tprecision mediump float;\n\tattribute vec3 a_vertex;\n\tuniform mat4 u_model;\n\tuniform mat4 u_viewprojection;\n\tvoid main() {\n\t\tvec4 vertex4 = vec4(a_vertex,1.0);\n\t\tgl_Position = (u_viewprojection * u_model) * vertex4;\n\t}\n\\color.fs\n\tprecision mediump float;\n\tuniform vec4 u_material_color;\n\tvoid main() {\n\t\tgl_FragColor = u_material_color;\n\t}\n\\picking.vs\n\tprecision mediump float;\n\tattribute vec3 a_vertex;\n\tuniform mat4 u_model;\n\tuniform mat4 u_viewprojection;\n\tvoid main() {\n\t\tvec4 vertex4 = vec4(a_vertex,1.0);\n\t\tgl_Position = (u_viewprojection * u_model) * vertex4;\n\t}\n\\picking.fs\n\tprecision mediump float;\n\tuniform vec4 u_material_color;\n\tvoid main() {\n\t\tgl_FragColor = u_material_color;\n\t}\n\\shadow.vs\n\tprecision mediump float;\n\tattribute vec3 a_vertex;\n\tuniform mat4 u_model;\n\tuniform mat4 u_viewprojection;\n\tvoid main() {\n\t\tvec4 vertex4 = vec4(a_vertex,1.0);\n\t\tgl_Position = (u_viewprojection * u_model) * vertex4;\n\t}\n\\shadow.fs\n\tprecision mediump float;\n\tuniform vec4 u_material_color;\n\tvoid main() {\n\t\tgl_FragColor = u_material_color;\n\t}\n";
d.ShaderCode=ea;d.registerResourceClass(ea);Aa.LOGIC_GRAPH=1;Aa.SHADER_GRAPH=2;Aa.EXTENSION="GRAPH.json";Aa.hasPreview=!1;Object.defineProperty(Aa.prototype,"graph",{enumerable:!1,get:function(){return this._graph},set:function(a){console.error("graph cannot be set manually")}});Object.defineProperty(Aa.prototype,"data",{enumerable:!1,get:function(){return this.getData()},set:function(a){this.setData(a)}});Object.defineProperty(Aa.prototype,"version",{enumerable:!1,get:function(){return this._version},
set:function(a){console.error("version cannot be set manually")}});Object.defineProperty(Aa.prototype,"type",{enumerable:!1,get:function(){return this.extra.type},set:function(a){this.extra.type=a}});Aa.prototype.setData=function(a,b){if(a){if(d.catch_exceptions)try{this._data=a.constructor===String?JSON.parse(a):JSON.parse(JSON.stringify(a))}catch(c){console.error("error in graph data");return}else this._data=a.constructor===String?JSON.parse(a):JSON.parse(JSON.stringify(a));this._graph.configure(this._data);
this._data.extra&&(this.extra=this._data.extra);b||(this._version++,this._modified=!0)}else this._data=null};Aa.prototype.getData=function(){var a=this.graph.serialize();a.object_class="GraphCode";a.extra=this.extra;return a};Aa.prototype.getDataToStore=function(){return JSON.stringify(this.getData())};Aa.prototype.getCategory=function(){return"Graph"};Aa.prototype.propagate=function(){if(this.type==Aa.LOGIC_GRAPH)for(var a=d.GlobalScene.findNodeComponents(d.Components.GraphComponent),b=0;b<a.length;++b){var c=
a[b];c.filename==this.filename&&(c.graphcode=this)}};Aa.prototype.getShaderCode=function(a){if(this._shader_code&&this._code_version==this._graph._version&&!a)return this._shader_code;this._shader_code||(this._shader_code=new d.ShaderCode);if(!this._graph.findNodesByClass("shader/surface"))return null;var b=d.SurfaceMaterial.code_template,c={uniforms:[]},e="",g=this._graph._nodes_in_order;if(g)for(var f=0;f<g.length;++f){var h=g[f];h.onGetCode&&(e+=h.onGetCode("glsl",c))}g="";for(f=0;f<c.uniforms.length;++f)h=
c.uniforms[f],g+="uniform "+h.type+" "+h.link_name+";\n";c={fs_out:g+"\n\nvoid surf( in Input IN, inout SurfaceOutput o ) {\n\to.Albedo = vec3(1.0) * IN.color.xyz;\n\to.Normal = IN.worldNormal;\n\to.Emission = vec3(0.0);\n\to.Specular = 1.0;\n\to.Gloss = 40.0;\n\to.Reflectivity = 0.0;\n\to.Alpha = IN.color.a;\n\n"+e+"\n}\n"};if(a)return c.fs_out;this._shader_code.code=d.ShaderCode.replaceCode(b,c);this._code_version=this._graph._version;return this._shader_code};d.GraphCode=Aa;d.registerResourceClass(Aa);
"undefined"!=typeof LiteGraph&&(da.LGraphScene=function(){this.addOutput("Time","number");this._scene=null},LGraphScene.title="Scene",LGraphScene.desc="Scene",LGraphScene.getComponents=function(a,b){b=b||[];var c=a.getComponents();if(!c)return b;for(var e=0;e<c.length;++e){var g=d.getClassName(c[e].constructor);b.push([g,g])}return b},LGraphScene.prototype.onAdded=function(a){this.bindEvents(this.graph.getScene?this.graph.getScene():d.GlobalScene)},LGraphScene.prototype.onRemoved=function(){this.bindEvents(null)},
LGraphScene.prototype.onConnectionsChange=function(){this.bindEvents(this.graph.getScene?this.graph.getScene():d.GlobalScene)},LGraphScene.prototype.bindEvents=function(a){this._scene&&LEvent.unbindAll(this._scene,this);if((this._scene=a)&&this.outputs&&this.outputs.length)for(a=0;a<this.outputs.length;++a){var b=this.outputs[a];b.type===LiteGraph.EVENT&&(b=b.name.substr(3),LEvent.bind(this._scene,b,this.onEvent,this))}},LGraphScene.prototype.onEvent=function(a,b){this.trigger("on_"+a,b)},LGraphScene.prototype.onExecute=
function(){var a=this.graph.getScene?this.graph.getScene():d.GlobalScene;if(this.inputs)for(var b=0;b<this.inputs.length;++b)this.getInputData(b);if(this.outputs)for(b=0;b<this.outputs.length;++b){var c=this.outputs[b];if(c.links&&c.links.length&&c.type!=LiteGraph.EVENT){var e=null;switch(c.name){case "Time":e=a.getTime();break;case "Elapsed":e=null!=a._last_dt?a._last_dt:0;break;case "Frame":e=null!=a._frame?a._frame:0;break;default:e=a.root.getComponent(c.name)}this.setOutputData(b,e)}}},LGraphScene.prototype.onGetOutputs=
function(){var a=[["Elapsed","number"],["Frame","number"],["on_start",LiteGraph.EVENT],["on_finish",LiteGraph.EVENT]];return LGraphScene.getComponents(this.graph.getScene().root,a)},LiteGraph.registerNodeType("scene/scene",LGraphScene),da.LGraphSceneNode=function(){this.properties={node_id:""};this.size=[140,30];this._node=null},LGraphSceneNode.title="SceneNode",LGraphSceneNode.desc="Node on the scene",LGraphSceneNode.prototype.onRemoved=function(){this._node&&this.bindNodeEvents(null)},LGraphSceneNode.prototype.onConnectionsChange=
function(){this.bindNodeEvents(this._component)},LGraphSceneNode.prototype.getNode=function(){var a=null;if(!this.graph)return null;this.inputs&&this.inputs[0]&&(a=this.getInputData(0));a&&(this.properties.node_id=a);!a&&this.properties.node_id&&(a=this.properties.node_id);if("@"==a)return this.graph._scenenode?this.graph._scenenode:null;var b=this.graph&&this.graph.getScene?this.graph.getScene():d.GlobalScene;if(b){var c=null;a&&(c=b.getNode(a));this._node!=c&&this.bindNodeEvents(c);return c}},LGraphSceneNode.prototype.onExecute=
function(){var a=this.getNode();if(a){if(this.inputs)for(var b=0;b<this.inputs.length;++b){var c=this.inputs[b];if(c.type!==LiteGraph.ACTION){var e=this.getInputData(b);if(void 0!==e)switch(c.name){case "UID":this.properties.node_id=e;break;case "SceneNode":this.properties.node_id=e?e.uid:null;e&&(a=e);break;case "Transform":a.transform.copyFrom(e);break;case "Material":a.material=e;break;case "Visible":a.flags.visible=e}}}if(this.outputs)for(b=0;b<this.outputs.length;++b)if(c=this.outputs[b],c.links&&
c.links.length&&c.type!=LiteGraph.EVENT)switch(c.name){case "SceneNode":this.setOutputData(b,a);break;case "Material":this.setOutputData(b,a.getMaterial());break;case "Transform":this.setOutputData(b,a.transform);break;case "Name":this.setOutputData(b,a.name);break;case "Children":this.setOutputData(b,a.children);break;case "UID":this.setOutputData(b,a.uid);break;case "Mesh":this.setOutputData(b,a.getMesh());break;case "Visible":this.setOutputData(b,a.flags.visible);break;default:e=a.getComponentByUId(c.name);
if(!e){var g=a.scene.findComponentByUId(c.name);g&&(e=d.getObjectClassName(g),e=a.getComponent(e))&&(c.name=e.uid)}this.setOutputData(b,e)}}},LGraphSceneNode.prototype.getComponents=function(a){a=a||[];var b=this.getNode();if(!b)return a;b=b.getComponents();if(!b)return a;for(var c=0;c<b.length;++c){var e=d.getClassName(b[c].constructor);a.push([b[c].uid,e,{label:e}])}return a},LGraphSceneNode.prototype.onDropItem=function(a){if(a=a.dataTransfer.getData("node_uid"))return this.properties.node_id=
a,this.onExecute(),!0},LGraphSceneNode.prototype.onPropertyChanged=function(a,b){"node_id"==a&&this.getNode()},LGraphSceneNode.prototype.bindNodeEvents=function(a){this._node&&LEvent.unbindAll(this._node,this);if((this._node=a)&&this.outputs&&this.outputs.length)for(a=0;a<this.outputs.length;++a){var b=this.outputs[a];b.type===LiteGraph.EVENT&&(b=b.name.substr(3),LEvent.bind(this._node,b,this.onNodeEvent,this))}},LGraphSceneNode.prototype.onNodeEvent=function(a,b){this.trigger("on_"+a,b)},LGraphSceneNode.prototype.onGetInputs=
function(){return this.getComponents([["Visible","boolean"],["UID","string"],["SceneNode","SceneNode"],["Material","Material"]])},LGraphSceneNode.prototype.onGetOutputs=function(){return this.getComponents([["SceneNode","SceneNode"],["Visible","boolean"],["Material","Material"],["Name","string"],["UID","string"],["Children","scenenode[]"],["on_clicked",LiteGraph.EVENT]])},LGraphSceneNode.prototype.onInspect=function(a){var b=this;a.addButton(null,"Inspect node",function(){var a=b.getNode();a&&EditorModule.inspect(a)})},
LiteGraph.registerNodeType("scene/node",LGraphSceneNode),da.LGraphMaterial=function(){this.properties={material_id:"",node_id:""};this.addInput("Material","Material");this.size=[100,30]},LGraphMaterial.title="Material",LGraphMaterial.desc="Material of a node",LGraphMaterial.prototype.onExecute=function(){var a=this.getMaterial();if(a){for(var b=0;b<this.inputs.length;++b){var c=this.inputs[b],e=this.getInputData(b);void 0!==e&&"Material"!=c.name&&a.setProperty(c.name,e)}if(this.outputs)for(b=0;b<
this.outputs.length;++b)c=this.outputs[b],c.links&&c.links.length&&(e=a.getProperty(c.name),this.setOutputData(b,e))}},LGraphMaterial.prototype.getMaterial=function(){var a=this.findInputSlot("Material");return-1!=a?this.getInputData(a):this.properties.material_id&&d.RM.materials[this.properties.material_id]?d.RM.materials[this.properties.material_id]:this.properties.node_id&&(a=this.graph.getScene().getNode(this.properties.node_id))?a.getMaterial():null},LGraphMaterial.prototype.onGetInputs=function(){var a=
this.getMaterial();if(a){var a=a.getPropertiesInfo(),b=[["Material","Material"]],c;for(c in a)b.push([c,a[c]]);return b}},LGraphMaterial.prototype.onGetOutputs=function(){var a=this.getMaterial();if(a){var a=a.getPropertiesInfo(),b=[["Material","Material"]],c;for(c in a)b.push([c,a[c]]);return b}},LGraphMaterial.prototype.onInspect=function(a){var b=this;a.addButton(null,"Inspect material",function(){var a=b.getMaterial();a&&EditorModule.inspect(a)})},LiteGraph.registerNodeType("scene/material",LGraphMaterial),
da.LGraphMaterial=LGraphMaterial,da.LGraphGlobal=function(){this.addOutput("Value");this.properties={name:"myvar",value:0,type:"number",widget:"default",min:0,max:1}},LGraphGlobal.title="Global",LGraphGlobal.desc="Global var for the graph",LGraphGlobal["@type"]={type:"enum",values:"number boolean string node vec2 vec3 vec4 color texture".split(" ")},LGraphGlobal["@widget"]={type:"enum",values:["default","slider","pad"]},LGraphGlobal.prototype.onExecute=function(){this.properties.name&&this.setOutputData(0,
this.properties.value)},LGraphGlobal.prototype.onDrawBackground=function(){this.outputs[0].label=this.properties.name},LiteGraph.registerNodeType("scene/global",LGraphGlobal),da.LGraphSceneTime=function(){this.addOutput("Time","number");this._scene=null},LGraphSceneTime.title="Time",LGraphSceneTime.desc="Time",LGraphSceneTime.prototype.onExecute=function(){var a=this.graph.getScene();if(a){if(this.inputs)for(var b=0;b<this.inputs.length;++b)this.getInputData(b);if(this.outputs)for(b=0;b<this.outputs.length;++b){var c=
this.outputs[b];if(c.links&&c.links.length&&c.type!=LiteGraph.EVENT){var e=null;switch(c.name){case "Time":e=a.getTime();break;case "Elapsed":e=null!=a._last_dt?a._last_dt:0;break;case "Frame":e=null!=a._frame?a._frame:0;break;default:continue}this.setOutputData(b,e)}}}},LGraphSceneTime.prototype.onGetOutputs=function(){return[["Elapsed","number"],["Time","number"]]},LiteGraph.registerNodeType("scene/time",LGraphSceneTime),da.LGraphLocatorProperty=function(){this.addInput("in");this.addOutput("out");
this.properties={locator:"",cache_object:!0};this._locator_info=this._locator_split=null},LGraphLocatorProperty.title="Property",LGraphLocatorProperty.desc="A property of a node or component of the scene specified by its locator string",LGraphLocatorProperty.prototype.getLocatorInfo=function(a){if(!this._locator_split)return null;if(!a&&this.properties.cache_object&&this._locator_info)return this._locator_info;if(!this.graph)return null;(this._locator_info=(this.graph._scene||d.GlobalScene).getPropertyInfoFromPath(this._locator_split))&&
this.inputs&&this.inputs.length&&(this.inputs[0].type=this._locator_info.type);return this._locator_info},LGraphLocatorProperty.prototype.onPropertyChanged=function(a,b){"locator"==a&&(this._locator_split=b?b.split("/"):null)},LGraphLocatorProperty.prototype.onAction=function(a,b){var c=this.getLocatorInfo();Na.setFromInfo(c,!Na.getFromInfo(c))},LGraphLocatorProperty.prototype.getTitle=function(){return this.title&&this.title!=LGraphLocatorProperty.title||!this._locator_info?this.title||LGraphLocatorProperty.title:
this._locator_info.name},LGraphLocatorProperty.prototype.onExecute=function(){var a=this.getLocatorInfo();a&&a.target&&(this.inputs.length&&null!==this.inputs[0].link&&Na.setFromInfo(a,this.getInputData(0)),this.outputs.length&&this.outputs[0].links&&this.outputs[0].links.length&&this.setOutputData(0,Na.getFromInfo(a)))},LGraphLocatorProperty.prototype.onInspect=function(a){var b=this.getLocatorInfo(!0);if(b){a.addSeparator();var c=b.type,e=null;b.target&&b.target.constructor["@"+b.name]&&(e=b.target.constructor["@"+
b.name],e.widget?c=e.widget:e.type&&(c=e.type));a.add(c,b.name,b.value,{callback:function(a){d.setObjectProperty(b.target,b.name,a)}})}},LiteGraph.registerNodeType("scene/property",LGraphLocatorProperty),da.LGraphToggleValue=function(){this.addInput("target","Component");this.addInput("toggle",LiteGraph.ACTION);this.properties={property_name:"enabled"}},LGraphToggleValue.title="Toggle",LGraphToggleValue.desc="Toggle a property value",LGraphToggleValue.prototype.getTitle=function(){return"Toggle: "+
this.properties.property_name},LGraphToggleValue.prototype.onAction=function(a,b){var c=this.getInputData(0,!0);if(c){var e=this.properties.property_name||"enabled";void 0!==c[e]&&(c[e]=!c[e])}},LiteGraph.registerNodeType("scene/toggle",LGraphToggleValue),da.LGraphFrame=function(){this.addOutput("Color","Texture");this.addOutput("Depth","Texture");this.addOutput("Extra","Texture");this.addOutput("Camera","Camera");this.properties={}},LGraphFrame.title="Frame",LGraphFrame.desc="One frame rendered from the scene renderer",
LGraphFrame.prototype.onExecute=function(){this.setOutputData(0,LGraphTexture.getTexture(this._color_texture));this.setOutputData(1,LGraphTexture.getTexture(this._depth_texture));this.setOutputData(2,LGraphTexture.getTexture(this._extra_texture));this.setOutputData(3,this._camera)},LGraphFrame.prototype.onDrawBackground=function(a){if(!(this.flags.collapsed||20>=this.size[1])&&this._color_texture&&a.webgl){if(this._last_preview_tex!=this._last_tex||!this._last_preview_tex)if(a.webgl&&this._canvas&&
this._canvas.constructor===GL.Texture)this._canvas=this._last_tex;else{var b=LGraphTexture.getTexture(this._color_texture);if(!b)return;b=LGraphTexture.generateLowResTexturePreview(b);if(!b)return;this._last_preview_tex=this._last_tex;this._canvas=cloneCanvas(b)}if(this._canvas){a.save();if(!a.webgl){if(this._canvas.constructor===GL.Texture){this._canvas=null;return}a.translate(0,this.size[1]);a.scale(1,-1)}a.drawImage(this._canvas,0,0,this.size[0],this.size[1]);a.restore()}}},LGraphFrame.prototype.onInspect=
function(a){var b=this,c=this.graph.component.frame;this.graph.component&&(a.showObjectFields(c),a.addSeparator(),a.addCheckbox("Antialiasing",this.graph.component.use_antialiasing,function(a){b.graph.component.use_antialiasing=a}))},LiteGraph.registerNodeType("scene/frame",LGraphFrame));"undefined"!=typeof LiteGraph&&(da.LGraphComponent=function(){this.properties={node_id:"",component_id:""};this._component=null},LGraphComponent.title="Component",LGraphComponent.desc="A component from a node",LGraphComponent.prototype.onRemoved=
function(){this.bindComponentEvents(null)},LGraphComponent.prototype.onConnectionsChange=function(a){this.bindComponentEvents(this._component)},LGraphComponent.prototype.onInit=function(){var a=this.getComponent();a&&this.processOutputs(a)},LGraphComponent.prototype.processOutputs=function(a){if(this.outputs&&this.outputs.length)for(var b=0;b<this.outputs.length;b++){var c=this.outputs[b];if(c.links&&c.links.length&&c.type!=LiteGraph.EVENT)if("Component"==c.name)this.setOutputData(b,a);else if(a.getProperty){var e=
a.getProperty(c.name);void 0!==e?this.setOutputData(b,e):this.setOutputData(b,a[c.name])}else this.setOutputData(b,a[c.name])}},LGraphComponent.prototype.onExecute=function(){var a=this.getComponent();if(a){if(this.inputs)for(var b=0;b<this.inputs.length;b++){var c=this.inputs[b];if(c.type!==LiteGraph.ACTION){var e=this.getInputData(b);void 0!==e&&d.setObjectProperty(a,c.name,e)}}this.processOutputs(a)}},LGraphComponent.updateOutputData=function(a){if(this.outputs&&!(a>=this.outputs.length)){var b=
this.outputs[Nb];if(b.links&&b.links.length&&b.type!=LiteGraph.EVENT){var c=this.getComponent();c&&("Component"==b.name?this.setOutputData(a,c):this.setOutputData(a,c[b.name]))}}},LGraphComponent.prototype.onDrawBackground=function(){var a=this.getComponent();a&&(this.title=d.getClassName(a.constructor))},LGraphComponent.prototype.onConnectionsChange=function(a,b,c,e,d){a==LiteGraph.INPUT&&d&&"Component"==d.name&&(a=this.getInputNode(b))&&a.onExecute&&(a.onExecute(),this.setDirtyCanvas(!0,!0))},LGraphComponent.prototype.getComponent=
function(){var a=this.graph._scene||d.GlobalScene,b=this.properties.node_id;if(!b)return this.inputs&&this.inputs.length&&(a=this.findInputSlot("Component"),-1!=a)?(a=this.getInputData(a))?a:null:null;a=a.getNode(b);if(!a)return null;var b=this.properties.component_id,c=null;if("@"==b.charAt(0))c=a.getComponentByUId(b);else if(d.Components[b])c=a.getComponent(d.Components[b]);else return null;if(c&&!c.constructor.is_component)return null;this._component!=c&&this.bindComponentEvents(c);return this._component=
c},LGraphComponent.prototype.bindComponentEvents=function(a){this._component&&LEvent.unbindAll(this._component,this);if((this._component=a)&&this.outputs&&this.outputs.length)for(a=0;a<this.outputs.length;++a){var b=this.outputs[a];b.type===LiteGraph.EVENT&&(b=b.name.substr(3),LEvent.bind(this._component,b,this.onComponentEvent,this))}},LGraphComponent.prototype.onComponentEvent=function(a,b){this.trigger("on_"+a,b)},LGraphComponent.prototype.getComponentProperties=function(a,b){var c=this.getComponent();
if(!c)return null;var e=null,e=c.getPropertiesInfo?c.getPropertiesInfo(a):d.getObjectProperties(c);b=b||[];for(var g in e)b.push([g,e[g]]);c.getExtraProperties&&c.getExtraProperties(b);return b},LGraphComponent.prototype.onAction=function(a,b){if(a){var c=this.getComponent();if(c)if(c.onAction)c.onAction(a,b);else if(c[a])c[a]()}},LGraphComponent.prototype.onSetValue=function(a,b){var c=this.getComponent();if(c){var e=c[a],d;if(null==e)b&&b.constructor===String&&(d=b);else switch(e.constructor){case Number:d=
Number(b);break;case Boolean:d="true"==b||"1"==b;break;case String:d=String(b);break;case Array:case Float32Array:d=null!=b?b.constructor===String?JSON.parse("["+b+"]"):b.constructor===Number?[b]:b:b}void 0!==d&&(c.setPropertyValue?c.setPropertyValue(a,d):c[a]=d)}},LGraphComponent.prototype.onGetInputs=function(){var a=[["Node",0],["Component",0],null];this.getComponentProperties("input",a);var b=this.getComponent();if(b&&b.getActions&&(b=b.getActions({})))if(b.constructor===Array)for(var c=0;c<b.length;++c)a.push([b[c],
LiteGraph.ACTION]);else for(c in b)a.push([c,LiteGraph.ACTION]);return a},LGraphComponent.prototype.onGetOutputs=function(){var a=[];a.push(["Component","Component"],null);this.getComponentProperties("output",a);var b=this.getComponent();if(b&&b.getEvents&&(b=b.getEvents()))if(b.constructor===Array)for(var c=0;c<b.length;++c)a.push(["on_"+b[c],LiteGraph.EVENT]);else for(c in b)a.push(["on_"+c,LiteGraph.EVENT]);return a},LGraphComponent.prototype.onInspect=function(a){var b=this,c=this.getComponent();
if(c&&c.onInspectNode)c.onInspectNode(a,this);a.addButton(null,"Inspect Component",function(){var a=b.getComponent();a&&EditorModule.inspect(a)})},LiteGraph.registerNodeType("scene/component",LGraphComponent),da.LGraphTransform=function(){this.properties={node_id:""};LGraphSceneNode._current_node_id&&(this.properties.node_id=LGraphSceneNode._current_node_id);this.addInput("Transform","Transform",{locked:!0});this.addOutput("Position","vec3")},LGraphTransform.title="Transform",LGraphTransform.desc=
"Transform info of a node",LGraphTransform.prototype.onExecute=function(){var a=null;this.inputs&&this.inputs[0]&&(a=this.getInputData(0));if(!a){var a=this.graph.getScene?this.graph.getScene():d.GlobalScene,b=this._node;if(this.properties.node_id&&(b=a.getNode(this.properties.node_id),!b))return;b||(b=this.graph._scenenode);a=b.transform}if(a){if(this.inputs)for(b=1;b<this.inputs.length;++b){var c=this.inputs[b],e=this.getInputData(b);if(void 0!==e)switch(c.name){case "x":a.x=e;break;case "y":a.y=
e;break;case "z":a.z=e;break;case "Position":a.setPosition(e);break;case "Rotation":a.setRotation(e);break;case "Scale":a.setScale(e);break;case "Matrix":a.fromMatrix(e);break;case "Mult.Matrix":a.applyTransformMatrix(e);break;case "Translate":a.translate(e);break;case "Translate Global":a.translateGlobal(e);break;case "Rotate":quat.multiply(a._rotation,a._rotation,e);a._must_update=!0;break;case "RotateX":a.rotateX(e);break;case "RotateY":a.rotateY(e);break;case "RotateZ":a.rotateZ(e)}}if(this.outputs)for(b=
0;b<this.outputs.length;++b)if(c=this.outputs[b],c.links&&c.links.length){e=void 0;switch(c.name){case "x":e=a.x;break;case "y":e=a.y;break;case "z":e=a.z;break;case "Position":e=a.position;break;case "Global Position":e=a.getGlobalPosition();break;case "Rotation":e=a.rotation;break;case "Global Rotation":e=a.getGlobalRotation();break;case "Scale":e=a.scaling;break;case "Matrix":e=a.getMatrix()}void 0!==e&&this.setOutputData(b,e)}}},LGraphTransform.prototype.onGetInputs=function(){return[["Position",
"vec3"],["Rotation","quat"],["Scale","number"],["x","number"],["y","number"],["z","number"],["Global Position","vec3"],["Global Rotation","quat"],["Matrix","mat4"],["Mult.Matrix","mat4"],["Translate","vec3"],["Translate Global","vec3"],["Rotate","quat"],["RotateX","number"],["RotateY","number"],["RotateZ","number"]]},LGraphTransform.prototype.onGetOutputs=function(){return[["Position","vec3"],["Rotation","quat"],["Scale","number"],["x","number"],["y","number"],["z","number"],["Global Position","vec3"],
["Global Rotation","quat"],["Matrix","mat4"]]},LiteGraph.registerNodeType("scene/transform",LGraphTransform));"undefined"!=typeof LiteGraph&&(da.LGraphSetValue=function(){this.properties={property_name:"",value:"",type:"String"};this.addInput("on_set",LiteGraph.ACTION);this.addInput("value","");this.addOutput("on",LiteGraph.EVENT);this.addOutput("node",0);this.mode=LiteGraph.ON_TRIGGER},LGraphSetValue.prototype.onAction=function(a,b){if(this.properties.property_name){var c=this.getOutputNodes(1);
if(c){for(var e=this.getInputOrProperty("value"),d=0;d<c.length;++d){var f=c[d];if(f.onSetValue)f.onSetValue(this.properties.property_name,e);else if(f.properties&&void 0!==f.properties.value&&(f.properties[this.properties.property_name]=e,f.onPropertyChanged))f.onPropertyChanged(this.properties.property_name,e)}this.trigger("on")}}},LGraphSetValue.title="SetValue",LGraphSetValue.desc="sets a value to a node (could be a property)",LiteGraph.registerNodeType("logic/setValue",LGraphSetValue));if("undefined"!=
typeof LiteGraph){var rc=!1;"undefined"==typeof LGraphTexture?console.error("LiteGraph found but no LGraphTexture, this means LiteGL wasnt not included BEFORE litegraph. Be sure to include LiteGL before LiteGraph to ensure all functionalities."):rc=!0;var lb=function(){this.addInput("Color","Texture");this.addInput("Depth","Texture");this.addInput("Intensity","number");this.addOutput("Final","Texture");this.properties={intensity:1,preserve_aspect:!0};this._fx_stack=new d.FXStack;this._fx_options=
{}};lb.title="FXStack";lb.desc="Apply FXs to Texture";lb.prototype.onExecute=function(){var a=this.getInputData(0);if(a&&this.isOutputConnected(0)){var b=this._final_texture;b&&b.width==a.width&&b.height==a.height&&b.type==a.type||(this._final_texture=new GL.Texture(a.width,a.height,{type:a.type,format:gl.RGBA,filter:gl.LINEAR}));this.isInputConnected(1)&&(this._fx_options.depth_texture=this.getInputData(1));b=this.properties.intensity;this.isInputConnected(2)&&(b=this.getInputData(2),this.properties.intensity=
b);this._fx_stack.applyFX(a,this._final_texture,this._fx_options);this.setOutputData(0,this._final_texture)}};lb.prototype.onInspect=function(a){return this._fx_stack.inspect(a)};lb.prototype.getResources=function(a){return this._fx_stack.getResources(a)};lb.prototype.onSerialize=function(a){a.stack=this._fx_stack.serialize()};lb.prototype.onConfigure=function(a){a.stack&&this._fx_stack.configure(a.stack)};LiteGraph.registerNodeType("texture/fxstack",lb);var ta=function(){this.addInput("in","Texture");
this.addInput("enabled","Boolean");this.addOutput("out","Texture");this.properties={enabled:!0,scale:0.5,position:[0,0],size:[1,1]}};ta.title="Histogram";ta.desc="Overlaps an histogram";ta.priority=2;ta.prototype.onExecute=function(){var a=this.getInputData(0);if(a){var b=this.getInputData(1);null!=b&&(this.properties.enabled=Boolean(b));if(this.properties.precision===LGraphTexture.PASS_THROUGH||!1===this.properties.enabled)this.setOutputData(0,a);else{if(!this._points_mesh){for(var b=new Float32Array(393216),
c=0;256>c;++c)for(var e=0;512>e;++e)b.set([e/512,c/256,0],1536*c+3*e);this._points_mesh=GL.Mesh.load({vertices:b})}this._texture||(this._texture=new GL.Texture(256,1,{type:gl.FLOAT,magFilter:gl.LINEAR,format:gl.RGB}));ta._shader||(ta._shader=new GL.Shader(ta.vertex_shader,ta.pixel_shader));var d=this._points_mesh,f=ta._shader,c=this.properties.scale;f.setUniform("u_texture",0);f.setUniform("u_factor",1/512);a.bind(0);gl.disable(gl.DEPTH_TEST);gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE);this._texture.drawTo(function(){gl.clearColor(0,
0,0,1);gl.clear(gl.COLOR_BUFFER_BIT);for(var a=0;3>a;++a)gl.colorMask(0==a,1==a,2==a,!0),f.setUniform("u_mask",ta.masks[a]),f.draw(d,gl.POINTS);gl.colorMask(!0,!0,!0,!0)});if(!this._line_mesh){b=new Float32Array(768);for(e=0;256>e;++e)b.set([e/256,0,0],3*e);this._line_mesh=GL.Mesh.load({vertices:b})}ta._line_shader||(ta._line_shader=new GL.Shader(ta.line_vertex_shader,ta.line_pixel_shader));d=this._line_mesh;f=ta._line_shader;f.setUniform("u_texture",0);f.setUniform("u_scale",c);this._texture.bind(0);
gl.disable(gl.BLEND);gl.viewport(this.properties.position[0]*gl.canvas.width,this.properties.position[1]*gl.canvas.height,this.properties.size[0]*gl.canvas.width,this.properties.size[1]*gl.canvas.height);for(a=0;3>a;++a)f.setUniform("u_mask",ta.masks[a]),f.draw(d,gl.LINE_STRIP);this.setOutputData(0,this._texture);gl.viewport(0,0,gl.canvas.width,gl.canvas.height)}}};ta.masks=[vec3.fromValues(1,0,0),vec3.fromValues(0,1,0),vec3.fromValues(0,0,1)];ta.vertex_shader="precision highp float;\n\t\n\tattribute vec3 a_vertex;\n\tuniform sampler2D u_texture;\n\tuniform vec3 u_mask;\n\t\n\tvoid main() {\n\t\tvec3 color = texture2D( u_texture, a_vertex.xy ).xyz * u_mask;\n\t\tfloat pos = min(1.0,length(color));\n\t\tgl_Position = vec4(pos*2.0-1.0,0.5,0.0,1.0);\n\t\tgl_PointSize = 1.0;\n\t}\n";
ta.pixel_shader="precision highp float;\n\tuniform float u_factor;\n\tvoid main() {\n\t\tgl_FragColor = vec4(u_factor);\n\t}\n";ta.line_vertex_shader="precision highp float;\n\t\n\tattribute vec3 a_vertex;\n\tuniform sampler2D u_texture;\n\tuniform vec3 u_mask;\n\tuniform float u_scale;\n\t\n\tvoid main() {\n\t\tvec3 color = texture2D( u_texture, a_vertex.xy ).xyz * u_mask;\n\t\tfloat pos = length(color);\n\t\tgl_Position = vec4(a_vertex.x*2.0-1.0, u_scale*pos*2.0-1.0,0.0,1.0);\n\t}\n";ta.line_pixel_shader=
"precision highp float;\n\tuniform vec3 u_mask;\n\tvoid main() {\n\t\tgl_FragColor = vec4(u_mask,1.0);\n\t}\n";LiteGraph.registerNodeType("texture/histogram",ta);var wa=function(){this.addInput("color","Texture");this.addInput("depth","Texture");this.addInput("camera","Camera");this.addOutput("out","Texture");this.properties={enabled:!0,intensity:1,ghosting_mitigation:!0,ghosting_threshold:0.4,freeze_camera:!1,low_quality:!1,precision:LGraphTexture.DEFAULT};this._inv_matrix=mat4.create();this._previous_viewprojection_matrix=
mat4.create();this._uniforms={u_color_texture:0,u_depth_texture:1,u_inv_vp:this._inv_matrix,u_intensity:1,u_camera_planes:null,u_viewprojection_matrix:null,u_previous_viewprojection_matrix:this._previous_viewprojection_matrix}};wa.widgets_info={precision:{widget:"combo",values:rc?LGraphTexture.MODE_VALUES:[]}};wa.title="Camera Motion Blur";wa.desc="A motion blur but only for camera movement";wa.prototype.onExecute=function(){var a=this.getInputData(0),b=this.getInputData(1),c=this.getInputData(2);
if(this.isOutputConnected(0)&&a&&b&&c){var e=this.getInputData(3);null!=e&&(this.properties.enabled=Boolean(e));if(this.properties.precision===LGraphTexture.PASS_THROUGH||!1===this.properties.enabled)this.setOutputData(0,a);else{var e=a.width,d=a.height,f=this.precision===LGraphTexture.LOW?gl.UNSIGNED_BYTE:gl.HIGH_PRECISION_FORMAT;this.precision===LGraphTexture.DEFAULT&&(f=a.type);this._tex&&this._tex.width==e&&this._tex.height==d&&this._tex.type==f||(this._tex=new GL.Texture(e,d,{type:f,format:gl.RGBA,
filter:gl.LINEAR}));this.properties.low_quality?wa._shader_low||(wa._shader_low=new GL.Shader(GL.Shader.SCREEN_VERTEX_SHADER,wa.pixel_shader,{SAMPLES:"4"}),wa._shader_no_ghosting_low=new GL.Shader(GL.Shader.SCREEN_VERTEX_SHADER,wa.pixel_shader,{GHOST_CORRECTION:"",SAMPLES:"4"})):wa._shader||(wa._shader=new GL.Shader(GL.Shader.SCREEN_VERTEX_SHADER,wa.pixel_shader),wa._shader_no_ghosting=new GL.Shader(GL.Shader.SCREEN_VERTEX_SHADER,wa.pixel_shader,{GHOST_CORRECTION:""}));var h=null,h=this.properties.low_quality?
this.properties.ghosting_mitigation?wa._shader_no_ghosting_low:wa._shader_low:this.properties.ghosting_mitigation?wa._shader_no_ghosting:wa._shader,e=this._inv_matrix,d=c._viewprojection_matrix,f=this._previous_viewprojection_matrix,k=this._uniforms;k.u_intensity=this.properties.intensity;k.u_viewprojection_matrix=c._viewprojection_matrix;k.u_camera_planes=c._uniforms.u_camera_planes;k.u_ghosting_threshold=this.properties.ghosting_threshold||0.4;for(var l=0,n=0;n<f.length;++n)l+=Math.abs(d[n]-f[n]);
mat4.invert(e,c._viewprojection_matrix);this._tex.drawTo(function(){gl.disable(gl.DEPTH_TEST);gl.disable(gl.CULL_FACE);gl.disable(gl.BLEND);a.bind(0);b.bind(1);var c=GL.Mesh.getScreenQuad();h.uniforms(k).draw(c)});this.properties.freeze_camera||f.set(c._viewprojection_matrix);this.setOutputData(0,this._tex)}}};wa.prototype.onGetInputs=function(){return[["enabled","boolean"]]};wa.pixel_shader="precision highp float;\n\t\t\n\t\tuniform sampler2D u_color_texture;\n\t\tuniform sampler2D u_depth_texture;\n\t\tvarying vec2 v_coord;\n\t\tuniform mat4 u_inv_vp;\n\t\tuniform mat4 u_viewprojection_matrix;\n\t\tuniform mat4 u_previous_viewprojection_matrix;\n\t\tuniform vec2 u_camera_planes;\n\t\tuniform float u_intensity;\n\t\tuniform float u_ghosting_threshold;\n\t\t#ifndef SAMPLES\n\t\t\t#define SAMPLES 16\n\t\t#endif\n\t\t\n\t\tvoid main() {\n\t\t\tvec2 uv = v_coord;\n\t\t\tfloat depth = texture2D(u_depth_texture, uv).x;\n\t\t\tfloat zNear = u_camera_planes.x;\n\t\t\tfloat zFar = u_camera_planes.y;\n\t\t\t//float z = (2.0 * zNear) / (zFar + zNear - depth * (zFar - zNear));\n\t\t\tdepth = depth * 2.0 - 1.0;\n\t\t\tfloat z = zNear * (depth + 1.0) / (zFar + zNear - depth * (zFar - zNear));\n\t\t\tvec4 screenpos = vec4( uv * 2.0 - vec2(1.0), depth, 1.0 );\n\t\t\tvec4 pos = u_inv_vp * screenpos;\n\t\t\tpos /= pos.w;\n\t\t\tvec4 old_screenpos = u_previous_viewprojection_matrix * pos;\n\t\t\told_screenpos /= old_screenpos.w;\n\t\t\tvec2 uv_final = old_screenpos.xy * 0.5 + vec2(0.5);\n\t\t\tvec2 uv_delta = (uv_final - uv);\n\t\t\tuv -= uv_delta * 0.5;\n\t\t\t//uv_delta *= 1.0 - z;\n\t\t\tuv_delta *= u_intensity / float(SAMPLES);\n\t\t\tvec4 color = vec4(0.0);\n\t\t\tfloat total = 0.0;\n\t\t\tfloat amount = 1.0;\n\t\t\tfor(int i = 0; i < SAMPLES; ++i)\n\t\t\t{\n\t\t\t\t#ifdef GHOST_CORRECTION\n\t\t\t\t\tfloat old_depth = texture2D(u_depth_texture, uv).x;\n\t\t\t\t\told_depth = old_depth * 2.0 - 1.0;\n\t\t\t\t\tfloat old_z = zNear * (old_depth + 1.0) / (zFar + zNear - old_depth * (zFar - zNear));\n\t\t\t\t\tif( abs(old_z - z) > u_ghosting_threshold )\n\t\t\t\t\t{\n\t\t\t\t\t\tuv += uv_delta;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t#endif\n\t\t\t\tcolor += texture2D( u_color_texture, uv );\n\t\t\t\tuv += uv_delta;\n\t\t\t\ttotal += amount;\n\t\t\t}\n\t\t\tgl_FragColor = color / total;\n\t\t\t//gl_FragColor = vec4( abs( old_screenpos.xy ), 1.0, 1.0 );\n\t\t\t//gl_FragColor = texture2D( u_color_texture, uv_final );\n\t\t\t//gl_FragColor = vec4( abs( pos.xyz * 0.001 ), 1.0 );\n\t\t\t//gl_FragColor = vec4( vec3( abs(old_z - z) ), 1.0);\n\t\t}\n\t\t";
LiteGraph.registerNodeType("texture/motionBlur",wa);var Ua=function(){this.addInput("color","Texture");this.addInput("depth","Texture");this.addInput("camera","Camera");this.addInput("light","Light,Component");this.addOutput("out","Texture");this.properties={enabled:!0,intensity:1,attenuation:2,precision:LGraphTexture.DEFAULT};this._inv_matrix=mat4.create();this._uniforms={u_color_texture:0,u_depth_texture:1,u_shadow_texture:2,u_noise_texture:3,u_intensity:1,u_camera_planes:null,u_inv_vp:this._inv_matrix,
u_rand:vec2.create()}};Ua.widgets_info={precision:{widget:"combo",values:LGraphTexture.MODE_VALUES}};Ua.title="Volumetric Light";Ua.desc="Adds fog with volumetric light";Ua.prototype.onExecute=function(){var a=this.getInputData(0),b=this.getInputData(1),c=this.getInputData(2),e=this.getInputData(3);if(this.isOutputConnected(0)){var g=this.getInputData(4);null!=g&&(this.properties.enabled=Boolean(g));var f=null;e&&e._shadowmap&&(f=e._shadowmap.texture);if(this.properties.precision!==LGraphTexture.PASS_THROUGH&&
!1!==this.properties.enabled&&b&&c&&e&&f){var g=b.width,h=b.height,k=this.precision===LGraphTexture.LOW?gl.UNSIGNED_BYTE:gl.HIGH_PRECISION_FORMAT;this.precision===LGraphTexture.DEFAULT&&(k=a?a.type:gl.UNSIGNED_BYTE);this._tex&&this._tex.width==g&&this._tex.height==h&&this._tex.type==k||(this._tex=new GL.Texture(g,h,{type:k,format:gl.RGBA,filter:gl.LINEAR}));Ua._shader_spot||(Ua._shader_spot=new GL.Shader(GL.Shader.SCREEN_VERTEX_SHADER,Ua.pixel_shader,{USE_SPOT:""}),Ua._shader_directional=new GL.Shader(GL.Shader.SCREEN_VERTEX_SHADER,
Ua.pixel_shader,{USE_DIRECTIONAL:""}));var l=null;switch(e.type){case d.Light.SPOT:l=Ua._shader_spot;break;case d.Light.DIRECTIONAL:l=Ua._shader_directional;break;case d.Light.OMNI:console.warn("volumetric light not supported for omni lights");this.properties.enabled=!1;return;default:return}g=this.properties.intensity;mat4.invert(this._inv_matrix,c._viewprojection_matrix);var n=this._uniforms;n.u_intensity=g;n.u_camera_planes=c._uniforms.u_camera_planes;n.u_shadow_params=e._uniforms.u_shadow_params;
n.u_attenuation=this.properties.attenuation;n.u_rand[1]=n.u_rand[0]=0;var p=e._uniforms;a||(a=d.Renderer._black_texture);var m=LGraphTexture.getNoiseTexture();this._tex.drawTo(function(){gl.disable(gl.DEPTH_TEST);gl.disable(gl.CULL_FACE);gl.disable(gl.BLEND);if(e.enabled){a.bind(0);b.bind(1);f.bind(2);m.bind(3);var c=GL.Mesh.getScreenQuad();l.uniforms(p);l.uniforms(n).draw(c)}else a.toViewport()});this.setOutputData(0,this._tex)}else this.setOutputData(0,a)}};Ua.prototype.onGetInputs=function(){return[["enabled",
"boolean"]]};Ua.pixel_shader="precision highp float;\n\t\t\n\t\tuniform sampler2D u_color_texture;\n\t\tuniform sampler2D u_depth_texture;\n\t\tuniform sampler2D u_shadow_texture;\n\t\tuniform sampler2D u_noise_texture;\n\t\tvarying vec2 v_coord;\n\t\tuniform mat4 u_inv_vp;\n\t\tuniform mat4 u_light_viewprojection_matrix;\n\t\tuniform vec2 u_camera_planes;\n\t\tuniform vec4 u_shadow_params;\n\t\tuniform vec4 u_light_info;\n\t\tuniform vec3 u_light_front;\n\t\tuniform vec3 u_light_color;\n\t\tuniform mat4 u_light_matrix;\n\t\tuniform float u_intensity;\n\t\tuniform float u_attenuation;\n\t\tuniform vec2 u_rand;\n\t\tconst float G_SCATTERING = 0.5;\n\t\tconst float PI = 3.14159265358979323846;\n\t\tfloat ComputeScattering(float lightDotView)\n\t\t{\n\t\t\tfloat result = 1.0 - G_SCATTERING * G_SCATTERING;\n\t\t\tresult /= (4.0 * PI * pow(1.0 + G_SCATTERING * G_SCATTERING - (2.0 * G_SCATTERING) * lightDotView, 1.5));\n\t\t\treturn result;\n\t\t}\n\t\t#define SAMPLES 64\n\t\t\n\t\tvoid main() {\n\t\t\tvec2 uv = v_coord;\n\t\t\tvec4 color = texture2D(u_color_texture, uv);\n\t\t\tfloat depth = texture2D(u_depth_texture, uv).x;\n\t\t\tfloat zNear = u_camera_planes.x;\n\t\t\tfloat zFar = u_camera_planes.y;\n\t\t\tdepth = depth * 2.0 - 1.0;\n\t\t\tfloat z = zNear * (depth + 1.0) / (zFar + zNear - depth * (zFar - zNear));\n\t\t\tvec4 screenpos = vec4( uv * 2.0 - vec2(1.0), depth, 1.0 );\n\t\t\tvec4 farpos = u_inv_vp * screenpos;\n\t\t\tfarpos /= farpos.w;\n\t\t\tscreenpos.z = 0.0;\n\t\t\tvec4 nearpos = u_inv_vp * screenpos;\n\t\t\tnearpos.xyz /= nearpos.w;\n\t\t\tvec3 rayDir = (farpos.xyz - nearpos.xyz) / float(SAMPLES);\n\t\t\tfloat weight = length(rayDir);\n\t\t\tvec4 current_pos = vec4( nearpos.xyz, 1.0 );\n\t\t\tcurrent_pos.xyz += rayDir * texture2D(u_noise_texture, uv * 2.0 + u_rand ).x;\n\t\t\tfloat brightness = 0.0;\n\t\t\tfloat bias = u_shadow_params.y;\n\t\t\tfloat accum = ComputeScattering( dot( normalize(rayDir), -u_light_front));\n\t\t\tfor(int i = 0; i < SAMPLES; ++i)\n\t\t\t{\n\t\t\t\tvec4 light_uv = u_light_matrix * current_pos;\n\t\t\t\tlight_uv.xy /= light_uv.w;\n\t\t\t\tlight_uv.xy = light_uv.xy * 0.5 + vec2(0.5);\n\t\t\t\tfloat shadow_depth = texture2D( u_shadow_texture, light_uv.xy ).x;\n\t\t\t\tif (((light_uv.z - bias) / light_uv.w * 0.5 + 0.5) < shadow_depth )\n\t\t\t\t\tbrightness += accum * weight;\n\t\t\t\tcurrent_pos.xyz += rayDir;\n\t\t\t}\n\t\t\t//color.xyz += u_intensity * u_light_color * brightness / float(SAMPLES);\n\t\t\tcolor.xyz = mix(color.xyz, u_light_color, clamp( pow(u_intensity * brightness / float(SAMPLES), u_attenuation),0.0,1.0));\n\t\t\tgl_FragColor = color;\n\t\t}\n\t\t";
LiteGraph.registerNodeType("texture/volumetric_light",Ua);if(LiteGraph.Nodes.LGraphTextureCanvas2D){var $a=function(){this.addInput("v");this.addOutput("out","Texture");this.properties={filename:"",width:512,height:512,clear:!0,precision:LGraphTexture.DEFAULT,use_html_canvas:!1};this._temp_texture=this._func=null;this.size=[180,30]};$a.title="Canvas2DFromScript";$a.desc="Executes Canvas2D script file inside a texture or the viewport.";$a.help="Set width and height to 0 to match viewport size.";$a.widgets_info=
{precision:{widget:"combo",values:LGraphTexture.MODE_VALUES},filename:{type:"script"},width:{type:"Number",precision:0,step:1},height:{type:"Number",precision:0,step:1}};$a.prototype.onPropertyChanged=function(a,b){var c=this;"filename"==a&&LiteGraph.allow_scripts&&(this._func=null,b&&d.ResourcesManager.load(b,function(a){c.compileCode(a.data);c._code_version=a._version||0}))};$a.prototype.onExecute=function(){if(this.isOutputConnected(0)){var a=d.ResourcesManager.getResource(this.properties.filename);
a&&a._version!=this._code_version&&(this.compileCode(a.data),this._code_version=a._version||0);(a=this._func)&&this.executeDraw(a)}};$a.prototype.getResources=function(a){this.properties.filename&&(a[this.properties.filename]=!0)};$a.prototype.compileCode=LiteGraph.Nodes.LGraphTextureCanvas2D.prototype.compileCode;$a.prototype.compileCode=LiteGraph.Nodes.LGraphTextureCanvas2D.prototype.compileCode;$a.prototype.executeDraw=LiteGraph.Nodes.LGraphTextureCanvas2D.prototype.executeDraw;LiteGraph.registerNodeType("texture/canvas2DfromScript",
$a)}}if("undefined"!=typeof LiteGraph){LiteGraph.CORNER_TOP_LEFT=0;LiteGraph.CORNER_TOP_RIGHT=1;LiteGraph.CORNER_BOTTOM_LEFT=2;LiteGraph.CORNER_BOTTOM_RIGHT=3;LiteGraph.CORNER_TOP_CENTER=4;LiteGraph.CORNER_BOTTOM_CENTER=5;var ub={type:"enum",values:{"top-left":LiteGraph.CORNER_TOP_LEFT,"top-right":LiteGraph.CORNER_TOP_RIGHT,"bottom-left":LiteGraph.CORNER_BOTTOM_LEFT,"bottom-right":LiteGraph.CORNER_BOTTOM_RIGHT,"top-center":LiteGraph.CORNER_TOP_CENTER,"bottom-center":LiteGraph.CORNER_BOTTOM_CENTER}},
vb=function(a,b,c){var e=a[0];a=a[1];switch(b){case LiteGraph.CORNER_TOP_RIGHT:e=gl.canvas.width-e;break;case LiteGraph.CORNER_BOTTOM_LEFT:a=gl.canvas.height-a;break;case LiteGraph.CORNER_BOTTOM_RIGHT:e=gl.canvas.width-e;a=gl.canvas.height-a;break;case LiteGraph.CORNER_TOP_CENTER:e=0.5*gl.canvas.width;break;case LiteGraph.CORNER_BOTTOM_CENTER:e=0.5*gl.canvas.width,a=gl.canvas.height-a}c[0]=e;c[1]=a},eb=function(){this.properties={enabled:!0,title:"",color:[0.1,0.1,0.1],opacity:0.7,titlecolor:[0,0,
0],position:[10,10],size:[300,200],rounding:8,corner:LiteGraph.CORNER_TOP_LEFT};this._pos=vec4.create();this._color=vec4.create();this._titlecolor=vec4.create()};eb.title="GUIPanel";eb.desc="renders a rectangle on webgl canvas";eb.priority=-1;eb["@corner"]=ub;eb["@color"]={type:"color"};eb["@titlecolor"]={type:"color"};eb["@opacity"]={widget:"slider",min:0,max:1};eb.prototype.onRenderGUI=function(){var a=window.gl;if(a&&this.properties.enabled){this._color.set(this.properties.color||[0.1,0.1,0.1]);
this._color[3]=this.properties.opacity;a.fillColor=this._color;vb(this.properties.position,this.properties.corner,this._pos);this._pos[2]=this.properties.size[0];this._pos[3]=this.properties.size[1];gl.disable(gl.DEPTH_TEST);gl.enable(gl.BLEND);gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA);var b=Math.min(15,this.properties.rounding);0<b?(a.beginPath(),a.roundRect(this._pos[0],this._pos[1],this.properties.size[0],this.properties.size[1],b,b),a.fill()):a.fillRect(this._pos[0],this._pos[1],this.properties.size[0],
this.properties.size[1]);this.properties.title&&(this._titlecolor.set(this.properties.titlecolor||[0.3,0.3,0.3]),this._titlecolor[3]=this.properties.opacity,a.fillColor=this._titlecolor,0<b?(a.beginPath(),a.roundRect(this._pos[0],this._pos[1],this.properties.size[0],30,b,0),a.fill()):a.fillRect(this._pos[0],this._pos[1],this.properties.size[0],30),a.fillColor=[0.8,0.8,0.8,this.properties.opacity],a.font="20px Arial",a.fillText(this.properties.title,10+this._pos[0],24+this._pos[1]))}};LiteGraph.registerNodeType("gui/panel",
eb);var mb=function(){this.addInput("text");this.properties={enabled:!0,text:"",font:"",color:[1,1,1,1],precision:3,position:[20,20],corner:LiteGraph.CORNER_TOP_LEFT};this._pos=vec2.create();this._text=""};mb.title="GUIText";mb.desc="renders text on webgl canvas";mb["@corner"]=ub;mb["@color"]={type:"color"};mb.prototype.onGetInputs=function(){return[["enabled","boolean"]]};mb.prototype.onExecute=function(){var a=this.getInputData(0);null!=a&&(this._text=a.constructor===Number?a.toFixed(this.properties.precision):
String(a))};mb.prototype.onRenderGUI=function(){var a=window.gl;if(a&&!1!==this.getInputOrProperty("enabled")){var b=(this.properties.text||"")+this._text;""!=b&&(a.font=this.properties.font||"20px Arial",a.textAlign="left",a.fillColor=this.properties.color||[1,1,1,1],vb(this.properties.position,this.properties.corner,this._pos),gl.disable(gl.DEPTH_TEST),gl.enable(gl.BLEND),gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA),a.fillText(b,this._pos[0],this._pos[1]))}};LiteGraph.registerNodeType("gui/text",
mb);var wb=function(){this.addInput("","image,canvas,texture");this.properties={enabled:!0,opacity:1,keep_aspect:!0,flipX:!1,flipY:!1,force_update:!1,position:[20,20],size:[300,200],corner:LiteGraph.CORNER_TOP_LEFT};this._pos=vec2.create()};wb.title="GUIImage";wb.desc="renders an image on webgl canvas";wb["@corner"]=ub;wb["@opacity"]={widget:"slider",min:0,max:1};wb.prototype.onGetInputs=function(){return[["enabled","boolean"]]};wb.prototype.onRenderGUI=function(){var a=window.gl;if(a){var b=this.getInputData(0);
if(!1!==this.getInputOrProperty("enabled")&&b){this.properties.force_update&&(b.mustUpdate=!0);vb(this.properties.position,this.properties.corner,this._pos);gl.disable(gl.DEPTH_TEST);gl.enable(gl.BLEND);gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA);var c=a.globalAlpha;a.globalAlpha*=this.properties.opacity;var e=this._pos[0],d=this._pos[1],f=this.properties.size[0],h=this.properties.size[1];this.properties.keep_aspect&&(h=this.properties.size[0]/b.width*b.height);this.properties.flipX&&(e+=f,
f*=-1);this.properties.flipY&&(d+=h,h*=-1);a.drawImage(b,e,d,f,h);a.globalAlpha=c}}};LiteGraph.registerNodeType("gui/image",wb);var xb=function(){this.addOutput("v");this.properties={enabled:!0,text:"",min:0,max:1,value:0,position:[20,20],size:[200,40],corner:LiteGraph.CORNER_TOP_LEFT};this._area=vec4.create()};xb.title="GUISlider";xb.desc="Renders a slider on the main canvas";xb["@corner"]=ub;xb.prototype.onRenderGUI=function(){this.properties.enabled&&(vb(this.properties.position,this.properties.corner,
this._area),this._area[2]=this.properties.size[0],this._area[3]=this.properties.size[1],this.properties.value=d.GUI.HorizontalSlider(this._area,Number(this.properties.value),Number(this.properties.min),Number(this.properties.max),!0),this.properties.text&&(gl.textAlign="right",gl.fillStyle="#AAA",gl.fillText(this.properties.text,this._area[0]-20,this._area[1]+0.75*this._area[3]),gl.textAlign="left"))};xb.prototype.onExecute=function(){this.inputs&&this.inputs.length&&(this.properties.enabled=this.getInputOrProperty("enabled"));
this.setOutputData(0,this.properties.value)};xb.prototype.onGetInputs=function(){return[["enabled","boolean"]]};LiteGraph.registerNodeType("gui/slider",xb);var Cb=function(){this.addOutput("v");this.properties={enabled:!0,value:!0,text:"toggle",position:[20,20],size:[140,40],corner:LiteGraph.CORNER_TOP_LEFT};this._area=vec4.create()};Cb.title="GUIToggle";Cb.desc="Renders a toggle widget on the main canvas";Cb["@corner"]=ub;Cb.prototype.onRenderGUI=function(){this.properties.enabled&&(vb(this.properties.position,
this.properties.corner,this._area),this._area[2]=this.properties.size[0],this._area[3]=this.properties.size[1],this.properties.value=d.GUI.Toggle(this._area,this.properties.value,this.properties.text))};Cb.prototype.onExecute=function(){this.setOutputData(0,this.properties.value)};LiteGraph.registerNodeType("gui/toggle",Cb);var yb=function(){this.addOutput("on",LiteGraph.EVENT);this.addOutput("was_pressed");this.properties={enabled:!0,text:"clickme",position:[20,20],size:[140,40],corner:LiteGraph.CORNER_TOP_LEFT};
this._area=vec4.create();this._was_pressed=!1};yb.title="GUIButton";yb.desc="Renders a toggle widget on the main canvas";yb["@corner"]=ub;yb.prototype.onRenderGUI=function(){this.properties.enabled&&(vb(this.properties.position,this.properties.corner,this._area),this._area[2]=this.properties.size[0],this._area[3]=this.properties.size[1],this._was_pressed=d.GUI.Button(this._area,this.properties.text))};yb.prototype.onExecute=function(){var a=this.getInputDataByName("enabled");if(!1===a||!0===a)this.properties.enabled=
a;this._was_pressed&&this.trigger("on");this.setOutputData(1,this._was_pressed);this._was_pressed=!1};yb.prototype.onGetInputs=function(){return[["enabled","boolean"]]};LiteGraph.registerNodeType("gui/button",yb);var fb=function(){this.addOutput("v");this.addOutput("i");this.properties={enabled:!0,selected:0,values:"option1;option2;option3",one_line:!1,position:[20,20],size:[180,100],corner:LiteGraph.CORNER_TOP_LEFT};this._area=vec4.create();this._values=this.properties.values.split(";");var a=this;
this.widget=this.addWidget("text","Options",this.properties.values,function(b){a.properties.values=b;a.onPropertyChanged("values",b)});this.size=[240,70]};fb.title="GUIMultipleChoice";fb.desc="Renders a multiple choice widget on the main canvas";fb["@corner"]=ub;fb.prototype.onPropertyChanged=function(a,b){"values"==a&&(this._values=b.split(";"),this.widget.value=b)};fb.prototype.onAction=function(a,b){"prev"==a?this.properties.selected-=1:"next"==a&&(this.properties.selected+=1);this.properties.selected%=
this._values.length;0>this.properties.selected&&(this.properties.selected+=this._values.length)};fb.prototype.onRenderGUI=function(){if(this._values.length&&this.properties.enabled){var a=this.properties.selected=Math.floor(this.properties.selected);vb(this.properties.position,this.properties.corner,this._area);var b=gl;if(this.properties.one_line){var c=this.properties.position,e=this.properties.size,g=e[1];this._area[2]=2*g;this._area[3]=e[1];d.GUI.ClickArea(this._area)&&(a-=1);this._area[0]+=e[0]-
2*g;d.GUI.ClickArea(this._area)&&(a+=1);a%=this._values.length;0>a&&(a+=this._values.length);b.fillStyle="black";b.strokeStyle="#AAA";b.lineWidth=2;b.beginPath();b.roundRect(c[0],c[1],e[0],e[1],0.5*g);b.fill();b.stroke();b.fillStyle="white";b.beginPath();var f=0.25*g;b.moveTo(c[0]+f,c[1]+0.5*g);b.lineTo(c[0]+0.5*g+2*f,c[1]+f);b.lineTo(c[0]+0.5*g+2*f,c[1]+g-f);b.fill();b.beginPath();b.moveTo(c[0]+e[0]-f,c[1]+0.5*g);b.lineTo(c[0]+e[0]-0.5*g-2*f,c[1]+f);b.lineTo(c[0]+e[0]-0.5*g-2*f,c[1]+g-f);b.fill();
b.fillStyle="#AAA";b.textAlign="center";b.font=(0.75*g).toFixed(0)+"px "+d.GUI.GUIStyle.font;b.fillText(String(this._values[a]),c[0]+0.5*e[0],c[1]+0.75*e[1])}else for(this._area[2]=this.properties.size[0],this._area[3]=this.properties.size[1]/this._values.length,b=this._area[1],c=0;c<this._values.length;++c)this._area[1]=b+c*this._area[3],d.GUI.Toggle(this._area,c==a,this._values[c],null,!0)&&(a=c);this.properties.selected=a;(a=d.Input.current_click)&&d.Input.isEventInRect(a,this._area,d.GUI._offset)&&
(d.Input.current_click=!1)}};fb.prototype.onGetInputs=function(){return[["enabled","boolean"],["options","array"],["next",LiteGraph.ACTION],["prev",LiteGraph.ACTION]]};fb.prototype.onExecute=function(){if(this.inputs)for(var a=0;a<this.inputs.length;++a){var b=this.inputs[a],c=this.getInputData(a);"enabled"==b.name?this.properties.enabled=Boolean(c):"options"==b.name&&c&&(this._values=c,this.properties.values=c.join(";"),this.widget.value=this.properties.values)}this.setOutputData(0,this._values[this.properties.selected]);
this.setOutputData(1,this.properties.selected)};LiteGraph.registerNodeType("gui/multiple_choice",fb);var fa=function(){this.addInput("x","number");this.addInput("y","number");this.addOutput("[]","array");this.addOutput("obj","object");this.addProperty("circular",!1);this.points=[];this.weights=[];this.weights_obj={};this.current_pos=new Float32Array([0.5,0.5]);this.size=[200,200];this.dragging=!1;this.show_names=!0;this.circle_center=[0,0];this.circle_radius=1;this.margin=20;this._values_changed=
!0;this._visualize_weights=!1;this._version=0;this._selected_point=null};LiteGraph.LGraphMap2D=fa;fa.title="Map2D";fa.colors=[[255,0,0],[0,255,0],[0,0,255],[0,128,128,0],[128,0,128],[128,128,0],[255,128,0],[255,0,128],[0,128,255],[128,0,255]];fa.grid_size=64;fa.prototype.onExecute=function(){var a=this.current_pos;a[0]=this.getInputData(0)||a[0];a[1]=this.getInputData(1)||a[1];this.computeWeights(a);this.setOutputData(0,this.weights);this.setOutputData(1,this.weights_obj)};fa.prototype.computeWeights=
function(a){if(this.points.length){var b=this._precomputed_weights;if(!b||this._values_changed)b=this.precomputeWeights();var c=vec2.create(),e=this.properties.circular,d=this.weights;d.length=this.points.length;for(var f=fa.grid_size,h=0;h<d.length;++h)d[h]=0;for(var k=0,h=0;h<f;++h)for(var l=0;l<f;++l){c[0]=l/f;c[1]=h/f;e&&(c[0]=2*c[0]-1,c[1]=2*c[1]-1);var n=2*l+h*f*2,p=b[n];vec2.distance(c,a)<b[n+1]+0.001&&(d[p]+=1,k++)}for(h=0;h<d.length;++h)d[h]/=k,this.weights_obj[this.points[h].name]=d[h];
return d}};fa.prototype.onMouseDown=function(a,b){return this.flags.collapsed||0>b[1]||b[0]<this.margin||b[0]>this.size[0]-this.margin||b[1]<this.margin?!1:b[1]>this.size[1]-this.margin?(this._visualize_weights=!this._visualize_weights,!0):this.dragging=!0};fa.prototype.onMouseUp=function(a,b){this.dragging=!1};fa.prototype.onMouseMove=function(a,b){if(this.dragging&&!this.flags.collapsed){var c=this.margin,e=[0,0],d=this.current_pos;d[0]=Math.clamp((b[0]-c)/(this.size[0]-2*c),0,1);d[1]=Math.clamp((b[1]-
c)/(this.size[1]-2*c),0,1);this.properties.circular&&(d[0]=2*d[0]-1,d[1]=2*d[1]-1,1<vec2.distance(d,e)&&vec2.normalize(d,d));return!0}};fa.prototype.onDrawBackground=function(a){if(!this.flags.collapsed){var b=this.current_pos,c=this.margin,e=this.properties.circular,d=this.show_names;a.fillStyle="black";a.strokeStyle="#BBB";e?(this.circle_center[0]=0.5*this.size[0],this.circle_center[1]=0.5*this.size[1],this.circle_radius=0.5*this.size[1]-c,a.lineWidth=2,a.beginPath(),a.arc(this.circle_center[0],
this.circle_center[1],this.circle_radius,0,2*Math.PI),a.fill(),a.stroke(),a.lineWidth=1,a.beginPath(),a.moveTo(this.circle_center[0]+0.5,this.circle_center[1]-this.circle_radius),a.lineTo(this.circle_center[0]+0.5,this.circle_center[1]+this.circle_radius),a.moveTo(this.circle_center[0]-this.circle_radius,this.circle_center[1]),a.lineTo(this.circle_center[0]+this.circle_radius,this.circle_center[1]),a.stroke()):(a.fillRect(c,c,this.size[0]-2*c,this.size[1]-2*c),a.strokeRect(c,c,this.size[0]-2*c,this.size[1]-
2*c));var f=this.precomputeWeightsToImage(b);f&&(a.globalAlpha=0.5,a.imageSmoothingEnabled=!1,e?(a.save(),a.beginPath(),a.arc(this.circle_center[0],this.circle_center[1],this.circle_radius,0,2*Math.PI),a.clip(),a.drawImage(f,this.circle_center[0]-this.circle_radius,this.circle_center[1]-this.circle_radius,2*this.circle_radius,2*this.circle_radius),a.restore()):a.drawImage(f,c,c,this.size[0]-2*c,this.size[1]-2*c),a.imageSmoothingEnabled=!0,a.globalAlpha=1);for(f=0;f<this.points.length;++f){var h=this.points[f],
k=h.pos[0],l=h.pos[1];e&&(k=0.5*k+0.5,l=0.5*l+0.5);k=k*(this.size[0]-2*c)+c;l=l*(this.size[1]-2*c)+c;k=Math.clamp(k,c,this.size[0]-c);l=Math.clamp(l,c,this.size[1]-c);a.fillStyle=h==this._selected_point?"#9DF":"#789";a.beginPath();a.arc(k,l,3,0,2*Math.PI);a.fill();d&&a.fillText(h.name,k+5,l+5)}a.fillStyle="white";a.beginPath();k=b[0];l=b[1];e&&(k=0.5*k+0.5,l=0.5*l+0.5);k=k*(this.size[0]-2*c)+c;l=l*(this.size[1]-2*c)+c;k=Math.clamp(k,c,this.size[0]-c);l=Math.clamp(l,c,this.size[1]-c);a.arc(k,l,5,0,
2*Math.PI);a.fill();a.save();a.fillStyle="black";a.fillRect(c,this.size[1]-c+2,this.size[0]-2*c,c-4);a.strokeStyle="white";a.strokeRect(c,this.size[1]-c+2,this.size[0]-2*c,c-4);a.textAlign="center";a.fillStyle="white";a.fillText("Visualize Weights",0.5*this.size[0],this.size[1]-0.3*c);a.textAlign="left";if(this.weights.length&&this._visualize_weights)for(k=this.size[0]+5,l=16,f=0;f<this.weights.length;++f)b=fa.colors[f%fa.colors.length],a.fillStyle="black",a.fillRect(k,l+5*f,100,4),a.fillStyle="rgb("+
(255*b[0]|0)+","+(255*b[1]|0)+","+(255*b[2]|0)+")",a.fillRect(k,l+5*f,100*this.weights[f],4);a.restore()}};fa.prototype.addPoint=function(a,b){this.findPoint(a)?console.warn("there is already a point with that name"):(b||(b=[this.current_pos[0],this.current_pos[1]]),b[0]=Math.clamp(b[0],-1,1),b[1]=Math.clamp(b[1],-1,1),this.points.push({name:a,pos:b}),this._values_changed=!0,this.setDirtyCanvas(!0))};fa.prototype.removePoint=function(a){for(var b=0;b<this.points.length;++b)if(this.points[b].name==
a){this.points.splice(b,1);this._values_changed=!0;break}};fa.prototype.findPoint=function(a){for(var b=0;b<this.points.length;++b)if(this.points[b].name==a)return this.points[b];return null};fa.prototype.precomputeWeights=function(){var a=this.points,b=a.length,c=vec2.create(),e=this.properties.circular;this._values_changed=!1;this._version++;var d=fa.grid_size,f=2*d*d;this._precomputed_weights&&this._precomputed_weights.length==f||(this._precomputed_weights=new Float32Array(f));f=this._precomputed_weights;
this._precomputed_weights_gridsize=d;for(var h=0;h<d;++h)for(var k=0;k<d;++k){for(var l=-1,n=1E5,p=0;p<b;++p){c[0]=k/d;c[1]=h/d;e&&(c[0]=2*c[0]-1,c[1]=2*c[1]-1);var m=vec2.distance(c,a[p].pos);m>n||(l=p,n=m)}f[2*k+2*h*d]=l;f[2*k+2*h*d+1]=n}return f};fa.prototype.precomputeWeightsToImage=function(a){if(!this.points.length)return null;var b=this._precomputed_weights;if(!b||this._values_changed||this._precomputed_weights_gridsize!=fa.grid_size)b=this.precomputeWeights();var c=this._canvas,e=fa.grid_size;
c||(c=this._canvas=document.createElement("canvas"));c.width=c.height=e;var d=c.getContext("2d"),f=vec2.create(),h=this.properties.circular,k=this.weights;k.length=this.points.length;for(var l=0;l<k.length;++l)k[l]=0;for(var n=0,p=d.getImageData(0,0,e,e),l=0;l<e;++l)for(var m=0;m<e;++m){f[0]=m/e;f[1]=l/e;h&&(f[0]=2*f[0]-1,f[1]=2*f[1]-1);var q=4*m+l*e*4,s=2*m+l*e*2,t=b[s],u=fa.colors[t%fa.colors.length];if(s=vec2.distance(f,a)<b[s+1]+0.001)k[t]+=1,n++;p.data[q]=u[0]+(s?128:0);p.data[q+1]=u[1]+(s?128:
0);p.data[q+2]=u[2]+(s?128:0);p.data[q+3]=255}for(l=0;l<k.length;++l)k[l]/=n;d.putImageData(p,0,0);return c};fa.prototype.clear=function(){this.points.length=0;this._selected_point=this._canvas=this._precomputed_weights=null;this.setDirtyCanvas(!0)};fa.prototype.getExtraMenuOptions=function(){return[{content:"Clear Points",callback:this.clear.bind(this)}]};fa.prototype.onInspect=function(a){var b=this;!this._selected_point&&this.points.length&&(this._selected_point=this.points[0]);a.addTitle("Points");
a.widgets_per_row=4;for(var c=0;c<this.points.length;++c){var e=this.points[c];a.addString(null,e.name,{point:e,width:"40%",callback:function(a){this.options.point.name=a;b.setDirtyCanvas(!0)}});a.addNumber(null,e.pos[0],{point:e,width:"20%",min:-1,max:1,step:0.01,callback:function(a){this.options.point.pos[0]=Math.clamp(a,-1,1);b._values_changed=!0}});a.addNumber(null,e.pos[1],{point:e,width:"20%",min:-1,max:1,step:0.01,callback:function(a){this.options.point.pos[1]=Math.clamp(a,-1,1);b._values_changed=
!0}});a.addButton(null,"o",{point:e,width:"10%",callback:function(){this.options.point.pos[0]=b.current_pos[0];this.options.point.pos[1]=b.current_pos[1];b._values_changed=!0}});a.addButton(null,"X",{point:e,width:"10%",callback:function(){LiteGUI.confirm("Are you sure? Removing one point could mess up the whole weights order",function(c){c&&(b.removePoint(this.point.name),a.refresh())}.bind(this.options))}})}a.widgets_per_row=1;var d="";a.widgets_per_row=2;a.addString("New Point","",{width:"75%",
callback:function(a){d=a}});a.addButton(null,"Create",{width:"25%",callback:function(c){d&&b.addPoint(d);a.refresh()}});a.widgets_per_row=1;a.addSeparator()};fa.prototype.onSerialize=function(a){a.current_pos=this.current_pos;for(var b=0;b<this.points.length;++b)delete this.points[b]._dist;a.points=this.points};fa.prototype.onConfigure=function(a){a.current_pos&&(this.current_pos=a.current_pos);a.points&&(this.points=a.points)};LiteGraph.registerNodeType("math/map2D",fa);var Va=function(){this.addInput("in",
"array");this.addOutput("out","object");this.points=[];this.current_weights={};this.properties={enabled:!0};var a=this;this.combo=this.addWidget("combo","Point","",function(b){a._selected_point=a.findPoint(b)},{values:[]});this.import_button=this.addWidget("button","import weights","",function(){a.importWeights(!0,!0)});this.size=[170,80];this._selected_point=null};Va.title="Remap Weights";Va.prototype.onExecute=function(){if(this.getInputOrProperty("enabled")){var a=this.getInputData(0);if(this.inputs)for(var b=
1;b<this.inputs.length;++b)if("selected"==this.inputs[b].name){var c=this.getInputData(b);c&&(this._selected_point=this.findPoint(c),this.combo.value=c)}for(b in this.current_weights)this.current_weights[b]=0;c=!1;if(a)for(b=0;b<a.length;++b){var e=this.points[b];if(e){var d=a[b],f;for(f in e.weights)this.current_weights[f]+=(e.weights[f]||0)*d}else c=!0}this.setOutputData(0,this.current_weights);if(this.outputs)for(b=1;b<this.outputs.length;++b)(a=this.outputs[b])&&("selected"==a.name?this.setOutputData(b,
this._selected_point?this._selected_point.name:""):this.setOutputData(b,this.current_weights[a.name]));c&&this.importPoints()}};Va.prototype.onAction=function(a,b){"import"==a&&this.importWeights(!0)};Va.prototype.addPoint=function(a,b){if(b){var c={},e;for(e in b)c[e]=b[e];this.points.push({name:a,weights:c})}else console.warn("no weights passed to add point")};Va.prototype.importPoints=function(){var a=this.getInputNode(0);if(a&&a.points&&a.points.length){this.points.length=a.points.length;for(var b=
0;b<this.points.length;++b)this.points[b]={name:a.points[b].name,weights:{}};(this._selected_point=this.points[0])?(this.combo.value=this._selected_point.name,this.combo.options.values=this.points.map(function(a){return a.name})):(this.combo.value="",this.combo.options.values=[""])}};Va.prototype.importWeights=function(a,b){this.graph&&b&&this.graph.runStep(1,!1,this.order);var c=this.getInputDataByName("name_weights");if(c)for(var e in c)this.current_weights[e]=c[e];else{c=this.getOutputNodes(0);
if(!c||0==c.length)return;for(var d=0;d<c.length;++d){var f=c[d];if(f.getComponent&&(f=f.getComponent())){var h=f.name_weights,h=f.name_weights;for(e in h)this.current_weights[e]=h[e]}}}this.setDirtyCanvas(!0);if(a&&this._selected_point)for(d in this._selected_point.weights={},this.current_weights)this._selected_point.weights[d]=this.current_weights[d]};Va.prototype.findPoint=function(a){for(var b=0;b<this.points.length;++b)if(this.points[b].name==a)return this.points[b];return null};Va.prototype.assignCurrentWeightsToPoint=
function(a){for(var b in this.current_weights)a.weights[b]=this.current_weights[b]};Va.prototype.onSerialize=function(a){a.current_weights=this.current_weights;a.points=this.points;a.enabled=this.enabled};Va.prototype.onConfigure=function(a){void 0!==a.enabled&&(this.properties.enabled=a.enabled);a.current_weights&&(this.current_weights=a.current_weights);if(a.points){this.points=a.points;for(a=0;a<this.points.length;++a){var b=this.points[a];b.weights&&b.weights.constructor!==Object&&(b.weights=
{})}this.combo.options.values=this.points.map(function(a){return a.name});this.combo.value=this.combo.options.values[0]||""}};Va.prototype.onInspect=function(a){var b=this;a.addButton(null,"Import points from input",{callback:function(){b.importPoints();a.refresh()}});a.addButton(null,"Import weights from output",{callback:function(){b.importWeights(null,!0);a.refresh()}});a.addSeparator();a.addTitle("Points");for(var c=[],e=0;e<this.points.length;++e)c.push(this.points[e].name);!this._selected_point&&
this.points.length&&(this._selected_point=this.points[0]);a.addCombo("Points",this._selected_point?this._selected_point.name:"",{values:c,callback:function(c){b._selected_point=b.findPoint(c);b.combo.value=c;if(b._selected_point)for(var e in b._selected_point.weights)b.current_weights[e]=b._selected_point.weights[e];b.setDirtyCanvas(!0);a.refresh()}});a.addButton(null,"current weights to point",{callback:function(){b._selected_point&&(b.assignCurrentWeightsToPoint(b._selected_point),a.refresh())}});
a.addSeparator();a.addTitle("Weights");for(e in this.current_weights)a.addNumber(e,this.current_weights[e],{name_width:"80%",index:e,callback:function(a){b.current_weights[this.options.index]=a}});a.addStringButton("Add Weight","",{button:"+",callback_button:function(c){b.current_weights[c]=0;a.refresh()}});a.addSeparator()};Va.prototype.onGetOutputs=function(){var a=[["selected","string"]],b;for(b in this.current_weights)a.push([b,"number"]);return a};Va.prototype.onGetInputs=function(){return[["enabled",
"boolean"],["import",LiteGraph.ACTION],["selected","string"],["name_weights","object"]]};LiteGraph.registerNodeType("math/remap_weights",Va);var fc=function(){this.addInput("camera","component,camera");this.addInput("pos3D","vec3");this.addOutput("screen_pos","vec4");this.properties={clamp_to_viewport:!1,reverse_y:!0};this._screen_pos=vec4.create();this.size=[160,50]};fc.title="Camera Project";fc.prototype.onExecute=function(){var a=this.getInputData(0),b=this.getInputData(1);a&&a.constructor==d.Camera&&
b&&(a.project(b,null,this._screen_pos,this.properties.reverse_y),b=vec3.distance(a.eye,b),this._screen_pos[3]=Math.sin(a.fov*DEG2RAD)/b*100,this.properties.clamp_to_viewport&&(this._screen_pos[0]=Math.clamp(this._screen_pos[0],0,gl.canvas.width),this._screen_pos[1]=Math.clamp(this._screen_pos[1],0,gl.canvas.height)),this.setOutputData(0,this._screen_pos))};LiteGraph.registerNodeType("math3d/camera_project",fc);var Sb=function(){this.addOutput("","boolean");this.addOutput("",LiteGraph.EVENT);this.properties=
{key:"SPACE"};var a=this;this.widgets_up=!0;this.addWidget("text","Key",this.properties.key,function(b){b&&(a.properties.key=b)})};Sb.title="Key";Sb.prototype.getTitle=function(){return this.flags.collapsed?"Key: "+this.properties.key:this.title};Sb.prototype.onExecute=function(){var a=d.Input.wasKeyPressed(this.properties.key);this.boxcolor=a?"#fff":"#000";this.setOutputData(0,a);a&&this.triggerSlot(1,this.properties.key)};LiteGraph.registerNodeType("input/key",Sb)}if("undefined"!=typeof LiteGraph){var nb=
LiteGraph.getInputLinkID=function(a,b){var c=a.getInputInfo(b);return c&&-1!=c.link?(c=a.graph.links[c.link])?"LINK_"+c.origin_id+"_"+c.origin_slot:null:null},Za=LiteGraph.getOutputLinkID=function(a,b,c){var e=a.getOutputInfo(b);return e&&e.links&&e.links.length||c?"LINK_"+a.id+"_"+b:null};LiteGraph.registerShaderNode=function(a,b){b.filter="shader";b.color="#333";b.bgcolor="#333";b.title_text_color="#AAA";LiteGraph.registerNodeType("shader/"+a,b)};var gc={number:"float",color:"vec3",color4:"vec4"};
LiteGraph.generatePreviewShader=function(a){for(var b=a.graph.getAncestors(a),c={uniforms:[]},e="",b=this._graph._nodes_in_order,d=0;d<b.length;++d)a=b[d],a.onGetCode&&(e+=a.onGetCode("glsl",c));for(d=0;d<c.uniforms.length;++d);};var ob=function(a,b){var c=a,e;e='this.addOutput("v","'+a+'");\n'+("this.properties = { value: "+JSON.stringify(b)+', uniform:""};\n');e=new Function(e);a=gc[a]||a;var d;d='if( lang != "glsl" ) return "";\nvar output = LiteGraph.getOutputLinkID( this, 0, true );\n'+('if(this.properties.uniform)\n \t{ context.uniforms.push({ name: this.properties.uniform, link_name: output, type: "'+
a+'", value: this.properties.value });\n return "";\t}');d+='return "\\t '+a+' "+output+" = '+a+'("+String(this.properties.value)+");\\n";\n';e.prototype.onGetCode=new Function("lang","context",d);e.prototype.onExecute=new Function('this.setOutputDataType( 0, "'+a+'" );\n');LiteGraph.registerShaderNode(c.toLowerCase(),e);e.title=c;e.desc="Shader constant "+c;e.prototype.getTitle=function(){return this.flags.collapsed?String(this.properties.value):this.title};e.prototype.onDrawBackground=function(){5>
this.properties.value.length&&(this.outputs[0].label=String(this.properties.value))};return e};ob("float",1);ob("vec2",[0,0]);ob("vec3",[0,0,0]);ob("color",[1,1,1]);ob("vec4",[0,0,0,0]);ob("color4",[1,1,1,1]);ob("mat3",[1,0,0,0,1,0,0,0,1]);ob("mat4",[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);var Ma=function(a,b,c,e,d){if(10<=b.length)throw"cannot be used with more than 10 vars, regexp not supporting it";for(var f='this.addOutput("v","'+c+'");\n',h=0;h<b.length;++h)f+='this.addInput("'+String.fromCharCode(65+
h)+'","'+b[h]+'");\n';var f=new Function(f),k;k='\tif( lang != "glsl" ) return "";\n\tvar code = "";\n';for(h=0;h<b.length;++h){var l=gc[b[h]]||b[h];k+="var input_"+h+" = LiteGraph.getInputLinkID( this, "+h+" );\n";k+="if(input_"+h+" == null) input_"+h+' = "'+l+'(1.0)";\n';e=e.replace(RegExp("@"+h,"gi"),'" + input_'+h+' + "')}k=k+"\tvar output = LiteGraph.getOutputLinkID(this, 0, true);\n"+('\treturn "\\t  '+(gc[c]||c)+' "+output+" = '+e+';\\n";\n');f.prototype.onGetCode=new Function("lang",k);d&&
(f.prototype.getTitle=new Function(' return "'+d+'";'));f.title=a;f.filter="shader";LiteGraph.registerShaderNode(a.toLowerCase(),f);return f};Ma("Float->Vec2",["float"],"vec2","vec2(@0)","vec2");Ma("Float->Vec3",["float"],"vec3","vec3(@0)","vec3");Ma("Add Float",["float","float"],"float","@0 + @1","A+B");Ma("Add Vec3",["vec3","vec3"],"vec3","@0 + @1","A+B");Ma("Sub Vec3",["vec3","vec3"],"vec3","@0 - @1","A-B");Ma("Scale Vec3",["vec3","float"],"vec3","@0 * @1","A*B");Ma("Sub Float",["float","float"],
"float","@0 - @1","A-B");Ma("Normalize Vec2",["vec2"],"vec2","normalize(@0)","normalize");Ma("Normalize Vec3",["vec3"],"vec3","normalize(@0)","normalize");Ma("Exp Float",["float"],"float","exp(@0)","exp");Ma("Pow Float",["float","float"],"float","pow(@0,@1)","pow");Ma("Pow Vec3",["vec3","float"],"vec3","pow(@0,@1)","pow");Ma("Float->Vec3",["float"],"vec3","vec3(@0)","vec3");Ma("Dot",["vec3","vec3"],"float","dot(@0,@1)","dot");Ma("Cross",["vec3","vec3"],"vec3","cross(@0,@1)","cross");Ma("Abs Vec3",
["vec3"],"vec3","abs(@0)","abs");Ma("Abs Float",["float"],"float","abs(@0)","abs");var Ib=function(){this.addInput("Albedo","vec3");this.addInput("Emission","vec3");this.addInput("Normal","vec3");this.addInput("Specular","float");this.addInput("Gloss","float");this.addInput("Reflectivity","float");this.addInput("Alpha","float");this.size=[90,110];this.properties={}};Ib.title="Surface";Ib.desc="Surface properties";Ib.prototype.onExecute=function(){};Ib.prototype.onGetCode=function(a){if("glsl"!=a)return"";
a="\n";var b=nb(this,0);b&&(a+="\t o.Albedo = "+b+";\n");(b=nb(this,1))&&(a+="\t o.Emission = "+b+";\n");(b=nb(this,2))&&(a+="\t o.Normal = "+b+";\n");(b=nb(this,3))&&(a+="\t o.Specular = "+b+";\n");(b=nb(this,4))&&(a+="\t o.Gloss = "+b+";\n");(b=nb(this,5))&&(a+="\t o.Reflectivity = "+b+";\n");(b=nb(this,6))&&(a+="\t o.Alpha = "+b+";\n");return a};LiteGraph.registerShaderNode("surface",Ib);var Jb=function(){this.addInput("in","vec3");this.addOutput("x","float");this.addOutput("y","float");this.addOutput("z",
"float")};Jb.title="Vec3->XYZ";Jb.desc="Split vec3";Jb.filter="shader";Jb.prototype.onGetCode=function(a){if("glsl"!=a)return"";a=nb(this,0);var b=Za(this,0),c=Za(this,1),e=Za(this,2);if(!a)return"";var d="";a&&b&&(d+="\tfloat "+b+" = "+a+".x;\n");a&&b&&(d+="\tfloat "+c+" = "+a+".y;\n");a&&b&&(d+="\tfloat "+e+" = "+a+".z;\n");return d};LiteGraph.registerShaderNode("Vec3toXYZ",Jb);var Tb=function(){this.addOutput("position","vec3");this.addOutput("local_position","vec3");this.addOutput("normal","vec3");
this.addOutput("local_normal","vec3");this.addOutput("uv","vec2");this.addOutput("screen","vec4");this.addOutput("viewDir","vec3");this.addOutput("camPos","vec3");this.addOutput("color","vec4");this.size=[97,156]};Tb.title="Vertex";Tb.desc="Reads info from vertex shader";Tb.prototype.onGetCode=function(a,b){if("glsl"!=a)return"";var c="",e=Za(this,0);e&&(c+="\t vec3 "+e+" = IN.worldPos;\n");(e=Za(this,1))&&(c+="\t vec3 "+e+" = IN.vertex;\n");(e=Za(this,2))&&(c+="\t vec3 "+e+" = IN.worldNormal;\n");
(e=Za(this,3))&&(c+="\t vec3 "+e+" = IN.normal;\n");(e=Za(this,4))&&(c+="\t vec2 "+e+" = IN.uv;\n");(e=Za(this,5))&&(c+="\t vec4 "+e+" = IN.screenPos;\n");(e=Za(this,6))&&(c+="\t vec3 "+e+" = IN.viewDir;\n");(e=Za(this,7))&&(c+="\t vec3 "+e+" = IN.camPos;\n");(e=Za(this,8))&&(c+="\t vec4 "+e+" = IN.color;\n");return c};LiteGraph.registerShaderNode("vertex",Tb)}xa.prototype.clear=function(){this.points.length=0};xa.prototype.addPoint=function(a){var b=vec3.create();b[0]=a[0];b[1]=a[1];2<a.length&&
(b[2]=a[2]);this.points.push(b)};xa.prototype.getSegments=function(){var a=this.points.length;switch(this.type){case d.LINEAR:if(2>a)break;return a-1+(this.closed?1:0);case d.HERMITE:if(2>a)break;return a-1+(this.closed?1:0);case d.BEZIER:if(3>a)break;return((a-1)/3|0)+(this.closed?1:0)}return 0};xa.prototype.movePoint=function(a,b,c){if(!(0>a&&a>=this.points.length)){var e=this.points[a],g=vec3.sub(vec3.create(),b,e);vec3.copy(e,b);c&&this.type==d.BEZIER&&(2==a%3&&this.points.length>a+2?(g=this.points[a+
1],a=this.points[a+2],e=vec3.sub(vec3.create(),g,e),vec3.add(a,g,e)):1==a%3&&3<a?(g=this.points[a-1],b=this.points[a-2],e=vec3.sub(vec3.create(),g,e),vec3.add(b,g,e)):0==a%3&&(1<a&&(b=this.points[a-1],vec3.add(b,b,g)),a<this.points.length-1&&(a=this.points[a+1],vec3.add(a,a,g))))}};xa.prototype.computePoint=function(a,b){switch(this.type){case d.HERMITE:return this.getHermitePoint(a,b);case d.BEZIER:return this.getBezierPoint(a,b);default:return this.getLinearPoint(a,b)}};xa.prototype.getLinearPoint=
function(a,b){b=b||vec3.create();var c=this.points.length,e=c;if(2>e)return b;if(0>=a)return vec3.copy(b,this.points[0]);if(1<=a)return this.closed?vec3.copy(b,this.points[0]):vec3.copy(b,this.points[e-1]);this.closed&&(e+=1);var e=(e-1)*a,d=e|0;return vec3.lerp(b,this.points[d%c],this.points[(d+1)%c],e-d)};xa.temp_vec3a=vec3.create();xa.temp_vec3b=vec3.create();xa.temp_vec3c=vec3.create();xa.prototype.getBezierPoint=function(a,b){b=b||vec3.create();var c=this.points.length;if(4>c)return b;c=3*((c-
1)/3|0)+1;if(0>=a)return vec3.copy(b,this.points[0]);if(1<=a)return vec3.copy(b,this.points[this.closed?0:c-1]);var e=(c-1)/3+(this.closed?1:0),d=e*a,f=d|0,d=d-f,h=3*f,k=3*f+1,l=3*f+2,n=3*f+3;this.closed&&f==e-1?(e=this.points[c-1],n=this.points[0],l=vec3.sub(xa.temp_vec3c,e,this.points[c-2]),c=vec3.add(xa.temp_vec3a,e,l),l=vec3.sub(xa.temp_vec3c,n,this.points[1]),l=vec3.add(xa.temp_vec3b,n,l)):(e=this.points[h],c=this.points[k],l=this.points[l],n=this.points[n]);f=(1-d)*(1-d)*(1-d);k=3*d*(1-d)*(1-
d);h=3*d*d*(1-d);d*=d*d;b[0]=e[0]*f+c[0]*k+l[0]*h+n[0]*d;b[1]=e[1]*f+c[1]*k+l[1]*h+n[1]*d;b[2]=e[2]*f+c[2]*k+l[2]*h+n[2]*d;return b};xa.prototype.getHermitePoint=function(a,b){b=b||vec3.create();var c=this.points.length;if(2>c)return b;if(0>=a)return vec3.copy(b,this.points[0]);if(1<=a)return vec3.copy(b,this.points[this.closed?0:c-1]);var e=(c-1+(this.closed?1:0))*a,d=e|0,f=this.points[d-1],h=this.points[d],k=this.points[d+1],l=this.points[d+2];f||(f=this.closed?this.points[c-1]:h);k||(k=this.points[(d+
1)%c]);l||(l=this.closed?this.points[(d+2)%c]:k);X.EvaluateHermiteSplineVector(h,k,f,l,e-d,b);return b};xa.prototype.samplePoints=function(a,b){if(0>=a){var c=this.getSegments();a=this.type==d.LINEAR?c+1:20*c}b=b||Array(a);b.length=a;for(c=0;c<a;c++)b[c]=this.computePoint(c/(a-1));return b};xa.prototype.samplePointsTyped=function(a,b){b&&b.length<3*a&&(a=Math.floor(b.length/3));if(0>=a){var c=this.getSegments();a=this.type==d.LINEAR?c+1:20*c}b=b||new Float32Array(3*a);for(c=0;c<a;c++)this.computePoint(c/
(a-1),b.subarray(3*c,3*c+3));return b};xa.prototype.serialize=function(){for(var a={},b=Array(3*this.points.length),c=0;c<this.points.length;c++){var e=this.points[c];b[3*c]=e[0];b[3*c+1]=e[1];b[3*c+2]=e[2]}a.points=b;a.type=this.type;a.closed=this.closed;return a};xa.prototype.configure=function(a){this.type=a.type;this.closed=a.closed;if(a.points){this.points.length=a.points.length/3;a=a.points;for(var b=0;b<this.points.length;b++)this.points[b]=vec3.fromValues(a[3*b],a[3*b+1],a[3*b+2])}};d.Path=
xa;Y.available_fx={brightness_contrast:{name:"Brightness & Contrast",uniforms:{brightness:{name:"u_brightness",type:"float",value:1,step:0.01},contrast:{name:"u_contrast",type:"float",value:1,step:0.01}},code:"color.xyz = (color.xyz * u_brightness@ - vec3(0.5)) * u_contrast@ + vec3(0.5);"},hue_saturation:{name:"Hue & Saturation",functions:["HSV"],uniforms:{hue:{name:"u_hue",type:"float",value:0,step:0.01},saturation:{name:"u_saturation",type:"float",value:1,step:0.01},brightness:{name:"u_brightness",
type:"float",value:0,step:0.01}},code:"color.xyz = rgb2hsv(color.xyz); color.xz += vec2(u_hue@,u_brightness@); color.y *= u_saturation@; color.xyz = hsv2rgb(color.xyz);"},invert:{name:"Invert color",code:"color.xyz = vec3(1.0) - color.xyz;"},threshold:{name:"Threshold",uniforms:{threshold:{name:"u_threshold",type:"float",value:0.5,min:0,max:2,step:0.01},threshold_width:{name:"u_threshold_width",type:"float",value:0.01,min:0,max:1,step:0.001}},code:"color.xyz = vec3( smoothstep( u_threshold@ - u_threshold_width@ * 0.5, u_threshold@ + u_threshold_width@ * 0.5,  length(color.xyz) ));"},
colorize:{name:"Colorize",uniforms:{colorize:{name:"u_colorize",type:"color3",value:[1,1,1]},vibrance:{name:"u_vibrance",type:"float",value:0,min:0,max:2,step:0.01}},code:"color.xyz = color.xyz * (u_colorize@ + vec3(u_vibrance@ * 0.1)) * (1.0 + u_vibrance@);"},color_add:{name:"Color add",uniforms:{color_add:{name:"u_coloradd",type:"color3",value:[0.1,0.1,0.1]}},code:"color.xyz = color.xyz + u_coloradd@;"},fog:{name:"fog",uniforms:{fog_color:{name:"u_fog_color",type:"color3",value:[0.1,0.1,0.1]},fog_start:{name:"u_fog_start",
type:"float",value:10},fog_density:{name:"u_fog_density",type:"float",precision:1E-5,value:0.001,step:1E-5}},code:"float z_n@ = 2.0 * texture2D( u_depth_texture, v_coord).x - 1.0;float cam_dist@ = 2.0 * u_depth_range.x * u_depth_range.y / (u_depth_range.y + u_depth_range.x - z_n@ * (u_depth_range.y - u_depth_range.x));float fog_factor@ = 1. - 1.0 / exp(max(0.0,cam_dist@ - u_fog_start@) * u_fog_density@);color.xyz = mix( color.xyz, u_fog_color@, fog_factor@ );"},vigneting:{name:"Vigneting",uniforms:{radius:{name:"u_radius",
type:"float",value:1},intensity:{name:"u_vigneting",type:"float",value:1,min:0,max:2,step:0.01}},code:"color.xyz = mix( color.xyz * max( 1.0 - (dist_to_center * u_radius@ / 0.7071), 0.0), color.xyz, u_vigneting@);"},aberration:{name:"Chromatic Aberration",break_pass:!0,uniforms:{difraction:{name:"u_difraction",type:"float",value:1}},code:"color.x = texture2D(u_texture, uv - to_center * 0.001 * u_difraction@ ).x;color.z = texture2D(u_texture, uv + to_center * 0.001 * u_difraction@ ).z;"},halftone:{name:"Halftone",
uniforms:{"Halftone angle":{name:"u_halftone_angle",type:"float",value:0,step:0.01},"Halftone size":{name:"u_halftone_size",type:"float",value:1,step:0.01}},functions:["pattern"],code:"color.x = ( (color.x * 10.0 - 5.0) + pattern( u_halftone_angle@, u_halftone_size@ ) );color.y = ( (color.y * 10.0 - 5.0) + pattern( u_halftone_angle@ + 0.167, u_halftone_size@ ) );color.z = ( (color.z * 10.0 - 5.0) + pattern( u_halftone_angle@ + 0.333, u_halftone_size@ ) );"},halftoneBN:{name:"Halftone B/N",uniforms:{"Halftone angle":{name:"u_halftone_angle",
type:"float",value:0,step:0.01},"Halftone size":{name:"u_halftone_size",type:"float",value:1,step:0.01}},functions:["pattern"],code:"color.xyz = vec3( (length(color.xyz) * 10.0 - 5.0) + pattern( u_halftone_angle@, u_halftone_size@ ) );"},lens:{name:"Lens Distortion",break_pass:!0,uniforms:{lens_k:{name:"u_lens_k",type:"float",value:-0.15},lens_kcube:{name:"u_lens_kcube",type:"float",value:0.8},lens_scale:{name:"u_lens_scale",type:"float",value:1}},uv_code:"float r2 = u_aspect * u_aspect * (uv.x-0.5) * (uv.x-0.5) + (uv.y-0.5) * (uv.y-0.5); float distort@ = 1. + r2 * (u_lens_k@ + u_lens_kcube@ * sqrt(r2)); uv = vec2( u_lens_scale@ * distort@ * (uv.x-0.5) + 0.5, u_lens_scale@  * distort@ * (uv.y-0.5) + 0.5 );"},
image:{name:"Image",uniforms:{image_texture:{name:"u_image_texture",type:"sampler2D",widget:"Texture",value:""},image_alpha:{name:"u_image_alpha",type:"float",value:1,step:0.001},image_scale:{name:"u_image_scale",type:"vec2",value:[1,1],step:0.001}},code:"vec4 image@ = texture2D( u_image_texture@, (uv - vec2(0.5)) * u_image_scale@ + vec2(0.5)); color.xyz = mix(color.xyz, image@.xyz, image@.a * u_image_alpha@ );"},warp:{name:"Warp",break_pass:!0,uniforms:{warp_amp:{name:"u_warp_amp",type:"float",value:0.01,
step:0.001},warp_offset:{name:"u_warp_offset",type:"vec2",value:[0,0],step:0.001},warp_scale:{name:"u_warp_scale",type:"vec2",value:[1,1],step:0.001},warp_texture:{name:"u_warp_texture",type:"sampler2D",widget:"Texture",value:""}},uv_code:"uv = uv + u_warp_amp@ * (texture2D( u_warp_texture@, uv * u_warp_scale@ + u_warp_offset@ ).xy - vec2(0.5));"},LUT:{name:"LUT",functions:["LUT"],uniforms:{lut_intensity:{name:"u_lut_intensity",type:"float",value:1,step:0.01},lut_texture:{name:"u_lut_texture",type:"sampler2D",
filter:"nearest",wrap:"clamp",widget:"Texture",value:""}},code:"color.xyz = mix(color.xyz, LUT( color.xyz, u_lut_texture@ ), u_lut_intensity@);"},pixelate:{name:"Pixelate",uniforms:{width:{name:"u_width",type:"float",value:256,step:1,min:1},height:{name:"u_height",type:"float",value:256,step:1,min:1}},uv_code:"uv = vec2( floor(uv.x * u_width@) / u_width@, floor(uv.y * u_height@) / u_height@ );"},quantize:{name:"Quantize",uniforms:{levels:{name:"u_levels",type:"float",value:8,step:1,min:1}},code:"color.xyz = floor(color.xyz * u_levels@) / u_levels@;"},
edges:{name:"Edges",break_pass:!0,uniforms:{"Edges factor":{name:"u_edges_factor",type:"float",value:1}},code:"vec4 color@ = texture2D(u_texture, uv );\n\t\t\t\tvec4 color_up@ = texture2D(u_texture, uv + vec2(0., u_iviewport.y));\n\t\t\t\tvec4 color_right@ = texture2D(u_texture, uv + vec2(u_iviewport.x,0.));\n\t\t\t\tvec4 color_down@ = texture2D(u_texture, uv + vec2(0., -u_iviewport.y));\n\t\t\t\tvec4 color_left@ = texture2D(u_texture, uv + vec2(-u_iviewport.x,0.));\n\t\t\t\tcolor = u_edges_factor@ * (abs(color@ - color_up@) + abs(color@ - color_down@) + abs(color@ - color_left@) + abs(color@ - color_right@));"},
depth:{name:"Depth",uniforms:{near:{name:"u_near",type:"float",value:0.01,step:0.1},far:{name:"u_far",type:"float",value:1E3,step:1}},code:"color.xyz = vec3( (2.0 * u_near@) / (u_far@ + u_near@ - texture2D( u_depth_texture, uv ).x * (u_far@ - u_near@)) );"},logarithmic:{name:"Logarithmic",uniforms:{"Log. A Factor":{name:"u_logfactor_a",type:"float",value:2,step:0.01},"Log. B Factor":{name:"u_logfactor_b",type:"float",value:2,step:0.01}},code:"color.xyz = log( color.xyz * u_logfactor_a@ ) * u_logfactor_b@;"},
ditherBN:{name:"dither B/N",functions:["dither"],code:"color.xyz = vec3( dither( color.x ) );"},dither:{name:"Dither",functions:["dither"],code:"color.xyz = vec3( dither( color.x ), dither( color.y ), dither( color.z ) );"},gamma:{name:"Gamma",uniforms:{Gamma:{name:"u_gamma",type:"float",value:2.2,step:0.01}},code:"color.xyz = pow( color.xyz, vec3( 1.0 / u_gamma@) );"},noiseBN:{name:"Noise B&N",functions:["noise"],uniforms:{noise:{name:"u_noise",type:"float",value:0.1,step:0.01}},code:"color.xyz += u_noise@ * vec3( noise( (u_random + v_coord) * u_viewport) );"}};
Y.available_functions={pattern:"float pattern(float angle, float size) {\n\t\t\t\tfloat s = sin(angle * 3.1415), c = cos(angle * 3.1415);\n\t\t\t\tvec2 tex = v_coord * u_viewport.xy;\n\t\t\t\tvec2 point = vec2( c * tex.x - s * tex.y , s * tex.x + c * tex.y ) * size;\n\t\t\t\treturn (sin(point.x) * sin(point.y)) * 4.0;\n\t\t\t}\n\t\t",dither:"float dither(float v) {\n\t\t\t\tvec2 pixel = v_coord * u_viewport;\n\t\t\t\tint i = int(floor(clamp(v,0.0,1.0) * 16.0 + 0.5));\n\t\t\t\tif(i < 1)\n\t\t\t\t\treturn 0.0;\n\t\t\t\tif(i >= 15)\n\t\t\t\t\treturn 1.0;\n\t\t\t\tfloat x = floor(pixel.x);\n\t\t\t\tfloat y = floor(pixel.y);\n\t\t\t\tbool xmod4 = mod(x, 4.0) == 0.0;\n\t\t\t\tbool ymod4 = mod(y, 4.0) == 0.0;\n\t\t\t\tbool xmod2 = mod(x, 2.0) == 0.0;\n\t\t\t\tbool ymod2 = mod(y, 2.0) == 0.0;\n\t\t\t\tbool xmod4_2 = mod(x + 2.0, 4.0) == 0.0;\n\t\t\t\tbool ymod4_2 = mod(y + 2.0, 4.0) == 0.0;\n\t\t\t\tbool xmod2_1 = mod(x + 1.0, 2.0) == 0.0;\n\t\t\t\tbool ymod2_1 = mod(y + 1.0, 2.0) == 0.0;\n\t\t\t\tbool xmod4_1 = mod(x + 1.0, 4.0) == 0.0;\n\t\t\t\tbool ymod4_1 = mod(y + 1.0, 4.0) == 0.0;\n\t\t\t\tbool xmod4_3 = mod(x + 3.0, 4.0) == 0.0;\n\t\t\t\tbool ymod4_3 = mod(y + 3.0, 4.0) == 0.0;\n\t\t\t\t\n\t\t\t\tif(i < 9)\n\t\t\t\t{\n\t\t\t\t\tif(i >= 1 && xmod4 && ymod4 )\n\t\t\t\t\t\treturn 1.0;\n\t\t\t\t\tif(i >= 2 && xmod4_2 && ymod4_2)\n\t\t\t\t\t\treturn 1.0;\n\t\t\t\t\tif(i >= 3 && xmod4_2 && ymod2 )\n\t\t\t\t\t\treturn 1.0;\n\t\t\t\t\tif(i >= 4 && xmod2 && ymod2 )\n\t\t\t\t\t\treturn 1.0;\n\t\t\t\t\tif(i >= 5 && xmod4_1 && ymod4_1 )\n\t\t\t\t\t\treturn 1.0;\n\t\t\t\t\tif(i >= 6 && xmod4_3 && ymod4_3 )\n\t\t\t\t\t\treturn 1.0;\n\t\t\t\t\tif(i >= 7 && xmod4_1 && ymod4_3 )\n\t\t\t\t\t\treturn 1.0;\n\t\t\t\t\tif(i >= 8 && xmod4_3 && ymod4_1 )\n\t\t\t\t\t\treturn 1.0;\n\t\t\t\t\treturn 0.0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(i < 15 && xmod4_1 && ymod4 )\n\t\t\t\t\t\treturn 0.0;\n\t\t\t\t\tif(i < 14 && xmod4_3 && ymod4_2)\n\t\t\t\t\t\treturn 0.0;\n\t\t\t\t\tif(i < 13 && xmod4_3 && ymod2 )\n\t\t\t\t\t\treturn 0.0;\n\t\t\t\t\tif(i < 12 && xmod2_1 && ymod2 )\n\t\t\t\t\t\treturn 0.0;\n\t\t\t\t\tif(i < 11 && xmod4_2 && ymod4_1 )\n\t\t\t\t\t\treturn 0.0;\n\t\t\t\t\tif(i < 10 && xmod4 && ymod4_3 )\n\t\t\t\t\t\treturn 0.0;\n\t\t\t\t\treturn 1.0;\n\t\t\t\t}\n\t\t\t}\n\t\t",
LUT:"vec3 LUT(in vec3 color, in sampler2D textureB) {\n\t\t lowp vec3 textureColor = clamp( color, vec3(0.0), vec3(1.0) );\n\t\t mediump float blueColor = textureColor.b * 63.0;\n\t\t mediump vec2 quad1;\n\t\t quad1.y = floor(floor(blueColor) / 8.0);\n\t\t quad1.x = floor(blueColor) - (quad1.y * 8.0);\n\t\t mediump vec2 quad2;\n\t\t quad2.y = floor(ceil(blueColor) / 8.0);\n\t\t quad2.x = ceil(blueColor) - (quad2.y * 8.0);\n\t\t highp vec2 texPos1;\n\t\t texPos1.x = (quad1.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);\n\t\t texPos1.y = 1.0 - ((quad1.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g));\n\t\t highp vec2 texPos2;\n\t\t texPos2.x = (quad2.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);\n\t\t texPos2.y = 1.0 - ((quad2.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g));\n\t\t lowp vec3 newColor1 = texture2D(textureB, texPos1).xyz;\n\t\t lowp vec3 newColor2 = texture2D(textureB, texPos2).xyz;\n\t\t lowp vec3 newColor = mix(newColor1, newColor2, fract(blueColor));\n\t\t return newColor.rgb;\n\t }",
noise:"\n\t\tfloat hash(float n) { return fract(sin(n) * 1e4); }\n\t\tfloat hash(vec2 p) { return fract(1e4 * sin(17.0 * p.x + p.y * 0.1) * (0.1 + abs(sin(p.y * 13.0 + p.x)))); }\n\t\tfloat noise(float x) {\n\t\t\tfloat i = floor(x);\n\t\t\tfloat f = fract(x);\n\t\t\tfloat u = f * f * (3.0 - 2.0 * f);\n\t\t\treturn mix(hash(i), hash(i + 1.0), u);\n\t\t}\n\t\tfloat noise(vec2 x) {\n\t\t\tvec2 i = floor(x);\n\t\t\tvec2 f = fract(x);\n\t\t\tfloat a = hash(i);\n\t\t\tfloat b = hash(i + vec2(1.0, 0.0));\n\t\t\tfloat c = hash(i + vec2(0.0, 1.0));\n\t\t\tfloat d = hash(i + vec2(1.0, 1.0));\n\t\t\tvec2 u = f * f * (3.0 - 2.0 * f);\n\t\t\treturn mix(a, b, u.x) + (c - a) * u.y * (1.0 - u.x) + (d - b) * u.x * u.y;\n\t\t}\n\t",
HSV:"vec3 rgb2hsv(vec3 c)\n\t\t{\n\t\t\tvec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n\t\t\tvec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));\n\t\t\tvec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));\n\t\t\t\n\t\t\tfloat d = q.x - min(q.w, q.y);\n\t\t\tfloat e = 1.0e-10;\n\t\t\treturn vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);\n\t\t}\n\t\t\n\t\tvec3 hsv2rgb(vec3 c)\n\t\t{\n\t\t\tvec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n\t\t\tvec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);\n\t\t\treturn c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);\n\t\t}"};
Y.prototype.configure=function(a){this.apply_fxaa=!!a.apply_fxaa;a.fx&&(this.fx=a.fx.concat());this._must_update_passes=!0};Y.prototype.serialize=Y.prototype.toJSON=function(){return{apply_fxaa:this.apply_fxaa,fx:this.fx.concat()}};Y.prototype.getResources=function(a){for(var b=this.fx,c=0;c<b.length;c++){var e=b[c],d=Y.available_fx[e.name];if(d&&d.uniforms)for(var f in d.uniforms)"sampler2D"==d.uniforms[f].type&&e[f]&&(a[e[f]]=GL.Texture)}return a};Y.prototype.onResourceRenamed=function(a,b,c){c=
this.fx;for(var e=0;e<c.length;e++){var d=c[e],f=Y.available_fx[d.name];if(f&&f.uniforms)for(var h in f.uniforms)"sampler2D"==f.uniforms[h].type&&d[h]==a&&(d[h]=b)}};Y.prototype.addFX=function(a){a&&(Y.available_fx[a]?(this.fx.push({name:a}),this._must_update_passes=!0):console.warn("FXStack not found: "+a))};Y.prototype.getFX=function(a){return this.fx[a]};Y.prototype.moveFX=function(a,b){b=b||-1;var c=this.fx.indexOf(a);-1!=c&&(this.fx.splice(c,1),c+=b,0<=c&&c<this.fx.length?this.fx.splice(c,0,
a):this.fx.push(a),this._must_update_passes=!0)};Y.prototype.removeFX=function(a){for(var b=0;b<this.fx.length;b++)if(this.fx[b]===a){this.fx.splice(b,1);this._must_update_passes=!0;break}};Y.prototype.buildPasses=function(){for(var a=this.fx,b=[],c={fxs:[],uniforms:{},shader:null,first_fx_id:0},e="",d="",f="",h={},k=!0,l=0,n=0;n<a.length;n++){var p=a[n],l=n,m=Y.available_fx[p.name];if(m){m.break_pass&&!k?(c.uv_code=e,c.color_code=d,c.uniforms_code=f,c.included_functions=h,b.push(c),this.buildPassShader(c),
f=d=e="",h={},c={fxs:[],uniforms:{},first_fx_id:l},k=!0):k=!1;if(m.functions)for(var q in m.functions)h[m.functions[q]]=!0;m.code&&(d+=m.code.split("@").join(l)+";\n");m.uv_code&&(e+=m.uv_code.split("@").join(l)+";\n");if(m.uniforms)for(var s in m.uniforms)var t=m.uniforms[s],f=f+("uniform "+t.type+" "+(t.name+l)+";\n");c.fxs.push(p)}}k||(c.uv_code=e,c.color_code=d,c.included_functions=h,b.push(c),this.buildPassShader(c));this._passes=b};Y.prototype.buildPassShader=function(a){var b="",c;for(c in a.included_functions){var e=
Y.available_functions[c];e?b+=e+"\n":console.error("FXStack: Function not found: "+c)}b="\n\t\t#extension GL_OES_standard_derivatives : enable\n\t\tprecision highp float;\n\t\t#define color3 vec3\n\t\t#define color4 vec4\n\t\tuniform sampler2D u_texture;\n\t\tuniform sampler2D u_depth_texture;\n\t\tvarying vec2 v_coord;\n\t\tuniform vec2 u_viewport;\n\t\tuniform vec2 u_iviewport;\n\t\tuniform float u_aspect;\n\t\tuniform vec2 u_depth_range;\n\t\tuniform vec2 u_random;\n\t\tvec2 uv;\n\t\t"+a.uniforms_code+
"\n\t\t"+b+"\n\t\tvoid main() {\n\t\t\tuv = v_coord;\n\t\t\tvec2 to_center = vec2(0.5) - uv;\n\t\t\tfloat dist_to_center = length(to_center);\n\t\t\t"+a.uv_code+"\n\t\t\tvec4 color = texture2D(u_texture, uv);\n\t\t\tfloat temp = 0.0;\n\t\t\t"+a.color_code+"\n\t\t\tgl_FragColor = color;\n\t\t}\n\t\t";this._must_update_passes=!1;a.shader=new GL.Shader(GL.Shader.SCREEN_VERTEX_SHADER,b);return a.shader};Y.prototype.applyFX=function(a,b,c){var e=c.depth_texture,g=this._uniforms;g.u_viewport[0]=a.width;
g.u_viewport[1]=a.height;g.u_iviewport[0]=1/a.width;g.u_iviewport[1]=1/a.height;g.u_aspect=a.width/a.height;g.u_random[0]=Math.random();g.u_random[1]=Math.random();this._passes&&!this._must_update_passes||this.buildPasses();if(this._passes.length){var f=b?b.width:a.width,h=b?b.height:a.height;c=GL.Texture.getTemporary(f,h,{type:a.type,format:a.format});f=GL.Texture.getTemporary(f,h,{type:a.type,format:a.format});a.copyTo(c);for(var k=0,h=0;h<this._passes.length;h++){for(var l=this._passes[h],n=2,
p=l.uniforms,m=0;m<l.fxs.length;++m){var q=l.fxs[m],k=l.first_fx_id+m,s=Y.available_fx[q.name];if(s&&s.uniforms)for(var t in s.uniforms){var u=s.uniforms[t],H=u.name+k;"sampler2D"==u.type?(p[H]=n,(H=this.getTexture(q[t]))?(H.bind(n),"nearest"==u.filter&&(gl.texParameteri(H.texture_type,gl.TEXTURE_MAG_FILTER,gl.NEAREST),gl.texParameteri(H.texture_type,gl.TEXTURE_MIN_FILTER,gl.NEAREST)),"clamp"==u.wrap&&(gl.texParameteri(H.texture_type,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE),gl.texParameteri(H.texture_type,
gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE))):(H=d.Renderer._missing_texture)&&H.bind(n),n++):p[H]=void 0!==q[m]?q[m]:u.value}}l=l.shader;if(!l){a.toViewport();break}e&&l.hasUniform("u_depth_texture")&&(e.bind(1),e.near_far_planes&&(p.u_depth_range=e.near_far_planes));l.uniforms(g);c.copyTo(f,l,p);k=c;c=f;f=k}a=f;a.setParameter(gl.TEXTURE_MAG_FILTER,this.filter?gl.LINEAR:gl.NEAREST);a.setParameter(gl.TEXTURE_MIN_FILTER,gl.LINEAR);gl.disable(gl.DEPTH_TEST);gl.disable(gl.BLEND);gl.disable(gl.CULL_FACE);this.apply_fxaa?
(p=GL.Shader.getFXAAShader(),p.setup(),b?a.copyTo(b,p):a.toViewport(p)):b?(l.uniforms(p),a.copyTo(b,l)):a.toViewport();GL.Texture.releaseTemporary(c);GL.Texture.releaseTemporary(f)}else b?a.copyTo(b):(b=GL.Shader.getFXAAShader(),b.setup(),a.toViewport(this.apply_fxaa?b:null))};Y.prototype.applyFX=function(a,b,c){c=c.depth_texture;var e=this.fx,g=this._must_update_passes;this._must_update_passes=!1;var f=this._uniforms;f.u_viewport[0]=a.width;f.u_viewport[1]=a.height;f.u_iviewport[0]=1/a.width;f.u_iviewport[1]=
1/a.height;f.u_aspect=a.width/a.height;f.u_random[0]=Math.random();f.u_random[1]=Math.random();for(var h="",k="",l={},n="",p=2,m=0,q=0;q<e.length;q++){var s=e[q],m=q,t=Y.available_fx[s.name];if(t){if(g){if(t.functions)for(var u in t.functions)l[t.functions[u]]=!0;t.code&&(k+=t.code.split("@").join(m)+";\n");t.uv_code&&(h+=t.uv_code.split("@").join(m)+";\n")}if(t.uniforms)for(var H in t.uniforms){var G=t.uniforms[H],Z=G.name+m;g&&(n+="uniform "+G.type+" "+Z+";\n");"sampler2D"==G.type?(f[Z]=p,(Z=this.getTexture(s[H]))?
(Z.bind(p),"nearest"==G.filter&&(gl.texParameteri(Z.texture_type,gl.TEXTURE_MAG_FILTER,gl.NEAREST),gl.texParameteri(Z.texture_type,gl.TEXTURE_MIN_FILTER,gl.NEAREST)),"clamp"==G.wrap&&(gl.texParameteri(Z.texture_type,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE),gl.texParameteri(Z.texture_type,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE))):(Z=d.Renderer._missing_texture)&&Z.bind(p),p++):f[Z]=void 0!==s[H]?s[H]:G.value}}}var M=null;if(g){u="";for(q in l)(l=Y.available_functions[q])?u+=l+"\n":console.error("FXStack: Function not found: "+
q);this._last_shader=new GL.Shader(GL.Shader.SCREEN_VERTEX_SHADER,"\n\t\t\t#extension GL_OES_standard_derivatives : enable\n\t\t\tprecision highp float;\n\t\t\t#define color3 vec3\n\t\t\t#define color4 vec4\n\t\t\tuniform sampler2D u_texture;\n\t\t\tuniform sampler2D u_depth_texture;\n\t\t\tvarying vec2 v_coord;\n\t\t\tuniform vec2 u_viewport;\n\t\t\tuniform vec2 u_iviewport;\n\t\t\tuniform float u_aspect;\n\t\t\tuniform vec2 u_depth_range;\n\t\t\tuniform vec2 u_random;\n\t\t\tvec2 uv;\n\t\t\t"+n+
"\n\t\t\t"+u+"\n\t\t\tvoid main() {\n\t\t\t\tuv = v_coord;\n\t\t\t\tvec2 to_center = vec2(0.5) - uv;\n\t\t\t\tfloat dist_to_center = length(to_center);\n\t\t\t\t"+h+"\n\t\t\t\tvec4 color = texture2D(u_texture, uv);\n\t\t\t\tfloat temp = 0.0;\n\t\t\t\t"+k+"\n\t\t\t\tgl_FragColor = color;\n\t\t\t}\n\t\t\t")}M=this._last_shader;gl.disable(gl.DEPTH_TEST);gl.disable(gl.BLEND);gl.disable(gl.CULL_FACE);M?(M.hasUniform("u_depth_texture")&&c&&(c.bind(1),c.near_far_planes&&(f.u_depth_range=c.near_far_planes)),
a.setParameter(gl.TEXTURE_MAG_FILTER,this.filter?gl.LINEAR:gl.NEAREST),a.setParameter(gl.TEXTURE_MIN_FILTER,gl.LINEAR),this.apply_fxaa?(this.temp_tex&&this.temp_tex.width==gl.viewport_data[2]&&this.temp_tex.height==gl.viewport_data[3]||(this.temp_tex=new GL.Texture(gl.viewport_data[2],gl.viewport_data[3])),this.temp_tex.drawTo(function(){a.toViewport(M,f)}),c=GL.Shader.getFXAAShader(),c.setup(),b?this.temp_tex.copyTo(b,c):this.temp_tex.toViewport(c)):(this.temp_tex=null,b?(M.uniforms(f),a.copyTo(b,
M)):a.toViewport(M,f))):a.toViewport()};Y.prototype.getTexture=function(a){return d.ResourcesManager.getTexture(a)};Y.prototype.getPropertyInfoFromPath=function(a){if(2>a.length)return null;var b=parseInt(a[0]);if(b>=this.fx.length)return null;var b=this.fx[b],c=Y.available_fx[b.name];if(!c)return null;a=a[1];return"name"==a?null:(c=c.uniforms[a])?{target:b,name:a,value:b[a],type:c.type||"number"}:null};Y.prototype.setPropertyValueFromPath=function(a,b,c){c=c||0;if(a.length<c+1)return null;var e=
parseInt(a[c]);if(e>=this.fx.length)return null;e=this.fx[e];if(!e)return null;a=a[c+1];if(void 0===e[a])return null;void 0!==e[a]&&void 0!==b&&e[a].constructor===b.constructor&&(e[a]=b)};Y.registerFX=function(a,b){b.name||(b.name=a);if(void 0===b.code)throw"FXStack must have a code";b.uniforms&&Object.keys(b.uniforms)&&b.code&&-1==b.code.indexOf("@")&&console.warn("FXStack using uniforms must use the character '@' at the end of every use to avoid collisions with other variables with the same name.");
Y.available_fx[a]=b};Y.registerFunction=function(a,b){Y.available_functions[a]=b};d.FXStack=Y;d.TextureFX=Y;d.Tween={MAX_EASINGS:256,EASE_IN_QUAD:1,EASE_OUT_QUAD:2,EASE_IN_OUT_QUAD:3,QUAD:3,EASE_IN_CUBIC:4,EASE_OUT_CUBIC:5,EASE_IN_OUT_CUBIC:6,CUBIC:6,EASE_IN_QUART:7,EASE_OUT_QUART:8,EASE_IN_OUT_QUART:9,QUART:9,EASE_IN_SINE:10,EASE_OUT_SINE:11,EASE_IN_OUT_SINE:12,SINE:12,EASE_IN_EXPO:13,EASE_OUT_EXPO:14,EASE_IN_OUT_EXPO:15,EXPO:15,EASE_IN_BACK:16,EASE_OUT_BACK:17,EASE_IN_OUT_BACK:18,BACK:18,current_easings:[],
_alife:[],reset:function(){this.current_easings=[];this._alife=[]},easeProperty:function(a,b,c,e,g,f,h){if(!a)throw"ease object cannot be null";if(void 0===c)throw"target vaue must be defined";if(void 0===a[b])throw"property not found in object, must be initialized to a value";if(this.current_easings.length)for(var k=0;k<this.current_easings.length;++k){var l=this.current_easings[k];if(l.object===a&&l.property==b){this.current_easings.splice(k,1);break}}g=g||this.EASE_IN_OUT_QUAD;k=null;k=b?d.cloneObject(a[b]):
d.cloneObject(a);c=d.cloneObject(c);l=0;c.constructor===Number?l=-1:c&&void 0!==c.length&&(l=c.length);var n=null,p=a.constructor["@"+b];p&&(n=p.type);c={object:a,property:b,origin:k,target:c,current:0,time:e,easing:g,on_complete:f,on_progress:h,size:l,type:n,running:!0};for(k=0;k<this.current_easings.length;++k)if(this.current_easings[k].object==a&&this.current_easings[k].property==b){this.current_easings[k]=c;break}this.current_easings.length>=this.MAX_EASINGS&&this.current_easings.shift();this.current_easings.push(c);
return c},easeObject:function(a,b,c,e,g,f){if(!a||!b)throw"ease object cannot be null";e=e||this.EASE_IN_OUT_QUAD;var h=d.cloneObject(a);b=d.cloneObject(b);var k=0;void 0!==b.length&&(k=b.length);b={object:a,origin:h,target:b,current:0,time:c,easing:e,on_complete:g,on_progress:f,size:k};for(c=0;c<this.current_easings.length;++c)if(this.current_easings[c].object==a){this.current_easings[c]=b;break}this.current_easings.length>=this.MAX_EASINGS&&this.current_easings.shift();this.current_easings.push(b);
return b},update:function(a){if(this.current_easings.length){var b=this.current_easings,c=this._alife;c.length=b.length;for(var e=0,d=0,f=b.length;d<f;++d){var h=b[d];h.current+=a;var k=1;h.current<h.time&&(k=h.current/h.time,c[e]=h,e+=1);var l=this.getEaseFactor(k,h.easing);if(h.size){if(-1==h.size)h.object[h.property]=h.target*l+h.origin*(1-l);else{var n=h.object[h.property];if(h.type&&"quat"==h.type)quat.slerp(n,h.origin,h.target,l);else for(var p=0;p<h.size;++p)n[p]=h.target[p]*l+h.origin[p]*
(1-l)}void 0!==h.object.mustUpdate&&(h.object.mustUpdate=!0)}if(h.on_progress)h.on_progress(h);if(1<=k){if(h.on_complete)h.on_complete(h);h.running=!1}}c.length=e;this.current_easings=c;this._alife=b}},getEaseFactor:function(a,b){1<a?a=1:0>a&&(a=0);var c=1.70158;b=b||this.QUAD;switch(b){case this.EASE_IN_QUAD:return a*a;case this.EASE_OUT_QUAD:return 1-a*a;case this.EASE_IN_OUT_QUAD:a*=2;if(1>a)return 0.5*a*a;a-=1;return-0.5*(a*(a-2)-1);case this.EASE_IN_CUBIC:return a*a*a;case this.EASE_OUT_CUBIC:return a-=
1,a*a*a+1;case this.EASE_IN_OUT_CUBIC:a*=2;if(1>a)return 0.5*a*a*a;a-=2;return 0.5*(a*a*a+2);case this.EASE_IN_QUART:return a*a*a*a;case this.EASE_OUT_QUART:return a-=1,-(a*a*a*a-1);case this.EASE_IN_OUT_QUART:a*=2;if(1>a)return 0.5*a*a*a*a;a-=2;return-0.5*(a*a*a*a-2);case this.EASE_IN_SINE:return 1-Math.cos(a*Math.PI/2);case this.EASE_OUT_SINE:return Math.sin(a*Math.PI/2);case this.EASE_IN_OUT_SINE:return-0.5*(Math.cos(Math.PI*a)-1);case this.EASE_IN_EXPO:return 0==a?0:Math.pow(2,10*(a-1));case this.EASE_OUT_EXPO:return 1==
a?1:1-Math.pow(2,-10*a);case this.EASE_IN_OUT_EXPO:if(0==a)return 0;if(1==a)return 1;a*=2;return 1>a?0.5*Math.pow(2,10*(a-1)):0.5*(-Math.pow(2,-10*(a-1))+2);case this.EASE_IN_BACK:return a*a*((c+1)*a-c);case this.EASE_OUT_BACK:return a*a*((c+1)*a+c)+1;case this.EASE_IN_OUT_BACK:a*=2;if(1>a)return c*=1.525,0.5*a*a*((c+1)*a-c);a-=2;c*=1.525;return 0.5*(a*a*((c+1)*a+c)+2)}return a}};Fb.prototype.addEntry=function(a,b,c){if(a.constructor===d.AnimationBlender.Entry)this.active_entries.push(a);else{var e=
new d.AnimationBlender.Entry;e.animation_name=a;e.take_name=b;e.time=c;this.active_entries.push(e);return e}};Fb.prototype.removeEntry=function(a){a=this.active_entries.indexOf(a);-1!=a&&this.active_entries.splice(a,1)};Fb.prototype.execute=function(a,b){for(var c={},e=0,d=0;d<this.active_entries.length;++d){var f=this.active_entries[d];if(f._animation_take)for(var e=e+f.weight,f=f._animation_take,h=0;h<f.tracks.length;++h){var k=f.tracks[h],l=c[k.property];l||(l=c[k.property]=[]);k=k.getSample();
l.push(k)}}for(d=0;d<this.active_entries.length;++d)f=this.active_entries[d],e+=f.weight;for(d=0;d<this.active_entries.length;++d)f=this.active_entries[d],f.execute(remaining/e,!1,a,b),remaining-=f.weight};d.AnimationBlender=Fb;Object.defineProperty(Bb.prototype,"take_name",{set:function(a){this._take_name!=a&&(this._take_name=a,this._must_update=!0)},get:function(){return this._take_name},enumerable:!1});Object.defineProperty(Bb.prototype,"animation_name",{set:function(a){this._animation_name!=a&&
(this._animation_name=a,this._must_update=!0)},get:function(){return this._animation_name},enumerable:!1});Object.defineProperty(Bb.prototype,"duration",{set:function(a){throw"duration cannot be set. It depends in the animation duration";},get:function(){return this._animation_take?this._animation_take.duration:-1},enumerable:!1});Object.defineProperty(Bb.prototype,"loaded",{set:function(a){throw"duration cannot be set. It depends in the animation duration";},get:function(){return!!this._animation_take},
enumerable:!1});Bb.prototype.execute=function(a,b,c,e){if(!this._animation_name||!this._take_name)return!1;if(this._must_update){var g=d.ResourcesManager.get(this._animation_name);if(!g)return!1;this._animation_take=g.takes[this._take_name]}if(this._animation_take)return this._animation_take.applyTracks(this.time,this._last_time,b,c,e,a),this._last_time=this.time,!0};Fb.Entry=Bb;sb.prototype.add=function(a,b){var c=this.root;c.push(a);this.objects_cell_by_id.set(a,c);return a.uid};sb.prototype.updateBounding=
function(a,b){};sb.prototype.remove=function(a,b){var c=this.objects_cell_by_id.get(a);if(c){var e=c.indexOf(a);-1!==e&&c.splice(e,1);this.objects_cell_by_id["delete"](a)}};sb.prototype.retrieve=function(a){return this.root};sb.prototype.retrieveFromCamera=function(a){return this.root};sb.prototype.clear=function(){this.root.length=0;this.objects_cell_by_id=new WeakMap};d.SpatialContainer=sb;Ta.AUTO_QUALITY=0;Ta.HIGH_QUALITY=1;Ta.MEDIUM_QUALITY=2;Ta.LOW_QUALITY=3;Ta.default_shadowmap_resolution=1024;
Ta["@default_shadowmap_resolution"]={widget:"combo",values:[0,256,512,1024,2048,4096]};Ta["@layers"]={type:"layers"};Ta.prototype.serialize=function(){return d.cloneObject(this)};Ta.prototype.configure=function(a){if(a)for(var b in a)this[b]=a[b];null===this.layers&&(this.layers=255)};Ta.prototype.toJSON=Ta.prototype.serialize;d.RenderSettings=Ta;Object.defineProperty(A.prototype,"front_face",{set:function(a){this._data[0]=a},get:function(){return this._data[0]},enumerable:!0});A.SKIP_BLEND=1;A.SKIP_DEPTH=
2;A.SKIP_STENCIL=4;A["@front_face"]={widget:"combo",values:{CW:GL.CW,CCW:GL.CCW}};Object.defineProperty(A.prototype,"cull_face",{set:function(a){this._data[1]=a?1:0},get:function(){return 0!==this._data[1]},enumerable:!0});Object.defineProperty(A.prototype,"cull_face_mode",{set:function(a){this._data[2]=a},get:function(){return this._data[2]},enumerable:!0});A["@cull_face_mode"]={widget:"combo",values:{FRONT:GL.FRONT,BACK:GL.BACK,FRONT_AND_BACK:GL.FRONT_AND_BACK}};Object.defineProperty(A.prototype,
"depth_test",{set:function(a){this._data[4]=a?1:0},get:function(){return 0!==this._data[4]},enumerable:!0});Object.defineProperty(A.prototype,"depth_mask",{set:function(a){this._data[5]=a?1:0},get:function(){return 0!==this._data[5]},enumerable:!0});Object.defineProperty(A.prototype,"depth_func",{set:function(a){this._data[6]=a},get:function(){return this._data[6]},enumerable:!0});A["@depth_func"]={widget:"combo",values:{LESS:GL.LESS,LEQUAL:GL.LEQUAL,EQUAL:GL.EQUAL,NOTEQUAL:GL.NOTEQUAL,GREATER:GL.GREATER,
GEQUAL:GL.GEQUAL,ALWAYS:GL.ALWAYS,NEVER:GL.NEVER}};Object.defineProperty(A.prototype,"depth_range",{set:function(a){a&&2==a.length&&(this._data[7]=a[0],this._data[8]=a[1])},get:function(){return this._data.subarray(7,9)},enumerable:!0});Object.defineProperty(A.prototype,"blend",{set:function(a){this._data[9]=a?1:0},get:function(){return 0!==this._data[9]},enumerable:!0});Object.defineProperty(A.prototype,"blendFunc0",{set:function(a){this._data[10]=a},get:function(){return this._data[10]},enumerable:!0});
A["@blendFunc0"]={widget:"combo",values:{ZERO:GL.ZERO,ONE:GL.ONE,SRC_COLOR:GL.SRC_COLOR,ONE_MINUS_SRC_COLOR:GL.ONE_MINUS_SRC_COLOR,DST_COLOR:GL.DST_COLOR,ONE_MINUS_DST_COLOR:GL.ONE_MINUS_DST_COLOR,SRC_ALPHA:GL.SRC_ALPHA,ONE_MINUS_SRC_ALPHA:GL.ONE_MINUS_SRC_ALPHA,DST_ALPHA:GL.DST_ALPHA,ONE_MINUS_DST_ALPHA:GL.ONE_MINUS_DST_ALPHA,CONSTANT_COLOR:GL.CONSTANT_COLOR,ONE_MINUS_CONSTANT_COLOR:GL.ONE_MINUS_CONSTANT_COLOR,CONSTANT_ALPHA:GL.CONSTANT_ALPHA,ONE_MINUS_CONSTANT_ALPHA:GL.ONE_MINUS_CONSTANT_ALPHA,
SRC_ALPHA_SATURATE:GL.SRC_ALPHA_SATURATE}};Object.defineProperty(A.prototype,"blendFunc1",{set:function(a){this._data[11]=a},get:function(){return this._data[11]},enumerable:!0});A["@blendFunc1"]={widget:"combo",values:{ZERO:GL.ZERO,ONE:GL.ONE,SRC_COLOR:GL.SRC_COLOR,ONE_MINUS_SRC_COLOR:GL.ONE_MINUS_SRC_COLOR,DST_COLOR:GL.DST_COLOR,ONE_MINUS_DST_COLOR:GL.ONE_MINUS_DST_COLOR,SRC_ALPHA:GL.SRC_ALPHA,ONE_MINUS_SRC_ALPHA:GL.ONE_MINUS_SRC_ALPHA,DST_ALPHA:GL.DST_ALPHA,ONE_MINUS_DST_ALPHA:GL.ONE_MINUS_DST_ALPHA,
CONSTANT_COLOR:GL.CONSTANT_COLOR,ONE_MINUS_CONSTANT_COLOR:GL.ONE_MINUS_CONSTANT_COLOR,CONSTANT_ALPHA:GL.CONSTANT_ALPHA,ONE_MINUS_CONSTANT_ALPHA:GL.ONE_MINUS_CONSTANT_ALPHA,SRC_ALPHA_SATURATE:GL.SRC_ALPHA_SATURATE}};Object.defineProperty(A.prototype,"blendFunc",{set:function(a){a&&2==a.length&&(this._data[10]=a[0],this._data[11]=a[1])},get:function(){return this._data.subarray(10,12)},enumerable:!1});Object.defineProperty(A.prototype,"colorMask0",{set:function(a){this._data[12]=a?1:0},get:function(){return 0!==
this._data[12]},enumerable:!0});Object.defineProperty(A.prototype,"colorMask1",{set:function(a){this._data[13]=a?1:0},get:function(){return 0!==this._data[13]},enumerable:!0});Object.defineProperty(A.prototype,"colorMask2",{set:function(a){this._data[14]=a?1:0},get:function(){return 0!==this._data[14]},enumerable:!0});Object.defineProperty(A.prototype,"colorMask3",{set:function(a){this._data[15]=a?1:0},get:function(){return 0!==this._data[15]},enumerable:!0});Object.defineProperty(A.prototype,"colorMask",
{set:function(a){a&&4==a.length&&(this._data[12]=a[0],this._data[13]=a[1],this._data[14]=a[2],this._data[15]=a[3])},get:function(){return this._data.subarray(12,16)},enumerable:!1});Object.defineProperty(A.prototype,"stencil_test",{set:function(a){this._data[16]=a?1:0},get:function(){return 0!==this._data[16]},enumerable:!0});Object.defineProperty(A.prototype,"stencil_mask",{set:function(a){this._data[17]=a},get:function(){return this._data[17]},enumerable:!0});Object.defineProperty(A.prototype,"skip_blend",
{set:function(a){this._data[25]=a?this._data[25]|A.SKIP_BLEND:this._data[25]&~A.SKIP_BLEND},get:function(){return Boolean(this._data[25]&A.SKIP_BLEND)},enumerable:!0});Object.defineProperty(A.prototype,"skip_depth",{set:function(a){this._data[25]=a?this._data[25]|A.SKIP_DEPTH:this._data[25]&~A.SKIP_DEPTH},get:function(){return Boolean(this._data[25]&A.SKIP_DEPTH)},enumerable:!0});Object.defineProperty(A.prototype,"skip_stencil",{set:function(a){this._data[25]=a?this._data[25]|A.SKIP_STENCIL:this._data[25]&
~A.SKIP_STENCIL},get:function(){return Boolean(this._data[25]&A.SKIP_STENCIL)},enumerable:!0});A["@stencil_mask"]={widget:"number",min:0,max:256,step:1,precision:0};Object.defineProperty(A.prototype,"stencil_func",{set:function(a){a&&3==a.length&&(this._data[18]=a[0],this._data[19]=a[1],this._data[20]=a[2])},get:function(){return this._data.subarray(18,21)},enumerable:!1});Object.defineProperty(A.prototype,"stencil_func_func",{set:function(a){this._data[18]=a},get:function(){return this._data[18]},
enumerable:!0});A["@stencil_func_func"]={widget:"combo",values:{LESS:GL.LESS,LEQUAL:GL.LEQUAL,EQUAL:GL.EQUAL,NOTEQUAL:GL.NOTEQUAL,GREATER:GL.GREATER,GEQUAL:GL.GEQUAL,ALWAYS:GL.ALWAYS,NEVER:GL.NEVER}};Object.defineProperty(A.prototype,"stencil_func_ref",{set:function(a){this._data[19]=a},get:function(){return this._data[19]},enumerable:!0});A["@stencil_func_ref"]={widget:"number",min:0,max:256,step:1,precision:0};Object.defineProperty(A.prototype,"stencil_func_mask",{set:function(a){this._data[20]=
a},get:function(){return this._data[20]},enumerable:!0});A["@stencil_func_mask"]={widget:"number",min:0,max:256,step:1,precision:0};Object.defineProperty(A.prototype,"stencil_op",{set:function(a){a&&3==a.length&&(this._data[21]=a[0],this._data[22]=a[1],this._data[23]=a[2])},get:function(){return this._data.subarray(21,24)},enumerable:!1});Object.defineProperty(A.prototype,"stencil_op_sfail",{set:function(a){this._data[21]=a},get:function(){return this._data[21]},enumerable:!0});A["@stencil_op_sfail"]=
{widget:"combo",values:{KEEP:GL.KEEP,ZERO:GL.ZERO,REPLACE:GL.REPLACE,INCR:GL.INCR,INCR_WRAP:GL.INCR_WRAP,DECR:GL.DECR_WRAP,INVERT:GL.INVERT}};Object.defineProperty(A.prototype,"stencil_op_dpfail",{set:function(a){this._data[22]=a},get:function(){return this._data[22]},enumerable:!0});A["@stencil_op_dpfail"]={widget:"combo",values:{KEEP:GL.KEEP,ZERO:GL.ZERO,REPLACE:GL.REPLACE,INCR:GL.INCR,INCR_WRAP:GL.INCR_WRAP,DECR:GL.DECR_WRAP,INVERT:GL.INVERT}};Object.defineProperty(A.prototype,"stencil_op_dppass",
{set:function(a){this._data[23]=a},get:function(){return this._data[23]},enumerable:!0});Object.defineProperty(A.prototype,"flags",{set:function(a){this._data[24]=a},get:function(){return this._data[24]},enumerable:!0});A["@stencil_op_dppass"]={widget:"combo",values:{KEEP:GL.KEEP,ZERO:GL.ZERO,REPLACE:GL.REPLACE,INCR:GL.INCR,INCR_WRAP:GL.INCR_WRAP,DECR:GL.DECR_WRAP,INVERT:GL.INVERT}};A.default_state={front_face:GL.CCW,cull_face:!0,depth_test:!0,depth_func:GL.LESS,depth_mask:!0,blend:!1,blendFunc0:GL.SRC_ALPHA,
blendFunc1:GL.ONE_MINUS_SRC_ALPHA,colorMask0:!0,colorMask1:!0,colorMask2:!0,colorMask3:!0,stencil_test:!1,stencil_mask:255,stencil_func_func:GL.ALWAYS,stencil_func_ref:0,stencil_func_mask:255,stencil_op_sfail:GL.KEEP,stencil_op_dpfail:GL.KEEP,stencil_op_dppass:GL.KEEP};A.last_state=null;A.prototype.init=function(){this.front_face=GL.CCW;this.depth_mask=this.depth_test=this.cull_face=!0;this.depth_func=GL.LESS;this.blend=!1;this.blendFunc0=GL.SRC_ALPHA;this.blendFunc1=GL.ONE_MINUS_SRC_ALPHA;this.colorMask3=
this.colorMask2=this.colorMask1=this.colorMask0=!0;this.stencil_test=!1;this.stencil_mask=255;this.stencil_func_func=GL.ALWAYS;this.stencil_func_ref=0;this.stencil_func_mask=255;this.stencil_op_dppass=this.stencil_op_dpfail=this.stencil_op_sfail=GL.KEEP;this.flags=0};A.prototype.setBlendMode=function(a){a&&a!=d.Blend.NORMAL?(this.blend=!0,this.blendFunc0=a[0],this.blendFunc1=a[1]):this.blend=!1};A.prototype.enable=function(a){A.enable(this,null,a)};A.enable=function(a,b,c){var e=a.flags;c=c&&c.force_two_sided?
!0:!1;if(b){d.Renderer._reverse_faces?gl.frontFace(a.front_face==GL.CCW?GL.CW:GL.CCW):b.front_face!==a.front_face&&gl.frontFace(a.front_face);if(b.cull_face!==a.cull_face||c)a.cull_face&&!c?gl.enable(gl.CULL_FACE):gl.disable(gl.CULL_FACE);e&A.SKIP_DEPTH||(b.depth_test!==a.depth_test&&(a.depth_test?gl.enable(gl.DEPTH_TEST):gl.disable(gl.DEPTH_TEST)),b.depth_mask!==a.depth_mask&&gl.depthMask(a.depth_mask),b.depth_func!==a.depth_func&&gl.depthFunc(a.depth_func));e&A.SKIP_BLEND||(b.blend!==a.blend&&(a.blend?
gl.enable(gl.BLEND):gl.disable(gl.BLEND)),b.blendFunc0===a.blendFunc0&&b.blendFunc1===a.blendFunc1||gl.blendFunc(a.blendFunc0,a.blendFunc1));b.colorMask0===a.colorMask0&&b.colorMask1===a.colorMask1&&b.colorMask2===a.colorMask2&&b.colorMask3===a.colorMask3||gl.colorMask(a.colorMask0,a.colorMask1,a.colorMask2,a.colorMask3);e&A.SKIP_STENCIL||(b.stencil_test!=a.stencil_test&&(a.stencil_test?gl.enable(gl.STENCIL_TEST):gl.disable(gl.STENCIL_TEST)),a.stencil_test&&(a.stencil_func_func===b.stencil_func_func&&
a.stencil_func_ref===b.stencil_func_ref&&a.stencil_func_mask===b.stencil_func_mask||gl.stencilFunc(a.stencil_func_func,a.stencil_func_ref,a.stencil_func_mask),a.stencil_op_sfail===b.stencil_op_sfail&&a.stencil_op_dpfail===stencil_op_dpfail&&a.stencil_op_dppass===stencil_op_dppass||gl.stencilOp(a.stencil_op_sfail,a.stencil_op_dpfail,a.stencil_op_dppass),a.stencil_mask!==b.stencil_mask&&gl.stencilMask(b.stencil_mask)))}else d.Renderer._reverse_faces?gl.frontFace(a.front_face==GL.CCW?GL.CW:GL.CCW):gl.frontFace(a.front_face),
a.cull_face&&!c?gl.enable(gl.CULL_FACE):gl.disable(gl.CULL_FACE),e&A.SKIP_DEPTH||(a.depth_test?gl.enable(gl.DEPTH_TEST):gl.disable(gl.DEPTH_TEST),gl.depthMask(a.depth_mask),gl.depthFunc(a.depth_func)),e&A.SKIP_BLEND||(a.blend?gl.enable(gl.BLEND):gl.disable(gl.BLEND),gl.blendFunc(a.blendFunc0,a.blendFunc1)),gl.colorMask(a.colorMask0,a.colorMask1,a.colorMask2,a.colorMask3),e&A.SKIP_STENCIL||(a.stencil_test?(gl.enable(gl.STENCIL_TEST),gl.stencilFunc(a.stencil_func_func,a.stencil_func_ref,a.stencil_func_mask),
gl.stencilOp(a.stencil_op_sfail,a.stencil_op_dpfail,a.stencil_op_dppass),gl.stencilMask(a.stencil_mask)):gl.disable(gl.STENCIL_TEST));this.last_state=a};A.reset=function(){this.enable(this.default_state)};A.prototype.serialize=function(){return d.cloneObject(this)};A.prototype.toJSON=A.prototype.serialize;A.prototype.configure=function(a){d.cloneObject(a,this)};A.prototype.copyFrom=function(a){this._data.set(a._data)};d.RenderState=A;gb.prototype.draw=function(){this.renderState.enable();this.shader.uniforms(this.uniforms).drawBuffers(this.vertex_buffers,
this.index_buffer,this.primitive,this.offset_start,this.offset_range)};gb.pool=[];gb.get=function(){return 0<gb.pool.length?gb.pool.pop():new gb};gb.prototype.release=function(){gb.pool.push(this)};ja.NO_SORT=0;ja.SORT_NEAR_FIRST=1;ja.SORT_FAR_FIRST=2;ja.fast_normalmatrix=!1;ja.prototype.fromNode=function(a){if(!a)throw"no node";this.node=a;a.transform?this.setMatrix(a.transform._global_matrix):this.setMatrix(d.IDENTITY);mat4.multiplyVec3(this.position,this.matrix,d.ZEROS);this.layers=a.layers};ja.prototype.setMatrix=
function(a,b){this.matrix.set(a);b?this.normal_matrix.set(b):this.computeNormalMatrix()};ja.prototype.computeNormalMatrix=function(){if(ja.fast_normalmatrix)this.normal_matrix.set(this.matrix),mat4.setTranslation(this.normal_matrix,d.ZEROS);else{var a=mat4.invert(this.normal_matrix,this.matrix);a&&mat4.transpose(this.normal_matrix,a)}};ja.prototype.applyTransform=function(a,b){mat4.mul(this.matrix,this.matrix,a);b?mat4.mul(this.normal_matrix,this.normal_matrix,b):this.computeNormalMatrix()};ja.prototype.setMaterial=
function(a){(!a||a.constructor.is_material)&&(this.material=a)&&a.applyToRenderInstance&&a.applyToRenderInstance(this)};ja.prototype.setMesh=function(a,b){if(-1==b||void 0===b)b=gl.TRIANGLES;this.primitive=b;a!=this.mesh&&(this.mesh=a,this.vertex_buffers={});if(this.mesh){for(var c in a.vertexBuffers)this.vertex_buffers[c]=a.vertexBuffers[c];switch(b){case gl.TRIANGLES:this.index_buffer=a.indexBuffers.triangles;break;case gl.LINES:this.index_buffer=a.indexBuffers.lines;break;case 10:this.primitive=
gl.LINES;a.indexBuffers.wireframe||a.computeWireframe();this.index_buffer=a.indexBuffers.wireframe;break;default:this.index_buffer=null}a.bounding?(this.oobb.set(a.bounding),this.use_bounding=!0):this.use_bounding=!1}};ja.prototype.setBoundingBox=function(a){this.oobb.set(a)};ja.prototype.setRange=function(a,b){this.range[0]=a;this.range[1]=b};ja.prototype.enableFlag=function(a){this.flags|=a};ja.prototype.disableFlag=function(a){this.flags&=~a};ja.prototype.isFlag=function(a){return this.flags&a};
ja.prototype.updateAABB=function(){BBox.transformMat4(this.aabb,this.oobb,this.matrix)};ja.prototype.update=function(){this.node&&this.node.transform&&this.setMatrix(this.node.transform._global_matrix)};ja.prototype.render=function(a,b){a.attributes.a_normal&&!this.vertex_buffers.normals&&(this.mesh.computeNormals(),this.vertex_buffers.normals=this.mesh.vertexBuffers.normals);a.attributes.a_tangent&&!this.vertex_buffers.tangents&&(this.mesh.computeTangents(),this.vertex_buffers.tangents=this.mesh.vertexBuffers.tangents);
a.attributes.a_coord1&&!this.vertex_buffers.coords1&&(this.mesh.createVertexBuffer("coords1",2,vertex_buffers.coords.data),this.vertex_buffers.coords1=this.mesh.vertexBuffers.coords1);a.attributes.a_normal&&!this.vertex_buffers.normals&&(this.mesh.computeNormals(),this.vertex_buffers.normals=this.mesh.vertexBuffers.normals);a.attributes.a_extra&&!this.vertex_buffers.extra&&(this.mesh.createVertexBuffer("extra","a_extra",1),this.vertex_buffers.extra=this.mesh.vertexBuffers.extra);a.attributes.a_extra2&&
!this.vertex_buffers.extra2&&(this.mesh.createVertexBuffer("extra2","a_extra2",2),this.vertex_buffers.extra2=this.mesh.vertexBuffers.extra2);a.attributes.a_extra3&&!this.vertex_buffers.extra3&&(this.mesh.createVertexBuffer("extra3","a_extra3",3),this.vertex_buffers.extra3=this.mesh.vertexBuffers.extra3);a.attributes.a_color&&!this.vertex_buffers.colors&&(this.mesh.createVertexBuffer("colors","a_color",4),this.vertex_buffers.colors=this.mesh.vertexBuffers.colors);a.drawBuffers(this.vertex_buffers,
this.index_buffer,void 0!==b?b:this.primitive,this.range[0],this.range[1])};ja.prototype.addShaderBlock=function(a,b){if(!(a.flag_mask&this.shader_block_flags&&void 0===b)){for(var c=0;c<this.shader_blocks.length;++c)if(this.shader_blocks[c]&&this.shader_blocks[c].block==a)return void 0!==b&&(this.shader_blocks[c].uniforms=b),c;this.shader_blocks.push({block:a,uniforms:b});this.shader_block_flags|=a.flag_mask;return this.shader_blocks.length-1}};ja.prototype.disableShaderBlock=function(a){if(a.flag_mask&
this.shader_block_flags)for(var b=0;b<this.shader_blocks.length;++b)if(this.shader_blocks[b]&&this.shader_blocks[b].block===a){this.shader_block_flags&=~a.flag_mask;break}};ja.prototype.removeShaderBlock=function(a){if(a.flag_mask&this.shader_block_flags)for(var b=0;b<this.shader_blocks.length;++b)if(this.shader_blocks[b]&&this.shader_blocks[b].block===a){this.shader_blocks.splice(b,1);this.shader_block_flags&=~a.flag_mask;break}};ja.prototype.computeShaderBlockFlags=function(){return this.shader_block_flags};
ja.prototype.overlapsSphere=function(a,b){return this.use_bounding?geo.testSphereBBox(a,b,this.aabb):!0};ja.prototype.wasVisibleByCamera=function(a){return a?this._camera_visibility|1<<a._rendering_index?!0:!1:0!=this._camera_visibility};d.RenderInstance=ja;P.current=null;P.stack=[];P.DEFAULT_PRECISION=0;P.LOW_PRECISION=1;P.MEDIUM_PRECISION=2;P.HIGH_PRECISION=3;P.DEFAULT_PRECISION_WEBGL_TYPE=GL.UNSIGNED_BYTE;P["@width"]={type:"number",step:1,precision:0};P["@height"]={type:"number",step:1,precision:0};
P["@precision"]={widget:"combo",values:{"default":P.DEFAULT_PRECISION,low:P.LOW_PRECISION,medium:P.MEDIUM_PRECISION,high:P.HIGH_PRECISION}};P["@format"]={widget:"combo",values:{RGB:GL.RGB,RGBA:GL.RGBA}};P["@num_extra_textures"]={type:"number",step:1,min:0,max:4,precision:0};P["@name"]={type:"string"};P.prototype.clear=function(){if(this.name){for(var a=0;a<this._textures.length;++a)delete d.ResourcesManager.textures[this.name+(1<a?a:"")];this._depth_texture&&delete d.ResourcesManager.textures[this.name+
"_depth"]}this._fbo=null;this._textures=[];this._depth_textures=this._color_texture=null};P.prototype.configure=function(a){this.width=a.width||0;this.height=a.height||0;this.format=a.format||GL.RGBA;this.precision=a.precision||0;this.filter_texture=!!a.filter_texture;this.adjust_aspect=!!a.adjust_aspect;this.use_depth_texture=!!a.use_depth_texture;this.use_stencil_buffer=!!a.use_stencil_buffer;this.num_extra_textures=a.num_extra_textures||0;this.name=a.name;this.clone_after_unbind=!!a.clone_after_unbind};
P.prototype.serialize=function(){return{width:this.width,height:this.height,filter_texture:this.filter_texture,precision:this.precision,format:this.format,adjust_aspect:this.adjust_aspect,use_depth_texture:this.use_depth_texture,use_stencil_buffer:this.use_stencil_buffer,num_extra_textures:this.num_extra_textures,clone_after_unbind:this.clone_after_unbind,name:this.name}};P.prototype.prepare=function(a,b){var c=this.width,e=this.height;0==c?c=a:0>c&&(c=a>>Math.abs(this.width));0==e?e=b:0>e&&(e=b>>
Math.abs(this.height));var d=this.format,f=this.filter_texture?gl.LINEAR:gl.NEAREST,h=0,k=gl.LINEAR;this.generate_mipmaps&&GL.isPowerOfTwo(c)&&GL.isPowerOfTwo(e)&&(k=gl.LINEAR_MIPMAP_LINEAR);this._minFilter=k;switch(this.precision){case P.LOW_PRECISION:h=gl.UNSIGNED_BYTE;break;case P.MEDIUM_PRECISION:h=gl.HIGH_PRECISION_FORMAT;break;case P.HIGH_PRECISION:h=gl.FLOAT;break;case P.DEFAULT_PRECISION:h=P.DEFAULT_PRECISION_WEBGL_TYPE;break;default:h=this.precision}h!=GL.HALF_FLOAT_OES||GL.FBO.testSupport(h,
d)||(d=gl.RGBA);h!=GL.HALF_FLOAT_OES||GL.FBO.testSupport(h,d)||(h=gl.FLOAT);var l=this._textures;this._color_texture&&this._color_texture.width==c&&this._color_texture.height==e&&this._color_texture.type==h&&this._color_texture.format==d&&this._color_texture.minFilter==k?this._color_texture.setParameter(gl.TEXTURE_MAG_FILTER,f):this._color_texture=new GL.Texture(c,e,{minFilter:k,magFilter:f,format:d,type:h});l[0]=this._color_texture;var n=Math.min(this.num_extra_textures,4);1!=gl.webgl_version||gl.extensions.WEBGL_draw_buffers||
(n=0);for(var p=0;p<n;++p){var m=l[1+p];m&&m.width==c&&m.height==e&&m.type==h&&m.format==d&&m.minFilter==k?m.setParameter(gl.TEXTURE_MAG_FILTER,f):m=new GL.Texture(c,e,{minFilter:k,magFilter:f,format:d,type:h});l[1+p]=m}d=gl.DEPTH_COMPONENT;f=gl.UNSIGNED_INT;this.use_stencil_buffer&&gl.extensions.WEBGL_depth_texture&&(d=gl.DEPTH_STENCIL,f=gl.extensions.WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL);!this.use_depth_texture||this._depth_texture&&this._depth_texture.width==c&&this._depth_texture.height==
e&&this._depth_texture.format==d&&this._depth_texture.type==f||!gl.extensions.WEBGL_depth_texture?this.use_depth_texture||(this._depth_texture=null):this._depth_texture=new GL.Texture(c,e,{filter:gl.NEAREST,format:d,type:f});this._depth_texture&&!this._depth_texture.near_far_planes&&(this._depth_texture.near_far_planes=vec2.create());this._fbo||(this._fbo=new GL.FBO);l.length=1+n;this._fbo.stencil=this.use_stencil_buffer;this._fbo.setTextures(l,this._depth_texture);this._version+=1};P.prototype.enable=
function(a,b,c){b=b||gl.viewport_data;this.prepare(b[2],b[3]);if(!this._fbo)throw"No FBO created in RenderFrameContext";P.enableFBO(this._fbo,this.adjust_aspect);d.RenderFrameContext.current&&P.stack.push(d.RenderFrameContext.current);d.RenderFrameContext.current=this;c=c||d.Renderer._current_camera;this._depth_texture&&c&&(this._depth_texture.near_far_planes[0]=c.near,this._depth_texture.near_far_planes[1]=c.far)};P.prototype.cloneBuffers=function(){gl.bindFramebuffer(gl.FRAMEBUFFER,null);if(this._textures.length){this._cloned_textures||
(this._cloned_textures=[]);var a=this._textures;this._cloned_textures.length=a.length;for(var b=0;b<a.length;++b){var c=a[b],e=this._cloned_textures[b];e&&e.hasSameSize(c)&&e.hasSameProperties(c)||(e=this._cloned_textures[b]=new GL.Texture(c.width,c.height,c.getProperties()));c.copyTo(e);0==b&&(d.ResourcesManager.textures[":color_buffer"]=e)}}this._depth_texture&&(a=this._depth_texture,this._cloned_depth_texture&&this._cloned_depth_texture.width==a.width&&this._cloned_depth_texture.height==a.height&&
this._cloned_depth_texture.hasSameProperties(a)||(this._cloned_depth_texture=new GL.Texture(a.width,a.height,a.getProperties())),a.copyTo(this._cloned_depth_texture),d.ResourcesManager.textures[":depth_buffer"]=this._cloned_depth_texture);gl.bindFramebuffer(gl.FRAMEBUFFER,this._fbo.handler)};P.prototype.disable=function(){P.disableFBO(this._fbo);if(this.name){for(var a=this._textures,b=0;b<a.length;++b){var c=this.name+(0<b?b:"");a[b].filename=c;var e=a[b];this.clone_after_unbind&&0===b&&(this._cloned_texture&&
this._cloned_texture.width===e.width&&this._cloned_texture.height===e.height&&this._cloned_texture.type===e.type?e.copyTo(this._cloned_texture):this._cloned_texture=e.clone(),e=this._cloned_texture);this._minFilter==gl.LINEAR_MIPMAP_LINEAR&&(e.bind(0),gl.generateMipmap(gl.TEXTURE_2D),e.has_mipmaps=!0);d.ResourcesManager.textures[c]=e}this._depth_texture&&(c=this.name+"_depth",this._depth_texture.filename=c,d.ResourcesManager.textures[c]=this._depth_texture)}d.RenderFrameContext.current=P.stack.length?
P.stack.pop():null};P.prototype.getColorTexture=function(a){return this._textures[a||0]||null};P.prototype.getDepthTexture=function(){return this._depth_texture||null};P.prototype.clearTextures=function(){for(var a=0;a<this._textures.length;++a){var b=this._textures[a];b&&b.fill([0,0,0,0])}};P.enableFBO=function(a,b){a.bind(!0);d.Renderer._full_viewport.set(gl.viewport_data);b?(a._old_aspect=d.Renderer.global_aspect,d.Renderer.global_aspect=gl.canvas.width/gl.canvas.height/(a.color_textures[0].width/
a.color_textures[0].height)):delete a._old_aspect};P.disableFBO=function(a){a.unbind();d.Renderer._full_viewport.set(a._old_viewport);a._old_aspect&&(d.Renderer.global_aspect=a._old_aspect)};P.prototype.show=function(a){var b=this._color_texture;if(a){a=gl.getViewport();var c=GL.Shader.getFXAAShader(),e=GL.Mesh.getScreenQuad();b.bind(0);c.uniforms({u_texture:0,uViewportSize:a.subarray(2,4),u_iViewportSize:[1/b.width,1/b.height]}).draw(e)}else b.toViewport()};P.reset=function(){gl.bindFramebuffer(gl.FRAMEBUFFER,
null);d.RenderFrameContext.current=null;d.RenderFrameContext.stack.length=0};d.RenderFrameContext=P;Ba.prototype.sort=function(){var a=null;switch(this.sort_mode){case 1:a=d.RenderQueue.sort_near_to_far_func;break;case 2:a=d.RenderQueue.sort_far_to_near_func;break;case 3:a=d.RenderQueue.sort_by_priority_func}a&&this.instances.sort(a)};Ba.prototype.add=function(a){this.instances.push(a)};Ba.prototype.clear=function(){this.instances.length=0};Ba.DEFAULT=0;Ba.BACKGROUND=5;Ba.GEOMETRY=10;Ba.TRANSPARENT=
15;Ba.READBACK_COLOR=20;Ba.OVERLAY=25;Ba.NO_SORT=0;Ba.SORT_NEAR_TO_FAR=1;Ba.SORT_FAR_TO_NEAR=2;Ba.SORT_BY_PRIORITY=3;Ba.sort_far_to_near_func=function(a,b){return b._dist-a._dist};Ba.sort_near_to_far_func=function(a,b){return a._dist-b._dist};Ba.sort_by_priority_func=function(a,b){return b.priority-a.priority};Ba.sort_by_priority_and_near_to_far_func=function(a,b){var c=b.priority-a.priority;return c?c:a._dist-b._dist};Ba.sort_by_priority_and_far_to_near_func=function(a,b){var c=b.priority-a.priority;
return c?c:b._dist-a._dist};d.RenderQueue=Ba;var tb=d.COLOR_PASS={name:"color",id:1},ec=d.SHADOW_PASS={name:"shadow",id:2},hc=d.PICKING_PASS={name:"picking",id:3};y.BEFORE_RENDER="beforeRender";y.READY_TO_RENDER="readyToRender";y.RENDER_SHADOWS="renderShadows";y.AFTER_VISIBILITY="afterVisibility";y.RENDER_REFLECTIONS="renderReflections";y.BEFORE_RENDER_MAIN_PASS="beforeRenderMainPass";y.ENABLE_FRAME_CONTEXT="enableFrameContext";y.SHOW_FRAME_CONTEXT="showFrameContext";y.AFTER_RENDER="afterRender";
y.BEFORE_RENDER_FRAME="beforeRenderFrame";y.BEFORE_RENDER_SCENE="beforeRenderScene";y.COMPUTE_VISIBILITY="computeVisibility";y.AFTER_RENDER_SCENE="afterRenderScene";y.RENDER_HELPERS="renderHelpers";y.BEFORE_SHOW_FRAME_CONTEXT="beforeShowFrameContext";y.BEFORE_CAMERA_ENABLED="beforeCameraEnabled";y.AFTER_CAMERA_ENABLED="afterCameraEnabled";y.BEFORE_RENDER_INSTANCES="beforeRenderInstances";y.RENDER_INSTANCES="renderInstances";y.RENDER_SCREEN_SPACE="renderScreenSpace";y.AFTER_RENDER_INSTANCES="afterRenderInstances";
y.RENDER_GUI="renderGUI";y.FILL_SCENE_UNIFORMS="fillSceneUniforms";y.AFTER_COLLECT_DATA="afterCollectData";y.PREPARE_MATERIALS="prepareMaterials";var xc={default_render_settings:new d.RenderSettings,default_material:new d.StandardMaterial,global_aspect:1,default_point_size:1,render_profiler:!1,_global_viewport:vec4.create(),_full_viewport:vec4.create(),_current_scene:null,_current_render_settings:null,_current_camera:null,_current_target:null,_current_pass:tb,_global_textures:{},_global_shader_blocks:[],
_global_shader_blocks_flags:0,_reverse_faces:!1,_in_player:!0,_queues:[],_main_camera:null,_visible_cameras:null,_visible_lights:null,_visible_instances:null,_visible_materials:[],_near_lights:[],_active_samples:[],_frame_time:0,_frame_cpu_time:0,_rendercalls:0,_rendered_instances:0,_rendered_passes:0,_frame:0,_last_time:0,gpu_times:{total:0,shadows:0,reflections:0,main:0,postpo:0,gui:0},_timer_queries:{},_waiting_queries:!1,_collect_frequency:1,_view_matrix:mat4.create(),_projection_matrix:mat4.create(),
_viewprojection_matrix:mat4.create(),_2Dviewprojection_matrix:mat4.create(),_temp_matrix:mat4.create(),_temp_cameye:vec3.create(),_identity_matrix:mat4.create(),_uniforms:{},_samplers:[],_instancing_data:[],_is_rendering_frame:!1,_ignore_reflection_probes:!1,allow_textures:!0,_sphere_mesh:null,_debug_instance:null,SHADOWMAP_TEXTURE_SLOT:7,ENVIRONMENT_TEXTURE_SLOT:6,IRRADIANCE_TEXTURE_SLOT:5,LIGHTPROJECTOR_TEXTURE_SLOT:4,LIGHTEXTRA_TEXTURE_SLOT:3,BONES_TEXTURE_SLOT:3,MORPHS_TEXTURE_SLOT:2,MORPHS_TEXTURE2_SLOT:1,
init:function(){this._black_texture=new GL.Texture(1,1,{pixel_data:[0,0,0,255]});this._gray_texture=new GL.Texture(1,1,{pixel_data:[128,128,128,255]});this._white_texture=new GL.Texture(1,1,{pixel_data:[255,255,255,255]});this._normal_texture=new GL.Texture(1,1,{pixel_data:[128,128,255,255]});this._missing_texture=this._gray_texture;[this._black_texture,this._gray_texture,this._white_texture,this._normal_texture,this._missing_texture].forEach(function(a){a._is_internal=!0});d.ResourcesManager.textures[":black"]=
this._black_texture;d.ResourcesManager.textures[":gray"]=this._gray_texture;d.ResourcesManager.textures[":white"]=this._white_texture;d.ResourcesManager.textures[":flatnormal"]=this._normal_texture;this._sphere_mesh=GL.Mesh.sphere({size:1,detail:32});d.Draw&&(d.Draw.init(),d.Draw.onRequestFrame=function(){d.GlobalScene.requestFrame()});da.enableWebGLCanvas&&!gl.canvas.canvas2DtoWebGL_enabled&&da.enableWebGLCanvas(gl.canvas);var a=this._max_texture_units=gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
this.SHADOWMAP_TEXTURE_SLOT=a-2;this.ENVIRONMENT_TEXTURE_SLOT=a-3;this.IRRADIANCE_TEXTURE_SLOT=a-4;this.LIGHTPROJECTOR_TEXTURE_SLOT=a-5;this.LIGHTEXTRA_TEXTURE_SLOT=a-6;this.BONES_TEXTURE_SLOT=a-7;this.MORPHS_TEXTURE_SLOT=a-8;this.MORPHS_TEXTURE2_SLOT=a-9;this._active_samples.length=a;this.createRenderQueue(d.RenderQueue.BACKGROUND,d.RenderQueue.NO_SORT);this.createRenderQueue(d.RenderQueue.GEOMETRY,d.RenderQueue.SORT_NEAR_TO_FAR);this.createRenderQueue(d.RenderQueue.TRANSPARENT,d.RenderQueue.SORT_FAR_TO_NEAR);
this.createRenderQueue(d.RenderQueue.READBACK_COLOR,d.RenderQueue.SORT_FAR_TO_NEAR,{onStart:function(a,c){"color"===c.name&&d.RenderFrameContext.current&&d.RenderFrameContext.current.cloneBuffers()}});this.createRenderQueue(d.RenderQueue.OVERLAY,d.RenderQueue.NO_SORT);this._full_viewport.set([0,0,gl.drawingBufferWidth,gl.drawingBufferHeight]);this._uniforms.u_viewport=gl.viewport_data;this._uniforms.environment_texture=this.ENVIRONMENT_TEXTURE_SLOT;this._uniforms.u_clipping_plane=vec4.create()},reset:function(){},
resetState:function(){this._reverse_faces=this._is_rendering_frame=!1},setFullViewport:function(a,b,c,e){0==arguments.length?(this._full_viewport[0]=this._full_viewport[1]=0,this._full_viewport[2]=gl.drawingBufferWidth,this._full_viewport[3]=gl.drawingBufferHeight):a.constructor===Number?(this._full_viewport[0]=a,this._full_viewport[1]=b,this._full_viewport[2]=c,this._full_viewport[3]=e):a.length&&this._full_viewport.set(a)},render:function(a,b,c){a=a||d.GlobalScene;if(this._is_rendering_frame)console.error("Last frame didn't finish and a new one was issued. Remember that you cannot call LS.Renderer.render from an event dispatched during the render, this would cause a recursive loop. Call LS.Renderer.reset() to clear from an error.");
else{this._is_rendering_frame=!0;this._current_render_settings=b=b||this.default_render_settings;this._current_scene=a;this._main_camera=c?c[0]:null;a._frame+=1;this._frame+=1;a._must_redraw=!1;var e=getTime();this._frame_time=e-this._last_time;this._last_time=e;this._rendered_passes=this._rendered_instances=this._rendercalls=0;this._global_shader_blocks_flags=this._global_shader_blocks.length=0;for(var g in this._global_textures)this._global_textures[g]=null;this._current_pass||(this._current_pass=
tb);this._reverse_faces=!1;this.resolveQueries();b.ignore_reset||d.RenderFrameContext.reset();gl.canvas.canvas2DtoWebGL_enabled&&gl.resetTransform();d.GUI.ResetImmediateGUI(!0);b.keep_viewport?this.setFullViewport(gl.viewport_data):(gl.viewport(0,0,gl.drawingBufferWidth,gl.drawingBufferHeight),this.setFullViewport(0,0,gl.drawingBufferWidth,gl.drawingBufferHeight));this._global_viewport.set(gl.viewport_data);this.startGPUQuery("beforeRender");LEvent.trigger(a,y.BEFORE_RENDER,b);this.endGPUQuery();
this.processVisibleData(a,b,c);c=c&&c.length?c:this._visible_cameras;if(0==c.length)throw"no cameras";this._visible_cameras=c;this._main_camera=c[0];LEvent.trigger(a,y.READY_TO_RENDER,b);this.startGPUQuery("shadows");LEvent.trigger(a,y.RENDER_SHADOWS,b);this.endGPUQuery();LEvent.trigger(a,y.AFTER_VISIBILITY,b);this.startGPUQuery("reflections");LEvent.trigger(a,y.RENDER_REFLECTIONS,b);this.endGPUQuery();LEvent.trigger(a,y.BEFORE_RENDER_MAIN_PASS,b);b.render_fx&&LEvent.trigger(a,y.ENABLE_FRAME_CONTEXT,
b);this.renderFrameCameras(c,b);b.keep_viewport&&gl.setViewport(this._global_viewport);b.render_fx&&(this.startGPUQuery("postpo"),LEvent.trigger(a,y.SHOW_FRAME_CONTEXT,b),this.endGPUQuery());this.startGPUQuery("gui");this.renderGUI(b);this.endGPUQuery();this._frame_cpu_time=getTime()-e;d.Draw&&(this._rendercalls+=d.Draw._rendercalls);d.Draw._rendercalls=0;LEvent.trigger(a,y.AFTER_RENDER,b);this._is_rendering_frame=!1;d.triggerCoroutines("render");this.render_profiler&&this.renderProfiler()}},renderFrameCameras:function(a,
b){for(var c=this._current_scene,e=0;e<a.length;++e){var d=a[e];LEvent.trigger(c,y.BEFORE_RENDER_FRAME,b);LEvent.trigger(d,y.BEFORE_RENDER_FRAME,b);LEvent.trigger(d,y.ENABLE_FRAME_CONTEXT,b);this.startGPUQuery("main");this.renderFrame(d,b);this.endGPUQuery();this.startGPUQuery("postpo");LEvent.trigger(d,y.SHOW_FRAME_CONTEXT,b);LEvent.trigger(d,y.AFTER_RENDER_FRAME,b);LEvent.trigger(c,y.AFTER_RENDER_FRAME,b);this.endGPUQuery()}},renderFrame:function(a,b,c){b=b||this.default_render_settings;c&&(c._frame++,
this.processVisibleData(c,b));this._current_scene=c=c||this._current_scene;this.enableCamera(a,b,b.skip_viewport,c);this.sortRenderQueues(a,b);this.clearBuffer(a,b);LEvent.trigger(c,y.BEFORE_RENDER_SCENE,a);LEvent.trigger(this,y.BEFORE_RENDER_SCENE,a);LEvent.trigger(this,y.COMPUTE_VISIBILITY,this._visible_instances);this.renderInstances(b,this._visible_instances);LEvent.trigger(c,y.AFTER_RENDER_SCENE,a);LEvent.trigger(this,y.AFTER_RENDER_SCENE,a);if(this.onRenderScene)this.onRenderScene(a,b,c);b.render_helpers&&
LEvent.trigger(this,y.RENDER_HELPERS,a)},showRenderFrameContext:function(a,b){LEvent.trigger(this,y.BEFORE_SHOW_FRAME_CONTEXT,a);a.show()},enableCamera:function(a,b,c,e){e=e||this._current_scene||d.GlobalScene;LEvent.trigger(a,y.BEFORE_CAMERA_ENABLED,b);LEvent.trigger(e,y.BEFORE_CAMERA_ENABLED,a);var g=this._full_viewport[0],f=this._full_viewport[1],h=this._full_viewport[2],k=this._full_viewport[3];0==h&&0==k&&(console.warn("enableCamera: full viewport was 0, assigning to full viewport"),h=gl.viewport_data[2],
k=gl.viewport_data[3]);var g=Math.floor(h*a._viewport[0]+g),f=Math.floor(k*a._viewport[1]+f),l=Math.ceil(h*a._viewport[2]),n=Math.ceil(k*a._viewport[3]);c||(b&&b.ignore_viewports?(a.final_aspect=h/k*a._aspect*this.global_aspect,gl.viewport(this._full_viewport[0],this._full_viewport[1],this._full_viewport[2],this._full_viewport[3])):(a.final_aspect=l/n*a._aspect*this.global_aspect,gl.viewport(g,f,l,n)));a._last_viewport_in_pixels.set(gl.viewport_data);a.updateMatrices();mat4.copy(this._view_matrix,
a._view_matrix);mat4.copy(this._projection_matrix,a._projection_matrix);mat4.copy(this._viewprojection_matrix,a._viewprojection_matrix);for(c=0;16>c;++c)isNaN(this._viewprojection_matrix[c])&&console.warn("warning: viewprojection matrix contains NaN when enableCamera is used");mat4.ortho(this._2Dviewprojection_matrix,-1,1,-1,1,1,-1);this._current_camera=a;d.Draw&&(d.Draw.reset(),d.Draw.setCamera(a));LEvent.trigger(a,y.AFTER_CAMERA_ENABLED,b);LEvent.trigger(e,y.AFTER_CAMERA_ENABLED,a)},getCurrentCamera:function(){return this._current_camera},
clearBuffer:function(a,b){b.ignore_clear||!a.clear_color&&!a.clear_depth||(gl.scissor(gl.viewport_data[0],gl.viewport_data[1],gl.viewport_data[2],gl.viewport_data[3]),gl.enable(gl.SCISSOR_TEST),gl.colorMask(!0,!0,!0,!0),gl.clearColor(a.background_color[0],a.background_color[1],a.background_color[2],a.background_color[3]),gl.depthMask(!0),gl.enable(gl.STENCIL_TEST),gl.clearStencil(0),gl.clear((a.clear_color?gl.COLOR_BUFFER_BIT:0)|(a.clear_depth?gl.DEPTH_BUFFER_BIT:0)|gl.STENCIL_BUFFER_BIT),gl.disable(gl.SCISSOR_TEST),
gl.disable(gl.STENCIL_TEST))},sortRenderQueues:function(a,b){var c=this._visible_instances;if(c){for(var e=a.getEye(this._temp_cameye),d=0,f=c.length;d<f;++d){var h=c[d];h&&(h._dist=vec3.dist(h.center,e))}d=0;for(f=this._queues.length;d<f;++d)(c=this._queues[d])&&c.sort_mode&&c.sort()}},resetGLState:function(a){gl.enable(gl.CULL_FACE);gl.frontFace(gl.CCW);gl.colorMask(!0,!0,!0,!0);gl.enable(gl.DEPTH_TEST);gl.depthFunc(gl.LESS);gl.depthMask(!0);gl.disable(gl.BLEND);gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA);
gl.disable(gl.STENCIL_TEST);gl.stencilMask(255);gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);gl.stencilFunc(gl.ALWAYS,1,255)},renderInstances:function(a,b,c){c=c||this._current_scene;if(!c)return console.warn("LS.Renderer.renderInstances: no scene found in LS.Renderer._current_scene"),0;this._rendered_passes+=1;var e=this._current_pass,d=this._current_camera,f=-1!=d._rendering_index?1<<d._rendering_index:0,h=a.frustum_culling,k=d.updateFrustumPlanes(),l=d.layers&a.layers;LEvent.trigger(c,y.BEFORE_RENDER_INSTANCES,
a);this.resetGLState(a);LEvent.trigger(c,y.RENDER_INSTANCES,a);LEvent.trigger(this,y.RENDER_INSTANCES,a);this.resetGLState(a);b=b||this._visible_instances;this.bindSamplers(this._samplers);for(var n=0,p=b.length;n<p;++n){var m=b[n],q=m.node.flags;m._is_visible=!1;e==ec&&!m.material.flags.cast_shadows||e==hc&&!1===q.selectable||0===(l&m.layers)||m.onPreRender&&!1===m.onPreRender(a)||!m.material||(q=d._overwrite_material||m.material,0>=q.opacity||h&&m.use_bounding&&!q.flags.ignore_frustum&&geo.frustumTestBox(k,
m.aabb)==CLIP_OUTSIDE||(m._is_visible=!0,f&&(m._camera_visibility|=f)))}f=this._rendered_instances;h=this._debug_instance;for(k=0;k<this._queues.length;++k)if((l=this._queues[k])&&l.instances.length&&(!l.onStart||!1!==l.onStart(a,e))){b=l.instances;n=0;for(p=b.length;n<p;++n){m=b[n];if(m==h){console.log(h);debugger}if(m._is_visible&&m.mesh){this._rendered_instances+=1;q=d._overwrite_material||m.material;if(e==hc&&q.renderPickingInstance)q.renderPickingInstance(m,a,e);else if(q.renderInstance)q.renderInstance(m,
a,e);else continue;if(m.onPostRender)m.onPostRender(a)}}if(l.onFinish)l.onFinish(a,e)}this.resetGLState(a);LEvent.trigger(c,y.RENDER_SCREEN_SPACE,a);this.resetGLState(a);LEvent.trigger(c,y.AFTER_RENDER_INSTANCES,a);LEvent.trigger(this,y.AFTER_RENDER_INSTANCES,a);this.resetGLState(a);return this._rendered_instances-f},renderGUI:function(a){gl.viewport(this._full_viewport[0],this._full_viewport[1],this._full_viewport[2],this._full_viewport[3]);gl.start2D&&gl.start2D();a.render_gui&&LEvent.hasBind(this._current_scene,
y.RENDER_GUI)&&(d.GUI&&d.GUI.ResetImmediateGUI(),LEvent.trigger(this._current_scene,y.RENDER_GUI,gl));if(this.on_render_gui)this.on_render_gui(a);gl.finish2D&&gl.finish2D()},getNearLights:function(a,b){b=b||[];b.length=0;var c=this._visible_lights;if(!c||!c.length)return b;b.length=0;for(var e=c.length,d=0;d<e;d++){var f=c[d];if(0!=(f.illuminated_layers&a.layers)&&0!=(f.illuminated_layers&this._current_camera.layers)&&!(1E-4>f.computeLightIntensity())){var h=f.computeLightRadius(),k=f.position;(-1==
h||a.overlapsSphere(k,h))&&b.push(f)}}return b},regenerateShadowmaps:function(a,b){a=a||this._current_scene;b=b||this.default_render_settings;LEvent.trigger(a,y.RENDER_SHADOWS,b);for(var c=0;c<this._visible_lights.length;++c){var e=this._visible_lights[c];e.prepare(b);e.onGenerateShadowmap()}},mergeSamplers:function(a,b){b=b||[];b.length=this._max_texture_units;for(var c=0;c<b.length;++c)for(var e=a.length-1;0<=e;--e)if(a[e][c]){b[c]=a[e][c];break}return b},clearSamplers:function(){for(var a=0;a<
this._max_texture_units;++a)gl.activeTexture(gl.TEXTURE0+a),gl.bindTexture(gl.TEXTURE_2D,null),gl.bindTexture(gl.TEXTURE_CUBE_MAP,null),this._active_samples[a]=null},bindSamplers:function(a){if(a)for(var b=this.allow_textures,c=0;c<a.length;++c){var e=a[c];if(e){var g=null;e.constructor===String||e.constructor===GL.Texture?(g=e,e=null):e.texture&&(g=e.texture);g&&g.constructor===String&&(g=d.ResourcesManager.textures[g]);b||(g=null);if(!g)if(e)switch(e.missing){case "black":g=this._black_texture;
break;case "white":g=this._white_texture;break;case "gray":g=this._gray_texture;break;case "normal":g=this._normal_texture;break;default:g=this._missing_texture}else g=this._missing_texture;g._in_current_fbo&&(g=this._missing_texture);g.bind(c);this._active_samples[c]=g;e&&(e.minFilter&&(e.minFilter!==gl.LINEAR_MIPMAP_LINEAR||GL.isPowerOfTwo(g.width)&&GL.isPowerOfTwo(g.height))&&gl.texParameteri(g.texture_type,gl.TEXTURE_MIN_FILTER,e.minFilter),e.magFilter&&gl.texParameteri(g.texture_type,gl.TEXTURE_MAG_FILTER,
e.magFilter),e.wrap&&(gl.texParameteri(g.texture_type,gl.TEXTURE_WRAP_S,e.wrap),gl.texParameteri(g.texture_type,gl.TEXTURE_WRAP_T,e.wrap)),null!=e.anisotropic&&gl.extensions.EXT_texture_filter_anisotropic&&gl.texParameteri(g.texture_type,gl.extensions.EXT_texture_filter_anisotropic.TEXTURE_MAX_ANISOTROPY_EXT,e.anisotropic))}}},fillSceneUniforms:function(a,b){var c=a._uniforms;c.u_time=a._time||0.001*getTime();c.u_ambient_light=a.info?a.info.ambient_color:vec3.create();this._samplers.length=0;this._global_textures.environment=
null;if(a.info)for(var e in a.info.textures)if(c=d.getTexture(a.info.textures[e])){var g=0;if("environment"==e){var g=d.Renderer.ENVIRONMENT_TEXTURE_SLOT,f=c.texture_type==gl.TEXTURE_2D?"_texture":"_cubemap";c.texture_type==gl.TEXTURE_2D&&(c.bind(0),c.setParameter(gl.TEXTURE_MIN_FILTER,gl.LINEAR));this._samplers[g]=c;a._uniforms[e+"_texture"]=g;a._uniforms[e+f]=g;"environment"==e&&(this._global_textures.environment=c)}}LEvent.trigger(a,y.FILL_SCENE_UNIFORMS,a._uniforms)},processVisibleData:function(a,
b,c,e,g){var f=a._frame;this._current_scene=a;this.fillSceneUniforms(a,b);g||(0==this._frame%this._collect_frequency&&a.collectData(c),LEvent.trigger(a,y.AFTER_COLLECT_DATA,a));c=c&&c.length?c:a._cameras;if(0==c.length)console.error("no cameras found");else{g=this._visible_materials;for(var h=g.length=0,k=c.length;h<k;++h){var l=c[h];l._rendering_index=h;l.prepare();if(l.overwrite_material){var n=l.overwrite_material.constructor===String?d.ResourcesManager.resources[l.overwrite_material]:l.overwrite_material;
n&&(l._overwrite_material=n,g.push(n))}else l._overwrite_material=null}this._main_camera||(this._main_camera=c.length?c[0]:new d.Camera);n=a.findNearestReflectionProbe(this._main_camera.getEye());e=e||a._instances;l=this._main_camera;l=l.getEye(this._temp_cameye);for(h=0;h<this._queues.length;++h)this._queues[h]&&this._queues[h].clear();h=0;for(k=e.length;h<k;++h){var p=e[h];if(p)if(p.mesh){p.material||(p.material=this.default_material);p.material._last_frame_update!=f&&(p.material._last_frame_update=
f,g.push(p.material));p._dist=vec3.dist(p.center,l);p._nearest_reflection_probe=a._reflection_probes.length&&!this._ignore_reflection_probes?n:null;b.force_wireframe&&p.primitive!=gl.LINES&&(p.primitive=gl.LINES,p.mesh&&(p.mesh.indexBuffers.wireframe||p.mesh.computeWireframe(),p.index_buffer=p.mesh.indexBuffers.wireframe));var m=p.material.queue,q=null;void 0===m||m===d.RenderQueue.DEFAULT?q=p.material._render_state.blend?this._queues[d.RenderQueue.TRANSPARENT]:this._queues[d.RenderQueue.GEOMETRY]:
(q=this._queues[m])||d.Renderer.createRenderQueue(m);q&&(q.add(p),p._camera_visibility=0)}else console.warn("RenderInstance must always have mesh")}for(h=0;h<g.length;++h)n=g[h],n._index=h,n.prepare&&n.prepare(a);LEvent.trigger(a,y.PREPARE_MATERIALS);h=0;for(k=e.length;h<k;++h)p=e[h],p.index=h;this._visible_instances=a._instances;this._visible_lights=a._lights;this._visible_cameras=c;h=0;for(k=this._visible_lights.length;h<k;++h)this._visible_lights[h].prepare(b);LEvent.trigger(a,y.AFTER_COLLECT_DATA,
a)}},renderInstancesToRT:function(a,b,c,e){function g(){d.Renderer.clearBuffer(a,c);d.Renderer.renderInstances(c,e)}c=c||this.default_render_settings;this._current_target=b;b._in_current_fbo=!0;b.texture_type==gl.TEXTURE_2D?(this.enableCamera(a,c),b.drawTo(g)):b.texture_type==gl.TEXTURE_CUBE_MAP&&this.renderToCubemap(a.getEye(),b.width,b,c,a.near,a.far);this._current_target=null;b._in_current_fbo=!1},renderToCubemap:function(a,b,c,e,g,f,h,k){b=b||256;g=g||1;f=f||1E3;if(e&&e.constructor!==d.RenderSettings)throw"render_settings parameter must be LS.RenderSettings.";
c&&c.constructor==GL.Texture||(c=null);var l=this._current_scene;l||(l=this._current_scene=d.GlobalScene);var n=this._cubemap_camera;n||(n=this._cubemap_camera=new d.Camera);n.configure({fov:90,aspect:1,near:g,far:f});this._current_target=c=c||new GL.Texture(b,b,{texture_type:gl.TEXTURE_CUBE_MAP,minFilter:gl.NEAREST});c._in_current_fbo=!0;c.drawTo(function(b,c){var f=d.Camera.cubemap_camera_parameters[c];b._is_shadowmap||!h?gl.clearColor(0,0,0,0):gl.clearColor(h[0],h[1],h[2],h[3]);gl.clear(gl.COLOR_BUFFER_BIT|
gl.DEPTH_BUFFER_BIT);n.configure({eye:a,center:[a[0]+f.dir[0],a[1]+f.dir[1],a[2]+f.dir[2]],up:f.up});d.Renderer.enableCamera(n,e,!0);d.Renderer.renderInstances(e,k,l)});this._current_target=null;c._in_current_fbo=!1;return c},getCameraAtPosition:function(a,b,c){c=c||this._visible_cameras;if(!c||!c.length)return null;for(var e=c.length-1;0<=e;--e){var d=c[e];if(d.enabled&&!d.render_to_texture&&d.isPoint2DInCameraViewport(a,b))return d}return null},createRenderQueue:function(a,b,c){if(void 0===a)throw"RenderQueue must have index";
b=new d.RenderQueue(b);this._queues[a]&&console.warn("There is already a RenderQueue in slot ",a);this._queues[a]=b;if(c)for(var e in c)b[e]=c[e]},setRenderPass:function(a){a||(a=tb);this._current_pass=a},enableFrameShaderBlock:function(a,b,c){if((a=a.constructor===d.ShaderBlock?a:d.Shaders.getShaderBlock(a))&&!(this._global_shader_blocks_flags&a.flag_mask)){this._global_shader_blocks.push(a);this._global_shader_blocks_flags|=a.flag_mask;if(b)for(var e in b)this._uniforms[e]=b[e];if(c)for(e=0;e<c.length;++e)c[e]&&
(this._samplers[e]=c[e])}},disableFrameShaderBlock:function(a,b,c){(a=a.constructor===d.ShaderBlock?a:d.Shaders.getShaderBlock(a))&&this._global_shader_blocks_flags&a.flag_mask&&(b=this._global_shader_blocks.indexOf(a),-1!=b&&this._global_shader_blocks.splice(b,1),this._global_shader_blocks_flags&=~a.flag_mask)},_current_query:null,startGPUQuery:function(a){if(gl.extensions.disjoint_timer_query&&!this._waiting_queries){var b=gl.extensions.disjoint_timer_query,c=this._timer_queries[a];c||(c=this._timer_queries[a]=
b.createQueryEXT());b.beginQueryEXT(b.TIME_ELAPSED_EXT,c);this._current_query=c}},endGPUQuery:function(){if(gl.extensions.disjoint_timer_query&&!this._waiting_queries){var a=gl.extensions.disjoint_timer_query;a.endQueryEXT(a.TIME_ELAPSED_EXT);this._current_query=null}},resolveQueries:function(){if(gl.extensions.disjoint_timer_query){var a=gl.extensions.disjoint_timer_query,b=this._timer_queries.gui;if(b)if(a.getQueryObjectEXT(b,a.QUERY_RESULT_AVAILABLE_EXT)){if(!gl.getParameter(a.GPU_DISJOINT_EXT)){var b=
0,c;for(c in this._timer_queries){var e=1E-5*a.getQueryObjectEXT(this._timer_queries[c],a.QUERY_RESULT_EXT),b=b+e;this.gpu_times[c]=e}this.gpu_times.total=b}this._waiting_queries=!1}else this._waiting_queries=!0}},profiler_text:[],renderProfiler:function(){if(gl.canvas.canvas2DtoWebGL_enabled){var a=this.profiler_text,b=gl.extensions.disjoint_timer_query;0==this._frame%5&&(a.length=0,a.push((1E3/this._frame_time).toFixed(2)+" FPS"),a.push("CPU: "+this._frame_cpu_time.toFixed(2)+" ms"),a.push(" - Passes: "+
this._rendered_passes),a.push(" - RIs: "+this._rendered_instances),a.push(" - Draws: "+this._rendercalls),b?(a.push("GPU: "+this.gpu_times.total.toFixed(2)),a.push(" - PreRender: "+this.gpu_times.beforeRender.toFixed(2)),a.push(" - Shadows: "+this.gpu_times.shadows.toFixed(2)),a.push(" - Reflections: "+this.gpu_times.reflections.toFixed(2)),a.push(" - Scene: "+this.gpu_times.main.toFixed(2)),a.push(" - Postpo: "+this.gpu_times.postpo.toFixed(2)),a.push(" - GUI: "+this.gpu_times.gui.toFixed(2))):a.push("GPU: ???"));
b=gl;b.save();b.translate(gl.canvas.width-200,gl.canvas.height-280);b.globalAlpha=0.7;b.font="14px Tahoma";b.fillStyle="black";b.fillRect(0,0,200,280);b.fillStyle="white";b.fillText("Profiler",20,20);b.fillStyle="#AFA";for(var c=0;c<a.length;++c)b.fillText(a[c],20,50+20*c);b.restore()}},blit:function(a,b,c,e){if(!a||!b)throw"data missing in blit";if(a!=b)b.drawTo(function(){a.toViewport(c,e)});else{if(!c)throw"blitting texture to the same texture doesnt makes sense unless a shader is specified";b=
GL.Texture.getTemporary(a.width,a.height,a);a.copyTo(b);b.copyTo(a,c,e);GL.Texture.releaseTemporary(b)}}};d.Renderer=xc;Xa.prototype.enable=function(a){this._in_scene||(a=a||d.GlobalScene,LEvent.bind(a,"afterRenderInstances",this.onRender,this),this._in_scene=a)};Xa.prototype.disable=function(a){this._in_scene&&(LEvent.unbind(this._in_scene,"afterRenderInstances",this.onRender,this),this._in_scene=null)};Xa.prototype.onRender=function(a,b){this.render(d.Renderer._current_camera)};Xa.prototype.render=
function(a,b,c){var e=this.settings;c=c||d.GlobalScene;gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA);gl.enable(gl.DEPTH_TEST);gl.disable(gl.BLEND);gl.disable(gl.CULL_FACE);gl.depthFunc(gl.LEQUAL);var g=null;e.render_grid&&0<e.grid_alpha&&this.renderGrid();e.render_origin&&(d.Draw.setColor([0.3,0.3,0.3,1]),d.Draw.push(),d.Draw.scale(0.01,0.01,0.01),d.Draw.rotate(-90,[1,0,0]),gl.blendFunc(gl.SRC_ALPHA,gl.ONE),d.Draw.renderText("Origin"),gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA),d.Draw.pop());
if(e.render_components)for(var f=0,h=c._nodes.length;f<h;++f){var k=c._nodes[f],l=k._is_selected,g=k;k.renderEditor&&k.renderEditor(l);for(var n=0,p=k._components.length;n<p;++n){var m=k._components[n],q=!1;b&&(q=b(m));m.renderEditor&&m.renderEditor(l,q)}}b=vec3.create();f=0;for(h=c._nodes.length;f<h;++f)k=c._nodes[f],!k._is_root&&k.flags.visible&&(l=k.transform?k.transform.getGlobalMatrixRef():mat4.create(),n=mat4.multiplyVec3(vec3.create(),l,b),e.render_null_nodes&&(k._is_selected?this.renderPoint(n,
!0,this.colors.selected):k._is_bone?this.renderPoint(n,!0,this.colors.bone):this.renderPoint(n,!1,this.colors.node)),e.render_names&&this.renderText(n,k.name,k._is_selected?[0.94,0.8,0.4,1]:[0.8,0.8,0.8,0.9]),k._parentNode&&k._parentNode.transform&&(e.render_tree||e.render_skeletons&&k._is_bone&&k._parentNode._is_bone)&&this.renderLine(n,k._parentNode.transform.getGlobalPosition(),this.colors.bone),e.render_axis&&(d.Draw.push(),d.Draw.multMatrix(l),d.Draw.setColor([1,1,1,1]),d.Draw.renderMesh(this.axis_mesh,
gl.LINES),d.Draw.pop()));e.render_colliders&&this.renderColliders(c);e.render_paths&&this.renderPaths(c);this._points.length&&(d.Draw.setPointSize(4),d.Draw.setColor([1,1,1,1]),d.Draw.renderPoints(this._points,this._points_color),this._points.length=0,this._points_color.length=0);this._points_nodepth.length&&(d.Draw.setPointSize(4),d.Draw.setColor([1,1,1,1]),gl.disable(gl.DEPTH_TEST),d.Draw.renderPoints(this._points_nodepth,this._points_color_nodepth),gl.enable(gl.DEPTH_TEST),this._points_nodepth.length=
0,this._points_color_nodepth.length=0);this._lines.length&&(gl.disable(gl.DEPTH_TEST),d.Draw.setColor([1,1,1,1]),d.Draw.renderLines(this._lines,this._lines_color),gl.enable(gl.DEPTH_TEST),this._lines.length=0,this._lines_color.length=0);this.debug_points.length&&(d.Draw.setPointSize(5),d.Draw.setColor([1,0,1,1]),d.Draw.renderPoints(this.debug_points));if(e.render_names&&gl.start2D){gl.disable(gl.DEPTH_TEST);f=this.camera2D;c=gl.getViewport();f.setOrthographic(0,c[2],0,c[3],-1,1);f.updateMatrices();
gl.start2D();gl.font="14px Arial";h=vec4.fromValues(0,0,0,0.5);for(f=0;f<this._names.length;++f)k=a.project(this._names[f][1]),0>k[2]||(k[2]=0,b=gl.measureText(this._names[f][0]),gl.fillColor=h,gl.fillRect(Math.floor(k[0]+10),c[3]-Math.floor(k[1]+8),b.width,b.height),gl.fillColor=this._names[f][2],gl.fillText(this._names[f][0],Math.floor(k[0]+10),c[3]-Math.floor(k[1]-4)));gl.finish2D();this._names.length=0}e.render_axis&&g&&g.transform&&(d.Draw.push(),a=g.transform.getGlobalRotation(),a=mat4.fromQuat(mat4.create(),
a),d.Draw.setMatrix(a),d.Draw.setColor([1,1,1,1]),d.Draw.scale(10,10,10),d.Draw.renderMesh(this.axis_mesh,gl.LINES),d.Draw.pop());gl.depthFunc(gl.LESS)};Xa.prototype.renderPoint=function(a,b,c){c=c||[1,1,1,1];b?(this._points_nodepth.push(a[0],a[1],a[2]),this._points_color_nodepth.push(c[0],c[1],c[2],c[3])):(this._points.push(a[0],a[1],a[2]),this._points_color.push(c[0],c[1],c[2],c[3]))};Xa.prototype.renderLine=function(a,b,c){c=c||[1,1,1,1];this._lines.push(a,b);this._lines_color.push(c,c)};Xa.prototype.renderText=
function(a,b,c){c=c||[1,1,1,1];this._names.push([b,a,c])};Xa.prototype.renderGrid=function(){var a=this.settings;this.grid_shader||(this.grid_shader=d.Draw.createSurfaceShader("vec2 f = vec2(1.0/64.0,-1.0/64.0); float brightness = texture2D(u_texture, pos.xz + f).x * 0.6 + texture2D(u_texture, pos.xz * 0.1 + f ).x * 0.3 + texture2D(u_texture, pos.xz * 0.01 + f ).x * 0.2; brightness /= max(1.0,0.001 * length(u_camera_position.xz - pos.xz));vec4 color = u_color * vec4(vec3(1.0),brightness); if( abs(pos.x) < 0.1 ) color = mix(vec4(0.4,0.4,1.0,0.5),color,abs(pos.x/0.1)); if( abs(pos.z) < 0.1 ) color = mix(vec4(1.0,0.4,0.4,0.5),color,abs(pos.z/0.1)); return color;"),
this.grid_shader_xy=d.Draw.createSurfaceShader("vec2 f = vec2(1.0/64.0,-1.0/64.0); float brightness = texture2D(u_texture, pos.xy + f).x * 0.6 + texture2D(u_texture, pos.xy * 0.1 + f ).x * 0.3 + texture2D(u_texture, pos.xy * 0.01 + f ).x * 0.2; brightness /= max(1.0,0.001 * length(u_camera_position.xy - pos.xy));vec4 color = u_color * vec4(vec3(1.0),brightness);  if( abs(pos.x) < 0.025 ) color *= vec4(0.4,1.0,0.4,1.0); if( abs(pos.y) < 0.025 ) color *= vec4(1.0,0.4,0.4,1.0); return color;"),this.grid_shader_yz=
d.Draw.createSurfaceShader("vec2 f = vec2(1.0/64.0,-1.0/64.0); float brightness = texture2D(u_texture, pos.yz + f).x * 0.6 + texture2D(u_texture, pos.yz * 0.1 + f ).x * 0.3 + texture2D(u_texture, pos.yz * 0.01 + f ).x * 0.2; brightness /= max(1.0,0.001 * length(u_camera_position.yz - pos.yz)); vec4 color = u_color * vec4(vec3(1.0),brightness);  if( abs(pos.y) < 0.025 ) color *= vec4(0.4, 0.4, 1.0, 1.0); if( abs(pos.z) < 0.025 ) color *= vec4(0.4,1.0,0.4,1.0); return color;"),this.grid_shader.uniforms({u_texture:0}),
this.grid_texture=this.grid_img&&this.grid_img.loaded?GL.Texture.fromImage(this.grid_img,{format:gl.RGB,wrap:gl.REPEAT,anisotropic:4,minFilter:gl.LINEAR_MIPMAP_LINEAR}):GL.Texture.fromURL(this.grid_texture_url,{format:gl.RGB,wrap:gl.REPEAT,anisotropic:4,minFilter:gl.LINEAR_MIPMAP_LINEAR}));d.Draw.push();"xy"==a.grid_plane?d.Draw.rotate(90,1,0,0):"yz"==a.grid_plane&&d.Draw.rotate(90,0,0,1);this.grid_texture&&!1!==this.grid_texture.ready?(gl.enable(gl.BLEND),this.grid_texture.bind(0),gl.depthMask(!1),
d.Draw.setColor([1,1,1,this.settings.grid_alpha]),d.Draw.translate(d.Draw.camera_position[0],0,d.Draw.camera_position[2]),d.Draw.scale(1E4,1E4,1E4),d.Draw.renderMesh(this.plane_mesh,gl.TRIANGLES,"xy"==a.grid_plane?this.grid_shader_xy:"yz"==a.grid_plane?this.grid_shader_yz:this.grid_shader),gl.depthMask(!0)):(d.Draw.setColor([0.2,0.2,0.2,0.75]),d.Draw.scale(1,1,1),d.Draw.renderMesh(this.grid_mesh,gl.LINES),d.Draw.scale(10,10,10),d.Draw.renderMesh(this.grid_mesh,gl.LINES));d.Draw.pop()};Xa.prototype.renderColliders=
function(a){a=a||d.GlobalScene;if(a._colliders){d.Draw.setColor([0.33,0.71,0.71,0.5]);for(var b=0;b<a._colliders.length;++b){var c=a._colliders[b],e=c.oobb;if(this.settings.render_colliders_aabb){var g=c.aabb;d.Draw.push();var f=BBox.getCenter(g),g=BBox.getHalfsize(g);d.Draw.translate(f);d.Draw.renderWireBox(2*g[0],2*g[1],2*g[2]);d.Draw.pop()}d.Draw.push();d.Draw.multMatrix(c.matrix);g=BBox.getHalfsize(e);c.type==d.PhysicsInstance.BOX?(d.Draw.translate(BBox.getCenter(e)),d.Draw.renderWireBox(2*g[0],
2*g[1],2*g[2])):c.type==d.PhysicsInstance.SPHERE?(d.Draw.translate(BBox.getCenter(e)),d.Draw.renderWireSphere(g[0],20)):c.type==d.PhysicsInstance.MESH&&(c=c.mesh)&&(c.indexBuffers.wireframe||c.computeWireframe(),d.Draw.renderMesh(c,gl.LINES,null,"wireframe"));d.Draw.pop()}}};Xa.prototype.renderPaths=function(a){a=a||d.GlobalScene;if(a._paths){d.Draw.setColor([0.7,0.6,0.3,0.5]);for(var b=0;b<a._paths.length;++b){var c=a._paths[b].samplePoints(0);d.Draw.renderLines(c,null,!0)}}};Xa.prototype.createMeshes=
function(){this.plane_mesh=GL.Mesh.plane({xz:!0});for(var a=10,b=[],c=-10;10>=c;c++)b.push([c*a,0,10*a]),b.push([c*a,0,10*-a]),b.push([10*a,0,c*a]),b.push([10*-a,0,c*a]);this.grid_mesh=GL.Mesh.load({vertices:b});b=new Float32Array([-1,1,1,-1,1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1]);c=new Uint16Array([0,1,0,4,0,3,1,2,1,5,2,3,2,6,3,7,4,5,4,7,6,7,5,6]);this.box_mesh=GL.Mesh.load({vertices:b,lines:c});this.circle_mesh=GL.Mesh.circle({size:1,slices:50});this.circle_empty_mesh=GL.Mesh.circle({size:1,
slices:50,empty:1});this.sphere_mesh=GL.Mesh.icosahedron({size:1,subdivisions:3});b=[];b.push([0.5*-a,0,0],[0.5*+a,0,0]);b.push([0,0.5*-a,0],[0,0.5*+a,0]);b.push([0,0,0.5*-a],[0,0,0.5*+a]);this.dummy_mesh=GL.Mesh.load({vertices:b});b=[];b.push([-1,1,1],[1,1,1],[-1,1,-1],[1,1,-1],[-1,-1,1],[1,-1,1],[-1,-1,-1],[1,-1,-1]);b.push([1,-1,1],[1,1,1],[1,-1,-1],[1,1,-1],[-1,-1,1],[-1,1,1],[-1,-1,-1],[-1,1,-1]);b.push([1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],[-1,1,1],[-1,1,-1],[-1,-1,1],[-1,-1,-1]);this.cube_mesh=
GL.Mesh.load({vertices:b});for(c=1;0<=c;c-=0.02)a=2*(1-0.001/c)-1,b.push([-1,1,a],[1,1,a],[-1,-1,a],[1,-1,a]),b.push([1,-1,a],[1,1,a],[-1,-1,a],[-1,1,a]);this.frustum_mesh=GL.Mesh.load({vertices:b});this.cylinder_mesh=GL.Mesh.cylinder({radius:10,height:2});b=[];c=[];a=2;b.push([0,0,0],[0.5*+a,0,0]);c.push([1,0,0,1],[1,0,0,1]);b.push([0,0,0],[0,0.5*+a,0]);c.push([0,1,0,1],[0,1,0,1]);b.push([0,0,0],[0,0,0.5*+a]);c.push([0,0,1,1],[0,0,1,1]);this.axis_mesh=GL.Mesh.load({vertices:b,colors:c});b=[];b.push([0,
0,0],[0,0.5*+a,0]);b.push([0,0.5*+a,0],[0.1*a,0.4*+a,0]);b.push([0,0.5*+a,0],[-0.1*a,0.4*+a,0]);this.top_line_mesh=GL.Mesh.load({vertices:b});b=[];b.push([0,0,0],[0,0,0.5*+a]);b.push([0,0,0.5*+a],[0,0.1*a,0.4*+a]);b.push([0,0,0.5*+a],[0,-0.1*a,0.4*+a]);this.front_line_mesh=GL.Mesh.load({vertices:b})};d.DebugRender=Xa;var pb={ready:!1,images:{},image_last_id:1,onRequestFrame:null,reset_stack_on_reset:!0,_rendercalls:0,init:function(){if(!this.ready&&gl){this.color=new Float32Array(4);this.color[3]=
1;this.mvp_matrix=mat4.create();this.temp_matrix=mat4.create();this.point_size=2;this.line_width=1;this.stack=new Float32Array(512);this.model_matrix=new Float32Array(this.stack.buffer,0,16);mat4.identity(this.model_matrix);this.camera=null;this.camera_position=vec3.create();this.view_matrix=mat4.create();this.projection_matrix=mat4.create();this.viewprojection_matrix=mat4.create();this.camera_stack=[];this.uniforms={u_model:this.model_matrix,u_viewprojection:this.viewprojection_matrix,u_mvp:this.mvp_matrix,
u_color:this.color,u_camera_position:this.camera_position,u_point_size:this.point_size,u_point_perspective:0,u_perspective:1,u_texture:0};this._temp=vec3.create();this.quad_mesh=GL.Mesh.load({vertices:[[-1,1,0],[1,1,0],[1,-1,0],[-1,-1,0]],coords:[[0,1],[1,1],[1,0],[0,0]]});var a=pb.vertex_shader_code,b=pb.fragment_shader_code;this.shader=new Shader(a,b);this.shader_instancing=new Shader(a,b,{USE_INSTANCING:""});this.shader_color=new Shader(a,b,{USE_COLOR:""});this.shader_color_instancing=new Shader(a,
b,{USE_COLOR:"",USE_INSTANCING:""});this.shader_texture=new Shader(a,b,{USE_TEXTURE:""});this.shader_texture_instancing=new Shader(a,b,{USE_TEXTURE:"",USE_INSTANCING:""});this.shader_points=new Shader(a,b,{USE_POINTS:""});this.shader_points_color=new Shader(a,b,{USE_COLOR:"",USE_POINTS:""});this.shader_points_color_size=new Shader(a,b,{USE_COLOR:"",USE_SIZE:"",USE_POINTS:""});this.shader_image=new Shader("\t\t\tprecision mediump float;\n\t\t\tattribute vec3 a_vertex;\n\t\t\tuniform mat4 u_mvp;\n\t\t\tuniform float u_point_size;\n\t\t\tvoid main() {\n\t\t\t\tgl_PointSize = u_point_size;\n\t\t\t\tgl_Position = u_mvp * vec4(a_vertex,1.0);\n\t\t\t}\t\t\t",
"\t\t\tprecision mediump float;\n\t\t\tuniform vec4 u_color;\n\t\t\tuniform sampler2D u_texture;\n\t\t\tvoid main() {\n\t\t\t  vec4 tex = texture2D(u_texture, vec2(gl_PointCoord.x,1.0 - gl_PointCoord.y) );\n\t\t\t  if(tex.a < 0.01)\n\t\t\t\tdiscard;\n\t\t\t  gl_FragColor = u_color * tex;\n\t\t\t}\t\t");this.shader_points_color_texture_size=new Shader("\t\t\tprecision mediump float;\n\t\t\tattribute vec3 a_vertex;\n\t\t\tattribute vec4 a_color;\n\t\t\tattribute float a_extra;\n\t\t\tuniform mat4 u_mvp;\n\t\t\tuniform float u_point_size;\n\t\t\tvarying vec4 v_color;\n\t\t\tvoid main() {\n\t\t\t\tv_color = a_color;\n\t\t\t\tgl_PointSize = u_point_size * a_extra;\n\t\t\t\tgl_Position = u_mvp * vec4(a_vertex,1.0);\n\t\t\t}\t\t\t",
"\t\t\tprecision mediump float;\n\t\t\tuniform vec4 u_color;\n\t\t\tvarying vec4 v_color;\n\t\t\tuniform sampler2D u_texture;\n\t\t\tvoid main() {\n\t\t\t  vec4 tex = texture2D(u_texture, vec2(gl_PointCoord.x,1.0 - gl_PointCoord.y) );\n\t\t\t  if(tex.a < 0.1)\n\t\t\t\tdiscard;\n\t\t\t  vec4 color = u_color * v_color * tex;\n\t\t\t  gl_FragColor = color;\n\t\t\t}\t\t");this.shader_text2D=new Shader("\t\t\tprecision mediump float;\n\t\t\tattribute vec3 a_vertex;\n\t\t\tattribute vec4 a_extra4;\n\t\t\tuniform mat4 u_mvp;\n\t\t\tuniform float u_point_size;\n\t\t\tvoid main() {\n\t\t\t\tgl_PointSize = u_point_size;\n\t\t\t\tgl_Position = u_mvp * vec4(a_vertex,1.0);\n\t\t\t}\t\t\t",
"\t\t\tprecision mediump float;\n\t\t\tuniform vec4 u_color;\n\t\t\tuniform sampler2D u_texture;\n\t\t\tvoid main() {\n\t\t\t  vec4 tex = texture2D(u_texture, vec2(gl_PointCoord.x,1.0 - gl_PointCoord.y) );\n\t\t\t  if(tex.a < 0.1)\n\t\t\t\tdiscard;\n\t\t\t  vec4 color = u_color * tex;\n\t\t\t  gl_FragColor = color;\n\t\t\t}\t\t");this.shader_phong=new Shader("\t\t\tprecision mediump float;\n\t\t\tattribute vec3 a_vertex;\n\t\t\tattribute vec3 a_normal;\n\t\t\tvarying vec3 v_pos;\n\t\t\tvarying vec3 v_normal;\n\t\t\t#ifdef USE_INSTANCING\n\t\t\t\tattribute mat4 u_model;\n\t\t\t#else\n\t\t\t\tuniform mat4 u_model;\n\t\t\t#endif\n\t\t\tuniform mat4 u_viewprojection;\n\t\t\tvoid main() {\n\t\t\t\tv_pos = ( u_model * vec4( a_vertex, 1.0 )).xyz;\n\t\t\t\tv_normal = (u_model * vec4(a_normal,0.0)).xyz;\n\t\t\t\tgl_Position = u_viewprojection * vec4( v_pos, 1.0 );\n\t\t\t}\n",
"\n\t\t\tprecision mediump float;\n\t\t\tuniform vec3 u_ambient_color;\n\t\t\tuniform vec3 u_light_color;\n\t\t\tuniform vec3 u_light_dir;\n\t\t\tuniform vec4 u_color;\n\t\t\tvarying vec3 v_pos;\n\t\t\tvarying vec3 v_normal;\n\t\t\tvoid main() {\n\t\t\t\tvec3 N = normalize(v_normal);\n\t\t\t\tfloat NdotL = max(0.0, dot(N,u_light_dir));\n\t\t\t\tgl_FragColor = u_color * vec4(u_ambient_color + u_light_color * NdotL, 1.0);\n\t\t\t}\n");this.shader_phong_instanced=new Shader("\t\t\tprecision mediump float;\n\t\t\tattribute vec3 a_vertex;\n\t\t\tattribute vec3 a_normal;\n\t\t\tvarying vec3 v_pos;\n\t\t\tvarying vec3 v_normal;\n\t\t\t#ifdef USE_INSTANCING\n\t\t\t\tattribute mat4 u_model;\n\t\t\t#else\n\t\t\t\tuniform mat4 u_model;\n\t\t\t#endif\n\t\t\tuniform mat4 u_viewprojection;\n\t\t\tvoid main() {\n\t\t\t\tv_pos = ( u_model * vec4( a_vertex, 1.0 )).xyz;\n\t\t\t\tv_normal = (u_model * vec4(a_normal,0.0)).xyz;\n\t\t\t\tgl_Position = u_viewprojection * vec4( v_pos, 1.0 );\n\t\t\t}\n",
"\n\t\t\tprecision mediump float;\n\t\t\tuniform vec3 u_ambient_color;\n\t\t\tuniform vec3 u_light_color;\n\t\t\tuniform vec3 u_light_dir;\n\t\t\tuniform vec4 u_color;\n\t\t\tvarying vec3 v_pos;\n\t\t\tvarying vec3 v_normal;\n\t\t\tvoid main() {\n\t\t\t\tvec3 N = normalize(v_normal);\n\t\t\t\tfloat NdotL = max(0.0, dot(N,u_light_dir));\n\t\t\t\tgl_FragColor = u_color * vec4(u_ambient_color + u_light_color * NdotL, 1.0);\n\t\t\t}\n",{USE_INSTANCING:""});a={u_ambient_color:[0.1,0.1,0.1],u_light_color:[0.8,
0.8,0.8],u_light_dir:[0,1,0]};this.shader_phong.uniforms(a);this.shader_phong_instanced.uniforms(a);this.shader_depth=new Shader("\t\t\tprecision mediump float;\n\t\t\tattribute vec3 a_vertex;\n\t\t\tvarying vec4 v_pos;\n\t\t\tuniform mat4 u_model;\n\t\t\tuniform mat4 u_mvp;\n\t\t\tvoid main() {\n\t\t\t\tv_pos = u_model * vec4(a_vertex,1.0);\n\t\t\t\tgl_Position = u_mvp * vec4(a_vertex,1.0);\n\t\t\t}\t\t\t","\t\t\tprecision mediump float;\n\t\t\tvarying vec4 v_pos;\n\t\t\t\n\t\t\tvec4 PackDepth32(float depth)\n\t\t\t{\n\t\t\t\tconst vec4 bitSh  = vec4(   256*256*256, 256*256,   256,         1);\n\t\t\t\tconst vec4 bitMsk = vec4(   0,      1.0/256.0,    1.0/256.0,    1.0/256.0);\n\t\t\t\tvec4 comp;\n\t\t\t\tcomp\t= depth * bitSh;\n\t\t\t\tcomp\t= fract(comp);\n\t\t\t\tcomp\t-= comp.xxyz * bitMsk;\n\t\t\t\treturn comp;\n\t\t\t}\n\t\t\tvoid main() {\n\t\t\t\tfloat depth = (v_pos.z / v_pos.w) * 0.5 + 0.5;\n\t\t\t\tgl_FragColor = PackDepth32(depth);\n\t\t\t}\t\t");
this.ready=!0}},createSurfaceShader:function(a,b,c){-1==a.indexOf("surface_function")&&(a="vec4 surface_function( vec3 pos, vec3 normal, vec2 coord ) { "+a+"\n } ");if(b)if(b.constructor===String)a=b+";\n"+a;else for(var e in b)a+="uniform "+b[e]+" "+e+";\n";return new GL.Shader("\t\t\tprecision mediump float;\n\t\t\tattribute vec3 a_vertex;\n\t\t\tattribute vec3 a_normal;\n\t\t\tattribute vec2 a_coord;\n\t\t\tvarying vec2 v_coord;\n\t\t\tvarying vec3 v_pos;\n\t\t\tvarying vec3 v_normal;\n\t\t\tuniform mat4 u_mvp;\n\t\t\tuniform mat4 u_model;\n\t\t\tvoid main() {\n\t\t\t\tv_coord = a_coord;\n\t\t\t\tv_pos = (u_model * vec4(a_vertex,1.0)).xyz;\n\t\t\t\tv_normal = (u_model * vec4(a_normal,0.0)).xyz;\n\t\t\t\tgl_Position = u_mvp * vec4(a_vertex,1.0);\n\t\t\t}\t\t\t",
"\t\t\tprecision mediump float;\n\t\t\tvarying vec2 v_coord;\n\t\t\tvarying vec3 v_pos;\n\t\t\tvarying vec3 v_normal;\n\t\t\tuniform vec4 u_color;\n\t\t\tuniform vec3 u_camera_position;\n\t\t\tuniform sampler2D u_texture;\n\t\t\t"+a+"\n\t\t\tvoid main() {\n\t\t\t\tgl_FragColor = surface_function(v_pos,v_normal,v_coord);\n\t\t\t}\t\t",c)},reset:function(a){this.ready?(this.color.set([1,1,1,1]),this.point_size=2,this.line_width=1):this.init();a&&(this.images={});this.reset_stack_on_reset&&(this.model_matrix=
new Float32Array(this.stack.buffer,0,16),this.uniforms.u_model=this.model_matrix,mat4.identity(this.model_matrix))},setColor:function(a){if(3<=arguments.length)this.color[0]=arguments[0],this.color[1]=arguments[1],this.color[2]=arguments[2],4==arguments.length&&(this.color[3]=arguments[3]);else for(var b=0;b<a.length;b++)this.color[b]=a[b]},setAlpha:function(a){this.color[3]=a},setPointSize:function(a,b){this.point_size=a;this.uniforms.u_point_size=a;this.uniforms.u_point_perspective=b?1:0},setLineWidth:function(a){gl.setLineWidth?
gl.setLineWidth(a):gl.lineWidth(a);this.line_width=a},setCamera:function(a){this.camera=a;a.updateMatrices();vec3.copy(this.camera_position,a.getEye());this.view_matrix.set(a._view_matrix);this.projection_matrix.set(a._projection_matrix);this.viewprojection_matrix.set(a._viewprojection_matrix);this.uniforms.u_perspective=gl.viewport_data[3]*this.projection_matrix[5]},setCameraPosition:function(a){vec3.copy(this.camera_position,a)},pushCamera:function(){this.camera_stack.push(mat4.create(this.viewprojection_matrix))},
popCamera:function(){if(0==this.camera_stack.length)throw"too many pops";this.viewprojection_matrix.set(this.camera_stack.pop())},setViewProjectionMatrix:function(a,b,c){mat4.copy(this.view_matrix,a);mat4.copy(this.projection_matrix,b);c?mat4.copy(this.viewprojection_matrix,c):mat4.multiply(this.viewprojection_matrix,a,c)},setMatrix:function(a){mat4.copy(this.model_matrix,a)},multMatrix:function(a){mat4.multiply(this.model_matrix,a,this.model_matrix)},renderLines:function(a,b,c,e){if(a&&a.length){var d=
null,d=a.constructor==Float32Array?a:this.linearize(a);b&&(b=b.constructor==Float32Array?b:this.linearize(b));b&&b.length/4!=d.length/3&&(b=null);a=gl.LINES;e?a=gl.LINE_LOOP:c&&(a=gl.LINE_STRIP);c=this.toGlobalMesh({vertices:d,colors:b});return this.renderMesh(c,a,b?this.shader_color:this.shader,void 0,0,d.length/3)}},renderPoints:function(a,b,c){if(a&&a.length){var e=null,e=a.constructor==Float32Array?a:a[0].length?this.linearize(a):new Float32Array(a);b&&b.constructor!=Float32Array&&(b=b.constructor===
Array&&b[0].constructor===Number?new Float32Array(b):this.linearize(b));a=this.toGlobalMesh({vertices:e,colors:b});c||(c=b?this.shader_color:this.shader);return this.renderMesh(a,gl.POINTS,c,void 0,0,e.length/3)}},renderRoundPoints:function(a,b,c){if(a&&a.length){var e=null,e=a.constructor==Float32Array?a:a[0].length?this.linearize(a):new Float32Array(a);b&&(b=b.constructor==Float32Array?b:this.linearize(b));a=this.toGlobalMesh({vertices:e,colors:b});c||(c=b?this.shader_points_color:this.shader_points);
return this.renderMesh(a,gl.POINTS,c,void 0,0,e.length/3)}},renderPointsWithSize:function(a,b,c,e,d){if(a&&a.length){var f=null,f=a.constructor==Float32Array?a:a[0].length?this.linearize(a):new Float32Array(a);if(!b)throw"colors required in Draw.renderPointsWithSize";b=b.constructor==Float32Array?b:this.linearize(b);if(!c)throw"sizes required in Draw.renderPointsWithSize";c=c.constructor==Float32Array?c:this.linearize(c);a=this.toGlobalMesh({vertices:f,colors:b,extra:c});d=d||(e?this.shader_points_color_texture_size:
this.shader_points_color_size);return this.renderMesh(a,gl.POINTS,d,void 0,0,f.length/3)}},createRectangleMesh:function(a,b,c,e){var d=new Float32Array(12);c?d.set([0.5*-a,0,0.5*b,0.5*a,0,0.5*b,0.5*a,0,0.5*-b,0.5*-a,0,0.5*-b]):d.set([0.5*-a,0.5*b,0,0.5*a,0.5*b,0,0.5*a,0.5*-b,0,0.5*-a,0.5*-b,0]);return e?this.toGlobalMesh({vertices:d}):GL.Mesh.load({vertices:d})},renderRectangle:function(a,b,c,e){a=this.createRectangleMesh(a,b,c,!0);return this.renderMesh(a,e?gl.TRIANGLE_FAN:gl.LINE_LOOP,void 0,void 0,
0,this._global_mesh_last_size)},createCircleMesh:function(a,b,c,e){b=b||32;quat.create();for(var d=this._temp,f=new Float32Array(3*b),h=2*Math.PI/b,k=0;k<b;k++)d[0]=Math.sin(h*k)*a,c?(d[1]=0,d[2]=Math.cos(h*k)*a):(d[2]=0,d[1]=Math.cos(h*k)*a),f.set(d,3*k);return e?this.toGlobalMesh({vertices:f}):GL.Mesh.load({vertices:f})},renderCircle:function(a,b,c,e){a=this.createCircleMesh(a,b,c,!0);return this.renderMesh(a,e?gl.TRIANGLE_FAN:gl.LINE_LOOP,void 0,void 0,0,this._global_mesh_last_size)},renderSolidCircle:function(a,
b,c){return this.renderCircle(a,b,c,!0)},createWireSphereMesh:function(a,b,c){b=b||100;quat.create();for(var e=this._temp,d=new Float32Array(18*b),f=1/b*Math.PI*2,h=0;h<b;h++)e.set([Math.sin(h*f)*a,Math.cos(h*f)*a,0]),d.set(e,18*h),e.set([Math.sin((h+1)*f)*a,Math.cos((h+1)*f)*a,0]),d.set(e,18*h+3),e.set([Math.sin(h*f)*a,0,Math.cos(h*f)*a]),d.set(e,18*h+6),e.set([Math.sin((h+1)*f)*a,0,Math.cos((h+1)*f)*a]),d.set(e,18*h+9),e.set([0,Math.sin(h*f)*a,Math.cos(h*f)*a]),d.set(e,18*h+12),e.set([0,Math.sin((h+
1)*f)*a,Math.cos((h+1)*f)*a]),d.set(e,18*h+15);return c?this.toGlobalMesh({vertices:d}):GL.Mesh.load({vertices:d})},renderWireSphere:function(a,b){var c=this.createWireSphereMesh(a,b,!0);return this.renderMesh(c,gl.LINES,void 0,void 0,0,this._global_mesh_last_size)},renderSolidSphere:function(a){var b=this._sphere_mesh;this._sphere_mesh||(b=this._sphere_mesh=GL.Mesh.sphere({size:1}));this.push();this.scale(a,a,a);this.renderMesh(b,gl.TRIANGLES);this.pop()},createWireBoxMesh:function(a,b,c,e){a*=0.5;
b*=0.5;c*=0.5;a=new Float32Array([-a,b,c,-a,b,-c,a,b,-c,a,b,c,-a,-b,c,-a,-b,-c,a,-b,-c,a,-b,c]);b=new Uint16Array([0,1,0,4,0,3,1,2,1,5,2,3,2,6,3,7,4,5,4,7,6,7,5,6]);return e?this.toGlobalMesh({vertices:a},b):GL.Mesh.load({vertices:a,lines:b})},renderWireBox:function(a,b,c){a=this.createWireBoxMesh(a,b,c,!0);return this.renderMesh(a,gl.LINES,void 0,"indices",0,this._global_mesh_last_size)},createSolidBoxMesh:function(a,b,c,e){a*=0.5;b*=0.5;c*=0.5;a=[-a,b,-c,-a,-b,+c,-a,b,c,-a,b,-c,-a,-b,-c,-a,-b,+c,
a,b,-c,a,b,c,a,-b,+c,a,b,-c,a,-b,+c,a,-b,-c,-a,b,c,a,-b,c,a,b,c,-a,b,c,-a,-b,c,a,-b,c,-a,b,-c,a,b,-c,a,-b,-c,-a,b,-c,a,-b,-c,-a,-b,-c,-a,b,-c,a,b,c,a,b,-c,-a,b,-c,-a,b,c,a,b,c,-a,-b,-c,a,-b,-c,a,-b,c,-a,-b,-c,a,-b,c,-a,-b,c];return e?this.toGlobalMesh({vertices:a}):GL.Mesh.load({vertices:a})},renderSolidBox:function(a,b,c){a=this.createSolidBoxMesh(a,b,c,!0);return this.renderMesh(a,gl.TRIANGLES,void 0,void 0,0,this._global_mesh_last_size)},renderWireCube:function(a){return this.renderWireBox(a,a,
a)},renderSolidCube:function(a){return this.renderSolidBox(a,a,a)},renderPlane:function(a,b,c,e){if(!a||!b)throw"LS.Draw.renderPlane param missing";this.push();this.translate(a);this.scale(b[0],b[1],1);c&&c.bind(0);!e&&c&&(e=this.shader_texture);this.renderMesh(this.quad_mesh,gl.TRIANGLE_FAN,e);c&&c.unbind(0);this.pop()},createGridMesh:function(a,b){a=a||20;b=b||10;for(var c=new Float32Array(12*(2*b+1)),e=0,d=-b;d<=b;d++)c.set([d*a,0,a*b],e),c.set([d*a,0,-a*b],e+3),c.set([a*b,0,d*a],e+6),c.set([-a*
b,0,d*a],e+9),e+=12;return GL.Mesh.load({vertices:c})},renderGrid:function(a,b){var c=this.createGridMesh(a,b);return this.renderMesh(c,gl.LINES)},createConeMesh:function(a,b,c,e,d){var f=[0,1,0];c=c||100;var h=quat.create(),k=this._temp,l=new Float32Array(3*(c+2));l.set(e?[0,0,b]:[0,b,0],0);for(b=0;b<=c;b++)quat.setAxisAngle(h,f,b/c*Math.PI*2),vec3.transformQuat(k,[0,0,a],h),e&&vec3.set(k,k[0],k[2],k[1]),l.set(k,3*b+3);return d?this.toGlobalMesh({vertices:l}):GL.Mesh.load({vertices:l})},renderCone:function(a,
b,c,e){a=this.createConeMesh(a,b,c,e,!0);return this.renderMesh(a,gl.TRIANGLE_FAN,void 0,void 0,0,this._global_mesh_last_size)},createCylinderMesh:function(a,b,c,e,d){e=[0,1,0];c=c||100;for(var f=quat.create(),h=this._temp,k=new Float32Array(6*(c+1)),l=0;l<=c;l++)quat.setAxisAngle(f,e,l/c*Math.PI*2),vec3.transformQuat(h,[0,0,a],f),k.set(h,6*l+3),h[1]=b,k.set(h,6*l);return d?this.toGlobalMesh({vertices:k}):GL.Mesh.load({vertices:k})},renderCylinder:function(a,b,c,e){a=this.createCylinderMesh(a,b,c,
e,!0);return this.renderMesh(a,gl.TRIANGLE_STRIP,void 0,void 0,0,this._global_mesh_last_size)},renderImage:function(a,b,c,e){if(!a||!b)throw"LS.Draw.renderImage param missing";c=c||10;var d=null;if("string"==typeof b){d=this.images[b];if(null==d){pb.images[b]=1;a=new Image;a.src=b;a.onload=function(){var a=GL.Texture.fromImage(this);pb.images[b]=a;if(pb.onRequestFrame)pb.onRequestFrame()};return}if(1==d)return}else b.constructor==Image?(b.texture||(b.texture=GL.Texture.fromImage(this)),d=b.texture):
b.constructor==Texture&&(d=b);d&&(e?(this.setPointSize(c),d.bind(0),this.renderPoints(a,null,this.shader_image)):(this.push(),this.billboard(a),this.scale(c,c,c),d.bind(0),this.renderMesh(this.quad_mesh,gl.TRIANGLE_FAN,this.shader_texture),this.pop()))},renderMesh:function(a,b,c,e,d,f){if(!this.ready)throw"Draw.js not initialized, call Draw.init()";if(!a)throw"LS.Draw.renderMesh mesh cannot be null";c||(c=a===this._global_mesh&&this._global_mesh_ignore_colors?this.shader:a.vertexBuffers.colors?this.shader_color:
this.shader);mat4.multiply(this.mvp_matrix,this.viewprojection_matrix,this.model_matrix);c.uniforms(this.uniforms);void 0===d?c.draw(a,void 0===b?gl.TRIANGLES:b,e):c.drawRange(a,void 0===b?gl.TRIANGLES:b,d,f,e);this._last_mesh=a;this._last_primitive=b;this._last_shader=c;this._last_indices=e;this._last_range_start=d;this._last_range_length=f;this._rendercalls+=1;return this.last_mesh=a},renderMeshesInstanced:function(){var a={u_model:null},b=mat4.create();return function(c,e,d,f,h){if(!this.ready)throw"Draw.js not initialized, call Draw.init()";
if(!c)throw"LS.Draw.renderMeshesInstanced mesh cannot be null";if(1==gl.webgl_version&&!gl.extensions.ANGLE_instanced_arrays)return null;f||(f=c.vertexBuffers.colors?this.shader_color_instancing:this.shader_instancing);if(!f.attributes.u_model)throw"Shader does not support instancing, it must have a attribute u_model";a.u_model=e;b.set(this.viewprojection_matrix);mat4.multiply(this.viewprojection_matrix,this.viewprojection_matrix,this.model_matrix);f.uniforms(this.uniforms);f.drawInstanced(c,void 0===
d?gl.TRIANGLES:d,h,a);this.viewprojection_matrix.set(b);this._rendercalls+=1;return c}}(),repeatLastRender:function(){this.renderMesh(this._last_mesh,this._last_primitive,this._last_shader,this._last_indices,this._last_range_start,this._last_range_length)},renderText:function(a,b){b=b||d.ZEROS;pb.font_atlas||this.createFontAtlas();for(var c=this.font_atlas,e=a.length,g=c.atlas.char_size,f=c.atlas.spacing,h=0,k=0;k<e;++k)null!=c.atlas[a.charCodeAt(k)]&&h++;for(var l=new Float32Array(18*h),h=new Float32Array(12*
h),n=0,p=0,m=0,k=0;k<e;++k){var q=c.atlas[a.charCodeAt(k)];q?(l.set([p+b[0],m+b[1],b[2]],18*n),l.set([p+b[0],m+b[1]+g,b[2]],18*n+3),l.set([p+b[0]+g,m+b[1]+g,b[2]],18*n+6),l.set([p+b[0]+g,m+b[1],b[2]],18*n+9),l.set([p+b[0],m+b[1],b[2]],18*n+12),l.set([p+b[0]+g,m+b[1]+g,b[2]],18*n+15),h.set([q[0],q[1]],12*n),h.set([q[0],q[3]],12*n+2),h.set([q[2],q[3]],12*n+4),h.set([q[2],q[1]],12*n+6),h.set([q[0],q[1]],12*n+8),h.set([q[2],q[3]],12*n+10),p+=f,++n):10==a.charCodeAt(k)?(p=0,m-=g):p+=g}e=this.toGlobalMesh({vertices:l,
coords:h});c.bind(0);return this.renderMesh(e,gl.TRIANGLES,this.shader_texture,void 0,0,l.length/3)},createFontAtlas:function(){var a=createCanvas(512,512),b=0.09*a.width|0,c=0.1*a.width|0,e=a.getContext("2d");e.fillStyle="white";e.font=b+"px Courier New";e.textAlign="center";for(var d=0,f=0,b=-0.3*b,h={char_size:c,offset:c/a.width,spacing:0.6*c},k=6;100>k;k++){var l=String.fromCharCode(k+27);h[k+27]=[d/a.width,1-(f+c)/a.height,(d+c)/a.width,1-f/a.height];e.fillText(l,Math.floor(d+0.5*c),Math.floor(f+
c+b),c);d+=c;d+c>a.width&&(d=0,f+=c)}this.font_atlas=GL.Texture.fromImage(a,{magFilter:gl.LINEAR,minFilter:gl.LINEAR_MIPMAP_LINEAR});gl.colorMask(!0,!0,!0,!1);this.font_atlas.fill([1,1,1,0]);gl.colorMask(!0,!0,!0,!0);this.font_atlas.atlas=h},linearize:function(a){if(!a.length)return[];if(a[0].constructor===Number)return a.constructor===Float32Array?a:new Float32Array(a);for(var b=a[0].length,c=new Float32Array(a.length*b),e=a.length,d=0;d<e;++d)c.set(a[d],d*b);return c},push:function(){if(this.model_matrix.byteOffset>=
this.stack.byteLength-64)throw"matrices stack overflow";var a=this.model_matrix;this.model_matrix=new Float32Array(this.stack.buffer,this.model_matrix.byteOffset+64,16);this.uniforms.u_model=this.model_matrix;mat4.copy(this.model_matrix,a)},pop:function(){if(0==this.model_matrix.byteOffset)throw"too many pops";this.model_matrix=new Float32Array(this.stack.buffer,this.model_matrix.byteOffset-64,16);this.uniforms.u_model=this.model_matrix},identity:function(){mat4.identity(this.model_matrix)},scale:function(a,
b,c){if(3==arguments.length){var e=this._temp;e[0]=a;e[1]=b;e[2]=c;mat4.scale(this.model_matrix,this.model_matrix,e)}else a.length?mat4.scale(this.model_matrix,this.model_matrix,a):(e=this._temp,e[0]=e[1]=e[2]=a,mat4.scale(this.model_matrix,this.model_matrix,e))},translate:function(a,b,c){if(3==arguments.length){var e=this._temp;e[0]=a;e[1]=b;e[2]=c;mat4.translate(this.model_matrix,this.model_matrix,e)}else mat4.translate(this.model_matrix,this.model_matrix,a)},rotate:function(a,b,c,e){if(4==arguments.length){var d=
this._temp;d[0]=b;d[1]=c;d[2]=e;mat4.rotate(this.model_matrix,this.model_matrix,a*DEG2RAD,[b,c,e])}else mat4.rotate(this.model_matrix,this.model_matrix,a*DEG2RAD,b)},lookAt:function(a,b,c){mat4.lookAt(this.model_matrix,a,b,c);mat4.invert(this.model_matrix,this.model_matrix)},billboard:function(a){mat4.invert(this.model_matrix,this.view_matrix);mat4.setTranslation(this.model_matrix,a)},fromTranslationFrontTop:function(a,b,c){mat4.fromTranslationFrontTop(this.model_matrix,a,b,c)},project:function(a,
b){b=b||vec3.create();return mat4.multiplyVec3(b,this.mvp_matrix,a)},getPhongShader:function(a,b,c,e){e=e?this.shader_phong_instanced:this.shader_phong;vec3.normalize(c,c);e.uniforms({u_ambient_color:a,u_light_color:b,u_light_dir:c});return e},getDepthShader:function(){return this.shader_depth},toGlobalMesh:function(a,b){this._global_mesh||(this._global_mesh_max_vertices=1024,this._global_mesh=new GL.Mesh({vertices:new Float32Array(3*this._global_mesh_max_vertices),normals:new Float32Array(3*this._global_mesh_max_vertices),
coords:new Float32Array(2*this._global_mesh_max_vertices),colors:new Float32Array(4*this._global_mesh_max_vertices),extra:new Float32Array(1*this._global_mesh_max_vertices)},{indices:new Uint16Array(3*this._global_mesh_max_vertices)},{stream_type:gl.DYNAMIC_STREAM}));for(var c in a){var e=this._global_mesh.getBuffer(c);if(e){var d=a[c];d&&(d.buffer||(d=new Float32Array(d)),d.length>e.data.length&&(console.warn("Draw: data is too big, resizing"),this.resizeGlobalMesh(),e=this._global_mesh.getBuffer(c),
d=d.subarray(0,e.data.length)),e.setData(d))}else console.warn("Draw: global mesh lacks one buffer: "+c)}this._global_mesh_ignore_colors=!a.colors;b?(e=this._global_mesh.getIndexBuffer("indices"),e.setData(b),this._global_mesh_last_size=b.length):this._global_mesh_last_size=a.vertices.length/3;return this._global_mesh},resizeGlobalMesh:function(){if(!this._global_mesh)throw"No global mesh to resize";this._global_mesh_max_vertices*=2;this._global_mesh.deleteBuffers();this._global_mesh=new GL.Mesh({vertices:new Float32Array(3*
this._global_mesh_max_vertices),normals:new Float32Array(3*this._global_mesh_max_vertices),coords:new Float32Array(2*this._global_mesh_max_vertices),colors:new Float32Array(4*this._global_mesh_max_vertices),extra:new Float32Array(1*this._global_mesh_max_vertices)},{indices:new Uint16Array(3*this._global_mesh_max_vertices)},{stream_type:gl.DYNAMIC_STREAM})},vertex_shader_code:"\tprecision mediump float;\n\tattribute vec3 a_vertex;\n\tvarying vec3 v_vertex;\n\tattribute vec3 a_normal;\n\tvarying vec3 v_normal;\n\t#ifdef USE_COLOR\n\t\tattribute vec4 a_color;\n\t\tvarying vec4 v_color;\n\t#endif\n\t#ifdef USE_TEXTURE\n\t\tattribute vec2 a_coord;\n\t\tvarying vec2 v_coord;\n\t#endif\n\t#ifdef USE_SIZE\n\t\tattribute float a_extra;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tattribute mat4 u_model;\n\t#else\n\t\tuniform mat4 u_model;\n\t#endif\n\tuniform mat4 u_viewprojection;\n\tuniform float u_point_size;\n\tuniform float u_perspective;\n\tuniform float u_point_perspective;\n\tfloat computePointSize(float radius, float w)\n\t{\n\t\tif(radius < 0.0)\n\t\t\treturn -radius;\n\t\treturn u_perspective * radius / w;\n\t}\n\tvoid main() {\n\t\t#ifdef USE_TEXTURE\n\t\t\tv_coord = a_coord;\n\t\t#endif\n\t\t#ifdef USE_COLOR\n\t\t\tv_color = a_color;\n\t\t#endif\n\t\tv_vertex = ( u_model * vec4( a_vertex, 1.0 )).xyz;\n\t\tv_normal = ( u_model * vec4( a_normal, 0.0 )).xyz;\n\t\tgl_Position = u_viewprojection * vec4(v_vertex,1.0);\n\t\tgl_PointSize = u_point_size;\n\t\t#ifdef USE_SIZE\n\t\t\tgl_PointSize = a_extra;\n\t\t#endif\n\t\tif(u_point_perspective != 0.0)\n\t\t\tgl_PointSize = computePointSize( gl_PointSize, gl_Position.w );\n\t}",
fragment_shader_code:"\tprecision mediump float;\n\tuniform vec4 u_color;\n\t#ifdef USE_COLOR\n\t\tvarying vec4 v_color;\n\t#endif\n\t#ifdef USE_TEXTURE\n\t\tvarying vec2 v_coord;\n\t\tuniform sampler2D u_texture;\n\t#endif\n\tvoid main() {\n\t\tvec4 color = u_color;\n\t\t#ifdef USE_TEXTURE\n\t\t  color *= texture2D(u_texture, v_coord);\n\t\t  if(color.a < 0.1)\n\t\t\tdiscard;\n\t\t#endif\n\t\t#ifdef USE_POINTS\n\t\t\tfloat dist = length( gl_PointCoord.xy - vec2(0.5) );\n\t\t\tif( dist > 0.45 )\n\t\t\t\tdiscard;\n\t\t#endif\n\t\t#ifdef USE_COLOR\n\t\t\tcolor *= v_color;\n\t\t#endif\n\t\tgl_FragColor = color;\n\t}"};
"undefined"!=typeof d&&(d.Draw=pb);sa.use_shadowmap_depth_texture=!0;sa.prototype.getReadShaderBlock=function(){return this.texture.format!=GL.DEPTH_COMPONENT?sa.shader_block.flag_mask|sa.depth_in_color_block.flag_mask:sa.shader_block.flag_mask};sa.prototype.getWriteShaderBlock=function(){return 0};sa.prototype.precomputeStaticShadowmap=function(){};sa.prototype.generate=function(a,b,c){c=this.light;if(!(1E-4>c.computeLightIntensity())){var e=this.resolution;0==e&&(e=b.default_shadowmap_resolution);
var g=e;c.type==d.Light.OMNI&&(e*=6);var f=gl.TEXTURE_2D;if(null==this.texture||this.texture.width!=g||this.texture.height!=e||this.texture.texture_type!=f){var h=gl.UNSIGNED_BYTE,k=gl.RGBA;sa.use_shadowmap_depth_texture&&gl.extensions.WEBGL_depth_texture&&(k=gl.DEPTH_COMPONENT,h=gl.UNSIGNED_INT);this.texture=new GL.Texture(g,e,{type:h,texture_type:f,format:k,magFilter:gl.NEAREST,minFilter:gl.NEAREST});this.texture.filename=":shadowmap_"+c.uid;d.ResourcesManager.textures[this.texture.filename]=this.texture;
this.texture.texture_type==gl.TEXTURE_2D&&(this.fbo=k==gl.RGBA?new GL.FBO([this.texture]):new GL.FBO(null,this.texture))}d.Renderer.setRenderPass(ec);d.Renderer._current_light=c;g=b.layers;b.layers=this.layers;this.texture.unbind();d.Renderer._current_target=this.texture;this.fbo.bind();e=1;f=this.texture.width;h=this.texture.height;c.type==d.Light.OMNI&&(e=6,h/=6);gl.clearColor(1,1,1,1);this.texture.type==gl.DEPTH_COMPONENT&&gl.colorMask(!1,!1,!1,!1);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);
for(k=0;k<e;++k){var l=c.getLightCamera(k);this.shadow_params[2]=l.near;this.shadow_params[3]=l.far;d.Renderer.enableCamera(l,b,!0);l=0;c.type==d.Light.OMNI&&(l=k*h);gl.viewport(0,l,f,h);this.reverse_faces&&(d.Renderer._reverse_faces=!0);d.Renderer.renderInstances(b,a);d.Renderer._reverse_faces=!1}this.fbo.unbind();d.Renderer._current_target=null;gl.colorMask(!0,!0,!0,!0);b.layers=g;d.Renderer.setRenderPass(tb);d.Renderer._current_light=null;if(this.onPostProcessShadowMap)this.onPostProcessShadowMap(this.texture)}};
sa.prototype.prepare=function(a,b){this.texture?(this.light.computeFar(),a.u_shadow_params=this.shadow_params,this.shadow_params[0]=1/this.texture.width,this.shadow_params[1]=this.bias,a.shadowmap=d.Renderer.SHADOWMAP_TEXTURE_SLOT,b[d.Renderer.SHADOWMAP_TEXTURE_SLOT]=this.texture):console.warn("shadowmap without texture?")};sa.prototype.toViewport=function(){this.texture&&this.texture.toViewport()};sa._enabled_vertex_code='\n\t#pragma snippet "light_structs"\n\tvarying vec4 v_light_coord;\n\tvoid applyLight( vec3 pos ) { v_light_coord = u_light_matrix * vec4(pos,1.0); }\n';
sa._disabled_vertex_code="\n\tvoid applyLight(vec3 pos) {}\n";sa._enabled_fragment_code='\n\t#ifndef TESTSHADOW\n\t\t#define TESTSHADOW\n\t#endif\n\t#pragma shaderblock "depth_in_color"\n\t#pragma snippet "PackDepth32"\n\t\n\tuniform sampler2D shadowmap;\n\tvarying vec4 v_light_coord;\n\tuniform vec4 u_shadow_params; // (1.0/(texture_size), bias, near, far)\n\t\n\tfloat UnpackDepth(vec4 depth)\n\t{\n\t\t#ifdef BLOCK_DEPTH_IN_COLOR\n\t\t\tconst vec4 bitShift = vec4( 1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0 );\n\t\t\treturn dot(depth, bitShift);\n\t\t#else\n\t\t\treturn depth.x;\n\t\t#endif\n\t}\n\tfloat texsize = 1.0 / u_shadow_params.x;\n\tfloat real_depth = 0.0;\n\t\n\tfloat pixelShadow( vec2 uv )\n\t{\n\t\tfloat sampleDepth = UnpackDepth( texture2D(shadowmap, uv) );\n\t\tfloat depth = (sampleDepth == 1.0) ? 1.0e9 : sampleDepth; //on empty data send it to far away\n\t\tif (depth > 0.0) \n\t\t\treturn real_depth > depth ? 0.0 : 1.0;\n\t\treturn 0.0;\n\t}\n\tfloat expFunc(float f)\n\t{\n\t\treturn f*f*f*(f*(f*6.0-15.0)+10.0);\n\t}\n\t\n\tfloat testShadow( Light LIGHT )\n\t{\n\t\tvec3 offset = vec3(0.0);\n\t\tfloat depth = 0.0;\n\t\tfloat bias = u_shadow_params.y;\n\t\t\n\t\tvec2 sample = (v_light_coord.xy / v_light_coord.w) * vec2(0.5) + vec2(0.5) + offset.xy;\n\t\t//is inside light frustum\n\t\tif (clamp(sample, 0.0, 1.0) != sample) \n\t\t\treturn LIGHT.Info.x == 3.0 ? 1.0 : 0.0; //outside of shadowmap, no shadow\n\t\t\n\t\treal_depth = (v_light_coord.z - bias) / v_light_coord.w * 0.5 + 0.5;\n\t\t#ifdef BLOCK_DEPTH_IN_COLOR\n\t\t\t//real_depth = linearDepthNormalized( real_depth, u_shadow_params.z, u_shadow_params.w );\n\t\t#endif\n\t\tvec2 topleft_uv = sample * texsize;\n\t\tvec2 offset_uv = fract( topleft_uv );\n\t\toffset_uv.x = expFunc(offset_uv.x);\n\t\toffset_uv.y = expFunc(offset_uv.y);\n\t\ttopleft_uv = floor(topleft_uv) * u_shadow_params.x;\n\t\tfloat topleft = pixelShadow( topleft_uv );\n\t\tfloat topright = pixelShadow( topleft_uv + vec2(u_shadow_params.x,0.0) );\n\t\tfloat bottomleft = pixelShadow( topleft_uv + vec2(0.0, u_shadow_params.x) );\n\t\tfloat bottomright = pixelShadow( topleft_uv + vec2(u_shadow_params.x, u_shadow_params.x) );\n\t\tfloat top = mix( topleft, topright, offset_uv.x );\n\t\tfloat bottom = mix( bottomleft, bottomright, offset_uv.x );\n\t\treturn mix( top, bottom, offset_uv.y );\n\t}\n';
sa._disabled_fragment_code="\nfloat testShadow( Light LIGHT ) { return 1.0; }\n";var sc=new d.ShaderBlock("depth_in_color");sc.register();sa.depth_in_color_block=sc;var Ub=new d.ShaderBlock("testShadow");Ub.addCode(GL.VERTEX_SHADER,sa._enabled_vertex_code,sa._disabled_vertex_code);Ub.addCode(GL.FRAGMENT_SHADER,sa._enabled_fragment_code,sa._disabled_fragment_code);Ub.register();sa.shader_block=Ub;var yc={picking_color_offset:10,_picking_points:[],_picking_nodes:null,_pickingMap:null,_picking_color:new Uint8Array(4),
_picking_depth:0,_picking_next_color_id:0,_picking_render_settings:new Ta,_use_scissor_test:!0,getNodeAtCanvasPosition:function(a,b,c,e,g){return(a=this.getInstanceAtCanvasPosition(a,b,c,e,g))?a.constructor==d.SceneNode?a:a._root&&a._root.constructor==d.SceneNode?a._root:a.node?a.node:null:null},getInstanceAtCanvasPosition:function(a,b,c,e,g){g=g||d.GlobalScene;c||(c=d.Renderer.getCameraAtPosition(a,b,g._cameras));if(!c)return null;this._picking_nodes={};this.getPickingColorFromBuffer(g,c,a,b,e);
this._picking_color[3]=0;a=(new Uint32Array(this._picking_color.buffer))[0];a=this._picking_nodes[a];this._picking_nodes={};return a},getNextPickingColor:function(a){this._picking_next_color_id+=this.picking_color_offset;var b=new Uint32Array(1);b[0]=this._picking_next_color_id;b=new Uint8Array(b.buffer);this._picking_nodes||(this._picking_nodes={});this._picking_nodes[this._picking_next_color_id]=a;return vec4.fromValues(b[0]/255,b[1]/255,b[2]/255,1)},getPickingColorFromBuffer:function(a,b,c,e,g){if(null==
this._pickingMap||this._pickingMap.width!=gl.canvas.width||this._pickingMap.height!=gl.canvas.height)this._pickingMap=new GL.Texture(gl.canvas.width,gl.canvas.height,{format:gl.RGBA,filter:gl.NEAREST}),this._pickingFBO=new GL.FBO([this._pickingMap]);var f=this._use_scissor_test;d.Renderer._current_target=this._pickingMap;this._pickingFBO.bind();f&&(gl.scissor(c-1,e-1,2,2),gl.enable(gl.SCISSOR_TEST));this.renderPickingBuffer(a,b,g,[c,e]);gl.readPixels(c,e,1,1,gl.RGBA,gl.UNSIGNED_BYTE,this._picking_color);
f&&gl.disable(gl.SCISSOR_TEST);this._pickingFBO.unbind();d.Renderer._current_target=null;return this._picking_color},renderPickingBuffer:function(a,b,c,e){void 0===c&&(c=65535);var g=this._picking_render_settings;d.Renderer.enableCamera(b,this._picking_render_settings);gl.clearColor(0,0,0,0);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);this._picking_next_color_id=0;d.Renderer.setRenderPass(hc);g.layers=c;c=null;if(e){if(b=b.getRay(e[0],e[1]),b=d.Physics.raycastRenderInstances(b.origin,b.direction)){c=
Array(b.length);for(var f=0;f<b.length;++f)c[f]=b[f].instance}}else c=a._instances;d.Renderer.renderInstances(g,c);LEvent.trigger(a,"renderPicking",e);LEvent.trigger(d.Renderer,"renderPicking",e);d.Renderer.setRenderPass(tb)},addPickingPoint:function(a,b,c){b=b||5;c=d.Picking.getNextPickingColor(c);this._picking_points.push([a,c,b])},renderPickingPoints:function(){if(this._picking_points.length){for(var a=new Float32Array(3*this._picking_points.length),b=new Float32Array(4*this._picking_points.length),
c=new Float32Array(this._picking_points.length),e=0;e<this._picking_points.length;e++)a.set(this._picking_points[e][0],3*e),b.set(this._picking_points[e][1],4*e),c[e]=this._picking_points[e][2];d.Draw.setPointSize(1);d.Draw.setColor([1,1,1,1]);gl.disable(gl.DEPTH_TEST);d.Draw.renderPointsWithSize(a,b,c);gl.enable(gl.DEPTH_TEST);this._picking_points.length=0}},visualize:function(a){d.Renderer.setRenderPass(a?d.PICKING_PASS:d.COLOR_PASS)}};d.Picking=yc;bc.isCloser=function(a,b){return a.distance-b.distance};
d.Collision=bc;Wa.BOX=1;Wa.SPHERE=2;Wa.PLANE=3;Wa.CAPSULE=4;Wa.MESH=5;Wa.FUNCTION=6;Wa.prototype.updateAABB=function(){BBox.transformMat4(this.aabb,this.oobb,this.matrix)};Wa.prototype.setMesh=function(a){this.mesh=a;this.type=Wa.MESH;BBox.setCenterHalfsize(this.oobb,BBox.getCenter(a.bounding),BBox.getHalfsize(a.bounding))};d.PhysicsInstance=Wa;d.Physics={raycast:function(a,b,c){c=c||{};if(!a||!b)throw"Physics.raycast: origin or direction missing.";var e=c.layers;void 0===e&&(e=65535);var g=c.max_distance||
Number.MAX_VALUE,f=c.scene||d.GlobalScene,h=c.first_collision,f=c.colliders||f._colliders,k=[];c=!!c.normal;if(!f)return null;for(var l=vec3.create(),n=vec3.create(),p=0;p<f.length;++p){var m=f[p];if(0!==(e&m.layers)){var q=vec3.create(),s=null;if(geo.testRayBBox(a,b,m.aabb,null,q,g)){var t=m.matrix,u=null;if(m.type==Wa.SPHERE){if(!geo.testRaySphere(a,b,m.center,m.oobb[3],q,g))continue;c&&(s=vec3.sub(vec3.create(),q,m.center))}else{var H=mat4.invert(mat4.create(),t);mat4.multiplyVec3(l,H,a);mat4.rotateVec3(n,
H,b);if(!geo.testRayBBox(l,n,m.oobb,null,q,g))continue;if(m.type==Wa.MESH){u=m.mesh.octree;u||(u=m.mesh.octree=new GL.Octree(m.mesh));u=u.testRay(l,n,0,g);if(!u)continue;mat4.multiplyVec3(q,t,u.pos);c&&(s=mat4.rotateVec3(vec3.create(),t,u.normal))}else vec3.transformMat4(q,q,t)}t=vec3.distance(a,q);k.push(new d.Collision(m.node,m,q,t,s,u));if(h)return k}}}k.sort(bc.isCloser);return k},testSphere:function(a,b,c){c=c||{};var e=c.layers;void 0===e&&(e=65535);var g=c.scene||d.GlobalScene;c=c.colliders||
g._colliders;g=vec3.create();if(!c)return null;for(var f=0;f<c.length;++f){var h=c[f];if(0!==(e&h.layers)&&geo.testSphereBBox(a,b,h.aabb)){var k=h.matrix,k=mat4.invert(mat4.create(),k);mat4.multiplyVec3(g,k,a);if(h.type==d.PhysicsInstance.SPHERE){if(vec3.distance(a,g)>b+BBox.getRadius(h.oobb))continue}else{if(!geo.testSphereBBox(g,b,h.oobb))continue;if(h.type==d.PhysicsInstance.MESH&&(k=h.mesh.octree,k||(k=h.mesh.octree=new GL.Octree(h.mesh)),!k.testSphere(g,b)))continue}return h}}return null},testCollision:function(a,
b){return geo.testBBoxBBox(a.aabb,b.aabb)?!0:!1},testAllCollisions:function(a,b,c){void 0===b&&(b=65535);c=c||d.GlobalScene;c=c._colliders;for(var e=c.length,g=!1,f=0;f<e;++f){var h=c[f];if(0!==(b&h.layers))for(var k=f+1;k<e;++k){var l=c[k];0!==(b&l.layers)&&this.testCollision(h,l)&&(a&&a(h,l),g=!0)}}return g},raycastRenderInstances:function(a,b,c){c=c||{};var e=c.layers;void 0===e&&(e=65535);var g=c.max_distance||Number.MAX_VALUE,f=c.scene||d.GlobalScene,h=!!c.triangle_collision,k=!!c.first_collision,
l=!!c.normal,n=!!c.ignore_transparent;c=c.instances||f._instances;if(!c||!c.length)return null;for(var f=[],p=vec3.create(),m=vec3.create(),q=0,s=c.length;q<s;++q){var t=c[q];if(0!==(e&t.layers)&&!(t.material&&t.material.render_state.blend&&n)){var u=vec3.create();if(geo.testRayBBox(a,b,t.aabb,null,u,g)){var H=t.matrix,G=null,Z=mat4.invert(mat4.create(),H);mat4.multiplyVec3(p,Z,a);mat4.rotateVec3(m,Z,b);if(geo.testRayBBox(p,m,t.oobb,null,u,g)){Z=null;if(h){var G=t.lod_mesh||t.mesh,M=G.octree;M||(M=
G.octree=new GL.Octree(G));G=M.testRay(p,m,0,g);if(!G)continue;mat4.multiplyVec3(u,H,G.pos);l&&(Z=mat4.rotateVec3(vec3.create(),H,G.normal))}else vec3.transformMat4(u,u,H);H=vec3.distance(a,u);H<g&&f.push(new d.Collision(t.node,t,u,H,Z,G));if(k)return f}}}}f.sort(d.Collision.isCloser);return f},raycastNode:function(a,b,c,e){e=e||{};e.instances=c._instances;return this.raycastRenderInstances(a,b,e)}};r.temp_matrix=mat4.create();r.icon="mini-icon-gizmo.png";r.ZERO=vec3.create();r.UP=vec3.fromValues(0,
1,0);r.RIGHT=vec3.fromValues(1,0,0);r.FRONT=vec3.fromValues(0,0,-1);r.TRANS10_IDENTITY=new Float32Array([0,0,0,0,0,0,1,1,1,1]);r["@rotation"]={type:"quat"};r["@data"]={type:"trans10"};r.properties={position:"vec3",scaling:"vec3",rotation:"quat"};r.prototype.onAddedToNode=function(a){a.transform||(a.transform=this)};r.prototype.onRemovedFromNode=function(a){a.transform==this&&delete a.transform};Object.defineProperty(r.prototype,"position",{get:function(){return this._position},set:function(a){a&&
a.length&&(this._position.set(a),this._must_update=!0)},enumerable:!0});Object.defineProperty(r.prototype,"x",{get:function(){return this._position[0]},set:function(a){this._position[0]=a;this._must_update=!0},enumerable:!1});Object.defineProperty(r.prototype,"y",{get:function(){return this._position[1]},set:function(a){this._position[1]=a;this._must_update=!0},enumerable:!1});Object.defineProperty(r.prototype,"z",{get:function(){return this._position[2]},set:function(a){this._position[2]=a;this._must_update=
!0},enumerable:!1});Object.defineProperty(r.prototype,"rotation",{get:function(){return this._rotation},set:function(a){this._rotation.set(a);this._must_update=!0},enumerable:!0});Object.defineProperty(r.prototype,"scaling",{get:function(){return this._scaling},set:function(a){a.constructor===Number?this._scaling[0]=this._scaling[1]=this._scaling[2]=a:this._scaling.set(a);this._must_update=!0},enumerable:!0});Object.defineProperty(r.prototype,"matrix",{get:function(){this._must_update&&this.updateMatrix();
return this._local_matrix},set:function(a){this.fromMatrix(a)},enumerable:!0});Object.defineProperty(r.prototype,"data",{get:function(){return this._data},set:function(a){this._data.set(a);this._must_update=!0},enumerable:!1});Object.defineProperty(r.prototype,"xrotation",{get:function(){return 0},set:function(a){this.rotateX(a*DEG2RAD)},enumerable:!1});Object.defineProperty(r.prototype,"yrotation",{get:function(){return 0},set:function(a){this.rotateY(a*DEG2RAD)},enumerable:!1});Object.defineProperty(r.prototype,
"zrotation",{get:function(){return 0},set:function(a){this.rotateZ(a*DEG2RAD)},enumerable:!1});Object.defineProperty(r.prototype,"globalPosition",{get:function(){return this.getGlobalPosition()},set:function(a){},enumerable:!0});Object.defineProperty(r.prototype,"globalMatrix",{get:function(){this.updateGlobalMatrix();return this._global_matrix},set:function(a){throw"globalMatrix cannot be set, use fromMatrix(m,true)";},enumerable:!0});Object.defineProperty(r.prototype,"forward",{get:function(){this.updateGlobalMatrix();
return mat4.rotateVec3(vec3.create(),this._global_matrix,d.FRONT)},set:function(a){throw"forward cannot be set";},enumerable:!1});Object.defineProperty(r.prototype,"mustUpdate",{get:function(){return this._must_update},set:function(a){this._must_update=!0},enumerable:!1});r.prototype.getPropertiesInfo=function(a){return"output"==a?{position:"vec3",scaling:"vec3",rotation:"quat",matrix:"mat4",globalPosition:"vec3",globalMatrix:"mat4"}:{position:"vec3",scaling:"vec3",rotation:"quat",matrix:"mat4"}};
r.prototype.copyFrom=function(a){this.configure(a.serialize())};r.prototype.configure=function(a){a.uid&&(this.uid=a.uid);a.position&&this._position.set(a.position);a.scaling&&this._scaling.set(a.scaling);a.rotation&&4==a.rotation.length&&this._rotation.set(a.rotation);if(a.rotation&&3==a.rotation.length){quat.identity(this._rotation);var b=quat.setAngleAxis(quat.create(),[1,0,0],a.rotation[0]*DEG2RAD);quat.multiply(this._rotation,this._rotation,b);quat.setAngleAxis(b,[0,1,0],a.rotation[1]*DEG2RAD);
quat.multiply(this._rotation,this._rotation,b);quat.setAngleAxis(b,[0,0,1],a.rotation[2]*DEG2RAD);quat.multiply(this._rotation,this._rotation,b)}this._must_update=!0;this.updateGlobalMatrix();this._on_change()};r.prototype.serialize=function(a){var b={object_class:"Transform",uid:this.uid,position:[this._position[0],this._position[1],this._position[2]],rotation:[this._rotation[0],this._rotation[1],this._rotation[2],this._rotation[3]],scaling:[this._scaling[0],this._scaling[1],this._scaling[2]]};this.isIdentity()||
a||(b.matrix=Array.apply([],this._local_matrix));return b};r.prototype.isIdentity=function(){for(var a=0;a<this._local_matrix.length;++a)if(0.001<Math.abs(this._local_matrix[a]-d.IDENTITY[a]))return!1;return!0};r.prototype.identity=function(){vec3.copy(this._position,d.ZEROS);quat.identity(this._rotation);vec3.copy(this._scaling,d.ONES);mat4.identity(this._local_matrix);mat4.identity(this._global_matrix);this._version+=1;this._must_update=!1};r.prototype.reset=r.prototype.identity;r.prototype.resetRotation=
function(){quat.identity(this._rotation);this._version+=1;this._must_update=!0;this._on_change()};r.prototype.resetPosition=function(){vec3.copy(this._position,d.ZEROS);this._version+=1;this._must_update=!0;this._on_change(!0)};r.prototype.resetScale=function(){vec3.copy(this._scaling,d.ONES);this._version+=1;this._must_update=!0;this._on_change(!0)};r.prototype.getPosition=function(a){a=a||vec3.create();a.set(this._position);return a};r.prototype.getGlobalPosition=function(a){a=a||vec3.create();
return this._parent?mat4.multiplyVec3(a,this.getGlobalMatrix(),r.ZERO):vec3.copy(a,this._position)};r.prototype.getRotation=function(a){a=a||quat.create();return vec3.copy(a,this._rotation)};r.prototype.getGlobalRotation=function(a){a=a||quat.create();if(!this._parent)return quat.copy(a,this._rotation),a;var b=this._parent;for(quat.copy(a,this._rotation);b;)quat.multiply(a,b._rotation,a),b=b._parent;return a};r.prototype.getScale=function(a){a=a||vec3.create();return vec3.copy(a,this._scaling)};r.prototype.getGlobalScale=
function(a){a=a||vec3.create();if(this._parent){var b=this;for(vec3.copy(a,this._scaling);b._parent;)vec3.multiply(a,a,b._scaling),b=b._parent;return a}return vec3.copy(a,this._scaling)};r.prototype.updateMatrix=function(){mat4.fromRotationTranslation(this._local_matrix,this._rotation,this._position);mat4.scale(this._local_matrix,this._local_matrix,this._scaling);this._must_update=!1;this._version+=1;this.updateDescendants()};r.prototype.updateLocalMatrix=r.prototype.updateMatrix;r.prototype.updateGlobalMatrix=
function(a){this._must_update&&this.updateMatrix();this._parent?mat4.multiply(this._global_matrix,a?this._parent._global_matrix:this._parent.getGlobalMatrix(this._parent._global_matrix),this._local_matrix):this._global_matrix.set(this._local_matrix)};r.prototype.getMatrix=function(a){a=a||mat4.create();this._must_update&&this.updateMatrix();return mat4.copy(a,this._local_matrix)};r.prototype.getLocalMatrix=r.prototype.getMatrix;r.prototype.getLocalMatrixRef=function(){this._must_update&&this.updateMatrix();
return this._local_matrix};r.prototype.getGlobalMatrix=function(a,b){this._must_update&&this.updateMatrix();a=a||mat4.create();this._parent?mat4.multiply(this._global_matrix,b?this._parent._global_matrix:this._parent.getGlobalMatrix(this._parent._global_matrix),this._local_matrix):mat4.copy(this._global_matrix,this._local_matrix);return mat4.copy(a,this._global_matrix)};r.prototype.getGlobalMatrixRef=function(a){this.updateGlobalMatrix(a);return this._global_matrix};r.prototype.getAncestors=function(){for(var a=
[this],b=this;b=b._parent;)a.unshift(b);return a};r.prototype.getGlobalTranslationMatrix=function(){var a=this.getGlobalPosition();return mat4.fromValues(1,0,0,0,0,1,0,0,0,0,1,0,a[0],a[1],a[2],1)};r.prototype.getGlobalRotationMatrix=function(a){a=a||mat4.create();if(!this._parent)return mat4.fromQuat(a,this._rotation);for(var b=mat4.create(),c=this;c;)mat4.fromQuat(b,c._rotation),mat4.multiply(a,a,b),c=c._parent;return a};r.prototype.getGlobalTranslationRotationMatrix=function(){var a=this.getGlobalPosition();
return mat4.fromRotationTranslation(mat4.create(),this.getGlobalRotation(),a)};r.prototype.getGlobalMatrixWithoutScale=r.prototype.getGlobalTranslationRotationMatrix;r.prototype.getNormalMatrix=function(a){this._must_update&&this.updateMatrix();a=a||mat4.create();this._parent?mat4.multiply(this._global_matrix,this._parent.getGlobalMatrix(),this._local_matrix):a.set(this._local_matrix);return mat4.transpose(a,mat4.invert(a,a))};r.prototype.fromMatrix=function(){var a=mat4.create(),b=mat4.create(),
c=mat3.create(),e=vec3.create();return function(g,f){if(f&&this._parent){mat4.copy(this._global_matrix,g);var h=this._parent.getGlobalMatrix(a);if(!mat4.invert(h,h))return;g=mat4.multiply(this._local_matrix,h,g)}b.set(g);mat4.multiplyVec3(this._position,b,d.ZEROS);this._scaling[0]=vec3.length(mat4.rotateVec3(e,b,d.RIGHT));this._scaling[1]=vec3.length(mat4.rotateVec3(e,b,d.TOP));this._scaling[2]=vec3.length(mat4.rotateVec3(e,b,d.BACK));vec3.normalize(b.subarray(0,3),b.subarray(0,3));vec3.normalize(b.subarray(4,
7),b.subarray(4,7));vec3.normalize(b.subarray(8,11),b.subarray(8,11));h=mat3.fromMat4(c,b);quat.fromMat3AndQuat(this._rotation,h);g!=this._local_matrix&&mat4.copy(this._local_matrix,g);this._must_update=!1;this._version+=1;this._on_change(!0)}}();r.prototype.fromGlobalMatrix=function(a){this.fromMatrix(a,!0)};r.fromMatrix4ToTransformData=function(){mat4.create();var a=mat4.create(),b=mat3.create(),c=vec3.create();return function(e,g){var f=g||new Float32Array(10),h=f.subarray(0,3),k=f.subarray(3,
7);quat.identity(k);var l=f.subarray(7,10);a.set(e);mat4.multiplyVec3(h,a,d.ZEROS);l[0]=vec3.length(mat4.rotateVec3(c,a,d.RIGHT));l[1]=vec3.length(mat4.rotateVec3(c,a,d.TOP));l[2]=vec3.length(mat4.rotateVec3(c,a,d.BACK));vec3.normalize(a.subarray(0,3),a.subarray(0,3));vec3.normalize(a.subarray(4,7),a.subarray(4,7));vec3.normalize(a.subarray(8,11),a.subarray(8,11));h=mat3.fromMat4(b,a);mat3.transpose(h,h);quat.fromMat3(k,h);quat.normalize(k,k);return f}}();r.prototype.setRotationFromEuler=function(a){quat.fromEuler(this._rotation,
a);this._must_update=!0;this._on_change()};r.prototype.setPosition=function(a,b,c){3==arguments.length?vec3.set(this._position,a,b,c):vec3.copy(this._position,a);this._must_update=!0;this._on_change(!0)};r.prototype.setRotation=function(a,b){b?quat.setAxisAngle(this._rotation,b,a):quat.copy(this._rotation,a);this._must_update=!0;this._on_change(!0)};r.prototype.setScale=function(a,b,c){3==arguments.length?vec3.set(this._scaling,a,b,c):vec3.set(this._scaling,a,a,a);this._must_update=!0;this._on_change(!0)};
r.prototype.translate=function(){var a=vec3.create(),b=vec3.create();return function(c,e,d){3==arguments.length?(b[0]=c,b[1]=e,b[2]=d,vec3.add(this._position,this._position,this.transformVector(b,a))):vec3.add(this._position,this._position,this.transformVector(c,a));this._must_update=!0;this._on_change(!0)}}();r.prototype.translateGlobal=function(a,b,c){3==arguments.length?vec3.add(this._position,this._position,[a,b,c]):vec3.add(this._position,this._position,a);this._must_update=!0;this._on_change(!0)};
r.prototype.rotate=function(){var a=quat.create(),b=quat.create();return function(c,e,d){d&&(e=this.globalVectorToLocal(e,b));quat.setAxisAngle(a,e,0.0174532925*c);quat.multiply(this._rotation,this._rotation,a);this._must_update=!0;this._on_change(!0)}}();r.prototype.rotateX=function(a){quat.rotateX(this._rotation,this._rotation,a);this._must_update=!0;this._on_change(!0)};r.prototype.rotateY=function(a){quat.rotateY(this._rotation,this._rotation,a);this._must_update=!0;this._on_change()};r.prototype.rotateZ=
function(a){quat.rotateZ(this._rotation,this._rotation,a);this._must_update=!0;this._on_change(!0)};r.prototype.rotateGlobal=function(a,b){var c=quat.setAxisAngle(quat.create(),b,0.0174532925*a);quat.multiply(this._rotation,c,this._rotation);this._must_update=!0;this._on_change(!0)};r.prototype.rotateQuat=function(a){quat.multiply(this._rotation,this._rotation,a);this._must_update=!0;this._on_change(!0)};r.prototype.rotateQuatGlobal=function(a){quat.multiply(this._rotation,a,this._rotation);this._must_update=
!0;this._on_change(!0)};r.prototype.scale=function(a,b,c){3==arguments.length?vec3.multiply(this._scaling,this._scaling,[a,b,c]):vec3.multiply(this._scaling,this._scaling,a);this._must_update=!0;this._on_change(!0)};r.interpolate=function(a,b,c,e){vec3.lerp(e._scaling,a._scaling,b._scaling,c);vec3.lerp(e._position,a._position,b._position,c);quat.slerp(e._rotation,a._rotation,b._rotation,c);this._must_update=!0;this._on_change()};r.prototype.orbit=function(){var a=quat.create(),b=vec3.create();return function(c,
e,d){if(!d)throw"Transform orbit requires a center";c=quat.setAxisAngle(a,e,0.0174532925*c);b.set(this._position);vec3.sub(b,b,d);vec3.transformQuat(b,b,c);vec3.add(b,b,d);this._position.set(b);this._must_update=!0}}();r.prototype.lookAt=function(){var a=mat4.create(),b=mat4.create(),c=vec3.create(),e=vec3.create(),g=vec3.create();return function(f,h,k,l){k=k||d.TOP;if(l&&this._parent){this._parent.getGlobalMatrix(a);l=mat4.invert(a,a);if(!l)return;mat4.multiplyVec3(c,l,f);mat4.multiplyVec3(e,l,h);
mat4.rotateVec3(g,l,k)}else c.set(f),e.set(h),g.set(k);mat4.lookAt(b,c,e,g);quat.fromMat4(this._rotation,b);this._position.set(c);this._must_update=!0}}();r.prototype.orientTo=function(){var a=mat4.create(),b=mat3.create(),c=vec3.create();return function(e,g,f,h){h=h||d.RIGHT;f=f||d.TOP;if(g&&this._parent){this._parent.getGlobalMatrix(a);g=mat4.invert(a,a);if(!g)return;mat4.multiplyVec3(c,g,e)}else c.set(e);mat3.setColumn(b,h,0);mat3.setColumn(b,f,1);mat3.setColumn(b,e,2);quat.fromMat3(this._rotation,
b);this._must_update=!0}}();r.prototype.orientAxis=function(){mat4.create();var a=mat3.create();return function(b,c){switch(c){case d.POSX:mat3.setColumn(a,b,0);mat3.setColumn(a,d.TOP,1);mat3.setColumn(a,d.FRONT,2);break;case d.POSY:mat3.setColumn(a,d.RIGHT,0);mat3.setColumn(a,b,1);mat3.setColumn(a,d.FRONT,2);break;case d.POSZ:mat3.setColumn(a,d.RIGHT,0);mat3.setColumn(a,d.TOP,1);mat3.setColumn(a,b,2);break;case d.NEGX:mat3.setColumn(a,b,0);mat3.setColumn(a,d.BOTTOM,1);mat3.setColumn(a,d.BACK,2);
break;case d.NEGY:mat3.setColumn(a,d.LEFT,0);mat3.setColumn(a,b,1);mat3.setColumn(a,d.BACK,2);break;case d.NEGZ:mat3.setColumn(a,d.LEFT,0);mat3.setColumn(a,d.BOTTOM,1);mat3.setColumn(a,b,2);break;default:return}quat.fromMat3(this._rotation,a);this._must_update=!0}}();r.prototype._on_change=function(a){a||(this._must_update=!0);LEvent.trigger(this,"changed",this);this._root&&LEvent.trigger(this._root,"transformChanged",this)};r.prototype.getFront=function(a){return vec3.transformQuat(a||vec3.create(),
r.FRONT,this.getGlobalRotation())};r.prototype.getTop=function(a){return vec3.transformQuat(a||vec3.create(),r.UP,this.getGlobalRotation())};r.prototype.getRight=function(a){return vec3.transformQuat(a||vec3.create(),r.RIGHT,this.getGlobalRotation())};r.prototype.transformPoint=function(a,b){b=b||vec3.create();this._must_update&&this.updateMatrix();return mat4.multiplyVec3(b,this._local_matrix,a)};r.prototype.localToGlobal=function(a,b){b=b||vec3.create();this._must_update&&this.updateMatrix();return mat4.multiplyVec3(b,
this.getGlobalMatrixRef(),a)};r.prototype.transformPointGlobal=r.prototype.localToGlobal;r.prototype.globalToLocal=function(){var a=mat4.create();return function(b,c){c=c||vec3.create();this._must_update&&this.updateMatrix();return mat4.invert(a,this.getGlobalMatrixRef())?mat4.multiplyVec3(c,a,b):a}}();r.prototype.transformVector=function(a,b){return vec3.transformQuat(b||vec3.create(),a,this._rotation)};r.prototype.localVectorToGlobal=function(a,b){return vec3.transformQuat(b||vec3.create(),a,this.getGlobalRotation())};
r.prototype.transformVectorGlobal=r.prototype.localVectorToGlobal;r.prototype.globalVectorToLocal=function(a,b){var c=this.getGlobalRotation();quat.invert(c,c);return vec3.transformQuat(b||vec3.create(),a,c)};r.prototype.applyTransform=function(a,b,c){vec3.add(this._position,this._position,a._position);quat.multiply(this._rotation,this._rotation,a._rotation);vec3.multiply(this._scaling,this._scaling,a._scaling);this._must_update=!0};r.prototype.applyTransformMatrix=function(){var a=mat4.create(),
b=vec3.create(),c=mat4.create();mat4.create();var e=mat4.create();return function(d,f,h){f&&(mat4.setTranslation(a,f),vec3.scale(b,f,-1),mat4.setTranslation(c,b),mat4.multiply(d,a,d),mat4.multiply(d,d,c));this._parent?(f=this.getGlobalMatrix(),h=this._parent._global_matrix,mat4.multiply(this._global_matrix,d,f),mat4.invert(e,h)&&(mat4.multiply(this._local_matrix,e,this._global_matrix),this.fromMatrix(this._local_matrix))):this.applyLocalTransformMatrix(d)}}();r.prototype.applyLocalTransformMatrix=
function(){var a=vec3.create(),b=mat3.create(),c=mat4.create(),e=quat.create();return function(d){vec3.transformMat4(this._position,this._position,d);mat4.rotateVec3(a,d,[1,0,0]);this._scaling[0]*=vec3.length(a);mat4.rotateVec3(a,d,[0,1,0]);this._scaling[1]*=vec3.length(a);mat4.rotateVec3(a,d,[0,0,1]);this._scaling[2]*=vec3.length(a);if(d=mat4.invert(c,d))mat4.transpose(d,d),d=mat3.fromMat4(b,d),d=quat.fromMat3(e,d),quat.normalize(d,d),quat.multiply(this._rotation,d,this._rotation),this._must_update=
!0,this._on_change()}}();r.prototype.updateDescendants=function(){if(this._root){var a=this._root._children;if(a)for(var b=0;b<a.length;++b){var c=a[b];c.transform&&(c.transform._must_update=!0,c.transform._version+=1,c._children&&c._children.length&&c.transform.updateDescendants())}}};d.registerComponent(r);d.Transform=r;w.icon="mini-icon-camera.png";w.PERSPECTIVE=1;w.ORTHOGRAPHIC=2;w.ORTHO2D=3;w.DEFAULT_EYE=[0,0,0];w.DEFAULT_CENTER=[0,0,-100];w.DEFAULT_UP=[0,1,0];w["@type"]={type:"enum",values:{perspective:w.PERSPECTIVE,
orthographic:w.ORTHOGRAPHIC,ortho2D:w.ORTHO2D}};w["@eye"]={type:"vec3",widget:"position"};w["@center"]={type:"vec3",widget:"position"};w["@layers"]={type:"layers"};w.cubemap_camera_parameters=[{name:"posx",dir:vec3.fromValues(1,0,0),up:vec3.fromValues(0,-1,0),crossx:2,crossy:1},{name:"negx",dir:vec3.fromValues(-1,0,0),up:vec3.fromValues(0,-1,0),crossx:0,crossy:1},{name:"posy",dir:vec3.fromValues(0,1,0),up:vec3.fromValues(0,0,1),crossx:1,crossy:0},{name:"negy",dir:vec3.fromValues(0,-1,0),up:vec3.fromValues(0,
0,-1),crossx:1,crossy:2},{name:"posz",dir:vec3.fromValues(0,0,1),up:vec3.fromValues(0,-1,0),crossx:1,crossy:1},{name:"negz",dir:vec3.fromValues(0,0,-1),up:vec3.fromValues(0,-1,0),crossx:3,crossy:1}];w.prototype.onResourceRenamed=function(a,b){a==this.overwrite_material&&(this.overwrite_material=b)};w.prototype.getResources=function(a){this.overwrite_material&&this.overwrite_material.constructor===String&&(a[this.overwrite_material]=!0);return a};Object.defineProperty(w.prototype,"type",{get:function(){return this._type},
set:function(a){this._type!=a&&(this._must_update_projection_matrix=this._must_update_view_matrix=!0);this._type=a},enumerable:!0});Object.defineProperty(w.prototype,"eye",{get:function(){return this._eye},set:function(a){this._eye.set(a);this._must_update_view_matrix=!0},enumerable:!0});Object.defineProperty(w.prototype,"center",{get:function(){return this._center},set:function(a){this._center.set(a);this._must_update_view_matrix=!0},enumerable:!0});var Db=vec3.create();Object.defineProperty(w.prototype,
"focalLength",{get:function(){return vec3.distance(this._eye,this._center)},set:function(a){a=Math.max(0.001,a);vec3.sub(Db,this._center,this._eye);var b=vec3.length(Db);1E-4>b?Db.set([0,0,-1]):a/=b;vec3.scaleAndAdd(Db,this._eye,Db,a);this._center.set(Db);this._must_update_view_matrix=!0},enumerable:!0});Object.defineProperty(w.prototype,"up",{get:function(){return this._up},set:function(a){this._up.set(a);this._must_update_view_matrix=!0},enumerable:!0});Object.defineProperty(w.prototype,"near",
{get:function(){return this._near},set:function(a){this._near!=a&&(this._must_update_projection_matrix=!0);this._near=a},enumerable:!0});Object.defineProperty(w.prototype,"far",{get:function(){return this._far},set:function(a){this._far!=a&&(this._must_update_projection_matrix=!0);this._far=a},enumerable:!0});Object.defineProperty(w.prototype,"aspect",{get:function(){return this._aspect},set:function(a){this._aspect!=a&&(this._must_update_projection_matrix=!0);this._aspect=a},enumerable:!0});Object.defineProperty(w.prototype,
"final_aspect",{get:function(){return this._final_aspect},set:function(a){this._final_aspect!=a&&(this._must_update_projection_matrix=!0);this._final_aspect=a},enumerable:!1});Object.defineProperty(w.prototype,"fov",{get:function(){return this._fov},set:function(a){this._fov!=a&&(this._must_update_projection_matrix=!0);this._fov=a},enumerable:!0});Object.defineProperty(w.prototype,"frustum_size",{get:function(){return this._frustum_size},set:function(a){this._frustum_size!=a&&(this._must_update_projection_matrix=
!0,this._frustum_size=a)},enumerable:!0});Object.defineProperty(w.prototype,"orthographic",{get:function(){return this._ortho},set:function(a){!a||4>a.length||(this._ortho.set(a),this._must_update_projection_matrix=!0)},enumerable:!0});Object.defineProperty(w.prototype,"view_matrix",{get:function(){return this._view_matrix},set:function(a){this.fromViewMatrix(a)},enumerable:!0});Object.defineProperty(w.prototype,"projection_matrix",{get:function(){return this._projection_matrix},set:function(a){throw"projection matrix cannot be set manually, use setCustomProjectionMatrix instead.";
},enumerable:!0});Object.defineProperty(w.prototype,"viewport",{get:function(){return this._viewport},set:function(a){this._viewport.set(a)},enumerable:!0});Object.defineProperty(w.prototype,"viewport_offset",{get:function(){return this._viewport.subarray(0,2)},set:function(a){this._viewport.set(a)},enumerable:!0});Object.defineProperty(w.prototype,"viewport_size",{get:function(){return this._viewport.subarray(2,4)},set:function(a){this._viewport.set(a,2)},enumerable:!0});Object.defineProperty(w.prototype,
"background_color",{get:function(){return this._background_color},set:function(a){this._background_color.set(a)},enumerable:!0});Object.defineProperty(w.prototype,"background_alpha",{get:function(){return this._background_color[3]},set:function(a){this._background_color[3]=a},enumerable:!0});Object.defineProperty(w.prototype,"render_to_texture",{get:function(){return!!this._frame},set:function(a){a?this._frame||(this._frame=new d.RenderFrameContext):this._frame=null},enumerable:!0});Object.defineProperty(w.prototype,
"frame",{set:function(a){throw"frame cannot be assigned manually, enable render_to_texture";},get:function(){return this._frame},enumerable:!1});Object.defineProperty(w.prototype,"frame_color_texture",{set:function(a){throw"frame_color_texture cannot be assigned manually, enable render_to_texture";},get:function(a){return this._frame?this._frame.getColorTexture():null},enumerable:!1});Object.defineProperty(w.prototype,"frame_depth_texture",{set:function(a){throw"frame_depth_texture cannot be assigned manually, enable render_to_texture";
},get:function(){return this._frame?this._frame.getDepthTexture():null},enumerable:!1});Object.defineProperty(w.prototype,"mustUpdate",{get:function(){return this._must_update_projection_matrix||this._must_update_view_matrix},set:function(a){this._must_update_projection_matrix=this._must_update_view_matrix=a},enumerable:!0});w.prototype.onAddedToNode=function(a){a.camera||(a.camera=this);LEvent.bind(a,"transformChanged",this.onNodeMoved,this)};w.prototype.onRemovedFromNode=function(a){a.camera==this&&
delete a.camera;LEvent.unbind(a,"transformChanged",this.onNodeMoved,this)};w.prototype.onAddedToScene=function(a){LEvent.bind(a,"collectCameras",this.onCollectCameras,this)};w.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"collectCameras",this.onCollectCameras,this);this._frame&&this._frame.clear();this._binded_render_frame&&(LEvent.unbind(this,"enableFrameContext",this.enableRenderFrameContext,this),LEvent.unbind(this,"showFrameContext",this.disableRenderFrameContext,this),this._binded_render_frame=
!1)};w.prototype.onNodeMoved=function(){this._must_update_view_matrix=!0};w.prototype.isRenderedToTexture=function(){return this.enabled&&this.render_to_texture};w.prototype.onCollectCameras=function(a,b){this.enabled&&(this.isRenderedToTexture()?b.unshift(this):b.push(this),this._frame?this._binded_render_frame||(LEvent.bind(this,"enableFrameContext",this.enableRenderFrameContext,this),LEvent.bind(this,"showFrameContext",this.disableRenderFrameContext,this),this._binded_render_frame=!0):this._binded_render_frame&&
(LEvent.unbind(this,"enableFrameContext",this.enableRenderFrameContext,this),LEvent.unbind(this,"showFrameContext",this.disableRenderFrameContext,this),this._binded_render_frame=!1))};w.prototype.lookAt=function(a,b,c){this._root&&this._root.transform?(this._root.transform.lookAt(a,b,c),this._eye.set(d.ZEROS),this._up.set([0,1,0]),this.focalLength=vec3.distance(a,b)):(vec3.copy(this._eye,a),vec3.copy(this._center,b),vec3.copy(this._up,c));this._must_update_view_matrix=!0};w.prototype.lookAtFromMatrix=
function(a,b){if(this._root&&this._root.transform){if(!b){var c=mat4.create();a=mat4.invert(c,a)}this._root.transform.matrix=a;this._eye.set(d.ZEROS);this._up.set([0,1,0]);this._must_update_view_matrix=!0;this.focalLength=1}else{c=mat4.create();mat4.invert(c,a);var e=b?a:c;this._view_matrix.set(b?c:a);vec3.transformMat4(this._eye,d.ZEROS,e);vec3.transformMat4(this._center,d.FRONT,e);mat4.rotateVec3(this._up,e,d.TOP)}};w.prototype.resetVectors=function(a){a=a||1;this._eye.set([0,0,0]);this._center.set([0,
0,-a]);this._up.set([0,1,0]);this._must_update_view_matrix=!0};w.prototype.updateMatrices=function(a){this._must_update_view_matrix=this._must_update_view_matrix||this._root&&!this._root._is_root;if(this._must_update_projection_matrix||this._must_update_view_matrix||a){!this._must_update_projection_matrix&&!a||this._use_custom_projection_matrix||(this.type==w.ORTHOGRAPHIC?mat4.ortho(this._projection_matrix,-this._frustum_size*this._final_aspect*0.5,this._frustum_size*this._final_aspect*0.5,0.5*-this._frustum_size,
0.5*this._frustum_size,this._near,this._far):this.type==w.ORTHO2D?mat4.ortho(this._projection_matrix,this._ortho[0],this._ortho[1],this._ortho[2],this._ortho[3],this._near,this._far):mat4.perspective(this._projection_matrix,this._fov*DEG2RAD,this._final_aspect,this._near,this._far));if(this._must_update_view_matrix||a)this._root&&this._root._is_root?mat4.lookAt(this._view_matrix,this._eye,this._center,this._up):mat4.lookAt(this._view_matrix,this.getEye(this._global_eye),this.getCenter(this._global_center),
this.getUp(this._global_up)),mat4.invert(this._model_matrix,this._view_matrix);mat4.multiply(this._viewprojection_matrix,this._projection_matrix,this._view_matrix);this.updateFrustumPlanes();this._must_update_projection_matrix=this._must_update_view_matrix=!1}};w.prototype.updateFrustumPlanes=function(){this._frustum_planes||(this._frustum_planes=new Float32Array(24));geo.extractPlanes(this._viewprojection_matrix,this._frustum_planes);return this._frustum_planes};w.prototype.getModelMatrix=function(a){a=
a||mat4.create();this._must_update_view_matrix&&this.updateMatrices();return mat4.copy(a,this._model_matrix)};w.prototype.getViewMatrix=function(a){a=a||mat4.create();this._must_update_view_matrix&&this.updateMatrices();return mat4.copy(a,this._view_matrix)};w.prototype.getProjectionMatrix=function(a){a=a||mat4.create();this._must_update_projection_matrix&&this.updateMatrices();return mat4.copy(a,this._projection_matrix)};w.prototype.getViewProjectionMatrix=function(a,b){a=a||mat4.create();(this._must_update_view_matrix||
this._must_update_projection_matrix||b)&&this.updateMatrices();return mat4.copy(a,this._viewprojection_matrix)};w.prototype.getModelViewProjectionMatrix=function(a,b){b=b||mat4.create();(this._must_update_view_matrix||this._must_update_projection_matrix)&&this.updateMatrices();return mat4.multiply(b,this._viewprojection_matrix,a)};w.prototype.updateVectors=function(a){var b=vec3.subtract(vec3.create(),this._center,this._eye),b=vec3.length(b);this._eye=mat4.multiplyVec3(vec3.create(),a,vec3.create());
this._center=mat4.multiplyVec3(vec3.create(),a,vec3.fromValues(0,0,-b));this._up=mat4.rotateVec3(vec3.create(),a,vec3.fromValues(0,1,0));this.updateMatrices()};w.prototype.getLocalPoint=function(a,b){b=b||vec3.create();if(this._root&&this._root.transform)return mat4.multiplyVec3(b,this._root.transform.getGlobalMatrixRef(),a);this._must_update_view_matrix&&this.updateMatrices();return mat4.multiplyVec3(b,this._model_matrix,a)};w.prototype.getLocalVector=function(a,b){b=b||vec3.create();if(this._root&&
this._root.transform)return mat4.rotateVec3(b,this._root.transform.getGlobalMatrixRef(),a);this._must_update_view_matrix&&this.updateMatrices();return mat4.rotateVec3(b,this._model_matrix,a)};w.prototype.getEye=function(a){a=a||vec3.create();a[0]=this._eye[0];a[1]=this._eye[1];a[2]=this._eye[2];return this._root&&this._root.transform?this._root.transform.getGlobalPosition(a):a};w.prototype.getCenter=function(a){a=a||vec3.create();if(this._root&&this._root.transform)return mat4.multiplyVec3(a,this._root.transform.getGlobalMatrixRef(),
this._center);a[0]=this._center[0];a[1]=this._center[1];a[2]=this._center[2];return a};w.prototype.getFront=function(a){a=a||vec3.create();if(this._root&&this._root.transform)return a[0]=a[1]=0,a[2]=-1,mat4.rotateVec3(a,this._root.transform.getGlobalMatrixRef(),a);vec3.sub(a,this._center,this._eye);return vec3.normalize(a,a)};w.prototype.getUp=function(a){a=a||vec3.create();a[0]=this._up[0];a[1]=this._up[1];a[2]=this._up[2];return this._root&&this._root.transform?mat4.rotateVec3(a,this._root.transform.getGlobalMatrixRef(),
a):a};w.prototype.getTop=function(a){a=a||vec3.create();var b=vec3.sub(vec3.create(),this._center,this._eye),c=vec3.cross(vec3.create(),this._up,b);a=vec3.cross(a,b,c);vec3.normalize(a,a);return this._root&&this._root.transform&&this._root._parent?mat4.rotateVec3(a,this._root.transform.getGlobalMatrixRef(),a):a};w.prototype.getRight=function(a){a=a||vec3.create();var b=vec3.sub(vec3.create(),this._center,this._eye);a=vec3.cross(a,this._up,b);vec3.normalize(a,a);return this._root&&this._root.transform&&
this._root._parent?mat4.rotateVec3(a,this._root.transform.getGlobalMatrixRef(),a):a};w.prototype.setEye=function(a){this._eye.set(a);this._must_update_view_matrix=!0};w.prototype.setCenter=function(a){this._center.set(a);this._must_update_view_matrix=!0};w.prototype.setPerspective=function(a,b,c,e){this._fov=a;this._aspect=b;this._near=c;this._far=e;this._type=w.PERSPECTIVE;this._must_update_projection_matrix=!0};w.prototype.setOrthographic=function(a,b,c,e,d,f){this._near=d;this._far=f;this._ortho.set([a,
b,c,e]);this._type=w.ORTHO2D;this._must_update_projection_matrix=!0};w.prototype.move=function(a){this._root&&this._root.transform?this._root.transform.move(a):(vec3.add(this._center,this._center,a),vec3.add(this._eye,this._eye,a));this._must_update_view_matrix=!0};w.prototype.rotate=function(){var a=quat.create(),b=vec3.create();return function(c,e,d){0!=c&&(this._root&&this._root.transform?this._root.transform.rotate(c,e,!d):(d?this.getLocalVector(e,b):b.set(e),c=quat.setAxisAngle(a,b,0.0174532925*
c),e=vec3.subtract(b,this._center,this._eye),vec3.transformQuat(e,e,c),vec3.add(this._center,this._eye,e)),this._must_update_view_matrix=!0)}}();w.prototype.orbit=function(){var a=quat.create(),b=vec3.create();return function(c,e,d){c=c||0;if(0!=c){if(!e)throw"axis missing";this._root&&this._root.transform?this._root.transform.orbit(c,e,d||this.getCenter()):(d=d||this._center,c=quat.setAxisAngle(a,e,0.0174532925*c),e=vec3.subtract(b,this._eye,d),vec3.transformQuat(e,e,c),vec3.add(this._eye,d,e));
this._must_update_view_matrix=!0}}}();w.prototype.orbitDistanceFactor=function(a,b){b=b||this._center;var c=vec3.subtract(vec3.create(),this._eye,b);vec3.scale(c,c,a);vec3.add(this._eye,b,c);this._must_update_view_matrix=!0};w.prototype.panning=function(a,b){var c=vec3.create(),e=vec3.create(),g=vec3.create();return function(a,b,k){k=k||1;this.getLocalVector(d.TOP,c);this.getLocalVector(d.RIGHT,e);vec3.scaleAndAdd(g,d.ZEROS,c,b*k);vec3.scaleAndAdd(g,g,e,a*k);this.move(g)}}();w.prototype.setDistanceToCenter=
function(a,b){if(this._root)console.warn("cannot use setDistanceToCenter in a camera attached to a node");else{var c=vec3.sub(vec3.create(),this._center,this._eye),e=vec3.length(c);b?vec3.scaleAndAdd(this._eye,this._center,c,-a/e):vec3.scaleAndAdd(this._center,this._eye,c,a/e);this._must_update_view_matrix=!0}};w.prototype.setOrientation=function(a,b){var c=this.getCenter(),e=this.getEye(),d=[0,1,0],c=vec3.sub(vec3.create(),c,e),c=vec3.length(c),f=null,f=vec3.fromValues(0,0,-c);b&&(vec3.rotateY(f,
f,-0.5*Math.PI),vec3.rotateY(d,d,-0.5*Math.PI));vec3.transformQuat(f,f,a);vec3.transformQuat(d,d,a);b&&(vec3.rotateY(f,f,0.5*Math.PI),vec3.rotateY(d,d,0.5*Math.PI));this.center=vec3.add(vec3.create(),e,f);this.up=d;this._must_update_view_matrix=!0};w.prototype.setEulerAngles=function(a,b,c){var e=quat.create();quat.fromEuler(e,[a,b,c]);this.setOrientation(e)};w.prototype.fromViewMatrix=function(a){this._root&&this._root.transform?(a=mat4.invert(mat4.create(),a),this._root.transform.fromMatrix(a,!0)):
(a=mat4.invert(mat4.create(),a),this.eye=vec3.transformMat4(vec3.create(),d.ZEROS,a),this.center=vec3.transformMat4(vec3.create(),d.FRONT,a),this.up=mat4.rotateVec3(vec3.create(),a,d.TOP),this._must_update_view_matrix=!0)};w.prototype.setCustomProjectionMatrix=function(a){a?(this._use_custom_projection_matrix=!0,this._projection_matrix.set(a),this._must_update_projection_matrix=!1,mat4.multiply(this._viewprojection_matrix,this._projection_matrix,this._view_matrix)):(this._use_custom_projection_matrix=
!1,this._must_update_projection_matrix=!0)};w.prototype.setViewportInPixels=function(a,b,c,e){this._viewport[0]=a/gl.canvas.width;this._viewport[1]=b/gl.canvas.height;this._viewport[2]=c/gl.canvas.width;this._viewport[3]=e/gl.canvas.height};w.prototype.project=function(a,b,c,e){c=c||vec3.create();if(!a)throw"camera project parameter 'vec' cannot be null";b=this.getLocalViewport(b);(this._must_update_view_matrix||this._must_update_projection_matrix)&&this.updateMatrices();vec3.project(c,a,this._viewprojection_matrix,
b);e||(c[1]=b[3]-c[1]+2*b[1]);return c};w.prototype.projectNodeCenter=function(a,b,c,e){a=a.transform?a.transform.getGlobalPosition():d.ZEROS;return this.project(a,b,c,e)};w.prototype.unproject=function(a,b,c){b=this.getLocalViewport(b);(this._must_update_view_matrix||this._must_update_projection_matrix)&&this.updateMatrices();return vec3.unproject(c||vec3.create(),a,this._viewprojection_matrix,b)};w.prototype.getLocalViewport=function(a,b){b=b||vec4.create();if(!a)return b[0]=gl.canvas.width*this._viewport[0],
b[1]=gl.canvas.height*this._viewport[1],b[2]=gl.canvas.width*this._viewport[2],b[3]=gl.canvas.height*this._viewport[3],b;b[0]=Math.floor(a[2]*this._viewport[0]+a[0]);b[1]=Math.floor(a[3]*this._viewport[1]+a[1]);b[2]=Math.ceil(a[2]*this._viewport[2]);b[3]=Math.ceil(a[3]*this._viewport[3]);return b};w.prototype.mouseToViewport=function(a,b){b=b||vec2.create();var c=this._last_viewport_in_pixels;b[0]=a[0]-c[0];b[1]=c[3]-(a[1]-c[1]);return b};w.prototype.getRay=function(){var a=vec3.create(),b=vec3.create();
return function(c,e,g,f,h){g=f?gl.viewport_data:this.getLocalViewport(g,this._viewport_in_pixels);(this._must_update_view_matrix||this._must_update_projection_matrix)&&this.updateMatrices();a[0]=c;a[1]=e;a[2]=1;var k=vec3.unproject(a,a,this._viewprojection_matrix,g);if(!k)return null;f=null;this.type==w.ORTHOGRAPHIC?(b[0]=c,b[1]=e,b[2]=0,f=vec3.unproject(b,b,this._viewprojection_matrix,g)):f=this.getEye(b);c=vec3.subtract(k,k,f);vec3.normalize(c,c);h=h||new d.Ray;h.origin.set(f);h.direction.set(c);
return h}}();w.prototype.getRayInPixel=w.prototype.getRay;w.prototype.isPoint2DInCameraViewport=function(a,b,c){c=this.getLocalViewport(c,this._viewport_in_pixels);return a<c[0]||a>c[0]+c[2]||b<c[1]||b>c[1]+c[3]?!1:!0};w.prototype.testSphereInsideFrustum=function(a,b){return geo.frustumTestSphere(this._frustum_planes,a,b||0)!=CLIP_OUTSIDE};w.prototype.configure=function(a){void 0!==a.uid&&(this.uid=a.uid);void 0!==a.layers&&(this.layers=a.layers);void 0!==a.enabled&&(this.enabled=a.enabled);void 0!==
a.type&&(this._type=a.type);void 0!==a.eye&&this._eye.set(a.eye);void 0!==a.center&&this._center.set(a.center);void 0!==a.up&&this._up.set(a.up);void 0!==a.near&&(this._near=a.near);void 0!==a.far&&(this._far=a.far);void 0!==a.fov&&(this._fov=a.fov);void 0!==a.aspect&&(this._aspect=a.aspect);void 0!==a.final_aspect&&(this._final_aspect=a.final_aspect);void 0!==a.frustum_size&&(this._frustum_size=a.frustum_size);void 0!==a.viewport&&this._viewport.set(a.viewport);void 0!==a.orthographic&&this._ortho.set(a.orthographic);
void 0!==a.background_color&&this._background_color.set(a.background_color);void 0!==a.render_to_texture&&(this.render_to_texture=a.render_to_texture);a.frame&&this._frame&&this._frame.configure(a.frame);void 0!==a.show_frame&&(this.show_frame=a.show_frame);void 0!==a.clear_color&&(this.clear_color=!!a.clear_color);void 0!==a.clear_depth&&(this.clear_depth=!!a.clear_depth);this.updateMatrices(!0)};w.prototype.serialize=function(){return{object_class:"Camera",uid:this.uid,layers:this.layers,enabled:this.enabled,
type:this._type,eye:vec3.toArray(this._eye),center:vec3.toArray(this._center),up:vec3.toArray(this._up),near:this._near,far:this._far,fov:this._fov,aspect:this._aspect,orthographic:vec4.toArray(this._ortho),background_color:vec4.toArray(this._background_color),frustum_size:this._frustum_size,viewport:Array.apply([],this._viewport),render_to_texture:this.render_to_texture,frame:this._frame?this._frame.serialize():null,show_frame:this.show_frame,clear_color:this.clear_color,clear_depth:this.clear_depth}};
w.prototype.checkLayersVisibility=function(a){return 0!==(this.layers&a)};w.prototype.getLayers=function(){for(var a=[],b=0;32>b;++b)this.layers&1<<b&&a.push(this._root.scene.layer_names[b]||"layer"+b);return a};w.prototype.setLayer=function(a,b){var c=1<<a;this.layers&=~c;b&&(this.layers|=c)};w.prototype.isInLayer=function(a){return 0!==(this.layers&1<<a)};w.prototype.getTransformMatrix=function(a){if(this._root&&this._root.transform)return null;var b=null,b="center"==a?this._center:this._eye;a=
mat4.create();mat4.setTranslation(a,b);return a};w.prototype.applyTransformMatrix=function(a,b,c){if(this._root&&this._root.transform)return!1;b=null;b="center"==c?this._center:this._eye;mat4.multiplyVec3(b,a,b);return this._must_update_view_matrix=!0};w.prototype.enableRenderFrameContext=function(){this._frame&&this._frame.enable()};w.prototype.disableRenderFrameContext=function(){this._frame&&(this._frame.disable(),this.show_frame&&d.Renderer.showRenderFrameContext(this._frame,this))};w.prototype.prepare=
function(){this._previous_viewprojection_matrix.set(this._viewprojection_matrix);this.updateMatrices();this.fillShaderUniforms()};w.prototype.fillShaderUniforms=function(){var a=this._uniforms;a.u_camera_planes[0]=this.near;a.u_camera_planes[1]=this.far;this.type==d.Camera.PERSPECTIVE?a.u_camera_perspective.set([this.fov*DEG2RAD,512/Math.tan(this.fov*DEG2RAD)]):a.u_camera_perspective.set([this._frustum_size,512/this._frustum_size]);a.u_camera_perspective[2]=this._projection_matrix[5];this.getEye(a.u_camera_eye);
this.getFront(a.u_camera_front);return a};d.registerComponent(w);d.Camera=w;ya.icon="mini-icon-fx.png";ya["@camera_uid"]={type:"String"};Object.defineProperty(ya.prototype,"use_antialiasing",{set:function(a){this.fx.apply_fxaa=a},get:function(){return this.fx.apply_fxaa},enumerable:!0});ya.prototype.configure=function(a){this.enabled=!!a.enabled;this.use_antialiasing=!!a.use_antialiasing;this.camera_uid=a.camera_uid;a.frame&&this.frame.configure(a.frame);a.fx&&this.fx.configure(a.fx)};ya.prototype.serialize=
function(){return{object_class:"CameraFX",enabled:this.enabled,use_antialiasing:this.use_antialiasing,frame:this.frame.serialize(),camera_uid:this.camera_uid,fx:this.fx.serialize()}};ya.prototype.getResources=function(a){this.fx.getResources(a);this.shader_material&&(a[this.shader_material]=!0);return a};ya.prototype.onResourceRenamed=function(a,b,c){if(this.shader_material==a)this.shader_material=b;else this.fx.onResourceRenamed(a,b,c)};ya.prototype.addFX=function(a){this.fx.addFX(a)};ya.prototype.getFX=
function(a){return this.fx.getFX(a)};ya.prototype.moveFX=function(a,b){return this.fx.moveFX(a,b)};ya.prototype.removeFX=function(a){return this.fx.removeFX(a)};ya.prototype.onAddedToScene=function(a){LEvent.bind(a,"enableFrameContext",this.onBeforeRender,this);LEvent.bind(a,"showFrameContext",this.onAfterRender,this)};ya.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"enableFrameContext",this.onBeforeRender,this);LEvent.unbind(a,"showFrameContext",this.onAfterRender,this);this._binded_camera&&
(LEvent.unbindAll(this._binded_camera,this),this._binded_camera=null)};ya.prototype.onBeforeRender=function(a,b){if(this.enabled){var c=this._root.camera;this.camera_uid&&(c=this._binded_camera&&this._binded_camera.uid==this.camera_uid?this._root.scene.findComponentByUId(this.camera_uid):this._binded_camera);c?(c&&c!=this._binded_camera&&(this._binded_camera&&LEvent.unbindAll(this._binded_camera,this),LEvent.bind(c,"enableFrameContext",this.enableCameraFBO,this),LEvent.bind(c,"showFrameContext",this.showCameraFBO,
this)),this._binded_camera=c):this._binded_camera&&(LEvent.unbindAll(this._binded_camera,this),this._binded_camera=null)}else this._binded_camera&&(LEvent.unbindAll(this._binded_camera,this),this._binded_camera=null)};ya.prototype.onAfterRender=function(a,b){};ya.prototype.enableCameraFBO=function(a,b){if(this.enabled){var c=this._viewport=this._binded_camera.getLocalViewport(null,this._viewport);this.frame.enable(b,c);b.ignore_viewports=!0}};ya.prototype.showCameraFBO=function(a,b){this.enabled&&
(b.ignore_viewports=!1,this.showFBO())};ya.prototype.showFBO=function(){if(this.enabled)if(this.frame.disable(),LEvent.trigger(d.Renderer,"beforeShowFrameContext",this.frame),this.shader_material){var a=d.ResourcesManager.getResource(this.shader_material),b=!1;a&&a.constructor===d.ShaderMaterial&&(b=a.applyToTexture(this.frame._color_texture));b||this.frame._color_texture.toViewport()}else this._viewport?(gl.setViewport(this._viewport),this.applyFX(),gl.setViewport(this.frame._fbo._old_viewport)):
this.applyFX()};ya.prototype.applyFX=function(){var a=this.frame._color_texture,b=this.frame._depth_texture;this.fx.apply_fxaa=this.use_antialiasing;this.fx.filter=this.frame.filter_texture;this.fx.applyFX(a,null,{depth_texture:b})};d.registerComponent(ya);Ja.icon="mini-icon-fx.png";Ja.prototype.configure=function(a){this.enabled=!!a.enabled;this.use_viewport_size=!!a.use_viewport_size;this.use_antialiasing=!!a.use_antialiasing;this.shader_material=a.shader_material;a.fx&&this.fx.configure(a.fx);
a.frame&&this.frame.configure(a.frame)};Ja.prototype.serialize=function(){return{object_class:"FrameFX",enabled:this.enabled,uid:this.uid,frame:this.frame.serialize(),shader_material:this.shader_material,use_antialiasing:this.use_antialiasing,use_viewport_size:this.use_viewport_size,fx:this.fx.serialize()}};Ja.prototype.getResources=function(a){this.fx.getResources(a);this.shader_material&&(a[this.shader_material]=!0);return a};Ja.prototype.onResourceRenamed=function(a,b,c){if(this.shader_material==
a)this.shader_material=b;else this.fx.onResourceRenamed(a,b,c)};Ja.prototype.addFX=function(a){this.fx.addFX(a)};Ja.prototype.getFX=function(a){return this.fx.getFX(a)};Ja.prototype.moveFX=function(a,b){return this.fx.moveFX(a,b)};Ja.prototype.removeFX=function(a){return this.fx.removeFX(a)};Ja.prototype.onAddedToScene=function(a){LEvent.bind(a,"enableFrameContext",this.onBeforeRender,this);LEvent.bind(a,"showFrameContext",this.onAfterRender,this)};Ja.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,
"enableFrameContext",this.onBeforeRender,this);LEvent.unbind(a,"showFrameContext",this.onAfterRender,this)};Ja.prototype.onBeforeRender=function(a,b){this.enabled&&this.enableFrameFBO(b)};Ja.prototype.onAfterRender=function(a,b){this.enabled&&this.showFBO()};Ja.prototype.enableFrameFBO=function(a){this.enabled&&this.frame.enable(a)};Ja.prototype.showFBO=function(){if(this.enabled)if(this.frame.disable(),LEvent.trigger(d.Renderer,"beforeShowFrameContext",this.frame),this.shader_material){var a=d.ResourcesManager.getResource(this.shader_material),
b=!1;a&&a.constructor===d.ShaderMaterial&&(b=a.applyToTexture(this.frame._color_texture));b||this.frame._color_texture.toViewport()}else this._viewport?(gl.setViewport(this._viewport),this.applyFX(),gl.setViewport(this.frame._fbo._old_viewport)):this.applyFX()};Ja.prototype.applyFX=function(){var a=this.frame._color_texture,b=this.frame._depth_texture;this.fx.apply_fxaa=this.use_antialiasing;this.fx.filter=this.frame.filter_texture;this.fx.applyFX(a,null,{depth_texture:b})};d.registerComponent(Ja);
x.NO_ATTENUATION=0;x.LINEAR_ATTENUATION=1;x.RANGE_ATTENUATION=2;x.AttenuationTypes={none:x.NO_ATTENUATION,linear:x.LINEAR_ATTENUATION,range:x.RANGE_ATTENUATION};x["@projective_texture"]={type:d.TYPES.TEXTURE};x["@extra_texture"]={type:d.TYPES.TEXTURE};x["@color"]={type:d.TYPES.COLOR};x["@attenuation_type"]={type:"enum",values:x.AttenuationTypes};Object.defineProperty(x.prototype,"type",{get:function(){return this._type},set:function(a){this._type=this._uniforms.u_light_info[0]=a},enumerable:!0});
Object.defineProperty(x.prototype,"position",{get:function(){return this._position},set:function(a){this._position.set(a)},enumerable:!0});Object.defineProperty(x.prototype,"target",{get:function(){return this._target},set:function(a){this._target.set(a)},enumerable:!0});Object.defineProperty(x.prototype,"extra",{get:function(){return this._uniforms.u_light_extra},set:function(a){a&&this._uniforms.u_light_extra.set(a)},enumerable:!0});Object.defineProperty(x.prototype,"up",{get:function(){return this._up},
set:function(a){this._up.set(a)},enumerable:!0});Object.defineProperty(x.prototype,"color",{get:function(){return this._color},set:function(a){this._color.set(a)},enumerable:!0});Object.defineProperty(x.prototype,"spot_cone",{get:function(){return this._spot_cone},set:function(a){this._spot_cone=a;this._uniforms.u_light_info[1]=a?1:0},enumerable:!0});x.OMNI=1;x.SPOT=2;x.DIRECTIONAL=3;x.DEFAULT_DIRECTIONAL_FRUSTUM_SIZE=50;x.prototype.onAddedToNode=function(a){a.light||(a.light=this)};x.prototype.onRemovedFromNode=
function(a){a.light==this&&delete a.light};x.prototype.onAddedToScene=function(a){LEvent.bind(a,"collectLights",this.onCollectLights,this);LEvent.bind(a,"renderShadows",this.onGenerateShadowmap,this)};x.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"collectLights",this.onCollectLights,this);LEvent.unbind(a,"renderShadows",this.onGenerateShadowmap,this);d.ResourcesManager.unregisterResource(":shadowmap_"+this.uid)};x.prototype.onGenerateShadowmap=function(a){this._update_shadowmap_render_settings&&
(this.generateShadowmap(this._update_shadowmap_render_settings),this._update_shadowmap_render_settings=null)};x.prototype.onCollectLights=function(a,b){this.enabled&&b.push(this)};x.prototype.getLightCamera=function(a){this.updateLightCamera(a);return this._light_camera};x._temp_matrix=mat4.create();x._temp2_matrix=mat4.create();x._temp3_matrix=mat4.create();x._temp_position=vec3.create();x._temp_target=vec3.create();x._temp_up=vec3.create();x._temp_front=vec3.create();x.prototype.updateLightCamera=
function(a){this._light_camera||(this._light_camera=new d.Components.Camera);var b=this._light_camera;b.type=this.type==x.DIRECTIONAL?d.Components.Camera.ORTHOGRAPHIC:d.Components.Camera.PERSPECTIVE;b.eye=this.getPosition(x._temp_position);if(this.type==x.OMNI&&null!=a){a=d.Camera.cubemap_camera_parameters[a];var c=x._temp_target;vec3.add(c,x._temp_position,a.dir);b.center=c;b.fov=45;b.up=a.up}else b.center=this.getTarget(x._temp_target),a=this.getUp(x._temp_up),c=this.getFront(x._temp_front),0.999<
Math.abs(vec3.dot(c,a))&&vec3.set(a,0,0,1),b.up=a,b.fov=this.angle_end||45;a=this.computeFar();b.frustum_size=this.frustum_size||x.DEFAULT_DIRECTIONAL_FRUSTUM_SIZE;b.near=this.near;b.far=a;b.layers=this.illuminated_layers;b.updateMatrices();this._light_matrix.set(b._viewprojection_matrix);return b};x.prototype.computeFar=function(){var a=this.far;this.type==x.OMNI?this.attenuation_type==this.RANGE_ATTENUATION&&this.att_end*Math.SQRT2<a&&(a=this.att_end/Math.SQRT2):this.attenuation_type==this.RANGE_ATTENUATION&&
this.att_end<a&&(a=this.att_end);return a};x.prototype.updateVectors=function(){var a=vec3.create();return function(){if(this._root&&this._root.transform){var b=this._root.transform.getGlobalMatrixRef();mat4.getTranslation(this._position,b);this.use_target||mat4.multiplyVec3(this._target,b,d.FRONT);mat4.multiplyVec3(this._up,b,d.TOP);mat4.rotateVec3(this._front,b,d.FRONT);mat4.rotateVec3(this._right,b,d.RIGHT);vec3.copy(this._top,this.up)}else vec3.subtract(this._front,this._target,this._position),
vec3.normalize(this._front,this._front),vec3.normalize(a,this._up),vec3.cross(this._right,this._front,a),vec3.cross(this._top,this._right,this._front)}}();x.prototype.getPosition=function(a){a=a||vec3.create();if(this._root&&this._root.transform)return this._root.transform.getGlobalPosition(a);a.set(this._position);return a};x.prototype.getTarget=function(a){a=a||vec3.create();if(this._root&&this._root.transform&&!this.use_target)return this._root.transform.localToGlobal(d.FRONT,a);a.set(this._target);
return a};x.prototype.getUp=function(a){a=a||vec3.create();if(this._root&&this._root.transform)return this._root.transform.transformVector(d.TOP,a);a.set(this._up);return a};x.prototype.getFront=function(a){a=a||vec3.create();this.getPosition(a);vec3.subtract(a,a,this.getTarget(x._temp_position));vec3.normalize(a,a);return a};x.prototype.getResources=function(a){this.projective_texture&&(a[this.projective_texture]=GL.Texture);this.extra_texture&&(a[this.extra_texture]=GL.Texture);return a};x.prototype.onResourceRenamed=
function(a,b,c){this.projective_texture==a&&(this.projective_texture=b);this.extra_texture==a&&(this.extra_texture=b)};x.prototype.checkLayersVisibility=function(a){return 0!==(this.illuminated_layers&a)};x.prototype.isInLayer=function(a){return 0!==(this.illuminated_layers&1<<a)};x.prototype.prepare=function(a){var b=this._uniforms,c=this._samplers;this._update_shadowmap_render_settings=null;(this.projective_texture||this.cast_shadows||this.force_light_matrix)&&this.updateLightCamera();a.shadows_enabled&&
this.cast_shadows||!this._shadowmap||(this._shadowmap=null,delete d.ResourcesManager.textures[":shadowmap_"+this.uid]);this.updateVectors();this.type==x.SPOT&&(b.u_light_angle[0]=this.angle*DEG2RAD,b.u_light_angle[1]=this.angle_end*DEG2RAD,b.u_light_angle[2]=Math.cos(this.angle*DEG2RAD*0.5),b.u_light_angle[3]=Math.cos(this.angle_end*DEG2RAD*0.5));vec3.scale(b.u_light_color,this.color,this.intensity);this._attenuation_info[0]=this.att_start;this._attenuation_info[1]=this.att_end;this._attenuation_info[2]=
this.attenuation_type;b.u_light_offset=this.offset;this._samplers.length=0;if(this.projective_texture){var e=this.projective_texture.constructor===String?d.ResourcesManager.textures[this.projective_texture]:this.projective_texture;e&&(e.texture_type==gl.TEXTURE_CUBE_MAP?b.light_cubemap=d.Renderer.LIGHTPROJECTOR_TEXTURE_SLOT:b.light_texture=d.Renderer.LIGHTPROJECTOR_TEXTURE_SLOT);c[d.Renderer.LIGHTPROJECTOR_TEXTURE_SLOT]=e}else delete b.light_texture,delete b.light_cubemap;if(this.extra_texture){if(e=
this.extra_texture.constructor===String?d.ResourcesManager.textures[this.extra_texture]:this.extra_texture)e.texture_type==gl.TEXTURE_CUBE_MAP?b.extra_light_cubemap=d.Renderer.LIGHTEXTRA_TEXTURE_SLOT:b.extra_light_texture=d.Renderer.LIGHTEXTRA_TEXTURE_SLOT;c[d.Renderer.LIGHTEXTRA_TEXTURE_SLOT]=e}else delete b.extra_light_texture,delete b.extra_light_cubemap;(a.update_shadowmaps||!this._shadowmap&&!d.ResourcesManager.isLoading())&&a.shadows_enabled&&!a.lights_disabled&&!a.low_quality&&(c=!1,c=this.isInsideVisibleFrustum())&&
(this._update_shadowmap_render_settings=a);this._shadowmap&&!this.cast_shadows&&(this._shadowmap=null);this.cast_shadows&&this._shadowmap&&null!=this._light_matrix&&!a.shadows_disabled&&this._shadowmap.prepare(b,this._samplers)};x.prototype.computeLightIntensity=function(){var a=Math.max(this.color[0],this.color[1],this.color[2]);return Math.max(0,a*this.intensity)};x.prototype.computeLightRadius=function(){return this.attenuation_type==x.NO_ATTENUATION||this.attenuation_type==x.LINEAR_ATTENUATION?
-1:this.type==x.OMNI?this.att_end*Math.SQRT2:this.att_end};x.prototype.generateShadowmap=function(a,b){this.cast_shadows&&(this._shadowmap||(this._shadowmap=new sa(this)),this._shadowmap.bias=this.shadow_bias,this._shadowmap.resolution=this.shadowmap_resolution,this._shadowmap.layers=this.shadows_layers,this._shadowmap.generate(null,a,b))};x.prototype.getGlobalMatrix=function(a){if(this._root&&this._root.transform)return this._root.transform.getGlobalMatrix(a);a=a||mat4.create();mat4.lookAt(a,this._position,
this._target,d.TOP);return a};x.prototype.getTransformMatrix=function(a,b){if(this._root&&this._root.transform)return this._root.transform.getGlobalMatrix(b);var c=null;if("matrix"==a)return this.getGlobalMatrix(b);var c="target"==a?this.target:this.position,e=b||mat4.create();mat4.setTranslation(e,c);return e};x.prototype.applyTransformMatrix=function(a,b,c){if(this._root&&this._root.transform)return!1;b=null;b="target"==c?this.target:this.position;mat4.multiplyVec3(b,a,b);return!0};x.prototype.applyShaderBlockFlags=
function(a,b,c){if(!this.enabled)return a;a|=x.shader_block.flag_mask;this.attenuation_type&&(a|=x.attenuation_block.flag_mask);this.projective_texture&&(a|=x.light_texture_block.flag_mask);this.cast_shadows&&c.shadows_enabled&&this._shadowmap&&(a|=this._shadowmap.getReadShaderBlock());return a};x.prototype.isInsideVisibleFrustum=function(){if(this.type!=x.OMNI)return!0;var a=d.Renderer._visible_cameras;if(!a)return!0;for(var b=this.computeFar(),c=this.position,e=0;e<a.length;e++)if(geo.frustumTestSphere(a[e]._frustum_planes,
c,b)!=CLIP_OUTSIDE)return!0;return!1};d.registerComponent(x);d.Light=x;Object.defineProperty(V.prototype,"enabled",{get:function(){return this._enabled},set:function(a){this._enabled=!!a;this.checkRenderInstances()},enumerable:!0});Object.defineProperty(V.prototype,"primitive",{get:function(){return this._primitive},set:function(a){a=void 0===a||null===a?-1:a|0;-1>a||10<a||(this._primitive=a,this.updateRIs())},enumerable:!0});Object.defineProperty(V.prototype,"material",{get:function(){return this._material},
set:function(a){this._material=a;this.updateRIs()},enumerable:!0});Object.defineProperty(V.prototype,"mesh",{get:function(){return this._mesh},set:function(a){this._mesh=a;this.updateRIs()},enumerable:!0});Object.defineProperty(V.prototype,"lod_mesh",{get:function(){return this._lod_mesh},set:function(a){this._lod_mesh=a;this.updateRIs()},enumerable:!0});Object.defineProperty(V.prototype,"submesh_id",{get:function(){return this._submesh_id},set:function(a){this._submesh_id=a},enumerable:!0});Object.defineProperty(V.prototype,
"render_instance",{get:function(){return this._RI},set:function(a){throw"cannot set a render_instance, must use the collectRenderInstances process.";},enumerable:!1});V.icon="mini-icon-teapot.png";V["@mesh"]={type:"mesh"};V["@lod_mesh"]={type:"mesh"};V["@material"]={type:"material"};V["@primitive"]={type:"enum",values:{Default:-1,Points:0,Lines:1,LineLoop:2,LineStrip:3,Triangles:4,TriangleStrip:5,TriangleFan:6,Wireframe:10}};V["@submesh_id"]={type:"enum",values:function(){var a=this.instance.getMesh();
if(!(a&&a&&a.info&&a.info.groups))return null;for(var b={all:null},c=0;c<a.info.groups.length;++c)b[a.info.groups[c].name]=c;return b}};V["@use_submaterials"]={type:d.TYPES.BOOLEAN,widget:null};V["@submaterials"]={widget:null};V.prototype.onAddedToScene=function(a){this.checkRenderInstances()};V.prototype.onRemovedFromScene=function(a){this.checkRenderInstances()};V.prototype.onAddedToNode=function(a){LEvent.bind(a,"materialChanged",this.updateRIs,this);LEvent.bind(a,"collectRenderInstances",this.onCollectInstances,
this);this._RI.node=a};V.prototype.onRemovedFromNode=function(a){LEvent.unbind(a,"materialChanged",this.updateRIs,this);LEvent.unbind(a,"collectRenderInstances",this.onCollectInstances,this)};V.prototype.configure=function(a){a.uid&&(this.uid=a.uid);void 0!==a.enabled&&(this.enabled=a.enabled);this.mesh=a.mesh;this.lod_mesh=a.lod_mesh;void 0!==a.submesh_id&&(this.submesh_id=a.submesh_id);this.primitive=a.primitive;this.material=a.material;this.use_submaterials=!!a.use_submaterials;a.submaterials&&
(this.submaterials=a.submaterials);a.material&&a.material.constructor===String&&(this.material=a.material)};V.prototype.serialize=function(){var a={object_class:"MeshRenderer",enabled:this.enabled,uid:this.uid,mesh:this.mesh,lod_mesh:this.lod_mesh};this.material&&this.material.constructor===String&&(a.material=this.material);-1!=this.primitive&&(a.primitive=this.primitive);-1!=this.submesh_id&&(a.submesh_id=this.submesh_id);a.material=this.material;this.use_submaterials&&(a.use_submaterials=this.use_submaterials);
a.submaterials=this.submaterials;return a};V.prototype.getMesh=function(){return this.mesh?this.mesh.constructor===String?d.ResourcesManager.meshes[this.mesh]:this.mesh:null};V.prototype.getLODMesh=function(){return this.lod_mesh?this.lod_mesh.constructor===String?d.ResourcesManager.meshes[this.lod_mesh]:null:null};V.prototype.getAnyMesh=function(){return this.getMesh()||this.getLODMesh()};V.prototype.getResources=function(a){this.mesh&&this.mesh.constructor===String&&(a[this.mesh]=GL.Mesh);this.lod_mesh&&
this.lod_mesh.constructor===String&&(a[this.lod_mesh]=GL.Mesh);this.material&&this.material.constructor===String&&(a[this.material]=d.Material);if(this.use_submaterials)for(var b=0;b<this.submaterials.length;++b)this.submaterials[b]&&(a[this.submaterials[b]]=d.Material);return a};V.prototype.onResourceRenamed=function(a,b,c){this.mesh==a&&(this.mesh=b);this.lod_mesh==a&&(this.lod_mesh=b);this.material==a&&(this.material=b);if(this.morph_targets)for(var e in this.morph_targets)this.morph_targets[e].mesh==
a&&(this.morph_targets[e].mesh=b)};V.prototype.checkRenderInstances=function(){};V.prototype.updateRIs=function(){};V.prototype.onCollectInstances=function(a,b){if(this._enabled)if(this.use_submaterials)this.onCollectInstancesSubmaterials(b);else{var c=this.getAnyMesh();if(!c)return null;if(this._root){var e=this._RI,g=this._root.flags&&this._root.flags.is_static,f=this._root.transform;e.layers=this._root.layers;e.fromNode(this._root);var h=null,h=this.material?d.ResourcesManager.getResource(this.material):
this._root.getMaterial();e.setMaterial(h);e.setMesh(c,this.primitive);if(-1!=this.submesh_id&&null!=this.submesh_id&&c.info&&c.info.groups){if(h=c.info.groups[this.submesh_id])e.setRange(h.start,h.length),h.bounding&&e.setBoundingBox(h.bounding)}else e.setRange(0,-1);e.collision_mesh=c;g&&d.allow_static&&!this.isLoading()&&(this._must_update_static=!1,this._transform_version=f?f._version:0);b.push(e)}}};V.prototype.onCollectInstancesSubmaterials=function(a){this._RIs||(this._RIs=[]);var b=this.getMesh();
if(b){var c=b.info.groups;if(c){var e=this._root.transform._global_matrix,g=vec3.create();mat4.multiplyVec3(g,e,d.ZEROS);for(var e=null,f=0;f<this.submaterials.length;++f){var h=this.submaterials[f];if(h){var k=c[f];if(k&&(h=d.ResourcesManager.getResource(h))){var l=this._RIs[f];l||(l=this._RIs[f]=new d.RenderInstance(this._root,this));e?l.setMatrix(e.matrix,e.normal_matrix):l.setMatrix(this._root.transform._global_matrix);l.center.set(g);l.setMaterial(h);l.setMesh(b,this.primitive);l.setRange(k.start,
k.length);a.push(l);e||(e=l)}}}}}};V.prototype.isLoading=function(){return this.mesh&&d.ResourcesManager.isLoading(this.mesh)||this.lod_mesh&&d.ResourcesManager.isLoading(this.lod_mesh)||this.material&&d.ResourcesManager.isLoading(this.material)||this._root&&this._root.material&&this._root.material.constructor===String&&d.ResourcesManager.isLoading(this._root.material)?!0:!1};V.prototype.explodeSubmeshesToChildNodes=function(){var a=this._root;if(a){var b=this.getMesh();if(b&&b.info&&b.info.groups){a.removeComponent(this);
for(var c=0;c<b.info.groups.length;++c){var e=b.info.groups[c],g=new d.SceneNode;a.addChild(g);e=new d.Components.MeshRenderer({mesh:this.mesh,submesh_id:c,material:e.material});g.addComponent(e)}d.GlobalScene.refresh()}}};d.registerComponent(V);d.MeshRenderer=V;z.AUTOMATIC=0;z.CPU=1;z.STREAMS=2;z.TEXTURES=3;z.icon="mini-icon-teapot.png";z.force_GPU=!0;z["@mode"]={type:"enum",values:{automatic:z.AUTOMATIC,CPU:z.CPU,streams:z.STREAMS,textures:z.TEXTURES}};z.prototype.onAddedToNode=function(a){LEvent.bind(a,
"collectRenderInstances",this.onCollectInstances,this)};Object.defineProperty(z.prototype,"name_weights",{set:function(a){if(a)for(var b=0;b<this.morph_targets.length;++b){var c=this.morph_targets[b];void 0!==a[c.mesh]&&(c.weight=Number(a[c.mesh]))}},get:function(){for(var a={},b=0;b<this.morph_targets.length;++b){var c=this.morph_targets[b];a[c.mesh]=c.weight}return a},enumeration:!1});Object.defineProperty(z.prototype,"weights",{set:function(a){if(a&&a.length)for(var b=0;b<a.length;++b)this.morph_targets[b]&&
(this.morph_targets[b].weight=a[b]||0)},get:function(){for(var a=Array(this.morph_targets.length),b=0;b<this.morph_targets.length;++b)a[b]=this.morph_targets[b].weight;return a},enumeration:!1});z.prototype.onRemovedFromNode=function(a){LEvent.unbind(a,"collectRenderInstances",this.onCollectInstances,this);this._last_RI&&this.disableMorphingGPU(this._last_RI);this._last_RI=null};z.prototype.getResources=function(a){for(var b=0;b<this.morph_targets.length;++b)this.morph_targets[b].mesh&&(a[this.morph_targets[b].mesh]=
GL.Mesh)};z.prototype.onResourceRenamed=function(a,b,c){for(c=0;c<this.morph_targets.length;++c)this.morph_targets[c].mesh==a&&(this.morph_targets[c].mesh=b)};z.prototype.clearWeights=function(){for(var a=0;a<this.morph_targets.length;++a)this.morph_targets[a].weight=0};z.prototype.addMorph=function(a,b){b=b||0;var c=this.getMorphIndex(a);-1==c?this.morph_targets.push({mesh:a,weight:b}):this.morph_targets[c]={mesh:a,weight:b}};z.prototype.onCollectInstances=function(a,b){if(b.length&&!(16>z.max_supported_vertex_attribs)){var c=
this.enabled?b[b.length-1]:null;c!=this._last_RI&&this._last_RI&&this.disableMorphingGPU(this._last_RI);if((this._last_RI=c)&&c.mesh)if(this._last_base_mesh=c.mesh,this._valid_morphs=this.computeValidMorphs(this._valid_morphs,c.mesh),this.mode===z.AUTOMATIC){if(void 0===this._morph_texture_supported&&(this._morph_texture_supported=void 0!==gl.extensions.OES_texture_float&&1<gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS)),0!=this._valid_morphs.length||z.force_GPU)this._valid_morphs.length<=z.max_supported_morph_targets_using_streams?
this.applyMorphTargetsByGPU(c,this._valid_morphs):this._morph_texture_supported?this.applyMorphUsingTextures(c,this._valid_morphs):this.applyMorphBySoftware(c,this._valid_morphs)}else switch(this.mode){case z.STREAMS:this.applyMorphTargetsByGPU(c,this._valid_morphs);break;case z.TEXTURES:this.applyMorphUsingTextures(c,this._valid_morphs);break;default:this.applyMorphBySoftware(c,this._valid_morphs)}}};z.prototype.computeValidMorphs=function(a,b){a=a||[];a.length=0;if(!b)return a;var c=this.morph_targets.concat();
c.sort(function(a,b){return Math.abs(b.weight)-Math.abs(a.weight)});for(var e=0;e<c.length;++e){var g=c[e];if(g.mesh&&!(0.001>Math.abs(g.weight))){var f=d.ResourcesManager.resources[g.mesh];f&&f.constructor===GL.Mesh&&(f.info||(f.info={}),f.info.morph_target_from=b.filename,a.push({name:g.mesh,weight:g.weight,mesh:f}))}}return a};z.prototype.applyMorphTargetsByGPU=function(a,b){for(var c=a.mesh,e=c.vertexBuffers.vertices,g={},f=[],h=0;h<b.length&&4>h;++h){var k=b[h],l=k.mesh,n=l.vertexBuffers.vertices;
n&&n.data.length==e.data.length&&(l=l.vertexBuffers.normals)&&(n=n.clone(!0),l=l.clone(!0),n.attribute=null,l.attribute=null,g["a_vertex_morph"+h]=n,g["a_normal_morph"+h]=l,f.push(k.weight))}a.vertex_buffers={};for(h in c.vertexBuffers)a.vertex_buffers[h]=c.vertexBuffers[h];for(h in g)a.vertex_buffers[h]=g[h];a.samplers[d.Renderer.MORPHS_TEXTURE_SLOT]&&(delete a.uniforms.u_morph_vertices_texture,delete a.uniforms.u_morph_normals_texture,a.samplers[d.Renderer.MORPHS_TEXTURE_SLOT]=null,a.samplers[d.Renderer.MORPHS_TEXTURE2_SLOT]=
null);c=this._stream_weights;if(c.fill)c.fill(0);else for(h=0;h<c.length;++h)c[h]=0;c.set(f);a.uniforms.u_morph_weights=c;a.uniforms.u_morph_info=this.delta_meshes?1:0;a.addShaderBlock(z.shader_block);a.addShaderBlock(d.MorphDeformer.morphing_streams_block,this._uniforms);a.removeShaderBlock(d.MorphDeformer.morphing_texture_block)};z.prototype.applyMorphUsingTextures=function(a,b){var c=a.mesh,e=c.vertexBuffers.vertices,g=c.vertexBuffers.normals;e._texture||(e._texture=this.createGeometryTexture(e));
g._texture||(g._texture=this.createGeometryTexture(g));var f=[];this._morphtarget_vertices_texture&&this._morphtarget_vertices_texture.height==e._texture.height||(this._morphtarget_vertices_texture=new GL.Texture(e._texture.width,e._texture.height,{format:gl.RGB,type:gl.FLOAT,filter:gl.NEAREST,wrap:gl.CLAMP_TO_EDGE,no_flip:!0}),this._morphtarget_normals_texture=new GL.Texture(g._texture.width,g._texture.height,{format:gl.RGB,type:gl.FLOAT,filter:gl.NEAREST,wrap:gl.CLAMP_TO_EDGE,no_flip:!0}),this._texture_size=
vec4.fromValues(this._morphtarget_vertices_texture.width,this._morphtarget_vertices_texture.height,1/this._morphtarget_vertices_texture.width,1/this._morphtarget_vertices_texture.height));for(c=0;c<b.length;++c){var h=b[c],k=h.mesh,l=k.vertexBuffers.vertices;l&&l.data.length==e.data.length&&(k=k.vertexBuffers.normals)&&(l._texture||(l._texture=this.createGeometryTexture(l)),k._texture||(k._texture=this.createGeometryTexture(k)),f.push({weight:h.weight,vertices:l._texture,normals:k._texture}))}var n=
this.getMorphTextureShader();n.uniforms({u_base_texture:0,u_morph_texture:1});gl.disable(gl.DEPTH_TEST);gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE);e._texture.bind(0);var p=GL.Mesh.getScreenQuad();this._morphtarget_vertices_texture.drawTo(function(){gl.clearColor(0,0,0,0);gl.clear(gl.COLOR_BUFFER_BIT);for(var a=0;a<f.length;++a)f[a].vertices.bind(1),n.uniforms({u_weight:f[a].weight}),n.draw(p,gl.TRIANGLES)});g._texture.bind(0);this._morphtarget_normals_texture.drawTo(function(){gl.clearColor(0,
0,0,0);gl.clear(gl.COLOR_BUFFER_BIT);for(var a=0;a<f.length;++a)f[a].normals.bind(1),n.uniforms({u_weight:f[a].weight}),n.draw(p,gl.TRIANGLES)});gl.disable(gl.BLEND);e=e.data.length/3;if(!this._ids_buffer||this._ids_buffer.data.length!=e){g=new Float32Array(e);for(c=0;c<e;++c)g[c]=c;this._ids_buffer=new GL.Buffer(gl.ARRAY_BUFFER,g,1,gl.STATIC_DRAW);this._ids_buffer.attribute="a_morphing_ids"}a.uniforms.u_morph_vertices_texture=d.Renderer.MORPHS_TEXTURE_SLOT;a.samplers[d.Renderer.MORPHS_TEXTURE_SLOT]=
this._morphtarget_vertices_texture;a.uniforms.u_morph_normals_texture=d.Renderer.MORPHS_TEXTURE2_SLOT;a.samplers[d.Renderer.MORPHS_TEXTURE2_SLOT]=this._morphtarget_normals_texture;a.uniforms.u_morph_texture_size=this._texture_size;a.vertex_buffers.a_morphing_ids=this._ids_buffer;a.addShaderBlock(z.shader_block);a.addShaderBlock(d.MorphDeformer.morphing_texture_block,{u_morph_vertices_texture:d.Renderer.MORPHS_TEXTURE_SLOT,u_morph_normals_texture:d.Renderer.MORPHS_TEXTURE2_SLOT,u_morph_texture_size:this._texture_size});
a.removeShaderBlock(d.MorphDeformer.morphing_streams_block)};z.prototype.disableMorphingGPU=function(a){a&&(a.samplers[d.Renderer.MORPHS_TEXTURE_SLOT]&&(a.samplers[d.Renderer.MORPHS_TEXTURE_SLOT]=null,a.samplers[d.Renderer.MORPHS_TEXTURE2_SLOT]=null,delete a.uniforms.u_morph_vertices_texture,delete a.uniforms.u_morph_normals_texture),a.removeShaderBlock(d.MorphDeformer.shader_block),a.removeShaderBlock(d.MorphDeformer.morphing_streams_block),a.removeShaderBlock(d.MorphDeformer.morphing_texture_block))};
z.prototype.applyMorphBySoftware=function(a,b){var c=a.mesh,e=c.vertexBuffers.vertices;this.disableMorphingGPU(a);for(var d="",e=0;e<b.length;++e)var f=b[e],d=d+(f.name+"|"+f.weight.toFixed(2)+"|");if(d==this._last_key)this._final_vertices_buffer&&(a.vertex_buffers.vertices=this._final_vertices_buffer),this._final_normals_buffer&&(a.vertex_buffers.normals=this._final_normals_buffer);else{this._last_key=d;e=c.vertexBuffers.vertices;d=e.data;c=c.vertexBuffers.normals.data;this._final_vertices&&this._final_vertices.length==
d.length||(this._final_vertices=new Float32Array(d.length),this._final_vertices_buffer=new GL.Buffer(gl.ARRAY_BUFFER,this._final_vertices,3,gl.STREAM_DRAW),this._final_vertices_buffer.attribute="a_vertex");this._final_normals&&this._final_normals.length==c.length||(this._final_normals=new Float32Array(c.length),this._final_normals_buffer=new GL.Buffer(gl.ARRAY_BUFFER,this._final_normals,3,gl.STREAM_DRAW),this._final_normals_buffer.attribute="a_normal");var h=this._final_vertices,k=this._final_normals;
h.set(d);k.set(c);for(var l=[],n=[],p=[],m=b.length,e=0;e<b.length;++e)f=b[e],l.push(f.mesh.vertexBuffers.vertices.data),n.push(f.mesh.vertexBuffers.normals.data),p.push(f.weight);if(this.delta_meshes)for(e=0,f=h.length;e<f;e+=3)for(var q=h.subarray(e,e+3),s=k.subarray(e,e+3),t=0;t<m;++t){var u=l[t],H=n[t],G=p[t];q[0]+=u[e]*G;q[1]+=u[e+1]*G;q[2]+=u[e+2]*G;s[0]+=H[e]*G;s[1]+=H[e+1]*G;s[2]+=H[e+2]*G}else for(e=0,f=h.length;e<f;e+=3)for(q=h.subarray(e,e+3),s=k.subarray(e,e+3),t=0;t<m;++t)u=l[t],H=n[t],
G=p[t],q[0]+=(u[e]-d[e])*G,q[1]+=(u[e+1]-d[e+1])*G,q[2]+=(u[e+2]-d[e+2])*G,s[0]+=(H[e]-c[e])*G,s[1]+=(H[e+1]-c[e+1])*G,s[2]+=(H[e+2]-c[e+2])*G;this._final_vertices_buffer.upload(gl.STREAM_DRAW);this._final_normals_buffer.upload(gl.STREAM_DRAW);a.vertex_buffers.vertices=this._final_vertices_buffer;a.vertex_buffers.normals=this._final_normals_buffer}};z._blend_shader_fragment_code="\n\tprecision highp float;\n\tuniform sampler2D u_base_texture;\n\tuniform sampler2D u_morph_texture;\n\tuniform float u_weight;\n\tvarying vec2 v_coord;\n\tvoid main() {\n\t\tgl_FragColor = u_weight * ( texture2D(u_morph_texture, v_coord) - texture2D(u_base_texture, v_coord) );\n\t\tgl_FragColor.w = 1.0;\n\t}\n";
z._delta_blend_shader_fragment_code="\n\tprecision highp float;\n\tuniform sampler2D u_morph_texture;\n\tuniform float u_weight;\n\tvarying vec2 v_coord;\n\tvoid main() {\n\t\tgl_FragColor = u_weight * texture2D(u_morph_texture, v_coord);\n\t\tgl_FragColor.w = 1.0;\n\t}\n";z.prototype.getMorphTextureShader=function(){if(this.delta_meshes)return this._delta_blend_shader||(this._delta_blend_shader=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,z._delta_blend_shader_fragment_code)),this._delta_blend_shader;
this._blend_shader||(this._blend_shader=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,z._blend_shader_fragment_code));return this._blend_shader};z.prototype.createGeometryTexture=function(a,b){var c=a.data,e=gl.getParameter(gl.MAX_TEXTURE_SIZE),d=c.length/3,e=Math.min(e,d),d=Math.ceil(d/e),f=new Float32Array(e*d*3);f.set(c);b&&b.width==e&&b.height==d?b.uploadData(f):b=new GL.Texture(e,d,{format:gl.RGB,type:gl.FLOAT,filter:gl.NEAREST,wrap:gl.CLAMP_TO_EDGE,pixel_data:f,no_flip:!0});return b};z.prototype.recomputeGeometryTextures=
function(){var a=this._last_RI;if(a){var b=a.mesh,a=b.vertexBuffers.vertices,b=b.vertexBuffers.normals;a._texture=this.createGeometryTexture(a,a._texture);b._texture=this.createGeometryTexture(b,b._texture);if(a=this._valid_morphs)for(b=0;b<a.length;++b){var c=a[b].mesh,e=c.vertexBuffers.vertices;e&&e._texture&&this.createGeometryTexture(e,e._texture);(c=c.vertexBuffers.normals)&&c._texture&&this.createGeometryTexture(c,c._texture)}}};z.prototype.getMorphIndex=function(a){for(var b=0;b<this.morph_targets.length;++b)if(this.morph_targets[b].mesh==
a)return b;return-1};z.prototype.setMorphMesh=function(a,b){a>=this.morph_targets.length||(this.morph_targets[a].mesh=b)};z.prototype.setMorphWeight=function(a,b){a>=this.morph_targets.length||(this.morph_targets[a].weight=b)};z.prototype.getPropertyInfoFromPath=function(a){if("morphs"==a[0]){if(1==a.length)return{node:this._root,target:this.morph_targets,type:"object"};var b=parseInt(a[1]);if(!(b>=this.morph_targets.length)&&(a=a[2],"mesh"==a||"weight"==a))return{node:this._root,target:this.morph_targets[b],
name:a,value:void 0!==this.morph_targets[b][a]?this.morph_targets[b][a]:null,type:"mesh"==a?"mesh":"number"}}};z.prototype.setPropertyValueFromPath=function(a,b,c){c=c||0;if(!(a.length<c+1)&&"morphs"==a[c]){var e=parseInt(a[c+1]);e>=this.morph_targets.length||(this.morph_targets[e][a[c+2]]=b)}};z.prototype.setProperty=function(a,b){if("enabled"==a)this.enabled=b;else if("morph"==a.substr(0,5)){a=a.substr(5);var c=a.split("_"),e=parseInt(c[0]);e<this.morph_targets.length&&("weight"==c[1]?this.morph_targets[e].weight=
b:"mesh"==c[1]&&(this.morph_targets[e].mesh=b))}else"weights"==a?this.weights=b:"name_weights"==a&&(this.name_weights=b)};z.prototype.getProperty=function(a){if("morph"==a.substr(0,5)&&5<a.length){a=a.substr(5).split("_");var b=this.morph_targets[Number(a[0])];if(b)return"mesh"==a[1]?b.mesh:"weight"==a[1]?b.weight:b}};z.prototype.getPropertiesInfo=function(){for(var a={enabled:"boolean",weights:"array",name_weights:"object"},b=0;b<this.morph_targets.length;b++)a["morph"+b+"_weight"]="number";return a};
z.prototype.getBaseMesh=function(){if(!this._root)return null;if(this._last_base_mesh)return this._last_base_mesh;var a=this._root.getComponent(d.Components.MeshRenderer);return a?d.ResourcesManager.resources[a.mesh]:null};z.prototype.optimizeMorphTargets=function(){for(var a=this.getBaseMesh(),b=this.morph_targets.concat(),c=0;c<b.length;++c){var e=b[c],g=d.ResourcesManager.meshes[e.mesh];if(g)if(g.removeVertexBuffer("coords",!0),g.removeIndexBuffer("triangles",!0),g.removeIndexBuffer("wireframe",
!0),a&&0.1>z.computeMeshDifference(a,g)){var f=g.fullpath||g.filename;console.log("morph target is too similar to base mesh, removing it: "+f);e=this.morph_targets.indexOf(e);this.morph_targets.splice(e,1);d.ResourcesManager.unregisterResource(f);(g=g.from_pack||g.from_prefab)&&(g=d.ResourcesManager.resources[g])&&g.removeResource(f)}else d.ResourcesManager.resourceModified(g)}console.log("Morph targets optimized")};z.computeMeshDifference=function(a,b){if(!(a&&b&&a.vertexBuffers.vertices&&b.vertexBuffers.vertices))return 0;
var c=a.vertexBuffers.vertices.data,e=b.vertexBuffers.vertices.data;if(!c||!e||c.length!=e.length)return 0;for(var d=0,f=0;f<c.length;f+=3)d+=vec3.distance(c.subarray(f,f+3),e.subarray(f,f+3));return d};z.prototype.onInspectNode=function(a,b){var c=this;a.addButton(null,"Add weights' inputs",{callback:function(){for(var a=0;a<c.morph_targets.length;++a)-1==b.findInputSlot("morph_"+a+"_weight")&&b.addInput("morph_"+a+"_weight","number");b.setDirtyCanvas(!0)}})};d.registerComponent(z);d.MorphDeformer=
z;z.morph_streams_enabled_shader_code="\n\t\n\t//max vertex attribs are 16 usually, so 10 are available after using 6 for V,N,UV,UV2,BW,BI\n\tattribute vec3 a_vertex_morph0;\n\tattribute vec3 a_normal_morph0;\n\tattribute vec3 a_vertex_morph1;\n\tattribute vec3 a_normal_morph1;\n\tattribute vec3 a_vertex_morph2;\n\tattribute vec3 a_normal_morph2;\n\tattribute vec3 a_vertex_morph3;\n\tattribute vec3 a_normal_morph3;\n\t\n\tuniform vec4 u_morph_weights;\n\tuniform float u_morph_info;\n\t\n\tvoid applyMorphing( inout vec4 position, inout vec3 normal )\n\t{\n\t\tvec3 original_vertex = vec3(0.0);\n\t\tvec3 original_normal = vec3(0.0);\n\t\tif( u_morph_info == 0.0 )\n\t\t{\n\t\t\toriginal_vertex = position.xyz;\n\t\t\toriginal_normal = normal.xyz;\n\t\t}\n\t\t\n\t\tif(u_morph_weights[0] != 0.0)\n\t\t{\n\t\t\tposition.xyz += (a_vertex_morph0 - original_vertex) * u_morph_weights[0]; normal.xyz += (a_normal_morph0 - original_normal) * u_morph_weights[0];\n\t\t}\n\t\tif(u_morph_weights[1] != 0.0)\n\t\t{\n\t\t\tposition.xyz += (a_vertex_morph1 - original_vertex) * u_morph_weights[1]; normal.xyz += (a_normal_morph1 - original_normal) * u_morph_weights[1];\n\t\t}\n\t\tif(u_morph_weights[2] != 0.0)\n\t\t{\n\t\t\tposition.xyz += (a_vertex_morph2 - original_vertex) * u_morph_weights[2]; normal.xyz += (a_normal_morph2 - original_normal) * u_morph_weights[2];\n\t\t}\n\t\tif(u_morph_weights[3] != 0.0)\n\t\t{\n\t\t\tposition.xyz += (a_vertex_morph3 - original_vertex) * u_morph_weights[3]; normal.xyz += (a_normal_morph3 - original_normal) * u_morph_weights[3];\n\t\t}\n\t}\n";
z.morph_texture_enabled_shader_code="\n\t\n\tattribute float a_morphing_ids;\n\t\n\tuniform sampler2D u_morph_vertices_texture;\n\tuniform sampler2D u_morph_normals_texture;\n\tuniform vec4 u_morph_texture_size;\n\t\n\tuniform vec4 u_morph_weights;\n\t\n\tvoid applyMorphing( inout vec4 position, inout vec3 normal )\n\t{\n\t\tvec2 coord;\n\t\tcoord.x = ( mod( a_morphing_ids, u_morph_texture_size.x ) + 0.5 ) / u_morph_texture_size.x;\n\t\tcoord.y = 1.0 - ( floor( a_morphing_ids / u_morph_texture_size.x ) + 0.5 ) / u_morph_texture_size.y;\n\t\tposition.xyz += texture2D( u_morph_vertices_texture, coord ).xyz;\n\t\tnormal.xyz += texture2D( u_morph_normals_texture, coord ).xyz;\n\t}\n";
z.morph_enabled_shader_code="\n\t\n\t#pragma shaderblock morphing_mode\n";z.morph_disabled_shader_code="\nvoid applyMorphing( inout vec4 position, inout vec3 normal ) {}\n";var ic=new d.ShaderBlock("morphing");ic.addCode(GL.VERTEX_SHADER,z.morph_enabled_shader_code,z.morph_disabled_shader_code);ic.register();z.shader_block=ic;var Vb=new d.ShaderBlock("morphing_streams");Vb.defineContextMacros({morphing_mode:"morphing_streams"});Vb.addCode(GL.VERTEX_SHADER,z.morph_streams_enabled_shader_code,z.morph_disabled_shader_code);
Vb.register();z.morphing_streams_block=Vb;var Wb=new d.ShaderBlock("morphing_texture");Wb.defineContextMacros({morphing_mode:"morphing_texture"});Wb.addCode(GL.VERTEX_SHADER,z.morph_texture_enabled_shader_code,z.morph_disabled_shader_code);Wb.register();z.morphing_texture_block=Wb;L.icon="mini-icon-stickman.png";L.MAX_BONES=64;L.MAX_TEXTURE_BONES=128;L.gpu_skinning_supported=!0;L.icon="mini-icon-stickman.png";L.apply_to_normals_by_software=!1;L["@skeleton_root_node"]={type:d.TYPES.SCENENODE};L.prototype.onAddedToNode=
function(a){LEvent.bind(a,"collectRenderInstances",this.onCollectInstances,this)};L.prototype.onRemovedFromNode=function(a){LEvent.unbind(a,"collectRenderInstances",this.onCollectInstances,this)};L.prototype.getBoneNode=function(a){var b=this._root,c=b.scene;if(!c)return null;if(this.skeleton_root_node){if(b=c.getNode(this.skeleton_root_node))return b.findNodeByName(a)}else return this.search_bones_in_parent?b.parentNode.findNode(a):c.getNode(a);return null};L.prototype.getBoneMatrix=function(a){if(this._skeleton)return this._skeleton.getBoneMatrix(a);
a=this.getBoneNode(a);if(!a)return null;a._is_bone=!0;return a.transform.getGlobalMatrixRef()};L.prototype.getBoneMatrices=function(a){var b=this._last_bones;if(!this._last_bones||this._last_bones.length!=a.bones.length)for(var b=this._last_bones=[],c=0;c<a.bones.length;++c)b[c]=mat4.create();if(this._skeleton)return c=this._root.transform?this._root.transform.getGlobalMatrixRef():null,this._skeleton.computeFinalBoneMatricesAsArray(b,a,c),b;for(c=0;c<a.bones.length;++c){var e=b[c],d=a.bones[c],f=
this.getBoneMatrix(d[0]);f?(mat4.multiply(e,f,d[1]),a.bind_matrix&&mat4.multiply(e,e,a.bind_matrix)):mat4.identity(e)}return b};L.prototype.onCollectInstances=function(a,b){if(b.length&&this.root){var c,e=this.root.getIndexOfComponent(this);if(e=this.root.getComponentByIndex(e-1))c=e._RI;c&&(this._ris_skinned.length=0,this.enabled?this.applySkinning(c):this.disableSkinning(c))}};L.prototype.applySkinning=function(a){var b=a.mesh;this._mesh=b;this._ris_skinned.push(a);if(b&&b.getBuffer("vertices")&&
b.getBuffer("bone_indices")){var c=null,e=this._u_bones;if(L.gpu_skinning_supported&&!this.cpu_skinning){c=this.getBoneMatrices(b);b=12*c.length;if(!b){console.warn("SkinDeformer.prototype.applySkinning: Bones not found");return}e&&e.length==b||(this._u_bones=e=new Float32Array(b));for(var g=0;g<c.length;g++)mat4.transpose(c[g],c[g]),e.set(c[g].subarray(0,12),12*g,12*(g+1));L.num_supported_uniforms>=b?(a.uniforms.u_bones=e,a.samplers[d.Renderer.BONES_TEXTURE_SLOT]=null,a.addShaderBlock(d.SkinDeformer.skinning_uniforms_block,
{u_bones:e})):0<L.num_supported_textures?(g=this._bones_texture,g||(g=this._bones_texture=new GL.Texture(1,3*L.MAX_TEXTURE_BONES,{format:gl.RGBA,type:gl.FLOAT,filter:gl.NEAREST}),g._data=new Float32Array(g.width*g.height*4)),g._data.set(e),g.uploadData(g._data,{no_flip:!0}),d.RM.textures[":bones_"+this.uid]=g,a.uniforms.u_bones=d.Renderer.BONES_TEXTURE_SLOT,a.samplers[d.Renderer.BONES_TEXTURE_SLOT]=g,a.addShaderBlock(d.SkinDeformer.skinning_texture_block,{u_bones:d.Renderer.BONES_TEXTURE_SLOT})):
console.error("impossible to get here");a.addShaderBlock(d.SkinDeformer.skinning_block)}else{if(!this._skinned_mesh||this._skinned_mesh._reference!=b){this._skinned_mesh=new GL.Mesh;this._skinned_mesh._reference=b;var f=b.getBuffer("vertices"),h=b.getBuffer("normals");for(g in b.vertexBuffers)this._skinned_mesh.vertexBuffers[g]=b.vertexBuffers[g];for(g in b.indexBuffers)this._skinned_mesh.indexBuffers[g]=b.indexBuffers[g];this._skinned_mesh.createVertexBuffer("vertices","a_vertex",3,new Float32Array(f.data),
gl.STREAM_DRAW);h&&this._skinned_mesh.createVertexBuffer("normals","a_normal",3,new Float32Array(h.data),gl.STREAM_DRAW)}this.applySoftwareSkinning(b,this._skinned_mesh);a.setMesh(this._skinned_mesh,this.primitive);this.disableSkinning(a)}this.ignore_transform?(mat4.identity(a.matrix),a.normal_matrix.set(a.matrix)):this._root.transform.getGlobalMatrix(a.matrix);if(c&&c.length){a.center.set(d.ZEROS);for(g=0;g<c.length;++g)a.center[0]+=c[g][3],a.center[1]+=c[g][7],a.center[2]+=c[g][11];a.center[0]/=
c.length;a.center[1]/=c.length;a.center[2]/=c.length}else e&&(a.center[0]=e[9],a.center[1]=e[10],a.center[2]=e[11]);mat4.getTranslation(a.position,a.matrix);a.use_bounding=!1}};L.prototype.disableSkinning=function(a){this._mesh=null;a.samplers.u_bones&&delete a.samplers.u_bones;a.removeShaderBlock(d.SkinDeformer.skinning_block);a.removeShaderBlock(d.SkinDeformer.skinning_uniforms_block);a.removeShaderBlock(d.SkinDeformer.skinning_texture_block)};L.prototype.getMesh=function(){return this._mesh};L.prototype.applySoftwareSkinning=
function(a,b){var c=a.getBuffer("vertices").data,e=null;a.getBuffer("normals")&&(e=a.getBuffer("normals").data);var d=a.getBuffer("weights").data,f=a.getBuffer("bone_indices").data,h=b.getBuffer("vertices"),k=h.data,l=null,n=null;L.zero_matrix||(L.zero_matrix=new Float32Array(16));var p=L.zero_matrix;e&&(l=b.getBuffer("normals"),n=l.data);var m=this.getBoneMatrices(a);if(0==m.length)return null;for(var q=vec3.create(),s=vec3.create(),t=mat4.create(),u=0,H=k.length/3;u<H;++u){c.subarray(3*u,3*u+3);
var G=f.subarray(4*u,4*u+4),Z=d.subarray(4*u,4*u+4),M=k.subarray(3*u,3*u+3),G=[m[G[0]],m[G[1]],m[G[2]],m[G[3]]];t.set(p);mat4.scaleAndAdd(t,t,G[0],Z[0]);0<Z[1]&&mat4.scaleAndAdd(t,t,G[1],Z[1]);0<Z[2]&&mat4.scaleAndAdd(t,t,G[2],Z[2]);0<Z[3]&&mat4.scaleAndAdd(t,t,G[3],Z[3]);mat4.multiplyVec3(M,t,c.subarray(3*u,3*u+3));if(n){var r=n.subarray(3*u,3*u+3);mat4.rotateVec3(r,t,e.subarray(3*u,3*u+3))}if(L.apply_to_normals_by_software)for(M[0]=M[1]=M[2]=0,mat4.multiplyVec3(M,G[0],s),vec3.scale(M,M,Z[0]),r=
1;4>r;++r)0<Z[r]&&(mat4.multiplyVec3(q,G[r],s),vec3.scaleAndAdd(M,M,q,Z[r]))}h.upload(gl.STREAM_DRAW);l&&l.upload(gl.STREAM_DRAW)};L.prototype.extractSkeleton=function(){};L.prototype.applyBindPose=function(){var a=this._mesh;if(a&&a.bones){mat4.create();for(var a=this.getBones(),b=0;b<a.length;++b){var c=a[b];c._level=c.getHierarchyLevel()}}};L.prototype.getBones=function(){var a=this._mesh;if(!a&&!a.bones)return null;var b=[],c;for(c in a.bones){var e=this.getBoneNode(a.bones[c][0]);e&&b.push(e)}return b};
d.registerComponent(L);d.SkinDeformer=L;L.skinning_shader_code="\n\t//Skinning ******************* \n\t#ifndef MAX_BONES\n\t\t#define MAX_BONES 64\n\t#endif\n\t#ifdef USE_SKINNING_TEXTURE\n\t\tuniform sampler2D u_bones;\n\t#else\n\t\tuniform vec4 u_bones[ MAX_BONES * 3];\n\t#endif\n\tattribute vec4 a_weights;\n\tattribute vec4 a_bone_indices;\n\t\n\tvoid getMat(int id, inout mat4 m) {\n\t\n\t\t#ifdef USE_SKINNING_TEXTURE\n\t\t\tfloat i_max_texture_bones_offset = 1.0 / (128.0 * 3.0);\n\t\t\tm[0] = texture2D( u_bones, vec2( 0.0, (float(id*3)+0.5) * i_max_texture_bones_offset ) ); \n\t\t\tm[1] = texture2D( u_bones, vec2( 0.0, (float(id*3+1)+0.5) * i_max_texture_bones_offset ) );\n\t\t\tm[2] = texture2D( u_bones, vec2( 0.0, (float(id*3+2)+0.5) * i_max_texture_bones_offset ) );\n\t\t#else\n\t\t\tm[0] = u_bones[ id * 3];\n\t\t\tm[1] = u_bones[ id * 3 + 1];\n\t\t\tm[2] = u_bones[ id * 3 + 2];\n\t\t#endif\n\t}\n\t\n\tmat3 mat3_emu(mat4 m4) {\n\t  return mat3(\n\t\t  m4[0][0], m4[0][1], m4[0][2],\n\t\t  m4[1][0], m4[1][1], m4[1][2],\n\t\t  m4[2][0], m4[2][1], m4[2][2]);\n\t}\n\t\n\tvoid applySkinning(inout vec4 position, inout vec3 normal)\n\t{\n\t\t//toji version seems faster\n\t\tmat4 bone_matrix = mat4(0.0,0.0,0.0,0.0, 0.0,0.0,0.0,0.0, 0.0,0.0,0.0,0.0, 0.0,0.0,0.0,1.0);\n\t\t\n\t\tgetMat( int(a_bone_indices.x), bone_matrix );\n\t\tmat4 result = a_weights.x * bone_matrix;\n\t\tgetMat( int(a_bone_indices.y), bone_matrix);\n\t\tresult = result + a_weights.y * bone_matrix;\n\t\tgetMat( int(a_bone_indices.z), bone_matrix);\n\t\tresult = result + a_weights.z * bone_matrix;\n\t\tgetMat( int(a_bone_indices.w), bone_matrix);\n\t\tresult = result + a_weights.w * bone_matrix;\n\t\t\n\t\tposition.xyz = (position * result).xyz;\n\t\tnormal = normal * mat3_emu(result);\n\t}\n";
L.skinning_enabled_shader_code="\n#pragma shaderblock skinning_mode\n#define USING_SKINNING\n";L.skinning_disabled_shader_code="\nvoid applySkinning( inout vec4 position, inout vec3 normal) {}\n";var jc=new d.ShaderBlock("skinning");jc.addCode(GL.VERTEX_SHADER,L.skinning_enabled_shader_code,L.skinning_disabled_shader_code);jc.register();L.skinning_block=jc;var Xb=new d.ShaderBlock("skinning_uniforms");Xb.defineContextMacros({skinning_mode:"skinning_uniforms"});Xb.addCode(GL.VERTEX_SHADER,L.skinning_shader_code,
L.skinning_disabled_shader_code);Xb.register();L.skinning_uniforms_block=Xb;var Yb=new d.ShaderBlock("skinning_texture");Yb.defineContextMacros({skinning_mode:"skinning_texture"});Yb.addCode(GL.VERTEX_SHADER,"\n#define USE_SKINNING_TEXTURE\n"+L.skinning_shader_code,L.skinning_disabled_shader_code);Yb.register();L.skinning_texture_block=Yb;Ya.icon="mini-icon-teapot.png";Ya["@svg"]={type:"resource"};Ya.prototype.onAddedToScene=function(a){};Ya.prototype.onRemovedFromScene=function(a){};Ya.prototype.onAddedToNode=
function(a){LEvent.bind(a,"collectRenderInstances",this.onCollectInstances,this);this._RI.node=a};Ya.prototype.onRemovedFromNode=function(a){LEvent.unbind(a,"collectRenderInstances",this.onCollectInstances,this)};Ya.prototype.getMesh=function(){if(!this.svg)return null;var a=d.ResourcesManager.getResource(this.svg),b=null;this._svg_data===a&&(b=this._mesh);b||(b=this._mesh=GL.Mesh.cube());return b};Ya.prototype.onCollectInstances=function(a,b){if(this._enabled){var c=this.getMesh();if(!c)return null;
if(this._root){var e=this._RI;e.setMatrix(this._root.transform._global_matrix);mat4.multiplyVec3(e.center,e.matrix,d.ZEROS);var g=this._root.getMaterial();e.setMaterial(g);e.setMesh(c,GL.TRIANGLES);e.setRange(0,-1);e.collision_mesh=c;b.push(e)}}};Ya.prototype.configure=function(a){void 0!==a.enabled&&(this.enabled=a.enabled);this.svg=a.svg};Ya.prototype.serialize=function(){return{enabled:this.enabled,svg:this.svg}};Ya.prototype.getResources=function(a){"string"==typeof this.svg&&(a[this.svg]=d.Resource);
return a};Ya.prototype.onResourceRenamed=function(a,b,c){this.svg==a&&(this.svg=b)};Da.icon="mini-icon-dome.png";Da["@material"]={type:d.TYPES.MATERIAL};Da["@texture"]={type:d.TYPES.TEXTURE};Da.prototype.onAddedToNode=function(a){LEvent.bind(a,"collectRenderInstances",this.onCollectInstances,this)};Da.prototype.onRemovedFromNode=function(a){LEvent.unbind(a,"collectRenderInstances",this.onCollectInstances,this)};Da.prototype.onAddedToScene=function(a){LEvent.bind(a,"start",this.onStart,this)};Da.prototype.onRemovedFromScene=
function(a){LEvent.unbind(a,"start",this.onStart,this)};Object.defineProperty(Da.prototype,"intensity",{set:function(a){this._intensity=a;this._material&&this._material._color.set([a,a,a,1])},get:function(){return this._intensity},enumerable:!0});Object.defineProperty(Da.prototype,"bake_to_cubemap",{set:function(a){(this._bake_to_cubemap=a)&&this.bakeToCubemap()},get:function(){return this._bake_to_cubemap},enumerable:!0});Da.prototype.getResources=function(a){this.texture&&this.texture.constructor===
String&&(a[this.texture]=GL.Texture);this.material&&this.material.constructor===String&&(a[this.material]=d.Material);return a};Da.prototype.onResourceRenamed=function(a,b,c){this.texture==a&&(this.texture=b)};Da.prototype.onCollectInstances=function(a,b){if(this._root&&this.enabled){var c=this._mesh;c||(c=this._mesh=GL.Mesh.cube({size:10}));var e=this._render_instance;e||(this._render_instance=e=new d.RenderInstance(this._root,this),e.priority=100,e.onPreRender=function(a){a=d.Renderer._current_camera.getEye();
mat4.identity(this.matrix);mat4.setTranslation(this.matrix,a);if(this.node.transform){var b=this.node.transform.getGlobalRotationMatrix();mat4.multiply(this.matrix,this.matrix,b)}vec3.copy(this.center,a)});var g=null;if(this.material)g=d.ResourcesManager.getResource(this.material);else{var f=null,f=this.use_environment&&d.Renderer._current_scene.info?d.Renderer._current_scene.info.textures.environment:this.texture;if(!f||!d.ResourcesManager.textures[f])return;(g=this._material)?g.color.set([this.intensity,
this.intensity,this.intensity]):(g=this._material=new d.ShaderMaterial({flags:{two_sided:!0,cast_shadows:!1,receive_shadows:!1,ignore_frustum:!0,ignore_lights:!0,depth_test:!1},use_scene_ambient:!1,color:[this.intensity,this.intensity,this.intensity]}),g.shader_code=new d.ShaderCode(Da.shader_code));g.setProperty("Texture",f)}e.setMesh(c);e.setMaterial(g);b.push(e);this.material&&g&&this._bake_to_cubemap&&(this._prev_mat!=g||this._mat_version!=g.version)&&(this._prev_mat=g,this._mat_version=g.version,
this.bakeToCubemap())}};Da.prototype.onStart=function(a){this._bake_to_cubemap&&this.bakeToCubemap()};Da.prototype.bakeToCubemap=function(a,b){var c=this;a=a||512;b=b||new d.RenderSettings;if(this.root&&this.root.scene){var e=this.root.scene;if(this._render_instance&&this._render_instance.material){var g=[];this.onCollectInstances(null,g);d.Renderer.processVisibleData(e,b,null,g,!0);b.render_helpers=!1;this._baked_texture=d.Renderer.renderToCubemap(vec3.create(),a,this._baked_texture,b,0.001,100,
vec4.create(),g);d.ResourcesManager.registerResource(":baked_skybox",this._baked_texture);this.root.scene.info&&(this.root.scene.info.textures.environment=":baked_skybox")}else setTimeout(function(){c.bakeToCubemap.bind(c)},500)}};Da.shader_code='\n\\js\n\tthis.createSampler("Texture","u_color_texture", { magFilter: GL.LINEAR, missing: "white"} );\n\tthis.queue = LS.RenderQueue.BACKGROUND;\n\tthis.render_state.cull_face = false;\n\tthis.render_state.front_face = GL.CW;\n\tthis.render_state.depth_test = false;\n\tthis.render_state.front_face = GL.CW;\n\tthis.flags.ignore_frustum = true;\n\tthis.flags.ignore_lights = true;\n\tthis.flags.cast_shadows = false;\n\tthis.flags.receive_shadows = false;\n\n\\color.vs\n\tprecision mediump float;\n\tattribute vec3 a_vertex;\n\tvarying vec3 v_world_position;\n\tuniform mat4 u_model;\n\tuniform mat4 u_viewprojection;\n\tvoid main() {\n\t\tvec4 vertex4 = u_model * vec4(a_vertex,1.0);\n\t\tv_world_position = vertex4.xyz;\n\t\tgl_Position = u_viewprojection * vertex4;\n\t}\n\\color.fs\n\tprecision mediump float;\n\tvarying vec3 v_world_position;\n\tuniform vec4 u_material_color;\n\tuniform vec3 u_camera_eye;\n\tuniform samplerCube u_color_texture;\n\tvec2 polarToCartesian(in vec3 V)\n\t{\n\t\treturn vec2( 0.5 - (atan(V.z, V.x) / -6.28318531), asin(V.y) / 1.57079633 * 0.5 + 0.5);\n\t}\n\tvoid main() {\n\t\tvec3 E = normalize( v_world_position - u_camera_eye);\n\t\tvec4 color = textureCube( u_color_texture, E );\n\t\tgl_FragColor = u_material_color * color;\n\t}\n\\picking.vs\n\tprecision mediump float;\n\tattribute vec3 a_vertex;\n\tuniform mat4 u_model;\n\tuniform mat4 u_viewprojection;\n\tvoid main() {\n\t\tvec4 vertex4 = vec4(a_vertex,1.0);\n\t\tgl_Position = (u_viewprojection * u_model) * vertex4;\n\t}\n\\picking.fs\n\tprecision mediump float;\n\tuniform vec4 u_material_color;\n\tvoid main() {\n\t\tgl_FragColor = u_material_color;\n\t}\n';
d.registerComponent(Da);d.Skybox=Da;ab.icon="mini-icon-bg.png";ab["@texture"]={type:"texture"};ab["@material_name"]={type:"material"};ab["@blend_mode"]={type:"enum",values:d.Blend};ab["@opacity"]={type:"number",step:0.01};ab.prototype.onAddedToNode=function(a){LEvent.bind(a,"collectRenderInstances",this.onCollectInstances,this)};ab.prototype.onRemovedFromNode=function(a){LEvent.unbind(a,"collectRenderInstances",this.onCollectInstances,this)};ab.prototype.getResources=function(a){"string"==typeof this.texture&&
(a[this.texture]=GL.Texture);return a};ab.prototype.onResourceRenamed=function(a,b,c){this.texture==a&&(this.texture=b)};ab.prototype.onCollectInstances=function(a,b){if(this.enabled){var c=null;this.material_name&&(c=d.ResourcesManager.materials[this.material_name]);if(!c){var e=this.texture;if(!e)return;e.constructor===String&&(e=d.ResourcesManager.textures[e]);c=this._material?this._material:this._material=new d.StandardMaterial({shader:"lowglobal",queue:d.RenderQueue.BACKGROUND,flags:{cast_shadows:!1,
ignore_lights:!0,two_sided:!0,depth_test:!1,ignore_frustum:!0},use_scene_ambient:!1});c.setTexture("color",e);c.color.set(this.color);c.opacity=this.opacity;c.blend_mode=this.blend_mode}e=this._mesh;e||(e=this._mesh=GL.Mesh.plane({size:2}));var g=this._render_instance;g||(this._render_instance=g=new d.RenderInstance(this._root,this));g.setMesh(e);g.setMaterial(c);b.push(g)}};Ea.icon="mini-icon-collider.png";Ea.BOX=d.PhysicsInstance.BOX;Ea.SPHERE=d.PhysicsInstance.SPHERE;Ea.MESH=d.PhysicsInstance.MESH;
Ea["@size"]={type:"vec3",step:0.01};Ea["@center"]={type:"vec3",step:0.01};Ea["@mesh"]={type:"mesh"};Ea["@shape"]={type:"enum",values:{Box:Ea.BOX,Sphere:Ea.SPHERE,Mesh:Ea.MESH}};Ea.prototype.onAddedToScene=function(a){LEvent.bind(a,"collectPhysicInstances",this.onGetColliders,this)};Ea.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"collectPhysicInstances",this.onGetColliders,this)};Ea.prototype.getMesh=function(){return"string"===typeof this.mesh?d.ResourcesManager.meshes[this.mesh]:this.mesh};
Ea.prototype.getResources=function(a){if(this.mesh)return"string"==typeof this.mesh&&(a[this.mesh]=Mesh),a};Ea.prototype.onResourceRenamed=function(a,b,c){this.mesh==a&&(this.mesh=b)};Ea.prototype.onGetColliders=function(a,b){if(this.enabled){var c=this._PI;c||(this._PI=c=new d.PhysicsInstance(this._root,this));this._root.transform&&c.matrix.set(this._root.transform._global_matrix);c.type=this.shape;c.layers=this._root.layers;var e=null;if(c.type===d.PhysicsInstance.MESH||this.use_mesh_bounding)e=
this.getMesh();c.type===d.PhysicsInstance.SPHERE?e?BBox.copy(c.oobb,e.bounding):BBox.setCenterHalfsize(c.oobb,this.center,[this.size[0],this.size[0],this.size[0]]):c.type===d.PhysicsInstance.BOX&&(e?BBox.copy(c.oobb,e.bounding):BBox.setCenterHalfsize(c.oobb,this.center,this.size));e?vec3.copy(c.center,BBox.getCenter(e.bounding)):vec3.copy(c.center,this.center);vec3.transformMat4(c.center,c.center,c.matrix);if(c.type===d.PhysicsInstance.MESH){if(!e)return;c.setMesh(e)}b.push(c)}};d.registerComponent(Ea);
Object.defineProperty(Sa.prototype,"properties",{set:function(a){if(a&&a.constructor===Array){this._properties.length=a.length;this._properties_by_name={};for(var b=0;b<a.length;++b){var c=a[b];this._properties[b]=c;this._properties_by_name[c.name]=c}}},get:function(){return this._properties},enumerable:!0});Sa.icon="mini-icon-bg.png";Sa.prototype.onAddedToNode=function(a){a.custom||(a.custom=this)};Sa.prototype.onRemovedFromNode=function(a){a.custom==this&&delete a.custom};Sa.prototype.getResources=
function(a){return a};Sa.prototype.addProperty=function(a){this._properties.push(a);this._properties_by_name[a.name]&&console.warn("CustomData: there is a property with the same name");this._properties_by_name[a.name]=a};Sa.prototype.getProperty=function(a){return this._properties_by_name[a]};Sa.prototype.getPropertiesInfo=function(){return this._properties};Sa.prototype.updateProperty=function(a){this._properties_by_name[a.name]=a};Sa.prototype.getPropertyInfoFromPath=function(a){return(a=this._properties_by_name[a[0]])?
{node:this._root,target:a,name:"value",value:a.value,type:a.type}:null};Sa.prototype.setPropertyValueFromPath=function(a,b,c){if(a=this._properties_by_name[a[c||0]])a.value&&a.value.set?a.value.set(b):a.value=b};Sa.prototype.get=function(a){if(a=this._properties_by_name[a])return a.value};Sa.prototype.onResourceRenamed=function(a,b,c){};d.registerComponent(Sa);d.CustomData=Sa;var Eb=vec3.create();Pa.icon="mini-icon-teapot.png";Pa["@texture"]={type:"texture"};Pa["@blend_mode"]={type:"enum",values:d.Blend};
Pa["@atlas"]={type:"component",filter:"SpriteAtlas"};Pa["@area"]={type:"vec4",step:0.001};Object.defineProperty(Pa.prototype,"size",{set:function(a){this._size.set(a)},get:function(){return this._size},enumerable:!0});Object.defineProperty(Pa.prototype,"area",{set:function(a){this._area.set(a)},get:function(){return this._area},enumerable:!0});Object.defineProperty(Pa.prototype,"atlas",{set:function(a){var b=null;a&&a.constructor===String?(this._atlas=a,(b=(this._root.scene||d.GlobalScene).findComponentByUId(a))&&
b.constructor!=d.Components.SpriteAtlas&&(console.warn("Atlas must be of type SpriteAtlas"),b=null)):(this._atlas=a?a.uid:null,b=a);this._atlas_component&&this._atlas_component!=b&&this._atlas_component.removeSprite(this);(this._atlas_component=b)&&this._atlas_component.addSprite(this)},get:function(){return this._atlas},enumerable:!0});Pa.prototype.onAddedToNode=function(a){LEvent.bind(a,"collectRenderInstances",this.onCollectInstances,this);this._atlas_component&&this._atlas_component.addSprite(this)};
Pa.prototype.onRemovedFromNode=function(a){LEvent.unbind(a,"collectRenderInstances",this.onCollectInstances,this);this._atlas_component&&this._atlas_component.removeSprite(this)};Pa.prototype.onAddedToScene=function(a){this._atlas_component&&this._atlas_component.addSprite(this)};Pa.prototype.onRemovedFromScene=function(a){this._atlas_component&&this._atlas_component.removeSprite(this)};Pa.prototype.onCollectInstances=function(a,b){if(this.enabled&&!this._atlas&&this._root){var c=d.Components.Sprite._mesh;
c||(c=d.Components.Sprite._mesh=GL.Mesh.plane());var e=this._render_instance;e||(this._render_instance=e=new d.RenderInstance(this._root,this),e.setMesh(c,gl.TRIANGLES));this._material||(this._material=new d.StandardMaterial({shader_name:"lowglobal",flags:{two_sided:!0}}));this._material.setTexture("color",this.texture,{uvs:d.Material.COORDS_UV_TRANSFORMED,magFilter:this.filtering?gl.LINEAR:gl.NEAREST});this._material.blend_mode=this.blend_mode;e.setMaterial(this._material);this._root.transform&&
e.setMatrix(this._root.transform._global_matrix);mat4.getTranslation(e.center,this._root.transform._global_matrix);Eb[0]=this._size[0]*(this.flip_x?-1:1);Eb[1]=this._size[1];Eb[2]=1;mat4.scale(e.matrix,e.matrix,Eb);mat3.identity(this._material.uvs_matrix);mat3.translate(this._material.uvs_matrix,this._material.uvs_matrix,this._area.subarray(0,2));mat3.scale(this._material.uvs_matrix,this._material.uvs_matrix,this._area.subarray(2,4));b.push(e)}};Pa.prototype.getResources=function(a){"string"==typeof this.texture&&
(a[this.texture]=GL.Texture);return a};Pa.prototype.onResourceRenamed=function(a,b,c){this.texture==a&&(this.texture=b)};d.registerComponent(Pa);Fa.icon="mini-icon-teapot.png";Fa["@texture"]={type:"texture"};Fa["@areas"]={type:"texture_areas"};Fa.plane_vertices=[vec3.fromValues(-0.5,0.5,0),vec3.fromValues(0.5,-0.5,0),vec3.fromValues(0.5,0.5,0),vec3.fromValues(-0.5,-0.5,0)];Fa.plane_normal=vec3.fromValues(0,0,1);Fa.prototype.onAddedToNode=function(a){LEvent.bind(a,"collectRenderInstances",this.onCollectInstances,
this)};Fa.prototype.onRemovedFromNode=function(a){LEvent.unbind(a,"collectRenderInstances",this.onCollectInstances,this)};Fa.prototype.createMesh=function(){if(this._mesh_maxsprites!=this._max_sprites){for(var a=new Float32Array(12*this._max_sprites),b=new Float32Array(12*this._max_sprites),c=new Float32Array(8*this._max_sprites),e=new Float32Array(16*this._max_sprites),d=new Uint16Array(6*this._max_sprites),f=new Float32Array([0,0,1,1,1,0,0,1]),h=new Float32Array([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]),
k=0,l=this._max_sprites;k<l;++k)c.set(f,8*k),e.set(h,16*k),d[6*k]=4*k,d[6*k+1]=4*k+1,d[6*k+2]=4*k+2,d[6*k+3]=4*k,d[6*k+4]=4*k+3,d[6*k+5]=4*k+1;this._mesh=new GL.Mesh;this._mesh.addBuffers({vertices:a,normals:b,coords:c,colors:e},{triangles:d},gl.STREAM_DRAW);this._mesh_maxsprites=this._max_sprites}};Fa.prototype.updateMesh=function(){this._mesh||this.createMesh();for(var a=this._mesh,b=Fa.plane_vertices,c=Fa.plane_normal,e=a.getBuffer("vertices"),d=a.getBuffer("normals"),a=a.getBuffer("coords"),f=
e.data,h=d.data,k=a.data,l=0,n=0,p=Math.min(this._sprites.length,this._max_sprites);n<p;++n){var m=this._sprites[n];if(m.enabled){var q=null;if(m.matrix)q=m.matrix;else if(m._root&&m._root.transform)q=m._root.transform._global_matrix;else continue;mat4.rotateVec3(Eb,q,c);for(var s=0;4>s;++s){var t=12*l+3*s,u=f.subarray(t,t+3);u.set(b[s]);u[0]*=m._size[0];u[1]*=m._size[1];vec3.transformMat4(u,u,q);h.set(Eb,t)}t=m._area;m=t[0];q=t[1];s=t[2];t=t[3];k.set([m,q,m+s,q+t,m+s,q,m,q+t],8*l);l+=1}}l&&(e.upload(),
d.upload(),a.upload());this._last_index=6*l};Fa.prototype.onCollectInstances=function(a,b){if(this.enabled&&this._root&&this._sprites.length){this.updateMesh();var c=this._mesh;if(this._last_index){var e=this._render_instance;e||(this._render_instance=e=new d.RenderInstance(this._root,this),e.setMesh(c,gl.TRIANGLES));this._material||(this._material=new d.StandardMaterial({shader_name:"lowglobal",flags:{two_sided:!0}}));this._material.setTexture("COLOR",this.texture);e.setMaterial(this._material);
e.setRange(0,this._last_index);b.push(e)}}};Fa.prototype.addSprite=function(a){-1==this._sprites.indexOf(a)&&this._sprites.push(a)};Fa.prototype.removeSprite=function(a){a=this._sprites.indexOf(a);-1!=a&&this._sprites.splice(a,1)};Fa.prototype.getResources=function(a){"string"==typeof this.texture&&(a[this.texture]=GL.Texture);return a};Fa.prototype.onResourceRenamed=function(a,b,c){this.texture==a&&(this.texture=b)};d.registerComponent(Fa);Fa.Area=function(){this._start=vec2.create();this._size=
vec2.create()};E.max_recursive_level=32;E.recursive_level=0;E.propagable_events="finish beforeRenderMainPass beforeRenderInstances afterRenderInstances readyToRender renderGUI renderHelpers".split(" ");E.fx_propagable_events=["enableFrameContext","showFrameContext"];Object.defineProperty(E.prototype,"scene_path",{set:function(a){this._scene_path!=a&&(this._scene_path=a,this._root.scene&&this.reloadScene())},get:function(){return this._scene_path},enumerable:!0});Object.defineProperty(E.prototype,
"frame_fx",{set:function(a){this._frame_fx!=a&&(this._frame_fx=a,this.updateBindings())},get:function(){return this._frame_fx},enumerable:!0});E["@scene_path"]={type:d.TYPES.SCENE,widget:"resource"};E.icon="mini-icon-teapot.png";E.prototype.onAddedToScene=function(a){LEvent.bind(a,"collectData",this.onCollectData,this);LEvent.bind(a,"start",this.onStart,this);LEvent.bind(a,"update",this.onUpdate,this);for(var b in E.propagable_events)LEvent.bind(a,E.propagable_events[b],this.onEvent,this);this.updateBindings();
this._scene_path&&this.reloadScene()};E.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"collectData",this.onCollectData,this);LEvent.unbind(a,"start",this.onStart,this);LEvent.unbind(a,"update",this.onUpdate,this);var b=E.propagable_events.concat(E.fx_propagable_events),c;for(c in b)LEvent.unbind(a,b[c],this.onEvent,this)};E.prototype.onStart=function(){E.recursive_level+=1;this._scene_is_ready&&E.recursive_level<E.max_recursive_level&&this._scene.start();E.recursive_level-=1};E.prototype.onUpdate=
function(a,b){E.recursive_level+=1;this.send_events&&E.recursive_level<E.max_recursive_level&&this._scene.update(b);E.recursive_level-=1};E.prototype.onEvent=function(a,b){this.enabled&&this.send_events&&this._scene_path&&(E.recursive_level+=1,E.recursive_level<E.max_recursive_level&&LEvent.trigger(this._scene,a,b),E.recursive_level-=1)};E.prototype.updateBindings=function(){var a=this._root.scene;if(a){if(this._frame_fx&&!this._frame_fx_binded){for(var b in E.fx_propagable_events)LEvent.bind(a,E.fx_propagable_events[b],
this.onEvent,this);this._frame_fx_binded=!0}if(!this._frame_fx&&this._frame_fx_binded){for(b in E.fx_propagable_events)LEvent.unbind(a,E.fx_propagable_events[b],this.onEvent,this);this._frame_fx_binded=!1}}};E.prototype.onCollectData=function(){if(this.enabled&&this._scene_path&&this._scene_is_ready){var a=this._root.scene,b=this._scene;E.recursive_level+=1;E.recursive_level<E.max_recursive_level&&b.collectData();E.recursive_level-=1;var c=null;this._root.transform&&(c=this._root.transform.getGlobalMatrix());
if(this.include_instances&&(a._instances.push.apply(a._instances,b._instances),a._colliders.push.apply(a._colliders,b._colliders),c))for(var e=0;e<b._instances.length;++e)b._instances[e].applyTransform(c);this.include_lights&&a._lights.push.apply(a._lights,b._lights);this.include_cameras&&a._cameras.push.apply(a._cameras,b._cameras)}};E.prototype.load=function(){this.reloadScene()};E.prototype.unload=function(){this._scene_is_ready=!1;this._scene.clear()};E.prototype.reloadScene=function(){function a(){console.log("SceneInclude: scene loaded");
this._scene_is_ready=!0;this._root.scene._state==d.PLAYING&&this._scene.start()}this._scene_is_ready=!1;E.recursive_level+=1;E.recursive_level<E.max_recursive_level&&this._scene.loadFromResources(this._scene_path,a.bind(this));E.recursive_level-=1};E.prototype.getPropertyInfoFromPath=function(a){if(!a.length||"custom"!=a[0])return null;var b=this._scene.root.custom;return b?(a=b._properties_by_name[a[1]])?{node:this._root,target:a,name:"value",value:a.value,type:a.type}:null:null};E.prototype.setPropertyValueFromPath=
function(a,b,c){c=c||0;if(!a.length||"custom"!=a[c])return null;var e=this._scene.root.custom;if(!e)return null;e.setPropertyValueFromPath(a,b,c+1)};E.prototype.getEvents=function(){return{loaded:"event",unloaded:"event"}};E.prototype.getActions=function(){return{load:"function",unload:"function"}};E.prototype.getResources=function(a){this._scene_path&&(a[this._scene_path]=d.Scene);return a};E.prototype.onResourceRenamed=function(a,b,c){a==this._scene_path&&(this._scene_path=b)};d.registerComponent(E);
Qa["@color"]={type:"vec4",step:0.01};Qa.CIRCLE=1;Qa.SQUARE=2;Qa["@subdivisions"]={type:"number",step:1,min:1,max:100,precision:0};Qa["@type"]={type:"enum",values:{circle:Qa.CIRCLE,square:Qa.SQUARE}};Qa.prototype.onAddedToScene=function(a){LEvent.bind(d.Renderer,"renderHelpers",this.onRender,this)};Qa.prototype.onRemovedFromScene=function(a){LEvent.unbind(d.Renderer,"renderHelpers",this.onRender,this)};Qa.prototype.onRender=function(a,b){if(this.enabled&&(d.Renderer._in_player&&this.in_player||!d.Renderer._in_player&&
this.in_editor)){this._is_visible=!0;var c=this._root;c&&c.visible&&c.transform&&(c=c.transform.getGlobalMatrixRef(),gl.enable(gl.BLEND),gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA),this.renderHelper(c,this.color,this.fill),gl.disable(gl.BLEND))}else this._is_visible=!1};Qa.prototype.renderHelper=function(a,b,c){this.always_on_top&&gl.disable(gl.DEPTH_TEST);gl.disable(gl.CULL_FACE);d.Draw.push();d.Draw.setMatrix(a);d.Draw.setColor(b);this.type==Qa.CIRCLE?d.Draw.renderCircle(this.size,32,!this.vertical,
c):this.type==Qa.SQUARE&&(c?d.Draw.renderRectangle(this.size,this.size,!this.vertical,!0):d.Draw.renderRectangle(this.size,this.size,!this.vertical));d.Draw.pop();gl.enable(gl.CULL_FACE);gl.enable(gl.DEPTH_TEST)};Qa.prototype.renderPicking=function(a){if(this._is_visible){a=this._root.transform.getGlobalMatrixRef(!0);var b=d.Picking.getNextPickingColor({instance:this});this.renderHelper(a,b,!0)}};d.registerComponent(Qa);Ka.editor_color=[0.33,0.874,0.56,0.9];Ka.onShowMainAnnotation=function(a){"undefined"!=
typeof AnnotationModule&&AnnotationModule.editAnnotation(a)};Ka.onShowPointAnnotation=function(a,b){function c(a){this.text=a}var e=a.getComponent(Ka);e&&"undefined"!=typeof AnnotationModule&&AnnotationModule.showDialog(b.text,{item:b,on_close:c.bind(b),on_delete:function(a){e.removeAnnotation(a.item);this._root.scene.requestFrame()},on_focus:function(a){AnnotationModule.focusInAnnotation(a.item);e._selected=a.item}})};Ka.prototype.addAnnotation=function(a){this._selected=null;this.notes.push(a)};
Ka.prototype.getAnnotation=function(a){return this.nodes[a]};Ka.prototype.removeAnnotation=function(a){this._selected=null;a=this.notes.indexOf(a);-1!=a&&this.notes.splice(a,1)};Ka.prototype.setStartTransform=function(){this.start_position=this.getObjectCenter()};Ka.prototype.getObjectCenter=function(){var a=vec3.create(),b=this._root.getMesh();b&&b.bounding&&vec3.copy(a,BBox.getCenter(b.bounding));return this._root.transform.localToGlobal(a)};Ka.prototype.serialize=function(){for(var a={object_class:"AnnotationComponent",
text:this.text,notes:[],start_position:this.start_position},b=0;b<this.notes.length;++b){var c=this.notes[b],e;for(e in c)c[e].constructor==Float32Array&&Array.prototype.slice.call(c[e]);a.notes.push(c)}return a};Ka.prototype.onAddedToScene=function(a){LEvent.bind(a,"mousedown",this.onMouse,this)};Ka.prototype.onRemovedFromScene=function(a){LEvent.bind(a,"mousedown",this.onMouse,this)};Ka.prototype.onMouse=function(a,b){if("mousedown"==b.eventType){this._screen_pos[2]=0;var c=vec3.dist(this._screen_pos,
[b.canvasx,gl.canvas.height-b.canvasy,0]);if(30>c)Ka.onShowMainAnnotation(this._root);for(var e=0;e<this.notes.length;++e){var d=this.notes[e],c=vec2.dist(d._end_screen,[b.mousex,gl.canvas.height-b.mousey]);if(30>c)return this._selected=d,Ka.onShowPointAnnotation(this._root,d),!0}}};Ka.prototype.renderEditor=function(a){if(this.text||this.notes.length){a=vec3.create();var b=this._root.getMesh();b&&vec3.copy(a,BBox.getCenter(b.bounding));a=d.Renderer._current_camera;var c=this._root.transform.getGlobalPosition(),
b=this.getObjectCenter(),e=a.getEye(),g=a.getLocalVector([1,0,0]),f=a.getLocalVector([0,1,0]);a.getLocalVector([0,0,1]);var h=Math.tan(a.fov*DEG2RAD)*vec3.dist(c,e),f=vec3.scale(vec3.create(),f,0.2*h),g=vec3.scale(vec3.create(),g,0.2*h),k=vec3.add(vec3.create(),c,f);vec3.add(k,g,k);a.project(k,null,this._screen_pos);gl.enable(gl.BLEND);gl.enable(gl.DEPTH_TEST);d.Draw.setColor([1,1,1,1]);var g=[],f=[],e=[],l=[];this.text&&(g.push(c,k),f.push([1,1,1,0],[1,1,1,1]),window.EditorModule&&d.Draw.renderImage(k,
EditorModule.icons_path+"/mini-icon-script.png",0.03*h));for(var n=this._root.transform.getGlobalMatrix(),c=0;c<this.notes.length;++c){var k=this.notes[c],h=mat4.multiplyVec3(vec3.create(),n,k.start),p=mat4.multiplyVec3(vec3.create(),n,k.end);k.end_world=p;e.push(p);g.push(h,p);this._selected==k?(l.push([1,1,1,1]),f.push([1,1,1,0.2],[1,1,0.8,1])):(l.push(d.Components.AnnotationComponent.editor_color),f.push([0,0,0,0.2],d.Components.AnnotationComponent.editor_color));k._end_screen=a.project(p)}if((h=
this.start_position)&&1<vec3.dist(h,b))for(k=vec3.dist(h,b)/20,b=vec3.subtract(vec3.create(),b,h),vec3.normalize(b,b),c=0;20>c;c+=2)n=vec3.scale(vec3.create(),b,c*k),vec3.add(n,n,h),g.push(n),n=vec3.scale(vec3.create(),b,(c+1)*k),vec3.add(n,n,h),g.push(n),f.push([0,1,0,0.2],[0,1,0,1]);d.Draw.setPointSize(12);d.Draw.renderPoints(e,l);d.Draw.setColor([0,0,0,0.5]);d.Draw.setPointSize(10);d.Draw.renderPoints(e,l);d.Draw.setColor([1,1,1,1]);d.Draw.renderLines(g,f);gl.depthFunc(gl.GREATER);d.Draw.setAlpha(0.1);
d.Draw.renderPoints(e,l);d.Draw.renderLines(g,f);gl.depthFunc(gl.LESS);if(gl.start2D)for(d.Draw.setColor(d.Components.AnnotationComponent.editor_color),b=vec3.create(),gl.start2D(),gl.fillColor=d.Components.AnnotationComponent.editor_color,gl.font="20px Arial",c=0;c<this.notes.length;++c)k=this.notes[c],a.project(k.end_world,null,b,!0),g=k.text.split("\n")[0],gl.fillText(g,b[0]+10,b[1]+8);gl.disable(gl.BLEND)}};d.registerComponent(Ka);Gb.icon="mini-icon-rotator.png";Gb.prototype.onAddedToScene=function(a){LEvent.bind(a,
"update",this.onUpdate,this)};Gb.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"update",this.onUpdate,this)};Gb.prototype.onUpdate=function(a,b){if(this._root&&this.enabled){var c=this._root.scene;this._default||(this._default=this._root.transform.getRotation());vec3.normalize(this.axis,this.axis);if(this.swing){var e=quat.setAxisAngle(quat.create(),this.axis,Math.sin(this.speed*c._global_time*2*Math.PI)*this.swing_amplitude*DEG2RAD);quat.multiply(this._root.transform._rotation,e,this._default);
this._root.transform._must_update=!0}else this.local_space?this._root.transform.rotate(this.speed*b,this.axis):this._root.transform.rotateGlobal(this.speed*b,this.axis);c&&c.requestFrame()}};d.registerComponent(Gb);D.NONE=0;D.ORBIT=1;D.ORBIT_HORIZONTAL=2;D.ROTATE=5;D.ROTATE_HORIZONTAL=6;D.PAN=10;D.PAN_XZ=11;D.CHANGE_DISTANCE=15;D.WALK=16;D.ELEVATE=17;D.FOV=18;D.icon="mini-icon-cameracontroller.png";D.mode_values={None:D.NONE,Orbit:D.ORBIT,"Orbit Horizontal":D.ORBIT_HORIZONTAL,Rotate:D.ROTATE,"Rotate Horizontal":D.ROTATE_HORIZONTAL,
Pan:D.PAN,"Pan XZ":D.PAN_XZ,"Change Distance":D.CHANGE_DISTANCE,Walk:D.WALK,Elevate:D.ELEVATE};D.wheel_values={None:D.NONE,"Change Distance":D.CHANGE_DISTANCE,FOV:D.FOV,Walk:D.WALK,Elevate:D.ELEVATE};D["@no_button_action"]={type:"enum",values:D.mode_values};D["@left_button_action"]={type:"enum",values:D.mode_values};D["@middle_button_action"]={type:"enum",values:D.mode_values};D["@right_button_action"]={type:"enum",values:D.mode_values};D["@mouse_wheel_action"]={type:"enum",values:D.wheel_values};
D.prototype.onAddedToScene=function(a){LEvent.bind(a,"start",this.onStart,this);LEvent.bind(a,"finish",this.onFinish,this);LEvent.bind(a,"mousedown",this.onMouse,this);LEvent.bind(a,"mousemove",this.onMouse,this);LEvent.bind(a,"mousewheel",this.onMouse,this);LEvent.bind(a,"touchstart",this.onTouch,this);LEvent.bind(a,"touchmove",this.onTouch,this);LEvent.bind(a,"touchend",this.onTouch,this);LEvent.bind(a,"keydown",this.onKey,this);LEvent.bind(a,"keyup",this.onKey,this);LEvent.bind(a,"update",this.onUpdate,
this);LEvent.bind(a,"renderGUI",this.onRenderGUI,this)};D.prototype.onRemovedFromScene=function(a){LEvent.unbindAll(a,this)};D.prototype.onStart=function(a){this.lock_mouse&&d.Input.lockMouse(!0)};D.prototype.onFinish=function(a){this.lock_mouse&&d.Input.lockMouse(!1)};D.prototype.onUpdate=function(a){if(this._root&&this.enabled&&(a=this._root.camera)&&a.enabled){if(0!=this._moving[0]||0!=this._moving[1]||0!=this._moving[2]){var b=a.getLocalVector(this._moving);this.keyboard_walk_plane&&(b[1]=0);
vec3.length(b)&&(vec3.normalize(b,b),vec3.scale(b,b,this.walk_speed*(this._fast?10:1)),this._root.transform?this._root.transform.translateGlobal(b):a.move(b),a.updateMatrices())}this.smooth&&this._root.scene.requestFrame()}};D.prototype.processMouseButtonDownEvent=function(a,b,c){var e=this._camera=this._root.camera;if(e&&e.enabled)return a==D.PAN?this.testPerpendicularPlane(b.canvasx,gl.canvas.height-b.canvasy,e.getCenter(),c):a==D.PAN_XZ&&this.testOriginPlane(b.canvasx,gl.canvas.height-b.canvasy,
c),!1};D.prototype.processMouseButtonMoveEvent=function(a,b,c){var e=this._root,g=this._camera=e.camera;if(g&&g.enabled){var f=e._is_root,h=!1;if(a==D.NONE)return!1;if(a==D.ORBIT){c=b.deltax*this.rot_speed;b=-b.deltay*this.rot_speed;1E-4<Math.abs(c)&&(f?g.orbit(-c,[0,1,0]):(h=g.getEye(),e.transform.globalToLocal(h,h),e.transform.orbit(-c,[0,1,0],h)),g.updateMatrices(),h=!0);c=g.getRight();a=g.getFront();var k=g.getUp();a=vec3.dot(k,a);0.99<a&&0<b||-0.99>a&&0>b||(f?g.orbit(-b,c,this.orbit_center):
(h=g.getEye(),e.transform.globalToLocal(h,h),e.transform.orbit(-b,c,h)),h=!0)}else a==D.ORBIT_HORIZONTAL?(c=b.deltax*this.rot_speed,1E-4<Math.abs(c)&&(f?g.orbit(-c,[0,1,0]):(h=g.getEye(),e.transform.globalToLocal(h,h),e.transform.orbit(-c,[0,1,0],h)),g.updateMatrices(),h=!0)):a==D.ROTATE||a==D.ROTATE_HORIZONTAL?(g.rotate(-b.deltax*this.rot_speed*0.2,d.TOP),g.updateMatrices(),a==D.ROTATE&&(c=g.getLocalVector(d.RIGHT),f?g.rotate(-b.deltay*this.rot_speed*0.2,c):e.transform.rotate(-b.deltay*this.rot_speed*
0.2,d.RIGHT),g.updateMatrices()),h=!0):a==D.PAN?(h=vec3.create(),a=vec3.create(),k=vec3.create(),g.getCenter(a),this.testPerpendicularPlane(b.canvasx,gl.canvas.height-b.canvasy,a,h),vec3.sub(k,c,h),f?g.move(k):e.transform.translateGlobal(k),g.updateMatrices(),h=!0):a==D.PAN_XZ?(h=vec3.create(),k=vec3.create(),this.testOriginPlane(b.canvasx,gl.canvas.height-b.canvasy,h),vec3.sub(k,c,h),f?g.move(k):e.transform.translateGlobal(k),g.updateMatrices(),h=!0):a==D.CHANGE_DISTANCE?(g.orbitDistanceFactor(1+
b.deltay*this.wheel_speed*-0.05),g.updateMatrices(),h=!0):a==D.WALK?(k=g.getLocalVector([0,0,b.deltay*this.walk_speed]),g.move(k),g.updateMatrices(),h=!0):a==D.ELEVATE&&(g.move([0,b.deltay*this.walk_speed,0]),g.updateMatrices(),h=!0);return h}};D.prototype.onMouse=function(a,b){if(this._root&&this.enabled){var c=this._root,e=c.scene,g=c.camera;if(g&&g.enabled)if(b||(b=a),"mousewheel"==b.eventType){e=0<b.wheel?1:-1;switch(this.mouse_wheel_action){case D.CHANGE_DISTANCE:g.orbitDistanceFactor(1+-0.05*
e*this.wheel_speed);g.updateMatrices();break;case D.FOV:g.fov-=e,g.updateMatrices()}c.scene.requestFrame()}else c=!1,"mousedown"==b.eventType&&(this.lock_mouse&&!document.pointerLockElement&&e._state==d.PLAYING&&d.Input.lockMouse(!0),d.Input.Mouse.isButtonPressed(GL.LEFT_MOUSE_BUTTON)&&(c|=this.processMouseButtonDownEvent(this.left_button_action,b,this._collision_left)),d.Input.Mouse.isButtonPressed(GL.MIDDLE_MOUSE_BUTTON)&&(c|=this.processMouseButtonDownEvent(this.middle_button_action,b,this._collision_middle)),
d.Input.Mouse.isButtonPressed(GL.RIGHT_MOUSE_BUTTON)&&(c|=this.processMouseButtonDownEvent(this.right_button_action,b,this._collision_right)),this._dragging=!0),b.dragging||(this._dragging=!1),"mousemove"!=b.eventType&&"touchmove"!=b.eventType||!this.lock_mouse||!document.pointerLockElement&&!b.is_touch||(c|=this.processMouseButtonMoveEvent(this.no_button_action,b,this._collision_none)),"mousemove"==b.eventType&&b.dragging&&this._dragging&&(d.Input.Mouse.isButtonPressed(GL.LEFT_MOUSE_BUTTON)&&(c|=
this.processMouseButtonMoveEvent(this.left_button_action,b,this._collision_left)),d.Input.Mouse.isButtonPressed(GL.MIDDLE_MOUSE_BUTTON)&&(c|=this.processMouseButtonMoveEvent(this.middle_button_action,b,this._collision_middle)),d.Input.Mouse.isButtonPressed(GL.RIGHT_MOUSE_BUTTON)&&(c|=this.processMouseButtonMoveEvent(this.right_button_action,b,this._collision_right))),c&&this._root.scene.requestFrame()}};D.prototype.onTouch=function(a,b){if(this._root&&this.enabled){var c=this._root.camera;if(c&&c.enabled){b||
(b=a);if("touchstart"==b.type&&2==b.touches.length){var e=b.touches[0].clientX-b.touches[1].clientX,d=b.touches[0].clientY-b.touches[1].clientY;this._touch_distance=Math.sqrt(e*e+d*d);this._touch_center=[0.5*(b.touches[0].clientX+b.touches[1].clientX),0.5*(b.touches[0].clientY+b.touches[1].clientY)];b.preventDefault();return!1}if("touchmove"==b.type&&2==b.touches.length)return e=b.touches[0].clientX-b.touches[1].clientX,d=b.touches[0].clientY-b.touches[1].clientY,e=Math.sqrt(e*e+d*d),0.1>e&&(e=0.1),
d=this._touch_distance/e,this._touch_distance=e,c.orbitDistanceFactor(d),c.updateMatrices(),c.panning(-(0.5*(b.touches[0].clientX+b.touches[1].clientX)-this._touch_center[0]),0.5*(b.touches[0].clientY+b.touches[1].clientY)-this._touch_center[1],c.focalLength/gl.canvas.width),this._touch_center[0]=0.5*(b.touches[0].clientX+b.touches[1].clientX),this._touch_center[1]=0.5*(b.touches[0].clientY+b.touches[1].clientY),c.updateMatrices(),this._root.scene.requestFrame(),b.preventDefault(),!1}}};D.prototype.testOriginPlane=
function(a,b,c){a=this._root.camera.getRay(a,gl.canvas.height-b);c=c||vec3.create();return geo.testRayPlane(a.origin,a.direction,d.ZEROS,d.TOP,c)?!0:!1};D.prototype.testPerpendicularPlane=function(a,b,c,e){var d=this._root.camera;a=d.getRay(a,gl.canvas.height-b);b=d.getFront();c=c||d.getCenter();e=e||vec3.create();return geo.testRayPlane(a.origin,a.direction,c,b,e)?!0:!1};D.prototype.onKey=function(a,b){this._root&&this.enabled&&this.keyboard_walk&&(87==b.keyCode?this._moving[2]="keydown"==b.type?
-1:0:83==b.keyCode?this._moving[2]="keydown"==b.type?1:0:65==b.keyCode?this._moving[0]="keydown"==b.type?-1:0:68==b.keyCode?this._moving[0]="keydown"==b.type?1:0:16==b.keyCode&&("keydown"==b.type?this._fast=!0:"keyup"==b.type&&(this._fast=!1)))};D.prototype.onRenderGUI=function(){if(this.render_crosshair&&this.enabled&&this._camera&&this._camera.enabled&&d.Input.isMouseLocked()){var a=gl;gl.start2D();a.fillStyle="rgba(0,0,0,0.5)";a.fillRect(0.5*gl.viewport_data[2]-1,0.5*gl.viewport_data[3]-1,4,4);
a.fillStyle="rgba(255,255,255,1)";a.fillRect(0.5*gl.viewport_data[2],0.5*gl.viewport_data[3],2,2);gl.finish2D()}};d.registerComponent(D);cb.icon="mini-icon-rotator.png";cb.prototype.onAddedToScene=function(a){LEvent.bind(a,"mousemove",this.onSceneMouse,this)};cb.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"mousemove",this.onSceneMouse,this)};cb.prototype.onAddedToNode=function(a){LEvent.bind(a,"mousemove",this.onNodeMouse,this)};cb.prototype.onRemovedFromNode=function(a){LEvent.unbind(a,
"mousemove",this.onNodeMouse,this)};cb.prototype.onNodeMouse=function(a,b){if(this.on_node_clicked&&this.enabled)return this.onMouse(a,b)};cb.prototype.onSceneMouse=function(a,b){if(!this.on_node_clicked&&this.enabled)return this.onMouse(a,b)};cb.prototype.onMouse=function(a,b){if(this._root&&this._root.transform&&b.dragging){var c=this._root.scene,e=c.getCamera(),g=this.use_global_up_for_yaw?d.Components.Transform.UP:e.getLocalVector(d.Components.Transform.UP);this._root.transform.rotateGlobal(b.deltax*
this.rot_speed[0],g);e=e.getLocalVector(d.Components.Transform.RIGHT);this._root.transform.rotateGlobal(b.deltay*this.rot_speed[1],e);c.requestFrame()}};d.registerComponent(cb);Q.icon="mini-icon-billboard.png";Q.POSX=1;Q.NEGX=2;Q.POSY=3;Q.NEGY=4;Q.POSZ=5;Q.NEGZ=6;Q["@node_id"]={type:"node_id"};Q["@front"]={type:"enum",values:{"-Z":Q.NEGZ,"+Z":Q.POSZ,"-Y":Q.NEGY,"+Y":Q.POSY,"-X":Q.NEGX,"+X":Q.POSX}};Q["@up"]={type:"enum",values:{"-Z":Q.NEGZ,"+Z":Q.POSZ,"-Y":Q.NEGY,"+Y":Q.POSY,"-X":Q.NEGX,"+X":Q.POSX}};
Q.prototype.onAddedToScene=function(a){LEvent.bind(a,d.EVENT.BEFORE_RENDER,this.onBeforeRender,this)};Q.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,d.EVENT.BEFORE_RENDER,this.onBeforeRender,this)};Q.prototype.onBeforeRender=function(a){this.enabled&&this.updateOrientation()};Q.temp_mat3=mat3.create();Q.temp_mat=mat4.create();Q.prototype.updateOrientation=function(){if(this._root&&this._root.transform){var a=this._root.scene,b=this._root.transform,c=null,e=null,g=b.getGlobalPosition(this._global_position);
switch(this.up){case Q.NEGX:e=vec3.fromValues(-1,0,0);break;case Q.POSX:e=vec3.fromValues(1,0,0);break;case Q.NEGZ:e=vec3.fromValues(0,0,-1);break;case Q.POSZ:e=vec3.fromValues(0,0,1);break;case Q.NEGY:e=vec3.fromValues(0,-1,0);break;default:e=vec3.fromValues(0,1,0)}if(this.node_id){a=a.getNode(this.node_id);if(!a||a==this._root||!a.transform)return;c=a.transform.getGlobalPosition(this._target_position)}else if(this.face_camera){a=d.Renderer._current_camera||d.Renderer._main_camera;if(!a)return;c=
a.getEye()}else return;this.cylindrical&&(c[1]=g[1]);mat4.lookAt(Q.temp_mat,g,c,e);quat.fromMat4(b._rotation,Q.temp_mat);switch(this.front){case Q.POSY:quat.rotateX(b._rotation,b._rotation,-0.5*Math.PI);break;case Q.NEGY:quat.rotateX(b._rotation,b._rotation,0.5*Math.PI);break;case Q.POSX:quat.rotateY(b._rotation,b._rotation,0.5*Math.PI);break;case Q.NEGX:quat.rotateY(b._rotation,b._rotation,-0.5*Math.PI);break;case Q.POSZ:quat.rotateY(b._rotation,b._rotation,Math.PI)}b._on_change()}};d.registerComponent(Q);
Ra.icon="mini-icon-fog.png";Ra.LINEAR=1;Ra.EXP=2;Ra.EXP2=3;Ra["@color"]={type:"color"};Ra["@density"]={type:"number",min:0,max:1,step:1E-4,precision:4};Ra["@type"]={type:"enum",values:{linear:Ra.LINEAR,exponential:Ra.EXP,"exponential 2":Ra.EXP2}};Ra.prototype.onAddedToScene=function(a){LEvent.bind(a,"fillSceneUniforms",this.fillSceneUniforms,this)};Ra.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"fillSceneUniforms",this.fillSceneUniforms,this)};Ra.prototype.fillSceneUniforms=function(a,
b){this.enabled&&(this._uniforms.u_fog_info[0]=this.start,this._uniforms.u_fog_info[1]=this.end,this._uniforms.u_fog_info[2]=this.density,this._uniforms.u_fog_color=this.color,d.Renderer.enableFrameShaderBlock("fog",this._uniforms))};d.registerComponent(Ra);var Zb=new d.ShaderBlock("fog");Zb.bindEvent("fs_functions","\tuniform vec3 u_fog_info;\n\tuniform vec3 u_fog_color;\n");Zb.bindEvent("fs_final_pass","\tif(u_light_info.z == 0.0) { float cam_dist = length(u_camera_eye - v_pos);\n\tfloat fog = 1. - 1.0 / exp(max(0.0,cam_dist - u_fog_info.x) * u_fog_info.z);\n\tfinal_color.xyz = mix(final_color.xyz, u_fog_color, fog);\n}\n\n");
Zb.register();Ra.block=Zb;Hb.icon="mini-icon-follow.png";Hb.prototype.onAddedToScene=function(a){LEvent.bind(a,"beforeRender",this.updatePosition,this)};Hb.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"beforeRender",this.updatePosition,this)};Hb.prototype.updatePosition=function(a,b){if(this._root){var c=null,c=this._root.scene;if(this.follow_camera){c=d.Renderer._main_camera;if(!c)return;c=c.getEye()}else{c=c.getNode(this.node_uid);if(!c||!c.transform)return;c=c.transform.getGlobalPosition()}this.fixed_y&&
(c[1]=this._root.transform._position[1]);this._root.transform&&(this._root.transform.position=c)}};d.registerComponent(Hb);Object.defineProperty(I.prototype,"geometry",{get:function(){return this._geometry},set:function(a){this._geometry!=a&&(a=void 0===a||null===a?-1:a|0,I.VALID[a]&&(this._geometry=a,this._version++))},enumerable:!0});Object.defineProperty(I.prototype,"size",{get:function(){return this._size},set:function(a){this._size!=a&&(this._size=a,this._version++)},enumerable:!0});Object.defineProperty(I.prototype,
"subdivisions",{get:function(){return this._subdivisions},set:function(a){this._subdivisions!=a&&(this._subdivisions=a,this._version++)},enumerable:!0});Object.defineProperty(I.prototype,"primitive",{get:function(){return this._primitive},set:function(a){a=void 0===a||null===a?-1:a|0;if(-1==a||0==a||1==a||4==a||10==a)this._primitive=a},enumerable:!0});Object.defineProperty(I.prototype,"point_size",{get:function(){return this._point_size},set:function(a){this._point_size!=a&&(this._point_size=a)},
enumerable:!0});Object.defineProperty(I.prototype,"mesh",{get:function(){return this._custom_mesh||this._mesh},set:function(a){if(a&&a.constructor!==GL.Mesh)throw"mesh must be a GL.Mesh";if(this._custom_mesh=a)this._geometry=I.CUSTOM},enumerable:!1});I.CUBE=1;I.PLANE=2;I.CYLINDER=3;I.SPHERE=4;I.CIRCLE=5;I.HEMISPHERE=6;I.ICOSAHEDRON=7;I.CONE=8;I.QUAD=9;I.CUSTOM=100;I.VALID={1:"CUBE",2:"PLANE",3:"CYLINDER",4:"SPHERE",5:"CIRCLE",6:"HEMISPHERE",7:"ICOSAHEDRON",8:"CONE",9:"QUAD",100:"CUSTOM"};I.icon="mini-icon-cube.png";
I["@geometry"]={type:"enum",values:{Cube:I.CUBE,Plane:I.PLANE,Cylinder:I.CYLINDER,Sphere:I.SPHERE,Cone:I.CONE,Icosahedron:I.ICOSAHEDRON,Circle:I.CIRCLE,Hemisphere:I.HEMISPHERE,Quad:I.QUAD,Custom:I.CUSTOM}};I["@primitive"]={widget:"enum",values:{Default:-1,Points:0,Lines:1,Triangles:4,Wireframe:10}};I["@subdivisions"]={type:"number",step:1,min:1,precision:0};I["@point_size"]={type:"number",step:0.001};I.prototype.onAddedToNode=function(a){LEvent.bind(a,"collectRenderInstances",this.onCollectInstances,
this)};I.prototype.onRemovedFromNode=function(a){LEvent.unbind(a,"collectRenderInstances",this.onCollectInstances,this)};I.prototype.serialize=function(){var a=d.BaseComponent.prototype.serialize.call(this);this._geometry==I.CUSTOM&&this._custom_mesh&&(a.custom_mesh=this._custom_mesh.toJSON());return a};I.prototype.configure=function(a){d.BaseComponent.prototype.configure.call(this,a);this._geometry==I.PLANE&&!1===a.align_z&&(this._geometry=I.QUAD);a.geometry==I.CUSTOM&&a.custom_mesh&&(this._custom_mesh||
(this._custom_mesh=new GL.Mesh),this._custom_mesh.fromJSON(a.custom_mesh));this._version++};I.prototype.updateMesh=function(){var a=Math.max(0,this.subdivisions|0);switch(this._geometry){case I.CUBE:this._mesh=GL.Mesh.cube({size:this.size,normals:!0,coords:!0});break;case I.PLANE:this._mesh=GL.Mesh.plane({size:this.size,xz:!0,detail:a,normals:!0,coords:!0});break;case I.CYLINDER:this._mesh=GL.Mesh.cylinder({size:this.size,subdivisions:a,normals:!0,coords:!0});break;case I.SPHERE:this._mesh=GL.Mesh.sphere({size:this.size,
"long":a,lat:a,normals:!0,coords:!0});break;case I.CIRCLE:this._mesh=GL.Mesh.circle({size:this.size,slices:a,normals:!0,coords:!0});break;case I.HEMISPHERE:this._mesh=GL.Mesh.sphere({size:this.size,"long":a,lat:a,normals:!0,coords:!0,hemi:!0});break;case I.ICOSAHEDRON:this._mesh=GL.Mesh.icosahedron({size:this.size,subdivisions:a});break;case I.CONE:this._mesh=GL.Mesh.cone({radius:this.size,height:this.size,subdivisions:a});break;case I.QUAD:this._mesh=GL.Mesh.plane({size:this.size,xz:!1,detail:a,
normals:!0,coords:!0});break;case I.CUSTOM:this._mesh=this._custom_mesh}this._mesh_version=this._version};I.prototype.setCustomMesh=function(a){this._geometry=I.CUSTOM;this._mesh=this._custom_mesh=a};I.prototype.onCollectInstances=function(a,b){if(this.enabled&&this._root){var c=this._render_instance;c||(this._render_instance=c=new d.RenderInstance(this._root,this));this._mesh&&this._version==this._mesh_version||this.updateMesh();this._mesh&&(c.fromNode(this._root),c.setMesh(this._mesh,this._primitive),
this._root.mesh=this._mesh,c.setMaterial(this.material||this._root.getMaterial()),this.primitive==gl.POINTS&&(c.uniforms.u_point_size=this.point_size),b.push(c))}};d.registerComponent(I);Object.defineProperty(La.prototype,"textures",{set:function(a){if("object"==typeof a)for(var b in a)if(null===a[b]||a[b].constructor===String||a[b]===GL.Texture)this._textures[b]=a[b]},get:function(){return this._textures},enumerable:!0});Object.defineProperty(La.prototype,"render_settings",{set:function(a){a?"object"==
typeof a&&(this._render_settings||(this._render_settings=new d.RenderSettings),a.constructor===Array&&"RenderSettings"==a[3]?this._render_settings.configure(a[2]):this._render_settings.configure(a)):this._render_settings=null},get:function(){return this._render_settings},enumerable:!0});La.prototype.computeIrradiance=function(a,b,c,e){if(!d.Components.IrradianceCache)throw"cannot compute, no LS.Components.IrradianceCache component found";a=a||vec3.create();var g=d.Components.IrradianceCache.capture_cubemap_size,
f={type:gl.FLOAT,texture_type:gl.TEXTURE_CUBE_MAP,format:gl.RGB},h=new GL.Texture(d.Components.IrradianceCache.final_cubemap_size,d.Components.IrradianceCache.final_cubemap_size,f),g=new GL.Texture(g,g,f);d.Components.IrradianceCache.captureIrradiance(a,h,render_settings,b||0.1,c||1E3,e||[0,0,0,1],!0,g);this._irradiance=d.Components.IrradianceCache.computeSH(h);console.log("IR factor",this._irradiance)};La.prototype.clearIrradiance=function(){this._irradiance=null};La.icon="mini-icon-bg.png";La.DEFAULT_AMBIENT_COLOR=
vec3.fromValues(0.2,0.2,0.2);La.prototype.onAddedToScene=function(a){a.info=this};La.prototype.onRemovedFromScene=function(a){};La.prototype.getResources=function(a){for(var b in this._textures)"string"==typeof this._textures[b]&&(a[this._textures[b]]=GL.Texture);return a};La.prototype.getPropertiesInfo=function(){return{ambient_color:"color","textures/environment":"texture",render_settings:"RenderSettings"}};La.prototype.setProperty=function(a,b){if("textures/"==a.substr(0,9)&&(!b||b.constructor===
String||b.constructor===GL.Texture))return this._textures[a.substr(9)]=b,!0};La.prototype.getPropertyInfoFromPath=function(a){if("textures"==a[0]){if(1==a.length)return{node:this._root,target:this._textures,type:"object"};a=a[1];return{node:this._root,target:this._textures,name:a,value:this._textures[a]||null,type:"texture"}}};La.prototype.setPropertyValueFromPath=function(a,b,c){c=c||0;a.length<c+1||"textures"==a[c]&&(this._textures[a[c+1]]=b)};La.prototype.onResourceRenamed=function(a,b,c){for(var e in this._textures)this._textures[e]==
a&&(this._textures[e]=b)};d.registerComponent(La);d.GlobalInfo=La;"undefined"!=typeof LGraphTexture&&(LGraphTexture.getTexturesContainer=function(){return d.ResourcesManager.textures},LGraphTexture.storeTexture=function(a,b){return d.ResourcesManager.registerResource(a,b)},LGraphTexture.loadTexture=d.ResourcesManager.load.bind(d.ResourcesManager),LiteGraph.allow_scripts=d.allow_scripts);"undefined"!=typeof LGAudio&&(LGAudio.onProcessAudioURL=function(a){return d.RM.getFullURL(a)});"undefined"!=typeof LiteGraph&&
(LiteGraph.onNodeTypeReplaced=function(a,b,c){a=d.GlobalScene.findNodeComponents(d.Components.GraphComponent);a=a.concat(d.GlobalScene.findNodeComponents(d.Components.FXGraphComponent));for(b=0;b<a.length;++b)a[b].graph.checkNodeTypes()});ga["@on_event"]={type:"enum",values:["start","render","beforeRenderScene","update","trigger"]};ga["@filename"]={type:"resource",data_type:"graph"};Object.defineProperty(ga.prototype,"graph",{enumerable:!1,get:function(){return this._graph},set:function(a){console.error("graph cannot be set manually")}});
Object.defineProperty(ga.prototype,"filename",{enumerable:!1,get:function(){return this._filename},set:function(a){this._filename!=a&&(a&&(a=d.ResourcesManager.cleanFullpath(a)),this.from_file=!0,this._filename=a,this._loading=!1,this._graphcode=null,this.processGraph())}});Object.defineProperty(ga.prototype,"graphcode",{enumerable:!1,get:function(){return this._graphcode},set:function(a){this._loading=!1;this._graphcode=a;this.from_file=!0;this._filename=this._graphcode?this._graphcode.fullpath||
this._graphcode.filename:null;this._graph_properties=this.serializeProperties();this.processGraph()}});ga.icon="mini-icon-graph.png";ga.prototype.configure=function(a){this._graph_version=-1;a.uid&&(this.uid=a.uid);null!=a.enabled&&(this.enabled=!!a.enabled);a.title&&(this.title=String(a.title));if(a.from_file)this.from_file=!0,this.filename=a.filename,a.graph_properties&&(this._loading?this._graph_properties=a.graph_properties:this.configureProperties(a.graph_properties));else if(a.graph_data)if(this.from_file=
!1,d.catch_exceptions)try{var b=JSON.parse(a.graph_data);!0==this._graph.configure(b)&&(d.GlobalScene.has_errors=!0)}catch(c){console.error("Error configuring Graph data: "+c)}else b=JSON.parse(a.graph_data),!0==this._graph.configure(b)&&(d.GlobalScene.has_errors=!0);a.on_event&&(this.on_event=a.on_event);null!=a.force_redraw&&(this.force_redraw=a.force_redraw)};ga.prototype.serialize=function(){return{object_class:"GraphComponent",uid:this.uid,title:this.title,enabled:this.enabled,from_file:this.from_file,
force_redraw:this.force_redraw,filename:this._filename,graph_properties:this.from_file?this.serializeProperties():null,graph_data:this.from_file?null:JSON.stringify(this._graph.serialize()),on_event:this.on_event}};ga.prototype.getResources=function(a){this._filename&&(a[this._filename]=!0);this._graph.sendEventToAllNodes("getResources",a);return a};ga.prototype.onAddedToNode=function(a){this._graph._scenenode=a;this._default_node&&(this._default_node.properties.node_id=a.uid)};ga.prototype.onRemovedFromNode=
function(a){this._graph._scenenode=null};ga.prototype.onAddedToScene=function(a){this._graph._scene=a;LEvent.bind(a,"init",this.onSceneEvent,this);LEvent.bind(a,"start",this.onSceneEvent,this);LEvent.bind(a,"pause",this.onSceneEvent,this);LEvent.bind(a,"unpause",this.onSceneEvent,this);LEvent.bind(a,"finish",this.onSceneEvent,this);LEvent.bind(a,"beforeRenderMainPass",this.onSceneEvent,this);LEvent.bind(a,"beforeRenderScene",this.onSceneEvent,this);LEvent.bind(a,"update",this.onSceneEvent,this);LEvent.bind(a,
"renderGUI",this.onRenderGUI,this)};ga.prototype.onRemovedFromScene=function(a){this._graph._scene=null;LEvent.unbind(a,"init",this.onSceneEvent,this);LEvent.unbind(a,"start",this.onSceneEvent,this);LEvent.unbind(a,"pause",this.onSceneEvent,this);LEvent.unbind(a,"unpause",this.onSceneEvent,this);LEvent.unbind(a,"finish",this.onSceneEvent,this);LEvent.unbind(a,"beforeRenderMainPass",this.onSceneEvent,this);LEvent.unbind(a,"beforeRenderScene",this.onSceneEvent,this);LEvent.unbind(a,"update",this.onSceneEvent,
this);LEvent.unbind(a,"renderGUI",this.onRenderGUI,this)};ga.prototype.onResourceRenamed=function(a,b,c){a==this._filename&&(this._filename=b);this._graph.sendEventToAllNodes("onResourceRenamed",[a,b,c])};ga.prototype.onRenderGUI=function(a,b){this.enabled&&this._graph.sendEventToAllNodes("onRenderGUI",b)};ga.prototype.onSceneEvent=function(a,b){"beforeRenderMainPass"==a&&(a="render");"init"==a?this._graph.sendEventToAllNodes("onInit"):"start"==a?(this._graph.sendEventToAllNodes("onStart"),this._graph.status=
LGraph.STATUS_RUNNING):"pause"==a?(this._graph.sendEventToAllNodes("onPause"),this._graph.status=LGraph.STATUS_RUNNING):"unpause"==a?(this._graph.sendEventToAllNodes("onUnpause"),this._graph.status=LGraph.STATUS_RUNNING):"finish"==a&&(this._graph.sendEventToAllNodes("onStop"),this._graph.status=LGraph.STATUS_STOPPED);this.on_event==a&&this.runGraph()};ga.prototype.trigger=function(a){"trigger"==this.on_event&&this.runGraph()};ga.prototype.runGraph=function(){this._root._in_tree&&this.enabled&&(!this.from_file||
this._graphcode)&&(this._graph.runStep(1,d.catch_exceptions),this.force_redraw&&this._root.scene.requestFrame())};ga.prototype.processGraph=function(a,b){if(this.from_file){var c=this;(this._graphcode=d.ResourcesManager.getResource(this._filename))||this._loading?(this._graph.configure(this._graphcode.data),this._graph_properties&&(this.configureProperties(this._graph_properties),this._graph_properties=null),this._graph_version=this._graphcode._version):(this._loading=!0,d.ResourcesManager.load(this._filename,
null,function(e,d){this._loading=!1;d==c.filename&&(c.processGraph(a),b&&b(c))}))}};ga.prototype.getResources=function(a){a[this._filename]=!0;this._graph.sendEventToAllNodes("getResources",a);return a};ga.prototype.serializeProperties=function(){var a={},b=this._graph.findNodesByType("scene/global");if(!b.length)return a;for(var c=0;c<b.length;++c){var e=b[c];a[e.id]=e.properties.value}return a};ga.prototype.configureProperties=function(a){var b=this._graph.findNodesByType("scene/global");if(!b.length)return a;
for(var c=0;c<b.length;++c){var e=b[c];void 0!==a[e.id]&&(e.properties.value=a[e.id])}};ga.prototype.getPropertyValue=function(a){var b=this._graph.findNodesByType("scene/global");if(!b.length)return null;for(var c=0;c<b.length;++c){var e=b[c];if(e.properties.name==a)return e.properties.value}};ga.prototype.setPropertyValue=function(a,b){var c=this._graph.findNodesByType("scene/global");if(c.length)for(var e=0;e<c.length;++e){var d=c[e];if(d.properties.name==a)return d.properties.value&&d.properties.value.set?
d.properties.value.set(b):d.properties.value=b,!0}};ga.prototype.getComponentTitle=function(){return this.title};d.registerComponent(ga);ca.icon="mini-icon-graph.png";ca.buffer_size=[1024,512];Object.defineProperty(ca.prototype,"graph",{enumerable:!1,get:function(){return this._graph},set:function(a){console.error("graph cannot be set manually")}});Object.defineProperty(ca.prototype,"render_node",{enumerable:!1,get:function(){return this._graph_frame_node},set:function(a){console.error("render_node cannot be set manually")}});
Object.defineProperty(ca.prototype,"viewport_node",{enumerable:!1,get:function(){return this._graph_viewport_node},set:function(a){console.error("viewport_node cannot be set manually")}});ca.prototype.configure=function(a){if(this._graph&&a.graph_data&&(this.uid=a.uid,this.enabled=!!a.enabled,a.title&&(this.title=a.title),this.use_antialiasing=!!a.use_antialiasing,this.use_node_camera=!!a.use_node_camera,a.frame&&this.frame.configure(a.frame),a=JSON.parse(a.graph_data),!0==this._graph.configure(a)&&
(d.GlobalScene.has_error=!0),this._graph_frame_node=this._graph.findNodesByTitle("Rendered Frame")[0],this._graph_viewport_node=this._graph.findNodesByType("texture/toviewport")[0],!this._graph_frame_node)){console.log("CONVERTING LEGACY DATA TO NEW FORMAT");this._graph_frame_node=LiteGraph.createNode("scene/frame","Rendered Frame");this._graph_frame_node.ignore_remove=!0;this._graph_frame_node.ignore_rename=!0;this._graph.add(this._graph_frame_node);a=["Color Buffer","Depth Buffer","Extra Buffer"];
for(var b=0;b<a.length;++b){var c=this._graph.findNodesByTitle(a[b])[0];if(c){var e=c.getOutputInfo(0);if(e.links){var e=e.links.concat(),g;for(g in e){var f=this._graph.links[e[g]];f&&this._graph_frame_node.connect(b,f.target_id,f.target_slot)}this._graph.remove(c)}}}}};ca.prototype.serialize=function(){return{object_class:"FXGraphComponent",uid:this.uid,enabled:this.enabled,title:this.title,use_antialiasing:this.use_antialiasing,frame:this.frame.serialize(),use_node_camera:this.use_node_camera,
graph_data:this._graph?JSON.stringify(this._graph.serialize()):null}};ca.prototype.getResources=function(a){if(this._graph)return this._graph.sendEventToAllNodes("getResources",a),a};ca.prototype.getPropertyValue=function(a){var b=this._graph.findNodesByType("scene/global");if(b.length)for(var c=0;c<b.length;++c){var e=b[c];if(e.properties.name==a)return e.properties.value}};ca.prototype.setPropertyValue=function(a,b){var c=this._graph.findNodesByType("scene/global");if(c.length)for(var e=0;e<c.length;++e){var d=
c[e];if(d.properties.name==a)return d.properties.value&&d.properties.value.set?d.properties.value.set(b):d.properties.value=b,!0}};ca.prototype.onRenderGUI=ga.prototype.onRenderGUI;ca.prototype.onResourceRenamed=function(a,b,c){this._graph&&this._graph.sendEventToAllNodes("onResourceRenamed",[a,b,c])};ca.prototype.onAddedToNode=function(a){this._graph&&(this._graph._scenenode=a)};ca.prototype.onRemovedFromNode=function(a){this._graph&&(this._graph._scenenode=null)};ca.prototype.onAddedToScene=function(a){LEvent.bind(a,
"renderGUI",this.onRenderGUI,this)};ca.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"renderGUI",this.onRenderGUI,this)};ca.prototype.onAddedToScene=function(a){this._graph&&(this._graph._scene=a,LEvent.bind(a,"beforeRender",this.onBeforeRender,this),LEvent.bind(a,"enableFrameContext",this.onEnableContext,this),LEvent.bind(a,"showFrameContext",this.onAfterRender,this))};ca.prototype.onRemovedFromScene=function(a){this._graph&&(this._graph._scene=null,LEvent.unbind(a,"beforeRender",this.onBeforeRender,
this),LEvent.unbind(a,"enableFrameContext",this.onEnableContext,this),LEvent.unbind(a,"showFrameContext",this.onAfterRender,this),d.ResourcesManager.unregisterResource(":color_"+this.uid),d.ResourcesManager.unregisterResource(":depth_"+this.uid),d.ResourcesManager.unregisterResource(":extra_"+this.uid))};ca.prototype.onBeforeRender=function(a,b){this.enabled&&this._graph&&this._graph.sendEventToAllNodes("onPreRenderExecute")};ca.prototype.onEnableContext=function(a,b){this._last_camera=d.Renderer._main_camera;
if(this.enabled)if(this.use_node_camera){var c=this._root.camera;c&&c!=this._binded_camera&&(this._binded_camera&&LEvent.unbindAll(this._binded_camera,this),LEvent.bind(c,"enableFrameContext",this.enableCameraFBO,this),LEvent.bind(c,"showFrameContext",this.showCameraFBO,this));this._binded_camera=c}else this._binded_camera&&(LEvent.unbindAll(this._binded_camera,this),this._binded_camera=null),this.enableGlobalFBO(b);else this._binded_camera&&(LEvent.unbindAll(this._binded_camera,this),this._binded_camera=
null)};ca.prototype.onAfterRender=function(a,b){this.enabled&&(this.use_node_camera||this.showFBO())};ca.prototype.enableCameraFBO=function(a,b){if(this.enabled){var c=this._viewport=this._binded_camera.getLocalViewport(null,this._viewport);this.frame.enable(b,c);b.ignore_viewports=!0}};ca.prototype.showCameraFBO=function(a,b){this.enabled&&(b.ignore_viewports=!1,this.showFBO())};ca.prototype.enableGlobalFBO=function(a){this.enabled&&(this.frame.enable(a,null,d.Renderer._main_camera),this._graph&&
this._graph.sendEventToAllNodes("onPreRenderExecute"))};ca.prototype.showFBO=function(){if(this.enabled){this.frame.disable();d.ResourcesManager.textures[":color_"+this.uid]=this.frame._color_texture;d.ResourcesManager.textures[":depth_"+this.uid]=this.frame._depth_texture;if(this.frame.num_extra_textures)for(var a=0;a<this.frame.num_extra_textures;++a)d.ResourcesManager.textures[":extra"+a+"_"+this.uid]=this.frame._textures[a+1];this.use_node_camera&&this._viewport?(gl.setViewport(this._viewport),
this.applyGraph(),gl.setViewport(this.frame._fbo._old_viewport)):this.applyGraph()}};ca.prototype.applyGraph=function(){this._graph&&(this._graph_frame_node||(this._graph_frame_node=this._graph.findNodesByTitle("Rendered Frame")[0]),this._graph_frame_node._color_texture=":color_"+this.uid,this._graph_frame_node._depth_texture=":depth_"+this.uid,this._graph_frame_node._extra_texture=":extra0_"+this.uid,this._graph_frame_node._camera=this._last_camera,this._graph_frame_node._extra_texture=":extra0_"+
this.uid,this._graph_viewport_node&&(this._graph_viewport_node.properties.filter=this.frame.filter_texture,this._graph_viewport_node.properties.antialiasing=this.use_antialiasing),this._graph.runStep(1,d.catch_exceptions))};ca.prototype.getComponentTitle=ga.prototype.getComponentTitle;d.registerComponent(ca);(function(){function a(a){this.enabled=!0;this.value=0;this.delta=0.01;this.min_value=this.steps=0;this.max_value=1;this.min_angle=-120;this.max_angle=120;this.axis=vec3.fromValues(0,0,1);this._dragging=
!1;a&&this.configure(a)}a.icon="mini-icon-knob.png";a.prototype.onAddedToScene=function(a){LEvent.bind(a,"mousedown",this.onMouse,this);LEvent.bind(a,"mouseup",this.onMouse,this);LEvent.bind(a,"mousemove",this.onMouse,this);this.updateKnob()};a.prototype.onRemovedFromScene=function(a){LEvent.unbindAll(a,this)};a.prototype.updateKnob=function(){this._root&&this.enabled&&(quat.setAxisAngle(this._root.transform._rotation,this.axis,(this.min_angle+this.value/(this.max_value-this.min_value)*(this.max_angle-
this.min_angle))*DEG2RAD),this._root.transform.mustUpdate=!0)};a.prototype.onMouse=function(a,c){if(this.enabled)if("mousedown"==a){if(this._root&&this._root._instances&&this._root._instances.length){var e=this._root._instances[0],g=d.Renderer.getCameraAtPosition(c.canvasx,c.canvasy);g&&(g=g.getRay(c.canvasx,c.canvasy))&&(this._dragging=geo.testRayBBox(g.origin,g.direction,e.aabb))}}else if("mouseup"==a)this._dragging=!1;else if(c.dragging&&this._dragging)return this.value-=c.deltay*this.delta,this.value>
this.max_value?this.value=this.max_value:this.value<this.min_value&&(this.value=this.min_value),this.updateKnob(),LEvent.trigger(this,"change",this.value),this._root&&LEvent.trigger(this._root,"knobChange",this.value),!1};d.registerComponent(a)})();Object.defineProperty(Lb.prototype,"pos",{get:function(){return this._pos},set:function(a){this._pos.set(a)},enumerable:!0});Object.defineProperty(Lb.prototype,"vel",{get:function(){return this._vel},set:function(a){this._vel.set(a)},enumerable:!0});W.BOX_EMISSOR=
1;W.SPHERE_EMISSOR=2;W.MESH_EMISSOR=3;W.CUSTOM_EMISSOR=10;W["@emissor_type"]={type:"enum",values:{Box:W.BOX_EMISSOR,Sphere:W.SPHERE_EMISSOR,Mesh:W.MESH_EMISSOR,Custom:W.CUSTOM_EMISSOR}};W.icon="mini-icon-particles.png";Object.defineProperty(W.prototype,"particle_start_color",{get:function(){return this._particle_start_color},set:function(a){a&&this._particle_start_color.set(a)},enumerable:!0});Object.defineProperty(W.prototype,"particle_end_color",{get:function(){return this._particle_end_color},
set:function(a){a&&this._particle_end_color.set(a)},enumerable:!0});W.prototype.onAddedToScene=function(a){LEvent.bind(a,"update",this.onUpdate,this);LEvent.bind(a,"start",this.onStart,this);LEvent.bind(a,"collectRenderInstances",this.onCollectInstances,this);LEvent.bind(a,"afterCameraEnabled",this.onAfterCamera,this)};W.prototype.onRemovedFromScene=function(a){LEvent.unbindAll(a,this)};W.prototype.getResources=function(a){this.emissor_mesh&&(a[this.emissor_mesh]=Mesh);this.texture&&(a[this.texture]=
Texture)};W.prototype.onResourceRenamed=function(a,b,c){this.emissor_mesh==a&&(this.emissor_mesh=b);this.texture==a&&(this.texture=b)};W.prototype.onAfterCamera=function(a,b){this.enabled&&this.align_always&&this.updateMesh(b)};W.prototype.createParticle=function(a){a=a||new Lb;switch(this.emissor_type){case W.BOX_EMISSOR:a._pos.set([this.emissor_size[0]*(Math.random()-0.5),this.emissor_size[1]*(Math.random()-0.5),this.emissor_size[2]*(Math.random()-0.5)]);break;case W.SPHERE_EMISSOR:var b=2*Math.PI*
Math.random(),c=Math.acos(2*Math.random()-1);a._pos.set([Math.sin(c)*Math.cos(b),Math.sin(c)*Math.sin(b),Math.cos(c)]);vec3.multiply(a.pos,a.pos,this.emissor_size);break;case W.MESH_EMISSOR:(b=this.emissor_mesh)&&b.constructor===String&&(b=d.ResourcesManager.getMesh(this.emissor_mesh)),b&&b.getBuffer("vertices")?(b=b.getBuffer("vertices").data,c=3*Math.floor(Math.random()*b.length/3),a._pos.set([b[c]+0.001*Math.random(),b[c+1]+0.001*Math.random(),b[c+2]+0.001*Math.random()])):a._pos.set([0,0,0])}a._vel.set([Math.random()-
0.5,Math.random()-0.5,Math.random()-0.5]);a.life=this.particle_life;a.id=this._last_id;a.angle=0;a.size=1;a.rot=this.particle_rotation+0.25*this.particle_rotation*Math.random();this._last_id+=1;this.independent_color&&(a.c=vec3.clone(this.particle_start_color));vec3.scale(a._vel,a._vel,this.particle_speed);if(this.emissor_type==W.CUSTOM_EMISSOR&&this.onCreateParticle)this.onCreateParticle(a,this);this.follow_emitter||vec3.add(a._pos,a._pos,this._emissor_pos);return a};W.prototype.onStart=function(a){if(this.enabled&&
!(0>=this.warm_up_time)){a=1/30;for(var b=0;b<this.warm_up_time;b+=a)this.onUpdate(null,a,!0)}};W.prototype.onUpdate=function(a,b,c){if(this.enabled){if(!this._root.scene)throw"update without scene? impossible";this._root.transform&&this._root.transform.getGlobalPosition(this._emissor_pos);0>this.emissor_rate&&(this.emissor_rate=0);if(!this.stop_update){var e=vec3.clone(this.physics_gravity),g=this.physics_friction;a=[];for(var f=vec3.create(),h=0,k=this._particles.length;h<k;++h){var l=this._particles[h];
vec3.copy(f,l._vel);vec3.add(f,e,f);vec3.scale(f,f,b);g&&(f[0]-=f[0]*g,f[1]-=f[1]*g,f[2]-=f[2]*g);vec3.add(l._pos,f,l._pos);l.angle+=l.rot*b;l.life-=b;if(this.onUpdateParticle)this.onUpdateParticle(l,b,this);0<l.life&&a.push(l)}if(0!=this.emissor_rate)for(b=(b+this._remining_dt)*this.emissor_rate,this._remining_dt=b%1/this.emissor_rate,b<<=0,b>this.max_particles&&(b=this.max_particles),h=0;h<b;h++)l=this.createParticle(),a.length<this.max_particles&&a.push(l);this._particles=a}this.align_always||
c||(this.updateMesh(d.Renderer._current_camera),this._root.scene.requestFrame());LEvent.trigger(this._root.scene,"change")}};W.prototype.createMesh=function(){if(this._mesh_maxparticles!=this.max_particles){this._vertices=new Float32Array(18*this.max_particles);this._coords=new Float32Array(12*this.max_particles);this._colors=new Float32Array(24*this.max_particles);this._extra2=new Float32Array(2*this.max_particles);for(var a=[1,1,0,1,1,0,0,1,0,0,1,0],b=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1],c=0;c<this.max_particles;c++)this._coords.set(a,12*c),this._colors.set(b,24*c),this._extra2[2*c]=1,this._extra2[2*c+1]=c;this._computed_grid_size=1;this._mesh=new GL.Mesh;this._mesh.addBuffers({vertices:this._vertices,coords:this._coords,colors:this._colors,extra2:this._extra2},null,gl.STREAM_DRAW);this._mesh_maxparticles=this.max_particles}};W._tmp_quat=quat.create();W.prototype.updateMesh=function(a){if(a){this._mesh_maxparticles!=this.max_particles&&this.createMesh();var b=a.getEye(),c=
this._min_particle_size,e=a.getLocalVector([0,0,1]),g=a.getLocalVector([1,0,0]),f=a.getLocalVector([0,1,0]);a=vec3.create();var h=vec3.fromValues(-1,0,-1),k=vec3.fromValues(1,0,-1),l=vec3.fromValues(-1,0,1),n=vec3.fromValues(1,0,1);this.align_with_camera&&(vec3.subtract(h,f,g),vec3.add(k,f,g),vec3.scale(l,k,-1),vec3.scale(n,h,-1));var g=vec3.create(),f=vec3.create(),p=vec3.create(),m=vec3.create(),q=this._particles;if(this.sort_in_z){for(var q=this._particles.concat(),s=geo.createPlane(b,e),t=1/Math.sqrt(s[0]*
s[0]+s[1]*s[1]+s[2]*s[2]),b=0;b<q.length;++b)q[b]._dist=Math.abs(vec3.dot(q[b]._pos,s)+s[3])*t;q.sort(function(a,b){return a._dist<b._dist?1:a._dist>b._dist?-1:0});this._particles=q}0==this.particle_life&&(this.particle_life=1E-4);var s=new Float32Array([1,1,1,1]),t=this._particle_start_color,u=this._particle_end_color,H=!1;if(this._computed_grid_size!=this.texture_grid_size||1<this.texture_grid_size||this.point_particles)H=!0,this._computed_grid_size=this.texture_grid_size;for(var G=1/this.texture_grid_size,
r=0,M=0,v=this.texture_grid_size<<2,w=this.animated_texture,y=this.loop_animation,x=this._root.scene.getTime()*this.animation_fps,B=new Float32Array(60*this.particle_life<<0),A=new Float32Array(60*this.particle_life<<0),z=this.particle_size,C=1/(60*this.particle_life),b=0;b<B.length;b+=1)B[b]=d.getCurveValueAt(this.particle_opacity_curve,0,1,0,b*C),A[b]=d.getCurveValueAt(this.particle_size_curve,0,1,0,b*C);for(var C=this.point_particles,D=this._vertices.length,E=this._vertices,F=this._colors,I=this._extra2,
J=this._coords,L=W._tmp_quat,N=r=b=0,O=q.length;N<O;++N)if(M=q[N],!(0>=M.life)){var r=1-M.life/this.particle_life,K=B[r*B.length<<0];this.independent_color&&M.c?vec3.clone(s,M.c):vec3.lerp(s,t,u,r);this.premultiplied_alpha?(vec3.scale(s,s,K),s[3]=1):s[3]=K;if(!(0.001>K||(K=M.size*A[r*A.length<<0],Math.abs(K*z)<c)))if(C){if(E.set(M._pos,3*b),F.set(s,4*b),H&&(r=(w?(y?x:r)*v<<0:M.id)%v,r*=G,M=1-(r<<0)*G-G,r%=1,J[2*b]=r,J[2*b+1]=M),I[2*b]=K,I[2*b+1]=b,++b,3*b>=D)break}else if(K*=z,vec3.scale(p,l,K),vec3.scale(f,
k,K),vec3.scale(g,h,K),vec3.scale(m,n,K),0!=M.angle&&(quat.setAxisAngle(L,e,M.angle*DEG2RAD),vec3.transformQuat(p,p,L),vec3.transformQuat(f,f,L),vec3.transformQuat(g,g,L),vec3.transformQuat(m,m,L)),vec3.add(a,M._pos,f),E.set(a,18*b),vec3.add(a,M._pos,g),E.set(a,18*b+3),vec3.add(a,M._pos,m),E.set(a,18*b+6),vec3.add(a,M._pos,g),E.set(a,18*b+9),vec3.add(a,M._pos,p),E.set(a,18*b+12),vec3.add(a,M._pos,m),E.set(a,18*b+15),F.set(s,24*b),F.set(s,24*b+4),F.set(s,24*b+8),F.set(s,24*b+12),F.set(s,24*b+16),F.set(s,
24*b+20),H&&(r=(w?(y?x:r)*v<<0:M.id)%v,r*=G,M=1-(r<<0)*G-G,r%=1,J.set([r+G,M+G,r,M+G,r+G,M,r,M+G,r,M,r+G,M],12*b)),++b,18*b>=D)break}this._visible_particles=b;this._mesh.vertexBuffers.vertices.data=this._vertices;this._mesh.vertexBuffers.vertices.upload(gl.STREAM_DRAW);this._mesh.vertexBuffers.colors.data=this._colors;this._mesh.vertexBuffers.colors.upload(gl.STREAM_DRAW);this._mesh.vertexBuffers.extra2.data=this._extra2;this._mesh.vertexBuffers.extra2.upload(gl.STREAM_DRAW);H&&(this._mesh.vertexBuffers.coords.data=
this._coords,this._mesh.vertexBuffers.coords.upload(gl.STREAM_DRAW))}};W._identity=mat4.create();W.prototype.onCollectInstances=function(a,b,c){if(this._root&&this.enabled){this._material||(this._material=new d.StandardMaterial({shader_name:"lowglobal"}));this._material.opacity=this.opacity-0.01;this._material.setTexture("color",this.texture);this._material.blend_mode=this.additive_blending?d.Blend.ADD:d.Blend.ALPHA;this._material.constant_diffuse=!0;this._material.uvs_matrix[0]=this._material.uvs_matrix[4]=
1/this.texture_grid_size;this._material.flags.depth_write=!1;this._material.flags.ignore_lights=this.ignore_lights;if(!this._mesh)return null;a=this._render_instance;a||(this._render_instance=a=new d.RenderInstance(this._root,this));this.follow_emitter?mat4.translate(a.matrix,W._identity,this._root.transform._position):(mat4.copy(a.matrix,W._identity),this._root.transform&&this._root.transform.getGlobalPosition(a.center));c=this._root.material&&this.use_node_material?this._root.getMaterial():this._material;
mat4.multiplyVec3(a.center,a.matrix,vec3.create());a.setMaterial(c);this.point_particles?(a.setMesh(this._mesh,gl.POINTS),a.uniforms.u_point_size=this.particle_size,a.setRange(0,this._visible_particles)):(a.setMesh(this._mesh,gl.TRIANGLES),a.setRange(0,6*this._visible_particles),delete a.uniforms.u_point_size);a.use_bounding=!1;b.push(a)}};d.Particle=Lb;d.registerComponent(W);hb.icon="mini-icon-text.png";hb.CSS_classname="LS3D_label";hb.prototype.onAddedToScene=function(a){LEvent.bind(a,"renderGUI",
this.render,this)};hb.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"renderGUI",this.render,this);this.removeHTML()};hb.prototype.createHTML=function(){var a=document.createElement("div");a.innerHTML=this.text;var b=a.style;b.className=this.constructor.CSS_classname;b.position="absolute";b.top=0;b.left=0;b.fontSize="20px";b.padding="10px";b.color="white";b.minWidth="100px";b.pointerEvents="none";b.backgroundColor="rgba(0,0,0,0.5)";b.borderRadius="2px";d.getGUIElement().appendChild(a);this._element=
a};hb.prototype.removeHTML=function(){this._element&&(this._element.parentNode&&this._element.parentNode.removeChild(this._element),this._element=null)};hb.prototype.render=function(a,b){var c=this._root,e=d.Renderer._main_camera;if(e)if(c.transform.getGlobalPosition(this._world_pos),e.project(this._world_pos,null,this._screen_pos),this.use_html)this._element||this.createHTML(),this._element.innerHTML!=this.text&&(this._element.innerHTML=this.text),this._element.style.display=!1===c.flags.visible?
"none":"block",this.text?(c=this.constructor.CSS_classname+" "+this.className,this._element.className!=c&&(this._element.className=c),this._element.style.left=this._screen_pos[0].toFixed(0)+"px",this._element.style.top=gl.canvas.height-(this._screen_pos[1]|0)-10+"px"):this._element.style.display="none";else if(this._element&&this.removeHTML(),gl.start2D){c=this._screen_pos[0]+5;e=gl.canvas.height-this._screen_pos[1]+10;gl.start2D();gl.font="20px Arial";var g=gl.measureText(this.text);gl.fillStyle=
"black";gl.globalAlpha=0.5;gl.fillRect(c-5,e-20,g.width+10,26);gl.globalAlpha=1;gl.fillStyle="white";gl.fillText(this.text,c,e);gl.finish2D()}};d.registerComponent(hb);ha.icon="mini-icon-points.png";ha["@texture"]={widget:"texture"};ha["@color"]={widget:"color"};ha["@num_points"]={widget:"info"};ha["@size"]={type:"number",step:0.001,precision:3};ha.default_color=vec4.fromValues(1,1,1,1);Object.defineProperty(ha.prototype,"num_points",{set:function(a){},get:function(){return this._points.length},enumerable:!0});
ha.prototype.addPoint=function(a,b,c,e){var d=new Float32Array(10);d.set(a,0);b?d.set(b,3):d.set(ha.default_color,3);d[7]=void 0!==c?c:1;d[8]=void 0!=e?e:0;this._points.push(d);this._must_update=!0;return this._points.length-1};ha.prototype.clear=function(){this._points.length=0};ha.prototype.reset=ha.prototype.clear;ha.prototype.setPoint=function(a,b,c,e,d){if(a=this._points[a])b&&a.set(b,0),c&&a.set(c,3),void 0!==e&&(a[7]=e),void 0!==d&&(a[8]=d),this._must_update=!0};ha.prototype.setPointsFromMesh=
function(a){};ha.prototype.removePoint=function(a){this._points.splice(a,1);this._must_update=!0};ha.prototype.onAddedToNode=function(a){LEvent.bind(a,"collectRenderInstances",this.onCollectInstances,this)};ha.prototype.onRemovedFromNode=function(a){LEvent.unbind(a,"collectRenderInstances",this.onCollectInstances,this)};ha.prototype.getResources=function(a){this.mesh&&(a[this.emissor_mesh]=Mesh);this.texture&&(a[this.texture]=Texture)};ha.prototype.onResourceRenamed=function(a,b,c){this.mesh==a&&
(this.mesh=b);this.texture==a&&(this.texture=b)};ha.prototype.createMesh=function(){var a=this.max_points|0;if(this._mesh_max_points!=a){this._vertices=new Float32Array(3*a);this._colors=new Float32Array(4*a);this._extra2=new Float32Array(2*a);for(var b=0;b<a;b++)this._colors.set(ha.default_color,4*b),this._extra2[2*b]=1;this._mesh&&this._mesh.deleteBuffers();this._mesh=new GL.Mesh;this._mesh.addBuffers({vertices:this._vertices,colors:this._colors,extra2:this._extra2},null,gl.STREAM_DRAW);this._mesh_max_points=
a}};ha.prototype.updateMesh=function(a){this._mesh_max_points!=(this.max_points|0)&&this.createMesh();var b=this._points;if(this.sort_in_z&&a){var c=a.getEye();a=a.getFront();b=this._points.concat();c=geo.createPlane(c,a);a=Math.sqrt(c[0]*c[0]+c[1]*c[1]+c[2]*c[2]);for(var e=0;e<b.length;++e)b[e][9]=Math.abs(vec3.dot(b[e].subarray(0,3),c)+c[3])/a;b.sort(function(a,b){return a[9]<b[9]?1:a[9]>b[9]?-1:0})}e=0;c=this._vertices;a=this._colors;for(var e=this._extra2,d=this.premultiplied_alpha,f=0;f<b.length&&
!(3*f>=c.length);++f){var h=b[f];c.set(h.subarray(0,3),3*f);var k=h.subarray(3,7);d&&vec3.scale(k,k,k[3]);a.set(k,4*f);e.set(h.subarray(7,9),2*f)}this._mesh.vertexBuffers.vertices.data=c;this._mesh.vertexBuffers.vertices.upload();this._mesh.vertexBuffers.colors.data=a;this._mesh.vertexBuffers.colors.upload();this._mesh.vertexBuffers.extra2.data=e;this._mesh.vertexBuffers.extra2.upload()};ha._identity=mat4.create();ha.prototype.onCollectInstances=function(a,b,c){if(this._root&&0!=this._points.length&&
this.enabled){a=d.Renderer._current_camera;this._last_premultiply!==this.premultiplied_alpha&&(this._must_update=!0);this._must_update&&this.updateMesh(a);this._material||(this._material=new d.StandardMaterial({}),this._material.extra_macros={USE_POINT_CLOUD:"",USE_TEXTURED_POINTS:""});c=this._material;c.color.set(this.color);c.opacity=this.premultiplied_alpha?0.99:this.global_opacity-0.01;this._last_premultiply=this.premultiplied_alpha;c.setTexture(d.Material.COLOR,this.texture);c.blend_mode=this.additive_blending?
d.Blend.ADD:d.Blend.ALPHA;c.constant_diffuse=!0;if(!this._mesh)return null;a=this._render_instance;a||(this._render_instance=a=new d.RenderInstance(this._root,this));this.in_world_coordinates&&this._root.transform?a.matrix.set(this._root.transform._global_matrix):mat4.copy(a.matrix,ha._identity);c=this._root.material&&this.use_node_material?this._root.getMaterial():this._material;mat4.multiplyVec3(a.center,a.matrix,vec3.create());a.uniforms.u_point_size=this.size;a.setMaterial(c);a.setMesh(this._mesh,
gl.POINTS);c=this._points.length;c>this._vertices.length/3&&(c=this._vertices.length/3);a.setRange(0,c);b.push(a)}};ha.prototype.serialize=function(){var a=d.cloneObject(this);a.object_class="PointCloud";this.uid&&(a.uid=this.uid);if(this.serialize_points){for(var b=Array(this._points.length),c=0;c<this._points.length;c++)b[c]=typedArrayToArray(this._points[c]);a.points=b}return a};ha.prototype.configure=function(a){if(a){a.uid&&(this.uid=a.uid);if(a.points&&a.serialize_points){this._points=Array(a.points.length);
for(var b=0;b<a.points.length;b++)this._points[b]=new Float32Array(a.points[b]);a.points=null}d.cloneObject(a,this)}};d.registerComponent(ha);Ga.icon="mini-icon-lines.png";Ga["@color"]={widget:"color"};Ga["@lines"]={widget:"null"};Object.defineProperty(Ga.prototype,"lines",{set:function(a){this._lines=a},get:function(){return this._lines},enumerable:!0});Object.defineProperty(Ga.prototype,"num_lines",{set:function(a){},get:function(){return this._lines.length},enumerable:!0});Ga.prototype.clear=function(){this._lines.length=
0};Ga.prototype.reset=Ga.prototype.clear;Ga.prototype.addPoint=function(a,b){var c=null,e=null;this._lines.length?(e=this._lines[this._lines.length-1],c=new Float32Array(e.subarray(3,6)),e=new Float32Array(e.subarray(10,14))):(c=a,e=b);this.addLine(c,a,e,b)};Ga.prototype.addLine=function(a,b,c,e){var d=new Float32Array(14);d.set(a,0);d.set(b,3);c?d.set(c,6):d.set([1,1,1,1],6);e?d.set(e,10):c?d.set(c,10):d.set([1,1,1,1],10);this._lines.push(d);this._must_update=!0;return this._lines.length-1};Ga.prototype.setLine=
function(a,b,c,e,d){a=this._lines[a];b&&a.set(b,0);c&&a.set(c,3);e&&a.set(e,6);d&&a.set(d,10);this._must_update=!0};Ga.prototype.removeLine=function(a){this._lines.splice(a,1);this._must_update=!0};Ga.prototype.onAddedToScene=function(a){LEvent.bind(a,"afterRenderScene",this.onAfterRender,this)};Ga.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"afterRenderScene",this.onAfterRender,this)};Ga.prototype.createMesh=function(){this._mesh_max_lines!=this.max_lines&&(this._vertices=new Float32Array(6*
this.max_lines),this._colors=new Float32Array(8*this.max_lines),this._mesh=new GL.Mesh,this._mesh.addBuffers({vertices:this._vertices,colors:this._colors},null,gl.STREAM_DRAW),this._mesh_max_lines=this.max_lines)};Ga.prototype.updateMesh=function(){this._mesh_max_lines!=this.max_lines&&this.createMesh();for(var a=0,b=this._vertices,c=this._colors,e=this._lines,d=this._lines.length,f=b.length,a=0;a<d&&!(6*a>=f);++a){var h=e[a];b.set(h.subarray(0,6),6*a);c.set(h.subarray(6,14),8*a)}this._mesh.vertexBuffers.vertices.data=
b;this._mesh.vertexBuffers.vertices.upload();this._mesh.vertexBuffers.colors.data=c;this._mesh.vertexBuffers.colors.upload()};Ga.prototype.onAfterRender=function(a){this._root&&0!=this._lines.length&&this.enabled&&(this._must_update&&this.updateMesh(),d.Draw.renderMesh(this._mesh,GL.LINES,null,null,0,2*this._lines.length))};d.registerComponent(Ga);N.LOOP=1;N.PINGPONG=2;N.ONCE=3;N.PAUSED=4;N.MODES={loop:N.LOOP,pingpong:N.PINGPONG,once:N.ONCE,paused:N.PAUSED};N.properties_order=["animation","take"];
N["@animation"]={widget:"animation"};N["@root_node"]={type:"node_id"};N["@mode"]={type:"enum",values:N.MODES};N["@current_time"]={type:d.TYPES.NUMBER,min:0,units:"s"};N["@blend_time"]={type:d.TYPES.NUMBER,min:0,units:"s"};N["@take"]={type:"enum",values:function(){var a=this.instance.getAnimation();if(!a)return["default"];var a=a.takes,b=[],c;for(c in a)b.push(c);return b}};Object.defineProperty(N.prototype,"animation",{set:function(a){a!=this._animation&&(this._blend_animation=this._animation,this._animation=
a,this.blend_time&&this._root&&this._root.scene&&(this._use_blend_animation=!0,this._root.scene.frame!=this._blend_updated_frame&&(this._blend_current_time=this.current_time,this._blend_remaining_time=this.blend_time,this._blend_updated_frame=this._root.scene.frame)))},get:function(){return this._animation},enumerable:!0});Object.defineProperty(N.prototype,"take",{set:function(a){a!=this._take&&(this._blend_take=this._take,this._take=a,this.blend_time&&this._root&&this._root.scene&&(this._use_blend_animation=
!0,this._root.scene.frame!=this._blend_updated_frame&&(this._blend_current_time=this.current_time,this._blend_remaining_time=this.blend_time,this._blend_updated_frame=this._root.scene.frame)))},get:function(){return this._take},enumerable:!0});N.prototype.configure=function(a){a.play&&delete a.play;void 0!==a.enabled&&(this.enabled=!!a.enabled);a.range&&(this.range=a.range.concat());void 0!==a.mode&&(this.mode=a.mode);a.animation&&(this._animation=a.animation);a.take&&(this._take=a.take);null!=a.playback_speed&&
(this.playback_speed=parseFloat(a.playback_speed));void 0!==a.root_node&&(this.root_node=a.root_node);void 0!==a.playing&&(this.playing=a.playing);void 0!==a.blend_time&&(this.blend_time=a.blend_time)};N.icon="mini-icon-clock.png";N.prototype.onAddedToScene=function(a){LEvent.bind(a,"update",this.onUpdate,this)};N.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"update",this.onUpdate,this)};N.prototype.onUpdate=function(a,b){if(this.enabled&&this.playing&&(this.mode!=N.PAUSED&&(this.current_time+=
b*this.playback_speed),this.onUpdateAnimation(b),this._use_blend_animation))this.onUpdateBlendAnimation(b)};N.prototype.onUpdateAnimation=function(a){if(a=this.getAnimation())if(a=a.takes[this.take]){var b=this.current_time,c=0,e=a.duration,d=e;this.range&&(c=this.range[0],d=this.range[1],e=d-c);if(b>d)switch(this.mode){case N.ONCE:b=d;LEvent.trigger(this,"end_animation");this.playing=!1;break;case N.PINGPONG:b=0==(b/e|0)%2?this.current_time%e:e-this.current_time%e;break;case N.PINGPONG:b=d;break;
default:b=(this.current_time-c)%e+c,LEvent.trigger(this,"animation_loop")}else b<c&&(b=c);this.applyAnimation(a,b,this._last_time);this._last_time=b;(a=this._root.scene)&&a.requestFrame()}};N.prototype.onUpdateBlendAnimation=function(a){var b=this.getAnimation(this._blend_animation||this._animation||"");if(b&&(b=b.takes[this._blend_take||this._take||"default"])){this._blend_current_time+=a;this._blend_remaining_time-=a;0>=this._blend_remaining_time&&(this._use_blend_animation=!1);a=this._blend_current_time*
this.playback_speed;var c=0,e=b.duration,d=e;this.range&&(c=this.range[0],d=this.range[1],e=d-c);if(a>d)switch(this.mode){case N.ONCE:a=d;this._use_blend_animation=!1;break;case N.PINGPONG:a=0==(a/e|0)%2?this._blend_current_time%e:e-this._blend_current_time%e;break;case N.PINGPONG:a=d;break;default:a=(this._blend_current_time-c)%e+c}else a<c&&(a=c);this.applyAnimation(b,a,null,this._blend_remaining_time/this.blend_time);(b=this._root.scene)&&b.requestFrame()}};N.prototype.getAnimation=function(a){a=
void 0===a?this.animation:a;return a&&"@"!=a[0]?(a=d.ResourcesManager.getResource(a))&&a.constructor===d.Animation?a:null:this._root.scene.animation};N.prototype.getTake=function(a){var b=this.getAnimation();if(!b)return null;a=a||this.take;return(a=b.takes[a])?a:null};N.prototype.getDuration=function(){var a=this.getTake();return a?a.duration:-1};N.prototype.play=function(){this._root&&this._root.scene||console.error("cannot play an animation if the component doesnt belong to a node in a scene");
this.playing=!0;this.current_time=0;this.range&&(this.current_time=this.range[0]);this._last_time=this.current_time;LEvent.trigger(this,"start_animation")};N.prototype.pause=function(){this.playing=!1};N.prototype.stop=function(){this.playing=!1;this.current_time=0;this.range&&(this.current_time=this.range[0]);this._last_time=this.current_time};N.prototype.playRange=function(a,b){this.playing=!0;this._last_time=this.current_time=a;this.range=[a,b]};N.prototype.applyAnimation=function(a,b,c,e){void 0===
c&&(c=b);if(this._root){var d=null;this.root_node&&this._root.scene&&(d="@"==this.root_node?this._root:this._root.scene.getNode(this.root_node));a.applyTracks(b,c,void 0,d,this._root.scene,e,this.onPreApply,this.onApplySample)}};N.prototype._processSample=function(a,b,c,e){if(e=this._root.scene)if(a=e.getNode(a)){e=a.transform;switch(b){case "translate.X":e&&(e.position[0]=c);break;case "translate.Y":e&&(e.position[1]=c);break;case "translate.Z":e&&(e.position[2]=c);break;case "matrix":e&&e.fromMatrix(c)}a.transform&&
a.transform.updateMatrix()}};N.prototype.getResources=function(a){this.animation&&(a[this.animation]=d.Animation)};N.prototype.onResourceRenamed=function(a,b,c){this.animation==a&&(this.animation=b)};N.prototype.getEvents=function(){return{start_animation:"event",end_animation:"event"}};N.prototype.getActions=function(a){a=a||{};a.play="function";a.pause="function";a.stop="function";return a};d.registerComponent(N);T.LOOP=1;T.PINGPONG=2;T.ONCE=3;T.PAUSED=4;T.MODES={loop:T.LOOP,pingpong:T.PINGPONG,
once:T.ONCE,paused:T.PAUSED};T["@animation"]={widget:"resource",resource_classname:"SkeletalAnimation"};T["@mode"]={type:"enum",values:T.MODES};T["@current_time"]={type:d.TYPES.NUMBER,min:0,units:"s"};T.prototype.configure=function(a){void 0!==a.enabled&&(this.enabled=!!a.enabled);a.range&&(this.range=a.range.concat());void 0!==a.mode&&(this.mode=a.mode);a.animation&&(this.animation=a.animation);null!=a.playback_speed&&(this.playback_speed=parseFloat(a.playback_speed));null!=a.current_time&&(this.current_time=
parseFloat(a.current_time));void 0!==a.playing&&(this.playing=a.playing)};T.icon="mini-icon-clock.png";T.prototype.onAddedToScene=function(a){LEvent.bind(a,"update",this.onUpdate,this)};T.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"update",this.onUpdate,this)};T.prototype.onUpdate=function(a,b){this.enabled&&this.playing&&(this.mode!=T.PAUSED&&(this.current_time+=b*this.playback_speed),this.onUpdateAnimation(b))};T.prototype.onUpdateAnimation=function(a){var b=this.getAnimation();if(b&&
b.constructor==d.SkeletalAnimation){a=this.current_time;var c=0,e=b=b.duration;this.range&&(c=this.range[0],e=this.range[1],b=e-c);if(a>e)switch(this.mode){case T.ONCE:a=e;LEvent.trigger(this,"end_animation");this.playing=!1;break;case T.PINGPONG:a=0==(a/b|0)%2?this.current_time%b:b-this.current_time%b;break;case T.PINGPONG:a=e;break;default:a=(this.current_time-c)%b+c,LEvent.trigger(this,"animation_loop")}else a<c&&(a=c);this.applyAnimation(a);(a=this._root.scene)&&a.requestFrame()}};T.prototype.getAnimation=
function(a){a=void 0===a?this.animation:a;return(a=d.ResourcesManager.getResource(a))&&a.constructor===d.SkeletalAnimation?a:null};T.prototype.getDuration=function(){var a=this.getAnimation();return a?a.duration:-1};T.prototype.play=function(){this._root&&this._root.scene||console.error("cannot play an animation if the component doesnt belong to a node in a scene");this.playing=!0;this.current_time=0;this.range&&(this.current_time=this.range[0]);LEvent.trigger(this,"start_animation")};T.prototype.pause=
function(){this.playing=!1};T.prototype.stop=function(){this.playing=!1;this.current_time=0;this.range&&(this.current_time=this.range[0])};T.prototype.playRange=function(a,b){this.playing=!0;this.current_time=a;this.range=[a,b]};T.prototype.applyAnimation=function(a){if(this._root){var b=this.getAnimation();b&&(b.assignTime(a,!0,this.interpolate),this._skeleton.copyFrom(b.skeleton),a=this._root.getComponent(d.Components.SkinDeformer))&&(a._skeleton=this._skeleton)}};T.prototype.getResources=function(a){this.animation&&
(a[this.animation]=d.SkeletalAnimation)};T.prototype.onResourceRenamed=function(a,b,c){this.animation==a&&(this.animation=b)};T.prototype.getEvents=function(){return{start_animation:"event",end_animation:"event"}};T.prototype.getActions=function(a){a=a||{};a.play="function";a.pause="function";a.stop="function";return a};T.prototype.getPropertiesInfo=function(){return{enabled:"boolean",current_time:"number",mode:"number",playing:"boolean",playback_speed:"number",skeleton:"skeleton"}};d.registerComponent(T);
ib.icon="mini-icon-reflector.png";ib["@texture_size"]={type:"enum",values:["viewport",64,128,256,512,1024,2048]};ib["@layers"]={type:"layers"};ib.prototype.onAddedToScene=function(a){LEvent.bind(a,d.EVENT.RENDER_REFLECTIONS,this.onRenderReflection,this);LEvent.bind(a,d.EVENT.AFTER_CAMERA_ENABLED,this.onCameraEnabled,this)};ib.prototype.onRemovedFromScene=function(a){LEvent.unbindAll(a,this);for(var b in this._textures)d.ResourcesManager.unregisterResource(":reflection_"+b);this._textures={}};ib.prototype.onRenderReflection=
function(a,b){if(this.enabled&&this._root&&this._root.visible){var c=this._root.scene;if(c&&(this.refresh_rate<<=0,0!=c._frame&&0==c._frame%this.refresh_rate||!this._rt)){var e=c=parseInt(this.texture_size),g=c,f=this._root.flags.visible;this._root.visible=!this.ignore_this_mesh;var h=b.layers;b.layers=this.layers;var k=d.Renderer._visible_cameras;d.Renderer.clearSamplers();for(var l=0;l<k.length;l++){var n=k[l];if(this.skip_if_node_not_visible){if(!this._root._instances.length)continue;for(var p=
!1,m=0;m<this._root._instances.length;++m)if(geo.frustumTestBox(n._frustum_planes,this._root._instances[l].aabb)!=CLIP_OUTSIDE){p=!0;break}if(!p)continue}isNaN(c)&&"viewport"==this.texture_size&&(g=n.getLocalViewport(null,n._viewport_in_pixels),e=g[2],g=g[3]);var m=gl.TEXTURE_2D,q=this.high_precision?gl.HIGH_PRECISION_FORMAT:gl.UNSIGNED_BYTE,p=this._textures[n.uid];p&&p.width==e&&p.height==g&&p.type==q&&p.texture_type==m&&p.minFilter==(this.generate_mipmaps?gl.LINEAR_MIPMAP_LINEAR:gl.LINEAR)||(p=
new GL.Texture(e,g,{type:q,texture_type:m,minFilter:this.generate_mipmaps?gl.LINEAR_MIPMAP_LINEAR:gl.LINEAR}),p.has_mipmaps=this.generate_mipmaps,this._textures[n.uid]=p);p._locked=!0;var m=this._root.transform.getGlobalPosition(),q=this._root.transform.getTop(),s=n.getEye(),t=n.getCenter(),u=n.getUp();if(this.use_mesh_info){var H=this._root.getMesh();H&&(m=this._root.transform.globalToLocal(BBox.getCenter(H.bounding)),q=this._root.transform.globalVectorToLocal(d.TOP))}vec3.add(m,m,this.offset);this._reflected_camera=
H=this._reflected_camera||new d.Camera;H.configure(n.serialize());H.fov=n.fov;H.aspect=n.aspect;s=geo.reflectPointInPlane(s,m,q);t=geo.reflectPointInPlane(t,m,q);u=geo.reflectPointInPlane(u,[0,0,0],q);H.lookAt(s,t,u);vec3.add(m,m,vec3.scale(vec3.create(),q,-this.clip_offset));this._clipping_plane.set(q);this._clipping_plane[3]=vec3.dot(m,q);d.Renderer._uniforms.u_clipping_plane.set(this._clipping_plane);d.Renderer.renderInstancesToRT(H,p,b);d.Renderer._uniforms.u_clipping_plane.set([0,0,0,0]);this.blur&&
((m=this._textures["blur_"+n.uid])&&(Texture.compareFormats(p,m)||m.minFilter!=p.minFilter)&&(m=null),p.applyBlur(this.blur,this.blur,1,null,m));this.generate_mipmaps&&isPowerOfTwo(e)&&isPowerOfTwo(g)&&(p.setParameter(gl.TEXTURE_MIN_FILTER,gl.LINEAR_MIPMAP_LINEAR),gl.generateMipmap(p.texture_type),p.unbind());p._locked=!1;p._is_planar=!0;this.texture_name&&d.ResourcesManager.registerResource(this.texture_name,p);d.ResourcesManager.registerResource(":reflection_"+n.uid,p);if(!this.all_cameras)break}b.layers=
h;delete b.brightness_factor;delete b.colorclip_factor;this._root.flags.visible=f}}};ib.prototype.onCameraEnabled=function(a,b){if(this.enabled&&this._root&&this._root.material&&this._textures[b.uid]){var c=this._root.getMaterial();c&&(c.setTexture(B.ENVIRONMENT_TEXTURE,":reflection_"+b.uid).uvs=B.COORDS_FLIPPED_SCREEN)}};d.registerComponent(ib);ba.last_id=0;ba.icon="mini-icon-reflector.png";ba["@texture_size"]={type:"enum",values:["viewport",64,128,256,512,1024,2048]};ba["@layers"]={type:"layers"};
ba["@background_color"]={type:"color"};Object.defineProperty(ba.prototype,"texture",{get:function(){return this._texture},set:function(){throw"probe cubemap cannot be set";},enumerable:!1});Object.defineProperty(ba.prototype,"enabled",{set:function(a){a!=this._enabled&&(this._enabled=a,a=this._root?this._root.scene:null,this._enabled?(this._registered||this.register(a),this.onRenderReflection(),d.GlobalScene.requestFrame()):this._registered&&this.unregister(a))},get:function(){return this._enabled},
enumerable:!0});ba.prototype.onAddedToScene=function(a){LEvent.bind(a,"start",this.onRenderReflection,this);LEvent.bind(a,"renderReflections",this.onRenderReflection,this);this.register(a)};ba.prototype.getExtraProperties=function(a){a.push(["texture","texture"])};ba.prototype.onRemovedFromScene=function(a){LEvent.unbindAll(a,this);this._texture&&d.ResourcesManager.unregisterResource(this._tex_id);this._texture=null;this.unregister(a)};ba.prototype.onSerialize=function(a){a.irradiance_shs=typedArrayToArray(this._irradiance_shs)};
ba.prototype.onConfigure=function(a){a.irradiance_shs&&this._irradiance_shs.set(a.irradiance_shs)};ba.prototype.onRenderReflection=function(a){if(this._enabled&&this._root&&this._root.scene){if(!this._must_update){if(d.ResourcesManager.isLoading())return;this.refresh_rate|=0;if(1>this.refresh_rate&&this._texture||this._texture&&0!=this._root.scene._frame%this.refresh_rate)return}this._must_update=!1;this.recompute()}};ba.prototype.recompute=function(a,b){if(this._root&&this._root.scene&&(this._root.transform.getGlobalPosition(this._current),
this.updateCubemap(this._current,a,!0),b)){var c=ba._temp_cubemap,e=F.capture_cubemap_size,d={type:gl.FLOAT,texture_type:gl.TEXTURE_CUBE_MAP,format:gl.RGB};c&&c.width==e&&c.height==e||(ba._temp_cubemap=c=new GL.Texture(e,e,d));this._texture.copyTo(c);this._irradiance_shs=F.computeSH(c)}};ba.use_float_for_high_precision=!1;ba.prototype.updateCubemap=function(a,b){b=b||d.Renderer.default_render_settings;var c=this._root.scene;if(c){var e=parseInt(this.texture_size),g=b.layers;b.layers=this.layers;d.Renderer.clearSamplers();
var f=gl.TEXTURE_CUBE_MAP,h=this.high_precision?ba.use_float_for_high_precision?gl.FLOAT:gl.HIGH_PRECISION_FORMAT:gl.UNSIGNED_BYTE,k=this._texture;k&&k.width==e&&k.height==e&&k.type==h&&k.texture_type==f&&k.minFilter==(this.generate_mipmaps?gl.LINEAR_MIPMAP_LINEAR:gl.LINEAR)||(k=new GL.Texture(e,e,{type:h,format:gl.RGB,texture_type:f,minFilter:this.generate_mipmaps?gl.LINEAR_MIPMAP_LINEAR:gl.LINEAR}),k.has_mipmaps=this.generate_mipmaps,this._texture=k);a?this._position.set(a):a=this._root.transform.getGlobalPosition(this._position);
k._in_current_fbo=!0;d.Renderer._visible_instances||(d.Renderer.processVisibleData(c,b),d.Renderer.regenerateShadowmaps(c,b));for(c=0;c<d.Renderer._visible_instances.length;++c)d.Renderer._visible_instances[c]._nearest_reflection_probe==this&&(d.Renderer._visible_instances[c]._nearest_reflection_probe=null);d.Renderer.renderToCubemap(a,0,k,b,this.near,this.far,this.background_color);k._in_current_fbo=!1;this.generate_mipmaps&&isPowerOfTwo(e)&&(k.setParameter(gl.TEXTURE_MIN_FILTER,gl.LINEAR_MIPMAP_LINEAR),
gl.generateMipmap(k.texture_type),k.unbind());for(c=0;c<d.Renderer._visible_instances.length;++c)null==d.Renderer._visible_instances[c]._nearest_reflection_probe&&(d.Renderer._visible_instances[c]._nearest_reflection_probe=this);this.texture_name&&d.ResourcesManager.registerResource(this.texture_name,k);d.ResourcesManager.registerResource(this._tex_id,k);b.layers=g}};ba.prototype.assignCubemaps=function(a){this._texture&&d.ResourcesManager.registerResource(this._tex_id,this._texture)};ba.prototype.register=
function(a){-1!=a._reflection_probes.indexOf(this)?console.warn("this reflection probe is already registered"):(a._reflection_probes.push(this),this._registered=!0)};ba.prototype.unregister=function(a){var b=a._reflection_probes.indexOf(this);-1==b?console.warn("this reflection probe is not registered"):(a._reflection_probes.splice(b,1),this._registered=!1)};ba.prototype.renderProbe=function(a,b){if(this._texture&&this._enabled){d.Draw.push();d.Draw.translate(this._position);d.Draw.scale(ba.helper_size);
if(b)d.Draw.setColor(b),d.Draw.renderMesh(d.Renderer._sphere_mesh,GL.TRIANGLES);else{var c=GL.Shader.getCubemapShowShader();a?this._irradiance_texture.bind(0):this._texture.bind(0);d.Draw.renderMesh(d.Renderer._sphere_mesh,GL.TRIANGLES,c);d.Draw.setColor(d.WHITE);d.Draw.scale(1.1);gl.enable(gl.CULL_FACE);gl.frontFace(gl.CW);d.Draw.renderMesh(d.Renderer._sphere_mesh,GL.TRIANGLES);gl.frontFace(gl.CCW)}d.Draw.pop()}};ba.updateAll=function(a,b){a=a||d.GlobalScene;for(var c=0;c<a._reflection_probes.length;++c)a._reflection_probes[c].recompute(b,
!0)};ba.visualize_helpers=!0;ba.visualize_irradiance=!1;ba.helper_size=1;d.registerComponent(ba);F.show_probes=!1;F.show_cubemaps=!1;F.probes_size=1;F.capture_cubemap_size=64;F.final_cubemap_size=16;F.OBJECT_MODE=1;F.VERTEX_MODE=2;F.PIXEL_MODE=3;F["@mode"]={type:"enum",values:{object:F.OBJECT_MODE,vertex:F.VERTEX_MODE,pixel:F.PIXEL_MODE}};F["@size"]={type:"vec3",min:0.1,step:0.1,precision:3};F["@subdivisions"]={type:"vec3",min:1,max:256,step:1,precision:0};F["@layers"]={widget:"layers"};F["@background_color"]=
{type:"color"};F["@intensity_color"]={type:"color"};F.default_coeffs=new Float32Array([0,0,0,0.5,0.75,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);F.use_sh_low=!1;F.prototype.onAddedToScene=function(a){LEvent.bind(a,"fillSceneUniforms",this.fillSceneUniforms,this)};F.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"fillSceneUniforms",this.fillSceneUniforms,this)};F.prototype.onConfigure=function(a){if(this.cache_filename){var b=this;d.ResourcesManager.load(this.cache_filename,function(a){a&&
(b._cache_resource=a,!b._sh_texture&&a._sh_texture&&(b._sh_texture=a._sh_texture),b.fromData(a.data),b.encodeCacheInTexture(),a._sh_texture=b._sh_texture,d.GlobalScene.requestFrame())})}};F.prototype.getResources=function(a){this.cache_filename&&this._cache_resource&&(a[this.cache_filename]=d.Resource)};F.prototype.onResourceRenamed=function(a,b){a==this.cache_filename&&(this.cache_filename=b)};F.prototype.fillSceneUniforms=function(){this.enabled&&this._sh_texture&&(this._samplers[d.Renderer.IRRADIANCE_TEXTURE_SLOT]=
this._sh_texture,this._uniforms.u_irradiance_distance=this.sampling_distance,d.Renderer.enableFrameShaderBlock("applyIrradiance",this._uniforms,this._samplers))};F.prototype.recompute=function(a){var b=this.subdivisions,c=this.size;1>b[0]&&(b[0]=1);1>b[1]&&(b[1]=1);1>b[2]&&(b[2]=1);var e=getTime();console.log("Capturing irradiance...");var g=vec3.fromValues(c[0]/b[0],c[1]/b[1],c[2]/b[2]),f=gl.FLOAT,h=d.Renderer.default_render_settings,k=h.layers;h.layers=this.layers;d.GlobalScene.info.textures.irradiance=
null;var l=F.final_cubemap_size,n=F.capture_cubemap_size,f={type:f,texture_type:gl.TEXTURE_CUBE_MAP,format:gl.RGB},p=F._temp_cubemap;p&&p.width==n&&p.height==n&&p.type==f.type||(F._temp_cubemap=new GL.Texture(n,n,f));if(this.onRecomputingIrradiance)this.onRecomputingIrradiance(c);if(!d.Renderer._visible_instances){c=this._root.scene;if(!c)throw"cannot compute irradiance without scene";d.Renderer.processVisibleData(c,h);d.Renderer.regenerateShadowmaps(c,h)}c=this.subdivisions[0]*this.subdivisions[1]*
this.subdivisions[2];this._irradiance_cubemaps.length=c;this._irradiance_shs.length=c;this._irradiance_subdivisions.set(this.subdivisions);c=vec3.create();n=this._irradiance_matrix;mat4.identity(n);this._root.transform&&this._root.transform.getGlobalMatrix(n);mat4.scale(n,n,g);for(var m=g=p=0;m<b[1];++m)for(var q=0;q<b[2];++q)for(var s=0;s<b[0];++s)if(c[0]=s+0.5,c[1]=m+0.5,c[2]=q+0.5,n&&mat4.multiplyVec3(c,n,c),a&&!a.testSphereInsideFrustum(c))p+=1;else{var t=this._irradiance_cubemaps[p];t&&t.type==
f.type&&t.width==l||(this._irradiance_cubemaps[p]=t=new GL.Texture(l,l,f));F.captureIrradiance(c,t,h,this.near,this.far,this.background_color,!0,F._temp_cubemap);this._irradiance_shs[p]=this.computeCubemapSH(t,c,p);p+=1;g+=1}a=getTime();console.log("Capturing light time: "+(a-e).toFixed(1)+"ms. Num. probes updated: "+g);this.encodeCacheInTexture();b=getTime();console.log("Packing in texture time: "+(b-a).toFixed(1)+"ms");console.log("Irradiance Total: "+(getTime()-e).toFixed(1)+"ms");if(this.onRecomputingFinished)this.onRecomputingFinished();
this.cache_filename||(this.cache_filename="IR_cache_"+this.uid.substr(1)+".bin");var u=this._cache_resource=d.ResourcesManager.getResource(u);u||(this._cache_resource=u=new d.Resource,d.ResourcesManager.registerResource(this.cache_filename,u));u.data=this.toData();d.RM.resourceModified(u);h.layers=k};F.captureIrradiance=function(a,b,c,e,g,f,h,k){d.Renderer.clearSamplers();d.Renderer.disableFrameShaderBlock("applyIrradiance");h&&(c.force_two_sided=!0);d.Renderer.renderToCubemap(a,0,k,c,e,g,f);h&&(c.force_two_sided=
!1);k.copyTo(b)};F.prototype.computeCubemapSH=function(a,b,c){for(var e=[],d=0;6>d;++d)e.push(a.getPixels(d));if(this.onPreprocessCubemap)this.onPreprocessCubemap(e,b,a,c);a=nc(e,a.width,4);if(this.onComputedSphericalHarmonics)this.onComputedSphericalHarmonics(a,b);return a};F.computeSH=function(a){for(var b=[],c=0;6>c;++c)b.push(a.getPixels(c));return nc(b,a.width,4)};F.prototype.encodeCacheInTexture=function(){if(this._irradiance_shs.length){var a=gl.FLOAT,b=gl.HIGH_PRECISION_FORMAT;GL.FBO.testSupport(b,
gl.RGB)||(b=gl.FLOAT);this._sh_texture&&this._sh_texture.height==this._irradiance_shs.length&&this._sh_texture.type==b||(this._sh_texture=new GL.Texture(9,this._irradiance_shs.length,{format:gl.RGB,type:b,magFilter:gl.NEAREST,minFilter:gl.NEAREST,wrap:gl.CLAMP_TO_EDGE}),d.ResourcesManager.registerResource(":IR_SHs",this._sh_texture));for(var c=new Float32Array(27*this._irradiance_shs.length),e=0;e<this._irradiance_shs.length;++e){var g=this._irradiance_shs[e];g&&c.set(g,27*e)}b==a?this._sh_texture.uploadData(c,
{no_flip:!0},!0):(this._sh_temp_texture&&this._sh_temp_texture.height==this._sh_temp_texture.length&&this._sh_temp_texture.type==a||(this._sh_temp_texture=new GL.Texture(9,this._irradiance_shs.length,{format:gl.RGB,type:a,magFilter:gl.NEAREST,minFilter:gl.NEAREST,wrap:gl.CLAMP_TO_EDGE})),this._sh_temp_texture.uploadData(c,{no_flip:!0},!0),this._sh_temp_texture.copyTo(this._sh_texture));a=this._uniforms.u_irradiance_imatrix;a.set(this._irradiance_matrix);mat4.invert(a,a)}};F.prototype.getSizeInBytes=
function(){return 108*this._irradiance_shs.length};F.prototype.showStats=function(){new Float32Array(9);new Float32Array(9);new Float32Array(9);for(var a=0;a<this._irradiance_shs.length;++a);};F.prototype.fromData=function(a){if(a){var b=new Uint8Array(a);if("IR_C"!=d.typedArrayToString(b.subarray(0,4)))return console.error("Irradiance data do not match"),!1;var b=new DataView(a),c=this._irradiance_subdivisions;c[0]=b.getUint8(4);c[1]=b.getUint8(5);c[2]=b.getUint8(6);b=c[0]*c[1]*c[2];a=new Float32Array(a,
16);this._irradiance_matrix.set(a.subarray(0,16));c=this._irradiance_shs;c.length=b;for(b=0;b<c.length;++b)c[b]=a.subarray(16+27*b,16+27*(b+1));return!0}};F.prototype.toData=function(){var a=this._irradiance_subdivisions,b=new ArrayBuffer(80+a[0]*a[1]*a[2]*108);(new Uint8Array(b)).set(d.stringToTypedArray("IR_C"),0);var c=new DataView(b);c.setUint8(4,a[0]);c.setUint8(5,a[1]);c.setUint8(6,a[2]);a=new Float32Array(b,16);a.set(this._irradiance_matrix);for(var c=this._irradiance_shs,e=0;e<c.length;++e){var g=
c[e];g&&a.set(g,16+27*e)}return b};F.prototype.renderEditor=function(a){if(this.enabled&&F.show_probes){a=GL.Shader.getCubemapShowShader();var b=F.sh_shader;b||(F.sh_shader=b=new GL.Shader(d.Draw.vertex_shader_code,F.fs_shader_code));var c=d.Renderer._sphere_mesh,e=this.subdivisions,c=this.size,g=vec3.fromValues(c[0]/e[0],c[1]/e[1],c[2]/e[2]),c=d.Renderer._sphere_mesh,f=F.default_cubemap;f||(f=F.default_cubemap=new GL.Texture(1,1,{texture_type:GL.TEXTURE_CUBE_MAP,format:GL.RGB,pixel_data:[255,255,
255]}));var h=vec3.create(),k=this._irradiance_matrix;mat4.identity(k);this._root.transform&&this._root.transform.getGlobalMatrix(k);mat4.scale(k,k,g);mat4.multiplyVec3(vec3.create(),k,[0,0,0]);mat4.multiplyVec3(vec3.create(),k,e);for(var g=d.Renderer._current_camera,l=0,n=0;n<e[1];++n)for(var p=0;p<e[2];++p)for(var m=0;m<e[0];++m)h[0]=m+0.5,h[1]=n+0.5,h[2]=p+0.5,mat4.multiplyVec3(h,k,h),g&&!g.testSphereInsideFrustum(h,F.probes_size)?l+=1:(d.Draw.push(),d.Draw.translate(h),d.Draw.scale(F.probes_size),
F.show_cubemaps?((this._irradiance_cubemaps[l]||f).bind(0),d.Draw.renderMesh(c,GL.TRIANGLES,a)):(b.uniforms({u_sh_coeffs:this._irradiance_shs[l]||F.default_coeffs}),d.Draw.renderMesh(c,GL.TRIANGLES,b)),d.Draw.pop(),l++)}};d.registerComponent(F);F.include_code="\nconst float Pi = 3.141592654;\nconst float CosineA0 = Pi;\nconst float CosineA1 = (2.0 * Pi) / 3.0;\nconst float CosineA2 = Pi * 0.25;\n\nstruct SH9\n{\n    float c[9];\n};\n\nstruct SH9Color\n{\n    vec3 c[9];\n};\n\nvoid SHCosineLobe(in vec3 dir, out SH9 sh)\n{\n\t\n    // Band 0\n    sh.c[0] = 0.282095 * CosineA0;\n\t\n    // Band 1\n    sh.c[1] = 0.488603 * dir.y * CosineA1;\n    sh.c[2] = 0.488603 * dir.z * CosineA1;\n    sh.c[3] = 0.488603 * dir.x * CosineA1;\n\t\n    // Band 2\n\t#ifndef SH_LOW\n\t\n    sh.c[4] = 1.092548 * dir.x * dir.y * CosineA2;\n    sh.c[5] = 1.092548 * dir.y * dir.z * CosineA2;\n    sh.c[6] = 0.315392 * (3.0 * dir.z * dir.z - 1.0) * CosineA2;\n    sh.c[7] = 1.092548 * dir.x * dir.z * CosineA2;\n    sh.c[8] = 0.546274 * (dir.x * dir.x - dir.y * dir.y) * CosineA2;\n\t#endif\n\t\n}\n\nvec3 ComputeSHIrradiance(in vec3 normal, in SH9Color radiance)\n{\n    // Compute the cosine lobe in SH, oriented about the normal direction\n    SH9 shCosine;\n\tSHCosineLobe(normal, shCosine);\n\t\n    // Compute the SH dot product to get irradiance\n    vec3 irradiance = vec3(0.0);\n\t#ifndef SH_LOW\n\tconst int num = 9;\n\t#else\n\tconst int num = 4;\n\t#endif\n    for(int i = 0; i < num; ++i)\n        irradiance += radiance.c[i] * shCosine.c[i];\n\t\n    return irradiance;\n}\n\nvec3 ComputeSHDiffuse(in vec3 normal, in SH9Color radiance)\n{\n    // Diffuse BRDF is albedo / Pi\n    return ComputeSHIrradiance( normal, radiance ) * (1.0 / Pi);\n}\n";
F.fs_shader_code="\nprecision mediump float;\n"+F.include_code+"\nvarying vec3 v_normal;\nuniform vec3 u_sh_coeffs[9];\nvoid main()\n{\n\tvec3 normal = normalize( v_normal );\n\tSH9Color coeffs;\n\tcoeffs.c[0] = u_sh_coeffs[0];\n\tcoeffs.c[1] = u_sh_coeffs[1];\n\tcoeffs.c[2] = u_sh_coeffs[2];\n\tcoeffs.c[3] = u_sh_coeffs[3];\n\tcoeffs.c[4] = u_sh_coeffs[4];\n\tcoeffs.c[5] = u_sh_coeffs[5];\n\tcoeffs.c[6] = u_sh_coeffs[6];\n\tcoeffs.c[7] = u_sh_coeffs[7];\n\tcoeffs.c[8] = u_sh_coeffs[8];\n\tgl_FragColor = vec4( max( vec3(0.001), ComputeSHDiffuse( normal, coeffs ) ), 1.0 );\n}\n";
var cc=[[[0,0,-1],[0,-1,0],[1,0,0]],[[0,0,1],[0,-1,0],[-1,0,0]],[[1,0,0],[0,0,1],[0,1,0]],[[1,0,0],[0,0,-1],[0,-1,0]],[[1,0,0],[0,-1,0],[0,0,1]],[[-1,0,0],[0,-1,0],[0,0,-1]]],zc="\n\tuniform sampler2D irradiance_texture;\n\tuniform vec3 u_irradiance_subdivisions;\n\tuniform vec3 u_irradiance_color;\n\tuniform mat4 u_irradiance_imatrix;\n\t//uniform float u_irradiance_debug;\n\tuniform float u_irradiance_distance;\n\t"+(F.use_sh_low?"#define SH_LOW":"")+"\n\t\n\t"+F.include_code+"\n\tvec3 computeSHRadianceAtLocalPos( in vec3 local_pos, in vec3 normal )\n\t{\n\t\tfloat floor_probes = u_irradiance_subdivisions.x * u_irradiance_subdivisions.z;\n\t\tfloat total_probes = floor_probes * u_irradiance_subdivisions.y;\n\t\tfloat i = floor(local_pos.x) + floor(local_pos.z) * u_irradiance_subdivisions.x + floor(local_pos.y) * floor_probes;\n\t\ti = (i+0.5) / (total_probes);\n\t\tSH9Color coeffs;\n\t\tcoeffs.c[0] = texture2D( irradiance_texture, vec2(0.5/9.0, i)).xyz;\n\t\tcoeffs.c[1] = texture2D( irradiance_texture, vec2(1.5/9.0, i)).xyz;\n\t\tcoeffs.c[2] = texture2D( irradiance_texture, vec2(2.5/9.0, i)).xyz;\n\t\tcoeffs.c[3] = texture2D( irradiance_texture, vec2(3.5/9.0, i)).xyz;\n\t\t#ifndef SH_LOW\n\t\tcoeffs.c[4] = texture2D( irradiance_texture, vec2(4.5/9.0, i)).xyz;\n\t\tcoeffs.c[5] = texture2D( irradiance_texture, vec2(5.5/9.0, i)).xyz;\n\t\tcoeffs.c[6] = texture2D( irradiance_texture, vec2(6.5/9.0, i)).xyz;\n\t\tcoeffs.c[7] = texture2D( irradiance_texture, vec2(7.5/9.0, i)).xyz;\n\t\tcoeffs.c[8] = texture2D( irradiance_texture, vec2(8.5/9.0, i)).xyz;\n\t\t#endif\n\t\treturn max( vec3(0.001), ComputeSHDiffuse( normal, coeffs ) );\n\t}\n\tfloat irr_expFunc(float f)\n\t{\n\t\t//f = f*f*f*(f*(f*6.0-15.0)+10.0);\n\t\t//if( f < 0.0 || f > 1.0 ) return 0.0;\n\t\treturn f;\n\t}\n\tvec3 computeSHRadianceAtPositionSmooth( in vec3 pos, in vec3 normal )\n\t{\n\t\tvec3 local_pos = (u_irradiance_imatrix * vec4(pos + u_irradiance_distance * normal, 1.0)).xyz - vec3(0.5);\n\t\tlocal_pos = clamp( local_pos, vec3(0.0), u_irradiance_subdivisions - vec3(1.0));\n\t\tfloat fx = fract(local_pos.x);\n\t\tfloat fy = 1.0 - fract(local_pos.y);\n\t\tfloat fz = 1.0 - fract(local_pos.z);\n\t\tfx = irr_expFunc(fx);\n\t\tfy = irr_expFunc(fy);\n\t\tfz = irr_expFunc(fz);\n\t\tvec3 LTF = computeSHRadianceAtLocalPos( vec3( floor(local_pos.x), ceil(local_pos.y), ceil(local_pos.z)), normal );\n\t\tvec3 LTB = computeSHRadianceAtLocalPos( vec3( floor(local_pos.x), ceil(local_pos.y), floor(local_pos.z)), normal );\n\t\tvec3 RTF = computeSHRadianceAtLocalPos( vec3( ceil(local_pos.x), ceil(local_pos.y), ceil(local_pos.z)), normal );\n\t\tvec3 RTB = computeSHRadianceAtLocalPos( vec3( ceil(local_pos.x), ceil(local_pos.y), floor(local_pos.z)), normal );\n\t\tvec3 LBF = computeSHRadianceAtLocalPos( vec3( floor(local_pos.x), floor(local_pos.y), ceil(local_pos.z)) , normal);\n\t\tvec3 LBB = computeSHRadianceAtLocalPos( vec3( floor(local_pos.x), floor(local_pos.y), floor(local_pos.z)), normal);\n\t\tvec3 RBF = computeSHRadianceAtLocalPos( vec3( ceil(local_pos.x), floor(local_pos.y), ceil(local_pos.z)), normal );\n\t\tvec3 RBB = computeSHRadianceAtLocalPos( vec3( ceil(local_pos.x), floor(local_pos.y), floor(local_pos.z)), normal);\n\t\tvec3 LT = mix(LTF,LTB,fz);\n\t\tvec3 LB = mix(LBF,LBB,fz);\n\t\tvec3 L = mix(LT,LB,fy);\n\t\tvec3 RT = mix(RTF,RTB,fz);\n\t\tvec3 RB = mix(RBF,RBB,fz);\n\t\tvec3 R = mix(RT,RB,fy);\n\t\treturn mix(L,R,fx);\n\t\t\n\t}\n\tvec3 computeSHRadianceAtPosition( in vec3 pos, in vec3 normal )\n\t{\n\t\tvec3 local_pos = (u_irradiance_imatrix * vec4(pos + u_irradiance_distance * normal, 1.0)).xyz - vec3(0.5);\n\t\tlocal_pos = clamp( local_pos, vec3(0.0), u_irradiance_subdivisions - vec3(1.0));\n\t\treturn computeSHRadianceAtLocalPos( local_pos, normal );\n\t\t\n\t}\n\t\n\tvoid applyIrradiance( in Input IN, in SurfaceOutput o, inout FinalLight FINALLIGHT )\n\t{\n\t\tFINALLIGHT.Ambient = o.Ambient * u_irradiance_color * computeSHRadianceAtPositionSmooth( IN.worldPos, o.Normal );\n\t}\n",
Kb="\n\tvoid applyIrradiance( in Input IN, in SurfaceOutput o, inout FinalLight FINALLIGHT )\n\t{\n\t}\n",zb=new d.ShaderBlock("applyIrradiance");K.irradiance_block=zb;zb.addCode(GL.FRAGMENT_SHADER,zc,Kb);zb.register(!0);var Ac="\n\tuniform vec3 u_sh_coeffs[9];\n\t"+F.include_code+"\n\tvoid applyIrradiance( in Input IN, in SurfaceOutput o, inout FinalLight FINALLIGHT )\n\t{\n\t\tSH9Color coeffs;\n\t\tcoeffs.c[0] = u_sh_coeffs[0];\n\t\tcoeffs.c[1] = u_sh_coeffs[1];\n\t\tcoeffs.c[2] = u_sh_coeffs[2];\n\t\tcoeffs.c[3] = u_sh_coeffs[3];\n\t\tcoeffs.c[4] = u_sh_coeffs[4];\n\t\tcoeffs.c[5] = u_sh_coeffs[5];\n\t\tcoeffs.c[6] = u_sh_coeffs[6];\n\t\tcoeffs.c[7] = u_sh_coeffs[7];\n\t\tcoeffs.c[8] = u_sh_coeffs[8];\n\t\tvec3 irr_color = ComputeSHDiffuse( o.Normal, coeffs );\n\t\tFINALLIGHT.Ambient = o.Ambient * irr_color;\n\t}\n",
kc=new d.ShaderBlock("applyIrradianceSingle");K.irradiance_single_block=kc;kc.addCode(GL.FRAGMENT_SHADER,Ac,Kb);kc.register(!0);v.secure_module=!1;v.block_execution=!1;v.catch_important_exceptions=!0;v.icon="mini-icon-script.png";v.templates={script:"//@unnamed\n//defined: component, node, scene, transform, globals\nthis.onStart = function()\n{\n}\n\nthis.onUpdate = function(dt)\n{\n\t//node.scene.refresh();\n}"};v["@code"]={type:"script"};v.BIND_TO_COMPONENT=1;v.BIND_TO_NODE=2;v.BIND_TO_SCENE=3;
v.BIND_TO_RENDERER=4;v.API_functions={};v.API_events_to_function={};v.defineAPIFunction=function(a,b,c,e){c=c||a;b=b||v.BIND_TO_SCENE;b={name:a,target:b,event:c,info:e};v.API_functions[a]=b;v.API_events_to_function[c]=b};v.defineAPIFunction("onStart",v.BIND_TO_SCENE,"start");v.defineAPIFunction("onAwake",v.BIND_TO_SCENE,"awake");v.defineAPIFunction("onFinish",v.BIND_TO_SCENE,"finish");v.defineAPIFunction("onPrefabReady",v.BIND_TO_NODE,"prefabReady");v.defineAPIFunction("onUpdate",v.BIND_TO_SCENE,
"update");v.defineAPIFunction("onFixedUpdate",v.BIND_TO_SCENE,"fixedUpdate");v.defineAPIFunction("onNodeClicked",v.BIND_TO_NODE,"node_clicked");v.defineAPIFunction("onClicked",v.BIND_TO_NODE,"clicked");v.defineAPIFunction("onSceneRender",v.BIND_TO_SCENE,"beforeRender");v.defineAPIFunction("onCollectRenderInstances",v.BIND_TO_NODE,"collectRenderInstances");v.defineAPIFunction("onRender",v.BIND_TO_SCENE,"beforeRenderInstances");v.defineAPIFunction("onAfterRender",v.BIND_TO_SCENE,"afterRenderInstances");
v.defineAPIFunction("onAfterSceneRender",v.BIND_TO_SCENE,"afterRender");v.defineAPIFunction("onRenderHelpers",v.BIND_TO_SCENE,"renderHelpers");v.defineAPIFunction("onRenderGUI",v.BIND_TO_SCENE,"renderGUI");v.defineAPIFunction("onEnableFrameContext",v.BIND_TO_SCENE,"enableFrameContext");v.defineAPIFunction("onShowFrameContext",v.BIND_TO_SCENE,"showFrameContext");v.defineAPIFunction("onMouseDown",v.BIND_TO_SCENE,"mousedown");v.defineAPIFunction("onMouseMove",v.BIND_TO_SCENE,"mousemove");v.defineAPIFunction("onMouseUp",
v.BIND_TO_SCENE,"mouseup");v.defineAPIFunction("onMouseWheel",v.BIND_TO_SCENE,"mousewheel");v.defineAPIFunction("onKeyDown",v.BIND_TO_SCENE,"keydown");v.defineAPIFunction("onKeyUp",v.BIND_TO_SCENE,"keyup");v.defineAPIFunction("onGamepadConnected",v.BIND_TO_SCENE,"gamepadconnected");v.defineAPIFunction("onGamepadDisconnected",v.BIND_TO_SCENE,"gamepaddisconnected");v.defineAPIFunction("onButtonDown",v.BIND_TO_SCENE,"buttondown");v.defineAPIFunction("onButtonUp",v.BIND_TO_SCENE,"buttonup");v.defineAPIFunction("onDragStart",
v.BIND_TO_SCENE,"dragstart");v.defineAPIFunction("onFileDrop",v.BIND_TO_SCENE,"fileDrop");v.defineAPIFunction("onEditorEvent",v.BIND_TO_SCENE,"editorEvent");v.defineAPIFunction("onEditorRender",v.BIND_TO_SCENE,"renderEditor");v.defineAPIFunction("onEditorRenderGUI",v.BIND_TO_SCENE,"renderEditorGUI");v.coding_help="For a complete guide check: <a href='https://github.com/jagenjo/litescene.js/blob/master/guides/scripting.md' target='blank'>Scripting Guide</a>";v.active_scripts={};Object.defineProperty(v.prototype,
"context",{set:function(a){console.error("Script: context cannot be assigned")},get:function(){return this._script?this._script._context:null},enumerable:!1});Object.defineProperty(v.prototype,"name",{set:function(a){console.error("Script: name cannot be assigned, add to the first line //@name")},get:function(){return this._name},enumerable:!1});v.prototype.configure=function(a){a.uid&&(this.uid=a.uid);void 0!==a.enabled&&(this.enabled=a.enabled);void 0!==a.code&&(this.code=a.code);this._root&&this._root.scene&&
this.processCode();a.properties&&this.setContextProperties(a.properties)};v.prototype.serialize=function(){return{object_class:"Script",uid:this.uid,enabled:this.enabled,code:this.code,properties:d.cloneObject(this.getContextProperties())}};v.prototype.getContext=function(){return this._script?this._script._context:null};v.prototype.getCode=function(){return this.code};v.prototype.setCode=function(a,b,c){this.code=a;this._blocked_functions.clear();this.processCode(b,c)};v.prototype.reload=function(){this.processCode()};
v.prototype.setBreakpoint=function(a,b){if(this._breakpoints||b)this._breakpoints||(this._breakpoints={}),b?this._breakpoints[a]=!0:(delete this._breakpoints[a],0==Object.keys(this._breakpoints).length&&(this._breakpoints=null))};v.prototype.hasBreakpoint=function(a){return this._breakpoints?this._breakpoints[a]:!1};v.prototype.processCode=function(a,b){this._blocked_functions.clear();this._script.code=this.code;this._name="";if(this.code){var c=this.code.substr(0,128);if(0==c.indexOf("//@")){var e=
c.indexOf("\n");-1==e&&(e=void 0);this._name=c.substr(3,e-3).trim()}}if(!this._root||d.Script.block_execution||!d.allow_scripts)return!0;this._script&&this._script._context&&this._script._context.unbindAll();c=this._stored_properties||this.getContextProperties();e=this._script.compile({component:this,node:this._root,scene:this._root.scene,transform:this._root.transform,globals:d.Globals});a||this.hookEvents();b||this.setContextProperties(c);this._stored_properties=null;if(this._script._context&&!this._script._context._initialized){if(this._root&&
this._script._context.onAddedToNode)this._script._context.onAddedToNode(this._root);if(this._root&&this._root.scene){if(this._script._context.onAddedToScene)this._script._context.onAddedToScene(this._root.scene);if(this._script._context.onBind)this._script._context.onBind(this._root.scene);this._root.scene._state===d.PLAYING&&this._script._context.start&&this._script._context.start()}this._script._context._initialized=!0}this._name&&this._root&&this._root.scene&&(d.Script.active_scripts[this._name]=
this);console.log(" + Script: "+this._name+" CTX: ",this._script._context);return e};v.prototype.getContextProperties=function(){var a=this.getContext();if(a)return this.onSerialize?this.onSerialize():d.cloneObject(a,null,!1,!1,!0)};v.prototype.setContextProperties=function(a){if(a){var b=this.getContext();if(b){if(d.cloneObject(a,b,!1,!0,!0),b.onConfigure)b.onConfigure(a)}else this._stored_properties=a}};v.prototype.setProperty=function(a,b){var c=this.getContext();if(c&&void 0!==c[a])if(c[a].set)c[a](b);
else c[a]=b;else this[a]&&(this[a]=b)};v.prototype.getPropertiesInfo=function(){var a=this.getContext();if(!a)return{enabled:"boolean"};a=d.getObjectProperties(a);a.enabled="boolean";return a};v.prototype.onAction=function(a,b){var c=this.getContext();if(c.onAction)return c.onAction(a,b)};v.prototype.getActions=function(a){var b=this.getContext();if(!b||!b.getActions)return a;if(b=b.getActions())for(var c in b)a[c]=b[c];return a};v.prototype.getEvents=function(){var a=this.getContext();return a&&
a.getEvents?a.getEvents():null};v.prototype.getPropertyInfoFromPath=function(a){if("context"==a[0]){var b=this.getContext();if(1==a.length)return{name:"context",node:this._root,target:b,type:"object",value:b};a=a[1];if(b&&void 0!==b[a]){var c=b[a],e=b["@"+a];e||(e=b.constructor["@"+a]);var d="";e&&(d=e.type);d||null===c||void 0===c||(c.constructor===String?d="string":c.constructor===Boolean?d="boolean":c.length?d="vec"+c.length:c.constructor===Number?d="number":c.constructor===Function&&(d="function"));
"function"==d&&(c=a);return{node:this._root,target:b,name:a,value:c,type:d}}}};v.prototype.setPropertyValueFromPath=function(a,b,c){c=c||0;if(!(a.length<c+1)&&"context"==a[c]){var e=this.getContext();a=a[c+1];if(e&&void 0!==e[a]&&void 0!==e[a]&&(!e[a]||e[a].constructor!=Function))return e[a]&&e[a].set?e[a].set(b):e[a]=b,!0}};v.prototype.hookEvents=function(){var a=this._root;if(!a)throw"hooking events of a Script without a node";var b=a.scene||d.GlobalScene,c=this.getContext();if(c)for(var e in d.Script.API_functions){var g=
e,f=d.Script.API_functions[g],h=null;switch(f.target){case v.BIND_TO_COMPONENT:h=this;break;case v.BIND_TO_NODE:h=a;break;case v.BIND_TO_SCENE:h=b;break;case v.BIND_TO_RENDERER:h=d.Renderer}if(!h)throw"Script event without target?";c[g]&&c[g].constructor===Function?LEvent.isBind(h,f.event,this.onScriptEvent,this)||LEvent.bind(h,f.event,this.onScriptEvent,this):LEvent.unbind(h,f.event,this.onScriptEvent,this)}};v.prototype.onScriptEvent=function(a,b){if(this.enabled){if(!a)throw"Event without type";
var c=d.Script.API_events_to_function[a];if(c){var e=!1;this._breakpoints&&this._breakpoints[c.name]&&(e=!0,this.setBreakpoint(c.name,!1));if(this._blocked_functions.has(c.name))console.warn("Script: blocked function trying to be executed, skipping: "+c.name);else{if(e)debugger;return this._script.callMethod(c.name,b,!1,this)}}}};v.prototype.onAddedToNode=function(a){a.script||(a.script=this)};v.prototype.onRemovedFromNode=function(a){if(this._script._context&&this._script._context.onDestroy)this._script._context.onDestroy();
a.script==this&&delete a.script};v.prototype.onAddedToScene=function(a){this._name&&(d.Script.active_scripts[this._name]=this);if(this._script&&this._script._context&&this._script._context._initialized){if(this._script._context.onBind)this._script._context.onBind()}else if(this.constructor.catch_important_exceptions)try{this.processCode()}catch(b){console.error(b)}else this.processCode()};v.prototype.onRemovedFromScene=function(a){this._name&&d.Script.active_scripts[this._name]==this&&delete d.Script.active_scripts[this._name];
LEvent.unbindAll(a,this);if(this._context){LEvent.unbindAll(a,this._context,this);if(this._script._context.onUnbind)this._script._context.onUnbind(a);if(this._script._context.onRemovedFromScene)this._context.onRemovedFromScene(a)}};v.prototype.getComponentTitle=function(){return this.name};v.prototype.toInfoString=function(){return this._root?d.getObjectClassName(this)+" in node "+this._root.name:d.getObjectClassName(this)};v.prototype.onError=function(a){var b=this._root.scene;b&&(a.script=this,
a.node=this._root,console.warn("Script: blocking function on script due to error: "+a.method_name),this._blocked_functions.add(a.method_name),LEvent.trigger(this,"code_error",a),LEvent.trigger(b,"code_error",a),LEvent.trigger(d,"code_error",a),console.log("app finishing due to error in script, scene state is keep as it was during the error."),b.finish())};v.prototype.onCodeChange=function(a){this.processCode()};v.prototype.getResources=function(a){var b=this.getContext(),c;for(c in b){var e=b[c],
g=b.constructor["@"+c];if(e&&g&&(d.RESOURCE_TYPES[g.type]&&(a[e]=!0),g.type==d.TYPES.ARRAY&&e.length&&g.data_type&&g.data_type.constructor===String&&d.RESOURCE_TYPES[g.data_type.toLowerCase()]))for(g=0;g<e.length;++g)a[e[g]]=!0}if(b&&b.onGetResources)b.onGetResources(a)};v.prototype.onResourceRenamed=function(a,b,c){var e=this.getContext();if(e&&e.onResourceRenamed)e.onResourceRenamed(a,b,c)};d.registerComponent(v);d.Script=v;va.coding_help=v.coding_help;Object.defineProperty(va.prototype,"filename",
{set:function(a){a&&(a=d.ResourcesManager.cleanFullpath(a));this._filename=a;this.processCode()},get:function(){return this._filename},enumerable:!0});Object.defineProperty(va.prototype,"context",{set:function(a){console.error("ScriptFromFile: context cannot be assigned")},get:function(){return this._script?this._script._context:null},enumerable:!1});Object.defineProperty(va.prototype,"name",{set:function(a){console.error("Script: name cannot be assigned, set the first line with //@name")},get:function(){return this._name},
enumerable:!1});va.prototype.onAddedToScene=function(a){if(this._script&&this._script._context&&this._script._context._initialized){if(this._script._context.onBind)this._script._context.onBind(a);if(this._script._context.onAddedToScene)this._script._context.onAddedToScene(a)}else if(this.constructor.catch_important_exceptions)try{this.processCode()}catch(b){console.error(b)}else this.processCode()};va.prototype.reload=function(a){if(this.filename){var b=this;d.ResourcesManager.load(this.filename,
null,function(c,e){e==b.filename&&(b.processCode(),a&&a(b))},!0)}};va.prototype.processCode=function(a,b,c){var e=this;if(this.filename){var g=d.ResourcesManager.getResource(this.filename);if(g)if(g=g.data,void 0===g)this._name="";else{if(this._script.code!=g){this._name="";if(g){var f=g.substr(0,128);if(0==f.indexOf("//@")){var h=f.indexOf("\n");-1==h&&(h=void 0);this._name=f.substr(3,h-3).trim()}}if(!this._root||d.Script.block_execution)return!0;this._script.code=g;this._script&&this._script._context&&
this._script._context.unbindAll();g=this._stored_properties||this.getContextProperties();f=this._script.compile({component:this,node:this._root,scene:this._root.scene,transform:this._root.transform,globals:d.Globals});a||this.hookEvents();c||this.setContextProperties(g);this._stored_properties=null;if(this._script._context&&!this._script._context._initialized){if(this._root&&this._script._context.onAddedToNode)this._script._context.onAddedToNode(this._root);if(this._root&&this._root.scene){if(this._script._context.onAddedToScene)this._script._context.onAddedToScene(this._root.scene);
if(this._script._context.onBind)this._script._context.onBind(this._root.scene);this._root.scene._state===d.PLAYING&&this._script._context.start&&this._script._context.start()}this._script._context._initialized=!0}this._name&&this._root&&this._root.scene&&(d.Script.active_scripts[this._name]=this);b&&b(this);console.log(" + Script: "+this._name+" CTX: ",this._script._context);return f}}else d.ResourcesManager.load(this.filename,null,function(c,d){d==e.filename&&(e.processCode(a),b&&b(e))})}};va.prototype.configure=
function(a){a.uid&&(this.uid=a.uid);void 0!==a.enabled&&(this.enabled=a.enabled);void 0!==a.filename&&(this.filename=a.filename);a.properties&&this.setContextProperties(a.properties);this._root&&this._root.scene&&this.processCode()};va.prototype.serialize=function(){return{object_class:"ScriptFromFile",uid:this.uid,enabled:this.enabled,filename:this.filename,properties:d.cloneObject(this.getContextProperties())}};va.prototype.onAction=function(a,b){var c=this.getContext();if(c&&c.onAction)return c.onAction(a,
b)};va.prototype.getActions=v.prototype.getActions();va.prototype.getEvents=v.prototype.getEvents();va.prototype.getResources=function(a){this.filename&&(a[this.filename]=d.Resource);var b=this.getContext();b&&b.getResources&&b.getResources(a)};va.prototype.onResourceRenamed=function(a,b,c){this.filename==a&&(this.filename=b)};va.prototype.getCodeResource=function(){return d.ResourcesManager.getResource(this.filename)};va.prototype.getCode=function(){var a=d.ResourcesManager.getResource(this.filename);
return a?a.data:""};va.prototype.setCode=function(a,b,c){var e=d.ResourcesManager.getResource(this.filename);if(!e)return"";e.data=a;this.processCode(b,null,c)};va.updateComponents=function(a,b){if(a)for(var c=a.fullpath||a.filename,e=d.GlobalScene.findNodeComponents(d.ScriptFromFile),g=0;g<e.length;++g){var f=e[g];f.filename==c&&f.processCode(b)}};d.extendClass(va,v);d.registerComponent(va);d.ScriptFromFile=va;U.GRID_MODE=1;U.RADIAL_MODE=2;U.MESH_MODE=3;U.CHILDREN_MODE=4;U.CUSTOM_MODE=5;U.icon="mini-icon-cloner.png";
U["@mesh"]={type:"mesh"};U["@lod_mesh"]={type:"mesh"};U["@mode"]={type:"enum",values:{Grid:U.GRID_MODE,Radial:U.RADIAL_MODE,Children:U.CHILDREN_MODE,Custom:U.CUSTOM_MODE}};U["@count"]={type:"vec3",min:1,step:1,precision:0};U.prototype.onAddedToScene=function(a){LEvent.bind(a,"collectRenderInstances",this.onCollectInstances,this);LEvent.bind(a,"afterCollectData",this.onUpdateInstances,this)};U.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"collectRenderInstances",this.onCollectInstances,
this);LEvent.unbind(a,"afterCollectData",this.onUpdateInstances,this)};U.prototype.getMesh=function(){return this.mesh&&this.mesh.constructor===String?Ob.meshes[this.mesh]:this.mesh};U.prototype.getLODMesh=function(){return this.lod_mesh&&this.lod_mesh.constructor===String?Ob.meshes[this.lod_mesh]:this.lod_mesh};U.prototype.getResources=function(a){this.mesh&&this.mesh.constructor===String&&(a[this.mesh]=Mesh);this.lod_mesh&&this.lod_mesh.constructor===String&&(a[this.lod_mesh]=Mesh);return a};U.prototype.onResourceRenamed=
function(a,b,c){this.mesh==a&&(this.mesh=b);this.lod_mesh==a&&(this.lod_mesh=b)};U.generateTransformKey=function(a,b,c){var e=new Float32Array(9);e.set(a);e.set(b,3);e.set(c,6);return e};U.compareKeys=function(a,b){for(var c=0;c<a.length;++c)if(a[c]!=b[c])return!1;return!0};U.prototype.onCollectInstances=function(a,b){if(this.enabled){var c=this.getMesh();if(!c)return null;var e=this._root;if(this._root){this.updateRenderInstancesArray();var d=this._RIs,f=this.material||this._root.getMaterial();if(d){var h=
b.length;b.length=h+d.length;for(var k=0,l=d.length;k<l;++k){var n=d[k];n.setMesh(c);n.layers=e.layers;n.setMaterial(f);b[h+k]=n}}}}};U.prototype.updateRenderInstancesArray=function(){var a=0;this.mode===U.GRID_MODE?a=(this.count[0]|0)*(this.count[1]|0)*(this.count[2]|0):this.mode===U.RADIAL_MODE?a=this.count[0]|0:this.mode===U.MESH_MODE?a=0:this.mode===U.CHILDREN_MODE&&this._root&&this._root._children&&(a=this._root._children.length);if(!a)this._RIs&&(this._RIs.length=0);else if(!this._RIs||this._RIs.length!=
a){this._RIs?this._RIs.length=a:this._RIs=Array(a);for(var b=0;b<a;++b)this._RIs[b]||(this._RIs[b]=new d.RenderInstance(this._root,this))}};U.prototype.onUpdateInstances=function(a,b){if(this.enabled){var c=this._RIs;if(c&&c.length){var e=this._root.transform.getGlobalMatrix(mat4.create()),d=this._count[0]|0,f=this._count[1]|0,h=this._count[2]|0;if(this.mode==U.GRID_MODE){var k=vec3.scale(vec3.create(),this.size,0.5),l=vec3.create();1<d?l[0]=this.size[0]/(d-1):k[0]=0;1<f?l[1]=this.size[1]/(f-1):k[1]=
0;1<h?l[2]=this.size[2]/(h-1):k[2]=0;for(var n=0,p=vec3.create(),m=vec3.create(),q=0;q<d;++q)for(var s=0;s<f;++s)for(var t=0;t<h;++t){var u=c[n];if(!u)return;p[0]=q*l[0]-k[0];p[1]=s*l[1]-k[1];p[2]=t*l[2]-k[2];mat4.translate(u.matrix,e,p);u.setMatrix(u.matrix);mat4.multiplyVec3(u.center,u.matrix,m);++n;u.picking_node=null}}else if(this.mode==U.RADIAL_MODE)for(l=2*Math.PI/c.length,p=vec3.create(),m=vec3.create(),n=0,d=c.length;n<d;++n){u=c[n];if(!u)break;p[0]=Math.sin(l*n)*this.size[0];p[1]=0;p[2]=
Math.cos(l*n)*this.size[0];u.matrix.set(e);mat4.translate(u.matrix,u.matrix,p);mat4.rotateY(u.matrix,u.matrix,l*n);u.setMatrix(u.matrix);mat4.multiplyVec3(u.center,u.matrix,m);u.picking_node=null}else if(this.mode==U.CHILDREN_MODE&&this._root&&this._root._children)for(n=0,d=c.length;n<d;++n){u=c[n];if(!u)break;if(l=this._root._children[n])l.transform&&l.transform.getGlobalMatrix(e),u.setMatrix(e),u.picking_node=l}}}};d.registerComponent(U);pa.icon="mini-icon-clock.png";Object.defineProperty(pa.prototype,
"weights",{set:function(a){if(a&&a.length)for(var b=0;b<a.length;++b)this.poses[b]&&(this.poses[b].weight=a[b]||0)},get:function(){for(var a=Array(this.poses.length),b=0;b<this.poses.length;++b)a[b]=this.poses[b].weight;return a},enumeration:!1});Object.defineProperty(pa.prototype,"name_weights",{set:function(a){if(a)for(var b in a){var c=this._poses_by_name[b];c&&(c.weight=Number(a[b]))}},get:function(){for(var a={},b=0;b<this.poses.length;++b){var c=this.poses[b];a[c.name]=c.weight}return a},enumeration:!1});
pa.prototype.onAddedToScene=function(a){LEvent.bind(a,"update",this.onUpdate,this)};pa.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"update",this.onUpdate,this)};pa.prototype.onUpdate=function(a,b){if(this.enabled&&this._root){this.applyPoseFromWeights();var c=this._root.scene;c&&c.requestFrame()}};pa.prototype.addBaseNode=function(a){for(var b=null,c=a.uid,e=0;e<this.base_nodes.length;++e){var d=this.base_nodes[e];if(d.node_uid==c){b=d;break}}b||(b={node_uid:c,position:[0,0,0],rotation:[0,
0,0,1],scaling:[1,1,1]},this.base_nodes.push(b));a.transform&&(vec3.copy(b.position,a.transform._position),quat.copy(b.rotation,a.transform._rotation),vec3.copy(b.scaling,a.transform._scaling))};pa.prototype.removeBaseNode=function(a){if(a)if(a.constructor===String&&(a=this._root.scene.getNode(a)),a)for(var b=0;b<this.base_nodes.length;++b){if(this.base_nodes[b].node_uid==a.uid){this.base_nodes.splice(b,1);this.purgePoses();break}}else console.warn("Node not found")};pa.prototype.setChildrenAsBaseNodes=
function(a){this.base_nodes.length=0;a&&this.addBaseNode(this._root);a=this._root.getDescendants();for(var b=0;b<a.length;++b)this.addBaseNode(a[b])};pa.prototype.addPose=function(a){var b={name:a,weight:0,nodes:[]};this.poses.push(b);this._poses_by_name[a]=b;this.updatePose(a)};pa.prototype.removePose=function(a){var b=this._poses_by_name[a];b&&(b=this.poses.indexOf(b),-1!=b&&this.poses.splice(b,1),delete this._poses_by_name[a])};pa.prototype.setPoseWeight=function(a,b){var c=this._poses_by_name[a];
c&&(c.weight=b)};pa.prototype.updatePose=function(a){if(this._root&&this._root.scene){a=this._poses_by_name[a];if(!a)return null;var b=this._root.scene;a.nodes.length=0;for(var c=vec3.create(),e=quat.create(),g=vec3.create(),f=0;f<this.base_nodes.length;++f){var h=this.base_nodes[f],k=b.getNode(h.node_uid);k?(vec3.sub(c,k.transform._position,h.position),quat.invert(e,k.transform._rotation),quat.mul(e,h.rotation,e),quat.invert(e,e),vec3.div(g,k.transform._scaling,h.scaling),h={node_uid:k.uid},1E-5<
vec3.length(c)&&(h.delta_pos=Array.apply([],c)),1E-4<vec4.dist(e,d.QUAT_IDENTITY)&&(h.delta_rot=Array.apply([],e)),1E-5<Math.abs(vec3.length(g)-1)&&(h.delta_scale=Array.apply([],g)),a.nodes.push(h)):console.warn("addPose error, node not found in scene")}return a}};pa.prototype.applyBasePose=function(){if(this._root&&this._root.scene){var a=this._root.scene;if(a)for(var b=0;b<this.base_nodes.length;++b){var c=this.base_nodes[b],e=a.getNode(c.node_uid);e&&e.transform&&(e.transform.position=c.position,
e.transform.rotation=c.rotation,e.transform.scaling=c.scaling)}}};pa.prototype.applyPose=function(a,b){if(this._root&&this._root.scene){var c=this._root.scene;if(c){var e=this._poses_by_name[a];if(e)for(var d=0;d<this.base_nodes.length;++d){var f=this.base_nodes[d],h=c.getNode(f.node_uid);if(h&&h.transform){var k=e.nodes[d];k?(k.delta_pos?vec3.add(h.transform._position,b?h.transform._position:f.position,k.delta_pos):b||(h.transform.position=f.position),k.delta_rot?quat.mul(h.transform._rotation,k.delta_rot,
b?h.transform._rotation:f.rotation):b||(h.transform.rotation=f.rotation),h.transform._must_update=!0):b||(h.transform.position=f.position,h.transform.rotation=f.rotation,h.transform.scaling=f.scaling)}}}}};pa.temp_quat=quat.create();pa.prototype.applyPoseFromWeights=function(){var a=this._root.scene;if(a){var b=this.base_nodes.length,c=this._positions_array,e=this._rotations_array,g=this._scalings_array;c&&c.length==3*b||(c=this._positions_array=new Float32Array(3*b),e=this._rotations_array=new Float32Array(4*
b),g=this._scalings_array=new Float32Array(3*b));for(var f=pa.temp_quat,h=0;h<b;++h)c.set(d.ZEROS,3*h),e.set(d.QUAT_IDENTITY,4*h),g.set(d.ONES,3*h);for(var k=0;k<this.poses.length;++k){var l=this.poses[k];if(l.weight)for(h=0;h<l.nodes.length;++h){var n=l.nodes[h];n.delta_pos&&(b=c.subarray(3*h,3*h+3),vec3.scaleAndAdd(b,b,n.delta_pos,l.weight));if(n.delta_rot){var p=e.subarray(4*h,4*h+4);quat.slerp(f,d.QUAT_IDENTITY,n.delta_rot,l.weight);quat.mul(p,p,f)}}}for(h=0;h<this.base_nodes.length;++h)f=this.base_nodes[h],
(k=a.getNode(f.node_uid))&&k.transform&&(b=c.subarray(3*h,3*h+3),p=e.subarray(4*h,4*h+4),g.subarray(3*h,3*h+3),quat.normalize(p,p),vec3.add(k.transform._position,b,f.position),quat.mul(k.transform._rotation,p,f.rotation),k.transform._must_update=!0)}};pa.prototype.purgePoses=function(){var a={},b=this._root.scene;if(b){for(var c=0;c<this.base_nodes.length;++c){var e=b.getNode(this.base_nodes[c].node_uid);e&&(a[e.uid]=!0)}for(c=0;c<this.poses.length;++c)for(b=this.poses[c].nodes,e=0;e<b.length;++e)a[b[e].node_uid]||
(b.splice(e,1),e--)}};pa.prototype.setProperty=function(a,b){if("enabled"==a)this.enabled=b;else if("pose_"==a.substr(0,5)){a=a.substr(5);var c=a.split("_"),e=this.poses[Number(c[0])];e&&"weight"==c[1]&&(e.weight=b)}else"weights"==a?this.weights=b:"name_weights"==a&&(this.name_weights=b)};pa.prototype.getProperty=function(a){if("pose_"==a.substr(0,5)&&5<a.length){a=a.substr(5).split("_");var b=this.poses[Number(a[0])];if(b&&"weight"==a[1])return b.weight}};pa.prototype.getPropertiesInfo=function(){for(var a=
{enabled:"boolean",weights:"array",name_weights:"object"},b=0;b<this.poses.length;++b)a["pose_"+b+"_weight"]="number";return a};pa.prototype.configure=function(a){d.BaseComponent.prototype.configure.call(this,a);for(a=0;a<this.poses.length;++a)this._poses_by_name[this.poses[a].name]=this.poses[a]};d.registerComponent(pa);qa["@subdivisions"]={type:"number",step:1,min:1,max:100,precision:0};qa["@type"]={type:"enum",values:{line:d.LINEAR,bezier:d.BEZIER,hermite:d.HERMITE}};qa.prototype.serialize=function(){return{enabled:this.enabled,
render:this._render_in_viewport,path:this.path.serialize(),subs:this._subdivisions,tangents:this.preserve_tangents}};qa.prototype.configure=function(a){this._must_update=!0;this.enabled=a.enabled;this.render_in_viewport=a.render;this.path.configure(a.path);this.preserve_tangents=a.tangents;this._subdivisions=a.subs||1};Object.defineProperty(qa.prototype,"render_in_viewport",{get:function(){return this._render_in_viewport},set:function(a){this._render_in_viewport!=a&&(this._render_in_viewport=a,this._root&&
(a?LEvent.bind(this._root,"collectRenderInstances",this.onCollectInstances,this):LEvent.unbind(this._root,"collectRenderInstances",this.onCollectInstances,this)))},enumerable:!0});Object.defineProperty(qa.prototype,"subdivisions",{get:function(){return this._subdivisions},set:function(a){this._subdivisions=a|0;this._must_update=!0},enumerable:!0});Object.defineProperty(qa.prototype,"closed",{get:function(){return this.path.closed},set:function(a){this.path.closed=a;this._must_update=!0},enumerable:!0});
Object.defineProperty(qa.prototype,"type",{get:function(){return this.path.type},set:function(a){this.path.type=a;this._must_update=!0},enumerable:!0});Object.defineProperty(qa.prototype,"numberOfPoints",{get:function(){return this.path.points.length},set:function(a){throw"number of points cannot be set, use addPoint";},enumerable:!1});Object.defineProperty(qa.prototype,"points",{get:function(){return this.path.points},set:function(a){throw"points cannot be set, use addPoint";},enumerable:!1});qa.prototype.onAddedToNode=
function(a){this._render_in_viewport&&LEvent.bind(a,"collectRenderInstances",this.onCollectInstances,this)};qa.prototype.onRemovedFromNode=function(a){this._render_in_viewport&&LEvent.unbind(a,"collectRenderInstances",this.onCollectInstances,this)};qa.prototype.onCollectInstances=function(a,b){if(this.enabled&&this._root&&0!=this.path.getSegments()){this._mesh&&!this._must_update||this.updateMesh();var c=this._render_instance;c||(this._render_instance=c=new d.RenderInstance(this._root,this));c.fromNode(this._root);
c.setMesh(this._mesh,gl.LINE_STRIP);c.setRange(0,this._range);c.setMaterial(this._root.getMaterial());b.push(c)}};qa.prototype.updateMesh=function(){this._mesh||(this._mesh=GL.Mesh.load({vertices:new Float32Array(3*this._max_points)}));var a=this._mesh.getVertexBuffer("vertices"),b=a.data,c=0,c=this.path.type==d.LINEAR?this.path.getSegments()+1:this.path.getSegments()*this._subdivisions;c>this._max_points&&(c=this._max_points);this.path.samplePointsTyped(c,b);a.uploadRange(0,12*c);this._range=c;this._must_update=
!1};qa.prototype.clear=function(){this._must_update=!0;this.path.clear()};qa.prototype.getPoint=function(a,b){b=b||vec3.create();this.path.closed&&(a%=1,0>a&&(a=1+a));this.path.computePoint(a,b);if(this._root.transform){var c=this._root.transform.getGlobalMatrix();mat4.multiplyVec3(b,c,b)}return b};qa.prototype.getPointRef=function(a){return a<this.path.points.length?this.path.points[a]:null};qa.prototype.addPoint=function(a){if(this._root.transform){var b=this._root.transform.getGlobalMatrix();mat4.invert(b,
b);a=mat4.multiplyVec3(vec3.create(),b,a)}this.path.addPoint(a);this._must_update=!0};qa.prototype.addPointLocal=function(a){this.path.addPoint(a);this._must_update=!0};qa.prototype.renderEditor=function(a){var b=this.path;2>b.points.length||(gl.disable(gl.DEPTH_TEST),d.Draw.push(),this._root.transform&&d.Draw.setMatrix(this._root.transform.getGlobalMatrixRef(!0)),a&&(d.Draw.setColor(0.9,0.5,0.9,1),d.Draw.setPointSize(9),d.Draw.renderRoundPoints(b.points)),this._render_in_viewport?(d.Draw.pop(),gl.enable(gl.DEPTH_TEST)):
(window.SelectionModule&&SelectionModule.selection&&SelectionModule.selection.instance==this&&void 0!=SelectionModule.selection.info&&(b=this.points[SelectionModule.selection.info],d.Draw.setColor(1,1,0.4,1),d.Draw.setPointSize(14),d.Draw.renderRoundPoints(b)),this._mesh&&!this._must_update||this.updateMesh(),a?d.Draw.setColor(0.6,0.6,0.6,0.8):d.Draw.setColor(0.6,0.5,0.4,0.5),d.Draw.renderMesh(this._mesh,GL.LINE_STRIP,null,null,0,this._range),gl.enable(gl.DEPTH_TEST),d.Draw.pop()))};qa.prototype.renderPicking=
function(a){a=this._root.transform.getGlobalMatrixRef(!0);for(var b=this.path,c=0;c<b.points.length;++c){var e=b.points[c];this._root.transform&&(e=mat4.multiplyVec3(vec3.create(),a,e));d.Picking.addPickingPoint(e,9,{instance:this,info:c})}};qa.prototype.applyTransformMatrix=function(a,b,c){b=this.path.points[c];if(!b)return!1;this._must_update=!0;a=mat4.multiplyVec3(vec3.create(),a,b);this.path.movePoint(c,a,this.preserve_tangents);return!0};qa.prototype.getTransformMatrix=function(a){a=this.path.points[a];
if(!a)return null;var b=this._root.transform.getGlobalMatrix();mat4.translate(b,b,a);return b};d.registerComponent(qa);jb["@spline"]={type:d.TYPES.COMPONENT_ID};jb["@factor"]={type:"number",step:0.001,precision:3};jb.prototype.serialize=function(){return{enabled:this.enabled,spline:this.spline,factor:this.factor}};jb.prototype.configure=function(a){this.enabled=a.enabled;this.spline=a.spline;this.factor=a.factor};jb.prototype.onAddedToScene=function(a){LEvent.bind(a,"update",this.onUpdate,this)};
jb.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,"update",this.onUpdate,this)};jb.prototype.onUpdate=function(a,b){var c=this._root;if(c&&c.transform){var e=d.GlobalScene.findComponentByUId(this.spline);if(e){var g=this._last_position,f=this._last_position_inc;e.getPoint(this.factor,g);e.getPoint(this.factor+0.001,f);c._parentNode&&c._parentNode.transform&&(e=c._parentNode.transform.getGlobalMatrix(),mat4.invert(e,e),mat4.multiplyVec3(g,e,g),mat4.multiplyVec3(f,e,f));1E-5>vec3.distance(g,
f)?c.transform.setPosition(g):c.transform.lookAt(g,f,d.TOP)}}};d.registerComponent(jb);$.icon="mini-icon-brush.png";$.MODE_CANVAS2D=1;$.MODE_WEBGL=2;$.MODE_IMMEDIATE=3;$["@mode"]={type:"enum",values:{Canvas2D:$.MODE_CANVAS2D,WebGL:$.MODE_WEBGL,Immediate:$.MODE_IMMEDIATE}};$["@width"]={type:"number",step:1,precision:0};$["@height"]={type:"number",step:1,precision:0};$["@texture_name"]={type:"string"};Object.defineProperty($.prototype,"texture",{set:function(){throw"Canvas3D texture cannot be set manually";
},get:function(){return this._texture},enumerable:!1});$.prototype.onAddedToScene=function(a){LEvent.bind(a,d.EVENT.READY_TO_RENDER,this.onRender,this);LEvent.bind(a,d.EVENT.AFTER_RENDER_INSTANCES,this.onRender,this)};$.prototype.onRemovedFromScene=function(a){LEvent.unbind(a,d.EVENT.READY_TO_RENDER,this.onRender,this);LEvent.unbind(a,d.EVENT.AFTER_RENDER_INSTANCES,this.onRender,this)};$.prototype.onAddedToNode=function(a){this.texture_name||(this.texture_name=":canvas3D");LEvent.bind(a,d.EVENT.COLLECT_RENDER_INSTANCES,
this.onCollectInstances,this)};$.prototype.onRemovedFromNode=function(a){LEvent.unbind(a,d.EVENT.COLLECT_RENDER_INSTANCES,this.onCollectInstances,this)};$.prototype.onRender=function(a){var b=d.Renderer._current_camera;this.enabled&&b&&b.checkLayersVisibility(this._root.layers)&&(a==d.EVENT.READY_TO_RENDER&&(this.mode==$.MODE_CANVAS2D||this.mode==$.MODE_WEBGL)||a==d.EVENT.AFTER_RENDER_INSTANCES&&this.mode==$.MODE_IMMEDIATE)&&this.drawCanvas()};$.prototype.drawCanvas=function(){var a=this.width|0,
b=this.height|0;this.mode==$.MODE_CANVAS2D&&(this._canvas||(this._canvas=document.createElement("canvas")),this._canvas.width!=a&&(this._canvas.width=a),this._canvas.height!=b&&(this._canvas.height=b));var c=this.high_precision?gl.HIGH_PRECISION_FORMAT:gl.UNSIGNED_BYTE;this.mode==$.MODE_IMMEDIATE||this._texture&&this._texture.width==a&&this._texture.height==b&&this._texture.type==c||(this._texture=new GL.Texture(a,b,{type:c,format:GL.RGBA,filter:GL.LINEAR,wrap:GL.CLAMP_TO_EDGE}));this.visible&&this.projectMouse();
if(this.mode==$.MODE_CANVAS2D)c=this._canvas.getContext("2d"),this._clear_buffer&&c.clearRect(0,0,this._canvas.width,this._canvas.height),d.GUI._ctx=c,this._root.processActionInComponents("onRenderCanvas",[c,this._canvas,this._mouse,this]),d.GUI._ctx=gl,this._texture.uploadImage(this._canvas);else if(this.mode==$.MODE_WEBGL)c=gl,this._fbo||(this._fbo=new GL.FBO),this._fbo.setTextures([this._texture]),this._fbo.bind(),gl.start2D(),this._clear_buffer&&(gl.clearColor(0,0,0,0),gl.clear(GL.COLOR_BUFFER_BIT)),
d.GUI._ctx=gl,this._root.processActionInComponents("onRenderCanvas",[c,this._texture,this._mouse,this]),gl.finish2D(),this._fbo.unbind();else if(this.mode==$.MODE_IMMEDIATE){c=gl;gl.start2D();d.GUI._ctx=gl;a=this._mvp;a||(a=this._mvp=mat4.create());mat4.identity(a);this._root.transform&&mat4.multiply(a,a,this._root.transform.getGlobalMatrixRef());mat4.scale(a,a,[1/this.width,-1/this.height,1]);mat4.translate(a,a,[-0.5*this.width,-0.5*this.height,0]);mat4.multiply(a,d.Renderer._current_camera._viewprojection_matrix,
a);gl.WebGLCanvas.set3DMatrix(a);this._canvas_info||(this._canvas_info={width:0,height:0});this._canvas_info.width=this.width;this._canvas_info.height=this.height;gl.disable(gl.CULL_FACE);gl.enable(gl.DEPTH_TEST);gl.depthFunc(gl.LEQUAL);gl.globalAlpha=this.opacity;this._root.processActionInComponents("onRenderCanvas",[c,this._canvas_info,this._mouse,this]);gl.globalAlpha=1;gl.finish2D();gl.depthFunc(gl.LESS);gl.WebGLCanvas.set3DMatrix(null);return}this._texture&&(this.generate_mipmaps&&isPowerOfTwo(a)&&
isPowerOfTwo(b)?(this._texture.setParameter(GL.TEXTURE_MIN_FILTER,GL.LINEAR_MIPMAP_LINEAR),gl.generateMipmap(gl.TEXTURE_2D)):this._texture.setParameter(GL.TEXTURE_MIN_FILTER,GL.LINEAR),d.RM.registerResource(this.texture_name||":canvas3D",this._texture));this._prev_mouse&&(d.Input.Mouse=this._prev_mouse,this._prev_mouse=null);d.Input.current_click&&this._prev_click_mouse&&(d.Input.current_click=this._prev_click_mouse,this._prev_click_mouse=null)};$.prototype.onCollectInstances=function(a,b){if(this.enabled&&
this.visible&&this._texture&&this.mode!=$.MODE_IMMEDIATE){this._RI||(this._RI=new d.RenderInstance);var c=this._RI,e=null;this.use_node_material&&(e=this._root.getMaterial());e||(e=this._standard_material);e||(e=this._standard_material=new d.MaterialClasses.StandardMaterial({flags:{ignore_lights:!0,cast_shadows:!1},blend_mode:d.Blend.ALPHA}));this.use_node_material||(e.opacity=this.opacity,e.blend_mode=1>e.opacity?d.Blend.ALPHA:d.Blend.NORMAL);e.setTexture("color",this.texture_name||":canvas3D");
c.fromNode(this._root);c.setMaterial(e);this._mesh||(this._mesh=GL.Mesh.plane());c.setMesh(this._mesh);b.push(c);return b}};$.prototype.clear=function(a){this.mode==$.MODE_CANVAS2D?this._canvas.getContext("2d").clearRect(0,0,this._canvas.width,this._canvas.height):this.mode==$.MODE_WEBGL&&this._texture&&this._texture.fill([0,0,0,0]);if(a)this.onRender()};$.prototype.projectMouse=function(){var a=d.Renderer._main_camera;if(a)if(this.root.transform){var b=0,b=vec3.distance(a.getEye(),this.root.transform.getGlobalPosition()),
c=b>this.max_interactive_distance;this._is_mouse_inside=!1;var e=d.Input.Mouse.canvasx,g=d.Input.Mouse.canvasy,f=this.width|0,h=this.height|0;if(!this.input_active||c)this._mouse[0]=-1,this._mouse[1]=-1,this._mouse[2]=-1;else{this._mouse[0]=-1;this._mouse[1]=-1;this._mouse[2]=b;a=a.getRay(e,g);if(!a)return;b=vec3.create();c=this.root.transform.localVectorToGlobal(d.FRONT,b);if(!this._skip_backside||0<vec3.dot(a.direction,c))b=this.root.transform.globalToLocal(a.origin,b),a=this.root.transform.globalVectorToLocal(a.direction),
geo.testRayPlane(b,a,d.ZEROS,d.FRONT,this._mouse)&&(this._mouse[0]=(this._mouse[0]+0.5)*f,this._mouse[1]=(this._mouse[1]+0.5)*h,this._mouse[1]=h-this._mouse[1])}0<=this._mouse[0]&&this._mouse[0]<f&&0<=this._mouse[1]&&this._mouse[1]<h&&(this._is_mouse_inside=!0);this._local_mouse.mousex=this._mouse[0];this._local_mouse.mousey=this._mouse[1];this._prev_mouse=d.Input.Mouse;d.Input.Mouse=this._local_mouse;d.Input.current_click&&(this._local_mouse_click.mousex=this._mouse[0],this._local_mouse_click.mousey=
this._mouse[1],this._prev_click_mouse=d.Input.current_click,d.Input.current_click=this._local_mouse_click)}else this._mouse[0]=d.Input.Mouse.canvasx,this._mouse[1]=d.Input.Mouse.canvasy,this._mouse[2]=0,this._is_mouse_inside=!0};d.registerComponent($);Object.defineProperty(S.prototype,"enabled",{set:function(a){(this._enabled=a)?(a=this._root?this._root.scene:null)&&a.state===d.RUNNING&&this._video.autoplay&&(this._video.currentTime>=this._video.duration&&(this._video.currentTime=0),this._video.play()):
this._video.pause()},get:function(){return this._enabled},enumerable:!0});Object.defineProperty(S.prototype,"ignore_proxy",{set:function(a){a!=this._ignore_proxy&&(this._ignore_proxy=a,this.load(this.src))},get:function(){return this._ignore_proxy},enumerable:!0});Object.defineProperty(S.prototype,"src",{set:function(a){a!=this._src&&(this._src=a,this.load(this._src))},get:function(){return this._src},enumerable:!0});Object.defineProperty(S.prototype,"time",{set:function(a){this._video.currentTime=
time},get:function(){return this._video.currentTime},enumerable:!1});Object.defineProperty(S.prototype,"texture",{set:function(a){throw"videoPlayer texture cannot be set";},get:function(){return this._texture},enumerable:!1});Object.defineProperty(S.prototype,"autoplay",{set:function(a){this._autoplay=a},get:function(){return this._autoplay},enumerable:!0});Object.defineProperty(S.prototype,"muted",{set:function(a){this._video.muted=a},get:function(){return this._video.muted},enumerable:!0});Object.defineProperty(S.prototype,
"duration",{set:function(a){throw"VideoPlayer duration cannot be assigned, is read-only";},get:function(){return this._video.duration},enumerable:!1});Object.defineProperty(S.prototype,"playback_rate",{set:function(a){0>a||(this._playback_rate=a,this._video.playbackRate=a)},get:function(){return this._playback_rate},enumerable:!0});Object.defineProperty(S.prototype,"video",{set:function(a){if(!a||a.constructor!==HTMLVideoElement)throw"Video must a HTMLVideoElement";a!=this._video&&(this._video=a,
this._video.muted=!1,this._video.autoplay=!1,this._video.playbackRate=this._playback_rate,this.bindVideoEvents(this._video))},get:function(){return this._video},enumerable:!1});S.NONE=0;S.PLANE=1;S.TO_MATERIAL=2;S.BACKGROUND=5;S.BACKGROUND_STRETCH=6;S["@src"]={type:"resource"};S["@render_mode"]={type:"enum",values:{NONE:S.NONE,PLANE:S.PLANE,TO_MATERIAL:S.TO_MATERIAL,BACKGROUND_STRETCH:S.BACKGROUND_STRETCH}};S.prototype.onAddedToScene=function(a){LEvent.bind(a,"start",this.onStart,this);LEvent.bind(a,
"pause",this.onPause,this);LEvent.bind(a,"unpause",this.onUnpause,this);LEvent.bind(a,"beforeRender",this.onBeforeRender,this);LEvent.bind(a,"beforeRenderScene",this.onBeforeRenderScene,this);LEvent.bind(a,"collectRenderInstances",this.onCollectInstances,this);LEvent.bind(a,"finish",this.onFinish,this)};S.prototype.onRemovedFromScene=function(a){LEvent.unbindAll(a,this)};S.prototype.onStart=function(){this.autoplay&&this.play()};S.prototype.onPause=function(){this.pause()};S.prototype.onUnpause=function(){this.autoplay&&
this.play()};S.prototype.onFinish=function(){this.stop()};S.prototype.load=function(a,b){if(a){var c=d.RM.getFullURL(a,{ignore_proxy:this.ignore_proxy});if(this._url_loading!=c||b)this._url_loading=a,this._video.crossOrigin="anonymous",this._video.src=c}};S.prototype.bindVideoEvents=function(a){a._component=this;a.has_litescene_events||(a.has_litescene_events=!0,this._video.addEventListener("loadedmetadata",function(a){console.log("Duration: "+this.duration+" seconds");console.log("Size: "+this.videoWidth+
","+this.videoHeight);this.width=this.videoWidth;this.height=this.videoHeight;this._component&&(a=this._component._root?this._component._root.scene:null)&&a.state===d.RUNNING&&this._component._autoplay&&this._component.play()}),this._video.addEventListener("error",function(a){console.error("Error loading video: "+this.src);if(this.error)switch(this.error.code){case this.error.MEDIA_ERR_ABORTED:console.error("You stopped the video.");break;case this.error.MEDIA_ERR_NETWORK:console.error("Network error - please try again later.");
break;case this.error.MEDIA_ERR_DECODE:console.error("Video is broken..");break;case this.error.MEDIA_ERR_SRC_NOT_SUPPORTED:console.error("Sorry, your browser can't play this video.")}}),this._video.addEventListener("ended",function(a){this._component&&(console.log("Ended."),(a=this._component._root?this._component._root.scene:null)&&a.state===d.RUNNING&&this._component._autoplay&&(this.currentTime=0,this._component.play()))}))};S.prototype.play=function(){this._video.videoWidth&&this._video.play()};
S.prototype.playPause=function(){this._video.paused?this.play():this.pause()};S.prototype.stop=function(){this._video.pause();this._video.currentTime=0};S.prototype.pause=function(){this._video.pause()};S.prototype.onBeforeRender=function(a){if(this.enabled&&0!=this._video.videoWidth){a=this._video;var b=this.generate_mipmaps;GL.isPowerOfTwo(a.videoWidth)&&GL.isPowerOfTwo(a.videoHeight)||(b=!1);this._texture&&this._texture.width==a.videoWidth&&this._texture.has_mipmaps==b||(this._texture=new GL.Texture(a.videoWidth,
a.videoHeight,{format:GL.RGB,minFilter:b?gl.LINEAR_MIPMAP_LINEAR:gl.LINEAR,magFilter:gl.LINEAR}),this._texture.has_mipmaps=b);this._texture._video_time!=a.currentTime&&(this._texture.uploadImage(a),b&&(this._texture.bind(0),gl.generateMipmap(this._texture.texture_type),this._texture.unbind(0)),this._texture._video_time=a.currentTime);this.texture_name&&d.RM.registerResource(this.texture_name,this._texture);this.render_mode==S.TO_MATERIAL&&(a=this._root.getMaterial())&&a.setTexture("color",this.texture_name)}};
S.prototype.onBeforeRenderScene=function(a){this.enabled&&(this.render_mode==S.BACKGROUND||this.render_mode==S.BACKGROUND_STRETCH)&&this._texture&&(gl.disable(gl.BLEND),gl.disable(gl.CULL_FACE),gl.disable(gl.DEPTH_TEST),this._texture.toViewport())};S.prototype.onCollectInstances=function(a,b){if(this.enabled&&this.render_mode==S.PLANE){this._material||(this._material=new d.StandardMaterial({flags:{ignore_lights:!0,two_sided:!0}}));if(!this._plane_ri){var c=this._plane_ri=new d.RenderInstance,e=GL.Mesh.plane();
c.setMesh(e);c.setMaterial(this._material)}this._plane_ri.fromNode(this._root);this._material.setTexture("color",this._texture);b.push(this._plane_ri)}};d.registerComponent(S);za.icon="mini-icon-cursor.png";za.PICKING=1;za.BOUNDING=2;za.COLLIDERS=3;za.RENDER_INSTANCES=4;za["@mode"]={type:"enum",values:{Picking:za.PICKING,Bounding:za.BOUNDING,Colliders:za.COLLIDERS}};za["@layers"]={type:"layers"};za.prototype.onAddedToScene=function(a){LEvent.bind(a,"mousedown",this._onMouse,this);LEvent.bind(a,"mousemove",
this._onMouse,this);LEvent.bind(a,"mouseup",this._onMouse,this)};za.prototype.onRemovedFromScene=function(a){LEvent.unbindAll(a,this)};za.prototype.getNodeUnderMouse=function(a){var b=this.layers;if(this.mode==za.PICKING)return d.Picking.getNodeAtCanvasPosition(a.canvasx,a.canvasy,null,b);var c=d.Renderer.getCameraAtPosition(a.canvasx,a.canvasy);if(!c)return null;a=c.getRay(a.canvasx,a.canvasy);if(this.mode==za.BOUNDING){b=d.Physics.raycastRenderInstances(a.origin,a.direction,{layers:b});if(!b||!b.length)return null;
this._last_collision=b[0];return b[0].node}if(this.mode==za.RENDER_INSTANCES){b=d.Physics.raycastRenderInstances(a.origin,a.direction,{layers:b,triangle_collision:!0});if(!b||!b.length)return null;this._last_collision=b[0];return b[0].node}if(this.mode==za.COLLIDERS){b=d.Physics.raycast(a.origin,a.direction,{layers:b});if(!b||!b.length)return null;this._last_collision=b[0];return b[0].node}return null};za.prototype._onMouse=function(a,b){if(this.enabled){if(("mousedown"==b.eventType||"mousewheel"==
b.eventType)&&(this._clicked_node=this.getNodeUnderMouse(b))&&"mousedown"==b.eventType&&0==b.button&&(console.log("Node clicked: "+this._clicked_node.name),LEvent.trigger(this._clicked_node,"clicked",this._clicked_node),LEvent.trigger(this._root,"node_clicked",this._clicked_node),LEvent.trigger(this._root.scene,"node_clicked",this._clicked_node),this.onNodeClicked))this.onNodeClicked(this._clicked_node);this._clicked_node&&(b.scene_node=this._clicked_node,LEvent.trigger(this._clicked_node,b.eventType,
b));"mouseup"==b.eventType&&(this._clicked_node=null);if(this._clicked_node)return!0}};d.registerComponent(za);y.INIT="init";y.CLEAR="clear";y.PRECONFIGURE="preConfigure";y.CONFIGURE="configure";y.CHANGE="change";y.LOAD="load";y.LOAD_COMPLETED="load_completed";y.AWAKE="awake";y.START="start";y.PAUSE="pause";y.UNPAUSE="unpause";y.COLLECT_RENDER_INSTANCES="collectRenderInstances";y.COLLECT_PHYSIC_INSTANCES="collectPhysicInstances";y.COLLECT_LIGHTS="collectLights";y.COLLECT_CAMERAS="collectCameras";
y.COLLECT_DATA="collectData";y.SERIALIZE="serialize";y.FINISH="finish";Object.defineProperty(C.prototype,"root",{enumerable:!0,get:function(){return this._root},set:function(a){throw"Root node cannot be replaced";}});Object.defineProperty(C.prototype,"time",{enumerable:!0,get:function(){return this._time},set:function(a){throw"Cannot set time directly";}});Object.defineProperty(C.prototype,"state",{enumerable:!0,get:function(){return this._state},set:function(a){throw"Cannot set state directly, use start, finish, pause, unpause";
}});Object.defineProperty(C.prototype,"globalTime",{enumerable:!0,get:function(){return this._global_time},set:function(a){throw"Cannot set global_time directly";}});Object.defineProperty(C.prototype,"frame",{enumerable:!0,get:function(){return this._frame},set:function(a){throw"Cannot set frame directly";}});C.supported_events="start update finish clear beforeReload change afterRender configure nodeAdded nodeChangeParent nodeComponentRemoved reload renderPicking scene_loaded serialize".split(" ");
C.prototype.init=function(){this.id="";this.external_repository=null;this.global_scripts=[];this.external_scripts=[];this.preloaded_resources={};this.texture_atlas=null;this._root.removeAllComponents();this._root.uid=d.generateUId("NODE-");this._nodes=[this._root];this._nodes_by_name={root:this._root};this._nodes_by_uid={};this._nodes_by_uid[this._root.uid]=this._root;this._components_by_uid={};this._spatial_container.clear();this.info=new d.Components.GlobalInfo;this._root.addComponent(this.info);
this._root.addComponent(new d.Camera({eye:[0,100,100],center:[0,0,0]}));this._root.addComponent(new d.Light({position:vec3.fromValues(100,100,100),target:vec3.fromValues(0,0,0)}));this._frame=0;this._last_collect_frame=-1;this._state=d.STOPPED;this._start_time=this._global_time=this._time=0;this._last_dt=1/60;this._must_redraw=!0;this._fixed_update_timestep=1/60;this._remaining_fixed_update_time=0;this.selected_node&&delete this.selected_node;this.layer_names=["main","secondary"];this.animation=null;
this._local_resources={};this.extra={}};C.prototype.clear=function(){for(;this._root._children&&this._root._children.length;)this._root.removeChild(this._root._children[0],!1,!0);this._root.processActionInComponents("onRemovedFromNode",this);this._root.processActionInComponents("onRemovedFromScene",this);this._instances.length=0;this._lights.length=0;this._cameras.length=0;this._colliders.length=0;this._reflection_probes.length=0;this._local_resources={};this.init();LEvent.trigger(this,y.CLEAR);LEvent.trigger(this,
y.CHANGE)};C.prototype.configure=function(a){if(!a||a.constructor===String)throw"Scene configure requires object";LEvent.trigger(this,y.PRECONFIGURE,a);this._root.removeAllComponents();a.uid&&(this.uid=a.uid);"Scene"!=(a.object_class||a.object_type)&&console.warn("Warning: object set to scene doesnt look like a propper one.",a);a.external_repository&&(this.external_repository=a.external_repository);a.extra&&(this.extra=a.extra);a.root&&(this._spatial_container.clear(),d._pending_encoded_objects=[],
this._root.configure(a.root),d.resolvePendingEncodedObjects());a.global_scripts&&(this.global_scripts=a.global_scripts.concat());a.external_scripts&&(this.external_scripts=a.external_scripts.concat());a.preloaded_resources&&(this.preloaded_resources=d.cloneObject(a.preloaded_resources));a.local_resources&&(this._local_resources=a.local_resources);a.layer_names&&(this.layer_names=a.layer_names.concat());a.animation&&(this.animation=new d.Animation(a.animation));a.editor&&(this._editor=a.editor);a.texture_atlas&&
(this.texture_atlas=a.texture_atlas);LEvent.trigger(this,y.CONFIGURE,a);LEvent.trigger(this,y.AWAKE);LEvent.trigger(this,y.CHANGE)};C.prototype.serialize=function(a){var b={};b.uid=this.uid;b.object_class=d.getObjectClassName(this);b.external_repository=this.external_repository;b.extra=this.extra||{};b.root=this.root.serialize(!1,a);this.animation&&(b.animation=this.animation.serialize());b.layer_names=this.layer_names.concat();b.global_scripts=this.global_scripts.concat();b.external_scripts=this.external_scripts.concat();
b.preloaded_resources=d.cloneObject(this.preloaded_resources);b.texture_atlas=d.cloneObject(this.texture_atlas);b.local_resources=d.cloneObject(this._local_resources);this._editor&&(b.editor=this._editor);LEvent.trigger(this,y.SERIALIZE,b);return b};C.prototype.setFromJSON=function(a,b,c,e,g,f){function h(a){f&&f(p,a);p.init();p.configure(a);p.texture_atlas?d.RM.loadTextureAtlas(p.texture_atlas,k):k()}function k(){p.loadResources(l);LEvent.trigger(p,y.LOAD);d.ResourcesManager.isLoading()||l();b&&
b(p)}function l(){g&&g(p);LEvent.trigger(p,y.LOAD_COMPLETED)}function n(a,b){console.error("Error loading script: "+b);c&&c(a)}if(a){var p=this;if(a.constructor===String)try{a=JSON.parse(a)}catch(m){console.log("Error: "+m);return}e=d.Scene.getScriptsList(a,!0);e.length?this.loadScripts(e,function(){h(a)},n):h(a)}};C.prototype.load=function(a,b,c,e,g,f){function h(b){d.ResourcesManager.processResource(a,b,null,k)}function k(a,b){if(b)if("Scene"==b.object_class)l(b);else if("SceneNode"==b.object_class){var c=
b.serialize();l({object_class:"Scene",root:c})}else b._data&&b._data["scene.json"]?(c=JSON.parse(b._data["scene.json"]),l(c)):console.error("Error loading PACK, doesnt look like it has a valid scene inside")}function l(a){if(a.constructor!==Object)throw"response must be object";var b=d.Scene.getScriptsList(a,!0);b.length?q.loadScripts(b,function(){n(a)},c):n(a)}function n(c){f&&f(q,a);q.init();q.configure(c);b&&b(q,a);q.loadResources(p);LEvent.trigger(q,y.LOAD);d.ResourcesManager.isLoading()||p()}
function p(){g&&g(q,a);LEvent.trigger(q,y.LOAD_COMPLETED)}function m(b){var e=b&&b.target?b.target.status:0;console.warn("Error loading scene: "+a+" -> "+e);c&&c(a,e,b)}if(a){var q=this,s=d.ResourcesManager.getExtension(a),t=d.Formats.getFileFormatInfo(s);t||(t={dataType:"json"});d.Network.request({url:a,nocache:!0,dataType:"json"==s?"json":t.dataType||"text",success:"json"==s?l:h,progress:e,error:m});this._state=d.LOADING;LEvent.trigger(this,"beforeLoad")}};C.prototype.loadFromResources=function(a,
b,c,e,g){a=d.ResourcesManager.getFullURL(a);this.load(a,b,c,e,g)};C.getScriptsList=function(a,b,c){if(!a)throw"Scene.getScriptsList: scene cannot be null";var e=[];a.external_scripts&&a.external_scripts.length&&(e=e.concat(a.external_scripts));if(a.global_scripts&&a.global_scripts.length)for(var g in a.global_scripts){var f=a.global_scripts[g];f&&"js"==d.ResourcesManager.getExtension(f)&&(d.ResourcesManager.getResource(f)&&b&&(f=d.ResourcesManager.cleanFullpath(f)),c&&(f=d.ResourcesManager.getFullURL(f)),
e.push(f))}return e};C.prototype.loadScripts=function(a,b,c,e){function g(){for(var a in h)URL.revokeObjectURL(h[a]);b&&b()}if(d.allow_scripts)if(a=a||d.Scene.getScriptsList(this,!0),a.length)if(d._block_scripts)console.error("Safety: LS.block_scripts enabled, cannot request script");else{var f=[],h=[],k;for(k in a){var l=a[k];if(-1==this.external_scripts.indexOf(l)){var n=d.ResourcesManager.getResource(l);!n||e?(l=d.ResourcesManager.getFullURL(l),f.push(l)):(l=new Blob([n.data],{encoding:"UTF-8",
type:"text/plain;charset=UTF-8"}),l=URL.createObjectURL(l),f.push(l),h.push(l))}else f.push(l)}d.Network.requestScript(f,g,c)}else b&&b();else console.error("LiteScene.allow_scripts is set to false, so scripts imported into this scene are ignored."),b&&b()};C.prototype.checkComponentsCodeModification=function(){for(var a=0;a<this._nodes.length;++a)for(var b=this._nodes[a],c=0;c<b._components.length;++c){var e=b._components[c],g=d.getObjectClassName(e);e.constructor==d.MissingComponent&&(g=e._comp_class);
var f=d.Components[g];if(f&&f!=e.constructor){var h=e.serialize(),f=new f(h),h=b.getIndexOfComponent(e);b.removeComponent(e);b.addComponent(f,h);console.log("Class replaced: "+g)}}};C.prototype.appendScene=function(a){a=a.root.childNodes;for(var b in a){var c=a[b],e=new d.SceneNode(c.id);this.root.addChild(e);e.configure(c.constructor==d.SceneNode?c.serialize():c)}};C.prototype.getCamera=function(){var a=this._root.camera;if(a)return a;if(this._cameras&&this._cameras.length)return this._cameras[0];
this.collectData();return this._cameras[0]};C.prototype.getActiveCameras=function(a){a&&LEvent.trigger(this,y.COLLECT_CAMERAS,this._cameras);return this._cameras};C.prototype.getAllCameras=function(){for(var a=[],b=0;b<this._nodes.length;++b){var c=this._nodes[b].getComponents(d.Components.Camera);c&&c.length&&(a=a.concat(c))}return a};C.prototype.getLight=function(){return this._root.light};C.prototype.getActiveLights=function(a){a&&LEvent.trigger(this,y.COLLECT_LIGHTS,this._lights);return this._lights};
C.prototype.onNodeAdded=function(a,b){if(b._in_tree&&b._in_tree!=this)throw"Cannot add a node from other scene, clone it";b._name&&!this._nodes_by_name[b._name]&&(this._nodes_by_name[b._name]=b);if(!b.uid||this._nodes_by_uid[b.uid])b._uid=d.generateUId("NODE-");this._nodes_by_uid[b.uid]=b;this._nodes.push(b);b.processActionInComponents("onAddedToScene",this);for(var c=0;c<b._components.length;++c)b._components[c].uid?this._components_by_uid[b._components[c].uid]=b._components[c]:console.warn("component without uid?",
b._components[c].uid);LEvent.trigger(this,"nodeAdded",b);LEvent.trigger(this,y.CHANGE)};C.prototype.onNodeRemoved=function(a,b){var c=this._nodes.indexOf(b);if(-1!=c){this._nodes.splice(c,1);b._name&&this._nodes_by_name[b._name]==b&&delete this._nodes_by_name[b._name];b.uid&&delete this._nodes_by_uid[b.uid];b.processActionInComponents("onRemovedFromScene",this);for(c=0;c<b._components.length;++c)delete this._components_by_uid[b._components[c].uid];LEvent.trigger(this,"nodeRemoved",b);LEvent.trigger(this,
y.CHANGE);return!0}};C.prototype.recomputeNodesArray=function(){function a(e){b[c]=e;c+=1;if(e._children&&e._children.length)for(var d=0;d<e._children.length;++d)a(e._children[d])}var b=this._nodes,c=0;a(this._root)};C.prototype.attachSceneElement=function(a){this._spatial_container.add(a)};C.prototype.detachSceneElement=function(a){this._spatial_container.remove(a)};C.prototype.getNodes=function(a){a&&this.recomputeNodesArray();return this._nodes};C.prototype.getNode=function(a){if(""==a)return this.root;
if(!a||a.constructor!==String)return null;if(a.charAt(0)==d._uid_prefix)return this._nodes_by_uid[a];if(-1!=a.indexOf("|")){a=a.split("|");for(var b=this.root,c=0;c<a.length&&b;++c)b=b.getChildByName(a[c]);return b}return this._nodes_by_name[a]};C.prototype.getNodeByName=function(a){return this._nodes_by_name[a]};C.prototype.getNodeByUId=function(a){return this._nodes_by_uid[a]};C.prototype.getNodeByIndex=function(a){return this._nodes[a]};C.prototype.getElementById=C.prototype.getNode;C.prototype.filterNodes=
function(a){for(var b=[],c=0;c<this._nodes.length;++c)a(this._nodes[c])&&b.push(this._nodes[c]);return b};C.prototype.findComponentByUId=function(a){for(var b=0;b<this._nodes.length;++b){var c=this._nodes[b].getComponentByUId(a);if(c)return c}return null};C.prototype.findMaterialByUId=function(a){if(d.RM.materials[a])return d.RM.materials[a];for(var b=0;b<this._nodes.length;++b){var c=this._nodes[b].getMaterial();if(c&&c.uid==a)return c}return null};C.prototype.getPropertyInfo=function(a){a=a.split("/");
var b=a[0].substr(0,5);return"@MAT-"==b?(b=d.RM.materials_by_uid[a[0]])?b.getPropertyInfoFromPath(a.slice(1)):null:"@COMP"==b?(b=this.findComponentByUId(a[0]))?1==a.length?{node:b.root,target:b,name:b?d.getObjectClassName(b):"",type:"component",value:b}:b.getPropertyInfoFromPath(a.slice(1)):null:(b=this.getNode(a[0]))?b.getPropertyInfoFromPath(a.slice(1)):null};C.prototype.getPropertyInfoFromPath=function(a){if("@MAT-"==a[0].substr(0,5)){var b=d.RM.materials_by_uid[a[0]];return b?b.getPropertyInfoFromPath(a.slice(1)):
null}return(b=this.getNode(a[0]))?b.getPropertyInfoFromPath(a.slice(1)):null};C.prototype.getPropertyValue=function(a,b){var c=property_uid.split("/");if("@MAT-"==c[0].substr(0,5)){var e=d.RM.materials_by_uid[c[0]];return e?e.getPropertyValueFromPath(c.slice(1)):null}return(e=this.getNode(c[0]))?e.getPropertyValueFromPath(c.slice(1)):null};C.prototype.getPropertyValueFromPath=function(a){if("@MAT-"==a[0].substr(0,5)){var b=d.RM.materials_by_uid[a[0]];return b?b.getPropertyValueFromPath(a.slice(1)):
null}return(b=this.getNode(a[0]))?b.getPropertyValueFromPath(a.slice(1)):null};C.prototype.setPropertyValue=function(a,b,c){a=a.split("/");this.setPropertyValueFromPath(a,b,c,0)};C.prototype.setPropertyValueFromPath=function(a,b,c,e){e=e||0;if(!(a.length<e+1))return"@MAT-"==a[e].substr(0,5)?(c=d.RM.materials_by_uid[a[e]])?c.setPropertyValueFromPath(a,b,e+1):null:(c=c?c.findNode(a[e]):this.getNode(a[e]))?c.setPropertyValueFromPath(a,b,e+1):null};C.prototype.getResources=function(a,b,c,e){a=a||{};var g=
null;a.constructor===Array&&(g=a,a={},b=!0);if(this.preloaded_resources)for(var f in this.preloaded_resources)a[f]=!0;this.texture_atlas&&(a[this.texture_atlas.filename]=!0);for(f=0;f<this.global_scripts.length;++f)this.global_scripts[f]&&(a[this.global_scripts[f]]=!0);for(f=0;f<this._nodes.length;++f)this._nodes[f].getResources(a);if(c)for(f in a)(c=d.ResourcesManager.resources[f])&&c&&(c.from_prefab||c.from_pack)&&delete a[f];if(e)for(f in a)":"==f[0]&&delete a[f];for(f in a)(c=d.ResourcesManager.resources[f])&&
c.getResources&&c.getResources(a);delete a[""];delete a["null"];if(!b)return a;b=g||[];for(f in a)b.push(f);return b};C.prototype.loadResources=function(a){function b(){LEvent.unbind(d.ResourcesManager,"end_loading_resources",b);a&&a()}var c=this.getResources([]),e=0,g;for(g in c)++e;0==e?a&&a():(LEvent.bind(d.ResourcesManager,"end_loading_resources",b),d.ResourcesManager.loadResources(c))};C.prototype.addPreloadResource=function(a){this.preloaded_resources[a]=!0};C.prototype.removePreloadResource=
function(a){delete this.preloaded_resources[a]};C.prototype.start=function(){this._state!=d.PLAYING&&(this._state=d.PLAYING,this._start_time=0.001*getTime(),LEvent.trigger(this,y.INIT,this),this.triggerInNodes(y.INIT),LEvent.trigger(this,y.START,this),this.triggerInNodes(y.START))};C.prototype.pause=function(){this._state==d.PLAYING&&(this._state=d.PAUSED,LEvent.trigger(this,y.PAUSE,this),this.triggerInNodes(y.PAUSE),this.purgeResidualEvents())};C.prototype.unpause=function(){this._state==d.PAUSED&&
(this._state=d.PLAYING,LEvent.trigger(this,y.UNPAUSE,this),this.triggerInNodes(y.UNPAUSE),this.purgeResidualEvents())};C.prototype.finish=function(){this._state!=d.STOPPED&&(this._state=d.STOPPED,LEvent.trigger(this,y.FINISH,this),this.triggerInNodes(y.FINISH),this.purgeResidualEvents())};C.prototype.collectData=function(a){var b=this._instances,c=this._lights,e=this._colliders;b.length=0;c.length=0;e.length=0;a&&0!=a.length||(a=this._cameras,a.length=0,LEvent.trigger(this,y.COLLECT_CAMERAS,a));var d=
this.getNodes();a=0;for(var f=d.length;a<f;++a){var h=d[a];!1!=h.flags.visible&&(h.transform&&h.transform.updateGlobalMatrix(),h._instances.length=0,LEvent.trigger(h,y.COLLECT_RENDER_INSTANCES,h._instances),LEvent.trigger(h,y.COLLECT_PHYSIC_INSTANCES,e),b.push.apply(b,h._instances))}LEvent.trigger(this,y.COLLECT_RENDER_INSTANCES,b);LEvent.trigger(this,y.COLLECT_PHYSIC_INSTANCES,e);LEvent.trigger(this,y.COLLECT_LIGHTS,c);LEvent.trigger(this,y.COLLECT_DATA);a=0;for(f=b.length;a<f;++a)c=b[a],c.use_bounding&&
c.updateAABB();a=0;for(f=e.length;a<f;++a)e[a].updateAABB();this._last_collect_frame=this._frame};C.prototype.update=function(a){LEvent.trigger(this,"beforeUpdate",this);this._global_time=0.001*getTime();this._time+=a;this._last_dt=a;LEvent.trigger(this,"update",a);if(0<this._fixed_update_timestep)if(this._remaining_fixed_update_time+=a,LEvent.hasBind(this,"fixedUpdate"))for(;this._remaining_fixed_update_time>this._fixed_update_timestep;)LEvent.trigger(this,"fixedUpdate",this._fixed_update_timestep),
this._remaining_fixed_update_time-=this._fixed_update_timestep;else this._remaining_fixed_update_time%=this._fixed_update_timestep;LEvent.trigger(this,"afterUpdate",this)};C.prototype.triggerInNodes=function(a,b){LEvent.triggerArray(this._nodes,a,b)};C.prototype.generateUniqueNodeName=function(a){a=a||"node";var b=1,c=a.lastIndexOf("_");if(c){var e=a.substr(c+1);parseInt(e)&&(b=parseInt(e),a=a.substr(0,c))}for(c=a+"_"+b;null!=this.getNode(c);)c=a+"_"+b++;return c};C.prototype.requestFrame=function(){this._must_redraw=
!0;LEvent.trigger(this,"requestFrame")};C.prototype.refresh=C.prototype.requestFrame;C.prototype.getTime=function(){return this._time};C.prototype.purgeResidualEvents=function(){if(this.__events)for(var a in this.__events){var b=this.__events[a];if(b){for(var c=[],e=0;e<b.length;++e){var g=b[e][1];!g||!d.isClassComponent(g.constructor)||g._root&&g._root.scene===this?c.push(b[e]):console.warn("Event attached to the Scene belongs to a removed node, purged. Event:",a,"Class:",d.getObjectClassName(g))}this.__events[a]=
c}}};C.prototype.getLayerNames=function(a){for(var b=[],c=0;32>c;++c)(void 0===a||a&1<<c)&&b.push(this.layer_names[c]||"layer"+c);return b};C.prototype.findNodeComponents=function(a){if(a){var b=null;if(b=a.constructor===String?d.Components[a]:a){a=[];for(var c=this._nodes,e=0;e<c.length;++e)for(var g=c[e]._components,f=0;f<g.length;++f)g[f].constructor===b&&a.push(g[f]);return a}}};C.prototype.instantiate=function(a,b,c,e){if(!a||a.constructor!==String)throw"prefab must be the url to the prefab";
var g=new d.SceneNode;b&&3===b.length&&(g.transform.position=b);c&&4===c.length&&(g.transform.rotation=c);e=e||this.root;e.addChild(g);g.prefab=a;return g};C.prototype.toPack=function(a,b){var c=d.RM.removeExtension(a||"unnamed_scene",!0)+".SCENE.wbin",e=JSON.stringify(this.serialize());b||(b=this.getResources(null,!0,!0,!0));e=d.Pack.createPack(d.RM.getFilename(c),b,{"scene.json":e});e.fullpath=c;e.category="Scene";return e};C.prototype.updateStaticObjects=function(){var a=d.allow_static;d.allow_static=
!1;this.collectData();d.allow_static=a};C.prototype.findNearestReflectionProbe=function(a){if(!this._reflection_probes.length)return null;if(1==this._reflection_probes.length)return this._reflection_probes[0];for(var b=this._reflection_probes,c=1E6,e=null,d=0;d<b.length;++d){var f=b[d],h=vec3.distance(a,f._position);h>c||(c=h,e=f)}return e};C.prototype.sendResourceRenamedEvent=function(a,b,c){for(var e=0;e<this.external_scripts.length;e++)this.external_scripts[e]==a&&(this.external_scripts[e]=b);
for(e=0;e<this.global_scripts.length;e++)this.global_scripts[e]==a&&(this.global_scripts[e]=b);for(e in this.preloaded_resources)e==a&&(delete this.preloaded_resources[a],this.preloaded_resources[b]=!0);this.texture_atlas&&this.texture_atlas.filename==a&&(this.texture_atlas.filename=b);for(var g=this._nodes.concat(),e=0;e<g.length;e++){var f=g[e];f.prefab&&f.prefab===a&&(f.prefab=b);for(var h=0;h<f._components.length;h++){var k=f._components[h];if(k.onResourceRenamed)k.onResourceRenamed(a,b,c)}f.material&&
(f.material==a?f.material=b:(f=f.getMaterial())&&f.onResourceRenamed?f.onResourceRenamed(a,b,c)&&d.RM.resourceModified(f):console.warn("sendResourceRenamedEvent: Material not found or it didnt have a onResourceRenamed"))}};C.prototype.getDataPath=function(a){return d.RM.cleanFullpath((this.extra.data_folder||this.extra.folder)+"/"+(a||""))};C.prototype.createAnimation=function(){if(this.animation)return this.animation;this.animation=new d.Animation;this.animation.name=d.Animation.DEFAULT_SCENE_NAME;
this.animation.createTake("default",d.Animation.DEFAULT_DURATION);return this.animation};d.Scene=C;d.Classes.Scene=C;d.Classes.SceneTree=C;O.prototype.init=function(a,b){b||(this.layers=3,this._name=name||"node_"+(1E4*Math.random()).toFixed(0),this._uid=d.generateUId("NODE-"),this._classList={},this._material=null,this.extra={},this.node_type=null,this.flags={visible:!0,is_static:!1,selectable:!0});a||(this._components&&this._components.length&&console.warn("SceneNode.init() should not be called if it contains components, call clear instead"),
this._components=[],this.addComponent(new d.Transform))};d.extendClass(O,Ca);d.extendClass(O,oa);Object.defineProperty(O.prototype,"name",{set:function(a){this.setName(a)},get:function(){return this._name},enumerable:!0});Object.defineProperty(O.prototype,"fullname",{set:function(a){throw"You cannot set fullname, it depends on the parent nodes";},get:function(){return this.getPathName()},enumerable:!1});Object.defineProperty(O.prototype,"uid",{set:function(a){a&&(a[0]!=d._uid_prefix&&(console.warn("Invalid UID, renaming it to: "+
a),a=d._uid_prefix+a),a!=this._uid&&(O._last_uid_changed=this._uid,this._in_tree&&this._in_tree._nodes_by_uid[this.uid]&&delete this._in_tree._nodes_by_uid[this.uid],this._uid=a,this._in_tree&&(this._in_tree._nodes_by_uid[this.uid]=this),LEvent.trigger(this,"uid_changed",a),this._in_tree&&LEvent.trigger(this._in_tree,"node_uid_changed",this)))},get:function(){return this._uid},enumerable:!0});Object.defineProperty(O.prototype,"visible",{set:function(a){this.flags.visible=a;if(this._children)for(var b=
0;b<this._children.length;++b)this._children[b].visible=a},get:function(){return this.flags.visible},enumerable:!0});Object.defineProperty(O.prototype,"is_static",{set:function(a){if((this.flags.is_static=a)&&this._children)for(var b=0;b<this._children.length;++b)this._children[b].is_static=a},get:function(){return this.flags.is_static},enumerable:!0});Object.defineProperty(O.prototype,"material",{set:function(a){if(this._material!=a){if(this._material=a){if(a.constructor===String)return;a._root&&
a._root!=this?console.warn("Cannot assign a material of one SceneNode to another, you must clone it or register it"):a._root=this}LEvent.trigger(this,"materialChanged")}},get:function(){return this._material},enumerable:!0});Object.defineProperty(O.prototype,"prefab",{set:function(a){if(this._prefab=a){var b=this;d.RM.getResource(a)?this.reloadFromPrefab():d.ResourcesManager.load(a,function(){b.reloadFromPrefab()})}},get:function(){return this._prefab},enumerable:!0});O.prototype.clear=function(){this.removeAllComponents();
this.removeAllChildren();this.init()};O.prototype.setName=function(a){if(this._name==a)return!0;if(!d.validateName(a))return console.warn("invalid name for node: "+a),!1;var b=this._in_tree;if(!b)return this._name=a,!0;this._name&&delete b._nodes_by_name[this._name];(this._name=a)&&!b._nodes_by_name[a]&&(b._nodes_by_name[this._name]=this);LEvent.trigger(this,"name_changed",a);b&&LEvent.trigger(b,"node_name_changed",this);return!0};Object.defineProperty(O.prototype,"classList",{get:function(){return this._classList},
set:function(a){},enumerable:!1});Object.defineProperty(O.prototype,"className",{get:function(){var a=null;if(Object.keys)a=Object.keys(this._classList);else{var a=[],b;for(b in this._classList)a.push(b)}return a.join(" ")},set:function(a){this._classList={};if(a){a=a.split(" ");for(var b in a)this._classList[a[b]]=!0}},enumerable:!0});O.prototype.destroy=function(a){if(a&&a.constructor===Number&&0<a)setTimeout(this.destroy.bind(this,0),0.001*a);else{LEvent.trigger(this,"destroy");this.removeAllComponents();
if(this.children)for(;this.children.length;)this.children[0].destroy();this._parentNode&&this._parentNode.removeChild(this)}};O.prototype.getLocator=function(a){return a?this.uid+"/"+a:this.uid};O.prototype.getPropertyInfo=function(a){a=a.split("/");return this.getPropertyInfoFromPath(a)};O.prototype.getPropertyInfoFromPath=function(a){var b=this,c=!1;if(0==a.length)return{node:this,target:null,name:"",value:this,type:"node"};if(1==a.length){if("@"==a[0][0])return b=this.getComponentByUId(a[0]),{node:this,
target:b,name:b?d.getObjectClassName(b):"",type:"component",value:b};if("material"==a[0])return b=this.getMaterial(),{node:this,target:b,name:b?d.getObjectClassName(b):"",type:"material",value:b};if("visible"==a[0])return{node:this,target:this,name:"visible",type:"boolean",value:this.visible};if(b=this.getComponent(a[0]))return{node:this,target:b,name:b?d.getObjectClassName(b):"",type:"component",value:b};switch(a[0]){case "matrix":case "x":case "y":case "z":case "position":case "rotX":case "rotY":case "rotZ":b=
this.transform;c=!0;break;default:b=this}}else if(1<a.length&&(b="@"==a[0][0]?this.getComponentByUId(a[0]):"material"==a[0]?this.getMaterial():"flags"==a[0]?this.flags:this.getComponent(a[0]),!b))return null;return b?b!=this&&b.getPropertyInfoFromPath?b.getPropertyInfoFromPath(c?a:a.slice(1)):null:null};O.prototype.getPropertyValue=function(a){a=a.split("/");return this.getPropertyValueFromPath(a)};O.prototype.getPropertyValueFromPath=function(a){var b=this,c=a[0],e=!1;if(0==a.length)return null;
if(1==a.length){if("@"==a[0][0])return this.getComponentByUId(a[0]);if("material"==a[0])return this.getMaterial();if(b=this.getComponent(a[0]))return b;switch(a[0]){case "matrix":case "x":case "y":case "z":case "position":case "rotX":case "rotY":case "rotZ":b=this.transform;c=a[0];e=!0;break;default:b=this,c=a[0]}}else if(1<a.length&&("@"==a[0][0]?(c=a[1],b=this.getComponentByUId(a[0])):"material"==a[0]?(b=this.getMaterial(),c=a[1]):"flags"==a[0]?(b=this.flags,c=a[1]):"visible"==a[0]?(b=this,c=a[0]):
(b=this.getComponent(a[0]),c=a[1]),!b))return null;var d=void 0;if(b.getPropertyValueFromPath&&b!=this){var f=b.getPropertyValueFromPath(e?a:a.slice(1));if(f)return f}b.getPropertyValue&&b!=this&&(d=b.getPropertyValue(c));return void 0===d&&2<a.length&&b[c]&&b[c].getPropertyValueFromPath&&(f=b[c].getPropertyValueFromPath(e?a.slice(1):a.slice(2)))?(f.node=this,f):void 0===d&&void 0===b[c]?null:void 0!==d?d:b[c]};O.prototype.setPropertyValue=function(a,b){var c=a.split("/");return this.setPropertyValueFromPath(c,
b,0)};O.prototype.setPropertyValueFromPath=function(a,b,c){c=c||0;if(!this.flags||!this.flags.locked){var e=null,d=a[c];if(a.length>c+1){if("@"==a[c][0]?(d=a[c+1],e=this.getComponentByUId(a[c])):"material"==a[c]?(e=this.getMaterial(),d=a[c+1]):"flags"==a[c]?(e=this.flags,d=a[c+1]):"visible"==a[c]?(e=this,d=a[c]):(e=this.getComponent(a[c]),d=a[c+1]),!e)return null}else switch(a[c]){case "matrix":e=this.transform;break;case "position":case "rotation":case "x":case "y":case "z":case "xrotation":case "yrotation":case "zrotation":e=
this.transform;d=a[c];break;case "translate.X":e=this.transform;d="x";break;case "translate.Y":e=this.transform;d="y";break;case "translate.Z":e=this.transform;d="z";break;case "rotateX.ANGLE":e=this.transform;d="pitch";break;case "rotateY.ANGLE":e=this.transform;d="yaw";break;case "rotateZ.ANGLE":e=this.transform;d="roll";break;default:e=this}if(!e)return null;if(e.setPropertyValueFromPath&&e!=this&&!0===e.setPropertyValueFromPath(a,b,c+1)||e.setPropertyValue&&e!=this&&!0===e.setPropertyValue(d,
b))return e;if(void 0!==e[d]){if(2<a.length&&e[d]&&e[d].setPropertyValueFromPath)return e[d].setPropertyValueFromPath(a,b,c+2);e[d]=b;return e}}};O.prototype.getResources=function(a,b){for(var c in this._components)this._components[c].getResources&&this._components[c].getResources(a);if(this.material){this.material.constructor===String&&":"!=this.material[0]&&(a[this.material]=d.Material);var e=this.getMaterial();e&&e.getResources(a)}this.prefab&&(a[this.prefab]=d.Prefab);if(b)for(c in this._children)this._children[c].getResources(a,
!0);return a};O.prototype.getTransform=function(){return this.transform};O.prototype.getMesh=function(a){var b=this.mesh,c=this.getComponent(d.Components.MeshRenderer);!b&&c&&(a&&(b=c.lod_mesh),b||(b=c.mesh));return b?b.constructor===String?d.ResourcesManager.meshes[b]:b:null};O.prototype.getLight=function(){return this.light};O.prototype.getCamera=function(){return this.camera};O.prototype.load=function(a,b){var c=this;d.ResourcesManager.load(a,function(a){a&&(c.assign(a),b&&b())})};O.prototype.assign=
function(a,b){if(a){if(a.constructor===String&&(a=d.ResourcesManager.getResource(a)),a)switch(a.constructor){case d.SceneNode:this.addChild(a);break;case d.Scene:var c=this;a.loadScripts(null,function(){a.loadResources(function(){c.addChild(a.root.clone())})});break;case d.Prefab:this.prefab=a.fullpath||a.filename;break;case GL.Mesh:var e=this.getComponent(d.Components.MeshRenderer);e?e.configure({mesh:a.fullpath||a.filename}):this.addComponent(new d.MeshRenderer({mesh:mesh_name,submesh_id:submesh_id}));
break;case d.Animation:(e=this.getComponent(d.Components.PlayAnimation))||(e=this.addComponent(new d.Components.PlayAnimation));e.animation=a.fullpath||a.filename;break;case d.Resource:"js"==d.ResourcesManager.getExtension(a.filename)&&((e=this.getComponent(d.Components.ScriptFromFile))||(e=this.addComponent(new d.Components.ScriptFromFile)),e.src=a.fullpath||a.filename);break;default:console.error("feature not supported loading this type of resource",a)}}else console.error("assignResource cannot have null as resource")};
O.prototype.setMesh=function(a,b){var c=this.getComponent(d.Components.MeshRenderer);c?c.configure({mesh:a,submesh_id:b}):this.addComponent(new d.MeshRenderer({mesh:a,submesh_id:b}))};O.prototype.getMaterial=function(){return this.material?this.material.constructor===String?this._in_tree?"@"==this.material[0]?d.ResourcesManager.materials_by_uid[this.material]:d.ResourcesManager.materials[this.material]:null:this.material:null};O.prototype.reloadFromPrefab=function(){if(this.prefab){var a=d.ResourcesManager.resources[this.prefab];
if(a){if(a.constructor!==d.Prefab)throw"prefab must be a LS.Prefab class";this.removeAllChildren();this.init(!0,!0);var b=a.prefab_data,b={children:a.prefab_data.children};this.configure(b);b=this.getResources({},!0);d.ResourcesManager.loadResources(b);LEvent.trigger(this,"prefabReady",a)}}};O.prototype.setLayer=function(a,b){if(null==a)throw"setLayer expects layer";var c;if(a.constructor===String){if(c=(this.scene||d.GlobalScene).layer_names.indexOf(a),-1==c){console.error("Layer with name:",a,"not found in scene");
return}}else c=a;c=1<<c;this.layers&=~c;b&&(this.layers|=c)};O.prototype.isInLayer=function(a){if(null==a)throw"setLayer expects layer";if(a.constructor===String){var b=(this.scene||d.GlobalScene).layer_names.indexOf(a);if(-1==b){console.error("Layer with name:",a,"not found in scene");return}a=b}return 0!==(this.layers&1<<a)};O.prototype.getLayers=function(){var a=[];if(!this.scene)return a;for(var b=0;32>b;++b)this.layers&1<<b&&a.push(this.scene.layer_names[b]||"layer"+b);return a};O.prototype.insidePrefab=
function(){for(var a=this;a;){if(a.prefab)return a;a=a._parentNode}return null};O.prototype.clone=function(){var a=this._in_tree,a=a?a.generateUniqueNodeName(this._name):this._name,a=new d.SceneNode(a),b=this.serialize();d.clearUIds(b);b.uid=d.generateUId("NODE-");a.configure(b);return a};O.prototype.configure=function(a){a.name?this.setName(a.name):a.id&&this.setName(a.id);void 0!==a.layers&&(this.layers=a.layers);a.uid&&(this.uid=a.uid);a.className&&a.className.constructor==String&&(this.className=
a.className);a.node_type&&(this.node_type=a.node_type,"JOINT"==a.node_type&&(this._is_bone=!0));a.camera&&this.addComponent(new d.Camera(a.camera));a.light&&this.addComponent(new d.Light(a.light));if(a.meshes)for(var b=0;b<a.meshes.length;++b)this.addMeshComponents(a.meshes[b],a);else a.mesh&&this.addMeshComponents(a.mesh,a);(a.position||a.model||a.transform)&&!this.transform&&this.addComponent(new d.Transform);a.position&&(this.transform.position=a.position);a.model&&this.transform.fromMatrix(a.model);
a.matrix&&this.transform.fromMatrix(a.matrix);a.transform&&this.transform.configure(a.transform);if(a.material){var c=a.material.material_class;c&&"newStandardMaterial"!=c||(c="StandardMaterial");var e=d.MaterialClasses[c];e?this.material="string"==typeof a.material?a.material:new e(a.material):console.warn("Material not found: "+c)}if(a.flags)for(b in a.flags)this.flags[b]=a.flags[b];a.animation&&(this.animation=a.animation,this.addComponent(new d.Components.PlayAnimation({animation:this.animation})));
a.extra&&(this.extra=a.extra);a.editor&&(this._editor=a.editor);a.comments&&(this.comments=a.comments);a.components&&this.configureComponents(a);a.prefab&&!this._is_root?this.prefab=a.prefab:this.configureChildren(a);LEvent.trigger(this,"configure",a)};O.prototype.addMeshComponents=function(a,b){b=b||{};if(a){if(a.constructor!==String&&(b=a,a=b.mesh,!a))return console.warn("Mesh info without mesh id"),null;var c=d.ResourcesManager.meshes[a];if(c){var e={mesh:a};void 0!==b.submesh_id&&(e.submesh_id=
b.submesh_id);void 0!==b.morph_targets&&(e.morph_targets=b.morph_targets);void 0!==b.material&&(e.material=b.material);e=new d.Components.MeshRenderer(e);if(c.primitive){switch(c.primitive){case "points":e.primitive=GL.POINTS;break;case "lines":e.primitive=GL.LINES;break;case "line_strip":e.primitive=GL.LINE_STRIP}delete c.primitive}this.addComponent(e);c&&c.bones&&(e=new d.Components.SkinDeformer({search_bones_in_parent:!1}),this.addComponent(e));c&&c.morph_targets&&(e=new d.Components.MorphDeformer({morph_targets:c.morph_targets}),
this.addComponent(e))}else console.warn("SceneNode mesh not found: "+a)}};O.prototype.serialize=function(a,b){var c={object_class:"SceneNode"};this._name&&(c.name=this._name);this.uid&&(c.uid=this.uid);this.className&&(c.className=this.className);c.layers=this.layers;this.node_type&&(c.node_type=this.node_type);this.mesh&&"string"==typeof this.mesh&&(c.mesh=this.mesh);null!=this.submesh_id&&(c.submesh_id=this.submesh_id);this.material&&(c.material="string"==typeof this.material?this.material:this.material.serialize(b));
!this.prefab||a||this._is_root||(c.prefab=this.prefab);this.flags&&(c.flags=d.cloneObject(this.flags));this.extra&&(c.extra=this.extra);this.comments&&(c.comments=this.comments);!this._children||this.prefab&&!a||(c.children=this.serializeChildren(b));this._editor&&(c.editor=this._editor);this.serializeComponents(c,b);LEvent.trigger(this,"serialize",c);return c};O.prototype._onChildAdded=function(a,b){if(b&&this.transform){var c=a.transform.getGlobalMatrix(),e=this.transform.getGlobalMatrix();mat4.invert(e,
e);a.transform.fromMatrix(mat4.multiply(e,e,c));a.transform.getGlobalMatrix()}this.transform&&(a.transform||a.transform.addComponent(new d.Transform),a.transform._parent=this.transform)};O.prototype._onChangeParent=function(a,b){if(b&&a.transform){var c=this.transform.getGlobalMatrix(),e=a.transform.getGlobalMatrix();mat4.invert(e,e);this.transform.fromMatrix(mat4.multiply(e,e,c))}a.transform&&(this.transform._parent=a.transform)};O.prototype._onChildRemoved=function(a,b,c){this.transform&&a.transform&&
(b?(b=a.transform.getGlobalMatrix(),a.transform._parent=null,a.transform.fromMatrix(b)):a.transform._parent=null);c&&a.removeAllComponents()};O.prototype.getBoundingBox=function(a,b){a=a||BBox.create();var c=this._instances;if(c)for(var e=0;e<c.length;++e)0==e?a.set(c[e].aabb):BBox.merge(a,a,c[e].aabb);return b?a:c&&0!=c.length||!this.transform?a:BBox.fromPoint(this.transform.getGlobalPosition())};d.Scene.Node=O;d.SceneNode=O;d.Classes.SceneNode=O;d.Shaders.registerSnippet("surface","\n\t//used to store surface shading properties\n\tstruct SurfaceOutput {\n\t\tvec3 Albedo;\n\t\tvec3 Normal; //separated in case there is a normal map\n\t\tvec3 Emission;\n\t\tvec3 Ambient;\n\t\tfloat Specular;\n\t\tfloat Gloss;\n\t\tfloat Alpha;\n\t\tfloat Reflectivity;\n\t\tvec4 Extra; //for special purposes\n\t};\n\t\n\tSurfaceOutput getSurfaceOutput()\n\t{\n\t\tSurfaceOutput o;\n\t\to.Albedo = u_material_color.xyz;\n\t\to.Alpha = u_material_color.a;\n\t\to.Normal = normalize( v_normal );\n\t\to.Specular = 0.5;\n\t\to.Gloss = 10.0;\n\t\to.Ambient = vec3(1.0);\n\t\to.Emission = vec3(0.0);\n\t\to.Reflectivity = 0.0;\n\t\to.Extra = vec4(0.0);\n\t\treturn o;\n\t}\n");
d.Shaders.registerSnippet("light_structs","\n\t#ifndef SB_LIGHT_STRUCTS\n\t#define SB_LIGHT_STRUCTS\n\tuniform lowp vec4 u_light_info;\n\tuniform vec3 u_light_position;\n\tuniform vec3 u_light_front;\n\tuniform vec3 u_light_color;\n\tuniform vec4 u_light_angle; //cone start,end,phi,theta \n\tuniform vec4 u_light_att; //start,end \n\tuniform float u_light_offset; //ndotl offset\n\tuniform vec4 u_light_extra; //user data\n\tuniform mat4 u_light_matrix; //projection to light screen space\n\tuniform vec3 u_ambient_light;\n\tstruct Light {\n\t\tlowp vec4 Info; //type of light (3: DIRECTIONAL), falloff type, pass index, num passes \n\t\tvec3 Color;\n\t\tvec3 Ambient;\n\t\tvec3 Position;\n\t\tvec3 Front;\n\t\tvec4 ConeInfo; //for spotlights\n\t\tvec4 Attenuation; //start,end,type,extra\n\t\tfloat Offset; //phong_offset\n\t\tvec4 Extra; //users can use this\n\t\tmat4 Matrix; //converts to light space\n\t\tfloat Distance;\n\t};\n\t//Returns the info about the light\n\tLight getLight()\n\t{\n\t\tLight LIGHT;\n\t\tLIGHT.Info = u_light_info;\n\t\tLIGHT.Color = u_light_color;\n\t\tif(u_light_info.z == 0.0)\n\t\t\tLIGHT.Ambient = u_ambient_light;\n\t\telse\n\t\t\tLIGHT.Ambient = vec3(0.0);\n\t\tLIGHT.Position = u_light_position;\n\t\tLIGHT.Front = u_light_front;\n\t\tLIGHT.ConeInfo = u_light_angle; //for spotlights\n\t\tLIGHT.Attenuation = u_light_att; //start and end\n\t\tLIGHT.Offset = u_light_offset;\n\t\tLIGHT.Distance = length( u_light_position - v_pos );\n\t\tLIGHT.Extra = u_light_extra;\n\t\tLIGHT.Matrix = u_light_matrix; //converts to light space\n\t\treturn LIGHT;\n\t}\n\t//used to store light contribution\n\tstruct FinalLight {\n\t\tvec3 Color;\n\t\tvec3 Ambient;\n\t\tfloat Diffuse; //NdotL\n\t\tfloat Specular; //RdotL\n\t\tvec3 Emission;\n\t\tvec3 Reflection;\n\t\tfloat Attenuation;\n\t\tvec3 Vector; //light vector\n\t\tfloat Shadow; //1.0 means fully lit\n\t};\n\t#endif\n");
x._vs_shaderblock_code='\n\t#pragma shaderblock "testShadow"\n';x._enabled_fs_shaderblock_code='\n\t#pragma snippet "input"\n\t#pragma snippet "surface"\n\t#pragma snippet "light_structs"\n\t#pragma snippet "spotFalloff"\n\t#pragma shaderblock "firstPass"\n\t#pragma shaderblock "lastPass"\n\t#pragma shaderblock "applyIrradiance"\n\t#pragma shaderblock "attenuation"\n\t#pragma shaderblock "testShadow"\n\t\n\t//Light is separated in two functions, computeLight (how much light receives the object) and applyLight (compute resulting final color)\n\t// FINAL LIGHT EQUATION, takes all the info from FinalLight and computes the final color \n\t\n\t// HERE we fill FinalLight structure with all the info (colors,NdotL,diffuse,specular,etc) \n\tFinalLight computeLight(in SurfaceOutput o, in Input IN, in Light LIGHT )\n\t{\n\t\tFinalLight FINALLIGHT;\n\t\t// INIT\n\t\tFINALLIGHT.Color = LIGHT.Color;\n\t\t\n\t\t// COMPUTE VECTORS\n\t\tvec3 N = o.Normal; //use the final normal (should be the same as IN.worldNormal)\n\t\tvec3 E = (u_camera_eye - v_pos);\n\t\tfloat cam_dist = length(E);\n\t\tE /= cam_dist;\n\t\t\n\t\tvec3 L = (LIGHT.Position - v_pos) / LIGHT.Distance;\n\t\t\n\t\tif( LIGHT.Info.x == 3.0 )\n\t\t\tL = -LIGHT.Front;\n\t\t\n\t\tFINALLIGHT.Vector = L;\n\t\tvec3 R = reflect(E,N);\n\t\t\n\t\t// IRRADIANCE\n\t\t#ifdef BLOCK_FIRSTPASS\n\t\t\tFINALLIGHT.Ambient = LIGHT.Ambient;\n\t\t\tapplyIrradiance( IN, o, FINALLIGHT );\n\t\t#endif\n\t\t// PHONG FORMULA\n\t\tfloat NdotL = 1.0;\n\t\tNdotL = dot(N,L);\n\t\tfloat EdotN = dot(E,N); //clamp(dot(E,N),0.0,1.0);\n\t\tNdotL = NdotL + LIGHT.Offset;\n\t\tNdotL = max( 0.0, NdotL );\n\t\tFINALLIGHT.Diffuse = abs(NdotL);\n\t\tFINALLIGHT.Specular = o.Specular * pow( clamp(dot(R,-L),0.001,1.0), o.Gloss );\n\t\t\n\t\t// ATTENUATION\n\t\tFINALLIGHT.Attenuation = 1.0;\n\t\t\n\t\t#ifdef BLOCK_ATTENUATION\n\t\t\tFINALLIGHT.Attenuation = computeAttenuation( LIGHT );\n\t\t#endif\n\t\tif( LIGHT.Info.x == 2.0 && LIGHT.Info.y == 1.0 )\n\t\t\tFINALLIGHT.Attenuation *= spotFalloff( LIGHT.Front, normalize( LIGHT.Position - v_pos ), LIGHT.ConeInfo.z, LIGHT.ConeInfo.w );\n\t\t\n\t\t// SHADOWS\n\t\tFINALLIGHT.Shadow = 1.0;\n\t\t#ifdef BLOCK_TESTSHADOW\n\t\t\tFINALLIGHT.Shadow = testShadow( LIGHT );\n\t\t#endif\n\t\t\n\t\t// LIGHT MODIFIERS\n\t\t#ifdef LIGHT_MODIFIER\n\t\t#endif\n\t\t// FINAL LIGHT FORMULA ************************* \n\t\treturn FINALLIGHT;\n\t}\n\t//here we apply the FINALLIGHT to the SurfaceOutput\n\tvec3 applyLight( in SurfaceOutput o, in FinalLight FINALLIGHT )\n\t{\n\t\tvec3 total_light = FINALLIGHT.Ambient * o.Ambient + FINALLIGHT.Color * FINALLIGHT.Diffuse * FINALLIGHT.Attenuation * FINALLIGHT.Shadow;\n\t\tvec3 final_color = o.Albedo * total_light;\n\t\t#ifdef BLOCK_FIRSTPASS\n\t\tfinal_color += o.Emission;\n\t\t#endif\n\t\tfinal_color\t+= o.Albedo * (FINALLIGHT.Color * FINALLIGHT.Specular * FINALLIGHT.Attenuation * FINALLIGHT.Shadow);\n\t\treturn max( final_color, vec3(0.0) );\n\t}\n\t\n\t//all done in one single step\n\tvec3 processLight(in SurfaceOutput o, in Input IN, in Light LIGHT)\n\t{\n\t\tFinalLight FINALLIGHT = computeLight( o, IN,LIGHT );\n\t\treturn applyLight(o,FINALLIGHT);\n\t}\n\t\n';
x._disabled_shaderblock_code='\n\t#pragma shaderblock "firstPass"\n\t#pragma shaderblock "lastPass"\n\t#pragma snippet "input"\n\t#pragma snippet "surface"\n\t#pragma snippet "light_structs"\n\t#pragma shaderblock "applyIrradiance"\n\tFinalLight computeLight( in SurfaceOutput o, in Input IN, in Light LIGHT )\n\t{\n\t\tFinalLight FINALLIGHT;\n\t\tFINALLIGHT.Ambient = LIGHT.Ambient;\n\t\tFINALLIGHT.Diffuse = 0.0;\n\t\tFINALLIGHT.Specular = 0.0;\n\t\tFINALLIGHT.Attenuation = 0.0;\n\t\tFINALLIGHT.Shadow = 0.0;\n\t\tapplyIrradiance( IN, o, FINALLIGHT );\n\t\treturn FINALLIGHT;\n\t}\n\tvec3 applyLight( in SurfaceOutput o, in FinalLight FINALLIGHT )\n\t{\n\t\tvec3 final_color = o.Albedo * o.Ambient * FINALLIGHT.Ambient;\n\t\t#ifdef BLOCK_FIRSTPASS\n\t\tfinal_color += o.Emission;\n\t\t#endif\n\t\treturn final_color;\n\t}\n\t\n\t//all done in one single step\n\tvec3 processLight(in SurfaceOutput o, in Input IN, in Light LIGHT)\n\t{\n\t\tFinalLight FINALLIGHT = computeLight( o, IN,LIGHT );\n\t\treturn applyLight(o,FINALLIGHT);\n\t}\n\t\n';
var $b=new d.ShaderBlock("light");$b.addCode(GL.VERTEX_SHADER,x._vs_shaderblock_code,x._vs_shaderblock_code);$b.addCode(GL.FRAGMENT_SHADER,x._enabled_fs_shaderblock_code,x._disabled_shaderblock_code);$b.register();x.shader_block=$b;x._attenuation_enabled_fragment_code="\n\tconst float LINEAR_ATTENUATION = 1.0;\n\tconst float RANGE_ATTENUATION = 2.0;\n\tfloat computeAttenuation( in Light LIGHT )\n\t{\n\t\t//no attenuation\n\t\tif(LIGHT.Attenuation.z == 0.0)\n\t\t\treturn 1.0;\n\t\t//directional light\n\t\tif( LIGHT.Info.x == 3.0 )\n\t\t\treturn 1.0;\n\t\tif( LIGHT.Attenuation.z == LINEAR_ATTENUATION )\n\t\t\treturn 10.0 / LIGHT.Distance;\n\t\tif( LIGHT.Attenuation.z == RANGE_ATTENUATION )\n\t\t{\n\t\t\tif(LIGHT.Distance >= LIGHT.Attenuation.y)\n\t\t\t\treturn 0.0;\n\t\t\tif(LIGHT.Distance >= LIGHT.Attenuation.x)\n\t\t\t\treturn 1.0 - (LIGHT.Distance - LIGHT.Attenuation.x) / (LIGHT.Attenuation.y - LIGHT.Attenuation.x);\n\t\t}\n\t\treturn 1.0;\n\t}\n";
x._attenuation_disabled_fragment_code="";var tc=x.attenuation_block=new d.ShaderBlock("attenuation");tc.addCode(GL.FRAGMENT_SHADER,x._attenuation_enabled_fragment_code,x._attenuation_disabled_fragment_code);tc.register();x._light_texture_fragment_enabled_code="\nuniform sampler2D light_texture;\nvoid applyLightTexture( in Input IN, inout Light LIGHT )\n{\n\tvec4 v = LIGHT.Matrix * vec4( IN.worldPos,1.0 );\n\tvec2 uv = v.xy / v.w * 0.5 + vec2(0.5);\n\tLIGHT.Color *= texture2D( light_texture, uv ).xyz;\n}\n";
x._light_texture_fragment_disabled_code="\nvoid applyLightTexture( in Input IN, inout Light LIGHT )\n{\n}\n";var uc=x.light_texture_block=new d.ShaderBlock("light_texture");uc.addCode(GL.FRAGMENT_SHADER,x._light_texture_fragment_enabled_code,x._light_texture_fragment_disabled_code);uc.register();var Rb=new d.ShaderBlock("environment_cubemap");Rb.addCode(GL.FRAGMENT_SHADER,"\n\t#ifdef ENVIRONMENT_TEXTURE\n\t\tuniform sampler2D environment_texture;\n\t#endif\n\t#ifdef ENVIRONMENT_PLANAR\n\t\tuniform sampler2D environment_texture;\n\t#endif\n\t#ifdef ENVIRONMENT_CUBEMAP\n\t\tuniform samplerCube environment_texture;\n\t#endif\n\tvec2 polarToCartesian(in vec3 V)\n\t{\n\t\treturn vec2( 0.5 - (atan(V.z, V.x) / -6.28318531), asin(V.y) / 1.57079633 * 0.5 + 0.5);\n\t}\n\t\n\tvec3 getEnvironmentColor( vec3 V, float area )\n\t{\n\t\t#ifdef ENVIRONMENT_TEXTURE\n\t\t\tvec2 uvs = polarToCartesian(V);\n\t\t\treturn texture2D( environment_texture, uvs ).xyz;\n\t\t#endif\n\t\t#ifdef ENVIRONMENT_CUBEMAP\n\t\t\treturn textureCube( environment_texture, -V ).xyz;\n\t\t#endif\n\t\treturn u_background_color.xyz;\n\t}\n",
"\n\tvec3 getEnvironmentColor( vec3 V, float area )\n\t{\n\t\treturn u_background_color.xyz;\n\t}\n",{ENVIRONMENT_CUBEMAP:""});Rb.defineContextMacros({ENVIRONMENTBLOCK:"environment_cubemap"});Rb.register();var Qb=new d.ShaderBlock("environment_2D");Qb.defineContextMacros({ENVIRONMENTBLOCK:"environment_2D"});Qb.addCode(GL.FRAGMENT_SHADER,"\n\t#ifdef ENVIRONMENT_TEXTURE\n\t\tuniform sampler2D environment_texture;\n\t#endif\n\t#ifdef ENVIRONMENT_PLANAR\n\t\tuniform sampler2D environment_texture;\n\t#endif\n\t#ifdef ENVIRONMENT_CUBEMAP\n\t\tuniform samplerCube environment_texture;\n\t#endif\n\tvec2 polarToCartesian(in vec3 V)\n\t{\n\t\treturn vec2( 0.5 - (atan(V.z, V.x) / -6.28318531), asin(V.y) / 1.57079633 * 0.5 + 0.5);\n\t}\n\t\n\tvec3 getEnvironmentColor( vec3 V, float area )\n\t{\n\t\t#ifdef ENVIRONMENT_TEXTURE\n\t\t\tvec2 uvs = polarToCartesian(V);\n\t\t\treturn texture2D( environment_texture, uvs ).xyz;\n\t\t#endif\n\t\t#ifdef ENVIRONMENT_CUBEMAP\n\t\t\treturn textureCube( environment_texture, -V ).xyz;\n\t\t#endif\n\t\treturn u_background_color.xyz;\n\t}\n",
"\n\tvec3 getEnvironmentColor( vec3 V, float area )\n\t{\n\t\treturn u_background_color.xyz;\n\t}\n",{ENVIRONMENT_TEXTURE:""});Qb.register();var Pb=new d.ShaderBlock("environment_planar");Pb.defineContextMacros({ENVIRONMENTBLOCK:"environment_planar"});Pb.addCode(GL.FRAGMENT_SHADER,"\n\t#ifdef ENVIRONMENT_TEXTURE\n\t\tuniform sampler2D environment_texture;\n\t#endif\n\t#ifdef ENVIRONMENT_PLANAR\n\t\tuniform sampler2D environment_texture;\n\t#endif\n\t#ifdef ENVIRONMENT_CUBEMAP\n\t\tuniform samplerCube environment_texture;\n\t#endif\n\tvec2 polarToCartesian(in vec3 V)\n\t{\n\t\treturn vec2( 0.5 - (atan(V.z, V.x) / -6.28318531), asin(V.y) / 1.57079633 * 0.5 + 0.5);\n\t}\n\t\n\tvec3 getEnvironmentColor( vec3 V, float area )\n\t{\n\t\t#ifdef ENVIRONMENT_TEXTURE\n\t\t\tvec2 uvs = polarToCartesian(V);\n\t\t\treturn texture2D( environment_texture, uvs ).xyz;\n\t\t#endif\n\t\t#ifdef ENVIRONMENT_CUBEMAP\n\t\t\treturn textureCube( environment_texture, -V ).xyz;\n\t\t#endif\n\t\treturn u_background_color.xyz;\n\t}\n",
"\n\tvec3 getEnvironmentColor( vec3 V, float area )\n\t{\n\t\treturn u_background_color.xyz;\n\t}\n",{ENVIRONMENT_PLANAR:""});Pb.register();var vc=new d.ShaderBlock("environment");vc.addCode(GL.FRAGMENT_SHADER,"\n\t#ifdef ENVIRONMENT_TEXTURE\n\t\tuniform sampler2D environment_texture;\n\t#endif\n\t#ifdef ENVIRONMENT_PLANAR\n\t\tuniform sampler2D environment_texture;\n\t#endif\n\t#ifdef ENVIRONMENT_CUBEMAP\n\t\tuniform samplerCube environment_texture;\n\t#endif\n\tvec2 polarToCartesian(in vec3 V)\n\t{\n\t\treturn vec2( 0.5 - (atan(V.z, V.x) / -6.28318531), asin(V.y) / 1.57079633 * 0.5 + 0.5);\n\t}\n\t\n\tvec3 getEnvironmentColor( vec3 V, float area )\n\t{\n\t\t#ifdef ENVIRONMENT_TEXTURE\n\t\t\tvec2 uvs = polarToCartesian(V);\n\t\t\treturn texture2D( environment_texture, uvs ).xyz;\n\t\t#endif\n\t\t#ifdef ENVIRONMENT_CUBEMAP\n\t\t\treturn textureCube( environment_texture, -V ).xyz;\n\t\t#endif\n\t\treturn u_background_color.xyz;\n\t}\n",
"\n\tvec3 getEnvironmentColor( vec3 V, float area )\n\t{\n\t\treturn u_background_color.xyz;\n\t}\n");vc.register();var lc=new d.ShaderBlock("applyReflection");K.reflection_block=lc;lc.addCode(GL.FRAGMENT_SHADER,'\n\t#pragma shaderblock ENVIRONMENTBLOCK "environment"\n\t\n\tvec4 applyReflection( Input IN, SurfaceOutput o, vec4 final_color )\n\t{\n\t\tvec3 R = reflect( IN.viewDir, o.Normal );\n\t\tvec3 bg = vec3(0.0);\n\t\t//is last pass for this object?\n\t\t#ifdef BLOCK_LASTPASS\n\t\t\t#ifdef ENVIRONMENT_PLANAR\n\t\t\t\tvec2 screen_uv = gl_FragCoord.xy / u_viewport.zw;\n\t\t\t\tscreen_uv.x = 1.0 - screen_uv.x;\n\t\t\t\tscreen_uv.xy += (u_view * vec4(o.Normal - IN.worldNormal, 0.0)).xy * 0.1;\n\t\t\t\tbg = texture2D( environment_texture, screen_uv ).xyz;\n\t\t\t#else\n\t\t\t\tbg = getEnvironmentColor( R, 0.0 );\n\t\t\t#endif\n\t\t#endif\n\t\tfinal_color.xyz = mix( final_color.xyz, bg, clamp( o.Reflectivity, 0.0, 1.0) );\n\t\treturn final_color;\n\t}\n',
"\n\tvec4 applyReflection( Input IN, SurfaceOutput o, vec4 final_color )\n\t{\n\t\treturn final_color;\n\t}\n");lc.register();Kb="\n\tvoid applyIrradiance( in Input IN, in SurfaceOutput o, inout FinalLight FINALLIGHT )\n\t{\n\t}\n";d.Shaders.getShaderBlock("applyIrradiance")||(zb=new d.ShaderBlock("applyIrradiance"),K.irradiance_block=zb,zb.addCode(GL.FRAGMENT_SHADER,Kb,Kb),zb.register());Object.defineProperty(ma.prototype,"file_drop_enabled",{set:function(a){this.setFileDrop(a)},get:function(){return this._file_drop_enabled},
enumerable:!0});ma.prototype.loadConfig=function(a,b,c){var e=this;d.Network.requestJSON(a,function(a){e.configure(a,c);b&&b(a)})};ma.prototype.configure=function(a,b){this.skip_play_button=void 0!==a.skip_play_button?a.skip_play_button:!1;this.autoplay=void 0!==a.autoplay?a.autoplay:!0;a.debug?this.enableDebug():this.enableDebug(!1);void 0!==a.resources&&d.ResourcesManager.setPath(a.resources);a.proxy&&d.ResourcesManager.setProxy(a.proxy);if(a.filesystems)for(var c in a.filesystems)d.ResourcesManager.registerFileSystem(c,
a.filesystems[c]);a.allow_base_files&&(d.ResourcesManager.allow_base_files=a.allow_base_files);a.autoresize&&!this._resize_callback&&(this._resize_callback=function(){this.canvas.width=this.canvas.parentNode.offsetWidth;this.canvas.height=this.canvas.parentNode.offsetHeight}.bind(this),window.addEventListener("resize",this._resize_callback));a.loadingbar?this.loading||this.enableLoadingBar():!1===a.loadingbar&&(this.loading=null);this.force_redraw=a.redraw||!1;a.debug_render&&this.setDebugRender(!0);
a.scene_url&&this.loadScene(a.scene_url,b)};ma.STOPPED=0;ma.PLAYING=1;ma.PAUSED=2;ma.prototype.loadScene=function(a,b,c){var e=this,d=this.scene;this.loading&&(this.loading.visible=!0);d.load(a,null,null,function(a){if(null!=e.loading){var b=0;a.total&&(b=a.loaded/a.total);e.loading.scene_loaded=b;c&&c(b)}},function(){e.autoplay?e.play():e.skip_play_button||e.showPlayDialog();e.loading&&(e.loading.visible=!1);e._ondraw(!0);b&&b()})};ma.prototype.setScene=function(a,b,c){function e(){h.configure(a);
h.loadResources(g)}function g(){f.loading.visible=!1;c&&c(h);f.autoplay&&f.play();h._must_redraw=!0;console.log("Scene playing");b&&b(h)}var f=this,h=this.scene;this.state==d.Player.PLAYING&&this.stop();h.clear();a&&a.constructor===String&&(a=JSON.parse(a));var k=d.Scene.getScriptsList(a);k&&k.length?(h.clear(),h.loadScripts(k,e)):e()};ma.prototype.pause=function(){this.state=d.Player.PAUSED};ma.prototype.play=function(){this.state!=d.Player.PLAYING&&(this.debug&&console.log("Start"),this.state=d.Player.PLAYING,
d.Input&&d.Input.reset(),d.GUI&&d.GUI.reset(),this.scene.start())};ma.prototype.stop=function(){this.state=d.Player.STOPPED;this.scene.finish();d.GUI&&d.GUI.reset()};ma.prototype.clear=function(){d.Input&&d.Input.reset();d.GUI&&d.GUI.reset();this.scene.clear()};ma.prototype.setFileDrop=function(a){function b(a){a.stopPropagation();a.preventDefault()}function c(a){d.addEventListener("dragexit",this._onDragStop);d.addEventListener("dragover",this._onDragStop);d.addEventListener("drop",this._onDrop);
a.stopPropagation();a.preventDefault()}function e(a){a.stopPropagation();a.preventDefault();d.removeEventListener("dragexit",this._onDragStop);d.removeEventListener("dragover",this._onDragStop);d.removeEventListener("drop",this._onDrop);if(a.dataTransfer.files.length)for(var b=0;b<a.dataTransfer.files.length;++b)!1===this._onfiledrop(a.dataTransfer.files[b],a)&&(a.stopPropagation(),a.stopImmediatePropagation())}if(this._file_drop_enabled!=a){var d=this.canvas;a?(this._file_drop_enabled=a,this._onDrag=
c.bind(this),this._onDrop=e.bind(this),this._onDragStop=b.bind(this),d.addEventListener("dragenter",this._onDrag)):d.removeEventListener("dragenter",this._onDrag)}};ma.prototype.enableLoadingBar=function(){this.loading={visible:!0,scene_loaded:0,resources_loaded:0};LEvent.bind(d.ResourcesManager,"start_loading_resources",function(a,b){this.loading&&(this.loading.resources_loaded=0)}.bind(this));LEvent.bind(d.ResourcesManager,"loading_resources_progress",function(a,b){this.loading&&this.loading.resources_loaded<
b&&(this.loading.resources_loaded=b)}.bind(this));LEvent.bind(d.ResourcesManager,"end_loading_resources",function(a,b){this.loading&&(this._total_loading=void 0,this.loading.resources_loaded=1,this.loading.visible=!1)}.bind(this))};ma.prototype._onfiledrop=function(a,b){return LEvent.trigger(d.GlobalScene,"fileDrop",{file:a,event:b})};ma.prototype.showPlayDialog=function(){var a=document.createElement("div");a.style.width="128px";a.style.position="absolute";a.style.top=(0.5*this.canvas.offsetHeight-
64|0)+"px";a.style.left=(0.5*this.canvas.offsetWidth-64|0)+"px";a.style.cursor="pointer";a.style.borderRadius="10px";a.style.backgroundColor="rgba(0,0,0,0.5)";a.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128"><circle fill="#3bd0bc" cx="64" cy="64" r="50"/><polygon id="play-button-triangle" name="play-button-triangle" fill="#FFFFFF" points="42,32 100,64, 42,96"/></svg>';this.canvas.parentNode.appendChild(a);var b=this;a.addEventListener("click",function(){console.log("play!");
this.parentNode.removeChild(this);b.play()})};ma.prototype._ondraw=function(a){var b=this.scene;if(this.state==d.Player.PLAYING||a){if(this.onPreDraw)this.onPreDraw();if(b._must_redraw||this.force_redraw)this.renderer._in_player=!0,this.renderer.render(b,b.info&&b.info.render_settings?b.info.render_settings:this.render_settings);if(this.onDraw)this.onDraw()}if(this.loading&&this.loading.visible&&(this.renderLoadingBar(this.loading),LEvent.trigger(this.scene,"render_loading"),this.onDrawLoading))this.onDrawLoading()};
ma.prototype._onupdate=function(a){if(this.state==d.Player.PLAYING){d.Tween&&d.Tween.update(a);d.Input&&d.Input.update(a);if(this.onPreUpdate)this.onPreUpdate(a);this.scene.update(a);if(this.onUpdate)this.onUpdate(a)}};ma.prototype._onmouse=function(a){if((!d.Input||!0!=d.Input.onMouse(a))&&this.state==d.Player.PLAYING&&(LEvent.trigger(this.scene,a.eventType||a.type,a,!0),this.onMouse))this.onMouse(a)};ma.prototype._ontouch=function(a){if(this.state==d.Player.PLAYING){if(!0===LEvent.trigger(this.scene,
a.eventType||a.type,a,!0))return!1;if(this.onTouch)this.onTouch(a)}};ma.prototype._onkey=function(a){if(d.Input)d.Input.onKey(a);this.state!=d.Player.PLAYING||this.onKey&&this.onKey(a)||LEvent.trigger(this.scene,a.eventType||a.type,a)};ma.prototype._ongamepad=function(a){this.state!=d.Player.PLAYING||this.onGamepad&&this.onGamepad(a)||LEvent.trigger(this.scene,a.eventType||a.type,a)};ma.prototype.renderLoadingBar=function(a){a&&da.enableWebGLCanvas&&(gl.canvas.canvas2DtoWebGL_enabled||enableWebGLCanvas(gl.canvas),
gl.start2D(),gl.fillColor=[0,0,0,1],gl.fillRect(0,0,gl.drawingBufferWidth,8),gl.fillColor=a.bar_color||[0.5,0.9,1,1],gl.fillRect(0,0,gl.drawingBufferWidth*a.scene_loaded,4),gl.fillColor=a.bar_color||[0.9,0.5,1,1],gl.fillRect(0,4,gl.drawingBufferWidth*a.resources_loaded,4),gl.finish2D())};ma.prototype.enableDebug=function(a){this.debug=!!a;d.Script.catch_important_exceptions=!a;d.catch_exceptions=!a};ma.prototype.setDebugRender=function(a){if(!this.debug_render){if(!a)return;this.debug_render=new d.DebugRender}a?
this.debug_render.enable():this.debug_render.disable()};d.Player=ma;d.Formats.addSupportedFormat("dds",{extension:"dds",type:"image",dataType:"arraybuffer",resource:"Texture",format:"binary",parse:function(a,b){if(!a||a.constructor!==ArrayBuffer)throw"ParserDDS: data must be ArrayBuffer";var c=gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),d=new GL.Texture(0,0,b);if(!window.DDS)throw"dds.js script must be included, not found";DDS.loadDDSTextureFromMemoryEx(gl,c,a,d,!0);return d}});d.Formats.addSupportedFormat("obj",
{extension:"obj",type:"mesh",resource:"Mesh",format:"text",dataType:"text",flipAxis:!1,parse:function(a,b){function c(a){var b,c,d,e=!1;if(-1==a.indexOf("-")){var g=u.get(a);if(void 0!==g)return g}else e=!0;d||(d=a.split("/"));if(1==d.length)d=c=b=parseInt(d[0]);else if(2==d.length)b=parseInt(d[0]),c=parseInt(d[1]),d=b;else if(3==d.length)b=parseInt(d[0]),c=parseInt(d[1]),d=parseInt(d[2]);else return console.log("Problem parsing: unknown number of values per face"),-1;0>b&&(b=f.length/3+b+1);0>d&&
(d=h.length/2+d+1);0>c&&(c=k.length/2+c+1);if(e&&(a=b+"/"+c+"/"+d,g=u.get(a),void 0!==g))return g;b-=1;c-=1;d-=1;l.push(f[3*b+0],f[3*b+1],f[3*b+2]);k.length&&p.push(k[2*c+0],k[2*c+1]);h.length&&n.push(h[3*d+0],h[3*d+1],h[3*d+2]);g=H;u.set(a,g);++H;return g}function d(a){a={name:a||"",material:"",start:-1,length:-1,indices:[]};m.push(a);return a}function g(a){if(!t.material)return t.material=a+".json",q[a]=t;var b=q[a];b||(b=d(s+"_"+a),b.material=a+".json",q[a]=b);return t=b}for(var f=[],h=[],k=[],
l=[],n=[],p=[],m=[],q={},s=null,t=d(),u=new Map,H=0,G={v:1,vt:2,vn:3,f:4,g:5,o:6,usemtl:7,mtllib:8},r,v,w,y=a.split("\n"),x=y.length,B=0;B<x;++B){var A=y[B],A=A.replace(/[ \t]+/g," ").replace(/\s\s*$/,"");if("\\"==A[A.length-1])var B=B+1,C=y[B].replace(/[ \t]+/g," ").replace(/\s\s*$/,""),A=(A.substr(0,A.length-1)+C).replace(/[ \t]+/g," ").replace(/\s\s*$/,"");if("#"!=A[0]&&""!=A)switch(C=A.split(" "),A=G[C[0]],3>=A&&(r=parseFloat(C[1]),v=parseFloat(C[2]),2!=A&&(w=parseFloat(C[3]))),A){case 1:f.push(r,
v,w);break;case 2:k.push(r,v);break;case 3:h.push(r,v,w);break;case 4:if(4>C.length)continue;for(var z=[],A=1;A<C.length;++A)z.push(c(C[A]));t.indices.push(z[0],z[1],z[2]);for(A=2;A<z.length-1;++A)t.indices.push(z[0],z[A],z[A+1]);break;case 5:case 6:s=A=C[1];t.name?(q={},t=d(A)):t.name=A;break;case 7:g(C[1])}}G=[];r=0;v=[];for(A=0;A<m.length;++A)t=m[A],t.indices&&(t.start=r,t.length=t.indices.length,G=G.concat(t.indices),delete t.indices,r+=t.length,v.push(t));m=v;v={};if(!f.length)return console.error("mesh without vertices"),
null;v.vertices=new Float32Array(l);n.length&&(v.normals=new Float32Array(n));p.length&&(v.coords=new Float32Array(p));G&&0<G.length&&(v.triangles=new (65536<r?Uint32Array:Uint16Array)(G));v.bounding=GL.Mesh.computeBoundingBox(v.vertices);G={};1<m.length&&(G.groups=m);v.info=G;if(!v.bounding)return console.log("empty mesh"),null;(0==v.bounding.radius||isNaN(v.bounding.radius))&&console.log("no radius found in mesh");return v}});d.Formats.addSupportedFormat("mtl",{extension:"mtl",type:"material",resource:"StandardMaterial",
format:"text",dataType:"text",parse:function(a,b){function c(a){return[parseFloat(a[1]),parseFloat(a[2]),parseFloat(a[3])]}for(var e=a.split("\n"),g=e.length,f={},h=null,k=0;k<g;++k){var l=e[k].replace(/[ \t]+/g," ").replace(/\s\s*$/,""),l=l.trim();if("#"!=l[0]&&""!=l){var l=l.split(" "),n=l[0];switch(n){case "newmtl":l=l[1]+".json";h={filename:l,textures:{}};f[l]=h;break;case "Ka":h.ambient=c(l);break;case "Kd":h.color=c(l);break;case "Ks":h.specular_factor=parseFloat(l[1]);break;case "Ke":h.emissive=
c(l);break;case "Ns":h.specular_gloss=parseFloat(l[1]);break;case "Tr":h.reflection=parseFloat(l[1]);break;case "map_Kd":h.textures.color=this.clearPath(l[1]);h.color=[1,1,1];break;case "map_Ka":h.textures.ambient=this.clearPath(l[1]);h.ambient=[1,1,1];break;case "map_Ks":h.textures.specular=this.clearPath(l[1]);h.specular_factor=1;break;case "map_d":h.textures.opacity=this.clearPath(l[1]);h.blend_mode=d.Blend.ALPHA;break;case "bump":case "map_bump":h.textures.bump=this.clearPath(l[1]);break;case "d":h.opacity=
parseFloat(l[1]);break;case "Tr":h.opacity=parseFloat(l[1]);break;case "illum":case "Tf":case "Ni":break;default:console.log("Unknown MTL info: ",n)}}}for(var p in f)e=f[p],e.ambient=[1,1,1],g=new d.StandardMaterial(e),d.RM.registerResource(e.filename,g);return null},clearPath:function(a){var b=a.lastIndexOf("\\");-1!=b&&(a=a.substr(b+1));a=d.RM.getFilename(a);d.RM.resources_renamed_recently[a]&&(a=d.RM.resources_renamed_recently[a]);return a.toLowerCase()}});d.Formats.addSupportedFormat("stl",{extension:"stl",
type:"mesh",format:"binary",dataType:"arraybuffer",parse:function(a,b){var c=[],e=[],g=[],f=new DataView(a,80),h=f.getUint32(0,!0);console.log("number of triangles: "+h);for(var k=4,l=vec3.create(),n=vec3.create(),p=vec3.create(),m=vec3.create(),q=0;q<h;q++){for(var s=f.getFloat32(k,!0),t=f.getFloat32(k+4,!0),u=f.getFloat32(k+8,!0),k=k+12,H=0;3>H;H++){var r=f.getFloat32(k,!0),v=f.getFloat32(k+4,!0),w=f.getFloat32(k+8,!0);c.push(r,w,-v);k+=12}0==s&&0==t&&0==u&&(s=c.length,l.set(c.slice(s-9,s-6)),n.set(c.slice(s-
6,s-3)),p.set(c.slice(s-3,s)),vec3.sub(n,n,l),vec3.sub(p,p,l),vec3.cross(m,p,n),s=m[0],t=m[1],u=m[2]);e.push(s,u,-t,s,u,-t,s,u,-t);k+=2}f={info:{}};f.vertices=new Float32Array(c);0<e.length&&(f.normals=new Float32Array(e));g&&0<g.length&&(f.triangles=new Uint16Array(g));f.bounding=d.Formats.computeMeshBounding(f.vertices);return f}});d.Formats.addSupportedFormat("tga",{extension:"tga",type:"image",dataType:"arraybuffer",format:"binary",parse:function(a,b){if(!a||a.constructor!==ArrayBuffer)throw"ParserTGA: data must be ArrayBuffer";
a=new Uint8Array(a);for(var c=new Uint8Array([0,0,2,0,0,0,0,0,0,0,0,0]),d=a.subarray(0,12),g=0;g<d.length;g++)if(c[g]!=d[g])return console.error("TGA header is not valid"),null;g=a.subarray(12,18);c={};c.width=256*g[1]+g[0];c.height=256*g[3]+g[2];c.bpp=g[4];c.bytesPerPixel=c.bpp/8;c.imageSize=c.width*c.height*c.bytesPerPixel;c.pixels=a.subarray(18,18+c.imageSize);c.pixels=new Uint8Array(c.pixels);for(var d=c.pixels,g=0,f=c.imageSize,h=c.bytesPerPixel;g<f;g+=h){var k=d[g];d[g]=d[g+2];d[g+2]=k}c.format=
32==c.bpp?"RGBA":"RGB";c.flipY=!0;return c}});(function(a){function b(a,b){var c=new XMLHttpRequest;c.onload=function(){200==this.status&&b&&b(this.response)};-1==a.indexOf("://")&&(a=g.dataPath+a);c.open("get",a,!0);c.send()}var c="undefined"==typeof window&&"undefined"==typeof exports,d=2*Math.PI/360;c&&(a.console={log:function(a){var b=Array.prototype.slice.call(arguments,0);self.postMessage({action:"log",params:b})},warn:function(a){var b=Array.prototype.slice.call(arguments,0);self.postMessage({action:"warn",
params:b})},error:function(a){var b=Array.prototype.slice.call(arguments,0);self.postMessage({action:"error",params:b})}},a.alert=console.error);a.Collada={libsPath:"./",workerPath:"./",no_flip:!0,use_transferables:!0,onerror:null,verbose:!1,config:{forceParser:!1},init:function(a){a=a||{};for(var b in a)this[b]=a[b];this.config=a;if(c)try{importScripts(this.libsPath+"gl-matrix-min.js",this.libsPath+"tinyxml.js")}catch(d){g.throwException(g.LIBMISSING_ERROR)}mat4.create();vec3.create();vec3.create();
vec3.create();quat.create();c&&console.log("Collada worker ready")},load:function(a,c){b(a,function(a){a?c(g.parse(a)):c(null)})},_xmlroot:null,_nodes_by_id:null,_nodes_by_sid:null,_transferables:null,_controllers_found:null,_geometries_found:null,safeString:function(a){return a?this.convertID?this.convertID(a):a.replace(/ /g,"_"):""},LIBMISSING_ERROR:"Libraries loading error, when using workers remember to pass the URL to the tinyxml.js in the options.libsPath",NOXMLPARSER_ERROR:"TinyXML not found, when using workers remember to pass the URL to the tinyxml.js in the options.libsPath (Workers do not allow to access the native XML DOMParser)",
throwException:function(a){if(c)self.postMessage({action:"exception",msg:a});else if(g.onerror)g.onerror(a);throw a;},getFilename:function(a){var b=a.lastIndexOf("\\");-1!=b&&(a=a.substr(b+1));b=a.lastIndexOf("/");-1!=b&&(a=a.substr(b+1));return a},last_name:0,generateName:function(a){a=(a||"name_")+this.last_name;this.last_name++;return a},parse:function(b,c,d){d=d||"_dae_"+Date.now()+".dae";var e=null;c=null;this._transferables=[];this.verbose&&console.log(" - XML parsing...");if(a.DOMParser&&!this.config.forceParser)e=
new DOMParser,c=e.parseFromString(b,"text/xml"),this.verbose&&console.log(" - XML parsed");else{if(!a.DOMImplementation)return g.throwException(g.NOXMLPARSER_ERROR);try{e=new DOMImplementation}catch(n){return g.throwException(g.NOXMLPARSER_ERROR)}c=e.loadXML(b);this.verbose&&console.log(" - XML parsed");b=c._nodes_by_id={};for(var e=0,p=c.all.length;e<p;++e){var m=c.all[e];b[m.id]=m;m.getAttribute("sid")&&(b[m.getAttribute("sid")]=m)}this.extra_functions||(this.extra_functions=!0,DOMDocument.prototype.querySelector=
DOMElement.prototype.querySelector=function(a){a=a.split(" ");for(var b=this;a.length;){var c=a.shift().split("#"),d=c[0],c=c[1],d=d?b.getElementsByTagName(d):b.childNodes;if(c)for(var e=0;e<d.length;e++){if(d.item(e).getAttribute("id")==c){if(0==a.length)return d.item(e);b=d.item(e);break}}else{if(0==a.length)return d.item(0);b=d.item(0)}}return null},DOMDocument.prototype.querySelectorAll=DOMElement.prototype.querySelectorAll=function(a){function b(a,c){if(c){var e=c.shift(),e=a.getElementsByTagName(e);
if(0==c.length)for(var f=0;f<e.length;f++)d.push(e.item(f));else for(f=0;f<e.length;f++)b(e.item(f),c.concat())}}var c=a.split(" ");if(1==c.length)return this.getElementsByTagName(a);var d=[];b(this,c);a=new DOMNodeList(this.documentElement);a._nodes=d;a.length=d.length;return a},Object.defineProperty(DOMElement.prototype,"textContent",{get:function(){return this.getChildNodes().item(0).toString()},set:function(){}}))}this._xmlroot=c;if(b=c.querySelector("COLLADA"))this._current_DAE_version=b.getAttribute("version"),
console.log("DAE Version:"+this._current_DAE_version);e=c.getElementsByTagName("visual_scene").item(0);if(!e)throw"visual_scene XML node not found in DAE";this._nodes_by_id={};this._nodes_by_sid={};this._controllers_found={};this._geometries_found={};b={object_class:"Scene",light:null,materials:{},meshes:{},resources:{},root:{children:[]},external_files:{}};if(m=c.getElementsByTagName("asset")[0])b.metadata=this.readAsset(m);p=e.childNodes;for(e=0;e<p.length;e++){var q=p.item(e);1==q.nodeType&&(m=
null,"node"==q.localName?m=this.readNodeTree(q,b,0,!1):console.warn("DAE contains unknown node type: "+q.localName),m&&b.root.children.push(m))}for(e=0;e<p.length;e++)"node"==p.item(e).localName&&this.readNodeInfo(p.item(e),b,0,!1);this.readLibraryControllers(b);if(e=this.readAnimations(c,b))d="animations_"+d.substr(0,d.indexOf(".")),b.resources[d]=e,b.root.animation=d;b.images=this.readImages(c);this._nodes_by_id={};this._nodes_by_sid={};this._controllers_found={};this._geometries_found={};this._xmlroot=
null;return b},readAsset:function(a){for(var b={},c=0;c<a.childNodes.length;c++){var d=a.childNodes.item(c);if(1==d.nodeType)switch(d.localName){case "contributor":if(d=d.querySelector("authoring_tool"))b.authoring_tool=d.textContext;break;case "unit":b.unit=d.getAttribute("name");break;default:b[d.localName]=d.textContent}}return b},readNodeTree:function(a,b,c,d){var e=this.safeString(a.getAttribute("id")),g=this.safeString(a.getAttribute("sid")),m=this.safeString(a.getAttribute("name")),q=e||g||
m;if(!q)return console.warn("Collada: node without name or id, skipping it"),null;var m={name:m,id:q,sid:g,children:[],_depth:c},s=a.getAttribute("type");s&&(m.type=s);this._nodes_by_id[q]=m;e&&(this._nodes_by_id[e]=m);g&&(this._nodes_by_sid[g]=m,this._nodes_by_id[g]=m);m.model=this.readTransform(a,c,d);for(e=0;e<a.childNodes.length;e++)if(q=a.childNodes.item(e),1==q.nodeType)"node"==q.localName?(g=this.readNodeTree(q,b,c+1,d))&&m.children.push(g):"instance_node"==q.localName&&(g=this._xmlroot.querySelector("library_nodes"))&&
(q=q.getAttribute("url"),q=q.replace(/\./gi,"\\."),(g=g.querySelector(q))?(g=this.readNodeTree(g,b,c+1,d))&&m.children.push(g):console.warn("instanced node not found:"+q));return m},readNodeInfo:function(a,b,c,d,e){var g=this.safeString(a.getAttribute("id")),m=this.safeString(a.getAttribute("sid")),q=this.safeString(a.getAttribute("name"));if(q=g||m||q)e=this._nodes_by_id[q];else if(e)e=this._nodes_by_id[e.id||e.sid||e.name];else return console.warn("Collada: node without name or id, skipping it"),
null;e||(e=this._nodes_by_sid[m]);if(!e)return console.warn("Collada: Node not found by id: "+(g||m)),null;for(g=0;g<a.childNodes.length;g++){var s=a.childNodes.item(g);if(1==s.nodeType)if("node"==s.localName)this.readNodeInfo(s,b,c+1,d,a);else if("instance_node"==s.localName)this.readInstancedNodeInfo(s,b,c+1,d,a);else if("instance_geometry"==s.localName){var m=s.getAttribute("url"),t=m.toString().substr(1);e.mesh?(e.meshes||(e.meshes=[e.mesh]),e.meshes.push(t)):e.mesh=t;if(b.meshes[m])console.warn("DAE node references mesh but not found: "+
m);else if(q=this.readGeometry(m,d))q.name=t,b.meshes[t]=q;if(m=s.querySelectorAll("instance_material"))for(s=0;s<m.length;++s)if(q=m.item(s)){t=q.getAttribute("target").toString().substr(1);if(!b.materials[t]){var u=this.readMaterial(t);u&&(u.id=t,b.materials[u.id]=u)}0==s?e.material=t:(e.materials||(e.materials=[]),e.materials.push(t))}else console.warn("instance_material not found: "+g)}else if("instance_controller"==s.localName)if(m=s.getAttribute("url"),q=m.replace(/\./gi,"\\."),(q=this._xmlroot.querySelector("controller"+
q))||(q=this.searchManuallyById("library_controllers",m.substr(1))),q){q=this.readController(q,d,b);if(s=s.querySelector("bind_material"))for(var H=s.querySelectorAll("technique_common"),r=0;r<H.length;r++)for(var v=H.item(r).querySelectorAll("instance_material"),s=0;s<v.length;s++)(t=v.item(s))?(t=t.getAttribute("target").toString().substr(1),!b.materials[t]&&(u=this.readMaterial(t))&&(u.id=t,b.materials[u.id]=u),0==s?e.material=t:(e.materials||(e.materials=[]),e.materials.push(t))):console.warn("instance_material for controller not found: "+
t);q&&(s=q,"morph"==q.type&&(s=q.mesh,e.morph_targets=q.morph_targets),s.name=m.toString(),e.mesh=m.toString(),b.meshes[m]=s)}else console.warn("DAE, node controller not found: "+m);else"instance_light"==s.localName?(m=s.getAttribute("url"),this.readLight(e,m)):"instance_camera"==s.localName&&(m=s.getAttribute("url"),this.readCamera(e,m))}},readInstancedNodeInfo:function(a,b,c,d,e){e=this._xmlroot.querySelector("library_nodes");if(!e)return!1;a=a.getAttribute("url");a=a.replace(/\./gi,"\\.");e=e.querySelector(a);
if(!e)return console.warn("instanced node not found:"+a),!1;this.readNodeInfo(e,b,c+1,d);return!0},searchManuallyById:function(a,b){var c=this._xmlroot.querySelector(a);if(!c)return null;for(var d=0;d<c.childNodes.length;++d){var e=c.childNodes[d];if(e.id==b)return e}return null},material_translate_table:{},light_translate_table:{point:"omni",directional:"directional",spot:"spot"},camera_translate_table:{xfov:"fov",aspect_ratio:"aspect",znear:"near",zfar:"far"},querySelectorAndId:function(a,b,c){a=
a.querySelectorAll(b);for(b=0;b<a.length;b++){var d=a.item(b).getAttribute("id");if(d&&(d=d.toString(),d==c))return a.item(b)}return null},getFirstChildElement:function(a,b){for(var c=a.childNodes,d=0;d<c.length;++d){var e=c.item(d);if(e.localName&&!b||b&&b==e.localName)return e}return null},readMaterial:function(a){a=this.querySelectorAndId(this._xmlroot,"library_materials material",a);if(!a)return null;a=a.querySelector("instance_effect");if(!a)return null;a=a.getAttribute("url").substr(1);a=this.querySelectorAndId(this._xmlroot,
"library_effects effect",a);if(!a)return null;var b=a.querySelector("technique");if(!b)return null;var c=a.querySelectorAll("newparam");a={};for(var d=0;d<c.length;d++){var e=c[d].querySelector("init_from"),g;if(!e&&(e=c[d].querySelector("source"),!g)){console.warn("no source found for material for newparam");continue}g=e.innerHTML;a[c[d].getAttribute("sid")]={parent:g}}g={};c=this.readImages(this._xmlroot);(e=b.querySelector("phong"))||(e=b.querySelector("blinn"));e||(e=b.querySelector("lambert"));
if(!e)return null;g.type=e.localName;for(d=0;d<e.childNodes.length;++d){var m=e.childNodes.item(d);if(m.localName){b=m.localName.toString();this.material_translate_table[b]&&(b=this.material_translate_table[b]);var q=this.getFirstChildElement(m);if(q)if("color"==q.localName.toString()){q=this.readContentAsFloats(q);if(m=m.getAttribute("opaque"))g.opaque_info=m;g[b]="RGB_ZERO"==m?q.subarray(0,4):q.subarray(0,3)}else"float"==q.localName.toString()?g[b]=this.readContentAsFloats(q)[0]:"texture"==q.localName.toString()&&
(g.textures||(g.textures={}),m=q.getAttribute("texture"))&&(-1===m.indexOf(".")&&(m=this.getParentParam(a,m),c[m]&&(m=c[m].path)),m={map_id:m},q=q.getAttribute("texcoord"),m.uvs=q,g.textures[b]=m)}}g.object_class="Material";return g},getParentParam:function(a,b){return a[b]?a[b].parent?this.getParentParam(a,a[b].parent):b:b},readLight:function(a,b){function c(a,b){for(var d=0;d<b.childNodes.length;d++){var e=b.childNodes.item(d);if(e&&1==e.nodeType)switch(e.localName){case "color":a.color=g.readContentAsFloats(e);
break;case "falloff_angle":a.angle_end=g.readContentAsFloats(e)[0],a.angle=a.angle_end-10}}}var d={},e=null;if(1<b.length)e=this._xmlroot.querySelector("library_lights "+b);else var p=this._xmlroot.querySelector("library_lights"),e=this.getFirstChildElement(p,"light");if(!e)return null;var p=[],m=e.querySelector("technique_common");if(m)for(var q=0;q<m.childNodes.length;q++)1==m.childNodes.item(q).nodeType&&p.push(m.childNodes.item(q));e=e.querySelectorAll("technique");for(q=0;q<e.length;q++)for(var m=
e.item(q),s=0;s<m.childNodes.length;s++)1==m.childNodes.item(s).nodeType&&p.push(m.childNodes.item(s));for(q=0;q<p.length;q++)switch(m=p[q],m.localName){case "point":d.type=this.light_translate_table[m.localName];c(d,m);break;case "directional":d.type=this.light_translate_table[m.localName];c(d,m);break;case "spot":d.type=this.light_translate_table[m.localName];c(d,m);break;case "intensity":d.intensity=this.readContentAsFloats(m)[0]}a.model?(d.position=[a.model[12],a.model[13],a.model[14]],p=[-a.model[8],
-a.model[9],-a.model[10]],d.target=[d.position[0]+p[0],d.position[1]+p[1],d.position[2]+p[2]]):(console.warn("Could not read light position for light: "+a.name+". Setting defaults."),d.position=[0,0,0],d.target=[0,-1,0]);a.light=d},readCamera:function(a,b){var c={},d=this._xmlroot.querySelector("library_cameras "+b);if(!d)return null;var e=[],p=d.querySelector("technique_common");if(p)for(d=0;d<p.childNodes.length;d++)1==p.childNodes.item(d).nodeType&&e.push(p.childNodes.item(d));for(d=0;d<e.length;d++)for(var p=
c,m=e[d],q=0;q<m.childNodes.length;q++){var s=m.childNodes.item(q);s&&1==s.nodeType&&(p[g.camera_translate_table[s.localName]||s.localName]=parseFloat(s.textContent))}c.yfov&&!c.fov&&(c.aspect?c.fov=c.yfov*c.aspect:console.warn("Could not convert camera yfov to xfov because aspect ratio not set"));a.camera=c},readTransform:function(a,b,c){for(var g=mat4.create(),n=mat4.create(),p=quat.create(),m=0;m<a.childNodes.length;m++){var q=a.childNodes.item(m);if(q&&1==q.nodeType){if("matrix"==q.localName){g=
this.readContentAsFloats(q);this.transformMatrix(g,0==b);break}if("translate"==q.localName){var s=this.readContentAsFloats(q);c&&0<b&&(q=s[1],s[1]=s[2],s[2]=-q);mat4.translate(g,g,s)}else"rotate"==q.localName?(s=this.readContentAsFloats(q),4==s.length&&("jointOrientX"==q.getAttribute("sid")&&(s[3]+=90),c&&(q=s[1],s[1]=s[2],s[2]=-q),0!=s[3]&&(quat.setAxisAngle(p,s.subarray(0,3),s[3]*d),mat4.fromQuat(n,p),mat4.multiply(g,g,n)))):"scale"==q.localName&&(s=this.readContentAsFloats(q),c&&(q=s[1],s[1]=s[2],
s[2]=-q),mat4.scale(g,g,s))}}return g},readTransform2:function(a,b,c){for(var g=mat4.create(),n=quat.create(),p=mat4.create(),m=quat.create(),q=vec3.create(),s=vec3.fromValues(1,1,1),t=0;t<a.childNodes.length;t++){var u=a.childNodes.item(t);if("matrix"==u.localName)return g=this.readContentAsFloats(u),this.transformMatrix(g,0==b),g;if("translate"==u.localName){var r=this.readContentAsFloats(u);q.set(r)}else"rotate"==u.localName?(r=this.readContentAsFloats(u),4==r.length&&("jointOrientX"==u.getAttribute("sid")&&
(r[3]+=90),c&&(u=r[1],r[1]=r[2],r[2]=-u),0!=r[3]&&(quat.setAxisAngle(m,r.subarray(0,3),r[3]*d),quat.multiply(n,n,m)))):"scale"==u.localName&&(r=this.readContentAsFloats(u),c&&(u=r[1],r[1]=r[2],r[2]=-u),s.set(r))}c&&0<b&&(u=q[1],q[1]=q[2],q[2]=-u);mat4.translate(g,g,q);mat4.fromQuat(p,n);mat4.multiply(g,g,p);mat4.scale(g,g,s);return g},readGeometry:function(a,b,d){if(void 0!==this._geometries_found[a])return this._geometries_found[a];var e=this._xmlroot.getElementById(a.substr(1));if(!e)return console.warn("readGeometry: geometry not found: "+
a),this._geometries_found[a]=null;if("controller"==e.localName)return e=this.readController(e,b,d),this._geometries_found[a]=e;if("geometry"!=e.localName)return console.warn("readGeometry: tag should be geometry, instead it was found: "+e.localName),this._geometries_found[a]=null;d=e.querySelector("mesh");if(!d)return console.warn("readGeometry: mesh not found in geometry: "+a),this._geometries_found[a]=null;for(var g=e.sources={},p=d.querySelectorAll("source"),e=0;e<p.length;e++){var m=p.item(e);
if(m.querySelector){var q=m.querySelector("float_array");if(q){var q=this.readContentAsFloats(q),s=m.querySelector("accessor"),t=parseInt(s.getAttribute("stride")),s=s.querySelector("param");g[m.getAttribute("id")]={stride:t,data:q,params:s.length}}}}p=d.querySelector("vertices input");p=g[p.getAttribute("source").substr(1)];g[d.querySelector("vertices").getAttribute("id")]=p;p=null;(m=d.querySelector("polygons"))&&(p=this.readPolygons(m,g));p||(m=d.querySelectorAll("triangles"))&&m.length&&(p=this.readTriangles(m,
g));p||(m=d.querySelectorAll("polylist"))&&m.length&&(p=this.readPolylistArray(m,g));p||(d=d.querySelector("linestrips"))&&(p=this.readLineStrip(g,d));if(!p)return console.log("no polygons or triangles in mesh: "+a),this._geometries_found[a]=null;if(b&&!this.no_flip){b=0;d=p.vertices;e=0;for(g=d.length;e<g;e+=3)b=d[e+1],d[e+1]=d[e+2],d[e+2]=-b;d=p.normals;e=0;for(g=d.length;e<g;e+=3)b=d[e+1],d[e+1]=d[e+2],d[e+2]=-b}if(c&&this.use_transferables)for(e in p)(b=p[e])&&b.buffer&&100<b.length&&this._transferables.push(b.buffer);
p.filename=a;p.object_class="Mesh";return this._geometries_found[a]=p},readPolygons:function(a,b){for(var c=[],d=0,e={},g=[],m=[],q=a.getAttribute("material"),s=[],t=[],u=0;u<a.childNodes.length;u++){var r=a.childNodes.item(u);if("input"==r.localName){var v=this.readInput(r,b);v&&s.push(v)}else"p"==r.localName?t.push(r):r.localName&&console.warn("unknown xml tag in <polygons>: "+r.localName)}for(var r=1,w=s.length,u=0;u<w;++u)r=Math.max(r,s[u][4]+1);for(u=0;u<t.length;u++){var y=t[u];if(!y||!y.textContent)break;
for(var y=y.textContent.trim().split(" "),x=-1,A=v=-1,B=0,C=y.length;B<C;B+=r){var z=y.slice(B,B+r).join(" "),A=v;if(e.hasOwnProperty(z))v=e[z];else{for(var D=0;D<w;++D){var v=s[D],E=v[1],F=v[3],I=parseInt(y[B+v[4]]);0==D&&(g[E.length/v[2]]=I);for(var I=I*v[2],J=0;J<v[2];++J)E.push(F[I+J])}v=d;d+=1;e[z]=v}0==B&&(x=v);2<B/r&&(m.push(x),m.push(A));m.push(v)}}c.push({name:"group",start:0,length:m.length-0,material:q||""});if(!s.length)return console.warn("collada: <polygon> without buffers"),null;c=
{vertices:new Float32Array(s[0][1]),info:{groups:c},_remap:new Uint32Array(g)};this.transformMeshInfo(c,s,m);return c},readTriangles:function(a,b){for(var c=[],d=[],e=0,g={},m=[],q=[],s=0,t="",u=0;u<a.length;u++){var r=a.item(u),t=r.getAttribute("material");parseFloat(r.getAttribute("count"));0==u&&(d=this.readShapeInputs(r,b));for(var r=r.querySelectorAll("p"),v=1,y=d.length,w=0;w<y;++w)v=Math.max(v,d[w][4]+1);for(w=0;w<r.length;w++){var x=r.item(w);if(!x||!x.textContent)break;for(var x=x.textContent.trim().split(" "),
A=-1,B=0,C=x.length;B<C;B+=v){var z=x.slice(B,B+v).join(" ");if(g.hasOwnProperty(z))A=g[z];else{for(A=0;A<y;++A){var D=d[A],E=D[1],F=D[3],I=parseInt(x[B+D[4]]);0==A&&(m[E.length/D[2]]=I);for(var I=I*D[2],J=0;J<D[2];++J)E.push(F[I+J])}A=e;e+=1;g[z]=A}q.push(A)}}t={name:"group"+u,start:s,length:q.length-s,material:t||""};s=q.length;c.push(t)}if(!d.length)return null;c={vertices:new Float32Array(d[0][1]),info:{groups:c},_remap:new Uint32Array(m)};this.transformMeshInfo(c,d,q);return c},readPolylistArray:function(a,
b){for(var c=[],d=0;d<a.length;++d){var e=this.readPolylist(a[d],b);e&&c.push(e)}return 2>c.length?c[0]:e=this.mergeMeshes(c)},readPolylist:function(a,b){for(var c=[],d=0,e={},g=[],m=[],q="",q=a.getAttribute("material")||"",c=this.readShapeInputs(a,b),s=a.querySelector("vcount"),s=this.readContentAsUInt32(s),t=a.querySelector("p"),t=this.readContentAsUInt32(t),u=0,r=1,v=c.length,w=0;w<v;++w)r=Math.max(r,c[w][4]+1);for(var w=0,y=s.length;w<y;++w){var x=s[w],A=-1,B=-1,C=-1;if(u>=t.length){console.warn("DAE has wrong number of polygons in polylist");
break}for(var z=0;z<x;++z){var D=t.slice(u,u+r).join(" "),C=B;if(e.hasOwnProperty(D))B=e[D];else{for(B=0;B<v;++B){var E=c[B],F=E[1],I=E[3],J=parseInt(t[u+E[4]]);0==B&&(g[F.length/E[2]]=J);for(var J=J*E[2],K=0;K<E[2];++K)F.push(I[J+K])}B=d;d+=1;e[D]=B}3<x&&(0==z&&(A=B),2<z&&(m.push(A),m.push(C)));m.push(B);u+=r}}d={vertices:new Float32Array(c[0][1]),info:{material:q},_remap:new Uint32Array(g)};this.transformMeshInfo(d,c,m);return d},readShapeInputs:function(a,b){for(var c=[],d=a.querySelectorAll("input"),
e=0;e<d.length;e++){var g=d.item(e);g.getAttribute&&((g=this.readInput(g,b))?c.push(g):console.warn("no buffer in collada"))}return c},readInput:function(a,b){if(!a.getAttribute)return null;var c=a.getAttribute("source").substr(1),d=null;if(-1!=c.indexOf("/")){var e=c.split("/"),g=this._xmlroot.getElementById(e[0]);g&&g.sources&&(d=g.sources[e[1]])}else d=b[c];if(!d)return console.warn("<input> source not found: "+c),null;c=a.getAttribute("semantic").toUpperCase();e=parseInt(a.getAttribute("offset"));
g=0;a.getAttribute("set")&&(g=parseInt(a.getAttribute("set")));return[c,[],d.stride,d.data,e,g]},transformMeshInfo:function(a,b,c){for(var d={normal:"normals",texcoord:"coords"},e=1;e<b.length;++e){var g=b[e][0].toLowerCase(),m=b[e][1];m.length&&(d[g]&&(g=d[g]),a[g]&&(g+=b[e][5]),a[g]=new Float32Array(m))}c&&c.length&&(a.triangles=65536<a.vertices.length?new Uint32Array(c):new Uint16Array(c));return a},readLineStrip:function(a,b){for(var c=[],d=0,e={},g=[],m=b.querySelectorAll("input"),q=0;q<m.length;q++){var s=
m.item(q);if(s.getAttribute){var t=s.getAttribute("semantic").toUpperCase(),u=a[s.getAttribute("source").substr(1)],r=parseInt(s.getAttribute("offset")),v=0;s.getAttribute("set")&&(v=parseInt(s.getAttribute("set")));c.push([t,[],u.stride,u.data,r,v])}}m=b.querySelectorAll("p");s=c.length;for(q=0;q<m.length;q++){t=m.item(q);if(!t||!t.textContent)break;for(var t=t.textContent.trim().split(" "),w=-1,u=0,r=t.length;u<r;u+=s){v=t.slice(u,u+s).join(" ");if(e.hasOwnProperty(v))w=e[v];else{for(w=0;w<c.length;++w)for(var y=
c[w],x=parseInt(t[u+w]),B=y[1],A=y[3],x=x*y[2],z=0;z<y[2];++z)B.push(A[x+z]);w=d;d+=1;e[v]=w}g.push(w)}}d={primitive:"line_strip",vertices:new Float32Array(c[0][1]),info:{}};return this.transformMeshInfo(d,c,g)},findXMLNodeById:function(a,b,c){if(this._xmlroot._nodes_by_id){var d=this._xmlroot._nodes_by_id[c];if(d&&d.localName==b)return d}else if(d=this._xmlroot.getElementById(c))return d;a=a.childNodes;for(d=0;d<a.length;++d){var e=a.item(d);if(1==e.nodeType&&e.localName==b&&e.getAttribute("id")==
c)return e}return null},readImages:function(a){var b=a.querySelector("library_images");if(!b)return null;a={};for(var b=b.childNodes,c=0;c<b.length;++c){var d=b.item(c);if(1==d.nodeType){var e=d.querySelector("init_from");if(e&&e.textContent){var g=this.getFilename(e.textContent),m=d.getAttribute("id");a[m]={filename:g,map:m,name:d.getAttribute("name"),path:e.textContent}}}}return a},readAnimations:function(a,b){var c=a.querySelector("library_animations");if(!c)return null;for(var d=c.childNodes,
c={object_class:"Animation",takes:{}},e={tracks:[]},g=e.tracks,m=0;m<d.length;++m){var q=d.item(m);if(1==q.nodeType&&"animation"==q.localName)if(q.getAttribute("id"))this.readAnimation(q,g);else{var s=q.querySelectorAll("animation");if(s.length)for(q=0;q<s.length;++q){var t=s.item(q);this.readAnimation(t,g)}else this.readAnimation(q,g)}}if(!g.length)return null;for(m=d=0;m<g.length;++m)d<g[m].duration&&(d=g[m].duration);e.name="default";e.duration=d;c.takes[e.name]=e;return c},readAnimation:function(a,
b){if("animation"!=a.localName)return null;a.getAttribute("id");var c=a.querySelectorAll("channel");if(!c.length)return null;for(var d=b||[],e=0;e<c.length;++e){var g=this.readChannel(c.item(e),a);g&&d.push(g)}return d},readChannel:function(a,b){if("channel"!=a.localName||"animation"!=b.localName)return null;var d=a.getAttribute("source"),e=a.getAttribute("target"),g=this.findXMLNodeById(b,"sampler",d.substr(1));if(!g)return console.error("Error DAE: Sampler not found in "+d),null;for(var d={},p=
{},m={},q=g.querySelectorAll("input"),g=null,s=0;s<q.length;s++){var t=q.item(s),u=t.getAttribute("source"),r=t.getAttribute("semantic"),v=this.findXMLNodeById(b,"source",u.substr(1));if(v){var w=v.querySelector("param");if(w){t=w.getAttribute("type");d[r]={source:u,type:t};var y=null;if("float"==t||"float4x4"==t)y=v.querySelector("float_array"),y=this.readContentAsFloats(y),m[u]=y,u=w.getAttribute("name"),"TIME"==u&&(g=y),"OUTPUT"==r&&(u=r),u?p[u]=t:console.warn("Collada: <param> without name attribute in <animation>")}}}if(!g)return console.error("Error DAE: no TIME info found in <channel>: "+
a.getAttribute("source")),null;s=e.split("/");e={};t=this.safeString(s[0]);q=this._nodes_by_id[t];if(!q)return console.warn("Node target '"+t+"' not found reading animation channel"),null;t=q.id+"/"+s[1];e.name=s[1];e.property=t;t="number";u=1;p=p.OUTPUT;switch(p){case "float":u=1;break;case "float3x3":u=9;t="mat3";break;case "float4x4":u=16,t="mat4"}e.type=t;e.value_size=u;e.duration=g[g.length-1];d=m[d.OUTPUT.source];if(!d)return null;m=u+1;t=new Float32Array(g.length*m);for(s=0;s<g.length;++s)t[s*
m]=g[s],r=d.subarray(s*u,(s+1)*u),"float4x4"==p&&this.transformMatrix(r,q?0==q._depth:0),t.set(r,s*m+1);c&&this.use_transferables&&t&&t.buffer&&100<t.length&&this._transferables.push(t.buffer);e.data=t;return e},findNode:function(a,b){if(a.id==b)return a;if(a.children)for(var c in a.children){var d=this.findNode(a.children[c],b);if(d)return d}return null},readLibraryControllers:function(a){var b=this._xmlroot.querySelector("library_controllers");if(!b)return null;for(var b=b.childNodes,c=0;c<b.length;++c){var d=
b.item(c);if(1==d.nodeType&&"controller"==d.localName){var e=d.getAttribute("id");this._controllers_found[e]||this.readController(d,null,a)}}},readController:function(a,b,c){if("controller"==!a.localName)return console.warn("readController: not a controller: "+a.localName),null;var d=a.getAttribute("id");if(this._controllers_found[d])return this._controllers_found[d];var e=null,g=a.querySelector("skin");g&&(e=this.readSkinController(g,b,c));(a=a.querySelector("morph"))&&(e=this.readMorphController(a,
b,c,e));return this._controllers_found[d]=e},readSkinController:function(a,b,c){var d=a.getAttribute("source");c=this.readGeometry(d,b,c);if(!c)return null;var e=this.readSources(a,b);if(!e)return null;b=null;(b=a.querySelector("bind_shape_matrix"))?(b=this.readContentAsFloats(b),this.transformMatrix(b,!0,!0)):b=mat4.create();var d=[],g=a.querySelector("joints");if(g){for(var m=null,q=null,s=g.querySelectorAll("input"),g=0;g<s.length;g++){var t=s[g],u=t.getAttribute("semantic").toUpperCase(),t=t.getAttribute("source"),
t=e[t.substr(1)];"JOINT"==u?m=t:"INV_BIND_MATRIX"==u&&(q=t)}if(!q||!m)return console.error("Error DAE: no joints or inv_bind sources found"),null;for(g=0;g<m.length;++g)s=q.subarray(16*g,16*g+16),u=m[g],(t=this._nodes_by_id[u])?(this.transformMatrix(s,0==t._depth,!0),d.push([u,s])):console.warn("Node "+u+" not found")}var t=0,r=[];if(a=a.querySelector("vertex_weights")){for(var v=null,s=a.querySelectorAll("input"),g=0;g<s.length;g++)"WEIGHT"==s[g].getAttribute("semantic").toUpperCase()&&(v=e[s.item(g).getAttribute("source").substr(1)]);
if(!v)throw"no weights found";var g=a.querySelector("vcount"),w=this.readContentAsUInt32(g),g=a.querySelector("v"),y=this.readContentAsUInt32(g);a=c.vertices.length/3;var e=new Float32Array(4*a),m=new Uint8Array(4*a),x=0,q=c._remap;if(!q)throw"no remap info found in mesh";for(var g=s=0,B=w.length;g<B;++g){var A=w[g],u=x;r.length=A;for(var z=0;z<A;++z)r[z]=[v[y[u+2*z+1]],y[u+2*z]];r.sort(this._bones_sort_func);4<r.length&&(r.length=4,t+=1);for(var C=m.subarray(4*g,4*g+4),u=e.subarray(4*g,4*g+4),D=
0,z=0;z<r.length;++z)C[z]=r[z][1],C[z]>s&&(s=C[z]),u[z]=r[z][0],D+=u[z];if(1>D)for(C=1/D,z=0;4>z;++z)u[z]*=C;x+=2*A}t&&console.warn("This mesh has "+t+" vertices with more than 4 bones, skipping extra bones. This could cause errors in the skinning.");t=new Float32Array(4*a);r=new Uint8Array(4*a);v=[];for(g=0;g<a;++g){z=4*q[g];u=e.subarray(z,z+4);C=m.subarray(z,z+4);for(w=0;3>w;++w){y=w;x=u[w];for(z=w+1;4>z;++z)u[z]<=x||(y=z,x=u[z]);y!=w&&(z=u[w],u[w]=u[y],u[y]=z,z=C[w],C[w]=C[y],C[y]=z)}t.set(u,4*
g);r.set(C,4*g);u[0]&&(v[C[0]]=!0);u[1]&&(v[C[1]]=!0);u[2]&&(v[C[2]]=!0);u[3]&&(v[C[3]]=!0)}s>=d.length&&console.warn("Mesh uses higher bone index than bones found");a=[];e={};for(g=0;g<v.length;++g)v[g]&&(e[g]=a.length,a.push(d[g]));if(a.length<d.length){for(g=0;g<r.length;g++)r[g]=e[r[g]];d=a}for(g=0;g<d.length;++g)a=d[g],(e=this._nodes_by_id[a[0]]||this._nodes_by_sid[a[0]])?a[0]=e.id||e.name:console.warn("Bone not found");c.weights=t;c.bone_indices=r;c.bones=d;c.bind_matrix=b}return c},_bones_sort_func:function(a,
b){return b[0]-a[0]},readMorphController:function(a,b,c,d){d=a.getAttribute("source");d=this.readGeometry(d,b,c);if(!d)return null;var e=this.readSources(a,b),g=[];a=a.querySelector("targets");if(!a)return null;for(var m=a.querySelectorAll("input"),q=a=null,s=0;s<m.length;s++){var t=m.item(s),u=t.getAttribute("semantic").toUpperCase(),t=e[t.getAttribute("source").substr(1)];"MORPH_TARGET"==u?a=t:"MORPH_WEIGHT"==u&&(q=t)}if(!a||!q)return console.warn("Morph controller without targets or weights. Skipping it."),
null;for(s in a)e="#"+a[s],m=this.readGeometry(e,b,c),c.meshes[e]=m,g.push({mesh:e,weight:q[s]});d.morph_targets=g;return d},readBindMaterials:function(a,b){for(var c=[],d=a.querySelectorAll("technique_common"),e=0;e<d.length;e++)for(var g=d.item(e).querySelectorAll("instance_material"),m=0;m<g.length;m++){var q=g.item(m);q&&c.push(q.getAttribute("symbol"))}return c},readSources:function(a,b){for(var c={},d=a.querySelectorAll("source"),e=0;e<d.length;e++){var g=d.item(e);if(g.querySelector)if(g.querySelector("float_array")){var m=
this.readContentAsFloats(g);c[g.getAttribute("id")]=m}else(m=g.querySelector("Name_array"))?(m=this.readContentAsStringsArray(m))&&(c[g.getAttribute("id")]=m):(m=g.querySelector("IDREF_array"))&&(m=this.readContentAsStringsArray(m))&&(c[g.getAttribute("id")]=m)}return c},readContentAsUInt32:function(a){if(!a)return null;a=a.textContent;a=a.replace(/\n/gi," ");a=a.replace(/\s\s+/gi," ");a=a.trim();if(0==a.length)return null;a=a.split(" ");for(var b=new Uint32Array(a.length),c=0;c<a.length;c++)b[c]=
parseInt(a[c]);return b},readContentAsFloats:function(a){if(!a)return null;var b=a.textContent,b=b.replace(/\n/gi," "),b=b.replace(/\s\s+/gi," "),b=b.replace(/\t/gi,""),b=b.trim(),b=b.split(" ");a.getAttribute("count");a=new Float32Array(b.length);for(var c=0;c<b.length;c++)a[c]=parseFloat(b[c]);return a},readContentAsStringsArray:function(a){if(!a)return null;for(var b=a.textContent,b=b.replace(/\n/gi," "),b=b.replace(/\s\s/gi," "),b=b.trim(),b=b.split(" "),c=0;c<b.length;c++)b[c]=b[c].trim();if(a.getAttribute("count")&&
parseInt(a.getAttribute("count"))!=b.length){var c=[],d="",e;for(e in b)d=d?d+(" "+b[e]):b[e],this._nodes_by_id[this.safeString(d)]&&(c.push(this.safeString(d)),d="");a=parseInt(a.getAttribute("count"));if(c.length==a)return c;console.error("Error: bone names have spaces, avoid using spaces in names");return null}return b},max3d_matrix_0:new Float32Array([0,-1,0,0,0,0,-1,0,1,0,0,-0,0,0,0,1]),transformMatrix:function(a,b,c){mat4.transpose(a,a);if(this.no_flip)return a;b?(b=new Float32Array(a.subarray(4,
8)),a.set(a.subarray(8,12),4),a.set(b,8),b=a.subarray(8,12),vec4.scale(b,b,-1)):(b=mat4.create(),b.set([a[0],a[2],-a[1]],0),b.set([a[8],a[10],-a[9]],4),b.set([-a[4],-a[6],a[5]],8),b.set([a[12],a[14],-a[13]],12),a.set(b));return a},mergeMeshes:function(a,b){b=b||{};for(var c={},d={},e={},g=[],m=0,q=[],s={triangles:!0,wireframe:!0},t=null,u=0,r=0;r<a.length;++r){var v=a[r],w=m;g.push(w);var y=v.vertices.length/3,m=m+y,x;for(x in v){var z=v[x];"info"!=x&&"_remap"!=x&&(s[x]?d[x]=d[x]?d[x]+z.length:z.length:
c[x]=c[x]?c[x]+z.length:z.length)}q.push({name:"mesh_"+(v.info.material||r),start:w,length:y,material:v.info.material||""})}for(x in c)r=b[x],null===r?delete c[x]:(r||(r=Float32Array),c[x]=new r(c[x]),e[x]=0);for(x in d)d[x]=new Uint32Array(d[x]),e[x]=0;for(r=0;r<a.length;++r){v=a[r];z=v.vertices;if(!z)return console.error("mesh without vertices");y=z.length/3;for(x in v)if(z=v[x],"info"!=x){if("_remap"==x){if(u)for(var m=z,w=u,B=0+z.length,A=0;A<B;++A)m[A]+=w;t?(m=new Uint32Array(t.length+z.length),
m.set(t),m.set(z,t.length),t=m):(t=new Uint32Array(z.length),t.set(z));u+=y}if(s[x]){d[x].set(z,e[x]);m=d[x];A=e[x];w=g[r];for(B=A+z.length;A<B;++A)m[A]+=w;e[x]+=z.length}else c[x]&&(c[x].set(z,e[x]),e[x]+=z.length)}}e={info:{groups:q}};for(r in c)e[r]=c[r];for(r in d)e[r]=d[r];t&&(e._remap=t);return e}};var g=a.Collada;c?(g.loadInWorker=function(a,b){g.load(b,a)},g.parseInWorker=function(a,b){a(g.parse(b))}):(g.launchWorker=function(){var a=this.worker=new Worker(g.workerPath+"collada.js");a.callback_ids=
{};a.addEventListener("error",function(a){if(g.onerror)g.onerror(err)});a.addEventListener("message",function(a){if(a.data)switch(a=a.data,a.action){case "log":console.log.apply(console,a.params);break;case "warn":console.warn.apply(console,a.params);break;case "exception":console.error.apply(console,a.params);if(g.onerror)g.onerror(a.msg);break;case "error":console.error.apply(console,a.params);break;case "result":var b=this.callback_ids[a.callback_id];if(!b)throw"callback not found";b(a.result);
break;default:console.warn("Unknown action:",a.action)}});this.callback_ids={};this.last_callback_id=1;this.toWorker("init",[this.config])},g.toWorker=function(a,b,c){this.worker||this.launchWorker();var d=this.last_callback_id++;this.worker.callback_ids[d]=c;this.worker.postMessage({func:a,params:b,callback_id:d})},g.loadInWorker=function(a,b){this.toWorker("loadInWorker",[a],b)},g.parseInWorker=function(a,b){this.toWorker("parseInWorker",[a],b)});c&&self.addEventListener("message",function(a){if("init"==
a.data.func)return g.init.apply(g,a.data.params);var b=a.data.func,c=a.data.params,d=a.data.callback_id;a=function(a){self.postMessage({action:"result",callback_id:d,result:a},g._transferables);g._transferables=null};var e=g[b];if(void 0===e)console.error("function not found:",b),a(null);else try{e.apply(g,c?[a].concat(c):[a])}catch(p){console.error("Error inside worker function call to "+b+" :: "+p),a(null)}},!1)})("undefined"!=typeof window?window:"undefined"!=typeof exports?exports:self);d.Formats.addSupportedFormat("dae",
{extension:"dae",type:"scene",resource:"SceneNode",format:"text",dataType:"text",convert_filenames_to_lowercase:!0,parse:function(a,b,c){function e(a){"root"==a.id&&(console.warn("DAE contains a node named root, renamed to _root"),a.id="_root",g.root=a.id);a.id&&!b.skip_renaming&&(a.uid="@"+f+"::"+a.id,g[a.id]=a.uid);a.type&&(a.node_type=a.type,delete a.type);if(a.material){var c=a.material.replace(/[^a-z0-9\.\-]/gi,"_")+".json";g[a.material]=c;a.material=c}if(a.materials)for(var d in a.materials)c=
a.materials[d].replace(/[^a-z0-9\.\-]/gi,"_")+".json",g[a.material]=c,a.materials[d]=c;if(a.meshes)for(d=0;d<a.meshes.length;d++)a.meshes[d]&&g[a.meshes[d]]&&(a.meshes[d]=g[a.meshes[d]]);a.mesh&&g[a.mesh]&&(a.mesh=g[a.mesh]);if(a.children)for(d in a.children)e(a.children[d])}if(!a||a.constructor!==String)return console.error("DAE parser requires string"),null;Collada.material_translate_table={reflectivity:"reflection_factor",specular:"specular_factor",shininess:"specular_gloss",emission:"emissive",
diffuse:"color"};c=d.RM.getFilename(c);a=Collada.parse(a,b,c);console.log(a);a.root.name=c;a.metadata&&"Z_UP"==a.metadata.up_axis&&(a.root.model=mat4.rotateX(mat4.create(),mat4.create(),-90*0.0174532925));var g={},f=c.substr(0,c.indexOf("."));c={};for(var h in a.meshes){var k=f+"__"+h+".wbin",k=k.replace(/[^a-z0-9\.\-]/gi,"_");g[h]=k;c[k]=a.meshes[h]}a.meshes=c;for(h in a.meshes)c=a.meshes[h],this.processMesh(c,g);e(a.root);for(h in a.meshes)if(c=a.meshes[h],c.bones)for(var l in c.bones)(k=g[c.bones[l][0]])&&
(c.bones[l][0]=k);a.root.animation&&(a.root.animation=this.renameResource(a.root.animation,a.root.animation+".wbin",a.resources));l={};for(h in a.materials)c=a.materials[h],this.processMaterial(c),l[c.id]=c;a.materials=l;for(h in a.resources)l=a.resources[h],d.ResourcesManager.getBasename(h)||console.warn("DAE contains resources without extension: "+h,l.constructor),"Animation"==l.object_class&&this.processAnimation(l,g);return a},renameResource:function(a,b,c){var d=c[a];if(!d)return c[b]||console.warn("Resource not found: "+
a),b;delete c[a];c[b]=d;return d.filename=b},processMesh:function(a,b){if(a.vertices){var c=a.vertices.length/3,d=a.coords?a.coords.length/2:0;if(d&&d!=c){var g=a.coords,f=new Float32Array(2*c);if(d>c)for(d=0;d<c;++d)f[2*d]=g[3*d],f[2*d+1]=g[3*d+1];a.coords=f}if(a.morph_targets)for(c=0;c<a.morph_targets.length;++c)g=a.morph_targets[c],g.mesh&&b[g.mesh]&&(g.mesh=b[g.mesh])}},processAnimation:function(a,b){for(var c in a.takes){for(var d=a.takes[c],g=0;g<d.tracks.length;++g){var f=d.tracks[g],h=f.property.indexOf("/");
if(h){var k=f.property.substr(0,h),l=f.property.substr(h);"/transform"==l&&(l="/matrix");b[k]&&(k=b[k],f.property=k+l)}}l={};for(g=0;g<d.tracks.length;++g)if(f=d.tracks[g],f.packed_data=!0,"rotateX.ANGLE"==f.name||"rotateY.ANGLE"==f.name||"rotateZ.ANGLE"==f.name)k=f.property.split("/")[0],l[k]||(l[k]={tracks:[]}),l[k].tracks.push(f);for(g in l){for(var k=l[g],h={data:[],type:"quat",value_size:4,property:g+"/Transform/rotation",name:"rotation"},n=[],p=0;p<k.tracks.length;++p)for(var f=k.tracks[p],
f=f.data,m=0;m<f.length;m+=2)n.push(f[m]);n.sort();f=-1;m=[];for(p=0;p<n.length;++p)n[p]!=f&&(m.push(n[p]),f=n[p]);n=m;h.data.length=n.length;for(p=0;p<h.data.length;++p){var q=n[p],s=quat.create();h.data[p]=[q,s];for(m=0;m<k.tracks.length;++m){var f=k.tracks[m],t;a:{t=f.data;for(var r=t.length,v=0;v<r;v+=2){if(t[v]==q){t=t[v+1];break a}if(t[v]>q){t=null;break a}}t=null}if(t)switch(t*=0.0174532925,f.name){case "rotateX.ANGLE":quat.rotateX(s,s,-t);break;case "rotateY.ANGLE":quat.rotateY(s,s,t);break;
case "rotateZ.ANGLE":quat.rotateZ(s,s,t)}}}d.tracks.push(h);for(m=0;m<k.tracks.length;++m)f=k.tracks[m],h=d.tracks.indexOf(f),-1!=h&&d.tracks.splice(h,1)}}},processMaterial:function(a){var b={specular_factor:"specular",transparent:"opacity"};a.object_class="StandardMaterial";a.id&&(a.id=a.id.replace(/[^a-z0-9\.\-]/gi,"_")+".json");void 0!==a.transparency&&(a.opacity=1);a.specular_factor&&a.specular_factor.length&&(a.specular_factor=a.specular_factor[0]);if(a.textures){var c={},e;for(e in a.textures){var g=
a.textures[e],f=e;b[f]&&(f=b[f]);var h=g.map_id;this.convert_filenames_to_lowercase&&(h=h.toLowerCase());var k=d.Material.COORDS_UV0;"TEX1"==g.uvs&&(k=d.Material.COORDS_UV1);g={texture:h,uvs:k};c[f]=g}a.textures=c}}});d.Formats.addSupportedFormat("bvh",{extension:"bvh",type:"scene",resource:"Scene",format:"text",dataType:"text",parse:function(a,b,c){var e=0,g=b=null,f=null,h=[],k=[],l=-1,n=-1,p=-1,m=0,q=[],s={Xposition:"x",Yposition:"y",Zposition:"z",Xrotation:"xrotation",Yrotation:"yrotation",Zrotation:"zrotation"},
t=!1;a=a.split("\n");for(var r=a.length,v=0;v<r;++v){var w=a[v].trim();if("#"!=w[0]&&""!=w)if(w=w.split(/[\s]+/),g=w[0],!e)switch(g){case "HIERARCHY":e=1}else if(1==e)switch(g){case "ROOT":f=w[1];f=f.replace(/[^a-z0-9\.\-]/gi,"_");b=f={name:f,node_type:"JOINT"};break;case "JOINT":g=f;h.push(g);f=w[1];f=f.replace(/[^a-z0-9\.\-]/gi,"_");f={name:f,node_type:"JOINT"};g.children||(g.children=[]);g.children.push(f);break;case "End":g=f;h.push(g);f={name:g.name+"_end",node_type:"JOINT"};g.children||(g.children=
[]);g.children.push(f);break;case "}":t?t=!1:(f=h.pop())||(f=b);break;case "CHANNELS":for(g=2;g<w.length;++g){var x=w[g].toLowerCase();s[x]&&(x=s[x]);var y={node:f,property:x,data:[]};k.push(y);f._channels||(f._channels={});f._channels_order||(f._channels_order=[]);f._channels[x]=y;f._channels_order.push(x)}break;case "OFFSET":g=f;w=w.slice(1).map(parseFloat);g.transform={position:w};break;case "MOTION":e=2}else if(2==e)"Frames:"==w[0]?l=parseInt(w[1]):"Frame"==w[0]&&"Time:"==w[1]&&(n=parseFloat(w[2])),
-1!=l&&-1!=n&&(p=l*n,e=3);else if(3==e){q.push(m*n);for(g=0;g<k.length;++g)k[g].data.push(parseFloat(w[g]));++m}}e=[];this.processMotion(b,e,q);q={root:b,object_class:"SceneNode",resources:{}};for(h=0;h<e.length;++h)e[h].duration=p;c={name:d.ResourcesManager.getBasename(c)+"_animation.wbin",object_class:"Animation",takes:{"default":{name:"default",duration:p,tracks:e}}};b.animation=c.name;q.resources[c.name]=c;console.log(q);return q},processMotion:function(a,b,c){var d=a._channels;if(d){var g=null,
f=null,h=vec3.fromValues(1,0,0),k=vec3.fromValues(0,1,0),l=vec3.fromValues(0,0,1);if(d.xposition||d.yposition||d.zposition)g={name:a.name+"/Transform/position",property:a.name+"/Transform/position",type:"vec3",value_size:3,data:[],packed_data:!0};if(d.xrotation||d.yrotation||d.zrotation)f={name:a.name+"/Transform/rotation",property:a.name+"/Transform/rotation",type:"quat",value_size:4,data:[],packed_data:!0};for(var n=0;n<c.length;++n){for(var p=c[n],m=vec3.create(),q=quat.create(),s=quat.create(),
t=0;t<a._channels_order.length;++t)switch(a._channels_order[t]){case "xposition":m[0]=d.xposition.data[n]+a.transform.position[0];break;case "yposition":m[1]=d.yposition.data[n]+a.transform.position[1];break;case "zposition":m[2]=d.zposition.data[n]+a.transform.position[2];break;case "xrotation":quat.setAxisAngle(s,h,d.xrotation.data[n]*DEG2RAD);quat.mul(q,q,s);break;case "yrotation":quat.setAxisAngle(s,k,d.yrotation.data[n]*DEG2RAD);quat.mul(q,q,s);break;case "zrotation":quat.setAxisAngle(s,l,d.zrotation.data[n]*
DEG2RAD),quat.mul(q,q,s)}g&&g.data.push(p,m[0],m[1],m[2]);f&&f.data.push(p,q[0],q[1],q[2],q[3])}g&&b.push(g);f&&b.push(f)}if(a.children)for(t=0;t<a.children.length;++t)this.processMotion(a.children[t],b,c)}});d.Formats.addSupportedFormat("ase",{extension:"ase",type:"mesh",resource:"Mesh",format:"text",dataType:"text",parse:function(a,b,c){b=b||{};var e=[],g=[];c=[];var f=null,h=[],k=[],l=null,l=null,n=0,p=-1,m=null,q=[],s=this.flipAxis;null!=b.flipAxis&&(s=b.flipAxis);b=s||b.flipNormals;a=a.split("\n");
for(var t=0;t<a.length;++t)if(l=a[t].replace(/[ \t]+/g," ").replace(/\s\s*$/,"")," "==l[0]&&(l=l.substr(1,l.length)),""!=l)if(l=l.split(" "),"*MESH"==l[0]){if(n+=1,h=[],1<n)break}else if("*NODE_NAME"==l[0])l[1].substr(1,l[1].length-2);else if("*MESH_VERTEX"==l[0])s?h.push([-1*parseFloat(l[2]),parseFloat(l[4]),parseFloat(l[3])]):h.push([parseFloat(l[2]),parseFloat(l[3]),parseFloat(l[4])]);else if("*MESH_FACE"==l[0]){var r=parseInt(l[17]);p!=r&&(p=r,null!=m&&(m.length=e.length/3-m.start,0<m.length&&
q.push(m)),m={name:"mat_"+r,start:e.length/3,length:-1,material:""});r=h[parseInt(l[3])];e.push(r[0],r[1],r[2]);r=h[parseInt(l[5])];e.push(r[0],r[1],r[2]);r=h[parseInt(l[7])];e.push(r[0],r[1],r[2])}else"*MESH_TVERTLIST"==l[0]?k=[]:"*MESH_TVERT"==l[0]?k.push([parseFloat(l[2]),parseFloat(l[3])]):"*MESH_TFACELIST"==l[0]?(f&&f.length&&c.push(f),f=[]):"*MESH_TFACE"==l[0]?(r=k[parseInt(l[2])],f.push(r[0],r[1]),r=k[parseInt(l[3])],f.push(r[0],r[1]),r=k[parseInt(l[4])],f.push(r[0],r[1])):"*MESH_MAPPINGCHANNEL"==
l[0]?(f&&c.push(f),f=[]):"*MESH_VERTEXNORMAL"==l[0]&&(b?g.push(-1*parseFloat(l[2]),parseFloat(l[4]),parseFloat(l[3])):g.push(parseFloat(l[2]),parseFloat(l[3]),parseFloat(l[4])));f&&c.push(f);f=e.length/3-m.start;m&&1<f&&(m.length=f,q.push(m));m={info:{}};m.vertices=new Float32Array(e);0<g.length&&(m.normals=new Float32Array(g));for(e=0;e<c.length;++e)g="",0<e&&(g=e+1),m["coords"+g]=new Float32Array(c[e]);m.bounding=d.Formats.computeMeshBounding(m.vertices);1<q.length&&(m.info.groups=q);return m}});
d.Formats.addSupportedFormat("jsmesh",{extension:"jsmesh",type:"mesh",format:"text",dataType:"string",parse:function(a,b){var c=null;"object"==typeof a?c=a:"string"==typeof a&&(c=JSON.parse(a));c.vertices.constructor==Array&&(c.vertices="number"==typeof c.vertices[0]?c.vertices:linearizeArray(c.vertices),c.normals&&(c.normals="number"==typeof c.normals[0]?c.normals:linearizeArray(c.normals)),c.coords&&(c.coords="number"==typeof c.coords[0]?c.coords:linearizeArray(c.coords)),c.triangles&&(c.triangles=
"number"==typeof c.triangles[0]?c.triangles:linearizeArray(c.triangles)),c.vertices=new Float32Array(c.vertices),c.normals&&(c.normals=new Float32Array(c.normals)),c.coords&&(c.coords=new Float32Array(c.coords)),c.triangles&&(c.triangles=new Uint16Array(c.triangles)));c.bounding||(c.bounding=d.Formats.computeMeshBounding(c.vertices));return c}});d.getCurveValueAt=function(a,b,c,d,g){if(g<b||g>c)return d;b=[b,d];for(var f=0,f=0;f<a.length;f+=1){var h=a[f];if(g==h[0])return h[1];if(g<h[0])return f=
(g-b[0])/(h[0]-b[0]),b[1]*(1-f)+h[1]*f;b=h}h=[c,d];f=(g-b[0])/(h[0]-b[0]);return b[1]*(1-f)+h[1]*f};d.resampleCurve=function(a,b,c,e,g){var f=[];f.length=g;for(var h=(c-b)/g,k=0;k<g;k++)f[k]=d.getCurveValueAt(a,b,c,e,b+h*k);return f};Object.prototype.hasOwnProperty("defineAttribute")||(Object.defineProperty(Object.prototype,"defineAttribute",{value:function(a,b,c){c&&"string"==typeof c&&(c={type:c});var d=this;"function"!=typeof this&&(this[a]=b,d=this.constructor);Object.defineProperty(d,"@"+a,{value:c||
{},enumerable:!1})},enumerable:!1,writable:!0}),Object.defineProperty(Object.prototype,"getAttribute",{value:function(a){a="@"+a;return this.hasOwnProperty(a)?this[a]:this.constructor&&this.constructor.hasOwnProperty(a)?this.constructor[a]:null},enumerable:!1,writable:!0}));String.prototype.hasOwnProperty("hashCode")||Object.defineProperty(String.prototype,"hashCode",{value:function(){var a=0,b,c,d;if(0==this.length)return a;b=0;for(d=this.length;b<d;++b)c=this.charCodeAt(b),a=(a<<5)-a+c,a|=0;return a},
enumerable:!1});Object.equals=function(a,b){if(a===b)return!0;if(!(a instanceof Object&&b instanceof Object)||a.constructor!==b.constructor)return!1;for(var c in a)if(a.hasOwnProperty(c)&&(!b.hasOwnProperty(c)||a[c]!==b[c]&&("object"!==typeof a[c]||!Object.equals(a[c],b[c]))))return!1;for(c in b)if(b.hasOwnProperty(c)&&!a.hasOwnProperty(c))return!1;return!0};Array.prototype.hasOwnProperty("equal")||Object.defineProperty(Array.prototype,"equal",{value:function(a){for(var b=0;b<this.length;++b)if(this[b]!=
a[b])return!1;return!0},enumerable:!1});Float32Array.prototype.hasOwnProperty("equal")||Object.defineProperty(Float32Array.prototype,"equal",{value:function(a){for(var b=0;b<this.length;++b)if(this[b]!=a[b])return!1;return!0},enumerable:!1});d.stringToTypedArray=function(a,b){for(var c=new Uint8Array(b?b:a.length),d=0;d<a.length;d++)c[d]=a.charCodeAt(d);return c};d.typedArrayToString=function(a,b){for(var c="",d=0;d<a.length;d++)if(0!=a[d]||b)c+=String.fromCharCode(a[d]);else break;return c};C=d.GlobalScene=
new d.Scene;d.newMeshNode=function(a,b){var c=new d.SceneNode(a);c.addComponent(new d.Components.MeshRenderer);c.setMesh(b);return c};d.newLightNode=function(a){a=new d.SceneNode(a);a.addComponent(new d.Components.Light);return a};d.newCameraNode=function(a){a=new d.SceneNode(a);a.addComponent(new d.Components.Camera);return a};da.LS=d})("undefined"!=typeof window?window:self);
