WebGLRenderer.js 64 KB

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