Unable to process animation with multiple morph targets with JSONLoader - three.js

I've made a simple scene in blender which contains a simple box and two shape deformation keyframes.
My exported .js file contains lots of morph targets (each one for each animation frame I suppose?), but still no animation shown in production, just a static box.
Here's the way I'm trying to get this working:
<script src="three.js" type="text/javascript"></script>
<script type="text/javascript">
var size_width = window.innerWidth;
var size_height = window.innerHeight;
var player;
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, size_width/size_height, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
var animation;
var animOffset = 1;
var duration = 1000;
var keyframes = 101;
var interpolation = duration / keyframes;
var lastKeyframe = 0;
var currentKeyframe = 0;
renderer.setSize(size_width, size_height);
document.body.appendChild(renderer.domElement);
camera.position.x = 10;
camera.position.y = -20;
camera.position.z = 10;
camera.rotation.x = 1.4;
var player_loader = new THREE.JSONLoader();
player_loader.load( "boxy.js", function(geo) {
player = new THREE.Mesh(geo);
scene.add(player);
});
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
if ( player ) {
var time = Date.now() % duration;
var keyframe = Math.floor( time / interpolation );
if ( keyframe != currentKeyframe ) {
player.morphTargetInfluences[ lastKeyframe ] = 0;
player.morphTargetInfluences[ currentKeyframe ] = 1;
player.morphTargetInfluences[ keyframe ] = 0;
lastKeyframe = currentKeyframe;
currentKeyframe = keyframe;
}
player.morphTargetInfluences[ keyframe ] = ( time % interpolation ) / interpolation;
player.morphTargetInfluences[ lastKeyframe ] = 1 - player.morphTargetInfluences[ keyframe ];
}
renderer.render(scene, camera);
}
animate();
</script>
here's my export:
http://touhou.ru/upload/7b7513a903963b0804b0be763b8cc67c.js
Also no errors were reported to the console.

You need to render your mesh with a material that expects morph targets. You can do this by instantiating a material with the morphTargets boolean set to true in the constructor options.
I'm not sure how familiar you are with three.js, but in most cases people create mesh objects with both a geometry object and a material object passed to the mesh constructor as arguments. You only gave the constructor a geometry object.
To get the animation running in your code change the line where you instantiate a new mesh in the loader callback:
player = new THREE.Mesh(geo);
to instantiate a mesh with a material with morph targets enable:
player = new THREE.Mesh( geo, new THREE.MeshLambertMaterial({ morphTargets: true }) );
When I ran your code with that change I saw one corner of a cube deforming outward and then back in.

Related

Three.js - Smooth shading results in weird edges

