Why is this threejs sphere not working on mobile? - javascript

I have this 3d sphere like halfway done. Its just working pretty slow on desktop, and doesnt even run on mobile. Could one of you guys take a look, and let me know what im doing wrong.
heres the threejs code
window.log = function()
{
if (this.console)
{
console.log(Array.prototype.slice.call(arguments));
}
};
// Namespace
var Defmech = Defmech ||
{};
Defmech.RotationWithQuaternion = (function()
{
'use_strict';
var container;
var camera, scene, renderer;
var sphere;
var mouseDown = false;
var rotateStartPoint = new THREE.Vector3(0, 0, 1);
var rotateEndPoint = new THREE.Vector3(0, 0, 1);
var curQuaternion;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var rotationSpeed = 2;
var lastMoveTimestamp,
moveReleaseTimeDelta = 50;
var startPoint = {
x: 0,
y: 0
};
var deltaX = 0,
deltaY = 0;
var setup = function()
{
container = document.createElement('div');
document.body.appendChild(container);
var info = document.createElement('div');
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
info.innerHTML = 'Pick you favorite color';
container.appendChild(info);
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.y = 150;
camera.position.z = 500;
scene = new THREE.Scene();
// Cube
var sphereGeometry = new THREE.SphereGeometry(200, 200, 200);
var material = new THREE.MeshPhongMaterial();
material.map = THREE.ImageUtils.loadTexture('/color.jpg');
sphere = new THREE.Mesh(sphereGeometry, material);
sphere.position.y = 100;
scene.add(sphere);
renderer = new THREE.CanvasRenderer();
renderer.setClearColor(0xf0f0f0);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener('mousedown', onDocumentMouseDown, false);
window.addEventListener('resize', onWindowResize, false);
animate();
};
function onWindowResize()
{
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseDown(event)
{
event.preventDefault();
document.addEventListener('mousemove', onDocumentMouseMove, false);
document.addEventListener('mouseup', onDocumentMouseUp, false);
mouseDown = true;
startPoint = {
x: event.clientX,
y: event.clientY
};
rotateStartPoint = rotateEndPoint = projectOnTrackball(0, 0);
}
function onDocumentMouseMove(event)
{
deltaX = event.x - startPoint.x;
deltaY = event.y - startPoint.y;
handleRotation();
startPoint.x = event.x;
startPoint.y = event.y;
lastMoveTimestamp = new Date();
}
function onDocumentMouseUp(event)
{
if (new Date().getTime() - lastMoveTimestamp.getTime() > moveReleaseTimeDelta)
{
deltaX = event.x - startPoint.x;
deltaY = event.y - startPoint.y;
}
mouseDown = false;
document.removeEventListener('mousemove', onDocumentMouseMove, false);
document.removeEventListener('mouseup', onDocumentMouseUp, false);
}
function projectOnTrackball(touchX, touchY)
{
var mouseOnBall = new THREE.Vector3();
mouseOnBall.set(
clamp(touchX / windowHalfX, -1, 1), clamp(-touchY / windowHalfY, -1, 1),
0.0
);
var length = mouseOnBall.length();
if (length > 1.0)
{
mouseOnBall.normalize();
}
else
{
mouseOnBall.z = Math.sqrt(1.0 - length * length);
}
return mouseOnBall;
}
function rotateMatrix(rotateStart, rotateEnd)
{
var axis = new THREE.Vector3(),
quaternion = new THREE.Quaternion();
var angle = Math.acos(rotateStart.dot(rotateEnd) / rotateStart.length() / rotateEnd.length());
if (angle)
{
axis.crossVectors(rotateStart, rotateEnd).normalize();
angle *= rotationSpeed;
quaternion.setFromAxisAngle(axis, angle);
}
return quaternion;
}
function clamp(value, min, max)
{
return Math.min(Math.max(value, min), max);
}
function animate()
{
requestAnimationFrame(animate);
render();
}
function render()
{
if (!mouseDown)
{
var drag = 0.95;
var minDelta = 0.05;
if (deltaX < -minDelta || deltaX > minDelta)
{
deltaX *= drag;
}
else
{
deltaX = 0;
}
if (deltaY < -minDelta || deltaY > minDelta)
{
deltaY *= drag;
}
else
{
deltaY = 0;
}
handleRotation();
}
renderer.render(scene, camera);
}
var handleRotation = function()
{
rotateEndPoint = projectOnTrackball(deltaX, deltaY);
var rotateQuaternion = rotateMatrix(rotateStartPoint, rotateEndPoint);
curQuaternion = sphere.quaternion;
curQuaternion.multiplyQuaternions(rotateQuaternion, curQuaternion);
curQuaternion.normalize();
sphere.setRotationFromQuaternion(curQuaternion);
rotateEndPoint = rotateStartPoint;
};
// PUBLIC INTERFACE
return {
init: function()
{
setup();
}
};
})();
document.onreadystatechange = function()
{
if (document.readyState === 'complete')
{
Defmech.RotationWithQuaternion.init();
}
};
heres a running demo (only works on desktop)
http://wander.ventures/sphere.html
everything works as it should on desktop, although its a bit slow, but on mobile safari, i wasnt even able to move the sphere.

Related

Three.js: How to change "diffuseMap" and "roughnessMap" to "cubeMap"?

This is the code I would like to work with:
var container;
var camera, scene, renderer;
let exrCubeRenderTarget, exrBackground;
let newEnvMap;
let torusMesh, planeMesh;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var object;
init();
animate();
function init() {
container = document.createElement("div");
container.className = "object";
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
1,
2000
);
camera.position.z = 250;
// scene
scene = new THREE.Scene();
scene.add(camera);
// manager
function loadModel() {
THREE.DefaultLoadingManager.onLoad = function() {
pmremGenerator.dispose();
};
// -----------------
function loadObjectAndAndEnvMap() {
const textureLoader = new THREE.TextureLoader();
const diffuseMap = textureLoader.load('https://threejs.org/examples/textures/brick_diffuse.jpg');
const roughnessMap = textureLoader.load('https://threejs.org/examples/textures/brick_roughness.jpg');
object.traverse(function(child) {
//This allow us to check if the children is an instance of the Mesh constructor
if (child instanceof THREE.Mesh) {
child.material = new THREE.MeshStandardMaterial({
color: "#555",
roughness: 1.0,
metalness: 0.5,
envMapIntensity: 5.0
});
child.material.envMap = newEnvMap;
child.material.map = diffuseMap;
child.material.roughnessMap = roughnessMap;
child.material.needsUpdate = true;
//Sometimes there are some vertex normals missing in the .obj files, ThreeJs will compute them
}
});
object.position.y = -90;
scene.add(object);
}
const pmremGenerator = new THREE.PMREMGenerator(renderer);
pmremGenerator.compileEquirectangularShader();
new THREE.EXRLoader()
.setDataType(THREE.UnsignedByteType)
.load(
"https://threejs.org/examples/textures/piz_compressed.exr",
function(texture) {
exrCubeRenderTarget = pmremGenerator.fromEquirectangular(texture);
exrBackground = exrCubeRenderTarget.texture;
newEnvMap = exrCubeRenderTarget ? exrCubeRenderTarget.texture : null;
loadObjectAndAndEnvMap(); // Add envmap once the texture has been loaded
texture.dispose();
}
);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.outputEncoding = THREE.sRGBEncoding;
}
var manager = new THREE.LoadingManager(loadModel);
manager.onProgress = function(item, loaded, total) {
console.log(item, loaded, total);
};
var loader = new THREE.OBJLoader(manager);
loader.load(
"https://threejs.org/examples/models/obj/female02/female02.obj",
function(obj) {
object = obj;
}
);
//
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener("mousemove", onDocumentMouseMove, false);
//
window.addEventListener("resize", onWindowResize, false);
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX) / 2;
mouseY = (event.clientY - windowHalfY) / 2;
}
//
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
camera.position.x += (mouseX - camera.position.x) * 0.05;
camera.position.y += (-mouseY - camera.position.y) * 0.05;
camera.lookAt(scene.position);
scene.background = exrBackground;
renderer.toneMappingExposure = 1.0;
renderer.render(scene, camera);
}
body {
margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three#0.125.2/build/three.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.125.2/examples/js/loaders/OBJLoader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.125.2/examples/js/loaders/EXRLoader.js"></script>
Instead of the existing material, I would like to have a metallic material like here.
For this, I have tried to delete diffuseMap and roughnessMap, and add cubeMap.
That's my not working result:
var container;
var camera, scene, renderer;
let newEnvMap;
let torusMesh, planeMesh;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var object;
init();
animate();
function init() {
container = document.createElement("div");
container.className = "object";
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
1,
2000
);
camera.position.z = 250;
// scene
scene = new THREE.Scene();
scene.add(camera);
// manager
function loadModel() {
THREE.DefaultLoadingManager.onLoad = function() {
pmremGenerator.dispose();
};
// -----------------
function loadObjectAndAndEnvMap() {
const textureLoader = new THREE.TextureLoader();
textureLoader.load('https://threejs.org/examples/textures/2294472375_24a3b8ef46_o.jpg', function(texture) {
texture.encoding = THREE.sRGBEncoding;
texture.mapping = THREE.EquirectangularReflectionMapping;
init(texture);
animate();
});
object.traverse(function(child) {
//This allow us to check if the children is an instance of the Mesh constructor
if (child instanceof THREE.Mesh) {
child.material = new THREE.MeshStandardMaterial({
color: "#555",
roughness: 1.0,
metalness: 0.5,
envMapIntensity: 5.0
});
child.material.envMap = newEnvMap;
child.material.needsUpdate = true;
//Sometimes there are some vertex normals missing in the .obj files, ThreeJs will compute them
}
});
object.position.y = -90;
scene.add(object);
}
const pmremGenerator = new THREE.PMREMGenerator(renderer);
pmremGenerator.compileEquirectangularShader();
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.outputEncoding = THREE.sRGBEncoding;
}
var manager = new THREE.LoadingManager(loadModel);
manager.onProgress = function(item, loaded, total) {
console.log(item, loaded, total);
};
var loader = new THREE.OBJLoader(manager);
loader.load(
"https://threejs.org/examples/models/obj/female02/female02.obj",
function(obj) {
object = obj;
}
);
//
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener("mousemove", onDocumentMouseMove, false);
//
window.addEventListener("resize", onWindowResize, false);
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX) / 2;
mouseY = (event.clientY - windowHalfY) / 2;
}
//
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
camera.position.x += (mouseX - camera.position.x) * 0.05;
camera.position.y += (-mouseY - camera.position.y) * 0.05;
camera.lookAt(scene.position);
renderer.toneMappingExposure = 1.0;
renderer.render(scene, camera);
}
body {
margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three#0.125.2/build/three.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.125.2/examples/js/loaders/OBJLoader.js"></script>
The background should be transparent in the end, only the OBJ object should be visible.
Could somebody help me please? Would be soooo happy about it!
There's not much you need to change to make it metallic:
child.material = new THREE.MeshStandardMaterial({
color: "#555",
roughness: 0.0, // <- roughness 0
metalness: 1.0, // <- metalness 1
envMapIntensity: 1.0
});
child.material.envMap = newEnvMap;
// Then you only need the envMap, remove the other stuff
//child.material.map = diffuseMap;
//child.material.roughnessMap = roughnessMap;
//child.material.needsUpdate = true;
And finally, if you don't want the background, remove it from the Render loop:
//scene.background = exrBackground;
Live demo:
var container;
var camera, scene, renderer;
let exrCubeRenderTarget, exrBackground;
let newEnvMap;
let torusMesh, planeMesh;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var object;
init();
animate();
function init() {
container = document.createElement("div");
container.className = "object";
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
1,
2000
);
camera.position.z = 250;
// scene
scene = new THREE.Scene();
scene.add(camera);
// manager
function loadModel() {
THREE.DefaultLoadingManager.onLoad = function() {
pmremGenerator.dispose();
};
// -----------------
function loadObjectAndAndEnvMap() {
const textureLoader = new THREE.TextureLoader();
const diffuseMap = textureLoader.load('https://threejs.org/examples/textures/brick_diffuse.jpg');
const roughnessMap = textureLoader.load('https://threejs.org/examples/textures/brick_roughness.jpg');
object.traverse(function(child) {
//This allow us to check if the children is an instance of the Mesh constructor
if (child instanceof THREE.Mesh) {
child.material = new THREE.MeshStandardMaterial({
color: "#555",
roughness: 0.0,
metalness: 1.0,
envMapIntensity: 5.0
});
child.material.envMap = newEnvMap;
//child.material.map = diffuseMap;
//child.material.roughnessMap = roughnessMap;
//child.material.needsUpdate = true;
//Sometimes there are some vertex normals missing in the .obj files, ThreeJs will compute them
}
});
object.position.y = -90;
scene.add(object);
}
const pmremGenerator = new THREE.PMREMGenerator(renderer);
pmremGenerator.compileEquirectangularShader();
new THREE.EXRLoader()
.setDataType(THREE.UnsignedByteType)
.load(
"https://threejs.org/examples/textures/piz_compressed.exr",
function(texture) {
exrCubeRenderTarget = pmremGenerator.fromEquirectangular(texture);
exrBackground = exrCubeRenderTarget.texture;
newEnvMap = exrCubeRenderTarget ? exrCubeRenderTarget.texture : null;
loadObjectAndAndEnvMap(); // Add envmap once the texture has been loaded
texture.dispose();
}
);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.outputEncoding = THREE.sRGBEncoding;
}
var manager = new THREE.LoadingManager(loadModel);
manager.onProgress = function(item, loaded, total) {
console.log(item, loaded, total);
};
var loader = new THREE.OBJLoader(manager);
loader.load(
"https://threejs.org/examples/models/obj/female02/female02.obj",
function(obj) {
object = obj;
}
);
//
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener("mousemove", onDocumentMouseMove, false);
//
window.addEventListener("resize", onWindowResize, false);
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX) / 2;
mouseY = (event.clientY - windowHalfY) / 2;
}
//
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
camera.position.x += (mouseX - camera.position.x) * 0.05;
camera.position.y += (-mouseY - camera.position.y) * 0.05;
camera.lookAt(scene.position);
//scene.background = exrBackground;
renderer.toneMappingExposure = 1.0;
renderer.render(scene, camera);
}
body {
margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three#0.125.2/build/three.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.125.2/examples/js/loaders/OBJLoader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.125.2/examples/js/loaders/EXRLoader.js"></script>

How to add map and roughnessMap in ThreeJS?

This is the code I am working with:
* {
margin: 0;
padding: 0;
}
.object {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
pointer-events: none;
background-color: rgb(200, 200, 200);
}
<script type="module">
import * as THREE from "https://threejs.org/build/three.module.js";
import { OBJLoader } from "https://threejs.org/examples/jsm/loaders/OBJLoader.js";
import { EXRLoader } from "https://threejs.org/examples/jsm/loaders/EXRLoader.js";
var container;
var camera, scene, renderer;
let exrCubeRenderTarget, exrBackground;
let newEnvMap;
let torusMesh, planeMesh;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var object;
init();
animate();
function init() {
container = document.createElement("div");
container.className = "object";
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
1,
2000
);
camera.position.z = 250;
// scene
scene = new THREE.Scene();
/*var ambientLight = new THREE.AmbientLight(0xcccccc, 0.4);
scene.add(ambientLight);
var pointLight = new THREE.PointLight(0xffffff, 2);
pointLight.position.set(100, 100, 50);
camera.add(pointLight);*/
scene.add(camera);
// manager
function loadModel() {
THREE.DefaultLoadingManager.onLoad = function () {
pmremGenerator.dispose();
};
// -----------------
function loadObjectAndAndEnvMap() {
object.traverse(function (child) {
//This allow us to check if the children is an instance of the Mesh constructor
if (child instanceof THREE.Mesh) {
child.material = new THREE.MeshStandardMaterial({
color: "#555",
roughness: 0.0,
metalness: 2.0,
envMapIntensity: 5.0
});
//child.material.flatShading = false;
console.log("setting envmap");
child.material.envMap = newEnvMap;
child.material.needsUpdate = true;
//Sometimes there are some vertex normals missing in the .obj files, ThreeJs will compute them
}
});
object.position.y = -90;
scene.add(object);
}
const pmremGenerator = new THREE.PMREMGenerator(renderer);
pmremGenerator.compileEquirectangularShader();
new EXRLoader()
.setDataType(THREE.UnsignedByteType)
.load(
"https://threejs.org/examples/textures/piz_compressed.exr",
function (texture) {
exrCubeRenderTarget = pmremGenerator.fromEquirectangular(texture);
exrBackground = exrCubeRenderTarget.texture;
newEnvMap = exrCubeRenderTarget ? exrCubeRenderTarget.texture : null;
loadObjectAndAndEnvMap(); // Add envmap once the texture has been loaded
texture.dispose();
}
);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.outputEncoding = THREE.sRGBEncoding;
}
var manager = new THREE.LoadingManager(loadModel);
manager.onProgress = function (item, loaded, total) {
console.log(item, loaded, total);
};
// model
function onProgress(xhr) {
if (xhr.lengthComputable) {
var percentComplete = (xhr.loaded / xhr.total) * 100;
console.log("model " + Math.round(percentComplete, 2) + "% downloaded");
}
}
function onError() {}
var loader = new OBJLoader(manager);
loader.load(
"https://threejs.org/examples/models/obj/female02/female02.obj",
function (obj) {
object = obj;
},
onProgress,
onError
);
//
renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener("mousemove", onDocumentMouseMove, false);
//
window.addEventListener("resize", onWindowResize, false);
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX) / 2;
mouseY = (event.clientY - windowHalfY) / 2;
}
//
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
camera.position.x += (mouseX - camera.position.x) * 0.05;
camera.position.y += (-mouseY - camera.position.y) * 0.05;
camera.lookAt(scene.position);
scene.background = exrBackground;
renderer.toneMappingExposure = 1.0;
renderer.render(scene, camera);
}
</script>
Now I want to add map and roughnessMap like here: https://threejs.org/docs/scenes/material-browser.html#MeshStandardMaterial
I thought I just should add the following:
const textureLoader = new THREE.TextureLoader();
const diffuseMaps = (function() {
const bricks = textureLoader.load('https://threejs.org/examples/textures/brick_diffuse.jpg');
bricks.wrapS = RepeatWrapping;
bricks.wrapT = RepeatWrapping;
bricks.repeat.set(9, 1);
return {
none: null,
bricks: bricks
};
})();
const roughnessMaps = (function() {
const bricks = textureLoader.load('https://threejs.org/examples/textures/brick_roughness.jpg');
bricks.wrapT = RepeatWrapping;
bricks.wrapS = RepeatWrapping;
bricks.repeat.set(9, 1);
return {
none: null,
bricks: bricks
};
})();
function loadObjectAndAndEnvMap() {
object.traverse(function(child) {
//This allow us to check if the children is an instance of the Mesh constructor
if (child instanceof THREE.Mesh) {
child.material = new THREE.MeshStandardMaterial({
color: "#555",
roughness: 0.0,
metalness: 2.0,
envMapIntensity: 5.0,
diffuseMapIntensity: 1.0,
roughnessMapIntensity: 1.0
});
//child.material.flatShading = false;
console.log("setting envmap");
child.material.envMap = newEnvMap;
child.material.diffuseMap = diffuseMaps;
child.material.roughnessMap = roughnessMaps;
child.material.needsUpdate = true;
//Sometimes there are some vertex normals missing in the .obj files, ThreeJs will compute them
}
});
object.position.y = -90;
scene.add(object);
}
Unfortunately, it does not work.
Could somebody help me please? I would be sooo thankful!!
Try it with this code:
var container;
var camera, scene, renderer;
let exrCubeRenderTarget, exrBackground;
let newEnvMap;
let torusMesh, planeMesh;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var object;
init();
animate();
function init() {
container = document.createElement("div");
container.className = "object";
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
1,
2000
);
camera.position.z = 250;
// scene
scene = new THREE.Scene();
scene.add(camera);
// manager
function loadModel() {
THREE.DefaultLoadingManager.onLoad = function() {
pmremGenerator.dispose();
};
// -----------------
function loadObjectAndAndEnvMap() {
const textureLoader = new THREE.TextureLoader();
const diffuseMap = textureLoader.load('https://threejs.org/examples/textures/brick_diffuse.jpg');
const roughnessMap = textureLoader.load('https://threejs.org/examples/textures/brick_roughness.jpg');
object.traverse(function(child) {
//This allow us to check if the children is an instance of the Mesh constructor
if (child instanceof THREE.Mesh) {
child.material = new THREE.MeshStandardMaterial({
color: "#555",
roughness: 1.0,
metalness: 0.5,
envMapIntensity: 5.0
});
child.material.envMap = newEnvMap;
child.material.map = diffuseMap;
child.material.roughnessMap = roughnessMap;
child.material.needsUpdate = true;
//Sometimes there are some vertex normals missing in the .obj files, ThreeJs will compute them
}
});
object.position.y = -90;
scene.add(object);
}
const pmremGenerator = new THREE.PMREMGenerator(renderer);
pmremGenerator.compileEquirectangularShader();
new THREE.EXRLoader()
.setDataType(THREE.UnsignedByteType)
.load(
"https://threejs.org/examples/textures/piz_compressed.exr",
function(texture) {
exrCubeRenderTarget = pmremGenerator.fromEquirectangular(texture);
exrBackground = exrCubeRenderTarget.texture;
newEnvMap = exrCubeRenderTarget ? exrCubeRenderTarget.texture : null;
loadObjectAndAndEnvMap(); // Add envmap once the texture has been loaded
texture.dispose();
}
);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.outputEncoding = THREE.sRGBEncoding;
}
var manager = new THREE.LoadingManager(loadModel);
manager.onProgress = function(item, loaded, total) {
console.log(item, loaded, total);
};
var loader = new THREE.OBJLoader(manager);
loader.load(
"https://threejs.org/examples/models/obj/female02/female02.obj",
function(obj) {
object = obj;
}
);
//
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener("mousemove", onDocumentMouseMove, false);
//
window.addEventListener("resize", onWindowResize, false);
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX) / 2;
mouseY = (event.clientY - windowHalfY) / 2;
}
//
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
camera.position.x += (mouseX - camera.position.x) * 0.05;
camera.position.y += (-mouseY - camera.position.y) * 0.05;
camera.lookAt(scene.position);
scene.background = exrBackground;
renderer.toneMappingExposure = 1.0;
renderer.render(scene, camera);
}
body {
margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three#0.125.2/build/three.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.125.2/examples/js/loaders/OBJLoader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.125.2/examples/js/loaders/EXRLoader.js"></script>
Please note:
The maximum value for roughness and metalness is 1. You have used 2for metalness.
Since the sampled value from a roughness map is multiplied with the roughness value from the material, you won't see any effect if you set it to 0. Always start with 1.

three.js - object look at mouse

Ok I understand it seems I did not try hard enough but I am really new to this
and I get no errors what so ever in Dreamweaver.
I deleted my old example and this is what I have now, trying to integrate
the look at function with the OBJ loader, camera and lights.
I think I understand what is happening more or less in the code,
but it's still not working, I assume it's because there is a code for
window resize but the look at function dose not take that into account,
thus it's not working since the function assume a fixed window size,
Am I right here?
Also I am not sure I need the two commented lines in the obj loader
object.rotateX(Math.PI / 2); and object.lookAt(new THREE.Vector3(0, 0, 0));
since this is just to get the starting position?
if I put these tow lines back, it will just rotate the object into an initial pose but the object will not turn relative to mouse position.
I am really not sure what is conflicting here
I changed the code now to this:
<script>
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var camera, scene;
var canvasRenderer, webglRenderer;
var container, mesh, geometry, plane;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 1500);
camera.position.x = 0;
camera.position.z = 100;
camera.position.y = 0;
camera.lookAt({
x: 0,
y: 0,
z: 0,
});
scene = new THREE.Scene();
// LIGHTS
scene.add(new THREE.AmbientLight(0x666666, 0.23));
var light;
light = new THREE.DirectionalLight(0xffc1c1, 2.20);
light.position.set(0, 100, 0);
light.position.multiplyScalar(1.2);
light.castShadow = true;
light.shadowCameraVisible = true;
light.shadowMapWidth = 512;
light.shadowMapHeight = 512;
var d = 50000;
light.shadowCameraLeft = -d;
light.shadowCameraRight = d;
light.shadowCameraTop = d;
light.shadowCameraBottom = -d;
light.shadowcameranear = 0.5;
light.shadowCameraFar = 1000;
//light.shadowcamerafov = 30;
light.shadowDarkness = 0.1;
scene.add(light);
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( 'model/' );
mtlLoader.load( 'rope.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.setPath( 'model/' );
objLoader.load( 'rope.obj', function ( object ) {
var positionX = 0;
var positionY = 0;
var positionZ = 0;
object.position.x = positionX;
object.position.y = positionY;
object.position.z = positionZ;
object.scale.x = 1;
object.scale.y = 1;
object.scale.z = 1;
//object.rotateX(Math.PI / 2);
//object.lookAt(new THREE.Vector3(0, 0, 0));
// castshow setting for object loaded by THREE.OBJLoader()
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.castShadow = true;
child.receiveShadow = true;
}
});
scene.add(object);
});
});
// RENDERER
//webglRenderer = new THREE.WebGLRenderer();
webglRenderer = new THREE.WebGLRenderer({
antialias: true
});
webglRenderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
webglRenderer.domElement.style.position = "relative";
webglRenderer.shadowMapEnabled = true;
webglRenderer.shadowMapSoft = true;
//webglRenderer.antialias: true;
container.appendChild(webglRenderer.domElement);
window.addEventListener('resize', onWindowResize, false);
}
window.addEventListener("mousemove", onmousemove, false);
var plane = new THREE.Plane(new THREE.Vector3(0, 0, 0), 0);
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var intersectPoint = new THREE.Vector3();
function onmousemove(event) {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
raycaster.ray.intersectPlane(plane, intersectPoint);
object.lookAt(intersectPoint);
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
webglRenderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
camera.lookAt(scene.position);
webglRenderer.render(scene, camera);
}
</script>
I took your code and adapted so it doesn't require a obj and put it into this codepen. The main problem seems to be that your intersection plane was defined incorrectly. The first argument is the normal vector which needs to be of length 1. Yours is 0. Therefore there are no meaningful intersections.
var plane = new THREE.Plane(new THREE.Vector3(0, 0, 0), 0);
If you change it to
var plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 10);
the intersections are more meaningful and the object actually rotates.

