How to use DRACO Loader with GLTF Loader? - javascript

Hello guys!
Been doing some experiments with three.js, managed to get a 70mb model down to 10 MB using draco, however I am not really familiar with Draco and I haven't been able to find a good example on how to use Draco loader together with GLTF Loader, can anyone show me a good example or check my code to see which things I have to change to use it and load the compressed model? TYSM!
import * as THREE from '../build/three.module.js';
import Stats from './jsm/libs/stats.module.js';
import { OrbitControls } from './jsm/controls/OrbitControls.js';
import { GLTFLoader } from './jsm/loaders/GLTFLoader.js';
let camera, scene, renderer, stats;
var raycaster, mouse = { x : 0, y : 0 };
var objects = [];
var selectedObject;
init();
animate();
function init() {
const container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.25, 20 );
camera.position.set( - 1.8, 0.6, 2.7 );
scene = new THREE.Scene();
scene.background = new THREE.Color( 0xa0a0a0 );
raycaster = new THREE.Raycaster();
const hemiLight = new THREE.HemisphereLight( 0xa0a0a0, 0xa0a0a0, 2);
scene.add(hemiLight);
// model
const loader = new GLTFLoader().setPath( 'models/fbx/lowlight3_out/' );
loader.load( 'lowlight3.gltf', function ( gltf ) {
gltf.scene.traverse( function ( child ) {
if ( child.isMesh ) {
child.castShadow = true;
child.receiveShadow = true;
}
} );
scene.add( gltf.scene );
} );

Guys just managed to get it working, just add to add Draco by following the three.js default example:
Add
import { DRACOLoader } from './jsm/loaders/DRACOLoader.js';
&
const loader = new GLTFLoader().setPath( 'models/fbx/compressed/' );
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath( './js/libs/draco/' );
loader.setDRACOLoader( dracoLoader );
For anyone having the same issue, just take a look to this example:
https://threejs.org/docs/#examples/en/loaders/GLTFLoader

Related

Three Js GLTF loader model not showing up

