ThreeJS extension for Thingworx - javascript

I am trying to create a 3 JS extension for Thingworx, but the renderHtml keeps bugging in combination with a 3 JS canvas in it (See code).
//runtime.ts file
renderHtml(): string {
let htmlString = '<div class="widget-content"><canvas></canvas></div>';
return htmlString;
}
afterRender(): void {
const OrbitControls = require('three-orbit-controls')(CourseView);
const OBJLoader = require('three-obj-loader')(CourseView);
var scene = new CourseView.Scene();
var width = this.getProperty('SceneWidth', 0);
var height = this.getProperty('SceneHeight', 0);
var color = this.getProperty('SceneColor', '#000000');
if(width <= 0) { width = window.innerWidth }
if(height <= 0) { height = window.innerHeight }
if(color == undefined){ color = "#000000" }
var ratio = width / height;
var camera = new CourseView.PerspectiveCamera(75, ratio, 0.1, 1000);
camera.position.z = 30;
var cv = this.jqElement.find("canvas").get(0);
console.log(cv);
this.renderer = new CourseView.WebGLRenderer({canvas: cv});
this.renderer.setSize(width, height);
this.renderer.setClearColor("#0000ff");
var control = new OrbitControls(camera, this.renderer.domElement);
const geometry = new CourseView.SphereGeometry( 15, 32, 16 );
const material = new CourseView.MeshBasicMaterial( { color: 0xff00ff, wireframe: true } );
const sphere = new CourseView.Mesh( geometry, material );
scene.add( sphere );
control.addEventListener('change', () => this.myRender(scene, camera));
this.myRender(scene, camera);
}
myRender(scene, camera) {
this.renderer.render(scene, camera);
}
As shown, the WebGLRenderer gets the canvas inside the div with the class widget-content. I need this div, to realize bindings of Thingworks. When I leave out the div, everything works fine. If the div exists to implement bindings, the sphere is not rendered. Moreover, the renderer seems stuck and also has no blue background, despite the clear-color call.
When I click on it (maybe its not updated) the color changes to blue, but still there is no sphere. Does anyone has realized ThreeJS in Thingworx and can show me how they did it? I think maybe the div widget-content does apply some changes to all childern (also my ThreeJS canvas), but I cant tell which changes... Maybe someone knows?
Full code: https://www.toptal.com/developers/hastebin/olelowawih.js

For those of you might having this problem in the future, check your setter, you might want to render there as well and keep track of NaN values...

Related

Three.JS Black screen on attaching camera to a GLTF object

