ThreeJS load time and texture rendering problems - html

I have a 3D object of a chair made in Blender and exported as a .obj and .mtl. First of all, the load time is a horrendous 40+ seconds; I have no idea why (Visual Studio possibly?) Second, the images textures are not loading properly. With no ambient or directional lighting I get a silhouette. With the lighting I get a slight hint of gray to give a little depth but nothing close to the many colors in the original object. I have only been working with ThreeJS for a few days now so I'm quite new to it. Hence, I am at a loss. I have read several artciles related to my issue but none seem to solve the problem. I even went so far as to add an addon to Blender to export to .js. I could not get it to even load properly (I assume it had to do with the fact I kept the same loader info from the .OBJMTLLoader and the .JSONLoader doesn't support or needs more than what I gave; I just am not familiar enough with it know). Any ideas/suggestions? Here is my script:
`
<script src="js/three.min.js"></script>
<script src="js/controls/TrackballControls.js"></script>
<script src="js/loaders/MTLLoader.js"></script>
<script src="js/loaders/OBJMTLLoader.js"></script>
<script src="js/Detector.js"></script>
<script>
if (!Detector.webgl) Detector.addGetWebGLMessage();
var container;
var camera, controls, scene, renderer;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 0.01, 1e10);
camera.position.z = 2;
//controls
controls = new THREE.TrackballControls(camera);
controls.rotateSpeed = 5.0;
controls.zoomSpeed = 5;
controls.panSpeed = 2;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
scene = new THREE.Scene();
scene.add(camera);
//lights
var ambient = new THREE.AmbientLight(0xCCCCCC);
scene.add(ambient);
var directionalLight = new THREE.DirectionalLight(0xCCCCCC);
directionalLight.position.set(0, 0, 2).normalize();
scene.add(directionalLight);
//main img
var material = new THREE.MeshBasicMaterial({ color: '0xCCCCCC' });
var loader = new THREE.OBJMTLLoader();
loader.addEventListener('load', function (event) {
var geometry = event.content;
//var mesh = new THREE.Mesh(geometry);
scene.add(geometry, material);
});
loader.load('chair.obj', 'chair.mtl');
// renderer
renderer = new THREE.WebGLRenderer({ antialias: false });
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
//
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
controls.handleResize();
}
function animate() {
requestAnimationFrame(animate);
render();
controls.update();
}
function render() {
var timer = Date.now() * 0.0005;
renderer.render(scene, camera);
}
</script>
`

Well, you are defining a gray MeshBasicMaterial to use with your obj instead of using the material(s) that the loader will create for you, i guess.
Just use this. The "object" should have the material defined in your mtl-file.
loader.addEventListener( 'load', function ( event ) {
var object = event.content;
scene.add( object );
});
loader.load( 'chair.obj', 'chair.mtl' );
Concerning your load time: Could be your local server. Also, be aware that the obj file format ist quite big in raw ascii format. Also, if the mtl-file defines textures, they are maybe quite big in file size, too.

#GuyGood was correct in my case for the long load time. I was using the python simplehttpserver and switch to a node server and no more slow texture loading problems. Check out the threejs wiki for other local server options.

Related

THEE.JSONLoader Object as public variable