I’m trying to get .stl files to appear smooth, but the edges result in these weird dark areas.
With flatShading set to true
With flatShading set to false
Is there any way to make the edges perfectly smooth without these weird artifacts?
var renderer = new THREE.WebGLRenderer({ alpha: true });
var camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 1, 500);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
window.addEventListener('resize', function () {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
}, false);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.2;
var scene = new THREE.Scene();
// Hemisphere light
var hemiLight = new THREE.HemisphereLight(0xffffff, 0x444444);
hemiLight.position.set(0, 100, 0);
scene.add(hemiLight);
// Directional light
var dirLight = new THREE.DirectionalLight(0x323232);
dirLight.position.set(- 0, 40, 50);
dirLight.castShadow = true;
dirLight.shadow.camera.top = 50;
dirLight.shadow.camera.bottom = - 25;
dirLight.shadow.camera.left = - 25;
dirLight.shadow.camera.right = 25;
dirLight.shadow.camera.near = 0.1;
dirLight.shadow.camera.far = 200;
dirLight.shadow.mapSize.set(1024, 1024);
scene.add(dirLight);
var loader = new THREE.STLLoader();
loader.load( 'https://bymu.eu/test.stl', function ( geometry ) {
var material = new THREE.MeshPhongMaterial({ specular: 0x111111, shininess: 200, color: 0xff5533, flatShading: false });
var tempGeometry = new THREE.Geometry().fromBufferGeometry(geometry);
tempGeometry.mergeVertices();
tempGeometry.computeVertexNormals();
tempGeometry.computeFaceNormals();
geometry.fromGeometry(tempGeometry);
var mesh = new THREE.Mesh(tempGeometry, material);
scene.add(mesh);
// Compute the middle
var middle = new THREE.Vector3();
geometry.computeBoundingBox();
geometry.boundingBox.getCenter(middle);
// Center it
mesh.position.x = -1 * middle.x;
mesh.position.y = -1 * middle.y;
mesh.position.z = -1 * middle.z;
// Pull the camera away as needed
var largestDimension = Math.max(geometry.boundingBox.max.x,
geometry.boundingBox.max.y, geometry.boundingBox.max.z)
camera.position.z = largestDimension * 1.5;
render();
});
function render() {
renderer.render( scene, camera );
}
var animate = function () {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}; animate();
body {
background: #b2b2b2;
margin:0;
padding:0;
overflow: hidden;
}
<script src="https://raw.githack.com/mrdoob/three.js/dev/build/three.min.js"></script>
<script src="https://raw.githack.com/mrdoob/three.js/dev/examples/js/controls/OrbitControls.js"></script>
<script src="https://raw.githack.com/mrdoob/three.js/dev/examples/js/loaders/STLLoader.js"></script>
The problem isn't with Three.js, but with your geometry. Three.js uses "vertex normals" to know which direction the vertex is facing. This is used to smooth out faces. See the illustration below, your edge has a "smooth edge" (left diagram), where the direction of the faces is blended along that 90-degree angle. If you want a "sharp edge" (on the right), you'll have to tell your your geometry to create a second normal, each one pointing perpendicular to the face, so the angles don't blend.
.
Here's what your normals look like in Blender, in a before/after animation. Notice that a single normal down the middle gives the undesired smooth shading:
The way to achieve this varies from one editor to another, but I'm sure you can find the exact step-by-step instructions by looking up "mark sharp edge" for your editor of choice.
Solved it, found this great function https://codepen.io/Ni55aN/pen/zROmoe
THREE.Geometry.prototype.computeAngleVertexNormals = function(angle){
function weightedNormal( normals, vector ) {
var normal = new THREE.Vector3();
for ( var i = 0, l = normals.length; i < l; i ++ ) {
if ( normals[ i ].angleTo( vector ) < angle ) {
normal.add( normals[ i ] );
}
}
return normal.normalize();
}
this.computeFaceNormals();
var vertexNormals = [];
for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
vertexNormals[ i ] = [];
}
for ( var i = 0, fl = this.faces.length; i < fl; i ++ ) {
var face = this.faces[ i ];
vertexNormals[ face.a ].push( face.normal );
vertexNormals[ face.b ].push( face.normal );
vertexNormals[ face.c ].push( face.normal );
}
for ( var i = 0, fl = this.faces.length; i < fl; i ++ ) {
var face = this.faces[ i ];
face.vertexNormals[ 0 ] = weightedNormal( vertexNormals[ face.a ], face.normal );
face.vertexNormals[ 1 ] = weightedNormal( vertexNormals[ face.b ], face.normal );
face.vertexNormals[ 2 ] = weightedNormal( vertexNormals[ face.c ], face.normal );
}
if ( this.faces.length > 0 ) {
this.normalsNeedUpdate = true;
}
}
Results in exactly what I want after playing around with the angle, however increases loading time and has a bit of a performance penalty when a bunch of meshes are loaded, something I can live with as the meshes look amazing. I tried exporting the meshes so the browser wouldn’t have to recalculate every time, but some of them inflated 5-10 times due to this process. So it’s a sacrifice of loading time either way.

Three.js - Create new mesh from certain faces/vertices of another mesh

