WebGLRenderer.js 66 KB

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