WebGLRenderer.js 69 KB

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