I am trying to use Three js to load in a 3d heart model and attach a picture to the front of the heart but it seems the heart isn’t showing up at all even without loading the image in. I am new at Three js so I might be doing it all wrong but I tried using the code straight from the documents and it still isn’t working. I am getting no errors and I can see AxesHelper also I have loaded in a cube and that works so I don't think there is a problem with my scene.
function handleHeart(img) {
document.getElementById("divRight").innerHTML = ""
let renderer = new THREE.WebGLRenderer();
document.getElementById("divRight").appendChild(renderer.domElement);
let w = document.getElementById("divRight").clientWidth
let h = 600
renderer.setSize( w, h)
let camera = new THREE.PerspectiveCamera(35, w / h, 0.1, 3000 );
const controls = new THREE.OrbitControls( camera, renderer.domElement );
camera.position.set( 0, 0, 10 );
camera.lookAt(new THREE.Vector3(0, 0, 0))
controls.update();
let scene = new THREE.Scene();
scene.background = new THREE.Color( 'grey' );
light = new THREE.AmbientLight(0xffffff);
scene.add(light);
const loader = new THREE.GLTFLoader();
loader.load(
// resource URL
'models/heart_v1.glb',
// called when the resource is loaded
function ( gltf ) {
let material = new THREE.MeshBasicMaterial( { map: img } );
let model = gltf.scene || gltf.scenes[0];
//model.scale.set(1000,1000,1000)
model.material = material
scene.add(model)
model.position.z = -10
},
// called while loading is progressing
function ( xhr ) {
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
// called when loading has errors
function ( error ) {
console.log(error)
console.log( 'An error happened' );
})
scene.add(new THREE.AxesHelper(100))
renderer.render(scene, camera)
}
here is a replit : https://repl.it/#AlecStein44/Threejs-help#javascript.js
model.material = material
This line is incorrect. It should be:
model.traverse( function( object ) {
if ( object.isMesh ) object.material = material;
} );
Notice that applying a texture will still not work since your model heart_v1.glb has no texture coordinates.

How to use three.js with React

I am trying to use three.js in a React application however even the basic sample from the three.js docs fails to load on the canvas.
I first made a vanilla.js sandbox implementation with the sample which works fine. Then I ported it over to create a react+three.js minimal sandbox implementation which fails to work.
Can anyone have a look at it and point me in the right direction ?
class Viewer extends Component {
state = {};
scene = null;
camera = null;
renderer = new WebGLRenderer();
inst = 0;
viewerRef = React.createRef();
componentDidMount() {
const { domElement } = this.renderer;
this.scene = new Scene();
this.scene.background = new Color("#ccc");
this.camera = new Camera(
75,
domElement.innerWidth / domElement.innerHeight,
0.1,
1000
);
this.renderer.setSize(domElement.innerWidth, domElement.innerHeight);
this.viewerRef.current.appendChild(this.renderer.domElement);
const geometry = new BoxGeometry(1, 1, 1);
const material = new MeshBasicMaterial({ color: 0x05ff00 });
const cube = new Mesh(geometry, material);
this.scene.add(cube);
this.camera.position.z = 5;
this.display();
}
display = () => {
this.renderer.render(this.scene, this.camera);
requestAnimationFrame(this.display);
};
render = () => <div className="viewer" ref={this.viewerRef} />;
}
Here is CodeSandBox that works with a basic React wrapper code for Three.js. It also has THREE.OrbitControls integration and scale on resize code:
https://codesandbox.io/s/github/supromikali/react-three-demo
Live demo: https://31yp61zxq6.codesandbox.io/
Here is a full code snippet in the case above listed links don't work for you:
index.js code
import React, { Component } from "react";
import ReactDOM from "react-dom";
import THREE from "./three";
class App extends Component {
componentDidMount() {
// BASIC THREE.JS THINGS: SCENE, CAMERA, RENDERER
// Three.js Creating a scene tutorial
// https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.z = 5;
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
// MOUNT INSIDE OF REACT
this.mount.appendChild(renderer.domElement); // mount a scene inside of React using a ref
// CAMERA CONTROLS
// https://threejs.org/docs/index.html#examples/controls/OrbitControls
this.controls = new THREE.OrbitControls(camera);
// ADD CUBE AND LIGHTS
// https://threejs.org/docs/index.html#api/en/geometries/BoxGeometry
// https://threejs.org/docs/scenes/geometry-browser.html#BoxGeometry
var geometry = new THREE.BoxGeometry(2, 2, 2);
var material = new THREE.MeshPhongMaterial( {
color: 0x156289,
emissive: 0x072534,
side: THREE.DoubleSide,
flatShading: true
} );
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
var lights = [];
lights[ 0 ] = new THREE.PointLight( 0xffffff, 1, 0 );
lights[ 1 ] = new THREE.PointLight( 0xffffff, 1, 0 );
lights[ 2 ] = new THREE.PointLight( 0xffffff, 1, 0 );
lights[ 0 ].position.set( 0, 200, 0 );
lights[ 1 ].position.set( 100, 200, 100 );
lights[ 2 ].position.set( - 100, - 200, - 100 );
scene.add( lights[ 0 ] );
scene.add( lights[ 1 ] );
scene.add( lights[ 2 ] );
// SCALE ON RESIZE
// Check "How can scene scale be preserved on resize?" section of Three.js FAQ
// https://threejs.org/docs/index.html#manual/en/introduction/FAQ
// code below is taken from Three.js fiddle
// http://jsfiddle.net/Q4Jpu/
// remember these initial values
var tanFOV = Math.tan( ( ( Math.PI / 180 ) * camera.fov / 2 ) );
var windowHeight = window.innerHeight;
window.addEventListener( 'resize', onWindowResize, false );
function onWindowResize( event ) {
camera.aspect = window.innerWidth / window.innerHeight;
// adjust the FOV
camera.fov = ( 360 / Math.PI ) * Math.atan( tanFOV * ( window.innerHeight / windowHeight ) );
camera.updateProjectionMatrix();
camera.lookAt( scene.position );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.render( scene, camera );
}
// ANIMATE THE SCENE
var animate = function() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
}
render() {
return <div ref={ref => (this.mount = ref)} />;
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
three.js code (THREE.OrbitControls import)
import * as THREE from 'three';
window.THREE = THREE; // THREE.OrbitControls expects THREE to be a global object
require('three/examples/js/controls/OrbitControls');
export default {...THREE, OrbitControls: window.THREE.OrbitControls};
Result should look like this:
I am not sure why nobody has mentioned react-three-fiber. It's a React renderer for ThreeJS.
Best part is, using rollupjs, we can even tree-shake a lot of unnecessary code, that we won't use in our React ThreeJS app. Also, using react-three-fiber in a desired way, we can achieve 60FPS for our ThreeJS animations 🥰
To learn basics, just take a look into react-three-fiber Examples
There's a few issues with your sandbox at the moment, which aren't necessarily related to React.
innerWidth and innerHeight are not defined. clientWidth and clientHeight are probably the fields you're looking for to get the dimensions of the dom element.
The dimensions of the canvas are being read before it has been added into the document, meaning the dimensions of the element will always be 0 0. Insert the element first before computing the camera aspect ratio and setting the render size.
Camera isn't intended to be used directly. The docs specify it as an abstract base class for cameras -- use PerspectiveCamera instead.
Here's a sample of the code with the above fixes
const { domElement } = this.renderer;
// Fix 1
this.viewerRef.current.appendChild(domElement);
// Fix 2
const width = domElement.clientWidth;
const height = domElement.clientHeight;
this.scene = new Scene();
this.scene.background = new Color("#ccc");
// Fix 3
this.camera = new PerspectiveCamera(
75,
width / height,
0.1,
1000
);
this.renderer.setSize(width, height);
const geometry = new BoxGeometry(1, 1, 1);
const material = new MeshBasicMaterial({ color: 0x05ff00 });
const cube = new Mesh(geometry, material);
this.scene.add(cube);
this.camera.position.z = 5;
this.display();
Hope that helps!

three.js fails to render scene when using PointerLockControls

I have the problem, that my three.js scene fails to render as soon as i create a PointerLockControls object. I have absoulute no clue what the issue could be.
main.js:
const THREE = require("three");
var PointerLockControls = require('three-pointerlock');
//utils
import detect from "./detect"
import dialogs from "./dialogs"
import calc from "./calc"
import {Player} from "./charackters"
//3D stuff
import world from "./world"
//Scene creation
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
var controls = new PointerLockControls(camera);
camera.position.y = -50;
camera.position.z = 40;
camera.rotation.x = calc.rad(90);
//WebGL Renderer
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor(0x000000);
document.body.appendChild( renderer.domElement );
world.drawFloor(scene, THREE);
var cGeo = new THREE.BoxGeometry(10,10,10);
var cTexture = new THREE.MeshNormalMaterial();
var Cube = new THREE.Mesh(cGeo, cTexture);
scene.add(Cube);
//tick function
var clock = new THREE.Clock(true);
function animate() {
requestAnimationFrame(animate);
controls.update(clock.getDelta);
renderer.render( scene, camera );
}
if(detect.webgl()){
animate();
}else{
dialogs.error("Your browser does not support WebGL. Please install a modern Browser such as Google Chrome or Mozilla Firefox to play AlphaWars!", "Warning:")
}
if you need any of my additional files please comment.
Thanks in advance.
Maybe you use the PointerLockControls in a wrong way. You should add
scene.add( controls.getObject() );
after
var controls = new PointerLockControls(camera);
because PointerLockControls object has a attribute pitchObject and you should add it into scene.

How to load two or more .obj objects in a scene using three.js from user input?

How to load more than two objects in three js of .obj file . I tried by applying a for loop across the loader file of obj and mtl but it is not working instead it shows only the last object ?Please if any one can help.
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
camera.position.z = 1000;
// scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight( 0x444444 );
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 ).normalize();
scene.add( directionalLight );
// model
THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );
var setBaseUrl1 = 'newObj/';
var setPath1 = 'newObj/';
var i = 0;
var mltLoad1,objLoad1;
var mtlLoader = new Array(res.length);
var objLoader = new Array(res.length);
for(i=0;i<res.length;i++)
{
mtlLoad1 = String(res[i].concat(".mtl"));
objLoad1 = String(res[i].concat(".obj"));
mtlLoader[i] = new THREE.MTLLoader();
mtlLoader[i].setBaseUrl( setBaseUrl1 );
mtlLoader[i].setPath( String(setPath1) );
mtlLoader[i].load( mtlLoad1, function( materials ) {
materials.preload();
objLoader[i] = new THREE.OBJLoader();
objLoader[i].setMaterials( materials );
objLoader[i].setPath( setPath1 );
objLoader[i].load( objLoad1, function(object) {
object.position.y = -95;
object.position.z = 500;
camera.position.x = 500;
scene.add( object );
});
});
}
}
load model without for loop ,it looks your variable holds obj override .

