WebGLRenderer.js 62 KB

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