OBJLoader and MTLLoader aren't rendering png/texture in ThreeJS - javascript

I imported the 3D model that contains .obj .mtl and bunch of jpeg and pngs
trying to load the model with /images like this
But, I'm getting is only a black model like his
I wonder what I have missed as I followed the guidelines for using the two loaders.
here is my code.
//loader
var MTTLoader = new THREE.MTLLoader();
MTTLoader.setPath( '/assets/HotAirBalloonIridesium/' );
MTTLoader.load('Air_Balloon.mtl',(materials) => {
console.log(materials);
materials.preload()
var objLoader = new THREE.OBJLoader();
objLoader.load('/assets/HotAirBalloonIridesium/Air_Balloon.obj', (object) => {
console.log(materials)
objLoader.setMaterials(materials)
scene.add(object);
})
})
I wonder what i'm missing as my asset folder contains all the model files

try loading obj using
var loader = new THREE.OBJLoader( manager );
loader.load( 's_v1.obj', function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh )
{
// child.material.map = texture2;
// child.material.specularMap=texture;
// child.material.map=texture;
}
} );
// object.position.x = - 60;
// object.rotation.x = 0; //20* Math.PI / 180;
// object.rotation.z = 0;//20* Math.PI / 180;
object.scale.x = 80;
object.scale.y = 80;
object.scale.z = 80;
obj = object
scene.add( obj );
animate(obj);
} );

okay quick update, there was nothing wrong with the loader but I was using the wrong lighting as Phong Material needed
var hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.50);
var dirLight = new THREE.DirectionalLight(0xffffff, 0.50);
to be apparent.

You must call "setMaterials" before load obj.
//loader
var MTTLoader = new THREE.MTLLoader();
MTTLoader.setPath( '/assets/HotAirBalloonIridesium/' );
MTTLoader.load('Air_Balloon.mtl',(materials) => {
console.log(materials);
materials.preload()
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials); // "setMaterials" must before "load"
objLoader.load('/assets/HotAirBalloonIridesium/Air_Balloon.obj', (object) => {
console.log(materials)
scene.add(object);
})
})

Related

Raycasting not working on imported OBJ model,but working on object created with the program

