How to change variable after checking controller.userData - three.js

I'm working with Three.js on a project. I just started working with it and mostly tried my luck with picking different things from the examples.
In short: I'm loading a volume and want to show another layer of it after the event listener for one of the controllers fired.
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js vr - dragging</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link type="text/css" rel="stylesheet" href="main.css">
</head>
<body>
<div id="info">
three.js nrrd
</div>
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/es-module-shims#1.3.6/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "../build/three.module.js",
"three/addons/": "./jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { VRButton } from 'three/addons/webxr/VRButton.js';
import { XRControllerModelFactory } from 'three/addons/webxr/XRControllerModelFactory.js';
import { NRRDLoader } from 'three/addons/loaders/NRRDLoader.js';
let camera, scene, renderer;
let controller1, controller2;
let raycaster;
let xlayer ;
const intersected = [];
const tempMatrix = new THREE.Matrix4();
let controls, group, array;
init();
animate();
function init() {
const container = document.createElement('div');
document.body.appendChild(container);
scene = new THREE.Scene();
scene.background = new THREE.Color(0x808080);
camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 40);
camera.position.set(0, 1.6, 3);
controls = new OrbitControls(camera, container);
controls.target.set(0, 1.6, 0);
controls.update();
scene.add(new THREE.HemisphereLight(0x808080, 0x606060));
group = new THREE.Group();
array = [];
scene.add(group);
var holder = new THREE.Group();
const loader = new NRRDLoader();
loader.load('models/nrrd/retina.nrrd', function (volume) {
const a = volume.xLength;
const b = volume.yLength;
const c = volume.zLength;
//box helper to see the extend of the volume
const geometry = new THREE.BoxGeometry(volume.xLength, volume.yLength, volume.zLength);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
cube.visible = false;
const box = new THREE.BoxHelper(cube);
holder.add(box);
box.applyMatrix4(volume.matrix);
holder.add(cube);
//z plane
const sliceZ = volume.extractSlice('z', xlayer);
holder.add(sliceZ.mesh);
holder.scale.set((1 / a) * 10, (1 / b) * 6, (1 / c) * 5);
holder.position.set(0, 0, -15);
scene.add(holder);
});
//l-left, r-right, t-top, b-bottom
const planegeometrylr = new THREE.PlaneGeometry(5, 6);
const planegeometrytb = new THREE.PlaneGeometry(10, 5);
const planematerial = new THREE.MeshBasicMaterial({ color: 'blue', side: THREE.DoubleSide });
const planel = new THREE.Mesh(planegeometrylr, planematerial);
const planer = new THREE.Mesh(planegeometrylr, planematerial);
const planet = new THREE.Mesh(planegeometrytb, planematerial);
const planeb = new THREE.Mesh(planegeometrytb, planematerial);
planel.rotateY(Math.PI / 2);
planel.position.set(-(10 / 2), 0, -15);
array.push(planel);
group.add(planel);
planer.rotateY(Math.PI / 2);
planer.position.set((10 / 2), 0, -15);
array.push(planer);
group.add(planer);
planet.rotateX(Math.PI / 2);
planet.position.set(0, (6 / 2), -15);
array.push(planet);
group.add(planet);
planeb.rotateX(Math.PI / 2);
planeb.position.set(0, -(6 / 2), -15);
array.push(planeb);
group.add(planeb);
//
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.shadowMap.enabled = true;
renderer.xr.enabled = true;
container.appendChild(renderer.domElement);
document.body.appendChild(VRButton.createButton(renderer));
// controllers
controller1 = renderer.xr.getController(0);
controller1.addEventListener('selectstart', onSelectStart);
controller1.addEventListener('selectend', onSelectEnd);
controller1.userData.selected = false;
scene.add(controller1);
controller2 = renderer.xr.getController(1);
controller2.addEventListener('selectstart', onSelectStart);
controller2.addEventListener('selectend', onSelectEnd);
controller2.userData.selected = false;
scene.add(controller2);
const controllerModelFactory = new XRControllerModelFactory();
//
const geometry = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, - 1)]);
const line = new THREE.Line(geometry);
line.name = 'line';
line.scale.z = 5;
controller1.add(line.clone());
controller2.add(line.clone());
raycaster = new THREE.Raycaster();
//
window.addEventListener('resize', onWindowResize);
function onSelectStart() {
this.userData.selected = true;
}
function onSelectEnd(event) {
const controller = event.target;
controller.userData.selected = false;
}
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function handle(controller) {
if (controller.userData.selected){
scene.background = new THREE.Color( 'green' );
xlayer=60;
}
}
function animate() {
renderer.setAnimationLoop(render);
}
function render() {
handle(controller1);
handle(controller2);
renderer.render(scene, camera);
}
</script>
</body>
</html>
xlayer=60 works in handle()(shows layer 60 other than defined in init()):
when its before the if clause of the controller.UserData
when its in it and I set it true right above the if clause
it doesn't work
whenever its in the if clause, even if something else in the if clause worked (like setting the background green)
I wonder if I did something wrong or if it just doesn't work like that.

Related

Exporting an animated scene with GLTFExporter in ThreeJS?