How to control fps with requestAnimationFrame?

I have used FBX format with three js. It seems like requestAnimationFrame is the de facto way to animate things now. The animation was working very speed, Like lightening. Can't find any solutions to control the fps.
See the below image.
Source code:
if (!Detector.webgl)
Detector.addGetWebGLMessage();
var container, stats, controls;
var camera, scene, renderer, light, mesh;
var clock = new THREE.Clock();
var mixers = [];
var mouseX = 0, mouseY = 0;
var spdx = 0, spdy = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 2000);
scene = new THREE.Scene();
// grid
var gridHelper = new THREE.GridHelper(28, 28, 0x303030, 0x303030);
gridHelper.position.set(0, -0.04, 0);
scene.add(gridHelper);
// stats
stats = new Stats();
container.appendChild(stats.dom);
// model
var manager = new THREE.LoadingManager();
manager.onProgress = function (item, loaded, total) {
console.log(item, loaded, total);
};
var onProgress = function (xhr) {
if (xhr.lengthComputable) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log(Math.round(percentComplete, 2) + '% downloaded');
}
};
var onError = function (xhr) {
console.error(xhr);
};
var loader = new THREE.FBXLoader(manager);
loader.load('assests/JetEngine_Ani.fbx', function (object) {
object.mixer = new THREE.AnimationMixer(object);
mixers.push(object.mixer);
var action = object.mixer.clipAction(object.animations[ 0 ]);
action.play();
scene.add(object);
}, onProgress, onError);
renderer = new THREE.WebGLRenderer({alpha: true});
renderer.setClearColor(0xdddddd, 1);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.target.set(0, 12, 0);
camera.position.z = 850;
controls.update();
window.addEventListener('resize', onWindowResize, false);
light = new THREE.HemisphereLight(0xffffff, 0x444444, 1.0);
light.position.set(0, 1, 0);
scene.add(light);
light = new THREE.DirectionalLight(0xffffff, 1.0);
light.position.set(0, 1, 0);
scene.add(light); }
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight); }
function onDocumentMouseMove(event) {
mouseX = event.clientX;
mouseY = event.clientY;
}
function animate() {
requestAnimationFrame(animate);
if (mixers.length > 0) {
for (var i = 0; i < mixers.length; i++) {
mixers[ i ].update(clock.getDelta());
}
}
stats.update();
render();
}
function render() {
renderer.render(scene, camera);
}
How to control the animation speed. Is there have other ways or only through fps(frames per second).
How can I reduce the animation speed??..
You want to control the duration of your AnimationAction loop. To do so, you can use this pattern:
action.setDuration( 10 ).play();
three.js r.87

