I have a simple box following a path created using the CatmullRomCurve3.
I'd like to have all the curves/edges to be more sharp. But I couldn't figure how to achieve this. Also not sure if I'm using the right type of curve for making paths.
<script src="https://ajax.googleapis.com/ajax/libs/threejs/r76/three.min.js"></script>
<header>
<style>
body canvas{
width: 100%,
height: 100%;
margin:0;
padding:0;
}
</style>
</header>
<body>
</body>
<script>
var renderer, camera, scene, controls, box, path, speed = 0,
path_progress = 0,
axis = new THREE.Vector3(),
tangent = new THREE.Vector3(),
up = new THREE.Vector3(1, 0, 0);
function initRenderer(){
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize( window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.setClearColor(0x264d73, 1);
}
function initScene(){
scene = new THREE.Scene();
}
function initCamera(){
camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 1, 10000);
camera.position.set(0, 40, 40);
camera.lookAt(scene.position);
scene.add(camera);
//controls = new THREE.OrbitControls( camera , renderer.domElement );
}
function initLights(){
var aLight = new THREE.AmbientLight(0xD0D0D0, 0.5);
scene.add(aLight);
}
////// Initializers ////////////////////////
function add_path(){
path = new THREE.CatmullRomCurve3( [
new THREE.Vector3( 3.4000015258789062, 0, 3.4000015258789062 ),
new THREE.Vector3( 10.600006103515625, 0, 3.4000015258789062 ),
new THREE.Vector3( 10.600006103515625, 0, 10.600006103515625 ),
new THREE.Vector3( 3.4000015258789062, 0, 10.600006103515625 )
]);
path.closed = true;
speed = 0.4 / path.getLength();
var material = new THREE.LineBasicMaterial({
color: 0xff00f0,
});
var geometry = new THREE.Geometry();
var splinePoints = path.getPoints(20);
for (var i = 0; i < splinePoints.length; i++) {
geometry.vertices.push(splinePoints[i]);
}
var line = new THREE.Line(geometry, material);
scene.add(line);
add_box(splinePoints[0]);
}
function add_box( pos ){
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var materials = [
new THREE.MeshBasicMaterial({
color: 0x80bfff,
}),
new THREE.MeshLambertMaterial({
color: 0x80bfff
}),
new THREE.MeshLambertMaterial({
color: 0x001a33
}),
new THREE.MeshLambertMaterial({
color: 0x80bfff
}),
new THREE.MeshLambertMaterial({
color: 0x80bfff
}),
new THREE.MeshLambertMaterial( {
color: 0x80bfff
})
];
var material = new THREE.MeshFaceMaterial( materials );
box = new THREE.Mesh( geometry, material );
box.scale.set( 1, 1, 1 );
box.position.copy( pos ); //// x,y,z ////
box.rotation.set( 0 , 0 , 0 );
scene.add( box );
camera.position.copy( box.position )
camera.position.x += 20;
camera.position.y += 10;
camera.lookAt(box.position);
setInterval( function(){
follow_path();
}, 100);
}
function follow_path(){
if( path !== null ){
if ( path_progress <= 1) {
camera.lookAt(box.position);
var pos = this.path.getPointAt( this.path_progress );
box.position.copy( pos );
tangent = this.path.getTangentAt( this.path_progress ).normalize();
axis.crossVectors( this.up, this.tangent).normalize();
var radians = Math.acos( this.up.dot(this.tangent) );
box.quaternion.setFromAxisAngle( this.axis, radians );
path_progress += speed;
}else{
path_progress = 0;
}
}
}
///// Mouse events ////////
///// Main /////////
function main(){
//console.log(" Initializing: ");
initRenderer(window.innerWidth, window.innerHeight );
initScene();
initCamera(window.innerWidth, window.innerHeight );
initLights();
add_path();
animate();
}
function animate(){
window.requestAnimationFrame( animate );
render_all();
}
function render_all(){
renderer.render(scene, camera);
}
main();
</script>
It seems that setting the path type = 'catmullrom' and setting the tension=0.1 solved the problem.
<script src="https://ajax.googleapis.com/ajax/libs/threejs/r76/three.min.js"></script>
<header>
<style>
body canvas{
width: 100%,
height: 100%;
margin:0;
padding:0;
}
</style>
</header>
<body>
</body>
<script>
var renderer, camera, scene, controls, box, path, speed = 0,
path_progress = 0,
axis = new THREE.Vector3(),
tangent = new THREE.Vector3(),
up = new THREE.Vector3(1, 0, 0);
function initRenderer(){
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize( window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.setClearColor(0x264d73, 1);
}
function initScene(){
scene = new THREE.Scene();
}
function initCamera(){
camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 1, 10000);
camera.position.set(0, 40, 40);
camera.lookAt(scene.position);
scene.add(camera);
//controls = new THREE.OrbitControls( camera , renderer.domElement );
}
function initLights(){
var aLight = new THREE.AmbientLight(0xD0D0D0, 0.5);
scene.add(aLight);
}
////// Initializers ////////////////////////
function add_path(){
path = new THREE.CatmullRomCurve3( [
new THREE.Vector3( 3.4000015258789062, 0, 3.4000015258789062 ),
new THREE.Vector3( 10.600006103515625, 0, 3.4000015258789062 ),
new THREE.Vector3( 10.600006103515625, 0, 10.600006103515625 ),
new THREE.Vector3( 3.4000015258789062, 0, 10.600006103515625 )
]);
path.closed = true;
path.type = "catmullrom";
path.tension = 0.1;
speed = 0.4 / path.getLength();
var material = new THREE.LineBasicMaterial({
color: 0xff00f0,
});
var geometry = new THREE.Geometry();
var splinePoints = path.getPoints(20);
for (var i = 0; i < splinePoints.length; i++) {
geometry.vertices.push(splinePoints[i]);
}
var line = new THREE.Line(geometry, material);
scene.add(line);
add_box(splinePoints[0]);
}
function add_box( pos ){
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var materials = [
new THREE.MeshBasicMaterial({
color: 0x80bfff,
}),
new THREE.MeshLambertMaterial({
color: 0x80bfff
}),
new THREE.MeshLambertMaterial({
color: 0x001a33
}),
new THREE.MeshLambertMaterial({
color: 0x80bfff
}),
new THREE.MeshLambertMaterial({
color: 0x80bfff
}),
new THREE.MeshLambertMaterial( {
color: 0x80bfff
})
];
var material = new THREE.MeshFaceMaterial( materials );
box = new THREE.Mesh( geometry, material );
box.scale.set( 1, 1, 1 );
box.position.copy( pos ); //// x,y,z ////
box.rotation.set( 0 , 0 , 0 );
scene.add( box );
camera.position.copy( box.position )
camera.position.x += 20;
camera.position.y += 10;
camera.lookAt(box.position);
setInterval( function(){
follow_path();
}, 100);
}
function follow_path(){
if( path !== null ){
if ( path_progress <= 1) {
camera.lookAt(box.position);
var pos = this.path.getPointAt( this.path_progress );
box.position.copy( pos );
tangent = this.path.getTangentAt( this.path_progress ).normalize();
axis.crossVectors( this.up, this.tangent).normalize();
var radians = Math.acos( this.up.dot(this.tangent) );
box.quaternion.setFromAxisAngle( this.axis, radians );
path_progress += speed;
}else{
path_progress = 0;
}
}
}
///// Mouse events ////////
///// Main /////////
function main(){
//console.log(" Initializing: ");
initRenderer(window.innerWidth, window.innerHeight );
initScene();
initCamera(window.innerWidth, window.innerHeight );
initLights();
add_path();
animate();
}
function animate(){
window.requestAnimationFrame( animate );
render_all();
}
function render_all(){
renderer.render(scene, camera);
}
main();
</script>
Related
I'm trying to create an ocean for my Three.js application. I took the example from this site:
https://codepen.io/RemiRuc/pen/gJMwOe?fbclid=IwAR2caTQL-AOPE2Gv6x4rzSWBrOmAh2j-raqesOO0XbYQAuSG37imbMszSis
var params = {
res : 32,
speed : 8,
amp : 2,
wireframe : true,
backgroundColor : 0x9c81e3,
planeColor : 0x4a4a4a
}
var scene = new THREE.Scene();
scene.background = new THREE.Color(params.backgroundColor)
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 )
let canvas = document.getElementById("webgl")
var renderer = new THREE.WebGLRenderer({canvas:canvas, antialias: true})
renderer.setSize( window.innerWidth, window.innerHeight )
var simplex = new SimplexNoise()
var light = new THREE.AmbientLight( 0xcccccc ); // soft white light
scene.add( light );
var pointLight = new THREE.PointLight( 0xeeeeee, 1, 100 );
pointLight.position.set( 0, 20, -20 );
scene.add( pointLight );
let geometry, material, plane
createPlane()
camera.position.z = 5;
camera.position.y = 3;
camera.lookAt(new THREE.Vector3( 0, 3, 0 ))
var animate = function () {
requestAnimationFrame( animate );
for (var i = 0; i < geometry.vertices.length; i++) {
var z = (i + Date.now() * params.speed/100000)
geometry.vertices[i].z = simplex.noise4D(z,z,z,z) * params.amp
plane.geometry.verticesNeedUpdate = true;
}
scene.background = new THREE.Color(params.backgroundColor)
material.color = new THREE.Color(params.planeColor)
material.wireframe = params.wireframe
camera.rotation.y += 0.001
renderer.render( scene, camera );
};
animate();
function createPlane(){
geometry = new THREE.PlaneGeometry( 200, 200, params.res,params.res );
material = new THREE.MeshLambertMaterial( {color: params.planeColor, side: THREE.DoubleSide, wireframe: params.wireframe} );
plane = new THREE.Mesh( geometry, material );
scene.add( plane );
plane.rotation.x = Math.PI/2
}
/***RESIZE***/
window.addEventListener('resize', ()=>{
document.querySelector('canvas').style.width = window.innerWidth + "px"
document.querySelector('canvas').style.height = window.innerHeight + "px"
renderer.setSize( window.innerWidth, window.innerHeight )
camera.aspect = window.innerWidth / window.innerHeight
camera.updateProjectionMatrix()
})
var gui = new dat.GUI()
var controller = gui.add(params, "res", 0, 100).name("Plane resolution")
gui.add(params, "speed", 0, 500).name("Wave speed")
gui.add(params, "amp", 0, 20).name("Wave amplitude")
gui.add(params, "wireframe", 0, 20).name("Wireframe")
gui.addColor(params, "backgroundColor").name("Background color")
gui.addColor(params, "planeColor").name("Plane color")
controller.onChange(()=>{
scene.remove(plane)
createPlane()
})
Issue is, I'm using PlaneBufferGeometry instead of PlaneGeometry, and it seems there are some differences
My code in render after creating the waterPlane
for (var i = 0; i < waterGeometry.attributes.position.count; i++) {
var z = (i + Date.now() * params.speed/100000);
waterGeometry.attributes.position[i] = simplex.noise4D(z,z,z,z) * params.amp;
}
waterGeometry.attributes.position.needsUpdate = true;
waterPlaneMesh.attributes.position.needsUpdate = true;
I'm not getting any errors, but no matter what I do, all I get is a flat wireframe plane geometry that doesn't move or anything. I think issue is in the updating of the plane?
This is an example of how you can displace vertices of a buffer geometry, using that SimplexNoise library:
body {
margin: 0;
background-color: #000;
color: #fff;
font-family: Monospace;
font-size: 13px;
line-height: 24px;
overscroll-behavior: none;
}
<script type="module">
import * as THREE from "https://cdn.skypack.dev/three#0.136.0";
import { OrbitControls } from "https://cdn.skypack.dev/three#0.136.0/examples/jsm/controls/OrbitControls";
import { createNoise3D } from "https://cdn.skypack.dev/simplex-noise";
let simplex = createNoise3D();
let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 2000);
camera.position.set(0, 0.5, 1).setLength(12);
let renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
window.addEventListener("resize", onWindowResize);
//scene.add(new THREE.GridHelper())
let controls = new OrbitControls(camera, renderer.domElement);
let light = new THREE.DirectionalLight(0xffffff, 0.5);
light.position.setScalar(1);
scene.add(light, new THREE.AmbientLight(0xffffff, 0.5));
let v3 = new THREE.Vector3();
let v2 = new THREE.Vector2();
let g = new THREE.PlaneGeometry(200, 200, 100, 100);
g.rotateX(-Math.PI *0.5);
let m = new THREE.MeshLambertMaterial({color: "aqua", wireframe: false});
let o = new THREE.Mesh(g, m);
scene.add(o);
let clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
let t = clock.getElapsedTime();
for(let i = 0; i < g.attributes.position.count; i++){
v2.fromBufferAttribute(g.attributes.uv, i).addScalar(t * 0.01).multiplyScalar(20);
let h = simplex(v2.x, v2.y, t * 0.1);
g.attributes.position.setY(i, h);
}
g.computeVertexNormals();
g.attributes.position.needsUpdate = true;
});
function onWindowResize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
}
</script>
My project uses geometry where each face is its own mesh. I need to clip the geometry to cut away a portion of it and have a stenciled cap face cover the clipped edges. I examined and tinkered with the Three.js clipping stencil example and I understand how to use a stencil to cap trimmed solid geometry, but when I try it on collections of face geometries it doesn't work. Here is some code I have been tinkering with, based on the example:
body { margin: 0; }
canvas { display: block; }
<script type="module">
import * as THREE from 'https://unpkg.com/three#0.120.1/build/three.module.js';
import { OrbitControls } from 'https://unpkg.com/three#0.120.1/examples/jsm/controls/OrbitControls.js';
import { BufferGeometryUtils } from 'https://unpkg.com/three#0.120.1/examples/jsm/utils/BufferGeometryUtils.js';
var camera, scene, renderer;
var planes, planeObjects;
init();
animate();
function createPlaneStencilGroup( geometry, plane, renderOrder )
{
var group = new THREE.Group();
var baseMat = new THREE.MeshBasicMaterial();
baseMat.depthWrite = false;
baseMat.depthTest = false;
baseMat.colorWrite = false;
baseMat.stencilWrite = true;
baseMat.stencilFunc = THREE.AlwaysStencilFunc;
// back faces
var mat0 = baseMat.clone();
mat0.side = THREE.BackSide;
mat0.clippingPlanes = [ plane ];
mat0.stencilFail = THREE.IncrementWrapStencilOp;
mat0.stencilZFail = THREE.IncrementWrapStencilOp;
mat0.stencilZPass = THREE.IncrementWrapStencilOp;
var mesh0 = new THREE.Mesh( geometry, mat0 );
mesh0.renderOrder = renderOrder;
group.add( mesh0 );
// front faces
var mat1 = baseMat.clone();
mat1.side = THREE.FrontSide;
mat1.clippingPlanes = [ plane ];
mat1.stencilFail = THREE.DecrementWrapStencilOp;
mat1.stencilZFail = THREE.DecrementWrapStencilOp;
mat1.stencilZPass = THREE.DecrementWrapStencilOp;
var mesh1 = new THREE.Mesh( geometry, mat1 );
mesh1.renderOrder = renderOrder;
group.add( mesh1 );
return group;
}
function init()
{
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 36, window.innerWidth / window.innerHeight, 1, 100 );
camera.position.set( 2, 2, 2 );
initLights();
planes = [
new THREE.Plane( new THREE.Vector3( 0, - 1, 0 ), 0.42 ),
new THREE.Plane( new THREE.Vector3( 0, 0, - 1 ), 0.25 )
];
var material = new THREE.MeshStandardMaterial( {
color: 0x00ff00,
metalness: 0.1,
roughness: 0.75,
side: THREE.DoubleSide,
clippingPlanes: planes,
clipShadows: true,
shadowSide: THREE.DoubleSide,
} );
// Simple sphere geometry. Something I know works, for comparison.
var sphereGeom = new THREE.SphereBufferGeometry( 0.5, 32, 32 );
sphereGeom.translate( -1.1, 0, 0 );
// Make a cube out of 6 planes and merge them together
var planeGeoms = [];
for(var i = 0; i < 6; i++)
{
planeGeoms.push( new THREE.PlaneBufferGeometry( 1, 1 ) );
}
var mergedBufferGeom = BufferGeometryUtils.mergeBufferGeometries( planeGeoms );
// Set up clip plane rendering
planeObjects = [];
var planeGeom = new THREE.PlaneBufferGeometry( 4, 4 );
for ( var i = 0; i < 2; i ++ )
{
var poGroup = new THREE.Group();
var plane = planes[ i ];
var stencilGroup_sphere = createPlaneStencilGroup( sphereGeom, plane, i + 1 );
var stencilGroup_Box = createPlaneStencilGroup( mergedBufferGeom, plane, i + 1 )
// plane is clipped by the other clipping planes
var planeMat = new THREE.MeshStandardMaterial( {
color: 0x0000ff,
metalness: 0.1,
roughness: 0.75,
clippingPlanes: planes.filter( p => p !== plane ),
stencilWrite: true,
stencilRef: 0,
stencilFunc: THREE.NotEqualStencilFunc,
stencilFail: THREE.ReplaceStencilOp,
stencilZFail: THREE.ReplaceStencilOp,
stencilZPass: THREE.ReplaceStencilOp,
} );
var po = new THREE.Mesh( planeGeom, planeMat );
po.onAfterRender = function ( renderer ) {
renderer.clearStencil();
};
po.renderOrder = i + 1.1;
plane.coplanarPoint( po.position );
po.lookAt(
po.position.x - plane.normal.x,
po.position.y - plane.normal.y,
po.position.z - plane.normal.z,
);
scene.add( stencilGroup_sphere );
scene.add( stencilGroup_Box );
poGroup.add( po );
planeObjects.push( po );
scene.add( poGroup );
}
var sphereMesh = new THREE.Mesh( sphereGeom, material );
sphereMesh.renderOrder = 6;
scene.add( sphereMesh );
var planeMeshes = [];
for(var i = 0; i < 6; i++)
{
planeMeshes.push( new THREE.Mesh(planeGeoms[i], material) );
}
planeMeshes[0].position.copy(new THREE.Vector3(.5, 0, 0));
planeMeshes[1].position.copy(new THREE.Vector3(0, .5, 0));
planeMeshes[2].position.copy(new THREE.Vector3(0, 0, .5));
planeMeshes[3].position.copy(new THREE.Vector3(-.5, 0, 0));
planeMeshes[4].position.copy(new THREE.Vector3(0, -.5, 0));
planeMeshes[5].position.copy(new THREE.Vector3(0, 0, -.5));
planeMeshes[0].lookAt(new THREE.Vector3(2, 0, 0));
planeMeshes[1].lookAt(new THREE.Vector3(0, 2, 0));
planeMeshes[2].lookAt(new THREE.Vector3(0, 0, 2));
planeMeshes[3].lookAt(new THREE.Vector3(-2, 0, 0));
planeMeshes[4].lookAt(new THREE.Vector3(0, -2, 0));
planeMeshes[5].lookAt(new THREE.Vector3(0, 0, -2));
for(var i = 0; i < 6; i++)
scene.add( planeMeshes[i] );
// Renderer
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.shadowMap.enabled = true;
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0x263238 );
renderer.localClippingEnabled = true;
window.addEventListener( 'resize', onWindowResize, false );
document.body.appendChild( renderer.domElement );
// Controls
var controls = new OrbitControls( camera, renderer.domElement );
controls.minDistance = 2;
controls.maxDistance = 20;
controls.update();
}
function initLights()
{
scene.add( new THREE.AmbientLight( 0xffffff, 0.5 ) );
var dirLight = new THREE.DirectionalLight( 0xffffff, 1 );
dirLight.position.set( 5, 10, 7.5 );
dirLight.castShadow = true;
dirLight.shadow.camera.right = 2;
dirLight.shadow.camera.left = - 2;
dirLight.shadow.camera.top = 2;
dirLight.shadow.camera.bottom = - 2;
dirLight.shadow.mapSize.width = 1024;
dirLight.shadow.mapSize.height = 1024;
scene.add( dirLight );
}
function onWindowResize()
{
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate()
{
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
</script>
It contains 2 clipping planes, a cube made from 6 separate PlaneGeometries, and a solid sphere for comparison. I made the stencil for the cube using an additional BufferGeometry made from merging the planes together into a single geometry object. The stencil for the cube appears to be the right shape and size, but only one cap face is drawn and it is not at the location of either of the clipping planes. Is there anything else I'm supposed to do with the stencil or the clipping plane beyond what the example already does to make it work on geometry of this type?
Turns out the PlaneBufferGeometries that were getting merged for the stencil were not in the same positions as the plane meshes that used those geometries. That is why the cap face wasn't being drawn properly. I had not considered the fact that if you apply a transform to a Mesh, then get the Mesh's geometry to use elsewhere, that geometry won't reflect the transform applied to the Mesh. I got it to work by applying the transform matrices from the plane meshes to the PlaneBufferGeometries that needed to be merged.
I am trying to get the user to click on two different points and get distance between them.
The clicks seems to be happening at random positions, so the calculation is getting to be wrong.
The calculation is correct when the the OBJ loader is used and we use an OBJ file, but if I use an STL file using the STL loader, it just shows up incorrect.
Codepen link: https://codepen.io/anon/pen/NLXavX
JS Code:
<script type="text/javascript" src="https://dl.dropboxusercontent.com/s/qooungyrgltucai/three.js"></script>
<script type="text/javascript" src="https://dl.dropboxusercontent.com/s/ddt89ncslm4o7ie/Detector.js"></script>
<script type="text/javascript" src="https://dl.dropboxusercontent.com/s/mrhumrr2bxwt9nt/OBJLoader.js"></script>
<script type="text/javascript" src="https://dl.dropboxusercontent.com/s/n5sjyymajykna51/TGALoader.js"></script>
<script type="text/javascript" src="https://dl.dropboxusercontent.com/s/y4r5bmq2037jacg/OrbitControls.js"></script>
<script type="text/javascript" src="https://dl.dropboxusercontent.com/s/h18h48v52739df4/STLLoader.js"></script>
<script>
var container;
var camera, controls, scene, renderer, model;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
controls = new THREE.OrbitControls(camera);
// scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight(0x404040); //0x101030
scene.add(ambient);
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
// Loading manager
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.log('Error: ' + xhr);
};
// Model
//model = new THREE.Object3D();
//scene.add(model);
var material = new THREE.MeshPhongMaterial({
color: 0xffffff,
needsUpdate: true
});
window.model ='';
// Added an if else here, STL code:
var loader = new THREE.STLLoader();
loader.load( 'https://dl.dropboxusercontent.com/s/t57h7xketafodui/5a9b75e521aaf-DI_PIPE_FBG_holder.stl', function ( geometry ) {
var material = new THREE.MeshPhongMaterial( { color: 0xff5533, specular: 0x111111, shininess: 200 } );
var mesh = new THREE.Mesh( geometry, material );
mesh.position.set( 0, - 0.25, 0.6 );
mesh.rotation.set( 0, - Math.PI / 2, 0 );
mesh.scale.set( 0.05, 0.05, 0.05 );
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add( mesh );
window.model = scene;
} );
// This OBJ Loader will load if user requests an OBJ file.
var loader = new THREE.OBJLoader(manager);
var object = loader.load('https://dl.dropboxusercontent.com/s/pn3yw6w5962o5r8/BIGIPIGI.obj', function (Object) {
Object.castShadow = true;
Object.position.x = 0;
Object.position.y = -1;
Object.position.z = 0;
Object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material = material;
}
});
console.log(Object);
window.model = Object;
scene.add(Object);
}, onProgress, onError);
// Object
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener('mousedown', onDocumentMouseDown, false);
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// Measurement Code
var pointA = new THREE.Vector3( 0, 1, 0 );
var pointB = new THREE.Vector3();
var markerA = new THREE.Mesh( new THREE.SphereGeometry( 0.1, 16, 16 ), new THREE.MeshBasicMaterial( { color: 0xFF5555, depthTest: false, depthWrite: false } ) );
var markerB = markerA.clone();
scene.add( markerA );
scene.add( markerB );
var line;
function getIntersections( event ) {
var vector = new THREE.Vector2();
vector.set(
( event.clientX / window.innerWidth ) * 2 - 1,
- ( event.clientY / window.innerHeight ) * 2 + 1 );
var raycaster = new THREE.Raycaster();
raycaster.setFromCamera( vector, camera );
var intersects = raycaster.intersectObjects( window.model.children );
return intersects;
}
function getLine( vectorA, vectorB ) {
var geometry = new THREE.Geometry();
geometry.vertices.push( vectorA );
geometry.vertices.push( vectorB );
var material = new THREE.LineBasicMaterial({
color: 0xFFFF00,
depthWrite: false,
depthTest: false
});
line = new THREE.Line( geometry, material );
return line;
}
function onDocumentMouseDown( event ) {
var intersects = getIntersections( event );
if( intersects.length > 0 ){
if ( ! pointB.equals( pointA ) ) {
pointB = intersects[ 0 ].point;
} else {
pointB = pointA;
}
pointA = intersects[ 0 ].point;
markerA.position.copy( pointA );
markerB.position.copy( pointB );
var distance = pointA.distanceTo( pointB );
if ( line instanceof THREE.Line ) {
scene.remove( line );
}
if ( distance > 0 ) {
console.log( "distance", distance );
alert( "distance: "+distance );
line = getLine( pointA, pointB );
scene.add(line);
}
}
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}</script>
Try to add in CSS section:
body{
overflow: hidden;
margin: 0;
}
How to show a cube map reflection on a object without showing the cubemap in the background?
I like to receive a reflection on a lever mechanism without showing a cubemap in the background. The background should be with a gradient from blue to white.
So basicially, the cubemap should be only visible on the object.
Thank you very much in advance!
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container;
var loader;
var camera, cameraTarget, controls, scene, renderer;
init();
animate();
function init() {
var previewDiv = document.getElementById("preview");
camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 15 );
camera.position.set( 3, 0.15, 3 );
cameraTarget = new THREE.Vector3( 0, -0.25, 0 );
controls = new THREE.OrbitControls( camera );
controls.maxPolarAngle = Math.PI / 2.2;
controls.minDistance = 3;
controls.maxDistance = 8;
// controls.noPan = true;
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0xdae1e6, 2, 15 );
// Ground
var plane = new THREE.Mesh(
new THREE.PlaneBufferGeometry( 40, 40 ),
new THREE.MeshPhongMaterial( { color: 0x999999, specular: 0x101010 } )
);
plane.rotation.x = -Math.PI/2;
plane.position.y = -0.5;
scene.add( plane );
plane.receiveShadow = true;
// feinleinen
var feinleinen = THREE.ImageUtils.loadTexture( 'textures/feinleinen.jpg' );
feinleinen.anisotropy = 1;
feinleinen.wrapS = feinleinen.wrapT = THREE.RepeatWrapping;
feinleinen.repeat.set( 5, 5 );
// create a cube
var basisGeometry = new THREE.BoxGeometry(3,0.02,3);
var basisMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff, map: feinleinen } );
var basis = new THREE.Mesh(basisGeometry, basisMaterial);
basis.castShadow = false;
basis.receiveShadow = true;
// position the cube
basis.position.set( 0, -0.47, 0 );
// add the cube to the scene
scene.add(basis);
var loader = new THREE.JSONLoader();
loader.load('/models/hebelmechanik.js', function(geo, mat){
var chrome = new THREE.MeshLambertMaterial( { ambient: 0x444444, color: 0x111111, shininess: 800, specular: 0x111111, shading: THREE.SmoothShading, reflectivity: 1.1 } );
var mesh = new THREE.Mesh(geo, chrome);
mesh.position.set( 0, - 0.497, 0 );
mesh.rotation.set( 0, - Math.PI / 2, 0 );
mesh.scale.set( 0.008, 0.008, 0.008 );
mesh.castShadow = true;
mesh.receiveShadow = true;
loadJson(mesh );
});
function loadJson(mesh){
scene.add( mesh );
}
// Lights
scene.add( new THREE.AmbientLight( 0x777777 ) );
addShadowedLight( 1, 1, 1, 0xffffff, 1.35 );
addShadowedLight( 0.5, 1, -1, 0xffffff, 1 );
// renderer
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColor( scene.fog.color );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.shadowMapEnabled = true;
renderer.shadowMapSoft = true;
renderer.shadowMapCullFace = THREE.CullFaceBack;
previewDiv.appendChild (renderer.domElement);
// resize
window.addEventListener( 'resize', onWindowResize, false );
}
function addShadowedLight( x, y, z, color, intensity ) {
var directionalLight = new THREE.DirectionalLight( color, intensity );
directionalLight.position.set( x, y, z )
scene.add( directionalLight );
directionalLight.castShadow = true;
// directionalLight.shadowCameraVisible = true;
var d = 1;
directionalLight.shadowCameraLeft = -d;
directionalLight.shadowCameraRight = d;
directionalLight.shadowCameraTop = d;
directionalLight.shadowCameraBottom = -d;
directionalLight.shadowCameraNear = 1;
directionalLight.shadowCameraFar = 4;
directionalLight.shadowMapWidth = 2048;
directionalLight.shadowMapHeight = 2048;
directionalLight.shadowBias = -0.005;
directionalLight.shadowDarkness = 0.15;
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
camera.lookAt( cameraTarget );
controls.update();
renderer.render( scene, camera );
}
</script>
You can add a cubemap reflection to your model by specifying the envMap property of the model's material.
Use a pattern like this one:
var path = "textures/cube/foo/";
var format = '.png';
var urls = [
path + 'px' + format, path + 'nx' + format,
path + 'py' + format, path + 'ny' + format,
path + 'pz' + format, path + 'nz' + format
];
var envMap = THREE.ImageUtils.loadTextureCube( urls, THREE.CubeReflectionMapping, callback ); // callback function is optional
var material = new THREE.MeshPhongMaterial( {
color : 0x999999,
specular : 0x050505,
shininess : 50,
envMap : envMap,
combine : THREE.MixOperation, // or THREE.AddOperation, THREE.MultiplyOperation
reflectivity : 0.5
} );
three.js r.71
Hi i am trying to draw the 2d objects in the canvas using js.if click the button it will change to 3d object in another canvas which is in same page.
I tried using three.js.if i want draw 3d object,i am giving the points manually in the code.but i dont know how to convert into 3d coordinates. please suggest any ideas
this is my code for drawing geomentry plan
function init()
{
// SCENE
scene = new THREE.Scene();
// CAMERA
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
scene.add(camera);
camera.position.set(0,150,400);
camera.lookAt(scene.position);
// RENDERER
if ( Detector.webgl )
renderer = new THREE.WebGLRenderer( {antialias:true} );
else
renderer = new THREE.CanvasRenderer();
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
container = document.getElementById( 'ThreeJS' );
container.appendChild( renderer.domElement );
// EVENTS
THREEx.WindowResize(renderer, camera);
THREEx.FullScreen.bindKey({ charCode : 'm'.charCodeAt(0) });
// CONTROLS
controls = new THREE.OrbitControls( camera, renderer.domElement );
// STATS
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.bottom = '0px';
stats.domElement.style.zIndex = 100;
container.appendChild( stats.domElement );
// LIGHT
var light = new THREE.PointLight(0xffffff);
light.position.set(0,250,0);
scene.add(light);
// FLOOR
var floorTexture = new THREE.ImageUtils.loadTexture( 'images/checkerboard.jpg' );
floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.repeat.set( 10, 10 );
var floorMaterial = new THREE.MeshBasicMaterial( { map: floorTexture, side: THREE.DoubleSide } );
var floorGeometry = new THREE.PlaneGeometry(1000, 1000, 10, 10);
var floor = new THREE.Mesh(floorGeometry, floorMaterial);
floor.position.y = -0.5;
floor.rotation.x = Math.PI / 2;
scene.add(floor);
// SKYBOX/FOG
var skyBoxGeometry = new THREE.CubeGeometry( 10000, 10000, 10000 );
var skyBoxMaterial = new THREE.MeshBasicMaterial( { color: 0x9999ff, side: THREE.BackSide } );
var skyBox = new THREE.Mesh( skyBoxGeometry, skyBoxMaterial );
scene.fog = new THREE.FogExp2( 0x9999ff, 0.00025 );
var starPoints = [];
starPoints.push( new THREE.Vector2 ( 10, 50 ) );
starPoints.push( new THREE.Vector2 ( 50, 100 ) );
starPoints.push( new THREE.Vector2 ( 100, 150 ) );
starPoints.push( new THREE.Vector2 ( 150, 200 ) );
/*starPoints.push( new THREE.Vector2 ( 30, -50 ) );
starPoints.push( new THREE.Vector2 ( 0, -20 ) );
starPoints.push( new THREE.Vector2 ( -30, -50 ) );
starPoints.push( new THREE.Vector2 ( -20, -10 ) );
starPoints.push( new THREE.Vector2 ( -40, 10 ) );
starPoints.push( new THREE.Vector2 ( -10, 10 ) );*/
var starShape = new THREE.Shape( starPoints );
var extrusionSettings = {
size: 30, height: 4, curveSegments: 3,
bevelThickness: 1, bevelSize: 2, bevelEnabled: false,
material: 0, extrudeMaterial: 1
};
var starGeometry = new THREE.ExtrudeGeometry( starShape, extrusionSettings );
var materialFront = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
var materialSide = new THREE.MeshBasicMaterial( { color: 0xff8800 } );
var materialArray = [ materialFront, materialSide ];
var starMaterial = new THREE.MeshFaceMaterial(materialArray);
var star = new THREE.Mesh( starGeometry, starMaterial );
star.position.set(0,50,0);
scene.add(star);
// add a wireframe to model
var wireframeTexture = new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true, transparent: true } );
var star = new THREE.Mesh( starGeometry, wireframeTexture );
star.position.set(0,50,0);
scene.add(star);
}
function animate()
{
requestAnimationFrame( animate );
render();
update();
}
function update()
{
if ( keyboard.pressed("z") )
{
// do something
}
controls.update();
stats.update();
}
function render()
{
renderer.render( scene, camera );
}
I want to help,
You can visit this :
http://stemkoski.github.io/Three.js/Extrusion.html
The method is:
var extrusionSettings = {
size: 30, height: 4, curveSegments: 3,
bevelThickness: 1, bevelSize: 2, bevelEnabled: false,
material: 0, extrudeMaterial: 1
};
var starGeometry = new THREE.ExtrudeGeometry( starShape, extrusionSettings );
Did you mean creating a 3d point from a constructor?
If so, it is just one line in three.js.
new THREE.Vector3( x, y, z );