Merge branch 'master' into geo_object_instancing

# Conflicts:
#	src/og/entity/Entity.js
#	src/og/math/Mat4.js
#	src/og/webgl/Handler.js
#	src/og/webgl/callbacks.js
#	tests/Globe.test.js
This commit is contained in:
Zemledelec 2021-11-13 00:07:12 +03:00
commit febe57e601
123 changed files with 5525 additions and 4251 deletions

View File

@ -1,14 +1,17 @@
module.exports = {
"env": {
"browser": true,
"jest": true,
"es2021": true
env: {
browser: true,
jest: true,
es2021: true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 13,
"sourceType": "module"
extends: "eslint:recommended",
parserOptions: {
ecmaVersion: 13,
sourceType: "module"
},
"rules": {
rules: {
"no-unused-vars": 0,
"no-useless-escape": 0,
"no-loss-of-precision": 0
}
};

View File

@ -28,7 +28,6 @@ jobs:
with:
node-version: 16
registry-url: https://registry.npmjs.org/
- run: npm ci
- run: npm run generate_types
- run: npm publish
env:

View File

@ -57,7 +57,7 @@
opacity: 0.7,
visibility: true,
isBaseLayer: false,
url: "//openglobus.org/geoserver/",
url: "//openglobus.org:8080/geoserver/",
layers: "topp:states",
transparentColor: [1.0, 1.0, 1.0]
});

View File

@ -88,7 +88,7 @@
extent: [[-128, 24], [-66, 49]],
visibility: false,
isBaseLayer: false,
url: "//openglobus.org/geoserver/",
url: "//openglobus.org:8080/geoserver/",
layers: "topp:states",
opacity: 0.4,
attribution: 'Hi!',

View File

@ -6,6 +6,10 @@ npm install @openglobus/og --save
yarn add @openglobus/og
```
### Code: using reactjs
[example](https://github.com/tbo47/openglobus_grafana)
### Code: using in Angular
```javascript

View File

@ -5,4 +5,5 @@ module.exports = {
coverageProvider: "v8",
setupFiles: ["jest-canvas-mock", "jest-webgl-canvas-mock"],
testEnvironment: "jsdom",
setupFilesAfterEnv: ["./tests/setupTests.js"]
};

2173
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{
"name": "@openglobus/og",
"version": "0.11.2",
"version": "0.11.5",
"description": "[OpenGlobus](http://www.openglobus.org/) is a javascript library designed to display interactive 3d maps and planets with map tiles, imagery and vector data, markers and 3d objects. It uses the WebGL technology, open source and completely free.",
"directories": {
"example": "./sandbox"
@ -18,6 +18,7 @@
"test_watch": "jest --env=jsdom --watch",
"lint": "eslint src/og",
"generate_types": "rm -rf types; tsc src/**/*.js --declaration --allowJs --emitDeclarationOnly --outDir types; exit 0",
"compile_js_as_ts": "tsc src/og/index.js --AllowJs --checkJs --outDir dist/@openglobus/src/",
"prepare": "husky install"
},
"repository": {
@ -43,21 +44,22 @@
"./css/og.css": "./css/og.css"
},
"devDependencies": {
"@babel/preset-env": "^7.15.8",
"@babel/preset-env": "^7.16.0",
"@rollup/plugin-json": "^4.1.0",
"eslint": "^8.0.1",
"husky": "^7.0.2",
"@types/jest": "^27.0.2",
"eslint": "^8.2.0",
"husky": "^7.0.4",
"jaguarjs-jsdoc": "^1.1.0",
"jest": "^27.2.5",
"jest": "^27.3.1",
"jest-canvas-mock": "^2.3.1",
"jest-webgl-canvas-mock": "^0.2.3",
"jsdoc": "^3.6.7",
"lint-staged": "^11.2.3",
"lint-staged": "^11.2.6",
"local-web-server": "^5.1.1",
"msdf-bmfont-xml": "^2.5.4",
"postcss": "^8.3.9",
"postcss": "^8.3.11",
"prettier": "^2.4.1",
"rollup": "^2.58.0",
"rollup": "^2.60.0",
"rollup-plugin-postcss": "^4.0.1",
"rollup-plugin-terser": "^7.0.2",
"typescript": "^4.4.4"

View File

@ -1,110 +1,24 @@
//'use strict';
//import { Globe } from '../../src/og/Globe.js';
//import { GlobusTerrain } from '../../src/og/terrain/GlobusTerrain.js';
//import { BilTerrain } from '../../src/og/terrain/BilTerrain.js';
//import { MapboxTerrain } from '../../src/og/terrain/MapboxTerrain.js';
//import { EmptyTerrain } from '../../src/og/terrain/EmptyTerrain.js';
//import { XYZ } from '../../src/og/layer/XYZ.js';
//import { WMS } from '../../src/og/layer/WMS.js';
import { Globe } from "../../src/og/Globe.js";
import { Entity } from "../../src/og/entity/Entity.js";
import { XYZ } from "../../src/og/layer/XYZ.js";
import { CanvasTiles } from "../../src/og/layer/CanvasTiles.js";
//import { Vector } from '../../src/og/layer/Vector.js';
//import { Entity } from '../../src/og/entity/Entity.js';
import { DebugInfo } from "../../src/og/control/DebugInfo.js";
//import { KeyboardNavigation } from '../../src/og/control/KeyboardNavigation.js';
import { ToggleWireframe } from "../../src/og/control/ToggleWireframe.js";
//import * as math from '../../src/og/math.js';
//import { LayerSwitcher } from '../../src/og/control/LayerSwitcher.js';
//import { Popup } from '../../src/og/Popup.js';
import { LonLat } from "../../src/og/LonLat.js";
//import { Vec3 } from '../../src/og/math/Vec3.js';
//import { ScaleControl } from '../../src/og/control/ScaleControl.js';
//import { stringTemplate } from '../../src/og/utils/shared.js';
//import { SegmentBoundVisualization } from '../../src/og/control/SegmentBoundVisualization.js';
//function toQuadKey(x, y, z) {
// var index = '';
// for (var i = z; i > 0; i--) {
// var b = 0;
// var mask = 1 << (i - 1);
// if ((x & mask) !== 0) b++;
// if ((y & mask) !== 0) b += 2;
// index += b.toString();
// }
// return index;
//};
//let bing = new XYZ("sat", {
// shininess: 20,
// isBaseLayer: false,
// subdomains: ['t0', 't1', 't2', 't3'],
// url: "https://ecn.{s}.tiles.virtualearth.net/tiles/a{quad}.jpeg?n=z&g=7146",
// visibility: true,
// attribution: `Bing`,
// maxNativeZoom: 19,
// defaultTextures: [{ color: "#001522" }, { color: "#E4E6F3" }],
// urlRewrite: function (s, u) {
// return stringTemplate(u, {
// 's': this._getSubdomain(),
// 'quad': toQuadKey(s.tileX, s.tileY, s.tileZoom)
// });
// }
//});
//// document.getElementById("ambient-r").addEventListener("input", function (e) {
//// osm.ambient.x = this.value;
//// document.querySelector(".value.ambient-r").innerHTML = this.value;
//// });
//// document.getElementById("ambient-g").addEventListener("input", function (e) {
//// osm.ambient.y = this.value;
//// document.querySelector(".value.ambient-g").innerHTML = this.value;
//// });
//// document.getElementById("ambient-b").addEventListener("input", function (e) {
//// osm.ambient.z = this.value;
//// document.querySelector(".value.ambient-b").innerHTML = this.value;
//// });
//// document.getElementById("diffuse-r").addEventListener("input", function (e) {
//// osm.diffuse.x = this.value;
//// document.querySelector(".value.diffuse-r").innerHTML = this.value;
//// });
//// document.getElementById("diffuse-g").addEventListener("input", function (e) {
//// osm.diffuse.y = this.value;
//// document.querySelector(".value.diffuse-g").innerHTML = this.value;
//// });
//// document.getElementById("diffuse-b").addEventListener("input", function (e) {
//// osm.diffuse.z = this.value;
//// document.querySelector(".value.diffuse-b").innerHTML = this.value;
//// });
//// document.getElementById("specular-r").addEventListener("input", function (e) {
//// osm.specular.x = this.value;
//// document.querySelector(".value.specular-r").innerHTML = this.value;
//// });
//// document.getElementById("specular-g").addEventListener("input", function (e) {
//// osm.specular.y = this.value;
//// document.querySelector(".value.specular-g").innerHTML = this.value;
//// });
//// document.getElementById("specular-b").addEventListener("input", function (e) {
//// osm.specular.z = this.value;
//// document.querySelector(".value.specular-b").innerHTML = this.value;
//// });
//// document.getElementById("shininess").addEventListener("input", function (e) {
//// osm.shininess = this.value;
//// document.querySelector(".value.shininess").innerHTML = this.value;
//// });
let cnv = document.createElement("canvas");
let ctx = cnv.getContext("2d");
cnv.width = 256;
cnv.height = 256;
import { Vector } from "../../src/og/layer/Vector.js";
import { GlobusTerrain } from "../../src/og/terrain/GlobusTerrain.js";
import { EmptyTerrain } from "../../src/og/terrain/EmptyTerrain.js";
import { labelXYZ } from "./labelXYZ.js";
const tg = new CanvasTiles("Tile grid", {
visibility: true,
isBaseLayer: false,
zIndex: 100,
drawTile: function (material, applyCanvas) {
//
// This is important create canvas here!
//
let cnv = document.createElement("canvas");
let ctx = cnv.getContext("2d");
cnv.width = 256;
cnv.height = 256;
//Clear canvas
ctx.clearRect(0, 0, cnv.width, cnv.height);
@ -117,276 +31,44 @@ const tg = new CanvasTiles("Tile grid", {
let size;
//Draw text
if (material.segment.tileZoom > 17) {
size = "18";
} else if (material.segment.tileZoom > 14) {
size = "26";
} else {
size = "32";
}
if (material.segment.isPole) {
let ext = material.segment.getExtentLonLat();
ctx.fillStyle = "black";
ctx.font = "normal " + size + "px Verdana";
ctx.textAlign = "center";
ctx.fillText(
material.segment.tileX + "," + material.segment.tileY + "," + material.segment.tileZoom,
cnv.width / 2,
cnv.height / 2
);
ctx.fillRect(0, 0, 256, 256);
//ctx.font = 'normal ' + 29 + 'px Verdana';
//ctx.textAlign = 'center';
//ctx.fillText(`${ext.northEast.lon.toFixed(3)} ${ext.northEast.lat.toFixed(3)}`, cnv.width / 2, cnv.height / 2 + 20);
//ctx.fillText(`${ext.southWest.lon.toFixed(3)} ${ext.southWest.lat.toFixed(3)}`, cnv.width / 2, cnv.height / 2 - 20);
} else {
ctx.fillRect(0, 0, 256, 256);
//Draw text
// if (material.segment.tileZoom > 14) {
// size = "26";
// } else {
// size = "32";
// }
// ctx.fillStyle = 'black';
// ctx.font = 'normal ' + size + 'px Verdana';
// ctx.textAlign = 'center';
// ctx.fillText(material.segment.tileX + "," + material.segment.tileY + "," + material.segment.tileZoom, cnv.width / 2, cnv.height / 2);
}
//Draw canvas tile
applyCanvas(cnv);
}
});
//let osm = new XYZ("OSM", {
// 'isBaseLayer': true,
// 'url': "//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
// 'visibility': true,
// 'attribution': 'Data @ OpenStreetMap contributors, ODbL'
//});
////let wien = new XYZ("512", {
//// 'isBaseLayer': true,
//// 'url': "//maps.wien.gv.at/basemap/bmaphidpi/normal/google3857/{z}/{y}/{x}.jpeg",
//// 'visibility': false
////});
////let sat = new XYZ("MapQuest Satellite", {
//// shininess: 20,
//// specular: [0.00048, 0.00037, 0.00035],
//// diffuse: [0.88, 0.85, 0.8],
//// ambient: [0.15, 0.1, 0.23],
//// isBaseLayer: true,
//// url: "//api.mapbox.com/styles/v1/mapbox/satellite-v9/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoibWdldmxpY2hzY2FuZXgiLCJhIjoiY2pwcGdsaXlnMDQzdDQybXhsOWZlbXBvdSJ9.fR2YE-ehJA4iajaJBAPKvw",
//// visibility: false,
//// attribution: `@2014 MapQuest - Portions @2014 "Map data @
//// <a target="_blank" href="//www.openstreetmap.org/">OpenStreetMap</a> and contributors,
//// <a target="_blank" href="//opendatacommons.org/licenses/odbl/"> CC-BY-SA</a>"`
////});
//let sat = new XYZ("Google Satellite", {
// shininess: 20,
// specular: [0.00048, 0.00037, 0.00035],
// diffuse: [0.88, 0.85, 0.8],
// ambient: [0.15, 0.1, 0.23],
// isBaseLayer: true,
// url: "https://khms1.googleapis.com/kh?v=894&hl=en-GB&x={x}&y={y}&z={z}",
// visibility: false,
// attribution: ``
//});
//let thames = new XYZ("Reconstructed Lakebed", {
// fading: true,
// isBaseLayer: false,
// visibility: true,
// url: "http://alacst.ddns.net:8181/Tiles/1xoverlay/{z}/{x}/{y}.png",
// // extent: [[-1.1210868226, 51.5993282113], [-1.11506810397, 51.6072360341]]
// extent: [[-1.12047, 51.60076], [-1.11807, 51.60285]]
//});
//let emptyTerrain = new EmptyTerrain(),
// globusTerrain = new GlobusTerrain(),
// mapboxTerrain = new MapboxTerrain(),
// bilTerrain = new BilTerrain({
// maxZoom: 19,
// url: "//127.0.0.1:8080/geoserver/",
// //url: "//95.211.82.211:8080/geoserver/og/",
// //layers: "og:n44_e009_1arc_v3",
// layers: "test:geotiff_coverage_2",
// //layers: "arizona:3",
// //imageSize: 129,
// gridSizeByZoom: [64, 16, 16, 16, 16, 16, 16, 16, 16, 16, 32, 16, 32, 16, 32, 16, 32, 16, 32, 16, 8, 4],
// //extent: [[8.9, 44.0], [10.0, 45]]
// });
//window.globe = new Globe({
// 'name': "Earth",
// 'target': "earth",
// 'terrain': /*bilTerrain/*/globusTerrain/*new MapboxTerrain(null, {
// url: "//alacst.ddns.net:8181/Tiles/testtile129/{z}/{x}/{y}.png",
// //url: "//alacst.ddns.net:8181/Tiles/129terrain/{z}/{x}/{y}.png",
// minZoom: 9,
// maxZoom: 23,
// gridSizeByZoom: [64, 32, 32, 16, 16, 16, 16, 32, 64, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 64, 32, 16],
// sourceImageSize: 129,
// equalizeVertices: false
// })*/,
// 'layers': [osm, tg, sat],
// 'viewExtent': [89.83484, 25.69255, 90.34796, 26.44652]
//});
//window.setEmptyTerrain = function () {
// window.globe.planet.setTerrain(emptyTerrain);
//};
//window.setOpenglobusTerrain = function () {
// window.globe.planet.setTerrain(globusTerrain);
//};
//window.setBilTerrain = function () {
// window.globe.planet.setTerrain(bilTerrain);
//};
//window.setMapboxTerrain = function () {
// window.globe.planet.setTerrain(mapboxTerrain);
//};
////window.globe = new Globe({
//// 'name': "Earth",
//// 'target': "earth",
//// 'terrain': new GlobusTerrain(),
//// 'layers': [osm, sat, tg, states, modis],
//// 'viewExtent': [7.86, 44.24, 11.29, 45.0]
////});
////window.globe = new Globe({
//// target: "earth",
//// name: "Bil Terrain Source",
//// terrain: new BilTerrain({
//// url: "//95.211.82.211:8080/geoserver/og/",
//// layers: "og:n44_e009_1arc_v3",
//// imageSize: 128,
//// gridSizeByZoom: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 64, 64, 32, 32, 32, 16, 8],
//// extent: [[8.9, 44.0], [10.0, 45]]
//// }),
//// viewExtent: [7.86, 44.24, 11.29, 45.0],
//// layers: [osm, sat, tg, states, modis]
////});
////globe.planet.addControl(new SegmentBoundVisualization());
//globe.planet.addControl(new KeyboardNavigation());
//globe.planet.addControl(new LayerSwitcher());
////globe.planet.addControl(new ScaleControl());
//let e1 = new Entity({
// 'name': 'strip1',
// 'strip': {
// 'color': [0 / 255, 38 / 255, 255 / 255],
// 'opacity': 0.27,
// 'path': [
// [[586523.0151173624, 4392830.957760274, 4570544.574074627], [587043.0890180465, 4396726.110503412, 4574597.306676116]],
// [[693687.4135420445, 4446600.854589337, 4502800.243641092], [694306.9328021071, 4450572.030680254, 4506821.6103556845]],
// [[695057.6327224943, 4446368.161289945, 4502875.06522507], [695283.9105581088, 4447815.688108607, 4504340.988014539]],
// [[695379.6262299116, 4446451.841945512, 4502776.850023308], [695603.3364033864, 4447882.307370998, 4504225.435734251]]
// ],
// }
//});
//let e2 = new Entity({
// 'name': 'strip2',
// 'strip': {
// 'color': [0 / 255, 38 / 255, 255 / 255],
// 'opacity': 0.27,
// 'path': [
// [[661936.3048841777, 4745603.382222995, 4189411.525681237], [1339051.734436527, 9600030.082993329, 8474892.113242555]],
// [[1126928.1072783293, 4760811.647727539, 4071007.90108061], [2277324.752646721, 9620768.297494425, 8226795.481871399]]
// ],
// }
//});
//let stripLayer = new Vector("test layer", {
// 'entities': [e1, e2],
// 'pickingEnabled': true,
// 'visibility': true
//});
//globe.planet.addLayer(stripLayer);
////new Vector("Markers", {
//// clampToGround: false,
//// polygonOffsetUnits: 0
////})
//// .addTo(globe.planet)
//// .add(new Entity({
//// lonlat: [5.73, 45.183, 273.5],
//// label: {
//// text: "Hi, Globus!",
//// outline: 0.77,
//// outlineColor: "rgba(255,255,255,.4)",
//// size: 27,
//// color: "black",
//// face: "Lucida Console",
//// offset: [10, -2]
//// },
//// billboard: {
//// src: "./marker.png",
//// width: 64,
//// height: 64,
//// offset: [0, 32]
//// }
//// }));
////globe.planet.viewExtentArr([-1.13284, 51.59951, -1.10951, 51.60386]);
////let myPopup = new Popup({
//// planet: globe.planet,
//// content: `Simple HTML popup<br>See <a href="//openglobus.org/examples/billboardsOnTHeGround/billboardsOnTHeGround.html">popup example</a>`,
//// offset: [0, 0],
//// lonLat: [5.73, 45.183, 273.5],
//// visibility: true
////});
////window.myPopup = myPopup;
////globe.planet.viewLonLat(new LonLat(-112.99778159686288, 37.23755430287543, 8952.673764926381));
////import { Globe } from '../../src/og/Globe.js';
////import { XYZ } from '../../src/og/layer/XYZ.js';
////import { GlobusTerrain } from '../../src/og/terrain/GlobusTerrain.js';
////import { Vec3 } from '../../src/og/math/Vec3.js';
////import { LonLat } from '../../src/og/LonLat.js';
////import { Vector } from '../../src/og/layer/Vector.js';
////import { Entity } from '../../src/og/entity/Entity.js';
////import { wgs84 } from '../../src/og/ellipsoid/wgs84.js';
////var osm = new XYZ("OpenStreetMap", {
//// isBaseLayer: true,
//// url: "//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
//// visibility: true,
//// attribution: 'Data @ OpenStreetMap contributors, ODbL'
////});
////let size = 1000000;
////let ellipsoid = wgs84;
////let startlonlat = new LonLat(51.5, 7, 0);
////let endlonlat = new LonLat(51.5, 7, 1000);
////let startPos = ellipsoid.lonLatToCartesian(startlonlat);
////let endPos = ellipsoid.lonLatToCartesian(endlonlat);
////let e = new Entity({
//// 'ray': {
//// 'startPosition': startPos,
//// 'endPosition': endPos,
//// 'length': size,
//// 'startColor': "red",
//// 'endColor': "green",
//// 'thickness': 10
//// }
////});
////let rayLayer = new Vector("rays", {
//// 'polygonOffsetUnits': 0
////});
////rayLayer.add(e);
////var globus = new Globe({
//// "target": "earth",
//// "name": "Earth",
//// "terrain": new GlobusTerrain(),
//// "layers": [osm, rayLayer],
//// "sun": {
//// "active": true
//// }
////});
import { Globe } from "../../src/og/Globe.js";
import { Entity } from "../../src/og/entity/Entity.js";
import { XYZ } from "../../src/og/layer/XYZ.js";
import { Vector } from "../../src/og/layer/Vector.js";
import { GlobusTerrain } from "../../src/og/terrain/GlobusTerrain.js";
import { EmptyTerrain } from "../../src/og/terrain/EmptyTerrain.js";
const labelLayer = new labelXYZ("labelLayer", {
isBaseLayer: false,
visibility: true,
// zIndex: GlobeConst.labelZIndex,
url: "//t.ssl.ak.dynamic.tiles.virtualearth.net/comp/ch/{key}?mkt=en-us&it=Z%2CGF%2CL&shading=hill&og=1471&n=z&ur=JP&js=1&cstl=in&st=me|lv:0_pp|lv:1_cr|lv:1_ad|lv:1&nvlos=1&vpt=e,p&pll=1&ell=1",
countryLayerData: "//assets.msn.com/weathermapdata/1/static/3d/label.0.1/country-{}.json",
height: 16,
size: 11.5,
color: "white"
});
var osm = new XYZ("OpenStreetMap", {
isBaseLayer: true,
@ -398,87 +80,14 @@ var osm = new XYZ("OpenStreetMap", {
var globus = new Globe({
target: "earth",
name: "Earth",
terrain: /*new EmptyTerrain({
gridSizeByZoom: [32, 16, 16, 8, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
}),/*/ new GlobusTerrain(),
useEarthNavigation: true,
layers: [osm /*, tg*/]
//'viewExtent': [-1.12135, 51.60133, -1.11704, 51.60224]
maxAltitude: 15000000,
minAltitude: 4200000,
terrain: new EmptyTerrain({
gridSizeByZoom: [32, 32, 32, 32, 16, 8, 8]
}),
layers: [labelLayer, tg],
useNightTexture: false,
useSpecularTexture: false
});
fetch("./szint.json")
.then((r) => {
return r.json();
})
.then((data) => {
var countries = new Vector("Countries", {
visibility: true,
isBaseLayer: false,
diffuse: [0, 0, 0],
ambient: [1, 1, 1]
});
countries.addTo(globus.planet);
var f = data.features;
for (var i = 0; i < f.length; i++) {
var fi = f[i];
countries.add(
new Entity({
geometry: {
type: fi.geometry.type,
coordinates: fi.geometry.coordinates,
style: {
fillColor: "rgba(255,255,0,1.0)",
lineColor: "rgba(255,255,0,1.0)"
}
}
})
);
}
//countries.events.on("mouseleave", function (e) {
// e.pickingObject.geometry.setFillColor(1, 1, 1, 0.6);
// e.pickingObject.geometry.setLineColor(0.2, 0.6, 0.8, 1.0);
//});
//countries.events.on("mouseenter", function (e) {
// e.pickingObject.geometry.bringToFront();
// e.pickingObject.geometry.setFillColor(1, 0, 0, 0.4);
// e.pickingObject.geometry.setLineColor(1, 0, 0, 1.0);
//});
//countries.events.on("lclick", function (e) {
// globus.planet.flyExtent(e.pickingObject.geometry.getExtent());
//});
//countries.events.on("touchstart", function (e) {
// globus.planet.flyExtent(e.pickingObject.geometry.getExtent());
//});
});
globus.planet.addControl(
new DebugInfo({
watch: [
{
label: "metersInMinSize",
frame: () => globus.planet.renderer.controls.scaleControl._metersInMinSize
},
{
label: "meters in pixel",
frame: () => globus.planet.renderer.controls.scaleControl._mPx
}
]
})
);
//setTimeout(() => {
//globus.planet.camera.setLonLat(new LonLat(10, 10, 4500000));
//}, 1000);
//globus.planet.camera.update()
globus.planet.addControl(
new ToggleWireframe({
isActive: false
})
);
window.globus = globus;

View File

@ -140,7 +140,7 @@ let emptyTerrain = new EmptyTerrain(),
}),
rastTerrain = new MapboxTerrain(null, {
maxZoom: 19,
url: "//terrain.openglobus.org/public/256/{z}/{x}/{y}.png",
url: /*"//terrain.openglobus.org/public/oahu/{z}/{x}/{y}.png",/*/ "//terrain.openglobus.org/public/256/{z}/{x}/{y}.png",
//imageSize: 129,
//plainGridSize: 128,
gridSizeByZoom: [

View File

@ -2,22 +2,21 @@
* @module og/Clock
*/
'use strict';
"use strict";
import { Events } from './Events.js';
import * as jd from './astro/jd.js';
import { Events } from "./Events.js";
import * as jd from "./astro/jd.js";
/**
* Class represents application timer that stores custom current julian datetime, and time speed multiplier.
* @class
* @param {Object} [params]: - Clock parameters:
* @param {Object} [params] - Clock parameters:
* @param {number} [params.startDate=0.0] - Julian start date.
* @param {number} [params.endDate=0.0] - Julian end date.
* @param {number} [params.currentDate] - Julian current date. Default: current date.
* @param {number} [params.multiplier=1.0] - Time speed multiolier.
*/
class Clock {
static get _staticCounter() {
if (!this._counter && this._counter !== 0) {
this._counter = 0;
@ -29,6 +28,10 @@ class Clock {
this._counter = n;
}
/**
*
* @param {Object} [params] - Clock parameters:
*/
constructor(params) {
params = params || {};
@ -46,10 +49,7 @@ class Clock {
* @public
* @type {Events}
*/
this.events = new Events([
"tick",
"end"
], this);
this.events = new Events(["tick", "end"], this);
/**
* Start julian date clock loop.

View File

@ -2,17 +2,20 @@
* @module og/Events
*/
'use strict';
"use strict";
import { stamp, binaryInsert } from './utils/shared.js';
import { stamp, binaryInsert } from "./utils/shared.js";
/**
* Base events class to handle custom events.
* @class
* @param {Array.<string>} [eventNames] - Event names that could be dispatched.
*/
class Events {
/**
*
* @param {Array.<string>} [eventNames] - Event names that could be dispatched.
* @param {*} [sender]
*/
constructor(eventNames, sender) {
/**
* Registered event names.
@ -76,7 +79,6 @@ class Events {
* @return {boolean} -
*/
_stamp(name, obj) {
var ogid = stamp(obj);
var st = this._getStamp(name, this.__id, ogid);

View File

@ -2,11 +2,11 @@
* @module og/Extent
*/
'use strict';
"use strict";
import * as math from './math.js';
import * as mercator from './mercator.js';
import { LonLat } from './LonLat.js';
import * as math from "./math.js";
import * as mercator from "./mercator.js";
import { LonLat } from "./LonLat.js";
/**
* Represents geographical coordinates extent.
@ -15,7 +15,6 @@ import { LonLat } from './LonLat.js';
* @param {LonLat} [ne] - North East extent corner coordiantes.
*/
export class Extent {
/**
* @param {LonLat} [sw] - South West extent corner coordiantes.
* @param {LonLat} [ne] - North East extent corner coordiantes.
@ -35,25 +34,31 @@ export class Extent {
* Whole mercator extent.
* @const
*/
static get FULL_MERC() { return new Extent(LonLat.SW_MERC, LonLat.NE_MERC); }
static get FULL_MERC() {
return new Extent(LonLat.SW_MERC, LonLat.NE_MERC);
}
/**
* Degrees extent from north mercator limit to north pole.
* @const
*/
static get NORTH_POLE_DEG() { return new Extent(LonLat.NW_MERC_DEG, new LonLat(180.0, 90.0)); }
static get NORTH_POLE_DEG() {
return new Extent(LonLat.NW_MERC_DEG, new LonLat(180.0, 90.0));
}
/**
* Degrees extent from south pole to south mercator limit.
* @const
*/
static get SOUTH_POLE_DEG() { return new Extent(new LonLat(-180.0, -90.0), LonLat.SE_MERC_DEG); }
static get SOUTH_POLE_DEG() {
return new Extent(new LonLat(-180.0, -90.0), LonLat.SE_MERC_DEG);
}
/**
* Creates extent instance from values in array.
* @static
* @param {Array.<number>} arr - South west and north east longitude and latidudes packed in array. (exactly 4 entries)
* @return {og.Extent} Extent object.
* @return {Extent} Extent object.
*/
static createFromArray(arr) {
return new Extent(new LonLat(arr[0], arr[1]), new LonLat(arr[2], arr[3]));
@ -66,8 +71,10 @@ export class Extent {
* @return {Extent} Extent object.
*/
static createByCoordinates(arr) {
let lonmin = math.MAX, lonmax = math.MIN,
latmin = math.MAX, latmax = math.MIN;
let lonmin = math.MAX,
lonmax = math.MIN,
latmin = math.MAX,
latmax = math.MIN;
for (let i = 0; i < arr.length; i++) {
const vi = arr[i];
if (vi.lon < lonmin) lonmin = vi.lon;
@ -82,11 +89,13 @@ export class Extent {
* Creates bound extent instance by coordinate array.
* @static
* @param {Array.<Array<number>>} arr - Coordinate array. (exactly 2 entries)
* @return {og.Extent} Extent object.
* @return {Extent} Extent object.
*/
static createByCoordinatesArr(arr) {
let lonmin = math.MAX, lonmax = math.MIN,
latmin = math.MAX, latmax = math.MIN;
let lonmin = math.MAX,
lonmax = math.MIN,
latmin = math.MAX,
latmax = math.MIN;
for (let i = 0; i < arr.length; i++) {
const vi = arr[i];
if (vi[0] < lonmin) lonmin = vi[0];
@ -105,7 +114,7 @@ export class Extent {
* @param {number} z -
* @param {number} width -
* @param {number} height -
* @returns {og.Extent} -
* @returns {Extent} -
*/
static fromTile(x, y, z, width, height) {
width = width || mercator.POLE_DOUBLE;
@ -127,11 +136,13 @@ export class Extent {
* Sets current bounding extent object by coordinate array.
* @public
* @param {Array.<LonLat>} arr - Coordinate array.
* @return {og.Extent} Current extent.
* @return {Extent} Current extent.
*/
setByCoordinates(arr) {
let lonmin = math.MAX, lonmax = math.MIN,
latmin = math.MAX, latmax = math.MIN;
let lonmin = math.MAX,
lonmax = math.MIN,
latmin = math.MAX,
latmax = math.MIN;
for (let i = 0; i < arr.length; i++) {
const vi = arr[i];
if (vi.lon < lonmin) lonmin = vi.lon;
@ -155,8 +166,12 @@ export class Extent {
isInside(lonlat) {
const sw = this.southWest,
ne = this.northEast;
return lonlat.lon >= sw.lon && lonlat.lon <= ne.lon &&
lonlat.lat >= sw.lat && lonlat.lat <= ne.lat;
return (
lonlat.lon >= sw.lon &&
lonlat.lon <= ne.lon &&
lonlat.lat >= sw.lat &&
lonlat.lat <= ne.lat
);
}
/**
@ -168,8 +183,12 @@ export class Extent {
overlaps(e) {
const sw = this.southWest,
ne = this.northEast;
return sw.lon <= e.northEast.lon && ne.lon >= e.southWest.lon &&
sw.lat <= e.northEast.lat && ne.lat >= e.southWest.lat;
return (
sw.lon <= e.northEast.lon &&
ne.lon >= e.southWest.lon &&
sw.lat <= e.northEast.lat &&
ne.lat >= e.southWest.lat
);
}
/**
@ -193,7 +212,7 @@ export class Extent {
/**
* Creates clone instance of the current extent.
* @public
* @return {og.Extent} Extent clone.
* @return {Extent} Extent clone.
*/
clone() {
return new Extent(this.southWest.clone(), this.northEast.clone());
@ -205,7 +224,8 @@ export class Extent {
* @return {number} Center coordinate.
*/
getCenter() {
const sw = this.southWest, ne = this.northEast;
const sw = this.southWest,
ne = this.northEast;
return new LonLat(sw.lon + (ne.lon - sw.lon) * 0.5, sw.lat + (ne.lat - sw.lat) * 0.5);
}
@ -261,18 +281,22 @@ export class Extent {
/**
* Returns extents are equals.
* @param {og.Extent} extent - Extent.
* @param {Extent} extent - Extent.
* @returns {boolean} -
*/
equals(extent) {
return this.southWest.lon === extent.southWest.lon && this.southWest.lat === extent.southWest.lat &&
this.northEast.lon === extent.northEast.lon && this.northEast.lat === extent.northEast.lat;
return (
this.southWest.lon === extent.southWest.lon &&
this.southWest.lat === extent.southWest.lat &&
this.northEast.lon === extent.northEast.lon &&
this.northEast.lat === extent.northEast.lat
);
}
/**
* Converts extent coordinates to mercator projection coordinates.
* @public
* @return {og.Extent} New instance of the current extent.
* @return {Extent} New instance of the current extent.
*/
forwardMercator() {
return new Extent(this.southWest.forwardMercator(), this.northEast.forwardMercator());
@ -281,7 +305,7 @@ export class Extent {
/**
* Converts extent coordinates from mercator projection to degrees.
* @public
* @return {og.Extent} New instance of the current extent.
* @return {Extent} New instance of the current extent.
*/
inverseMercator() {
return new Extent(this.southWest.inverseMercator(), this.northEast.inverseMercator());
@ -290,21 +314,29 @@ export class Extent {
/**
* Gets cartesian bounding bounds of the current ellipsoid.
* @public
* @param {og.Ellipsoid} ellipsoid - Ellipsoid.
* @param {Ellipsoid} ellipsoid - Ellipsoid.
* @return {Array.<number>} Cartesian 3d coordinate array. (exactly 6 entries)
*/
getCartesianBounds(ellipsoid) {
let xmin = math.MAX, xmax = math.MIN, ymin = math.MAX,
ymax = math.MIN, zmin = math.MAX, zmax = math.MIN;
let xmin = math.MAX,
xmax = math.MIN,
ymin = math.MAX,
ymax = math.MIN,
zmin = math.MAX,
zmax = math.MIN;
const v = [new LonLat(this.southWest.lon, this.southWest.lat),
const v = [
new LonLat(this.southWest.lon, this.southWest.lat),
new LonLat(this.southWest.lon, this.northEast.lat),
new LonLat(this.northEast.lon, this.northEast.lat),
new LonLat(this.northEast.lon, this.southWest.lat)];
new LonLat(this.northEast.lon, this.southWest.lat)
];
for (let i = 0; i < v.length; i++) {
const coord = ellipsoid.lonLatToCartesian(v[i]);
const x = coord.x, y = coord.y, z = coord.z;
const x = coord.x,
y = coord.y,
z = coord.z;
if (x < xmin) xmin = x;
if (x > xmax) xmax = x;
if (y < ymin) ymin = y;
@ -317,7 +349,16 @@ export class Extent {
}
toString() {
return "[" + this.southWest.lon + ", " + this.southWest.lat + ", " + this.northEast.lon + ", " + this.northEast.lat + "]";
return (
"[" +
this.southWest.lon +
", " +
this.southWest.lat +
", " +
this.northEast.lon +
", " +
this.northEast.lat +
"]"
);
}
}

View File

@ -50,20 +50,26 @@ const PLANET_NAME_PREFIX = "globus_planet_";
*
* @param {object} options - Options:
* @param {string} options.target - HTML element id where planet canvas have to be created.
* @param {og.scene.RenderNode} [options.skybox] - Render skybox. null - default.
* @param {RenderNode} [options.skybox] - Render skybox. null - default.
* @param {string} [options.name] - Planet name. Default is unic identifier.
* @param {og.terrain.Terrain} [options.terrain] - Terrain provider. Default no terrain - og.terrain.EmptyTerrain.
* @param {Array.<og.control.Control>} [options.controls] - Renderer controls array.
* @param {Array.<og.Layer>} [options.layers] - Planet layers.
* @param {og.Extent} [options.viewExtent] - Viewable starting extent.
* @param {Terrain} [options.terrain] - Terrain provider. Default no terrain - og.terrain.EmptyTerrain.
* @param {Array.<control.Control>} [options.controls] - Renderer controls array.
* @param {Array.<Layer>} [options.layers] - Planet layers.
* @param {Extent} [options.viewExtent] - Viewable starting extent.
* @param {boolean} [options.autoActivate] - Globe rendering auto activation flag. True is default.
* @param {DOMElement} [options.attributionContainer] - Container for attribution list.
* @param {Number} [options.maxGridSize] = Maximal segment grid size. 128 is default
* @param {boolean} [options.useSpecularTexture] - use specular water mask
* @param {boolean} [options.useNightTexture] - show night cities
* @param {Number} [options.maxEqualZoomAltitude=850000.0] - Maximal altitude since segments on the screen bacame the same zoom level
* @param {Number} [options.minEqualZoomAltitude=10000.0] - Minimal altitude since segments on the screen bacame the same zoom level
* @param {Number} [options.minEqualZoomCameraSlope=0.8] - Minimal camera slope above te globe where segments on the screen bacame the same zoom level
*/
class Globe {
/**
* @param {*} options
*/
constructor(options) {
// Canvas creation
var _canvasId = CANVAS_ID_PREFIX + Globe._staticCounter++;
@ -108,7 +114,7 @@ class Globe {
/**
* Interface for the renderer context(events, input states, renderer nodes etc.)
* @public
* @type {og.Renderer}
* @type {Renderer}
*/
this.renderer = new Renderer(
new Handler(_canvasId, {
@ -148,7 +154,7 @@ class Globe {
/**
* Render node renders a planet.
* @public
* @type {og.scene.Planet|og.scene.PlanetAtmosphere}
* @type {Planet|og.scene.PlanetAtmosphere}
*/
// TODO:
} else {
@ -159,7 +165,10 @@ class Globe {
useNightTexture: options.useNightTexture,
useSpecularTexture: options.useSpecularTexture,
minAltitude: options.minAltitude,
maxAltitude: options.maxAltitude
maxAltitude: options.maxAltitude,
maxEqualZoomAltitude: options.maxEqualZoomAltitude,
minEqualZoomAltitude: options.minEqualZoomAltitude,
minEqualZoomCameraSlope: options.minEqualZoomCameraSlope
});
}

View File

@ -2,15 +2,17 @@
* @module og/ImageCanvas
*/
'use strict';
"use strict";
/**
* Usefull class for working with JS canvas object.
* @class
*/
class ImageCanvas {
/**
* @param {number} [width] - Canvas width. Default 256.
* @param {number} [height] - Canvas height. Default 256.
*/
class ImageCanvas {
constructor(width, height) {
/**
* Canvas object.
@ -26,7 +28,7 @@ class ImageCanvas {
* @protected
* @type {Object}
*/
this._context = this._canvas.getContext('2d');
this._context = this._canvas.getContext("2d");
}
/**
@ -100,7 +102,7 @@ class ImageCanvas {
resize(width, height) {
this._canvas.width = width;
this._canvas.height = height;
this._context = this._canvas.getContext('2d');
this._context = this._canvas.getContext("2d");
}
/**
@ -113,7 +115,7 @@ class ImageCanvas {
* @param {number} [height] - Image height slice. Image height is default.
*/
drawImage(img, x, y, width, height) {
this._context = this._canvas.getContext('2d');
this._context = this._canvas.getContext("2d");
this._context.drawImage(img, x || 0, y || 0, width || img.width, height || img.height);
}
@ -151,8 +153,8 @@ class ImageCanvas {
* @param {string} [color] - Css font color.
*/
drawText(text, x, y, font, color) {
this._context.fillStyle = color || 'black';
this._context.font = font || 'normal 14px Verdana';
this._context.fillStyle = color || "black";
this._context.font = font || "normal 14px Verdana";
this._context.fillText(text, x || 0, y || 14);
}
@ -198,14 +200,18 @@ class ImageCanvas {
openImage() {
var img = this.getImage();
var dataUrl = img.src;
var windowContent = '<!DOCTYPE html>';
windowContent += '<html>';
windowContent += '<head><title>Print</title></head>';
windowContent += '<body>';
var windowContent = "<!DOCTYPE html>";
windowContent += "<html>";
windowContent += "<head><title>Print</title></head>";
windowContent += "<body>";
windowContent += '<img src="' + dataUrl + '">';
windowContent += '</body>';
windowContent += '</html>';
var printWin = window.open('', '', 'width=' + img.width + 'px ,height=' + img.height + 'px');
windowContent += "</body>";
windowContent += "</html>";
var printWin = window.open(
"",
"",
"width=" + img.width + "px ,height=" + img.height + "px"
);
printWin.document.open();
printWin.document.write(windowContent);
printWin.document.close();

View File

@ -2,9 +2,9 @@
* @module og/LonLat
*/
'use strict';
"use strict";
import * as mercator from './mercator.js';
import * as mercator from "./mercator.js";
const HALF_PI = Math.PI * 0.5;
const INV_PI_BY_180 = 180.0 / Math.PI;
@ -20,14 +20,12 @@ const INV_PI_BY_180_HALF_PI = INV_PI_BY_180 * HALF_PI;
* @param {number} [height] - Height over the surface.
*/
export class LonLat {
/**
* @param {number} [lon]
* @param {number} [lat]
* @param {number} [height]
* @param {number} [lon] - Longitude.
* @param {number} [lat] - Latitude.
* @param {number} [height] - Height over the surface.
*/
constructor(lon, lat, height) {
/**
* Longitude.
* @public
@ -88,9 +86,11 @@ export class LonLat {
* @returns {LonLat} -
*/
static forwardMercator(lon, lat, height) {
return new LonLat(lon * mercator.POLE_BY_180,
return new LonLat(
lon * mercator.POLE_BY_180,
Math.log(Math.tan((90.0 + lat) * PI_BY_360)) * mercator.POLE_BY_PI,
height);
height
);
}
/**
@ -102,9 +102,11 @@ export class LonLat {
* @returns {LonLat} -
*/
static inverseMercator(x, y, height) {
return new LonLat(x * mercator.INV_POLE_BY_180,
return new LonLat(
x * mercator.INV_POLE_BY_180,
INV_PI_BY_360 * Math.atan(Math.exp(y * mercator.PI_BY_POLE)) - INV_PI_BY_180_HALF_PI,
height);
height
);
}
/**
@ -162,7 +164,8 @@ export class LonLat {
}
return new LonLat(
this.lon * mercator.POLE_BY_180,
Math.log(Math.tan((90.0 + lat) * PI_BY_360)) * mercator.POLE_BY_PI);
Math.log(Math.tan((90.0 + lat) * PI_BY_360)) * mercator.POLE_BY_PI
);
}
/**

View File

@ -1,11 +1,10 @@
'use strict';
"use strict";
import { Events } from './Events.js';
import { Vec3 } from './math/Vec3.js';
import { getHTML, parseHTML, createLonLat } from './utils/shared.js';
import { Events } from "./Events.js";
import { Vec3 } from "./math/Vec3.js";
import { getHTML, parseHTML, createLonLat } from "./utils/shared.js";
const TEMPLATE =
`<div class="og-popup {className}">
const TEMPLATE = `<div class="og-popup {className}">
<div class="og-popup-content-wrapper">
<div class="og-popup-content"></div>
</div>
@ -20,8 +19,11 @@ const TEMPLATE =
</div>`;
class Popup {
/**
*
* @param {*} options
*/
constructor(options) {
this._id = Popup._staticCounter++;
this.events = new Events(["open", "close"]);
@ -72,7 +74,12 @@ class Popup {
setScreen(p) {
if (this._planet) {
this.el.style.transform = "translate(" + (p.x - this.clientWidth * 0.5) + "px, " + (p.y - this._planet.renderer.handler.canvas.height - this._tipEl.clientHeight) + "px)"
this.el.style.transform =
"translate(" +
(p.x - this.clientWidth * 0.5) +
"px, " +
(p.y - this._planet.renderer.handler.canvas.height - this._tipEl.clientHeight) +
"px)";
}
}
@ -97,8 +104,8 @@ class Popup {
render(params) {
this.el = this._renderTemplate(params);
this._contentEl = this.el.querySelector(".og-popup-content");
this._titleEl = this.el.querySelector(".og-popup-title")
this._tipEl = this.el.querySelector(".og-popup-tip-container")
this._titleEl = this.el.querySelector(".og-popup-title");
this._tipEl = this.el.querySelector(".og-popup-tip-container");
this.setOffset(this._offset[0], this._offset[1]);
this.setContent(this._content);
this.setTitle(this._title);
@ -148,7 +155,6 @@ class Popup {
}
setCartesian3v(cart, height = 0) {
this._cartPos = cart;
if (this._planet) {
@ -187,10 +193,10 @@ class Popup {
if (content) {
this.clear();
this._content = content;
if (typeof content === 'string') {
if (typeof content === "string") {
this._contentEl.innerHTML = content;
} else {
this._contentEl.appendChild(content)
this._contentEl.appendChild(content);
}
}
return this;

View File

@ -1,6 +1,10 @@
'use strict';
"use strict";
class QueueArray {
/**
*
* @param {number} [size]
*/
constructor(size) {
this._size = size || 2048;
this._array = new Array(this._size);

View File

@ -1,4 +1,4 @@
'use strict';
"use strict";
/**
* 2D Rectangle class.
@ -7,10 +7,15 @@
* @param {number} [top] - Top coordinate. 0 - default.
* @param {number} [right] - Right coordinate. 0 - default.
* @param {number} [bottom] - Bottom coordinate. 0 - default.
*/
*/
class Rectangle {
/**
* @param {number} [left] - Left coordinate. 0 - default.
* @param {number} [top] - Top coordinate. 0 - default.
* @param {number} [right] - Right coordinate. 0 - default.
* @param {number} [bottom] - Bottom coordinate. 0 - default.
*/
constructor(left, top, right, bottom) {
/**
* Left coordinate.
* @public
@ -43,7 +48,7 @@ class Rectangle {
/**
* Clone rectangle object.
* @public
* @returns {og.Rectangle}
* @returns {Rectangle}
*/
clone() {
return new Rectangle(this.left, this.top, this.right, this.bottom);
@ -95,7 +100,7 @@ class Rectangle {
* @type {boolean}
*/
fit(width, height) {
return (this.getWidth() == width && this.getHeight() == height);
return this.getWidth() == width && this.getHeight() == height;
}
isInside(x, y) {

View File

@ -2,7 +2,7 @@
* @module og/Stack
*/
'use strict';
"use strict";
class Node {
constructor() {
@ -13,8 +13,11 @@ class Node {
}
class Stack {
/**
*
* @param {number} [size]
*/
constructor(size = 256) {
this._current = new Node();
this._head = this._current;

View File

@ -2,7 +2,7 @@
* @module og/ajax
*/
'use strict';
"use strict";
/**
* Ajax parameters.
@ -13,8 +13,7 @@ const ajax = {
* Ajax ready state result.
* @enum
*/
ReadyState:
{
ReadyState: {
Uninitialized: 0,
Loading: 1,
Loaded: 2,
@ -25,8 +24,7 @@ const ajax = {
* Ajax status code.
* @enum
*/
Status:
{
Status: {
OK: 200,
Created: 201,
Accepted: 202,
@ -88,24 +86,6 @@ const defaultParams = {
responseType: "text"
};
function createXMLHttp() {
var xhr = null;
if (typeof XMLHttpRequest != "undefined") {
xhr = new XMLHttpRequest();
return xhr;
} else if (window.ActiveXObject) {
var ieXMLHttpVersions = ['MSXML2.XMLHttp.5.0', 'MSXML2.XMLHttp.4.0', 'MSXML2.XMLHttp.3.0', 'MSXML2.XMLHttp', 'Microsoft.XMLHttp'];
for (var i = 0; i < ieXMLHttpVersions.length; i++) {
try {
xhr = new ActiveXObject(ieXMLHttpVersions[i]);
return xhr;
} catch (e) {
throw new Error('og.ajax.createXMLHttp creation failed.');
}
}
}
}
/**
* Send an ajax request.
* @function
@ -122,10 +102,10 @@ function createXMLHttp() {
* @returns {ajax.Xhr} - Returns object that could be aborted.
*/
ajax.request = function (url, params) {
params = params || {};
var p = {}, i;
var p = {},
i;
for (i in defaultParams) {
p[i] = defaultParams[i];
@ -137,18 +117,23 @@ ajax.request = function (url, params) {
p.data = params.data;
var xhr = createXMLHttp();
var xhr = new XMLHttpRequest();
var customXhr = new Xhr(xhr);
var body = null, d;
var body = null,
d;
if (p.type === ajax.Method.Post) {
if (p.data) {
body = "";
for (let key in p.data) {
d = p.data[key];
body += key + "=" + encodeURIComponent(d instanceof Object ? JSON.stringify(d) : d) + "&";
body +=
key +
"=" +
encodeURIComponent(d instanceof Object ? JSON.stringify(d) : d) +
"&";
}
body = body.slice(0, -1);
}
@ -158,7 +143,8 @@ ajax.request = function (url, params) {
var tail = "?";
for (let key in p.data) {
d = p.data[key];
tail += key + "=" + encodeURIComponent(d instanceof Object ? JSON.stringify(d) : d) + "&";
tail +=
key + "=" + encodeURIComponent(d instanceof Object ? JSON.stringify(d) : d) + "&";
}
tail = tail.slice(0, -1);
xhr.open(p.type, url + tail, p.async);
@ -190,7 +176,8 @@ ajax.request = function (url, params) {
* @param {Object} Response data
* @param {Object} Status object
*/
params.abort && params.abort.call(params.sender || customXhr, xhr.response, xhr.status);
params.abort &&
params.abort.call(params.sender || customXhr, xhr.response, xhr.status);
} else {
/**
* Error callback.
@ -198,9 +185,10 @@ ajax.request = function (url, params) {
* @param {Object} Response data
* @param {Object} Status object
*/
params.error && params.error.call(params.sender || customXhr, xhr.response, xhr.status);
params.error &&
params.error.call(params.sender || customXhr, xhr.response, xhr.status);
}
delete xhr['onreadystatechange'];
delete xhr["onreadystatechange"];
xhr.onreadystatechange = null;
xhr = null;
} else {

View File

@ -1,6 +1,6 @@
'use strict';
"use strict";
import * as jd from './jd.js';
import * as jd from "./jd.js";
/**
* Angle between J2000 mean equator and the ecliptic plane.
@ -16,7 +16,7 @@ export const J2000_OBLIQUITY = 23.4392911;
* @const
* @type{Number}
*/
export const AU_TO_METERS = 1.49597870e+11;
export const AU_TO_METERS = 1.4959787e11;
/**
* Terestrial and atomic time difference.
@ -45,7 +45,7 @@ export const SUN_GRAVITATIONAL_PARAMETER = 1.32712440018e20;
* @returns {Number} - returns barycentric dynamical time.
*/
export function TAItoTDB(tai) {
tai += og.astro.TDT_TAI * jd.ONE_BY_SECONDS_PER_DAY;
tai += TDT_TAI * jd.ONE_BY_SECONDS_PER_DAY;
var g = 6.239996 + 0.0172019696544 * (tai - jd.J2000);
return tai + 0.001658 * Math.sin(g + 1.671e-2 * Math.sin(g)) * jd.ONE_BY_SECONDS_PER_DAY;
}

View File

@ -2,18 +2,18 @@
* @module og/astro/earth
*/
'use strict';
"use strict";
import * as jd from './jd.js';
import * as math from '../math.js';
import * as astro from './astro.js';
import { Quat } from '../math/Quat.js';
import { Vec3 } from '../math/Vec3.js';
import * as jd from "./jd.js";
import * as math from "../math.js";
import * as astro from "./astro.js";
import { Quat } from "../math/Quat.js";
import { Vec3 } from "../math/Vec3.js";
/**
* Returns Sun position in the geocentric coordinate system by the time.
* @param {Number} jDate - Julian date time.
* @returns {og.Vec3} - Sun geocentric coordinates.
* @returns {Vec3} - Sun geocentric coordinates.
*/
export function getSunPosition(jDate) {
// http://stjarnhimlen.se/comp/tutorial.html
@ -70,16 +70,17 @@ export function getSunPosition(jDate) {
var d = jDate - jd.J2000;
var w = 282.9404 + 4.70935E-5 * d; // longitude of perihelion
var w = 282.9404 + 4.70935e-5 * d; // longitude of perihelion
// var a = 1.000000; // mean distance, a.u.
var e = 0.016709 - 1.151E-9 * d; // eccentricity
var M = math.rev(356.0470 + 0.9856002585 * d); // mean anomaly
var e = 0.016709 - 1.151e-9 * d; // eccentricity
var M = math.rev(356.047 + 0.9856002585 * d); // mean anomaly
var oblecl = astro.J2000_OBLIQUITY - 3.563E-7 * d; // obliquity of the ecliptic
var oblecl = astro.J2000_OBLIQUITY - 3.563e-7 * d; // obliquity of the ecliptic
// var L = math.rev(w + M); // Sun's mean longitude
var E = M + math.DEGREES * e * Math.sin(M * math.RADIANS) * (1 + e * Math.cos(M * math.RADIANS)); // eccentric anomaly
var E =
M + math.DEGREES * e * Math.sin(M * math.RADIANS) * (1 + e * Math.cos(M * math.RADIANS)); // eccentric anomaly
// Sun rectangular coordiantes, where the X axis points towards the perihelion
var x = Math.cos(E * math.RADIANS) - e;
@ -99,10 +100,15 @@ export function getSunPosition(jDate) {
var yequat = y * Math.cos(oblecl * math.RADIANS);
var zequat = y * Math.sin(oblecl * math.RADIANS);
var theta = math.TWO_PI * (d * 24.0 / 23.9344694 - 259.853 / 360.0); // Siderial spin time
var theta = math.TWO_PI * ((d * 24.0) / 23.9344694 - 259.853 / 360.0); // Siderial spin time
return Quat.yRotation(-theta).mulVec3(new Vec3(-yequat * astro.AU_TO_METERS,
zequat * astro.AU_TO_METERS, -xequat * astro.AU_TO_METERS));
return Quat.yRotation(-theta).mulVec3(
new Vec3(
-yequat * astro.AU_TO_METERS,
zequat * astro.AU_TO_METERS,
-xequat * astro.AU_TO_METERS
)
);
// Convert to RA and Decl
// var RA = Math.atan2(yequat, xequat) * math.DEGREES;

View File

@ -2,9 +2,9 @@
* @module og/astro/jd
*/
'use strict';
"use strict";
import { binarySearch } from '../utils/shared.js';
import { binarySearch } from "../utils/shared.js";
/**
* Seconds in millisecond.
@ -172,8 +172,13 @@ export function T(jd) {
export function getDayNumber(year, month, day) {
var a = ((month - 14) / 12) | 0;
var b = year + 4800 + a;
return (((1461 * b) / 4) | 0) + (((367 * (month - 2 - 12 * a)) / 12) | 0) -
(((3 * (((b + 100) / 100) | 0)) / 4) | 0) + day - 32075;
return (
(((1461 * b) / 4) | 0) +
(((367 * (month - 2 - 12 * a)) / 12) | 0) -
(((3 * (((b + 100) / 100) | 0)) / 4) | 0) +
day -
32075
);
}
/**
@ -190,7 +195,8 @@ export function DateToUTC(date) {
}
var secondsOfDay =
date.getUTCSeconds() + hour * SECONDS_PER_HOUR +
date.getUTCSeconds() +
hour * SECONDS_PER_HOUR +
date.getUTCMinutes() * SECONDS_PER_MINUTE +
date.getUTCMilliseconds() * SECONDS_PER_MILLISECOND;
@ -198,7 +204,7 @@ export function DateToUTC(date) {
dayNumber--;
}
var extraDays = secondsOfDay * ONE_BY_SECONDS_PER_DAY | 0;
var extraDays = (secondsOfDay * ONE_BY_SECONDS_PER_DAY) | 0;
dayNumber += extraDays;
secondsOfDay -= SECONDS_PER_DAY * extraDays;
@ -300,7 +306,7 @@ export function UTCtoDate(utc) {
}
var L = (julianDayNumber + 68569) | 0;
var N = (4 * L / 146097) | 0;
var N = ((4 * L) / 146097) | 0;
L = (L - (((146097 * N + 3) / 4) | 0)) | 0;
var I = ((4000 * (L + 1)) / 1461001) | 0;
L = (L - (((1461 * I) / 4) | 0) + 31) | 0;
@ -310,12 +316,12 @@ export function UTCtoDate(utc) {
var month = (J + 2 - 12 * L) | 0;
var year = (100 * (N - 49) + I + L) | 0;
var hour = secondsOfDay * ONE_BY_SECONDS_PER_HOUR | 0;
var hour = (secondsOfDay * ONE_BY_SECONDS_PER_HOUR) | 0;
var remainingSeconds = secondsOfDay - hour * SECONDS_PER_HOUR;
var minute = remainingSeconds * ONE_BY_SECONDS_PER_MINUTE | 0;
var minute = (remainingSeconds * ONE_BY_SECONDS_PER_MINUTE) | 0;
remainingSeconds = remainingSeconds - minute * SECONDS_PER_MINUTE;
var second = remainingSeconds | 0;
var millisecond = (remainingSeconds - second) * MILLISECONDS_PER_SECOND | 0;
var millisecond = ((remainingSeconds - second) * MILLISECONDS_PER_SECOND) | 0;
hour += 12;
if (hour > 23) {
@ -331,11 +337,10 @@ export function UTCtoDate(utc) {
* @returns {Date} JavaScript Date object
*/
export function TAItoDate(tai) {
var utc = TAItoUTC(tai);
if (!utc) {
utc = TAItoUTC(addSeconds(tai, -1));
og.console.logWrn("TAItoDate:336 - can't conv utc.");
console.warn("TAItoDate:336 - can't conv utc.");
}
return UTCtoDate(utc);
@ -399,7 +404,7 @@ export function addDays(jd, days) {
export function getMilliseconds(jd) {
var s = jd - (jd | 0);
s *= SECONDS_PER_DAY;
return (s - (s | 0)) * MILLISECONDS_PER_SECOND | 0;
return ((s - (s | 0)) * MILLISECONDS_PER_SECOND) | 0;
}
/**
@ -421,12 +426,12 @@ export function getHours(jd) {
var julianDayNumber = jd | 0;
var secondsOfDay = (jd - julianDayNumber) * SECONDS_PER_DAY;
var hour = secondsOfDay * ONE_BY_SECONDS_PER_HOUR | 0;
var hour = (secondsOfDay * ONE_BY_SECONDS_PER_HOUR) | 0;
var remainingSeconds = secondsOfDay - hour * SECONDS_PER_HOUR;
var minute = remainingSeconds * ONE_BY_SECONDS_PER_MINUTE | 0;
var minute = (remainingSeconds * ONE_BY_SECONDS_PER_MINUTE) | 0;
remainingSeconds = remainingSeconds - minute * SECONDS_PER_MINUTE;
var second = remainingSeconds | 0;
var millisecond = (remainingSeconds - second) * MILLISECONDS_PER_SECOND | 0;
var millisecond = ((remainingSeconds - second) * MILLISECONDS_PER_SECOND) | 0;
hour += 12 + minute / 60 + second / 3600 + millisecond / 1000;
if (hour > 23) {
@ -443,7 +448,7 @@ export function getHours(jd) {
*/
export function getMinutes(jd) {
var s = jd - (jd | 0);
return s * MINUTES_PER_DAY | 0;
return (s * MINUTES_PER_DAY) | 0;
}
/**

View File

@ -2,10 +2,10 @@
* @module og/astro/orbit
*/
'use strict';
"use strict";
import * as math from '../math.js';
import { Mat3 } from '../math/Mat3.js';
import * as math from "../math.js";
import { Mat3 } from "../math/Mat3.js";
export function getEccentricAnomaly(M, ecc) {
if (ecc == 0.0) {
@ -22,14 +22,14 @@ export function getEccentricAnomaly(M, ecc) {
// Extremely stable Laguerre-Conway method for solving Kepler's
// equation. Only use this for high-eccentricity orbits, as it
// requires more calcuation.
let E = M + 0.85 * ecc * sign(sin(M));
let E = M + 0.85 * ecc * Math.sign(Math.sin(M));
return math.solve_iteration_fixed(solveKeplerLaguerreConway(ecc, M), E, 8);
} else if (ecc == 1.0) {
// TODO: Parabolic orbit
return M;
} else {
// Laguerre-Conway method for hyperbolic (ecc > 1) orbits.
let E = log(2 * M / ecc + 1.85);
let E = Math.log((2 * M) / ecc + 1.85);
return math.solve_iteration_fixed(solveKeplerLaguerreConwayHyp(ecc, M), E, 30);
}
}
@ -57,7 +57,7 @@ function solveKeplerLaguerreConway(ecc, M) {
var f = x - s - M;
var f1 = 1 - c;
var f2 = s;
x += -5 * f / (f1 + Math.sign(f1) * Math.sqrt(abs(16 * f1 * f1 - 20 * f * f2)));
x += (-5 * f) / (f1 + Math.sign(f1) * Math.sqrt(Math.abs(16 * f1 * f1 - 20 * f * f2)));
return x;
};
}
@ -69,7 +69,7 @@ function solveKeplerLaguerreConwayHyp(ecc, M) {
var f = s - x - M;
var f1 = c - 1;
var f2 = s;
x += -5 * f / (f1 + Math.sign(f1) * Math.sqrt(Math.abs(16 * f1 * f1 - 20 * f * f2)));
x += (-5 * f) / (f1 + Math.sign(f1) * Math.sqrt(Math.abs(16 * f1 * f1 - 20 * f * f2)));
return x;
};
}
@ -77,7 +77,7 @@ function solveKeplerLaguerreConwayHyp(ecc, M) {
export function getEllipticalEccentricAnomaly(meanAnomaly, eccentricity) {
var tol = 0.00000001745;
var iterations = 20;
var e = meanAnomaly - 2.0 * Math.PI * (meanAnomaly / (2.0 * Math.PI) | 0);
var e = meanAnomaly - 2.0 * Math.PI * ((meanAnomaly / (2.0 * Math.PI)) | 0);
var err = 1;
while (Math.abs(err) > tol && iterations > 0) {
err = e - eccentricity * Math.sin(e) - meanAnomaly;
@ -91,8 +91,10 @@ export function getEllipticalEccentricAnomaly(meanAnomaly, eccentricity) {
export function getTrueAnomaly(eccentricAnomaly, eccentricity) {
var revs = Math.floor(eccentricAnomaly / math.TWO_PI);
eccentricAnomaly -= revs * math.TWO_PI;
var trueAnomaly = Math.atan2(Math.sin(eccentricAnomaly) * Math.sqrt(1 - eccentricity * eccentricity),
Math.cos(eccentricAnomaly) - eccentricity);
var trueAnomaly = Math.atan2(
Math.sin(eccentricAnomaly) * Math.sqrt(1 - eccentricity * eccentricity),
Math.cos(eccentricAnomaly) - eccentricity
);
trueAnomaly = math.zeroTwoPI(trueAnomaly);
if (eccentricAnomaly < 0) {
trueAnomaly -= math.TWO_PI;

View File

@ -2,20 +2,29 @@
* @module og/astro/rotation
*/
'use strict';
"use strict";
export function getRotationMatrix(rightAscension, declination) {
xAxis.x = Math.cos(rightAscension + og.math.PI_TWO);
xAxis.y = Math.sin(rightAscension + og.math.PI_TWO);
import { Vec3 } from "../math/Vec3.js";
import { Mat3 } from "../math/Mat3.js";
import { PI_TWO } from "../math.js";
export function getRotationMatrix(rightAscension, declination, res) {
let xAxis = new Vec3(),
zAxis = new Vec3();
res = res || new Mat3();
xAxis.x = Math.cos(rightAscension + PI_TWO);
xAxis.y = Math.sin(rightAscension + PI_TWO);
xAxis.z = 0.0;
var cosDec = Math.cos(declination);
let cosDec = Math.cos(declination);
zAxis.x = cosDec * Math.cos(rightAscension);
zAxis.y = cosDec * Math.sin(rightAscension);
zAxis.z = Math.sin(declination);
var yAxis = zAxis.cross(xAxis);
let yAxis = zAxis.cross(xAxis);
res._m[0] = xAxis.x;
res._m[1] = yAxis.x;
@ -27,5 +36,5 @@ export function getRotationMatrix(rightAscension, declination) {
res._m[7] = yAxis.z;
res._m[8] = zAxis.z;
return result;
return res;
}

View File

@ -11,11 +11,15 @@ import { Vec3 } from "../math/Vec3.js";
* @class
*/
class Box {
/**
*
* @param {*} boundsArr
*/
constructor(boundsArr) {
/**
* Vertices array.
* @public
* @type{Array.<og.Vec3>}
* @type{Array.<Vec3>}
*/
this.vertices = [
new Vec3(),
@ -65,8 +69,8 @@ class Box {
/**
* Sets bounding box coordiantes by ellipsoid geodetic extend.
* @param {og.Ellipsoid} ellipsoid - Ellipsoid.
* @param {og.Extent} extent - Geodetic extent.
* @param {Ellipsoid} ellipsoid - Ellipsoid.
* @param {Extent} extent - Geodetic extent.
*/
setFromExtent(ellipsoid, extent) {
this.setFromBoundsArr(extent.getCartesianBounds(ellipsoid));

View File

@ -2,15 +2,15 @@
* @module og/bv/Sphere
*/
'use strict';
"use strict";
import { Vec3 } from '../math/Vec3.js';
import { Vec3 } from "../math/Vec3.js";
/**
* Bounding sphere class.
* @class
* @param {Number} [radius] - Bounding sphere radius.
* @param {og.Vec3} [center] - Bounding sphere coordiantes.
* @param {Vec3} [center] - Bounding sphere coordiantes.
*/
class Sphere {
/**
@ -19,7 +19,6 @@ class Sphere {
* @param {Vec3} center
*/
constructor(radius, center) {
/**
* Sphere radius.
* @public
@ -30,7 +29,7 @@ class Sphere {
/**
* Sphere coordiantes.
* @public
* @type {og.Vec3}
* @type {Vec3}
*/
this.center = center ? center.clone() : new Vec3();
}
@ -41,14 +40,18 @@ class Sphere {
*/
setFromBounds(bounds) {
let m = new Vec3(bounds[0], bounds[1], bounds[2]);
this.center.set(m.x + (bounds[3] - m.x) * 0.5, m.y + (bounds[3] - m.y) * 0.5, m.z + (bounds[5] - m.z) * 0.5);
this.center.set(
m.x + (bounds[3] - m.x) * 0.5,
m.y + (bounds[3] - m.y) * 0.5,
m.z + (bounds[5] - m.z) * 0.5
);
this.radius = this.center.distance(m);
}
/**
* Sets bounding sphere coordiantes by ellipsoid geodetic extend.
* @param {og.Ellipsoid} ellipsoid - Ellipsoid.
* @param {og.Extent} extent - Geodetic extent.
* @param {Ellipsoid} ellipsoid - Ellipsoid.
* @param {Extent} extent - Geodetic extent.
*/
setFromExtent(ellipsoid, extent) {
this.setFromBounds(extent.getCartesianBounds(ellipsoid));

View File

@ -12,52 +12,56 @@ import { Mat4 } from "../math/Mat4.js";
/**
* Camera class.
* @class
* @param {og.Renderer} [renderer] - Renderer uses the camera instance.
* @param {Renderer} [renderer] - Renderer uses the camera instance.
* @param {Object} [options] - Camera options:
* @param {Object} [options.name] - Camera name.
* @param {number} [options.viewAngle=38] - Camera angle of view. Default is 30.0
* @param {number} [options.near=1] - Camera near plane distance. Default is 1.0
* @param {number} [options.far=og.math.MAX] - Camera far plane distance. Deafult is og.math.MAX
* @param {og.Vec3} [options.eye=[0,0,0]] - Camera eye position. Default (0,0,0)
* @param {og.Vec3} [options.look=[0,0,0]] - Camera look position. Default (0,0,0)
* @param {og.Vec3} [options.up=[0,1,0]] - Camera eye position. Default (0,1,0)
* @param {Vec3} [options.eye=[0,0,0]] - Camera eye position. Default (0,0,0)
* @param {Vec3} [options.look=[0,0,0]] - Camera look position. Default (0,0,0)
* @param {Vec3} [options.up=[0,1,0]] - Camera eye position. Default (0,1,0)
*
* @fires og.Camera#viewchange
*/
class Camera {
/**
* @param {Renderer} [renderer] - Renderer uses the camera instance.
* @param {Object} [options] - Camera options:
*/
constructor(renderer, options) {
/**
* Assigned renderer
* @public
* @type {og.Renderer}
* @type {Renderer}
*/
this.renderer = renderer;
/**
* Camera events handler
* @public
* @type {og.Events}
* @type {Events}
*/
this.events = new Events(EVENT_NAMES, this);
/**
* Camera position.
* @public
* @type {og.Vec3}
* @type {Vec3}
*/
this.eye = new Vec3();
/**
* Camera RTE high position
* @public
* @type {og.Vec3}
* @type {Vec3}
*/
this.eyeHigh = new Float32Array(3);
/**
* Camera RTE low position
* @public
* @type {og.Vec3}
* @type {Vec3}
*/
this.eyeLow = new Float32Array(3);
@ -78,35 +82,35 @@ class Camera {
/**
* Camera normal matrix.
* @protected
* @type {og.Mat3}
* @type {Mat3}
*/
this._normalMatrix = new Mat3();
/**
* Camera view matrix.
* @protected
* @type {og.Mat4}
* @type {Mat4}
*/
this._viewMatrix = new Mat4();
/**
* Camera right vector.
* @protected
* @type {og.Vec3}
* @type {Vec3}
*/
this._u = new Vec3(0.0, 1.0, 0.0); // up x n
/**
* Camera up vector.
* @protected
* @type {og.Vec3}
* @type {Vec3}
*/
this._v = new Vec3(1.0, 0.0, 0.0); // n x u - UP
/**
* Camera forward vector.
* @protected
* @type {og.Vec3}
* @type {Vec3}
*/
this._n = new Vec3(0.0, 0.0, 1.0); // eye - look - FORWARD
@ -115,7 +119,7 @@ class Camera {
this._pv = this._v.clone();
this._pn = this._n.clone();
this._peye = this.eye.clone();
this._moved = false;
this.isMoved = false;
this._tanViewAngle_hrad = 0.0;
this._tanViewAngle_hradOneByHeight = 0.0;
@ -174,20 +178,13 @@ class Camera {
n = this._n,
eye = this.eye;
if (this.events.moveend.handlers.length) {
if (
this._peye.equal(eye) &&
this._pu.equal(u) &&
this._pv.equal(v) &&
this._pn.equal(n)
) {
if (this._moved) {
if (this._peye.equal(eye) && this._pu.equal(u) && this._pv.equal(v) && this._pn.equal(n)) {
if (this.isMoved) {
this.events.dispatch(this.events.moveend, this);
}
this._moved = false;
this.isMoved = false;
} else {
this._moved = true;
}
this.isMoved = true;
}
this._pu.copy(u);
@ -199,14 +196,14 @@ class Camera {
/**
* Camera initialization.
* @public
* @param {og.Renderer} renderer - OpenGlobus renderer object.
* @param {Renderer} renderer - OpenGlobus renderer object.
* @param {Object} [options] - Camera options:
* @param {number} [options.viewAngle] - Camera angle of view. Default is 30.0
* @param {number} [options.near] - Camera near plane distance. Default is 1.0
* @param {number} [options.far] - Camera far plane distance. Deafult is og.math.MAX
* @param {og.Vec3} [options.eye] - Camera eye position. Default (0,0,0)
* @param {og.Vec3} [options.look] - Camera look position. Default (0,0,0)
* @param {og.Vec3} [options.up] - Camera eye position. Default (0,1,0)
* @param {Vec3} [options.eye] - Camera eye position. Default (0,0,0)
* @param {Vec3} [options.look] - Camera look position. Default (0,0,0)
* @param {Vec3} [options.up] - Camera eye position. Default (0,1,0)
*/
_init(options) {
this._setProj(this._viewAngle, this._aspect);
@ -362,10 +359,10 @@ class Camera {
/**
* Sets camera to eye position
* @public
* @param {og.Vec3} eye - Camera position
* @param {og.Vec3} look - Look point
* @param {og.Vec3} up - Camera up vector
* @returns {og.Camera} - This camera
* @param {Vec3} eye - Camera position
* @param {Vec3} look - Look point
* @param {Vec3} up - Camera up vector
* @returns {Camera} - This camera
*/
set(eye, look, up) {
this.eye.x = eye.x;
@ -386,8 +383,8 @@ class Camera {
/**
* Sets camera look point
* @public
* @param {og.Vec3} look - Look point
* @param {og.Vec3} [up] - Camera up vector otherwise camera current up vector(this._v)
* @param {Vec3} look - Look point
* @param {Vec3} [up] - Camera up vector otherwise camera current up vector(this._v)
*/
look(look, up) {
this._n.set(this.eye.x - look.x, this.eye.y - look.y, this.eye.z - look.z);
@ -478,7 +475,7 @@ class Camera {
* @public
* @param {number} x - Scren X coordinate
* @param {number} y - Scren Y coordinate
* @returns {og.Vec3} - Direction vector
* @returns {Vec3} - Direction vector
*/
unproject(x, y) {
var c = this.renderer.handler.canvas,
@ -501,8 +498,8 @@ class Camera {
/**
* Gets projected 3d point to the 2d screen coordiantes
* @public
* @param {og.Vec3} v - Cartesian 3d coordiantes
* @returns {og.Vec2} - Screen point coordinates
* @param {Vec3} v - Cartesian 3d coordiantes
* @returns {Vec2} - Screen point coordinates
*/
project(v) {
var r = this.frustums[0]._projectionViewMatrix.mulVec4(v.toVec4()),
@ -516,8 +513,8 @@ class Camera {
* @param {number} angle - Rotation angle in radians
* @param {boolean} isArc - If true camera up vector gets from current up vector every frame,
* otherwise up is always input parameter.
* @param {og.Vec3} center - Point that the camera rotates around
* @param {og.math.Vecto3} [up] - Camera up vector
* @param {Vec3} center - Point that the camera rotates around
* @param {Vecto3} [up] - Camera up vector
*/
rotateAround(angle, isArc, center, up) {
center = center || Vec3.ZERO;
@ -541,8 +538,8 @@ class Camera {
* @param {number} angle - Rotation angle in radians.
* @param {boolaen} isArc - If true camera up vector gets from current up vector every frame,
* otherwise up is always input parameter.
* @param {og.Vec3} center - Point that the camera rotates around.
* @param {og.Vec3} [up] - Camera up vector.
* @param {Vec3} center - Point that the camera rotates around.
* @param {Vec3} [up] - Camera up vector.
*/
rotateHorizontal(angle, isArc, center, up) {
this.rotateAround(angle, isArc, center, up);
@ -551,7 +548,7 @@ class Camera {
/**
* Rotates camera around center point by vecrtical.
* @param {number} angle - Rotation angle in radians.
* @param {og.Vec3} center - Point that the camera rotates around.
* @param {Vec3} center - Point that the camera rotates around.
*/
rotateVertical(angle, center) {
this.rotateAround(angle, false, center, this._u);
@ -560,8 +557,8 @@ class Camera {
/**
* Gets 3d size factor. Uses in LOD distance calculation.
* @public
* @param {og.Vec3} p - Far point.
* @param {og.Vec3} r - Far point.
* @param {Vec3} p - Far point.
* @param {Vec3} r - Far point.
* @returns {number} - Size factor.
*/
projectedSize(p, r) {
@ -571,7 +568,7 @@ class Camera {
/**
* Returns normal matrix.
* @public
* @returns {og.Mat3} - Normal matrix.
* @returns {Mat3} - Normal matrix.
*/
getNormalMatrix() {
return this._normalMatrix._m;
@ -580,7 +577,7 @@ class Camera {
/**
* Returns model matrix.
* @public
* @returns {og.Mat4} - View matrix.
* @returns {Mat4} - View matrix.
*/
getViewMatrix() {
return this._viewMatrix._m;
@ -601,7 +598,7 @@ class Camera {
/**
* Returns projection matrix.
* @public
* @returns {og.Mat4} - Projection matrix.
* @returns {Mat4} - Projection matrix.
*/
getProjectionMatrix() {
return this.frustum._projectionMatrix._m;
@ -610,7 +607,7 @@ class Camera {
/**
* Returns projection and model matrix product.
* @public
* @return {og.Mat4} - Projection-view matrix.
* @return {Mat4} - Projection-view matrix.
*/
getProjectionViewMatrix() {
return this.frustum._projectionViewMatrix._m;
@ -619,7 +616,7 @@ class Camera {
/**
* Returns inverse projection and model matrix product.
* @public
* @returns {og.Mat4} - Inversed projection-view matrix.
* @returns {Mat4} - Inversed projection-view matrix.
*/
getInverseProjectionViewMatrix() {
return this.frustum._inverseProjectionViewMatrix._m;
@ -628,7 +625,7 @@ class Camera {
/**
* Returns inverse projection matrix.
* @public
* @returns {og.Mat4} - Inversed projection-view matrix.
* @returns {Mat4} - Inversed projection-view matrix.
*/
getInverseProjectionMatrix() {
return this.frustum._inverseProjectionMatrix._m;

View File

@ -1,6 +1,6 @@
'use strict';
"use strict";
import { Mat4 } from '../math/Mat4.js';
import { Mat4 } from "../math/Mat4.js";
function planeNormalize(plane) {
var t = 1.0 / Math.sqrt(plane[0] * plane[0] + plane[1] * plane[1] + plane[2] * plane[2]);
@ -15,6 +15,9 @@ function planeNormalize(plane) {
* @class
*/
class Frustum {
/**
* @param {*} options
*/
constructor(options = {}) {
/**
* Frustum planes.
@ -29,28 +32,28 @@ class Frustum {
/**
* Camera projection matrix.
* @protected
* @type {og.Mat4}
* @type {Mat4}
*/
this._projectionMatrix = new Mat4();
/**
* Camera inverse projection matrix.
* @protected
* @type {og.Mat4}
* @type {Mat4}
*/
this._inverseProjectionMatrix = new Mat4();
/**
* Product of projection and view matrices.
* @protected
* @type {og.Mat4}
* @type {Mat4}
*/
this._projectionViewMatrix = new Mat4();
/**
* Inverse projectionView Matrix.
* @protected
* @type {og.Mat4}
* @type {Mat4}
*/
this._inverseProjectionViewMatrix = new Mat4();
@ -85,7 +88,8 @@ class Frustum {
*/
this.far = 0.0;
this._cameraFrustumIndex = options.cameraFrustumIndex != undefined ? options.cameraFrustumIndex : -1;
this._cameraFrustumIndex =
options.cameraFrustumIndex != undefined ? options.cameraFrustumIndex : -1;
this.setProjectionMatrix(
options.fov || 30.0,
@ -140,15 +144,21 @@ class Frustum {
* @param {number} far - Far camera distance.
*/
setProjectionMatrix(angle, aspect, near, far) {
this.top = near * Math.tan(angle * Math.PI / 360);
this.top = near * Math.tan((angle * Math.PI) / 360);
this.bottom = -this.top;
this.right = this.top * aspect;
this.left = -this.right;
this.near = near;
this.far = far;
this._projectionMatrix.setPerspective(this.left, this.right, this.bottom, this.top, near, far);
this._projectionMatrix.setPerspective(
this.left,
this.right,
this.bottom,
this.top,
near,
far
);
this._projectionMatrix.inverseTo(this._inverseProjectionMatrix);
}
@ -158,7 +168,6 @@ class Frustum {
* @param {Mat4} projectionView - projectionView matrix.
*/
setViewMatrix(viewMatrix) {
this._projectionViewMatrix = this._projectionMatrix.mul(viewMatrix);
this._projectionViewMatrix.inverseTo(this._inverseProjectionViewMatrix);
@ -210,7 +219,7 @@ class Frustum {
/**
* Returns true if a point in the frustum.
* @public
* @param {og.Vec3} point - Cartesian point.
* @param {Vec3} point - Cartesian point.
* @returns {boolean} -
*/
containsPoint(point) {
@ -227,7 +236,7 @@ class Frustum {
/**
* Returns true if the frustum contains a bonding sphere, but bottom plane exclude.
* @public
* @param {og.bv.Sphere} sphere - Bounding sphere.
* @param {Sphere} sphere - Bounding sphere.
* @returns {boolean} -
*/
containsSphereBottomExc(sphere) {
@ -251,7 +260,7 @@ class Frustum {
/**
* Returns true if the frustum contains a bonding sphere.
* @public
* @param {og.bv.Sphere} sphere - Bounding sphere.
* @param {Sphere} sphere - Bounding sphere.
* @returns {boolean} -
*/
containsSphere(sphere) {
@ -287,15 +296,17 @@ class Frustum {
/**
* Returns true if the frustum contains a bounding box.
* @public
* @param {og.bv.Box} box - Bounding box.
* @param {Box} box - Bounding box.
* @returns {boolean} -
*/
containsBox(box) {
var result = true, cout, cin;
var result = true,
cout,
cin;
for (var i = 0; i < 6; i++) {
cout = 0; cin = 0;
cout = 0;
cin = 0;
for (var k = 0; k < 8 && (cin === 0 || cout === 0); k++) {
var d = box.vertices[k].dotArr(this._f[i]) + this._f[i][3];

View File

@ -17,8 +17,8 @@ import { Mat4 } from "../math/Mat4.js";
/**
* Planet camera.
* @class
* @extends {og.Camera}
* @param {og.RenderNode} planet - Planet render node.
* @extends {Camera}
* @param {RenderNode} planet - Planet render node.
* @param {Object} [options] - Planet camera options:
* @param {Object} [options.name] - Camera name.
* @param {number} [options.viewAngle=37] - Camera angle of view. Default is 35.0
@ -26,11 +26,15 @@ import { Mat4 } from "../math/Mat4.js";
* @param {number} [options.far] - Camera far plane distance. Deafult is og.math.MAX
* @param {number} [options.minAltitude] - Minimal altitude for the camera. Deafult is 1
* @param {number} [options.maxAltitude] - Maximal altitude for the camera. Deafult is 20000000
* @param {og.Vec3} [options.eye] - Camera eye position. Default (0,0,0)
* @param {og.Vec3} [options.look] - Camera look position. Default (0,0,0)
* @param {og.Vec3} [options.up] - Camera eye position. Default (0,1,0)
* @param {Vec3} [options.eye] - Camera eye position. Default (0,0,0)
* @param {Vec3} [options.look] - Camera look position. Default (0,0,0)
* @param {Vec3} [options.up] - Camera eye position. Default (0,1,0)
*/
class PlanetCamera extends Camera {
/**
* @param {RenderNode} planet - Planet render node.
* @param {Object} [options] - Planet camera options:
*/
constructor(planet, options) {
super(
planet.renderer,
@ -50,7 +54,7 @@ class PlanetCamera extends Camera {
/**
* Assigned camera's planet.
* @public
* @type {og.scene.Planet}
* @type {Planet}
*/
this.planet = planet;
@ -92,14 +96,14 @@ class PlanetCamera extends Camera {
/**
* Cartesian coordinates on the terrain.
* @protected
* @type {og.Vec3}
* @type {Vec3}
*/
this._terrainPoint = new Vec3();
/**
* Quad node that camera flies over.
* @protected
* @type {og.quadTree.Node}
* @type {quadTree.Node}
*/
this._insideSegment = null;
@ -178,7 +182,7 @@ class PlanetCamera extends Camera {
* @public
* @param {LonLat} lonlat - New camera and camera view position.
* @param {LonLat} [lookLonLat] - Look up coordinates.
* @param {og.Vec3} [up] - Camera UP vector. Default (0,1,0)
* @param {Vec3} [up] - Camera UP vector. Default (0,1,0)
*/
setLonLat(lonlat, lookLonLat, up) {
this.stopFlying();
@ -211,9 +215,9 @@ class PlanetCamera extends Camera {
/**
* Gets position by viewable extent.
* @public
* @param {og.Extent} extent - Viewable extent.
* @param {Extent} extent - Viewable extent.
* @param {Number} height - Camera height
* @returns {og.Vec3}
* @returns {Vec3}
*/
getExtentPosition(extent, height) {
var north = extent.getNorth();
@ -281,7 +285,7 @@ class PlanetCamera extends Camera {
/**
* View current extent.
* @public
* @param {og.Extent} extent - Current extent.
* @param {Extent} extent - Current extent.
*/
viewExtent(extent, height) {
this.stopFlying();
@ -292,8 +296,8 @@ class PlanetCamera extends Camera {
/**
* Flies to the current extent.
* @public
* @param {og.Extent} extent - Current extent.
* @param {og.Vec3} [up] - Camera UP in the end of flying. Default - (0,1,0)
* @param {Extent} extent - Current extent.
* @param {Vec3} [up] - Camera UP in the end of flying. Default - (0,1,0)
* @param {Number} [ampl] - Altitude amplitude factor.
* @param {cameraCallback} [completeCallback] - Callback that calls after flying when flying is finished.
* @param {cameraCallback} [startCallback] - Callback that calls befor the flying begins.
@ -356,9 +360,9 @@ class PlanetCamera extends Camera {
/**
* Flies to the cartesian coordinates.
* @public
* @param {og.Vec3} cartesian - Finish cartesian coordinates.
* @param {og.Vec3} [look] - Camera LOOK in the end of flying. Default - (0,0,0)
* @param {og.Vec3} [up] - Camera UP vector in the end of flying. Default - (0,1,0)
* @param {Vec3} cartesian - Finish cartesian coordinates.
* @param {Vec3} [look] - Camera LOOK in the end of flying. Default - (0,0,0)
* @param {Vec3} [up] - Camera UP vector in the end of flying. Default - (0,1,0)
* @param {Number} [ampl=1.0] - Altitude amplitude factor.
* @param {cameraCallback} [completeCallback] - Callback that calls after flying when flying is finished.
* @param {cameraCallback} [startCallback] - Callback that calls befor the flying begins.
@ -453,8 +457,8 @@ class PlanetCamera extends Camera {
* Flies to the geo coordiantes.
* @public
* @param {LonLat} lonlat - Finish coordinates.
* @param {og.Vec3} [look] - Camera LOOK in the end of flying. Default - (0,0,0)
* @param {og.Vec3} [up] - Camera UP vector in the end of flying. Default - (0,1,0)
* @param {Vec3} [look] - Camera LOOK in the end of flying. Default - (0,0,0)
* @param {Vec3} [up] - Camera UP vector in the end of flying. Default - (0,1,0)
* @param {Number} [ampl] - Altitude amplitude factor.
* @param {cameraCallback} [completeCallback] - Callback that calls after flying when flying is finished.
* @param {cameraCallback} [startCallback] - Callback that calls befor the flying begins.

View File

@ -82,10 +82,14 @@ let svg = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
/**
* Planet compass button
* @class
* @extends {og.control.Control}
* @extends {Control}
* @params {Object} [options] - Control options.
*/
class CompassButton extends Control {
/**
*
* @params {Object} [options] - Control options.
*/
constructor(options) {
super(options);

View File

@ -2,7 +2,7 @@
* @module og/control/Control
*/
'use strict';
"use strict";
/**
* Base control class for implementing renderer controls.
@ -12,6 +12,9 @@
* @param {Boolean} [options.autoActivated=true] - If true - calls initialize function after the renderer assigning.
*/
class Control {
/**
* @param {Object} [options] - Control activation options:
*/
constructor(options) {
options = options || {};
@ -29,7 +32,7 @@ class Control {
/**
* Assigned renderer.
* @public
* @type {og.Renderer}
* @type {Renderer}
*/
this.renderer = null;
@ -73,40 +76,40 @@ class Control {
* @public
* @virtual
*/
oninit() { }
oninit() {}
/**
* Control renderer assigning function have to be overriden.
* @public
* @virtual
*/
onadd() { }
onadd() {}
/**
* Control remove function have to be overriden.
* @public
* @virtual
*/
onremove() { }
onremove() {}
/**
* Control activation function have to be overriden.
* @public
* @virtual
*/
onactivate() { }
onactivate() {}
/**
* Control deactivation function have to be overriden.
* @public
* @virtual
*/
ondeactivate() { }
ondeactivate() {}
/**
* Assign renderer to the control.
* @public
* @type {og.Renderer}
* @type {Renderer}
*/
addTo(renderer) {
if (renderer) {
@ -126,7 +129,6 @@ class Control {
* @public
*/
remove() {
this.onremove && this.onremove();
let r = this.renderer,

View File

@ -9,10 +9,13 @@ import { Control } from "./Control.js";
/**
* Debug information
* @class
* @extends {og.control.Control}
* @extends {Control}
* @param {Object} [options] - Control options.
*/
class DebugInfo extends Control {
/**
* @param {Object} [options] - Control options.
*/
constructor(options) {
options = options || {};
if (!options.name || options.name === "") {

View File

@ -2,26 +2,31 @@
* @module og/control/EarthCoordinates
*/
'use strict';
"use strict";
import { Control } from './Control.js';
import { Control } from "./Control.js";
function dec2deg(base) {
var t;
var degrees = base < 0 ? Math.ceil(base) : Math.floor(base);
var minutes = Math.floor(t = Math.abs((base - degrees)) * 60);
var minutes = Math.floor((t = Math.abs(base - degrees) * 60));
var seconds = Math.floor((t - minutes) * 6000);
seconds = seconds / 100.00;
return (numToFixedString(degrees, 3) + "\u00B0" +
numToFixedString(minutes, 2) + "\u0027" +
numToFixedString(seconds.toFixed(2), 2) + "\u0022");
seconds = seconds / 100.0;
return (
numToFixedString(degrees, 3) +
"\u00B0" +
numToFixedString(minutes, 2) +
"\u0027" +
numToFixedString(seconds.toFixed(2), 2) +
"\u0022"
);
}
function numToFixedString(num, fixed) {
var dl = num.toString().split('.')[0].length;
var dl = num.toString().split(".")[0].length;
var white = "&nbsp;";
for (var i = dl; i < fixed; i++) {
white += '&nbsp;&nbsp;';
white += "&nbsp;&nbsp;";
}
return white + num.toString();
}
@ -39,21 +44,21 @@ function toMercator(ll) {
return m.lat.toFixed(5) + ", " + m.lon.toFixed(5);
}
const DisplayTypesConverters = [
toDecimal,
toDegrees,
toMercator
];
const DisplayTypesConverters = [toDecimal, toDegrees, toMercator];
/**
* Control displays mouse or screen center Earth coordinates.
* @class
* @extends {og.control.Control}
* @extends {Control}
* @param {Object} [options] - Options:
* @param {Boolean} [options.center] - Earth coordiantes by screen center otherwise mouse pointer. False is default.
* @param {Boolean} [options.type] - Coordinates shown: 0 - is decimal degrees, 1 - degrees, 2 - mercator geodetic coordinates.
*/
class EarthCoordinates extends Control {
/**
*
* @param {Object} [options] - Options:
*/
constructor(options) {
super(options);
@ -87,27 +92,32 @@ class EarthCoordinates extends Control {
*/
var pad = false;
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
if (
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
)
) {
pad = true;
}
this._center = options.center || pad;
this._centerDiv = null;
/**
* Current position.
* @public
* @type {og.Vec3}
* @type {Vec3}
*/
this.position = null;
}
oninit() {
this._display = document.createElement('div');
this._display.className = 'ogEarthCoordinatesControl';
this._display = document.createElement("div");
this._display.className = "ogEarthCoordinatesControl";
var that = this;
function _refresh(el) {
if (that._displayType >= DisplayTypesConverters.length) {
that._displayType = 0;
}
@ -132,19 +142,19 @@ class EarthCoordinates extends Control {
_refresh(this._display);
let centerDiv = document.createElement('div');
centerDiv.className = 'ogCenterIcon';
centerDiv.innerHTML = '<svg width="12" height="12"><g><path stroke-width="1" stroke-opacity="1" d="M6 0L6 12M0 6L12 6" stroke="#009DFF"></path></g></svg>';
this.renderer.div.appendChild(centerDiv);
this._centerDiv = document.createElement("div");
this._centerDiv.className = "ogCenterIcon";
this._centerDiv.innerHTML =
'<svg width="12" height="12"><g><path stroke-width="1" stroke-opacity="1" d="M6 0L6 12M0 6L12 6" stroke="#009DFF"></path></g></svg>';
this.renderer.div.appendChild(this._centerDiv);
if (this._center) {
this.renderer.activeCamera.events.on("moveend", this._grabCoordinates, this);
centerDiv.style.display = "block";
this._centerDiv.style.display = "block";
} else {
this.renderer.events.on("mousemove", this._onMouseMove, this);
centerDiv.style.display = "none";
this._centerDiv.style.display = "none";
}
}
/**
@ -158,19 +168,28 @@ class EarthCoordinates extends Control {
if (center) {
this.renderer.events.off("mousemove", this._onMouseMove);
this.renderer.activeCamera.events.on("moveend", this._grabCoordinates, this);
centerDiv.style.display = "block";
this._centerDiv.style.display = "block";
} else {
this.renderer.events.off("draw", this._draw);
this.renderer.events.on("mousemove", this._onMouseMove, this);
centerDiv.style.display = "none";
this._centerDiv.style.display = "none";
}
}
}
_showPosition() {
if (this.position) {
this.position.height = ((this.position.height > 10000 || this.position.height < -10000) ? 0 : this.position.height);
this._display.innerHTML = "Lat/Lon: " + this._converter(this.position) + " h(m): " + (this.position.height > 0 ? "~" + (Math.round(this.position.height) / 1000).toFixed(3) * 1000 : "-");
this.position.height =
this.position.height > 10000 || this.position.height < -10000
? 0
: this.position.height;
this._display.innerHTML =
"Lat/Lon: " +
this._converter(this.position) +
" h(m): " +
(this.position.height > 0
? "~" + (Math.round(this.position.height) / 1000).toFixed(3) * 1000
: "-");
} else {
this._display.innerHTML = "Lat/Lon: " + "_____________________";
}
@ -185,9 +204,11 @@ class EarthCoordinates extends Control {
_onMouseMove() {
var r = this.renderer;
var ms = r.events.mouseState;
if (!(ms.leftButtonDown || ms.rightButtonDown) &&
if (
!(ms.leftButtonDown || ms.rightButtonDown) &&
r.controlsBag.scaleRot <= 0 &&
!r.activeCamera._flying) {
!r.activeCamera._flying
) {
this.position = this.planet.getLonLatFromPixelTerrain(ms, true);
this._showPosition();
}

View File

@ -2,17 +2,17 @@
* @module og/control/KeyboardNavigation
*/
'use strict';
"use strict";
import * as math from '../math.js';
import { Control } from './Control.js';
import { input } from '../input/input.js';
import { Vec3 } from '../math/Vec3.js';
import * as math from "../math.js";
import { Control } from "./Control.js";
import { input } from "../input/input.js";
import { Vec3 } from "../math/Vec3.js";
/**
* Planet camera keyboard navigation. Use W,S,A,D and left shift key for fly around a planet.
* @class
* @extends {og.control.Control}
* @extends {Control}
* @param {Object} [options] - Control options.
*/
@ -69,7 +69,7 @@ class KeyboardNavigation extends Control {
if (this.renderer.events.isKeyPressed(input.KEY_SHIFT)) {
cam.pitch(15 / this.renderer.handler.deltaTime);
} else {
cam.rotateVertical(cam._lonLat.height / 3000000 * math.RADIANS, Vec3.ZERO);
cam.rotateVertical((cam._lonLat.height / 3000000) * math.RADIANS, Vec3.ZERO);
}
cam.update();
}
@ -79,7 +79,7 @@ class KeyboardNavigation extends Control {
if (this.renderer.events.isKeyPressed(input.KEY_SHIFT)) {
cam.pitch(-15 / this.renderer.handler.deltaTime);
} else {
cam.rotateVertical(-cam._lonLat.height / 3000000 * math.RADIANS, Vec3.ZERO);
cam.rotateVertical((-cam._lonLat.height / 3000000) * math.RADIANS, Vec3.ZERO);
}
cam.update();
}
@ -89,7 +89,7 @@ class KeyboardNavigation extends Control {
if (this.renderer.events.isKeyPressed(input.KEY_SHIFT)) {
cam.yaw(15 / this.renderer.handler.deltaTime);
} else {
cam.rotateHorizontal(cam._lonLat.height / 3000000 * math.RADIANS, false, Vec3.ZERO);
cam.rotateHorizontal((cam._lonLat.height / 3000000) * math.RADIANS, false, Vec3.ZERO);
}
cam.update();
}
@ -99,7 +99,7 @@ class KeyboardNavigation extends Control {
if (this.renderer.events.isKeyPressed(input.KEY_SHIFT)) {
cam.yaw(-15 / this.renderer.handler.deltaTime);
} else {
cam.rotateHorizontal(-cam._lonLat.height / 3000000 * math.RADIANS, false, Vec3.ZERO);
cam.rotateHorizontal((-cam._lonLat.height / 3000000) * math.RADIANS, false, Vec3.ZERO);
}
cam.update();
}

View File

@ -2,14 +2,14 @@
* @module og/control/LayerSwitcher
*/
'use strict';
"use strict";
import { Control } from './Control.js';
import { Control } from "./Control.js";
/**
* Simple(OpenLayers like)layer switcher, includes base layers, overlays, geo images etc. groups.
* @class
* @extends {og.control.Control}
* @extends {Control}
* @param {Object} [options] - Control options.
*/
class LayerSwitcher extends Control {
@ -56,16 +56,16 @@ class LayerSwitcher extends Control {
}
addSwitcher(type, obj, container, id) {
var lineDiv = document.createElement('div');
var lineDiv = document.createElement("div");
var that = this;
var center = document.createElement('div');
center.classList.add('ogViewExtentBtn');
var center = document.createElement("div");
center.classList.add("ogViewExtentBtn");
center.onclick = function () {
that.planet.flyExtent(obj.getExtent());
};
var inp = document.createElement('input');
var inp = document.createElement("input");
inp.type = type;
inp.name = "ogBaseLayerRadiosId" + (id || "");
inp.checked = obj.getVisibility();
@ -74,11 +74,12 @@ class LayerSwitcher extends Control {
obj.setVisibility(this.checked);
};
obj.events && obj.events.on("visibilitychange", function (e) {
obj.events &&
obj.events.on("visibilitychange", function (e) {
inp.checked = e.getVisibility();
});
var lbl = document.createElement('label');
var lbl = document.createElement("label");
lbl.className = "ogLayerSwitcherLabel";
lbl.innerHTML = (obj.name || obj.src || "noname") + "</br>";
@ -94,35 +95,35 @@ class LayerSwitcher extends Control {
}
createBaseLayersContainer() {
var layersDiv = document.createElement('div');
var layersDiv = document.createElement("div");
layersDiv.className = "layersDiv";
this.dialog.appendChild(layersDiv);
var baseLayersLbl = document.createElement('div');
var baseLayersLbl = document.createElement("div");
baseLayersLbl.className = "layersDiv";
baseLayersLbl.innerHTML = "Base Layer";
layersDiv.appendChild(baseLayersLbl);
this.baseLayersDiv = document.createElement('div');
this.baseLayersDiv = document.createElement("div");
layersDiv.appendChild(this.baseLayersDiv);
}
createOverlaysContainer() {
var overlaysDiv = document.createElement('div');
var overlaysDiv = document.createElement("div");
overlaysDiv.className = "layersDiv";
this.dialog.appendChild(overlaysDiv);
var overlaysLbl = document.createElement('div');
var overlaysLbl = document.createElement("div");
overlaysLbl.className = "layersDiv";
overlaysLbl.innerHTML = "Overlays";
overlaysDiv.appendChild(overlaysLbl);
this.overlaysDiv = document.createElement('div');
this.overlaysDiv = document.createElement("div");
overlaysDiv.appendChild(this.overlaysDiv);
}
createDialog() {
this.dialog = document.createElement('div');
this.dialog = document.createElement("div");
this.dialog.id = "ogLayerSwitcherDialog";
this.dialog.className = "displayNone";
this.renderer.div.appendChild(this.dialog);
@ -138,8 +139,8 @@ class LayerSwitcher extends Control {
}
createSwitcher() {
var button = document.createElement('div');
button.className = 'ogLayerSwitcherButton';
var button = document.createElement("div");
button.className = "ogLayerSwitcherButton";
button.id = "ogLayerSwitcherButtonMaximize";
var that = this;
button.onclick = function (e) {

View File

@ -115,7 +115,7 @@ const TEMPLATE = `<div class="og-lighing">
/**
* Helps to setup lighting.
* @class
* @extends {og.control.Control}
* @extends {Control}
* @param {Object} [options] -
*/
class Lighting extends Control {

View File

@ -18,7 +18,7 @@ import { Vec3 } from "../math/Vec3.js";
/**
* Mouse planet camera dragging control.
* @class
* @extends {og.control.Control}
* @extends {Control}
* @param {Object} [options] - Control options.
*/
class MouseNavigation extends Control {

View File

@ -21,7 +21,7 @@ const TEMPLATE = `<div class="og-scale-container">
/**
* Planet zoom buttons control.
* @class
* @extends {og.control.Control}
* @extends {Control}
* @params {Object} [options] - Control options.
*/
class ScaleControl extends Control {

View File

@ -1,13 +1,13 @@
'use strict';
"use strict";
import { Control } from './Control.js';
import { EntityCollection } from '../entity/EntityCollection.js';
import { Entity } from '../entity/Entity.js';
import { Control } from "./Control.js";
import { EntityCollection } from "../entity/EntityCollection.js";
import { Entity } from "../entity/Entity.js";
/**
* Frame per second(FPS) display control.
* @class
* @extends {og.control.Control}
* @extends {Control}
* @param {Object} [options] - Control options.
*/
class SegmentBoundVisualization extends Control {
@ -18,7 +18,6 @@ class SegmentBoundVisualization extends Control {
}
oninit() {
this.planet.addEntityCollection(this._boundingSphereCollection);
this.renderer.events.on("draw", this._predraw, this);

View File

@ -2,15 +2,15 @@
* @module og/control/ShowFps
*/
'use strict';
"use strict";
import { Control } from './Control.js';
import { print2d } from '../utils/shared.js';
import { Control } from "./Control.js";
import { print2d } from "../utils/shared.js";
/**
* Frame per second(FPS) display control.
* @class
* @extends {og.control.Control}
* @extends {Control}
* @param {Object} [options] - Control options.
*/
class ShowFps extends Control {
@ -19,15 +19,20 @@ class ShowFps extends Control {
}
oninit() {
var d = document.createElement('div');
d.className = 'defaultText ';
var d = document.createElement("div");
d.className = "defaultText ";
d.id = "ogShowFpsControl";
document.body.appendChild(d);
this.renderer.events.on("draw", this._draw, this);
}
_draw() {
print2d("ogShowFpsControl", (1000.0 / this.renderer.handler.deltaTime).toFixed(1), this.renderer.handler.canvas.clientWidth - 60, 0);
print2d(
"ogShowFpsControl",
(1000.0 / this.renderer.handler.deltaTime).toFixed(1),
this.renderer.handler.canvas.clientWidth - 60,
0
);
}
}

View File

@ -1,12 +1,12 @@
'use strict';
"use strict";
import { Control } from './Control.js';
import { input } from '../input/input.js';
import { Control } from "./Control.js";
import { input } from "../input/input.js";
/**
* Simple keyboard camera navigation with W,S,A,D and shift keys to fly around the scene.
* @class
* @extends {og.control.Control}
* @extends {Control}
* @param {Object} [options] - Control options.
*/
class SimpleNavigation extends Control {
@ -18,11 +18,9 @@ class SimpleNavigation extends Control {
this.speed = options.speed || 1.0;
}
onactivate() {
}
onactivate() {}
ondeactivate() {
}
ondeactivate() {}
oninit() {
this.camera = this.renderer.activeCamera;

View File

@ -2,19 +2,19 @@
* @module og/control/Sun
*/
'use strict';
"use strict";
import { Control } from './Control.js';
import { getSunPosition } from '../astro/earth.js';
import { LightSource } from '../light/LightSource.js';
import { Quat } from '../math/Quat.js';
import { Vec3 } from '../math/Vec3.js';
import { Control } from "./Control.js";
import { getSunPosition } from "../astro/earth.js";
import { LightSource } from "../light/LightSource.js";
import { Quat } from "../math/Quat.js";
import { Vec3 } from "../math/Vec3.js";
const ACTIVATION_HEIGHT = 12079000.0;
/**
* Real Sun geocentric position control that place the Sun on the right place by the Earth.
* @class
* @extends {og.control.Control}
* @extends {Control}
* @param {Object} [options] - Control options.
*/
class Sun extends Control {
@ -28,7 +28,7 @@ class Sun extends Control {
/**
* Earth planet node.
* @public
* @type {og.scene.Planet}
* @type {Planet}
*/
this.planet = null;
@ -46,7 +46,7 @@ class Sun extends Control {
/**
* Light source.
* @public
* @type {og.LightSource}
* @type {LightSource}
*/
this.sunlight = null;
@ -72,7 +72,6 @@ class Sun extends Control {
}
oninit() {
this.planet.lightEnabled = true;
// sunlight initialization
@ -120,12 +119,17 @@ class Sun extends Control {
}
var tu = Vec3.proj_b_to_plane(u, n, u).normalize().scale(this.offsetVertical);
var tr = Vec3.proj_b_to_plane(cam._u, n, cam._u).normalize().scale(this.offsetHorizontal); // right
var tr = Vec3.proj_b_to_plane(cam._u, n, cam._u)
.normalize()
.scale(this.offsetHorizontal); // right
var d = tu.add(tr);
var pos = cam.eye.add(d);
if (this._k > 0) {
this._k -= 0.01;
let rot = Quat.getRotationBetweenVectors(this.sunlight._position.normal(), pos.normal());
let rot = Quat.getRotationBetweenVectors(
this.sunlight._position.normal(),
pos.normal()
);
let r = rot.slerp(Quat.IDENTITY, this._k).normalize();
this.sunlight.setPosition3v(r.mulVec3(this.sunlight._position));
} else {
@ -135,11 +139,17 @@ class Sun extends Control {
this._k = 1;
if (this._f > 0) {
this._f -= 0.01;
let rot = Quat.getRotationBetweenVectors(this.sunlight._position.normal(), getSunPosition(this._currDate).normal());
let rot = Quat.getRotationBetweenVectors(
this.sunlight._position.normal(),
getSunPosition(this._currDate).normal()
);
let r = rot.slerp(Quat.IDENTITY, this._f).normalize();
this.sunlight.setPosition3v(r.mulVec3(this.sunlight._position));
} else {
if ((Math.abs(this._currDate - this._prevDate) > 0.00034 && this._active) || this._lightOn) {
if (
(Math.abs(this._currDate - this._prevDate) > 0.00034 && this._active) ||
this._lightOn
) {
this._lightOn = false;
this._prevDate = this._currDate;
this.sunlight.setPosition3v(getSunPosition(this._currDate));

View File

@ -2,15 +2,15 @@
* @module og/control/ToggleWireframe
*/
'use strict';
"use strict";
import { Control } from './Control.js';
import { input } from '../input/input.js';
import { Control } from "./Control.js";
import { input } from "../input/input.js";
/**
* Planet GL draw mode(TRIANGLE_STRIP/LINE_STRING) changer.
* @class
* @extends {og.control.Control}
* @extends {Control}
* @param {Object} [options] - Control options.
*/
class ToggleWireframe extends Control {

View File

@ -2,16 +2,16 @@
* @module og/control/TouchNavigation
*/
'use strict';
"use strict";
import * as math from '../math.js';
import { Control } from './Control.js';
import { Key } from '../Lock.js';
import { LonLat } from '../LonLat.js';
import { Quat } from '../math/Quat.js';
import { Ray } from '../math/Ray.js';
import { Sphere } from '../bv/Sphere.js';
import { Vec3 } from '../math/Vec3.js';
import * as math from "../math.js";
import { Control } from "./Control.js";
import { Key } from "../Lock.js";
import { LonLat } from "../LonLat.js";
import { Quat } from "../math/Quat.js";
import { Ray } from "../math/Ray.js";
import { Sphere } from "../bv/Sphere.js";
import { Vec3 } from "../math/Vec3.js";
class Touch {
constructor() {
@ -21,15 +21,19 @@ class Touch {
this.prev_y = 0;
this.grabbedPoint = new Vec3();
this.grabbedSpheroid = new Sphere();
this.dX = function () { return this.x - this.prev_x; };
this.dY = function () { return this.y - this.prev_y; };
this.dX = function () {
return this.x - this.prev_x;
};
this.dY = function () {
return this.y - this.prev_y;
};
}
}
/**
* Touch pad planet camera dragging control.
* @class
* @extends {og.control.Control}
* @extends {Control}
* @param {Object} [options] - Control options.
*/
class TouchNavigation extends Control {
@ -69,11 +73,9 @@ class TouchNavigation extends Control {
}
onTouchStart(e) {
this._touching = true;
if (e.sys.touches.length === 2) {
var t0 = this.touches[0],
t1 = this.touches[1];
@ -90,7 +92,10 @@ class TouchNavigation extends Control {
t1.grabbedPoint = this.planet.getCartesianFromPixelTerrain(t1, true);
// this.planet._viewChanged = true;
this.pointOnEarth = this.planet.getCartesianFromPixelTerrain(this.renderer.handler.getCenter(), true);
this.pointOnEarth = this.planet.getCartesianFromPixelTerrain(
this.renderer.handler.getCenter(),
true
);
if (this.pointOnEarth) {
this.earthUp = this.pointOnEarth.normal();
@ -101,7 +106,6 @@ class TouchNavigation extends Control {
t1.grabbedSpheroid.radius = t1.grabbedPoint.length();
this.stopRotation();
}
} else if (e.sys.touches.length === 1) {
this._startTouchOne(e);
}
@ -141,12 +145,13 @@ class TouchNavigation extends Control {
var p = this.planet.getCartesianFromPixelTerrain(this.touches[0], true);
if (p) {
var g = this.planet.ellipsoid.cartesianToLonLat(p);
this.planet.flyLonLat(new LonLat(g.lon, g.lat, this.renderer.activeCamera.eye.distance(p) * 0.57));
this.planet.flyLonLat(
new LonLat(g.lon, g.lat, this.renderer.activeCamera.eye.distance(p) * 0.57)
);
}
}
onTouchEnd(e) {
if (e.sys.touches.length === 0) {
this._touching = false;
}
@ -155,21 +160,20 @@ class TouchNavigation extends Control {
this._startTouchOne(e);
}
if ((Math.abs(this.touches[0].x - this.touches[0].prev_x) < 3) &&
(Math.abs(this.touches[0].y - this.touches[0].prev_y) < 3)) {
if (
Math.abs(this.touches[0].x - this.touches[0].prev_x) < 3 &&
Math.abs(this.touches[0].y - this.touches[0].prev_y) < 3
) {
this.scaleRot = 0;
}
}
onTouchCancel(e) {
}
onTouchCancel(e) {}
onTouchMove(e) {
var cam = this.renderer.activeCamera;
if (e.sys.touches.length === 2) {
this.renderer.controlsBag.scaleRot = 1;
var t0 = this.touches[0],
@ -191,9 +195,14 @@ class TouchNavigation extends Control {
t1.x = e.sys.touches.item(1).clientX - e.sys.offsetLeft;
t1.y = e.sys.touches.item(1).clientY - e.sys.offsetTop;
if ((t0.dY() > 0 && t1.dY() > 0) || (t0.dY() < 0 && t1.dY() < 0) ||
(t0.dX() > 0 && t1.dX() > 0) || (t0.dX() < 0 && t1.dX() < 0)) {
var l = 0.5 / cam.eye.distance(this.pointOnEarth) * cam._lonLat.height * math.RADIANS;
if (
(t0.dY() > 0 && t1.dY() > 0) ||
(t0.dY() < 0 && t1.dY() < 0) ||
(t0.dX() > 0 && t1.dX() > 0) ||
(t0.dX() < 0 && t1.dX() < 0)
) {
var l =
(0.5 / cam.eye.distance(this.pointOnEarth)) * cam._lonLat.height * math.RADIANS;
if (l > 0.007) l = 0.007;
cam.rotateHorizontal(l * t0.dX(), false, this.pointOnEarth, this.earthUp);
cam.rotateVertical(l * t0.dY(), this.pointOnEarth, true);
@ -202,9 +211,7 @@ class TouchNavigation extends Control {
}
this.scaleRot = 0;
} else if (e.sys.touches.length === 1) {
var t = this.touches[0];
t.prev_x = t.x;
@ -223,7 +230,10 @@ class TouchNavigation extends Control {
if (targetPoint) {
if (cam.slope > 0.2) {
this.qRot = Quat.getRotationBetweenVectors(targetPoint.normal(), t.grabbedPoint.normal());
this.qRot = Quat.getRotationBetweenVectors(
targetPoint.normal(),
t.grabbedPoint.normal()
);
var rot = this.qRot;
cam.eye = rot.mulVec3(cam.eye);
cam._v = rot.mulVec3(cam._v);
@ -250,7 +260,6 @@ class TouchNavigation extends Control {
}
onDraw(e) {
this.renderer.controlsBag.scaleRot = this.scaleRot;
if (this._touching) {
@ -281,7 +290,9 @@ class TouchNavigation extends Control {
this.scaleRot = 0;
} else {
r.controlsBag.scaleRot = this.scaleRot;
var rot = this.qRot.slerp(Quat.IDENTITY, 1 - this.scaleRot * this.scaleRot * this.scaleRot).normalize();
var rot = this.qRot
.slerp(Quat.IDENTITY, 1 - this.scaleRot * this.scaleRot * this.scaleRot)
.normalize();
if (!(rot.x || rot.y || rot.z)) {
this.scaleRot = 0;
}

View File

@ -2,15 +2,15 @@
* @module og/control/ZoomControl
*/
'use strict';
"use strict";
import { Control } from './Control.js';
import { Key } from '../Lock.js';
import { Control } from "./Control.js";
import { Key } from "../Lock.js";
/**
* Planet zoom buttons control.
* @class
* @extends {og.control.Control}
* @extends {Control}
* @params {Object} [options] - Control options.
*/
class ZoomControl extends Control {
@ -27,13 +27,13 @@ class ZoomControl extends Control {
}
oninit() {
var zoomDiv = document.createElement('div'),
btnZoomIn = document.createElement('button'),
btnZoomOut = document.createElement('button');
var zoomDiv = document.createElement("div"),
btnZoomIn = document.createElement("button"),
btnZoomOut = document.createElement("button");
zoomDiv.className = 'ogZoomControl';
btnZoomIn.className = 'ogZoomButton ogZoomIn';
btnZoomOut.className = 'ogZoomButton ogZoomOut';
zoomDiv.className = "ogZoomControl";
btnZoomIn.className = "ogZoomButton ogZoomIn";
btnZoomOut.className = "ogZoomButton ogZoomOut";
zoomDiv.appendChild(btnZoomIn);
zoomDiv.appendChild(btnZoomOut);
@ -46,13 +46,31 @@ class ZoomControl extends Control {
btnZoomOut.addEventListener("mousedown", (e) => this.zoomOut());
btnZoomOut.addEventListener("mouseup", (e) => this.stopZoom());
btnZoomIn.addEventListener('touchstart', (e) => { e.preventDefault(); this.zoomIn(); });
btnZoomIn.addEventListener('touchend', (e) => { e.preventDefault(); this.stopZoom(); });
btnZoomIn.addEventListener('touchcancel', (e) => { e.preventDefault(); this.stopZoom(); });
btnZoomIn.addEventListener("touchstart", (e) => {
e.preventDefault();
this.zoomIn();
});
btnZoomIn.addEventListener("touchend", (e) => {
e.preventDefault();
this.stopZoom();
});
btnZoomIn.addEventListener("touchcancel", (e) => {
e.preventDefault();
this.stopZoom();
});
btnZoomOut.addEventListener('touchstart', (e) => { e.preventDefault(); this.zoomOut(); });
btnZoomOut.addEventListener('touchend', (e) => { e.preventDefault(); this.stopZoom(); });
btnZoomOut.addEventListener('touchcancel', (e) => { e.preventDefault(); this.stopZoom(); });
btnZoomOut.addEventListener("touchstart", (e) => {
e.preventDefault();
this.zoomOut();
});
btnZoomOut.addEventListener("touchend", (e) => {
e.preventDefault();
this.stopZoom();
});
btnZoomOut.addEventListener("touchcancel", (e) => {
e.preventDefault();
this.stopZoom();
});
this.renderer.events.on("draw", this._draw, this);
}
@ -62,7 +80,6 @@ class ZoomControl extends Control {
* @public
*/
zoomIn() {
this.planet.layerLock.lock(this._keyLock);
this.planet.terrainLock.lock(this._keyLock);
this.planet._normalMapCreator.lock(this._keyLock);
@ -77,7 +94,6 @@ class ZoomControl extends Control {
* @public
*/
zoomOut() {
this.planet.layerLock.lock(this._keyLock);
this.planet.terrainLock.lock(this._keyLock);
this.planet._normalMapCreator.lock(this._keyLock);
@ -87,7 +103,6 @@ class ZoomControl extends Control {
}
stopZoom() {
this._move = 0;
this.planet.layerLock.free(this._keyLock);
@ -96,12 +111,13 @@ class ZoomControl extends Control {
}
_draw(e) {
var cam = this.renderer.activeCamera;
if (this._move !== 0) {
var d = cam.eye.distance(
this.planet.getCartesianFromPixelTerrain(this._targetPoint, true)) * 0.075;
var d =
cam.eye.distance(
this.planet.getCartesianFromPixelTerrain(this._targetPoint, true)
) * 0.075;
cam.eye.addA(cam.getForward().scale(this._move * d));
cam.checkTerrainCollision();
cam.update();

View File

@ -2,11 +2,11 @@
* @module og/ellipsoid/Ellipsoid
*/
'use strict';
"use strict";
import * as math from '../math.js';
import { Vec3 } from '../math/Vec3.js';
import { LonLat } from '../LonLat.js';
import * as math from "../math.js";
import { Vec3 } from "../math/Vec3.js";
import { LonLat } from "../LonLat.js";
/**
* Class represents a plant ellipsoid.
@ -15,6 +15,10 @@ import { LonLat } from '../LonLat.js';
* @param {number} polarSize - Polar ellipsoid size.
*/
class Ellipsoid {
/**
* @param {number} equatorialSize - Equatorial ellipsoid size.
* @param {number} polarSize - Polar ellipsoid size.
*/
constructor(equatorialSize, polarSize) {
this._a = equatorialSize;
this._b = polarSize;
@ -40,8 +44,10 @@ class Ellipsoid {
}
static getRelativeBearing(a, b) {
let a_y = Math.cos(a), a_x = Math.sin(a),
b_y = Math.cos(b), b_x = Math.sin(b);
let a_y = Math.cos(a),
a_x = Math.sin(a),
b_y = Math.cos(b),
b_x = Math.sin(b);
let c = a_y * b_x - b_y * a_x,
d = a_x * b_x + a_y * b_y;
if (c > 0.0) {
@ -71,7 +77,7 @@ class Ellipsoid {
var l3 = l1 + Math.atan2(By, Math.cos(f1) + Bx);
return new LonLat((l3 * math.DEGREES + 540) % 360 - 180, f3 * math.DEGREES);
return new LonLat(((l3 * math.DEGREES + 540) % 360) - 180, f3 * math.DEGREES);
}
/**
@ -82,15 +88,25 @@ class Ellipsoid {
* @returns {LonLat} Intermediate point between points.
*/
static getIntermediatePointOnGreatCircle(lonLat1, lonLat2, fraction) {
var f1 = lonLat1.lat * math.RADIANS, l1 = lonLat1.lon * math.RADIANS;
var f2 = lonLat2.lat * math.RADIANS, l2 = lonLat2.lon * math.RADIANS;
var f1 = lonLat1.lat * math.RADIANS,
l1 = lonLat1.lon * math.RADIANS;
var f2 = lonLat2.lat * math.RADIANS,
l2 = lonLat2.lon * math.RADIANS;
var sinf1 = Math.sin(f1), cosf1 = Math.cos(f1), sinl1 = Math.sin(l1), cosl1 = Math.cos(l1);
var sinf2 = Math.sin(f2), cosf2 = Math.cos(f2), sinl2 = Math.sin(l2), cosl2 = Math.cos(l2);
var sinf1 = Math.sin(f1),
cosf1 = Math.cos(f1),
sinl1 = Math.sin(l1),
cosl1 = Math.cos(l1);
var sinf2 = Math.sin(f2),
cosf2 = Math.cos(f2),
sinl2 = Math.sin(l2),
cosl2 = Math.cos(l2);
var df = f2 - f1,
dl = l2 - l1;
var a = Math.sin(df / 2) * Math.sin(df / 2) + Math.cos(f1) * Math.cos(f2) * Math.sin(dl / 2) * Math.sin(dl / 2);
var a =
Math.sin(df / 2) * Math.sin(df / 2) +
Math.cos(f1) * Math.cos(f2) * Math.sin(dl / 2) * Math.sin(dl / 2);
var d = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var A = Math.sin((1 - fraction) * d) / Math.sin(d);
@ -103,12 +119,15 @@ class Ellipsoid {
var f3 = Math.atan2(z, Math.sqrt(x * x + y * y));
var l3 = Math.atan2(y, x);
return new LonLat((l3 * math.DEGREES + 540) % 360 - 180, f3 * math.DEGREES);
return new LonLat(((l3 * math.DEGREES + 540) % 360) - 180, f3 * math.DEGREES);
}
static getRhumbBearing(lonLat1, lonLat2) {
var dLon = (lonLat2.lon - lonLat1.lon) * math.RADIANS;
var dPhi = Math.log(Math.tan(lonLat2.lat * math.RADIANS / 2 + Math.PI / 4) / Math.tan(lonLat1.lat * math.RADIANS / 2 + Math.PI / 4));
var dPhi = Math.log(
Math.tan((lonLat2.lat * math.RADIANS) / 2 + Math.PI / 4) /
Math.tan((lonLat1.lat * math.RADIANS) / 2 + Math.PI / 4)
);
if (Math.abs(dLon) > Math.PI) {
if (dLon > 0) {
dLon = (2 * Math.PI - dLon) * -1;
@ -120,8 +139,10 @@ class Ellipsoid {
}
static getBearing(lonLat1, lonLat2) {
var f1 = lonLat1.lat * math.RADIANS, l1 = lonLat1.lon * math.RADIANS;
var f2 = lonLat2.lat * math.RADIANS, l2 = lonLat2.lon * math.RADIANS;
var f1 = lonLat1.lat * math.RADIANS,
l1 = lonLat1.lon * math.RADIANS;
var f2 = lonLat2.lat * math.RADIANS,
l2 = lonLat2.lon * math.RADIANS;
var y = Math.sin(l2 - l1) * Math.cos(f2);
var x = Math.cos(f1) * Math.sin(f2) - Math.sin(f1) * Math.cos(f2) * Math.cos(l2 - l1);
return Math.atan2(y, x) * math.DEGREES;
@ -138,8 +159,7 @@ class Ellipsoid {
f2 = lonLat2.lat * math.RADIANS;
var dl = (lonLat2.lon - lonLat1.lon) * math.RADIANS;
var y = Math.sin(dl) * Math.cos(f2);
var x = Math.cos(f1) * Math.sin(f2) -
Math.sin(f1) * Math.cos(f2) * Math.cos(dl);
var x = Math.cos(f1) * Math.sin(f2) - Math.sin(f1) * Math.cos(f2) * Math.cos(dl);
var D = Math.atan2(y, x);
return (D * math.DEGREES + 360) % 360;
}
@ -162,19 +182,30 @@ class Ellipsoid {
var df = f2 - f1,
dl = l2 - l1;
var d12 = 2 * Math.asin(Math.sqrt(Math.sin(df / 2) * Math.sin(df / 2) + Math.cos(f1) * Math.cos(f2) * Math.sin(dl / 2) * Math.sin(dl / 2)));
var d12 =
2 *
Math.asin(
Math.sqrt(
Math.sin(df / 2) * Math.sin(df / 2) +
Math.cos(f1) * Math.cos(f2) * Math.sin(dl / 2) * Math.sin(dl / 2)
)
);
if (d12 == 0) return null;
// initial/final bearings between points
var Da = Math.acos((Math.sin(f2) - Math.sin(f1) * Math.cos(d12)) / (Math.sin(d12) * Math.cos(f1)));
var Da = Math.acos(
(Math.sin(f2) - Math.sin(f1) * Math.cos(d12)) / (Math.sin(d12) * Math.cos(f1))
);
if (isNaN(Da)) Da = 0; // protect against rounding
var Db = Math.acos((Math.sin(f1) - Math.sin(f2) * Math.cos(d12)) / (Math.sin(d12) * Math.cos(f2)));
var Db = Math.acos(
(Math.sin(f1) - Math.sin(f2) * Math.cos(d12)) / (Math.sin(d12) * Math.cos(f2))
);
var D12 = Math.sin(l2 - l1) > 0 ? Da : 2 * Math.PI - Da;
var D21 = Math.sin(l2 - l1) > 0 ? 2 * Math.PI - Db : Db;
var a1 = (D13 - D12 + Math.PI) % (2 * Math.PI) - Math.PI;
var a2 = (D21 - D23 + Math.PI) % (2 * Math.PI) - Math.PI;
var a1 = ((D13 - D12 + Math.PI) % (2 * Math.PI)) - Math.PI;
var a2 = ((D21 - D23 + Math.PI) % (2 * Math.PI)) - Math.PI;
if (Math.sin(a1) == 0 && Math.sin(a2) == 0) return null; // infinite intersections
if (Math.sin(a1) * Math.sin(a2) < 0) return null; // ambiguous intersection
@ -183,13 +214,23 @@ class Ellipsoid {
// a2 = Math.abs(a2);
// ... Ed Williams takes abs of a1/a2, but seems to break calculation?
var a3 = Math.acos(-Math.cos(a1) * Math.cos(a2) + Math.sin(a1) * Math.sin(a2) * Math.cos(d12));
var d13 = Math.atan2(Math.sin(d12) * Math.sin(a1) * Math.sin(a2), Math.cos(a2) + Math.cos(a1) * Math.cos(a3));
var f3 = Math.asin(Math.sin(f1) * Math.cos(d13) + Math.cos(f1) * Math.sin(d13) * Math.cos(D13));
var dl13 = Math.atan2(Math.sin(D13) * Math.sin(d13) * Math.cos(f1), Math.cos(d13) - Math.sin(f1) * Math.sin(f3));
var a3 = Math.acos(
-Math.cos(a1) * Math.cos(a2) + Math.sin(a1) * Math.sin(a2) * Math.cos(d12)
);
var d13 = Math.atan2(
Math.sin(d12) * Math.sin(a1) * Math.sin(a2),
Math.cos(a2) + Math.cos(a1) * Math.cos(a3)
);
var f3 = Math.asin(
Math.sin(f1) * Math.cos(d13) + Math.cos(f1) * Math.sin(d13) * Math.cos(D13)
);
var dl13 = Math.atan2(
Math.sin(D13) * Math.sin(d13) * Math.cos(f1),
Math.cos(d13) - Math.sin(f1) * Math.sin(f3)
);
var l3 = l1 + dl13;
return new LonLat((l3 * math.DEGREES + 540) % 360 - 180, f3 * math.DEGREES);
return new LonLat(((l3 * math.DEGREES + 540) % 360) - 180, f3 * math.DEGREES);
}
/**
@ -226,7 +267,7 @@ class Ellipsoid {
* Gets cartesian ECEF from Wgs84 geodetic coordiantes.
* @public
* @param {LonLat} lonlat - Degrees geodetic coordiantes.
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
lonLatToCartesian(lonlat) {
var latrad = math.RADIANS * lonlat.lat,
@ -240,15 +281,16 @@ class Ellipsoid {
return new Vec3(
nc * Math.sin(lonrad),
(N * (1.0 - this._e2) + lonlat.height) * slt,
nc * Math.cos(lonrad));
nc * Math.cos(lonrad)
);
}
/**
* Gets cartesian ECEF from Wgs84 geodetic coordiantes.
* @public
* @param {LonLat} lonlat - Degrees geodetic coordiantes.
* @param {og.Vec3} res - Output result.
* @returns {og.Vec3} -
* @param {Vec3} res - Output result.
* @returns {Vec3} -
*/
lonLatToCartesianRes(lonlat, res) {
var latrad = math.RADIANS * lonlat.lat,
@ -272,7 +314,7 @@ class Ellipsoid {
* @param {Number} lon - Longitude.
* @param {Number} lat - Latitude.
* @param {Number} height - Height.
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
geodeticToCartesian(lon, lat, height = 0) {
var latrad = math.RADIANS * lat,
@ -286,17 +328,20 @@ class Ellipsoid {
return new Vec3(
nc * Math.sin(lonrad),
(N * (1 - this._e2) + height) * slt,
nc * Math.cos(lonrad));
nc * Math.cos(lonrad)
);
}
/**
* Gets Wgs84 geodetic coordiantes from cartesian ECEF.
* @public
* @param {og.Vec3} cartesian - Cartesian coordinates.
* @param {Vec3} cartesian - Cartesian coordinates.
* @returns {LonLat} -
*/
cartesianToLonLat(cartesian) {
var x = cartesian.z, y = cartesian.x, z = cartesian.y;
var x = cartesian.z,
y = cartesian.x,
z = cartesian.y;
var ecc2 = this._e2;
var ecc22 = this._e22;
var r2 = x * x + y * y;
@ -305,24 +350,37 @@ class Ellipsoid {
var f = 54.0 * this._b2 * z2;
var g = r2 + (1.0 - ecc2) * z2 + ecc2 * (this._a2 - this._b2);
var g2 = g * g;
var c = ecc22 * f * r2 / (g2 * g);
var s = Math.pow((1.0 + c + Math.sqrt(c * (c + 2.0))), 0.33333333333333333);
var p = f / (3.0 * Math.pow((1.0 + s + 1.0 / s), 2.0) * g2);
var c = (ecc22 * f * r2) / (g2 * g);
var s = Math.pow(1.0 + c + Math.sqrt(c * (c + 2.0)), 0.33333333333333333);
var p = f / (3.0 * Math.pow(1.0 + s + 1.0 / s, 2.0) * g2);
var q = Math.sqrt(1.0 + 2.0 * ecc22 * p);
var recc2r0 = r - ecc2 * (-(p * ecc2 * r) / 1 + q + Math.sqrt(0.5 * this._a2 * (1.0 + 1.0 / q) - p * (1.0 - ecc2) * z2 / (q * (1.0 + q)) - 0.5 * p * r2));
var recc2r0 =
r -
ecc2 *
(-(p * ecc2 * r) / 1 +
q +
Math.sqrt(
0.5 * this._a2 * (1.0 + 1.0 / q) -
(p * (1.0 - ecc2) * z2) / (q * (1.0 + q)) -
0.5 * p * r2
));
var recc2r02 = recc2r0 * recc2r0;
var v = Math.sqrt(recc2r02 + (1.0 - ecc2) * z2);
var z0 = this._b2 * z / (this._a * v);
var z0 = (this._b2 * z) / (this._a * v);
var lat = Math.atan((z + this._k2 * z0) / r) * math.DEGREES;
var lon = Math.atan2(y, x) * math.DEGREES;
return new LonLat(lon, lat, cartesian.length() - this.geodeticToCartesian(lon, lat).length());
return new LonLat(
lon,
lat,
cartesian.length() - this.geodeticToCartesian(lon, lat).length()
);
}
/**
* Gets ellipsoid surface normal.
* @public
* @param {og.Vec3} coord - Spatial coordiantes.
* @returns {og.Vec3} -
* @param {Vec3} coord - Spatial coordiantes.
* @returns {Vec3} -
*/
getSurfaceNormal3v(coord) {
var r2 = this._invRadii2;
@ -335,11 +393,22 @@ class Ellipsoid {
getBearingDestination(lonLat1, bearing, distance) {
bearing = bearing * math.RADIANS;
var nlon = (lonLat1.lon + 540) % 360 - 180;
var f1 = lonLat1.lat * math.RADIANS, l1 = nlon * math.RADIANS;
var nlon = ((lonLat1.lon + 540) % 360) - 180;
var f1 = lonLat1.lat * math.RADIANS,
l1 = nlon * math.RADIANS;
var dR = distance / this._a;
var f2 = Math.asin(Math.sin(f1) * Math.cos(dR) + Math.cos(f1) * Math.sin(dR) * Math.cos(bearing));
return new LonLat((l1 + Math.atan2(Math.sin(bearing) * Math.sin(dR) * Math.cos(f1), Math.cos(dR) - Math.sin(f1) * Math.sin(f2))) * math.DEGREES, f2 * math.DEGREES);
var f2 = Math.asin(
Math.sin(f1) * Math.cos(dR) + Math.cos(f1) * Math.sin(dR) * Math.cos(bearing)
);
return new LonLat(
(l1 +
Math.atan2(
Math.sin(bearing) * Math.sin(dR) * Math.cos(f1),
Math.cos(dR) - Math.sin(f1) * Math.sin(f2)
)) *
math.DEGREES,
f2 * math.DEGREES
);
}
/**
@ -351,8 +420,12 @@ class Ellipsoid {
getGreatCircleDistance(lonLat1, lonLat2) {
var dLat = (lonLat2.lat - lonLat1.lat) * math.RADIANS;
var dLon = (lonLat2.lon - lonLat1.lon) * math.RADIANS;
var a = Math.sin(dLat / 2.0) * Math.sin(dLat / 2.0) +
Math.sin(dLon / 2.0) * Math.sin(dLon / 2) * Math.cos(lonLat1.lat * math.RADIANS) * Math.cos(lonLat2.lat * math.RADIANS);
var a =
Math.sin(dLat / 2.0) * Math.sin(dLat / 2.0) +
Math.sin(dLon / 2.0) *
Math.sin(dLon / 2) *
Math.cos(lonLat1.lat * math.RADIANS) *
Math.cos(lonLat2.lat * math.RADIANS);
return this._a * 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a));
}
@ -373,28 +446,52 @@ class Ellipsoid {
sinAlpha1 = Math.sin(alpha1),
cosAlpha1 = Math.cos(alpha1),
tanU1 = (1 - f) * Math.tan(lat1 * math.RADIANS),
cosU1 = 1 / Math.sqrt((1 + tanU1 * tanU1)), sinU1 = tanU1 * cosU1,
cosU1 = 1 / Math.sqrt(1 + tanU1 * tanU1),
sinU1 = tanU1 * cosU1,
sigma1 = Math.atan2(tanU1, cosAlpha1),
sinAlpha = cosU1 * sinAlpha1,
cosSqAlpha = 1 - sinAlpha * sinAlpha,
uSq = cosSqAlpha * (a * a - b * b) / (b * b),
A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))),
B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))),
uSq = (cosSqAlpha * (a * a - b * b)) / (b * b),
A = 1 + (uSq / 16384) * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))),
B = (uSq / 1024) * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))),
sigma = s / (b * A),
sigmaP = 2 * Math.PI;
while (Math.abs(sigma - sigmaP) > 1e-12) {
var cos2SigmaM = Math.cos(2 * sigma1 + sigma),
sinSigma = Math.sin(sigma),
cosSigma = Math.cos(sigma),
deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
deltaSigma =
B *
sinSigma *
(cos2SigmaM +
(B / 4) *
(cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) -
(B / 6) *
cos2SigmaM *
(-3 + 4 * sinSigma * sinSigma) *
(-3 + 4 * cos2SigmaM * cos2SigmaM)));
sigmaP = sigma;
sigma = s / (b * A) + deltaSigma;
}
var tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1,
lat2 = Math.atan2(sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1, (1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp)),
lambda = Math.atan2(sinSigma * sinAlpha1, cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1),
C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha)),
L = lambda - (1 - C) * f * sinAlpha * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM))),
lat2 = Math.atan2(
sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1,
(1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp)
),
lambda = Math.atan2(
sinSigma * sinAlpha1,
cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1
),
C = (f / 16) * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha)),
L =
lambda -
(1 - C) *
f *
sinAlpha *
(sigma +
C *
sinSigma *
(cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM))),
revAz = Math.atan2(sinAlpha, -tmp); // final bearing
return new LonLat(lon1 + L * math.DEGREES, lat2 * math.DEGREES);
}
@ -403,12 +500,11 @@ class Ellipsoid {
* Returns ray vector hit ellipsoid coordinates.
* If the ray doesn't hit ellipsoid returns null.
* @public
* @param {og.Vec3} origin - Ray origin point.
* @param {og.Vec3} direction - Ray direction.
* @returns {og.Vec3} -
* @param {Vec3} origin - Ray origin point.
* @param {Vec3} direction - Ray direction.
* @returns {Vec3} -
*/
hitRay(origin, direction) {
var q = this._invRadii.mul(origin);
var w = this._invRadii.mul(direction);

View File

@ -2,12 +2,12 @@
* @module og/ellipsoid/wgs84
*/
'use strict';
"use strict";
import { Ellipsoid } from './Ellipsoid.js';
import { Ellipsoid } from "./Ellipsoid.js";
/**
* WGS84 ellipsoid object.
* @type {og.Ellipsoid}
* @type {Ellipsoid}
*/
export const wgs84 = new Ellipsoid(6378137.000, 6356752.3142);
export const wgs84 = new Ellipsoid(6378137.0, 6356752.3142);

View File

@ -2,20 +2,20 @@
* @module og/entity/BaseBillboard
*/
'use strict';
"use strict";
import * as utils from '../utils/shared.js';
import { Vec3 } from '../math/Vec3.js';
import * as utils from "../utils/shared.js";
import { Vec3 } from "../math/Vec3.js";
/**
* Base prototype for billboard and label classes.
* @class
* @param {Object} [options] - Options:
* @param {og.Vec3|Array.<number>} [options.position] - Billboard spatial position.
* @param {Vec3|Array.<number>} [options.position] - Billboard spatial position.
* @param {number} [options.rotation] - Screen angle rotaion.
* @param {og.Vec4|string|Array.<number>} [options.color] - Billboard color.
* @param {og.Vec3|Array.<number>} [options.alignedAxis] - Billboard aligned vector.
* @param {og.Vec3|Array.<number>} [options.offset] - Billboard center screen offset.
* @param {Vec4|string|Array.<number>} [options.color] - Billboard color.
* @param {Vec3|Array.<number>} [options.alignedAxis] - Billboard aligned vector.
* @param {Vec3|Array.<number>} [options.offset] - Billboard center screen offset.
* @param {boolean} [options.visibility] - Visibility.
*/
class BaseBillboard {
@ -33,7 +33,7 @@ class BaseBillboard {
/**
* Billboard center cartesian position.
* @protected
* @type {og.Vec3}
* @type {Vec3}
*/
this._position = utils.createVector3(options.position);
@ -53,21 +53,21 @@ class BaseBillboard {
/**
* RGBA color.
* @protected
* @type {og.Vec4}
* @type {Vec4}
*/
this._color = utils.createColorRGBA(options.color);
/**
* Cartesian aligned axis vector.
* @protected
* @type {og.Vec3}
* @type {Vec3}
*/
this._alignedAxis = utils.createVector3(options.alignedAxis);
/**
* Billboard center screen space offset. Where x,y - screen space offset and z - depth offset.
* @protected
* @type {og.math.Vecto3}
* @type {math.Vecto3}
*/
this._offset = utils.createVector3(options.offset);
@ -81,14 +81,14 @@ class BaseBillboard {
/**
* Entity instance that holds this billboard.
* @protected
* @type {og.Entity}
* @type {Entity}
*/
this._entity = null;
/**
* Handler that stores and renders this billboard object.
* @protected
* @type {og.BillboardHandler}
* @type {BillboardHandler}
*/
this._handler = null;
@ -122,27 +122,29 @@ class BaseBillboard {
this._position.x = x;
this._position.y = y;
this._position.z = z;
Vec3.doubleToTwoFloats(position, this._positionHigh, this._positionLow);
this._handler && this._handler.setPositionArr(this._handlerIndex, this._positionHigh, this._positionLow);
Vec3.doubleToTwoFloats(this._position, this._positionHigh, this._positionLow);
this._handler &&
this._handler.setPositionArr(this._handlerIndex, this._positionHigh, this._positionLow);
}
/**
* Sets billboard position.
* @public
* @param {og.Vec3} position - Cartesian coordinates.
* @param {Vec3} position - Cartesian coordinates.
*/
setPosition3v(position) {
this._position.x = position.x;
this._position.y = position.y;
this._position.z = position.z;
Vec3.doubleToTwoFloats(position, this._positionHigh, this._positionLow);
this._handler && this._handler.setPositionArr(this._handlerIndex, this._positionHigh, this._positionLow);
this._handler &&
this._handler.setPositionArr(this._handlerIndex, this._positionHigh, this._positionLow);
}
/**
* Returns billboard position.
* @public
* @returns {og.Vec3}
* @returns {Vec3}
*/
getPosition() {
return this._position;
@ -158,26 +160,26 @@ class BaseBillboard {
setOffset(x, y, z) {
this._offset.x = x;
this._offset.y = y;
(z != undefined) && (this._offset.z = z);
z != undefined && (this._offset.z = z);
this._handler && this._handler.setOffsetArr(this._handlerIndex, this._offset);
}
/**
* Sets screen space offset.
* @public
* @param {og.Vec2} offset - Offset size.
* @param {Vec2} offset - Offset size.
*/
setOffset3v(offset) {
this._offset.x = offset.x;
this._offset.y = offset.y;
(offset.z != undefined) && (this._offset.z = offset.z);
offset.z != undefined && (this._offset.z = offset.z);
this._handler && this._handler.setOffsetArr(this._handlerIndex, offset);
}
/**
* Returns billboard screen space offset size.
* @public
* @returns {og.Vec3}
* @returns {Vec3}
*/
getOffset() {
return this._offset;
@ -224,20 +226,20 @@ class BaseBillboard {
this._color.x = r;
this._color.y = g;
this._color.z = b;
(a != undefined) && (this._color.w = a);
a != undefined && (this._color.w = a);
this._handler && this._handler.setRgbaArr(this._handlerIndex, this._color);
}
/**
* Sets RGBA color. Each channel from 0.0 to 1.0.
* @public
* @param {og.Vec4} color - RGBA vector.
* @param {Vec4} color - RGBA vector.
*/
setColor4v(color) {
this._color.x = color.x;
this._color.y = color.y;
this._color.z = color.z;
(color.w != undefined) && (this._color.w = color.w);
color.w != undefined && (this._color.w = color.w);
this._handler && this._handler.setRgbaArr(this._handlerIndex, color);
}
@ -253,7 +255,7 @@ class BaseBillboard {
/**
* Returns RGBA color.
* @public
* @returns {og.Vec4}
* @returns {Vec4}
*/
getColor() {
return this._color;
@ -295,7 +297,7 @@ class BaseBillboard {
/**
* Sets billboard aligned vector.
* @public
* @param {og.math.Vecto3} alignedAxis - Vector to align.
* @param {math.Vecto3} alignedAxis - Vector to align.
*/
setAlignedAxis3v(alignedAxis) {
this._alignedAxis.x = alignedAxis.x;
@ -307,7 +309,7 @@ class BaseBillboard {
/**
* Returns aligned vector.
* @public
* @returns {og.Vec3}
* @returns {Vec3}
*/
getAlignedAxis() {
return this._alignedAxis;
@ -325,7 +327,7 @@ class BaseBillboard {
/**
* Sets billboard picking color.
* @public
* @param {og.Vec3} color - Picking color.
* @param {Vec3} color - Picking color.
*/
setPickingColor3v(color) {
this._handler && this._handler.setPickingColorArr(this._handlerIndex, color);

View File

@ -2,20 +2,20 @@
* @module og/entity/Billboard
*/
'use strict';
"use strict";
import { BaseBillboard } from './BaseBillboard.js';
import { BaseBillboard } from "./BaseBillboard.js";
/**
* Represents basic quad billboard image.
* @class
* @extends {og.BaseBillboard}
* @extends {BaseBillboard}
* @param {Object} [options] - Options:
* @param {og.Vec3|Array.<number>} [options.position] - Billboard spatial position.
* @param {Vec3|Array.<number>} [options.position] - Billboard spatial position.
* @param {number} [options.rotation] - Screen angle rotaion.
* @param {og.Vec4|string|Array.<number>} [options.color] - Billboard color.
* @param {og.Vec3|Array.<number>} [options.alignedAxis] - Billboard aligned vector.
* @param {og.Vec3|Array.<number>} [options.offset] - Billboard center screen offset.
* @param {Vec4|string|Array.<number>} [options.color] - Billboard color.
* @param {Vec3|Array.<number>} [options.alignedAxis] - Billboard aligned vector.
* @param {Vec3|Array.<number>} [options.offset] - Billboard center screen offset.
* @param {boolean} [options.visibility] - Visibility.
* @param {string} [options.src] - Billboard image url source.
* @param {Image} [options.image] - Billboard image object.
@ -76,7 +76,10 @@ class Billboard extends BaseBillboard {
ta.loadImage(src, function (img) {
if (ta.nodes[img.__nodeIndex]) {
that._image = img;
bh.setTexCoordArr(that._handlerIndex, ta.nodes[that._image.__nodeIndex].texCoords);
bh.setTexCoordArr(
that._handlerIndex,
ta.nodes[that._image.__nodeIndex].texCoords
);
} else {
ta.addImage(img);
ta.createTexture();
@ -106,7 +109,8 @@ class Billboard extends BaseBillboard {
setSize(width, height) {
this._width = width;
this._height = height;
this._handler && this._handler.setSizeArr(this._handlerIndex, width * this._scale, height * this._scale);
this._handler &&
this._handler.setSizeArr(this._handlerIndex, width * this._scale, height * this._scale);
}
/**

View File

@ -2,10 +2,10 @@
* @module og/entity/BillboardHandler
*/
'use strict';
"use strict";
import * as shaders from '../shaders/billboard.js';
import { concatTypedArrays, spliceTypedArray } from '../utils/shared.js';
import * as shaders from "../shaders/billboard.js";
import { concatTypedArrays, spliceTypedArray } from "../utils/shared.js";
const PICKINGCOLOR_BUFFER = 0;
const POSITION_BUFFER = 1;
@ -23,8 +23,11 @@ const ALIGNEDAXIS_BUFFER = 8;
*
*/
class BillboardHandler {
/**
*
* @param {*} entityCollection
*/
constructor(entityCollection) {
/**
* Picking rendering option.
* @public
@ -96,7 +99,6 @@ class BillboardHandler {
initProgram() {
if (this._renderer.handler) {
if (!this._renderer.handler.programs.billboard) {
this._renderer.handler.addProgram(shaders.billboard_screen());
}
@ -131,7 +133,6 @@ class BillboardHandler {
}
clear() {
this._texCoordArr = null;
this._vertexArr = null;
this._positionHighArr = null;
@ -211,36 +212,180 @@ class BillboardHandler {
_addBillboardToArrays(billboard) {
if (billboard._visibility) {
this._vertexArr = concatTypedArrays(this._vertexArr, [-0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5]);
this._vertexArr = concatTypedArrays(
this._vertexArr,
[-0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5]
);
} else {
this._vertexArr = concatTypedArrays(this._vertexArr, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
this._vertexArr = concatTypedArrays(
this._vertexArr,
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
);
}
this._texCoordArr = concatTypedArrays(this._texCoordArr, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
this._texCoordArr = concatTypedArrays(
this._texCoordArr,
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
);
var x = billboard._positionHigh.x, y = billboard._positionHigh.y, z = billboard._positionHigh.z, w;
this._positionHighArr = concatTypedArrays(this._positionHighArr, [x, y, z, x, y, z, x, y, z, x, y, z, x, y, z, x, y, z]);
var x = billboard._positionHigh.x,
y = billboard._positionHigh.y,
z = billboard._positionHigh.z,
w;
this._positionHighArr = concatTypedArrays(this._positionHighArr, [
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z
]);
x = billboard._positionLow.x; y = billboard._positionLow.y; z = billboard._positionLow.z;
this._positionLowArr = concatTypedArrays(this._positionLowArr, [x, y, z, x, y, z, x, y, z, x, y, z, x, y, z, x, y, z]);
x = billboard._positionLow.x;
y = billboard._positionLow.y;
z = billboard._positionLow.z;
this._positionLowArr = concatTypedArrays(this._positionLowArr, [
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z
]);
x = billboard._width; y = billboard._height;
x = billboard._width;
y = billboard._height;
this._sizeArr = concatTypedArrays(this._sizeArr, [x, y, x, y, x, y, x, y, x, y, x, y]);
x = billboard._offset.x; y = billboard._offset.y; z = billboard._offset.z;
this._offsetArr = concatTypedArrays(this._offsetArr, [x, y, z, x, y, z, x, y, z, x, y, z, x, y, z, x, y, z]);
x = billboard._offset.x;
y = billboard._offset.y;
z = billboard._offset.z;
this._offsetArr = concatTypedArrays(this._offsetArr, [
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z
]);
x = billboard._color.x; y = billboard._color.y; z = billboard._color.z; w = billboard._color.w;
this._rgbaArr = concatTypedArrays(this._rgbaArr, [x, y, z, w, x, y, z, w, x, y, z, w, x, y, z, w, x, y, z, w, x, y, z, w]);
x = billboard._color.x;
y = billboard._color.y;
z = billboard._color.z;
w = billboard._color.w;
this._rgbaArr = concatTypedArrays(this._rgbaArr, [
x,
y,
z,
w,
x,
y,
z,
w,
x,
y,
z,
w,
x,
y,
z,
w,
x,
y,
z,
w,
x,
y,
z,
w
]);
x = billboard._rotation;
this._rotationArr = concatTypedArrays(this._rotationArr, [x, x, x, x, x, x]);
x = billboard._alignedAxis.x; y = billboard._alignedAxis.y; z = billboard._alignedAxis.z;
this._alignedAxisArr = concatTypedArrays(this._alignedAxisArr, [x, y, z, x, y, z, x, y, z, x, y, z, x, y, z, x, y, z]);
x = billboard._alignedAxis.x;
y = billboard._alignedAxis.y;
z = billboard._alignedAxis.z;
this._alignedAxisArr = concatTypedArrays(this._alignedAxisArr, [
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z
]);
x = billboard._entity._pickingColor.x / 255; y = billboard._entity._pickingColor.y / 255; z = billboard._entity._pickingColor.z / 255;
this._pickingColorArr = concatTypedArrays(this._pickingColorArr, [x, y, z, x, y, z, x, y, z, x, y, z, x, y, z, x, y, z]);
x = billboard._entity._pickingColor.x / 255;
y = billboard._entity._pickingColor.y / 255;
z = billboard._entity._pickingColor.z / 255;
this._pickingColorArr = concatTypedArrays(this._pickingColorArr, [
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z,
x,
y,
z
]);
}
_displayPASS() {
@ -268,19 +413,43 @@ class BillboardHandler {
gl.uniform1f(shu.uOpacity, ec._fadingOpacity);
gl.uniform2fv(shu.uFloatParams, [ec.renderNode._planetRadius2 || 0, r.activeCamera._tanViewAngle_hradOneByHeight]);
gl.uniform2fv(shu.uFloatParams, [
ec.renderNode._planetRadius2 || 0,
r.activeCamera._tanViewAngle_hradOneByHeight
]);
gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordBuffer);
gl.vertexAttribPointer(sha.a_texCoord, this._texCoordBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.a_texCoord,
this._texCoordBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
gl.vertexAttribPointer(sha.a_vertices, this._vertexBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, this._positionHighBuffer);
gl.vertexAttribPointer(sha.a_positionsHigh, this._positionHighBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.a_positionsHigh,
this._positionHighBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.bindBuffer(gl.ARRAY_BUFFER, this._positionLowBuffer);
gl.vertexAttribPointer(sha.a_positionsLow, this._positionLowBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.a_positionsLow,
this._positionLowBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.bindBuffer(gl.ARRAY_BUFFER, this._rgbaBuffer);
gl.vertexAttribPointer(sha.a_rgba, this._rgbaBuffer.itemSize, gl.FLOAT, false, 0, 0);
@ -292,10 +461,24 @@ class BillboardHandler {
gl.vertexAttribPointer(sha.a_offset, this._offsetBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, this._rotationBuffer);
gl.vertexAttribPointer(sha.a_rotation, this._rotationBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.a_rotation,
this._rotationBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.bindBuffer(gl.ARRAY_BUFFER, this._alignedAxisBuffer);
gl.vertexAttribPointer(sha.a_alignedAxis, this._alignedAxisBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.a_alignedAxis,
this._alignedAxisBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.drawArrays(gl.TRIANGLES, 0, this._vertexBuffer.numItems);
}
@ -325,19 +508,43 @@ class BillboardHandler {
gl.uniform1f(shu.pickingScale, ec.pickingScale);
gl.uniform2fv(shu.uFloatParams, [ec.renderNode._planetRadius2 || 0, r.activeCamera._tanViewAngle_hradOneByHeight]);
gl.uniform2fv(shu.uFloatParams, [
ec.renderNode._planetRadius2 || 0,
r.activeCamera._tanViewAngle_hradOneByHeight
]);
gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
gl.vertexAttribPointer(sha.a_vertices, this._vertexBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, this._positionHighBuffer);
gl.vertexAttribPointer(sha.a_positionsHigh, this._positionHighBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.a_positionsHigh,
this._positionHighBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.bindBuffer(gl.ARRAY_BUFFER, this._positionLowBuffer);
gl.vertexAttribPointer(sha.a_positionsLow, this._positionLowBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.a_positionsLow,
this._positionLowBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.bindBuffer(gl.ARRAY_BUFFER, this._pickingColorBuffer);
gl.vertexAttribPointer(sha.a_pickingColor, this._pickingColorBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.a_pickingColor,
this._pickingColorBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.bindBuffer(gl.ARRAY_BUFFER, this._sizeBuffer);
gl.vertexAttribPointer(sha.a_size, this._sizeBuffer.itemSize, gl.FLOAT, false, 0, 0);
@ -346,10 +553,24 @@ class BillboardHandler {
gl.vertexAttribPointer(sha.a_offset, this._offsetBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, this._rotationBuffer);
gl.vertexAttribPointer(sha.a_rotation, this._rotationBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.a_rotation,
this._rotationBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.bindBuffer(gl.ARRAY_BUFFER, this._alignedAxisBuffer);
gl.vertexAttribPointer(sha.a_alignedAxis, this._alignedAxisBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.a_alignedAxis,
this._alignedAxisBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.drawArrays(gl.TRIANGLES, 0, this._vertexBuffer.numItems);
}
@ -411,11 +632,13 @@ class BillboardHandler {
}
setPositionArr(index, positionHigh, positionLow) {
var i = index * 18;
// High
var a = this._positionHighArr, x = positionHigh.x, y = positionHigh.y, z = positionHigh.z;
var a = this._positionHighArr,
x = positionHigh.x,
y = positionHigh.y,
z = positionHigh.z;
a[i] = x;
a[i + 1] = y;
@ -442,7 +665,10 @@ class BillboardHandler {
a[i + 17] = z;
// Low
a = this._positionLowArr; x = positionLow.x; y = positionLow.y; z = positionLow.z;
a = this._positionLowArr;
x = positionLow.x;
y = positionLow.y;
z = positionLow.z;
a[i] = x;
a[i + 1] = y;
@ -472,9 +698,11 @@ class BillboardHandler {
}
setPickingColorArr(index, color) {
var i = index * 18;
var a = this._pickingColorArr, x = color.x / 255, y = color.y / 255, z = color.z / 255;
var a = this._pickingColorArr,
x = color.x / 255,
y = color.y / 255,
z = color.z / 255;
a[i] = x;
a[i + 1] = y;
@ -504,9 +732,10 @@ class BillboardHandler {
}
setSizeArr(index, width, height) {
var i = index * 12;
var a = this._sizeArr, x = width, y = height;
var a = this._sizeArr,
x = width,
y = height;
a[i] = x;
a[i + 1] = y;
@ -530,9 +759,11 @@ class BillboardHandler {
}
setOffsetArr(index, offset) {
var i = index * 18;
var a = this._offsetArr, x = offset.x, y = offset.y, z = offset.z;
var a = this._offsetArr,
x = offset.x,
y = offset.y,
z = offset.z;
a[i] = x;
a[i + 1] = y;
@ -562,9 +793,12 @@ class BillboardHandler {
}
setRgbaArr(index, rgba) {
var i = index * 24;
var a = this._rgbaArr, x = rgba.x, y = rgba.y, z = rgba.z, w = rgba.w;
var a = this._rgbaArr,
x = rgba.x,
y = rgba.y,
z = rgba.z,
w = rgba.w;
a[i] = x;
a[i + 1] = y;
@ -600,7 +834,6 @@ class BillboardHandler {
}
setRotationArr(index, rotation) {
var i = index * 6;
var a = this._rotationArr;
@ -615,7 +848,6 @@ class BillboardHandler {
}
setTexCoordArr(index, tcoordArr) {
var i = index * 12;
var a = this._texCoordArr;
@ -651,7 +883,6 @@ class BillboardHandler {
}
setVertexArr(index, vertexArr) {
var i = index * 12;
var a = this._vertexArr;
@ -675,9 +906,11 @@ class BillboardHandler {
}
setAlignedAxisArr(index, alignedAxis) {
var i = index * 18;
var a = this._alignedAxisArr, x = alignedAxis.x, y = alignedAxis.y, z = alignedAxis.z;
var a = this._alignedAxisArr,
x = alignedAxis.x,
y = alignedAxis.y,
z = alignedAxis.z;
a[i] = x;
a[i + 1] = y;
@ -759,19 +992,31 @@ class BillboardHandler {
createTexCoordBuffer() {
var h = this._renderer.handler;
h.gl.deleteBuffer(this._texCoordBuffer);
this._texCoordBuffer = h.createArrayBuffer(this._texCoordArr, 2, this._texCoordArr.length / 2);
this._texCoordBuffer = h.createArrayBuffer(
this._texCoordArr,
2,
this._texCoordArr.length / 2
);
}
createAlignedAxisBuffer() {
var h = this._renderer.handler;
h.gl.deleteBuffer(this._alignedAxisBuffer);
this._alignedAxisBuffer = h.createArrayBuffer(this._alignedAxisArr, 3, this._alignedAxisArr.length / 3);
this._alignedAxisBuffer = h.createArrayBuffer(
this._alignedAxisArr,
3,
this._alignedAxisArr.length / 3
);
}
createPickingColorBuffer() {
var h = this._renderer.handler;
h.gl.deleteBuffer(this._pickingColorBuffer);
this._pickingColorBuffer = h.createArrayBuffer(this._pickingColorArr, 3, this._pickingColorArr.length / 3);
this._pickingColorBuffer = h.createArrayBuffer(
this._pickingColorArr,
3,
this._pickingColorArr.length / 3
);
}
refreshTexCoordsArr() {

View File

@ -2,21 +2,21 @@
* @module og/entity/Entity
*/
'use strict';
"use strict";
import * as mercator from '../mercator.js';
import * as utils from '../utils/shared.js';
import { Billboard } from './Billboard.js';
import { Strip } from './Strip.js';
import { Extent } from '../Extent.js';
import { Geometry } from './Geometry.js';
import { Label } from './Label.js';
import { LonLat } from '../LonLat.js';
import { Polyline } from './Polyline.js';
import { Ray } from './Ray.js';
import { PointCloud } from './PointCloud.js';
import { Sphere } from '../shapes/Sphere.js';
import { Vec3 } from '../math/Vec3.js';
import * as mercator from "../mercator.js";
import * as utils from "../utils/shared.js";
import { Billboard } from "./Billboard.js";
import { Strip } from "./Strip.js";
import { Extent } from "../Extent.js";
import { Geometry } from "./Geometry.js";
import { Label } from "./Label.js";
import { LonLat } from "../LonLat.js";
import { Polyline } from "./Polyline.js";
import { Ray } from "./Ray.js";
import { PointCloud } from "./PointCloud.js";
import { Sphere } from "../shapes/Sphere.js";
import { Vec3 } from "../math/Vec3.js";
import { GeoObject } from "./GeoObject.js";
/**
@ -26,7 +26,7 @@ import { GeoObject } from "./GeoObject.js";
* @class
* @param {Object} [options] - Entity options:
* @param {string} [options.name] - A human readable name to display to users. It does not have to be unique.
* @param {og.Vec3|Array.<number>} [options.cartesian] - Spatial entities like billboard, label, sphere etc. cartesian position.
* @param {Vec3|Array.<number>} [options.cartesian] - Spatial entities like billboard, label, sphere etc. cartesian position.
* @param {LonLat} [options.lonlat] - Geodetic coordiantes for an entities like billboard, label, sphere etc.
* @param {boolean} [options.aground] - True for entities that have to be placed on the relief.
* @param {boolean} [options.visibility] - Entity visibility.
@ -42,7 +42,6 @@ import { GeoObject } from "./GeoObject.js";
*/
class Entity {
constructor(options) {
options = options || {};
options.properties = options.properties || {};
@ -71,21 +70,21 @@ class Entity {
/**
* Children entities.
* @public
* @type {Array.<og.Entity>}
* @type {Array.<Entity>}
*/
this.childrenNodes = [];
/**
* Parent entity.
* @public
* @type {og.Entity}
* @type {Entity}
*/
this.parent = null;
/**
* Entity cartesian position.
* @protected
* @type {og.Vec3}
* @type {Vec3}
*/
this._cartesian = utils.createVector3(options.cartesian);
@ -120,7 +119,7 @@ class Entity {
/**
* Entity collection that this entity belongs to.
* @protected
* @type {og.EntityCollection}
* @type {EntityCollection}
*/
this._entityCollection = null;
@ -134,7 +133,7 @@ class Entity {
/**
* Assigned vector layer pointer.
* @protected
* @type {og.layer.Vector}
* @type {layer.Vector}
*/
this._layer = null;
@ -148,7 +147,7 @@ class Entity {
/**
* Picking color.
* @protected
* @type {og.Vec3}
* @type {Vec3}
*/
this._pickingColor = new Vec3(0, 0, 0);
@ -168,65 +167,65 @@ class Entity {
/**
* Billboard entity.
* @public
* @type {og.Billboard}
* @type {Billboard}
*/
this.billboard = this._createOptionFeature('billboard', options.billboard);
this.billboard = this._createOptionFeature("billboard", options.billboard);
/**
* Text label entity.
* @public
* @type {og.Label}
* @type {Label}
*/
this.label = this._createOptionFeature('label', options.label);
this.label = this._createOptionFeature("label", options.label);
/**
* Shape entity.
* @public
* @type {og.shape.BaseShape}
* @type {shape.BaseShape}
*/
this.shape = this._createOptionFeature('sphere', options.sphere || options.box);
this.shape = this._createOptionFeature("sphere", options.sphere || options.box);
/**
* Polyline entity.
* @public
* @type {og.Polyline}
* @type {Polyline}
*/
this.polyline = this._createOptionFeature('polyline', options.polyline);
this.polyline = this._createOptionFeature("polyline", options.polyline);
/**
* Ray entity.
* @public
* @type {og.ray}
* @type {ray}
*/
this.ray = this._createOptionFeature('ray', options.ray);
this.ray = this._createOptionFeature("ray", options.ray);
/**
* PointCloud entity.
* @public
* @type {og.PointCloud}
* @type {PointCloud}
*/
this.pointCloud = this._createOptionFeature('pointCloud', options.pointCloud);
this.pointCloud = this._createOptionFeature("pointCloud", options.pointCloud);
/**
* Geometry entity(available for vector layer only).
* @public
* @type {og.Geometry}
* @type {Geometry}
*/
this.geometry = this._createOptionFeature('geometry', options.geometry);
this.geometry = this._createOptionFeature("geometry", options.geometry);
/**
* Geo object entity
* @public
* @type {og.Geometry}
*/
this.geoObject = this._createOptionFeature('geoObject', options.geoObject);
this.geoObject = this._createOptionFeature("geoObject", options.geoObject);
/**
* Strip entity.
* @public
* @type {og.Strip}
* @type {Strip}
*/
this.strip = this._createOptionFeature('strip', options.strip);
this.strip = this._createOptionFeature("strip", options.strip);
}
static get _staticCounter() {
@ -259,9 +258,9 @@ class Entity {
/**
* Adds current entity into the specified entity collection.
* @public
* @param {og.EntityCollection|og.layer.Vector} collection - Specified entity collection or vector layer.
* @param {EntityCollection|Vector} collection - Specified entity collection or vector layer.
* @param {Boolean} [rightNow=false] - Entity insertion option for vector layer.
* @returns {og.Entity} - This object.
* @returns {Entity} - This object.
*/
addTo(collection, rightNow) {
collection.add(this, rightNow);
@ -323,7 +322,7 @@ class Entity {
/**
* Sets entity cartesian position.
* @public
* @param {og.Vec3} cartesian - Cartesian position in 3d space.
* @param {Vec3} cartesian - Cartesian position in 3d space.
*/
setCartesian3v(cartesian) {
this.setCartesian(cartesian.x, cartesian.y, cartesian.z);
@ -337,7 +336,6 @@ class Entity {
* @param {number} z - 3d space Z - position.
*/
setCartesian(x, y, z) {
var p = this._cartesian;
p.x = x;
@ -363,7 +361,6 @@ class Entity {
var ec = this._entityCollection;
if (ec && ec.renderNode && ec.renderNode.ellipsoid) {
this._lonlat = ec.renderNode.ellipsoid.cartesianToLonLat(p);
if (Math.abs(this._lonlat.lat) < mercator.MAX_LAT) {
@ -379,11 +376,10 @@ class Entity {
/**
* Sets entity cartesian position without event dispatching.
* @protected
* @param {og.Vec3} cartesian - Cartesian position in 3d space.
* @param {Vec3} cartesian - Cartesian position in 3d space.
* @param {boolean} skipLonLat - skip geodetic calculation.
*/
_setCartesian3vSilent(cartesian, skipLonLat) {
var p = this._cartesian;
p.x = cartesian.x;
@ -403,13 +399,12 @@ class Entity {
this.shape && this.shape.setPosition3v(p);
for (var i = 0; i < this.childrenNodes.length; i++) {
this.childrenNodes[i].setCartesian(x, y, z);
this.childrenNodes[i].setCartesian(p.x, p.y, p.z);
}
var ec = this._entityCollection;
if (!skipLonLat && ec && ec.renderNode && ec.renderNode.ellipsoid) {
this._lonlat = ec.renderNode.ellipsoid.cartesianToLonLat(p);
if (Math.abs(this._lonlat.lat) < mercator.MAX_LAT) {
@ -443,7 +438,6 @@ class Entity {
var ec = this._entityCollection;
if (ec && ec.renderNode && ec.renderNode.ellipsoid) {
if (Math.abs(lonlat.lat) < mercator.MAX_LAT) {
this._lonlatMerc = lonlat.forwardMercator();
} else {
@ -476,7 +470,7 @@ class Entity {
/**
* Returns carteain position.
* @public
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
getCartesian() {
return this._cartesian.clone();
@ -485,8 +479,8 @@ class Entity {
/**
* Sets entity billboard.
* @public
* @param {og.Billboard} billboard - Billboard object.
* @returns {og.Billboard} -
* @param {Billboard} billboard - Billboard object.
* @returns {Billboard} -
*/
setBillboard(billboard) {
if (this.billboard) {
@ -503,8 +497,8 @@ class Entity {
/**
* Sets entity label.
* @public
* @param {og.Label} label - Text label.
* @returns {og.Label} -
* @param {Label} label - Text label.
* @returns {Label} -
*/
setLabel(label) {
if (this.label) {
@ -521,8 +515,8 @@ class Entity {
/**
* Sets entity ray.
* @public
* @param {og.Ray} ray - Ray object.
* @returns {og.Ray} -
* @param {Ray} ray - Ray object.
* @returns {Ray} -
*/
setRay(ray) {
if (this.ray) {
@ -538,8 +532,8 @@ class Entity {
/**
* Sets entity shape.
* @public
* @param {og.BaseShape} shape - Shape object.
* @returns {og.Polyline} -
* @param {BaseShape} shape - Shape object.
* @returns {Polyline} -
*/
setShape(shape) {
if (this.shape) {
@ -556,8 +550,8 @@ class Entity {
/**
* Sets entity polyline.
* @public
* @param {og.Polyline} polyline - Polyline object.
* @returns {og.Polyline} -
* @param {Polyline} polyline - Polyline object.
* @returns {Polyline} -
*/
setPolyline(polyline) {
if (this.polyline) {
@ -573,8 +567,8 @@ class Entity {
/**
* Sets entity pointCloud.
* @public
* @param {og.PointCloud} pointCloud - PointCloud object.
* @returns {og.PointCloud} -
* @param {PointCloud} pointCloud - PointCloud object.
* @returns {PointCloud} -
*/
setPointCloud(pointCloud) {
if (this.pointCloud) {
@ -590,8 +584,8 @@ class Entity {
/**
* Sets entity geometry.
* @public
* @param {og.Geometry} geometry - Geometry object.
* @returns {og.Geometry} -
* @param {Geometry} geometry - Geometry object.
* @returns {Geometry} -
*/
setGeometry(geometry) {
if (this.geometry) {
@ -607,8 +601,8 @@ class Entity {
/**
* Sets entity geoObject.
* @public
* @param {og.GeoObject} geoObject - GeoObject.
* @returns {og.GeoObject} -
* @param {GeoObject} geoObject - GeoObject.
* @returns {GeoObject} -
*/
setGeoObject(geoObject) {
if (this.geoObject) {
@ -620,14 +614,13 @@ class Entity {
this.geoObject.setVisibility(this._visibility);
this._entityCollection && this._entityCollection._geoObjectHandler.add(geoObject);
return geoObject;
}
/**
* Sets entity strip.
* @public
* @param {og.Strip} strip - Strip object.
* @returns {og.Strip} -
* @param {Strip} strip - Strip object.
* @returns {Strip} -
*/
setStrip(strip) {
if (this.strip) {
@ -650,12 +643,13 @@ class Entity {
} else if (this._entityCollection) {
return this._entityCollection.events;
}
return null;
}
/**
* Append child entity.
* @public
* @param {og.Entity} entity - Child entity.
* @param {Entity} entity - Child entity.
*/
appendChild(entity) {
entity._entityCollection = this._entityCollection;
@ -670,7 +664,6 @@ class Entity {
* @public
*/
setPickingColor() {
var c = this._pickingColor;
// billboard
@ -700,7 +693,7 @@ class Entity {
/**
* Return geodethic extent.
* @returns {og.Extent} -
* @returns {Extent} -
*/
getExtent() {
var res;

View File

@ -20,7 +20,7 @@ import { GeoObjectHandler } from "./GeoObjectHandler.js";
* Entity collection provide handlers for an each type of entity like billboard, label or 3ds object.
* @constructor
* @param {Object} [options] - Entity options:
* @param {Array.<og.Entity>} [options.entities] - Entities array.
* @param {Array.<Entity>} [options.entities] - Entities array.
* @param {boolean} [options.visibility=true] - Entity visibility.
* @param {Array.<number>} [options.scaleByDistance] - Entity scale by distance parameters. (exactly 3 entries)
* First index - near distance to the entity, after entity becomes full scale.
@ -85,7 +85,7 @@ class EntityCollection {
/**
* Render node context.
* @public
* @type {og.scene.RenderNode}
* @type {RenderNode}
*/
this.renderNode = null;
@ -115,49 +115,49 @@ class EntityCollection {
/**
* Billboards handler
* @public
* @type {og.BillboardHandler}
* @type {BillboardHandler}
*/
this.billboardHandler = new BillboardHandler(this);
/**
* Labels handler
* @public
* @type {og.LabelHandler}
* @type {LabelHandler}
*/
this.labelHandler = new LabelHandler(this, options.labelMaxLetters);
/**
* Shape handler
* @public
* @type {og.ShapeHandler}
* @type {ShapeHandler}
*/
this.shapeHandler = new ShapeHandler(this);
/**
* Polyline handler
* @public
* @type {og.PolylineHandler}
* @type {PolylineHandler}
*/
this.polylineHandler = new PolylineHandler(this);
/**
* Ray handler
* @public
* @type {og.RayHandler}
* @type {RayHandler}
*/
this.rayHandler = new RayHandler(this);
/**
* PointCloud handler
* @public
* @type {og.PointCloudHandler}
* @type {PointCloudHandler}
*/
this.pointCloudHandler = new PointCloudHandler(this);
/**
* Strip handler
* @public
* @type {og.StripHandler}
* @type {StripHandler}
*/
this.stripHandler = new StripHandler(this);
@ -175,7 +175,7 @@ class EntityCollection {
/**
* Entities array.
* @protected
* @type {Array.<og.Entity>}
* @type {Array.<Entity>}
*/
this._entities = [];
@ -207,7 +207,7 @@ class EntityCollection {
/**
* Entity collection events handler.
* @public
* @type {og.Events}
* @type {Events}
*/
this.events = new Events(EVENT_NAMES, this);
@ -340,8 +340,8 @@ class EntityCollection {
/**
* Adds entity to the collection and returns collection.
* @public
* @param {og.Entity} entity - Entity.
* @returns {og.EntityCollection} -
* @param {Entity} entity - Entity.
* @returns {EntityCollection} -
*/
add(entity) {
if (!entity._entityCollection) {
@ -364,8 +364,8 @@ class EntityCollection {
/**
* Adds entities array to the collection and returns collection.
* @public
* @param {Array.<og.Entity>} entities - Entities array.
* @returns {og.EntityCollection} -
* @param {Array.<Entity>} entities - Entities array.
* @returns {EntityCollection} -
*/
addEntities(entities) {
for (let i = 0, len = entities.length; i < len; i++) {
@ -377,7 +377,7 @@ class EntityCollection {
/**
* Returns true if the entity belongs this collection, otherwise returns false.
* @public
* @param {og.Entity} entity - Entity.
* @param {Entity} entity - Entity.
* @returns {boolean} -
*/
belongs(entity) {
@ -423,7 +423,7 @@ class EntityCollection {
/**
* Removes entity from this collection.
* @public
* @param {og.Entity} entity - Entity to remove.
* @param {Entity} entity - Entity to remove.
*/
removeEntity(entity) {
this._entities.splice(entity._entityCollectionIndex, 1);
@ -486,9 +486,9 @@ class EntityCollection {
/**
* Adds this collection to render node.
* @public
* @param {og.scene.RenderNode} renderNode - Render node.
* @param {RenderNode} renderNode - Render node.
* @param {boolean} [isHidden] - Uses in vector layers that render in planet render specific function.
* @returns {og.EntityCollection} -
* @returns {EntityCollection} -
*/
addTo(renderNode, isHidden) {
if (!this.renderNode) {
@ -508,7 +508,7 @@ class EntityCollection {
/**
* This function is called in the RenderNode assign function.
* @param {og.RenderNode} renderNode
* @param {RenderNode} renderNode
*/
bindRenderNode(renderNode) {
if (renderNode.renderer) {
@ -532,7 +532,7 @@ class EntityCollection {
/**
* Updates coordiantes all lonLat entities in collection after collecction attached to the planet node.
* @private
* @param {og.Ellipsoid} ellipsoid - Globe ellipsoid.
* @param {Ellipsoid} ellipsoid - Globe ellipsoid.
*/
_updateGeodeticCoordinates(ellipsoid) {
var e = this._entities;
@ -593,7 +593,7 @@ class EntityCollection {
/**
* Gets entity array.
* @public
* @returns {Array.<og.Entity>} -
* @returns {Array.<Entity>} -
*/
getEntities() {
return [].concat(this._entities);
@ -644,7 +644,7 @@ class EntityCollection {
/**
* Clears entity recursevely.
* @private
* @param {og.Entity} entity - Entity to clear.
* @param {Entity} entity - Entity to clear.
*/
_clearEntity(entity) {
entity._entityCollection = null;

View File

@ -160,7 +160,7 @@ class GeoObject {
this._position.x = x;
this._position.y = y;
this._position.z = z;
Vec3.doubleToTwoFloats(position, this._positionHigh, this._positionLow);
Vec3.doubleToTwoFloats(this._position, this._positionHigh, this._positionLow);
this._handler &&
this._handler.setPositionArr(this._handlerIndex, this._positionHigh, this._positionLow);
this.updateDirection();

View File

@ -2,12 +2,12 @@
* @module og/entity/Geometry
*/
'use strict';
"use strict";
import * as utils from '../utils/shared.js';
import { Extent } from '../Extent.js';
import { Vec4 } from '../math/Vec4.js';
import { LonLat } from '../LonLat.js';
import * as utils from "../utils/shared.js";
import { Extent } from "../Extent.js";
import { Vec4 } from "../math/Vec4.js";
import { LonLat } from "../LonLat.js";
const GeometryType = {
POINT: 1,
@ -27,7 +27,7 @@ class Geometry {
/**
* Entity instance that holds this geometry.
* @protected
* @type {og.Entity}
* @type {Entity}
*/
this._entity = null;
@ -58,15 +58,27 @@ class Geometry {
this._type = (options.type && Geometry.getType(options.type)) || GeometryType.POINT;
this._coordinates = [];
this._extent = Geometry.getExtent({
this._extent = Geometry.getExtent(
{
type: options.type || "Point",
coordinates: options.coordinates || []
}, this._coordinates);
},
this._coordinates
);
this._style = options.style || {};
this._style.fillColor = utils.createColorRGBA(options.style.fillColor, new Vec4(0.19, 0.62, 0.85, 0.4));
this._style.lineColor = utils.createColorRGBA(options.style.lineColor, new Vec4(0.19, 0.62, 0.85, 1));
this._style.strokeColor = utils.createColorRGBA(options.style.strokeColor, new Vec4(1, 1, 1, 0.95));
this._style.fillColor = utils.createColorRGBA(
options.style.fillColor,
new Vec4(0.19, 0.62, 0.85, 0.4)
);
this._style.lineColor = utils.createColorRGBA(
options.style.lineColor,
new Vec4(0.19, 0.62, 0.85, 1)
);
this._style.strokeColor = utils.createColorRGBA(
options.style.strokeColor,
new Vec4(1, 1, 1, 0.95)
);
this._style.lineWidth = options.style.lineWidth || 3;
this._style.strokeWidth = options.style.strokeWidth || 0;
@ -96,7 +108,7 @@ class Geometry {
@static
@param {Object} geometryObj - GeoJSON style geometry feature.
@param {LonLat[]} outCoordinates - Geometry feature coordinates clone.
@returns {og.Extent} -
@returns {Extent} -
*/
static getExtent(geometryObj, outCoordinates) {
var res = new Extent(new LonLat(180.0, 90.0), new LonLat(-180.0, -90.0));
@ -110,9 +122,7 @@ class Geometry {
res.northEast.lon = lon;
res.northEast.lat = lat;
outCoordinates && (outCoordinates[0] = lon) && (outCoordinates[1] = lat);
} else if (t === GeometryType.LINESTRING) {
let c = geometryObj.coordinates;
for (let i = 0; i < c.length; i++) {
let lon = c[i][0],
@ -123,9 +133,7 @@ class Geometry {
if (lat > res.northEast.lat) res.northEast.lat = lat;
outCoordinates && (outCoordinates[i] = [lon, lat]);
}
} else if (t === GeometryType.POLYGON) {
let c = geometryObj.coordinates;
for (let i = 0; i < c.length; i++) {
let ci = c[i];
@ -141,9 +149,7 @@ class Geometry {
outCoordinates && (outCoordinates[i][j] = [lon, lat]);
}
}
} else if (t === GeometryType.MULTIPOLYGON) {
let p = geometryObj.coordinates;
for (let i = 0; i < p.length; i++) {
let pi = p[i];
@ -163,9 +169,7 @@ class Geometry {
}
}
}
} else if (t === GeometryType.MULTILINESTRING) {
let c = geometryObj.coordinates;
for (let i = 0; i < c.length; i++) {
let ci = c[i];
@ -181,10 +185,9 @@ class Geometry {
outCoordinates && (outCoordinates[i][j] = [lon, lat]);
}
}
} else {
res.southWest.lon = res.southWest.lat = res.northEast.lon = res.northEast.lat = 0.0;
outCoordinates && (outCoordinates[0] = lon) && (outCoordinates[1] = lat);
outCoordinates && (outCoordinates[0] = 0) && (outCoordinates[1] = 0);
}
return res;
}

View File

@ -2,14 +2,14 @@
* @module og/entity/GeometryHandler
*/
'use strict';
"use strict";
import * as mercator from '../mercator.js';
import * as quadTree from '../quadTree/quadTree.js';
import { earcut, flatten } from '../utils/earcut.js';
import { GeometryType } from './Geometry.js';
import { Vec2 } from '../math/Vec2.js';
import { doubleToTwoFloatsV2 } from '../math/coder.js';
import * as mercator from "../mercator.js";
import * as quadTree from "../quadTree/quadTree.js";
import { earcut, flatten } from "../utils/earcut.js";
import { GeometryType } from "./Geometry.js";
import { Vec2 } from "../math/Vec2.js";
import { doubleToTwoFloatsV2 } from "../math/coder.js";
const POLYVERTICES_BUFFER = 0;
const POLYINDEXES_BUFFER = 1;
@ -25,8 +25,8 @@ const POLYPICKINGCOLORS_BUFFER = 10;
const LINEPICKINGCOLORS_BUFFER = 11;
function doubleToTwoFloats(v, high, low) {
let x = v[0], y = v[1];
let x = v[0],
y = v[1];
if (x >= 0.0) {
let doubleHigh = Math.floor(x / 65536.0) * 65536.0;
@ -132,9 +132,26 @@ class GeometryHandler {
this._counter = n;
}
static appendLineData(pathArr, isClosed, color, pickingColor, thickness, strokeColor, strokeSize,
outVerticesHigh, outVerticesLow, outOrders, outIndexes, outColors, outPickingColors, outThickness, outStrokeColors, outStrokes,
outVerticesHigh2, outVerticesLow2) {
static appendLineData(
pathArr,
isClosed,
color,
pickingColor,
thickness,
strokeColor,
strokeSize,
outVerticesHigh,
outVerticesLow,
outOrders,
outIndexes,
outColors,
outPickingColors,
outThickness,
outStrokeColors,
outStrokes,
outVerticesHigh2,
outVerticesLow2
) {
var index = 0;
if (outIndexes.length > 0) {
@ -174,37 +191,211 @@ class GeometryHandler {
doubleToTwoFloats(last, tempHigh, tempLow);
outVerticesHigh.push(tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y);
outVerticesLow.push(tempLow.x, tempLow.y, tempLow.x, tempLow.y, tempLow.x, tempLow.y, tempLow.x, tempLow.y);
outVerticesHigh.push(
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y
);
outVerticesLow.push(
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y
);
outVerticesHigh2.push(tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y);
outVerticesLow2.push(tempLow.x, tempLow.y, tempLow.x, tempLow.y, tempLow.x, tempLow.y, tempLow.x, tempLow.y);
outVerticesHigh2.push(
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y
);
outVerticesLow2.push(
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y
);
outOrders.push(1, -1, 2, -2);
outThickness.push(t, t, t, t);
outStrokes.push(s, s, s, s);
outColors.push(c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3]);
outStrokeColors.push(sc[0], sc[1], sc[2], sc[3], sc[0], sc[1], sc[2], sc[3], sc[0], sc[1], sc[2], sc[3], sc[0], sc[1], sc[2], sc[3]);
outPickingColors.push(p[0], p[1], p[2], p[3], p[0], p[1], p[2], p[3], p[0], p[1], p[2], p[3], p[0], p[1], p[2], p[3]);
outColors.push(
c[0],
c[1],
c[2],
c[3],
c[0],
c[1],
c[2],
c[3],
c[0],
c[1],
c[2],
c[3],
c[0],
c[1],
c[2],
c[3]
);
outStrokeColors.push(
sc[0],
sc[1],
sc[2],
sc[3],
sc[0],
sc[1],
sc[2],
sc[3],
sc[0],
sc[1],
sc[2],
sc[3],
sc[0],
sc[1],
sc[2],
sc[3]
);
outPickingColors.push(
p[0],
p[1],
p[2],
p[3],
p[0],
p[1],
p[2],
p[3],
p[0],
p[1],
p[2],
p[3],
p[0],
p[1],
p[2],
p[3]
);
for (var i = 0; i < path.length; i++) {
var cur = path[i];
doubleToTwoFloats(cur, tempHigh, tempLow);
outVerticesHigh.push(tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y);
outVerticesLow.push(tempLow.x, tempLow.y, tempLow.x, tempLow.y, tempLow.x, tempLow.y, tempLow.x, tempLow.y);
outVerticesHigh.push(
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y
);
outVerticesLow.push(
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y
);
outVerticesHigh2.push(tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y);
outVerticesLow2.push(tempLow.x, tempLow.y, tempLow.x, tempLow.y, tempLow.x, tempLow.y, tempLow.x, tempLow.y);
outVerticesHigh2.push(
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y
);
outVerticesLow2.push(
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y
);
outOrders.push(1, -1, 2, -2);
outThickness.push(t, t, t, t);
outStrokes.push(s, s, s, s);
outColors.push(c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3]);
outStrokeColors.push(sc[0], sc[1], sc[2], sc[3], sc[0], sc[1], sc[2], sc[3], sc[0], sc[1], sc[2], sc[3], sc[0], sc[1], sc[2], sc[3]);
outPickingColors.push(p[0], p[1], p[2], p[3], p[0], p[1], p[2], p[3], p[0], p[1], p[2], p[3], p[0], p[1], p[2], p[3]);
outColors.push(
c[0],
c[1],
c[2],
c[3],
c[0],
c[1],
c[2],
c[3],
c[0],
c[1],
c[2],
c[3],
c[0],
c[1],
c[2],
c[3]
);
outStrokeColors.push(
sc[0],
sc[1],
sc[2],
sc[3],
sc[0],
sc[1],
sc[2],
sc[3],
sc[0],
sc[1],
sc[2],
sc[3],
sc[0],
sc[1],
sc[2],
sc[3]
);
outPickingColors.push(
p[0],
p[1],
p[2],
p[3],
p[0],
p[1],
p[2],
p[3],
p[0],
p[1],
p[2],
p[3],
p[0],
p[1],
p[2],
p[3]
);
outIndexes.push(index++, index++, index++, index++);
}
@ -226,18 +417,105 @@ class GeometryHandler {
doubleToTwoFloats(first, tempHigh, tempLow);
outVerticesHigh.push(tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y);
outVerticesLow.push(tempLow.x, tempLow.y, tempLow.x, tempLow.y, tempLow.x, tempLow.y, tempLow.x, tempLow.y);
outVerticesHigh.push(
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y
);
outVerticesLow.push(
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y
);
outVerticesHigh2.push(tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y, tempHigh.x, tempHigh.y);
outVerticesLow2.push(tempLow.x, tempLow.y, tempLow.x, tempLow.y, tempLow.x, tempLow.y, tempLow.x, tempLow.y);
outVerticesHigh2.push(
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y,
tempHigh.x,
tempHigh.y
);
outVerticesLow2.push(
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y,
tempLow.x,
tempLow.y
);
outOrders.push(1, -1, 2, -2);
outThickness.push(t, t, t, t);
outStrokes.push(s, s, s, s);
outColors.push(c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3]);
outStrokeColors.push(sc[0], sc[1], sc[2], sc[3], sc[0], sc[1], sc[2], sc[3], sc[0], sc[1], sc[2], sc[3], sc[0], sc[1], sc[2], sc[3]);
outPickingColors.push(p[0], p[1], p[2], p[3], p[0], p[1], p[2], p[3], p[0], p[1], p[2], p[3], p[0], p[1], p[2], p[3]);
outColors.push(
c[0],
c[1],
c[2],
c[3],
c[0],
c[1],
c[2],
c[3],
c[0],
c[1],
c[2],
c[3],
c[0],
c[1],
c[2],
c[3]
);
outStrokeColors.push(
sc[0],
sc[1],
sc[2],
sc[3],
sc[0],
sc[1],
sc[2],
sc[3],
sc[0],
sc[1],
sc[2],
sc[3],
sc[0],
sc[1],
sc[2],
sc[3]
);
outPickingColors.push(
p[0],
p[1],
p[2],
p[3],
p[0],
p[1],
p[2],
p[3],
p[0],
p[1],
p[2],
p[3],
p[0],
p[1],
p[2],
p[3]
);
if (j < pathArr.length - 1) {
index += 8;
@ -253,7 +531,7 @@ class GeometryHandler {
/**
* @public
* @param {og.Geometry} geometry - Geometry object.
* @param {Geometry} geometry - Geometry object.
*/
add(geometry) {
//
@ -271,13 +549,15 @@ class GeometryHandler {
geometry._lineVerticesLowMerc = [];
if (geometry._type === GeometryType.POLYGON) {
let coordinates = geometry._coordinates;
let ci = [];
for (let j = 0; j < coordinates.length; j++) {
ci[j] = [];
for (var k = 0; k < coordinates[j].length; k++) {
ci[j][k] = [mercator.forward_lon(coordinates[j][k][0]), mercator.forward_lat(coordinates[j][k][1])];
ci[j][k] = [
mercator.forward_lon(coordinates[j][k][0]),
mercator.forward_lat(coordinates[j][k][1])
];
}
}
@ -298,7 +578,12 @@ class GeometryHandler {
for (let i = 0; i < data.vertices.length * 0.5; i++) {
this._polyColors.push(color.x, color.y, color.z, color.w);
this._polyPickingColors.push(pickingColor.x, pickingColor.y, pickingColor.z, 1.0);
this._polyPickingColors.push(
pickingColor.x,
pickingColor.y,
pickingColor.z,
1.0
);
}
for (let i = 0; i < data.vertices.length; i++) {
@ -323,20 +608,38 @@ class GeometryHandler {
geometry._lineColorsHandlerIndex = this._lineColors.length;
geometry._lineThicknessHandlerIndex = this._lineThickness.length;
GeometryHandler.appendLineData(ci, true,
geometry._style.lineColor, pickingColor, geometry._style.lineWidth,
geometry._style.strokeColor, geometry._style.strokeWidth,
this._lineVerticesHighMerc, this._lineVerticesLowMerc, this._lineOrders, this._lineIndexes, this._lineColors, this._linePickingColors,
this._lineThickness, this._lineStrokeColors, this._lineStrokes, geometry._lineVerticesHighMerc, geometry._lineVerticesLowMerc);
geometry._lineVerticesLength = this._lineVerticesHighMerc.length - geometry._lineVerticesHandlerIndex;
geometry._lineOrdersLength = this._lineOrders.length - geometry._lineOrdersHandlerIndex;
geometry._lineIndexesLength = this._lineIndexes.length - geometry._lineIndexesHandlerIndex;
geometry._lineColorsLength = this._lineColors.length - geometry._lineColorsHandlerIndex;
geometry._lineThicknessLength = this._lineThickness.length - geometry._lineThicknessHandlerIndex;
GeometryHandler.appendLineData(
ci,
true,
geometry._style.lineColor,
pickingColor,
geometry._style.lineWidth,
geometry._style.strokeColor,
geometry._style.strokeWidth,
this._lineVerticesHighMerc,
this._lineVerticesLowMerc,
this._lineOrders,
this._lineIndexes,
this._lineColors,
this._linePickingColors,
this._lineThickness,
this._lineStrokeColors,
this._lineStrokes,
geometry._lineVerticesHighMerc,
geometry._lineVerticesLowMerc
);
geometry._lineVerticesLength =
this._lineVerticesHighMerc.length - geometry._lineVerticesHandlerIndex;
geometry._lineOrdersLength =
this._lineOrders.length - geometry._lineOrdersHandlerIndex;
geometry._lineIndexesLength =
this._lineIndexes.length - geometry._lineIndexesHandlerIndex;
geometry._lineColorsLength =
this._lineColors.length - geometry._lineColorsHandlerIndex;
geometry._lineThicknessLength =
this._lineThickness.length - geometry._lineThicknessHandlerIndex;
} else if (geometry._type === GeometryType.MULTIPOLYGON) {
let coordinates = geometry._coordinates;
let vertices = [],
indexes = [];
@ -354,7 +657,10 @@ class GeometryHandler {
for (let j = 0; j < cci.length; j++) {
ci[j] = [];
for (let k = 0; k < coordinates[i][j].length; k++) {
ci[j][k] = [mercator.forward_lon(cci[j][k][0]), mercator.forward_lat(cci[j][k][1])];
ci[j][k] = [
mercator.forward_lon(cci[j][k][0]),
mercator.forward_lat(cci[j][k][1])
];
}
}
let data = flatten(ci);
@ -366,11 +672,26 @@ class GeometryHandler {
vertices.push.apply(vertices, data.vertices);
GeometryHandler.appendLineData(ci, true,
geometry._style.lineColor, pickingColor, geometry._style.lineWidth,
geometry._style.strokeColor, geometry._style.strokeWidth,
this._lineVerticesHighMerc, this._lineVerticesLowMerc, this._lineOrders, this._lineIndexes, this._lineColors, this._linePickingColors,
this._lineThickness, this._lineStrokeColors, this._lineStrokes, geometry._lineVerticesHighMerc, geometry._lineVerticesLowMerc);
GeometryHandler.appendLineData(
ci,
true,
geometry._style.lineColor,
pickingColor,
geometry._style.lineWidth,
geometry._style.strokeColor,
geometry._style.strokeWidth,
this._lineVerticesHighMerc,
this._lineVerticesLowMerc,
this._lineOrders,
this._lineIndexes,
this._lineColors,
this._linePickingColors,
this._lineThickness,
this._lineStrokeColors,
this._lineStrokes,
geometry._lineVerticesHighMerc,
geometry._lineVerticesLowMerc
);
}
geometry._polyVerticesHandlerIndex = this._polyVerticesHighMerc.length;
@ -387,7 +708,12 @@ class GeometryHandler {
for (let i = 0; i < vertices.length * 0.5; i++) {
this._polyColors.push(color.x, color.y, color.z, color.w);
this._polyPickingColors.push(pickingColor.x, pickingColor.y, pickingColor.z, 1.0);
this._polyPickingColors.push(
pickingColor.x,
pickingColor.y,
pickingColor.z,
1.0
);
}
for (let i = 0; i < vertices.length; i++) {
@ -405,18 +731,24 @@ class GeometryHandler {
geometry._polyVerticesLength = vertices.length;
geometry._polyIndexesLength = indexes.length;
geometry._lineVerticesLength = this._lineVerticesHighMerc.length - geometry._lineVerticesHandlerIndex;
geometry._lineOrdersLength = this._lineOrders.length - geometry._lineOrdersHandlerIndex;
geometry._lineIndexesLength = this._lineIndexes.length - geometry._lineIndexesHandlerIndex;
geometry._lineColorsLength = this._lineColors.length - geometry._lineColorsHandlerIndex;
geometry._lineThicknessLength = this._lineThickness.length - geometry._lineThicknessHandlerIndex;
geometry._lineVerticesLength =
this._lineVerticesHighMerc.length - geometry._lineVerticesHandlerIndex;
geometry._lineOrdersLength =
this._lineOrders.length - geometry._lineOrdersHandlerIndex;
geometry._lineIndexesLength =
this._lineIndexes.length - geometry._lineIndexesHandlerIndex;
geometry._lineColorsLength =
this._lineColors.length - geometry._lineColorsHandlerIndex;
geometry._lineThicknessLength =
this._lineThickness.length - geometry._lineThicknessHandlerIndex;
} else if (geometry._type === GeometryType.LINESTRING) {
let coordinates = geometry._coordinates;
let ci = new Array(coordinates.length);
for (let j = 0; j < coordinates.length; j++) {
ci[j] = [mercator.forward_lon(coordinates[j][0]), mercator.forward_lat(coordinates[j][1])];
ci[j] = [
mercator.forward_lon(coordinates[j][0]),
mercator.forward_lat(coordinates[j][1])
];
}
// Creates polygon stroke data
@ -426,25 +758,47 @@ class GeometryHandler {
geometry._lineColorsHandlerIndex = this._lineColors.length;
geometry._lineThicknessHandlerIndex = this._lineThickness.length;
GeometryHandler.appendLineData([ci], false,
geometry._style.lineColor, pickingColor, geometry._style.lineWidth,
geometry._style.strokeColor, geometry._style.strokeWidth,
this._lineVerticesHighMerc, this._lineVerticesLowMerc, this._lineOrders, this._lineIndexes, this._lineColors, this._linePickingColors,
this._lineThickness, this._lineStrokeColors, this._lineStrokes, geometry._lineVerticesHighMerc, geometry._lineVerticesLowMerc);
geometry._lineVerticesLength = this._lineVerticesHighMerc.length - geometry._lineVerticesHandlerIndex;
geometry._lineOrdersLength = this._lineOrders.length - geometry._lineOrdersHandlerIndex;
geometry._lineIndexesLength = this._lineIndexes.length - geometry._lineIndexesHandlerIndex;
geometry._lineColorsLength = this._lineColors.length - geometry._lineColorsHandlerIndex;
geometry._lineThicknessLength = this._lineThickness.length - geometry._lineThicknessHandlerIndex;
GeometryHandler.appendLineData(
[ci],
false,
geometry._style.lineColor,
pickingColor,
geometry._style.lineWidth,
geometry._style.strokeColor,
geometry._style.strokeWidth,
this._lineVerticesHighMerc,
this._lineVerticesLowMerc,
this._lineOrders,
this._lineIndexes,
this._lineColors,
this._linePickingColors,
this._lineThickness,
this._lineStrokeColors,
this._lineStrokes,
geometry._lineVerticesHighMerc,
geometry._lineVerticesLowMerc
);
geometry._lineVerticesLength =
this._lineVerticesHighMerc.length - geometry._lineVerticesHandlerIndex;
geometry._lineOrdersLength =
this._lineOrders.length - geometry._lineOrdersHandlerIndex;
geometry._lineIndexesLength =
this._lineIndexes.length - geometry._lineIndexesHandlerIndex;
geometry._lineColorsLength =
this._lineColors.length - geometry._lineColorsHandlerIndex;
geometry._lineThicknessLength =
this._lineThickness.length - geometry._lineThicknessHandlerIndex;
} else if (geometry._type === GeometryType.MULTILINESTRING) {
let coordinates = geometry._coordinates;
let ci = [];
for (let j = 0; j < coordinates.length; j++) {
ci[j] = [];
for (let k = 0; k < coordinates[j].length; k++) {
ci[j][k] = [mercator.forward_lon(coordinates[j][k][0]), mercator.forward_lat(coordinates[j][k][1])];
ci[j][k] = [
mercator.forward_lon(coordinates[j][k][0]),
mercator.forward_lat(coordinates[j][k][1])
];
}
}
@ -455,17 +809,37 @@ class GeometryHandler {
geometry._lineColorsHandlerIndex = this._lineColors.length;
geometry._lineThicknessHandlerIndex = this._lineThickness.length;
GeometryHandler.appendLineData(ci, false,
geometry._style.lineColor, pickingColor, geometry._style.lineWidth,
geometry._style.strokeColor, geometry._style.strokeWidth,
this._lineVerticesHighMerc, this._lineVerticesLowMerc, this._lineOrders, this._lineIndexes, this._lineColors, this._linePickingColors,
this._lineThickness, this._lineStrokeColors, this._lineStrokes, geometry._lineVerticesHighMerc, geometry._lineVerticesLowMerc);
GeometryHandler.appendLineData(
ci,
false,
geometry._style.lineColor,
pickingColor,
geometry._style.lineWidth,
geometry._style.strokeColor,
geometry._style.strokeWidth,
this._lineVerticesHighMerc,
this._lineVerticesLowMerc,
this._lineOrders,
this._lineIndexes,
this._lineColors,
this._linePickingColors,
this._lineThickness,
this._lineStrokeColors,
this._lineStrokes,
geometry._lineVerticesHighMerc,
geometry._lineVerticesLowMerc
);
geometry._lineVerticesLength = this._lineVerticesHighMerc.length - geometry._lineVerticesHandlerIndex;
geometry._lineOrdersLength = this._lineOrders.length - geometry._lineOrdersHandlerIndex;
geometry._lineIndexesLength = this._lineIndexes.length - geometry._lineIndexesHandlerIndex;
geometry._lineColorsLength = this._lineColors.length - geometry._lineColorsHandlerIndex;
geometry._lineThicknessLength = this._lineThickness.length - geometry._lineThicknessHandlerIndex;
geometry._lineVerticesLength =
this._lineVerticesHighMerc.length - geometry._lineVerticesHandlerIndex;
geometry._lineOrdersLength =
this._lineOrders.length - geometry._lineOrdersHandlerIndex;
geometry._lineIndexesLength =
this._lineIndexes.length - geometry._lineIndexesHandlerIndex;
geometry._lineColorsLength =
this._lineColors.length - geometry._lineColorsHandlerIndex;
geometry._lineThicknessLength =
this._lineThickness.length - geometry._lineThicknessHandlerIndex;
}
// Refresh visibility
@ -484,12 +858,27 @@ class GeometryHandler {
// polygon
// this._polyVerticesLonLat.splice(geometry._polyVerticesHandlerIndex, geometry._polyVerticesLength);
this._polyVerticesHighMerc.splice(geometry._polyVerticesHandlerIndex, geometry._polyVerticesLength);
this._polyVerticesLowMerc.splice(geometry._polyVerticesHandlerIndex, geometry._polyVerticesLength);
this._polyVerticesHighMerc.splice(
geometry._polyVerticesHandlerIndex,
geometry._polyVerticesLength
);
this._polyVerticesLowMerc.splice(
geometry._polyVerticesHandlerIndex,
geometry._polyVerticesLength
);
this._polyColors.splice(geometry._polyVerticesHandlerIndex * 2, geometry._polyVerticesLength * 2);
this._polyPickingColors.splice(geometry._polyVerticesHandlerIndex * 2, geometry._polyVerticesLength * 2);
this._polyIndexes.splice(geometry._polyIndexesHandlerIndex, geometry._polyIndexesLength);
this._polyColors.splice(
geometry._polyVerticesHandlerIndex * 2,
geometry._polyVerticesLength * 2
);
this._polyPickingColors.splice(
geometry._polyVerticesHandlerIndex * 2,
geometry._polyVerticesLength * 2
);
this._polyIndexes.splice(
geometry._polyIndexesHandlerIndex,
geometry._polyIndexesLength
);
var di = geometry._polyVerticesLength * 0.5;
for (var i = geometry._polyIndexesHandlerIndex; i < this._polyIndexes.length; i++) {
this._polyIndexes[i] -= di;
@ -497,15 +886,36 @@ class GeometryHandler {
// line
// this._lineVerticesLonLat.splice(geometry._lineVerticesHandlerIndex, geometry._lineVerticesLength);
this._lineVerticesHighMerc.splice(geometry._lineVerticesHandlerIndex, geometry._lineVerticesLength);
this._lineVerticesLowMerc.splice(geometry._lineVerticesHandlerIndex, geometry._lineVerticesLength);
this._lineVerticesHighMerc.splice(
geometry._lineVerticesHandlerIndex,
geometry._lineVerticesLength
);
this._lineVerticesLowMerc.splice(
geometry._lineVerticesHandlerIndex,
geometry._lineVerticesLength
);
this._lineOrders.splice(geometry._lineOrdersHandlerIndex, geometry._lineOrdersLength);
this._lineColors.splice(geometry._lineColorsHandlerIndex, geometry._lineColorsLength);
this._linePickingColors.splice(geometry._lineColorsHandlerIndex, geometry._lineColorsLength);
this._lineStrokeColors.splice(geometry._lineColorsHandlerIndex, geometry._lineColorsLength);
this._lineThickness.splice(geometry._lineThicknessHandlerIndex, geometry._lineThicknessLength);
this._lineStrokes.splice(geometry._lineThicknessHandlerIndex, geometry._lineThicknessLength);
this._lineIndexes.splice(geometry._lineIndexesHandlerIndex, geometry._lineIndexesLength);
this._linePickingColors.splice(
geometry._lineColorsHandlerIndex,
geometry._lineColorsLength
);
this._lineStrokeColors.splice(
geometry._lineColorsHandlerIndex,
geometry._lineColorsLength
);
this._lineThickness.splice(
geometry._lineThicknessHandlerIndex,
geometry._lineThicknessLength
);
this._lineStrokes.splice(
geometry._lineThicknessHandlerIndex,
geometry._lineThicknessLength
);
this._lineIndexes.splice(
geometry._lineIndexesHandlerIndex,
geometry._lineIndexesLength
);
di = geometry._lineVerticesLength * 0.5;
for (let i = geometry._lineIndexesHandlerIndex; i < this._lineIndexes.length; i++) {
this._lineIndexes[i] -= di;
@ -551,7 +961,8 @@ class GeometryHandler {
geometry._lineThicknessHandlerIndex = -1;
geometry._lineColorsHandlerIndex = -1;
!this._removeGeometryExtents[geometry._id] && this._removeGeometryExtentArr.push(geometry.getExtent());
!this._removeGeometryExtents[geometry._id] &&
this._removeGeometryExtentArr.push(geometry.getExtent());
this._removeGeometryExtents[geometry._id] = true;
this.refresh();
@ -753,9 +1164,14 @@ class GeometryHandler {
}
bringToFront(geometry) {
var polyIndexes = this._polyIndexes.splice(geometry._polyIndexesHandlerIndex, geometry._polyIndexesLength);
var lineIndexes = this._lineIndexes.splice(geometry._lineIndexesHandlerIndex, geometry._lineIndexesLength);
var polyIndexes = this._polyIndexes.splice(
geometry._polyIndexesHandlerIndex,
geometry._polyIndexesLength
);
var lineIndexes = this._lineIndexes.splice(
geometry._lineIndexesHandlerIndex,
geometry._lineIndexesLength
);
this._geometries.splice(geometry._handlerIndex, 1);
@ -786,79 +1202,135 @@ class GeometryHandler {
createPolyVerticesBuffer() {
var h = this._handler;
h.gl.deleteBuffer(this._polyVerticesHighBufferMerc);
this._polyVerticesHighBufferMerc = h.createArrayBuffer(new Float32Array(this._polyVerticesHighMerc), 2, this._polyVerticesHighMerc.length / 2);
this._polyVerticesHighBufferMerc = h.createArrayBuffer(
new Float32Array(this._polyVerticesHighMerc),
2,
this._polyVerticesHighMerc.length / 2
);
h.gl.deleteBuffer(this._polyVerticesLowBufferMerc);
this._polyVerticesLowBufferMerc = h.createArrayBuffer(new Float32Array(this._polyVerticesLowMerc), 2, this._polyVerticesLowMerc.length / 2);
this._polyVerticesLowBufferMerc = h.createArrayBuffer(
new Float32Array(this._polyVerticesLowMerc),
2,
this._polyVerticesLowMerc.length / 2
);
}
createPolyIndexesBuffer() {
var h = this._handler;
h.gl.deleteBuffer(this._polyIndexesBuffer);
this._polyIndexesBuffer = h.createElementArrayBuffer(new Uint32Array(this._polyIndexes), 1, this._polyIndexes.length);
this._polyIndexesBuffer = h.createElementArrayBuffer(
new Uint32Array(this._polyIndexes),
1,
this._polyIndexes.length
);
}
createPolyColorsBuffer() {
var h = this._handler;
h.gl.deleteBuffer(this._polyColorsBuffer);
this._polyColorsBuffer = h.createArrayBuffer(new Float32Array(this._polyColors), 4, this._polyColors.length / 4);
this._polyColorsBuffer = h.createArrayBuffer(
new Float32Array(this._polyColors),
4,
this._polyColors.length / 4
);
}
createPolyPickingColorsBuffer() {
var h = this._handler;
h.gl.deleteBuffer(this._polyPickingColorsBuffer);
this._polyPickingColorsBuffer = h.createArrayBuffer(new Float32Array(this._polyPickingColors), 4, this._polyPickingColors.length / 4);
this._polyPickingColorsBuffer = h.createArrayBuffer(
new Float32Array(this._polyPickingColors),
4,
this._polyPickingColors.length / 4
);
}
createLineVerticesBuffer() {
var h = this._handler;
h.gl.deleteBuffer(this._lineVerticesHighBufferMerc);
this._lineVerticesHighBufferMerc = h.createArrayBuffer(new Float32Array(this._lineVerticesHighMerc), 2, this._lineVerticesHighMerc.length / 2);
this._lineVerticesHighBufferMerc = h.createArrayBuffer(
new Float32Array(this._lineVerticesHighMerc),
2,
this._lineVerticesHighMerc.length / 2
);
h.gl.deleteBuffer(this._lineVerticesLowBufferMerc);
this._lineVerticesLowBufferMerc = h.createArrayBuffer(new Float32Array(this._lineVerticesLowMerc), 2, this._lineVerticesLowMerc.length / 2);
this._lineVerticesLowBufferMerc = h.createArrayBuffer(
new Float32Array(this._lineVerticesLowMerc),
2,
this._lineVerticesLowMerc.length / 2
);
}
createLineIndexesBuffer() {
var h = this._handler;
h.gl.deleteBuffer(this._lineIndexesBuffer);
this._lineIndexesBuffer = h.createElementArrayBuffer(new Uint32Array(this._lineIndexes), 1, this._lineIndexes.length);
this._lineIndexesBuffer = h.createElementArrayBuffer(
new Uint32Array(this._lineIndexes),
1,
this._lineIndexes.length
);
}
createLineOrdersBuffer() {
var h = this._handler;
h.gl.deleteBuffer(this._lineOrdersBuffer);
this._lineOrdersBuffer = h.createArrayBuffer(new Float32Array(this._lineOrders), 1, this._lineOrders.length / 2);
this._lineOrdersBuffer = h.createArrayBuffer(
new Float32Array(this._lineOrders),
1,
this._lineOrders.length / 2
);
}
createLineColorsBuffer() {
var h = this._handler;
h.gl.deleteBuffer(this._lineColorsBuffer);
this._lineColorsBuffer = h.createArrayBuffer(new Float32Array(this._lineColors), 4, this._lineColors.length / 4);
this._lineColorsBuffer = h.createArrayBuffer(
new Float32Array(this._lineColors),
4,
this._lineColors.length / 4
);
}
createLinePickingColorsBuffer() {
var h = this._handler;
h.gl.deleteBuffer(this._linePickingColorsBuffer);
this._linePickingColorsBuffer = h.createArrayBuffer(new Float32Array(this._linePickingColors), 4, this._linePickingColors.length / 4);
this._linePickingColorsBuffer = h.createArrayBuffer(
new Float32Array(this._linePickingColors),
4,
this._linePickingColors.length / 4
);
}
createLineThicknessBuffer() {
var h = this._handler;
h.gl.deleteBuffer(this._lineThicknessBuffer);
this._lineThicknessBuffer = h.createArrayBuffer(new Float32Array(this._lineThickness), 1, this._lineThickness.length);
this._lineThicknessBuffer = h.createArrayBuffer(
new Float32Array(this._lineThickness),
1,
this._lineThickness.length
);
}
createLineStrokesBuffer() {
var h = this._handler;
h.gl.deleteBuffer(this._lineStrokesBuffer);
this._lineStrokesBuffer = h.createArrayBuffer(new Float32Array(this._lineStrokes), 1, this._lineStrokes.length);
this._lineStrokesBuffer = h.createArrayBuffer(
new Float32Array(this._lineStrokes),
1,
this._lineStrokes.length
);
}
createLineStrokeColorsBuffer() {
var h = this._handler;
h.gl.deleteBuffer(this._lineStrokeColorsBuffer);
this._lineStrokeColorsBuffer = h.createArrayBuffer(new Float32Array(this._lineStrokeColors), 4, this._lineStrokeColors.length / 4);
this._lineStrokeColorsBuffer = h.createArrayBuffer(
new Float32Array(this._lineStrokeColors),
4,
this._lineStrokeColors.length / 4
);
}
}

View File

@ -2,11 +2,11 @@
* @module og/entity/Label
*/
'use strict';
"use strict";
import * as utils from '../utils/shared.js';
import { BaseBillboard } from './BaseBillboard.js';
import { Vec4 } from '../math/Vec4.js';
import * as utils from "../utils/shared.js";
import { BaseBillboard } from "./BaseBillboard.js";
import { Vec4 } from "../math/Vec4.js";
const ALIGN = {
RIGHT: 0,
@ -28,13 +28,13 @@ const STR2ALIGN = {
/**
* Billboard text label.
* @class
* @extends {og.BaseBillboard}
* @extends {BaseBillboard}
* @param {Object} [options] - Label options:
* @param {og.Vec3|Array.<number>} [options.position] - Billboard spatial position.
* @param {Vec3|Array.<number>} [options.position] - Billboard spatial position.
* @param {number} [options.rotation] - Screen angle rotaion.
* @param {og.Vec4|string|Array.<number>} [options.color] - Billboard color.
* @param {og.Vec3|Array.<number>} [options.alignedAxis] - Billboard aligned vector.
* @param {og.Vec3|Array.<number>} [options.offset] - Billboard center screen offset.
* @param {Vec4|string|Array.<number>} [options.color] - Billboard color.
* @param {Vec3|Array.<number>} [options.alignedAxis] - Billboard aligned vector.
* @param {Vec3|Array.<number>} [options.offset] - Billboard center screen offset.
* @param {boolean} [options.visibility] - Visibility.
* @param {string} [options.text] - Text string.
* @param {string} [options.face] - HTML5 font face.
@ -42,8 +42,8 @@ const STR2ALIGN = {
* @param {string} [options.style] - HTML5 font style. Example 'normal', 'italic'.
* @param {string} [options.weight] - HTML5 font weight. Example 'normal', 'bold'.
* @param {number} [options.outline] - Text outline size. 0 - no outline, 1 - maximum outline. Default 0.58.
* @param {og.Vec4|string|Array.<number>} [options.outlineColor] - Outline color.
* @param {og.Label.ALIGN} [options.align] - Text horizontal align: "left", "right" and "center".
* @param {Vec4|string|Array.<number>} [options.outlineColor] - Outline color.
* @param {Label.ALIGN} [options.align] - Text horizontal align: "left", "right" and "center".
*/
class Label extends BaseBillboard {
constructor(options) {
@ -82,16 +82,21 @@ class Label extends BaseBillboard {
/**
* Label outline color.
* @private
* @type {og.Vec4}
* @type {Vec4}
*/
this._outlineColor = utils.createColorRGBA(options.outlineColor, new Vec4(0.0, 0.0, 0.0, 1.0));
this._outlineColor = utils.createColorRGBA(
options.outlineColor,
new Vec4(0.0, 0.0, 0.0, 1.0)
);
/**
* Text horizontal align: "left", "right" and "center".
* @private
* @type {og.Label.ALIGN}
* @type {Label.ALIGN}
*/
this._align = options.align ? STR2ALIGN[options.align.trim().toLowerCase()] || ALIGN.RIGHT : ALIGN.RIGHT;
this._align = options.align
? STR2ALIGN[options.align.trim().toLowerCase()] || ALIGN.RIGHT
: ALIGN.RIGHT;
/**
* Label font atlas index.
@ -103,7 +108,7 @@ class Label extends BaseBillboard {
/**
* Font atlas pointer.
* @private
* @type {og.utils.FontAtlas}
* @type {utils.FontAtlas}
*/
this._fontAtlas = null;
}
@ -116,7 +121,8 @@ class Label extends BaseBillboard {
*/
setText(text) {
this._text = text.toString();
this._handler && this._handler.setText(this._handlerIndex, text, this._fontIndex, this._align);
this._handler &&
this._handler.setText(this._handlerIndex, text, this._fontIndex, this._align);
}
/**
@ -131,17 +137,18 @@ class Label extends BaseBillboard {
/**
* Sets label text align. Could be center, left or right. Left is default.
* @public
* @param {og.Label.ALIGN} align - Text align.
* @param {Label.ALIGN} align - Text align.
*/
setAlign(align) {
this._align = STR2ALIGN[align.trim().toLowerCase()];
this._handler && this._handler.setText(this._handlerIndex, this._text, this._fontIndex, this._align);
this._handler &&
this._handler.setText(this._handlerIndex, this._text, this._fontIndex, this._align);
}
/**
* Gets label text current alignment.
* @public
* @returns {og.Label.ALIGN}
* @returns {Label.ALIGN}
*/
getAlign() {
return this._align;
@ -235,7 +242,7 @@ class Label extends BaseBillboard {
/**
* Sets text outline color.
* @public
* @param {og.Vec4} rgba - Color vector.
* @param {Vec4} rgba - Color vector.
*/
setOutlineColor4v(rgba) {
this._outlineColor.x = rgba.x;
@ -257,7 +264,7 @@ class Label extends BaseBillboard {
/**
* Gets outline color vector.
* @public
* @returns {og.Vec4}
* @returns {Vec4}
*/
getOutlineColor() {
return this._outlineColor;
@ -286,11 +293,10 @@ class Label extends BaseBillboard {
* Updates label parameters.
* @public
*/
update() {
async update() {
if (this._fontAtlas) {
this._fontAtlas.getFontIndex(this._face).then((fontIndex) => {
const fontIndex = await this._fontAtlas.getFontIndex(this._face);
this._applyFontIndex(fontIndex);
});
}
}
@ -305,7 +311,7 @@ class Label extends BaseBillboard {
/**
* Assigns font atlas and update.
* @public
* @param {og.utils.FontAtlas} fontAtlas - Font atlas.
* @param {utils.FontAtlas} fontAtlas - Font atlas.
*/
assignFontAtlas(fontAtlas) {
!this._fontAtlas && (this._fontAtlas = fontAtlas);

View File

@ -30,6 +30,11 @@ window.dZ = 1.1;
*
*/
class LabelHandler extends BillboardHandler {
/**
*
* @param {*} entityCollection
* @param {*} maxLetters
*/
constructor(entityCollection, maxLetters = 21) {
super(entityCollection);
@ -1151,8 +1156,6 @@ class LabelHandler extends BillboardHandler {
}
setFontIndexArr(index, fontIndex) {
fontIndex = fontIndex;
var i = index * 6 * this._maxLetters;
var a = this._fontIndexArr;

View File

@ -1,21 +1,20 @@
/* eslint-disable no-param-reassign */
'use strict';
"use strict";
import { htmlColorToFloat32Array } from '../utils/shared.js';
import { Vec3 } from '../math/Vec3.js';
import { htmlColorToFloat32Array } from "../utils/shared.js";
import { Vec3 } from "../math/Vec3.js";
function getColor(color) {
if (color instanceof Array) {
return color;
} else if (typeof color === 'string') {
} else if (typeof color === "string") {
return htmlColorToFloat32Array(color);
}
return [1.0, 1.0, 1.0, 1.0];
};
}
class Object3d {
constructor(data) {
this._name = data.name || "noname";
this._vertices = data.vertices || [];
this._texCoords = [];
@ -58,11 +57,15 @@ class Object3d {
for (let i = 0; i < vertices.length; i++) {
vertices[i] *= s;
}
};
}
static centroid(vertices) {
let minX = 1000.0, minY = 1000.0, minZ = 1000.0,
maxX = -1000.0, maxY = -1000.0, maxZ = -1000.0;
let minX = 1000.0,
minY = 1000.0,
minZ = 1000.0,
maxX = -1000.0,
maxY = -1000.0,
maxZ = -1000.0;
for (let i = 0; i < vertices.length; i += 3) {
let x = vertices[i],
@ -76,12 +79,8 @@ class Object3d {
if (z > maxZ) maxZ = z;
}
return [
minX + (maxX - minX) * 0.5,
minY + (maxY - minY) * 0.5,
minZ + (maxZ - minZ) * 0.5
];
};
return [minX + (maxX - minX) * 0.5, minY + (maxY - minY) * 0.5, minZ + (maxZ - minZ) * 0.5];
}
static translate(vertices, v) {
for (let i = 0; i < vertices.length; i += 3) {
@ -89,13 +88,12 @@ class Object3d {
vertices[i + 1] -= v[1];
vertices[i + 2] -= v[2];
}
};
}
static getNormals(vertices) {
let res = new Array(vertices.length);
for (var i = 0; i < vertices.length; i += 9) {
let t03 = i,
t13 = i + 3,
t23 = i + 6,
@ -140,19 +138,25 @@ class Object3d {
return res;
}
static createSphere(lonBands = 16, latBands = 16, radius = 1.0, offsetX = 0, offsetY = 0, offsetZ = 0) {
static createSphere(
lonBands = 16,
latBands = 16,
radius = 1.0,
offsetX = 0,
offsetY = 0,
offsetZ = 0
) {
let vertices = [],
indexes = [],
normals = [];
for (let latNumber = 0; latNumber <= latBands; latNumber++) {
var theta = latNumber * Math.PI / latBands;
var theta = (latNumber * Math.PI) / latBands;
var sinTheta = Math.sin(theta);
var cosTheta = Math.cos(theta);
for (let longNumber = 0; longNumber <= lonBands; longNumber++) {
var phi = longNumber * 2 * Math.PI / lonBands;
var phi = (longNumber * 2 * Math.PI) / lonBands;
var sinPhi = Math.sin(phi);
var cosPhi = Math.cos(phi);
var x = cosPhi * sinTheta + offsetX;
@ -173,7 +177,7 @@ class Object3d {
for (let latNumber = 0; latNumber < latBands; latNumber++) {
for (let longNumber = 0; longNumber < lonBands; longNumber++) {
var first = (latNumber * (lonBands + 1)) + longNumber;
var first = latNumber * (lonBands + 1) + longNumber;
var second = first + lonBands + 1;
indexes.push(first);
@ -187,14 +191,22 @@ class Object3d {
}
return new Object3d({
'vertices': vertices,
'normals': normals,
'indexes': indexes
vertices: vertices,
normals: normals,
indexes: indexes
});
}
static createDisc(radius = 1.0, height = 0.0, radialSegments = 8, isTop = true, startIndex = 0, offsetX = 0, offsetY, offsetZ = 0) {
static createDisc(
radius = 1.0,
height = 0.0,
radialSegments = 8,
isTop = true,
startIndex = 0,
offsetX = 0,
offsetY,
offsetZ = 0
) {
let vertices = [],
indexes = [],
normals = [];
@ -202,7 +214,7 @@ class Object3d {
let thetaStart = 0.0,
thetaLength = Math.PI * 2;
let sign = (isTop === true) ? 1.0 : -1.0;
let sign = isTop === true ? 1.0 : -1.0;
let centerIndexStart = startIndex;
@ -216,14 +228,17 @@ class Object3d {
let centerIndexEnd = startIndex;
for (let x = 0; x <= radialSegments; x++) {
let u = x / radialSegments;
let theta = u * thetaLength + thetaStart;
let cosTheta = Math.cos(theta);
let sinTheta = Math.sin(theta);
vertices.push(radius * sinTheta + offsetX, height * sign + offsetY, radius * cosTheta + offsetZ);
vertices.push(
radius * sinTheta + offsetX,
height * sign + offsetY,
radius * cosTheta + offsetZ
);
normals.push(0, sign, 0);
//texCoords.push((cosTheta * 0.5) + 0.5, (sinTheta * 0.5 * sign) + 0.5);
@ -241,14 +256,24 @@ class Object3d {
}
return new Object3d({
'vertices': vertices,
'normals': normals,
'indexes': indexes
vertices: vertices,
normals: normals,
indexes: indexes
});
}
static createCylinder(radiusTop = 1.0, radiusBottom = 1.0, height = 1.0, radialSegments = 32, heightSegments = 1.0, isTop = true, isBottom = true, offsetX = 0, offsetY = 0, offsetZ = 0) {
static createCylinder(
radiusTop = 1.0,
radiusBottom = 1.0,
height = 1.0,
radialSegments = 32,
heightSegments = 1.0,
isTop = true,
isBottom = true,
offsetX = 0,
offsetY = 0,
offsetZ = 0
) {
let vertices = [],
indexes = [],
normals = [];
@ -264,7 +289,6 @@ class Object3d {
var slope = (radiusBottom - radiusTop) / height;
for (let y = 0; y <= heightSegments; y++) {
let indexRow = [];
let v = y / heightSegments;
@ -272,7 +296,6 @@ class Object3d {
let radius = v * (radiusBottom - radiusTop) + radiusTop;
for (let x = 0; x <= radialSegments; x++) {
let u = x / radialSegments;
let theta = u * thetaLength + thetaStart;
@ -280,7 +303,11 @@ class Object3d {
let sinTheta = Math.sin(theta),
cosTheta = Math.cos(theta);
vertices.push(radius * sinTheta + offsetX, -v * height + height + offsetY, radius * cosTheta + offsetZ);
vertices.push(
radius * sinTheta + offsetX,
-v * height + height + offsetY,
radius * cosTheta + offsetZ
);
normal.set(sinTheta, slope, cosTheta).normalize();
normals.push(normal.x, normal.y, normal.z);
@ -294,7 +321,6 @@ class Object3d {
for (let x = 0; x < radialSegments; x++) {
for (let y = 0; y < heightSegments; y++) {
let a = indexArray[y][x],
b = indexArray[y + 1][x],
c = indexArray[y + 1][x + 1],
@ -306,23 +332,41 @@ class Object3d {
}
if (radiusTop !== 0.0 && isTop) {
let cap = Object3d.createDisc(radiusTop, height, radialSegments, true, index, offsetX, offsetY, offsetZ);
let cap = Object3d.createDisc(
radiusTop,
height,
radialSegments,
true,
index,
offsetX,
offsetY,
offsetZ
);
vertices.push(...cap.vertices);
normals.push(...cap.normals);
indexes.push(...cap.indexes);
}
if (radiusBottom !== 0.0 && isBottom) {
let cap = Object3d.createDisc(radiusBottom, 0, radialSegments, false, index + (isTop ? (1 + 2 * radialSegments) : 0), offsetX, offsetY, offsetZ);
let cap = Object3d.createDisc(
radiusBottom,
0,
radialSegments,
false,
index + (isTop ? 1 + 2 * radialSegments : 0),
offsetX,
offsetY,
offsetZ
);
vertices.push(...cap.vertices);
normals.push(...cap.normals);
indexes.push(...cap.indexes);
}
return new Object3d({
'vertices': vertices,
'normals': normals,
'indexes': indexes
vertices: vertices,
normals: normals,
indexes: indexes
});
}
@ -334,52 +378,124 @@ class Object3d {
return new Object3d({
vertices: [
//bottom
-l, -h, d,
l, -h, -d,
l, -h, d,
-l, -h, d,
-l, -h, -d,
l, -h, -d,
-l,
-h,
d,
l,
-h,
-d,
l,
-h,
d,
-l,
-h,
d,
-l,
-h,
-d,
l,
-h,
-d,
//top
-l, h, d,
l, h, d,
l, h, -d,
-l, h, d,
l, h, -d,
-l, h, -d,
-l,
h,
d,
l,
h,
d,
l,
h,
-d,
-l,
h,
d,
l,
h,
-d,
-l,
h,
-d,
//front
-l, -h, d,
l, -h, d,
-l, h, d,
-l, h, d,
l, -h, d,
l, h, d,
-l,
-h,
d,
l,
-h,
d,
-l,
h,
d,
-l,
h,
d,
l,
-h,
d,
l,
h,
d,
//back
-l, -h, -d,
-l, h, -d,
l, -h, -d,
-l, h, -d,
l, h, -d,
l, -h, -d,
-l,
-h,
-d,
-l,
h,
-d,
l,
-h,
-d,
-l,
h,
-d,
l,
h,
-d,
l,
-h,
-d,
//left
l, -h, d,
l, -h, -d,
l, h, d,
l, h, d,
l, -h, -d,
l, h, -d,
l,
-h,
d,
l,
-h,
-d,
l,
h,
d,
l,
h,
d,
l,
-h,
-d,
l,
h,
-d,
//right
-l, -h, d,
-l, h, d,
-l, -h, -d,
-l, h, d,
-l, h, -d,
-l, -h, -d
-l,
-h,
d,
-l,
h,
d,
-l,
-h,
-d,
-l,
h,
d,
-l,
h,
-d,
-l,
-h,
-d
]
});
}

View File

@ -2,10 +2,10 @@
* @module og/entity/PointCloud
*/
'use strict';
"use strict";
import { Vec3 } from '../math/Vec3.js';
import { Vec4 } from '../math/Vec4.js';
import { Vec3 } from "../math/Vec3.js";
import { Vec4 } from "../math/Vec4.js";
const COORDINATES_BUFFER = 0;
const COLOR_BUFFER = 1;
@ -33,7 +33,6 @@ const PICKING_COLOR_BUFFER = 2;
*/
class PointCloud {
constructor(options) {
options = options || {};
/**
@ -49,7 +48,7 @@ class PointCloud {
* @public
* @type {boolean}
*/
this.visibility = (options.visibility != undefined ? options.visibility : true);
this.visibility = options.visibility != undefined ? options.visibility : true;
/**
* Point screen size in pixels.
@ -68,14 +67,14 @@ class PointCloud {
/**
* Parent collection render node.
* @private
* @type {og.scene.RenderNode}
* @type {RenderNode}
*/
this._renderNode = null;
/**
* Entity instance that holds this point cloud.
* @private
* @type {og.Entity}
* @type {Entity}
*/
this._entity = null;
@ -114,7 +113,7 @@ class PointCloud {
/**
* Handler that stores and renders this object.
* @private
* @type {og.PointCloudHandler}
* @type {PointCloudHandler}
*/
this._handler = null;
this._handlerIndex = -1;
@ -145,7 +144,6 @@ class PointCloud {
* @public
*/
clear() {
this._points.length = 0;
this._points = [];
@ -189,7 +187,7 @@ class PointCloud {
/**
* Assign rendering scene node.
* @public
* @param {og.scene.RenderNode} renderNode - Assigned render node.
* @param {RenderNode} renderNode - Assigned render node.
*/
setRenderNode(renderNode) {
this._renderNode = renderNode;
@ -217,7 +215,7 @@ class PointCloud {
for (var i = 0; i < points.length; i++) {
var pi = points[i];
var pos = new Vec3(pi[0], pi[1], pi[2]),
col = new Vec4(pi[3], pi[4], pi[5], (pi[6] == undefined ? 255.0 : pi[6]));
col = new Vec4(pi[3], pi[4], pi[5], pi[6] == undefined ? 255.0 : pi[6]);
this._coordinatesData.push(pos.x, pos.y, pos.z);
this._colorData.push(col.x / 255.0, col.y / 255.0, col.z / 255.0, col.w / 255.0);
var p = {
@ -233,7 +231,12 @@ class PointCloud {
if (this._renderNode) {
this._renderNode.renderer.assignPickingColor(p);
this._pickingColorData.push(p._pickingColor.x / 255.0, p._pickingColor.y / 255.0, p._pickingColor.z / 255.0, 1.0);
this._pickingColorData.push(
p._pickingColor.x / 255.0,
p._pickingColor.y / 255.0,
p._pickingColor.z / 255.0,
1.0
);
}
}
@ -243,21 +246,18 @@ class PointCloud {
}
setPointPosition(index, x, y, z) {
// TODO: ...
this._changedBuffers[COORDINATES_BUFFER] = true;
}
setPointColor(index, r, g, b, a) {
// TODO: ...
this._changedBuffers[COLOR_BUFFER] = true;
}
addPoints(points) {
// TODO: ...
this._changedBuffers[COORDINATES_BUFFER] = true;
@ -266,7 +266,6 @@ class PointCloud {
}
addPoint(index, point) {
// TODO: ...
this._changedBuffers[COORDINATES_BUFFER] = true;
@ -285,7 +284,6 @@ class PointCloud {
}
removePoint(index) {
// TODO: ...
this._changedBuffers[COORDINATES_BUFFER] = true;
@ -294,7 +292,6 @@ class PointCloud {
}
insertPoint(index, point) {
// TODO: ...
this._changedBuffers[COORDINATES_BUFFER] = true;
@ -316,7 +313,6 @@ class PointCloud {
draw() {
if (this.visibility && this._coordinatesData.length) {
this._update();
var rn = this._renderNode;
@ -327,18 +323,32 @@ class PointCloud {
sha = p.attributes,
shu = p.uniforms;
gl.polygonOffset(this._handler._entityCollection.polygonOffsetFactor, this._handler._entityCollection.polygonOffsetUnits);
gl.polygonOffset(
this._handler._entityCollection.polygonOffsetFactor,
this._handler._entityCollection.polygonOffsetUnits
);
sh.activate();
gl.uniformMatrix4fv(shu.projectionViewMatrix, false, r.activeCamera._projectionViewMatrix._m);
gl.uniformMatrix4fv(
shu.projectionViewMatrix,
false,
r.activeCamera._projectionViewMatrix._m
);
gl.uniform1f(shu.opacity, this._handler._entityCollection._fadingOpacity);
gl.uniform1f(shu.pointSize, this.pointSize);
gl.bindBuffer(gl.ARRAY_BUFFER, this._coordinatesBuffer);
gl.vertexAttribPointer(sha.coordinates, this._coordinatesBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.coordinates,
this._coordinatesBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.bindBuffer(gl.ARRAY_BUFFER, this._colorBuffer);
gl.vertexAttribPointer(sha.colors, this._colorBuffer.itemSize, gl.FLOAT, false, 0, 0);
@ -359,19 +369,40 @@ class PointCloud {
sh.activate();
gl.polygonOffset(this._handler._entityCollection.polygonOffsetFactor, this._handler._entityCollection.polygonOffsetUnits);
gl.polygonOffset(
this._handler._entityCollection.polygonOffsetFactor,
this._handler._entityCollection.polygonOffsetUnits
);
gl.uniformMatrix4fv(shu.projectionViewMatrix, false, r.activeCamera._projectionViewMatrix._m);
gl.uniformMatrix4fv(
shu.projectionViewMatrix,
false,
r.activeCamera._projectionViewMatrix._m
);
gl.uniform1f(shu.opacity, this._handler._entityCollection._fadingOpacity);
gl.uniform1f(shu.pointSize, this.pointSize + this.pickingDistance);
gl.bindBuffer(gl.ARRAY_BUFFER, this._coordinatesBuffer);
gl.vertexAttribPointer(sha.coordinates, this._coordinatesBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.coordinates,
this._coordinatesBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.bindBuffer(gl.ARRAY_BUFFER, this._pickingColorBuffer);
gl.vertexAttribPointer(sha.colors, this._pickingColorBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.colors,
this._pickingColorBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.drawArrays(gl.POINTS, 0, this._coordinatesBuffer.numItems);
}
@ -415,19 +446,31 @@ class PointCloud {
_createCoordinatesBuffer() {
var h = this._renderNode.renderer.handler;
h.gl.deleteBuffer(this._coordinatesBuffer);
this._coordinatesBuffer = h.createArrayBuffer(new Float32Array(this._coordinatesData), 3, (this._coordinatesData.length) / 3);
this._coordinatesBuffer = h.createArrayBuffer(
new Float32Array(this._coordinatesData),
3,
this._coordinatesData.length / 3
);
}
_createColorBuffer() {
var h = this._renderNode.renderer.handler;
h.gl.deleteBuffer(this._colorBuffer);
this._colorBuffer = h.createArrayBuffer(new Float32Array(this._colorData), 4, (this._colorData.length) / 4);
this._colorBuffer = h.createArrayBuffer(
new Float32Array(this._colorData),
4,
this._colorData.length / 4
);
}
_createPickingColorBuffer() {
var h = this._renderNode.renderer.handler;
h.gl.deleteBuffer(this._pickingColorBuffer);
this._pickingColorBuffer = h.createArrayBuffer(new Float32Array(this._pickingColorData), 4, (this._pickingColorData.length) / 4);
this._pickingColorBuffer = h.createArrayBuffer(
new Float32Array(this._pickingColorData),
4,
this._pickingColorData.length / 4
);
}
_setPickingColors() {
@ -437,7 +480,12 @@ class PointCloud {
p._entity = this._entity;
p._entityCollection = this._entity._entityCollection;
this._renderNode.renderer.assignPickingColor(p);
this._pickingColorData.push(p._pickingColor.x / 255.0, p._pickingColor.y / 255.0, p._pickingColor.z / 255.0, 1.0);
this._pickingColorData.push(
p._pickingColor.x / 255.0,
p._pickingColor.y / 255.0,
p._pickingColor.z / 255.0,
1.0
);
}
this._changedBuffers[PICKING_COLOR_BUFFER] = true;
}

View File

@ -2,13 +2,12 @@
* @module og/entity/PointCloudHandler
*/
'use strict';
"use strict";
import * as shaders from '../shaders/pointCloud.js';
import * as shaders from "../shaders/pointCloud.js";
class PointCloudHandler {
constructor(entityCollection) {
/**
* Picking rendering option.
* @public
@ -19,21 +18,21 @@ class PointCloudHandler {
/**
* Parent collection
* @private
* @type {og.EntityCollection}
* @type {EntityCollection}
*/
this._entityCollection = entityCollection;
/**
* Renderer
* @private
* @type {og.Renderer}
* @type {Renderer}
*/
this._renderer = null;
/**
* Point cloud array
* @private
* @type {Array.<og.PointCloud>}
* @type {Array.<PointCloud>}
*/
this._pointClouds = [];
@ -72,7 +71,8 @@ class PointCloudHandler {
pointCloud._handler = this;
pointCloud._handlerIndex = this._pointClouds.length;
this._pointClouds.push(pointCloud);
this._entityCollection && this._entityCollection.renderNode &&
this._entityCollection &&
this._entityCollection.renderNode &&
pointCloud.setRenderNode(this._entityCollection.renderNode);
}
}

View File

@ -32,7 +32,7 @@ const A = 3;
* @param {Object} [options] - Polyline options:
* @param {number} [options.thickness] - Thickness in screen pixels 1.5 is default.
* @param {Number} [options.altitude] - Relative to ground layers altitude value.
* @param {og.Vec4} [options.color] - RGBA color.
* @param {Vec4} [options.color] - RGBA color.
* @param {Boolean} [options.opacity] - Line opacity.
* @param {Boolean} [options.visibility] - Polyline visibility. True default.
* @param {Boolean} [options.isClosed] - Closed geometry type identificator.
@ -88,7 +88,7 @@ class Polyline {
/**
* Polyline cartesian coordinates.
* @private
* @type {Array.<og.Vec3>}
* @type {Array.<Vec3>}
*/
this._path3v = [];
@ -113,7 +113,7 @@ class Polyline {
/**
* Polyline geodetic extent.
* @protected
* @type {og.Extent}
* @type {Extent}
*/
this._extent = new Extent();
@ -136,14 +136,14 @@ class Polyline {
/**
* Entity instance that holds this Polyline.
* @private
* @type {og.Entity}
* @type {Entity}
*/
this._entity = null;
/**
* Handler that stores and renders this Polyline object.
* @private
* @type {og.PolylineHandler}
* @type {PolylineHandler}
*/
this._handler = null;
this._handlerIndex = -1;
@ -183,11 +183,11 @@ class Polyline {
* @param {Number[]} outVertices - Out vertices data array.
* @param {Number[]} outOrders - Out vertices orders data array.
* @param {Number[]} outIndexes - Out vertices indexes data array.
* @param {og.Ellipsoid} [ellipsoid] - Ellipsoid to coordinates transformation.
* @param {Ellipsoid} [ellipsoid] - Ellipsoid to coordinates transformation.
* @param {Array.<Array.<LonLat>>} [outTransformedPathLonLat] - Geodetic coordinates out array.
* @param {Array.<Array.<LonLat>>} [outPath3v] - Cartesian coordinates out array.
* @param {Array.<Array.<LonLat>>} [outTransformedPathMerc] - Mercator coordinates out array.
* @param {og.Extent} [outExtent] - Geodetic line extent.
* @param {Extent} [outExtent] - Geodetic line extent.
* @param {Array} [outColors]
* @static
*/
@ -454,11 +454,11 @@ class Polyline {
* @param {Number[]} outVertices - Out vertices data array.
* @param {Number[]} outOrders - Out vertices orders data array.
* @param {Number[]} outIndexes - Out vertices indexes data array.
* @param {og.Ellipsoid} [ellipsoid] - Ellipsoid to coordinates transformation.
* @param {Ellipsoid} [ellipsoid] - Ellipsoid to coordinates transformation.
* @param {Array.<Array.<LonLat>>} [outTransformedPathLonLat] - Geodetic coordinates out array.
* @param {Array.<Array.<LonLat>>} [outPath3v] - Cartesian coordinates out array.
* @param {Array.<Array.<LonLat>>} [outTransformedPathMerc] - Mercator coordinates out array.
* @param {og.Extent} [outExtent] - Geodetic line extent.
* @param {Extent} [outExtent] - Geodetic line extent.
* @static
*/
static appendPoint3v(
@ -706,11 +706,11 @@ class Polyline {
* @param {Number[]} outVertices - Out vertices data array.
* @param {Number[]} outOrders - Out vertices orders data array.
* @param {Number[]} outIndexes - Out indexes data array.
* @param {og.Ellipsoid} ellipsoid - Ellipsoid to coordinates transformation.
* @param {Ellipsoid} ellipsoid - Ellipsoid to coordinates transformation.
* @param {Array.<Array.<number>>} outTransformedPathCartesian - Cartesian coordinates out array. [[0,0,0], [1,1,1],...]
* @param {Array.<Array.<LonLat>>} outPathLonLat - Geographic coordinates out array.
* @param {Array.<Array.<LonLat>>} outTransformedPathMerc - Mercator coordinates out array.
* @param {og.Extent} outExtent - Geodetic line extent.
* @param {Extent} outExtent - Geodetic line extent.
* @static
*/
static appendLineDataLonLat(
@ -1579,7 +1579,7 @@ class Polyline {
/**
* Adds a new cartesian point in the end of the path in a last line segment.
* @public
* @param {og.Vec3} point3v - New coordinate.
* @param {Vec3} point3v - New coordinate.
*/
appendPoint3v(point3v, color, skipEllipsoid) {
if (this._path3v.length === 0) {
@ -1623,7 +1623,7 @@ class Polyline {
/**
* Adds a new cartesian point in the end of the path.
* @public
* @param {og.Vec3} point3v - New coordinate.
* @param {Vec3} point3v - New coordinate.
* @param {number} [multiLineIndex=0] - Path part index, first by default.
*/
addPoint3v(point3v, multiLineIndex = 0) {
@ -1752,7 +1752,7 @@ class Polyline {
/**
* Assign with render node.
* @public
* @param {og.scene.RenderNode} renderNode -
* @param {RenderNode} renderNode -
*/
setRenderNode(renderNode) {
if (renderNode) {
@ -1870,7 +1870,7 @@ class Polyline {
/**
* Returns polyline geodetic extent.
* @public
* @returns {og.Extent} - Geodetic extent
* @returns {Extent} - Geodetic extent
*/
getExtent() {
return this._extent.clone();
@ -1878,7 +1878,7 @@ class Polyline {
/**
* Returns path cartesian coordinates.
* @return {Array.<og.Vec3>} Polyline path.
* @return {Array.<Vec3>} Polyline path.
*/
getPath3v() {
return this._path3v;

View File

@ -2,21 +2,21 @@
* @module og/entity/BaseBillboard
*/
'use strict';
"use strict";
import * as utils from '../utils/shared.js';
import { Vec3 } from '../math/Vec3.js';
import { Entity } from './Entity.js';
import { doubleToTwoFloats2 } from '../math/coder.js';
import * as utils from "../utils/shared.js";
import { Vec3 } from "../math/Vec3.js";
import { Entity } from "./Entity.js";
import { doubleToTwoFloats2 } from "../math/coder.js";
/**
* Ray class.
* @class
* @param {Object} [options] - Options:
* @param {og.Vec3|Array.<number>} [options.startPosition] - Ray start point position.
* @param {og.Vec3|Array.<number>} [options.endPosition] - Ray end point position.
* @param {og.Vec3|Array.<number>} [options.startColor] - Ray start point color.
* @param {og.Vec3|Array.<number>} [options.endColor] - Ray end point color.
* @param {Vec3|Array.<number>} [options.startPosition] - Ray start point position.
* @param {Vec3|Array.<number>} [options.endPosition] - Ray end point position.
* @param {Vec3|Array.<number>} [options.startColor] - Ray start point color.
* @param {Vec3|Array.<number>} [options.endColor] - Ray end point color.
* @param {boolean} [options.visibility] - Visibility.
*/
class Ray {
@ -43,7 +43,11 @@ class Ray {
this._startPosition = utils.createVector3(options.startPosition);
this._startPositionHigh = new Vec3();
this._startPositionLow = new Vec3();
Vec3.doubleToTwoFloats(this._startPosition, this._startPositionHigh, this._startPositionLow);
Vec3.doubleToTwoFloats(
this._startPosition,
this._startPositionHigh,
this._startPositionLow
);
// RTE end position
this._endPosition = utils.createVector3(options.endPosition);
@ -65,14 +69,14 @@ class Ray {
/**
* Entity instance that holds this billboard.
* @protected
* @type {og.Entity}
* @type {Entity}
*/
this._entity = null;
/**
* Handler that stores and renders this billboard object.
* @protected
* @type {og.BillboardHandler}
* @type {BillboardHandler}
*/
this._handler = null;
@ -95,21 +99,39 @@ class Ray {
this._startPosition.x = x;
this._startPosition.y = y;
this._startPosition.z = z;
Vec3.doubleToTwoFloats(this._startPosition, this._startPositionHigh, this._startPositionLow);
this._handler && this._handler.setStartPositionArr(this._handlerIndex, this._startPositionHigh, this._startPositionLow);
Vec3.doubleToTwoFloats(
this._startPosition,
this._startPositionHigh,
this._startPositionLow
);
this._handler &&
this._handler.setStartPositionArr(
this._handlerIndex,
this._startPositionHigh,
this._startPositionLow
);
}
/**
* Sets ray start position.
* @public
* @param {og.Vec3} position - Cartesian coordinates.
* @param {Vec3} position - Cartesian coordinates.
*/
setStartPosition3v(position) {
this._startPosition.x = position.x;
this._startPosition.y = position.y;
this._startPosition.z = position.z;
Vec3.doubleToTwoFloats(this._startPosition, this._startPositionHigh, this._startPositionLow);
this._handler && this._handler.setStartPositionArr(this._handlerIndex, this._startPositionHigh, this._startPositionLow);
Vec3.doubleToTwoFloats(
this._startPosition,
this._startPositionHigh,
this._startPositionLow
);
this._handler &&
this._handler.setStartPositionArr(
this._handlerIndex,
this._startPositionHigh,
this._startPositionLow
);
}
/**
@ -124,20 +146,30 @@ class Ray {
this._endPosition.y = y;
this._endPosition.z = z;
Vec3.doubleToTwoFloats(this._endPosition, this._endPositionHigh, this._endPositionLow);
this._handler && this._handler.setEndPositionArr(this._handlerIndex, this._endPositionHigh, this._endPositionLow);
this._handler &&
this._handler.setEndPositionArr(
this._handlerIndex,
this._endPositionHigh,
this._endPositionLow
);
}
/**
* Sets ray end position.
* @public
* @param {og.Vec3} position - Cartesian coordinates.
* @param {Vec3} position - Cartesian coordinates.
*/
setEndPosition3v(position) {
this._endPosition.x = position.x;
this._endPosition.y = position.y;
this._endPosition.z = position.z;
Vec3.doubleToTwoFloats(this._endPosition, this._endPositionHigh, this._endPositionLow);
this._handler && this._handler.setEndPositionArr(this._handlerIndex, this._endPositionHigh, this._endPositionLow);
this._handler &&
this._handler.setEndPositionArr(
this._handlerIndex,
this._endPositionHigh,
this._endPositionLow
);
}
setLength(length) {
@ -165,11 +197,11 @@ class Ray {
this._endColor.w = endColor.w;
}
this._handler && this._handler.setRgbaArr(this._handlerIndex, this._startColor, this._endColor);
this._handler &&
this._handler.setRgbaArr(this._handlerIndex, this._startColor, this._endColor);
}
setColorsHTML(startColor, endColor) {
if (startColor) {
this._startColor = utils.htmlColorToRgba(startColor);
}
@ -178,13 +210,14 @@ class Ray {
this._endColor = utils.htmlColorToRgba(endColor);
}
this._handler && this._handler.setRgbaArr(this._handlerIndex, this._startColor, this._endColor);
this._handler &&
this._handler.setRgbaArr(this._handlerIndex, this._startColor, this._endColor);
}
/**
* Returns ray start position.
* @public
* @returns {og.Vec3}
* @returns {Vec3}
*/
getStartPosition() {
return this._startPosition;
@ -193,7 +226,7 @@ class Ray {
/**
* Returns ray end position.
* @public
* @returns {og.Vec3}
* @returns {Vec3}
*/
getEndPosition() {
return this._endPosition;
@ -230,7 +263,7 @@ class Ray {
/**
* Sets billboard picking color.
* @public
* @param {og.Vec3} color - Picking color.
* @param {Vec3} color - Picking color.
*/
setPickingColor3v(color) {
this._handler && this._handler.setPickingColorArr(this._handlerIndex, color);

View File

@ -1,8 +1,8 @@
'use strict';
"use strict";
import * as utils from '../utils/shared.js';
import { Vec3 } from '../math/Vec3.js';
import { Line3 } from '../math/Line3.js';
import * as utils from "../utils/shared.js";
import { Vec3 } from "../math/Vec3.js";
import { Line3 } from "../math/Line3.js";
let _tempHigh = new Vec3(),
_tempLow = new Vec3();
@ -25,7 +25,6 @@ let _tempHigh = new Vec3(),
*/
class Strip {
constructor(options) {
options = options || {};
/**
@ -41,7 +40,7 @@ class Strip {
* @public
* @type {boolean}
*/
this.visibility = (options.visibility != undefined ? options.visibility : true);
this.visibility = options.visibility != undefined ? options.visibility : true;
this.color = new Float32Array([1.0, 1.0, 1.0, 0.5]);
@ -57,14 +56,14 @@ class Strip {
/**
* Parent collection render node.
* @private
* @type {og.scene.RenderNode}
* @type {RenderNode}
*/
this._renderNode = null;
/**
* Entity instance that holds this strip.
* @private
* @type {og.Entity}
* @type {Entity}
*/
this._entity = null;
@ -87,7 +86,7 @@ class Strip {
/**
* Handler that stores and renders this object.
* @private
* @type {og.StripHandler}
* @type {StripHandler}
*/
this._handler = null;
this._handlerIndex = -1;
@ -111,7 +110,7 @@ class Strip {
/**
* Assign picking color.
* @protected
* @param {og.Vec3} color - Picking RGB color.
* @param {Vec3} color - Picking RGB color.
*/
setPickingColor3v(color) {
this._pickingColor[0] = color.x / 255.0;
@ -125,7 +124,6 @@ class Strip {
* @public
*/
clear() {
this._path.length = 0;
this._path = [];
@ -177,7 +175,7 @@ class Strip {
/**
* Assign rendering scene node.
* @public
* @param {og.scene.RenderNode} renderNode - Assigned render node.
* @param {RenderNode} renderNode - Assigned render node.
*/
setRenderNode(renderNode) {
this._renderNode = renderNode;
@ -219,11 +217,30 @@ class Strip {
gl.uniform4fv(shu.uColor, this.color);
gl.uniform1f(shu.uOpacity, this._entity._entityCollection._fadingOpacity);
gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesHighBuffer);
gl.vertexAttribPointer(sha.aVertexPositionHigh, this._verticesHighBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.aVertexPositionHigh,
this._verticesHighBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesLowBuffer);
gl.vertexAttribPointer(sha.aVertexPositionLow, this._verticesLowBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.aVertexPositionLow,
this._verticesLowBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
gl.drawElements(r.handler.gl.TRIANGLE_STRIP, this._indexBuffer.numItems, gl.UNSIGNED_INT, 0);
gl.drawElements(
r.handler.gl.TRIANGLE_STRIP,
this._indexBuffer.numItems,
gl.UNSIGNED_INT,
0
);
gl.enable(gl.CULL_FACE);
}
}
@ -254,11 +271,30 @@ class Strip {
gl.uniform4fv(shu.uColor, this._pickingColor);
gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesHighBuffer);
gl.vertexAttribPointer(sha.aVertexPositionHigh, this._verticesHighBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.aVertexPositionHigh,
this._verticesHighBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesLowBuffer);
gl.vertexAttribPointer(sha.aVertexPositionLow, this._verticesLowBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
sha.aVertexPositionLow,
this._verticesLowBuffer.itemSize,
gl.FLOAT,
false,
0,
0
);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
gl.drawElements(r.handler.gl.TRIANGLE_STRIP, this._indexBuffer.numItems, gl.UNSIGNED_INT, 0);
gl.drawElements(
r.handler.gl.TRIANGLE_STRIP,
this._indexBuffer.numItems,
gl.UNSIGNED_INT,
0
);
gl.enable(gl.CULL_FACE);
}
}
@ -289,9 +325,21 @@ class Strip {
gl.deleteBuffer(this._verticesHighBuffer);
gl.deleteBuffer(this._verticesLowBuffer);
this._verticesHighBuffer = this._renderNode.renderer.handler.createArrayBuffer(new Float32Array(this._verticesHigh), 3, this._verticesHigh.length / 3);
this._verticesLowBuffer = this._renderNode.renderer.handler.createArrayBuffer(new Float32Array(this._verticesLow), 3, this._verticesLow.length / 3);
this._indexBuffer = this._renderNode.renderer.handler.createElementArrayBuffer(new Uint32Array(this._indexes), 1, this._indexes.length);
this._verticesHighBuffer = this._renderNode.renderer.handler.createArrayBuffer(
new Float32Array(this._verticesHigh),
3,
this._verticesHigh.length / 3
);
this._verticesLowBuffer = this._renderNode.renderer.handler.createArrayBuffer(
new Float32Array(this._verticesLow),
3,
this._verticesLow.length / 3
);
this._indexBuffer = this._renderNode.renderer.handler.createElementArrayBuffer(
new Uint32Array(this._indexes),
1,
this._indexes.length
);
}
}
@ -299,11 +347,8 @@ class Strip {
let length = this._path.length;
if (length === 0) {
this._path.push([p2.clone(), p3.clone()]);
} else {
let p0 = this._path[length - 1][0],
p1 = this._path[length - 1][1];
@ -323,19 +368,17 @@ class Strip {
let d = Math.abs(p0.sub(p1).normal().dot(p2.sub(p0).normal()));
for (let i = 0; i < gs1; i++) {
let di = i / gs;
let p02 = p0.lerp(p2, di),
p13 = p1.lerp(p3, di);
for (let j = 0; j < gs1; j++) {
let dj = j / gs;
let p01 = p0.lerp(p1, dj),
p23 = p2.lerp(p3, dj);
if (d !== 1.0) {
(new Line3(p02, p13)).intersects(new Line3(p01, p23), p);
new Line3(p02, p13).intersects(new Line3(p01, p23), p);
} else {
p = p23;
}
@ -369,17 +412,15 @@ class Strip {
}
setEdge3v(p2, p3, index) {
if (index === this._path.length) {
this.addEdge3v(p2, p3);
return;
} if (this._path[index]) {
}
if (this._path[index]) {
this._path[index][0] = p2;
this._path[index][1] = p3;
if (this._path.length > 1) {
let gs = this._gridSize,
gs1 = gs + 1;
@ -391,7 +432,6 @@ class Strip {
vLow = this._verticesLow;
if (index === this._path.length - 1) {
let p0 = this._path[index - 1][0],
p1 = this._path[index - 1][1];
@ -401,19 +441,17 @@ class Strip {
let d = Math.abs(p0.sub(p1).normal().dot(p2.sub(p0).normal()));
for (let i = 0; i < gs1; i++) {
let di = i / gs;
let p02 = p0.lerp(p2, di),
p13 = p1.lerp(p3, di);
for (let j = 0; j < gs1; j++) {
let dj = j / gs;
let p01 = p0.lerp(p1, dj),
p23 = p2.lerp(p3, dj);
if (d !== 1.0) {
(new Line3(p02, p13)).intersects(new Line3(p01, p23), p);
new Line3(p02, p13).intersects(new Line3(p01, p23), p);
} else {
p = p23;
}
@ -433,9 +471,7 @@ class Strip {
vLow[ind3 + 2] = _tempLow.z;
}
}
} else if (index === 0) {
let ind = 0;
let p0 = p2,
@ -445,18 +481,16 @@ class Strip {
p3 = this._path[1][1];
for (let i = 0; i < gs1; i++) {
let di = i / gs;
let p02 = p0.lerp(p2, di),
p13 = p1.lerp(p3, di);
for (let j = 0; j < gs1; j++) {
let dj = j / gs;
let p01 = p0.lerp(p1, dj),
p23 = p2.lerp(p3, dj);
(new Line3(p02, p13)).intersects(new Line3(p01, p23), p);
new Line3(p02, p13).intersects(new Line3(p01, p23), p);
ind = i * gs1 + j;
@ -474,7 +508,6 @@ class Strip {
}
}
} else if (index > 0 && index < this._path.length) {
let p0 = this._path[index - 1][0],
p1 = this._path[index - 1][1];
@ -486,7 +519,6 @@ class Strip {
ind = prev;
for (let i = 0; i < gs1; i++) {
let di = i / gs;
let p02 = p0.lerp(p2, di),
p35 = p3.lerp(p5, di),
@ -494,13 +526,12 @@ class Strip {
p13 = p1.lerp(p3, di);
for (let j = 0; j < gs1; j++) {
let dj = j / gs;
let p01 = p0.lerp(p1, dj),
p23 = p2.lerp(p3, dj);
// prev
(new Line3(p02, p13)).intersects(new Line3(p01, p23), p);
new Line3(p02, p13).intersects(new Line3(p01, p23), p);
let ij = i * gs1 + j;
@ -523,7 +554,7 @@ class Strip {
p23 = p2.lerp(p3, dj);
(new Line3(p24, p35)).intersects(new Line3(p23, p45), p);
new Line3(p24, p35).intersects(new Line3(p23, p45), p);
ind = next + ij;
@ -564,14 +595,12 @@ class Strip {
}
setPath(path) {
this._verticesHigh = [];
this._verticesLow = [];
this._indexes = [];
this._path = [];
for (let i = 0; i < path.length; i++) {
let p0 = path[i][0],
p1 = path[i][1];

View File

@ -1,10 +1,9 @@
'use strict';
"use strict";
import { Program } from '../webgl/Program.js';
import { Program } from "../webgl/Program.js";
class StripHandler {
constructor(entityCollection) {
/**
* Picking rendering option.
* @public
@ -15,21 +14,21 @@ class StripHandler {
/**
* Parent collection
* @private
* @type {og.EntityCollection}
* @type {EntityCollection}
*/
this._entityCollection = entityCollection;
/**
* Renderer
* @private
* @type {og.Renderer}
* @type {Renderer}
*/
this._renderer = null;
/**
* Point cloud array
* @private
* @type {Array.<og.Strip>}
* @type {Array.<Strip>}
*/
this._strips = [];
@ -50,21 +49,21 @@ class StripHandler {
_initProgram() {
if (this._renderer.handler) {
!this._renderer.handler.programs.strip &&
this._renderer.handler.addProgram(new Program("strip", {
this._renderer.handler.addProgram(
new Program("strip", {
uniforms: {
projectionMatrix: { type: 'mat4' },
viewMatrix: { type: 'mat4' },
projectionMatrix: { type: "mat4" },
viewMatrix: { type: "mat4" },
eyePositionHigh: "vec3",
eyePositionLow: "vec3",
uColor: { type: 'vec4' },
uOpacity: { type: 'float' }
uColor: { type: "vec4" },
uOpacity: { type: "float" }
},
attributes: {
aVertexPositionHigh: { type: 'vec3' },
aVertexPositionLow: { type: 'vec3' }
aVertexPositionHigh: { type: "vec3" },
aVertexPositionLow: { type: "vec3" }
},
vertexShader:
`attribute vec3 aVertexPositionHigh;
vertexShader: `attribute vec3 aVertexPositionHigh;
attribute vec3 aVertexPositionLow;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
@ -80,14 +79,14 @@ class StripHandler {
gl_Position = projectionMatrix * viewMatrixRTE * vec4(highDiff + lowDiff, 1.0);
}`,
fragmentShader:
`precision highp float;
fragmentShader: `precision highp float;
uniform vec4 uColor;
uniform float uOpacity;
void main(void) {
gl_FragColor = vec4(uColor.rgb, uColor.a * uOpacity);
}`
}));
})
);
}
}
@ -104,7 +103,8 @@ class StripHandler {
strip._handler = this;
strip._handlerIndex = this._strips.length;
this._strips.push(strip);
this._entityCollection && this._entityCollection.renderNode &&
this._entityCollection &&
this._entityCollection.renderNode &&
strip.setRenderNode(this._entityCollection.renderNode);
}
}

View File

@ -1,17 +1,9 @@
import { Entity } from './Entity';
import { EntityCollection } from './EntityCollection';
import { Billboard } from './Billboard';
import { Geometry } from './Geometry';
import { Label } from './Label';
import { PointCloud } from './PointCloud';
import { Polyline } from './Polyline';
import { Entity } from "./Entity.js";
import { EntityCollection } from "./EntityCollection.js";
import { Billboard } from "./Billboard.js";
import { Geometry } from "./Geometry.js";
import { Label } from "./Label.js";
import { PointCloud } from "./PointCloud.js";
import { Polyline } from "./Polyline.js";
export {
Entity,
EntityCollection,
Billboard,
Geometry,
Label,
PointCloud,
Polyline
};
export { Entity, EntityCollection, Billboard, Geometry, Label, PointCloud, Polyline };

View File

@ -1,8 +0,0 @@
/**
* @module og/inherits
*/
export function inherits(childCtor, parentCtor) {
childCtor.prototype = Object.create(parentCtor.prototype);
childCtor.prototype.constructor = childCtor;
}

View File

@ -2,17 +2,17 @@
* @module og/layer/BaseGeoImage
*/
'use strict';
"use strict";
import * as mercator from '../mercator.js';
import { Extent } from '../Extent.js';
import { Layer } from './Layer.js';
import { LonLat } from '../LonLat.js';
import * as mercator from "../mercator.js";
import { Extent } from "../Extent.js";
import { Layer } from "./Layer.js";
import { LonLat } from "../LonLat.js";
/**
* BaseGeoImage layer represents square imagery layer that could be an static image, or animated video or webgl buffer object displayed on the globe.
* @class
* @extends {og.Layer}
* @extends {Layer}
*/
class BaseGeoImage extends Layer {
constructor(name, options) {
@ -58,8 +58,12 @@ class BaseGeoImage extends Layer {
*/
getCornersLonLat() {
var c = this._cornersWgs84;
return [new LonLat(c[0].lon, c[0].lat), new LonLat(c[1].lon, c[1].lat),
new LonLat(c[2].lon, c[2].lat), new LonLat(c[3].lon, c[3].lat)];
return [
new LonLat(c[0].lon, c[0].lat),
new LonLat(c[1].lon, c[1].lat),
new LonLat(c[2].lon, c[2].lat),
new LonLat(c[3].lon, c[3].lat)
];
}
/**
@ -69,7 +73,12 @@ class BaseGeoImage extends Layer {
*/
getCorners() {
var c = this._cornersWgs84;
return [[c[0].lon, c[0].lat], [c[1].lon, c[1].lat], [c[2].lon, c[2].lat], [c[3].lon, c[3].lat]];
return [
[c[0].lon, c[0].lat],
[c[1].lon, c[1].lat],
[c[2].lon, c[2].lat],
[c[3].lon, c[3].lat]
];
}
/**
@ -92,7 +101,12 @@ class BaseGeoImage extends Layer {
*/
setCornersLonLat(corners) {
this._refreshFrame = true;
this._cornersWgs84 = [corners[0].clone(), corners[1].clone(), corners[2].clone(), corners[3].clone()] || [0, 0, 0, 0];
this._cornersWgs84 = [
corners[0].clone(),
corners[1].clone(),
corners[2].clone(),
corners[3].clone()
] || [0, 0, 0, 0];
for (var i = 0; i < this._cornersWgs84.length; i++) {
if (this._cornersWgs84[i].lat >= 89.9) {
@ -105,8 +119,7 @@ class BaseGeoImage extends Layer {
this._extent.setByCoordinates(this._cornersWgs84);
var me = this._extent;
if (me.southWest.lat > mercator.MAX_LAT ||
me.northEast.lat < mercator.MIN_LAT) {
if (me.southWest.lat > mercator.MAX_LAT || me.northEast.lat < mercator.MIN_LAT) {
this._projType = 0;
this.rendering = this._renderingProjType0;
} else {
@ -126,15 +139,32 @@ class BaseGeoImage extends Layer {
_createFrame() {
this._extentWgs84 = this._extent.clone();
this._cornersMerc = [this._cornersWgs84[0].forwardMercatorEPS01(), this._cornersWgs84[1].forwardMercatorEPS01(),
this._cornersWgs84[2].forwardMercatorEPS01(), this._cornersWgs84[3].forwardMercatorEPS01()];
this._cornersMerc = [
this._cornersWgs84[0].forwardMercatorEPS01(),
this._cornersWgs84[1].forwardMercatorEPS01(),
this._cornersWgs84[2].forwardMercatorEPS01(),
this._cornersWgs84[3].forwardMercatorEPS01()
];
this._extentMerc = new Extent(this._extentWgs84.southWest.forwardMercatorEPS01(), this._extentWgs84.northEast.forwardMercatorEPS01());
this._extentMerc = new Extent(
this._extentWgs84.southWest.forwardMercatorEPS01(),
this._extentWgs84.northEast.forwardMercatorEPS01()
);
if (this._projType === 0) {
this._extentWgs84Params = [this._extentWgs84.southWest.lon, this._extentWgs84.southWest.lat, 2.0 / this._extentWgs84.getWidth(), 2.0 / this._extentWgs84.getHeight()];
this._extentWgs84Params = [
this._extentWgs84.southWest.lon,
this._extentWgs84.southWest.lat,
2.0 / this._extentWgs84.getWidth(),
2.0 / this._extentWgs84.getHeight()
];
} else {
this._extentMercParams = [this._extentMerc.southWest.lon, this._extentMerc.southWest.lat, 2.0 / this._extentMerc.getWidth(), 2.0 / this._extentMerc.getHeight()];
this._extentMercParams = [
this._extentMerc.southWest.lon,
this._extentMerc.southWest.lat,
2.0 / this._extentMerc.getWidth(),
2.0 / this._extentMerc.getHeight()
];
}
// creates material frame textures
@ -146,7 +176,10 @@ class BaseGeoImage extends Layer {
gl.deleteTexture(this._materialTexture);
this._materialTexture = h.createEmptyTexture_l(this._frameWidth, this._frameHeight);
this._gridBuffer = this._planet._geoImageCreator.createGridBuffer(this._cornersWgs84, this._projType);
this._gridBuffer = this._planet._geoImageCreator.createGridBuffer(
this._cornersWgs84,
this._projType
);
this._refreshFrame = false;
}
@ -154,7 +187,7 @@ class BaseGeoImage extends Layer {
/**
* @virtual
* @param {og.planetSegment.Material} material - GeoImage material.
* @param {Material} material - GeoImage material.
*/
abortMaterialLoading(material) {
this._creationProceeding = false;
@ -200,7 +233,6 @@ class BaseGeoImage extends Layer {
*/
setVisibility(visibility) {
if (visibility !== this._visibility) {
super.setVisibility(visibility);
// remove from creator
@ -215,7 +247,7 @@ class BaseGeoImage extends Layer {
/**
* @virtual
* @protected
* @param {og.planetSegment.Material} material - GeoImage material.
* @param {Material} material - GeoImage material.
*/
clearMaterial(material) {
material.image = null;
@ -227,11 +259,10 @@ class BaseGeoImage extends Layer {
/**
* @virtual
* @protected
* @param {og.planetSegment.Material} material - GeoImage material.
* @param {Material} material - GeoImage material.
* @returns {Array<number> } -
*/
applyMaterial(material) {
var segment = material.segment;
if (this._ready) {

View File

@ -30,7 +30,7 @@ const EVENT_NAMES = [
/**
* Layer used to rendering each tile as a separate canvas object.
* @class
* @extends {og.Layer}
* @extends {Layer}
* //TODO: make asynchronous handler.
* @param {String} [name="noname"] - Layer name.
* @param {Object} options:
@ -41,7 +41,7 @@ const EVENT_NAMES = [
* @param {string} [options.attribution] - Layer attribution that displayed in the attribution area on the screen.
* @param {boolean} [options.isBaseLayer=false] - Base layer flag.
* @param {boolean} [options.visibility=true] - Layer visibility.
* @param {og.layer.CanvasTiles~drawTileCallback} [options.drawTile] - Draw tile callback.
* @param {layer.CanvasTiles~drawTileCallback} [options.drawTile] - Draw tile callback.
* @fires og.layer.CanvasTiles#load
* @fires og.layer.CanvasTiles#loadend
*/
@ -63,13 +63,13 @@ class CanvasTiles extends Layer {
/**
* Tile pending queue that waiting for create.
* @protected
* @type {Array.<og.planetSegment.Material>}
* @type {Array.<planetSegment.Material>}
*/
this._pendingsQueue = []; // new og.QueueArray();
/**
* Draw tile callback.
* @type {og.layer.CanvasTiles~drawTileCallback}
* @type {layer.CanvasTiles~drawTileCallback}
* @public
*/
this.drawTile = options.drawTile || null;
@ -116,7 +116,7 @@ class CanvasTiles extends Layer {
* Start to load tile material.
* @public
* @virtual
* @param {og.planetSegment.Material} material -
* @param {Material} material -
*/
loadMaterial(material) {
var seg = material.segment;
@ -143,7 +143,7 @@ class CanvasTiles extends Layer {
/**
* Loads material image and apply it to the planet segment.
* @protected
* @param {og.planetSegment.Material} material - Loads material image.
* @param {Material} material - Loads material image.
*/
_exec(material) {
CanvasTiles.__requestsCounter++;
@ -153,7 +153,7 @@ class CanvasTiles extends Layer {
/**
* Tile custom draw function.
* @callback og.layer.CanvasTiles~drawTileCallback
* @param {og.planetSegment.Material} material
* @param {Material} material
* @param {applyCanvasCallback} applyCanvasCallback
*/
var e = that.events.load;
@ -186,7 +186,7 @@ class CanvasTiles extends Layer {
/**
* Abort exact material loading.
* @public
* @param {og.planetSegment.Material} material - Segment material.
* @param {Material} material - Segment material.
*/
abortMaterialLoading(material) {
if (material.isLoading && material.image) {

View File

@ -2,14 +2,14 @@
* @module og/layer/GeoImage
*/
'use strict';
"use strict";
import { BaseGeoImage } from './BaseGeoImage.js';
import { BaseGeoImage } from "./BaseGeoImage.js";
/**
* Used to load and display a single image over specific corner coordinates on the globe, implements og.layer.BaseGeoImage interface.
* @class
* @extends {og.layer.BaseGeoImage}
* @extends {BaseGeoImage}
*/
class GeoImage extends BaseGeoImage {
constructor(name, options) {
@ -84,7 +84,7 @@ class GeoImage extends BaseGeoImage {
* Loads planet segment material. In this case - GeoImage source image.
* @virtual
* @public
* @param {og.planetSegment.Material} material - GeoImage planet material.
* @param {Material} material - GeoImage planet material.
*/
loadMaterial(material) {
material.isLoading = true;
@ -95,14 +95,14 @@ class GeoImage extends BaseGeoImage {
this._onLoad(this._image);
} else if (this._image.src) {
let that = this;
this._image.addEventListener('load', function (e) {
this._image.addEventListener("load", function (e) {
that._onLoad(this);
});
}
} else {
let that = this;
this._image = new Image();
this._image.addEventListener('load', function (e) {
this._image.addEventListener("load", function (e) {
that._onLoad(this);
});
this._image.src = this._src;
@ -114,10 +114,10 @@ class GeoImage extends BaseGeoImage {
/**
* @virtual
* @param {og.planetSegment.Material} material - GeoImage material.
* @param {Material} material - GeoImage material.
*/
abortMaterialLoading(material) {
this._image && (this._image.src = '');
this._image && (this._image.src = "");
this._creationProceeding = false;
material.isLoading = false;
material.isReady = false;

View File

@ -9,7 +9,7 @@ import { BaseGeoImage } from "./BaseGeoImage.js";
/**
* Used to load and display a video stream by specific corners coordinates on the globe, implements og.layer.BaseGeoImage interface.
* @class
* @extends {og.layer.BaseGeoImage}
* @extends {BaseGeoImage}
*/
class GeoVideo extends BaseGeoImage {
constructor(name, options) {
@ -139,7 +139,7 @@ class GeoVideo extends BaseGeoImage {
* Loads planet segment material. In this case - GeoImage source video.
* @virtual
* @public
* @param {og.planetSegment.Material} material - GeoImage planet material.
* @param {Material} material - GeoImage planet material.
*/
loadMaterial(material) {
material.isLoading = true;
@ -177,7 +177,7 @@ class GeoVideo extends BaseGeoImage {
/**
* @virtual
* @param {og.planetSegment.Material} material - GeoImage material.
* @param {Material} material - GeoImage material.
*/
abortMaterialLoading(material) {
this._video && (this._video.src = "");

View File

@ -2,19 +2,18 @@
* @module og/layer/KML
*/
'use strict';
import { Entity } from '../entity/Entity.js';
import { Extent } from '../Extent.js';
import { LonLat } from '../LonLat.js';
import { Vector } from './Vector.js';
"use strict";
import { Entity } from "../entity/Entity.js";
import { Extent } from "../Extent.js";
import { LonLat } from "../LonLat.js";
import { Vector } from "./Vector.js";
/**
* Layer to render KMLs files
* @class
* @extends {og.Vector}
* @extends {Vector}
*/
export class KML extends Vector {
/**
*
* @param {string} name
@ -23,20 +22,31 @@ export class KML extends Vector {
constructor(name, options = {}) {
super(name, options);
this._extent = null;
this._billboard = options.billboard || { src: 'https://openglobus.org/examples/billboards/carrot.png' };
this._color = options.color || '#6689db';
this._billboard = options.billboard || {
src: "https://openglobus.org/examples/billboards/carrot.png"
};
/**
* @type {string}
*/
this._color = options.color || "#6689db";
}
get instanceName() {
return 'KML';
return "KML";
}
/**
* @private
*/
_extractCoordonatesFromKml(xmlDoc) {
const raw = Array.from(xmlDoc.getElementsByTagName('coordinates'));
const coordinates = raw.map(item => item.textContent.trim().replace(/\n/g, ' ').split(' ').map(co => co.split(',').map(parseFloat)));
const raw = Array.from(xmlDoc.getElementsByTagName("coordinates"));
const coordinates = raw.map((item) =>
item.textContent
.trim()
.replace(/\n/g, " ")
.split(" ")
.map((co) => co.split(",").map(parseFloat))
);
return coordinates;
}
@ -45,31 +55,34 @@ export class KML extends Vector {
* @private
* @param {Array} coordonates
* @param {string} color
* @returns {Array<og.Entity>}
* @returns {Array<Entity>}
*/
_convertCoordonatesIntoEntities(coordinates, color, billboard) {
const extent = new Extent(new LonLat(180.0, 90.0), new LonLat(-180.0, -90.0));
const addToExtent = (c) => {
const lon = c[0], lat = c[1];
const lon = c[0],
lat = c[1];
if (lon < extent.southWest.lon) extent.southWest.lon = lon;
if (lat < extent.southWest.lat) extent.southWest.lat = lat;
if (lon > extent.northEast.lon) extent.northEast.lon = lon;
if (lat > extent.northEast.lat) extent.northEast.lat = lat;
};
const _pathes = [];
coordinates.forEach(kmlFile => kmlFile.forEach(p => _pathes.push(p)));
const entities = _pathes.map(path => {
coordinates.forEach((kmlFile) => kmlFile.forEach((p) => _pathes.push(p)));
const entities = _pathes.map((path) => {
if (path.length === 1) {
const lonlat = path[0];
const _entity = new Entity({ lonlat, billboard });
addToExtent(lonlat);
return _entity;
} else if (path.length > 1) {
const pathLonLat = path.map(item => {
const pathLonLat = path.map((item) => {
addToExtent(item);
return new LonLat(item[0], item[1], item[2]);
});
const _entity = new Entity({ polyline: { pathLonLat: [pathLonLat], thickness: 3, color, isClosed: false } });
const _entity = new Entity({
polyline: { pathLonLat: [pathLonLat], thickness: 3, color, isClosed: false }
});
return _entity;
}
});
@ -78,11 +91,13 @@ export class KML extends Vector {
/**
* @private
* @returns {Document}
*/
_getXmlContent(file) {
return new Promise(resolve => {
return new Promise((resolve) => {
const fileReader = new FileReader();
fileReader.onload = async i => resolve((new DOMParser()).parseFromString(i.target.result, 'text/xml'));
fileReader.onload = async (i) =>
resolve(new DOMParser().parseFromString(i.target.result, "text/xml"));
fileReader.readAsText(file);
});
}
@ -92,22 +107,30 @@ export class KML extends Vector {
*/
_expandExtents(extent1, extent2) {
if (!extent1) return extent2;
if (extent2.southWest.lon < extent1.southWest.lon) extent1.southWest.lon = extent2.southWest.lon;
if (extent2.southWest.lat < extent1.southWest.lat) extent1.southWest.lat = extent2.southWest.lat;
if (extent2.northEast.lon > extent1.northEast.lon) extent1.northEast.lon = extent2.northEast.lon;
if (extent2.northEast.lat > extent1.northEast.lat) extent1.northEast.lat = extent2.northEast.lat;
if (extent2.southWest.lon < extent1.southWest.lon)
extent1.southWest.lon = extent2.southWest.lon;
if (extent2.southWest.lat < extent1.southWest.lat)
extent1.southWest.lat = extent2.southWest.lat;
if (extent2.northEast.lon > extent1.northEast.lon)
extent1.northEast.lon = extent2.northEast.lon;
if (extent2.northEast.lat > extent1.northEast.lat)
extent1.northEast.lat = extent2.northEast.lat;
return extent1;
}
/**
* @public
* @param {File[]} kmls
* @returns {Promise}
* @returns {Promise<{entities: Entity[], extent: Extent}>}
*/
async addKmlFromFiles(kmls) {
const kmlObjs = await Promise.all(kmls.map(this._getXmlContent));
const coordonates = kmlObjs.map(this._extractCoordonatesFromKml);
const { entities, extent } = this._convertCoordonatesIntoEntities(coordonates, this._color, this._billboard);
const { entities, extent } = this._convertCoordonatesIntoEntities(
coordonates,
this._color,
this._billboard
);
this._extent = this._expandExtents(this._extent, extent);
entities.forEach(this.add.bind(this));
return { entities, extent };
@ -128,14 +151,14 @@ export class KML extends Vector {
_getKmlFromUrl(url) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'document';
request.overrideMimeType('text/xml');
request.open("GET", url, true);
request.responseType = "document";
request.overrideMimeType("text/xml");
request.onload = () => {
if (request.readyState === request.DONE && request.status === 200) {
resolve(request.responseXML);
} else {
reject(new Error('no valid kml file'));
reject(new Error("no valid kml file"));
}
};
request.send();
@ -145,15 +168,18 @@ export class KML extends Vector {
/**
* @public
* @param {string} url - Url of the KML to display. './myFile.kml' or 'http://mySite/myFile.kml' for example.
* @returns {Promise}
* @returns {Promise<{entities: Entity[], extent: Extent}>}
*/
async addKmlFromUrl(url) {
const kml = await this._getKmlFromUrl(url);
const coordonates = this._extractCoordonatesFromKml(kml);
const { entities, extent } = this._convertCoordonatesIntoEntities([coordonates], this._color, this._billboard);
const { entities, extent } = this._convertCoordonatesIntoEntities(
[coordonates],
this._color,
this._billboard
);
this._extent = this._expandExtents(this._extent, extent);
entities.forEach(this.add.bind(this));
return { entities, extent };
}
}

View File

@ -11,6 +11,7 @@ import { Extent } from "../Extent.js";
import { LonLat } from "../LonLat.js";
import { Material } from "./Material.js";
import { Vec3 } from "../math/Vec3.js";
import { createTexture } from "../webgl/Handler.js";
export const FADING_FACTOR = 0.29;
@ -28,10 +29,11 @@ export const FADING_FACTOR = 0.29;
* @param {string} [options.attribution] - Layer attribution that displayed in the attribution area on the screen.
* @param {boolean} [options.isBaseLayer=false] - This is a base layer.
* @param {boolean} [options.visibility=true] - Layer visibility.
* @param {og.Extent} [options.extent=[[-180.0, -90.0], [180.0, 90.0]]] - Visible extent.
* @param {og.Vec3} [options.ambient=[0.1, 0.1, 0.21]] - Ambient RGB color.
* @param {og.Vec3} [options.diffuse=[1.0, 1.0, 1.0]] - Diffuse RGB color.
* @param {og.Vec3} [options.specular=[0.00025, 0.00015, 0.0001]] - Specular RGB color.
* @param {Extent} [options.extent=[[-180.0, -90.0], [180.0, 90.0]]] - Visible extent.
* @param {Vec3} [options.ambient=[0.1, 0.1, 0.21]] - Ambient RGB color.
* @param {Vec3} [options.diffuse=[1.0, 1.0, 1.0]] - Diffuse RGB color.
* @param {Vec3} [options.specular=[0.00025, 0.00015, 0.0001]] - Specular RGB color.
* @param {string} [options.textureFilter="anisotropic"] - Image texture filter. Available values: "nearest", "linear", "mipmap" and "anisotropic".
* @param {Number} [options.shininess=100] - Shininess.
*
* @fires og.Layer#visibilitychange
@ -118,7 +120,7 @@ class Layer {
/**
* Planet node.
* @protected
* @type {og.scene.Planet}
* @type {Planet}
*/
this._planet = null;
@ -179,14 +181,22 @@ class Layer {
/**
* Visible degrees extent.
* @protected
* @type {og.Extent}
* @type {Extent}
*/
this._extent = null;
if (options.textureFilter) {
this.createTexture =
createTexture[options.textureFilter.trim().toUpperCase()] ||
createTexture.ANISOTROPIC;
} else {
this.createTexture = createTexture.ANISOTROPIC;
}
/**
* Visible mercator extent.
* @protected
* @type {og.Extent}
* @type {Extent}
*/
this._extentMerc = null;
@ -201,7 +211,7 @@ class Layer {
/**
* Layer picking color. Assign when added to the planet.
* @protected
* @type {og.Vec3}
* @type {Vec3}
*/
this._pickingColor = new Vec3();
@ -210,7 +220,7 @@ class Layer {
/**
* Events handler.
* @public
* @type {og.Events}
* @type {Events}
*/
this.events = new Events(EVENT_NAMES, this);
}
@ -310,7 +320,7 @@ class Layer {
/**
* Compares layers instances.
* @public
* @param {og.Layer} layer - Layer instance to compare.
* @param {Layer} layer - Layer instance to compare.
* @returns {boolean} - Returns true if the layers is the same instance of the input.
*/
isEqual(layer) {
@ -321,7 +331,7 @@ class Layer {
* Assign the planet.
* @protected
* @virtual
* @param {og.scene.Planet} planet - Planet render node.
* @param {Planet} planet - Planet render node.
*/
_assignPlanet(planet) {
planet.layers.push(this);
@ -348,7 +358,7 @@ class Layer {
/**
* Adds layer to the planet.
* @public
* @param {og.scene.Planet} planet - Adds layer to the planet.
* @param {Planet} planet - Adds layer to the planet.
*/
addTo(planet) {
if (!this._planet) {
@ -360,7 +370,7 @@ class Layer {
/**
* Removes from planet.
* @public
* @returns {og.Layer} -This layer.
* @returns {Layer} -This layer.
*/
remove() {
var p = this._planet;
@ -514,7 +524,7 @@ class Layer {
/**
* Sets visible geographical extent.
* @public
* @param {og.Extent} extent - Layer visible geographical extent.
* @param {Extent} extent - Layer visible geographical extent.
*/
setExtent(extent) {
var sw = extent.southWest.clone(),
@ -533,7 +543,7 @@ class Layer {
/**
* Gets layer extent.
* @public
* @return {og.Extent} - Layer geodetic extent.
* @return {Extent} - Layer geodetic extent.
*/
getExtent() {
return this._extent;

View File

@ -2,10 +2,9 @@
* @module og/layer/Material
*/
'use strict';
"use strict";
class Material {
/**
*
* @param {*} segment
@ -30,12 +29,12 @@ class Material {
this.pickingReady = false;
}
/**
* @param {*} layer
*/
assignLayer(layer) {
this.layer = layer;
}
///**
// * @param {*} layer
// */
//assignLayer(layer) {
// this.layer = layer;
//}
/**
*
@ -44,6 +43,10 @@ class Material {
this.layer.abortMaterialLoading(this);
}
_createTexture(img) {
return this.layer.createTexture(this.segment.handler, img);
}
/**
*
* @param {*} img
@ -52,7 +55,7 @@ class Material {
if (this.segment.initialized) {
this._updateTexture = null;
//this.image = img;
this.texture = this.segment.handler.createTexture(img);
this.texture = this._createTexture(img);
this.appliedNodeId = this.segment.node.nodeId;
this.isReady = true;
this.pickingReady = true;

View File

@ -2,19 +2,22 @@
* @module og/layer/Vector
*/
'use strict';
"use strict";
import * as math from '../math.js';
import * as mercator from '../mercator.js';
import * as quadTree from '../quadTree/quadTree.js';
import { Entity } from '../entity/Entity.js';
import { EntityCollection } from '../entity/EntityCollection.js';
import { Extent } from '../Extent.js';
import { EntityCollectionNode, EntityCollectionNodeWGS84 } from '../quadTree/EntityCollectionNode.js';
import { GeometryHandler } from '../entity/GeometryHandler.js';
import { Layer } from './Layer.js';
import { QueueArray } from '../QueueArray.js';
import { Vec3 } from '../math/Vec3.js';
import * as math from "../math.js";
import * as mercator from "../mercator.js";
import * as quadTree from "../quadTree/quadTree.js";
import { Entity } from "../entity/Entity.js";
import { EntityCollection } from "../entity/EntityCollection.js";
import { Extent } from "../Extent.js";
import {
EntityCollectionNode,
EntityCollectionNodeWGS84
} from "../quadTree/EntityCollectionNode.js";
import { GeometryHandler } from "../entity/GeometryHandler.js";
import { Layer } from "./Layer.js";
import { QueueArray } from "../QueueArray.js";
import { Vec3 } from "../math/Vec3.js";
/**
* Creates entity instance array.
@ -38,7 +41,7 @@ function _entitiesConstructor(entities) {
* Vector layer represents alternative entities store. Used for geospatial data rendering like
* points, lines, polygons, geometry objects etc.
* @class
* @extends {og.Layer}
* @extends {Layer}
* @param {string} [name="noname"] - Layer name.
* @param {Object} [options] - Layer options:
* @param {number} [options.minZoom=0] - Minimal visible zoom. 0 is default
@ -47,7 +50,7 @@ function _entitiesConstructor(entities) {
* @param {string} [options.zIndex=0] - Layer Z-order index. 0 is default.
* @param {boolean} [options.visibility=true] - Layer visibility. True is default.
* @param {boolean} [options.isBaseLayer=false] - Layer base layer. False is default.
* @param {Array.<og.Entity>} [options.entities] - Entities array.
* @param {Array.<Entity>} [options.entities] - Entities array.
* @param {Array.<number>} [options.scaleByDistance] - Scale by distance parameters. (exactly 3 entries)
* First index - near distance to the entity, after entity becomes full scale.
* Second index - far distance to the entity, when entity becomes zero scale.
@ -68,13 +71,11 @@ function _entitiesConstructor(entities) {
* @fires og.layer.Vector#visibilitychange
*/
class Vector extends Layer {
/**
* @param {string} name
* @param {*} [options]
*/
constructor(name, options = {}) {
super(name, options);
this.events.registerNames(EVENT_NAMES);
@ -160,14 +161,16 @@ class Vector extends Layer {
* @public
* @type {Number}
*/
this.polygonOffsetFactor = options.polygonOffsetFactor != undefined ? options.polygonOffsetFactor : 0.0;
this.polygonOffsetFactor =
options.polygonOffsetFactor != undefined ? options.polygonOffsetFactor : 0.0;
/**
* Specifies the scale Units for gl.polygonOffset function to calculate depth values, 0.0 is default.
* @public
* @type {Number}
*/
this.polygonOffsetUnits = options.polygonOffsetUnits != undefined ? options.polygonOffsetUnits : -637000.0;
this.polygonOffsetUnits =
options.polygonOffsetUnits != undefined ? options.polygonOffsetUnits : -637000.0;
this.pickingEnabled = this._pickingEnabled;
}
@ -183,8 +186,8 @@ class Vector extends Layer {
/**
* Adds layer to the planet.
* @public
* @param {og.Planet} planet - Planet scene object.
* @returns {og.layer.Vector} -
* @param {Planet} planet - Planet scene object.
* @returns {layer.Vector} -
*/
addTo(planet) {
if (!this._planet) {
@ -200,7 +203,7 @@ class Vector extends Layer {
/**
* Returns stored entities.
* @public
* @returns {Array.<og.Entity>} -
* @returns {Array.<Entity>} -
*/
getEntities() {
return [].concat(this._entities);
@ -237,9 +240,9 @@ class Vector extends Layer {
/**
* Adds entity to the layer.
* @public
* @param {og.Entity} entity - Entity.
* @param {Entity} entity - Entity.
* @param {boolean} [rightNow] - Entity insertion option. False is deafult.
* @returns {og.layer.Vector} - Returns this layer.
* @returns {layer.Vector} - Returns this layer.
*/
add(entity, rightNow) {
if (!(entity._layer || entity._entityCollection)) {
@ -255,10 +258,10 @@ class Vector extends Layer {
/**
* Adds entity to the layer in the index position.
* @public
* @param {og.Entity} entity - Entity.
* @param {Entity} entity - Entity.
* @param {Number} index - Index position.
* @param {boolean} [rightNow] - Entity insertion option. False is deafult.
* @returns {og.layer.Vector} - Returns this layer.
* @returns {layer.Vector} - Returns this layer.
*/
insert(entity, index, rightNow) {
if (!(entity._layer || entity._entityCollection)) {
@ -277,7 +280,6 @@ class Vector extends Layer {
}
_proceedEntity(entity, rightNow) {
let temp = this._hasImageryTiles;
//
@ -302,9 +304,10 @@ class Vector extends Layer {
if (entity.billboard || entity.label) {
if (this._planet) {
if (entity._cartesian.isZero() && !entity._lonlat.isZero()) {
entity._setCartesian3vSilent(this._planet.ellipsoid.lonLatToCartesian(entity._lonlat));
entity._setCartesian3vSilent(
this._planet.ellipsoid.lonLatToCartesian(entity._lonlat)
);
} else {
entity._lonlat = this._planet.ellipsoid.cartesianToLonLat(entity._cartesian);
}
@ -334,9 +337,9 @@ class Vector extends Layer {
/**
* Adds entity array to the layer.
* @public
* @param {Array.<og.Entity>} entities - Entities array.
* @param {Array.<Entity>} entities - Entities array.
* @param {boolean} [rightNow] - Entity insertion option. False is deafult.
* @returns {og.layer.Vector} - Returns this layer.
* @returns {layer.Vector} - Returns this layer.
*/
addEntities(entities, rightNow) {
var i = entities.length;
@ -350,8 +353,8 @@ class Vector extends Layer {
* Remove entity from layer.
* TODO: memory leaks.
* @public
* @param {og.Entity} entity - Entity to remove.
* @returns {og.layer.Vector} - Returns this layer.
* @param {Entity} entity - Entity to remove.
* @returns {layer.Vector} - Returns this layer.
*/
removeEntity(entity) {
if (entity._layer && this.isEqual(entity._layer)) {
@ -367,15 +370,17 @@ class Vector extends Layer {
node.count--;
node = node.parentNode;
}
if (entity._nodePtr && entity._nodePtr.count === 0 &&
entity._nodePtr.deferredEntities.length === 0) {
if (
entity._nodePtr &&
entity._nodePtr.count === 0 &&
entity._nodePtr.deferredEntities.length === 0
) {
entity._nodePtr.entityCollection = null;
//
// ...
//
}
} else if (entity._nodePtr &&
entity._nodePtr.deferredEntities.length) {
} else if (entity._nodePtr && entity._nodePtr.deferredEntities.length) {
var defEntities = entity._nodePtr.deferredEntities;
var j = defEntities.length;
while (j--) {
@ -447,8 +452,8 @@ class Vector extends Layer {
/**
* Removes entities from layer.
* @public
* @param {Array.<og.Entity>} entities - Entity array.
* @returns {og.layer.Vector} - Returns this layer.
* @param {Array.<Entity>} entities - Entity array.
* @returns {layer.Vector} - Returns this layer.
*/
removeEntities(entities) {
var i = entities.length;
@ -464,7 +469,7 @@ class Vector extends Layer {
* @param {number} near - Full scale entity distance.
* @param {number} far - Zerol scale entity distance.
* @param {number} [farInvisible] - Entity visibility distance.
* @returns {og.layer.Vector} -
* @returns {layer.Vector} -
*/
setScaleByDistance(near, far, farInvisible) {
this.scaleByDistance[0] = near;
@ -478,7 +483,6 @@ class Vector extends Layer {
* @public
*/
clear() {
let temp = new Array(this._entities.length);
for (let i = 0; i < temp.length; i++) {
@ -517,11 +521,10 @@ class Vector extends Layer {
/**
* Removes current entities from layer and adds new entities.
* @public
* @param {Array.<og.Entity>} entities - New entity array.
* @returns {og.layer.Vector} - Returns layer instance.
* @param {Array.<Entity>} entities - New entity array.
* @returns {layer.Vector} - Returns layer instance.
*/
setEntities(entities) {
let temp = new Array(entities.length);
for (let i = 0, len = entities.length; i < len; i++) {
temp[i] = entities[i];
@ -573,12 +576,33 @@ class Vector extends Layer {
_createEntityCollectionsTree(entitiesForTree) {
if (this._planet) {
this._entityCollectionsTree = new EntityCollectionNode(this, quadTree.NW, null, 0,
Extent.createFromArray([-20037508.34, -20037508.34, 20037508.34, 20037508.34]), this._planet, 0);
this._entityCollectionsTreeNorth = new EntityCollectionNodeWGS84(this, quadTree.NW, null, 0,
Extent.createFromArray([-180, mercator.MAX_LAT, 180, 90]), this._planet, 0);
this._entityCollectionsTreeSouth = new EntityCollectionNodeWGS84(this, quadTree.NW, null, 0,
Extent.createFromArray([-180, -90, 180, mercator.MIN_LAT]), this._planet, 0);
this._entityCollectionsTree = new EntityCollectionNode(
this,
quadTree.NW,
null,
0,
Extent.createFromArray([-20037508.34, -20037508.34, 20037508.34, 20037508.34]),
this._planet,
0
);
this._entityCollectionsTreeNorth = new EntityCollectionNodeWGS84(
this,
quadTree.NW,
null,
0,
Extent.createFromArray([-180, mercator.MAX_LAT, 180, 90]),
this._planet,
0
);
this._entityCollectionsTreeSouth = new EntityCollectionNodeWGS84(
this,
quadTree.NW,
null,
0,
Extent.createFromArray([-180, -90, 180, mercator.MIN_LAT]),
this._planet,
0
);
for (let i = 0, len = entitiesForTree.length; i < len; i++) {
let entity = entitiesForTree[i];
@ -682,7 +706,6 @@ class Vector extends Layer {
}
_collectStripCollectionPASS(outArr) {
var ec = this._stripEntityCollection;
ec._fadingOpacity = this._fadingOpacity;
@ -699,7 +722,6 @@ class Vector extends Layer {
}
_collectPolylineCollectionPASS(outArr) {
var ec = this._polylineEntityCollection;
ec._fadingOpacity = this._fadingOpacity;
@ -737,7 +759,12 @@ class Vector extends Layer {
if (seg._extent.isInside(ll)) {
let cart = p._path3v[c_j][c_j_h];
seg.getTerrainPoint(cart, ll, res);
p.setPoint3v(res.addA(res.normal().scale((rtg && p.altitude) || 0.0)), c_j_h, c_j, true);
p.setPoint3v(
res.addA(res.normal().scale((rtg && p.altitude) || 0.0)),
c_j_h,
c_j,
true
);
break;
}
}
@ -751,9 +778,10 @@ class Vector extends Layer {
collectVisibleCollections(outArr) {
var p = this._planet;
if ((this._fading && this._fadingOpacity > 0.0) ||
(this.minZoom <= this._planet.maxCurrZoom && this.maxZoom >= p.maxCurrZoom)) {
if (
(this._fading && this._fadingOpacity > 0.0) ||
(this.minZoom <= this._planet.maxCurrZoom && this.maxZoom >= p.maxCurrZoom)
) {
this._renderingNodes = {};
this._renderingNodesNorth = {};
this._renderingNodesSouth = {};
@ -768,23 +796,41 @@ class Vector extends Layer {
this._entityCollectionsTree.collectRenderCollectionsPASS1(p._visibleNodes, outArr);
var i = this._secondPASS.length;
while (i--) {
this._secondPASS[i].collectRenderCollectionsPASS2(p._visibleNodes, outArr, this._secondPASS[i].nodeId);
this._secondPASS[i].collectRenderCollectionsPASS2(
p._visibleNodes,
outArr,
this._secondPASS[i].nodeId
);
}
// North nodes
this._secondPASS = [];
this._entityCollectionsTreeNorth.collectRenderCollectionsPASS1(p._visibleNodesNorth, outArr);
this._entityCollectionsTreeNorth.collectRenderCollectionsPASS1(
p._visibleNodesNorth,
outArr
);
i = this._secondPASS.length;
while (i--) {
this._secondPASS[i].collectRenderCollectionsPASS2(p._visibleNodesNorth, outArr, this._secondPASS[i].nodeId);
this._secondPASS[i].collectRenderCollectionsPASS2(
p._visibleNodesNorth,
outArr,
this._secondPASS[i].nodeId
);
}
// South nodes
this._secondPASS = [];
this._entityCollectionsTreeSouth.collectRenderCollectionsPASS1(p._visibleNodesSouth, outArr);
this._entityCollectionsTreeSouth.collectRenderCollectionsPASS1(
p._visibleNodesSouth,
outArr
);
i = this._secondPASS.length;
while (i--) {
this._secondPASS[i].collectRenderCollectionsPASS2(p._visibleNodesSouth, outArr, this._secondPASS[i].nodeId);
this._secondPASS[i].collectRenderCollectionsPASS2(
p._visibleNodesSouth,
outArr,
this._secondPASS[i].nodeId
);
}
}
}
@ -823,14 +869,15 @@ class Vector extends Layer {
* Start to load tile material.
* @public
* @virtual
* @param {og.Segment.Material} material - Current material.
* @param {Segment.Material} material - Current material.
*/
loadMaterial(material) {
var seg = material.segment;
if (this._isBaseLayer) {
material.texture = seg._isNorth ? seg.planet.solidTextureOne : seg.planet.solidTextureTwo;
material.texture = seg._isNorth
? seg.planet.solidTextureOne
: seg.planet.solidTextureTwo;
} else {
material.texture = seg.planet.transparentTexture;
}
@ -845,7 +892,7 @@ class Vector extends Layer {
/**
* Abort exact material loading.
* @public
* @param {og.planetSegment.Material} material - Segment material.
* @param {Material} material - Segment material.
*/
abortMaterialLoading(material) {
material.isLoading = false;
@ -856,7 +903,6 @@ class Vector extends Layer {
if (material.isReady) {
return [0, 0, 1, 1];
} else {
!material.isLoading && this.loadMaterial(material);
var segment = material.segment;

View File

@ -2,17 +2,17 @@
* @module og/layer/WMS
*/
'use strict';
"use strict";
import * as mercator from '../mercator.js';
import { Extent } from '../Extent.js';
import { LonLat } from '../LonLat.js';
import { XYZ } from './XYZ.js';
import * as mercator from "../mercator.js";
import { Extent } from "../Extent.js";
import { LonLat } from "../LonLat.js";
import { XYZ } from "./XYZ.js";
/**
* Used to display WMS services as tile layers on the globe.
* @class
* @extends {og.layer.XYZ}
* @extends {XYZ}
* //TODO: WMS version, format, and custom srs cpecification.
* @param {string} name - Layer name.
* @param {Object} options - Options:
@ -87,17 +87,34 @@ class WMS extends XYZ {
srs,
bbox,
width = 256,
height = 256) {
height = 256
) {
return `${url}/wms?LAYERS=${layers}&FORMAT=${format}&SERVICE=WMS&VERSION=${version}&REQUEST=${request}
&SRS=${srs}&BBOX=${bbox}&WIDTH=${width}&HEIGHT=${height}`;
}
static get_bbox_v1_1_1(extent) {
return extent.getWest() + "," + extent.getSouth() + "," + extent.getEast() + "," + extent.getNorth();
return (
extent.getWest() +
"," +
extent.getSouth() +
"," +
extent.getEast() +
"," +
extent.getNorth()
);
}
static get_bbox_v1_3_0(extent) {
return extent.getSouth() + "," + extent.getWest() + "," + extent.getNorth() + "," + extent.getEast();
return (
extent.getSouth() +
"," +
extent.getWest() +
"," +
extent.getNorth() +
"," +
extent.getEast()
);
}
_checkSegment(segment) {

View File

@ -2,18 +2,18 @@
* @module og/layer/XYZ
*/
'use strict';
"use strict";
import * as mercator from '../mercator.js';
import { EPSG3857 } from '../proj/EPSG3857.js';
import { Layer } from './Layer.js';
import { stringTemplate } from '../utils/shared.js';
import { RENDERING } from '../quadTree/quadTree.js';
import * as mercator from "../mercator.js";
import { EPSG3857 } from "../proj/EPSG3857.js";
import { Layer } from "./Layer.js";
import { stringTemplate } from "../utils/shared.js";
import { RENDERING } from "../quadTree/quadTree.js";
/**
* Represents an imagery tiles source provider.
* @class
* @extends {og.Layer}
* @extends {Layer}
* @param {string} name - Layer name.
* @param {Object} options:
* @param {number} [options.opacity=1.0] - Layer opacity.
@ -28,7 +28,8 @@ import { RENDERING } from '../quadTree/quadTree.js';
* @param {boolean} [options.visibility=true] - Layer visibility.
* @param {string} [options.crossOrigin=true] - If true, all tiles will have their crossOrigin attribute set to ''.
* @param {string} options.url - Tile url source template(see example below).
* @param {og.layer.XYZ~_urlRewriteCallback} options.urlRewrite - Url rewrite function.
* @param {string} options.textureFilter - texture gl filter. NEAREST, LINEAR, MIPMAP, ANISOTROPHIC.
* @param {layer.XYZ~_urlRewriteCallback} options.urlRewrite - Url rewrite function.
* @fires og.layer.XYZ#load
* @fires og.layer.XYZ#loadend
*
@ -41,7 +42,6 @@ import { RENDERING } from '../quadTree/quadTree.js';
* });
*/
class XYZ extends Layer {
/**
* @param {string} name - Layer name.
* @param {*} options
@ -63,7 +63,7 @@ class XYZ extends Layer {
/**
* @protected
*/
this._s = options.subdomains || ['a', 'b', 'c'];
this._s = options.subdomains || ["a", "b", "c"];
/**
* Minimal native zoom level when tiles are available.
@ -82,13 +82,13 @@ class XYZ extends Layer {
/**
* @protected
*/
this._crossOrigin = options.crossOrigin === undefined ? '' : options.crossOrigin;
this._crossOrigin = options.crossOrigin === undefined ? "" : options.crossOrigin;
/**
* Rewrites imagery tile url query.
* @private
* @callback og.layer.XYZ~_urlRewriteCallback
* @param {og.planetSegment.Segment} segment - Segment to load.
* @param {Segment} segment - Segment to load.
* @param {string} url - Created url.
* @returns {string} - Url query string.
*/
@ -114,7 +114,6 @@ class XYZ extends Layer {
*/
setVisibility(visibility) {
if (visibility !== this._visibility) {
super.setVisibility(visibility);
if (!visibility) {
@ -143,10 +142,9 @@ class XYZ extends Layer {
* Start to load tile material.
* @public
* @virtual
* @param {og.planetSegment.Material} material - Loads current material.
* @param {Material} material - Loads current material.
*/
loadMaterial(material, forceLoading) {
let seg = material.segment;
if (this._isBaseLayer) {
@ -156,20 +154,21 @@ class XYZ extends Layer {
}
if (this._planet.layerLock.isFree()) {
material.isReady = false;
material.isLoading = true;
if (this._checkSegment(seg)) {
material.loadingAttempts++;
this._planet._tileLoader.load({
this._planet._tileLoader.load(
{
src: this._getHTTPRequestString(material.segment),
type: 'imageBitmap',
filter: () => (seg.initialized && seg.node.getState() === RENDERING) || forceLoading,
type: "imageBitmap",
filter: () =>
(seg.initialized && seg.node.getState() === RENDERING) || forceLoading,
options: {}
}, (response) => {
},
(response) => {
if (response.status === "ready") {
if (material.isLoading) {
let e = this.events.load;
@ -186,7 +185,8 @@ class XYZ extends Layer {
material.textureNotExists();
}
}
});
}
);
} else {
material.textureNotExists();
}
@ -197,7 +197,7 @@ class XYZ extends Layer {
* Creates query url.
* @protected
* @virtual
* @param {og.planetSegment.Segment} segment - Creates specific url for current segment.
* @param {Segment} segment - Creates specific url for current segment.
* @returns {String} - Returns url string.
*/
_createUrl(segment) {
@ -216,28 +216,28 @@ class XYZ extends Layer {
/**
* Returns actual url query string.
* @protected
* @param {og.planetSegment.Segment} segment - Segment that loads image data.
* @param {Segment} segment - Segment that loads image data.
* @returns {string} - Url string.
*/
_getHTTPRequestString(segment) {
return this._urlRewriteCallback ? this._urlRewriteCallback(segment, this.url) : this._createUrl(segment);
return this._urlRewriteCallback
? this._urlRewriteCallback(segment, this.url)
: this._createUrl(segment);
}
/**
* Sets url rewrite callback, used for custom url rewriting for every tile laoding.
* @public
* @param {og.layer.XYZ~_urlRewriteCallback} ur - The callback that returns tile custom created url.
* @param {layer.XYZ~_urlRewriteCallback} ur - The callback that returns tile custom created url.
*/
setUrlRewriteCallback(ur) {
this._urlRewriteCallback = ur;
}
applyMaterial(material) {
if (material.isReady) {
return material.texOffset;
} else {
// if (material.loadingAttempts > 20) {
// debugger;
// }
@ -272,7 +272,9 @@ class XYZ extends Layer {
if (pnm) {
!pnm.isLoading && !pnm.isReady && this.loadMaterial(pnm, true);
} else {
pnm = pn.segment.materials[material.layer._id] = material.layer.createMaterial(pn.segment);
pnm = pn.segment.materials[material.layer._id] = material.layer.createMaterial(
pn.segment
);
this.loadMaterial(pnm, true);
}
}
@ -305,7 +307,7 @@ class XYZ extends Layer {
material.texture = null;
if (material.image) {
material.image.src = '';
material.image.src = "";
material.image = null;
}
}

View File

@ -2,19 +2,19 @@
* @module og/light/LightSource
*/
'use strict';
"use strict";
import { Vec3 } from '../math/Vec3.js';
import { Vec3 } from "../math/Vec3.js";
/**
* Represents basic light source.
* @class
* @param {string} [name] - Light source name.
* @param {Object} [params] - Light parameters:
* @param {og.Vec3} [params.position] - Light source position if it is a point light, otherwise it is a light direction vector.
* @param {og.Vec3} [params.ambient] - Ambient RGB color.
* @param {og.Vec3} [params.diffuse] - Diffuse RGB color.
* @param {og.Vec3} [params.specular] - Specular RGB color.
* @param {Vec3} [params.position] - Light source position if it is a point light, otherwise it is a light direction vector.
* @param {Vec3} [params.ambient] - Ambient RGB color.
* @param {Vec3} [params.diffuse] - Diffuse RGB color.
* @param {Vec3} [params.specular] - Specular RGB color.
* @param {number} [params.shininess] - Specular shininess.
*/
class LightSource {
@ -37,19 +37,19 @@ class LightSource {
* @protected
* @type {string}
*/
this._name = name || ("light_" + LightSource._staticCounter++);
this._name = name || "light_" + LightSource._staticCounter++;
/**
* Render node where light is shines.
* @protected
* @type {og.scene.RenderNode}
* @type {RenderNode}
*/
this._renderNode = null;
/**
* Light position.
* @protected
* @type {og.Vec3}
* @type {Vec3}
*/
this._position = params.position || new Vec3();
@ -63,21 +63,21 @@ class LightSource {
/**
* Ambient color.
* @protected
* @type {og.Vec3}
* @type {Vec3}
*/
this._ambient = params.ambient || new Vec3();
/**
* Diffuse color.
* @protected
* @type {og.Vec3}
* @type {Vec3}
*/
this._diffuse = params.diffuse || new Vec3(0.8, 0.8, 0.8);
/**
* Specular color.
* @protected
* @type {og.Vec3}
* @type {Vec3}
*/
this._specular = params.specular || new Vec3(0.18, 0.18, 0.18);
@ -105,7 +105,7 @@ class LightSource {
* Creates clone of the current light object.
* @todo: TODO
* @public
* @returns {og.LightSource}
* @returns {LightSource}
*/
clone() {
// TODO
@ -158,8 +158,8 @@ class LightSource {
/**
* Set light source position, or if it is a directional type sets light direction vector.
* @public
* @param {og.Vec3} position - Light position or direction vector.
* @returns {og.LightSource}
* @param {Vec3} position - Light position or direction vector.
* @returns {LightSource}
*/
setPosition3v(position) {
this._position.x = position.x;
@ -171,8 +171,8 @@ class LightSource {
/**
* Set light source position, or if it is a directional type sets light direction vector.
* @public
* @param {og.Vec3} position - Light position or direction vector.
* @returns {og.LightSource}
* @param {Vec3} position - Light position or direction vector.
* @returns {LightSource}
*/
setPosition(x, y, z) {
this._position.x = x;
@ -184,7 +184,7 @@ class LightSource {
/**
* Returns light source position, or if it is a directional type sets light direction vector.
* @public
* @returns {og.Vec3} - Light source position/direction.
* @returns {Vec3} - Light source position/direction.
*/
getPosition() {
return this._position.clone();
@ -193,8 +193,8 @@ class LightSource {
/**
* Set ambient color.
* @public
* @param {og.Vec3} rgb - Ambient color.
* @returns {og.LightSource}
* @param {Vec3} rgb - Ambient color.
* @returns {LightSource}
*/
setAmbient3v(rgb) {
return this.setAmbient(rgb.x, rgb.y, rgb.z);
@ -203,8 +203,8 @@ class LightSource {
/**
* Set diffuse color.
* @public
* @param {og.Vec3} rgb - Diffuse color.
* @returns {og.LightSource}
* @param {Vec3} rgb - Diffuse color.
* @returns {LightSource}
*/
setDiffuse3v(rgb) {
return this.setDiffuse(rgb.x, rgb.y, rgb.z);
@ -213,8 +213,8 @@ class LightSource {
/**
* Set specular color.
* @public
* @param {og.Vec3} rgb - Specular color.
* @returns {og.LightSource}
* @param {Vec3} rgb - Specular color.
* @returns {LightSource}
*/
setSpecular3v(rgb) {
return this.setSpecular(rgb.x, rgb.y, rgb.z);
@ -223,8 +223,8 @@ class LightSource {
/**
* Set ambient color.
* @public
* @param {og.Vec3} rgb - Ambient color.
* @returns {og.LightSource}
* @param {Vec3} rgb - Ambient color.
* @returns {LightSource}
*/
setAmbient(r, g, b) {
this._ambient.set(r, g, b);
@ -243,7 +243,7 @@ class LightSource {
/**
* Set diffuse color.
* @public
* @returns {og.LightSource}
* @returns {LightSource}
*/
setDiffuse(r, g, b) {
this._diffuse.set(r, g, b);
@ -262,7 +262,7 @@ class LightSource {
/**
* Set specular color.
* @public
* @returns {og.LightSource}
* @returns {LightSource}
*/
setSpecular(r, g, b) {
this._specular.set(r, g, b);
@ -281,7 +281,7 @@ class LightSource {
/**
* Set material shininess.
* @public
* @returns {og.LightSource}
* @returns {LightSource}
*/
setShininess(shininess) {
this._shininess = shininess;
@ -298,7 +298,7 @@ class LightSource {
/**
* Sets light to black.
* @public
* @returns {og.LightSource}
* @returns {LightSource}
*/
setBlack() {
this._ambient.clear();
@ -309,9 +309,16 @@ class LightSource {
if (rn) {
var index = 9 * rn._lightsNames.indexOf(this._name);
if (index != -1) {
rn._lightsParamsv[index] = rn._lightsParamsv[index + 1] = rn._lightsParamsv[index + 2] =
rn._lightsParamsv[index + 3] = rn._lightsParamsv[index + 4] = rn._lightsParamsv[index + 5] =
rn._lightsParamsv[index + 6] = rn._lightsParamsv[index + 7] = rn._lightsParamsv[index + 8] = 0;
rn._lightsParamsv[index] =
rn._lightsParamsv[index + 1] =
rn._lightsParamsv[index + 2] =
rn._lightsParamsv[index + 3] =
rn._lightsParamsv[index + 4] =
rn._lightsParamsv[index + 5] =
rn._lightsParamsv[index + 6] =
rn._lightsParamsv[index + 7] =
rn._lightsParamsv[index + 8] =
0;
}
}
return this;
@ -320,8 +327,8 @@ class LightSource {
/**
* Adds current light to the render node scene.
* @public
* @param {og.scene.RenderNode} renderNode - Render node scene.
* @returns {og.LightSource}
* @param {RenderNode} renderNode - Render node scene.
* @returns {LightSource}
*/
addTo(renderNode) {
this._renderNode = renderNode;

View File

@ -77,7 +77,7 @@ export const EPSILON20 = 1e-20;
* @param {number} base - Base value.
* @returns {number} -
* @example
* og.math.log(64, 2)
* log(64, 2)
* //returns 6
*/
export function log(n, base) {
@ -92,7 +92,7 @@ export function log(n, base) {
* @param {number} max - Maximal edge.
* @returns {number} -
* @example
* og.math.clamp(12, 1, 5)
* clamp(12, 1, 5)
* //returns 5
*/
export function clamp(number, min, max) {
@ -200,9 +200,9 @@ export function mod(m, n) {
* @returns {number} -
*/
export function zeroTwoPI(a) {
var mod = og.math.mod(a, og.math.TWO_PI);
if (Math.abs(mod) < og.math.EPSILON14 && Math.abs(a) > og.math.EPSILON14) {
return og.math.TWO_PI;
var mod = mod(a, TWO_PI);
if (Math.abs(mod) < EPSILON14 && Math.abs(a) > EPSILON14) {
return TWO_PI;
}
return mod;
}
@ -235,7 +235,7 @@ export function frac(x) {
* @returns {number} -
*/
export function log2(x) {
return Math.log(x) / og.math.LOG2;
return Math.log(x) / LOG2;
}
/**
@ -299,11 +299,11 @@ export function bezier1v(t, p0, p1, p2, p3) {
* Performs a 3D bezier interpolation.
* @function
* @param {number} t - Interpolation value.
* @param {og.Vec3} p0 - First control point.
* @param {og.Vec3} p1 - Second control point.
* @param {og.Vec3} p2 - Third control point.
* @param {og.Vec3} p3 - Fourth control point.
* @returns {og.Vec3} -
* @param {Vec3} p0 - First control point.
* @param {Vec3} p1 - Second control point.
* @param {Vec3} p2 - Third control point.
* @param {Vec3} p3 - Fourth control point.
* @returns {Vec3} -
*/
export function bezier3v(t, p0, p1, p2, p3) {
var u = 1 - t;
@ -346,7 +346,7 @@ export function norm_lon(lon) {
* @returns {number} -
*/
export function negativePItoPI(a) {
return og.math.zeroTwoPI(a + Math.PI) - Math.PI;
return zeroTwoPI(a + Math.PI) - Math.PI;
}
/**

View File

@ -2,17 +2,16 @@
* @module og/math/Mat3
*/
'use strict';
"use strict";
import { Mat4 } from './Mat4.js';
import { Vec3 } from './Vec3.js';
import { Mat4 } from "./Mat4.js";
import { Vec3 } from "./Vec3.js";
/**
* Class represents a 3x3 matrix.
* @class
*/
export class Mat3 {
constructor() {
/**
* A 3x3 matrix, indexable as a column-major order array.
@ -26,7 +25,7 @@ export class Mat3 {
* Sets column-major order array matrix.
* @public
* @param {Array.<number>} m - Matrix array.
* @returns {og.Mat3}
* @returns {Mat3}
*/
set(m) {
this._m[0] = m[0];
@ -44,7 +43,7 @@ export class Mat3 {
/**
* Duplicates a Mat3 instance.
* @public
* @returns {og.Mat3}
* @returns {Mat3}
*/
clone() {
var res = new Mat3();
@ -55,8 +54,8 @@ export class Mat3 {
/**
* Copy matrix.
* @public
* @param {og.Mat3} a - Matrix to copy.
* @returns {og.Mat3}
* @param {Mat3} a - Matrix to copy.
* @returns {Mat3}
*/
copy(a) {
return this.set(a._m);
@ -65,37 +64,51 @@ export class Mat3 {
/**
* Creates trasposed matrix from the current.
* @public
* @returns {og.Mat3}
* @returns {Mat3}
*/
transposeTo() {
var res = new Mat3();
var m = this._m;
res._m[0] = m[0]; res._m[1] = m[3]; res._m[2] = m[6];
res._m[3] = m[1]; res._m[4] = m[4]; res._m[5] = m[7];
res._m[6] = m[2]; res._m[7] = m[5]; res._m[8] = m[8];
res._m[0] = m[0];
res._m[1] = m[3];
res._m[2] = m[6];
res._m[3] = m[1];
res._m[4] = m[4];
res._m[5] = m[7];
res._m[6] = m[2];
res._m[7] = m[5];
res._m[8] = m[8];
return res;
}
/**
* Sets matrix to identity.
* @public
* @returns {og.Mat3}
* @returns {Mat3}
*/
setIdentity() {
this._m[0] = 1; this._m[1] = 0; this._m[2] = 0;
this._m[3] = 0; this._m[4] = 1; this._m[5] = 0;
this._m[6] = 0; this._m[7] = 0; this._m[8] = 1;
this._m[0] = 1;
this._m[1] = 0;
this._m[2] = 0;
this._m[3] = 0;
this._m[4] = 1;
this._m[5] = 0;
this._m[6] = 0;
this._m[7] = 0;
this._m[8] = 1;
return this;
}
/**
* Multiply to 3d vector.
* @public
* @params {og.Vec3} p - 3d vector.
* @returns {og.Vec3}
* @params {Vec3} p - 3d vector.
* @returns {Vec3}
*/
mulVec(p) {
var d = p.x, e = p.y, g = p.z;
var d = p.x,
e = p.y,
g = p.z;
var m = this._m;
return new Vec3(
m[0] * d + m[3] * e + m[6] * g,
@ -107,7 +120,7 @@ export class Mat3 {
/**
* Converts to 4x4 matrix.
* @public
* @returns {og.Mat4}
* @returns {Mat4}
*/
toMatrix4() {
var res = new Mat4();
@ -131,13 +144,12 @@ export class Mat3 {
b[15] = 1;
return res;
}
}
/**
* Mat3 factory.
* @static
* @return {og.Mat3}
* @return {Mat3}
*/
export function mat3() {
return new Mat3();

View File

@ -1,9 +1,9 @@
'use strict';
"use strict";
import { Mat3 } from './Mat3.js';
import { Quat } from './Quat.js';
import { Vec3 } from './Vec3.js';
import { Vec4 } from './Vec4.js';
import { Mat3 } from "./Mat3.js";
import { Quat } from "./Quat.js";
import { Vec3 } from "./Vec3.js";
import { Vec4 } from "./Vec4.js";
/**
* Class represents a 4x4 matrix.
@ -22,14 +22,26 @@ export class Mat4 {
/**
* Returns identity matrix instance.
* @static
* @returns {og.Mat4} -
* @returns {Mat4} -
*/
static get identity() {
static identity() {
var res = new Mat4();
res._m[0] = 1; res._m[1] = 0; res._m[2] = 0; res._m[3] = 0;
res._m[4] = 0; res._m[5] = 1; res._m[6] = 0; res._m[7] = 0;
res._m[8] = 0; res._m[9] = 0; res._m[10] = 1; res._m[11] = 0;
res._m[12] = 0; res._m[13] = 0; res._m[14] = 0; res._m[15] = 1;
res._m[0] = 1;
res._m[1] = 0;
res._m[2] = 0;
res._m[3] = 0;
res._m[4] = 0;
res._m[5] = 1;
res._m[6] = 0;
res._m[7] = 0;
res._m[8] = 0;
res._m[9] = 0;
res._m[10] = 1;
res._m[11] = 0;
res._m[12] = 0;
res._m[13] = 0;
res._m[14] = 0;
res._m[15] = 1;
return res;
}
@ -37,7 +49,7 @@ export class Mat4 {
* Sets column-major order array matrix.
* @public
* @param {Array.<number>} m - Matrix array.
* @returns {og.Mat4} -
* @returns {Mat4} -
*/
set(m) {
this._m[0] = m[0];
@ -62,7 +74,7 @@ export class Mat4 {
/**
* Duplicates a Matrix3 instance.
* @public
* @returns {og.Mat4} -
* @returns {Mat4} -
*/
clone() {
var res = new Mat4();
@ -73,7 +85,7 @@ export class Mat4 {
/**
* Copy matrix.
* @public
* @param {og.Mat3} a - Matrix to copy.
* @param {Mat3} a - Matrix to copy.
*/
copy(a) {
this.set(a._m);
@ -82,7 +94,7 @@ export class Mat4 {
/**
* Converts to 3x3 matrix.
* @public
* @returns {og.Mat3} -
* @returns {Mat3} -
*/
toMatrix3() {
var res = new Mat3();
@ -103,11 +115,13 @@ export class Mat4 {
/**
* Multiply to 3d vector.
* @public
* @param {og.Vec3} p - 3d vector.
* @returns {og.Vec3} -
* @param {Vec3} p - 3d vector.
* @returns {Vec3} -
*/
mulVec3(p) {
var d = p.x, e = p.y, g = p.z;
var d = p.x,
e = p.y,
g = p.z;
return new Vec3(
this._m[0] * d + this._m[4] * e + this._m[8] * g + this._m[12],
this._m[1] * d + this._m[5] * e + this._m[9] * g + this._m[13],
@ -118,11 +132,14 @@ export class Mat4 {
/**
* Multiply to 4d vector.
* @public
* @param {og.Vec4} p - 4d vector.
* @returns {og.Vec4} -
* @param {Vec4} p - 4d vector.
* @returns {Vec4} -
*/
mulVec4(p) {
var d = p.x, e = p.y, g = p.z, f = p.w;
var d = p.x,
e = p.y,
g = p.z,
f = p.w;
return new Vec4(
this._m[0] * d + this._m[4] * e + this._m[8] * g + this._m[12] * f,
this._m[1] * d + this._m[5] * e + this._m[9] * g + this._m[13] * f,
@ -134,13 +151,19 @@ export class Mat4 {
/**
* Creates an inversed 3x3 matrix of the current.
* @public
* @returns {og.Mat3} -
* @returns {Mat3} -
*/
toInverseMatrix3() {
var a = this._m;
var c = a[0], d = a[1], e = a[2],
g = a[4], f = a[5], h = a[6],
i = a[8], j = a[9], k = a[10],
var c = a[0],
d = a[1],
e = a[2],
g = a[4],
f = a[5],
h = a[6],
i = a[8],
j = a[9],
k = a[10],
l = k * f - h * j,
o = -k * g + h * i,
m = j * g - f * i,
@ -168,13 +191,25 @@ export class Mat4 {
/**
* Creates an inversed matrix of the current.
* @public
* @returns {og.Mat4} -
* @returns {Mat4} -
*/
inverseTo(res) {
var c = this._m[0], d = this._m[1], e = this._m[2], g = this._m[3],
f = this._m[4], h = this._m[5], i = this._m[6], j = this._m[7],
k = this._m[8], l = this._m[9], o = this._m[10], m = this._m[11],
n = this._m[12], p = this._m[13], r = this._m[14], s = this._m[15],
var c = this._m[0],
d = this._m[1],
e = this._m[2],
g = this._m[3],
f = this._m[4],
h = this._m[5],
i = this._m[6],
j = this._m[7],
k = this._m[8],
l = this._m[9],
o = this._m[10],
m = this._m[11],
n = this._m[12],
p = this._m[13],
r = this._m[14],
s = this._m[15],
A = c * h - d * f,
B = c * i - e * f,
t = c * j - g * f,
@ -187,76 +222,151 @@ export class Mat4 {
C = l * r - o * p,
D = l * s - m * p,
E = o * s - m * r,
q = 1 / (A * E - B * D + t * C + u * z - v * y + w * x),
q = 1 / (A * E - B * D + t * C + u * z - v * y + w * x);
res = res || new Mat4();
res._m[0] = (h * E - i * D + j * C) * q; res._m[1] = (-d * E + e * D - g * C) * q; res._m[2] = (p * w - r * v + s * u) * q; res._m[3] = (-l * w + o * v - m * u) * q;
res._m[4] = (-f * E + i * z - j * y) * q; res._m[5] = (c * E - e * z + g * y) * q; res._m[6] = (-n * w + r * t - s * B) * q; res._m[7] = (k * w - o * t + m * B) * q;
res._m[8] = (f * D - h * z + j * x) * q; res._m[9] = (-c * D + d * z - g * x) * q; res._m[10] = (n * v - p * t + s * A) * q; res._m[11] = (-k * v + l * t - m * A) * q;
res._m[12] = (-f * C + h * y - i * x) * q; res._m[13] = (c * C - d * y + e * x) * q; res._m[14] = (-n * u + p * B - r * A) * q; res._m[15] = (k * u - l * B + o * A) * q;
res._m[0] = (h * E - i * D + j * C) * q;
res._m[1] = (-d * E + e * D - g * C) * q;
res._m[2] = (p * w - r * v + s * u) * q;
res._m[3] = (-l * w + o * v - m * u) * q;
res._m[4] = (-f * E + i * z - j * y) * q;
res._m[5] = (c * E - e * z + g * y) * q;
res._m[6] = (-n * w + r * t - s * B) * q;
res._m[7] = (k * w - o * t + m * B) * q;
res._m[8] = (f * D - h * z + j * x) * q;
res._m[9] = (-c * D + d * z - g * x) * q;
res._m[10] = (n * v - p * t + s * A) * q;
res._m[11] = (-k * v + l * t - m * A) * q;
res._m[12] = (-f * C + h * y - i * x) * q;
res._m[13] = (c * C - d * y + e * x) * q;
res._m[14] = (-n * u + p * B - r * A) * q;
res._m[15] = (k * u - l * B + o * A) * q;
return res;
}
/**
* Creates a trasposed matrix of the current.
* @public
* @returns {og.Mat4} -
* @returns {Mat4} -
*/
transposeTo() {
var res = new Mat4();
res._m[0] = this._m[0]; res._m[1] = this._m[4]; res._m[2] = this._m[8]; res._m[3] = this._m[12];
res._m[4] = this._m[1]; res._m[5] = this._m[5]; res._m[6] = this._m[9]; res._m[7] = this._m[13];
res._m[8] = this._m[2]; res._m[9] = this._m[6]; res._m[10] = this._m[10]; res._m[11] = this._m[14];
res._m[12] = this._m[3]; res._m[13] = this._m[7]; res._m[14] = this._m[11]; res._m[15] = this._m[15];
res._m[0] = this._m[0];
res._m[1] = this._m[4];
res._m[2] = this._m[8];
res._m[3] = this._m[12];
res._m[4] = this._m[1];
res._m[5] = this._m[5];
res._m[6] = this._m[9];
res._m[7] = this._m[13];
res._m[8] = this._m[2];
res._m[9] = this._m[6];
res._m[10] = this._m[10];
res._m[11] = this._m[14];
res._m[12] = this._m[3];
res._m[13] = this._m[7];
res._m[14] = this._m[11];
res._m[15] = this._m[15];
return res;
}
/**
* Sets matrix to identity.
* @public
* @returns {og.Mat4} -
* @returns {Mat4} -
*/
setIdentity() {
this._m[0] = 1; this._m[1] = 0; this._m[2] = 0; this._m[3] = 0;
this._m[4] = 0; this._m[5] = 1; this._m[6] = 0; this._m[7] = 0;
this._m[8] = 0; this._m[9] = 0; this._m[10] = 1; this._m[11] = 0;
this._m[12] = 0; this._m[13] = 0; this._m[14] = 0; this._m[15] = 1;
this._m[0] = 1;
this._m[1] = 0;
this._m[2] = 0;
this._m[3] = 0;
this._m[4] = 0;
this._m[5] = 1;
this._m[6] = 0;
this._m[7] = 0;
this._m[8] = 0;
this._m[9] = 0;
this._m[10] = 1;
this._m[11] = 0;
this._m[12] = 0;
this._m[13] = 0;
this._m[14] = 0;
this._m[15] = 1;
return this;
}
/**
* Computes the product of two matrices.
* @public
* @param {og.Mat4} mx - Matrix to multiply.
* @returns {og.Mat4} -
* @param {Mat4} mx - Matrix to multiply.
* @returns {Mat4} -
*/
mul(mx) {
let d = this._m[0], e = this._m[1], g = this._m[2], f = this._m[3],
h = this._m[4], i = this._m[5], j = this._m[6], k = this._m[7],
l = this._m[8], o = this._m[9], m = this._m[10], n = this._m[11],
p = this._m[12], r = this._m[13], s = this._m[14], a = this._m[15];
let d = this._m[0],
e = this._m[1],
g = this._m[2],
f = this._m[3],
h = this._m[4],
i = this._m[5],
j = this._m[6],
k = this._m[7],
l = this._m[8],
o = this._m[9],
m = this._m[10],
n = this._m[11],
p = this._m[12],
r = this._m[13],
s = this._m[14],
a = this._m[15];
let A = mx._m[0], B = mx._m[1], t = mx._m[2], u = mx._m[3],
v = mx._m[4], w = mx._m[5], x = mx._m[6], y = mx._m[7],
z = mx._m[8], C = mx._m[9], D = mx._m[10], E = mx._m[11],
q = mx._m[12], F = mx._m[13], G = mx._m[14], b = mx._m[15];
let A = mx._m[0],
B = mx._m[1],
t = mx._m[2],
u = mx._m[3],
v = mx._m[4],
w = mx._m[5],
x = mx._m[6],
y = mx._m[7],
z = mx._m[8],
C = mx._m[9],
D = mx._m[10],
E = mx._m[11],
q = mx._m[12],
F = mx._m[13],
G = mx._m[14],
b = mx._m[15];
var res = new Mat4();
res._m[0] = A * d + B * h + t * l + u * p; res._m[1] = A * e + B * i + t * o + u * r; res._m[2] = A * g + B * j + t * m + u * s; res._m[3] = A * f + B * k + t * n + u * a;
res._m[4] = v * d + w * h + x * l + y * p; res._m[5] = v * e + w * i + x * o + y * r; res._m[6] = v * g + w * j + x * m + y * s; res._m[7] = v * f + w * k + x * n + y * a;
res._m[8] = z * d + C * h + D * l + E * p; res._m[9] = z * e + C * i + D * o + E * r; res._m[10] = z * g + C * j + D * m + E * s; res._m[11] = z * f + C * k + D * n + E * a;
res._m[12] = q * d + F * h + G * l + b * p; res._m[13] = q * e + F * i + G * o + b * r; res._m[14] = q * g + F * j + G * m + b * s; res._m[15] = q * f + F * k + G * n + b * a;
res._m[0] = A * d + B * h + t * l + u * p;
res._m[1] = A * e + B * i + t * o + u * r;
res._m[2] = A * g + B * j + t * m + u * s;
res._m[3] = A * f + B * k + t * n + u * a;
res._m[4] = v * d + w * h + x * l + y * p;
res._m[5] = v * e + w * i + x * o + y * r;
res._m[6] = v * g + w * j + x * m + y * s;
res._m[7] = v * f + w * k + x * n + y * a;
res._m[8] = z * d + C * h + D * l + E * p;
res._m[9] = z * e + C * i + D * o + E * r;
res._m[10] = z * g + C * j + D * m + E * s;
res._m[11] = z * f + C * k + D * n + E * a;
res._m[12] = q * d + F * h + G * l + b * p;
res._m[13] = q * e + F * i + G * o + b * r;
res._m[14] = q * g + F * j + G * m + b * s;
res._m[15] = q * f + F * k + G * n + b * a;
return res;
}
/**
* Add translation vector to the current matrix.
* @public
* @param {og.Vec3} v - Translate vector.
* @returns {og.Mat4} -
* @param {Vec3} v - Translate vector.
* @returns {Mat4} -
*/
translate(v) {
var d = v.x, e = v.y, b = v.z;
var d = v.x,
e = v.y,
b = v.z;
var a = this._m;
a[12] = a[0] * d + a[4] * e + a[8] * b + a[12];
a[13] = a[1] * d + a[5] * e + a[9] * b + a[13];
@ -268,8 +378,8 @@ export class Mat4 {
/**
* Sets translation matrix to the position.
* @public
* @param {og.Vec3} v - Translate to position.
* @returns {og.Mat4} -
* @param {Vec3} v - Translate to position.
* @returns {Mat4} -
*/
translateToPosition(v) {
var a = this._m;
@ -282,9 +392,9 @@ export class Mat4 {
/**
* Rotate currrent matrix around the aligned axis and angle.
* @public
* @param {og.Vec3} u - Aligned axis.
* @param {Vec3} u - Aligned axis.
* @param {number} angle - Aligned axis angle in radians.
* @returns {og.Mat4} -
* @returns {Mat4} -
* @todo: OPTIMIZE: reveal multiplication
*/
rotate(u, angle) {
@ -292,37 +402,61 @@ export class Mat4 {
s = Math.sin(angle);
var rot = new Mat4();
var mx = rot._m;
mx[0] = c + (1 - c) * u.x * u.x; mx[1] = (1 - c) * u.y * u.x - s * u.z; mx[2] = (1 - c) * u.z * u.x + s * u.y; mx[3] = 0;
mx[4] = (1 - c) * u.x * u.y + s * u.z; mx[5] = c + (1 - c) * u.y * u.y; mx[6] = (1 - c) * u.z * u.y - s * u.x; mx[7] = 0;
mx[8] = (1 - c) * u.x * u.z - s * u.y; mx[9] = (1 - c) * u.y * u.z + s * u.x; mx[10] = c + (1 - c) * u.z * u.z; mx[11] = 0;
mx[12] = 0; mx[13] = 0; mx[14] = 0; mx[15] = 1;
mx[0] = c + (1 - c) * u.x * u.x;
mx[1] = (1 - c) * u.y * u.x - s * u.z;
mx[2] = (1 - c) * u.z * u.x + s * u.y;
mx[3] = 0;
mx[4] = (1 - c) * u.x * u.y + s * u.z;
mx[5] = c + (1 - c) * u.y * u.y;
mx[6] = (1 - c) * u.z * u.y - s * u.x;
mx[7] = 0;
mx[8] = (1 - c) * u.x * u.z - s * u.y;
mx[9] = (1 - c) * u.y * u.z + s * u.x;
mx[10] = c + (1 - c) * u.z * u.z;
mx[11] = 0;
mx[12] = 0;
mx[13] = 0;
mx[14] = 0;
mx[15] = 1;
return this.mul(rot);
}
/**
* Sets current rotation matrix around the aligned axis and angle.
* @public
* @param {og.Vec3} u - Aligned axis.
* @param {Vec3} u - Aligned axis.
* @param {number} angle - Aligned axis angle in radians.
* @returns {og.Mat4} -
* @returns {Mat4} -
*/
setRotation(u, angle) {
var c = Math.cos(angle),
s = Math.sin(angle);
var mx = this._m;
mx[0] = c + (1 - c) * u.x * u.x; mx[1] = (1 - c) * u.y * u.x - s * u.z; mx[2] = (1 - c) * u.z * u.x + s * u.y; mx[3] = 0;
mx[4] = (1 - c) * u.x * u.y + s * u.z; mx[5] = c + (1 - c) * u.y * u.y; mx[6] = (1 - c) * u.z * u.y - s * u.x; mx[7] = 0;
mx[8] = (1 - c) * u.x * u.z - s * u.y; mx[9] = (1 - c) * u.y * u.z + s * u.x; mx[10] = c + (1 - c) * u.z * u.z; mx[11] = 0;
mx[12] = 0; mx[13] = 0; mx[14] = 0; mx[15] = 1;
mx[0] = c + (1 - c) * u.x * u.x;
mx[1] = (1 - c) * u.y * u.x - s * u.z;
mx[2] = (1 - c) * u.z * u.x + s * u.y;
mx[3] = 0;
mx[4] = (1 - c) * u.x * u.y + s * u.z;
mx[5] = c + (1 - c) * u.y * u.y;
mx[6] = (1 - c) * u.z * u.y - s * u.x;
mx[7] = 0;
mx[8] = (1 - c) * u.x * u.z - s * u.y;
mx[9] = (1 - c) * u.y * u.z + s * u.x;
mx[10] = c + (1 - c) * u.z * u.z;
mx[11] = 0;
mx[12] = 0;
mx[13] = 0;
mx[14] = 0;
mx[15] = 1;
return this;
}
/**
* Gets the rotation matrix from one vector to another.
* @public
* @param {og.Vec3} a - Firtst vector.
* @param {og.Vec3} b - Second vector.
* @returns {og.Mat4} -
* @param {Vec3} a - Firtst vector.
* @param {Vec3} b - Second vector.
* @returns {Mat4} -
*/
rotateBetweenVectors(a, b) {
var q = Quat.getRotationBetweenVectors(a, b);
@ -332,14 +466,23 @@ export class Mat4 {
/**
* Scale current matrix to the vector values.
* @public
* @param {og.Vec3} v - Scale vector.
* @returns {og.Mat4} -
* @param {Vec3} v - Scale vector.
* @returns {Mat4} -
*/
scale(v) {
var mx = this._m;
mx[0] = mx[0] * v.x; mx[1] = mx[1] * v.x; mx[2] = mx[2] * v.x; mx[3] = mx[3] * v.x;
mx[4] = mx[4] * v.y; mx[5] = mx[5] * v.y; mx[6] = mx[6] * v.y; mx[7] = mx[7] * v.y;
mx[8] = mx[8] * v.z; mx[9] = mx[9] * v.z; mx[10] = mx[10] * v.z; mx[11] = mx[11] * v.z;
mx[0] = mx[0] * v.x;
mx[1] = mx[1] * v.x;
mx[2] = mx[2] * v.x;
mx[3] = mx[3] * v.x;
mx[4] = mx[4] * v.y;
mx[5] = mx[5] * v.y;
mx[6] = mx[6] * v.y;
mx[7] = mx[7] * v.y;
mx[8] = mx[8] * v.z;
mx[9] = mx[9] * v.z;
mx[10] = mx[10] * v.z;
mx[11] = mx[11] * v.z;
return this;
}
@ -352,16 +495,18 @@ export class Mat4 {
* @param {number} top -
* @param {number} near -
* @param {number} far -
* @returns {og.Mat4} -
* @returns {Mat4} -
*/
setPerspective(left, right, bottom, top, near, far) {
var h = right - left, i = top - bottom, j = far - near;
this._m[0] = near * 2 / h;
var h = right - left,
i = top - bottom,
j = far - near;
this._m[0] = (near * 2) / h;
this._m[1] = 0;
this._m[2] = 0;
this._m[3] = 0;
this._m[4] = 0;
this._m[5] = near * 2 / i;
this._m[5] = (near * 2) / i;
this._m[6] = 0;
this._m[7] = 0;
this._m[8] = (right + left) / h;
@ -384,10 +529,9 @@ export class Mat4 {
* @param {number} top -
* @param {number} near -
* @param {number} far -
* @return {og.Mat4} -
* @return {Mat4} -
*/
setOrtho(left, right, bottom, top, near, far) {
var lr = 1.0 / (left - right),
bt = 1.0 / (bottom - top),
nf = 1.0 / (near - far),
@ -418,7 +562,7 @@ export class Mat4 {
* @param {number} ax - Rotation angle in radians arond X axis.
* @param {number} ay - Rotation angle in radians arond Y axis.
* @param {number} az - Rotation angle in radians arond Z axis.
* @returns {og.Mat4} -
* @returns {Mat4} -
*/
eulerToMatrix(ax, ay, az) {
var a = Math.cos(ax),
@ -452,8 +596,8 @@ export class Mat4 {
/**
* Mat4 factory.
* @static
* @returns {og.Mat4} -
* @returns {Mat4} -
*/
export function mat4() {
return new og.Mat4();
return new Mat4();
}

View File

@ -1,18 +1,18 @@
'use strict';
"use strict";
import * as math from '../math.js';
import { Vec3 } from './Vec3.js';
import * as math from "../math.js";
import { Vec3 } from "./Vec3.js";
/**
* Plane class.
* @constructor
* @param {og.Vec3} [p] - Plane point.
* @param {og.Vec3} [n] - Planet normal.
* @param {Vec3} [p] - Plane point.
* @param {Vec3} [n] - Planet normal.
*/
class Plane {
constructor(p, n) {
this.p = (p ? p.clone() : new Vec3());
this.n = (n ? n.clone() : this.p.normal());
this.p = p ? p.clone() : new Vec3();
this.n = n ? n.clone() : this.p.normal();
}
set(p, n) {
@ -47,18 +47,19 @@ class Plane {
}
getIntersection(Pn1, Pn2, L) {
var u = Pn1.n.cross(Pn2.n);
var ax = (u.x >= 0 ? u.x : -u.x);
var ay = (u.y >= 0 ? u.y : -u.y);
var az = (u.z >= 0 ? u.z : -u.z);
var ax = u.x >= 0 ? u.x : -u.x;
var ay = u.y >= 0 ? u.y : -u.y;
var az = u.z >= 0 ? u.z : -u.z;
// test if the two planes are parallel
if ((ax + ay + az) < math.EPSILON5) { // Pn1 and Pn2 are near parallel
if (ax + ay + az < math.EPSILON5) {
// Pn1 and Pn2 are near parallel
// test if disjoint or coincide
var v = Pn2.p.sub(Pn1.p);
if (Pn1.n.dot(v) == 0) { // Pn2.V0 lies in Pn1
if (Pn1.n.dot(v) == 0) {
// Pn2.V0 lies in Pn1
return 1; // Pn1 and Pn2 coincide
} else {
return 0; // Pn1 and Pn2 are disjoint

View File

@ -1,9 +1,9 @@
'use strict';
"use strict";
import * as math from '../math.js';
import { Mat3 } from './Mat3.js';
import { Mat4 } from './Mat4.js';
import { Vec3 } from './Vec3.js';
import * as math from "../math.js";
import { Mat3 } from "./Mat3.js";
import { Mat4 } from "./Mat4.js";
import { Vec3 } from "./Vec3.js";
/**
* A set of 4-dimensional coordinates used to represent rotation in 3-dimensional space.
@ -14,7 +14,6 @@ import { Vec3 } from './Vec3.js';
* @param {Number} [w=0.0] The W component.
*/
export class Quat {
/**
* @param {Number} [x=0.0] The X component.
* @param {Number} [y=0.0] The Y component.
@ -58,7 +57,7 @@ export class Quat {
/**
* Identity Quat.
* @const
* @type {og.Quat}
* @type {Quat}
*/
static get IDENTITY() {
return new Quat(0.0, 0.0, 0.0, 1.0);
@ -68,7 +67,7 @@ export class Quat {
* Returns a Quat represents rotation around X axis.
* @static
* @param {number} a - The angle in radians to rotate around the axis.
* @returns {og.Quat} -
* @returns {Quat} -
*/
static xRotation(a) {
a *= 0.5;
@ -79,7 +78,7 @@ export class Quat {
* Returns a Quat represents rotation around Y axis.
* @static
* @param {number} a - The angle in radians to rotate around the axis.
* @returns {og.Quat} -
* @returns {Quat} -
*/
static yRotation(a) {
a *= 0.5;
@ -90,7 +89,7 @@ export class Quat {
* Returns a Quat represents rotation around Z axis.
* @static
* @param {number} a - The angle in radians to rotate around the axis.
* @returns {og.Quat} -
* @returns {Quat} -
*/
static zRotation(a) {
a *= 0.5;
@ -100,90 +99,65 @@ export class Quat {
/**
* Computes a Quat representing a rotation around an axis.
* @static
* @param {og.Vec3} axis - The axis of rotation.
* @param {Vec3} axis - The axis of rotation.
* @param {number} [angle=0.0] The angle in radians to rotate around the axis.
* @returns {og.Quat} -
* @returns {Quat} -
*/
static axisAngleToQuat(axis, angle) {
angle = angle || 0.0;
var v = axis.normal();
var half_angle = angle * 0.5;
var sin_a = Math.sin(half_angle);
return new Quat(
v.x * sin_a,
v.y * sin_a,
v.z * sin_a,
Math.cos(half_angle));
return new Quat(v.x * sin_a, v.y * sin_a, v.z * sin_a, Math.cos(half_angle));
}
/**
* Computes a rotation from the given heading and up vector.
* @static
* @param {og.Vec3} forward - Heading target coordinates.
* @param {og.Vec3} up - Up vector.
* @returns {og.Quat} -
* @param {Vec3} forward - Heading target coordinates.
* @param {Vec3} up - Up vector.
* @returns {Quat} -
*/
static getLookRotation(forward, up) {
var f = forward.normal().negate();
var s = (up.cross(f)).normalize();
var s = up.cross(f).normalize();
var u = f.cross(s);
var z = 1.0 + s.x + u.y + f.z;
if (z > 0.000001) {
let fd = 1.0 / (2.0 * Math.sqrt(z));
return new Quat(
(f.y - u.z) * fd,
(s.z - f.x) * fd,
(u.x - s.y) * fd,
0.25 / fd
);
return new Quat((f.y - u.z) * fd, (s.z - f.x) * fd, (u.x - s.y) * fd, 0.25 / fd);
}
if (s.x > u.y && s.x > f.z) {
let fd = 1.0 / (2.0 * Math.sqrt(1.0 + s.x - u.y - f.z));
return new Quat(
0.25 / fd,
(u.x + s.y) * fd,
(s.z + f.x) * fd,
(f.y - u.z) * fd
);
return new Quat(0.25 / fd, (u.x + s.y) * fd, (s.z + f.x) * fd, (f.y - u.z) * fd);
}
if (u.y > f.z) {
let fd = 1.0 / (2.0 * Math.sqrt(1.0 + u.y - s.x - f.z));
return new Quat(
(u.x + s.y) * fd,
0.25 / fd,
(f.y + u.z) * fd,
(s.z - f.x) * fd
);
return new Quat((u.x + s.y) * fd, 0.25 / fd, (f.y + u.z) * fd, (s.z - f.x) * fd);
}
let fd = 1.0 / (2.0 * Math.sqrt(1.0 + f.z - s.x - u.y));
return new Quat(
(s.z + f.x) * fd,
(f.y + u.z) * fd,
0.25 / fd,
(u.x - s.y) * fd
);
return new Quat((s.z + f.x) * fd, (f.y + u.z) * fd, 0.25 / fd, (u.x - s.y) * fd);
}
/**
* Computes a Quat from from source point heading to the destination point.
* @static
* @param {og.Vec3} sourcePoint - Source coordinate.
* @param {og.Vec3} destPoint - Destination coordinate.
* @returns {og.Quat} -
* @param {Vec3} sourcePoint - Source coordinate.
* @param {Vec3} destPoint - Destination coordinate.
* @returns {Quat} -
*/
static getLookAtSourceDest(sourcePoint, destPoint) {
var forwardVector = destPoint.subA(sourcePoint).normalize();
var dot = Vec3.FORWARD.dot(forwardVector);
if (Math.abs(dot - (-1.0)) < 0.000001) {
if (Math.abs(dot - -1.0) < 0.000001) {
return Quat.axisAngleToQuat(Vec3.UP, Math.PI);
}
if (Math.abs(dot - (1.0)) < 0.000001) {
if (Math.abs(dot - 1.0) < 0.000001) {
return new Quat(0.0, 0.0, 0.0, 1.0);
}
var rotAngle = Math.acos(dot);
@ -194,9 +168,9 @@ export class Quat {
/**
* Compute rotation between two vectors.
* @static
* @param {og.Vec3} u - First vector.
* @param {og.Vec3} v - Second vector.
* @returns {og.Quat} -
* @param {Vec3} u - First vector.
* @param {Vec3} v - Second vector.
* @returns {Quat} -
*/
static getRotationBetweenVectors(u, v) {
var w = u.cross(v);
@ -207,10 +181,10 @@ export class Quat {
/**
* Compute rotation between two vectors.
* @static
* @param {og.Vec3} u - First vector.
* @param {og.Vec3} v - Second vector.
* @param {Vec3} u - First vector.
* @param {Vec3} v - Second vector.
* @param {Quat} res
* @returns {og.Quat} -
* @returns {Quat} -
*/
static getRotationBetweenVectorsRes(u, v, res) {
var w = u.cross(v);
@ -223,10 +197,10 @@ export class Quat {
* for exactly opposite vectors. If vectors exaclty in the same
* direction than returns identity Quat.
* @static
* @param {og.Vec3} source - First vector.
* @param {og.Vec3} dest - Second vector.
* @param {og.Vec3} up - Up vector.
* @returns {og.Quat} -
* @param {Vec3} source - First vector.
* @param {Vec3} dest - Second vector.
* @param {Vec3} up - Up vector.
* @returns {Quat} -
*/
static getRotationBetweenVectorsUp(source, dest, up) {
var dot = source.dot(dest);
@ -248,8 +222,8 @@ export class Quat {
/**
* Returns true if the components are zero.
* @public
* @param {og.Quat} q - Quat to subtract.
* @returns {og.Quat} -
* @param {Quat} q - Quat to subtract.
* @returns {Quat} -
*/
isZero() {
return this.x === 0.0 && this.y === 0.0 && this.z === 0.0 && this.w === 0.0;
@ -258,7 +232,7 @@ export class Quat {
/**
* Clear Quat. Sets zeroes.
* @public
* @returns {og.Quat} -
* @returns {Quat} -
*/
clear() {
this.x = this.y = this.z = this.w = 0;
@ -272,7 +246,7 @@ export class Quat {
* @param {Number} [y=0.0] The Y component.
* @param {Number} [z=0.0] The Z component.
* @param {Number} [w=0.0] The W component.
* @returns {og.Quat} -
* @returns {Quat} -
*/
set(x, y, z, w) {
this.x = x;
@ -285,8 +259,8 @@ export class Quat {
/**
* Copy Quat values.
* @public
* @param {og.Quat} q - Copy Quat.
* @returns {og.Quat} -
* @param {Quat} q - Copy Quat.
* @returns {Quat} -
*/
copy(q) {
this.x = q.x;
@ -299,7 +273,7 @@ export class Quat {
/**
* Set current Quat instance to identity Quat.
* @public
* @returns {og.Quat} -
* @returns {Quat} -
*/
setIdentity() {
this.x = 0.0;
@ -312,7 +286,7 @@ export class Quat {
/**
* Duplicates a Quat instance.
* @public
* @returns {og.Quat} -
* @returns {Quat} -
*/
clone() {
return new Quat(this.x, this.y, this.z, this.w);
@ -321,8 +295,8 @@ export class Quat {
/**
* Computes the componentwise sum of two Quats.
* @public
* @param {og.Quat} q - Quat to add.
* @returns {og.Quat} -
* @param {Quat} q - Quat to add.
* @returns {Quat} -
*/
add(q) {
return new Quat(this.x + q.x, this.y + q.y, this.z + q.z, this.w + q.w);
@ -331,8 +305,8 @@ export class Quat {
/**
* Computes the componentwise difference of two Quats.
* @public
* @param {og.Quat} q - Quat to subtract.
* @returns {og.Quat} -
* @param {Quat} q - Quat to subtract.
* @returns {Quat} -
*/
sub(q) {
return new Quat(this.x - q.x, this.y - q.y, this.z - q.z, this.w - q.w);
@ -342,7 +316,7 @@ export class Quat {
* Multiplies the provided Quat componentwise by the provided scalar.
* @public
* @param {Number} scale - The scalar to multiply with.
* @returns {og.Quat} -
* @returns {Quat} -
*/
scaleTo(scale) {
return new Quat(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
@ -352,10 +326,13 @@ export class Quat {
* Multiplies the provided Quat componentwise.
* @public
* @param {Number} scale - The scalar to multiply with.
* @returns {og.Quat} -
* @returns {Quat} -
*/
scale(scale) {
this.x *= scale; this.y *= scale; this.z *= scale; this.w *= scale;
this.x *= scale;
this.y *= scale;
this.z *= scale;
this.w *= scale;
return this;
}
@ -374,7 +351,7 @@ export class Quat {
* @param {number} lat - Latitude.
* @param {number} lon - Longitude.
* @param {number} angle - Angle in radians.
* @returns {og.Quat} -
* @returns {Quat} -
*/
setFromSphericalCoords(lat, lon, angle) {
var sin_a = Math.sin(angle / 2);
@ -393,14 +370,13 @@ export class Quat {
/**
* Sets rotation with the given heading and up vectors.
* @static
* @param {og.Vec3} forward - Heading target coordinates.
* @param {og.Vec3} up - Up vector.
* @returns {og.Quat} -
* @param {Vec3} forward - Heading target coordinates.
* @param {Vec3} up - Up vector.
* @returns {Quat} -
*/
setLookRotation(forward, up) {
var f = forward.normal().negate();
var s = (up.cross(f)).normalize();
var s = up.cross(f).normalize();
var u = f.cross(s);
var z = 1.0 + s.x + u.y + f.z;
@ -450,7 +426,8 @@ export class Quat {
var ty = this.y / sin_a;
var tz = this.z / sin_a;
var lon, lat = -Math.asin(ty);
var lon,
lat = -Math.asin(ty);
if (tx * tx + tz * tz < 0.0005) {
lon = 0;
} else {
@ -466,9 +443,9 @@ export class Quat {
/**
* Sets current Quat representing a rotation around an axis.
* @public
* @param {og.Vec3} axis - The axis of rotation.
* @param {Vec3} axis - The axis of rotation.
* @param {number} angle The angle in radians to rotate around the axis.
* @returns {og.Quat} -
* @returns {Quat} -
*/
setFromAxisAngle(axis, angle) {
var v = axis.normal();
@ -484,12 +461,16 @@ export class Quat {
* @returns {Object} -
*/
getAxisAngle() {
var vl = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
let x = this.x,
y = this.y,
z = this.z,
w = this.w;
var vl = Math.sqrt(x * x + y * y + z * z);
var axis, angle;
if (vl > 0.0000001) {
var ivl = 1.0 / vl;
axis = new Vec3(x * ivl, y * ivl, z * ivl);
if (this.w < 0) {
if (w < 0) {
angle = 2.0 * Math.atan2(-vl, -w); // -PI,0
} else {
angle = 2.0 * Math.atan2(vl, w); // 0,PI
@ -507,7 +488,7 @@ export class Quat {
* @param {number} pitch - Pitch angle in degrees.
* @param {number} yaw - Yaw angle in degrees.
* @param {number} roll - Roll angle in degrees.
* @returns {og.Quat} -
* @returns {Quat} -
*/
setFromEulerAngles(pitch, yaw, roll) {
var ex = pitch * math.RADIANS_HALF,
@ -539,8 +520,10 @@ export class Quat {
* @returns {Object} -
*/
getEulerAngles() {
let x = this.x, y = this.y, z = this.z, w = this.w;
let x = this.x,
y = this.y,
z = this.z,
w = this.w;
let sqy = y * y;
@ -563,11 +546,13 @@ export class Quat {
/**
* Computes a Quat from the provided 4x4 matrix instance.
* @public
* @param {og.Mat4} m - The rotation matrix.
* @returns {og.Quat} -
* @param {Mat4} m - The rotation matrix.
* @returns {Quat} -
*/
setFromMatrix4(m) {
var tr, s, q = [];
var tr,
s,
q = [];
var i, j, k;
m = m._m;
@ -589,7 +574,7 @@ export class Quat {
j = nxt[i];
k = nxt[j];
s = Math.sqrt((m[i * 5] - (m[j * 5] + m[k * 5])) + 1.0);
s = Math.sqrt(m[i * 5] - (m[j * 5] + m[k * 5]) + 1.0);
q[i] = s * 0.5;
@ -610,7 +595,7 @@ export class Quat {
/**
* Converts current Quat to the rotation 4x4 matrix.
* @public
* @returns {og.Mat4} -
* @returns {Mat4} -
*/
getMat4(out) {
var xs = this.x + this.x;
@ -626,13 +611,30 @@ export class Quat {
var yz = this.y * zs;
var zz = this.z * zs;
var m = out || new Mat4();
return m.set([1 - (yy + zz), xy - wz, xz + wy, 0, xy + wz, 1 - (xx + zz), yz - wx, 0, xz - wy, yz + wx, 1 - (xx + yy), 0, 0, 0, 0, 1]);
return m.set([
1 - (yy + zz),
xy - wz,
xz + wy,
0,
xy + wz,
1 - (xx + zz),
yz - wx,
0,
xz - wy,
yz + wx,
1 - (xx + yy),
0,
0,
0,
0,
1
]);
}
/**
* Converts current Quat to the rotation 3x3 matrix.
* @public
* @returns {og.Mat3} -
* @returns {Mat3} -
* @todo NOT TESTED
*/
getMat3() {
@ -658,9 +660,15 @@ export class Quat {
h = g * h;
g = g * i;
mx[0] = 1 - (l + e); mx[1] = k - g; mx[2] = c + h;
mx[3] = k + g; mx[4] = 1 - (j + e); mx[5] = d - f;
mx[6] = c - h; mx[7] = d + f; mx[8] = 1 - (j + l);
mx[0] = 1 - (l + e);
mx[1] = k - g;
mx[2] = c + h;
mx[3] = k + g;
mx[4] = 1 - (j + e);
mx[5] = d - f;
mx[6] = c - h;
mx[7] = d + f;
mx[8] = 1 - (j + l);
return m;
}
@ -668,11 +676,10 @@ export class Quat {
/**
* Returns quatrenion and vector production.
* @public
* @param {og.Vec3} v - 3d Vector.
* @returns {og.Vec3} -
* @param {Vec3} v - 3d Vector.
* @returns {Vec3} -
*/
mulVec3(v) {
// t = 2 * cross(q.xyz, v)
// v' = v + q.w * t + cross(q.xyz, t)
@ -694,34 +701,48 @@ export class Quat {
return new Vec3(
i * a + d * -b + j * -h - k * -f,
j * a + d * -f + k * -b - i * -h,
k * a + d * -h + i * -f - j * -b);
k * a + d * -h + i * -f - j * -b
);
}
/**
* Computes the product of two Quats.
* @public
* @param {og.Quat} q - Quat to multiply.
* @returns {og.Quat} -
* @param {Quat} q - Quat to multiply.
* @returns {Quat} -
*/
mul(q) {
var d = this.x, e = this.y, g = this.z, a = this.w;
var f = q.x, h = q.y, i = q.z, b = q.w;
var d = this.x,
e = this.y,
g = this.z,
a = this.w;
var f = q.x,
h = q.y,
i = q.z,
b = q.w;
return new Quat(
d * b + a * f + e * i - g * h,
e * b + a * h + g * f - d * i,
g * b + a * i + d * h - e * f,
a * b - d * f - e * h - g * i);
a * b - d * f - e * h - g * i
);
}
/**
* Computes the product of two Quats.
* @public
* @param {og.Quat} q - Quat to multiply.
* @returns {og.Quat} -
* @param {Quat} q - Quat to multiply.
* @returns {Quat} -
*/
mulA(q) {
var d = this.x, e = this.y, g = this.z, a = this.w;
var f = q.x, h = q.y, i = q.z, b = q.w;
var d = this.x,
e = this.y,
g = this.z,
a = this.w;
var f = q.x,
h = q.y,
i = q.z,
b = q.w;
this.x = d * b + a * f + e * i - g * h;
this.y = e * b + a * h + g * f - d * i;
this.z = g * b + a * i + d * h - e * f;
@ -732,7 +753,7 @@ export class Quat {
/**
* Gets the conjugate of the Quat.
* @public
* @returns {og.Quat} -
* @returns {Quat} -
*/
conjugate() {
return new Quat(-this.x, -this.y, -this.z, this.w);
@ -741,7 +762,7 @@ export class Quat {
/**
* Computes the inverse of the Quat.
* @public
* @returns {og.Quat} -
* @returns {Quat} -
*/
inverse() {
var n = 1 / this.magnitude2();
@ -754,7 +775,10 @@ export class Quat {
* @returns {number} -
*/
magnitude() {
var b = this.x, c = this.y, d = this.z, a = this.w;
var b = this.x,
c = this.y,
d = this.z,
a = this.w;
return Math.sqrt(b * b + c * c + d * d + a * a);
}
@ -764,14 +788,17 @@ export class Quat {
* @returns {number} -
*/
magnitude2() {
var b = this.x, c = this.y, d = this.z, a = this.w;
var b = this.x,
c = this.y,
d = this.z,
a = this.w;
return b * b + c * c + d * d + a * a;
}
/**
* Computes the dot (scalar) product of two Quats.
* @public
* @param {og.Quat} q - Second quatrnion.
* @param {Quat} q - Second quatrnion.
* @returns {number} -
*/
dot(q) {
@ -781,10 +808,13 @@ export class Quat {
/**
* Current Quat normalization.
* @public
* @returns {og.Quat} -
* @returns {Quat} -
*/
normalize() {
var c = this.x, d = this.y, e = this.z, g = this.w,
var c = this.x,
d = this.y,
e = this.z,
g = this.w,
f = Math.sqrt(c * c + d * d + e * e + g * g);
if (f === 0.0) {
this.x = 0;
@ -804,7 +834,7 @@ export class Quat {
/**
* Compares two Quats.
* @public
* @param {og.Quat} q - Second quatrnion.
* @param {Quat} q - Second quatrnion.
* @returns {Boolean} -
*/
isEqual(q) {
@ -818,14 +848,19 @@ export class Quat {
/**
* Performs a spherical linear interpolation between two Quats.
* @public
* @param {og.Quat} b - The end rotation Quat.
* @param {Quat} b - The end rotation Quat.
* @param {number} t - interpolation amount between the two Quats.
* @returns {og.Quat} -
* @returns {Quat} -
*/
slerp(b, t) {
var ax = this.x, ay = this.y, az = this.z, aw = this.w,
bx = b.x, by = b.y, bz = b.z, bw = b.w;
var ax = this.x,
ay = this.y,
az = this.z,
aw = this.w,
bx = b.x,
by = b.y,
bz = b.z,
bw = b.w;
var omega, cosom, sinom, scale0, scale1;
@ -839,7 +874,7 @@ export class Quat {
bw = -bw;
}
if ((1.0 - cosom) > 0.000001) {
if (1.0 - cosom > 0.000001) {
omega = Math.acos(cosom);
sinom = Math.sin(omega);
scale0 = Math.sin((1.0 - t) * omega) / sinom;
@ -864,7 +899,10 @@ export class Quat {
* @returns {Number} -
*/
getRoll(reprojectAxis) {
var x = this.x, y = this.y, z = this.z, w = this.w;
var x = this.x,
y = this.y,
z = this.z,
w = this.w;
if (reprojectAxis) {
var fTy = 2.0 * y;
var fTz = 2.0 * z;
@ -885,7 +923,10 @@ export class Quat {
* @returns {number} -
*/
getPitch(reprojectAxis) {
var x = this.x, y = this.y, z = this.z, w = this.w;
var x = this.x,
y = this.y,
z = this.z,
w = this.w;
if (reprojectAxis) {
var fTx = 2.0 * x;
var fTz = 2.0 * z;
@ -906,7 +947,10 @@ export class Quat {
* @returns {number} -
*/
getYaw(reprojectAxis) {
var x = this.x, y = this.y, z = this.z, w = this.w;
var x = this.x,
y = this.y,
z = this.z,
w = this.w;
if (reprojectAxis) {
var fTx = 2.0 * x;
var fTy = 2.0 * y;
@ -929,9 +973,8 @@ export class Quat {
* @param {Number} [y=0.0] The Y component.
* @param {Number} [z=0.0] The Z component.
* @param {Number} [w=0.0] The W component.
* @returns {og.Quat} -
* @returns {Quat} -
*/
export function quat(x, y, z, w) {
return new Quat(x, y, z, w);
}

View File

@ -2,51 +2,58 @@
* @module og/math/Ray
*/
'use strict';
"use strict";
import * as math from '../math.js';
import { Vec3 } from './Vec3.js';
import * as math from "../math.js";
import { Vec3 } from "./Vec3.js";
/**
* Represents a ray that extends infinitely from the provided origin in the provided direction.
* @class
* @param {og.Vec3} origin - The origin of the ray.
* @param {og.Vec3} direction - The direction of the ray.
* @param {Vec3} origin - The origin of the ray.
* @param {Vec3} direction - The direction of the ray.
*/
export class Ray {
constructor(origin, direction) {
/**
* The origin of the ray.
* @public
* @type {og.Vec3}
* @type {Vec3}
*/
this.origin = origin || new Vec3();
/**
* The direction of the ray.
* @public
* @type {og.Vec3}
* @type {Vec3}
*/
this.direction = direction || new Vec3();
}
/** @const */
static get OUTSIDE() { return 0; }
static get OUTSIDE() {
return 0;
}
/** @const */
static get INSIDE() { return 1; }
static get INSIDE() {
return 1;
}
/** @const */
static get INPLANE() { return 2; }
static get INPLANE() {
return 2;
}
/** @const */
static get AWAY() { return 3; }
static get AWAY() {
return 3;
}
/**
* Sets a ray parameters.
* @public
* @param {og.Vec3} origin - The origin of the ray.
* @param {og.Vec3} direction - The direction of the ray.
* @returns {og.Ray}
* @param {Vec3} origin - The origin of the ray.
* @param {Vec3} direction - The direction of the ray.
* @returns {Ray}
*/
set(origin, direction) {
this.origin = origin;
@ -58,7 +65,7 @@ export class Ray {
* Computes the point along the ray on the distance.
* @public
* @param {number} distance - Point distance.
* @returns {og.Vec3}
* @returns {Vec3}
*/
getPoint(distance) {
return Vec3.add(this.origin, this.direction.scaleTo(distance));
@ -67,10 +74,10 @@ export class Ray {
/**
* Returns ray hit a triange result.
* @public
* @param {og.Vec3} v0 - First triangle corner coordinate.
* @param {og.Vec3} v1 - Second triangle corner coordinate.
* @param {og.Vec3} v2 - Third triangle corner coordinate.
* @param {og.Vec3} res - Hit point object pointer that stores hit result.
* @param {Vec3} v0 - First triangle corner coordinate.
* @param {Vec3} v1 - Second triangle corner coordinate.
* @param {Vec3} v2 - Third triangle corner coordinate.
* @param {Vec3} res - Hit point object pointer that stores hit result.
* @returns {number} - Hit code, could 0 - og.Ray.OUTSIDE, 1 - og.Ray.INSIDE,
* 2 - og.Ray.INPLANE and 3 - og.Ray.AWAY(ray goes away from triangle).
*/
@ -120,7 +127,7 @@ export class Ray {
}
var t = (uv * wu - uu * wv) / D;
if (t < 0.0 || (s + t) > 1.0) {
if (t < 0.0 || s + t > 1.0) {
return Ray.OUTSIDE;
}
@ -130,10 +137,10 @@ export class Ray {
/**
* Gets a ray hit a plane result. If the ray cross the plane returns 1 - og.Ray.INSIDE otherwise returns 0 - og.Ray.OUTSIDE.
* @public
* @param {og.Vec3} v0 - First plane point.
* @param {og.Vec3} v1 - Second plane point.
* @param {og.Vec3} v2 - Third plane point.
* @param {og.Vec3} res - Hit point object pointer that stores hit result.
* @param {Vec3} v0 - First plane point.
* @param {Vec3} v1 - Second plane point.
* @param {Vec3} v2 - Third plane point.
* @param {Vec3} res - Hit point object pointer that stores hit result.
* @returns {number}
*/
hitPlane(v0, v1, v2, res) {
@ -171,8 +178,8 @@ export class Ray {
/**
* Returns a ray hit sphere coordiante. If there isn't hit returns null.
* @public
* @param {og.bv.Sphere} sphere - Sphere object.
* @returns {og.Vec3}
* @param {Sphere} sphere - Sphere object.
* @returns {Vec3}
*/
hitSphere(sphere) {
var r = sphere.radius,
@ -218,17 +225,15 @@ export class Ray {
// TODO
//
}
}
/**
* Ray object creator.
* @function
* @param {og.Vec3} origin - The origin of the ray.
* @param {og.Vec3} direction - The direction of the ray.
* @returns {og.Ray}
* @param {Vec3} origin - The origin of the ray.
* @param {Vec3} direction - The direction of the ray.
* @returns {Ray}
*/
export function ray(origin, direction) {
return new Ray(origin, direction);
}

View File

@ -2,9 +2,9 @@
* @module og/math/Vec2
*/
'use strict';
"use strict";
import { Vec3 } from './Vec3.js';
import { Vec3 } from "./Vec3.js";
/**
* Class represents a 3d vector.
@ -13,9 +13,7 @@ import { Vec3 } from './Vec3.js';
* @param {number} [y] - Second value.
*/
export class Vec2 {
constructor(x, y) {
/**
* @public
* @type {number}
@ -29,22 +27,32 @@ export class Vec2 {
this.y = y || 0.0;
}
/** @const */
static get UP() { return new Vec2(0, 1) }
static get UP() {
return new Vec2(0, 1);
}
/** @const */
static get DOWN() { return new Vec2(0, -1) }
static get DOWN() {
return new Vec2(0, -1);
}
/** @const */
static get RIGHT() { return new Vec2(1, 0) }
static get RIGHT() {
return new Vec2(1, 0);
}
/** @const */
static get LEFT() { return new Vec2(-1, 0) }
static get LEFT() {
return new Vec2(-1, 0);
}
/** @const */
static get ZERO() { return new Vec2() }
static get ZERO() {
return new Vec2();
}
/**
* Returns summary vector.
* @static
* @param {og.math.Vec2} a - First vector.
* @param {og.math.Vec2} b - Second vector.
* @returns {og.math.Vec2} - Summary vector.
* @param {math.Vec2} a - First vector.
* @param {math.Vec2} b - Second vector.
* @returns {math.Vec2} - Summary vector.
*/
static add(a, b) {
var res = new Vec2(a.x, a.y);
@ -55,9 +63,9 @@ export class Vec2 {
/**
* Returns two vectors subtraction.
* @static
* @param {og.math.Vec2} a - First vector.
* @param {og.math.Vec2} b - Second vector.
* @returns {og.math.Vec2} - Vectors subtraction.
* @param {math.Vec2} a - First vector.
* @param {math.Vec2} b - Second vector.
* @returns {math.Vec2} - Vectors subtraction.
*/
static sub(a, b) {
var res = new Vec2(a.x, a.y);
@ -68,9 +76,9 @@ export class Vec2 {
/**
* Returns scaled vector.
* @static
* @param {og.math.Vec2} a - Input vector.
* @param {math.Vec2} a - Input vector.
* @param {number} scale - Scale value.
* @returns {og.math.Vec2}
* @returns {math.Vec2}
*/
static scale(a, scale) {
var res = new Vec2(a.x, a.y);
@ -81,9 +89,9 @@ export class Vec2 {
/**
* Returns two vectors production.
* @static
* @param {og.math.Vec2} a - First vector.
* @param {og.math.Vec2} b - Second vector.
* @returns {og.math.Vec2}
* @param {math.Vec2} a - First vector.
* @param {math.Vec2} b - Second vector.
* @returns {math.Vec2}
*/
static mul(a, b) {
var res = new Vec2(a.x, a.y);
@ -94,9 +102,9 @@ export class Vec2 {
/**
* Returns vector components division product one to another.
* @static
* @param {og.math.Vec2} a - First vector.
* @param {og.math.Vec2} b - Second vector.
* @returns {og.math.Vec2}
* @param {math.Vec2} a - First vector.
* @param {math.Vec2} b - Second vector.
* @returns {math.Vec2}
*/
static div(a, b) {
var res = new Vec2(a.x, a.y);
@ -107,9 +115,9 @@ export class Vec2 {
/**
* Get projection of the first vector to the second.
* @static
* @param {og.math.Vec2} b - First vector.
* @param {og.math.Vec2} a - Second vector.
* @returns {og.math.Vec2}
* @param {math.Vec2} b - First vector.
* @param {math.Vec2} a - Second vector.
* @returns {math.Vec2}
*/
static proj_b_to_a(b, a) {
return a.scaleTo(a.dot(b) / a.dot(a));
@ -118,8 +126,8 @@ export class Vec2 {
/**
* Gets angle between two vectors.
* @static
* @param {og.math.Vec2} a - First vector.
* @param {og.math.Vec2} b - Second vector.
* @param {math.Vec2} a - First vector.
* @param {math.Vec2} b - Second vector.
* @returns {number}
*/
static angle(a, b) {
@ -129,9 +137,9 @@ export class Vec2 {
/**
* Makes vectors normalized and orthogonal to each other.
* @static
* @param {og.math.Vec2} normal - Normal vector.
* @param {og.math.Vec2} tangent - Tangent vector.
* @returns {og.math.Vec2}
* @param {math.Vec2} normal - Normal vector.
* @param {math.Vec2} tangent - Tangent vector.
* @returns {math.Vec2}
*/
static orthoNormalize(normal, tangent) {
normal = normal.norm();
@ -142,7 +150,7 @@ export class Vec2 {
/**
* Converts to 3d vector, third value is 0.0.
* @public
* @returns {og.Vec3}
* @returns {Vec3}
*/
toVector3() {
return new Vec3(this.x, this.y, 0);
@ -151,7 +159,7 @@ export class Vec2 {
/**
* Returns clone vector.
* @public
* @returns {og.math.Vec2}
* @returns {math.Vec2}
*/
clone() {
return new Vec2(this.x, this.y);
@ -160,7 +168,7 @@ export class Vec2 {
/**
* Compares with vector. Returns true if it equals another.
* @public
* @param {og.math.Vec2} p - Vector to compare.
* @param {math.Vec2} p - Vector to compare.
* @returns {boolean}
*/
equal(p) {
@ -169,8 +177,8 @@ export class Vec2 {
/**
* Copy input vector's values.
* @param {og.math.Vec2} point2 - Vector to copy.
* @returns {og.math.Vec2}
* @param {math.Vec2} point2 - Vector to copy.
* @returns {math.Vec2}
*/
copy(point2) {
this.x = point2.x;
@ -199,8 +207,8 @@ export class Vec2 {
/**
* Adds vector to the current.
* @public
* @param {og.math.Vec2}
* @returns {og.math.Vec2}
* @param {math.Vec2}
* @returns {math.Vec2}
*/
addA(v) {
this.x += v.x;
@ -211,8 +219,8 @@ export class Vec2 {
/**
* Summarize two vectors.
* @public
* @param {og.math.Vec2}
* @returns {og.math.Vec2}
* @param {math.Vec2}
* @returns {math.Vec2}
*/
add(v) {
return new Vec2(this.x + v.x, this.y + v.y);
@ -221,8 +229,8 @@ export class Vec2 {
/**
* Subtract vector from the current where results saved on the current instance.
* @public
* @param {og.math.Vec2} v - Subtract vector.
* @returns {og.math.Vec2}
* @param {math.Vec2} v - Subtract vector.
* @returns {math.Vec2}
*/
subA(v) {
this.x -= v.x;
@ -233,8 +241,8 @@ export class Vec2 {
/**
* Subtract vector from the current.
* @public
* @param {og.math.Vec2} v - Subtract vector.
* @returns {og.math.Vec2}
* @param {math.Vec2} v - Subtract vector.
* @returns {math.Vec2}
*/
sub(v) {
return new Vec2(this.x - v.x, this.y - v.y);
@ -244,7 +252,7 @@ export class Vec2 {
* Scale current vector.
* @public
* @param {number} scale - Scale value.
* @returns {og.math.Vec2}
* @returns {math.Vec2}
*/
scale(scale) {
this.x *= scale;
@ -256,7 +264,7 @@ export class Vec2 {
* Scale current vector to another instance.
* @public
* @param {number} scale - Scale value.
* @returns {og.math.Vec2}
* @returns {math.Vec2}
*/
scaleTo(scale) {
return new Vec2(this.x * scale, this.y * scale);
@ -265,8 +273,8 @@ export class Vec2 {
/**
* Multiply current vector object to another and store result in the current instance.
* @public
* @param {og.math.Vec2} vec - Multiply vector.
* @returns {og.math.Vec2}
* @param {math.Vec2} vec - Multiply vector.
* @returns {math.Vec2}
*/
mulA(vec) {
this.x *= vec.x;
@ -277,8 +285,8 @@ export class Vec2 {
/**
* Multiply current vector object to another and returns new vector instance.
* @public
* @param {og.math.Vec2} vec - Multiply vector.
* @returns {og.math.Vec2}
* @param {math.Vec2} vec - Multiply vector.
* @returns {math.Vec2}
*/
mul(vec) {
return new Vec2(this.x * vec.x, this.y * vec.y);
@ -287,8 +295,8 @@ export class Vec2 {
/**
* Divide current vector's components to another. Results stores in the current vector object.
* @public
* @param {og.math.Vec2}
* @returns {og.math.Vec2}
* @param {math.Vec2}
* @returns {math.Vec2}
*/
divA(vec) {
this.x /= vec.x;
@ -299,7 +307,7 @@ export class Vec2 {
/**
* Gets vectors dot production.
* @public
* @param {og.math.Vec2} v - Another vector.
* @param {math.Vec2} v - Another vector.
* @returns {number}
*/
dot(v) {
@ -319,8 +327,8 @@ export class Vec2 {
/**
* Gets vectors cross production.
* @public
* @param {og.math.Vec2} v - Another vector.
* @returns {og.math.Vec2}
* @param {math.Vec2} v - Another vector.
* @returns {math.Vec2}
*/
cross(v) {
return this.x * v.y - this.y * v.x;
@ -329,7 +337,7 @@ export class Vec2 {
/**
* Sets vector to zero.
* @public
* @returns {og.math.Vec2}
* @returns {math.Vec2}
*/
clear() {
this.x = this.y = 0;
@ -339,7 +347,7 @@ export class Vec2 {
/**
* Returns normalized vector.
* @public
* @returns {og.math.Vec2}
* @returns {math.Vec2}
*/
normal() {
var res = new Vec2();
@ -356,7 +364,7 @@ export class Vec2 {
/**
* Normalize current vector.
* @public
* @returns {og.math.Vec2}
* @returns {math.Vec2}
*/
normalize() {
var length = 1.0 / this.length();
@ -379,7 +387,7 @@ export class Vec2 {
/**
* Gets distance to point.
* @public
* @param {og.math.Vec2} p - Distant point.
* @param {math.Vec2} p - Distant point.
* @returns {number}
*/
distance(p) {
@ -392,7 +400,7 @@ export class Vec2 {
* @public
* @param {number} x - Value X.
* @param {number} y - Value Y.
* @returns {og.math.Vec2}
* @returns {math.Vec2}
*/
set(x, y) {
this.x = x;
@ -403,7 +411,7 @@ export class Vec2 {
/**
* Negate current vector.
* @public
* @returns {og.math.Vec2}
* @returns {math.Vec2}
*/
negate() {
this.x = -this.x;
@ -414,7 +422,7 @@ export class Vec2 {
/**
* Negate current vector to another instance.
* @public
* @returns {og.math.Vec2}
* @returns {math.Vec2}
*/
negateTo() {
return new Vec2(-this.x, -this.y);
@ -423,9 +431,9 @@ export class Vec2 {
/**
* Gets projected point coordinates of the current vector on the ray.
* @public
* @param {og.math.Vec2} pos - Ray position.
* @param {og.math.Vec2} direction - Ray direction.
* @returns {og.math.Vec2}
* @param {math.Vec2} pos - Ray position.
* @param {math.Vec2} direction - Ray direction.
* @returns {math.Vec2}
*/
projToRay(pos, direction) {
var v = Vec2.proj_b_to_a(Vec2.sub(this, pos), direction);
@ -436,7 +444,7 @@ export class Vec2 {
/**
* Gets angle between two vectors.
* @public
* @param {og.math.Vec2} a - Another vector.
* @param {math.Vec2} a - Another vector.
* @returns {number}
*/
angle(a) {
@ -446,9 +454,9 @@ export class Vec2 {
/**
* Returns two vectors linear interpolation.
* @public
* @param {og.math.Vec2} v2 - End vector.
* @param {math.Vec2} v2 - End vector.
* @param {number} l - Interpolate value.
* @returns {og.math.Vec2}
* @returns {math.Vec2}
*/
lerp(v1, v2, l) {
var res = Vec2.clone(this);
@ -462,7 +470,9 @@ export class Vec2 {
return res;
}
static get LERP_DELTA() { return 1e-6 }
static get LERP_DELTA() {
return 1e-6;
}
/**
* Spherically interpolates between two vectors.
@ -470,9 +480,9 @@ export class Vec2 {
* the vectors are treated as directions rather than points in space. The direction of the returned vector is interpolated
* by the angle and its magnitude is interpolated between the magnitudes of from and to.
* @public
* @param {og.math.Vec2} v2 -
* @param {math.Vec2} v2 -
* @param {number} t - The parameter t is clamped to the range [0, 1].
* @returns {og.math.Vec2}
* @returns {math.Vec2}
*/
slerp(v2, t) {
var res = new Vec2();
@ -488,7 +498,7 @@ export class Vec2 {
var omega, sinom, scale0, scale1;
var cosom = this.dot(v2);
if ((1.0 - cosom) > Vec2.LERP_DELTA) {
if (1.0 - cosom > Vec2.LERP_DELTA) {
omega = Math.acos(cosom);
sinom = Math.sin(omega);
scale0 = Math.sin((1.0 - t) * omega) / sinom;
@ -507,7 +517,7 @@ export class Vec2 {
* @function
* @param {number} [x] - First cvalue.
* @param {number} [y] - Second value.
* @returns {og.math.Vec2}
* @returns {math.Vec2}
*/
export function vec2(x, y) {
return new Vec2(x, y);

View File

@ -2,10 +2,10 @@
* @module og/math/Vec3
*/
'use strict';
"use strict";
import { Vec4 } from './Vec4.js';
import { Quat } from './Quat.js';
import { Vec4 } from "./Vec4.js";
import { Quat } from "./Quat.js";
/**
* Class represents a 3d vector.
@ -15,9 +15,7 @@ import { Quat } from './Quat.js';
* @param {number} [z] - Third value.
*/
export class Vec3 {
constructor(x, y, z) {
/**
* @public
* @type {number}
@ -38,25 +36,45 @@ export class Vec3 {
}
/** @const */
static get UP() { return new Vec3(0, 1, 0) }
static get UP() {
return new Vec3(0, 1, 0);
}
/** @const */
static get DOWN() { return new Vec3(0, -1, 0) }
static get DOWN() {
return new Vec3(0, -1, 0);
}
/** @const */
static get RIGHT() { return new Vec3(1, 0, 0) }
static get RIGHT() {
return new Vec3(1, 0, 0);
}
/** @const */
static get LEFT() { return new Vec3(-1, 0, 0) }
static get LEFT() {
return new Vec3(-1, 0, 0);
}
/** @const */
static get FORWARD() { return new Vec3(0, 0, -1) }
static get FORWARD() {
return new Vec3(0, 0, -1);
}
/** @const */
static get BACKWARD() { return new Vec3(0, 0, 1) }
static get BACKWARD() {
return new Vec3(0, 0, 1);
}
/** @const */
static get ZERO() { return new Vec3() }
static get ZERO() {
return new Vec3();
}
/** @const */
static get UNIT_X() { return new Vec3(1, 0, 0) }
static get UNIT_X() {
return new Vec3(1, 0, 0);
}
/** @const */
static get UNIT_Y() { return new Vec3(0, 1, 0) }
static get UNIT_Y() {
return new Vec3(0, 1, 0);
}
/** @const */
static get UNIT_Z() { return new Vec3(0, 0, 1) }
static get UNIT_Z() {
return new Vec3(0, 0, 1);
}
/**
* Separate 63 bit Vec3 to two Vec3 32 bit float values.
@ -67,8 +85,9 @@ export class Vec3 {
* @returns {Array.<number>} Encoded array. (exactly 2 entries)
*/
static doubleToTwoFloats(v, high, low) {
let x = v.x, y = v.y, z = v.z;
let x = v.x,
y = v.y,
z = v.z;
if (x >= 0.0) {
let doubleHigh = Math.floor(x / 65536.0) * 65536.0;
@ -110,8 +129,9 @@ export class Vec3 {
* @returns {Array.<number>} Encoded array. (exactly 2 entries)
*/
static doubleToTwoFloat32Array(v, high, low) {
let x = v.x, y = v.y, z = v.z;
let x = v.x,
y = v.y,
z = v.z;
if (x >= 0.0) {
let doubleHigh = Math.floor(x / 65536.0) * 65536.0;
@ -148,7 +168,7 @@ export class Vec3 {
* Creates 3d vector from array.
* @function
* @param {Array.<number>} arr - Input array (exactly 3 entries)
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
static fromVec(arr) {
return new Vec3(arr[0], arr[1], arr[2]);
@ -157,8 +177,8 @@ export class Vec3 {
/**
* Gets angle between two vectors.
* @static
* @param {og.Vec3} a - First vector.
* @param {og.Vec3} b - Second vector.
* @param {Vec3} a - First vector.
* @param {Vec3} b - Second vector.
* @returns {number} -
*/
static angle(a, b) {
@ -168,10 +188,10 @@ export class Vec3 {
/**
* Returns two vectors linear interpolation.
* @static
* @param {og.Vec3} v1 - Start vector.
* @param {og.Vec3} v2 - End vector.
* @param {Vec3} v1 - Start vector.
* @param {Vec3} v2 - End vector.
* @param {number} l - Interpolate value.
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
static lerp(v1, v2, l) {
return Vec3(v1.x + (v2.x - v1.x) * l, v1.y + (v2.y - v1.y) * l, v1.z + (v2.z - v1.z) * l);
@ -180,9 +200,9 @@ export class Vec3 {
/**
* Returns summary vector.
* @static
* @param {og.Vec3} a - First vector.
* @param {og.Vec3} b - Second vector.
* @returns {og.Vec3} - Summary vector.
* @param {Vec3} a - First vector.
* @param {Vec3} b - Second vector.
* @returns {Vec3} - Summary vector.
*/
static add(a, b) {
var res = new Vec3(a.x, a.y, a.z);
@ -193,9 +213,9 @@ export class Vec3 {
/**
* Returns two vectors subtraction.
* @static
* @param {og.Vec3} a - First vector.
* @param {og.Vec3} b - Second vector.
* @returns {og.Vec3} - Vectors subtraction.
* @param {Vec3} a - First vector.
* @param {Vec3} b - Second vector.
* @returns {Vec3} - Vectors subtraction.
*/
static sub(a, b) {
var res = new Vec3(a.x, a.y, a.z);
@ -206,9 +226,9 @@ export class Vec3 {
/**
* Returns scaled vector.
* @static
* @param {og.Vec3} a - Input vector.
* @param {Vec3} a - Input vector.
* @param {number} scale - Scale value.
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
static scale(a, scale) {
var res = new Vec3(a.x, a.y, a.z);
@ -219,9 +239,9 @@ export class Vec3 {
/**
* Returns two vectors production.
* @static
* @param {og.Vec3} a - First vector.
* @param {og.Vec3} b - Second vector.
* @returns {og.Vec3} -
* @param {Vec3} a - First vector.
* @param {Vec3} b - Second vector.
* @returns {Vec3} -
*/
static mul(a, b) {
var res = new Vec3(a.x, a.y, a.z);
@ -232,9 +252,9 @@ export class Vec3 {
/**
* Returns true if two vectors are non collinear.
* @public
* @param {og.Vec3} a - First vector.
* @param {og.Vec3} b - Second vector.
* @returns {og.Vec3} -
* @param {Vec3} a - First vector.
* @param {Vec3} b - Second vector.
* @returns {Vec3} -
*/
static noncollinear(a, b) {
return a.y * b.z - a.z * b.y || a.z * b.x - a.x * b.z || a.x * b.y - a.y * b.z;
@ -243,10 +263,10 @@ export class Vec3 {
/**
* Get projection of the vector to plane where n - normal to the plane.
* @static
* @param {og.Vec3} b - Vector to project.
* @param {og.Vec3} n - Plane normal.
* @param {og.Vec3} [def] - Default value for non existed result.
* @returns {og.Vec3} -
* @param {Vec3} b - Vector to project.
* @param {Vec3} n - Plane normal.
* @param {Vec3} [def] - Default value for non existed result.
* @returns {Vec3} -
*/
static proj_b_to_plane(b, n, def) {
var res = b.sub(n.scaleTo(n.dot(b) / n.dot(n)));
@ -259,9 +279,9 @@ export class Vec3 {
/**
* Get projection of the first vector to the second.
* @static
* @param {og.Vec3} b - First vector.
* @param {og.Vec3} a - Second vector.
* @returns {og.Vec3} -
* @param {Vec3} b - First vector.
* @param {Vec3} a - Second vector.
* @returns {Vec3} -
*/
static proj_b_to_a(b, a) {
return a.scaleTo(a.dot(b) / a.dot(a));
@ -271,9 +291,9 @@ export class Vec3 {
* Makes vectors normalized and orthogonal to each other.
* Normalizes normal. Normalizes tangent and makes sure it is orthogonal to normal (that is, angle between them is 90 degrees).
* @static
* @param {og.Vec3} normal - Normal vector.
* @param {og.Vec3} tangent - Tangent vector.
* @returns {og.Vec3} -
* @param {Vec3} normal - Normal vector.
* @param {Vec3} tangent - Tangent vector.
* @returns {Vec3} -
*/
static orthoNormalize(normal, tangent) {
normal = normal.normal();
@ -284,9 +304,9 @@ export class Vec3 {
/**
* Returns vector components division product one to another.
* @static
* @param {og.Vec3} a - First vector.
* @param {og.Vec3} b - Second vector.
* @returns {og.Vec3} -
* @param {Vec3} a - First vector.
* @param {Vec3} b - Second vector.
* @returns {Vec3} -
*/
static div(a, b) {
var res = new Vec3(a.x, a.y, a.z);
@ -297,7 +317,7 @@ export class Vec3 {
/**
* Converts to 4d vector, Fourth value is 1.0.
* @public
* @returns {og.Vec4} -
* @returns {Vec4} -
*/
toVec4() {
return new Vec4(this.x, this.y, this.z, 1.0);
@ -306,7 +326,7 @@ export class Vec3 {
/**
* Returns clone vector.
* @public
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
clone() {
return new Vec3(this.x, this.y, this.z);
@ -333,8 +353,8 @@ export class Vec3 {
/**
* Get projection of the first vector to the second.
* @static
* @param {og.Vec3} a - Project vector.
* @returns {og.Vec3} -
* @param {Vec3} a - Project vector.
* @returns {Vec3} -
*/
projToVec(a) {
return a.scaleTo(a.dot(this) / a.dot(a));
@ -343,7 +363,7 @@ export class Vec3 {
/**
* Compares with vector. Returns true if it equals another.
* @public
* @param {og.Vec3} p - Vector to compare.
* @param {Vec3} p - Vector to compare.
* @returns {boolean} -
*/
equal(p) {
@ -352,8 +372,8 @@ export class Vec3 {
/**
* Copy input vector's values.
* @param {og.Vec3} point3 - Vector to copy.
* @returns {og.Vec3} -
* @param {Vec3} point3 - Vector to copy.
* @returns {Vec3} -
*/
copy(point3) {
this.x = point3.x;
@ -383,7 +403,7 @@ export class Vec3 {
/**
* Converts vector's values to a quaternion object.
* @public
* @returns {og.Quat} -
* @returns {Quat} -
*/
getQuat() {
return new Quat(this.x, this.y, this.z);
@ -392,8 +412,8 @@ export class Vec3 {
/**
* Adds vector to the current.
* @public
* @param {og.Vec3} point3 - Point to add.
* @returns {og.Vec3} -
* @param {Vec3} point3 - Point to add.
* @returns {Vec3} -
*/
addA(point3) {
this.x += point3.x;
@ -405,8 +425,8 @@ export class Vec3 {
/**
* Gets two vectors summarization.
* @public
* @param {og.Vec3} point3 - Vector to add.
* @returns {og.Vec3} Returns a sum vector.
* @param {Vec3} point3 - Vector to add.
* @returns {Vec3} Returns a sum vector.
*/
add(point3) {
return new Vec3(this.x + point3.x, this.y + point3.y, this.z + point3.z);
@ -415,8 +435,8 @@ export class Vec3 {
/**
* Subtract vector from the current.
* @public
* @param {og.Vec3} point3 - Subtract vector.
* @returns {og.Vec3} -
* @param {Vec3} point3 - Subtract vector.
* @returns {Vec3} -
*/
subA(point3) {
this.x -= point3.x;
@ -428,8 +448,8 @@ export class Vec3 {
/**
* Gets vector subtraction.
* @public
* @param {og.Vec3} point3 - Subtract vector.
* @return {og.Vec3} Returns new instance of a subtraction
* @param {Vec3} point3 - Subtract vector.
* @return {Vec3} Returns new instance of a subtraction
*/
sub(point3) {
return new Vec3(this.x - point3.x, this.y - point3.y, this.z - point3.z);
@ -439,7 +459,7 @@ export class Vec3 {
* Scale current vector.
* @public
* @param {number} scale - Scale value.
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
scale(scale) {
this.x *= scale;
@ -452,7 +472,7 @@ export class Vec3 {
* Scale current vector to another instance.
* @public
* @param {number} scale - Scale value.
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
scaleTo(scale) {
return new Vec3(this.x * scale, this.y * scale, this.z * scale);
@ -461,8 +481,8 @@ export class Vec3 {
/**
* Multiply current vector object to another and store result in the current instance.
* @public
* @param {og.Vec3} vec - Multiply vector.
* @returns {og.Vec3} -
* @param {Vec3} vec - Multiply vector.
* @returns {Vec3} -
*/
mulA(vec) {
this.x *= vec.x;
@ -474,8 +494,8 @@ export class Vec3 {
/**
* Multiply current vector object to another and returns new vector instance.
* @public
* @param {og.Vec3} vec - Multiply vector.
* @returns {og.Vec3} -
* @param {Vec3} vec - Multiply vector.
* @returns {Vec3} -
*/
mul(vec) {
return new Vec3(this.x * vec.x, this.y * vec.y, this.z * vec.z);
@ -484,8 +504,8 @@ export class Vec3 {
/**
* Divide current vector's components to another. Results stores in the current vector object.
* @public
* @param {og.Vec3} vec - Div vector.
* @returns {og.Vec3} -
* @param {Vec3} vec - Div vector.
* @returns {Vec3} -
*/
divA(vec) {
this.x /= vec.x;
@ -497,8 +517,8 @@ export class Vec3 {
/**
* Divide current vector's components to another and returns new vector instance.
* @public
* @param {og.Vec3} vec - Div vector.
* @returns {og.Vec3} -
* @param {Vec3} vec - Div vector.
* @returns {Vec3} -
*/
div(vec) {
return new Vec3(this.x / vec.x, this.y / vec.y, this.z / vec.z);
@ -507,7 +527,7 @@ export class Vec3 {
/**
* Gets vectors dot production.
* @public
* @param {og.Vec3} point3 - Another vector.
* @param {Vec3} point3 - Another vector.
* @returns {number} -
*/
dot(point3) {
@ -527,8 +547,8 @@ export class Vec3 {
/**
* Gets vectors cross production.
* @public
* @param {og.Vec3} point3 - Another vector.
* @returns {og.Vec3} -
* @param {Vec3} point3 - Another vector.
* @returns {Vec3} -
*/
cross(point3) {
return new Vec3(
@ -541,7 +561,7 @@ export class Vec3 {
/**
* Sets vector to zero.
* @public
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
clear() {
this.x = this.y = this.z = 0;
@ -551,7 +571,7 @@ export class Vec3 {
/**
* Returns normalized vector.
* @public
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
getNormal() {
var res = new Vec3();
@ -570,7 +590,7 @@ export class Vec3 {
* Returns normalized vector.
* @deprecated
* @public
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
normal() {
var res = new Vec3();
@ -588,7 +608,7 @@ export class Vec3 {
/**
* Returns normalized negate vector.
* @public
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
normalNegate() {
var res = new Vec3();
@ -606,7 +626,7 @@ export class Vec3 {
/**
* Returns normalized negate scale vector.
* @public
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
normalNegateScale(scale) {
var res = new Vec3();
@ -624,7 +644,7 @@ export class Vec3 {
/**
* Returns normalized scale vector.
* @public
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
normalScale(scale) {
var res = new Vec3();
@ -642,7 +662,7 @@ export class Vec3 {
/**
* Normalize current vector.
* @public
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
normalize() {
var length = 1.0 / this.length();
@ -676,7 +696,7 @@ export class Vec3 {
/**
* Gets distance to point.
* @public
* @param {og.Vec3} point3 - Distant point.
* @param {Vec3} point3 - Distant point.
* @returns {number} -
*/
distance(point3) {
@ -689,7 +709,7 @@ export class Vec3 {
* @param {number} x - Value X.
* @param {number} y - Value Y.
* @param {number} z - Value Z.
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
set(x, y, z) {
this.x = x;
@ -701,7 +721,7 @@ export class Vec3 {
/**
* Negate current vector.
* @public
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
negate() {
this.x = -this.x;
@ -713,7 +733,7 @@ export class Vec3 {
/**
* Negate current vector to another instance.
* @public
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
negateTo() {
return new Vec3(-this.x, -this.y, -this.z);
@ -722,9 +742,9 @@ export class Vec3 {
/**
* Gets projected point coordinates of the current vector on the ray.
* @public
* @param {og.Vec3} pos - Ray position.
* @param {og.Vec3} direction - Ray direction.
* @returns {og.Vec3} -
* @param {Vec3} pos - Ray position.
* @param {Vec3} direction - Ray direction.
* @returns {Vec3} -
*/
projToRay(pos, direction) {
var v = Vec3.proj_b_to_a(Vec3.sub(this, pos), direction);
@ -735,7 +755,7 @@ export class Vec3 {
/**
* Gets angle between two vectors.
* @public
* @param {og.Vec3} a - Another vector.
* @param {Vec3} a - Another vector.
* @returns {number} -
*/
angle(a) {
@ -745,27 +765,37 @@ export class Vec3 {
/**
* Returns two vectors linear interpolation.
* @public
* @param {og.Vec3} v2 - End vector.
* @param {Vec3} v2 - End vector.
* @param {number} l - Interpolate value.
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
lerp(v2, l) {
return new Vec3(this.x + (v2.x - this.x) * l, this.y + (v2.y - this.y) * l, this.z + (v2.z - this.z) * l);
return new Vec3(
this.x + (v2.x - this.x) * l,
this.y + (v2.y - this.y) * l,
this.z + (v2.z - this.z) * l
);
}
/**
* Returns vector interpolation by v(t) = v1 * t + v2 * (1 - t)
* @public
* @param {og.Vec3} v2 - End vector.
* @param {Vec3} v2 - End vector.
* @param {number} t - Interpolate value.
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
smerp(v2, t) {
var one_d = 1 - t;
return new Vec3(this.x * t + v2.x * one_d, this.y * t + v2.y * one_d, this.z * t + v2.z * one_d);
return new Vec3(
this.x * t + v2.x * one_d,
this.y * t + v2.y * one_d,
this.z * t + v2.z * one_d
);
}
static get LERP_DELTA() { return 1e-6 }
static get LERP_DELTA() {
return 1e-6;
}
/**
* Spherically interpolates between two vectors.
@ -773,9 +803,9 @@ export class Vec3 {
* the vectors are treated as directions rather than points in space. The direction of the returned vector is interpolated
* by the angle and its magnitude is interpolated between the magnitudes of from and to.
* @public
* @param {og.Vec3} v2 -
* @param {Vec3} v2 -
* @param {number} t - The parameter t is clamped to the range [0, 1].
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
slerp(v2, t) {
var res = new Vec3();
@ -791,7 +821,7 @@ export class Vec3 {
var omega, sinom, scale0, scale1;
var cosom = this.dot(v2);
if ((1.0 - cosom) > Vec3.LERP_DELTA) {
if (1.0 - cosom > Vec3.LERP_DELTA) {
omega = Math.acos(cosom);
sinom = Math.sin(omega);
scale0 = Math.sin((1.0 - t) * omega) / sinom;
@ -825,14 +855,15 @@ export class Vec3 {
return Quat.IDENTITY.clone();
}
if (d < (1e-6 - 1.0)) {
if (d < 1e-6 - 1.0) {
if (!fallbackAxis.isEqual(Vec3.ZERO)) {
// rotate 180 degrees about the fallback axis
return Quat.axisAngleToQuat(Math.PI, fallbackAxis);
} else {
// Generate an axis
let axis = Vec3.UNIT_X.cross(v0);
if (axis.isZero()) { // pick another if colinear
if (axis.isZero()) {
// pick another if colinear
axis = Vec3.UNIT_Y.cross(v0);
}
axis.normalize();
@ -857,9 +888,8 @@ export class Vec3 {
* @param {number} [x] - First cvalue.
* @param {number} [y] - Second value.
* @param {number} [z] - Third value.
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
export function vec3(x, y, z) {
return new Vec3(x, y, z);
}

View File

@ -2,9 +2,10 @@
* @module og/math/Vec4
*/
'use strict';
"use strict";
import { Vec3 } from './Vec3.js';
import { Vec3 } from "./Vec3.js";
import { frac } from "../math.js";
/**
* Class represents a 4d vector.
@ -15,9 +16,7 @@ import { Vec3 } from './Vec3.js';
* @param {number} [w] - Fourth value.
*/
export class Vec4 {
constructor(x, y, z, w) {
/**
* @public
* @type {number}
@ -46,15 +45,17 @@ export class Vec4 {
/**
* Identity vector [0,0,0,1].
* @const
* @type {og.math.Vec4}
* @type {Vec4}
*/
static get identity() { return new Vec4(0, 0, 0, 1) }
static get identity() {
return new Vec4(0, 0, 0, 1);
}
/**
* Creates 4d vector from array.
* @function
* @param {Array.<number>} - (exactly 4 entries)
* @returns {og.math.Vec4}
* @returns {Vec4}
*/
static fromVec(arr) {
return new Vec4(arr[0], arr[1], arr[2], arr[3]);
@ -63,7 +64,7 @@ export class Vec4 {
/**
* Converts to 3d vector, without fourth value.
* @public
* @returns {og.Vec3}
* @returns {Vec3}
*/
toVec3() {
return new Vec3(this.x, this.y, this.z);
@ -72,7 +73,7 @@ export class Vec4 {
/**
* Returns clone vector.
* @public
* @returns {og.math.Vec4}
* @returns {Vec4}
*/
clone(v) {
return new Vec4(this.x, this.y, this.z, this.w);
@ -81,7 +82,7 @@ export class Vec4 {
/**
* Compares with vector. Returns true if it equals another.
* @public
* @param {og.math.Vec4} p - Vector to compare.
* @param {Vec4} p - Vector to compare.
* @returns {boolean}
*/
equal(v) {
@ -90,8 +91,8 @@ export class Vec4 {
/**
* Copy input vector's values.
* @param {og.math.Vec4} v - Vector to copy.
* @returns {og.math.Vec4}
* @param {Vec4} v - Vector to copy.
* @returns {Vec4}
*/
copy(v) {
this.x = v.x;
@ -127,7 +128,7 @@ export class Vec4 {
* @param {number} y - Value Y.
* @param {number} z - Value Z.
* @param {number} w - Value W.
* @returns {og.math.Vec4}
* @returns {Vec4}
*/
set(x, y, z, w) {
this.x = x;
@ -140,8 +141,8 @@ export class Vec4 {
/**
* Adds vector to the current.
* @public
* @param {og.math.Vec4}
* @returns {og.math.Vec4}
* @param {Vec4}
* @returns {Vec4}
*/
addA(v) {
this.x += v.x;
@ -154,8 +155,8 @@ export class Vec4 {
/**
* Subtract vector from the current.
* @public
* @param {og.math.Vec4} v - Subtract vector.
* @returns {og.math.Vec4}
* @param {Vec4} v - Subtract vector.
* @returns {Vec4}
*/
subA(v) {
this.x -= v.x;
@ -169,7 +170,7 @@ export class Vec4 {
* Scale current vector.
* @public
* @param {number} scale - Scale value.
* @returns {og.math.Vec4}
* @returns {Vec4}
*/
scale(scale) {
this.x *= scale;
@ -182,7 +183,7 @@ export class Vec4 {
/**
* Makes vector affinity. Thereby fourh component becomes to 1.0.
* @public
* @returns {og.math.Vec4}
* @returns {Vec4}
*/
affinity() {
var iw = 1 / this.w;
@ -197,7 +198,7 @@ export class Vec4 {
* Scale current vector to another instance.
* @public
* @param {number} scale - Scale value.
* @returns {og.Vec3}
* @returns {Vec3}
*/
scaleTo(scale) {
return new Vec4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
@ -206,7 +207,7 @@ export class Vec4 {
/**
* Vector's edge function that returns vector where each component is 0.0 if it's smaller then edge and otherwise 1.0.
* @public
* @returns {og.math.Vec4}
* @returns {Vec4}
*/
getStep(edge) {
return new Vec4(
@ -220,21 +221,16 @@ export class Vec4 {
/**
* The vector fract function returns the vector of fractional parts of each value, i.e. x minus floor(x).
* @public
* @returns {og.math.Vec4}
* @returns {Vec4}
*/
getFrac(v) {
return new Vec4(
og.math.frac(v.x),
og.math.frac(v.y),
og.math.frac(v.z),
og.math.frac(v.w)
);
return new Vec4(frac(v.x), frac(v.y), frac(v.z), frac(v.w));
}
/**
* Gets vectors dot production.
* @public
* @param {og.math.Vec4} v - Another vector.
* @param {math.Vec4} v - Another vector.
* @returns {number} - Dot product.
*/
dot(v) {
@ -258,8 +254,8 @@ export class Vec4 {
* @param {number} [y] - Second value.
* @param {number} [z] - Third value.
* @param {number} [w] - Fourth value.
* @returns {og.math.Vec4}
* @returns {Vec4}
*/
export function vec4(x, y, z, w) {
return new og.math.Vec4(x, y, z, w);
return new Vec4(x, y, z, w);
}

View File

@ -2,19 +2,19 @@
* @module og/math/coder
*/
'use strict';
"use strict";
import * as math from '../math.js';
import { Vec4 } from './Vec4.js';
import * as math from "../math.js";
import { Vec4 } from "./Vec4.js";
/**
* Encode 32 bit float value to the RGBA vector.
* @function
* @param {number} v - 32 bit float value.
* @returns {og.math.Vec4} - RGBA vector value.
* @returns {math.Vec4} - RGBA vector value.
*/
export function encodeFloatToRGBA(v) {
var enc = new Vec4(1.0 * v % 1, 255.0 * v % 1, 65025.0 * v % 1, 160581375.0 * v % 1);
var enc = new Vec4((1.0 * v) % 1, (255.0 * v) % 1, (65025.0 * v) % 1, (160581375.0 * v) % 1);
var yzww = new Vec4(enc.y / 255, enc.z / 255, enc.w / 255, 0);
return enc.subA(yzww);
}
@ -22,26 +22,26 @@ export function encodeFloatToRGBA(v) {
/**
* Decode RGBA vector to 32 bit float value.
* @function
* @param {og.Vec4} rgba - RGBA encoded 32 bit float value.
* @param {Vec4} rgba - RGBA encoded 32 bit float value.
* @returns {number} - Float value.
*/
export function decodeFloatFromRGBA(rgba) {
var s = 1.0 - math.step(128.0, rgba.x) * 2.0;
var e = 2.0 * math.mod(rgba.x, 128.0) + math.step(128.0, rgba.y) - 127.0;
var m = math.mod(rgba.y, 128.0) * 65536.0 + rgba.z * 256.0 + rgba.w + 8388608.00;
var m = math.mod(rgba.y, 128.0) * 65536.0 + rgba.z * 256.0 + rgba.w + 8388608.0;
return s * math.exp2(e) * (m * 1.1920928955078125e-7);
}
/**
* Decode RGBA vector to 32 bit float value.
* @function
* @param {og.Vec4} rgba - RGBA encoded 32 bit float value.
* @param {Vec4} rgba - RGBA encoded 32 bit float value.
* @returns {number} - Float value.
*/
export function decodeFloatFromRGBAArr(arr, use32) {
var s = 1.0 - math.step(128.0, arr[0]) * 2.0;
var e = 2.0 * math.mod(arr[0], 128.0) + math.step(128.0, arr[1]) - 127.0;
var m = math.mod(arr[1], 128.0) * 65536.0 + arr[2] * 256.0 + (use32 ? arr[3] : 0.0) + 8388608.00;
var m = math.mod(arr[1], 128.0) * 65536.0 + arr[2] * 256.0 + (use32 ? arr[3] : 0.0) + 8388608.0;
return s * math.exp2(e) * (m * 1.1920928955078125e-7);
}

View File

@ -2,12 +2,12 @@
* @module og/proj/EPSG3857
*/
'use strict';
"use strict";
import { Units, Proj } from './Proj.js';
import { Units, Proj } from "./Proj.js";
/**
* EPSG:3857 projection object.
* @type {og.Proj}
* @type {Proj}
*/
export const EPSG3857 = new Proj({ code: "epsg:3857", units: Units.METERS });

View File

@ -2,12 +2,12 @@
* @module og/proj/EPSG4326
*/
'use strict';
"use strict";
import { Units, Proj } from './Proj.js';
import { Units, Proj } from "./Proj.js";
/**
* EPSG:4326 projection object.
* @type {og.Proj}
* @type {Proj}
*/
export const EPSG4326 = new Proj({ code: "epsg:4326", units: Units.DEGREES });

View File

@ -2,7 +2,7 @@
* @module og/proj/Proj
*/
'use strict';
"use strict";
/**
* Projection units: 'degrees', 'ft', 'm' or 'km'.
@ -28,9 +28,7 @@ METERS_PER_UNIT[Units.KILOMETERS] = 1000;
let _counter = 0;
class Proj {
constructor(options) {
/**
* @public
* @type {string}
@ -39,7 +37,7 @@ class Proj {
/**
* @public
* @type {og.proj.Units}
* @type {proj.Units}
*/
this.units = /** @type {Units} */ (options.units);
@ -54,7 +52,7 @@ class Proj {
/**
* Compare projections.
* @public
* @param {og.Proj} proj - Projetion object.
* @param {Proj} proj - Projetion object.
* @returns {boolean}
*/
equal(proj) {

View File

@ -55,16 +55,15 @@ let BOUNDS = {
/**
* Quad tree planet segment node.
* @constructor
* @param {og.planetSegment.Segment|og.planetSegment.SegmentLonLat} segmentPrototype - Planet segment node constructor.
* @param {og.scene.RenderNode} planet - Planet render node.
* @param {Segment|og.planetSegment.SegmentLonLat} segmentPrototype - Planet segment node constructor.
* @param {RenderNode} planet - Planet render node.
* @param {number} partId - NorthEast, SouthWest etc.
* @param {og.quadTree.Node} parent - Parent of this node.
* @param {quadTree.Node} parent - Parent of this node.
* @param {number} id - Tree node identifier (id * 4 + 1);
* @param {number} tileZoom - Deep index of the quad tree.
* @param {og.Extent} extent - Planet segment extent.
* @param {Extent} extent - Planet segment extent.
*/
class Node {
constructor(SegmentPrototype, planet, partId, parent, id, tileZoom, extent) {
this.SegmentPrototype = SegmentPrototype;
this.planet = planet;
@ -173,7 +172,7 @@ class Node {
* Returns the same deep existent neighbour node.
* @public
* @param {Number} side - Neighbour side index e.g. og.quadTree.N, og.quadTree.W etc.
* @returns {og.quadTree.Node} -
* @returns {quadTree.Node} -
*/
getEqualNeighbor(side) {
var pn = this;
@ -295,14 +294,26 @@ class Node {
if (seg.tileZoom < 2 && seg.normalMapReady) {
this.traverseNodes(cam, maxZoom, terrainReadySegment, stopLoading);
} else if ((!maxZoom && seg.acceptForRendering(cam)) || seg.tileZoom === maxZoom) {
this.prepareForRendering(cam, altVis, this.inFrustum, terrainReadySegment, stopLoading);
this.prepareForRendering(
cam,
altVis,
this.inFrustum,
terrainReadySegment,
stopLoading
);
} else if (seg.tileZoom < planet.terrain._maxNodeZoom && seg.terrainReady) {
// Deleting terrainReady here, you have to remove
// this.appliedTerrainNodeId !== pn.nodeId in whileTerrainLoading,
// also have to fix createBoundsByParent(*)
this.traverseNodes(cam, maxZoom, seg, stopLoading);
} else {
this.prepareForRendering(cam, altVis, this.inFrustum, terrainReadySegment, stopLoading);
this.prepareForRendering(
cam,
altVis,
this.inFrustum,
terrainReadySegment,
stopLoading
);
}
} else {
this.state = NOTRENDERING;
@ -322,13 +333,7 @@ class Node {
n[3].renderTree(cam, maxZoom, terrainReadySegment, stopLoading);
}
prepareForRendering(
cam,
altVis,
inFrustum,
terrainReadySegment,
stopLoading
) {
prepareForRendering(cam, altVis, inFrustum, terrainReadySegment, stopLoading) {
let seg = this.segment;
if (cam._lonLat.height < VISIBLE_HEIGHT) {
@ -769,8 +774,16 @@ class Node {
let v_lt = new Vec3(bigOne[0], bigOne[1], bigOne[2]),
v_rb = new Vec3(bigOne[9], bigOne[10], bigOne[11]);
let vn = new Vec3(bigOne[3] - bigOne[0], bigOne[4] - bigOne[1], bigOne[5] - bigOne[2]),
vw = new Vec3(bigOne[6] - bigOne[0], bigOne[7] - bigOne[1], bigOne[8] - bigOne[2]),
let vn = new Vec3(
bigOne[3] - bigOne[0],
bigOne[4] - bigOne[1],
bigOne[5] - bigOne[2]
),
vw = new Vec3(
bigOne[6] - bigOne[0],
bigOne[7] - bigOne[1],
bigOne[8] - bigOne[2]
),
ve = new Vec3(
bigOne[3] - bigOne[9],
bigOne[4] - bigOne[10],
@ -983,7 +996,8 @@ class Node {
offset = 0;
while (pNode.segment.tileZoom > neighbourZoom) {
offset += PARTOFFSET[pNode.partId][side] / (1 << (pNode.segment.tileZoom - neighbourZoom));
offset +=
PARTOFFSET[pNode.partId][side] / (1 << (pNode.segment.tileZoom - neighbourZoom));
pNode = pNode.parentNode;
}

View File

@ -24,7 +24,7 @@ let __depthCallbackCounter__ = 0;
/**
* Represents high level WebGL context interface that starts WebGL handler working in real time.
* @class
* @param {og.webgl.Handler} handler - WebGL handler context.
* @param {Handler} handler - WebGL handler context.
* @param {Object} [params] - Renderer parameters:
* @fires og.RendererEvents#draw
* @fires og.RendererEvents#resize
@ -55,7 +55,6 @@ let __depthCallbackCounter__ = 0;
* @fires og.RendererEvents#touchenter
*/
class Renderer {
constructor(handler, params) {
params = params || {};
@ -69,7 +68,7 @@ class Renderer {
/**
* WebGL handler context.
* @public
* @type {og.webgl.Handler}
* @type {Handler}
*/
this.handler = handler;
@ -86,7 +85,7 @@ class Renderer {
/**
* Render nodes drawing queue.
* @private
* @type {Array.<og.scene.RenderNode>}
* @type {Array.<scene.RenderNode>}
*/
this._renderNodesArr = [];
@ -100,14 +99,14 @@ class Renderer {
/**
* Current active camera.
* @public
* @type {og.Camera}
* @type {Camera}
*/
this.activeCamera = null;
/**
* Renderer events. Represents interface for setting events like mousemove, draw, keypress etc.
* @public
* @type {og.RendererEvents}
* @type {RendererEvents}
*/
this.events = new RendererEvents(this);
@ -140,20 +139,20 @@ class Renderer {
/**
* Color picking objects rendering queue.
* @type {Array.<og.Renderer~pickingCallback>}
* @type {Array.<Renderer~pickingCallback>}
*/
this._pickingCallbacks = [];
/**
* Picking objects(labels and billboards) framebuffer.
* @public
* @type {og.webgl.Framebuffer}
* @type {Framebuffer}
*/
this.pickingFramebuffer = null;
/**
* Depth objects rendering queue.
* @type {Array.<og.Renderer~depthCallback>}
* @type {Array.<Renderer~depthCallback>}
*/
this._depthCallbacks = [];
@ -193,14 +192,14 @@ class Renderer {
/**
* Texture atlas for the billboards images. One atlas per node.
* @protected
* @type {og.utils.TextureAtlas}
* @type {utils.TextureAtlas}
*/
this.billboardsTextureAtlas = new TextureAtlas();
/**
* Texture font atlas for the font families and styles. One atlas per node.
* @public
* @type {og.utils.FontAtlas}
* @type {utils.FontAtlas}
*/
this.fontAtlas = new FontAtlas();
@ -249,7 +248,7 @@ class Renderer {
/**
* Adds picking rendering callback function.
* @param {object} sender - Callback context.
* @param {og.Renderer~pickingCallback} callback - Rendering callback.
* @param {Renderer~pickingCallback} callback - Rendering callback.
* @returns {Number} Handler id
*/
addPickingCallback(sender, callback) {
@ -346,7 +345,7 @@ class Renderer {
/**
* Get center of the screen
* @public
* @returns {og.math.Vec2} -
* @returns {math.Vec2} -
*/
getCenter() {
var cnv = this.handler.canvas;
@ -355,7 +354,7 @@ class Renderer {
/**
* Add the given control to the renderer.
* @param {og.control.Control} control - Control.
* @param {control.Control} control - Control.
*/
addControl(control) {
control.addTo(this);
@ -363,7 +362,7 @@ class Renderer {
/**
* Add the given controls array to the planet node.
* @param {Array.<og.control.Control>} cArr - Control array.
* @param {Array.<control.Control>} cArr - Control array.
*/
addControls(cArr) {
for (var i = 0; i < cArr.length; i++) {
@ -373,7 +372,7 @@ class Renderer {
/**
* Remove control from the renderer.
* @param {og.control.Control} control - Control.
* @param {control.Control} control - Control.
*/
removeControl(control) {
control.remove();
@ -441,7 +440,7 @@ class Renderer {
useDepth: false
}).init();
this.readPixels = () => { };
this.readPixels = () => {};
if (this.handler.gl.type === "webgl") {
this.sceneFramebuffer = new Framebuffer(this.handler);
@ -538,7 +537,8 @@ class Renderer {
);
this.toneMappingFramebuffer &&
this.toneMappingFramebuffer.setSize(obj.clientWidth, obj.clientHeight, true);
this.depthFramebuffer && this.depthFramebuffer.setSize(obj.clientWidth, obj.clientHeight, true);
this.depthFramebuffer &&
this.depthFramebuffer.setSize(obj.clientWidth, obj.clientHeight, true);
this.screenDepthFramebuffer &&
this.screenDepthFramebuffer.setSize(obj.clientWidth, obj.clientHeight, true);
@ -564,7 +564,7 @@ class Renderer {
/**
* Adds render node to the renderer.
* @public
* @param {og.scene.RenderNode} renderNode - Render node.
* @param {RenderNode} renderNode - Render node.
*/
addNode(renderNode) {
if (!this.renderNodes[renderNode.name]) {
@ -579,7 +579,7 @@ class Renderer {
/**
* Adds render node to the renderer before specific node.
* @public
* @param {og.scene.RenderNode} renderNode - Render node.
* @param {RenderNode} renderNode - Render node.
*/
addNodeBefore(renderNode, renderNodeBefore) {
if (!this.renderNodes[renderNode.name]) {
@ -600,7 +600,7 @@ class Renderer {
/**
* Adds render nodes array to the renderer.
* @public
* @param {Array.<og.scene.RenderNode>} nodesArr - Render nodes array.
* @param {Array.<scene.RenderNode>} nodesArr - Render nodes array.
*/
addNodes(nodesArr) {
for (var i = 0; i < nodesArr.length; i++) {
@ -610,7 +610,11 @@ class Renderer {
getMaxMSAA(internalFormat) {
var gl = this.handler.gl;
let samples = gl.getInternalformatParameter(gl.RENDERBUFFER, gl[internalFormat], gl.SAMPLES);
let samples = gl.getInternalformatParameter(
gl.RENDERBUFFER,
gl[internalFormat],
gl.SAMPLES
);
return samples[0];
}
@ -741,7 +745,12 @@ class Renderer {
let h = this.handler;
h.gl.clearColor(this.backgroundColor.x, this.backgroundColor.y, this.backgroundColor.z, 1.0);
h.gl.clearColor(
this.backgroundColor.x,
this.backgroundColor.y,
this.backgroundColor.z,
1.0
);
h.gl.clear(h.gl.COLOR_BUFFER_BIT | h.gl.DEPTH_BUFFER_BIT);
e.dispatch(e.draw, this);
@ -970,7 +979,6 @@ class Renderer {
start() {
this.handler.start();
}
}
export { Renderer };

View File

@ -19,7 +19,7 @@ const MB_M = 0b0100;
/**
* Renderer events handler.
* @class
* @param {og.Renderer} renderer - Renderer object, events that works for.
* @param {Renderer} renderer - Renderer object, events that works for.
*/
class RendererEvents extends Events {
constructor(renderer) {
@ -28,28 +28,28 @@ class RendererEvents extends Events {
/**
* Assigned renderer.
* @public
* @type {og.Renderer}
* @type {Renderer}
*/
this.renderer = renderer;
/**
* Low level touch events handler.
* @private
* @type {og.input.TouchHandler}
* @type {input.TouchHandler}
*/
this._touchHandler = new TouchHandler(renderer.handler.canvas);
/**
* Low level mouse events handler.
* @private
* @type {og.input.MouseHandler}
* @type {input.MouseHandler}
*/
this._mouseHandler = new MouseHandler(renderer.handler.canvas);
/**
* Low level keyboard events handler.
* @private
* @type {og.input.KeyboardHandler}
* @type {input.KeyboardHandler}
*/
this._keyboardHandler = new KeyboardHandler();
@ -190,6 +190,9 @@ class RendererEvents extends Events {
this._dblTchCoords = new Vec2();
this._oneTouchStart = false;
this._dblTchBegins = 0;
/**
* @type {number}
*/
this._mousestopThread = null;
this._ldblClkBegins = 0;
this._rdblClkBegins = 0;
@ -332,7 +335,7 @@ class RendererEvents extends Events {
*/
onMouseMove(event, sys) {
var ms = this.mouseState;
this.updateButtonsStates(sys.buttons)
this.updateButtonsStates(sys.buttons);
ms.sys = event;
let ex = event.clientX,

View File

@ -2,7 +2,7 @@
* @module og/scene/BaseNode
*/
'use strict';
"use strict";
/**
* Scene node base class.
@ -11,7 +11,6 @@
*/
class BaseNode {
constructor(name) {
/**
* Node name.
* @public
@ -22,7 +21,7 @@ class BaseNode {
/**
* Top scene tree node pointer.
* @public
* @type {og.RenderNode}
* @type {RenderNode}
*/
this.topNode = this;
@ -32,14 +31,14 @@ class BaseNode {
/**
* Children nodes.
* @public
* @type {Array.<og.RenderNode>}
* @type {Array.<RenderNode>}
*/
this.childNodes = [];
/**
* Parent node pointer.
* @public
* @type {og.RenderNode}
* @type {RenderNode}
*/
this.parentNode = null;
@ -60,7 +59,7 @@ class BaseNode {
/**
* Adds node to the current hierarchy.
* @public
* @type {og.BaseNode}
* @type {BaseNode}
*/
addNode(node) {
if (this.parentNode == null) {
@ -89,7 +88,7 @@ class BaseNode {
* Gets node by name in the current.
* @public
* @param {string} name - Node name.
* @return {og.RenderNode} Node object in the current node.
* @return {RenderNode} Node object in the current node.
*/
getNodeByName(name) {
return this._dictionary[name];

View File

@ -89,10 +89,13 @@ const EVENT_NAMES = [
/**
* Main class for rendering planet
* @class
* @extends {og.scene.RenderNode}
* @param {string} name - Planet name(Earth by default)
* @param {og.Ellipsoid} ellipsoid - Planet ellipsoid(WGS84 by default)
* @param {Number} [maxGridSize=128] - Segment maximal grid size
* @extends {RenderNode}
* @param {string} [options.name="Earth"] - Planet name(Earth by default)
* @param {Ellipsoid} [options.ellipsoid] - Planet ellipsoid(WGS84 by default)
* @param {Number} [options.maxGridSize=128] - Segment maximal grid size
* @param {Number} [options.maxEqualZoomAltitude=850000.0] - Maximal altitude since segments on the screen bacame the same zoom level
* @param {Number} [options.minEqualZoomAltitude=10000.0] - Minimal altitude since segments on the screen bacame the same zoom level
* @param {Number} [options.minEqualZoomCameraSlope=0.8] - Minimal camera slope above te globe where segments on the screen bacame the same zoom level
* @fires og.scene.Planet#draw
* @fires og.scene.Planet#layeradd
* @fires og.scene.Planet#baselayerchange
@ -106,7 +109,7 @@ export class Planet extends RenderNode {
/**
* @public
* @type {og.Ellipsoid}
* @type {Ellipsoid}
*/
this.ellipsoid = options.ellipsoid || wgs84;
@ -126,21 +129,21 @@ export class Planet extends RenderNode {
/**
* All layers array.
* @public
* @type {Array.<og.Layer>}
* @type {Array.<Layer>}
*/
this.layers = [];
/**
* Current visible imagery tile layers array.
* @public
* @type {Array.<og.Layer>}
* @type {Array.<Layer>}
*/
this.visibleTileLayers = [];
/**
* Current visible vector layers array.
* @protected
* @type {Array.<og.layer.Vector>}
* @type {Array.<layer.Vector>}
*/
this.visibleVectorLayers = [];
@ -149,38 +152,42 @@ export class Planet extends RenderNode {
/**
* Vector layers visible nodes with collections.
* @protected
* @type {Array.<og.EntityCollection>}
* @type {Array.<EntityCollection>}
*/
this._frustumEntityCollections = [];
/**
* There is only one base layer on the globe when layer.isBaseLayer is true.
* @public
* @type {og.Layer}
* @type {Layer}
*/
this.baseLayer = null;
/**
* Terrain provider.
* @public
* @type {og.terrain.Terrain}
* @type {Terrain}
*/
this.terrain = null;
/**
* Camera is this.renderer.activeCamera pointer.
* @public
* @type {og.PlanetCamera}
* @type {PlanetCamera}
*/
this.camera = null;
this._minAltitude = options.minAltitude;
this._maxAltitude = options.maxAltitude;
this.maxEqualZoomAltitude = options.maxEqualZoomAltitude || 850000.0;
this.minEqualZoomAltitude = options.minEqualZoomAltitude || 10000.0;
this.minEqualZoomCameraSlope = options.minEqualZoomCameraSlope || 0.8;
/**
* Screen mouse pointer projected to planet cartesian position.
* @public
* @type {og.Vec3}
* @type {Vec3}
*/
this.mousePositionOnEarth = new Vec3();
@ -212,7 +219,7 @@ export class Planet extends RenderNode {
/**
* Planet's segments collected for rendering frame.
* @protected
* @type {og.quadTree.Node}
* @type {quadTree.Node}
*/
this._renderedNodes = [];
this._renderedNodesInFrustum = [];
@ -220,42 +227,42 @@ export class Planet extends RenderNode {
/**
* Created nodes cache
* @protected
* @type {og.quadTree.Node}
* @type {quadTree.Node}
*/
this._quadTreeNodesCacheMerc = {};
/**
* Current visible mercator segments tree nodes array.
* @protected
* @type {og.quadTree.Node}
* @type {quadTree.Node}
*/
this._visibleNodes = {};
/**
* Current visible north pole nodes tree nodes array.
* @protected
* @type {og.quadTree.Node}
* @type {quadTree.Node}
*/
this._visibleNodesNorth = {};
/**
* Current visible south pole nodes tree nodes array.
* @protected
* @type {og.quadTree.Node}
* @type {quadTree.Node}
*/
this._visibleNodesSouth = {};
/**
* Layers activity lock.
* @public
* @type {og.idle.Lock}
* @type {idle.Lock}
*/
this.layerLock = new Lock();
/**
* Terrain providers activity lock.
* @public
* @type {og.idle.Lock}
* @type {idle.Lock}
*/
this.terrainLock = new Lock();
@ -298,21 +305,21 @@ export class Planet extends RenderNode {
/**
* Mercator grid tree.
* @protected
* @type {og.quadTree.Node}
* @type {quadTree.Node}
*/
this._quadTree = null;
/**
* North grid tree.
* @protected
* @type {og.quadTree.Node}
* @type {quadTree.Node}
*/
this._quadTreeNorth = null;
/**
* South grid tree.
* @protected
* @type {og.quadTree.Node}
* @type {quadTree.Node}
*/
this._quadTreeSouth = null;
@ -378,7 +385,7 @@ export class Planet extends RenderNode {
/**
* GeoImage creator.
* @protected
* @type{og.utils.GeoImageCreator}
* @type{utils.GeoImageCreator}
*/
this._geoImageCreator = null;
@ -415,7 +422,7 @@ export class Planet extends RenderNode {
/**
* Add the given control to the renderer of the planet scene.
* @param {og.control.Control} control - Control.
* @param {control.Control} control - Control.
*/
addControl(control) {
control.planet = this;
@ -427,11 +434,12 @@ export class Planet extends RenderNode {
if (minLod) {
this._minLodRatio = minLod;
}
this._renderCompletedActivated = false;
}
/**
* Add the given controls array to the renderer of the planet.
* @param {Array.<og.control.Control>} cArr - Control array.
* @param {Array.<control.Control>} cArr - Control array.
*/
addControls(cArr) {
for (var i = 0; i < cArr.length; i++) {
@ -443,7 +451,7 @@ export class Planet extends RenderNode {
* Return layer by it name
* @param {string} name - Name of the layer. og.Layer.prototype.name
* @public
* @returns {og.Layer} -
* @returns {Layer} -
*/
getLayerByName(name) {
var i = this.layers.length;
@ -456,7 +464,7 @@ export class Planet extends RenderNode {
/**
* Adds the given layer to the planet.
* @param {og.Layer} layer - Layer object.
* @param {Layer} layer - Layer object.
* @public
*/
addLayer(layer) {
@ -465,7 +473,7 @@ export class Planet extends RenderNode {
/**
* Dispatch layer visibility changing event.
* @param {og.Layer} layer - Changed layer.
* @param {Layer} layer - Changed layer.
* @protected
*/
_onLayerVisibilityChanged(layer) {
@ -474,7 +482,7 @@ export class Planet extends RenderNode {
/**
* Adds the given layers array to the planet.
* @param {Array.<og.Layer>} layers - Layers array.
* @param {Array.<Layer>} layers - Layers array.
* @public
*/
addLayers(layers) {
@ -485,8 +493,8 @@ export class Planet extends RenderNode {
/**
* Removes the given layer from the planet.
* @param {og.Layer} layer - Layer to remove.
* @return {og.Layer|undefined} The removed layer or undefined if the layer was not found.
* @param {Layer} layer - Layer to remove.
* @return {Layer|undefined} The removed layer or undefined if the layer was not found.
* @public
*/
removeLayer(layer) {
@ -496,7 +504,7 @@ export class Planet extends RenderNode {
/**
*
* @protected
* @param {og.Layer} layer - Material layer.
* @param {Layer} layer - Material layer.
*/
_clearLayerMaterial(layer) {
var lid = layer._id;
@ -511,7 +519,7 @@ export class Planet extends RenderNode {
/**
* Get the collection of layers associated with this planet.
* @return {Array.<og.Layer>} Layers array.
* @return {Array.<Layer>} Layers array.
* @public
*/
getLayers() {
@ -520,7 +528,7 @@ export class Planet extends RenderNode {
/**
* Sets base layer coverage to the planet.
* @param {og.Layer} layer - Layer object.
* @param {Layer} layer - Layer object.
* @public
*/
setBaseLayer(layer) {
@ -543,6 +551,8 @@ export class Planet extends RenderNode {
* @param {number} factor - Elevation scale.
*/
setHeightFactor(factor) {
this._renderCompletedActivated = false;
if (this._heightFactor !== factor) {
this._heightFactor = factor;
this._quadTree.destroyBranches();
@ -560,7 +570,7 @@ export class Planet extends RenderNode {
/**
* Sets terrain provider
* @public
* @param {og.terrain.Terrain} terrain - Terrain provider.
* @param {Terrain} terrain - Terrain provider.
*/
setTerrain(terrain) {
this._renderCompletedActivated = false;
@ -811,7 +821,7 @@ export class Planet extends RenderNode {
this._quadTree.renderNode(true);
this._normalMapCreator.drawSingle(this._quadTree.segment);
for (var i = 0; i < this._quadTree.nodes.length; i++) {
for (let i = 0; i < this._quadTree.nodes.length; i++) {
this._quadTree.nodes[i].segment.createPlainSegment();
this._quadTree.nodes[i].renderNode(true);
this._normalMapCreator.drawSingle(this._quadTree.nodes[i].segment);
@ -822,7 +832,7 @@ export class Planet extends RenderNode {
this._quadTreeNorth.renderNode(true);
this._normalMapCreator.drawSingle(this._quadTreeNorth.segment);
for (var i = 0; i < this._quadTreeNorth.nodes.length; i++) {
for (let i = 0; i < this._quadTreeNorth.nodes.length; i++) {
this._quadTreeNorth.nodes[i].segment.createPlainSegment();
this._quadTreeNorth.nodes[i].renderNode(true);
this._normalMapCreator.drawSingle(this._quadTreeNorth.nodes[i].segment);
@ -833,7 +843,7 @@ export class Planet extends RenderNode {
this._quadTreeSouth.renderNode(true);
this._normalMapCreator.drawSingle(this._quadTreeSouth.segment);
for (var i = 0; i < this._quadTreeSouth.nodes.length; i++) {
for (let i = 0; i < this._quadTreeSouth.nodes.length; i++) {
this._quadTreeSouth.nodes[i].segment.createPlainSegment();
this._quadTreeSouth.nodes[i].renderNode(true);
this._normalMapCreator.drawSingle(this._quadTreeSouth.nodes[i].segment);
@ -986,13 +996,15 @@ export class Planet extends RenderNode {
* @protected
*/
_collectRenderNodes() {
let cam = this.camera;
this._lodRatio = math.lerp(
this.camera.slope < 0.0 ? 0.0 : this.camera.slope,
cam.slope < 0.0 ? 0.0 : cam.slope,
this._maxLodRatio,
this._minLodRatio
);
this.camera._insideSegment = null;
cam._insideSegment = null;
this._nodeCounterError_ = 0;
@ -1008,12 +1020,12 @@ export class Planet extends RenderNode {
this.minCurrZoom = math.MAX;
this.maxCurrZoom = math.MIN;
this._quadTree.renderTree(this.camera, 0, null);
this._quadTree.renderTree(cam, 0, null);
if (
this.renderer.activeCamera.slope > 0.8 &&
this.renderer.activeCamera._lonLat.height < 850000.0 &&
this.renderer.activeCamera._lonLat.height > 10000.0
cam.slope > this.minEqualZoomCameraSlope &&
cam._lonLat.height < this.maxEqualZoomAltitude &&
cam._lonLat.height > this.minEqualZoomAltitude
) {
this.minCurrZoom = this.maxCurrZoom;
@ -1048,18 +1060,20 @@ export class Planet extends RenderNode {
}
for (let i = 0, len = temp2.length; i < len; i++) {
temp2[i].renderTree(this.camera, this.maxCurrZoom, null);
temp2[i].renderTree(cam, this.maxCurrZoom, null);
}
}
this._quadTreeNorth.renderTree(this.camera, 0, null);
this._quadTreeSouth.renderTree(this.camera, 0, null);
this._quadTreeNorth.renderTree(cam, 0, null);
this._quadTreeSouth.renderTree(cam, 0, null);
}
_globalPreDraw() {
this._distBeforeMemClear += this._prevCamEye.distance(this.camera.eye);
this._prevCamEye.copy(this.camera.eye);
this.renderer.activeCamera.checkFly();
let cam = this.camera;
this._distBeforeMemClear += this._prevCamEye.distance(cam.eye);
this._prevCamEye.copy(cam.eye);
cam.checkFly();
// free memory
if (this._createdNodesCount > MAX_NODES && this._distBeforeMemClear > 1000.0) {
@ -1110,7 +1124,7 @@ export class Planet extends RenderNode {
gl.disable(gl.POLYGON_OFFSET_FILL);
if (frustumIndex === cam.FARTHEST_FRUSTUM_INDEX) {
if (this._skipPreRender && (!this._renderCompletedActivated || cam._moved)) {
if (this._skipPreRender && (!this._renderCompletedActivated || cam.isMoved)) {
this._collectRenderNodes();
}
this._skipPreRender = true;
@ -1134,7 +1148,9 @@ export class Planet extends RenderNode {
}
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.enable(gl.BLEND);
gl.enable(gl.CULL_FACE);
@ -1457,8 +1473,8 @@ export class Planet extends RenderNode {
* Returns ray vector hit ellipsoid coordinates.
* If the ray doesn't hit ellipsoit returns null.
* @public
* @param {og.Ray} ray - Ray 3d.
* @returns {og.Vec3} -
* @param {Ray} ray - Ray 3d.
* @returns {Vec3} -
*/
getRayIntersectionEllipsoid(ray) {
return this.ellipsoid.hitRay(ray.origin, ray.direction);
@ -1467,8 +1483,8 @@ export class Planet extends RenderNode {
/**
* Returns 2d screen coordanates projection point to the planet ellipsoid 3d coordinates.
* @public
* @param {og.math.Pixel} px - 2D sreen coordinates.
* @returns {og.Vec3} -
* @param {math.Pixel} px - 2D sreen coordinates.
* @returns {Vec3} -
*/
getCartesianFromPixelEllipsoid(px) {
var cam = this.renderer.activeCamera;
@ -1478,7 +1494,7 @@ export class Planet extends RenderNode {
/**
* Returns 2d screen coordanates projection point to the planet ellipsoid geographical coordinates.
* @public
* @param {og.math.Pixel} px - 2D screen coordinates.
* @param {math.Pixel} px - 2D screen coordinates.
* @returns {LonLat} -
*/
getLonLatFromPixelEllipsoid(px) {
@ -1494,7 +1510,7 @@ export class Planet extends RenderNode {
* position or null if mouse cursor is outside the planet.
* @public
* @param {Boolean} [force=false] - Force framebuffer rendering.
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
getCartesianFromMouseTerrain(force) {
var ms = this.renderer.events.mouseState;
@ -1509,9 +1525,9 @@ export class Planet extends RenderNode {
* Returns 3d cartesian coordinates on the relief planet by 2d screen coordinates.
* position or null if input coordinates is outside the planet.
* @public
* @param {og.Vec2} px - Pixel screen 2d coordinates.
* @param {Vec2} px - Pixel screen 2d coordinates.
* @param {Boolean} [force=false] - Force framebuffer rendering.
* @returns {og.Vec3} -
* @returns {Vec3} -
*/
getCartesianFromPixelTerrain(px, force) {
var distance = this.getDistanceFromPixel(px, force);
@ -1526,7 +1542,7 @@ export class Planet extends RenderNode {
* Returns geographical coordinates on the relief planet by 2d screen coordinates.
* position or null if input coordinates is outside the planet.
* @public
* @param {og.Vec2} px - Pixel screen 2d coordinates.
* @param {Vec2} px - Pixel screen 2d coordinates.
* @param {Boolean} [force=false] - Force framebuffer rendering.
* @returns {LonLat} -
*/
@ -1541,8 +1557,8 @@ export class Planet extends RenderNode {
/**
* Returns projected 2d screen coordinates by 3d cartesian coordiantes.
* @public
* @param {og.Vec3} coords - Cartesian coordinates.
* @returns {og.Vec2} -
* @param {Vec3} coords - Cartesian coordinates.
* @returns {Vec2} -
*/
getPixelFromCartesian(coords) {
return this.renderer.activeCamera.project(coords);
@ -1552,7 +1568,7 @@ export class Planet extends RenderNode {
* Returns projected 2d screen coordinates by geographical coordinates.
* @public
* @param {LonLat} lonlat - Geographical coordinates.
* @returns {og.Vec2} -
* @returns {Vec2} -
*/
getPixelFromLonLat(lonlat) {
var coords = this.ellipsoid.lonLatToCartesian(lonlat);
@ -1566,7 +1582,7 @@ export class Planet extends RenderNode {
* Returns distance from active camera to the the planet ellipsoid
* coordiantes unprojected by 2d screen coordiantes, or null if screen coordinates outside the planet.
* @public
* @param {og.Vec2} px - Screen coordinates.
* @param {Vec2} px - Screen coordinates.
* @returns {number} -
*/
getDistanceFromPixelEllipsoid(px) {
@ -1580,7 +1596,7 @@ export class Planet extends RenderNode {
* If screen coordinates inside the planet but relief is not exists in the
* point than function returns distance to the planet ellipsoid.
* @public
* @param {og.Vec2} px - Screen coordinates.
* @param {Vec2} px - Screen coordinates.
* @param {Boolean} [force=false] - Force framebuffer rendering.
* @returns {number} -
*/
@ -1624,7 +1640,7 @@ export class Planet extends RenderNode {
/**
* Sets camera to the planet geographical extent.
* @public
* @param {og.Extent} extent - Geographical extent.
* @param {Extent} extent - Geographical extent.
*/
viewExtent(extent) {
this.renderer.activeCamera.viewExtent(extent);
@ -1648,7 +1664,7 @@ export class Planet extends RenderNode {
/**
* Gets current viewing geographical extent.
* @public
* @returns {og.Extent} -
* @returns {Extent} -
*/
getViewExtent() {
return this._viewExtent;
@ -1680,7 +1696,7 @@ export class Planet extends RenderNode {
* Sets camera to the planet geographical position.
* @public
* @param {LonLat} lonlat - New geographical position.
* @param {og.Vec3} [up] - Camera UP vector.
* @param {Vec3} [up] - Camera UP vector.
*/
viewLonLat(lonlat, up) {
this.renderer.activeCamera.setLonLat(lonlat, up);
@ -1689,9 +1705,9 @@ export class Planet extends RenderNode {
/**
* Fly camera to the planet geographical extent.
* @public
* @param {og.Extent} extent - Geographical extent.
* @param {Extent} extent - Geographical extent.
* @param {Number} [height] - Height on the end of the flight route.
* @param {og.Vec3} [up] - Camera UP vector on the end of a flying.
* @param {Vec3} [up] - Camera UP vector on the end of a flying.
* @param {Number} [ampl] - Altitude amplitude factor.
* @param {cameraCallback} [startCallback] - Callback that calls after flying when flying is finished.
* @param {cameraCallback} [completeCallback] - Callback that calls befor the flying begins.
@ -1710,9 +1726,9 @@ export class Planet extends RenderNode {
/**
* Fly camera to the new point.
* @public
* @param {og.Vec3} cartesian - Fly coordiantes.
* @param {og.Vec3} [look] - Camera "look at" point.
* @param {og.Vec3} [up] - Camera UP vector on the end of a flying.
* @param {Vec3} cartesian - Fly coordiantes.
* @param {Vec3} [look] - Camera "look at" point.
* @param {Vec3} [up] - Camera UP vector on the end of a flying.
* @param {Number} [ampl] - Altitude amplitude factor.
* @param [completeCallback]
* @param [startCallback]
@ -1734,8 +1750,8 @@ export class Planet extends RenderNode {
* Fly camera to the new geographical position.
* @public
* @param {LonLat} lonlat - Fly geographical coordiantes.
* @param {og.Vec3} [look] - Camera "look at" point on the end of a flying.
* @param {og.Vec3} [up] - Camera UP vector on the end of a flying.
* @param {Vec3} [look] - Camera "look at" point on the end of a flying.
* @param {Vec3} [up] - Camera UP vector on the end of a flying.
* @param {Number} [ampl] - Altitude amplitude factor.
* @param [completeCallback]
* @param [startCallback]

View File

@ -1,7 +1,7 @@
'use strict';
"use strict";
import { BaseNode } from './BaseNode.js';
import { Events } from '../Events.js';
import { BaseNode } from "./BaseNode.js";
import { Events } from "../Events.js";
/**
* Render node is a logical part of a render mechanism. Represents scene rendering.
@ -10,7 +10,7 @@ import { Events } from '../Events.js';
* There are collections of ligh sources, entities and so on in the node.
* Access to the node is renderer.renderNodes["Earth"]
* @class
* @extends {og.RenderNode}
* @extends {RenderNode}
* @param {string} name - Node name.
*/
class RenderNode extends BaseNode {
@ -20,7 +20,7 @@ class RenderNode extends BaseNode {
/**
* Renderer that calls frame() callback.
* @public
* @type {og.Renderer}
* @type {Renderer}
*/
this.renderer = null;
@ -43,7 +43,7 @@ class RenderNode extends BaseNode {
/**
* Point light array.
* @private
* @type {Array.<og.LightSource>}
* @type {Array.<LightSource>}
*/
this._lights = [];
this._lightsTransformedPositions = [];
@ -54,7 +54,7 @@ class RenderNode extends BaseNode {
/**
* Entity collection array.
* @public
* @type {Array.<og.EntityCollection>}
* @type {Array.<EntityCollection>}
*/
this.entityCollections = [];
@ -66,7 +66,7 @@ class RenderNode extends BaseNode {
/**
* Adds node to the current hierarchy.
* @public
* @type {og.RenderNode}
* @type {RenderNode}
*/
addNode(node) {
super.addNode(node);
@ -76,7 +76,7 @@ class RenderNode extends BaseNode {
/**
* Assign render node with renderer.
* @public
* @param {og.Renderer} renderer - Redner node's renderer.
* @param {Renderer} renderer - Redner node's renderer.
*/
assign(renderer) {
this.renderer = renderer;
@ -98,8 +98,7 @@ class RenderNode extends BaseNode {
n = this.name;
if (r) {
if (r.renderNodes[n] &&
r.renderNodes[n].isEqual(this)) {
if (r.renderNodes[n] && r.renderNodes[n].isEqual(this)) {
r.renderNodes[n] = null;
delete r.renderNodes[n];
}
@ -119,9 +118,9 @@ class RenderNode extends BaseNode {
/**
* Adds entity collection.
* @public
* @param {og.EntityCollection} entityCollection - Entity collection.
* @param {EntityCollection} entityCollection - Entity collection.
* @param {boolean} [isHidden] - If it's true that this collection has specific rendering.
* @returns {og.scene.RenderNode} -
* @returns {RenderNode} -
*/
addEntityCollection(entityCollection, isHidden) {
entityCollection.addTo(this, isHidden);
@ -131,7 +130,7 @@ class RenderNode extends BaseNode {
/**
* Removes entity collection.
* @public
* @param {og.EntityCollection} entityCollection - Entity collection for remove.
* @param {EntityCollection} entityCollection - Entity collection for remove.
*/
removeEntityCollection(entityCollection) {
entityCollection.remove();
@ -140,8 +139,8 @@ class RenderNode extends BaseNode {
/**
* Adds point light source.
* @public
* @param {og.LightSource} light - Light source.
* @returns {og.scene.RenderNode}
* @param {LightSource} light - Light source.
* @returns {RenderNode}
*/
addLight(light) {
light.addTo(this);
@ -152,7 +151,7 @@ class RenderNode extends BaseNode {
* Gets light object by its name.
* @public
* @param {string} name - Point light name.
* @returns {og.LightSource}
* @returns {LightSource}
*/
getLightByName(name) {
var li = this._lightsNames.indexOf(name);
@ -162,7 +161,7 @@ class RenderNode extends BaseNode {
/**
* Removes light source.
* @public
* @param {og.LightSource} light - Light source object.
* @param {LightSource} light - Light source object.
*/
removeLight(light) {
light.remove();
@ -195,7 +194,10 @@ class RenderNode extends BaseNode {
if (this.renderer) {
if (this._isActive && this._pickingId === -1) {
this._pickingId = this.renderer.addPickingCallback(this, this._entityCollectionPickingCallback);
this._pickingId = this.renderer.addPickingCallback(
this,
this._entityCollectionPickingCallback
);
} else if (!this._isActive && this._pickingId !== -1) {
this.renderer.removePickingCallback(this._pickingId);
this._pickingId = -1;
@ -277,7 +279,6 @@ class RenderNode extends BaseNode {
*/
drawPickingEntityCollections(ec) {
if (ec.length) {
var gl = this.renderer.handler.gl;
gl.disable(gl.CULL_FACE);

View File

@ -11,6 +11,7 @@ import { Sphere } from "../bv/Sphere.js";
import { Box } from "../bv/Box.js";
import { Vec3 } from "../math/Vec3.js";
import * as segmentHelper from "../segment/segmentHelper.js";
import { getMatrixSubArray } from "../utils/shared.js";
export const MAX_NORMAL_ZOOM = 7;
@ -58,15 +59,15 @@ window.BBSC = 100;
/**
* Planet segment Web Mercator tile class that stored and rendered with quad tree.
* @class
* @param {og.quadTree.Node} node - Segment node.
* @param {og.scene.Planet} planet - Current planet scene.
* @param {quadTree.Node} node - Segment node.
* @param {Planet} planet - Current planet scene.
* @param {Number} tileZoom - Zoom index.
* @param {og.Extent} extent - Segment extent.
* @param {Extent} extent - Segment extent.
*/
class Segment {
/**
* @param {quadTree.Node} node - Segment node.
* @param {scene.Planet} planet - Current planet scene.
* @param {Planet} planet - Current planet scene.
* @param {number} tileZoom - Zoom index.
* @param {Extent} extent - Segment extent.
*/
@ -79,25 +80,25 @@ class Segment {
/**
* Quad tree node of the segment.
* @type {og.quadTree.Node}
* @type {quadTree.Node}
*/
this.node = node;
/**
* Planet pointer.
* @type {og.scene.Planet}
* @type {Planet}
*/
this.planet = planet;
/**
* WebGl handler pointer.
* @type {og.webgl.Handler}
* @type {Handler}
*/
this.handler = planet.renderer.handler;
/**
* Segment bounding sphere
* @type {og.bv.Sphere}
* @type {Sphere}
*/
this.bsphere = new Sphere();
@ -105,7 +106,7 @@ class Segment {
/**
* Segment bounding box.
* @type {og.bv.Box}
* @type {Box}
*/
this.bbox = new Box();
@ -116,7 +117,7 @@ class Segment {
/**
* Geographical extent.
* @type {og.Extent}
* @type {Extent}
*/
this._extent = extent;
@ -162,7 +163,7 @@ class Segment {
/**
* Texture materials array.
* @type {Array.<og.planetSegment.Material>}
* @type {Array.<planetSegment.Material>}
*/
this.materials = [];
@ -252,7 +253,7 @@ class Segment {
/**
* Returns that segment good for rendering with camera by current lod ratio.
* @public
* @param {og.Camera} camera - Camera object.
* @param {Camera} camera - Camera object.
* @returns {boolean} -
*/
acceptForRendering(camera) {
@ -265,10 +266,10 @@ class Segment {
/**
* Returns entity terrain point.
* @public
* @param {og.Entity} entity - Entity.
* @param {og.Vec3} res - Point coordinates.
* @param {og.Vec3} [normal] - Terrain point normal.
* @returns {og.Vec3} -
* @param {Entity} entity - Entity.
* @param {Vec3} res - Point coordinates.
* @param {Vec3} [normal] - Terrain point normal.
* @returns {Vec3} -
*/
getEntityTerrainPoint(entity, res, normal) {
return this.getTerrainPoint(entity._cartesian, entity._lonlatMerc, res, normal);
@ -281,10 +282,10 @@ class Segment {
/**
* Returns distance from object to terrain coordinates and terrain point that calculates out in the res parameter.
* @public
* @param {og.Vec3} xyz - Cartesian object position.
* @param {Vec3} xyz - Cartesian object position.
* @param {LonLat} insideSegmentPosition - Geodetic object position.
* @param {og.Vec3} [res] - Result cartesian coordiantes on the terrain.
* @param {og.Vec3} [normal] - Terrain point normal.
* @param {Vec3} [res] - Result cartesian coordiantes on the terrain.
* @param {Vec3} [normal] - Terrain point normal.
* @returns {number} -
*/
getTerrainPoint(xyz, insideSegmentPosition, res, normal) {
@ -375,6 +376,10 @@ class Segment {
return lonlat.forwardMercator();
}
/**
*
* @param {boolean} forceLoading
*/
loadTerrain(forceLoading) {
if (this.tileZoom < this.planet.terrain.minZoom) {
this.terrainIsLoading = true;
@ -1434,8 +1439,8 @@ class Segment {
/**
* Gets specific layer material.
* @public
* @param {og.Layer} layer - Layer object.
* @returns {og.planetSegment.Material} - Segment material.
* @param {Layer} layer - Layer object.
* @returns {planetSegment.Material} - Segment material.
*/
getMaterialByLayer(layer) {
return this.materials[layer._id];

View File

@ -19,16 +19,16 @@ let _tempHigh = new Vec3(),
/**
* Planet segment Web Mercator tile class that stored and rendered with quad tree.
* @class
* @extends {og.planetSegment.Segment}
* @param {og.quadNode.Node} node - Quad tree segment node.
* @param {og.scene.Planet} planet - Scene planet.
* @extends {Segment}
* @param {quadNode.Node} node - Quad tree segment node.
* @param {Planet} planet - Scene planet.
* @param {Number} tileZoom - Segment tile zoom index.
* @param {og.Extent} extent - Segment WGS84 extent.
* @param {Extent} extent - Segment WGS84 extent.
*/
class SegmentLonLat extends Segment {
/**
* @param {quadTree.Node} node - Segment node.
* @param {scene.Planet} planet - Current planet scene.
* @param {Planet} planet - Current planet scene.
* @param {number} tileZoom - Zoom index.
* @param {Extent} extent - Segment extent.
*/

Some files were not shown because too many files have changed in this diff Show More