Merge pull request #58 from potree/develop

Develop
This commit is contained in:
Markus Schütz 2014-10-24 19:05:35 +02:00
commit 16260af3de
65 changed files with 3628 additions and 27 deletions

View File

@ -1132,6 +1132,8 @@ THREE.FirstPersonControls = function ( object, domElement ) {
} else if ( state === STATE.PAN ) {
panEnd.set( event.clientX, event.clientY );
panDelta.subVectors( panEnd, panStart );
//panDelta.multiplyScalar(this.moveSpeed).multiplyScalar(0.0001);
panDelta.multiplyScalar(0.0005).multiplyScalar(scope.moveSpeed);
scope.pan( panDelta.x, panDelta.y );
@ -1389,6 +1391,7 @@ Potree.PointCloudOctree = function(geometry, material){
this.LODFalloff = 1.3;
this.LOD = 4;
this.showBoundingBox = false;
this.loadQueue = [];
var rootProxy = new Potree.PointCloudOctreeProxyNode(this.pcoGeometry.root);
@ -1400,6 +1403,7 @@ Potree.PointCloudOctree.prototype = Object.create(THREE.Object3D.prototype);
Potree.PointCloudOctree.prototype.update = function(camera){
this.numVisibleNodes = 0;
this.numVisiblePoints = 0;
this.loadQueue = [];
// create frustum in object space
camera.updateMatrixWorld();
@ -1420,6 +1424,9 @@ Potree.PointCloudOctree.prototype.update = function(camera){
//var ray = new THREE.Ray(camera.position, new THREE.Vector3( 0, -1, 0 ) );
// check visibility
// TODO min and max points
//var minPoints = 1*1000*1000;
//var maxPoints = 5*1000*1000;
var stack = [];
stack.push(this);
while(stack.length > 0){
@ -1437,12 +1444,17 @@ Potree.PointCloudOctree.prototype.update = function(camera){
var visible = true;
visible = visible && frustum.intersectsBox(box);
if(object.level > 1){
// cull detail nodes based in distance to camera
visible = visible && Math.pow(radius, 0.8) / distance > (1 / this.LOD);
visible = visible && (this.numVisiblePoints + object.numPoints < Potree.pointLoadLimit);
visible = visible && (this.numVisibleNodes <= this.maxVisibleNodes);
visible = visible && (this.numVisiblePoints <= this.maxVisiblePoints);
if(object.level > 0){
//if(this.numVisiblePoints > minPoints && this.numVisiblePoints < maxPoints){
// cull detail nodes based in distance to camera
visible = visible && Math.pow(radius, 0.8) / distance > (1 / this.LOD);
visible = visible && (this.numVisiblePoints + object.numPoints < Potree.pointLoadLimit);
visible = visible && (this.numVisibleNodes <= this.maxVisibleNodes);
visible = visible && (this.numVisiblePoints <= this.maxVisiblePoints);
//}else if(this.numVisiblePoints > maxPoints){
// visible = false;
//}
}else{
//visible = true;
}
@ -1484,12 +1496,29 @@ Potree.PointCloudOctree.prototype.update = function(camera){
Potree.PointCloudOctree.lru.touch(object);
object.material = this.material;
}else if (object instanceof Potree.PointCloudOctreeProxyNode) {
this.replaceProxy(object);
var geometryNode = object.geometryNode;
if(geometryNode.loaded === true){
this.replaceProxy(object);
}else{
this.loadQueue.push({node: object, lod: Math.pow(radius, 0.8) / distance});
}
}
for(var i = 0; i < object.children.length; i++){
stack.push(object.children[i]);
}
//console.log(object.name);
}
if(this.loadQueue.length > 0){
if(this.loadQueue.length >= 2){
this.loadQueue.sort(function(a,b){return b.lod - a.lod});
}
for(var i = 0; i < Math.min(5, this.loadQueue.length); i++){
this.loadQueue[i].node.geometryNode.load();
}
}
}
@ -1514,10 +1543,21 @@ Potree.PointCloudOctree.prototype.replaceProxy = function(proxy){
var child = geometryNode.children[i];
var childProxy = new Potree.PointCloudOctreeProxyNode(child);
node.add(childProxy);
//for(var j = 0; j < 8; j++){
// if(child.children[j] !== undefined){
// var cchild = child.children[j];
// var cchildProxy = new Potree.PointCloudOctreeProxyNode(cchild);
// childProxy.add(cchildProxy);
//
//
// }
//}
}
}
}else{
geometryNode.load();
//geometryNode.load();
//this.loadQueue.push(geometryNode);
}
}
@ -1570,6 +1610,52 @@ Potree.PointCloudOctree.prototype.getBoundingBoxWorld = function(){
return tBox;
}
Potree.PointCloudOctree.prototype.getProfile = function(start, end, width, depth){
var stack = [];
stack.push(this);
var side = new THREE.Vector3().subVectors(end, start).normalize();
var up = new THREE.Vector3(0, 1, 0);
var forward = new THREE.Vector3().crossVectors(side, up).normalize();
var N = forward;
var cutPlane = new THREE.Plane().setFromNormalAndCoplanarPoint(N, start);
var inside = [];
while(stack.length > 0){
var object = stack.shift();
console.log("traversing: " + object.name);
if(object instanceof THREE.PointCloud){
var geometry = object.geometry;
var positions = geometry.attributes.position;
var p = positions.array;
var pointCount = positions.length / positions.itemSize;
for(var i = 0; i < pointCount; i++){
var pos = new THREE.Vector3(p[3*i], p[3*i+1], p[3*i+2]);
pos.applyMatrix4(this.matrixWorld);
var distance = Math.abs(cutPlane.distanceToPoint(pos));
if(distance < width/2){
inside.push(pos);
}
}
}
if(object == this || object.level < depth){
for(var i = 0; i < object.children.length; i++){
stack.push(object.children[i]);
}
}
}
console.log("points inside: " + inside.length);
return inside;
}
/**
*
@ -1679,7 +1765,86 @@ Potree.PointCloudOctreeGeometryNode.prototype.load = function(){
nodesLoadTimes[url] = {};
nodesLoadTimes[url].start = new Date().getTime();
LasLazLoader.load(url, new Potree.LasLazBatcher(this, url));
}else {
} else if ( pointAttributes === "POT"){
var callback = function(node, buffer){
var dv = new DataView(buffer, 0, 4);
var headerSize = dv.getUint32(0, true);
var pointOffset = 4 + headerSize;
var headerBuffer = buffer.slice(4, 4 + headerSize);
var header = String.fromCharCode.apply(null, new Uint8Array(headerBuffer));
header = JSON.parse(header);
console.log(header);
var pScale = header.attributes[0].scale;
var pOffset = header.attributes[0].offset;
var pEncoding = header.attributes[0].encoding;
var scale = new THREE.Vector3(pScale[0], pScale[1], pScale[2]);
var offset = new THREE.Vector3(pOffset[0], pOffset[1], pOffset[2]);
var min = pEncoding.min;
var max = pEncoding.max;
var bits = pEncoding.bits;
var pointBuffer = buffer.slice(pointOffset, pointOffset + buffer.byteLength - pointOffset);
var br = new BitReader(pointBuffer);
var X = br.read(32);
var Y = br.read(32);
var Z = br.read(32);
var r = br.read(8);
var g = br.read(8);
var b = br.read(8);
var geometry = new THREE.BufferGeometry();
var numPoints = header.pointcount;
var positions = new Float32Array(numPoints*3);
var colors = new Float32Array(numPoints*3);
var color = new THREE.Color();
for(var i = 0; i < header.pointcount - 1; i++){
dx = br.read(bits[0]) + min[0];
dy = br.read(bits[1]) + min[1];
dz = br.read(bits[2]) + min[2];
X = X + dx;
Y = Y + dy;
Z = Z + dz;
x = X * scale.x + offset.x;
y = Y * scale.y + offset.y;
z = Z * scale.z + offset.z;
r = br.read(8);
g = br.read(8);
b = br.read(8);
positions[3*i+0] = x;// + node.pcoGeometry.offset.x;
positions[3*i+1] = y;// + node.pcoGeometry.offset.y;
positions[3*i+2] = z;// + node.pcoGeometry.offset.z;
colors[3*i+0] = r / 255;
colors[3*i+1] = g / 255;
colors[3*i+2] = b / 255;
}
geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3));
geometry.boundingBox = node.boundingBox;
node.geometry = geometry;
node.loaded = true;
node.loading = false;
node.pcoGeometry.numNodesLoading--;
};
Potree.BinaryNodeLoader.load(this, "pot", callback);
} else {
// load binary node files
var url = this.pcoGeometry.octreeDir + "/" + this.name;
@ -1722,7 +1887,7 @@ Potree.PointCloudOctreeGeometryNode.prototype.load = function(){
nodesLoadTimes[url] = {};
nodesLoadTimes[url].start = new Date().getTime();
Potree.BinaryNodeLoader.load(this, callback);
Potree.BinaryNodeLoader.load(this, "", callback);
}
}
@ -1730,8 +1895,11 @@ Potree.BinaryNodeLoader = function(){
}
Potree.BinaryNodeLoader.load = function(node, callback){
Potree.BinaryNodeLoader.load = function(node, extension, callback){
var url = node.pcoGeometry.octreeDir + "/" + node.name;
if(extension !== undefined && extension.length > 0){
url += "." + extension;
}
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
@ -1950,3 +2118,662 @@ Potree.utils.createGrid = function createGrid(width, length, spacing, color){
line.receiveShadow = true;
return line;
}
/**
* adapted from http://stemkoski.github.io/Three.js/Sprite-Text-Labels.html
*/
Potree.TextSprite = function(text){
var texture = new THREE.Texture();
var spriteMaterial = new THREE.SpriteMaterial(
{ map: texture, useScreenCoordinates: false} );
THREE.Sprite.call(this, spriteMaterial);
this.borderThickness = 4;
this.fontface = "Arial";
this.fontsize = 28;
this.borderColor = { r:0, g:0, b:0, a:1.0 };
this.backgroundColor = { r:255, g:255, b:255, a:1.0 };
this.text = "";
this.setText(text);
};
Potree.TextSprite.prototype = new THREE.Sprite();
Potree.TextSprite.prototype.setText = function(text){
this.text = text;
this.update();
}
Potree.TextSprite.prototype.setBorderColor = function(color){
this.borderColor = color;
this.update();
}
Potree.TextSprite.prototype.setBackgroundColor = function(color){
this.backgroundColor = color;
this.update();
}
Potree.TextSprite.prototype.update = function(){
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = "Bold " + this.fontsize + "px " + this.fontface;
// get size data (height depends only on font size)
var metrics = context.measureText( this.text );
var textWidth = metrics.width;
var spriteWidth = textWidth + 2 * this.borderThickness;
var spriteHeight = this.fontsize * 1.4 + 2 * this.borderThickness;
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.canvas.width = spriteWidth;
context.canvas.height = spriteHeight;
context.font = "Bold " + this.fontsize + "px " + this.fontface;
// background color
context.fillStyle = "rgba(" + this.backgroundColor.r + "," + this.backgroundColor.g + ","
+ this.backgroundColor.b + "," + this.backgroundColor.a + ")";
// border color
context.strokeStyle = "rgba(" + this.borderColor.r + "," + this.borderColor.g + ","
+ this.borderColor.b + "," + this.borderColor.a + ")";
context.lineWidth = this.borderThickness;
this.roundRect(context, this.borderThickness/2, this.borderThickness/2,
textWidth + this.borderThickness, this.fontsize * 1.4 + this.borderThickness, 6);
// text color
context.strokeStyle = "rgba(0, 0, 0, 1.0)";
context.strokeText( this.text, this.borderThickness, this.fontsize + this.borderThickness);
context.fillStyle = "rgba(255, 255, 255, 1.0)";
context.fillText( this.text, this.borderThickness, this.fontsize + this.borderThickness);
var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
//var spriteMaterial = new THREE.SpriteMaterial(
// { map: texture, useScreenCoordinates: false } );
this.material.map = texture;
this.scale.set(spriteWidth*0.01,spriteHeight*0.01,1.0);
//this.material = spriteMaterial;
}
Potree.TextSprite.prototype.roundRect = function(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x+r, y);
ctx.lineTo(x+w-r, y);
ctx.quadraticCurveTo(x+w, y, x+w, y+r);
ctx.lineTo(x+w, y+h-r);
ctx.quadraticCurveTo(x+w, y+h, x+w-r, y+h);
ctx.lineTo(x+r, y+h);
ctx.quadraticCurveTo(x, y+h, x, y+h-r);
ctx.lineTo(x, y+r);
ctx.quadraticCurveTo(x, y, x+r, y);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
Potree.MeasuringTool = function(scene, camera, domElement){
var scope = this;
this.scene = scene;
this.camera = camera;
this.domElement = domElement;
this.mouse = {x: 0, y: 0};
var STATE = {
DEFAULT: 0,
PICKING: 1
};
var state = STATE.DEFAULT;
this.activeMeasurement;
this.measurements = [];
this.sceneMeasurement = new THREE.Scene();
this.sceneRoot = new THREE.Object3D();
this.sceneMeasurement.add(this.sceneRoot);
function Measure(){
this.points = [];
this.spheres = [];
this.edges = [];
this.sphereLabels = [];
this.edgeLabels = [];
}
function onDoubleClick(event){
var I = getMousePointCloudIntersection();
if(I){
var pos = I.clone();
var sphereMaterial = new THREE.MeshNormalMaterial({shading: THREE.SmoothShading})
var sphereGeometry = new THREE.SphereGeometry(0.4, 10, 10);
var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.position.copy(I);
scope.sceneRoot.add(sphere);
var sphereEnd = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphereEnd.position.copy(I);
scope.sceneRoot.add(sphereEnd);
var msg = pos.x.toFixed(2) + " / " + pos.y.toFixed(2) + " / " + pos.z.toFixed(2);
var label = new Potree.TextSprite(msg);
label.setBorderColor({r:0, g:255, b:0, a:1.0});
label.material.depthTest = false;
label.material.opacity = 0;
label.position.copy(I);
label.position.y += 0.5;
scope.sceneRoot.add( label );
var labelEnd = new Potree.TextSprite(msg);
labelEnd.setBorderColor({r:0, g:255, b:0, a:1.0});
labelEnd.material.depthTest = false;
labelEnd.material.opacity = 0;
labelEnd.position.copy(I);
labelEnd.position.y += 0.5;
scope.sceneRoot.add( labelEnd );
var lc = new THREE.Color( 0xff0000 );
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push(I.clone(), I.clone());
lineGeometry.colors.push(lc, lc, lc);
var lineMaterial = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
lineMaterial.depthTest = false;
sConnection = new THREE.Line(lineGeometry, lineMaterial);
scope.sceneRoot.add(sConnection);
var edgeLabel = new Potree.TextSprite(0);
edgeLabel.setBorderColor({r:0, g:255, b:0, a:0.0});
edgeLabel.setBackgroundColor({r:0, g:255, b:0, a:0.0});
edgeLabel.material.depthTest = false;
edgeLabel.position.copy(I);
edgeLabel.position.y += 0.5;
scope.sceneRoot.add( edgeLabel );
//floatingOrigin.addReferenceFrame(sphere);
//floatingOrigin.addReferenceFrame(sphereEnd);
//floatingOrigin.addReferenceFrame(label);
//floatingOrigin.addReferenceFrame(labelEnd);
//floatingOrigin.addReferenceFrame(sConnection);
//floatingOrigin.addReferenceFrame(edgeLabel);
if(state === STATE.DEFAULT){
state = STATE.PICKING;
scope.activeMeasurement = new Measure();
scope.activeMeasurement.spheres.push(sphere);
}else if(state === STATE.PICKING){
}
scope.activeMeasurement.points.push(I);
scope.activeMeasurement.spheres.push(sphereEnd);
scope.activeMeasurement.sphereLabels.push(label);
scope.activeMeasurement.sphereLabels.push(labelEnd);
scope.activeMeasurement.edges.push(sConnection);
scope.activeMeasurement.edgeLabels.push(edgeLabel);
var event = {
type: 'newpoint',
position: pos.clone()
};
scope.dispatchEvent(event);
}
};
function onMouseMove(event){
scope.mouse.x = ( event.clientX / scope.domElement.clientWidth ) * 2 - 1;
scope.mouse.y = - ( event.clientY / scope.domElement.clientHeight ) * 2 + 1;
if(state == STATE.PICKING && scope.activeMeasurement){
var I = getMousePointCloudIntersection();
if(I){
var pos = I.clone();
var l = scope.activeMeasurement.spheres.length;
var sphere = scope.activeMeasurement.spheres[l-1];
var label = scope.activeMeasurement.sphereLabels[l-1];
var edge = scope.activeMeasurement.edges[l-2];
var edgeLabel = scope.activeMeasurement.edgeLabels[l-2];
var msg = pos.x.toFixed(2) + " / " + pos.y.toFixed(2) + " / " + pos.z.toFixed(2);
label.setText(msg);
sphere.position.copy(I);
label.position.copy(I);
label.position.y += 0.5;
edge.geometry.vertices[1].copy(I);
edge.geometry.verticesNeedUpdate = true;
edge.geometry.computeBoundingSphere();
var edgeLabelPos = edge.geometry.vertices[1].clone().add(edge.geometry.vertices[0]).multiplyScalar(0.5);
var edgeLabelText = edge.geometry.vertices[0].distanceTo(edge.geometry.vertices[1]).toFixed(2);
edgeLabel.position.copy(edgeLabelPos);
edgeLabel.setText(edgeLabelText);
edgeLabel.scale.multiplyScalar(10);
}
}
};
function onRightClick(event){
if(state == STATE.PICKING){
var sphere = scope.activeMeasurement.spheres.pop();
var edge = scope.activeMeasurement.edges.pop();
var sphereLabel = scope.activeMeasurement.sphereLabels.pop();
var edgeLabel = scope.activeMeasurement.edgeLabels.pop();
scope.sceneRoot.remove(sphere);
scope.sceneRoot.remove(edge);
scope.sceneRoot.remove(sphereLabel);
scope.sceneRoot.remove(edgeLabel);
scope.measurements.push(scope.activeMeasurement);
scope.activeMeasurement = undefined;
state = STATE.DEFAULT;
}
}
function onMouseDown(event){
if(event.which === 3){
onRightClick(event);
}
}
function getMousePointCloudIntersection(){
var vector = new THREE.Vector3( scope.mouse.x, scope.mouse.y, 0.5 );
var projector = new THREE.Projector();
projector.unprojectVector( vector, scope.camera );
var raycaster = new THREE.Raycaster();
raycaster.params = {"PointCloud" : {threshold: 1}};
raycaster.ray.set( scope.camera.position, vector.sub( scope.camera.position ).normalize() );
var pointClouds = [];
scope.scene.traverse(function(object){
if(object instanceof Potree.PointCloudOctree){
pointClouds.push(object);
}
});
var intersects = raycaster.intersectObjects(pointClouds, true);
if(intersects.length > 0){
var I = intersects[0];
return I.point;
}else{
return undefined;
}
}
this.domElement.addEventListener("dblclick", onDoubleClick, false);
this.domElement.addEventListener( 'mousemove', onMouseMove, false );
this.domElement.addEventListener( 'mousedown', onMouseDown, false );
};
Potree.MeasuringTool.prototype = Object.create( THREE.EventDispatcher.prototype );
Potree.ProfileTool = function(width, height, depth){
THREE.Object3D.call( this );
var boxGeometry = new THREE.BoxGeometry(1,1,1,1,1,1);
var boxMaterial = new THREE.MeshBasicMaterial({color: 0xFF0000, transparent: true, opacity: 0.3});
this.profileFrustum = new THREE.Mesh(boxGeometry, boxMaterial);
this.add(this.profileFrustum);
this.camera = new THREE.OrthographicCamera( -width / 2, width / 2, height / 2, -height / 2, 1, 1 + depth );
this.add(this.camera);
this.setDimension(width, height, depth);
this.rtProfile = new THREE.WebGLRenderTarget( 512, 512, { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBFormat } );
this.hudGeometry = new THREE.BoxGeometry(2,2,1);
this.hudMaterial = new THREE.MeshBasicMaterial( { color: 0xffffff, map: this.rtProfile } );
this.hudMaterial.depthTest = false;
this.hudElement = new THREE.Mesh(this.hudGeometry, this.hudMaterial);
this.hudElement.scale.set(1,1,1);
this.hudElement.position.set(0, 0, 0);
}
Potree.ProfileTool.prototype = Object.create( THREE.Object3D.prototype );
Potree.ProfileTool.prototype.setDimension = function(width, height, depth){
this.profileFrustum.scale.set(width, height, depth);
this.width = width;
this.height = height;
this.depth = depth;
this.camera.left = -width / 2;
this.camera.right = width / 2;
this.camera.top = height / 2;
this.camera.bottom = -height / 2;
this.camera.updateProjectionMatrix();
}
Potree.ProfileTool.prototype.setOrientation = function(forward, side){
var oldPosition = this.position.clone();
this.position.add(forward);
this.lookAt(oldPosition);
this.position.copy(oldPosition);
this.camera.position.copy(oldPosition.clone().add(forward));
this.camera.lookAt(oldPosition);
}
Potree.ProfileTool.prototype.render = function(renderer, scene){
this.camera.matrixWorld.copy(this.matrixWorld);
//TODO maybe we should store old sizes in a map instead of the objects
scene.traverse(function(object){
if(object instanceof Potree.PointCloudOctree){
object.material.oldSize = object.material.size;
object.material.size = 0;
}
});
renderer.render(scene, this.camera, this.rtProfile, true);
scene.traverse(function(object){
if(object instanceof Potree.PointCloudOctree){
object.material.size = object.material.oldSize;
}
});
//this.hudElement.scale.x = 0.5;
//this.hudElement.scale.y = 0.5 * (renderer.domElement.clientWidth / renderer.domElement.clientHeight) * (this.height / this.width);
//this.hudElement.position.x = 0.7;
//this.hudElement.position.y = -0.7;
}
Potree.TranslationTool = function(camera) {
THREE.Object3D.call( this );
var scope = this;
this.camera = camera;
this.geometry = new THREE.Geometry();
this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
this.STATE = {
DEFAULT: 0,
TRANSLATE_X: 1,
TRANSLATE_Y: 2,
TRANSLATE_Z: 3
};
this.parts = {
ARROW_X : {name: "arrow_x", object: undefined, color: new THREE.Color( 0xff0000 ), state: this.STATE.TRANSLATE_X},
ARROW_Y : {name: "arrow_y", object: undefined, color: new THREE.Color( 0x00ff00 ), state: this.STATE.TRANSLATE_Y},
ARROW_Z : {name: "arrow_z", object: undefined, color: new THREE.Color( 0x0000ff ), state: this.STATE.TRANSLATE_Z}
}
this.translateStart;
this.state = this.STATE.DEFAULT;
this.highlighted;
this.targets;
this.build = function(){
var arrowX = scope.createArrow(scope.parts.ARROW_X, scope.parts.ARROW_X.color);
arrowX.rotation.z = -Math.PI/2;
var arrowY = scope.createArrow(scope.parts.ARROW_Y, scope.parts.ARROW_Y.color);
var arrowZ = scope.createArrow(scope.parts.ARROW_Z, scope.parts.ARROW_Z.color);
arrowZ.rotation.x = -Math.PI/2;
scope.add(arrowX);
scope.add(arrowY);
scope.add(arrowZ);
var boxXY = scope.createBox(new THREE.Color( 0xffff00 ));
boxXY.scale.z = 0.02;
boxXY.position.set(0.5, 0.5, 0);
var boxXZ = scope.createBox(new THREE.Color( 0xff00ff ));
boxXZ.scale.y = 0.02;
boxXZ.position.set(0.5, 0, -0.5);
var boxYZ = scope.createBox(new THREE.Color( 0x00ffff ));
boxYZ.scale.x = 0.02;
boxYZ.position.set(0, 0.5, -0.5);
scope.add(boxXY);
scope.add(boxXZ);
scope.add(boxYZ);
scope.parts.ARROW_X.object = arrowX;
scope.parts.ARROW_Y.object = arrowY;
scope.parts.ARROW_Z.object = arrowZ;
scope.scale.multiplyScalar(5);
};
this.createBox = function(color){
var boxGeometry = new THREE.BoxGeometry(1, 1, 1);
var boxMaterial = new THREE.MeshBasicMaterial({color: color, transparent: true, opacity: 0.5});
var box = new THREE.Mesh(boxGeometry, boxMaterial);
return box;
};
this.createArrow = function(partID, color){
var material = new THREE.MeshBasicMaterial({color: color});
var shaftGeometry = new THREE.CylinderGeometry(0.1, 0.1, 3, 10, 1, false);
var shaftMatterial = material;
var shaft = new THREE.Mesh(shaftGeometry, shaftMatterial);
shaft.position.y = 1.5;
var headGeometry = new THREE.CylinderGeometry(0, 0.3, 1, 10, 1, false);
var headMaterial = material;
var head = new THREE.Mesh(headGeometry, headMaterial);
head.position.y = 3;
var arrow = new THREE.Object3D();
arrow.add(shaft);
arrow.add(head);
arrow.partID = partID;
arrow.material = material;
return arrow;
};
this.setHighlighted = function(partID){
if(partID === undefined){
if(scope.highlighted){
scope.highlighted.object.material.color = scope.highlighted.color;
scope.highlighted = undefined;
}
return;
}else if(scope.highlighted !== undefined && scope.highlighted !== partID){
scope.highlighted.object.material.color = scope.highlighted.color;
}
scope.highlighted = partID;
partID.object.material.color = new THREE.Color(0xffff00);
}
this.getHoveredObject = function(mouse){
var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
var projector = new THREE.Projector();
projector.unprojectVector( vector, scope.camera );
var raycaster = new THREE.Raycaster();
raycaster.ray.set( scope.camera.position, vector.sub( scope.camera.position ).normalize() );
var intersections = raycaster.intersectObject(scope, true);
if(intersections.length === 0){
scope.setHighlighted(undefined);
return undefined;
}
var I = intersections[0];
var partID = I.object.parent.partID;
return partID;
}
this.onMouseMove = function(event){
var mouse = event.normalizedPosition;
if(scope.state === scope.STATE.DEFAULT){
scope.setHighlighted(scope.getHoveredObject(mouse));
}else if(scope.state === scope.STATE.TRANSLATE_X || scope.state === scope.STATE.TRANSLATE_Y || scope.state === scope.STATE.TRANSLATE_Z){
var origin = scope.start.lineStart.clone();
var direction = scope.start.lineEnd.clone().sub(scope.start.lineStart);
direction.normalize();
var mousePoint = new THREE.Vector3(mouse.x, mouse.y);
var directionDistance = new THREE.Vector3().subVectors(mousePoint, origin).dot(direction);
var pointOnLine = direction.clone().multiplyScalar(directionDistance).add(origin);
var projector = new THREE.Projector();
projector.unprojectVector(pointOnLine, scope.camera);
var diff = pointOnLine.clone().sub(scope.position);
scope.position.copy(pointOnLine);
for(var i = 0; i < scope.targets.length; i++){
var target = scope.targets[0];
target.position.add(diff);
}
event.signal.halt();
}
};
this.onMouseDown = function(event){
if(scope.state === scope.STATE.DEFAULT){
var hoveredObject = scope.getHoveredObject(event.normalizedPosition, scope.camera);
if(hoveredObject){
scope.state = hoveredObject.state;
var lineStart = scope.position.clone();
var lineEnd;
if(scope.state === scope.STATE.TRANSLATE_X){
lineEnd = scope.position.clone();
lineEnd.x += 2;
}else if(scope.state === scope.STATE.TRANSLATE_Y){
lineEnd = scope.position.clone();
lineEnd.y += 2;
}else if(scope.state === scope.STATE.TRANSLATE_Z){
lineEnd = scope.position.clone();
lineEnd.z -= 2;
}
//lineEnd = scope.position.clone();
var projector = new THREE.Projector();
projector.projectVector( lineStart, scope.camera );
projector.projectVector( lineEnd, scope.camera );
scope.start = {
mouse: event.normalizedPosition,
lineStart: lineStart,
lineEnd: lineEnd
};
event.signal.halt();
}
}
};
this.onMouseUp = function(event){
scope.setHighlighted();
scope.state = scope.STATE.DEFAULT;
};
this.setTargets = function(targets){
scope.targets = targets;
if(scope.targets.length === 0){
return;
}
//TODO calculate centroid of all targets
var centroid = targets[0].position.clone();
//for(var i = 0; i < targets.length; i++){
// var target = targets[i];
//}
scope.position.copy(centroid);
}
this.build();
};
Potree.TranslationTool.prototype = Object.create( THREE.Object3D.prototype );

File diff suppressed because one or more lines are too long

View File

@ -3,7 +3,7 @@
<title>Lion</title>
</head>
<body style="margin: 0px; padding: 0px;">
<body style="margin: 0px; padding: 0px; overflow: hidden">
<style type="text/css">
@ -156,6 +156,8 @@
camera.updateMatrixWorld(true);
controls.update(0.1);
vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
projector.unprojectVector( vector, camera );
raycaster.params = {"PointCloud" : {threshold: 0.1}};

View File

@ -0,0 +1,373 @@
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="http://openlayers.org/en/v3.0.0/css/ol.css" type="text/css">
<style>
body{
margin: 0;
padding: 0;
}
.map {
position: absolute;
height: 300px;
width: 400px;
right: 5px;
bottom: 5px;
z-index: 1000;
}
#renderArea{
position: absolute;
width: 100%;
height: 100%;
right: 0;
bottom: 0;
z-index: 0;
margin: 0;
padding: 0;
}
.info{
position: absolute;
z-index: 2000;
color:white;
font-weight: bold;
text-shadow: 1px 1px 1px black,
1px -1px 1px black,
-1px 1px 1px black,
-1px -1px 1px black;
}
a:hover, a:visited, a:link, a:active{
color: #ccccff;
text-decoration: none;
}
</style>
<script src="http://openlayers.org/en/v3.0.0/build/ol.js" type="text/javascript"></script>
<script src="../libs/three.js/build/three.js"></script>
<script src="../libs/other/dat.gui.min.js"></script>
<script src="../libs/proj4/proj4.js"></script>
<script src="../build/js/potree.js"></script>
<title>Georeferencing Example</title>
</head>
<body>
<div id="map" class="map"></div>
<div id="renderArea"></div>
<div class="info" style="position: absolute; left: 300px; right: 300px; top: 10px; text-align: center;">
<a href="http://potree.org" target="_blank">potree.org</a><br>
Georeferencing (sync with OpenLayers3) and Measurement.<br>
Double click to generate measurement points. Measurement points will be displayed
in the point cloud as well as the OpenStreetMap window.
<br><br>
Point cloud courtesy of <a href="http://www.sigeom.ch/" target="_blank">sigeom sa</a><br>
Rue des Oeuches 45<br>
2740 Moutier<br>
Switzerland <br>
<br>
</div>
<script type="text/javascript">
var pointcloudPath = "../resources/pointclouds/vol_total/cloud.js";
var defaultPointSize = 3;
var defaultLOD = 17;
// add EPSG:21781 to the proj4 projection database
proj4.defs('EPSG:21781', "+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +k_0=1 +x_0=600000 +y_0=200000 +ellps=bessel +towgs84=674.4,15.1,405.3,0,0,0,0 +units=m +no_defs ");
var fromSwiss = proj4.defs("EPSG:21781");
var toWGS84 = proj4.defs("WGS84");
// extent (with altitude) in EPSG:21781 / Swiss Coordinate System
var minSwiss = [584757.154, 230878.747, 662.379];
var maxSwiss = [593758.872, 232521.598, 850.323];
// extent in EPSG:4326 / WGS84 World Geodetic System
var minExtent = proj4(proj4.defs("EPSG:21781"), proj4.defs("WGS84"), [minSwiss[0], minSwiss[1]]);
var maxExtent = proj4(proj4.defs("EPSG:21781"), proj4.defs("WGS84"), [maxSwiss[0], maxSwiss[1]]);
// extent in EPSG:3857 / WGS84 Web Mercator
var minT = ol.proj.transform(minExtent, 'EPSG:4326', 'EPSG:3857');
var maxT = ol.proj.transform(maxExtent, 'EPSG:4326', 'EPSG:3857');
// the offset of the point cloud in EPSG:21781 coordinate system to local scene coordinates.
// subtract this offset in order to move from local scene coordinates (obtained from picking, etc.)
// to EPSG:21781 coordinates
var offset = new THREE.Vector3();
// OpenLayers3 stuff
var featureVector;
var camFrustumFeatureVector;
var camFrustum;
// three.js / potree stuff
var renderer;
var scene;
var camera;
var skybox;
var materials = {};
var clock = new THREE.Clock();
var measuringTool;
function initMapView(){
var extent = [minT[0], minT[1], maxT[0], maxT[1]];
var center = [(maxT[0] + minT[0]) / 2, (maxT[1] + minT[1]) / 2];
// draw the extent as box inside the map view
var box = new ol.geom.LineString([
minT, [maxT[0], minT[1]], maxT, [minT[0], maxT[1]], minT
]);
var feature = new ol.Feature(box);
featureVector = new ol.source.Vector({
features: [feature]
});
var layer = new ol.layer.Vector({
source: featureVector,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ff0000',
width: 2
}),
image: new ol.style.Circle({
radius: 3,
fill: new ol.style.Fill({
color: '#0000ff'
})
})
})
});
camFrustumFeatureVector = new ol.source.Vector({
features: []
});
var camFrustumLayer = new ol.layer.Vector({
source: camFrustumFeatureVector,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ff0000',
width: 2
}),
image: new ol.style.Circle({
radius: 3,
fill: new ol.style.Fill({
color: '#ff0000'
})
})
})
});
// create the map
var map = new ol.Map({
controls: ol.control.defaults({
attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}).extend([
new ol.control.ZoomToExtent({
extent: extent,
closest: true
})
]),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
layer,
camFrustumLayer
],
target: 'map',
view: new ol.View({
center: center,
zoom: 12
})
});
}
function initPotreeView(){
var renderArea = document.getElementById("renderArea");
var near = 0.1;
var far = 100000;
var fov = 60;
var aspect = renderArea.clientWidth / renderArea.clientHeight;
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
renderer = new THREE.WebGLRenderer();
renderer.setSize(renderArea.clientWidth, renderArea.clientHeight);
renderer.autoClear = false;
renderArea.appendChild(renderer.domElement);
skybox = Potree.utils.loadSkybox("../resources/textures/skybox/");
camera.position.set(500, 200, -300);
controls = new THREE.FirstPersonControls(camera, renderer.domElement);
camera.rotation.order = 'ZYX';
camera.rotation.x = -0.5;
camera.rotation.y = -5*Math.PI/4;
controls.moveSpeed *= 10;
materials.rgb = new Potree.PointCloudRGBMaterial({ size: defaultPointSize});
// load pointcloud
var pco = POCLoader.load(pointcloudPath, {toOrigin: true});
offset = pco.offset;
pointcloud = new Potree.PointCloudOctree(pco, materials.rgb);
pointcloud.LOD = defaultLOD;
pointcloud.applyMatrix(new THREE.Matrix4().set(
1,0,0,0,
0,0,1,0,
0,-1,0,0,
0,0,0,1
));
scene.add(pointcloud);
measuringTool = new Potree.MeasuringTool(scene, camera, renderer.domElement);
// execute this event whenever a new measurement point has been set
measuringTool.addEventListener("newpoint", function(event){
// transform from local scene to swiss projection.
var point = new THREE.Vector3(event.position.x, -event.position.z, event.position.y);
point = point.sub(offset);
// transform from swiss projection to WGS84
var fromSwiss = proj4.defs("EPSG:21781");
var toWGS84 = proj4.defs("WGS84");
var coordinate = proj4(fromSwiss, toWGS84, [point.x, point.y]);
// transform from WGS84 to Web Mercator
coordinate = ol.proj.transform(coordinate, 'EPSG:4326', 'EPSG:3857');
// add a point to the OpenLayers map
var olPoint = new ol.geom.Point(coordinate);
var feature = new ol.Feature(olPoint);
featureVector.addFeature(feature);
});
}
function initGUI(){
// dat.gui
var gui = new dat.GUI({
height : 5 * 32 - 1
});
var params = {
PointSize: defaultPointSize,
LOD: defaultLOD,
"bounding box" : false
};
var pLOD = gui.add(params, 'LOD', 0.5,20);
pLOD.onChange(function(value){
pointcloud.LOD = value;
});
var pPointSize = gui.add(params, 'PointSize', 0.01, 4.0);
pPointSize.onChange(function(value){
pointcloud.material.size = value;
});
var pBoundingBox = gui.add(params, 'bounding box');
pBoundingBox.onChange(function(value){
pointcloud.showBoundingBox = value;
});
}
function update(){
controls.update(clock.getDelta());
pointcloud.update(camera);
if(camFrustum === undefined){
camFrustum = new ol.geom.LineString([ [0,0], [0, 0] ]);
var feature = new ol.Feature(camFrustum);
camFrustumFeatureVector.addFeature(feature);
}
var aspect = camera.aspect;
var top = Math.tan( THREE.Math.degToRad( camera.fov * 0.5 ) ) * camera.near;
var bottom = - top;
var left = aspect * bottom;
var right = aspect * top;
var camPos = new THREE.Vector3(0, 0, 0);
left = new THREE.Vector3(left, 0, -camera.near).multiplyScalar(3000);
right = new THREE.Vector3(right, 0, -camera.near).multiplyScalar(3000);
camPos.applyMatrix4(camera.matrixWorld);
left.applyMatrix4(camera.matrixWorld);
right.applyMatrix4(camera.matrixWorld);
// transform from local scene to swiss projection.
camPos = new THREE.Vector3(camPos.x, -camPos.z, camPos.y).sub(offset);
left = new THREE.Vector3(left.x, -left.z, left.y).sub(offset);
right = new THREE.Vector3(right.x, -right.z, right.y).sub(offset);
camPos = proj4(fromSwiss, toWGS84, [camPos.x, camPos.y]);
left = proj4(fromSwiss, toWGS84, [left.x, left.y]);
right = proj4(fromSwiss, toWGS84, [right.x, right.y]);
camPos = ol.proj.transform(camPos, 'EPSG:4326', 'EPSG:3857');
left = ol.proj.transform(left, 'EPSG:4326', 'EPSG:3857');
right = ol.proj.transform(right, 'EPSG:4326', 'EPSG:3857');
camFrustum.setCoordinates([camPos, left, right, camPos]);
}
function render(){
// resize
var renderArea = document.getElementById("renderArea");
var width = renderArea.clientWidth;
var height = renderArea.clientHeight;
renderer.setSize(width, height-10);
camera.aspect = width / height;
camera.updateProjectionMatrix();
// render skybox
skybox.camera.rotation.copy(camera.rotation);
renderer.render(skybox.scene, skybox.camera);
// render scenes
renderer.render(scene, camera);
renderer.render(measuringTool.sceneMeasurement, camera);
}
function loop(){
requestAnimationFrame(loop);
update();
render();
}
initMapView();
initPotreeView();
initGUI();
loop();
</script>
</body>
</html>