I'm trying to export an animation scene in ThreeJS with GLTFExporter, but the animation is not being exported. Everything is correctly exported, the shapes, the color... This project is using the example to export: https://threejs.org/examples/#misc_exporter_gltf, and the example to animate: https://threejs.org/examples/#misc_animation_keys, but they don't work together. Any idea?
If I open the file with https://gltf-viewer.donmccurdy.com/, I see an error:
But if I log the export options when exporting, I can see the animations are there:
Here's the code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - exporter - gltf</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="main.css">
</head>
<body>
<div id="info">
<button id="export_scene">Export Scene</button>
</div>
<script type="module">
import * as THREE from '../../build/three.module.js';
import { GLTFExporter } from './jsm/exporters/GLTFExporter.js';
function exportGLTF(input, animationClip) {
const gltfExporter = new GLTFExporter();
const options = {
binary: true,
maxTextureSize: 4096,
animations: [animationClip],
includeCustomExtensions: true
};
console.log(options);
gltfExporter.parse(input, function (result) {
if (result instanceof ArrayBuffer) {
saveArrayBuffer(result, 'scene.glb');
} else {
const output = JSON.stringify(result, null, 2);
console.log(output);
saveString(output, 'scene.gltf');
}
}, options);
}
document.getElementById('export_scene').addEventListener('click', function () {
exportGLTF(scene, clip);
});
const link = document.createElement('a');
link.style.display = 'none';
document.body.appendChild(link); // Firefox workaround, see #6594
function save(blob, filename) {
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
}
function saveString(text, filename) {
save(new Blob([text], { type: 'text/plain' }), filename);
}
function saveArrayBuffer(buffer, filename) {
save(new Blob([buffer], { type: 'application/octet-stream' }), filename);
}
let clock;
let camera, geometry, scene, renderer, mixer, clip;
let gridHelper, sphere, smallSphere;
init();
animate();
function init() {
scene = new THREE.Scene();
scene.name = 'scene';
// Perspective Camera
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
camera.position.set(10, 300, 0);
camera.name = "PerspectiveCamera";
scene.add(camera);
// Ambient light
const ambientLight = new THREE.AmbientLight(0xffffff, 0.2);
ambientLight.name = 'AmbientLight';
scene.add(ambientLight);
// DirectLight
const dirLight = new THREE.DirectionalLight(0xffffff, 1);
dirLight.target.position.set(0, 0, - 1);
dirLight.add(dirLight.target);
dirLight.lookAt(- 1, - 1, 0);
dirLight.name = 'DirectionalLight';
scene.add(dirLight);
//Axes
/*
const axes = new THREE.AxesHelper(500);
axes.name = "AxesHelper";
scene.add(axes);*/
// Sphere
const material = new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true });
sphere = new THREE.Mesh(new THREE.SphereGeometry(70, 10, 10), material);
sphere.position.set(0, 0, 0);
sphere.name = "Sphere";
scene.add(sphere);
// Small sphere
smallSphere = new THREE.Mesh(new THREE.SphereGeometry(20, 10, 10), material);
smallSphere.position.set(80, 0, 0);
smallSphere.name = "SmallSphere";
scene.add(smallSphere);
// POSITION
const positionKF = new THREE.VectorKeyframeTrack('.position', [0, 1, 2], [0, 90, 60, 30, 0, 60, 70, 40, 50]);
// SCALE
const scaleKF = new THREE.VectorKeyframeTrack('.scale', [0, 1, 2], [1, 1, 1, 2, 2, 2, 1, 1, 1]);
// ROTATION
// Rotation should be performed using quaternions, using a THREE.QuaternionKeyframeTrack
// Interpolating Euler angles (.rotation property) can be problematic and is currently not supported
// set up rotation about x axis
const xAxis = new THREE.Vector3(1, 0, 0);
const qInitial = new THREE.Quaternion().setFromAxisAngle(xAxis, 0);
const qFinal = new THREE.Quaternion().setFromAxisAngle(xAxis, Math.PI);
const quaternionKF = new THREE.QuaternionKeyframeTrack('.quaternion', [0, 1, 2], [qInitial.x, qInitial.y, qInitial.z, qInitial.w, qFinal.x, qFinal.y, qFinal.z, qFinal.w, qInitial.x, qInitial.y, qInitial.z, qInitial.w]);
// COLOR
const colorKF = new THREE.ColorKeyframeTrack('.material.color', [0, 1, 2], [1, 0, 0, 0, 1, 0, 0, 0, 1], THREE.InterpolateDiscrete);
// OPACITY
const opacityKF = new THREE.NumberKeyframeTrack('.material.opacity', [0, 1, 2], [1, 0, 1]);
// Clip
clip = new THREE.AnimationClip('Action', 3, [scaleKF, positionKF, quaternionKF, colorKF, opacityKF]);
// Mixer
mixer = new THREE.AnimationMixer(smallSphere);
const clipAction = mixer.clipAction(clip);
clipAction.play();
// Clock
clock = new THREE.Clock();
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
window.addEventListener('resize', onWindowResize);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
const timer = Date.now() * 0.0001;
const delta = clock.getDelta();
if (mixer) {
mixer.update(delta);
}
camera.position.x = Math.cos(timer) * 400;
camera.position.z = Math.sin(timer) * 400;
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
</script>
</body>
</html>
Any idea?
As Don McCurdy explained in the comments, there were two problems:
It's not possible to export animations for the material properties (opacity and color).
I had to specify the object name before each pointer: <object-name>.position.
Thank you Don McCurdy.
You need to set a name to your Object3D:
const mesh = new THREE.Mesh(geometry, material);
mesh.name = 'myMesh'; // <- set a name
scene.add(mesh);
When you create your KeyframeTrack use that object's name:
const positionKF = new THREE.VectorKeyframeTrack('myMesh.position', times, values); // <-- use that object's name

Display loaded OBJ model in wireframe mode in three.js

