text: (function(exports,global){function Tw2RawData(){this.nextOffset=0,this.data=null,this.elements={}}function Tw2BinaryReader(data){this.data=data,this.cursor=0}function Tw2VertexElement(usage,usageIndex,type,elements,offset){this.usage=usage,this.usageIndex=usageIndex,this.type=type,this.elements=elements,this.offset=offset===void 0?0:offset,this.location=null,this.customSetter=null}function Tw2VertexDeclaration(){this.elements=[],this._elementsSorted=[]}function CompareDeclarationElements(a,b){return a.usage<b.usage?-1:a.usage>b.usage?1:a.usageIndex<b.usageIndex?-1:a.usageIndex>b.usageIndex?1:0}function Tw2ObjectReader(xmlNode){this.xmlNode=xmlNode}function Tw2Resource(){this.path="",this._isLoading=!1,this._isGood=!1,this._isPurged=!1,this._notifications=[],this.activeFrame=0,this.doNotPurge=0}function Inherit(derived,base){for(var i in base.prototype)i in derived.prototype||(derived.prototype[i]=base.prototype[i]);derived.prototype._super=base.prototype}function Tw2VariableStore(){this._variables={}}function Tw2MotherLode(){this._loadedObjects={},this.Find=function(path){return path in this._loadedObjects?this._loadedObjects[path]:null},this.Add=function(path,obj){this._loadedObjects[path]=obj},this.Remove=function(path){delete this._loadedObjects[path]},this.Clear=function(){this._loadedObjects={}},this.PurgeInactive=function(curFrame,frameLimit,frameDistance){for(var path in this._loadedObjects){var obj=this._loadedObjects[path];obj.doNotPurge||(obj._isPurged&&(console.log("Removed purged resource ",obj.path),delete this._loadedObjects[path]),obj._isGood&&(curFrame-obj.activeFrame)%frameLimit>=frameDistance&&obj.Unload()&&(console.info("Unloaded unused resource ",obj.path),delete this._loadedObjects[path]))}}}function Tw2LoadingObject(){this._super.constructor.call(this),this.object=null,this._redContents=null,this._inPrepare=null,this._objects=[]}function Tw2ResMan(){function _NormalizePath(path){return"str:/"==path.substr(0,5)?path:(path=path.toLowerCase(),path.replace("\\","/"),path)}function _GetPathExt(path){if("str:/"==path.substr(0,5)){var slash=path.indexOf("/",5);return-1==slash?null:path.substr(5,slash-5)}var dot=path.lastIndexOf(".");return-1==dot?null:path.substr(dot+1)}function _DoLoadResource(obj){return function(){readyState=0;try{readyState=this.readyState}catch(e){return console.error("ResMan:",' communication error when loading  "',obj.path,'" (readyState ',readyState,")"),obj.LoadFinished(!1),resMan._pendingLoads--,void 0}if(4===readyState){if(200===this.status){obj.LoadFinished(!0);var data=null,xml=null;try{data=this.responseText,xml=this.responseXML}catch(e){data=this.response}resMan._prepareQueue.push([obj,data,xml])}else console.error("ResMan:",' communication error when loading  "',obj.path,'" (code ',this.status,")"),obj.LoadFinished(!1);resMan._pendingLoads--}}}this.resourcePaths={},this.resourcePaths.res="res/",this._extensions={},this.motherLode=new Tw2MotherLode,this.maxPrepareTime=.05,this.prepareBudget=0,this._prepareQueue=[],this.autoPurgeResources=!0,this.activeFrame=0,this._purgeTime=0,this._purgeFrame=0,this._purgeFrameLimit=1e3,this.purgeTime=30,this._pendingLoads=0,this._noLoadFrames=0,this.IsLoading=function(){return 2>this._noLoadFrames},this.RegisterExtension=function(extension,constructor){this._extensions[extension]=constructor},this._CreateHttpRequest=function(){var httpRequest=null;if(window.XMLHttpRequest)httpRequest=new XMLHttpRequest;else if(window.ActiveXObject)try{httpRequest=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{httpRequest=new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}return httpRequest||console.error("ResMan:"," could not create an XMLHTTP instance"),httpRequest},this.LogPathString=function(path){return"str:/"==path.substr(0,5)&&path.length>64?path.substr(0,64)+"...":path},this.PrepareLoop=function(dt){0==this._prepareQueue.length&&0==this._pendingLoads?2>this._noLoadFrames&&this._noLoadFrames++:this._noLoadFrames=0,resMan.prepareBudget=resMan.maxPrepareTime;for(var now=new Date,startTime=now.getTime(),preparedCount=0;resMan._prepareQueue.length;){if(!resMan._prepareQueue[0][0].Prepare(resMan._prepareQueue[0][1],resMan._prepareQueue[0][2])){var now=new Date;console.info("Prepared ",resMan._prepareQueue[0][0].path," in ",.001*(now.getTime()-startTime)," secs"),resMan._prepareQueue.shift(),preparedCount++}var now=new Date;if(resMan.prepareBudget-=.001*(now.getTime()-startTime),0>resMan.prepareBudget)break}return this._purgeTime+=dt,this._purgeTime>1&&(this.activeFrame+=1,this._purgeTime-=Math.floor(this._purgeTime),this._purgeFrame+=1,this._purgeFrame>=5&&this.autoPurgeResources&&this.motherLode.PurgeInactive(this._purgeFrame,this._purgeFrameLimit,this.purgeTime)),!0},this.BuildUrl=function(resPath){var prefixIndex=resPath.indexOf(":/");if(-1==prefixIndex)return console.error("ResMan:",' invalid resource path: "',resPath,'"'),resPath;var prefix=resPath.substr(0,prefixIndex);return prefix in this.resourcePaths?this.resourcePaths[prefix]+resPath.substr(prefixIndex+2):(console.error("ResMan:",' invalid resource path: "',resPath,'"'),resPath)},this._LoadResource=function(obj){obj._isPurged=!1;var path=obj.path;if(this.motherLode.Add(path,obj),"DoCustomLoad"in obj&&obj.DoCustomLoad(path))return obj;var httpRequest=this._CreateHttpRequest();httpRequest.onreadystatechange=_DoLoadResource(obj),console.info('Requesting "',this.BuildUrl(path),'"'),httpRequest.open("GET",this.BuildUrl(path)),obj.requestResponseType&&(httpRequest.responseType=obj.requestResponseType),obj.LoadStarted();try{httpRequest.send(),this._pendingLoads++}catch(e){console.error("ResMan:"," error sending resource HTTP request: ",""+e)}},this.ReloadResource=function(resource){var path=resource.path;console.info("ResMan:","reloading resource ",path);var obj=this.motherLode.Find(path);return null===obj||obj.IsPurged()?(this._LoadResource(resource),resource):obj},this.GetResource=function(path){path=_NormalizePath(path);var obj=this.motherLode.Find(path);if(null!==obj)return obj.IsPurged()&&obj.Reload(),obj;var ext=_GetPathExt(path);if(null==ext)return console.error("ResMan:"," unknown extension for path ",this.LogPathString(path)),null;if(!(ext in this._extensions))return console.error("ResMan:"," unregistered extension  ",ext),null;var obj=new this._extensions[ext];return obj.path=path,this._LoadResource(obj),obj},this.GetObject=function(path,callback){this._GetObject(path,callback,!0)},this.GetObjectNoInitialize=function(path,callback){this._GetObject(path,callback,!1)},this._GetObject=function(path,callback,initialize){path=_NormalizePath(path);var obj=null;obj={};var res=this.motherLode.Find(path);if(null!==res)return res.AddObject(obj,callback,initialize),void 0;res=new Tw2LoadingObject,res.path=path,res.AddObject(obj,callback,initialize),this.motherLode.Add(path,res);var httpRequest=this._CreateHttpRequest();httpRequest.onreadystatechange=_DoLoadResource(res),console.info('Requesting "',this.BuildUrl(path),'"'),httpRequest.open("GET",this.BuildUrl(path)),res.LoadStarted(),obj._objectLoaded=!1;try{httpRequest.send(),this._pendingLoads++}catch(e){console.error("ResMan:"," error sending object HTTP request: ",""+e)}},this.Clear=function(){this.motherLode.Clear()}}function Tw2PerObjectData(){}function Tw2SamplerState(){this.registerIndex=0,this.minFilter=device.gl.LINEAR,this.maxFilter=device.gl.LINEAR,this.minFilterNoMips=device.gl.LINEAR,this.addressU=device.gl.REPEAT,this.addressV=device.gl.REPEAT,this.addressW=device.gl.REPEAT,this.anisotropy=1,this.samplerType=device.gl.TEXTURE_2D,this.isVolume=!1,this.hash=0}function Tw2FloatParameter(name,value){this.name=name!==void 0?name:"",this.value=value!==void 0?value:1,this.constantBuffer=null}function Tw2FloatParameter(name,value){this.name=name!==void 0?name:"",this.value=value!==void 0?value:1,this.constantBuffer=null}function Tw2Vector2Parameter(name,value){this.name=name!==void 0?name:"",this.value=value!==void 0?value:new Float32Array(1,1)}function Tw2Vector3Parameter(name,value){this.name=name!==void 0?name:"",this.value=value!==void 0?vec3.create(value):vec3.create([1,1,1]),this.constantBuffer=null,this.offset=0}function Tw2Vector4Parameter(name,value){this.name=name!==void 0?name:"",this.value=value!==void 0?value:quat4.create([1,1,1,1]),this.constantBuffer=null,this.offset=0}function Tw2MatrixParameter(name,value){this.name=name!==void 0?name:"",value!==void 0?this.value=value:(this.value=mat4.create(),mat4.identity(this.value)),this.constantBuffer=null,this.offset=0}function Tw2VariableParameter(name,variableName){this.name=name!==void 0?name:"",this.variableName=variableName!==void 0?variableName:""}function Tw2TextureParameter(name,texturePath){this.name=name!==void 0?name:"",this.textureRes=null,texturePath!==void 0?(this.resourcePath=texturePath,this.Initialize()):this.resourcePath=""}function Tw2TransformParameter(name){this.name=name!==void 0?name:"",this.scaling=vec3.create([1,1,1]),this.rotationCenter=vec3.create([0,0,0]),this.rotation=[0,0,0,1],this.translation=vec3.create([0,0,0]),this.worldTransform=mat4.create(),mat4.identity(this.worldTransform)}function Tw2Device(){this.RM_ANY=-1,this.RM_OPAQUE=0,this.RM_DECAL=1,this.RM_TRANSPARENT=2,this.RM_ADDITIVE=3,this.RM_DEPTH=4,this.RM_FULLSCREEN=5,this.RS_ZENABLE=7,this.RS_FILLMODE=8,this.RS_SHADEMODE=9,this.RS_ZWRITEENABLE=14,this.RS_ALPHATESTENABLE=15,this.RS_LASTPIXEL=16,this.RS_SRCBLEND=19,this.RS_DESTBLEND=20,this.RS_CULLMODE=22,this.RS_ZFUNC=23,this.RS_ALPHAREF=24,this.RS_ALPHAFUNC=25,this.RS_DITHERENABLE=26,this.RS_ALPHABLENDENABLE=27,this.RS_FOGENABLE=28,this.RS_SPECULARENABLE=29,this.RS_FOGCOLOR=34,this.RS_FOGTABLEMODE=35,this.RS_FOGSTART=36,this.RS_FOGEND=37,this.RS_FOGDENSITY=38,this.RS_RANGEFOGENABLE=48,this.RS_STENCILENABLE=52,this.RS_STENCILFAIL=53,this.RS_STENCILZFAIL=54,this.RS_STENCILPASS=55,this.RS_STENCILFUNC=56,this.RS_STENCILREF=57,this.RS_STENCILMASK=58,this.RS_STENCILWRITEMASK=59,this.RS_TEXTUREFACTOR=60,this.RS_WRAP0=128,this.RS_WRAP1=129,this.RS_WRAP2=130,this.RS_WRAP3=131,this.RS_WRAP4=132,this.RS_WRAP5=133,this.RS_WRAP6=134,this.RS_WRAP7=135,this.RS_CLIPPING=136,this.RS_LIGHTING=137,this.RS_AMBIENT=139,this.RS_FOGVERTEXMODE=140,this.RS_COLORVERTEX=141,this.RS_LOCALVIEWER=142,this.RS_NORMALIZENORMALS=143,this.RS_DIFFUSEMATERIALSOURCE=145,this.RS_SPECULARMATERIALSOURCE=146,this.RS_AMBIENTMATERIALSOURCE=147,this.RS_EMISSIVEMATERIALSOURCE=148,this.RS_VERTEXBLEND=151,this.RS_CLIPPLANEENABLE=152,this.RS_POINTSIZE=154,this.RS_POINTSIZE_MIN=155,this.RS_POINTSPRITEENABLE=156,this.RS_POINTSCALEENABLE=157,this.RS_POINTSCALE_A=158,this.RS_POINTSCALE_B=159,this.RS_POINTSCALE_C=160,this.RS_MULTISAMPLEANTIALIAS=161,this.RS_MULTISAMPLEMASK=162,this.RS_PATCHEDGESTYLE=163,this.RS_DEBUGMONITORTOKEN=165,this.RS_POINTSIZE_MAX=166,this.RS_INDEXEDVERTEXBLENDENABLE=167,this.RS_COLORWRITEENABLE=168,this.RS_TWEENFACTOR=170,this.RS_BLENDOP=171,this.RS_POSITIONDEGREE=172,this.RS_NORMALDEGREE=173,this.RS_SCISSORTESTENABLE=174,this.RS_SLOPESCALEDEPTHBIAS=175,this.RS_ANTIALIASEDLINEENABLE=176,this.RS_TWOSIDEDSTENCILMODE=185,this.RS_CCW_STENCILFAIL=186,this.RS_CCW_STENCILZFAIL=187,this.RS_CCW_STENCILPASS=188,this.RS_CCW_STENCILFUNC=189,this.RS_COLORWRITEENABLE1=190,this.RS_COLORWRITEENABLE2=191,this.RS_COLORWRITEENABLE3=192,this.RS_BLENDFACTOR=193,this.RS_SRGBWRITEENABLE=194,this.RS_DEPTHBIAS=195,this.RS_SEPARATEALPHABLENDENABLE=206,this.RS_SRCBLENDALPHA=207,this.RS_DESTBLENDALPHA=208,this.RS_BLENDOPALPHA=209,this.CULL_NONE=1,this.CULL_CW=2,this.CULL_CCW=3,this.CMP_NEVER=1,this.CMP_LESS=2,this.CMP_EQUAL=3,this.CMP_LEQUAL=4,this.CMP_GREATER=5,this.CMP_NOTEQUAL=6,this.CMP_GREATEREQUAL=7,this.CMP_ALWAYS=8,this.BLEND_ZERO=1,this.BLEND_ONE=2,this.BLEND_SRCCOLOR=3,this.BLEND_INVSRCCOLOR=4,this.BLEND_SRCALPHA=5,this.BLEND_INVSRCALPHA=6,this.BLEND_DESTALPHA=7,this.BLEND_INVDESTALPHA=8,this.BLEND_DESTCOLOR=9,this.BLEND_INVDESTCOLOR=10,this.BLEND_SRCALPHASAT=11,this.BLEND_BOTHSRCALPHA=12,this.BLEND_BOTHINVSRCALPHA=13,this.BLEND_BLENDFACTOR=14,this.BLEND_INVBLENDFACTOR=15,this.gl=null,this.debugMode=!1,this.mipLevelSkipCount=0,this.shaderModel="hi",this.enableAnisotropicFiltering=!0,this.effectDir="/effect.gles2/",this._scheduled=[],this._quadBuffer=null,this._cameraQuadBuffer=null,this._currentRenderMode=null,this._whiteTexture=null,this._whiteCube=null,this.world=mat4.create(),mat4.identity(this.world),this.worldInverse=mat4.create(),mat4.identity(this.worldInverse),this.view=mat4.create(),mat4.identity(this.view),this.viewInv=mat4.create(),mat4.identity(this.viewInv),this.projection=mat4.create(),mat4.identity(this.projection),this.eyePosition=vec3.create(),this.perObjectData=null,variableStore.RegisterVariable("WorldMat",this.world),variableStore.RegisterVariable("ViewMat",this.view),variableStore.RegisterVariable("ProjectionMat",this.projection),variableStore.RegisterType("ViewProjectionMat",Tw2MatrixParameter),variableStore.RegisterType("ViewportSize",Tw2Vector4Parameter),variableStore.RegisterType("Time",Tw2Vector4Parameter),this.frameCounter=0,this.startTime=new Date,this.CreateDevice=function(canvas,params){function tick(){requestAnimFrame(tick),self.Tick()}this.gl=null;try{this.gl=canvas.getContext("webgl",params)||canvas.getContext("experimental-webgl",params)}catch(e){}if(!this.gl)return console.error("Could not initialise WebGL"),!1;if(this.debugMode&&(this.gl=WebGLDebugUtils.makeDebugContext(this.gl)),this.gl.getExtension("OES_standard_derivatives"),this.alphaBlendBackBuffer=!params||params.alpha===void 0||params.alpha,this.antialiasing=this.gl.getParameter(this.gl.SAMPLES)>1,this.anisotropicFilter=this.gl.getExtension("EXT_texture_filter_anisotropic")||this.gl.getExtension("MOZ_EXT_texture_filter_anisotropic")||this.gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.anisotropicFilter&&(this.anisotropicFilter.maxAnisotropy=this.gl.getParameter(this.anisotropicFilter.MAX_TEXTURE_MAX_ANISOTROPY_EXT)),this.shaderBinary=this.gl.getExtension("CCP_shader_binary"),this.useBinaryShaders=!1,this.effectDir="/effect.gles2/",this.shaderBinary){var renderer=this.gl.getParameter(this.gl.RENDERER),maliVer=renderer.match(/Mali-(\w+).*/);maliVer&&(this.effectDir="/effect.gles2.mali"+maliVer[1]+"/",this.useBinaryShaders=!0)}canvas.width=canvas.clientWidth,canvas.height=canvas.clientHeight,this.viewportWidth=canvas.clientWidth,this.viewportHeight=canvas.clientHeight,this.canvas=canvas;var self=this;this._quadBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this._quadBuffer);var vertices=[1,1,0,1,1,1,-1,1,0,1,0,1,1,-1,0,1,1,0,-1,-1,0,1,0,0];return this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(vertices),this.gl.STATIC_DRAW),this._cameraQuadBuffer=this.gl.createBuffer(),this._quadDecl=new Tw2VertexDeclaration,this._quadDecl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_POSITION,0,this.gl.FLOAT,4,0)),this._quadDecl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,0,this.gl.FLOAT,2,16)),this._quadDecl.RebuildHash(),this.alphaTestState={},this.alphaTestState.states={},this.alphaTestState.states[this.RS_ALPHATESTENABLE]=0,this.alphaTestState.states[this.RS_ALPHAREF]=-1,this.alphaTestState.states[this.RS_ALPHAFUNC]=this.CMP_GREATER,this.alphaTestState.states[this.RS_CLIPPING]=0,this.alphaTestState.states[this.RS_CLIPPLANEENABLE]=0,this.alphaTestState.dirty=!1,this.alphaBlendState={},this.alphaBlendState.states={},this.alphaBlendState.states[this.RS_SRCBLEND]=this.BLEND_SRCALPHA,this.alphaBlendState.states[this.RS_DESTBLEND]=this.BLEND_INVSRCALPHA,this.alphaBlendState.states[this.RS_BLENDOP]=this.BLENDOP_ADD,this.alphaBlendState.states[this.RS_SEPARATEALPHABLENDENABLE]=0,this.alphaBlendState.states[this.RS_BLENDOPALPHA]=this.BLENDOP_ADD,this.alphaBlendState.states[this.RS_SRCBLENDALPHA]=this.BLEND_SRCALPHA,this.alphaBlendState.states[this.RS_DESTBLENDALPHA]=this.BLEND_INVSRCALPHA,this.alphaBlendState.dirty=!1,this.depthOffsetState={},this.depthOffsetState.states={},this.depthOffsetState.states[this.RS_SLOPESCALEDEPTHBIAS]=0,this.depthOffsetState.states[this.RS_DEPTHBIAS]=0,this.depthOffsetState.dirty=!1,this._blendTable=[-1,this.gl.ZERO,this.gl.ONE,this.gl.SRC_COLOR,this.gl.ONE_MINUS_SRC_COLOR,this.gl.SRC_ALPHA,this.gl.ONE_MINUS_SRC_ALPHA,this.gl.DST_ALPHA,this.gl.ONE_MINUS_DST_ALPHA,this.gl.DST_COLOR,this.gl.ONE_MINUS_DST_COLOR,this.gl.SRC_ALPHA_SATURATE,-1,-1,this.gl.CONSTANT_COLOR,this.gl.ONE_MINUS_CONSTANT_COLOR],this._shadowStateBuffer=new Float32Array(24),this._prevTime=null,requestAnimFrame(tick),!0},this.Schedule=function(render){this._scheduled[this._scheduled.length]=render},this.Tick=function(){(this.canvas.clientWidth!=this.viewportWidth||this.canvas.clientHeight!=this.viewportHeight)&&(this.canvas.width=this.canvas.clientWidth,this.canvas.height=this.canvas.clientHeight,this.viewportWidth=this.canvas.clientWidth,this.viewportHeight=this.canvas.clientHeight);var now=new Date;now=now.getTime();var currentTime=.001*(now-this.startTime),time=variableStore._variables.Time.value;time[3]=time[0],time[0]=currentTime,time[1]=currentTime-Math.floor(currentTime),time[2]=this.frameCounter;var viewportSize=variableStore._variables.ViewportSize.value;viewportSize[0]=this.viewportWidth,viewportSize[1]=this.viewportHeight,viewportSize[2]=this.viewportWidth,viewportSize[3]=this.viewportHeight;var dt=null==this._prevTime?0:.001*(now-this._prevTime);this._prevTime=now,resMan.PrepareLoop(dt);for(var i=0;this._scheduled.length>i;++i)this._scheduled[i](dt)||(this._scheduled.splice(i,1),--i);this.frameCounter++},this.SetWorld=function(matrix){mat4.set(matrix,this.world)},this.SetView=function(matrix){mat4.set(matrix,this.view),mat4.multiply(this.projection,this.view,variableStore._variables.ViewProjectionMat.value),mat4.inverse(this.view,this.viewInv),this.eyePosition.set([this.viewInv[12],this.viewInv[13],this.viewInv[14]])},this.SetProjection=function(matrix){mat4.set(matrix,this.projection),mat4.multiply(this.projection,this.view,variableStore._variables.ViewProjectionMat.value)},this.GetEyePosition=function(){return this.eyePosition},this.RenderFullScreenQuad=function(effect){if(effect){var effectRes=effect.GetEffectRes();if(effectRes.IsGood()){device.gl.bindBuffer(device.gl.ARRAY_BUFFER,this._quadBuffer);for(var pass=0;effect.GetPassCount()>pass;++pass){if(effect.ApplyPass(pass),!this._quadDecl.SetDeclaration(effect.GetPassInput(pass),24))return!1;this.ApplyShadowState(),device.gl.drawArrays(device.gl.TRIANGLE_STRIP,0,4)}}}},this.RenderTexture=function(texture){if(!this.blitEffect){this.blitEffect=new Tw2Effect,this.blitEffect.effectFilePath="res:/graphics/effect/managed/space/system/blit.fx";var param=new Tw2TextureParameter;param.name="BlitSource",this.blitEffect.parameters[param.name]=param,this.blitEffect.Initialize()}this.blitEffect.parameters.BlitSource.textureRes=texture,this.RenderFullScreenQuad(this.blitEffect)},this.RenderCameraSpaceQuad=function(effect){if(effect){var effectRes=effect.GetEffectRes();if(effectRes.IsGood()){var vertices=[1,1,0,1,1,1,-1,1,0,1,0,1,1,-1,0,1,1,0,-1,-1,0,1,0,0];vertices=new Float32Array(vertices);for(var projInv=mat4.inverse(this.projection,mat4.create()),i=0;4>i;++i){var vec=vertices.subarray(6*i,6*i+4);mat4.multiplyVec4(projInv,vec),vec3.scale(vec,1/vec[3]),vec[3]=1}this.gl.bindBuffer(device.gl.ARRAY_BUFFER,this._cameraQuadBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,vertices,this.gl.STATIC_DRAW);for(var pass=0;effect.GetPassCount()>pass;++pass){if(effect.ApplyPass(pass),!this._quadDecl.SetDeclaration(effect.GetPassInput(pass),24))return!1;this.ApplyShadowState(),device.gl.drawArrays(device.gl.TRIANGLE_STRIP,0,4)}}}},this._DwordToFloat=function(value){var b4=255&value,b3=(65280&value)>>8,b2=(16711680&value)>>16,b1=(4278190080&value)>>24,sign=1-2*(b1>>7),exp=(255&b1<<1|b2>>7)-127,sig=(127&b2)<<16|b3<<8|b4;return 0==sig&&-127==exp?0:sign*(1+sig*Math.pow(2,-23))*Math.pow(2,exp)},this.IsAlphaTestEnabled=function(){return this.alphaTestState.states[this.RS_ALPHATESTENABLE]},this.SetRenderState=function(state,value){var gl=this.gl;switch(state){case this.RS_ZENABLE:return value?gl.enable(gl.DEPTH_TEST):gl.disable(gl.DEPTH_TEST),void 0;case this.RS_ZWRITEENABLE:return gl.depthMask(value?!0:!1),void 0;case this.RS_ALPHATESTENABLE:case this.RS_ALPHAREF:case this.RS_ALPHAFUNC:case this.RS_CLIPPING:case this.RS_CLIPPLANEENABLE:return this.alphaTestState[state]!=value&&(this.alphaTestState.states[state]=value,this.alphaTestState.dirty=!0),void 0;case this.RS_SRCBLEND:case this.RS_DESTBLEND:case this.RS_BLENDOP:case this.RS_SEPARATEALPHABLENDENABLE:case this.RS_BLENDOPALPHA:case this.RS_SRCBLENDALPHA:case this.RS_DESTBLENDALPHA:return this.alphaBlendState[state]!=value&&(this.alphaBlendState.states[state]=value,this.alphaBlendState.dirty=!0),void 0;case this.RS_CULLMODE:switch(value){case this.CULL_NONE:return gl.disable(gl.CULL_FACE),void 0;case this.CULL_CW:return gl.enable(gl.CULL_FACE),gl.cullFace(gl.FRONT),void 0;case this.CULL_CCW:return gl.enable(gl.CULL_FACE),gl.cullFace(gl.BACK),void 0}return;case this.RS_ZFUNC:return gl.depthFunc(512+value-1),void 0;case this.RS_ALPHABLENDENABLE:return value?gl.enable(gl.BLEND):gl.disable(gl.BLEND),void 0;case this.RS_COLORWRITEENABLE:return gl.colorMask(0!=(1&value),0!=(2&value),0!=(4&value),0!=(8&value)),void 0;case this.RS_SCISSORTESTENABLE:return value?gl.enable(gl.SCISSOR_TEST):gl.disable(gl.SCISSOR_TEST),void 0;case this.RS_SLOPESCALEDEPTHBIAS:case this.RS_DEPTHBIAS:return value=this._DwordToFloat(value),this.depthOffsetState[state]!=value&&(this.depthOffsetState.states[state]=value,this.depthOffsetState.dirty=!0),void 0}},this.shadowHandles=null,this.ApplyShadowState=function(){if(this.alphaBlendState.dirty){var blendOp=this.gl.FUNC_ADD;2==this.alphaBlendState.states[this.RS_BLENDOP]?blendOp=this.gl.FUNC_SUBTRACT:3==this.alphaBlendState.states[this.RS_BLENDOP]&&(blendOp=this.gl.FUNC_REVERSE_SUBTRACT);var srcBlend=this._blendTable[this.alphaBlendState.states[this.RS_SRCBLEND]],destBlend=this._blendTable[this.alphaBlendState.states[this.RS_DESTBLEND]];if(this.alphaBlendState.states[this.RS_SEPARATEALPHABLENDENABLE]){var blendOpAlpha=this.gl.FUNC_ADD;2==this.alphaBlendState.states[this.RS_BLENDOP]?blendOpAlpha=this.gl.FUNC_SUBTRACT:3==this.alphaBlendState.states[this.RS_BLENDOP]&&(blendOpAlpha=this.gl.FUNC_REVERSE_SUBTRACT);var srcBlendAlpha=this._blendTable[this.alphaBlendState.states[this.RS_SRCBLENDALPHA]],destBlendAlpha=this._blendTable[this.alphaBlendState.states[this.RS_DESTBLENDALPHA]];this.gl.blendEquationSeparate(blendOp,blendOpAlpha),this.gl.blendFuncSeparate(srcBlend,destBlend,srcBlendAlpha,destBlendAlpha)}else this.gl.blendEquation(blendOp),this.gl.blendFunc(srcBlend,destBlend);this.alphaBlendState.dirty=!1}if(this.depthOffsetState.dirty&&(this.gl.polygonOffset(this.depthOffsetState.states[this.RS_SLOPESCALEDEPTHBIAS],this.depthOffsetState.states[this.RS_DEPTHBIAS]),this.depthOffsetState.dirty=!1),this.shadowHandles&&this.alphaTestState.states[this.RS_ALPHATESTENABLE]){switch(this.alphaTestState.states[this.RS_ALPHAFUNC]){case this.CMP_NEVER:var alphaTestFunc=0,invertedAlphaTest=1,alphaTestRef=-256;break;case this.CMP_LESS:var alphaTestFunc=0,invertedAlphaTest=-1,alphaTestRef=this.alphaTestState.states[this.RS_ALPHAREF]-1;break;case this.CMP_EQUAL:var alphaTestFunc=1,invertedAlphaTest=0,alphaTestRef=this.alphaTestState.states[this.RS_ALPHAREF];break;case this.CMP_LEQUAL:var alphaTestFunc=0,invertedAlphaTest=-1,alphaTestRef=this.alphaTestState.states[this.RS_ALPHAREF];break;case this.CMP_GREATER:var alphaTestFunc=0,invertedAlphaTest=1,alphaTestRef=-this.alphaTestState.states[this.RS_ALPHAREF]-1;break;case this.CMP_GREATEREQUAL:var alphaTestFunc=0,invertedAlphaTest=1,alphaTestRef=-this.alphaTestState.states[this.RS_ALPHAREF];break;default:var alphaTestFunc=0,invertedAlphaTest=0,alphaTestRef=1}var clipPlaneEnable=0;device.gl.uniform4f(this.shadowHandles.shadowStateInt,invertedAlphaTest,alphaTestRef,alphaTestFunc,clipPlaneEnable)}},this.SetStandardStates=function(renderMode){if(this._currentRenderMode!=renderMode){switch(this.gl.frontFace(this.gl.CW),renderMode){case this.RM_OPAQUE:this.SetRenderState(this.RS_ZENABLE,!0),this.SetRenderState(this.RS_ZWRITEENABLE,!0),this.SetRenderState(this.RS_ZFUNC,this.CMP_LEQUAL),this.SetRenderState(this.RS_CULLMODE,this.CULL_CW),this.SetRenderState(this.RS_ALPHABLENDENABLE,!1),this.SetRenderState(this.RS_ALPHATESTENABLE,!1),this.SetRenderState(this.RS_SEPARATEALPHABLENDENABLE,!1),this.SetRenderState(this.RS_SLOPESCALEDEPTHBIAS,0),this.SetRenderState(this.RS_DEPTHBIAS,0),this.SetRenderState(this.RS_COLORWRITEENABLE,15);break;case this.RM_DECAL:this.SetRenderState(this.RS_ALPHABLENDENABLE,!1),this.SetRenderState(this.RS_ALPHATESTENABLE,!0),this.SetRenderState(this.RS_ALPHAFUNC,this.CMP_GREATER),this.SetRenderState(this.RS_ALPHAREF,127),this.SetRenderState(this.RS_ZENABLE,!0),this.SetRenderState(this.RS_ZWRITEENABLE,!0),this.SetRenderState(this.RS_ZFUNC,this.CMP_LEQUAL),this.SetRenderState(this.RS_CULLMODE,this.CULL_CW),this.SetRenderState(this.RS_BLENDOP,this.BLENDOP_ADD),this.SetRenderState(this.RS_SLOPESCALEDEPTHBIAS,0),this.SetRenderState(this.RS_DEPTHBIAS,0),this.SetRenderState(this.RS_SEPARATEALPHABLENDENABLE,!1),this.SetRenderState(this.RS_COLORWRITEENABLE,15);break;case this.RM_TRANSPARENT:this.SetRenderState(this.RS_CULLMODE,this.CULL_CW),this.SetRenderState(this.RS_ALPHABLENDENABLE,!0),this.SetRenderState(this.RS_SRCBLEND,this.BLEND_SRCALPHA),this.SetRenderState(this.RS_DESTBLEND,this.BLEND_INVSRCALPHA),this.SetRenderState(this.RS_BLENDOP,this.BLENDOP_ADD),this.SetRenderState(this.RS_ZENABLE,!0),this.SetRenderState(this.RS_ZWRITEENABLE,!1),this.SetRenderState(this.RS_ZFUNC,this.CMP_LEQUAL),this.SetRenderState(this.RS_ALPHATESTENABLE,!1),this.SetRenderState(this.RS_SLOPESCALEDEPTHBIAS,0),this.SetRenderState(this.RS_DEPTHBIAS,0),this.SetRenderState(this.RS_SEPARATEALPHABLENDENABLE,!1),this.SetRenderState(this.RS_COLORWRITEENABLE,15);break;case this.RM_ADDITIVE:this.SetRenderState(this.RS_CULLMODE,this.CULL_NONE),this.SetRenderState(this.RS_ALPHABLENDENABLE,!0),this.SetRenderState(this.RS_SRCBLEND,this.BLEND_ONE),this.SetRenderState(this.RS_DESTBLEND,this.BLEND_ONE),this.SetRenderState(this.RS_BLENDOP,this.BLENDOP_ADD),this.SetRenderState(this.RS_ZENABLE,!0),this.SetRenderState(this.RS_ZWRITEENABLE,!1),this.SetRenderState(this.RS_ZFUNC,this.CMP_LEQUAL),this.SetRenderState(this.RS_ALPHATESTENABLE,!1),this.SetRenderState(this.RS_SLOPESCALEDEPTHBIAS,0),this.SetRenderState(this.RS_DEPTHBIAS,0),this.SetRenderState(this.RS_SEPARATEALPHABLENDENABLE,!1),this.SetRenderState(this.RS_COLORWRITEENABLE,15);break;case this.RM_FULLSCREEN:this.SetRenderState(this.RS_ALPHABLENDENABLE,!1),this.SetRenderState(this.RS_ALPHATESTENABLE,!1),this.SetRenderState(this.RS_CULLMODE,this.CULL_NONE),this.SetRenderState(this.RS_ZENABLE,!1),this.SetRenderState(this.RS_ZWRITEENABLE,!1),this.SetRenderState(this.RS_ZFUNC,this.CMP_ALWAYS),this.SetRenderState(this.RS_SLOPESCALEDEPTHBIAS,0),this.SetRenderState(this.RS_DEPTHBIAS,0),this.SetRenderState(this.RS_SEPARATEALPHABLENDENABLE,!1),this.SetRenderState(this.RS_COLORWRITEENABLE,15);break;default:return}this._currentRenderMode=renderMode}},this.GetFallbackTexture=function(){return null==this._whiteTexture&&(this._whiteTexture=device.gl.createTexture(),device.gl.bindTexture(device.gl.TEXTURE_2D,this._whiteTexture),device.gl.texImage2D(device.gl.TEXTURE_2D,0,device.gl.RGBA,1,1,0,device.gl.RGBA,device.gl.UNSIGNED_BYTE,new Uint8Array([0,0,0,0])),device.gl.texParameteri(device.gl.TEXTURE_2D,device.gl.TEXTURE_WRAP_S,device.gl.CLAMP_TO_EDGE),device.gl.texParameteri(device.gl.TEXTURE_2D,device.gl.TEXTURE_WRAP_T,device.gl.CLAMP_TO_EDGE),device.gl.texParameteri(device.gl.TEXTURE_2D,device.gl.TEXTURE_MAG_FILTER,device.gl.NEAREST),device.gl.texParameteri(device.gl.TEXTURE_2D,device.gl.TEXTURE_MIN_FILTER,device.gl.NEAREST),device.gl.bindTexture(device.gl.TEXTURE_2D,null)),this._whiteTexture},this.GetFallbackCubeMap=function(){if(null==this._whiteCube){this._whiteCube=device.gl.createTexture(),device.gl.bindTexture(device.gl.TEXTURE_CUBE_MAP,this._whiteCube);for(var j=0;6>j;++j)device.gl.texImage2D(device.gl.TEXTURE_CUBE_MAP_POSITIVE_X+j,0,device.gl.RGBA,1,1,0,device.gl.RGBA,device.gl.UNSIGNED_BYTE,new Uint8Array([0,0,0,0]));device.gl.texParameteri(device.gl.TEXTURE_CUBE_MAP,device.gl.TEXTURE_WRAP_S,device.gl.CLAMP_TO_EDGE),device.gl.texParameteri(device.gl.TEXTURE_CUBE_MAP,device.gl.TEXTURE_WRAP_T,device.gl.CLAMP_TO_EDGE),device.gl.texParameteri(device.gl.TEXTURE_CUBE_MAP,device.gl.TEXTURE_MAG_FILTER,device.gl.NEAREST),device.gl.texParameteri(device.gl.TEXTURE_CUBE_MAP,device.gl.TEXTURE_MIN_FILTER,device.gl.NEAREST),device.gl.bindTexture(device.gl.TEXTURE_CUBE_MAP,null)}return this._whiteCube}}function Tw2BatchAccumulator(sorting){this.batches=[],this.count=0,this._sortMethod=sorting}function Tw2RenderBatch(){this.renderMode=device.RM_ANY,this.perObjectData=null}function Tw2ForwardingRenderBatch(){this.geometryProvider=null}function Tw2GeometryBatch(){this._super.constructor.call(this),this.geometryRes=null,this.meshIx=0,this.start=0,this.count=1,this.effect=null,this.batchDepth=0}function Tw2GeometryLineBatch(){this._super.constructor.call(this),this.geometryRes=null,this.meshIx=0,this.start=0,this.count=1,this.effect=null,this.batchDepth=0}function Tw2GeometryMeshArea(){this.name="",this.start=0,this.count=0,this.minBounds=vec3.create(),this.maxBounds=vec3.create(),this.boundsSpherePosition=vec3.create(),this.boundsSphereRadius=0}function Tw2GeometryMeshBinding(){this.mesh=null,this.bones=[]}function Tw2GeometryModel(){this.name="",this.meshBindings=[],this.skeleton=null}function Tw2GeometrySkeleton(){this.bones=[]}function Tw2GeometryBone(){this.name="",this.parentIndex=-1,this.position=vec3.create(),this.orientation=quat4.create(),this.scaleShear=mat3.create(),this.localTransform=mat4.create(),this.worldTransform=mat4.create(),this.worldTransformInv=mat4.create()}function Tw2GeometryAnimation(){this.name="",this.duration=0,this.trackGroups=[]}function Tw2GeometryTrackGroup(){this.name="",this.model=null,this.transformTracks=[]}function Tw2GeometryTransformTrack(){this.name="",this.position=null,this.orientation=null,this.scaleShear=null}function Tw2GeometryCurve(){this.dimension=0,this.degree=0,this.knots=null,this.controls=null}function Tw2BlendShapeData(){this.name="",this.declaration=new Tw2VertexDeclaration,this.buffers=[],this.indexes=null,this.weightProxy=null}function Tw2GeometryMesh(){this.name="",this.declaration=new Tw2VertexDeclaration,this.areas=[],this.buffer=null,this.bufferData=null,this.indexes=null,this.indexType=0,this.minBounds=vec3.create(),this.maxBounds=vec3.create(),this.boundsSpherePosition=vec3.create(),this.boundsSphereRadius=0,this.bones=[]}function Tw2GeometryRes(){this._super.constructor.call(this),this.meshes=[],this.minBounds=vec3.create(),this.maxBounds=vec3.create(),this.boundsSpherePosition=vec3.create(),this.boundsSphereRadius=0,this.models=[],this.animations=[],this.systemMirror=!1,this._instanceCount=1}function boundsIncludePoint(minBounds,maxBounds,point){minBounds[0]>point[0]&&(minBounds[0]=point[0]),minBounds[1]>point[1]&&(minBounds[1]=point[1]),minBounds[2]>point[2]&&(minBounds[2]=point[2]),maxBounds[0]<point[0]&&(maxBounds[0]=point[0]),maxBounds[1]<point[1]&&(maxBounds[1]=point[1]),maxBounds[2]<point[2]&&(maxBounds[2]=point[2])}function Tw2TextureRes(){this._super.constructor.call(this),this.texture=null,this.isCube=!1,this.images=[],this.width=0,this.height=0,this._facesLoaded=0,this.hasMipMaps=!1,this._currentSampler=0}function Tw2EffectRes(){this._super.constructor.call(this),this.passes=[],this.annotations={}}function Tw2Effect(){this.name="",this.effectFilePath="",this.effectRes=null,this.parameters={},this.passes=[]}function Tw2MeshArea(){this.name="",this.effect=null,this.meshIndex=0,this.index=0,this.count=1,this.debugIsHidden=!1}function Tw2MeshLineArea(){this.name="",this.effect=null,this.meshIndex=0,this.index=0,this.count=1,this.debugIsHidden=!1
  }function Tw2Mesh(){this.name="",this.meshIndex=0,this.geometryResPath="",this.lowDetailGeometryResPath="",this.geometryResource=null,this.opaqueAreas=[],this.transparentAreas=[],this.transparentAreas=[],this.additiveAreas=[],this.pickableAreas=[],this.decalAreas=[],this.depthAreas=[],this.debugIsHidden=!1}function Tw2Track(){this.trackRes=null,this.bone=null}function Tw2TrackGroup(){this.trackGroupRes=null,this.model=null,this.transformTracks=[]}function Tw2Animation(){this.animationRes=null,this.time=0,this.timeScale=1,this.cycle=!1,this.isPlaying=!1,this.callback=null,this.trackGroups=[]}function Tw2Bone(){this.boneRes=null,this.localTransform=mat4.create(),this.worldTransform=mat4.create(),this.offsetTransform=mat4.create()}function Tw2Model(){this.modelRes=null,this.bones=[]}function Tw2AnimationController(geometryResource){this.geometryResources=[],this.models=[],this.animations=[],this.meshBindings=[],this.loaded=!1,this.update=!0,geometryResource!==void 0&&this.SetGeometryResource(geometryResource)}function Tw2RenderTarget(){this.texture=null,this._frameBuffer=null,this.width=null,this.height=null,this.hasDepth=null}function Tw2InstancedMesh(){this._super.constructor.call(this),this.instanceGeometryResource=null,this.instanceGeometryResPath="",this.instanceMeshIndex=0,this.minBounds=vec3.create(),this.maxBounds=vec3.create()}function Tw2InstancedMeshBatch(){this._super.constructor.call(this),this.instanceMesh=null}function EveLocator(){this.name="",this.transform=mat4.create()}function EveBoosterSet(){this.display=!0,this.effect=null,this.glows=null,this.glowScale=1,this.glowColor=[0,0,0,0],this.symHaloScale=1,this.haloScaleX=1,this.haloScaleY=1,this.maxVel=250,this.haloColor=[0,0,0,0],this.alwaysOn=!0,this._parentTransform=mat4.create(),this._wavePhase=[],this._boosterTransforms=[],this._positions=device.gl.createBuffer(),this._decl=new Tw2VertexDeclaration,this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_POSITION,0,device.gl.FLOAT,3,0)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,0,device.gl.FLOAT,2,12)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,1,device.gl.FLOAT,4,20)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,2,device.gl.FLOAT,4,36)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,3,device.gl.FLOAT,4,52)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,4,device.gl.FLOAT,4,68)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,5,device.gl.FLOAT,1,84)),this._decl.RebuildHash(),this._perObjectData=new Tw2PerObjectData,this._perObjectData.perObjectVSData=new Tw2RawData,this._perObjectData.perObjectVSData.Declare("WorldMat",16),this._perObjectData.perObjectVSData.Declare("Shipdata",4),this._perObjectData.perObjectVSData.Create(),this.rebuildPending=!1}function EveBoosterBatch(){this.renderMode=device.RM_ANY,this.perObjectData=null,this.boosters=null}function EveSpriteSet(){this.sprites=[],this.effect=null,this._time=0,this._vertexBuffer=null,this._indexBuffer=null,this._decl=new Tw2VertexDeclaration,this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,5,device.gl.FLOAT,1,0)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_POSITION,0,device.gl.FLOAT,3,4)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_COLOR,0,device.gl.FLOAT,3,16)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,0,device.gl.FLOAT,1,28)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,1,device.gl.FLOAT,1,32)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,2,device.gl.FLOAT,1,36)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,3,device.gl.FLOAT,1,40)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,4,device.gl.FLOAT,1,44)),this._decl.RebuildHash()}function EveSpriteSetBatch(){this._super.constructor.call(this),this.spriteSet=null}function EveSpriteSetItem(){this.name="",this.position=vec3.create([0,0,0]),this.blinkRate=0,this.blinkPhase=0,this.minScale=1,this.maxScale=1,this.falloff=0,this.color=vec3.create([0,0,0])}function EveSpotlightSetItem(){this.name="",this.transform=mat4.create(),this.coneColor=quat4.create(),this.spriteColor=quat4.create(),this.flareColor=quat4.create(),this.spriteScale=vec3.create()}function EveSpotlightSet(){this.name="",this.display=!0,this.coneEffect=null,this.glowEffect=null,this.spotlightItems=[],this._coneVertexBuffer=null,this._spriteVertexBuffer=null,this._indexBuffer=null,this._decl=new Tw2VertexDeclaration,this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_COLOR,0,device.gl.FLOAT,4,0)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,0,device.gl.FLOAT,4,16)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,1,device.gl.FLOAT,4,32)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,2,device.gl.FLOAT,4,48)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,3,device.gl.FLOAT,3,64)),this._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,4,device.gl.FLOAT,1,76)),this._decl.RebuildHash()}function EveSpotlightSetBatch(){this._super.constructor.call(this),this.spotlightSet=null}function EveBasicPerObjectData(){}function EveTransform(){this.NONE=0,this.BILLBOARD=1,this.TRANSLATE_WITH_CAMERA=2,this.LOOK_AT_CAMERA=3,this.SIMPLE_HALO=4,this.EVE_CAMERA_ROTATION_ALIGNED=100,this.EVE_BOOSTER=101,this.EVE_SIMPLE_HALO=102,this.EVE_CAMERA_ROTATION=103,this.name="",this.display=!0,this.useDistanceBasedScale=!1,this.modifier=this.NONE,this.scaling=vec3.create([1,1,1]),this.translation=vec3.create([0,0,0]),this.rotation=[0,0,0,1],this.localTransform=mat4.create(),this.rotationTransform=mat4.create(),mat4.identity(this.localTransform),this.worldTransform=mat4.create(),mat4.identity(this.worldTransform),this.sortValueMultiplier=1,this.distanceBasedScaleArg1=.2,this.distanceBasedScaleArg2=.63,this.particleSystems=[],this.particleEmitters=[],this._perObjectData=new EveBasicPerObjectData,this._perObjectData.perObjectFFEData=new Tw2RawData,this._perObjectData.perObjectFFEData.Declare("World",16),this._perObjectData.perObjectFFEData.Declare("WorldInverseTranspose",16),this._perObjectData.perObjectFFEData.Create(),this.children=[],this.mesh=null,this._mat4Cache=[mat4.create(),mat4.create()],this._vec3Cache=[];for(var i=0;7>i;++i)this._vec3Cache[i]=vec3.create()}function EveTurretData(){this.visible=!0,this.localTransform=mat4.create(),this.worldTransform=mat4.create()}function EveTurretSet(){this.name="",this.boundingSphere=[0,0,0,0],this.bottomClipHeight=0,this.locatorName="",this.turretEffect=null,this.geometryResPath="",this.sysBoneHeight=0,this.firingEffectResPath="",this.firingEffect=null,this.display=!0,this.geometryResource=null,this.animation=new Tw2AnimationController,this.turrets=[],this.STATE_INACTIVE=0,this.STATE_IDLE=1,this.STATE_FIRING=2,this.STATE_PACKING=3,this.STATE_UNPACKING=4,this.state=this.STATE_IDLE,this.targetPosition=vec3.create(),this._perObjectData=new Tw2PerObjectData,this._perObjectData.perObjectVSData=new Tw2RawData,this._perObjectData.perObjectVSData.Declare("clipData",4),this._perObjectData.perObjectVSData.Declare("shipMatrix",16),this._perObjectData.perObjectVSData.Declare("turretData0",4),this._perObjectData.perObjectVSData.Declare("turretData1",4),this._perObjectData.perObjectVSData.Declare("turretData2",4),this._perObjectData.perObjectVSData.Declare("turretWorld0",16),this._perObjectData.perObjectVSData.Declare("turretWorld1",16),this._perObjectData.perObjectVSData.Declare("turretWorld2",16),this._perObjectData.perObjectVSData.Declare("turretPose0",180),this._perObjectData.perObjectVSData.Declare("turretPose1",180),this._perObjectData.perObjectVSData.Declare("turretPose2",180),this._perObjectData.perObjectVSData.Create(),this.worldNames=["turretWorld0","turretWorld1","turretWorld2"]}function EveSpaceObject(){this.name="",this.mesh=null,this.spriteSets=[],this.boundingSphereCenter=vec3.create(),this.boundingSphereRadius=0,this.locators=[],this.turretSets=[],this.decals=[],this.spotlightSets=[],this.transform=mat4.create(),mat4.identity(this.transform),this.children=[],this._perObjectData=new Tw2PerObjectData,this._perObjectData.perObjectVSData=new Tw2RawData,this._perObjectData.perObjectVSData.Declare("WorldMat",16),this._perObjectData.perObjectVSData.Declare("Shipdata",4),this._perObjectData.perObjectVSData.Declare("JointMat",196),this._perObjectData.perObjectVSData.Create(),this._perObjectData.perObjectPSData=new Tw2RawData,this._perObjectData.perObjectPSData.Declare("Shipdata",4),this._perObjectData.perObjectPSData.Create(),this.animation=new Tw2AnimationController}function EveShip(){this._super.constructor.call(this),this.boosterGain=1,this.boosters=null,this.turretSets=[],this._turretSetsLocatorInfo=[]}function EveTurretSetLocatorInfo(){this.isJoint=!1,this.locatorTransforms=[]}function EveSpaceObjectDecal(){this.display=!0,this.decalEffect=null,this.name="",this.decalGeometryPath="",this.decalIndex=0,this.decalGeometry=null,this.position=vec3.create(),this.rotation=quat4.create(),this.scaling=vec3.create(),this.decalMatrix=mat4.create(),this.invDecalMatrix=mat4.create(),this.parentGeometry=null,this._perObjectData=new Tw2PerObjectData,this._perObjectData.perObjectVSData=new Tw2RawData,this._perObjectData.perObjectVSData.Declare("worldMatrix",16),this._perObjectData.perObjectVSData.Declare("invWorldMatrix",16),this._perObjectData.perObjectVSData.Declare("decalMatrix",16),this._perObjectData.perObjectVSData.Declare("invDecalMatrix",16),this._perObjectData.perObjectVSData.Create(),variableStore.RegisterType("u_DecalMatrix",Tw2MatrixParameter),variableStore.RegisterType("u_InvDecalMatrix",Tw2MatrixParameter)}function EvePlanet(){this.highDetail=new EveTransform,this.effectHeight=new Tw2Effect,this.itemID=0,this.heightMapResPath1="",this.heightMapResPath2="",this.heightMap=new Tw2RenderTarget,this.hightDirty=!1,this.lockedResources=[]}function EveOccluder(){if(this.name="",this.display=!0,this.value=1,this.sprites=[],variableStore.RegisterType("OccluderValue",Tw2Vector4Parameter),!EveOccluder._collectEffect){EveOccluder._collectEffect=new Tw2Effect,EveOccluder._collectEffect.effectFilePath="res:/graphics/effect/managed/space/specialfx/lensflares/collectsamples.fx";var param=new Tw2TextureParameter;param.name="BackBuffer",EveOccluder._collectEffect.parameters[param.name]=param;var param=new Tw2Vector4Parameter;param.name="OccluderPosition",EveOccluder._collectEffect.parameters[param.name]=param;var param=new Tw2Vector3Parameter;param.name="OccluderIndex",EveOccluder._collectEffect.parameters[param.name]=param,EveOccluder._collectEffect.Initialize(),EveOccluder._vertexBuffer=null,EveOccluder._decl=new Tw2VertexDeclaration,EveOccluder._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_POSITION,0,device.gl.FLOAT,2,0)),EveOccluder._decl.elements.push(new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,0,device.gl.FLOAT,2,8)),EveOccluder._decl.RebuildHash();for(var vb=new Float32Array(6120),index=0,i=0;16>i;++i)for(var j=0;16>j;++j){var x=2*((i+Math.random())/16)-1,y=2*((j+Math.random())/16)-1;vb[index++]=1,vb[index++]=1,vb[index++]=x,vb[index++]=y,vb[index++]=-1,vb[index++]=1,vb[index++]=x,vb[index++]=y,vb[index++]=1,vb[index++]=-1,vb[index++]=x,vb[index++]=y,vb[index++]=-1,vb[index++]=1,vb[index++]=x,vb[index++]=y,vb[index++]=1,vb[index++]=-1,vb[index++]=x,vb[index++]=y,vb[index++]=-1,vb[index++]=-1,vb[index++]=x,vb[index++]=y}EveOccluder._vertexBuffer=device.gl.createBuffer(),device.gl.bindBuffer(device.gl.ARRAY_BUFFER,EveOccluder._vertexBuffer),device.gl.bufferData(device.gl.ARRAY_BUFFER,vb,device.gl.STATIC_DRAW),device.gl.bindBuffer(device.gl.ARRAY_BUFFER,null)}}function EveLensflare(){this.name="",this.display=!0,this.update=!0,this.doOcclusionQueries=!0,this.cameraFactor=20,this.position=vec3.create(),this.flares=[],this.occluders=[],this.backgroundOccluders=[],this.occlusionIntensity=1,this.backgroundOcclusionIntensity=1,this._directionVar=variableStore.RegisterVariable("LensflareFxDirectionScale",quat4.create()),variableStore.RegisterVariable("LensflareFxOccScale",quat4.create([1,1,0,0])),this._direction=vec3.create(),this._transform=mat4.create(),EveLensflare.backBuffer||(EveLensflare.backBuffer=new Tw2TextureRes,EveLensflare.backBuffer.Attach(device.gl.createTexture()),EveLensflare.backBuffer.width=0,EveLensflare.backBuffer.height=0,EveLensflare.backBuffer.hasMipMaps=!1,EveLensflare.occluderLevels=new Tw2RenderTarget)}function EveSpaceScene(){this.lensflares=[],this.objects=[],this.backgroundEffect=null,this.envMapResPath="",this.envMap1ResPath="",this.envMap2ResPath="",this.envMap3ResPath="",this.fogStart=0,this.fogEnd=0,this.fogMax=0,this.sunDirection=vec3.create([1,-1,1]),this.sunDiffuseColor=quat4.create([1,1,1,1]),this.ambientColor=quat4.create([.1,.1,.1,1]),this.fogColor=quat4.create([1,1,1,1]),this.envMapScaling=vec3.create([1,1,1]),this.envMapRotation=quat4.create([0,0,0,1]),this.renderDebugInfo=!1,this.backgroundRenderingEnabled=!0,this.envMapRes=null,this.envMap1Res=null,this.envMap2Res=null,this.envMap3Res=null,this._envMapHandle=variableStore.RegisterVariable("EveSpaceSceneEnvMap",""),this._envMap1Handle=variableStore.RegisterVariable("EnvMap1",""),this._envMap2Handle=variableStore.RegisterVariable("EnvMap2",""),this._envMap3Handle=variableStore.RegisterVariable("EnvMap3",""),this._debugHelper=null,this._batches=new Tw2BatchAccumulator,this._perFrameVS=new Tw2RawData,this._perFrameVS.Declare("ViewInverseTransposeMat",16),this._perFrameVS.Declare("ViewProjectionMat",16),this._perFrameVS.Declare("ViewMat",16),this._perFrameVS.Declare("ProjectionMat",16),this._perFrameVS.Declare("ShadowViewMat",16),this._perFrameVS.Declare("ShadowViewProjectionMat",16),this._perFrameVS.Declare("EnvMapRotationMat",16),this._perFrameVS.Declare("SunData.DirWorld",4),this._perFrameVS.Declare("SunData.DiffuseColor",4),this._perFrameVS.Declare("FogFactors",4),this._perFrameVS.Declare("TargetResolution",4),this._perFrameVS.Declare("ViewportAdjustment",4),this._perFrameVS.Declare("SceneData.AmbientColor",4),this._perFrameVS.Declare("SceneData.FogColor",4),this._perFrameVS.Create(),this._perFramePS=new Tw2RawData,this._perFramePS.Declare("ViewInverseTransposeMat",16),this._perFramePS.Declare("ProjectionMat",16),this._perFramePS.Declare("ViewMat",16),this._perFramePS.Declare("EnvMapRotationMat",16),this._perFramePS.Declare("SunData.DirWorld",4),this._perFramePS.Declare("SunData.DiffuseColor",4),this._perFramePS.Declare("SceneData.AmbientColor",4),this._perFramePS.Declare("SceneData.FogColor",4),this._perFramePS.Declare("ShadowCameraRange",4),this._perFramePS.Declare("TargetResolution",4),this._perFramePS.Create(),variableStore.RegisterVariable("ShadowLightness",0)}function Tw2PostProcess(){this.width=0,this.height=0,this.texture=null,this.quadRT0=new Tw2RenderTarget,this.quadRT1=new Tw2RenderTarget,this.steps=[],this.steps[0]=new Tw2Effect,this.steps[0]={effect:new Tw2Effect,rt:this.quadRT1,inputs:{BlitCurrent:null}},this.steps[0].effect.effectFilePath="res:/Graphics/Effect/Managed/Space/PostProcess/ColorDownFilter4.fx",this.steps[0].effect.Initialize(),this.steps[0].effect.parameters.BlitCurrent=new Tw2TextureParameter("BlitCurrent"),this.steps[0].effect.parameters.g_texelSize=new Tw2Vector4Parameter("g_texelSize"),this.steps[1]=new Tw2Effect,this.steps[1]={effect:new Tw2Effect,rt:this.quadRT0,inputs:{BlitCurrent:this.quadRT1}},this.steps[1].effect.effectFilePath="res:/Graphics/Effect/Managed/Space/PostProcess/ColorHighPassFilter.fx",this.steps[1].effect.Initialize(),this.steps[1].effect.parameters.BlitCurrent=new Tw2TextureParameter("BlitCurrent"),this.steps[1].effect.parameters.LuminanceThreshold=new Tw2FloatParameter("LuminanceThreshold",.5),this.steps[1].effect.parameters.LuminanceScale=new Tw2FloatParameter("LuminanceScale",5),this.steps[2]=new Tw2Effect,this.steps[2]={effect:new Tw2Effect,rt:this.quadRT1,inputs:{BlitCurrent:this.quadRT0}},this.steps[2].effect.effectFilePath="res:/Graphics/Effect/Managed/Space/PostProcess/ColorExpBlurHorizontalBig.fx",this.steps[2].effect.Initialize(),this.steps[2].effect.parameters.BlitCurrent=new Tw2TextureParameter("BlitCurrent"),this.steps[2].effect.parameters.g_texelSize=new Tw2Vector4Parameter("g_texelSize"),this.steps[3]=new Tw2Effect,this.steps[3]={effect:new Tw2Effect,rt:this.quadRT0,inputs:{BlitCurrent:this.quadRT1}},this.steps[3].effect.effectFilePath="res:/Graphics/Effect/Managed/Space/PostProcess/ColorExpBlurVerticalBig.fx",this.steps[3].effect.Initialize(),this.steps[3].effect.parameters.BlitCurrent=new Tw2TextureParameter("BlitCurrent"),this.steps[3].effect.parameters.g_texelSize=new Tw2Vector4Parameter("g_texelSize"),this.steps[4]=new Tw2Effect,this.steps[4]={effect:new Tw2Effect,rt:null,inputs:{BlitCurrent:this.quadRT0,BlitOriginal:null}},this.steps[4].effect.effectFilePath="res:/Graphics/Effect/Managed/Space/PostProcess/ColorUpFilter4_Add.fx",this.steps[4].effect.Initialize(),this.steps[4].effect.parameters.BlitCurrent=new Tw2TextureParameter("BlitCurrent"),this.steps[4].effect.parameters.BlitOriginal=new Tw2TextureParameter("BlitOriginal"),this.steps[4].effect.parameters.g_texelSize=new Tw2Vector4Parameter("g_texelSize"),this.steps[4].effect.parameters.ScalingFactor=new Tw2FloatParameter("ScalingFactor",1)}function Tw2ParticleElementDeclaration(){this.elementType=4,this.customName="",this.dimension=1,this.usageIndex=0,this.usedByGPU=!0}function Tr2ParticleElement(decl){this.elementType=decl.elementType,this.customName=decl.customName,this.dimension=decl.GetDimension(),this.usageIndex=decl.usageIndex,this.usedByGPU=decl.usedByGPU,this.buffer=null,this.startOffset=0,this.offset=0,this.instanceStride=0,this.vertexStride=0,this.dirty=!1}function Tw2ParticleSystem(){this.name="",this.aliveCount=0,this.maxParticleCount=0,this.emitParticleOnDeathEmitter=null,this.emitParticleDuringLifeEmitter=null,this.elements=[],this.isValid=!1,this.requiresSorting=!1,this.updateSimulation=!0,this.applyForce=!0,this.applyAging=!0,this.isGlobal=!1,this.forces=[],this.constraints=[],this.updateBoundingBox=!1,this.aabbMin=vec3.create(),this.aabbMax=vec3.create(),this.peakAliveCount=0,this.bufferDirty=!1,this._vb=null,this._declaration=null}function Tw2StaticEmitter(){this.name="",this.particleSystem=null,this.geometryResourcePath="",this.geometryResource=null,this.geometryIndex=0,this._spawned=!1}function Tw2DynamicEmitter(){this.name="",this.rate=0,this.isValid=!1,this.particleSystem=null,this._accumulatedRate=0,this.generators=[]}function Tw2RandomUniformAttributeGenerator(){this.elementType=Tw2ParticleElementDeclaration.CUSTOM,this.customName="",this.minRange=quat4.create(),this.maxRange=quat4.create(),this._element=null}function Tw2SphereShapeAttributeGenerator(){this.minRadius=0,this.maxRadius=0,this.minPhi=0,this.maxPhi=360,this.minTheta=0,this.maxTheta=360,this.controlPosition=!0,this.controlVelocity=!0,this.minSpeed=0,this.maxSpeed=0,this.parentVelocityFactor=1,this.position=vec3.create(),this.rotation=quat4.create([0,0,0,1]),this._position=null,this._velocity=null}function Tw2ParticleSpring(){this.springConstant=0,this.position=vec3.create()}function Tw2ParticleDragForce(){this.drag=.1}function Tw2ParticleTurbulenceForce(){this.noiseLevel=3,this.noiseRatio=.5,this.amplitude=vec3.create([1,1,1]),this.frequency=quat4.create([1,1,1,1]),this._time=0}function InitializeNoise(){for(var i=0;256>i;i++)s_noiseLookup[i]=quat4.create([Math.random()-.5,Math.random()-.5,Math.random()-.5,Math.random()-.5]),s_permutations[i]=i;for(var i=256;--i;){var tmp=s_permutations[i],index=Math.floor(256*Math.random());s_permutations[i]=s_permutations[index],s_permutations[index]=tmp}for(var i=0;256>i;i++)s_permutations[256+i]=s_permutations[i],s_noiseLookup[256+i]=s_noiseLookup[i],s_noiseLookup[512+i]=s_noiseLookup[i];for(var i=0;15>i;++i)s_globalNoiseTemps[i]=vec3.create()}function AddNoise(pos_0,pos_1,pos_2,pos_3,power,result){pos_0+=4096,pos_1+=4096,pos_2+=4096,pos_3+=4096;var a_0=Math.floor(pos_0),a_1=Math.floor(pos_1),a_2=Math.floor(pos_2),a_3=Math.floor(pos_3),t_0=pos_0-a_0,t_1=pos_1-a_1,t_2=pos_2-a_2,t_3=pos_3-a_3;a_0&=255,a_1&=255,a_2&=255,a_3&=255;var b_0=a_0+1,b_1=a_1+1,b_2=a_2+1,b_3=a_3+1,i=s_permutations[a_0],j=s_permutations[b_0],b00=s_permutations[i+a_1],b10=s_permutations[j+a_1],b01=s_permutations[i+b_1],b11=s_permutations[j+b_1],c00=vec3.lerp(s_noiseLookup[b00+a_2+a_3],s_noiseLookup[b10+a_2+a_3],t_0,s_globalNoiseTemps[0]),c10=vec3.lerp(s_noiseLookup[b01+a_2+a_3],s_noiseLookup[b11+a_2+a_3],t_0,s_globalNoiseTemps[1]),c01=vec3.lerp(s_noiseLookup[b00+b_2+a_3],s_noiseLookup[b10+b_2+a_3],t_0,s_globalNoiseTemps[2]),c11=vec3.lerp(s_noiseLookup[b00+b_2+a_3],s_noiseLookup[b10+b_2+a_3],t_0,s_globalNoiseTemps[3]),c0=vec3.lerp(c00,c10,t_1,s_globalNoiseTemps[4]),c1=vec3.lerp(c01,c11,t_1,s_globalNoiseTemps[5]),c=vec3.lerp(c0,c1,t_2,s_globalNoiseTemps[6]),c00=vec3.lerp(s_noiseLookup[b00+a_2+b_3],s_noiseLookup[b10+a_2+b_3],t_0,s_globalNoiseTemps[7]),c10=vec3.lerp(s_noiseLookup[b01+a_2+b_3],s_noiseLookup[b11+a_2+b_3],t_0,s_globalNoiseTemps[8]),c01=vec3.lerp(s_noiseLookup[b00+b_2+b_3],s_noiseLookup[b10+b_2+b_3],t_0,s_globalNoiseTemps[9]),c11=vec3.lerp(s_noiseLookup[b00+b_2+b_3],s_noiseLookup[b10+b_2+b_3],t_0,s_globalNoiseTemps[10]),c0=vec3.lerp(c00,c10,t_1,s_globalNoiseTemps[11]),c1=vec3.lerp(c01,c11,t_1,s_globalNoiseTemps[12]),d=vec3.lerp(c0,c1,t_2,s_globalNoiseTemps[13]),r=vec3.lerp(c,d,t_3,s_globalNoiseTemps[14]);result[0]+=r[0]*power,result[1]+=r[1]*power,result[2]+=r[2]*power}function Tw2ParticleDirectForce(){this.force=vec3.create()}global.ccpwgl_int=exports,Tw2RawData.prototype.Declare=function(name,size){this.elements[name]={offset:this.nextOffset,size:size,array:null},this.nextOffset+=size},Tw2RawData.prototype.Create=function(){this.data=new Float32Array(this.nextOffset);for(var el in this.elements)this.elements[el].array=this.data.subarray(this.elements[el].offset,this.elements[el].offset+this.elements[el].size)},Tw2RawData.prototype.Set=function(name,value){var el=this.elements[name];this.data.set(value.length>el.size?value.subarray(0,el.size):value,el.offset)},Tw2RawData.prototype.Get=function(name){return this.elements[name].array},Tw2BinaryReader.prototype.ReadUInt8=function(){return this.data[this.cursor++]},Tw2BinaryReader.prototype.ReadInt8=function(){var val=this.data[this.cursor++];return val>127&&(val=val-255-1),val},Tw2BinaryReader.prototype.ReadUInt16=function(){return this.data[this.cursor++]+(this.data[this.cursor++]<<8)},Tw2BinaryReader.prototype.ReadInt16=function(){var val=this.data[this.cursor++]+(this.data[this.cursor++]<<8);return val>32767&&(val=val-65535-1),val},Tw2BinaryReader.prototype.ReadUInt32=function(){return this.data[this.cursor++]+(this.data[this.cursor++]<<8)+(this.data[this.cursor++]<<16)+(this.data[this.cursor++]<<24>>>0)},Tw2BinaryReader.prototype.ReadInt32=function(){var val=this.data[this.cursor++]+(this.data[this.cursor++]<<8)+(this.data[this.cursor++]<<16)+(this.data[this.cursor++]<<24>>>0);return val>2147483647&&(val=val-4294967295-1),val},Tw2BinaryReader.prototype.ReadFloat16=function(){var b2=this.data[this.cursor++],b1=this.data[this.cursor++],sign=1-2*(b1>>7),exp=(31&b1>>2)-15,sig=(3&b1)<<8|b2;return 0==sig&&-15==exp?0:sign*(1+sig*Math.pow(2,-10))*Math.pow(2,exp)},Tw2BinaryReader.prototype.ReadFloat32=function(){var b4=this.data[this.cursor++],b3=this.data[this.cursor++],b2=this.data[this.cursor++],b1=this.data[this.cursor++],sign=1-2*(b1>>7),exp=(255&b1<<1|b2>>7)-127,sig=(127&b2)<<16|b3<<8|b4;return 0==sig&&-127==exp?0:sign*(1+sig*Math.pow(2,-23))*Math.pow(2,exp)},Tw2BinaryReader.prototype.ReadString=function(){for(var length=this.data[this.cursor++],str="",i=0;length>i;++i)str+=String.fromCharCode(this.data[this.cursor++]);return str},Tw2VertexDeclaration.DECL_POSITION=0,Tw2VertexDeclaration.DECL_COLOR=1,Tw2VertexDeclaration.DECL_NORMAL=2,Tw2VertexDeclaration.DECL_TANGENT=3,Tw2VertexDeclaration.DECL_BINORMAL=4,Tw2VertexDeclaration.DECL_TEXCOORD=5,Tw2VertexDeclaration.DECL_BLENDWEIGHT=6,Tw2VertexDeclaration.DECL_BLENDINDICES=7,Tw2VertexDeclaration.prototype.RebuildHash=function(){this._elementsSorted=[];for(var i=0;this.elements.length>i;++i)this._elementsSorted[i]=this.elements[i];this._elementsSorted.sort(CompareDeclarationElements)},Tw2VertexDeclaration.prototype.FindUsage=function(usage,usageIndex){for(var i=0;this._elementsSorted.length>i;++i){var e=this._elementsSorted[i];if(e.usage==usage){if(e.usageIndex==usageIndex)return e;if(e.usageIndex>usageIndex)return null}if(e.usage>usage)return null}return null},Tw2VertexDeclaration.prototype.SetDeclaration=function(inputDecl,stride){for(var index=0,i=0;inputDecl._elementsSorted.length>i;++i){var el=inputDecl._elementsSorted[i];if(!(0>el.location))for(;;){var input=this._elementsSorted[index];if(0==CompareDeclarationElements(input,el)){input.customSetter?input.customSetter(el):(device.gl.enableVertexAttribArray(el.location),device.gl.vertexAttribPointer(el.location,input.elements,input.type,!1,stride,input.offset));break}if(index++,index>=this._elementsSorted.length)return!1}}return!0},Tw2VertexDeclaration.prototype.SetPartialDeclaration=function(inputDecl,stride){for(var index=0,i=0;inputDecl._elementsSorted.length>i;++i){var el=inputDecl._elementsSorted[i];if(!(0>el.location))for(;;){var input=this._elementsSorted[index],cmp=CompareDeclarationElements(input,el);if(0==cmp){input.customSetter?input.customSetter(el):(device.gl.enableVertexAttribArray(el.location),device.gl.vertexAttribPointer(el.location,input.elements,input.type,!1,stride,input.offset));break}if(cmp>0)break;if(index++,index>=this._elementsSorted.length)return!1}}return!0},Tw2ObjectReader.prototype.Construct=function(initialize){this._inputStack=[],this._inputStack.push([this.xmlNode.documentElement,this,"result"]),this._initializeObjects=[],this._ids=[];var self=this;return function(){return self.ConstructFromNode(initialize,!0)}},Tw2ObjectReader.prototype.ConstructAsync=function(initialize){for(this._inputStack=[],this._inputStack.push([this.xmlNode.documentElement,this,"result"]);!this.ConstructFromNode(initialize,!1););return this.result},Tw2ObjectReader.prototype.ConstructFromNode=function(initialize,async){for(var now=new Date,startTime=now.getTime();this._inputStack.length;){var endTime=now.getTime();if(async&&.001*(endTime-startTime)>resMan.prepareBudget)return!1;var inputData=this._inputStack.pop(),xmlNode=inputData[0],parent=inputData[1],index=inputData[2];if(null!=xmlNode){var ref=xmlNode.attributes.getNamedItem("ref");if(ref){var object=this._ids[ref.value];parent[index]=object}else{var type=xmlNode.attributes.getNamedItem("type");if(type){var object=null;if("dict"==type.value)object={};else try{object=eval("new "+type.value+"()")}catch(e){throw Error('YAML: object with undefined type "'+type.value+'"')}this._inputStack.push([null,object,null]);for(var i=0;xmlNode.childNodes.length>i;++i){var child=xmlNode.childNodes[xmlNode.childNodes.length-1-i];"#text"!=child.nodeName&&("dict"==type.value||void 0!==object[child.nodeName]?this._inputStack.push([child,object,child.nodeName]):console.warn("Tw2ObjectReader:",' object "',type.value,'" does not have property "',child.nodeName,'"'))}var id=xmlNode.attributes.getNamedItem("id");id&&(this._ids[id.value]=object),parent[index]=object}else{var list=xmlNode.attributes.getNamedItem("list");if(list){object=[];var arrayIndex=0;this._inputStack.push([null,object,null]);for(var i=0;xmlNode.childNodes.length>i;++i){var child=xmlNode.childNodes[xmlNode.childNodes.length-1-i];"#text"!=child.nodeName&&arrayIndex++}for(var i=0;xmlNode.childNodes.length>i;++i){var child=xmlNode.childNodes[xmlNode.childNodes.length-1-i];"#text"!=child.nodeName&&this._inputStack.push([child,object,--arrayIndex])}var id=xmlNode.attributes.getNamedItem("id");id&&(this._ids[id.value]=object),parent[index]=object}else{for(var value="",i=0;xmlNode.childNodes.length>i;++i){var child=xmlNode.childNodes[i];"#text"==child.nodeName&&(value+=child.data)}var json=xmlNode.attributes.getNamedItem("json");if(json){try{parent[index]=new Float32Array(eval(value))}catch(e){throw Error('YAML: property "'+value+'" is not a valid JSON property')}var id=xmlNode.attributes.getNamedItem("id");id&&(this._ids[id.value]=parent[index])}else{var capture=/^(\-?\d+\.\d+(?:e|E\-?\d+)?)/.exec(value);capture?parent[index]=parseFloat(capture[1]):(capture=/^(\-?\d+)/.exec(value),capture?parent[index]=parseInt(capture[1],10):(capture=/^\b(enabled|true|yes|on)\b/.exec(value),capture?parent[index]=!0:(capture=/^\b(disabled|false|no|off)\b/.exec(value),parent[index]=capture?!1:value)))}}}}}else initialize&&parent.Initialize!==void 0&&this._initializeObjects.push(parent)}for(;this._initializeObjects.length;){var endTime=now.getTime();if(async&&.001*(endTime-startTime)>resMan.prepareBudget)return!1;var object=this._initializeObjects.shift();object.Initialize()}return!0},Tw2Resource.prototype.IsLoading=function(){return this.KeepAlive(),this._isLoading},Tw2Resource.prototype.IsGood=function(){return this.KeepAlive(),this._isGood},Tw2Resource.prototype.IsPurged=function(){return this._isPurged},Tw2Resource.prototype.LoadStarted=function(){this._isLoading=!0;for(var i=0;this._notifications.length>i;++i)this._notifications[i].ReleaseCachedData(this)},Tw2Resource.prototype.LoadFinished=function(success){this._isLoading=!1,success||(this._isGood=!1)},Tw2Resource.prototype.PrepareFinished=function(success){this._isLoading=!1,this._isGood=success;for(var i=0;this._notifications.length>i;++i)this._notifications[i].RebuildCachedData(this)},Tw2Resource.prototype.SetIsGood=function(success){this._isGood=success},Tw2Resource.prototype.Unload=function(){},Tw2Resource.prototype.Reload=function(){this.Unload(),resMan.ReloadResource(this)},Tw2Resource.prototype.KeepAlive=function(){this.activeFrame=resMan.activeFrame,this._isPurged&&this.Reload()},Tw2Resource.prototype.RegisterNotification=function(notification){for(var i=0;this._notifications.length>i;++i)if(this._notifications[i]==notification)return;this._notifications[this._notifications.length]=notification,this._isGood&&notification.RebuildCachedData(this)},Tw2Resource.prototype.UnregisterNotification=function(notification){for(var i=0;this._notifications.length>i;++i)if(this._notifications[i]==notification)return this._notifications.splice(i,1),void 0},Tw2VariableStore.prototype.RegisterVariableWithType=function(name,value,type){return this._variables[name]=new type(name,value)},Tw2VariableStore.prototype.RegisterType=function(name,type){return this._variables[name]=new type(name)},Tw2VariableStore.prototype.RegisterVariable=function(name,value){if(value.constructor==(new glMatrixArrayType).constructor){if(16==value.length)return this.RegisterVariableWithType(name,value,Tw2MatrixParameter);if(4==value.length)return this.RegisterVariableWithType(name,value,Tw2Vector4Parameter);if(3==value.length)return this.RegisterVariableWithType(name,value,Tw2Vector3Parameter);if(2==value.length)return this.RegisterVariableWithType(name,value,Tw2Vector2Parameter)}else{if("number"==typeof value)return this.RegisterVariableWithType(name,value,Tw2FloatParameter);if("string"==typeof value)return this.RegisterVariableWithType(name,value,Tw2TextureParameter)}};var variableStore=new Tw2VariableStore;Tw2LoadingObject.prototype.AddObject=function(object,callback,initialize){return object._loadCallback=callback,object._initialize=initialize,this._objects.push(object),!1},Tw2LoadingObject.prototype.Prepare=function(text,xml){if(null==xml)return console.error("Invalid XML for object "+this.path),this.PrepareFinished(!1),void 0;for(null===this._inPrepare&&(this._redContents=xml,this._constructor=new Tw2ObjectReader(this._redContents),this._constructorFunction=null,this._inPrepare=0);this._inPrepare<this._objects.length;){if(!this._constructorFunction){var initialize=this._objects[this._inPrepare]._initialize;
  this._constructorFunction=this._constructor.Construct(initialize)}if(!this._constructorFunction())return!0;this._constructorFunction=null,this._objects[this._inPrepare]._loadCallback(this._constructor.result),this._inPrepare++}resMan.motherLode.Remove(this.path),console.info("Prepared "+this.path),this.PrepareFinished(!0)},Inherit(Tw2LoadingObject,Tw2Resource);var resMan=new Tw2ResMan;Tw2PerObjectData.prototype.SetPerObjectDataToDevice=function(constantBufferHandles){this.perObjectVSData&&constantBufferHandles[3]&&device.gl.uniform4fv(constantBufferHandles[3],this.perObjectVSData.data),this.perObjectPSData&&constantBufferHandles[4]&&device.gl.uniform4fv(constantBufferHandles[4],this.perObjectPSData.data)},Tw2SamplerState.prototype.ComputeHash=function(){this.hash=2166136261,this.hash*=16777619,this.hash^=this.minFilter,this.hash*=16777619,this.hash^=this.maxFilter,this.hash*=16777619,this.hash^=this.addressU,this.hash*=16777619,this.hash^=this.addressV,this.hash*=16777619,this.hash^=this.anisotropy},Tw2SamplerState.prototype.Apply=function(hasMipMaps){var targetType=this.samplerType,d=device,gl=d.gl;gl.texParameteri(targetType,gl.TEXTURE_WRAP_S,this.addressU),gl.texParameteri(targetType,gl.TEXTURE_WRAP_T,this.addressV),gl.texParameteri(targetType,gl.TEXTURE_MIN_FILTER,hasMipMaps?this.minFilter:this.minFilterNoMips),gl.texParameteri(targetType,gl.TEXTURE_MAG_FILTER,this.magFilter),d.anisotropicFilter&&d.enableAnisotropicFiltering&&gl.texParameterf(targetType,d.anisotropicFilter.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(this.anisotropy,d.anisotropicFilter.maxAnisotropy))},Tw2FloatParameter.prototype.Bind=function(constantBuffer,offset,size){return null!=this.constantBuffer||1>size?!1:(this.constantBuffer=constantBuffer,this.offset=offset,this.Apply(this.constantBuffer,this.offset,size),void 0)},Tw2FloatParameter.prototype.Unbind=function(){this.constantBuffer=null},Tw2FloatParameter.prototype.OnValueChanged=function(){null!=this.constantBuffer&&(constantBuffer[this.offset]=this.value)},Tw2FloatParameter.prototype.Apply=function(constantBuffer,offset){constantBuffer[offset]=this.value},Tw2FloatParameter.prototype.Bind=function(constantBuffer,offset,size){return null!=this.constantBuffer||1>size?!1:(this.constantBuffer=constantBuffer,this.offset=offset,this.Apply(this.constantBuffer,this.offset,size),void 0)},Tw2FloatParameter.prototype.Unbind=function(){this.constantBuffer=null},Tw2FloatParameter.prototype.OnValueChanged=function(){null!=this.constantBuffer&&(constantBuffer[this.offset]=this.value)},Tw2FloatParameter.prototype.Apply=function(constantBuffer,offset){constantBuffer[offset]=this.value},Tw2Vector2Parameter.prototype.Bind=function(constantBuffer,offset,size){return null!=this.constantBuffer||2>size?!1:(this.constantBuffer=constantBuffer,this.offset=offset,this.Apply(this.constantBuffer,this.offset,size),!0)},Tw2Vector2Parameter.prototype.Unbind=function(){this.constantBuffer=null},Tw2Vector2Parameter.prototype.SetValue=function(value){this.value=value,null!=this.constantBuffer&&this.constantBuffer.set(this.value,this.offset)},Tw2Vector2Parameter.prototype.OnValueChanged=function(){null!=this.constantBuffer&&this.constantBuffer.set(this.value,this.offset)},Tw2Vector2Parameter.prototype.Apply=function(constantBuffer,offset){constantBuffer.set(this.value,offset)},Tw2Vector3Parameter.prototype.Bind=function(constantBuffer,offset,size){return null!=this.constantBuffer||3>size?!1:(this.constantBuffer=constantBuffer,this.offset=offset,this.Apply(this.constantBuffer,this.offset,size),!0)},Tw2Vector3Parameter.prototype.Unbind=function(){this.constantBuffer=null},Tw2Vector3Parameter.prototype.SetValue=function(value){this.value=value,null!=this.constantBuffer&&this.constantBuffer.set(this.value,this.offset)},Tw2Vector3Parameter.prototype.OnValueChanged=function(){null!=this.constantBuffer&&this.constantBuffer.set(this.value,this.offset)},Tw2Vector3Parameter.prototype.Apply=function(constantBuffer,offset){constantBuffer.set(this.value,offset)},Tw2Vector4Parameter.prototype.Bind=function(constantBuffer,offset,size){return null!=this.constantBuffer||4>size?!1:(this.constantBuffer=constantBuffer,this.offset=offset,this.Apply(this.constantBuffer,this.offset,size),!0)},Tw2Vector4Parameter.prototype.Unbind=function(){this.constantBuffer=null},Tw2Vector4Parameter.prototype.SetValue=function(value){this.value=value,null!=this.constantBuffer&&this.constantBuffer.set(this.value,this.offset)},Tw2Vector4Parameter.prototype.OnValueChanged=function(){null!=this.constantBuffer&&this.constantBuffer.set(this.value,this.offset)},Tw2Vector4Parameter.prototype.Apply=function(constantBuffer,offset){constantBuffer.set(this.value,offset)},Tw2MatrixParameter.prototype.Bind=function(constantBuffer,offset,size){return null!=this.constantBuffer||16>size?!1:(this.constantBuffer=constantBuffer,this.offset=offset,this.Apply(this.constantBuffer,this.offset,size),void 0)},Tw2MatrixParameter.prototype.SetValue=function(value){this.value=value,null!=this.constantBuffer&&this.constantBuffer.set(this.value,this.offset)},Tw2MatrixParameter.prototype.Apply=function(constantBuffer,offset){constantBuffer.set(this.value,offset)},Tw2VariableParameter.prototype.Bind=function(){return!1},Tw2VariableParameter.prototype.Apply=function(constantBuffer,offset,size){variableStore._variables[this.variableName]!==void 0&&variableStore._variables[this.variableName].Apply(constantBuffer,offset,size)},Tw2TextureParameter.prototype.SetTexturePath=function(texturePath){this.resourcePath=texturePath,""!=this.resourcePath&&(this.textureRes=resMan.GetResource(this.resourcePath))},Tw2TextureParameter.prototype.Initialize=function(){""!=this.resourcePath&&(this.textureRes=resMan.GetResource(this.resourcePath))},Tw2TextureParameter.prototype.Apply=function(stage,sampler,slices){this.textureRes&&(device.gl.activeTexture(device.gl.TEXTURE0+stage),this.textureRes.Bind(sampler,slices))},Tw2TransformParameter.prototype.Initialize=function(){this.OnModified()},Tw2TransformParameter.prototype.OnModified=function(){mat4.identity(this.worldTransform),mat4.scale(this.worldTransform,this.scaling);var rotationCenter=mat4.create();mat4.identity(rotationCenter),mat4.translate(rotationCenter,this.rotationCenter);var rotationCenterInv=mat4.create();mat4.identity(rotationCenterInv),mat4.translate(rotationCenterInv,[-this.rotationCenter[0],-this.rotationCenter[1],-this.rotationCenter[2]]);var rotation=mat4.create();rotation[0]=1-2*this.rotation[1]*this.rotation[1]-2*this.rotation[2]*this.rotation[2],rotation[4]=2*this.rotation[0]*this.rotation[1]-2*this.rotation[2]*this.rotation[3],rotation[8]=2*this.rotation[0]*this.rotation[2]+2*this.rotation[1]*this.rotation[3],rotation[1]=2*this.rotation[0]*this.rotation[1]+2*this.rotation[2]*this.rotation[3],rotation[5]=1-2*this.rotation[0]*this.rotation[0]-2*this.rotation[2]*this.rotation[2],rotation[9]=2*this.rotation[1]*this.rotation[2]-2*this.rotation[0]*this.rotation[3],rotation[2]=2*this.rotation[0]*this.rotation[2]-2*this.rotation[1]*this.rotation[3],rotation[6]=2*this.rotation[1]*this.rotation[2]+2*this.rotation[0]*this.rotation[3],rotation[10]=1-2*this.rotation[0]*this.rotation[0]-2*this.rotation[1]*this.rotation[1],rotation[15]=1,mat4.multiply(this.worldTransform,rotationCenterInv),mat4.multiply(this.worldTransform,rotation),mat4.multiply(this.worldTransform,rotationCenter),mat4.translate(this.worldTransform,this.translation),mat4.transpose(this.worldTransform)},Tw2TransformParameter.prototype.Bind=function(constantBuffer,offset,size){return null!=this.constantBuffer||16>size?!1:(this.constantBuffer=constantBuffer,this.offset=offset,this.Apply(this.constantBuffer,this.offset,size),void 0)},Tw2TransformParameter.prototype.Apply=function(constantBuffer,offset,size){size>=16?constantBuffer.set(this.worldTransform,offset):constantBuffer.set(this.worldTransform.subarray(0,size),offset)},window.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){window.setTimeout(callback,1e3/60)}}();var device=new Tw2Device;Tw2BatchAccumulator.prototype.Commit=function(batch){this.batches[this.count++]=batch},Tw2BatchAccumulator.prototype.Clear=function(){this.count=0},Tw2BatchAccumulator.prototype.Render=function(overrideEffect){this._sortMethod!==void 0&&this.batches.sort(this._sortMethod);for(var i=0;this.count>i;++i)this.batches[i].renderMode!=device.RM_ANY&&device.SetStandardStates(this.batches[i].renderMode),device.perObjectData=this.batches[i].perObjectData,this.batches[i].Commit(overrideEffect)},Tw2ForwardingRenderBatch.prototype.Commit=function(overrideEffect){this.geometryProvider&&this.geometryProvider.Render(this,overrideEffect)},Inherit(Tw2ForwardingRenderBatch,Tw2RenderBatch),Tw2GeometryBatch.prototype.Commit=function(overrideEffect){var effect=overrideEffect===void 0?this.effect:overrideEffect;this.geometryRes&&effect&&this.geometryRes.RenderAreas(this.meshIx,this.start,this.count,effect)},Inherit(Tw2GeometryBatch,Tw2RenderBatch),Tw2GeometryLineBatch.prototype.Commit=function(overrideEffect){var effect=overrideEffect===void 0?this.effect:overrideEffect;this.geometryRes&&effect&&this.geometryRes.RenderLines(this.meshIx,this.start,this.count,effect)},Inherit(Tw2GeometryLineBatch,Tw2RenderBatch),Tw2GeometryModel.prototype.FindBoneByName=function(name){if(null==this.skeleton)return null;for(var b=0;this.skeleton.bones.length>b;++b)if(this.skeleton.bones[b].name==name)return this.skeleton.bones[b];return null},Tw2GeometryBone.prototype.UpdateTransform=function(){return mat3.toMat4(this.scaleShear,this.localTransform),mat4.multiply(this.localTransform,mat4.transpose(quat4.toMat4(quat4.normalize(this.orientation)))),this.localTransform[12]=this.position[0],this.localTransform[13]=this.position[1],this.localTransform[14]=this.position[2],this.localTransform},Tw2GeometryRes.prototype.requestResponseType="arraybuffer",Tw2GeometryRes.prototype.SetInstanceCount=function(instanceCount){instanceCount>this._instanceCount&&(this._instanceCount=instanceCount,this.IsGood()&&this.Reload())},Tw2GeometryRes.prototype.Prepare=function(data){function ReadVertexBuffer(declaration){for(var declCount=reader.ReadUInt8(),vertexSize=0,declIx=0;declCount>declIx;++declIx){var element=new Tw2VertexElement;element.usage=reader.ReadUInt8(),element.usageIndex=reader.ReadUInt8(),element.fileType=reader.ReadUInt8(),element.type=device.gl.FLOAT,element.elements=(element.fileType>>5)+1,element.offset=4*vertexSize,declaration.elements[declIx]=element,vertexSize+=element.elements}if(declaration.RebuildHash(),declaration.stride=4*vertexSize,reader.ReadVertexBuffer)return reader.ReadVertexBuffer(declaration);var vertexCount=reader.ReadUInt32();if(0==vertexCount)return null;for(var buffer=new Float32Array(vertexSize*vertexCount),index=0,vtxIx=0;vertexCount>vtxIx;++vtxIx)for(var declIx=0;declCount>declIx;++declIx)switch(15&declaration.elements[declIx].fileType){case 0:if(16&declaration.elements[declIx].fileType)for(var i=0;declaration.elements[declIx].elements>i;++i)buffer[index++]=reader.ReadInt8()/127;else for(var i=0;declaration.elements[declIx].elements>i;++i)buffer[index++]=reader.ReadInt8();break;case 1:if(16&declaration.elements[declIx].fileType)for(var i=0;declaration.elements[declIx].elements>i;++i)buffer[index++]=reader.ReadInt8()/32767;else for(var i=0;declaration.elements[declIx].elements>i;++i)buffer[index++]=reader.ReadInt16();break;case 2:for(var i=0;declaration.elements[declIx].elements>i;++i)buffer[index++]=reader.ReadInt32();break;case 3:for(var i=0;declaration.elements[declIx].elements>i;++i)buffer[index++]=reader.ReadFloat16();break;case 4:for(var i=0;declaration.elements[declIx].elements>i;++i)buffer[index++]=reader.ReadFloat32();break;case 8:if(16&declaration.elements[declIx].fileType)for(var i=0;declaration.elements[declIx].elements>i;++i)buffer[index++]=reader.ReadUInt8()/255;else for(var i=0;declaration.elements[declIx].elements>i;++i)buffer[index++]=reader.ReadUInt8();break;case 9:if(16&declaration.elements[declIx].fileType)for(var i=0;declaration.elements[declIx].elements>i;++i)buffer[index++]=reader.ReadUInt8()/65535;else for(var i=0;declaration.elements[declIx].elements>i;++i)buffer[index++]=reader.ReadUInt16();break;case 10:for(var i=0;declaration.elements[declIx].elements>i;++i)buffer[index++]=reader.ReadUInt32();break;default:throw console.error("Tw2GeometryRes:"," error loading wbg data (file ",self.path,")"),1}return buffer}function ReadIndexBuffer(){if(reader.ReadIndexBuffer)return reader.ReadIndexBuffer();var ibType=reader.ReadUInt8(),indexCount=reader.ReadUInt32();if(0==ibType){for(var indexes=new Uint16Array(indexCount),i=0;indexCount>i;++i)indexes[i]=reader.ReadUInt16();return indexes}for(var indexes=new Uint32Array(indexCount),i=0;indexCount>i;++i)indexes[i]=reader.ReadUInt32();return indexes}function ReadCurve(){var type=reader.ReadUInt8();if(0==type)return null;var dimension=reader.ReadUInt8(),curve=new Tw2GeometryCurve;curve.dimension=dimension,curve.degree=reader.ReadUInt8();var knotCount=reader.ReadUInt32();curve.knots=new Float32Array(knotCount);for(var i=0;knotCount>i;++i)curve.knots[i]=reader.ReadFloat32();var controlCount=reader.ReadUInt32();curve.controls=new Float32Array(controlCount);for(var i=0;controlCount>i;++i)curve.controls[i]=reader.ReadFloat32();return curve}var reader=new Tw2BinaryReader(new Uint8Array(data)),self=this;reader.ReadUInt8();for(var meshCount=reader.ReadUInt8(),meshIx=0;meshCount>meshIx;++meshIx){var mesh=new Tw2GeometryMesh;mesh.name=reader.ReadString();var buffer=ReadVertexBuffer(mesh.declaration);if(buffer){if(mesh.buffer=device.gl.createBuffer(),device.gl.bindBuffer(device.gl.ARRAY_BUFFER,mesh.buffer),this._instanceCount>1){for(var tmp=new Float32Array(buffer.length*this._instanceCount),i=0;this._instanceCount>i;++i)tmp.set(buffer,buffer.length*i);buffer=tmp}device.gl.bufferData(device.gl.ARRAY_BUFFER,buffer,device.gl.STATIC_DRAW)}else mesh.buffer=null;var indexes=ReadIndexBuffer();if(indexes){if(mesh.indexes=device.gl.createBuffer(),mesh.indexType=2==indexes.BYTES_PER_ELEMENT?device.gl.UNSIGNED_SHORT:device.gl.UNSIGNED_INT,device.gl.bindBuffer(device.gl.ELEMENT_ARRAY_BUFFER,mesh.indexes),this._instanceCount>1){for(var tmp=2==indexes.BYTES_PER_ELEMENT?new Uint16Array(indexes.length*this._instanceCount):new Uint32Array(indexes.length*this._instanceCount),offset=0,i=0;this._instanceCount>i;++i){for(var j=0;indexes.length>j;++j)tmp[j+offset]=indexes[j]+offset;offset+=buffer.length}indexes=tmp}device.gl.bufferData(device.gl.ELEMENT_ARRAY_BUFFER,indexes,device.gl.STATIC_DRAW)}else mesh.indexes=null;for(var areaCount=reader.ReadUInt8(),i=0;areaCount>i;++i)mesh.areas[i]=new Tw2GeometryMeshArea,mesh.areas[i].name=reader.ReadString(),mesh.areas[i].start=reader.ReadUInt32()*indexes.BYTES_PER_ELEMENT,mesh.areas[i].count=3*reader.ReadUInt32(),mesh.areas[i].minBounds=vec3.create([reader.ReadFloat32(),reader.ReadFloat32(),reader.ReadFloat32()]),mesh.areas[i].maxBounds=vec3.create([reader.ReadFloat32(),reader.ReadFloat32(),reader.ReadFloat32()]);var boneBindingCount=reader.ReadUInt8();mesh.boneBindings=[];for(var i=0;boneBindingCount>i;++i)mesh.boneBindings[i]=reader.ReadString();var annotationSetCount=reader.ReadUInt16();if((annotationSetCount||this.systemMirror)&&(mesh.bufferData=buffer),annotationSetCount){mesh.blendShapes=[];for(var i=0;annotationSetCount>i;++i)mesh.blendShapes[i]=new Tw2BlendShapeData,mesh.blendShapes[i].name=reader.ReadString(),mesh.blendShapes[i].buffer=ReadVertexBuffer(mesh.blendShapes[i].declaration),mesh.blendShapes[i].indexes=ReadIndexBuffer()}this.meshes[meshIx]=mesh}for(var modelCount=reader.ReadUInt8(),modelIx=0;modelCount>modelIx;++modelIx){var model=new Tw2GeometryModel;model.name=reader.ReadString(),model.skeleton=new Tw2GeometrySkeleton;for(var boneCount=reader.ReadUInt8(),j=0;boneCount>j;++j){var bone=new Tw2GeometryBone;bone.name=reader.ReadString();var flags=reader.ReadUInt8();if(bone.parentIndex=reader.ReadUInt8(),255==bone.parentIndex&&(bone.parentIndex=-1),1&flags?vec3.set([reader.ReadFloat32(),reader.ReadFloat32(),reader.ReadFloat32()],bone.position):vec3.set([0,0,0],bone.position),2&flags?quat4.set([reader.ReadFloat32(),reader.ReadFloat32(),reader.ReadFloat32(),reader.ReadFloat32()],bone.orientation):quat4.set([0,0,0,1],bone.orientation),4&flags)for(var k=0;9>k;++k)bone.scaleShear[k]=reader.ReadFloat32();else mat3.identity(bone.scaleShear);model.skeleton.bones[j]=bone}for(var j=0;model.skeleton.bones.length>j;++j)model.skeleton.bones[j].UpdateTransform(),-1!=model.skeleton.bones[j].parentIndex?mat4.multiply(model.skeleton.bones[model.skeleton.bones[j].parentIndex].worldTransform,model.skeleton.bones[j].localTransform,model.skeleton.bones[j].worldTransform):mat4.set(model.skeleton.bones[j].localTransform,model.skeleton.bones[j].worldTransform),mat4.inverse(model.skeleton.bones[j].worldTransform,model.skeleton.bones[j].worldTransformInv);for(var meshBindingCount=reader.ReadUInt8(),j=0;meshBindingCount>j;++j){var binding=new Tw2GeometryMeshBinding;binding.mesh=this.meshes[reader.ReadUInt8()];for(var b=0;binding.mesh.boneBindings.length>b;++b){var name=binding.mesh.boneBindings[b],bone=model.FindBoneByName(name);null==bone?console.error("Tw2GeometryRes:","mesh '",binding.mesh.name,"' in file '",this.path,"' has invalid bone name '",name,"' for model '",model.name,"'"):binding.bones[binding.bones.length]=bone}model.meshBindings[model.meshBindings.length]=binding}this.models[this.models.length]=model}for(var animationCount=reader.ReadUInt8(),i=0;animationCount>i;++i){var animation=new Tw2GeometryAnimation;animation.name=reader.ReadString(),animation.duration=reader.ReadFloat32();for(var groupCount=reader.ReadUInt8(),j=0;groupCount>j;++j){var group=new Tw2GeometryTrackGroup;group.name=reader.ReadString();for(var m=0;this.models.length>m;++m)if(this.models[m].name==name){group.model=this.models[m];break}for(var transformTrackCount=reader.ReadUInt8(),k=0;transformTrackCount>k;++k){var track=new Tw2GeometryTransformTrack;if(track.name=reader.ReadString(),track.orientation=ReadCurve(),track.position=ReadCurve(),track.scaleShear=ReadCurve(),track.orientation)for(var lastX=0,lastY=0,lastZ=0,lastW=0,n=0;track.orientation.controls.length>n;n+=4){var x=track.orientation.controls[n],y=track.orientation.controls[n+1],z=track.orientation.controls[n+2],w=track.orientation.controls[n+3];0>lastX*x+lastY*y+lastZ*z+lastW*w&&(track.orientation.controls[n]=-x,track.orientation.controls[n+1]=-y,track.orientation.controls[n+2]=-z,track.orientation.controls[n+3]=-w),lastX=x,lastY=y,lastZ=z,lastW=w}group.transformTracks[group.transformTracks.length]=track}animation.trackGroups[animation.trackGroups.length]=group}this.animations[this.animations.length]=animation}this.PrepareFinished(!0)},Tw2GeometryRes.prototype.RenderAreas=function(meshIx,start,count,effect,cb){if(this.KeepAlive(),!this._isGood)return!1;var effectRes=effect.GetEffectRes();if(!effectRes._isGood)return!1;if(meshIx>=this.meshes.length)return!1;var d=device,mesh=this.meshes[meshIx];d.gl.bindBuffer(d.gl.ARRAY_BUFFER,mesh.buffer),d.gl.bindBuffer(d.gl.ELEMENT_ARRAY_BUFFER,mesh.indexes);for(var passCount=effect.GetPassCount(),pass=0;passCount>pass;++pass){effect.ApplyPass(pass);var passInput=effect.GetPassInput(pass);if(!mesh.declaration.SetDeclaration(passInput,mesh.declaration.stride))return console.error("Tw2GeometryRes:"," error binding mesh to effect"),!1;if(d.ApplyShadowState(),cb!==void 0){for(var drawElements=[],i=0;count>i;++i)if(mesh.areas.length>i+start){var area=mesh.areas[i+start];drawElements.push([d.gl.TRIANGLES,area.count,mesh.indexType,area.start])}cb(pass,drawElements)}else for(var i=0;count>i;++i)if(mesh.areas.length>i+start){for(var area=mesh.areas[i+start],start=area.start,acount=area.count;count>i+1;){var area=mesh.areas[i+1+start];if(area.start!=start+2*acount)break;acount+=area.count,++i}d.gl.drawElements(d.gl.TRIANGLES,acount,mesh.indexType,start)}}return!0},Tw2GeometryRes.prototype.RenderLines=function(meshIx,start,count,effect,cb){if(this.KeepAlive(),!this._isGood)return!1;var effectRes=effect.GetEffectRes();if(!effectRes._isGood)return!1;if(meshIx>=this.meshes.length)return!1;var d=device,mesh=this.meshes[meshIx];d.gl.bindBuffer(d.gl.ARRAY_BUFFER,mesh.buffer),d.gl.bindBuffer(d.gl.ELEMENT_ARRAY_BUFFER,mesh.indexes);for(var passCount=effect.GetPassCount(),pass=0;passCount>pass;++pass){effect.ApplyPass(pass);var passInput=effect.GetPassInput(pass);if(!mesh.declaration.SetDeclaration(passInput,mesh.declaration.stride))return console.error("Tw2GeometryRes:"," error binding mesh to effect"),!1;if(d.ApplyShadowState(),cb!==void 0){for(var drawElements=[],i=0;count>i;++i)if(mesh.areas.length>i+start){var area=mesh.areas[i+start];drawElements.push([d.gl.LINES,area.count,mesh.indexType,area.start])}cb(pass,drawElements)}else for(var i=0;count>i;++i)if(mesh.areas.length>i+start){for(var area=mesh.areas[i+start],start=area.start,acount=area.count;count>i+1;){var area=mesh.areas[i+1+start];if(area.start!=start+2*acount)break;acount+=area.count,++i}d.gl.drawElements(d.gl.LINES,acount,mesh.indexType,start)}}return!0},Tw2GeometryRes.prototype.RenderDebugInfo=function(debugHelper){if(!this.IsGood())return!1;for(var i=0;this.models.length>i;++i)if(this.models[i].skeleton)for(var j=0;this.models[i].skeleton.bones.length>j;++j){var b0=this.models[i].skeleton.bones[j];if(b0.parentIndex>=0){var b1=this.models[i].skeleton.bones[b0.parentIndex];debugHelper.AddLine([b0.worldTransform[12],b0.worldTransform[13],b0.worldTransform[14]],[b1.worldTransform[12],b1.worldTransform[13],b1.worldTransform[14]],[0,.7,0,1],[0,.7,0,1])}}},Tw2GeometryRes.prototype.Unload=function(){for(var i=0;this.meshes.length>i;++i)this.meshes[i].buffer&&(device.gl.deleteBuffer(this.meshes[i].buffer),this.meshes[i].buffer=null),this.meshes[i].indexes&&(device.gl.deleteBuffer(this.meshes[i].indexes),this.meshes[i].indexes=null);return this._isPurged=!0,this._isGood=!1,!0},Inherit(Tw2GeometryRes,Tw2Resource),resMan.RegisterExtension("wbg",Tw2GeometryRes),Tw2TextureRes.prototype.Prepare=function(text){var format=device.gl.RGBA;if(this.images[0].ccpGLFormat&&(format=this.images[0].ccpGLFormat),"cube"==text){this.texture=device.gl.createTexture(),device.gl.bindTexture(device.gl.TEXTURE_CUBE_MAP,this.texture);for(var j=0;6>j;++j)device.gl.texImage2D(device.gl.TEXTURE_CUBE_MAP_POSITIVE_X+j,0,format,format,device.gl.UNSIGNED_BYTE,this.images[j]);device.gl.generateMipmap(device.gl.TEXTURE_CUBE_MAP),device.gl.bindTexture(device.gl.TEXTURE_CUBE_MAP,null),this.width=this.images[0].width,this.height=this.images[0].height,this.hasMipMaps=!0,this.PrepareFinished(!0)}else this.texture=device.gl.createTexture(),device.gl.bindTexture(device.gl.TEXTURE_2D,this.texture),device.gl.texImage2D(device.gl.TEXTURE_2D,0,format,format,device.gl.UNSIGNED_BYTE,this.images[0]),this.hasMipMaps=this.IsPowerOfTwo(this.images[0].width)&&this.IsPowerOfTwo(this.images[0].height),this.hasMipMaps&&device.gl.generateMipmap(device.gl.TEXTURE_2D),device.gl.bindTexture(device.gl.TEXTURE_2D,null),this.width=this.images[0].width,this.height=this.images[0].height,this.PrepareFinished(!0);delete this.images},Tw2TextureRes.prototype.IsPowerOfTwo=function(x){return 0==(x&x-1)},Tw2TextureRes.prototype.DoCustomLoad=function(path){this.LoadStarted(),this.images=[];var self=this;path=resMan.BuildUrl(path);var mipExt="";if(device.mipLevelSkipCount>0&&(mipExt="."+(""+device.mipLevelSkipCount)),".cube"==path.substr(-5)){this.isCube=!0,this._facesLoaded=0;for(var base=path.substr(0,path.length-5),extensions=[".px",".nx",".py",".ny",".pz",".nz"],onCubeFaceImageLoaded=function(){resMan._pendingLoads--,self._facesLoaded++,self._facesLoaded>=6&&(self.LoadFinished(!0),resMan._prepareQueue.push([self,"cube",null]))},i=0;6>i;++i)resMan._pendingLoads++,this.images[i]=new Image,this.images[i].crossOrigin="anonymous",this.images[i].onload=onCubeFaceImageLoaded,this.images[i].src=base+mipExt+extensions[i]+".png"}else{if(resMan._pendingLoads++,this.isCube=!1,this.images[0]=new Image,this.images[0].crossOrigin="anonymous",this.images[0].onload=function(){resMan._pendingLoads--,self.LoadFinished(!0),resMan._prepareQueue.push([self,"",null])},device.mipLevelSkipCount>0){var index=path.lastIndexOf(".");index>=0&&(path=path.substr(0,index)+mipExt+path.substr(index))}this.images[0].src=path}return!0},Tw2TextureRes.prototype.Unload=function(){return this.texture&&(device.gl.deleteTexture(this.texture),this.texture=null,this.isPurged=!0),this._isPurged=!0,this._isGood=!1,!0},Tw2TextureRes.prototype.Attach=function(texture){this.texture=texture,this.LoadFinished(!0),this.PrepareFinished(!0)},Tw2TextureRes.prototype.Bind=function(sampler,slices){this.KeepAlive();var targetType=sampler.samplerType;return null==this.texture?(device.gl.bindTexture(targetType,targetType==device.gl.TEXTURE_2D?device.GetFallbackTexture():device.GetFallbackCubeMap()),void 0):(sampler.isVolume&&device.gl.uniform1f(slices,this.height/this.width),device.gl.bindTexture(targetType,this.texture),sampler.hash!=this._currentSampler&&(sampler.Apply(this.hasMipMaps),this._currentSampler=sampler.hash),void 0)},Inherit(Tw2TextureRes,Tw2Resource),resMan.RegisterExtension("png",Tw2TextureRes),resMan.RegisterExtension("cube",Tw2TextureRes),Tw2EffectRes.prototype.requestResponseType="arraybuffer",Tw2EffectRes.prototype.Prepare=function(data){function ReadString(){for(var offset=reader.ReadUInt32(),end=offset;stringTable.charCodeAt(end);)++end;return stringTable.substr(offset,end-offset)}function CompileShader(stageType,prefix,shaderCode,path){var shader=device.gl.createShader(0==stageType?device.gl.VERTEX_SHADER:device.gl.FRAGMENT_SHADER);if(device.useBinaryShaders)device.shaderBinary.shaderBinary(shader,shaderCode);else{var source=prefix+String.fromCharCode.apply(null,shaderCode);source=source.substr(0,source.length-1),device.gl.shaderSource(shader,source),device.gl.compileShader(shader)}return device.gl.getShaderParameter(shader,device.gl.COMPILE_STATUS)?shader:(console.error("Tw2EffectRes:"," error compiling ",0==stageType?"vertex":"fragment"," shader (effect '",path,"'): ",device.gl.getShaderInfoLog(shader)),null)}function CreateProgram(vertexShader,fragmentShader,pass,path){var program={};if(program.program=device.gl.createProgram(),device.gl.attachShader(program.program,vertexShader),device.gl.attachShader(program.program,fragmentShader),device.gl.linkProgram(program.program),!device.gl.getProgramParameter(program.program,device.gl.LINK_STATUS))return console.error("Tw2EffectRes:"," error linking shaders (effect '",path,"'): ",device.gl.getProgramInfoLog(program.program)),null;device.gl.useProgram(program.program),program.constantBufferHandles=[];for(var j=0;16>j;++j)program.constantBufferHandles[j]=device.gl.getUniformLocation(program.program,"cb"+j);program.samplerHandles=[];for(var j=0;16>j;++j)program.samplerHandles[j]=device.gl.getUniformLocation(program.program,"s"+j),device.gl.uniform1i(program.samplerHandles[j],j);for(var j=0;16>j;++j)program.samplerHandles[j+16]=device.gl.getUniformLocation(program.program,"vs"+j),device.gl.uniform1i(program.samplerHandles[j+16],j+16);program.input=new Tw2VertexDeclaration;for(var j=0;pass.stages[0].inputDefinition.elements.length>j;++j){var location=device.gl.getAttribLocation(program.program,"attr"+j);if(location>=0){var el=new Tw2VertexElement(pass.stages[0].inputDefinition.elements[j].usage,pass.stages[0].inputDefinition.elements[j].usageIndex);el.location=location,program.input.elements.push(el)}}program.input.RebuildHash(),program.shadowStateInt=device.gl.getUniformLocation(program.program,"ssi"),program.shadowStateFloat=device.gl.getUniformLocation(program.program,"ssf"),program.shadowStateYFlip=device.gl.getUniformLocation(program.program,"ssyf"),device.gl.uniform3f(program.shadowStateYFlip,0,0,1),program.volumeSlices=[];for(var j=0;pass.stages[1].samplers.length>j;++j)pass.stages[1].samplers[j].isVolume&&(program.volumeSlices[pass.stages[1].samplers[j].registerIndex]=device.gl.getUniformLocation(program.program,"s"+pass.stages[1].samplers[j].registerIndex+"sl"));return program}this.passes=[],this.annotations={};var reader=new Tw2BinaryReader(new Uint8Array(data)),stringTable="",version=reader.ReadUInt32();if(2!=version&&3!=version)return console.error("Tw2EffectRes:",' invalid version of effect file "',this.path,'" (version ',version,")"),this.PrepareFinished(!1),void 0;var headerSize=reader.ReadUInt32();if(0==headerSize)return console.error("Tw2EffectRes:",' file "',this.path,'" contains no compiled effects'),this.PrepareFinished(!1),void 0;reader.ReadUInt32();var offset=reader.ReadUInt32();reader.cursor=8+4*3*headerSize;var stringTableSize=reader.ReadUInt32();stringTable=String.fromCharCode.apply(null,reader.data.subarray(reader.cursor,reader.cursor+stringTableSize)),reader.cursor=offset;for(var passCount=reader.ReadUInt8(),passIx=0;passCount>passIx;++passIx){var pass={};pass.stages=[{},{}];for(var stageCount=reader.ReadUInt8(),validShadowShader=!0,stageIx=0;stageCount>stageIx;++stageIx){var stage={};stage.inputDefinition=new Tw2VertexDeclaration,stage.constants=[],stage.textures=[],stage.samplers=[];for(var stageType=reader.ReadUInt8(),inputCount=reader.ReadUInt8(),inputIx=0;inputCount>inputIx;++inputIx){var usage=reader.ReadUInt8();reader.ReadUInt8();var usageIndex=reader.ReadUInt8();reader.ReadUInt8(),stage.inputDefinition.elements[inputIx]=new Tw2VertexElement(usage,usageIndex,0)}stage.inputDefinition.RebuildHash();var shaderSize=reader.ReadUInt32(),shaderCode=reader.data.subarray(reader.cursor,reader.cursor+shaderSize);reader.cursor+=shaderSize;var shadowShaderSize=reader.ReadUInt32(),shadowShaderCode=reader.data.subarray(reader.cursor,reader.cursor+shadowShaderSize);if(reader.cursor+=shadowShaderSize,stage.shader=CompileShader(stageType,"",shaderCode,this.path),null==stage.shader)return this.PrepareFinished(!1),void 0;validShadowShader?(stage.shadowShader=0==shadowShaderSize?CompileShader(stageType,"\n#define PS\n",shaderCode,this.path):CompileShader(stageType,"",shadowShaderCode,this.path),null==stage.shadowShader&&(validShadowShader=!1)):stage.shadowShader=null,3==version&&(reader.ReadUInt32(),reader.ReadUInt32(),reader.ReadUInt32()),stage.constantSize=0;for(var constantCount=reader.ReadUInt32(),constantIx=0;constantCount>constantIx;++constantIx){var constant={};if(constant.name=ReadString(),constant.offset=reader.ReadUInt32()/4,constant.size=reader.ReadUInt32()/4,constant.type=reader.ReadUInt8(),constant.dimension=reader.ReadUInt8(),constant.elements=reader.ReadUInt32(),constant.isSRGB=reader.ReadUInt8(),constant.isAutoregister=reader.ReadUInt8(),stage.constants[constantIx]=constant,"PerFrameVS"!=constant.name&&"PerObjectVS"!=constant.name&&"PerFramePS"!=constant.name&&"PerObjectPS"!=constant.name){var last=constant.offset+constant.size;last>stage.constantSize&&(stage.constantSize=last)}}var constantValueSize=reader.ReadUInt32()/4;stage.constantValues=new Float32Array(constantValueSize);for(var i=0;constantValueSize>i;++i)stage.constantValues[i]=reader.ReadFloat32();stage.constantSize=Math.max(stage.constantSize,constantValueSize);for(var textureCount=reader.ReadUInt8(),textureIx=0;textureCount>textureIx;++textureIx){var registerIndex=reader.ReadUInt8(),texture={};texture.registerIndex=registerIndex,texture.name=ReadString(),texture.type=reader.ReadUInt8(),texture.isSRGB=reader.ReadUInt8(),texture.isAutoregister=reader.ReadUInt8(),stage.textures.push(texture)}for(var samplerCount=reader.ReadUInt8(),samplerIx=0;samplerCount>samplerIx;++samplerIx){var registerIndex=reader.ReadUInt8();reader.ReadUInt8();var minFilter=reader.ReadUInt8(),magFilter=reader.ReadUInt8(),mipFilter=reader.ReadUInt8(),addressU=reader.ReadUInt8(),addressV=reader.ReadUInt8(),addressW=reader.ReadUInt8();reader.ReadFloat32();var maxAnisotropy=reader.ReadUInt8();reader.ReadUInt8();var borderColor=quat4.create();
  borderColor[0]=reader.ReadFloat32(),borderColor[1]=reader.ReadFloat32(),borderColor[2]=reader.ReadFloat32(),borderColor[3]=reader.ReadFloat32(),reader.ReadFloat32(),reader.ReadFloat32(),reader.ReadUInt8();var sampler=new Tw2SamplerState;if(sampler.registerIndex=registerIndex,1==minFilter){switch(mipFilter){case 0:sampler.minFilter=device.gl.NEAREST;break;case 1:sampler.minFilter=device.gl.NEAREST_MIPMAP_NEAREST;break;default:sampler.minFilter=device.gl.NEAREST_MIPMAP_LINEAR}sampler.minFilterNoMips=device.gl.NEAREST}else{switch(mipFilter){case 0:sampler.minFilter=device.gl.LINEAR;break;case 1:sampler.minFilter=device.gl.LINEAR_MIPMAP_NEAREST;break;default:sampler.minFilter=device.gl.LINEAR_MIPMAP_LINEAR}sampler.minFilterNoMips=device.gl.LINEAR}sampler.magFilter=1==magFilter?device.gl.NEAREST:device.gl.LINEAR;var wrapModes=[0,device.gl.REPEAT,device.gl.MIRRORED_REPEAT,device.gl.CLAMP_TO_EDGE,device.gl.CLAMP_TO_EDGE,device.gl.CLAMP_TO_EDGE];sampler.addressU=wrapModes[addressU],sampler.addressV=wrapModes[addressV],sampler.addressW=wrapModes[addressW],(3==minFilter||3==magFilter||3==mipFilter)&&(sampler.anisotropy=Math.max(maxAnisotropy,1));for(var n=0;stage.textures.length>n;++n)if(stage.textures[n].registerIndex==sampler.registerIndex){sampler.samplerType=4==stage.textures[n].type?device.gl.TEXTURE_CUBE_MAP:device.gl.TEXTURE_2D,sampler.isVolume=3==stage.textures[n].type;break}sampler.ComputeHash(),stage.samplers.push(sampler)}3==version&&reader.ReadUInt8(),pass.stages[stageType]=stage}pass.states=[];for(var stateCount=reader.ReadUInt8(),stateIx=0;stateCount>stateIx;++stateIx){var state=reader.ReadUInt32(),value=reader.ReadUInt32();pass.states.push({state:state,value:value})}if(pass.shaderProgram=CreateProgram(pass.stages[0].shader,pass.stages[1].shader,pass,this.path),null==pass.shaderProgram)return this.PrepareFinished(!1),void 0;validShadowShader?(pass.shadowShaderProgram=CreateProgram(pass.stages[0].shadowShader,pass.stages[1].shadowShader,pass,this.path),null==pass.shadowShaderProgram&&(pass.shadowShaderProgram=pass.shaderProgram)):pass.shadowShaderProgram=pass.shaderProgram,this.passes[passIx]=pass}for(var parameterCount=reader.ReadUInt16(),paramIx=0;parameterCount>paramIx;++paramIx){for(var name=ReadString(),annotations=[],annotationCount=reader.ReadUInt8(),annotationIx=0;annotationCount>annotationIx;++annotationIx)switch(annotations[annotationIx]={},annotations[annotationIx].name=ReadString(),annotations[annotationIx].type=reader.ReadUInt8(),annotations[annotationIx].type){case 0:annotations[annotationIx].value=0!=reader.ReadUInt32();break;case 1:annotations[annotationIx].value=reader.ReadInt32();break;case 2:annotations[annotationIx].value=reader.ReadFloat32();break;default:annotations[annotationIx].value=ReadString()}this.annotations[name]=annotations}this.PrepareFinished(!0)},Tw2EffectRes.prototype.ApplyPass=function(pass){pass=this.passes[pass];for(var i=0;pass.states.length>i;++i)device.SetRenderState(pass.states[i].state,pass.states[i].value);device.IsAlphaTestEnabled()?(device.gl.useProgram(pass.shadowShaderProgram.program),device.shadowHandles=pass.shadowShaderProgram):(device.gl.useProgram(pass.shaderProgram.program),device.shadowHandles=null)},Inherit(Tw2EffectRes,Tw2Resource),resMan.RegisterExtension("sm_hi",Tw2EffectRes),resMan.RegisterExtension("sm_lo",Tw2EffectRes),Tw2Effect.prototype.Initialize=function(){if(""!=this.effectFilePath){var path=this.effectFilePath,dot=path.lastIndexOf(".");path.substr(dot),path=path.toLowerCase().substr(0,dot).replace("/effect/",device.effectDir)+".sm_"+device.shaderModel,this.effectRes=resMan.GetResource(path),this.effectRes.RegisterNotification(this)}},Tw2Effect.prototype.GetEffectRes=function(){return this.effectRes},Tw2Effect.prototype.RebuildCachedData=function(resource){resource.IsGood()&&this.BindParameters()},Tw2Effect.prototype.BindParameters=function(){if(null==this.effectRes||!this.effectRes.IsGood())return!1;for(var i=0;this.passes.length>i;++i)for(var j=0;this.passes[i].stages.length>j;++j)for(var k=0;this.passes[i].stages[j].reroutedParameters.length>k;++k)this.passes[i].stages[j].reroutedParameters[k].Unbind();this.passes=[];for(var i=0;this.effectRes.passes.length>i;++i){var pass=[];pass.stages=[];for(var j=0;this.effectRes.passes[i].stages.length>j;++j){var stageRes=this.effectRes.passes[i].stages[j],stage={};stage.constantBuffer=new Float32Array(stageRes.constantSize),stage.reroutedParameters=[],stage.parameters=[],stage.textures=[],stage.constantBuffer.set(stageRes.constantValues);for(var k=0;stageRes.constants.length>k;++k){var constant=stageRes.constants[k],name=constant.name;if("PerFrameVS"!=name&&"PerObjectVS"!=name&&"PerFramePS"!=name&&"PerObjectPS"!=name&&"PerObjectPSInt"!=name)if(name in this.parameters){var param=this.parameters[name];if(param.Bind(stage.constantBuffer,constant.offset,constant.size))stage.reroutedParameters.push(param);else{var p={};p.parameter=param,p.constantBuffer=stage.constantBuffer,p.offset=constant.offset,p.size=constant.size,stage.parameters.push(p)}}else if(name in variableStore._variables){var param=variableStore._variables[name],p={};p.parameter=param,p.constantBuffer=stage.constantBuffer,p.offset=constant.offset,p.size=constant.size,stage.parameters.push(p)}else if(constant.isAutoregister){variableStore.RegisterType(name,constant.type);var param=variableStore._variables[name],p={};p.parameter=param,p.constantBuffer=stage.constantBuffer,p.offset=constant.offset,p.size=constant.size,stage.parameters.push(p)}}for(var k=0;stageRes.textures.length>k;++k){var name=stageRes.textures[k].name,param=null;if(name in this.parameters)param=this.parameters[name];else if(name in variableStore._variables)param=variableStore._variables[name];else{if(!stageRes.textures[k].isAutoregister)continue;variableStore.RegisterType(name,Tw2TextureParameter),param=variableStore._variables[name]}var p={};p.parameter=param,p.slot=stageRes.textures[k].registerIndex,p.sampler=null;for(var n=0;stageRes.samplers.length>n;++n)if(stageRes.samplers[n].registerIndex==p.slot){p.sampler=stageRes.samplers[n];break}0==j&&(p.slot+=16),stage.textures.push(p)}pass.stages.push(stage)}this.passes.push(pass)}return device.effectObserver&&device.effectObserver.OnEffectChanged(this),!0},Tw2Effect.prototype.ApplyPass=function(pass){if(null!=this.effectRes&&this.effectRes.IsGood()&&!(pass>=this.passes.length)){this.effectRes.ApplyPass(pass);var p=this.passes[pass],d=device;if(d.IsAlphaTestEnabled()&&this.effectRes.passes[pass].shadowShaderProgram)var program=this.effectRes.passes[pass].shadowShaderProgram;else var program=this.effectRes.passes[pass].shaderProgram;for(var i=0;2>i;++i){for(var j=0;p.stages[i].parameters.length>j;++j){var pp=p.stages[i].parameters[j];pp.parameter.Apply(pp.constantBuffer,pp.offset,pp.size)}for(var j=0;p.stages[i].textures.length>j;++j)p.stages[i].textures[j].parameter.Apply(p.stages[i].textures[j].slot,p.stages[i].textures[j].sampler,program.volumeSlices[p.stages[i].textures[j].sampler.registerIndex])}null!=program.constantBufferHandles[0]&&d.gl.uniform4fv(program.constantBufferHandles[0],p.stages[0].constantBuffer),null!=program.constantBufferHandles[7]&&d.gl.uniform4fv(program.constantBufferHandles[7],p.stages[1].constantBuffer),device.perFrameVSData&&program.constantBufferHandles[1]&&d.gl.uniform4fv(program.constantBufferHandles[1],d.perFrameVSData.data),device.perFramePSData&&program.constantBufferHandles[2]&&d.gl.uniform4fv(program.constantBufferHandles[2],d.perFramePSData.data),d.perObjectData&&d.perObjectData.SetPerObjectDataToDevice(program.constantBufferHandles)}},Tw2Effect.prototype.GetPassCount=function(){return null!=this.effectRes&&this.effectRes.IsGood()?this.passes.length:0},Tw2Effect.prototype.GetPassInput=function(pass){return null==this.effectRes||!this.effectRes.IsGood()||pass>=this.passes.length?null:device.IsAlphaTestEnabled()&&this.effectRes.passes[pass].shadowShaderProgram?this.effectRes.passes[pass].shadowShaderProgram.input:this.effectRes.passes[pass].shaderProgram.input},Tw2Effect.prototype.Render=function(cb){for(var count=this.GetPassCount(),i=0;count>i;++i)this.ApplyPass(i),cb(this,i)},Tw2MeshArea.batchType=Tw2GeometryBatch,Tw2MeshLineArea.batchType=Tw2GeometryLineBatch,Tw2Mesh.prototype.Initialize=function(){""!=this.geometryResPath&&(this.geometryResource=resMan.GetResource(this.geometryResPath))},Tw2Mesh.prototype._GetAreaBatches=function(areas,mode,accumulator,perObjectData){for(var i=0;areas.length>i;++i){var area=areas[i];if(null!=area.effect&&!area.debugIsHidden){var batch=new area.constructor.batchType;batch.renderMode=mode,batch.perObjectData=perObjectData,batch.geometryRes=this.geometryResource,batch.meshIx=area.meshIndex,batch.start=area.index,batch.count=area.count,batch.effect=area.effect,accumulator.Commit(batch)}}},Tw2Mesh.prototype.GetBatches=function(mode,accumulator,perObjectData){return null==this.geometryResource||this.debugIsHidden?!1:(mode==device.RM_OPAQUE?this._GetAreaBatches(this.opaqueAreas,mode,accumulator,perObjectData):mode==device.RM_DECAL?this._GetAreaBatches(this.decalAreas,mode,accumulator,perObjectData):mode==device.RM_TRANSPARENT?this._GetAreaBatches(this.transparentAreas,mode,accumulator,perObjectData):mode==device.RM_ADDITIVE&&this._GetAreaBatches(this.additiveAreas,mode,accumulator,perObjectData),!0)},Tw2Animation.prototype.IsFinished=function(){return!this.cycle&&this.time>=this.duration},Tw2AnimationController.prototype.SetGeometryResource=function(geometryResource){this.models=[],this.animations=[],this.meshBindings=[];for(var i=0;this.geometryResources.length>i;++i)this.geometryResources[i].UnregisterNotification(this);this.loaded=!1,this.geometryResources=[],geometryResource&&(this.geometryResources.push(geometryResource),geometryResource.RegisterNotification(this))},Tw2AnimationController.prototype.AddGeometryResource=function(geometryResource){for(var i=0;this.geometryResources.length>i;++i)if(this.geometryResources[i]==geometryResource)return;this.geometryResources.push(geometryResource),geometryResource.RegisterNotification(this)},Tw2AnimationController.prototype.AddAnimationsFromRes=function(resource){for(var i=0;resource.animations.length>i;++i){for(var animation=null,j=0;this.animations.length>j;++j)if(this.animations[j].animationRes==resource.animations[i]){animation=this.animations[i];break}animation||(animation=new Tw2Animation,animation.animationRes=resource.animations[i],this.animations.push(animation));for(var j=0;animation.animationRes.trackGroups.length>j;++j){for(var found=!1,k=0;animation.trackGroups.length>k;++k)if(animation.trackGroups[k].trackGroupRes==animation.animationRes.trackGroups[j]){found=!0;break}if(!found){for(var model=null,k=0;this.models.length>k;++k)if(this.models[k].modelRes.name==animation.animationRes.trackGroups[j].name){model=this.models[k];break}if(null!=model){var group=new Tw2TrackGroup;group.trackGroupRes=animation.animationRes.trackGroups[j];for(var k=0;group.trackGroupRes.transformTracks.length>k;++k)for(var m=0;model.bones.length>m;++m)if(model.bones[m].boneRes.name==group.trackGroupRes.transformTracks[k].name){var track=new Tw2Track;track.trackRes=group.trackGroupRes.transformTracks[k],track.bone=model.bones[m],group.transformTracks.push(track);break}animation.trackGroups.push(group)}}}}},Tw2AnimationController.prototype._AddModel=function(modelRes){for(var i=0;this.models.length>i;++i)if(this.models[i].modelRes.name==modelRes.name)return null;var model=new Tw2Model;model.modelRes=modelRes;var skeleton=modelRes.skeleton;if(null!=skeleton)for(var j=0;skeleton.bones.length>j;++j){var bone=new Tw2Bone;bone.boneRes=skeleton.bones[j],model.bones.push(bone)}return this.models.push(model),model},Tw2AnimationController.prototype._FindMeshBindings=function(resource){for(var i=0;this.meshBindings.length>i;++i)if(this.meshBindings[i].resource==resource)return this.meshBindings[i];return null},Tw2AnimationController.prototype.RebuildCachedData=function(resource){for(var found=!1,i=0;this.geometryResources.length>i;++i)if(this.geometryResources[i]==resource){found=!0;break}if(found){var newModels=[];if(resource.meshes.length)for(var i=0;resource.models.length>i;++i){var model=this._AddModel(resource.models[i]);model&&newModels.push(model)}for(var i=0;this.geometryResources.length>i;++i)this.AddAnimationsFromRes(this.geometryResources[i],this.models);for(var i=0;resource.models.length>i;++i){for(var model=null,j=0;this.models.length>j;++j)if(this.models[j].modelRes.name==resource.models[i].name){model=this.models[j];break}if(null!=model)for(var j=0;resource.models[i].meshBindings.length>j;++j){var meshIx=resource.meshes.indexOf(resource.models[i].meshBindings[j].mesh),meshBindings=this._FindMeshBindings(resource);null==meshBindings&&(meshBindings=[],meshBindings.resource=resource,this.meshBindings.push(meshBindings)),meshBindings[meshIx]=new glMatrixArrayType(12*resource.models[i].meshBindings[j].bones.length);for(var k=0;resource.models[i].meshBindings[j].bones.length>k;++k)for(var n=0;model.bones.length>n;++n)if(model.bones[n].boneRes.name==resource.models[i].meshBindings[j].bones[k].name){model.bones[n].bindingArrays||(model.bones[n].bindingArrays=[]);var arrayInfo={array:meshBindings[meshIx],offset:12*k};model.bones[n].bindingArrays[model.bones[n].bindingArrays.length]=arrayInfo;break}}}if(resource.meshes.length&&resource.models.length&&this.ResetBoneTransforms(resource.models),this.loaded=!0,this.animations.length){if(this.pendingCommands)for(var i=0;this.pendingCommands.length>i;++i)this.pendingCommands[i].func.apply(this,this.pendingCommands[i].args);this.pendingCommands=null}}},Tw2AnimationController.prototype.PlayAnimation=function(name,cycle,callback){if(0==this.animations.length)return this.pendingCommands||(this.pendingCommands=[]),this.pendingCommands.push({func:this.PlayAnimation,args:[name,cycle,callback]}),void 0;for(var i=0;this.animations.length>i;++i)this.animations[i].animationRes.name==name&&(this.animations[i].time=0,this.animations[i].isPlaying=!0,cycle!==void 0&&(this.animations[i].cycle=cycle),callback!==void 0&&(this.animations[i].callback=callback))},Tw2AnimationController.prototype.StopAnimation=function(name){for(var i=0;this.animations.length>i;++i)this.animations[i].animationRes.name==name&&(this.animations[i].isPlaying=!1)},Tw2AnimationController.prototype.StopAllAnimations=function(){for(var i=0;this.animations.length>i;++i)this.animations[i].isPlaying=!1},Tw2AnimationController.prototype.ResetBoneTransforms=function(){for(var i=0;this.models.length>i;++i)for(var j=0;this.models[i].bones.length>j;++j){var bone=this.models[i].bones[j],boneRes=bone.boneRes;mat4.set(boneRes.localTransform,bone.localTransform),-1!=boneRes.parentIndex?mat4.multiply(bone.localTransform,this.models[i].bones[bone.boneRes.parentIndex].worldTransform,bone.worldTransform):mat4.set(bone.localTransform,bone.worldTransform),mat4.identity(bone.offsetTransform)}for(var id=mat4.identity(mat4.create()),i=0;this.meshBindings.length>i;++i)for(var j=0;this.meshBindings[i].length>j;++j)for(var k=0;this.meshBindings[i][j].length>16*k;++k)for(var m=0;16>m;++m)this.meshBindings[i][j][16*k+m]=id[m]},Tw2AnimationController.prototype.Update=function(dt){function EvaluateCurve(curve,time,value,cycle,duration){for(var count=curve.knots.length,knot=count-1,t=0,i=0;curve.knots.length>i;++i)if(curve.knots[i]>time){knot=i;break}if(0==curve.degree)for(var i=0;curve.dimension>i;++i)value[i]=curve.controls[knot*curve.dimension+i];else if(1==curve.degree){var knot0=cycle?(knot+count-1)%count:0==knot?0:knot-1,dt=curve.knots[knot]-curve.knots[knot0];0>dt&&(dt+=duration),dt>0&&(t=(time-curve.knots[i-1])/dt);for(var i=0;curve.dimension>i;++i)value[i]=curve.controls[knot0*curve.dimension+i]*(1-t)+curve.controls[knot*curve.dimension+i]*t}else{var k_2=cycle?(knot+count-2)%count:0==knot?0:knot-2,k_1=cycle?(knot+count-1)%count:0==knot?0:knot-1,p1=k_2*curve.dimension,p2=k_1*curve.dimension,p3=knot*curve.dimension,ti_2=curve.knots[k_2],ti_1=curve.knots[k_1],ti=curve.knots[knot],ti1=curve.knots[(knot+1)%count];ti_2>ti&&(ti+=duration,ti1+=duration,time+=duration),ti_1>ti&&(ti+=duration,ti1+=duration,time+=duration),ti>ti1&&(ti1+=duration);var tmti_1=time-ti_1,tmti_2=time-ti_2,dL0=ti-ti_1,dL1_1=ti-ti_2,dL1_2=ti1-ti_1,L0=tmti_1/dL0,L1_1=tmti_2/dL1_1,L1_2=tmti_1/dL1_2,ci_2=L1_1+L0-L0*L1_1,ci=L0*L1_2,ci_1=ci_2-ci;ci_2=1-ci_2;for(var i=0;curve.dimension>i;++i)value[i]=ci_2*curve.controls[p1+i]+ci_1*curve.controls[p2+i]+ci*curve.controls[p3+i]}}if(null!=this.models&&this.update){for(var i=0;this.geometryResources.length>i;++i)this.geometryResources[i].KeepAlive();for(var tempMat=mat4.create(),updateBones=!1,i=0;this.animations.length>i;++i){var animation=this.animations[i];if(animation.isPlaying){var res=animation.animationRes;animation.time+=dt*animation.timeScale,animation.time>res.duration&&(null!=animation.callback&&animation.callback(this,animation),animation.cycle?animation.time=animation.time%res.duration:(animation.isPlaying=!1,animation.time=res.duration));for(var orientation=quat4.create(),scale=mat3.create(),position=vec3.create(),j=0;animation.trackGroups.length>j;++j)for(var k=0;animation.trackGroups[j].transformTracks.length>k;++k){var track=animation.trackGroups[j].transformTracks[k];track.trackRes.position?EvaluateCurve(track.trackRes.position,animation.time,position,animation.cycle,res.duration):position[0]=position[1]=position[2]=0,track.trackRes.orientation?(EvaluateCurve(track.trackRes.orientation,animation.time,orientation,animation.cycle,res.duration),quat4.normalize(orientation)):(orientation[0]=orientation[1]=orientation[2]=0,orientation[3]=1),track.trackRes.scaleShear?EvaluateCurve(track.trackRes.scaleShear,animation.time,scale,animation.cycle,res.duration):mat3.identity(scale),mat3.toMat4(scale,track.bone.localTransform),mat4.multiply(track.bone.localTransform,mat4.transpose(quat4.toMat4(orientation,tempMat))),track.bone.localTransform[12]=position[0],track.bone.localTransform[13]=position[1],track.bone.localTransform[14]=position[2],updateBones=!0}}}for(var i=0;this.models.length>i;++i)for(var j=0;this.models[i].bones.length>j;++j){var bone=this.models[i].bones[j];if(-1!=bone.boneRes.parentIndex?mat4.multiply(this.models[i].bones[bone.boneRes.parentIndex].worldTransform,bone.localTransform,bone.worldTransform):mat4.set(bone.localTransform,bone.worldTransform),mat4.multiply(bone.worldTransform,bone.boneRes.worldTransformInv,bone.offsetTransform),bone.bindingArrays)for(var a=0;bone.bindingArrays.length>a;++a)bone.bindingArrays[a].array[bone.bindingArrays[a].offset+0]=bone.offsetTransform[0],bone.bindingArrays[a].array[bone.bindingArrays[a].offset+1]=bone.offsetTransform[4],bone.bindingArrays[a].array[bone.bindingArrays[a].offset+2]=bone.offsetTransform[8],bone.bindingArrays[a].array[bone.bindingArrays[a].offset+3]=bone.offsetTransform[12],bone.bindingArrays[a].array[bone.bindingArrays[a].offset+4]=bone.offsetTransform[1],bone.bindingArrays[a].array[bone.bindingArrays[a].offset+5]=bone.offsetTransform[5],bone.bindingArrays[a].array[bone.bindingArrays[a].offset+6]=bone.offsetTransform[9],bone.bindingArrays[a].array[bone.bindingArrays[a].offset+7]=bone.offsetTransform[13],bone.bindingArrays[a].array[bone.bindingArrays[a].offset+8]=bone.offsetTransform[2],bone.bindingArrays[a].array[bone.bindingArrays[a].offset+9]=bone.offsetTransform[6],bone.bindingArrays[a].array[bone.bindingArrays[a].offset+10]=bone.offsetTransform[10],bone.bindingArrays[a].array[bone.bindingArrays[a].offset+11]=bone.offsetTransform[14]}}},Tw2AnimationController.prototype.RenderDebugInfo=function(debugHelper){for(var i=0;this.models.length>i;++i)for(var j=0;this.models[i].bones.length>j;++j){var b0=this.models[i].bones[j];if(b0.boneRes.parentIndex>=0){var b1=this.models[i].bones[b0.boneRes.parentIndex];debugHelper.AddLine([b0.worldTransform[12],b0.worldTransform[13],b0.worldTransform[14]],[b1.worldTransform[12],b1.worldTransform[13],b1.worldTransform[14]])}}},Tw2AnimationController.prototype.GetBoneMatrixes=function(meshIndex,geometryResource){if(0==this.geometryResources.length)return new Float32Array;geometryResource===void 0&&(geometryResource=this.geometryResources[0]);var meshBindings=this._FindMeshBindings(geometryResource);return meshBindings&&meshBindings.length>meshIndex?meshBindings[meshIndex]:new Float32Array},Tw2AnimationController.prototype.FindModelForMesh=function(meshIndex,geometryResource){if(0==this.geometryResources.length)return null;if(geometryResource===void 0&&(geometryResource=this.geometryResources[0]),!geometryResource.IsGood())return null;for(var mesh=geometryResource.meshes[meshIndex],i=0;this.models.length>i;++i)for(var j=0;this.models[i].modelRes.meshBindings.length>j;++i)if(this.models[i].modelRes.meshBindings[j].mesh=mesh)return this.models[i];return null},Tw2RenderTarget.prototype.Destroy=function(){this.texture&&(device.gl.deleteTexture(this.texture.texture),this.texture=null),this._renderBuffer&&(device.gl.deleteRenderbuffer(this._renderBuffer),this._renderBuffer=null),this._frameBuffer&&(device.gl.deleteFramebuffer(this._frameBuffer),this._frameBuffer=null)},Tw2RenderTarget.prototype.Create=function(width,height,hasDepth){this.Destroy(),this.texture=new Tw2TextureRes,this.texture.Attach(device.gl.createTexture()),this._frameBuffer=device.gl.createFramebuffer(),device.gl.bindFramebuffer(device.gl.FRAMEBUFFER,this._frameBuffer),device.gl.bindTexture(device.gl.TEXTURE_2D,this.texture.texture),device.gl.texImage2D(device.gl.TEXTURE_2D,0,device.gl.RGBA,width,height,0,device.gl.RGBA,device.gl.UNSIGNED_BYTE,null),device.gl.texParameteri(device.gl.TEXTURE_2D,device.gl.TEXTURE_MAG_FILTER,device.gl.LINEAR),device.gl.texParameteri(device.gl.TEXTURE_2D,device.gl.TEXTURE_MIN_FILTER,device.gl.LINEAR),device.gl.bindTexture(device.gl.TEXTURE_2D,null),this._renderBuffer=null,hasDepth&&(this._renderBuffer=device.gl.createRenderbuffer(),device.gl.bindRenderbuffer(device.gl.RENDERBUFFER,this._renderBuffer),device.gl.renderbufferStorage(device.gl.RENDERBUFFER,device.gl.DEPTH_COMPONENT16,width,height)),device.gl.framebufferTexture2D(device.gl.FRAMEBUFFER,device.gl.COLOR_ATTACHMENT0,device.gl.TEXTURE_2D,this.texture.texture,0),hasDepth&&device.gl.framebufferRenderbuffer(device.gl.FRAMEBUFFER,device.gl.DEPTH_ATTACHMENT,device.gl.RENDERBUFFER,this._renderBuffer),device.gl.bindRenderbuffer(device.gl.RENDERBUFFER,null),device.gl.bindFramebuffer(device.gl.FRAMEBUFFER,null),this.width=width,this.height=height,this.hasDepth=hasDepth},Tw2RenderTarget.prototype.Set=function(){this._oldViewport=device.gl.getParameter(device.gl.VIEWPORT),device.gl.bindFramebuffer(device.gl.FRAMEBUFFER,this._frameBuffer),device.gl.viewport(0,0,this.width,this.height)},Tw2RenderTarget.prototype.Unset=function(){device.gl.bindFramebuffer(device.gl.FRAMEBUFFER,null),device.gl.viewport(this._oldViewport[0],this._oldViewport[1],this._oldViewport[2],this._oldViewport[3])},Inherit(Tw2InstancedMesh,Tw2Mesh),Tw2InstancedMesh.prototype.Initialize=function(){this._super.Initialize.call(this),""!=this.instanceGeometryResPath?(this.instanceGeometryResource=resMan.GetResource(this.instanceGeometryResPath),this.instanceGeometryResource.RegisterNotification(this)):this.instanceGeometryResource&&this.geometryResource&&this.geometryResource.SetInstanceCount(this.instanceGeometryResource.GetMaxInstanceCount(this.instanceMeshIndex))},Tw2InstancedMesh.prototype.RebuildCachedData=function(){this.instanceGeometryResource&&this.geometryResource&&this.geometryResource.SetInstanceCount(this.instanceGeometryResource.GetMaxInstanceCount(this.instanceMeshIndex))},Tw2InstancedMesh.prototype._GetAreaBatches=function(areas,mode,accumulator,perObjectData){for(var i=0;areas.length>i;++i){var area=areas[i];if(null!=area.effect&&!area.debugIsHidden){var batch=new Tw2InstancedMeshBatch;batch.renderMode=mode,batch.perObjectData=perObjectData,batch.instanceMesh=this,batch.meshIx=area.meshIndex,batch.start=area.index,batch.count=area.count,batch.effect=area.effect,accumulator.Commit(batch)}}},Tw2InstancedMesh.prototype.RenderAreas=function(effect){if(this.geometryResource&&this.geometryResource.KeepAlive(),this.instanceGeometryResource&&this.instanceGeometryResource.KeepAlive&&this.instanceGeometryResource.KeepAlive(),this.geometryResource&&this.instanceGeometryResource){if(!this.geometryResource.IsGood())return;this.instanceGeometryResource.Render(effect,this.geometryResource.meshes[0].buffer,this.geometryResource.meshes[0].indexes,this.geometryResource.meshes[0].declaration,this.geometryResource.meshes[0].declaration.stride)}},Inherit(Tw2InstancedMeshBatch,Tw2RenderBatch),Tw2InstancedMeshBatch.prototype.Commit=function(overrideEffect){var effect=overrideEffect===void 0?this.effect:overrideEffect;this.instanceMesh&&effect&&this.instanceMesh.RenderAreas(effect)},EveBoosterSet.prototype.Initialize=function(){this.rebuildPending=!0},EveBoosterSet.prototype.Clear=function(){this._boosterTransforms=[],this._wavePhase=mat4.create(),this.glows&&this.glows.Clear()},EveBoosterSet.prototype.Add=function(localMatrix){var transform=mat4.create();if(mat4.set(localMatrix,transform),this._boosterTransforms[this._boosterTransforms.length]=transform,this._wavePhase[this._wavePhase.length]=Math.random(),this.glows){var pos=vec3.create([localMatrix[12],localMatrix[13],localMatrix[14]]),dir=vec3.create([localMatrix[8],localMatrix[9],localMatrix[10]]),scale=vec3.length(dir),spritePos=vec3.create();vec3.subtract(pos,vec3.scale(dir,2.5,spritePos),spritePos),this.glows.Add(spritePos,0,0,scale*this.glowScale,scale*this.glowScale,0,this.glowColor),vec3.subtract(pos,vec3.scale(dir,3,spritePos),spritePos),this.glows.Add(spritePos,0,1,scale*this.symHaloScale,scale*this.symHaloScale,0,this.haloColor),vec3.subtract(pos,vec3.scale(dir,3.01,spritePos),spritePos),this.glows.Add(spritePos,0,1,scale*this.haloScaleX,scale*this.haloScaleY,0,this.haloColor)}},EveBoosterSet.prototype.Rebuild=function(){for(var data=new Float32Array(22*6*4*this._boosterTransforms.length),order=[[-1,-1,0,1,1],[1,1,-1,0,0],[-1,-1,-1,1,0],[-1,-1,0,1,1],[1,1,0,0,1],[1,1,-1,0,0]],index=0,booster=0;this._boosterTransforms.length>booster;++booster){vec3.create();for(var i=0;4>i;++i)for(var t=i*Math.PI/4,x=.5*Math.cos(t),y=.5*Math.sin(t),j=0;6>j;++j)data[index++]=x*order[j][0],data[index++]=y*order[j][1],data[index++]=order[j][2],data[index++]=order[j][3],data[index++]=order[j][4],data.set(this._boosterTransforms[booster],index),index+=16,data[index++]=this._wavePhase[booster]}device.gl.bindBuffer(device.gl.ARRAY_BUFFER,this._positions),device.gl.bufferData(device.gl.ARRAY_BUFFER,data,device.gl.STATIC_DRAW),this.rebuildPending=!1,this.glows&&this.glows.RebuildBuffers()},EveBoosterSet.prototype.Update=function(dt,parentMatrix){this.glows&&this.glows.Update(dt),this._parentTransform=parentMatrix},EveBoosterBatch.prototype.Commit=function(overrideEffect){this.boosters.Render(overrideEffect)},EveBoosterSet.prototype.GetBatches=function(mode,accumulator,perObjectData){if(this.display&&mode==device.RM_ADDITIVE){if(this.effect&&this._boosterTransforms.length){var batch=new EveBoosterBatch;mat4.transpose(this._parentTransform,this._perObjectData.perObjectVSData.Get("WorldMat")),this._perObjectData.perObjectVSData.Set("Shipdata",perObjectData.perObjectVSData.Get("Shipdata")),this._perObjectData.perObjectPSData=perObjectData.perObjectPSData,batch.perObjectData=this._perObjectData,batch.boosters=this,batch.renderMode=device.RM_ADDITIVE,accumulator.Commit(batch)}this.glows&&this.glows.GetBatches(mode,accumulator,perObjectData)}},EveBoosterSet.prototype.Render=function(overrideEffect){var effect=overrideEffect===void 0?this.effect:overrideEffect,effectRes=effect.GetEffectRes();if(!effectRes.IsGood())return!1;device.gl.bindBuffer(device.gl.ARRAY_BUFFER,this._positions);for(var pass=0;effect.GetPassCount()>pass;++pass){if(effect.ApplyPass(pass),!this._decl.SetDeclaration(effect.GetPassInput(pass),88))return!1;device.ApplyShadowState(),device.gl.drawArrays(device.gl.TRIANGLES,0,3*8*this._boosterTransforms.length)}return!0},EveSpriteSet.prototype.Initialize=function(){this.RebuildBuffers()},EveSpriteSet.prototype.RebuildBuffers=function(){for(var vertexSize=12,array=new Float32Array(4*this.sprites.length*vertexSize),i=0;this.sprites.length>i;++i){var offset=4*i*vertexSize;array[offset+0*vertexSize]=0,array[offset+1*vertexSize]=1,array[offset+2*vertexSize]=2,array[offset+3*vertexSize]=3;for(var j=0;4>j;++j){var vtxOffset=offset+j*vertexSize;array[vtxOffset+1]=this.sprites[i].position[0],array[vtxOffset+2]=this.sprites[i].position[1],array[vtxOffset+3]=this.sprites[i].position[2],array[vtxOffset+4]=this.sprites[i].color[0],array[vtxOffset+5]=this.sprites[i].color[1],array[vtxOffset+6]=this.sprites[i].color[2],array[vtxOffset+7]=this.sprites[i].blinkPhase,array[vtxOffset+8]=this.sprites[i].blinkRate,array[vtxOffset+9]=this.sprites[i].minScale,array[vtxOffset+10]=this.sprites[i].maxScale,array[vtxOffset+11]=this.sprites[i].falloff}}this._vertexBuffer=device.gl.createBuffer(),device.gl.bindBuffer(device.gl.ARRAY_BUFFER,this._vertexBuffer),device.gl.bufferData(device.gl.ARRAY_BUFFER,array,device.gl.STATIC_DRAW),device.gl.bindBuffer(device.gl.ARRAY_BUFFER,null);for(var indexes=new Uint16Array(6*this.sprites.length),i=0;this.sprites.length>i;++i){var offset=6*i,vtxOffset=4*i;indexes[offset]=vtxOffset,indexes[offset+1]=vtxOffset+2,indexes[offset+2]=vtxOffset+1,indexes[offset+3]=vtxOffset+0,indexes[offset+4]=vtxOffset+3,indexes[offset+5]=vtxOffset+2}this._indexBuffer=device.gl.createBuffer(),device.gl.bindBuffer(device.gl.ELEMENT_ARRAY_BUFFER,this._indexBuffer),device.gl.bufferData(device.gl.ELEMENT_ARRAY_BUFFER,indexes,device.gl.STATIC_DRAW),device.gl.bindBuffer(device.gl.ELEMENT_ARRAY_BUFFER,null),this._indexBuffer.count=6*this.sprites.length},EveSpriteSetBatch.prototype.Commit=function(overrideEffect){this.spriteSet.Render(overrideEffect)},Inherit(EveSpriteSetBatch,Tw2RenderBatch),EveSpriteSet.prototype.GetBatches=function(mode,accumulator,perObjectData){if(mode==device.RM_ADDITIVE){var batch=new EveSpriteSetBatch;batch.renderMode=device.RM_ADDITIVE,batch.spriteSet=this,batch.perObjectData=perObjectData,accumulator.Commit(batch)}},EveSpriteSet.prototype.Render=function(overrideEffect){var effect=overrideEffect===void 0?this.effect:overrideEffect;if(effect&&this._vertexBuffer){var effectRes=effect.GetEffectRes();if(effectRes.IsGood()){device.SetStandardStates(device.RM_ADDITIVE),device.gl.bindBuffer(device.gl.ARRAY_BUFFER,this._vertexBuffer),device.gl.bindBuffer(device.gl.ELEMENT_ARRAY_BUFFER,this._indexBuffer);for(var pass=0;effect.GetPassCount()>pass;++pass){if(effect.ApplyPass(pass),!this._decl.SetDeclaration(effect.GetPassInput(pass),48))return;device.ApplyShadowState(),device.gl.drawElements(device.gl.TRIANGLES,this._indexBuffer.count,device.gl.UNSIGNED_SHORT,0)}}}},EveSpriteSet.prototype.Update=function(dt){this._time+=dt},EveSpriteSet.prototype.Clear=function(){this.sprites=[]},EveSpriteSet.prototype.Add=function(pos,blinkRate,blinkPhase,minScale,maxScale,falloff,color){var item=new EveSpriteSetItem;item.position=vec3.create(pos),item.blinkRate=blinkRate,item.blinkPhase=blinkPhase,item.minScale=minScale,item.maxScale=maxScale,item.falloff=falloff,item.color=color,this.sprites[this.sprites.length]=item},EveSpotlightSet.prototype.Initialize=function(){this.Rebuild()},EveSpotlightSet.prototype.Rebuild=function(){var itemCount=this.spotlightItems.length;if(0!=itemCount){for(var vertCount=4,coneQuadCount=4,coneVertexCount=itemCount*coneQuadCount*vertCount,vertexSize=20,array=new Float32Array(coneVertexCount*vertexSize),indexes=[1,0,2,3],i=0;itemCount>i;++i)for(var item=this.spotlightItems[i],q=0;coneQuadCount>q;++q)for(var v=0;vertCount>v;++v){var offset=(i*coneQuadCount*vertCount+vertCount*q+v)*vertexSize;array[offset]=item.coneColor[0],array[offset+1]=item.coneColor[1],array[offset+2]=item.coneColor[2],array[offset+3]=item.coneColor[3],array[offset+4]=item.transform[0],array[offset+5]=item.transform[4],array[offset+6]=item.transform[8],array[offset+7]=item.transform[12],array[offset+8]=item.transform[1],array[offset+9]=item.transform[5],array[offset+10]=item.transform[9],array[offset+11]=item.transform[13],array[offset+12]=item.transform[2],array[offset+13]=item.transform[6],array[offset+14]=item.transform[10],array[offset+15]=item.transform[14],array[offset+16]=1,array[offset+17]=1,array[offset+18]=1,array[offset+19]=q*vertCount+indexes[v]
  }this._coneVertexBuffer=device.gl.createBuffer(),device.gl.bindBuffer(device.gl.ARRAY_BUFFER,this._coneVertexBuffer),device.gl.bufferData(device.gl.ARRAY_BUFFER,array,device.gl.STATIC_DRAW),this._coneVertexBuffer.count=6*itemCount*coneQuadCount;var spriteQuadCount=2,spriteVertexCount=itemCount*spriteQuadCount*vertCount;array=new Float32Array(spriteVertexCount*vertexSize);for(var indexes=[1,0,2,3],i=0;itemCount>i;++i)for(var item=this.spotlightItems[i],q=0;spriteQuadCount>q;++q)for(var v=0;vertCount>v;++v){var offset=(i*spriteQuadCount*vertCount+vertCount*q+v)*vertexSize;0==q%2?(array[offset]=item.spriteColor[0],array[offset+1]=item.spriteColor[1],array[offset+2]=item.spriteColor[2],array[offset+3]=item.spriteColor[3],array[offset+16]=item.spriteScale[0],array[offset+17]=1,array[offset+18]=1):(array[offset]=item.flareColor[0],array[offset+1]=item.flareColor[1],array[offset+2]=item.flareColor[2],array[offset+3]=item.flareColor[3],array[offset+16]=1,array[offset+17]=item.spriteScale[1],array[offset+18]=item.spriteScale[2]),array[offset+4]=item.transform[0],array[offset+5]=item.transform[4],array[offset+6]=item.transform[8],array[offset+7]=item.transform[12],array[offset+8]=item.transform[1],array[offset+9]=item.transform[5],array[offset+10]=item.transform[9],array[offset+11]=item.transform[13],array[offset+12]=item.transform[2],array[offset+13]=item.transform[6],array[offset+14]=item.transform[10],array[offset+15]=item.transform[14],array[offset+19]=q*vertCount+indexes[v]}this._spriteVertexBuffer=device.gl.createBuffer(),device.gl.bindBuffer(device.gl.ARRAY_BUFFER,this._spriteVertexBuffer),device.gl.bufferData(device.gl.ARRAY_BUFFER,array,device.gl.STATIC_DRAW),this._spriteVertexBuffer.count=6*itemCount*spriteQuadCount;for(var indexes=new Uint16Array(6*itemCount*coneQuadCount),i=0;itemCount*coneQuadCount>i;++i){var offset=6*i,vtxOffset=4*i;indexes[offset]=vtxOffset,indexes[offset+1]=vtxOffset+1,indexes[offset+2]=vtxOffset+2,indexes[offset+3]=vtxOffset+2,indexes[offset+4]=vtxOffset+3,indexes[offset+5]=vtxOffset+0}this._indexBuffer=device.gl.createBuffer(),device.gl.bindBuffer(device.gl.ELEMENT_ARRAY_BUFFER,this._indexBuffer),device.gl.bufferData(device.gl.ELEMENT_ARRAY_BUFFER,indexes,device.gl.STATIC_DRAW),device.gl.bindBuffer(device.gl.ELEMENT_ARRAY_BUFFER,null)}},EveSpotlightSetBatch.prototype.Commit=function(overrideEffect){this.spotlightSet.RenderCones(overrideEffect),this.spotlightSet.RenderGlow(overrideEffect)},Inherit(EveSpotlightSetBatch,Tw2RenderBatch),EveSpotlightSet.prototype.GetBatches=function(mode,accumulator,perObjectData){if(this.display&&mode==device.RM_ADDITIVE){var batch=new EveSpotlightSetBatch;batch.renderMode=device.RM_ADDITIVE,batch.spotlightSet=this,batch.perObjectData=perObjectData,accumulator.Commit(batch)}},EveSpotlightSet.prototype.RenderCones=function(overrideEffect){var effect=overrideEffect===void 0?this.coneEffect:overrideEffect;this._Render(effect,this._coneVertexBuffer)},EveSpotlightSet.prototype.RenderGlow=function(overrideEffect){var effect=overrideEffect===void 0?this.glowEffect:overrideEffect;this._Render(effect,this._spriteVertexBuffer)},EveSpotlightSet.prototype._Render=function(effect,buffer){if(effect&&buffer&&this._indexBuffer){var effectRes=effect.GetEffectRes();if(effectRes.IsGood()){device.SetStandardStates(device.RM_ADDITIVE),device.gl.bindBuffer(device.gl.ARRAY_BUFFER,buffer);var stride=80;device.gl.bindBuffer(device.gl.ELEMENT_ARRAY_BUFFER,this._indexBuffer);for(var pass=0;effect.GetPassCount()>pass;++pass){if(effect.ApplyPass(pass),!this._decl.SetDeclaration(effect.GetPassInput(pass),stride))return;device.ApplyShadowState(),device.gl.drawElements(device.gl.TRIANGLES,buffer.count,device.gl.UNSIGNED_SHORT,0)}}}},EveBasicPerObjectData.prototype.SetPerObjectDataToDevice=function(constantBufferHandles){this.perObjectVSData&&constantBufferHandles[3]&&device.gl.uniform4fv(constantBufferHandles[3],this.perObjectVSData.data),this.perObjectPSData&&constantBufferHandles[4]&&device.gl.uniform4fv(constantBufferHandles[4],this.perObjectPSData.data),this.perObjectFFEData&&constantBufferHandles[5]&&device.gl.uniform4fv(constantBufferHandles[5],this.perObjectFFEData.data)},EveTransform.prototype.Initialize=function(){mat4.identity(this.localTransform),mat4.translate(this.localTransform,this.translation),mat4.transpose(quat4.toMat4(this.rotation,this.rotationTransform)),mat4.multiply(this.localTransform,this.rotationTransform,this.localTransform),mat4.scale(this.localTransform,this.scaling)},EveTransform.prototype.GetBatches=function(mode,accumulator,perObjectData){if(this.display){null!=this.mesh&&(mat4.transpose(this.worldTransform,this._perObjectData.perObjectFFEData.Get("World")),mat4.inverse(this.worldTransform,this._perObjectData.perObjectFFEData.Get("WorldInverseTranspose")),perObjectData&&(this._perObjectData.perObjectVSData=perObjectData.perObjectVSData,this._perObjectData.perObjectPSData=perObjectData.perObjectPSData),this.mesh.GetBatches(mode,accumulator,this._perObjectData));for(var i=0;this.children.length>i;++i)this.children[i].GetBatches(mode,accumulator,perObjectData)}},EveTransform.prototype.Update=function(dt){for(var i=0;this.children.length>i;++i)this.children[i].Update(dt);for(var i=0;this.particleEmitters.length>i;++i)this.particleEmitters[i].Update(dt);for(var i=0;this.particleSystems.length>i;++i)this.particleSystems[i].Update(dt)},mat4.multiply3x3=function(a,b,c){c||(c=b);var d=b[0],e=b[1];return b=b[2],c[0]=a[0]*d+a[4]*e+a[8]*b,c[1]=a[1]*d+a[5]*e+a[9]*b,c[2]=a[2]*d+a[6]*e+a[10]*b,c},EveTransform.prototype.UpdateViewDependentData=function(parentTransform){switch(this.modifier){case this.BILLBOARD:case this.SIMPLE_HALO:mat4.multiply(parentTransform,this.localTransform,this.worldTransform);var finalScale=this._vec3Cache[0];vec3.set(this.scaling,finalScale);var parentScaleX=vec3.length(parentTransform),parentScaleY=vec3.length(parentTransform.subarray(4)),parentScaleZ=vec3.length(parentTransform.subarray(8));if(finalScale[0]*=parentScaleX,finalScale[1]*=parentScaleY,finalScale[2]*=parentScaleZ,this.modifier==this.SIMPLE_HALO){var camPos=device.GetEyePosition(),d=this._vec3Cache[1];vec3.subtract(camPos,this.worldTransform.subarray(12),d);var scale=vec3.dot(vec3.normalize(d),vec3.normalize(this.worldTransform.subarray(8),this._vec3Cache[2]));0>scale&&(scale=0),vec3.scale(finalScale,scale*scale)}var invView=device.viewInv;this.worldTransform[0]=invView[0]*finalScale,this.worldTransform[1]=invView[1]*finalScale,this.worldTransform[2]=invView[2]*finalScale,this.worldTransform[4]=invView[4]*finalScale,this.worldTransform[5]=invView[5]*finalScale,this.worldTransform[6]=invView[6]*finalScale,this.worldTransform[8]=invView[8]*finalScale,this.worldTransform[9]=invView[9]*finalScale,this.worldTransform[10]=invView[10]*finalScale;break;case this.EVE_CAMERA_ROTATION:var newTranslation=mat4.multiplyVec3(parentTransform,this.translation,vec3.create());mat4.identity(this.localTransform),mat4.translate(this.localTransform,newTranslation),mat4.transpose(quat4.toMat4(this.rotation,this.rotationTransform)),mat4.multiply(this.localTransform,this.rotationTransform,this.localTransform),mat4.scale(this.localTransform,this.scaling);var x=this.localTransform[12],y=this.localTransform[13],z=this.localTransform[14];mat4.multiply(device.viewInv,this.localTransform,this.worldTransform),this.worldTransform[12]=x,this.worldTransform[13]=y,this.worldTransform[14]=z;break;case this.EVE_CAMERA_ROTATION_ALIGNED:case this.EVE_SIMPLE_HALO:mat4.translate(parentTransform,this.translation,this.worldTransform);var camPos=device.GetEyePosition(),d=this._vec3Cache[0];d[0]=camPos[0]-this.worldTransform[12],d[1]=camPos[1]-this.worldTransform[13],d[2]=camPos[2]-this.worldTransform[14];var parentT=this._mat4Cache[0];mat4.transpose(parentTransform,parentT);var camFwd=this._vec3Cache[1];vec3.set(d,camFwd),mat4.multiply3x3(parentT,camFwd);var parentScaleX=vec3.length(parentTransform);camFwd[0]/=parentScaleX;var parentScaleY=vec3.length(parentTransform.subarray(4));camFwd[1]/=parentScaleY;var parentScaleZ=vec3.length(parentTransform.subarray(8));camFwd[2]/=parentScaleZ,vec3.length(camFwd),vec3.normalize(camFwd);var right=this._vec3Cache[2];right[0]=device.view[0],right[1]=device.view[4],right[2]=device.view[8],mat4.multiply3x3(parentT,right),vec3.normalize(right);var up=this._vec3Cache[3];vec3.cross(camFwd,right,up),vec3.normalize(up);var alignMat=this._mat4Cache[1];if(vec3.cross(up,camFwd,right),alignMat[0]=right[0],alignMat[1]=right[1],alignMat[2]=right[2],alignMat[4]=up[0],alignMat[5]=up[1],alignMat[6]=up[2],alignMat[8]=camFwd[0],alignMat[9]=camFwd[1],alignMat[10]=camFwd[2],alignMat[15]=1,mat4.multiply(alignMat,this.rotationTransform,alignMat),this.modifier==this.EVE_SIMPLE_HALO){var forward=this._vec3Cache[4];vec3.normalize(this.worldTransform.subarray(8),forward);var dirToCamNorm=d;vec3.normalize(dirToCamNorm);var scale=-vec3.dot(dirToCamNorm,forward);0>scale&&(scale=0),mat4.multiply(this.worldTransform,alignMat,this.worldTransform),mat4.scale(this.worldTransform,[this.scaling[0]*scale,this.scaling[1]*scale,this.scaling[2]*scale])}else mat4.scale(this.worldTransform,this.scaling),mat4.multiply(this.worldTransform,alignMat,this.worldTransform);break;default:mat4.multiply(parentTransform,this.localTransform,this.worldTransform)}for(var i=0;this.children.length>i;++i)this.children[i].UpdateViewDependentData(this.worldTransform)},EveTurretSet.prototype.Initialize=function(){""!=this.geometryResPath&&(this.geometryResource=resMan.GetResource(this.geometryResPath),this.animation.SetGeometryResource(this.geometryResource),this.geometryResource&&this.geometryResource.RegisterNotification(this))},EveTurretSet.prototype.RebuildCachedData=function(){for(var instancedElement=new Tw2VertexElement(Tw2VertexDeclaration.DECL_TEXCOORD,1,device.gl.FLOAT,2),i=0;this.geometryResource.meshes.length>i;++i)this.geometryResource.meshes[i].declaration.elements.push(instancedElement),this.geometryResource.meshes[i].declaration.RebuildHash();switch(this.state){case this.STATE_INACTIVE:this.animation.PlayAnimation("Inactive",!0);break;case this.STATE_IDLE:this.animation.PlayAnimation("Active",!0);break;case this.STATE_FIRING:this.animation.PlayAnimation("Fire",!0);break;case this.STATE_PACKING:this.EnterStateIdle();break;case this.STATE_UNPACKING:this.EnterStateDeactive()}},EveTurretSet.prototype.SetLocalTransform=function(index,localTransform){if(index>=this.turrets.length){var data=new EveTurretData;data.localTransform=localTransform,this.turrets[index]=data}else this.turrets[index].localTransform=localTransform},EveTurretSet.prototype.GetBatches=function(mode,accumulator,perObjectData){if(null==this.geometryResource||!this.display)return!1;if(mode==device.RM_OPAQUE){var transforms=this.animation.GetBoneMatrixes(0);if(0==transforms.length)return!0;mat4.identity(this._perObjectData.perObjectVSData.Get("shipMatrix")),this._perObjectData.perObjectVSData.Get("clipData")[0]=this.bottomClipHeight,this._perObjectData.perObjectVSData.Set("turretPose0",transforms),this._perObjectData.perObjectVSData.Set("turretPose1",transforms),this._perObjectData.perObjectVSData.Set("turretPose2",transforms);for(var i=0;this.turrets.length>i;++i)mat4.transpose(this.turrets[i].worldTransform,this._perObjectData.perObjectVSData.Get(this.worldNames[i]));this._perObjectData.perObjectPSData=perObjectData.perObjectPSData;var batch=new Tw2ForwardingRenderBatch;batch.perObjectData=this._perObjectData,batch.geometryProvider=this,accumulator.Commit(batch)}return this.firingEffect&&this.firingEffect.GetBatches(mode,accumulator,perObjectData),!0},EveTurretSet.prototype.Update=function(dt,parentMatrix){if(this.animation.Update(dt),this.firingEffect){for(var i=0;this.turrets.length>i;++i)this.firingEffect.SetMuzzlePosition(i,[this.turrets[i].localTransform[12],this.turrets[i].localTransform[13],this.turrets[i].localTransform[14]]),this.firingEffect.SetTargetPosition(this.targetPosition);this.firingEffect.Update(dt)}for(var i=0;this.turrets.length>i;++i)mat4.multiply(parentMatrix,this.turrets[i].localTransform,this.turrets[i].worldTransform)},EveTurretSet.prototype.Render=function(batch,overrideEffect){for(var effect=overrideEffect===void 0?this.turretEffect:overrideEffect,index=0,i=0;this.geometryResource.meshes.length>i;++i){var decl=this.geometryResource.meshes[i].declaration;decl.FindUsage(Tw2VertexDeclaration.DECL_TEXCOORD,1).customSetter=function(el){device.gl.disableVertexAttribArray(el.location),device.gl.vertexAttrib2f(el.location,index,index)}}for(;this.turrets.length>index;++index)this.geometryResource.RenderAreas(0,0,1,effect)},EveTurretSet.prototype.EnterStateDeactive=function(){if(this.state!=this.STATE_INACTIVE&&this.state!=this.STATE_PACKING){var self=this;this.animation.StopAllAnimations(),this.animation.PlayAnimation("Pack",!1,function(){self.state=self.STATE_INACTIVE,self.animation.PlayAnimation("Inactive",!0)}),this.state=this.STATE_PACKING}},EveTurretSet.prototype.EnterStateIdle=function(){if(this.state!=this.STATE_IDLE&&this.state!=this.STATE_UNPACKING){var self=this;this.animation.StopAllAnimations(),this.state==this.STATE_FIRING?self.animation.PlayAnimation("Active",!0):this.animation.PlayAnimation("Deploy",!1,function(){self.state=self.STATE_IDLE,self.animation.PlayAnimation("Active",!0)}),this.state=this.STATE_UNPACKING}},EveTurretSet.prototype.EnterStateFiring=function(){if(this.state!=this.STATE_FIRING){var self=this;this.animation.StopAllAnimations(),this.state==this.STATE_INACTIVE?(this.animation.PlayAnimation("Deploy",!1,function(){self.state=self.STATE_FIRING,self.Fire(),self.animation.PlayAnimation("Fire",!0,function(){self.Fire()})}),this.state=this.STATE_UNPACKING):(self.state=self.STATE_FIRING,self.Fire(),self.animation.PlayAnimation("Fire",!0,function(){self.Fire()}))}},EveTurretSet.prototype.ForceStateDeactive=function(){this.state!=this.STATE_INACTIVE&&(this.animation.StopAllAnimations(),this.animation.PlayAnimation("Inactive",!0),this.state=this.STATE_INACTIVE)},EveTurretSet.prototype.ForceStateIdle=function(){this.state!=this.STATE_IDLE&&(this.animation.StopAllAnimations(),this.animation.PlayAnimation("Active",!0),this.state=this.STATE_IDLE)},EveTurretSet.prototype.Fire=function(){this.firingEffect&&this.firingEffect.Fire()},EveSpaceObject.prototype.Initialize=function(){if(this.mesh){this.animation.SetGeometryResource(this.mesh.geometryResource);for(var i=0;this.decals.length>i;++i)this.decals[i].SetParentGeometry(this.mesh.geometryResource)}},EveSpaceObject.prototype.GetBatches=function(mode,accumulator){for(var i=0;this.children.length>i;++i)this.children[i].UpdateViewDependentData(this.transform);mat4.transpose(this.transform,this._perObjectData.perObjectVSData.Get("WorldMat")),this.animation.animations.length&&this._perObjectData.perObjectVSData.Set("JointMat",this.animation.GetBoneMatrixes(0)),null!=this.mesh&&this.mesh.GetBatches(mode,accumulator,this._perObjectData);for(var i=0;this.spriteSets.length>i;++i)this.spriteSets[i].GetBatches(mode,accumulator,this._perObjectData);for(var i=0;this.spotlightSets.length>i;++i)this.spotlightSets[i].GetBatches(mode,accumulator,this._perObjectData);for(var i=0;this.children.length>i;++i)this.children[i].GetBatches(mode,accumulator,this._perObjectData);for(var i=0;this.decals.length>i;++i)this.decals[i].GetBatches(mode,accumulator,this._perObjectData)},EveSpaceObject.prototype.Update=function(dt){for(var i=0;this.spriteSets.length>i;++i)this.spriteSets[i].Update(dt);for(var i=0;this.children.length>i;++i)this.children[i].Update(dt);this.animation.Update(dt)},EveSpaceObject.prototype.GetLocatorCount=function(prefix){for(var count=0,i=0;this.locators.length>i;++i)this.locators[i].name.substr(0,prefix.length)==prefix&&++count;return count},EveSpaceObject.prototype.FindLocatorJointByName=function(name){var model=this.animation.FindModelForMesh(0);if(null!=model)for(var i=0;model.bones.length>i;++i)if(model.bones[i].boneRes.name==name)return model.bones[i].worldTransform;return null},EveSpaceObject.prototype.FindLocatorTransformByName=function(name){for(var i=0;this.locators.length>i;++i)if(this.locators[i].name==name)return this.locators[i].transform;return null},EveSpaceObject.prototype.RenderDebugInfo=function(debugHelper){this.animation.RenderDebugInfo(debugHelper)},EveStation=EveSpaceObject,EveShip.prototype.GetBatches=function(mode,accumulator){this._super.GetBatches.call(this,mode,accumulator),this._perObjectData.perObjectVSData.Get("Shipdata")[0]=this.boosterGain,this._perObjectData.perObjectPSData.Get("Shipdata")[0]=this.boosterGain;for(var i=0;this.turretSets.length>i;++i)this.turretSets[i].GetBatches(mode,accumulator,this._perObjectData);this.boosters&&this.boosters.GetBatches(mode,accumulator,this._perObjectData)},EveShip.prototype.Update=function(dt){this._super.Update.call(this,dt),this.boosters&&(this.boosters.rebuildPending&&this.RebuildBoosterSet(),this.boosters.Update(dt,this.transform));for(var i=0;this.turretSets.length>i;++i){if(this._turretSetsLocatorInfo.length>i&&this._turretSetsLocatorInfo[i].isJoint)for(var j=0;this._turretSetsLocatorInfo[i].locatorTransforms.length>j;++j)this.turretSets[i].SetLocalTransform(j,this._turretSetsLocatorInfo[i].locatorTransforms[j]);this.turretSets[i].Update(dt,this.transform)}},EveShip.prototype.RebuildBoosterSet=function(){if(this.boosters){this.boosters.Clear();for(var prefix="locator_booster",i=0;this.locators.length>i;++i)this.locators[i].name.substr(0,prefix.length)==prefix&&this.boosters.Add(this.locators[i].transform);this.boosters.Rebuild()}},EveShip.prototype.RebuildTurretPositions=function(){this._turretSetsLocatorInfo=[];for(var i=0;this.turretSets.length>i;++i){for(var name=this.turretSets[i].locatorName,locatorCount=this.GetLocatorCount(name),locator=new EveTurretSetLocatorInfo,j=0;locatorCount>j;++j){var locatorName=name+String.fromCharCode("a".charCodeAt(0)+j),locatorTransform=this.FindLocatorJointByName(locatorName);null!=locatorTransform?locator.isJoint=!0:locatorTransform=this.FindLocatorTransformByName(locatorName),null!=locatorTransform&&(this.turretSets[i].SetLocalTransform(j,locatorTransform),locator.locatorTransforms[locator.locatorTransforms.length]=locatorTransform)}this._turretSetsLocatorInfo[this._turretSetsLocatorInfo.length]=locator}},Inherit(EveShip,EveSpaceObject),EveSpaceObjectDecal.prototype.Initialize=function(){""!=this.decalGeometryPath&&(this.decalGeometry=resMan.GetResource(this.decalGeometryPath)),mat4.scale(mat4.transpose(quat4.toMat4(this.rotation,this.decalMatrix)),this.scaling),this.decalMatrix[12]=this.position[0],this.decalMatrix[13]=this.position[1],this.decalMatrix[14]=this.position[2],mat4.inverse(this.decalMatrix,this.invDecalMatrix)},EveSpaceObjectDecal.prototype.SetParentGeometry=function(geometryRes){this.parentGeometry=geometryRes},EveSpaceObjectDecal.prototype.GetBatches=function(mode,accumulator,perObjectData){if(mode==device.RM_DECAL&&this.display&&this.decalEffect&&this.parentGeometry&&this.parentGeometry.IsGood()&&this.decalGeometry&&this.decalGeometry.IsGood()){var batch=new Tw2ForwardingRenderBatch;this._perObjectData.perObjectVSData.Set("worldMatrix",perObjectData.perObjectVSData.Get("WorldMat")),mat4.inverse(this._perObjectData.perObjectVSData.Get("worldMatrix"),this._perObjectData.perObjectVSData.Get("invWorldMatrix")),mat4.transpose(this.decalMatrix,this._perObjectData.perObjectVSData.Get("decalMatrix")),mat4.transpose(this.invDecalMatrix,this._perObjectData.perObjectVSData.Get("invDecalMatrix")),batch.perObjectData=this._perObjectData,batch.geometryProvider=this,batch.renderMode=device.RM_DECAL,accumulator.Commit(batch)}},EveSpaceObjectDecal.prototype.Render=function(batch,overrideEffect){var bkIB=this.parentGeometry.meshes[0].indexes,bkStart=this.parentGeometry.meshes[0].areas[0].start,bkCount=this.parentGeometry.meshes[0].areas[0].count;mat4.set(this.decalMatrix,variableStore._variables.u_DecalMatrix.value),mat4.set(this.invDecalMatrix,variableStore._variables.u_InvDecalMatrix.value),this.parentGeometry.meshes[0].indexes=this.decalGeometry.meshes[this.decalIndex].indexes,this.parentGeometry.meshes[0].areas[0].start=this.decalGeometry.meshes[this.decalIndex].areas[0].start,this.parentGeometry.meshes[0].areas[0].count=this.decalGeometry.meshes[this.decalIndex].areas[0].count,this.parentGeometry.RenderAreas(0,0,1,overrideEffect?overrideEffect:this.decalEffect),this.parentGeometry.meshes[0].indexes=bkIB,this.parentGeometry.meshes[0].areas[0].start=bkStart,this.parentGeometry.meshes[0].areas[0].count=bkCount},EvePlanet.prototype.Create=function(itemID,planetPath,atmospherePath,heightMap1,heightMap2){this.itemID=itemID,this.heightMapResPath1=heightMap1,this.heightMapResPath2=heightMap2,this.highDetail.children=[];var self=this;resMan.GetObject(planetPath,function(obj){self.highDetail.children.unshift(obj),self._MeshLoaded()}),atmospherePath&&resMan.GetObject(atmospherePath,function(obj){self.highDetail.children.push(obj)}),this.hightDirty=!0},EvePlanet.prototype.GetResources=function(obj,visited,result){if(-1==visited.indexOf(obj)){if(visited.push(obj),obj&&obj.doNotPurge!==void 0)return result.push(obj),void 0;for(var prop in obj)"object"==typeof obj[prop]&&this.GetResources(obj[prop],visited,result)}},EvePlanet.prototype._MeshLoaded=function(){this.lockedResources=[],this.GetResources(this.highDetail,[],this.lockedResources);var mainMesh=this.highDetail.children[0].mesh,originalEffect=null;if(mainMesh.transparentAreas.length){originalEffect=mainMesh.transparentAreas[0].effect;var resPath=originalEffect.effectFilePath}else if(mainMesh.opaqueAreas.length){originalEffect=mainMesh.opaqueAreas[0].effect;var resPath=originalEffect.effectFilePath}else var resPath="res:/Graphics/Effect/Managed/Space/Planet/EarthlikePlanet.fx";resPath=resPath.replace(".fx","BlitHeight.fx");for(var param in originalEffect.parameters)this.effectHeight.parameters[param]=originalEffect.parameters[param];for(var i=0;this.highDetail.children[0].children.length>i;++i)if(mainMesh=this.highDetail.children[0].children[i].mesh){if(originalEffect=null,mainMesh.transparentAreas.length)originalEffect=mainMesh.transparentAreas[0].effect;else{if(!mainMesh.opaqueAreas.length)continue;originalEffect=mainMesh.opaqueAreas[0].effect}for(var param in originalEffect.parameters)this.effectHeight.parameters[param]=originalEffect.parameters[param]}var param=new Tw2TextureParameter;param.name="NormalHeight1",param.resourcePath=this.heightMapResPath1,param.Initialize(),this.lockedResources.push(param.textureRes),this.effectHeight.parameters[param.name]=param,param=new Tw2TextureParameter,param.name="NormalHeight2",param.resourcePath=this.heightMapResPath2,param.Initialize(),this.lockedResources.push(param.textureRes),this.effectHeight.parameters[param.name]=param,param=new Tw2FloatParameter,param.name="Random",param.value=this.itemID%100,this.effectHeight.parameters[param.name]=param,param=new Tw2FloatParameter,param.name="TargetTextureHeight",param.value=1024,this.effectHeight.parameters[param.name]=param,this.effectHeight.effectFilePath=resPath,this.effectHeight.Initialize(),this.hightDirty=!0,this.heightMap.Create(2048,1024,!1);for(var i=0;this.lockedResources.length>i;++i)this.lockedResources[i].doNotPurge++,this.lockedResources[i].IsPurged()&&this.lockedResources[i].Reload()},EvePlanet.prototype.GetBatches=function(mode,accumulator){if(this.hightDirty&&!resMan.IsLoading()&&""!=this.heightMapResPath1){this.heightMap.Set(),device.SetStandardStates(device.RM_FULLSCREEN),device.gl.clearColor(0,0,0,0),device.gl.clear(device.gl.COLOR_BUFFER_BIT),device.RenderFullScreenQuad(this.effectHeight),this.heightMap.Unset(),this.hightDirty=!1;for(var i=0;this.lockedResources.length>i;++i)this.lockedResources[i].doNotPurge--;var mainMesh=this.highDetail.children[0].mesh,originalEffect=null;mainMesh.transparentAreas.length?originalEffect=mainMesh.transparentAreas[0].effect:mainMesh.opaqueAreas.length&&(originalEffect=mainMesh.opaqueAreas[0].effect),originalEffect&&(originalEffect.parameters.HeightMap.textureRes=this.heightMap.texture)}this.highDetail.GetBatches(mode,accumulator)},EvePlanet.prototype.Update=function(dt){this.highDetail.Update(dt)},EvePlanet.prototype.UpdateViewDependentData=function(parentTransform){this.highDetail.UpdateViewDependentData(parentTransform)},EveOccluder.prototype.UpdateValue=function(parentTransform,index){if(this.display&&device.alphaBlendBackBuffer){for(var batches=new Tw2BatchAccumulator,i=0;this.sprites.length>i;++i)this.sprites[i].UpdateViewDependentData(parentTransform),this.sprites[i].GetBatches(device.RM_DECAL,batches);variableStore._variables.OccluderValue.value.set([(1<<2*index)/255,(2<<2*index)/255,0,0]),batches.Render();var worldViewProj=mat4.multiply(device.projection,device.view,mat4.create());worldViewProj=mat4.multiply(worldViewProj,this.sprites[0].worldTransform);var center=quat4.create([0,0,0,1]);mat4.multiplyVec4(worldViewProj,center);var x0=.5*(center[0]/center[3]+1),y0=.5*(center[1]/center[3]+1);center[0]=center[1]=.5,center[2]=0,center[3]=1,mat4.multiplyVec4(worldViewProj,center);var x1=.5*(center[0]/center[3]+1),y1=.5*(center[1]/center[3]+1);center[0]=x0,center[1]=y0,center[2]=x1-x0,center[3]=y1-y0,EveOccluder._collectEffect.parameters.OccluderPosition.SetValue(center)}},EveOccluder.prototype.CollectSamples=function(tex,index,total,samples){var effect=EveOccluder._collectEffect,effectRes=effect.GetEffectRes();if(effectRes.IsGood()){effect.parameters.BackBuffer.textureRes=tex,effect.parameters.OccluderIndex.SetValue([index,total,samples]),device.SetStandardStates(device.RM_ADDITIVE),device.gl.bindBuffer(device.gl.ARRAY_BUFFER,EveOccluder._vertexBuffer);for(var pass=0;effect.GetPassCount()>pass;++pass){if(effect.ApplyPass(pass),!EveOccluder._decl.SetDeclaration(effect.GetPassInput(pass),16))return;device.ApplyShadowState(),device.gl.drawArrays(device.gl.TRIANGLES,0,1530)}}},EveLensflare.prototype.Initialize=function(){for(var i=0;this.flares.length>i;++i)if(this.flares[i].mesh)for(var j=0;this.flares[i].mesh.additiveAreas.length>j;++j)if(this.flares[i].mesh.additiveAreas[j].effect){var param=new Tw2Vector4Parameter;param.name="OccluderPosition",this.flares[i]._occluderPosition=param,this.flares[i].mesh.additiveAreas[j].effect.parameters[param.name]=param;var param=new Tw2TextureParameter;param.name="BackBuffer",param.textureRes=EveLensflare.backBuffer,this.flares[i]._backBuffer=param,this.flares[i].mesh.additiveAreas[j].effect.parameters[param.name]=param,this.flares[i].mesh.additiveAreas[j].effect.BindParameters()}},EveLensflare.prototype.MatrixArcFromForward=function(out,v){var norm=vec3.normalize(v,norm);if(mat4.identity(out),!(-.99999>norm[2])){if(norm[2]>.99999)return out[5]=-1,out[10]=-1,void 0;var h=(1+norm[2])/(norm[0]*norm[0]+norm[1]*norm[1]);out[0]=h*norm[1]*norm[1]-norm[2],out[1]=-h*norm[0]*norm[1],out[2]=norm[0],out[4]=out[1],out[5]=h*norm[0]*norm[0]-norm[2],out[6]=norm[1],out[8]=-norm[0],out[9]=-norm[1],out[10]=-norm[2]}},EveLensflare.prototype.PrepareRender=function(){if(this.display){var cameraPos=mat4.multiplyVec3(device.viewInv,vec3.create());if(0==vec3.length(this.position)){var curPos=vec3.negate(cameraPos,vec3.create()),distScale=vec3.length(curPos);distScale=distScale>1.5?1/Math.log(distScale):2.5,vec3.normalize(curPos,this._direction)}else{var invPos=vec3.negate(this.position,vec3.create());vec3.normalize(invPos,this._direction)}var viewDir=mat4.multiplyVec4(device.viewInv,quat4.create([0,0,1,0])),cameraSpacePos=vec3.create();cameraSpacePos[0]=-this.cameraFactor*viewDir[0]+cameraPos[0],cameraSpacePos[1]=-this.cameraFactor*viewDir[1]+cameraPos[1],cameraSpacePos[2]=-this.cameraFactor*viewDir[2]+cameraPos[2];var negDirVec=vec3.negate(this._direction,vec3.create());this.MatrixArcFromForward(this._transform,negDirVec),this._transform[12]=cameraSpacePos[0],this._transform[13]=cameraSpacePos[1],this._transform[14]=cameraSpacePos[2],mat4.scale(mat4.identity(mat4.create()),[this.occlusionIntensity,this.occlusionIntensity,1]),this._directionVar.value[0]=this._direction[0],this._directionVar.value[1]=this._direction[1],this._directionVar.value[2]=this._direction[2],this._directionVar.value[3]=1;for(var i=0;this.flares.length>i;++i)this.flares[i].UpdateViewDependentData(this._transform)}},EveLensflare.prototype.UpdateOccluders=function(){if(this.doOcclusionQueries){if(this.occlusionIntensity=1,this.backgroundOcclusionIntensity=1,!EveLensflare.occluderLevels.texture||EveLensflare.occluderLevels.width<2*this.occluders.length){EveLensflare.occluderLevels.Create(2*this.occluders.length,1,!1);for(var j=0;this.flares.length>j;++j)"_backBuffer"in this.flares[j]&&(this.flares[j]._backBuffer.textureRes=EveLensflare.occluderLevels.texture)}EveLensflare.occluderLevels.Set(),device.SetStandardStates(device.RM_OPAQUE),device.gl.clearColor(0,0,0,1),device.gl.clear(device.gl.COLOR_BUFFER_BIT),EveLensflare.occluderLevels.Unset();var samples=1;device.antialiasing&&(samples=device.gl.getParameter(device.gl.SAMPLES),device.gl.sampleCoverage(1/samples,!1));for(var i=0;this.occluders.length>i;++i)device.SetRenderState(device.RS_COLORWRITEENABLE,8),device.gl.colorMask(!1,!1,!1,!0),device.gl.clearColor(0,0,0,0),device.gl.clear(device.gl.COLOR_BUFFER_BIT),device.antialiasing&&(device.gl.enable(device.gl.SAMPLE_COVERAGE),device.gl.sampleCoverage(.25,!1)),this.occluders[i].UpdateValue(this._transform,i),device.antialiasing&&device.gl.disable(device.gl.SAMPLE_COVERAGE),device.gl.bindTexture(device.gl.TEXTURE_2D,EveLensflare.backBuffer.texture),(EveLensflare.backBuffer.width!=device.viewportWidth||EveLensflare.backBuffer.height!=device.viewportHeight)&&(device.gl.texImage2D(device.gl.TEXTURE_2D,0,device.gl.RGBA,device.viewportWidth,device.viewportHeight,0,device.gl.RGBA,device.gl.UNSIGNED_BYTE,null),EveLensflare.backBuffer.width=device.viewportWidth,EveLensflare.backBuffer.height=device.viewportHeight),device.gl.copyTexImage2D(device.gl.TEXTURE_2D,0,device.alphaBlendBackBuffer?device.gl.RGBA:device.gl.RGB,0,0,EveLensflare.backBuffer.width,EveLensflare.backBuffer.height,0),device.gl.bindTexture(device.gl.TEXTURE_2D,null),EveLensflare.occluderLevels.Set(),this.occluders[i].CollectSamples(EveLensflare.backBuffer,i,EveLensflare.occluderLevels.width/2,samples),EveLensflare.occluderLevels.Unset();device.antialiasing&&device.gl.sampleCoverage(1,!1)}},EveLensflare.prototype.GetBatches=function(mode,accumulator,perObjectData){if(this.display)for(var i=0;this.flares.length>i;++i)this.flares[i].GetBatches(mode,accumulator,perObjectData)},EveSpaceScene.prototype.Initialize=function(){""!=this.envMapResPath&&(this.envMapRes=resMan.GetResource(this.envMapResPath)),""!=this.envMap1ResPath&&(this.envMap1Res=resMan.GetResource(this.envMap1ResPath)),""!=this.envMap2ResPath&&(this.envMap2Res=resMan.GetResource(this.envMap2ResPath)),""!=this.envMap3ResPath&&(this.envMap3Res=resMan.GetResource(this.envMap3ResPath))},EveSpaceScene.prototype.SetEnvMapPath=function(index,path){switch(index){case 0:this.envMap1ResPath=path,this.envMap1Res=""!=this.envMap1ResPath?resMan.GetResource(this.envMap1ResPath):null;break;case 1:this.envMap2ResPath=path,this.envMap2Res=""!=this.envMap2ResPath?resMan.GetResource(this.envMap2ResPath):null;break;case 2:this.envMap3ResPath=path,this.envMap3Res=""!=this.envMap3ResPath?resMan.GetResource(this.envMap3ResPath):null}},EveSpaceScene.prototype.RenderBatches=function(mode){for(var i=0;this.objects.length>i;++i)this.objects[i].GetBatches!==void 0&&this.objects[i].GetBatches(mode,this._batches)},EveSpaceScene.prototype.ApplyPerFrameData=function(){var view=device.view,projection=device.projection,viewInverseTranspose=mat4.inverse(view,mat4.create());this._perFrameVS.Set("ViewInverseTransposeMat",viewInverseTranspose),mat4.transpose(mat4.multiply(projection,view,this._perFrameVS.Get("ViewProjectionMat"))),mat4.transpose(view,this._perFrameVS.Get("ViewMat")),mat4.transpose(projection,this._perFrameVS.Get("ProjectionMat"));var envMapTransform=mat4.scale(quat4.toMat4(this.envMapRotation),this.envMapScaling,mat4.create());
  mat4.transpose(envMapTransform),this._perFrameVS.Set("EnvMapRotationMat",envMapTransform),vec3.normalize(vec3.negate(this.sunDirection,this._perFrameVS.Get("SunData.DirWorld"))),this._perFrameVS.Set("SunData.DiffuseColor",this.sunDiffuseColor);var fogFactors=this._perFrameVS.Get("FogFactors"),distance=this.fogEnd-this.fogStart;1e-5>Math.abs(distance)&&(distance=1e-5);var factor=1/distance;fogFactors[0]=this.fogEnd*factor,fogFactors[1]=factor,fogFactors[2]=this.fogMax;var targetResolution=this._perFrameVS.Get("TargetResolution");targetResolution[0]=device.viewportWidth,targetResolution[1]=device.viewportHeight;var aspectRatio=projection[0]?projection[5]/projection[0]:0,aspectAdjustment=1;aspectRatio>1.6&&(aspectAdjustment=aspectRatio/1.6);var fov=2*Math.atan(aspectAdjustment/projection[5]);targetResolution[3]=fov,targetResolution[2]=targetResolution[3]*aspectRatio;var viewportAdj=this._perFrameVS.Get("ViewportAdjustment");viewportAdj[0]=1,viewportAdj[1]=1,viewportAdj[2]=1,viewportAdj[3]=1,this._perFrameVS.Set("SceneData.AmbientColor",this.ambientColor),this._perFrameVS.Set("SceneData.FogColor",this.fogColor),this._perFramePS.Set("ViewInverseTransposeMat",viewInverseTranspose),mat4.transpose(view,this._perFramePS.Get("ViewMat")),mat4.transpose(projection,this._perFramePS.Get("ProjectionMat")),this._perFramePS.Set("EnvMapRotationMat",envMapTransform),vec3.normalize(vec3.negate(this.sunDirection,this._perFramePS.Get("SunData.DirWorld"))),this._perFramePS.Set("SunData.DiffuseColor",this.sunDiffuseColor),this._perFramePS.Set("SceneData.AmbientColor",this.ambientColor),this._perFramePS.Set("SceneData.FogColor",this.fogColor),this._perFramePS.Get("ShadowCameraRange")[0]=1;var targetResolution=this._perFramePS.Get("TargetResolution");targetResolution[0]=device.viewportWidth,targetResolution[1]=device.viewportHeight,targetResolution[3]=fov,targetResolution[2]=targetResolution[3]*aspectRatio,this._envMapHandle.textureRes=this.envMapRes,this._envMap1Handle.textureRes=this.envMap1Res,this._envMap2Handle.textureRes=this.envMap2Res,this._envMap3Handle.textureRes=this.envMap3Res,device.perFrameVSData=this._perFrameVS,device.perFramePSData=this._perFramePS},EveSpaceScene.prototype.Render=function(){this.ApplyPerFrameData(),this.backgroundRenderingEnabled&&this.backgroundEffect&&(device.SetStandardStates(device.RM_FULLSCREEN),device.RenderCameraSpaceQuad(this.backgroundEffect));for(var id=mat4.identity(mat4.create()),i=0;this.objects.length>i;++i)this.objects[i].UpdateViewDependentData&&this.objects[i].UpdateViewDependentData(id);for(var i=0;this.lensflares.length>i;++i)this.lensflares[i].PrepareRender();this._batches.Clear(),this.RenderBatches(device.RM_OPAQUE),this.RenderBatches(device.RM_DECAL),this.RenderBatches(device.RM_TRANSPARENT),this.RenderBatches(device.RM_ADDITIVE);for(var i=0;this.lensflares.length>i;++i)this.lensflares[i].GetBatches(device.RM_ADDITIVE,this._batches);this._batches.Render();for(var i=0;this.lensflares.length>i;++i)this.lensflares[i].UpdateOccluders();if(this.renderDebugInfo){null==this._debugHelper&&(this._debugHelper=new Tw2DebugRenderer);for(var i=0;this.objects.length>i;++i)this.objects[i].RenderDebugInfo!==void 0&&this.objects[i].RenderDebugInfo(this._debugHelper);this._debugHelper.Render()}},EveSpaceScene.prototype.Update=function(dt){for(var i=0;this.objects.length>i;++i)this.objects[i].Update!==void 0&&this.objects[i].Update(dt)},Tw2PostProcess.prototype.Render=function(){var width=device.viewportWidth,height=device.viewportHeight;if(!(0>=width||0>=height)){if(null==this.texture&&(this.texture=new Tw2TextureRes,this.texture.Attach(device.gl.createTexture())),width!=this.width||height!=this.height){device.gl.bindTexture(device.gl.TEXTURE_2D,this.texture.texture),device.gl.texImage2D(device.gl.TEXTURE_2D,0,device.gl.RGBA,width,height,0,device.gl.RGBA,device.gl.UNSIGNED_BYTE,null),device.gl.bindTexture(device.gl.TEXTURE_2D,null),this.quadRT0.Create(width/4,height/4,!1),this.quadRT1.Create(width/4,height/4,!1),this.width=width,this.height=height;for(var i=0;this.steps.length>i;++i){var step=this.steps[i];for(var name in step.inputs)step.effect.parameters[name].textureRes=step.inputs[name]?step.inputs[name].texture:this.texture;if("g_texelSize"in step.effect.parameters&&"BlitCurrent"in step.inputs){var size=step.effect.parameters.g_texelSize,rt=step.inputs.BlitCurrent;rt?(size.value[0]=1/rt.width,size.value[1]=1/rt.width):(size.value[0]=1/width,size.value[1]=1/width),size.OnValueChanged()}}}device.gl.bindTexture(device.gl.TEXTURE_2D,this.texture.texture),device.gl.copyTexImage2D(device.gl.TEXTURE_2D,0,device.alphaBlendBackBuffer?device.gl.RGBA:device.gl.RGB,0,0,width,height,0),device.gl.bindTexture(device.gl.TEXTURE_2D,null),device.SetStandardStates(device.RM_OPAQUE);for(var i=0;this.steps.length>i;++i){var step=this.steps[i];null!=step.rt?step.rt.Set():(device.gl.bindFramebuffer(device.gl.FRAMEBUFFER,null),device.gl.viewport(0,0,width,height)),device.RenderFullScreenQuad(step.effect)}}},Tw2ParticleElementDeclaration.LIFETIME=0,Tw2ParticleElementDeclaration.POSITION=1,Tw2ParticleElementDeclaration.VELOCITY=2,Tw2ParticleElementDeclaration.MASS=3,Tw2ParticleElementDeclaration.CUSTOM=4,Tw2ParticleElementDeclaration.prototype.GetDimension=function(){switch(this.elementType){case Tw2ParticleElementDeclaration.LIFETIME:return 2;case Tw2ParticleElementDeclaration.POSITION:return 3;case Tw2ParticleElementDeclaration.VELOCITY:return 3;case Tw2ParticleElementDeclaration.MASS:return 1}return this.dimension},Tw2ParticleElementDeclaration.prototype.GetDeclaration=function(){var usage=Tw2VertexDeclaration.DECL_TEXCOORD,usageIndex=8;switch(this.elementType){case Tw2ParticleElementDeclaration.LIFETIME:usage=Tw2VertexDeclaration.DECL_TANGENT;break;case Tw2ParticleElementDeclaration.POSITION:usage=Tw2VertexDeclaration.DECL_POSITION;break;case Tw2ParticleElementDeclaration.VELOCITY:usage=Tw2VertexDeclaration.DECL_NORMAL;break;case Tw2ParticleElementDeclaration.MASS:usage=Tw2VertexDeclaration.DECL_BINORMAL;break;default:usageIndex=this.usageIndex+8}return new Tw2VertexElement(usage,usageIndex,device.gl.FLOAT,this.GetDimension())},Tw2ParticleSystem.prototype.Initialize=function(){this.UpdateElementDeclaration()},Tw2ParticleSystem.prototype.UpdateElementDeclaration=function(){if(this.isValid=!1,this._vb&&(device.gl.deleteBuffer(this._vb),this._vb=null),this._declaration=null,this.aliveCount=0,0!=this.elements.length){this._stdElements=[null,null,null,null],this._elements=[],this.instanceStride=[0,0],this.vertexStride=[0,0],this._declaration=new Tw2VertexDeclaration,this.buffers=[null,null];for(var i=0;this.elements.length>i;++i){var bufferIndex=this.elements[i].usedByGPU?0:1,el=new Tr2ParticleElement(this.elements[i]);if(el.startOffset=this.vertexStride[bufferIndex],el.offset=el.startOffset,this.elements[i].elementType!=Tw2ParticleElementDeclaration.CUSTOM&&(this._stdElements[this.elements[i].elementType]=el),this.vertexStride[bufferIndex]+=el.dimension,this._elements.push(el),0==bufferIndex){var d=this.elements[i].GetDeclaration();d.offset=4*el.startOffset,this._declaration.elements.push(d)}}this._declaration.RebuildHash();for(var i=0;this._elements.length>i;++i){var bufferIndex=this._elements[i].usedByGPU?0:1;this._elements[i].vertexStride=this.vertexStride[bufferIndex]}this.instanceStride[0]=4*this.vertexStride[0],this.instanceStride[1]=4*this.vertexStride[1];for(var i=0;this._elements.length>i;++i){var bufferIndex=this._elements[i].usedByGPU?0:1;this._elements[i].instanceStride=this.instanceStride[bufferIndex]}if(this.buffers=[null,null],this.instanceStride[0]){this.buffers[0]=new Float32Array(this.instanceStride[0]*this.maxParticleCount),this._vb=device.gl.createBuffer(),device.gl.bindBuffer(device.gl.ARRAY_BUFFER,this._vb),device.gl.bufferData(device.gl.ARRAY_BUFFER,4*this.buffers[0].length,device.gl.DYNAMIC_DRAW),device.gl.bindBuffer(device.gl.ARRAY_BUFFER,null),this._ib=device.gl.createBuffer();for(var ib=new Uint16Array(6*this.maxParticleCount),i=0;this.maxParticleCount>i;++i)ib[6*i]=4*i,ib[6*i+1]=4*i+1,ib[6*i+2]=4*i+2,ib[6*i+3]=4*i+2,ib[6*i+4]=4*i+1,ib[6*i+5]=4*i+3;device.gl.bindBuffer(device.gl.ELEMENT_ARRAY_BUFFER,this._ib),device.gl.bufferData(device.gl.ELEMENT_ARRAY_BUFFER,ib,device.gl.STATIC_DRAW),device.gl.bindBuffer(device.gl.ELEMENT_ARRAY_BUFFER,null)}this.instanceStride[1]&&(this.buffers[1]=new Float32Array(this.instanceStride[1]*this.maxParticleCount));for(var i=0;this._elements.length>i;++i){var bufferIndex=this._elements[i].usedByGPU?0:1;this._elements[i].buffer=this.buffers[bufferIndex]}this.requiresSorting&&(this._sortedIndexes=Array(this.maxParticleCount),this._sortedBuffer=new Float32Array(this.instanceStride[0]*this.maxParticleCount)),this.isValid=!0,this.bufferDirty=!0}},Tw2ParticleSystem.prototype.HasElement=function(type){return null!=this._stdElements[type]},Tw2ParticleSystem.prototype.GetElement=function(type){return this._stdElements[type]&&(this._stdElements[type].offset=this._stdElements[type].startOffset),this._stdElements[type]},Tw2ParticleSystem.prototype.BeginSpawnParticle=function(){return!this.isValid||this.aliveCount>=this.maxParticleCount?null:this.aliveCount++},Tw2ParticleSystem.prototype.EndSpawnParticle=function(){for(var index=this.aliveCount-1,j=0;2>j;++j)if(this.buffers[j])for(var original=this.buffers[j].subarray(this.instanceStride[j]*index,this.instanceStride[j]*index+this.vertexStride[j]),i=1;4>i;++i)this.buffers[j].set(original,this.instanceStride[j]*index+i*this.vertexStride[j]);this.bufferDirty=!0},Tw2ParticleSystem.prototype.Update=function(dt){if(dt=Math.min(dt,.1),this.applyAging&&this.HasElement(Tw2ParticleElementDeclaration.LIFETIME)){for(var lifetime=this.GetElement(Tw2ParticleElementDeclaration.LIFETIME),position=this.emitParticleOnDeathEmitter?this.GetElement(Tw2ParticleElementDeclaration.POSITION):null,velocity=this.emitParticleOnDeathEmitter?this.GetElement(Tw2ParticleElementDeclaration.VELOCITY):null,i=0;this.aliveCount>i;++i)if(lifetime.buffer[lifetime.offset]+=dt/lifetime.buffer[lifetime.offset+1],lifetime.buffer[lifetime.offset]>1){if(this.emitParticleOnDeathEmitter&&this.emitParticleOnDeathEmitter.SpawnParticles(position,velocity,1),this.aliveCount--,this.aliveCount>i){for(var j=0;2>j;++j)this.buffers[j]&&this.buffers[j].set(this.buffers[j].subarray(this.instanceStride[j]*this.aliveCount,this.instanceStride[j]*this.aliveCount+this.instanceStride[j]),i*this.instanceStride[j]);--i,this.bufferDirty=!0}}else lifetime.offset+=lifetime.instanceStride,position&&(position.offset+=position.instanceStride),velocity&&(velocity.offset+=velocity.instanceStride);lifetime.dirty=!0}var tmpVec3=vec3.create();if(this.updateSimulation&&this.HasElement(Tw2ParticleElementDeclaration.POSITION)&&this.HasElement(Tw2ParticleElementDeclaration.VELOCITY)){for(var hasForces=this.applyForce&&this.forces.length,i=0;this.forces.length>i;++i)this.forces[i].Update(dt);for(var position=this.GetElement(Tw2ParticleElementDeclaration.POSITION),velocity=this.GetElement(Tw2ParticleElementDeclaration.VELOCITY),mass=hasForces?this.GetElement(Tw2ParticleElementDeclaration.MASS):null,i=0;this.aliveCount>i;++i){if(hasForces){var force=tmpVec3;force[0]=force[1]=force[2]=0;for(var j=0;this.forces.length>j;++j)this.forces[j].ApplyForce(position,velocity,force);mass&&vec3.scale(force,1/mass.buffer[mass.offset]),velocity.buffer[velocity.offset]+=force[0]*dt,velocity.buffer[velocity.offset+1]+=force[1]*dt,velocity.buffer[velocity.offset+2]+=force[2]*dt}position.buffer[position.offset]+=velocity.buffer[velocity.offset]*dt,position.buffer[position.offset+1]+=velocity.buffer[velocity.offset+1]*dt,position.buffer[position.offset+2]+=velocity.buffer[velocity.offset+2]*dt,this.emitParticleDuringLifeEmitter&&this.emitParticleDuringLifeEmitter.SpawnParticles(position,velocity),position.offset+=position.instanceStride,velocity.offset+=velocity.instanceStride,mass&&(mass.offset+=mass.instanceStride)}position.dirty=!0,velocity.dirty=!0}if(this.updateSimulation&&this.constraints.length)for(var i=0;this.constraints.length>i;++i)this.constraints[i].ApplyConstraint(this.buffers,this.instanceStride,this.aliveCount,dt);if(this.updateBoundingBox&&this.GetBoundingBox(this.aabbMin,this.aabbMax),this.emitParticleDuringLifeEmitter&&(!this.HasElement(Tw2ParticleElementDeclaration.POSITION)||!this.HasElement(Tw2ParticleElementDeclaration.VELOCITY))&&this.updateSimulation)for(var position=this.GetElement(Tw2ParticleElementDeclaration.POSITION),velocity=this.GetElement(Tw2ParticleElementDeclaration.VELOCITY),i=0;this.aliveCount>i;++i)this.emitParticleDuringLifeEmitter.SpawnParticles(position,velocity,1),position&&(position.offset+=position.instanceStride),velocity&&(velocity.offset+=velocity.instanceStride);for(var i=0;this._elements.length>i;++i){var el=this._elements[i];if(el.offset=el.startOffset,el.dirty){this.bufferDirty=!0;for(var j=0;this.aliveCount>j;++j){for(var k=1;4>k;++k)for(var m=0;el.dimension>m;++m)el.buffer[el.offset+k*el.vertexStride+m]=el.buffer[el.offset+m];el.offset+=el.instanceStride}el.dirty=!1}}},Tw2ParticleSystem.prototype.GetBoundingBox=function(aabbMin,aabbMax){if(this.aliveCount&&this.HasElement(Tw2ParticleElementDeclaration.POSITION)){var position=this.GetElement(Tw2ParticleElementDeclaration.POSITION);aabbMin[0]=position.buffer[position.offset],aabbMin[1]=position.buffer[position.offset+1],aabbMin[2]=position.buffer[position.offset+2],aabbMax[0]=position.buffer[position.offset],aabbMax[1]=position.buffer[position.offset+1],aabbMax[2]=position.buffer[position.offset+2];for(var i=0;this.aliveCount>i;++i)aabbMin[0]=Math.min(aabbMin[0],position.buffer[position.offset]),aabbMin[1]=Math.min(aabbMin[1],position.buffer[position.offset+1]),aabbMin[2]=Math.min(aabbMin[2],position.buffer[position.offset+2]),aabbMax[0]=Math.max(aabbMax[0],position.buffer[position.offset]),aabbMax[1]=Math.max(aabbMax[1],position.buffer[position.offset+1]),aabbMax[2]=Math.max(aabbMax[2],position.buffer[position.offset+2]),position.offset+=position.instanceStride;return!0}return!1},Tw2ParticleSystem.prototype.Render=function(effect,instanceVB,instanceIB,instanceDecl,instanceStride){if(0==this.aliveCount)return!1;var effectRes=effect.GetEffectRes();if(!effectRes._isGood)return!1;var d=device;if(this.requiresSorting&&this.HasElement(Tw2ParticleElementDeclaration.POSITION)&&this.buffers){for(var eye=device.viewInv,position=this.GetElement(Tw2ParticleElementDeclaration.POSITION),count=this.aliveCount,sortItems=function(a,b){if(a>=count&&b>=count)return b>a?-1:a>b?1:0;if(a>count)return 1;if(b>count)return-1;var o0=position.offset+position.instanceStride*a,o1=position.offset+position.instanceStride*b,d=position.buffer[o0]-eye[12],l0=d*d;d=position.buffer[o0+1]-eye[13],l0+=d*d,d=position.buffer[o0+2]-eye[14],l0+=d*d,d=position.buffer[o1]-eye[12];var l1=d*d;return d=position.buffer[o1+1]-eye[13],l1+=d*d,d=position.buffer[o1+2]-eye[14],l1+=d*d,l1>l0?1:l0>l1?-1:0},i=0;this.maxParticleCount>i;++i)this._sortedIndexes[i]=i;this._sortedIndexes.sort(sortItems);for(var i=0;this.maxParticleCount>i;++i)this._sortedBuffer.set(this.buffers[0].subarray(this.instanceStride[0]*this._sortedIndexes[i],this.instanceStride[0]*(this._sortedIndexes[i]+1)),this.instanceStride[0]*i);d.gl.bindBuffer(d.gl.ARRAY_BUFFER,this._vb),d.gl.bufferSubData(d.gl.ARRAY_BUFFER,0,this._sortedBuffer.subarray(0,this.instanceStride[0]*this.aliveCount)),this.bufferDirty=!1}else this.bufferDirty&&(d.gl.bindBuffer(d.gl.ARRAY_BUFFER,this._vb),d.gl.bufferSubData(d.gl.ARRAY_BUFFER,0,this.buffers[0].subarray(0,this.instanceStride[0]*this.aliveCount)),this.bufferDirty=!1);d.gl.bindBuffer(d.gl.ELEMENT_ARRAY_BUFFER,this._ib);for(var passCount=effect.GetPassCount(),pass=0;passCount>pass;++pass){effect.ApplyPass(pass);var passInput=effect.GetPassInput(pass);d.gl.bindBuffer(d.gl.ARRAY_BUFFER,this._vb),this._declaration.SetPartialDeclaration(passInput,4*this.vertexStride[0]),d.gl.bindBuffer(d.gl.ARRAY_BUFFER,instanceVB),instanceDecl.SetPartialDeclaration(passInput,instanceStride),d.ApplyShadowState(),d.gl.drawElements(d.gl.TRIANGLES,6*this.aliveCount,d.gl.UNSIGNED_SHORT,0)}return!0},Tw2ParticleSystem.prototype.GetMaxInstanceCount=function(){return this.maxParticleCount},Tw2StaticEmitter.prototype.Initialize=function(){""!=this.geometryResourcePath&&(this.geometryResource=resMan.GetResource(this.geometryResourcePath),this.geometryResource.systemMirror=!0,this.geometryResource.RegisterNotification(this)),this._spawned=!1},Tw2StaticEmitter.prototype.RebuildCachedData=function(){this.geometryResource&&this.geometryResource.meshes.length&&(this.geometryResource.meshes[0].bufferData||(this.geometryResource.systemMirror=!0,this.geometryResource.Reload()))},Tw2StaticEmitter.prototype.Update=function(){if(!this._spawned&&this.particleSystem&&this.geometryResource&&this.geometryResource.IsGood()&&this.geometryResource.meshes.length>this.geometryIndex&&this.geometryResource.meshes[this.geometryIndex].bufferData){this._spawned=!0;for(var mesh=this.geometryResource.meshes[this.geometryIndex],elts=this.particleSystem.elements,inputs=Array(elts.length),i=0;elts.length>i;++i){var d=elts[i].GetDeclaration(),input=mesh.declaration.FindUsage(d.usage,d.usageIndex-8);if(null==input)return console.error("Tw2StaticEmitter: ","input geometry res '",this.geometryResource.path,"' mesh lacks (",d.usage,", ",d.usageIndex,") element required by particle system"),void 0;if(input.elements<d.elements)return console.error("Tw2StaticEmitter: ","input geometry res '",this.geometryResource.path,"' mesh elements (",d.usage,", ",d.usageIndex,") does not have required number of components"),void 0;inputs[i]=input.offset/4}for(var vertexCount=4*(mesh.bufferData.length/mesh.declaration.stride),i=0;vertexCount>i;++i){var index=this.particleSystem.BeginSpawnParticle();if(null==index)break;for(var j=0;this.particleSystem._elements.length>j;++j)for(var e=this.particleSystem._elements[j],k=0;e.dimension>k;++k)e.buffer[e.instanceStride*index+e.startOffset+k]=mesh.bufferData[inputs[j]+k+i*mesh.declaration.stride/4];this.particleSystem.EndSpawnParticle()}}},Tw2DynamicEmitter.prototype.Initialize=function(){this.Rebind()},Tw2DynamicEmitter.prototype.Update=function(dt){this.SpawnParticles(null,null,Math.min(dt,.1))},Tw2DynamicEmitter.prototype.Rebind=function(){if(this.isValid=!1,this.particleSystem){for(var i=0;this.generators.length>i;++i)if(!this.generators[i].Bind(this.particleSystem))return;this.isValid=!0}},Tw2DynamicEmitter.prototype.SpawnParticles=function(position,velocity,rateModifier){if(this.isValid){this._accumulatedRate+=this.rate*rateModifier;var count=Math.floor(this._accumulatedRate);this._accumulatedRate-=count;for(var i=0;count>i;++i){var index=this.particleSystem.BeginSpawnParticle();if(null==index)break;for(var j=0;this.generators.length>j;++j)this.generators[j].Generate(position,velocity,index);this.particleSystem.EndSpawnParticle()}}},Tw2RandomUniformAttributeGenerator.prototype.Bind=function(ps){for(var i=0;ps._elements.length>i;++i)if(ps._elements[i].elementType==this.elementType&&(this.elementType!=Tw2ParticleElementDeclaration.CUSTOM||ps._elements[i].customName==this.customName))return this._element=ps._elements[i],!0;return!1},Tw2RandomUniformAttributeGenerator.prototype.Generate=function(position,velocity,index){for(var i=0;this._element.dimension>i;++i)this._element.buffer[this._element.instanceStride*index+this._element.startOffset+i]=this.minRange[i]+Math.random()*(this.maxRange[i]-this.minRange[i])},Tw2SphereShapeAttributeGenerator.prototype.Bind=function(ps){this._position=null,this._velocity=null;for(var i=0;ps._elements.length>i;++i)ps._elements[i].elementType==Tw2ParticleElementDeclaration.POSITION&&this.controlPosition?this._position=ps._elements[i]:ps._elements[i].elementType==Tw2ParticleElementDeclaration.VELOCITY&&this.controlVelocity&&(this._velocity=ps._elements[i]);return!(this.controlPosition&&null==this._position||this.controlVelocity&&null==this._velocity)},Tw2SphereShapeAttributeGenerator.prototype.Generate=function(position,velocity,index){var phi=180*(this.minPhi+Math.random()*(this.maxPhi-this.minPhi))/Math.PI,theta=180*(this.minTheta+Math.random()*(this.maxTheta-this.minTheta))/Math.PI,rv=vec3.create();if(rv[0]=Math.sin(phi)*Math.cos(theta),rv[1]=-Math.cos(phi),rv[2]=Math.sin(phi)*Math.sin(theta),quat4.multiplyVec3(this.rotation,rv),this._velocity){var speed=this.minSpeed+Math.random()*(this.maxSpeed-this.minSpeed),offset=this._velocity.instanceStride*index+this._velocity.startOffset;this._velocity.buffer[offset]=rv[0]*speed,this._velocity.buffer[offset+1]=rv[1]*speed,this._velocity.buffer[offset+2]=rv[2]*speed,velocity&&(this._velocity.buffer[offset]+=velocity.buffer[velocity.startOffset]*this.parentVelocityScale,this._velocity.buffer[offset+1]+=velocity.buffer[velocity.startOffset+1]*this.parentVelocityScale,this._velocity.buffer[offset+2]+=velocity.buffer[velocity.startOffset+2]*this.parentVelocityScale)}if(this._position){vec3.scale(rv,this.minRadius+Math.random()*(this.maxRadius-this.minRadius)),vec3.add(rv,this.position),position&&(rv[0]+=position.buffer[position.startOffset],rv[1]+=position.buffer[position.startOffset+1],rv[2]+=position.buffer[position.startOffset+2]);var offset=this._position.instanceStride*index+this._position.startOffset;this._position.buffer[offset]=rv[0],this._position.buffer[offset+1]=rv[1],this._position.buffer[offset+2]=rv[2]}},Tw2ParticleSpring.prototype.ApplyForce=function(position,velocity,force){force[0]+=(this.position[0]-position.buffer[position.offset])*this.springConstant,force[1]+=(this.position[1]-position.buffer[position.offset+1])*this.springConstant,force[2]+=(this.position[2]-position.buffer[position.offset+2])*this.springConstant},Tw2ParticleSpring.prototype.Update=function(){},Tw2ParticleDragForce.prototype.ApplyForce=function(position,velocity,force){force[0]+=velocity.buffer[velocity.offset]*-this.drag,force[1]+=velocity.buffer[velocity.offset+1]*-this.drag,force[2]+=velocity.buffer[velocity.offset+2]*-this.drag},Tw2ParticleDragForce.prototype.Update=function(){},s_noiseLookup=[],s_permutations=[];var s_globalNoiseTemps=[];InitializeNoise(),Tw2ParticleTurbulenceForce.prototype.ApplyForce=function(position,velocity,force){if(0!=this.noiseLevel){for(var pos_0=position.buffer[position.offset]*this.frequency[0],pos_1=position.buffer[position.offset+1]*this.frequency[1],pos_2=position.buffer[position.offset+2]*this.frequency[2],pos_3=this._time*this.frequency[3],noise=quat4.create(),power=.5,sum=0,frequency=1/this.noiseRatio,i=0;this.noiseLevel>i;++i)AddNoise(pos_0,pos_1,pos_2,pos_3,power,noise),sum+=power,pos_0*=frequency,pos_1*=frequency,pos_2*=frequency,pos_3*=frequency,power*=this.noiseRatio;force[0]+=noise[0]*this.amplitude[0]*sum,force[1]+=noise[1]*this.amplitude[1]*sum,force[2]+=noise[2]*this.amplitude[2]*sum}},Tw2ParticleTurbulenceForce.prototype.Update=function(dt){this._time+=dt},Tw2ParticleDirectForce.prototype.ApplyForce=function(position,velocity,force){force[0]+=this.force[0],force[1]+=this.force[1],force[2]+=this.force[2]},Tw2ParticleDirectForce.prototype.Update=function(){},exports.Tw2RawData=Tw2RawData,exports.Tw2BinaryReader=Tw2BinaryReader,exports.Tw2VertexElement=Tw2VertexElement,exports.Tw2VertexDeclaration=Tw2VertexDeclaration,exports.CompareDeclarationElements=CompareDeclarationElements,exports.Tw2ObjectReader=Tw2ObjectReader,exports.Tw2Resource=Tw2Resource,exports.Inherit=Inherit,exports.Tw2VariableStore=Tw2VariableStore,exports.variableStore=variableStore,exports.Tw2MotherLode=Tw2MotherLode,exports.Tw2LoadingObject=Tw2LoadingObject,exports.Tw2ResMan=Tw2ResMan,exports.resMan=resMan,exports.Tw2PerObjectData=Tw2PerObjectData,exports.Tw2SamplerState=Tw2SamplerState,exports.Tw2FloatParameter=Tw2FloatParameter,exports.Tw2Vector2Parameter=Tw2Vector2Parameter,exports.Tw2Vector3Parameter=Tw2Vector3Parameter,exports.Tw2Vector4Parameter=Tw2Vector4Parameter,exports.Tw2MatrixParameter=Tw2MatrixParameter,exports.Tw2VariableParameter=Tw2VariableParameter,exports.Tw2TextureParameter=Tw2TextureParameter,exports.Tw2TransformParameter=Tw2TransformParameter,exports.Tw2Device=Tw2Device,exports.device=device,exports.Tw2BatchAccumulator=Tw2BatchAccumulator,exports.Tw2RenderBatch=Tw2RenderBatch,exports.Tw2ForwardingRenderBatch=Tw2ForwardingRenderBatch,exports.Tw2GeometryBatch=Tw2GeometryBatch,exports.Tw2GeometryLineBatch=Tw2GeometryLineBatch,exports.Tw2GeometryMeshArea=Tw2GeometryMeshArea,exports.Tw2GeometryMeshBinding=Tw2GeometryMeshBinding,exports.Tw2GeometryModel=Tw2GeometryModel,exports.Tw2GeometrySkeleton=Tw2GeometrySkeleton,exports.Tw2GeometryBone=Tw2GeometryBone,exports.Tw2GeometryAnimation=Tw2GeometryAnimation,exports.Tw2GeometryTrackGroup=Tw2GeometryTrackGroup,exports.Tw2GeometryTransformTrack=Tw2GeometryTransformTrack,exports.Tw2GeometryCurve=Tw2GeometryCurve,exports.Tw2BlendShapeData=Tw2BlendShapeData,exports.Tw2GeometryMesh=Tw2GeometryMesh,exports.Tw2GeometryRes=Tw2GeometryRes,exports.boundsIncludePoint=boundsIncludePoint,exports.Tw2TextureRes=Tw2TextureRes,exports.Tw2EffectRes=Tw2EffectRes,exports.Tw2Effect=Tw2Effect,exports.Tw2MeshArea=Tw2MeshArea,exports.Tw2MeshLineArea=Tw2MeshLineArea,exports.Tw2Mesh=Tw2Mesh,exports.Tw2Track=Tw2Track,exports.Tw2TrackGroup=Tw2TrackGroup,exports.Tw2Animation=Tw2Animation,exports.Tw2Bone=Tw2Bone,exports.Tw2Model=Tw2Model,exports.Tw2AnimationController=Tw2AnimationController,exports.Tw2RenderTarget=Tw2RenderTarget,exports.Tw2InstancedMesh=Tw2InstancedMesh,exports.Tw2InstancedMeshBatch=Tw2InstancedMeshBatch,exports.EveLocator=EveLocator,exports.EveBoosterSet=EveBoosterSet,exports.EveBoosterBatch=EveBoosterBatch,exports.EveSpriteSet=EveSpriteSet,exports.EveSpriteSetBatch=EveSpriteSetBatch,exports.EveSpriteSetItem=EveSpriteSetItem,exports.EveSpotlightSetItem=EveSpotlightSetItem,exports.EveSpotlightSet=EveSpotlightSet,exports.EveSpotlightSetBatch=EveSpotlightSetBatch,exports.EveBasicPerObjectData=EveBasicPerObjectData,exports.EveTransform=EveTransform,exports.EveTurretData=EveTurretData,exports.EveTurretSet=EveTurretSet,exports.EveSpaceObject=EveSpaceObject,exports.EveShip=EveShip,exports.EveTurretSetLocatorInfo=EveTurretSetLocatorInfo,exports.EveSpaceObjectDecal=EveSpaceObjectDecal,exports.EvePlanet=EvePlanet,exports.EveOccluder=EveOccluder,exports.EveLensflare=EveLensflare,exports.EveSpaceScene=EveSpaceScene,exports.Tw2PostProcess=Tw2PostProcess,exports.Tw2ParticleElementDeclaration=Tw2ParticleElementDeclaration,exports.Tr2ParticleElement=Tr2ParticleElement,exports.Tw2ParticleSystem=Tw2ParticleSystem,exports.Tw2StaticEmitter=Tw2StaticEmitter,exports.Tw2DynamicEmitter=Tw2DynamicEmitter,exports.Tw2RandomUniformAttributeGenerator=Tw2RandomUniformAttributeGenerator,exports.Tw2SphereShapeAttributeGenerator=Tw2SphereShapeAttributeGenerator,exports.Tw2ParticleSpring=Tw2ParticleSpring,exports.Tw2ParticleDragForce=Tw2ParticleDragForce,exports.Tw2ParticleTurbulenceForce=Tw2ParticleTurbulenceForce,exports.s_globalNoiseTemps=s_globalNoiseTemps,exports.InitializeNoise=InitializeNoise,exports.AddNoise=AddNoise,exports.Tw2ParticleDirectForce=Tw2ParticleDirectForce})({},function(){return this}());