WebGLRenderer.js 68 KB

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