I have a .obj and .mtl which load textures from .tga files. This all seems to work / look fine in 3D modeling software, but when loaded with three.js (THREE.WebGLRenderer({ antialias: true })) some of the object's children, (specifically between the knees and the calves, but not, for example, the pockets and legs), seem to have a transparent jagged gap / empty triangles.
(Tried turning on antialiasing, changing the overdraw value, turning off transparency, etc.)
Loader function:
threejsHelper.helpers.loadObject('objects/pants/MaleBaggyPants.obj', 'objects/pants/MaleBaggyPants.mtl', {
blinn1SG: (new THREE.MeshPhongMaterial({ color: 0xffffff, transparent: false, opacity: 1.0, overdraw: 0.5, map: threejsHelper.helpers.loadTexture(app.manager, 'objects/pants/button.tga') })),
blinn2SG: (new THREE.MeshPhongMaterial({ color: 0xffffff, transparent: false, opacity: 1.0, overdraw: 0.5, map: threejsHelper.helpers.loadTexture(app.manager, 'objects/pants/back.tga') })),
blinn4SG: (new THREE.MeshPhongMaterial({ color: 0xffffff, transparent: false, opacity: 1.0, overdraw: 0.5, map: threejsHelper.helpers.loadTexture(app.manager, 'objects/pants/front.tga') })),
blinn5SG: (new THREE.MeshPhongMaterial({ color: 0xffffff, transparent: false, opacity: 1.0, overdraw: 0.5, map: threejsHelper.helpers.loadTexture(app.manager, 'objects/pants/pocket.tga') })),
blinn6SG: (new THREE.MeshPhongMaterial({ color: 0xffffff, transparent: false, opacity: 1.0, overdraw: 0.5, map: threejsHelper.helpers.loadTexture(app.manager, 'objects/pants/back.tga') })),
blinn7SG: (new THREE.MeshPhongMaterial({ color: 0xffffff, transparent: false, opacity: 1.0, overdraw: 0.5, map: threejsHelper.helpers.loadTexture(app.manager, 'objects/pants/front.tga') }))
}, function (object) {
object.rotation.x = (-90*Math.PI/180);
object.rotation.z = (-90*Math.PI/180);
app.scene.add(object);
app.ready = true;
});
Helper functions:
...
loadTexture: function (manager, path) {
var texture;
if (path.split('.').pop() == 'tga') {
var loader = new THREE.TGALoader();
texture = loader.load(path);
} else {
texture = new THREE.Texture();
var loader = new THREE.ImageLoader(manager);
loader.load(path, function (image) {
texture.image = image;
texture.needsUpdate = true;
});
}
return texture;
},
loadMaterial: function (mtlPath, textures, complete) {
var loader = new THREE.MTLLoader();
loader.load(mtlPath, function (materials) {
materials.preload();
if (!!materials.materials) {
for (var key in materials.materials) {
if (key in textures) {
materials.materials[key] = textures[key];
}
}
}
complete(materials);
});
},
loadObject: function (objPath, mtlPath, textures, complete) {
app.helpers.loadMaterial(mtlPath, textures, function (materials) {
var loader = new THREE.OBJLoader();
loader.setMaterials(materials);
loader.load(objPath, function (object) {
complete(object);
});
});
},
...
You seem to have extra vertices along the seem on both the objects which I think will screw with the triangulation.
Remove these vertices that are not needed and I'm 99% sure it will fix your problem.
I also noticed the model is at a very small scale.
I had the same problem. Some triangle didn't properly render on Threejs while it properly rendered on my OpenGL app.
I solved this trouble by using Uint32Array instead of Uint16Array to define the index of the geometry. I just put this line of code and everything worked like a charm.
const indices = new Uint32Array(faceDict.index);
Related
I have some text rendering over a background quad. Let's call this a 'label'. Both are positioned at the same point which causes z-fighting.
I'd like to promote the text to avoid z-fighting using polygon offset.
This is how I add the polygon offset to the text material:
const material = new THREE.RawShaderMaterial(
CreateMSDFShader({
map: this.glyphs,
opacity: opt.opacity ?? 1,
alphaTest: (opt.opacity ?? 1) < 1 ? 0.001 : 1,
color: opt.colour ?? '#ffffff',
transparent: opt.transparent ?? true,
glslVersion: opt.renderMode === 'webgl' ? THREE.GLSL1 : THREE.GLSL3,
side: opt.side ?? THREE.DoubleSide,
depthFunc: opt.depthFunc ?? THREE.LessEqualDepth,
depthTest: true,
depthWrite: false,
polygonOffset: true,
polygonOffsetUnits: -1.0,
polygonOffsetFactor: -4.0,
})
);
const mesh = new THREE.Mesh(geom, material);
and this is the background material:
if (tableOptions.background) {
const geometry = new THREE.PlaneGeometry(1, 1, 1, 1);
const backgroundMaterial = new ActivatableMaterial(
{
color: new THREE.Color(tableOptions.backgroundColour),
toneMapped: false,
opacity: 1,
alphaTest: 0.001,
transparent: true,
},
{
activationColour: new THREE.Color(tableOptions.activationColour),
}
);
this.background = buildUIObject(
Actions.ExpandLabel as Action,
geometry,
backgroundMaterial
);
setName(this.background, 'Background');
this.tableGroup.add(this.background);
}
The polygon offset just isn't working (using Chrome). The text disappears behind the background quad as I orbit the camera around, and reappears at random. The labels are always facing the camera (using lookAt).
What could stop the polygon offset from working?
The labels are rendering to a renderpass with a render taget set up as follows:
const pars = {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
format: THREE.RGBAFormat,
stencilBuffer: false,
depthBuffer: false,
};
this.renderTargetBuffer = new THREE.WebGLRenderTarget(
resolution.x,
resolution.y,
pars
);
this.renderTargetBuffer.texture.name = 'RenderTargetBuffer';
this.renderTargetBuffer.texture.generateMipmaps = false;
I'm assuming that because the polygonOffset is a state thing it doesn't matter that this is a RawShaderMaterial. Is that a safe assumption?
Edit: I have added the opposite polygonOffset to the background mesh separately and again it doesn't work.
Polygon offset wasn't the best solution in this case. I switched to maintaining a custom order for the labels based on distance to the camera. That way I could force the text render order to be greater than the background.
I was using CanvasRenderer in my scenes to render a brain with neurons.
The problem is that when I draw the neurons (every neuron consists of many many lines) the scene is really slow because I render a lot of neurons. So I switched into WebGLRenderer and it is much faster and smoother, but the scene looked completely different! No opacity is applied any more which made the neurons hidden inside the brain
Here is a comparison between the two scenes:
CanvasRenderer:
The brain has some transparency, and there is a green sphere represents a region of interest (ROI) also has transparency.
WebGLRenderer:
The transparency has completely gone!
I am using the following materials for the brain model and the ROI model:
var brain_material = new THREE.MeshPhongMaterial({
wireframe: false,
color: 0xaaaaaa,
specular: 0xcccccc,
opacity: 0.4
});
var roi_material = new THREE.MeshBasicMaterial({
color: selected_roi_color,
opacity: 0.2,
visible: true
})
and here is my renderer:
renderer = new THREE.WebGLRenderer({alpha:true});
renderer.setClearColor(renderer_clear_color);
renderer.setPixelRatio(viewport_width / viewport_height);
renderer.setSize(viewport_width, viewport_height);
renderer.sortObjects = false;
container.appendChild(renderer.domElement);
How can I get a similar result to the CanvasRenderer using the WebGLRenderer?
Thank you very much
If you use opacity, then you have to use it with transparent:
var brain_material = new THREE.MeshPhongMaterial({
wireframe: false,
color: 0xaaaaaa,
specular: 0xcccccc,
transparent: true, // here
opacity: 0.4
});
var roi_material = new THREE.MeshBasicMaterial({
color: selected_roi_color,
transparent: true, // here
opacity: 0.2,
visible: true
})
I'm creating a cube and I apply 6 different textures to each of it's faces. Each texture is a .png file and contains transparent parts. I'm also applying a color to the cube - I want to see that color trough png transparency.
Problem: Transparency renders as white color so I cannot see the base color of the cube (which renders ok if I remove the png texture)
How can I make the png transparency work? I tried playing with some material settings but none make it transparent.
Code for creating the cube and materials:
var geometry = new THREE.CubeGeometry(150, 200, 150, 2, 2, 2);
var materials = [];
// create textures array for all cube sides
for (var i = 1; i < 7; i++) {
var img = new Image();
img.src = 'img/s' + i + '.png';
var tex = new THREE.Texture(img);
img.tex = tex;
img.onload = function () {
this.tex.needsUpdate = true;
};
var mat = new THREE.MeshBasicMaterial({color: 0x00ff00, map: tex, transparent: true, overdraw: true });
materials.push(mat);
}
cube = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
cube.position.y = 150;
scene.add(cube);
EDIT:
Picture below shows the problem - with senthanal solution the left texture now renders ok - it is a png image without transparency - I set the transparency in code with
materialArray.push(new THREE.MeshBasicMaterial({ map: THREE.ImageUtils.loadTexture('img/s2.png'), transparent: true, opacity: 0.9, color: 0xFF0000 }));
The right texture is also a png image - only that it has a transparent area (all that renders white should be pure red since it is transparent and should take the color from the cube?). How can I make that white part transparent?
the opacity attribute of material does the trick for you. Follows, example code snippet:
var materialArray = [];
materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/xpos.png' ), transparent: true, opacity: 0.5, color: 0xFF0000 }));
materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/xneg.png' ), transparent: true, opacity: 0.5, color: 0xFF0000 }));
materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/ypos.png' ), transparent: true, opacity: 0.5, color: 0xFF0000 }));
materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/yneg.png' ), transparent: true, opacity: 0.5, color: 0xFF0000 }));
materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/zpos.png' ), transparent: true, opacity: 0.5, color: 0xFF0000 }));
materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/zneg.png' ), transparent: true, opacity: 0.5, color: 0xFF0000 }));
var MovingCubeMat = new THREE.MeshFaceMaterial(materialArray);
var MovingCubeGeom = new THREE.CubeGeometry( 50, 50, 50, 1, 1, 1, materialArray );
MovingCube = new THREE.Mesh( MovingCubeGeom, MovingCubeMat );
MovingCube.position.set(0, 25.1, 0);
scene.add( MovingCube );
http://threejs.org/docs/#Reference/Materials/Material The key is to set transparent attribute true and set opacity to 0.5(for example).
Add the second the cube which fits inside exactly with no transparency, idea from #WestLangley ( Three.js canvas render and transparency )
backCube = new THREE.Mesh( MovingCubeGeom, new THREE.MeshBasicMaterial( { color: 0xFF0000 }) );
backCube.position.set(0, 25.1, 0);
backCube.scale.set( 0.99, 0.99, 0.99 );
scene.add( backCube );
for those looking for a simple transparent png import helper:
import { MeshBasicMaterial, TextureLoader } from 'three'
export const importTexture = async(url, material) => {
const loader = new TextureLoader()
const texture = await loader.loadAsync(url)
material.map = texture
material.transparent = true
material.needsUpdate = true
return texture
}
//usage
const geo = new PlaneGeometry(1, 1)
const mat = new MeshBasicMaterial()
const mesh = new Mesh(geo, mat)
scene.add(mesh)
//this is asynchronous
importTexture('path/to/texture.png', mat)
I'm trying to define a material to meshes I loaded in from OBJLoader through the following wrapper function:
function applyTexture(src){
var texture = new THREE.Texture();
var loader = new THREE.ImageLoader();
loader.addEventListener( 'load', function ( event ) {
texture.image = event.content;
texture.needsUpdate = true;
// find the meshes from the loaded OBJ and apply the texture to it.
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
if(child.name.indexOf("Lens") < 0){
child.dynamic = true;
child.material = new THREE.MeshLambertMaterial( { color: 0xdddddd, shading: THREE.FlatShading, map : texture } );
// also tried:
//child.material = new THREE.MeshPhongMaterial( { color: 0x000000, specular: 0x666666, emissive: 0x000000, ambient: 0x000000, shininess: 10, shading: THREE.SmoothShading, map : texture} );
// and:
//child.material = new THREE.MeshBasicMaterial({map : texture});
child.material.map = texture; // won't throw the WebGL Warning, but won't show the texture either;
} else {
// works just fine.
child.material = new THREE.MeshPhongMaterial( { color: 0x000000, specular: 0x666666, emissive: 0x000011, ambient: 0x000000, shininess: 10, shading: THREE.SmoothShading, opacity: 0.6, transparent: true } );
}
}
});
});
loader.load( src );
}
When the texture has loaded and it's time to apply the material to the mesh, I start getting the following warning on the console:
.WebGLRenderingContext: GL ERROR :GL_INVALID_OPERATION : glDrawElements: attempt to access out of range vertices in attribute 0
and the mesh itself disappears.
what am I doing wrong here?
UPDATE
As #WestLangley pointed on the comments: Never try to apply texture/materials after things have been rendered. Create the materials before rendering the object to the scene and then change them using:
obj.material.map = texture
With WebGLRenderer, you can't switch from a material without a texture, to a material with a texture, after the mesh has been rendered once. This is because, without an initial texture, the geometry will not have the necessary baked-in WebGL UV buffers.
A work-around is to begin with a material having a simple white texture.
UPDATE: Alternatively, you can begin with a textureless material, and then set the following flags when a texture is added:
material.needsUpdate = true;
geometry.buffersNeedUpdate = true;
geometry.uvsNeedUpdate = true;
three.js r.58
I also got this error while loading a scene from blender. For me the problem was fixed when unwrapping the uv's for each mesh i want to have a texture on.
I've the custom geometry with sqaure-base and it looks like a cone. here is jsfiddle link: http://jsfiddle.net/suvKg/18/
I've obtained transparency to the whole object at here:
var meshMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, opacity: 0.6, depthWrite: false, depthTest: false, vertexColors: THREE.VertexColors } );
But I don't want transparency to be applied to base of the cone, but only side faces should have it. How to do that?
you need to use THREE.MeshFaceMaterial() for your entire mesh. For example if your geometry have X faces and 2 differents materials :
var materials = [
new THREE.MeshLambertMaterial( { color: 0xffffff, opacity: 0.6, depthWrite: false, depthTest: false, vertexColors: THREE.VertexColors } ),
new THREE.MeshLambertMaterial( { color: 0xffffff, opacity: 1, depthWrite: false, depthTest: false, vertexColors: THREE.VertexColors } )
]; // the two materials
var mesh = new THREE.Mesh(yourGeometry, new THREE.MeshFaceMaterial(materials)); //tell three.js that you will have several materials in your geometry
Then, you will need to determine materialIndex manualy in each of your faces based on the materials indexes
yourGeometry.faces[0].materialIndex = 0;
yourGeometry.faces[1].materialIndex = 0;
yourGeometry.faces[2].materialIndex = 1; // <= the cone base
...
yourGeometry.faces[lastFaceIndex].materialIndex = 0;
NB: default parameter for materialIndex is 0 so you will need to determine only one face to its material index in your case