I'm writing and animation loop using three.js and all the examples (mrdoob, stemkoski) I see online use unprotected globals at the beginning of the script. I tried to enclose these in the init() function and then pass them as arguments through the animation loop. However, the renderer is coming up undefined.
I'm not sure what I'm missing below. My primary question is how to understand best practice for setting up an animation loop with good closure (protecting variables that would otherwise be global). Thanks!
// THE MAIN ANIMATION LOOP:
// UPDATE the scene
function update(keyboard, controls, stats, clock) {
// delta = change in time since last call (in seconds)
var delta = clock.getDelta();
// functionality provided by THREEx.KeyboardState.js
if ( keyboard.pressed("z") )
{
// do something
}
controls.update();
stats.update();
};
// RENDER the scene
function render(renderer, scene, camera) {
renderer.render(scene, camera);
};
// ANIMATE the scene
function animate(scene, camera, renderer, controls, stats, keyboard, clock) {
requestAnimationFrame(animate);
render(renderer, scene, camera);
update(keyboard, controls, stats, clock);
};
// *********************
// INITIALIZES THE SCENE
function init(images) { // `images` is passed by a callback from loadImages
// standard global variables, held privately
var container, scene, camera, renderer, controls, stats;
var keyboard = new THREEx.KeyboardState();
var clock = new THREE.Clock();
///////////
// SCENE //
///////////
scene = new THREE.Scene();
////////////
// CAMERA //
////////////
// set the view size in pixels (custom or according to window size)
var SCREEN_WIDTH = 1920, SCREEN_HEIGHT = 1080;
// var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
// camera attributes
var VIEW_ANGLE = 20, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
// set up camera
camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
// add the camera to the scene
scene.add(camera);
// the camera defaults to position (0,0,0)
// so pull it back (z = 400) and up (y = 100) and set the angle towards the scene origin
// (x,y,z)
camera.position.set(0,150,1000);
camera.lookAt(scene.position);
//////////////
// RENDERER //
//////////////
// create and start the renderer; choose antialias setting.
if (Detector.webgl)
renderer = new THREE.WebGLRenderer( {antialias:true} );
else
renderer = new THREE.CanvasRenderer();
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
// attach div element to variable to contain the renderer
container = document.getElementById( 'ThreeJS' );
// attach renderer to the container div
container.appendChild( renderer.domElement );
///////////
// STATS //
///////////
// displays current and past frames per second attained by scene
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.bottom = '0px';
stats.domElement.style.zIndex = 100;
container.appendChild( stats.domElement );
///////////
// LIGHT //
///////////
// create a light
var light = new THREE.PointLight(0xffffff);
light.position.set(100,250,0);
scene.add(light);
////////////
// IMAGES //
////////////
var element1 = THREE.ImageUtils.loadTexture(images.dresser10);
var element2 = THREE.ImageUtils.loadTexture(images.dresser14);
var element1Material = new THREE.SpriteMaterial( { map: element1, useScreenCoordinates: true, alignment: THREE.SpriteAlignment.topLeft } );
var sprite = new THREE.Sprite(element1Material);
sprite.position.set( 50, 50, 0 );
sprite.scale.set( 64, 64, 1.0 ); // imageWidth, imageHeight
scene.add(sprite);
animate(container, scene, camera, renderer, controls, stats, keyboard, clock);
};
// ********************************************************
// CHECKS TO SEE IF THE WINDOW HAS LOADED BEFORE PROCEEDING
// Once the window is loaded, calls the init function
window.addEventListener ("load", eventWindowLoaded, false);
function eventWindowLoaded() {
loadImages(init); // calls to initialize the scene once the images are loaded
}
I followed #Bergi 's advice above and rewrote the animation loop in a Crockford style module that returns an object full of privileged methods that can access the now protected variables. Here it is for anyone looking for a similar pattern:
// ************************
// THE MAIN ANIMATION LOOP:
var animLoop = (function () {
// standard global variables, held privately in this module
var container, scene, camera, renderer, controls, stats;
var keyboard = new THREEx.KeyboardState();
var clock = new THREE.Clock();
// SCENE
scene = new THREE.Scene();
// CAMERA
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
var VIEW_ANGLE = 20, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
scene.add(camera);
camera.position.set(0,150,1000);
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 );
// LIGHT
var light = new THREE.PointLight(0xffffff);
light.position.set(100,250,0);
scene.add(light);
// IMAGES
var images;
var element1, element2, element1Material, sprite;
// RETURN:
// *** returns an object full of functions with priviledged access to the private variables listed above ***
return {
setImages: function (images_) { // sets the value of the images (array) above
images = images_;
},
createSprites: function () {
var element1 = THREE.ImageUtils.loadTexture(images.dresser10.src);
var element1Material = new THREE.SpriteMaterial( { map: element1, useScreenCoordinates: true, alignment: THREE.SpriteAlignment.topLeft } );
var sprite = new THREE.Sprite(element1Material);
sprite.position.set( 50, 50, 0 );
sprite.scale.set( 64, 64, 1.0 );
scene.add(sprite);
},
update: function () {
var delta = clock.getDelta();
// functionality provided by THREEx.KeyboardState.js
if ( keyboard.pressed("z") )
{
// do something
}
},
render: function () {
renderer.render(scene, camera);
}
};
}());
// ANIMATE the scene
function animate() {
requestAnimationFrame( animate );
animLoop.render();
animLoop.update();
};
// INITIALIZES THE SCENE
function init(images) { // `images` is passed by a callback not included here
animLoop.setImages(images); // places the initial array of images as a private variable in the animLoop object
animLoop.createSprites();
animate();
};
window.addEventListener ("load", eventWindowLoaded, false);
function eventWindowLoaded() {
loadImages(init); // calls to initialize the scene once the images are loaded
};
Related
In the last two months i have learned a lot about three.js and javascript. i have now gone deeper into the handling of shaders and i once saw a nice example of creating procedural planets on the web. I find spherical geometries interesting because their non-euclidean geometry makes them a nice challenge for textures.
I have shown the main code here. my problem is that the texture rendering doesn't work.
I have tested the individual components of my program. The shader and the planet class, all functions work correctly.
the problem is the renderer. I need this to display the scene but also to create the textures. When in the function
textureGeneratorMaterial (below) renderer.render(textureScene, textureCamera, texture, true); is activate, I only get a black screen. There after the function renderer.render(scene, camera); is called, I mean that the normal scene should be seen. Does the program remain trapped in the texture scene? Why does renderer.render(scene, camera) not work, if the renderer is also called in textureGeneratorMaterial?
I've already tried to create a second renderer, but that doesn't work either. At the moment i don't know what to do, because i don't understand the cause. Someone knows why the renderer doesn't want the way I want?
var camera, controls, scene, renderer, container;
var sunLight, ambientlight;
var test1, test2, test3, test4;
function main() {
init();
animate();
}
function init() {
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
container = document.getElementById('container');
renderer.setSize(container.clientWidth, container.clientHeight);
container.appendChild( renderer.domElement );
var aspect = container.clientWidth / container.clientHeight;
scene = new THREE.Scene();
scene.background = new THREE.Color( 0x000000 );
camera = new THREE.PerspectiveCamera( 45, container.clientWidth / container.clientHeight, 1, 10000 );
camera.position.set(0, 0, 20);
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.enableZoom = true;
controls.enabled = true;
controls.target.set(0, 0, 0);
//-------------
sunLight = new THREE.PointLight(new THREE.Color(0xffffff), 1.0);
sunLight.position.set(100, 0, 0);
scene.add(sunLight);
ambientlight = new THREE.AmbientLight( 0xF0F0F0 ); // soft white light
scene.add( ambientlight );
var maps = generateTextures(); //--here is the problem---
/* -----used ro check "function textureGeneratorMaterial(index)" works------
var plane = new THREE.Mesh(
new THREE.PlaneGeometry(1024, 1024),
textureGeneratorMaterial(0)
);
scene.add( plane );
*/
/*-----used ro check "Planet class" works------
for(var i = 0; i <6;i++){
maps.textureMaps[i].texture = new THREE.TextureLoader().load("img/Cay_sand.jpeg");
maps.bumpMaps[i].texture = new THREE.TextureLoader().load("img/Cay_sand.jpeg");
}
*/
scene.add(new Planet(5, maps.textureMaps, maps.bumpMaps)); // works correct
}//-------End init----------
function animate() {
requestAnimationFrame( animate );
render();
}//-------End animate----------
function render() {
document.getElementById("demo1").innerHTML = test1;
document.getElementById("demo2").innerHTML = test2;
document.getElementById("demo3").innerHTML = test3;
document.getElementById("demo4").innerHTML = test4;
camera.updateMatrixWorld();
camera.updateProjectionMatrix();
renderer.render(scene, camera);
}//-------End render----------
function generateTextures() {
var textureMaps = [];
var bumpMaps = [];
var resolution = 1024;
for (var index = 0; index < 6; index++) {
var texture = new THREE.WebGLRenderTarget(resolution, resolution, {minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat});
var textureCamera = new THREE.OrthographicCamera(-resolution/2, resolution/2, resolution/2, -resolution/2, -100, 100);
textureCamera.position.z = 10;
var textureScene = new THREE.Scene();
var plane = new THREE.Mesh(
new THREE.PlaneGeometry(resolution, resolution),
textureGeneratorMaterial(index)
);
plane.position.z = -10;
textureScene.add(plane);
// renderer.render(textureScene, textureCamera, texture, true);
var buffer = new Uint8Array(resolution * resolution * 4);
var gl = renderer.getContext();
gl.readPixels( 0, 0, resolution, resolution, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
textureMaps.push(texture);
bumpMaps.push({image: {data: buffer, height: resolution, width: resolution}});
}
return {textureMaps: textureMaps, bumpMaps: bumpMaps};
}
Ok i have found a solution. I was convinced that it was up to the renderer and that it would remain trapped in the texture target when it was called up for the first time.
In three.js there is the possibility to reset the render target and if you do that, three.js seems to see it as in need of initialization and accepts the call to the renderer to render the main scene.
I added this line: renderer.setRenderTarget(null);
See below
function generateTextures() {
var textureMaps = [];
var bumpMaps = [];
var resolution = 2048;
for (var index = 0; index < 6; index++) {
var texture = new THREE.WebGLRenderTarget(resolution, resolution, {minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat});
var textureCamera = new THREE.OrthographicCamera(-resolution/2, resolution/2, resolution/2, -resolution/2, -100, 100);
textureCamera.position.z = 10;
var textureScene = new THREE.Scene();
var plane = new THREE.Mesh(
new THREE.PlaneGeometry(resolution, resolution),
textureGeneratorMaterial(index)
);
plane.position.z = -10;
textureScene.add(plane);
renderer.render(textureScene, textureCamera, texture, true);
var buffer = new Uint8Array(resolution * resolution * 4);
var gl = renderer.getContext();
gl.readPixels( 0, 0, resolution, resolution, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
textureMaps.push(texture);
bumpMaps.push({image: {data: buffer, height: resolution, width: resolution}});
renderer.setRenderTarget(null);
}
return {textureMaps: textureMaps, bumpMaps: bumpMaps};
}
In older versions like the example I saw, this wasn't necessary. But this is not meant as a criticism. It's a clean solution. So three always knows that there is a need for renderer action.
I am loading a model through GLTF loader. I want to select a mesh on mouse hover. Everything is going cool, but the main problem is when hovering its changing the color all material whose name is same (as per my researches). When i am debugging its INTERSECTED returning single material. I don't know why its happening. After many researches i am asking this question here.
Please see my code below.
<div id="ThreeJS" style="position: absolute; left:0px; top:0px"></div>
var container, scene, camera, renderer, controls, stats;
var clock = new THREE.Clock();
var xyzz;
// custom global variables
var cube;
var projector,
mouse = {
x: 0,
y: 0
},
INTERSECTED;
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 = 20000;
camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
scene.add(camera);
camera.position.set(0, 0, 0);
camera.lookAt(scene.position);
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
container = document.getElementById("ThreeJS");
container.appendChild(renderer.domElement);
// EVENTS
// CONTROLS
controls = new THREE.OrbitControls(camera, renderer.domElement);
// STATS
stats = new Stats();
stats.domElement.style.position = "absolute";
stats.domElement.style.bottom = "0px";
stats.domElement.style.zIndex = 100;
container.appendChild(stats.domElement);
// LIGHT
const skyColor = 0xb1e1ff; // light blue
const groundColor = 0xb97a20; // brownish orange
const intensity = 5;
const light = new THREE.HemisphereLight(
skyColor,
groundColor,
intensity
);
scene.add(light);
scene.background = new THREE.Color("#fff");
// GLTF Loader
function frameArea(sizeToFitOnScreen, boxSize, boxCenter, camera) {
const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
const halfFovY = THREE.Math.degToRad(camera.fov * 0.5);
const distance = halfSizeToFitOnScreen / Math.tan(halfFovY);
// compute a unit vector that points in the direction the camera is now
// in the xz plane from the center of the box
const direction = new THREE.Vector3()
.subVectors(camera.position, boxCenter)
.multiply(new THREE.Vector3(1, 0, 1))
.normalize();
// move the camera to a position distance units way from the center
// in whatever direction the camera was from the center already
camera.position.copy(
direction.multiplyScalar(distance).add(boxCenter)
);
// pick some near and far values for the frustum that
// will contain the box.
camera.near = boxSize / 100;
camera.far = boxSize * 100;
camera.updateProjectionMatrix();
// point the camera to look at the center of the box
// camera.position.set(0, 150, 400);
camera.lookAt(boxCenter.x, boxCenter.y, boxCenter.z);
}
var loader = new THREE.GLTFLoader();
loader.load(
// resource URL
"models/gltf/DamagedHelmet/glTF/50423_ Revit Model.gltf",
// called when the resource is loaded
function(gltf) {
const root = gltf.scene;
scene.add(root);
// console.log(dumpObject(root).join("\n"));
const box = new THREE.Box3().setFromObject(root);
const boxSize = box.getSize(new THREE.Vector3()).length();
const boxCenter = box.getCenter(new THREE.Vector3());
// set the camera to frame the box
frameArea(boxSize * 1, boxSize, boxCenter, camera);
// update the Trackball controls to handle the new size
controls.maxDistance = boxSize * 10;
controls.target.copy(boxCenter);
controls.update();
},
// called while loading is progressing
function(xhr) {
console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
},
// called when loading has errors
function(error) {
debugger;
console.log("An error happened");
}
);
projector = new THREE.Projector();
// when the mouse moves, call the given function
document.addEventListener("mousemove", onDocumentMouseMove, false);
}
function onDocumentMouseMove(event) {
// update the mouse variable
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
}
function animate() {
requestAnimationFrame(animate);
render();
update();
}
function update() {
// find intersections
// create a Ray with origin at the mouse position
// and direction into the scene (camera direction)
var vector = new THREE.Vector3(mouse.x, mouse.y, 1);
vector.unproject(camera);
var ray = new THREE.Raycaster(
camera.position,
vector.sub(camera.position).normalize()
);
// create an array containing all objects in the scene with which the ray intersects
var intersects = ray.intersectObjects(scene.children, true);
// INTERSECTED = the object in the scene currently closest to the camera
// and intersected by the Ray projected from the mouse position
// if there is one (or more) intersections
if (intersects.length > 0) {
// if the closest object intersected is not the currently stored intersection object
if (intersects[0].object != INTERSECTED) {
// restore previous intersection object (if it exists) to its original color
if (INTERSECTED) {
INTERSECTED.material.color.setHex(INTERSECTED.currentHex);
}
// store reference to closest object as current intersection object
INTERSECTED = intersects[0].object;
console.log(INTERSECTED);
// store color of closest object (for later restoration)
INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
// set a new color for closest object
INTERSECTED.material.color.setHex(0xffff00);
}
}
// there are no intersections
else {
// restore previous intersection object (if it exists) to its original color
if (INTERSECTED)
INTERSECTED.material.color.setHex(INTERSECTED.currentHex);
// remove previous intersection object reference
// by setting current intersection object to "nothing"
INTERSECTED = null;
}
controls.update();
stats.update();
}
function render() {
renderer.render(scene, camera);
}
function dumpObject(obj, lines = [], isLast = true, prefix = "") {
const localPrefix = isLast ? "└─" : "├─";
lines.push(
`${prefix}${prefix ? localPrefix : ""}${obj.name || "*no-name*"} [${
obj.type
}]`
);
const newPrefix = prefix + (isLast ? " " : "│ ");
const lastNdx = obj.children.length - 1;
obj.children.forEach((child, ndx) => {
const isLast = ndx === lastNdx;
dumpObject(child, lines, isLast, newPrefix);
});
return lines;
}
Please help me out.
I didn't read through all of the code, but I think this might already help:
In your intersection-handler, you are updating the color of the material assigned to the object (INTERSECTED.material.color.setHex(...)). This will cause the problems you describe as identical materials are very likely reused for multiple objects. To prevent that, you could use a different material:
const hightlightMaterial = new MeshStandardMaterial(...);
and instead of just updating the color, replace the material:
INTERSECTED.originalMaterial = INTERSECTED.material;
INTERSECTED.material = highlightMaterial;
Restore the original when "unhighlighting" the object:
INTERSECTED.material = INTERSECTED.originalMaterial;
delete INTERSECTED.originalMaterial;
If you need the highlightMaterial to retain other material-properties from the original, you can do this to copy over all material properties beforehand:
highlightMaterial.copy(INTERSECTED.material);
highlightMaterial.color.copy(highlightColor);
I'm setting up a 3d asset viewer in Three.js. I'm running the code on a Plesk server provided by the university and have it linked via Dreamweaver. I'm a total newbie to JS and it was suggested in many threads and posts that I wrap my code within an 'init();' function. Up doing so, and clearing any errors that the code had, it is now showing a black screen, rather than the 3d model it would show before.
I've spent the whole day error checking removing problems that I was having which included the 'canvas' not being created inside the 'container' div, and the 'onWindowResize' function. All these problems have been resolved, and there are no errors in the code apparently. I've got ambient lights in the code and there was a working skybox, so I'm sure its not a problem with position of camera or lack of lighting.
I know that you need as little code as possible, but I have no idea where the problem is coming from, so a majority of the code on the page is here :
<div id="container" ></div>
<script>
let container;
let camera;
let controls;
let scene;
let renderer;
init();
animate;
function init(){
// Renderer - WebGL is primary Renderer for Three.JS
var renderer = new THREE.WebGLRenderer({antialias : true});
renderer.setClearColor(0xEEEEEE, 0.5);
// Selects and applies parameters to the 'Container' div
var container = document.querySelector("#container");
container.appendChild(renderer.domElement);
renderer.setSize(container.clientWidth, container.clientHeight);
// Perspective Camera (FOV, aspect ratio based on container, near, far)
var camera = new THREE.PerspectiveCamera( 75, container.clientWidth / container.clientHeight, 0.1, 1000);
camera.position.x = 750;
camera.position.y = 500;
camera.position.z = 1250;
// Scene will contain all objects in the world
var scene = new THREE.Scene();
//Lighting (Colour, intensity)
var light1Ambient = new THREE.AmbientLight(0xffffff , 0.3);
scene.add(light1Ambient);
var light1Point = new THREE.PointLight(0xfff2c1, 0.5, 0, 2);
scene.add(light1Point);
var light2Point = new THREE.PointLight(0xd6e3ff, 0.4, 0, 2);
scene.add(light2Point);
// All basic Geomety
var newPlane = new THREE.PlaneGeometry(250,250,100,100);
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial( {color: 0x00ff00} )
);
scene.add(mesh);
// Water
water = new THREE.Water(newPlane,
{
textureWidth: 512,
textureHeight: 512,
waterNormals: new THREE.TextureLoader().load( 'http://up826703.ct.port.ac.uk/CTPRO/textures/waternormals.jpg', function ( texture ) {
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
} ),
alpha: 1.0,
sunDirection: light1Point.position.clone().normalize(),
sunColor: 0xffffff,
waterColor: 0x001e0f,
distortionScale: 0.5,
fog: scene.fog !== undefined
}
);
water.rotation.x = - Math.PI / 2;
scene.add( water );
// All Materials (Normal for Debugging) (Lambert: color)
var material = new THREE.MeshLambertMaterial({color: 0xF3FFE2});
var materialNew = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
// Skybox
var skybox = new THREE.BoxGeometry(1000,1000, 1000);
var skyboxMaterials =
[
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_ft.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_bk.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_up.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_dn.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_rt.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_lf.jpg"), side: THREE.DoubleSide }),
];
var skyboxMaterial = new THREE.MeshFaceMaterial(skyboxMaterials);
var skyMesh = new THREE.Mesh (skybox, skyboxMaterial);
scene.add(skyMesh);
//Grid Helper Beneath Ship
scene.add(new THREE.GridHelper(250, 250));
//OBJ Model Loading
var objLoader = new THREE.OBJLoader();
objLoader.load('http://up826703.ct.port.ac.uk/CTPRO/models/ship1.obj', function(object){
scene.add(object);
});
// Object positioning
water.position.y = -2.5;
// Misc Positioning
light1Point.position.z =20;
light1Point.position.x = 25;
// z - front-back position
light2Point.position.z = -400;
// x - left-right
light2Point.position.x = -25;
// y - up- down
light2Point.position.y = 250;
window.addEventListener("resize", onWindowResize, false);
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(container.clientWidth, container.clientHeight);
};
};
// Canvas adapts size based on changing windows size
//Render loop
var animate = function(){
water.material.uniforms[ "time" ].value += 1.0 / 120.0;
function drawFrame(ts){
var center = new THREE.Vector2(0,0);
window.requestAnimationFrame(drawFrame);
var vLength = newPlane.geometry.vertices.length;
for (var i = 0; i < vLength; i++) {
var v = newPlane.geometry.vertices[i];
var dist = new THREE.Vector2(v.x, v.y).sub(center);
var size = 2.0;
var magnitude = 8;
v.z = Math.sin(dist.length()/-size + (ts/900)) * magnitude;
}
newPlane.geometry.verticesNeedUpdate = true;
};
requestAnimationFrame(animate)
renderer.render(scene, camera);
controls.update();
}
</script>
I'm no professional, so I'm sorry if this is super rough for those of you with experience!
I need to point out, before wrapping all of this in the init(); function, it was working perfectly.
When working, I should see a crudely modeled ship sitting in some water, with a cloud skybox. The controls were working and it would auto rotate.
Right now it does none of this. The obj loader is working as seen in the chrome console log OBJLoader: 1661.970703125ms but again, nothing is actually displayed, it's just a black screen.
Thanks to anyone who's able to help me out with this!
this line
animate;
needs to a function call
animate();
Also you probably need to change the code below where you create the animate function from
var animate = function(){
To this
function animate(){
The reason is named functions are defined when the code is loaded but variables var are created when the code is executed. So with code like this
init();
animate();
var animate = function(){ ...
animate doesn't actually exist at the point the code tries to call it whereas with this
init();
animate();
function animate(){ ...
it does exist
You could also re-arrange the code so for example define animate before you use it should work.
var animate = function(){
...
};
init();
animate();
It also appear some are declared inside init which means that are not available to animate. So for example
var renderer = new THREE.WebGLRenderer({antialias : true});
declares a new variable renderer that only init can see. You wanted to set the renderer variable that is outside of init so change the code to
renderer = new THREE.WebGLRenderer({antialias : true});
controls is never defined so you probably need to define it or comment out
controls.update();
to
// controls.update();
note: you might find these tutorials helpful although if you're new to JavaScript you should probably spend time learning JavaScript
I tried to set all the necessary functionality into one class in order to create a simple three.js scene with a cube. I don't get any errors, but the scene stays black when I open it in the browser.
Here is my code:
class SceneInit {
constructor(fov = 45,camera,scene,controls,renderer)
{
this.camera = camera;
this.scene = scene;
this.controls = controls;
this.renderer = renderer;
this.fov = fov;
}
initScene() {
this.camera = new THREE.PerspectiveCamera(this.fov, window.innerWidth / window.innerHeight, 1, 1000);
this.camera.position.z = 15;
this.controls = new THREE.TrackballControls( this.camera );
//this.controls.addEventListener('change', this.renderScene);
this.scene = new THREE.Scene();
//specify a canvas which is already created in the HTML file and tagged by an id //aliasing enabled
this.renderer = new THREE.WebGLRenderer({canvas: document.getElementById('myThreeJsCanvas') , antialias: true});
this.renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(this.renderer.domElement);
//ambient light which is for the whole scene
let ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
ambientLight.castShadow = false;
this.scene.add(ambientLight);
//spot light which is illuminating the chart directly
let spotLight = new THREE.SpotLight(0xffffff, 0.55);
spotLight.castShadow = true;
spotLight.position.set(0,40,10);
this.scene.add(spotLight);
//if window resizes
window.addEventListener('resize', this.onWindowResize, false);
}
animate(){
requestAnimationFrame( this.animate.bind(this) );
this.render();
this.controls.update();
}
render(){
this.renderer.render( this.scene, this.camera );
}
onWindowResize() {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize( window.innerWidth, window.innerHeight );
}
}
And then I try to instantiate a new object and add an object to the scene. When I try to print the children of the scene, it returns me the right objects, but as I mentioned before the scene stays black. Only the renderer window is getting drawed in the browser.
let test = new SceneInit(45);
test.initScene();
test.animate();
let geometry = new THREE.BoxBufferGeometry( 200, 200, 200 );
let material = new THREE.MeshBasicMaterial();
let mesh = new THREE.Mesh( geometry, material );
test.scene.add(mesh);
console.log(test.scene.children); //returns 3 objects (ambientLight, spotLight, mesh)
I got the answer.
The problem in the code was that the BoxGeometry was too big and the camera was inside the box. With the clipping set to 1 it wouldn't even render it.
So the solution is to set a smaller BoxGeometry. or to move the camera away!
I used the OBJMTLLoader class for one obj file and rotation worked well around a fixed point on the object by using object.rotation.y -= 0.5. Using the same code (minus changing the camera position), I replaced the .obj file with another and the rotation is now going in a circular motion, like around the camera instead of staying in place. Any idea why when I used the same code?
Thanks
EDIT:
var OBJLoaded;
function init()
{
container = document.getElementById('player');
camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 1, 2000);
camera.position.x = 110;
camera.position.z = -160;
camera.position.y = 15;
// camera.position.z = 40;
// camera.position.y = 2;
//scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight( 0x444444 );
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffffff );
directionalLight.position.set( 100, 90, 200 );
scene.add( directionalLight );
//model
var loader = new THREE.OBJMTLLoader();
//loader.load('./assets/Stereo_LowPoly.obj', './assets/Stereo_LowPoly.mtl', function(object)
loader.load('./assets/studio_beats.obj', './assets/studio_beats.mtl', function(object)
{
OBJLoaded = object;
console.log(object);
scene.add( object );
});
renderer = new THREE.WebGLRenderer({alpha: true});
renderer.setClearColor(0x000000, 0);
renderer.setSize($('#player').width(), $('#player').height());
container.appendChild(renderer.domElement);
scene.add(camera);
}
function animateBoombox()
{
requestAnimationFrame(animateBoombox);
render();
}
function render()
{
var rotSpeed = 0.004;
if (OBJLoaded)
{
OBJLoaded.rotation.y -= rotSpeed;
}
renderer.render(scene, camera);
}
The parts commented (camera and object load) is for the previous object that was loaded. That works fine, but the uncommented partdoes not work the same.
The object you loaded has a pivot point which came from the model creater software... You need to change the pivot point of the object before you load it with three.js.
If you cannot, you should do it like i had in loader callback:
var loader = new THREE.OBJMTLLoader();
loader.load('your_file.obj', 'your_file.mtl', function (object) {
object.traverse(function (child) {
child.centroid = new THREE.Vector3();
for (var i = 0, l = child.geometry.vertices.length; i < l; i++) {
child.centroid.add(child.geometry.vertices[i].clone());
}
child.centroid.divideScalar(child.geometry.vertices.length);
var offset = child.centroid.clone();
child.geometry.applyMatrix(new THREE.Matrix4().makeTranslation(-offset.x, -offset.y, -offset.z));
child.position.copy(child.centroid);
child.geometry.computeBoundingBox();
});
});
Then rotate your object...