So I am writing a bit of stuff if Three.JS and I seem to have hit a stump with the camera. I'm attempting to attach the camera to an imported model object and it would seem that it IS attaching, however it would seem as if shadows are negated, the distance is far off from the actual field I've created. As well as some other annoying issues like Orbit controls would be inverted and non-functional. Here is my code (with certain things blocked out because I'm hotlinking script files hosted on my server...):
// This is basically everything to setup for a basic THREE.JS field to do our work in
var scene = new THREE.Scene(); // Empty Space
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000); // Perspective Camera (Args, FOV, Aspect = W/H, Min View Dist, Max View Dist)
//var controls = new THREE.OrbitControls(camera); // We will use this to look around
camera.position.set(0, 2, 5); // Note that depth into positon is mainly the opposite of where you normally want it to be.
camera.rotation.x = -0.3 // This is an attempt to rotate the angle of the camera off of an axis
var renderer = new THREE.WebGLRenderer({antialias: true}); // Our Renderer + Antialiasing
renderer.shadowMap.enabled = true; // This allows shadows to work in our 3D animation
renderer.shadowMap.type = THREE.PCFSoftShadowMap; // This one isn't as blocky as THREE.PCFShadowMap
renderer.setClearColor("#00CCCC"); // Note: same as 0x000000
renderer.setSize(window.innerWidth, window.innerHeight); // Renderer Dimensions
document.getElementById("container").appendChild(renderer.domElement); // Add our renderer creation to our div named "container"
// Lighting (It's not necessary but it looks cool!)
var light = new THREE.PointLight("#FFFFFF", 5, 1000); // Color, intensity, range(lighting will not exceed render distance)
light.castShadow = true;
light.position.set(5, 5, 0); // This will treat the light coming from an angle!
scene.add(light);
light.shadow.mapSize.width = 512;
light.shadow.mapSize.height = 512;
light.shadow.camera.near = 0.5;
light.shadow.camera.far = 500;
// We will make a cube here
var cubeGeo = new THREE.BoxGeometry(1, 1, 1); // This is the shape, width, height and length of our cube. Note BoxGeometry IS the current shape!
var cubeMat = new THREE.MeshStandardMaterial({color: "#FF0000"}); // Create a basic mesh with undefined color, you can also use a singular color using Basic rather than Normal, There is also Lambert and Phong. Lambert is more of a Matte material while Phong is more of a gloss or shine effect.
var cube = new THREE.Mesh(cubeGeo, cubeMat); // Create the object with defined dimensions and colors!
cube.castShadow = true; // This will allow our cube to cast a shadow outward.
cube.recieveShadow = false // This will make our cube not recieve shadows from other objects (Although it isn't needed because it's default, you show make a habit of writing it anyways as some things default to true!)
scene.add(cube); // scene.add(object) is what we will use for almost every object we create in THREE.JS
//cube.add(camera); // This is an attempt to attach the camera to the cube...
// Loader
var ship;
var loader = new THREE.GLTFLoader();
loader.load("http://ipaddress:port/files/models/raven/scene.gltf", function(gltf) {
scene.add(gltf.scene);
ship = gltf.scene;
ship.scale.multiplyScalar(0.005);
ship.rotation.y = Math.PI;
}, undefined, function(error) {
console.error(error);
});
// Lest make a floor to show the shadow!
var floorGeo = new THREE.BoxGeometry(1000, 0.1, 1000);
var floorMat = new THREE.MeshStandardMaterial({color: "#0000FF"});
var floor = new THREE.Mesh(floorGeo, floorMat);
floor.recieveShadow = true; // This will allow the shadow from the cube to portray itself unto it.
floor.position.set(0, -3, 0);
scene.add(floor);
// Now let's create an object on the floor so that we can distance ourself from our starting point.
var buildingGeo = new THREE.BoxGeometry(10, 100, 10);
var buildingMat = new THREE.MeshNormalMaterial();
var building = new THREE.Mesh(buildingGeo, buildingMat);
building.position.z = -100;
scene.add(building);
var rotation = 0;
// Controls
var keyState = {};
window.addEventListener('keydown',function(e){
keyState[e.keyCode || e.which] = true;
},true);
window.addEventListener('keyup',function(e){
keyState[e.keyCode || e.which] = false;
},true);
document.addEventListener("keydown", function(event) {
console.log(event.which);
});
var camAdded = false;
var render = function() {
requestAnimationFrame(render); // This grabs the browsers frame animation function.
if (rotation == 1) {
ship.rotation.x += 0.01; // rotation is treated similarly to how two dimensional objects' location is treated
ship.rotation.y += 0.01; // however it will be based on an axis point plus the width/height and subtract but keep it's indice location!
ship.rotation.z += 0.01;
}
if (keyState[87]) { // Up
ship.rotateX(0.01);
}
if (keyState[83]) { // Down
ship.rotateX(-0.01);
}
if (keyState[65]) { // Left
ship.rotateY(0.03);
}
if (keyState[68]) { // Right
ship.rotateY(-0.03);
}
if (keyState[81]) {
ship.rotateZ(0.1);
}
if (keyState[69]) {
ship.rotateZ(-0.1);
}
if (keyState[82]) { // Reset
for (var i = 0; i < 10; i++) {
if (!ship.rotation.x == 0) {
if (ship.rotation.x > 0) {
ship.rotation.x -= 0.005;
} else if (ship.rotation.x < 0){
ship.rotation.x += 0.005;
}
}
if (!ship.rotation.z == 0) {
if (ship.rotation.z > 0) {
ship.rotation.z -= 0.01;
} else if (ship.rotation.z < 0){
ship.rotation.z += 0.01;
}
}
}
}
ship.translateZ(0.2); // This will translate our ship forward in the direction it's currently facing so that it will look as if it is flyimg.
renderer.render(scene, camera); // This will render the scene after the effects have changed (rotation!)
window.addEventListener('resize', onWindowResize, false);
}
render(); // Finally, we need to loop the animation otherwise our object will not move on it's own!
function onWindowResize() {
var sceneWidth = window.innerWidth - 20;
var sceneHeight = window.innerHeight - 20;
renderer.setSize(sceneWidth, sceneHeight);
camera.aspect = sceneWidth / sceneHeight;
camera.updateProjectionMatrix();
}
<!DOCTYPE htm>
<html>
<head>
<meta charset="utf-8">
<title>Basic Three.JS</title>
</head>
<body style="background-color: #2B2B29; color: #FFFFFF; text-align: center;">
<div id="container"></div>
<script>
window.onload = function() {
document.getElementById("container").width = window.innerWidth - 20;
document.getElementById("container").height = window.innerHeight - 20;
}
</script>
<script src="http://ipaddress:port/files/scripts/three.min.js"></script>
<script src="http://ipaddress:port/files/scripts/GLTFLoader.js"></script>
<script src="http://ipaddress:port/files/scripts/OrbitControls.js"></script>
<script src="http://ipaddress:port/files/scripts/basicthree.js"></script> <!-- This is the code below -->
</body>
</html>
Nevermind, I have found a solution - shoddy as it may be...
if (typeof ship != "undefined") {
// Previous code inside of the main three.js loop...
ship.translateZ(0.2); // Move ship
camera.position.set(ship.position.x, ship.position.y, ship.position.z); // Set the camera's position to the ships position
camera.translateZ(10); // Push the camera back a bit so it's not inside the ship
camera.rotation.set(ship.rotation.x, ship.rotation.y, ship.rotation.z); // Set the rotation of the ship to be the exact same as the ship
camera.rotateX(0.3); // Tilt the camera downwards so that it's viewing over the ship
camera.rotateY(Math.PI); // Flip the camera so it's not facing the head of the ship model.
// Note: many bits of code I have are inverted due to the ship's model being backwards (or so it seems)...
}

