WebGLRenderer2.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. THREE.WebGLRenderer2 = function () {
  5. var _canvas = document.createElement( 'canvas' ),
  6. _gl, _currentProgram,
  7. _modelViewMatrix = new THREE.Matrix4(),
  8. _viewMatrixArray = new Float32Array( 16 ),
  9. _modelViewMatrixArray = new Float32Array( 16 ),
  10. _projectionMatrixArray = new Float32Array( 16 ),
  11. _normalMatrixArray = new Float32Array( 9 ),
  12. _objectMatrixArray = new Float32Array( 16 );
  13. try {
  14. _gl = _canvas.getContext( 'experimental-webgl', { antialias: true } );
  15. } catch(e) { }
  16. if ( !_gl ) {
  17. alert("WebGL not supported");
  18. throw "cannot create webgl context";
  19. }
  20. _gl.clearColor( 0, 0, 0, 1 );
  21. _gl.clearDepth( 1 );
  22. _gl.enable( _gl.DEPTH_TEST );
  23. _gl.depthFunc( _gl.LEQUAL );
  24. _gl.frontFace( _gl.CCW );
  25. _gl.cullFace( _gl.BACK );
  26. _gl.enable( _gl.CULL_FACE );
  27. _gl.enable( _gl.BLEND );
  28. _gl.blendFunc( _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  29. _gl.clearColor( 0, 0, 0, 0 );
  30. this.domElement = _canvas;
  31. this.autoClear = true;
  32. this.setSize = function ( width, height ) {
  33. _canvas.width = width;
  34. _canvas.height = height;
  35. _gl.viewport( 0, 0, _canvas.width, _canvas.height );
  36. };
  37. this.clear = function () {
  38. _gl.clear( _gl.COLOR_BUFFER_BIT | _gl.DEPTH_BUFFER_BIT );
  39. };
  40. this.render = function( scene, camera ) {
  41. var o, ol;
  42. this.autoClear && this.clear();
  43. camera.autoUpdateMatrix && camera.updateMatrix();
  44. // Setup camera matrices
  45. _viewMatrixArray.set( camera.matrix.flatten() );
  46. _projectionMatrixArray.set( camera.projectionMatrix.flatten() );
  47. for ( o = 0, ol = scene.objects.length; o < ol; o++ ) {
  48. object = scene.objects[ o ];
  49. if ( object.visible ) {
  50. renderObject( object );
  51. }
  52. }
  53. function renderObject( object ) {
  54. var geometry, material, m, nl,
  55. program, attributes;
  56. object.autoUpdateMatrix && object.updateMatrix();
  57. // Setup object matrices
  58. _objectMatrixArray.set( object.matrix.flatten() );
  59. _modelViewMatrix.multiply( camera.matrix, object.matrix );
  60. _modelViewMatrixArray.set( _modelViewMatrix.flatten() );
  61. _normalMatrix = THREE.Matrix4.makeInvert3x3( _modelViewMatrix ).transpose();
  62. _normalMatrixArray.set( _normalMatrix.m );
  63. if ( object instanceof THREE.Mesh ) {
  64. geometry = object.geometry;
  65. if ( geometry.__webglBuffers == undefined ) {
  66. if ( buildBuffers( geometry ) == false ) return;
  67. }
  68. for ( m = 0, ml = object.material.length; m < ml; m ++ ) {
  69. material = object.material[ m ];
  70. if ( material.__webglProgram == undefined ) {
  71. if ( createProgram( material ) == false ) continue;
  72. }
  73. program = material.__webglProgram;
  74. attributes = program.attributes;
  75. if( program != _currentProgram ) {
  76. _gl.useProgram( program );
  77. _currentProgram = program;
  78. }
  79. if ( material instanceof THREE.MeshBasicMaterial ||
  80. material instanceof THREE.MeshLambertMaterial ||
  81. material instanceof THREE.MeshPhongMaterial ) {
  82. _gl.uniform3f( program.uniforms.mColor, material.color.r, material.color.g, material.color.b );
  83. _gl.uniform1f( program.uniforms.mOpacity, material.opacity );
  84. if ( material.map ) {
  85. setTexture( material.map, 0 );
  86. _gl.uniform1i( program.uniforms.tMap, 0 );
  87. }
  88. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  89. _gl.uniform1f( program.uniforms.mOpacity, material.opacity );
  90. }
  91. _gl.uniform3f( program.uniforms.cameraPosition, camera.position.x, camera.position.y, camera.position.z );
  92. _gl.uniformMatrix4fv( program.uniforms.viewMatrix, false, _viewMatrixArray );
  93. _gl.uniformMatrix4fv( program.uniforms.projectionMatrix, false, _projectionMatrixArray );
  94. _gl.uniformMatrix4fv( program.uniforms.objectMatrix, false, _objectMatrixArray );
  95. _gl.uniformMatrix4fv( program.uniforms.modelViewMatrix, false, _modelViewMatrixArray );
  96. _gl.uniformMatrix3fv( program.uniforms.normalMatrix, false, _normalMatrixArray );
  97. var buffer, buffers = geometry.__webglBuffers;
  98. for ( var i = 0, l = buffers.length; i < l; i ++ ) {
  99. buffer = buffers[ i ];
  100. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer.vertices );
  101. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  102. if ( attributes.normal >= 0 ) {
  103. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer.normals );
  104. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  105. }
  106. if ( attributes.uv >= 0 ) {
  107. if ( buffer.uvs ) {
  108. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer.uvs );
  109. _gl.enableVertexAttribArray( attributes.uv );
  110. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  111. } else {
  112. _gl.disableVertexAttribArray( attributes.uv );
  113. }
  114. }
  115. if ( ! material.wireframe ) {
  116. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, buffer.faces );
  117. _gl.drawElements( _gl.TRIANGLES, buffer.faceCount, _gl.UNSIGNED_SHORT, 0 );
  118. } else {
  119. _gl.lineWidth( material.wireframe_linewidth );
  120. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, buffer.lines );
  121. _gl.drawElements( _gl.LINES, buffer.lineCount, _gl.UNSIGNED_SHORT, 0 );
  122. }
  123. }
  124. }
  125. }
  126. }
  127. // Buffers
  128. function buildBuffers( geometry ) {
  129. // TODO: Handle 65535
  130. var vertexIndex = 0, group,
  131. f, fl, face, v1, v2, v3, vertexNormals, normal, uv,
  132. vertices = [], faces = [], lines = [], normals = [], uvs = [],
  133. buffers = {};
  134. for ( f = 0, fl = geometry.faces.length; f < fl; f++ ) {
  135. face = geometry.faces[ f ];
  136. uv = geometry.uvs[ f ];
  137. vertexNormals = face.vertexNormals;
  138. faceNormal = face.normal;
  139. if ( face instanceof THREE.Face3 ) {
  140. v1 = geometry.vertices[ face.a ].position;
  141. v2 = geometry.vertices[ face.b ].position;
  142. v3 = geometry.vertices[ face.c ].position;
  143. vertices.push( v1.x, v1.y, v1.z );
  144. vertices.push( v2.x, v2.y, v2.z );
  145. vertices.push( v3.x, v3.y, v3.z );
  146. if ( vertexNormals.length == 3 ) {
  147. for ( i = 0; i < 3; i ++ ) {
  148. normals.push( vertexNormals[ i ].x, vertexNormals[ i ].y, vertexNormals[ i ].z );
  149. }
  150. } else {
  151. for ( i = 0; i < 3; i ++ ) {
  152. normals.push( faceNormal.x, faceNormal.y, faceNormal.z );
  153. }
  154. }
  155. if ( uv ) {
  156. for ( i = 0; i < 3; i ++ ) {
  157. uvs.push( uv[ i ].u, uv[ i ].v );
  158. }
  159. }
  160. faces.push( vertexIndex, vertexIndex + 1, vertexIndex + 2 );
  161. // TODO: don't add lines that already exist (faces sharing edge)
  162. lines.push( vertexIndex, vertexIndex + 1 );
  163. lines.push( vertexIndex, vertexIndex + 2 );
  164. lines.push( vertexIndex + 1, vertexIndex + 2 );
  165. vertexIndex += 3;
  166. } else if ( face instanceof THREE.Face4 ) {
  167. group = Math.floor( vertexIndex / 65535 );
  168. if ( !vertices ) {
  169. vertices = [];
  170. faces = [];
  171. normals = [];
  172. lines = [];
  173. uvs = [];
  174. }
  175. v1 = geometry.vertices[ face.a ].position;
  176. v2 = geometry.vertices[ face.b ].position;
  177. v3 = geometry.vertices[ face.c ].position;
  178. v4 = geometry.vertices[ face.d ].position;
  179. vertices.push( v1.x, v1.y, v1.z );
  180. vertices.push( v2.x, v2.y, v2.z );
  181. vertices.push( v3.x, v3.y, v3.z );
  182. vertices.push( v4.x, v4.y, v4.z );
  183. if ( vertexNormals.length == 4 ) {
  184. for ( i = 0; i < 4; i ++ ) {
  185. normals.push( vertexNormals[ i ].x, vertexNormals[ i ].y, vertexNormals[ i ].z );
  186. }
  187. } else {
  188. for ( i = 0; i < 4; i ++ ) {
  189. normals.push( faceNormal.x, faceNormal.y, faceNormal.z );
  190. }
  191. }
  192. if ( uv ) {
  193. for ( i = 0; i < 4; i ++ ) {
  194. uvs.push( uv[ i ].u, uv[ i ].v );
  195. }
  196. }
  197. faces.push( vertexIndex, vertexIndex + 1, vertexIndex + 2 );
  198. faces.push( vertexIndex, vertexIndex + 2, vertexIndex + 3 );
  199. // TODO: don't add lines that already exist (faces sharing edge)
  200. lines.push( vertexIndex, vertexIndex + 1 );
  201. lines.push( vertexIndex, vertexIndex + 2 );
  202. lines.push( vertexIndex, vertexIndex + 3 );
  203. lines.push( vertexIndex + 1, vertexIndex + 2 );
  204. lines.push( vertexIndex + 2, vertexIndex + 3 );
  205. vertexIndex += 4;
  206. }
  207. }
  208. if ( !vertices.length ) return false;
  209. var buffer, buffers = [];
  210. // for ( var i = 0, l = group; i <= l; i ++ ) {
  211. buffer = {
  212. vertices: null,
  213. faces: null,
  214. faceCount: faces.length,
  215. normals: null,
  216. lines: null,
  217. lineCount: lines.length,
  218. uvs: null
  219. };
  220. buffer.vertices = _gl.createBuffer();
  221. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer.vertices );
  222. _gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( vertices ), _gl.STATIC_DRAW );
  223. buffer.normals = _gl.createBuffer();
  224. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer.normals );
  225. _gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( normals ), _gl.STATIC_DRAW );
  226. if ( uvs.length > 0 ) {
  227. buffer.uvs = _gl.createBuffer();
  228. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer.uvs );
  229. _gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( uvs ), _gl.STATIC_DRAW );
  230. }
  231. buffer.faces = _gl.createBuffer();
  232. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, buffer.faces );
  233. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( faces ), _gl.STATIC_DRAW );
  234. buffer.lines = _gl.createBuffer();
  235. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, buffer.lines );
  236. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( lines ), _gl.STATIC_DRAW );
  237. buffers.push( buffer );
  238. // }
  239. geometry.__webglBuffers = buffers;
  240. return true;
  241. }
  242. // Shaders
  243. function createProgram( material ) {
  244. var pvs = '', vs = '', pfs = '', fs = '',
  245. identifiers = [ 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'objectMatrix', 'cameraPosition' ];
  246. if ( material instanceof THREE.MeshBasicMaterial ||
  247. material instanceof THREE.MeshLambertMaterial ||
  248. material instanceof THREE.MeshPhongMaterial ) {
  249. vs += 'void main() {\n';
  250. fs += 'void main() {\n';
  251. vs += 'gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n';
  252. pfs += 'uniform vec3 mColor;\n';
  253. pfs += 'uniform float mOpacity;\n';
  254. fs += 'gl_FragColor = vec4( mColor.xyz, mOpacity );\n';
  255. if ( material.map ) {
  256. pvs += 'varying vec2 vUv;\n',
  257. vs += 'vUv = uv;\n',
  258. pfs += 'uniform sampler2D tMap;\n';
  259. pfs += 'varying vec2 vUv;\n';
  260. fs += 'gl_FragColor *= texture2D( tMap, vUv );\n';
  261. identifiers.push( 'tMap' );
  262. }
  263. identifiers.push( 'mColor' );
  264. identifiers.push( 'mOpacity' );
  265. vs += '}';
  266. fs += '}';
  267. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  268. vs += 'void main() {\n';
  269. fs += 'void main() {\n';
  270. pvs += 'varying vec3 vNormal;\n';
  271. vs += 'gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n';
  272. vs += 'vNormal = normalize( normalMatrix * normal );\n';
  273. pfs += 'uniform float mOpacity;\n';
  274. pfs += 'varying vec3 vNormal;\n';
  275. fs += 'gl_FragColor = vec4( ( normalize( vNormal ) + 1.0 ) * 0.5, mOpacity );\n';
  276. identifiers.push( 'mOpacity' );
  277. vs += '}';
  278. fs += '}';
  279. } else if ( material instanceof THREE.MeshShaderMaterial ) {
  280. vs = material.vertex_shader;
  281. fs = material.fragment_shader;
  282. for( uniform in material.uniforms ) {
  283. identifiers.push( uniform );
  284. }
  285. } else {
  286. return false;
  287. }
  288. material.__webglProgram = compileProgram( pvs + vs, pfs + fs );
  289. cacheUniformLocations( material.__webglProgram, identifiers );
  290. cacheAttributeLocations( material.__webglProgram, [ "position", "normal", "uv"/*, "tangent"*/ ] );
  291. return true;
  292. }
  293. function compileProgram( vertex_shader, fragment_shader ) {
  294. var program = _gl.createProgram(), shader
  295. prefix_vertex = [
  296. maxVertexTextures() > 0 ? "#define VERTEX_TEXTURES" : "",
  297. "uniform mat4 objectMatrix;",
  298. "uniform mat4 modelViewMatrix;",
  299. "uniform mat4 projectionMatrix;",
  300. //"uniform mat4 viewMatrix;",
  301. "uniform mat3 normalMatrix;",
  302. "uniform vec3 cameraPosition;",
  303. "attribute vec3 position;",
  304. "attribute vec3 normal;",
  305. "attribute vec2 uv;",
  306. ""
  307. ].join("\n"),
  308. prefix_fragment = [
  309. "#ifdef GL_ES",
  310. "precision highp float;",
  311. "#endif",
  312. //"uniform mat4 viewMatrix;",
  313. ""
  314. ].join("\n");
  315. // Vertex shader
  316. shader = _gl.createShader( _gl.VERTEX_SHADER );
  317. _gl.shaderSource( shader, prefix_vertex + vertex_shader );
  318. _gl.compileShader( shader );
  319. _gl.attachShader( program, shader );
  320. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  321. alert( _gl.getShaderInfoLog( shader ) );
  322. return null;
  323. }
  324. // Fragment Shader
  325. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  326. _gl.shaderSource( shader, prefix_fragment + fragment_shader );
  327. _gl.compileShader( shader );
  328. _gl.attachShader( program, shader );
  329. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  330. alert( _gl.getShaderInfoLog( shader ) );
  331. return null;
  332. }
  333. _gl.linkProgram( program );
  334. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  335. alert( "Could not initialise shaders.\n" +
  336. "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + "\n" +
  337. "ERROR: " + _gl.getError() + "\n\n" +
  338. "Vertex Shader: \n" + prefix_vertex + vertex_shader + "\n\n" +
  339. "Fragment Shader: \n" + prefix_fragment + fragment_shader );
  340. }
  341. program.uniforms = {};
  342. program.attributes = {};
  343. return program;
  344. }
  345. function cacheUniformLocations( program, identifiers ) {
  346. var i, l, id;
  347. for( i = 0, l = identifiers.length; i < l; i++ ) {
  348. id = identifiers[ i ];
  349. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  350. }
  351. }
  352. function cacheAttributeLocations( program, identifiers ) {
  353. var i, l, id;
  354. for( i = 0, l = identifiers.length; i < l; i++ ) {
  355. id = identifiers[ i ];
  356. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  357. if ( program.attributes[ id ] >= 0 ) {
  358. _gl.enableVertexAttribArray( program.attributes[ id ] );
  359. }
  360. }
  361. }
  362. // Textures
  363. function setTexture( texture, slot ) {
  364. if ( !texture.__webglTexture && texture.image.loaded ) {
  365. texture.__webglTexture = _gl.createTexture();
  366. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  367. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, texture.image );
  368. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrap_s ) );
  369. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrap_t ) );
  370. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.mag_filter ) );
  371. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.min_filter ) );
  372. _gl.generateMipmap( _gl.TEXTURE_2D );
  373. _gl.bindTexture( _gl.TEXTURE_2D, null );
  374. }
  375. _gl.activeTexture( _gl.TEXTURE0 + slot );
  376. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  377. }
  378. function maxVertexTextures() {
  379. return _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  380. };
  381. function paramThreeToGL( p ) {
  382. switch ( p ) {
  383. case THREE.RepeatWrapping: return _gl.REPEAT; break;
  384. case THREE.ClampToEdgeWrapping: return _gl.CLAMP_TO_EDGE; break;
  385. case THREE.MirroredRepeatWrapping: return _gl.MIRRORED_REPEAT; break;
  386. case THREE.NearestFilter: return _gl.NEAREST; break;
  387. case THREE.NearestMipMapNearestFilter: return _gl.NEAREST_MIPMAP_NEAREST; break;
  388. case THREE.NearestMipMapLinearFilter: return _gl.NEAREST_MIPMAP_LINEAR; break;
  389. case THREE.LinearFilter: return _gl.LINEAR; break;
  390. case THREE.LinearMipMapNearestFilter: return _gl.LINEAR_MIPMAP_NEAREST; break;
  391. case THREE.LinearMipMapLinearFilter: return _gl.LINEAR_MIPMAP_LINEAR; break;
  392. }
  393. return 0;
  394. }
  395. };
  396. };