I wanted to display my loaded .obj file in wireframe mode..
I got to know about the WireFrameGeometry But for somereason the .mtl texture only gets display .
Below is the code ..
/* Model */
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setBaseUrl('assets/');
mtlLoader.setPath('assets/');
mtlLoader.load('materialfile.mtl', function(materials) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.setPath('assets/');
objLoader.load('Objectfile.obj', function(object) {
object.traverse(function(child) {
if (child.isMesh) {
var wireframeGeomtry = new THREE.WireframeGeometry(child.geometry);
var wireframeMaterial = new THREE.LineBasicMaterial({
color: 0xffffff
});
var wireframe = new THREE.LineSegments(wireframeGeomtry, wireframeMaterial);
child.add(wireframe);
}
});
scene.add(object);
});
});
I only want the wireframe of the model without any fill..
Thanks in advance.
The entire code is below...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="three.js"></script>
<script src="TrackballControls.js"></script>
<script src="cannon.js"></script>
<script src="Detector.js"></script>
<script src="OrbitControls.js"></script>
<script src="OBJLoader.js"></script>
<script src="MTLLoader.js"></script>
</head>
<body>
<script>
if (!Detector.webgl) {
Detector.addGetWebGLMessage();
}
var container;
var camera, controls, scene, renderer;
var lighting, ambient, keyLight, fillLight, backLight;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
/* Camera */
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 50;
/* Scene */
scene = new THREE.Scene();
lighting = false;
ambient = new THREE.AmbientLight(0xffffff, 1.0);
scene.add(ambient);
// keyLight = new THREE.DirectionalLight(new THREE.Color('hsl(30, 100%, 75%)'), 1.0);
// keyLight.position.set(-100, 0, 100);
// fillLight = new THREE.DirectionalLight(new THREE.Color('hsl(240, 100%, 75%)'), 0.75);
// fillLight.position.set(100, 0, 100);
// backLight = new THREE.DirectionalLight(0xffffff, 1.0);
// backLight.position.set(100, 0, -100).normalize();
/* Model */
// var mtlLoader = new THREE.MTLLoader();
// mtlLoader.setBaseUrl('assets/');
// mtlLoader.setPath('assets/');
// mtlLoader.load('mtlfile.mtl', function(materials) {
// materials.preload();
// materials.materials.default.map.magFilter = THREE.NearestFilter;
// materials.materials.default.map.minFilter = THREE.LinearFilter;
var objLoader = new THREE.OBJLoader();
// objLoader.setMaterials(materials);
objLoader.setPath('assets/');
objLoader.load('objectfile.obj', function(object) {
object.traverse(function(child) {
if (child.isMesh) {
var wireframeGeomtry = new THREE.WireframeGeometry(child.geometry);
var wireframeMaterial = new THREE.LineBasicMaterial({
color: 0xeeeeee
});
var wireframe = new THREE.LineSegments(wireframeGeomtry, wireframeMaterial);
// add to child so we get same orientation
child.add(wireframe);
// to parent of child. Using attach keeps our orietation
child.parent.attach(wireframe);
// remove child (we don't want child)
child.parent.remove(child);
}
});
scene.add(object);
});
// });
/* Renderer */
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(new THREE.Color("hsl(0, 0%, 10%)"));
container.appendChild(renderer.domElement);
/* Controls */
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = true;
controls.autoRotate = true;
/* Events */
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
controls.update();
render();
}
function render() {
renderer.render(scene, camera);
}
</script>
</body>
</html>
So this is the entire code..
Its just the basic obj loader ..
I don't know whether the problem is in the code or model .
It shows as a fully filled white model
object.traverse(function(child) {
if (child.isMesh) {
child.material.wireframe = true;
}
}
This worked for me
objLoader.load('Objectfile.obj', function(object) {
object.traverse(function(child) {
if (child.isMesh) {
var wireframeGeomtry = new THREE.WireframeGeometry(child.geometry);
var wireframeMaterial = new THREE.LineBasicMaterial({
color: 0xffffff
});
var wireframe = new THREE.LineSegments(wireframeGeomtry, wireframeMaterial);
// add to child so we get same orientation
child.add(wireframe);
// to parent of child. Using attach keeps our orietation
child.parent.attach(wireframe);
// remove child (we don't want child)
child.parent.remove(child);
}
});
scene.add(object);
});
Example:
html, body {
margin: 0;
height: 100%;
}
#c {
width: 100%;
height: 100%;
display: block;
}
<canvas id="c"></canvas>
<script type="module">
import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/build/three.module.js';
import {OrbitControls} from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/examples/jsm/controls/OrbitControls.js';
import {OBJLoader2} from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/examples/jsm/loaders/OBJLoader2.js';
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 45;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 100;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(0, 10, 20);
const controls = new OrbitControls(camera, canvas);
controls.target.set(0, 5, 0);
controls.update();
const scene = new THREE.Scene();
scene.background = new THREE.Color('black');
{
const objLoader = new OBJLoader2();
objLoader.load('https://threejsfundamentals.org/threejs/resources/models/windmill/windmill.obj', (root) => {
root.traverse(child => {
if (child.isMesh) {
var wireframeGeomtry = new THREE.WireframeGeometry(child.geometry);
var wireframeMaterial = new THREE.LineBasicMaterial({
color: 0xffffff
});
var wireframe = new THREE.LineSegments(wireframeGeomtry, wireframeMaterial);
child.add(wireframe);
child.parent.attach(wireframe);
child.parent.remove(child);
}
});
scene.add(root);
});
}
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render() {
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
</script>
You can also do it the way manthrax suggested except you need to check if child.material is an array or not, then for each material remove the map (so the texture is not used) and set emissive to some color (you might also want to set color to black)`.
html, body {
margin: 0;
height: 100%;
}
#c {
width: 100%;
height: 100%;
display: block;
}
<canvas id="c"></canvas>
<script type="module">
import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/build/three.module.js';
import {OrbitControls} from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/examples/jsm/controls/OrbitControls.js';
import {OBJLoader2} from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/examples/jsm/loaders/OBJLoader2.js';
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 45;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 100;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(0, 10, 20);
const controls = new OrbitControls(camera, canvas);
controls.target.set(0, 5, 0);
controls.update();
const scene = new THREE.Scene();
scene.background = new THREE.Color('black');
function makeWireframe(material) {
material.wireframe = true;
material.emissive.set('#0FF');
material.map = undefined;
}
{
const objLoader = new OBJLoader2();
objLoader.load('https://threejsfundamentals.org/threejs/resources/models/windmill/windmill.obj', (root) => {
root.traverse(child => {
if (child.isMesh) {
if (Array.isArray(child.material)) {
child.material.forEach(makeWireframe);
} else {
makeWireframe(child.material)
}
}
});
scene.add(root);
});
}
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render() {
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
</script>

three.js post processing maskpass with multiple renderpass never works

I am working towards this:
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
background-color: #000;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="../build/three.js"></script>
<script src="js/shaders/CopyShader.js"></script>
<script src="js/postprocessing/EffectComposer.js"></script>
<script src="js/postprocessing/ClearPass.js"></script>
<script src="js/postprocessing/ShaderPass.js"></script>
<script src="js/postprocessing/MaskPass.js"></script>
<script src="js/postprocessing/RenderPass.js"></script>
<script src="js/Detector.js"></script>
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var composer, renderer;
var box_mask, box_1, box_2;
init();
animate();
function init() {
var camera_mask = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1000 );
camera_mask.position.z = 6;
var camera_1 = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1000 );
camera_1.position.z = 6;
var camera_2 = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1000 );
camera_2.position.z = 6;
var scene_mask = new THREE.Scene();
var scene_1 = new THREE.Scene();
var scene_2 = new THREE.Scene();
scene_mask.background = new THREE.Color( 0x000000 );
scene_1.background = new THREE.Color( 0xffffff );
scene_2.background = new THREE.Color( 0x000000 );
var box_mask_1 = new THREE.CircleGeometry( 2, 4 );
var box_mask_2 = new THREE.CircleGeometry( 2, 4 );
var singleGeometry_mask = new THREE.Geometry();
var boxMesh_mask_1 = new THREE.Mesh(box_mask_1);
boxMesh_mask_1.position.z = 1;
var boxMesh_mask_2 = new THREE.Mesh(box_mask_2);
boxMesh_mask_2.rotation.y = Math.PI;
boxMesh_mask_2.position.z = -1;
boxMesh_mask_1.updateMatrix(); // as needed
singleGeometry_mask.merge(boxMesh_mask_1.geometry, boxMesh_mask_1.matrix);
boxMesh_mask_2.updateMatrix(); // as needed
singleGeometry_mask.merge(boxMesh_mask_2.geometry, boxMesh_mask_2.matrix);
var material_mask = new THREE.MeshBasicMaterial({color: 0xffffff});
box_mask = new THREE.Mesh(singleGeometry_mask, material_mask);
scene_mask.add( box_mask );
var box_1_1 = new THREE.CircleGeometry( 2, 4 );
var box_1_2 = new THREE.CircleGeometry( 2, 4 );
var singleGeometry_1 = new THREE.Geometry();
var boxMesh_1_1 = new THREE.Mesh(box_1_1);
boxMesh_1_1.position.z = -1;
var boxMesh_1_2 = new THREE.Mesh(box_1_2);
boxMesh_1_2.rotation.y = Math.PI;
boxMesh_1_2.position.z = 1;
boxMesh_1_1.updateMatrix();
singleGeometry_1.merge(boxMesh_1_1.geometry, boxMesh_1_1.matrix);
boxMesh_1_2.updateMatrix();
singleGeometry_1.merge(boxMesh_1_2.geometry, boxMesh_1_2.matrix);
var material_1 = new THREE.MeshBasicMaterial({color: 0x000000});
box_1 = new THREE.Mesh(singleGeometry_1, material_1);
scene_1.add( box_1 );
var box_2_1 = new THREE.CircleGeometry( 2, 4 );
var box_2_2 = new THREE.CircleGeometry( 2, 4 );
var singleGeometry_2 = new THREE.Geometry();
var boxMesh_2_1 = new THREE.Mesh(box_2_1);
boxMesh_2_1.position.z = -1;
var boxMesh_2_2 = new THREE.Mesh(box_2_2);
boxMesh_2_2.rotation.y = Math.PI;
boxMesh_2_2.position.z = 1;
boxMesh_2_1.updateMatrix();
singleGeometry_2.merge(boxMesh_2_1.geometry, boxMesh_2_1.matrix);
boxMesh_2_2.updateMatrix();
singleGeometry_2.merge(boxMesh_2_2.geometry, boxMesh_2_2.matrix);
var material_2 = new THREE.MeshBasicMaterial({color: 0xffffff});
box_2 = new THREE.Mesh(singleGeometry_2, material_2);
scene_2.add( box_2 );
renderer = new THREE.WebGLRenderer();
renderer.setClearColor( 0xffffff );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.autoClear = false;
document.body.appendChild( renderer.domElement );
var clearPass = new THREE.ClearPass();
var clearMaskPass = new THREE.ClearMaskPass();
var maskPass = new THREE.MaskPass( scene_mask, camera_mask );
var renderPass_1 = new THREE.RenderPass( scene_1, camera_1 );
var renderPass_2 = new THREE.RenderPass( scene_2, camera_2 );
var outputPass = new THREE.ShaderPass( THREE.CopyShader );
outputPass.renderToScreen = true;
var parameters = {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
format: THREE.RGBFormat,
stencilBuffer: true
};
var renderTarget = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, parameters );
composer = new THREE.EffectComposer( renderer , renderTarget );
composer.addPass( clearPass );
composer.addPass( renderPass_1 );
composer.addPass( maskPass );
composer.addPass( renderPass_2 );
composer.addPass( clearMaskPass );
composer.addPass( outputPass );
}
function animate() {
requestAnimationFrame( animate );
var time = performance.now() * 0.001 * 2;
box_mask.rotation.y = time;
box_1.rotation.y = time;
box_2.rotation.y = time;
renderer.clear();
composer.render( time );
}
</script>
</body>
</html>
this never works:
composer.addPass( clearPass );
composer.addPass( renderPass_1 );
composer.addPass( maskPass );
composer.addPass( renderPass_2 );
composer.addPass( clearMaskPass );
composer.addPass( outputPass );
if i switch out "renderPass_2" with a THREE.TexturePass it works, but it's not what I want.
Here is the codepen:
https://codepen.io/oxbits/pen/yEQLGK?editors=0010
Anyone able to combine two renderPasses with a mask?
Should I be using a different approach?
I finally got it to work! Though I'm not sure how...
Take a look:
https://codepen.io/anon/pen/PyJObz
One trick was not using a scene background in the 2nd render. Instead I had to create a background mesh.
Code below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
html, body, canvas {
margin: 0px;
overflow: hidden;
}
#fps {
position: absolute;
top: 0px;
left: 0px;
color: #fff;
z-index: 50;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="../build/three.js"></script>
<script src="js/shaders/CopyShader.js"></script>
<script src="js/postprocessing/EffectComposer.js"></script>
<script src="js/postprocessing/ClearPass.js"></script>
<script src="js/postprocessing/ShaderPass.js"></script>
<script src="js/postprocessing/MaskPass.js"></script>
<script src="js/postprocessing/RenderPass.js"></script>
<script src="js/Detector.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
// if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
let scene = null;
let normal = null;
let outline = null;
let outScene = null;
let maskScene = null;
let light = null;
let renderer = null;
let composer = null;
let camera1 = null;
let camera2 = null;
let camera3 = null;
let mesh1 = null;
let mesh2 = null;
let mesh3 = null;
let bg_mesh = null;
let renderTarget = null;
let screenWidth = window.innerWidth;
let screenHeight = window.innerHeight;
const clock = new THREE.Clock;
let elapsedTime = 0;
let frameCount = 0;
const init = function() {
// SCENE
scene = new THREE.Scene;
maskScene = new THREE.Scene;
outScene = new THREE.Scene;
setModel();
// SCENE CAMERA
camera1 = new THREE.PerspectiveCamera(40, screenWidth/screenHeight, 1, 1000);
camera1.position.set(0, 0, 10);
scene.add(camera1);
camera2 = new THREE.PerspectiveCamera(40, screenWidth/screenHeight, 1, 1000);
camera2.position.set(0, 0, 10);
outScene.add(camera2);
camera3 = new THREE.PerspectiveCamera(40, screenWidth/screenHeight, 1, 1000);
camera3.position.set(0, 0, 10);
maskScene.add(camera3);
scene.background = new THREE.Color( 0xffffff );
// RENDERER
renderer = new THREE.WebGLRenderer({
width: screenWidth,
height: screenHeight,
antialias: true
});
renderer.setSize(screenWidth, screenHeight);
renderer.setClearColor(0x000000);
renderer.autoClear = false;
renderer.gammaInput = true;
renderer.gammaOutput = true;
document.body.appendChild(renderer.domElement);
// POSTPROCESSING
const renderTargetParameters = {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
format: THREE.RGBAFormat,
stencilBuffer: true
};
renderTarget = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight, renderTargetParameters);
composer = new THREE.EffectComposer(renderer);
composer.renderTarget1.stencilBuffer = true;
composer.renderTarget2.stencilBuffer = true;
normal = new THREE.RenderPass(scene, camera1);
outline = new THREE.RenderPass(outScene, camera2);
outline.clear = false;
const mask = new THREE.MaskPass(maskScene, camera3);
mask.inverse = false;
const clearMask = new THREE.ClearMaskPass;
const copyPass = new THREE.ShaderPass(THREE.CopyShader);
copyPass.renderToScreen = true;
composer.addPass(normal);
composer.addPass(mask);
composer.addPass(outline);
composer.addPass(clearMask);
composer.addPass(copyPass);
// EVENTS
return window.addEventListener('resize', onWindowResize, false);
};
var setModel = function() {
var box_mask_1 = new THREE.CircleGeometry( 2, 4 );
var box_mask_2 = new THREE.CircleGeometry( 2, 4 );
var singleGeometry_mask = new THREE.Geometry();
var boxMesh_mask_1 = new THREE.Mesh(box_mask_1);
boxMesh_mask_1.position.z = 1;
var boxMesh_mask_2 = new THREE.Mesh(box_mask_2);
boxMesh_mask_2.rotation.y = Math.PI;
boxMesh_mask_2.position.z = -1;
boxMesh_mask_1.updateMatrix(); // as needed
singleGeometry_mask.merge(boxMesh_mask_1.geometry, boxMesh_mask_1.matrix);
boxMesh_mask_2.updateMatrix(); // as needed
singleGeometry_mask.merge(boxMesh_mask_2.geometry, boxMesh_mask_2.matrix);
var box_1_1 = new THREE.CircleGeometry( 2, 4 );
var box_1_2 = new THREE.CircleGeometry( 2, 4 );
var singleGeometry_1 = new THREE.Geometry();
var boxMesh_1_1 = new THREE.Mesh(box_1_1);
boxMesh_1_1.position.z = -1;
var boxMesh_1_2 = new THREE.Mesh(box_1_2);
boxMesh_1_2.rotation.y = Math.PI;
boxMesh_1_2.position.z = 1;
boxMesh_1_1.updateMatrix();
singleGeometry_1.merge(boxMesh_1_1.geometry, boxMesh_1_1.matrix);
boxMesh_1_2.updateMatrix();
singleGeometry_1.merge(boxMesh_1_2.geometry, boxMesh_1_2.matrix);
var box_2_1 = new THREE.CircleGeometry( 2, 4 );
var box_2_2 = new THREE.CircleGeometry( 2, 4 );
var singleGeometry_2 = new THREE.Geometry();
var boxMesh_2_1 = new THREE.Mesh(box_2_1);
boxMesh_2_1.position.z = -1;
var boxMesh_2_2 = new THREE.Mesh(box_2_2);
boxMesh_2_2.rotation.y = Math.PI;
boxMesh_2_2.position.z = 1;
boxMesh_2_1.updateMatrix();
singleGeometry_2.merge(boxMesh_2_1.geometry, boxMesh_2_1.matrix);
boxMesh_2_2.updateMatrix();
singleGeometry_2.merge(boxMesh_2_2.geometry, boxMesh_2_2.matrix);
const matColor = new THREE.MeshBasicMaterial({
color: 0x000000});
mesh1 = new THREE.Mesh(singleGeometry_1, matColor); // geometry, matColor);
scene.add(mesh1);
// flat mask
const matFlat = new THREE.MeshBasicMaterial({
color: 0x000000});
mesh2 = new THREE.Mesh(singleGeometry_mask, matFlat);
maskScene.add(mesh2);
const matColor2 = new THREE.MeshBasicMaterial({
color: 0xffffff});
mesh3 = new THREE.Mesh(singleGeometry_2, matColor2);
outScene.add(mesh3);
const matColor3 = new THREE.MeshBasicMaterial({
color: 0x000000});
bg_mesh = new THREE.Mesh(new THREE.CircleGeometry( 100, 4 ), matColor3);
outScene.add(bg_mesh);
bg_mesh.position.set(0, 0, -10);
};
var onWindowResize = function() {
screenWidth = window.innerWidth;
screenHeight = window.innerHeight;
camera1.aspect = screenWidth / screenHeight;
camera2.aspect = camera1.aspect;
camera3.aspect = camera1.aspect;
camera1.updateProjectionMatrix();
camera2.updateProjectionMatrix();
camera3.updateProjectionMatrix();
return renderer.setSize(screenWidth, screenHeight);
};
var animate = function() {
updateFps();
requestAnimationFrame(animate);
return render();
};
var render = function() {
const now = Date.now();
const delta = clock.getDelta();
if (mesh1) {
mesh1.rotation.y += 0.015;
mesh2.rotation.y = mesh1.rotation.y;
mesh3.rotation.y = mesh1.rotation.y;
}
return composer.render();
};
var updateFps = function() {
elapsedTime += clock.getDelta();
frameCount++;
if (elapsedTime >= 1) {
$('#fps').html(frameCount);
frameCount = 0;
return elapsedTime = 0;
}
};
init();
animate();
</script>
</body>
</html>
Just chiming in because I don't know the specifics of your situation but I have used the composer before...
What if you just add the texturePass after the maskPass and leave the renderPass1 as the next one after that?
The composer works by applying operations through a succession of buffers, so in between operations you sometimes have to do a texturePass to copy the current output back to the input for the next pass...
But this is just a guess, in case nobody else answers....

three.js r88 meshdepthmaterial there is no effect

I'm a new three.js men, and below is my code snippet...
In three.js docs said that the MeshDepthMaterial is drawing geometry by depth. Depth is based off of the camera near and far plane. White is nearest, black is farthest. But in my case, there is no effect for three.js r88, but three.js r 67. Can anybody please tell me why? Thanks very much...
<!DOCTYPE html>
<html>
<head>
<title>示例 04.02 - MeshDepthMaterial</title>
<script src="../build/three.js"></script>
<script src="../build/js/controls/OrbitControls.js"></script>
<script src="../build/js/libs/stats.min.js"></script>
<script src="../build/js/libs/dat.gui.min.js"></script>
<script src="../build/js/renderers/CanvasRenderer.js"></script>
<script src="../build/js/renderers/Projector.js"></script>
<script src="../jquery/jquery-3.2.1.min.js"></script>
<style>
body {
/* 设置 margin 为 0,并且 overflow 为 hidden,来完成页面样式 */
margin: 0;
overflow: hidden;
}
/* 统计对象的样式 */
#Stats-output {
position: absolute;
left: 0px;
top: 0px;
}
</style>
</head>
<body>
<!-- 用于 WebGL 输出的 Div -->
<div id="webgl-output"></div>
<!-- 用于统计 FPS 输出的 Div -->
<div id="stats-output"></div>
<!-- 运行 Three.js 示例的 Javascript 代码 -->
<script type="text/javascript">
var scene;
var camera;
var render;
var webglRender;
var canvasRender;
var controls;
var stats;
var guiParams;
var ground;
var cube;
var plane;
var sphere;
var meshMaterial;
var ambientLight;
var spotLight;
$(function() {
stats = initStats();
scene = new THREE.Scene();
scene.overrideMaterial = new THREE.MeshDepthMaterial({
morphTargets: true
});
webglRender = new THREE.WebGLRenderer( {antialias: true, alpha: true, logarithmicDepthBuffer: true} ); // antialias 抗锯齿
webglRender.setSize(window.innerWidth, window.innerHeight);
webglRender.setClearColor(0x000000, 1.0);
webglRender.shadowMap.enabled = true; // 允许阴影投射
render = webglRender;
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000); // 2147483647
camera.position.set(-50, 40, 50);
var target = new THREE.Vector3(0, 0 , 0);
controls = new THREE.OrbitControls(camera, render.domElement);
controls.target = target;
camera.lookAt(target);
$('#webgl-output')[0].appendChild(render.domElement);
window.addEventListener('resize', onWindowResize, false);
ambientLight = new THREE.AmbientLight(0x000000);
scene.add(ambientLight);
/** 用来保存那些需要修改的变量 */
guiParams = new function() {
this.rotationSpeed = 0.02;
this.near = 2;
this.far = 50;
this.addCube = function() {
for (var i=0; i<100; i++) {
// 定义 cube 几何
var cubeGeometry = new THREE.BoxGeometry(5, 5, 5);
// 定义网格材质
meshMaterial = new THREE.MeshLambertMaterial({color: Math.random() * 0xffffff});
// 定义 cube 网格
cube = new THREE.Mesh(cubeGeometry, meshMaterial);
cube.castShadow = true;
cube.position.x = -60 + Math.round((Math.random() * 100));
cube.position.y = Math.round((Math.random() * 10));
cube.position.z = -100 + Math.round((Math.random() * 150));
// 默认加入 cube
scene.add(cube);
}
};
}
/** 定义 dat.GUI 对象,并绑定 guiParams 的几个属性 */
var gui = new dat.GUI();
gui.add(guiParams, 'addCube');
gui.add(guiParams, 'near', 0, 50).onChange(function(e) {
camera.near = e;
});
gui.add(guiParams, 'far', 5, 200).onChange(function(e) {
camera.far = e;
});
guiParams.addCube();
renderScene();
});
/** 渲染场景 */
function renderScene() {
stats.update();
rotateMesh(); // 旋转物体
requestAnimationFrame(renderScene);
render.render(scene, camera);
}
/** 初始化 stats 统计对象 */
function initStats() {
stats = new Stats();
stats.setMode(0); // 0 为监测 FPS;1 为监测渲染时间
$('#stats-output').append(stats.domElement);
return stats;
}
/** 当浏览器窗口大小变化时触发 */
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
render.setSize(window.innerWidth, window.innerHeight);
}
/** 旋转物体 */
function rotateMesh() {
scene.traverse(function(mesh) {
if (mesh instanceof THREE.Mesh) {
mesh.rotation.x += guiParams.rotationSpeed;
mesh.rotation.y += guiParams.rotationSpeed;
mesh.rotation.z += guiParams.rotationSpeed;
}
});
}
</script>
</body>
</html>
When you change camera.near or camera.far you need to call:
camera.updateProjectionMatrix();
three.js r.88

Pan is the only working thing for OrbitControls

I am trying to program a solar system that you can orbit around and pan so I added an OrbitControls to my project and pan is working fine but for some reason rotate and zoom aren't working. I have tried copying other people's examples and I cannot figure out what is wrong with mine. I don't know if it could just be my computer, but I have no reason to believe that it would be.
<!DOCTYPE html>
<html>
<head>
<title>Example 01.02 - First Scene</title>
<script type="text/javascript" src="../libs/three.js"></script>
<script type="text/javascript" src="../libs/jquery-1.9.0.js"></script>
<script type="text/javascript" src="../libs/stats.js"></script>
<script type="text/javascript" src="../libs/dat.gui.js"></script>
<script type="text/javascript" src="../libs/OrbitControls.js"></script>
<script type="text/javascript" src="../libs/chroma.js"></script>
<script type="text/javascript" src="../libs/dat.gui.js"></script>
<style>
body{
/* set margin to 0 and overflow to hidden, to go fullscreen */
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="Stats-output">
</div>
<!-- Div which will hold the Output -->
<div id="WebGL-output">
</div>
<!-- Javascript code that runs our Three.js examples -->
<script type="text/javascript">
// once everything is loaded, we run our Three.js stuff.
$(function () {
var stats = initStats();
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
var clock = new THREE.Clock();
// create a scene, that will hold all our elements such as objects, cameras and lights.
var scene = new THREE.Scene();
// create a camera, which defines where we're looking at.
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 5000);
// position and point the camera to the center of the scene
camera.position.x = -150;
camera.position.y = 200;
camera.position.z = 150;
camera.lookAt(scene.position);
// create a render and set the size
renderer = new THREE.WebGLRenderer( {antialias:true} );
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
ccontrols = new THREE.OrbitControls( camera, renderer.domElement );
ccontrols.damping = 0.2;
ccontrols.addEventListener( 'change', render );
var ambiLight = new THREE.AmbientLight(0x747474)
scene.add(ambiLight);
var pointLight = new THREE.PointLight(0xffffff);
pointLight.position.set(0, 0, 0);
pointLight.distance = 100;
scene.add(pointLight);
//create the light box
var lightboxgeom = new THREE.SphereGeometry(3000,50,50);
var lightboxmat = new THREE.MeshPhongMaterial({map: THREE.ImageUtils.loadTexture("./TexturesAndModels/lightbox.png"), side: THREE.BackSide});
var lightbox = new THREE.Mesh(lightboxgeom, lightboxmat);
//sun and glow
var sun = createMesh(new THREE.SphereGeometry(20, 20, 20), "texture_sun.jpg", "texture_sun_DISP.jpg", "texture_sun_SPEC.jpg");
sun.shading = THREE.NoShading;
var spriteMaterial = new THREE.SpriteMaterial(
{
map: new THREE.ImageUtils.loadTexture( "TexturesAndModels/GLOW.png" ),
useScreenCoordinates: false, alignment: THREE.SpriteAlignment.center,
color: 0xffcc00, transparent: false, blending: THREE.AdditiveBlending
});
var sprite = new THREE.Sprite( spriteMaterial );
sprite.scale.set(100, 100, 1.0);
sun.add(sprite);
//mercury
var mercury = createMesh(new THREE.SphereGeometry(1.50, 20, 20), "texture_mercury.jpg", "texture_mercury_DISP.jpg", "texture_mercury_SPEC.jpg", "texture_mercury_NRM.jpg");
//venus
var venus = createMesh(new THREE.SphereGeometry(3.80, 20, 20), "texture_venus_surface.jpg", "texture_venus_surface_DISP.jpg", "texture_venus_surface_SPEC.jpg", "texture_venus_surface_NRM.jpg");
//earth and clouds
var earth = createMesh(new THREE.SphereGeometry(4.00, 20, 20), "ColorMap.jpg", "Bump2.jpg", "SpecMask2.png", "ColorMap_NRM.jpg");
//mars
var mars = createMesh(new THREE.SphereGeometry(2.10, 20, 20), "texture_mars.jpg", "texture_mars_DISP.jpg", "texture_mars_SPEC.jpg", "texture_mars_NRM.jpg");
//Jupiter
var jupiter = createMesh(new THREE.SphereGeometry(18.7, 20, 20), "texture_jupiter.jpg", "texture_jupiter_DISP.jpg", "texture_jupiter_SPEC.jpg", "texture_jupiter_NRM.jpg");
//saturn
var saturn = createMesh(new THREE.SphereGeometry(18, 20, 20), "texture_saturn.jpg", "texture_saturn_DISP.jpg", "texture_saturn_SPEC.jpg", "texture_saturn_NRM.jpg");
//uranus
var uranus = createMesh(new THREE.SphereGeometry(15, 20, 20), "texture_uranus.jpg", "texture_uranus_DISP.jpg", "texture_uranus_SPEC.jpg", "texture_uranus_NRM.jpg");
//neptune
var neptune = createMesh(new THREE.SphereGeometry(14, 20, 20), "texture_neptune.jpg", "texture_neptune_DISP.jpg", "texture_neptune_SPEC.jpg", "texture_neptune_NRM.jpg");
// position the planets
sun.position.x=0;
sun.position.y=0;
sun.position.z=0;
earth.position.y=0;
mars.position.y=0;
venus.position.y=0;
mercury.position.y=0;
saturn.position.y=0;
jupiter.position.y=0;
uranus.position.y=0;
neptune.position.y=0;
// add the planets to the scene
scene.add(lightbox);
scene.add(earth);
scene.add(sun);
scene.add(mercury);
scene.add(venus);
scene.add(mars);
scene.add(jupiter);
scene.add(saturn);
scene.add(uranus);
scene.add(saturn);
// add the output of the renderer to the html element
$("#WebGL-output").append(renderer.domElement);
var r = 0;
var step = 0;
var controls = new function() {
this.timeScale = 1;
}
var gui = new dat.GUI();
gui.add(controls, 'timeScale', 0, 10);
// render the scene
render();
function createMesh(geom, imageFile, bump, spec, normal) {
var texture = THREE.ImageUtils.loadTexture("./TexturesAndModels/" + imageFile)
var mat = new THREE.MeshPhongMaterial();
mat.map = texture;
if (bump) {
var bump = THREE.ImageUtils.loadTexture("./TexturesAndModels/" + bump)
mat.bumpMap = bump;
mat.bumpScale = 0.2;
}
if(spec) {
var spec = THREE.ImageUtils.loadTexture("./TexturesandModels/" + spec)
mat.specularMap = spec;
}
if(normal) {
var norm = THREE.ImageUtils.loadTexture("./TexturesAndModels/" + normal)
mat.normalMap = norm;
}
var mesh = new THREE.Mesh(geom, mat);
return mesh;
}
function render() {
stats.update();
earth.position.x = Math.sin(r*0.1)*150;
earth.position.z = Math.cos(r*0.1)*150;
earth.rotation.y = step += controls.timeScale * 0.02;
mercury.position.x = Math.sin(r*0.4)*58;
mercury.position.z = Math.cos(r*0.4)*58;
mercury.rotation.y = step/58.7;
venus.position.x = Math.sin(r*0.1625)*108;
venus.position.z = Math.cos(r*0.1625)*108;
venus.rotation.y = step/243;
mars.position.x = Math.sin(r*0.05)*228;
mars.position.z = Math.cos(r*0.05)*228;
mars.rotation.y = step*1.026;
jupiter.position.x = Math.sin(r*.008)*483;
jupiter.position.z = Math.cos(r*.008)*483;
jupiter.rotation.y = step*2.44;
saturn.position.x = Math.sin(r*.003)*886;
saturn.position.z = Math.cos(r*.003)*886;
saturn.rotation.y = step*2.35;
uranus.position.x = Math.sin(r*.001)*1784;
uranus.position.z = Math.cos(r*.001)*1784;
uranus.rotation.y = step*1.34;
neptune.position.x = Math.sin(r*.0006)*2794;
neptune.position.z = Math.cos(r*.0006)*2794;
neptune.rotation.y = step*1.26;
r+=controls.timeScale * (Math.PI/180*2);
renderer.render(scene, camera);
requestAnimationFrame(render);
}
function initStats() {
var stats = new Stats();
stats.setMode(0); // 0: fps, 1: ms
// Align top-left
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
$("#Stats-output").append(stats.domElement);
return stats;
}
});
</script>
</body>
</html>

Resources