WebGLRenderer.js 66 KB

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