View File

@ -31,7 +31,7 @@
<script src="../libs/other/dat.gui.min.js"></script>
<script src="../build/js/potree.min.js"></script>
<div id="lblNumVisibleNodes" class="info" style="position: absolute; left: 10px; top: 80px; width: 400px; color:white"></div>
<div id="lblNumVisiblePoints" class="info" style="position: absolute; left: 10px; top: 100px; width: 400px; color:white"></div>

404
examples/profile.html Normal file
View File

@ -0,0 +1,404 @@
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="http://openlayers.org/en/v3.0.0/css/ol.css" type="text/css">
<style>
body{
margin: 0;
padding: 0;
}
.map {
position: absolute;
height: 300px;
width: 400px;
right: 5px;
bottom: 5px;
z-index: 1000;
}
#renderArea{
position: absolute;
width: 100%;
height: 100%;
right: 0;
bottom: 0;
z-index: 0;
margin: 0;
padding: 0;
}
.info{
position: absolute;
z-index: 2000;
color:white;
font-weight: bold;
text-shadow: 1px 1px 1px black,
1px -1px 1px black,
-1px 1px 1px black,
-1px -1px 1px black;
}
a:hover, a:visited, a:link, a:active{
color: #ccccff;
text-decoration: none;
}
</style>
<script src="http://openlayers.org/en/v3.0.0/build/ol.js" type="text/javascript"></script>
<script src="../libs/signals/signals.min.js"></script>
<script src="../libs/three.js/build/three.js"></script>
<script src="../libs/other/dat.gui.min.js"></script>
<script src="../libs/proj4/proj4.js"></script>
<script src="../build/js/potree.js"></script>
<script src="profile.js"></script>
<title>Georeferencing Example</title>
</head>
<body>
<div id="map" class="map"></div>
<div id="renderArea"></div>
<div class="info" style="position: absolute; left: 300px; right: 300px; top: 10px; text-align: center;">
<a href="http://potree.org" target="_blank">potree.org</a><br>
Georeferencing (sync with OpenLayers3) and Measurement.<br>
Double click to generate measurement points.
<br><br>
Point cloud courtesy of <a href="http://www.sigeom.ch/" target="_blank">sigeom sa</a><br>
Rue des Oeuches 45<br>
2740 Moutier<br>
Switzerland <br>
</div>
<script type="text/javascript">
var pointcloudPath = "../resources/pointclouds/vol_total/cloud.js";
var defaultPointSize = 3;
var defaultLOD = 17;
// add EPSG:21781 to the proj4 projection database
proj4.defs('EPSG:21781', "+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +k_0=1 +x_0=600000 +y_0=200000 +ellps=bessel +towgs84=674.4,15.1,405.3,0,0,0,0 +units=m +no_defs ");
var fromSwiss = proj4.defs("EPSG:21781");
var toWGS84 = proj4.defs("WGS84");
// extent (with altitude) in EPSG:21781 / Swiss Coordinate System
var minSwiss = [584757.154, 230878.747, 662.379];
var maxSwiss = [593758.872, 232521.598, 850.323];
// extent in EPSG:4326 / WGS84 World Geodetic System
var minExtent = proj4(proj4.defs("EPSG:21781"), proj4.defs("WGS84"), [minSwiss[0], minSwiss[1]]);
var maxExtent = proj4(proj4.defs("EPSG:21781"), proj4.defs("WGS84"), [maxSwiss[0], maxSwiss[1]]);
// extent in EPSG:3857 / WGS84 Web Mercator
var minT = ol.proj.transform(minExtent, 'EPSG:4326', 'EPSG:3857');
var maxT = ol.proj.transform(maxExtent, 'EPSG:4326', 'EPSG:3857');
// the offset of the point cloud in EPSG:21781 coordinate system to local scene coordinates.
// subtract this offset in order to move from local scene coordinates (obtained from picking, etc.)
// to EPSG:21781 coordinates
var offset = new THREE.Vector3();
// OpenLayers3 stuff
var featureVector;
var camFrustumFeatureVector;
var camFrustum;
// three.js / potree stuff
var renderer;
var scene, sceneHUD;
var camera, cameraHUD;
var skybox;
var materials = {};
var clock = new THREE.Clock();
var viewerControls;
var profileTool;
var translationTool;
function initMapView(){
var extent = [minT[0], minT[1], maxT[0], maxT[1]];
var center = [(maxT[0] + minT[0]) / 2, (maxT[1] + minT[1]) / 2];
// draw the extent as box inside the map view
var box = new ol.geom.LineString([
minT, [maxT[0], minT[1]], maxT, [minT[0], maxT[1]], minT
]);
var feature = new ol.Feature(box);
featureVector = new ol.source.Vector({
features: [feature]
});
var layer = new ol.layer.Vector({
source: featureVector,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ff0000',
width: 2
}),
image: new ol.style.Circle({
radius: 3,
fill: new ol.style.Fill({
color: '#0000ff'
})
})
})
});
camFrustumFeatureVector = new ol.source.Vector({
features: []
});
var camFrustumLayer = new ol.layer.Vector({
source: camFrustumFeatureVector,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ff0000',
width: 2
}),
image: new ol.style.Circle({
radius: 3,
fill: new ol.style.Fill({
color: '#ff0000'
})
})
})
});
// create the map
var map = new ol.Map({
controls: ol.control.defaults({
attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}).extend([
new ol.control.ZoomToExtent({
extent: extent,
closest: true
})
]),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
layer,
camFrustumLayer
],
target: 'map',
view: new ol.View({
center: center,
zoom: 12
})
});
}
function initPotreeView(){
var renderArea = document.getElementById("renderArea");
var near = 0.1;
var far = 100000;
var fov = 60;
var aspect = renderArea.clientWidth / renderArea.clientHeight;
scene = new THREE.Scene();
sceneHUD = new THREE.Scene();
camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
cameraHUD = new THREE.OrthographicCamera( -1, 1, 1, -1, -100, 1000 );
renderer = new THREE.WebGLRenderer();
renderer.setSize(renderArea.clientWidth, renderArea.clientHeight);
renderer.autoClear = false;
renderArea.appendChild(renderer.domElement);
skybox = Potree.utils.loadSkybox("../resources/textures/skybox/");
camera.position.set(500, 200, -300);
controls = new THREE.FirstPersonControls(camera, renderer.domElement);
camera.rotation.order = 'ZYX';
camera.rotation.x = -0.5;
camera.rotation.y = -5*Math.PI/4;
controls.moveSpeed *= 10;
materials.rgb = new Potree.PointCloudRGBMaterial({ size: defaultPointSize});
// load pointcloud
var pco = POCLoader.load(pointcloudPath, {toOrigin: true});
offset = pco.offset;
pointcloud = new Potree.PointCloudOctree(pco, materials.rgb);
pointcloud.LOD = defaultLOD;
pointcloud.applyMatrix(new THREE.Matrix4().set(
1,0,0,0,
0,0,1,0,
0,-1,0,0,
0,0,0,1
));
scene.add(pointcloud);
profileTool = new Potree.ProfileTool(200, 100, 2);
profileTool.position.set(200, 50, -100);
profileTool.rotation.y = Math.PI / 2;
scene.add(profileTool);
sceneHUD.add(profileTool.hudElement);
translationTool = new Potree.TranslationTool(camera);
translationTool.setTargets([profileTool]);
scene.add(translationTool);
//measuringTool = new Potree.MeasuringTool(scene, camera, renderer.domElement);
// execute this event whenever a new measurement point has been set
//measuringTool.addEventListener("newpoint", function(event){
// // transform from local scene to swiss projection.
// var point = new THREE.Vector3(event.position.x, -event.position.z, event.position.y);
// point = point.sub(offset);
//
// // transform from swiss projection to WGS84
// var fromSwiss = proj4.defs("EPSG:21781");
// var toWGS84 = proj4.defs("WGS84");
// var coordinate = proj4(fromSwiss, toWGS84, [point.x, point.y]);
//
// // transform from WGS84 to Web Mercator
// coordinate = ol.proj.transform(coordinate, 'EPSG:4326', 'EPSG:3857');
//
// // add a point to the OpenLayers map
// var olPoint = new ol.geom.Point(coordinate);
// var feature = new ol.Feature(olPoint);
// featureVector.addFeature(feature);
//});
}
function initGUI(){
// dat.gui
var gui = new dat.GUI({
height : 5 * 32 - 1
});
var params = {
PointSize: defaultPointSize,
LOD: defaultLOD,
"bounding box" : false
};
var pLOD = gui.add(params, 'LOD', 0.5,20);
pLOD.onChange(function(value){
pointcloud.LOD = value;
});
var pPointSize = gui.add(params, 'PointSize', 0.01, 4.0);
pPointSize.onChange(function(value){
pointcloud.material.size = value;
});
var pBoundingBox = gui.add(params, 'bounding box');
pBoundingBox.onChange(function(value){
pointcloud.showBoundingBox = value;
});
}
function update(){
var renderArea = document.getElementById("renderArea");
var width = renderArea.clientWidth;
var height = renderArea.clientHeight;
//controls.update(clock.getDelta());
viewerControls.update(clock.getDelta());
pointcloud.update(camera);
if(camFrustum === undefined){
camFrustum = new ol.geom.LineString([ [0,0], [0, 0] ]);
var feature = new ol.Feature(camFrustum);
camFrustumFeatureVector.addFeature(feature);
}
var aspect = camera.aspect;
var top = Math.tan( THREE.Math.degToRad( camera.fov * 0.5 ) ) * camera.near;
var bottom = - top;
var left = aspect * bottom;
var right = aspect * top;
var camPos = new THREE.Vector3(0, 0, 0);
left = new THREE.Vector3(left, 0, -camera.near).multiplyScalar(3000);
right = new THREE.Vector3(right, 0, -camera.near).multiplyScalar(3000);
camPos.applyMatrix4(camera.matrixWorld);
left.applyMatrix4(camera.matrixWorld);
right.applyMatrix4(camera.matrixWorld);
// transform from local scene to swiss projection.
camPos = new THREE.Vector3(camPos.x, -camPos.z, camPos.y).sub(offset);
left = new THREE.Vector3(left.x, -left.z, left.y).sub(offset);
right = new THREE.Vector3(right.x, -right.z, right.y).sub(offset);
camPos = proj4(fromSwiss, toWGS84, [camPos.x, camPos.y]);
left = proj4(fromSwiss, toWGS84, [left.x, left.y]);
right = proj4(fromSwiss, toWGS84, [right.x, right.y]);
camPos = ol.proj.transform(camPos, 'EPSG:4326', 'EPSG:3857');
left = ol.proj.transform(left, 'EPSG:4326', 'EPSG:3857');
right = ol.proj.transform(right, 'EPSG:4326', 'EPSG:3857');
camFrustum.setCoordinates([camPos, left, right, camPos]);
profileTool.hudElement.scale.x = 400 / width;
profileTool.hudElement.scale.y = 300 / height;
profileTool.hudElement.position.x = 1 - 405 / width;
profileTool.hudElement.position.y = -1 + 905 / height;
}
function render(){
// resize
var renderArea = document.getElementById("renderArea");
var width = renderArea.clientWidth;
var height = renderArea.clientHeight;
renderer.setSize(width, height-10);
camera.aspect = width / height;
camera.updateProjectionMatrix();
// render skybox
skybox.camera.rotation.copy(camera.rotation);
renderer.render(skybox.scene, skybox.camera);
// render scenes
renderer.render(scene, camera);
renderer.render(measuringControl.sceneMeasurement, camera);
renderer.render(sceneHUD, cameraHUD);
profileTool.render(renderer, scene);
}
function loop(){
requestAnimationFrame(loop);
update();
render();
}
initMapView();
initPotreeView();
initGUI();
initSignals();
loop();
</script>
</body>
</html>

