I am trying to add a level .obj for my program but it renders black. The .mtl file requires several images placed everywhere (not one space is non-textured). I used to same object in my last project and it works, but it doesn't in my current project. When I remove the materials the lighting affects it, but when I add it, it is pitch black. The renderer renders continously. Also, there are no errors in the console.
Here is the code used in my current project: (MaterialLoader is an MTLLoader instance and ObjectLoader is an OBJLoader instance)
MaterialLoader.load("bbb/bbb.mtl",
function(materials) {
materials.preload()
ObjectLoader.setMaterials(materials)
ObjectLoader.load("bbb.obj",
function(model) {
let mesh = model.children[0]
scene.add(mesh)
}, null, function(error) {alert(error)}
)
}, null, function(error) {alert(error)}
)
Here is the code from my previous project (the loader variable is an OBJLoader instance, and the materials load successfully here.)
mtlLoader.load(
"bbb.mtl",
function(materials) {
materials.preload()
loader.setMaterials(materials)
loader.load("bbb.obj",
function(obj) {
level = obj.children[0]
scene.add(level)
}, null,
function(error) { alert(error) }
)
}, null,
function(error) { alert(error) }
)
https://discourse.threejs.org/t/objloader-mtlloader-not-loading-texture-image/2534
try change object material color, like this:
model.children[0].material.color.r = 1;
model.children[0].material.color.g = 1;
model.children[0].material.color.b = 1;
its work for me
Your code works when tested! Maybe it's an issue with the material export, uv unwrapping, the texture's path, do you have lighting added to the scene, etc. Here's my test code:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75,320/240,1,500);
camera.position.set( 0,2,2 );
camera.lookAt( scene.position );
var lightIntensity = 1;
var lightDistance = 10;
var light = new THREE.AmbientLight( 0xFFFFFF, lightIntensity, lightDistance );
light.position.set( 0, 5, 0 );
scene.add( light );
var grid = new THREE.GridHelper(10,10);
scene.add( grid );
var renderer = new THREE.WebGLRenderer({});
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( 320,240 );
renderer.domElement.style.margin = '0 auto';
renderer.domElement.style.display = 'block';
renderer.domElement.style.backgroundColor = '#dddddd';
$(document.body).append(renderer.domElement);
function update(){
renderer.render( scene, camera );
requestAnimationFrame( update );
}
update();
mtl_loader = new THREE.MTLLoader();
mtl_loader.load("assets/doughnut.mtl",
function(materials) {
materials.preload()
var obj_loader = new THREE.OBJLoader();
obj_loader.setMaterials(materials)
obj_loader.load("assets/doughnut.obj",
function(object) {
let mesh = object.children[0]
scene.add(mesh);
}, null, function(error) {alert(error)}
)
}, null, function(error) {alert(error)}
);
Related
So I'm trying to upload a .obj file that also has multiple .png and .jpg files that are it's textures. The problem is I'm not sure how to even handle all these textures when they are uploaded.
Heres my code so far:
var loader = new THREE.OBJLoader(manager);
loader.load(obj_path, function (obj) {
model = obj;
modelWithTextures = true;
model.traverse( function ( child ) {
if ( child.isMesh ) child.material.map = texture;
} );
var textureLoader = new THREE.TextureLoader( manager );
var i;
for (var i = 0; i < files.length; i++) {
file = files[i];
console.log('Texture Files:' + files[i].name);
var texture = textureLoader.load(files[i].name);
}
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
setCamera(model);
setSmooth(model);
model.position.set(0, 0, 0);
setBoundBox(model);
setPolarGrid(model);
setGrid(model);
setAxis(model);
scaleUp(model);
scaleDown(model);
fixRotation(model);
resetRotation(model);
selectedObject = model;
outlinePass.selectedObjects = [selectedObject];
outlinePass.enabled = false;
renderer.render( scene, camera );
scene.add(model);
});
As you can see I'm using the textureLoader but just not sure what to do.
I'm very new to threeJS and 3d models.
Any help or advice would be much appreciated.
Thank you.
In your code, you probably won't see very much, because you render the scene before you add the model to the scene. You should render the scene after you did any changes (unless you have a render loop with requestAnimationFrame). Loading textures also is asynchronous. Use the callback of the .load method to better react when things are finished loading, e.g. trigger render().
I would load the textures within model.traverse() callback. But you have to determine which texture belongs to which mesh. This depends on how your data is structured.
var files = ['mesh1_tex.jpg', 'mesh2_tex.jpg'];
var loader = new THREE.OBJLoader( manager );
var textureLoader = new THREE.TextureLoader( manager );
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.set( 0, 0, -100); // depends on the size and location of your loaded model
var renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
var scene = new THREE.Scene();
loader.load(obj_path, function ( model ) {
model.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
// here you have to find a way how to choose the correct texture for the mesh
// the following is just an example, how it could be done, but it depends on your data
const file = files.find( f => f === child.name + '_tex.jpg');
if (!file) {
console.warn(`Couldn't find texture file.`);
return;
}
textureLoader.load(file, ( texture ) => {
child.material.map = texture;
child.material.needsupdate = true;
render(); // only if there is no render loop
});
}
} );
scene.add( model );
camera.lookAt( model ); // depends on the location of your loaded model
render(); // only if there is no render loop
});
function render() {
renderer.render( scene, camera );
}
Disclaimer: I just wrote down this code without testing.
I am stuck with loading in two .obj models into two different div elements.
Currently, both objects end up in the last div element, as seen here:
https://casagroupproject.github.io/template1/test.html
My code is based on this example here:
https://threejs.org/examples/?q=mul#webgl_multiple_elements
I create an array with my models stored in:
var canvas;
var scenes = [], renderer;
var scene;
//external geometries
var models = {
tent: {
obj:"./assets/Tent_Poles_01.obj",
},
campfire: {
obj:"./assets/Campfire_01.obj",
}}
init();
animate();
I then load them in a loop in init():
for( var _key in models ){
scene = new THREE.Scene();
var element = document.createElement( "div" );
element.className = "list-item";
element.innerHTML = template.replace( '$', _key);
console.log('does this work', element.innerHTML);
scene.userData.element = element.querySelector( ".scene" );
content.appendChild( element );
var camera = new THREE.PerspectiveCamera( 50, 1, 1, 10 );
camera.position.z = 2;
scene.userData.camera = camera;
var objLoader = new THREE.OBJLoader();
objLoader.load(
models[_key].obj,
function ( object ) {
scene.add( object );
console.log(object);
},
);
}
And render them here:
renderer = new THREE.WebGLRenderer( { canvas: canvas, antialias: true } );
renderer.setClearColor( 0xffffff, 1 );
renderer.setPixelRatio( window.devicePixelRatio );
Why do both models end up in the last div?
I am building a 3D Visualization and Interactive application using threejs.Following are the key functionalities I want to provide in this application:
In this User should be able to:
Rotate and Scale the Obj. -- done
Manipulate some certain parts of the Obj like, changing its color, replace that part with another. -- pending
I am following the vast threejs
documentation
and its list of examples, which
really helped me a lot and I am able to achieve a little.
Also I have come across an useful threejs inspector Chrome
Ext.
This threejs inspector Chrome Ext all in all does everything what I want to achieve, but unfortunately I am not able to understand that how does it work and how does it able to select and manipulate the parts of an Obj file.
I am using the following piece of code using threejs for now to just display, rotate and scale the Obj file.
Updated Code:
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, camera, controls, scene, renderer, mesh;
var mtlObject = {};
var strDownloadMime = "image/octet-stream";
init();
animate();
function init() {
var saveLink = document.createElement('div');
saveLink.style.position = 'absolute';
saveLink.style.top = '10px';
saveLink.style.width = '100%';
saveLink.style.color = 'white !important';
saveLink.style.textAlign = 'center';
saveLink.innerHTML ='Save Frame';
document.body.appendChild(saveLink);
document.getElementById("saveLink").addEventListener('click', saveAsImage);
renderer = new THREE.WebGLRenderer({
preserveDrawingBuffer: true
});
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 500;
controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 2.0;
controls.zoomSpeed = 2.0;
controls.panSpeed = 2.0;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
controls.keys = [ 65, 83, 68 ];
controls.addEventListener( 'change', render );
// world
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
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 ) { };
//mtl loader
THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( 'obj/' );
mtlLoader.load( 'arm.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.setPath( 'obj/' );
objLoader.load( 'arm.obj', function ( object ) {
object.name = "object_name";
object.position.y = - 95;
scene.add( object );
//As 'TheJim01' suggested
//I have used an object variable.
//then traverse through the scene nodes
//and target some particular parts of the obj as:
var nameToObject = {};
scene.traverse( function( node ) {
nameToObject[node.name] = node;
if (node.name == ("Pad01")) {
node.visible = false;
}
if (node.name == ("Arm_01")) {
node.visible = false;
}
if (node.name == ("Pad02")) {
node.visible = false;
}
if (node.name == ("Arm_02")) {
node.visible = false;
}
});
}, onProgress, onError );
});
// lights
var light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 1, 1, 1 );
scene.add( light );
var light = new THREE.DirectionalLight( 0x002288 );
light.position.set( -1, -1, -1 );
scene.add( light );
var light = new THREE.AmbientLight( 0x222222 );
scene.add( light );
// renderer
renderer = new THREE.WebGLRenderer( { antialias: false } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container = document.getElementById( 'container' );
container.appendChild( renderer.domElement );
//
window.addEventListener( 'resize', onWindowResize, false );
//
render();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
controls.handleResize();
render();
}
function animate() {
requestAnimationFrame( animate );
controls.update();
}
function render() {
renderer.render( scene, camera );
}
//my next challenge is to save the canvas as image
//after making all the changes to the obj file
function saveAsImage() {
var imgData, imgNode;
try {
var strMime = "image/jpeg";
imgData = renderer.domElement.toDataURL(strMime);
saveFile(imgData.replace(strMime, strDownloadMime), "test.jpg");
} catch (e) {
console.log(e);
return;
}
}
var saveFile = function (strData, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
document.body.appendChild(link); //Firefox requires the link to be in the body
link.download = filename;
link.href = strData;
link.click();
document.body.removeChild(link); //remove the link when done
} else {
location.replace(uri);
}
}
$(document).ready(function() {
//Set Color of the Obj parts accordingly
$('#armblock').on('click', function(){
$(this).children('ul').slideToggle(400);
$(this).children('ul').children('li').on('click', function(){
$color = new THREE.Color($(this).css('backgroundColor'));
var selectedColor = '#' + $color.getHexString();
//As 'TheJim01' suggested
//I have used and object variable.
//then traverse through the scene nodes
//and target some perticular parts of the obj as:
var nameToObject = {};
scene.traverse( function( node ) {
nameToObject[node.name] = node;
if (node.name == ("Arm_01")) {
node.visible = true;
nameToObject["Arm_01"].material.color.set(selectedColor);
}
if (node.name == ("Arm_02")) {
node.visible = true;
nameToObject["Arm_02"].material.color.set(selectedColor);
}
});
});
});
$('#padblock').on('click', function(){
$(this).children('ul').slideToggle(400);
$(this).children('ul').children('li').on('click', function(){
$color = new THREE.Color($(this).css('backgroundColor'));
var selectedColor = '#' + $color.getHexString();
//As 'TheJim01' suggested
//I have used an object variable.
//then traverse through the scene nodes
//and target some particular parts of the obj as:
var nameToObject = {};
scene.traverse( function( node ) {
nameToObject[node.name] = node;
if (node.name == ("Pad01")) {
node.visible = true;
nameToObject["Pad01"].material.color.set(selectedColor);
}
if (node.name == ("Pad02")) {
node.visible = true;
nameToObject["Pad02"].material.color.set(selectedColor);
}
});
});
});
});
Please if anyone can help me out in this.
Thanks in advance and please comment if I am missing anything.
Update
Next Challenges
I am able to change the color of a particular node(part of the obj) but its not spontaneous as I have to click on the canvas/obj again to see the changes.
I am able to hide/show a particular node(part of the obj) but I want to replace that particular node(part of the obj) with another one.
I want to save the final obj file after making all the changes as an Image, but in future as an gif or video so that user can visualize 360deg view of the final product.
PS
TheJim01 helped me a lot into understanding the basic but very important concept of traversing the obj file and its parts.
That leads me to build at least closer to something what I want.
All three.js inspector is doing is parsing the scene, and displaying the various properties of the objects in an interactive UI.
Let's say you have an OBJ file arranged like this:
bike
frame
seat
drive
pedals
frontSprocket
chain
rearSprocket
rearWheel
steering
handlebars
fork
frontWheel
OBJLoader would create a scene hierarchy like this:
bike // THREE.Group
frame // THREE.Mesh
seat // THREE.Mesh
drive // THREE.Group
pedals // THREE.Mesh
frontSprocket // THREE.Mesh
chain // THREE.Mesh
rearSprocket // THREE.Mesh
rearWheel // THREE.Mesh
steering // THREE.Group
handlebars // THREE.Mesh
fork // THREE.Mesh
frontWheel // THREE.Mesh
three.js inspector displays this same hierarchy, using the names of the objects. When you click on an object in its tree, it references the object in the scene, and grabs/displays its properties, such as its position, rotation, visible state, etc. When you make a change in the three.js inspector UI, it sets the value on the object in the scene, resulting in the changes you see.
You can do all of this yourself, and you don't even need to be so general about it. Say you want to create a map of object name to the scene object for easier reference (searching the scene is fast enough, but it's recursive). So you could do this:
var nameToObject = {};
scene.traverse(function(node){
// watch out for duplicate empty names!
nameToObject[node.name] = node;
});
(That doesn't give you the hierarchy, but this is just an example.)
Now you can get and update any object by name:
// enlarge the rear tire
nameToObject["rearTire"].scale.addScalar(0.1);
You can read and set all properties of the object. For example, if MTLLoader created a basic material for the frame, you could do something like this:
// make the frame red
nameToObject["frame"].material.color.setRGB(1.0, 0.0, 0.0);
Or you could outright replace the entire material.
For your example of replacing an object, let's say you already loaded a new Mesh called newRearTire...
// replace the rear tire
var drive = nameToObject["drive"]; // the parent of rearTire
drive.remove(nameToObject["rearTire"]);
drive.add(newRearTire);
(Of course you would need to re-build your name map at this point.)
These are just very general examples, but should get you started. If you encounter any problems accessing your data, leave a comment and I'll try to clarify.
texture is not loaded in to ring 3d model.but it will work for some other objects.there is no compile errors.I set the all all light condition correctly.but 3d model color is grey/black.texture loaded for other object correctly.3d object file format is .obj,I didn't load mtl file to my code. mtlobjloader is not in threejs.org,there are someway to load mtl file and mapping the texture to object.
plz help me.
enter code here
<html>
<head>
<title> Test Three.js</title>
<style type="text/css">
BODY
{
margin: 0;
}
canvas
{
width: 100%;
height:100%;
}
</style>
</head>
<body>
<div>
<p>Color:
<button class="jscolor{onFineChange:'onClick(this)',valueElement:null,value:'66ccff'}"
style="width:50px; height:20px;"></button>
</p>
<p>Object:
<button style="width:50px; height:20px;" id="object"></button>
</p>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="three.min.js"></script>
<script src="TrackballControls.js"></script>
<script src="jscolor.js"></script>
<script src="AmbientLight.js"></script>
<script src="SpotLight.js"></script>">
<script src="JSONLoader.js"></script>">
<script src="ObjectLoader.js"></script>">
<script src="OBJLoader.js"></script>">
<script src="MTLLoader.js"></script>">
<script src="Material.js"></script>">
<script src="MeshPhongMaterial.js"></script>">
<script>
function onClick(jscolor) {
cube.material.color = new THREE.Color('#'+jscolor);
cube.material.needsUpdate = true;
};
var onClicked=function (){
scene.remove(cube);
var material1 = new THREE.LineBasicMaterial({
color: 'red'
});
var geometry1 = new THREE.Geometry();
geometry1.vertices.push(
new THREE.Vector3( -10, 0, 0 ),
new THREE.Vector3( 0, 10, 0 ),
new THREE.Vector3( 10, 0, 0 )
);
var cube1 = new THREE.Line( geometry1, material1 );
scene.add( cube1);
};
$('#object').click(onClicked);
var scene =new THREE.Scene();
var camera=new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,0.1,1000);
var controls =new THREE.TrackballControls(camera);
controls.addEventListener('change',render);
var renderer = new THREE.WebGLRenderer( { alpha: true });
renderer.setSize(window.innerWidth,window.innerHeight);
document.body.appendChild(renderer.domElement);
/*var material = new THREE.MeshLambertMaterial({color:'red'});
var geometry=new THREE.CubeGeometry(100,100,100);
var cube=new THREE.Mesh(geometry,material);
scene.add(cube);*/
camera.position.z=500;
var light = new THREE.AmbientLight( 0x404040 );
light.intensity = 0;
light.position.z=10;
light.position.y=10; // soft white light
scene.add( light );
// }
//init();
/* var loader = new THREE.JSONLoader();
loader.load( 'ring.json', function ( geometry ) {
var mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
mesh.position.x =500;
mesh.position.y =100;
mesh.position.z =500;
scene.add( mesh );
}); *//*
var loader = new THREE.ObjectLoader();
loader.load("ring.json",function ( obj ) {
THREE.ImageUtils.crossOrigin = '';
var texture = THREE.TextureLoader("images.jpg");
//obj.map= texture;
obj.scale.set (10,10,10);
obj.traverse( function( child ) {
if ( child instanceof THREE.Mesh ) {
child.geometry.computeVertexNormals();
child.material.map=texture;
}
} );
scene.add( obj );
});*/
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
var texture = new THREE.Texture();
var loader = new THREE.ImageLoader( manager );
// You can set the texture properties in this function.
// The string has to be the path to your texture file.
loader.load( 'brick_bump.jpg', function ( image ) {
texture.image = image;
texture.needsUpdate = true;
// I wanted a nearest neighbour filtering for my low-poly character,
// so that every pixel is crips and sharp. You can delete this lines
// if have a larger texture and want a smooth linear filter.
// texture.magFilter = THREE.NearestFilter;
//texture.minFilter = THREE.NearestMipMapLinearFilter;
} );
var loader = new THREE.OBJLoader(manager);
/*var Mloader= new THREE.MTLLoader(manager);
Mloader.load('ring.mtl',function(object){
object.traverse( function ( child ) {
if (child.material instanceof THREE.MeshPhongMaterial ) {
child.material.map = texture;
}
} );
scene.add( object );
});*/
// As soon as the OBJ has been loaded this function looks for a mesh
// inside the data and applies the texture to it.
loader.load( 'ring1.obj', function ( event ) {
var object = event;
/*for ( var i = 0, l = object.children.length; i < l; i ++ ) {
object.children[ i ].material.map = texture;
console.log("rgr"+ object);
}*/
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material.map = texture;
console.log("rgr"+ object.children);
}
} );
// My initial model was too small, so I scaled it upwards.
object.scale = new THREE.Vector3( 25, 25, 25 );
// You can change the position of the object, so that it is not
// centered in the view and leaves some space for overlay text.
object.position.y -= 2.5;
scene.add( object );
});
function render(){
renderer.render(scene,camera);
}
function animate(){
requestAnimationFrame(animate);
controls.update();
}
animate();
</script>
</body>
</html>
First I would check the ring.obj file. You'll need to verify that the ring.obj file is exporting with UV values on all vertexes. UV values assign points on the texture to specific points on the mesh. E.g. they define how the texture is draped over the surface. If you do not have control of the ring.obj export process to quality assure it, there was a conversation on stack about generating UVs at load time here:
THREE.js generate UV coordinate
But your milage may vary if the mesh author had specific texture anchors.
This may not be the issue, but since the texture is working for other meshes, I would think there is an issue with the ring mesh.
first, i have already read this question didn't help
How i do: first i export a model from C4D to .ojb. Then i import the obj into www.trheejs/editor
I fill all the blank
then from the tree i select my object and export it to a Threejs Object, it save a .json file
My code
<script>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var kiss = new THREE.Object3D(), loader = new THREE.JSONLoader(true);
loader.load( "brikk2.json", function ( geometry, materials ) {
var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( { color: 0xff0000, ambient: 0xff0000 } ) );
scene.add( mesh );
});
var render = function () {
requestAnimationFrame(render);
renderer.render(scene, camera);
};
render();
</script>
When i run i have theses error messages
THREE.WebGLRenderer 67 three.js:20806
THREE.WebGLRenderer: elementindex as unsigned integer not supported. three.js:26942
XHR finished loading: "http://xxxxxx.xx/tst/mrdoob-three2/brikk2.json". three.js:12018
THREE.JSONLoader.loadAjaxJSON three.js:12018
THREE.JSONLoader.load three.js:11942
load test.html:23
(anonymous function) test.html:28
Uncaught TypeError: Cannot read property 'length' of undefined three.js:12087
parseModel three.js:12087
THREE.JSONLoader.parse three.js:12028
xhr.onreadystatechange three.js:11969
the Json i load
{
"metadata": {
"version": 4.3,
"type": "Object",
"generator": "ObjectExporter"
},
"geometries": [
{
"uuid": "213E28EF-E388-46FE-AED3-54695667E086",
"name": "brikkG",
"type": "Geometry",
"data": {
"vertices": [0.036304,-0.016031,-0.027174,0.036304,0.......
........ 232,1228,1139,1141,1140,1]
}
}],
"materials": [
{
"uuid": "F74C77E4-8371-41BC-85CA-31FC96916CC6",
"name": "lego",
"type": "MeshPhongMaterial",
"color": 16721408,
"ambient": 16777215,
"emissive": 0,
"specular": 16777215,
"shininess": 30,
"opacity": 1,
"transparent": false,
"wireframe": false
}],
"object": {
"uuid": "3BAAB8CA-1EB7-464A-8C6D-FC4BBB3C63C6",
"name": "BrikkM",
"type": "Mesh",
"geometry": "213E28EF-E388-46FE-AED3-54695667E086",
"material": "F74C77E4-8371-41BC-85CA-31FC96916CC6",
"matrix": [1000,0,0,0,0,1000,0,0,0,0,1000,0,0,0,0,1]
}
}
structure of the json file
basically i have tried all i have read about importing native json into ThreeJS, i tried files from the treejs/editor or clara.io still have the same error message, i have no idea anymore, i spend 3 days trying all the way i read to solve this.
If i try to create geometry like CubeGeometry it render without problems, but at soon as i try with native json, nothing work anymore
somebody could help ?
Ok, i found the answer here: http://helloenjoy.com/2013/from-unity-to-three-js/
the native json code is perfect, it's just no be mean to be loaded with JSONLoader but with ObjectLoader (do not mismatch with OBJLoader like i did i one of my experiment). JSONLoader is mean to load json, but with a different format/structure. ObjectLoader is mean to load native format that is also written in json but with a native structure/format.
so use
var loader = new THREE.ObjectLoader();
loader.load( 'brikk2.json', function ( object ) {
scene.add( object );
} );
and it's working
full example code
<body>
<script src="build/three.min.js"></script>
<script>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setClearColor( 0xffffff, 1);
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var ambient = new THREE.AmbientLight( 0x101030 );
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 );
scene.add( directionalLight );
var loader = new THREE.ObjectLoader();
loader.load( 'brikk2.js', function ( object ) {
scene.add( object );
} );
camera.position.z = 5;
var render = function () {
requestAnimationFrame(render);
renderer.render(scene, camera);
};
render();
</script>
</body>
EDIT
The top code i showed in the top question was right but it was for Geometry loading
loader = new THREE.JSONLoader();
loader.load( 'ugeometry.json', function ( geometry ) {
mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { envMap: THREE.ImageUtils.loadTexture( 'environment.jpg', new THREE.SphericalReflectionMapping() ), overdraw: 0.5 } ) );
scene.add( mesh );
So the recap.
if from threes/editor or Clara.io you save GEOMETRY use JSONLoader, if you save as OBJECT use ObjectLoader, and if you save as SCENE they should be a SceneLoader (unverified)