I was wondering if its possible to add an object that is loaded via THREE.JSONLoader as public variable? Ideally, I'd like all my loaded textures, material creation, and geometry to be public variables at the top of my script for easy manipulation (I have strong 3D background but new to js and webGL). I'm finding that my public vars that are declared something - are no longer public once they're added as a parameter to a function - in this case the JSONLoader. However, just naming a var, without declaring its value "runs" but I get weird THREE.min.js error I can't comprehend. I've included my code below - know it has other issues - please feel free to let me know how bad it is - it helps me learn :)
//webGL
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.set(0, 16, 25);
camera.rotation.x += -0.32;
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
cubeCamera = new THREE.CubeCamera(1, 1000, 256); // parameters: near, far, resolution
cubeCamera.renderTarget.texture.minFilter = THREE.LinearMipMapLinearFilter; // mipmap filter
scene.add(cubeCamera);
///LOADERS
var loadTexture = new THREE.TextureLoader();
var loaderJs = new THREE.JSONLoader();
///TEXTURES
var skyTexture = loadTexture.load("textures/background.jpg");
var seatTexture = loadTexture.load("textures/abc_Diffuse.jpg");
///MATERIALS
var skyMaterial = new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
map: skyTexture
});
var frameMaterial = new THREE.MeshLambertMaterial({
//envMap: cubeCamera.renderTarget,
color: 0xffffff
});
var seatMaterial = new THREE.MeshLambertMaterial({
map: seatTexture
});
///GEOMETRY and MESHES
var frameGeo;
var skyGeo = new THREE.SphereGeometry(30, 30, 30);
var skySphere = new THREE.Mesh(skyGeo, skyMaterial);
scene.add(skySphere);
loaderJs.load("models/stoolFrame.js", function (){
frameGeo = new THREE.Mesh(frameGeo, frameMaterial);
frameGeo.scale.set(.5, .5, .5);
barStool.add(frameGeo);
});
loaderJs.load("models/stoolSeat.js", function (seatGeo){
seatGeo = new THREE.Mesh(seatGeo, seatMaterial);
seatGeo.scale.set(.5, .5, .5);
barStool.add(seatGeo);
});
var barStool = new THREE.Object3D();
scene.add(barStool);
var render = function () {
requestAnimationFrame(render);
barStool.rotation.y += 0.01;
frameGeo.visible = false;
cubeCamera.position.copy(frameGeo.position);
cubeCamera.updateCubeMap(renderer, scene);
frameGeo.visible = true;
renderer.render(scene, camera);
};
render();
When loading your stoolFrame, you forgot to add the parameters for the callback function, check the documentation example. The callback function takes a geometry and a material. When loading the stoolSeat you forgot the material aswell (provided you have a material for the stool)
var frameGeometry;
var frameMaterial;
var frameMesh;
loaderJs.load("models/stoolFrame.js", function (geometry, material){
frameGeometry = geometry;
frameMaterial = material
frameMesh = new THREE.Mesh(frameGeometry, frameMaterial);
frameMesh.scale.set(.5, .5, .5);
barStool.add(frameMesh);
});
Above is an example on how to make the geometry, material and mesh into global variables. However you probably dont need to save the geometry and material as global vars (you can access them from the mesh anyway: frameMesh.material; frameMesh.geometry).
If the parameter names are the same as a global variable name, javascript will use the parameter variable instead of the global one when trying to access it.

Three.js JSONLoader blender model error: property 'length' undefined

I have been trying out Three.js lately and i used the exporter addon for Blender to test out making models in blender and exporting so i can use them in a three.js program.
I included the add-on to blender, and using just the basic cube model of blender, exported it to .json as the exporter says. Then i imported the model into my three.js using this as a guide
but that gave me an error:
Uncaught TypeError: Cannot read property 'length' of undefined.
Ive already searched online and tried a few different approaches(like including a materials in the function call of the loader) but nothing seems to work.
I also checked stackoverflow for answers but so far nothing seems solved. If anyone would clarify what im doing wrong I would be very grateful.
The code for my three.js program:
var WIDTH = 1000,
HEIGHT = 1000;
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
var radius = 50,
segments = 16,
rings = 16;
var sphereMaterial =
new THREE.MeshLambertMaterial(
{
color: 0xCCCCCC
});
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(
radius,
segments,
rings),
sphereMaterial);
var pointLight =
new THREE.PointLight(0x660000);
var $container = $('#container');
var renderer = new THREE.WebGLRenderer();
var camera =
new THREE.PerspectiveCamera(
VIEW_ANGLE,
ASPECT,
NEAR,
FAR);
var scene = new THREE.Scene();
var loader = new THREE.JSONLoader(); // init the loader util
scene.add(camera);
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
scene.add(pointLight);
camera.position.z = 300;
renderer.setSize(WIDTH, HEIGHT);
$container.append(renderer.domElement);
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
loader.load('test.json', function (geometry, materials) {
var material = new THREE.MeshFaceMaterial(materials);
var object = new THREE.Mesh(geometry, material);
scene.add(object);
});
(function animloop() {
requestAnimFrame(animloop);
renderer.render(scene, camera);
})();
When you export, change the Type from buffergeometry to Geometry (Blender 2.76)
In my experience so far with the exporter, you have to be very careful which boxes you tick!
This length error is usually because you are either not exporting the vertexes, or exporting the scene rather the object.
I have the same issue with the new exporter.
If select SCENE then I usually get "Cannot read property 'length' of undefined"
If I select only the object and the materials and vertices. It usually just seems to get stuck forever.
UPDATE
Check this response to this issue!
Threejs blender exporter exports in wrong format
As roadkill stated earlier, exporting as Geometry instead of BufferedGeometry works.
Also note that loading JSON model loading is handled asyncronously (the callback is only called only when the operation is completed, the rest of your code keeps running). The model won't exist for the first frame or two, so check that your model exists before doing any operations with it inside the animation loop.