I´ve been several days struggling with a particular Three.js issue, and I cannot find any way to do it. This is my case:
1) I have a floating mesh, formed by several triangled faces. This mesh is created from the geometry returned by a loader, after obtaining its vertices and faces using getAttribute('position'): How to smooth mesh triangles in STL loaded BufferGeometry
2) What I want to do now is to "project" the bottom face agains the floor.
3) Later, with this new face added, create the resulting mesh of filling the space between the 3 vertices of both faces.
I already have troubles in step 2... To create a new face I´m supossed to have its 3 vertices already added to geometry.vertices. I did it, cloning the original face vertices. I use geometry.vertices.push() results to know their new indexes, and later I use that indexes (-1) to finally create the new face. But its shape is weird, also the positions and the size. I think I´m not getting the world/scene/vector position equivalence theory right :P
I tried applying this, with no luck:
How to get the absolute position of a vertex in three.js?
Converting World coordinates to Screen coordinates in Three.js using Projection
http://barkofthebyte.azurewebsites.net/post/2014/05/05/three-js-projecting-mouse-clicks-to-a-3d-scene-how-to-do-it-and-how-it-works
I discovered that if I directly clone the full original face and simply add it to the mesh, the face is added but in the same position, so I cannot then change its vertices to place it on the floor (or at least without modifying the original face vertices!). I mean, I can change their x, y, z properties, but they are in a very small measure that doesn´t match the original mesh dimensions.
Could someone help me get this concept right?
EDIT: source code
// Create geometry
var geo = new THREE.Geometry();
var geofaces = [];
var geovertices = [];
original_geometry.updateMatrixWorld();
for(var index in original_geometry.faces){
// Get original face vertexNormals to know its 3 vertices
var face = original_geometry[index];
var vertexNormals = face.vertexNormals;
// Create 3 new vertices, add it to the array and then create a new face using the vertices indexes
var vertexIndexes = [null, null, null];
for (var i = 0, l = vertexNormals.length; i < l; i++) {
var vectorClone = vertexNormals[i].clone();
vectorClone.applyMatrix4( original_geometry.matrixWorld );
//vectorClone.unproject(camera); // JUST TESTING
//vectorClone.normalize(); // JUST TESTING
var vector = new THREE.Vector3(vectorClone.x, vectorClone.z, vectorClone.y)
//vector.normalize(); // JUST TESTING
//vector.project(camera); // JUST TESTING
//vector.unproject(camera); // JUST TESTING
vertexIndexes[i] = geovertices.push( vector ) - 1;
}
var newFace = new THREE.Face3( vertexIndexes[0], vertexIndexes[1], vertexIndexes[2] );
geofaces.push(newFace);
}
// Assign filled arrays to the geometry
geo.faces = geofaces;
geo.vertices = geovertices;
geo.mergeVertices();
geo.computeVertexNormals();
geo.computeFaceNormals();
// Create a new mesh with resulting geometry and add it to scene (in this case, to the original mesh to keep the positions)
new_mesh = new THREE.Mesh( geo, new THREE.MeshFaceMaterial(material) ); // material is defined elsewhere
new_mesh.position.set(0, -100, 0);
original_mesh.add( new_mesh );
I created a fully operational JSFiddle with the case to try things and see the problem more clear. With this STL (smaller than my local example) I cannot even see the badly cloned faces added to the scene.. Maybe they are too small or out of focus.
Take a look to the calculateProjectedMesh() function, here is where I tried to clone and place the bottom faces (already detected because they have a different materialIndex):
JSFiddle: https://jsfiddle.net/tc39sgo1/
var container;
var stlPath = 'https://dl.dropboxusercontent.com/s/p1xp4lhy4wxmf19/Handle_Tab_floating.STL';
var camera, controls, scene, renderer, model;
var mouseX = 0,
mouseY = 0;
var test = true;
var meshPlane = null, meshStl = null, meshCube = null, meshHang = null;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
/*THREE.FrontSide = 0;
THREE.BackSide = 1;
THREE.DoubleSide = 2;*/
var materials = [];
materials.push( new THREE.MeshPhongMaterial({color : 0x00FF00, side:0, shading: THREE.FlatShading, transparent: true, opacity: 0.9, overdraw : true, wireframe: false}) );
materials.push( new THREE.MeshPhongMaterial({color : 0xFF0000, transparent: true, opacity: 0.8, side:0, shading: THREE.FlatShading, overdraw : true, metal: false, wireframe: false}) );
materials.push( new THREE.MeshPhongMaterial({color : 0x0000FF, side:2, shading: THREE.FlatShading, overdraw : true, metal: false, wireframe: false}) );
var lineMaterial = new THREE.LineBasicMaterial({ color: 0x0000ff, transparent: true, opacity: 0.05 });
init();
animate();
function webglAvailable() {
try {
var canvas = document.createElement('canvas');
return !!(window.WebGLRenderingContext && (
canvas.getContext('webgl') || canvas.getContext('experimental-webgl')));
} catch (e) {
return false;
}
}
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(25, window.innerWidth / window.innerHeight, 0.1, 100000000);
camera.position.x = 1500;
camera.position.z = -2000;
camera.position.y = 1000;
controls = new THREE.OrbitControls(camera);
// scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight(0x101030); //0x101030
scene.add(ambient);
var directionalLight = new THREE.DirectionalLight(0xffffff, 2);
directionalLight.position.set(0, 3, 0).normalize();
scene.add(directionalLight);
var directionalLight = new THREE.DirectionalLight(0xffffff, 2);
directionalLight.position.set(0, 1, -2).normalize();
scene.add(directionalLight);
if (webglAvailable()) {
renderer = new THREE.WebGLRenderer();
} else {
renderer = new THREE.CanvasRenderer();
}
renderer.setClearColor( 0xCDCDCD, 1 );
// renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener('mousemove', onDocumentMouseMove, false);
window.addEventListener('resize', onWindowResize, false);
createPlane(500, 500);
createCube(500);
loadStl();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX) / 2;
mouseY = (event.clientY - windowHalfY) / 2;
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}
function createPlane(width, height) {
var planegeometry = new THREE.PlaneBufferGeometry(width, height, 0, 0);
var material = new THREE.MeshLambertMaterial({
color: 0xFFFFFF,
side: THREE.DoubleSide
});
planegeometry.computeBoundingBox();
planegeometry.center();
meshPlane = new THREE.Mesh(planegeometry, material);
meshPlane.rotation.x = 90 * (Math.PI/180);
//meshPlane.position.y = -height/2;
scene.add(meshPlane);
}
function createCube(size) {
var geometry = new THREE.BoxGeometry( size, size, size );
geometry.computeFaceNormals();
geometry.mergeVertices();
geometry.computeVertexNormals();
geometry.center();
var material = new THREE.MeshPhongMaterial({
color: 0xFF0000,
opacity: 0.04,
transparent: true,
wireframe: true,
side: THREE.DoubleSide
});
meshCube = new THREE.Mesh(geometry, material);
meshCube.position.y = size/2;
scene.add(meshCube);
}
function loadStl() {
var loader = new THREE.STLLoader();
loader.load( stlPath, function ( geometry ) {
// Convert BufferGeometry to Geometry
var geometry = new THREE.Geometry().fromBufferGeometry( geometry );
geometry.computeBoundingBox();
geometry.computeVertexNormals();
geometry.center();
var faces = geometry.faces;
for(var index in faces){
var face = faces[index];
var faceNormal = face.normal;
var axis = new THREE.Vector3(0,-1,0);
var angle = Math.acos(axis.dot(faceNormal));
var angleReal = (angle / (Math.PI/180));
if(angleReal <= 70){
face.materialIndex = 1;
}
else{
face.materialIndex = 0;
}
}
geometry.computeFaceNormals();
geometry.computeVertexNormals();
meshStl = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
meshStl.position.x = 0;
meshStl.position.y = 400;
scene.add( meshStl );
// Once loaded, calculate projections mesh
calculateProjectedMesh();
});
}
function calculateProjectedMesh(){
var geometry = meshStl.geometry;
var faces = geometry.faces;
var vertices = geometry.vertices;
var geometry_projected = new THREE.Geometry();
var faces_projected = [];
var vertices_projected = [];
meshStl.updateMatrixWorld();
for(var index in faces){
var face = faces[index];
// This are the faces
if(face.materialIndex == 1){
var vertexIndexes = [face.a, face.b, face.c];
for (var i = 0, l = vertexIndexes.length; i < l; i++) {
var relatedVertice = vertices[ vertexIndexes[i] ];
var vectorClone = relatedVertice.clone();
console.warn(vectorClone);
vectorClone.applyMatrix4( meshStl.matrixWorld );
////////////////////////////////////////////////////////////////
// TEST: draw line
var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(vectorClone.x, vectorClone.y, vectorClone.z));
//geometry.vertices.push(new THREE.Vector3(vectorClone.x, vectorClone.y, vectorClone.z));
geometry.vertices.push(new THREE.Vector3(vectorClone.x, meshPlane.position.y, vectorClone.z));
var line = new THREE.Line(geometry, lineMaterial);
scene.add(line);
console.log("line added");
////////////////////////////////////////////////////////////////
vectorClone.y = 0;
var vector = new THREE.Vector3(vectorClone.x, vectorClone.y, vectorClone.z);
vertexIndexes[i] = vertices_projected.push( vector ) - 1;
}
var newFace = new THREE.Face3( vertexIndexes[0], vertexIndexes[1], vertexIndexes[2] );
newFace.materialIndex = 2;
faces_projected.push(newFace);
}
}
geometry_projected.faces = faces_projected;
geometry_projected.vertices = vertices_projected;
geometry_projected.mergeVertices();
console.info(geometry_projected);
meshHang = new THREE.Mesh(geometry_projected, new THREE.MeshFaceMaterial(materials));
var newY = -(2 * meshStl.position.y) + 0;
var newY = -meshStl.position.y;
meshHang.position.set(0, newY, 0);
meshStl.add( meshHang );
}
EDIT: Finally!! I got it! To clone the original faces I must access their 3 original vertices using "a", "b" and "c" properties, which are indexes referencing Vector3 instances in the "vertices" array of the original geometry.
I cloned the 3 vertices flatting the Z position to zero, use their new indexes to create the new face and add it to the projection mesh (in blue).
I´m also adding lines as a visual union between both faces. Now I´m ready for step 3, but I think this is complex enough to close this question.
Thanks for the updateMatrixWorld clue! It was vital to achieve my goal ;)
try this
original_geometry.updateMatrixWorld();
var vertexIndexes = [null, null, null];
for (var i = 0, l = vertexNormals.length; i < l; i++) {
var position = original_geometry.geometry.vertices[i].clone();
position.applyMatrix4( original_geometry.matrixWorld );
var vector = new THREE.Vector3(position.x, position.y, position.z)
vertexIndexes[i] = geovertices.push( vector ) - 1;
}

