awv3
Version:
⚡ AWV3 embedded CAD
460 lines (408 loc) • 17.4 kB
JavaScript
import * as THREE from 'three';
import v4 from 'uuid-v4';
import * as Error from './error';
import { queryDom, setPrefixedValue } from './helpers';
import { lastCreated } from './canvas';
import DomEvents from './dom';
import Interaction from './interaction';
import Stats from '../misc/stats';
import Orbit from '../controls/orbit';
import CombinedCamera from '../three/combinedcamera';
import Events from '../core/events';
import checkResize from 'element-resize-event';
/** A view represents a portion of canvas on which webGL can draw.
The view is defined and tracked by a dom node on which the drawing take place. */
export default class View extends Events {
/** Construct a new View
@param {Object} [canvas=lastCreated] - The parent canvas, if none defined the lastCreated will be used
@param {Object} [options={}] - this.options to initialize the View with
@param {HTMLElement} [options.dom=canvas.dom] - The HTML element on which the view will draw
@param {Boolean} [options.renderAlways=false] - Set to true the view will render 60fps,
set to false it will render on changes (default, recommended)
@param {Boolean} [options.visible=true] - Set to true the view will render
@param {Function} [options.callbackBefore=undefined] - Callback before the render pass
@param {Function} [options.callbackRender=undefined] - Callback to custom-render the scene
@param {Function} [options.callbackAfter=undefined] - Callback after the render pass
@param {Number} [options.background=canvas.renderer.clearColor] - Background color
@param {Number} [options.opacity=0.0] - Background opacity
@param {Number} [options.ambientColor=0xffffff] - Ambient color
@param {Number} [options.ambientIntensity=1.0] - Ambient intensity
@example
import View from 'view';
// Create a view, defaults into the same dom as the canvas
const view = new View(canvas, { dom: '#view', ambient: 0x909090 });
// Add model to the view's scene
view.scene.add(model);
@returns {Object} The constructed View */
constructor(canvas = lastCreated, options = {}) {
super();
this.id = v4();
this.canvas = canvas;
this.renderer = canvas.renderer;
this.resolution = this.renderer.resolution;
this.invalidateFrames = 2;
this.force = 0;
this.dirty = true;
this.bounds = {
box: new THREE.Box3(),
sphere: new THREE.Sphere(),
};
this.options = {
dom: canvas.dom,
renderAlways: false,
visible: true,
callback: undefined,
callbackRender: undefined,
callbackAfter: undefined,
background: this.renderer.clearColor,
opacity: 0,
defaultCursor: 'auto',
...options,
};
this.dom = queryDom(this.options.dom);
this.renderAlways = this.options.renderAlways;
this.visible = this.options.visible;
this.callbackBefore = this.options.callback;
this.callbackRender = this.options.callbackRender;
this.callbackAfter = this.options.callbackAfter;
this.background = this.options.background;
this.opacity = this.options.opacity;
this.defaultCursor = this.options.defaultCursor;
// Make sure the view hides overflow and is not selectable
this.options.dom.style.cssText +=
'-webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; overlay: hidden';
// A border will hide gaps caused by imprecise layout returns
if (this.options.background !== this.renderer.clearColor)
this.dom.style.border = `2px solid #${this.background.getHexString()}`;
this.input = new DomEvents(this, {
wheel: state => {
this.controls.onMouseWheel(state);
this.hud.forEach(hud => hud.onMouseWheel(state));
},
mouseout: state => {
this.interaction.onMouseOut(state);
},
mousemove: state => {
this.interaction.onMouseMove(state);
this.input.mouse.down && this.controls.onMouseMove(state);
this.input.mouse.down && this.hud.forEach(hud => hud.onMouseMove(state));
},
mousedown: state => {
this.interaction.onMouseDown(state);
this.controls.onMouseDown(state);
this.hud.forEach(hud => hud.onMouseDown(state));
},
mouseup: state => {
this.interaction.onMouseUp(state);
this.controls.onMouseUp(state);
this.hud.forEach(hud => hud.onMouseUp(state));
},
touchstart: state => {
this.interaction.onMouseDown(state);
this.controls.onTouchStart(state);
this.hud.forEach(hud => hud.onTouchStart(state));
},
touchmove: state => {
this.interaction.onMouseMove(state);
this.controls.onTouchMove(state);
this.hud.forEach(hud => hud.onTouchMove(state));
},
touchend: state => {
this.interaction.onMouseUp(state);
this.controls.onTouchEnd(state);
this.hud.forEach(hud => hud.onTouchEnd(state));
},
});
this.scene = new THREE.Scene();
this.scene.canvas = canvas;
this.scene.view = this;
this.ambient = new THREE.AmbientLight(this.options.ambientColor ? this.options.ambientColor : 0xffffff);
this.ambient.intensity = typeof this.options.ambientIntensity !== 'undefined' ? this.options.ambientIntensity : 1.0;
this.ambient.keep = true;
this.ambient.view = this;
this.scene.add(this.ambient);
this.camera = new CombinedCamera(this, this.options);
// his.camera = Being set by the above
this.controls = new Orbit(this, {
maxPolarAngle: Math.PI,
minDistance: 1,
maxDistance: 20000,
...this.options,
});
this.hud = [];
this.interaction = new Interaction(this);
this.updateScopes();
this.canvas.views.push(this);
this.renderer.resize();
checkResize(this.dom, () => this.invalidate(30));
if (this.options.stats) {
this.showStats = true;
}
}
destroy() {
if (!this.__destroyed) {
this.__destroyed = true;
this.input.detach();
this.input.removeListeners();
this.input.removeInspectors();
this.scene.destroy({ keep: false });
this.render = function() {};
this.clear = function() {};
this.view = undefined;
this.canvas = undefined;
this.renderer = undefined;
this.bound = undefined;
this.input = undefined;
this.scene = undefined;
this.hud.forEach(hud => hud.destroy());
this.hud = [];
this.dom.querySelector('object').remove();
let parent = this.dom;
while (!!parent && parent != this.canvas.dom) {
let scope = this.canvas.scopes.get(parent);
if (scope) this.canvas.scopes.set(parent, scope.filter(s => s !== this));
parent = parent.parentNode;
}
this.dom = undefined;
}
}
addHud(obj) {
this.hud = this.hud.concat(obj);
}
removeHud(obj) {
this.hud = this.hud.filter(hud => hud !== obj);
}
get hudInMotion() {
return (
this.hud.length > 0 && this.hud.reduce((acc, val) => ({ inMotion: acc.inMotion && val.inMotion })).inMotion
);
}
set showStats(value) {
if (this.stats) {
this.stats.remove();
this.stats = undefined;
}
if (value) {
this.stats = new Stats();
this.dom.appendChild(this.stats.dom);
}
}
/** Sets the cursor style. Applies when the mouse is inside the view's rect.
@param {String} style='auto' - CSS cursor style
@param {String} [fallback] - Fallback style, should the target style not be available
@example
// 'grab' is available in WebKit and Blink only
view.setCursor('grab', 'move'); */
setCursor(style = this.defaultCursor, fallback) {
if (style != this.cursor) {
setPrefixedValue(this.dom, 'cursor', style, fallback);
this.cursor = style;
}
return this;
}
/** Projects 2-dimensional coordinate from a 3-dimensional point within the view's scene.
@param {THREE.Vector3} point3 - Input point
@example
// Grab x and y off THREE's projected Vector2
let {x, y} = view.getPoint2D(new THREE.Vector3(10, 20, 100));
@returns {THREE.Vector2} The projected point */
getPoint2(point3, camera = this.camera.display) {
let widthHalf = this.width / 2, heightHalf = this.height / 2;
let vector = point3.project(camera);
vector.x = vector.x * widthHalf + widthHalf;
vector.y = -(vector.y * heightHalf) + heightHalf;
return vector;
}
/**
* Projects a 2D point into 3D space. Z-Value for the 2D-Point can be passed within bounds of 0 to 1.
* Note: maximal depth is used by default (z = 1), so the point is on the "far" frustum (with huge coordinates)
*/
getPoint3(point2, camera = this.camera.display, zValue = 1) {
let vector = new THREE.Vector3(point2.x / this.width * 2 - 1, -(point2.y / this.height) * 2 + 1, zValue);
vector.unproject(camera);
return vector;
}
///returns a line of all the points corresponding to given 2D view coords
getViewLine3(point2, camera = this.camera.display) {
let near = new THREE.Vector3(point2.x / this.width * 2 - 1, -(point2.y / this.height) * 2 + 1, 0);
let far = new THREE.Vector3(point2.x / this.width * 2 - 1, -(point2.y / this.height) * 2 + 1, 1);
near.unproject(camera);
far.unproject(camera);
return new THREE.Line3(near, far);
}
/**
* Calculate the scale factor that will make the object at the point3 position be radiusPx pixels wide.
* Example use: object.scale.set(calculateScaleFactor(object.getWorldPosition(), radiusPx));
* @param point3 Vector3 position of the object
* @param radiusPx Number desired radius of the object in pixels
* @return Number scale factor for the object
*/
calculateScaleFactor(point3, radiusPx, camera = this.camera.display) {
const point2 = this.getPoint2(point3.clone());
let scale = 0;
for (let i = 0; i < 2; ++i) {
const point2off = point2.clone().setComponent(i, point2.getComponent(i) + radiusPx);
const point3off = this.getPoint3(point2off, camera, point2off.z);
scale = Math.max(scale, point3.distanceTo(point3off));
}
return scale;
}
updateOverlays() {}
updateScopes() {
let parent = this.dom;
while (!!parent && parent != this.canvas.dom) {
let scope = this.canvas.scopes.get(parent);
if (scope) scope.push(this);
else this.canvas.scopes.set(parent, [this]);
parent = parent.parentNode;
}
}
clear(time) {
// Measure and check if dirty (size & position changed)
this.dirty = this.invalidateFrames > 0 && this.measure();
if (this.visible) {
// Call event scheduler
this.input.debounce && this.input.update();
// Update controls
this.controls.update(time);
this.hud.forEach(hud => hud.update(time));
// Update interaction
this.interaction.update();
if (
this.dirty ||
this.renderAlways ||
this.controls.inMotion ||
this.hudInMotion
) {
// Clear canvas only if dirty, it isn't necessary for simple interaction
if (this.dirty) {
this.renderer.dirty = true;
this.renderer.gl.setViewport(this.old[0], this.old[1], this.old[2], this.old[3]);
this.renderer.gl.setScissor(
this.old[0] * this.resolution,
this.old[1] * this.resolution,
this.old[2] * this.resolution,
this.old[3] * this.resolution,
);
this.renderer.gl.setClearColor(this.renderer.clearColor, 0);
this.renderer.gl.clear();
}
}
}
// Remove frames
if (this.invalidateFrames > 0) this.invalidateFrames--;
return this.dirty;
}
render(time) {
if (
this.force > 0 ||
this.dirty ||
this.renderAlways ||
this.controls.inMotion ||
this.stats ||
this.hudInMotion
) {
this.callbackBefore && this.callbackBefore();
this.renderer.gl.setViewport(this.new[0], this.new[1], this.new[2], this.new[3]);
this.renderer.gl.setScissor(
this.new[0] * this.resolution,
this.new[1] * this.resolution,
this.new[2] * this.resolution,
this.new[3] * this.resolution,
);
var camera = this.camera;
if (!this.callbackRender) {
this.renderer.gl.setClearColor(this.background, this.opacity);
this.renderer.gl.clear();
this.renderer.gl.render(this.scene, this.camera.display);
this.renderer.gl.clearDepth();
this.hud.forEach(hud => hud.render());
} else this.callbackRender();
this.callbackAfter && this.callbackAfter();
this.stats && this.stats.update();
if (this.force > 0) this.force--;
}
}
invalidate(frames = 1) {
this.force += frames;
if (this.force > 60) this.force = 60;
this.invalidateFrames += frames;
if (this.invalidateFrames > 60) this.invalidateFrames = 60;
return this;
}
measure(force) {
let dirty = false;
let bounds = this.dom.getBoundingClientRect();
let offset = {
top: bounds.top,
left: bounds.left,
width: bounds.width,
height: bounds.height,
};
offset.top -= this.renderer.offset.top;
offset.left -= this.renderer.offset.left;
// Size changed, calibrate & invalidate
if (force || offset.width != this.width || offset.height != this.height) {
this.calibrate(offset.width, offset.height);
this.invalidate(10);
dirty = true;
this.emit(View.Events.SizeChanged, offset);
}
// Position changed, invalidate!
if (force || offset.top != this.top || offset.left != this.left) {
this.invalidate(10);
dirty = true;
this.emit(View.Events.PositionChanged, offset);
}
// Save old data
this.old = [
this.left /* this.renderer.resolution*/,
this.bottom /* this.renderer.resolution*/,
this.width /* this.renderer.resolution*/,
this.height /* this.renderer.resolution*/,
];
// Apply new
this.width = offset.width;
this.height = offset.height;
this.top = offset.top;
this.left = offset.left;
this.bottom = this.renderer.offset.height - offset.height - offset.top;
// Premultiply new
this.new = [
this.left /* this.renderer.resolution*/,
this.bottom /* this.renderer.resolution*/,
this.width /* this.renderer.resolution*/,
this.height /* this.renderer.resolution*/,
];
// Check visibility
let visible = !(this.height <= 0 ||
this.width <= 0 ||
this.top >= this.renderer.offset.height ||
this.left >= this.renderer.offset.width ||
this.top + this.height <= 0 ||
this.left + this.width <= 0);
if (this.visible != visible) {
this.visible = visible;
this.visible && this.invalidate(10);
dirty = true;
}
return dirty;
}
calibrate(width, height) {
this.aspect = width / height;
this.camera.aspect = this.aspect;
this.camera.updateProjectionMatrix();
this.camera.radius = (width + height) / 4;
this.hud.forEach(hud => hud.calibrate(width, height));
}
updateBounds(box = undefined) {
this.scene.updateBounds(box);
this.bounds.box = this.scene.bounds.box;
this.bounds.sphere = this.scene.bounds.sphere;
return this;
}
static Events = {
SizeChanged: 'SizeChanged',
PositionChanged: 'PositionChanged',
};
}