Three.js - Rotate object along (0,0,0) on mouse move

I have this object here in Three.js. The object has been implemented on blender and i have imported it in three.js format. What i want is to rotate the object with my mouse. If someone could help i would really appreciate it! Thanks
function init(x, y, z, base, small, big, corners) {
scene = new THREE.Scene();
initMesh(x, y, z, base, small, big, corners);
initCamera();
initLights();
initRenderer();
var e = document.body.appendChild(renderer.domElement);
e.style.marginLeft="300px";
e.style.position="absolute";
render();
}
function initCamera() {
camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 10);
camera.position.set(0, 3.5, 3);
camera.lookAt(scene.position);
}
function initRenderer() {
renderer = new THREE.WebGLRenderer({ antialias: true});
renderer.setSize(WIDTH, HEIGHT);
renderer.setClearColor("white");
}
var mesh = null;
var mesh1 = null;
var mesh2 = null;
var mesh3 = null;
var group;
function initMesh(x, y, z, base, small, big, corners) {
group = new THREE.Object3D();
var loader = new THREE.JSONLoader();
loader.load(base, function(geometry, materials) {
mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
mesh.scale.x = x;
mesh.scale.y = y;
mesh.scale.z = z;
mesh.opacity=1;
mesh.castShadow = false;
var model = new THREE.Object3D();
model.add(mesh);
model.position.set(0,0,0);
//mesh.translation = THREE.GeometryUtils.center(geometry);
group.add(model);
});
loader.load(small, function(geometry, materials) {
mesh1 = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
mesh1.scale.x = x;
mesh1.scale.y = y;
mesh1.scale.z = z;
mesh1.opacity=1;
mesh1.castShadow = false;
var model1 = new THREE.Object3D();
model1.add(mesh1);
model1.position.set(0,0,0);
//mesh1.translation = THREE.GeometryUtils.center(geometry);
group.add(model1);
});
loader.load(big, function(geometry, materials) {
mesh2 = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
mesh2.scale.x = x;
mesh2.scale.y = y;
mesh2.scale.z = z;
mesh2.opacity=1;
mesh2.castShadow = false;
var model2 = new THREE.Object3D();
model2.add(mesh2);
model2.position.set(0,0,0);
//mesh1.translation = THREE.GeometryUtils.center(geometry);
group.add(model2);
});
loader.load(corners, function(geometry, materials) {
mesh3 = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
mesh3.scale.x = x;
mesh3.scale.y = y;
mesh3.scale.z = z;
mesh3.opacity=1;
mesh3.castShadow = false;
var model3 = new THREE.Object3D();
model3.add(mesh3);
model3.position.set(0,0,0);
//mesh1.translation = THREE.GeometryUtils.center(geometry);
group.add(model3);
});
scene.add(group);
}
function initLights() {
var light; // A light shining from the direction of the camera.
light = new THREE.DirectionalLight();
light.position.set(0,100,10);
group.castShadow = false;
group.receiveShadow = false;
scene.add(light);
}
function rotateMesh() {
if (!mesh) {
return;
}
//group.rotation.y -= 0.4* ( Math.PI / 180 );
}
function render() {
requestAnimationFrame(render);
rotateMesh();
renderer.render(scene, camera);
}
init(0.5, 0.5, 0.5, "base.js", "small.js", "big.js", "corners.js");
To whom it may concern i found the answer here. In my case root must become group
var mouseDown = false,
mouseX = 0,
mouseY = 0;
function onMouseMove(evt) {
if (!mouseDown) {
return;
}
evt.preventDefault();
var deltaX = evt.clientX - mouseX,
deltaY = evt.clientY - mouseY;
mouseX = evt.clientX;
mouseY = evt.clientY;
rotateScene(deltaX, deltaY);
}
function onMouseDown(evt) {
evt.preventDefault();
mouseDown = true;
mouseX = evt.clientX;
mouseY = evt.clientY;
}
function onMouseUp(evt) {
evt.preventDefault();
mouseDown = false;
}
var ee = document.body.appendChild(renderer.domElement);
ee.addEventListener('mousemove', function (e) {
onMouseMove(e);
}, false);
ee.addEventListener('mousedown', function (e) {
onMouseDown(e);
}, false);
ee.addEventListener('mouseup', function (e) {
onMouseUp(e);
}, false);
var c=1;
var cc=3;
var ccc=3;
ee.addEventListener('wheel', function (e) {
console.log(e.deltaY);
if(e.deltaY>0){
c=c*0.95
cc=cc*0.95;
ccc=ccc*0.95
camera.position.set(c, cc, ccc);
}else{
c=c*1.05
cc=cc*1.05;
ccc=ccc*1.05
camera.position.set(c, cc, ccc);}
});
function rotateScene(deltaX, deltaY) {
group.rotation.y += deltaX / 100;
group.rotation.x += deltaY / 100;
}
I added a zoom function too, it needs this lib here

Categories

Resources