Three.js FirstPersonControl does nothing

I implemented the following short script:
var screenWidth = window.innerWidth;
var screenHeight = window.innerHeight;
var camera;
var controls;
var scene;
var renderer;
var container;
var controls;
var keyboard = new THREEx.KeyboardState();
var clock = new THREE.Clock();
var light;
var floor;
var movingGeometry;
function setup()
{
var viewAngle = 45;
var aspect = screenWidth / screenHeight;
var near = 0.1;
var far = 20000;
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(viewAngle, aspect, near, far);
camera.position.set(0,150,400);
camera.lookAt(scene.position);
scene.add(camera);
controls = new THREE.FirstPersonControls(camera);
controls.movementSpeed = 70;
controls.lookSpeed = 0.05;
controls.noFly = true;
controls.lookVertical = false;
renderer = new THREE.WebGLRenderer();
renderer.setSize(screenWidth, screenHeight);
container = document.getElementById('canvas');
container.appendChild( renderer.domElement );
createLight();
createFloor();
createSkyBox();
createGeometry();
animate();
}
function createLight()
{
light = new THREE.PointLight(0xffffff);
light.position.set(0,250,0);
scene.add(light);
}
function createFloor()
{
var floorMaterial = new THREE.MeshLambertMaterial({color: 0x00FF00});
floor = new THREE.Mesh(new THREE.BoxGeometry(1000, 1000, 3, 1, 1, 1), floorMaterial);
floor.position.y = -0.5;
floor.rotation.x = Math.PI / 2;
scene.add(floor);
}
function createSkyBox()
{
var skyBoxGeometry = new THREE.BoxGeometry(10000, 10000, 10000);
var skyBoxMaterial = new THREE.MeshBasicMaterial({color: 0x0000FF, side: THREE.BackSide});
var skyBox = new THREE.Mesh(skyBoxGeometry, skyBoxMaterial);
scene.add(skyBox);
}
function createGeometry()
{
var material = new THREE.MeshNormalMaterial();
var geometry = new THREE.BoxGeometry(50, 50, 50);
movingGeometry = new THREE.Mesh(geometry, material);
movingGeometry.position.set(0, 28, 0);
scene.add(movingGeometry);
}
function animate()
{
requestAnimationFrame(animate);
render();
update();
}
function render()
{
renderer.render(scene, camera);
controls.update();
}
function update()
{
var delta = clock.getDelta(); // seconds.
var moveDistance = 200 * delta; // 200 pixels per second
var rotateAngle = Math.PI / 2 * delta; // pi/2 radians (90 degrees) per second
if (keyboard.pressed("W"))
{
movingGeometry.translateZ(-moveDistance);
}
if (keyboard.pressed("S"))
{
movingGeometry.translateZ(moveDistance);
}
if (keyboard.pressed("A"))
{
movingGeometry.rotateOnAxis(new THREE.Vector3(0,1,0), rotateAngle);
}
if (keyboard.pressed("D"))
{
movingGeometry.rotateOnAxis(new THREE.Vector3(0,1,0), -rotateAngle);
}
var relativeCameraOffset = new THREE.Vector3(0,50,200);
var cameraOffset = relativeCameraOffset.applyMatrix4(movingGeometry.matrixWorld);
camera.position.x = cameraOffset.x;
camera.position.y = cameraOffset.y;
camera.position.z = cameraOffset.z;
camera.lookAt(movingGeometry.position);
}
I wanted to implement a camera which is sticking to an object. If i use 'w', 'a', 's', 'd' i can move the object and the camera follows. But i also want to be able to rotate the camera (at its position) by leftclick + dragging and i also want to rotate the object by rightclick + dragging (the typical first person behaviour).
So i added the FirstPersonControls from Three.js to the camera. The result: nothing happens when i use the mouse or click or anything and i also have no idea what i need to do to rotate the object by rightclicking and dragging.
Can someone help?
At first sight it seems like you have a problem with overwriting the cameras lookAt
Since in update() you do :
camera.lookAt(movingGeometry.position);
List item
Your order of execution order is:
animate
(your) render
(threejs) render
(threejs) controls update
(your) update
and in your update you overwrite the cameras lookat from the first person controls.