I am new to three.js, and i am trying to use raycasting, i am quite confused with how raycasting would work on imported 3d models. Here i imported an obj model, and when i try to detect whether i touch with the imported 3D model, the funciton is not working as i expect. But when i change it to detect a box object i create with three.js, is working as i expected, can someone help with this problem?
import * as THREE from 'https://unpkg.com/three#0.126.1/build/three.module.js';
import { OrbitControls } from 'https://unpkg.com/three#0.126.1/examples/jsm/controls/OrbitControls.js';
import {OBJLoader} from "https://unpkg.com/three#0.126.1/examples/jsm/loaders/OBJLoader.js";
import {MTLLoader} from "https://unpkg.com/three#0.126.1/examples/jsm/loaders/MTLLoader.js";
import * as GUI from "https://unpkg.com/dat.gui#0.7.7/build/dat.gui.module.js";
//Set Up Enviroment for 3D model
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth,window.innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
//Set up Lighting
var keyLight = new THREE.DirectionalLight(new THREE.Color('hsl(30,100%,75%)'),1.0);
var fillLight = new THREE.DirectionalLight(new THREE.Color('hsl(240,100%,75%)'),0.75);
var backLight = new THREE.DirectionalLight(0xffffff,1.0);
keyLight.position.set(-100,0,100);
fillLight.position.set(100,0,100);
backLight.position.set(100,0,-100).normalize();
scene.add(keyLight);
scene.add(fillLight);
scene.add(backLight);
//Set up Camera
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth/window.innerHeight,
0.1,
1000
);
const orbit = new OrbitControls(camera,renderer.domElement);
camera.position.set(0,2,7.5);
orbit.update();
//Set up base
const planeGeometry = new THREE.PlaneGeometry(100,100);
const planeMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
wireframe: false,
side: THREE.DoubleSide
});
var plane = new THREE.Mesh(planeGeometry,planeMaterial);
scene.add(plane);
plane.rotation.x = -0.5 * Math.PI;
//Model for testing
const boxGeometry = new THREE.BoxGeometry(10,10,10);
const boxMaterial = new THREE.MeshBasicMaterial({color: 0x0000ff})
var box = new THREE.Mesh(boxGeometry,boxMaterial);
scene.add(box);
box.position.x += 20;
//Set up GUI for controlling base
const gridHelper = new THREE.GridHelper(100);
scene.add(gridHelper);
const gui = new GUI.GUI();
const options = {
planeColor: '#ffea00',
wireframe: false
};
gui.addColor(options,'planeColor').onChange(function(e){
plane.material.color.set(e);
});
gui.add(options,'wireframe').onChange(function(e){
plane.material.wireframe = e;
});
//Set up Background image
const textureLoader = new THREE.TextureLoader();
textureLoader.load(
'../img/doge.jpg',
function ( texture ) {
scene.background = texture;
},
undefined,
function ( err ) {
console.error( 'An error happened.' );
}
);
//Import obj and mtl file to build 3D model
var building;
const mtlLoader = new MTLLoader();
mtlLoader.load(
'../source/building_04.mtl',
(materials)=>{
materials.preload();
console.log(materials);
const objLoader = new OBJLoader()
objLoader.setMaterials(materials)
objLoader.load(
'../source/building_04.obj',
(object)=>{
scene.add(object)
building = object;
object.position.y +=1;
},
(xhr) => {
console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
},
(error) => {
console.log("Object error")
}
)
},
(xhr) => {
console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
},
(error) => {
console.log("Material Eror")
}
)
//Set up raycasting environment
const raycaster = new THREE.Raycaster();
const mousePosition = new THREE.Vector2();
window.addEventListener('mousemove', function(e){
mousePosition.x = (e.clientX/this.window.innerWidth)*2 - 1;
mousePosition.y = -(e.clientY/this.window.innerHeight)*2 + 1;
});
//Function making sure everything to be up to date
function animate(){
//Raycasting
raycaster.setFromCamera( mousePosition, camera );
const intersects = raycaster.intersectObjects( scene.children,true);
if(intersects.length > 0){
for ( let i = 0; i < intersects.length; i ++ ) {
if(building != undefined){
if(intersects[0].object.id === building.id){
console.log("Touched!");
}
else{
console.log("did not touch!");
}
}
else{
console.log("Not reeady!");
}
console.log(intersects[i].object.id);
}
}
else{
console.log("did not touched")
}
console.log("finished")
renderer.render(scene,camera);
}
renderer.setAnimationLoop(animate);
//Make the screen to resize following the browser size
window.addEventListener('resize',function(){
camera.aspect = window.innerWidth/this.window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth,window.innerHeight);
});
The problem is that the object you get from OBJLoader and assign to your building variable is an instance of THREE.Group. Groups do not have an own geometry or material. They are more or less containers holding other 3D objects (like meshes, point clouds, lines or other groups) and representing them as a logical group.
That means they are never the result of a raycasting evaluation which means if(intersects[0].object.id === building.id) always fails.
I suggest you do this after the loading process which tags your objects:
building.traverse( function( object ) {
object.userData.tag = 'building';
} );
You can then use the tag property in your raycasting routine for detecting the building.

how to convert 3D obj file to particles in three.js

I'm trying to play around with particles in three.js but, there's a problem with converting obj file (3D model) into particles in three.js. The following is the code snippets. I tried but, all failed.
Is there anyone who can help correcting the errors or provide with any examples of getting vertices/particles from a 3D model in obj?
Thanks a lot.
var p_geom = new THREE.Geometry();
var p_material = new THREE.ParticleBasicMaterial({
color: 0xFFFFFF,
size: 1.5
});
var loader = new THREE.OBJLoader();
loader.load( 'human.obj',function(object){
object.traverse( function(child){
if ( child instanceof THREE.Mesh ) {
// child.material.map = texture;
var scale = 10.0;
object.attributes.position.array.forEach(function() {
p_geom.vertices.push(new THREE.Vector3(this.x * scale, this.y * scale, this.z * scale));
})
}
});
scene.add(p)
});
p = new THREE.ParticleSystem(
p_geom,
p_material
);
You are using an outdated code reference. With recent three.js version, the code looks more like the following:
const loader = new THREE.OBJLoader();
loader.load('human.obj', function(object) {
const vertices = [];
object.traverse(function(child) {
if (child.isMesh) {
vertices.push(...child.geometry.attributes.position.array);
}
});
const p_geom = new THREE.BufferGeometry();
const p_material = new THREE.PointsMaterial({
color: 0xFFFFFF,
size: 1.5
});
p_geom.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
const p = new THREE.Points(p_geom, p_material);
p.scale.set(10, 10, 10);
scene.add(p)
});

