WebGLRenderer.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928
  1. /**
  2. * @author supereggbert / http://www.paulbrunt.co.uk/
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author alteredq / http://alteredqualia.com/
  5. */
  6. THREE.WebGLRenderer = function ( parameters ) {
  7. // Currently you can use just up to 4 directional / point lights total.
  8. // Chrome barfs on shader linking when there are more than 4 lights :(
  9. // The problem comes from shader using too many varying vectors.
  10. // This is not GPU limitation as the same shader works ok in Firefox
  11. // and Chrome with "--use-gl=desktop" flag.
  12. // Difference comes from Chrome on Windows using by default ANGLE,
  13. // thus going DirectX9 route (while FF uses OpenGL).
  14. // See http://code.google.com/p/chromium/issues/detail?id=63491
  15. var _canvas = document.createElement( 'canvas' ), _gl,
  16. _oldProgram, _uberProgram,
  17. _modelViewMatrix = new THREE.Matrix4(), _normalMatrix,
  18. _viewMatrixArray = new Float32Array(16),
  19. _modelViewMatrixArray = new Float32Array(16),
  20. _projectionMatrixArray = new Float32Array(16),
  21. _normalMatrixArray = new Float32Array(9),
  22. _objectMatrixArray = new Float32Array(16),
  23. // ubershader material constants
  24. LAMBERT = 1, PHONG = 2,
  25. // heuristics to create shader parameters according to lights in the scene
  26. // (not to blow over maxLights budget)
  27. maxLightCount = allocateLights( parameters.scene, 4 );
  28. fog = parameters.scene ? parameters.scene.fog : null,
  29. antialias = parameters.antialias != undefined ? parameters.antialias : true,
  30. clearColor = parameters.clearColor ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  31. clearAlpha = parameters.clearAlpha ? parameters.clearAlpha : 0;
  32. this.domElement = _canvas;
  33. this.autoClear = true;
  34. initGL( antialias, clearColor, clearAlpha );
  35. _uberProgram = initUbershader( maxLightCount.directional, maxLightCount.point, fog );
  36. _oldProgram = _uberProgram;
  37. //alert( dumpObject( getGLParams() ) );
  38. this.setSize = function ( width, height ) {
  39. _canvas.width = width;
  40. _canvas.height = height;
  41. _gl.viewport( 0, 0, _canvas.width, _canvas.height );
  42. };
  43. this.setClearColor = function( hex, alpha ) {
  44. var color = new THREE.Color( hex );
  45. _gl.clearColor( color.r, color.g, color.b, alpha );
  46. };
  47. this.clear = function () {
  48. _gl.clear( _gl.COLOR_BUFFER_BIT | _gl.DEPTH_BUFFER_BIT );
  49. };
  50. this.setupLights = function ( program, lights ) {
  51. var l, ll, light, r, g, b,
  52. ambientLights = [], pointLights = [], directionalLights = [],
  53. colors = [], positions = [];
  54. _gl.uniform1i( program.uniforms.enableLighting, lights.length );
  55. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  56. light = lights[ l ];
  57. if ( light instanceof THREE.AmbientLight ) {
  58. ambientLights.push( light );
  59. } else if ( light instanceof THREE.DirectionalLight ) {
  60. directionalLights.push( light );
  61. } else if( light instanceof THREE.PointLight ) {
  62. pointLights.push( light );
  63. }
  64. }
  65. // sum all ambient lights
  66. r = g = b = 0.0;
  67. for ( l = 0, ll = ambientLights.length; l < ll; l++ ) {
  68. r += ambientLights[ l ].color.r;
  69. g += ambientLights[ l ].color.g;
  70. b += ambientLights[ l ].color.b;
  71. }
  72. _gl.uniform3f( program.uniforms.ambientLightColor, r, g, b );
  73. // pass directional lights as float arrays
  74. colors = []; positions = [];
  75. for ( l = 0, ll = directionalLights.length; l < ll; l++ ) {
  76. light = directionalLights[ l ];
  77. colors.push( light.color.r * light.intensity );
  78. colors.push( light.color.g * light.intensity );
  79. colors.push( light.color.b * light.intensity );
  80. positions.push( light.position.x );
  81. positions.push( light.position.y );
  82. positions.push( light.position.z );
  83. }
  84. if ( directionalLights.length ) {
  85. _gl.uniform1i( program.uniforms.directionalLightNumber, directionalLights.length );
  86. _gl.uniform3fv( program.uniforms.directionalLightDirection, positions );
  87. _gl.uniform3fv( program.uniforms.directionalLightColor, colors );
  88. }
  89. // pass point lights as float arrays
  90. colors = []; positions = [];
  91. for ( l = 0, ll = pointLights.length; l < ll; l++ ) {
  92. light = pointLights[ l ];
  93. colors.push( light.color.r * light.intensity );
  94. colors.push( light.color.g * light.intensity );
  95. colors.push( light.color.b * light.intensity );
  96. positions.push( light.position.x );
  97. positions.push( light.position.y );
  98. positions.push( light.position.z );
  99. }
  100. if ( pointLights.length ) {
  101. _gl.uniform1i( program.uniforms.pointLightNumber, pointLights.length );
  102. _gl.uniform3fv( program.uniforms.pointLightPosition, positions );
  103. _gl.uniform3fv( program.uniforms.pointLightColor, colors );
  104. }
  105. };
  106. this.createBuffers = function ( object, g ) {
  107. var f, fl, fi, face, vertexNormals, normal, uv, v1, v2, v3, v4, t1, t2, t3, t4, m, ml, i,
  108. faceArray = [],
  109. lineArray = [],
  110. vertexArray = [],
  111. normalArray = [],
  112. tangentArray = [],
  113. uvArray = [],
  114. vertexIndex = 0,
  115. geometryChunk = object.geometry.geometryChunks[ g ],
  116. needsSmoothNormals = bufferNeedsSmoothNormals ( geometryChunk, object );
  117. for ( f = 0, fl = geometryChunk.faces.length; f < fl; f++ ) {
  118. fi = geometryChunk.faces[ f ];
  119. face = object.geometry.faces[ fi ];
  120. vertexNormals = face.vertexNormals;
  121. faceNormal = face.normal;
  122. uv = object.geometry.uvs[ fi ];
  123. if ( face instanceof THREE.Face3 ) {
  124. v1 = object.geometry.vertices[ face.a ].position;
  125. v2 = object.geometry.vertices[ face.b ].position;
  126. v3 = object.geometry.vertices[ face.c ].position;
  127. vertexArray.push( v1.x, v1.y, v1.z );
  128. vertexArray.push( v2.x, v2.y, v2.z );
  129. vertexArray.push( v3.x, v3.y, v3.z );
  130. if ( object.geometry.hasTangents ) {
  131. t1 = object.geometry.vertices[ face.a ].tangent;
  132. t2 = object.geometry.vertices[ face.b ].tangent;
  133. t3 = object.geometry.vertices[ face.c ].tangent;
  134. tangentArray.push( t1.x, t1.y, t1.z, t1.w );
  135. tangentArray.push( t2.x, t2.y, t2.z, t2.w );
  136. tangentArray.push( t3.x, t3.y, t3.z, t3.w );
  137. }
  138. if ( vertexNormals.length == 3 && needsSmoothNormals ) {
  139. for ( i = 0; i < 3; i ++ ) {
  140. normalArray.push( vertexNormals[ i ].x, vertexNormals[ i ].y, vertexNormals[ i ].z );
  141. }
  142. } else {
  143. for ( i = 0; i < 3; i ++ ) {
  144. normalArray.push( faceNormal.x, faceNormal.y, faceNormal.z );
  145. }
  146. }
  147. if ( uv ) {
  148. for ( i = 0; i < 3; i ++ ) {
  149. uvArray.push( uv[ i ].u, uv[ i ].v );
  150. }
  151. }
  152. faceArray.push( vertexIndex, vertexIndex + 1, vertexIndex + 2 );
  153. // TODO: don't add lines that already exist (faces sharing edge)
  154. lineArray.push( vertexIndex, vertexIndex + 1 );
  155. lineArray.push( vertexIndex, vertexIndex + 2 );
  156. lineArray.push( vertexIndex + 1, vertexIndex + 2 );
  157. vertexIndex += 3;
  158. } else if ( face instanceof THREE.Face4 ) {
  159. v1 = object.geometry.vertices[ face.a ].position;
  160. v2 = object.geometry.vertices[ face.b ].position;
  161. v3 = object.geometry.vertices[ face.c ].position;
  162. v4 = object.geometry.vertices[ face.d ].position;
  163. vertexArray.push( v1.x, v1.y, v1.z );
  164. vertexArray.push( v2.x, v2.y, v2.z );
  165. vertexArray.push( v3.x, v3.y, v3.z );
  166. vertexArray.push( v4.x, v4.y, v4.z );
  167. if ( object.geometry.hasTangents ) {
  168. t1 = object.geometry.vertices[ face.a ].tangent;
  169. t2 = object.geometry.vertices[ face.b ].tangent;
  170. t3 = object.geometry.vertices[ face.c ].tangent;
  171. t4 = object.geometry.vertices[ face.d ].tangent;
  172. tangentArray.push( t1.x, t1.y, t1.z, t1.w );
  173. tangentArray.push( t2.x, t2.y, t2.z, t2.w );
  174. tangentArray.push( t3.x, t3.y, t3.z, t3.w );
  175. tangentArray.push( t4.x, t4.y, t4.z, t4.w );
  176. }
  177. if ( vertexNormals.length == 4 && needsSmoothNormals ) {
  178. for ( i = 0; i < 4; i ++ ) {
  179. normalArray.push( vertexNormals[ i ].x, vertexNormals[ i ].y, vertexNormals[ i ].z );
  180. }
  181. } else {
  182. for ( i = 0; i < 4; i ++ ) {
  183. normalArray.push( faceNormal.x, faceNormal.y, faceNormal.z );
  184. }
  185. }
  186. if ( uv ) {
  187. for ( i = 0; i < 4; i ++ ) {
  188. uvArray.push( uv[ i ].u, uv[ i ].v );
  189. }
  190. }
  191. faceArray.push( vertexIndex, vertexIndex + 1, vertexIndex + 2 );
  192. faceArray.push( vertexIndex, vertexIndex + 2, vertexIndex + 3 );
  193. // TODO: don't add lines that already exist (faces sharing edge)
  194. lineArray.push( vertexIndex, vertexIndex + 1 );
  195. lineArray.push( vertexIndex, vertexIndex + 2 );
  196. lineArray.push( vertexIndex, vertexIndex + 3 );
  197. lineArray.push( vertexIndex + 1, vertexIndex + 2 );
  198. lineArray.push( vertexIndex + 2, vertexIndex + 3 );
  199. vertexIndex += 4;
  200. }
  201. }
  202. if ( !vertexArray.length ) {
  203. return;
  204. }
  205. geometryChunk.__webGLVertexBuffer = _gl.createBuffer();
  206. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryChunk.__webGLVertexBuffer );
  207. _gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( vertexArray ), _gl.STATIC_DRAW );
  208. geometryChunk.__webGLNormalBuffer = _gl.createBuffer();
  209. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryChunk.__webGLNormalBuffer );
  210. _gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( normalArray ), _gl.STATIC_DRAW );
  211. if ( object.geometry.hasTangents ) {
  212. geometryChunk.__webGLTangentBuffer = _gl.createBuffer();
  213. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryChunk.__webGLTangentBuffer );
  214. _gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( tangentArray ), _gl.STATIC_DRAW );
  215. }
  216. if ( uvArray.length > 0 ) {
  217. geometryChunk.__webGLUVBuffer = _gl.createBuffer();
  218. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryChunk.__webGLUVBuffer );
  219. _gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( uvArray ), _gl.STATIC_DRAW );
  220. }
  221. geometryChunk.__webGLFaceBuffer = _gl.createBuffer();
  222. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryChunk.__webGLFaceBuffer );
  223. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( faceArray ), _gl.STATIC_DRAW );
  224. geometryChunk.__webGLLineBuffer = _gl.createBuffer();
  225. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryChunk.__webGLLineBuffer );
  226. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( lineArray ), _gl.STATIC_DRAW );
  227. geometryChunk.__webGLFaceCount = faceArray.length;
  228. geometryChunk.__webGLLineCount = lineArray.length;
  229. };
  230. function setMaterialShaders( material, shaders ) {
  231. material.fragment_shader = shaders.fragment_shader;
  232. material.vertex_shader = shaders.vertex_shader;
  233. material.uniforms = Uniforms.clone( shaders.uniforms );
  234. };
  235. function refreshUniforms( material, fog ) {
  236. material.uniforms.color.value.setHex( material.color.hex );
  237. material.uniforms.opacity.value = material.opacity;
  238. material.uniforms.map.texture = material.map;
  239. material.uniforms.env_map.texture = material.env_map;
  240. material.uniforms.reflectivity.value = material.reflectivity;
  241. material.uniforms.refraction_ratio.value = material.refraction_ratio;
  242. material.uniforms.combine.value = material.combine;
  243. material.uniforms.useRefract.value = material.env_map && material.env_map.mapping instanceof THREE.CubeRefractionMapping;
  244. if ( fog ) {
  245. material.uniforms.fogColor.value.setHex( fog.color.hex );
  246. if ( fog instanceof THREE.Fog ) {
  247. material.uniforms.fogNear.value = fog.near;
  248. material.uniforms.fogFar.value = fog.far;
  249. } else if ( fog instanceof THREE.FogExp2 ) {
  250. material.uniforms.fogDensity.value = fog.density;
  251. }
  252. }
  253. };
  254. this.renderBuffer = function ( camera, lights, fog, material, geometryChunk ) {
  255. var mColor, mOpacity, mReflectivity,
  256. mWireframe, mLineWidth, mBlending,
  257. mAmbient, mSpecular, mShininess,
  258. mMap, envMap, mixEnvMap,
  259. mRefractionRatio, useRefract,
  260. program, u, identifiers, attributes;
  261. if ( material instanceof THREE.MeshShaderMaterial ||
  262. material instanceof THREE.MeshDepthMaterial ||
  263. material instanceof THREE.MeshNormalMaterial ||
  264. material instanceof THREE.MeshBasicMaterial ) {
  265. if ( !material.program ) {
  266. if ( material instanceof THREE.MeshDepthMaterial ) {
  267. setMaterialShaders( material, THREE.ShaderLib[ 'depth' ] );
  268. material.uniforms.mNear.value = camera.near;
  269. material.uniforms.mFar.value = camera.far;
  270. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  271. setMaterialShaders( material, THREE.ShaderLib[ 'normal' ] );
  272. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  273. setMaterialShaders( material, THREE.ShaderLib[ 'basic' ] );
  274. refreshUniforms( material, fog );
  275. }
  276. material.program = buildProgram( material.fragment_shader, material.vertex_shader, { fog: fog, map: material.map, env_map: material.env_map } );
  277. identifiers = [ 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'objectMatrix', 'cameraPosition' ];
  278. for( u in material.uniforms ) {
  279. identifiers.push(u);
  280. }
  281. cacheUniformLocations( material.program, identifiers );
  282. cacheAttributeLocations( material.program, [ "position", "normal", "uv", "tangent" ] );
  283. }
  284. program = material.program;
  285. } else {
  286. program = _uberProgram;
  287. }
  288. if( program != _oldProgram ) {
  289. _gl.useProgram( program );
  290. _oldProgram = program;
  291. }
  292. if ( program == _uberProgram ) {
  293. this.setupLights( program, lights );
  294. }
  295. this.loadCamera( program, camera );
  296. this.loadMatrices( program );
  297. if ( material instanceof THREE.MeshBasicMaterial ) {
  298. refreshUniforms( material, fog );
  299. }
  300. if ( material instanceof THREE.MeshShaderMaterial ||
  301. material instanceof THREE.MeshDepthMaterial ||
  302. material instanceof THREE.MeshNormalMaterial ||
  303. material instanceof THREE.MeshBasicMaterial ) {
  304. mWireframe = material.wireframe;
  305. mLineWidth = material.wireframe_linewidth;
  306. mBlending = material.blending;
  307. setUniforms( program, material.uniforms );
  308. }
  309. if ( material instanceof THREE.MeshPhongMaterial ||
  310. material instanceof THREE.MeshLambertMaterial ) {
  311. mColor = material.color;
  312. mOpacity = material.opacity;
  313. mWireframe = material.wireframe;
  314. mLineWidth = material.wireframe_linewidth;
  315. mBlending = material.blending;
  316. mMap = material.map;
  317. envMap = material.env_map;
  318. mixEnvMap = material.combine == THREE.MixOperation;
  319. mReflectivity = material.reflectivity;
  320. useRefract = material.env_map && material.env_map.mapping instanceof THREE.CubeRefractionMapping;
  321. mRefractionRatio = material.refraction_ratio;
  322. _gl.uniform4f( program.uniforms.mColor, mColor.r * mOpacity, mColor.g * mOpacity, mColor.b * mOpacity, mOpacity );
  323. _gl.uniform1i( program.uniforms.mixEnvMap, mixEnvMap );
  324. _gl.uniform1f( program.uniforms.mReflectivity, mReflectivity );
  325. _gl.uniform1i( program.uniforms.useRefract, useRefract );
  326. _gl.uniform1f( program.uniforms.mRefractionRatio, mRefractionRatio );
  327. if ( fog ) {
  328. _gl.uniform3f( program.uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  329. if ( fog instanceof THREE.Fog ) {
  330. _gl.uniform1f( program.uniforms.fogNear, fog.near );
  331. _gl.uniform1f( program.uniforms.fogFar, fog.far );
  332. } else if ( fog instanceof THREE.FogExp2 ) {
  333. _gl.uniform1f( program.uniforms.fogDensity, fog.density );
  334. }
  335. }
  336. }
  337. if ( material instanceof THREE.MeshPhongMaterial ) {
  338. mAmbient = material.ambient;
  339. mSpecular = material.specular;
  340. mShininess = material.shininess;
  341. _gl.uniform4f( program.uniforms.mAmbient, mAmbient.r, mAmbient.g, mAmbient.b, mOpacity );
  342. _gl.uniform4f( program.uniforms.mSpecular, mSpecular.r, mSpecular.g, mSpecular.b, mOpacity );
  343. _gl.uniform1f( program.uniforms.mShininess, mShininess );
  344. _gl.uniform1i( program.uniforms.material, PHONG );
  345. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  346. _gl.uniform1i( program.uniforms.material, LAMBERT );
  347. }
  348. if ( mMap ) {
  349. setTexture( mMap, 0 );
  350. _gl.uniform1i( program.uniforms.tMap, 0 );
  351. _gl.uniform1i( program.uniforms.enableMap, 1 );
  352. } else {
  353. _gl.uniform1i( program.uniforms.enableMap, 0 );
  354. }
  355. if ( envMap ) {
  356. setCubeTexture( envMap, 1 );
  357. _gl.uniform1i( program.uniforms.tCube, 1 );
  358. _gl.uniform1i( program.uniforms.enableCubeMap, 1 );
  359. } else {
  360. _gl.uniform1i( program.uniforms.enableCubeMap, 0 );
  361. }
  362. attributes = program.attributes;
  363. // vertices
  364. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryChunk.__webGLVertexBuffer );
  365. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  366. _gl.enableVertexAttribArray( attributes.position );
  367. // normals
  368. if ( attributes.normal >= 0 ) {
  369. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryChunk.__webGLNormalBuffer );
  370. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  371. _gl.enableVertexAttribArray( attributes.normal );
  372. }
  373. // tangents
  374. if ( attributes.tangent >= 0 ) {
  375. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryChunk.__webGLTangentBuffer );
  376. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  377. _gl.enableVertexAttribArray( attributes.tangent );
  378. }
  379. // uvs
  380. if ( attributes.uv >= 0 ) {
  381. if ( geometryChunk.__webGLUVBuffer ) {
  382. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryChunk.__webGLUVBuffer );
  383. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  384. _gl.enableVertexAttribArray( attributes.uv );
  385. } else {
  386. _gl.disableVertexAttribArray( attributes.uv );
  387. }
  388. }
  389. // render triangles
  390. if ( ! mWireframe ) {
  391. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryChunk.__webGLFaceBuffer );
  392. _gl.drawElements( _gl.TRIANGLES, geometryChunk.__webGLFaceCount, _gl.UNSIGNED_SHORT, 0 );
  393. // render lines
  394. } else {
  395. _gl.lineWidth( mLineWidth );
  396. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryChunk.__webGLLineBuffer );
  397. _gl.drawElements( _gl.LINES, geometryChunk.__webGLLineCount, _gl.UNSIGNED_SHORT, 0 );
  398. }
  399. };
  400. this.renderPass = function ( camera, lights, fog, object, geometryChunk, blending, transparent ) {
  401. var i, l, m, ml, material, meshMaterial;
  402. for ( m = 0, ml = object.materials.length; m < ml; m++ ) {
  403. meshMaterial = object.materials[ m ];
  404. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  405. for ( i = 0, l = geometryChunk.materials.length; i < l; i++ ) {
  406. material = geometryChunk.materials[ i ];
  407. if ( material && material.blending == blending && ( material.opacity < 1.0 == transparent ) ) {
  408. this.setBlending( material.blending );
  409. this.renderBuffer( camera, lights, fog, material, geometryChunk );
  410. }
  411. }
  412. } else {
  413. material = meshMaterial;
  414. if ( material && material.blending == blending && ( material.opacity < 1.0 == transparent ) ) {
  415. this.setBlending( material.blending );
  416. this.renderBuffer( camera, lights, fog, material, geometryChunk );
  417. }
  418. }
  419. }
  420. };
  421. this.render = function( scene, camera ) {
  422. var o, ol, webGLObject, object, buffer,
  423. lights = scene.lights,
  424. fog = scene.fog;
  425. this.initWebGLObjects( scene );
  426. if ( this.autoClear ) {
  427. this.clear();
  428. }
  429. camera.autoUpdateMatrix && camera.updateMatrix();
  430. _viewMatrixArray.set( camera.matrix.flatten() );
  431. _projectionMatrixArray.set( camera.projectionMatrix.flatten() );
  432. // opaque pass
  433. for ( o = 0, ol = scene.__webGLObjects.length; o < ol; o++ ) {
  434. webGLObject = scene.__webGLObjects[ o ];
  435. object = webGLObject.object;
  436. buffer = webGLObject.buffer;
  437. if ( object.visible ) {
  438. this.setupMatrices( object, camera );
  439. this.renderPass( camera, lights, fog, object, buffer, THREE.NormalBlending, false );
  440. }
  441. }
  442. // transparent pass
  443. for ( o = 0, ol = scene.__webGLObjects.length; o < ol; o++ ) {
  444. webGLObject = scene.__webGLObjects[ o ];
  445. object = webGLObject.object;
  446. buffer = webGLObject.buffer;
  447. if ( object.visible ) {
  448. this.setupMatrices( object, camera );
  449. // opaque blended materials
  450. this.renderPass( camera, lights, fog, object, buffer, THREE.AdditiveBlending, false );
  451. this.renderPass( camera, lights, fog, object, buffer, THREE.SubtractiveBlending, false );
  452. // transparent blended materials
  453. this.renderPass( camera, lights, fog, object, buffer, THREE.AdditiveBlending, true );
  454. this.renderPass( camera, lights, fog, object, buffer, THREE.SubtractiveBlending, true );
  455. // transparent normal materials
  456. this.renderPass( camera, lights, fog, object, buffer, THREE.NormalBlending, true );
  457. }
  458. }
  459. };
  460. this.initWebGLObjects = function( scene ) {
  461. var o, ol, object, globject, g, geometryChunk, objmap;
  462. if ( !scene.__webGLObjects ) {
  463. scene.__webGLObjects = [];
  464. scene.__webGLObjectsMap = {};
  465. }
  466. for ( o = 0, ol = scene.objects.length; o < ol; o++ ) {
  467. object = scene.objects[ o ];
  468. if ( scene.__webGLObjectsMap[ object.id ] == undefined ) {
  469. scene.__webGLObjectsMap[ object.id ] = {};
  470. }
  471. objmap = scene.__webGLObjectsMap[ object.id ];
  472. if ( object instanceof THREE.Mesh ) {
  473. // create separate VBOs per geometry chunk
  474. for ( g in object.geometry.geometryChunks ) {
  475. geometryChunk = object.geometry.geometryChunks[ g ];
  476. // initialise VBO on the first access
  477. if( ! geometryChunk.__webGLVertexBuffer ) {
  478. this.createBuffers( object, g );
  479. }
  480. // create separate wrapper per each use of VBO
  481. if ( objmap[ g ] == undefined ) {
  482. globject = { buffer: geometryChunk, object: object };
  483. scene.__webGLObjects.push( globject );
  484. objmap[ g ] = 1;
  485. }
  486. }
  487. }/* else if ( object instanceof THREE.Line ) {
  488. } else if ( object instanceof THREE.Particle ) {
  489. }*/
  490. }
  491. };
  492. this.removeObject = function ( scene, object ) {
  493. var o, ol, zobject;
  494. for ( o = scene.__webGLObjects.length - 1; o >= 0; o-- ) {
  495. zobject = scene.__webGLObjects[ o ].object;
  496. if ( object == zobject ) {
  497. scene.__webGLObjects.splice( o, 1 );
  498. }
  499. }
  500. };
  501. this.setupMatrices = function ( object, camera ) {
  502. object.autoUpdateMatrix && object.updateMatrix();
  503. _modelViewMatrix.multiply( camera.matrix, object.matrix );
  504. _modelViewMatrixArray.set( _modelViewMatrix.flatten() );
  505. _normalMatrix = THREE.Matrix4.makeInvert3x3( _modelViewMatrix ).transpose();
  506. _normalMatrixArray.set( _normalMatrix.m );
  507. _objectMatrixArray.set( object.matrix.flatten() );
  508. };
  509. this.loadMatrices = function ( program ) {
  510. _gl.uniformMatrix4fv( program.uniforms.viewMatrix, false, _viewMatrixArray );
  511. _gl.uniformMatrix4fv( program.uniforms.modelViewMatrix, false, _modelViewMatrixArray );
  512. _gl.uniformMatrix4fv( program.uniforms.projectionMatrix, false, _projectionMatrixArray );
  513. _gl.uniformMatrix3fv( program.uniforms.normalMatrix, false, _normalMatrixArray );
  514. _gl.uniformMatrix4fv( program.uniforms.objectMatrix, false, _objectMatrixArray );
  515. };
  516. this.loadCamera = function( program, camera ) {
  517. _gl.uniform3f( program.uniforms.cameraPosition, camera.position.x, camera.position.y, camera.position.z );
  518. };
  519. this.setBlending = function( blending ) {
  520. switch ( blending ) {
  521. case THREE.AdditiveBlending:
  522. _gl.blendEquation( _gl.FUNC_ADD );
  523. _gl.blendFunc( _gl.ONE, _gl.ONE );
  524. break;
  525. case THREE.SubtractiveBlending:
  526. //_gl.blendEquation( _gl.FUNC_SUBTRACT );
  527. _gl.blendFunc( _gl.DST_COLOR, _gl.ZERO );
  528. break;
  529. default:
  530. _gl.blendEquation( _gl.FUNC_ADD );
  531. _gl.blendFunc( _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  532. break;
  533. }
  534. };
  535. this.setFaceCulling = function ( cullFace, frontFace ) {
  536. if ( cullFace ) {
  537. if ( !frontFace || frontFace == "ccw" ) {
  538. _gl.frontFace( _gl.CCW );
  539. } else {
  540. _gl.frontFace( _gl.CW );
  541. }
  542. if( cullFace == "back" ) {
  543. _gl.cullFace( _gl.BACK );
  544. } else if( cullFace == "front" ) {
  545. _gl.cullFace( _gl.FRONT );
  546. } else {
  547. _gl.cullFace( _gl.FRONT_AND_BACK );
  548. }
  549. _gl.enable( _gl.CULL_FACE );
  550. } else {
  551. _gl.disable( _gl.CULL_FACE );
  552. }
  553. };
  554. this.supportsVertexTextures = function() {
  555. return maxVertexTextures() > 0;
  556. };
  557. function maxVertexTextures() {
  558. return _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  559. };
  560. function initGL( antialias, clearColor, clearAlpha ) {
  561. try {
  562. _gl = _canvas.getContext( 'experimental-webgl', { antialias: antialias } );
  563. } catch(e) { }
  564. if (!_gl) {
  565. alert("WebGL not supported");
  566. throw "cannot create webgl context";
  567. }
  568. _gl.clearColor( 0, 0, 0, 1 );
  569. _gl.clearDepth( 1 );
  570. _gl.enable( _gl.DEPTH_TEST );
  571. _gl.depthFunc( _gl.LEQUAL );
  572. _gl.frontFace( _gl.CCW );
  573. _gl.cullFace( _gl.BACK );
  574. _gl.enable( _gl.CULL_FACE );
  575. _gl.enable( _gl.BLEND );
  576. _gl.blendFunc( _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  577. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  578. };
  579. function generateFragmentShader( maxDirLights, maxPointLights ) {
  580. var chunks = [
  581. maxDirLights ? "#define MAX_DIR_LIGHTS " + maxDirLights : "",
  582. maxPointLights ? "#define MAX_POINT_LIGHTS " + maxPointLights : "",
  583. "uniform int material;", // 1 - Lambert, 2 - Phong
  584. "uniform bool enableMap;",
  585. "uniform bool enableCubeMap;",
  586. "uniform bool mixEnvMap;",
  587. "uniform samplerCube tCube;",
  588. "uniform float mReflectivity;",
  589. "uniform sampler2D tMap;",
  590. "uniform vec4 mColor;",
  591. "uniform float mOpacity;",
  592. "uniform vec4 mAmbient;",
  593. "uniform vec4 mSpecular;",
  594. "uniform float mShininess;",
  595. THREE.Snippets[ "fog_uniforms" ],
  596. "uniform int pointLightNumber;",
  597. "uniform int directionalLightNumber;",
  598. maxDirLights ? "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];" : "",
  599. "varying vec3 vNormal;",
  600. "varying vec2 vUv;",
  601. "varying vec3 vLightWeighting;",
  602. maxPointLights ? "varying vec3 vPointLightVector[ MAX_POINT_LIGHTS ];" : "",
  603. "varying vec3 vViewPosition;",
  604. "varying vec3 vReflect;",
  605. "void main() {",
  606. "vec4 mapColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  607. "vec4 cubeColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  608. // diffuse map
  609. "if ( enableMap ) {",
  610. "mapColor = texture2D( tMap, vUv );",
  611. "}",
  612. // cube map
  613. "if ( enableCubeMap ) {",
  614. "cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  615. // "cubeColor.r = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) ).r;",
  616. // "cubeColor.g = textureCube( tCube, vec3( -vReflect.x + 0.005, vReflect.yz ) ).g;",
  617. // "cubeColor.b = textureCube( tCube, vec3( -vReflect.x + 0.01, vReflect.yz ) ).b;",
  618. "}",
  619. // Blinn-Phong
  620. // based on o3d example
  621. "if ( material == 2 ) { ",
  622. "vec3 normal = normalize( vNormal );",
  623. "vec3 viewPosition = normalize( vViewPosition );",
  624. // point lights
  625. maxPointLights ? "vec4 pointDiffuse = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",
  626. maxPointLights ? "vec4 pointSpecular = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",
  627. maxPointLights ? "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {" : "",
  628. maxPointLights ? "vec3 pointVector = normalize( vPointLightVector[ i ] );" : "",
  629. maxPointLights ? "vec3 pointHalfVector = normalize( vPointLightVector[ i ] + vViewPosition );" : "",
  630. maxPointLights ? "float pointDotNormalHalf = dot( normal, pointHalfVector );" : "",
  631. maxPointLights ? "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );" : "",
  632. // Ternary conditional is from the original o3d shader. Here it produces abrupt dark cutoff artefacts.
  633. // Using just pow works ok in Chrome, but makes different artefact in Firefox 4.
  634. // Zeroing on negative pointDotNormalHalf seems to work in both.
  635. //"float specularCompPoint = dot( normal, pointVector ) < 0.0 || pointDotNormalHalf < 0.0 ? 0.0 : pow( pointDotNormalHalf, mShininess );",
  636. //"float specularCompPoint = pow( pointDotNormalHalf, mShininess );",
  637. //"float pointSpecularWeight = pointDotNormalHalf < 0.0 ? 0.0 : pow( pointDotNormalHalf, mShininess );",
  638. // Ternary conditional inside for loop breaks Chrome shader linking.
  639. // Must do it with if.
  640. maxPointLights ? "float pointSpecularWeight = 0.0;" : "",
  641. maxPointLights ? "if ( pointDotNormalHalf >= 0.0 )" : "",
  642. maxPointLights ? "pointSpecularWeight = pow( pointDotNormalHalf, mShininess );" : "",
  643. maxPointLights ? "pointDiffuse += mColor * pointDiffuseWeight;" : "",
  644. maxPointLights ? "pointSpecular += mSpecular * pointSpecularWeight;" : "",
  645. maxPointLights ? "}" : "",
  646. // directional lights
  647. maxDirLights ? "vec4 dirDiffuse = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",
  648. maxDirLights ? "vec4 dirSpecular = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",
  649. maxDirLights ? "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {" : "",
  650. maxDirLights ? "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );" : "",
  651. maxDirLights ? "vec3 dirVector = normalize( lDirection.xyz );" : "",
  652. maxDirLights ? "vec3 dirHalfVector = normalize( lDirection.xyz + vViewPosition );" : "",
  653. maxDirLights ? "float dirDotNormalHalf = dot( normal, dirHalfVector );" : "",
  654. maxDirLights ? "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );" : "",
  655. maxDirLights ? "float dirSpecularWeight = 0.0;" : "",
  656. maxDirLights ? "if ( dirDotNormalHalf >= 0.0 )" : "",
  657. maxDirLights ? "dirSpecularWeight = pow( dirDotNormalHalf, mShininess );" : "",
  658. maxDirLights ? "dirDiffuse += mColor * dirDiffuseWeight;" : "",
  659. maxDirLights ? "dirSpecular += mSpecular * dirSpecularWeight;" : "",
  660. maxDirLights ? "}" : "",
  661. // all lights contribution summation
  662. "vec4 totalLight = mAmbient;",
  663. maxDirLights ? "totalLight += dirDiffuse + dirSpecular;" : "",
  664. maxPointLights ? "totalLight += pointDiffuse + pointSpecular;" : "",
  665. // looks nicer with weighting
  666. "if ( mixEnvMap ) {",
  667. "gl_FragColor = vec4( mix( mapColor.rgb * totalLight.xyz * vLightWeighting, cubeColor.rgb, mReflectivity ), mapColor.a );",
  668. "} else {",
  669. "gl_FragColor = vec4( mapColor.rgb * cubeColor.rgb * totalLight.xyz * vLightWeighting, mapColor.a );",
  670. "}",
  671. // Lambert: diffuse lighting
  672. "} else if ( material == 1 ) {",
  673. "if ( mixEnvMap ) {",
  674. "gl_FragColor = vec4( mix( mColor.rgb * mapColor.rgb * vLightWeighting, cubeColor.rgb, mReflectivity ), mColor.a * mapColor.a );",
  675. "} else {",
  676. "gl_FragColor = vec4( mColor.rgb * mapColor.rgb * cubeColor.rgb * vLightWeighting, mColor.a * mapColor.a );",
  677. "}",
  678. "}",
  679. THREE.Snippets[ "fog_fragment" ],
  680. "}" ];
  681. return chunks.join("\n");
  682. };
  683. function generateVertexShader( maxDirLights, maxPointLights ) {
  684. var chunks = [
  685. maxDirLights ? "#define MAX_DIR_LIGHTS " + maxDirLights : "",
  686. maxPointLights ? "#define MAX_POINT_LIGHTS " + maxPointLights : "",
  687. "uniform bool enableLighting;",
  688. "uniform bool useRefract;",
  689. "uniform int pointLightNumber;",
  690. "uniform int directionalLightNumber;",
  691. "uniform vec3 ambientLightColor;",
  692. maxDirLights ? "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];" : "",
  693. maxDirLights ? "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];" : "",
  694. maxPointLights ? "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];" : "",
  695. maxPointLights ? "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];" : "",
  696. "varying vec3 vNormal;",
  697. "varying vec2 vUv;",
  698. "varying vec3 vLightWeighting;",
  699. maxPointLights ? "varying vec3 vPointLightVector[ MAX_POINT_LIGHTS ];" : "",
  700. "varying vec3 vViewPosition;",
  701. "varying vec3 vReflect;",
  702. "uniform float mRefractionRatio;",
  703. "void main(void) {",
  704. // world space
  705. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  706. "vViewPosition = cameraPosition - mPosition.xyz;",
  707. // this doesn't work on Mac
  708. //"vec3 nWorld = mat3(objectMatrix) * normal;",
  709. "vec3 nWorld = mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal;",
  710. // eye space
  711. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  712. "vec3 transformedNormal = normalize( normalMatrix * normal );",
  713. "if ( !enableLighting ) {",
  714. "vLightWeighting = vec3( 1.0, 1.0, 1.0 );",
  715. "} else {",
  716. "vLightWeighting = ambientLightColor;",
  717. // directional lights
  718. maxDirLights ? "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {" : "",
  719. maxDirLights ? "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );" : "",
  720. maxDirLights ? "float directionalLightWeighting = max( dot( transformedNormal, normalize( lDirection.xyz ) ), 0.0 );" : "",
  721. maxDirLights ? "vLightWeighting += directionalLightColor[ i ] * directionalLightWeighting;" : "",
  722. maxDirLights ? "}" : "",
  723. // point lights
  724. maxPointLights ? "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {" : "",
  725. maxPointLights ? "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );" : "",
  726. maxPointLights ? "vPointLightVector[ i ] = normalize( lPosition.xyz - mvPosition.xyz );" : "",
  727. maxPointLights ? "float pointLightWeighting = max( dot( transformedNormal, vPointLightVector[ i ] ), 0.0 );" : "",
  728. maxPointLights ? "vLightWeighting += pointLightColor[ i ] * pointLightWeighting;" : "",
  729. maxPointLights ? "}" : "",
  730. "}",
  731. "vNormal = transformedNormal;",
  732. "vUv = uv;",
  733. "if ( useRefract ) {",
  734. "vReflect = refract( normalize(mPosition.xyz - cameraPosition), normalize(nWorld.xyz), mRefractionRatio );",
  735. "} else {",
  736. "vReflect = reflect( normalize(mPosition.xyz - cameraPosition), normalize(nWorld.xyz) );",
  737. "}",
  738. "gl_Position = projectionMatrix * mvPosition;",
  739. "}" ];
  740. return chunks.join("\n");
  741. };
  742. function buildProgram( fragment_shader, vertex_shader, parameters ) {
  743. var program = _gl.createProgram(),
  744. prefix_fragment = [
  745. "#ifdef GL_ES",
  746. "precision highp float;",
  747. "#endif",
  748. parameters.fog ? "#define USE_FOG" : "",
  749. parameters.fog instanceof THREE.FogExp2 ? "#define FOG_EXP2" : "",
  750. parameters.map ? "#define USE_MAP" : "",
  751. parameters.env_map ? "#define USE_ENVMAP" : "",
  752. "uniform mat4 viewMatrix;",
  753. "uniform vec3 cameraPosition;",
  754. ""
  755. ].join("\n"),
  756. prefix_vertex = [
  757. maxVertexTextures() > 0 ? "#define VERTEX_TEXTURES" : "",
  758. parameters.map ? "#define USE_MAP" : "",
  759. parameters.env_map ? "#define USE_ENVMAP" : "",
  760. "uniform mat4 objectMatrix;",
  761. "uniform mat4 modelViewMatrix;",
  762. "uniform mat4 projectionMatrix;",
  763. "uniform mat4 viewMatrix;",
  764. "uniform mat3 normalMatrix;",
  765. "uniform vec3 cameraPosition;",
  766. "attribute vec3 position;",
  767. "attribute vec3 normal;",
  768. "attribute vec2 uv;",
  769. ""
  770. ].join("\n");
  771. _gl.attachShader( program, getShader( "fragment", prefix_fragment + fragment_shader ) );
  772. _gl.attachShader( program, getShader( "vertex", prefix_vertex + vertex_shader ) );
  773. _gl.linkProgram( program );
  774. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  775. alert( "Could not initialise shaders\n"+
  776. "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  777. }
  778. program.uniforms = {};
  779. program.attributes = {};
  780. return program;
  781. };
  782. function setUniforms( program, uniforms ) {
  783. var u, value, type, location, texture;
  784. for( u in uniforms ) {
  785. type = uniforms[u].type;
  786. value = uniforms[u].value;
  787. location = program.uniforms[u];
  788. if( type == "i" ) {
  789. _gl.uniform1i( location, value );
  790. } else if( type == "f" ) {
  791. _gl.uniform1f( location, value );
  792. } else if( type == "v3" ) {
  793. _gl.uniform3f( location, value.x, value.y, value.z );
  794. } else if( type == "c" ) {
  795. _gl.uniform3f( location, value.r, value.g, value.b );
  796. } else if( type == "t" ) {
  797. _gl.uniform1i( location, value );
  798. texture = uniforms[u].texture;
  799. if ( !texture ) continue;
  800. if ( texture.image instanceof Array && texture.image.length == 6 ) {
  801. setCubeTexture( texture, value );
  802. } else {
  803. setTexture( texture, value );
  804. }
  805. }
  806. }
  807. };
  808. function setCubeTexture( texture, slot ) {
  809. if ( texture.image.length == 6 ) {
  810. if ( !texture.image.__webGLTextureCube &&
  811. !texture.image.__cubeMapInitialized && texture.image.loadCount == 6 ) {
  812. texture.image.__webGLTextureCube = _gl.createTexture();
  813. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webGLTextureCube );
  814. _gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  815. _gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  816. _gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_MAG_FILTER, _gl.LINEAR );
  817. _gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR_MIPMAP_LINEAR );
  818. for ( var i = 0; i < 6; ++i ) {
  819. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, texture.image[ i ] );
  820. }
  821. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  822. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  823. texture.image.__cubeMapInitialized = true;
  824. }
  825. _gl.activeTexture( _gl.TEXTURE0 + slot );
  826. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webGLTextureCube );
  827. }
  828. };
  829. function setTexture( texture, slot ) {
  830. if ( !texture.__webGLTexture && texture.image.loaded ) {
  831. texture.__webGLTexture = _gl.createTexture();
  832. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webGLTexture );
  833. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, texture.image );
  834. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrap_s ) );
  835. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrap_t ) );
  836. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.mag_filter ) );
  837. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.min_filter ) );
  838. _gl.generateMipmap( _gl.TEXTURE_2D );
  839. _gl.bindTexture( _gl.TEXTURE_2D, null );
  840. }
  841. _gl.activeTexture( _gl.TEXTURE0 + slot );
  842. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webGLTexture );
  843. };
  844. function cacheUniformLocations( program, identifiers ) {
  845. var i, l, id;
  846. for( i = 0, l = identifiers.length; i < l; i++ ) {
  847. id = identifiers[ i ];
  848. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  849. }
  850. };
  851. function cacheAttributeLocations( program, identifiers ) {
  852. var i, l, id;
  853. for( i = 0, l = identifiers.length; i < l; i++ ) {
  854. id = identifiers[ i ];
  855. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  856. }
  857. };
  858. function initUbershader( maxDirLights, maxPointLights, fog ) {
  859. var vertex_shader = generateVertexShader( maxDirLights, maxPointLights ),
  860. fragment_shader = generateFragmentShader( maxDirLights, maxPointLights ),
  861. program;
  862. //console.log ( vertex_shader );
  863. //console.log ( fragment_shader );
  864. program = buildProgram( fragment_shader, vertex_shader, { fog: fog } );
  865. _gl.useProgram( program );
  866. // matrices
  867. // lights
  868. // material properties (Basic / Lambert / Blinn-Phong shader)
  869. cacheUniformLocations( program, [ 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'objectMatrix', 'cameraPosition',
  870. 'enableLighting', 'ambientLightColor',
  871. 'material', 'mColor', 'mAmbient', 'mSpecular', 'mShininess', 'mOpacity',
  872. 'enableMap', 'tMap',
  873. 'enableCubeMap', 'tCube', 'mixEnvMap', 'mReflectivity',
  874. 'mRefractionRatio', 'useRefract'
  875. ] );
  876. if ( fog ) {
  877. cacheUniformLocations( program, [ 'fogColor', 'fogNear', 'fogFar', 'fogDensity' ] );
  878. }
  879. if ( maxDirLights ) {
  880. cacheUniformLocations( program, [ 'directionalLightNumber', 'directionalLightColor', 'directionalLightDirection' ] );
  881. }
  882. if ( maxPointLights ) {
  883. cacheUniformLocations( program, [ 'pointLightNumber', 'pointLightColor', 'pointLightPosition' ] );
  884. }
  885. // texture (diffuse map)
  886. _gl.uniform1i( program.uniforms.enableMap, 0 );
  887. _gl.uniform1i( program.uniforms.tMap, 0 );
  888. // cube texture
  889. _gl.uniform1i( program.uniforms.enableCubeMap, 0 );
  890. _gl.uniform1i( program.uniforms.tCube, 1 ); // it's important to use non-zero texture unit, otherwise it doesn't work
  891. _gl.uniform1i( program.uniforms.mixEnvMap, 0 );
  892. // refraction
  893. _gl.uniform1i( program.uniforms.useRefract, 0 );
  894. // attribute arrays
  895. cacheAttributeLocations( program, [ "position", "normal", "uv" ] );
  896. return program;
  897. };
  898. function getShader( type, string ) {
  899. var shader;
  900. if ( type == "fragment" ) {
  901. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  902. } else if ( type == "vertex" ) {
  903. shader = _gl.createShader( _gl.VERTEX_SHADER );
  904. }
  905. _gl.shaderSource( shader, string );
  906. _gl.compileShader( shader );
  907. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  908. alert( _gl.getShaderInfoLog( shader ) );
  909. return null;
  910. }
  911. return shader;
  912. };
  913. function paramThreeToGL( p ) {
  914. switch ( p ) {
  915. case THREE.RepeatWrapping: return _gl.REPEAT; break;
  916. case THREE.ClampToEdgeWrapping: return _gl.CLAMP_TO_EDGE; break;
  917. case THREE.MirroredRepeatWrapping: return _gl.MIRRORED_REPEAT; break;
  918. case THREE.NearestFilter: return _gl.NEAREST; break;
  919. case THREE.NearestMipMapNearestFilter: return _gl.NEAREST_MIPMAP_NEAREST; break;
  920. case THREE.NearestMipMapLinearFilter: return _gl.NEAREST_MIPMAP_LINEAR; break;
  921. case THREE.LinearFilter: return _gl.LINEAR; break;
  922. case THREE.LinearMipMapNearestFilter: return _gl.LINEAR_MIPMAP_NEAREST; break;
  923. case THREE.LinearMipMapLinearFilter: return _gl.LINEAR_MIPMAP_LINEAR; break;
  924. }
  925. return 0;
  926. };
  927. function materialNeedsSmoothNormals( material ) {
  928. return material && material.shading != undefined && material.shading == THREE.SmoothShading;
  929. };
  930. function bufferNeedsSmoothNormals( geometryChunk, object ) {
  931. var m, ml, i, l, needsSmoothNormals = false;
  932. for ( m = 0, ml = object.materials.length; m < ml; m++ ) {
  933. meshMaterial = object.materials[ m ];
  934. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  935. for ( i = 0, l = geometryChunk.materials.length; i < l; i++ ) {
  936. if ( materialNeedsSmoothNormals( geometryChunk.materials[ i ] ) ) {
  937. needsSmoothNormals = true;
  938. break;
  939. }
  940. }
  941. } else {
  942. if ( materialNeedsSmoothNormals( meshMaterial ) ) {
  943. needsSmoothNormals = true;
  944. break;
  945. }
  946. }
  947. if ( needsSmoothNormals ) break;
  948. }
  949. return needsSmoothNormals;
  950. };
  951. function allocateLights( scene, maxLights ) {
  952. if ( scene ) {
  953. var l, ll, light, dirLights = pointLights = maxDirLights = maxPointLights = 0;
  954. for ( l = 0, ll = scene.lights.length; l < ll; l++ ) {
  955. light = scene.lights[ l ];
  956. if ( light instanceof THREE.DirectionalLight ) dirLights++;
  957. if ( light instanceof THREE.PointLight ) pointLights++;
  958. }
  959. if ( ( pointLights + dirLights ) <= maxLights ) {
  960. maxDirLights = dirLights;
  961. maxPointLights = pointLights;
  962. } else {
  963. maxDirLights = Math.ceil( maxLights * dirLights / ( pointLights + dirLights ) );
  964. maxPointLights = maxLights - maxDirLights;
  965. }
  966. return { 'directional' : maxDirLights, 'point' : maxPointLights };
  967. }
  968. return { 'directional' : 1, 'point' : maxLights - 1 };
  969. };
  970. /* DEBUG
  971. function getGLParams() {
  972. var params = {
  973. 'MAX_VARYING_VECTORS': _gl.getParameter( _gl.MAX_VARYING_VECTORS ),
  974. 'MAX_VERTEX_ATTRIBS': _gl.getParameter( _gl.MAX_VERTEX_ATTRIBS ),
  975. 'MAX_TEXTURE_IMAGE_UNITS': _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS ),
  976. 'MAX_VERTEX_TEXTURE_IMAGE_UNITS': _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ),
  977. 'MAX_COMBINED_TEXTURE_IMAGE_UNITS' : _gl.getParameter( _gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS ),
  978. 'MAX_VERTEX_UNIFORM_VECTORS': _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS ),
  979. 'MAX_FRAGMENT_UNIFORM_VECTORS': _gl.getParameter( _gl.MAX_FRAGMENT_UNIFORM_VECTORS )
  980. }
  981. return params;
  982. };
  983. function dumpObject( obj ) {
  984. var p, str = "";
  985. for ( p in obj ) {
  986. str += p + ": " + obj[p] + "\n";
  987. }
  988. return str;
  989. }
  990. */
  991. };
  992. THREE.Snippets = {
  993. fog_uniforms: [
  994. "#ifdef USE_FOG",
  995. "uniform vec3 fogColor;",
  996. "#ifdef FOG_EXP2",
  997. "uniform float fogDensity;",
  998. "#else",
  999. "uniform float fogNear;",
  1000. "uniform float fogFar;",
  1001. "#endif",
  1002. "#endif"
  1003. ].join("\n"),
  1004. fog_fragment: [
  1005. "#ifdef USE_FOG",
  1006. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  1007. "#ifdef FOG_EXP2",
  1008. "const float LOG2 = 1.442695;",
  1009. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  1010. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  1011. "#else",
  1012. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  1013. "#endif",
  1014. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, 1.0 ), fogFactor );",
  1015. "#endif"
  1016. ].join("\n")
  1017. };
  1018. THREE.ShaderLib = {
  1019. 'depth': {
  1020. uniforms: { "mNear": { type: "f", value: 1.0 },
  1021. "mFar" : { type: "f", value: 2000.0 } },
  1022. fragment_shader: [
  1023. "uniform float mNear;",
  1024. "uniform float mFar;",
  1025. "void main() {",
  1026. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  1027. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  1028. "gl_FragColor = vec4( vec3( color ), 1.0 );",
  1029. "}"
  1030. ].join("\n"),
  1031. vertex_shader: [
  1032. "void main() {",
  1033. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  1034. "}"
  1035. ].join("\n")
  1036. },
  1037. 'normal': {
  1038. uniforms: { },
  1039. fragment_shader: [
  1040. "varying vec3 vNormal;",
  1041. "void main() {",
  1042. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, 1.0 );",
  1043. "}"
  1044. ].join("\n"),
  1045. vertex_shader: [
  1046. "varying vec3 vNormal;",
  1047. "void main() {",
  1048. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  1049. "vNormal = normalize( normalMatrix * normal );",
  1050. "gl_Position = projectionMatrix * mvPosition;",
  1051. "}"
  1052. ].join("\n")
  1053. },
  1054. 'basic': {
  1055. uniforms: { "color" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  1056. "opacity" : { type: "f", value: 1 },
  1057. "map" : { type: "t", value: 0, texture: null },
  1058. "env_map" : { type: "t", value: 1, texture: null },
  1059. "useRefract" : { type: "i", value: 0 },
  1060. "reflectivity" : { type: "f", value: 1 },
  1061. "refraction_ratio": { type: "f", value: 0.98 },
  1062. "combine" : { type: "i", value: 0 },
  1063. "fogDensity": { type: "f", value: 0.00025 },
  1064. "fogNear" : { type: "f", value: 1 },
  1065. "fogFar" : { type: "f", value: 2000 },
  1066. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  1067. },
  1068. fragment_shader: [
  1069. "uniform vec3 color;",
  1070. "uniform float opacity;",
  1071. "#ifdef USE_MAP",
  1072. "varying vec2 vUv;",
  1073. "uniform sampler2D map;",
  1074. "#endif",
  1075. "#ifdef USE_ENVMAP",
  1076. "varying vec3 vReflect;",
  1077. "uniform float reflectivity;",
  1078. "uniform samplerCube env_map;",
  1079. "uniform int combine;",
  1080. "#endif",
  1081. THREE.Snippets[ "fog_uniforms" ],
  1082. "void main() {",
  1083. "vec4 mColor = vec4( color, opacity );",
  1084. "vec4 mapColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  1085. "vec4 cubeColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  1086. // diffuse map
  1087. "#ifdef USE_MAP",
  1088. "mapColor = texture2D( map, vUv );",
  1089. "#endif",
  1090. // environment map
  1091. "#ifdef USE_ENVMAP",
  1092. "cubeColor = textureCube( env_map, vec3( -vReflect.x, vReflect.yz ) );",
  1093. "if ( combine == 1 ) {",
  1094. "gl_FragColor = mix( mColor * mapColor, cubeColor, reflectivity );",
  1095. "} else {",
  1096. "gl_FragColor = mColor * mapColor * cubeColor;",
  1097. "}",
  1098. "#else",
  1099. "gl_FragColor = mColor * mapColor;",
  1100. "#endif",
  1101. THREE.Snippets[ "fog_fragment" ],
  1102. "}"
  1103. ].join("\n"),
  1104. vertex_shader: [
  1105. "#ifdef USE_MAP",
  1106. "varying vec2 vUv;",
  1107. "#endif",
  1108. "#ifdef USE_ENVMAP",
  1109. "varying vec3 vReflect;",
  1110. "uniform float refraction_ratio;",
  1111. "uniform bool useRefract;",
  1112. "#endif",
  1113. "void main() {",
  1114. "#ifdef USE_MAP",
  1115. "vUv = uv;",
  1116. "#endif",
  1117. "#ifdef USE_ENVMAP",
  1118. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  1119. "vec3 nWorld = mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal;",
  1120. "if ( useRefract ) {",
  1121. "vReflect = refract( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ), refraction_ratio );",
  1122. "} else {",
  1123. "vReflect = reflect( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ) );",
  1124. "}",
  1125. "#endif",
  1126. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  1127. "}"
  1128. ].join("\n")
  1129. }
  1130. };