smooth terrain from height map three js

I am currently trying to create some smooth terrain using the PlaneBufferGeometry of three.js from a height map I got from Google Images:
https://forums.unrealengine.com/filedata/fetch?id=1192062&d=1471726925
but the result is kinda choppy..
(Sorry, this is my first question and evidently I need 10 reputation to post images, otherwise I would.. but here's an even better thing: a live demo! left click + drag to rotate, scroll to zoom)
I want, like i said, a smooth terrain, so am I doing something wrong or is this just the result and i need to smoothen it afterwards somehow?
Also here is my code:
const IMAGE_SRC = 'terrain2.png';
const SIZE_AMPLIFIER = 5;
const HEIGHT_AMPLIFIER = 10;
var WIDTH;
var HEIGHT;
var container = jQuery('#wrapper');
var scene, camera, renderer, controls;
var data, plane;
image();
// init();
function image() {
var image = new Image();
image.src = IMAGE_SRC;
image.onload = function() {
WIDTH = image.width;
HEIGHT = image.height;
var canvas = document.createElement('canvas');
canvas.width = WIDTH;
canvas.height = HEIGHT;
var context = canvas.getContext('2d');
console.log('image loaded');
context.drawImage(image, 0, 0);
data = context.getImageData(0, 0, WIDTH, HEIGHT).data;
console.log(data);
init();
}
}
function init() {
// initialize camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, .1, 100000);
camera.position.set(0, 1000, 0);
// initialize scene
scene = new THREE.Scene();
// initialize directional light (sun)
var sun = new THREE.DirectionalLight(0xFFFFFF, 1.0);
sun.position.set(300, 400, 300);
sun.distance = 1000;
scene.add(sun);
var frame = new THREE.SpotLightHelper(sun);
scene.add(frame);
// initialize renderer
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0x000000);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.append(renderer.domElement);
// initialize controls
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = .05;
controls.rotateSpeed = .1;
// initialize plane
plane = new THREE.PlaneBufferGeometry(WIDTH * SIZE_AMPLIFIER, HEIGHT * SIZE_AMPLIFIER, WIDTH - 1, HEIGHT - 1);
plane.castShadow = true;
plane.receiveShadow = true;
var vertices = plane.attributes.position.array;
// apply height map to vertices of plane
for(i=0, j=2; i < data.length; i += 4, j += 3) {
vertices[j] = data[i] * HEIGHT_AMPLIFIER;
}
var material = new THREE.MeshPhongMaterial({color: 0xFFFFFF, side: THREE.DoubleSide, shading: THREE.FlatShading});
var mesh = new THREE.Mesh(plane, material);
mesh.rotation.x = - Math.PI / 2;
mesh.matrixAutoUpdate = false;
mesh.updateMatrix();
plane.computeFaceNormals();
plane.computeVertexNormals();
scene.add(mesh);
animate();
}
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
controls.update();
}
The result is jagged because the height map has low color depth. I took the liberty of coloring a portion of the height map (Paint bucket in Photoshop, 0 tolerance, non-continuous) so you can see for yourself how large are the areas which have the same color value, i.e. the same height.
The areas of the same color will create a plateau in your terrain. That's why you have plateaus and sharp steps in your terrain.
What you can do is either smooth out the Z values of the geometry or use a height map which utilizes 16bits or event 32bits for height information. The current height map only uses 8bits, i.e. 256 values.
One thing you could do to smooth things out a bit is to sample more than just a single pixel from the heightmap. Right now, the vertex indices directly correspond to the pixel position in the data-array. And you just update the z-value from the image.
for(i=0, j=2; i < data.length; i += 4, j += 3) {
vertices[j] = data[i] * HEIGHT_AMPLIFIER;
}
Instead you could do things like this:
get multiple samples with certain offsets along the x/y axes
compute an (weighted) average value from the samples
That way you would get some smoothing at the borders of the same-height areas.
The second option is to use something like a blur-kernel (gaussian blur is horribly expensive, but maybe something like a fast box-blur would work for you).
As you are very limited in resolution due to just using a single byte, you should convert that image to float32 first:
const highResData = new Float32Array(data.length / 4);
for (let i = 0; i < highResData.length; i++) {
highResData[i] = data[4 * i] / 255;
}
Now the data is in a format that allows for far higher numeric resolution, so we can smooth that now. You could either adjust something like the StackBlur for the float32 use-case, use ndarrays and ndarray-gaussian-filter or implement something simple yourself. The basic idea is to find an average value for all the values in those uniformly colored plateaus.
Hope that helps, good luck :)