Three.js scene background doesn't appear

I'm trying to add a background to a webgl scene(Three.js). The scene contains two animated spritesheets that I created using DAZ3D and Photoshop. I've tried just about everything but to no avail, the background is either white or black. I've tried many examples on the web then either my spritesheet animator won't work or the background won't appear. I read that I need to make two scenes with two camera's, but that doesn't seem to work as well.
I really don't understand why I would need to have two scenes anyway.
<script>
// standard global variables
var container,scene,camera,renderer,controls,stats;
var keyboard = new THREEx.KeyboardState();
var clock = new THREE.Clock();
// custom global variables
var attack,defense;
init();
animate();
// FUNCTIONS
function init(){
// SCENE
scene = new THREE.Scene();
// CAMERA
var SCREEN_WIDTH = window.innerWidth,SCREEN_HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45,ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT,NEAR = 0.1,FAR = 1000;
var light = new THREE.PointLight(0xEEEEEE);
var lightAmb = new THREE.AmbientLight(0x777777);
camera = new THREE.PerspectiveCamera(VIEW_ANGLE,ASPECT,NEAR,FAR);
scene.add(camera);
camera.position.set(-10,30,400);
camera.lookAt(scene.position);
// RENDERER
if (Detector.webgl)
renderer = new THREE.WebGLRenderer({antialias:true});
else
renderer = new THREE.CanvasRenderer();
renderer.setSize(SCREEN_WIDTH,SCREEN_HEIGHT);
container = document.getElementById('ThreeJS');
container.appendChild(renderer.domElement);
// EVENTS
THREEx.WindowResize(renderer,camera);
THREEx.FullScreen.bindKey({charCode :'m'.charCodeAt(0)});
// LIGHTS
light.position.set(20,0,20);
scene.add(light);
scene.add(lightAmb);
// BACKGROUND
var texture = THREE.ImageUtils.loadTexture('images/sky.jpg');
var backgroundMesh = new THREE.Mesh(new THREE.PlaneGeometry(2,2,0),new THREE.MeshBasicMaterial({map:texture}));
backgroundMesh.material.depthTest = false;
backgroundMesh.material.depthWrite = false;
var backgroundScene = new THREE.Scene();
var backgroundCamera = new THREE.Camera();
backgroundScene.add(backgroundCamera);
backgroundScene.add(backgroundMesh);
// FLOOR
var floorTexture = new THREE.ImageUtils.loadTexture('images/checkerboard.jpg');
floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.repeat.set(10,10);
var floorMaterial = new THREE.MeshBasicMaterial({map:floorTexture,side:THREE.DoubleSide,shininess:30});
var floorGeometry = new THREE.PlaneGeometry(1000,1000);
var floor = new THREE.Mesh(floorGeometry,floorMaterial);
floor.position.y = -0.5;
floor.rotation.x = Math.PI / 2;
scene.add(floor);
// MESHES WITH ANIMATED TEXTURES!
var attackerTexture = new THREE.ImageUtils.loadTexture('images/kitinalevel2.png');
attack = new TextureAnimator(attackerTexture,2,13,26,25); // texture,#horiz,#vert,#total,duration.
var attackerMaterial = new THREE.MeshBasicMaterial({map:attackerTexture,side:THREE.DoubleSide,transparent:true});
var attackerGeometry = new THREE.PlaneGeometry(50,50,1,1);
var attacker = new THREE.Mesh(attackerGeometry,attackerMaterial);
attacker.position.set(-5,20,350);
scene.add(attacker);
var defenderTexture = new THREE.ImageUtils.loadTexture('images/kitinalevel1.png');
defense = new TextureAnimator(defenderTexture,2,13,26,25); // texture,#horiz,#vert,#total,duration.
var defenderMaterial = new THREE.MeshBasicMaterial({map:defenderTexture,side:THREE.DoubleSide,transparent:true});
var defenderGeometry = new THREE.PlaneGeometry(50,50,1,1);
var defenderx = new THREE.Mesh(defenderGeometry,defenderMaterial);
defenderx.position.set(25,20,350);
scene.add(defenderx);
}
function animate(){
requestAnimationFrame(animate);
render();
update();
}
function update(){
var delta = clock.getDelta();
attack.update(1000 * delta);
defense.update(1000 * delta);
//controls.update();
//stats.update();
}
function render(){
renderer.autoClear = false;
renderer.clear();
renderer.render(scene,camera);
renderer.render(backgroundScene,backgroundCamera);
}
function TextureAnimator(texture,tilesHoriz,tilesVert,numTiles,tileDispDuration){
// note:texture passed by reference,will be updated by the update function.
this.tilesHorizontal = tilesHoriz;
this.tilesVertical = tilesVert;
// how many images does this spritesheet contain?
// usually equals tilesHoriz * tilesVert,but not necessarily,
// if there at blank tiles at the bottom of the spritesheet.
this.numberOfTiles = numTiles;
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(1 / this.tilesHorizontal,1 / this.tilesVertical);
// how long should each image be displayed?
this.tileDisplayDuration = tileDispDuration;
// how long has the current image been displayed?
this.currentDisplayTime = 0;
// which image is currently being displayed?
this.currentTile = 0;
this.update = function(milliSec){
this.currentDisplayTime += milliSec;
while(this.currentDisplayTime>this.tileDisplayDuration){
this.currentDisplayTime-=this.tileDisplayDuration;
this.currentTile++;
if (this.currentTile == this.numberOfTiles)
this.currentTile = 0;
var currentColumn = this.currentTile%this.tilesHorizontal;
texture.offset.x = currentColumn/this.tilesHorizontal;
var currentRow = Math.floor(this.currentTile/this.tilesHorizontal);
texture.offset.y = currentRow/this.tilesVertical;
}
};
}
</script>
What am I doing wrong?
Thanks in advance.
Found a solution:
renderer = new THREE.WebGLRenderer({antialias:true,alpha: true });
This will keep the background transparant, then with a little css I made the background appear.