Three.js JSON loader on apache

I have created a 3D model website for showing JSON files with three.js.
This is working if I open the html file locally stored on my computer.
But if I upload all files to my webserver (apache2) nothing is displayed.
I have tried to run a simple Three.js example without JSON loader and this is working on my webserver.
I also checked the paths to the JSON files and they are all relative paths I can open each file in the browser if I type the name or if I use firebug I can browse all files.
I checked the apache error log but no error message appears.
What can be the problem or how can I find out what the problem is?
This is my Script part.
var scene;
var camera;
var controls;
var geometryArray;
initializeScene();
animateScene();
function initializeScene(){
if(!Detector.webgl){
Detector.addGetWebGLMessage();
return;
}
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setClearColor(0x000000, 1);
canvasWidth = window.innerWidth;
canvasHeight = window.innerHeight;
renderer.setSize(canvasWidth, canvasHeight);
document.getElementById("WebGLCanvas").appendChild(renderer.domElement);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(45, canvasWidth / canvasHeight, 1, 100);
camera.position.set(0, 0, 6);
camera.lookAt(scene.position);
scene.add(camera);
controls = new THREE.TrackballControls(camera, renderer.domElement);
axisSystem = new AxisSystem(camera, controls);
geometryArray = new Object();
var loader = new THREE.JSONLoader();
for(var i = 0; i < jsonFileNames.length; i++){
var layerName = jsonFileNames[i].split("/")[2].split(".")[0];
loader.load(layerName, jsonFileNames[i], function(geometry, materials, layerName){
mesh = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({vertexColors: THREE.FaceColors, side:THREE.DoubleSide}));
mesh.scale.set(0.013, 0.013, 0.013);
scene.add(mesh);
geometryArray[layerName] = mesh;
}, layerName);
}
var directionalLight = new THREE.DirectionalLight(0xffffff, 1.0);
directionalLight.position = camera.position;
scene.add(directionalLight);
}
function animateScene(){
controls.update();
axisSystem.animate();
requestAnimationFrame(animateScene);
renderScene();
}
function renderScene(){
renderer.render(scene, camera);
axisSystem.render();
}
My guess is that your files are not being loaded because of the for loop you are using. Load is asynchronous, so each time you call loader.load, you corrupt object state from previous call. Try creating new loader in every step or come up with different way of loading multiple files.

Three.js: tiling textures, buffering and browser compatibility