how to render alphabets in 2D using threejs

I'm making a 2d game, where blocks are falling down ( tetris style). I need to render alphabets on these blocks. This is how I am creating blocks:
var geometry = new THREE.BoxGeometry( this.BLOCK_WIDTH, this.BLOCK_WIDTH, 4 );
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
this.blocks = [];
for (var i = 0; i < rows * columns; i++) {
cube = new THREE.Mesh( geometry, material );
cube.visible = false;
cube.letter = letterGenerator.getNextLetter();
this.blocks[i] = cube;
scene.add( this.blocks[i] );
};
As you can see, all blocks will look exactly alike except for the fact, that they will have a different alphabet associated with them. In my update(), I move the block, left/right or down. When I do so, block position will be updated and obviously the alphabet should be rendered accordingly.
How should I go about rendering alphabets on these blocks ?
EDIT: I am using WebGLRenderer.
You can get the screen position of each block (your "cube" variable above) that you want to paint text on and use HTML to paint text at that screen location over each block. Using HTML to make a text sprite like this is discussed here:
https://github.com/mrdoob/three.js/issues/1321
You can get the screen position for your "cube" above like so:
var container = document.getElementById("idcanvas");
var containerWidth = container.clientWidth;
var containerHeight = container.clientHeight;
var widthHalf = containerWidth / 2, heightHalf = containerHeight / 2;
var locvector = new THREE.Vector3();
locvector.setFromMatrixPosition(cube.matrixWorld);
locvector.project(your_camera); //returns center of mesh
var xpos = locvector.x = (locvector.x * widthHalf) + widthHalf; //convert to screen coordinates
var ypos = locvector.y = -(locvector.y * heightHalf) + heightHalf;
You'll have to update the HTML for cube movement.
Another approach is to create specific textures with the text you want and apply each texture as a material to the appropriate cube.