Use custom mesh instead of generated one in three.js

I have just discovered the world of three.js and it's amazing.
I downloaded the examples, and started checking some of them.
I have never been coding in JavaScript, so I was wondering if somebody could help me with editing one of the example files (misc_controls_trackball.html). Instead of generated geometry (mesh.position.x = ( Math.random() - 0.5 ) ...) I was wondering if I could just include an already made mesh (from 3 studio max for example)?
I think this is the part of the code which generates the mesh:
// world
scene = new THREE.Scene();
scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
var geometry = new THREE.CylinderGeometry( 0, 10, 30, 4, 1 );
var material = new THREE.MeshLambertMaterial( { color:0xffffff, shading: THREE.FlatShading } );
for ( var i = 0; i < 500; i ++ ) {
var mesh = new THREE.Mesh( geometry, material );
mesh.position.x = ( Math.random() - 0.5 ) * 1000;
mesh.position.y = ( Math.random() - 0.5 ) * 1000;
mesh.position.z = ( Math.random() - 0.5 ) * 1000;
mesh.updateMatrix();
mesh.matrixAutoUpdate = false;
scene.add( mesh );
}
In what way should this be changed, so that I could import my external mesh (in form of .3ds, .obj, .dae, does not matter)?
Thank you.
Here is the misc_controls_trackball.html example file along with "js" folder.
Tried this?
http://threejs.org/examples/webgl_loader_collada
It`s an example for Collada, but for the other formats the concept is the same, just using a different loader.
var loader = new THREE.ColladaLoader();
// Depending on how you created your model, you may need to
loader.options.convertUpAxis = true;
// Then load it:
loader.load( './models/collada/monster/monster.dae', function ( collada ) {
// All this will happen asynchronously
dae = collada.scene;
// Before displaying it, you can tweak it as necessary
dae.scale.x = dae.scale.y = dae.scale.z = 0.002;
dae.updateMatrix();
scene.add(dae);
// At the next frame, you`ll have your model loaded.
} );
EDIT, additions
First you need the links to the proper libraries, including the ColladaLoader
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r69/three.js"></script>
<script src="js/loaders/ColladaLoader.js"></script>
Then a number of things needed fixing in the code.
- scene object was missing
- Model loaded, but to be scaled up a bit
- No call to render() in the animate function, so you had no animation.
- The fog statement was broken... Best spending some time on the basics, first...
function init() {
// Create your scene first
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 500;
controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
controls.keys = [ 65, 83, 68 ];
controls.addEventListener( 'change', render );
// world
var loader = new THREE.ColladaLoader();
// Depending on how you created your model, you may need to
loader.options.convertUpAxis = true;
// Then load it:
//loader.load( './models/collada/monster/monster.dae', function ( collada ) {
loader.load( 'models/monster.dae', function ( collada ) {
// All this will happen asynchronously
dae = collada.scene;
// Give it a decent scale
dae.scale.x = dae.scale.y = dae.scale.z = 1;
dae.updateMatrix();
scene.add(dae);
// At the next frame, you`ll have your model loaded.
} );
// lights
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 1, 1, 1 );
scene.add( light );
light = new THREE.DirectionalLight( 0x002288 );
light.position.set( -1, -1, -1 );
scene.add( light );
light = new THREE.AmbientLight( 0x222222 );
scene.add( light );
// renderer
renderer = new THREE.WebGLRenderer( { antialias: false } );
//renderer.setClearColor( scene.fog.color, 1 );
renderer.setSize( window.innerWidth, window.innerHeight );
container = document.getElementById( 'container' );
container.appendChild( renderer.domElement );
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
stats.domElement.style.zIndex = 100;
container.appendChild( stats.domElement );
//
window.addEventListener( 'resize', onWindowResize, false );
// The following is not necessary at this stage, as you`ll call it
// from animate later down (if you want to do an animation, of course,
// which I guess you do)
render();
}
And the animate function should look like this
function animate() {
requestAnimationFrame( animate );
controls.update();
render();
}
Hope that helps! :)

Categories

Resources