WebGLRenderer.js 59 KB

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