WebGLRenderer.js 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778
  1. /**
  2. * @author supereggbert / http://www.paulbrunt.co.uk/
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author alteredq / http://alteredqualia.com/
  5. * @author szimek / https://github.com/szimek/
  6. * @author tschw
  7. */
  8. THREE.WebGLRenderer = function ( parameters ) {
  9. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10. parameters = parameters || {};
  11. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  12. _context = parameters.context !== undefined ? parameters.context : null,
  13. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  17. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  18. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  19. var lights = [];
  20. var opaqueObjects = [];
  21. var opaqueObjectsLastIndex = - 1;
  22. var transparentObjects = [];
  23. var transparentObjectsLastIndex = - 1;
  24. var morphInfluences = new Float32Array( 8 );
  25. var sprites = [];
  26. var lensFlares = [];
  27. // public properties
  28. this.domElement = _canvas;
  29. this.context = null;
  30. // clearing
  31. this.autoClear = true;
  32. this.autoClearColor = true;
  33. this.autoClearDepth = true;
  34. this.autoClearStencil = true;
  35. // scene graph
  36. this.sortObjects = true;
  37. // user-defined clipping
  38. this.clippingPlanes = [];
  39. this.localClippingEnabled = false;
  40. // physically based shading
  41. this.gammaFactor = 2.0; // for backwards compatibility
  42. this.gammaInput = false;
  43. this.gammaOutput = false;
  44. // physical lights
  45. this.physicallyCorrectLights = false;
  46. // tone mapping
  47. this.toneMapping = THREE.LinearToneMapping;
  48. this.toneMappingExposure = 1.0;
  49. this.toneMappingWhitePoint = 1.0;
  50. // morphs
  51. this.maxMorphTargets = 8;
  52. this.maxMorphNormals = 4;
  53. // internal properties
  54. var _this = this,
  55. // internal state cache
  56. _currentProgram = null,
  57. _currentRenderTarget = null,
  58. _currentFramebuffer = null,
  59. _currentMaterialId = - 1,
  60. _currentGeometryProgram = '',
  61. _currentCamera = null,
  62. _currentScissor = new THREE.Vector4(),
  63. _currentScissorTest = null,
  64. _currentViewport = new THREE.Vector4(),
  65. //
  66. _usedTextureUnits = 0,
  67. //
  68. _clearColor = new THREE.Color( 0x000000 ),
  69. _clearAlpha = 0,
  70. _width = _canvas.width,
  71. _height = _canvas.height,
  72. _pixelRatio = 1,
  73. _scissor = new THREE.Vector4( 0, 0, _width, _height ),
  74. _scissorTest = false,
  75. _viewport = new THREE.Vector4( 0, 0, _width, _height ),
  76. // frustum
  77. _frustum = new THREE.Frustum(),
  78. // clipping
  79. _clipping = new THREE.WebGLClipping(),
  80. _clippingEnabled = false,
  81. _localClippingEnabled = false,
  82. _sphere = new THREE.Sphere(),
  83. // camera matrices cache
  84. _projScreenMatrix = new THREE.Matrix4(),
  85. _vector3 = new THREE.Vector3(),
  86. // light arrays cache
  87. _lights = {
  88. hash: '',
  89. ambient: [ 0, 0, 0 ],
  90. directional: [],
  91. directionalShadowMap: [],
  92. directionalShadowMatrix: [],
  93. spot: [],
  94. spotShadowMap: [],
  95. spotShadowMatrix: [],
  96. point: [],
  97. pointShadowMap: [],
  98. pointShadowMatrix: [],
  99. hemi: [],
  100. shadows: []
  101. },
  102. // info
  103. _infoRender = {
  104. calls: 0,
  105. vertices: 0,
  106. faces: 0,
  107. points: 0
  108. };
  109. this.info = {
  110. render: _infoRender,
  111. memory: {
  112. geometries: 0,
  113. textures: 0
  114. },
  115. programs: null
  116. };
  117. // initialize
  118. var _gl;
  119. try {
  120. var attributes = {
  121. alpha: _alpha,
  122. depth: _depth,
  123. stencil: _stencil,
  124. antialias: _antialias,
  125. premultipliedAlpha: _premultipliedAlpha,
  126. preserveDrawingBuffer: _preserveDrawingBuffer
  127. };
  128. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  129. if ( _gl === null ) {
  130. if ( _canvas.getContext( 'webgl' ) !== null ) {
  131. throw 'Error creating WebGL context with your selected attributes.';
  132. } else {
  133. throw 'Error creating WebGL context.';
  134. }
  135. }
  136. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  137. if ( _gl.getShaderPrecisionFormat === undefined ) {
  138. _gl.getShaderPrecisionFormat = function () {
  139. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  140. };
  141. }
  142. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  143. } catch ( error ) {
  144. console.error( 'THREE.WebGLRenderer: ' + error );
  145. }
  146. var extensions = new THREE.WebGLExtensions( _gl );
  147. extensions.get( 'WEBGL_depth_texture' );
  148. extensions.get( 'OES_texture_float' );
  149. extensions.get( 'OES_texture_float_linear' );
  150. extensions.get( 'OES_texture_half_float' );
  151. extensions.get( 'OES_texture_half_float_linear' );
  152. extensions.get( 'OES_standard_derivatives' );
  153. extensions.get( 'ANGLE_instanced_arrays' );
  154. if ( extensions.get( 'OES_element_index_uint' ) ) {
  155. THREE.BufferGeometry.MaxIndex = 4294967296;
  156. }
  157. var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters );
  158. var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
  159. var properties = new THREE.WebGLProperties();
  160. var textures = new THREE.WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
  161. var objects = new THREE.WebGLObjects( _gl, properties, this.info );
  162. var programCache = new THREE.WebGLPrograms( this, capabilities );
  163. var lightCache = new THREE.WebGLLights();
  164. this.info.programs = programCache.programs;
  165. var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
  166. var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  167. //
  168. var backgroundCamera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  169. var backgroundCamera2 = new THREE.PerspectiveCamera();
  170. var backgroundPlaneMesh = new THREE.Mesh(
  171. new THREE.PlaneBufferGeometry( 2, 2 ),
  172. new THREE.MeshBasicMaterial( { depthTest: false, depthWrite: false } )
  173. );
  174. var backgroundBoxShader = THREE.ShaderLib[ 'cube' ];
  175. var backgroundBoxMesh = new THREE.Mesh(
  176. new THREE.BoxBufferGeometry( 5, 5, 5 ),
  177. new THREE.ShaderMaterial( {
  178. uniforms: backgroundBoxShader.uniforms,
  179. vertexShader: backgroundBoxShader.vertexShader,
  180. fragmentShader: backgroundBoxShader.fragmentShader,
  181. depthTest: false,
  182. depthWrite: false,
  183. side: THREE.BackSide
  184. } )
  185. );
  186. objects.update( backgroundPlaneMesh );
  187. objects.update( backgroundBoxMesh );
  188. //
  189. function getTargetPixelRatio() {
  190. return _currentRenderTarget === null ? _pixelRatio : 1;
  191. }
  192. function glClearColor( r, g, b, a ) {
  193. if ( _premultipliedAlpha === true ) {
  194. r *= a; g *= a; b *= a;
  195. }
  196. state.clearColor( r, g, b, a );
  197. }
  198. function setDefaultGLState() {
  199. state.init();
  200. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  201. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  202. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  203. }
  204. function resetGLState() {
  205. _currentProgram = null;
  206. _currentCamera = null;
  207. _currentGeometryProgram = '';
  208. _currentMaterialId = - 1;
  209. state.reset();
  210. }
  211. setDefaultGLState();
  212. this.context = _gl;
  213. this.capabilities = capabilities;
  214. this.extensions = extensions;
  215. this.properties = properties;
  216. this.state = state;
  217. // shadow map
  218. var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects );
  219. this.shadowMap = shadowMap;
  220. // Plugins
  221. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  222. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  223. // API
  224. this.getContext = function () {
  225. return _gl;
  226. };
  227. this.getContextAttributes = function () {
  228. return _gl.getContextAttributes();
  229. };
  230. this.forceContextLoss = function () {
  231. extensions.get( 'WEBGL_lose_context' ).loseContext();
  232. };
  233. this.getMaxAnisotropy = function () {
  234. return capabilities.getMaxAnisotropy();
  235. };
  236. this.getPrecision = function () {
  237. return capabilities.precision;
  238. };
  239. this.getPixelRatio = function () {
  240. return _pixelRatio;
  241. };
  242. this.setPixelRatio = function ( value ) {
  243. if ( value === undefined ) return;
  244. _pixelRatio = value;
  245. this.setSize( _viewport.z, _viewport.w, false );
  246. };
  247. this.getSize = function () {
  248. return {
  249. width: _width,
  250. height: _height
  251. };
  252. };
  253. this.setSize = function ( width, height, updateStyle ) {
  254. _width = width;
  255. _height = height;
  256. _canvas.width = width * _pixelRatio;
  257. _canvas.height = height * _pixelRatio;
  258. if ( updateStyle !== false ) {
  259. _canvas.style.width = width + 'px';
  260. _canvas.style.height = height + 'px';
  261. }
  262. this.setViewport( 0, 0, width, height );
  263. };
  264. this.setViewport = function ( x, y, width, height ) {
  265. state.viewport( _viewport.set( x, y, width, height ) );
  266. };
  267. this.setScissor = function ( x, y, width, height ) {
  268. state.scissor( _scissor.set( x, y, width, height ) );
  269. };
  270. this.setScissorTest = function ( boolean ) {
  271. state.setScissorTest( _scissorTest = boolean );
  272. };
  273. // Clearing
  274. this.getClearColor = function () {
  275. return _clearColor;
  276. };
  277. this.setClearColor = function ( color, alpha ) {
  278. _clearColor.set( color );
  279. _clearAlpha = alpha !== undefined ? alpha : 1;
  280. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  281. };
  282. this.getClearAlpha = function () {
  283. return _clearAlpha;
  284. };
  285. this.setClearAlpha = function ( alpha ) {
  286. _clearAlpha = alpha;
  287. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  288. };
  289. this.clear = function ( color, depth, stencil ) {
  290. var bits = 0;
  291. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  292. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  293. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  294. _gl.clear( bits );
  295. };
  296. this.clearColor = function () {
  297. this.clear( true, false, false );
  298. };
  299. this.clearDepth = function () {
  300. this.clear( false, true, false );
  301. };
  302. this.clearStencil = function () {
  303. this.clear( false, false, true );
  304. };
  305. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  306. this.setRenderTarget( renderTarget );
  307. this.clear( color, depth, stencil );
  308. };
  309. // Reset
  310. this.resetGLState = resetGLState;
  311. this.dispose = function() {
  312. transparentObjects = [];
  313. transparentObjectsLastIndex = -1;
  314. opaqueObjects = [];
  315. opaqueObjectsLastIndex = -1;
  316. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  317. };
  318. // Events
  319. function onContextLost( event ) {
  320. event.preventDefault();
  321. resetGLState();
  322. setDefaultGLState();
  323. properties.clear();
  324. }
  325. function onMaterialDispose( event ) {
  326. var material = event.target;
  327. material.removeEventListener( 'dispose', onMaterialDispose );
  328. deallocateMaterial( material );
  329. }
  330. // Buffer deallocation
  331. function deallocateMaterial( material ) {
  332. releaseMaterialProgramReference( material );
  333. properties.delete( material );
  334. }
  335. function releaseMaterialProgramReference( material ) {
  336. var programInfo = properties.get( material ).program;
  337. material.program = undefined;
  338. if ( programInfo !== undefined ) {
  339. programCache.releaseProgram( programInfo );
  340. }
  341. }
  342. // Buffer rendering
  343. this.renderBufferImmediate = function ( object, program, material ) {
  344. state.initAttributes();
  345. var buffers = properties.get( object );
  346. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  347. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  348. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  349. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  350. var attributes = program.getAttributes();
  351. if ( object.hasPositions ) {
  352. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  353. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  354. state.enableAttribute( attributes.position );
  355. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  356. }
  357. if ( object.hasNormals ) {
  358. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  359. if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === THREE.FlatShading ) {
  360. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  361. var array = object.normalArray;
  362. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  363. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  364. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  365. array[ i + 0 ] = nx;
  366. array[ i + 1 ] = ny;
  367. array[ i + 2 ] = nz;
  368. array[ i + 3 ] = nx;
  369. array[ i + 4 ] = ny;
  370. array[ i + 5 ] = nz;
  371. array[ i + 6 ] = nx;
  372. array[ i + 7 ] = ny;
  373. array[ i + 8 ] = nz;
  374. }
  375. }
  376. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  377. state.enableAttribute( attributes.normal );
  378. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  379. }
  380. if ( object.hasUvs && material.map ) {
  381. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  382. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  383. state.enableAttribute( attributes.uv );
  384. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  385. }
  386. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  387. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  388. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  389. state.enableAttribute( attributes.color );
  390. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  391. }
  392. state.disableUnusedAttributes();
  393. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  394. object.count = 0;
  395. };
  396. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  397. setMaterial( material );
  398. var program = setProgram( camera, fog, material, object );
  399. var updateBuffers = false;
  400. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  401. if ( geometryProgram !== _currentGeometryProgram ) {
  402. _currentGeometryProgram = geometryProgram;
  403. updateBuffers = true;
  404. }
  405. // morph targets
  406. var morphTargetInfluences = object.morphTargetInfluences;
  407. if ( morphTargetInfluences !== undefined ) {
  408. var activeInfluences = [];
  409. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  410. var influence = morphTargetInfluences[ i ];
  411. activeInfluences.push( [ influence, i ] );
  412. }
  413. activeInfluences.sort( absNumericalSort );
  414. if ( activeInfluences.length > 8 ) {
  415. activeInfluences.length = 8;
  416. }
  417. var morphAttributes = geometry.morphAttributes;
  418. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  419. var influence = activeInfluences[ i ];
  420. morphInfluences[ i ] = influence[ 0 ];
  421. if ( influence[ 0 ] !== 0 ) {
  422. var index = influence[ 1 ];
  423. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  424. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  425. } else {
  426. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  427. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  428. }
  429. }
  430. program.getUniforms().setValue(
  431. _gl, 'morphTargetInfluences', morphInfluences );
  432. updateBuffers = true;
  433. }
  434. //
  435. var index = geometry.index;
  436. var position = geometry.attributes.position;
  437. if ( material.wireframe === true ) {
  438. index = objects.getWireframeAttribute( geometry );
  439. }
  440. var renderer;
  441. if ( index !== null ) {
  442. renderer = indexedBufferRenderer;
  443. renderer.setIndex( index );
  444. } else {
  445. renderer = bufferRenderer;
  446. }
  447. if ( updateBuffers ) {
  448. setupVertexAttributes( material, program, geometry );
  449. if ( index !== null ) {
  450. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  451. }
  452. }
  453. //
  454. var dataStart = 0;
  455. var dataCount = Infinity;
  456. if ( index !== null ) {
  457. dataCount = index.count;
  458. } else if ( position !== undefined ) {
  459. dataCount = position.count;
  460. }
  461. var rangeStart = geometry.drawRange.start;
  462. var rangeCount = geometry.drawRange.count;
  463. var groupStart = group !== null ? group.start : 0;
  464. var groupCount = group !== null ? group.count : Infinity;
  465. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  466. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  467. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  468. //
  469. if ( object instanceof THREE.Mesh ) {
  470. if ( material.wireframe === true ) {
  471. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  472. renderer.setMode( _gl.LINES );
  473. } else {
  474. switch ( object.drawMode ) {
  475. case THREE.TrianglesDrawMode:
  476. renderer.setMode( _gl.TRIANGLES );
  477. break;
  478. case THREE.TriangleStripDrawMode:
  479. renderer.setMode( _gl.TRIANGLE_STRIP );
  480. break;
  481. case THREE.TriangleFanDrawMode:
  482. renderer.setMode( _gl.TRIANGLE_FAN );
  483. break;
  484. }
  485. }
  486. } else if ( object instanceof THREE.Line ) {
  487. var lineWidth = material.linewidth;
  488. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  489. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  490. if ( object instanceof THREE.LineSegments ) {
  491. renderer.setMode( _gl.LINES );
  492. } else {
  493. renderer.setMode( _gl.LINE_STRIP );
  494. }
  495. } else if ( object instanceof THREE.Points ) {
  496. renderer.setMode( _gl.POINTS );
  497. }
  498. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  499. if ( geometry.maxInstancedCount > 0 ) {
  500. renderer.renderInstances( geometry, drawStart, drawCount );
  501. }
  502. } else {
  503. renderer.render( drawStart, drawCount );
  504. }
  505. };
  506. function setupVertexAttributes( material, program, geometry, startIndex ) {
  507. var extension;
  508. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  509. extension = extensions.get( 'ANGLE_instanced_arrays' );
  510. if ( extension === null ) {
  511. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  512. return;
  513. }
  514. }
  515. if ( startIndex === undefined ) startIndex = 0;
  516. state.initAttributes();
  517. var geometryAttributes = geometry.attributes;
  518. var programAttributes = program.getAttributes();
  519. var materialDefaultAttributeValues = material.defaultAttributeValues;
  520. for ( var name in programAttributes ) {
  521. var programAttribute = programAttributes[ name ];
  522. if ( programAttribute >= 0 ) {
  523. var geometryAttribute = geometryAttributes[ name ];
  524. if ( geometryAttribute !== undefined ) {
  525. var type = _gl.FLOAT;
  526. var array = geometryAttribute.array;
  527. var normalized = geometryAttribute.normalized;
  528. if ( array instanceof Float32Array ) {
  529. type = _gl.FLOAT;
  530. } else if ( array instanceof Float64Array ) {
  531. console.warn("Unsupported data buffer format: Float64Array");
  532. } else if ( array instanceof Uint16Array ) {
  533. type = _gl.UNSIGNED_SHORT;
  534. } else if ( array instanceof Int16Array ) {
  535. type = _gl.SHORT;
  536. } else if ( array instanceof Uint32Array ) {
  537. type = _gl.UNSIGNED_INT;
  538. } else if ( array instanceof Int32Array ) {
  539. type = _gl.INT;
  540. } else if ( array instanceof Int8Array ) {
  541. type = _gl.BYTE;
  542. } else if ( array instanceof Uint8Array ) {
  543. type = _gl.UNSIGNED_BYTE;
  544. }
  545. var size = geometryAttribute.itemSize;
  546. var buffer = objects.getAttributeBuffer( geometryAttribute );
  547. if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
  548. var data = geometryAttribute.data;
  549. var stride = data.stride;
  550. var offset = geometryAttribute.offset;
  551. if ( data instanceof THREE.InstancedInterleavedBuffer ) {
  552. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  553. if ( geometry.maxInstancedCount === undefined ) {
  554. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  555. }
  556. } else {
  557. state.enableAttribute( programAttribute );
  558. }
  559. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  560. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  561. } else {
  562. if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
  563. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  564. if ( geometry.maxInstancedCount === undefined ) {
  565. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  566. }
  567. } else {
  568. state.enableAttribute( programAttribute );
  569. }
  570. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  571. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT );
  572. }
  573. } else if ( materialDefaultAttributeValues !== undefined ) {
  574. var value = materialDefaultAttributeValues[ name ];
  575. if ( value !== undefined ) {
  576. switch ( value.length ) {
  577. case 2:
  578. _gl.vertexAttrib2fv( programAttribute, value );
  579. break;
  580. case 3:
  581. _gl.vertexAttrib3fv( programAttribute, value );
  582. break;
  583. case 4:
  584. _gl.vertexAttrib4fv( programAttribute, value );
  585. break;
  586. default:
  587. _gl.vertexAttrib1fv( programAttribute, value );
  588. }
  589. }
  590. }
  591. }
  592. }
  593. state.disableUnusedAttributes();
  594. }
  595. // Sorting
  596. function absNumericalSort( a, b ) {
  597. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  598. }
  599. function painterSortStable ( a, b ) {
  600. if ( a.object.renderOrder !== b.object.renderOrder ) {
  601. return a.object.renderOrder - b.object.renderOrder;
  602. } else if ( a.material.id !== b.material.id ) {
  603. return a.material.id - b.material.id;
  604. } else if ( a.z !== b.z ) {
  605. return a.z - b.z;
  606. } else {
  607. return a.id - b.id;
  608. }
  609. }
  610. function reversePainterSortStable ( a, b ) {
  611. if ( a.object.renderOrder !== b.object.renderOrder ) {
  612. return a.object.renderOrder - b.object.renderOrder;
  613. } if ( a.z !== b.z ) {
  614. return b.z - a.z;
  615. } else {
  616. return a.id - b.id;
  617. }
  618. }
  619. // Rendering
  620. this.render = function ( scene, camera, renderTarget, forceClear ) {
  621. if ( camera instanceof THREE.Camera === false ) {
  622. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  623. return;
  624. }
  625. var fog = scene.fog;
  626. // reset caching for this frame
  627. _currentGeometryProgram = '';
  628. _currentMaterialId = - 1;
  629. _currentCamera = null;
  630. // update scene graph
  631. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  632. // update camera matrices and frustum
  633. if ( camera.parent === null ) camera.updateMatrixWorld();
  634. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  635. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  636. _frustum.setFromMatrix( _projScreenMatrix );
  637. lights.length = 0;
  638. opaqueObjectsLastIndex = - 1;
  639. transparentObjectsLastIndex = - 1;
  640. sprites.length = 0;
  641. lensFlares.length = 0;
  642. _localClippingEnabled = this.localClippingEnabled;
  643. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  644. projectObject( scene, camera );
  645. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  646. transparentObjects.length = transparentObjectsLastIndex + 1;
  647. if ( _this.sortObjects === true ) {
  648. opaqueObjects.sort( painterSortStable );
  649. transparentObjects.sort( reversePainterSortStable );
  650. }
  651. //
  652. if ( _clippingEnabled ) _clipping.beginShadows();
  653. setupShadows( lights );
  654. shadowMap.render( scene, camera );
  655. setupLights( lights, camera );
  656. if ( _clippingEnabled ) _clipping.endShadows();
  657. //
  658. _infoRender.calls = 0;
  659. _infoRender.vertices = 0;
  660. _infoRender.faces = 0;
  661. _infoRender.points = 0;
  662. if ( renderTarget === undefined ) {
  663. renderTarget = null;
  664. }
  665. this.setRenderTarget( renderTarget );
  666. //
  667. var needsClear = this.autoClear || forceClear;
  668. var background = scene.background;
  669. if ( background === null ) {
  670. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  671. } else if ( background instanceof THREE.CubeTexture ) {
  672. backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix );
  673. backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld );
  674. backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld );
  675. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  676. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  677. _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  678. needsClear = false;
  679. } else if ( background instanceof THREE.Texture ) {
  680. backgroundPlaneMesh.material.map = background;
  681. _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  682. needsClear = false;
  683. } else if ( background instanceof THREE.Color ) {
  684. glClearColor( background.r, background.g, background.b, 1 );
  685. needsClear = true;
  686. }
  687. if ( needsClear ) {
  688. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  689. }
  690. //
  691. if ( scene.overrideMaterial ) {
  692. var overrideMaterial = scene.overrideMaterial;
  693. renderObjects( opaqueObjects, camera, fog, overrideMaterial );
  694. renderObjects( transparentObjects, camera, fog, overrideMaterial );
  695. } else {
  696. // opaque pass (front-to-back order)
  697. state.setBlending( THREE.NoBlending );
  698. renderObjects( opaqueObjects, camera, fog );
  699. // transparent pass (back-to-front order)
  700. renderObjects( transparentObjects, camera, fog );
  701. }
  702. // custom render plugins (post pass)
  703. spritePlugin.render( scene, camera );
  704. lensFlarePlugin.render( scene, camera, _currentViewport );
  705. // Generate mipmap if we're using any kind of mipmap filtering
  706. if ( renderTarget ) {
  707. textures.updateRenderTargetMipmap( renderTarget );
  708. }
  709. // Ensure depth buffer writing is enabled so it can be cleared on next render
  710. state.setDepthTest( true );
  711. state.setDepthWrite( true );
  712. state.setColorWrite( true );
  713. // _gl.finish();
  714. };
  715. function pushRenderItem( object, geometry, material, z, group ) {
  716. var array, index;
  717. // allocate the next position in the appropriate array
  718. if ( material.transparent ) {
  719. array = transparentObjects;
  720. index = ++ transparentObjectsLastIndex;
  721. } else {
  722. array = opaqueObjects;
  723. index = ++ opaqueObjectsLastIndex;
  724. }
  725. // recycle existing render item or grow the array
  726. var renderItem = array[ index ];
  727. if ( renderItem !== undefined ) {
  728. renderItem.id = object.id;
  729. renderItem.object = object;
  730. renderItem.geometry = geometry;
  731. renderItem.material = material;
  732. renderItem.z = _vector3.z;
  733. renderItem.group = group;
  734. } else {
  735. renderItem = {
  736. id: object.id,
  737. object: object,
  738. geometry: geometry,
  739. material: material,
  740. z: _vector3.z,
  741. group: group
  742. };
  743. // assert( index === array.length );
  744. array.push( renderItem );
  745. }
  746. }
  747. // TODO Duplicated code (Frustum)
  748. function isObjectViewable( object ) {
  749. var geometry = object.geometry;
  750. if ( geometry.boundingSphere === null )
  751. geometry.computeBoundingSphere();
  752. _sphere.copy( geometry.boundingSphere ).
  753. applyMatrix4( object.matrixWorld );
  754. return isSphereViewable( _sphere );
  755. }
  756. function isSpriteViewable( sprite ) {
  757. _sphere.center.set( 0, 0, 0 );
  758. _sphere.radius = 0.7071067811865476;
  759. _sphere.applyMatrix4( sprite.matrixWorld );
  760. return isSphereViewable( _sphere );
  761. }
  762. function isSphereViewable( sphere ) {
  763. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  764. var numPlanes = _clipping.numPlanes;
  765. if ( numPlanes === 0 ) return true;
  766. var planes = _this.clippingPlanes,
  767. center = sphere.center,
  768. negRad = - sphere.radius,
  769. i = 0;
  770. do {
  771. // out when deeper than radius in the negative halfspace
  772. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  773. } while ( ++ i !== numPlanes );
  774. return true;
  775. }
  776. function projectObject( object, camera ) {
  777. if ( object.visible === false ) return;
  778. if ( object.layers.test( camera.layers ) ) {
  779. if ( object instanceof THREE.Light ) {
  780. lights.push( object );
  781. } else if ( object instanceof THREE.Sprite ) {
  782. if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) {
  783. sprites.push( object );
  784. }
  785. } else if ( object instanceof THREE.LensFlare ) {
  786. lensFlares.push( object );
  787. } else if ( object instanceof THREE.ImmediateRenderObject ) {
  788. if ( _this.sortObjects === true ) {
  789. _vector3.setFromMatrixPosition( object.matrixWorld );
  790. _vector3.applyProjection( _projScreenMatrix );
  791. }
  792. pushRenderItem( object, null, object.material, _vector3.z, null );
  793. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) {
  794. if ( object instanceof THREE.SkinnedMesh ) {
  795. object.skeleton.update();
  796. }
  797. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  798. var material = object.material;
  799. if ( material.visible === true ) {
  800. if ( _this.sortObjects === true ) {
  801. _vector3.setFromMatrixPosition( object.matrixWorld );
  802. _vector3.applyProjection( _projScreenMatrix );
  803. }
  804. var geometry = objects.update( object );
  805. if ( material instanceof THREE.MultiMaterial ) {
  806. var groups = geometry.groups;
  807. var materials = material.materials;
  808. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  809. var group = groups[ i ];
  810. var groupMaterial = materials[ group.materialIndex ];
  811. if ( groupMaterial.visible === true ) {
  812. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  813. }
  814. }
  815. } else {
  816. pushRenderItem( object, geometry, material, _vector3.z, null );
  817. }
  818. }
  819. }
  820. }
  821. }
  822. var children = object.children;
  823. for ( var i = 0, l = children.length; i < l; i ++ ) {
  824. projectObject( children[ i ], camera );
  825. }
  826. }
  827. function renderObjects( renderList, camera, fog, overrideMaterial ) {
  828. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  829. var renderItem = renderList[ i ];
  830. var object = renderItem.object;
  831. var geometry = renderItem.geometry;
  832. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  833. var group = renderItem.group;
  834. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  835. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  836. if ( object instanceof THREE.ImmediateRenderObject ) {
  837. setMaterial( material );
  838. var program = setProgram( camera, fog, material, object );
  839. _currentGeometryProgram = '';
  840. object.render( function ( object ) {
  841. _this.renderBufferImmediate( object, program, material );
  842. } );
  843. } else {
  844. _this.renderBufferDirect( camera, fog, geometry, material, object, group );
  845. }
  846. }
  847. }
  848. function initMaterial( material, fog, object ) {
  849. var materialProperties = properties.get( material );
  850. var parameters = programCache.getParameters(
  851. material, _lights, fog, _clipping.numPlanes, object );
  852. var code = programCache.getProgramCode( material, parameters );
  853. var program = materialProperties.program;
  854. var programChange = true;
  855. if ( program === undefined ) {
  856. // new material
  857. material.addEventListener( 'dispose', onMaterialDispose );
  858. } else if ( program.code !== code ) {
  859. // changed glsl or parameters
  860. releaseMaterialProgramReference( material );
  861. } else if ( parameters.shaderID !== undefined ) {
  862. // same glsl and uniform list
  863. return;
  864. } else {
  865. // only rebuild uniform list
  866. programChange = false;
  867. }
  868. if ( programChange ) {
  869. if ( parameters.shaderID ) {
  870. var shader = THREE.ShaderLib[ parameters.shaderID ];
  871. materialProperties.__webglShader = {
  872. name: material.type,
  873. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  874. vertexShader: shader.vertexShader,
  875. fragmentShader: shader.fragmentShader
  876. };
  877. } else {
  878. materialProperties.__webglShader = {
  879. name: material.type,
  880. uniforms: material.uniforms,
  881. vertexShader: material.vertexShader,
  882. fragmentShader: material.fragmentShader
  883. };
  884. }
  885. material.__webglShader = materialProperties.__webglShader;
  886. program = programCache.acquireProgram( material, parameters, code );
  887. materialProperties.program = program;
  888. material.program = program;
  889. }
  890. var attributes = program.getAttributes();
  891. if ( material.morphTargets ) {
  892. material.numSupportedMorphTargets = 0;
  893. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  894. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  895. material.numSupportedMorphTargets ++;
  896. }
  897. }
  898. }
  899. if ( material.morphNormals ) {
  900. material.numSupportedMorphNormals = 0;
  901. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  902. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  903. material.numSupportedMorphNormals ++;
  904. }
  905. }
  906. }
  907. var uniforms = materialProperties.__webglShader.uniforms;
  908. if ( ! ( material instanceof THREE.ShaderMaterial ) &&
  909. ! ( material instanceof THREE.RawShaderMaterial ) ||
  910. material.clipping === true ) {
  911. materialProperties.numClippingPlanes = _clipping.numPlanes;
  912. uniforms.clippingPlanes = _clipping.uniform;
  913. }
  914. if ( material.lights ) {
  915. // store the light setup it was created for
  916. materialProperties.lightsHash = _lights.hash;
  917. // wire up the material to this renderer's lighting state
  918. uniforms.ambientLightColor.value = _lights.ambient;
  919. uniforms.directionalLights.value = _lights.directional;
  920. uniforms.spotLights.value = _lights.spot;
  921. uniforms.pointLights.value = _lights.point;
  922. uniforms.hemisphereLights.value = _lights.hemi;
  923. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  924. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  925. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  926. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  927. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  928. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  929. }
  930. var progUniforms = materialProperties.program.getUniforms(),
  931. uniformsList =
  932. THREE.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  933. materialProperties.uniformsList = uniformsList;
  934. materialProperties.dynamicUniforms =
  935. THREE.WebGLUniforms.splitDynamic( uniformsList, uniforms );
  936. }
  937. function setMaterial( material ) {
  938. if ( material.side !== THREE.DoubleSide )
  939. state.enable( _gl.CULL_FACE );
  940. else
  941. state.disable( _gl.CULL_FACE );
  942. state.setFlipSided( material.side === THREE.BackSide );
  943. if ( material.transparent === true ) {
  944. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  945. } else {
  946. state.setBlending( THREE.NoBlending );
  947. }
  948. state.setDepthFunc( material.depthFunc );
  949. state.setDepthTest( material.depthTest );
  950. state.setDepthWrite( material.depthWrite );
  951. state.setColorWrite( material.colorWrite );
  952. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  953. }
  954. function setProgram( camera, fog, material, object ) {
  955. _usedTextureUnits = 0;
  956. var materialProperties = properties.get( material );
  957. if ( _clippingEnabled ) {
  958. if ( _localClippingEnabled || camera !== _currentCamera ) {
  959. var useCache =
  960. camera === _currentCamera &&
  961. material.id === _currentMaterialId;
  962. // we might want to call this function with some ClippingGroup
  963. // object instead of the material, once it becomes feasible
  964. // (#8465, #8379)
  965. _clipping.setState(
  966. material.clippingPlanes, material.clipShadows,
  967. camera, materialProperties, useCache );
  968. }
  969. if ( materialProperties.numClippingPlanes !== undefined &&
  970. materialProperties.numClippingPlanes !== _clipping.numPlanes ) {
  971. material.needsUpdate = true;
  972. }
  973. }
  974. if ( materialProperties.program === undefined ) {
  975. material.needsUpdate = true;
  976. }
  977. if ( materialProperties.lightsHash !== undefined &&
  978. materialProperties.lightsHash !== _lights.hash ) {
  979. material.needsUpdate = true;
  980. }
  981. if ( material.needsUpdate ) {
  982. initMaterial( material, fog, object );
  983. material.needsUpdate = false;
  984. }
  985. var refreshProgram = false;
  986. var refreshMaterial = false;
  987. var refreshLights = false;
  988. var program = materialProperties.program,
  989. p_uniforms = program.getUniforms(),
  990. m_uniforms = materialProperties.__webglShader.uniforms;
  991. if ( program.id !== _currentProgram ) {
  992. _gl.useProgram( program.program );
  993. _currentProgram = program.id;
  994. refreshProgram = true;
  995. refreshMaterial = true;
  996. refreshLights = true;
  997. }
  998. if ( material.id !== _currentMaterialId ) {
  999. _currentMaterialId = material.id;
  1000. refreshMaterial = true;
  1001. }
  1002. if ( refreshProgram || camera !== _currentCamera ) {
  1003. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  1004. if ( capabilities.logarithmicDepthBuffer ) {
  1005. p_uniforms.setValue( _gl, 'logDepthBufFC',
  1006. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  1007. }
  1008. if ( camera !== _currentCamera ) {
  1009. _currentCamera = camera;
  1010. // lighting uniforms depend on the camera so enforce an update
  1011. // now, in case this material supports lights - or later, when
  1012. // the next material that does gets activated:
  1013. refreshMaterial = true; // set to true on material change
  1014. refreshLights = true; // remains set until update done
  1015. }
  1016. // load material specific uniforms
  1017. // (shader material also gets them for the sake of genericity)
  1018. if ( material instanceof THREE.ShaderMaterial ||
  1019. material instanceof THREE.MeshPhongMaterial ||
  1020. material instanceof THREE.MeshStandardMaterial ||
  1021. material.envMap ) {
  1022. var uCamPos = p_uniforms.map.cameraPosition;
  1023. if ( uCamPos !== undefined ) {
  1024. uCamPos.setValue( _gl,
  1025. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  1026. }
  1027. }
  1028. if ( material instanceof THREE.MeshPhongMaterial ||
  1029. material instanceof THREE.MeshLambertMaterial ||
  1030. material instanceof THREE.MeshBasicMaterial ||
  1031. material instanceof THREE.MeshStandardMaterial ||
  1032. material instanceof THREE.ShaderMaterial ||
  1033. material.skinning ) {
  1034. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  1035. }
  1036. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  1037. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  1038. }
  1039. // skinning uniforms must be set even if material didn't change
  1040. // auto-setting of texture unit for bone texture must go before other textures
  1041. // not sure why, but otherwise weird things happen
  1042. if ( material.skinning ) {
  1043. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  1044. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  1045. var skeleton = object.skeleton;
  1046. if ( skeleton ) {
  1047. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  1048. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  1049. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  1050. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  1051. } else {
  1052. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  1053. }
  1054. }
  1055. }
  1056. if ( refreshMaterial ) {
  1057. if ( material.lights ) {
  1058. // the current material requires lighting info
  1059. // note: all lighting uniforms are always set correctly
  1060. // they simply reference the renderer's state for their
  1061. // values
  1062. //
  1063. // use the current material's .needsUpdate flags to set
  1064. // the GL state when required
  1065. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1066. }
  1067. // refresh uniforms common to several materials
  1068. if ( fog && material.fog ) {
  1069. refreshUniformsFog( m_uniforms, fog );
  1070. }
  1071. if ( material instanceof THREE.MeshBasicMaterial ||
  1072. material instanceof THREE.MeshLambertMaterial ||
  1073. material instanceof THREE.MeshPhongMaterial ||
  1074. material instanceof THREE.MeshStandardMaterial ||
  1075. material instanceof THREE.MeshDepthMaterial ) {
  1076. refreshUniformsCommon( m_uniforms, material );
  1077. }
  1078. // refresh single material specific uniforms
  1079. if ( material instanceof THREE.LineBasicMaterial ) {
  1080. refreshUniformsLine( m_uniforms, material );
  1081. } else if ( material instanceof THREE.LineDashedMaterial ) {
  1082. refreshUniformsLine( m_uniforms, material );
  1083. refreshUniformsDash( m_uniforms, material );
  1084. } else if ( material instanceof THREE.PointsMaterial ) {
  1085. refreshUniformsPoints( m_uniforms, material );
  1086. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  1087. refreshUniformsLambert( m_uniforms, material );
  1088. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  1089. refreshUniformsPhong( m_uniforms, material );
  1090. } else if ( material instanceof THREE.MeshPhysicalMaterial ) {
  1091. refreshUniformsPhysical( m_uniforms, material );
  1092. } else if ( material instanceof THREE.MeshStandardMaterial ) {
  1093. refreshUniformsStandard( m_uniforms, material );
  1094. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  1095. if ( material.displacementMap ) {
  1096. m_uniforms.displacementMap.value = material.displacementMap;
  1097. m_uniforms.displacementScale.value = material.displacementScale;
  1098. m_uniforms.displacementBias.value = material.displacementBias;
  1099. }
  1100. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  1101. m_uniforms.opacity.value = material.opacity;
  1102. }
  1103. THREE.WebGLUniforms.upload(
  1104. _gl, materialProperties.uniformsList, m_uniforms, _this );
  1105. }
  1106. // common matrices
  1107. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  1108. p_uniforms.set( _gl, object, 'normalMatrix' );
  1109. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  1110. // dynamic uniforms
  1111. var dynUniforms = materialProperties.dynamicUniforms;
  1112. if ( dynUniforms !== null ) {
  1113. THREE.WebGLUniforms.evalDynamic(
  1114. dynUniforms, m_uniforms, object, camera );
  1115. THREE.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this );
  1116. }
  1117. return program;
  1118. }
  1119. // Uniforms (refresh uniforms objects)
  1120. function refreshUniformsCommon ( uniforms, material ) {
  1121. uniforms.opacity.value = material.opacity;
  1122. uniforms.diffuse.value = material.color;
  1123. if ( material.emissive ) {
  1124. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  1125. }
  1126. uniforms.map.value = material.map;
  1127. uniforms.specularMap.value = material.specularMap;
  1128. uniforms.alphaMap.value = material.alphaMap;
  1129. if ( material.aoMap ) {
  1130. uniforms.aoMap.value = material.aoMap;
  1131. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  1132. }
  1133. // uv repeat and offset setting priorities
  1134. // 1. color map
  1135. // 2. specular map
  1136. // 3. normal map
  1137. // 4. bump map
  1138. // 5. alpha map
  1139. // 6. emissive map
  1140. var uvScaleMap;
  1141. if ( material.map ) {
  1142. uvScaleMap = material.map;
  1143. } else if ( material.specularMap ) {
  1144. uvScaleMap = material.specularMap;
  1145. } else if ( material.displacementMap ) {
  1146. uvScaleMap = material.displacementMap;
  1147. } else if ( material.normalMap ) {
  1148. uvScaleMap = material.normalMap;
  1149. } else if ( material.bumpMap ) {
  1150. uvScaleMap = material.bumpMap;
  1151. } else if ( material.roughnessMap ) {
  1152. uvScaleMap = material.roughnessMap;
  1153. } else if ( material.metalnessMap ) {
  1154. uvScaleMap = material.metalnessMap;
  1155. } else if ( material.alphaMap ) {
  1156. uvScaleMap = material.alphaMap;
  1157. } else if ( material.emissiveMap ) {
  1158. uvScaleMap = material.emissiveMap;
  1159. }
  1160. if ( uvScaleMap !== undefined ) {
  1161. // backwards compatibility
  1162. if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) {
  1163. uvScaleMap = uvScaleMap.texture;
  1164. }
  1165. var offset = uvScaleMap.offset;
  1166. var repeat = uvScaleMap.repeat;
  1167. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1168. }
  1169. uniforms.envMap.value = material.envMap;
  1170. // don't flip CubeTexture envMaps, flip everything else:
  1171. // WebGLRenderTargetCube will be flipped for backwards compatibility
  1172. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  1173. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  1174. uniforms.flipEnvMap.value = ( ! ( material.envMap instanceof THREE.CubeTexture ) ) ? 1 : - 1;
  1175. uniforms.reflectivity.value = material.reflectivity;
  1176. uniforms.refractionRatio.value = material.refractionRatio;
  1177. }
  1178. function refreshUniformsLine ( uniforms, material ) {
  1179. uniforms.diffuse.value = material.color;
  1180. uniforms.opacity.value = material.opacity;
  1181. }
  1182. function refreshUniformsDash ( uniforms, material ) {
  1183. uniforms.dashSize.value = material.dashSize;
  1184. uniforms.totalSize.value = material.dashSize + material.gapSize;
  1185. uniforms.scale.value = material.scale;
  1186. }
  1187. function refreshUniformsPoints ( uniforms, material ) {
  1188. uniforms.diffuse.value = material.color;
  1189. uniforms.opacity.value = material.opacity;
  1190. uniforms.size.value = material.size * _pixelRatio;
  1191. uniforms.scale.value = _canvas.clientHeight * 0.5;
  1192. uniforms.map.value = material.map;
  1193. if ( material.map !== null ) {
  1194. var offset = material.map.offset;
  1195. var repeat = material.map.repeat;
  1196. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1197. }
  1198. }
  1199. function refreshUniformsFog ( uniforms, fog ) {
  1200. uniforms.fogColor.value = fog.color;
  1201. if ( fog instanceof THREE.Fog ) {
  1202. uniforms.fogNear.value = fog.near;
  1203. uniforms.fogFar.value = fog.far;
  1204. } else if ( fog instanceof THREE.FogExp2 ) {
  1205. uniforms.fogDensity.value = fog.density;
  1206. }
  1207. }
  1208. function refreshUniformsLambert ( uniforms, material ) {
  1209. if ( material.lightMap ) {
  1210. uniforms.lightMap.value = material.lightMap;
  1211. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1212. }
  1213. if ( material.emissiveMap ) {
  1214. uniforms.emissiveMap.value = material.emissiveMap;
  1215. }
  1216. }
  1217. function refreshUniformsPhong ( uniforms, material ) {
  1218. uniforms.specular.value = material.specular;
  1219. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  1220. if ( material.lightMap ) {
  1221. uniforms.lightMap.value = material.lightMap;
  1222. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1223. }
  1224. if ( material.emissiveMap ) {
  1225. uniforms.emissiveMap.value = material.emissiveMap;
  1226. }
  1227. if ( material.bumpMap ) {
  1228. uniforms.bumpMap.value = material.bumpMap;
  1229. uniforms.bumpScale.value = material.bumpScale;
  1230. }
  1231. if ( material.normalMap ) {
  1232. uniforms.normalMap.value = material.normalMap;
  1233. uniforms.normalScale.value.copy( material.normalScale );
  1234. }
  1235. if ( material.displacementMap ) {
  1236. uniforms.displacementMap.value = material.displacementMap;
  1237. uniforms.displacementScale.value = material.displacementScale;
  1238. uniforms.displacementBias.value = material.displacementBias;
  1239. }
  1240. }
  1241. function refreshUniformsStandard ( uniforms, material ) {
  1242. uniforms.roughness.value = material.roughness;
  1243. uniforms.metalness.value = material.metalness;
  1244. if ( material.roughnessMap ) {
  1245. uniforms.roughnessMap.value = material.roughnessMap;
  1246. }
  1247. if ( material.metalnessMap ) {
  1248. uniforms.metalnessMap.value = material.metalnessMap;
  1249. }
  1250. if ( material.lightMap ) {
  1251. uniforms.lightMap.value = material.lightMap;
  1252. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1253. }
  1254. if ( material.emissiveMap ) {
  1255. uniforms.emissiveMap.value = material.emissiveMap;
  1256. }
  1257. if ( material.bumpMap ) {
  1258. uniforms.bumpMap.value = material.bumpMap;
  1259. uniforms.bumpScale.value = material.bumpScale;
  1260. }
  1261. if ( material.normalMap ) {
  1262. uniforms.normalMap.value = material.normalMap;
  1263. uniforms.normalScale.value.copy( material.normalScale );
  1264. }
  1265. if ( material.displacementMap ) {
  1266. uniforms.displacementMap.value = material.displacementMap;
  1267. uniforms.displacementScale.value = material.displacementScale;
  1268. uniforms.displacementBias.value = material.displacementBias;
  1269. }
  1270. if ( material.envMap ) {
  1271. //uniforms.envMap.value = material.envMap; // part of uniforms common
  1272. uniforms.envMapIntensity.value = material.envMapIntensity;
  1273. }
  1274. }
  1275. function refreshUniformsPhysical ( uniforms, material ) {
  1276. uniforms.clearCoat.value = material.clearCoat;
  1277. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  1278. refreshUniformsStandard( uniforms, material );
  1279. }
  1280. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1281. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  1282. uniforms.ambientLightColor.needsUpdate = value;
  1283. uniforms.directionalLights.needsUpdate = value;
  1284. uniforms.pointLights.needsUpdate = value;
  1285. uniforms.spotLights.needsUpdate = value;
  1286. uniforms.hemisphereLights.needsUpdate = value;
  1287. }
  1288. // Lighting
  1289. function setupShadows ( lights ) {
  1290. var lightShadowsLength = 0;
  1291. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  1292. var light = lights[ i ];
  1293. if ( light.castShadow ) {
  1294. _lights.shadows[ lightShadowsLength ++ ] = light;
  1295. }
  1296. }
  1297. _lights.shadows.length = lightShadowsLength;
  1298. }
  1299. function setupLights ( lights, camera ) {
  1300. var l, ll, light,
  1301. r = 0, g = 0, b = 0,
  1302. color,
  1303. intensity,
  1304. distance,
  1305. shadowMap,
  1306. viewMatrix = camera.matrixWorldInverse,
  1307. directionalLength = 0,
  1308. pointLength = 0,
  1309. spotLength = 0,
  1310. hemiLength = 0;
  1311. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  1312. light = lights[ l ];
  1313. color = light.color;
  1314. intensity = light.intensity;
  1315. distance = light.distance;
  1316. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  1317. if ( light instanceof THREE.AmbientLight ) {
  1318. r += color.r * intensity;
  1319. g += color.g * intensity;
  1320. b += color.b * intensity;
  1321. } else if ( light instanceof THREE.DirectionalLight ) {
  1322. var uniforms = lightCache.get( light );
  1323. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  1324. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1325. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  1326. uniforms.direction.sub( _vector3 );
  1327. uniforms.direction.transformDirection( viewMatrix );
  1328. uniforms.shadow = light.castShadow;
  1329. if ( light.castShadow ) {
  1330. uniforms.shadowBias = light.shadow.bias;
  1331. uniforms.shadowRadius = light.shadow.radius;
  1332. uniforms.shadowMapSize = light.shadow.mapSize;
  1333. }
  1334. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  1335. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  1336. _lights.directional[ directionalLength ++ ] = uniforms;
  1337. } else if ( light instanceof THREE.SpotLight ) {
  1338. var uniforms = lightCache.get( light );
  1339. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  1340. uniforms.position.applyMatrix4( viewMatrix );
  1341. uniforms.color.copy( color ).multiplyScalar( intensity );
  1342. uniforms.distance = distance;
  1343. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1344. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  1345. uniforms.direction.sub( _vector3 );
  1346. uniforms.direction.transformDirection( viewMatrix );
  1347. uniforms.coneCos = Math.cos( light.angle );
  1348. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  1349. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  1350. uniforms.shadow = light.castShadow;
  1351. if ( light.castShadow ) {
  1352. uniforms.shadowBias = light.shadow.bias;
  1353. uniforms.shadowRadius = light.shadow.radius;
  1354. uniforms.shadowMapSize = light.shadow.mapSize;
  1355. }
  1356. _lights.spotShadowMap[ spotLength ] = shadowMap;
  1357. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  1358. _lights.spot[ spotLength ++ ] = uniforms;
  1359. } else if ( light instanceof THREE.PointLight ) {
  1360. var uniforms = lightCache.get( light );
  1361. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  1362. uniforms.position.applyMatrix4( viewMatrix );
  1363. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  1364. uniforms.distance = light.distance;
  1365. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  1366. uniforms.shadow = light.castShadow;
  1367. if ( light.castShadow ) {
  1368. uniforms.shadowBias = light.shadow.bias;
  1369. uniforms.shadowRadius = light.shadow.radius;
  1370. uniforms.shadowMapSize = light.shadow.mapSize;
  1371. }
  1372. _lights.pointShadowMap[ pointLength ] = shadowMap;
  1373. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  1374. _lights.pointShadowMatrix[ pointLength ] = new THREE.Matrix4();
  1375. }
  1376. // for point lights we set the shadow matrix to be a translation-only matrix
  1377. // equal to inverse of the light's position
  1378. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  1379. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  1380. _lights.point[ pointLength ++ ] = uniforms;
  1381. } else if ( light instanceof THREE.HemisphereLight ) {
  1382. var uniforms = lightCache.get( light );
  1383. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1384. uniforms.direction.transformDirection( viewMatrix );
  1385. uniforms.direction.normalize();
  1386. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  1387. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  1388. _lights.hemi[ hemiLength ++ ] = uniforms;
  1389. }
  1390. }
  1391. _lights.ambient[ 0 ] = r;
  1392. _lights.ambient[ 1 ] = g;
  1393. _lights.ambient[ 2 ] = b;
  1394. _lights.directional.length = directionalLength;
  1395. _lights.spot.length = spotLength;
  1396. _lights.point.length = pointLength;
  1397. _lights.hemi.length = hemiLength;
  1398. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length;
  1399. }
  1400. // GL state setting
  1401. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  1402. state.setCullFace( cullFace );
  1403. state.setFlipSided( frontFaceDirection === THREE.FrontFaceDirectionCW );
  1404. };
  1405. // Textures
  1406. function allocTextureUnit() {
  1407. var textureUnit = _usedTextureUnits;
  1408. if ( textureUnit >= capabilities.maxTextures ) {
  1409. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  1410. }
  1411. _usedTextureUnits += 1;
  1412. return textureUnit;
  1413. }
  1414. this.allocTextureUnit = allocTextureUnit;
  1415. // this.setTexture2D = setTexture2D;
  1416. this.setTexture2D = ( function() {
  1417. var warned = false;
  1418. // backwards compatibility: peel texture.texture
  1419. return function setTexture2D( texture, slot ) {
  1420. if ( texture instanceof THREE.WebGLRenderTarget ) {
  1421. if ( ! warned ) {
  1422. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  1423. warned = true;
  1424. }
  1425. texture = texture.texture;
  1426. }
  1427. textures.setTexture2D( texture, slot );
  1428. };
  1429. }() );
  1430. this.setTexture = ( function() {
  1431. var warned = false;
  1432. return function setTexture( texture, slot ) {
  1433. if ( ! warned ) {
  1434. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  1435. warned = true;
  1436. }
  1437. textures.setTexture2D( texture, slot );
  1438. };
  1439. }() );
  1440. this.setTextureCube = ( function() {
  1441. var warned = false;
  1442. return function setTextureCube( texture, slot ) {
  1443. // backwards compatibility: peel texture.texture
  1444. if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  1445. if ( ! warned ) {
  1446. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  1447. warned = true;
  1448. }
  1449. texture = texture.texture;
  1450. }
  1451. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  1452. // TODO: unify these code paths
  1453. if ( texture instanceof THREE.CubeTexture ||
  1454. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  1455. // CompressedTexture can have Array in image :/
  1456. // this function alone should take care of cube textures
  1457. textures.setTextureCube( texture, slot );
  1458. } else {
  1459. // assumed: texture property of THREE.WebGLRenderTargetCube
  1460. textures.setTextureCubeDynamic( texture, slot );
  1461. }
  1462. };
  1463. }() );
  1464. this.getCurrentRenderTarget = function() {
  1465. return _currentRenderTarget;
  1466. };
  1467. this.setRenderTarget = function ( renderTarget ) {
  1468. _currentRenderTarget = renderTarget;
  1469. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  1470. textures.setupRenderTarget( renderTarget );
  1471. }
  1472. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  1473. var framebuffer;
  1474. if ( renderTarget ) {
  1475. var renderTargetProperties = properties.get( renderTarget );
  1476. if ( isCube ) {
  1477. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  1478. } else {
  1479. framebuffer = renderTargetProperties.__webglFramebuffer;
  1480. }
  1481. _currentScissor.copy( renderTarget.scissor );
  1482. _currentScissorTest = renderTarget.scissorTest;
  1483. _currentViewport.copy( renderTarget.viewport );
  1484. } else {
  1485. framebuffer = null;
  1486. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  1487. _currentScissorTest = _scissorTest;
  1488. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  1489. }
  1490. if ( _currentFramebuffer !== framebuffer ) {
  1491. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1492. _currentFramebuffer = framebuffer;
  1493. }
  1494. state.scissor( _currentScissor );
  1495. state.setScissorTest( _currentScissorTest );
  1496. state.viewport( _currentViewport );
  1497. if ( isCube ) {
  1498. var textureProperties = properties.get( renderTarget.texture );
  1499. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  1500. }
  1501. };
  1502. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  1503. if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
  1504. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1505. return;
  1506. }
  1507. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1508. if ( framebuffer ) {
  1509. var restore = false;
  1510. if ( framebuffer !== _currentFramebuffer ) {
  1511. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1512. restore = true;
  1513. }
  1514. try {
  1515. var texture = renderTarget.texture;
  1516. if ( texture.format !== THREE.RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  1517. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  1518. return;
  1519. }
  1520. if ( texture.type !== THREE.UnsignedByteType &&
  1521. paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) &&
  1522. ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) &&
  1523. ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  1524. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1525. return;
  1526. }
  1527. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  1528. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1529. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1530. _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
  1531. }
  1532. } else {
  1533. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  1534. }
  1535. } finally {
  1536. if ( restore ) {
  1537. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  1538. }
  1539. }
  1540. }
  1541. };
  1542. // Map three.js constants to WebGL constants
  1543. function paramThreeToGL ( p ) {
  1544. var extension;
  1545. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  1546. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  1547. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  1548. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  1549. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  1550. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  1551. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  1552. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  1553. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  1554. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  1555. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  1556. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  1557. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  1558. if ( p === THREE.ByteType ) return _gl.BYTE;
  1559. if ( p === THREE.ShortType ) return _gl.SHORT;
  1560. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  1561. if ( p === THREE.IntType ) return _gl.INT;
  1562. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  1563. if ( p === THREE.FloatType ) return _gl.FLOAT;
  1564. extension = extensions.get( 'OES_texture_half_float' );
  1565. if ( extension !== null ) {
  1566. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  1567. }
  1568. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  1569. if ( p === THREE.RGBFormat ) return _gl.RGB;
  1570. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  1571. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  1572. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  1573. if ( p === THREE.DepthFormat ) return _gl.DEPTH_COMPONENT;
  1574. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  1575. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  1576. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  1577. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  1578. if ( p === THREE.OneFactor ) return _gl.ONE;
  1579. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  1580. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  1581. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  1582. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  1583. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  1584. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  1585. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  1586. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  1587. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  1588. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  1589. if ( extension !== null ) {
  1590. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  1591. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  1592. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  1593. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  1594. }
  1595. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  1596. if ( extension !== null ) {
  1597. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  1598. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  1599. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  1600. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  1601. }
  1602. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  1603. if ( extension !== null ) {
  1604. if ( p === THREE.RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  1605. }
  1606. extension = extensions.get( 'EXT_blend_minmax' );
  1607. if ( extension !== null ) {
  1608. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  1609. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  1610. }
  1611. return 0;
  1612. }
  1613. };