Dynamic height of cube with fixed floor

I am creating a dynamic cube that can be dynamically changed by scaling its mesh. The issue is, I would like to keep it fixed to the floor when modifying its height. This is a snippet of my code:
function init() {
// Floor position
floor = new THREE.Mesh( shadowGeo, shadowMaterial );
floor.position.y = 0;
floor.rotation.x = - Math.PI / 2;
scene.add( floor );
// Defines the cube and its original position
var BoxGeometry = new THREE.BoxGeometry(50, 50, 50);
var boxMaterial = new THREE.MeshLambertMaterial({color: 0x000088});
cube = new THREE.Mesh(BoxGeometry, boxMaterial);
cube.position.set(0,30,0);
scene.add(cube);
// GUI PANEL INTERACTION
// Now the GUI panel for the interaction is defined
gui = new dat.GUI();
parameters = {
height: 1,
reset: function() {resetCube()}
}
// Define the second folder which takes care of the scaling of the cube
var folder1 = gui.addFolder("Dimensions");
var cubeHeight = folder2.add(parameters, "height").min(0).max(200).step(1);
folder1.open();
// Function taking care of the cube changes
cubeHeight.onChange(function(value){cube.scale.y = value;});
gui.open();
}
// Update cube characteristics
function updateCube() {
cube.scale.y = parameters.y;
}
// Reset cube settings
function resetCube() {
parameters.height = 1;
updateCube();
}
// Rest of the code
I have searched around and I saw this similar topic, but still it does not properly explain how to modify dimensions when the object with a reference floor. Do you know how can I solve this issue?
Changed your .onChange() function to have the cube stay on the ground:
// Function taking care of the cube changes
cubeHeightScale.onChange(
function(value)
{
cube.scale.y = value;
cube.position.y = (cubeHeight * value) / 2;
} );
Here is a fiddle to check the changes live: http://jsfiddle.net/Lsjh965o/
three.js r71

Three.js - Edit plane geometry

So, I want to make a simple terrain editor. So, on mouseDown, I want the selected face to move up.
The intersection works great, and I try to modify the geometry like so:
var intersects2 = ray.intersectObjects([plane]);
if (intersects2.length > 0) {
var face = intersects2[0].face;
var obj1 = intersects2[0].object;
var geo = obj1.geometry;
geo.vertices[face.a].z += 50;
geo.vertices[100].z += 50;
geo.vertices[0].z += 50;
geo.computeVertexNormals();
geo.computeFaceNormals();
geo.__dirtyVertices = true;
geo.__dirtyNormals = true;
console.log(face.a);
}
The console log shows the correct vertex index, but nothing on the plane moves. Any ideas why?
The plane is created like this:
var planegeo = new THREE.PlaneGeometry( 500, 500, 10, 10 );
planegeo.dynamic = true;
plane = new THREE.Mesh( planegeo, new THREE.MeshPhongMaterial( { color: 0x99ff66 } ) );
plane.receiveShadow = true;
scene.add( plane );
Looking at your code, it looks like you are using syntax pre R49. It may just be that you need to update your dirty flag code to (assuming you are now using a newer library!):
geo.verticesNeedUpdate = true;
geo.normalsNeedUpdate = true;

Categories

Resources