I am working on a project in html 5 canvas. For this I use the three.js library to draw some simple cubes in the shape of a simple cupboard. I have already added ambient lighting, anti-aliasing and textures. If all goes well it renders the cupboard and you can use your mouse to move it around.
Current issues:
var textureMap = map: THREE.ImageUtils.loadTexture("wood1.jpg")
textureMap.wrapS = THREE.RepeatWrapping;
textureMap.wrapT = THREE.RepeatWrapping;
textureMap.repeat.x = 100;
textureMap.repeat.y = 100;
material = new THREE.MeshLambertMaterial(textureMap);
The texture is currently stretched over each surface. I prefer tiling but can't seem to get it working. The code above was the best guess I came up with based on what I found on a site (sorry, can't share more links with my current reputation). It is commented out because it stops the script from running at all.
I used to have some lag issues. After a quick search I found a site (sorry, can't share more links with my current reputation) that told me I had to put a timeout in the main loop and that I should use a second canvas for buffering. Adding the timeout worked like a charm but I'm still curious about the buffering canvas. I'm unsure how to go about this since I'm dealing with a renderer and a canvas. I don't even know if I should still bother with a buffer, since it seems to work just fine now, although that may change in the future when I try to render more meshes at a time.
My code currently only runs in firefox for me. Chrome and Internet explorer both just show a blank screen. Any ideas what I need to change in order to fix this?
When I run the code in firefox the cupboard is completely black at first. When I move it (at all) it immediately changes to the texture. Any ideas? I could come up with a dirty fix that moves the camera up and down 1 pixel in the setup but I'd rather not.
I tried uploading the code to jsfiddle (importing the texture from tinypic) but that doesn't go so well. Either I'm importing the texture wrong or jsfiddle just doesn't like it when I use external pictures. However, if you download the texture and put it in the same folder as the code you should be able to open it in firefox (only works in firefox (see issue 4)). So if you want to see what's going on: copy the code into a .html file and download the texture.
<!DOCTYPE HTML>
<html>
<head>
<title>Canvas demo</title>
<script type="text/javascript" src="http://www.html5canvastutorials.com/libraries/Three.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
//three.js vars
var camera;
var scene;
var renderer;
var material;
var directionalLight;
//input vars
var lastX = 0;
var lastY = 450;
var clickX;
var clickY;
var mousedown;
function rerender(){
//draw
renderer.render(scene, camera);
//redraw after 25 ms (the 25 ms delay reduces lag)
setTimeOut( requestAnimFrame(function(){rerender()}), 25);
}
$(document).ready(function() {
//initialize renderer
renderer = new THREE.WebGLRenderer({antialias : true});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.domElement.id = "visiblecanvas";
document.body.appendChild(renderer.domElement);
//camera
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.y = -450;
camera.position.z = 400;
camera.rotation.x = 45.2;
//scene
scene = new THREE.Scene();
//material
//non-working tiled texture
/*
var textureMap = map: THREE.ImageUtils.loadTexture("wood1.jpg")
textureMap.wrapS = THREE.RepeatWrapping;
textureMap.wrapT = THREE.RepeatWrapping;
textureMap.repeat.x = 100;
textureMap.repeat.y = 100;
*/
//workingg stretched texture
material = new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture("wood1.jpg")});
//the cupboard
//cube
var cube1 = new THREE.Mesh(new THREE.CubeGeometry(300,50,10), material);
cube1.overdraw = true;
scene.add(cube1);
//cube
var cube2 = new THREE.Mesh(new THREE.CubeGeometry(300,10,300), material);
cube2.overdraw = true;
cube2.position.z += 150;
cube2.position.y += 20;
scene.add(cube2);
//cube
var cube3 = new THREE.Mesh(new THREE.CubeGeometry(10,50,300), material);
cube3.overdraw = true;
cube3.position.z += 150;
cube3.position.x += 145;
scene.add(cube3);
//cube
var cube4 = new THREE.Mesh(new THREE.CubeGeometry(10,50,300), material);
cube4.overdraw = true;
cube4.position.z += 150;
cube4.position.x -= 145;
scene.add(cube4);
//cube
var cube5 = new THREE.Mesh(new THREE.CubeGeometry(300,50,10), material);
cube5.overdraw = true;
cube5.position.z += 300;
scene.add(cube5);
// add subtle ambient lighting
var ambientLight = new THREE.AmbientLight(0x555555);
scene.add(ambientLight);
// add directional light source
directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
//mousedown event
$('#visiblecanvas').mousedown(function(e){
clickX = e.pageX - this.offsetLeft + lastX;
clickY = e.pageY - this.offsetLeft + lastY;
mousedown = true;
});
//mousemove event, act if mousedown
$('#visiblecanvas').mousemove(function(e){
if(mousedown) {
var xDiff = e.pageX - this.offsetLeft - clickX;
var yDiff = e.pageY - this.offsetLeft - clickY;
lastX = -xDiff;
lastY = -yDiff;
camera.position.x = lastX;
camera.position.y = -lastY;
rerender();
}
delay(5);
});
//mouseup event
$('#visiblecanvas').mouseup(function(e){
mousedown = false;
});
//mouseleave event (mouse leaves canvas, stop moving cupboard)
$('#visiblecanvas').mouseleave(function(e){
mousedown = false;
});
rerender();
});
//request new frame
window.requestAnimFrame = (function (callback){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
})();
</script>
</body>
</html>
Thanks for taking a look! hope you can answer any of my questions.
1) Use JavaScript console to debug the code.
2) The jsfiddle is missing jQuery.
3) This line:
var textureMap = map: THREE.ImageUtils.loadTexture("wood1.jpg")
must be:
var textureMap = THREE.ImageUtils.loadTexture("wood1.jpg");
See the extra map: and the missing semicolon.
4) The repeat texture parameters are too big. Default value is 1, to repeat the texture one time. Try to change that values to 2, 3, ... and so.
5) delay function is undefined, remove it
6) setTimeOut function is undefined (setTimeout?, JavaScript is case sensitive)
7) Rewrite the rendererer function to this:
function rerender(){
requestAnimFrame(rerender);
renderer.render(scene, camera);
}
Take a look at this: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
8) Remove the call to the rerender function inside the mousemove event
9) IE and WebGL?
Try:
function rerender(){
requestAnimFrame(rerender);
renderer.render(scene, camera);
}