774
examples/profile.js Normal file
View File

@ -0,0 +1,774 @@
function initSignals(){
viewerControls = new ViewerControls(renderer.domElement, camera, scene);
measuringControl = new Potree.MeasuringControls(scene, camera);
viewerControls.addControl(measuringControl);
viewerControls.addControl(translationTool);
var firstPersonControls = new THREE.FirstPersonControls(camera, renderer.domElement);
firstPersonControls.moveSpeed *= 10;
viewerControls.addControl(firstPersonControls);
}
ViewerControls = function(element, camera, scene){
var scope = this;
this.mouse = {x: 0, y: 0};
this.element = element;
this.camera = camera;
this.scene = scene;
this.events = {
mousemove : new signals.Signal(),
mouseclick : new signals.Signal(),
mousedown : new signals.Signal(),
mouseup : new signals.Signal(),
mousewheel : new signals.Signal(),
dblclick : new signals.Signal(),
update : new signals.Signal(),
keydown: new signals.Signal(),
keyup: new signals.Signal()
};
this.addControl = function(control){
if(control.onMouseMove !== undefined){
scope.events.mousemove.add(control.onMouseMove);
}
if(control.onMouseClick !== undefined){
scope.events.mouseclick.add(control.onMouseClick);
}
if(control.onMouseDown !== undefined){
scope.events.mousedown.add(control.onMouseDown);
}
if(control.onMouseUp !== undefined){
scope.events.mouseup.add(control.onMouseUp);
}
if(control.onMouseWheel !== undefined){
scope.events.mousewheel.add(control.onMouseWheel);
}
if(control.onDoubleClick !== undefined){
scope.events.dblclick.add(control.onDoubleClick);
}
if(control.update !== undefined){
scope.events.update.add(control.update);
}
if(control.onKeyDown !== undefined){
scope.events.keydown.add(control.onKeyDown);
}
if(control.onKeyUp !== undefined){
scope.events.keyup.add(control.onKeyUp);
}
}
this.onMouseMove = function(event){
scope.mouse.x = ( event.clientX / scope.element.clientWidth ) * 2 - 1;
scope.mouse.y = - ( event.clientY / scope.element.clientHeight ) * 2 + 1;
var vector = new THREE.Vector3( scope.mouse.x, scope.mouse.y, 0.5 );
var projector = new THREE.Projector();
projector.unprojectVector( vector, scope.camera );
scope.mouse.relativePosition = {x: event.clientX, y: event.clientY};
scope.mouse.normalizedPosition = {x: scope.mouse.x, y: scope.mouse.y};
scope.mouse.scenePosition = vector;
var message = {
relativePosition: scope.mouse.relativePosition,
normalizedPosition: scope.mouse.normalizedPosition,
scenePosition: scope.mouse.scenePosition,
signal: scope.events.mousemove
};
scope.events.mousemove.dispatch(message);
}
this.onMouseClick = function(event){
var message = {
};
scope.events.mouseclick.dispatch(message);
}
this.onDoubleClick = function(event){
var message = {
relativePosition: scope.mouse.relativePosition,
normalizedPosition: scope.mouse.normalizedPosition,
scenePosition: scope.mouse.scenePosition
};
scope.events.dblclick.dispatch(message);
}
this.onMouseDown = function(event){
event.preventDefault();
var message = {
which: event.which,
button: event.button,
relativePosition: scope.mouse.relativePosition,
normalizedPosition: scope.mouse.normalizedPosition,
scenePosition: scope.mouse.scenePosition,
signal: scope.events.mousedown
};
scope.events.mousedown.dispatch(message);
}
this.onMouseUp = function(event){
event.preventDefault();
var message = {
};
scope.events.mouseup.dispatch(message);
}
this.update = function(time){
var message = {
time: time
};
scope.events.update.dispatch(message);
}
this.onKeyDown = function(event){
var message = {
keyCode: event.keyCode
};
scope.events.keydown.dispatch(message);
}
this.onKeyUp = function(event){
var message = {
keyCode: event.keyCode
};
scope.events.keyup.dispatch(message);
}
this.onContextMenu = function(event){
event.preventDefault();
}
this.onMouseWheel = function(event){
event.preventDefault();
var delta = 0;
if ( event.wheelDelta !== undefined ) { // WebKit / Opera / Explorer 9
delta = event.wheelDelta;
} else if ( event.detail !== undefined ) { // Firefox
delta = - event.detail;
}
var message = {
delta: delta
};
scope.events.mousewheel.dispatch(message);
}
element.addEventListener("mousemove", this.onMouseMove);
element.addEventListener("click", this.onMouseClick);
element.addEventListener("dblclick", this.onDoubleClick);
element.addEventListener("mousedown", this.onMouseDown);
element.addEventListener("mouseup", this.onMouseUp);
element.addEventListener("contextmenu", this.onContextMenu);
element.addEventListener("mousewheel", this.onMouseWheel);
window.addEventListener("keydown", this.onKeyDown);
window.addEventListener("keyup", this.onKeyUp);
};
Potree.MeasuringControls = function(scene, camera){
var scope = this;
this.scene = scene;
this.camera = camera;
this.mouse = {x: 0, y: 0};
var STATE = {
DEFAULT: 0,
PICKING: 1
};
var state = STATE.DEFAULT;
this.activeMeasurement;
this.measurements = [];
this.sceneMeasurement = new THREE.Scene();
this.sceneRoot = new THREE.Object3D();
this.sceneMeasurement.add(this.sceneRoot);
function Measure(){
this.points = [];
this.spheres = [];
this.edges = [];
this.sphereLabels = [];
this.edgeLabels = [];
}
this.onDoubleClick = function(event){
var I = getMousePointCloudIntersection(event.normalizedPosition);
if(I){
var pos = I.clone();
var sphereMaterial = new THREE.MeshNormalMaterial({shading: THREE.SmoothShading})
var sphereGeometry = new THREE.SphereGeometry(0.4, 10, 10);
var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.position.copy(I);
scope.sceneRoot.add(sphere);
var sphereEnd = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphereEnd.position.copy(I);
scope.sceneRoot.add(sphereEnd);
var msg = pos.x.toFixed(2) + " / " + pos.y.toFixed(2) + " / " + pos.z.toFixed(2);
var label = new Potree.TextSprite(msg);
label.setBorderColor({r:0, g:255, b:0, a:1.0});
label.material.depthTest = false;
label.material.opacity = 0;
label.position.copy(I);
label.position.y += 0.5;
scope.sceneRoot.add( label );
var labelEnd = new Potree.TextSprite(msg);
labelEnd.setBorderColor({r:0, g:255, b:0, a:1.0});
labelEnd.material.depthTest = false;
labelEnd.material.opacity = 0;
labelEnd.position.copy(I);
labelEnd.position.y += 0.5;
scope.sceneRoot.add( labelEnd );
var lc = new THREE.Color( 0xff0000 );
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push(I.clone(), I.clone());
lineGeometry.colors.push(lc, lc, lc);
var lineMaterial = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
lineMaterial.depthTest = false;
sConnection = new THREE.Line(lineGeometry, lineMaterial);
scope.sceneRoot.add(sConnection);
var edgeLabel = new Potree.TextSprite(0);
edgeLabel.setBorderColor({r:0, g:255, b:0, a:0.0});
edgeLabel.setBackgroundColor({r:0, g:255, b:0, a:0.0});
edgeLabel.material.depthTest = false;
edgeLabel.position.copy(I);
edgeLabel.position.y += 0.5;
scope.sceneRoot.add( edgeLabel );
//floatingOrigin.addReferenceFrame(sphere);
//floatingOrigin.addReferenceFrame(sphereEnd);
//floatingOrigin.addReferenceFrame(label);
//floatingOrigin.addReferenceFrame(labelEnd);
//floatingOrigin.addReferenceFrame(sConnection);
//floatingOrigin.addReferenceFrame(edgeLabel);
if(state === STATE.DEFAULT){
state = STATE.PICKING;
scope.activeMeasurement = new Measure();
scope.activeMeasurement.spheres.push(sphere);
}else if(state === STATE.PICKING){
}
scope.activeMeasurement.points.push(I);
scope.activeMeasurement.spheres.push(sphereEnd);
scope.activeMeasurement.sphereLabels.push(label);
scope.activeMeasurement.sphereLabels.push(labelEnd);
scope.activeMeasurement.edges.push(sConnection);
scope.activeMeasurement.edgeLabels.push(edgeLabel);
var event = {
type: 'newpoint',
position: pos.clone()
};
scope.dispatchEvent(event);
}
};
this.onMouseMove = function(event){
if(state == STATE.PICKING && scope.activeMeasurement){
var I = getMousePointCloudIntersection(event.normalizedPosition);
if(I){
var pos = I.clone();
var l = scope.activeMeasurement.spheres.length;
var sphere = scope.activeMeasurement.spheres[l-1];
var label = scope.activeMeasurement.sphereLabels[l-1];
var edge = scope.activeMeasurement.edges[l-2];
var edgeLabel = scope.activeMeasurement.edgeLabels[l-2];
var msg = pos.x.toFixed(2) + " / " + pos.y.toFixed(2) + " / " + pos.z.toFixed(2);
label.setText(msg);
sphere.position.copy(I);
label.position.copy(I);
label.position.y += 0.5;
edge.geometry.vertices[1].copy(I);
edge.geometry.verticesNeedUpdate = true;
edge.geometry.computeBoundingSphere();
var edgeLabelPos = edge.geometry.vertices[1].clone().add(edge.geometry.vertices[0]).multiplyScalar(0.5);
var edgeLabelText = edge.geometry.vertices[0].distanceTo(edge.geometry.vertices[1]).toFixed(2);
edgeLabel.position.copy(edgeLabelPos);
edgeLabel.setText(edgeLabelText);
edgeLabel.scale.multiplyScalar(10);
}
}
};
this.onRightClick = function(event){
if(state == STATE.PICKING){
var sphere = scope.activeMeasurement.spheres.pop();
var edge = scope.activeMeasurement.edges.pop();
var sphereLabel = scope.activeMeasurement.sphereLabels.pop();
var edgeLabel = scope.activeMeasurement.edgeLabels.pop();
scope.sceneRoot.remove(sphere);
scope.sceneRoot.remove(edge);
scope.sceneRoot.remove(sphereLabel);
scope.sceneRoot.remove(edgeLabel);
scope.measurements.push(scope.activeMeasurement);
scope.activeMeasurement = undefined;
state = STATE.DEFAULT;
}
}
this.onMouseDown = function(event){
if(event.which === 3){
scope.onRightClick(event);
}
}
function getMousePointCloudIntersection(mouse){
var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
var projector = new THREE.Projector();
projector.unprojectVector( vector, scope.camera );
var raycaster = new THREE.Raycaster();
raycaster.params = {"PointCloud" : {threshold: 1}};
raycaster.ray.set( scope.camera.position, vector.sub( scope.camera.position ).normalize() );
var pointClouds = [];
scope.scene.traverse(function(object){
if(object instanceof Potree.PointCloudOctree){
pointClouds.push(object);
}
});
var intersects = raycaster.intersectObjects(pointClouds, true);
if(intersects.length > 0){
var I = intersects[0];
return I.point;
}else{
return undefined;
}
}
};
Potree.MeasuringControls.prototype = Object.create( THREE.EventDispatcher.prototype );
THREE.FirstPersonControls = function ( object, domElement ) {
this.object = object;
this.domElement = ( domElement !== undefined ) ? domElement : document;
// Set to false to disable this control
this.enabled = true;
this.rotateSpeed = 1.0;
this.moveSpeed = 10.0;
this.keys = {
LEFT: 37,
UP: 38,
RIGHT: 39,
BOTTOM: 40,
A: 'A'.charCodeAt(0),
S: 'S'.charCodeAt(0),
D: 'D'.charCodeAt(0),
W: 'W'.charCodeAt(0)
};
var scope = this;
var rotateStart = new THREE.Vector2();
var rotateEnd = new THREE.Vector2();
var rotateDelta = new THREE.Vector2();
var panStart = new THREE.Vector2();
var panEnd = new THREE.Vector2();
var panDelta = new THREE.Vector2();
var panOffset = new THREE.Vector3();
var offset = new THREE.Vector3();
var phiDelta = 0;
var thetaDelta = 0;
var scale = 1;
var pan = new THREE.Vector3();
var lastPosition = new THREE.Vector3();
var STATE = { NONE : -1, ROTATE : 0, SPEEDCHANGE : 1, PAN : 2 };
var state = STATE.NONE;
// for reset
this.position0 = this.object.position.clone();
// events
var changeEvent = { type: 'change' };
var startEvent = { type: 'start'};
var endEvent = { type: 'end'};
this.rotateLeft = function ( angle ) {
thetaDelta -= angle;
};
this.rotateUp = function ( angle ) {
phiDelta -= angle;
};
// pass in distance in world space to move left
this.panLeft = function ( distance ) {
var te = this.object.matrix.elements;
// get X column of matrix
panOffset.set( te[ 0 ], te[ 1 ], te[ 2 ] );
panOffset.multiplyScalar( - distance );
pan.add( panOffset );
};
// pass in distance in world space to move up
this.panUp = function ( distance ) {
var te = this.object.matrix.elements;
// get Y column of matrix
panOffset.set( te[ 4 ], te[ 5 ], te[ 6 ] );
panOffset.multiplyScalar( distance );
pan.add( panOffset );
};
// pass in distance in world space to move forward
this.panForward = function ( distance ) {
var te = this.object.matrix.elements;
// get Y column of matrix
panOffset.set( te[ 8 ], te[ 9 ], te[ 10 ] );
panOffset.multiplyScalar( distance );
pan.add( panOffset );
};
this.pan = function ( deltaX, deltaY ) {
var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
if ( scope.object.fov !== undefined ) {
// perspective
var position = scope.object.position;
var offset = position.clone();
var targetDistance = offset.length();
// half of the fov is center to top of screen
targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 );
// we actually don't use screenWidth, since perspective camera is fixed to screen height
scope.panLeft( 2 * deltaX * targetDistance / element.clientHeight );
scope.panUp( 2 * deltaY * targetDistance / element.clientHeight );
} else if ( scope.object.top !== undefined ) {
// orthographic
scope.panLeft( deltaX * (scope.object.right - scope.object.left) / element.clientWidth );
scope.panUp( deltaY * (scope.object.top - scope.object.bottom) / element.clientHeight );
} else {
// camera neither orthographic or perspective
console.warn( 'WARNING: FirstPersonControls.js encountered an unknown camera type - pan disabled.' );
}
};
this.update = function (event) {
var delta = event.time;
var position = scope.object.position;
if(delta !== undefined){
if(scope.moveRight){
scope.panLeft(-delta * scope.moveSpeed);
}
if(scope.moveLeft){
scope.panLeft(delta * scope.moveSpeed);
}
if(scope.moveForward){
scope.panForward(-delta * scope.moveSpeed);
}
if(scope.moveBackward){
scope.panForward(delta * scope.moveSpeed);
}
}
if(!pan.equals(new THREE.Vector3(0,0,0))){
var event = {
type: 'move',
translation: pan.clone()
};
scope.dispatchEvent(event);
}
position.add(pan);
scope.object.updateMatrix();
var rot = new THREE.Matrix4().makeRotationY(thetaDelta);
var res = new THREE.Matrix4().multiplyMatrices(rot, scope.object.matrix);
scope.object.quaternion.setFromRotationMatrix(res);
scope.object.rotation.x += phiDelta;
thetaDelta = 0;
phiDelta = 0;
scale = 1;
pan.set( 0, 0, 0 );
if ( lastPosition.distanceTo( scope.object.position ) > 0 ) {
scope.dispatchEvent( changeEvent );
lastPosition.copy( scope.object.position );
}
};
this.reset = function () {
state = STATE.NONE;
this.object.position.copy( this.position0 );
};
this.onMouseDown = function( event ) {
if ( scope.enabled === false ) return;
if ( event.button === 0 ) {
state = STATE.ROTATE;
rotateStart.set( event.relativePosition.x, event.relativePosition.y );
} else if ( event.button === 2 ) {
state = STATE.PAN;
panStart.set( event.relativePosition.x, event.relativePosition.y );
}
scope.dispatchEvent( startEvent );
}
this.onMouseMove = function( event ) {
if ( scope.enabled === false ) return;
var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
if ( state === STATE.ROTATE ) {
rotateEnd.set( event.relativePosition.x, event.relativePosition.y );
rotateDelta.subVectors( rotateEnd, rotateStart );
// rotating across whole screen goes 360 degrees around
scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed );
// rotating up and down along whole screen attempts to go 360, but limited to 180
scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed );
rotateStart.copy( rotateEnd );
} else if ( state === STATE.PAN ) {
panEnd.set( event.relativePosition.x, event.relativePosition.y );
panDelta.subVectors( panEnd, panStart );
panDelta.multiplyScalar(0.0005).multiplyScalar(scope.moveSpeed);
scope.pan( panDelta.x, panDelta.y );
panStart.copy( panEnd );
}
}
this.onMouseUp = function() {
if ( scope.enabled === false ) return;
scope.dispatchEvent( endEvent );
state = STATE.NONE;
}
this.onMouseWheel = function(event) {
if ( scope.enabled === false || scope.noZoom === true ) return;
scope.moveSpeed += scope.moveSpeed * 0.001 * event.delta;
scope.moveSpeed = Math.max(0.1, scope.moveSpeed);
scope.dispatchEvent( startEvent );
scope.dispatchEvent( endEvent );
}
this.onKeyDown = function( event ) {
if ( scope.enabled === false) return;
switch ( event.keyCode ) {
case scope.keys.UP: scope.moveForward = true; break;
case scope.keys.BOTTOM: scope.moveBackward = true; break;
case scope.keys.LEFT: scope.moveLeft = true; break;
case scope.keys.RIGHT: scope.moveRight = true; break;
case scope.keys.W: scope.moveForward = true; break;
case scope.keys.S: scope.moveBackward = true; break;
case scope.keys.A: scope.moveLeft = true; break;
case scope.keys.D: scope.moveRight = true; break;
}
}
this.onKeyUp = function( event ) {
switch ( event.keyCode ) {
case scope.keys.W: scope.moveForward = false; break;
case scope.keys.S: scope.moveBackward = false; break;
case scope.keys.A: scope.moveLeft = false; break;
case scope.keys.D: scope.moveRight = false; break;
case scope.keys.UP: scope.moveForward = false; break;
case scope.keys.BOTTOM: scope.moveBackward = false; break;
case scope.keys.LEFT: scope.moveLeft = false; break;
case scope.keys.RIGHT: scope.moveRight = false; break;
}
}
};
THREE.FirstPersonControls.prototype = Object.create( THREE.EventDispatcher.prototype );