How do I make a material show up on a sphere

// set the scene size
var WIDTH = 1650,
HEIGHT = 700;
// set some camera attributes
var VIEW_ANGLE = 100,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
// get the DOM element to attach to
// - assume we've got jQuery to hand
var $container = $('#container');
// create a WebGL renderer, camera
// and a scene
var renderer = new THREE.WebGLRenderer();
var camera = new THREE.PerspectiveCamera( VIEW_ANGLE,
ASPECT,
NEAR,
FAR );
//camera.lookAt(new THREE.Vector3( 0, 0, 0 ));
var scene = new THREE.Scene();
// the camera starts at 0,0,0 so pull it back
camera.position.x = 200;
camera.position.y = 200;
camera.position.z = 300;
// start the renderer
renderer.setSize(WIDTH, HEIGHT);
// attach the render-supplied DOM element
$container.append(renderer.domElement);
// create the sphere's material
var sphereMaterial = new THREE.MeshLambertMaterial(
{
color: 0xCC0000
});
// set up the sphere vars
var radius = 60, segments = 20, rings = 20;
// create a new mesh with sphere geometry -
// we will cover the sphereMaterial next!
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(radius, segments, rings),
img);
// add the sphere to the scene
scene.add(sphere);
// and the camera
scene.add(camera);
// create a point light
var pointLight = new THREE.PointLight( 0xFFFFFF );
// set its position
pointLight.position.x = 50;
pointLight.position.y = 100;
pointLight.position.z = 180;
// add to the scene
scene.add(pointLight);
// add a base plane
var planeGeo = new THREE.PlaneGeometry(500, 500,8, 8);
var planeMat = new THREE.MeshLambertMaterial({color: 0x666699});
var plane = new THREE.Mesh(planeGeo, planeMat);
plane.position.x = 160;
plane.position.y = 0;
plane.position.z = 20;
//rotate it to correct position
plane.rotation.x = -Math.PI/2;
scene.add(plane);
// add 3D img
var img = new THREE.MeshBasicMaterial({
map:THREE.ImageUtils.loadTexture('cube.png')
});
img.map.needsUpdate = true;
// draw!
renderer.render(scene, camera);
I've put the var img as a material to the sphere but everytime I render it aoutomaticly changes color...
How do I do so it just will have the image as I want... not all the colors?
I whould possibly put the img on a plane.
You need to use the callback of the loadTexture function. If you refer to the source of THREE.ImageUtils you will see that the loadTexture function is defined as
loadTexture: function ( url, mapping, onLoad, onError ) {
var image = new Image();
var texture = new THREE.Texture( image, mapping );
var loader = new THREE.ImageLoader();
loader.addEventListener( 'load', function ( event ) {
texture.image = event.content;
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
} );
loader.addEventListener( 'error', function ( event ) {
if ( onError ) onError( event.message );
} );
loader.crossOrigin = this.crossOrigin;
loader.load( url, image );
return texture;
},
Here, only the url parameter is required. The texture mapping can be passed in as null. The last two parameters are the callbacks. You can pass in a function for each one which will be called at the respective load and error events. The problem you are experiencing is most likely caused by the fact that three.js is attempting to apply your material before your texture is properly loaded. In order to remedy this, you should only do this inside a function passed as the onLoad callback (which will only be called after the image has been loaded up). Also, you should always create your material before you apply it to an object.
So you should change your code from:
// set up the sphere vars
var radius = 60, segments = 20, rings = 20;
// create a new mesh with sphere geometry -
// we will cover the sphereMaterial next!
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(radius, segments, rings),
img);
// add the sphere to the scene
scene.add(sphere);
to something like:
var sphereGeo, sphereTex, sphereMat, sphereMesh;
var radius = 60, segments = 20, rings = 20;
sphereGeo = new THREE.SphereGeometry(radius, segments, rings);
sphereTex = THREE.ImageUtils.loadTexture('cube.png', null, function () {
sphereMat = new THREE.MeshBasicMaterial({map: sphereTex});
sphereMesh = new THREE.Mesh(sphereGeo, sphereMat);
scene.add(sphereMesh);
});

Resources