Three.js does not show texture on sphere

There are some threads about textures which do not showing up. I have tried them all, but nothing helped.
I have spent a few hours on this now. Every time I end up looking at a black sphere.
I am working on Chrome v18 and Windows 7. I also tried Firefox, but this browser does not really support Three.js.
This is the body of the script:
<body>
<script src="../build/Three.js"></script>
<script src="js/Stats.js"></script>
<script src="../build/jquery-1.7.2.min.js"></script>
This is the script itself:
// stap1) camera, set the scene size
var WIDTH = 400,
HEIGHT = 300;
// set some camera attributes
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
var camera = new THREE.PerspectiveCamera(
VIEW_ANGLE,
ASPECT,
NEAR,
FAR );
// stap2) scene:
var scene = new THREE.Scene();
// the camera starts at 0,0,0 so pull it back
scene.add(camera);
camera.position.z = +300;
// get the DOM element to attach to
// - assume we've got jQuery to hand
var container = $('#container');
// stap3)create a WebGL renderer:
var renderer = new THREE.WebGLRenderer();
// start the renderer
renderer.setSize(WIDTH, HEIGHT);
// attach the render-supplied DOM element
container.append(renderer.domElement);
// bol maken:
// create the sphere's material
// b.v: THREE.MeshBasicMaterial
var sphereMaterial = new THREE.MeshLambertMaterial(
{
map: THREE.ImageUtils.loadTexture("http://dev.root.nl/tree/examples/textures/ash_uvgrid01.jpg")
});
// set up the sphere vars
var radius = 50, segments = 16, rings = 16;
var sphereGeometry = new THREE.SphereGeometry(radius, segments, rings);
// create a new mesh with sphere geometry -
var sphere = new THREE.Mesh(
sphereGeometry,
sphereMaterial
);
sphere.position.x=0;
var s=1;
sphere.scale.set(s, s, s);
// add the sphere to the scene
scene.add(sphere);
// create a point light
var pointLight = new THREE.PointLight( 0xFFFFFF );
// set its position
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
// add to the scene
scene.add(pointLight);
// draw!
renderer.render(scene, camera);
You need to wait until the image used as texture is fully downloaded.
I have put your code on the web: http://jsfiddle.net/4Qg7K/ and just added a classic "render loop":
requestAnimationFrame(render);
function render(){
requestAnimationFrame(render);
sphere.rotation.y += 0.005; //rotation stuff, just for fun
renderer.render(scene, camera);
};
requestAnimationFrame function works like a timer, calling to the render function each time the browser is ready to update the web page.
BTW, Three.js works fine with Firefox.