View File

@ -31,7 +31,11 @@ var paths = {
"src/LRU.js",
"src/PointCloudOctree.js",
"src/PointCloudOctreeGeometry.js",
"src/utils.js"
"src/utils.js",
"src/TextSprite.js",
"src/utils/MeasuringTool.js",
"src/utils/ProfileTool.js",
"src/utils/TranslationTool.js"
]
};

29
libs/proj4/LICENSE.md Normal file
View File

@ -0,0 +1,29 @@
##Proj4js -- Javascript reprojection library.
Authors:
- Mike Adair madairATdmsolutions.ca
- Richard Greenwood richATgreenwoodmap.com
- Didier Richard didier.richardATign.fr
- Stephen Irons stephen.ironsATclear.net.nz
- Olivier Terral oterralATgmail.com
- Calvin Metcalf cmetcalfATappgeo.com
Copyright (c) 2014, Mike Adair, Richard Greenwood, Didier Richard, Stephen Irons, Olivier Terral and Calvin Metcalf
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
_THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE._

153
libs/proj4/README.md Normal file
View File

@ -0,0 +1,153 @@
#PROJ4JS [![Build Status](https://travis-ci.org/proj4js/proj4js.svg)](https://travis-ci.org/proj4js/proj4js)
Proj4js is a JavaScript library to transform point coordinates from one coordinate system to another, including datum transformations.
Originally a port of [PROJ.4](http://trac.osgeo.org/proj/) and [GCTCP C](http://edcftp.cr.usgs.gov/pub//software/gctpc) it is
a part of the [MetaCRS](http://wiki.osgeo.org/wiki/MetaCRS) group of projects.
##Installing
Depending on your preferences
```bash
npm install proj4
bower install proj4
jam install proj4
component install proj4js/proj4js
```
or just manually grab the file `proj4.js` from the [latest release](https://github.com/proj4js/proj4js/releases).
if you do not want to download anything, Proj4js is also hosted on [cdnjs](http://www.cdnjs.com/libraries/proj4js) for direct use in your browser applications.
##Using
the basic signature is:
```javascript
proj4(fromProjection[, toProjection2, coordinates])
```
Projections can be proj or wkt strings.
Coordinates may an object of the form `{x:x,y:y}` or an array of the form `[x,y]`.
When all 3 arguments are given, the result is that the coordinates are transformed from projection1 to projection 2. And returned in the same format that they were given in.
```javascript
var firstProjection = 'PROJCS["NAD83 / Massachusetts Mainland",GEOGCS["NAD83",DATUM["North_American_Datum_1983",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4269"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",42.68333333333333],PARAMETER["standard_parallel_2",41.71666666666667],PARAMETER["latitude_of_origin",41],PARAMETER["central_meridian",-71.5],PARAMETER["false_easting",200000],PARAMETER["false_northing",750000],AUTHORITY["EPSG","26986"],AXIS["X",EAST],AXIS["Y",NORTH]]';
var secondProjection = "+proj=gnom +lat_0=90 +lon_0=0 +x_0=6300000 +y_0=6300000 +ellps=WGS84 +datum=WGS84 +units=m +no_defs";
//I'm not going to redefine those two in latter examples.
proj4(firstProjection,secondProjection,[2,5]);
// [-2690666.2977344505, 3662659.885459918]
```
If only 1 projection is given then it is assumed that it is being projected *from* WGS84 (fromProjection is WGS84).
```javascript
proj4(firstProjection,[-71,41]);
// [242075.00535055372, 750123.32090043]
```
If no coordinates are given an object with two methods is returned, its methods are `forward` which projects from the first projection to the second and `inverse` which projects from the second to the first.
```javascript
proj4(firstProjection,secondProjection).forward([2,5]);
// [-2690666.2977344505, 3662659.885459918]
proj4(secondProjection,firstProjection).inverse([2,5]);
// [-2690666.2977344505, 3662659.885459918]
```
and as above if only one projection is given, it's assumed to be coming from wgs84
```javascript
proj4(firstProjection).forward([-71,41]);
// [242075.00535055372, 750123.32090043]
proj4(firstProjection).inverse([242075.00535055372, 750123.32090043]);
//[-71, 40.99999999999986]
//the floating points to answer your question
```
## Named Projections
If you prefer to define a projection as a string and reference it that way, you may use the proj4.defs method which can be called 2 ways, with a name and projection:
```js
proj4.defs('WGS84', "+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees");
```
or with an array
```js
proj4.defs([
[
'EPSG:4326',
'+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees'],
[
'EPSG:4269',
'+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees'
]
]);
```
you can then do
```js
proj4('EPSG:4326');
```
instead of writing out the whole proj definition, by default proj4 has the following projections predefined:
- 'EPSG:4326', which has the following alias
- 'WGS84'
- 'EPSG:4269'
- 'EPSG:3857', which has the following aliases
- 'EPSG:3785'
- 'GOOGLE'
- 'EPSG:900913'
- 'EPSG:102113'
defined projections can also be accessed through the proj4.defs function (`proj4.defs('EPSG:4326')`).
proj4.defs can also be used to define a named alias:
```javascript
proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326'));
```
##Developing
to set up build tools make sure you have node and grunt-cli installed and then run `npm install`
to do the complete build and browser tests run
```bash
grunt
```
to run node tests run
```bash
npm test
```
to run node tests with coverage run
```bash
node test --coverage
```
to create a build with only default projections (latlon and Mercator) run
```bash
grunt build
```
to create a build with only custom projections include a comma separated list of projections codes (the file name in 'lib/projections' without the '.js') after a colon, e.g.
```bash
grunt build:tmerc
#includes transverse Mercator
grunt build:lcc
#includes lambert conformal conic
grunt build:omerc,moll
#includes oblique Mercator and Mollweide
```

3
libs/proj4/proj4.js Normal file

File diff suppressed because one or more lines are too long

97
libs/signals/README.md Normal file
View File

@ -0,0 +1,97 @@
# JS-Signals #
[![Build Status](https://secure.travis-ci.org/millermedeiros/js-signals.png)](https://travis-ci.org/millermedeiros/js-signals)
Custom event/messaging system for JavaScript inspired by [AS3-Signals](https://github.com/robertpenner/as3-signals).
For a more in-depth introduction read the [JS-Signals Project Page](http://millermedeiros.github.com/js-signals/) and visit the links below.
## Links ##
* [Project Page](http://millermedeiros.github.com/js-signals/)
* [Wiki](http://github.com/millermedeiros/js-signals/wiki/)
* [Documentation](http://millermedeiros.github.com/js-signals/docs)
* [Changelog](http://github.com/millermedeiros/js-signals/blob/master/CHANGELOG.md)
* [CompoundSignal - special Signal kind](https://github.com/millermedeiros/CompoundSignal)
* [jasmine-signals](https://github.com/AdamNowotny/jasmine-signals)
(Jasmine assertions to simplify signals testing)
## License ##
* [MIT License](http://www.opensource.org/licenses/mit-license.php)
## Distribution Files ##
You can use the same distribution file for all the evironments, browser script
tag, AMD, CommonJS (since v0.7.0).
Files inside `dist` folder:
* docs/index.html : Documentation.
* signals.js : Uncompressed source code with comments.
* signals.min.js : Compressed code.
You can install JS-Signals on Node.js using [NPM](http://npmjs.org/)
npm install signals
## CompoundSignal
Note that there is an advanced Signal type called `CompoundSignal` that is
compatible with js-signals v0.7.0+. It's useful for cases where you may need to
execute an action after multiple Signals are dispatched. It was split into its'
own repository since this feature isn't always needed and that way it can be
easily distributed trough npm.
[CompoundSignal repository](https://github.com/millermedeiros/CompoundSignal)
## Repository Structure ##
### Folder Structure ###
|-build -> files used on the build process
|-src -> source files
|-tests -> unit tests
`-dist -> distribution files
`-docs -> documentation
### Branches ###
master -> always contain code from the latest stable version
release-** -> code canditate for the next stable version (alpha/beta)
develop -> main development branch (nightly)
**other** -> features/hotfixes/experimental, probably non-stable code
## Building your own ##
This project uses [Apache Ant](http://ant.apache.org/) for the build process. If for some reason you need to build a custom version of JS-Signals install Ant and run:
ant build
This will delete all JS files inside the `dist` folder, merge/update/compress source files, validate generated code using [JSLint](http://www.jslint.com/) and copy the output to the `dist` folder.
There is also another ant task that runs the build task and generate
documentation (used before each deploy):
ant deploy
**IMPORTANT:** `dist` folder always contain the latest version, regular users should **not** need to run build task.
## Running Tests ##
The specs work on the browser and on node.js, during development you can use
the `spec/runner_dev.html` file to avoid doing a build every time you make
changes to the source files. On node.js you need to run `ant compile` after
each source file change otherwise `npm test` will execute the files from last
build - not adding it as a `pretest` script since the build adds information
about the build date and build number and that would pollute the commit
history.

14
libs/signals/signals.min.js vendored Normal file
View File

@ -0,0 +1,14 @@
/*
JS Signals <http://millermedeiros.github.com/js-signals/>
Released under the MIT license
Author: Miller Medeiros
Version: 1.0.0 - Build: 268 (2012/11/29 05:48 PM)
*/
(function(i){function h(a,b,c,d,e){this._listener=b;this._isOnce=c;this.context=d;this._signal=a;this._priority=e||0}function g(a,b){if(typeof a!=="function")throw Error("listener is a required param of {fn}() and should be a Function.".replace("{fn}",b));}function e(){this._bindings=[];this._prevParams=null;var a=this;this.dispatch=function(){e.prototype.dispatch.apply(a,arguments)}}h.prototype={active:!0,params:null,execute:function(a){var b;this.active&&this._listener&&(a=this.params?this.params.concat(a):
a,b=this._listener.apply(this.context,a),this._isOnce&&this.detach());return b},detach:function(){return this.isBound()?this._signal.remove(this._listener,this.context):null},isBound:function(){return!!this._signal&&!!this._listener},isOnce:function(){return this._isOnce},getListener:function(){return this._listener},getSignal:function(){return this._signal},_destroy:function(){delete this._signal;delete this._listener;delete this.context},toString:function(){return"[SignalBinding isOnce:"+this._isOnce+
", isBound:"+this.isBound()+", active:"+this.active+"]"}};e.prototype={VERSION:"1.0.0",memorize:!1,_shouldPropagate:!0,active:!0,_registerListener:function(a,b,c,d){var e=this._indexOfListener(a,c);if(e!==-1){if(a=this._bindings[e],a.isOnce()!==b)throw Error("You cannot add"+(b?"":"Once")+"() then add"+(!b?"":"Once")+"() the same listener without removing the relationship first.");}else a=new h(this,a,b,c,d),this._addBinding(a);this.memorize&&this._prevParams&&a.execute(this._prevParams);return a},
_addBinding:function(a){var b=this._bindings.length;do--b;while(this._bindings[b]&&a._priority<=this._bindings[b]._priority);this._bindings.splice(b+1,0,a)},_indexOfListener:function(a,b){for(var c=this._bindings.length,d;c--;)if(d=this._bindings[c],d._listener===a&&d.context===b)return c;return-1},has:function(a,b){return this._indexOfListener(a,b)!==-1},add:function(a,b,c){g(a,"add");return this._registerListener(a,!1,b,c)},addOnce:function(a,b,c){g(a,"addOnce");return this._registerListener(a,
!0,b,c)},remove:function(a,b){g(a,"remove");var c=this._indexOfListener(a,b);c!==-1&&(this._bindings[c]._destroy(),this._bindings.splice(c,1));return a},removeAll:function(){for(var a=this._bindings.length;a--;)this._bindings[a]._destroy();this._bindings.length=0},getNumListeners:function(){return this._bindings.length},halt:function(){this._shouldPropagate=!1},dispatch:function(a){if(this.active){var b=Array.prototype.slice.call(arguments),c=this._bindings.length,d;if(this.memorize)this._prevParams=
b;if(c){d=this._bindings.slice();this._shouldPropagate=!0;do c--;while(d[c]&&this._shouldPropagate&&d[c].execute(b)!==!1)}}},forget:function(){this._prevParams=null},dispose:function(){this.removeAll();delete this._bindings;delete this._prevParams},toString:function(){return"[Signal active:"+this.active+" numListeners:"+this.getNumListeners()+"]"}};var f=e;f.Signal=e;typeof define==="function"&&define.amd?define(function(){return f}):typeof module!=="undefined"&&module.exports?module.exports=f:i.signals=
f})(this);

View File

@ -0,0 +1,8 @@
Point cloud courtesy of sigeom sa, http://www.sigeom.ch/
Rue des Oeuches 45
2740 Moutier
Switzerland
This is a small subsample of the original dataset.

View File

@ -0,0 +1,61 @@
{
"version": "1.3",
"octreeDir": "data",
"boundingBox": {
"lx": 589500,
"ly": 231300,
"lz": 722.505,
"ux": 590100,
"uy": 231900,
"uz": 1322.5
},
"pointAttributes": [
"POSITION_CARTESIAN",
"COLOR_PACKED"
],
"spacing": 4,
"hierarchy": [
["r", 7216],
["r0", 13528],
["r4", 15110],
["r00", 16867],
["r02", 9126],
["r04", 16556],
["r06", 9022],
["r40", 17735],
["r42", 11099],
["r44", 16810],
["r46", 13343],
["r000", 14480],
["r002", 12859],
["r004", 12308],
["r006", 13143],
["r020", 14888],
["r024", 11722],
["r026", 42],
["r040", 12458],
["r042", 12109],
["r044", 13674],
["r046", 12629],
["r060", 11858],
["r062", 939],
["r064", 12096],
["r066", 2128],
["r400", 17040],
["r402", 13750],
["r404", 15026],
["r406", 14224],
["r420", 13019],
["r422", 3833],
["r424", 14990],
["r426", 5513],
["r440", 13117],
["r442", 13087],
["r444", 12760],
["r446", 12802],
["r460", 14258],
["r462", 6718],
["r464", 16970],
["r466", 8016]
]
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,3 @@
oôIabHP-;DAf1˙hôIRbHw.;DStN˙·ôI‚bHo";DHl3˙űôIDbHŮ&;DUzD˙đôI@bH/%;DLt?˙őIVbH;;DBiE˙ÂôIpbHü!;DVyB˙˝ôIXbH##;DLp<˙_ôIDbH˘-;DLp2˙őIdbH&;Do•P˙ÍôIubH##;DT|A˙°ôI[bH´ ;Dc<44>I˙ÉôIFbH{$;DRz<˙<>ôIpbHR(;DIm2˙śôIHbHJ,;DCg)˙“ôIEbH–3;DR|@˙<>ôIWbH10;DAf/˙őI<>bH-;D:_>˙ŮôILbHŮ&;D[<5B>?˙ÖôIobHç#;DHn;˙
őI¦bH¤ ;D:a-˙|ôIDbH5;DU{>˙›ôItbHu+;D]<5D>F˙éôIibHĹ(;DIr<˙ůôIťbH%&;DEk4˙őIvbH
';D=b0˙őIťbHÉ;DNt>˙-ôIGbHĎ/;DNvB˙ăôI“bHh);DHq9˙őI}bHÍ$;DPt>˙úôIpbHH);DSzB˙őISbHP%;DRu@˙őIŞbH¦#;DLr<˙zôIfbHĽ,;DOx?˙ĄôIKbH`%;DCgD˙‹ôIWbH *;Da…F˙¬ôI}bHĽ$;DTy@˙TôIUbH10;DBk6˙ŢôIebH‹$;DEl5˙ÓôIŽbHž;DJo9˙IôIPbHŞ1;DEp:˙8ôIHbHd3;DMv@˙

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

49
src/BitReader.js Normal file
View File

@ -0,0 +1,49 @@
/**
* Reads unsigned integers encoded in a variable amount of bits from the buffer.
* Bits are aligned into 32bit unsigned integers.
* for example, given 3 integers:
* x: 123 encoded in 11 bits, binary: 00001111011
* y: 7945 encoded in 17 bits, binary: 00001111100001001
* z: 12 encoded in 6 bits, binary: 001100
*
* | --- 32 bits --- || --- 32 bits --- |
* |................................||................................|
* |00001111011000011111000010010011||00
* | x || y || z |
*
* z does not fit fully into the first 32 bit integer.
* The first 4 bits of z are stored at the end of the first 32 bit integer
* and the remaining 2 bits at the next 32 bit integer.
*
*/
BitReader = function(buf){
var buffer = new Uint32Array(buf);
var bitOffset = 0;
this.read = function(bits){
var result;
if((bitOffset % 32) + bits <= 32){
var val = buffer[Math.floor(bitOffset / 32)];
var leftGap = bitOffset % 32;
var rightGap = 32 - (leftGap + bits);
result = (val << leftGap) >>> (leftGap + rightGap);
}else{
var val = buffer[Math.floor(bitOffset / 32)];
var leftGap = bitOffset % 32;
var rightGap = (leftGap + bits) - 32;
result = (val << leftGap) >>> (leftGap - rightGap)
val = buffer[Math.floor(bitOffset / 32)+1];
result = result | val >>> (32 - rightGap);
}
bitOffset += bits;
return result;
}
}

View File

@ -248,6 +248,8 @@ THREE.FirstPersonControls = function ( object, domElement ) {
} else if ( state === STATE.PAN ) {
panEnd.set( event.clientX, event.clientY );
panDelta.subVectors( panEnd, panStart );
//panDelta.multiplyScalar(this.moveSpeed).multiplyScalar(0.0001);
panDelta.multiplyScalar(0.0005).multiplyScalar(scope.moveSpeed);
scope.pan( panDelta.x, panDelta.y );

View File

@ -36,6 +36,7 @@ Potree.PointCloudOctree = function(geometry, material){
this.LODFalloff = 1.3;
this.LOD = 4;
this.showBoundingBox = false;
this.loadQueue = [];
var rootProxy = new Potree.PointCloudOctreeProxyNode(this.pcoGeometry.root);
@ -47,6 +48,7 @@ Potree.PointCloudOctree.prototype = Object.create(THREE.Object3D.prototype);
Potree.PointCloudOctree.prototype.update = function(camera){
this.numVisibleNodes = 0;
this.numVisiblePoints = 0;
this.loadQueue = [];
// create frustum in object space
camera.updateMatrixWorld();
@ -64,7 +66,6 @@ Potree.PointCloudOctree.prototype.update = function(camera){
var camObjPos = new THREE.Vector3().setFromMatrixPosition( camMatrixObject );
var ray = new THREE.Ray(camera.position, new THREE.Vector3( 0, 0, -1 ).applyQuaternion( camera.quaternion ) );
//var ray = new THREE.Ray(camera.position, new THREE.Vector3( 0, -1, 0 ) );
// check visibility
var stack = [];
@ -78,20 +79,18 @@ Potree.PointCloudOctree.prototype.update = function(camera){
}
var box = object.boundingBox;
//var tbox = Potree.utils.computeTransformedBoundingBox(box, this.matrixWorld);
var distance = box.center().distanceTo(camObjPos);
var radius = box.size().length() * 0.5;
var visible = true;
visible = visible && frustum.intersectsBox(box);
if(object.level > 1){
if(object.level > 0){
// cull detail nodes based in distance to camera
visible = visible && Math.pow(radius, 0.8) / distance > (1 / this.LOD);
visible = visible && (this.numVisiblePoints + object.numPoints < Potree.pointLoadLimit);
visible = visible && (this.numVisibleNodes <= this.maxVisibleNodes);
visible = visible && (this.numVisiblePoints <= this.maxVisiblePoints);
}else{
//visible = true;
}
// trying to skip higher detail nodes, if parents already cover all holes
@ -131,12 +130,29 @@ Potree.PointCloudOctree.prototype.update = function(camera){
Potree.PointCloudOctree.lru.touch(object);
object.material = this.material;
}else if (object instanceof Potree.PointCloudOctreeProxyNode) {
this.replaceProxy(object);
var geometryNode = object.geometryNode;
if(geometryNode.loaded === true){
this.replaceProxy(object);
}else{
this.loadQueue.push({node: object, lod: Math.pow(radius, 0.8) / distance});
}
}
for(var i = 0; i < object.children.length; i++){
stack.push(object.children[i]);
}
//console.log(object.name);
}
if(this.loadQueue.length > 0){
if(this.loadQueue.length >= 2){
this.loadQueue.sort(function(a,b){return b.lod - a.lod});
}
for(var i = 0; i < Math.min(5, this.loadQueue.length); i++){
this.loadQueue[i].node.geometryNode.load();
}
}
}
@ -163,8 +179,6 @@ Potree.PointCloudOctree.prototype.replaceProxy = function(proxy){
node.add(childProxy);
}
}
}else{
geometryNode.load();
}
}
@ -217,6 +231,52 @@ Potree.PointCloudOctree.prototype.getBoundingBoxWorld = function(){
return tBox;
}
Potree.PointCloudOctree.prototype.getProfile = function(start, end, width, depth){
var stack = [];
stack.push(this);
var side = new THREE.Vector3().subVectors(end, start).normalize();
var up = new THREE.Vector3(0, 1, 0);
var forward = new THREE.Vector3().crossVectors(side, up).normalize();
var N = forward;
var cutPlane = new THREE.Plane().setFromNormalAndCoplanarPoint(N, start);
var inside = [];
while(stack.length > 0){
var object = stack.shift();
console.log("traversing: " + object.name);
if(object instanceof THREE.PointCloud){
var geometry = object.geometry;
var positions = geometry.attributes.position;
var p = positions.array;
var pointCount = positions.length / positions.itemSize;
for(var i = 0; i < pointCount; i++){
var pos = new THREE.Vector3(p[3*i], p[3*i+1], p[3*i+2]);
pos.applyMatrix4(this.matrixWorld);
var distance = Math.abs(cutPlane.distanceToPoint(pos));
if(distance < width/2){
inside.push(pos);
}
}
}
if(object == this || object.level < depth){
for(var i = 0; i < object.children.length; i++){
stack.push(object.children[i]);
}
}
}
console.log("points inside: " + inside.length);
return inside;
}
/**
*

View File

@ -51,7 +51,86 @@ Potree.PointCloudOctreeGeometryNode.prototype.load = function(){
nodesLoadTimes[url] = {};
nodesLoadTimes[url].start = new Date().getTime();
LasLazLoader.load(url, new Potree.LasLazBatcher(this, url));
}else {
} else if ( pointAttributes === "POT"){
var callback = function(node, buffer){
var dv = new DataView(buffer, 0, 4);
var headerSize = dv.getUint32(0, true);
var pointOffset = 4 + headerSize;
var headerBuffer = buffer.slice(4, 4 + headerSize);
var header = String.fromCharCode.apply(null, new Uint8Array(headerBuffer));
header = JSON.parse(header);
console.log(header);
var pScale = header.attributes[0].scale;
var pOffset = header.attributes[0].offset;
var pEncoding = header.attributes[0].encoding;
var scale = new THREE.Vector3(pScale[0], pScale[1], pScale[2]);
var offset = new THREE.Vector3(pOffset[0], pOffset[1], pOffset[2]);
var min = pEncoding.min;
var max = pEncoding.max;
var bits = pEncoding.bits;
var pointBuffer = buffer.slice(pointOffset, pointOffset + buffer.byteLength - pointOffset);
var br = new BitReader(pointBuffer);
var X = br.read(32);
var Y = br.read(32);
var Z = br.read(32);
var r = br.read(8);
var g = br.read(8);
var b = br.read(8);
var geometry = new THREE.BufferGeometry();
var numPoints = header.pointcount;
var positions = new Float32Array(numPoints*3);
var colors = new Float32Array(numPoints*3);
var color = new THREE.Color();
for(var i = 0; i < header.pointcount - 1; i++){
dx = br.read(bits[0]) + min[0];
dy = br.read(bits[1]) + min[1];
dz = br.read(bits[2]) + min[2];
X = X + dx;
Y = Y + dy;
Z = Z + dz;
x = X * scale.x + offset.x;
y = Y * scale.y + offset.y;
z = Z * scale.z + offset.z;
r = br.read(8);
g = br.read(8);
b = br.read(8);
positions[3*i+0] = x;// + node.pcoGeometry.offset.x;
positions[3*i+1] = y;// + node.pcoGeometry.offset.y;
positions[3*i+2] = z;// + node.pcoGeometry.offset.z;
colors[3*i+0] = r / 255;
colors[3*i+1] = g / 255;
colors[3*i+2] = b / 255;
}
geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3));
geometry.boundingBox = node.boundingBox;
node.geometry = geometry;
node.loaded = true;
node.loading = false;
node.pcoGeometry.numNodesLoading--;
};
Potree.BinaryNodeLoader.load(this, "pot", callback);
} else {
// load binary node files
var url = this.pcoGeometry.octreeDir + "/" + this.name;
@ -94,7 +173,7 @@ Potree.PointCloudOctreeGeometryNode.prototype.load = function(){
nodesLoadTimes[url] = {};
nodesLoadTimes[url].start = new Date().getTime();
Potree.BinaryNodeLoader.load(this, callback);
Potree.BinaryNodeLoader.load(this, "", callback);
}
}
@ -102,8 +181,11 @@ Potree.BinaryNodeLoader = function(){
}
Potree.BinaryNodeLoader.load = function(node, callback){
Potree.BinaryNodeLoader.load = function(node, extension, callback){
var url = node.pcoGeometry.octreeDir + "/" + node.name;
if(extension !== undefined && extension.length > 0){
url += "." + extension;
}
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';

108
src/TextSprite.js Normal file
View File

@ -0,0 +1,108 @@
/**
* adapted from http://stemkoski.github.io/Three.js/Sprite-Text-Labels.html
*/
Potree.TextSprite = function(text){
var texture = new THREE.Texture();
var spriteMaterial = new THREE.SpriteMaterial(
{ map: texture, useScreenCoordinates: false} );
THREE.Sprite.call(this, spriteMaterial);
this.borderThickness = 4;
this.fontface = "Arial";
this.fontsize = 28;
this.borderColor = { r:0, g:0, b:0, a:1.0 };
this.backgroundColor = { r:255, g:255, b:255, a:1.0 };
this.text = "";
this.setText(text);
};
Potree.TextSprite.prototype = new THREE.Sprite();
Potree.TextSprite.prototype.setText = function(text){
this.text = text;
this.update();
}
Potree.TextSprite.prototype.setBorderColor = function(color){
this.borderColor = color;
this.update();
}
Potree.TextSprite.prototype.setBackgroundColor = function(color){
this.backgroundColor = color;
this.update();
}
Potree.TextSprite.prototype.update = function(){
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = "Bold " + this.fontsize + "px " + this.fontface;
// get size data (height depends only on font size)
var metrics = context.measureText( this.text );
var textWidth = metrics.width;
var spriteWidth = textWidth + 2 * this.borderThickness;
var spriteHeight = this.fontsize * 1.4 + 2 * this.borderThickness;
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.canvas.width = spriteWidth;
context.canvas.height = spriteHeight;
context.font = "Bold " + this.fontsize + "px " + this.fontface;
// background color
context.fillStyle = "rgba(" + this.backgroundColor.r + "," + this.backgroundColor.g + ","
+ this.backgroundColor.b + "," + this.backgroundColor.a + ")";
// border color
context.strokeStyle = "rgba(" + this.borderColor.r + "," + this.borderColor.g + ","
+ this.borderColor.b + "," + this.borderColor.a + ")";
context.lineWidth = this.borderThickness;
this.roundRect(context, this.borderThickness/2, this.borderThickness/2,
textWidth + this.borderThickness, this.fontsize * 1.4 + this.borderThickness, 6);
// text color
context.strokeStyle = "rgba(0, 0, 0, 1.0)";
context.strokeText( this.text, this.borderThickness, this.fontsize + this.borderThickness);
context.fillStyle = "rgba(255, 255, 255, 1.0)";
context.fillText( this.text, this.borderThickness, this.fontsize + this.borderThickness);
var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
//var spriteMaterial = new THREE.SpriteMaterial(
// { map: texture, useScreenCoordinates: false } );
this.material.map = texture;
this.scale.set(spriteWidth*0.01,spriteHeight*0.01,1.0);
//this.material = spriteMaterial;
}
Potree.TextSprite.prototype.roundRect = function(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x+r, y);
ctx.lineTo(x+w-r, y);
ctx.quadraticCurveTo(x+w, y, x+w, y+r);
ctx.lineTo(x+w, y+h-r);
ctx.quadraticCurveTo(x+w, y+h, x+w-r, y+h);
ctx.lineTo(x+r, y+h);
ctx.quadraticCurveTo(x, y+h, x, y+h-r);
ctx.lineTo(x, y+r);
ctx.quadraticCurveTo(x, y, x+r, y);
ctx.closePath();
ctx.fill();
ctx.stroke();
}

214
src/utils/MeasuringTool.js Normal file
View File

@ -0,0 +1,214 @@
Potree.MeasuringTool = function(scene, camera, domElement){
var scope = this;
this.scene = scene;
this.camera = camera;
this.domElement = domElement;
this.mouse = {x: 0, y: 0};
var STATE = {
DEFAULT: 0,
PICKING: 1
};
var state = STATE.DEFAULT;
this.activeMeasurement;
this.measurements = [];
this.sceneMeasurement = new THREE.Scene();
this.sceneRoot = new THREE.Object3D();
this.sceneMeasurement.add(this.sceneRoot);
function Measure(){
this.points = [];
this.spheres = [];
this.edges = [];
this.sphereLabels = [];
this.edgeLabels = [];
}
function onDoubleClick(event){
var I = getMousePointCloudIntersection();
if(I){
var pos = I.clone();
var sphereMaterial = new THREE.MeshNormalMaterial({shading: THREE.SmoothShading})
var sphereGeometry = new THREE.SphereGeometry(0.4, 10, 10);
var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.position.copy(I);
scope.sceneRoot.add(sphere);
var sphereEnd = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphereEnd.position.copy(I);
scope.sceneRoot.add(sphereEnd);
var msg = pos.x.toFixed(2) + " / " + pos.y.toFixed(2) + " / " + pos.z.toFixed(2);
var label = new Potree.TextSprite(msg);
label.setBorderColor({r:0, g:255, b:0, a:1.0});
label.material.depthTest = false;
label.material.opacity = 0;
label.position.copy(I);
label.position.y += 0.5;
scope.sceneRoot.add( label );
var labelEnd = new Potree.TextSprite(msg);
labelEnd.setBorderColor({r:0, g:255, b:0, a:1.0});
labelEnd.material.depthTest = false;
labelEnd.material.opacity = 0;
labelEnd.position.copy(I);
labelEnd.position.y += 0.5;
scope.sceneRoot.add( labelEnd );
var lc = new THREE.Color( 0xff0000 );
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push(I.clone(), I.clone());
lineGeometry.colors.push(lc, lc, lc);
var lineMaterial = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
lineMaterial.depthTest = false;
sConnection = new THREE.Line(lineGeometry, lineMaterial);
scope.sceneRoot.add(sConnection);
var edgeLabel = new Potree.TextSprite(0);
edgeLabel.setBorderColor({r:0, g:255, b:0, a:0.0});
edgeLabel.setBackgroundColor({r:0, g:255, b:0, a:0.0});
edgeLabel.material.depthTest = false;
edgeLabel.position.copy(I);
edgeLabel.position.y += 0.5;
scope.sceneRoot.add( edgeLabel );
//floatingOrigin.addReferenceFrame(sphere);
//floatingOrigin.addReferenceFrame(sphereEnd);
//floatingOrigin.addReferenceFrame(label);
//floatingOrigin.addReferenceFrame(labelEnd);
//floatingOrigin.addReferenceFrame(sConnection);
//floatingOrigin.addReferenceFrame(edgeLabel);
if(state === STATE.DEFAULT){
state = STATE.PICKING;
scope.activeMeasurement = new Measure();
scope.activeMeasurement.spheres.push(sphere);
}else if(state === STATE.PICKING){
}
scope.activeMeasurement.points.push(I);
scope.activeMeasurement.spheres.push(sphereEnd);
scope.activeMeasurement.sphereLabels.push(label);
scope.activeMeasurement.sphereLabels.push(labelEnd);
scope.activeMeasurement.edges.push(sConnection);
scope.activeMeasurement.edgeLabels.push(edgeLabel);
var event = {
type: 'newpoint',
position: pos.clone()
};
scope.dispatchEvent(event);
}
};
function onMouseMove(event){
scope.mouse.x = ( event.clientX / scope.domElement.clientWidth ) * 2 - 1;
scope.mouse.y = - ( event.clientY / scope.domElement.clientHeight ) * 2 + 1;
if(state == STATE.PICKING && scope.activeMeasurement){
var I = getMousePointCloudIntersection();
if(I){
var pos = I.clone();
var l = scope.activeMeasurement.spheres.length;
var sphere = scope.activeMeasurement.spheres[l-1];
var label = scope.activeMeasurement.sphereLabels[l-1];
var edge = scope.activeMeasurement.edges[l-2];
var edgeLabel = scope.activeMeasurement.edgeLabels[l-2];
var msg = pos.x.toFixed(2) + " / " + pos.y.toFixed(2) + " / " + pos.z.toFixed(2);
label.setText(msg);
sphere.position.copy(I);
label.position.copy(I);
label.position.y += 0.5;
edge.geometry.vertices[1].copy(I);
edge.geometry.verticesNeedUpdate = true;
edge.geometry.computeBoundingSphere();
var edgeLabelPos = edge.geometry.vertices[1].clone().add(edge.geometry.vertices[0]).multiplyScalar(0.5);
var edgeLabelText = edge.geometry.vertices[0].distanceTo(edge.geometry.vertices[1]).toFixed(2);
edgeLabel.position.copy(edgeLabelPos);
edgeLabel.setText(edgeLabelText);
edgeLabel.scale.multiplyScalar(10);
}
}
};
function onRightClick(event){
if(state == STATE.PICKING){
var sphere = scope.activeMeasurement.spheres.pop();
var edge = scope.activeMeasurement.edges.pop();
var sphereLabel = scope.activeMeasurement.sphereLabels.pop();
var edgeLabel = scope.activeMeasurement.edgeLabels.pop();
scope.sceneRoot.remove(sphere);
scope.sceneRoot.remove(edge);
scope.sceneRoot.remove(sphereLabel);
scope.sceneRoot.remove(edgeLabel);
scope.measurements.push(scope.activeMeasurement);
scope.activeMeasurement = undefined;
state = STATE.DEFAULT;
}
}
function onMouseDown(event){
if(event.which === 3){
onRightClick(event);
}
}
function getMousePointCloudIntersection(){
var vector = new THREE.Vector3( scope.mouse.x, scope.mouse.y, 0.5 );
var projector = new THREE.Projector();
projector.unprojectVector( vector, scope.camera );
var raycaster = new THREE.Raycaster();
raycaster.params = {"PointCloud" : {threshold: 1}};
raycaster.ray.set( scope.camera.position, vector.sub( scope.camera.position ).normalize() );
var pointClouds = [];
scope.scene.traverse(function(object){
if(object instanceof Potree.PointCloudOctree){
pointClouds.push(object);
}
});
var intersects = raycaster.intersectObjects(pointClouds, true);
if(intersects.length > 0){
var I = intersects[0];
return I.point;
}else{
return undefined;
}
}
this.domElement.addEventListener("dblclick", onDoubleClick, false);
this.domElement.addEventListener( 'mousemove', onMouseMove, false );
this.domElement.addEventListener( 'mousedown', onMouseDown, false );
};
Potree.MeasuringTool.prototype = Object.create( THREE.EventDispatcher.prototype );

84
src/utils/ProfileTool.js Normal file
View File

@ -0,0 +1,84 @@
Potree.ProfileTool = function(width, height, depth){
THREE.Object3D.call( this );
var boxGeometry = new THREE.BoxGeometry(1,1,1,1,1,1);
var boxMaterial = new THREE.MeshBasicMaterial({color: 0xFF0000, transparent: true, opacity: 0.3});
this.profileFrustum = new THREE.Mesh(boxGeometry, boxMaterial);
this.add(this.profileFrustum);
this.camera = new THREE.OrthographicCamera( -width / 2, width / 2, height / 2, -height / 2, 1, 1 + depth );
this.add(this.camera);
this.setDimension(width, height, depth);
this.rtProfile = new THREE.WebGLRenderTarget( 512, 512, { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBFormat } );
this.hudGeometry = new THREE.BoxGeometry(2,2,1);
this.hudMaterial = new THREE.MeshBasicMaterial( { color: 0xffffff, map: this.rtProfile } );
this.hudMaterial.depthTest = false;
this.hudElement = new THREE.Mesh(this.hudGeometry, this.hudMaterial);
this.hudElement.scale.set(1,1,1);
this.hudElement.position.set(0, 0, 0);
}
Potree.ProfileTool.prototype = Object.create( THREE.Object3D.prototype );
Potree.ProfileTool.prototype.setDimension = function(width, height, depth){
this.profileFrustum.scale.set(width, height, depth);
this.width = width;
this.height = height;
this.depth = depth;
this.camera.left = -width / 2;
this.camera.right = width / 2;
this.camera.top = height / 2;
this.camera.bottom = -height / 2;
this.camera.updateProjectionMatrix();
}
Potree.ProfileTool.prototype.setOrientation = function(forward, side){
var oldPosition = this.position.clone();
this.position.add(forward);
this.lookAt(oldPosition);
this.position.copy(oldPosition);
this.camera.position.copy(oldPosition.clone().add(forward));
this.camera.lookAt(oldPosition);
}
Potree.ProfileTool.prototype.render = function(renderer, scene){
this.camera.matrixWorld.copy(this.matrixWorld);
//TODO maybe we should store old sizes in a map instead of the objects
scene.traverse(function(object){
if(object instanceof Potree.PointCloudOctree){
object.material.oldSize = object.material.size;
object.material.size = 0;
}
});
renderer.render(scene, this.camera, this.rtProfile, true);
scene.traverse(function(object){
if(object instanceof Potree.PointCloudOctree){
object.material.size = object.material.oldSize;
}
});
//this.hudElement.scale.x = 0.5;
//this.hudElement.scale.y = 0.5 * (renderer.domElement.clientWidth / renderer.domElement.clientHeight) * (this.height / this.width);
//this.hudElement.position.x = 0.7;
//this.hudElement.position.y = -0.7;
}

View File

@ -0,0 +1,250 @@
Potree.TranslationTool = function(camera) {
THREE.Object3D.call( this );
var scope = this;
this.camera = camera;
this.geometry = new THREE.Geometry();
this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
this.STATE = {
DEFAULT: 0,
TRANSLATE_X: 1,
TRANSLATE_Y: 2,
TRANSLATE_Z: 3
};
this.parts = {
ARROW_X : {name: "arrow_x", object: undefined, color: new THREE.Color( 0xff0000 ), state: this.STATE.TRANSLATE_X},
ARROW_Y : {name: "arrow_y", object: undefined, color: new THREE.Color( 0x00ff00 ), state: this.STATE.TRANSLATE_Y},
ARROW_Z : {name: "arrow_z", object: undefined, color: new THREE.Color( 0x0000ff ), state: this.STATE.TRANSLATE_Z}
}
this.translateStart;
this.state = this.STATE.DEFAULT;
this.highlighted;
this.targets;
this.build = function(){
var arrowX = scope.createArrow(scope.parts.ARROW_X, scope.parts.ARROW_X.color);
arrowX.rotation.z = -Math.PI/2;
var arrowY = scope.createArrow(scope.parts.ARROW_Y, scope.parts.ARROW_Y.color);
var arrowZ = scope.createArrow(scope.parts.ARROW_Z, scope.parts.ARROW_Z.color);
arrowZ.rotation.x = -Math.PI/2;
scope.add(arrowX);
scope.add(arrowY);
scope.add(arrowZ);
var boxXY = scope.createBox(new THREE.Color( 0xffff00 ));
boxXY.scale.z = 0.02;
boxXY.position.set(0.5, 0.5, 0);
var boxXZ = scope.createBox(new THREE.Color( 0xff00ff ));
boxXZ.scale.y = 0.02;
boxXZ.position.set(0.5, 0, -0.5);
var boxYZ = scope.createBox(new THREE.Color( 0x00ffff ));
boxYZ.scale.x = 0.02;
boxYZ.position.set(0, 0.5, -0.5);
scope.add(boxXY);
scope.add(boxXZ);
scope.add(boxYZ);
scope.parts.ARROW_X.object = arrowX;
scope.parts.ARROW_Y.object = arrowY;
scope.parts.ARROW_Z.object = arrowZ;
scope.scale.multiplyScalar(5);
};
this.createBox = function(color){
var boxGeometry = new THREE.BoxGeometry(1, 1, 1);
var boxMaterial = new THREE.MeshBasicMaterial({color: color, transparent: true, opacity: 0.5});
var box = new THREE.Mesh(boxGeometry, boxMaterial);
return box;
};
this.createArrow = function(partID, color){
var material = new THREE.MeshBasicMaterial({color: color});
var shaftGeometry = new THREE.CylinderGeometry(0.1, 0.1, 3, 10, 1, false);
var shaftMatterial = material;
var shaft = new THREE.Mesh(shaftGeometry, shaftMatterial);
shaft.position.y = 1.5;
var headGeometry = new THREE.CylinderGeometry(0, 0.3, 1, 10, 1, false);
var headMaterial = material;
var head = new THREE.Mesh(headGeometry, headMaterial);
head.position.y = 3;
var arrow = new THREE.Object3D();
arrow.add(shaft);
arrow.add(head);
arrow.partID = partID;
arrow.material = material;
return arrow;
};
this.setHighlighted = function(partID){
if(partID === undefined){
if(scope.highlighted){
scope.highlighted.object.material.color = scope.highlighted.color;
scope.highlighted = undefined;
}
return;
}else if(scope.highlighted !== undefined && scope.highlighted !== partID){
scope.highlighted.object.material.color = scope.highlighted.color;
}
scope.highlighted = partID;
partID.object.material.color = new THREE.Color(0xffff00);
}
this.getHoveredObject = function(mouse){
var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
var projector = new THREE.Projector();
projector.unprojectVector( vector, scope.camera );
var raycaster = new THREE.Raycaster();
raycaster.ray.set( scope.camera.position, vector.sub( scope.camera.position ).normalize() );
var intersections = raycaster.intersectObject(scope, true);
if(intersections.length === 0){
scope.setHighlighted(undefined);
return undefined;
}
var I = intersections[0];
var partID = I.object.parent.partID;
return partID;
}
this.onMouseMove = function(event){
var mouse = event.normalizedPosition;
if(scope.state === scope.STATE.DEFAULT){
scope.setHighlighted(scope.getHoveredObject(mouse));
}else if(scope.state === scope.STATE.TRANSLATE_X || scope.state === scope.STATE.TRANSLATE_Y || scope.state === scope.STATE.TRANSLATE_Z){
var origin = scope.start.lineStart.clone();
var direction = scope.start.lineEnd.clone().sub(scope.start.lineStart);
direction.normalize();
var mousePoint = new THREE.Vector3(mouse.x, mouse.y);
var directionDistance = new THREE.Vector3().subVectors(mousePoint, origin).dot(direction);
var pointOnLine = direction.clone().multiplyScalar(directionDistance).add(origin);
var projector = new THREE.Projector();
projector.unprojectVector(pointOnLine, scope.camera);
var diff = pointOnLine.clone().sub(scope.position);
scope.position.copy(pointOnLine);
for(var i = 0; i < scope.targets.length; i++){
var target = scope.targets[0];
target.position.add(diff);
}
event.signal.halt();
}
};
this.onMouseDown = function(event){
if(scope.state === scope.STATE.DEFAULT){
var hoveredObject = scope.getHoveredObject(event.normalizedPosition, scope.camera);
if(hoveredObject){
scope.state = hoveredObject.state;
var lineStart = scope.position.clone();
var lineEnd;
if(scope.state === scope.STATE.TRANSLATE_X){
lineEnd = scope.position.clone();
lineEnd.x += 2;
}else if(scope.state === scope.STATE.TRANSLATE_Y){
lineEnd = scope.position.clone();
lineEnd.y += 2;
}else if(scope.state === scope.STATE.TRANSLATE_Z){
lineEnd = scope.position.clone();
lineEnd.z -= 2;
}
//lineEnd = scope.position.clone();
var projector = new THREE.Projector();
projector.projectVector( lineStart, scope.camera );
projector.projectVector( lineEnd, scope.camera );
scope.start = {
mouse: event.normalizedPosition,
lineStart: lineStart,
lineEnd: lineEnd
};
event.signal.halt();
}
}
};
this.onMouseUp = function(event){
scope.setHighlighted();
scope.state = scope.STATE.DEFAULT;
};
this.setTargets = function(targets){
scope.targets = targets;
if(scope.targets.length === 0){
return;
}
//TODO calculate centroid of all targets
var centroid = targets[0].position.clone();
//for(var i = 0; i < targets.length; i++){
// var target = targets[i];
//}
scope.position.copy(centroid);
}
this.build();
};
Potree.TranslationTool.prototype = Object.create( THREE.Object3D.prototype );