Three JS OBJloader - obj not importing properly

i'm trying to import an obj with OBJLoader but it isn't importing properly
The obj is like this -
Obj img
And it's importing this -
Obj in three js
What happens is that the whole obj isn't importing well.
What can i do about it ?
The code that i'm doing is
var objLoader = new THREE.OBJLoader();
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setTexturePath("obj2/");
mtlLoader.setPath( "obj2/" );
mtlLoader.load( "Mules/Base_10.mtl", function( materials ) {
materials.preload();
objLoader.setMaterials( materials );
objLoader.load( 'obj2/Mules/Base_10.obj', function ( object ) {
object.traverse( function ( child )
{
if ( child instanceof THREE.Mesh )
{
meshes.push(child);
}
});
var object = meshes[meshes.length-1];
object.position.y = -0.05;
object.position.x = 0;
object.position.z = 0;
object.name = "salto";
scene.add(object);
}, onProgress, onError );
});
Thank you.
The problem is:
object.traverse(...);
var object = meshes[meshes.length-1]; //<-- you overriding the object, with the last mesh.
object.position.y = -0.05;
object.position.x = 0;
object.position.z = 0;
object.name = "salto";
scene.add(object); //<-- than you add the object to your scene.
do not override the object. Also you don't need to traverse through the objects, as you will add the whole thing to your scene. and you do nothing with your meshes anyway :)
so try this:
object.position.y = -0.05;
object.position.x = 0;
object.position.z = 0;
object.name = "salto";
scene.add(object);

How to use multiple texture use in `OBJLoader` three.js?

How to multiple textures material use in Three.js?.Here three textures using and one 3D sofa.obj format file. I tried a lot of time. Below my code. What do I mistake in my code?
var loader = new THREE.OBJLoader();
var textureLoader = new THREE.TextureLoader();
threeDTexture = new THREE.ImageUtils.loadTexture( 'models/Sofa/Texturses/paradis_beige.jpg' );
threeDTexture2 = new THREE.ImageUtils.loadTexture( 'models/Sofa/Texturses/1.jpg' );
threeDTexture3 = new THREE.ImageUtils.loadTexture( 'models/Sofa/Texturses/2.jpg' );
loader.load('models/Sofa/sofa.obj', function (object) {
var geo = object.children[0].geometry;
var mats = [threeDTexture, threeDTexture2,threeDTexture3];
objct = new THREE.Mesh(geo, mats);
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material = objct;
}
});
object.position.x = posX;
object.position.y = 0;
object.position.z = posZ;
var size = new THREE.Box3().setFromObject(object).getSize();
object.scale.set(width/size.x, height/size.y, depth/size.z);
scene1.add(object);
console.log(object);
console.log(size);
console.log(width/size.x, height/size.y, depth/size.z);
},
function ( xhr ) {
returnValue = ( xhr.loaded / xhr.total * 100 ) + '% loaded';
console.log(returnValue);
},
function ( error ) {
console.log( 'An error happened' );
}
);
break
first, the textureLoader declared on line-2 is not in use;
second, belowing mats is not an Material Array, you should new MeshBasicMaterial(...) to wrap a texture, see the document here.
var mats = [threeDTexture, threeDTexture2,threeDTexture3];
objct = new THREE.Mesh(geo, mats); // Mesh will not accept this mats param!

Not loading the texture with OBJ+MTL loader in three.js

I have a problem. I wrote this function to load an obj and mtl model
(taken from:https://threejs.org/examples/#webgl_loader_obj_mtl):
var mtlLoader = new THREE.MTLLoader();
//mtlLoader.setTexturePath(path)
mtlLoader.setPath(path);
mtlLoader.load(material, function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.setPath(path);
objLoader.load(model, function ( mesh ) {
mesh.position.set(x, y, z);
mesh.scale.set(s, s, s);
mesh.rotation.y = Math.PI;
mesh.castShadow = false;
mesh.receiveShadow = true;
scene.add(mesh);
if(handler) {
handler(mesh);
}
}, function(e){}, function(e){} );
});
Where material is file.mtl and model is file.obj. It works fine for this model: https://free3d.com/3d-model/hk416-with-animation-37927.html but it doesn't work for another obj+mtl. The texture is not loaded and I see only white model. Why?
I use three.js r85.
Thank you!!

Categories