WebGLRenderer.js 68 KB

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