WebGLRenderer.js 41 KB

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