Trying to merge...

This commit is contained in:
Mr.doob
2010-11-15 01:56:10 +00:00
parent 11bde7e2d3
commit 5feee3839f
21 changed files with 222 additions and 205963 deletions
+6 -1
View File
File diff suppressed because one or more lines are too long
+6 -1
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -354,7 +354,7 @@
boid.setAvoidWalls( true );
boid.setWorldSize( 500, 500, 400 );
bird = birds[ i ] = new THREE.Mesh( new Bird(), new THREE.MeshColorFillMaterial( Math.random() * 0xffffff ) );
bird = birds[ i ] = new THREE.Mesh( new Bird(), new THREE.MeshBasicMaterial( { color:Math.random() * 0xffffff } ) );
bird.phase = Math.floor( Math.random() * 62.83 );
bird.position = boids[ i ].position;
bird.doubleSided = true;
+4 -5
View File
@@ -137,7 +137,7 @@
// light representation
sphere = new Sphere( 100, 16, 8, 1 );
lightMesh = new THREE.Mesh( sphere, new THREE.MeshColorFillMaterial( 0xffaa00 ) );
lightMesh = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0xffaa00 } ) );
lightMesh.scale.x = lightMesh.scale.y = lightMesh.scale.z = 0.05;
lightMesh.position = pointLight.position;
lightMesh.overdraw = true;
@@ -176,7 +176,6 @@
var s = (new Date).getTime();
var loader = new THREE.Loader();
//loader.loadAsciiOld( "obj/lucy/Lucy100k.js", function() { createScene( new Lucy100k(), s ) } );
//loader.loadAscii( 'obj/lucy/Lucy100k_slim.js', function( geometry ) { createScene( geometry, s ) } );
loader.loadBinary( 'obj/lucy/Lucy100k_bin.js', function( geometry ) { createScene( geometry, s ) }, "obj/lucy" );
@@ -184,10 +183,10 @@
function createScene( geometry, start ) {
addMesh( geometry, 0.75, 900, 0, 0, 0,0,0, new THREE.MeshPhongMaterial( 0x030303, 0x030303, 0x990000, 30, 1.0 ) );
addMesh( geometry, 0.75, 900, 0, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x030303, specular: 0x990000, shininess: 30 } ) );
addMesh( geometry, 0.75, 300, 0, 0, 0,0,0, new THREE.MeshFaceMaterial( ) );
addMesh( geometry, 0.75, -300, 0, 0, 0,0,0, new THREE.MeshPhongMaterial( 0x030303, 0x111111, 0xffaa00, 10, 1.0 ) );
addMesh( geometry, 0.75, -900, 0, 0, 0,0,0, new THREE.MeshPhongMaterial( 0x030303, 0x555555, 0x666666, 10, 1.0 ) );
addMesh( geometry, 0.75, -300, 0, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x111111, specular: 0xffaa00, shininess: 10 } ) );
addMesh( geometry, 0.75, -900, 0, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x555555, specular: 0x666666, shininess: 10 } ) );
log( "geometry.vertices: " + geometry.vertices.length );
log( "geometry.faces: " + geometry.faces.length );
+20 -29
View File
@@ -65,14 +65,15 @@
<script type="text/javascript" src="../src/objects/Mesh.js"></script>
<script type="text/javascript" src="../src/objects/Particle.js"></script>
<script type="text/javascript" src="../src/objects/Line.js"></script>
<script type="text/javascript" src="../src/materials/LineColorMaterial.js"></script>
<script type="text/javascript" src="../src/materials/Material.js"></script>
<script type="text/javascript" src="../src/materials/LineBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshLambertMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshPhongMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshBitmapMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshColorFillMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshColorStrokeMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshFaceMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleCircleMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleBitmapMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/Texture.js"></script>
<script type="text/javascript" src="../src/scenes/Scene.js"></script>
<script type="text/javascript" src="../src/renderers/Projector.js"></script>
<script type="text/javascript" src="../src/renderers/CanvasRenderer.js"></script>
@@ -107,30 +108,18 @@
scene = new THREE.Scene();
var loader = new THREE.Loader();
loader.loadAsciiOld( "obj/walt/WaltHead.js", function() {
//object = new THREE.Mesh( new WaltHead(), [ new THREE.MeshColorStrokeMaterial( 0xffffff ) ] );
//object = new THREE.Mesh( new WaltHead(), new THREE.MeshColorFillMaterial( 0xffffff ) );
object = new THREE.Mesh( new WaltHead(), new THREE.MeshPhongMaterial( 0x555555, 0x555555, 0xffffff, 50, 1.0 ) );
object.scale.x = object.scale.y = object.scale.z = 0.80;
object.overdraw = true;
scene.addObject( object );
});
/*
loader.loadAscii( "obj/walt/WaltHead_slim.js", function( geometry ) {
object = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( 0x555555, 0x555555, 0xffffff, 50, 1.0 ) );
object = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( { ambient: 0x555555, color: 0x555555, specular: 0xffffff, shininess: 50 } ) );
object.scale.x = object.scale.y = object.scale.z = 0.80;
object.overdraw = true;
scene.addObject( object );
});
*/
/*
/*
loader.loadBinary( "obj/walt/WaltHead_bin.js", function( geometry ) {
object = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( 0x555555, 0x555555, 0xffffff, 50, 1.0 ) );
@@ -139,8 +128,8 @@
scene.addObject( object );
}, "obj/walt");
*/
*/
/*
var directionalLight = new THREE.DirectionalLight( 0x111111, 0.9 );
directionalLight.position.x = 1;
@@ -162,15 +151,17 @@
light3 = new THREE.PointLight( 0x80ff80 );
scene.addLight( light3 );
var l1 = new THREE.Mesh( new Sphere( 1, 16, 8, 1 ), new THREE.MeshColorFillMaterial( 0xff0040 ) );
var sphere = new Sphere( 0.5, 16, 8, 1 );
var l1 = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0xff0040 } ) );
l1.position = light1.position;
scene.addObject( l1 );
var l2 = new THREE.Mesh( new Sphere( 1, 16, 8, 1 ), new THREE.MeshColorFillMaterial( 0x0040ff ) );
var l2 = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0x0040ff } ) );
l2.position = light2.position;
scene.addObject( l2 );
var l3 = new THREE.Mesh( new Sphere( 1, 16, 8, 1 ), new THREE.MeshColorFillMaterial( 0x80ff80 ) );
var l3 = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0x80ff80 } ) );
l3.position = light3.position;
scene.addObject( l3 );
@@ -193,7 +184,7 @@
var time = new Date().getTime() * 0.0005;
object.rotation.y -= 0.01;
if( object ) object.rotation.y -= 0.01;
light1.position.x = Math.sin( time * 0.7 ) * 30;
light1.position.y = Math.cos( time * 0.5 ) * 40;
@@ -212,9 +203,9 @@
//stats.update();
}
function log() {
}
function log() {
}
</script>
</body>
+11 -11
View File
@@ -39,11 +39,10 @@
<pre id="log"></pre>
<script type="text/javascript" src="../build/Three.js"></script>
<!--
<script type="text/javascript" src="../build/Three.js"></script>
-->
<!--
<script type="text/javascript" src="../src/Three.js"></script>
<script type="text/javascript" src="../src/core/Color.js"></script>
<script type="text/javascript" src="../src/core/Vector2.js"></script>
@@ -67,14 +66,15 @@
<script type="text/javascript" src="../src/objects/Mesh.js"></script>
<script type="text/javascript" src="../src/objects/Particle.js"></script>
<script type="text/javascript" src="../src/objects/Line.js"></script>
<script type="text/javascript" src="../src/materials/LineColorMaterial.js"></script>
<script type="text/javascript" src="../src/materials/Material.js"></script>
<script type="text/javascript" src="../src/materials/LineBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshLambertMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshPhongMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshBitmapMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshColorFillMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshColorStrokeMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshFaceMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleCircleMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleBitmapMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/Texture.js"></script>
<script type="text/javascript" src="../src/scenes/Scene.js"></script>
<script type="text/javascript" src="../src/renderers/Projector.js"></script>
<script type="text/javascript" src="../src/renderers/CanvasRenderer.js"></script>
@@ -84,6 +84,7 @@
<script type="text/javascript" src="../src/renderers/renderables/RenderableFace4.js"></script>
<script type="text/javascript" src="../src/renderers/renderables/RenderableParticle.js"></script>
<script type="text/javascript" src="../src/renderers/renderables/RenderableLine.js"></script>
<!--
-->
<script type="text/javascript" src="../src/extras/primitives/Sphere.js"></script>
@@ -148,7 +149,7 @@
sphere = new Sphere( 100, 16, 8, 0 );
for (var i=0; i<30; i++) {
mesh = new THREE.Mesh( sphere, new THREE.MeshColorFillMaterial( 0xffffff ) );
mesh = new THREE.Mesh( sphere, new THREE.MeshLambertMaterial( { color: 0xffffff } ) );
mesh.position.x = 500 * (Math.random() - 0.5);
mesh.position.y = 500 * (Math.random() - 0.5);
mesh.position.z = 500 * (Math.random() - 0.5);
@@ -178,7 +179,7 @@
sphere = new Sphere( 100, 16, 8, 1 );
lightMesh = new THREE.Mesh( sphere, new THREE.MeshColorFillMaterial( 0xffaa00 ) );
lightMesh = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0xffaa00 } ) );
lightMesh.scale.x = lightMesh.scale.y = lightMesh.scale.z = 0.05;
lightMesh.position = pointLight.position;
lightMesh.overdraw = true;
@@ -214,7 +215,6 @@
var loader = new THREE.Loader();
//loader.loadAsciiOld( "obj/torus/Torus.js", function() { createScene( new Torus() ) } );
//loader.loadAscii( "obj/torus/Torus_slim.js", function( geometry ) { createScene( geometry ) } );
loader.loadBinary( "obj/torus/Torus_bin.js", function( geometry ) { createScene( geometry ) }, "obj/torus" );
@@ -222,7 +222,7 @@
function createScene( geometry ) {
zmesh = new THREE.Mesh( geometry, new THREE.MeshColorFillMaterial( 0xffffff ) );
zmesh = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: 0xffffff } ) );
zmesh.position.x = 0;
zmesh.position.z = 0;
zmesh.position.y = 0;
+26 -24
View File
@@ -42,11 +42,10 @@
<div id="log"></div>
<script type="text/javascript" src="../build/Three.js"></script>
<!--
<script type="text/javascript" src="../build/Three.js"></script>
-->
<!--
<script type="text/javascript" src="../src/Three.js"></script>
<script type="text/javascript" src="../src/core/Color.js"></script>
<script type="text/javascript" src="../src/core/Vector2.js"></script>
@@ -70,14 +69,15 @@
<script type="text/javascript" src="../src/objects/Mesh.js"></script>
<script type="text/javascript" src="../src/objects/Particle.js"></script>
<script type="text/javascript" src="../src/objects/Line.js"></script>
<script type="text/javascript" src="../src/materials/LineColorMaterial.js"></script>
<script type="text/javascript" src="../src/materials/Material.js"></script>
<script type="text/javascript" src="../src/materials/LineBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshLambertMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshPhongMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshBitmapMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshColorFillMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshColorStrokeMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshFaceMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleCircleMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleBitmapMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/Texture.js"></script>
<script type="text/javascript" src="../src/scenes/Scene.js"></script>
<script type="text/javascript" src="../src/renderers/Projector.js"></script>
<script type="text/javascript" src="../src/renderers/CanvasRenderer.js"></script>
@@ -87,6 +87,7 @@
<script type="text/javascript" src="../src/renderers/renderables/RenderableFace4.js"></script>
<script type="text/javascript" src="../src/renderers/renderables/RenderableParticle.js"></script>
<script type="text/javascript" src="../src/renderers/renderables/RenderableLine.js"></script>
<!--
-->
<script type="text/javascript" src="../src/extras/primitives/Sphere.js"></script>
@@ -150,10 +151,11 @@
sphere = new Sphere( 100, 16, 8, 1 );
for (var i=0; i<10; i++) {
//mesh = new THREE.Mesh( sphere, new THREE.MeshColorFillMaterial( 0xffffff ) );
mesh = new THREE.Mesh( sphere, [ new THREE.MeshColorFillMaterial( 0xffffff ), new THREE.MeshColorStrokeMaterial( 0x000000, 1, 1.5 ) ] );
//mesh = new THREE.Mesh( sphere, new THREE.MeshColorStrokeMaterial( 0x00aa00, 1, 1.5 ) );
//mesh = new THREE.Mesh( sphere, new THREE.MeshFaceColorStrokeMaterial( 2.5 ) );
//mesh = new THREE.Mesh( sphere, new THREE.MeshLambertMaterial( ) );
mesh = new THREE.Mesh( sphere, [ new THREE.MeshLambertMaterial( { color: 0xffffff } ),
new THREE.MeshLambertMaterial( { color: 0x000000, wireframe: true, wireframe_linewidth: 1.5 } ) ] );
//mesh = new THREE.Mesh( sphere, new THREE.MeshLambertMaterial( { color: 0x00aa00, wireframe: true, wireframe_linewidth: 1.5 } ) );
//mesh = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { wireframe: true, wireframe_linewidth: 2.5 } ) );
mesh.position.x = 500 * (Math.random() - 0.5);
mesh.position.y = 500 * (Math.random() - 0.5);
mesh.position.z = 500 * (Math.random() - 0.5);
@@ -182,7 +184,7 @@
pointLight.position.z = 120;
//scene.addLight( pointLight );
mesh = new THREE.Mesh( sphere, new THREE.MeshColorFillMaterial( 0xff0000 ) );
mesh = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0xff0000 } ) );
mesh.scale.x = mesh.scale.y = mesh.scale.z = 0.1;
mesh.position = pointLight.position;
mesh.updateMatrix();
@@ -215,9 +217,8 @@
bwebgl.addEventListener("click", toggleWebGL, false);
var loader = new THREE.Loader();
loader.loadAsciiOld( "obj/female02/female02.js", function() { createScene( new Female02( "obj/female02" ) ) } );
//loader.loadAscii( "obj/female02/Female02_slim.js", function( geometry ) { createScene( geometry) }, "obj/female02" );
//loader.loadBinary( "obj/female02/Female02_bin.js", function( geometry ) { createScene( geometry) }, "obj/female02" );
loader.loadAscii( "obj/female02/Female02_slim.js", function( geometry ) { createScene( geometry) }, "obj/female02" );
//loader.loadBinary( "obj/female02/Female02_bin.js", function( geometry ) { createScene( geometry) }, "obj/female02" );
}
@@ -252,24 +253,24 @@
xc2.fillRect(i*4, 5, 2, 54);
}
var xm1 = new THREE.MeshBitmapMaterial( x1 );
xm1.loaded = 1; // this is procedurally generated texture
var xm1 = new THREE.MeshLambertMaterial( { map: new THREE.Texture( x1 ) } );
xm1.map.loaded = 1; // this is procedurally generated texture
var xm2 = new THREE.MeshBitmapMaterial( x2 );
xm2.loaded = 1; // this is procedurally generated texture
var xm2 = new THREE.MeshLambertMaterial( { map: new THREE.Texture( x2 ) } );
xm2.map.loaded = 1; // this is procedurally generated texture
geometry.materials[0].push ( xm1 ); // goes to faces with material 0
geometry.materials[1].push ( xm2 ); // goes to faces with material 1
geometry.materials[4].push ( new THREE.MeshColorFillMaterial(0xff0000, 0.5) );
geometry.materials[4].push ( new THREE.MeshLambertMaterial( { color: 0xff0000, opacity:0.5 } ) );
var materials = [ new THREE.MeshFaceMaterial() ];
// full-mesh wireframe overlay
//materials.push( new THREE.MeshColorStrokeMaterial(0xff0000, 1, 1.5) );
//materials.push( new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true, wireframe_linewidth: 1.5 } ) );
// full-mesh color overlay
//materials.push( new THREE.MeshColorFillMaterial(0xff0000, 0.5) );
//materials.push( new THREE.MeshBasicMaterial { color: 0xff0000, opacity: 0.5 } ) );
zmesh = new THREE.Mesh( geometry, materials, 1 );
zmesh.position.x = -80;
@@ -283,6 +284,7 @@
// PLANES with all materials from the model
createMaterialsPalette( geometry.materials, 100, 0 );
}
function createMaterialsPalette( materials, size, bottom ) {
@@ -309,8 +311,8 @@
xc.font = "50pt arial bold";
xc.fillText(i, 10, 64);
var xm = new THREE.MeshBitmapMaterial( x );
xm.loaded = 1;
var xm = new THREE.MeshBasicMaterial( { map: new THREE.Texture( x ) } );
xm.map.loaded = 1;
mesh = new THREE.Mesh( new Plane( size, size ), xm );
mesh.position.x = i * (size + 5) - ( ( materials.length - 1 )* ( size + 5 )/2);
+30 -46
View File
@@ -41,11 +41,10 @@
<pre id="log"></pre>
<script type="text/javascript" src="../build/Three.js"></script>
<!--
<script type="text/javascript" src="../build/Three.js"></script>
-->
<!--
<script type="text/javascript" src="../src/Three.js"></script>
<script type="text/javascript" src="../src/core/Color.js"></script>
<script type="text/javascript" src="../src/core/Vector2.js"></script>
@@ -69,13 +68,15 @@
<script type="text/javascript" src="../src/objects/Mesh.js"></script>
<script type="text/javascript" src="../src/objects/Particle.js"></script>
<script type="text/javascript" src="../src/objects/Line.js"></script>
<script type="text/javascript" src="../src/materials/LineColorMaterial.js"></script>
<script type="text/javascript" src="../src/materials/Material.js"></script>
<script type="text/javascript" src="../src/materials/LineBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshLambertMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshPhongMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshFaceMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleCircleMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleBitmapMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/Texture.js"></script>
<script type="text/javascript" src="../src/scenes/Scene.js"></script>
<script type="text/javascript" src="../src/renderers/Projector.js"></script>
<script type="text/javascript" src="../src/renderers/CanvasRenderer.js"></script>
@@ -85,6 +86,7 @@
<script type="text/javascript" src="../src/renderers/renderables/RenderableFace4.js"></script>
<script type="text/javascript" src="../src/renderers/renderables/RenderableParticle.js"></script>
<script type="text/javascript" src="../src/renderers/renderables/RenderableLine.js"></script>
<!--
-->
<script type="text/javascript" src="../src/extras/primitives/Sphere.js"></script>
@@ -179,7 +181,7 @@
// light representation
sphere = new Sphere( 100, 16, 8, 1 );
lightMesh = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0xffaa00 } );
lightMesh = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0xffaa00 } ) );
lightMesh.scale.x = lightMesh.scale.y = lightMesh.scale.z = 0.05;
lightMesh.position = pointLight.position;
lightMesh.overdraw = true;
@@ -191,26 +193,26 @@
var y1 = 0, y2 = -200;
addMesh( sphere, 1, -600, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x050505, diffuse: 0x000000, specular: 0x555555, shininess: 30 } );
addMesh( sphere, 1, -600, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { diffuse: 0x050505 } );
addMesh( sphere, 1, -600, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x050505, color: 0x000000, specular: 0x555555, shininess: 30 } ) );
addMesh( sphere, 1, -600, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { color: 0x050505 } ) );
addMesh( sphere, 1, -400, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, diffuse: 0xffffff, specular: 0x555555, shininess: 30 } );
addMesh( sphere, 1, -400, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { diffuse: 0xffffff } );
addMesh( sphere, 1, -400, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, color: 0xffffff, specular: 0x555555, shininess: 30 } ) );
addMesh( sphere, 1, -400, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { color: 0xffffff } ) );
addMesh( sphere, 1, -200, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, diffuse: 0xff5500, specular: 0x555555, shininess: 10 } );
addMesh( sphere, 1, -200, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { diffuse: 0xff5500 } );
addMesh( sphere, 1, -200, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, color: 0xff5500, specular: 0x555555, shininess: 10 } ) );
addMesh( sphere, 1, -200, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { color: 0xff5500 } ) );
addMesh( sphere, 1, 0, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, diffuse: 0xffaa00, specular: 0x555555, shininess: 30 } );
addMesh( sphere, 1, 0, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { diffuse: 0xffaa00 } );
addMesh( sphere, 1, 0, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, color: 0xffaa00, specular: 0x555555, shininess: 30 } ) );
addMesh( sphere, 1, 0, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { color: 0xffaa00 } ) );
addMesh( sphere, 1, 200, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, diffuse: 0x55ff00, specular: 0x555555, shininess: 30 } );
addMesh( sphere, 1, 200, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { diffuse: 0x55ff00 } );
addMesh( sphere, 1, 200, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, color: 0x55ff00, specular: 0x555555, shininess: 30 } ) );
addMesh( sphere, 1, 200, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { color: 0x55ff00 } ) );
addMesh( sphere, 1, 400, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, diffuse: 0x0055ff, specular: 0x555555, shininess: 30 } );
addMesh( sphere, 1, 400, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { diffuse: 0x0055ff } );
addMesh( sphere, 1, 400, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, color: 0x0055ff, specular: 0x555555, shininess: 30 } ) );
addMesh( sphere, 1, 400, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { color: 0x0055ff } ) );
addMesh( sphere, 1, 600, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, diffuse: 0x5500ff, specular: 0x555555, shininess: 30 } );
addMesh( sphere, 1, 600, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { diffuse: 0x5500ff } );
addMesh( sphere, 1, 600, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, color: 0x5500ff, specular: 0x555555, shininess: 30 } ) );
addMesh( sphere, 1, 600, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { color: 0x5500ff } ) );
if ( render_gl ) {
try {
@@ -240,9 +242,8 @@
bwebgl.addEventListener("click", toggleWebGL, false);
var loader = new THREE.Loader();
loader.loadAsciiOld( "obj/torus/Torus.js", function() { createScene( new Torus() ) } );
//loader.loadAscii( "obj/torus/Torus_slim.js", function( geometry ) { createScene( geometry ) } );
//loader.loadBinary( "obj/torus/Torus_bin.js", function( geometry ) { createScene( geometry ) }, "obj/torus" );
loader.loadAscii( "obj/torus/Torus_slim.js", function( geometry ) { createScene( geometry ) } );
//loader.loadBinary( "obj/torus/Torus_bin.js", function( geometry ) { createScene( geometry ) }, "obj/torus" );
}
@@ -250,23 +251,13 @@
var s = 80, t = s + 20, y = 200;
addMesh( geometry, s, -6*t, y, 0, 1.57,0,0, new THREE.MeshPhongMaterial( 0x000000, 0x000000, 0x333333, 10, 1.0 ) );
addMesh( geometry, s, -4*t, y, 0, 1.57,0,0, new THREE.MeshPhongMaterial( 0x030303, 0x888888, 0x333333, 10, 1.0 ) );
addMesh( geometry, s, -2*t, y, 0, 1.57,0,0, new THREE.MeshPhongMaterial( 0x030303, 0x030303, 0xff5500, 10, 1.0 ) );
addMesh( geometry, s, 0, y, 0, 1.57,0,0, new THREE.MeshPhongMaterial( 0x030303, 0x030303, 0xffaa00, 10, 1.0 ) );
addMesh( geometry, s, 2*t, y, 0, 1.57,0,0, new THREE.MeshPhongMaterial( 0x030303, 0x030303, 0x55ff00, 10, 1.0 ) );
addMesh( geometry, s, 4*t, y, 0, 1.57,0,0, new THREE.MeshPhongMaterial( 0x030303, 0x030303, 0x0055ff, 10, 1.0 ) );
addMesh( geometry, s, 6*t, y, 0, 1.57,0,0, new THREE.MeshPhongMaterial( 0x030303, 0x030303, 0x5500ff, 10, 1.0 ) );
}
function loadAsync( url, callback ) {
var el = document.createElement( 'script' );
el.type = 'text/javascript';
el.onload = callback;
el.src = url;
document.getElementsByTagName("head")[0].appendChild(el);
addMesh( geometry, s, -6*t, y, 0, 1.57,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, color: 0x000000, specular: 0x333333, shininess: 10 } ) );
addMesh( geometry, s, -4*t, y, 0, 1.57,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x888888, specular: 0x333333, shininess: 10 } ) );
addMesh( geometry, s, -2*t, y, 0, 1.57,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x030303, specular: 0xff5500, shininess: 10 } ) );
addMesh( geometry, s, 0, y, 0, 1.57,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x030303, specular: 0xffaa00, shininess: 10 } ) );
addMesh( geometry, s, 2*t, y, 0, 1.57,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x030303, specular: 0x55ff00, shininess: 10 } ) );
addMesh( geometry, s, 4*t, y, 0, 1.57,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x030303, specular: 0x0055ff, shininess: 10 } ) );
addMesh( geometry, s, 6*t, y, 0, 1.57,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x030303, specular: 0x5500ff, shininess: 10 } ) );
}
@@ -285,14 +276,7 @@
camera.position.x += ( mouseX - camera.position.x ) * .05;
camera.position.y += ( - mouseY - camera.position.y ) * .05;
camera.updateMatrix();
/*
for(var i=0; i<scene.objects.length; ++i) {
scene.objects[i].rotation.x += 0.0025;
scene.objects[i].updateMatrix();
}
*/
lightMesh.position.x = 700*Math.cos(r);
lightMesh.position.z = 700*Math.sin(r);
lightMesh.updateMatrix();
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+12 -14
View File
@@ -69,14 +69,15 @@
<script type="text/javascript" src="../src/objects/Mesh.js"></script>
<script type="text/javascript" src="../src/objects/Particle.js"></script>
<script type="text/javascript" src="../src/objects/Line.js"></script>
<script type="text/javascript" src="../src/materials/LineColorMaterial.js"></script>
<script type="text/javascript" src="../src/materials/Material.js"></script>
<script type="text/javascript" src="../src/materials/LineBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshLambertMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshPhongMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshBitmapMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshColorFillMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshColorStrokeMaterial.js"></script>
<script type="text/javascript" src="../src/materials/MeshFaceMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleCircleMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleBitmapMaterial.js"></script>
<script type="text/javascript" src="../src/materials/ParticleBasicMaterial.js"></script>
<script type="text/javascript" src="../src/materials/Texture.js"></script>
<script type="text/javascript" src="../src/scenes/Scene.js"></script>
<script type="text/javascript" src="../src/renderers/Projector.js"></script>
<script type="text/javascript" src="../src/renderers/CanvasRenderer.js"></script>
@@ -162,8 +163,8 @@
xc.fillStyle = "#555";
xc.fillRect(96, 96, 32, 32);
var xm = new THREE.MeshBitmapMaterial( x );
xm.loaded = 1;
var xm = new THREE.MeshBasicMaterial( { map: new THREE.Texture( x ) } );
xm.map.loaded = 1;
geometry = new Plane( 100, 100, 15, 10 );
for(var i=0; i<geometry.uvs.length; i++) {
@@ -187,7 +188,7 @@
sphere = new Sphere( 100, 16, 8, 1 );
for (var i=0; i<10; i++) {
mesh = new THREE.Mesh( sphere, new THREE.MeshColorFillMaterial( 0xdddddd ) );
mesh = new THREE.Mesh( sphere, new THREE.MeshLambertMaterial( { color: 0xdddddd } ) );
mesh.position.x = 500 * (Math.random() - 0.5);
mesh.position.y = 300 * (Math.random() - 0) + FLOOR;
mesh.position.z = 100 * (Math.random() - 1);
@@ -241,9 +242,6 @@
bwebgl.addEventListener("click", toggleWebGL, false);
var loader = new THREE.Loader();
//loader.loadAsciiOld( "obj/male02/male02.js", function() { createScene( new Male02( "obj/male02" ), 90, 50, FLOOR, 105 ) } );
//loader.loadAsciiOld( "obj/female02/female02.js", function() { createScene( new Female02( "obj/female02" ), -80, 50, FLOOR, 0 ) } );
//loader.loadAscii( "obj/male02/Male02_slim.js", function( geometry ) { createScene( geometry, 90, 50, FLOOR, 105 ) }, "obj/male02" );
//loader.loadAscii( "obj/female02/Female02_slim.js", function( geometry ) { createScene( geometry, -80, 50, FLOOR, 0 ) }, "obj/female02" );
@@ -291,8 +289,8 @@
xc.font = "50pt arial bold";
xc.fillText(i, 10, 64);
var xm = new THREE.MeshBitmapMaterial( x );
xm.loaded = 1;
var xm = new THREE.MeshBasicMaterial( { map: new THREE.Texture( x ) } );
xm.map.loaded = 1;
mesh = new THREE.Mesh( new Plane( size, size ), xm );
mesh.position.x = i * (size + 5) - ( ( materials.length - 1 )* ( size + 5 )/2);
@@ -323,7 +321,7 @@
zmesh.rotation.y += 0.005;
zmesh.updateMatrix();
}
if ( render_canvas ) canvasRenderer.render( scene, camera );
if ( render_gl && has_gl ) webglRenderer.render( scene, camera );
+1
View File
@@ -212,6 +212,7 @@
webglRenderer = new THREE.WebGLRenderer();
webglRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
//webglRenderer.setFaceCulling( 0 );
container.appendChild( webglRenderer.domElement );
stats = new Stats();
+9 -9
View File
@@ -951,7 +951,7 @@ THREE.Loader.prototype = {
if ( m.map_diffuse && urlbase ) {
texture = document.createElement( 'canvas' );
material = new THREE.MeshBitmapMaterial( texture );
material = new THREE.MeshLambertMaterial( { map: new THREE.Texture( texture ) } );
image = new Image();
image.onload = function () {
@@ -961,17 +961,17 @@ THREE.Loader.prototype = {
var w = nearest_pow2( this.width ),
h = nearest_pow2( this.height );
material.bitmap.width = w;
material.bitmap.height = h;
material.bitmap.getContext("2d").drawImage( this, 0, 0, w, h );
material.map.image.width = w;
material.map.image.height = h;
material.map.image.getContext("2d").drawImage( this, 0, 0, w, h );
} else {
material.bitmap = this;
material.map.image = this;
}
material.loaded = 1;
material.map.loaded = 1;
};
@@ -980,15 +980,15 @@ THREE.Loader.prototype = {
} else if ( m.col_diffuse ) {
color = (m.col_diffuse[0]*255 << 16) + (m.col_diffuse[1]*255 << 8) + m.col_diffuse[2]*255;
material = new THREE.MeshColorFillMaterial( color, m.transparency );
material = new THREE.MeshLambertMaterial( { color: color, opacity: m.transparency } );
} else if ( m.a_dbg_color ) {
material = new THREE.MeshColorFillMaterial( m.a_dbg_color );
material = new THREE.MeshLambertMaterial( { color: m.a_dbg_color } );
} else {
material = new THREE.MeshColorFillMaterial( 0xeeeeee );
material = new THREE.MeshLambertMaterial( { color: 0xeeeeee } );
}
+1 -1
View File
@@ -16,7 +16,7 @@ THREE.MeshBasicMaterial = function ( parameters ) {
this.id = THREE.MeshBasicMaterialCounter.value ++;
this.color = new THREE.Color( 0xff0000 );
this.color = new THREE.Color( 0xeeeeee );
this.map = null;
this.opacity = 1;
this.blending = THREE.NormalBlending;
+1 -1
View File
@@ -17,7 +17,7 @@ THREE.MeshLambertMaterial = function ( parameters ) {
this.id = THREE.MeshLambertMaterialCounter.value ++;
this.color = new THREE.Color( 0xff0000 );
this.color = new THREE.Color( 0xeeeeee );
this.map = null;
this.opacity = 1;
this.shading = THREE.GouraudShading;
+2 -2
View File
@@ -21,7 +21,7 @@ THREE.MeshPhongMaterial = function ( parameters ) {
this.id = THREE.MeshPhongMaterialCounter.value ++;
this.color = new THREE.Color( 0xff0000 );
this.color = new THREE.Color( 0xeeeeee );
this.map = null;
this.ambient = new THREE.Color( 0x050505 );
this.specular = new THREE.Color( 0x111111 );
@@ -38,7 +38,7 @@ THREE.MeshPhongMaterial = function ( parameters ) {
if ( parameters.color !== undefined ) this.color = new THREE.Color( parameters.color );
if ( parameters.map !== undefined ) this.map = parameters.map;
if ( parameters.ambient !== undefined ) this.ambient = new THREE.Color( parameters.ambient );
if ( parameters.specular !== undefined ) this.specular_color = new THREE.Color( parameters.specular );
if ( parameters.specular !== undefined ) this.specular = new THREE.Color( parameters.specular );
if ( parameters.specular_map !== undefined ) this.specular_map = parameters.specular_map;
if ( parameters.shininess !== undefined ) this.shininess = parameters.shininess;
if ( parameters.opacity !== undefined ) this.opacity = parameters.opacity;
+92 -71
View File
@@ -18,7 +18,7 @@ THREE.WebGLRenderer = function ( scene ) {
var _canvas = document.createElement( 'canvas' ), _gl, _program,
_modelViewMatrix = new THREE.Matrix4(), _normalMatrix,
COLORFILL = 0, COLORSTROKE = 1, BITMAP = 2, PHONG = 3, // material constants used in shader
BASIC = 0, LAMBERT = 1, PHONG = 2, // material constants used in shader
maxLightCount = allocateLights( scene, 5 );
@@ -91,7 +91,7 @@ THREE.WebGLRenderer = function ( scene ) {
this.setupLights = function ( scene ) {
var l, ll, light, r, g, b,
ambientLights = [], pointLights = [], directionalLights = [],
ambientLights = [], pointLights = [], directionalLights = [],
colors = [], positions = [];
_gl.uniform1i( _program.enableLighting, scene.lights.length );
@@ -334,42 +334,58 @@ THREE.WebGLRenderer = function ( scene ) {
this.renderBuffer = function ( material, materialFaceGroup ) {
var mColor, mOpacity, mWireframe, mLineWidth, mBlending,
mAmbient, mSpecular, mShininess,
mMap;
if ( material instanceof THREE.MeshPhongMaterial ||
material instanceof THREE.MeshLambertMaterial ||
material instanceof THREE.MeshBasicMaterial ) {
mColor = material.color;
mOpacity = material.opacity;
mWireframe = material.wireframe;
mLineWidth = material.wireframe_linewidth;
mBlending = material.blending;
mMap = material.map;
_gl.uniform4f( _program.mColor, mColor.r * mOpacity, mColor.g * mOpacity, mColor.b * mOpacity, mOpacity );
}
if ( material instanceof THREE.MeshPhongMaterial ) {
mAmbient = material.ambient;
mDiffuse = material.diffuse;
mSpecular = material.specular;
_gl.uniform4f( _program.mAmbient, mAmbient.r, mAmbient.g, mAmbient.b, material.opacity );
_gl.uniform4f( _program.mDiffuse, mDiffuse.r, mDiffuse.g, mDiffuse.b, material.opacity );
_gl.uniform4f( _program.mSpecular, mSpecular.r, mSpecular.g, mSpecular.b, material.opacity );
_gl.uniform1f( _program.mShininess, material.shininess );
mShininess = material.shininess;
_gl.uniform4f( _program.mAmbient, mAmbient.r, mAmbient.g, mAmbient.b, mOpacity );
_gl.uniform4f( _program.mSpecular, mSpecular.r, mSpecular.g, mSpecular.b, mOpacity );
_gl.uniform1f( _program.mShininess, mShininess );
_gl.uniform1i( _program.material, PHONG );
} else if ( material instanceof THREE.MeshColorFillMaterial ) {
} else if ( material instanceof THREE.MeshLambertMaterial ) {
_gl.uniform1i( _program.material, LAMBERT );
color = material.color;
_gl.uniform4f( _program.mColor, color.r * color.a, color.g * color.a, color.b * color.a, color.a );
_gl.uniform1i( _program.material, COLORFILL );
} else if ( material instanceof THREE.MeshBasicMaterial ) {
} else if ( material instanceof THREE.MeshColorStrokeMaterial ) {
_gl.uniform1i( _program.material, BASIC );
lineWidth = material.lineWidth;
}
if ( mMap ) {
color = material.color;
_gl.uniform4f( _program.mColor, color.r * color.a, color.g * color.a, color.b * color.a, color.a );
_gl.uniform1i( _program.material, COLORSTROKE );
} else if ( material instanceof THREE.MeshBitmapMaterial ) {
if ( !material.__webGLTexture && material.loaded ) {
if ( !material.__webGLTexture && material.map.loaded ) {
material.__webGLTexture = _gl.createTexture();
_gl.bindTexture( _gl.TEXTURE_2D, material.__webGLTexture );
_gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, material.bitmap ) ;
_gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, material.map.image ) ;
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.LINEAR );
//_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR_MIPMAP_NEAREST );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR_MIPMAP_LINEAR );
_gl.generateMipmap( _gl.TEXTURE_2D );
_gl.bindTexture( _gl.TEXTURE_2D, null );
@@ -378,11 +394,16 @@ THREE.WebGLRenderer = function ( scene ) {
_gl.activeTexture( _gl.TEXTURE0 );
_gl.bindTexture( _gl.TEXTURE_2D, material.__webGLTexture );
_gl.uniform1i( _program.tDiffuse, 0 );
_gl.uniform1i( _program.tMap, 0 );
_gl.uniform1i( _program.material, BITMAP );
_gl.uniform1i( _program.enableMap, 1 );
} else {
_gl.uniform1i( _program.enableMap, 0 );
}
// vertices
@@ -396,7 +417,7 @@ THREE.WebGLRenderer = function ( scene ) {
// uvs
if ( material instanceof THREE.MeshBitmapMaterial ) {
if ( mMap ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLUVBuffer );
@@ -411,19 +432,16 @@ THREE.WebGLRenderer = function ( scene ) {
// render triangles
if ( material instanceof THREE.MeshBitmapMaterial ||
material instanceof THREE.MeshColorFillMaterial ||
material instanceof THREE.MeshPhongMaterial ) {
if ( ! mWireframe ) {
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLFaceBuffer );
_gl.drawElements( _gl.TRIANGLES, materialFaceGroup.__webGLFaceCount, _gl.UNSIGNED_SHORT, 0 );
// render lines
} else if ( material instanceof THREE.MeshColorStrokeMaterial ) {
} else {
_gl.lineWidth( lineWidth );
_gl.lineWidth( mLineWidth );
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLLineBuffer );
_gl.drawElements( _gl.LINES, materialFaceGroup.__webGLLineCount, _gl.UNSIGNED_SHORT, 0 );
@@ -631,13 +649,14 @@ THREE.WebGLRenderer = function ( scene ) {
maxDirLights ? "#define MAX_DIR_LIGHTS " + maxDirLights : "",
maxPointLights ? "#define MAX_POINT_LIGHTS " + maxPointLights : "",
"uniform int material;", // 0 - ColorFill, 1 - ColorStroke, 2 - Bitmap, 3 - Phong
"uniform int material;", // 0 - Basic, 1 - Lambert, 2 - Phong
"uniform sampler2D tDiffuse;",
"uniform bool enableMap;",
"uniform sampler2D tMap;",
"uniform vec4 mColor;",
"uniform vec4 mAmbient;",
"uniform vec4 mDiffuse;",
"uniform vec4 mSpecular;",
"uniform float mShininess;",
@@ -658,10 +677,18 @@ THREE.WebGLRenderer = function ( scene ) {
"void main() {",
"vec4 mapColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
// Blinn-Phong
// based on o3d example
"if ( material == 3 ) { ",
"if ( enableMap ) {",
"mapColor = texture2D( tMap, vUv );",
"}",
"if ( material == 2 ) { ",
"vec3 normal = normalize( vNormal );",
"vec3 viewPosition = normalize( vViewPosition );",
@@ -694,7 +721,7 @@ THREE.WebGLRenderer = function ( scene ) {
maxPointLights ? "if ( pointDotNormalHalf >= 0.0 )" : "",
maxPointLights ? "pointSpecularWeight = pow( pointDotNormalHalf, mShininess );" : "",
maxPointLights ? "pointDiffuse += mDiffuse * pointDiffuseWeight;" : "",
maxPointLights ? "pointDiffuse += mColor * pointDiffuseWeight;" : "",
maxPointLights ? "pointSpecular += mSpecular * pointSpecularWeight;" : "",
maxPointLights ? "}" : "",
@@ -719,7 +746,7 @@ THREE.WebGLRenderer = function ( scene ) {
maxDirLights ? "if ( dirDotNormalHalf >= 0.0 )" : "",
maxDirLights ? "dirSpecularWeight = pow( dirDotNormalHalf, mShininess );" : "",
maxDirLights ? "dirDiffuse += mDiffuse * dirDiffuseWeight;" : "",
maxDirLights ? "dirDiffuse += mColor * dirDiffuseWeight;" : "",
maxDirLights ? "dirSpecular += mSpecular * dirSpecularWeight;" : "",
maxDirLights ? "}" : "",
@@ -732,27 +759,19 @@ THREE.WebGLRenderer = function ( scene ) {
// looks nicer with weighting
"gl_FragColor = vec4( totalLight.xyz * vLightWeighting, 1.0 );",
//"gl_FragColor = vec4( totalLight.xyz, 1.0 );",
"gl_FragColor = vec4( mapColor.rgb * totalLight.xyz * vLightWeighting, mapColor.a );",
// Bitmap: texture
"} else if ( material == 2 ) {",
"vec4 texelColor = texture2D( tDiffuse, vUv );",
"gl_FragColor = vec4( texelColor.rgb * vLightWeighting, texelColor.a );",
// ColorStroke: wireframe using uniform color
// Lambert: diffuse lighting
"} else if ( material == 1 ) {",
"gl_FragColor = vec4( mColor.rgb * vLightWeighting, mColor.a );",
"gl_FragColor = vec4( mColor.rgb * mapColor.rgb * vLightWeighting, mColor.a * mapColor.a );",
// ColorFill: triangle using uniform color
// Basic: unlit color / texture
"} else {",
"gl_FragColor = vec4( mColor.rgb * vLightWeighting, mColor.a );",
"gl_FragColor = mColor * mapColor;",
"}",
@@ -884,49 +903,51 @@ THREE.WebGLRenderer = function ( scene ) {
_program.normalMatrix = _gl.getUniformLocation( _program, "normalMatrix" );
_program.objMatrix = _gl.getUniformLocation( _program, "objMatrix" );
_program.cameraPosition = _gl.getUniformLocation(_program, 'cameraPosition');
_program.cameraPosition = _gl.getUniformLocation( _program, 'cameraPosition' );
// lights
_program.enableLighting = _gl.getUniformLocation(_program, 'enableLighting');
_program.enableLighting = _gl.getUniformLocation( _program, 'enableLighting' );
_program.ambientLightColor = _gl.getUniformLocation(_program, 'ambientLightColor');
_program.ambientLightColor = _gl.getUniformLocation( _program, 'ambientLightColor' );
if ( maxDirLights ) {
_program.directionalLightNumber = _gl.getUniformLocation(_program, 'directionalLightNumber');
_program.directionalLightColor = _gl.getUniformLocation(_program, 'directionalLightColor');
_program.directionalLightDirection = _gl.getUniformLocation(_program, 'directionalLightDirection');
_program.directionalLightNumber = _gl.getUniformLocation( _program, 'directionalLightNumber' );
_program.directionalLightColor = _gl.getUniformLocation( _program, 'directionalLightColor' );
_program.directionalLightDirection = _gl.getUniformLocation( _program, 'directionalLightDirection' );
}
if ( maxPointLights ) {
_program.pointLightNumber = _gl.getUniformLocation(_program, 'pointLightNumber');
_program.pointLightColor = _gl.getUniformLocation(_program, 'pointLightColor');
_program.pointLightPosition = _gl.getUniformLocation(_program, 'pointLightPosition');
_program.pointLightNumber = _gl.getUniformLocation( _program, 'pointLightNumber' );
_program.pointLightColor = _gl.getUniformLocation( _program, 'pointLightColor' );
_program.pointLightPosition = _gl.getUniformLocation( _program, 'pointLightPosition' );
}
// material
_program.material = _gl.getUniformLocation(_program, 'material');
_program.material = _gl.getUniformLocation( _program, 'material' );
// material properties (ColorFill / ColorStroke shader)
// material properties (Basic / Lambert / Blinn-Phong shader)
_program.mColor = _gl.getUniformLocation(_program, 'mColor');
_program.mColor = _gl.getUniformLocation( _program, 'mColor' );
// material properties (Blinn-Phong shader)
_program.mAmbient = _gl.getUniformLocation(_program, 'mAmbient');
_program.mDiffuse = _gl.getUniformLocation(_program, 'mDiffuse');
_program.mSpecular = _gl.getUniformLocation(_program, 'mSpecular');
_program.mShininess = _gl.getUniformLocation(_program, 'mShininess');
_program.mAmbient = _gl.getUniformLocation( _program, 'mAmbient' );
_program.mSpecular = _gl.getUniformLocation( _program, 'mSpecular' );
_program.mShininess = _gl.getUniformLocation( _program, 'mShininess' );
// texture (Bitmap shader)
// texture (diffuse map)
_program.tDiffuse = _gl.getUniformLocation( _program, "tDiffuse");
_gl.uniform1i( _program.tDiffuse, 0 );
_program.enableMap = _gl.getUniformLocation( _program, "enableMap" );
_gl.uniform1i( _program.enableMap, 0 );
_program.tMap = _gl.getUniformLocation( _program, "tMap" );
_gl.uniform1i( _program.tMap, 0 );
// vertex arrays
-851
View File
@@ -1,851 +0,0 @@
"""Convert Wavefront OBJ / MTL files into Three.js
-------------------------
How to use this converter
-------------------------
python convert_obj_threejs.py -i filename.obj -o filename.js [-a center|top|bottom] [-s smooth|flat]
Note: by default, model is centered (middle of bounding box goes to 0,0,0)
and uses smooth shading (if there were vertex normals in the original
model).
--------------------------------------------------
How to use generated JS file in your HTML document
--------------------------------------------------
<script type="text/javascript" src="Three.js"></script>
<script type="text/javascript" src="ModelName.js"></script>
...
<script type="text/javascript">
...
var normalizeUVsFlag = 1; // set to 1 if canvas render has missing materials
var geometry = new ModelName( path_to_textures );
var mesh = new THREE.Mesh( geometry, geometry.materials, normalizeUVsFlag );
...
</script>
-------------------------------------
Parsers based on formats descriptions
-------------------------------------
http://en.wikipedia.org/wiki/Obj
http://en.wikipedia.org/wiki/Material_Template_Library
-------------------
Current limitations
-------------------
- for the moment, only diffuse color and texture are used
(will need to extend shaders / renderers / materials in Three)
- models can have more than 65,536 vertices,
but in most cases it will not work well with browsers,
which currently seem to have troubles with handling
large JS files
- texture coordinates can be wrong in canvas renderer
(there is crude normalization, but it doesn't
work for all cases)
- smoothing can be turned on/off only for the whole mesh
----------------------------------------------
How to get proper OBJ + MTL files with Blender
----------------------------------------------
0. Remove default cube (press DEL and ENTER)
1. Import / create model
2. Select all meshes (Select -> Select All by Type -> Mesh)
3. Export to OBJ (File -> Export -> Wavefront .obj) [*]
- enable following options in exporter
Material Groups
Rotate X90
Apply Modifiers
High Quality Normals
Copy Images
Selection Only
Objects as OBJ Objects
UVs
Normals
Materials
Edges
- select empty folder
- give your exported file name with "obj" extension
- click on "Export OBJ" button
4. Your model is now all files in this folder (OBJ, MTL, number of images)
- this converter assumes all files staying in the same folder,
(OBJ / MTL files use relative paths)
- for WebGL, textures must be power of 2 sized
[*] If OBJ export fails (Blender 2.54 beta), patch your Blender installation
following instructions here:
http://www.blendernation.com/2010/09/12/blender-2-54-beta-released/
------
Author
------
AlteredQualia http://alteredqualia.com
"""
import fileinput
import operator
import random
import os.path
import getopt
import sys
# #####################################################
# Configuration
# #####################################################
ALIGN = "center" # center bottom top none
SHADING = "smooth" # flat smooth
# default colors for debugging (each material gets one distinct color):
# white, red, green, blue, yellow, cyan, magenta
COLORS = [0xeeeeee, 0xee0000, 0x00ee00, 0x0000ee, 0xeeee00, 0x00eeee, 0xee00ee]
# #####################################################
# Templates
# #####################################################
TEMPLATE_FILE = u"""\
// Converted from: %(fname)s
// vertices: %(nvertex)d
// faces: %(nface)d
// materials: %(nmaterial)d
//
// Generated with OBJ -> Three.js converter
// http://github.com/alteredq/three.js/blob/master/utils/exporters/convert_obj_threejs.py
var %(name)s = function ( urlbase ) {
var scope = this;
THREE.Geometry.call(this);
var materials = [%(materials)s];
init_materials();
var normals = [%(normals)s];
%(vertices)s
%(uvs)s
%(faces)s
this.computeCentroids();
this.computeNormals();
function material_color( mi ) {
var m = materials[mi];
if( m.col_diffuse )
return (m.col_diffuse[0]*255 << 16) + (m.col_diffuse[1]*255 << 8) + m.col_diffuse[2]*255;
else if ( m.a_dbg_color )
return m.a_dbg_color;
else
return 0xffeeeeee;
}
function v( x, y, z ) {
scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
}
function f3( a, b, c, mi ) {
var material = scope.materials[ mi ];
scope.faces.push( new THREE.Face3( a, b, c, null, material ) );
}
function f4( a, b, c, d, mi ) {
var material = scope.materials[ mi ];
scope.faces.push( new THREE.Face4( a, b, c, d, null, material ) );
}
function f3n( a, b, c, mi, n1, n2, n3 ) {
var material = scope.materials[ mi ];
var n1x = normals[n1][0];
var n1y = normals[n1][1];
var n1z = normals[n1][2];
var n2x = normals[n2][0];
var n2y = normals[n2][1];
var n2z = normals[n2][2];
var n3x = normals[n3][0];
var n3y = normals[n3][1];
var n3z = normals[n3][2];
scope.faces.push( new THREE.Face3( a, b, c,
[new THREE.Vector3( n1x, n1y, n1z ), new THREE.Vector3( n2x, n2y, n2z ), new THREE.Vector3( n3x, n3y, n3z )],
material ) );
}
function f4n( a, b, c, d, mi, n1, n2, n3, n4 ) {
var material = scope.materials[ mi ];
var n1x = normals[n1][0];
var n1y = normals[n1][1];
var n1z = normals[n1][2];
var n2x = normals[n2][0];
var n2y = normals[n2][1];
var n2z = normals[n2][2];
var n3x = normals[n3][0];
var n3y = normals[n3][1];
var n3z = normals[n3][2];
var n4x = normals[n4][0];
var n4y = normals[n4][1];
var n4z = normals[n4][2];
scope.faces.push( new THREE.Face4( a, b, c, d,
[new THREE.Vector3( n1x, n1y, n1z ), new THREE.Vector3( n2x, n2y, n2z ), new THREE.Vector3( n3x, n3y, n3z ), new THREE.Vector3( n4x, n4y, n4z )],
material ) );
}
function uv( u1, v1, u2, v2, u3, v3, u4, v4 ) {
var uv = [];
uv.push( new THREE.UV( u1, v1 ) );
uv.push( new THREE.UV( u2, v2 ) );
uv.push( new THREE.UV( u3, v3 ) );
if ( u4 && v4 ) uv.push( new THREE.UV( u4, v4 ) );
scope.uvs.push( uv );
}
function init_materials() {
scope.materials = [];
for(var i=0; i<materials.length; ++i) {
scope.materials[i] = [ create_material( materials[i], urlbase ) ];
}
}
function is_pow2( n ) {
var l = Math.log(n) / Math.LN2;
return Math.floor(l) == l;
}
function nearest_pow2(n) {
var l = Math.log(n) / Math.LN2;
return Math.pow( 2, Math.round(l) );
}
function create_material( m ) {
var material;
if( m.map_diffuse && urlbase ) {
var texture = document.createElement( 'canvas' );
material = new THREE.MeshBitmapMaterial( texture );
var image = new Image();
image.onload = function () {
if ( !is_pow2(this.width) || !is_pow2(this.height) ) {
var w = nearest_pow2( this.width );
var h = nearest_pow2( this.height );
material.bitmap.width = w;
material.bitmap.height = h;
material.bitmap.getContext("2d").drawImage( this, 0, 0, w, h );
}
else {
material.bitmap = this;
}
material.loaded = 1;
};
image.src = urlbase + "/" + m.map_diffuse;
}
else if( m.col_diffuse ) {
var color = (m.col_diffuse[0]*255 << 16) + (m.col_diffuse[1]*255 << 8) + m.col_diffuse[2]*255;
material = new THREE.MeshColorFillMaterial( color, m.transparency );
}
else if( m.a_dbg_color ) {
material = new THREE.MeshColorFillMaterial( m.a_dbg_color );
}
else {
material = new THREE.MeshColorFillMaterial( 0xffeeeeee );
}
return material;
}
}
%(name)s.prototype = new THREE.Geometry();
%(name)s.prototype.constructor = %(name)s;
"""
TEMPLATE_VERTEX = "\tv(%f,%f,%f);"
TEMPLATE_UV3 = "\tuv(%f,%f,%f,%f,%f,%f);"
TEMPLATE_UV4 = "\tuv(%f,%f,%f,%f,%f,%f,%f,%f);"
TEMPLATE_FACE3 = "\tf3(%d,%d,%d,%d);"
TEMPLATE_FACE4 = "\tf4(%d,%d,%d,%d,%d);"
TEMPLATE_FACE3N = "\tf3n(%d,%d,%d, %d, %d,%d,%d);"
TEMPLATE_FACE4N = "\tf4n(%d,%d,%d,%d, %d, %d,%d,%d,%d);"
TEMPLATE_N = "[%f,%f,%f]"
# #####################################################
# Utils
# #####################################################
def file_exists(filename):
"""Return true if file exists and is accessible for reading.
Should be safer than just testing for existence due to links and
permissions magic on Unix filesystems.
@rtype: boolean
"""
try:
f = open(filename, 'r')
f.close()
return True
except IOError:
return False
def get_name(fname):
"""Create model name based of filename ("path/fname.js" -> "fname").
"""
return os.path.basename(fname).split(".")[0]
def bbox(vertices):
"""Compute bounding box of vertex array.
"""
if len(vertices)>0:
minx = maxx = vertices[0][0]
miny = maxy = vertices[0][1]
minz = maxz = vertices[0][2]
for v in vertices[1:]:
if v[0]<minx:
minx = v[0]
elif v[0]>maxx:
maxx = v[0]
if v[1]<miny:
miny = v[1]
elif v[1]>maxy:
maxy = v[1]
if v[2]<minz:
minz = v[2]
elif v[2]>maxz:
maxz = v[2]
return { 'x':[minx,maxx], 'y':[miny,maxy], 'z':[minz,maxz] }
else:
return { 'x':[0,0], 'y':[0,0], 'z':[0,0] }
def translate(vertices, t):
"""Translate array of vertices by vector t.
"""
for i in xrange(len(vertices)):
vertices[i][0] += t[0]
vertices[i][1] += t[1]
vertices[i][2] += t[2]
def center(vertices):
"""Center model (middle of bounding box).
"""
bb = bbox(vertices)
cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
cy = bb['y'][0] + (bb['y'][1] - bb['y'][0])/2.0
cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
translate(vertices, [-cx,-cy,-cz])
def top(vertices):
"""Align top of the model with the floor (Y-axis) and center it around X and Z.
"""
bb = bbox(vertices)
cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
cy = bb['y'][1]
cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
translate(vertices, [-cx,-cy,-cz])
def bottom(vertices):
"""Align bottom of the model with the floor (Y-axis) and center it around X and Z.
"""
bb = bbox(vertices)
cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
cy = bb['y'][0]
cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
translate(vertices, [-cx,-cy,-cz])
def normalize(v):
"""Normalize 3d vector"""
l = math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
v[0] /= l
v[1] /= l
v[2] /= l
# #####################################################
# MTL parser
# #####################################################
def parse_mtl(fname):
"""Parse MTL file.
"""
materials = {}
for line in fileinput.input(fname):
chunks = line.split()
if len(chunks) > 0:
# Material start
# newmtl identifier
if chunks[0] == "newmtl" and len(chunks) == 2:
identifier = chunks[1]
if not identifier in materials:
materials[identifier] = {}
# Diffuse color
# Kd 1.000 1.000 1.000
if chunks[0] == "Kd" and len(chunks) == 4:
materials[identifier]["col_diffuse"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
# Ambient color
# Ka 1.000 1.000 1.000
if chunks[0] == "Ka" and len(chunks) == 4:
materials[identifier]["col_ambient"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
# Specular color
# Ks 1.000 1.000 1.000
if chunks[0] == "Ks" and len(chunks) == 4:
materials[identifier]["col_specular"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
# Specular coefficient
# Ns 154.000
if chunks[0] == "Ns" and len(chunks) == 2:
materials[identifier]["specular_coef"] = float(chunks[1])
# Transparency
# Tr 0.9 or d 0.9
if (chunks[0] == "Tr" or chunks[0] == "d") and len(chunks) == 2:
materials[identifier]["transparency"] = float(chunks[1])
# Optical density
# Ni 1.0
if chunks[0] == "Ni" and len(chunks) == 2:
materials[identifier]["optical_density"] = float(chunks[1])
# Diffuse texture
# map_Kd texture_diffuse.jpg
if chunks[0] == "map_Kd" and len(chunks) == 2:
materials[identifier]["map_diffuse"] = chunks[1]
# Ambient texture
# map_Ka texture_ambient.jpg
if chunks[0] == "map_Ka" and len(chunks) == 2:
materials[identifier]["map_ambient"] = chunks[1]
# Specular texture
# map_Ks texture_specular.jpg
if chunks[0] == "map_Ks" and len(chunks) == 2:
materials[identifier]["map_specular"] = chunks[1]
# Alpha texture
# map_d texture_alpha.png
if chunks[0] == "map_d" and len(chunks) == 2:
materials[identifier]["map_alpha"] = chunks[1]
# Bump texture
# map_bump texture_bump.jpg or bump texture_bump.jpg
if (chunks[0] == "map_bump" or chunks[0] == "bump") and len(chunks) == 2:
materials[identifier]["map_bump"] = chunks[1]
# Illumination
# illum 2
#
# 0. Color on and Ambient off
# 1. Color on and Ambient on
# 2. Highlight on
# 3. Reflection on and Ray trace on
# 4. Transparency: Glass on, Reflection: Ray trace on
# 5. Reflection: Fresnel on and Ray trace on
# 6. Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
# 7. Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
# 8. Reflection on and Ray trace off
# 9. Transparency: Glass on, Reflection: Ray trace off
# 10. Casts shadows onto invisible surfaces
if chunks[0] == "illum" and len(chunks) == 2:
materials[identifier]["illumination"] = int(chunks[1])
return materials
# #####################################################
# OBJ parser
# #####################################################
def parse_vertex(text):
"""Parse text chunk specifying single vertex.
Possible formats:
vertex index
vertex index / texture index
vertex index / texture index / normal index
vertex index / / normal index
"""
v = 0
t = 0
n = 0
chunks = text.split("/")
v = int(chunks[0])
if len(chunks) > 1:
if chunks[1]:
t = int(chunks[1])
if len(chunks) > 2:
if chunks[2]:
n = int(chunks[2])
return { 'v':v, 't':t, 'n':n }
def parse_obj(fname):
"""Parse OBJ file.
"""
vertices = []
normals = []
uvs = []
faces = []
materials = {}
mcounter = 0
mcurrent = 0
mtllib = ""
# current face state
group = 0
object = 0
smooth = 0
for line in fileinput.input(fname):
chunks = line.split()
if len(chunks) > 0:
# Vertices as (x,y,z) coordinates
# v 0.123 0.234 0.345
if chunks[0] == "v" and len(chunks) == 4:
x = float(chunks[1])
y = float(chunks[2])
z = float(chunks[3])
vertices.append([x,y,z])
# Normals in (x,y,z) form; normals might not be unit
# vn 0.707 0.000 0.707
if chunks[0] == "vn" and len(chunks) == 4:
x = float(chunks[1])
y = float(chunks[2])
z = float(chunks[3])
normals.append([x,y,z])
# Texture coordinates in (u,v[,w]) coordinates, w is optional
# vt 0.500 -1.352 [0.234]
if chunks[0] == "vt" and len(chunks) >= 3:
u = float(chunks[1])
v = float(chunks[2])
w = 0
if len(chunks)>3:
w = float(chunks[3])
uvs.append([u,v,w])
# Face
if chunks[0] == "f" and len(chunks) >= 4:
vertex_index = []
uv_index = []
normal_index = []
for v in chunks[1:]:
vertex = parse_vertex(v)
if vertex['v']:
vertex_index.append(vertex['v'])
if vertex['t']:
uv_index.append(vertex['t'])
if vertex['n']:
normal_index.append(vertex['n'])
faces.append({
'vertex':vertex_index,
'uv':uv_index,
'normal':normal_index,
'material':mcurrent,
'group':group,
'object':object,
'smooth':smooth,
})
# Group
if chunks[0] == "g" and len(chunks) == 2:
group = chunks[1]
# Object
if chunks[0] == "o" and len(chunks) == 2:
object = chunks[1]
# Materials definition
if chunks[0] == "mtllib" and len(chunks) == 2:
mtllib = chunks[1]
# Material
if chunks[0] == "usemtl" and len(chunks) == 2:
material = chunks[1]
if not material in materials:
mcurrent = mcounter
materials[material] = mcounter
mcounter += 1
else:
mcurrent = materials[material]
# Smooth shading
if chunks[0] == "s" and len(chunks) == 2:
smooth = chunks[1]
return faces, vertices, uvs, normals, materials, mtllib
# #####################################################
# Generator
# #####################################################
def generate_vertex(v):
return TEMPLATE_VERTEX % (v[0], v[1], v[2])
def generate_uv(f, uvs):
ui = f['uv']
if len(ui) == 3:
return TEMPLATE_UV3 % (uvs[ui[0]-1][0], 1.0 - uvs[ui[0]-1][1],
uvs[ui[1]-1][0], 1.0 - uvs[ui[1]-1][1],
uvs[ui[2]-1][0], 1.0 - uvs[ui[2]-1][1])
elif len(ui) == 4:
return TEMPLATE_UV4 % (uvs[ui[0]-1][0], 1.0 - uvs[ui[0]-1][1],
uvs[ui[1]-1][0], 1.0 - uvs[ui[1]-1][1],
uvs[ui[2]-1][0], 1.0 - uvs[ui[2]-1][1],
uvs[ui[3]-1][0], 1.0 - uvs[ui[3]-1][1])
return ""
def generate_face(f):
vi = f['vertex']
if f["normal"] and SHADING == "smooth":
ni = f['normal']
if len(vi) == 3:
return TEMPLATE_FACE3N % (vi[0]-1, vi[1]-1, vi[2]-1, f['material'], ni[0]-1, ni[1]-1, ni[2]-1)
elif len(vi) == 4:
return TEMPLATE_FACE4N % (vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1, f['material'], ni[0]-1, ni[1]-1, ni[2]-1, ni[3]-1)
else:
if len(vi) == 3:
return TEMPLATE_FACE3 % (vi[0]-1, vi[1]-1, vi[2]-1, f['material'])
elif len(vi) == 4:
return TEMPLATE_FACE4 % (vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1, f['material'])
return ""
def generate_normal(n):
return TEMPLATE_N % (n[0], n[1], n[2])
def generate_color(i):
"""Generate hex color corresponding to integer.
Colors should have well defined ordering.
First N colors are hardcoded, then colors are random
(must seed random number generator with deterministic value
before getting colors).
"""
if i < len(COLORS):
return "0x%06x" % COLORS[i]
else:
return "0x%06x" % int(0xffffff * random.random())
def value2string(v):
if type(v)==str and v[0] != "0":
return '"%s"' % v
return str(v)
def generate_materials(mtl, materials):
"""Generate JS array of materials objects
JS material objects are basically prettified one-to-one
mappings of MTL properties in JSON format.
"""
mtl_array = []
for m in mtl:
index = materials[m]
# add debug information
# materials should be sorted according to how
# they appeared in OBJ file (for the first time)
# this index is identifier used in face definitions
mtl[m]['a_dbg_name'] = m
mtl[m]['a_dbg_index'] = index
mtl[m]['a_dbg_color'] = generate_color(index)
mtl_raw = ",\n".join(['\t"%s" : %s' % (n, value2string(v)) for n,v in sorted(mtl[m].items())])
mtl_string = "\t{\n%s\n\t}" % mtl_raw
mtl_array.append([index, mtl_string])
return ",\n\n".join([m for i,m in sorted(mtl_array)])
def generate_mtl(materials):
"""Generate dummy materials (if there is no MTL file).
"""
mtl = {}
for m in materials:
index = materials[m]
mtl[m] = {
'a_dbg_name': m,
'a_dbg_index': index,
'a_dbg_color': generate_color(index)
}
return mtl
# #####################################################
# API
# #####################################################
def convert(infile, outfile):
"""Convert infile.obj to outfile.js
Here is where everything happens. If you need to automate conversions,
just import this file as Python module and call this method.
"""
if not file_exists(infile):
print "Couldn't find [%s]" % infile
return
faces, vertices, uvs, normals, materials, mtllib = parse_obj(infile)
if ALIGN == "center":
center(vertices)
elif ALIGN == "bottom":
bottom(vertices)
elif ALIGN == "top":
top(vertices)
random.seed(42) # to get well defined color order for materials
uv_string = ""
if len(uvs)>0:
uv_string = "\n".join([generate_uv(f, uvs) for f in faces])
# default materials with debug colors for when
# there is no specified MTL / MTL loading failed,
# or if there were no materials / null materials
if not materials:
materials = { 'default':0 }
mtl = generate_mtl(materials)
if mtllib:
# create full pathname for MTL (included from OBJ)
path = os.path.dirname(infile)
fname = os.path.join(path, mtllib)
if file_exists(fname):
# override default materials with real ones from MTL
# (where they exist, otherwise keep defaults)
mtl.update(parse_mtl(fname))
else:
print "Couldn't find [%s]" % fname
normals_string = ""
if SHADING == "smooth":
normals_string = ",".join(generate_normal(n) for n in normals)
text = TEMPLATE_FILE % {
"name" : get_name(outfile),
"vertices" : "\n".join([generate_vertex(v) for v in vertices]),
"faces" : "\n".join([generate_face(f) for f in faces]),
"uvs" : uv_string,
"normals" : normals_string,
"materials" : generate_materials(mtl, materials),
"fname" : infile,
"nvertex" : len(vertices),
"nface" : len(faces),
"nmaterial" : len(materials)
}
out = open(outfile, "w")
out.write(text)
out.close()
print "%d vertices, %d faces, %d materials" % (len(vertices), len(faces), len(materials))
# #############################################################################
# Helpers
# #############################################################################
def usage():
print "Usage: %s -i filename.obj -o filename.js [-a center|top|bottom] [-s flat|smooth]" % os.path.basename(sys.argv[0])
# #####################################################
# Main
# #####################################################
if __name__ == "__main__":
# get parameters from the command line
try:
opts, args = getopt.getopt(sys.argv[1:], "hi:o:a:s:", ["help", "input=", "output=", "align=", "shading="])
except getopt.GetoptError:
usage()
sys.exit(2)
infile = outfile = ""
for o, a in opts:
if o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-i", "--input"):
infile = a
elif o in ("-o", "--output"):
outfile = a
elif o in ("-a", "--align"):
if a in ("top", "bottom", "center"):
ALIGN = a
elif o in ("-s", "--shading"):
if a in ("flat", "smooth"):
SHADING = a
if infile == "" or outfile == "":
usage()
sys.exit(2)
print "Converting [%s] into [%s] ..." % (infile, outfile)
convert(infile, outfile)