123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855 |
- /**
- * @author supereggbert / http://www.paulbrunt.co.uk/
- * @author mrdoob / http://mrdoob.com/
- * @author alteredq / http://alteredqualia.com/
- * @author szimek / https://github.com/szimek/
- * @author tschw
- */
- THREE.WebGLRenderer = function ( parameters ) {
- console.log( 'THREE.WebGLRenderer', THREE.REVISION );
- parameters = parameters || {};
- var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
- _context = parameters.context !== undefined ? parameters.context : null,
- _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
- _depth = parameters.depth !== undefined ? parameters.depth : true,
- _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
- _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
- _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
- _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
- var lights = [];
- var opaqueObjects = [];
- var opaqueObjectsLastIndex = - 1;
- var transparentObjects = [];
- var transparentObjectsLastIndex = - 1;
- var morphInfluences = new Float32Array( 8 );
- var sprites = [];
- var lensFlares = [];
- // public properties
- this.domElement = _canvas;
- this.context = null;
- // clearing
- this.autoClear = true;
- this.autoClearColor = true;
- this.autoClearDepth = true;
- this.autoClearStencil = true;
- // scene graph
- this.sortObjects = true;
- // user-defined clipping
- this.clippingPlanes = [];
- this.localClippingEnabled = false;
- // physically based shading
- this.gammaFactor = 2.0; // for backwards compatibility
- this.gammaInput = false;
- this.gammaOutput = false;
- // physical lights
- this.physicallyCorrectLights = false;
- // tone mapping
- this.toneMapping = THREE.LinearToneMapping;
- this.toneMappingExposure = 1.0;
- this.toneMappingWhitePoint = 1.0;
- // morphs
- this.maxMorphTargets = 8;
- this.maxMorphNormals = 4;
- // flags
- this.autoScaleCubemaps = true;
- // internal properties
- var _this = this,
- // internal state cache
- _currentProgram = null,
- _currentRenderTarget = null,
- _currentFramebuffer = null,
- _currentMaterialId = - 1,
- _currentGeometryProgram = '',
- _currentCamera = null,
- _currentScissor = new THREE.Vector4(),
- _currentScissorTest = null,
- _currentViewport = new THREE.Vector4(),
- //
- _usedTextureUnits = 0,
- //
- _clearColor = new THREE.Color( 0x000000 ),
- _clearAlpha = 0,
- _width = _canvas.width,
- _height = _canvas.height,
- _pixelRatio = 1,
- _scissor = new THREE.Vector4( 0, 0, _width, _height ),
- _scissorTest = false,
- _viewport = new THREE.Vector4( 0, 0, _width, _height ),
- // frustum
- _frustum = new THREE.Frustum(),
- // clipping
- _clippingEnabled = false,
- _localClippingEnabled = false,
- _clipRenderingShadows = false,
- _numClippingPlanes = 0,
- _clippingPlanesUniform = {
- type: '4fv', value: null, needsUpdate: false },
- _globalClippingState = null,
- _numGlobalClippingPlanes = 0,
- _matrix3 = new THREE.Matrix3(),
- _sphere = new THREE.Sphere(),
- _plane = new THREE.Plane(),
- // camera matrices cache
- _projScreenMatrix = new THREE.Matrix4(),
- _vector3 = new THREE.Vector3(),
- // light arrays cache
- _lights = {
- hash: '',
- ambient: [ 0, 0, 0 ],
- directional: [],
- directionalShadowMap: [],
- directionalShadowMatrix: [],
- spot: [],
- spotShadowMap: [],
- spotShadowMatrix: [],
- point: [],
- pointShadowMap: [],
- pointShadowMatrix: [],
- hemi: [],
- shadows: []
- },
- // info
- _infoMemory = {
- geometries: 0,
- textures: 0
- },
- _infoRender = {
- calls: 0,
- vertices: 0,
- faces: 0,
- points: 0
- };
- this.info = {
- render: _infoRender,
- memory: _infoMemory,
- programs: null
- };
- // initialize
- var _gl;
- try {
- var attributes = {
- alpha: _alpha,
- depth: _depth,
- stencil: _stencil,
- antialias: _antialias,
- premultipliedAlpha: _premultipliedAlpha,
- preserveDrawingBuffer: _preserveDrawingBuffer
- };
- _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
- if ( _gl === null ) {
- if ( _canvas.getContext( 'webgl' ) !== null ) {
- throw 'Error creating WebGL context with your selected attributes.';
- } else {
- throw 'Error creating WebGL context.';
- }
- }
- // Some experimental-webgl implementations do not have getShaderPrecisionFormat
- if ( _gl.getShaderPrecisionFormat === undefined ) {
- _gl.getShaderPrecisionFormat = function () {
- return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
- };
- }
- _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
- } catch ( error ) {
- console.error( 'THREE.WebGLRenderer: ' + error );
- }
- var extensions = new THREE.WebGLExtensions( _gl );
- extensions.get( 'OES_texture_float' );
- extensions.get( 'OES_texture_float_linear' );
- extensions.get( 'OES_texture_half_float' );
- extensions.get( 'OES_texture_half_float_linear' );
- extensions.get( 'OES_standard_derivatives' );
- extensions.get( 'ANGLE_instanced_arrays' );
- if ( extensions.get( 'OES_element_index_uint' ) ) {
- THREE.BufferGeometry.MaxIndex = 4294967296;
- }
- var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters );
- var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
- var properties = new THREE.WebGLProperties();
- var objects = new THREE.WebGLObjects( _gl, properties, this.info );
- var programCache = new THREE.WebGLPrograms( this, capabilities );
- var lightCache = new THREE.WebGLLights();
- this.info.programs = programCache.programs;
- var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
- var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
- //
- function getTargetPixelRatio() {
- return _currentRenderTarget === null ? _pixelRatio : 1;
- }
- function glClearColor( r, g, b, a ) {
- if ( _premultipliedAlpha === true ) {
- r *= a; g *= a; b *= a;
- }
- state.clearColor( r, g, b, a );
- }
- function setDefaultGLState() {
- state.init();
- state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
- state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
- glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
- }
- function resetGLState() {
- _currentProgram = null;
- _currentCamera = null;
- _currentGeometryProgram = '';
- _currentMaterialId = - 1;
- state.reset();
- }
- setDefaultGLState();
- this.context = _gl;
- this.capabilities = capabilities;
- this.extensions = extensions;
- this.properties = properties;
- this.state = state;
- // shadow map
- var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects );
- this.shadowMap = shadowMap;
- // Plugins
- var spritePlugin = new THREE.SpritePlugin( this, sprites );
- var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
- // API
- this.getContext = function () {
- return _gl;
- };
- this.getContextAttributes = function () {
- return _gl.getContextAttributes();
- };
- this.forceContextLoss = function () {
- extensions.get( 'WEBGL_lose_context' ).loseContext();
- };
- this.getMaxAnisotropy = ( function () {
- var value;
- return function getMaxAnisotropy() {
- if ( value !== undefined ) return value;
- var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
- if ( extension !== null ) {
- value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
- } else {
- value = 0;
- }
- return value;
- };
- } )();
- this.getPrecision = function () {
- return capabilities.precision;
- };
- this.getPixelRatio = function () {
- return _pixelRatio;
- };
- this.setPixelRatio = function ( value ) {
- if ( value === undefined ) return;
- _pixelRatio = value;
- this.setSize( _viewport.z, _viewport.w, false );
- };
- this.getSize = function () {
- return {
- width: _width,
- height: _height
- };
- };
- this.setSize = function ( width, height, updateStyle ) {
- _width = width;
- _height = height;
- _canvas.width = width * _pixelRatio;
- _canvas.height = height * _pixelRatio;
- if ( updateStyle !== false ) {
- _canvas.style.width = width + 'px';
- _canvas.style.height = height + 'px';
- }
- this.setViewport( 0, 0, width, height );
- };
- this.setViewport = function ( x, y, width, height ) {
- state.viewport( _viewport.set( x, y, width, height ) );
- };
- this.setScissor = function ( x, y, width, height ) {
- state.scissor( _scissor.set( x, y, width, height ) );
- };
- this.setScissorTest = function ( boolean ) {
- state.setScissorTest( _scissorTest = boolean );
- };
- // Clearing
- this.getClearColor = function () {
- return _clearColor;
- };
- this.setClearColor = function ( color, alpha ) {
- _clearColor.set( color );
- _clearAlpha = alpha !== undefined ? alpha : 1;
- glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
- };
- this.getClearAlpha = function () {
- return _clearAlpha;
- };
- this.setClearAlpha = function ( alpha ) {
- _clearAlpha = alpha;
- glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
- };
- this.clear = function ( color, depth, stencil ) {
- var bits = 0;
- if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
- if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
- if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
- _gl.clear( bits );
- };
- this.clearColor = function () {
- this.clear( true, false, false );
- };
- this.clearDepth = function () {
- this.clear( false, true, false );
- };
- this.clearStencil = function () {
- this.clear( false, false, true );
- };
- this.clearTarget = function ( renderTarget, color, depth, stencil ) {
- this.setRenderTarget( renderTarget );
- this.clear( color, depth, stencil );
- };
- // Reset
- this.resetGLState = resetGLState;
- this.dispose = function() {
- _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
- };
- // Events
- function onContextLost( event ) {
- event.preventDefault();
- resetGLState();
- setDefaultGLState();
- properties.clear();
- }
- function onTextureDispose( event ) {
- var texture = event.target;
- texture.removeEventListener( 'dispose', onTextureDispose );
- deallocateTexture( texture );
- _infoMemory.textures --;
- }
- function onRenderTargetDispose( event ) {
- var renderTarget = event.target;
- renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
- deallocateRenderTarget( renderTarget );
- _infoMemory.textures --;
- }
- function onMaterialDispose( event ) {
- var material = event.target;
- material.removeEventListener( 'dispose', onMaterialDispose );
- deallocateMaterial( material );
- }
- // Buffer deallocation
- function deallocateTexture( texture ) {
- var textureProperties = properties.get( texture );
- if ( texture.image && textureProperties.__image__webglTextureCube ) {
- // cube texture
- _gl.deleteTexture( textureProperties.__image__webglTextureCube );
- } else {
- // 2D texture
- if ( textureProperties.__webglInit === undefined ) return;
- _gl.deleteTexture( textureProperties.__webglTexture );
- }
- // remove all webgl properties
- properties.delete( texture );
- }
- function deallocateRenderTarget( renderTarget ) {
- var renderTargetProperties = properties.get( renderTarget );
- var textureProperties = properties.get( renderTarget.texture );
- if ( ! renderTarget || textureProperties.__webglTexture === undefined ) return;
- _gl.deleteTexture( textureProperties.__webglTexture );
- if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
- for ( var i = 0; i < 6; i ++ ) {
- _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
- _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
- }
- } else {
- _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
- _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
- }
- properties.delete( renderTarget.texture );
- properties.delete( renderTarget );
- }
- function deallocateMaterial( material ) {
- releaseMaterialProgramReference( material );
- properties.delete( material );
- }
- function releaseMaterialProgramReference( material ) {
- var programInfo = properties.get( material ).program;
- material.program = undefined;
- if ( programInfo !== undefined ) {
- programCache.releaseProgram( programInfo );
- }
- }
- // Buffer rendering
- this.renderBufferImmediate = function ( object, program, material ) {
- state.initAttributes();
- var buffers = properties.get( object );
- if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
- if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
- if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
- if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
- var attributes = program.getAttributes();
- if ( object.hasPositions ) {
- _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
- _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
- state.enableAttribute( attributes.position );
- _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
- }
- if ( object.hasNormals ) {
- _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
- if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === THREE.FlatShading ) {
- for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
- var array = object.normalArray;
- var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
- var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
- var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
- array[ i + 0 ] = nx;
- array[ i + 1 ] = ny;
- array[ i + 2 ] = nz;
- array[ i + 3 ] = nx;
- array[ i + 4 ] = ny;
- array[ i + 5 ] = nz;
- array[ i + 6 ] = nx;
- array[ i + 7 ] = ny;
- array[ i + 8 ] = nz;
- }
- }
- _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
- state.enableAttribute( attributes.normal );
- _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
- }
- if ( object.hasUvs && material.map ) {
- _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
- _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
- state.enableAttribute( attributes.uv );
- _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
- }
- if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
- _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
- _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
- state.enableAttribute( attributes.color );
- _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
- }
- state.disableUnusedAttributes();
- _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
- object.count = 0;
- };
- this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
- setMaterial( material );
- var program = setProgram( camera, fog, material, object );
- var updateBuffers = false;
- var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
- if ( geometryProgram !== _currentGeometryProgram ) {
- _currentGeometryProgram = geometryProgram;
- updateBuffers = true;
- }
- // morph targets
- var morphTargetInfluences = object.morphTargetInfluences;
- if ( morphTargetInfluences !== undefined ) {
- var activeInfluences = [];
- for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
- var influence = morphTargetInfluences[ i ];
- activeInfluences.push( [ influence, i ] );
- }
- activeInfluences.sort( absNumericalSort );
- if ( activeInfluences.length > 8 ) {
- activeInfluences.length = 8;
- }
- var morphAttributes = geometry.morphAttributes;
- for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
- var influence = activeInfluences[ i ];
- morphInfluences[ i ] = influence[ 0 ];
- if ( influence[ 0 ] !== 0 ) {
- var index = influence[ 1 ];
- if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
- if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
- } else {
- if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
- if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
- }
- }
- var uniforms = program.getUniforms();
- if ( uniforms.morphTargetInfluences !== null ) {
- _gl.uniform1fv( uniforms.morphTargetInfluences, morphInfluences );
- }
- updateBuffers = true;
- }
- //
- var index = geometry.index;
- var position = geometry.attributes.position;
- if ( material.wireframe === true ) {
- index = objects.getWireframeAttribute( geometry );
- }
- var renderer;
- if ( index !== null ) {
- renderer = indexedBufferRenderer;
- renderer.setIndex( index );
- } else {
- renderer = bufferRenderer;
- }
- if ( updateBuffers ) {
- setupVertexAttributes( material, program, geometry );
- if ( index !== null ) {
- _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
- }
- }
- //
- var dataStart = 0;
- var dataCount = Infinity;
- if ( index !== null ) {
- dataCount = index.count;
- } else if ( position !== undefined ) {
- dataCount = position.count;
- }
- var rangeStart = geometry.drawRange.start;
- var rangeCount = geometry.drawRange.count;
- var groupStart = group !== null ? group.start : 0;
- var groupCount = group !== null ? group.count : Infinity;
- var drawStart = Math.max( dataStart, rangeStart, groupStart );
- var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
- var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
- //
- if ( object instanceof THREE.Mesh ) {
- if ( material.wireframe === true ) {
- state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
- renderer.setMode( _gl.LINES );
- } else {
- switch ( object.drawMode ) {
- case THREE.TrianglesDrawMode:
- renderer.setMode( _gl.TRIANGLES );
- break;
- case THREE.TriangleStripDrawMode:
- renderer.setMode( _gl.TRIANGLE_STRIP );
- break;
- case THREE.TriangleFanDrawMode:
- renderer.setMode( _gl.TRIANGLE_FAN );
- break;
- }
- }
- } else if ( object instanceof THREE.Line ) {
- var lineWidth = material.linewidth;
- if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
- state.setLineWidth( lineWidth * getTargetPixelRatio() );
- if ( object instanceof THREE.LineSegments ) {
- renderer.setMode( _gl.LINES );
- } else {
- renderer.setMode( _gl.LINE_STRIP );
- }
- } else if ( object instanceof THREE.Points ) {
- renderer.setMode( _gl.POINTS );
- }
- if ( geometry instanceof THREE.InstancedBufferGeometry ) {
- if ( geometry.maxInstancedCount > 0 ) {
- renderer.renderInstances( geometry, drawStart, drawCount );
- }
- } else {
- renderer.render( drawStart, drawCount );
- }
- };
- function setupVertexAttributes( material, program, geometry, startIndex ) {
- var extension;
- if ( geometry instanceof THREE.InstancedBufferGeometry ) {
- extension = extensions.get( 'ANGLE_instanced_arrays' );
- if ( extension === null ) {
- console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
- return;
- }
- }
- if ( startIndex === undefined ) startIndex = 0;
- state.initAttributes();
- var geometryAttributes = geometry.attributes;
- var programAttributes = program.getAttributes();
- var materialDefaultAttributeValues = material.defaultAttributeValues;
- for ( var name in programAttributes ) {
- var programAttribute = programAttributes[ name ];
- if ( programAttribute >= 0 ) {
- var geometryAttribute = geometryAttributes[ name ];
- if ( geometryAttribute !== undefined ) {
- var size = geometryAttribute.itemSize;
- var buffer = objects.getAttributeBuffer( geometryAttribute );
- if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
- var data = geometryAttribute.data;
- var stride = data.stride;
- var offset = geometryAttribute.offset;
- if ( data instanceof THREE.InstancedInterleavedBuffer ) {
- state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
- if ( geometry.maxInstancedCount === undefined ) {
- geometry.maxInstancedCount = data.meshPerAttribute * data.count;
- }
- } else {
- state.enableAttribute( programAttribute );
- }
- _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
- _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
- } else {
- if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
- state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
- if ( geometry.maxInstancedCount === undefined ) {
- geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
- }
- } else {
- state.enableAttribute( programAttribute );
- }
- var type = _gl.FLOAT;
- var normalized = false;
- var array = geometryAttribute.array;
- if ( array instanceof Uint8Array ) {
- type = _gl.UNSIGNED_BYTE;
- normalized = true;
- }
- _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
- _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * array.BYTES_PER_ELEMENT );
- }
- } else if ( materialDefaultAttributeValues !== undefined ) {
- var value = materialDefaultAttributeValues[ name ];
- if ( value !== undefined ) {
- switch ( value.length ) {
- case 2:
- _gl.vertexAttrib2fv( programAttribute, value );
- break;
- case 3:
- _gl.vertexAttrib3fv( programAttribute, value );
- break;
- case 4:
- _gl.vertexAttrib4fv( programAttribute, value );
- break;
- default:
- _gl.vertexAttrib1fv( programAttribute, value );
- }
- }
- }
- }
- }
- state.disableUnusedAttributes();
- }
- // Sorting
- function absNumericalSort( a, b ) {
- return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
- }
- function painterSortStable ( a, b ) {
- if ( a.object.renderOrder !== b.object.renderOrder ) {
- return a.object.renderOrder - b.object.renderOrder;
- } else if ( a.material.id !== b.material.id ) {
- return a.material.id - b.material.id;
- } else if ( a.z !== b.z ) {
- return a.z - b.z;
- } else {
- return a.id - b.id;
- }
- }
- function reversePainterSortStable ( a, b ) {
- if ( a.object.renderOrder !== b.object.renderOrder ) {
- return a.object.renderOrder - b.object.renderOrder;
- } if ( a.z !== b.z ) {
- return b.z - a.z;
- } else {
- return a.id - b.id;
- }
- }
- // Rendering
- this.render = function ( scene, camera, renderTarget, forceClear ) {
- if ( camera instanceof THREE.Camera === false ) {
- console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
- return;
- }
- var fog = scene.fog;
- // reset caching for this frame
- _currentGeometryProgram = '';
- _currentMaterialId = - 1;
- _currentCamera = null;
- // update scene graph
- if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
- // update camera matrices and frustum
- if ( camera.parent === null ) camera.updateMatrixWorld();
- camera.matrixWorldInverse.getInverse( camera.matrixWorld );
- _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
- _frustum.setFromMatrix( _projScreenMatrix );
- lights.length = 0;
- opaqueObjectsLastIndex = - 1;
- transparentObjectsLastIndex = - 1;
- sprites.length = 0;
- lensFlares.length = 0;
- setupGlobalClippingPlanes( this.clippingPlanes, camera );
- projectObject( scene, camera );
- opaqueObjects.length = opaqueObjectsLastIndex + 1;
- transparentObjects.length = transparentObjectsLastIndex + 1;
- if ( _this.sortObjects === true ) {
- opaqueObjects.sort( painterSortStable );
- transparentObjects.sort( reversePainterSortStable );
- }
- //
- if ( _clippingEnabled ) {
- _clipRenderingShadows = true;
- setupClippingPlanes( null );
- }
- setupShadows( lights );
- shadowMap.render( scene, camera );
- setupLights( lights, camera );
- if ( _clippingEnabled ) {
- _clipRenderingShadows = false;
- resetGlobalClippingState();
- }
- //
- _infoRender.calls = 0;
- _infoRender.vertices = 0;
- _infoRender.faces = 0;
- _infoRender.points = 0;
- if ( renderTarget === undefined ) {
- renderTarget = null;
- }
- this.setRenderTarget( renderTarget );
- if ( this.autoClear || forceClear ) {
- this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
- }
- //
- if ( scene.overrideMaterial ) {
- var overrideMaterial = scene.overrideMaterial;
- renderObjects( opaqueObjects, camera, fog, overrideMaterial );
- renderObjects( transparentObjects, camera, fog, overrideMaterial );
- } else {
- // opaque pass (front-to-back order)
- state.setBlending( THREE.NoBlending );
- renderObjects( opaqueObjects, camera, fog );
- // transparent pass (back-to-front order)
- renderObjects( transparentObjects, camera, fog );
- }
- // custom render plugins (post pass)
- spritePlugin.render( scene, camera );
- lensFlarePlugin.render( scene, camera, _currentViewport );
- // Generate mipmap if we're using any kind of mipmap filtering
- if ( renderTarget ) {
- var texture = renderTarget.texture;
- if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
- texture.minFilter !== THREE.NearestFilter &&
- texture.minFilter !== THREE.LinearFilter ) {
- updateRenderTargetMipmap( renderTarget );
- }
- }
- // Ensure depth buffer writing is enabled so it can be cleared on next render
- state.setDepthTest( true );
- state.setDepthWrite( true );
- state.setColorWrite( true );
- // _gl.finish();
- };
- function pushRenderItem( object, geometry, material, z, group ) {
- var array, index;
- // allocate the next position in the appropriate array
- if ( material.transparent ) {
- array = transparentObjects;
- index = ++ transparentObjectsLastIndex;
- } else {
- array = opaqueObjects;
- index = ++ opaqueObjectsLastIndex;
- }
- // recycle existing render item or grow the array
- var renderItem = array[ index ];
- if ( renderItem !== undefined ) {
- renderItem.id = object.id;
- renderItem.object = object;
- renderItem.geometry = geometry;
- renderItem.material = material;
- renderItem.z = _vector3.z;
- renderItem.group = group;
- } else {
- renderItem = {
- id: object.id,
- object: object,
- geometry: geometry,
- material: material,
- z: _vector3.z,
- group: group
- };
- // assert( index === array.length );
- array.push( renderItem );
- }
- }
- function isObjectViewable( object ) {
- var geometry = object.geometry;
- if ( geometry.boundingSphere === null )
- geometry.computeBoundingSphere();
- var sphere = _sphere.
- copy( geometry.boundingSphere ).
- applyMatrix4( object.matrixWorld );
- if ( ! _frustum.intersectsSphere( sphere ) ) return false;
- if ( _numClippingPlanes === 0 ) return true;
- var planes = _this.clippingPlanes,
- center = sphere.center,
- negRad = - sphere.radius,
- i = 0;
- do {
- // out when deeper than radius in the negative halfspace
- if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
- } while ( ++ i !== _numClippingPlanes );
- return true;
- }
- function projectObject( object, camera ) {
- if ( object.visible === false ) return;
- if ( object.layers.test( camera.layers ) ) {
- if ( object instanceof THREE.Light ) {
- lights.push( object );
- } else if ( object instanceof THREE.Sprite ) {
- if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
- sprites.push( object );
- }
- } else if ( object instanceof THREE.LensFlare ) {
- lensFlares.push( object );
- } else if ( object instanceof THREE.ImmediateRenderObject ) {
- if ( _this.sortObjects === true ) {
- _vector3.setFromMatrixPosition( object.matrixWorld );
- _vector3.applyProjection( _projScreenMatrix );
- }
- pushRenderItem( object, null, object.material, _vector3.z, null );
- } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) {
- if ( object instanceof THREE.SkinnedMesh ) {
- object.skeleton.update();
- }
- if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
- var material = object.material;
- if ( material.visible === true ) {
- if ( _this.sortObjects === true ) {
- _vector3.setFromMatrixPosition( object.matrixWorld );
- _vector3.applyProjection( _projScreenMatrix );
- }
- var geometry = objects.update( object );
- if ( material instanceof THREE.MultiMaterial ) {
- var groups = geometry.groups;
- var materials = material.materials;
- for ( var i = 0, l = groups.length; i < l; i ++ ) {
- var group = groups[ i ];
- var groupMaterial = materials[ group.materialIndex ];
- if ( groupMaterial.visible === true ) {
- pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
- }
- }
- } else {
- pushRenderItem( object, geometry, material, _vector3.z, null );
- }
- }
- }
- }
- }
- var children = object.children;
- for ( var i = 0, l = children.length; i < l; i ++ ) {
- projectObject( children[ i ], camera );
- }
- }
- function renderObjects( renderList, camera, fog, overrideMaterial ) {
- for ( var i = 0, l = renderList.length; i < l; i ++ ) {
- var renderItem = renderList[ i ];
- var object = renderItem.object;
- var geometry = renderItem.geometry;
- var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
- var group = renderItem.group;
- object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
- object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
- if ( object instanceof THREE.ImmediateRenderObject ) {
- setMaterial( material );
- var program = setProgram( camera, fog, material, object );
- _currentGeometryProgram = '';
- object.render( function ( object ) {
- _this.renderBufferImmediate( object, program, material );
- } );
- } else {
- _this.renderBufferDirect( camera, fog, geometry, material, object, group );
- }
- }
- }
- function initMaterial( material, fog, object ) {
- var materialProperties = properties.get( material );
- var parameters = programCache.getParameters(
- material, _lights, fog, _numClippingPlanes, object );
- var code = programCache.getProgramCode( material, parameters );
- var program = materialProperties.program;
- var programChange = true;
- if ( program === undefined ) {
- // new material
- material.addEventListener( 'dispose', onMaterialDispose );
- } else if ( program.code !== code ) {
- // changed glsl or parameters
- releaseMaterialProgramReference( material );
- } else if ( parameters.shaderID !== undefined ) {
- // same glsl and uniform list
- return;
- } else {
- // only rebuild uniform list
- programChange = false;
- }
- if ( programChange ) {
- if ( parameters.shaderID ) {
- var shader = THREE.ShaderLib[ parameters.shaderID ];
- materialProperties.__webglShader = {
- name: material.type,
- uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
- vertexShader: shader.vertexShader,
- fragmentShader: shader.fragmentShader
- };
- } else {
- materialProperties.__webglShader = {
- name: material.type,
- uniforms: material.uniforms,
- vertexShader: material.vertexShader,
- fragmentShader: material.fragmentShader
- };
- }
- material.__webglShader = materialProperties.__webglShader;
- program = programCache.acquireProgram( material, parameters, code );
- materialProperties.program = program;
- material.program = program;
- }
- var attributes = program.getAttributes();
- if ( material.morphTargets ) {
- material.numSupportedMorphTargets = 0;
- for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
- if ( attributes[ 'morphTarget' + i ] >= 0 ) {
- material.numSupportedMorphTargets ++;
- }
- }
- }
- if ( material.morphNormals ) {
- material.numSupportedMorphNormals = 0;
- for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
- if ( attributes[ 'morphNormal' + i ] >= 0 ) {
- material.numSupportedMorphNormals ++;
- }
- }
- }
- var uniforms = materialProperties.__webglShader.uniforms;
- if ( ! ( material instanceof THREE.ShaderMaterial ) &&
- ! ( material instanceof THREE.RawShaderMaterial ) ||
- material.clipping === true ) {
- materialProperties.numClippingPlanes = _numClippingPlanes;
- uniforms.clippingPlanes = _clippingPlanesUniform;
- }
- var uniformLocations = materialProperties.program.getUniforms();
- materialProperties.uniformsList = [];
- for ( var u in uniforms ) {
- var location = uniformLocations[ u ];
- if ( location ) {
- materialProperties.uniformsList.push( [ materialProperties.__webglShader.uniforms[ u ], location ] );
- }
- }
- if ( material instanceof THREE.MeshPhongMaterial ||
- material instanceof THREE.MeshLambertMaterial ||
- material instanceof THREE.MeshStandardMaterial ||
- material.lights ) {
- // store the light setup it was created for
- materialProperties.lightsHash = _lights.hash;
- // wire up the material to this renderer's lighting state
- uniforms.ambientLightColor.value = _lights.ambient;
- uniforms.directionalLights.value = _lights.directional;
- uniforms.spotLights.value = _lights.spot;
- uniforms.pointLights.value = _lights.point;
- uniforms.hemisphereLights.value = _lights.hemi;
- uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
- uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
- uniforms.spotShadowMap.value = _lights.spotShadowMap;
- uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
- uniforms.pointShadowMap.value = _lights.pointShadowMap;
- uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
- }
- // detect dynamic uniforms
- materialProperties.hasDynamicUniforms = false;
- for ( var j = 0, jl = materialProperties.uniformsList.length; j < jl; j ++ ) {
- var uniform = materialProperties.uniformsList[ j ][ 0 ];
- if ( uniform.dynamic === true ) {
- materialProperties.hasDynamicUniforms = true;
- break;
- }
- }
- }
- function setMaterial( material ) {
- setMaterialFaces( material );
- if ( material.transparent === true ) {
- state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
- } else {
- state.setBlending( THREE.NoBlending );
- }
- state.setDepthFunc( material.depthFunc );
- state.setDepthTest( material.depthTest );
- state.setDepthWrite( material.depthWrite );
- state.setColorWrite( material.colorWrite );
- state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
- }
- function setMaterialFaces( material ) {
- material.side !== THREE.DoubleSide ? state.enable( _gl.CULL_FACE ) : state.disable( _gl.CULL_FACE );
- state.setFlipSided( material.side === THREE.BackSide );
- }
- function setProgram( camera, fog, material, object ) {
- _usedTextureUnits = 0;
- var materialProperties = properties.get( material );
- if ( _clippingEnabled ) {
- if ( _localClippingEnabled || camera !== _currentCamera ) {
- var useCache =
- camera === _currentCamera &&
- material.id === _currentMaterialId;
- // we might want to call this function with some ClippingGroup
- // object instead of the material, once it becomes feasible
- // (#8465, #8379)
- setClippingState(
- material.clippingPlanes, material.clipShadows,
- camera, materialProperties, useCache );
- }
- if ( materialProperties.numClippingPlanes !== undefined &&
- materialProperties.numClippingPlanes !== _numClippingPlanes ) {
- material.needsUpdate = true;
- }
- }
- if ( materialProperties.program === undefined ) {
- material.needsUpdate = true;
- }
- if ( materialProperties.lightsHash !== undefined &&
- materialProperties.lightsHash !== _lights.hash ) {
- material.needsUpdate = true;
- }
- if ( material.needsUpdate ) {
- initMaterial( material, fog, object );
- material.needsUpdate = false;
- }
- var refreshProgram = false;
- var refreshMaterial = false;
- var refreshLights = false;
- var program = materialProperties.program,
- p_uniforms = program.getUniforms(),
- m_uniforms = materialProperties.__webglShader.uniforms;
- if ( program.id !== _currentProgram ) {
- _gl.useProgram( program.program );
- _currentProgram = program.id;
- refreshProgram = true;
- refreshMaterial = true;
- refreshLights = true;
- }
- if ( material.id !== _currentMaterialId ) {
- _currentMaterialId = material.id;
- refreshMaterial = true;
- }
- if ( refreshProgram || camera !== _currentCamera ) {
- _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
- if ( capabilities.logarithmicDepthBuffer ) {
- _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
- }
- if ( camera !== _currentCamera ) {
- _currentCamera = camera;
- // lighting uniforms depend on the camera so enforce an update
- // now, in case this material supports lights - or later, when
- // the next material that does gets activated:
- refreshMaterial = true; // set to true on material change
- refreshLights = true; // remains set until update done
- }
- // load material specific uniforms
- // (shader material also gets them for the sake of genericity)
- if ( material instanceof THREE.ShaderMaterial ||
- material instanceof THREE.MeshPhongMaterial ||
- material instanceof THREE.MeshStandardMaterial ||
- material.envMap ) {
- if ( p_uniforms.cameraPosition !== undefined ) {
- _vector3.setFromMatrixPosition( camera.matrixWorld );
- _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
- }
- }
- if ( material instanceof THREE.MeshPhongMaterial ||
- material instanceof THREE.MeshLambertMaterial ||
- material instanceof THREE.MeshBasicMaterial ||
- material instanceof THREE.MeshStandardMaterial ||
- material instanceof THREE.ShaderMaterial ||
- material.skinning ) {
- if ( p_uniforms.viewMatrix !== undefined ) {
- _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
- }
- }
- if ( p_uniforms.toneMappingExposure !== undefined ) {
- _gl.uniform1f( p_uniforms.toneMappingExposure, _this.toneMappingExposure );
- }
- if ( p_uniforms.toneMappingWhitePoint !== undefined ) {
- _gl.uniform1f( p_uniforms.toneMappingWhitePoint, _this.toneMappingWhitePoint );
- }
- }
- // skinning uniforms must be set even if material didn't change
- // auto-setting of texture unit for bone texture must go before other textures
- // not sure why, but otherwise weird things happen
- if ( material.skinning ) {
- if ( object.bindMatrix && p_uniforms.bindMatrix !== undefined ) {
- _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
- }
- if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== undefined ) {
- _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
- }
- if ( capabilities.floatVertexTextures && object.skeleton && object.skeleton.useVertexTexture ) {
- if ( p_uniforms.boneTexture !== undefined ) {
- var textureUnit = getTextureUnit();
- _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
- _this.setTexture( object.skeleton.boneTexture, textureUnit );
- }
- if ( p_uniforms.boneTextureWidth !== undefined ) {
- _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
- }
- if ( p_uniforms.boneTextureHeight !== undefined ) {
- _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
- }
- } else if ( object.skeleton && object.skeleton.boneMatrices ) {
- if ( p_uniforms.boneGlobalMatrices !== undefined ) {
- _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
- }
- }
- }
- if ( refreshMaterial ) {
- if ( material instanceof THREE.MeshPhongMaterial ||
- material instanceof THREE.MeshLambertMaterial ||
- material instanceof THREE.MeshStandardMaterial ||
- material.lights ) {
- // the current material requires lighting info
- // note: all lighting uniforms are always set correctly
- // they simply reference the renderer's state for their
- // values
- //
- // use the current material's .needsUpdate flags to set
- // the GL state when required
- markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
- }
- // refresh uniforms common to several materials
- if ( fog && material.fog ) {
- refreshUniformsFog( m_uniforms, fog );
- }
- if ( material instanceof THREE.MeshBasicMaterial ||
- material instanceof THREE.MeshLambertMaterial ||
- material instanceof THREE.MeshPhongMaterial ||
- material instanceof THREE.MeshStandardMaterial ) {
- refreshUniformsCommon( m_uniforms, material );
- }
- // refresh single material specific uniforms
- if ( material instanceof THREE.LineBasicMaterial ) {
- refreshUniformsLine( m_uniforms, material );
- } else if ( material instanceof THREE.LineDashedMaterial ) {
- refreshUniformsLine( m_uniforms, material );
- refreshUniformsDash( m_uniforms, material );
- } else if ( material instanceof THREE.PointsMaterial ) {
- refreshUniformsPoints( m_uniforms, material );
- } else if ( material instanceof THREE.MeshLambertMaterial ) {
- refreshUniformsLambert( m_uniforms, material );
- } else if ( material instanceof THREE.MeshPhongMaterial ) {
- refreshUniformsPhong( m_uniforms, material );
- } else if ( material instanceof THREE.MeshPhysicalMaterial ) {
- refreshUniformsPhysical( m_uniforms, material );
- } else if ( material instanceof THREE.MeshStandardMaterial ) {
- refreshUniformsStandard( m_uniforms, material );
- } else if ( material instanceof THREE.MeshDepthMaterial ) {
- m_uniforms.mNear.value = camera.near;
- m_uniforms.mFar.value = camera.far;
- m_uniforms.opacity.value = material.opacity;
- } else if ( material instanceof THREE.MeshNormalMaterial ) {
- m_uniforms.opacity.value = material.opacity;
- }
- // load common uniforms
- loadUniformsGeneric( materialProperties.uniformsList );
- }
- loadUniformsMatrices( p_uniforms, object );
- if ( p_uniforms.modelMatrix !== undefined ) {
- _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
- }
- if ( materialProperties.hasDynamicUniforms === true ) {
- updateDynamicUniforms( materialProperties.uniformsList, object, camera );
- }
- return program;
- }
- function updateDynamicUniforms ( uniforms, object, camera ) {
- var dynamicUniforms = [];
- for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
- var uniform = uniforms[ j ][ 0 ];
- var onUpdateCallback = uniform.onUpdateCallback;
- if ( onUpdateCallback !== undefined ) {
- onUpdateCallback.bind( uniform )( object, camera );
- dynamicUniforms.push( uniforms[ j ] );
- }
- }
- loadUniformsGeneric( dynamicUniforms );
- }
- // Uniforms (refresh uniforms objects)
- function refreshUniformsCommon ( uniforms, material ) {
- uniforms.opacity.value = material.opacity;
- uniforms.diffuse.value = material.color;
- if ( material.emissive ) {
- uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
- }
- uniforms.map.value = material.map;
- uniforms.specularMap.value = material.specularMap;
- uniforms.alphaMap.value = material.alphaMap;
- if ( material.aoMap ) {
- uniforms.aoMap.value = material.aoMap;
- uniforms.aoMapIntensity.value = material.aoMapIntensity;
- }
- // uv repeat and offset setting priorities
- // 1. color map
- // 2. specular map
- // 3. normal map
- // 4. bump map
- // 5. alpha map
- // 6. emissive map
- var uvScaleMap;
- if ( material.map ) {
- uvScaleMap = material.map;
- } else if ( material.specularMap ) {
- uvScaleMap = material.specularMap;
- } else if ( material.displacementMap ) {
- uvScaleMap = material.displacementMap;
- } else if ( material.normalMap ) {
- uvScaleMap = material.normalMap;
- } else if ( material.bumpMap ) {
- uvScaleMap = material.bumpMap;
- } else if ( material.roughnessMap ) {
- uvScaleMap = material.roughnessMap;
- } else if ( material.metalnessMap ) {
- uvScaleMap = material.metalnessMap;
- } else if ( material.alphaMap ) {
- uvScaleMap = material.alphaMap;
- } else if ( material.emissiveMap ) {
- uvScaleMap = material.emissiveMap;
- }
- if ( uvScaleMap !== undefined ) {
- if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) {
- uvScaleMap = uvScaleMap.texture;
- }
- var offset = uvScaleMap.offset;
- var repeat = uvScaleMap.repeat;
- uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
- }
- uniforms.envMap.value = material.envMap;
- uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
- uniforms.reflectivity.value = material.reflectivity;
- uniforms.refractionRatio.value = material.refractionRatio;
- }
- function refreshUniformsLine ( uniforms, material ) {
- uniforms.diffuse.value = material.color;
- uniforms.opacity.value = material.opacity;
- }
- function refreshUniformsDash ( uniforms, material ) {
- uniforms.dashSize.value = material.dashSize;
- uniforms.totalSize.value = material.dashSize + material.gapSize;
- uniforms.scale.value = material.scale;
- }
- function refreshUniformsPoints ( uniforms, material ) {
- uniforms.diffuse.value = material.color;
- uniforms.opacity.value = material.opacity;
- uniforms.size.value = material.size * _pixelRatio;
- uniforms.scale.value = _canvas.clientHeight * 0.5;
- uniforms.map.value = material.map;
- if ( material.map !== null ) {
- var offset = material.map.offset;
- var repeat = material.map.repeat;
- uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
- }
- }
- function refreshUniformsFog ( uniforms, fog ) {
- uniforms.fogColor.value = fog.color;
- if ( fog instanceof THREE.Fog ) {
- uniforms.fogNear.value = fog.near;
- uniforms.fogFar.value = fog.far;
- } else if ( fog instanceof THREE.FogExp2 ) {
- uniforms.fogDensity.value = fog.density;
- }
- }
- function refreshUniformsLambert ( uniforms, material ) {
- if ( material.lightMap ) {
- uniforms.lightMap.value = material.lightMap;
- uniforms.lightMapIntensity.value = material.lightMapIntensity;
- }
- if ( material.emissiveMap ) {
- uniforms.emissiveMap.value = material.emissiveMap;
- }
- }
- function refreshUniformsPhong ( uniforms, material ) {
- uniforms.specular.value = material.specular;
- uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
- if ( material.lightMap ) {
- uniforms.lightMap.value = material.lightMap;
- uniforms.lightMapIntensity.value = material.lightMapIntensity;
- }
- if ( material.emissiveMap ) {
- uniforms.emissiveMap.value = material.emissiveMap;
- }
- if ( material.bumpMap ) {
- uniforms.bumpMap.value = material.bumpMap;
- uniforms.bumpScale.value = material.bumpScale;
- }
- if ( material.normalMap ) {
- uniforms.normalMap.value = material.normalMap;
- uniforms.normalScale.value.copy( material.normalScale );
- }
- if ( material.displacementMap ) {
- uniforms.displacementMap.value = material.displacementMap;
- uniforms.displacementScale.value = material.displacementScale;
- uniforms.displacementBias.value = material.displacementBias;
- }
- }
- function refreshUniformsStandard ( uniforms, material ) {
- uniforms.roughness.value = material.roughness;
- uniforms.metalness.value = material.metalness;
- if ( material.roughnessMap ) {
- uniforms.roughnessMap.value = material.roughnessMap;
- }
- if ( material.metalnessMap ) {
- uniforms.metalnessMap.value = material.metalnessMap;
- }
- if ( material.lightMap ) {
- uniforms.lightMap.value = material.lightMap;
- uniforms.lightMapIntensity.value = material.lightMapIntensity;
- }
- if ( material.emissiveMap ) {
- uniforms.emissiveMap.value = material.emissiveMap;
- }
- if ( material.bumpMap ) {
- uniforms.bumpMap.value = material.bumpMap;
- uniforms.bumpScale.value = material.bumpScale;
- }
- if ( material.normalMap ) {
- uniforms.normalMap.value = material.normalMap;
- uniforms.normalScale.value.copy( material.normalScale );
- }
- if ( material.displacementMap ) {
- uniforms.displacementMap.value = material.displacementMap;
- uniforms.displacementScale.value = material.displacementScale;
- uniforms.displacementBias.value = material.displacementBias;
- }
- if ( material.envMap ) {
- //uniforms.envMap.value = material.envMap; // part of uniforms common
- uniforms.envMapIntensity.value = material.envMapIntensity;
- }
- }
- function refreshUniformsPhysical ( uniforms, material ) {
- refreshUniformsStandard( uniforms, material );
- }
- // If uniforms are marked as clean, they don't need to be loaded to the GPU.
- function markUniformsLightsNeedsUpdate ( uniforms, value ) {
- uniforms.ambientLightColor.needsUpdate = value;
- uniforms.directionalLights.needsUpdate = value;
- uniforms.pointLights.needsUpdate = value;
- uniforms.spotLights.needsUpdate = value;
- uniforms.hemisphereLights.needsUpdate = value;
- }
- // Uniforms (load to GPU)
- function loadUniformsMatrices ( uniforms, object ) {
- _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object.modelViewMatrix.elements );
- if ( uniforms.normalMatrix ) {
- _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object.normalMatrix.elements );
- }
- }
- function getTextureUnit() {
- var textureUnit = _usedTextureUnits;
- if ( textureUnit >= capabilities.maxTextures ) {
- console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
- }
- _usedTextureUnits += 1;
- return textureUnit;
- }
- function loadUniform( uniform, type, location, value ) {
- var texture, textureUnit;
- if ( type === '1i' ) {
- _gl.uniform1i( location, value );
- } else if ( type === '1f' ) {
- _gl.uniform1f( location, value );
- } else if ( type === '2f' ) {
- _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
- } else if ( type === '3f' ) {
- _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
- } else if ( type === '4f' ) {
- _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
- } else if ( type === '1iv' ) {
- _gl.uniform1iv( location, value );
- } else if ( type === '3iv' ) {
- _gl.uniform3iv( location, value );
- } else if ( type === '1fv' ) {
- _gl.uniform1fv( location, value );
- } else if ( type === '2fv' ) {
- _gl.uniform2fv( location, value );
- } else if ( type === '3fv' ) {
- _gl.uniform3fv( location, value );
- } else if ( type === '4fv' ) {
- _gl.uniform4fv( location, value );
- } else if ( type === 'Matrix2fv' ) {
- _gl.uniformMatrix2fv( location, false, value );
- } else if ( type === 'Matrix3fv' ) {
- _gl.uniformMatrix3fv( location, false, value );
- } else if ( type === 'Matrix4fv' ) {
- _gl.uniformMatrix4fv( location, false, value );
- //
- } else if ( type === 'i' ) {
- // console.warn( 'THREE.WebGLRenderer: Uniform "i" is now "1i".' );
- _gl.uniform1i( location, value );
- } else if ( type === 'f' ) {
- // console.warn( 'THREE.WebGLRenderer: Uniform "f" is now "1f".' );
- _gl.uniform1f( location, value );
- } else if ( type === 'iv1' ) {
- // console.warn( 'THREE.WebGLRenderer: Uniform "iv1" is now "1iv".' );
- _gl.uniform1iv( location, value );
- } else if ( type === 'iv' ) {
- // console.warn( 'THREE.WebGLRenderer: Uniform "iv" is now "3iv".' );
- _gl.uniform3iv( location, value );
- } else if ( type === 'fv1' ) {
- // console.warn( 'THREE.WebGLRenderer: Uniform "fv1" is now "1fv".' );
- _gl.uniform1fv( location, value );
- } else if ( type === 'fv' ) {
- // console.warn( 'THREE.WebGLRenderer: Uniform "fv" is now "3fv".' );
- _gl.uniform3fv( location, value );
- } else if ( type === 'v2' ) {
- // single THREE.Vector2
- _gl.uniform2f( location, value.x, value.y );
- } else if ( type === 'v3' ) {
- // single THREE.Vector3
- _gl.uniform3f( location, value.x, value.y, value.z );
- } else if ( type === 'v4' ) {
- // single THREE.Vector4
- _gl.uniform4f( location, value.x, value.y, value.z, value.w );
- } else if ( type === 'c' ) {
- // single THREE.Color
- _gl.uniform3f( location, value.r, value.g, value.b );
- } else if ( type === 's' ) {
- // TODO: Optimize this
- var properties = uniform.properties;
- for ( var name in properties ) {
- var property = properties[ name ];
- var locationProperty = location[ name ];
- var valueProperty = value[ name ];
- loadUniform( property, property.type, locationProperty, valueProperty );
- }
- } else if ( type === 'sa' ) {
- // TODO: Optimize this
- var properties = uniform.properties;
- for ( var i = 0, l = value.length; i < l; i ++ ) {
- for ( var name in properties ) {
- var property = properties[ name ];
- var locationProperty = location[ i ][ name ];
- var valueProperty = value[ i ][ name ];
- loadUniform( property, property.type, locationProperty, valueProperty );
- }
- }
- } else if ( type === 'v2v' ) {
- // array of THREE.Vector2
- if ( uniform._array === undefined ) {
- uniform._array = new Float32Array( 2 * value.length );
- }
- for ( var i = 0, i2 = 0, il = value.length; i < il; i ++, i2 += 2 ) {
- uniform._array[ i2 + 0 ] = value[ i ].x;
- uniform._array[ i2 + 1 ] = value[ i ].y;
- }
- _gl.uniform2fv( location, uniform._array );
- } else if ( type === 'v3v' ) {
- // array of THREE.Vector3
- if ( uniform._array === undefined ) {
- uniform._array = new Float32Array( 3 * value.length );
- }
- for ( var i = 0, i3 = 0, il = value.length; i < il; i ++, i3 += 3 ) {
- uniform._array[ i3 + 0 ] = value[ i ].x;
- uniform._array[ i3 + 1 ] = value[ i ].y;
- uniform._array[ i3 + 2 ] = value[ i ].z;
- }
- _gl.uniform3fv( location, uniform._array );
- } else if ( type === 'v4v' ) {
- // array of THREE.Vector4
- if ( uniform._array === undefined ) {
- uniform._array = new Float32Array( 4 * value.length );
- }
- for ( var i = 0, i4 = 0, il = value.length; i < il; i ++, i4 += 4 ) {
- uniform._array[ i4 + 0 ] = value[ i ].x;
- uniform._array[ i4 + 1 ] = value[ i ].y;
- uniform._array[ i4 + 2 ] = value[ i ].z;
- uniform._array[ i4 + 3 ] = value[ i ].w;
- }
- _gl.uniform4fv( location, uniform._array );
- } else if ( type === 'm2' ) {
- // single THREE.Matrix2
- _gl.uniformMatrix2fv( location, false, value.elements );
- } else if ( type === 'm3' ) {
- // single THREE.Matrix3
- _gl.uniformMatrix3fv( location, false, value.elements );
- } else if ( type === 'm3v' ) {
- // array of THREE.Matrix3
- if ( uniform._array === undefined ) {
- uniform._array = new Float32Array( 9 * value.length );
- }
- for ( var i = 0, il = value.length; i < il; i ++ ) {
- value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
- }
- _gl.uniformMatrix3fv( location, false, uniform._array );
- } else if ( type === 'm4' ) {
- // single THREE.Matrix4
- _gl.uniformMatrix4fv( location, false, value.elements );
- } else if ( type === 'm4v' ) {
- // array of THREE.Matrix4
- if ( uniform._array === undefined ) {
- uniform._array = new Float32Array( 16 * value.length );
- }
- for ( var i = 0, il = value.length; i < il; i ++ ) {
- value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
- }
- _gl.uniformMatrix4fv( location, false, uniform._array );
- } else if ( type === 't' ) {
- // single THREE.Texture (2d or cube)
- texture = value;
- textureUnit = getTextureUnit();
- _gl.uniform1i( location, textureUnit );
- if ( ! texture ) return;
- if ( texture instanceof THREE.CubeTexture ||
- ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
- // CompressedTexture can have Array in image :/
- setCubeTexture( texture, textureUnit );
- } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
- setCubeTextureDynamic( texture.texture, textureUnit );
- } else if ( texture instanceof THREE.WebGLRenderTarget ) {
- _this.setTexture( texture.texture, textureUnit );
- } else {
- _this.setTexture( texture, textureUnit );
- }
- } else if ( type === 'tv' ) {
- // array of THREE.Texture (2d or cube)
- if ( uniform._array === undefined ) {
- uniform._array = [];
- }
- for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
- uniform._array[ i ] = getTextureUnit();
- }
- _gl.uniform1iv( location, uniform._array );
- for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
- texture = uniform.value[ i ];
- textureUnit = uniform._array[ i ];
- if ( ! texture ) continue;
- if ( texture instanceof THREE.CubeTexture ||
- ( texture.image instanceof Array && texture.image.length === 6 ) ) {
- // CompressedTexture can have Array in image :/
- setCubeTexture( texture, textureUnit );
- } else if ( texture instanceof THREE.WebGLRenderTarget ) {
- _this.setTexture( texture.texture, textureUnit );
- } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
- setCubeTextureDynamic( texture.texture, textureUnit );
- } else {
- _this.setTexture( texture, textureUnit );
- }
- }
- } else {
- console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
- }
- }
- function loadUniformsGeneric( uniforms ) {
- for ( var i = 0, l = uniforms.length; i < l; i ++ ) {
- var uniform = uniforms[ i ][ 0 ];
- // needsUpdate property is not added to all uniforms.
- if ( uniform.needsUpdate === false ) continue;
- var type = uniform.type;
- var location = uniforms[ i ][ 1 ];
- var value = uniform.value;
- loadUniform( uniform, type, location, value );
- }
- }
- function setupShadows ( lights ) {
- var lightShadowsLength = 0;
- for ( var i = 0, l = lights.length; i < l; i ++ ) {
- var light = lights[ i ];
- if ( light.castShadow ) {
- _lights.shadows[ lightShadowsLength ++ ] = light;
- }
- }
- _lights.shadows.length = lightShadowsLength;
- }
- function setupLights ( lights, camera ) {
- var l, ll, light,
- r = 0, g = 0, b = 0,
- color,
- intensity,
- distance,
- viewMatrix = camera.matrixWorldInverse,
- directionalLength = 0,
- pointLength = 0,
- spotLength = 0,
- hemiLength = 0;
- for ( l = 0, ll = lights.length; l < ll; l ++ ) {
- light = lights[ l ];
- color = light.color;
- intensity = light.intensity;
- distance = light.distance;
- if ( light instanceof THREE.AmbientLight ) {
- r += color.r * intensity;
- g += color.g * intensity;
- b += color.b * intensity;
- } else if ( light instanceof THREE.DirectionalLight ) {
- var uniforms = lightCache.get( light );
- uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
- uniforms.direction.setFromMatrixPosition( light.matrixWorld );
- _vector3.setFromMatrixPosition( light.target.matrixWorld );
- uniforms.direction.sub( _vector3 );
- uniforms.direction.transformDirection( viewMatrix );
- uniforms.shadow = light.castShadow;
- if ( light.castShadow ) {
- uniforms.shadowBias = light.shadow.bias;
- uniforms.shadowRadius = light.shadow.radius;
- uniforms.shadowMapSize = light.shadow.mapSize;
- }
- _lights.directionalShadowMap[ directionalLength ] = light.shadow.map;
- _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
- _lights.directional[ directionalLength ++ ] = uniforms;
- } else if ( light instanceof THREE.SpotLight ) {
- var uniforms = lightCache.get( light );
- uniforms.position.setFromMatrixPosition( light.matrixWorld );
- uniforms.position.applyMatrix4( viewMatrix );
- uniforms.color.copy( color ).multiplyScalar( intensity );
- uniforms.distance = distance;
- uniforms.direction.setFromMatrixPosition( light.matrixWorld );
- _vector3.setFromMatrixPosition( light.target.matrixWorld );
- uniforms.direction.sub( _vector3 );
- uniforms.direction.transformDirection( viewMatrix );
- uniforms.coneCos = Math.cos( light.angle );
- uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
- uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
- uniforms.shadow = light.castShadow;
- if ( light.castShadow ) {
- uniforms.shadowBias = light.shadow.bias;
- uniforms.shadowRadius = light.shadow.radius;
- uniforms.shadowMapSize = light.shadow.mapSize;
- }
- _lights.spotShadowMap[ spotLength ] = light.shadow.map;
- _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
- _lights.spot[ spotLength ++ ] = uniforms;
- } else if ( light instanceof THREE.PointLight ) {
- var uniforms = lightCache.get( light );
- uniforms.position.setFromMatrixPosition( light.matrixWorld );
- uniforms.position.applyMatrix4( viewMatrix );
- uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
- uniforms.distance = light.distance;
- uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
- uniforms.shadow = light.castShadow;
- if ( light.castShadow ) {
- uniforms.shadowBias = light.shadow.bias;
- uniforms.shadowRadius = light.shadow.radius;
- uniforms.shadowMapSize = light.shadow.mapSize;
- }
- _lights.pointShadowMap[ pointLength ] = light.shadow.map;
- if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
- _lights.pointShadowMatrix[ pointLength ] = new THREE.Matrix4();
- }
- // for point lights we set the shadow matrix to be a translation-only matrix
- // equal to inverse of the light's position
- _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
- _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
- _lights.point[ pointLength ++ ] = uniforms;
- } else if ( light instanceof THREE.HemisphereLight ) {
- var uniforms = lightCache.get( light );
- uniforms.direction.setFromMatrixPosition( light.matrixWorld );
- uniforms.direction.transformDirection( viewMatrix );
- uniforms.direction.normalize();
- uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
- uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
- _lights.hemi[ hemiLength ++ ] = uniforms;
- }
- }
- _lights.ambient[ 0 ] = r;
- _lights.ambient[ 1 ] = g;
- _lights.ambient[ 2 ] = b;
- _lights.directional.length = directionalLength;
- _lights.spot.length = spotLength;
- _lights.point.length = pointLength;
- _lights.hemi.length = hemiLength;
- _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length;
- }
- function setupGlobalClippingPlanes( planes, camera ) {
- _clippingEnabled =
- _this.clippingPlanes.length !== 0 ||
- _this.localClippingEnabled ||
- // enable state of previous frame - the clipping code has to
- // run another frame in order to reset the state:
- _numGlobalClippingPlanes !== 0 ||
- _localClippingEnabled;
- _localClippingEnabled = _this.localClippingEnabled;
- _globalClippingState = setupClippingPlanes( planes, camera, 0 );
- _numGlobalClippingPlanes = planes !== null ? planes.length : 0;
- }
- function setupClippingPlanes( planes, camera, dstOffset, skipTransform ) {
- var nPlanes = planes !== null ? planes.length : 0,
- dstArray = null;
- if ( nPlanes !== 0 ) {
- dstArray = _clippingPlanesUniform.value;
- if ( skipTransform !== true || dstArray === null ) {
- var flatSize = dstOffset + nPlanes * 4,
- viewMatrix = camera.matrixWorldInverse,
- viewNormalMatrix = _matrix3.getNormalMatrix( viewMatrix );
- if ( dstArray === null || dstArray.length < flatSize ) {
- dstArray = new Float32Array( flatSize );
- }
- for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
- var plane = _plane.copy( planes[ i ] ).
- applyMatrix4( viewMatrix, viewNormalMatrix );
- plane.normal.toArray( dstArray, i4 );
- dstArray[ i4 + 3 ] = plane.constant;
- }
- }
- _clippingPlanesUniform.value = dstArray;
- _clippingPlanesUniform.needsUpdate = true;
- }
- _numClippingPlanes = nPlanes;
- return dstArray;
- }
- function resetGlobalClippingState() {
- if ( _clippingPlanesUniform.value !== _globalClippingState ) {
- _clippingPlanesUniform.value = _globalClippingState;
- _clippingPlanesUniform.needsUpdate = _numGlobalClippingPlanes > 0;
- }
- _numClippingPlanes = _numGlobalClippingPlanes;
- }
- function setClippingState( planes, clipShadows, camera, cache, fromCache ) {
- if ( ! _localClippingEnabled ||
- planes === null || planes.length === 0 ||
- _clipRenderingShadows && ! clipShadows ) {
- // there's no local clipping
- if ( _clipRenderingShadows ) {
- // there's no global clipping
- setupClippingPlanes( null );
- } else {
- resetGlobalClippingState();
- }
- } else {
- var nGlobal = _clipRenderingShadows ? 0 : _numGlobalClippingPlanes,
- lGlobal = nGlobal * 4,
- dstArray = cache.clippingState || null;
- _clippingPlanesUniform.value = dstArray; // ensure unique state
- dstArray = setupClippingPlanes(
- planes, camera, lGlobal, fromCache );
- for ( var i = 0; i !== lGlobal; ++ i ) {
- dstArray[ i ] = _globalClippingState[ i ];
- }
- cache.clippingState = dstArray;
- _numClippingPlanes += nGlobal;
- }
- }
- // GL state setting
- this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
- if ( cullFace === THREE.CullFaceNone ) {
- state.disable( _gl.CULL_FACE );
- } else {
- if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
- _gl.frontFace( _gl.CW );
- } else {
- _gl.frontFace( _gl.CCW );
- }
- if ( cullFace === THREE.CullFaceBack ) {
- _gl.cullFace( _gl.BACK );
- } else if ( cullFace === THREE.CullFaceFront ) {
- _gl.cullFace( _gl.FRONT );
- } else {
- _gl.cullFace( _gl.FRONT_AND_BACK );
- }
- state.enable( _gl.CULL_FACE );
- }
- };
- // Textures
- function setTextureParameters ( textureType, texture, isPowerOfTwoImage ) {
- var extension;
- if ( isPowerOfTwoImage ) {
- _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
- _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
- _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
- _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
- } else {
- _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
- _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
- if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
- console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
- }
- _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
- _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
- if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
- console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
- }
- }
- extension = extensions.get( 'EXT_texture_filter_anisotropic' );
- if ( extension ) {
- if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
- if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
- if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
- _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
- properties.get( texture ).__currentAnisotropy = texture.anisotropy;
- }
- }
- }
- function uploadTexture( textureProperties, texture, slot ) {
- if ( textureProperties.__webglInit === undefined ) {
- textureProperties.__webglInit = true;
- texture.addEventListener( 'dispose', onTextureDispose );
- textureProperties.__webglTexture = _gl.createTexture();
- _infoMemory.textures ++;
- }
- state.activeTexture( _gl.TEXTURE0 + slot );
- state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
- _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
- _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
- _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
- var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
- if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
- image = makePowerOfTwo( image );
- }
- var isPowerOfTwoImage = isPowerOfTwo( image ),
- glFormat = paramThreeToGL( texture.format ),
- glType = paramThreeToGL( texture.type );
- setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
- var mipmap, mipmaps = texture.mipmaps;
- if ( texture instanceof THREE.DataTexture ) {
- // use manually created mipmaps if available
- // if there are no manual mipmaps
- // set 0 level mipmap and then use GL to generate other mipmap levels
- if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
- for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
- mipmap = mipmaps[ i ];
- state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
- }
- texture.generateMipmaps = false;
- } else {
- state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
- }
- } else if ( texture instanceof THREE.CompressedTexture ) {
- for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
- mipmap = mipmaps[ i ];
- if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
- if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
- state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
- } else {
- console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
- }
- } else {
- state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
- }
- }
- } else {
- // regular Texture (image, video, canvas)
- // use manually created mipmaps if available
- // if there are no manual mipmaps
- // set 0 level mipmap and then use GL to generate other mipmap levels
- if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
- for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
- mipmap = mipmaps[ i ];
- state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
- }
- texture.generateMipmaps = false;
- } else {
- state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
- }
- }
- if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
- textureProperties.__version = texture.version;
- if ( texture.onUpdate ) texture.onUpdate( texture );
- }
- this.setTexture = function ( texture, slot ) {
- var textureProperties = properties.get( texture );
- if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
- var image = texture.image;
- if ( image === undefined ) {
- console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
- return;
- }
- if ( image.complete === false ) {
- console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
- return;
- }
- uploadTexture( textureProperties, texture, slot );
- return;
- }
- state.activeTexture( _gl.TEXTURE0 + slot );
- state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
- };
- function clampToMaxSize ( image, maxSize ) {
- if ( image.width > maxSize || image.height > maxSize ) {
- // Warning: Scaling through the canvas will only work with images that use
- // premultiplied alpha.
- var scale = maxSize / Math.max( image.width, image.height );
- var canvas = document.createElement( 'canvas' );
- canvas.width = Math.floor( image.width * scale );
- canvas.height = Math.floor( image.height * scale );
- var context = canvas.getContext( '2d' );
- context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
- console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
- return canvas;
- }
- return image;
- }
- function isPowerOfTwo( image ) {
- return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
- }
- function textureNeedsPowerOfTwo( texture ) {
- if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true;
- if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true;
- return false;
- }
- function makePowerOfTwo( image ) {
- if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
- var canvas = document.createElement( 'canvas' );
- canvas.width = THREE.Math.nearestPowerOfTwo( image.width );
- canvas.height = THREE.Math.nearestPowerOfTwo( image.height );
- var context = canvas.getContext( '2d' );
- context.drawImage( image, 0, 0, canvas.width, canvas.height );
- console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
- return canvas;
- }
- return image;
- }
- function setCubeTexture ( texture, slot ) {
- var textureProperties = properties.get( texture );
- if ( texture.image.length === 6 ) {
- if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
- if ( ! textureProperties.__image__webglTextureCube ) {
- texture.addEventListener( 'dispose', onTextureDispose );
- textureProperties.__image__webglTextureCube = _gl.createTexture();
- _infoMemory.textures ++;
- }
- state.activeTexture( _gl.TEXTURE0 + slot );
- state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
- _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
- var isCompressed = texture instanceof THREE.CompressedTexture;
- var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
- var cubeImage = [];
- for ( var i = 0; i < 6; i ++ ) {
- if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
- cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
- } else {
- cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
- }
- }
- var image = cubeImage[ 0 ],
- isPowerOfTwoImage = isPowerOfTwo( image ),
- glFormat = paramThreeToGL( texture.format ),
- glType = paramThreeToGL( texture.type );
- setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
- for ( var i = 0; i < 6; i ++ ) {
- if ( ! isCompressed ) {
- if ( isDataTexture ) {
- state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
- } else {
- state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
- }
- } else {
- var mipmap, mipmaps = cubeImage[ i ].mipmaps;
- for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
- mipmap = mipmaps[ j ];
- if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
- if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
- state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
- } else {
- console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
- }
- } else {
- state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
- }
- }
- }
- }
- if ( texture.generateMipmaps && isPowerOfTwoImage ) {
- _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
- }
- textureProperties.__version = texture.version;
- if ( texture.onUpdate ) texture.onUpdate( texture );
- } else {
- state.activeTexture( _gl.TEXTURE0 + slot );
- state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
- }
- }
- }
- function setCubeTextureDynamic ( texture, slot ) {
- state.activeTexture( _gl.TEXTURE0 + slot );
- state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
- }
- // Render targets
- // Setup storage for target texture and bind it to correct framebuffer
- function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) {
- var glFormat = paramThreeToGL( renderTarget.texture.format );
- var glType = paramThreeToGL( renderTarget.texture.type );
- state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
- _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
- _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
- _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
- }
- // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
- function setupRenderBufferStorage ( renderbuffer, renderTarget ) {
- _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
- if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
- _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
- _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
- } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
- _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
- _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
- } else {
- // FIXME: We don't support !depth !stencil
- _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
- }
- _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
- }
- // Setup GL resources for a non-texture depth buffer
- function setupDepthRenderbuffer( renderTarget ) {
- var renderTargetProperties = properties.get( renderTarget );
- var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
- if ( isCube ) {
- renderTargetProperties.__webglDepthbuffer = [];
- for ( var i = 0; i < 6; i ++ ) {
- _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
- renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
- setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
- }
- } else {
- _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
- renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
- setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
- }
- _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
- }
- // Set up GL resources for the render target
- function setupRenderTarget( renderTarget ) {
- var renderTargetProperties = properties.get( renderTarget );
- var textureProperties = properties.get( renderTarget.texture );
- renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
- textureProperties.__webglTexture = _gl.createTexture();
- _infoMemory.textures ++;
- var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
- var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height );
- // Setup framebuffer
- if ( isCube ) {
- renderTargetProperties.__webglFramebuffer = [];
- for ( var i = 0; i < 6; i ++ ) {
- renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
- }
- } else {
- renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
- }
- // Setup color buffer
- if ( isCube ) {
- state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
- setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
- for ( var i = 0; i < 6; i ++ ) {
- setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
- }
- if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
- state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
- } else {
- state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
- setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
- setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
- if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
- state.bindTexture( _gl.TEXTURE_2D, null );
- }
- // Setup depth and stencil buffers
- if ( renderTarget.depthBuffer ) {
- setupDepthRenderbuffer( renderTarget );
- }
- }
- this.getCurrentRenderTarget = function() {
- return _currentRenderTarget;
- }
- this.setRenderTarget = function ( renderTarget ) {
- _currentRenderTarget = renderTarget;
- if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
- setupRenderTarget( renderTarget );
- }
- var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
- var framebuffer;
- if ( renderTarget ) {
- var renderTargetProperties = properties.get( renderTarget );
- if ( isCube ) {
- framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
- } else {
- framebuffer = renderTargetProperties.__webglFramebuffer;
- }
- _currentScissor.copy( renderTarget.scissor );
- _currentScissorTest = renderTarget.scissorTest;
- _currentViewport.copy( renderTarget.viewport );
- } else {
- framebuffer = null;
- _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
- _currentScissorTest = _scissorTest;
- _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
- }
- if ( _currentFramebuffer !== framebuffer ) {
- _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
- _currentFramebuffer = framebuffer;
- }
- state.scissor( _currentScissor );
- state.setScissorTest( _currentScissorTest );
- state.viewport( _currentViewport );
- if ( isCube ) {
- var textureProperties = properties.get( renderTarget.texture );
- _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
- }
- };
- this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
- if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
- console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
- return;
- }
- var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
- if ( framebuffer ) {
- var restore = false;
- if ( framebuffer !== _currentFramebuffer ) {
- _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
- restore = true;
- }
- try {
- var texture = renderTarget.texture;
- if ( texture.format !== THREE.RGBAFormat
- && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
- console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
- return;
- }
- if ( texture.type !== THREE.UnsignedByteType
- && paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE )
- && ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) )
- && ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
- console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
- return;
- }
- if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
- _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
- } else {
- console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
- }
- } finally {
- if ( restore ) {
- _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
- }
- }
- }
- };
- function updateRenderTargetMipmap( renderTarget ) {
- var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
- var texture = properties.get( renderTarget.texture ).__webglTexture;
- state.bindTexture( target, texture );
- _gl.generateMipmap( target );
- state.bindTexture( target, null );
- }
- // Fallback filters for non-power-of-2 textures
- function filterFallback ( f ) {
- if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
- return _gl.NEAREST;
- }
- return _gl.LINEAR;
- }
- // Map three.js constants to WebGL constants
- function paramThreeToGL ( p ) {
- var extension;
- if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
- if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
- if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
- if ( p === THREE.NearestFilter ) return _gl.NEAREST;
- if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
- if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
- if ( p === THREE.LinearFilter ) return _gl.LINEAR;
- if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
- if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
- if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
- if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
- if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
- if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
- if ( p === THREE.ByteType ) return _gl.BYTE;
- if ( p === THREE.ShortType ) return _gl.SHORT;
- if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
- if ( p === THREE.IntType ) return _gl.INT;
- if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
- if ( p === THREE.FloatType ) return _gl.FLOAT;
- extension = extensions.get( 'OES_texture_half_float' );
- if ( extension !== null ) {
- if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
- }
- if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
- if ( p === THREE.RGBFormat ) return _gl.RGB;
- if ( p === THREE.RGBAFormat ) return _gl.RGBA;
- if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
- if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
- if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
- if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
- if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
- if ( p === THREE.ZeroFactor ) return _gl.ZERO;
- if ( p === THREE.OneFactor ) return _gl.ONE;
- if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
- if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
- if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
- if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
- if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
- if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
- if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
- if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
- if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
- extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
- if ( extension !== null ) {
- if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
- if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
- if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
- if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
- }
- extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
- if ( extension !== null ) {
- if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
- if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
- if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
- if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
- }
- extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
- if ( extension !== null ) {
- if ( p === THREE.RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
- }
- extension = extensions.get( 'EXT_blend_minmax' );
- if ( extension !== null ) {
- if ( p === THREE.MinEquation ) return extension.MIN_EXT;
- if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
- }
- return 0;
- }
- };
|