@dspacev-bundle/vue-cesium
Version:
Vue 3.x components for CesiumJS.
48,507 lines • 1.83 MB
JavaScript
/*! VueCesium v3.1.5 */
System.register(['@dspacev-bundle/vue3', 'lodash-es', 'mitt', 'echarts'], (function (exports) {
'use strict';
var ref, getCurrentInstance, inject, computed, provide, unref, isRef, onBeforeUnmount, onUnmounted, watch, markRaw, reactive, onMounted, nextTick, h, withDirectives, defineComponent, Transition, Teleport, createCommentVNode, createApp, toRaw, renderSlot, isUndefined, isNull, findIndex, camelCase, get$1, isEqual, cloneDeep, differenceBy, debounce, remove, find, uniqWith, mitt, echarts;
return {
setters: [function (module) {
ref = module.ref;
getCurrentInstance = module.getCurrentInstance;
inject = module.inject;
computed = module.computed;
provide = module.provide;
unref = module.unref;
isRef = module.isRef;
onBeforeUnmount = module.onBeforeUnmount;
onUnmounted = module.onUnmounted;
watch = module.watch;
markRaw = module.markRaw;
reactive = module.reactive;
onMounted = module.onMounted;
nextTick = module.nextTick;
h = module.h;
withDirectives = module.withDirectives;
defineComponent = module.defineComponent;
Transition = module.Transition;
Teleport = module.Teleport;
createCommentVNode = module.createCommentVNode;
createApp = module.createApp;
toRaw = module.toRaw;
renderSlot = module.renderSlot;
}, function (module) {
isUndefined = module.isUndefined;
isNull = module.isNull;
findIndex = module.findIndex;
camelCase = module.camelCase;
get$1 = module.get;
isEqual = module.isEqual;
cloneDeep = module.cloneDeep;
differenceBy = module.differenceBy;
debounce = module.debounce;
remove = module.remove;
find = module.find;
uniqWith = module.uniqWith;
}, function (module) {
mitt = module["default"];
}, function (module) {
echarts = module;
}],
execute: (function () {
exports({
useCommon: useCommon,
useDatasources: useDatasources,
useEvents: useEvents,
useGeometries: useGeometries,
useGraphics: useGraphics,
useHandler: useHandler,
usePrimitiveCollectionItems: usePrimitiveCollectionItems,
usePrimitiveCollections: usePrimitiveCollections,
usePrimitives: usePrimitives,
useProviders: useProviders,
useVueCesium: useVueCesium
});
const version$1 = "3.1.5";
const hasSymbol = typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol";
const vcKey = exports('vcKey', hasSymbol ? Symbol("VueCesium") : "VueCesium");
const fabKey = hasSymbol ? Symbol("_vc_f_") : "_vc_f_";
const configProviderContextKey = Symbol();
/**
* Make a map and return a function for checking if a key
* is in that map.
* IMPORTANT: all calls of this function must be prefixed with
* \/\*#\_\_PURE\_\_\*\/
* So that rollup can tree-shake them if necessary.
*/
const hasOwnProperty$1 = Object.prototype.hasOwnProperty;
const hasOwn = (val, key) => hasOwnProperty$1.call(val, key);
const isArray = Array.isArray;
const isFunction = (val) => typeof val === 'function';
const isString = (val) => typeof val === 'string';
const isObject = (val) => val !== null && typeof val === 'object';
const objectToString = Object.prototype.toString;
const toTypeString = (value) => objectToString.call(value);
const isPlainObject = (val) => toTypeString(val) === '[object Object]';
const cacheStringFunction = (fn) => {
const cache = Object.create(null);
return ((str) => {
const hit = cache[str];
return hit || (cache[str] = fn(str));
});
};
const camelizeRE = /-(\w)/g;
/**
* @private
*/
const camelize = cacheStringFunction((str) => {
return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
});
const hyphenateRE = /\B([A-Z])/g;
/**
* @private
*/
const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
/**
* @private
*/
const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
function dirname(path) {
if (typeof path !== "string")
path = path + "";
if (path.length === 0)
return ".";
let code = path.charCodeAt(0);
const hasRoot = code === 47;
let end = -1;
let matchedSlash = true;
for (let i = path.length - 1; i >= 1; --i) {
code = path.charCodeAt(i);
if (code === 47) {
if (!matchedSlash) {
end = i;
break;
}
} else {
matchedSlash = false;
}
}
if (end === -1)
return hasRoot ? "/" : ".";
if (hasRoot && end === 1) {
return "/";
}
return path.slice(0, end);
}
function isEmptyObj(obj) {
if (isUndefined(obj) || isNull(obj)) {
return true;
}
if (obj instanceof Element) {
return false;
}
const arr = Object.keys(obj);
return arr.length === 0;
}
const kebabCase = hyphenate;
function myInstanceof(left, right) {
if (typeof left !== "object" || left === null)
return false;
let proto = Object.getPrototypeOf(left);
while (true) {
if (proto === null)
return false;
if (proto === (right == null ? void 0 : right.prototype))
return true;
proto = Object.getPrototypeOf(proto);
}
}
function getCesiumClassName(obj) {
let result = void 0;
const constructorNames = Object.keys(Cesium);
for (let i = 0; i < constructorNames.length; i++) {
const className = constructorNames[i];
if (myInstanceof(obj, Cesium[className])) {
result = className;
break;
}
}
return result;
}
function getObjClassName(obj, findCesiumClass = false) {
if (obj && obj.constructor) {
if (findCesiumClass) {
const cesiumClassName = getCesiumClassName(obj);
if (cesiumClassName) {
return cesiumClassName;
}
}
return obj.constructor.name;
}
return typeof obj;
}
function defaultValue(a, b) {
if (a !== void 0 && a !== null) {
return a;
}
return b;
}
function getDefaultOptionByProps(props, ignores = []) {
const defaultOptions = {};
Object.keys(props).forEach((key) => {
if (ignores.indexOf(key) === -1) {
const value = props[key];
defaultOptions[key] = isFunction(value) ? void 0 : isPlainObject(value) ? isFunction(value.default) ? value.default() : value.default : value;
}
});
return defaultOptions;
}
const addCustomProperty = (obj, options, ignores = []) => {
for (const prop in options) {
if (!obj[prop] && ignores.indexOf(prop) === -1) {
obj[prop] = options[prop];
}
}
};
function isArrayLike(obj) {
if (Array.isArray(obj))
return true;
if (typeof obj !== "object" || !obj)
return false;
const length = obj.length;
return typeof length === "number" && length >= 0;
}
function deepMerge(src = {}, target = {}) {
let key;
for (key in target) {
src[key] = isObject(src[key]) ? deepMerge(src[key], target[key]) : src[key] = target[key];
}
return src;
}
function isNumber$1(v) {
return typeof v === "number" && isFinite(v);
}
function getCesiumColor(inputColor, fallbackColor, timestamp) {
const { JulianDate, Color } = Cesium;
const now = JulianDate.now();
if (inputColor) {
if (typeof inputColor.getValue === "function") {
inputColor = inputColor.getValue(timestamp || now);
}
if (typeof inputColor === "string") {
return Color.fromCssColorString(inputColor);
} else if (typeof inputColor === "function") {
return getCesiumColor(inputColor(timestamp), fallbackColor);
} else {
return inputColor;
}
} else {
return fallbackColor;
}
}
function getCesiumValue(value, valueType, timestamp) {
const { JulianDate, Property } = Cesium;
const now = JulianDate.now();
if (!value)
return value;
if (valueType) {
if (value instanceof valueType)
return value;
else {
if (value instanceof Property && value._value instanceof valueType)
return value._value;
}
}
if (isFunction(value.getValue))
return value.getValue(timestamp || now);
return value;
}
const keysOf = (arr) => Object.keys(arr);
const globalConfig = ref();
function useGlobalConfig(key, defaultValue = void 0) {
const config = getCurrentInstance() ? inject(configProviderContextKey, globalConfig) : globalConfig;
if (key) {
return computed(() => {
var _a, _b;
return (_b = (_a = config.value) == null ? void 0 : _a[key]) != null ? _b : defaultValue;
});
} else {
return config;
}
}
const provideGlobalConfig = (config, app, global = false) => {
var _a;
const inSetup = !!getCurrentInstance();
const oldConfig = inSetup ? useGlobalConfig() : void 0;
const provideFn = (_a = app == null ? void 0 : app.provide) != null ? _a : inSetup ? provide : void 0;
if (!provideFn) {
console.warn("provideGlobalConfig", "provideGlobalConfig() can only be used inside setup().");
return;
}
const context = computed(() => {
const cfg = unref(config);
if (!(oldConfig == null ? void 0 : oldConfig.value))
return cfg;
return mergeConfig(oldConfig.value, cfg);
});
if (app == null ? void 0 : app.provide) {
app.provide(configProviderContextKey, context);
} else {
provide(configProviderContextKey, context);
}
if (global || !globalConfig.value) {
globalConfig.value = context.value;
}
return context;
};
const mergeConfig = (a, b) => {
var _a;
const keys = [.../* @__PURE__ */ new Set([...keysOf(a), ...keysOf(b)])];
const obj = {};
for (const key of keys) {
obj[key] = (_a = b[key]) != null ? _a : a[key];
}
return obj;
};
function useLog(vcInstance) {
var _a, _b, _c, _d;
const makeLog = (prefix = "") => {
return function(...args) {
if (prefix) {
if (isString(args[0])) {
args[0] = prefix.trim() + " " + args[0];
} else {
args = [prefix.trim(), ...args];
}
}
console.log(...args);
};
};
const makeWarn = (prefix = "") => {
return function(...args) {
if (prefix) {
if (isString(args[0])) {
args[0] = prefix.trim() + " " + args[0];
} else {
args = [prefix.trim(), ...args];
}
}
console.warn(...args);
};
};
const makeError = (prefix = "") => {
return function(...args) {
if (prefix) {
if (isString(args[0])) {
args[0] = prefix.trim() + " " + args[0];
} else {
args = [prefix.trim(), ...args];
}
}
console.error(...args);
};
};
const makeDebug = (prefix = "") => {
return function(...args) {
if (prefix) {
if (isString(args[0])) {
args[0] = prefix.trim() + " " + args[0];
} else {
args = [prefix.trim(), ...args];
}
}
};
};
const typeColor = (type = "default") => {
let color = "";
switch (type) {
case "default":
color = "#35495E";
break;
case "primary":
color = "#3488ff";
break;
case "success":
color = "#43B883";
break;
case "warning":
color = "#e6a23c";
break;
case "danger":
color = "#f56c6c";
break;
}
return color;
};
const capsule = (title, info, type = "primary") => {
console.log(
`%c ${title} %c ${info} %c`,
"background:#35495E; padding: 1px; border-radius: 3px 0 0 3px; color: #fff;",
`background:${typeColor(type)}; padding: 1px; border-radius: 0 3px 3px 0; color: #fff;`,
"background:transparent"
);
};
const colorful = (textArr) => {
console.log(`%c${textArr.map((t) => t.text || "").join("%c")}`, ...textArr.map((t) => `color: ${typeColor(t.type)};`));
};
const success = (text) => {
colorful([{ text, type: "success" }]);
};
const warning = (text) => {
colorful([{ text, type: "warning" }]);
};
const danger = (text) => {
colorful([{ text, type: "danger" }]);
};
const primary = (text) => {
colorful([{ text, type: "primary" }]);
};
return {
log: makeLog(`[VueCesium] ${(_a = vcInstance == null ? void 0 : vcInstance.proxy) == null ? void 0 : _a.$options.name}`),
warn: makeWarn(`[VueCesium] WARN ${(_b = vcInstance == null ? void 0 : vcInstance.proxy) == null ? void 0 : _b.$options.name}`),
error: makeError(`[VueCesium] ERR ${(_c = vcInstance == null ? void 0 : vcInstance.proxy) == null ? void 0 : _c.$options.name}`),
debug: makeDebug(`[VueCesium] Debug ${(_d = vcInstance == null ? void 0 : vcInstance.proxy) == null ? void 0 : _d.$options.name}`),
capsule,
success,
warning,
danger,
primary
};
}
useLog(void 0);
const INSTALLED_KEY = Symbol("INSTALLED_KEY");
const makeInstaller = exports('makeInstaller', (components = []) => {
const install = (app, opts) => {
if (app[INSTALLED_KEY])
return;
const defaultConfig = {
cesiumPath: "https://unpkg.com/cesium@latest/Build/Cesium/Cesium.js",
accessToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2OGE2MjZlOC1mMzhiLTRkZjQtOWEwZi1jZTE0MWY0YzhlMTAiLCJpZCI6MjU5LCJpYXQiOjE2NDM3MjU1NzZ9.ptZ5tVXvMmuWRC0WhjtYTg-17nQh14fgxBsx0HJiVXQ"
};
app[INSTALLED_KEY] = true;
const options = Object.assign(defaultConfig, opts);
components.forEach((c) => {
app.use(c, options);
});
provideGlobalConfig(options, app, true);
};
return {
version: version$1,
install
};
});
/*!
* merge-descriptors
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
const hasOwnProperty = Object.prototype.hasOwnProperty;
function merge(dest, src, redefine) {
if (!dest) {
throw new TypeError("argument dest is required");
}
if (!src) {
throw new TypeError("argument src is required");
}
if (redefine === void 0) {
redefine = true;
}
Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName(name) {
if (!redefine && hasOwnProperty.call(dest, name)) {
return;
}
const descriptor = Object.getOwnPropertyDescriptor(src, name);
Object.defineProperty(dest, name, descriptor);
});
return dest;
}
function mergeDescriptors(...args) {
let redefine;
if (typeof args[args.length - 1] !== "object") {
redefine = args.pop();
}
return args.slice(1).reduce((dest, src, i) => merge(dest, src, redefine), args[0]);
}
function vmHasRouter(vm) {
return vm.appContext.config.globalProperties.$router !== void 0;
}
function vmHasListener(vm, listenerName) {
return vm.vnode.props !== null && vm.vnode.props[listenerName] !== void 0;
}
function getInstanceListener(vcInstance, listenerName) {
const props = vcInstance.vnode.props;
if (props === null) {
return void 0;
}
const propKeys = Object.keys(props);
const index = findIndex(propKeys, (o) => {
return o.includes(`on${capitalize(listenerName)}`) || o.includes(`on${capitalize(camelCase(listenerName))}`);
});
const listener = props[propKeys[index]];
return listener;
}
function $(ref) {
return ref.value;
}
function getVcParentInstance(instance) {
var _a, _b;
const parentInstance = instance.parent;
return !parentInstance.cesiumClass && ((_a = parentInstance.proxy) == null ? void 0 : _a.$options.name) !== "VcViewer" ? getVcParentInstance(parentInstance) : ((_b = parentInstance.proxy) == null ? void 0 : _b.getVcViewer) ? parentInstance.proxy.getVcViewer().getInstance() : parentInstance;
}
const semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
const validateAndParse = (version) => {
if (typeof version !== 'string') {
throw new TypeError('Invalid argument expected string');
}
const match = version.match(semver);
if (!match) {
throw new Error(`Invalid argument not valid semver ('${version}' received)`);
}
match.shift();
return match;
};
const isWildcard = (s) => s === '*' || s === 'x' || s === 'X';
const tryParse = (v) => {
const n = parseInt(v, 10);
return isNaN(n) ? v : n;
};
const forceType = (a, b) => typeof a !== typeof b ? [String(a), String(b)] : [a, b];
const compareStrings = (a, b) => {
if (isWildcard(a) || isWildcard(b))
return 0;
const [ap, bp] = forceType(tryParse(a), tryParse(b));
if (ap > bp)
return 1;
if (ap < bp)
return -1;
return 0;
};
const compareSegments = (a, b) => {
for (let i = 0; i < Math.max(a.length, b.length); i++) {
const r = compareStrings(a[i] || '0', b[i] || '0');
if (r !== 0)
return r;
}
return 0;
};
/**
* Compare [semver](https://semver.org/) version strings to find greater, equal or lesser.
* This library supports the full semver specification, including comparing versions with different number of digits like `1.0.0`, `1.0`, `1`, and pre-release versions like `1.0.0-alpha`.
* @param v1 - First version to compare
* @param v2 - Second version to compare
* @returns Numeric value compatible with the [Array.sort(fn) interface](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters).
*/
const compareVersions = (v1, v2) => {
// validate input and split into segments
const n1 = validateAndParse(v1);
const n2 = validateAndParse(v2);
// pop off the patch
const p1 = n1.pop();
const p2 = n2.pop();
// validate numbers
const r = compareSegments(n1, n2);
if (r !== 0)
return r;
// validate pre-release
if (p1 && p2) {
return compareSegments(p1.split('.'), p2.split('.'));
}
else if (p1 || p2) {
return p1 ? -1 : 1;
}
return 0;
};
/**
* Compare [semver](https://semver.org/) version strings using the specified operator.
*
* @param v1 First version to compare
* @param v2 Second version to compare
* @param operator Allowed arithmetic operator to use
* @returns `true` if the comparison between the firstVersion and the secondVersion satisfies the operator, `false` otherwise.
*
* @example
* ```
* compare('10.1.8', '10.0.4', '>'); // return true
* compare('10.0.1', '10.0.1', '='); // return true
* compare('10.1.1', '10.2.2', '<'); // return true
* compare('10.1.1', '10.2.2', '<='); // return true
* compare('10.1.1', '10.2.2', '>='); // return false
* ```
*/
const compare = (v1, v2, operator) => {
// validate input operator
assertValidOperator(operator);
// since result of compareVersions can only be -1 or 0 or 1
// a simple map can be used to replace switch
const res = compareVersions(v1, v2);
return operatorResMap[operator].includes(res);
};
const operatorResMap = {
'>': [1],
'>=': [0, 1],
'=': [0],
'<=': [-1, 0],
'<': [-1],
'!=': [-1, 1],
};
const allowedOperators = Object.keys(operatorResMap);
const assertValidOperator = (op) => {
if (typeof op !== 'string') {
throw new TypeError(`Invalid operator type, expected string but got ${typeof op}`);
}
if (allowedOperators.indexOf(op) === -1) {
throw new Error(`Invalid operator, expected one of ${allowedOperators.join('|')}`);
}
};
var VcCircleWaveMaterial = `
czm_material czm_getMaterial(czm_materialInput materialInput) {
czm_material material = czm_getDefaultMaterial(materialInput);
material.diffuse = 1.5 * color.rgb;
vec2 st = materialInput.st;
vec3 str = materialInput.str;
float dis = distance(st, vec2(0.5, 0.5));
float per = fract(time);
if (abs(str.z) > 0.001) {
discard;
}
if (dis > 0.5) {
discard;
} else {
float perDis = 0.5 / count;
float disNum;
float bl = .0;
for (int i = 0; i <= 9; i++) {
if (float(i) <= count) {
disNum = perDis *float(i) - dis + per / count;
if (disNum > 0.0) {
if (disNum < perDis) {
bl = 1.0 - disNum / perDis;
} else if(disNum - perDis < perDis) {
bl = 1.0 - abs(1.0 - disNum / perDis);
}
material.alpha = pow(bl, gradient);
}
}
}
}
return material;
}`;
var VcLineFlowMaterial = `
uniform float globalAlpha;
uniform bool axisY;
uniform bool mixt;
czm_material czm_getMaterial(czm_materialInput materialInput) {
czm_material material = czm_getDefaultMaterial(materialInput);
vec2 st = repeat * materialInput.st;
vec4 colorImage;
if (speed != 0.0) {
float currTime;
if (time < 0.0) {
currTime = speed * czm_frameNumber / 1000.0;
} else {
currTime = time;
}
colorImage = texture(image, vec2(fract((axisY ? st.t : st.s) - currTime), st.t));
} else {
colorImage = texture(image, st);
}
if (color.a == 0.0) {
if (colorImage.rgb == vec3(1.0)) {
discard;
}
}
if (color.rgb == vec3(1.0)) {
material.alpha = colorImage.a * globalAlpha;
material.diffuse = colorImage.rgb;
} else {
material.alpha = colorImage.a * color.a * globalAlpha;
if (mixt)
material.diffuse = max(colorImage.rgb * color.rgb * material.alpha * 3.0, colorImage.rgb * color.rgb);
else
material.diffuse = max(color.rgb * material.alpha * 3.0, color.rgb);
}
if (hasImage2) {
vec4 colorBG = texture(image2, materialInput.st);
if (colorBG.a > 0.5) {
material.diffuse = color2.rgb;
}
}
return material;
}
`;
let isExtended$2 = false;
class MaterialExtend {
static extend(viewer) {
var _a;
if (isExtended$2) {
return;
}
const { Material, Color, Cartesian2 } = Cesium;
const webgl2 = (_a = viewer.scene.context) == null ? void 0 : _a.webgl2;
let shaderSourceTextVcLine = VcLineFlowMaterial;
let shaderSourceTextVcCircle = VcCircleWaveMaterial;
if (!webgl2) {
shaderSourceTextVcLine = shaderSourceTextVcLine.replace(/texture\(/g, "texture2D(");
shaderSourceTextVcCircle = shaderSourceTextVcCircle.replace(/texture\(/g, "texture2D(");
}
Material["VcCircleWave"] = "VcCircleWave";
Cesium.Material["_materialCache"].addMaterial(Material["VcCircleWave"], {
fabric: {
type: Material["VcCircleWave"],
uniforms: {
color: new Color(1, 0, 0, 1),
time: 1,
count: 1,
gradient: 0.1
},
source: shaderSourceTextVcCircle
},
translucent() {
return true;
}
});
Material["VcLineFlow"] = "VcLineFlow";
Cesium.Material["_materialCache"].addMaterial(Material["VcLineFlow"], {
fabric: {
type: Material["VcLineFlow"],
uniforms: {
image: Material.DefaultImageId,
color: new Color(1, 1, 1, 1),
repeat: new Cartesian2(1, 1),
axisY: false,
mixt: false,
speed: 10,
time: -1,
hasImage2: false,
image2: Material.DefaultImageId,
color2: new Color(1, 1, 1),
globalAlpha: 1
},
source: shaderSourceTextVcLine
},
translucent() {
return true;
}
});
isExtended$2 = true;
}
static revoke(viewer) {
if (!isExtended$2) {
return;
}
isExtended$2 = false;
}
} exports('MaterialExtend', MaterialExtend);
class BaseMaterialProperty {
constructor(options = {}) {
this.options = options;
this._definitionChanged = new Cesium.Event();
}
get isConstant() {
return true;
}
get definitionChanged() {
return this._definitionChanged;
}
getType(parameter) {
return null;
}
getValue(context, defaultValue = {}) {
return defaultValue;
}
equals(other) {
return this === other;
}
}
class VcCircleWaveMaterialProperty extends BaseMaterialProperty {
constructor(options) {
super(options);
const { Event, defaultValue } = Cesium;
if (!Object.getOwnPropertyDescriptor(VcCircleWaveMaterialProperty.prototype, "color")) {
Object.defineProperties(VcCircleWaveMaterialProperty.prototype, {
color: Cesium["createPropertyDescriptor"]("color")
});
}
this._definitionChanged = new Event();
this._color = new Cesium.ConstantProperty(options.color);
this._duration = defaultValue(options.duration, 1e3);
this.count = defaultValue(options.count, 2);
if (this.count <= 0) {
this.count = 1;
}
this._gradient = defaultValue(options.gradient, 0.1);
if (this._gradient === 0) {
this._gradient = 0;
}
if (this._gradient > 1) {
this._gradient = 1;
}
this._time = (/* @__PURE__ */ new Date()).getTime();
}
get isConstant() {
return false;
}
get definitionChanged() {
return this._definitionChanged;
}
get color() {
return this._color;
}
set color(value) {
const oldValue = this._color;
if (oldValue !== value) {
this._color = new Cesium.ConstantProperty(value);
this._definitionChanged.raiseEvent(this, "color", value, oldValue);
}
}
get duration() {
return this._duration;
}
set duration(value) {
const oldValue = this._duration;
if (oldValue !== value) {
this._duration = value;
this._definitionChanged.raiseEvent(this, "duration", value, oldValue);
}
}
get count() {
return this._count;
}
set count(value) {
const oldValue = this._count;
if (oldValue !== value) {
this._count = value;
this._definitionChanged.raiseEvent(this, "count", value, oldValue);
}
}
getType() {
return "VcCircleWave";
}
getValue(time, result) {
if (!Cesium.defined(result)) {
result = {};
}
result.color = Cesium.Property["getValueOrClonedDefault"](this._color, time, Cesium.Color.YELLOW, result.color);
result.time = ((/* @__PURE__ */ new Date()).getTime() - this._time) % this.duration / this.duration;
result.count = this.count;
result.gradient = 1 + 10 * (1 - this._gradient);
return result;
}
equals(other) {
const reData = this === other || other instanceof VcCircleWaveMaterialProperty && Cesium.Property["equals"](this._color, other._color);
return reData;
}
} exports('VcCircleWaveMaterialProperty', VcCircleWaveMaterialProperty);
class VcLineFlowMaterialProperty extends BaseMaterialProperty {
constructor(options = {}) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
super(options);
const { Color, Cartesian2, defined } = Cesium;
this.image = (_a = options.image) != null ? _a : options.url;
this.color = (_b = options.color) != null ? _b : new Color(1, 1, 1, 0);
this.axisY = (_c = options.axisY) != null ? _c : false;
this.mixt = (_d = options.mixt) != null ? _d : false;
this.speed = (_e = options.speed) != null ? _e : 10;
this.duration = options.duration;
this.repeat = (_f = options.repeat) != null ? _f : new Cartesian2(1, 1);
this.image2 = (_g = options.image2) != null ? _g : options.bgUrl;
this.color2 = (_i = (_h = options.color2) != null ? _h : options.bgColor) != null ? _i : new Color(1, 1, 1, 0);
this.hasImage2 = defined(this.image2);
this.globalAlpha = (_j = options.globalAlpha) != null ? _j : true;
}
getType(value) {
return "VcLineFlow";
}
getValue(time, result) {
const { Color, Cartesian2, defined } = Cesium;
!defined(result) && (result = {});
result.image = this.image;
result.color = getCesiumColor(this.color, new Color(1, 1, 1, 0), time);
result.repeat = getCesiumValue(this.repeat, Cartesian2, time);
result.axisY = this.axisY;
result.mixt = this.mixt;
result.speed = getCesiumValue(this.speed, Number, time);
if (this.duration) {
if (this._time === void 0) {
this._time = (/* @__PURE__ */ new Date()).getTime();
result.time = ((/* @__PURE__ */ new Date()).getTime() - this._time) / (this.duration * 1e3);
}
} else {
result.time = -1;
}
result.hasImage2 = this.hasImage2;
result.image2 = this.image2;
result.color2 = getCesiumColor(this.color2, new Color(1, 1, 1, 0), time);
result.globalAlpha = this.globalAlpha;
return result;
}
equals(other) {
const reData = this === other || other instanceof VcLineFlowMaterialProperty && Cesium.Property["equals"](this.color, other.color) && Cesium.Property["equals"](this.repeat, other.repeat) && this.image === other.image && this.axisY === other.axisY && this.speed === other.speed && this.hasImage2 === other.hasImage2 && this.image2 === other.image2 && this.image2 === other.image2 && Cesium.Property["equals"](this.color2, other.color2);
return reData;
}
} exports('VcLineFlowMaterialProperty', VcLineFlowMaterialProperty);
function makeCartesian2(val, isConstant = false) {
const { Cartesian2, CallbackProperty } = Cesium;
if (val instanceof Cesium.Cartesian2 || val instanceof CallbackProperty) {
return val;
}
if (isPlainObject(val)) {
if (hasOwn(val, "x") && hasOwn(val, "y")) {
const value = val;
return new Cartesian2(value.x, value.y);
}
}
if (isArray(val)) {
return new Cartesian2(val[0], val[1]);
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant);
}
return void 0;
}
function makeCartesian3(val, ellipsoid, isConstant = false) {
const {
CallbackProperty,
Cartesian3,
Ellipsoid,
SampledPositionProperty,
CompositePositionProperty,
ConstantPositionProperty,
TimeIntervalCollectionPositionProperty
} = Cesium;
if (val instanceof Cartesian3 || val instanceof CallbackProperty || val instanceof SampledPositionProperty || val instanceof CompositePositionProperty || val instanceof ConstantPositionProperty || val instanceof TimeIntervalCollectionPositionProperty) {
return val;
}
ellipsoid = ellipsoid || Ellipsoid.WGS84;
if (isPlainObject(val)) {
if (hasOwn(val, "x") && hasOwn(val, "y") && hasOwn(val, "z")) {
const value = val;
return new Cartesian3(value.x, value.y, value.z);
} else if (hasOwn(val, "lng") && hasOwn(val, "lat")) {
const value = val;
return Cartesian3.fromDegrees(value.lng, value.lat, value.height || 0, ellipsoid);
}
}
if (isArray(val)) {
return Cartesian3.fromDegrees(val[0], val[1], val[2] || 0, ellipsoid);
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant);
}
return void 0;
}
function makeCartesian3Array(vals, ellipsoid, isConstant = false) {
const { CallbackProperty, Cartesian3, Ellipsoid } = Cesium;
if (vals instanceof CallbackProperty) {
return vals;
}
if (isFunction(vals)) {
return new CallbackProperty(vals, isConstant);
}
ellipsoid = ellipsoid || Ellipsoid.WGS84;
if (isArray(vals)) {
if (isArray(vals[0]) || isPlainObject(vals[0])) {
const results = [];
vals.forEach((val) => {
results.push(makeCartesian3(val, ellipsoid));
});
return results;
}
return Cartesian3.fromDegreesArrayHeights(vals, ellipsoid);
}
return void 0;
}
function makeCartesian2Array(vals, isConstant) {
const { CallbackProperty } = Cesium;
if (vals instanceof CallbackProperty) {
return vals;
}
if (isFunction(vals)) {
return new CallbackProperty(vals, isConstant);
}
if (isArray(vals)) {
const points = [];
vals.forEach((val) => {
points.push(makeCartesian2(val));
});
return points;
}
return void 0;
}
function makeQuaternion(val, isConstant = false) {
const { CallbackProperty, Quaternion, VelocityOrientationProperty } = Cesium;
if (val instanceof Quaternion || val instanceof CallbackProperty || val instanceof VelocityOrientationProperty) {
return val;
}
if (isPlainObject(val) && hasOwn(val, "x") && hasOwn(val, "y")) {
const value = val;
return new Quaternion(value.x, value.y, value.z, value.w);
}
if (isArray(val)) {
return new Quaternion(val[0], val[1], val[2], val[3]);
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant);
}
return void 0;
}
function parsePolygonHierarchyJson(val, ellipsoid) {
val.forEach((item) => {
item.positions = makeCartesian3Array(item.positions, ellipsoid);
if (item.holes) {
parsePolygonHierarchyJson(item.holes, ellipsoid);
}
});
}
function makePolygonHierarchy(val, ellipsoid, isConstant = false) {
var _a;
const { PolygonHierarchy, CallbackProperty } = Cesium;
if (val instanceof PolygonHierarchy || val instanceof CallbackProperty) {
return val;
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant);
}
if (isArray(val) && val.length >= 3) {
const points = makeCartesian3Array(val, ellipsoid);
return new PolygonHierarchy(points);
}
if (isPlainObject(val) && hasOwn(val, "positions")) {
const value = val;
value.positions = makeCartesian3Array(value.positions, ellipsoid);
((_a = value.holes) == null ? void 0 : _a.length) && parsePolygonHierarchyJson(value.holes, ellipsoid);
return value;
}
return void 0;
}
function makeNearFarScalar(val, isConstant = false) {
const { NearFarScalar, CallbackProperty } = Cesium;
if (val instanceof NearFarScalar || val instanceof CallbackProperty) {
return val;
}
if (isPlainObject(val) && hasOwn(val, "near") && hasOwn(val, "far")) {
const value = val;
return new NearFarScalar(value.near, value.nearValue || 0, value.far, value.farValue || 1);
}
if (isArray(val)) {
return new NearFarScalar(val[0], val[1], val[2], val[3]);
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant);
}
return void 0;
}
function makeDistanceDisplayCondition(val, isConstant = false) {
const { DistanceDisplayCondition, CallbackProperty } = Cesium;
if (val instanceof DistanceDisplayCondition || val instanceof CallbackProperty) {
return val;
}
if (isPlainObject(val) && hasOwn(val, "near") && hasOwn(val, "far")) {
const value = val;
return new DistanceDisplayCondition(value.near, value.far);
}
if (isArray(val)) {
return new DistanceDisplayCondition(val[0], val[1]);
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant);
}
return void 0;
}
function makeColor(val, isConstant = false) {
const { Color, CallbackProperty, defaultValue } = Cesium;
if (val instanceof Color || val instanceof CallbackProperty) {
return val;
}
if (isString(val)) {
return Color.fromCssColorString(val);
}
if (isPlainObject(val)) {
if (hasOwn(val, "red")) {
const value = val;
return Color.fromBytes(
defaultValue(value.red, 255),
defaultValue(value.green, 255),
defaultValue(value.blue, 255),
defaultValue(value.alpha, 255)
);
} else if (hasOwn(val, "x")) {
const value = val;
return new Color(defaultValue(value.x, 1), defaultValue(value.y, 1), defaultValue(value.z, 1), defaultValue(value.w, 1));
}
}
if (isArray(val)) {
return Color.fromBytes(val[0], val[1], val[2], defaultValue(val[3], 255));
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant);
}
return void 0;
}
function makeColors(vals) {
if (isArray(vals)) {
const results = [];
vals.forEach((val) => {
results.push(makeColor(val));
});
return results;
} else {
return vals;
}
}
function makeMaterialProperty(val, isConstant = false) {
const {
CallbackProperty,
Color,
CheckerboardMaterialProperty,
ColorMaterialProperty,
CompositeMaterialProperty,
GridMaterialProperty,
ImageMaterialProperty,
MaterialProperty,
PolylineArrowMaterialProperty,
PolylineDashMaterialProperty,
PolylineGlowMaterialProperty,
PolylineOutlineMaterialProperty,
StripeMaterialProperty,
StripeOrientation,
defaultValue,
Cartesian2,
Material
} = Cesium;
if (val instanceof CallbackProperty || val instanceof Color || val instanceof CheckerboardMaterialProperty || val instanceof ColorMaterialProperty || val instanceof CompositeMaterialProperty || val instanceof GridMaterialProperty || val instanceof ImageMaterialProperty || val instanceof MaterialProperty || val instanceof PolylineArrowMaterialProperty || val instanceof PolylineDashMaterialProperty || val instanceof PolylineGlowMaterialProperty || val instanceof PolylineOutlineMaterialProperty || val instanceof StripeMaterialProperty || val instanceof VcCircleWaveMaterialProperty || val instanceof VcLineFlowMaterialProperty) {
return val;
}
if (isString(val) && /(.*)\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/.test(val) || val instanceof HTMLImageElement || val instanceof HTMLCanvasElement || val instanceof HTMLVideoElement) {
return new ImageMaterialProperty({
image: val,
repeat: makeCartesian2({ x: 1, y: 1 }),
color: Color.WHITE,
transparent: true
});
}
if (isArray(val) || isString(val)) {
return new ColorMaterialProperty(makeColor(val));
}
if (isPlainObject(val) && hasOwn(val, "fabric")) {
const value = val;
switch (value.fabric.type) {
case "Image":
return new ImageMaterialProperty({
image: value.fabric.uniforms.image,
repeat: makeCartesian2(defaultValue(value.fabric.uniforms.repeat, { x: 1, y: 1 })),
color: defaultValue(makeColor(value.fabric.uniforms.color), Color.WHITE),
transparent: defaultValue(value.fabric.uniforms.transparent, false)
});
case "Color":
return new ColorMaterialProperty(makeColor(defaultValue(value.fabric.uniforms.color, Color.WHITE)));
case "PolylineArrow":
return new PolylineArrowMaterialProperty(makeColor(defaultValue(value.fabric.uniforms.color, Color.WHITE)));
case "PolylineDash":
return new PolylineDashMaterialProperty({
color: makeColor(defaultValue(value.fabric.uniforms.color, "white")),
gapColor: makeColor(defaultValue(value.fabric.uniforms.gapColor, Color.TRANSPARENT)),
dashLength: defaultValue(value.fabric.uniforms.taperPower, 16),
dashPattern: defaultValue(value.fabric.uniforms.taperPower, 255)
});
case "PolylineGlow":
return new PolylineGlowMaterialProperty({
color: makeColor(defaultValue(value.fabric.uniforms.color, Color.WHITE)),
glowPower: defaultValue(value.fabric.uniforms.glowPower, 0.25),
taperPower: defaultValue(value.fabric.uniforms.taperPower, 1)
});
case "PolylineOutline":
return new PolylineOutlineMaterialProperty({
color: makeColor(defaultValue(value.fabric.uniforms.color, Color.WHITE)),
outlineColor: makeColor(defaultValue(value.fabric.uniforms.outlineColor, Color.BLACK)),
outlineWidth: defaultValue(value.fabric.uniforms.outlineWidth, 1)
});
case "Checkerboard":
return new CheckerboardMaterialProperty({
evenColor: makeColor(defaultValue(value.fabric.uniforms.evenColor, Color.WHITE)),
oddColor: makeColor(defaultValue(value.fabric.uniforms.oddColor, Color.BLACK)),
repeat: defaultValue(makeCartesian2(value.fabric.uniforms.repeat), { x: 2, y: 2 })
});
case "Grid":
return new GridMaterialProperty({
color: makeColor(defaultValue(value.fabric.uniforms.color, Color.WHITE)),
cellAlpha: defaultValue(value.fabric.uniforms.cellAlpha, 0.1),
lineCount: defaultValue(makeCartesian2(value.fabric.uniforms.lineCount), { x: 8, y: 8 }),
lineThickness: defaultValue(makeCartesian2(value.fabric.uniforms.lineThickness), { x: 1, y: 1 }),
lineOffset: defaultValue(makeCartesian2(value.fabric.uniforms.lineOffset), { x: 0, y: 0 })
});
case "Stripe":
return new StripeMaterialProperty({
orientation: defaultValue(value.fabric.uniforms.orientation, StripeOrientation.HORIZONTAL),
evenColor: makeColor(defaultValue(value.fabric.uniforms.evenColor, "white")),
oddColor: makeColor(defaultValue(value.fabric.uniforms.oddColor, "black")),
offset: defaultValue(value.fabric.uniforms.offset, 0),
repeat: defaultValue(value.fabric.uniforms.repeat, 1)
});
case "VcCircleWave": {
return new VcCircleWaveMaterialProperty({
duration: defaultValue(value.fabric.uniforms.duration, 3e3),
gradient: defaultValue(value.fabric.uniforms.gradient, 0.5),
color: makeColor(defaultValue(value.fabric.uniforms.color, Color.RED)),
count: defaultValue(value.fabric.uniforms.count, 3)
});
}
case "VcLineFlow": {
return new VcLineFlowMaterialProperty({
image: defaultValue(value.fabric.uniforms.image, Material.DefaultImageId),
color: makeColor(defaultValue(value.fabric.uniforms.color, new Color(1, 1, 1, 1))),
repeat: makeCartesian2(defaultValue(value.fabric.uniforms.repeat, new Cartesian2(1, 1))),
axisY: defaultValue(value.fabric.uniforms.axisY, false),
mixt: defaultValue(value.fabric.uniforms.mixt, false),
speed: defaultValue(value.fabric.uniforms.speed, 10),
time: defaultValue(value.fabric.uniforms.time, -1)
});
}
}
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant);
}
return val;
}
function makeMaterial(val) {
var _a;
const vcInstance = this;
const cmpName = (_a = vcInstance == null ? void 0 : vcInstance.proxy) == null ? void 0 : _a.$options.name;
if (cmpName && (cmpName.indexOf("Graphics") !== -1 || cmpName.indexOf("Datasource") !== -1 || cmpName === "VcOverlayDynamic" || cmpName === "VcEntity")) {
return makeMaterialProperty(val);
}
const { Material, combine } = Cesium;
if (val instanceof Material) {
return val;
}
if (isPlainObject(val) && hasOwn(val, "fabric")) {
const f = (obj) => {
for (const i in obj) {
if (!isArray(obj[i]) && isPlainObject(obj[i])) {
f(obj[i]);
} else {
if (i.toLocaleLowerCase().indexOf("color") !== -1 && !isEmptyObj(obj[i])) {
const result = makeColor(obj[i]);
obj[i] = combine(result, result, true);
}
}
}
};
f(val);
return new Material(val);
}
if (isArray(val) || isString(val)) {
const material = Material.fromType("Color");
material.uniforms.color = makeColor(val);
return material;
}
return void 0;
}
function makeAppearance(val) {
var _a;
const {
Appearance,
DebugAppearance,
MaterialAppearance,
PolylineColorAppearance,
EllipsoidSurfaceAppearance,
PerInstanceColorAppearance,
PolylineMaterialAppearance
} = Cesium;
if (val instanceof Appearance || val instanceof DebugAppearance || val instanceof MaterialAppearance || val instanceof PolylineColorAppearance || val instanceof EllipsoidSurfaceAppearance || val instanceof PerInstanceColorAppearance || val instanceof PolylineMaterialAppearance) {
return val;
}
if (isPlainObject(val) && hasOwn(val, "type")) {
const options = {
...val.options
};
if ((_a = val.options) == null ? void 0 : _a.material) {
options.material = makeMaterial.call(this, val.options.material);
}
return new Cesium[val.type]({
...options
});
}
return void 0;
}
function makeRectangle(val, isConstant = false) {
const { Rectangle, RectangleGraphics, CallbackProperty } = Cesium;
if (val instanceof RectangleGraphics || val instanceof Rectangle || val instanceof CallbackProperty) {
return val;
}
if (isArray(val)) {
return Rectangle.fromDegrees(val[0], val[1], val[2], val[3]);
}
if (isPlainObject(val)) {
if (hasOwn(val, "west")) {
const value = val;
return Rectangle.fromDegrees(value.west, value.south, value.east, value.north);
} else if (hasOwn(val, "x")) {
const value = val;
return new Rectangle(value.x, value.y, value.z, value.w);
}
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant);
}
return void 0;
}
function makeBoundingRectangle(val, isConstant = false) {
const { BoundingRectangle, CallbackProperty } = Cesium;
if (val instanceof BoundingRectangle || val instanceof CallbackProperty) {
return val;
}
if (isPlainObject(val) && hasOwn(val, "x")) {
const value = val;
return new BoundingRectangle(value.x, value.y, value.width, value.height);
}
if (isArray(val)) {
return new BoundingRectangle(val[0], val[1], val[2], val[3]);
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant);
}
return void 0;
}
function makePlane(val, isConstant = false) {
const { Cartesian3, Plane, PlaneGraphics, CallbackProperty } = Cesium;
if (val instanceof PlaneGraphics || val instanceof Plane || val instanceof CallbackProperty) {
return val;
}
if (isPlainObject(val) && hasOwn(val, "normal")) {
const value = val;
Cartesian3.normalize(makeCartesian3(value.normal), value.normal);
return new Plane(value.normal, value.distance);
}
if (isArray(val)) {
const point3D = makeCartesian3(val[0]);
const normalizePoint3D = Cartesian3.normalize(point3D, new Cartesian3());
return new Plane(normalizePoint3D, val[1]);
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant);
}
return void 0;
}
function makeTranslationRotationScale(val, isConstant = false) {
const { TranslationRotationScale, CallbackProperty } = Cesium;
if (val instanceof CallbackProperty || val instanceof TranslationRotationScale) {
return val;
}
if (isPlainObject(val) && hasOwn(val, "translation")) {
const value = val;
return new TranslationRotationScale(
makeCartesian3(value.translation),
makeQuaternion(value.rotation),
makeCartesian3(value.scale)
);
}
if (isArray(val)) {
return new TranslationRotationScale(
makeCartesian3(val[0]),
makeQuaternion(val[1]),
makeCartesian3(val[2])
);
}
if (isFunction(val)) {
return new CallbackProperty(val, isConstant);
}
return val;
}
function makeOptions(val) {
var _a;
const vcInstance = this;
const cmpName = (_a = vcInstance.proxy) == null ? void 0 : _a.$options.name;
const result = {};
switch (cmpName) {
case "VcDatasourceGeojson":
Object.assign(result, val);
result && result.markerColor && (result.markerColor = makeColor(result.markerColor));
result && result.stroke && (result.stroke = makeColor(result.stroke));
result && result.fill && (result.fill = makeColor(result.fill));
return result;
}
return val;
}
function captureScreenshot(viewer) {
const scene = viewer.scene;
const promise = new Promise((resolve, reject) => {
const removeCallback = viewer.scene.postRender.addEventListener(() => {
removeCallback();
try {
const cesiumCanvas = viewer.scene.canvas;
const canvas = cesiumCanvas;
resolve(canvas.toDataURL("image/png"));
} catch (e) {
reject(e);
}
});
});
scene.render(viewer.clock.currentTime);
return promise;
}
function makeCameraOptions(camera, ellipsoid) {
const { Math: CesiumMath, Rectangle, defaultValue } = Cesium;
let destination = void 0;
let orientation = {};
if (hasOwn(camera, "position")) {
const position = camera.position;
destination = makeCartesian3(position, ellipsoid);
if (hasOwn(position, "lng") && hasOwn(position, "lat") || isArray(position)) {
orientation = {
heading: CesiumMath.toRadians(defaultValue(camera.heading, 360)),
pitch: CesiumMath.toRadians(defaultValue(camera.pitch, -90)),
roll: CesiumMath.toRadians(defaultValue(camera.roll, 0))
};
} else {
orientation = {
heading: defaultValue(camera.heading, 2 * Math.PI),
pitch: defaultValue(camera.pitch, -Math.PI / 2),
roll: defaultValue(camera.roll, 0)
};
}
} else if (hasOwn(camera, "rectangle")) {
const rectangle = camera.rectangle;
destination = makeRectangle(rectangle);
Rectangle.validate(destination);
if (hasOwn(rectangle, "west") && hasOwn(rectangle, "south") && hasOwn(rectangle, "east") && hasOwn(rectangle, "north") || isArray(rectangle)) {
orientation = {
heading: CesiumMath.toRadians(defaultValue(camera.heading, 360)),
pitch: CesiumMath.toRadians(defaultValue(camera.pitch, -90)),
roll: CesiumMath.toRadians(defaultValue(camera.roll, 0))
};
} else {
orientation = {
heading: defaultValue(camera.heading, 2 * Math.PI),
pitch: defaultValue(camera.pitch, -Math.PI / 2),
roll: defaultValue(camera.roll, 0)
};
}
}
return {
destination,
orientation
};
}
function setViewerCamera(viewer, camera) {
const { destination, orientation } = makeCameraOptions(camera, viewer.scene.globe.ellipsoid);
viewer.camera.setView({
destination,
orientation
});
}
function flyToCamera(viewer, cameraOpts, options) {
const { destination, orientation } = makeCameraOptions(cameraOpts, viewer.scene.globe.ellipsoid);
viewer.camera.flyTo({
...options,
destination: (options == null ? void 0 : options.destination) || destination,
orientation: (options == null ? void 0 : options.orientation) || orientation
});
}
function getGeodesicDistance(start, end, ellipsoid) {
const { EllipsoidGeodesic, Ellipsoid } = Cesium;
ellipsoid = ellipsoid || Ellipsoid.WGS84;
const pickedPointCartographic = ellipsoid.cartesianToCartographic(start);
const lastPointCartographic = ellipsoid.cartesianToCartographic(end);
const geodesic = new EllipsoidGeodesic(pickedPointCartographic, lastPointCartographic);
return geodesic.surfaceDistance;
}
function getHeadingPitchRoll(start, end, scene, result) {
const { Cartesian3 } = Cesium;
if (Cartesian3.equals(start, end)) {
return void 0;
}
const vector2 = Cesium.Cartesian3.subtract(end, start, new Cesium.Cartesian3());
const normal = Cesium.Cartesian3.normalize(vector2, new Cesium.Cartesian3());
const rotationMatrix3 = Cesium.Transforms.rotationMatrixFromPositionVelocity(start, normal, scene.globe.ellipsoid);
const m = Cesium.Matrix4.fromRotationTranslation(rotationMatrix3, start);
const m1 = Cesium.Transforms.eastNorthUpToFixedFrame(
Cesium.Matrix4.getTranslation(m, new Cesium.Cartesian3()),
Cesium.Ellipsoid.WGS84,
new Cesium.Matrix4()
);
const m3 = Cesium.Matrix4.multiply(Cesium.Matrix4.inverse(m1, new Cesium.Matrix4()), m, new Cesium.Matrix4());
const mat3 = Cesium.Matrix4.getMatrix3(m3, new Cesium.Matrix3());
const q = Cesium.Quaternion.fromRotationMatrix(mat3);
const hpr = Cesium.HeadingPitchRoll.fromQuaternion(q);
return hpr;
}
function getPolylineSegmentEndpoint(start, heading, distance, ellipsoid) {
const { HeadingPitchRoll, Transforms, Matrix4, Cartesian3, Cartesian4, Quaternion, Cartographic, Ellipsoid } = Cesium;
ellipsoid = ellipsoid || Ellipsoid.WGS84;
const hpr = new HeadingPitchRoll(heading, 0, 0);
const scale = new Cartesian3(1, 1, 1);
const matrix = Transforms.headingPitchRollToFixedFrame(start, hpr);
const translation = Matrix4.getColumn(matrix, 1, new Cartesian4());
const axis = new Cartesian3(translation.x, translation.y, translation.z);
const quaternion = Quaternion.fromAxisAngle(axis, distance * ellipsoid.oneOverRadii.x);
const hprMatrix = Matrix4.fromTranslationQuaternionRotationScale(Cartesian3.ZERO, quaternion, scale);
const position = Matrix4.multiplyByPoint(hprMatrix, start, new Cartesian3());
const startCartographic = Cartographic.fromCartesian(start, ellipsoid);
const positionCartographic = Cartographic.fromCartesian(position, ellipsoid);
positionCartographic.height = startCartographic.height;
return Cartographic.toCartesian(positionCartographic, ellipsoid);
}
function calculateAreaByPostions(positions) {
let area = 0;
const { CoplanarPolygonGeometry, VertexFormat, defined, Cartesian3 } = Cesium;
const geometry = CoplanarPolygonGeometry.createGeometry(
CoplanarPolygonGeometry.fromPositions({
positions,
vertexFormat: VertexFormat.POSITION_ONLY
})
);
if (!isUndefined(geometry) && defined(geometry)) {
const indices = geometry.indices;
const positionValues = geometry.attributes.position.values;
for (let i = 0; i < indices.length; i += 3) {
const indice0 = indices[i];
const indice1 = indices[i + 1];
const indice2 = indices[i + 2];
area += triangleArea(
Cartesian3.unpack(positionValues, 3 * indice0, {}),
Cartesian3.unpack(positionValues, 3 * indice1, {}),
Cartesian3.unpack(positionValues, 3 * indice2, {})
);
}
}
return area;
}
const triangleArea = (vertexA, vertexB, vertexC) => {
const { Cartesian3 } = Cesium;
const vectorBA = Cartesian3.subtract(vertexA, vertexB, {});
const vectorBC = Cartesian3.subtract(vertexC, vertexB, {});
const crossProduct = Cartesian3.cross(vectorBA, vectorBC, vectorBA);
return 0.5 * Cartesian3.magnitude(crossProduct);
};
function makeJulianDate(val) {
const { JulianDate } = Cesium;
if (val instanceof JulianDate) {
return val;
} else if (isString(val)) {
return Cesium.JulianDate.fromDate(new Date(val));
} else if (val instanceof Date) {
return Cesium.JulianDate.fromDate(val);
}
return Cesium.JulianDate.now();
}
function makeHeadingPitchRang(val) {
const { HeadingPitchRange, Math: CesiumMath } = Cesium;
if (val instanceof Cesium.HeadingPitchRange) {
return val;
} else if (Array.isArray(val)) {
return new HeadingPitchRange(CesiumMath.toRadians(val[0]) || 0, CesiumMath.toRadians(val[1]) || 0, val[2] || 0);
} else if (isPlainObject(val)) {
return new HeadingPitchRange(val.heading || 0, val.pitch || 0, val.range || 0);
}
return new HeadingPitchRange();
}
function getPolylineSegmentHeading(start, end) {
const { Cartesian3, Matrix4, Transforms, Math: CesiumMath } = Cesium;
const cartesian3Scratch = new Cartesian3();
const matrix4Scratch = Transforms.eastNorthUpToFixedFrame(start);
Matrix4.inverse(matrix4Scratch, matrix4Scratch);
Matrix4.multiplyByPoint(matrix4Scratch, end, cartesian3Scratch);
Cartesian3.normalize(cartesian3Scratch, cartesian3Scratch);
return CesiumMath.toDegrees(Math.atan2(cartesian3Scratch.x, cartesian3Scratch.y));
}
function getPolylineSegmentPitch(start, end) {
const { Cartesian3, Matrix4, Transforms, Math: CesiumMath } = Cesium;
const cartesian3Scratch = new Cartesian3();
const matrix4Scratch = Transforms.eastNorthUpToFixedFrame(start);
Matrix4.inverse(matrix4Scratch, matrix4Scratch);
Matrix4.multiplyByPoint(matrix4Scratch, end, cartesian3Scratch);
Cartesian3.normalize(cartesian3Scratch, cartesian3Scratch);
return CesiumMath.toDegrees(Math.asin(cartesian3Scratch.z));
}
function getFirstIntersection(start, end, viewer, objectsToExclude = []) {
const { Cartesian3, Ray, defined } = Cesium;
const direction = Cartesian3.normalize(Cartesian3.subtract(end, start, new Cartesian3()), new Cartesian3());
const ray = new Ray(start, direction);
const result = viewer.scene.pickFromRay(ray, objectsToExclude);
if (defined(result)) {
if (defined(result.position)) {
const intersection = result.position;
return intersection;
}
}
return void 0;
}
function heightToLevel(altitude) {
const A = 40487.57;
const B = 7096758e-11;
const C = 91610.74;
const D = -40467.74;
return Math.round(D + (A - D) / (1 + Math.pow(altitude / C, B)));
}
function compareCesiumVersion(a, b, operator = ">=") {
return compare(a, b, operator);
}
function makeImageBasedLighting(options) {
const { ImageBasedLighting, defined } = Cesium;
if (options instanceof Cesium.ImageBasedLighting) {
return options;
}
const imageBasedLighting = new ImageBasedLighting();
if (imageBasedLighting.imageBasedLightingFactor) {
imageBasedLighting.imageBasedLightingFactor = makeCartesian2(options.imageBasedLightingFactor);
}
if (imageBasedLighting.sphericalHarmonicCoefficients) {
imageBasedLighting.sphericalHarmonicCoefficients = makeCartesian3Array(options.sphericalHarmonicCoefficients);
}
if (imageBasedLighting.luminanceAtZenith) {
imageBasedLighting.luminanceAtZenith = Number(options.luminanceAtZenith);
}
if (defined(imageBasedLighting.specularEnvironmentMaps)) {
imageBasedLighting.specularEnvironmentMaps = options.specularEnvironmentMaps;
}
return imageBasedLighting;
}
const position$1 = {
/**
* A Property specifying the entity position.
*/
position: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeCartesian3,
deep: true
// 在 use-common 中已将 SampledPositionProperty 类型的 deep 设为 false
}
}
};
const viewFrom = {
/**
* A suggested initial offset for viewing this object.
*/
viewFrom: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeCartesian3,
deep: true
}
}
};
const orientation = {
orientation: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeQuaternion
}
}
};
const alignedAxis = {
alignedAxis: {
type: [Object, Array, Function],
default: () => {
return {
x: 0,
y: 0,
z: 0
};
},
watcherOptions: {
cesiumObjectBuilder: makeCartesian3
}
}
};
const color = {
color: {
type: [Object, String, Array, Function],
default: "white",
watcherOptions: {
cesiumObjectBuilder: makeColor
}
}
};
const depthFailColor = {
depthFailColor: {
type: [Object, String, Array, Function],
default: "white",
watcherOptions: {
cesiumObjectBuilder: makeColor
}
}
};
const disableDepthTestDistance = {
disableDepthTestDistance: [Number, Object, Function]
};
const distanceDisplayCondition = {
distanceDisplayCondition: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeDistanceDisplayCondition
}
}
};
const eyeOffset = {
eyeOffset: {
type: [Object, Array, Function],
default: () => {
return {
x: 0,
y: 0,
z: 0
};
},
watcherOptions: {
cesiumObjectBuilder: makeCartesian3
}
}
};
const height = {
height: [Number, Object, Function]
};
const heightReference = {
heightReference: {
type: [Number, Object, Function]
// default: 0
}
};
const horizontalOrigin = {
horizontalOrigin: {
type: [Number, Object, Function],
default: 0
}
};
const image = {
image: [String, Object, HTMLCanvasElement, Function]
};
const imageSubRegion = {
imageSubRegion: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeBoundingRectangle
}
}
};
const pixelOffset = {
pixelOffset: {
type: [Object, Array, Function],
default: () => {
return {
x: 0,
y: 0
};
},
validator: (v) => {
if (isArray(v)) {
return v.length === 2;
}
if (isObject(v)) {
return hasOwn(v, "x") && hasOwn(v, "y");
}
if (isFunction(v)) {
return true;
}
return false;
},
watcherOptions: {
cesiumObjectBuilder: makeCartesian2
}
}
};
const pixelOffsetScaleByDistance = {
pixelOffsetScaleByDistance: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeNearFarScalar
}
}
};
const rotation = {
rotation: {
type: [Number, Object, Function],
default: 0
}
};
const scale = {
scale: {
type: [Number, Object, Function],
default: 1
}
};
const scaleByDistance = {
scaleByDistance: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeNearFarScalar
}
}
};
const show = {
show: {
type: [Boolean, Object, Function],
default: true
}
};
const sizeInMeters = {
sizeInMeters: {
type: [Boolean, Object, Function],
default: false
}
};
const translucencyByDistance = {
translucencyByDistance: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeNearFarScalar
}
}
};
const verticalOrigin = {
verticalOrigin: {
type: [Number, Object, Function],
default: 0
}
};
const width = {
width: [Number, Object, Function]
};
const dimensions = {
dimensions: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeCartesian3
}
}
};
const fill = {
fill: {
type: [Boolean, Object, Function],
default: true
}
};
const material = {
material: {
type: [Object, String, Array, Function],
default: "white",
watcherOptions: {
cesiumObjectBuilder: makeMaterial
}
}
};
const outline = {
outline: {
type: [Boolean, Object, Function],
default: false
}
};
const outlineColor = {
outlineColor: {
type: [Object, String, Array, Function],
default: "black",
watcherOptions: {
cesiumObjectBuilder: makeColor
}
}
};
const outlineWidth = {
outlineWidth: {
type: [Number, Object, Function],
default: 1
}
};
const shadows = {
shadows: [Number, Object, Function]
};
const positions = {
positions: {
type: [Array, Object, Function],
watcherOptions: {
cesiumObjectBuilder: makeCartesian3Array,
exclude: "_callback",
deep: true
}
}
};
const extrudedHeight = {
extrudedHeight: [Number, Object, Function]
};
const extrudedHeightReference = {
extrudedHeightReference: [Number, Object, Function]
};
const cornerType = {
cornerType: {
type: [Number, Object, Function],
default: 0
}
};
const granularity = {
granularity: [Number, Object, Function]
};
const classificationType = {
classificationType: {
type: [Number, Object, Function]
}
};
const zIndex = {
zIndex: [Number, Object, Function]
};
const length = {
length: [Number, Object, Function]
};
const topRadius = {
topRadius: [Number, Object, Function]
};
const bottomRadius = {
bottomRadius: [Number, Object, Function]
};
const numberOfVerticalLines = {
numberOfVerticalLines: {
type: [Number, Object, Function],
default: 16
}
};
const slices = {
slices: {
type: [Number, Object, Function],
default: 128
}
};
const semiMajorAxis = {
semiMajorAxis: [Number, Object, Function]
};
const semiMinorAxis = {
semiMinorAxis: [Number, Object, Function]
};
const stRotation = {
stRotation: {
type: [Number, Object, Function],
default: 0
}
};
const radii = {
radii: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeCartesian3
}
}
};
const innerRadii = {
innerRadii: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeCartesian3
}
}
};
const minimumClock = {
minimumClock: {
type: [Number, Object, Function],
default: 0
}
};
const maximumClock = {
maximumClock: {
type: [Number, Object, Function],
default: 2 * Math.PI
}
};
const minimumCone = {
minimumCone: {
type: [Number, Object, Function],
default: 0
}
};
const maximumCone = {
maximumCone: {
type: [Number, Object, Function],
default: Math.PI
}
};
const stackPartitions = {
stackPartitions: {
type: [Number, Object, Function],
default: 64
}
};
const slicePartitions = {
slicePartitions: {
type: [Number, Object, Function],
default: 64
}
};
const subdivisions = {
subdivisions: {
type: [Number, Object, Function],
default: 128
}
};
const text$7 = {
text: [String, Object, Function]
};
const font = {
font: {
type: [String, Object, Function],
default: "30px sans-serif"
}
};
const labelStyle = {
labelStyle: {
type: [Number, Object, Function],
default: 0
}
};
const showBackground = {
showBackground: {
type: [Boolean, Object, Function],
default: false
}
};
const backgroundColor = {
backgroundColor: {
type: [Object, String, Array, Function],
default: () => {
return { x: 0.165, y: 0.165, z: 0.165, w: 0.8 };
},
watcherOptions: {
cesiumObjectBuilder: makeColor
}
}
};
const backgroundPadding = {
backgroundPadding: {
type: [Object, Array, Function],
default: () => {
return { x: 7, y: 5 };
},
watcherOptions: {
cesiumObjectBuilder: makeCartesian2
}
}
};
const fillColor = {
fillColor: {
type: [Object, String, Array, Function],
default: "white",
watcherOptions: {
cesiumObjectBuilder: makeColor
}
}
};
const uri = {
uri: [String, Object, Function]
};
const minimumPixelSize = {
minimumPixelSize: {
type: [Number, Object, Function],
default: 0
}
};
const maximumScale = {
maximumScale: [Number, Object, Function]
};
const incrementallyLoadTextures = {
incrementallyLoadTextures: {
type: [Boolean, Object, Function],
default: true
}
};
const runAnimations = {
clampAnimations: {
type: [Boolean, Object, Function],
default: true
}
};
const clampAnimations = {
clampAnimations: {
type: [Boolean, Object, Function],
default: true
}
};
const silhouetteColor = {
silhouetteColor: {
type: [Object, String, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeColor
}
}
};
const silhouetteSize = {
silhouetteSize: {
type: [Number, Object, Function],
default: 0
}
};
const colorBlendMode = {
colorBlendMode: {
type: [Number, Object, Function],
default: 0
}
};
const colorBlendAmount = {
colorBlendAmount: {
type: [Number, Object, Function],
default: 0.5
}
};
const imageBasedLightingFactor = {
imageBasedLightingFactor: {
type: [Object, Array, Function],
default: () => [1, 1],
watcherOptions: {
cesiumObjectBuilder: makeCartesian2
}
}
};
const lightColor = {
lightColor: {
type: [Object, String, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeColor
}
}
};
const nodeTransformations = {
nodeTransformations: {
type: [Object, Function],
watcherOptions: {
cesiumObjectBuilder: makeTranslationRotationScale
}
}
};
const articulations = {
articulations: [Object, Function]
};
const clippingPlanes = {
clippingPlanes: [Object, Function]
};
const plane = {
plane: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makePlane
}
}
};
const pixelSize = {
pixelSize: {
type: [Number, Object, Function],
default: 1
}
};
const hierarchy = {
hierarchy: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makePolygonHierarchy,
deep: true,
exclude: "_callback"
}
}
};
const perPositionHeight = {
perPositionHeight: {
type: [Boolean, Object, Function],
default: false
}
};
const closeTop = {
closeTop: {
type: [Boolean, Object, Function],
default: true
}
};
const closeBottom = {
closeBottom: {
type: [Boolean, Object, Function],
default: true
}
};
const arcType = {
arcType: {
type: [Number, Object, Function],
default: 1
}
};
const depthFailMaterial = {
depthFailMaterial: {
type: [Object, String, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeMaterial
}
}
};
const clampToGround = {
clampToGround: {
type: [Boolean, Object, Function],
default: false
}
};
const shape = {
shape: {
type: [Array, Object, Function],
watcherOptions: {
cesiumObjectBuilder: makeCartesian2Array
}
}
};
const coordinates = {
coordinates: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeRectangle
}
}
};
const maximumScreenSpaceError = {
maximumScreenSpaceError: {
type: [Number, Object, Function],
default: 16
}
};
const minimumHeights = {
minimumHeights: [Array, Object, Function]
};
const maximumHeights = {
maximumHeights: [Array, Object, Function]
};
const cutoutRectangle = {
cutoutRectangle: {
type: [Object, Array],
watcherOptions: {
cesiumObjectBuilder: makeRectangle
}
}
};
const colorToAlpha = {
colorToAlpha: {
type: [Object, String, Array],
watcherOptions: {
cesiumObjectBuilder: makeColor
}
}
};
const url = {
url: [String, Object]
};
const token = {
token: String
};
const tileDiscardPolicy = {
tileDiscardPolicy: Object
};
const layers = {
layers: String
};
const enablePickFeatures = {
enablePickFeatures: {
type: Boolean,
default: true
}
};
const rectangle = {
rectangle: {
type: [Object, Array],
watcherOptions: {
cesiumObjectBuilder: makeRectangle
}
}
};
const tilingScheme = {
tilingScheme: Object
};
const ellipsoid = {
ellipsoid: Object
};
const credit = {
credit: {
type: [String, Object],
default: ""
}
};
const tileWidth = {
tileWidth: {
type: Number,
default: 256
}
};
const tileHeight = {
tileHeight: {
type: Number,
default: 256
}
};
const maximumLevel = {
maximumLevel: Number
};
const minimumLevel = {
minimumLevel: {
type: Number,
default: 0
}
};
const fileExtension = {
fileExtension: {
type: String,
default: "png"
}
};
const accessToken = {
accessToken: String
};
const format = {
format: {
type: String,
default: "png"
}
};
const subdomains = {
subdomains: [String, Array]
};
const getFeatureInfoFormats = {
getFeatureInfoFormats: Array
};
const clock = {
clock: Object
};
const times = {
times: Object
};
const projectionTransforms = {
projectionTransforms: {
type: [Boolean, Object],
default: false
}
};
const customShader = {
customShader: {
type: Object
}
};
const maximumMemoryUsage = {
maximumMemoryUsage: {
type: Number,
default: 256
}
};
const defaultColor = {
defaultColor: {
type: [Object, String, Array],
watcherOptions: {
cesiumObjectBuilder: makeColor
}
}
};
const tileStyle = {
tileStyle: {
type: Object
}
};
const allowPicking = {
allowPicking: {
type: Boolean,
default: true
}
};
const asynchronous = {
asynchronous: {
type: Boolean,
default: true
}
};
const debugShowShadowVolume = {
debugShowShadowVolume: {
type: Boolean,
default: false
}
};
const releaseGeometryInstances = {
releaseGeometryInstances: {
type: Boolean,
default: true
}
};
const interleave = {
interleave: {
type: Boolean,
default: false
}
};
const appearance = {
appearance: {
type: Object,
watcherOptions: {
cesiumObjectBuilder: makeAppearance,
deep: true
// 在 use-common 中已将 CesiumAppearance 类型的 deep 设为 false
}
}
};
const depthFailAppearance = {
depthFailAppearance: {
type: Object,
watcherOptions: {
cesiumObjectBuilder: makeAppearance,
deep: true
}
}
};
const geometryInstances = {
geometryInstances: [Array, Object]
};
const vertexCacheOptimize = {
vertexCacheOptimize: {
type: Boolean,
default: false
}
};
const compressVertices = {
compressVertices: {
type: Boolean,
default: true
}
};
const modelMatrix = {
modelMatrix: Object
};
const debugShowBoundingVolume = {
debugShowBoundingVolume: {
tyep: Boolean,
default: false
}
};
const scene = {
scene: Object
};
const blendOption = {
blendOption: {
type: Number,
default: 2
}
};
const id = {
id: null
};
const loop = {
loop: {
type: Boolean,
default: false
}
};
const debugWireframe = {
debugWireframe: {
type: Boolean,
default: false
}
};
const vertexFormat = {
vertexFormat: Object
};
const center = {
/**
* center
*/
center: {
type: [Object, Array],
watcherOptions: {
cesiumObjectBuilder: makeCartesian3
}
}
};
const radius = {
radius: Number
};
const frustum = {
frustum: Object
};
const origin = {
origin: {
type: [Object, Array],
watcherOptions: {
cesiumObjectBuilder: makeCartesian3
}
}
};
const polygonHierarchy = {
polygonHierarchy: {
type: [Object, Array],
watcherOptions: {
cesiumObjectBuilder: makePolygonHierarchy,
deep: true
}
}
};
const startColor = {
startColor: {
type: [Object, String, Array],
watcherOptions: {
cesiumObjectBuilder: makeColor
}
}
};
const endColor = {
endColor: {
type: [Object, String, Array],
watcherOptions: {
cesiumObjectBuilder: makeColor
}
}
};
const minimumImageSize = {
minimumImageSize: {
type: [Object, Array],
watcherOptions: {
cesiumObjectBuilder: makeCartesian2
}
}
};
const maximumImageSize = {
maximumImageSize: {
type: [Object, Array],
watcherOptions: {
cesiumObjectBuilder: makeCartesian2
}
}
};
const imageSize = {
imageSize: {
type: [Object, Array],
watcherOptions: {
cesiumObjectBuilder: makeCartesian2
}
}
};
const shapePositions = {
shapePositions: {
type: Array,
watcherOptions: {
cesiumObjectBuilder: makeCartesian2Array,
deep: true
}
}
};
const polylinePositions = {
polylinePositions: {
type: Array,
watcherOptions: {
cesiumObjectBuilder: makeCartesian3Array,
deep: true
}
}
};
const lightColor2 = {
lightColor: {
type: [Object, Array],
watcherOptions: {
cesiumObjectBuilder: makeCartesian3
}
}
};
const luminanceAtZenith = {
luminanceAtZenith: {
type: Number,
default: 0.2
}
};
const sphericalHarmonicCoefficients = {
sphericalHarmonicCoefficients: {
type: [Array, Object],
watcherOptions: {
cesiumObjectBuilder: makeCartesian3Array
}
}
};
const specularEnvironmentMaps = {
specularEnvironmentMaps: String
};
const imageBasedLighting = {
imageBasedLighting: {
type: Object,
watcherOptions: {
cesiumObjectBuilder: makeImageBasedLighting
}
}
};
const backFaceCulling = {
backFaceCulling: {
type: Boolean,
default: true
}
};
const colors = {
colors: {
type: Array,
watcherOptions: {
cesiumObjectBuilder: makeColors,
deep: true
}
}
};
const data = {
data: {
type: [String, Object],
required: true
}
};
const sourceUri = {
sourceUri: {
type: [String, Object]
}
};
const options = {
options: {
type: Object,
watcherOptions: {
cesiumObjectBuilder: makeOptions,
deep: true
}
}
};
const glowColor = {
glowColor: {
type: [String, Array, Object],
default: () => [0, 1, 0, 0.05],
watcherOptions: {
cesiumObjectBuilder: makeColor
}
}
};
const clearColor = {
clearColor: {
type: [String, Array, Object],
watcherOptions: {
cesiumObjectBuilder: makeColor
}
}
};
const scissorRectangle = {
scissorRectangle: {
type: [Object, Array],
watcherOptions: {
cesiumObjectBuilder: makeBoundingRectangle
}
}
};
const enableMouseEvent = {
enableMouseEvent: {
type: Boolean,
default: true
}
};
var cesiumProps = /*#__PURE__*/Object.freeze({
__proto__: null,
customShader: customShader,
maximumMemoryUsage: maximumMemoryUsage,
tileStyle: tileStyle,
defaultColor: defaultColor,
viewFrom: viewFrom,
projectionTransforms: projectionTransforms,
sourceUri: sourceUri,
colors: colors,
enableMouseEvent: enableMouseEvent,
backFaceCulling: backFaceCulling,
imageBasedLighting: imageBasedLighting,
specularEnvironmentMaps: specularEnvironmentMaps,
sphericalHarmonicCoefficients: sphericalHarmonicCoefficients,
luminanceAtZenith: luminanceAtZenith,
maximumScreenSpaceError: maximumScreenSpaceError,
runAnimations: runAnimations,
articulations: articulations,
scissorRectangle: scissorRectangle,
clearColor: clearColor,
glowColor: glowColor,
options: options,
data: data,
imageSubRegion: imageSubRegion,
coordinates: coordinates,
nodeTransformations: nodeTransformations,
hierarchy: hierarchy,
plane: plane,
colorToAlpha: colorToAlpha,
cutoutRectangle: cutoutRectangle,
polylinePositions: polylinePositions,
shapePositions: shapePositions,
imageSize: imageSize,
maximumImageSize: maximumImageSize,
minimumImageSize: minimumImageSize,
endColor: endColor,
startColor: startColor,
shape: shape,
lightColor: lightColor,
lightColor2: lightColor2,
imageBasedLightingFactor: imageBasedLightingFactor,
polygonHierarchy: polygonHierarchy,
orientation: orientation,
origin: origin,
frustum: frustum,
maximumCone: maximumCone,
minimumCone: minimumCone,
maximumClock: maximumClock,
minimumClock: minimumClock,
innerRadii: innerRadii,
radius: radius,
center: center,
debugWireframe: debugWireframe,
vertexFormat: vertexFormat,
position: position$1,
loop: loop,
geometryInstances: geometryInstances,
depthFailAppearance: depthFailAppearance,
appearance: appearance,
interleave: interleave,
releaseGeometryInstances: releaseGeometryInstances,
debugShowShadowVolume: debugShowShadowVolume,
id: id,
allowPicking: allowPicking,
asynchronous: asynchronous,
vertexCacheOptimize: vertexCacheOptimize,
compressVertices: compressVertices,
modelMatrix: modelMatrix,
debugShowBoundingVolume: debugShowBoundingVolume,
scene: scene,
blendOption: blendOption,
maximumHeights: maximumHeights,
minimumHeights: minimumHeights,
arcType: arcType,
clampToGround: clampToGround,
closeBottom: closeBottom,
closeTop: closeTop,
perPositionHeight: perPositionHeight,
pixelSize: pixelSize,
clippingPlanes: clippingPlanes,
colorBlendAmount: colorBlendAmount,
colorBlendMode: colorBlendMode,
silhouetteSize: silhouetteSize,
silhouetteColor: silhouetteColor,
clampAnimations: clampAnimations,
incrementallyLoadTextures: incrementallyLoadTextures,
maximumScale: maximumScale,
minimumPixelSize: minimumPixelSize,
uri: uri,
fillColor: fillColor,
backgroundPadding: backgroundPadding,
backgroundColor: backgroundColor,
showBackground: showBackground,
labelStyle: labelStyle,
font: font,
text: text$7,
subdivisions: subdivisions,
slicePartitions: slicePartitions,
stackPartitions: stackPartitions,
radii: radii,
stRotation: stRotation,
semiMinorAxis: semiMinorAxis,
semiMajorAxis: semiMajorAxis,
slices: slices,
numberOfVerticalLines: numberOfVerticalLines,
bottomRadius: bottomRadius,
topRadius: topRadius,
length: length,
zIndex: zIndex,
classificationType: classificationType,
granularity: granularity,
cornerType: cornerType,
extrudedHeightReference: extrudedHeightReference,
extrudedHeight: extrudedHeight,
positions: positions,
image: image,
scale: scale,
pixelOffset: pixelOffset,
eyeOffset: eyeOffset,
horizontalOrigin: horizontalOrigin,
verticalOrigin: verticalOrigin,
heightReference: heightReference,
depthFailColor: depthFailColor,
color: color,
rotation: rotation,
alignedAxis: alignedAxis,
sizeInMeters: sizeInMeters,
width: width,
height: height,
scaleByDistance: scaleByDistance,
translucencyByDistance: translucencyByDistance,
pixelOffsetScaleByDistance: pixelOffsetScaleByDistance,
disableDepthTestDistance: disableDepthTestDistance,
dimensions: dimensions,
fill: fill,
depthFailMaterial: depthFailMaterial,
material: material,
outline: outline,
outlineColor: outlineColor,
outlineWidth: outlineWidth,
shadows: shadows,
distanceDisplayCondition: distanceDisplayCondition,
show: show,
times: times,
clock: clock,
getFeatureInfoFormats: getFeatureInfoFormats,
subdomains: subdomains,
format: format,
accessToken: accessToken,
fileExtension: fileExtension,
minimumLevel: minimumLevel,
maximumLevel: maximumLevel,
tileHeight: tileHeight,
url: url,
token: token,
tileDiscardPolicy: tileDiscardPolicy,
layers: layers,
enablePickFeatures: enablePickFeatures,
rectangle: rectangle,
tilingScheme: tilingScheme,
ellipsoid: ellipsoid,
credit: credit,
tileWidth: tileWidth
});
var Chinese = {
name: "zh-hans",
nativeName: "\u4E2D\u6587(\u7B80\u4F53)",
vc: {
loadError: "\u52A0\u8F7D\u5931\u8D25\uFF0C\u5FC5\u987B\u4F5C\u4E3A VcViewer \u7684\u5B50\u7EC4\u4EF6\u52A0\u8F7D\u3002",
navigation: {
compass: {
outerTip: "\u65CB\u8F6C\u89C6\u56FE\uFF1A\u987A/\u9006\u65F6\u9488\u65B9\u5411\u62D6\u62FD\u7F57\u76D8\u5916\u73AF\u3002\n\u91CD\u7F6E\u89C6\u56FE\uFF1A\u53CC\u51FB\u7F57\u76D8\u5916\u73AF\u3002",
innerTip: "\u7FFB\u8F6C\u89C6\u56FE\uFF1A\u7531\u5185\u73AF\u5411\u5916\u73AF\u62D6\u62FD\u7F57\u76D8\u3002\n \u6216\u8005\u6309\u4F4F Ctrl \u952E\u7684\u540C\u65F6\u62D6\u62FD\u5730\u56FE\u3002",
title: "\u6309\u4F4F\u9F20\u6807\u62D6\u62FD\u65CB\u8F6C\u76F8\u673A\u3002"
},
zoomCotrol: {
zoomInTip: "\u653E\u5927",
zoomResetTip: "\u91CD\u7F6E\u89C6\u56FE",
zoomOutTip: "\u7F29\u5C0F"
},
print: {
printTip: "\u573A\u666F\u622A\u56FE/\u6253\u5370",
printViewTitle: "\u6253\u5370\u9884\u89C8",
credit: "\u5730\u56FE\u7248\u6743",
screenshot: "\u573A\u666F\u622A\u56FE"
},
myLocation: {
myLocationTip: "\u5B9A\u4F4D\u60A8\u7684\u4F4D\u7F6E",
positioning: "\u5B9A\u4F4D\u4E2D...",
fail: "\u5B9A\u4F4D\u5931\u8D25",
centreMap: "\u6211\u7684\u4F4D\u7F6E",
lat: "\u7EAC\u5EA6",
lng: "\u7ECF\u5EA6",
address: "\u5730\u5740"
},
statusBar: {
lat: "\u7EAC\u5EA6",
lng: "\u7ECF\u5EA6",
zone: "\u5E26\u53F7",
e: "X",
n: "Y",
elev: "\u9AD8\u7A0B",
level: "\u5C42\u7EA7",
heading: "\u65B9\u4F4D",
pitch: "\u4FEF\u4EF0",
roll: "\u4FA7\u7FFB",
cameraHeight: "\u89C6\u9AD8",
tip: "\u70B9\u51FB\u5207\u6362\u9F20\u6807\u663E\u793A\u5750\u6807\u4E3A UTM \u6295\u5F71\u5750\u6807"
}
},
navigationSm: {
compass: {
outerTip: "\u65CB\u8F6C\u89C6\u56FE\uFF1A\u987A/\u9006\u65F6\u9488\u65B9\u5411\u62D6\u62FD\u7F57\u76D8\u5916\u73AF\uFF1B\u91CD\u7F6E\u89C6\u56FE\uFF1A\u53CC\u51FB\u7F57\u76D8\u5916\u73AF\u3002"
},
zoomCotrol: {
zoomInTip: "\u653E\u5927",
zoomBarTip: "\u6309\u4F4F\u6ED1\u5757\u5411\u4E0A\u653E\u5927\uFF0C\u5411\u4E0B\u7F29\u5C0F\u3002",
zoomOutTip: "\u7F29\u5C0F"
}
},
measurement: {
expand: "\u5C55\u5F00",
collapse: "\u6536\u62E2",
editor: {
move: "\u79FB\u52A8\u8282\u70B9",
insert: "\u63D2\u5165\u8282\u70B9",
remove: "\u79FB\u9664\u8282\u70B9",
removeAll: "\u79FB\u9664\u6240\u6709\u8282\u70B9"
},
distance: {
tip: "\u8DDD\u79BB\u91CF\u7B97",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u8DDD\u79BB\u91CF\u7B97\u8D77\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u8DDD\u79BB\u91CF\u7B97\u7EC8\u70B9\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
"component-distance": {
tip: "\u4E09\u89D2\u91CF\u7B97",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u4E09\u89D2\u91CF\u7B97\u8D77\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u4E09\u89D2\u91CF\u7B97\u7EC8\u70B9\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
polyline: {
tip: "\u6298\u7EBF\u8DDD\u79BB\u91CF\u7B97",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u7B2C\u4E00\u4E2A\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u4E0B\u4E00\u4E2A\u70B9\uFF0C\u53CC\u51FB\u5DE6\u952E\u7ED3\u675F\u91CF\u7B97\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
horizontal: {
tip: "\u6C34\u5E73\u8DDD\u79BB\u91CF\u7B97",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u7B2C\u4E00\u4E2A\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u4E0B\u4E00\u4E2A\u70B9\uFF0C\u53CC\u51FB\u5DE6\u952E\u7ED3\u675F\u91CF\u7B97\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
vertical: {
tip: "\u5782\u76F4\u8DDD\u79BB\u91CF\u7B97",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u5782\u76F4\u8DDD\u79BB\u91CF\u7B97\u8D77\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u5782\u76F4\u8DDD\u79BB\u91CF\u7B97\u7EC8\u70B9\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
height: {
tip: "\u5730\u8868\u9AD8\u5EA6\u91CF\u7B97",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u9AD8\u5EA6\u91CF\u7B97\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u9AD8\u5EA6\u91CF\u7B97\u70B9\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
area: {
tip: "\u9762\u79EF\u91CF\u7B97",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u7B2C\u4E00\u4E2A\u70B9\u3002",
drawingTipEnd: "\u70B9\u51FB\u5DE6\u952E\u7ED8\u5236\u4E0B\u4E00\u4E2A\u70B9\uFF0C\u53CC\u51FB\u5DE6\u952E\u7ED3\u675F\u91CF\u7B97\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
point: {
tip: "\u5750\u6807\u91CF\u7B97",
drawingTipStart: "\u70B9\u51FB\u5DE6\u952E\u7ED8\u5236\u5750\u6807\u91CF\u7B97\u70B9\u3002",
drawingTipEnd: "\u70B9\u51FB\u5DE6\u952E\u7ED8\u5236\u5750\u6807\u91CF\u7B97\u70B9\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002",
lng: "\u7ECF\u5EA6\uFF1A",
lat: "\u7EAC\u5EA6\uFF1A",
height: "\u9AD8\u5EA6\uFF1A",
slope: "\u5761\u5EA6\uFF1A"
},
rectangle: {
tip: "\u77E9\u5F62\u91CF\u7B97",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u77E9\u5F62\u91CF\u7B97\u8D77\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u77E9\u5F62\u91CF\u7B97\u7EC8\u70B9\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
regular: {
tip: "\u6B63\u591A\u8FB9\u5F62\u91CF\u7B97",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u6B63\u591A\u8FB9\u5F62\u91CF\u7B97\u8D77\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u6B63\u591A\u8FB9\u5F62\u91CF\u7B97\u7EC8\u70B9\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
circle: {
tip: "\u5706\u5F62\u91CF\u7B97",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u5706\u5F62\u91CF\u7B97\u8D77\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u5706\u5F62\u91CF\u7B97\u7EC8\u70B9\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
clear: {
tip: "\u6E05\u9664\u91CF\u7B97\u7ED3\u679C"
}
},
drawing: {
expand: "\u5C55\u5F00",
collapse: "\u6536\u62E2",
editor: {
move: "\u79FB\u52A8\u8282\u70B9",
insert: "\u63D2\u5165\u8282\u70B9",
remove: "\u79FB\u9664\u8282\u70B9",
removeAll: "\u79FB\u9664\u6240\u6709\u8282\u70B9"
},
pin: {
tip: "\u7ED8\u5236\u56FE\u6807\u70B9",
drawingTipStart: "\u70B9\u51FB\u5DE6\u952E\u7ED8\u5236\u56FE\u6807\u70B9\u3002",
drawingTipEnd: "\u70B9\u51FB\u5DE6\u952E\u7ED8\u5236\u56FE\u6807\u70B9\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
point: {
tip: "\u7ED8\u5236\u70B9",
drawingTipStart: "\u70B9\u51FB\u5DE6\u952E\u7ED8\u5236\u70B9\u3002",
drawingTipEnd: "\u70B9\u51FB\u5DE6\u952E\u7ED8\u5236\u70B9\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
polyline: {
tip: "\u7ED8\u5236\u7EBF",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u7B2C\u4E00\u4E2A\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u4E0B\u4E00\u4E2A\u70B9\uFF0C\u53CC\u51FB\u5DE6\u952E\u7ED3\u675F\u7ED8\u5236\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
polygon: {
tip: "\u7ED8\u5236\u9762",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u7B2C\u4E00\u4E2A\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u4E0B\u4E00\u4E2A\u70B9\uFF0C\u53CC\u51FB\u5DE6\u952E\u7ED3\u675F\u7ED8\u5236\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
rectangle: {
tip: "\u7ED8\u5236\u77E9\u5F62",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u77E9\u5F62\u8D77\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u77E9\u5F62\u7EC8\u70B9\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
circle: {
tip: "\u7ED8\u5236\u5706",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u5706\u5F62\u8D77\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u5706\u5F62\u7EC8\u70B9\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
regular: {
tip: "\u7ED8\u5236\u6B63\u591A\u8FB9\u5F62",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u6B63\u591A\u8FB9\u5F62\u8D77\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u6B63\u591A\u8FB9\u5F62\u7EC8\u70B9\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
clear: {
tip: "\u6E05\u9664\u7ED8\u5236\u7ED3\u679C"
}
},
analysis: {
expand: "\u5C55\u5F00",
collapse: "\u6536\u62E2",
editor: {
move: "\u79FB\u52A8\u8282\u70B9",
insert: "\u63D2\u5165\u8282\u70B9",
remove: "\u79FB\u9664\u8282\u70B9",
removeAll: "\u79FB\u9664\u6240\u6709\u8282\u70B9"
},
sightline: {
tip: "\u901A\u89C6\u5206\u6790",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u89C2\u6D4B\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u76EE\u6807\u70B9\uFF0C\u53CC\u51FB\u5DE6\u952E\u7ED3\u675F\u7ED8\u5236\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
viewshed: {
tip: "\u53EF\u89C6\u57DF\u5206\u6790",
drawingTipStart: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u53EF\u89C6\u57DF\u5206\u6790\u8D77\u70B9\u3002",
drawingTipEnd: "\u5355\u51FB\u5DE6\u952E\u7ED8\u5236\u53EF\u89C6\u57DF\u5206\u6790\u7EC8\u70B9\u3002",
drawingTipEditing: "\u79FB\u52A8\u9F20\u6807\u4FEE\u6539\u8282\u70B9\uFF0C\u5355\u51FB\u5DE6\u952E\u786E\u5B9A\u4FEE\u6539\uFF0C\u5355\u51FB\u53F3\u952E\u653E\u5F03\u4FEE\u6539\u3002"
},
clear: {
tip: "\u6E05\u9664\u5206\u6790\u7ED3\u679C"
}
},
overview: {
show: "\u663E\u793A\u9E70\u773C",
hidden: "\u9690\u85CF\u9E70\u773C"
},
typhoon: {
warn: "\u64AD\u653E\u53F0\u98CE\u5931\u8D25\uFF0C\u539F\u56E0\uFF1A\u672A\u627E\u5230\u5BF9\u5E94\u7F16\u53F7\u7684\u53F0\u98CE\u6570\u636E\u3002"
}
}
};
const buildTranslator = exports('buildTranslator', (locale) => (path, option) => translate$1(path, option, unref(locale)));
const translate$1 = exports('translate', (path, option, locale) => get$1(locale, path, path).replace(/\{(\w+)\}/g, (_, key) => {
var _a;
return `${(_a = option == null ? void 0 : option[key]) != null ? _a : `{${key}}`}`;
}));
const buildLocaleContext = exports('buildLocaleContext', (locale) => {
const lang = computed(() => unref(locale).name);
const localeRef = isRef(locale) ? locale : ref(locale);
return {
lang,
locale: localeRef,
t: buildTranslator(locale)
};
});
const useLocale = exports('useLocale', () => {
const locale = useGlobalConfig("locale");
return buildLocaleContext(computed(() => locale.value || Chinese));
});
function useEvents(props, vcInstance, logger) {
const bindEvents = (cesiumObject, cesiumEvents, register = true) => {
const ev = cesiumEvents || vcInstance.cesiumEvents || [];
ev && ev.forEach((eventName) => {
if (cesiumObject[eventName]) {
const listener = getInstanceListener(vcInstance, eventName);
const methodName = register ? "addEventListener" : "removeEventListener";
listener && cesiumObject[eventName][methodName](listener);
}
});
};
const registerEvents = (register) => {
var _a;
const { viewer, cesiumObject } = vcInstance;
if (cesiumObject === void 0 || viewer === void 0) {
return;
}
const { ScreenSpaceEventHandler, ScreenSpaceEventType } = Cesium;
if (!viewer._vcPickScreenSpaceEventHandler || !viewer._vcViewerScreenSpaceEventHandler) {
viewer._vcPickScreenSpaceEventHandler = new ScreenSpaceEventHandler(viewer.canvas);
viewer._vcViewerScreenSpaceEventHandler = new ScreenSpaceEventHandler(viewer.canvas);
viewerScreenSpaceEvents.forEach((type) => {
const listener = getInstanceListener(vcInstance, type);
listener && viewer._vcViewerScreenSpaceEventHandler.setInputAction(listener, ScreenSpaceEventType[type]);
viewer._vcPickScreenSpaceEventHandler.setInputAction(pickedAction.bind({ eventName: type, viewer }), ScreenSpaceEventType[type]);
});
}
bindEvents(cesiumObject, vcInstance.cesiumEvents || [], register);
(_a = vcInstance.cesiumMembersEvents) == null ? void 0 : _a.forEach((eventName) => {
const cesiumIntanceMember = isArray(eventName.name) && eventName.name.length > 0 && cesiumObject[eventName.name[0]] ? cesiumObject[eventName.name[0]][eventName.name[1]] : cesiumObject[eventName.name];
cesiumIntanceMember && bindEvents(cesiumIntanceMember, eventName.events, register);
});
if (props.enableMouseEvent) {
pickEvents.forEach((eventName) => {
const listener = getInstanceListener(vcInstance, eventName);
if (register) {
listener && (cesiumObject[`vc${eventName}`] = listener);
} else {
listener && delete cesiumObject[`vc${eventName}`];
}
});
}
};
function pickedAction(movement) {
if (!props.enableMouseEvent || !movement) {
return;
}
const viewer = this.viewer;
const { eventName } = this;
const position = movement.position || movement.endPosition;
if (!position) {
return;
}
const pickedFeatureAndCallbackNames = [];
let callbackName;
if (eventName.indexOf("LEFT_DOUBLE_CLICK") !== -1) {
callbackName = "dblclick";
} else if (eventName.indexOf("CLICK") !== -1) {
callbackName = "click";
} else if (eventName.indexOf("DOWN") !== -1) {
callbackName = "mousedown";
} else if (eventName.indexOf("UP") !== -1) {
callbackName = "mouseup";
} else if (eventName.indexOf("MOUSE_MOVE") !== -1) {
callbackName = "mousemove";
}
let callbackNameOut;
if (callbackName === "mousemove") {
callbackNameOut = "mouseout";
} else if (callbackName === "click") {
callbackNameOut = "clickout";
}
const pickedFeature = viewer.scene.pick(position);
if (!Cesium.defined(pickedFeature)) {
if (this.pickedFeature) {
pickedFeatureAndCallbackNames.push({
callbackName: callbackNameOut,
pickedFeature: this.pickedFeature
});
}
this.pickedFeature = void 0;
} else {
if (this.pickedFeature && this.pickedFeature.id !== pickedFeature.id) {
pickedFeatureAndCallbackNames.push({
// 拾取到对象,this.pickedFeature也有记录,两者不同,说明操作到另外一个对象上去了
callbackName: callbackNameOut,
pickedFeature: this.pickedFeature
});
}
if (callbackName === "mousemove" && (!this.pickedFeature || this.pickedFeature.id !== pickedFeature.id)) {
pickedFeatureAndCallbackNames.push({
callbackName: "mouseover",
pickedFeature
});
}
pickedFeatureAndCallbackNames.push({
callbackName,
pickedFeature
});
}
if (pickedFeatureAndCallbackNames.length === 0) {
return;
}
let intersection;
const scene = viewer.scene;
if (scene.mode === Cesium.SceneMode.SCENE3D) {
const ray = scene.camera.getPickRay(position);
intersection = scene.globe.pick(ray, scene);
} else {
intersection = scene.camera.pickEllipsoid(position, scene.globe.ellipsoid);
}
let button = -1;
if (eventName.indexOf("LEFT") !== -1) {
button = 0;
} else if (eventName.indexOf("MIDDLE") !== -1) {
button = 1;
} else if (eventName.indexOf("RIGHT") !== -1) {
button = 2;
}
const eventSourceList = [];
pickedFeatureAndCallbackNames.forEach((item) => {
const callbackName2 = item.callbackName;
const pickedFeature2 = item.pickedFeature;
if (pickedFeature2.id) {
if (isArray(pickedFeature2.id)) {
if (pickedFeature2.id[0] instanceof Cesium.Entity) {
eventSourceList.push({
callbackName: callbackName2,
cesiumObject: pickedFeature2.id[0].entityCollection.owner,
pickedFeature: pickedFeature2
});
} else {
eventSourceList.push({
callbackName: callbackName2,
cesiumObject: pickedFeature2.primitive.owner,
pickedFeature: pickedFeature2
});
}
} else if (pickedFeature2.id instanceof Cesium.Entity) {
eventSourceList.push({
callbackName: callbackName2,
cesiumObject: pickedFeature2.id,
pickedFeature: pickedFeature2
});
eventSourceList.push({
callbackName: callbackName2,
cesiumObject: pickedFeature2.id.entityCollection.owner,
pickedFeature: pickedFeature2
});
}
}
const getParentCollection = (e) => {
eventSourceList.push({
callbackName: callbackName2,
cesiumObject: e,
pickedFeature: pickedFeature2
});
if (e._vcParent) {
getParentCollection(e._vcParent);
}
};
if (pickedFeature2.primitive) {
if (pickedFeature2.primitive._vcParent) {
getParentCollection(pickedFeature2.primitive._vcParent);
}
eventSourceList.push({
callbackName: callbackName2,
cesiumObject: pickedFeature2.primitive,
pickedFeature: pickedFeature2
});
}
if (pickedFeature2.collection) {
if (pickedFeature2.collection._vcParent) {
getParentCollection(pickedFeature2.collection._vcParent);
}
eventSourceList.push({
callbackName: callbackName2,
cesiumObject: pickedFeature2.collection,
pickedFeature: pickedFeature2
});
}
});
eventSourceList.forEach((event) => {
if (event.callbackName) {
const fn = event.cesiumObject[`vc${event.callbackName}`] || event.cesiumObject[`on${capitalize(event.callbackName)}`] || event.cesiumObject[kebabCase(`on${capitalize(event.callbackName)}`)];
if (Cesium.defined(fn)) {
const payload = {
type: `on${event.callbackName}`,
windowPosition: position,
surfacePosition: intersection,
pickedFeature: event.pickedFeature,
button,
cesiumObject: event.cesiumObject
};
if (fn instanceof Cesium.CallbackProperty) {
fn._callback(payload);
} else {
fn(payload);
}
}
}
});
this.pickedFeature = pickedFeature;
}
return {
bindEvents,
registerEvents
};
}
const viewerScreenSpaceEvents = [
"LEFT_CLICK",
"LEFT_DOUBLE_CLICK",
"LEFT_DOWN",
"LEFT_UP",
"MIDDLE_CLICK",
"MIDDLE_DOWN",
"MIDDLE_UP",
"MOUSE_MOVE",
"PINCH_END",
"PINCH_MOVE",
"PINCH_START",
"RIGHT_CLICK",
"RIGHT_DOWN",
"RIGHT_UP",
"WHEEL"
];
const pickEvents = ["mousedown", "mouseup", "click", "clickout", "dblclick", "mousemove", "mouseover", "mouseout"];
function useTimeout() {
let timer;
onBeforeUnmount(() => {
clearTimeout(timer);
});
return {
registerTimeout(fn, delay) {
clearTimeout(timer);
timer = setTimeout(fn, delay);
},
removeTimeout() {
clearTimeout(timer);
}
};
}
const callbackCmpNames = ["Graphics", "VcEntity", "Datasource", "VcOverlayDynamic"];
function useCommon(props, { emit, attrs }, vcInstance) {
const logger = useLog(vcInstance);
const { registerTimeout, removeTimeout } = useTimeout();
vcInstance.alreadyListening = [];
vcInstance.removeCallbacks = [];
let unwatchFns = [];
vcInstance.mounted = false;
const vcMitt = mitt();
vcInstance.vcMitt = vcMitt;
const $services = inject(vcKey);
const { t } = useLocale();
if ($services === void 0) {
console.error(`${vcInstance.cesiumClass} ${t("vc.loadError")}`);
return;
}
const parentVcInstance = getVcParentInstance(vcInstance);
const eventsState = useEvents(props, vcInstance);
vcInstance.children = [];
const entityGraphics = {
billboard: true,
box: true,
corridor: true,
cylinder: true,
ellipse: true,
ellipsoid: true,
label: true,
model: true,
tileset: true,
path: true,
plane: true,
point: true,
polygon: true,
polyline: true,
polylineVolume: true,
rectangle: true,
wall: true
};
const globalConfig = useGlobalConfig();
const beforeLoad = async () => {
emit("beforeLoad", vcInstance);
if (parentVcInstance.nowaiting) {
return true;
} else {
await parentVcInstance.proxy.creatingPromise;
}
};
const load = async () => {
var _a;
if (vcInstance.mounted) {
return false;
}
logger.debug(`${vcInstance.cesiumClass}---loading`);
await beforeLoad();
const { Cesium: Cesium2, viewer } = $services;
vcInstance.viewer = viewer;
vcInstance.Cesium = Cesium2;
if (!parentVcInstance.cesiumObject && !parentVcInstance.nowaiting) {
return await ((_a = parentVcInstance.proxy) == null ? void 0 : _a.load());
}
setPropsWatcher(true);
return createCesiumObject().then(async (cesiumObject) => {
vcInstance.cesiumObject = cesiumObject;
return mount().then(() => {
vcInstance.mounted = true;
parentVcInstance.children.push(vcInstance);
Object.assign(vcInstance.proxy, {
cesiumObject: vcInstance.cesiumObject
});
const readyObj = { Cesium: Cesium2, viewer, cesiumObject, vm: vcInstance };
emit("ready", readyObj);
vcMitt.emit("ready", readyObj);
logger.debug(`${vcInstance.cesiumClass}---loaded`);
return readyObj;
});
});
};
const beforeUnload = async () => {
await vcInstance.unloadingPromise;
};
const unload = async () => {
await beforeUnload();
for (let i = 0; i < vcInstance.children.length; i++) {
const vcChildCmp = vcInstance.children[i].proxy;
await vcChildCmp.unload();
}
vcInstance.children.length = 0;
vcInstance.isUnmounted = false;
return vcInstance.mounted ? unmount().then(async () => {
setPropsWatcher(false);
vcInstance.cesiumObject = void 0;
vcInstance.mounted = false;
vcInstance.removeCallbacks.forEach((removeCallback) => {
removeCallback();
});
emit("destroyed", vcInstance);
vcMitt.emit("destroyed", vcInstance);
logger.debug(`${vcInstance.cesiumClass}---unmounted`);
return vcInstance.renderByParent && !vcInstance.unloadingPromise ? parentVcInstance.proxy.unload() : true;
}) : false;
};
const beforeReload = async () => {
await vcInstance.reloadingPromise;
};
const reload = async () => {
await beforeReload();
return unload().then(() => {
return load();
});
};
const mount = async () => {
var _a;
eventsState.registerEvents(true);
return ((_a = vcInstance.mount) == null ? void 0 : _a.call(vcInstance)) || true;
};
const unmount = async () => {
var _a;
eventsState.registerEvents(false);
return ((_a = vcInstance.unmount) == null ? void 0 : _a.call(vcInstance)) || true;
};
const createCesiumObject = async () => {
logger.debug("do createCesiumObject");
if (isFunction(vcInstance.createCesiumObject)) {
return vcInstance.createCesiumObject();
} else {
const options = transformProps(props);
return new Cesium[vcInstance.cesiumClass](options);
}
};
const deepWatchHandler = (vueProp, watcherOptions) => {
let deep = watcherOptions == null ? void 0 : watcherOptions.deep;
const {
SampledPositionProperty,
Appearance,
DebugAppearance,
MaterialAppearance,
PolylineColorAppearance,
EllipsoidSurfaceAppearance,
PerInstanceColorAppearance,
PolylineMaterialAppearance
} = Cesium;
if (vueProp === "position") {
deep = !(vcInstance.proxy[vueProp] instanceof SampledPositionProperty);
} else if (vueProp === "appearance" || vueProp === "depthFailAppearance") {
const value = vcInstance.proxy[vueProp];
deep = !(value instanceof Appearance || value instanceof DebugAppearance || value instanceof MaterialAppearance || value instanceof PolylineColorAppearance || value instanceof EllipsoidSurfaceAppearance || value instanceof PerInstanceColorAppearance || value instanceof PolylineMaterialAppearance || getObjClassName(value).indexOf("Appearance") !== -1);
}
return deep;
};
const setPropsWatcher = (register) => {
if (register) {
if (!vcInstance.cesiumClass || !Cesium[vcInstance.cesiumClass]) {
return;
}
props && Object.keys(props).forEach((vueProp) => {
var _a, _b, _c, _d, _e;
let cesiumProp = vueProp;
if (vueProp === "labelStyle" || vueProp === "wmtsStyle") {
cesiumProp = "style";
} else if (vueProp === "bmKey") {
cesiumProp = "key";
}
if (((_b = (_a = vcInstance.proxy) == null ? void 0 : _a.$options.watch) == null ? void 0 : _b[vueProp]) || vcInstance.alreadyListening.indexOf(vueProp) !== -1) {
return;
}
const watcherOptions = (_d = (_c = vcInstance.proxy) == null ? void 0 : _c.$options.props[vueProp]) == null ? void 0 : _d.watcherOptions;
const unwatch = (_e = vcInstance.proxy) == null ? void 0 : _e.$watch(
vueProp,
async (val, oldVal) => {
await vcInstance.proxy.creatingPromise;
const { cesiumObject } = vcInstance;
const pd = cesiumObject && Object.getOwnPropertyDescriptor(cesiumObject, cesiumProp);
const pdProto = cesiumObject && Object.getOwnPropertyDescriptor(Object.getPrototypeOf(cesiumObject), cesiumProp);
const hasSetter = pd && (pd.writable || pd.set) || pdProto && (pdProto.writable || pdProto.set);
if (hasSetter) {
if (watcherOptions && watcherOptions.cesiumObjectBuilder) {
const newVal = watcherOptions.cesiumObjectBuilder.call(vcInstance, val, vcInstance.viewer.scene.globe.ellipsoid);
if (!(Cesium.defined(cesiumObject[cesiumProp]) && Cesium.defined(cesiumObject[cesiumProp]._callback))) {
cesiumObject[cesiumProp] = newVal;
}
} else {
cesiumObject[cesiumProp] = transformProp(cesiumProp, val);
}
return true;
} else {
if (!isEqual(val, oldVal) || Array.isArray(val)) {
if (attrs["reload-mode"] === "once" || attrs["reloadMode"] === "once" || globalConfig.value.reloadMode === "once") {
removeTimeout();
registerTimeout(() => {
vcInstance.proxy.reload();
}, 0);
} else {
vcInstance.reloadingPromise = new Promise((resolve, reject) => {
vcInstance.proxy.reload().then(() => {
resolve(true);
}).catch((e) => {
reject(e);
});
});
}
}
}
},
{
deep: deepWatchHandler(vueProp, watcherOptions)
}
);
unwatchFns.push(unwatch);
});
} else {
unwatchFns.forEach((item) => item());
unwatchFns = [];
}
};
const transformProps = (props2, childProps) => {
const options = {};
props2 && Object.keys(props2).forEach((vueProp) => {
let cesiumProp = vueProp;
if (vueProp === "labelStyle" || vueProp === "wmtsStyle") {
cesiumProp = "style";
} else if (vueProp === "bmKey") {
cesiumProp = "key";
}
if (props2[vueProp] === void 0 || props2[vueProp] === null) {
return;
}
const className = getObjClassName(props2[vueProp]);
if (className && // className.indexOf('Graphics') === -1 &&
entityGraphics[cesiumProp] && (vcInstance.cesiumClass === "Entity" || vcInstance.cesiumClass.indexOf("DataSource") > 0 || vcInstance.cesiumClass === "VcOverlayDynamic")) {
options[cesiumProp] = transformProps(props2[vueProp], childProps);
} else {
options[cesiumProp] = transformProp(vueProp, props2[vueProp], childProps);
}
});
return options;
};
const transformProp = (prop, value, childProps) => {
var _a, _b;
const className = getObjClassName(value);
if (className && // className.indexOf('Graphics') === -1 &&
entityGraphics[prop] && (vcInstance.cesiumClass === "Entity" || vcInstance.cesiumClass.indexOf("DataSource") > 0 || vcInstance.cesiumClass === "VcOverlayDynamic")) {
return transformProps(value, childProps);
} else {
const cmpName = (_a = vcInstance.proxy) == null ? void 0 : _a.$options.name;
let supportCallbackProperty = false;
if (isFunction(value) && cmpName) {
callbackCmpNames.forEach((v) => {
if (cmpName.indexOf(v) !== -1) {
supportCallbackProperty = true;
}
});
}
const propOption = ((_b = vcInstance.proxy) == null ? void 0 : _b.$options.props[prop]) || (childProps == null ? void 0 : childProps[prop]) || cesiumProps[prop] && cesiumProps[prop][prop];
return (propOption == null ? void 0 : propOption.watcherOptions) && !isEmptyObj(value) ? propOption.watcherOptions.cesiumObjectBuilder.call(vcInstance, value, vcInstance.viewer.scene.globe.ellipsoid) : supportCallbackProperty ? new Cesium.CallbackProperty(value, false) : value;
}
};
const getServices = () => {
return mergeDescriptors({}, $services || {});
};
const creatingPromise = new Promise((resolve, reject) => {
try {
let isLoading = false;
if ($services.viewer) {
isLoading = true;
load().then((e) => {
resolve(e);
isLoading = false;
}).catch((e) => {
emit("unready", e);
reject(e);
});
}
parentVcInstance.vcMitt.on("ready", () => {
if (!isLoading && !vcInstance.isUnmounted) {
load().then((e) => {
resolve(e);
}).catch((e) => {
emit("unready", e);
reject(e);
});
}
});
} catch (e) {
emit("unready", e);
reject(e);
}
});
logger.debug(`${vcInstance.cesiumClass}---onCreated`);
onUnmounted(() => {
logger.debug(`${vcInstance.cesiumClass}---onUnmounted`);
vcInstance.unloadingPromise = new Promise((resolve, reject) => {
unload().then(() => {
logger.debug(`${vcInstance.cesiumClass}---unloaded`);
resolve(true);
vcInstance.isUnmounted = true;
vcInstance.unloadingPromise = void 0;
vcMitt.all.clear();
});
});
vcInstance.alreadyListening = [];
});
Object.assign(vcInstance.proxy, {
creatingPromise,
load,
unload,
reload,
getCreatingPromise: () => creatingPromise,
getCesiumObject: () => vcInstance.cesiumObject
});
return {
$services,
load,
unload,
reload,
creatingPromise,
transformProp,
transformProps,
unwatchFns,
setPropsWatcher,
logger,
getServices
};
}
function useDatasources(props, ctx, vcInstance) {
vcInstance.cesiumEvents = ["changedEvent", "errorEvent", "loadingEvent"];
if (vcInstance.cesiumClass === "KmlDataSource") {
vcInstance.cesiumEvents.push("refreshEvent");
vcInstance.cesiumEvents.push("unsupportedNodeEvent");
}
vcInstance.cesiumMembersEvents = [
{
name: "clock",
events: ["definitionChanged"]
},
{
name: "clustering",
events: ["clusterEvent"]
},
{
name: "entities",
events: ["collectionChanged"]
}
];
const commonState = useCommon(props, ctx, vcInstance);
if (commonState === void 0) {
return;
}
vcInstance.alreadyListening.push("entities");
let unwatchFns = [];
unwatchFns.push(
watch(
() => cloneDeep(props.entities),
(newVal, oldVal) => {
if (!vcInstance.mounted) {
return;
}
const datasource = vcInstance.cesiumObject;
if (newVal.length === oldVal.length) {
const modifies = [];
for (let i = 0; i < newVal.length; i++) {
const options = newVal[i];
const oldOptions = oldVal[i];
if (JSON.stringify(options) !== JSON.stringify(oldOptions)) {
modifies.push({
newOptions: options,
oldOptions
});
}
}
modifies.forEach((v) => {
const modifyEntity = datasource.entities.getById(v.oldOptions.id);
if (v.oldOptions.id === v.newOptions.id) {
modifyEntity && Object.keys(v.newOptions).forEach((prop) => {
if (v.oldOptions[prop] !== v.newOptions[prop]) {
modifyEntity[prop] = commonState.transformProp(prop, v.newOptions[prop]);
}
});
} else {
datasource.entities.remove(modifyEntity);
const entityOptions = v.newOptions;
addEntities(datasource, [entityOptions]);
}
});
} else {
const addeds = differenceBy(newVal, oldVal, "id");
const deletes = differenceBy(oldVal, newVal, "id");
const deletedEntities = [];
for (let i = 0; i < deletes.length; i++) {
const deleteEntity = datasource.entities.getById(deletes[i].id);
deletedEntities.push(deleteEntity);
}
deletedEntities.forEach((v) => {
datasource.entities.remove(v);
});
addEntities(datasource, addeds);
}
},
{
deep: true
}
)
);
const addEntities = (datasource, entities) => {
for (let i = 0; i < entities.length; i++) {
const entityOptions = entities[i];
const entityOptionsTransform = commonState.transformProps(entityOptions);
const entity = datasource.entities.add(entityOptionsTransform);
entityOptions.id !== entity.id && (entityOptions.id = entity.id);
addCustomProperty(entity, entityOptionsTransform);
}
};
vcInstance.mount = async () => {
const dataSources = commonState.$services.dataSources;
const datasource = vcInstance.cesiumObject;
datasource.show = props.show;
addEntities(datasource, props.entities);
return dataSources.add(datasource).then(() => {
return true;
});
};
vcInstance.unmount = async () => {
const dataSources = commonState.$services.dataSources;
const datasource = vcInstance.cesiumObject;
return dataSources && dataSources.remove(datasource, props.destroy);
};
const getServices = () => {
return mergeDescriptors(commonState.getServices(), {
get datasource() {
return vcInstance.cesiumObject;
},
get entities() {
var _a;
return (_a = vcInstance.cesiumObject) == null ? void 0 : _a.entities;
}
});
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
provide(vcKey, getServices());
return {
transformProps: commonState.transformProps,
unwatchFns: commonState.unwatchFns,
setPropsWatcher: commonState.setPropsWatcher
};
}
function useGeometries(props, ctx, vcInstance) {
vcInstance.cesiumEvents = [];
vcInstance.renderByParent = true;
const commonState = useCommon(props, ctx, vcInstance);
if (commonState === void 0) {
return;
}
vcInstance.mount = async () => {
var _a;
const geometry = vcInstance.cesiumObject;
const parentVM = getVcParentInstance(vcInstance).proxy;
return (_a = parentVM.__updateGeometry) == null ? void 0 : _a.call(parentVM, geometry);
};
return {
transformProps: commonState.transformProps,
unwatchFns: commonState.unwatchFns,
setPropsWatcher: commonState.setPropsWatcher
};
}
function useGraphics(props, ctx, vcInstance) {
vcInstance.cesiumEvents = ["definitionChanged"];
const commonState = useCommon(props, ctx, vcInstance);
if (commonState === void 0) {
return;
}
vcInstance.mount = async () => {
var _a, _b;
const graphics = vcInstance.cesiumObject;
if (graphics === void 0) {
return false;
}
const cmpNameArr = kebabCase(((_a = vcInstance.proxy) == null ? void 0 : _a.$options.name) || "").split("-");
const emitType = cmpNameArr.length === 3 ? `update:${cmpNameArr[2]}` : "update:polylineVolume";
const parentVM = getVcParentInstance(vcInstance).proxy;
return parentVM && ((_b = parentVM.__updateGraphics) == null ? void 0 : _b.call(parentVM, graphics, emitType));
};
vcInstance.unmount = async () => {
var _a, _b;
const cmpNameArr = kebabCase(((_a = vcInstance.proxy) == null ? void 0 : _a.$options.name) || "").split("-");
const emitType = cmpNameArr.length === 3 ? `update:${cmpNameArr[2]}` : "update:polylineVolume";
const parentVM = getVcParentInstance(vcInstance).proxy;
return parentVM && ((_b = parentVM.__updateGraphics) == null ? void 0 : _b.call(parentVM, void 0, emitType));
};
}
const createDirective = (raw) => markRaw(raw);
function css(element, css2) {
const style2 = element.style;
Object.keys(css2).forEach((prop) => {
style2[prop] = css2[prop];
});
}
function getElement(el) {
if (el === void 0 || el === null) {
return void 0;
}
if (typeof el === "string") {
try {
return document.querySelector(el) || void 0;
} catch (err) {
return void 0;
}
}
const target = isRef(el) === true ? el.value : el;
if (target) {
return target.$el || target;
}
}
const listenOpts = {
hasPassive: false,
passiveCapture: true,
notPassiveCapture: true,
passive: void 0
};
try {
const opts = Object.defineProperty({}, "passive", {
get() {
Object.assign(listenOpts, {
hasPassive: true,
passive: { passive: true },
notPassive: { passive: false },
passiveCapture: { passive: true, capture: true },
notPassiveCapture: { passive: false, capture: true }
});
}
});
window.addEventListener("qtest", null, opts);
window.removeEventListener("qtest", null, opts);
} catch (e) {
}
function noop() {
}
function leftClick(e) {
return e.button === 0;
}
function position(e) {
if (e.touches && e.touches[0]) {
e = e.touches[0];
} else if (e.changedTouches && e.changedTouches[0]) {
e = e.changedTouches[0];
} else if (e.targetTouches && e.targetTouches[0]) {
e = e.targetTouches[0];
}
return {
top: e.clientY,
left: e.clientX
};
}
function stop(e) {
e.stopPropagation();
}
function prevent(e) {
e.cancelable !== false && e.preventDefault();
}
function stopAndPrevent(e) {
e.cancelable !== false && e.preventDefault();
e.stopPropagation();
}
function preventDraggable(el, status) {
if (el === void 0 || status === true && el.__dragPrevented === true) {
return;
}
const fn = status === true ? (el2) => {
el2.__dragPrevented = true;
el2.addEventListener("dragstart", prevent, listenOpts.notPassiveCapture);
} : (el2) => {
delete el2.__dragPrevented;
el2.removeEventListener("dragstart", prevent, listenOpts.notPassiveCapture);
};
el.querySelectorAll("a, img").forEach(fn);
}
function addEvt(ctx, targetName, events) {
const name = `__vc_${targetName}_evt`;
ctx[name] = ctx[name] !== void 0 ? ctx[name].concat(events) : events;
events.forEach((evt) => {
evt[0].addEventListener(evt[1], ctx[evt[2]], listenOpts[evt[3]]);
});
}
function cleanEvt(ctx, targetName) {
const name = `__vc_${targetName}_evt`;
if (ctx[name] !== void 0) {
ctx[name].forEach((evt) => {
evt[0].removeEventListener(evt[1], ctx[evt[2]], listenOpts[evt[3]]);
});
ctx[name] = void 0;
}
}
function shouldIgnoreKey(evt) {
return evt !== Object(evt) || evt.isComposing === true || evt.qKeyEvent === true;
}
function isKeyCode(evt, keyCodes) {
return shouldIgnoreKey(evt) === true ? false : [].concat(keyCodes).includes(evt.keyCode);
}
function throttle(fn, limit = 250) {
let wait = false, result;
return function() {
if (wait === false) {
wait = true;
setTimeout(() => {
wait = false;
}, limit);
result = fn.apply(this, arguments);
}
return result;
};
}
function showRipple(evt, el, ctx, forceCenter) {
ctx.modifiers.stop === true && stop(evt);
const color = ctx.modifiers.color;
let center = ctx.modifiers.center;
center = center === true || forceCenter === true;
const node = document.createElement("span"), innerNode = document.createElement("span"), pos = position(evt), { left, top, width, height } = el.getBoundingClientRect(), diameter = Math.sqrt(width * width + height * height), radius = diameter / 2, centerX = `${(width - diameter) / 2}px`, x = center ? centerX : `${pos.left - left - radius}px`, centerY = `${(height - diameter) / 2}px`, y = center ? centerY : `${pos.top - top - radius}px`;
innerNode.className = "vc-ripple__inner";
css(innerNode, {
height: `${diameter}px`,
width: `${diameter}px`,
transform: `translate3d(${x},${y},0) scale3d(.2,.2,1)`,
opacity: 0
});
node.className = `vc-ripple${color ? " text-" + color : ""}`;
node.setAttribute("dir", "ltr");
node.appendChild(innerNode);
el.appendChild(node);
const abort = () => {
node.remove();
clearTimeout(timer);
};
ctx.abort.push(abort);
let timer = setTimeout(() => {
innerNode.classList.add("vc-ripple__inner--enter");
innerNode.style.transform = `translate3d(${centerX},${centerY},0) scale3d(1,1,1)`;
innerNode.style.opacity = "0.2";
timer = setTimeout(() => {
innerNode.classList.remove("vc-ripple__inner--enter");
innerNode.classList.add("vc-ripple__inner--leave");
innerNode.style.opacity = "0";
timer = setTimeout(() => {
node.remove();
ctx.abort.splice(ctx.abort.indexOf(abort), 1);
}, 275);
}, 250);
}, 50);
}
function updateModifiers(ctx, { modifiers, value, arg, instance }) {
const cfg = Object.assign({}, modifiers, value);
ctx.modifiers = {
early: cfg.early === true,
stop: cfg.stop === true,
center: cfg.center === true,
color: cfg.color || arg,
keyCodes: [].concat(cfg.keyCodes || 13)
};
}
var Ripple = exports('Ripple', createDirective({
name: "ripple",
beforeMount(el, binding) {
const ctx = {
enabled: binding.value !== false,
modifiers: {},
abort: [],
start(evt) {
if (ctx.enabled === true && evt.qSkipRipple !== true && (ctx.modifiers.early === true ? ["mousedown", "touchstart"].includes(evt.type) === true : evt.type === "click")) {
showRipple(evt, el, ctx, evt.qKeyEvent === true);
}
},
keystart: throttle((evt) => {
if (ctx.enabled === true && evt.qSkipRipple !== true && isKeyCode(evt, ctx.modifiers.keyCodes) === true && evt.type === `key${ctx.modifiers.early === true ? "down" : "up"}`) {
showRipple(evt, el, ctx, true);
}
}, 300)
};
updateModifiers(ctx, binding);
el.__vcripple = ctx;
addEvt(ctx, "main", [
[el, "mousedown", "start", "passive"],
[el, "touchstart", "start", "passive"],
[el, "click", "start", "passive"],
[el, "keydown", "keystart", "passive"],
[el, "keyup", "keystart", "passive"]
]);
},
updated(el, binding) {
if (binding.oldValue !== binding.value) {
const ctx = el.__vcripple;
ctx.enabled = binding.value !== false;
if (ctx.enabled === true && Object(binding.value) === binding.value) {
updateModifiers(ctx, binding);
}
}
},
beforeUnmount(el) {
const ctx = el.__vcripple;
ctx.abort.forEach((fn) => {
fn();
});
cleanEvt(ctx, "main");
delete el._vcripple;
}
}));
function platform() {
const ua = navigator.userAgent;
const isWindowsPhone = /(?:Windows Phone)/.test(ua);
const isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone;
const isAndroid = /(?:Android)/.test(ua);
const isFireFox = /(?:Firefox)/.test(ua);
const isChrome = /(?:Chrome|CriOS)/.test(ua);
const isTablet = /(?:iPad|PlayBook)/.test(ua) || isAndroid && !/(?:Mobile)/.test(ua) || isFireFox && /(?:Tablet)/.test(ua);
const isPhone = /(?:iPhone)/.test(ua) && !isTablet;
const isPc = !isPhone && !isAndroid && !isSymbian;
const isIOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
return {
isTablet,
isPhone,
isAndroid,
isPc,
isFireFox,
isChrome,
isIOS,
hasTouch: "ontouchstart" in window || window.navigator.maxTouchPoints > 0
};
}
function clearSelection() {
if (window.getSelection !== void 0) {
const selection = window.getSelection();
if ((selection == null ? void 0 : selection.empty) !== void 0) {
selection.empty();
} else if ((selection == null ? void 0 : selection.removeAllRanges) !== void 0) {
selection.removeAllRanges();
platform().isPhone !== true && selection.addRange(document.createRange());
}
} else if (document.selection !== void 0) {
document.selection.empty();
}
}
var TouchHold = exports('TouchHold', createDirective({
name: "touch-hold",
beforeMount(el, binding) {
const { modifiers } = binding;
if (modifiers.mouse !== true && platform().hasTouch !== true) {
return;
}
const ctx = {
handler: binding.value,
noop,
mouseStart(evt) {
if (typeof ctx.handler === "function" && leftClick(evt) === true) {
addEvt(ctx, "temp", [
[document, "mousemove", "move", "passiveCapture"],
[document, "click", "end", "notPassiveCapture"]
]);
ctx.start(evt, true);
}
},
touchStart(evt) {
var _a;
if (evt.target !== void 0 && typeof ctx.handler === "function") {
const target = evt.target;
addEvt(ctx, "temp", [
[target, "touchmove", "move", "passiveCapture"],
[target, "touchcancel", "end", "notPassiveCapture"],
[target, "touchend", "end", "notPassiveCapture"]
]);
ctx.start(evt);
(_a = binding == null ? void 0 : binding.touchStart) == null ? void 0 : _a.call(binding, evt);
}
},
start(evt, mouseEvent) {
ctx.origin = position(evt);
const startTime = Date.now();
if (platform().isPhone === true) {
document.body.classList.add("non-selectable");
clearSelection();
ctx.styleCleanup = (withDelay) => {
ctx.styleCleanup = void 0;
const remove = () => {
document.body.classList.remove("non-selectable");
};
if (withDelay === true) {
clearSelection();
setTimeout(remove, 10);
} else {
remove();
}
};
}
ctx.triggered = false;
ctx.sensitivity = mouseEvent === true ? ctx.mouseSensitivity : ctx.touchSensitivity;
ctx.timer = setTimeout(() => {
clearSelection();
ctx.triggered = true;
ctx.handler({
evt,
touch: mouseEvent !== true,
mouse: mouseEvent === true,
position: ctx.origin,
duration: Date.now() - startTime
});
}, ctx.duration);
},
move(evt) {
const { top, left } = position(evt);
if (Math.abs(left - ctx.origin.left) >= ctx.sensitivity || Math.abs(top - ctx.origin.top) >= ctx.sensitivity) {
clearTimeout(ctx.timer);
}
},
end(evt) {
var _a;
cleanEvt(ctx, "temp");
ctx.styleCleanup !== void 0 && ctx.styleCleanup(ctx.triggered);
if (ctx.triggered === true) {
evt !== void 0 && stopAndPrevent(evt);
} else {
clearTimeout(ctx.timer);
}
(_a = binding == null ? void 0 : binding.touchEnd) == null ? void 0 : _a.call(binding, evt);
}
};
const data = [600, 5, 7];
if (typeof binding.arg === "string" && binding.arg.length > 0) {
binding.arg.split(":").forEach((val, index) => {
const v = parseInt(val, 10);
v && (data[index] = v);
});
}
[ctx.duration, ctx.touchSensitivity, ctx.mouseSensitivity] = data;
el.__vctouchhold = ctx;
modifiers.mouse === true && addEvt(ctx, "main", [[el, "mousedown", "mouseStart", `passive${modifiers.mouseCapture === true ? "Capture" : ""}`]]);
platform().hasTouch === true && addEvt(ctx, "main", [
[el, "touchstart", "touchStart", `passive${modifiers.capture === true ? "Capture" : ""}`],
[el, "touchend", "noop", "notPassiveCapture"]
]);
},
updated(el, binding) {
const ctx = el.__vctouchhold;
if (ctx !== void 0 && binding.oldValue !== binding.value) {
typeof binding.value !== "function" && ctx.end();
ctx.handler = binding.value;
}
},
beforeUnmount(el) {
const ctx = el.__vctouchhold;
if (ctx !== void 0) {
cleanEvt(ctx, "main");
cleanEvt(ctx, "temp");
clearTimeout(ctx.timer);
ctx.styleCleanup !== void 0 && ctx.styleCleanup();
delete el.__vctouchhold;
}
}
}));
const keyCodes$1 = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
up: 38,
left: 37,
right: 39,
down: 40,
delete: [8, 46]
}, keyRegex = new RegExp(`^([\\d+]+|${Object.keys(keyCodes$1).join("|")})$`, "i");
function shouldEnd(evt, origin) {
const { top, left } = position(evt);
return Math.abs(left - origin.left) >= 7 || Math.abs(top - origin.top) >= 7;
}
var index = exports('TouchRepeat', createDirective({
name: "touch-repeat",
beforeMount(el, { modifiers, value, arg, touchStart }) {
const keyboard = Object.keys(modifiers).reduce((acc, key) => {
if (keyRegex.test(key) === true) {
const keyCode = isNaN(parseInt(key, 10)) ? keyCodes$1[key.toLowerCase()] : parseInt(key, 10);
keyCode >= 0 && acc.push(keyCode);
}
return acc;
}, []);
if (modifiers.mouse !== true && platform().hasTouch !== true && keyboard.length === 0) {
return;
}
const durations = typeof arg === "string" && arg.length > 0 ? arg.split(":").map((val) => parseInt(val, 10)) : [0, 600, 300];
const durationsLast = durations.length - 1;
const ctx = {
keyboard,
handler: value,
noop,
mouseStart(evt) {
if (ctx.event === void 0 && typeof ctx.handler === "function" && leftClick(evt) === true) {
addEvt(ctx, "temp", [
[document, "mousemove", "move", "passiveCapture"],
[document, "click", "end", "notPassiveCapture"]
]);
ctx.start(evt, true);
}
},
keyboardStart(evt) {
if (typeof ctx.handler === "function" && isKeyCode(evt, keyboard) === true) {
if (durations[0] === 0 || ctx.event !== void 0) {
stopAndPrevent(evt);
el.focus();
if (ctx.event !== void 0) {
return;
}
}
addEvt(ctx, "temp", [
[document, "keyup", "end", "notPassiveCapture"],
[document, "click", "end", "notPassiveCapture"]
]);
ctx.start(evt, false, true);
}
},
touchStart(evt) {
if (evt.target !== void 0 && typeof ctx.handler === "function") {
const target = evt.target;
addEvt(ctx, "temp", [
[target, "touchmove", "move", "passiveCapture"],
[target, "touchcancel", "end", "notPassiveCapture"],
[target, "touchend", "end", "notPassiveCapture"]
]);
ctx.start(evt);
touchStart == null ? void 0 : touchStart(evt);
}
},
start(evt, mouseEvent, keyboardEvent) {
if (keyboardEvent !== true) {
ctx.origin = position(evt);
}
function styleCleanup(withDelay) {
ctx.styleCleanup = void 0;
document.documentElement.style.cursor = "";
const remove = () => {
document.body.classList.remove("non-selectable");
};
if (withDelay === true) {
clearSelection();
setTimeout(remove, 10);
} else {
remove();
}
}
if (platform().isPhone === true) {
document.body.classList.add("non-selectable");
clearSelection();
ctx.styleCleanup = styleCleanup;
}
ctx.event = {
touch: mouseEvent !== true && keyboardEvent !== true,
mouse: mouseEvent === true,
keyboard: keyboardEvent === true,
startTime: Date.now(),
repeatCount: 0
};
const fn = () => {
if (ctx.event === void 0) {
return;
}
if (ctx.event.repeatCount === 0) {
ctx.event.evt = evt;
if (keyboardEvent === true) {
ctx.event.keyCode = evt.keyCode;
} else {
ctx.event.position = position(evt);
}
if (platform().isPhone !== true) {
document.documentElement.style.cursor = "pointer";
document.body.classList.add("non-selectable");
clearSelection();
ctx.styleCleanup = styleCleanup;
}
}
ctx.event.duration = Date.now() - ctx.event.startTime;
ctx.event.repeatCount += 1;
ctx.handler(ctx.event);
const index = durationsLast < ctx.event.repeatCount ? durationsLast : ctx.event.repeatCount;
ctx.timer = setTimeout(fn, durations[index]);
};
if (durations[0] === 0) {
fn();
} else {
ctx.timer = setTimeout(fn, durations[0]);
}
},
move(evt) {
if (ctx.event !== void 0 && shouldEnd(evt, ctx.origin) === true) {
clearTimeout(ctx.timer);
}
},
end(evt) {
if (ctx.event === void 0) {
return;
}
ctx.styleCleanup !== void 0 && ctx.styleCleanup(true);
evt !== void 0 && ctx.event.repeatCount > 0 && stopAndPrevent(evt);
cleanEvt(ctx, "temp");
clearTimeout(ctx.timer);
ctx.event = void 0;
}
};
el.__vctouchrepeat = ctx;
modifiers.mouse === true && addEvt(ctx, "main", [[el, "mousedown", "mouseStart", `passive${modifiers.mouseCapture === true ? "Capture" : ""}`]]);
platform().hasTouch === true && addEvt(ctx, "main", [
[el, "touchstart", "touchStart", `passive${modifiers.capture === true ? "Capture" : ""}`],
[el, "touchend", "noop", "notPassiveCapture"]
]);
keyboard.length > 0 && addEvt(ctx, "main", [[el, "keydown", "keyboardStart", `notPassive${modifiers.keyCapture === true ? "Capture" : ""}`]]);
},
updated(el, { oldValue, value }) {
const ctx = el.__vctouchrepeat;
if (ctx !== void 0 && oldValue !== value) {
typeof value !== "function" && ctx.end();
ctx.handler = value;
}
},
beforeUnmount(el) {
const ctx = el.__vctouchrepeat;
if (ctx !== void 0) {
clearTimeout(ctx.timer);
cleanEvt(ctx, "main");
cleanEvt(ctx, "temp");
ctx.styleCleanup !== void 0 && ctx.styleCleanup();
delete el.__vctouchrepeat;
}
}
}));
const directions$1 = ["left", "right", "up", "down", "horizontal", "vertical"];
const modifiersAll = {
left: true,
right: true,
up: true,
down: true,
horizontal: true,
vertical: true,
all: true
};
function getModifierDirections(mod) {
const dir = {};
directions$1.forEach((direction) => {
if (mod[direction]) {
dir[direction] = true;
}
});
if (Object.keys(dir).length === 0) {
return modifiersAll;
}
if (dir.horizontal === true) {
dir.left = dir.right = true;
}
if (dir.vertical === true) {
dir.up = dir.down = true;
}
if (dir.left === true && dir.right === true) {
dir.horizontal = true;
}
if (dir.up === true && dir.down === true) {
dir.vertical = true;
}
if (dir.horizontal === true && dir.vertical === true) {
dir.all = true;
}
return dir;
}
const getTouchTarget = platform().isIOS || navigator.vendor.toLowerCase().indexOf("apple") > -1 ? () => document : (target) => target;
function shouldStart(evt, ctx) {
return ctx.event === void 0 && evt.target !== void 0 && evt.target.draggable !== true && typeof ctx.handler === "function" && evt.target.nodeName.toUpperCase() !== "INPUT" && (evt.qClonedBy === void 0 || evt.qClonedBy.indexOf(ctx.uid) === -1);
}
function getChanges(evt, ctx, isFinal) {
const pos = position(evt);
let dir, distX = pos.left - ctx.event.x, distY = pos.top - ctx.event.y, absX = Math.abs(distX), absY = Math.abs(distY);
const direction = ctx.direction;
if (direction.horizontal === true && direction.vertical !== true) {
dir = distX < 0 ? "left" : "right";
} else if (direction.horizontal !== true && direction.vertical === true) {
dir = distY < 0 ? "up" : "down";
} else if (direction.up === true && distY < 0) {
dir = "up";
if (absX > absY) {
if (direction.left === true && distX < 0) {
dir = "left";
} else if (direction.right === true && distX > 0) {
dir = "right";
}
}
} else if (direction.down === true && distY > 0) {
dir = "down";
if (absX > absY) {
if (direction.left === true && distX < 0) {
dir = "left";
} else if (direction.right === true && distX > 0) {
dir = "right";
}
}
} else if (direction.left === true && distX < 0) {
dir = "left";
if (absX < absY) {
if (direction.up === true && distY < 0) {
dir = "up";
} else if (direction.down === true && distY > 0) {
dir = "down";
}
}
} else if (direction.right === true && distX > 0) {
dir = "right";
if (absX < absY) {
if (direction.up === true && distY < 0) {
dir = "up";
} else if (direction.down === true && distY > 0) {
dir = "down";
}
}
}
let synthetic = false;
if (dir === void 0 && isFinal === false) {
if (ctx.event.isFirst === true || ctx.event.lastDir === void 0) {
return {};
}
dir = ctx.event.lastDir;
synthetic = true;
if (dir === "left" || dir === "right") {
pos.left -= distX;
absX = 0;
distX = 0;
} else {
pos.top -= distY;
absY = 0;
distY = 0;
}
}
return {
synthetic,
payload: {
evt,
touch: ctx.event.mouse !== true,
mouse: ctx.event.mouse === true,
position: pos,
direction: dir,
isFirst: ctx.event.isFirst,
isFinal: isFinal === true,
duration: Date.now() - ctx.event.time,
distance: {
x: absX,
y: absY
},
offset: {
x: distX,
y: distY
},
delta: {
x: pos.left - ctx.event.lastX,
y: pos.top - ctx.event.lastY
}
}
};
}
let uid = 0;
var TouchPan = exports('TouchPan', createDirective({
name: "touch-pan",
beforeMount(el, { value, modifiers }) {
if (modifiers.mouse !== true && platform().hasTouch !== true) {
return;
}
function handleEvent(evt, mouseEvent) {
if (modifiers.mouse === true && mouseEvent === true) {
stopAndPrevent(evt);
} else {
modifiers.stop === true && stop(evt);
modifiers.prevent === true && prevent(evt);
}
}
const ctx = {
uid: "qvtp_" + uid++,
handler: value,
modifiers,
direction: getModifierDirections(modifiers),
noop,
mouseStart(evt) {
if (shouldStart(evt, ctx) && leftClick(evt)) {
addEvt(ctx, "temp", [
[document, "mousemove", "move", "notPassiveCapture"],
[document, "mouseup", "end", "passiveCapture"]
]);
ctx.start(evt, true);
}
},
touchStart(evt) {
if (shouldStart(evt, ctx)) {
const target = evt.target;
addEvt(ctx, "temp", [
[target, "touchmove", "move", "notPassiveCapture"],
[target, "touchcancel", "end", "passiveCapture"],
[target, "touchend", "end", "passiveCapture"]
]);
ctx.start(evt);
}
},
start(evt, mouseEvent) {
platform().isFireFox === true && preventDraggable(el, true);
ctx.lastEvt = evt;
if (mouseEvent === true || modifiers.stop === true) {
if (ctx.direction.all !== true && // account for UMD too where modifiers will be lowercased to work
(mouseEvent !== true || ctx.modifiers.mouseAllDir !== true && ctx.modifiers.mousealldir !== true)) {
const clone = evt.type.indexOf("mouse") > -1 ? new MouseEvent(evt.type, evt) : new TouchEvent(evt.type, evt);
evt.defaultPrevented === true && prevent(clone);
evt.cancelBubble === true && stop(clone);
Object.assign(clone, {
qKeyEvent: evt.qKeyEvent,
qClickOutside: evt.qClickOutside,
qAnchorHandled: evt.qAnchorHandled,
qClonedBy: evt.qClonedBy === void 0 ? [ctx.uid] : evt.qClonedBy.concat(ctx.uid)
});
ctx.initialEvent = {
target: evt.target,
event: clone
};
}
stop(evt);
}
const { left, top } = position(evt);
ctx.event = {
x: left,
y: top,
time: Date.now(),
mouse: mouseEvent === true,
detected: false,
isFirst: true,
isFinal: false,
lastX: left,
lastY: top
};
},
move(evt) {
if (ctx.event === void 0) {
return;
}
const pos = position(evt), distX = pos.left - ctx.event.x, distY = pos.top - ctx.event.y;
if (distX === 0 && distY === 0) {
return;
}
ctx.lastEvt = evt;
const isMouseEvt = ctx.event.mouse === true;
const start = () => {
handleEvent(evt, isMouseEvt);
let cursor;
if (modifiers.preserveCursor !== true && modifiers.preservecursor !== true) {
cursor = document.documentElement.style.cursor || "";
document.documentElement.style.cursor = "grabbing";
}
isMouseEvt === true && document.body.classList.add("no-pointer-events--children");
document.body.classList.add("non-selectable");
clearSelection();
ctx.styleCleanup = (withDelayedFn) => {
ctx.styleCleanup = void 0;
if (cursor !== void 0) {
document.documentElement.style.cursor = cursor;
}
document.body.classList.remove("non-selectable");
if (isMouseEvt === true) {
const remove = () => {
document.body.classList.remove("no-pointer-events--children");
};
if (withDelayedFn !== void 0) {
setTimeout(() => {
remove();
withDelayedFn();
}, 50);
} else {
remove();
}
} else if (withDelayedFn !== void 0) {
withDelayedFn();
}
};
};
if (ctx.event.detected === true) {
ctx.event.isFirst !== true && handleEvent(evt, ctx.event.mouse);
const { payload, synthetic } = getChanges(evt, ctx, false);
if (payload !== void 0) {
if (ctx.handler(payload) === false) {
ctx.end(evt);
} else {
if (ctx.styleCleanup === void 0 && ctx.event.isFirst === true) {
start();
}
ctx.event.lastX = payload.position.left;
ctx.event.lastY = payload.position.top;
ctx.event.lastDir = synthetic === true ? void 0 : payload.direction;
ctx.event.isFirst = false;
}
}
return;
}
if (ctx.direction.all === true || // account for UMD too where modifiers will be lowercased to work
isMouseEvt === true && (ctx.modifiers.mouseAllDir === true || ctx.modifiers.mousealldir === true)) {
start();
ctx.event.detected = true;
ctx.move(evt);
return;
}
const absX = Math.abs(distX), absY = Math.abs(distY);
if (absX !== absY) {
if (ctx.direction.horizontal === true && absX > absY || ctx.direction.vertical === true && absX < absY || ctx.direction.up === true && absX < absY && distY < 0 || ctx.direction.down === true && absX < absY && distY > 0 || ctx.direction.left === true && absX > absY && distX < 0 || ctx.direction.right === true && absX > absY && distX > 0) {
ctx.event.detected = true;
ctx.move(evt);
} else {
ctx.end(evt, true);
}
}
},
end(evt, abort) {
if (ctx.event === void 0) {
return;
}
cleanEvt(ctx, "temp");
platform().isFireFox === true && preventDraggable(el, false);
if (abort === true) {
ctx.styleCleanup !== void 0 && ctx.styleCleanup();
if (ctx.event.detected !== true && ctx.initialEvent !== void 0) {
ctx.initialEvent.target.dispatchEvent(ctx.initialEvent.event);
}
} else if (ctx.event.detected === true) {
ctx.event.isFirst === true && ctx.handler(getChanges(evt === void 0 ? ctx.lastEvt : evt, ctx).payload);
const { payload } = getChanges(evt === void 0 ? ctx.lastEvt : evt, ctx, true);
const fn = () => {
ctx.handler(payload);
};
if (ctx.styleCleanup !== void 0) {
ctx.styleCleanup(fn);
} else {
fn();
}
}
ctx.event = void 0;
ctx.initialEvent = void 0;
ctx.lastEvt = void 0;
}
};
el.__qtouchpan = ctx;
if (modifiers.mouse === true) {
const capture = modifiers.mouseCapture === true || modifiers.mousecapture === true ? "Capture" : "";
addEvt(ctx, "main", [[el, "mousedown", "mouseStart", `passive${capture}`]]);
}
platform().hasTouch === true && addEvt(ctx, "main", [
[el, "touchstart", "touchStart", `passive${modifiers.capture === true ? "Capture" : ""}`],
[el, "touchmove", "noop", "notPassiveCapture"]
// cannot be passive (ex: iOS scroll)
]);
},
updated(el, bindings) {
const ctx = el.__qtouchpan;
if (ctx !== void 0) {
if (bindings.oldValue !== bindings.value) {
typeof bindings.value !== "function" && ctx.end();
ctx.handler = bindings.value;
}
ctx.direction = getModifierDirections(bindings.modifiers);
}
},
beforeUnmount(el) {
const ctx = el.__qtouchpan;
if (ctx !== void 0) {
ctx.event !== void 0 && ctx.end();
cleanEvt(ctx, "main");
cleanEvt(ctx, "temp");
platform().isFireFox === true && preventDraggable(el, false);
ctx.styleCleanup !== void 0 && ctx.styleCleanup();
delete el.__qtouchpan;
}
}
}));
function defer() {
let resolve;
let reject;
const promise = new Promise(function(res, rej) {
resolve = res;
reject = rej;
});
return {
resolve,
reject,
promise
};
}
function useHandler($services, {
handleMouseClick = void 0,
handleMouseDown = void 0,
handleMouseUp = void 0,
handleMouseMove = void 0,
handleDoubleClick = void 0,
handleMouseWheel = void 0,
handlePinch = void 0
}) {
const handler = ref(void 0);
const isActive = ref(false);
const activate = () => {
if (isActive.value) {
return;
}
const { ScreenSpaceEventType, KeyboardEventModifier, ScreenSpaceEventHandler } = Cesium;
if (!handler.value) {
const { viewer } = $services;
handler.value = new ScreenSpaceEventHandler(viewer.canvas);
TouchHold.beforeMount(viewer.canvas, {
arg: "2000",
value: onTouchHold,
touchStart: onTouchStart,
touchEnd: onTouchEnd,
modifiers: {}
});
}
const sseh = handler.value;
sseh.setInputAction(onLeftClick, ScreenSpaceEventType.LEFT_CLICK);
sseh.setInputAction(onLeftClickShift, ScreenSpaceEventType.LEFT_CLICK, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onLeftClickCtrl, ScreenSpaceEventType.LEFT_CLICK, KeyboardEventModifier.CTRL);
sseh.setInputAction(onLeftDown, ScreenSpaceEventType.LEFT_DOWN);
sseh.setInputAction(onLeftDownShift, ScreenSpaceEventType.LEFT_DOWN, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onLeftDownCtrl, ScreenSpaceEventType.LEFT_DOWN, KeyboardEventModifier.CTRL);
sseh.setInputAction(onLeftUp, ScreenSpaceEventType.LEFT_UP);
sseh.setInputAction(onLeftUpShift, ScreenSpaceEventType.LEFT_UP, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onLeftUpCtrl, ScreenSpaceEventType.LEFT_UP, KeyboardEventModifier.CTRL);
sseh.setInputAction(onRightClick, ScreenSpaceEventType.RIGHT_CLICK);
sseh.setInputAction(onRightClickShift, ScreenSpaceEventType.RIGHT_CLICK, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onRightClickCtrl, ScreenSpaceEventType.RIGHT_CLICK, KeyboardEventModifier.CTRL);
sseh.setInputAction(onRightDown, ScreenSpaceEventType.RIGHT_DOWN);
sseh.setInputAction(onRightDownShift, ScreenSpaceEventType.RIGHT_DOWN, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onRightDownCtrl, ScreenSpaceEventType.RIGHT_DOWN, KeyboardEventModifier.CTRL);
sseh.setInputAction(onRightUp, ScreenSpaceEventType.RIGHT_UP);
sseh.setInputAction(onRightUpShift, ScreenSpaceEventType.RIGHT_UP, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onRightUpCtrl, ScreenSpaceEventType.RIGHT_UP, KeyboardEventModifier.CTRL);
sseh.setInputAction(onMiddleClick, ScreenSpaceEventType.MIDDLE_CLICK);
sseh.setInputAction(onMiddleClickShift, ScreenSpaceEventType.MIDDLE_CLICK, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onMiddleClickCtrl, ScreenSpaceEventType.MIDDLE_CLICK, KeyboardEventModifier.CTRL);
sseh.setInputAction(onMiddleDown, ScreenSpaceEventType.MIDDLE_DOWN);
sseh.setInputAction(onMiddleDownShift, ScreenSpaceEventType.MIDDLE_DOWN, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onMiddleDownCtrl, ScreenSpaceEventType.MIDDLE_DOWN, KeyboardEventModifier.CTRL);
sseh.setInputAction(onMiddleUp, ScreenSpaceEventType.MIDDLE_UP);
sseh.setInputAction(onMiddleUpShift, ScreenSpaceEventType.MIDDLE_UP, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onMiddleUpCtrl, ScreenSpaceEventType.MIDDLE_UP, KeyboardEventModifier.CTRL);
sseh.setInputAction(onDoubleClick, ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
sseh.setInputAction(onDoubleClickShift, ScreenSpaceEventType.LEFT_DOUBLE_CLICK, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onDoubleClickCtrl, ScreenSpaceEventType.LEFT_DOUBLE_CLICK, KeyboardEventModifier.CTRL);
sseh.setInputAction(onMouseMove, ScreenSpaceEventType.MOUSE_MOVE);
sseh.setInputAction(onMouseMoveShift, ScreenSpaceEventType.MOUSE_MOVE, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onMouseMoveCtrl, ScreenSpaceEventType.MOUSE_MOVE, KeyboardEventModifier.CTRL);
sseh.setInputAction(onMouseWheel, ScreenSpaceEventType.WHEEL);
sseh.setInputAction(onMouseWheelShift, ScreenSpaceEventType.WHEEL, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onMouseWheelCtrl, ScreenSpaceEventType.WHEEL, KeyboardEventModifier.CTRL);
sseh.setInputAction(onPinchStart, ScreenSpaceEventType.PINCH_START);
sseh.setInputAction(onPinchStartShift, ScreenSpaceEventType.PINCH_START, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onPinchStartCtrl, ScreenSpaceEventType.PINCH_START, KeyboardEventModifier.CTRL);
sseh.setInputAction(onPinchEnd, ScreenSpaceEventType.PINCH_END);
sseh.setInputAction(onPinchEndShift, ScreenSpaceEventType.PINCH_END, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onPinchEndCtrl, ScreenSpaceEventType.PINCH_END, KeyboardEventModifier.CTRL);
sseh.setInputAction(onPinchMove, ScreenSpaceEventType.PINCH_MOVE);
sseh.setInputAction(onPinchMoveShift, ScreenSpaceEventType.PINCH_MOVE, KeyboardEventModifier.SHIFT);
sseh.setInputAction(onPinchMoveCtrl, ScreenSpaceEventType.PINCH_MOVE, KeyboardEventModifier.CTRL);
isActive.value = true;
};
const deactivate = () => {
if (!isActive.value) {
return;
}
const { ScreenSpaceEventType, KeyboardEventModifier } = Cesium;
const sseh = handler.value;
if (!sseh) {
return;
}
sseh.removeInputAction(ScreenSpaceEventType.LEFT_CLICK);
sseh.removeInputAction(ScreenSpaceEventType.LEFT_CLICK, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.LEFT_CLICK, KeyboardEventModifier.CTRL);
sseh.removeInputAction(ScreenSpaceEventType.LEFT_DOWN);
sseh.removeInputAction(ScreenSpaceEventType.LEFT_DOWN, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.LEFT_DOWN, KeyboardEventModifier.CTRL);
sseh.removeInputAction(ScreenSpaceEventType.LEFT_UP);
sseh.removeInputAction(ScreenSpaceEventType.LEFT_UP, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.LEFT_UP, KeyboardEventModifier.CTRL);
sseh.removeInputAction(ScreenSpaceEventType.RIGHT_CLICK);
sseh.removeInputAction(ScreenSpaceEventType.RIGHT_CLICK, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.RIGHT_CLICK, KeyboardEventModifier.CTRL);
sseh.removeInputAction(ScreenSpaceEventType.RIGHT_DOWN);
sseh.removeInputAction(ScreenSpaceEventType.RIGHT_DOWN, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.RIGHT_DOWN, KeyboardEventModifier.CTRL);
sseh.removeInputAction(ScreenSpaceEventType.RIGHT_UP);
sseh.removeInputAction(ScreenSpaceEventType.RIGHT_UP, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.RIGHT_UP, KeyboardEventModifier.CTRL);
sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_CLICK);
sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_CLICK, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_CLICK, KeyboardEventModifier.CTRL);
sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_DOWN);
sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_DOWN, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_DOWN, KeyboardEventModifier.CTRL);
sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_UP);
sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_UP, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_UP, KeyboardEventModifier.CTRL);
sseh.removeInputAction(ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
sseh.removeInputAction(ScreenSpaceEventType.LEFT_DOUBLE_CLICK, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.LEFT_DOUBLE_CLICK, KeyboardEventModifier.CTRL);
sseh.removeInputAction(ScreenSpaceEventType.MOUSE_MOVE);
sseh.removeInputAction(ScreenSpaceEventType.MOUSE_MOVE, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.MOUSE_MOVE, KeyboardEventModifier.CTRL);
sseh.removeInputAction(ScreenSpaceEventType.WHEEL);
sseh.removeInputAction(ScreenSpaceEventType.WHEEL, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.WHEEL, KeyboardEventModifier.CTRL);
sseh.removeInputAction(ScreenSpaceEventType.PINCH_START);
sseh.removeInputAction(ScreenSpaceEventType.PINCH_START, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.PINCH_START, KeyboardEventModifier.CTRL);
sseh.removeInputAction(ScreenSpaceEventType.PINCH_END);
sseh.removeInputAction(ScreenSpaceEventType.PINCH_END, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.PINCH_END, KeyboardEventModifier.CTRL);
sseh.removeInputAction(ScreenSpaceEventType.PINCH_MOVE);
sseh.removeInputAction(ScreenSpaceEventType.PINCH_MOVE, KeyboardEventModifier.SHIFT);
sseh.removeInputAction(ScreenSpaceEventType.PINCH_MOVE, KeyboardEventModifier.CTRL);
const { viewer } = $services;
TouchHold.beforeUnmount(viewer.canvas);
isActive.value = false;
};
const destroy = () => {
var _a;
(_a = handler.value) == null ? void 0 : _a.destroy();
handler.value = void 0;
};
const onLeftClick = (movement) => {
handleMouseClick == null ? void 0 : handleMouseClick(movement, {
button: 0
});
};
const onLeftClickShift = (movement) => {
handleMouseClick == null ? void 0 : handleMouseClick(movement, {
button: 0,
shift: true
});
};
const onLeftClickCtrl = (movement) => {
handleMouseClick == null ? void 0 : handleMouseClick(movement, {
button: 0,
ctrl: true
});
};
const onMiddleClick = (movement) => {
handleMouseClick == null ? void 0 : handleMouseClick(movement, {
button: 1
});
};
const onMiddleClickShift = (movement) => {
handleMouseClick == null ? void 0 : handleMouseClick(movement, {
button: 1,
shift: true
});
};
const onMiddleClickCtrl = (movement) => {
handleMouseClick == null ? void 0 : handleMouseClick(movement, {
button: 1,
ctrl: true
});
};
let touchPromise = void 0;
const onRightClick = (movement) => {
var _a;
if (touchPromise) {
(_a = touchPromise == null ? void 0 : touchPromise.promise) == null ? void 0 : _a.then((flag) => {
flag && (handleMouseClick == null ? void 0 : handleMouseClick(movement, {
button: 2
}));
});
} else {
handleMouseClick == null ? void 0 : handleMouseClick(movement, {
button: 2
});
}
};
const onRightClickShift = (movement) => {
handleMouseClick == null ? void 0 : handleMouseClick(movement, {
button: 2,
shift: true
});
};
const onRightClickCtrl = (movement) => {
handleMouseClick == null ? void 0 : handleMouseClick(movement, {
button: 2,
ctrl: true
});
};
const onLeftDown = (movement) => {
handleMouseDown == null ? void 0 : handleMouseDown(movement, {
button: 0
});
};
const onLeftDownShift = (movement) => {
handleMouseDown == null ? void 0 : handleMouseDown(movement, {
button: 0,
shift: true
});
};
const onLeftDownCtrl = (movement) => {
handleMouseDown == null ? void 0 : handleMouseDown(movement, {
button: 0,
ctrl: true
});
};
const onMiddleDown = (movement) => {
handleMouseDown == null ? void 0 : handleMouseDown(movement, {
button: 1
});
};
const onMiddleDownShift = (movement) => {
handleMouseDown == null ? void 0 : handleMouseDown(movement, {
button: 1,
shift: true
});
};
const onMiddleDownCtrl = (movement) => {
handleMouseDown == null ? void 0 : handleMouseDown(movement, {
button: 1,
ctrl: true
});
};
const onRightDown = (movement) => {
handleMouseDown == null ? void 0 : handleMouseDown(movement, {
button: 2
});
};
const onRightDownShift = (movement) => {
handleMouseDown == null ? void 0 : handleMouseDown(movement, {
button: 2,
shift: true
});
};
const onRightDownCtrl = (movement) => {
handleMouseDown == null ? void 0 : handleMouseDown(movement, {
button: 2,
ctrl: true
});
};
const onLeftUp = (movement) => {
handleMouseUp == null ? void 0 : handleMouseUp(movement, {
button: 0
});
};
const onLeftUpShift = (movement) => {
handleMouseUp == null ? void 0 : handleMouseUp(movement, {
button: 0,
shift: true
});
};
const onLeftUpCtrl = (movement) => {
handleMouseUp == null ? void 0 : handleMouseUp(movement, {
button: 0,
ctrl: true
});
};
const onMiddleUp = (movement) => {
handleMouseUp == null ? void 0 : handleMouseUp(movement, {
button: 1,
ctrl: true
});
};
const onMiddleUpShift = (movement) => {
handleMouseUp == null ? void 0 : handleMouseUp(movement, {
button: 1,
shift: true
});
};
const onMiddleUpCtrl = (movement) => {
handleMouseUp == null ? void 0 : handleMouseUp(movement, {
button: 1,
ctrl: true
});
};
const onRightUp = (movement) => {
handleMouseUp == null ? void 0 : handleMouseUp(movement, {
button: 2
});
};
const onRightUpShift = (movement) => {
handleMouseUp == null ? void 0 : handleMouseUp(movement, {
button: 2,
shift: true
});
};
const onRightUpCtrl = (movement) => {
handleMouseUp == null ? void 0 : handleMouseUp(movement, {
button: 2,
ctrl: true
});
};
const onDoubleClick = (movement) => {
handleDoubleClick == null ? void 0 : handleDoubleClick(movement, {
button: 0
});
};
const onDoubleClickShift = (movement) => {
handleDoubleClick == null ? void 0 : handleDoubleClick(movement, {
button: 0,
shift: true
});
};
const onDoubleClickCtrl = (movement) => {
handleDoubleClick == null ? void 0 : handleDoubleClick(movement, {
button: 0,
ctrl: true
});
};
const onMouseMove = (movement) => {
handleMouseMove == null ? void 0 : handleMouseMove(movement);
};
const onMouseMoveShift = (movement) => {
handleMouseMove == null ? void 0 : handleMouseMove(movement, {
shift: true
});
};
const onMouseMoveCtrl = (movement) => {
handleMouseMove == null ? void 0 : handleMouseMove(movement, {
ctrl: true
});
};
const onMouseWheel = (e) => {
handleMouseWheel == null ? void 0 : handleMouseWheel(e);
};
const onMouseWheelShift = (e) => {
handleMouseWheel == null ? void 0 : handleMouseWheel(e, {
shift: true
});
};
const onMouseWheelCtrl = (e) => {
handleMouseWheel == null ? void 0 : handleMouseWheel(e, {
ctrl: true
});
};
const onPinchStart = (e) => {
handlePinch == null ? void 0 : handlePinch(e, {
start: true
});
};
const onPinchStartShift = (e) => {
handlePinch == null ? void 0 : handlePinch(e, {
start: true,
shift: true
});
};
const onPinchStartCtrl = (e) => {
handlePinch == null ? void 0 : handlePinch(e, {
start: true,
ctrl: true
});
};
const onPinchEnd = (e) => {
handlePinch == null ? void 0 : handlePinch(e, {
end: true
});
};
const onPinchEndShift = (e) => {
handlePinch == null ? void 0 : handlePinch(e, {
end: true,
shift: true
});
};
const onPinchEndCtrl = (e) => {
handlePinch == null ? void 0 : handlePinch(e, {
end: true,
ctrl: true
});
};
const onPinchMove = (e) => {
handlePinch == null ? void 0 : handlePinch(e, {
move: true
});
};
const onPinchMoveShift = (e) => {
handlePinch == null ? void 0 : handlePinch(e, {
move: true,
shift: true
});
};
const onPinchMoveCtrl = (e) => {
handlePinch == null ? void 0 : handlePinch(e, {
move: true,
ctrl: true
});
};
const onTouchHold = (e) => {
if (e.touch) {
const movement = {
position: {
x: e.position.left,
y: e.position.top
}
};
handleDoubleClick == null ? void 0 : handleDoubleClick(movement, {
button: 0
});
}
touchPromise.resolve(false);
};
const onTouchEnd = (e) => {
touchPromise.resolve(true);
};
const onTouchStart = (e) => {
touchPromise = defer();
};
return {
activate,
deactivate,
destroy,
isActive
};
}
function usePrimitiveCollectionItems(props, ctx, vcInstance) {
const commonState = useCommon(props, ctx, vcInstance);
if (commonState === void 0) {
return;
}
vcInstance.createCesiumObject = async () => {
const options = commonState.transformProps(props);
const primitives = commonState.$services.primitives;
return primitives && primitives.add(options);
};
vcInstance.mount = async () => {
const primitives = commonState.$services.primitives;
const collectionItem = vcInstance.cesiumObject;
return primitives && primitives.contains(collectionItem);
};
vcInstance.unmount = async () => {
const primitives = commonState.$services.primitives;
const collectionItem = vcInstance.cesiumObject;
return primitives && !primitives.isDestroyed() && primitives.remove(collectionItem);
};
return {
transformProps: commonState.transformProps,
unwatchFns: commonState.unwatchFns,
setPropsWatcher: commonState.setPropsWatcher,
$services: commonState.$services
};
}
function usePrimitiveCollections(props, ctx, vcInstance) {
vcInstance.cesiumEvents = ["primitiveAdded", "primitiveRemoved"];
const commonState = useCommon(props, ctx, vcInstance);
if (commonState === void 0) {
return;
}
vcInstance.mount = async () => {
const primitives = commonState.$services.primitives;
const collection = vcInstance.cesiumObject;
const object = primitives && primitives.add(collection);
return Cesium.defined(object);
};
vcInstance.unmount = async () => {
const primitives = commonState.$services.primitives;
const collection = vcInstance.cesiumObject;
return primitives && primitives.remove(collection);
};
const getServices = () => {
return mergeDescriptors(commonState.getServices(), {
get primitives() {
return vcInstance.cesiumObject;
}
});
};
provide(vcKey, getServices());
return {
transformProps: commonState.transformProps,
transformProp: commonState.transformProp,
unwatchFns: commonState.unwatchFns,
setPropsWatcher: commonState.setPropsWatcher
};
}
function usePrimitives(props, ctx, vcInstance) {
const commonState = useCommon(props, ctx, vcInstance);
if (commonState === void 0) {
return;
}
const { emit } = ctx;
const childCount = ref(0);
const instances = ref([]);
vcInstance.createCesiumObject = async () => {
var _a, _b;
const options = commonState.transformProps(props);
if (!options.asynchronous) {
await ((_b = (_a = Cesium[vcInstance.cesiumClass]).initializeTerrainHeights) == null ? void 0 : _b.call(_a));
}
if (props.geometryInstances) {
if (isArray(props.geometryInstances)) {
instances.value.push(...props.geometryInstances);
childCount.value += props.geometryInstances.length;
} else {
childCount.value += 1;
instances.value.push(props.geometryInstances);
}
}
if ((vcInstance.cesiumClass === "Cesium3DTileset" || vcInstance.cesiumClass === "I3SDataProvider") && compareCesiumVersion(Cesium.VERSION, "1.104")) {
try {
if (Cesium.defined(props.assetId) && vcInstance.cesiumClass === "Cesium3DTileset") {
return await Cesium[vcInstance.cesiumClass].fromIonAssetId(props.assetId, options);
} else {
return await Cesium[vcInstance.cesiumClass].fromUrl(props.url, options);
}
} catch (error) {
commonState.logger.error(`Failed to load tileset: ${error}`);
}
} else {
return new Cesium[vcInstance.cesiumClass](options);
}
};
vcInstance.mount = async () => {
var _a;
const primitives = commonState.$services.primitives;
const primitive = vcInstance.cesiumObject;
(_a = primitive == null ? void 0 : primitive.readyPromise) == null ? void 0 : _a.then((e) => {
const listener = getInstanceListener(vcInstance, "readyPromise");
listener && emit("readyPromise", e, commonState.$services.viewer, vcInstance.proxy);
});
primitive._vcParent = primitives;
const object = primitives && primitives.add(primitive);
if (vcInstance.cesiumClass === "ParticleSystem") {
const intervalId = setInterval(() => {
if (Cesium.defined(object._billboardCollection)) {
object._billboardCollection._vcParent = object;
clearInterval(intervalId);
}
}, 500);
}
return Cesium.defined(object);
};
vcInstance.unmount = async () => {
childCount.value = 0;
instances.value = [];
const primitives = commonState.$services.primitives;
const primitive = vcInstance.cesiumObject;
return primitives && primitives.remove(primitive);
};
const updateGeometryInstances = (instance, index) => {
instances.value.push(instance);
if (index === childCount.value - 1) {
const listener = getInstanceListener(vcInstance, "update:geometryInstances");
if (listener) {
ctx.emit("update:geometryInstances", instances.value);
} else {
const primitive = vcInstance.cesiumObject;
primitive.geometryInstances = index === 0 ? instance : instances.value;
}
}
return true;
};
const removeGeometryInstances = (instance) => {
const index = instances.value.indexOf(instance);
instances.value.splice(index, 1);
return true;
};
const getServices = () => {
return mergeDescriptors(commonState.getServices(), {
get primitive() {
return vcInstance.cesiumObject;
}
});
};
provide(vcKey, getServices());
Object.assign(vcInstance.proxy, {
// private but needed by VcGeometryInstance
__updateGeometryInstances: updateGeometryInstances,
__removeGeometryInstances: removeGeometryInstances,
__childCount: childCount
});
return {
transformProps: commonState.transformProps,
transformProp: commonState.transformProp,
unwatchFns: commonState.unwatchFns,
setPropsWatcher: commonState.setPropsWatcher,
$services: commonState.$services
};
}
const x_PI = 3.141592653589793 * 3e3 / 180;
const PI = 3.141592653589793;
const a = 6378245;
const ee = 0.006693421622965943;
const bd09togcj02 = function bd09togcj022(bd_lng, bd_lat) {
var bd_lng = +bd_lng;
var bd_lat = +bd_lat;
const x = bd_lng - 65e-4;
const y = bd_lat - 6e-3;
const z = Math.sqrt(x * x + y * y) - 2e-5 * Math.sin(y * x_PI);
const theta = Math.atan2(y, x) - 3e-6 * Math.cos(x * x_PI);
const gg_lng = z * Math.cos(theta);
const gg_lat = z * Math.sin(theta);
return [gg_lng, gg_lat];
};
const gcj02tobd09 = function gcj02tobd092(lng, lat) {
var lat = +lat;
var lng = +lng;
const z = Math.sqrt(lng * lng + lat * lat) + 2e-5 * Math.sin(lat * x_PI);
const theta = Math.atan2(lat, lng) + 3e-6 * Math.cos(lng * x_PI);
const bd_lng = z * Math.cos(theta) + 65e-4;
const bd_lat = z * Math.sin(theta) + 6e-3;
return [bd_lng, bd_lat];
};
const wgs84togcj02 = function wgs84togcj022(lng, lat) {
var lat = +lat;
var lng = +lng;
if (out_of_china(lng, lat)) {
return [lng, lat];
} else {
let dlat = transformlat(lng - 105, lat - 35);
let dlng = transformlng(lng - 105, lat - 35);
const radlat = lat / 180 * PI;
let magic = Math.sin(radlat);
magic = 1 - ee * magic * magic;
const sqrtmagic = Math.sqrt(magic);
dlat = dlat * 180 / (a * (1 - ee) / (magic * sqrtmagic) * PI);
dlng = dlng * 180 / (a / sqrtmagic * Math.cos(radlat) * PI);
const mglat = lat + dlat;
const mglng = lng + dlng;
return [mglng, mglat];
}
};
const gcj02towgs84 = function gcj02towgs842(lng, lat) {
var lat = +lat;
var lng = +lng;
if (out_of_china(lng, lat)) {
return [lng, lat];
} else {
let dlat = transformlat(lng - 105, lat - 35);
let dlng = transformlng(lng - 105, lat - 35);
const radlat = lat / 180 * PI;
let magic = Math.sin(radlat);
magic = 1 - ee * magic * magic;
const sqrtmagic = Math.sqrt(magic);
dlat = dlat * 180 / (a * (1 - ee) / (magic * sqrtmagic) * PI);
dlng = dlng * 180 / (a / sqrtmagic * Math.cos(radlat) * PI);
const mglat = lat + dlat;
const mglng = lng + dlng;
return [lng * 2 - mglng, lat * 2 - mglat];
}
};
var transformlat = function transformlat2(lng, lat) {
var lat = +lat;
var lng = +lng;
let ret = -100 + 2 * lng + 3 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
ret += (20 * Math.sin(6 * lng * PI) + 20 * Math.sin(2 * lng * PI)) * 2 / 3;
ret += (20 * Math.sin(lat * PI) + 40 * Math.sin(lat / 3 * PI)) * 2 / 3;
ret += (160 * Math.sin(lat / 12 * PI) + 320 * Math.sin(lat * PI / 30)) * 2 / 3;
return ret;
};
var transformlng = function transformlng2(lng, lat) {
var lat = +lat;
var lng = +lng;
let ret = 300 + lng + 2 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
ret += (20 * Math.sin(6 * lng * PI) + 20 * Math.sin(2 * lng * PI)) * 2 / 3;
ret += (20 * Math.sin(lng * PI) + 40 * Math.sin(lng / 3 * PI)) * 2 / 3;
ret += (150 * Math.sin(lng / 12 * PI) + 300 * Math.sin(lng / 30 * PI)) * 2 / 3;
return ret;
};
var out_of_china = function out_of_china2(lng, lat) {
var lat = +lat;
var lng = +lng;
return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55);
};
var coordtransform = /*#__PURE__*/Object.freeze({
__proto__: null,
bd09togcj02: bd09togcj02,
gcj02tobd09: gcj02tobd09,
wgs84togcj02: wgs84togcj02,
gcj02towgs84: gcj02towgs84
});
function useProviders(props, ctx, vcInstance) {
vcInstance.cesiumEvents = ["errorEvent"];
const commonState = useCommon(props, ctx, vcInstance);
if (commonState === void 0) {
return;
}
const { emit } = ctx;
vcInstance.createCesiumObject = async () => {
const options = commonState.transformProps(props);
if (compareCesiumVersion(Cesium.VERSION, "1.104") && typeof Cesium[vcInstance.cesiumClass].fromUrl === "function") {
return await Cesium[vcInstance.cesiumClass].fromUrl(options.url, options);
} else {
return new Cesium[vcInstance.cesiumClass](options);
}
};
vcInstance.mount = async () => {
var _a, _b, _c, _d, _e;
const { viewer } = commonState.$services;
if (vcInstance.cesiumClass.indexOf("ImageryProvider") !== -1) {
vcInstance.renderByParent = true;
const imageryProvider = vcInstance.cesiumObject;
(_a = imageryProvider == null ? void 0 : imageryProvider.readyPromise) == null ? void 0 : _a.then(() => {
const listener = getInstanceListener(vcInstance, "readyPromise");
listener && emit("readyPromise", imageryProvider, viewer, vcInstance.proxy);
});
if (props.projectionTransforms && props.projectionTransforms.from !== props.projectionTransforms.to) {
const ignoreTransforms = ((_b = vcInstance.proxy) == null ? void 0 : _b.$options.name) === "VcImageryProviderBaidu" || ((_c = vcInstance.proxy) == null ? void 0 : _c.$options.name) === "VcImageryProviderTianditu" && imageryProvider._epsgCode === "4490";
if (!ignoreTransforms) {
const { WebMercatorTilingScheme, Cartographic, Math: CesiumMath } = Cesium;
const tilingScheme = new WebMercatorTilingScheme();
const projection = tilingScheme.projection;
const nativeProject = projection.project;
const nativeUnProject = projection.unproject;
let projectMethods;
let unprojectMethods;
if (props.projectionTransforms.to.toUpperCase() === "WGS84") {
projectMethods = "wgs84togcj02";
unprojectMethods = "gcj02towgs84";
} else if (props.projectionTransforms.to.toUpperCase() === "GCJ02") {
projectMethods = "gcj02towgs84";
unprojectMethods = "wgs84togcj02";
}
if (projectMethods && unprojectMethods) {
projection.project = function(cartographic, result) {
result = result || new Cesium.Cartesian3();
result = coordtransform[projectMethods](CesiumMath.toDegrees(cartographic.longitude), CesiumMath.toDegrees(cartographic.latitude));
return nativeProject.call(this, new Cartographic(CesiumMath.toRadians(result == null ? void 0 : result[0]), CesiumMath.toRadians(result == null ? void 0 : result[1])));
};
projection.unproject = function(cartesian2, result) {
result = result || new Cartographic();
const cartographic = nativeUnProject.call(this, cartesian2);
result = coordtransform[unprojectMethods](CesiumMath.toDegrees(cartographic.longitude), CesiumMath.toDegrees(cartographic.latitude));
return new Cartographic(CesiumMath.toRadians(result == null ? void 0 : result[0]), CesiumMath.toRadians(result == null ? void 0 : result[1]));
};
imageryProvider._tilingScheme = tilingScheme;
}
}
}
const parentVM = getVcParentInstance(vcInstance).proxy;
return parentVM && ((_d = parentVM.__updateProvider) == null ? void 0 : _d.call(parentVM, imageryProvider));
} else {
const terrainProvider = vcInstance.cesiumObject;
(_e = terrainProvider == null ? void 0 : terrainProvider.readyPromise) == null ? void 0 : _e.then(() => {
const listener = getInstanceListener(vcInstance, "readyPromise");
listener && emit("readyPromise", terrainProvider, viewer, vcInstance.proxy);
});
viewer.terrainProvider = terrainProvider;
return true;
}
};
vcInstance.unmount = async () => {
var _a, _b;
const { viewer } = commonState.$services;
if (vcInstance.cesiumClass.indexOf("ImageryProvider") !== -1) {
const parentVM = getVcParentInstance(vcInstance).proxy;
return parentVM && ((_a = parentVM.__updateProvider) == null ? void 0 : _a.call(parentVM, void 0));
} else {
const terrainProvider = new Cesium.EllipsoidTerrainProvider();
(_b = terrainProvider == null ? void 0 : terrainProvider.readyPromise) == null ? void 0 : _b.then(() => {
const listener = getInstanceListener(vcInstance, "readyPromise");
listener && emit("readyPromise", terrainProvider, viewer, vcInstance.proxy);
});
viewer.terrainProvider = terrainProvider;
return true;
}
};
return {
transformProps: commonState.transformProps,
unwatchFns: commonState.unwatchFns,
setPropsWatcher: commonState.setPropsWatcher
};
}
function useVueCesium(containerId) {
var _a, _b, _c;
const instance = getCurrentInstance();
const provides = (instance == null ? void 0 : instance.parent) === null ? instance.vnode.appContext && instance.vnode.appContext.provides : (_a = instance == null ? void 0 : instance.parent) == null ? void 0 : _a.provides;
if ((!provides || !(vcKey in provides)) && !containerId) {
containerId = "cesiumContainer";
}
const logger = useLog();
if (instance) {
if (containerId) {
const $vc = (_c = (_b = instance.appContext.config.globalProperties) == null ? void 0 : _b.$VueCesium) == null ? void 0 : _c[containerId];
if (!$vc) {
logger.warn(`Failed to get $vc, reason: vc-viewer with containerId: ${containerId} was not found.`);
}
return $vc;
} else {
return inject(vcKey);
}
} else {
logger.warn("VueCesium useVueCesium() can only be used inside setup().");
}
}
var defaultProps$7 = {
cesiumPath: String,
animation: {
type: Boolean,
default: false
},
baseLayerPicker: {
type: Boolean,
default: false
},
fullscreenButton: {
type: Boolean,
default: false
},
vrButton: {
type: Boolean,
default: false
},
geocoder: {
type: [Boolean, Array],
default: false
},
homeButton: {
type: Boolean,
default: false
},
infoBox: {
type: Boolean,
default: true
},
sceneModePicker: {
type: Boolean,
default: false
},
selectionIndicator: {
type: Boolean,
default: true
},
timeline: {
type: Boolean,
default: false
},
navigationHelpButton: {
type: Boolean,
default: false
},
navigationInstructionsInitiallyVisible: {
type: Boolean,
default: false
},
scene3DOnly: {
type: Boolean,
default: false
},
shouldAnimate: {
type: Boolean,
default: false
},
clockViewModel: Object,
selectedImageryProviderViewModel: Object,
imageryProviderViewModels: Array,
selectedTerrainProviderViewModel: Object,
terrainProviderViewModels: Array,
imageryProvider: Object,
baseLayer: Object,
terrainProvider: Object,
skyBox: {
type: [Object, Boolean],
default: () => void 0
},
skyAtmosphere: {
type: [Object, Boolean],
default: () => void 0
},
fullscreenElement: {
type: [String, Element]
},
useDefaultRenderLoop: {
type: Boolean,
default: true
},
targetFrameRate: Number,
showRenderLoopErrors: {
type: Boolean,
default: true
},
useBrowserRecommendedResolution: {
type: Boolean,
default: true
},
automaticallyTrackDataSourceClocks: {
type: Boolean,
default: true
},
contextOptions: Object,
sceneMode: {
type: Number,
default: 3
},
mapProjection: Object,
globe: {
type: [Object, Boolean],
default: () => void 0
},
orderIndependentTranslucency: {
type: Boolean,
default: true
},
creditContainer: [String, Element],
creditViewport: [String, Element],
dataSources: Object,
terrainExaggeration: {
type: Number,
default: 1
},
shadows: {
type: Boolean,
default: false
},
terrainShadows: {
type: Number,
default: 3
},
mapMode2D: {
type: Number,
default: 1
},
projectionPicker: {
type: Boolean,
default: false
},
requestRenderMode: {
type: Boolean,
default: false
},
maximumRenderTimeChange: {
type: Number,
default: 0
},
debugShowFramesPerSecond: {
type: Boolean,
default: false
},
showCredit: {
type: Boolean,
default: true
},
accessToken: String,
camera: {
type: Object,
default: () => ({
position: {
lng: 105,
lat: 29.999999999999993,
height: 19059568497290563e-9
},
heading: 360,
pitch: -90,
roll: 0
})
},
navigation: {
// for supermap
type: Boolean,
default: false
},
TZCode: {
type: String
// default: new Date().getTimezoneOffset() === 0 ? 'UTC' : 'UTC' + '+' + -(new Date().getTimezoneOffset() / 60)
},
UTCOffset: {
type: Number
// default: new Date().getTimezoneOffset()
},
removeCesiumScript: {
type: Boolean,
default: true
},
autoSortImageryLayers: {
type: Boolean,
default: true
},
enableMouseEvent: {
type: Boolean,
default: true
},
skeleton: {
type: [Boolean, Object],
default: () => ({
dark: false,
animation: "wave",
square: true,
bordered: true,
color: void 0
})
},
touchHoldArg: {
type: String,
default: "1000"
},
viewerCreator: Function,
mars3dConfig: Object,
containerId: String
};
function getMars3dConfig() {
const libsConfig = {
"font-awesome": [
// libpath + 'fonts/font-awesome/css/font-awesome.min.css'
"https://unpkg.com/font-awesome@latest/css/font-awesome.min.css"
],
haoutil: [
// libpath + 'hao/haoutil.js'
"https://unpkg.com/haoutil@latest/dist/haoutil-src.js"
],
turf: [
// libpath + 'turf/turf.min.js'
"https://unpkg.com/@turf/turf@latest/turf.min.js"
],
"mars3d-space": [
//卫星插件
// libpath + 'mars3d/plugins/space/mars3d-space.js'
"https://unpkg.com/mars3d-space@latest/dist/mars3d-space.js"
],
"mars3d-echarts": [
//echarts支持插件
// libpath + 'echarts/echarts.min.js',
"https://unpkg.com/echarts@latest/dist/echarts.min.js",
// libpath + 'echarts/echarts-gl.min.js',
"https://unpkg.com/echarts-gl@latest/dist/echarts-gl.min.js",
// libpath + 'mars3d/plugins/echarts/mars3d-echarts.js'
"https://unpkg.com/mars3d-echarts@latest/dist/mars3d-echarts.js"
],
"mars3d-mapv": [
//mapv支持插件
// libpath + 'mapV/mapv.min.js',
"https://unpkg.com/mapv@latest/build/mapv.min.js",
// libpath + 'mars3d/plugins/mapv/mars3d-mapv.js'
"https://unpkg.com/mars3d-mapv@latest/dist/mars3d-mapv.js"
],
"mars3d-heatmap": [
//heatmap热力图支持插件
// libpath + 'mars3d/plugins/heatmap/heatmap.min.js',
"https://unpkg.com/heatmapjs@latest/heatmap.min.js",
// libpath + 'mars3d/plugins/heatmap/mars3d-heatmap.js'
"https://unpkg.com/mars3d-heatmap@latest/dist/mars3d-heatmap.js"
],
"mars3d-wind": [
//风场图层插件
// libpath + 'mars3d/plugins/wind/netcdfjs.js', //m10_windLayer解析nc
"https://unpkg.com/netcdfjs@latest/lib/index.js",
// libpath + 'mars3d/plugins/wind/mars3d-wind.js'
"https://unpkg.com/mars3d-wind@latest/dist/mars3d-wind.js"
],
"mars3d-tdt": ["https://unpkg.com/mars3d-tdt@latest/dist/mars3d-tdt.js"],
"mars3d-widget": ["https://unpkg.com/mars3d-widget@latest/dist/mars3d-widget.js"],
mars3d: [
//三维地球“主库”
// libpath + 'Cesium/Widgets/widgets.css', //cesium
"https://unpkg.com/mars3d-cesium@latest/Build/Cesium/Widgets/widgets.css",
// libpath + 'Cesium/Cesium.js',
"https://unpkg.com/mars3d-cesium@latest/Build/Cesium/Cesium.js",
// libpath + 'mars3d/mars3d.css', //mars3d
"https://unpkg.com/mars3d@latest/dist/mars3d.css",
// libpath + 'mars3d/mars3d.js'
"https://unpkg.com/mars3d@latest/dist/mars3d.js"
]
};
return libsConfig;
}
class VisibilityState {
constructor() {
this.states = new Cesium.ManagedArray();
this.count = 0;
}
hidePrimitiveCollection(primitiveCollection) {
const { PrimitiveCollection, Cesium3DTileset, Model } = Cesium;
const length = primitiveCollection.length;
for (let i = 0; i < length; i++) {
const primitive = primitiveCollection.get(i);
if (primitive instanceof PrimitiveCollection) {
this.hidePrimitiveCollection(primitive);
} else {
this.states.push(primitive.show);
primitive instanceof Cesium3DTileset || primitive instanceof Model || (primitive.show = false);
}
}
}
restorePrimitiveCollection(primitiveCollection) {
const { PrimitiveCollection } = Cesium;
const length = primitiveCollection.length;
for (let i = 0; i < length; i++) {
const primitive = primitiveCollection.get(i);
if (primitive instanceof PrimitiveCollection) {
this.restorePrimitiveCollection(primitive);
} else {
primitive.show = this.states.get(this.count++);
}
}
}
hide(scene) {
this.states.length = 0;
this.hidePrimitiveCollection(scene.primitives);
this.hidePrimitiveCollection(scene.groundPrimitives);
}
restore(scene) {
this.count = 0;
this.restorePrimitiveCollection(scene.primitives);
this.restorePrimitiveCollection(scene.groundPrimitives);
}
} exports('VisibilityState', VisibilityState);
var DrawStatus = exports('DrawStatus', {
BeforeDraw: 0,
Drawing: 1,
AfterDraw: 2
});
const DistanceUnits = exports('DistanceUnits', Object.freeze({
METERS: "METERS",
CENTIMETERS: "CENTIMETERS",
KILOMETERS: "KILOMETERS",
FEET: "FEET",
US_SURVEY_FEET: "US_SURVEY_FEET",
INCHES: "INCHES",
YARDS: "YARDS",
MILES: "MILES"
}));
const AreaUnits = exports('AreaUnits', Object.freeze({
SQUARE_METERS: "SQUARE_METERS",
SQUARE_CENTIMETERS: "SQUARE_CENTIMETERS",
SQUARE_KILOMETERS: "SQUARE_KILOMETERS",
SQUARE_FEET: "SQUARE_FEET",
SQUARE_INCHES: "SQUARE_INCHES",
SQUARE_YARDS: "SQUARE_YARDS",
SQUARE_MILES: "SQUARE_MILES",
ACRES: "ACRES",
HECTARES: "HECTARES"
}));
const VolumeUnits = exports('VolumeUnits', Object.freeze({
CUBIC_METERS: "CUBIC_METERS",
CUBIC_CENTIMETERS: "CUBIC_CENTIMETERS",
CUBIC_KILOMETERS: "CUBIC_KILOMETERS",
CUBIC_FEET: "CUBIC_FEET",
CUBIC_INCHES: "CUBIC_INCHES",
CUBIC_YARDS: "CUBIC_YARDS",
CUBIC_MILES: "CUBIC_MILES"
}));
const AngleUnits = exports('AngleUnits', Object.freeze({
DEGREES: "DEGREES",
RADIANS: "RADIANS",
DEGREES_MINUTES_SECONDS: "DEGREES_MINUTES_SECONDS",
GRADE: "GRADE",
RATIO: "RATIO"
}));
const _MeasureUnits = class _MeasureUnits {
constructor(options) {
options = defaultValue(options, {});
this.distanceUnits = defaultValue(options.distanceUnits, DistanceUnits.METERS);
this.areaUnits = defaultValue(options.areaUnits, AreaUnits.SQUARE_METERS);
this.volumeUnits = defaultValue(options.volumeUnits, VolumeUnits.CUBIC_METERS);
this.angleUnits = defaultValue(options.angleUnits, AngleUnits.DEGREES);
this.slopeUnits = defaultValue(options.slopeUnits, AngleUnits.DEGREES);
}
static distanceToString(distance, distanceUnits, locale, decimals) {
distance = _MeasureUnits.convertDistance(distance, DistanceUnits.METERS, distanceUnits);
return numberToFormattedString(distance, locale, decimals) + _MeasureUnits.getDistanceUnitSpacing(distanceUnits) + _MeasureUnits.getDistanceUnitSymbol(distanceUnits);
}
static areaToString(area, areaUnits, locale, decimals) {
area = _MeasureUnits.convertArea(area, AreaUnits.SQUARE_METERS, areaUnits);
return numberToFormattedString(area, locale, decimals) + _MeasureUnits.getAreaUnitSpacing(areaUnits) + _MeasureUnits.getAreaUnitSymbol(areaUnits);
}
static angleToString(angle, angleUnits, locale, decimals) {
const { Math: CesiumMath } = Cesium;
if (angleUnits === AngleUnits.DEGREES || angleUnits === AngleUnits.RADIANS || angleUnits === AngleUnits.GRADE) {
angle = convertAngleFromRadians(angle, angleUnits);
return numberToFormattedString(angle, locale, decimals) + _MeasureUnits.getAngleUnitSpacing(angleUnits) + _MeasureUnits.getAngleUnitSymbol(angleUnits);
}
if (angleUnits === AngleUnits.DEGREES_MINUTES_SECONDS) {
const angleDegrees = CesiumMath.toDegrees(angle);
const prefix = angleDegrees < 0 ? "-" : "";
const degrees = Math.floor(angleDegrees);
const minutes = 60 * (angleDegrees - degrees);
const seconds = Math.floor(minutes);
return prefix + degrees + "\xB0 " + seconds + "' " + numberToFormattedString(60 * (minutes - seconds), void 0, decimals) + '"';
}
if (angleUnits === AngleUnits.RATIO) ;
}
static volumeToString(volume, volumeUnits, locale, decimals) {
volume = _MeasureUnits.convertArea(volume, VolumeUnits.CUBIC_METERS, volumeUnits);
return numberToFormattedString(volume, locale, decimals) + _MeasureUnits.getVolumeUnitSpacing(volumeUnits) + _MeasureUnits.getVolumeUnitSymbol(volumeUnits);
}
static getDistanceUnitSpacing(distanceUnits) {
return " ";
}
static getAreaUnitSpacing(distanceUnits) {
return " ";
}
static getAngleUnitSpacing(angleUnits) {
return angleUnits === AngleUnits.RADIANS ? " " : "";
}
static getVolumeUnitSpacing(distanceUnits) {
return " ";
}
static getDistanceUnitSymbol(distanceUnits) {
switch (distanceUnits) {
case DistanceUnits.METERS:
return "m";
case DistanceUnits.CENTIMETERS:
return "cm";
case DistanceUnits.KILOMETERS:
return "km";
case DistanceUnits.FEET:
case DistanceUnits.US_SURVEY_FEET:
return "ft";
case DistanceUnits.INCHES:
return "in";
case DistanceUnits.YARDS:
return "yd";
case DistanceUnits.MILES:
return "mi";
default:
return void 0;
}
}
static getAreaUnitSymbol(areaUnits) {
switch (areaUnits) {
case AreaUnits.SQUARE_METERS:
return "m\xB2";
case AreaUnits.SQUARE_CENTIMETERS:
return "cm\xB2";
case AreaUnits.SQUARE_KILOMETERS:
return "km\xB2";
case AreaUnits.SQUARE_FEET:
return "sq ft";
case AreaUnits.SQUARE_INCHES:
return "sq in";
case AreaUnits.SQUARE_YARDS:
return "sq yd";
case AreaUnits.SQUARE_MILES:
return "sq mi";
case AreaUnits.ACRES:
return "ac";
case AreaUnits.HECTARES:
return "ha";
default:
return void 0;
}
}
static getVolumeUnitSymbol(volumeUnits) {
switch (volumeUnits) {
case VolumeUnits.CUBIC_METERS:
return "m\xB3";
case VolumeUnits.CUBIC_CENTIMETERS:
return "cm\xB3";
case VolumeUnits.CUBIC_KILOMETERS:
return "km\xB3";
case VolumeUnits.CUBIC_FEET:
return "cu ft";
case VolumeUnits.CUBIC_INCHES:
return "cu in";
case VolumeUnits.CUBIC_YARDS:
return "cu yd";
case VolumeUnits.CUBIC_MILES:
return "cu mi";
default:
return void 0;
}
}
static getAngleUnitSymbol(angleUnits) {
return angleUnits === AngleUnits.DEGREES ? "\xB0" : angleUnits === AngleUnits.RADIANS ? "rad" : angleUnits === AngleUnits.GRADE ? "%" : void 0;
}
static convertDistance(distance, distanceUnitsFrom, distanceUnitsTo) {
return distanceUnitsFrom === distanceUnitsTo ? distance : distance * getDistanceUnitConversion(distanceUnitsFrom) * (1 / getDistanceUnitConversion(distanceUnitsTo));
}
static convertArea(area, areaUnitsFrom, areaUnitsTo) {
return areaUnitsFrom === areaUnitsTo ? area : area * getAreaUnitConversion(areaUnitsFrom) * (1 / getAreaUnitConversion(areaUnitsTo));
}
static convertVolume(volume, volumeUnitsFrom, volumeUnitsTo) {
return volumeUnitsFrom === volumeUnitsTo ? volume : volume * getVolumeUnitConversion(volumeUnitsFrom) * (1 / getVolumeUnitConversion(volumeUnitsTo));
}
static convertAngle(angle, angleUnitsFrom, angleUnitsTo) {
return angleUnitsFrom === angleUnitsTo ? angle : convertAngleFromRadians(convertAngleToRadians(angle, angleUnitsFrom), angleUnitsTo);
}
static longitudeToString(longitude, angleUnits, locale, decimals) {
return _MeasureUnits.angleToString(Math.abs(longitude), angleUnits, locale, decimals) + " " + (longitude < 0 ? "W" : "E");
}
static latitudeToString(latitude, angleUnits, locale, decimals) {
return _MeasureUnits.angleToString(Math.abs(latitude), angleUnits, locale, decimals) + " " + (latitude < 0 ? "S" : "N");
}
};
_MeasureUnits.numberToString = function(number, locale, decimals) {
return numberToFormattedString(number, locale, decimals);
};
let MeasureUnits = exports('MeasureUnits', _MeasureUnits);
function getDistanceUnitConversion(distanceUnits) {
switch (distanceUnits) {
case DistanceUnits.METERS:
return 1;
case DistanceUnits.CENTIMETERS:
return 0.01;
case DistanceUnits.KILOMETERS:
return 1e3;
case DistanceUnits.FEET:
return 0.3048;
case DistanceUnits.US_SURVEY_FEET:
return 1200 / 3937;
case DistanceUnits.INCHES:
return 0.254;
case DistanceUnits.YARDS:
return 0.9144;
case DistanceUnits.MILES:
return 1609.344;
default:
return 1;
}
}
function getAreaUnitConversion(areaUnits) {
switch (areaUnits) {
case AreaUnits.SQUARE_METERS:
return 1;
case AreaUnits.SQUARE_CENTIMETERS:
return 1e-4;
case AreaUnits.SQUARE_KILOMETERS:
return 1e6;
case AreaUnits.SQUARE_FEET:
return 0.09290304;
case AreaUnits.SQUARE_INCHES:
return 64516e-8;
case AreaUnits.SQUARE_YARDS:
return 0.83612736;
case AreaUnits.SQUARE_MILES:
return 2589988110336e-6;
case AreaUnits.ACRES:
return 4046.85642232;
case AreaUnits.HECTARES:
return 1e4;
default:
return 1;
}
}
function getVolumeUnitConversion(volumeUnits) {
switch (volumeUnits) {
case VolumeUnits.CUBIC_METERS:
return 1;
case VolumeUnits.CUBIC_CENTIMETERS:
return 1e-6;
case VolumeUnits.CUBIC_KILOMETERS:
return 1e9;
case VolumeUnits.CUBIC_FEET:
return 0.09290304 * 0.3048;
case VolumeUnits.CUBIC_INCHES:
return 16387064e-12;
case VolumeUnits.CUBIC_YARDS:
return 0.764554857984;
case VolumeUnits.CUBIC_MILES:
return 416818182544058e-5;
default:
return 1;
}
}
function convertAngleToRadians(angle, angleUnits) {
const { defined, Math: CesiumMath, RuntimeError } = Cesium;
if (angleUnits === AngleUnits.RADIANS)
return angle;
if (angleUnits === AngleUnits.DEGREES)
return CesiumMath.toRadians(angle);
if (angleUnits === AngleUnits.GRADE)
return angle === Number.POSITIVE_INFINITY ? CesiumMath.PI_OVER_TWO : Math.atan(angle / 100);
if (angleUnits === AngleUnits.RATIO)
return Math.atan(angle);
if (angleUnits === AngleUnits.DEGREES_MINUTES_SECONDS) {
const degreesMinutesSecondsRegex = /(-?)(\d+)\s*°\s*(\d+)\s*'\s*([\d.,]+)"\s*([WENS]?)/i;
const result = degreesMinutesSecondsRegex.exec(angle) || [];
if (!defined(result))
throw new RuntimeError("Could not convert angle to radians: " + angle);
let r = 0 < result[1].length ? -1 : 1;
const degrees = parseInt(result[2]);
const minutes = parseInt(result[3]);
const seconds = parseFloat(result[4]);
let s = result[5];
1 === s.length && ("W" !== (s = s.toUpperCase()) && "S" !== s || (r *= -1));
const l = r * (degrees + minutes / 60 + seconds / 3600);
return CesiumMath.toRadians(l);
}
}
function convertAngleFromRadians(angle, angleUnits) {
const { Math: CesiumMath } = Cesium;
if (angleUnits === AngleUnits.RADIANS) {
return angle;
} else if (angleUnits === AngleUnits.DEGREES) {
return CesiumMath.toDegrees(angle);
} else if (angleUnits === AngleUnits.GRADE) {
if (CesiumMath.clamp(angle, 0, CesiumMath.PI_OVER_TWO) === CesiumMath.PI_OVER_TWO) {
return Number.POSITIVE_INFINITY;
} else {
return 100 * Math.tan(angle);
}
} else if (angleUnits === AngleUnits.RATIO) {
return Math.sin(angle) / Math.cos(angle);
}
return void 0;
}
function numberToFormattedString(number, locale, decimals) {
const options = getLocaleFormatStringOptions(decimals, number, locale);
const strLocale = number.toLocaleString(locale, options);
const negativeZero = -0;
const positiveZero = 0;
return strLocale === negativeZero.toLocaleString(locale, options) ? positiveZero.toLocaleString(locale, options) : strLocale;
}
function getLocaleFormatStringOptions(decimals, number, locale) {
let numberFormatter = {
minimumFractionDigits: 0,
maximumFractionDigits: 0
};
decimals = Cesium.defaultValue(decimals, 2);
if (typeof decimals === "number") {
numberFormatter.minimumFractionDigits = decimals;
numberFormatter.maximumFractionDigits = decimals;
} else {
numberFormatter = typeof decimals === "function" ? decimals(number, locale) : decimals;
}
return numberFormatter;
}
class PolygonPrimitive {
constructor(options) {
const { defined, defaultValue, createGuid, BoundingSphere, Ellipsoid, ClassificationType, ArcType } = Cesium;
options = defaultValue(options, {});
this.show = defaultValue(options.show, true);
this._id = defined(options.id) ? options.id : createGuid();
this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
this._appearance = defaultValue(options.appearance, new Cesium.MaterialAppearance());
this._depthFailAppearance = options.depthFailAppearance;
this._positions = defaultValue(options.positions, []);
this._polygonHierarchy = options.polygonHierarchy;
this._clampToGround = defaultValue(options.clampToGround, false);
this._classificationType = defaultValue(options.classificationType, ClassificationType.BOTH);
this._arcType = defaultValue(options.arcType, ArcType.RHUMB);
this._allowPicking = defaultValue(options.allowPicking, true);
this._asynchronous = defaultValue(options.asynchronous, false);
this._boundingSphere = new BoundingSphere();
this._primitive = void 0;
this._update = true;
}
get positions() {
return this._positions;
}
set positions(val) {
this._positions = val;
this._update = true;
}
get polygonHierarchy() {
return this._polygonHierarchy;
}
set polygonHierarchy(val) {
this._polygonHierarchy = val;
this._update = true;
}
get appearance() {
return this._appearance;
}
set appearance(val) {
this._appearance = val;
if (this._primitive !== void 0) {
this._primitive.appearance = val;
}
}
get depthFailAppearance() {
return this._depthFailAppearance;
}
set depthFailAppearance(val) {
this._depthFailAppearance = val;
if (this._primitive !== void 0 && this._primitive instanceof Cesium.Primitive) {
this._primitive.depthFailAppearance = val;
}
}
get id() {
return this._id;
}
set id(id) {
this._id = id;
}
get boundingVolume() {
return this._boundingSphere;
}
get ellipsoid() {
return this._ellipsoid;
}
get clampToGround() {
return this._clampToGround;
}
set clampToGround(val) {
this._clampToGround = val;
}
get classificationType() {
return this._classificationType;
}
set classificationType(e) {
this._classificationType = e;
this._update = true;
}
get allowPicking() {
return this._allowPicking;
}
set allowPicking(val) {
this._allowPicking = val;
}
get asynchronous() {
return this._asynchronous;
}
set asynchronous(val) {
this._asynchronous = val;
}
async update(frameState) {
if (this.show) {
const positions = this._polygonHierarchy ? this._polygonHierarchy.positions : this._positions;
if (positions.length < 3) {
this._primitive && this._primitive.destroy();
this._primitive = void 0;
} else {
if (this._update) {
this._update = false;
let promise;
if (this._clampToGround) {
promise = this._createGroundPolygon();
} else {
promise = this._createPolygon();
}
promise.then((primitive) => {
this._primitive && this._primitive.destroy();
this._primitive = void 0;
this._primitive = primitive;
this._primitive._vcParent = this;
this._boundingSphere = Cesium.BoundingSphere.fromPoints(positions, this._boundingSphere);
});
}
this._primitive && this._primitive.update(frameState);
}
}
}
async _createPolygon() {
const { Primitive, GeometryInstance, CoplanarPolygonGeometry, Cartesian3 } = Cesium;
return new Primitive({
geometryInstances: new GeometryInstance({
geometry: this._polygonHierarchy ? new CoplanarPolygonGeometry({
polygonHierarchy: this._polygonHierarchy,
ellipsoid: this._ellipsoid
}) : CoplanarPolygonGeometry.fromPositions({
positions: this._positions.map(function(e) {
return Cartesian3.clone(e);
}),
ellipsoid: this._ellipsoid
}),
id: this._id
}),
appearance: this._appearance,
depthFailAppearance: this._depthFailAppearance,
allowPicking: this._allowPicking,
asynchronous: this._asynchronous
});
}
async _createGroundPolygon() {
const { GroundPrimitive, GeometryInstance, PolygonGeometry, Cartesian3 } = Cesium;
await Cesium.GroundPrimitive.initializeTerrainHeights();
return new GroundPrimitive({
geometryInstances: new GeometryInstance({
geometry: this._polygonHierarchy ? new PolygonGeometry({
polygonHierarchy: this._polygonHierarchy,
ellipsoid: this._ellipsoid,
arcType: this._arcType
}) : PolygonGeometry.fromPositions({
positions: this._positions.map(function(e) {
return Cartesian3.clone(e);
}),
ellipsoid: this._ellipsoid,
arcType: this._arcType
}),
id: this._id
}),
appearance: this._appearance,
allowPicking: this._allowPicking,
asynchronous: this._asynchronous,
classificationType: this._classificationType
});
}
isDestroyed() {
return false;
}
destroy() {
this._primitive && this._primitive.destroy();
this._primitive = void 0;
return Cesium.destroyObject(this);
}
} exports('PolygonPrimitive', PolygonPrimitive);
class DynamicOverlay {
constructor(options) {
const { SampledPositionProperty, Entity, ExtrapolationType, VelocityOrientationProperty, CallbackProperty } = Cesium;
this._lastTime = void 0;
this._sampledPosition = new SampledPositionProperty();
this._sampledPosition.forwardExtrapolationType = options.forwardExtrapolationType || ExtrapolationType.HOLD;
this._sampledPosition.backwardExtrapolationType = options.backwardExtrapolationType || ExtrapolationType.HOLD;
this._cache = [];
this._maxCacheSize = options.maxCacheSize || 10;
const entity = new Entity(options);
entity.position = this._sampledPosition;
if (!Cesium.defined(options.orientation)) {
const orientation = new VelocityOrientationProperty(this._sampledPosition);
let lastOri;
entity.orientation = new CallbackProperty((time, result) => {
const ori = orientation.getValue(time);
if (ori) {
lastOri = ori;
} else {
return lastOri;
}
return ori;
}, false);
}
this._entity = entity;
this._velocityVectorProperty = new Cesium.VelocityVectorProperty(this._sampledPosition, false);
}
get id() {
return this._entity.id;
}
set id(id) {
this._entity.id = id;
}
set maxCacheSize(maxCacheSize) {
this._maxCacheSize = maxCacheSize;
}
get maxCacheSize() {
return this._maxCacheSize;
}
get position() {
return this._sampledPosition.getValue(Cesium.JulianDate.now());
}
_removePosition() {
if (this._cache.length > this._maxCacheSize) {
const start = Cesium.JulianDate.addSeconds(this._cache[0], -0.2, new Cesium.JulianDate());
const stop = Cesium.JulianDate.addSeconds(this._cache[this._cache.length - this._maxCacheSize], -0.2, new Cesium.JulianDate());
this._sampledPosition.removeSamples(
new Cesium.TimeInterval({
start,
stop
})
);
this._cache.splice(0, this._cache.length - this._maxCacheSize);
}
}
/**
*
* @param position
* @param interval
* @returns
*/
addPosition(position, timeOrInterval) {
this._removePosition();
let time;
if (typeof timeOrInterval === "number") {
const now = Cesium.JulianDate.now();
time = Cesium.JulianDate.addSeconds(now, timeOrInterval, new Cesium.JulianDate());
Cesium.destroyObject(now);
} else {
time = makeJulianDate(timeOrInterval);
}
this._sampledPosition.addSample(time, makeCartesian3(position));
this._lastTime = time;
this._cache.push(this._lastTime);
return time;
}
} exports('DynamicOverlay', DynamicOverlay);
const attributeLocations = {
position: 0,
normal: 1
};
class DebugCameraPrimitive {
constructor(options) {
const { defaultValue, Matrix4, Math: CesiumMath, Color, BoundingSphere } = Cesium;
this.modelMatrix = defaultValue(options.modelMatrix, new Matrix4());
this.fovH = defaultValue(options.fovH, CesiumMath.toRadians(60));
this.fovV = defaultValue(options.fovV, CesiumMath.toRadians(30));
this.segmentH = defaultValue(options.segmentH, 16);
this.segmentV = defaultValue(options.segmentV, 8);
this.subSegmentH = defaultValue(options.subSegmentH, 3);
this.subSegmentV = defaultValue(options.subSegmentV, 3);
this._faceColor = defaultValue(options.faceColor, new Color(1, 1, 1, 0.1));
this._lineColor = defaultValue(options.lineColor, new Color(1, 1, 1, 0.4));
this.show = defaultValue(options.show, true);
this._modelMatrix = Matrix4.clone(Matrix4.IDENTITY);
this._fovH = 0;
this._fovV = 0;
this._segmentH = 1;
this._segmentV = 1;
this._subSegmentH = 1;
this._subSegmentV = 1;
this._boundingSphere = new BoundingSphere();
this._initBoundingSphere = void 0;
this._command = void 0;
}
get faceColor() {
return this._faceColor;
}
set faceColor(e) {
this._faceColor = e;
}
get lineColor() {
return this._lineColor;
}
set lineColor(e) {
this._lineColor = e;
}
update(frameState) {
if (this.show && frameState.passes.render) {
const { clone, Matrix4, defined, BoundingSphere } = Cesium;
this.fovH === this._fovH && this.fovV === this._fovV && this.segmentH === this._segmentH && this.segmentV === this._segmentV && this.subSegmentH === this._subSegmentH && this.subSegmentV === this._subSegmentV || (this._fovH = this.fovH, this._fovV = this.fovV, this._segmentH = this.segmentH, this._segmentV = this.segmentV, this._subSegmentH = this.subSegmentH, this._subSegmentV = this.subSegmentV, this._modelMatrix = clone(Matrix4.IDENTITY), this._destroyVideoMemory());
if (this.fovH !== this._fovH && this.fovV !== this._fovV && this.segmentH !== this._segmentH && this.segmentV !== this._segmentV && this.subSegmentH !== this._subSegmentH && this.subSegmentV !== this._subSegmentV) {
this._fovH = this.fovH;
this._fovV = this.fovV;
this._segmentH = this.segmentH;
this._segmentV = this.segmentV;
this._subSegmentH = this.subSegmentH;
this._subSegmentV = this.subSegmentV;
this._modelMatrix = clone(Matrix4.IDENTITY);
this._destroyVideoMemory();
}
if (!defined(this._command)) {
this._createCommand(frameState.context);
}
if (!Matrix4.equals(this.modelMatrix, this._modelMatrix)) {
Matrix4.clone(this.modelMatrix, this._modelMatrix);
this._command.modelMatrix = Matrix4.IDENTITY;
this._command.modelMatrix = this._modelMatrix;
this._command.boundingVolume = BoundingSphere.transform(this._initBoundingSphere, this._modelMatrix, this._boundingSphere);
this._lineCommand.modelMatrix = Matrix4.IDENTITY;
this._lineCommand.modelMatrix = this._modelMatrix;
this._lineCommand.boundingVolume = BoundingSphere.transform(this._initBoundingSphere, this._modelMatrix, this._boundingSphere);
}
this._command && frameState.commandList.push(this._command);
this._lineCommand && frameState.commandList.push(this._lineCommand);
}
}
isDestroyed() {
return false;
}
destroy() {
this._destroyVideoMemory();
Cesium.destroyObject(this);
}
_createCommand(context) {
const {
Appearance,
RenderState,
ShaderSource,
ShaderProgram,
BufferUsage,
IndexDatatype,
VertexArray,
ComponentDatatype,
BoundingSphere,
DrawCommand,
PrimitiveType,
Pass,
Matrix4
} = Cesium;
const that = this;
const segmentHLength = this._subSegmentH * this._segmentH;
const segmentVLength = this._subSegmentV * this._segmentV;
const positionTypedArray1 = createTypedArray(this._fovH, this._fovV, segmentHLength, segmentVLength);
const positionTypedArray2 = createTypedArray(this._fovH, this._fovV, segmentHLength, segmentVLength);
const indexTypedArray1 = generateIndices1(segmentHLength, segmentVLength);
const indexTypedArray2 = generateIndices2(this._segmentH, this._segmentV, this._subSegmentH, this._subSegmentV);
const appearance = Appearance["getDefaultRenderState"](true, false, void 0);
const renderState = RenderState.fromCache(appearance);
const webgl2 = context.webgl2;
const vs = new ShaderSource({
sources: [
`
// \u4F7F\u7528double\u7C7B\u578B\u7684position\u8FDB\u884C\u8BA1\u7B97
// attribute vec3 position3DHigh;
// attribute vec3 position3DLow;
${webgl2 ? "in" : "attribute"} vec3 position;
${webgl2 ? "in" : "attribute"} vec3 normal;
// attribute vec2 st;
// attribute float batchId;
${webgl2 ? "out" : "varying"} vec3 v_positionEC;
${webgl2 ? "out" : "varying"} vec3 v_normalEC;
// varying vec2 v_st;
void main()
{
// \u4F7F\u7528double\u7C7B\u578B\u7684position\u8FDB\u884C\u8BA1\u7B97
// vec4 p = czm_translateRelativeToEye(position3DHigh, position3DLow);
// v_positionEC = (czm_modelViewRelativeToEye * p).xyz;
// position in eye coordinates
// v_normalEC = czm_normal * normal;
// normal in eye coordinates
// v_st = st;
// gl_Position = czm_modelViewProjectionRelativeToEye * p;
v_positionEC = (czm_modelView * vec4(position, 1.0)).xyz;
// position in eye coordinates
v_normalEC = czm_normal * normal;
// normal in eye coordinates
// v_st = st;
gl_Position = czm_modelViewProjection * vec4(position, 1.0);
}
`
]
});
const fs = new ShaderSource({
sources: [
`
${webgl2 ? "in" : "varying"} vec3 v_positionEC;
${webgl2 ? "in" : "varying"} vec3 v_normalEC;
// varying vec2 v_st;
// uniform sampler2D myImage;
uniform vec4 vcColor;
void main()
{
vec3 positionToEyeEC = -v_positionEC;
vec3 normalEC = normalize(v_normalEC);
#ifdef FACE_FORWARD
normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);
#endif
czm_materialInput materialInput;
materialInput.normalEC = normalEC;
materialInput.positionToEyeEC = positionToEyeEC;
// materialInput.st = v_st;
//czm_material material = czm_getMaterial(materialInput);
czm_material material = czm_getDefaultMaterial(materialInput);
// material.diffuse = texture2D(myImage, materialInput.st).rgb;
material.diffuse = vcColor.rgb;
material.alpha = vcColor.a;
#ifdef FLAT
${webgl2 ? "out_FragColor" : "gl_FragColor"} = vec4(material.diffuse + material.emission, material.alpha);
#else
${webgl2 ? "out_FragColor" : "gl_FragColor"} = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);
#endif
}
`
]
});
const uniformsFace = {
vcColor: function() {
return that._faceColor;
}
};
const uniformsLine = {
vcColor: function() {
return that._lineColor;
}
};
const shaderProgram = ShaderProgram.fromCache({
context,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations
});
this._shaderprogram = shaderProgram;
const positionBuffer1 = Cesium["Buffer"].createVertexBuffer({
context,
typedArray: positionTypedArray1,
usage: BufferUsage.STATIC_DRAW
});
const positionBuffer2 = Cesium["Buffer"].createVertexBuffer({
context,
typedArray: positionTypedArray2,
usage: BufferUsage.STATIC_DRAW
});
const indexBuffer1 = Cesium["Buffer"].createIndexBuffer({
context,
typedArray: indexTypedArray1,
usage: BufferUsage.STATIC_DRAW,
indexDatatype: IndexDatatype.UNSIGNED_SHORT
});
const indexBuffer2 = Cesium["Buffer"].createIndexBuffer({
context,
typedArray: indexTypedArray2,
usage: BufferUsage.STATIC_DRAW,
indexDatatype: IndexDatatype.UNSIGNED_SHORT
});
const textureVA1 = new VertexArray({
context,
attributes: [
{
index: 0,
vertexBuffer: positionBuffer1,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype.FLOAT
},
{
index: 1,
vertexBuffer: positionBuffer2,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype.FLOAT
}
],
indexBuffer: indexBuffer1
});
const textureVA2 = new VertexArray({
context,
attributes: [
{
index: 0,
vertexBuffer: positionBuffer1,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype.FLOAT
},
{
index: 1,
vertexBuffer: positionBuffer2,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype.FLOAT
}
],
indexBuffer: indexBuffer2
});
this._initBoundingSphere = BoundingSphere.fromVertices(positionTypedArray1);
this._command = new DrawCommand({
vertexArray: textureVA1,
primitiveType: PrimitiveType.TRIANGLES,
renderState,
shaderProgram,
uniformMap: uniformsFace,
owner: this,
pass: Pass.TRANSLUCENT,
modelMatrix: new Matrix4(),
boundingVolume: new BoundingSphere(),
cull: true
});
this._lineCommand = new DrawCommand({
vertexArray: textureVA2,
primitiveType: PrimitiveType.LINES,
renderState,
shaderProgram,
uniformMap: uniformsLine,
owner: this,
pass: Pass.TRANSLUCENT,
modelMatrix: new Matrix4(),
boundingVolume: new BoundingSphere(),
cull: true
});
}
_destroyVideoMemory() {
const { defined } = Cesium;
this._shaderprogram = this._shaderprogram && this._shaderprogram.destroy();
if (defined(this._command)) {
this._command.vertexArray.destroy();
this._command = void 0;
}
if (defined(this._lineCommand)) {
this._lineCommand.vertexArray.destroy();
this._lineCommand = void 0;
}
}
} exports('DebugCameraPrimitive', DebugCameraPrimitive);
function createTypedArray(fovH, fovV, segmentHLength, segmentVLength) {
const buffer = new Float32Array((segmentHLength + 1) * (segmentVLength + 1) * 3 + 3);
for (let i = 0; i < segmentHLength + 1; i++) {
for (let j = 0; j < segmentVLength + 1; j++) {
const width = fovH * (i / segmentHLength - 0.5);
const height = fovV * (j / segmentVLength - 0.5);
const positions = [Math.cos(-width) * Math.cos(-height), Math.sin(-width) * Math.cos(-height), Math.sin(height)];
buffer[3 * (j * (segmentHLength + 1) + i) + 0] = positions[0];
buffer[3 * (j * (segmentHLength + 1) + i) + 1] = positions[1];
buffer[3 * (j * (segmentHLength + 1) + i) + 2] = positions[2];
}
}
buffer[(segmentHLength + 1) * (segmentVLength + 1) * 3 + 0] = 0;
buffer[(segmentHLength + 1) * (segmentVLength + 1) * 3 + 1] = 0;
buffer[(segmentHLength + 1) * (segmentVLength + 1) * 3 + 2] = 0;
return buffer;
}
function generateIndices1(segmentHLength, segmentVLength) {
const vertexCount = segmentHLength * segmentVLength * 6;
const indices = new Uint16Array(vertexCount);
for (let i = 0; i < segmentHLength; i++) {
for (let j = 0; j < segmentVLength; j++) {
const a = j * (1 + segmentHLength) + i;
const b = j * (1 + segmentHLength) + i + 1;
const c = (j + 1) * (1 + segmentHLength) + i;
const d = (j + 1) * (1 + segmentHLength) + i + 1;
const quadIndex = 6 * (j * segmentHLength + i);
indices[0 + quadIndex] = a;
indices[1 + quadIndex] = b;
indices[2 + quadIndex] = d;
indices[3 + quadIndex] = a;
indices[4 + quadIndex] = d;
indices[5 + quadIndex] = c;
}
}
return indices;
}
function generateIndices2(segmentH, segmentV, subSegmentH, subSegmentV) {
const segmentHLength = segmentH * subSegmentH;
const segmentVLength = segmentV * subSegmentV;
const indices = new Uint16Array((segmentH + 1) * (2 * segmentVLength) + (segmentV + 1) * (2 * segmentHLength) + 8);
for (let i = 0; i < segmentH + 1; i++) {
for (let j = 0; j < segmentVLength; j++) {
const index2 = i * subSegmentH;
indices[2 * (i * segmentVLength + j) + 0] = j * (1 + segmentHLength) + index2;
indices[2 * (i * segmentVLength + j) + 1] = (j + 1) * (1 + segmentHLength) + index2;
}
}
const size = (segmentH + 1) * (2 * segmentVLength);
for (let i = 0; i < segmentV; i++) {
for (let j = 0; j < segmentHLength; j++) {
const index2 = i * subSegmentV;
indices[size + 2 * (j + i * segmentHLength)] = index2 * (1 + segmentHLength) + j;
indices[size + 2 * (j + i * segmentHLength) + 1] = index2 * (1 + segmentHLength) + j + 1;
}
}
const index = (segmentH + 1) * (2 * segmentVLength) + (segmentV + 1) * (2 * segmentHLength);
indices[index] = 0;
indices[index + 1] = (1 + segmentHLength) * (1 + segmentVLength);
indices[index + 2] = segmentHLength;
indices[index + 3] = (1 + segmentHLength) * (1 + segmentVLength);
indices[index + 4] = (1 + segmentHLength) * segmentVLength;
indices[index + 5] = (1 + segmentHLength) * (1 + segmentVLength);
indices[index + 6] = (1 + segmentHLength) * (1 + segmentVLength) - 1;
indices[index + 7] = (1 + segmentHLength) * (1 + segmentVLength);
return indices;
}
function sortKD(ids, coords, nodeSize, left, right, depth) {
if (right - left <= nodeSize) return;
const m = (left + right) >> 1;
select(ids, coords, m, left, right, depth % 2);
sortKD(ids, coords, nodeSize, left, m - 1, depth + 1);
sortKD(ids, coords, nodeSize, m + 1, right, depth + 1);
}
function select(ids, coords, k, left, right, inc) {
while (right > left) {
if (right - left > 600) {
const n = right - left + 1;
const m = k - left + 1;
const z = Math.log(n);
const s = 0.5 * Math.exp(2 * z / 3);
const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
select(ids, coords, k, newLeft, newRight, inc);
}
const t = coords[2 * k + inc];
let i = left;
let j = right;
swapItem(ids, coords, left, k);
if (coords[2 * right + inc] > t) swapItem(ids, coords, left, right);
while (i < j) {
swapItem(ids, coords, i, j);
i++;
j--;
while (coords[2 * i + inc] < t) i++;
while (coords[2 * j + inc] > t) j--;
}
if (coords[2 * left + inc] === t) swapItem(ids, coords, left, j);
else {
j++;
swapItem(ids, coords, j, right);
}
if (j <= k) left = j + 1;
if (k <= j) right = j - 1;
}
}
function swapItem(ids, coords, i, j) {
swap(ids, i, j);
swap(coords, 2 * i, 2 * j);
swap(coords, 2 * i + 1, 2 * j + 1);
}
function swap(arr, i, j) {
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
function range(ids, coords, minX, minY, maxX, maxY, nodeSize) {
const stack = [0, ids.length - 1, 0];
const result = [];
let x, y;
while (stack.length) {
const axis = stack.pop();
const right = stack.pop();
const left = stack.pop();
if (right - left <= nodeSize) {
for (let i = left; i <= right; i++) {
x = coords[2 * i];
y = coords[2 * i + 1];
if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);
}
continue;
}
const m = Math.floor((left + right) / 2);
x = coords[2 * m];
y = coords[2 * m + 1];
if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);
const nextAxis = (axis + 1) % 2;
if (axis === 0 ? minX <= x : minY <= y) {
stack.push(left);
stack.push(m - 1);
stack.push(nextAxis);
}
if (axis === 0 ? maxX >= x : maxY >= y) {
stack.push(m + 1);
stack.push(right);
stack.push(nextAxis);
}
}
return result;
}
function within(ids, coords, qx, qy, r, nodeSize) {
const stack = [0, ids.length - 1, 0];
const result = [];
const r2 = r * r;
while (stack.length) {
const axis = stack.pop();
const right = stack.pop();
const left = stack.pop();
if (right - left <= nodeSize) {
for (let i = left; i <= right; i++) {
if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]);
}
continue;
}
const m = Math.floor((left + right) / 2);
const x = coords[2 * m];
const y = coords[2 * m + 1];
if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]);
const nextAxis = (axis + 1) % 2;
if (axis === 0 ? qx - r <= x : qy - r <= y) {
stack.push(left);
stack.push(m - 1);
stack.push(nextAxis);
}
if (axis === 0 ? qx + r >= x : qy + r >= y) {
stack.push(m + 1);
stack.push(right);
stack.push(nextAxis);
}
}
return result;
}
function sqDist(ax, ay, bx, by) {
const dx = ax - bx;
const dy = ay - by;
return dx * dx + dy * dy;
}
const defaultGetX = p => p[0];
const defaultGetY = p => p[1];
class KDBush {
constructor(points, getX = defaultGetX, getY = defaultGetY, nodeSize = 64, ArrayType = Float64Array) {
this.nodeSize = nodeSize;
this.points = points;
const IndexArrayType = points.length < 65536 ? Uint16Array : Uint32Array;
const ids = this.ids = new IndexArrayType(points.length);
const coords = this.coords = new ArrayType(points.length * 2);
for (let i = 0; i < points.length; i++) {
ids[i] = i;
coords[2 * i] = getX(points[i]);
coords[2 * i + 1] = getY(points[i]);
}
sortKD(ids, coords, nodeSize, 0, ids.length - 1, 0);
}
range(minX, minY, maxX, maxY) {
return range(this.ids, this.coords, minX, minY, maxX, maxY, this.nodeSize);
}
within(x, y, r) {
return within(this.ids, this.coords, x, y, r, this.nodeSize);
}
}
class PrimitiveCluster$1 {
constructor(options) {
options = defaultValue(options, {});
this._enabled = defaultValue(options.enabled, false);
this._pixelRange = defaultValue(options.pixelRange, 80);
this._minimumClusterSize = defaultValue(options.minimumClusterSize, 2);
this._clusterBillboards = defaultValue(options.clusterBillboards, true);
this._clusterLabels = defaultValue(options.clusterLabels, true);
this._clusterPoints = defaultValue(options.clusterPoints, true);
this._labelCollection = void 0;
this._billboardCollection = void 0;
this._pointCollection = void 0;
this._clusterBillboardCollection = void 0;
this._clusterLabelCollection = void 0;
this._clusterPointCollection = void 0;
this._collectionIndicesByEntity = {};
this._unusedLabelIndices = [];
this._unusedBillboardIndices = [];
this._unusedPointIndices = [];
this._previousClusters = [];
this._previousHeight = void 0;
this._enabledDirty = false;
this._clusterDirty = false;
this._cluster = void 0;
this._removeEventListener = void 0;
this._clusterEvent = new Cesium.Event();
this.show = defaultValue(options.show, true);
}
_initialize(scene) {
this._scene = scene;
const cluster = createDeclutterCallback(this);
this._cluster = cluster;
this._removeEventListener = scene.camera.changed.addEventListener(cluster);
}
get enabled() {
return this._enabled;
}
set enabled(value) {
this._enabledDirty = value !== this._enabled;
this._enabled = value;
}
get pixelRange() {
return this._pixelRange;
}
set pixelRange(value) {
this._clusterDirty = this._clusterDirty || value !== this._pixelRange;
this._pixelRange = value;
}
get minimumClusterSize() {
return this._minimumClusterSize;
}
set minimumClusterSize(value) {
this._clusterDirty = this._clusterDirty || value !== this._minimumClusterSize;
this._minimumClusterSize = value;
}
get clusterEvent() {
return this._clusterEvent;
}
get clusterBillboards() {
return this._clusterBillboards;
}
set clusterBillboards(value) {
this._clusterDirty = this._clusterDirty || value !== this._clusterBillboards;
this._clusterBillboards = value;
}
get clusterLabels() {
return this._clusterLabels;
}
set clusterLabels(value) {
this._clusterDirty = this._clusterDirty || value !== this._clusterLabels;
this._clusterLabels = value;
}
get clusterPoints() {
return this._clusterPoints;
}
set clusterPoints(value) {
this._clusterDirty = this._clusterDirty || value !== this._clusterPoints;
this._clusterPoints = value;
}
getLabel(entity) {
return createGetEntity.call(this, entity, "_labelCollection", Cesium.LabelCollection, "_unusedLabelIndices", "labelIndex");
}
removeLabel(entity) {
const { defined } = Cesium;
const entityIndices = this._collectionIndicesByEntity && this._collectionIndicesByEntity[entity.id];
if (!defined(this._labelCollection) || !defined(entityIndices) || !defined(entityIndices.labelIndex)) {
return;
}
const index = entityIndices.labelIndex;
entityIndices.labelIndex = void 0;
removeEntityIndicesIfUnused(this, entity.id);
const label = this._labelCollection.get(index);
label.show = false;
label.text = "";
label.id = void 0;
this._unusedLabelIndices.push(index);
this._clusterDirty = true;
}
getBillboard(entity) {
return createGetEntity.call(this, entity, "_billboardCollection", Cesium.BillboardCollection, "_unusedBillboardIndices", "billboardIndex");
}
removeBillboard(entity) {
const { defined } = Cesium;
const entityIndices = this._collectionIndicesByEntity && this._collectionIndicesByEntity[entity.id];
if (!defined(this._billboardCollection) || !defined(entityIndices) || !defined(entityIndices.billboardIndex)) {
return;
}
const index = entityIndices.billboardIndex;
entityIndices.billboardIndex = void 0;
removeEntityIndicesIfUnused(this, entity.id);
const billboard = this._billboardCollection.get(index);
billboard.id = void 0;
billboard.show = false;
billboard.image = void 0;
this._unusedBillboardIndices.push(index);
this._clusterDirty = true;
}
getPoint(entity) {
return createGetEntity.call(this, entity, "_pointCollection", Cesium.PointPrimitiveCollection, "_unusedPointIndices", "pointIndex");
}
removePoint(entity) {
const { defined } = Cesium;
const entityIndices = this._collectionIndicesByEntity && this._collectionIndicesByEntity[entity.id];
if (!defined(this._pointCollection) || !defined(entityIndices) || !defined(entityIndices.pointIndex)) {
return;
}
const index = entityIndices.pointIndex;
entityIndices.pointIndex = void 0;
removeEntityIndicesIfUnused(this, entity.id);
const point = this._pointCollection.get(index);
point.show = false;
point.id = void 0;
this._unusedPointIndices.push(index);
this._clusterDirty = true;
}
update(frameState) {
if (!this.show) {
return;
}
const { defined } = Cesium;
let commandList;
if (defined(this._labelCollection) && this._labelCollection.length > 0 && this._labelCollection.get(0)._glyphs.length === 0) {
commandList = frameState.commandList;
frameState.commandList = [];
this._labelCollection.update(frameState);
frameState.commandList = commandList;
}
if (defined(this._billboardCollection) && this._billboardCollection.length > 0 && !defined(this._billboardCollection.get(0).width)) {
commandList = frameState.commandList;
frameState.commandList = [];
this._billboardCollection.update(frameState);
frameState.commandList = commandList;
}
if (this._enabledDirty) {
this._enabledDirty = false;
updateEnable(this);
this._clusterDirty = true;
}
if (this._clusterDirty) {
this._clusterDirty = false;
this._cluster();
}
if (defined(this._clusterLabelCollection)) {
this._clusterLabelCollection.update(frameState);
}
if (defined(this._clusterBillboardCollection)) {
this._clusterBillboardCollection.update(frameState);
}
if (defined(this._clusterPointCollection)) {
this._clusterPointCollection.update(frameState);
}
if (defined(this._labelCollection)) {
this._labelCollection.update(frameState);
}
if (defined(this._billboardCollection)) {
this._billboardCollection.update(frameState);
}
if (defined(this._pointCollection)) {
this._pointCollection.update(frameState);
}
}
destroy() {
const { defined } = Cesium;
this._labelCollection = this._labelCollection && this._labelCollection.destroy();
this._billboardCollection = this._billboardCollection && this._billboardCollection.destroy();
this._pointCollection = this._pointCollection && this._pointCollection.destroy();
this._clusterLabelCollection = this._clusterLabelCollection && this._clusterLabelCollection.destroy();
this._clusterBillboardCollection = this._clusterBillboardCollection && this._clusterBillboardCollection.destroy();
this._clusterPointCollection = this._clusterPointCollection && this._clusterPointCollection.destroy();
if (defined(this._removeEventListener)) {
this._removeEventListener();
this._removeEventListener = void 0;
}
this._labelCollection = void 0;
this._billboardCollection = void 0;
this._pointCollection = void 0;
this._clusterBillboardCollection = void 0;
this._clusterLabelCollection = void 0;
this._clusterPointCollection = void 0;
this._collectionIndicesByEntity = void 0;
this._unusedLabelIndices = [];
this._unusedBillboardIndices = [];
this._unusedPointIndices = [];
this._previousClusters = [];
this._previousHeight = void 0;
this._enabledDirty = false;
this._pixelRangeDirty = false;
this._minimumClusterSizeDirty = false;
return void 0;
}
} exports('PrimitiveCluster', PrimitiveCluster$1);
function updateEnable(entityCluster) {
if (entityCluster.enabled) {
return;
}
const { defined } = Cesium;
if (defined(entityCluster._clusterLabelCollection)) {
entityCluster._clusterLabelCollection.destroy();
}
if (defined(entityCluster._clusterBillboardCollection)) {
entityCluster._clusterBillboardCollection.destroy();
}
if (defined(entityCluster._clusterPointCollection)) {
entityCluster._clusterPointCollection.destroy();
}
entityCluster._clusterLabelCollection = void 0;
entityCluster._clusterBillboardCollection = void 0;
entityCluster._clusterPointCollection = void 0;
disableCollectionClustering(entityCluster._labelCollection);
disableCollectionClustering(entityCluster._billboardCollection);
disableCollectionClustering(entityCluster._pointCollection);
}
function disableCollectionClustering(collection) {
const { defined } = Cesium;
if (!defined(collection)) {
return;
}
const length = collection.length;
for (let i = 0; i < length; ++i) {
collection.get(i).clusterShow = true;
}
}
function createGetEntity(entity, collectionProperty, CollectionConstructor, unusedIndicesProperty, entityIndexProperty) {
const { defined } = Cesium;
let collection = this[collectionProperty];
if (!defined(this._collectionIndicesByEntity)) {
this._collectionIndicesByEntity = {};
}
let entityIndices = this._collectionIndicesByEntity[entity.id];
if (!defined(entityIndices)) {
entityIndices = this._collectionIndicesByEntity[entity.id] = {
billboardIndex: void 0,
labelIndex: void 0,
pointIndex: void 0
};
}
if (defined(collection) && defined(entityIndices[entityIndexProperty])) {
return collection.get(entityIndices[entityIndexProperty]);
}
if (!defined(collection)) {
collection = this[collectionProperty] = new CollectionConstructor({
scene: this._scene
});
}
let index;
let entityItem;
const unusedIndices = this[unusedIndicesProperty];
if (unusedIndices.length > 0) {
index = unusedIndices.pop();
entityItem = collection.get(index);
} else {
entityItem = collection.add();
index = collection.length - 1;
}
entityIndices[entityIndexProperty] = index;
const that = this;
Promise.resolve().then(function() {
that._clusterDirty = true;
});
return entityItem;
}
function removeEntityIndicesIfUnused(entityCluster, entityId) {
const { defined } = Cesium;
const indices = entityCluster._collectionIndicesByEntity[entityId];
if (!defined(indices.billboardIndex) && !defined(indices.labelIndex) && !defined(indices.pointIndex)) {
delete entityCluster._collectionIndicesByEntity[entityId];
}
}
function getX(point) {
return point.coord.x;
}
function getY(point) {
return point.coord.y;
}
function expandBoundingBox(bbox, pixelRange) {
bbox.x -= pixelRange;
bbox.y -= pixelRange;
bbox.width += pixelRange * 2;
bbox.height += pixelRange * 2;
}
function getBoundingBox(item, coord, pixelRange, entityCluster, result) {
const { defined, Label, Billboard, PointPrimitive, BoundingRectangle } = Cesium;
const labelBoundingBoxScratch = new BoundingRectangle();
if (defined(item._labelCollection) && entityCluster._clusterLabels) {
result = Label["getScreenSpaceBoundingBox"](item, coord, result);
} else if (defined(item._billboardCollection) && entityCluster._clusterBillboards) {
result = Billboard["getScreenSpaceBoundingBox"](item, coord, result);
} else if (defined(item._pointPrimitiveCollection) && entityCluster._clusterPoints) {
result = PointPrimitive["getScreenSpaceBoundingBox"](item, coord, result);
}
expandBoundingBox(result, pixelRange);
if (entityCluster._clusterLabels && !defined(item._labelCollection) && defined(item.id) && hasLabelIndex(entityCluster, item.id.id) && defined(item.id._label)) {
const labelIndex = entityCluster._collectionIndicesByEntity[item.id.id].labelIndex;
const label = entityCluster._labelCollection.get(labelIndex);
const labelBBox = Label["getScreenSpaceBoundingBox"](label, coord, labelBoundingBoxScratch);
expandBoundingBox(labelBBox, pixelRange);
result = BoundingRectangle.union(result, labelBBox, result);
}
return result;
}
function addNonClusteredItem(item, entityCluster) {
const { defined } = Cesium;
item.clusterShow = true;
if (!defined(item._labelCollection) && defined(item.id) && hasLabelIndex(entityCluster, item.id.id) && defined(item.id._label)) {
const labelIndex = entityCluster._collectionIndicesByEntity[item.id.id].labelIndex;
const label = entityCluster._labelCollection.get(labelIndex);
label.clusterShow = true;
}
}
function addCluster(position, numPoints, ids, entityCluster) {
const cluster = {
billboard: entityCluster._clusterBillboardCollection.add(),
label: entityCluster._clusterLabelCollection.add(),
point: entityCluster._clusterPointCollection.add()
};
cluster.billboard.show = false;
cluster.point.show = false;
cluster.label.show = true;
cluster.label.text = numPoints.toLocaleString();
cluster.label.id = ids;
cluster.billboard.position = cluster.label.position = cluster.point.position = position;
cluster.billboard.owner = entityCluster;
cluster.label.owner = entityCluster;
cluster.point.owner = entityCluster;
entityCluster._clusterEvent.raiseEvent(ids, cluster);
}
function hasLabelIndex(entityCluster, entityId) {
const { defined } = Cesium;
return defined(entityCluster) && defined(entityCluster._collectionIndicesByEntity[entityId]) && defined(entityCluster._collectionIndicesByEntity[entityId].labelIndex);
}
function getScreenSpacePositions(collection, points, scene, occluder, entityCluster) {
const { defined, SceneMode } = Cesium;
if (!defined(collection)) {
return;
}
const length = collection.length;
for (let i = 0; i < length; ++i) {
const item = collection.get(i);
item.clusterShow = false;
if (!item.show || entityCluster._scene.mode === SceneMode.SCENE3D && !occluder.isPointVisible(item.position)) {
continue;
}
const coord = item.computeScreenSpacePosition(scene);
if (!defined(coord)) {
continue;
}
points.push({
index: i,
collection,
clustered: false,
coord
});
}
}
function createDeclutterCallback(entityCluster) {
const { defined, LabelCollection, BillboardCollection, PointPrimitiveCollection, Billboard, Matrix4, Cartesian3, Cartesian2, BoundingRectangle } = Cesium;
const pointBoundinRectangleScratch = new BoundingRectangle();
const totalBoundingRectangleScratch = new BoundingRectangle();
const neighborBoundingRectangleScratch = new BoundingRectangle();
return function(amount) {
if (defined(amount) && amount < 0.05 || !entityCluster.enabled) {
return;
}
const scene = entityCluster._scene;
const labelCollection = entityCluster._labelCollection;
const billboardCollection = entityCluster._billboardCollection;
const pointCollection = entityCluster._pointCollection;
if (!defined(labelCollection) && !defined(billboardCollection) && !defined(pointCollection) || !entityCluster._clusterBillboards && !entityCluster._clusterLabels && !entityCluster._clusterPoints) {
return;
}
let clusteredLabelCollection = entityCluster._clusterLabelCollection;
let clusteredBillboardCollection = entityCluster._clusterBillboardCollection;
let clusteredPointCollection = entityCluster._clusterPointCollection;
if (defined(clusteredLabelCollection)) {
clusteredLabelCollection.removeAll();
} else {
clusteredLabelCollection = entityCluster._clusterLabelCollection = new LabelCollection({
scene
});
}
if (defined(clusteredBillboardCollection)) {
clusteredBillboardCollection.removeAll();
} else {
clusteredBillboardCollection = entityCluster._clusterBillboardCollection = new BillboardCollection({
scene
});
}
if (defined(clusteredPointCollection)) {
clusteredPointCollection.removeAll();
} else {
clusteredPointCollection = entityCluster._clusterPointCollection = new PointPrimitiveCollection();
}
const pixelRange = entityCluster._pixelRange;
const minimumClusterSize = entityCluster._minimumClusterSize;
const clusters = entityCluster._previousClusters;
const newClusters = [];
const previousHeight = entityCluster._previousHeight;
const currentHeight = scene.camera.positionCartographic.height;
const ellipsoid = scene.mapProjection.ellipsoid;
const cameraPosition = scene.camera.positionWC;
const occluder = new Cesium["EllipsoidalOccluder"](ellipsoid, cameraPosition);
const points = [];
if (entityCluster._clusterLabels) {
getScreenSpacePositions(labelCollection, points, scene, occluder, entityCluster);
}
if (entityCluster._clusterBillboards) {
getScreenSpacePositions(billboardCollection, points, scene, occluder, entityCluster);
}
if (entityCluster._clusterPoints) {
getScreenSpacePositions(pointCollection, points, scene, occluder, entityCluster);
}
let i;
let j;
let length;
let bbox;
let neighbors;
let neighborLength;
let neighborIndex;
let neighborPoint;
let ids;
let numPoints;
let collection;
let collectionIndex;
const index = new KDBush(points, getX, getY, 64, Int32Array);
if (currentHeight < previousHeight) {
length = clusters.length;
for (i = 0; i < length; ++i) {
const cluster = clusters[i];
if (!occluder.isPointVisible(cluster.position)) {
continue;
}
const coord = Billboard["_computeScreenSpacePosition"](Matrix4.IDENTITY, cluster.position, Cartesian3.ZERO, Cartesian2.ZERO, scene);
if (!defined(coord)) {
continue;
}
const factor = 1 - currentHeight / previousHeight;
let width = cluster.width = cluster.width * factor;
let height = cluster.height = cluster.height * factor;
width = Math.max(width, cluster.minimumWidth);
height = Math.max(height, cluster.minimumHeight);
const minX = coord.x - width * 0.5;
const minY = coord.y - height * 0.5;
const maxX = coord.x + width;
const maxY = coord.y + height;
neighbors = index.range(minX, minY, maxX, maxY);
neighborLength = neighbors.length;
numPoints = 0;
ids = [];
for (j = 0; j < neighborLength; ++j) {
neighborIndex = neighbors[j];
neighborPoint = points[neighborIndex];
if (!neighborPoint.clustered) {
++numPoints;
collection = neighborPoint.collection;
collectionIndex = neighborPoint.index;
ids.push(collection.get(collectionIndex).id);
}
}
if (numPoints >= minimumClusterSize) {
addCluster(cluster.position, numPoints, ids, entityCluster);
newClusters.push(cluster);
for (j = 0; j < neighborLength; ++j) {
points[neighbors[j]].clustered = true;
}
}
}
}
length = points.length;
for (i = 0; i < length; ++i) {
const point = points[i];
if (point.clustered) {
continue;
}
point.clustered = true;
collection = point.collection;
collectionIndex = point.index;
const item = collection.get(collectionIndex);
bbox = getBoundingBox(item, point.coord, pixelRange, entityCluster, pointBoundinRectangleScratch);
const totalBBox = BoundingRectangle.clone(bbox, totalBoundingRectangleScratch);
neighbors = index.range(bbox.x, bbox.y, bbox.x + bbox.width, bbox.y + bbox.height);
neighborLength = neighbors.length;
const clusterPosition = Cartesian3.clone(item.position);
numPoints = 1;
ids = [item.id];
for (j = 0; j < neighborLength; ++j) {
neighborIndex = neighbors[j];
neighborPoint = points[neighborIndex];
if (!neighborPoint.clustered) {
const neighborItem = neighborPoint.collection.get(neighborPoint.index);
const neighborBBox = getBoundingBox(neighborItem, neighborPoint.coord, pixelRange, entityCluster, neighborBoundingRectangleScratch);
Cartesian3.add(neighborItem.position, clusterPosition, clusterPosition);
BoundingRectangle.union(totalBBox, neighborBBox, totalBBox);
++numPoints;
ids.push(neighborItem.id);
}
}
if (numPoints >= minimumClusterSize) {
const position = Cartesian3.multiplyByScalar(clusterPosition, 1 / numPoints, clusterPosition);
addCluster(position, numPoints, ids, entityCluster);
newClusters.push({
position,
width: totalBBox.width,
height: totalBBox.height,
minimumWidth: bbox.width,
minimumHeight: bbox.height
});
for (j = 0; j < neighborLength; ++j) {
points[neighbors[j]].clustered = true;
}
} else {
addNonClusteredItem(item, entityCluster);
}
}
if (clusteredLabelCollection.length === 0) {
clusteredLabelCollection.destroy();
entityCluster._clusterLabelCollection = void 0;
}
if (clusteredBillboardCollection.length === 0) {
clusteredBillboardCollection.destroy();
entityCluster._clusterBillboardCollection = void 0;
}
if (clusteredPointCollection.length === 0) {
clusteredPointCollection.destroy();
entityCluster._clusterPointCollection = void 0;
}
entityCluster._previousClusters = newClusters;
entityCluster._previousHeight = currentHeight;
};
}
let isExtended$1 = false;
class RectangleExtend {
static extend(viewer) {
if (isExtended$1) {
return;
}
const { Rectangle } = Cesium;
Rectangle.prototype.expand = function(widthFactor, heightFactor, result) {
result = result && result instanceof Rectangle ? result : this.clone();
widthFactor = result.width * (1 - widthFactor) / 2;
heightFactor = result.height * (1 - heightFactor) / 2;
result.west += widthFactor;
result.south += heightFactor;
result.east -= widthFactor;
result.north -= heightFactor;
result.west = result.west < -Math.PI ? -Math.PI : result.west;
result.east = result.east > Math.PI ? Math.PI : result.east;
result.north = result.north > Math.PI / 2 ? Math.PI / 2 : result.north;
result.south = result.south < -Math.PI / 2 ? -Math.PI / 2 : result.south;
return result;
};
isExtended$1 = true;
}
static revoke(viewer) {
if (!isExtended$1) {
return;
}
const { Rectangle } = Cesium;
Rectangle.prototype.expand = void 0;
isExtended$1 = false;
}
} exports('RectangleExtend', RectangleExtend);
let isExtended = false;
let createShadowReceiveFragmentShaderNative;
class ShadowMapShaderExtend {
static extend(viewer) {
if (isExtended) {
return;
}
const ShadowMapShader = Cesium["ShadowMapShader"];
createShadowReceiveFragmentShaderNative = ShadowMapShader.createShadowReceiveFragmentShader;
ShadowMapShader.createShadowReceiveFragmentShader = function(fs, shadowMap, castShadows, isTerrain, hasTerrainNormal) {
var _a;
fs = createShadowReceiveFragmentShaderNative.bind(this)(fs, shadowMap, castShadows, isTerrain, hasTerrainNormal);
const isSpotLight = shadowMap._isSpotLight;
if (isSpotLight) {
fs.sources[0] = `
uniform vec4 shadowMap_viewshedVisibleColor;
uniform vec4 shadowMap_viewshedInvisibleColor;
${fs.sources[0]}
`;
const webgl2 = (_a = viewer.scene.context) == null ? void 0 : _a.webgl2;
fs.sources[fs.sources.length - 1] = fs.sources[fs.sources.length - 1].replace(
`${webgl2 ? "out_FragColor" : "gl_FragColor"}.rgb *= visibility;`,
`
float _depth = shadowPosition.z - shadowParameters.depthBias;
float _visibility = czm_shadowDepthCompare(shadowMap_texture, shadowPosition.xy, _depth);
${webgl2 ? "out_FragColor" : "gl_FragColor"}.rgb *= (_visibility < 0.999 ? shadowMap_viewshedInvisibleColor.rgb :shadowMap_viewshedVisibleColor.rgb);
`
);
fs.sources[fs.sources.length - 1] = fs.sources[fs.sources.length - 1].replace(
"vec3 directionEC = normalize(positionEC.xyz - shadowMap_lightPositionEC.xyz);",
"vec3 directionEC = normalize(positionEC.xyz - shadowMap_lightPositionEC.xyz);if (distance(positionEC.xyz, shadowMap_lightPositionEC.xyz) > shadowMap_lightPositionEC.w) { return; }"
);
}
return fs;
};
isExtended = true;
}
static revoke(viewer) {
if (!isExtended) {
return;
}
const ShadowMapShader = Cesium["ShadowMapShader"];
ShadowMapShader.createShadowReceiveFragmentShader = createShadowReceiveFragmentShaderNative;
isExtended = false;
}
} exports('ShadowMapShaderExtend', ShadowMapShaderExtend);
class Viewshed {
constructor(scene, options) {
const {
defined,
DeveloperError,
PerspectiveFrustum,
Math: CesiumMath,
Camera,
ShadowMap,
ShadowMode,
Event,
Cartesian3,
defaultValue,
Color
} = Cesium;
if (!defined(scene)) {
throw new DeveloperError("scene is required.");
}
this._scene = scene;
this._frustum = new PerspectiveFrustum();
this._frustum.fov = CesiumMath.PI / 3;
this._frustum.aspectRatio = 3;
this._frustum.near = 1;
this._frustum.far = 400;
this._spotLightCamera = new Camera(this._scene);
this._frustum.clone(this._spotLightCamera.frustum);
this._viewshedShadowMap = new ShadowMap({
context: this._scene.context,
lightCamera: this._spotLightCamera,
cascadesEnabled: false
});
options = options || {};
this._scene.globe.shadows = ShadowMode.ENABLED;
this._viewshedShadowMap._terrainBias.depthBias = 0;
this._debugCameraPrimitive = new DebugCameraPrimitive({});
this._enabledChangedEvent = new Event();
this._position = new Cartesian3();
this._offsetHeight = defaultValue(options.offsetHeight, 1.8);
this._visibleColor = defaultValue(options.visibleColor, new Color(0, 1, 0, 1));
this._invisibleColor = defaultValue(options.invisibleColor, new Color(1, 0, 0, 1));
this._viewshedShadowMap._viewshedColors = {
visible: this._visibleColor,
invisible: this._invisibleColor
};
this._showGridLine = options.showGridLine;
this._debugCameraPrimitive.show = this._showGridLine;
this._debugCameraPrimitive.lineColor = defaultValue(options.lineColor, new Color(1, 1, 1, 0.4));
this._debugCameraPrimitive.faceColor = defaultValue(options.faceColor, new Color(1, 1, 1, 0.1));
}
get frustum() {
return this._frustum;
}
get fovH() {
return this._fovH;
}
set fovH(e) {
if (isNaN(e) || void 0 === e || null == e || e < 0 || e >= Math.PI) {
throw new Error("fovH must be in the range [0, PI).");
}
this._fovH = Number(e);
this.frustum.aspectRatio = Math.tan(0.5 * this._fovH) / Math.tan(0.5 * this._fovV);
this.frustum.fov = this._fovH > this._fovV ? this._fovH : this._fovV;
}
get fovV() {
return this._fovV;
}
set fovV(e) {
if (isNaN(e) || void 0 === e || null == e || e < 0 || e >= Math.PI) {
throw new Error("fovV must be in the range [0, PI).");
}
this._fovV = Number(e);
this.frustum.aspectRatio = Math.tan(0.5 * this._fovH) / Math.tan(0.5 * this._fovV);
this.frustum.fov = this._fovH > this._fovV ? this._fovH : this._fovV;
}
get near() {
return this.frustum.near;
}
set near(e) {
this.frustum.near !== e && (this.frustum.near = e);
}
get far() {
return this.far.near;
}
set far(e) {
this.frustum.far !== e && (this.frustum.far = e);
}
get position() {
return this._position;
}
set position(e) {
if (e instanceof Cesium.Cartesian3) {
this.setView({
destination: e.clone(),
orientation: {
heading: this._spotLightCamera.heading,
pitch: this._spotLightCamera.pitch,
roll: this._spotLightCamera.roll
}
});
}
}
get offsetHeight() {
return this._offsetHeight;
}
set offsetHeight(e) {
if (isNaN(e) || null == e || null == e) {
throw new Error("Unacceptable offset.");
}
this._offsetHeight = Number(e);
this.setView({
destination: this._position,
orientation: {
heading: this._spotLightCamera.heading,
pitch: this._spotLightCamera.pitch,
roll: this._spotLightCamera.roll
}
});
}
get heading() {
return this._spotLightCamera.heading;
}
set heading(e) {
this._spotLightCamera.heading !== e && this._spotLightCamera.setView({
destination: this._spotLightCamera.positionWC,
orientation: {
heading: e,
pitch: this._spotLightCamera.pitch,
roll: this._spotLightCamera.roll
}
});
}
get pitch() {
return this._spotLightCamera.pitch;
}
set pitch(e) {
this._spotLightCamera.pitch !== e && this._spotLightCamera.setView({
destination: this._spotLightCamera.positionWC,
orientation: {
heading: this._spotLightCamera.heading,
pitch: e,
roll: this._spotLightCamera.roll
}
});
}
get roll() {
return this._spotLightCamera.roll;
}
set roll(e) {
this._spotLightCamera.roll !== e && this._spotLightCamera.setView({
destination: this._spotLightCamera.positionWC,
orientation: {
heading: this._spotLightCamera.heading,
pitch: this._spotLightCamera.pitch,
roll: e
}
});
}
get shadowMap() {
return this._viewshedShadowMap;
}
get lightCamera() {
return this._spotLightCamera;
}
get enabled() {
return this._viewshedShadowMap.enabled;
}
set enabled(e) {
if (this._viewshedShadowMap.enabled !== e) {
if (e) {
this._viewshedShadowMap.enabled = true;
this._viewshedShadowMap._pointLightRadius = this._spotLightCamera.frustum.far;
} else {
this._viewshedShadowMap.enabled = false;
}
this._enabledChangedEvent.raiseEvent(e);
}
}
get enabledChangedEvent() {
return this._enabledChangedEvent;
}
get visibleColor() {
return this._visibleColor;
}
set visibleColor(e) {
this._visibleColor = e;
this._viewshedShadowMap._viewshedColors.visible = e;
}
get invisibleColor() {
return this._invisibleColor;
}
set invisibleColor(e) {
this._invisibleColor = e;
this._viewshedShadowMap._viewshedColors.invisible = e;
}
get showGridLine() {
return this._showGridLine;
}
set showGridLine(e) {
this._showGridLine = e;
this._debugCameraPrimitive.show = e;
}
get faceColor() {
return this._debugCameraPrimitive.faceColor;
}
set faceColor(e) {
this._debugCameraPrimitive.faceColor = e;
}
get lineColor() {
return this._debugCameraPrimitive.lineColor;
}
set lineColor(e) {
this._debugCameraPrimitive.lineColor = e;
}
update(frameState) {
if (this._viewshedShadowMap.enabled) {
const { ShadowMode, Matrix3, Matrix4, Math: CesiumMath } = Cesium;
this._scene.globe.shadows !== ShadowMode.ENABLED && (this._scene.globe.shadows = ShadowMode.ENABLED);
frameState.shadowMaps.unshift(this._viewshedShadowMap);
if (!this._frustum.equals(this._spotLightCamera.frustum)) {
this._frustum.clone(this._spotLightCamera.frustum);
this._viewshedShadowMap._pointLightRadius = this._frustum.far;
this.shadowMap._boundingSphere.radius = Math.random();
}
if (this._debugCameraPrimitive.show) {
const modelMatrix = this._debugCameraPrimitive.modelMatrix;
Matrix4.clone(this._spotLightCamera.inverseViewMatrix, modelMatrix);
const r0 = Matrix3.fromRotationZ(0.5 * CesiumMath.PI);
const r1 = Matrix3.fromRotationY(0.5 * CesiumMath.PI);
const rotation = new Matrix3();
Matrix3.multiply(r0, r1, rotation);
Matrix4.multiplyByMatrix3(modelMatrix, rotation, modelMatrix);
Matrix4.multiplyByUniformScale(modelMatrix, this._spotLightCamera.frustum.far, modelMatrix);
const frustum = this._spotLightCamera.frustum;
this._debugCameraPrimitive.fovV = frustum.aspectRatio <= 1 ? frustum.fov : 2 * Math.atan(Math.tan(0.5 * frustum.fov) / frustum.aspectRatio);
this._debugCameraPrimitive.fovH = 1 < frustum.aspectRatio ? frustum.fov : 2 * Math.atan(Math.tan(0.5 * frustum.fov) * frustum.aspectRatio);
this._debugCameraPrimitive.segmentH = parseInt(String(this._debugCameraPrimitive.fovH / (Math.PI / 30))) || 1;
this._debugCameraPrimitive.segmentV = parseInt(String(this._debugCameraPrimitive.fovV / (Math.PI / 30))) || 1;
this._debugCameraPrimitive.update(frameState);
}
}
}
setView(options) {
options = options || {};
const destination = options.destination;
if (destination instanceof Cesium.Cartesian3) {
this._position = destination.clone();
const offsetHeight = this._offsetHeight;
const cartographic = Cesium.Cartographic.fromCartesian(destination, this._scene.globe.ellipsoid);
if (cartographic) {
cartographic.height = cartographic.height + offsetHeight;
const cartesian = Cesium.Cartesian3.fromRadians(
cartographic.longitude,
cartographic.latitude,
cartographic.height,
this._scene.globe.ellipsoid
);
options.destination = cartesian;
}
}
this._spotLightCamera.setView(options);
}
isDestroyed() {
return false;
}
destroy() {
this._debugCameraPrimitive && this._debugCameraPrimitive.destroy();
this._viewshedShadowMap && this._viewshedShadowMap.destroy();
Cesium.destroyObject(this);
}
} exports('Viewshed', Viewshed);
class VcTimelineHighlightRange {
constructor(color, heightInPx, base) {
this._color = color;
this._height = heightInPx;
this._base = Cesium.defaultValue(base, 0);
}
getHeight() {
return this._height;
}
getBase() {
return this._base;
}
getStartTime() {
return this._start;
}
getStopTime() {
return this._stop;
}
setRange(start, stop) {
this._start = start;
this._stop = stop;
}
render(renderState) {
let range = "";
const { JulianDate } = Cesium;
if (this._start && this._stop && this._color) {
const highlightStart = JulianDate.secondsDifference(this._start, renderState.epochJulian);
let highlightLeft = Math.round(renderState.timeBarWidth * renderState.getAlpha(highlightStart));
const highlightStop = JulianDate.secondsDifference(this._stop, renderState.epochJulian);
let highlightWidth = Math.round(renderState.timeBarWidth * renderState.getAlpha(highlightStop)) - highlightLeft;
if (highlightLeft < 0) {
highlightWidth += highlightLeft;
highlightLeft = 0;
}
if (highlightLeft + highlightWidth > renderState.timeBarWidth) {
highlightWidth = renderState.timeBarWidth - highlightLeft;
}
if (highlightWidth > 0) {
range = `<span class="cesium-timeline-highlight" style="left: ${highlightLeft.toString()}px; width: ${highlightWidth.toString()}px; bottom: ${this._base.toString()}px; height: ${this._height}px; background-color: ${this._color};"></span>`;
}
}
return range;
}
}
class TimelineTrack {
constructor(interval, pixelHeight, color, backgroundColor) {
const { Color } = Cesium;
this.interval = interval;
this.height = pixelHeight;
this.color = color || new Color(0.5, 0.5, 0.5, 1);
this.backgroundColor = backgroundColor || new Color(0, 0, 0, 0);
}
render(context, renderState) {
const { JulianDate, defined } = Cesium;
const startInterval = this.interval.start;
const stopInterval = this.interval.stop;
const spanStart = renderState.startJulian;
const spanStop = JulianDate.addSeconds(renderState.startJulian, renderState.duration, new JulianDate());
if (JulianDate.lessThan(startInterval, spanStart) && JulianDate.greaterThan(stopInterval, spanStop)) {
context.fillStyle = this.color.toCssColorString();
context.fillRect(0, renderState.y, renderState.timeBarWidth, this.height);
} else if (JulianDate.lessThanOrEquals(startInterval, spanStop) && JulianDate.greaterThanOrEquals(stopInterval, spanStart)) {
let x;
let start, stop;
for (x = 0; x < renderState.timeBarWidth; ++x) {
const currentTime = JulianDate.addSeconds(renderState.startJulian, x / renderState.timeBarWidth * renderState.duration, new JulianDate());
if (!defined(start) && JulianDate.greaterThanOrEquals(currentTime, startInterval)) {
start = x;
} else if (!defined(stop) && JulianDate.greaterThanOrEquals(currentTime, stopInterval)) {
stop = x;
}
}
context.fillStyle = this.backgroundColor.toCssColorString();
context.fillRect(0, renderState.y, renderState.timeBarWidth, this.height);
if (defined(start)) {
if (!defined(stop)) {
stop = renderState.timeBarWidth;
}
context.fillStyle = this.color.toCssColorString();
context.fillRect(start, renderState.y, Math.max(stop - start, 1), this.height);
}
}
}
}
let timelineWheelDelta = 1e12;
const timelineMouseMode = {
none: 0,
scrub: 1,
slide: 2,
zoom: 3,
touchOnly: 4
};
const timelineTouchMode = {
none: 0,
scrub: 1,
slideZoom: 2,
singleTap: 3,
ignore: 4
};
const timelineTicScales = [
1e-3,
2e-3,
5e-3,
0.01,
0.02,
0.05,
0.1,
0.25,
0.5,
1,
2,
5,
10,
15,
30,
60,
// 1min
120,
// 2min
300,
// 5min
600,
// 10min
900,
// 15min
1800,
// 30min
3600,
// 1hr
7200,
// 2hr
14400,
// 4hr
21600,
// 6hr
43200,
// 12hr
86400,
// 24hr
172800,
// 2days
345600,
// 4days
604800,
// 7days
1296e3,
// 15days
2592e3,
// 30days
5184e3,
// 60days
7776e3,
// 90days
15552e3,
// 180days
31536e3,
// 365days
63072e3,
// 2years
126144e3,
// 4years
15768e4,
// 5years
31536e4,
// 10years
63072e4,
// 20years
126144e4,
// 40years
15768e5,
// 50years
31536e5,
// 100years
63072e5,
// 200years
126144e5,
// 400years
15768e6,
// 500years
31536e6
// 1000years
];
const timelineMonthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
class VcTimeline {
constructor(container, clock) {
this.smallestTicInPixels = 7;
const { defined, DeveloperError } = Cesium;
if (!defined(container)) {
throw new DeveloperError("container is required.");
}
if (!defined(clock)) {
throw new DeveloperError("clock is required.");
}
container = getElement(container);
const ownerDocument = container.ownerDocument;
this.container = container;
const topDiv = ownerDocument.createElement("div");
topDiv.className = "cesium-timeline-main";
container.appendChild(topDiv);
this._topDiv = topDiv;
this._endJulian = void 0;
this._epochJulian = void 0;
this._lastXPos = void 0;
this._scrubElement = void 0;
this._startJulian = void 0;
this._timeBarSecondsSpan = void 0;
this._clock = clock;
this._scrubJulian = clock.currentTime;
this._mainTicSpan = -1;
this._mouseMode = timelineMouseMode.none;
this._touchMode = timelineTouchMode.none;
this._touchState = {
centerX: 0,
spanX: 0
};
this._mouseX = 0;
this._timelineDrag = 0;
this._timelineDragLocation = void 0;
this._lastHeight = void 0;
this._lastWidth = void 0;
this._topDiv.innerHTML = '<div class="cesium-timeline-bar"></div><div class="cesium-timeline-trackContainer"><canvas class="cesium-timeline-tracks" width="10" height="1"></canvas></div><div class="cesium-timeline-needle"></div><span class="cesium-timeline-ruler"></span>';
this._timeBarEle = this._topDiv.childNodes[0];
this._trackContainer = this._topDiv.childNodes[1];
this._trackListEle = this._topDiv.childNodes[1].childNodes[0];
this._needleEle = this._topDiv.childNodes[2];
this._rulerEle = this._topDiv.childNodes[3];
this._context = this._trackListEle.getContext("2d");
this._trackList = [];
this._highlightRanges = [];
this.zoomTo(clock.startTime, clock.stopTime);
this._onMouseDown = createMouseDownCallback(this);
this._onMouseUp = createMouseUpCallback(this);
this._onMouseMove = createMouseMoveCallback(this);
this._onMouseWheel = createMouseWheelCallback(this);
this._onTouchStart = createTouchStartCallback(this);
this._onTouchMove = createTouchMoveCallback(this);
this._onTouchEnd = createTouchEndCallback(this);
const timeBarEle = this._timeBarEle;
ownerDocument.addEventListener("mouseup", this._onMouseUp, false);
ownerDocument.addEventListener("mousemove", this._onMouseMove, false);
timeBarEle.addEventListener("mousedown", this._onMouseDown, false);
timeBarEle.addEventListener("DOMMouseScroll", this._onMouseWheel, false);
timeBarEle.addEventListener("mousewheel", this._onMouseWheel, false);
timeBarEle.addEventListener("touchstart", this._onTouchStart, false);
timeBarEle.addEventListener("touchmove", this._onTouchMove, false);
timeBarEle.addEventListener("touchend", this._onTouchEnd, false);
timeBarEle.addEventListener("touchcancel", this._onTouchEnd, false);
this._topDiv.oncontextmenu = function() {
return false;
};
clock.onTick.addEventListener(this.updateFromClock, this);
this.updateFromClock();
}
addEventListener(type, listener, useCapture) {
this._topDiv.addEventListener(type, listener, useCapture);
}
removeEventListener(type, listener, useCapture) {
this._topDiv.removeEventListener(type, listener, useCapture);
}
isDestroyed() {
return false;
}
destroy() {
this._clock.onTick.removeEventListener(this.updateFromClock, this);
const doc = this.container.ownerDocument;
doc.removeEventListener("mouseup", this._onMouseUp, false);
doc.removeEventListener("mousemove", this._onMouseMove, false);
const timeBarEle = this._timeBarEle;
timeBarEle.removeEventListener("mousedown", this._onMouseDown, false);
timeBarEle.removeEventListener("DOMMouseScroll", this._onMouseWheel, false);
timeBarEle.removeEventListener("mousewheel", this._onMouseWheel, false);
timeBarEle.removeEventListener("touchstart", this._onTouchStart, false);
timeBarEle.removeEventListener("touchmove", this._onTouchMove, false);
timeBarEle.removeEventListener("touchend", this._onTouchEnd, false);
timeBarEle.removeEventListener("touchcancel", this._onTouchEnd, false);
this.container.removeChild(this._topDiv);
Cesium.destroyObject(this);
}
addHighlightRange(color, heightInPx, base) {
const newHighlightRange = new VcTimelineHighlightRange(color, heightInPx, base);
this._highlightRanges.push(newHighlightRange);
this.resize();
return newHighlightRange;
}
addTrack(interval, heightInPx, color, backgroundColor) {
const newTrack = new TimelineTrack(interval, heightInPx, color, backgroundColor);
this._trackList.push(newTrack);
this._lastHeight = void 0;
this.resize();
return newTrack;
}
resize() {
const width = this.container.clientWidth;
const height = this.container.clientHeight;
if (width === this._lastWidth && height === this._lastHeight) {
return;
}
this._trackContainer.style.height = `${height}px`;
let trackListHeight = 1;
this._trackList.forEach(function(track) {
trackListHeight += track.height;
});
this._trackListEle.style.height = `${trackListHeight.toString()}px`;
this._trackListEle.width = this._trackListEle.clientWidth;
this._trackListEle.height = trackListHeight;
this._makeTics();
this._lastXPos = void 0;
this._lastWidth = width;
this._lastHeight = height;
}
zoomTo(startTime, stopTime) {
const { defined, JulianDate, DeveloperError, ClockRange } = Cesium;
if (!defined(startTime)) {
throw new DeveloperError("startTime is required.");
}
if (!defined(stopTime)) {
throw new DeveloperError("stopTime is required");
}
if (JulianDate.lessThanOrEquals(stopTime, startTime)) {
throw new DeveloperError("Start time must come before end time.");
}
this._startJulian = startTime;
this._endJulian = stopTime;
this._timeBarSecondsSpan = JulianDate.secondsDifference(stopTime, startTime);
if (this._clock && this._clock.clockRange !== ClockRange.UNBOUNDED) {
const clockStart = this._clock.startTime;
const clockEnd = this._clock.stopTime;
const clockSpan = JulianDate.secondsDifference(clockEnd, clockStart);
const startOffset = JulianDate.secondsDifference(clockStart, this._startJulian);
const endOffset = JulianDate.secondsDifference(clockEnd, this._endJulian);
if (this._timeBarSecondsSpan >= clockSpan) {
this._timeBarSecondsSpan = clockSpan;
this._startJulian = this._clock.startTime;
this._endJulian = this._clock.stopTime;
} else if (startOffset > 0) {
this._endJulian = JulianDate.addSeconds(this._endJulian, startOffset, new JulianDate());
this._startJulian = clockStart;
this._timeBarSecondsSpan = JulianDate.secondsDifference(this._endJulian, this._startJulian);
} else if (endOffset < 0) {
this._startJulian = JulianDate.addSeconds(this._startJulian, endOffset, new JulianDate());
this._endJulian = clockEnd;
this._timeBarSecondsSpan = JulianDate.secondsDifference(this._endJulian, this._startJulian);
}
}
this._makeTics();
const evt = new Event("setzoom", { bubbles: true, cancelable: true, composed: true });
evt.startJulian = this._startJulian;
evt.endJulian = this._endJulian;
evt.epochJulian = this._epochJulian;
evt.totalSpan = this._timeBarSecondsSpan;
evt.mainTicSpan = this._mainTicSpan;
this._topDiv.dispatchEvent(evt);
}
updateFromClock() {
const { defined, JulianDate } = Cesium;
this._scrubJulian = this._clock.currentTime;
const scrubElement = this._scrubElement;
if (defined(this._scrubElement)) {
const seconds = JulianDate.secondsDifference(this._scrubJulian, this._startJulian);
const xPos = Math.round(seconds * this._topDiv.clientWidth / this._timeBarSecondsSpan);
if (this._lastXPos !== xPos) {
this._lastXPos = xPos;
scrubElement.style.left = `${xPos - 8}px`;
this._needleEle.style.left = `${xPos}px`;
}
}
if (defined(this._timelineDragLocation)) {
this._setTimeBarTime(this._timelineDragLocation, this._timelineDragLocation * this._timeBarSecondsSpan / this._topDiv.clientWidth);
this.zoomTo(
JulianDate.addSeconds(this._startJulian, this._timelineDrag, new JulianDate()),
JulianDate.addSeconds(this._endJulian, this._timelineDrag, new JulianDate())
);
}
}
_setTimeBarTime(xPos, seconds) {
const { JulianDate } = Cesium;
xPos = Math.round(xPos);
this._scrubJulian = JulianDate.addSeconds(this._startJulian, seconds, new JulianDate());
if (this._scrubElement) {
const scrubX = xPos - 8;
this._scrubElement.style.left = `${scrubX.toString()}px`;
this._needleEle.style.left = `${xPos.toString()}px`;
}
const evt = new Event("settime", { bubbles: true, cancelable: true, composed: true });
evt.clientX = xPos;
evt.timeSeconds = seconds;
evt.timeJulian = this._scrubJulian;
evt.clock = this._clock;
this._topDiv.dispatchEvent(evt);
}
zoomFrom(amount) {
const { JulianDate } = Cesium;
let centerSec = JulianDate.secondsDifference(this._scrubJulian, this._startJulian);
if (amount > 1 || centerSec < 0 || centerSec > this._timeBarSecondsSpan) {
centerSec = this._timeBarSecondsSpan * 0.5;
} else {
centerSec += centerSec - this._timeBarSecondsSpan * 0.5;
}
const centerSecFlip = this._timeBarSecondsSpan - centerSec;
this.zoomTo(
JulianDate.addSeconds(this._startJulian, centerSec - centerSec * amount, new JulianDate()),
JulianDate.addSeconds(this._endJulian, centerSecFlip * amount - centerSecFlip, new JulianDate())
);
}
makeLabel(time) {
const { JulianDate } = Cesium;
const gregorian = JulianDate.toGregorianDate(time);
const millisecond = gregorian.millisecond;
let millisecondString = " UTC";
if (millisecond > 0 && this._timeBarSecondsSpan < 3600) {
millisecondString = Math.floor(millisecond).toString();
while (millisecondString.length < 3) {
millisecondString = `0${millisecondString}`;
}
millisecondString = `.${millisecondString}`;
}
return `${timelineMonthNames[gregorian.month - 1]} ${gregorian.day} ${gregorian.year} ${twoDigits(gregorian.hour)}:${twoDigits(
gregorian.minute
)}:${twoDigits(gregorian.second)}${millisecondString}`;
}
_makeTics() {
const { JulianDate } = Cesium;
const timeBar = this._timeBarEle;
const seconds = JulianDate.secondsDifference(this._scrubJulian, this._startJulian);
const xPos = Math.round(seconds * this._topDiv.clientWidth / this._timeBarSecondsSpan);
const scrubX = xPos - 8;
let tic;
const widget = this;
this._needleEle.style.left = `${xPos.toString()}px`;
let tics = "";
const minimumDuration = 0.01;
const maximumDuration = 31536e6;
const epsilon = 1e-10;
let minSize = 0;
let duration = this._timeBarSecondsSpan;
if (duration < minimumDuration) {
duration = minimumDuration;
this._timeBarSecondsSpan = minimumDuration;
this._endJulian = JulianDate.addSeconds(this._startJulian, minimumDuration, new JulianDate());
} else if (duration > maximumDuration) {
duration = maximumDuration;
this._timeBarSecondsSpan = maximumDuration;
this._endJulian = JulianDate.addSeconds(this._startJulian, maximumDuration, new JulianDate());
}
let timeBarWidth = this._timeBarEle.clientWidth;
if (timeBarWidth < 10) {
timeBarWidth = 10;
}
const startJulian = this._startJulian;
const epsilonTime = Math.min(duration / timeBarWidth * 1e-5, 0.4);
let epochJulian;
const gregorianDate = JulianDate.toGregorianDate(startJulian);
if (duration > 31536e4) {
epochJulian = JulianDate.fromDate(new Date(Date.UTC(Math.floor(gregorianDate.year / 100) * 100, 0)));
} else if (duration > 31536e3) {
epochJulian = JulianDate.fromDate(new Date(Date.UTC(Math.floor(gregorianDate.year / 10) * 10, 0)));
} else if (duration > 86400) {
epochJulian = JulianDate.fromDate(new Date(Date.UTC(gregorianDate.year, 0)));
} else {
epochJulian = JulianDate.fromDate(new Date(Date.UTC(gregorianDate.year, gregorianDate.month, gregorianDate.day)));
}
const startTime = JulianDate.secondsDifference(this._startJulian, JulianDate.addSeconds(epochJulian, epsilonTime, new JulianDate()));
let endTime = startTime + duration;
this._epochJulian = epochJulian;
function getStartTic(ticScale) {
return Math.floor(startTime / ticScale) * ticScale;
}
function getNextTic(tic2, ticScale) {
return Math.ceil(tic2 / ticScale + 0.5) * ticScale;
}
function getAlpha(time) {
return (time - startTime) / duration;
}
function remainder(x, y) {
return x - y * Math.round(x / y);
}
this._rulerEle.innerHTML = this.makeLabel(JulianDate.addSeconds(this._endJulian, -minimumDuration, new JulianDate()));
let sampleWidth = this._rulerEle.offsetWidth + 20;
if (sampleWidth < 30) {
sampleWidth = 180;
}
const origMinSize = minSize;
minSize -= epsilon;
const renderState = {
startTime,
startJulian,
epochJulian,
duration,
timeBarWidth,
getAlpha
};
this._highlightRanges.forEach(function(highlightRange) {
tics += highlightRange.render(renderState);
});
let mainTic = 0, subTic = 0, tinyTic = 0;
let idealTic = sampleWidth / timeBarWidth;
if (idealTic > 1) {
idealTic = 1;
}
idealTic *= this._timeBarSecondsSpan;
let ticIndex = -1, smallestIndex = -1;
const ticScaleLen = timelineTicScales.length;
let i;
for (i = 0; i < ticScaleLen; ++i) {
const sc = timelineTicScales[i];
++ticIndex;
mainTic = sc;
if (sc > idealTic && sc > minSize) {
break;
}
if (smallestIndex < 0 && timeBarWidth * (sc / this._timeBarSecondsSpan) >= this.smallestTicInPixels) {
smallestIndex = ticIndex;
}
}
if (ticIndex > 0) {
while (ticIndex > 0) {
--ticIndex;
if (Math.abs(remainder(mainTic, timelineTicScales[ticIndex])) < 1e-5) {
if (timelineTicScales[ticIndex] >= minSize) {
subTic = timelineTicScales[ticIndex];
}
break;
}
}
if (smallestIndex >= 0) {
while (smallestIndex < ticIndex) {
if (Math.abs(remainder(subTic, timelineTicScales[smallestIndex])) < 1e-5 && timelineTicScales[smallestIndex] >= minSize) {
tinyTic = timelineTicScales[smallestIndex];
break;
}
++smallestIndex;
}
}
}
minSize = origMinSize;
if (minSize > epsilon && tinyTic < 1e-5 && Math.abs(minSize - mainTic) > epsilon) {
tinyTic = minSize;
if (minSize <= mainTic + epsilon) {
subTic = 0;
}
}
let lastTextLeft = -999999, textWidth;
if (timeBarWidth * (tinyTic / this._timeBarSecondsSpan) >= 3) {
for (tic = getStartTic(tinyTic); tic <= endTime; tic = getNextTic(tic, tinyTic)) {
tics += `<span class="cesium-timeline-ticTiny" style="left: ${Math.round(timeBarWidth * getAlpha(tic)).toString()}px;"></span>`;
}
}
if (timeBarWidth * (subTic / this._timeBarSecondsSpan) >= 3) {
for (tic = getStartTic(subTic); tic <= endTime; tic = getNextTic(tic, subTic)) {
tics += `<span class="cesium-timeline-ticSub" style="left: ${Math.round(timeBarWidth * getAlpha(tic)).toString()}px;"></span>`;
}
}
if (timeBarWidth * (mainTic / this._timeBarSecondsSpan) >= 2) {
this._mainTicSpan = mainTic;
endTime += mainTic;
tic = getStartTic(mainTic);
const leapSecond = JulianDate.computeTaiMinusUtc(epochJulian);
while (tic <= endTime) {
let ticTime = JulianDate.addSeconds(startJulian, tic - startTime, new JulianDate());
if (mainTic > 2.1) {
const ticLeap = JulianDate.computeTaiMinusUtc(ticTime);
if (Math.abs(ticLeap - leapSecond) > 0.1) {
tic += ticLeap - leapSecond;
ticTime = JulianDate.addSeconds(startJulian, tic - startTime, new JulianDate());
}
}
const ticLeft = Math.round(timeBarWidth * getAlpha(tic));
const ticLabel = this.makeLabel(ticTime);
this._rulerEle.innerHTML = ticLabel;
textWidth = this._rulerEle.offsetWidth;
if (textWidth < 10) {
textWidth = sampleWidth;
}
const labelLeft = ticLeft - (textWidth / 2 - 1);
if (labelLeft > lastTextLeft) {
lastTextLeft = labelLeft + textWidth + 5;
tics += `<span class="cesium-timeline-ticMain" style="left: ${ticLeft.toString()}px;"></span><span class="cesium-timeline-ticLabel" style="left: ${labelLeft.toString()}px;">${ticLabel}</span>`;
} else {
tics += `<span class="cesium-timeline-ticSub" style="left: ${ticLeft.toString()}px;"></span>`;
}
tic = getNextTic(tic, mainTic);
}
} else {
this._mainTicSpan = -1;
}
tics += `<span class="cesium-timeline-icon16" style="left:${scrubX}px;bottom:0;background-position: 0 0;"></span>`;
timeBar.innerHTML = tics;
this._scrubElement = timeBar.lastChild;
this._context.clearRect(0, 0, this._trackListEle.width, this._trackListEle.height);
renderState.y = 0;
this._trackList.forEach(function(track) {
track.render(widget._context, renderState);
renderState.y += track.height;
});
}
} exports('VcTimeline', VcTimeline);
function createMouseDownCallback(timeline) {
return function(e) {
if (timeline._mouseMode !== timelineMouseMode.touchOnly) {
if (e.button === 0) {
timeline._mouseMode = timelineMouseMode.scrub;
if (timeline._scrubElement) {
timeline._scrubElement.style.backgroundPosition = "-16px 0";
}
timeline._onMouseMove(e);
} else {
timeline._mouseX = e.clientX;
if (e.button === 2) {
timeline._mouseMode = timelineMouseMode.zoom;
} else {
timeline._mouseMode = timelineMouseMode.slide;
}
}
}
e.preventDefault();
};
}
function createMouseUpCallback(timeline) {
return function(e) {
timeline._mouseMode = timelineMouseMode.none;
if (timeline._scrubElement) {
timeline._scrubElement.style.backgroundPosition = "0 0";
}
timeline._timelineDrag = 0;
timeline._timelineDragLocation = void 0;
};
}
function createMouseMoveCallback(timeline) {
return function(e) {
let dx;
if (timeline._mouseMode === timelineMouseMode.scrub) {
e.preventDefault();
const x = e.clientX - timeline._topDiv.getBoundingClientRect().left;
if (x < 0) {
timeline._timelineDragLocation = 0;
timeline._timelineDrag = -0.01 * timeline._timeBarSecondsSpan;
} else if (x > timeline._topDiv.clientWidth) {
timeline._timelineDragLocation = timeline._topDiv.clientWidth;
timeline._timelineDrag = 0.01 * timeline._timeBarSecondsSpan;
} else {
timeline._timelineDragLocation = void 0;
timeline._setTimeBarTime(x, x * timeline._timeBarSecondsSpan / timeline._topDiv.clientWidth);
}
} else if (timeline._mouseMode === timelineMouseMode.slide) {
dx = timeline._mouseX - e.clientX;
timeline._mouseX = e.clientX;
if (dx !== 0) {
const { JulianDate } = Cesium;
const dsec = dx * timeline._timeBarSecondsSpan / timeline._topDiv.clientWidth;
timeline.zoomTo(
JulianDate.addSeconds(timeline._startJulian, dsec, new JulianDate()),
JulianDate.addSeconds(timeline._endJulian, dsec, new JulianDate())
);
}
} else if (timeline._mouseMode === timelineMouseMode.zoom) {
dx = timeline._mouseX - e.clientX;
timeline._mouseX = e.clientX;
if (dx !== 0) {
timeline.zoomFrom(Math.pow(1.01, dx));
}
}
};
}
function createMouseWheelCallback(timeline) {
return function(e) {
let dy = e.wheelDeltaY || e.wheelDelta || -e.detail;
timelineWheelDelta = Math.max(Math.min(Math.abs(dy), timelineWheelDelta), 1);
dy /= timelineWheelDelta;
timeline.zoomFrom(Math.pow(1.05, -dy));
};
}
function createTouchStartCallback(timeline) {
return function(e) {
const len = e.touches.length;
let seconds, xPos;
const leftX = timeline._topDiv.getBoundingClientRect().left;
e.preventDefault();
timeline._mouseMode = timelineMouseMode.touchOnly;
if (len === 1) {
seconds = Cesium.JulianDate.secondsDifference(timeline._scrubJulian, timeline._startJulian);
xPos = Math.round(seconds * timeline._topDiv.clientWidth / timeline._timeBarSecondsSpan + leftX);
if (Math.abs(e.touches[0].clientX - xPos) < 50) {
timeline._touchMode = timelineTouchMode.scrub;
if (timeline._scrubElement) {
timeline._scrubElement.style.backgroundPosition = len === 1 ? "-16px 0" : "0 0";
}
} else {
timeline._touchMode = timelineTouchMode.singleTap;
timeline._touchState.centerX = e.touches[0].clientX - leftX;
}
} else if (len === 2) {
timeline._touchMode = timelineTouchMode.slideZoom;
timeline._touchState.centerX = (e.touches[0].clientX + e.touches[1].clientX) * 0.5 - leftX;
timeline._touchState.spanX = Math.abs(e.touches[0].clientX - e.touches[1].clientX);
} else {
timeline._touchMode = timelineTouchMode.ignore;
}
};
}
function createTouchEndCallback(timeline) {
return function(e) {
const len = e.touches.length, leftX = timeline._topDiv.getBoundingClientRect().left;
if (timeline._touchMode === timelineTouchMode.singleTap) {
timeline._touchMode = timelineTouchMode.scrub;
timeline._onTouchMove(e);
} else if (timeline._touchMode === timelineTouchMode.scrub) {
timeline._onTouchMove(e);
}
timeline._mouseMode = timelineMouseMode.touchOnly;
if (len !== 1) {
timeline._touchMode = len > 0 ? timelineTouchMode.ignore : timelineTouchMode.none;
} else if (timeline._touchMode === timelineTouchMode.slideZoom) {
timeline._touchState.centerX = e.touches[0].clientX - leftX;
}
if (timeline._scrubElement) {
timeline._scrubElement.style.backgroundPosition = "0 0";
}
};
}
function createTouchMoveCallback(timeline) {
return function(e) {
let dx, x, len, newCenter, newSpan, newStartTime, zoom = 1;
const leftX = timeline._topDiv.getBoundingClientRect().left;
if (timeline._touchMode === timelineTouchMode.singleTap) {
timeline._touchMode = timelineTouchMode.slideZoom;
}
timeline._mouseMode = timelineMouseMode.touchOnly;
if (timeline._touchMode === timelineTouchMode.scrub) {
e.preventDefault();
if (e.changedTouches.length === 1) {
x = e.changedTouches[0].clientX - leftX;
if (x >= 0 && x <= timeline._topDiv.clientWidth) {
timeline._setTimeBarTime(x, x * timeline._timeBarSecondsSpan / timeline._topDiv.clientWidth);
}
}
} else if (timeline._touchMode === timelineTouchMode.slideZoom) {
len = e.touches.length;
if (len === 2) {
newCenter = (e.touches[0].clientX + e.touches[1].clientX) * 0.5 - leftX;
newSpan = Math.abs(e.touches[0].clientX - e.touches[1].clientX);
} else if (len === 1) {
newCenter = e.touches[0].clientX - leftX;
newSpan = 0;
}
const { defined, JulianDate } = Cesium;
if (defined(newCenter)) {
if (newSpan > 0 && timeline._touchState.spanX > 0) {
zoom = timeline._touchState.spanX / newSpan;
newStartTime = JulianDate.addSeconds(
timeline._startJulian,
(timeline._touchState.centerX * timeline._timeBarSecondsSpan - newCenter * timeline._timeBarSecondsSpan * zoom) / timeline._topDiv.clientWidth,
new JulianDate()
);
} else {
dx = timeline._touchState.centerX - newCenter;
newStartTime = JulianDate.addSeconds(
timeline._startJulian,
dx * timeline._timeBarSecondsSpan / timeline._topDiv.clientWidth,
new JulianDate()
);
}
timeline.zoomTo(newStartTime, JulianDate.addSeconds(newStartTime, timeline._timeBarSecondsSpan * zoom, new JulianDate()));
timeline._touchState.centerX = newCenter;
timeline._touchState.spanX = newSpan;
}
}
};
}
function twoDigits(num) {
return num < 10 ? `0${num.toString()}` : num.toString();
}
const vcExtends = [RectangleExtend, ShadowMapShaderExtend, MaterialExtend];
function useVcExtension() {
const invokeExtensions = (viewer) => {
vcExtends.forEach((item) => {
item.extend(viewer);
});
};
const revokeExtensions = (viewer) => {
vcExtends.forEach((item) => {
item.revoke(viewer);
});
};
return {
invokeExtensions,
revokeExtensions
};
}
const viewerProps = exports('viewerProps', defaultProps$7);
function useViewer(props, ctx, vcInstance) {
let createResolve, reject;
const creatingPromise = new Promise((_resolve, _reject) => {
createResolve = _resolve;
reject = _reject;
});
const viewerRef = ref();
const isReady = ref(false);
const vcMitt = mitt();
const { emit } = ctx;
const globalConfig = useGlobalConfig();
const logger = useLog(vcInstance);
vcInstance.mounted = false;
vcInstance.vcMitt = vcMitt;
vcInstance.cesiumClass = "Viewer";
vcInstance.children = [];
const eventsState = useEvents(props, vcInstance);
const layout = reactive({
toolbarContainerRC: void 0,
timelineContainerRC: void 0,
animationContainerRC: void 0,
bottomContainerRC: void 0
});
let loadLibs = [];
logger.debug("viewer creating");
const { t } = useLocale();
const { invokeExtensions, revokeExtensions } = useVcExtension();
watch(
() => props.selectionIndicator,
(val) => {
const { viewer, viewerElement } = vcInstance;
const { defined, SelectionIndicator } = Cesium;
let selectionIndicatorContainer;
if (defined(viewer.selectionIndicator) && !viewer.selectionIndicator.isDestroyed() && !val) {
selectionIndicatorContainer = viewer.selectionIndicator.container;
viewerElement == null ? void 0 : viewerElement.removeChild(selectionIndicatorContainer);
viewer.selectionIndicator.destroy();
viewer._selectionIndicator = void 0;
} else if (!defined(viewer.selectionIndicator) || viewer.selectionIndicator.isDestroyed()) {
selectionIndicatorContainer = document.createElement("div");
selectionIndicatorContainer.className = "cesium-viewer-selectionIndicatorContainer";
viewerElement == null ? void 0 : viewerElement.appendChild(selectionIndicatorContainer);
const selectionIndicator = new SelectionIndicator(selectionIndicatorContainer, viewer.scene);
viewer._selectionIndicator = selectionIndicator;
}
viewer.viewerWidgetResized.raiseEvent({
type: "selectionIndicator",
status: val ? "added" : "removed",
target: selectionIndicatorContainer
});
}
);
watch(
() => props.infoBox,
(val) => {
var _a, _b;
const { viewer, viewerElement } = vcInstance;
const { defined, InfoBox } = Cesium;
const events = ["cameraClicked", "closeClicked"];
let infoBoxContainer;
if (defined(viewer.infoBox) && !viewer.infoBox.isDestroyed() && !val) {
const infoBoxViewModel = viewer.infoBox.viewModel;
infoBoxViewModel && eventsState.bindEvents(infoBoxViewModel, events, false);
infoBoxContainer = viewer.infoBox.container;
viewerElement == null ? void 0 : viewerElement.removeChild(infoBoxContainer);
viewer.infoBox.destroy();
viewer._infoBox = void 0;
} else if (!defined(viewer.infoBox) || viewer.infoBox.isDestroyed()) {
infoBoxContainer = document.createElement("div");
infoBoxContainer.className = "cesium-viewer-infoBoxContainer";
viewerElement == null ? void 0 : viewerElement.appendChild(infoBoxContainer);
const infoBox = new InfoBox(infoBoxContainer);
const infoBoxViewModel = infoBox.viewModel;
viewer._onInfoBoxCameraClicked && ((_a = viewer._eventHelper) == null ? void 0 : _a.add(infoBoxViewModel.cameraClicked, viewer._onInfoBoxCameraClicked, viewer));
viewer._onInfoBoxClockClicked && ((_b = viewer._eventHelper) == null ? void 0 : _b.add(infoBoxViewModel.closeClicked, viewer._onInfoBoxClockClicked, viewer));
infoBoxViewModel && eventsState.bindEvents(infoBoxViewModel, events, true);
viewer._infoBox = infoBox;
}
viewer.forceResize();
viewer.viewerWidgetResized.raiseEvent({
type: "infoBox",
status: val ? "added" : "removed",
target: infoBoxContainer
});
}
);
watch(
() => props.geocoder,
(val) => {
var _a;
const { viewer } = vcInstance;
const toolbar = viewer._toolbar;
const { defined, Geocoder } = Cesium;
let geocoderContainer;
if (defined(viewer.geocoder) && !viewer.geocoder.isDestroyed() && !val) {
geocoderContainer = viewer.geocoder.container;
toolbar == null ? void 0 : toolbar.removeChild(geocoderContainer);
viewer.geocoder.destroy();
viewer._geocoder = void 0;
} else if (!defined(viewer.geocoder) || viewer.geocoder.isDestroyed()) {
geocoderContainer = document.createElement("div");
geocoderContainer.className = "cesium-viewer-geocoderContainer";
toolbar == null ? void 0 : toolbar.appendChild(geocoderContainer);
const geocoder = new Geocoder({
container: geocoderContainer,
geocoderServices: defined(props.geocoder) && typeof props.geocoder !== "boolean" ? Array.isArray(props.geocoder) ? props.geocoder : [props.geocoder] : void 0,
scene: viewer.scene
});
viewer._clearObjects && ((_a = viewer._eventHelper) == null ? void 0 : _a.add(geocoder.viewModel.search.beforeExecute, viewer._clearObjects, viewer));
viewer._geocoder = geocoder;
resizeToolbar(toolbar);
}
viewer.viewerWidgetResized.raiseEvent({
type: "geocoder",
status: val ? "added" : "removed",
target: geocoderContainer
});
}
);
watch(
() => props.homeButton,
(val) => {
var _a, _b;
const { viewer } = vcInstance;
const toolbar = viewer._toolbar;
const { defined, HomeButton } = Cesium;
if (defined(viewer.homeButton) && !viewer.homeButton.isDestroyed() && !val) {
viewer.homeButton.destroy();
viewer._homeButton = void 0;
} else if (!defined(viewer.homeButton) || viewer.homeButton.isDestroyed()) {
const homeButton = new HomeButton(toolbar, viewer.scene);
if (defined(viewer.geocoder)) {
(_a = viewer._eventHelper) == null ? void 0 : _a.add(homeButton.viewModel.command.afterExecute, function() {
const viewModel = viewer.geocoder.viewModel;
viewModel.searchText = "";
viewModel.isSearchInProgress && viewModel.search();
});
}
viewer._clearTrackedObject && ((_b = viewer._eventHelper) == null ? void 0 : _b.add(homeButton.viewModel.command.beforeExecute, viewer._clearTrackedObject, viewer));
viewer._homeButton = homeButton;
resizeToolbar(toolbar);
}
viewer.viewerWidgetResized.raiseEvent({
type: "homeButton",
status: val ? "added" : "removed",
target: toolbar
});
}
);
watch(
() => props.sceneModePicker,
(val) => {
const { viewer } = vcInstance;
const toolbar = viewer._toolbar;
const { defined, DeveloperError, SceneModePicker } = Cesium;
if (defined(viewer.sceneModePicker) && !viewer.sceneModePicker.isDestroyed() && !val) {
viewer.sceneModePicker.destroy();
viewer._sceneModePicker = void 0;
} else if (!defined(viewer.sceneModePicker) || viewer.sceneModePicker.isDestroyed()) {
if (props.sceneModePicker && props.scene3DOnly) {
throw new DeveloperError("options.sceneModePicker is not available when options.scene3DOnly is set to true.");
}
if (!props.scene3DOnly && props.sceneModePicker) {
const sceneModePicker = new SceneModePicker(toolbar, viewer.scene);
viewer._sceneModePicker = sceneModePicker;
resizeToolbar(toolbar);
}
}
viewer.viewerWidgetResized.raiseEvent({
type: "sceneModePicker",
status: val ? "added" : "removed",
target: toolbar
});
}
);
watch(
() => props.projectionPicker,
(val) => {
const { viewer } = vcInstance;
const toolbar = viewer._toolbar;
const { defined, ProjectionPicker } = Cesium;
if (defined(viewer.projectionPicker) && !viewer.projectionPicker.isDestroyed() && !val) {
viewer.projectionPicker.destroy();
viewer._projectionPicker = void 0;
} else if (!defined(viewer.projectionPicker) || viewer.projectionPicker.isDestroyed()) {
const projectionPicker = new ProjectionPicker(toolbar, viewer.scene);
viewer._projectionPicker = projectionPicker;
resizeToolbar(toolbar);
}
viewer.viewerWidgetResized.raiseEvent({
type: "projectionPicker",
status: val ? "added" : "removed",
target: toolbar
});
}
);
watch(
() => props.baseLayerPicker,
async (val) => {
const { viewer } = vcInstance;
const toolbar = viewer._toolbar;
const {
defined,
buildModuleUrl,
DeveloperError,
defaultValue,
createDefaultImageryProviderViewModels,
createDefaultTerrainProviderViewModels,
BaseLayerPicker
} = Cesium;
if (defined(viewer.baseLayerPicker) && !viewer.baseLayerPicker.isDestroyed() && !val) {
viewer.baseLayerPicker.destroy();
viewer._baseLayerPicker = void 0;
viewer.imageryLayers.remove(viewer.imageryLayers.get(viewer.imageryLayers.length - 1));
const url = buildModuleUrl("Assets/Textures/NaturalEarthII");
const baseLayer = viewer.imageryLayers.addImageryProvider(
compareCesiumVersion(Cesium.VERSION, "1.104") ? await Cesium.TileMapServiceImageryProvider.fromUrl(url) : new Cesium.TileMapServiceImageryProvider({
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
url
})
);
viewer.imageryLayers.lowerToBottom(baseLayer);
} else if (!defined(viewer.baseLayerPicker) || viewer.baseLayerPicker.isDestroyed()) {
const createBaseLayerPicker = (!Cesium.defined(viewer.scene.globe) || props.globe !== false) && (!Cesium.defined(viewer.baseLayerPicker) || props.baseLayerPicker !== false);
if (createBaseLayerPicker && defined(props.imageryProvider)) {
throw new DeveloperError(`options.imageryProvider is not available when using the BaseLayerPicker widget.
Either specify options.selectedImageryProviderViewModel instead or set options.baseLayerPicker to false.`);
}
if (!createBaseLayerPicker && defined(props.selectedImageryProviderViewModel)) {
throw new DeveloperError(`options.selectedImageryProviderViewModel is not available when not using the BaseLayerPicker widget.
Either specify options.imageryProvider instead or set options.baseLayerPicker to true.`);
}
if (createBaseLayerPicker && defined(props.terrainProvider)) {
throw new DeveloperError(`options.terrainProvider is not available when using the BaseLayerPicker widget.
Either specify options.selectedTerrainProviderViewModel instead or set options.baseLayerPicker to false.`);
}
if (!createBaseLayerPicker && defined(props.selectedTerrainProviderViewModel)) {
throw new DeveloperError(`options.selectedTerrainProviderViewModel is not available when not using the BaseLayerPicker widget.
Either specify options.terrainProvider instead or set options.baseLayerPicker to true.`);
}
if (createBaseLayerPicker) {
const imageryProviderViewModels = defaultValue(props.imageryProviderViewModels, createDefaultImageryProviderViewModels());
const terrainProviderViewModels = defaultValue(props.terrainProviderViewModels, createDefaultTerrainProviderViewModels());
const baseLayerPicker = new BaseLayerPicker(toolbar, {
globe: viewer.scene.globe,
imageryProviderViewModels,
selectedImageryProviderViewModel: imageryProviderViewModels[0],
terrainProviderViewModels,
selectedTerrainProviderViewModel: terrainProviderViewModels[0]
});
const elements = toolbar == null ? void 0 : toolbar.getElementsByClassName("cesium-baseLayerPicker-dropDown");
const baseLayerPickerDropDown = elements == null ? void 0 : elements[0];
viewer._baseLayerPickerDropDown = baseLayerPickerDropDown;
viewer._baseLayerPicker = baseLayerPicker;
viewer.imageryLayers.raiseToTop(viewer.imageryLayers.get(0));
resizeToolbar(toolbar);
}
}
viewer.viewerWidgetResized.raiseEvent({
type: "baseLayerPicker",
status: val ? "added" : "removed",
target: toolbar
});
}
);
watch(
() => props.navigationHelpButton,
(val) => {
const { viewer } = vcInstance;
const toolbar = viewer._toolbar;
const { defined, defaultValue, NavigationHelpButton } = Cesium;
if (defined(viewer.navigationHelpButton) && !viewer.navigationHelpButton.isDestroyed() && !val) {
viewer.navigationHelpButton.destroy();
viewer._navigationHelpButton = void 0;
} else if (!defined(viewer.navigationHelpButton) || viewer.navigationHelpButton.isDestroyed()) {
let showNavHelp = true;
try {
if (defined(window.localStorage)) {
const hasSeenNavHelp = window.localStorage.getItem("cesium-hasSeenNavHelp");
if (defined(hasSeenNavHelp) && Boolean(hasSeenNavHelp)) {
showNavHelp = false;
} else {
window.localStorage.setItem("cesium-hasSeenNavHelp", "true");
}
}
} catch (e) {
}
const navigationHelpButton = new NavigationHelpButton({
container: toolbar,
instructionsInitiallyVisible: defaultValue(props.navigationInstructionsInitiallyVisible, showNavHelp)
});
viewer._navigationHelpButton = navigationHelpButton;
resizeToolbar(toolbar);
}
viewer.viewerWidgetResized.raiseEvent({
type: "navigationHelpButton",
status: val ? "added" : "removed",
target: toolbar
});
}
);
watch(
() => props.animation,
(val) => {
const { viewer, viewerElement } = vcInstance;
const { defined, Animation, AnimationViewModel } = Cesium;
let animationContainer;
if (defined(viewer.animation) && !viewer.animation.isDestroyed() && !val) {
animationContainer = viewer.animation.container;
viewerElement == null ? void 0 : viewerElement.removeChild(animationContainer);
viewer.animation.destroy();
viewer._animation = void 0;
} else if (!defined(viewer.animation) || viewer.animation.isDestroyed()) {
animationContainer = document.createElement("div");
animationContainer.className = "cesium-viewer-animationContainer";
viewerElement == null ? void 0 : viewerElement.appendChild(animationContainer);
const animation = new Animation(animationContainer, new AnimationViewModel(viewer.clockViewModel));
animation.viewModel.dateFormatter = localeDateTimeFormatter;
animation.viewModel.timeFormatter = localeTimeFormatter;
viewer._animation = animation;
}
viewer.forceResize();
viewer.viewerWidgetResized.raiseEvent({
type: "animation",
status: val ? "added" : "removed",
target: animationContainer
});
}
);
watch(
() => props.timeline,
(val) => {
var _a;
const { viewer, viewerElement } = vcInstance;
const { defined, Timeline } = Cesium;
let timelineContainer;
if (defined(viewer.timeline) && !viewer.timeline.isDestroyed() && !val) {
timelineContainer = viewer.timeline.container;
viewerElement == null ? void 0 : viewerElement.removeChild(timelineContainer);
viewer.timeline.destroy();
viewer._timeline = void 0;
} else if (!defined(viewer.timeline) || viewer.timeline.isDestroyed()) {
timelineContainer = document.createElement("div");
timelineContainer.className = "cesium-viewer-timelineContainer";
viewerElement == null ? void 0 : viewerElement.appendChild(timelineContainer);
const timeline = new Timeline(timelineContainer, viewer.clock);
timeline.makeLabel = (time) => {
return localeDateTimeFormatter(time);
};
(_a = timeline.addEventListener) == null ? void 0 : _a.call(timeline, "settime", onTimelineScrubfunction, false);
timeline.zoomTo(viewer.clock.startTime, viewer.clock.stopTime);
viewer._timeline = timeline;
}
viewer.forceResize();
viewer.viewerWidgetResized.raiseEvent({
type: "timeline",
status: val ? "added" : "removed",
target: timelineContainer
});
}
);
watch(
() => props.fullscreenButton,
(val) => {
const { viewer, viewerElement } = vcInstance;
const { defined, FullscreenButton } = Cesium;
let fullscreenContainer;
if (defined(viewer.fullscreenButton) && !viewer.fullscreenButton.isDestroyed() && !val) {
fullscreenContainer = viewer.fullscreenButton.container;
viewerElement == null ? void 0 : viewerElement.removeChild(fullscreenContainer);
viewer.fullscreenButton.destroy();
viewer._fullscreenButton = void 0;
} else if (!defined(viewer.fullscreenButton) || viewer.fullscreenButton.isDestroyed()) {
fullscreenContainer = document.createElement("div");
fullscreenContainer.className = "cesium-viewer-fullscreenContainer";
viewerElement == null ? void 0 : viewerElement.appendChild(fullscreenContainer);
const fullscreenButton = new FullscreenButton(fullscreenContainer, viewerElement);
viewer._fullscreenButton = fullscreenButton;
}
viewer.forceResize();
viewer.viewerWidgetResized.raiseEvent({
type: "fullscreenButton",
status: val ? "added" : "removed",
target: fullscreenContainer
});
}
);
watch(
() => props.fullscreenElement,
(val) => {
const { viewer } = vcInstance;
const { defined } = Cesium;
if (!defined(viewer.fullscreenButton)) {
return;
}
if (defined(val)) {
viewer.fullscreenButton.viewModel.fullscreenElement = val;
}
}
);
watch(
() => props.vrButton,
(val) => {
const { viewer, viewerElement } = vcInstance;
const { defined, VRButton } = Cesium;
let vrContainer;
if (defined(viewer.vrButton) && !viewer.vrButton.isDestroyed() && !val) {
vrContainer = viewer.vrButton.container;
viewerElement == null ? void 0 : viewerElement.removeChild(vrContainer);
viewer.vrButton.destroy();
viewer._vrButton = void 0;
} else if (!defined(viewer.vrButton) || viewer.vrButton.isDestroyed()) {
vrContainer = document.createElement("div");
vrContainer.className = "cesium-viewer-vrContainer";
viewerElement == null ? void 0 : viewerElement.appendChild(vrContainer);
const vrButton = new VRButton(vrContainer, viewer.scene, viewerElement);
const viewModelCommand = vrButton.viewModel.command;
vrButton.viewModel._command = function(VRButtonViewModel) {
viewModelCommand();
enableVRUI(viewer, VRButtonViewModel.isVRMode);
};
viewer._vrButton = vrButton;
}
viewer.forceResize();
viewer.viewerWidgetResized.raiseEvent({
type: "fullscreenButton",
status: val ? "added" : "removed",
target: vrContainer
});
}
);
watch(
() => props.useDefaultRenderLoop,
(val) => {
vcInstance.viewer.useDefaultRenderLoop = val;
}
);
watch(
() => props.sceneMode,
(val) => {
const { SceneMode } = Cesium;
if (SceneMode.COLUMBUS_VIEW === val || SceneMode.MORPHING === val || SceneMode.SCENE2D === val || SceneMode.SCENE3D === val) {
vcInstance.viewer.scene.mode = val;
}
}
);
watch(
() => props.shouldAnimate,
(val) => {
vcInstance.viewer.clock.shouldAnimate = val;
}
);
watch(
() => props.terrainExaggeration,
(val) => {
vcInstance.viewer._terrainExaggeration = val;
}
);
watch(
() => props.shadows,
(val) => {
vcInstance.viewer.scene.shadowMap.enabled = val;
}
);
watch(
() => props.terrainProvider,
(val) => {
val && (vcInstance.viewer.terrainProvider = val);
}
);
watch(
() => props.camera,
(val) => {
setViewerCamera(vcInstance.viewer, val);
},
{ deep: true }
);
watch(
() => props.imageryProvider,
(val, oldVal) => {
const { viewer } = vcInstance;
const { defined } = Cesium;
if (defined(val)) {
for (let i = 0; i < viewer.imageryLayers.length; i++) {
viewer.imageryLayers.get(i).imageryProvider === oldVal && viewer.imageryLayers.remove(viewer.imageryLayers[i]);
}
val && viewer.imageryLayers.addImageryProvider(val);
}
}
);
watch(
() => props.showCredit,
(val) => {
const { viewer } = vcInstance;
viewer.cesiumWidget.creditContainer.style.display = val ? "inline" : "none";
viewer.viewerWidgetResized.raiseEvent({
type: "credit",
status: val ? "added" : "removed",
target: viewer.cesiumWidget.creditContainer
});
}
);
watch(
() => props.debugShowFramesPerSecond,
(val) => {
const { viewer } = vcInstance;
viewer.scene.debugShowFramesPerSecond = val;
}
);
const beforeLoad = async function() {
logger.debug("beforeLoad - viewer");
const listener = getInstanceListener(vcInstance, "beforeLoad");
listener && emit("beforeLoad", vcInstance);
globalConfig.value.__scriptPromise = globalConfig.value.__scriptPromise || getCesiumScript();
await globalConfig.value.__scriptPromise;
};
const load = async function() {
var _a, _b, _c;
logger.debug("loading-viewer");
if (vcInstance.mounted) {
return false;
}
await beforeLoad();
if (typeof Cesium === "undefined") {
return false;
}
const { Ion, buildModuleUrl, ImageryLayer, TileMapServiceImageryProvider, Viewer, defined, Math: CesiumMath, Event } = Cesium;
const accessToken = props.accessToken ? props.accessToken : globalConfig.value.accessToken;
Ion.defaultAccessToken = accessToken;
const url = buildModuleUrl("Assets/Textures/NaturalEarthII");
const options = {};
props && Object.keys(props).forEach((vueProp) => {
if (props[vueProp] === void 0 || props[vueProp] === null) {
return;
}
options[vueProp] = props[vueProp];
});
options.fullscreenElement = isEmptyObj(options.fullscreenElement) ? $(viewerRef) : options.fullscreenElement;
if (compareCesiumVersion(Cesium.VERSION, "1.104")) {
options.baseLayer = isEmptyObj(options.baseLayer) ? ImageryLayer.fromProviderAsync(TileMapServiceImageryProvider.fromUrl(url), {}) : options.baseLayer;
} else {
options.imageryProvider = isEmptyObj(options.imageryProvider) ? new TileMapServiceImageryProvider({ url }) : options.imageryProvider;
}
let viewer;
if (props.viewerCreator) {
viewer = props.viewerCreator(vcInstance, $(viewerRef), options);
} else {
if (globalThis.mars3d) {
vcInstance.map = new mars3d.Map($(viewerRef).id, {
scene: options,
control: options
});
viewer = (_a = vcInstance.map) == null ? void 0 : _a._viewer;
} else if (globalThis.DC) {
vcInstance.dcViewer = new DC.Viewer($(viewerRef).id, options);
viewer = (_b = vcInstance.dcViewer) == null ? void 0 : _b.delegate;
} else if (globalThis.XE) {
vcInstance.earth = new globalThis.XE.Earth($(viewerRef), options);
viewer = (_c = vcInstance.earth) == null ? void 0 : _c.czm.viewer;
} else {
viewer = new Viewer($(viewerRef), options);
}
}
invokeExtensions(viewer);
vcInstance.Cesium = Cesium;
vcInstance.viewer = viewer;
vcInstance.viewerElement = viewer._element;
vcInstance.mounted = true;
if (compareCesiumVersion(Cesium.VERSION, "1.83")) {
viewer.scene.globe.terrainExaggeration = options.terrainExaggeration;
}
defined(options.camera) && setViewerCamera(viewer, options.camera);
const listener = getInstanceListener(vcInstance, "update:camera");
listener && viewer.camera.changed.addEventListener(() => {
const cartographic = viewer.camera.positionCartographic;
let cameraNew;
if (hasOwn(options.camera.position, "lng")) {
cameraNew = {
position: {
lng: CesiumMath.toDegrees(cartographic.longitude),
lat: CesiumMath.toDegrees(cartographic.latitude),
height: cartographic.height
},
heading: CesiumMath.toDegrees(viewer.camera.heading || 360),
pitch: CesiumMath.toDegrees(viewer.camera.pitch || -90),
roll: CesiumMath.toDegrees(viewer.camera.roll || 0)
};
} else {
cameraNew = {
position: {
x: viewer.camera.position.x,
y: viewer.camera.position.y,
z: viewer.camera.position.z
},
heading: viewer.camera.heading || 2 * Math.PI,
pitch: viewer.camera.pitch || -Math.PI / 2,
roll: viewer.camera.roll || 0
};
}
emit("update:camera", cameraNew);
});
if (defined(viewer.animation)) {
viewer.animation.viewModel.dateFormatter = localeDateTimeFormatter;
viewer.animation.viewModel.timeFormatter = localeTimeFormatter;
}
if (defined(viewer.timeline)) {
viewer.timeline.makeLabel = (time) => {
return localeDateTimeFormatter(time);
};
viewer.timeline.zoomTo(viewer.clock.startTime, viewer.clock.stopTime);
}
!props.showCredit && (viewer.cesiumWidget.creditContainer.style.display = "none");
props.debugShowFramesPerSecond && (viewer.scene.debugShowFramesPerSecond = true);
viewer.viewerWidgetResized = viewer.viewerWidgetResized || new Event();
viewer.viewerWidgetResized.addEventListener(onViewerWidgetResized);
viewer.imageryLayers.layerAdded.addEventListener(onImageryLayerAdded);
eventsState.registerEvents(true);
const readyObj = {
Cesium,
viewer,
vm: vcInstance
};
if (globalThis.XE) {
Object.assign(readyObj, {
earth: vcInstance.earth
});
} else if (globalThis.mars3d) {
Object.assign(readyObj, {
map: vcInstance.map
});
} else if (globalThis.DC) {
Object.assign(readyObj, {
dcViewer: vcInstance.dcViewer
});
}
const listenerReady = getInstanceListener(vcInstance, "ready");
listenerReady && emit("ready", readyObj);
vcMitt == null ? void 0 : vcMitt.emit("ready", readyObj);
nextTick(() => {
viewer.resize();
onViewerWidgetResized({
type: "viewer",
status: "added",
target: viewer.container
});
isReady.value = true;
});
logger.debug("loaded-viewer");
Object.assign(vcInstance.proxy, {
cesiumObject: viewer
});
return readyObj;
};
const unload = async function() {
if (!vcInstance.mounted) {
return false;
}
logger.debug("viewer---unloading");
let unloadingResolve;
globalConfig.value.__viewerUnloadingPromise = new Promise((resolve, reject2) => {
unloadingResolve = resolve;
});
for (let i = 0; i < vcInstance.children.length; i++) {
const vcChildCmp = vcInstance.children[i].proxy;
await vcChildCmp.unload();
}
vcInstance.children.length = 0;
const { viewer, earth, map, dcViewer } = vcInstance;
if (globalThis.Cesium) {
viewer.imageryLayers.layerAdded.removeEventListener(onImageryLayerAdded);
eventsState.registerEvents(false);
}
const { removeCesiumScript } = props;
viewer._vcPickScreenSpaceEventHandler && viewer._vcPickScreenSpaceEventHandler.destroy();
viewer._vcViewerScreenSpaceEventHandler && viewer._vcViewerScreenSpaceEventHandler.destroy();
viewer._vcPickScreenSpaceEventHandler = void 0;
viewer._vcViewerScreenSpaceEventHandler = void 0;
removeCesiumScript && revokeExtensions(viewer);
delete vcInstance.appContext.config.globalProperties.$VueCesium[viewer.container.id];
if (globalThis.XE) {
earth && earth.destroy();
} else if (globalThis.mars3d) {
map && map.destroy();
} else if (globalThis.DC) {
dcViewer && dcViewer.destroy();
} else {
viewer && viewer.destroy();
}
vcInstance.viewer = void 0;
vcInstance.mounted = false;
if (removeCesiumScript && globalThis.Cesium) {
const scripts = document.getElementsByTagName("script");
const removeScripts = [];
for (const script of scripts) {
script.src.indexOf("/Cesium.js") > -1 && removeScripts.push(script);
script.src.indexOf("/Workers/zlib.min.js") > -1 && removeScripts.push(script);
if (globalThis.XE) {
script.src.indexOf("/rxjs.umd.min.js") > -1 && removeScripts.push(script);
script.src.indexOf("/XbsjCesium.js") > -1 && removeScripts.push(script);
script.src.indexOf("/viewerCesiumNavigationMixin.js") > -1 && removeScripts.push(script);
script.src.indexOf("/XbsjEarth.js") > -1 && removeScripts.push(script);
}
loadLibs.includes(script.src) && !removeScripts.includes(script) && removeScripts.push(script);
}
const links = document.getElementsByTagName("link");
for (const link of links) {
link.href.includes("Widgets/widgets.css") && !removeScripts.includes(link) && removeScripts.push(link);
loadLibs.includes(link.href) && !removeScripts.includes(link) && removeScripts.push(link);
}
removeScripts.forEach((script) => {
script.parentNode && script.parentNode.removeChild(script);
});
globalThis.Cesium && (globalThis.Cesium = void 0);
globalThis.XbsjCesium && (globalThis.XbsjCesium = void 0);
globalThis.XbsjEarth && (globalThis.XbsjEarth = void 0);
globalThis.XE && (globalThis.XE = void 0);
globalThis.mars3d && (globalThis.mars3d = void 0);
globalThis.DC && (globalThis.DC = void 0);
globalThis.DcCore && (globalThis.DcCore = void 0);
globalConfig.value.__scriptPromise = void 0;
loadLibs = [];
}
vcInstance.isUnmounted = false;
const listener = getInstanceListener(vcInstance, "destroyed");
listener && emit("destroyed", vcInstance);
vcMitt.emit("destroyed", vcInstance);
logger.debug("viewer---unloaded");
unloadingResolve(true);
globalConfig.value.__viewerUnloadingPromise = void 0;
isReady.value = false;
return true;
};
const reload = function() {
return unload().then(() => {
return load();
});
};
const getCesiumScript = async function() {
logger.debug("getCesiumScript");
if (!globalThis.Cesium) {
const cesiumPath = props.cesiumPath ? props.cesiumPath : globalConfig.value.cesiumPath;
const dirName = dirname(cesiumPath);
const mars3dConfig = globalConfig.value.mars3dConfig || props.mars3dConfig;
if (mars3dConfig) {
const libsConfig = mars3dConfig.libs || getMars3dConfig();
const include = mars3dConfig.include || "mars3d";
const arrInclude = include.trim().split(",");
const keys = {};
for (let i = 0, len = arrInclude.length; i < len; i++) {
const key = arrInclude[i];
if (keys[key]) {
continue;
}
keys[key] = true;
loadLibs.push(...libsConfig[key]);
}
} else if (cesiumPath.includes("/dc.base.min.js")) {
loadLibs.push(cesiumPath);
loadLibs.push(cesiumPath.replace("/dc.base.min.js", "/dc.core.min.js"));
loadLibs.push(cesiumPath.replace("/dc.base.min.js", "/dc.core.min.js").replace("/dc.core.min.js", "/dc.core.min.css"));
} else if (cesiumPath.includes("/XbsjEarth.js")) {
loadLibs.push(cesiumPath);
} else {
loadLibs.push(cesiumPath);
loadLibs.push(`${dirName}/Widgets/widgets.css`);
}
const secondaryLibs = loadLibs;
if (mars3dConfig) {
const primaryLib = loadLibs.find((v) => v.includes("Cesium.js"));
await loadScript(primaryLib);
secondaryLibs.splice(secondaryLibs.indexOf(primaryLib), 1);
}
const scriptLoadPromises = [];
secondaryLibs.forEach((url) => {
const cssExpr = new RegExp("\\.css");
if (cssExpr.test(url)) {
scriptLoadPromises.push(loadLink(url));
} else {
scriptLoadPromises.push(loadScript(url));
}
});
return Promise.all(scriptLoadPromises).then(() => {
if (globalThis.Cesium) {
const listener = getInstanceListener(vcInstance, "cesiumReady");
listener && emit("cesiumReady", globalThis.Cesium);
return globalThis.Cesium;
} else if (globalThis.XE) {
return globalThis.XE.ready().then(() => {
const listener = getInstanceListener(vcInstance, "cesiumReady");
listener && emit("cesiumReady", globalThis.Cesium);
return globalThis.Cesium;
});
} else if (globalThis.DC) {
globalThis.DC.use(globalThis.DcCore.default || globalThis.DcCore);
globalThis.DC.baseUrl = `${dirName}/resources/`;
globalThis.DC.ready(() => {
globalThis.Cesium = DC.Namespace.Cesium;
const listener = getInstanceListener(vcInstance, "cesiumReady");
listener && emit("cesiumReady", globalThis.DC);
return globalThis.Cesium;
});
return globalThis.Cesium;
} else {
reject(new Error("VueCesium ERROR: Error loading CesiumJS!"));
}
});
} else {
return Promise.resolve(globalThis.Cesium);
}
};
const loadScript = (src) => {
const $script = document.createElement("script");
$script.async = false;
$script.src = src;
document.body.appendChild($script);
return new Promise((resolve, reject2) => {
$script.onload = () => {
resolve(true);
};
});
};
const loadLink = (src) => {
const $link = document.createElement("link");
$link.rel = "stylesheet";
$link.href = src;
document.head.appendChild($link);
return new Promise((resolve, reject2) => {
$link.onload = () => {
resolve(true);
};
});
};
const onViewerWidgetResized = (e) => {
var _a, _b;
const { viewer } = vcInstance;
const toolbarElement = viewer._toolbar;
if (toolbarElement !== void 0 && getComputedStyle(toolbarElement).visibility !== "hidden" && getComputedStyle(toolbarElement).display !== "none") {
layout.toolbarContainerRC = toolbarElement.getBoundingClientRect();
} else {
layout.toolbarContainerRC = void 0;
}
const bottomContainer = viewer.bottomContainer;
if (bottomContainer !== void 0 && getComputedStyle(bottomContainer).visibility !== "hidden" && getComputedStyle(bottomContainer).display !== "none") {
layout.bottomContainerRC = bottomContainer.getBoundingClientRect();
} else {
layout.bottomContainerRC = void 0;
}
const timelineContainer = (_a = viewer.timeline) == null ? void 0 : _a.container;
if (timelineContainer !== void 0 && getComputedStyle(timelineContainer).visibility !== "hidden" && getComputedStyle(timelineContainer).display !== "none") {
layout.timelineContainerRC = timelineContainer.getBoundingClientRect();
} else {
layout.timelineContainerRC = void 0;
}
const animationContainer = (_b = viewer.animation) == null ? void 0 : _b.container;
if (animationContainer !== void 0 && getComputedStyle(animationContainer).visibility !== "hidden" && getComputedStyle(animationContainer).display !== "none") {
layout.animationContainerRC = animationContainer.getBoundingClientRect();
} else {
layout.animationContainerRC = void 0;
}
viewer.resize();
const listener = getInstanceListener(vcInstance, "viewerWidgetResized");
listener && emit("viewerWidgetResized", e);
};
const onImageryLayerAdded = (layer) => {
const viewer = vcInstance.viewer;
const { autoSortImageryLayers } = props;
if (viewer.baseLayerPicker) {
viewer.imageryLayers.raiseToTop(layer);
}
const { defined } = Cesium;
if (autoSortImageryLayers) {
layer.sortOrder = defined(layer.sortOrder) ? layer.sortOrder : 9999;
viewer.imageryLayers._layers.sort((a, b) => a.sortOrder - b.sortOrder);
viewer.imageryLayers._update();
}
};
const localeDateTimeFormatter = function(date, viewModel, ignoredate) {
const { JulianDate } = Cesium;
let TZCode;
if (props.UTCOffset) {
date = JulianDate.addMinutes(date, props.UTCOffset, new JulianDate());
const offset = (/* @__PURE__ */ new Date()).getTimezoneOffset() - props.UTCOffset;
TZCode = offset === 0 ? "UTC" : "UTC+" + -(offset / 60);
} else {
TZCode = (/* @__PURE__ */ new Date()).getTimezoneOffset() === 0 ? "UTC" : "UTC+" + -((/* @__PURE__ */ new Date()).getTimezoneOffset() / 60);
}
const jsDate = JulianDate.toDate(date);
const timeString = jsDate.toLocaleString(t("name"), {
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: false
}).replace(/,/g, "");
const dateString = jsDate.toLocaleString(t("name"), {
year: "numeric",
month: "short",
day: "numeric"
}).replace(/,/g, "");
if (!ignoredate && (viewModel || jsDate.getHours() + jsDate.getMinutes() === 0)) {
return dateString;
}
props.TZCode && (TZCode = props.TZCode);
return ignoredate ? `${timeString} ${TZCode}` : `${dateString} ${timeString} ${TZCode}`;
};
const localeTimeFormatter = function(time, viewModel) {
return localeDateTimeFormatter(time, viewModel, true);
};
const onTimelineScrubfunction = function(e) {
const clock = e.clock;
clock.currentTime = e.timeJulian;
clock.shouldAnimate = false;
};
const enableVRUI = function(viewer, enabled) {
const geocoder = viewer._geocoder;
const homeButton = viewer._homeButton;
const sceneModePicker = viewer._sceneModePicker;
const projectionPicker = viewer._projectionPicker;
const baseLayerPicker = viewer._baseLayerPicker;
const animation = viewer._animation;
const timeline = viewer._timeline;
const fullscreenButton = viewer._fullscreenButton;
const infoBox = viewer._infoBox;
const selectionIndicator = viewer._selectionIndicator;
const visibility = enabled ? "hidden" : "visible";
const { defined } = Cesium;
if (defined(geocoder)) {
geocoder.container.style.visibility = visibility;
}
if (defined(homeButton)) {
homeButton.container.style.visibility = visibility;
}
if (defined(sceneModePicker)) {
sceneModePicker.container.style.visibility = visibility;
}
if (defined(projectionPicker)) {
projectionPicker.container.style.visibility = visibility;
}
if (defined(baseLayerPicker)) {
baseLayerPicker.container.style.visibility = visibility;
}
if (defined(animation)) {
animation.container.style.visibility = visibility;
}
if (defined(timeline)) {
timeline.container.style.visibility = visibility;
}
if (defined(fullscreenButton) && fullscreenButton.viewModel.isFullscreenEnabled) {
fullscreenButton.container.style.visibility = visibility;
}
if (defined(infoBox)) {
infoBox.container.style.visibility = visibility;
}
if (defined(selectionIndicator)) {
selectionIndicator.container.style.visibility = visibility;
}
if (viewer._container) {
const right = enabled || !defined(fullscreenButton) ? 0 : fullscreenButton.container.clientWidth;
viewer._vrButton.container.style.right = right + "px";
viewer.forceResize();
}
};
const resizeToolbar = function(parent, child) {
Array.prototype.slice.call(parent.children).forEach((element) => {
switch (element.className) {
case "cesium-viewer-geocoderContainer":
element.customIndex = 1;
break;
case "cesium-button cesium-toolbar-button cesium-home-button":
element.customIndex = 2;
break;
case "cesium-sceneModePicker-wrapper cesium-toolbar-button":
element.customIndex = 3;
break;
case "cesium-projectionPicker-wrapper cesium-toolbar-button":
element.customIndex = 4;
break;
case "cesium-button cesium-toolbar-button":
case "cesium-baseLayerPicker-dropDown":
element.customIndex = 5;
break;
case "cesium-navigationHelpButton-wrapper":
element.customIndex = 6;
break;
}
});
const arr = [];
Array.prototype.slice.call(parent.children).forEach((element) => {
arr.push(element);
});
arr.sort(function(a, b) {
return a.customIndex - b.customIndex;
});
for (let i = 0; i < arr.length; i++) {
parent.appendChild(arr[i]);
}
};
const getServices = function() {
return mergeDescriptors(
{},
{
get layout() {
return layout;
},
get vm() {
return vcInstance;
},
get Cesium() {
return vcInstance.Cesium;
},
get viewer() {
return vcInstance.viewer;
},
get dataSources() {
var _a;
return (_a = vcInstance.viewer) == null ? void 0 : _a.dataSources;
},
get entities() {
var _a;
return (_a = vcInstance.viewer) == null ? void 0 : _a.entities;
},
get imageryLayers() {
var _a;
return (_a = vcInstance.viewer) == null ? void 0 : _a.imageryLayers;
},
get primitives() {
var _a;
return (_a = vcInstance.viewer) == null ? void 0 : _a.scene.primitives;
},
get groundPrimitives() {
var _a;
return (_a = vcInstance.viewer) == null ? void 0 : _a.scene.groundPrimitives;
},
get postProcessStages() {
var _a;
return (_a = vcInstance.viewer) == null ? void 0 : _a.postProcessStages;
},
get creatingPromise() {
return creatingPromise;
},
/**
* for mars3d only
*/
get mars3dMap() {
return vcInstance.map;
},
/**
* for dc-sdk only
*/
get dcViewer() {
return vcInstance.dcViewer;
},
/**
* for earth-sdk only
*/
get earth() {
return vcInstance.earth;
}
}
);
};
Object.defineProperties(vcInstance, {
cesiumObject: {
enumerable: true,
get: () => vcInstance.viewer
}
});
onMounted(async () => {
var _a;
try {
logger.debug("viewer - onMounted");
await ((_a = globalConfig.value) == null ? void 0 : _a.__viewerUnloadingPromise);
load().then((e) => {
createResolve(e);
}).catch((e) => {
emit("unready", e);
reject(e);
});
} catch (e) {
emit("unready", e);
reject(e);
}
});
onUnmounted(() => {
logger.debug("viewer - onUnmounted");
unload().then(() => {
vcMitt.all.clear();
});
});
return {
isReady,
load,
unload,
reload,
getServices,
viewerRef,
creatingPromise
};
}
const viewerEvents = [
{
// viewer.imageryLayers
name: "imageryLayers",
events: ["layerAdded", "layerMoved", "layerRemoved", "layerShownOrHidden"]
},
{
// viewer.dataSources
name: "dataSources",
events: ["dataSourceAdded", "dataSourceMoved", "dataSourceRemoved"]
},
{
// viewer.entities
name: "entities",
events: ["collectionChanged"]
},
{
// viewer.scene
name: "scene",
events: ["morphComplete", "morphStart", "postRender", "postUpdate", "preRender", "preUpdate", "renderError", "terrainProviderChanged"]
},
{
// viewer.camera
name: "camera",
events: ["changed", "moveEnd", "moveStart"]
},
{
// viewer.clock
name: "clock",
events: ["onStop", "onTick"]
},
{
// viewer.terrainProvider
name: "terrainProvider",
events: ["errorEvent"]
},
{
// viewer.infoBox.viewModel
name: ["infoBox", "viewModel"],
events: ["cameraClicked", "closeClicked"]
},
// viewer.scene.globe
{
name: ["scene", "globe"],
events: ["imageryLayersUpdatedEvent", "terrainProviderChanged", "tileLoadProgressEvent"]
}
];
const viewerScreenSpaceEventsCamel = viewerScreenSpaceEvents.map((v) => camelCase(v));
const cmpEvents = [
"beforeLoad",
"cesiumReady",
"ready",
"destroyed",
"update:camera",
"viewerWidgetResized",
...viewerScreenSpaceEvents,
...viewerScreenSpaceEventsCamel,
...pickEvents
];
viewerEvents.reduce((pre, cur) => {
return pre.concat(cur.events);
}, cmpEvents);
const useSizeDefaults = {
xs: 18,
sm: 24,
md: 32,
lg: 38,
xl: 46
};
const useSizeProps = {
size: String
};
function useSize(props, sizes = useSizeDefaults) {
return computed(() => props.size !== void 0 ? { fontSize: props.size in sizes ? `${sizes[props.size]}px` : props.size } : null);
}
function hSlot(slot, otherwise) {
return slot !== void 0 ? slot() : otherwise;
}
function hMergeSlot(slot, source) {
return slot !== void 0 ? source.concat(slot()) : source;
}
function hDir(tag, data, children, key, condition, getDirsFn) {
data.key = key + condition;
const vnode = h(tag, data, children);
return condition === true ? withDirectives(vnode, getDirsFn()) : vnode;
}
const iconProps = exports('iconProps', {
...useSizeProps,
tag: {
type: String,
default: "i"
},
name: String,
color: String,
hoverColor: String,
left: Boolean,
right: Boolean
});
var Icon = defineComponent({
name: "VcIcon",
props: iconProps,
setup(props, { slots }) {
const sizeStyle = useSize(props);
const style = computed(() => {
const css = sizeStyle.value;
if (!css) {
return void 0;
}
props.color && (css.color = props.color);
props.hoverColor && (css["--hover-color"] = props.hoverColor);
return css;
});
const classes = computed(
() => "vc-icon" + (props.left === true ? " on-left" : "") + (props.right === true ? " on-right" : "") + (props.color !== void 0 ? ` text-${props.color}` : "")
);
const type = computed(() => {
let cls;
let icon = props.name;
if (!icon) {
return {
none: true,
cls: classes.value
};
}
if (icon.startsWith("M") === true) {
const [def, viewBox] = icon.split("|");
return {
svg: true,
cls: classes.value,
nodes: def.split("&&").map((path) => {
const [d, style2, transform] = path.split("@@");
return h("path", {
style: style2,
d,
transform
});
}),
viewBox: viewBox !== void 0 ? viewBox : "0 0 24 24"
};
}
if (icon.startsWith("img:") === true) {
return {
img: true,
cls: classes.value,
src: icon.substring(4)
};
}
if (icon.startsWith("svguse:") === true) {
const [def, viewBox] = icon.split("|");
return {
svguse: true,
cls: classes.value,
src: def.substring(7),
viewBox: viewBox !== void 0 ? viewBox : "0 0 24 24"
};
}
let content = " ";
if (/^[l|f]a[s|r|l|b|d]{0,1} /.test(icon) || icon.startsWith("icon-") === true) {
cls = icon;
} else if (icon.startsWith("bt-") === true) {
cls = `bt ${icon}`;
} else if (icon.startsWith("eva-") === true) {
cls = `eva ${icon}`;
} else if (/^ion-(md|ios|logo)/.test(icon) === true) {
cls = `ionicons ${icon}`;
} else if (icon.startsWith("ion-") === true) {
cls = `ionicons ion-md${icon.substr(3)}`;
} else if (icon.startsWith("mdi-") === true) {
cls = `mdi ${icon}`;
} else if (icon.startsWith("iconfont ") === true) {
cls = `${icon}`;
} else if (icon.startsWith("ti-") === true) {
cls = `themify-icon ${icon}`;
} else if (icon.startsWith("vc-") === true) {
cls = `vc-icons ${icon}`;
} else {
cls = "notranslate material-icons";
if (icon.startsWith("o_") === true) {
icon = icon.substring(2);
cls += "-outlined";
} else if (icon.startsWith("r_") === true) {
icon = icon.substring(2);
cls += "-round";
} else if (icon.startsWith("s_") === true) {
icon = icon.substring(2);
cls += "-sharp";
}
content = icon;
}
return {
cls: cls + " " + classes.value,
content
};
});
return () => {
const data = {
class: type.value.cls,
style: style.value,
"aria-hidden": "true",
role: "presentation",
viewBox: "",
src: ""
};
if (type.value.none === true) {
return h(props.tag, data, hSlot(slots.default));
}
if (type.value.img === true) {
data.src = type.value.src;
if (data.style) {
data.style.width = data.style.fontSize;
data.style.height = data.style.fontSize;
}
return h("img", data);
}
if (type.value.svg === true) {
data.viewBox = type.value.viewBox;
data["aria-hidden"] = "true";
if (data.style) {
data.style.width = data.style.fontSize;
data.style.height = data.style.fontSize;
}
return h("svg", data, hMergeSlot(slots.default, type.value.nodes));
}
if (type.value.svguse === true) {
data.viewBox = type.value.viewBox;
data["aria-hidden"] = "true";
if (data.style) {
data.style.width = data.style.fontSize;
data.style.height = data.style.fontSize;
}
return h("svg", data, hMergeSlot(slots.default, [h("use", { "xlink:href": type.value.src })]));
}
return h(props.tag, data, hMergeSlot(slots.default, [type.value.content]));
};
}
});
const useSpinnerProps = {
size: {
type: [Number, String],
default: "1em"
},
color: String
};
function useSpinner(props) {
return {
cSize: computed(() => props.size in useSizeDefaults ? `${useSizeDefaults[props.size]}px` : props.size),
classes: computed(() => "vc-spinner" + (props.color ? ` text-${props.color}` : ""))
};
}
const svg$a = [
h(
"g",
{
transform: "translate(1 1)",
"stroke-width": "2",
fill: "none",
"fill-rule": "evenodd"
},
[
h(
"circle",
{
cx: "5",
cy: "50",
r: "5"
},
[
h("animate", {
attributeName: "cy",
begin: "0s",
dur: "2.2s",
values: "50;5;50;50",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "cx",
begin: "0s",
dur: "2.2s",
values: "5;27;49;5",
calcMode: "linear",
repeatCount: "indefinite"
})
]
),
h(
"circle",
{
cx: "27",
cy: "5",
r: "5"
},
[
h("animate", {
attributeName: "cy",
begin: "0s",
dur: "2.2s",
from: "5",
to: "5",
values: "5;50;50;5",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "cx",
begin: "0s",
dur: "2.2s",
from: "27",
to: "27",
values: "27;49;5;27",
calcMode: "linear",
repeatCount: "indefinite"
})
]
),
h(
"circle",
{
cx: "49",
cy: "50",
r: "5"
},
[
h("animate", {
attributeName: "cy",
begin: "0s",
dur: "2.2s",
values: "50;50;5;50",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "cx",
from: "49",
to: "49",
begin: "0s",
dur: "2.2s",
values: "49;5;27;49",
calcMode: "linear",
repeatCount: "indefinite"
})
]
)
]
)
];
var SpinnerBall = exports('SpinnerBall', defineComponent({
name: "VcSpinnerBall",
props: useSpinnerProps,
setup(props) {
const { cSize, classes } = useSpinner(props);
return () => h(
"svg",
{
class: classes.value,
stroke: "currentColor",
width: cSize.value,
height: cSize.value,
viewBox: "0 0 57 57",
xmlns: "http://www.w3.org/2000/svg"
},
svg$a
);
}
}));
const svg$9 = [
h(
"rect",
{
y: "10",
width: "15",
height: "120",
rx: "6"
},
[
h("animate", {
attributeName: "height",
begin: "0.5s",
dur: "1s",
values: "120;110;100;90;80;70;60;50;40;140;120",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "y",
begin: "0.5s",
dur: "1s",
values: "10;15;20;25;30;35;40;45;50;0;10",
calcMode: "linear",
repeatCount: "indefinite"
})
]
),
h(
"rect",
{
x: "30",
y: "10",
width: "15",
height: "120",
rx: "6"
},
[
h("animate", {
attributeName: "height",
begin: "0.25s",
dur: "1s",
values: "120;110;100;90;80;70;60;50;40;140;120",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "y",
begin: "0.25s",
dur: "1s",
values: "10;15;20;25;30;35;40;45;50;0;10",
calcMode: "linear",
repeatCount: "indefinite"
})
]
),
h(
"rect",
{
x: "60",
width: "15",
height: "140",
rx: "6"
},
[
h("animate", {
attributeName: "height",
begin: "0s",
dur: "1s",
values: "120;110;100;90;80;70;60;50;40;140;120",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "y",
begin: "0s",
dur: "1s",
values: "10;15;20;25;30;35;40;45;50;0;10",
calcMode: "linear",
repeatCount: "indefinite"
})
]
),
h(
"rect",
{
x: "90",
y: "10",
width: "15",
height: "120",
rx: "6"
},
[
h("animate", {
attributeName: "height",
begin: "0.25s",
dur: "1s",
values: "120;110;100;90;80;70;60;50;40;140;120",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "y",
begin: "0.25s",
dur: "1s",
values: "10;15;20;25;30;35;40;45;50;0;10",
calcMode: "linear",
repeatCount: "indefinite"
})
]
),
h(
"rect",
{
x: "120",
y: "10",
width: "15",
height: "120",
rx: "6"
},
[
h("animate", {
attributeName: "height",
begin: "0.5s",
dur: "1s",
values: "120;110;100;90;80;70;60;50;40;140;120",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "y",
begin: "0.5s",
dur: "1s",
values: "10;15;20;25;30;35;40;45;50;0;10",
calcMode: "linear",
repeatCount: "indefinite"
})
]
)
];
var SpinnerBars = exports('SpinnerBars', defineComponent({
name: "VcSpinnerBars",
props: useSpinnerProps,
setup(props) {
const { cSize, classes } = useSpinner(props);
return () => h(
"svg",
{
class: classes.value,
fill: "currentColor",
width: cSize.value,
height: cSize.value,
viewBox: "0 0 135 140",
xmlns: "http://www.w3.org/2000/svg"
},
svg$9
);
}
}));
const svg$8 = [
h(
"circle",
{
cx: "15",
cy: "15",
r: "15"
},
[
h("animate", {
attributeName: "r",
from: "15",
to: "15",
begin: "0s",
dur: "0.8s",
values: "15;9;15",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "fill-opacity",
from: "1",
to: "1",
begin: "0s",
dur: "0.8s",
values: "1;.5;1",
calcMode: "linear",
repeatCount: "indefinite"
})
]
),
h(
"circle",
{
cx: "60",
cy: "15",
r: "9",
"fill-opacity": ".3"
},
[
h("animate", {
attributeName: "r",
from: "9",
to: "9",
begin: "0s",
dur: "0.8s",
values: "9;15;9",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "fill-opacity",
from: ".5",
to: ".5",
begin: "0s",
dur: "0.8s",
values: ".5;1;.5",
calcMode: "linear",
repeatCount: "indefinite"
})
]
),
h(
"circle",
{
cx: "105",
cy: "15",
r: "15"
},
[
h("animate", {
attributeName: "r",
from: "15",
to: "15",
begin: "0s",
dur: "0.8s",
values: "15;9;15",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "fill-opacity",
from: "1",
to: "1",
begin: "0s",
dur: "0.8s",
values: "1;.5;1",
calcMode: "linear",
repeatCount: "indefinite"
})
]
)
];
var SpinnerDots = exports('SpinnerDots', defineComponent({
name: "VcSpinnerDots",
props: useSpinnerProps,
setup(props) {
const { cSize, classes } = useSpinner(props);
return () => h(
"svg",
{
class: classes.value,
fill: "currentColor",
width: cSize.value,
height: cSize.value,
viewBox: "0 0 120 30",
xmlns: "http://www.w3.org/2000/svg"
},
svg$8
);
}
}));
const svg$7 = [
h(
"g",
{
transform: "translate(-20,-20)"
},
[
h(
"path",
{
d: "M79.9,52.6C80,51.8,80,50.9,80,50s0-1.8-0.1-2.6l-5.1-0.4c-0.3-2.4-0.9-4.6-1.8-6.7l4.2-2.9c-0.7-1.6-1.6-3.1-2.6-4.5 L70,35c-1.4-1.9-3.1-3.5-4.9-4.9l2.2-4.6c-1.4-1-2.9-1.9-4.5-2.6L59.8,27c-2.1-0.9-4.4-1.5-6.7-1.8l-0.4-5.1C51.8,20,50.9,20,50,20 s-1.8,0-2.6,0.1l-0.4,5.1c-2.4,0.3-4.6,0.9-6.7,1.8l-2.9-4.1c-1.6,0.7-3.1,1.6-4.5,2.6l2.1,4.6c-1.9,1.4-3.5,3.1-5,4.9l-4.5-2.1 c-1,1.4-1.9,2.9-2.6,4.5l4.1,2.9c-0.9,2.1-1.5,4.4-1.8,6.8l-5,0.4C20,48.2,20,49.1,20,50s0,1.8,0.1,2.6l5,0.4 c0.3,2.4,0.9,4.7,1.8,6.8l-4.1,2.9c0.7,1.6,1.6,3.1,2.6,4.5l4.5-2.1c1.4,1.9,3.1,3.5,5,4.9l-2.1,4.6c1.4,1,2.9,1.9,4.5,2.6l2.9-4.1 c2.1,0.9,4.4,1.5,6.7,1.8l0.4,5.1C48.2,80,49.1,80,50,80s1.8,0,2.6-0.1l0.4-5.1c2.3-0.3,4.6-0.9,6.7-1.8l2.9,4.2 c1.6-0.7,3.1-1.6,4.5-2.6L65,69.9c1.9-1.4,3.5-3,4.9-4.9l4.6,2.2c1-1.4,1.9-2.9,2.6-4.5L73,59.8c0.9-2.1,1.5-4.4,1.8-6.7L79.9,52.6 z M50,65c-8.3,0-15-6.7-15-15c0-8.3,6.7-15,15-15s15,6.7,15,15C65,58.3,58.3,65,50,65z",
fill: "currentColor"
},
[
h("animateTransform", {
attributeName: "transform",
type: "rotate",
from: "90 50 50",
to: "0 50 50",
dur: "1s",
repeatCount: "indefinite"
})
]
)
]
),
h(
"g",
{
transform: "translate(20,20) rotate(15 50 50)"
},
[
h(
"path",
{
d: "M79.9,52.6C80,51.8,80,50.9,80,50s0-1.8-0.1-2.6l-5.1-0.4c-0.3-2.4-0.9-4.6-1.8-6.7l4.2-2.9c-0.7-1.6-1.6-3.1-2.6-4.5 L70,35c-1.4-1.9-3.1-3.5-4.9-4.9l2.2-4.6c-1.4-1-2.9-1.9-4.5-2.6L59.8,27c-2.1-0.9-4.4-1.5-6.7-1.8l-0.4-5.1C51.8,20,50.9,20,50,20 s-1.8,0-2.6,0.1l-0.4,5.1c-2.4,0.3-4.6,0.9-6.7,1.8l-2.9-4.1c-1.6,0.7-3.1,1.6-4.5,2.6l2.1,4.6c-1.9,1.4-3.5,3.1-5,4.9l-4.5-2.1 c-1,1.4-1.9,2.9-2.6,4.5l4.1,2.9c-0.9,2.1-1.5,4.4-1.8,6.8l-5,0.4C20,48.2,20,49.1,20,50s0,1.8,0.1,2.6l5,0.4 c0.3,2.4,0.9,4.7,1.8,6.8l-4.1,2.9c0.7,1.6,1.6,3.1,2.6,4.5l4.5-2.1c1.4,1.9,3.1,3.5,5,4.9l-2.1,4.6c1.4,1,2.9,1.9,4.5,2.6l2.9-4.1 c2.1,0.9,4.4,1.5,6.7,1.8l0.4,5.1C48.2,80,49.1,80,50,80s1.8,0,2.6-0.1l0.4-5.1c2.3-0.3,4.6-0.9,6.7-1.8l2.9,4.2 c1.6-0.7,3.1-1.6,4.5-2.6L65,69.9c1.9-1.4,3.5-3,4.9-4.9l4.6,2.2c1-1.4,1.9-2.9,2.6-4.5L73,59.8c0.9-2.1,1.5-4.4,1.8-6.7L79.9,52.6 z M50,65c-8.3,0-15-6.7-15-15c0-8.3,6.7-15,15-15s15,6.7,15,15C65,58.3,58.3,65,50,65z",
fill: "currentColor"
},
[
h("animateTransform", {
attributeName: "transform",
type: "rotate",
from: "0 50 50",
to: "90 50 50",
dur: "1s",
repeatCount: "indefinite"
})
]
)
]
)
];
var SpinnerGears = exports('SpinnerGears', defineComponent({
name: "VcSpinnerGears",
props: useSpinnerProps,
setup(props) {
const { cSize, classes } = useSpinner(props);
return () => h(
"svg",
{
class: classes.value,
width: cSize.value,
height: cSize.value,
viewBox: "0 0 100 100",
preserveAspectRatio: "xMidYMid",
xmlns: "http://www.w3.org/2000/svg"
},
svg$7
);
}
}));
const svg$6 = [
h("g", [
h("path", {
fill: "none",
stroke: "currentColor",
"stroke-width": "5",
"stroke-miterlimit": "10",
d: "M58.4,51.7c-0.9-0.9-1.4-2-1.4-2.3s0.5-0.4,1.4-1.4 C70.8,43.8,79.8,30.5,80,15.5H70H30H20c0.2,15,9.2,28.1,21.6,32.3c0.9,0.9,1.4,1.2,1.4,1.5s-0.5,1.6-1.4,2.5 C29.2,56.1,20.2,69.5,20,85.5h10h40h10C79.8,69.5,70.8,55.9,58.4,51.7z"
}),
h(
"clipPath",
{
id: "uil-hourglass-clip1"
},
[
h(
"rect",
{
x: "15",
y: "20",
width: " 70",
height: "25"
},
[
h("animate", {
attributeName: "height",
from: "25",
to: "0",
dur: "1s",
repeatCount: "indefinite",
values: "25;0;0",
keyTimes: "0;0.5;1"
}),
h("animate", {
attributeName: "y",
from: "20",
to: "45",
dur: "1s",
repeatCount: "indefinite",
values: "20;45;45",
keyTimes: "0;0.5;1"
})
]
)
]
),
h(
"clipPath",
{
id: "uil-hourglass-clip2"
},
[
h(
"rect",
{
x: "15",
y: "55",
width: " 70",
height: "25"
},
[
h("animate", {
attributeName: "height",
from: "0",
to: "25",
dur: "1s",
repeatCount: "indefinite",
values: "0;25;25",
keyTimes: "0;0.5;1"
}),
h("animate", {
attributeName: "y",
from: "80",
to: "55",
dur: "1s",
repeatCount: "indefinite",
values: "80;55;55",
keyTimes: "0;0.5;1"
})
]
)
]
),
h("path", {
d: "M29,23c3.1,11.4,11.3,19.5,21,19.5S67.9,34.4,71,23H29z",
"clip-path": "url(#uil-hourglass-clip1)",
fill: "currentColor"
}),
h("path", {
d: "M71.6,78c-3-11.6-11.5-20-21.5-20s-18.5,8.4-21.5,20H71.6z",
"clip-path": "url(#uil-hourglass-clip2)",
fill: "currentColor"
}),
h("animateTransform", {
attributeName: "transform",
type: "rotate",
from: "0 50 50",
to: "180 50 50",
repeatCount: "indefinite",
dur: "1s",
values: "0 50 50;0 50 50;180 50 50",
keyTimes: "0;0.7;1"
})
])
];
var SpinnerHourglass = exports('SpinnerHourglass', defineComponent({
name: "VcSpinnerHourglass",
props: useSpinnerProps,
setup(props) {
const { cSize, classes } = useSpinner(props);
return () => h(
"svg",
{
class: classes.value,
width: cSize.value,
height: cSize.value,
viewBox: "0 0 100 100",
preserveAspectRatio: "xMidYMid",
xmlns: "http://www.w3.org/2000/svg"
},
svg$6
);
}
}));
const svg$5 = [
h(
"g",
{
"stroke-width": "4",
"stroke-linecap": "round"
},
[
h(
"line",
{
y1: "17",
y2: "29",
transform: "translate(32,32) rotate(180)"
},
[
h("animate", {
attributeName: "stroke-opacity",
dur: "750ms",
values: "1;.85;.7;.65;.55;.45;.35;.25;.15;.1;0;1",
repeatCount: "indefinite"
})
]
),
h(
"line",
{
y1: "17",
y2: "29",
transform: "translate(32,32) rotate(210)"
},
[
h("animate", {
attributeName: "stroke-opacity",
dur: "750ms",
values: "0;1;.85;.7;.65;.55;.45;.35;.25;.15;.1;0",
repeatCount: "indefinite"
})
]
),
h(
"line",
{
y1: "17",
y2: "29",
transform: "translate(32,32) rotate(240)"
},
[
h("animate", {
attributeName: "stroke-opacity",
dur: "750ms",
values: ".1;0;1;.85;.7;.65;.55;.45;.35;.25;.15;.1",
repeatCount: "indefinite"
})
]
),
h(
"line",
{
y1: "17",
y2: "29",
transform: "translate(32,32) rotate(270)"
},
[
h("animate", {
attributeName: "stroke-opacity",
dur: "750ms",
values: ".15;.1;0;1;.85;.7;.65;.55;.45;.35;.25;.15",
repeatCount: "indefinite"
})
]
),
h(
"line",
{
y1: "17",
y2: "29",
transform: "translate(32,32) rotate(300)"
},
[
h("animate", {
attributeName: "stroke-opacity",
dur: "750ms",
values: ".25;.15;.1;0;1;.85;.7;.65;.55;.45;.35;.25",
repeatCount: "indefinite"
})
]
),
h(
"line",
{
y1: "17",
y2: "29",
transform: "translate(32,32) rotate(330)"
},
[
h("animate", {
attributeName: "stroke-opacity",
dur: "750ms",
values: ".35;.25;.15;.1;0;1;.85;.7;.65;.55;.45;.35",
repeatCount: "indefinite"
})
]
),
h(
"line",
{
y1: "17",
y2: "29",
transform: "translate(32,32) rotate(0)"
},
[
h("animate", {
attributeName: "stroke-opacity",
dur: "750ms",
values: ".45;.35;.25;.15;.1;0;1;.85;.7;.65;.55;.45",
repeatCount: "indefinite"
})
]
),
h(
"line",
{
y1: "17",
y2: "29",
transform: "translate(32,32) rotate(30)"
},
[
h("animate", {
attributeName: "stroke-opacity",
dur: "750ms",
values: ".55;.45;.35;.25;.15;.1;0;1;.85;.7;.65;.55",
repeatCount: "indefinite"
})
]
),
h(
"line",
{
y1: "17",
y2: "29",
transform: "translate(32,32) rotate(60)"
},
[
h("animate", {
attributeName: "stroke-opacity",
dur: "750ms",
values: ".65;.55;.45;.35;.25;.15;.1;0;1;.85;.7;.65",
repeatCount: "indefinite"
})
]
),
h(
"line",
{
y1: "17",
y2: "29",
transform: "translate(32,32) rotate(90)"
},
[
h("animate", {
attributeName: "stroke-opacity",
dur: "750ms",
values: ".7;.65;.55;.45;.35;.25;.15;.1;0;1;.85;.7",
repeatCount: "indefinite"
})
]
),
h(
"line",
{
y1: "17",
y2: "29",
transform: "translate(32,32) rotate(120)"
},
[
h("animate", {
attributeName: "stroke-opacity",
dur: "750ms",
values: ".85;.7;.65;.55;.45;.35;.25;.15;.1;0;1;.85",
repeatCount: "indefinite"
})
]
),
h(
"line",
{
y1: "17",
y2: "29",
transform: "translate(32,32) rotate(150)"
},
[
h("animate", {
attributeName: "stroke-opacity",
dur: "750ms",
values: "1;.85;.7;.65;.55;.45;.35;.25;.15;.1;0;1",
repeatCount: "indefinite"
})
]
)
]
)
];
var SpinnerIos = exports('SpinnerIos', defineComponent({
name: "VcSpinnerIos",
props: useSpinnerProps,
setup(props) {
const { cSize, classes } = useSpinner(props);
return () => h(
"svg",
{
class: classes.value,
width: cSize.value,
height: cSize.value,
stroke: "currentColor",
fill: "currentColor",
viewBox: "0 0 64 64"
},
svg$5
);
}
}));
const svg$4 = [
h("circle", {
cx: "50",
cy: "50",
r: "44",
fill: "none",
"stroke-width": "4",
"stroke-opacity": ".5",
stroke: "currentColor"
}),
h(
"circle",
{
cx: "8",
cy: "54",
r: "6",
fill: "currentColor",
"stroke-width": "3",
stroke: "currentColor"
},
[
h("animateTransform", {
attributeName: "transform",
type: "rotate",
from: "0 50 48",
to: "360 50 52",
dur: "2s",
repeatCount: "indefinite"
})
]
)
];
var SpinnerOrbit = exports('SpinnerOrbit', defineComponent({
name: "VcSpinnerOrbit",
props: useSpinnerProps,
setup(props) {
const { cSize, classes } = useSpinner(props);
return () => h(
"svg",
{
class: classes.value,
width: cSize.value,
height: cSize.value,
viewBox: "0 0 100 100",
preserveAspectRatio: "xMidYMid",
xmlns: "http://www.w3.org/2000/svg"
},
svg$4
);
}
}));
const svg$3 = [
h(
"g",
{
transform: "translate(1 1)",
"stroke-width": "2",
fill: "none",
"fill-rule": "evenodd"
},
[
h("circle", {
"stroke-opacity": ".5",
cx: "18",
cy: "18",
r: "18"
}),
h(
"path",
{
d: "M36 18c0-9.94-8.06-18-18-18"
},
[
h("animateTransform", {
attributeName: "transform",
type: "rotate",
from: "0 18 18",
to: "360 18 18",
dur: "1s",
repeatCount: "indefinite"
})
]
)
]
)
];
var SpinnerOval = exports('SpinnerOval', defineComponent({
name: "VcSpinnerOval",
props: useSpinnerProps,
setup(props) {
const { cSize, classes } = useSpinner(props);
return () => h(
"svg",
{
class: classes.value,
stroke: "currentColor",
width: cSize.value,
height: cSize.value,
viewBox: "0 0 38 38",
xmlns: "http://www.w3.org/2000/svg"
},
svg$3
);
}
}));
const svg$2 = [
h(
"g",
{
fill: "none",
"fill-rule": "evenodd",
"stroke-width": "2"
},
[
h(
"circle",
{
cx: "22",
cy: "22",
r: "1"
},
[
h("animate", {
attributeName: "r",
begin: "0s",
dur: "1.8s",
values: "1; 20",
calcMode: "spline",
keyTimes: "0; 1",
keySplines: "0.165, 0.84, 0.44, 1",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "stroke-opacity",
begin: "0s",
dur: "1.8s",
values: "1; 0",
calcMode: "spline",
keyTimes: "0; 1",
keySplines: "0.3, 0.61, 0.355, 1",
repeatCount: "indefinite"
})
]
),
h(
"circle",
{
cx: "22",
cy: "22",
r: "1"
},
[
h("animate", {
attributeName: "r",
begin: "-0.9s",
dur: "1.8s",
values: "1; 20",
calcMode: "spline",
keyTimes: "0; 1",
keySplines: "0.165, 0.84, 0.44, 1",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "stroke-opacity",
begin: "-0.9s",
dur: "1.8s",
values: "1; 0",
calcMode: "spline",
keyTimes: "0; 1",
keySplines: "0.3, 0.61, 0.355, 1",
repeatCount: "indefinite"
})
]
)
]
)
];
var SpinnerPuff = exports('SpinnerPuff', defineComponent({
name: "VcSpinnerPuff",
props: useSpinnerProps,
setup(props) {
const { cSize, classes } = useSpinner(props);
return () => h(
"svg",
{
class: classes.value,
stroke: "currentColor",
width: cSize.value,
height: cSize.value,
viewBox: "0 0 44 44",
xmlns: "http://www.w3.org/2000/svg"
},
svg$2
);
}
}));
const svg$1 = [
h(
"g",
{
fill: "none",
"fill-rule": "evenodd",
transform: "translate(1 1)",
"stroke-width": "2"
},
[
h(
"circle",
{
cx: "22",
cy: "22",
r: "6"
},
[
h("animate", {
attributeName: "r",
begin: "1.5s",
dur: "3s",
values: "6;22",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "stroke-opacity",
begin: "1.5s",
dur: "3s",
values: "1;0",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "stroke-width",
begin: "1.5s",
dur: "3s",
values: "2;0",
calcMode: "linear",
repeatCount: "indefinite"
})
]
),
h(
"circle",
{
cx: "22",
cy: "22",
r: "6"
},
[
h("animate", {
attributeName: "r",
begin: "3s",
dur: "3s",
values: "6;22",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "stroke-opacity",
begin: "3s",
dur: "3s",
values: "1;0",
calcMode: "linear",
repeatCount: "indefinite"
}),
h("animate", {
attributeName: "stroke-width",
begin: "3s",
dur: "3s",
values: "2;0",
calcMode: "linear",
repeatCount: "indefinite"
})
]
),
h(
"circle",
{
cx: "22",
cy: "22",
r: "8"
},
[
h("animate", {
attributeName: "r",
begin: "0s",
dur: "1.5s",
values: "6;1;2;3;4;5;6",
calcMode: "linear",
repeatCount: "indefinite"
})
]
)
]
)
];
var SpinnerRings = exports('SpinnerRings', defineComponent({
name: "VcSpinnerRings",
props: useSpinnerProps,
setup(props) {
const { cSize, classes } = useSpinner(props);
return () => h(
"svg",
{
class: classes.value,
stroke: "currentColor",
width: cSize.value,
height: cSize.value,
viewBox: "0 0 45 45",
xmlns: "http://www.w3.org/2000/svg"
},
svg$1
);
}
}));
const svg = [
h("defs", [
h(
"linearGradient",
{
x1: "8.042%",
y1: "0%",
x2: "65.682%",
y2: "23.865%",
id: "a"
},
[
h("stop", {
"stop-color": "currentColor",
"stop-opacity": "0",
offset: "0%"
}),
h("stop", {
"stop-color": "currentColor",
"stop-opacity": ".631",
offset: "63.146%"
}),
h("stop", {
"stop-color": "currentColor",
offset: "100%"
})
]
)
]),
h(
"g",
{
transform: "translate(1 1)",
fill: "none",
"fill-rule": "evenodd"
},
[
h(
"path",
{
d: "M36 18c0-9.94-8.06-18-18-18",
stroke: "url(#a)",
"stroke-width": "2"
},
[
h("animateTransform", {
attributeName: "transform",
type: "rotate",
from: "0 18 18",
to: "360 18 18",
dur: "0.9s",
repeatCount: "indefinite"
})
]
),
h(
"circle",
{
fill: "currentColor",
cx: "36",
cy: "18",
r: "1"
},
[
h("animateTransform", {
attributeName: "transform",
type: "rotate",
from: "0 18 18",
to: "360 18 18",
dur: "0.9s",
repeatCount: "indefinite"
})
]
)
]
)
];
var SpinnerTail = exports('SpinnerTail', defineComponent({
name: "VcSpinnerTail",
props: useSpinnerProps,
setup(props) {
const { cSize, classes } = useSpinner(props);
return () => h(
"svg",
{
class: classes.value,
width: cSize.value,
height: cSize.value,
viewBox: "0 0 38 38",
xmlns: "http://www.w3.org/2000/svg"
},
svg
);
}
}));
var Spinner = exports('Spinner', defineComponent({
name: "VcSpinner",
props: {
...useSpinnerProps,
thickness: {
type: Number,
default: 5
}
},
setup(props) {
const { cSize, classes } = useSpinner(props);
return () => h(
"svg",
{
class: classes.value + " vc-spinner-mat",
width: cSize.value,
height: cSize.value,
viewBox: "25 25 50 50"
},
[
h("circle", {
class: "path",
cx: "50",
cy: "50",
r: "20",
fill: "none",
stroke: "currentColor",
"stroke-width": props.thickness,
"stroke-miterlimit": "10"
})
]
);
}
}));
const alignMap = {
left: "start",
center: "center",
right: "end",
between: "between",
around: "around",
evenly: "evenly",
stretch: "stretch"
};
const alignValues$1 = Object.keys(alignMap);
const useAlignProps = {
align: {
type: String,
validator: (v) => alignValues$1.includes(v)
}
};
function useAlign(props) {
return computed(() => {
const align = props.align === void 0 ? props.vertical === true ? "stretch" : "left" : props.align;
return `${props.vertical === true ? "items" : "justify"}-${alignMap[align]}`;
});
}
const padding = {
none: 0,
xs: 4,
sm: 8,
md: 16,
lg: 24,
xl: 32
};
const defaultSizes = {
xs: 8,
sm: 10,
md: 14,
lg: 20,
xl: 24
};
const useBtnProps = {
...useSizeProps,
type: {
type: String,
default: "button"
},
label: [Number, String],
icon: String,
iconRight: String,
round: Boolean,
outline: Boolean,
flat: Boolean,
unelevated: Boolean,
rounded: Boolean,
push: Boolean,
glossy: Boolean,
size: String,
fab: Boolean,
fabMini: Boolean,
padding: String,
color: String,
textColor: String,
noCaps: Boolean,
noWrap: Boolean,
dense: Boolean,
tabindex: [Number, String],
ripple: {
type: [Boolean, Object],
default: true
},
align: {
...useAlignProps.align,
default: "center"
},
stack: Boolean,
stretch: Boolean,
loading: {
type: Boolean,
default: null
},
disable: Boolean
};
function useBtn(props) {
const sizeStyle = useSize(props, defaultSizes);
const alignClass = useAlign(props);
const style = computed(() => {
const obj = props.fab === false && props.fabMini === false ? sizeStyle.value : {};
return props.padding !== void 0 ? Object.assign({}, obj, {
padding: props.padding.split(/\s+/).map((v) => v in padding ? padding[v] + "px" : v).join(" "),
minWidth: "0",
minHeight: "0"
}) : obj;
});
const isRounded = computed(() => props.rounded === true || props.fab === true || props.fabMini === true);
const isActionable = computed(() => props.disable !== true && props.loading !== true);
const tabIndex = computed(() => isActionable.value === true ? props.tabindex || 0 : -1);
const design = computed(() => {
if (props.flat === true)
return "flat";
if (props.outline === true)
return "outline";
if (props.push === true)
return "push";
if (props.unelevated === true)
return "unelevated";
return "standard";
});
const attributes = computed(() => {
const acc = { tabindex: tabIndex.value };
if (props.type !== "a") {
acc.type = props.type;
}
acc.role = props.type === "a" ? "link" : "button";
if (props.loading === true && props.percentage !== void 0) {
Object.assign(acc, {
role: "progressbar",
"aria-valuemin": 0,
"aria-valuemax": 100,
"aria-valuenow": props.percentage
});
}
if (props.disable === true) {
acc.disabled = "";
acc["aria-disabled"] = "true";
}
return acc;
});
const classes = computed(() => {
let colors;
if (props.color !== void 0) {
if (props.flat === true || props.outline === true) {
colors = `text-${props.textColor || props.color}`;
} else {
colors = `bg-${props.color} text-${props.textColor || "white"}`;
}
} else if (props.textColor) {
colors = `text-${props.textColor}`;
}
return `vc-btn--${design.value} vc-btn--${props.round === true ? "round" : `rectangle${isRounded.value === true ? " vc-btn--rounded" : ""}`}` + (colors !== void 0 ? " " + colors : "") + (isActionable.value === true ? " vc-btn--actionable vc-focusable vc-hoverable" : props.disable === true ? " disabled" : "") + (props.fab === true ? " vc-btn--fab" : props.fabMini === true ? " vc-btn--fab-mini" : "") + (props.noCaps === true ? " vc-btn--no-uppercase" : "") + (props.dense === true ? " vc-btn--dense" : "") + (props.stretch === true ? " no-border-radius self-stretch" : "") + (props.glossy === true ? " glossy" : "");
});
const innerClasses = computed(
() => alignClass.value + (props.stack === true ? " column" : " row") + (props.noWrap === true ? " no-wrap text-no-wrap" : "") + (props.loading === true ? " vc-btn__content--hidden" : "")
);
return {
classes,
style,
innerClasses,
attributes,
isActionable
};
}
const { passiveCapture } = listenOpts;
let touchTarget, keyboardTarget, mouseTarget;
const btnProps = exports('btnProps', {
...useBtnProps,
percentage: {
type: Number,
default: 0
},
darkPercentage: Boolean
});
var Btn = defineComponent({
name: "VcBtn",
props: btnProps,
emits: ["click", "keydown", "touchstart", "mousedown", "keyup"],
setup(props, { slots, emit }) {
var _a;
const proxy = (_a = getCurrentInstance()) == null ? void 0 : _a.proxy;
const { classes, style, innerClasses, attributes, isActionable } = useBtn(props);
const rootRef = ref();
const blurTargetRef = ref();
let localTouchTargetEl = null, avoidMouseRipple, mouseTimer;
const hasLabel = computed(() => props.label !== void 0 && props.label !== null && props.label !== "");
const ripple = computed(
() => props.ripple === false ? false : {
// keyCodes: isLink.value === true ? [ 13, 32 ] : [ 13 ],
keyCodes: 13,
...props.ripple === true ? {} : props.ripple
}
);
const percentageStyle = computed(() => {
const val = Math.max(0, Math.min(100, props.percentage));
return val > 0 ? { transition: "transform 0.6s", transform: `translateX(${val - 100}%)` } : {};
});
const onEvents = computed(() => {
if (props.loading === true) {
return {
onMousedown: onLoadingEvt,
onTouchstart: onLoadingEvt,
onClick: onLoadingEvt,
onKeydown: onLoadingEvt,
onKeyup: onLoadingEvt
};
} else if (isActionable.value === true) {
return {
onClick,
onKeydown,
onMousedown,
onTouchstart
};
}
return {};
});
const directives = computed(() => {
return [[Ripple, ripple.value, void 0, { center: props.round }]];
});
const nodeProps = computed(() => ({
ref: rootRef,
class: "vc-btn vc-btn-item non-selectable no-outline " + classes.value,
style: style.value,
...attributes.value,
...onEvents.value
}));
function onClick(e) {
var _a2;
if (e !== void 0) {
if (e.defaultPrevented === true) {
return;
}
const el = document.activeElement;
if (props.type === "submit" && el !== document.body && ((_a2 = rootRef.value) == null ? void 0 : _a2.contains(el)) === false && // required for iOS and desktop Safari
(el == null ? void 0 : el.contains(rootRef.value)) === false) {
rootRef.value.focus();
const onClickCleanup = () => {
document.removeEventListener("keydown", stopAndPrevent, true);
document.removeEventListener("keyup", onClickCleanup, passiveCapture);
rootRef.value !== null && rootRef.value.removeEventListener("blur", onClickCleanup, passiveCapture);
};
document.addEventListener("keydown", stopAndPrevent, true);
document.addEventListener("keyup", onClickCleanup, passiveCapture);
rootRef.value.addEventListener("blur", onClickCleanup, passiveCapture);
}
}
const go = () => {
};
emit("click", e, go);
}
function onKeydown(e) {
var _a2, _b, _c;
if (isKeyCode(e, [13, 32]) === true) {
stopAndPrevent(e);
if (keyboardTarget !== rootRef.value) {
keyboardTarget !== null && cleanup();
(_a2 = rootRef.value) == null ? void 0 : _a2.focus();
keyboardTarget = rootRef.value;
(_b = rootRef.value) == null ? void 0 : _b.classList.add("vc-btn--active");
document.addEventListener("keyup", onPressEnd, true);
(_c = rootRef.value) == null ? void 0 : _c.addEventListener("blur", onPressEnd, passiveCapture);
}
}
emit("keydown", e);
}
function onTouchstart(e) {
if (touchTarget !== rootRef.value) {
touchTarget !== null && cleanup();
touchTarget = rootRef.value;
localTouchTargetEl = getTouchTarget(e.target);
localTouchTargetEl == null ? void 0 : localTouchTargetEl.addEventListener("touchcancel", onPressEnd, passiveCapture);
localTouchTargetEl == null ? void 0 : localTouchTargetEl.addEventListener("touchend", onPressEnd, passiveCapture);
}
avoidMouseRipple = true;
clearTimeout(mouseTimer);
mouseTimer = setTimeout(() => {
avoidMouseRipple = false;
}, 200);
emit("touchstart", e);
}
function onMousedown(e) {
var _a2;
if (mouseTarget !== rootRef.value) {
mouseTarget !== null && cleanup();
mouseTarget = rootRef.value;
(_a2 = rootRef.value) == null ? void 0 : _a2.classList.add("vc-btn--active");
document.addEventListener("mouseup", onPressEnd, passiveCapture);
}
e.qSkipRipple = avoidMouseRipple === true;
emit("mousedown", e);
}
function onPressEnd(e) {
var _a2;
if (e !== void 0 && e.type === "blur" && document.activeElement === rootRef.value) {
return;
}
if (e !== void 0 && e.type === "keyup") {
if (keyboardTarget === rootRef.value && isKeyCode(e, [13, 32]) === true) {
const evt = new MouseEvent("click", e);
evt.qKeyEvent = true;
e.defaultPrevented === true && prevent(evt);
e.cancelBubble === true && stop(evt);
(_a2 = rootRef.value) == null ? void 0 : _a2.dispatchEvent(evt);
stopAndPrevent(e);
e.qKeyEvent = true;
}
emit("keyup", e);
}
cleanup();
}
function cleanup(destroying) {
const blurTarget = blurTargetRef.value;
if (destroying !== true && (touchTarget === rootRef.value || mouseTarget === rootRef.value) && blurTarget !== null && blurTarget !== document.activeElement) {
blurTarget.setAttribute("tabindex", "-1");
blurTarget.focus();
}
if (touchTarget === rootRef.value) {
if (localTouchTargetEl !== null) {
localTouchTargetEl.removeEventListener("touchcancel", onPressEnd, passiveCapture);
localTouchTargetEl.removeEventListener("touchend", onPressEnd, passiveCapture);
}
touchTarget = localTouchTargetEl = null;
}
if (mouseTarget === rootRef.value) {
document.removeEventListener("mouseup", onPressEnd, passiveCapture);
mouseTarget = null;
}
if (keyboardTarget === rootRef.value) {
document.removeEventListener("keyup", onPressEnd, true);
rootRef.value !== null && rootRef.value.removeEventListener("blur", onPressEnd, passiveCapture);
keyboardTarget = null;
}
rootRef.value !== null && rootRef.value.classList.remove("vc-btn--active");
}
function onLoadingEvt(evt) {
stopAndPrevent(evt);
evt.qSkipRipple = true;
}
onBeforeUnmount(() => {
cleanup(true);
});
Object.assign(proxy, {
click: onClick
});
return () => {
let inner = [];
props.icon !== void 0 && inner.push(
h(Icon, {
name: props.icon,
left: props.stack === false && hasLabel.value === true,
role: "img",
"aria-hidden": "true"
})
);
hasLabel.value === true && inner.push(h("span", { class: "block" }, [props.label]));
inner = hMergeSlot(slots.default, inner);
if (props.iconRight !== void 0 && props.round === false) {
inner.push(
h(Icon, {
name: props.iconRight,
right: props.stack === false && hasLabel.value === true,
role: "img",
"aria-hidden": "true"
})
);
}
const child = [
h("span", {
class: "vc-focus-helper",
ref: blurTargetRef
})
];
if (props.loading === true && props.percentage !== void 0) {
child.push(
h(
"span",
{
class: "vc-btn__progress absolute-full overflow-hidden"
},
[
h("span", {
class: "vc-btn__progress-indicator fit block" + (props.darkPercentage === true ? " vc-btn__progress--dark" : ""),
style: percentageStyle.value
})
]
)
);
}
child.push(
h(
"span",
{
class: "vc-btn__content text-center col items-center vc-anchor--skip " + innerClasses.value
},
inner
)
);
props.loading !== null && child.push(
h(
Transition,
{
name: "vc-transition--fade"
},
() => props.loading === true ? [
h(
"span",
{
key: "loading",
class: "absolute-full flex flex-center"
},
slots.loading !== void 0 ? slots.loading() : [h(Spinner)]
)
] : null
)
);
return hDir("button", nodeProps.value, child, "ripple", props.disable !== true && props.ripple !== false, () => directives.value);
};
}
});
const useAnchorProps = {
target: {
type: [Boolean, String],
default: true
},
noParentEvent: Boolean,
contextMenu: Boolean
};
function useAnchor({
showing,
avoidEmit,
// required for VcPopupProxy (true)
configureAnchorEl
// optional
}) {
const { props, proxy, emit } = getCurrentInstance();
const anchorEl = ref(null);
let touchTimer;
function canShow(evt) {
return anchorEl.value === null ? false : evt === void 0 || evt.touches === void 0 || evt.touches.length <= 1;
}
const anchorEvents = {};
if (configureAnchorEl === void 0) {
Object.assign(anchorEvents, {
hide(evt) {
proxy.hide(evt);
},
toggle(evt) {
proxy.toggle(evt);
},
toggleKey(evt) {
isKeyCode(evt, 13) === true && proxy.toggle(evt);
},
contextClick(evt) {
proxy.hide(evt);
nextTick(() => {
proxy.show(evt);
});
prevent(evt);
},
mobilePrevent: prevent,
mobileTouch(evt) {
var _a;
anchorEvents.mobileCleanup(evt);
if (canShow(evt) !== true) {
return;
}
proxy.hide(evt);
(_a = anchorEl.value) == null ? void 0 : _a.classList.add("non-selectable");
const target = getTouchTarget(evt.target);
addEvt(anchorEvents, "anchor", [
[target, "touchmove", "mobileCleanup", "passive"],
[target, "touchend", "mobileCleanup", "passive"],
[target, "touchcancel", "mobileCleanup", "passive"],
[anchorEl.value, "contextmenu", "mobilePrevent", "notPassive"]
]);
touchTimer = setTimeout(() => {
proxy.show(evt);
}, 300);
},
mobileCleanup(evt) {
anchorEl.value.classList.remove("non-selectable");
clearTimeout(touchTimer);
if (showing.value === true && evt !== void 0) {
clearSelection();
}
}
});
configureAnchorEl = function(context = props.contextMenu) {
if (props.noParentEvent === true || anchorEl.value === null) {
return;
}
let evts;
if (context === true) {
if (platform().isPhone === true) {
evts = [[anchorEl.value, "touchstart", "mobileTouch", "passive"]];
} else {
evts = [
[anchorEl.value, "click", "hide", "passive"],
[anchorEl.value, "contextmenu", "contextClick", "notPassive"]
];
}
} else {
evts = [
[anchorEl.value, "click", "toggle", "passive"],
[anchorEl.value, "keyup", "toggleKey", "passive"]
];
}
addEvt(anchorEvents, "anchor", evts);
};
}
function unconfigureAnchorEl() {
cleanEvt(anchorEvents, "anchor");
}
function setAnchorEl(el) {
anchorEl.value = el;
while (anchorEl.value.classList.contains("vc-anchor--skip")) {
anchorEl.value = anchorEl.value.parentNode;
}
configureAnchorEl();
}
function pickAnchorEl() {
if (props.target === false || props.target === "") {
anchorEl.value = null;
} else if (props.target === true) {
setAnchorEl(proxy == null ? void 0 : proxy.$el.parentNode);
} else {
let el = props.target;
if (typeof props.target === "string") {
try {
el = document.querySelector(props.target);
} catch (err) {
el = void 0;
}
}
if (el !== void 0 && el !== null) {
anchorEl.value = el.$el || el;
configureAnchorEl();
} else {
anchorEl.value = null;
console.error(`Anchor: target "${props.target}" not found`);
}
}
}
watch(
() => props.contextMenu,
(val) => {
if (anchorEl.value !== null) {
unconfigureAnchorEl();
configureAnchorEl(val);
}
}
);
watch(
() => props.target,
() => {
if (anchorEl.value !== null) {
unconfigureAnchorEl();
}
pickAnchorEl();
}
);
watch(
() => props.noParentEvent,
(val) => {
if (anchorEl.value !== null) {
if (val === true) {
unconfigureAnchorEl();
} else {
configureAnchorEl();
}
}
}
);
onMounted(() => {
pickAnchorEl();
if (avoidEmit !== true && props.modelValue === true && anchorEl.value === null) {
emit("update:modelValue", false);
}
});
onBeforeUnmount(() => {
clearTimeout(touchTimer);
unconfigureAnchorEl();
});
return {
anchorEl,
canShow,
anchorEvents
};
}
function useScrollTarget(props, configureScrollTarget) {
const localScrollTarget = ref(null);
let scrollFn;
function changeScrollEvent(scrollTarget, fn) {
const fnProp = `${fn !== void 0 ? "add" : "remove"}EventListener`;
const fnHandler = fn !== void 0 ? fn : scrollFn;
if (scrollTarget !== window) {
scrollTarget[fnProp]("scroll", fnHandler, listenOpts.passive);
}
window[fnProp]("scroll", fnHandler, listenOpts.passive);
scrollFn = fn;
}
function unconfigureScrollTarget() {
if (localScrollTarget.value !== null) {
changeScrollEvent(localScrollTarget.value);
localScrollTarget.value = null;
}
}
const noParentEventWatcher = watch(
() => props.noParentEvent,
() => {
if (localScrollTarget.value !== null) {
unconfigureScrollTarget();
configureScrollTarget();
}
}
);
onBeforeUnmount(noParentEventWatcher);
return {
localScrollTarget,
unconfigureScrollTarget,
changeScrollEvent
};
}
const useModelToggleProps = {
modelValue: {
type: Boolean,
default: null
}
};
const useModelToggleEmits = ["update:modelValue", "before-show", "show", "before-hide", "hide"];
function useModelToggle({
showing,
canShow = void 0,
// optional
hideOnRouteChange = void 0,
// optional
handleShow = void 0,
// optional
handleHide = void 0,
// optional
processOnMount = void 0
// optional
}) {
const vm = getCurrentInstance();
const { props, emit, proxy } = vm;
let payload;
function toggle(evt) {
if ((showing == null ? void 0 : showing.value) === true) {
hide(evt);
} else {
show(evt);
}
}
function show(evt) {
if (props.disable === true || canShow !== void 0 && canShow(evt) !== true) {
return;
}
const listener = vmHasListener(vm, "onUpdate:modelValue") === true;
if (listener === true) {
emit("update:modelValue", true);
payload = evt;
nextTick(() => {
if (payload === evt) {
payload = void 0;
}
});
}
if (props.modelValue === null || listener === false) {
processShow(evt);
}
}
function processShow(evt) {
if ((showing == null ? void 0 : showing.value) === true) {
return;
}
showing && (showing.value = true);
emit("before-show", evt);
if (evt && evt.cancel === true) {
return;
}
if (handleShow !== void 0) {
handleShow(evt);
} else {
emit("show", evt);
}
}
function hide(evt) {
if (props.disable === true) {
return;
}
const listener = vmHasListener(vm, "onUpdate:modelValue") === true;
if (listener === true) {
emit("update:modelValue", false);
payload = evt;
nextTick(() => {
if (payload === evt) {
payload = void 0;
}
});
}
if (props.modelValue === null || listener === false) {
processHide(evt);
}
}
function processHide(evt) {
if ((showing == null ? void 0 : showing.value) === false) {
return;
}
showing && (showing.value = false);
emit("before-hide", evt);
if (handleHide !== void 0) {
handleHide(evt);
} else {
emit("hide", evt);
}
}
function processModelChange(val) {
if (props.disable === true && val === true) {
if (vmHasListener(vm, "onUpdate:modelValue") === true) {
emit("update:modelValue", false);
}
} else if (val === true !== (showing == null ? void 0 : showing.value)) {
const fn = val === true ? processShow : processHide;
fn(payload);
}
}
watch(() => props.modelValue, processModelChange);
if (hideOnRouteChange !== void 0 && vmHasRouter(vm) === true) {
watch(
() => proxy.$route,
() => {
if (hideOnRouteChange.value === true && (showing == null ? void 0 : showing.value) === true) {
hide();
}
}
);
}
processOnMount === true && onMounted(() => {
processModelChange(props.modelValue);
});
const publicMethods = { show, hide, toggle };
Object.assign(proxy, publicMethods);
return publicMethods;
}
let target = document.body;
function createGlobalNode(id) {
const el = document.createElement("div");
if (id !== void 0) {
el.id = id;
}
target.appendChild(el);
return el;
}
function removeGlobalNode(el) {
el.remove();
}
const portalList = [];
function isOnGlobalDialog(vm) {
vm = vm.parent;
while (vm !== void 0 && vm !== null) {
if (vm.type.name === "VcGlobalDialog") {
return true;
}
if (vm.type.name === "VcDialog" || vm.type.name === "VcMenu") {
return false;
}
vm = vm.parent;
}
return false;
}
function usePortal(vm, innerRef, renderPortalContent, checkGlobalDialog) {
var _a, _b, _c, _d;
let portalEl = null;
if ((_b = (_a = vm.props) == null ? void 0 : _a.teleport) == null ? void 0 : _b.to) {
portalEl = (_d = (_c = vm.props) == null ? void 0 : _c.teleport) == null ? void 0 : _d.to;
}
const onGlobalDialog = checkGlobalDialog === true && isOnGlobalDialog(vm);
const portalIsActive = ref(false);
function showPortal() {
if (onGlobalDialog === false && portalEl === null) {
portalEl = createGlobalNode();
}
portalIsActive.value = true;
portalList.push(vm.proxy);
}
function hidePortal() {
var _a2, _b2;
portalIsActive.value = false;
const index = portalList.indexOf(vm.proxy);
if (index > -1) {
portalList.splice(index, 1);
}
if (portalEl !== null && !((_b2 = (_a2 = vm.props) == null ? void 0 : _a2.teleport) == null ? void 0 : _b2.to)) {
removeGlobalNode(portalEl);
portalEl = null;
}
}
onUnmounted(hidePortal);
Object.assign(vm.proxy, { __vcPortalInnerRef: innerRef });
return {
showPortal,
hidePortal,
portalIsActive,
renderPortal: () => {
return onGlobalDialog === true ? renderPortalContent() : portalIsActive.value === true ? [h(Teleport, { to: portalEl }, renderPortalContent())] : void 0;
}
};
}
const useTransitionProps = {
transitionShow: {
type: String,
default: "fade"
},
transitionHide: {
type: String,
default: "fade"
},
transitionDuration: {
type: [String, Number],
default: 300
}
};
function useTransition(props, showing) {
const transitionState = ref(showing.value);
watch(showing, (val) => {
nextTick(() => {
transitionState.value = val;
});
});
return {
transition: computed(() => "vc-transition--" + (transitionState.value === true ? props.transitionHide : props.transitionShow)),
transitionStyle: computed(() => `--vc-transition-duration: ${props.transitionDuration}ms`)
};
}
function useTick() {
let tickFn;
onBeforeUnmount(() => {
tickFn = void 0;
});
return {
registerTick(fn) {
tickFn = fn;
},
removeTick() {
tickFn = void 0;
},
prepareTick() {
if (tickFn !== void 0) {
const fn = tickFn;
nextTick(() => {
if (tickFn === fn) {
tickFn();
tickFn = void 0;
}
});
}
}
};
}
const scrollTargets = [null, document, document.body, document.scrollingElement, document.documentElement];
function getScrollTarget(el, targetEl) {
let target = getElement(targetEl);
if (target === void 0) {
if (el === void 0 || el === null) {
return window;
}
target = el.closest(".scroll,.scroll-y,.overflow-auto");
}
return scrollTargets.includes(target) ? window : target;
}
let size;
function getScrollbarWidth() {
if (size !== void 0) {
return size;
}
const inner = document.createElement("p"), outer = document.createElement("div");
css(inner, {
width: "100%",
height: "200px"
});
css(outer, {
position: "absolute",
top: "0px",
left: "0px",
visibility: "hidden",
width: "200px",
height: "150px",
overflow: "hidden"
});
outer.appendChild(inner);
document.body.appendChild(outer);
const w1 = inner.offsetWidth;
outer.style.overflow = "scroll";
let w2 = inner.offsetWidth;
if (w1 === w2) {
w2 = outer.clientWidth;
}
outer.remove();
size = w1 - w2;
return size;
}
let vpLeft, vpTop;
function validatePosition(pos) {
const parts = pos.split(" ");
if (parts.length !== 2) {
return false;
}
if (["top", "center", "bottom"].includes(parts[0]) !== true) {
console.error("Anchor/Self position must start with one of top/center/bottom");
return false;
}
if (["left", "middle", "right", "start", "end"].includes(parts[1]) !== true) {
console.error("Anchor/Self position must end with one of left/middle/right/start/end");
return false;
}
return true;
}
function validateOffset(val) {
if (!val) {
return true;
}
if (val.length !== 2) {
return false;
}
if (typeof val[0] !== "number" || typeof val[1] !== "number") {
return false;
}
return true;
}
const horizontalPos = {
"start#ltr": "left",
"start#rtl": "right",
"end#ltr": "right",
"end#rtl": "left"
};
["left", "middle", "right"].forEach((pos) => {
horizontalPos[`${pos}#ltr`] = pos;
horizontalPos[`${pos}#rtl`] = pos;
});
function parsePosition(pos, rtl) {
const parts = pos.split(" ");
return {
vertical: parts[0],
horizontal: horizontalPos[`${parts[1]}#${rtl === true ? "rtl" : "ltr"}`]
};
}
function getAnchorProps(el, offset) {
let { top, left, right, bottom, width, height } = el.getBoundingClientRect();
if (offset !== void 0) {
top -= offset[1];
left -= offset[0];
bottom += offset[1];
right += offset[0];
width += offset[0];
height += offset[1];
}
return {
top,
left,
right,
bottom,
width,
height,
middle: left + (right - left) / 2,
center: top + (bottom - top) / 2
};
}
function getTargetProps(el) {
return {
top: 0,
center: el.offsetHeight / 2,
bottom: el.offsetHeight,
left: 0,
middle: el.offsetWidth / 2,
right: el.offsetWidth
};
}
function setPosition(cfg) {
if (platform().isIOS === true && window.visualViewport !== void 0) {
const el = document.body.style;
const { offsetLeft: left, offsetTop: top } = window.visualViewport;
if (left !== vpLeft) {
el.setProperty("--vc-pe-left", left + "px");
vpLeft = left;
}
if (top !== vpTop) {
el.setProperty("--vc-pe-top", top + "px");
vpTop = top;
}
}
let anchorProps = {};
const { scrollLeft, scrollTop } = cfg.el;
if (cfg.absoluteOffset === void 0) {
anchorProps = getAnchorProps(cfg.anchorEl, cfg.cover === true ? [0, 0] : cfg.offset);
} else {
const { top: anchorTop, left: anchorLeft } = cfg.anchorEl.getBoundingClientRect(), top = anchorTop + cfg.absoluteOffset.top, left = anchorLeft + cfg.absoluteOffset.left;
anchorProps = { top, left, width: 1, height: 1, right: left + 1, center: top, middle: left, bottom: top + 1 };
}
let elStyle = {
maxHeight: cfg.maxHeight,
maxWidth: cfg.maxWidth,
visibility: "visible"
};
if (cfg.fit === true || cfg.cover === true) {
elStyle.minWidth = anchorProps.width + "px";
if (cfg.cover === true) {
elStyle.minHeight = anchorProps.height + "px";
}
}
Object.assign(cfg.el.style, elStyle);
const targetProps = getTargetProps(cfg.el), props = {
top: anchorProps[cfg.anchorOrigin.vertical] - targetProps[cfg.selfOrigin.vertical],
left: anchorProps[cfg.anchorOrigin.horizontal] - targetProps[cfg.selfOrigin.horizontal]
};
applyBoundaries(props, anchorProps, targetProps, cfg.anchorOrigin, cfg.selfOrigin);
elStyle = {
top: props.top + "px",
left: props.left + "px"
};
if (props.maxHeight !== void 0) {
elStyle.maxHeight = props.maxHeight + "px";
if (anchorProps.height > props.maxHeight) {
elStyle.minHeight = elStyle.maxHeight;
}
}
if (props.maxWidth !== void 0) {
elStyle.maxWidth = props.maxWidth + "px";
if (anchorProps.width > props.maxWidth) {
elStyle.minWidth = elStyle.maxWidth;
}
}
Object.assign(cfg.el.style, elStyle);
if (cfg.el.scrollTop !== scrollTop) {
cfg.el.scrollTop = scrollTop;
}
if (cfg.el.scrollLeft !== scrollLeft) {
cfg.el.scrollLeft = scrollLeft;
}
}
function applyBoundaries(props, anchorProps, targetProps, anchorOrigin, selfOrigin) {
const currentHeight = targetProps.bottom, currentWidth = targetProps.right, margin = getScrollbarWidth(), innerHeight = window.innerHeight - margin, innerWidth = document.body.clientWidth;
if (props.top < 0 || props.top + currentHeight > innerHeight) {
if (selfOrigin.vertical === "center") {
props.top = anchorProps[anchorOrigin.vertical] > innerHeight / 2 ? Math.max(0, innerHeight - currentHeight) : 0;
props.maxHeight = Math.min(currentHeight, innerHeight);
} else if (anchorProps[anchorOrigin.vertical] > innerHeight / 2) {
const anchorY = Math.min(
innerHeight,
anchorOrigin.vertical === "center" ? anchorProps.center : anchorOrigin.vertical === selfOrigin.vertical ? anchorProps.bottom : anchorProps.top
);
props.maxHeight = Math.min(currentHeight, anchorY);
props.top = Math.max(0, anchorY - currentHeight);
} else {
props.top = Math.max(
0,
anchorOrigin.vertical === "center" ? anchorProps.center : anchorOrigin.vertical === selfOrigin.vertical ? anchorProps.top : anchorProps.bottom
);
props.maxHeight = Math.min(currentHeight, innerHeight - props.top);
}
}
if (props.left < 0 || props.left + currentWidth > innerWidth) {
props.maxWidth = Math.min(currentWidth, innerWidth);
if (selfOrigin.horizontal === "middle") {
props.left = anchorProps[anchorOrigin.horizontal] > innerWidth / 2 ? Math.max(0, innerWidth - currentWidth) : 0;
} else if (anchorProps[anchorOrigin.horizontal] > innerWidth / 2) {
const anchorX = Math.min(
innerWidth,
anchorOrigin.horizontal === "middle" ? anchorProps.middle : anchorOrigin.horizontal === selfOrigin.horizontal ? anchorProps.right : anchorProps.left
);
props.maxWidth = Math.min(currentWidth, anchorX);
props.left = Math.max(0, anchorX - props.maxWidth);
} else {
props.left = Math.max(
0,
anchorOrigin.horizontal === "middle" ? anchorProps.middle : anchorOrigin.horizontal === selfOrigin.horizontal ? anchorProps.left : anchorProps.right
);
props.maxWidth = Math.min(currentWidth, innerWidth - props.left);
}
}
}
const tooltipProps = exports('tooltipProps', {
...useAnchorProps,
...useModelToggleProps,
...useTransitionProps,
maxHeight: {
type: String,
default: null
},
maxWidth: {
type: String,
default: null
},
transitionShow: {
type: String,
default: "jump-down"
},
transitionHide: {
type: String,
default: "jump-up"
},
anchor: {
type: String,
default: "bottom middle",
validator: validatePosition
},
self: {
type: String,
default: "top middle",
validator: validatePosition
},
offset: {
type: Array,
default: () => [14, 14],
validator: validateOffset
},
scrollTarget: String,
delay: {
type: Number,
default: 0
},
hideDelay: {
type: Number,
default: 0
},
persistent: {
type: Boolean
}
});
var Tooltip = defineComponent({
name: "VcTooltip",
inheritAttrs: false,
props: tooltipProps,
emits: [...useModelToggleEmits],
setup(props, { slots, emit, attrs }) {
let unwatchPosition, observer;
const vm = getCurrentInstance();
const innerRef = ref(null);
const showing = ref(false);
const anchorOrigin = computed(() => parsePosition(props.anchor, true));
const selfOrigin = computed(() => parsePosition(props.self, true));
const hideOnRouteChange = computed(() => props.persistent !== true);
const { registerTick, removeTick, prepareTick } = useTick();
const { registerTimeout, removeTimeout } = useTimeout();
const { transition, transitionStyle } = useTransition(props, showing);
const { localScrollTarget, changeScrollEvent, unconfigureScrollTarget } = useScrollTarget(props, configureScrollTarget);
const { anchorEl, canShow, anchorEvents } = useAnchor({ showing, configureAnchorEl, avoidEmit: void 0 });
const { show, hide } = useModelToggle({
showing,
canShow,
handleShow,
handleHide,
hideOnRouteChange,
processOnMount: true
});
Object.assign(anchorEvents, { delayShow, delayHide });
const { showPortal, hidePortal, renderPortal } = usePortal(vm, innerRef, renderPortalContent);
function handleShow(evt) {
removeTick();
removeTimeout();
showPortal();
registerTick(() => {
observer = new MutationObserver(() => updatePosition());
observer.observe(innerRef.value, { attributes: false, childList: true, characterData: true, subtree: true });
updatePosition();
configureScrollTarget();
});
prepareTick();
if (unwatchPosition === void 0) {
unwatchPosition = watch(() => props.self + "|" + props.anchor, updatePosition);
}
registerTimeout(() => {
emit("show", evt);
}, props.transitionDuration);
}
function handleHide(evt) {
removeTick();
removeTimeout();
anchorCleanup();
registerTimeout(() => {
hidePortal();
emit("hide", evt);
}, props.transitionDuration);
}
function anchorCleanup() {
if (observer !== void 0) {
observer.disconnect();
observer = void 0;
}
if (unwatchPosition !== void 0) {
unwatchPosition();
unwatchPosition = void 0;
}
unconfigureScrollTarget();
cleanEvt(anchorEvents, "tooltipTemp");
}
function updatePosition() {
const el = innerRef.value;
if (anchorEl.value === void 0 || !el) {
return;
}
setPosition({
el,
offset: props.offset,
anchorEl: anchorEl.value,
anchorOrigin: anchorOrigin.value,
selfOrigin: selfOrigin.value,
maxHeight: props.maxHeight,
maxWidth: props.maxWidth
});
}
function delayShow(evt) {
if (platform().isPhone === true) {
clearSelection();
document.body.classList.add("non-selectable");
const target = getTouchTarget(anchorEl.value);
const evts = ["touchmove", "touchcancel", "touchend", "click"].map((e) => [target, e, "__delayHide", "passiveCapture"]);
addEvt(anchorEvents, "tooltipTemp", evts);
}
registerTimeout(() => {
show(evt);
}, props.delay);
}
function delayHide(evt) {
removeTimeout();
if (platform().isPhone === true) {
cleanEvt(anchorEvents, "tooltipTemp");
clearSelection();
setTimeout(() => {
document.body.classList.remove("non-selectable");
}, 10);
}
registerTimeout(() => {
hide(evt);
}, props.hideDelay);
}
function configureAnchorEl() {
if (props.noParentEvent === true || anchorEl.value === void 0) {
return;
}
const evts = platform().isPhone === true ? [[anchorEl.value, "touchstart", "delayShow", "passive"]] : [
[anchorEl.value, "mouseenter", "delayShow", "passive"],
[anchorEl.value, "mouseleave", "delayHide", "passive"]
];
addEvt(anchorEvents, "anchor", evts);
}
function configureScrollTarget() {
if (anchorEl.value !== void 0 || props.scrollTarget !== void 0) {
localScrollTarget.value = getScrollTarget(anchorEl.value, props.scrollTarget);
const fn = props.noParentEvent === true ? updatePosition : hide;
changeScrollEvent(localScrollTarget.value, fn);
}
}
function getTooltipContent() {
return showing.value === true ? h(
"div",
{
...attrs,
ref: innerRef,
class: ["vc-tooltip vc-tooltip--style vc-position-engine no-pointer-events", attrs.class],
style: transitionStyle.value,
role: "complementary"
},
hSlot(slots.default)
) : null;
}
function renderPortalContent() {
return h(
Transition,
{
name: transition.value,
appear: true
},
getTooltipContent
);
}
onBeforeUnmount(anchorCleanup);
Object.assign(vm == null ? void 0 : vm.proxy, { updatePosition });
return renderPortal;
}
});
function between(v, min, max) {
return max <= min ? min : Math.min(max, Math.max(min, v));
}
const xhr = XMLHttpRequest, open = xhr.prototype.open, positionValues = ["top", "right", "bottom", "left"];
let stack = [];
let highjackCount = 0;
function translate({ p, pos, active, horiz, reverse, dir }) {
let x = 1, y = 1;
if (horiz === true) {
if (reverse === true) {
x = -1;
}
if (pos === "bottom") {
y = -1;
}
return { transform: `translate3d(${x * (p - 100)}%,${active ? 0 : y * -200}%,0)` };
}
if (reverse === true) {
y = -1;
}
if (pos === "right") {
x = -1;
}
return { transform: `translate3d(${active ? 0 : dir * x * -200}%,${y * (p - 100)}%,0)` };
}
function inc(p, amount) {
if (typeof amount !== "number") {
if (p < 25) {
amount = Math.random() * 3 + 3;
} else if (p < 65) {
amount = Math.random() * 3;
} else if (p < 85) {
amount = Math.random() * 2;
} else if (p < 99) {
amount = 0.6;
} else {
amount = 0;
}
}
return between(p + amount, 0, 100);
}
function highjackAjax(stackEntry) {
highjackCount++;
stack.push(stackEntry);
if (highjackCount > 1) {
return;
}
xhr.prototype.open = function(_, url) {
const stopStack = [];
const loadStart = () => {
stack.forEach((entry) => {
if (entry.hijackFilter.value === null || entry.hijackFilter.value(url) === true) {
entry.start();
stopStack.push(entry.stop);
}
});
};
const loadEnd = () => {
stopStack.forEach((stop) => {
stop();
});
};
this.addEventListener("loadstart", loadStart, { once: true });
this.addEventListener("loadend", loadEnd, { once: true });
open.apply(this, arguments);
};
}
function restoreAjax(start) {
stack = stack.filter((entry) => entry.start !== start);
highjackCount = Math.max(0, highjackCount - 1);
if (highjackCount === 0) {
xhr.prototype.open = open;
}
}
const ajaxBarProps = exports('ajaxBarProps', {
position: {
type: String,
default: "top",
validator: (val) => positionValues.includes(val)
},
size: {
type: String,
default: "2px"
},
color: String,
skipHijack: Boolean,
reverse: Boolean,
positioning: {
type: String,
default: "absolute",
validator: (val) => ["absolute", "fixed"].includes(val)
},
hijackFilter: Function
});
var AjaxBar = defineComponent({
name: "VcAjaxBar",
props: ajaxBarProps,
emits: ["start", "stop"],
setup(props, { emit }) {
const { proxy } = getCurrentInstance();
const progress = ref(0);
const onScreen = ref(false);
const animate = ref(true);
let sessions = 0, timer, speed;
const classes = computed(
() => `vc-loading-bar vc-loading-bar--${props.position}` + (props.color !== void 0 ? ` bg-${props.color}` : "") + (animate.value === true ? "" : " no-transition")
);
const horizontal = computed(() => props.position === "top" || props.position === "bottom");
const sizeProp = computed(() => horizontal.value === true ? "height" : "width");
const style = computed(() => {
const active = onScreen.value;
const obj = translate({
p: progress.value,
pos: props.position,
active,
horiz: horizontal.value,
reverse: props.reverse,
dir: 1
});
obj[sizeProp.value] = props.size;
obj.opacity = active ? 1 : 0;
obj.position = props.positioning === "absolute" ? "absolute" : "fixed";
obj.backgroundColor = props.color;
return obj;
});
const attributes = computed(
() => onScreen.value === true ? {
role: "progressbar",
"aria-valuemin": 0,
"aria-valuemax": 100,
"aria-valuenow": progress.value
} : { "aria-hidden": "true" }
);
function start(newSpeed = 300) {
const oldSpeed = speed;
speed = Math.max(0, newSpeed) || 0;
sessions++;
if (sessions > 1) {
if (oldSpeed === 0 && newSpeed > 0) {
planNextStep();
} else if (oldSpeed > 0 && newSpeed <= 0) {
clearTimeout(timer);
}
return sessions;
}
clearTimeout(timer);
emit("start");
progress.value = 0;
timer = setTimeout(
() => {
animate.value = true;
newSpeed > 0 && planNextStep();
},
onScreen.value === true ? 500 : 1
);
if (onScreen.value !== true) {
onScreen.value = true;
animate.value = false;
}
return sessions;
}
function increment(amount) {
if (sessions > 0) {
progress.value = inc(progress.value, amount);
}
return sessions;
}
function stop() {
sessions = Math.max(0, sessions - 1);
if (sessions > 0) {
return sessions;
}
clearTimeout(timer);
emit("stop");
const end = () => {
animate.value = true;
progress.value = 100;
timer = setTimeout(() => {
onScreen.value = false;
}, 1e3);
};
if (progress.value === 0) {
timer = setTimeout(end, 1);
} else {
end();
}
}
function planNextStep() {
if (progress.value < 100) {
timer = setTimeout(() => {
increment();
planNextStep();
}, speed);
}
}
let hijacked;
onMounted(() => {
if (props.skipHijack !== true) {
hijacked = true;
highjackAjax({
start,
stop,
hijackFilter: computed(() => props.hijackFilter || null)
});
}
});
onBeforeUnmount(() => {
clearTimeout(timer);
hijacked === true && restoreAjax(start);
});
Object.assign(proxy, { start, stop, increment });
return () => h("div", {
class: classes.value,
style: style.value,
...attributes.value
});
}
});
const useDarkProps = {
dark: {
type: Boolean,
default: null
}
};
function useDark(props) {
return computed(() => props.dark);
}
const skeletonTypes = exports('skeletonTypes', [
"text",
"rect",
"circle",
"VcBtn",
"VcBadge",
"VcChip",
"VcToolbar",
"VcCheckbox",
"VcRadio",
"VcToggle",
"VcSlider",
"VcRange",
"VcInput",
"VcAvatar"
]);
const skeletonAnimations = exports('skeletonAnimations', ["wave", "pulse", "pulse-x", "pulse-y", "fade", "blink", "none"]);
const skeletonProps = exports('skeletonProps', {
...useDarkProps,
tag: {
type: String,
default: "div"
},
type: {
type: String,
validator: (v) => skeletonTypes.includes(v),
default: "rect"
},
animation: {
type: String,
validator: (v) => skeletonAnimations.includes(v),
default: "wave"
},
square: Boolean,
bordered: Boolean,
size: String,
width: String,
height: String
});
var Skeleton = defineComponent({
name: "VcSkeleton",
props: skeletonProps,
setup(props, { slots }) {
const isDark = useDark(props);
const style = computed(() => props.size !== void 0 ? { width: props.size, height: props.size } : { width: props.width, height: props.height });
const classes = computed(
() => `vc-skeleton vc-skeleton--${isDark.value === true ? "dark" : "light"} vc-skeleton--type-${props.type}` + (props.animation !== "none" ? ` vc-skeleton--anim vc-skeleton--anim-${props.animation}` : "") + (props.square === true ? " vc-skeleton--square" : "") + (props.bordered === true ? " vc-skeleton--bordered" : "")
);
return () => h(
props.tag,
{
class: classes.value,
style: style.value
},
hSlot(slots.default)
);
}
});
const labelPositions = ["top", "right", "bottom", "left"];
const useFabProps = {
type: {
type: String,
default: "a"
},
outline: Boolean,
push: Boolean,
flat: Boolean,
unelevated: Boolean,
color: String,
textColor: String,
glossy: Boolean,
square: Boolean,
padding: String,
size: String,
label: {
type: [String, Number],
default: ""
},
labelPosition: {
type: String,
default: "right",
validator: (v) => labelPositions.includes(v)
},
externalLabel: Boolean,
hideLabel: {
type: Boolean
},
labelClass: [Array, String, Object],
labelStyle: [Array, String, Object],
disable: Boolean,
tabindex: [Number, String]
};
function useFab(props, showing) {
return {
formClass: computed(() => `vc-fab--form-${props.square === true ? "square" : "rounded"}`),
stacked: computed(() => props.externalLabel === false && ["top", "bottom"].includes(props.labelPosition)),
labelProps: computed(() => {
if (props.externalLabel === true) {
const hideLabel = props.hideLabel === null ? showing.value === false : props.hideLabel;
return {
action: "push",
data: {
class: [
props.labelClass,
`vc-fab__label vc-tooltip--style vc-fab__label--external vc-fab__label--external-${props.labelPosition}` + (hideLabel === true ? " vc-fab__label--external-hidden" : "")
],
style: props.labelStyle
}
};
}
return {
action: ["left", "top"].includes(props.labelPosition) ? "unshift" : "push",
data: {
class: [
props.labelClass,
`vc-fab__label vc-fab__label--internal vc-fab__label--internal-${props.labelPosition}` + (props.hideLabel === true ? " vc-fab__label--internal-hidden" : "")
],
style: props.labelStyle
}
};
})
};
}
const directions = ["up", "right", "down", "left"];
const alignValues = ["left", "center", "right"];
const defaultProps$6 = {
...useFabProps,
...useModelToggleProps,
icon: String,
activeIcon: String,
hideActionOnClick: {
type: Boolean,
default: true
},
hideIcon: Boolean,
hideLabel: {
type: Boolean,
default: true
},
direction: {
type: String,
default: "right",
validator: (v) => directions.includes(v)
},
persistent: Boolean,
stacked: Boolean,
verticalActionsAlign: {
type: String,
default: "center",
validator: (v) => alignValues.includes(v)
}
};
const fabProps = exports('fabProps', defaultProps$6);
var Fab = defineComponent({
name: "VcFab",
props: fabProps,
emits: useModelToggleEmits,
setup(props, { slots }) {
const triggerRef = ref(null);
const showing = ref(props.modelValue === true);
const { formClass, labelProps } = useFab(props, showing);
const hideOnRouteChange = computed(() => props.persistent !== true);
const { hide, toggle } = useModelToggle({
showing,
hideOnRouteChange
});
const slotScope = computed(() => ({ opened: showing.value }));
const classes = computed(
() => `vc-fab z-fab row inline justify-center vc-fab--align-${props.verticalActionsAlign} ${formClass.value}` + (showing.value === true ? " vc-fab--opened" : " vc-fab--closed")
);
const actionClass = computed(
() => `vc-fab__actions flex no-wrap inline vc-fab__actions--${props.direction} vc-fab__actions--${showing.value === true ? "opened" : "closed"}`
);
const iconHolderClass = computed(() => `vc-fab__icon-holder vc-fab__icon-holder--${showing.value === true ? "opened" : "closed"}`);
function getIcon(kebab, camel) {
const slotFn = slots[kebab];
const classes2 = `vc-fab__${kebab} absolute-full`;
return slotFn === void 0 ? h(Icon, { class: classes2, name: props[camel] }) : h("div", { class: classes2 }, slotFn(slotScope.value));
}
function getTriggerContent() {
const child = [];
props.hideIcon !== true && child.push(h("div", { class: iconHolderClass.value }, [getIcon("icon", "icon"), getIcon("active-icon", "activeIcon")]));
if (props.label !== "" || slots.label !== void 0) {
child[labelProps.value.action](h("div", labelProps.value.data, slots.label !== void 0 ? slots.label(slotScope.value) : [props.label]));
}
return hMergeSlot(slots.tooltip, child);
}
provide(fabKey, {
showing,
onChildClick(evt) {
props.hideActionOnClick && hide(evt);
if (triggerRef.value !== null) {
triggerRef.value.$el.focus();
}
}
});
return () => h(
"div",
{
class: classes.value
},
[
h(
Btn,
{
ref: triggerRef,
class: formClass.value,
...props,
noWrap: true,
stack: props.stacked,
align: void 0,
icon: void 0,
label: void 0,
noCaps: true,
fab: true,
flat: props.flat,
size: props.size,
"aria-expanded": showing.value === true ? "true" : "false",
"aria-haspopup": "true",
onClick: toggle
},
getTriggerContent
),
h("div", { class: actionClass.value }, hSlot(slots.default))
]
);
}
});
const anchorMap = {
start: "self-end",
center: "self-center",
end: "self-start"
};
const anchorValues = Object.keys(anchorMap);
const defaultProps$5 = {
...useFabProps,
icon: {
type: String,
default: ""
},
stacked: Boolean,
anchor: {
type: String,
validator: (v) => anchorValues.includes(v)
},
to: [String, Object],
replace: Boolean
};
const fabActionProps = exports('fabActionProps', defaultProps$5);
var FabAction = defineComponent({
name: "VcFabAction",
props: fabActionProps,
emits: ["click"],
setup(props, { slots, emit }) {
const $fab = inject(fabKey);
const { formClass, labelProps } = useFab(props, $fab == null ? void 0 : $fab.showing);
const classes = computed(() => {
let align = void 0;
if (props.anchor) {
align = anchorMap[props.anchor];
}
return formClass.value + (align !== void 0 ? ` ${align}` : "");
});
const isDisabled = computed(() => {
var _a;
return props.disable === true || ((_a = $fab == null ? void 0 : $fab.showing) == null ? void 0 : _a.value) !== true;
});
function click(e) {
var _a;
(_a = $fab == null ? void 0 : $fab.onChildClick) == null ? void 0 : _a.call($fab, e);
emit("click", e);
}
function getContent() {
const child = [];
props.icon !== "" && child.push(h(Icon, { name: props.icon }));
props.label !== "" && child[labelProps.value.action](h("div", labelProps.value.data, [props.label]));
return hMergeSlot(slots.default, child);
}
const vm = getCurrentInstance();
Object.assign(vm == null ? void 0 : vm.proxy, { click });
return () => h(
Btn,
{
class: classes.value,
...props,
noWrap: true,
stack: props.stacked,
icon: void 0,
label: void 0,
noCaps: true,
fabMini: true,
disable: isDisabled.value,
size: props.size,
onClick: click
},
getContent
);
}
});
const useFormProps = {
name: String
};
function useFormAttrs(props) {
return computed(() => ({
type: "hidden",
name: props.name,
value: props.modelValue
}));
}
function useFormInject(formAttrs = {}) {
return (child, action, className) => {
child[action](
h("input", {
class: "hidden" + (className || ""),
...formAttrs.value
})
);
};
}
const markerPrefixClass = "vc-slider__marker-labels";
const defaultMarkerConvertFn = (v) => ({ value: v });
const defaultMarkerLabelRenderFn = ({ marker }) => h(
"div",
{
key: marker.value,
style: marker.style,
class: marker.classes
},
marker.label
);
const keyCodes = [34, 37, 40, 33, 39, 38];
const useSliderProps = {
...useDarkProps,
...useFormProps,
min: {
type: Number,
default: 0
},
max: {
type: Number,
default: 100
},
innerMin: Number,
innerMax: Number,
step: {
type: Number,
default: 1,
validator: (v) => v >= 0
},
snap: Boolean,
vertical: Boolean,
reverse: Boolean,
hideSelection: Boolean,
color: String,
markerLabelsClass: String,
label: Boolean,
labelColor: String,
labelTextColor: String,
labelAlways: Boolean,
switchLabelSide: Boolean,
markers: [Boolean, Number],
markerLabels: [Boolean, Array, Object, Function],
switchMarkerLabelsSide: Boolean,
trackImg: String,
trackColor: String,
innerTrackImg: String,
innerTrackColor: String,
selectionColor: String,
selectionImg: String,
thumbSize: {
type: String,
default: "20px"
},
trackSize: {
type: String,
default: "4px"
},
disable: Boolean,
readonly: Boolean,
dense: Boolean,
tabindex: [String, Number],
thumbColor: String,
thumbPath: {
type: String,
default: "M 4, 10 a 6,6 0 1,0 12,0 a 6,6 0 1,0 -12,0"
}
};
const useSliderEmits = ["pan", "update:modelValue", "change"];
function useSlider({ updateValue, updatePosition, getDragging, formAttrs }) {
const { props, emit, slots, proxy } = getCurrentInstance();
const isDark = useDark(props);
const injectFormInput = useFormInject(formAttrs);
const active = ref(false);
const preventFocus = ref(false);
const focus = ref(false);
const dragging = ref(false);
const axis = computed(() => props.vertical === true ? "--v" : "--h");
const labelSide = computed(() => "-" + (props.switchLabelSide === true ? "switched" : "standard"));
const isReversed = computed(() => props.reverse === true);
const innerMin = computed(() => isNaN(props.innerMin) === true || props.innerMin < props.min ? props.min : props.innerMin);
const innerMax = computed(() => isNaN(props.innerMax) === true || props.innerMax > props.max ? props.max : props.innerMax);
const editable = computed(() => props.disable !== true && props.readonly !== true && innerMin.value < innerMax.value);
const decimals = computed(() => (String(props.step).trim().split(".")[1] || "").length);
const step = computed(() => props.step === 0 ? 1 : props.step);
const tabindex = computed(() => editable.value === true ? props.tabindex || 0 : -1);
const trackLen = computed(() => props.max - props.min);
const innerBarLen = computed(() => innerMax.value - innerMin.value);
const innerMinRatio = computed(() => convertModelToRatio(innerMin.value));
const innerMaxRatio = computed(() => convertModelToRatio(innerMax.value));
const positionProp = computed(
() => props.vertical === true ? isReversed.value === true ? "bottom" : "top" : isReversed.value === true ? "right" : "left"
);
const sizeProp = computed(() => props.vertical === true ? "height" : "width");
const thicknessProp = computed(() => props.vertical === true ? "width" : "height");
const orientation = computed(() => props.vertical === true ? "vertical" : "horizontal");
const attributes = computed(() => {
const acc = {
role: "slider",
"aria-valuemin": innerMin.value,
"aria-valuemax": innerMax.value,
"aria-orientation": orientation.value,
"data-step": props.step
};
if (props.disable === true) {
acc["aria-disabled"] = "true";
} else if (props.readonly === true) {
acc["aria-readonly"] = "true";
}
return acc;
});
const classes = computed(
() => `vc-slider vc-slider${axis.value} vc-slider--${active.value === true ? "" : "in"}active inline no-wrap ` + (props.vertical === true ? "row" : "column") + (props.disable === true ? " disabled" : " vc-slider--enabled" + (editable.value === true ? " vc-slider--editable" : "")) + (focus.value === "both" ? " vc-slider--focus" : "") + (props.label || props.labelAlways === true ? " vc-slider--label" : "") + (props.labelAlways === true ? " vc-slider--label-always" : "") + (isDark.value === true ? " vc-slider--dark" : "") + (props.dense === true ? " vc-slider--dense vc-slider--dense" + axis.value : "")
);
function getPositionClass(name) {
const cls = "vc-slider__" + name;
return `${cls} ${cls}${axis.value} ${cls}${axis.value}${labelSide.value}`;
}
function getAxisClass(name) {
const cls = "vc-slider__" + name;
return `${cls} ${cls}${axis.value}`;
}
const selectionBarClass = computed(() => {
const color = props.selectionColor || props.color;
return "vc-slider__selection absolute" + (color !== void 0 ? ` text-${color}` : "");
});
const markerClass = computed(() => getAxisClass("markers") + " absolute overflow-hidden");
const trackContainerClass = computed(() => getAxisClass("track-container"));
const pinClass = computed(() => getPositionClass("pin"));
const labelClass = computed(() => getPositionClass("label"));
const textContainerClass = computed(() => getPositionClass("text-container"));
const markerLabelsContainerClass = computed(
() => getPositionClass("marker-labels-container") + (props.markerLabelsClass !== void 0 ? ` ${props.markerLabelsClass}` : "")
);
const trackClass = computed(() => "vc-slider__track relative-position no-outline" + (props.trackColor !== void 0 ? ` bg-${props.trackColor}` : ""));
const trackStyle = computed(() => {
const acc = { [thicknessProp.value]: props.trackSize };
if (props.trackImg !== void 0) {
acc.backgroundImage = `url(${props.trackImg}) !important`;
}
return acc;
});
const innerBarClass = computed(() => "vc-slider__inner absolute" + (props.innerTrackColor !== void 0 ? ` bg-${props.innerTrackColor}` : ""));
const innerBarStyle = computed(() => {
const acc = {
[positionProp.value]: `${100 * innerMinRatio.value}%`,
[sizeProp.value]: `${100 * (innerMaxRatio.value - innerMinRatio.value)}%`
};
if (props.innerTrackImg !== void 0) {
acc.backgroundImage = `url(${props.innerTrackImg}) !important`;
}
return acc;
});
function convertRatioToModel(ratio) {
const { min, max, step: step2 } = props;
let model = min + ratio * (max - min);
if (step2 > 0) {
const modulo = (model - min) % step2;
model += (Math.abs(modulo) >= step2 / 2 ? (modulo < 0 ? -1 : 1) * step2 : 0) - modulo;
}
if (decimals.value > 0) {
model = parseFloat(model.toFixed(decimals.value));
}
return between(model, innerMin.value, innerMax.value);
}
function convertModelToRatio(model) {
return trackLen.value === 0 ? 0 : (model - props.min) / trackLen.value;
}
function getDraggingRatio(evt, dragging2) {
const pos = position(evt), val = props.vertical === true ? between((pos.top - dragging2.top) / dragging2.height, 0, 1) : between((pos.left - dragging2.left) / dragging2.width, 0, 1);
return between(isReversed.value === true ? 1 - val : val, innerMinRatio.value, innerMaxRatio.value);
}
const markerStep = computed(() => isNumber$1(props.markers) === true ? props.markers : step.value);
const markerTicks = computed(() => {
const acc = [];
const step2 = markerStep.value;
const max = props.max;
let value = props.min;
do {
acc.push(value);
value += step2;
} while (value < max);
acc.push(max);
return acc;
});
const markerLabelClass = computed(() => {
const prefix = ` ${markerPrefixClass}${axis.value}-`;
return markerPrefixClass + `${prefix}${props.switchMarkerLabelsSide === true ? "switched" : "standard"}${prefix}${isReversed.value === true ? "rtl" : "ltr"}`;
});
const markerLabelsList = computed(() => {
if (props.markerLabels === false) {
return null;
}
return getMarkerList(props.markerLabels).map((entry, index) => ({
index,
value: entry.value,
label: entry.label || entry.value,
classes: markerLabelClass.value + (entry.classes !== void 0 ? " " + entry.classes : ""),
style: {
...getMarkerLabelStyle(entry.value),
...entry.style || {}
}
}));
});
const markerScope = computed(() => ({
markerList: markerLabelsList.value,
markerMap: markerLabelsMap.value,
classes: markerLabelClass.value,
// TODO ts definition
getStyle: getMarkerLabelStyle
}));
const markerStyle = computed(() => {
if (innerBarLen.value !== 0) {
const size = 100 * markerStep.value / innerBarLen.value;
return {
...innerBarStyle.value,
backgroundSize: props.vertical === true ? `2px ${size}%` : `${size}% 2px`
};
}
return null;
});
function getMarkerList(def) {
if (def === false) {
return null;
}
if (def === true) {
return markerTicks.value.map(defaultMarkerConvertFn);
}
if (typeof def === "function") {
return markerTicks.value.map((value) => {
const item = def(value);
return isObject(item) === true ? { ...item, value } : { value, label: item };
});
}
const filterFn = ({ value }) => value >= props.min && value <= props.max;
if (Array.isArray(def) === true) {
return def.map((item) => isObject(item) === true ? item : { value: item }).filter(filterFn);
}
return Object.keys(def).map((key) => {
const item = def[key];
const value = Number(key);
return isObject(item) === true ? { ...item, value } : { value, label: item };
}).filter(filterFn);
}
function getMarkerLabelStyle(val) {
return { [positionProp.value]: `${100 * (val - props.min) / trackLen.value}%` };
}
const markerLabelsMap = computed(() => {
if (props.markerLabels === false) {
return null;
}
const acc = {};
markerLabelsList.value.forEach((entry) => {
acc[entry.value] = entry;
});
return acc;
});
function getMarkerLabelsContent() {
if (slots["marker-label-group"] !== void 0) {
return slots["marker-label-group"](markerScope.value);
}
const fn = slots["marker-label"] || defaultMarkerLabelRenderFn;
return markerLabelsList.value.map(
(marker) => fn({
marker,
...markerScope.value
})
);
}
const panDirective = computed(() => {
return [
[
TouchPan,
onPan,
void 0,
{
[orientation.value]: true,
prevent: true,
stop: true,
mouse: true,
mouseAllDir: true
}
]
];
});
function onPan(event) {
if (event.isFinal === true) {
if (dragging.value !== void 0) {
updatePosition(event.evt);
event.touch === true && updateValue(true);
dragging.value = void 0;
emit("pan", "end");
}
active.value = false;
focus.value = false;
} else if (event.isFirst === true) {
dragging.value = getDragging(event.evt);
updatePosition(event.evt);
updateValue();
active.value = true;
emit("pan", "start");
} else {
updatePosition(event.evt);
updateValue();
}
}
function onBlur() {
focus.value = false;
}
function onActivate(evt) {
updatePosition(evt, getDragging(evt));
updateValue();
preventFocus.value = true;
active.value = true;
document.addEventListener("mouseup", onDeactivate, true);
}
function onDeactivate() {
preventFocus.value = false;
active.value = false;
updateValue(true);
onBlur();
document.removeEventListener("mouseup", onDeactivate, true);
}
function onMobileClick(evt) {
updatePosition(evt, getDragging(evt));
updateValue(true);
}
function onKeyup(evt) {
if (keyCodes.includes(evt.keyCode)) {
updateValue(true);
}
}
function getTextContainerStyle(ratio) {
if (props.vertical === true) {
return null;
}
const p = ratio;
return {
transform: `translateX(calc(${2 * p - 1} * ${props.thumbSize} / 2 + ${50 - 100 * p}%))`
};
}
function getThumbRenderFn(thumb) {
const focusClass = computed(
() => preventFocus.value === false && (focus.value === thumb.focusValue || focus.value === "both") ? " vc-slider--focus" : ""
);
const classes2 = computed(
() => `vc-slider__thumb vc-slider__thumb${axis.value} vc-slider__thumb${axis.value}-${isReversed.value === true ? "rtl" : "ltr"} absolute non-selectable` + focusClass.value + (thumb.thumbColor.value !== void 0 ? ` text-${thumb.thumbColor.value}` : "")
);
const style = computed(() => ({
width: props.thumbSize,
height: props.thumbSize,
[positionProp.value]: `${100 * thumb.ratio.value}%`,
zIndex: focus.value === thumb.focusValue ? 2 : void 0
}));
const pinColor = computed(() => thumb.labelColor.value !== void 0 ? ` text-${thumb.labelColor.value}` : "");
const textContainerStyle = computed(() => getTextContainerStyle(thumb.ratio.value));
const textClass = computed(() => "vc-slider__text" + (thumb.labelTextColor.value !== void 0 ? ` text-${thumb.labelTextColor.value}` : ""));
return () => {
const thumbContent = [
h(
"svg",
{
class: "vc-slider__thumb-shape absolute-full",
viewBox: "0 0 20 20",
"aria-hidden": "true"
},
[h("path", { d: props.thumbPath })]
),
h("div", { class: "vc-slider__focus-ring fit" })
];
if (props.label === true || props.labelAlways === true) {
thumbContent.push(
h(
"div",
{
class: pinClass.value + " absolute fit no-pointer-events" + pinColor.value
},
[
h(
"div",
{
class: labelClass.value,
style: { minWidth: props.thumbSize }
},
[
h(
"div",
{
class: textContainerClass.value,
style: textContainerStyle.value
},
[h("span", { class: textClass.value }, thumb.label.value)]
)
]
)
]
)
);
if (props.name !== void 0 && props.disable !== true) {
injectFormInput(thumbContent, "push");
}
}
return h(
"div",
{
class: classes2.value,
style: style.value,
...thumb.getNodeData()
},
thumbContent
);
};
}
function getContent(selectionBarStyle, trackContainerTabindex, trackContainerEvents, injectThumb) {
const trackContent = [];
props.innerTrackColor !== "transparent" && trackContent.push(
h("div", {
key: "inner",
class: innerBarClass.value,
style: innerBarStyle.value
})
);
props.selectionColor !== "transparent" && trackContent.push(
h("div", {
key: "selection",
class: selectionBarClass.value,
style: selectionBarStyle.value
})
);
props.markers !== false && trackContent.push(
h("div", {
key: "marker",
class: markerClass.value,
style: markerStyle.value
})
);
injectThumb(trackContent);
const content = [
hDir(
"div",
{
key: "trackC",
class: trackContainerClass.value,
tabindex: trackContainerTabindex.value,
...trackContainerEvents.value
},
[
h(
"div",
{
class: trackClass.value,
style: trackStyle.value
},
trackContent
)
],
"slide",
editable.value,
() => panDirective.value
)
];
if (props.markerLabels !== false) {
const action = props.switchMarkerLabelsSide === true ? "unshift" : "push";
content[action](
h(
"div",
{
key: "markerL",
class: markerLabelsContainerClass.value
},
getMarkerLabelsContent()
)
);
}
return content;
}
onBeforeUnmount(() => {
document.removeEventListener("mouseup", onDeactivate, true);
});
return {
state: {
active,
focus,
preventFocus,
dragging,
editable,
classes,
tabindex,
attributes,
step,
decimals,
trackLen,
innerMin,
innerMinRatio,
innerMax,
innerMaxRatio,
positionProp,
sizeProp,
isReversed
},
methods: {
onActivate,
onMobileClick,
onBlur,
onKeyup,
getContent,
getThumbRenderFn,
convertRatioToModel,
convertModelToRatio,
getDraggingRatio
}
};
}
const getNodeData = () => ({});
const sliderProps = exports('sliderProps', {
...useSliderProps,
modelValue: {
required: true,
default: null,
validator: (v) => typeof v === "number" || v === null
},
labelValue: [String, Number]
});
var Slider = defineComponent({
name: "VcSlider",
props: sliderProps,
emits: useSliderEmits,
setup(props, { emit }) {
const { state, methods } = useSlider({
updateValue,
updatePosition,
getDragging,
formAttrs: useFormAttrs(props)
});
const rootRef = ref(null);
const curRatio = ref(0);
const model = ref(0);
function normalizeModel() {
model.value = props.modelValue === null ? state.innerMin.value : between(props.modelValue, state.innerMin.value, state.innerMax.value);
}
watch(() => `${props.modelValue}|${state.innerMin.value}|${state.innerMax.value}`, normalizeModel);
normalizeModel();
const modelRatio = computed(() => methods.convertModelToRatio(model.value));
const ratio = computed(() => state.active.value === true ? curRatio.value : modelRatio.value);
const selectionBarStyle = computed(() => {
const acc = {
[state.positionProp.value]: `${100 * state.innerMinRatio.value}%`,
[state.sizeProp.value]: `${100 * (ratio.value - state.innerMinRatio.value)}%`
};
if (props.selectionImg !== void 0) {
acc.backgroundImage = `url(${props.selectionImg}) !important`;
}
return acc;
});
const getThumb = methods.getThumbRenderFn({
focusValue: true,
getNodeData,
ratio,
label: computed(() => props.labelValue !== void 0 ? props.labelValue : model.value),
thumbColor: computed(() => props.thumbColor || props.color),
labelColor: computed(() => props.labelColor),
labelTextColor: computed(() => props.labelTextColor)
});
const trackContainerEvents = computed(() => {
if (state.editable.value !== true) {
return {};
}
return platform().isPhone === true ? { onClick: methods.onMobileClick } : {
onMousedown: methods.onActivate,
onFocus,
onBlur: methods.onBlur,
onKeydown,
onKeyup: methods.onKeyup
};
});
function updateValue(change) {
if (model.value !== props.modelValue) {
emit("update:modelValue", model.value);
}
change === true && emit("change", model.value);
}
function getDragging() {
return rootRef.value.getBoundingClientRect();
}
function updatePosition(event, dragging = state.dragging.value) {
const ratio2 = methods.getDraggingRatio(event, dragging);
model.value = methods.convertRatioToModel(ratio2);
curRatio.value = props.snap !== true || props.step === 0 ? ratio2 : methods.convertModelToRatio(model.value);
}
function onFocus() {
state.focus.value = true;
}
function onKeydown(evt) {
if (!keyCodes.includes(evt.keyCode)) {
return;
}
stopAndPrevent(evt);
const stepVal = ([34, 33].includes(evt.keyCode) ? 10 : 1) * state.step.value, offset = ([34, 37, 40].includes(evt.keyCode) ? -1 : 1) * (state.isReversed.value === true ? -1 : 1) * (props.vertical === true ? -1 : 1) * stepVal;
model.value = between(parseFloat((model.value + offset).toFixed(state.decimals.value)), state.innerMin.value, state.innerMax.value);
updateValue();
}
return () => {
const content = methods.getContent(selectionBarStyle, state.tabindex, trackContainerEvents, (node) => {
node.push(getThumb());
});
return h(
"div",
{
ref: rootRef,
class: state.classes.value + (props.modelValue === null ? " vc-slider--no-value" : ""),
...state.attributes.value,
"aria-valuenow": props.modelValue
},
content
);
};
}
});
const components$a = [
Btn,
Icon,
SpinnerBall,
SpinnerBars,
SpinnerDots,
SpinnerGears,
SpinnerHourglass,
SpinnerIos,
SpinnerOrbit,
SpinnerOval,
SpinnerPuff,
SpinnerRings,
SpinnerTail,
Spinner,
Tooltip,
AjaxBar,
Skeleton,
Fab,
FabAction,
Slider
];
components$a.forEach((cmp) => {
cmp["install"] = (app) => {
app.component(cmp.name, cmp);
};
});
const VcBtn = exports('VcBtn', Btn);
const VcIcon = exports('VcIcon', Icon);
const VcSpinnerBall = exports('VcSpinnerBall', SpinnerBall);
const VcSpinnerBars = exports('VcSpinnerBars', SpinnerBars);
const VcSpinnerDots = exports('VcSpinnerDots', SpinnerDots);
const VcSpinnerGears = exports('VcSpinnerGears', SpinnerGears);
const VcSpinnerHourglass = exports('VcSpinnerHourglass', SpinnerHourglass);
const VcSpinnerIos = exports('VcSpinnerIos', SpinnerIos);
const VcSpinnerOrbit = exports('VcSpinnerOrbit', SpinnerOrbit);
const VcSpinnerOval = exports('VcSpinnerOval', SpinnerOval);
const VcSpinnerPuff = exports('VcSpinnerPuff', SpinnerPuff);
const VcSpinnerRings = exports('VcSpinnerRings', SpinnerRings);
const VcSpinnerTail = exports('VcSpinnerTail', SpinnerTail);
const VcSpinner = exports('VcSpinner', Spinner);
const VcTooltip = exports('VcTooltip', Tooltip);
const VcAjaxBar = exports('VcAjaxBar', AjaxBar);
const VcSkeleton = exports('VcSkeleton', Skeleton);
const VcFab = exports('VcFab', Fab);
const VcFabAction = exports('VcFabAction', FabAction);
const VcSlider = exports('VcSlider', Slider);
const commonEmits = exports('commonEmits', {
beforeLoad: (instance) => true,
ready: (readyObj) => true,
unready: (e) => true,
destroyed: (instance) => true
});
const pickEventEmits = exports('pickEventEmits', {
mousedown: (evt) => true,
mouseup: (evt) => true,
click: (evt) => true,
clickout: (evt) => true,
dblclick: (evt) => true,
mousemove: (evt) => true,
mouseover: (evt) => true,
mouseout: (evt) => true
});
const graphicsEmits = exports('graphicsEmits', {
...commonEmits,
definitionChanged: (property) => true
});
const providerEmits = exports('providerEmits', {
...commonEmits,
errorEvent: (evt) => true,
readyPromise: (evt, viewer, instance) => true
});
const primitiveEmits = exports('primitiveEmits', {
...commonEmits,
...pickEventEmits,
readyPromise: (primitive, viewer, instance) => true,
"update:geometryInstances": (instances) => true
});
const primitiveCollectionEmits = exports('primitiveCollectionEmits', {
...commonEmits,
...pickEventEmits
});
const datasourceEmits = exports('datasourceEmits', {
...commonEmits,
...pickEventEmits,
definitionChanged: (property) => true,
clusterEvent: (entities, cluster) => true,
collectionChanged: (collection, addedArray, removedArray, changedArray) => true,
changedEvent: (datasource) => true,
errorEvent: (datasource, error) => true,
loadingEvent: (datasource, isLoading) => true,
refreshEvent: (datasource, url) => true,
unsupportedNodeEvent: (datasource, parentEntity, node, entityCollection, styleCollection, sourceResource, uriResolver) => true
});
const drawingEmit = exports('drawingEmit', {
...commonEmits,
activeEvt: (evt, viewer) => true,
drawEvt: (evt, viewer) => true,
editorEvt: (evt, viewer) => true,
mouseEvt: (evt, viewer) => true
});
const emits$n = {
...commonEmits,
cesiumReady: (payload) => true,
viewerWidgetResized: (payload) => true,
selectedEntityChanged: (entity) => true,
trackedEntityChanged: (entity) => true,
layerAdded: (imageryLayer, index) => true,
layerMoved: (imageryLayer, newIndex, oldIndex) => true,
layerRemoved: (imageryLayer, index) => true,
layerShownOrHidden: (imageryLayer, index, show) => true,
dataSourceAdded: (collection, dataSource) => true,
dataSourceMoved: (dataSource, newIndex, oldIndex) => true,
dataSourceRemoved: (collection, dataSource) => true,
collectionChanged: (collection, addedArray, removedArray, changedArray) => true,
morphComplete: (transitioner, preceneModeMode, sceneMode, wasMorphing) => true,
morphStart: (transitioner, preceneModeMode, sceneMode, wasMorphing) => true,
postRender: (scene, time) => true,
preRender: (scene, time) => true,
postUpdate: (scene, time) => true,
preUpdate: (scene, time) => true,
renderError: (scene, error) => true,
terrainProviderChanged: (provider) => true,
changed: (percent) => true,
moveEnd: () => true,
moveStart: () => true,
onStop: (clock) => true,
onTick: (clock) => true,
errorEvent: (tileProviderError) => true,
cameraClicked: (viewModel) => true,
closeClicked: (viewModel) => true,
leftClick: (mouseClickEvent) => true,
leftDoubleClick: (mouseClickEvent) => true,
leftDown: (mouseClickEvent) => true,
leftUp: (mouseClickEvent) => true,
middleClick: (mouseClickEvent) => true,
middleDown: (mouseClickEvent) => true,
middleUp: (mouseClickEvent) => true,
mouseMove: (mouseClickEvent) => true,
pinchStart: (touch2StartEvent) => true,
pinchMove: (touchPinchMovementEvent) => true,
pinchEnd: () => true,
rightClick: (mouseClickEvent) => true,
rightDown: (mouseClickEvent) => true,
rightUp: (mouseClickEvent) => true,
wheel: (delta) => true,
imageryLayersUpdatedEvent: () => true,
tileLoadProgressEvent: (length) => true,
touchEnd: (evt) => true
};
var Viewer = defineComponent({
name: "VcViewer",
props: viewerProps,
emits: emits$n,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumEvents = ["selectedEntityChanged", "trackedEntityChanged"];
instance.cesiumMembersEvents = viewerEvents;
const viewerStates = useViewer(props, ctx, instance);
const containerId = computed(() => {
return props.containerId || ctx.attrs.id || "cesiumContainer";
});
provide(vcKey, viewerStates.getServices());
instance.appContext.config.globalProperties.$VueCesium = instance.appContext.config.globalProperties.$VueCesium || {};
instance.appContext.config.globalProperties.$VueCesium[containerId.value] = viewerStates.getServices();
Object.assign(instance.proxy, {
creatingPromise: viewerStates.creatingPromise,
load: viewerStates.load,
unload: viewerStates.unload,
reload: viewerStates.reload,
cesiumObject: instance.cesiumObject,
getCesiumObject: () => instance.cesiumObject,
getInstance: () => instance
});
const onTouchHold = (e) => {
ctx.emit("touchEnd", e);
};
return () => {
var _a;
const children = [];
if (isPlainObject(props.skeleton) && !viewerStates.isReady.value) {
children.push(
h(VcSkeleton, {
...props.skeleton,
style: { background: props.skeleton.color, width: "100%", height: "100%" }
})
);
} else {
children.push(createCommentVNode("v-if"));
}
children.push(
createCommentVNode("vc-viewer"),
withDirectives(
h(
"div",
{
ref: viewerStates.viewerRef,
class: kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""),
id: containerId.value,
style: ctx.attrs.style || { width: "100%", height: "100%" }
},
hSlot(ctx.slots.default)
),
[[TouchHold, onTouchHold, props.touchHoldArg]]
)
);
return children;
};
}
});
Viewer.install = (app, opts) => {
app.component(Viewer.name, Viewer);
};
const _Viewer = Viewer;
const VcViewer = exports('VcViewer', _Viewer);
const positionProps = {
position: {
type: String,
default: "top-right",
validator: (v) => ["top-right", "top-left", "bottom-right", "bottom-left", "top", "right", "bottom", "left"].includes(v)
},
offset: {
type: Array,
validator: (v) => v.length === 2
}
};
function usePosition(props, $services) {
const attach = computed(() => {
const pos = props.position;
return {
top: pos.indexOf("top") > -1,
right: pos.indexOf("right") > -1,
bottom: pos.indexOf("bottom") > -1,
left: pos.indexOf("left") > -1,
vertical: pos === "top" || pos === "bottom",
horizontal: pos === "left" || pos === "right"
};
});
const top = ref(0);
const right = ref(0);
const left = ref(0);
const bottom = ref(0);
const style = computed(() => {
let posX = 0;
let posY = 0;
const side = attach.value;
const dir = 1;
if (side.top === true && top.value !== 0) {
posY = `${top.value}px`;
} else if (side.bottom === true && bottom.value !== 0) {
posY = `${-bottom.value}px`;
}
if (side.left === true && left.value !== 0) {
posX = `${dir * left.value}px`;
} else if (side.right === true && right.value !== 0) {
posX = `${-dir * right.value}px`;
}
const css = {
transform: `translate(${posX}, ${posY})`
};
if (props.offset) {
css.margin = `${props.offset[1]}px ${props.offset[0]}px`;
}
if (side.vertical === true) {
if (left.value !== 0) {
css["right"] = `${left.value}px`;
}
if (right.value !== 0) {
css["left"] = `${right.value}px`;
}
} else if (side.horizontal === true) {
if (top.value !== 0) {
css.top = `${top.value}px`;
}
if (bottom.value !== 0) {
css.bottom = `${bottom.value}px`;
}
}
return typeof props.teleportToViewer === "undefined" || props.teleportToViewer ? css : {};
});
const classes = computed(
() => typeof props.teleportToViewer === "undefined" || props.teleportToViewer ? `absolute absolute-${props.position}` : "relative-position"
);
return {
attach,
style,
classes
};
}
const defaultProps$4 = {
enableCompassOuterRing: {
type: Boolean,
default: true
},
duration: {
type: Number,
default: 1.5
},
...positionProps,
outerOptions: {
type: Object,
default: () => ({
icon: "vc-icons-compass-outer",
size: "96px",
color: "#3f4854",
background: "transparent",
tooltip: {
delay: 1e3,
anchor: "bottom middle",
offset: [0, 20],
tip: void 0
}
})
},
innerOptions: {
type: Object,
default: () => ({
icon: "vc-icons-compass-inner",
size: "24px",
color: "#3f4854",
background: "#fff",
tooltip: {
delay: 1e3,
anchor: "bottom middle",
offset: [0, 20],
tip: void 0
}
})
},
markerOptions: {
type: Object,
default: () => ({
icon: "vc-icons-compass-rotation-marker",
size: "96px",
color: "#1976D2"
})
},
customClass: {
type: String,
default: ""
},
teleportToViewer: {
type: Boolean,
default: true
}
};
const defaultOptions$6 = getDefaultOptionByProps(defaultProps$4);
class CameraFlightPath {
static createTween(scene, options) {
const { Cartesian2, Cartesian3, defaultValue, defined, DeveloperError, EasingFunction, Math: CesiumMath, SceneMode } = Cesium;
options = defaultValue(options, {});
let destination = options.destination;
if (!defined(scene)) {
throw new DeveloperError("scene is required.");
}
if (!defined(destination)) {
throw new DeveloperError("destination is required.");
}
const mode = scene.mode;
if (mode === SceneMode.MORPHING) {
return emptyFlight();
}
const convert = defaultValue(options.convert, true);
const projection = scene.mapProjection;
const ellipsoid = projection.ellipsoid;
const maximumHeight = options.maximumHeight;
const flyOverLongitude = options.flyOverLongitude;
const flyOverLongitudeWeight = options.flyOverLongitudeWeight;
const pitchAdjustHeight = options.pitchAdjustHeight;
let easingFunction = options.easingFunction;
if (convert && mode !== SceneMode.SCENE3D) {
ellipsoid.cartesianToCartographic(destination, scratchCartographic);
destination = projection.project(scratchCartographic, scratchDestination);
}
const camera = scene.camera;
const transform = options.endTransform;
if (defined(transform)) {
camera._setTransform(transform);
}
let duration = options.duration;
if (!defined(duration)) {
duration = Math.ceil(Cartesian3.distance(camera.position, destination) / 1e6) + 2;
duration = Math.min(duration, 3);
}
const heading = defaultValue(options.heading, 0);
const pitch = defaultValue(options.pitch, -CesiumMath.PI_OVER_TWO);
const roll = defaultValue(options.roll, 0);
const controller = scene.screenSpaceCameraController;
controller.enableInputs = false;
const complete = wrapCallback(controller, options.complete);
const cancel = wrapCallback(controller, options.cancel);
const frustum = camera.frustum;
let empty = scene.mode === SceneMode.SCENE2D;
empty = empty && Cartesian2.equalsEpsilon(camera.position, destination, CesiumMath.EPSILON6);
empty = empty && CesiumMath.equalsEpsilon(Math.max(frustum.right - frustum.left, frustum.top - frustum.bottom), destination.z, CesiumMath.EPSILON6);
empty = empty || scene.mode !== SceneMode.SCENE2D && Cartesian3.equalsEpsilon(destination, camera.position, CesiumMath.EPSILON10);
empty = empty && CesiumMath.equalsEpsilon(CesiumMath.negativePiToPi(heading), CesiumMath.negativePiToPi(camera.heading), CesiumMath.EPSILON10) && CesiumMath.equalsEpsilon(CesiumMath.negativePiToPi(pitch), CesiumMath.negativePiToPi(camera.pitch), CesiumMath.EPSILON10) && CesiumMath.equalsEpsilon(CesiumMath.negativePiToPi(roll), CesiumMath.negativePiToPi(camera.roll), CesiumMath.EPSILON10);
if (empty) {
return emptyFlight(complete, cancel);
}
const updateFunctions = new Array(4);
updateFunctions[SceneMode.SCENE2D] = createUpdate2D;
updateFunctions[SceneMode.SCENE3D] = createUpdate3D;
updateFunctions[SceneMode.COLUMBUS_VIEW] = createUpdateCV;
if (duration <= 0) {
const newOnComplete = function() {
const update2 = updateFunctions[mode](
scene,
1,
destination,
heading,
pitch,
roll,
maximumHeight,
flyOverLongitude,
flyOverLongitudeWeight,
pitchAdjustHeight
);
update2({ time: 1 });
if (typeof complete === "function") {
complete();
}
};
return emptyFlight(newOnComplete, cancel);
}
const update = updateFunctions[mode](
scene,
duration,
destination,
heading,
pitch,
roll,
maximumHeight,
flyOverLongitude,
flyOverLongitudeWeight,
pitchAdjustHeight
);
if (!defined(easingFunction)) {
const startHeight = camera.positionCartographic.height;
const endHeight = mode === SceneMode.SCENE3D ? ellipsoid.cartesianToCartographic(destination).height : destination.z;
if (startHeight > endHeight && startHeight > 11500) {
easingFunction = EasingFunction.CUBIC_OUT;
} else {
easingFunction = EasingFunction.QUINTIC_IN_OUT;
}
}
return {
duration,
easingFunction,
startObject: {
time: 0
},
stopObject: {
time: duration
},
update,
complete,
cancel
};
}
}
function getAltitude(frustum, dx, dy) {
const { PerspectiveFrustum, PerspectiveOffCenterFrustum } = Cesium;
let near;
let top;
let right;
if (frustum instanceof PerspectiveFrustum) {
const tanTheta = Math.tan(0.5 * frustum.fovy);
near = frustum.near;
top = frustum.near * tanTheta;
right = frustum.aspectRatio * top;
return Math.max(dx * near / right, dy * near / top);
} else if (frustum instanceof PerspectiveOffCenterFrustum) {
near = frustum.near;
top = frustum.top;
right = frustum.right;
return Math.max(dx * near / right, dy * near / top);
}
return Math.max(dx, dy);
}
const scratchCart = {};
const scratchCart2 = {};
function createPitchFunction(startPitch, endPitch, heightFunction, pitchAdjustHeight) {
const { defined, Math: CesiumMath } = Cesium;
if (defined(pitchAdjustHeight) && heightFunction(0.5) > pitchAdjustHeight) {
const startHeight = heightFunction(0);
const endHeight = heightFunction(1);
const middleHeight = heightFunction(0.5);
const d1 = middleHeight - startHeight;
const d2 = middleHeight - endHeight;
return function(time) {
const altitude = heightFunction(time);
if (time <= 0.5) {
const t1 = (altitude - startHeight) / d1;
return CesiumMath.lerp(startPitch, -CesiumMath.PI_OVER_TWO, t1);
}
const t2 = (altitude - endHeight) / d2;
return CesiumMath.lerp(-CesiumMath.PI_OVER_TWO, endPitch, 1 - t2);
};
}
return function(time) {
return CesiumMath.lerp(startPitch, endPitch, time);
};
}
function createHeightFunction(camera, destination, startHeight, endHeight, optionAltitude) {
const { Cartesian3, defined, Math: CesiumMath } = Cesium;
let altitude = optionAltitude;
const maxHeight = Math.max(startHeight, endHeight);
if (!defined(altitude)) {
const start = camera.position;
const end = destination;
const up = camera.up;
const right = camera.right;
const frustum = camera.frustum;
const diff = Cartesian3.subtract(start, end, scratchCart);
const verticalDistance = Cartesian3.magnitude(Cartesian3.multiplyByScalar(up, Cartesian3.dot(diff, up), scratchCart2));
const horizontalDistance = Cartesian3.magnitude(Cartesian3.multiplyByScalar(right, Cartesian3.dot(diff, right), scratchCart2));
altitude = Math.min(getAltitude(frustum, verticalDistance, horizontalDistance) * 0.2, 1e9);
}
if (maxHeight < altitude) {
const power = 8;
const factor = 1e6;
const s = -Math.pow((altitude - startHeight) * factor, 1 / power);
const e = Math.pow((altitude - endHeight) * factor, 1 / power);
return function(t) {
const x = t * (e - s) + s;
return -Math.pow(x, power) / factor + altitude;
};
}
return function(t) {
return CesiumMath.lerp(startHeight, endHeight, t);
};
}
function adjustAngleForLERP(startAngle, endAngle) {
const { Math: CesiumMath } = Cesium;
if (CesiumMath.equalsEpsilon(startAngle, CesiumMath.TWO_PI, CesiumMath.EPSILON11)) {
startAngle = 0;
}
if (endAngle > startAngle + Math.PI) {
startAngle += CesiumMath.TWO_PI;
} else if (endAngle < startAngle - Math.PI) {
startAngle -= CesiumMath.TWO_PI;
}
return startAngle;
}
const scratchStart = {};
function createUpdateCV(scene, duration, destination, heading, pitch, roll, optionAltitude) {
const { Cartesian2, Cartesian3, Math: CesiumMath } = Cesium;
const camera = scene.camera;
const start = Cartesian3.clone(camera.position, scratchStart);
const startPitch = camera.pitch;
const startHeading = adjustAngleForLERP(camera.heading, heading);
const startRoll = adjustAngleForLERP(camera.roll, roll);
const heightFunction = createHeightFunction(camera, destination, start.z, destination.z, optionAltitude);
function update(value) {
const time = value.time / duration;
camera.setView({
orientation: {
heading: CesiumMath.lerp(startHeading, heading, time),
pitch: CesiumMath.lerp(startPitch, pitch, time),
roll: CesiumMath.lerp(startRoll, roll, time)
}
});
Cartesian2.lerp(start, destination, time, camera.position);
camera.position.z = heightFunction(time);
}
return update;
}
function useLongestFlight(startCart, destCart) {
const { Math: CesiumMath } = Cesium;
if (startCart.longitude < destCart.longitude) {
startCart.longitude += CesiumMath.TWO_PI;
} else {
destCart.longitude += CesiumMath.TWO_PI;
}
}
function useShortestFlight(startCart, destCart) {
const { Math: CesiumMath } = Cesium;
const diff = startCart.longitude - destCart.longitude;
if (diff < -CesiumMath.PI) {
startCart.longitude += CesiumMath.TWO_PI;
} else if (diff > CesiumMath.PI) {
destCart.longitude += CesiumMath.TWO_PI;
}
}
const scratchStartCart = {};
const scratchEndCart = {};
function createUpdate3D(scene, duration, destination, heading, pitch, roll, optionAltitude, optionFlyOverLongitude, optionFlyOverLongitudeWeight, optionPitchAdjustHeight) {
const { Cartesian3, Cartographic, defined, Math: CesiumMath } = Cesium;
const camera = scene.camera;
const projection = scene.mapProjection;
const ellipsoid = projection.ellipsoid;
const startCart = Cartographic.clone(camera.positionCartographic, scratchStartCart);
const startPitch = camera.pitch;
const startHeading = adjustAngleForLERP(camera.heading, heading);
const startRoll = adjustAngleForLERP(camera.roll, roll);
const destCart = ellipsoid.cartesianToCartographic(destination, scratchEndCart);
startCart.longitude = CesiumMath.zeroToTwoPi(startCart.longitude);
destCart.longitude = CesiumMath.zeroToTwoPi(destCart.longitude);
let useLongFlight = false;
if (defined(optionFlyOverLongitude)) {
const hitLon = CesiumMath.zeroToTwoPi(optionFlyOverLongitude);
const lonMin = Math.min(startCart.longitude, destCart.longitude);
const lonMax = Math.max(startCart.longitude, destCart.longitude);
const hitInside = hitLon >= lonMin && hitLon <= lonMax;
if (defined(optionFlyOverLongitudeWeight)) {
const din = Math.abs(startCart.longitude - destCart.longitude);
const dot = CesiumMath.TWO_PI - din;
const hitDistance = hitInside ? din : dot;
const offDistance = hitInside ? dot : din;
if (hitDistance < offDistance * optionFlyOverLongitudeWeight && !hitInside) {
useLongFlight = true;
}
} else if (!hitInside) {
useLongFlight = true;
}
}
if (useLongFlight) {
useLongestFlight(startCart, destCart);
} else {
useShortestFlight(startCart, destCart);
}
const heightFunction = createHeightFunction(camera, destination, startCart.height, destCart.height, optionAltitude);
const pitchFunction = createPitchFunction(startPitch, pitch, heightFunction, optionPitchAdjustHeight);
function isolateUpdateFunction() {
const startLongitude = startCart.longitude;
const destLongitude = destCart.longitude;
const startLatitude = startCart.latitude;
const destLatitude = destCart.latitude;
return function update(value) {
const time = value.time / duration;
const position = Cartesian3.fromRadians(
CesiumMath.lerp(startLongitude, destLongitude, time),
CesiumMath.lerp(startLatitude, destLatitude, time),
heightFunction(time),
scene.globe.ellipsoid
);
camera.setView({
destination: position,
orientation: {
heading: CesiumMath.lerp(startHeading, heading, time),
pitch: pitchFunction(time),
roll: CesiumMath.lerp(startRoll, roll, time)
}
});
};
}
return isolateUpdateFunction();
}
function createUpdate2D(scene, duration, destination, heading, pitch, roll, optionAltitude) {
const { Cartesian2, Cartesian3, Math: CesiumMath } = Cesium;
const camera = scene.camera;
const start = Cartesian3.clone(camera.position, scratchStart);
const startHeading = adjustAngleForLERP(camera.heading, heading);
const startHeight = camera.frustum.right - camera.frustum.left;
const heightFunction = createHeightFunction(camera, destination, startHeight, destination.z, optionAltitude);
function update(value) {
const time = value.time / duration;
camera.setView({
orientation: {
heading: CesiumMath.lerp(startHeading, heading, time)
}
});
Cartesian2.lerp(start, destination, time, camera.position);
const zoom = heightFunction(time);
const frustum = camera.frustum;
const ratio = frustum.top / frustum.right;
const incrementAmount = (zoom - (frustum.right - frustum.left)) * 0.5;
frustum.right += incrementAmount;
frustum.left -= incrementAmount;
frustum.top = ratio * frustum.right;
frustum.bottom = -frustum.top;
}
return update;
}
const scratchCartographic = {};
const scratchDestination = {};
function emptyFlight(complete, cancel) {
return {
startObject: {},
stopObject: {},
duration: 0,
complete,
cancel
};
}
function wrapCallback(controller, cb) {
function wrapped() {
if (typeof cb === "function") {
cb();
}
controller.enableInputs = true;
}
return wrapped;
}
function useCompass$1(props, { emit }, vcInstance) {
const vectorScratch = {};
const oldTransformScratch = {};
const newTransformScratch = {};
const centerScratch = {};
let unsubscribeFromPostRender;
let unsubscribeFromClockTick;
let orbitMouseMoveFunction;
let orbitMouseUpFunction;
let orbitTickFunction;
const heading = ref(0);
const orbitCursorAngle = ref(0);
const orbitCursorOpacity = ref(0);
let orbitLastTimestamp = 0;
let orbitFrame = {};
let orbitIsLook = false;
let rotateMouseUpFunction;
let rotateMouseMoveFunction;
let rotateInitialCursorAngle = 0;
let rotateFrame = {};
let rotateInitialCameraAngle = 0;
const iconOuterTooltipRef = ref(null);
const iconInnerTooltipRef = ref(null);
const handleMouseDown = (e) => {
var _a, _b;
if (e.stopPropagation)
e.stopPropagation();
if (e.preventDefault)
e.preventDefault();
(_a = $(iconOuterTooltipRef)) == null ? void 0 : _a.hide();
(_b = $(iconInnerTooltipRef)) == null ? void 0 : _b.hide();
const { SceneMode, Cartesian2 } = Cesium;
const scene = vcInstance.viewer.scene;
if (scene.mode === SceneMode.MORPHING) {
return true;
}
const compassElement = e.currentTarget;
const compassRectangle = compassElement.getBoundingClientRect();
const maxDistance = compassRectangle.width / 2;
const center = new Cartesian2((compassRectangle.right - compassRectangle.left) / 2, (compassRectangle.bottom - compassRectangle.top) / 2);
let clickLocation;
if (e instanceof MouseEvent) {
clickLocation = new Cartesian2(e.clientX - compassRectangle.left, e.clientY - compassRectangle.top);
} else if (e instanceof TouchEvent) {
clickLocation = new Cartesian2(e.changedTouches[0].clientX - compassRectangle.left, e.changedTouches[0].clientY - compassRectangle.top);
}
const vector = Cartesian2.subtract(clickLocation, center, vectorScratch);
const distanceFromCenter = Cartesian2.magnitude(vector);
const distanceFraction = distanceFromCenter / maxDistance;
const nominalTotalRadius = 145;
const norminalGyroRadius = 50;
if (distanceFraction < norminalGyroRadius / nominalTotalRadius) {
orbit(compassElement, vector);
} else if (distanceFraction < 1) {
rotate(compassElement, vector);
} else {
return true;
}
};
const handleDoubleClick = (e) => {
const { Cartesian2, Cartesian3, defined, Ellipsoid, Matrix4, Ray, SceneMode, Transforms } = Cesium;
const { viewer } = vcInstance;
const scene = viewer.scene;
const camera = scene.camera;
const sscc = scene.screenSpaceCameraController;
if (scene.mode === SceneMode.MORPHING || !sscc.enableInputs) {
return true;
}
if (scene.mode === SceneMode.COLUMBUS_VIEW && !sscc.enableTranslate) {
return;
}
if (scene.mode === SceneMode.SCENE3D || scene.mode === SceneMode.COLUMBUS_VIEW) {
if (!sscc.enableLook) {
return;
}
if (scene.mode === SceneMode.SCENE3D) {
if (!sscc.enableRotate) {
return;
}
}
}
const windowPosition = new Cartesian2();
windowPosition.x = scene.canvas.clientWidth / 2;
windowPosition.y = scene.canvas.clientHeight / 2;
const pickRayScratch = new Ray();
const ray = camera.getPickRay(windowPosition, pickRayScratch);
const center = scene.globe.pick(ray, scene, centerScratch);
if (!isObject(center) || !defined(center)) {
viewer.camera.flyHome();
return;
}
const listener = getInstanceListener(vcInstance, "compassEvt");
listener && emit("compassEvt", {
type: "reset",
camera: viewer.camera,
status: "start",
target: e.currentTarget
});
const rotateFrame2 = Transforms.eastNorthUpToFixedFrame(center, viewer.scene.globe.ellipsoid);
const lookVector = Cartesian3.subtract(center, camera.position, new Cartesian3());
const flight = CameraFlightPath.createTween(scene, {
destination: Matrix4.multiplyByPoint(rotateFrame2, new Cartesian3(0, 0, Cartesian3.magnitude(lookVector)), new Cartesian3()),
direction: Matrix4.multiplyByPointAsVector(rotateFrame2, new Cartesian3(0, 0, -1), new Cartesian3()),
up: Matrix4.multiplyByPointAsVector(rotateFrame2, new Cartesian3(0, 1, 0), new Cartesian3()),
duration: props.duration,
complete: () => {
listener && emit("compassEvt", {
type: "reset",
camera: viewer.camera,
status: "end",
target: e.currentTarget
});
},
cancel: () => {
listener && emit("compassEvt", {
type: "reset",
camera: viewer.camera,
status: "cancel",
target: e.currentTarget
});
}
});
scene.tweens.add(flight);
};
const resetRotater = () => {
orbitCursorOpacity.value = 0;
orbitCursorAngle.value = 0;
};
const viewerChange = () => {
const { defined } = Cesium;
if (defined(vcInstance.viewer)) {
if (unsubscribeFromPostRender) {
unsubscribeFromPostRender();
unsubscribeFromPostRender = void 0;
}
unsubscribeFromPostRender = vcInstance.viewer.scene.postRender.addEventListener(function() {
if (heading.value !== vcInstance.viewer.scene.camera.heading) {
heading.value = vcInstance.viewer.scene.camera.heading;
}
});
} else {
if (unsubscribeFromPostRender) {
unsubscribeFromPostRender();
unsubscribeFromPostRender = void 0;
}
}
};
const orbit = (compassElement, cursorVector) => {
const { Cartesian2, Cartesian3, defined, getTimestamp, Math: CesiumMath, Matrix4, Ray, SceneMode, Transforms } = Cesium;
let scene = vcInstance.viewer.scene;
let camera = scene.camera;
const sscc = scene.screenSpaceCameraController;
if (scene.mode === SceneMode.MORPHING || !sscc.enableInputs) {
return;
}
switch (scene.mode) {
case SceneMode.COLUMBUS_VIEW:
if (sscc.enableLook) {
break;
}
if (!sscc.enableTranslate || !sscc.enableTilt) {
return;
}
break;
case SceneMode.SCENE3D:
if (sscc.enableLook) {
break;
}
if (!sscc.enableTilt || !sscc.enableRotate) {
return;
}
break;
case Cesium.SceneMode.SCENE2D:
if (!sscc.enableTranslate) {
return;
}
break;
}
const listener = getInstanceListener(vcInstance, "compassEvt");
listener && emit("compassEvt", {
type: "orbit",
camera: scene.camera,
status: "start",
target: compassElement
});
document.removeEventListener("mousemove", orbitMouseMoveFunction, false);
document.removeEventListener("mouseup", orbitMouseUpFunction, false);
document.removeEventListener("touchmove", orbitMouseMoveFunction, false);
document.removeEventListener("touchend", orbitMouseUpFunction, false);
if (defined(orbitTickFunction)) {
vcInstance.viewer.clock.onTick.removeEventListener(orbitTickFunction);
}
orbitMouseMoveFunction = void 0;
orbitMouseUpFunction = void 0;
orbitTickFunction = void 0;
orbitLastTimestamp = getTimestamp();
const windowPosition = new Cartesian2();
windowPosition.x = scene.canvas.clientWidth / 2;
windowPosition.y = scene.canvas.clientHeight / 2;
const pickRayScratch = new Ray();
const ray = camera.getPickRay(windowPosition, pickRayScratch);
const center = scene.globe.pick(ray, scene, centerScratch);
if (!defined(center)) {
orbitFrame = Transforms.eastNorthUpToFixedFrame(camera.positionWC, scene.globe.ellipsoid, newTransformScratch);
orbitIsLook = true;
} else {
orbitFrame = Transforms.eastNorthUpToFixedFrame(center || new Cesium.Cartesian3(), scene.globe.ellipsoid, newTransformScratch);
orbitIsLook = false;
}
orbitTickFunction = function(e) {
const timestamp = getTimestamp();
const deltaT = timestamp - orbitLastTimestamp;
const rate = (orbitCursorOpacity.value - 0.5) * 2.5 / 1e3;
const distance = deltaT * rate;
const angle = orbitCursorAngle.value + CesiumMath.PI_OVER_TWO;
const x = Math.cos(angle) * distance;
const y = Math.sin(angle) * distance;
scene = vcInstance.viewer.scene;
camera = scene.camera;
const oldTransform = Matrix4.clone(camera.transform, oldTransformScratch);
camera.lookAtTransform(orbitFrame);
if (orbitIsLook) {
camera.look(Cartesian3.UNIT_Z, -x);
camera.look(camera.right, -y);
} else {
camera.rotateLeft(x);
camera.rotateUp(y);
}
camera.lookAtTransform(oldTransform);
orbitLastTimestamp = timestamp;
};
function updateAngleAndOpacity(vector, compassWidth) {
const angle = Math.atan2(-vector.y, vector.x);
orbitCursorAngle.value = CesiumMath.zeroToTwoPi(angle - CesiumMath.PI_OVER_TWO);
const distance = Cartesian2.magnitude(vector);
const maxDistance = compassWidth / 2;
const distanceFraction = Math.min(distance / maxDistance, 1);
const easedOpacity = 0.5 * distanceFraction * distanceFraction + 0.5;
orbitCursorOpacity.value = easedOpacity;
}
orbitMouseMoveFunction = function(e) {
const compassRectangle = compassElement.getBoundingClientRect();
const center2 = new Cartesian2((compassRectangle.right - compassRectangle.left) / 2, (compassRectangle.bottom - compassRectangle.top) / 2);
let clickLocation;
if (e instanceof MouseEvent) {
clickLocation = new Cartesian2(e.clientX - compassRectangle.left, e.clientY - compassRectangle.top);
} else if (e instanceof TouchEvent) {
clickLocation = new Cartesian2(e.changedTouches[0].clientX - compassRectangle.left, e.changedTouches[0].clientY - compassRectangle.top);
}
const vector = Cartesian2.subtract(clickLocation, center2, vectorScratch);
updateAngleAndOpacity(vector, compassRectangle.width);
listener && emit("compassEvt", {
type: "orbit",
camera: scene.camera,
status: "changing",
target: compassElement
});
};
orbitMouseUpFunction = function(e) {
document.removeEventListener("mousemove", orbitMouseMoveFunction, false);
document.removeEventListener("mouseup", orbitMouseUpFunction, false);
document.removeEventListener("touchmove", orbitMouseMoveFunction, false);
document.removeEventListener("touchend", orbitMouseUpFunction, false);
if (defined(orbitTickFunction)) {
vcInstance.viewer.clock.onTick.removeEventListener(orbitTickFunction);
}
orbitMouseMoveFunction = void 0;
orbitMouseUpFunction = void 0;
orbitTickFunction = void 0;
resetRotater();
listener && emit("compassEvt", {
type: "orbit",
camera: scene.camera,
status: "end",
target: compassElement
});
};
document.addEventListener("mousemove", orbitMouseMoveFunction, false);
document.addEventListener("mouseup", orbitMouseUpFunction, false);
document.addEventListener("touchmove", orbitMouseMoveFunction, false);
document.addEventListener("touchend", orbitMouseUpFunction, false);
unsubscribeFromClockTick = vcInstance.viewer.clock.onTick.addEventListener(orbitTickFunction);
updateAngleAndOpacity(cursorVector, compassElement.getBoundingClientRect().width);
};
const rotate = (compassElement, cursorVector) => {
if (!props.enableCompassOuterRing) {
return;
}
const scene = vcInstance.viewer.scene;
let camera = scene.camera;
const sscc = scene.screenSpaceCameraController;
if (scene.mode === Cesium.SceneMode.MORPHING || scene.mode === Cesium.SceneMode.SCENE2D || !sscc.enableInputs) {
return;
}
if (!sscc.enableLook && (scene.mode === Cesium.SceneMode.COLUMBUS_VIEW || scene.mode === Cesium.SceneMode.SCENE3D && !sscc.enableRotate)) {
return;
}
document.removeEventListener("mousemove", rotateMouseMoveFunction, false);
document.removeEventListener("touchmove", rotateMouseMoveFunction, false);
document.removeEventListener("mouseup", rotateMouseUpFunction, false);
document.removeEventListener("touchend", rotateMouseUpFunction, false);
const { Cartesian2, Cartesian3, defined, Math: CesiumMath, Matrix4, Ray, Transforms } = Cesium;
rotateMouseMoveFunction = void 0;
rotateMouseUpFunction = void 0;
const listener = getInstanceListener(vcInstance, "compassEvt");
listener && emit("compassEvt", {
type: "rotate",
camera: scene.camera,
status: "start",
target: compassElement
});
rotateInitialCursorAngle = Math.atan2(-cursorVector.y, cursorVector.x);
const windowPosition = new Cartesian2();
windowPosition.x = scene.canvas.clientWidth / 2;
windowPosition.y = scene.canvas.clientHeight / 2;
const pickRayScratch = new Ray();
const ray = camera.getPickRay(windowPosition, pickRayScratch);
const viewCenter = scene.globe.pick(ray, scene, centerScratch);
if (!defined(viewCenter)) {
rotateFrame = Transforms.eastNorthUpToFixedFrame(camera.positionWC, scene.globe.ellipsoid, newTransformScratch);
} else {
rotateFrame = Transforms.eastNorthUpToFixedFrame(viewCenter || new Cartesian3(), scene.globe.ellipsoid, newTransformScratch);
}
let oldTransform = Matrix4.clone(camera.transform, oldTransformScratch);
camera.lookAtTransform(rotateFrame);
rotateInitialCameraAngle = Math.atan2(camera.position.y, camera.position.x);
Cartesian3.magnitude(new Cartesian3(camera.position.x, camera.position.y, 0));
camera.lookAtTransform(oldTransform);
rotateMouseMoveFunction = function(e) {
const compassRectangle = compassElement.getBoundingClientRect();
const center = new Cartesian2((compassRectangle.right - compassRectangle.left) / 2, (compassRectangle.bottom - compassRectangle.top) / 2);
let clickLocation;
if (e instanceof MouseEvent) {
clickLocation = new Cartesian2(e.clientX - compassRectangle.left, e.clientY - compassRectangle.top);
} else if (e instanceof TouchEvent) {
clickLocation = new Cartesian2(e.changedTouches[0].clientX - compassRectangle.left, e.changedTouches[0].clientY - compassRectangle.top);
}
const vector = Cartesian2.subtract(clickLocation, center, vectorScratch);
const angle = Math.atan2(-vector.y, vector.x);
const angleDifference = angle - rotateInitialCursorAngle;
const newCameraAngle = CesiumMath.zeroToTwoPi(rotateInitialCameraAngle - angleDifference);
camera = vcInstance.viewer.scene.camera;
oldTransform = Matrix4.clone(camera.transform, oldTransformScratch);
camera.lookAtTransform(rotateFrame);
const currentCameraAngle = Math.atan2(camera.position.y, camera.position.x);
camera.rotateRight(newCameraAngle - currentCameraAngle);
camera.lookAtTransform(oldTransform);
listener && emit("compassEvt", {
type: "rotate",
camera: scene.camera,
status: "changing",
target: compassElement
});
};
rotateMouseUpFunction = function(e) {
document.removeEventListener("mousemove", rotateMouseMoveFunction, false);
document.removeEventListener("touchmove", rotateMouseMoveFunction, false);
document.removeEventListener("mouseup", rotateMouseUpFunction, false);
document.removeEventListener("touchend", rotateMouseUpFunction, false);
rotateMouseMoveFunction = void 0;
rotateMouseUpFunction = void 0;
listener && emit("compassEvt", {
type: "rotate",
camera: scene.camera,
status: "end",
target: compassElement
});
};
document.addEventListener("mousemove", rotateMouseMoveFunction, false);
document.addEventListener("touchmove", rotateMouseMoveFunction, false);
document.addEventListener("mouseup", rotateMouseUpFunction, false);
document.addEventListener("touchend", rotateMouseUpFunction, false);
};
const onTooltipBeforeShow = (e) => {
if (rotateMouseMoveFunction !== void 0 || orbitMouseMoveFunction !== void 0) {
e.cancel = true;
}
};
const load = async (viewer) => {
vcInstance.viewer = viewer;
viewerChange();
return true;
};
const unload = async () => {
document.removeEventListener("mousemove", orbitMouseMoveFunction, false);
document.removeEventListener("mouseup", orbitMouseUpFunction, false);
document.removeEventListener("touchmove", orbitMouseMoveFunction, false);
document.removeEventListener("touchend", orbitMouseUpFunction, false);
unsubscribeFromClockTick && unsubscribeFromClockTick();
unsubscribeFromPostRender && unsubscribeFromPostRender();
return true;
};
return {
heading,
orbitCursorAngle,
orbitCursorOpacity,
handleDoubleClick,
handleMouseDown,
resetRotater,
onTooltipBeforeShow,
viewerChange,
load,
unload,
iconOuterTooltipRef,
iconInnerTooltipRef
};
}
const emits$m = {
...commonEmits,
compassEvt: (evt) => true
};
const compassProps = exports('compassProps', defaultProps$4);
var Compass = defineComponent({
name: "VcCompass",
props: compassProps,
emits: emits$m,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "VcCompass";
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { t } = useLocale();
const parentInstance = getVcParentInstance(instance);
const { $services } = commonState;
const compassState = useCompass$1(props, ctx, instance);
const positionState = usePosition(props);
const rootRef = ref(null);
const outerRingRef = ref(null);
const hasVcNavigation = ((_a = parentInstance.proxy) == null ? void 0 : _a.$options.name) === "VcNavigation";
const canRender = ref(hasVcNavigation);
const rootStyle = reactive({});
watch(
() => props,
(val) => {
nextTick(() => {
if (!instance.mounted) {
return;
}
updateRootStyle();
});
},
{
deep: true
}
);
const innerOptions = computed(() => {
return Object.assign({}, defaultOptions$6.innerOptions, props.innerOptions);
});
const outerOptions = computed(() => {
return Object.assign({}, defaultOptions$6.outerOptions, props.outerOptions);
});
const markerOptions = computed(() => {
return Object.assign({}, defaultOptions$6.markerOptions, props.markerOptions);
});
const outerCircleStyle = computed(() => {
return {
transform: "translate(-50%,-50%) rotate(-" + compassState.heading.value + "rad)",
WebkitTransform: "translate(-50%,-50%) rotate(-" + compassState.heading.value + "rad)",
// transform: 'rotate(-' + heading.value + 'rad)',
// WebkitTransform: 'rotate(-' + heading.value + 'rad)',
opacity: void 0,
background: outerOptions.value.background,
color: outerOptions.value.color
};
});
const rotationMarkerStyle = computed(() => {
return {
transform: "rotate(-" + compassState.orbitCursorAngle.value + "rad)",
WebkitTransform: "rotate(-" + compassState.orbitCursorAngle.value + "rad)",
opacity: compassState.orbitCursorOpacity.value,
color: markerOptions.value.color
};
});
const innerRingStyle = computed(() => {
const css = {
background: innerOptions.value.background,
color: innerOptions.value.color
};
return css;
});
instance.createCesiumObject = async () => {
return rootRef;
};
instance.mount = async () => {
var _a2;
canRender.value = true;
nextTick(() => {
updateRootStyle();
});
const { viewer } = $services;
(_a2 = viewer.viewerWidgetResized) == null ? void 0 : _a2.raiseEvent({
type: instance.cesiumClass,
status: "mounted",
target: $(rootRef)
});
return compassState.load($services.viewer);
};
instance.unmount = async () => {
var _a2;
canRender.value = false;
const { viewer } = $services;
(_a2 = viewer.viewerWidgetResized) == null ? void 0 : _a2.raiseEvent({
type: instance.cesiumClass,
status: "unmounted",
target: $(rootRef)
});
return compassState.unload();
};
const updateRootStyle = () => {
var _a2;
const css = positionState.style.value;
const outerRingTarget = (_a2 = $(outerRingRef)) == null ? void 0 : _a2.$el;
if (outerRingTarget !== void 0) {
const clientRect = outerRingTarget.getBoundingClientRect();
css.width = `${clientRect.width}px`;
css.height = `${clientRect.height}px`;
}
if (typeof props.teleportToViewer === "undefined" || props.teleportToViewer) {
rootStyle.left = css.left;
rootStyle.top = css.top;
rootStyle.transform = css.transform;
const side = positionState.attach.value;
if (outerRingTarget !== void 0) {
if ((side.bottom || side.top) && !side.left && !side.right) {
css.left = "50%";
css.transform = "translate(-50%, 0)";
}
if ((side.left || side.right) && !side.top && !side.bottom) {
css.top = "50%";
css.transform = "translate(0, -50%)";
}
}
}
Object.assign(rootStyle, css);
};
return () => {
if (canRender.value) {
let children = [];
children = hMergeSlot(ctx.slots.default, children);
children.push(
h(
VcBtn,
{
ref: outerRingRef,
class: "vc-compass-outerRing absolute-center",
style: outerCircleStyle.value,
size: outerOptions.value.size,
dense: true,
round: true,
disabled: !props.enableCompassOuterRing
},
() => [
h(VcIcon, {
size: outerOptions.value.size,
name: outerOptions.value.icon
}),
outerOptions.value.tooltip ? h(
VcTooltip,
{
ref: compassState.iconOuterTooltipRef,
...outerOptions.value.tooltip,
onBeforeShow: compassState.onTooltipBeforeShow
},
() => h("strong", {}, outerOptions.value.tooltip.tip || t("vc.navigation.compass.outerTip"))
) : createCommentVNode("v-if")
]
)
);
children.push(
h(
VcBtn,
{
class: "vc-compass-innerRing absolute-center",
style: innerRingStyle.value,
size: innerOptions.value.size,
dense: true,
round: true
},
() => [
h(VcIcon, {
size: innerOptions.value.size,
name: innerOptions.value.icon
}),
innerOptions.value.tooltip ? h(
VcTooltip,
{
ref: compassState.iconInnerTooltipRef,
...innerOptions.value.tooltip,
onBeforeShow: compassState.onTooltipBeforeShow
},
() => h("strong", {}, innerOptions.value.tooltip.tip || t("vc.navigation.compass.innerTip"))
) : createCommentVNode("v-if")
]
)
);
children.push(
rotationMarkerStyle.value.opacity ? h(
VcBtn,
{
class: "vc-compass-rotation-marker absolute-center",
dense: true,
round: true
},
() => [
h(VcIcon, {
size: markerOptions.value.size,
name: markerOptions.value.icon,
style: rotationMarkerStyle.value
})
]
) : createCommentVNode("v-if")
);
const renderContent = h(
"div",
{
ref: rootRef,
class: `vc-compass ${positionState.classes.value} ${props.customClass}`,
style: rootStyle,
onDblclick: compassState.handleDoubleClick,
onMousedown: compassState.handleMouseDown,
onMouseup: compassState.resetRotater,
onTouchend: compassState.resetRotater,
onTouchstart: compassState.handleMouseDown
},
children
);
return !hasVcNavigation && props.teleportToViewer ? h(Teleport, { to: $services.viewer._element }, renderContent) : renderContent;
} else {
return createCommentVNode("v-if");
}
};
}
});
const defaultProps$3 = {
enableResetButton: {
type: Boolean,
default: true
},
zoomAmount: {
type: Number,
default: 2
},
duration: {
type: Number,
default: 0.5
},
durationReset: {
type: Number
},
defaultResetView: {
type: Object,
default: () => {
return {
position: {
lng: 105,
lat: 30,
height: 190595685e-1
}
};
}
},
overrideViewerCamera: {
type: Boolean,
default: false
},
...positionProps,
background: {
type: String,
default: "#3f4854"
},
border: {
type: String,
default: "solid 1px rgba(255, 255, 255, 0.2)"
},
borderRadius: {
type: String,
default: "100px"
},
direction: {
type: String,
default: "vertical",
validator: (v) => ["vertical", "horizontal"].includes(v)
},
zoomInOptions: {
type: Object,
default: () => ({
icon: "vc-icons-zoom-in",
size: "24px",
color: "#fff",
background: "transparent",
round: true,
flat: true,
label: void 0,
stack: false,
tooltip: {
delay: 500,
anchor: "bottom middle",
offset: [0, 20],
tip: void 0
}
})
},
zoomOutOptions: {
type: Object,
default: () => ({
icon: "vc-icons-zoom-out",
size: "24px",
color: "#fff",
background: "transparent",
round: true,
flat: true,
label: void 0,
stack: false,
tooltip: {
delay: 500,
anchor: "bottom middle",
offset: [0, 20],
tip: void 0
}
})
},
zoomResetOptions: {
type: Object,
default: () => ({
icon: "vc-icons-reset",
size: "24px",
color: "#fff",
background: "transparent",
round: true,
flat: true,
label: void 0,
stack: false,
tooltip: {
delay: 500,
anchor: "bottom middle",
offset: [0, 20],
tip: void 0
}
})
},
customClass: {
type: String,
default: ""
},
teleportToViewer: {
type: Boolean,
default: true
}
};
const defaultOptions$5 = getDefaultOptionByProps(defaultProps$3);
function useZoomControl$1(props, { emit }, vcInstance, $services) {
const zoomInTooltipRef = ref(null);
const zoomOutTooltipRef = ref(null);
const resetTooltipRef = ref(null);
const zoomIn = (e) => {
zoom(1 / props.zoomAmount, e);
};
const zoomOut = (e) => {
zoom(props.zoomAmount, e);
};
const zoom = (relativeAmount, e) => {
var _a, _b;
(_a = $(zoomInTooltipRef)) == null ? void 0 : _a.hide();
(_b = $(zoomOutTooltipRef)) == null ? void 0 : _b.hide();
const { Cartesian3, defined, IntersectionTests, Ray, SceneMode } = Cesium;
const { viewer } = $services;
if (defined(viewer)) {
const scene = viewer.scene;
const sscc = scene.screenSpaceCameraController;
if (!sscc.enableInputs || !sscc.enableZoom) {
return;
}
if (scene.mode === SceneMode.COLUMBUS_VIEW && !sscc.enableTranslate) {
return;
}
const camera = scene.camera;
let orientation;
switch (scene.mode) {
case SceneMode.MORPHING: {
break;
}
case SceneMode.SCENE2D: {
camera.zoomIn(camera.positionCartographic.height * (1 - relativeAmount));
break;
}
default: {
let focus;
if (defined(viewer.trackedEntity)) {
focus = new Cesium.Cartesian3();
} else {
focus = getCameraFocus(viewer.scene);
}
if (!Cesium.defined(focus)) {
const ray = new Ray(
camera.worldToCameraCoordinatesPoint(scene.globe.ellipsoid.cartographicToCartesian(camera.positionCartographic)),
camera.directionWC
);
focus = IntersectionTests.grazingAltitudeLocation(ray, scene.globe.ellipsoid);
orientation = {
heading: camera.heading,
pitch: camera.pitch,
roll: camera.roll
};
} else {
orientation = {
direction: camera.direction,
up: camera.up
};
}
const cartesian3Scratch = new Cartesian3();
const direction = Cartesian3.subtract(camera.position, focus, cartesian3Scratch);
const movementVector = Cartesian3.multiplyByScalar(direction, relativeAmount, direction);
const endPosition = Cartesian3.add(focus, movementVector, focus);
const type = relativeAmount < 1 ? "zoomIn" : "zoomOut";
const target = e.currentTarget;
const level = heightToLevel(camera.positionCartographic.height).toFixed(0);
const listener = getInstanceListener(vcInstance, "zoomEvt");
listener && emit("zoomEvt", {
type,
camera: viewer.camera,
status: "start",
target,
level
});
if (Cesium.defined(viewer.trackedEntity) || scene.mode === SceneMode.COLUMBUS_VIEW) {
camera.position = endPosition;
} else {
camera.flyTo({
destination: endPosition,
orientation,
duration: props.duration,
convert: false,
complete: () => {
listener && emit("zoomEvt", {
type,
camera: viewer.camera,
status: "end",
target,
level
});
},
cancel: () => {
listener && emit("zoomEvt", {
type,
camera: viewer.camera,
status: "cancel",
target,
level
});
}
});
}
}
}
}
};
const zoomReset = (e) => {
var _a;
(_a = $(resetTooltipRef)) == null ? void 0 : _a.hide();
const { viewer } = $services;
const scene = viewer.scene;
const sscc = scene.screenSpaceCameraController;
if (!sscc.enableInputs) {
return;
}
if (Cesium.defined(viewer.trackedEntity)) {
const trackedEntity = viewer.trackedEntity;
viewer.trackedEntity = void 0;
viewer.trackedEntity = trackedEntity;
} else {
const listener = getInstanceListener(vcInstance, "zoomEvt");
const target = e.currentTarget;
const level = heightToLevel(viewer.camera.positionCartographic.height).toFixed(0);
listener && emit("zoomEvt", {
type: "zoomReset",
camera: viewer.camera,
status: "start",
target,
level
});
const complete = () => {
listener && emit("zoomEvt", {
type: "zoomReset",
camera: viewer.camera,
status: "end",
target,
level
});
};
const cancel = () => {
listener && emit("zoomEvt", {
type: "zoomReset",
camera: viewer.camera,
status: "cancel",
target,
level
});
};
const resetView = props.defaultResetView;
const options = {
duration: props.durationReset,
complete,
cancel
};
flyToCamera(viewer, resetView, options);
}
};
const getCameraFocus = (scene) => {
const { defined, IntersectionTests, Ray } = Cesium;
const ray = new Ray(scene.camera.positionWC, scene.camera.directionWC);
const intersections = IntersectionTests.rayEllipsoid(ray, scene.globe.ellipsoid);
if (defined(intersections)) {
return Ray.getPoint(ray, intersections.start);
}
return IntersectionTests.grazingAltitudeLocation(ray, scene.globe.ellipsoid);
};
return {
zoomIn,
zoomOut,
zoomReset,
zoomInTooltipRef,
zoomOutTooltipRef,
resetTooltipRef
};
}
const emits$l = {
...commonEmits,
zoomEvt: (evt) => true
};
const zoomControlProps = exports('zoomControlProps', defaultProps$3);
var ZoomControl = defineComponent({
name: "VcZoomControl",
props: zoomControlProps,
emits: emits$l,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "VcZoomControl";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { t } = useLocale();
const { $services } = commonState;
const zoomControlState = useZoomControl$1(props, ctx, instance, $services);
const positionState = usePosition(props);
const rootRef = ref(null);
const zoomInRef = ref(null);
const zoomResetRef = ref(null);
const zoomOutRef = ref(null);
const parentInstance = getVcParentInstance(instance);
const hasVcNavigation = ((_a = parentInstance.proxy) == null ? void 0 : _a.$options.name) === "VcNavigation";
const canRender = ref(hasVcNavigation);
const rootStyle = reactive({});
watch(
() => props,
(val) => {
nextTick(() => {
if (!instance.mounted) {
return;
}
updateRootStyle();
});
},
{
deep: true
}
);
const zoomOutOptions = computed(() => Object.assign({}, defaultOptions$5.zoomOutOptions, props.zoomOutOptions));
const zoomInOptions = computed(() => Object.assign({}, defaultOptions$5.zoomInOptions, props.zoomInOptions));
const zoomResetOptions = computed(() => Object.assign({}, defaultOptions$5.zoomResetOptions, props.zoomResetOptions));
instance.createCesiumObject = async () => {
const { viewer } = $services;
if (props.overrideViewerCamera) {
const resetView = props.defaultResetView;
setViewerCamera(viewer, resetView);
}
return rootRef;
};
instance.mount = async () => {
var _a2;
canRender.value = true;
nextTick(() => {
updateRootStyle();
});
const { viewer } = $services;
(_a2 = viewer.viewerWidgetResized) == null ? void 0 : _a2.raiseEvent({
type: instance.cesiumClass,
status: "mounted",
target: $(rootRef)
});
return true;
};
instance.unmount = async () => {
var _a2;
canRender.value = false;
const { viewer } = $services;
(_a2 = viewer.viewerWidgetResized) == null ? void 0 : _a2.raiseEvent({
type: instance.cesiumClass,
status: "unmounted",
target: $(rootRef)
});
return true;
};
const updateRootStyle = () => {
var _a2, _b, _c;
const css = positionState.style.value;
rootStyle.left = css.left;
rootStyle.top = css.top;
rootStyle.transform = css.transform;
css.flexDirection = props.direction === "vertical" ? "column" : "row";
css.background = props.background;
css.borderRadius = props.borderRadius;
css.border = props.border;
if (!hasVcNavigation) {
const zoomInTarget = (_a2 = $(zoomInRef)) == null ? void 0 : _a2.$el;
const zoomResetTarget = (_b = $(zoomResetRef)) == null ? void 0 : _b.$el;
const zoomOutTarget = (_c = $(zoomOutRef)) == null ? void 0 : _c.$el;
let width = 0;
let height = 0;
if (zoomInTarget !== void 0) {
const zoomInClientRect = zoomInTarget.getBoundingClientRect();
if (props.direction === "horizontal") {
width += zoomInClientRect.width;
height = zoomInClientRect.height > height ? zoomInClientRect.height : height;
} else {
height += zoomInClientRect.height;
width = zoomInClientRect.width > width ? zoomInClientRect.width : width;
}
}
if (zoomResetTarget !== void 0) {
const zoomResetClientRect = zoomResetTarget.getBoundingClientRect();
if (props.direction === "horizontal") {
width += zoomResetClientRect.width;
height = zoomResetClientRect.height > height ? zoomResetClientRect.height : height;
} else {
height += zoomResetClientRect.height;
width = zoomResetClientRect.width > width ? zoomResetClientRect.width : width;
}
}
if (zoomOutTarget !== void 0) {
const zoomOutClientRect = zoomOutTarget.getBoundingClientRect();
if (props.direction === "horizontal") {
width += zoomOutClientRect.width;
height = zoomOutClientRect.height > height ? zoomOutClientRect.height : height;
} else {
height += zoomOutClientRect.height;
width = zoomOutClientRect.width > width ? zoomOutClientRect.width : width;
}
}
css.width = `${width + 4}px`;
css.height = `${height + 4}px`;
if (typeof props.teleportToViewer === "undefined" || props.teleportToViewer) {
const side = positionState.attach.value;
if ((side.bottom || side.top) && !side.left && !side.right) {
css.left = "50%";
css.transform = "translate(-50%, 0)";
}
if ((side.left || side.right) && !side.top && !side.bottom) {
css.top = "50%";
css.transform = "translate(0, -50%)";
}
}
}
Object.assign(rootStyle, css);
};
const getContent = (options, type) => {
var _a2, _b, _c;
let btnRef;
let tooltipRef;
let tip;
let onClick;
if (type === "zoomIn") {
btnRef = zoomInRef;
tooltipRef = zoomControlState.zoomInTooltipRef;
tip = ((_a2 = options.tooltip) == null ? void 0 : _a2.tip) || t("vc.navigation.zoomCotrol.zoomInTip");
onClick = zoomControlState.zoomIn;
} else if (type === "zoomOut") {
btnRef = zoomOutRef;
tooltipRef = zoomControlState.zoomOutTooltipRef;
tip = ((_b = options.tooltip) == null ? void 0 : _b.tip) || t("vc.navigation.zoomCotrol.zoomOutTip");
onClick = zoomControlState.zoomOut;
} else if (type === "zoomReset") {
btnRef = zoomResetRef;
tooltipRef = zoomControlState.resetTooltipRef;
tip = ((_c = options.tooltip) == null ? void 0 : _c.tip) || t("vc.navigation.zoomCotrol.zoomResetTip");
onClick = zoomControlState.zoomReset;
}
const inner = [];
inner.push(
h(VcIcon, {
name: options.icon,
size: options.size
})
);
inner.push(h("div", null, options.label));
if (options.tooltip) {
inner.push(
h(
VcTooltip,
{
ref: tooltipRef,
...options.tooltip
},
() => h("strong", null, tip)
)
);
} else {
inner.push(createCommentVNode("v-if"));
}
const content = h(
VcBtn,
{
class: `vc-${kebabCase(type)}`,
ref: btnRef,
size: options.size,
flat: options.flat,
stack: options.stack,
round: options.round,
dense: true,
style: { color: options.color, background: options.background },
onClick
},
() => hMergeSlot(ctx.slots.default, inner)
);
return content;
};
Object.assign(instance.proxy, {
zoomIn: () => zoomControlState.zoomIn,
zoomOut: () => zoomControlState.zoomOut,
zoomReset: () => zoomControlState.zoomReset
});
return () => {
if (canRender.value) {
const children = [];
children.push(h("li", null, getContent(zoomInOptions.value, "zoomIn")));
if (props.enableResetButton) {
children.push(h("li", null, getContent(zoomResetOptions.value, "zoomReset")));
} else {
children.push(createCommentVNode("v-if"));
}
children.push(h("li", null, getContent(zoomOutOptions.value, "zoomOut")));
const renderContent = h(
"div",
{
ref: rootRef,
class: `vc-zoom-control ${positionState.classes.value} ${props.customClass}`,
style: rootStyle
},
h(
"ul",
{
class: "vc-list"
},
children
)
);
return !hasVcNavigation && props.teleportToViewer ? h(Teleport, { to: $services.viewer._element }, renderContent) : renderContent;
} else {
return createCommentVNode("v-if");
}
};
}
});
const VcPrintView = defineComponent({
name: "VcPrintView",
props: {
options: Object
},
setup(props) {
const ready = ref(false);
const printingStarted = ref(false);
const instance = getCurrentInstance();
instance.cesiumClass = "VcPrintView";
const { t } = useLocale();
const checkForImagesReady = () => {
var _a, _b;
if (ready.value) {
return;
}
const imageTags = (_a = props.options) == null ? void 0 : _a.printWindow.document.getElementsByTagName("img");
if (imageTags.length === 0) {
return;
}
let allImagesReady = true;
for (let i = 0; allImagesReady && i < imageTags.length; ++i) {
allImagesReady = imageTags[i].complete;
}
if (allImagesReady) {
stopCheckingForImages();
ready.value = allImagesReady;
if (ready.value && !printingStarted.value) {
if ((_b = props.options) == null ? void 0 : _b.readyCallback) {
props.options.readyCallback(props.options.printWindow);
}
printingStarted.value = true;
}
}
};
let _stopCheckingForImages;
const stopCheckingForImages = () => {
if (_stopCheckingForImages) {
_stopCheckingForImages();
}
};
onMounted(() => {
var _a;
const printWindow = (_a = props.options) == null ? void 0 : _a.printWindow;
const mainWindow = window;
const printWindowIntervalId = printWindow == null ? void 0 : printWindow.setInterval(checkForImagesReady, 200);
const mainWindowIntervalId = mainWindow.setInterval(checkForImagesReady, 200);
_stopCheckingForImages = () => {
printWindow.clearInterval(printWindowIntervalId);
mainWindow.clearInterval(mainWindowIntervalId);
_stopCheckingForImages = void 0;
};
});
onUnmounted(() => {
stopCheckingForImages();
});
return () => {
var _a, _b, _c, _d, _e, _f;
const child = [];
child.push(
h(
"p",
{},
h("img", {
src: (_a = props.options) == null ? void 0 : _a.image,
alt: t("vc.navigation.screenshot"),
class: "vc-map-image"
})
)
);
if (((_b = props.options) == null ? void 0 : _b.credits.length) && ((_c = props.options) == null ? void 0 : _c.showCredit)) {
child.push(h("h1", {}, t("vc.navigation.credit")));
} else {
child.push(createCommentVNode("v-if"));
}
if (((_d = props.options) == null ? void 0 : _d.credits.length) && ((_e = props.options) == null ? void 0 : _e.showCredit)) {
const inner = [];
(_f = props.options) == null ? void 0 : _f.credits.forEach((credit) => {
inner.push(
h("li", {
innerHTML: credit
})
);
});
child.push(h("ul", {}, inner));
} else {
child.push(createCommentVNode("v-if"));
}
return h("div", {}, child);
};
}
});
const styles = `
.background {
width: 100%;
fill: rgba(255, 255, 255, 1.0);
}
.map-image {
max-width: 95vw;
max-height: 95vh;
}
.layer-legends {
display: inline;
float: left;
padding-left: 20px;
padding-right: 20px;
}
.layer-title {
font-weight: bold;
}
h1, h2, h3 {
clear: both;
}
`;
const createPrintView = (options) => {
const { printWindow = window.open(), closeCallback, title } = options;
if (closeCallback) {
printWindow.addEventListener("unload", () => {
closeCallback(printWindow);
});
}
printWindow.document.open();
printWindow.document.close();
printWindow.document.head.innerHTML = `
<meta charset="UTF-8">
<title>${options.title}</title>
<style>${styles}</style>
`;
printWindow.document.body.innerHTML = '<div id="print"></div>';
options.printWindow = options.printWindow || printWindow;
const printViewProps = {
options
};
const app = createApp(VcPrintView, printViewProps);
app.mount(printWindow.document.getElementById("print"));
};
var printDefaultProps = {
showCredit: {
type: Boolean,
default: true
},
printAutomatically: {
type: Boolean,
default: false
},
showPrintView: {
type: Boolean,
default: true
},
downloadAutomatically: {
type: Boolean,
default: false
},
...positionProps,
icon: {
type: String,
default: "vc-icons-capture"
},
size: {
type: String,
default: "24px"
},
color: {
type: String,
default: "#3f4854"
},
background: {
type: String,
default: "#fff"
},
round: {
type: Boolean,
default: true
},
flat: {
type: Boolean,
default: false
},
label: String,
stack: {
type: Boolean,
default: false
},
tooltip: {
type: [Boolean, Object],
default: () => ({
delay: 500,
anchor: "bottom middle",
offset: [0, 20],
tip: void 0
})
},
screenshotName: String,
customClass: {
type: String,
default: ""
},
teleportToViewer: {
type: Boolean,
default: true
}
};
function printWindow(windowToPrint) {
const deferred = defer();
let printInProgressCount = 0;
const timeout = setTimeout(function() {
deferred.reject(false);
}, 1e4);
function cancelTimeout() {
clearTimeout(timeout);
}
function resolveIfZero() {
if (printInProgressCount <= 0) {
deferred.resolve();
}
}
if (windowToPrint.matchMedia) {
windowToPrint.matchMedia("print").addListener(function(evt) {
cancelTimeout();
if (evt.matches) {
++printInProgressCount;
} else {
--printInProgressCount;
resolveIfZero();
}
});
}
windowToPrint.onbeforeprint = function() {
cancelTimeout();
++printInProgressCount;
};
windowToPrint.onafterprint = function() {
cancelTimeout();
--printInProgressCount;
resolveIfZero();
};
const result = windowToPrint.document.execCommand("print", true, null);
if (!result) {
windowToPrint.print();
}
return deferred.promise;
}
const emits$k = {
...commonEmits,
printEvt: (evt) => true
};
const printProps = exports('printProps', printDefaultProps);
var Print = defineComponent({
name: "VcPrint",
props: printProps,
emits: emits$k,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "VcPrint";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { t } = useLocale();
const { $services } = commonState;
const rootRef = ref(null);
const tooltipRef = ref(null);
const btnRef = ref(null);
const positionState = usePosition(props);
const creatingPrintView = ref(false);
const parentInstance = getVcParentInstance(instance);
const hasVcNavigation = ((_a = parentInstance.proxy) == null ? void 0 : _a.$options.name) === "VcNavigation";
const canRender = ref(hasVcNavigation);
const rootStyle = reactive({});
watch(
() => props,
(val) => {
nextTick(() => {
if (!instance.mounted) {
return;
}
updateRootStyle();
});
},
{
deep: true
}
);
instance.createCesiumObject = async () => {
return rootRef;
};
instance.mount = async () => {
var _a2;
canRender.value = true;
nextTick(() => {
updateRootStyle();
});
const { viewer } = $services;
(_a2 = viewer.viewerWidgetResized) == null ? void 0 : _a2.raiseEvent({
type: instance.cesiumClass,
status: "mounted",
target: $(rootRef)
});
return true;
};
instance.unmount = async () => {
var _a2;
canRender.value = false;
const { viewer } = $services;
(_a2 = viewer.viewerWidgetResized) == null ? void 0 : _a2.raiseEvent({
type: instance.cesiumClass,
status: "unmounted",
target: $(rootRef)
});
return true;
};
const updateRootStyle = () => {
var _a2;
const css = positionState.style.value;
rootStyle.left = css.left;
rootStyle.top = css.top;
rootStyle.transform = css.transform;
if (!hasVcNavigation) {
const side = positionState.attach.value;
const btnTarget = (_a2 = $(btnRef)) == null ? void 0 : _a2.$el;
if (btnTarget !== void 0) {
if (typeof props.teleportToViewer === "undefined" || props.teleportToViewer) {
if ((side.bottom || side.top) && !side.left && !side.right) {
css.left = "50%";
css.transform = "translate(-50%, 0)";
}
if ((side.left || side.right) && !side.top && !side.bottom) {
css.top = "50%";
css.transform = "translate(0, -50%)";
}
}
}
}
Object.assign(rootStyle, css);
};
const onHandleClick = () => {
var _a2;
(_a2 = $(tooltipRef)) == null ? void 0 : _a2.hide();
const { viewer } = $services;
captureScreenshot(viewer).then((imgSrc) => {
if (props.downloadAutomatically) {
const link = document.createElement("a");
link.download = props.screenshotName || t("vc.navigation.print.screenshot");
link.style.display = "none";
link.href = imgSrc;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
if (props.printAutomatically || props.showPrintView) {
if (props.showPrintView) {
showPrintView(imgSrc);
} else if (props.printAutomatically) {
print(imgSrc);
}
}
const listener = getInstanceListener(instance, "printEvt");
listener && ctx.emit("printEvt", {
type: "capture",
image: imgSrc,
status: "end"
});
});
};
const print = (image) => {
create(true, true, image);
};
const showPrintView = (image) => {
create(false, false, image);
};
const create = (hidden, printAutomatically, image) => {
creatingPrintView.value = true;
let iframe;
if (hidden) {
iframe = document.createElement("iframe");
document.body.appendChild(iframe);
}
const { viewer } = $services;
createPrintView({
image,
showCredit: props.showCredit,
credits: getCredits(viewer),
printWindow: iframe ? iframe.contentWindow : void 0,
title: t("vc.navigation.print.printViewTitle"),
readyCallback: (windowToPrint) => {
if (printAutomatically) {
printWindow(windowToPrint).catch((e) => {
commonState.logger.warn(e);
}).then(() => {
if (iframe) {
document.body.removeChild(iframe);
}
if (hidden) {
creatingPrintView.value = false;
}
});
}
},
closeCallback: (windowToPrint) => {
if (hidden) {
creatingPrintView.value = false;
}
}
});
if (!hidden) {
creatingPrintView.value = false;
}
};
const getCredits = (viewer) => {
const credits = viewer.scene.frameState.creditDisplay._currentFrameCredits.screenCredits.values.concat(
viewer.scene.frameState.creditDisplay._currentFrameCredits.lightboxCredits.values
);
return credits.map((credit) => credit.html);
};
const onTooltipBeforeShow = (e) => {
if (creatingPrintView.value) {
e.cancel = true;
}
};
return () => {
if (canRender.value) {
const inner = [];
inner.push(
h(VcIcon, {
name: props.icon,
size: props.size
})
);
inner.push(h("div", null, props.label));
if (isPlainObject(props.tooltip)) {
inner.push(
h(
VcTooltip,
{
ref: tooltipRef,
onBeforeShow: onTooltipBeforeShow,
...props.tooltip
},
() => h("strong", null, isPlainObject(props.tooltip) && props.tooltip.tip || t("vc.navigation.print.printTip"))
)
);
} else {
inner.push(createCommentVNode("v-if"));
}
const child = [
h(
VcBtn,
{
ref: btnRef,
size: props.size,
disabled: creatingPrintView.value,
flat: props.flat,
stack: props.stack,
round: props.round,
style: { color: props.color, background: props.background },
dense: true,
onClick: onHandleClick
},
() => inner
)
];
const renderContent = h(
"div",
{
ref: rootRef,
class: `vc-print ${positionState.classes.value} ${props.customClass}`,
style: rootStyle
},
child
);
return !hasVcNavigation && props.teleportToViewer ? h(Teleport, { to: $services.viewer._element }, renderContent) : renderContent;
} else {
return createCommentVNode("v-if");
}
};
}
});
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var dist = {exports: {}};
dist.exports;
(function (module, exports) {
(function(m,p){module.exports=p();})(commonjsGlobal,function(){function m(a){var b=[];a.AMapUI&&b.push(p(a.AMapUI));a.Loca&&b.push(r(a.Loca));return Promise.all(b)}function p(a){return new Promise(function(h,c){var f=[];if(a.plugins)for(var e=0;e<a.plugins.length;e+=1)-1==d.AMapUI.plugins.indexOf(a.plugins[e])&&f.push(a.plugins[e]);if(g.AMapUI===b.failed)c("\u524d\u6b21\u8bf7\u6c42 AMapUI \u5931\u8d25");
else if(g.AMapUI===b.notload){g.AMapUI=b.loading;d.AMapUI.version=a.version||d.AMapUI.version;e=d.AMapUI.version;var l=document.body||document.head,k=document.createElement("script");k.type="text/javascript";k.src="https://webapi.amap.com/ui/"+e+"/main.js";k.onerror=function(a){g.AMapUI=b.failed;c("\u8bf7\u6c42 AMapUI \u5931\u8d25");};k.onload=function(){g.AMapUI=b.loaded;if(f.length)window.AMapUI.loadUI(f,function(){for(var a=0,b=f.length;a<b;a++){var c=f[a].split("/").slice(-1)[0];window.AMapUI[c]=
arguments[a];}for(h();n.AMapUI.length;)n.AMapUI.splice(0,1)[0]();});else for(h();n.AMapUI.length;)n.AMapUI.splice(0,1)[0]();};l.appendChild(k);}else g.AMapUI===b.loaded?a.version&&a.version!==d.AMapUI.version?c("\u4e0d\u5141\u8bb8\u591a\u4e2a\u7248\u672c AMapUI \u6df7\u7528"):f.length?window.AMapUI.loadUI(f,function(){for(var a=0,b=f.length;a<b;a++){var c=f[a].split("/").slice(-1)[0];window.AMapUI[c]=arguments[a];}h();}):h():a.version&&a.version!==d.AMapUI.version?c("\u4e0d\u5141\u8bb8\u591a\u4e2a\u7248\u672c AMapUI \u6df7\u7528"):
n.AMapUI.push(function(a){a?c(a):f.length?window.AMapUI.loadUI(f,function(){for(var a=0,b=f.length;a<b;a++){var c=f[a].split("/").slice(-1)[0];window.AMapUI[c]=arguments[a];}h();}):h();});})}function r(a){return new Promise(function(h,c){if(g.Loca===b.failed)c("\u524d\u6b21\u8bf7\u6c42 Loca \u5931\u8d25");else if(g.Loca===b.notload){g.Loca=b.loading;d.Loca.version=a.version||d.Loca.version;var f=d.Loca.version,e=d.AMap.version.startsWith("2"),l=f.startsWith("2");if(e&&!l||!e&&l)c("JSAPI \u4e0e Loca \u7248\u672c\u4e0d\u5bf9\u5e94\uff01\uff01");
else {e=d.key;l=document.body||document.head;var k=document.createElement("script");k.type="text/javascript";k.src="https://webapi.amap.com/loca?v="+f+"&key="+e;k.onerror=function(a){g.Loca=b.failed;c("\u8bf7\u6c42 AMapUI \u5931\u8d25");};k.onload=function(){g.Loca=b.loaded;for(h();n.Loca.length;)n.Loca.splice(0,1)[0]();};l.appendChild(k);}}else g.Loca===b.loaded?a.version&&a.version!==d.Loca.version?c("\u4e0d\u5141\u8bb8\u591a\u4e2a\u7248\u672c Loca \u6df7\u7528"):h():a.version&&a.version!==d.Loca.version?
c("\u4e0d\u5141\u8bb8\u591a\u4e2a\u7248\u672c Loca \u6df7\u7528"):n.Loca.push(function(a){a?c(a):c();});})}if(!window)throw Error("AMap JSAPI can only be used in Browser.");var b;(function(a){a.notload="notload";a.loading="loading";a.loaded="loaded";a.failed="failed";})(b||(b={}));var d={key:"",AMap:{version:"1.4.15",plugins:[]},AMapUI:{version:"1.1",plugins:[]},Loca:{version:"1.3.2"}},g={AMap:b.notload,AMapUI:b.notload,Loca:b.notload},n={AMap:[],AMapUI:[],Loca:[]},q=[],t=function(a){"function"==typeof a&&
(g.AMap===b.loaded?a(window.AMap):q.push(a));};return {load:function(a){return new Promise(function(h,c){if(g.AMap==b.failed)c("");else if(g.AMap==b.notload){var f=a.key,e=a.version,l=a.plugins;f?(window.AMap&&"lbs.amap.com"!==location.host&&c("\u7981\u6b62\u591a\u79cdAPI\u52a0\u8f7d\u65b9\u5f0f\u6df7\u7528"),d.key=f,d.AMap.version=e||d.AMap.version,d.AMap.plugins=l||d.AMap.plugins,g.AMap=b.loading,e=document.body||document.head,window.___onAPILoaded=function(d){delete window.___onAPILoaded;if(d)g.AMap=
b.failed,c(d);else for(g.AMap=b.loaded,m(a).then(function(){h(window.AMap);})["catch"](c);q.length;)q.splice(0,1)[0]();},l=document.createElement("script"),l.type="text/javascript",l.src="https://webapi.amap.com/maps?callback=___onAPILoaded&v="+d.AMap.version+"&key="+f+"&plugin="+d.AMap.plugins.join(","),l.onerror=function(a){g.AMap=b.failed;c(a);},e.appendChild(l)):c("\u8bf7\u586b\u5199key");}else if(g.AMap==b.loaded)if(a.key&&a.key!==d.key)c("\u591a\u4e2a\u4e0d\u4e00\u81f4\u7684 key");else if(a.version&&
a.version!==d.AMap.version)c("\u4e0d\u5141\u8bb8\u591a\u4e2a\u7248\u672c JSAPI \u6df7\u7528");else {f=[];if(a.plugins)for(e=0;e<a.plugins.length;e+=1)-1==d.AMap.plugins.indexOf(a.plugins[e])&&f.push(a.plugins[e]);if(f.length)window.AMap.plugin(f,function(){m(a).then(function(){h(window.AMap);})["catch"](c);});else m(a).then(function(){h(window.AMap);})["catch"](c);}else if(a.key&&a.key!==d.key)c("\u591a\u4e2a\u4e0d\u4e00\u81f4\u7684 key");else if(a.version&&a.version!==d.AMap.version)c("\u4e0d\u5141\u8bb8\u591a\u4e2a\u7248\u672c JSAPI \u6df7\u7528");
else {var k=[];if(a.plugins)for(e=0;e<a.plugins.length;e+=1)-1==d.AMap.plugins.indexOf(a.plugins[e])&&k.push(a.plugins[e]);t(function(){if(k.length)window.AMap.plugin(k,function(){m(a).then(function(){h(window.AMap);})["catch"](c);});else m(a).then(function(){h(window.AMap);})["catch"](c);});}})},reset:function(){delete window.AMap;delete window.AMapUI;delete window.Loca;d={key:"",AMap:{version:"1.4.15",plugins:[]},AMapUI:{version:"1.1",plugins:[]},Loca:{version:"1.3.2"}};g={AMap:b.notload,AMapUI:b.notload,
Loca:b.notload};n={AMap:[],AMapUI:[],Loca:[]};}}});
} (dist, dist.exports));
var distExports = dist.exports;
var AMapLoader = /*@__PURE__*/getDefaultExportFromCjs(distExports);
var locationDefaultProps = {
geolocation: {
type: Object,
default: () => ({
enableHighAccuracy: true,
timeout: 5e3,
maximumAge: 0
})
},
/**
* refer https://developer.amap.com/api/jsapi-v2/documentation#geolocation
* {
* key: '',
* version: '2.0',
* options: {
* timeout: 5000,
* convert: false,
* noGeoLocation: 3,
* needAddress: true
* extensions: 'all'
* },
* transformToWGS84: true
* }
*/
amap: Object,
id: {
type: String,
default: "My Location"
},
pointColor: {
type: [Array, Object, String],
default: "#08ABD5"
},
pixelSize: {
type: Number,
default: 25 / 2
},
outlineWidth: {
type: Number,
default: 3
},
outlineColor: {
type: [Array, Object, String],
default: "#ffffff"
},
level: {
type: Number,
default: 6
},
duration: {
type: Number,
default: 3
},
factor: {
type: Number,
default: 0.01
},
maximumHeight: Number,
hpr: {
type: Array,
default: () => [0, 0, 3e3]
},
customAPI: Function,
customApi: Function,
description: Function,
...positionProps,
icon: {
type: String,
default: "vc-icons-geolocation"
},
size: {
type: String,
default: "24px"
},
color: {
type: String,
default: "#3f4854"
},
background: {
type: String,
default: "#fff"
},
round: {
type: Boolean,
default: true
},
flat: {
type: Boolean,
default: false
},
label: String,
stack: {
type: Boolean,
default: false
},
tooltip: {
type: [Boolean, Object],
default: () => ({
delay: 500,
anchor: "bottom middle",
offset: [0, 20],
tip: void 0
})
},
loadingType: {
type: String,
default: "puff"
},
customClass: {
type: String,
default: ""
},
teleportToViewer: {
type: Boolean,
default: true
}
};
const emits$j = {
...commonEmits,
locationEvt: (evt) => true
};
const myLocationProps = exports('myLocationProps', locationDefaultProps);
var MyLocation = defineComponent({
name: "VcMyLocation",
props: myLocationProps,
emits: emits$j,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "VcMyLocation";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { $services } = commonState;
const { t } = useLocale();
const rootRef = ref(null);
const tooltipRef = ref(null);
const btnRef = ref(null);
const positioning = ref(false);
const positionState = usePosition(props);
const parentInstance = getVcParentInstance(instance);
const hasVcNavigation = ((_a = parentInstance.proxy) == null ? void 0 : _a.$options.name) === "VcNavigation";
const canRender = ref(hasVcNavigation);
const rootStyle = reactive({});
let datasource;
let amapGeolocation = void 0;
watch(
() => props,
(val) => {
nextTick(() => {
if (!instance.mounted) {
return;
}
updateRootStyle();
});
},
{
deep: true
}
);
const myLocationTip = computed(() => {
return positioning.value ? t("vc.navigation.myLocation.positioning") : isPlainObject(props.tooltip) && props.tooltip.tip || t("vc.navigation.myLocation.myLocationTip");
});
instance.createCesiumObject = async () => {
const { viewer } = $services;
const { CustomDataSource } = Cesium;
const locationDsArray = viewer.dataSources.getByName("__vc-myLocation__");
if (locationDsArray.length) {
datasource = locationDsArray[0];
} else {
viewer.dataSources.add(new CustomDataSource("__vc-myLocation__")).then((ds) => {
datasource = ds;
});
}
let promiseLoadAmap = void 0;
if (props.amap && props.amap.key) {
const options = props.amap.options;
promiseLoadAmap = new Promise((resolve, reject) => {
var _a2, _b;
AMapLoader.load({
key: (_a2 = props.amap) == null ? void 0 : _a2.key,
version: (_b = props.amap) == null ? void 0 : _b.version,
plugins: ["AMap.Geolocation"]
}).then((Amap) => {
amapGeolocation = new Amap.Geolocation(options);
resolve(amapGeolocation);
}).catch((e) => {
commonState.logger.error(e);
reject(e);
});
});
}
const promiseAppend = new Promise((resolve, reject) => {
nextTick(() => {
resolve($(rootRef));
});
});
return Promise.all([promiseAppend, promiseLoadAmap]).then((e) => {
return e[0];
});
};
instance.mount = async () => {
var _a2;
canRender.value = true;
nextTick(() => {
updateRootStyle();
});
const { viewer } = $services;
(_a2 = viewer.viewerWidgetResized) == null ? void 0 : _a2.raiseEvent({
type: instance.cesiumClass,
status: "mounted",
target: $(rootRef)
});
return true;
};
instance.unmount = async () => {
var _a2;
canRender.value = false;
const { viewer } = $services;
if (amapGeolocation) {
const scripts = document.getElementsByTagName("script");
const removeScripts = [];
for (const script of scripts) {
if (script.src.indexOf("/webapi.amap.com/maps") > -1) {
removeScripts.push(script);
}
}
removeScripts.forEach((script) => {
document.getElementsByTagName("body")[0].removeChild(script);
});
}
(_a2 = viewer.viewerWidgetResized) == null ? void 0 : _a2.raiseEvent({
type: instance.cesiumClass,
status: "unmounted",
target: $(rootRef)
});
return viewer.dataSources.remove(datasource, true);
};
const updateRootStyle = () => {
var _a2;
const css = positionState.style.value;
rootStyle.left = css.left;
rootStyle.top = css.top;
rootStyle.transform = css.transform;
if (!hasVcNavigation) {
const side = positionState.attach.value;
const btnTarget = (_a2 = $(btnRef)) == null ? void 0 : _a2.$el;
if (btnTarget !== void 0) {
if (typeof props.teleportToViewer === "undefined" || props.teleportToViewer) {
if ((side.bottom || side.top) && !side.left && !side.right) {
css.left = "50%";
css.transform = "translate(-50%, 0)";
}
if ((side.left || side.right) && !side.top && !side.bottom) {
css.top = "50%";
css.transform = "translate(0, -50%)";
}
}
}
}
Object.assign(rootStyle, css);
};
const onHandleClick = () => {
var _a2;
(_a2 = $(tooltipRef)) == null ? void 0 : _a2.hide();
positioning.value = true;
const customApi = props.customApi || props.customAPI;
if (isFunction(customApi)) {
const position = customApi(handleLocationError);
zoomToMyLocation(position);
} else if (amapGeolocation && props.amap && props.amap.key) {
amapGeolocation.getCurrentPosition((status, result) => {
var _a3;
if (status === "complete") {
let position = [result.position.lng, result.position.lat];
if ((_a3 = props.amap) == null ? void 0 : _a3.transformToWGS84) {
position = gcj02towgs84(position[0], position[1]);
}
zoomToMyLocation(
{
lng: position[0],
lat: position[1],
address: result.formattedAddress
},
result
);
} else {
handleLocationError(t("vc.navigation.myLocation.fail"), result.message);
}
});
} else if (props.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
zoomToMyLocation(
{
lng: position.coords.longitude,
lat: position.coords.latitude
},
position
);
},
handleLocationError,
{
enableHighAccuracy: props.geolocation.enableHighAccuracy,
timeout: props.geolocation.timeout,
maximumAge: props.geolocation.maximumAge
}
);
} else {
handleLocationError(t("vc.navigation.myLocation.fail"));
}
};
const zoomToMyLocation = (position, detail) => {
var _a2;
const longitude = position.lng;
const latitude = position.lat;
const address = position.address;
const { Rectangle, sampleTerrain, defined, SceneMode } = Cesium;
const { viewer } = $services;
datasource.entities.removeAll();
const myPositionEntity = datasource.entities.add({
id: props.id,
position: makeCartesian3([longitude, latitude], viewer.scene.globe.ellipsoid),
point: {
color: makeColor(props.pointColor),
pixelSize: props.pixelSize,
outlineWidth: props.outlineWidth,
outlineColor: makeColor(props.outlineColor)
},
properties: {
...detail
},
description: ((_a2 = props.description) == null ? void 0 : _a2.call(this, position, detail)) || describeWithoutUnderscores({
[t("vc.navigation.myLocation.lng")]: longitude,
[t("vc.navigation.myLocation.lat")]: latitude,
[t("vc.navigation.myLocation.address")]: address
})
});
const listener = getInstanceListener(instance, "locationEvt");
listener && ctx.emit("locationEvt", {
type: "location",
position,
detail,
entity: myPositionEntity
});
const options = {
duration: props.duration
};
defined(props.maximumHeight) && (options.maximumHeight = props.maximumHeight);
defined(props.hpr) && isArray(props.hpr) && (options.offset = new Cesium.HeadingPitchRange(props.hpr[0], props.hpr[1], props.hpr[2]));
if (viewer.scene.mode === SceneMode.SCENE2D || viewer.scene.mode === SceneMode.COLUMBUS_VIEW) {
return viewer.flyTo(myPositionEntity, options).then(() => {
positioning.value = false;
listener && ctx.emit("locationEvt", {
type: "zoomIn",
camera: viewer.camera,
status: "end"
});
});
}
const factor = props.factor;
const rectangle = Rectangle.fromDegrees(longitude - factor, latitude - factor, longitude + factor, latitude + factor);
const camera = viewer.scene.camera;
const destinationCartesian = camera.getRectangleCameraCoordinates(rectangle);
const destination = viewer.scene.globe.ellipsoid.cartesianToCartographic(destinationCartesian);
const terrainProvider = viewer.scene.globe.terrainProvider;
const level = props.level;
const positions = [Rectangle.center(rectangle)];
return sampleTerrain(terrainProvider, level, positions).then(function(results) {
const finalDestinationCartographic = {
longitude: destination.longitude,
latitude: destination.latitude,
height: destination.height + results[0].height
};
const finalDestination = viewer.scene.globe.ellipsoid.cartographicToCartesian(finalDestinationCartographic);
listener && ctx.emit("locationEvt", {
type: "zoomIn",
camera: viewer.camera,
status: "start"
});
camera.flyTo({
duration: props.duration,
destination: finalDestination,
complete: () => {
positioning.value = false;
listener && ctx.emit("locationEvt", {
type: "zoomIn",
camera: viewer.camera,
status: "end"
});
},
cancel: () => {
positioning.value = false;
listener && ctx.emit("locationEvt", {
type: "zoomIn",
camera: viewer.camera,
status: "cancel"
});
}
});
});
};
const describeWithoutUnderscores = (properties, nameProperty) => {
let html = "";
if (properties instanceof Cesium.PropertyBag) {
properties = properties.getValue(Cesium.JulianDate.now());
}
for (let key in properties) {
if (Object.prototype.hasOwnProperty.call(properties, key)) {
if (key === nameProperty) {
continue;
}
let value = properties[key];
if (typeof value === "object") {
value = describeWithoutUnderscores(value);
}
key = key.replace(/_/g, " ");
if (Cesium.defined(value)) {
html += "<tr><th>" + key + "</th><td>" + value + "</td></tr>";
}
}
}
if (html.length > 0) {
html = '<table class="cesium-infoBox-defaultTable"><tbody>' + html + "</tbody></table>";
}
return html;
};
const handleLocationError = (...args) => {
positioning.value = false;
commonState.logger.error(...args);
};
const getLoadingCmp = () => {
switch (props.loadingType) {
case "bars":
return VcSpinnerBars;
case "ios":
return VcSpinnerIos;
case "orbit":
return VcSpinnerOrbit;
case "oval":
return VcSpinnerOval;
case "puff":
return VcSpinnerPuff;
case "tail":
return VcSpinnerTail;
default:
return VcSpinnerBars;
}
};
const onTooltipBeforeShow = (e) => {
if (positioning.value) {
e.cancel = true;
}
};
return () => {
if (canRender.value) {
const inner = [];
inner.push(
h(VcIcon, {
name: props.icon,
size: props.size
})
);
inner.push(h("div", null, props.label));
if (isPlainObject(props.tooltip)) {
inner.push(
h(
VcTooltip,
{
ref: tooltipRef,
onBeforeShow: onTooltipBeforeShow,
...props.tooltip
},
() => h("strong", null, myLocationTip.value)
)
);
} else {
inner.push(createCommentVNode("v-if"));
}
const renderContent = h(
"div",
{
ref: rootRef,
class: `vc-my-location ${positionState.classes.value} ${props.customClass}`,
style: rootStyle
},
[
h(
VcBtn,
{
ref: btnRef,
size: props.size,
flat: props.flat,
stack: props.stack,
round: props.round,
loading: positioning.value,
dense: true,
style: { color: props.color, background: props.background },
onClick: onHandleClick
},
{
default: () => inner,
loading: () => h(getLoadingCmp())
}
)
]
);
return !hasVcNavigation && props.teleportToViewer ? h(Teleport, { to: $services.viewer._element }, renderContent) : renderContent;
} else {
return createCommentVNode("v-if");
}
};
}
});
function prettifyCoordinates(longitude, latitude, options) {
const result = {
latitude: "",
longitude: "",
elevation: ""
};
const { defaultValue, defined } = Cesium;
const optionsDefaulted = defaultValue(options, {});
const decimal = defaultValue(optionsDefaulted.decimal, 5);
if (optionsDefaulted.rangeType === 0) {
result.latitude = Math.abs(latitude).toFixed(decimal) + "\xB0" + (latitude < 0 ? "S" : "N");
result.longitude = Math.abs(longitude).toFixed(decimal) + "\xB0" + (longitude < 0 ? "W" : "E");
} else if (optionsDefaulted.rangeType === 1) {
result.latitude = latitude.toFixed(decimal) + "\xB0";
result.longitude = longitude.toFixed(decimal) + "\xB0";
} else if (optionsDefaulted.rangeType === 2) {
result.latitude = latitude.toFixed(decimal) + "\xB0";
result.longitude = (longitude < 0 ? 360 + longitude : longitude).toFixed(decimal) + "\xB0";
}
if (defined(optionsDefaulted.height)) {
result.elevation = Math.round(optionsDefaulted.height) + (defined(optionsDefaulted.errorBar) ? "\xB1" + Math.round(optionsDefaulted.errorBar) : "") + "m";
} else {
result.elevation = "";
}
return result;
}
function globals(defs) {
defs('EPSG:4326', "+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees");
defs('EPSG:4269', "+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees");
defs('EPSG:3857', "+title=WGS 84 / Pseudo-Mercator +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs");
defs.WGS84 = defs['EPSG:4326'];
defs['EPSG:3785'] = defs['EPSG:3857']; // maintain backward compat, official code is 3857
defs.GOOGLE = defs['EPSG:3857'];
defs['EPSG:900913'] = defs['EPSG:3857'];
defs['EPSG:102113'] = defs['EPSG:3857'];
}
var PJD_3PARAM = 1;
var PJD_7PARAM = 2;
var PJD_GRIDSHIFT = 3;
var PJD_WGS84 = 4; // WGS84 or equivalent
var PJD_NODATUM = 5; // WGS84 or equivalent
var SRS_WGS84_SEMIMAJOR = 6378137.0; // only used in grid shift transforms
var SRS_WGS84_SEMIMINOR = 6356752.314; // only used in grid shift transforms
var SRS_WGS84_ESQUARED = 0.0066943799901413165; // only used in grid shift transforms
var SEC_TO_RAD = 4.84813681109535993589914102357e-6;
var HALF_PI = Math.PI/2;
// ellipoid pj_set_ell.c
var SIXTH = 0.1666666666666666667;
/* 1/6 */
var RA4 = 0.04722222222222222222;
/* 17/360 */
var RA6 = 0.02215608465608465608;
var EPSLN = 1.0e-10;
// you'd think you could use Number.EPSILON above but that makes
// Mollweide get into an infinate loop.
var D2R$1 = 0.01745329251994329577;
var R2D = 57.29577951308232088;
var FORTPI = Math.PI/4;
var TWO_PI = Math.PI * 2;
// SPI is slightly greater than Math.PI, so values that exceed the -180..180
// degree range by a tiny amount don't get wrapped. This prevents points that
// have drifted from their original location along the 180th meridian (due to
// floating point error) from changing their sign.
var SPI = 3.14159265359;
var exports$3 = {};
exports$3.greenwich = 0.0; //"0dE",
exports$3.lisbon = -9.131906111111; //"9d07'54.862\"W",
exports$3.paris = 2.337229166667; //"2d20'14.025\"E",
exports$3.bogota = -74.080916666667; //"74d04'51.3\"W",
exports$3.madrid = -3.687938888889; //"3d41'16.58\"W",
exports$3.rome = 12.452333333333; //"12d27'8.4\"E",
exports$3.bern = 7.439583333333; //"7d26'22.5\"E",
exports$3.jakarta = 106.807719444444; //"106d48'27.79\"E",
exports$3.ferro = -17.666666666667; //"17d40'W",
exports$3.brussels = 4.367975; //"4d22'4.71\"E",
exports$3.stockholm = 18.058277777778; //"18d3'29.8\"E",
exports$3.athens = 23.7163375; //"23d42'58.815\"E",
exports$3.oslo = 10.722916666667; //"10d43'22.5\"E"
var units = {
ft: {to_meter: 0.3048},
'us-ft': {to_meter: 1200 / 3937}
};
var ignoredChar = /[\s_\-\/\(\)]/g;
function match(obj, key) {
if (obj[key]) {
return obj[key];
}
var keys = Object.keys(obj);
var lkey = key.toLowerCase().replace(ignoredChar, '');
var i = -1;
var testkey, processedKey;
while (++i < keys.length) {
testkey = keys[i];
processedKey = testkey.toLowerCase().replace(ignoredChar, '');
if (processedKey === lkey) {
return obj[testkey];
}
}
}
function projStr(defData) {
var self = {};
var paramObj = defData.split('+').map(function(v) {
return v.trim();
}).filter(function(a) {
return a;
}).reduce(function(p, a) {
var split = a.split('=');
split.push(true);
p[split[0].toLowerCase()] = split[1];
return p;
}, {});
var paramName, paramVal, paramOutname;
var params = {
proj: 'projName',
datum: 'datumCode',
rf: function(v) {
self.rf = parseFloat(v);
},
lat_0: function(v) {
self.lat0 = v * D2R$1;
},
lat_1: function(v) {
self.lat1 = v * D2R$1;
},
lat_2: function(v) {
self.lat2 = v * D2R$1;
},
lat_ts: function(v) {
self.lat_ts = v * D2R$1;
},
lon_0: function(v) {
self.long0 = v * D2R$1;
},
lon_1: function(v) {
self.long1 = v * D2R$1;
},
lon_2: function(v) {
self.long2 = v * D2R$1;
},
alpha: function(v) {
self.alpha = parseFloat(v) * D2R$1;
},
gamma: function(v) {
self.rectified_grid_angle = parseFloat(v);
},
lonc: function(v) {
self.longc = v * D2R$1;
},
x_0: function(v) {
self.x0 = parseFloat(v);
},
y_0: function(v) {
self.y0 = parseFloat(v);
},
k_0: function(v) {
self.k0 = parseFloat(v);
},
k: function(v) {
self.k0 = parseFloat(v);
},
a: function(v) {
self.a = parseFloat(v);
},
b: function(v) {
self.b = parseFloat(v);
},
r_a: function() {
self.R_A = true;
},
zone: function(v) {
self.zone = parseInt(v, 10);
},
south: function() {
self.utmSouth = true;
},
towgs84: function(v) {
self.datum_params = v.split(",").map(function(a) {
return parseFloat(a);
});
},
to_meter: function(v) {
self.to_meter = parseFloat(v);
},
units: function(v) {
self.units = v;
var unit = match(units, v);
if (unit) {
self.to_meter = unit.to_meter;
}
},
from_greenwich: function(v) {
self.from_greenwich = v * D2R$1;
},
pm: function(v) {
var pm = match(exports$3, v);
self.from_greenwich = (pm ? pm : parseFloat(v)) * D2R$1;
},
nadgrids: function(v) {
if (v === '@null') {
self.datumCode = 'none';
}
else {
self.nadgrids = v;
}
},
axis: function(v) {
var legalAxis = "ewnsud";
if (v.length === 3 && legalAxis.indexOf(v.substr(0, 1)) !== -1 && legalAxis.indexOf(v.substr(1, 1)) !== -1 && legalAxis.indexOf(v.substr(2, 1)) !== -1) {
self.axis = v;
}
},
approx: function() {
self.approx = true;
}
};
for (paramName in paramObj) {
paramVal = paramObj[paramName];
if (paramName in params) {
paramOutname = params[paramName];
if (typeof paramOutname === 'function') {
paramOutname(paramVal);
}
else {
self[paramOutname] = paramVal;
}
}
else {
self[paramName] = paramVal;
}
}
if(typeof self.datumCode === 'string' && self.datumCode !== "WGS84"){
self.datumCode = self.datumCode.toLowerCase();
}
return self;
}
var NEUTRAL = 1;
var KEYWORD = 2;
var NUMBER = 3;
var QUOTED = 4;
var AFTERQUOTE = 5;
var ENDED = -1;
var whitespace = /\s/;
var latin = /[A-Za-z]/;
var keyword = /[A-Za-z84_]/;
var endThings = /[,\]]/;
var digets = /[\d\.E\-\+]/;
// const ignoredChar = /[\s_\-\/\(\)]/g;
function Parser(text) {
if (typeof text !== 'string') {
throw new Error('not a string');
}
this.text = text.trim();
this.level = 0;
this.place = 0;
this.root = null;
this.stack = [];
this.currentObject = null;
this.state = NEUTRAL;
}
Parser.prototype.readCharicter = function() {
var char = this.text[this.place++];
if (this.state !== QUOTED) {
while (whitespace.test(char)) {
if (this.place >= this.text.length) {
return;
}
char = this.text[this.place++];
}
}
switch (this.state) {
case NEUTRAL:
return this.neutral(char);
case KEYWORD:
return this.keyword(char)
case QUOTED:
return this.quoted(char);
case AFTERQUOTE:
return this.afterquote(char);
case NUMBER:
return this.number(char);
case ENDED:
return;
}
};
Parser.prototype.afterquote = function(char) {
if (char === '"') {
this.word += '"';
this.state = QUOTED;
return;
}
if (endThings.test(char)) {
this.word = this.word.trim();
this.afterItem(char);
return;
}
throw new Error('havn\'t handled "' +char + '" in afterquote yet, index ' + this.place);
};
Parser.prototype.afterItem = function(char) {
if (char === ',') {
if (this.word !== null) {
this.currentObject.push(this.word);
}
this.word = null;
this.state = NEUTRAL;
return;
}
if (char === ']') {
this.level--;
if (this.word !== null) {
this.currentObject.push(this.word);
this.word = null;
}
this.state = NEUTRAL;
this.currentObject = this.stack.pop();
if (!this.currentObject) {
this.state = ENDED;
}
return;
}
};
Parser.prototype.number = function(char) {
if (digets.test(char)) {
this.word += char;
return;
}
if (endThings.test(char)) {
this.word = parseFloat(this.word);
this.afterItem(char);
return;
}
throw new Error('havn\'t handled "' +char + '" in number yet, index ' + this.place);
};
Parser.prototype.quoted = function(char) {
if (char === '"') {
this.state = AFTERQUOTE;
return;
}
this.word += char;
return;
};
Parser.prototype.keyword = function(char) {
if (keyword.test(char)) {
this.word += char;
return;
}
if (char === '[') {
var newObjects = [];
newObjects.push(this.word);
this.level++;
if (this.root === null) {
this.root = newObjects;
} else {
this.currentObject.push(newObjects);
}
this.stack.push(this.currentObject);
this.currentObject = newObjects;
this.state = NEUTRAL;
return;
}
if (endThings.test(char)) {
this.afterItem(char);
return;
}
throw new Error('havn\'t handled "' +char + '" in keyword yet, index ' + this.place);
};
Parser.prototype.neutral = function(char) {
if (latin.test(char)) {
this.word = char;
this.state = KEYWORD;
return;
}
if (char === '"') {
this.word = '';
this.state = QUOTED;
return;
}
if (digets.test(char)) {
this.word = char;
this.state = NUMBER;
return;
}
if (endThings.test(char)) {
this.afterItem(char);
return;
}
throw new Error('havn\'t handled "' +char + '" in neutral yet, index ' + this.place);
};
Parser.prototype.output = function() {
while (this.place < this.text.length) {
this.readCharicter();
}
if (this.state === ENDED) {
return this.root;
}
throw new Error('unable to parse string "' +this.text + '". State is ' + this.state);
};
function parseString(txt) {
var parser = new Parser(txt);
return parser.output();
}
function mapit(obj, key, value) {
if (Array.isArray(key)) {
value.unshift(key);
key = null;
}
var thing = key ? {} : obj;
var out = value.reduce(function(newObj, item) {
sExpr(item, newObj);
return newObj
}, thing);
if (key) {
obj[key] = out;
}
}
function sExpr(v, obj) {
if (!Array.isArray(v)) {
obj[v] = true;
return;
}
var key = v.shift();
if (key === 'PARAMETER') {
key = v.shift();
}
if (v.length === 1) {
if (Array.isArray(v[0])) {
obj[key] = {};
sExpr(v[0], obj[key]);
return;
}
obj[key] = v[0];
return;
}
if (!v.length) {
obj[key] = true;
return;
}
if (key === 'TOWGS84') {
obj[key] = v;
return;
}
if (key === 'AXIS') {
if (!(key in obj)) {
obj[key] = [];
}
obj[key].push(v);
return;
}
if (!Array.isArray(key)) {
obj[key] = {};
}
var i;
switch (key) {
case 'UNIT':
case 'PRIMEM':
case 'VERT_DATUM':
obj[key] = {
name: v[0].toLowerCase(),
convert: v[1]
};
if (v.length === 3) {
sExpr(v[2], obj[key]);
}
return;
case 'SPHEROID':
case 'ELLIPSOID':
obj[key] = {
name: v[0],
a: v[1],
rf: v[2]
};
if (v.length === 4) {
sExpr(v[3], obj[key]);
}
return;
case 'PROJECTEDCRS':
case 'PROJCRS':
case 'GEOGCS':
case 'GEOCCS':
case 'PROJCS':
case 'LOCAL_CS':
case 'GEODCRS':
case 'GEODETICCRS':
case 'GEODETICDATUM':
case 'EDATUM':
case 'ENGINEERINGDATUM':
case 'VERT_CS':
case 'VERTCRS':
case 'VERTICALCRS':
case 'COMPD_CS':
case 'COMPOUNDCRS':
case 'ENGINEERINGCRS':
case 'ENGCRS':
case 'FITTED_CS':
case 'LOCAL_DATUM':
case 'DATUM':
v[0] = ['name', v[0]];
mapit(obj, key, v);
return;
default:
i = -1;
while (++i < v.length) {
if (!Array.isArray(v[i])) {
return sExpr(v, obj[key]);
}
}
return mapit(obj, key, v);
}
}
var D2R = 0.01745329251994329577;
function rename(obj, params) {
var outName = params[0];
var inName = params[1];
if (!(outName in obj) && (inName in obj)) {
obj[outName] = obj[inName];
if (params.length === 3) {
obj[outName] = params[2](obj[outName]);
}
}
}
function d2r(input) {
return input * D2R;
}
function cleanWKT(wkt) {
if (wkt.type === 'GEOGCS') {
wkt.projName = 'longlat';
} else if (wkt.type === 'LOCAL_CS') {
wkt.projName = 'identity';
wkt.local = true;
} else {
if (typeof wkt.PROJECTION === 'object') {
wkt.projName = Object.keys(wkt.PROJECTION)[0];
} else {
wkt.projName = wkt.PROJECTION;
}
}
if (wkt.AXIS) {
var axisOrder = '';
for (var i = 0, ii = wkt.AXIS.length; i < ii; ++i) {
var axis = [wkt.AXIS[i][0].toLowerCase(), wkt.AXIS[i][1].toLowerCase()];
if (axis[0].indexOf('north') !== -1 || ((axis[0] === 'y' || axis[0] === 'lat') && axis[1] === 'north')) {
axisOrder += 'n';
} else if (axis[0].indexOf('south') !== -1 || ((axis[0] === 'y' || axis[0] === 'lat') && axis[1] === 'south')) {
axisOrder += 's';
} else if (axis[0].indexOf('east') !== -1 || ((axis[0] === 'x' || axis[0] === 'lon') && axis[1] === 'east')) {
axisOrder += 'e';
} else if (axis[0].indexOf('west') !== -1 || ((axis[0] === 'x' || axis[0] === 'lon') && axis[1] === 'west')) {
axisOrder += 'w';
}
}
if (axisOrder.length === 2) {
axisOrder += 'u';
}
if (axisOrder.length === 3) {
wkt.axis = axisOrder;
}
}
if (wkt.UNIT) {
wkt.units = wkt.UNIT.name.toLowerCase();
if (wkt.units === 'metre') {
wkt.units = 'meter';
}
if (wkt.UNIT.convert) {
if (wkt.type === 'GEOGCS') {
if (wkt.DATUM && wkt.DATUM.SPHEROID) {
wkt.to_meter = wkt.UNIT.convert*wkt.DATUM.SPHEROID.a;
}
} else {
wkt.to_meter = wkt.UNIT.convert;
}
}
}
var geogcs = wkt.GEOGCS;
if (wkt.type === 'GEOGCS') {
geogcs = wkt;
}
if (geogcs) {
//if(wkt.GEOGCS.PRIMEM&&wkt.GEOGCS.PRIMEM.convert){
// wkt.from_greenwich=wkt.GEOGCS.PRIMEM.convert*D2R;
//}
if (geogcs.DATUM) {
wkt.datumCode = geogcs.DATUM.name.toLowerCase();
} else {
wkt.datumCode = geogcs.name.toLowerCase();
}
if (wkt.datumCode.slice(0, 2) === 'd_') {
wkt.datumCode = wkt.datumCode.slice(2);
}
if (wkt.datumCode === 'new_zealand_geodetic_datum_1949' || wkt.datumCode === 'new_zealand_1949') {
wkt.datumCode = 'nzgd49';
}
if (wkt.datumCode === 'wgs_1984' || wkt.datumCode === 'world_geodetic_system_1984') {
if (wkt.PROJECTION === 'Mercator_Auxiliary_Sphere') {
wkt.sphere = true;
}
wkt.datumCode = 'wgs84';
}
if (wkt.datumCode.slice(-6) === '_ferro') {
wkt.datumCode = wkt.datumCode.slice(0, - 6);
}
if (wkt.datumCode.slice(-8) === '_jakarta') {
wkt.datumCode = wkt.datumCode.slice(0, - 8);
}
if (~wkt.datumCode.indexOf('belge')) {
wkt.datumCode = 'rnb72';
}
if (geogcs.DATUM && geogcs.DATUM.SPHEROID) {
wkt.ellps = geogcs.DATUM.SPHEROID.name.replace('_19', '').replace(/[Cc]larke\_18/, 'clrk');
if (wkt.ellps.toLowerCase().slice(0, 13) === 'international') {
wkt.ellps = 'intl';
}
wkt.a = geogcs.DATUM.SPHEROID.a;
wkt.rf = parseFloat(geogcs.DATUM.SPHEROID.rf, 10);
}
if (geogcs.DATUM && geogcs.DATUM.TOWGS84) {
wkt.datum_params = geogcs.DATUM.TOWGS84;
}
if (~wkt.datumCode.indexOf('osgb_1936')) {
wkt.datumCode = 'osgb36';
}
if (~wkt.datumCode.indexOf('osni_1952')) {
wkt.datumCode = 'osni52';
}
if (~wkt.datumCode.indexOf('tm65')
|| ~wkt.datumCode.indexOf('geodetic_datum_of_1965')) {
wkt.datumCode = 'ire65';
}
if (wkt.datumCode === 'ch1903+') {
wkt.datumCode = 'ch1903';
}
if (~wkt.datumCode.indexOf('israel')) {
wkt.datumCode = 'isr93';
}
}
if (wkt.b && !isFinite(wkt.b)) {
wkt.b = wkt.a;
}
function toMeter(input) {
var ratio = wkt.to_meter || 1;
return input * ratio;
}
var renamer = function(a) {
return rename(wkt, a);
};
var list = [
['standard_parallel_1', 'Standard_Parallel_1'],
['standard_parallel_1', 'Latitude of 1st standard parallel'],
['standard_parallel_2', 'Standard_Parallel_2'],
['standard_parallel_2', 'Latitude of 2nd standard parallel'],
['false_easting', 'False_Easting'],
['false_easting', 'False easting'],
['false-easting', 'Easting at false origin'],
['false_northing', 'False_Northing'],
['false_northing', 'False northing'],
['false_northing', 'Northing at false origin'],
['central_meridian', 'Central_Meridian'],
['central_meridian', 'Longitude of natural origin'],
['central_meridian', 'Longitude of false origin'],
['latitude_of_origin', 'Latitude_Of_Origin'],
['latitude_of_origin', 'Central_Parallel'],
['latitude_of_origin', 'Latitude of natural origin'],
['latitude_of_origin', 'Latitude of false origin'],
['scale_factor', 'Scale_Factor'],
['k0', 'scale_factor'],
['latitude_of_center', 'Latitude_Of_Center'],
['latitude_of_center', 'Latitude_of_center'],
['lat0', 'latitude_of_center', d2r],
['longitude_of_center', 'Longitude_Of_Center'],
['longitude_of_center', 'Longitude_of_center'],
['longc', 'longitude_of_center', d2r],
['x0', 'false_easting', toMeter],
['y0', 'false_northing', toMeter],
['long0', 'central_meridian', d2r],
['lat0', 'latitude_of_origin', d2r],
['lat0', 'standard_parallel_1', d2r],
['lat1', 'standard_parallel_1', d2r],
['lat2', 'standard_parallel_2', d2r],
['azimuth', 'Azimuth'],
['alpha', 'azimuth', d2r],
['srsCode', 'name']
];
list.forEach(renamer);
if (!wkt.long0 && wkt.longc && (wkt.projName === 'Albers_Conic_Equal_Area' || wkt.projName === 'Lambert_Azimuthal_Equal_Area')) {
wkt.long0 = wkt.longc;
}
if (!wkt.lat_ts && wkt.lat1 && (wkt.projName === 'Stereographic_South_Pole' || wkt.projName === 'Polar Stereographic (variant B)')) {
wkt.lat0 = d2r(wkt.lat1 > 0 ? 90 : -90);
wkt.lat_ts = wkt.lat1;
} else if (!wkt.lat_ts && wkt.lat0 && wkt.projName === 'Polar_Stereographic') {
wkt.lat_ts = wkt.lat0;
wkt.lat0 = d2r(wkt.lat0 > 0 ? 90 : -90);
}
}
function wkt(wkt) {
var lisp = parseString(wkt);
var type = lisp.shift();
var name = lisp.shift();
lisp.unshift(['name', name]);
lisp.unshift(['type', type]);
var obj = {};
sExpr(lisp, obj);
cleanWKT(obj);
return obj;
}
function defs(name) {
/*global console*/
var that = this;
if (arguments.length === 2) {
var def = arguments[1];
if (typeof def === 'string') {
if (def.charAt(0) === '+') {
defs[name] = projStr(arguments[1]);
}
else {
defs[name] = wkt(arguments[1]);
}
} else {
defs[name] = def;
}
}
else if (arguments.length === 1) {
if (Array.isArray(name)) {
return name.map(function(v) {
if (Array.isArray(v)) {
defs.apply(that, v);
}
else {
defs(v);
}
});
}
else if (typeof name === 'string') {
if (name in defs) {
return defs[name];
}
}
else if ('EPSG' in name) {
defs['EPSG:' + name.EPSG] = name;
}
else if ('ESRI' in name) {
defs['ESRI:' + name.ESRI] = name;
}
else if ('IAU2000' in name) {
defs['IAU2000:' + name.IAU2000] = name;
}
else {
console.log(name);
}
return;
}
}
globals(defs);
function testObj(code){
return typeof code === 'string';
}
function testDef(code){
return code in defs;
}
var codeWords = ['PROJECTEDCRS', 'PROJCRS', 'GEOGCS','GEOCCS','PROJCS','LOCAL_CS', 'GEODCRS', 'GEODETICCRS', 'GEODETICDATUM', 'ENGCRS', 'ENGINEERINGCRS'];
function testWKT(code){
return codeWords.some(function (word) {
return code.indexOf(word) > -1;
});
}
var codes = ['3857', '900913', '3785', '102113'];
function checkMercator(item) {
var auth = match(item, 'authority');
if (!auth) {
return;
}
var code = match(auth, 'epsg');
return code && codes.indexOf(code) > -1;
}
function checkProjStr(item) {
var ext = match(item, 'extension');
if (!ext) {
return;
}
return match(ext, 'proj4');
}
function testProj(code){
return code[0] === '+';
}
function parse(code){
if (testObj(code)) {
//check to see if this is a WKT string
if (testDef(code)) {
return defs[code];
}
if (testWKT(code)) {
var out = wkt(code);
// test of spetial case, due to this being a very common and often malformed
if (checkMercator(out)) {
return defs['EPSG:3857'];
}
var maybeProjStr = checkProjStr(out);
if (maybeProjStr) {
return projStr(maybeProjStr);
}
return out;
}
if (testProj(code)) {
return projStr(code);
}
}else {
return code;
}
}
function extend(destination, source) {
destination = destination || {};
var value, property;
if (!source) {
return destination;
}
for (property in source) {
value = source[property];
if (value !== undefined) {
destination[property] = value;
}
}
return destination;
}
function msfnz(eccent, sinphi, cosphi) {
var con = eccent * sinphi;
return cosphi / (Math.sqrt(1 - con * con));
}
function sign(x) {
return x<0 ? -1 : 1;
}
function adjust_lon(x) {
return (Math.abs(x) <= SPI) ? x : (x - (sign(x) * TWO_PI));
}
function tsfnz(eccent, phi, sinphi) {
var con = eccent * sinphi;
var com = 0.5 * eccent;
con = Math.pow(((1 - con) / (1 + con)), com);
return (Math.tan(0.5 * (HALF_PI - phi)) / con);
}
function phi2z(eccent, ts) {
var eccnth = 0.5 * eccent;
var con, dphi;
var phi = HALF_PI - 2 * Math.atan(ts);
for (var i = 0; i <= 15; i++) {
con = eccent * Math.sin(phi);
dphi = HALF_PI - 2 * Math.atan(ts * (Math.pow(((1 - con) / (1 + con)), eccnth))) - phi;
phi += dphi;
if (Math.abs(dphi) <= 0.0000000001) {
return phi;
}
}
//console.log("phi2z has NoConvergence");
return -9999;
}
function init$w() {
var con = this.b / this.a;
this.es = 1 - con * con;
if(!('x0' in this)){
this.x0 = 0;
}
if(!('y0' in this)){
this.y0 = 0;
}
this.e = Math.sqrt(this.es);
if (this.lat_ts) {
if (this.sphere) {
this.k0 = Math.cos(this.lat_ts);
}
else {
this.k0 = msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts));
}
}
else {
if (!this.k0) {
if (this.k) {
this.k0 = this.k;
}
else {
this.k0 = 1;
}
}
}
}
/* Mercator forward equations--mapping lat,long to x,y
--------------------------------------------------*/
function forward$u(p) {
var lon = p.x;
var lat = p.y;
// convert to radians
if (lat * R2D > 90 && lat * R2D < -90 && lon * R2D > 180 && lon * R2D < -180) {
return null;
}
var x, y;
if (Math.abs(Math.abs(lat) - HALF_PI) <= EPSLN) {
return null;
}
else {
if (this.sphere) {
x = this.x0 + this.a * this.k0 * adjust_lon(lon - this.long0);
y = this.y0 + this.a * this.k0 * Math.log(Math.tan(FORTPI + 0.5 * lat));
}
else {
var sinphi = Math.sin(lat);
var ts = tsfnz(this.e, lat, sinphi);
x = this.x0 + this.a * this.k0 * adjust_lon(lon - this.long0);
y = this.y0 - this.a * this.k0 * Math.log(ts);
}
p.x = x;
p.y = y;
return p;
}
}
/* Mercator inverse equations--mapping x,y to lat/long
--------------------------------------------------*/
function inverse$u(p) {
var x = p.x - this.x0;
var y = p.y - this.y0;
var lon, lat;
if (this.sphere) {
lat = HALF_PI - 2 * Math.atan(Math.exp(-y / (this.a * this.k0)));
}
else {
var ts = Math.exp(-y / (this.a * this.k0));
lat = phi2z(this.e, ts);
if (lat === -9999) {
return null;
}
}
lon = adjust_lon(this.long0 + x / (this.a * this.k0));
p.x = lon;
p.y = lat;
return p;
}
var names$w = ["Mercator", "Popular Visualisation Pseudo Mercator", "Mercator_1SP", "Mercator_Auxiliary_Sphere", "merc"];
var merc = {
init: init$w,
forward: forward$u,
inverse: inverse$u,
names: names$w
};
function init$v() {
//no-op for longlat
}
function identity(pt) {
return pt;
}
var names$v = ["longlat", "identity"];
var longlat = {
init: init$v,
forward: identity,
inverse: identity,
names: names$v
};
var projs = [merc, longlat];
var names$u = {};
var projStore = [];
function add(proj, i) {
var len = projStore.length;
if (!proj.names) {
console.log(i);
return true;
}
projStore[len] = proj;
proj.names.forEach(function(n) {
names$u[n.toLowerCase()] = len;
});
return this;
}
function get(name) {
if (!name) {
return false;
}
var n = name.toLowerCase();
if (typeof names$u[n] !== 'undefined' && projStore[names$u[n]]) {
return projStore[names$u[n]];
}
}
function start() {
projs.forEach(add);
}
var projections = {
start: start,
add: add,
get: get
};
var exports$2 = {};
exports$2.MERIT = {
a: 6378137.0,
rf: 298.257,
ellipseName: "MERIT 1983"
};
exports$2.SGS85 = {
a: 6378136.0,
rf: 298.257,
ellipseName: "Soviet Geodetic System 85"
};
exports$2.GRS80 = {
a: 6378137.0,
rf: 298.257222101,
ellipseName: "GRS 1980(IUGG, 1980)"
};
exports$2.IAU76 = {
a: 6378140.0,
rf: 298.257,
ellipseName: "IAU 1976"
};
exports$2.airy = {
a: 6377563.396,
b: 6356256.910,
ellipseName: "Airy 1830"
};
exports$2.APL4 = {
a: 6378137,
rf: 298.25,
ellipseName: "Appl. Physics. 1965"
};
exports$2.NWL9D = {
a: 6378145.0,
rf: 298.25,
ellipseName: "Naval Weapons Lab., 1965"
};
exports$2.mod_airy = {
a: 6377340.189,
b: 6356034.446,
ellipseName: "Modified Airy"
};
exports$2.andrae = {
a: 6377104.43,
rf: 300.0,
ellipseName: "Andrae 1876 (Den., Iclnd.)"
};
exports$2.aust_SA = {
a: 6378160.0,
rf: 298.25,
ellipseName: "Australian Natl & S. Amer. 1969"
};
exports$2.GRS67 = {
a: 6378160.0,
rf: 298.2471674270,
ellipseName: "GRS 67(IUGG 1967)"
};
exports$2.bessel = {
a: 6377397.155,
rf: 299.1528128,
ellipseName: "Bessel 1841"
};
exports$2.bess_nam = {
a: 6377483.865,
rf: 299.1528128,
ellipseName: "Bessel 1841 (Namibia)"
};
exports$2.clrk66 = {
a: 6378206.4,
b: 6356583.8,
ellipseName: "Clarke 1866"
};
exports$2.clrk80 = {
a: 6378249.145,
rf: 293.4663,
ellipseName: "Clarke 1880 mod."
};
exports$2.clrk80ign = {
a: 6378249.2,
b: 6356515,
rf: 293.4660213,
ellipseName: "Clarke 1880 (IGN)"
};
exports$2.clrk58 = {
a: 6378293.645208759,
rf: 294.2606763692654,
ellipseName: "Clarke 1858"
};
exports$2.CPM = {
a: 6375738.7,
rf: 334.29,
ellipseName: "Comm. des Poids et Mesures 1799"
};
exports$2.delmbr = {
a: 6376428.0,
rf: 311.5,
ellipseName: "Delambre 1810 (Belgium)"
};
exports$2.engelis = {
a: 6378136.05,
rf: 298.2566,
ellipseName: "Engelis 1985"
};
exports$2.evrst30 = {
a: 6377276.345,
rf: 300.8017,
ellipseName: "Everest 1830"
};
exports$2.evrst48 = {
a: 6377304.063,
rf: 300.8017,
ellipseName: "Everest 1948"
};
exports$2.evrst56 = {
a: 6377301.243,
rf: 300.8017,
ellipseName: "Everest 1956"
};
exports$2.evrst69 = {
a: 6377295.664,
rf: 300.8017,
ellipseName: "Everest 1969"
};
exports$2.evrstSS = {
a: 6377298.556,
rf: 300.8017,
ellipseName: "Everest (Sabah & Sarawak)"
};
exports$2.fschr60 = {
a: 6378166.0,
rf: 298.3,
ellipseName: "Fischer (Mercury Datum) 1960"
};
exports$2.fschr60m = {
a: 6378155.0,
rf: 298.3,
ellipseName: "Fischer 1960"
};
exports$2.fschr68 = {
a: 6378150.0,
rf: 298.3,
ellipseName: "Fischer 1968"
};
exports$2.helmert = {
a: 6378200.0,
rf: 298.3,
ellipseName: "Helmert 1906"
};
exports$2.hough = {
a: 6378270.0,
rf: 297.0,
ellipseName: "Hough"
};
exports$2.intl = {
a: 6378388.0,
rf: 297.0,
ellipseName: "International 1909 (Hayford)"
};
exports$2.kaula = {
a: 6378163.0,
rf: 298.24,
ellipseName: "Kaula 1961"
};
exports$2.lerch = {
a: 6378139.0,
rf: 298.257,
ellipseName: "Lerch 1979"
};
exports$2.mprts = {
a: 6397300.0,
rf: 191.0,
ellipseName: "Maupertius 1738"
};
exports$2.new_intl = {
a: 6378157.5,
b: 6356772.2,
ellipseName: "New International 1967"
};
exports$2.plessis = {
a: 6376523.0,
rf: 6355863.0,
ellipseName: "Plessis 1817 (France)"
};
exports$2.krass = {
a: 6378245.0,
rf: 298.3,
ellipseName: "Krassovsky, 1942"
};
exports$2.SEasia = {
a: 6378155.0,
b: 6356773.3205,
ellipseName: "Southeast Asia"
};
exports$2.walbeck = {
a: 6376896.0,
b: 6355834.8467,
ellipseName: "Walbeck"
};
exports$2.WGS60 = {
a: 6378165.0,
rf: 298.3,
ellipseName: "WGS 60"
};
exports$2.WGS66 = {
a: 6378145.0,
rf: 298.25,
ellipseName: "WGS 66"
};
exports$2.WGS7 = {
a: 6378135.0,
rf: 298.26,
ellipseName: "WGS 72"
};
var WGS84 = exports$2.WGS84 = {
a: 6378137.0,
rf: 298.257223563,
ellipseName: "WGS 84"
};
exports$2.sphere = {
a: 6370997.0,
b: 6370997.0,
ellipseName: "Normal Sphere (r=6370997)"
};
function eccentricity(a, b, rf, R_A) {
var a2 = a * a; // used in geocentric
var b2 = b * b; // used in geocentric
var es = (a2 - b2) / a2; // e ^ 2
var e = 0;
if (R_A) {
a *= 1 - es * (SIXTH + es * (RA4 + es * RA6));
a2 = a * a;
es = 0;
} else {
e = Math.sqrt(es); // eccentricity
}
var ep2 = (a2 - b2) / b2; // used in geocentric
return {
es: es,
e: e,
ep2: ep2
};
}
function sphere(a, b, rf, ellps, sphere) {
if (!a) { // do we have an ellipsoid?
var ellipse = match(exports$2, ellps);
if (!ellipse) {
ellipse = WGS84;
}
a = ellipse.a;
b = ellipse.b;
rf = ellipse.rf;
}
if (rf && !b) {
b = (1.0 - 1.0 / rf) * a;
}
if (rf === 0 || Math.abs(a - b) < EPSLN) {
sphere = true;
b = a;
}
return {
a: a,
b: b,
rf: rf,
sphere: sphere
};
}
var exports$1 = {};
exports$1.wgs84 = {
towgs84: "0,0,0",
ellipse: "WGS84",
datumName: "WGS84"
};
exports$1.ch1903 = {
towgs84: "674.374,15.056,405.346",
ellipse: "bessel",
datumName: "swiss"
};
exports$1.ggrs87 = {
towgs84: "-199.87,74.79,246.62",
ellipse: "GRS80",
datumName: "Greek_Geodetic_Reference_System_1987"
};
exports$1.nad83 = {
towgs84: "0,0,0",
ellipse: "GRS80",
datumName: "North_American_Datum_1983"
};
exports$1.nad27 = {
nadgrids: "@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat",
ellipse: "clrk66",
datumName: "North_American_Datum_1927"
};
exports$1.potsdam = {
towgs84: "598.1,73.7,418.2,0.202,0.045,-2.455,6.7",
ellipse: "bessel",
datumName: "Potsdam Rauenberg 1950 DHDN"
};
exports$1.carthage = {
towgs84: "-263.0,6.0,431.0",
ellipse: "clark80",
datumName: "Carthage 1934 Tunisia"
};
exports$1.hermannskogel = {
towgs84: "577.326,90.129,463.919,5.137,1.474,5.297,2.4232",
ellipse: "bessel",
datumName: "Hermannskogel"
};
exports$1.osni52 = {
towgs84: "482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15",
ellipse: "airy",
datumName: "Irish National"
};
exports$1.ire65 = {
towgs84: "482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15",
ellipse: "mod_airy",
datumName: "Ireland 1965"
};
exports$1.rassadiran = {
towgs84: "-133.63,-157.5,-158.62",
ellipse: "intl",
datumName: "Rassadiran"
};
exports$1.nzgd49 = {
towgs84: "59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993",
ellipse: "intl",
datumName: "New Zealand Geodetic Datum 1949"
};
exports$1.osgb36 = {
towgs84: "446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894",
ellipse: "airy",
datumName: "Airy 1830"
};
exports$1.s_jtsk = {
towgs84: "589,76,480",
ellipse: 'bessel',
datumName: 'S-JTSK (Ferro)'
};
exports$1.beduaram = {
towgs84: '-106,-87,188',
ellipse: 'clrk80',
datumName: 'Beduaram'
};
exports$1.gunung_segara = {
towgs84: '-403,684,41',
ellipse: 'bessel',
datumName: 'Gunung Segara Jakarta'
};
exports$1.rnb72 = {
towgs84: "106.869,-52.2978,103.724,-0.33657,0.456955,-1.84218,1",
ellipse: "intl",
datumName: "Reseau National Belge 1972"
};
function datum(datumCode, datum_params, a, b, es, ep2, nadgrids) {
var out = {};
if (datumCode === undefined || datumCode === 'none') {
out.datum_type = PJD_NODATUM;
} else {
out.datum_type = PJD_WGS84;
}
if (datum_params) {
out.datum_params = datum_params.map(parseFloat);
if (out.datum_params[0] !== 0 || out.datum_params[1] !== 0 || out.datum_params[2] !== 0) {
out.datum_type = PJD_3PARAM;
}
if (out.datum_params.length > 3) {
if (out.datum_params[3] !== 0 || out.datum_params[4] !== 0 || out.datum_params[5] !== 0 || out.datum_params[6] !== 0) {
out.datum_type = PJD_7PARAM;
out.datum_params[3] *= SEC_TO_RAD;
out.datum_params[4] *= SEC_TO_RAD;
out.datum_params[5] *= SEC_TO_RAD;
out.datum_params[6] = (out.datum_params[6] / 1000000.0) + 1.0;
}
}
}
if (nadgrids) {
out.datum_type = PJD_GRIDSHIFT;
out.grids = nadgrids;
}
out.a = a; //datum object also uses these values
out.b = b;
out.es = es;
out.ep2 = ep2;
return out;
}
/**
* Resources for details of NTv2 file formats:
* - https://web.archive.org/web/20140127204822if_/http://www.mgs.gov.on.ca:80/stdprodconsume/groups/content/@mgs/@iandit/documents/resourcelist/stel02_047447.pdf
* - http://mimaka.com/help/gs/html/004_NTV2%20Data%20Format.htm
*/
var loadedNadgrids = {};
/**
* Load a binary NTv2 file (.gsb) to a key that can be used in a proj string like +nadgrids=<key>. Pass the NTv2 file
* as an ArrayBuffer.
*/
function nadgrid(key, data) {
var view = new DataView(data);
var isLittleEndian = detectLittleEndian(view);
var header = readHeader(view, isLittleEndian);
var subgrids = readSubgrids(view, header, isLittleEndian);
var nadgrid = {header: header, subgrids: subgrids};
loadedNadgrids[key] = nadgrid;
return nadgrid;
}
/**
* Given a proj4 value for nadgrids, return an array of loaded grids
*/
function getNadgrids(nadgrids) {
// Format details: http://proj.maptools.org/gen_parms.html
if (nadgrids === undefined) { return null; }
var grids = nadgrids.split(',');
return grids.map(parseNadgridString);
}
function parseNadgridString(value) {
if (value.length === 0) {
return null;
}
var optional = value[0] === '@';
if (optional) {
value = value.slice(1);
}
if (value === 'null') {
return {name: 'null', mandatory: !optional, grid: null, isNull: true};
}
return {
name: value,
mandatory: !optional,
grid: loadedNadgrids[value] || null,
isNull: false
};
}
function secondsToRadians(seconds) {
return (seconds / 3600) * Math.PI / 180;
}
function detectLittleEndian(view) {
var nFields = view.getInt32(8, false);
if (nFields === 11) {
return false;
}
nFields = view.getInt32(8, true);
if (nFields !== 11) {
console.warn('Failed to detect nadgrid endian-ness, defaulting to little-endian');
}
return true;
}
function readHeader(view, isLittleEndian) {
return {
nFields: view.getInt32(8, isLittleEndian),
nSubgridFields: view.getInt32(24, isLittleEndian),
nSubgrids: view.getInt32(40, isLittleEndian),
shiftType: decodeString(view, 56, 56 + 8).trim(),
fromSemiMajorAxis: view.getFloat64(120, isLittleEndian),
fromSemiMinorAxis: view.getFloat64(136, isLittleEndian),
toSemiMajorAxis: view.getFloat64(152, isLittleEndian),
toSemiMinorAxis: view.getFloat64(168, isLittleEndian),
};
}
function decodeString(view, start, end) {
return String.fromCharCode.apply(null, new Uint8Array(view.buffer.slice(start, end)));
}
function readSubgrids(view, header, isLittleEndian) {
var gridOffset = 176;
var grids = [];
for (var i = 0; i < header.nSubgrids; i++) {
var subHeader = readGridHeader(view, gridOffset, isLittleEndian);
var nodes = readGridNodes(view, gridOffset, subHeader, isLittleEndian);
var lngColumnCount = Math.round(
1 + (subHeader.upperLongitude - subHeader.lowerLongitude) / subHeader.longitudeInterval);
var latColumnCount = Math.round(
1 + (subHeader.upperLatitude - subHeader.lowerLatitude) / subHeader.latitudeInterval);
// Proj4 operates on radians whereas the coordinates are in seconds in the grid
grids.push({
ll: [secondsToRadians(subHeader.lowerLongitude), secondsToRadians(subHeader.lowerLatitude)],
del: [secondsToRadians(subHeader.longitudeInterval), secondsToRadians(subHeader.latitudeInterval)],
lim: [lngColumnCount, latColumnCount],
count: subHeader.gridNodeCount,
cvs: mapNodes(nodes)
});
gridOffset += 176 + subHeader.gridNodeCount * 16;
}
return grids;
}
function mapNodes(nodes) {
return nodes.map(function (r) {return [secondsToRadians(r.longitudeShift), secondsToRadians(r.latitudeShift)];});
}
function readGridHeader(view, offset, isLittleEndian) {
return {
name: decodeString(view, offset + 8, offset + 16).trim(),
parent: decodeString(view, offset + 24, offset + 24 + 8).trim(),
lowerLatitude: view.getFloat64(offset + 72, isLittleEndian),
upperLatitude: view.getFloat64(offset + 88, isLittleEndian),
lowerLongitude: view.getFloat64(offset + 104, isLittleEndian),
upperLongitude: view.getFloat64(offset + 120, isLittleEndian),
latitudeInterval: view.getFloat64(offset + 136, isLittleEndian),
longitudeInterval: view.getFloat64(offset + 152, isLittleEndian),
gridNodeCount: view.getInt32(offset + 168, isLittleEndian)
};
}
function readGridNodes(view, offset, gridHeader, isLittleEndian) {
var nodesOffset = offset + 176;
var gridRecordLength = 16;
var gridShiftRecords = [];
for (var i = 0; i < gridHeader.gridNodeCount; i++) {
var record = {
latitudeShift: view.getFloat32(nodesOffset + i * gridRecordLength, isLittleEndian),
longitudeShift: view.getFloat32(nodesOffset + i * gridRecordLength + 4, isLittleEndian),
latitudeAccuracy: view.getFloat32(nodesOffset + i * gridRecordLength + 8, isLittleEndian),
longitudeAccuracy: view.getFloat32(nodesOffset + i * gridRecordLength + 12, isLittleEndian),
};
gridShiftRecords.push(record);
}
return gridShiftRecords;
}
function Projection(srsCode,callback) {
if (!(this instanceof Projection)) {
return new Projection(srsCode);
}
callback = callback || function(error){
if(error){
throw error;
}
};
var json = parse(srsCode);
if(typeof json !== 'object'){
callback(srsCode);
return;
}
var ourProj = Projection.projections.get(json.projName);
if(!ourProj){
callback(srsCode);
return;
}
if (json.datumCode && json.datumCode !== 'none') {
var datumDef = match(exports$1, json.datumCode);
if (datumDef) {
json.datum_params = json.datum_params || (datumDef.towgs84 ? datumDef.towgs84.split(',') : null);
json.ellps = datumDef.ellipse;
json.datumName = datumDef.datumName ? datumDef.datumName : json.datumCode;
}
}
json.k0 = json.k0 || 1.0;
json.axis = json.axis || 'enu';
json.ellps = json.ellps || 'wgs84';
json.lat1 = json.lat1 || json.lat0; // Lambert_Conformal_Conic_1SP, for example, needs this
var sphere_ = sphere(json.a, json.b, json.rf, json.ellps, json.sphere);
var ecc = eccentricity(sphere_.a, sphere_.b, sphere_.rf, json.R_A);
var nadgrids = getNadgrids(json.nadgrids);
var datumObj = json.datum || datum(json.datumCode, json.datum_params, sphere_.a, sphere_.b, ecc.es, ecc.ep2,
nadgrids);
extend(this, json); // transfer everything over from the projection because we don't know what we'll need
extend(this, ourProj); // transfer all the methods from the projection
// copy the 4 things over we calculated in deriveConstants.sphere
this.a = sphere_.a;
this.b = sphere_.b;
this.rf = sphere_.rf;
this.sphere = sphere_.sphere;
// copy the 3 things we calculated in deriveConstants.eccentricity
this.es = ecc.es;
this.e = ecc.e;
this.ep2 = ecc.ep2;
// add in the datum object
this.datum = datumObj;
// init the projection
this.init();
// legecy callback from back in the day when it went to spatialreference.org
callback(null, this);
}
Projection.projections = projections;
Projection.projections.start();
function compareDatums(source, dest) {
if (source.datum_type !== dest.datum_type) {
return false; // false, datums are not equal
} else if (source.a !== dest.a || Math.abs(source.es - dest.es) > 0.000000000050) {
// the tolerance for es is to ensure that GRS80 and WGS84
// are considered identical
return false;
} else if (source.datum_type === PJD_3PARAM) {
return (source.datum_params[0] === dest.datum_params[0] && source.datum_params[1] === dest.datum_params[1] && source.datum_params[2] === dest.datum_params[2]);
} else if (source.datum_type === PJD_7PARAM) {
return (source.datum_params[0] === dest.datum_params[0] && source.datum_params[1] === dest.datum_params[1] && source.datum_params[2] === dest.datum_params[2] && source.datum_params[3] === dest.datum_params[3] && source.datum_params[4] === dest.datum_params[4] && source.datum_params[5] === dest.datum_params[5] && source.datum_params[6] === dest.datum_params[6]);
} else {
return true; // datums are equal
}
} // cs_compare_datums()
/*
* The function Convert_Geodetic_To_Geocentric converts geodetic coordinates
* (latitude, longitude, and height) to geocentric coordinates (X, Y, Z),
* according to the current ellipsoid parameters.
*
* Latitude : Geodetic latitude in radians (input)
* Longitude : Geodetic longitude in radians (input)
* Height : Geodetic height, in meters (input)
* X : Calculated Geocentric X coordinate, in meters (output)
* Y : Calculated Geocentric Y coordinate, in meters (output)
* Z : Calculated Geocentric Z coordinate, in meters (output)
*
*/
function geodeticToGeocentric(p, es, a) {
var Longitude = p.x;
var Latitude = p.y;
var Height = p.z ? p.z : 0; //Z value not always supplied
var Rn; /* Earth radius at location */
var Sin_Lat; /* Math.sin(Latitude) */
var Sin2_Lat; /* Square of Math.sin(Latitude) */
var Cos_Lat; /* Math.cos(Latitude) */
/*
** Don't blow up if Latitude is just a little out of the value
** range as it may just be a rounding issue. Also removed longitude
** test, it should be wrapped by Math.cos() and Math.sin(). NFW for PROJ.4, Sep/2001.
*/
if (Latitude < -HALF_PI && Latitude > -1.001 * HALF_PI) {
Latitude = -HALF_PI;
} else if (Latitude > HALF_PI && Latitude < 1.001 * HALF_PI) {
Latitude = HALF_PI;
} else if (Latitude < -HALF_PI) {
/* Latitude out of range */
//..reportError('geocent:lat out of range:' + Latitude);
return { x: -Infinity, y: -Infinity, z: p.z };
} else if (Latitude > HALF_PI) {
/* Latitude out of range */
return { x: Infinity, y: Infinity, z: p.z };
}
if (Longitude > Math.PI) {
Longitude -= (2 * Math.PI);
}
Sin_Lat = Math.sin(Latitude);
Cos_Lat = Math.cos(Latitude);
Sin2_Lat = Sin_Lat * Sin_Lat;
Rn = a / (Math.sqrt(1.0e0 - es * Sin2_Lat));
return {
x: (Rn + Height) * Cos_Lat * Math.cos(Longitude),
y: (Rn + Height) * Cos_Lat * Math.sin(Longitude),
z: ((Rn * (1 - es)) + Height) * Sin_Lat
};
} // cs_geodetic_to_geocentric()
function geocentricToGeodetic(p, es, a, b) {
/* local defintions and variables */
/* end-criterium of loop, accuracy of sin(Latitude) */
var genau = 1e-12;
var genau2 = (genau * genau);
var maxiter = 30;
var P; /* distance between semi-minor axis and location */
var RR; /* distance between center and location */
var CT; /* sin of geocentric latitude */
var ST; /* cos of geocentric latitude */
var RX;
var RK;
var RN; /* Earth radius at location */
var CPHI0; /* cos of start or old geodetic latitude in iterations */
var SPHI0; /* sin of start or old geodetic latitude in iterations */
var CPHI; /* cos of searched geodetic latitude */
var SPHI; /* sin of searched geodetic latitude */
var SDPHI; /* end-criterium: addition-theorem of sin(Latitude(iter)-Latitude(iter-1)) */
var iter; /* # of continous iteration, max. 30 is always enough (s.a.) */
var X = p.x;
var Y = p.y;
var Z = p.z ? p.z : 0.0; //Z value not always supplied
var Longitude;
var Latitude;
var Height;
P = Math.sqrt(X * X + Y * Y);
RR = Math.sqrt(X * X + Y * Y + Z * Z);
/* special cases for latitude and longitude */
if (P / a < genau) {
/* special case, if P=0. (X=0., Y=0.) */
Longitude = 0.0;
/* if (X,Y,Z)=(0.,0.,0.) then Height becomes semi-minor axis
* of ellipsoid (=center of mass), Latitude becomes PI/2 */
if (RR / a < genau) {
Latitude = HALF_PI;
Height = -b;
return {
x: p.x,
y: p.y,
z: p.z
};
}
} else {
/* ellipsoidal (geodetic) longitude
* interval: -PI < Longitude <= +PI */
Longitude = Math.atan2(Y, X);
}
/* --------------------------------------------------------------
* Following iterative algorithm was developped by
* "Institut for Erdmessung", University of Hannover, July 1988.
* Internet: www.ife.uni-hannover.de
* Iterative computation of CPHI,SPHI and Height.
* Iteration of CPHI and SPHI to 10**-12 radian resp.
* 2*10**-7 arcsec.
* --------------------------------------------------------------
*/
CT = Z / RR;
ST = P / RR;
RX = 1.0 / Math.sqrt(1.0 - es * (2.0 - es) * ST * ST);
CPHI0 = ST * (1.0 - es) * RX;
SPHI0 = CT * RX;
iter = 0;
/* loop to find sin(Latitude) resp. Latitude
* until |sin(Latitude(iter)-Latitude(iter-1))| < genau */
do {
iter++;
RN = a / Math.sqrt(1.0 - es * SPHI0 * SPHI0);
/* ellipsoidal (geodetic) height */
Height = P * CPHI0 + Z * SPHI0 - RN * (1.0 - es * SPHI0 * SPHI0);
RK = es * RN / (RN + Height);
RX = 1.0 / Math.sqrt(1.0 - RK * (2.0 - RK) * ST * ST);
CPHI = ST * (1.0 - RK) * RX;
SPHI = CT * RX;
SDPHI = SPHI * CPHI0 - CPHI * SPHI0;
CPHI0 = CPHI;
SPHI0 = SPHI;
}
while (SDPHI * SDPHI > genau2 && iter < maxiter);
/* ellipsoidal (geodetic) latitude */
Latitude = Math.atan(SPHI / Math.abs(CPHI));
return {
x: Longitude,
y: Latitude,
z: Height
};
} // cs_geocentric_to_geodetic()
/****************************************************************/
// pj_geocentic_to_wgs84( p )
// p = point to transform in geocentric coordinates (x,y,z)
/** point object, nothing fancy, just allows values to be
passed back and forth by reference rather than by value.
Other point classes may be used as long as they have
x and y properties, which will get modified in the transform method.
*/
function geocentricToWgs84(p, datum_type, datum_params) {
if (datum_type === PJD_3PARAM) {
// if( x[io] === HUGE_VAL )
// continue;
return {
x: p.x + datum_params[0],
y: p.y + datum_params[1],
z: p.z + datum_params[2],
};
} else if (datum_type === PJD_7PARAM) {
var Dx_BF = datum_params[0];
var Dy_BF = datum_params[1];
var Dz_BF = datum_params[2];
var Rx_BF = datum_params[3];
var Ry_BF = datum_params[4];
var Rz_BF = datum_params[5];
var M_BF = datum_params[6];
// if( x[io] === HUGE_VAL )
// continue;
return {
x: M_BF * (p.x - Rz_BF * p.y + Ry_BF * p.z) + Dx_BF,
y: M_BF * (Rz_BF * p.x + p.y - Rx_BF * p.z) + Dy_BF,
z: M_BF * (-Ry_BF * p.x + Rx_BF * p.y + p.z) + Dz_BF
};
}
} // cs_geocentric_to_wgs84
/****************************************************************/
// pj_geocentic_from_wgs84()
// coordinate system definition,
// point to transform in geocentric coordinates (x,y,z)
function geocentricFromWgs84(p, datum_type, datum_params) {
if (datum_type === PJD_3PARAM) {
//if( x[io] === HUGE_VAL )
// continue;
return {
x: p.x - datum_params[0],
y: p.y - datum_params[1],
z: p.z - datum_params[2],
};
} else if (datum_type === PJD_7PARAM) {
var Dx_BF = datum_params[0];
var Dy_BF = datum_params[1];
var Dz_BF = datum_params[2];
var Rx_BF = datum_params[3];
var Ry_BF = datum_params[4];
var Rz_BF = datum_params[5];
var M_BF = datum_params[6];
var x_tmp = (p.x - Dx_BF) / M_BF;
var y_tmp = (p.y - Dy_BF) / M_BF;
var z_tmp = (p.z - Dz_BF) / M_BF;
//if( x[io] === HUGE_VAL )
// continue;
return {
x: x_tmp + Rz_BF * y_tmp - Ry_BF * z_tmp,
y: -Rz_BF * x_tmp + y_tmp + Rx_BF * z_tmp,
z: Ry_BF * x_tmp - Rx_BF * y_tmp + z_tmp
};
} //cs_geocentric_from_wgs84()
}
function checkParams(type) {
return (type === PJD_3PARAM || type === PJD_7PARAM);
}
function datum_transform(source, dest, point) {
// Short cut if the datums are identical.
if (compareDatums(source, dest)) {
return point; // in this case, zero is sucess,
// whereas cs_compare_datums returns 1 to indicate TRUE
// confusing, should fix this
}
// Explicitly skip datum transform by setting 'datum=none' as parameter for either source or dest
if (source.datum_type === PJD_NODATUM || dest.datum_type === PJD_NODATUM) {
return point;
}
// If this datum requires grid shifts, then apply it to geodetic coordinates.
var source_a = source.a;
var source_es = source.es;
if (source.datum_type === PJD_GRIDSHIFT) {
var gridShiftCode = applyGridShift(source, false, point);
if (gridShiftCode !== 0) {
return undefined;
}
source_a = SRS_WGS84_SEMIMAJOR;
source_es = SRS_WGS84_ESQUARED;
}
var dest_a = dest.a;
var dest_b = dest.b;
var dest_es = dest.es;
if (dest.datum_type === PJD_GRIDSHIFT) {
dest_a = SRS_WGS84_SEMIMAJOR;
dest_b = SRS_WGS84_SEMIMINOR;
dest_es = SRS_WGS84_ESQUARED;
}
// Do we need to go through geocentric coordinates?
if (source_es === dest_es && source_a === dest_a && !checkParams(source.datum_type) && !checkParams(dest.datum_type)) {
return point;
}
// Convert to geocentric coordinates.
point = geodeticToGeocentric(point, source_es, source_a);
// Convert between datums
if (checkParams(source.datum_type)) {
point = geocentricToWgs84(point, source.datum_type, source.datum_params);
}
if (checkParams(dest.datum_type)) {
point = geocentricFromWgs84(point, dest.datum_type, dest.datum_params);
}
point = geocentricToGeodetic(point, dest_es, dest_a, dest_b);
if (dest.datum_type === PJD_GRIDSHIFT) {
var destGridShiftResult = applyGridShift(dest, true, point);
if (destGridShiftResult !== 0) {
return undefined;
}
}
return point;
}
function applyGridShift(source, inverse, point) {
if (source.grids === null || source.grids.length === 0) {
console.log('Grid shift grids not found');
return -1;
}
var input = {x: -point.x, y: point.y};
var output = {x: Number.NaN, y: Number.NaN};
var attemptedGrids = [];
outer:
for (var i = 0; i < source.grids.length; i++) {
var grid = source.grids[i];
attemptedGrids.push(grid.name);
if (grid.isNull) {
output = input;
break;
}
grid.mandatory;
if (grid.grid === null) {
if (grid.mandatory) {
console.log("Unable to find mandatory grid '" + grid.name + "'");
return -1;
}
continue;
}
var subgrids = grid.grid.subgrids;
for (var j = 0, jj = subgrids.length; j < jj; j++) {
var subgrid = subgrids[j];
// skip tables that don't match our point at all
var epsilon = (Math.abs(subgrid.del[1]) + Math.abs(subgrid.del[0])) / 10000.0;
var minX = subgrid.ll[0] - epsilon;
var minY = subgrid.ll[1] - epsilon;
var maxX = subgrid.ll[0] + (subgrid.lim[0] - 1) * subgrid.del[0] + epsilon;
var maxY = subgrid.ll[1] + (subgrid.lim[1] - 1) * subgrid.del[1] + epsilon;
if (minY > input.y || minX > input.x || maxY < input.y || maxX < input.x ) {
continue;
}
output = applySubgridShift(input, inverse, subgrid);
if (!isNaN(output.x)) {
break outer;
}
}
}
if (isNaN(output.x)) {
console.log("Failed to find a grid shift table for location '"+
-input.x * R2D + " " + input.y * R2D + " tried: '" + attemptedGrids + "'");
return -1;
}
point.x = -output.x;
point.y = output.y;
return 0;
}
function applySubgridShift(pin, inverse, ct) {
var val = {x: Number.NaN, y: Number.NaN};
if (isNaN(pin.x)) { return val; }
var tb = {x: pin.x, y: pin.y};
tb.x -= ct.ll[0];
tb.y -= ct.ll[1];
tb.x = adjust_lon(tb.x - Math.PI) + Math.PI;
var t = nadInterpolate(tb, ct);
if (inverse) {
if (isNaN(t.x)) {
return val;
}
t.x = tb.x - t.x;
t.y = tb.y - t.y;
var i = 9, tol = 1e-12;
var dif, del;
do {
del = nadInterpolate(t, ct);
if (isNaN(del.x)) {
console.log("Inverse grid shift iteration failed, presumably at grid edge. Using first approximation.");
break;
}
dif = {x: tb.x - (del.x + t.x), y: tb.y - (del.y + t.y)};
t.x += dif.x;
t.y += dif.y;
} while (i-- && Math.abs(dif.x) > tol && Math.abs(dif.y) > tol);
if (i < 0) {
console.log("Inverse grid shift iterator failed to converge.");
return val;
}
val.x = adjust_lon(t.x + ct.ll[0]);
val.y = t.y + ct.ll[1];
} else {
if (!isNaN(t.x)) {
val.x = pin.x + t.x;
val.y = pin.y + t.y;
}
}
return val;
}
function nadInterpolate(pin, ct) {
var t = {x: pin.x / ct.del[0], y: pin.y / ct.del[1]};
var indx = {x: Math.floor(t.x), y: Math.floor(t.y)};
var frct = {x: t.x - 1.0 * indx.x, y: t.y - 1.0 * indx.y};
var val= {x: Number.NaN, y: Number.NaN};
var inx;
if (indx.x < 0 || indx.x >= ct.lim[0]) {
return val;
}
if (indx.y < 0 || indx.y >= ct.lim[1]) {
return val;
}
inx = (indx.y * ct.lim[0]) + indx.x;
var f00 = {x: ct.cvs[inx][0], y: ct.cvs[inx][1]};
inx++;
var f10= {x: ct.cvs[inx][0], y: ct.cvs[inx][1]};
inx += ct.lim[0];
var f11 = {x: ct.cvs[inx][0], y: ct.cvs[inx][1]};
inx--;
var f01 = {x: ct.cvs[inx][0], y: ct.cvs[inx][1]};
var m11 = frct.x * frct.y, m10 = frct.x * (1.0 - frct.y),
m00 = (1.0 - frct.x) * (1.0 - frct.y), m01 = (1.0 - frct.x) * frct.y;
val.x = (m00 * f00.x + m10 * f10.x + m01 * f01.x + m11 * f11.x);
val.y = (m00 * f00.y + m10 * f10.y + m01 * f01.y + m11 * f11.y);
return val;
}
function adjust_axis(crs, denorm, point) {
var xin = point.x,
yin = point.y,
zin = point.z || 0.0;
var v, t, i;
var out = {};
for (i = 0; i < 3; i++) {
if (denorm && i === 2 && point.z === undefined) {
continue;
}
if (i === 0) {
v = xin;
if ("ew".indexOf(crs.axis[i]) !== -1) {
t = 'x';
} else {
t = 'y';
}
}
else if (i === 1) {
v = yin;
if ("ns".indexOf(crs.axis[i]) !== -1) {
t = 'y';
} else {
t = 'x';
}
}
else {
v = zin;
t = 'z';
}
switch (crs.axis[i]) {
case 'e':
out[t] = v;
break;
case 'w':
out[t] = -v;
break;
case 'n':
out[t] = v;
break;
case 's':
out[t] = -v;
break;
case 'u':
if (point[t] !== undefined) {
out.z = v;
}
break;
case 'd':
if (point[t] !== undefined) {
out.z = -v;
}
break;
default:
//console.log("ERROR: unknow axis ("+crs.axis[i]+") - check definition of "+crs.projName);
return null;
}
}
return out;
}
function common (array){
var out = {
x: array[0],
y: array[1]
};
if (array.length>2) {
out.z = array[2];
}
if (array.length>3) {
out.m = array[3];
}
return out;
}
function checkSanity (point) {
checkCoord(point.x);
checkCoord(point.y);
}
function checkCoord(num) {
if (typeof Number.isFinite === 'function') {
if (Number.isFinite(num)) {
return;
}
throw new TypeError('coordinates must be finite numbers');
}
if (typeof num !== 'number' || num !== num || !isFinite(num)) {
throw new TypeError('coordinates must be finite numbers');
}
}
function checkNotWGS(source, dest) {
return (
(source.datum.datum_type === PJD_3PARAM || source.datum.datum_type === PJD_7PARAM || source.datum.datum_type === PJD_GRIDSHIFT) && dest.datumCode !== 'WGS84') ||
((dest.datum.datum_type === PJD_3PARAM || dest.datum.datum_type === PJD_7PARAM || dest.datum.datum_type === PJD_GRIDSHIFT) && source.datumCode !== 'WGS84');
}
function transform(source, dest, point, enforceAxis) {
var wgs84;
if (Array.isArray(point)) {
point = common(point);
} else {
// Clone the point object so inputs don't get modified
point = {
x: point.x,
y: point.y,
z: point.z,
m: point.m
};
}
var hasZ = point.z !== undefined;
checkSanity(point);
// Workaround for datum shifts towgs84, if either source or destination projection is not wgs84
if (source.datum && dest.datum && checkNotWGS(source, dest)) {
wgs84 = new Projection('WGS84');
point = transform(source, wgs84, point, enforceAxis);
source = wgs84;
}
// DGR, 2010/11/12
if (enforceAxis && source.axis !== 'enu') {
point = adjust_axis(source, false, point);
}
// Transform source points to long/lat, if they aren't already.
if (source.projName === 'longlat') {
point = {
x: point.x * D2R$1,
y: point.y * D2R$1,
z: point.z || 0
};
} else {
if (source.to_meter) {
point = {
x: point.x * source.to_meter,
y: point.y * source.to_meter,
z: point.z || 0
};
}
point = source.inverse(point); // Convert Cartesian to longlat
if (!point) {
return;
}
}
// Adjust for the prime meridian if necessary
if (source.from_greenwich) {
point.x += source.from_greenwich;
}
// Convert datums if needed, and if possible.
point = datum_transform(source.datum, dest.datum, point);
if (!point) {
return;
}
// Adjust for the prime meridian if necessary
if (dest.from_greenwich) {
point = {
x: point.x - dest.from_greenwich,
y: point.y,
z: point.z || 0
};
}
if (dest.projName === 'longlat') {
// convert radians to decimal degrees
point = {
x: point.x * R2D,
y: point.y * R2D,
z: point.z || 0
};
} else { // else project
point = dest.forward(point);
if (dest.to_meter) {
point = {
x: point.x / dest.to_meter,
y: point.y / dest.to_meter,
z: point.z || 0
};
}
}
// DGR, 2010/11/12
if (enforceAxis && dest.axis !== 'enu') {
return adjust_axis(dest, true, point);
}
if (point && !hasZ) {
delete point.z;
}
return point;
}
var wgs84 = Projection('WGS84');
function transformer(from, to, coords, enforceAxis) {
var transformedArray, out, keys;
if (Array.isArray(coords)) {
transformedArray = transform(from, to, coords, enforceAxis) || {x: NaN, y: NaN};
if (coords.length > 2) {
if ((typeof from.name !== 'undefined' && from.name === 'geocent') || (typeof to.name !== 'undefined' && to.name === 'geocent')) {
if (typeof transformedArray.z === 'number') {
return [transformedArray.x, transformedArray.y, transformedArray.z].concat(coords.splice(3));
} else {
return [transformedArray.x, transformedArray.y, coords[2]].concat(coords.splice(3));
}
} else {
return [transformedArray.x, transformedArray.y].concat(coords.splice(2));
}
} else {
return [transformedArray.x, transformedArray.y];
}
} else {
out = transform(from, to, coords, enforceAxis);
keys = Object.keys(coords);
if (keys.length === 2) {
return out;
}
keys.forEach(function (key) {
if ((typeof from.name !== 'undefined' && from.name === 'geocent') || (typeof to.name !== 'undefined' && to.name === 'geocent')) {
if (key === 'x' || key === 'y' || key === 'z') {
return;
}
} else {
if (key === 'x' || key === 'y') {
return;
}
}
out[key] = coords[key];
});
return out;
}
}
function checkProj(item) {
if (item instanceof Projection) {
return item;
}
if (item.oProj) {
return item.oProj;
}
return Projection(item);
}
function proj4(fromProj, toProj, coord) {
fromProj = checkProj(fromProj);
var single = false;
var obj;
if (typeof toProj === 'undefined') {
toProj = fromProj;
fromProj = wgs84;
single = true;
} else if (typeof toProj.x !== 'undefined' || Array.isArray(toProj)) {
coord = toProj;
toProj = fromProj;
fromProj = wgs84;
single = true;
}
toProj = checkProj(toProj);
if (coord) {
return transformer(fromProj, toProj, coord);
} else {
obj = {
forward: function (coords, enforceAxis) {
return transformer(fromProj, toProj, coords, enforceAxis);
},
inverse: function (coords, enforceAxis) {
return transformer(toProj, fromProj, coords, enforceAxis);
}
};
if (single) {
obj.oProj = toProj;
}
return obj;
}
}
/**
* UTM zones are grouped, and assigned to one of a group of 6
* sets.
*
* {int} @private
*/
var NUM_100K_SETS = 6;
/**
* The column letters (for easting) of the lower left value, per
* set.
*
* {string} @private
*/
var SET_ORIGIN_COLUMN_LETTERS = 'AJSAJS';
/**
* The row letters (for northing) of the lower left value, per
* set.
*
* {string} @private
*/
var SET_ORIGIN_ROW_LETTERS = 'AFAFAF';
var A = 65; // A
var I = 73; // I
var O = 79; // O
var V = 86; // V
var Z = 90; // Z
var mgrs = {
forward: forward$t,
inverse: inverse$t,
toPoint: toPoint
};
/**
* Conversion of lat/lon to MGRS.
*
* @param {object} ll Object literal with lat and lon properties on a
* WGS84 ellipsoid.
* @param {int} accuracy Accuracy in digits (5 for 1 m, 4 for 10 m, 3 for
* 100 m, 2 for 1000 m or 1 for 10000 m). Optional, default is 5.
* @return {string} the MGRS string for the given location and accuracy.
*/
function forward$t(ll, accuracy) {
accuracy = accuracy || 5; // default accuracy 1m
return encode(LLtoUTM({
lat: ll[1],
lon: ll[0]
}), accuracy);
}
/**
* Conversion of MGRS to lat/lon.
*
* @param {string} mgrs MGRS string.
* @return {array} An array with left (longitude), bottom (latitude), right
* (longitude) and top (latitude) values in WGS84, representing the
* bounding box for the provided MGRS reference.
*/
function inverse$t(mgrs) {
var bbox = UTMtoLL(decode(mgrs.toUpperCase()));
if (bbox.lat && bbox.lon) {
return [bbox.lon, bbox.lat, bbox.lon, bbox.lat];
}
return [bbox.left, bbox.bottom, bbox.right, bbox.top];
}
function toPoint(mgrs) {
var bbox = UTMtoLL(decode(mgrs.toUpperCase()));
if (bbox.lat && bbox.lon) {
return [bbox.lon, bbox.lat];
}
return [(bbox.left + bbox.right) / 2, (bbox.top + bbox.bottom) / 2];
}/**
* Conversion from degrees to radians.
*
* @private
* @param {number} deg the angle in degrees.
* @return {number} the angle in radians.
*/
function degToRad(deg) {
return (deg * (Math.PI / 180.0));
}
/**
* Conversion from radians to degrees.
*
* @private
* @param {number} rad the angle in radians.
* @return {number} the angle in degrees.
*/
function radToDeg(rad) {
return (180.0 * (rad / Math.PI));
}
/**
* Converts a set of Longitude and Latitude co-ordinates to UTM
* using the WGS84 ellipsoid.
*
* @private
* @param {object} ll Object literal with lat and lon properties
* representing the WGS84 coordinate to be converted.
* @return {object} Object literal containing the UTM value with easting,
* northing, zoneNumber and zoneLetter properties, and an optional
* accuracy property in digits. Returns null if the conversion failed.
*/
function LLtoUTM(ll) {
var Lat = ll.lat;
var Long = ll.lon;
var a = 6378137.0; //ellip.radius;
var eccSquared = 0.00669438; //ellip.eccsq;
var k0 = 0.9996;
var LongOrigin;
var eccPrimeSquared;
var N, T, C, A, M;
var LatRad = degToRad(Lat);
var LongRad = degToRad(Long);
var LongOriginRad;
var ZoneNumber;
// (int)
ZoneNumber = Math.floor((Long + 180) / 6) + 1;
//Make sure the longitude 180.00 is in Zone 60
if (Long === 180) {
ZoneNumber = 60;
}
// Special zone for Norway
if (Lat >= 56.0 && Lat < 64.0 && Long >= 3.0 && Long < 12.0) {
ZoneNumber = 32;
}
// Special zones for Svalbard
if (Lat >= 72.0 && Lat < 84.0) {
if (Long >= 0.0 && Long < 9.0) {
ZoneNumber = 31;
}
else if (Long >= 9.0 && Long < 21.0) {
ZoneNumber = 33;
}
else if (Long >= 21.0 && Long < 33.0) {
ZoneNumber = 35;
}
else if (Long >= 33.0 && Long < 42.0) {
ZoneNumber = 37;
}
}
LongOrigin = (ZoneNumber - 1) * 6 - 180 + 3; //+3 puts origin
// in middle of
// zone
LongOriginRad = degToRad(LongOrigin);
eccPrimeSquared = (eccSquared) / (1 - eccSquared);
N = a / Math.sqrt(1 - eccSquared * Math.sin(LatRad) * Math.sin(LatRad));
T = Math.tan(LatRad) * Math.tan(LatRad);
C = eccPrimeSquared * Math.cos(LatRad) * Math.cos(LatRad);
A = Math.cos(LatRad) * (LongRad - LongOriginRad);
M = a * ((1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256) * LatRad - (3 * eccSquared / 8 + 3 * eccSquared * eccSquared / 32 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.sin(2 * LatRad) + (15 * eccSquared * eccSquared / 256 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.sin(4 * LatRad) - (35 * eccSquared * eccSquared * eccSquared / 3072) * Math.sin(6 * LatRad));
var UTMEasting = (k0 * N * (A + (1 - T + C) * A * A * A / 6.0 + (5 - 18 * T + T * T + 72 * C - 58 * eccPrimeSquared) * A * A * A * A * A / 120.0) + 500000.0);
var UTMNorthing = (k0 * (M + N * Math.tan(LatRad) * (A * A / 2 + (5 - T + 9 * C + 4 * C * C) * A * A * A * A / 24.0 + (61 - 58 * T + T * T + 600 * C - 330 * eccPrimeSquared) * A * A * A * A * A * A / 720.0)));
if (Lat < 0.0) {
UTMNorthing += 10000000.0; //10000000 meter offset for
// southern hemisphere
}
return {
northing: Math.round(UTMNorthing),
easting: Math.round(UTMEasting),
zoneNumber: ZoneNumber,
zoneLetter: getLetterDesignator(Lat)
};
}
/**
* Converts UTM coords to lat/long, using the WGS84 ellipsoid. This is a convenience
* class where the Zone can be specified as a single string eg."60N" which
* is then broken down into the ZoneNumber and ZoneLetter.
*
* @private
* @param {object} utm An object literal with northing, easting, zoneNumber
* and zoneLetter properties. If an optional accuracy property is
* provided (in meters), a bounding box will be returned instead of
* latitude and longitude.
* @return {object} An object literal containing either lat and lon values
* (if no accuracy was provided), or top, right, bottom and left values
* for the bounding box calculated according to the provided accuracy.
* Returns null if the conversion failed.
*/
function UTMtoLL(utm) {
var UTMNorthing = utm.northing;
var UTMEasting = utm.easting;
var zoneLetter = utm.zoneLetter;
var zoneNumber = utm.zoneNumber;
// check the ZoneNummber is valid
if (zoneNumber < 0 || zoneNumber > 60) {
return null;
}
var k0 = 0.9996;
var a = 6378137.0; //ellip.radius;
var eccSquared = 0.00669438; //ellip.eccsq;
var eccPrimeSquared;
var e1 = (1 - Math.sqrt(1 - eccSquared)) / (1 + Math.sqrt(1 - eccSquared));
var N1, T1, C1, R1, D, M;
var LongOrigin;
var mu, phi1Rad;
// remove 500,000 meter offset for longitude
var x = UTMEasting - 500000.0;
var y = UTMNorthing;
// We must know somehow if we are in the Northern or Southern
// hemisphere, this is the only time we use the letter So even
// if the Zone letter isn't exactly correct it should indicate
// the hemisphere correctly
if (zoneLetter < 'N') {
y -= 10000000.0; // remove 10,000,000 meter offset used
// for southern hemisphere
}
// There are 60 zones with zone 1 being at West -180 to -174
LongOrigin = (zoneNumber - 1) * 6 - 180 + 3; // +3 puts origin
// in middle of
// zone
eccPrimeSquared = (eccSquared) / (1 - eccSquared);
M = y / k0;
mu = M / (a * (1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256));
phi1Rad = mu + (3 * e1 / 2 - 27 * e1 * e1 * e1 / 32) * Math.sin(2 * mu) + (21 * e1 * e1 / 16 - 55 * e1 * e1 * e1 * e1 / 32) * Math.sin(4 * mu) + (151 * e1 * e1 * e1 / 96) * Math.sin(6 * mu);
// double phi1 = ProjMath.radToDeg(phi1Rad);
N1 = a / Math.sqrt(1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad));
T1 = Math.tan(phi1Rad) * Math.tan(phi1Rad);
C1 = eccPrimeSquared * Math.cos(phi1Rad) * Math.cos(phi1Rad);
R1 = a * (1 - eccSquared) / Math.pow(1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad), 1.5);
D = x / (N1 * k0);
var lat = phi1Rad - (N1 * Math.tan(phi1Rad) / R1) * (D * D / 2 - (5 + 3 * T1 + 10 * C1 - 4 * C1 * C1 - 9 * eccPrimeSquared) * D * D * D * D / 24 + (61 + 90 * T1 + 298 * C1 + 45 * T1 * T1 - 252 * eccPrimeSquared - 3 * C1 * C1) * D * D * D * D * D * D / 720);
lat = radToDeg(lat);
var lon = (D - (1 + 2 * T1 + C1) * D * D * D / 6 + (5 - 2 * C1 + 28 * T1 - 3 * C1 * C1 + 8 * eccPrimeSquared + 24 * T1 * T1) * D * D * D * D * D / 120) / Math.cos(phi1Rad);
lon = LongOrigin + radToDeg(lon);
var result;
if (utm.accuracy) {
var topRight = UTMtoLL({
northing: utm.northing + utm.accuracy,
easting: utm.easting + utm.accuracy,
zoneLetter: utm.zoneLetter,
zoneNumber: utm.zoneNumber
});
result = {
top: topRight.lat,
right: topRight.lon,
bottom: lat,
left: lon
};
}
else {
result = {
lat: lat,
lon: lon
};
}
return result;
}
/**
* Calculates the MGRS letter designator for the given latitude.
*
* @private
* @param {number} lat The latitude in WGS84 to get the letter designator
* for.
* @return {char} The letter designator.
*/
function getLetterDesignator(lat) {
//This is here as an error flag to show that the Latitude is
//outside MGRS limits
var LetterDesignator = 'Z';
if ((84 >= lat) && (lat >= 72)) {
LetterDesignator = 'X';
}
else if ((72 > lat) && (lat >= 64)) {
LetterDesignator = 'W';
}
else if ((64 > lat) && (lat >= 56)) {
LetterDesignator = 'V';
}
else if ((56 > lat) && (lat >= 48)) {
LetterDesignator = 'U';
}
else if ((48 > lat) && (lat >= 40)) {
LetterDesignator = 'T';
}
else if ((40 > lat) && (lat >= 32)) {
LetterDesignator = 'S';
}
else if ((32 > lat) && (lat >= 24)) {
LetterDesignator = 'R';
}
else if ((24 > lat) && (lat >= 16)) {
LetterDesignator = 'Q';
}
else if ((16 > lat) && (lat >= 8)) {
LetterDesignator = 'P';
}
else if ((8 > lat) && (lat >= 0)) {
LetterDesignator = 'N';
}
else if ((0 > lat) && (lat >= -8)) {
LetterDesignator = 'M';
}
else if ((-8 > lat) && (lat >= -16)) {
LetterDesignator = 'L';
}
else if ((-16 > lat) && (lat >= -24)) {
LetterDesignator = 'K';
}
else if ((-24 > lat) && (lat >= -32)) {
LetterDesignator = 'J';
}
else if ((-32 > lat) && (lat >= -40)) {
LetterDesignator = 'H';
}
else if ((-40 > lat) && (lat >= -48)) {
LetterDesignator = 'G';
}
else if ((-48 > lat) && (lat >= -56)) {
LetterDesignator = 'F';
}
else if ((-56 > lat) && (lat >= -64)) {
LetterDesignator = 'E';
}
else if ((-64 > lat) && (lat >= -72)) {
LetterDesignator = 'D';
}
else if ((-72 > lat) && (lat >= -80)) {
LetterDesignator = 'C';
}
return LetterDesignator;
}
/**
* Encodes a UTM location as MGRS string.
*
* @private
* @param {object} utm An object literal with easting, northing,
* zoneLetter, zoneNumber
* @param {number} accuracy Accuracy in digits (1-5).
* @return {string} MGRS string for the given UTM location.
*/
function encode(utm, accuracy) {
// prepend with leading zeroes
var seasting = "00000" + utm.easting,
snorthing = "00000" + utm.northing;
return utm.zoneNumber + utm.zoneLetter + get100kID(utm.easting, utm.northing, utm.zoneNumber) + seasting.substr(seasting.length - 5, accuracy) + snorthing.substr(snorthing.length - 5, accuracy);
}
/**
* Get the two letter 100k designator for a given UTM easting,
* northing and zone number value.
*
* @private
* @param {number} easting
* @param {number} northing
* @param {number} zoneNumber
* @return the two letter 100k designator for the given UTM location.
*/
function get100kID(easting, northing, zoneNumber) {
var setParm = get100kSetForZone(zoneNumber);
var setColumn = Math.floor(easting / 100000);
var setRow = Math.floor(northing / 100000) % 20;
return getLetter100kID(setColumn, setRow, setParm);
}
/**
* Given a UTM zone number, figure out the MGRS 100K set it is in.
*
* @private
* @param {number} i An UTM zone number.
* @return {number} the 100k set the UTM zone is in.
*/
function get100kSetForZone(i) {
var setParm = i % NUM_100K_SETS;
if (setParm === 0) {
setParm = NUM_100K_SETS;
}
return setParm;
}
/**
* Get the two-letter MGRS 100k designator given information
* translated from the UTM northing, easting and zone number.
*
* @private
* @param {number} column the column index as it relates to the MGRS
* 100k set spreadsheet, created from the UTM easting.
* Values are 1-8.
* @param {number} row the row index as it relates to the MGRS 100k set
* spreadsheet, created from the UTM northing value. Values
* are from 0-19.
* @param {number} parm the set block, as it relates to the MGRS 100k set
* spreadsheet, created from the UTM zone. Values are from
* 1-60.
* @return two letter MGRS 100k code.
*/
function getLetter100kID(column, row, parm) {
// colOrigin and rowOrigin are the letters at the origin of the set
var index = parm - 1;
var colOrigin = SET_ORIGIN_COLUMN_LETTERS.charCodeAt(index);
var rowOrigin = SET_ORIGIN_ROW_LETTERS.charCodeAt(index);
// colInt and rowInt are the letters to build to return
var colInt = colOrigin + column - 1;
var rowInt = rowOrigin + row;
var rollover = false;
if (colInt > Z) {
colInt = colInt - Z + A - 1;
rollover = true;
}
if (colInt === I || (colOrigin < I && colInt > I) || ((colInt > I || colOrigin < I) && rollover)) {
colInt++;
}
if (colInt === O || (colOrigin < O && colInt > O) || ((colInt > O || colOrigin < O) && rollover)) {
colInt++;
if (colInt === I) {
colInt++;
}
}
if (colInt > Z) {
colInt = colInt - Z + A - 1;
}
if (rowInt > V) {
rowInt = rowInt - V + A - 1;
rollover = true;
}
else {
rollover = false;
}
if (((rowInt === I) || ((rowOrigin < I) && (rowInt > I))) || (((rowInt > I) || (rowOrigin < I)) && rollover)) {
rowInt++;
}
if (((rowInt === O) || ((rowOrigin < O) && (rowInt > O))) || (((rowInt > O) || (rowOrigin < O)) && rollover)) {
rowInt++;
if (rowInt === I) {
rowInt++;
}
}
if (rowInt > V) {
rowInt = rowInt - V + A - 1;
}
var twoLetter = String.fromCharCode(colInt) + String.fromCharCode(rowInt);
return twoLetter;
}
/**
* Decode the UTM parameters from a MGRS string.
*
* @private
* @param {string} mgrsString an UPPERCASE coordinate string is expected.
* @return {object} An object literal with easting, northing, zoneLetter,
* zoneNumber and accuracy (in meters) properties.
*/
function decode(mgrsString) {
if (mgrsString && mgrsString.length === 0) {
throw ("MGRSPoint coverting from nothing");
}
var length = mgrsString.length;
var hunK = null;
var sb = "";
var testChar;
var i = 0;
// get Zone number
while (!(/[A-Z]/).test(testChar = mgrsString.charAt(i))) {
if (i >= 2) {
throw ("MGRSPoint bad conversion from: " + mgrsString);
}
sb += testChar;
i++;
}
var zoneNumber = parseInt(sb, 10);
if (i === 0 || i + 3 > length) {
// A good MGRS string has to be 4-5 digits long,
// ##AAA/#AAA at least.
throw ("MGRSPoint bad conversion from: " + mgrsString);
}
var zoneLetter = mgrsString.charAt(i++);
// Should we check the zone letter here? Why not.
if (zoneLetter <= 'A' || zoneLetter === 'B' || zoneLetter === 'Y' || zoneLetter >= 'Z' || zoneLetter === 'I' || zoneLetter === 'O') {
throw ("MGRSPoint zone letter " + zoneLetter + " not handled: " + mgrsString);
}
hunK = mgrsString.substring(i, i += 2);
var set = get100kSetForZone(zoneNumber);
var east100k = getEastingFromChar(hunK.charAt(0), set);
var north100k = getNorthingFromChar(hunK.charAt(1), set);
// We have a bug where the northing may be 2000000 too low.
// How
// do we know when to roll over?
while (north100k < getMinNorthing(zoneLetter)) {
north100k += 2000000;
}
// calculate the char index for easting/northing separator
var remainder = length - i;
if (remainder % 2 !== 0) {
throw ("MGRSPoint has to have an even number \nof digits after the zone letter and two 100km letters - front \nhalf for easting meters, second half for \nnorthing meters" + mgrsString);
}
var sep = remainder / 2;
var sepEasting = 0.0;
var sepNorthing = 0.0;
var accuracyBonus, sepEastingString, sepNorthingString, easting, northing;
if (sep > 0) {
accuracyBonus = 100000.0 / Math.pow(10, sep);
sepEastingString = mgrsString.substring(i, i + sep);
sepEasting = parseFloat(sepEastingString) * accuracyBonus;
sepNorthingString = mgrsString.substring(i + sep);
sepNorthing = parseFloat(sepNorthingString) * accuracyBonus;
}
easting = sepEasting + east100k;
northing = sepNorthing + north100k;
return {
easting: easting,
northing: northing,
zoneLetter: zoneLetter,
zoneNumber: zoneNumber,
accuracy: accuracyBonus
};
}
/**
* Given the first letter from a two-letter MGRS 100k zone, and given the
* MGRS table set for the zone number, figure out the easting value that
* should be added to the other, secondary easting value.
*
* @private
* @param {char} e The first letter from a two-letter MGRS 100´k zone.
* @param {number} set The MGRS table set for the zone number.
* @return {number} The easting value for the given letter and set.
*/
function getEastingFromChar(e, set) {
// colOrigin is the letter at the origin of the set for the
// column
var curCol = SET_ORIGIN_COLUMN_LETTERS.charCodeAt(set - 1);
var eastingValue = 100000.0;
var rewindMarker = false;
while (curCol !== e.charCodeAt(0)) {
curCol++;
if (curCol === I) {
curCol++;
}
if (curCol === O) {
curCol++;
}
if (curCol > Z) {
if (rewindMarker) {
throw ("Bad character: " + e);
}
curCol = A;
rewindMarker = true;
}
eastingValue += 100000.0;
}
return eastingValue;
}
/**
* Given the second letter from a two-letter MGRS 100k zone, and given the
* MGRS table set for the zone number, figure out the northing value that
* should be added to the other, secondary northing value. You have to
* remember that Northings are determined from the equator, and the vertical
* cycle of letters mean a 2000000 additional northing meters. This happens
* approx. every 18 degrees of latitude. This method does *NOT* count any
* additional northings. You have to figure out how many 2000000 meters need
* to be added for the zone letter of the MGRS coordinate.
*
* @private
* @param {char} n Second letter of the MGRS 100k zone
* @param {number} set The MGRS table set number, which is dependent on the
* UTM zone number.
* @return {number} The northing value for the given letter and set.
*/
function getNorthingFromChar(n, set) {
if (n > 'V') {
throw ("MGRSPoint given invalid Northing " + n);
}
// rowOrigin is the letter at the origin of the set for the
// column
var curRow = SET_ORIGIN_ROW_LETTERS.charCodeAt(set - 1);
var northingValue = 0.0;
var rewindMarker = false;
while (curRow !== n.charCodeAt(0)) {
curRow++;
if (curRow === I) {
curRow++;
}
if (curRow === O) {
curRow++;
}
// fixing a bug making whole application hang in this loop
// when 'n' is a wrong character
if (curRow > V) {
if (rewindMarker) { // making sure that this loop ends
throw ("Bad character: " + n);
}
curRow = A;
rewindMarker = true;
}
northingValue += 100000.0;
}
return northingValue;
}
/**
* The function getMinNorthing returns the minimum northing value of a MGRS
* zone.
*
* Ported from Geotrans' c Lattitude_Band_Value structure table.
*
* @private
* @param {char} zoneLetter The MGRS zone to get the min northing for.
* @return {number}
*/
function getMinNorthing(zoneLetter) {
var northing;
switch (zoneLetter) {
case 'C':
northing = 1100000.0;
break;
case 'D':
northing = 2000000.0;
break;
case 'E':
northing = 2800000.0;
break;
case 'F':
northing = 3700000.0;
break;
case 'G':
northing = 4600000.0;
break;
case 'H':
northing = 5500000.0;
break;
case 'J':
northing = 6400000.0;
break;
case 'K':
northing = 7300000.0;
break;
case 'L':
northing = 8200000.0;
break;
case 'M':
northing = 9100000.0;
break;
case 'N':
northing = 0.0;
break;
case 'P':
northing = 800000.0;
break;
case 'Q':
northing = 1700000.0;
break;
case 'R':
northing = 2600000.0;
break;
case 'S':
northing = 3500000.0;
break;
case 'T':
northing = 4400000.0;
break;
case 'U':
northing = 5300000.0;
break;
case 'V':
northing = 6200000.0;
break;
case 'W':
northing = 7000000.0;
break;
case 'X':
northing = 7900000.0;
break;
default:
northing = -1.0;
}
if (northing >= 0.0) {
return northing;
}
else {
throw ("Invalid zone letter: " + zoneLetter);
}
}
function Point$2(x, y, z) {
if (!(this instanceof Point$2)) {
return new Point$2(x, y, z);
}
if (Array.isArray(x)) {
this.x = x[0];
this.y = x[1];
this.z = x[2] || 0.0;
} else if(typeof x === 'object') {
this.x = x.x;
this.y = x.y;
this.z = x.z || 0.0;
} else if (typeof x === 'string' && typeof y === 'undefined') {
var coords = x.split(',');
this.x = parseFloat(coords[0], 10);
this.y = parseFloat(coords[1], 10);
this.z = parseFloat(coords[2], 10) || 0.0;
} else {
this.x = x;
this.y = y;
this.z = z || 0.0;
}
console.warn('proj4.Point will be removed in version 3, use proj4.toPoint');
}
Point$2.fromMGRS = function(mgrsStr) {
return new Point$2(toPoint(mgrsStr));
};
Point$2.prototype.toMGRS = function(accuracy) {
return forward$t([this.x, this.y], accuracy);
};
var C00 = 1;
var C02 = 0.25;
var C04 = 0.046875;
var C06 = 0.01953125;
var C08 = 0.01068115234375;
var C22 = 0.75;
var C44 = 0.46875;
var C46 = 0.01302083333333333333;
var C48 = 0.00712076822916666666;
var C66 = 0.36458333333333333333;
var C68 = 0.00569661458333333333;
var C88 = 0.3076171875;
function pj_enfn(es) {
var en = [];
en[0] = C00 - es * (C02 + es * (C04 + es * (C06 + es * C08)));
en[1] = es * (C22 - es * (C04 + es * (C06 + es * C08)));
var t = es * es;
en[2] = t * (C44 - es * (C46 + es * C48));
t *= es;
en[3] = t * (C66 - es * C68);
en[4] = t * es * C88;
return en;
}
function pj_mlfn(phi, sphi, cphi, en) {
cphi *= sphi;
sphi *= sphi;
return (en[0] * phi - cphi * (en[1] + sphi * (en[2] + sphi * (en[3] + sphi * en[4]))));
}
var MAX_ITER$3 = 20;
function pj_inv_mlfn(arg, es, en) {
var k = 1 / (1 - es);
var phi = arg;
for (var i = MAX_ITER$3; i; --i) { /* rarely goes over 2 iterations */
var s = Math.sin(phi);
var t = 1 - es * s * s;
//t = this.pj_mlfn(phi, s, Math.cos(phi), en) - arg;
//phi -= t * (t * Math.sqrt(t)) * k;
t = (pj_mlfn(phi, s, Math.cos(phi), en) - arg) * (t * Math.sqrt(t)) * k;
phi -= t;
if (Math.abs(t) < EPSLN) {
return phi;
}
}
//..reportError("cass:pj_inv_mlfn: Convergence error");
return phi;
}
// Heavily based on this tmerc projection implementation
function init$u() {
this.x0 = this.x0 !== undefined ? this.x0 : 0;
this.y0 = this.y0 !== undefined ? this.y0 : 0;
this.long0 = this.long0 !== undefined ? this.long0 : 0;
this.lat0 = this.lat0 !== undefined ? this.lat0 : 0;
if (this.es) {
this.en = pj_enfn(this.es);
this.ml0 = pj_mlfn(this.lat0, Math.sin(this.lat0), Math.cos(this.lat0), this.en);
}
}
/**
Transverse Mercator Forward - long/lat to x/y
long/lat in radians
*/
function forward$s(p) {
var lon = p.x;
var lat = p.y;
var delta_lon = adjust_lon(lon - this.long0);
var con;
var x, y;
var sin_phi = Math.sin(lat);
var cos_phi = Math.cos(lat);
if (!this.es) {
var b = cos_phi * Math.sin(delta_lon);
if ((Math.abs(Math.abs(b) - 1)) < EPSLN) {
return (93);
}
else {
x = 0.5 * this.a * this.k0 * Math.log((1 + b) / (1 - b)) + this.x0;
y = cos_phi * Math.cos(delta_lon) / Math.sqrt(1 - Math.pow(b, 2));
b = Math.abs(y);
if (b >= 1) {
if ((b - 1) > EPSLN) {
return (93);
}
else {
y = 0;
}
}
else {
y = Math.acos(y);
}
if (lat < 0) {
y = -y;
}
y = this.a * this.k0 * (y - this.lat0) + this.y0;
}
}
else {
var al = cos_phi * delta_lon;
var als = Math.pow(al, 2);
var c = this.ep2 * Math.pow(cos_phi, 2);
var cs = Math.pow(c, 2);
var tq = Math.abs(cos_phi) > EPSLN ? Math.tan(lat) : 0;
var t = Math.pow(tq, 2);
var ts = Math.pow(t, 2);
con = 1 - this.es * Math.pow(sin_phi, 2);
al = al / Math.sqrt(con);
var ml = pj_mlfn(lat, sin_phi, cos_phi, this.en);
x = this.a * (this.k0 * al * (1 +
als / 6 * (1 - t + c +
als / 20 * (5 - 18 * t + ts + 14 * c - 58 * t * c +
als / 42 * (61 + 179 * ts - ts * t - 479 * t))))) +
this.x0;
y = this.a * (this.k0 * (ml - this.ml0 +
sin_phi * delta_lon * al / 2 * (1 +
als / 12 * (5 - t + 9 * c + 4 * cs +
als / 30 * (61 + ts - 58 * t + 270 * c - 330 * t * c +
als / 56 * (1385 + 543 * ts - ts * t - 3111 * t)))))) +
this.y0;
}
p.x = x;
p.y = y;
return p;
}
/**
Transverse Mercator Inverse - x/y to long/lat
*/
function inverse$s(p) {
var con, phi;
var lat, lon;
var x = (p.x - this.x0) * (1 / this.a);
var y = (p.y - this.y0) * (1 / this.a);
if (!this.es) {
var f = Math.exp(x / this.k0);
var g = 0.5 * (f - 1 / f);
var temp = this.lat0 + y / this.k0;
var h = Math.cos(temp);
con = Math.sqrt((1 - Math.pow(h, 2)) / (1 + Math.pow(g, 2)));
lat = Math.asin(con);
if (y < 0) {
lat = -lat;
}
if ((g === 0) && (h === 0)) {
lon = 0;
}
else {
lon = adjust_lon(Math.atan2(g, h) + this.long0);
}
}
else { // ellipsoidal form
con = this.ml0 + y / this.k0;
phi = pj_inv_mlfn(con, this.es, this.en);
if (Math.abs(phi) < HALF_PI) {
var sin_phi = Math.sin(phi);
var cos_phi = Math.cos(phi);
var tan_phi = Math.abs(cos_phi) > EPSLN ? Math.tan(phi) : 0;
var c = this.ep2 * Math.pow(cos_phi, 2);
var cs = Math.pow(c, 2);
var t = Math.pow(tan_phi, 2);
var ts = Math.pow(t, 2);
con = 1 - this.es * Math.pow(sin_phi, 2);
var d = x * Math.sqrt(con) / this.k0;
var ds = Math.pow(d, 2);
con = con * tan_phi;
lat = phi - (con * ds / (1 - this.es)) * 0.5 * (1 -
ds / 12 * (5 + 3 * t - 9 * c * t + c - 4 * cs -
ds / 30 * (61 + 90 * t - 252 * c * t + 45 * ts + 46 * c -
ds / 56 * (1385 + 3633 * t + 4095 * ts + 1574 * ts * t))));
lon = adjust_lon(this.long0 + (d * (1 -
ds / 6 * (1 + 2 * t + c -
ds / 20 * (5 + 28 * t + 24 * ts + 8 * c * t + 6 * c -
ds / 42 * (61 + 662 * t + 1320 * ts + 720 * ts * t)))) / cos_phi));
}
else {
lat = HALF_PI * sign(y);
lon = 0;
}
}
p.x = lon;
p.y = lat;
return p;
}
var names$t = ["Fast_Transverse_Mercator", "Fast Transverse Mercator"];
var tmerc = {
init: init$u,
forward: forward$s,
inverse: inverse$s,
names: names$t
};
function sinh(x) {
var r = Math.exp(x);
r = (r - 1 / r) / 2;
return r;
}
function hypot(x, y) {
x = Math.abs(x);
y = Math.abs(y);
var a = Math.max(x, y);
var b = Math.min(x, y) / (a ? a : 1);
return a * Math.sqrt(1 + Math.pow(b, 2));
}
function log1py(x) {
var y = 1 + x;
var z = y - 1;
return z === 0 ? x : x * Math.log(y) / z;
}
function asinhy(x) {
var y = Math.abs(x);
y = log1py(y * (1 + y / (hypot(1, y) + 1)));
return x < 0 ? -y : y;
}
function gatg(pp, B) {
var cos_2B = 2 * Math.cos(2 * B);
var i = pp.length - 1;
var h1 = pp[i];
var h2 = 0;
var h;
while (--i >= 0) {
h = -h2 + cos_2B * h1 + pp[i];
h2 = h1;
h1 = h;
}
return (B + h * Math.sin(2 * B));
}
function clens(pp, arg_r) {
var r = 2 * Math.cos(arg_r);
var i = pp.length - 1;
var hr1 = pp[i];
var hr2 = 0;
var hr;
while (--i >= 0) {
hr = -hr2 + r * hr1 + pp[i];
hr2 = hr1;
hr1 = hr;
}
return Math.sin(arg_r) * hr;
}
function cosh(x) {
var r = Math.exp(x);
r = (r + 1 / r) / 2;
return r;
}
function clens_cmplx(pp, arg_r, arg_i) {
var sin_arg_r = Math.sin(arg_r);
var cos_arg_r = Math.cos(arg_r);
var sinh_arg_i = sinh(arg_i);
var cosh_arg_i = cosh(arg_i);
var r = 2 * cos_arg_r * cosh_arg_i;
var i = -2 * sin_arg_r * sinh_arg_i;
var j = pp.length - 1;
var hr = pp[j];
var hi1 = 0;
var hr1 = 0;
var hi = 0;
var hr2;
var hi2;
while (--j >= 0) {
hr2 = hr1;
hi2 = hi1;
hr1 = hr;
hi1 = hi;
hr = -hr2 + r * hr1 - i * hi1 + pp[j];
hi = -hi2 + i * hr1 + r * hi1;
}
r = sin_arg_r * cosh_arg_i;
i = cos_arg_r * sinh_arg_i;
return [r * hr - i * hi, r * hi + i * hr];
}
// Heavily based on this etmerc projection implementation
function init$t() {
if (!this.approx && (isNaN(this.es) || this.es <= 0)) {
throw new Error('Incorrect elliptical usage. Try using the +approx option in the proj string, or PROJECTION["Fast_Transverse_Mercator"] in the WKT.');
}
if (this.approx) {
// When '+approx' is set, use tmerc instead
tmerc.init.apply(this);
this.forward = tmerc.forward;
this.inverse = tmerc.inverse;
}
this.x0 = this.x0 !== undefined ? this.x0 : 0;
this.y0 = this.y0 !== undefined ? this.y0 : 0;
this.long0 = this.long0 !== undefined ? this.long0 : 0;
this.lat0 = this.lat0 !== undefined ? this.lat0 : 0;
this.cgb = [];
this.cbg = [];
this.utg = [];
this.gtu = [];
var f = this.es / (1 + Math.sqrt(1 - this.es));
var n = f / (2 - f);
var np = n;
this.cgb[0] = n * (2 + n * (-2 / 3 + n * (-2 + n * (116 / 45 + n * (26 / 45 + n * (-2854 / 675 ))))));
this.cbg[0] = n * (-2 + n * ( 2 / 3 + n * ( 4 / 3 + n * (-82 / 45 + n * (32 / 45 + n * (4642 / 4725))))));
np = np * n;
this.cgb[1] = np * (7 / 3 + n * (-8 / 5 + n * (-227 / 45 + n * (2704 / 315 + n * (2323 / 945)))));
this.cbg[1] = np * (5 / 3 + n * (-16 / 15 + n * ( -13 / 9 + n * (904 / 315 + n * (-1522 / 945)))));
np = np * n;
this.cgb[2] = np * (56 / 15 + n * (-136 / 35 + n * (-1262 / 105 + n * (73814 / 2835))));
this.cbg[2] = np * (-26 / 15 + n * (34 / 21 + n * (8 / 5 + n * (-12686 / 2835))));
np = np * n;
this.cgb[3] = np * (4279 / 630 + n * (-332 / 35 + n * (-399572 / 14175)));
this.cbg[3] = np * (1237 / 630 + n * (-12 / 5 + n * ( -24832 / 14175)));
np = np * n;
this.cgb[4] = np * (4174 / 315 + n * (-144838 / 6237));
this.cbg[4] = np * (-734 / 315 + n * (109598 / 31185));
np = np * n;
this.cgb[5] = np * (601676 / 22275);
this.cbg[5] = np * (444337 / 155925);
np = Math.pow(n, 2);
this.Qn = this.k0 / (1 + n) * (1 + np * (1 / 4 + np * (1 / 64 + np / 256)));
this.utg[0] = n * (-0.5 + n * ( 2 / 3 + n * (-37 / 96 + n * ( 1 / 360 + n * (81 / 512 + n * (-96199 / 604800))))));
this.gtu[0] = n * (0.5 + n * (-2 / 3 + n * (5 / 16 + n * (41 / 180 + n * (-127 / 288 + n * (7891 / 37800))))));
this.utg[1] = np * (-1 / 48 + n * (-1 / 15 + n * (437 / 1440 + n * (-46 / 105 + n * (1118711 / 3870720)))));
this.gtu[1] = np * (13 / 48 + n * (-3 / 5 + n * (557 / 1440 + n * (281 / 630 + n * (-1983433 / 1935360)))));
np = np * n;
this.utg[2] = np * (-17 / 480 + n * (37 / 840 + n * (209 / 4480 + n * (-5569 / 90720 ))));
this.gtu[2] = np * (61 / 240 + n * (-103 / 140 + n * (15061 / 26880 + n * (167603 / 181440))));
np = np * n;
this.utg[3] = np * (-4397 / 161280 + n * (11 / 504 + n * (830251 / 7257600)));
this.gtu[3] = np * (49561 / 161280 + n * (-179 / 168 + n * (6601661 / 7257600)));
np = np * n;
this.utg[4] = np * (-4583 / 161280 + n * (108847 / 3991680));
this.gtu[4] = np * (34729 / 80640 + n * (-3418889 / 1995840));
np = np * n;
this.utg[5] = np * (-20648693 / 638668800);
this.gtu[5] = np * (212378941 / 319334400);
var Z = gatg(this.cbg, this.lat0);
this.Zb = -this.Qn * (Z + clens(this.gtu, 2 * Z));
}
function forward$r(p) {
var Ce = adjust_lon(p.x - this.long0);
var Cn = p.y;
Cn = gatg(this.cbg, Cn);
var sin_Cn = Math.sin(Cn);
var cos_Cn = Math.cos(Cn);
var sin_Ce = Math.sin(Ce);
var cos_Ce = Math.cos(Ce);
Cn = Math.atan2(sin_Cn, cos_Ce * cos_Cn);
Ce = Math.atan2(sin_Ce * cos_Cn, hypot(sin_Cn, cos_Cn * cos_Ce));
Ce = asinhy(Math.tan(Ce));
var tmp = clens_cmplx(this.gtu, 2 * Cn, 2 * Ce);
Cn = Cn + tmp[0];
Ce = Ce + tmp[1];
var x;
var y;
if (Math.abs(Ce) <= 2.623395162778) {
x = this.a * (this.Qn * Ce) + this.x0;
y = this.a * (this.Qn * Cn + this.Zb) + this.y0;
}
else {
x = Infinity;
y = Infinity;
}
p.x = x;
p.y = y;
return p;
}
function inverse$r(p) {
var Ce = (p.x - this.x0) * (1 / this.a);
var Cn = (p.y - this.y0) * (1 / this.a);
Cn = (Cn - this.Zb) / this.Qn;
Ce = Ce / this.Qn;
var lon;
var lat;
if (Math.abs(Ce) <= 2.623395162778) {
var tmp = clens_cmplx(this.utg, 2 * Cn, 2 * Ce);
Cn = Cn + tmp[0];
Ce = Ce + tmp[1];
Ce = Math.atan(sinh(Ce));
var sin_Cn = Math.sin(Cn);
var cos_Cn = Math.cos(Cn);
var sin_Ce = Math.sin(Ce);
var cos_Ce = Math.cos(Ce);
Cn = Math.atan2(sin_Cn * cos_Ce, hypot(sin_Ce, cos_Ce * cos_Cn));
Ce = Math.atan2(sin_Ce, cos_Ce * cos_Cn);
lon = adjust_lon(Ce + this.long0);
lat = gatg(this.cgb, Cn);
}
else {
lon = Infinity;
lat = Infinity;
}
p.x = lon;
p.y = lat;
return p;
}
var names$s = ["Extended_Transverse_Mercator", "Extended Transverse Mercator", "etmerc", "Transverse_Mercator", "Transverse Mercator", "tmerc"];
var etmerc = {
init: init$t,
forward: forward$r,
inverse: inverse$r,
names: names$s
};
function adjust_zone(zone, lon) {
if (zone === undefined) {
zone = Math.floor((adjust_lon(lon) + Math.PI) * 30 / Math.PI) + 1;
if (zone < 0) {
return 0;
} else if (zone > 60) {
return 60;
}
}
return zone;
}
var dependsOn = 'etmerc';
function init$s() {
var zone = adjust_zone(this.zone, this.long0);
if (zone === undefined) {
throw new Error('unknown utm zone');
}
this.lat0 = 0;
this.long0 = ((6 * Math.abs(zone)) - 183) * D2R$1;
this.x0 = 500000;
this.y0 = this.utmSouth ? 10000000 : 0;
this.k0 = 0.9996;
etmerc.init.apply(this);
this.forward = etmerc.forward;
this.inverse = etmerc.inverse;
}
var names$r = ["Universal Transverse Mercator System", "utm"];
var utm = {
init: init$s,
names: names$r,
dependsOn: dependsOn
};
function srat(esinp, exp) {
return (Math.pow((1 - esinp) / (1 + esinp), exp));
}
var MAX_ITER$2 = 20;
function init$r() {
var sphi = Math.sin(this.lat0);
var cphi = Math.cos(this.lat0);
cphi *= cphi;
this.rc = Math.sqrt(1 - this.es) / (1 - this.es * sphi * sphi);
this.C = Math.sqrt(1 + this.es * cphi * cphi / (1 - this.es));
this.phic0 = Math.asin(sphi / this.C);
this.ratexp = 0.5 * this.C * this.e;
this.K = Math.tan(0.5 * this.phic0 + FORTPI) / (Math.pow(Math.tan(0.5 * this.lat0 + FORTPI), this.C) * srat(this.e * sphi, this.ratexp));
}
function forward$q(p) {
var lon = p.x;
var lat = p.y;
p.y = 2 * Math.atan(this.K * Math.pow(Math.tan(0.5 * lat + FORTPI), this.C) * srat(this.e * Math.sin(lat), this.ratexp)) - HALF_PI;
p.x = this.C * lon;
return p;
}
function inverse$q(p) {
var DEL_TOL = 1e-14;
var lon = p.x / this.C;
var lat = p.y;
var num = Math.pow(Math.tan(0.5 * lat + FORTPI) / this.K, 1 / this.C);
for (var i = MAX_ITER$2; i > 0; --i) {
lat = 2 * Math.atan(num * srat(this.e * Math.sin(p.y), - 0.5 * this.e)) - HALF_PI;
if (Math.abs(lat - p.y) < DEL_TOL) {
break;
}
p.y = lat;
}
/* convergence failed */
if (!i) {
return null;
}
p.x = lon;
p.y = lat;
return p;
}
var names$q = ["gauss"];
var gauss = {
init: init$r,
forward: forward$q,
inverse: inverse$q,
names: names$q
};
function init$q() {
gauss.init.apply(this);
if (!this.rc) {
return;
}
this.sinc0 = Math.sin(this.phic0);
this.cosc0 = Math.cos(this.phic0);
this.R2 = 2 * this.rc;
if (!this.title) {
this.title = "Oblique Stereographic Alternative";
}
}
function forward$p(p) {
var sinc, cosc, cosl, k;
p.x = adjust_lon(p.x - this.long0);
gauss.forward.apply(this, [p]);
sinc = Math.sin(p.y);
cosc = Math.cos(p.y);
cosl = Math.cos(p.x);
k = this.k0 * this.R2 / (1 + this.sinc0 * sinc + this.cosc0 * cosc * cosl);
p.x = k * cosc * Math.sin(p.x);
p.y = k * (this.cosc0 * sinc - this.sinc0 * cosc * cosl);
p.x = this.a * p.x + this.x0;
p.y = this.a * p.y + this.y0;
return p;
}
function inverse$p(p) {
var sinc, cosc, lon, lat, rho;
p.x = (p.x - this.x0) / this.a;
p.y = (p.y - this.y0) / this.a;
p.x /= this.k0;
p.y /= this.k0;
if ((rho = Math.sqrt(p.x * p.x + p.y * p.y))) {
var c = 2 * Math.atan2(rho, this.R2);
sinc = Math.sin(c);
cosc = Math.cos(c);
lat = Math.asin(cosc * this.sinc0 + p.y * sinc * this.cosc0 / rho);
lon = Math.atan2(p.x * sinc, rho * this.cosc0 * cosc - p.y * this.sinc0 * sinc);
}
else {
lat = this.phic0;
lon = 0;
}
p.x = lon;
p.y = lat;
gauss.inverse.apply(this, [p]);
p.x = adjust_lon(p.x + this.long0);
return p;
}
var names$p = ["Stereographic_North_Pole", "Oblique_Stereographic", "sterea","Oblique Stereographic Alternative","Double_Stereographic"];
var sterea = {
init: init$q,
forward: forward$p,
inverse: inverse$p,
names: names$p
};
function ssfn_(phit, sinphi, eccen) {
sinphi *= eccen;
return (Math.tan(0.5 * (HALF_PI + phit)) * Math.pow((1 - sinphi) / (1 + sinphi), 0.5 * eccen));
}
function init$p() {
// setting default parameters
this.x0 = this.x0 || 0;
this.y0 = this.y0 || 0;
this.lat0 = this.lat0 || 0;
this.long0 = this.long0 || 0;
this.coslat0 = Math.cos(this.lat0);
this.sinlat0 = Math.sin(this.lat0);
if (this.sphere) {
if (this.k0 === 1 && !isNaN(this.lat_ts) && Math.abs(this.coslat0) <= EPSLN) {
this.k0 = 0.5 * (1 + sign(this.lat0) * Math.sin(this.lat_ts));
}
}
else {
if (Math.abs(this.coslat0) <= EPSLN) {
if (this.lat0 > 0) {
//North pole
//trace('stere:north pole');
this.con = 1;
}
else {
//South pole
//trace('stere:south pole');
this.con = -1;
}
}
this.cons = Math.sqrt(Math.pow(1 + this.e, 1 + this.e) * Math.pow(1 - this.e, 1 - this.e));
if (this.k0 === 1 && !isNaN(this.lat_ts) && Math.abs(this.coslat0) <= EPSLN && Math.abs(Math.cos(this.lat_ts)) > EPSLN) {
// When k0 is 1 (default value) and lat_ts is a vaild number and lat0 is at a pole and lat_ts is not at a pole
// Recalculate k0 using formula 21-35 from p161 of Snyder, 1987
this.k0 = 0.5 * this.cons * msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts)) / tsfnz(this.e, this.con * this.lat_ts, this.con * Math.sin(this.lat_ts));
}
this.ms1 = msfnz(this.e, this.sinlat0, this.coslat0);
this.X0 = 2 * Math.atan(this.ssfn_(this.lat0, this.sinlat0, this.e)) - HALF_PI;
this.cosX0 = Math.cos(this.X0);
this.sinX0 = Math.sin(this.X0);
}
}
// Stereographic forward equations--mapping lat,long to x,y
function forward$o(p) {
var lon = p.x;
var lat = p.y;
var sinlat = Math.sin(lat);
var coslat = Math.cos(lat);
var A, X, sinX, cosX, ts, rh;
var dlon = adjust_lon(lon - this.long0);
if (Math.abs(Math.abs(lon - this.long0) - Math.PI) <= EPSLN && Math.abs(lat + this.lat0) <= EPSLN) {
//case of the origine point
//trace('stere:this is the origin point');
p.x = NaN;
p.y = NaN;
return p;
}
if (this.sphere) {
//trace('stere:sphere case');
A = 2 * this.k0 / (1 + this.sinlat0 * sinlat + this.coslat0 * coslat * Math.cos(dlon));
p.x = this.a * A * coslat * Math.sin(dlon) + this.x0;
p.y = this.a * A * (this.coslat0 * sinlat - this.sinlat0 * coslat * Math.cos(dlon)) + this.y0;
return p;
}
else {
X = 2 * Math.atan(this.ssfn_(lat, sinlat, this.e)) - HALF_PI;
cosX = Math.cos(X);
sinX = Math.sin(X);
if (Math.abs(this.coslat0) <= EPSLN) {
ts = tsfnz(this.e, lat * this.con, this.con * sinlat);
rh = 2 * this.a * this.k0 * ts / this.cons;
p.x = this.x0 + rh * Math.sin(lon - this.long0);
p.y = this.y0 - this.con * rh * Math.cos(lon - this.long0);
//trace(p.toString());
return p;
}
else if (Math.abs(this.sinlat0) < EPSLN) {
//Eq
//trace('stere:equateur');
A = 2 * this.a * this.k0 / (1 + cosX * Math.cos(dlon));
p.y = A * sinX;
}
else {
//other case
//trace('stere:normal case');
A = 2 * this.a * this.k0 * this.ms1 / (this.cosX0 * (1 + this.sinX0 * sinX + this.cosX0 * cosX * Math.cos(dlon)));
p.y = A * (this.cosX0 * sinX - this.sinX0 * cosX * Math.cos(dlon)) + this.y0;
}
p.x = A * cosX * Math.sin(dlon) + this.x0;
}
//trace(p.toString());
return p;
}
//* Stereographic inverse equations--mapping x,y to lat/long
function inverse$o(p) {
p.x -= this.x0;
p.y -= this.y0;
var lon, lat, ts, ce, Chi;
var rh = Math.sqrt(p.x * p.x + p.y * p.y);
if (this.sphere) {
var c = 2 * Math.atan(rh / (2 * this.a * this.k0));
lon = this.long0;
lat = this.lat0;
if (rh <= EPSLN) {
p.x = lon;
p.y = lat;
return p;
}
lat = Math.asin(Math.cos(c) * this.sinlat0 + p.y * Math.sin(c) * this.coslat0 / rh);
if (Math.abs(this.coslat0) < EPSLN) {
if (this.lat0 > 0) {
lon = adjust_lon(this.long0 + Math.atan2(p.x, - 1 * p.y));
}
else {
lon = adjust_lon(this.long0 + Math.atan2(p.x, p.y));
}
}
else {
lon = adjust_lon(this.long0 + Math.atan2(p.x * Math.sin(c), rh * this.coslat0 * Math.cos(c) - p.y * this.sinlat0 * Math.sin(c)));
}
p.x = lon;
p.y = lat;
return p;
}
else {
if (Math.abs(this.coslat0) <= EPSLN) {
if (rh <= EPSLN) {
lat = this.lat0;
lon = this.long0;
p.x = lon;
p.y = lat;
//trace(p.toString());
return p;
}
p.x *= this.con;
p.y *= this.con;
ts = rh * this.cons / (2 * this.a * this.k0);
lat = this.con * phi2z(this.e, ts);
lon = this.con * adjust_lon(this.con * this.long0 + Math.atan2(p.x, - 1 * p.y));
}
else {
ce = 2 * Math.atan(rh * this.cosX0 / (2 * this.a * this.k0 * this.ms1));
lon = this.long0;
if (rh <= EPSLN) {
Chi = this.X0;
}
else {
Chi = Math.asin(Math.cos(ce) * this.sinX0 + p.y * Math.sin(ce) * this.cosX0 / rh);
lon = adjust_lon(this.long0 + Math.atan2(p.x * Math.sin(ce), rh * this.cosX0 * Math.cos(ce) - p.y * this.sinX0 * Math.sin(ce)));
}
lat = -1 * phi2z(this.e, Math.tan(0.5 * (HALF_PI + Chi)));
}
}
p.x = lon;
p.y = lat;
//trace(p.toString());
return p;
}
var names$o = ["stere", "Stereographic_South_Pole", "Polar Stereographic (variant B)", "Polar_Stereographic"];
var stere = {
init: init$p,
forward: forward$o,
inverse: inverse$o,
names: names$o,
ssfn_: ssfn_
};
/*
references:
Formules et constantes pour le Calcul pour la
projection cylindrique conforme à axe oblique et pour la transformation entre
des systèmes de référence.
http://www.swisstopo.admin.ch/internet/swisstopo/fr/home/topics/survey/sys/refsys/switzerland.parsysrelated1.31216.downloadList.77004.DownloadFile.tmp/swissprojectionfr.pdf
*/
function init$o() {
var phy0 = this.lat0;
this.lambda0 = this.long0;
var sinPhy0 = Math.sin(phy0);
var semiMajorAxis = this.a;
var invF = this.rf;
var flattening = 1 / invF;
var e2 = 2 * flattening - Math.pow(flattening, 2);
var e = this.e = Math.sqrt(e2);
this.R = this.k0 * semiMajorAxis * Math.sqrt(1 - e2) / (1 - e2 * Math.pow(sinPhy0, 2));
this.alpha = Math.sqrt(1 + e2 / (1 - e2) * Math.pow(Math.cos(phy0), 4));
this.b0 = Math.asin(sinPhy0 / this.alpha);
var k1 = Math.log(Math.tan(Math.PI / 4 + this.b0 / 2));
var k2 = Math.log(Math.tan(Math.PI / 4 + phy0 / 2));
var k3 = Math.log((1 + e * sinPhy0) / (1 - e * sinPhy0));
this.K = k1 - this.alpha * k2 + this.alpha * e / 2 * k3;
}
function forward$n(p) {
var Sa1 = Math.log(Math.tan(Math.PI / 4 - p.y / 2));
var Sa2 = this.e / 2 * Math.log((1 + this.e * Math.sin(p.y)) / (1 - this.e * Math.sin(p.y)));
var S = -this.alpha * (Sa1 + Sa2) + this.K;
// spheric latitude
var b = 2 * (Math.atan(Math.exp(S)) - Math.PI / 4);
// spheric longitude
var I = this.alpha * (p.x - this.lambda0);
// psoeudo equatorial rotation
var rotI = Math.atan(Math.sin(I) / (Math.sin(this.b0) * Math.tan(b) + Math.cos(this.b0) * Math.cos(I)));
var rotB = Math.asin(Math.cos(this.b0) * Math.sin(b) - Math.sin(this.b0) * Math.cos(b) * Math.cos(I));
p.y = this.R / 2 * Math.log((1 + Math.sin(rotB)) / (1 - Math.sin(rotB))) + this.y0;
p.x = this.R * rotI + this.x0;
return p;
}
function inverse$n(p) {
var Y = p.x - this.x0;
var X = p.y - this.y0;
var rotI = Y / this.R;
var rotB = 2 * (Math.atan(Math.exp(X / this.R)) - Math.PI / 4);
var b = Math.asin(Math.cos(this.b0) * Math.sin(rotB) + Math.sin(this.b0) * Math.cos(rotB) * Math.cos(rotI));
var I = Math.atan(Math.sin(rotI) / (Math.cos(this.b0) * Math.cos(rotI) - Math.sin(this.b0) * Math.tan(rotB)));
var lambda = this.lambda0 + I / this.alpha;
var S = 0;
var phy = b;
var prevPhy = -1000;
var iteration = 0;
while (Math.abs(phy - prevPhy) > 0.0000001) {
if (++iteration > 20) {
//...reportError("omercFwdInfinity");
return;
}
//S = Math.log(Math.tan(Math.PI / 4 + phy / 2));
S = 1 / this.alpha * (Math.log(Math.tan(Math.PI / 4 + b / 2)) - this.K) + this.e * Math.log(Math.tan(Math.PI / 4 + Math.asin(this.e * Math.sin(phy)) / 2));
prevPhy = phy;
phy = 2 * Math.atan(Math.exp(S)) - Math.PI / 2;
}
p.x = lambda;
p.y = phy;
return p;
}
var names$n = ["somerc"];
var somerc = {
init: init$o,
forward: forward$n,
inverse: inverse$n,
names: names$n
};
var TOL = 1e-7;
function isTypeA(P) {
var typeAProjections = ['Hotine_Oblique_Mercator','Hotine_Oblique_Mercator_Azimuth_Natural_Origin'];
var projectionName = typeof P.PROJECTION === "object" ? Object.keys(P.PROJECTION)[0] : P.PROJECTION;
return 'no_uoff' in P || 'no_off' in P || typeAProjections.indexOf(projectionName) !== -1;
}
/* Initialize the Oblique Mercator projection
------------------------------------------*/
function init$n() {
var con, com, cosph0, D, F, H, L, sinph0, p, J, gamma = 0,
gamma0, lamc = 0, lam1 = 0, lam2 = 0, phi1 = 0, phi2 = 0, alpha_c = 0;
// only Type A uses the no_off or no_uoff property
// https://github.com/OSGeo/proj.4/issues/104
this.no_off = isTypeA(this);
this.no_rot = 'no_rot' in this;
var alp = false;
if ("alpha" in this) {
alp = true;
}
var gam = false;
if ("rectified_grid_angle" in this) {
gam = true;
}
if (alp) {
alpha_c = this.alpha;
}
if (gam) {
gamma = (this.rectified_grid_angle * D2R$1);
}
if (alp || gam) {
lamc = this.longc;
} else {
lam1 = this.long1;
phi1 = this.lat1;
lam2 = this.long2;
phi2 = this.lat2;
if (Math.abs(phi1 - phi2) <= TOL || (con = Math.abs(phi1)) <= TOL ||
Math.abs(con - HALF_PI) <= TOL || Math.abs(Math.abs(this.lat0) - HALF_PI) <= TOL ||
Math.abs(Math.abs(phi2) - HALF_PI) <= TOL) {
throw new Error();
}
}
var one_es = 1.0 - this.es;
com = Math.sqrt(one_es);
if (Math.abs(this.lat0) > EPSLN) {
sinph0 = Math.sin(this.lat0);
cosph0 = Math.cos(this.lat0);
con = 1 - this.es * sinph0 * sinph0;
this.B = cosph0 * cosph0;
this.B = Math.sqrt(1 + this.es * this.B * this.B / one_es);
this.A = this.B * this.k0 * com / con;
D = this.B * com / (cosph0 * Math.sqrt(con));
F = D * D -1;
if (F <= 0) {
F = 0;
} else {
F = Math.sqrt(F);
if (this.lat0 < 0) {
F = -F;
}
}
this.E = F += D;
this.E *= Math.pow(tsfnz(this.e, this.lat0, sinph0), this.B);
} else {
this.B = 1 / com;
this.A = this.k0;
this.E = D = F = 1;
}
if (alp || gam) {
if (alp) {
gamma0 = Math.asin(Math.sin(alpha_c) / D);
if (!gam) {
gamma = alpha_c;
}
} else {
gamma0 = gamma;
alpha_c = Math.asin(D * Math.sin(gamma0));
}
this.lam0 = lamc - Math.asin(0.5 * (F - 1 / F) * Math.tan(gamma0)) / this.B;
} else {
H = Math.pow(tsfnz(this.e, phi1, Math.sin(phi1)), this.B);
L = Math.pow(tsfnz(this.e, phi2, Math.sin(phi2)), this.B);
F = this.E / H;
p = (L - H) / (L + H);
J = this.E * this.E;
J = (J - L * H) / (J + L * H);
con = lam1 - lam2;
if (con < -Math.pi) {
lam2 -=TWO_PI;
} else if (con > Math.pi) {
lam2 += TWO_PI;
}
this.lam0 = adjust_lon(0.5 * (lam1 + lam2) - Math.atan(J * Math.tan(0.5 * this.B * (lam1 - lam2)) / p) / this.B);
gamma0 = Math.atan(2 * Math.sin(this.B * adjust_lon(lam1 - this.lam0)) / (F - 1 / F));
gamma = alpha_c = Math.asin(D * Math.sin(gamma0));
}
this.singam = Math.sin(gamma0);
this.cosgam = Math.cos(gamma0);
this.sinrot = Math.sin(gamma);
this.cosrot = Math.cos(gamma);
this.rB = 1 / this.B;
this.ArB = this.A * this.rB;
this.BrA = 1 / this.ArB;
this.A * this.B;
if (this.no_off) {
this.u_0 = 0;
} else {
this.u_0 = Math.abs(this.ArB * Math.atan(Math.sqrt(D * D - 1) / Math.cos(alpha_c)));
if (this.lat0 < 0) {
this.u_0 = - this.u_0;
}
}
F = 0.5 * gamma0;
this.v_pole_n = this.ArB * Math.log(Math.tan(FORTPI - F));
this.v_pole_s = this.ArB * Math.log(Math.tan(FORTPI + F));
}
/* Oblique Mercator forward equations--mapping lat,long to x,y
----------------------------------------------------------*/
function forward$m(p) {
var coords = {};
var S, T, U, V, W, temp, u, v;
p.x = p.x - this.lam0;
if (Math.abs(Math.abs(p.y) - HALF_PI) > EPSLN) {
W = this.E / Math.pow(tsfnz(this.e, p.y, Math.sin(p.y)), this.B);
temp = 1 / W;
S = 0.5 * (W - temp);
T = 0.5 * (W + temp);
V = Math.sin(this.B * p.x);
U = (S * this.singam - V * this.cosgam) / T;
if (Math.abs(Math.abs(U) - 1.0) < EPSLN) {
throw new Error();
}
v = 0.5 * this.ArB * Math.log((1 - U)/(1 + U));
temp = Math.cos(this.B * p.x);
if (Math.abs(temp) < TOL) {
u = this.A * p.x;
} else {
u = this.ArB * Math.atan2((S * this.cosgam + V * this.singam), temp);
}
} else {
v = p.y > 0 ? this.v_pole_n : this.v_pole_s;
u = this.ArB * p.y;
}
if (this.no_rot) {
coords.x = u;
coords.y = v;
} else {
u -= this.u_0;
coords.x = v * this.cosrot + u * this.sinrot;
coords.y = u * this.cosrot - v * this.sinrot;
}
coords.x = (this.a * coords.x + this.x0);
coords.y = (this.a * coords.y + this.y0);
return coords;
}
function inverse$m(p) {
var u, v, Qp, Sp, Tp, Vp, Up;
var coords = {};
p.x = (p.x - this.x0) * (1.0 / this.a);
p.y = (p.y - this.y0) * (1.0 / this.a);
if (this.no_rot) {
v = p.y;
u = p.x;
} else {
v = p.x * this.cosrot - p.y * this.sinrot;
u = p.y * this.cosrot + p.x * this.sinrot + this.u_0;
}
Qp = Math.exp(-this.BrA * v);
Sp = 0.5 * (Qp - 1 / Qp);
Tp = 0.5 * (Qp + 1 / Qp);
Vp = Math.sin(this.BrA * u);
Up = (Vp * this.cosgam + Sp * this.singam) / Tp;
if (Math.abs(Math.abs(Up) - 1) < EPSLN) {
coords.x = 0;
coords.y = Up < 0 ? -HALF_PI : HALF_PI;
} else {
coords.y = this.E / Math.sqrt((1 + Up) / (1 - Up));
coords.y = phi2z(this.e, Math.pow(coords.y, 1 / this.B));
if (coords.y === Infinity) {
throw new Error();
}
coords.x = -this.rB * Math.atan2((Sp * this.cosgam - Vp * this.singam), Math.cos(this.BrA * u));
}
coords.x += this.lam0;
return coords;
}
var names$m = ["Hotine_Oblique_Mercator", "Hotine Oblique Mercator", "Hotine_Oblique_Mercator_Azimuth_Natural_Origin", "Hotine_Oblique_Mercator_Two_Point_Natural_Origin", "Hotine_Oblique_Mercator_Azimuth_Center", "Oblique_Mercator", "omerc"];
var omerc = {
init: init$n,
forward: forward$m,
inverse: inverse$m,
names: names$m
};
function init$m() {
//double lat0; /* the reference latitude */
//double long0; /* the reference longitude */
//double lat1; /* first standard parallel */
//double lat2; /* second standard parallel */
//double r_maj; /* major axis */
//double r_min; /* minor axis */
//double false_east; /* x offset in meters */
//double false_north; /* y offset in meters */
//the above value can be set with proj4.defs
//example: proj4.defs("EPSG:2154","+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
if (!this.lat2) {
this.lat2 = this.lat1;
} //if lat2 is not defined
if (!this.k0) {
this.k0 = 1;
}
this.x0 = this.x0 || 0;
this.y0 = this.y0 || 0;
// Standard Parallels cannot be equal and on opposite sides of the equator
if (Math.abs(this.lat1 + this.lat2) < EPSLN) {
return;
}
var temp = this.b / this.a;
this.e = Math.sqrt(1 - temp * temp);
var sin1 = Math.sin(this.lat1);
var cos1 = Math.cos(this.lat1);
var ms1 = msfnz(this.e, sin1, cos1);
var ts1 = tsfnz(this.e, this.lat1, sin1);
var sin2 = Math.sin(this.lat2);
var cos2 = Math.cos(this.lat2);
var ms2 = msfnz(this.e, sin2, cos2);
var ts2 = tsfnz(this.e, this.lat2, sin2);
var ts0 = tsfnz(this.e, this.lat0, Math.sin(this.lat0));
if (Math.abs(this.lat1 - this.lat2) > EPSLN) {
this.ns = Math.log(ms1 / ms2) / Math.log(ts1 / ts2);
}
else {
this.ns = sin1;
}
if (isNaN(this.ns)) {
this.ns = sin1;
}
this.f0 = ms1 / (this.ns * Math.pow(ts1, this.ns));
this.rh = this.a * this.f0 * Math.pow(ts0, this.ns);
if (!this.title) {
this.title = "Lambert Conformal Conic";
}
}
// Lambert Conformal conic forward equations--mapping lat,long to x,y
// -----------------------------------------------------------------
function forward$l(p) {
var lon = p.x;
var lat = p.y;
// singular cases :
if (Math.abs(2 * Math.abs(lat) - Math.PI) <= EPSLN) {
lat = sign(lat) * (HALF_PI - 2 * EPSLN);
}
var con = Math.abs(Math.abs(lat) - HALF_PI);
var ts, rh1;
if (con > EPSLN) {
ts = tsfnz(this.e, lat, Math.sin(lat));
rh1 = this.a * this.f0 * Math.pow(ts, this.ns);
}
else {
con = lat * this.ns;
if (con <= 0) {
return null;
}
rh1 = 0;
}
var theta = this.ns * adjust_lon(lon - this.long0);
p.x = this.k0 * (rh1 * Math.sin(theta)) + this.x0;
p.y = this.k0 * (this.rh - rh1 * Math.cos(theta)) + this.y0;
return p;
}
// Lambert Conformal Conic inverse equations--mapping x,y to lat/long
// -----------------------------------------------------------------
function inverse$l(p) {
var rh1, con, ts;
var lat, lon;
var x = (p.x - this.x0) / this.k0;
var y = (this.rh - (p.y - this.y0) / this.k0);
if (this.ns > 0) {
rh1 = Math.sqrt(x * x + y * y);
con = 1;
}
else {
rh1 = -Math.sqrt(x * x + y * y);
con = -1;
}
var theta = 0;
if (rh1 !== 0) {
theta = Math.atan2((con * x), (con * y));
}
if ((rh1 !== 0) || (this.ns > 0)) {
con = 1 / this.ns;
ts = Math.pow((rh1 / (this.a * this.f0)), con);
lat = phi2z(this.e, ts);
if (lat === -9999) {
return null;
}
}
else {
lat = -HALF_PI;
}
lon = adjust_lon(theta / this.ns + this.long0);
p.x = lon;
p.y = lat;
return p;
}
var names$l = [
"Lambert Tangential Conformal Conic Projection",
"Lambert_Conformal_Conic",
"Lambert_Conformal_Conic_1SP",
"Lambert_Conformal_Conic_2SP",
"lcc",
"Lambert Conic Conformal (1SP)",
"Lambert Conic Conformal (2SP)"
];
var lcc = {
init: init$m,
forward: forward$l,
inverse: inverse$l,
names: names$l
};
function init$l() {
this.a = 6377397.155;
this.es = 0.006674372230614;
this.e = Math.sqrt(this.es);
if (!this.lat0) {
this.lat0 = 0.863937979737193;
}
if (!this.long0) {
this.long0 = 0.7417649320975901 - 0.308341501185665;
}
/* if scale not set default to 0.9999 */
if (!this.k0) {
this.k0 = 0.9999;
}
this.s45 = 0.785398163397448; /* 45 */
this.s90 = 2 * this.s45;
this.fi0 = this.lat0;
this.e2 = this.es;
this.e = Math.sqrt(this.e2);
this.alfa = Math.sqrt(1 + (this.e2 * Math.pow(Math.cos(this.fi0), 4)) / (1 - this.e2));
this.uq = 1.04216856380474;
this.u0 = Math.asin(Math.sin(this.fi0) / this.alfa);
this.g = Math.pow((1 + this.e * Math.sin(this.fi0)) / (1 - this.e * Math.sin(this.fi0)), this.alfa * this.e / 2);
this.k = Math.tan(this.u0 / 2 + this.s45) / Math.pow(Math.tan(this.fi0 / 2 + this.s45), this.alfa) * this.g;
this.k1 = this.k0;
this.n0 = this.a * Math.sqrt(1 - this.e2) / (1 - this.e2 * Math.pow(Math.sin(this.fi0), 2));
this.s0 = 1.37008346281555;
this.n = Math.sin(this.s0);
this.ro0 = this.k1 * this.n0 / Math.tan(this.s0);
this.ad = this.s90 - this.uq;
}
/* ellipsoid */
/* calculate xy from lat/lon */
/* Constants, identical to inverse transform function */
function forward$k(p) {
var gfi, u, deltav, s, d, eps, ro;
var lon = p.x;
var lat = p.y;
var delta_lon = adjust_lon(lon - this.long0);
/* Transformation */
gfi = Math.pow(((1 + this.e * Math.sin(lat)) / (1 - this.e * Math.sin(lat))), (this.alfa * this.e / 2));
u = 2 * (Math.atan(this.k * Math.pow(Math.tan(lat / 2 + this.s45), this.alfa) / gfi) - this.s45);
deltav = -delta_lon * this.alfa;
s = Math.asin(Math.cos(this.ad) * Math.sin(u) + Math.sin(this.ad) * Math.cos(u) * Math.cos(deltav));
d = Math.asin(Math.cos(u) * Math.sin(deltav) / Math.cos(s));
eps = this.n * d;
ro = this.ro0 * Math.pow(Math.tan(this.s0 / 2 + this.s45), this.n) / Math.pow(Math.tan(s / 2 + this.s45), this.n);
p.y = ro * Math.cos(eps) / 1;
p.x = ro * Math.sin(eps) / 1;
if (!this.czech) {
p.y *= -1;
p.x *= -1;
}
return (p);
}
/* calculate lat/lon from xy */
function inverse$k(p) {
var u, deltav, s, d, eps, ro, fi1;
var ok;
/* Transformation */
/* revert y, x*/
var tmp = p.x;
p.x = p.y;
p.y = tmp;
if (!this.czech) {
p.y *= -1;
p.x *= -1;
}
ro = Math.sqrt(p.x * p.x + p.y * p.y);
eps = Math.atan2(p.y, p.x);
d = eps / Math.sin(this.s0);
s = 2 * (Math.atan(Math.pow(this.ro0 / ro, 1 / this.n) * Math.tan(this.s0 / 2 + this.s45)) - this.s45);
u = Math.asin(Math.cos(this.ad) * Math.sin(s) - Math.sin(this.ad) * Math.cos(s) * Math.cos(d));
deltav = Math.asin(Math.cos(s) * Math.sin(d) / Math.cos(u));
p.x = this.long0 - deltav / this.alfa;
fi1 = u;
ok = 0;
var iter = 0;
do {
p.y = 2 * (Math.atan(Math.pow(this.k, - 1 / this.alfa) * Math.pow(Math.tan(u / 2 + this.s45), 1 / this.alfa) * Math.pow((1 + this.e * Math.sin(fi1)) / (1 - this.e * Math.sin(fi1)), this.e / 2)) - this.s45);
if (Math.abs(fi1 - p.y) < 0.0000000001) {
ok = 1;
}
fi1 = p.y;
iter += 1;
} while (ok === 0 && iter < 15);
if (iter >= 15) {
return null;
}
return (p);
}
var names$k = ["Krovak", "krovak"];
var krovak = {
init: init$l,
forward: forward$k,
inverse: inverse$k,
names: names$k
};
function mlfn(e0, e1, e2, e3, phi) {
return (e0 * phi - e1 * Math.sin(2 * phi) + e2 * Math.sin(4 * phi) - e3 * Math.sin(6 * phi));
}
function e0fn(x) {
return (1 - 0.25 * x * (1 + x / 16 * (3 + 1.25 * x)));
}
function e1fn(x) {
return (0.375 * x * (1 + 0.25 * x * (1 + 0.46875 * x)));
}
function e2fn(x) {
return (0.05859375 * x * x * (1 + 0.75 * x));
}
function e3fn(x) {
return (x * x * x * (35 / 3072));
}
function gN(a, e, sinphi) {
var temp = e * sinphi;
return a / Math.sqrt(1 - temp * temp);
}
function adjust_lat(x) {
return (Math.abs(x) < HALF_PI) ? x : (x - (sign(x) * Math.PI));
}
function imlfn(ml, e0, e1, e2, e3) {
var phi;
var dphi;
phi = ml / e0;
for (var i = 0; i < 15; i++) {
dphi = (ml - (e0 * phi - e1 * Math.sin(2 * phi) + e2 * Math.sin(4 * phi) - e3 * Math.sin(6 * phi))) / (e0 - 2 * e1 * Math.cos(2 * phi) + 4 * e2 * Math.cos(4 * phi) - 6 * e3 * Math.cos(6 * phi));
phi += dphi;
if (Math.abs(dphi) <= 0.0000000001) {
return phi;
}
}
//..reportError("IMLFN-CONV:Latitude failed to converge after 15 iterations");
return NaN;
}
function init$k() {
if (!this.sphere) {
this.e0 = e0fn(this.es);
this.e1 = e1fn(this.es);
this.e2 = e2fn(this.es);
this.e3 = e3fn(this.es);
this.ml0 = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0);
}
}
/* Cassini forward equations--mapping lat,long to x,y
-----------------------------------------------------------------------*/
function forward$j(p) {
/* Forward equations
-----------------*/
var x, y;
var lam = p.x;
var phi = p.y;
lam = adjust_lon(lam - this.long0);
if (this.sphere) {
x = this.a * Math.asin(Math.cos(phi) * Math.sin(lam));
y = this.a * (Math.atan2(Math.tan(phi), Math.cos(lam)) - this.lat0);
}
else {
//ellipsoid
var sinphi = Math.sin(phi);
var cosphi = Math.cos(phi);
var nl = gN(this.a, this.e, sinphi);
var tl = Math.tan(phi) * Math.tan(phi);
var al = lam * Math.cos(phi);
var asq = al * al;
var cl = this.es * cosphi * cosphi / (1 - this.es);
var ml = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, phi);
x = nl * al * (1 - asq * tl * (1 / 6 - (8 - tl + 8 * cl) * asq / 120));
y = ml - this.ml0 + nl * sinphi / cosphi * asq * (0.5 + (5 - tl + 6 * cl) * asq / 24);
}
p.x = x + this.x0;
p.y = y + this.y0;
return p;
}
/* Inverse equations
-----------------*/
function inverse$j(p) {
p.x -= this.x0;
p.y -= this.y0;
var x = p.x / this.a;
var y = p.y / this.a;
var phi, lam;
if (this.sphere) {
var dd = y + this.lat0;
phi = Math.asin(Math.sin(dd) * Math.cos(x));
lam = Math.atan2(Math.tan(x), Math.cos(dd));
}
else {
/* ellipsoid */
var ml1 = this.ml0 / this.a + y;
var phi1 = imlfn(ml1, this.e0, this.e1, this.e2, this.e3);
if (Math.abs(Math.abs(phi1) - HALF_PI) <= EPSLN) {
p.x = this.long0;
p.y = HALF_PI;
if (y < 0) {
p.y *= -1;
}
return p;
}
var nl1 = gN(this.a, this.e, Math.sin(phi1));
var rl1 = nl1 * nl1 * nl1 / this.a / this.a * (1 - this.es);
var tl1 = Math.pow(Math.tan(phi1), 2);
var dl = x * this.a / nl1;
var dsq = dl * dl;
phi = phi1 - nl1 * Math.tan(phi1) / rl1 * dl * dl * (0.5 - (1 + 3 * tl1) * dl * dl / 24);
lam = dl * (1 - dsq * (tl1 / 3 + (1 + 3 * tl1) * tl1 * dsq / 15)) / Math.cos(phi1);
}
p.x = adjust_lon(lam + this.long0);
p.y = adjust_lat(phi);
return p;
}
var names$j = ["Cassini", "Cassini_Soldner", "cass"];
var cass = {
init: init$k,
forward: forward$j,
inverse: inverse$j,
names: names$j
};
function qsfnz(eccent, sinphi) {
var con;
if (eccent > 1.0e-7) {
con = eccent * sinphi;
return ((1 - eccent * eccent) * (sinphi / (1 - con * con) - (0.5 / eccent) * Math.log((1 - con) / (1 + con))));
}
else {
return (2 * sinphi);
}
}
/*
reference
"New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
*/
var S_POLE = 1;
var N_POLE = 2;
var EQUIT = 3;
var OBLIQ = 4;
/* Initialize the Lambert Azimuthal Equal Area projection
------------------------------------------------------*/
function init$j() {
var t = Math.abs(this.lat0);
if (Math.abs(t - HALF_PI) < EPSLN) {
this.mode = this.lat0 < 0 ? this.S_POLE : this.N_POLE;
}
else if (Math.abs(t) < EPSLN) {
this.mode = this.EQUIT;
}
else {
this.mode = this.OBLIQ;
}
if (this.es > 0) {
var sinphi;
this.qp = qsfnz(this.e, 1);
this.mmf = 0.5 / (1 - this.es);
this.apa = authset(this.es);
switch (this.mode) {
case this.N_POLE:
this.dd = 1;
break;
case this.S_POLE:
this.dd = 1;
break;
case this.EQUIT:
this.rq = Math.sqrt(0.5 * this.qp);
this.dd = 1 / this.rq;
this.xmf = 1;
this.ymf = 0.5 * this.qp;
break;
case this.OBLIQ:
this.rq = Math.sqrt(0.5 * this.qp);
sinphi = Math.sin(this.lat0);
this.sinb1 = qsfnz(this.e, sinphi) / this.qp;
this.cosb1 = Math.sqrt(1 - this.sinb1 * this.sinb1);
this.dd = Math.cos(this.lat0) / (Math.sqrt(1 - this.es * sinphi * sinphi) * this.rq * this.cosb1);
this.ymf = (this.xmf = this.rq) / this.dd;
this.xmf *= this.dd;
break;
}
}
else {
if (this.mode === this.OBLIQ) {
this.sinph0 = Math.sin(this.lat0);
this.cosph0 = Math.cos(this.lat0);
}
}
}
/* Lambert Azimuthal Equal Area forward equations--mapping lat,long to x,y
-----------------------------------------------------------------------*/
function forward$i(p) {
/* Forward equations
-----------------*/
var x, y, coslam, sinlam, sinphi, q, sinb, cosb, b, cosphi;
var lam = p.x;
var phi = p.y;
lam = adjust_lon(lam - this.long0);
if (this.sphere) {
sinphi = Math.sin(phi);
cosphi = Math.cos(phi);
coslam = Math.cos(lam);
if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
y = (this.mode === this.EQUIT) ? 1 + cosphi * coslam : 1 + this.sinph0 * sinphi + this.cosph0 * cosphi * coslam;
if (y <= EPSLN) {
return null;
}
y = Math.sqrt(2 / y);
x = y * cosphi * Math.sin(lam);
y *= (this.mode === this.EQUIT) ? sinphi : this.cosph0 * sinphi - this.sinph0 * cosphi * coslam;
}
else if (this.mode === this.N_POLE || this.mode === this.S_POLE) {
if (this.mode === this.N_POLE) {
coslam = -coslam;
}
if (Math.abs(phi + this.lat0) < EPSLN) {
return null;
}
y = FORTPI - phi * 0.5;
y = 2 * ((this.mode === this.S_POLE) ? Math.cos(y) : Math.sin(y));
x = y * Math.sin(lam);
y *= coslam;
}
}
else {
sinb = 0;
cosb = 0;
b = 0;
coslam = Math.cos(lam);
sinlam = Math.sin(lam);
sinphi = Math.sin(phi);
q = qsfnz(this.e, sinphi);
if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
sinb = q / this.qp;
cosb = Math.sqrt(1 - sinb * sinb);
}
switch (this.mode) {
case this.OBLIQ:
b = 1 + this.sinb1 * sinb + this.cosb1 * cosb * coslam;
break;
case this.EQUIT:
b = 1 + cosb * coslam;
break;
case this.N_POLE:
b = HALF_PI + phi;
q = this.qp - q;
break;
case this.S_POLE:
b = phi - HALF_PI;
q = this.qp + q;
break;
}
if (Math.abs(b) < EPSLN) {
return null;
}
switch (this.mode) {
case this.OBLIQ:
case this.EQUIT:
b = Math.sqrt(2 / b);
if (this.mode === this.OBLIQ) {
y = this.ymf * b * (this.cosb1 * sinb - this.sinb1 * cosb * coslam);
}
else {
y = (b = Math.sqrt(2 / (1 + cosb * coslam))) * sinb * this.ymf;
}
x = this.xmf * b * cosb * sinlam;
break;
case this.N_POLE:
case this.S_POLE:
if (q >= 0) {
x = (b = Math.sqrt(q)) * sinlam;
y = coslam * ((this.mode === this.S_POLE) ? b : -b);
}
else {
x = y = 0;
}
break;
}
}
p.x = this.a * x + this.x0;
p.y = this.a * y + this.y0;
return p;
}
/* Inverse equations
-----------------*/
function inverse$i(p) {
p.x -= this.x0;
p.y -= this.y0;
var x = p.x / this.a;
var y = p.y / this.a;
var lam, phi, cCe, sCe, q, rho, ab;
if (this.sphere) {
var cosz = 0,
rh, sinz = 0;
rh = Math.sqrt(x * x + y * y);
phi = rh * 0.5;
if (phi > 1) {
return null;
}
phi = 2 * Math.asin(phi);
if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
sinz = Math.sin(phi);
cosz = Math.cos(phi);
}
switch (this.mode) {
case this.EQUIT:
phi = (Math.abs(rh) <= EPSLN) ? 0 : Math.asin(y * sinz / rh);
x *= sinz;
y = cosz * rh;
break;
case this.OBLIQ:
phi = (Math.abs(rh) <= EPSLN) ? this.lat0 : Math.asin(cosz * this.sinph0 + y * sinz * this.cosph0 / rh);
x *= sinz * this.cosph0;
y = (cosz - Math.sin(phi) * this.sinph0) * rh;
break;
case this.N_POLE:
y = -y;
phi = HALF_PI - phi;
break;
case this.S_POLE:
phi -= HALF_PI;
break;
}
lam = (y === 0 && (this.mode === this.EQUIT || this.mode === this.OBLIQ)) ? 0 : Math.atan2(x, y);
}
else {
ab = 0;
if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
x /= this.dd;
y *= this.dd;
rho = Math.sqrt(x * x + y * y);
if (rho < EPSLN) {
p.x = this.long0;
p.y = this.lat0;
return p;
}
sCe = 2 * Math.asin(0.5 * rho / this.rq);
cCe = Math.cos(sCe);
x *= (sCe = Math.sin(sCe));
if (this.mode === this.OBLIQ) {
ab = cCe * this.sinb1 + y * sCe * this.cosb1 / rho;
q = this.qp * ab;
y = rho * this.cosb1 * cCe - y * this.sinb1 * sCe;
}
else {
ab = y * sCe / rho;
q = this.qp * ab;
y = rho * cCe;
}
}
else if (this.mode === this.N_POLE || this.mode === this.S_POLE) {
if (this.mode === this.N_POLE) {
y = -y;
}
q = (x * x + y * y);
if (!q) {
p.x = this.long0;
p.y = this.lat0;
return p;
}
ab = 1 - q / this.qp;
if (this.mode === this.S_POLE) {
ab = -ab;
}
}
lam = Math.atan2(x, y);
phi = authlat(Math.asin(ab), this.apa);
}
p.x = adjust_lon(this.long0 + lam);
p.y = phi;
return p;
}
/* determine latitude from authalic latitude */
var P00 = 0.33333333333333333333;
var P01 = 0.17222222222222222222;
var P02 = 0.10257936507936507936;
var P10 = 0.06388888888888888888;
var P11 = 0.06640211640211640211;
var P20 = 0.01641501294219154443;
function authset(es) {
var t;
var APA = [];
APA[0] = es * P00;
t = es * es;
APA[0] += t * P01;
APA[1] = t * P10;
t *= es;
APA[0] += t * P02;
APA[1] += t * P11;
APA[2] = t * P20;
return APA;
}
function authlat(beta, APA) {
var t = beta + beta;
return (beta + APA[0] * Math.sin(t) + APA[1] * Math.sin(t + t) + APA[2] * Math.sin(t + t + t));
}
var names$i = ["Lambert Azimuthal Equal Area", "Lambert_Azimuthal_Equal_Area", "laea"];
var laea = {
init: init$j,
forward: forward$i,
inverse: inverse$i,
names: names$i,
S_POLE: S_POLE,
N_POLE: N_POLE,
EQUIT: EQUIT,
OBLIQ: OBLIQ
};
function asinz(x) {
if (Math.abs(x) > 1) {
x = (x > 1) ? 1 : -1;
}
return Math.asin(x);
}
function init$i() {
if (Math.abs(this.lat1 + this.lat2) < EPSLN) {
return;
}
this.temp = this.b / this.a;
this.es = 1 - Math.pow(this.temp, 2);
this.e3 = Math.sqrt(this.es);
this.sin_po = Math.sin(this.lat1);
this.cos_po = Math.cos(this.lat1);
this.t1 = this.sin_po;
this.con = this.sin_po;
this.ms1 = msfnz(this.e3, this.sin_po, this.cos_po);
this.qs1 = qsfnz(this.e3, this.sin_po);
this.sin_po = Math.sin(this.lat2);
this.cos_po = Math.cos(this.lat2);
this.t2 = this.sin_po;
this.ms2 = msfnz(this.e3, this.sin_po, this.cos_po);
this.qs2 = qsfnz(this.e3, this.sin_po);
this.sin_po = Math.sin(this.lat0);
this.cos_po = Math.cos(this.lat0);
this.t3 = this.sin_po;
this.qs0 = qsfnz(this.e3, this.sin_po);
if (Math.abs(this.lat1 - this.lat2) > EPSLN) {
this.ns0 = (this.ms1 * this.ms1 - this.ms2 * this.ms2) / (this.qs2 - this.qs1);
}
else {
this.ns0 = this.con;
}
this.c = this.ms1 * this.ms1 + this.ns0 * this.qs1;
this.rh = this.a * Math.sqrt(this.c - this.ns0 * this.qs0) / this.ns0;
}
/* Albers Conical Equal Area forward equations--mapping lat,long to x,y
-------------------------------------------------------------------*/
function forward$h(p) {
var lon = p.x;
var lat = p.y;
this.sin_phi = Math.sin(lat);
this.cos_phi = Math.cos(lat);
var qs = qsfnz(this.e3, this.sin_phi);
var rh1 = this.a * Math.sqrt(this.c - this.ns0 * qs) / this.ns0;
var theta = this.ns0 * adjust_lon(lon - this.long0);
var x = rh1 * Math.sin(theta) + this.x0;
var y = this.rh - rh1 * Math.cos(theta) + this.y0;
p.x = x;
p.y = y;
return p;
}
function inverse$h(p) {
var rh1, qs, con, theta, lon, lat;
p.x -= this.x0;
p.y = this.rh - p.y + this.y0;
if (this.ns0 >= 0) {
rh1 = Math.sqrt(p.x * p.x + p.y * p.y);
con = 1;
}
else {
rh1 = -Math.sqrt(p.x * p.x + p.y * p.y);
con = -1;
}
theta = 0;
if (rh1 !== 0) {
theta = Math.atan2(con * p.x, con * p.y);
}
con = rh1 * this.ns0 / this.a;
if (this.sphere) {
lat = Math.asin((this.c - con * con) / (2 * this.ns0));
}
else {
qs = (this.c - con * con) / this.ns0;
lat = this.phi1z(this.e3, qs);
}
lon = adjust_lon(theta / this.ns0 + this.long0);
p.x = lon;
p.y = lat;
return p;
}
/* Function to compute phi1, the latitude for the inverse of the
Albers Conical Equal-Area projection.
-------------------------------------------*/
function phi1z(eccent, qs) {
var sinphi, cosphi, con, com, dphi;
var phi = asinz(0.5 * qs);
if (eccent < EPSLN) {
return phi;
}
var eccnts = eccent * eccent;
for (var i = 1; i <= 25; i++) {
sinphi = Math.sin(phi);
cosphi = Math.cos(phi);
con = eccent * sinphi;
com = 1 - con * con;
dphi = 0.5 * com * com / cosphi * (qs / (1 - eccnts) - sinphi / com + 0.5 / eccent * Math.log((1 - con) / (1 + con)));
phi = phi + dphi;
if (Math.abs(dphi) <= 1e-7) {
return phi;
}
}
return null;
}
var names$h = ["Albers_Conic_Equal_Area", "Albers", "aea"];
var aea = {
init: init$i,
forward: forward$h,
inverse: inverse$h,
names: names$h,
phi1z: phi1z
};
/*
reference:
Wolfram Mathworld "Gnomonic Projection"
http://mathworld.wolfram.com/GnomonicProjection.html
Accessed: 12th November 2009
*/
function init$h() {
/* Place parameters in static storage for common use
-------------------------------------------------*/
this.sin_p14 = Math.sin(this.lat0);
this.cos_p14 = Math.cos(this.lat0);
// Approximation for projecting points to the horizon (infinity)
this.infinity_dist = 1000 * this.a;
this.rc = 1;
}
/* Gnomonic forward equations--mapping lat,long to x,y
---------------------------------------------------*/
function forward$g(p) {
var sinphi, cosphi; /* sin and cos value */
var dlon; /* delta longitude value */
var coslon; /* cos of longitude */
var ksp; /* scale factor */
var g;
var x, y;
var lon = p.x;
var lat = p.y;
/* Forward equations
-----------------*/
dlon = adjust_lon(lon - this.long0);
sinphi = Math.sin(lat);
cosphi = Math.cos(lat);
coslon = Math.cos(dlon);
g = this.sin_p14 * sinphi + this.cos_p14 * cosphi * coslon;
ksp = 1;
if ((g > 0) || (Math.abs(g) <= EPSLN)) {
x = this.x0 + this.a * ksp * cosphi * Math.sin(dlon) / g;
y = this.y0 + this.a * ksp * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon) / g;
}
else {
// Point is in the opposing hemisphere and is unprojectable
// We still need to return a reasonable point, so we project
// to infinity, on a bearing
// equivalent to the northern hemisphere equivalent
// This is a reasonable approximation for short shapes and lines that
// straddle the horizon.
x = this.x0 + this.infinity_dist * cosphi * Math.sin(dlon);
y = this.y0 + this.infinity_dist * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon);
}
p.x = x;
p.y = y;
return p;
}
function inverse$g(p) {
var rh; /* Rho */
var sinc, cosc;
var c;
var lon, lat;
/* Inverse equations
-----------------*/
p.x = (p.x - this.x0) / this.a;
p.y = (p.y - this.y0) / this.a;
p.x /= this.k0;
p.y /= this.k0;
if ((rh = Math.sqrt(p.x * p.x + p.y * p.y))) {
c = Math.atan2(rh, this.rc);
sinc = Math.sin(c);
cosc = Math.cos(c);
lat = asinz(cosc * this.sin_p14 + (p.y * sinc * this.cos_p14) / rh);
lon = Math.atan2(p.x * sinc, rh * this.cos_p14 * cosc - p.y * this.sin_p14 * sinc);
lon = adjust_lon(this.long0 + lon);
}
else {
lat = this.phic0;
lon = 0;
}
p.x = lon;
p.y = lat;
return p;
}
var names$g = ["gnom"];
var gnom = {
init: init$h,
forward: forward$g,
inverse: inverse$g,
names: names$g
};
function iqsfnz(eccent, q) {
var temp = 1 - (1 - eccent * eccent) / (2 * eccent) * Math.log((1 - eccent) / (1 + eccent));
if (Math.abs(Math.abs(q) - temp) < 1.0E-6) {
if (q < 0) {
return (-1 * HALF_PI);
}
else {
return HALF_PI;
}
}
//var phi = 0.5* q/(1-eccent*eccent);
var phi = Math.asin(0.5 * q);
var dphi;
var sin_phi;
var cos_phi;
var con;
for (var i = 0; i < 30; i++) {
sin_phi = Math.sin(phi);
cos_phi = Math.cos(phi);
con = eccent * sin_phi;
dphi = Math.pow(1 - con * con, 2) / (2 * cos_phi) * (q / (1 - eccent * eccent) - sin_phi / (1 - con * con) + 0.5 / eccent * Math.log((1 - con) / (1 + con)));
phi += dphi;
if (Math.abs(dphi) <= 0.0000000001) {
return phi;
}
}
//console.log("IQSFN-CONV:Latitude failed to converge after 30 iterations");
return NaN;
}
/*
reference:
"Cartographic Projection Procedures for the UNIX Environment-
A User's Manual" by Gerald I. Evenden,
USGS Open File Report 90-284and Release 4 Interim Reports (2003)
*/
function init$g() {
//no-op
if (!this.sphere) {
this.k0 = msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts));
}
}
/* Cylindrical Equal Area forward equations--mapping lat,long to x,y
------------------------------------------------------------*/
function forward$f(p) {
var lon = p.x;
var lat = p.y;
var x, y;
/* Forward equations
-----------------*/
var dlon = adjust_lon(lon - this.long0);
if (this.sphere) {
x = this.x0 + this.a * dlon * Math.cos(this.lat_ts);
y = this.y0 + this.a * Math.sin(lat) / Math.cos(this.lat_ts);
}
else {
var qs = qsfnz(this.e, Math.sin(lat));
x = this.x0 + this.a * this.k0 * dlon;
y = this.y0 + this.a * qs * 0.5 / this.k0;
}
p.x = x;
p.y = y;
return p;
}
/* Cylindrical Equal Area inverse equations--mapping x,y to lat/long
------------------------------------------------------------*/
function inverse$f(p) {
p.x -= this.x0;
p.y -= this.y0;
var lon, lat;
if (this.sphere) {
lon = adjust_lon(this.long0 + (p.x / this.a) / Math.cos(this.lat_ts));
lat = Math.asin((p.y / this.a) * Math.cos(this.lat_ts));
}
else {
lat = iqsfnz(this.e, 2 * p.y * this.k0 / this.a);
lon = adjust_lon(this.long0 + p.x / (this.a * this.k0));
}
p.x = lon;
p.y = lat;
return p;
}
var names$f = ["cea"];
var cea = {
init: init$g,
forward: forward$f,
inverse: inverse$f,
names: names$f
};
function init$f() {
this.x0 = this.x0 || 0;
this.y0 = this.y0 || 0;
this.lat0 = this.lat0 || 0;
this.long0 = this.long0 || 0;
this.lat_ts = this.lat_ts || 0;
this.title = this.title || "Equidistant Cylindrical (Plate Carre)";
this.rc = Math.cos(this.lat_ts);
}
// forward equations--mapping lat,long to x,y
// -----------------------------------------------------------------
function forward$e(p) {
var lon = p.x;
var lat = p.y;
var dlon = adjust_lon(lon - this.long0);
var dlat = adjust_lat(lat - this.lat0);
p.x = this.x0 + (this.a * dlon * this.rc);
p.y = this.y0 + (this.a * dlat);
return p;
}
// inverse equations--mapping x,y to lat/long
// -----------------------------------------------------------------
function inverse$e(p) {
var x = p.x;
var y = p.y;
p.x = adjust_lon(this.long0 + ((x - this.x0) / (this.a * this.rc)));
p.y = adjust_lat(this.lat0 + ((y - this.y0) / (this.a)));
return p;
}
var names$e = ["Equirectangular", "Equidistant_Cylindrical", "eqc"];
var eqc = {
init: init$f,
forward: forward$e,
inverse: inverse$e,
names: names$e
};
var MAX_ITER$1 = 20;
function init$e() {
/* Place parameters in static storage for common use
-------------------------------------------------*/
this.temp = this.b / this.a;
this.es = 1 - Math.pow(this.temp, 2); // devait etre dans tmerc.js mais n y est pas donc je commente sinon retour de valeurs nulles
this.e = Math.sqrt(this.es);
this.e0 = e0fn(this.es);
this.e1 = e1fn(this.es);
this.e2 = e2fn(this.es);
this.e3 = e3fn(this.es);
this.ml0 = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0); //si que des zeros le calcul ne se fait pas
}
/* Polyconic forward equations--mapping lat,long to x,y
---------------------------------------------------*/
function forward$d(p) {
var lon = p.x;
var lat = p.y;
var x, y, el;
var dlon = adjust_lon(lon - this.long0);
el = dlon * Math.sin(lat);
if (this.sphere) {
if (Math.abs(lat) <= EPSLN) {
x = this.a * dlon;
y = -1 * this.a * this.lat0;
}
else {
x = this.a * Math.sin(el) / Math.tan(lat);
y = this.a * (adjust_lat(lat - this.lat0) + (1 - Math.cos(el)) / Math.tan(lat));
}
}
else {
if (Math.abs(lat) <= EPSLN) {
x = this.a * dlon;
y = -1 * this.ml0;
}
else {
var nl = gN(this.a, this.e, Math.sin(lat)) / Math.tan(lat);
x = nl * Math.sin(el);
y = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, lat) - this.ml0 + nl * (1 - Math.cos(el));
}
}
p.x = x + this.x0;
p.y = y + this.y0;
return p;
}
/* Inverse equations
-----------------*/
function inverse$d(p) {
var lon, lat, x, y, i;
var al, bl;
var phi, dphi;
x = p.x - this.x0;
y = p.y - this.y0;
if (this.sphere) {
if (Math.abs(y + this.a * this.lat0) <= EPSLN) {
lon = adjust_lon(x / this.a + this.long0);
lat = 0;
}
else {
al = this.lat0 + y / this.a;
bl = x * x / this.a / this.a + al * al;
phi = al;
var tanphi;
for (i = MAX_ITER$1; i; --i) {
tanphi = Math.tan(phi);
dphi = -1 * (al * (phi * tanphi + 1) - phi - 0.5 * (phi * phi + bl) * tanphi) / ((phi - al) / tanphi - 1);
phi += dphi;
if (Math.abs(dphi) <= EPSLN) {
lat = phi;
break;
}
}
lon = adjust_lon(this.long0 + (Math.asin(x * Math.tan(phi) / this.a)) / Math.sin(lat));
}
}
else {
if (Math.abs(y + this.ml0) <= EPSLN) {
lat = 0;
lon = adjust_lon(this.long0 + x / this.a);
}
else {
al = (this.ml0 + y) / this.a;
bl = x * x / this.a / this.a + al * al;
phi = al;
var cl, mln, mlnp, ma;
var con;
for (i = MAX_ITER$1; i; --i) {
con = this.e * Math.sin(phi);
cl = Math.sqrt(1 - con * con) * Math.tan(phi);
mln = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, phi);
mlnp = this.e0 - 2 * this.e1 * Math.cos(2 * phi) + 4 * this.e2 * Math.cos(4 * phi) - 6 * this.e3 * Math.cos(6 * phi);
ma = mln / this.a;
dphi = (al * (cl * ma + 1) - ma - 0.5 * cl * (ma * ma + bl)) / (this.es * Math.sin(2 * phi) * (ma * ma + bl - 2 * al * ma) / (4 * cl) + (al - ma) * (cl * mlnp - 2 / Math.sin(2 * phi)) - mlnp);
phi -= dphi;
if (Math.abs(dphi) <= EPSLN) {
lat = phi;
break;
}
}
//lat=phi4z(this.e,this.e0,this.e1,this.e2,this.e3,al,bl,0,0);
cl = Math.sqrt(1 - this.es * Math.pow(Math.sin(lat), 2)) * Math.tan(lat);
lon = adjust_lon(this.long0 + Math.asin(x * cl / this.a) / Math.sin(lat));
}
}
p.x = lon;
p.y = lat;
return p;
}
var names$d = ["Polyconic", "poly"];
var poly = {
init: init$e,
forward: forward$d,
inverse: inverse$d,
names: names$d
};
function init$d() {
this.A = [];
this.A[1] = 0.6399175073;
this.A[2] = -0.1358797613;
this.A[3] = 0.063294409;
this.A[4] = -0.02526853;
this.A[5] = 0.0117879;
this.A[6] = -0.0055161;
this.A[7] = 0.0026906;
this.A[8] = -0.001333;
this.A[9] = 0.00067;
this.A[10] = -0.00034;
this.B_re = [];
this.B_im = [];
this.B_re[1] = 0.7557853228;
this.B_im[1] = 0;
this.B_re[2] = 0.249204646;
this.B_im[2] = 0.003371507;
this.B_re[3] = -0.001541739;
this.B_im[3] = 0.041058560;
this.B_re[4] = -0.10162907;
this.B_im[4] = 0.01727609;
this.B_re[5] = -0.26623489;
this.B_im[5] = -0.36249218;
this.B_re[6] = -0.6870983;
this.B_im[6] = -1.1651967;
this.C_re = [];
this.C_im = [];
this.C_re[1] = 1.3231270439;
this.C_im[1] = 0;
this.C_re[2] = -0.577245789;
this.C_im[2] = -0.007809598;
this.C_re[3] = 0.508307513;
this.C_im[3] = -0.112208952;
this.C_re[4] = -0.15094762;
this.C_im[4] = 0.18200602;
this.C_re[5] = 1.01418179;
this.C_im[5] = 1.64497696;
this.C_re[6] = 1.9660549;
this.C_im[6] = 2.5127645;
this.D = [];
this.D[1] = 1.5627014243;
this.D[2] = 0.5185406398;
this.D[3] = -0.03333098;
this.D[4] = -0.1052906;
this.D[5] = -0.0368594;
this.D[6] = 0.007317;
this.D[7] = 0.01220;
this.D[8] = 0.00394;
this.D[9] = -0.0013;
}
/**
New Zealand Map Grid Forward - long/lat to x/y
long/lat in radians
*/
function forward$c(p) {
var n;
var lon = p.x;
var lat = p.y;
var delta_lat = lat - this.lat0;
var delta_lon = lon - this.long0;
// 1. Calculate d_phi and d_psi ... // and d_lambda
// For this algorithm, delta_latitude is in seconds of arc x 10-5, so we need to scale to those units. Longitude is radians.
var d_phi = delta_lat / SEC_TO_RAD * 1E-5;
var d_lambda = delta_lon;
var d_phi_n = 1; // d_phi^0
var d_psi = 0;
for (n = 1; n <= 10; n++) {
d_phi_n = d_phi_n * d_phi;
d_psi = d_psi + this.A[n] * d_phi_n;
}
// 2. Calculate theta
var th_re = d_psi;
var th_im = d_lambda;
// 3. Calculate z
var th_n_re = 1;
var th_n_im = 0; // theta^0
var th_n_re1;
var th_n_im1;
var z_re = 0;
var z_im = 0;
for (n = 1; n <= 6; n++) {
th_n_re1 = th_n_re * th_re - th_n_im * th_im;
th_n_im1 = th_n_im * th_re + th_n_re * th_im;
th_n_re = th_n_re1;
th_n_im = th_n_im1;
z_re = z_re + this.B_re[n] * th_n_re - this.B_im[n] * th_n_im;
z_im = z_im + this.B_im[n] * th_n_re + this.B_re[n] * th_n_im;
}
// 4. Calculate easting and northing
p.x = (z_im * this.a) + this.x0;
p.y = (z_re * this.a) + this.y0;
return p;
}
/**
New Zealand Map Grid Inverse - x/y to long/lat
*/
function inverse$c(p) {
var n;
var x = p.x;
var y = p.y;
var delta_x = x - this.x0;
var delta_y = y - this.y0;
// 1. Calculate z
var z_re = delta_y / this.a;
var z_im = delta_x / this.a;
// 2a. Calculate theta - first approximation gives km accuracy
var z_n_re = 1;
var z_n_im = 0; // z^0
var z_n_re1;
var z_n_im1;
var th_re = 0;
var th_im = 0;
for (n = 1; n <= 6; n++) {
z_n_re1 = z_n_re * z_re - z_n_im * z_im;
z_n_im1 = z_n_im * z_re + z_n_re * z_im;
z_n_re = z_n_re1;
z_n_im = z_n_im1;
th_re = th_re + this.C_re[n] * z_n_re - this.C_im[n] * z_n_im;
th_im = th_im + this.C_im[n] * z_n_re + this.C_re[n] * z_n_im;
}
// 2b. Iterate to refine the accuracy of the calculation
// 0 iterations gives km accuracy
// 1 iteration gives m accuracy -- good enough for most mapping applications
// 2 iterations bives mm accuracy
for (var i = 0; i < this.iterations; i++) {
var th_n_re = th_re;
var th_n_im = th_im;
var th_n_re1;
var th_n_im1;
var num_re = z_re;
var num_im = z_im;
for (n = 2; n <= 6; n++) {
th_n_re1 = th_n_re * th_re - th_n_im * th_im;
th_n_im1 = th_n_im * th_re + th_n_re * th_im;
th_n_re = th_n_re1;
th_n_im = th_n_im1;
num_re = num_re + (n - 1) * (this.B_re[n] * th_n_re - this.B_im[n] * th_n_im);
num_im = num_im + (n - 1) * (this.B_im[n] * th_n_re + this.B_re[n] * th_n_im);
}
th_n_re = 1;
th_n_im = 0;
var den_re = this.B_re[1];
var den_im = this.B_im[1];
for (n = 2; n <= 6; n++) {
th_n_re1 = th_n_re * th_re - th_n_im * th_im;
th_n_im1 = th_n_im * th_re + th_n_re * th_im;
th_n_re = th_n_re1;
th_n_im = th_n_im1;
den_re = den_re + n * (this.B_re[n] * th_n_re - this.B_im[n] * th_n_im);
den_im = den_im + n * (this.B_im[n] * th_n_re + this.B_re[n] * th_n_im);
}
// Complex division
var den2 = den_re * den_re + den_im * den_im;
th_re = (num_re * den_re + num_im * den_im) / den2;
th_im = (num_im * den_re - num_re * den_im) / den2;
}
// 3. Calculate d_phi ... // and d_lambda
var d_psi = th_re;
var d_lambda = th_im;
var d_psi_n = 1; // d_psi^0
var d_phi = 0;
for (n = 1; n <= 9; n++) {
d_psi_n = d_psi_n * d_psi;
d_phi = d_phi + this.D[n] * d_psi_n;
}
// 4. Calculate latitude and longitude
// d_phi is calcuated in second of arc * 10^-5, so we need to scale back to radians. d_lambda is in radians.
var lat = this.lat0 + (d_phi * SEC_TO_RAD * 1E5);
var lon = this.long0 + d_lambda;
p.x = lon;
p.y = lat;
return p;
}
var names$c = ["New_Zealand_Map_Grid", "nzmg"];
var nzmg = {
init: init$d,
forward: forward$c,
inverse: inverse$c,
names: names$c
};
/*
reference
"New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
*/
/* Initialize the Miller Cylindrical projection
-------------------------------------------*/
function init$c() {
//no-op
}
/* Miller Cylindrical forward equations--mapping lat,long to x,y
------------------------------------------------------------*/
function forward$b(p) {
var lon = p.x;
var lat = p.y;
/* Forward equations
-----------------*/
var dlon = adjust_lon(lon - this.long0);
var x = this.x0 + this.a * dlon;
var y = this.y0 + this.a * Math.log(Math.tan((Math.PI / 4) + (lat / 2.5))) * 1.25;
p.x = x;
p.y = y;
return p;
}
/* Miller Cylindrical inverse equations--mapping x,y to lat/long
------------------------------------------------------------*/
function inverse$b(p) {
p.x -= this.x0;
p.y -= this.y0;
var lon = adjust_lon(this.long0 + p.x / this.a);
var lat = 2.5 * (Math.atan(Math.exp(0.8 * p.y / this.a)) - Math.PI / 4);
p.x = lon;
p.y = lat;
return p;
}
var names$b = ["Miller_Cylindrical", "mill"];
var mill = {
init: init$c,
forward: forward$b,
inverse: inverse$b,
names: names$b
};
var MAX_ITER = 20;
function init$b() {
/* Place parameters in static storage for common use
-------------------------------------------------*/
if (!this.sphere) {
this.en = pj_enfn(this.es);
}
else {
this.n = 1;
this.m = 0;
this.es = 0;
this.C_y = Math.sqrt((this.m + 1) / this.n);
this.C_x = this.C_y / (this.m + 1);
}
}
/* Sinusoidal forward equations--mapping lat,long to x,y
-----------------------------------------------------*/
function forward$a(p) {
var x, y;
var lon = p.x;
var lat = p.y;
/* Forward equations
-----------------*/
lon = adjust_lon(lon - this.long0);
if (this.sphere) {
if (!this.m) {
lat = this.n !== 1 ? Math.asin(this.n * Math.sin(lat)) : lat;
}
else {
var k = this.n * Math.sin(lat);
for (var i = MAX_ITER; i; --i) {
var V = (this.m * lat + Math.sin(lat) - k) / (this.m + Math.cos(lat));
lat -= V;
if (Math.abs(V) < EPSLN) {
break;
}
}
}
x = this.a * this.C_x * lon * (this.m + Math.cos(lat));
y = this.a * this.C_y * lat;
}
else {
var s = Math.sin(lat);
var c = Math.cos(lat);
y = this.a * pj_mlfn(lat, s, c, this.en);
x = this.a * lon * c / Math.sqrt(1 - this.es * s * s);
}
p.x = x;
p.y = y;
return p;
}
function inverse$a(p) {
var lat, temp, lon, s;
p.x -= this.x0;
lon = p.x / this.a;
p.y -= this.y0;
lat = p.y / this.a;
if (this.sphere) {
lat /= this.C_y;
lon = lon / (this.C_x * (this.m + Math.cos(lat)));
if (this.m) {
lat = asinz((this.m * lat + Math.sin(lat)) / this.n);
}
else if (this.n !== 1) {
lat = asinz(Math.sin(lat) / this.n);
}
lon = adjust_lon(lon + this.long0);
lat = adjust_lat(lat);
}
else {
lat = pj_inv_mlfn(p.y / this.a, this.es, this.en);
s = Math.abs(lat);
if (s < HALF_PI) {
s = Math.sin(lat);
temp = this.long0 + p.x * Math.sqrt(1 - this.es * s * s) / (this.a * Math.cos(lat));
//temp = this.long0 + p.x / (this.a * Math.cos(lat));
lon = adjust_lon(temp);
}
else if ((s - EPSLN) < HALF_PI) {
lon = this.long0;
}
}
p.x = lon;
p.y = lat;
return p;
}
var names$a = ["Sinusoidal", "sinu"];
var sinu = {
init: init$b,
forward: forward$a,
inverse: inverse$a,
names: names$a
};
function init$a() {}
/* Mollweide forward equations--mapping lat,long to x,y
----------------------------------------------------*/
function forward$9(p) {
/* Forward equations
-----------------*/
var lon = p.x;
var lat = p.y;
var delta_lon = adjust_lon(lon - this.long0);
var theta = lat;
var con = Math.PI * Math.sin(lat);
/* Iterate using the Newton-Raphson method to find theta
-----------------------------------------------------*/
while (true) {
var delta_theta = -(theta + Math.sin(theta) - con) / (1 + Math.cos(theta));
theta += delta_theta;
if (Math.abs(delta_theta) < EPSLN) {
break;
}
}
theta /= 2;
/* If the latitude is 90 deg, force the x coordinate to be "0 + false easting"
this is done here because of precision problems with "cos(theta)"
--------------------------------------------------------------------------*/
if (Math.PI / 2 - Math.abs(lat) < EPSLN) {
delta_lon = 0;
}
var x = 0.900316316158 * this.a * delta_lon * Math.cos(theta) + this.x0;
var y = 1.4142135623731 * this.a * Math.sin(theta) + this.y0;
p.x = x;
p.y = y;
return p;
}
function inverse$9(p) {
var theta;
var arg;
/* Inverse equations
-----------------*/
p.x -= this.x0;
p.y -= this.y0;
arg = p.y / (1.4142135623731 * this.a);
/* Because of division by zero problems, 'arg' can not be 1. Therefore
a number very close to one is used instead.
-------------------------------------------------------------------*/
if (Math.abs(arg) > 0.999999999999) {
arg = 0.999999999999;
}
theta = Math.asin(arg);
var lon = adjust_lon(this.long0 + (p.x / (0.900316316158 * this.a * Math.cos(theta))));
if (lon < (-Math.PI)) {
lon = -Math.PI;
}
if (lon > Math.PI) {
lon = Math.PI;
}
arg = (2 * theta + Math.sin(2 * theta)) / Math.PI;
if (Math.abs(arg) > 1) {
arg = 1;
}
var lat = Math.asin(arg);
p.x = lon;
p.y = lat;
return p;
}
var names$9 = ["Mollweide", "moll"];
var moll = {
init: init$a,
forward: forward$9,
inverse: inverse$9,
names: names$9
};
function init$9() {
/* Place parameters in static storage for common use
-------------------------------------------------*/
// Standard Parallels cannot be equal and on opposite sides of the equator
if (Math.abs(this.lat1 + this.lat2) < EPSLN) {
return;
}
this.lat2 = this.lat2 || this.lat1;
this.temp = this.b / this.a;
this.es = 1 - Math.pow(this.temp, 2);
this.e = Math.sqrt(this.es);
this.e0 = e0fn(this.es);
this.e1 = e1fn(this.es);
this.e2 = e2fn(this.es);
this.e3 = e3fn(this.es);
this.sinphi = Math.sin(this.lat1);
this.cosphi = Math.cos(this.lat1);
this.ms1 = msfnz(this.e, this.sinphi, this.cosphi);
this.ml1 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat1);
if (Math.abs(this.lat1 - this.lat2) < EPSLN) {
this.ns = this.sinphi;
}
else {
this.sinphi = Math.sin(this.lat2);
this.cosphi = Math.cos(this.lat2);
this.ms2 = msfnz(this.e, this.sinphi, this.cosphi);
this.ml2 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat2);
this.ns = (this.ms1 - this.ms2) / (this.ml2 - this.ml1);
}
this.g = this.ml1 + this.ms1 / this.ns;
this.ml0 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0);
this.rh = this.a * (this.g - this.ml0);
}
/* Equidistant Conic forward equations--mapping lat,long to x,y
-----------------------------------------------------------*/
function forward$8(p) {
var lon = p.x;
var lat = p.y;
var rh1;
/* Forward equations
-----------------*/
if (this.sphere) {
rh1 = this.a * (this.g - lat);
}
else {
var ml = mlfn(this.e0, this.e1, this.e2, this.e3, lat);
rh1 = this.a * (this.g - ml);
}
var theta = this.ns * adjust_lon(lon - this.long0);
var x = this.x0 + rh1 * Math.sin(theta);
var y = this.y0 + this.rh - rh1 * Math.cos(theta);
p.x = x;
p.y = y;
return p;
}
/* Inverse equations
-----------------*/
function inverse$8(p) {
p.x -= this.x0;
p.y = this.rh - p.y + this.y0;
var con, rh1, lat, lon;
if (this.ns >= 0) {
rh1 = Math.sqrt(p.x * p.x + p.y * p.y);
con = 1;
}
else {
rh1 = -Math.sqrt(p.x * p.x + p.y * p.y);
con = -1;
}
var theta = 0;
if (rh1 !== 0) {
theta = Math.atan2(con * p.x, con * p.y);
}
if (this.sphere) {
lon = adjust_lon(this.long0 + theta / this.ns);
lat = adjust_lat(this.g - rh1 / this.a);
p.x = lon;
p.y = lat;
return p;
}
else {
var ml = this.g - rh1 / this.a;
lat = imlfn(ml, this.e0, this.e1, this.e2, this.e3);
lon = adjust_lon(this.long0 + theta / this.ns);
p.x = lon;
p.y = lat;
return p;
}
}
var names$8 = ["Equidistant_Conic", "eqdc"];
var eqdc = {
init: init$9,
forward: forward$8,
inverse: inverse$8,
names: names$8
};
/* Initialize the Van Der Grinten projection
----------------------------------------*/
function init$8() {
//this.R = 6370997; //Radius of earth
this.R = this.a;
}
function forward$7(p) {
var lon = p.x;
var lat = p.y;
/* Forward equations
-----------------*/
var dlon = adjust_lon(lon - this.long0);
var x, y;
if (Math.abs(lat) <= EPSLN) {
x = this.x0 + this.R * dlon;
y = this.y0;
}
var theta = asinz(2 * Math.abs(lat / Math.PI));
if ((Math.abs(dlon) <= EPSLN) || (Math.abs(Math.abs(lat) - HALF_PI) <= EPSLN)) {
x = this.x0;
if (lat >= 0) {
y = this.y0 + Math.PI * this.R * Math.tan(0.5 * theta);
}
else {
y = this.y0 + Math.PI * this.R * -Math.tan(0.5 * theta);
}
// return(OK);
}
var al = 0.5 * Math.abs((Math.PI / dlon) - (dlon / Math.PI));
var asq = al * al;
var sinth = Math.sin(theta);
var costh = Math.cos(theta);
var g = costh / (sinth + costh - 1);
var gsq = g * g;
var m = g * (2 / sinth - 1);
var msq = m * m;
var con = Math.PI * this.R * (al * (g - msq) + Math.sqrt(asq * (g - msq) * (g - msq) - (msq + asq) * (gsq - msq))) / (msq + asq);
if (dlon < 0) {
con = -con;
}
x = this.x0 + con;
//con = Math.abs(con / (Math.PI * this.R));
var q = asq + g;
con = Math.PI * this.R * (m * q - al * Math.sqrt((msq + asq) * (asq + 1) - q * q)) / (msq + asq);
if (lat >= 0) {
//y = this.y0 + Math.PI * this.R * Math.sqrt(1 - con * con - 2 * al * con);
y = this.y0 + con;
}
else {
//y = this.y0 - Math.PI * this.R * Math.sqrt(1 - con * con - 2 * al * con);
y = this.y0 - con;
}
p.x = x;
p.y = y;
return p;
}
/* Van Der Grinten inverse equations--mapping x,y to lat/long
---------------------------------------------------------*/
function inverse$7(p) {
var lon, lat;
var xx, yy, xys, c1, c2, c3;
var a1;
var m1;
var con;
var th1;
var d;
/* inverse equations
-----------------*/
p.x -= this.x0;
p.y -= this.y0;
con = Math.PI * this.R;
xx = p.x / con;
yy = p.y / con;
xys = xx * xx + yy * yy;
c1 = -Math.abs(yy) * (1 + xys);
c2 = c1 - 2 * yy * yy + xx * xx;
c3 = -2 * c1 + 1 + 2 * yy * yy + xys * xys;
d = yy * yy / c3 + (2 * c2 * c2 * c2 / c3 / c3 / c3 - 9 * c1 * c2 / c3 / c3) / 27;
a1 = (c1 - c2 * c2 / 3 / c3) / c3;
m1 = 2 * Math.sqrt(-a1 / 3);
con = ((3 * d) / a1) / m1;
if (Math.abs(con) > 1) {
if (con >= 0) {
con = 1;
}
else {
con = -1;
}
}
th1 = Math.acos(con) / 3;
if (p.y >= 0) {
lat = (-m1 * Math.cos(th1 + Math.PI / 3) - c2 / 3 / c3) * Math.PI;
}
else {
lat = -(-m1 * Math.cos(th1 + Math.PI / 3) - c2 / 3 / c3) * Math.PI;
}
if (Math.abs(xx) < EPSLN) {
lon = this.long0;
}
else {
lon = adjust_lon(this.long0 + Math.PI * (xys - 1 + Math.sqrt(1 + 2 * (xx * xx - yy * yy) + xys * xys)) / 2 / xx);
}
p.x = lon;
p.y = lat;
return p;
}
var names$7 = ["Van_der_Grinten_I", "VanDerGrinten", "vandg"];
var vandg = {
init: init$8,
forward: forward$7,
inverse: inverse$7,
names: names$7
};
function init$7() {
this.sin_p12 = Math.sin(this.lat0);
this.cos_p12 = Math.cos(this.lat0);
}
function forward$6(p) {
var lon = p.x;
var lat = p.y;
var sinphi = Math.sin(p.y);
var cosphi = Math.cos(p.y);
var dlon = adjust_lon(lon - this.long0);
var e0, e1, e2, e3, Mlp, Ml, tanphi, Nl1, Nl, psi, Az, G, H, GH, Hs, c, kp, cos_c, s, s2, s3, s4, s5;
if (this.sphere) {
if (Math.abs(this.sin_p12 - 1) <= EPSLN) {
//North Pole case
p.x = this.x0 + this.a * (HALF_PI - lat) * Math.sin(dlon);
p.y = this.y0 - this.a * (HALF_PI - lat) * Math.cos(dlon);
return p;
}
else if (Math.abs(this.sin_p12 + 1) <= EPSLN) {
//South Pole case
p.x = this.x0 + this.a * (HALF_PI + lat) * Math.sin(dlon);
p.y = this.y0 + this.a * (HALF_PI + lat) * Math.cos(dlon);
return p;
}
else {
//default case
cos_c = this.sin_p12 * sinphi + this.cos_p12 * cosphi * Math.cos(dlon);
c = Math.acos(cos_c);
kp = c ? c / Math.sin(c) : 1;
p.x = this.x0 + this.a * kp * cosphi * Math.sin(dlon);
p.y = this.y0 + this.a * kp * (this.cos_p12 * sinphi - this.sin_p12 * cosphi * Math.cos(dlon));
return p;
}
}
else {
e0 = e0fn(this.es);
e1 = e1fn(this.es);
e2 = e2fn(this.es);
e3 = e3fn(this.es);
if (Math.abs(this.sin_p12 - 1) <= EPSLN) {
//North Pole case
Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
Ml = this.a * mlfn(e0, e1, e2, e3, lat);
p.x = this.x0 + (Mlp - Ml) * Math.sin(dlon);
p.y = this.y0 - (Mlp - Ml) * Math.cos(dlon);
return p;
}
else if (Math.abs(this.sin_p12 + 1) <= EPSLN) {
//South Pole case
Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
Ml = this.a * mlfn(e0, e1, e2, e3, lat);
p.x = this.x0 + (Mlp + Ml) * Math.sin(dlon);
p.y = this.y0 + (Mlp + Ml) * Math.cos(dlon);
return p;
}
else {
//Default case
tanphi = sinphi / cosphi;
Nl1 = gN(this.a, this.e, this.sin_p12);
Nl = gN(this.a, this.e, sinphi);
psi = Math.atan((1 - this.es) * tanphi + this.es * Nl1 * this.sin_p12 / (Nl * cosphi));
Az = Math.atan2(Math.sin(dlon), this.cos_p12 * Math.tan(psi) - this.sin_p12 * Math.cos(dlon));
if (Az === 0) {
s = Math.asin(this.cos_p12 * Math.sin(psi) - this.sin_p12 * Math.cos(psi));
}
else if (Math.abs(Math.abs(Az) - Math.PI) <= EPSLN) {
s = -Math.asin(this.cos_p12 * Math.sin(psi) - this.sin_p12 * Math.cos(psi));
}
else {
s = Math.asin(Math.sin(dlon) * Math.cos(psi) / Math.sin(Az));
}
G = this.e * this.sin_p12 / Math.sqrt(1 - this.es);
H = this.e * this.cos_p12 * Math.cos(Az) / Math.sqrt(1 - this.es);
GH = G * H;
Hs = H * H;
s2 = s * s;
s3 = s2 * s;
s4 = s3 * s;
s5 = s4 * s;
c = Nl1 * s * (1 - s2 * Hs * (1 - Hs) / 6 + s3 / 8 * GH * (1 - 2 * Hs) + s4 / 120 * (Hs * (4 - 7 * Hs) - 3 * G * G * (1 - 7 * Hs)) - s5 / 48 * GH);
p.x = this.x0 + c * Math.sin(Az);
p.y = this.y0 + c * Math.cos(Az);
return p;
}
}
}
function inverse$6(p) {
p.x -= this.x0;
p.y -= this.y0;
var rh, z, sinz, cosz, lon, lat, con, e0, e1, e2, e3, Mlp, M, N1, psi, Az, cosAz, tmp, A, B, D, Ee, F, sinpsi;
if (this.sphere) {
rh = Math.sqrt(p.x * p.x + p.y * p.y);
if (rh > (2 * HALF_PI * this.a)) {
return;
}
z = rh / this.a;
sinz = Math.sin(z);
cosz = Math.cos(z);
lon = this.long0;
if (Math.abs(rh) <= EPSLN) {
lat = this.lat0;
}
else {
lat = asinz(cosz * this.sin_p12 + (p.y * sinz * this.cos_p12) / rh);
con = Math.abs(this.lat0) - HALF_PI;
if (Math.abs(con) <= EPSLN) {
if (this.lat0 >= 0) {
lon = adjust_lon(this.long0 + Math.atan2(p.x, - p.y));
}
else {
lon = adjust_lon(this.long0 - Math.atan2(-p.x, p.y));
}
}
else {
/*con = cosz - this.sin_p12 * Math.sin(lat);
if ((Math.abs(con) < EPSLN) && (Math.abs(p.x) < EPSLN)) {
//no-op, just keep the lon value as is
} else {
var temp = Math.atan2((p.x * sinz * this.cos_p12), (con * rh));
lon = adjust_lon(this.long0 + Math.atan2((p.x * sinz * this.cos_p12), (con * rh)));
}*/
lon = adjust_lon(this.long0 + Math.atan2(p.x * sinz, rh * this.cos_p12 * cosz - p.y * this.sin_p12 * sinz));
}
}
p.x = lon;
p.y = lat;
return p;
}
else {
e0 = e0fn(this.es);
e1 = e1fn(this.es);
e2 = e2fn(this.es);
e3 = e3fn(this.es);
if (Math.abs(this.sin_p12 - 1) <= EPSLN) {
//North pole case
Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
rh = Math.sqrt(p.x * p.x + p.y * p.y);
M = Mlp - rh;
lat = imlfn(M / this.a, e0, e1, e2, e3);
lon = adjust_lon(this.long0 + Math.atan2(p.x, - 1 * p.y));
p.x = lon;
p.y = lat;
return p;
}
else if (Math.abs(this.sin_p12 + 1) <= EPSLN) {
//South pole case
Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
rh = Math.sqrt(p.x * p.x + p.y * p.y);
M = rh - Mlp;
lat = imlfn(M / this.a, e0, e1, e2, e3);
lon = adjust_lon(this.long0 + Math.atan2(p.x, p.y));
p.x = lon;
p.y = lat;
return p;
}
else {
//default case
rh = Math.sqrt(p.x * p.x + p.y * p.y);
Az = Math.atan2(p.x, p.y);
N1 = gN(this.a, this.e, this.sin_p12);
cosAz = Math.cos(Az);
tmp = this.e * this.cos_p12 * cosAz;
A = -tmp * tmp / (1 - this.es);
B = 3 * this.es * (1 - A) * this.sin_p12 * this.cos_p12 * cosAz / (1 - this.es);
D = rh / N1;
Ee = D - A * (1 + A) * Math.pow(D, 3) / 6 - B * (1 + 3 * A) * Math.pow(D, 4) / 24;
F = 1 - A * Ee * Ee / 2 - D * Ee * Ee * Ee / 6;
psi = Math.asin(this.sin_p12 * Math.cos(Ee) + this.cos_p12 * Math.sin(Ee) * cosAz);
lon = adjust_lon(this.long0 + Math.asin(Math.sin(Az) * Math.sin(Ee) / Math.cos(psi)));
sinpsi = Math.sin(psi);
lat = Math.atan2((sinpsi - this.es * F * this.sin_p12) * Math.tan(psi), sinpsi * (1 - this.es));
p.x = lon;
p.y = lat;
return p;
}
}
}
var names$6 = ["Azimuthal_Equidistant", "aeqd"];
var aeqd = {
init: init$7,
forward: forward$6,
inverse: inverse$6,
names: names$6
};
function init$6() {
//double temp; /* temporary variable */
/* Place parameters in static storage for common use
-------------------------------------------------*/
this.sin_p14 = Math.sin(this.lat0);
this.cos_p14 = Math.cos(this.lat0);
}
/* Orthographic forward equations--mapping lat,long to x,y
---------------------------------------------------*/
function forward$5(p) {
var sinphi, cosphi; /* sin and cos value */
var dlon; /* delta longitude value */
var coslon; /* cos of longitude */
var ksp; /* scale factor */
var g, x, y;
var lon = p.x;
var lat = p.y;
/* Forward equations
-----------------*/
dlon = adjust_lon(lon - this.long0);
sinphi = Math.sin(lat);
cosphi = Math.cos(lat);
coslon = Math.cos(dlon);
g = this.sin_p14 * sinphi + this.cos_p14 * cosphi * coslon;
ksp = 1;
if ((g > 0) || (Math.abs(g) <= EPSLN)) {
x = this.a * ksp * cosphi * Math.sin(dlon);
y = this.y0 + this.a * ksp * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon);
}
p.x = x;
p.y = y;
return p;
}
function inverse$5(p) {
var rh; /* height above ellipsoid */
var z; /* angle */
var sinz, cosz; /* sin of z and cos of z */
var con;
var lon, lat;
/* Inverse equations
-----------------*/
p.x -= this.x0;
p.y -= this.y0;
rh = Math.sqrt(p.x * p.x + p.y * p.y);
z = asinz(rh / this.a);
sinz = Math.sin(z);
cosz = Math.cos(z);
lon = this.long0;
if (Math.abs(rh) <= EPSLN) {
lat = this.lat0;
p.x = lon;
p.y = lat;
return p;
}
lat = asinz(cosz * this.sin_p14 + (p.y * sinz * this.cos_p14) / rh);
con = Math.abs(this.lat0) - HALF_PI;
if (Math.abs(con) <= EPSLN) {
if (this.lat0 >= 0) {
lon = adjust_lon(this.long0 + Math.atan2(p.x, - p.y));
}
else {
lon = adjust_lon(this.long0 - Math.atan2(-p.x, p.y));
}
p.x = lon;
p.y = lat;
return p;
}
lon = adjust_lon(this.long0 + Math.atan2((p.x * sinz), rh * this.cos_p14 * cosz - p.y * this.sin_p14 * sinz));
p.x = lon;
p.y = lat;
return p;
}
var names$5 = ["ortho"];
var ortho = {
init: init$6,
forward: forward$5,
inverse: inverse$5,
names: names$5
};
// QSC projection rewritten from the original PROJ4
/* constants */
var FACE_ENUM = {
FRONT: 1,
RIGHT: 2,
BACK: 3,
LEFT: 4,
TOP: 5,
BOTTOM: 6
};
var AREA_ENUM = {
AREA_0: 1,
AREA_1: 2,
AREA_2: 3,
AREA_3: 4
};
function init$5() {
this.x0 = this.x0 || 0;
this.y0 = this.y0 || 0;
this.lat0 = this.lat0 || 0;
this.long0 = this.long0 || 0;
this.lat_ts = this.lat_ts || 0;
this.title = this.title || "Quadrilateralized Spherical Cube";
/* Determine the cube face from the center of projection. */
if (this.lat0 >= HALF_PI - FORTPI / 2.0) {
this.face = FACE_ENUM.TOP;
} else if (this.lat0 <= -(HALF_PI - FORTPI / 2.0)) {
this.face = FACE_ENUM.BOTTOM;
} else if (Math.abs(this.long0) <= FORTPI) {
this.face = FACE_ENUM.FRONT;
} else if (Math.abs(this.long0) <= HALF_PI + FORTPI) {
this.face = this.long0 > 0.0 ? FACE_ENUM.RIGHT : FACE_ENUM.LEFT;
} else {
this.face = FACE_ENUM.BACK;
}
/* Fill in useful values for the ellipsoid <-> sphere shift
* described in [LK12]. */
if (this.es !== 0) {
this.one_minus_f = 1 - (this.a - this.b) / this.a;
this.one_minus_f_squared = this.one_minus_f * this.one_minus_f;
}
}
// QSC forward equations--mapping lat,long to x,y
// -----------------------------------------------------------------
function forward$4(p) {
var xy = {x: 0, y: 0};
var lat, lon;
var theta, phi;
var t, mu;
/* nu; */
var area = {value: 0};
// move lon according to projection's lon
p.x -= this.long0;
/* Convert the geodetic latitude to a geocentric latitude.
* This corresponds to the shift from the ellipsoid to the sphere
* described in [LK12]. */
if (this.es !== 0) {//if (P->es != 0) {
lat = Math.atan(this.one_minus_f_squared * Math.tan(p.y));
} else {
lat = p.y;
}
/* Convert the input lat, lon into theta, phi as used by QSC.
* This depends on the cube face and the area on it.
* For the top and bottom face, we can compute theta and phi
* directly from phi, lam. For the other faces, we must use
* unit sphere cartesian coordinates as an intermediate step. */
lon = p.x; //lon = lp.lam;
if (this.face === FACE_ENUM.TOP) {
phi = HALF_PI - lat;
if (lon >= FORTPI && lon <= HALF_PI + FORTPI) {
area.value = AREA_ENUM.AREA_0;
theta = lon - HALF_PI;
} else if (lon > HALF_PI + FORTPI || lon <= -(HALF_PI + FORTPI)) {
area.value = AREA_ENUM.AREA_1;
theta = (lon > 0.0 ? lon - SPI : lon + SPI);
} else if (lon > -(HALF_PI + FORTPI) && lon <= -FORTPI) {
area.value = AREA_ENUM.AREA_2;
theta = lon + HALF_PI;
} else {
area.value = AREA_ENUM.AREA_3;
theta = lon;
}
} else if (this.face === FACE_ENUM.BOTTOM) {
phi = HALF_PI + lat;
if (lon >= FORTPI && lon <= HALF_PI + FORTPI) {
area.value = AREA_ENUM.AREA_0;
theta = -lon + HALF_PI;
} else if (lon < FORTPI && lon >= -FORTPI) {
area.value = AREA_ENUM.AREA_1;
theta = -lon;
} else if (lon < -FORTPI && lon >= -(HALF_PI + FORTPI)) {
area.value = AREA_ENUM.AREA_2;
theta = -lon - HALF_PI;
} else {
area.value = AREA_ENUM.AREA_3;
theta = (lon > 0.0 ? -lon + SPI : -lon - SPI);
}
} else {
var q, r, s;
var sinlat, coslat;
var sinlon, coslon;
if (this.face === FACE_ENUM.RIGHT) {
lon = qsc_shift_lon_origin(lon, +HALF_PI);
} else if (this.face === FACE_ENUM.BACK) {
lon = qsc_shift_lon_origin(lon, +SPI);
} else if (this.face === FACE_ENUM.LEFT) {
lon = qsc_shift_lon_origin(lon, -HALF_PI);
}
sinlat = Math.sin(lat);
coslat = Math.cos(lat);
sinlon = Math.sin(lon);
coslon = Math.cos(lon);
q = coslat * coslon;
r = coslat * sinlon;
s = sinlat;
if (this.face === FACE_ENUM.FRONT) {
phi = Math.acos(q);
theta = qsc_fwd_equat_face_theta(phi, s, r, area);
} else if (this.face === FACE_ENUM.RIGHT) {
phi = Math.acos(r);
theta = qsc_fwd_equat_face_theta(phi, s, -q, area);
} else if (this.face === FACE_ENUM.BACK) {
phi = Math.acos(-q);
theta = qsc_fwd_equat_face_theta(phi, s, -r, area);
} else if (this.face === FACE_ENUM.LEFT) {
phi = Math.acos(-r);
theta = qsc_fwd_equat_face_theta(phi, s, q, area);
} else {
/* Impossible */
phi = theta = 0;
area.value = AREA_ENUM.AREA_0;
}
}
/* Compute mu and nu for the area of definition.
* For mu, see Eq. (3-21) in [OL76], but note the typos:
* compare with Eq. (3-14). For nu, see Eq. (3-38). */
mu = Math.atan((12 / SPI) * (theta + Math.acos(Math.sin(theta) * Math.cos(FORTPI)) - HALF_PI));
t = Math.sqrt((1 - Math.cos(phi)) / (Math.cos(mu) * Math.cos(mu)) / (1 - Math.cos(Math.atan(1 / Math.cos(theta)))));
/* Apply the result to the real area. */
if (area.value === AREA_ENUM.AREA_1) {
mu += HALF_PI;
} else if (area.value === AREA_ENUM.AREA_2) {
mu += SPI;
} else if (area.value === AREA_ENUM.AREA_3) {
mu += 1.5 * SPI;
}
/* Now compute x, y from mu and nu */
xy.x = t * Math.cos(mu);
xy.y = t * Math.sin(mu);
xy.x = xy.x * this.a + this.x0;
xy.y = xy.y * this.a + this.y0;
p.x = xy.x;
p.y = xy.y;
return p;
}
// QSC inverse equations--mapping x,y to lat/long
// -----------------------------------------------------------------
function inverse$4(p) {
var lp = {lam: 0, phi: 0};
var mu, nu, cosmu, tannu;
var tantheta, theta, cosphi, phi;
var t;
var area = {value: 0};
/* de-offset */
p.x = (p.x - this.x0) / this.a;
p.y = (p.y - this.y0) / this.a;
/* Convert the input x, y to the mu and nu angles as used by QSC.
* This depends on the area of the cube face. */
nu = Math.atan(Math.sqrt(p.x * p.x + p.y * p.y));
mu = Math.atan2(p.y, p.x);
if (p.x >= 0.0 && p.x >= Math.abs(p.y)) {
area.value = AREA_ENUM.AREA_0;
} else if (p.y >= 0.0 && p.y >= Math.abs(p.x)) {
area.value = AREA_ENUM.AREA_1;
mu -= HALF_PI;
} else if (p.x < 0.0 && -p.x >= Math.abs(p.y)) {
area.value = AREA_ENUM.AREA_2;
mu = (mu < 0.0 ? mu + SPI : mu - SPI);
} else {
area.value = AREA_ENUM.AREA_3;
mu += HALF_PI;
}
/* Compute phi and theta for the area of definition.
* The inverse projection is not described in the original paper, but some
* good hints can be found here (as of 2011-12-14):
* http://fits.gsfc.nasa.gov/fitsbits/saf.93/saf.9302
* (search for "Message-Id: <9302181759.AA25477 at fits.cv.nrao.edu>") */
t = (SPI / 12) * Math.tan(mu);
tantheta = Math.sin(t) / (Math.cos(t) - (1 / Math.sqrt(2)));
theta = Math.atan(tantheta);
cosmu = Math.cos(mu);
tannu = Math.tan(nu);
cosphi = 1 - cosmu * cosmu * tannu * tannu * (1 - Math.cos(Math.atan(1 / Math.cos(theta))));
if (cosphi < -1) {
cosphi = -1;
} else if (cosphi > +1) {
cosphi = +1;
}
/* Apply the result to the real area on the cube face.
* For the top and bottom face, we can compute phi and lam directly.
* For the other faces, we must use unit sphere cartesian coordinates
* as an intermediate step. */
if (this.face === FACE_ENUM.TOP) {
phi = Math.acos(cosphi);
lp.phi = HALF_PI - phi;
if (area.value === AREA_ENUM.AREA_0) {
lp.lam = theta + HALF_PI;
} else if (area.value === AREA_ENUM.AREA_1) {
lp.lam = (theta < 0.0 ? theta + SPI : theta - SPI);
} else if (area.value === AREA_ENUM.AREA_2) {
lp.lam = theta - HALF_PI;
} else /* area.value == AREA_ENUM.AREA_3 */ {
lp.lam = theta;
}
} else if (this.face === FACE_ENUM.BOTTOM) {
phi = Math.acos(cosphi);
lp.phi = phi - HALF_PI;
if (area.value === AREA_ENUM.AREA_0) {
lp.lam = -theta + HALF_PI;
} else if (area.value === AREA_ENUM.AREA_1) {
lp.lam = -theta;
} else if (area.value === AREA_ENUM.AREA_2) {
lp.lam = -theta - HALF_PI;
} else /* area.value == AREA_ENUM.AREA_3 */ {
lp.lam = (theta < 0.0 ? -theta - SPI : -theta + SPI);
}
} else {
/* Compute phi and lam via cartesian unit sphere coordinates. */
var q, r, s;
q = cosphi;
t = q * q;
if (t >= 1) {
s = 0;
} else {
s = Math.sqrt(1 - t) * Math.sin(theta);
}
t += s * s;
if (t >= 1) {
r = 0;
} else {
r = Math.sqrt(1 - t);
}
/* Rotate q,r,s into the correct area. */
if (area.value === AREA_ENUM.AREA_1) {
t = r;
r = -s;
s = t;
} else if (area.value === AREA_ENUM.AREA_2) {
r = -r;
s = -s;
} else if (area.value === AREA_ENUM.AREA_3) {
t = r;
r = s;
s = -t;
}
/* Rotate q,r,s into the correct cube face. */
if (this.face === FACE_ENUM.RIGHT) {
t = q;
q = -r;
r = t;
} else if (this.face === FACE_ENUM.BACK) {
q = -q;
r = -r;
} else if (this.face === FACE_ENUM.LEFT) {
t = q;
q = r;
r = -t;
}
/* Now compute phi and lam from the unit sphere coordinates. */
lp.phi = Math.acos(-s) - HALF_PI;
lp.lam = Math.atan2(r, q);
if (this.face === FACE_ENUM.RIGHT) {
lp.lam = qsc_shift_lon_origin(lp.lam, -HALF_PI);
} else if (this.face === FACE_ENUM.BACK) {
lp.lam = qsc_shift_lon_origin(lp.lam, -SPI);
} else if (this.face === FACE_ENUM.LEFT) {
lp.lam = qsc_shift_lon_origin(lp.lam, +HALF_PI);
}
}
/* Apply the shift from the sphere to the ellipsoid as described
* in [LK12]. */
if (this.es !== 0) {
var invert_sign;
var tanphi, xa;
invert_sign = (lp.phi < 0 ? 1 : 0);
tanphi = Math.tan(lp.phi);
xa = this.b / Math.sqrt(tanphi * tanphi + this.one_minus_f_squared);
lp.phi = Math.atan(Math.sqrt(this.a * this.a - xa * xa) / (this.one_minus_f * xa));
if (invert_sign) {
lp.phi = -lp.phi;
}
}
lp.lam += this.long0;
p.x = lp.lam;
p.y = lp.phi;
return p;
}
/* Helper function for forward projection: compute the theta angle
* and determine the area number. */
function qsc_fwd_equat_face_theta(phi, y, x, area) {
var theta;
if (phi < EPSLN) {
area.value = AREA_ENUM.AREA_0;
theta = 0.0;
} else {
theta = Math.atan2(y, x);
if (Math.abs(theta) <= FORTPI) {
area.value = AREA_ENUM.AREA_0;
} else if (theta > FORTPI && theta <= HALF_PI + FORTPI) {
area.value = AREA_ENUM.AREA_1;
theta -= HALF_PI;
} else if (theta > HALF_PI + FORTPI || theta <= -(HALF_PI + FORTPI)) {
area.value = AREA_ENUM.AREA_2;
theta = (theta >= 0.0 ? theta - SPI : theta + SPI);
} else {
area.value = AREA_ENUM.AREA_3;
theta += HALF_PI;
}
}
return theta;
}
/* Helper function: shift the longitude. */
function qsc_shift_lon_origin(lon, offset) {
var slon = lon + offset;
if (slon < -SPI) {
slon += TWO_PI;
} else if (slon > +SPI) {
slon -= TWO_PI;
}
return slon;
}
var names$4 = ["Quadrilateralized Spherical Cube", "Quadrilateralized_Spherical_Cube", "qsc"];
var qsc = {
init: init$5,
forward: forward$4,
inverse: inverse$4,
names: names$4
};
// Robinson projection
var COEFS_X = [
[1.0000, 2.2199e-17, -7.15515e-05, 3.1103e-06],
[0.9986, -0.000482243, -2.4897e-05, -1.3309e-06],
[0.9954, -0.00083103, -4.48605e-05, -9.86701e-07],
[0.9900, -0.00135364, -5.9661e-05, 3.6777e-06],
[0.9822, -0.00167442, -4.49547e-06, -5.72411e-06],
[0.9730, -0.00214868, -9.03571e-05, 1.8736e-08],
[0.9600, -0.00305085, -9.00761e-05, 1.64917e-06],
[0.9427, -0.00382792, -6.53386e-05, -2.6154e-06],
[0.9216, -0.00467746, -0.00010457, 4.81243e-06],
[0.8962, -0.00536223, -3.23831e-05, -5.43432e-06],
[0.8679, -0.00609363, -0.000113898, 3.32484e-06],
[0.8350, -0.00698325, -6.40253e-05, 9.34959e-07],
[0.7986, -0.00755338, -5.00009e-05, 9.35324e-07],
[0.7597, -0.00798324, -3.5971e-05, -2.27626e-06],
[0.7186, -0.00851367, -7.01149e-05, -8.6303e-06],
[0.6732, -0.00986209, -0.000199569, 1.91974e-05],
[0.6213, -0.010418, 8.83923e-05, 6.24051e-06],
[0.5722, -0.00906601, 0.000182, 6.24051e-06],
[0.5322, -0.00677797, 0.000275608, 6.24051e-06]
];
var COEFS_Y = [
[-5.20417e-18, 0.0124, 1.21431e-18, -8.45284e-11],
[0.0620, 0.0124, -1.26793e-09, 4.22642e-10],
[0.1240, 0.0124, 5.07171e-09, -1.60604e-09],
[0.1860, 0.0123999, -1.90189e-08, 6.00152e-09],
[0.2480, 0.0124002, 7.10039e-08, -2.24e-08],
[0.3100, 0.0123992, -2.64997e-07, 8.35986e-08],
[0.3720, 0.0124029, 9.88983e-07, -3.11994e-07],
[0.4340, 0.0123893, -3.69093e-06, -4.35621e-07],
[0.4958, 0.0123198, -1.02252e-05, -3.45523e-07],
[0.5571, 0.0121916, -1.54081e-05, -5.82288e-07],
[0.6176, 0.0119938, -2.41424e-05, -5.25327e-07],
[0.6769, 0.011713, -3.20223e-05, -5.16405e-07],
[0.7346, 0.0113541, -3.97684e-05, -6.09052e-07],
[0.7903, 0.0109107, -4.89042e-05, -1.04739e-06],
[0.8435, 0.0103431, -6.4615e-05, -1.40374e-09],
[0.8936, 0.00969686, -6.4636e-05, -8.547e-06],
[0.9394, 0.00840947, -0.000192841, -4.2106e-06],
[0.9761, 0.00616527, -0.000256, -4.2106e-06],
[1.0000, 0.00328947, -0.000319159, -4.2106e-06]
];
var FXC = 0.8487;
var FYC = 1.3523;
var C1 = R2D/5; // rad to 5-degree interval
var RC1 = 1/C1;
var NODES = 18;
var poly3_val = function(coefs, x) {
return coefs[0] + x * (coefs[1] + x * (coefs[2] + x * coefs[3]));
};
var poly3_der = function(coefs, x) {
return coefs[1] + x * (2 * coefs[2] + x * 3 * coefs[3]);
};
function newton_rapshon(f_df, start, max_err, iters) {
var x = start;
for (; iters; --iters) {
var upd = f_df(x);
x -= upd;
if (Math.abs(upd) < max_err) {
break;
}
}
return x;
}
function init$4() {
this.x0 = this.x0 || 0;
this.y0 = this.y0 || 0;
this.long0 = this.long0 || 0;
this.es = 0;
this.title = this.title || "Robinson";
}
function forward$3(ll) {
var lon = adjust_lon(ll.x - this.long0);
var dphi = Math.abs(ll.y);
var i = Math.floor(dphi * C1);
if (i < 0) {
i = 0;
} else if (i >= NODES) {
i = NODES - 1;
}
dphi = R2D * (dphi - RC1 * i);
var xy = {
x: poly3_val(COEFS_X[i], dphi) * lon,
y: poly3_val(COEFS_Y[i], dphi)
};
if (ll.y < 0) {
xy.y = -xy.y;
}
xy.x = xy.x * this.a * FXC + this.x0;
xy.y = xy.y * this.a * FYC + this.y0;
return xy;
}
function inverse$3(xy) {
var ll = {
x: (xy.x - this.x0) / (this.a * FXC),
y: Math.abs(xy.y - this.y0) / (this.a * FYC)
};
if (ll.y >= 1) { // pathologic case
ll.x /= COEFS_X[NODES][0];
ll.y = xy.y < 0 ? -HALF_PI : HALF_PI;
} else {
// find table interval
var i = Math.floor(ll.y * NODES);
if (i < 0) {
i = 0;
} else if (i >= NODES) {
i = NODES - 1;
}
for (;;) {
if (COEFS_Y[i][0] > ll.y) {
--i;
} else if (COEFS_Y[i+1][0] <= ll.y) {
++i;
} else {
break;
}
}
// linear interpolation in 5 degree interval
var coefs = COEFS_Y[i];
var t = 5 * (ll.y - coefs[0]) / (COEFS_Y[i+1][0] - coefs[0]);
// find t so that poly3_val(coefs, t) = ll.y
t = newton_rapshon(function(x) {
return (poly3_val(coefs, x) - ll.y) / poly3_der(coefs, x);
}, t, EPSLN, 100);
ll.x /= poly3_val(COEFS_X[i], t);
ll.y = (5 * i + t) * D2R$1;
if (xy.y < 0) {
ll.y = -ll.y;
}
}
ll.x = adjust_lon(ll.x + this.long0);
return ll;
}
var names$3 = ["Robinson", "robin"];
var robin = {
init: init$4,
forward: forward$3,
inverse: inverse$3,
names: names$3
};
function init$3() {
this.name = 'geocent';
}
function forward$2(p) {
var point = geodeticToGeocentric(p, this.es, this.a);
return point;
}
function inverse$2(p) {
var point = geocentricToGeodetic(p, this.es, this.a, this.b);
return point;
}
var names$2 = ["Geocentric", 'geocentric', "geocent", "Geocent"];
var geocent = {
init: init$3,
forward: forward$2,
inverse: inverse$2,
names: names$2
};
var mode = {
N_POLE: 0,
S_POLE: 1,
EQUIT: 2,
OBLIQ: 3
};
var params = {
h: { def: 100000, num: true }, // default is Karman line, no default in PROJ.7
azi: { def: 0, num: true, degrees: true }, // default is North
tilt: { def: 0, num: true, degrees: true }, // default is Nadir
long0: { def: 0, num: true }, // default is Greenwich, conversion to rad is automatic
lat0: { def: 0, num: true } // default is Equator, conversion to rad is automatic
};
function init$2() {
Object.keys(params).forEach(function (p) {
if (typeof this[p] === "undefined") {
this[p] = params[p].def;
} else if (params[p].num && isNaN(this[p])) {
throw new Error("Invalid parameter value, must be numeric " + p + " = " + this[p]);
} else if (params[p].num) {
this[p] = parseFloat(this[p]);
}
if (params[p].degrees) {
this[p] = this[p] * D2R$1;
}
}.bind(this));
if (Math.abs((Math.abs(this.lat0) - HALF_PI)) < EPSLN) {
this.mode = this.lat0 < 0 ? mode.S_POLE : mode.N_POLE;
} else if (Math.abs(this.lat0) < EPSLN) {
this.mode = mode.EQUIT;
} else {
this.mode = mode.OBLIQ;
this.sinph0 = Math.sin(this.lat0);
this.cosph0 = Math.cos(this.lat0);
}
this.pn1 = this.h / this.a; // Normalize relative to the Earth's radius
if (this.pn1 <= 0 || this.pn1 > 1e10) {
throw new Error("Invalid height");
}
this.p = 1 + this.pn1;
this.rp = 1 / this.p;
this.h1 = 1 / this.pn1;
this.pfact = (this.p + 1) * this.h1;
this.es = 0;
var omega = this.tilt;
var gamma = this.azi;
this.cg = Math.cos(gamma);
this.sg = Math.sin(gamma);
this.cw = Math.cos(omega);
this.sw = Math.sin(omega);
}
function forward$1(p) {
p.x -= this.long0;
var sinphi = Math.sin(p.y);
var cosphi = Math.cos(p.y);
var coslam = Math.cos(p.x);
var x, y;
switch (this.mode) {
case mode.OBLIQ:
y = this.sinph0 * sinphi + this.cosph0 * cosphi * coslam;
break;
case mode.EQUIT:
y = cosphi * coslam;
break;
case mode.S_POLE:
y = -sinphi;
break;
case mode.N_POLE:
y = sinphi;
break;
}
y = this.pn1 / (this.p - y);
x = y * cosphi * Math.sin(p.x);
switch (this.mode) {
case mode.OBLIQ:
y *= this.cosph0 * sinphi - this.sinph0 * cosphi * coslam;
break;
case mode.EQUIT:
y *= sinphi;
break;
case mode.N_POLE:
y *= -(cosphi * coslam);
break;
case mode.S_POLE:
y *= cosphi * coslam;
break;
}
// Tilt
var yt, ba;
yt = y * this.cg + x * this.sg;
ba = 1 / (yt * this.sw * this.h1 + this.cw);
x = (x * this.cg - y * this.sg) * this.cw * ba;
y = yt * ba;
p.x = x * this.a;
p.y = y * this.a;
return p;
}
function inverse$1(p) {
p.x /= this.a;
p.y /= this.a;
var r = { x: p.x, y: p.y };
// Un-Tilt
var bm, bq, yt;
yt = 1 / (this.pn1 - p.y * this.sw);
bm = this.pn1 * p.x * yt;
bq = this.pn1 * p.y * this.cw * yt;
p.x = bm * this.cg + bq * this.sg;
p.y = bq * this.cg - bm * this.sg;
var rh = hypot(p.x, p.y);
if (Math.abs(rh) < EPSLN) {
r.x = 0;
r.y = p.y;
} else {
var cosz, sinz;
sinz = 1 - rh * rh * this.pfact;
sinz = (this.p - Math.sqrt(sinz)) / (this.pn1 / rh + rh / this.pn1);
cosz = Math.sqrt(1 - sinz * sinz);
switch (this.mode) {
case mode.OBLIQ:
r.y = Math.asin(cosz * this.sinph0 + p.y * sinz * this.cosph0 / rh);
p.y = (cosz - this.sinph0 * Math.sin(r.y)) * rh;
p.x *= sinz * this.cosph0;
break;
case mode.EQUIT:
r.y = Math.asin(p.y * sinz / rh);
p.y = cosz * rh;
p.x *= sinz;
break;
case mode.N_POLE:
r.y = Math.asin(cosz);
p.y = -p.y;
break;
case mode.S_POLE:
r.y = -Math.asin(cosz);
break;
}
r.x = Math.atan2(p.x, p.y);
}
p.x = r.x + this.long0;
p.y = r.y;
return p;
}
var names$1 = ["Tilted_Perspective", "tpers"];
var tpers = {
init: init$2,
forward: forward$1,
inverse: inverse$1,
names: names$1
};
function init$1() {
this.flip_axis = (this.sweep === 'x' ? 1 : 0);
this.h = Number(this.h);
this.radius_g_1 = this.h / this.a;
if (this.radius_g_1 <= 0 || this.radius_g_1 > 1e10) {
throw new Error();
}
this.radius_g = 1.0 + this.radius_g_1;
this.C = this.radius_g * this.radius_g - 1.0;
if (this.es !== 0.0) {
var one_es = 1.0 - this.es;
var rone_es = 1 / one_es;
this.radius_p = Math.sqrt(one_es);
this.radius_p2 = one_es;
this.radius_p_inv2 = rone_es;
this.shape = 'ellipse'; // Use as a condition in the forward and inverse functions.
} else {
this.radius_p = 1.0;
this.radius_p2 = 1.0;
this.radius_p_inv2 = 1.0;
this.shape = 'sphere'; // Use as a condition in the forward and inverse functions.
}
if (!this.title) {
this.title = "Geostationary Satellite View";
}
}
function forward(p) {
var lon = p.x;
var lat = p.y;
var tmp, v_x, v_y, v_z;
lon = lon - this.long0;
if (this.shape === 'ellipse') {
lat = Math.atan(this.radius_p2 * Math.tan(lat));
var r = this.radius_p / hypot(this.radius_p * Math.cos(lat), Math.sin(lat));
v_x = r * Math.cos(lon) * Math.cos(lat);
v_y = r * Math.sin(lon) * Math.cos(lat);
v_z = r * Math.sin(lat);
if (((this.radius_g - v_x) * v_x - v_y * v_y - v_z * v_z * this.radius_p_inv2) < 0.0) {
p.x = Number.NaN;
p.y = Number.NaN;
return p;
}
tmp = this.radius_g - v_x;
if (this.flip_axis) {
p.x = this.radius_g_1 * Math.atan(v_y / hypot(v_z, tmp));
p.y = this.radius_g_1 * Math.atan(v_z / tmp);
} else {
p.x = this.radius_g_1 * Math.atan(v_y / tmp);
p.y = this.radius_g_1 * Math.atan(v_z / hypot(v_y, tmp));
}
} else if (this.shape === 'sphere') {
tmp = Math.cos(lat);
v_x = Math.cos(lon) * tmp;
v_y = Math.sin(lon) * tmp;
v_z = Math.sin(lat);
tmp = this.radius_g - v_x;
if (this.flip_axis) {
p.x = this.radius_g_1 * Math.atan(v_y / hypot(v_z, tmp));
p.y = this.radius_g_1 * Math.atan(v_z / tmp);
} else {
p.x = this.radius_g_1 * Math.atan(v_y / tmp);
p.y = this.radius_g_1 * Math.atan(v_z / hypot(v_y, tmp));
}
}
p.x = p.x * this.a;
p.y = p.y * this.a;
return p;
}
function inverse(p) {
var v_x = -1.0;
var v_y = 0.0;
var v_z = 0.0;
var a, b, det, k;
p.x = p.x / this.a;
p.y = p.y / this.a;
if (this.shape === 'ellipse') {
if (this.flip_axis) {
v_z = Math.tan(p.y / this.radius_g_1);
v_y = Math.tan(p.x / this.radius_g_1) * hypot(1.0, v_z);
} else {
v_y = Math.tan(p.x / this.radius_g_1);
v_z = Math.tan(p.y / this.radius_g_1) * hypot(1.0, v_y);
}
var v_zp = v_z / this.radius_p;
a = v_y * v_y + v_zp * v_zp + v_x * v_x;
b = 2 * this.radius_g * v_x;
det = (b * b) - 4 * a * this.C;
if (det < 0.0) {
p.x = Number.NaN;
p.y = Number.NaN;
return p;
}
k = (-b - Math.sqrt(det)) / (2.0 * a);
v_x = this.radius_g + k * v_x;
v_y *= k;
v_z *= k;
p.x = Math.atan2(v_y, v_x);
p.y = Math.atan(v_z * Math.cos(p.x) / v_x);
p.y = Math.atan(this.radius_p_inv2 * Math.tan(p.y));
} else if (this.shape === 'sphere') {
if (this.flip_axis) {
v_z = Math.tan(p.y / this.radius_g_1);
v_y = Math.tan(p.x / this.radius_g_1) * Math.sqrt(1.0 + v_z * v_z);
} else {
v_y = Math.tan(p.x / this.radius_g_1);
v_z = Math.tan(p.y / this.radius_g_1) * Math.sqrt(1.0 + v_y * v_y);
}
a = v_y * v_y + v_z * v_z + v_x * v_x;
b = 2 * this.radius_g * v_x;
det = (b * b) - 4 * a * this.C;
if (det < 0.0) {
p.x = Number.NaN;
p.y = Number.NaN;
return p;
}
k = (-b - Math.sqrt(det)) / (2.0 * a);
v_x = this.radius_g + k * v_x;
v_y *= k;
v_z *= k;
p.x = Math.atan2(v_y, v_x);
p.y = Math.atan(v_z * Math.cos(p.x) / v_x);
}
p.x = p.x + this.long0;
return p;
}
var names = ["Geostationary Satellite View", "Geostationary_Satellite", "geos"];
var geos = {
init: init$1,
forward: forward,
inverse: inverse,
names: names,
};
function includedProjections(proj4){
proj4.Proj.projections.add(tmerc);
proj4.Proj.projections.add(etmerc);
proj4.Proj.projections.add(utm);
proj4.Proj.projections.add(sterea);
proj4.Proj.projections.add(stere);
proj4.Proj.projections.add(somerc);
proj4.Proj.projections.add(omerc);
proj4.Proj.projections.add(lcc);
proj4.Proj.projections.add(krovak);
proj4.Proj.projections.add(cass);
proj4.Proj.projections.add(laea);
proj4.Proj.projections.add(aea);
proj4.Proj.projections.add(gnom);
proj4.Proj.projections.add(cea);
proj4.Proj.projections.add(eqc);
proj4.Proj.projections.add(poly);
proj4.Proj.projections.add(nzmg);
proj4.Proj.projections.add(mill);
proj4.Proj.projections.add(sinu);
proj4.Proj.projections.add(moll);
proj4.Proj.projections.add(eqdc);
proj4.Proj.projections.add(vandg);
proj4.Proj.projections.add(aeqd);
proj4.Proj.projections.add(ortho);
proj4.Proj.projections.add(qsc);
proj4.Proj.projections.add(robin);
proj4.Proj.projections.add(geocent);
proj4.Proj.projections.add(tpers);
proj4.Proj.projections.add(geos);
}
proj4.defaultDatum = 'WGS84'; //default datum
proj4.Proj = Projection;
proj4.WGS84 = new proj4.Proj('WGS84');
proj4.Point = Point$2;
proj4.toPoint = common;
proj4.defs = defs;
proj4.nadgrid = nadgrid;
proj4.transform = transform;
proj4.mgrs = mgrs;
proj4.version = '__VERSION__';
includedProjections(proj4);
function prettifyProjection(longitude, latitude, proj4Projection, proj4longlat, projectionUnits) {
const zone = 1 + Math.floor((longitude + 180) / 6);
const projection = proj4Projection + " +zone=" + zone + (latitude < 0 ? " +south" : "");
const projPoint = proj4(proj4longlat, projection, [longitude, latitude]);
return {
utmZone: zone + (latitude < 0 ? "S" : "N"),
north: projPoint[1].toFixed(2) + projectionUnits,
east: projPoint[0].toFixed(2) + projectionUnits
};
}
class EarthGravityModel1996 {
/**
* The Earth Gravity Model 1996 (EGM96) geoid.
* @param {String} gridFileUrl The URL of the WW15MGH.DAC file.
*/
constructor(gridFileUrl) {
this.gridFileUrl = gridFileUrl;
this.data = void 0;
this.minimumHeight = -106.99;
this.maximumHeight = 85.39;
}
/**
* Determines if this class will work in the current environment. It will return false on older browsers without support
* for typed arrays.
* @return {Boolean} True if this class may be used in this environment; otherwise, false.
*/
isSupported() {
return typeof Int16Array !== "undefined" && typeof Uint8Array !== "undefined";
}
/**
* Gets the height of EGM96 above the surface of the ellipsoid.
* @param {String} baseUrl The base URL for TerriaJS resources.
* @param {Number} longitude The longitude.
* @param {Number} latitude The latitude
* @return {Promise|Number} A promise, that, when it results The height of mean sea level above the ellipsoid at the specified location. Negative numbers indicate that mean sea level
* is below the ellipsoid.
*/
getHeight(longitude, latitude) {
return getHeightData(this).then(function(data) {
return getHeightFromData(data, longitude, latitude);
});
}
getHeights(cartographicArray) {
return getHeightData(this).then(function(data) {
for (let i = 0; i < cartographicArray.length; ++i) {
const cartographic = cartographicArray[i];
cartographic.height = getHeightFromData(data, cartographic.longitude, cartographic.latitude);
}
return cartographicArray;
});
}
}
async function getHeightData(model) {
const { defined } = Cesium;
if (!defined(model.data)) {
model.data = loadArrayBuffer(model.gridFileUrl);
}
let data = model.data;
if (model.data instanceof Promise) {
data = await model.data;
}
if (!(model.data instanceof Int16Array)) {
const byteView = new Uint8Array(data);
for (let k = 0; k < byteView.length; k += 2) {
const tmp = byteView[k];
byteView[k] = byteView[k + 1];
byteView[k + 1] = tmp;
}
model.data = new Int16Array(data);
}
return model.data;
}
function getHeightFromData(data, longitude, latitude) {
const { Math: CesiumMath } = Cesium;
let recordIndex = 720 * (CesiumMath.PI_OVER_TWO - latitude) / Math.PI;
if (recordIndex < 0) {
recordIndex = 0;
} else if (recordIndex > 720) {
recordIndex = 720;
}
longitude = CesiumMath.zeroToTwoPi(longitude);
let heightIndex = 1440 * longitude / CesiumMath.TWO_PI;
if (heightIndex < 0) {
heightIndex = 0;
} else if (heightIndex > 1440) {
heightIndex = 1440;
}
const i = heightIndex | 0;
const j = recordIndex | 0;
const xMinusX1 = heightIndex - i;
const yMinusY1 = recordIndex - j;
const x2MinusX = 1 - xMinusX1;
const y2MinusY = 1 - yMinusY1;
const f11 = getHeightValue(data, j, i);
const f21 = getHeightValue(data, j, i + 1);
const f12 = getHeightValue(data, j + 1, i);
const f22 = getHeightValue(data, j + 1, i + 1);
return (f11 * x2MinusX * y2MinusY + f21 * xMinusX1 * y2MinusY + f12 * x2MinusX * yMinusY1 + f22 * xMinusX1 * yMinusY1) / 100;
}
function getHeightValue(data, recordIndex, heightIndex) {
if (recordIndex > 720) {
recordIndex = 720;
} else if (recordIndex < 0) {
recordIndex = 0;
}
if (heightIndex > 1439) {
heightIndex -= 1440;
} else if (heightIndex < 0) {
heightIndex += 1440;
}
return data[recordIndex * 1440 + heightIndex];
}
function loadArrayBuffer(urlOrResource) {
const { Resource } = Cesium;
const resource = Resource.createIfNeeded(urlOrResource);
return resource.fetchArrayBuffer();
}
class MouseCoords {
constructor(options) {
const { Cartographic, knockout } = Cesium;
const gridFileUrl = options.gridFileUrl;
gridFileUrl && (this.geoidModel = new EarthGravityModel1996(gridFileUrl));
this.proj4Projection = options.proj4Projection;
this.projectionUnits = options.projectionUnits;
this.proj4longlat = options.proj4longlat;
this.lastHeightSamplePosition = new Cartographic();
this.accurateSamplingDebounceTime = 250;
this.tileRequestInFlight = void 0;
this.elevation = "";
this.utmZone = "";
this.latitude = "";
this.longitude = "";
this.north = "";
this.east = "";
this.useProjection = false;
this.debounceSampleAccurateHeight = debounce(this.sampleAccurateHeight, this.accurateSamplingDebounceTime);
this.decimal = options.decimal || 5;
this.rangeType = options.rangeType || 0;
knockout.track(this, ["elevation", "utmZone", "latitude", "longitude", "north", "east", "useProjection"]);
}
toggleUseProjection() {
this.useProjection = !this.useProjection;
}
updateCoordinatesFromCesium(viewer, position) {
const { Cartographic, defined, EllipsoidTerrainProvider, Intersections2D, SceneMode } = Cesium;
const scene = viewer.scene;
const camera = scene.camera;
const pickRay = camera.getPickRay(position);
const globe = scene.globe;
const pickedTriangle = globe.pickTriangle(pickRay, scene);
if (defined(pickedTriangle)) {
const ellipsoid = globe.ellipsoid;
const v0 = ellipsoid.cartesianToCartographic(pickedTriangle.v0);
const v1 = ellipsoid.cartesianToCartographic(pickedTriangle.v1);
const v2 = ellipsoid.cartesianToCartographic(pickedTriangle.v2);
const intersection = ellipsoid.cartesianToCartographic(
scene.mode === SceneMode.SCENE3D ? pickedTriangle.intersection : scene.globe.pick(pickRay, scene)
);
let errorBar;
if (globe.terrainProvider instanceof EllipsoidTerrainProvider) {
intersection.height = void 0;
} else {
const barycentric = Intersections2D.computeBarycentricCoordinates(
intersection.longitude,
intersection.latitude,
v0.longitude,
v0.latitude,
v1.longitude,
v1.latitude,
v2.longitude,
v2.latitude
);
if (barycentric.x >= -1e-15 && barycentric.y >= -1e-15 && barycentric.z >= -1e-15) {
const height = barycentric.x * v0.height + barycentric.y * v1.height + barycentric.z * v2.height;
intersection.height = height;
}
const geometricError = globe.terrainProvider.getLevelMaximumGeometricError(pickedTriangle.tile.level);
const approximateHeight = intersection.height;
const minHeight = Math.max(pickedTriangle.tile.data.tileBoundingRegion.minimumHeight, approximateHeight - geometricError);
const maxHeight = Math.min(pickedTriangle.tile.data.tileBoundingRegion.maximumHeight, approximateHeight + geometricError);
const minHeightGeoid = minHeight - (this.geoidModel ? this.geoidModel.minimumHeight : 0);
const maxHeightGeoid = maxHeight + (this.geoidModel ? this.geoidModel.maximumHeight : 0);
errorBar = Math.max(Math.abs(approximateHeight - minHeightGeoid), Math.abs(maxHeightGeoid - approximateHeight));
}
Cartographic.clone(intersection, this.lastHeightSamplePosition);
const terrainProvider = globe.terrainProvider;
this.cartographicToFields(intersection, errorBar);
if (!(terrainProvider instanceof EllipsoidTerrainProvider)) {
this.debounceSampleAccurateHeight(terrainProvider, intersection);
}
} else {
this.elevation = "";
this.utmZone = "";
this.latitude = "";
this.longitude = "";
this.north = "";
this.east = "";
}
}
cartographicToFields(coordinates, errorBar) {
const { Math: CesiumMath } = Cesium;
const latitude = CesiumMath.toDegrees(coordinates.latitude);
const longitude = CesiumMath.toDegrees(coordinates.longitude);
if (this.useProjection) {
const prettyProjection = prettifyProjection(longitude, latitude, this.proj4Projection, this.proj4longlat, this.projectionUnits);
this.utmZone = prettyProjection.utmZone;
this.north = prettyProjection.north;
this.east = prettyProjection.east;
}
const prettyCoordinate = prettifyCoordinates(longitude, latitude, {
height: coordinates.height,
errorBar,
decimal: this.decimal,
rangeType: this.rangeType
});
this.latitude = prettyCoordinate.latitude;
this.longitude = prettyCoordinate.longitude;
this.elevation = prettyCoordinate.elevation;
}
sampleAccurateHeight(terrainProvider, position) {
const { Cartographic, sampleTerrainMostDetailed } = Cesium;
if (this.tileRequestInFlight) {
this.debounceSampleAccurateHeight.cancel();
this.debounceSampleAccurateHeight(terrainProvider, position);
return;
}
const positionWithHeight = Cartographic.clone(position);
const geoidHeightPromise = this.geoidModel ? this.geoidModel.getHeight(position.longitude, position.latitude) : void 0;
const terrainPromise = sampleTerrainMostDetailed(terrainProvider, [positionWithHeight]);
this.tileRequestInFlight = Promise.all([geoidHeightPromise, terrainPromise]).then((result) => {
const geoidHeight = result[0] || 0;
this.tileRequestInFlight = void 0;
if (Cartographic.equals(position, this.lastHeightSamplePosition)) {
position.height = positionWithHeight.height - geoidHeight;
this.cartographicToFields(position);
}
}).catch(() => {
this.tileRequestInFlight = void 0;
});
}
}
const scratchArray = [];
const scratchSphereIntersectionResult = {
start: 0,
stop: 0
};
const scratchV0 = {};
const scratchV1 = {};
const scratchV2 = {};
function extendForMouseCoords() {
const { Globe, GlobeSurfaceTile, BoundingSphere, defaultValue, Cartesian3, defined, DeveloperError, IntersectionTests, SceneMode } = Cesium;
Globe.prototype.pickTriangle = Globe.prototype.pickTriangle || function(ray, scene, cullBackFaces, result) {
if (!defined(ray)) {
throw new DeveloperError("ray is required");
}
if (!defined(scene)) {
throw new DeveloperError("scene is required");
}
cullBackFaces = defaultValue(cullBackFaces, true);
const mode = scene.mode;
const projection = scene.mapProjection;
const sphereIntersections = scratchArray;
sphereIntersections.length = 0;
const tilesToRender = this._surface._tilesToRender;
let length = tilesToRender.length;
let tile;
let i;
for (i = 0; i < length; ++i) {
tile = tilesToRender[i];
const surfaceTile = tile.data;
if (!defined(surfaceTile)) {
continue;
}
const boundingVolume = surfaceTile.pickBoundingSphere;
if (mode !== SceneMode.SCENE3D) {
BoundingSphere.fromRectangleWithHeights2D(tile.rectangle, projection, surfaceTile.minimumHeight, surfaceTile.maximumHeight, boundingVolume);
Cartesian3.fromElements(boundingVolume.center.z, boundingVolume.center.x, boundingVolume.center.y, boundingVolume.center);
} else {
BoundingSphere.clone(surfaceTile.boundingSphere3D, boundingVolume);
}
const boundingSphereIntersection = IntersectionTests.raySphere(ray, boundingVolume, scratchSphereIntersectionResult);
if (defined(boundingSphereIntersection)) {
sphereIntersections.push(tile);
}
}
sphereIntersections.sort(createComparePickTileFunction(ray.origin));
let intersection;
length = sphereIntersections.length;
for (i = 0; i < length; ++i) {
intersection = sphereIntersections[i].data.pickTriangle(ray, scene.mode, scene.mapProjection, cullBackFaces, result);
if (defined(intersection)) {
intersection.tile = sphereIntersections[i];
break;
}
}
return intersection;
};
GlobeSurfaceTile.prototype.pickTriangle = GlobeSurfaceTile.prototype.pickTriangle || function(ray, mode, projection, cullBackFaces) {
const mesh = this.renderedMesh;
if (!defined(mesh)) {
return void 0;
}
const vertices = mesh.vertices;
const indices = mesh.indices;
const encoding = mesh.encoding;
const length = indices.length;
for (let i = 0; i < length; i += 3) {
const i0 = indices[i];
const i1 = indices[i + 1];
const i2 = indices[i + 2];
const v0 = getPosition(encoding, mode, projection, vertices, i0, scratchV0);
const v1 = getPosition(encoding, mode, projection, vertices, i1, scratchV1);
const v2 = getPosition(encoding, mode, projection, vertices, i2, scratchV2);
const intersection = IntersectionTests.rayTriangle(ray, v0, v1, v2, cullBackFaces, new Cartesian3());
if (defined(intersection)) {
return {
intersection,
v0,
v1,
v2
};
}
}
return void 0;
};
}
function createComparePickTileFunction(rayOrigin) {
const { BoundingSphere } = Cesium;
return function(a, b) {
const aDist = BoundingSphere.distanceSquaredTo(a.data.pickBoundingSphere, rayOrigin);
const bDist = BoundingSphere.distanceSquaredTo(b.data.pickBoundingSphere, rayOrigin);
return aDist - bDist;
};
}
function getPosition(encoding, mode, projection, vertices, index, result) {
encoding.decodePosition(vertices, index, result);
const { Cartesian3, defined, SceneMode } = Cesium;
if (defined(mode) && mode !== SceneMode.SCENE3D) {
const ellipsoid = projection.ellipsoid;
const positionCart = ellipsoid.cartesianToCartographic(result);
projection.project(positionCart, result);
Cartesian3.fromElements(result.z, result.x, result.y, result);
}
return result;
}
var statusBarDefaultProps = {
gridFileUrl: {
type: String,
default: "https://zouyaoji.top/vue-cesium/SampleData/WW15MGH.DAC"
},
proj4Projection: {
type: String,
default: "+proj=utm +ellps=GRS80 +units=m +no_defs"
},
projectionUnits: {
type: String,
default: "m"
},
proj4longlat: {
type: String,
default: "+proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees +no_defs"
},
position: {
type: String,
default: "bottom-right",
validator: (v) => ["top-right", "top-left", "bottom-right", "bottom-left", "top", "right", "bottom", "left"].includes(v)
},
offset: {
type: Array,
validator: (v) => v.length === 2
},
color: {
type: String,
default: "#fff"
},
decimal: {
type: Number,
default: 6
},
rangeType: {
type: Number,
default: 0
},
background: {
type: String,
default: "#3f4854"
},
showCameraInfo: {
type: Boolean,
default: true
},
showMouseInfo: {
type: Boolean,
default: true
},
showPerformanceInfo: {
type: Boolean,
default: true
},
useProjection: {
type: Boolean,
default: true
},
tooltip: {
type: [Boolean, Object],
default: () => ({
delay: 500,
anchor: "bottom middle",
offset: [0, 20],
tip: void 0
})
},
customClass: {
type: String,
default: ""
},
teleportToViewer: {
type: Boolean,
default: true
}
};
const emits$i = {
...commonEmits,
statusBarEvt: (evt) => true
};
const statusBarProps = exports('statusBarProps', statusBarDefaultProps);
var StatusBar = defineComponent({
name: "VcStatusBar",
props: statusBarProps,
emits: emits$i,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "VcStatusBar";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const parentInstance = getVcParentInstance(instance);
const { $services } = commonState;
const rootRef = ref(null);
const tooltipRef = ref(null);
const { t } = useLocale();
let lastMouseX = -1;
let lastMouseY = -1;
const cameraInfo = reactive({
heading: "NaN",
pitch: "NaN",
roll: "NaN",
height: "NaN",
level: "NaN"
});
const performanceInfo = reactive({
fps: "NaN",
ms: "NaN"
});
const mouseCoordsInfo = ref();
const positionState = usePosition(props);
const hasVcNavigation = ((_a = parentInstance.proxy) == null ? void 0 : _a.$options.name) === "VcNavigation";
const canRender = ref(hasVcNavigation);
const rootStyle = reactive({});
let debugShowFramesPerSecond = false;
watch(
() => props,
(val) => {
nextTick(() => {
if (!instance.mounted) {
return;
}
updateRootStyle();
});
},
{
deep: true
}
);
instance.createCesiumObject = async () => {
const { viewer } = $services;
const viewerElement = viewer._element;
if (props.showMouseInfo) {
mouseCoordsInfo.value = new MouseCoords({
gridFileUrl: props.gridFileUrl,
proj4Projection: props.proj4Projection,
projectionUnits: props.projectionUnits,
proj4longlat: props.proj4longlat,
decimal: props.decimal,
rangeType: props.rangeType
});
viewerElement.addEventListener("wheel", onMouseMove, false);
viewerElement.addEventListener("mousemove", onMouseMove, false);
viewerElement.addEventListener("touchmove", onMouseMove, false);
extendForMouseCoords();
}
if (props.showCameraInfo) {
viewer.camera.changed.addEventListener(onCameraChanged);
onCameraChanged();
}
if (props.showPerformanceInfo) {
debugShowFramesPerSecond = viewer.scene.debugShowFramesPerSecond;
viewer.scene.debugShowFramesPerSecond = true;
viewer.scene.postRender.addEventListener(onScenePostRender);
}
return rootRef;
};
instance.mount = async () => {
var _a2, _b;
canRender.value = true;
nextTick(() => {
updateRootStyle();
});
const { viewer } = $services;
(_b = viewer.viewerWidgetResized) == null ? void 0 : _b.raiseEvent({
type: instance.cesiumClass,
status: "mounted",
target: (_a2 = $(rootRef)) == null ? void 0 : _a2.$el
});
return true;
};
instance.unmount = async () => {
var _a2, _b;
canRender.value = false;
const { viewer } = $services;
const viewerElement = viewer._element;
if (props.showMouseInfo) {
mouseCoordsInfo.value = void 0;
viewerElement.removeEventListener("wheel", onMouseMove);
viewerElement.removeEventListener("mousemove", onMouseMove);
viewerElement.removeEventListener("touchmove", onMouseMove);
}
if (props.showCameraInfo) {
viewer.camera.changed.removeEventListener(onCameraChanged);
}
if (props.showPerformanceInfo) {
if (debugShowFramesPerSecond) {
viewer.scene._performanceDisplay._container.style.display = "block";
} else {
viewer.scene.debugShowFramesPerSecond = false;
}
viewer.scene.postRender.removeEventListener(onScenePostRender);
}
(_b = viewer.viewerWidgetResized) == null ? void 0 : _b.raiseEvent({
type: instance.cesiumClass,
status: "unmounted",
target: (_a2 = $(rootRef)) == null ? void 0 : _a2.$el
});
return true;
};
const updateRootStyle = () => {
const css = positionState.style.value;
rootStyle.left = css.left;
rootStyle.top = css.top;
rootStyle.transform = css.transform;
css.background = props.background;
css.color = props.color;
if (typeof props.teleportToViewer === "undefined" || props.teleportToViewer) {
const side = positionState.attach.value;
if ((side.bottom || side.top) && !side.left && !side.right) {
css.left = "50%";
css.transform = "translate(-50%, 0)";
}
if ((side.left || side.right) && !side.top && !side.bottom) {
css.top = "50%";
css.transform = "translate(0, -50%)";
}
}
Object.assign(rootStyle, css);
};
const onScenePostRender = throttle((scene) => {
var _a2, _b;
performanceInfo.fps = (_a2 = scene._performanceDisplay) == null ? void 0 : _a2._fpsText.nodeValue;
performanceInfo.ms = (_b = scene._performanceDisplay) == null ? void 0 : _b._msText.nodeValue;
scene._performanceDisplay._container.style.display = "none";
}, 250);
const onCameraChanged = () => {
const { viewer } = $services;
const scene = viewer.scene;
const sscc = scene.screenSpaceCameraController;
if (scene.mode === Cesium.SceneMode.MORPHING || !sscc.enableInputs) {
return;
}
const { Math: CesiumMath } = Cesium;
cameraInfo.heading = CesiumMath.toDegrees(viewer.camera.heading).toFixed(1);
cameraInfo.pitch = CesiumMath.toDegrees(viewer.camera.pitch).toFixed(1);
cameraInfo.roll = CesiumMath.toDegrees(viewer.camera.roll).toFixed(1);
cameraInfo.height = viewer.camera.positionCartographic.height.toFixed(2);
cameraInfo.level = heightToLevel(Number(cameraInfo.height)).toFixed(0);
};
const onMouseMove = (e) => {
var _a2;
const { Cartesian2, SceneMode } = Cesium;
const { viewer } = $services;
if (viewer.scene.mode === SceneMode.MORPHING)
return;
const clientX = e.type === "mousemove" || e.type === "wheel" ? e.clientX : e.changedTouches[0].clientX;
const clientY = e.type === "mousemove" || e.type === "wheel" ? e.clientY : e.changedTouches[0].clientY;
if (clientX === lastMouseX && clientY === lastMouseY) {
return;
}
lastMouseX = clientX;
lastMouseY = clientY;
const viewerElement = viewer._element;
if (viewer) {
if (props.showMouseInfo) {
const rect = viewerElement.getBoundingClientRect();
const position = new Cartesian2(clientX - rect.left, clientY - rect.top);
(_a2 = mouseCoordsInfo.value) == null ? void 0 : _a2.updateCoordinatesFromCesium(viewer, position);
}
const listener = getInstanceListener(instance, "statusBarEvt");
listener && ctx.emit("statusBarEvt", {
type: "statusBar",
mouseCoordsInfo: mouseCoordsInfo.value,
cameraInfo,
performanceInfo
});
}
};
const toggleUseProjection = () => {
var _a2, _b;
if (!props.useProjection) {
return;
}
(_a2 = $(tooltipRef)) == null ? void 0 : _a2.hide();
if (props.showMouseInfo) {
(_b = mouseCoordsInfo.value) == null ? void 0 : _b.toggleUseProjection();
}
};
Object.assign(instance.proxy, {
getMouseCoordsInfo: () => mouseCoordsInfo.value,
getCameraInfo: () => cameraInfo,
getPerformanceInfo: () => performanceInfo
});
return () => {
var _a2, _b, _c, _d, _e, _f, _g, _h;
if (canRender.value) {
const inner = [];
if (props.showMouseInfo) {
if (!((_a2 = mouseCoordsInfo.value) == null ? void 0 : _a2.useProjection)) {
inner.push(
h(
"div",
{
class: "vc-section ellipsis"
},
[
h(
"span",
{
...ctx.attrs
},
t("vc.navigation.statusBar.lng")
),
h("span", {}, (_b = mouseCoordsInfo.value) == null ? void 0 : _b.longitude)
]
),
h(
"div",
{
class: "vc-section ellipsis"
},
[h("span", {}, t("vc.navigation.statusBar.lat")), h("span", {}, (_c = mouseCoordsInfo.value) == null ? void 0 : _c.latitude)]
)
);
} else {
inner.push(
h(
"div",
{
class: "vc-section-short ellipsis"
},
[
h(
"span",
{
...ctx.attrs
},
t("vc.navigation.statusBar.zone")
),
h("span", null, (_d = mouseCoordsInfo.value) == null ? void 0 : _d.utmZone)
]
),
h(
"div",
{
class: "vc-section ellipsis"
},
[
h(
"span",
{
...ctx.attrs
},
t("vc.navigation.statusBar.e")
),
h("span", null, (_e = mouseCoordsInfo.value) == null ? void 0 : _e.east)
]
),
h(
"div",
{
class: "vc-section ellipsis"
},
[
h(
"span",
{
...ctx.attrs
},
t("vc.navigation.statusBar.n")
),
h("span", null, (_f = mouseCoordsInfo.value) == null ? void 0 : _f.north)
]
)
);
}
if ((_g = mouseCoordsInfo.value) == null ? void 0 : _g.elevation) {
inner.push(
h(
"div",
{
class: "vc-section ellipsis"
},
[
h(
"span",
{
...ctx.attrs
},
t("vc.navigation.statusBar.elev")
),
h("span", {}, (_h = mouseCoordsInfo.value) == null ? void 0 : _h.elevation)
]
)
);
} else {
inner.push(createCommentVNode("v-if"));
}
} else {
inner.push(createCommentVNode("v-if"));
}
if (props.showCameraInfo) {
inner.push(
h(
"div",
{
class: "vc-section-short-mini ellipsis"
},
[
h(
"span",
{
...ctx.attrs
},
t("vc.navigation.statusBar.level")
),
h("span", null, cameraInfo.level)
]
),
h(
"div",
{
class: "vc-section-short ellipsis"
},
[
h(
"span",
{
...ctx.attrs
},
t("vc.navigation.statusBar.heading")
),
h("span", null, `${cameraInfo.heading}\xB0`)
]
),
h(
"div",
{
class: "vc-section-short ellipsis"
},
[
h(
"span",
{
...ctx.attrs
},
t("vc.navigation.statusBar.pitch")
),
h("span", null, `${cameraInfo.pitch}\xB0`)
]
),
h(
"div",
{
class: "vc-section-short ellipsis"
},
[
h(
"span",
{
...ctx.attrs
},
t("vc.navigation.statusBar.roll")
),
h("span", null, `${cameraInfo.roll}\xB0`)
]
),
h(
"div",
{
class: "vc-section ellipsis"
},
[
h(
"span",
{
...ctx.attrs
},
t("vc.navigation.statusBar.cameraHeight")
),
h("span", null, `${cameraInfo.height}m`)
]
)
);
} else {
inner.push(createCommentVNode("v-if"));
}
if (props.showPerformanceInfo) {
inner.push(
h(
"div",
{
class: "vc-section-short-mini ellipsis"
},
[h("span", null, performanceInfo.ms)]
),
h(
"div",
{
class: "vc-section-short-mini ellipsis"
},
[h("span", null, performanceInfo.fps)]
)
);
} else {
inner.push(createCommentVNode("v-if"));
}
if (isPlainObject(props.tooltip) && props.showMouseInfo && props.useProjection) {
inner.push(
h(
VcTooltip,
{
ref: tooltipRef,
...props.tooltip
},
() => h("strong", null, isPlainObject(props.tooltip) && props.tooltip.tip || t("vc.navigation.statusBar.tip"))
)
);
} else {
inner.push(createCommentVNode("v-if"));
}
const renderContent = h(
VcBtn,
{
ref: rootRef,
class: `vc-status-bar ${positionState.classes.value} ${props.customClass}`,
style: rootStyle,
noCaps: true,
onClick: toggleUseProjection
},
() => inner
);
return !hasVcNavigation && props.teleportToViewer ? h(Teleport, { to: $services.viewer._element }, renderContent) : renderContent;
} else {
return createCommentVNode("v-if");
}
};
}
});
var distancelegendDefaultProps = {
position: {
type: String,
default: "bottom-right",
validator: (v) => ["top-right", "top-left", "bottom-right", "bottom-left", "top", "right", "bottom", "left"].includes(v)
},
offset: {
type: Array,
validator: (v) => v.length === 2
},
color: {
type: String,
default: "#fff"
},
background: {
type: String,
default: "#3f4854"
},
width: {
type: Number,
default: 100
},
barBackground: {
type: String,
default: "#fff"
},
customClass: {
type: String,
default: ""
},
teleportToViewer: {
type: Boolean,
default: true
}
};
const emits$h = {
...commonEmits,
distanceLegendEvt: (evt) => true
};
const distanceLegendProps = exports('distanceLegendProps', distancelegendDefaultProps);
var DistanceLegend = defineComponent({
name: "VcDistanceLegend",
props: distanceLegendProps,
emits: emits$h,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "VcDistanceLegend";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const parentInstance = getVcParentInstance(instance);
const { $services } = commonState;
const rootRef = ref(null);
const distanceLabel = ref("");
const positionState = usePosition(props);
const hasVcNavigation = ((_a = parentInstance.proxy) == null ? void 0 : _a.$options.name) === "VcNavigation";
const canRender = ref(hasVcNavigation);
const rootStyle = reactive({});
let lastLegendUpdate = 0;
const barWidth = ref(0);
let distance = 0;
watch(
() => props,
(val) => {
nextTick(() => {
if (!instance.mounted) {
return;
}
updateRootStyle();
});
},
{
deep: true
}
);
const barStyle = computed(() => {
return {
width: `${barWidth.value}px`,
left: `${5 + (props.width + 15 - barWidth.value) / 2}px`,
height: "2px",
background: props.barBackground
};
});
instance.createCesiumObject = async () => {
distanceLabel.value = "";
return rootRef;
};
instance.mount = async () => {
var _a2, _b;
canRender.value = true;
nextTick(() => {
updateRootStyle();
});
const { viewer } = $services;
viewer.scene.postRender.addEventListener(onScenePostRender);
(_b = viewer.viewerWidgetResized) == null ? void 0 : _b.raiseEvent({
type: instance.cesiumClass,
status: "mounted",
target: (_a2 = $(rootRef)) == null ? void 0 : _a2.$el
});
return true;
};
instance.unmount = async () => {
var _a2, _b;
canRender.value = false;
const { viewer } = $services;
viewer.scene.postRender.removeEventListener(onScenePostRender);
(_b = viewer.viewerWidgetResized) == null ? void 0 : _b.raiseEvent({
type: instance.cesiumClass,
status: "unmounted",
target: (_a2 = $(rootRef)) == null ? void 0 : _a2.$el
});
return true;
};
const updateRootStyle = () => {
const css = positionState.style.value;
rootStyle.left = css.left;
rootStyle.top = css.top;
rootStyle.transform = css.transform;
css.background = props.background;
css.color = props.color;
if (typeof props.teleportToViewer === "undefined" || props.teleportToViewer) {
const side = positionState.attach.value;
if ((side.bottom || side.top) && !side.left && !side.right) {
css.left = "50%";
css.transform = "translate(-50%, 0)";
}
if ((side.left || side.right) && !side.top && !side.bottom) {
css.top = "50%";
css.transform = "translate(0, -50%)";
}
}
css.width = `${props.width}px`;
Object.assign(rootStyle, css);
};
const onScenePostRender = throttle((scene) => {
const { Cartesian2, defined, getTimestamp, EllipsoidGeodesic } = Cesium;
const now = getTimestamp();
if (now < lastLegendUpdate + 250) {
return;
}
lastLegendUpdate = now;
const geodesic = new EllipsoidGeodesic();
const width = scene.canvas.clientWidth;
const height = scene.canvas.clientHeight;
const left = scene.camera.getPickRay(new Cartesian2(width / 2 | 0, height - 1));
const right = scene.camera.getPickRay(new Cartesian2(1 + width / 2 | 0, height - 1));
const globe = scene.globe;
const leftPosition = globe.pick(left, scene);
const rightPosition = globe.pick(right, scene);
if (!defined(leftPosition) || !defined(rightPosition)) {
barWidth.value = 0;
distanceLabel.value = "";
return;
}
const leftCartographic = globe.ellipsoid.cartesianToCartographic(leftPosition);
const rightCartographic = globe.ellipsoid.cartesianToCartographic(rightPosition);
geodesic.setEndPoints(leftCartographic, rightCartographic);
const pixelDistance = geodesic.surfaceDistance;
const maxBarWidth = props.width - 10;
let _distance;
for (let i = distances.length - 1; !defined(_distance) && i >= 0; --i) {
if (distances[i] / pixelDistance < maxBarWidth) {
_distance = distances[i];
if (distance !== _distance) {
distance = _distance;
const listener = getInstanceListener(instance, "distanceLegendEvt");
listener && ctx.emit("distanceLegendEvt", {
type: "distanceLegend",
distance,
status: "changed"
});
}
}
}
if (defined(_distance)) {
let label;
if (distance >= 1e3) {
label = (_distance / 1e3).toString() + " km";
} else {
label = _distance.toString() + " m";
}
barWidth.value = _distance / pixelDistance | 0;
distanceLabel.value = label;
} else {
barWidth.value = 0;
distanceLabel.value = "";
}
}, 500);
return () => {
if (canRender.value && distanceLabel.value !== void 0) {
const renderContent = h(
VcBtn,
{
ref: rootRef,
class: `vc-distance-legend ${positionState.classes.value} ${props.customClass}`,
style: rootStyle,
stack: true,
noCaps: true
},
() => [
h("label", null, distanceLabel.value),
h("div", {
style: barStyle.value,
class: "vc-bar"
})
]
);
return !hasVcNavigation && props.teleportToViewer ? h(Teleport, { to: $services.viewer._element }, renderContent) : renderContent;
} else {
return createCommentVNode("v-if");
}
};
}
});
const distances = [
1,
2,
3,
5,
10,
20,
30,
50,
100,
200,
300,
500,
1e3,
2e3,
3e3,
5e3,
1e4,
2e4,
3e4,
5e4,
1e5,
2e5,
3e5,
5e5,
1e6,
2e6,
3e6,
5e6,
1e7,
2e7,
3e7,
5e7
];
const defaultProps$2 = {
...positionProps,
compassOpts: {
// compassOptions
type: [Object, Boolean],
default: () => getDefaultOptionByProps(defaultProps$4, ["position", "offset"])
},
zoomOpts: {
type: [Object, Boolean],
default: () => getDefaultOptionByProps(defaultProps$3, ["position", "offset"])
},
printOpts: {
type: [Object, Boolean],
default: () => getDefaultOptionByProps(printDefaultProps, ["position", "offset"])
},
locationOpts: {
type: [Object, Boolean],
default: () => getDefaultOptionByProps(locationDefaultProps, ["position", "offset"])
},
otherOpts: {
// otherControlOptions
type: [Object, Boolean],
default: () => ({
position: "bottom-right",
offset: [2, 3],
statusBarOpts: getDefaultOptionByProps(statusBarDefaultProps, ["position", "offset"]),
distancelegendOpts: getDefaultOptionByProps(distancelegendDefaultProps, ["position", "offset"])
})
},
customClass: {
type: String,
default: ""
},
teleportToViewer: {
type: Boolean,
default: true
}
};
const defaultOptions$4 = getDefaultOptionByProps(defaultProps$2);
const emits$g = {
...commonEmits,
zoomEvt: (evt) => true,
compassEvt: (evt) => true,
locationEvt: (evt) => true,
printEvt: (evt) => true,
statusBarEvt: (evt) => true,
distanceLegendEvt: (evt) => true
};
const navigationProps = exports('navigationProps', defaultProps$2);
var Navigation = defineComponent({
name: "VcNavigation",
inheritAttrs: false,
props: navigationProps,
emits: emits$g,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VcNavigation";
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const canRender = ref(false);
const { $services } = commonState;
const positionState = usePosition(props);
const positionStateOther = usePosition(props.otherOpts || { position: "bottom-right" });
const rootRef = ref(null);
const secondRootRef = ref(null);
const compassRef = ref(null);
const zoomControlRef = ref(null);
const printRef = ref(null);
const myLocationRef = ref(null);
const statusBarRef = ref(null);
const distanceLegendRef = ref(null);
const rootStyle = reactive({});
const secondRootStyle = reactive({});
const { emit } = ctx;
watch(
() => props,
() => {
nextTick(() => {
var _a, _b, _c, _d, _e, _f;
updateRootStyle();
(_a = $(compassRef)) == null ? void 0 : _a.reload();
(_b = $(zoomControlRef)) == null ? void 0 : _b.reload();
(_c = $(myLocationRef)) == null ? void 0 : _c.reload();
(_d = $(printRef)) == null ? void 0 : _d.reload();
(_e = $(statusBarRef)) == null ? void 0 : _e.reload();
(_f = $(distanceLegendRef)) == null ? void 0 : _f.reload();
});
},
{
deep: true
}
);
const compassOptions = computed(() => Object.assign({}, defaultOptions$4.compassOpts, props.compassOpts));
const zoomControlOptions = computed(() => Object.assign({}, defaultOptions$4.zoomOpts, props.zoomOpts));
const printViewOptions = computed(() => Object.assign({}, defaultOptions$4.printOpts, props.printOpts));
const myLocationOptions = computed(() => Object.assign({}, defaultOptions$4.locationOpts, props.locationOpts));
const otherControlOptions = computed(() => Object.assign({}, defaultOptions$4.otherOpts, props.otherOpts));
const onCompassEvt = (evt) => {
const listener = getInstanceListener(instance, "compassEvt");
listener && emit("compassEvt", evt);
};
const onZoomEvt = (evt) => {
const listener = getInstanceListener(instance, "zoomEvt");
listener && emit("zoomEvt", evt);
};
const onPrintEvt = (evt) => {
const listener = getInstanceListener(instance, "printEvt");
listener && emit("printEvt", evt);
};
const onLocationEvt = (evt) => {
const listener = getInstanceListener(instance, "locationEvt");
listener && emit("locationEvt", evt);
};
const onStatusBarEvt = (evt) => {
const listener = getInstanceListener(instance, "statusBarEvt");
listener && emit("statusBarEvt", evt);
};
const onDistanceLegendEvt = (evt) => {
const listener = getInstanceListener(instance, "distanceLegendEvt");
listener && emit("distanceLegendEvt", evt);
};
instance.createCesiumObject = async () => {
var _a;
const { viewer } = $services;
(_a = viewer.viewerWidgetResized) == null ? void 0 : _a.addEventListener(onViewerWidgetResized);
return [rootRef, secondRootRef];
};
instance.mount = async () => {
var _a;
canRender.value = true;
nextTick(() => {
updateRootStyle();
});
const { viewer } = $services;
(_a = viewer.viewerWidgetResized) == null ? void 0 : _a.raiseEvent({
type: instance.cesiumClass,
status: "mounted",
target: $(rootRef)
});
return true;
};
instance.unmount = async () => {
var _a, _b;
canRender.value = false;
const { viewer } = $services;
(_a = viewer.viewerWidgetResized) == null ? void 0 : _a.removeEventListener(onViewerWidgetResized);
(_b = viewer.viewerWidgetResized) == null ? void 0 : _b.raiseEvent({
type: instance.cesiumClass,
status: "unmounted",
target: $(rootRef)
});
return true;
};
const onViewerWidgetResized = () => {
nextTick(() => {
updateRootStyle();
});
};
const updateRootStyle = () => {
var _a, _b, _c, _d, _e;
const compassTarget = (_a = $(compassRef)) == null ? void 0 : _a.$el;
let height = 0;
let marginX = 0;
if (compassTarget !== void 0 && compassTarget.nodeName !== "#comment") {
const margin = getComputedStyle(compassTarget.parentNode).margin;
marginX = parseInt(margin);
height += compassTarget.getBoundingClientRect().height + marginX * 2;
}
const zoomControlTarget = (_b = $(zoomControlRef)) == null ? void 0 : _b.$el;
if (zoomControlTarget !== void 0 && zoomControlTarget.nodeName !== "#comment") {
height += zoomControlTarget.getBoundingClientRect().height + marginX * 2;
}
const printTarget = (_c = $(printRef)) == null ? void 0 : _c.$el;
if (printTarget !== void 0 && printTarget.nodeName !== "#comment") {
height += printTarget.getBoundingClientRect().height + marginX * 2;
}
const myLocationTarget = (_d = $(myLocationRef)) == null ? void 0 : _d.$el;
if (myLocationTarget !== void 0 && myLocationTarget.nodeName !== "#comment") {
height += myLocationTarget.getBoundingClientRect().height + marginX * 2;
}
const css = positionState.style.value;
const side = positionState.attach.value;
rootStyle.left = css.left;
rootStyle.top = css.top;
rootStyle.transform = css.transform;
if (typeof props.teleportToViewer === "undefined" || props.teleportToViewer) {
if ((side.bottom || side.top) && !side.left && !side.right) {
css.left = "50%";
css.transform = "translate(-50%, 0)";
}
if ((side.left || side.right) && !side.top && !side.bottom) {
css.top = "50%";
css.transform = "translate(0, -50%)";
}
}
Object.assign(rootStyle, css, { height: `${height}px` });
const cssSecondRoot = positionStateOther.style.value;
const sideSecondRoot = positionStateOther.attach.value;
secondRootStyle.left = cssSecondRoot.left;
secondRootStyle.top = cssSecondRoot.top;
secondRootStyle.transform = cssSecondRoot.transform;
if (typeof props.teleportToViewer === "undefined" || props.teleportToViewer) {
if ((sideSecondRoot.bottom || sideSecondRoot.top) && !sideSecondRoot.left && !sideSecondRoot.right) {
cssSecondRoot.left = "50%";
cssSecondRoot.transform = "translate(-50%, 0)";
}
if ((sideSecondRoot.left || sideSecondRoot.right) && !sideSecondRoot.top && !sideSecondRoot.bottom) {
cssSecondRoot.top = "50%";
cssSecondRoot.transform = "translate(0, -50%)";
}
}
let height2 = 0;
const statusBarRefTarget = (_e = $(statusBarRef)) == null ? void 0 : _e.$el;
if (statusBarRefTarget !== void 0 && statusBarRefTarget.nodeName !== "#comment") {
height2 += statusBarRefTarget.getBoundingClientRect().height;
}
Object.assign(secondRootStyle, cssSecondRoot, { height: `${height2}px` });
};
return () => {
if (canRender.value) {
const inner = [];
if (compassOptions.value && props.compassOpts !== false) {
inner.push(
h(
"div",
{
class: "vc-navigation-control"
},
[
h(Compass, {
ref: compassRef,
...compassOptions.value,
onCompassEvt
})
]
)
);
} else {
inner.push(createCommentVNode("v-if"));
}
if (zoomControlOptions.value && props.zoomOpts !== false) {
inner.push(
h(
"div",
{
class: "vc-navigation-control"
},
[
h(ZoomControl, {
ref: zoomControlRef,
...zoomControlOptions.value,
onZoomEvt
})
]
)
);
} else {
inner.push(createCommentVNode("v-if"));
}
if (printViewOptions.value && props.printOpts !== false) {
inner.push(
h(
"div",
{
class: "vc-navigation-control"
},
[
h(Print, {
ref: printRef,
...printViewOptions.value,
onPrintEvt
})
]
)
);
} else {
inner.push(createCommentVNode("v-if"));
}
if (myLocationOptions.value && props.locationOpts !== false) {
inner.push(
h(
"div",
{
class: "vc-navigation-control"
},
[
h(MyLocation, {
ref: myLocationRef,
...myLocationOptions.value,
onLocationEvt
})
]
)
);
} else {
inner.push(createCommentVNode("v-if"));
}
let children = [h("div", { class: "vc-navigation-controls" }, inner)];
children = hMergeSlot(ctx.slots.default, children);
const root = [];
const renderNavigationContent = h(
"div",
{
ref: rootRef,
class: `vc-navigation ${positionState.classes.value} ${props.customClass}`,
style: rootStyle
},
children
);
if (props.teleportToViewer) {
root.push(h(Teleport, { to: $services.viewer._element }, renderNavigationContent));
} else {
root.push(renderNavigationContent);
}
if (props.otherOpts !== false) {
const renderOtherContent = h(
"div",
{
ref: secondRootRef,
class: "vc-location-other-controls " + positionStateOther.classes.value,
style: secondRootStyle
},
[
h(StatusBar, {
ref: statusBarRef,
...otherControlOptions.value.statusBarOpts,
onStatusBarEvt
}),
h(DistanceLegend, {
ref: distanceLegendRef,
...otherControlOptions.value.distancelegendOpts,
onDistanceLegendEvt
})
]
);
if (props.teleportToViewer) {
root.push(h(Teleport, { to: $services.viewer._element }, renderOtherContent));
} else {
root.push(renderOtherContent);
}
}
return root;
} else {
return createCommentVNode("v-if");
}
};
}
});
function useCompass(props, { emit }, vcInstance) {
const vectorScratch = {};
const oldTransformScratch = {};
const newTransformScratch = {};
const centerScratch = {};
let unsubscribeFromPostRender;
let unsubscribeFromClockTick;
let rotateEastMouseUpFunction;
let rotateEastTickFunction;
const heading = ref(0);
let rotateMouseUpFunction;
let rotateMouseMoveFunction;
let rotateInitialCursorAngle = 0;
let rotateFrame = {};
let rotateInitialCameraAngle = 0;
let screenSpaceEventHandler;
let tiltMouseMoveFunction;
let tiltMouseUpFunction;
let tiltFrame = {};
let tiltInitialCursorAngle = 0;
const tiltbarLeft = ref(56);
const tiltbarTop = ref(3);
let clickStartPosition;
const tooltipRef = ref(null);
const handleMouseDown = (e) => {
var _a;
if (e.stopPropagation)
e.stopPropagation();
if (e.preventDefault)
e.preventDefault();
(_a = $(tooltipRef)) == null ? void 0 : _a.hide();
const { Cartesian2, SceneMode, Math: CesiumMath } = Cesium;
const scene = vcInstance.viewer.scene;
if (scene.mode === SceneMode.MORPHING) {
return true;
}
const compassElement = e.currentTarget;
const compassRectangle = e.currentTarget.getBoundingClientRect();
const center = new Cartesian2((compassRectangle.right - compassRectangle.left) / 2, (compassRectangle.bottom - compassRectangle.top) / 2);
let clickLocation;
if (e instanceof MouseEvent) {
clickLocation = new Cartesian2(e.clientX - compassRectangle.left, e.clientY - compassRectangle.top);
clickStartPosition = new Cartesian2(e.clientX, e.clientY);
} else if (e instanceof TouchEvent) {
clickLocation = new Cartesian2(e.changedTouches[0].clientX - compassRectangle.left, e.changedTouches[0].clientY - compassRectangle.top);
clickStartPosition = new Cartesian2(e.changedTouches[0].clientX, e.changedTouches[0].clientY);
}
const vector = Cartesian2.subtract(clickLocation, center, vectorScratch);
const distanceFromCenter = Cartesian2.magnitude(vector);
if (distanceFromCenter > 30 && distanceFromCenter < 45) {
rotate(compassElement, vector);
} else if (!(distanceFromCenter > 50 && distanceFromCenter < 70)) {
rotateEast(compassElement, vector);
} else {
const angle = CesiumMath.PI_OVER_TWO - Math.atan2(-vector.y, vector.x);
angle >= 0 && angle <= CesiumMath.PI_OVER_TWO && tilt(compassElement, vector);
}
};
const handleMouseUp = (event) => {
const { Cartesian2, Math: CesiumMath } = Cesium;
const compassRectangle = event.currentTarget.getBoundingClientRect();
const center = new Cartesian2((compassRectangle.right - compassRectangle.left) / 2, (compassRectangle.bottom - compassRectangle.top) / 2);
const clickLocation = event.type === "mouseup" ? new Cartesian2(event.clientX - compassRectangle.left, event.clientY - compassRectangle.top) : new Cartesian2(event.changedTouches[0].clientX - compassRectangle.left, event.changedTouches[0].clientY - compassRectangle.top);
const vector = Cartesian2.subtract(clickLocation, center, vectorScratch);
const magnitude = Cartesian2.magnitude(vector);
if (magnitude > 30 && magnitude < 45) {
const angle = CesiumMath.toDegrees(Math.atan2(-vector.y, vector.x));
const clickStartPositionUp = event.type === "mouseup" ? new Cartesian2(event.clientX, event.clientY) : new Cartesian2(event.changedTouches[0].clientX, event.changedTouches[0].clientY);
const dX = clickStartPositionUp.x - clickStartPosition.x;
const dY = clickStartPositionUp.y - clickStartPosition.y;
const distance = Math.sqrt(dX * dX + dY * dY);
if (distance > 5) {
return;
}
const headingDegree = CesiumMath.toDegrees(heading.value);
const m = Math.abs(angle - headingDegree);
const scene = vcInstance.viewer.scene;
if (angle > 0 && headingDegree > 0 && headingDegree < 90 && m > 80 && m < 100 || m > 260 && m < 280) {
scene.camera.flyTo({
destination: scene.camera.position,
orientation: {
heading: 0,
pitch: scene.camera.pitch
}
});
}
}
};
const handleDoubleClick = (e) => {
const { Cartesian2, Cartesian3, defined, Matrix4, Ray, SceneMode, Transforms } = Cesium;
const { viewer } = vcInstance;
const scene = viewer.scene;
const camera = scene.camera;
const sscc = scene.screenSpaceCameraController;
if (scene.mode === SceneMode.MORPHING || !sscc.enableInputs) {
return true;
}
if (scene.mode === SceneMode.COLUMBUS_VIEW && !sscc.enableTranslate) {
return;
}
if (scene.mode === SceneMode.SCENE3D || scene.mode === SceneMode.COLUMBUS_VIEW) {
if (!sscc.enableLook) {
return;
}
if (scene.mode === SceneMode.SCENE3D) {
if (!sscc.enableRotate) {
return;
}
}
}
const windowPosition = new Cartesian2();
windowPosition.x = scene.canvas.clientWidth / 2;
windowPosition.y = scene.canvas.clientHeight / 2;
const pickRayScratch = new Ray();
const ray = camera.getPickRay(windowPosition, pickRayScratch);
const center = scene.globe.pick(ray, scene, centerScratch);
if (!defined(center)) {
viewer.camera.flyHome();
return;
}
const listener = getInstanceListener(vcInstance, "compassEvt");
listener && emit("compassEvt", {
type: "reset",
camera: viewer.camera,
status: "start",
target: e.currentTarget
});
const rotateFrame2 = Transforms.eastNorthUpToFixedFrame(center || new Cartesian3(), viewer.scene.globe.ellipsoid);
const lookVector = Cartesian3.subtract(center || new Cartesian3(), camera.position, new Cartesian3());
const flight = CameraFlightPath.createTween(scene, {
destination: Matrix4.multiplyByPoint(rotateFrame2, new Cartesian3(0, 0, Cartesian3.magnitude(lookVector)), new Cartesian3()),
direction: Matrix4.multiplyByPointAsVector(rotateFrame2, new Cartesian3(0, 0, -1), new Cartesian3()),
up: Matrix4.multiplyByPointAsVector(rotateFrame2, new Cartesian3(0, 1, 0), new Cartesian3()),
duration: props.duration,
complete: () => {
listener && emit("compassEvt", {
type: "reset",
camera: viewer.camera,
status: "end",
target: e.currentTarget
});
},
cancel: () => {
listener && emit("compassEvt", {
type: "reset",
camera: viewer.camera,
status: "cancel",
target: e.currentTarget
});
}
});
scene.tweens.add(flight);
};
const viewerChange = () => {
const { defined } = Cesium;
if (defined(vcInstance.viewer)) {
if (unsubscribeFromPostRender) {
unsubscribeFromPostRender();
unsubscribeFromPostRender = void 0;
}
unsubscribeFromPostRender = vcInstance.viewer.scene.postRender.addEventListener(function() {
if (heading.value !== vcInstance.viewer.scene.camera.heading) {
heading.value = vcInstance.viewer.scene.camera.heading;
}
});
} else {
if (unsubscribeFromPostRender) {
unsubscribeFromPostRender();
unsubscribeFromPostRender = void 0;
}
}
};
const rotateEast = (compassElement, cursorVector) => {
const { defined, getTimestamp, SceneMode, Math: CesiumMath, ScreenSpaceEventType } = Cesium;
const scene = vcInstance.viewer.scene;
const sscc = scene.screenSpaceCameraController;
if (scene.mode === SceneMode.MORPHING || !sscc.enableInputs) {
return;
}
switch (scene.mode) {
case SceneMode.COLUMBUS_VIEW:
if (sscc.enableLook) {
break;
}
if (!sscc.enableTranslate || !sscc.enableTilt) {
return;
}
break;
case SceneMode.SCENE3D:
if (sscc.enableLook) {
break;
}
if (!sscc.enableTilt || !sscc.enableRotate) {
return;
}
break;
case Cesium.SceneMode.SCENE2D:
if (!sscc.enableTranslate) {
return;
}
break;
}
screenSpaceEventHandler.removeInputAction(ScreenSpaceEventType.LEFT_UP);
if (defined(rotateEastTickFunction)) {
vcInstance.viewer.clock.onTick.removeEventListener(rotateEastTickFunction);
}
rotateEastMouseUpFunction = void 0;
rotateEastTickFunction = void 0;
getTimestamp();
let angle = CesiumMath.PI_OVER_TWO - Math.atan2(-cursorVector.y, cursorVector.x);
const quarterPI = Math.PI / 4;
let roateDirection = 0;
const roateType = {
LEFT: 1,
RIGHT: 2,
UP: 3,
DOWN: 4
};
roateDirection = angle >= -quarterPI && quarterPI >= angle ? roateType.DOWN : angle >= quarterPI && 3 * quarterPI >= angle ? roateType.RIGHT : angle >= 3 * quarterPI && 5 * quarterPI >= angle ? roateType.UP : roateType.LEFT;
const listener = getInstanceListener(vcInstance, "compassEvt");
let type = `rotateEast`;
switch (roateDirection) {
case roateType.LEFT:
type = "rotateWest";
break;
case roateType.RIGHT:
type = "rotateEast";
break;
case roateType.UP:
type = "rotateNorth";
break;
case roateType.DOWN:
type = "rotateSouth";
}
listener && emit("compassEvt", {
type,
camera: scene.camera,
status: "start",
target: compassElement
});
rotateEastTickFunction = function(e) {
const scene2 = vcInstance.viewer.scene;
const camera = scene2.camera;
getTimestamp();
angle = 20 * Math.abs(camera.positionCartographic.height / 6378317) * 5e-4;
switch (roateDirection) {
case roateType.LEFT:
camera.rotateLeft(angle);
break;
case roateType.RIGHT:
camera.rotateRight(angle);
break;
case roateType.UP:
camera.rotate(camera.right, -angle);
break;
case roateType.DOWN:
camera.rotate(camera.right, angle);
}
listener && emit("compassEvt", {
type,
camera: scene2.camera,
status: "changing",
target: compassElement
});
};
rotateEastMouseUpFunction = function(e) {
screenSpaceEventHandler.removeInputAction(ScreenSpaceEventType.LEFT_UP);
defined(rotateEastTickFunction) && vcInstance.viewer.clock.onTick.removeEventListener(rotateEastTickFunction);
rotateEastMouseUpFunction = void 0;
rotateEastTickFunction = void 0;
listener && emit("compassEvt", {
type,
camera: scene.camera,
status: "end",
target: compassElement
});
};
screenSpaceEventHandler.setInputAction(rotateEastMouseUpFunction, ScreenSpaceEventType.LEFT_UP);
unsubscribeFromClockTick = vcInstance.viewer.clock.onTick.addEventListener(rotateEastTickFunction);
};
const rotate = (compassElement, cursorVector) => {
if (!props.enableCompassOuterRing) {
return;
}
const scene = vcInstance.viewer.scene;
let camera = scene.camera;
const sscc = scene.screenSpaceCameraController;
if (scene.mode === Cesium.SceneMode.MORPHING || scene.mode === Cesium.SceneMode.SCENE2D || !sscc.enableInputs) {
return;
}
if (!sscc.enableLook && (scene.mode === Cesium.SceneMode.COLUMBUS_VIEW || scene.mode === Cesium.SceneMode.SCENE3D && !sscc.enableRotate)) {
return;
}
document.removeEventListener("mousemove", rotateMouseMoveFunction, false);
document.removeEventListener("touchmove", rotateMouseMoveFunction, false);
document.removeEventListener("mouseup", rotateMouseUpFunction, false);
document.removeEventListener("touchend", rotateMouseUpFunction, false);
const { Cartesian2, Cartesian3, defined, Math: CesiumMath, Matrix4, Ray, Transforms } = Cesium;
rotateMouseMoveFunction = void 0;
rotateMouseUpFunction = void 0;
const listener = getInstanceListener(vcInstance, "compassEvt");
listener && emit("compassEvt", {
type: "rotate",
camera: scene.camera,
status: "start",
target: compassElement
});
rotateInitialCursorAngle = Math.atan2(-cursorVector.y, cursorVector.x);
const windowPosition = new Cartesian2();
windowPosition.x = scene.canvas.clientWidth / 2;
windowPosition.y = scene.canvas.clientHeight / 2;
const pickRayScratch = new Ray();
const ray = camera.getPickRay(windowPosition, pickRayScratch);
const viewCenter = scene.globe.pick(ray, scene, centerScratch);
if (!defined(viewCenter)) {
rotateFrame = Transforms.eastNorthUpToFixedFrame(camera.positionWC, scene.globe.ellipsoid, newTransformScratch);
} else {
rotateFrame = Transforms.eastNorthUpToFixedFrame(viewCenter || new Cartesian3(), scene.globe.ellipsoid, newTransformScratch);
}
let oldTransform = Matrix4.clone(camera.transform, oldTransformScratch);
camera.lookAtTransform(rotateFrame);
rotateInitialCameraAngle = Math.atan2(camera.position.y, camera.position.x);
Cartesian3.magnitude(new Cartesian3(camera.position.x, camera.position.y, 0));
camera.lookAtTransform(oldTransform);
rotateMouseMoveFunction = function(e) {
const compassRectangle = compassElement.getBoundingClientRect();
const center = new Cartesian2((compassRectangle.right - compassRectangle.left) / 2, (compassRectangle.bottom - compassRectangle.top) / 2);
let clickLocation;
if (e instanceof MouseEvent) {
clickLocation = new Cartesian2(e.clientX - compassRectangle.left, e.clientY - compassRectangle.top);
} else if (e instanceof TouchEvent) {
clickLocation = new Cartesian2(e.changedTouches[0].clientX - compassRectangle.left, e.changedTouches[0].clientY - compassRectangle.top);
}
const vector = Cartesian2.subtract(clickLocation, center, vectorScratch);
const angle = Math.atan2(-vector.y, vector.x);
const angleDifference = angle - rotateInitialCursorAngle;
const newCameraAngle = CesiumMath.zeroToTwoPi(rotateInitialCameraAngle - angleDifference);
camera = vcInstance.viewer.scene.camera;
oldTransform = Matrix4.clone(camera.transform, oldTransformScratch);
camera.lookAtTransform(rotateFrame);
const currentCameraAngle = Math.atan2(camera.position.y, camera.position.x);
camera.rotateRight(newCameraAngle - currentCameraAngle);
camera.lookAtTransform(oldTransform);
listener && emit("compassEvt", {
type: "rotate",
camera: scene.camera,
status: "changing",
target: compassElement
});
};
rotateMouseUpFunction = function(e) {
document.removeEventListener("mousemove", rotateMouseMoveFunction, false);
document.removeEventListener("touchmove", rotateMouseMoveFunction, false);
document.removeEventListener("mouseup", rotateMouseUpFunction, false);
document.removeEventListener("touchend", rotateMouseUpFunction, false);
rotateMouseMoveFunction = void 0;
rotateMouseUpFunction = void 0;
listener && emit("compassEvt", {
type: "rotate",
camera: scene.camera,
status: "end",
target: compassElement
});
};
document.addEventListener("mousemove", rotateMouseMoveFunction, false);
document.addEventListener("touchmove", rotateMouseMoveFunction, false);
document.addEventListener("mouseup", rotateMouseUpFunction, false);
document.addEventListener("touchend", rotateMouseUpFunction, false);
};
const tilt = (compassElement, cursorVector) => {
const { Cartesian2, defined, Math: CesiumMath, Matrix4, ScreenSpaceEventType, Transforms } = Cesium;
screenSpaceEventHandler.removeInputAction(ScreenSpaceEventType.MOUSE_MOVE);
screenSpaceEventHandler.removeInputAction(ScreenSpaceEventType.LEFT_UP);
tiltMouseMoveFunction = void 0;
tiltMouseUpFunction = void 0;
tiltInitialCursorAngle = CesiumMath.PI_OVER_TWO - Math.atan2(-cursorVector.y, cursorVector.x);
tiltInitialCursorAngle = tiltInitialCursorAngle < 0 ? 0 : tiltInitialCursorAngle;
tiltInitialCursorAngle = tiltInitialCursorAngle > CesiumMath.PI_OVER_TWO ? CesiumMath.PI_OVER_TWO : tiltInitialCursorAngle;
const scene = vcInstance.viewer.scene;
const camera = scene.camera;
const windowPosition = new Cartesian2();
windowPosition.x = scene.canvas.clientWidth / 2;
windowPosition.y = scene.canvas.clientHeight / 2;
let pickPosition = camera.pickEllipsoid(windowPosition, scene.globe.ellipsoid);
if (!defined(pickPosition)) {
for (; windowPosition.y < scene.canvas.clientHeight; ) {
windowPosition.y += 5;
pickPosition = camera.pickEllipsoid(windowPosition, scene.globe.ellipsoid);
}
}
const listener = getInstanceListener(vcInstance, "compassEvt");
listener && emit("compassEvt", {
type: "tilt",
camera: scene.camera,
status: "start",
target: compassElement
});
isObject(pickPosition) && defined(pickPosition) && (tiltFrame = Transforms.eastNorthUpToFixedFrame(pickPosition, scene.globe.ellipsoid));
tiltMouseMoveFunction = (e) => {
const compassRectangle = compassElement.getBoundingClientRect();
const center = new Cesium.Cartesian2(
(compassRectangle.right - compassRectangle.left) / 2,
(compassRectangle.bottom - compassRectangle.top) / 2
);
const endPosition = Cartesian2.clone(e.endPosition);
const vector = Cartesian2.subtract(endPosition, center, vectorScratch);
let angle = CesiumMath.PI_OVER_TWO - Math.atan2(-vector.y, vector.x);
angle = angle < 0 ? 0 : angle;
angle = angle > CesiumMath.PI_OVER_TWO ? CesiumMath.PI_OVER_TWO : angle;
const camera2 = vcInstance.viewer.scene.camera;
const oldTransform = Matrix4.clone(camera2.transform, oldTransformScratch);
camera2.lookAtTransform(tiltFrame);
const rotateUpAngle = angle - tiltInitialCursorAngle;
camera2.rotateUp(rotateUpAngle);
tiltInitialCursorAngle = angle;
camera2.lookAtTransform(oldTransform);
let level = Math.ceil(angle / (Math.PI / 40));
level = level > 19 ? 19 : level;
const position = getPoints()[level];
tiltbarLeft.value = position.x;
tiltbarTop.value = position.y;
listener && emit("compassEvt", {
type: "tilt",
camera: scene.camera,
status: "changing",
target: compassElement
});
};
tiltMouseUpFunction = function(e) {
screenSpaceEventHandler.removeInputAction(ScreenSpaceEventType.MOUSE_MOVE);
screenSpaceEventHandler.removeInputAction(ScreenSpaceEventType.LEFT_UP);
tiltMouseMoveFunction = void 0;
tiltMouseUpFunction = void 0;
listener && emit("compassEvt", {
type: "tilt",
camera: scene.camera,
status: "end",
target: compassElement
});
};
screenSpaceEventHandler.setInputAction(tiltMouseMoveFunction, ScreenSpaceEventType.MOUSE_MOVE);
screenSpaceEventHandler.setInputAction(tiltMouseUpFunction, ScreenSpaceEventType.LEFT_UP);
};
const onTooltipBeforeShow = (e) => {
if (rotateMouseMoveFunction !== void 0) {
e.cancel = true;
}
};
const getTiltbarPosition = () => {
const { Math: CesiumMath } = Cesium;
const pitch = CesiumMath.PI_OVER_TWO + vcInstance.viewer.scene.camera.pitch;
const length = Math.PI / 2 / 20;
let level = Math.floor(pitch / length);
level = level > 19 ? 19 : level;
level = level < 0 ? 0 : level;
tiltbarLeft.value = getPoints()[level].x;
tiltbarTop.value = getPoints()[level].y;
};
const load = async (viewer, el) => {
vcInstance.viewer = viewer;
heading.value = viewer.scene.camera.heading;
viewerChange();
screenSpaceEventHandler = new Cesium.ScreenSpaceEventHandler(el);
getTiltbarPosition();
return true;
};
const unload = async () => {
document.removeEventListener("mousemove", rotateMouseMoveFunction, false);
document.removeEventListener("touchmove", rotateMouseMoveFunction, false);
document.removeEventListener("mouseup", rotateMouseUpFunction, false);
document.removeEventListener("touchend", rotateMouseUpFunction, false);
unsubscribeFromClockTick && unsubscribeFromClockTick();
unsubscribeFromPostRender && unsubscribeFromPostRender();
screenSpaceEventHandler == null ? void 0 : screenSpaceEventHandler.destroy();
return true;
};
return {
heading,
handleDoubleClick,
handleMouseDown,
handleMouseUp,
onTooltipBeforeShow,
viewerChange,
load,
unload,
tiltbarLeft,
tiltbarTop,
tooltipRef
};
}
function getPoints() {
return [
{
x: 56,
y: 3
},
{
x: 59,
y: 4
},
{
x: 64,
y: 5
},
{
x: 69,
y: 6
},
{
x: 74,
y: 7
},
{
x: 79,
y: 9
},
{
x: 84,
y: 12
},
{
x: 89,
y: 15
},
{
x: 92,
y: 19
},
{
x: 94,
y: 20
},
{
x: 99,
y: 25
},
{
x: 104,
y: 34
},
{
x: 106,
y: 40
},
{
x: 107,
y: 44
},
{
x: 107,
y: 46
},
{
x: 107,
y: 48
},
{
x: 107,
y: 50
},
{
x: 107,
y: 52
},
{
x: 107,
y: 54
},
{
x: 107,
y: 56
}
];
}
const compassSmProps = exports('compassSmProps', {
enableCompassOuterRing: {
type: Boolean,
default: true
},
duration: {
type: Number,
default: 1.5
},
tooltip: {
type: [Boolean, Object],
default: () => ({
delay: 500,
anchor: "bottom middle",
offset: [0, 20],
tip: void 0
})
},
autoHidden: {
type: Boolean,
default: true
},
...positionProps
});
const emits$f = {
...commonEmits,
compassEvt: (evt) => true
};
var CompassSm = defineComponent({
name: "VcCompassSm",
props: compassSmProps,
emits: emits$f,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "VcCompassSm";
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { t } = useLocale();
const parentInstance = getVcParentInstance(instance);
const { $services } = commonState;
const compassState = useCompass(props, ctx, instance);
const positionState = usePosition(props);
const rootRef = ref(null);
const outerRingRef = ref(null);
const hasVcNavigation = ((_a = parentInstance.proxy) == null ? void 0 : _a.$options.name) === "VcNavigationSm";
const canRender = ref(hasVcNavigation);
const rootStyle = reactive({});
watch(
() => props,
(val) => {
nextTick(() => {
if (!instance.mounted) {
return;
}
updateRootStyle();
});
},
{
deep: true
}
);
const tiltbarStyle = computed(() => {
return {
left: compassState.tiltbarLeft.value + "px",
top: compassState.tiltbarTop.value + "px",
visibility: props.autoHidden ? "hidden" : "visible"
};
});
const visibilityStyle = computed(() => {
return {
visibility: props.autoHidden ? "hidden" : "visible"
};
});
const outerRingStyle = computed(() => {
return {
transform: "rotate(-" + compassState.heading.value + "rad)",
WebkitTransform: "rotate(-" + compassState.heading.value + "rad)"
};
});
instance.createCesiumObject = async () => {
canRender.value = true;
const { viewer } = $services;
return new Promise((resolve, reject) => {
nextTick(() => {
if (!hasVcNavigation) {
const viewerElement = viewer._element;
viewerElement.appendChild($(rootRef));
resolve($(rootRef));
} else {
resolve($(rootRef));
}
});
});
};
instance.mount = async () => {
var _a2;
updateRootStyle();
const { viewer } = $services;
(_a2 = viewer.viewerWidgetResized) == null ? void 0 : _a2.raiseEvent({
type: instance.cesiumClass,
status: "mounted",
target: $(rootRef)
});
return compassState.load($services.viewer, $(rootRef));
};
instance.unmount = async () => {
var _a2;
const { viewer } = $services;
const viewerElement = viewer._element;
if (!hasVcNavigation) {
viewerElement.contains($(rootRef)) && viewerElement.removeChild($(rootRef));
}
(_a2 = viewer.viewerWidgetResized) == null ? void 0 : _a2.raiseEvent({
type: instance.cesiumClass,
status: "unmounted",
target: $(rootRef)
});
return compassState.unload();
};
const updateRootStyle = () => {
const css = positionState.style.value;
rootStyle.left = css.left;
rootStyle.top = css.top;
rootStyle.transform = css.transform;
const side = positionState.attach.value;
const outerRingTarget = $(outerRingRef);
if (outerRingTarget !== void 0) {
const clientRect = outerRingTarget == null ? void 0 : outerRingTarget.getBoundingClientRect();
css.width = `${clientRect == null ? void 0 : clientRect.width}px`;
css.height = `${clientRect == null ? void 0 : clientRect.height}px`;
if ((side.bottom || side.top) && !side.left && !side.right) {
css.left = "50%";
css.transform = "translate(-50%, 0)";
}
if ((side.left || side.right) && !side.top && !side.bottom) {
css.top = "50%";
css.transform = "translate(0, -50%)";
}
}
Object.assign(rootStyle, css);
};
return () => {
if (canRender.value) {
let children = [];
children = hMergeSlot(ctx.slots.default, children);
children.push(
h("div", {
class: "vc-compass-tilt-sm",
style: visibilityStyle.value
})
);
children.push(
h("div", {
class: "vc-compass-tiltbar-sm",
style: tiltbarStyle.value
})
);
children.push(
h("div", {
class: "vc-compass-arrows-sm",
style: visibilityStyle.value
})
);
children.push(
h(
"div",
{
ref: outerRingRef,
class: "vc-compass-outer-ring-sm",
style: outerRingStyle.value
},
props.tooltip ? h(
VcTooltip,
{
ref: compassState.tooltipRef,
...props.tooltip,
onBeforeShow: compassState.onTooltipBeforeShow
},
() => h("strong", {}, props.tooltip.tip || t("vc.navigationSm.compass.outerTip"))
) : createCommentVNode("v-if")
)
);
children.push(
h("div", {
class: "vc-arrows-e-sm",
style: visibilityStyle.value
})
);
children.push(
h("div", {
class: "vc-arrows-n-sm",
style: visibilityStyle.value
})
);
children.push(
h("div", {
class: "vc-arrows-s-sm",
style: visibilityStyle.value
})
);
children.push(
h("div", {
class: "vc-arrows-w-sm",
style: visibilityStyle.value
})
);
return h(
"div",
{
ref: rootRef,
class: "vc-compass-sm " + positionState.classes.value,
style: rootStyle,
onDblclick: compassState.handleDoubleClick,
onMousedown: compassState.handleMouseDown,
onMouseup: compassState.handleMouseUp,
onTouchend: compassState.handleMouseUp,
onTouchstart: compassState.handleMouseDown
},
children
);
} else {
return createCommentVNode("v-if");
}
};
}
});
function useZoomControl(props, { emit }, vcInstance, $services) {
const zoombarTop = ref(65);
const zoomInTooltipRef = ref(null);
const zoomOutTooltipRef = ref(null);
const zoomBarTooltipRef = ref(null);
let screenSpaceEventHandler;
let zoominTickFunction;
let zoominMouseUpFunction;
let unsubscribeFromClockTickZoomin;
let zoomoutTickFunction;
let zoomoutMouseUpFunction;
let unsubscribeFromClockTickZoomout;
let zoomBarScrollMouseMoveFunction;
let zoomBarScrollMouseUpFunction;
let zoombarTickFunction;
let unsubscribeFromClockTickZoomBar;
let container;
const handleZoomInMouseDown = (e) => {
var _a, _b, _c;
const { defined, getTimestamp, SceneMode, ScreenSpaceEventType } = Cesium;
const { viewer } = $services;
(_a = $(zoomInTooltipRef)) == null ? void 0 : _a.hide();
(_b = $(zoomOutTooltipRef)) == null ? void 0 : _b.hide();
(_c = $(zoomBarTooltipRef)) == null ? void 0 : _c.hide();
screenSpaceEventHandler.removeInputAction(ScreenSpaceEventType.LEFT_UP);
defined(zoominTickFunction) && viewer.clock.onTick.removeEventListener(zoominTickFunction);
zoominMouseUpFunction = void 0;
zoominTickFunction = void 0;
getTimestamp();
const scene = viewer.scene;
const camera = scene.camera;
zoominTickFunction = () => {
viewer.scene.mode === SceneMode.COLUMBUS_VIEW || viewer.scene.mode === SceneMode.SCENE2D ? camera.zoomIn() : handlezoom(1);
};
zoominMouseUpFunction = () => {
screenSpaceEventHandler.removeInputAction(ScreenSpaceEventType.LEFT_UP);
defined(zoominTickFunction) && viewer.clock.onTick.removeEventListener(zoominTickFunction);
zoominMouseUpFunction = void 0;
zoominTickFunction = void 0;
};
screenSpaceEventHandler.setInputAction(zoominMouseUpFunction, ScreenSpaceEventType.LEFT_UP);
unsubscribeFromClockTickZoomin = viewer.clock.onTick.addEventListener(zoominTickFunction);
};
const handleZoomOutMouseDown = (event) => {
var _a, _b, _c;
(_a = $(zoomInTooltipRef)) == null ? void 0 : _a.hide();
(_b = $(zoomOutTooltipRef)) == null ? void 0 : _b.hide();
(_c = $(zoomBarTooltipRef)) == null ? void 0 : _c.hide();
const { defined, getTimestamp, SceneMode, ScreenSpaceEventType } = Cesium;
const { viewer } = $services;
screenSpaceEventHandler.removeInputAction(ScreenSpaceEventType.LEFT_UP);
defined(zoomoutTickFunction) && viewer.clock.onTick.removeEventListener(zoomoutTickFunction);
zoomoutMouseUpFunction = void 0;
zoomoutTickFunction = void 0;
getTimestamp();
const scene = viewer.scene;
const camera = scene.camera;
zoomoutTickFunction = () => {
viewer.scene.mode === SceneMode.COLUMBUS_VIEW || viewer.scene.mode === SceneMode.SCENE2D ? camera.zoomOut() : handlezoom(-1);
};
zoomoutMouseUpFunction = () => {
screenSpaceEventHandler.removeInputAction(ScreenSpaceEventType.LEFT_UP);
defined(zoomoutTickFunction) && viewer.clock.onTick.removeEventListener(zoomoutTickFunction);
zoomoutMouseUpFunction = void 0;
zoomoutTickFunction = void 0;
};
screenSpaceEventHandler.setInputAction(zoomoutMouseUpFunction, ScreenSpaceEventType.LEFT_UP);
unsubscribeFromClockTickZoomout = viewer.clock.onTick.addEventListener(zoomoutTickFunction);
};
const handleZoomBarScrollMouseDown = (event) => {
var _a, _b, _c;
(_a = $(zoomInTooltipRef)) == null ? void 0 : _a.hide();
(_b = $(zoomOutTooltipRef)) == null ? void 0 : _b.hide();
(_c = $(zoomBarTooltipRef)) == null ? void 0 : _c.hide();
const { Cartesian2, defined, SceneMode } = Cesium;
const { viewer } = $services;
document.removeEventListener("mousemove", zoomBarScrollMouseMoveFunction, false);
document.removeEventListener("touchmove", zoomBarScrollMouseMoveFunction, false);
document.removeEventListener("mouseup", zoomBarScrollMouseUpFunction, false);
document.removeEventListener("touchend", zoomBarScrollMouseUpFunction, false);
defined(zoombarTickFunction) && viewer.clock.onTick.removeEventListener(zoombarTickFunction);
zoomBarScrollMouseUpFunction = void 0;
zoombarTickFunction = void 0;
const scene = viewer.scene;
const camera = scene.camera;
zoombarTickFunction = () => {
const zoomOffset = zoombarTop.value - 65;
if (zoomOffset > 0) {
if (viewer.scene.mode === SceneMode.COLUMBUS_VIEW || viewer.scene.mode === SceneMode.SCENE2D) {
camera.zoomOut();
} else {
handlezoom(-1);
}
} else if (zoomOffset < 0) {
if (viewer.scene.mode === SceneMode.COLUMBUS_VIEW || viewer.scene.mode === SceneMode.SCENE2D) {
camera.zoomIn();
} else {
handlezoom(1);
}
}
};
zoomBarScrollMouseMoveFunction = (e) => {
const zoombarTopMove = zoombarTop.value;
const clientRect = e.target.parentElement.getBoundingClientRect();
const rectNavigation = container.getBoundingClientRect();
const endPosition = new Cesium.Cartesian2();
endPosition.x = e.type === "touchmove" ? e.changedTouches[0].clientX - rectNavigation.left : e.clientX - rectNavigation.left;
endPosition.y = e.type === "touchmove" ? e.changedTouches[0].clientY - rectNavigation.top : e.clientY - rectNavigation.top;
const padding = new Cartesian2(clientRect.width - endPosition.x, clientRect.height - endPosition.y);
let offset = padding.y - 16;
offset = offset < 0 ? 0 : offset;
offset = offset > 120 ? 120 : offset;
zoombarTop.value = 120 - offset;
const zoomFlag = zoombarTop.value - zoombarTopMove;
if (zoomFlag > 0) {
if (viewer.scene.mode === SceneMode.COLUMBUS_VIEW || viewer.scene.mode === SceneMode.SCENE2D) {
camera.zoomOut();
} else {
handlezoom(-1);
}
} else {
if (viewer.scene.mode === SceneMode.COLUMBUS_VIEW || viewer.scene.mode === SceneMode.SCENE2D) {
camera.zoomIn();
} else {
handlezoom(1);
}
}
};
zoomBarScrollMouseUpFunction = () => {
document.removeEventListener("mousemove", zoomBarScrollMouseMoveFunction, false);
document.removeEventListener("touchmove", zoomBarScrollMouseMoveFunction, false);
document.removeEventListener("mouseup", zoomBarScrollMouseUpFunction, false);
document.removeEventListener("touchend", zoomBarScrollMouseUpFunction, false);
defined(zoombarTickFunction) && viewer.clock.onTick.removeEventListener(zoombarTickFunction);
zoomBarScrollMouseUpFunction = void 0;
zoomBarScrollMouseMoveFunction = void 0;
zoombarTickFunction = void 0;
zoombarTop.value = 65;
};
document.addEventListener("mousemove", zoomBarScrollMouseMoveFunction, false);
document.addEventListener("touchmove", zoomBarScrollMouseMoveFunction, false);
document.addEventListener("mouseup", zoomBarScrollMouseUpFunction, false);
document.addEventListener("touchend", zoomBarScrollMouseUpFunction, false);
unsubscribeFromClockTickZoomBar = viewer.clock.onTick.addEventListener(zoombarTickFunction);
};
const handlezoom = (i) => {
const { Cartesian2, Cartesian3, defined, Ellipsoid, Math } = Cesium;
const { viewer } = $services;
const scene = viewer.scene;
const camera = scene.camera;
const canvas = scene.canvas;
const centerPixel = new Cartesian2();
centerPixel.x = canvas.clientWidth / 2;
centerPixel.y = canvas.clientHeight / 2;
const centerPosition = pickGlobe(centerPixel);
if (defined(centerPosition)) {
const distance = Cartesian3.distance(camera.position, centerPosition);
let factor = 0.0618 * i * 0.2;
factor = distance > 300 ? factor : 2 * factor;
const amount = distance * factor;
const direction = new Cartesian3();
Cartesian3.subtract(centerPosition, camera.position, direction);
const cameraRight = Cartesian3.clone(camera.right);
const dot = Cartesian3.dot(direction, cameraRight);
const movementVector = new Cartesian3();
Cartesian3.multiplyByScalar(cameraRight, dot, movementVector);
Cartesian3.subtract(direction, movementVector, direction);
Cartesian3.normalize(direction, direction);
camera.move(direction, amount);
const centerPositionNormal = new Cartesian3();
Cartesian3.normalize(centerPosition, centerPositionNormal);
const pickPosition = camera.pickEllipsoid(centerPixel, viewer.scene.globe.ellipsoid);
if (isObject(pickPosition) && defined(pickPosition) && !isNaN(pickPosition.x) && !isNaN(pickPosition.y) && !isNaN(pickPosition.z) && !(camera.positionCartographic.height < 0)) {
Cartesian3.normalize(pickPosition, pickPosition);
const angle = Cartesian3.angleBetween(centerPositionNormal, pickPosition);
if (!Math.equalsEpsilon(angle, 0, Math.EPSILON10)) {
const axis = Cartesian3.cross(centerPositionNormal, pickPosition, new Cartesian3());
camera.rotate(axis, angle);
const listener = getInstanceListener(vcInstance, "zoomEvt");
listener && emit("zoomEvt", {
type: i === 1 ? "zoomIn" : "zoomOut",
camera: viewer.camera,
status: "end"
});
}
}
}
};
const pickGlobe = (mousePosition) => {
const { defined, Cartesian3 } = Cesium;
const { viewer } = $services;
const scene = viewer.scene;
const globe = scene.globe;
const camera = scene.camera;
if (defined(globe)) {
let depthIntersection;
if (scene.pickPositionSupported) {
depthIntersection = scene.pickPositionWorldCoordinates(mousePosition);
}
const ray = camera.getPickRay(mousePosition);
const rayIntersection = globe.pick(ray, scene);
const pickDistance = defined(depthIntersection) ? Cartesian3.distance(depthIntersection, camera.positionWC) : Number.POSITIVE_INFINITY;
const rayDistance = isObject(rayIntersection) && defined(rayIntersection) ? Cartesian3.distance(rayIntersection, camera.positionWC) : Number.POSITIVE_INFINITY;
return rayDistance > pickDistance ? depthIntersection : rayIntersection;
}
};
const onTooltipBeforeShow = (e) => {
if (zoomBarScrollMouseMoveFunction !== void 0 || zoominTickFunction !== void 0 || zoomoutTickFunction !== void 0) {
e.cancel = true;
}
};
const load = (el) => {
container = el;
screenSpaceEventHandler = new Cesium.ScreenSpaceEventHandler(el);
return true;
};
const unload = () => {
document.removeEventListener("mousemove", zoomBarScrollMouseMoveFunction, false);
document.removeEventListener("touchmove", zoomBarScrollMouseMoveFunction, false);
document.removeEventListener("mouseup", zoomBarScrollMouseUpFunction, false);
document.removeEventListener("touchend", zoomBarScrollMouseUpFunction, false);
unsubscribeFromClockTickZoomin == null ? void 0 : unsubscribeFromClockTickZoomin();
unsubscribeFromClockTickZoomout == null ? void 0 : unsubscribeFromClockTickZoomout();
unsubscribeFromClockTickZoomBar == null ? void 0 : unsubscribeFromClockTickZoomBar();
screenSpaceEventHandler == null ? void 0 : screenSpaceEventHandler.destroy();
return true;
};
return {
handleZoomInMouseDown,
handleZoomOutMouseDown,
handleZoomBarScrollMouseDown,
load,
unload,
zoombarTop,
zoomInTooltipRef,
zoomOutTooltipRef,
zoomBarTooltipRef,
onTooltipBeforeShow
};
}
const zoomControlSmProps = exports('zoomControlSmProps', {
...positionProps,
autoHidden: {
type: Boolean,
default: false
},
tooltip: {
type: Object,
default: () => ({
delay: 1e3,
anchor: "bottom middle",
offset: [0, 20],
zoomInTip: void 0,
zoomOutTip: void 0,
zoomBarTip: void 0
})
}
});
const emits$e = {
...commonEmits,
zoomEvt: (evt) => true
};
var ZoomControlSm = defineComponent({
name: "VcZoomControlSm",
props: zoomControlSmProps,
emits: emits$e,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "VcZoomControlSm";
instance.cesiumEvents = [];
const rootRef = ref();
const zoomInRef = ref();
const zoomBarRef = ref();
const zoomOutRef = ref();
const parentInstance = getVcParentInstance(instance);
const hasVcNavigation = ((_a = parentInstance.proxy) == null ? void 0 : _a.$options.name) === "VcNavigationSm";
const canRender = ref(hasVcNavigation);
const rootStyle = reactive({});
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { t } = useLocale();
const { $services } = commonState;
const positionState = usePosition(props);
const zoomControlState = useZoomControl(props, ctx, instance, $services);
watch(
() => props,
(val) => {
nextTick(() => {
if (!instance.mounted) {
return;
}
updateRootStyle();
});
},
{
deep: true
}
);
const zoombarStyle = computed(() => ({ top: zoomControlState.zoombarTop.value + "px" }));
instance.createCesiumObject = async () => {
return new Promise((resolve, reject) => {
canRender.value = true;
nextTick(() => {
const rootEl = $(rootRef);
const { viewer } = $services;
if (!hasVcNavigation) {
const viewerElement = viewer._element;
isObject(rootEl) && (viewerElement == null ? void 0 : viewerElement.appendChild(rootEl));
resolve(rootEl);
} else {
resolve(rootEl);
}
});
});
};
instance.mount = async () => {
var _a2;
updateRootStyle();
const { viewer } = $services;
(_a2 = viewer.viewerWidgetResized) == null ? void 0 : _a2.raiseEvent({
type: instance.cesiumClass,
status: "mounted",
target: $(rootRef)
});
return zoomControlState.load($(rootRef));
};
instance.unmount = async () => {
var _a2;
const { viewer } = $services;
if (!hasVcNavigation) {
const viewerElement = viewer._element;
const rootEl = $(rootRef);
isObject(rootEl) && (viewerElement == null ? void 0 : viewerElement.contains(rootEl)) && viewerElement.removeChild(rootEl);
}
(_a2 = viewer.viewerWidgetResized) == null ? void 0 : _a2.raiseEvent({
type: instance.cesiumClass,
status: "unmounted",
target: $(rootRef)
});
return zoomControlState.unload();
};
const updateRootStyle = () => {
const css = positionState.style.value;
rootStyle.left = css.left;
rootStyle.top = css.top;
rootStyle.transform = css.transform;
rootStyle.visibility = props.autoHidden ? "hidden" : "visible";
if (!hasVcNavigation) {
const side = positionState.attach.value;
if ((side.bottom || side.top) && !side.left && !side.right) {
css.left = "50%";
css.transform = "translate(-50%, 0)";
}
if ((side.left || side.right) && !side.top && !side.bottom) {
css.top = "50%";
css.transform = "translate(0, -50%)";
}
}
Object.assign(rootStyle, css);
};
return () => {
if (canRender.value) {
let children = [];
children = hMergeSlot(ctx.slots.default, children);
children.push(
h(
"div",
{
ref: zoomInRef,
class: "vc-zoomin-sm",
onMousedown: zoomControlState.handleZoomInMouseDown,
onTouchstart: zoomControlState.handleZoomInMouseDown
},
props.tooltip ? h(
VcTooltip,
{
ref: zoomControlState.zoomInTooltipRef,
...props.tooltip,
onBeforeShow: zoomControlState.onTooltipBeforeShow
},
() => h("strong", {}, props.tooltip.zoomInTip || t("vc.navigationSm.zoomCotrol.zoomInTip"))
) : createCommentVNode("v-if")
)
);
children.push(
h(
"div",
{
ref: zoomOutRef,
class: "vc-zoomout-sm",
onMousedown: zoomControlState.handleZoomOutMouseDown,
onTouchstart: zoomControlState.handleZoomOutMouseDown
},
props.tooltip ? h(
VcTooltip,
{
ref: zoomControlState.zoomInTooltipRef,
...props.tooltip,
onBeforeShow: zoomControlState.onTooltipBeforeShow
},
() => h("strong", {}, props.tooltip.zoomOutTip || t("vc.navigationSm.zoomCotrol.zoomOutTip"))
) : createCommentVNode("v-if")
)
);
children.push(
h(
"div",
{
ref: zoomBarRef,
class: "vc-zoombar-sm",
style: zoombarStyle.value,
onMousedown: zoomControlState.handleZoomBarScrollMouseDown,
onTouchstart: zoomControlState.handleZoomBarScrollMouseDown
},
props.tooltip ? h(
VcTooltip,
{
ref: zoomControlState.zoomInTooltipRef,
...props.tooltip,
onBeforeShow: zoomControlState.onTooltipBeforeShow
},
() => h("strong", {}, props.tooltip.zoomBarTip || t("vc.navigationSm.zoomCotrol.zoomBarTip"))
) : createCommentVNode("v-if")
)
);
return h(
"div",
{
ref: rootRef,
class: "vc-zoom-control-sm " + positionState.classes.value,
style: rootStyle
},
children
);
} else {
return createCommentVNode("v-if");
}
};
}
});
const compassOptsDefault = {
enableCompassOuterRing: true,
duration: 1.5,
autoHidden: true,
tooltip: {
delay: 1e3,
anchor: "bottom middle",
offset: [0, 20],
tip: void 0
}
};
const zoomOptsDefault = {
autoHidden: true,
tooltip: {
delay: 1e3,
anchor: "bottom middle",
offset: [0, 20],
tip: void 0
}
};
const navigationSmProps = exports('navigationSmProps', {
...positionProps,
compassOpts: {
type: [Boolean, Object],
default: () => compassOptsDefault
},
zoomOpts: {
type: [Boolean, Object],
default: () => zoomOptsDefault
}
});
const emits$d = {
...commonEmits,
zoomEvt: (evt) => true,
compassEvt: (evt) => true
};
var NavigationSm = defineComponent({
name: "VcNavigationSm",
inheritAttrs: false,
props: navigationSmProps,
emits: emits$d,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VcNavigationSm";
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const canRender = ref(false);
const { $services } = commonState;
const positionState = usePosition(props);
const rootRef = ref(null);
const compassRef = ref(null);
const zoomControlRef = ref(null);
const rootStyle = reactive({});
const { emit } = ctx;
watch(
() => props,
() => {
nextTick(() => {
var _a, _b;
updateRootStyle();
(_a = $(compassRef)) == null ? void 0 : _a.reload();
(_b = $(zoomControlRef)) == null ? void 0 : _b.reload();
});
},
{
deep: true
}
);
const compassOptions = computed(() => Object.assign({}, compassOptsDefault, props.compassOpts));
const zoomControlOptions = computed(() => Object.assign({}, zoomOptsDefault, props.zoomOpts));
const onCompassEvt = (e) => {
const listener = getInstanceListener(instance, "compassEvt");
listener && emit("compassEvt", e);
};
const onZoomEvt = (e) => {
const listener = getInstanceListener(instance, "zoomEvt");
listener && emit("zoomEvt", e);
};
instance.createCesiumObject = async () => {
var _a;
canRender.value = true;
const { viewer } = $services;
(_a = viewer.viewerWidgetResized) == null ? void 0 : _a.addEventListener(onViewerWidgetResized);
return new Promise((resolve, reject) => {
nextTick(() => {
const viewerElement = viewer._element;
viewerElement.appendChild($(rootRef));
resolve($(rootRef));
});
});
};
instance.mount = async () => {
var _a;
updateRootStyle();
const { viewer } = $services;
(_a = viewer.viewerWidgetResized) == null ? void 0 : _a.raiseEvent({
type: instance.cesiumClass,
status: "mounted",
target: $(rootRef)
});
return true;
};
instance.unmount = async () => {
var _a, _b;
const { viewer } = $services;
const viewerElement = viewer._element;
viewerElement.contains($(rootRef)) && viewerElement.removeChild($(rootRef));
(_a = viewer.viewerWidgetResized) == null ? void 0 : _a.removeEventListener(onViewerWidgetResized);
(_b = viewer.viewerWidgetResized) == null ? void 0 : _b.raiseEvent({
type: instance.cesiumClass,
status: "unmounted",
target: $(rootRef)
});
return true;
};
const onViewerWidgetResized = () => {
nextTick(() => {
updateRootStyle();
});
};
const updateRootStyle = () => {
const css = positionState.style.value;
const side = positionState.attach.value;
rootStyle.left = css.left;
rootStyle.top = css.top;
rootStyle.transform = css.transform;
if ((side.bottom || side.top) && !side.left && !side.right) {
css.left = "50%";
css.transform = "translate(-50%, 0)";
}
if ((side.left || side.right) && !side.top && !side.bottom) {
css.top = "50%";
css.transform = "translate(0, -50%)";
}
Object.assign(rootStyle, css);
};
return () => {
if (canRender.value) {
let children = [];
children = hMergeSlot(ctx.slots.default, children);
if (compassOptions.value && props.compassOpts !== false) {
children.push(
h(CompassSm, {
ref: compassRef,
onCompassEvt,
...compassOptions.value
})
);
}
if (zoomControlOptions.value && props.zoomOpts !== false) {
children.push(
h(ZoomControlSm, {
ref: zoomControlRef,
onZoomEvt,
...zoomControlOptions.value
})
);
}
return h(
"div",
{
ref: rootRef,
class: "vc-navigation-sm " + positionState.classes.value,
style: rootStyle
},
children
);
} else {
return createCommentVNode("v-if");
}
};
}
});
const overviewProps = exports('overviewProps', {
position: {
type: String,
default: "bottom-right",
validator: (v) => ["top-right", "top-left", "bottom-right", "bottom-left"].includes(v)
},
offset: {
type: Array,
validator: (v) => v.length === 2
},
width: {
type: String,
default: "150px"
},
height: {
type: String,
default: "150px"
},
border: {
type: String,
default: "solid 4px rgb(255, 255, 255)"
},
borderRadius: {
type: String
},
toggleOpts: {
type: Object
},
viewerOpts: {
type: Object
},
centerRectColor: {
type: [Object, Array, String],
default: "#ff000080"
},
widthFactor: {
type: Number,
default: 2
},
heightFactor: {
type: Number,
default: 2
},
modelValue: {
type: Boolean,
default: true
}
});
var OverviewMap = defineComponent({
name: "VcOverviewMap",
props: overviewProps,
emits: {
...commonEmits,
"update:modelValue": (value) => true
},
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VcOverviewMap";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { t } = useLocale();
const { $services } = commonState;
const rootRef = ref(null);
const toggleBtnRef = ref(null);
const rootStyle = reactive({});
const tooltipRef = ref(null);
const viewerRef = ref(null);
const positionState = usePosition(props);
const showing = ref(props.modelValue);
let unwatchFns = [];
let overviewViewer;
let centerRect;
const toggleOpts = computed(() => {
return Object.assign(
{},
{
color: "#fff",
background: "#3f4854",
icon: "vc-icons-overview-toggle",
size: "15px",
tooltip: {
delay: 500,
anchor: "bottom middle",
offset: [0, 20],
tip: void 0
}
},
props.toggleOpts
);
});
const viewerOpts = computed(() => {
return Object.assign(
{},
{
removeCesiumScript: false,
showCredit: false,
sceneMode: 2,
containerId: "vc-overview-map"
},
props.viewerOpts
);
});
instance.createCesiumObject = async () => {
const { viewer } = $services;
const viewerElement = viewer._element;
viewerElement.appendChild($(rootRef));
return [$(rootRef), $(viewerRef)];
};
instance.mount = async () => {
updateRootStyle();
const { viewer } = $services;
viewer.clock.onTick.addEventListener(onClockTick);
return true;
};
instance.unmount = async () => {
const { viewer } = $services;
const viewerElement = viewer._element;
viewer.clock.onTick.removeEventListener(onClockTick);
viewerElement.contains($(rootRef)) && viewerElement.removeChild($(rootRef));
return true;
};
const onClockTick = () => {
if (overviewViewer) {
const { viewer: parentViewer } = $services;
const parentCameraRectangle = parentViewer.camera.computeViewRectangle();
const { defined } = Cesium;
if (!defined(parentCameraRectangle)) {
return;
}
const rectangle = parentCameraRectangle.expand(props.widthFactor, props.heightFactor);
overviewViewer.camera.flyTo({
destination: rectangle.clone(),
// destination: parentViewer.camera.position,
orientation: {
heading: parentViewer.camera.heading,
pitch: parentViewer.camera.pitch,
roll: parentViewer.camera.roll
},
duration: 0
});
const { Cartesian3, SceneTransforms } = Cesium;
const wnPosition = Cartesian3.fromRadians(parentCameraRectangle.west, parentCameraRectangle.north);
const enPosition = Cartesian3.fromRadians(parentCameraRectangle.east, parentCameraRectangle.north);
const wsPosition = Cartesian3.fromRadians(parentCameraRectangle.west, parentCameraRectangle.south);
const esPosition = Cartesian3.fromRadians(parentCameraRectangle.east, parentCameraRectangle.south);
const scene = overviewViewer.scene;
const wnWindowPosition = SceneTransforms.wgs84ToWindowCoordinates(scene, wnPosition);
const enWindowPosition = SceneTransforms.wgs84ToWindowCoordinates(scene, enPosition);
const wsWindowPosition = SceneTransforms.wgs84ToWindowCoordinates(scene, wsPosition);
const esWindowPosition = SceneTransforms.wgs84ToWindowCoordinates(scene, esPosition);
if (!defined(wnWindowPosition) || !defined(enWindowPosition) || !defined(wsWindowPosition) || !defined(esWindowPosition)) {
return;
}
const width = enWindowPosition.x - wnWindowPosition.x;
const height = wsWindowPosition.y - wnWindowPosition.y;
const x = (wnWindowPosition.x + enWindowPosition.x) / 2 - width / 2;
const y = (wnWindowPosition.y + wsWindowPosition.y) / 2 - height / 2;
if (width <= 0 || height <= 0) {
return;
}
const boundingRectangle = new Cesium.BoundingRectangle(x, y, width, height);
centerRect.rectangle = boundingRectangle;
centerRect.material.uniforms.color = makeColor(props.centerRectColor);
centerRect.show = true;
}
};
const onViewerReady = (readyObj) => {
const { viewer } = readyObj;
overviewViewer = viewer;
const control = viewer.scene.screenSpaceCameraController;
control.enableRotate = false;
control.enableTranslate = false;
control.enableZoom = false;
control.enableTilt = false;
control.enableLook = false;
overviewViewer.scene.highDynamicRange = false;
overviewViewer.scene.globe.enableLighting = false;
overviewViewer.scene.globe.showWaterEffect = false;
overviewViewer.scene.globe.depthTestAgainstTerrain = false;
overviewViewer.scene.skyAtmosphere.show = false;
overviewViewer.scene.fog.enabled = false;
overviewViewer.scene.skyBox.show = false;
overviewViewer.scene.sun.show = false;
overviewViewer.scene.moon.show = false;
overviewViewer.scene.highDynamicRange = false;
overviewViewer.scene.globe.showGroundAtmosphere = false;
centerRect = new Cesium.ViewportQuad(new Cesium.BoundingRectangle(150, 100, 100, 50));
centerRect.show = false;
overviewViewer.scene.primitives.add(centerRect);
};
const updateRootStyle = () => {
var _a;
const css = positionState.style.value;
rootStyle.left = css.left;
rootStyle.top = css.top;
rootStyle.transform = css.transform;
rootStyle["pointer-events"] = "none";
css.borderRadius = props.borderRadius;
css.border = props.border;
if (showing.value) {
css.width = props.width;
css.height = props.height;
} else {
const reg = /(\d+)/g;
const regResult = reg.exec(props.border);
const boder = (regResult == null ? void 0 : regResult.length) ? parseFloat(regResult[0]) : 0;
const toggleBtnRefStyle = getComputedStyle((_a = $(toggleBtnRef)) == null ? void 0 : _a.$el);
css.width = `${parseFloat(toggleBtnRefStyle.width) + parseFloat(toggleBtnRefStyle.padding) + boder}px`;
css.height = `${parseFloat(toggleBtnRefStyle.height) + parseFloat(toggleBtnRefStyle.padding) + boder}px`;
}
Object.assign(rootStyle, css);
};
const onToggle = () => {
if (showing.value) {
minimize();
} else {
restore();
}
showing.value = !showing.value;
ctx.emit("update:modelValue", showing.value);
};
const minimize = () => {
var _a;
const reg = /(\d+)/g;
const regResult = reg.exec(props.border);
const boder = (regResult == null ? void 0 : regResult.length) ? parseFloat(regResult[0]) : 0;
const toggleBtnRefStyle = getComputedStyle((_a = $(toggleBtnRef)) == null ? void 0 : _a.$el);
rootStyle.width = `${parseFloat(toggleBtnRefStyle.width) + parseFloat(toggleBtnRefStyle.padding) + boder}px`;
rootStyle.height = `${parseFloat(toggleBtnRefStyle.height) + parseFloat(toggleBtnRefStyle.padding) + boder}px`;
};
const restore = () => {
rootStyle.width = props.width;
rootStyle.height = props.height;
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
return () => {
const children = [];
children.push(
h(
VcBtn,
{
ref: toggleBtnRef,
class: "toggle toggle-" + props.position + (!showing.value ? " minimized " : ""),
flat: true,
dense: true,
icon: toggleOpts.value.icon,
size: toggleOpts.value.size,
style: { color: toggleOpts.value.color, background: toggleOpts.value.background, "pointer-events": "auto" },
onClick: onToggle
},
() => toggleOpts.value.tooltip ? h(
VcTooltip,
{
ref: tooltipRef,
...toggleOpts.value.tooltip
// onBeforeShow: onTooltipBeforeShow
},
() => h("strong", {}, toggleOpts.value.tooltip.tip || t(`vc.overview.${!showing.value ? "show" : "hidden"}`))
) : createCommentVNode("v-if")
)
);
children.push(
h(
_Viewer,
{
ref: viewerRef,
...viewerOpts.value,
onReady: onViewerReady
},
() => hSlot(ctx.slots.default)
)
);
return h(
"div",
{
ref: rootRef,
class: "vc-overview-map " + positionState.classes.value,
style: rootStyle
},
children
);
};
}
});
class Feature {
constructor(options) {
this.id = options.id || Cesium.createGuid();
}
static getBoundingSphere(cesiumObject, viewer) {
var _a, _b, _c, _d;
const { Primitive, ClassificationPrimitive, GroundPolylinePrimitive, GroundPrimitive, Polyline } = Cesium;
let boundingSphere;
if (cesiumObject instanceof ClassificationPrimitive || cesiumObject instanceof GroundPolylinePrimitive) {
boundingSphere = (_b = (_a = cesiumObject._primitive) == null ? void 0 : _a._boundingSphereWC) == null ? void 0 : _b[0];
} else if (cesiumObject instanceof Primitive) {
boundingSphere = (_c = cesiumObject._boundingSphereWC) == null ? void 0 : _c[0];
} else if (cesiumObject instanceof GroundPrimitive) {
boundingSphere = (_d = cesiumObject._boundingVolumes) == null ? void 0 : _d[0];
} else if (cesiumObject instanceof Polyline) {
boundingSphere = cesiumObject._boundingVolumeWC;
} else if (cesiumObject instanceof Cesium.Entity) {
boundingSphere = new Cesium.BoundingSphere();
viewer.dataSourceDisplay.getBoundingSphere(cesiumObject, true, boundingSphere);
}
return boundingSphere;
}
static fromPickedFeature(cesiumObject, pickedFeature, viewer, screenPosition) {
var _a, _b, _c, _d, _e;
const feature = new Feature({ id: cesiumObject.id });
if (cesiumObject.position) {
feature.position = cesiumObject.position;
} else if (cesiumObject instanceof Cesium.Model) {
feature.position = Cesium.Matrix4.getTranslation(cesiumObject.modelMatrix, new Cesium.Cartesian3());
} else if (cesiumObject instanceof Cesium.Cesium3DTileset) {
let position = pickedFeature.content.tile.boundingSphere.center;
let positionProperty = (_a = pickedFeature == null ? void 0 : pickedFeature.getProperty) == null ? void 0 : _a.call(pickedFeature, "position");
if (Cesium.defined(positionProperty)) {
if (typeof positionProperty === "string") {
positionProperty = JSON.parse(positionProperty);
}
position = makeCartesian3(positionProperty);
}
feature.position = position;
} else {
feature.position = (_b = Feature.getBoundingSphere(cesiumObject, viewer)) == null ? void 0 : _b.center;
}
feature.cesiumObject = cesiumObject;
feature.pickedFeature = pickedFeature;
feature.windowPosition = screenPosition;
feature.description = (cesiumObject == null ? void 0 : cesiumObject.description) || ((_c = cesiumObject == null ? void 0 : cesiumObject.description) == null ? void 0 : _c.getValue());
feature.properties = (cesiumObject == null ? void 0 : cesiumObject.properties) || ((_d = cesiumObject == null ? void 0 : cesiumObject.properties) == null ? void 0 : _d.getValue()) || ((_e = cesiumObject == null ? void 0 : cesiumObject.feature) == null ? void 0 : _e.properties);
return feature;
}
static fromImageryLayerFeature(imageryFeature, viewer) {
const feature = new Feature({
id: imageryFeature.name
});
feature.name = imageryFeature.name;
feature.description = imageryFeature.description;
feature.properties = imageryFeature.properties;
feature.data = imageryFeature.data;
feature.imageryLayer = imageryFeature.imageryLayer;
feature.position = viewer.scene.globe.ellipsoid.cartographicToCartesian(imageryFeature.position);
feature.coords = imageryFeature.coords;
return feature;
}
}
class PickedFeatures {
constructor() {
const { knockout } = Cesium;
this.allFeaturesAvailablePromise = void 0;
this.isLoading = true;
this.pickPosition = void 0;
this.features = [];
this.error = void 0;
this.providerCoords = void 0;
knockout.track(this, ["isLoading", "features", "error"]);
}
}
function pickImageryHelper(scene, pickedLocation, pickFeatures, callback) {
const { defined, Rectangle, Math: CesiumMath } = Cesium;
const tilesToRender = scene.globe._surface._tilesToRender;
let pickedTile;
for (let textureIndex = 0; !defined(pickedTile) && textureIndex < tilesToRender.length; ++textureIndex) {
const tile = tilesToRender[textureIndex];
if (Rectangle.contains(tile.rectangle, pickedLocation)) {
pickedTile = tile;
}
}
if (!defined(pickedTile)) {
return;
}
const imageryTiles = pickedTile.data.imagery;
for (let i = imageryTiles.length - 1; i >= 0; --i) {
const terrainImagery = imageryTiles[i];
const imagery = terrainImagery.readyImagery;
if (!defined(imagery)) {
continue;
}
const provider = imagery.imageryLayer.imageryProvider;
if (pickFeatures && !defined(provider.pickFeatures)) {
continue;
}
if (!Rectangle.contains(imagery.rectangle, pickedLocation)) {
continue;
}
const applicableRectangle = new Rectangle();
const epsilon = 1 / 1024;
applicableRectangle.west = CesiumMath.lerp(
pickedTile.rectangle.west,
pickedTile.rectangle.east,
terrainImagery.textureCoordinateRectangle.x - epsilon
);
applicableRectangle.east = CesiumMath.lerp(
pickedTile.rectangle.west,
pickedTile.rectangle.east,
terrainImagery.textureCoordinateRectangle.z + epsilon
);
applicableRectangle.south = CesiumMath.lerp(
pickedTile.rectangle.south,
pickedTile.rectangle.north,
terrainImagery.textureCoordinateRectangle.y - epsilon
);
applicableRectangle.north = CesiumMath.lerp(
pickedTile.rectangle.south,
pickedTile.rectangle.north,
terrainImagery.textureCoordinateRectangle.w + epsilon
);
if (!Rectangle.contains(applicableRectangle, pickedLocation)) {
continue;
}
callback(imagery);
}
}
function pickImageryLayerFeatures(ray, scene, includeImageryIds = [], excludeImageryIds = []) {
const { defined } = Cesium;
const pickedPosition = scene.globe.pick(ray, scene);
if (!defined(pickedPosition)) {
return;
}
const pickedLocation = scene.globe.ellipsoid.cartesianToCartographic(pickedPosition);
const promises = [];
const imageryLayers = [];
pickImageryHelper(scene, pickedLocation, true, function(imagery) {
if (excludeImageryIds.indexOf(imagery.imageryLayer.vcId) !== -1) {
return;
}
if (includeImageryIds.length && includeImageryIds.indexOf(imagery.imageryLayer.vcId) === -1) {
return;
}
const provider = imagery.imageryLayer.imageryProvider;
const promise = provider.pickFeatures(imagery.x, imagery.y, imagery.level, pickedLocation.longitude, pickedLocation.latitude);
if (defined(promise)) {
promises.push(promise);
imageryLayers.push(imagery.imageryLayer);
}
});
if (promises.length === 0) {
return void 0;
}
return Promise.all(promises).then(function(results) {
const features = [];
for (let resultIndex = 0; resultIndex < results.length; ++resultIndex) {
const result = results[resultIndex];
const image = imageryLayers[resultIndex];
if (defined(result) && result.length > 0) {
for (let featureIndex = 0; featureIndex < result.length; ++featureIndex) {
const feature = result[featureIndex];
feature.imageryLayer = image;
if (!defined(feature.position)) {
feature.position = pickedLocation;
}
features.push(feature);
}
}
}
return features;
});
}
function useSelectionIndicatior(instance, props, $services) {
const offScreen = "-1000px";
const screenPositionX = ref(offScreen);
const screenPositionY = ref(offScreen);
const transform = "";
const opacity = 1;
const position = ref();
const rootRef = ref();
let selectionIndicatorTween;
let selectionIndicatorIsAppearing;
const pickedFeatures = ref(null);
const selectedFeature = ref(null);
let unwatchFns = [];
let isCluster = false;
const rootStyle = reactive({
top: screenPositionY.value,
left: screenPositionX.value,
transform,
opacity
});
unwatchFns.push(
watch(selectedFeature, (val) => {
var _a, _b, _c;
const selectedFeature2 = val;
const { defined } = Cesium;
if (defined(selectedFeature2) && defined(selectedFeature2 == null ? void 0 : selectedFeature2.position)) {
const { viewer } = $services;
position.value = (selectedFeature2 == null ? void 0 : selectedFeature2.position) instanceof Cesium.Cartesian3 ? selectedFeature2 == null ? void 0 : selectedFeature2.position : (_a = selectedFeature2 == null ? void 0 : selectedFeature2.position) == null ? void 0 : _a.getValue(viewer.clock.currentTime);
animateAppear();
(_b = instance.proxy) == null ? void 0 : _b.$emit("pickEvt", selectedFeature2);
} else {
animateDepart();
(_c = instance.proxy) == null ? void 0 : _c.$emit("pickEvt", selectedFeature2);
}
update();
})
);
unwatchFns.push(
watch(pickedFeatures, (val) => {
const { defined, Entity } = Cesium;
const pickedFeatures2 = val;
if (!defined(pickedFeatures2)) {
selectedFeature.value = void 0;
} else {
const fakeFeature = new Entity({
id: "__Vc__Pick__Location__"
});
fakeFeature.position = pickedFeatures2.pickPosition;
selectedFeature.value = fakeFeature;
}
nextTick(() => {
if (defined(pickedFeatures2.allFeaturesAvailablePromise)) {
pickedFeatures2.allFeaturesAvailablePromise.then(() => {
var _a, _b, _c;
const featuresShownAtAll = pickedFeatures2.features.filter((x) => defined(x));
selectedFeature.value = featuresShownAtAll.filter(featureHasInfo)[0];
if (!defined(selectedFeature.value) && featuresShownAtAll.length > 0) {
selectedFeature.value = featuresShownAtAll[0];
if (isCluster) {
if (selectedFeature.value instanceof Feature && ((_c = (_b = (_a = selectedFeature.value) == null ? void 0 : _a.pickedFeature) == null ? void 0 : _b.primitive) == null ? void 0 : _c.position)) {
selectedFeature.value.position = selectedFeature.value.pickedFeature.primitive.position;
}
}
}
});
}
});
})
);
const featureHasInfo = (feature) => {
const { defined } = Cesium;
return defined(feature.properties) || defined(feature.description);
};
const pickFromScreenPosition = (screenPosition) => {
const { defined } = Cesium;
const { viewer } = $services;
const scene = viewer.scene;
const pickRay = scene.camera.getPickRay(screenPosition);
let pickPosition = scene.globe.pick(pickRay, scene);
if (!defined(pickPosition)) {
pickPosition = scene.pickPosition(screenPosition);
if (!defined(pickPosition)) {
return;
}
}
const pickPositionCartographic = scene.globe.ellipsoid.cartesianToCartographic(pickPosition || new Cesium.Cartesian3());
const vectorFeatures = pickVectorFeatures(screenPosition);
const providerCoords = attachProviderCoordHooks();
const pickRasterPromise = props.allowFeatureInfoRequests ? pickImageryLayerFeatures(pickRay, scene, props.includeImageryIds, props.excludeImageryIds) : Promise.resolve();
const result = buildPickedFeatures(
providerCoords,
pickPosition,
vectorFeatures,
[pickRasterPromise],
void 0,
pickPositionCartographic.height,
false,
viewer
);
pickedFeatures.value = result;
};
const buildPickedFeatures = (providerCoords, pickPosition, existingFeatures, featurePromises, imageryLayers, defaultHeight, ignoreSplitter, viewer) => {
const { defined, defaultValue } = Cesium;
ignoreSplitter = defaultValue(ignoreSplitter, false);
const result = new PickedFeatures();
result.providerCoords = providerCoords;
result.pickPosition = pickPosition;
result.allFeaturesAvailablePromise = Promise.all(featurePromises).then(function(allFeatures) {
result.isLoading = false;
result.features = allFeatures.reduce(
function(resultFeaturesSoFar, imageryLayerFeatures, i) {
if (!defined(imageryLayerFeatures)) {
return resultFeaturesSoFar;
}
const features = imageryLayerFeatures.map(
function(feature) {
if (defined(imageryLayers)) {
feature.imageryLayer = imageryLayers[i];
}
if (!defined(feature.position)) {
feature.position = viewer.scene.globe.ellipsoid.cartesianToCartographic(pickPosition);
}
if (!defined(feature.position.height) || feature.position.height === 0) {
feature.position.height = defaultHeight;
}
return Feature.fromImageryLayerFeature(feature, viewer);
}.bind(this)
);
return resultFeaturesSoFar.concat(features);
}.bind(this),
defaultValue(existingFeatures, [])
);
}).catch(function() {
result.isLoading = false;
result.error = "An unknown error occurred while picking features.";
});
return result;
};
const pickVectorFeatures = (screenPosition) => {
var _a, _b;
const vectorFeatures = [];
const { defined } = Cesium;
const { viewer } = $services;
const scene = viewer.scene;
const pickedList = scene.drillPick(screenPosition, props.limit);
for (let i = 0; i < pickedList.length; ++i) {
const picked = pickedList[i];
let id = picked.id;
if (!defined(id) && defined(picked.primitive)) {
id = picked.primitive;
}
const catalogItem = (_b = (_a = picked == null ? void 0 : picked.primitive) == null ? void 0 : _a._catalogItem) != null ? _b : id == null ? void 0 : id._catalogItem;
if (typeof (catalogItem == null ? void 0 : catalogItem.getFeaturesFromPickResult) === "function") {
const result = catalogItem.getFeaturesFromPickResult.bind(catalogItem)(screenPosition, picked);
if (result) {
if (Array.isArray(result)) {
vectorFeatures.push(...result);
} else {
vectorFeatures.push(result);
}
}
} else {
const pickedFeature = picked;
if (pickedFeature.id) {
if (isArray(pickedFeature.id) && pickedFeature.id[0] instanceof Cesium.Entity) {
isCluster = true;
pickedFeature.id.forEach((entity) => {
const feature = Feature.fromPickedFeature(entity, pickedFeature, viewer, screenPosition);
vectorFeatures.push(feature);
});
continue;
} else if (pickedFeature.id instanceof Cesium.Entity) {
const feature = Feature.fromPickedFeature(pickedFeature.id, pickedFeature, viewer, screenPosition);
vectorFeatures.push(feature);
isCluster = false;
continue;
} else {
isCluster = false;
}
}
if (pickedFeature.primitive) {
const feature = Feature.fromPickedFeature(pickedFeature.primitive, pickedFeature, viewer, screenPosition);
vectorFeatures.push(feature);
} else if (pickedFeature.collection) {
const feature = Feature.fromPickedFeature(pickedFeature.collection, pickedFeature, viewer, screenPosition);
vectorFeatures.push(feature);
}
}
}
return vectorFeatures;
};
const attachProviderCoordHooks = () => {
const providerCoords = {};
const { viewer } = $services;
const scene = viewer.scene;
const pickFeaturesHook = function(imageryProvider, oldPick, x, y, level, longitude, latitude) {
if (oldPick) {
const featuresPromise = oldPick.call(imageryProvider, x, y, level, longitude, latitude);
if (imageryProvider.url) {
providerCoords[imageryProvider.url] = {
x,
y,
level
};
}
imageryProvider.pickFeatures = oldPick;
return featuresPromise;
}
return Promise.reject(false);
};
for (let j = 0; j < scene.imageryLayers.length; j++) {
const imageryProvider = scene.imageryLayers.get(j).imageryProvider;
imageryProvider.pickFeatures = pickFeaturesHook.bind(void 0, imageryProvider, imageryProvider.pickFeatures);
}
return providerCoords;
};
const computeScreenSpacePosition = (position2, result) => {
const { viewer } = $services;
return Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewer.scene, position2, result);
};
const update = () => {
const { defined, Cartesian2 } = Cesium;
if (props.show && defined(position.value)) {
const screenPosition = computeScreenSpacePosition(position.value, new Cartesian2());
if (!defined(screenPosition)) ; else {
const { viewer } = $services;
const container = viewer.container;
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const indicatorSize = props.width;
const halfSize = indicatorSize * 0.5;
screenPosition.x = Math.min(Math.max(screenPosition.x, -indicatorSize), containerWidth + indicatorSize) - halfSize;
screenPosition.y = Math.min(Math.max(screenPosition.y, -indicatorSize), containerHeight + indicatorSize) - halfSize;
rootStyle.left = Math.floor(screenPosition.x + 0.25) + "px";
rootStyle.top = Math.floor(screenPosition.y + 0.25) + "px";
}
}
};
const animateAppear = () => {
const { viewer } = $services;
const { defined, EasingFunction } = Cesium;
if (defined(selectionIndicatorTween)) {
if (selectionIndicatorIsAppearing) {
return;
}
selectionIndicatorTween.cancelTween();
selectionIndicatorTween = void 0;
}
selectionIndicatorIsAppearing = true;
selectionIndicatorTween = viewer.scene.tweens.add({
startObject: {
scale: 2,
opacity: 0,
rotate: -180
},
stopObject: {
scale: 1,
opacity: 1,
rotate: 0
},
duration: 0.8,
easingFunction: EasingFunction.EXPONENTIAL_OUT,
update: function(value) {
rootStyle.opacity = value.opacity;
rootStyle.transform = "scale(" + value.scale + ") rotate(" + value.rotate + "deg)";
},
complete: function() {
selectionIndicatorTween = void 0;
},
cancel: function() {
selectionIndicatorTween = void 0;
}
});
};
const animateDepart = () => {
const { viewer } = $services;
const { defined, EasingFunction } = Cesium;
if (defined(selectionIndicatorTween)) {
if (!selectionIndicatorIsAppearing) {
return;
}
selectionIndicatorTween.cancelTween();
selectionIndicatorTween = void 0;
}
selectionIndicatorIsAppearing = false;
selectionIndicatorTween = viewer.scene.tweens.add({
startObject: {
scale: 1,
opacity: 1
},
stopObject: {
scale: 1.5,
opacity: 0
},
duration: 0.8,
easingFunction: EasingFunction.EXPONENTIAL_OUT,
update: function(value) {
rootStyle.opacity = value.opacity;
rootStyle.transform = "scale(" + value.scale + ") rotate(0deg)";
},
complete: function() {
selectionIndicatorTween = void 0;
},
cancel: function() {
selectionIndicatorTween = void 0;
}
});
};
const onPostRender = () => {
update();
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
Object.assign(instance.proxy, {
selectedFeature,
position,
computeScreenSpacePosition,
update,
animateAppear,
animateDepart,
getPickedFeatures: () => pickedFeatures
});
return {
pickFromScreenPosition,
rootRef,
rootStyle,
onPostRender
};
}
const selectionIndicatorProps = exports('selectionIndicatorProps', {
show: {
type: Boolean,
default: true
},
width: {
type: Number,
default: 50
},
height: {
type: Number,
default: 50
},
allowFeatureInfoRequests: {
type: Boolean,
default: true
},
includeImageryIds: {
type: Array,
default: () => []
},
excludeImageryIds: {
type: Array,
default: () => []
},
limit: {
type: Number,
default: 25
}
});
const emits$c = {
...commonEmits,
pickEvt: (evt) => true
};
var SelectionIndicator = defineComponent({
name: "VcSelectionIndicator",
props: selectionIndicatorProps,
emits: emits$c,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VcSelectionIndicator";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { $services } = commonState;
let pickScreenSpaceEventHandler;
const useSelectionIndicatiorState = useSelectionIndicatior(instance, props, $services);
instance.createCesiumObject = async () => {
const { viewer } = $services;
const viewerElement = viewer._element;
viewerElement.appendChild($(useSelectionIndicatiorState.rootRef));
return $(useSelectionIndicatiorState.rootRef);
};
instance.mount = async () => {
const { viewer } = $services;
const { ScreenSpaceEventHandler, ScreenSpaceEventType } = Cesium;
pickScreenSpaceEventHandler = new ScreenSpaceEventHandler(viewer.canvas);
pickScreenSpaceEventHandler.setInputAction((movement) => {
useSelectionIndicatiorState.pickFromScreenPosition(movement.position);
}, ScreenSpaceEventType.LEFT_CLICK);
viewer.scene.postRender.addEventListener(useSelectionIndicatiorState.onPostRender);
return true;
};
instance.unmount = async () => {
const { viewer } = $services;
const viewerElement = viewer._element;
viewerElement.contains($(useSelectionIndicatiorState.rootRef)) && viewerElement.removeChild($(useSelectionIndicatiorState.rootRef));
viewer.scene.postRender.removeEventListener(useSelectionIndicatiorState.onPostRender);
pickScreenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
pickScreenSpaceEventHandler.destroy();
pickScreenSpaceEventHandler = void 0;
return true;
};
return () => {
return h(
"div",
{
ref: useSelectionIndicatiorState.rootRef,
class: "vc-selection-indicator",
style: useSelectionIndicatiorState.rootStyle
},
h("img", {
src: "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+DQo8c3ZnIHdpZHRoPSIxNzZweCIgaGVpZ2h0PSIxNzZweCIgdmlld0JveD0iMCAwIDE3NiAxNzYiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6c2tldGNoPSJodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2gvbnMiPg0KICAgIDwhLS0gR2VuZXJhdG9yOiBTa2V0Y2ggMy4xLjEgKDg3NjEpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPg0KICAgIDx0aXRsZT5Mb2NhdGlvblRhcmdldCArIFBhdGg8L3RpdGxlPg0KICAgIDxkZXNjPkNyZWF0ZWQgd2l0aCBTa2V0Y2guPC9kZXNjPg0KICAgIDxkZWZzPg0KICAgICAgICA8ZmlsdGVyIHg9Ii01MCUiIHk9Ii01MCUiIHdpZHRoPSIyMDAlIiBoZWlnaHQ9IjIwMCUiIGZpbHRlclVuaXRzPSJvYmplY3RCb3VuZGluZ0JveCIgaWQ9ImZpbHRlci0xIj4NCiAgICAgICAgICAgIDxmZU9mZnNldCBkeD0iMCIgZHk9IjAiIGluPSJTb3VyY2VBbHBoYSIgcmVzdWx0PSJzaGFkb3dPZmZzZXRPdXRlcjEiPjwvZmVPZmZzZXQ+DQogICAgICAgICAgICA8ZmVHYXVzc2lhbkJsdXIgc3RkRGV2aWF0aW9uPSIyIiBpbj0ic2hhZG93T2Zmc2V0T3V0ZXIxIiByZXN1bHQ9InNoYWRvd0JsdXJPdXRlcjEiPjwvZmVHYXVzc2lhbkJsdXI+DQogICAgICAgICAgICA8ZmVDb2xvck1hdHJpeCB2YWx1ZXM9IjAgMCAwIDAgMCAgIDAgMCAwIDAgMCAgIDAgMCAwIDAgMCAgMCAwIDAgMC41MjY0NDY0NDUgMCIgaW49InNoYWRvd0JsdXJPdXRlcjEiIHR5cGU9Im1hdHJpeCIgcmVzdWx0PSJzaGFkb3dNYXRyaXhPdXRlcjEiPjwvZmVDb2xvck1hdHJpeD4NCiAgICAgICAgICAgIDxmZU1lcmdlPg0KICAgICAgICAgICAgICAgIDxmZU1lcmdlTm9kZSBpbj0ic2hhZG93TWF0cml4T3V0ZXIxIj48L2ZlTWVyZ2VOb2RlPg0KICAgICAgICAgICAgICAgIDxmZU1lcmdlTm9kZSBpbj0iU291cmNlR3JhcGhpYyI+PC9mZU1lcmdlTm9kZT4NCiAgICAgICAgICAgIDwvZmVNZXJnZT4NCiAgICAgICAgPC9maWx0ZXI+DQogICAgICAgIDxmaWx0ZXIgeD0iLTUwJSIgeT0iLTUwJSIgd2lkdGg9IjIwMCUiIGhlaWdodD0iMjAwJSIgZmlsdGVyVW5pdHM9Im9iamVjdEJvdW5kaW5nQm94IiBpZD0iZmlsdGVyLTIiPg0KICAgICAgICAgICAgPGZlT2Zmc2V0IGR4PSIwIiBkeT0iMCIgaW49IlNvdXJjZUFscGhhIiByZXN1bHQ9InNoYWRvd09mZnNldE91dGVyMSI+PC9mZU9mZnNldD4NCiAgICAgICAgICAgIDxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjIiIGluPSJzaGFkb3dPZmZzZXRPdXRlcjEiIHJlc3VsdD0ic2hhZG93Qmx1ck91dGVyMSI+PC9mZUdhdXNzaWFuQmx1cj4NCiAgICAgICAgICAgIDxmZUNvbG9yTWF0cml4IHZhbHVlcz0iMCAwIDAgMCAwICAgMCAwIDAgMCAwICAgMCAwIDAgMCAwICAwIDAgMCAwLjUyNjQ0NjQ0NSAwIiBpbj0ic2hhZG93Qmx1ck91dGVyMSIgdHlwZT0ibWF0cml4IiByZXN1bHQ9InNoYWRvd01hdHJpeE91dGVyMSI+PC9mZUNvbG9yTWF0cml4Pg0KICAgICAgICAgICAgPGZlTWVyZ2U+DQogICAgICAgICAgICAgICAgPGZlTWVyZ2VOb2RlIGluPSJzaGFkb3dNYXRyaXhPdXRlcjEiPjwvZmVNZXJnZU5vZGU+DQogICAgICAgICAgICAgICAgPGZlTWVyZ2VOb2RlIGluPSJTb3VyY2VHcmFwaGljIj48L2ZlTWVyZ2VOb2RlPg0KICAgICAgICAgICAgPC9mZU1lcmdlPg0KICAgICAgICA8L2ZpbHRlcj4NCiAgICA8L2RlZnM+DQogICAgPGcgaWQ9IlBhZ2UtMSIgc3Ryb2tlPSJub25lIiBzdHJva2Utd2lkdGg9IjEiIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+DQogICAgICAgIDxnIGlkPSJBcnRib2FyZC0xIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtNjkxLjAwMDAwMCwgLTQ5OC4wMDAwMDApIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZT0iI0ZGRkZGRiI+DQogICAgICAgICAgICA8ZyBpZD0iTG9jYXRpb25UYXJnZXQtKy1QYXRoIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg2OTkuMDAwMDAwLCA1MDYuMDAwMDAwKSI+DQogICAgICAgICAgICAgICAgPHBhdGggZD0iTTgwLDE0NCBDMTE1LjM0NjIyNCwxNDQgMTQ0LDExNS4zNDYyMjQgMTQ0LDgwIEMxNDQsNDQuNjUzNzc2IDExNS4zNDYyMjQsMTYgODAsMTYgQzQ0LjY1Mzc3NiwxNiAxNiw0NC42NTM3NzYgMTYsODAgQzE2LDExNS4zNDYyMjQgNDQuNjUzNzc2LDE0NCA4MCwxNDQgWiBNMTYwLDgwIEwxNDQsODAgTTE2LDgwIEwwLDgwIE03OS42LC0wLjQgTDc5LjYsMTUuNiBNNzguOCwxNDQgTDc4LjgsMTYwIiBpZD0iTG9jYXRpb25UYXJnZXQiIHN0cm9rZS13aWR0aD0iNyIgZmlsdGVyPSJ1cmwoI2ZpbHRlci0xKSI+PC9wYXRoPg0KICAgICAgICAgICAgICAgIDxjaXJjbGUgaWQ9IlBhdGgiIHN0cm9rZS13aWR0aD0iMiIgb3BhY2l0eT0iMC4yNTIyMTU0ODUiIGZpbHRlcj0idXJsKCNmaWx0ZXItMikiIGN4PSI4MCIgY3k9IjgwIiByPSI2Ij48L2NpcmNsZT4NCiAgICAgICAgICAgIDwvZz4NCiAgICAgICAgPC9nPg0KICAgIDwvZz4NCjwvc3ZnPg==",
width: props.width,
height: props.height
})
);
};
}
});
const components$9 = [
Compass,
ZoomControl,
Print,
MyLocation,
StatusBar,
DistanceLegend,
Navigation,
CompassSm,
ZoomControlSm,
NavigationSm,
OverviewMap,
SelectionIndicator
];
components$9.forEach((cmp) => {
cmp["install"] = (app) => {
app.component(cmp.name, cmp);
};
});
const VcCompass = exports('VcCompass', Compass);
const VcZoomControl = exports('VcZoomControl', ZoomControl);
const VcPrint = exports('VcPrint', Print);
const VcMyLocation = exports('VcMyLocation', MyLocation);
const VcStatusBar = exports('VcStatusBar', StatusBar);
const VcDistanceLegend = exports('VcDistanceLegend', DistanceLegend);
const VcNavigation = exports('VcNavigation', Navigation);
const VcCompassSm = exports('VcCompassSm', CompassSm);
const VcZoomControlSm = exports('VcZoomControlSm', ZoomControlSm);
const VcNavigationSm = exports('VcNavigationSm', NavigationSm);
const VcOverviewMap = exports('VcOverviewMap', OverviewMap);
const VcSelectionIndicator = exports('VcSelectionIndicator', SelectionIndicator);
const actionOptions = {
externalLabel: false,
label: "",
labelPosition: "right",
hideLabel: false,
tabindex: void 0,
disable: false,
outline: false,
push: false,
flat: false,
unelevated: false,
color: "primary",
textColor: void 0,
glossy: false,
labelClass: void 0,
labelStyle: void 0,
square: false,
tooltip: {
delay: 500,
anchor: "bottom middle",
offset: [0, 20],
tip: void 0
}
};
const polylinePrimitiveOptsDefault = {
show: true,
enableMouseEvent: true,
asynchronous: false,
classificationType: 2,
appearance: {
type: "PolylineMaterialAppearance",
options: {
material: {
fabric: {
type: "Color",
uniforms: {
color: "#51ff00"
}
}
}
}
},
depthFailAppearance: {
type: "PolylineMaterialAppearance",
options: {
material: {
fabric: {
type: "PolylineDash",
uniforms: {
color: [255, 0, 0, 127]
}
}
}
}
}
};
const pointOptsDefault = {
show: true,
color: "rgb(255,229,0)",
pixelSize: 8,
outlineColor: "black",
outlineWidth: 1,
disableDepthTestDistance: Number.POSITIVE_INFINITY
};
const billboardOptsDefault = {
show: true,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
verticalOrigin: 1,
image: ""
};
const polylineOptsDefault = {
width: 2,
arcType: 0,
ellipsoid: void 0
};
const polygonOptsDefault = {
show: true,
enableMouseEvent: true,
asynchronous: false,
classificationType: 2,
appearance: {
type: "MaterialAppearance",
options: {
material: {
fabric: {
type: "Color",
uniforms: {
color: [255, 165, 0, 125]
}
}
},
faceForward: true,
renderState: {
cull: {
enabled: false
},
depthTest: {
enabled: false
}
}
}
}
};
const labelOptsDefault = {
show: true,
font: "16px Arial Microsoft YaHei sans-serif",
scale: 1,
fillColor: "white",
showBackground: true,
backgroundColor: { x: 0.165, y: 0.165, z: 0.165, w: 0.8 },
backgroundPadding: [7, 5],
horizontalOrigin: 0,
// center
verticalOrigin: 1,
// bottom
pixelOffset: [0, -9],
disableDepthTestDistance: Number.POSITIVE_INFINITY
};
const editorOptsDefault = {
icon: "vc-icons-move",
size: "24px",
color: "#1296db",
background: "#fff",
round: true,
flat: false,
label: void 0,
stack: false,
dense: true,
tooltip: {
delay: 1e3,
// 鼠标悬浮多久显示提示信息
anchor: "bottom middle",
// 提示信息锚点
offset: [0, 20]
// 提示信息位置偏移
}
};
const pointDrawingDefault = {
show: true,
drawtip: {
show: true,
pixelOffset: [32, 32]
},
pointOpts: pointOptsDefault,
editorOpts: {
delay: 1e3,
hideDelay: 1e3,
pixelOffset: [16, -8],
move: Object.assign({}, editorOptsDefault),
remove: Object.assign({}, editorOptsDefault, {
icon: "vc-icons-remove"
})
},
heightReference: 1,
disableDepthTest: false,
showLabel: false,
labelOpts: Object.assign({}, labelOptsDefault, {
horizontalOrigin: 1,
// left
verticalOrigin: 0,
// center
pixelOffset: [10, 0]
})
};
const segmentDrawingDefault = {
show: true,
showComponentLines: false,
drawtip: {
show: true,
pixelOffset: [32, 32]
},
pointOpts: pointOptsDefault,
polylineOpts: polylineOptsDefault,
primitiveOpts: polylinePrimitiveOptsDefault,
editorOpts: {
pixelOffset: [16, -8],
delay: 1e3,
hideDelay: 1e3,
move: Object.assign({}, editorOptsDefault),
removeAll: Object.assign({}, editorOptsDefault, {
icon: "vc-icons-delete"
})
},
disableDepthTest: false
};
const polylineDrawingDefault = {
show: true,
drawtip: {
show: true,
pixelOffset: [32, 32]
},
pointOpts: pointOptsDefault,
polylineOpts: polylineOptsDefault,
primitiveOpts: polylinePrimitiveOptsDefault,
editorOpts: {
pixelOffset: [16, -8],
delay: 1e3,
hideDelay: 1e3,
move: Object.assign({}, editorOptsDefault),
insert: Object.assign({}, editorOptsDefault, {
icon: "vc-icons-insert"
}),
remove: Object.assign({}, editorOptsDefault, {
icon: "vc-icons-remove"
}),
removeAll: Object.assign({}, editorOptsDefault, {
icon: "vc-icons-delete"
})
},
loop: false,
disableDepthTest: false,
showLabel: false,
showAngleLabel: false,
showDistanceLabel: false,
labelOpts: labelOptsDefault,
labelsOpts: Object.assign({}, labelOptsDefault, {
scale: 0.8,
horizontalOrigin: 1,
// left
verticalOrigin: -1,
// top,
pixelOffset: [5, 5]
})
};
const polygonDrawingDefault = {
show: true,
drawtip: {
show: true,
pixelOffset: [32, 32]
},
pointOpts: pointOptsDefault,
polylineOpts: polylineOptsDefault,
primitiveOpts: Object.assign({}, polylinePrimitiveOptsDefault, {
depthFailAppearance: {
type: "PolylineMaterialAppearance",
options: {
material: {
fabric: {
type: "Color",
uniforms: {
color: "#51ff00"
}
}
}
}
}
}),
polygonOpts: polygonOptsDefault,
editorOpts: {
pixelOffset: [16, -8],
delay: 1e3,
hideDelay: 1e3,
move: Object.assign({}, editorOptsDefault),
insert: Object.assign({}, editorOptsDefault, {
icon: "vc-icons-insert"
}),
remove: Object.assign({}, editorOptsDefault, {
icon: "vc-icons-remove"
}),
removeAll: Object.assign({}, editorOptsDefault, {
icon: "vc-icons-delete"
})
},
loop: true,
disableDepthTest: false,
showDistanceLabel: false,
showLabel: false,
showAngleLabel: false,
labelOpts: labelOptsDefault,
labelsOpts: Object.assign({}, labelOptsDefault, {
scale: 0.8,
horizontalOrigin: 1,
// left
verticalOrigin: -1,
// top,
pixelOffset: [5, 5]
})
};
const rectangleDrawingDefault = Object.assign({}, polygonDrawingDefault, {
pointOpts: Object.assign({}, pointOptsDefault, {
show: false
}),
editorOpts: {
pixelOffset: [16, -8],
delay: 1e3,
hideDelay: 1e3,
move: Object.assign({}, editorOptsDefault),
removeAll: Object.assign({}, editorOptsDefault, {
icon: "vc-icons-delete"
})
},
edge: 4,
loop: false,
disableDepthTest: false,
showLabel: false,
showAngleLabel: false,
showDistanceLabel: false,
labelOpts: labelOptsDefault,
labelsOpts: Object.assign({}, labelOptsDefault, {
scale: 0.8,
horizontalOrigin: 1,
// left
verticalOrigin: -1,
// top,
pixelOffset: [5, 5]
})
});
const circleDrawingDefault = Object.assign({}, rectangleDrawingDefault, {
edge: 360
});
const regularDrawingDefault = Object.assign({}, rectangleDrawingDefault, {
edge: 6,
loop: true
});
const clearActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-clear",
color: "red"
});
const regularDrawingActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-drawing-regular"
});
const circleDrawingActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-drawing-circle"
});
const useDrawingActionProps = {
...enableMouseEvent,
show: Boolean,
editable: Boolean,
drawtip: Object,
pointOpts: Object,
editorOpts: Object,
mode: Number,
preRenderDatas: Array,
disableDepthTest: Boolean
};
const useDrawingFabProps = {
...show,
position: {
type: String,
default: "bottom-left",
validator: (v) => ["top-right", "top-left", "bottom-right", "bottom-left", "top", "right", "bottom", "left"].includes(v)
},
offset: {
type: Array,
validator: (v) => v.length === 2
},
mode: {
type: Number,
default: 1
},
activeColor: {
type: String,
default: "positive"
},
editable: {
type: Boolean
},
clampToGround: {
type: Boolean
},
clearActionOpts: {
type: Object,
default: () => clearActionDefault
}
};
const distanceMeasurementActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-measure-distance"
});
const distanceMeasurementDefault = Object.assign({}, segmentDrawingDefault, {
labelOpts: Object.assign({}, labelOptsDefault, {
horizontalOrigin: 1,
// left
verticalOrigin: -1,
// top
pixelOffset: [10, 10]
}),
measureUnits: new MeasureUnits(),
decimals: {
distance: 2,
angle: 2
},
locale: void 0,
autoUpdateLabelPosition: true
});
const componentDistanceMeasurementActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-measure-component-distance"
});
const componentDistanceMeasurementDefault = Object.assign({}, distanceMeasurementDefault, {
showComponentLines: true,
xLabelOpts: labelOptsDefault,
xAngleLabelOpts: Object.assign({}, labelOptsDefault, {
horizontalOrigin: 1,
// left
verticalOrigin: 0,
// center
pixelOffset: [9, 0]
}),
yLabelOpts: Object.assign({}, labelOptsDefault, {
horizontalOrigin: -1,
// right
pixelOffset: [-9, 0]
}),
yAngleLabelOpts: Object.assign({}, labelOptsDefault, {
verticalOrigin: -1,
// top
pixelOffset: [0, 9]
})
});
const polylineMeasurementActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-measure-polyline-distance"
});
const polylineMeasurementDefault = Object.assign({}, polylineDrawingDefault, {
measureUnits: new MeasureUnits(),
labelOpts: labelOptsDefault,
labelsOpts: Object.assign({}, labelOptsDefault, {
scale: 0.8,
horizontalOrigin: 1,
// left
verticalOrigin: -1,
// tOP,
pixelOffset: [5, 5]
}),
decimals: {
distance: 2,
angle: 2
},
showLabel: true,
showAngleLabel: true,
showDistanceLabel: true,
locale: void 0,
loop: false,
autoUpdateLabelPosition: true
});
const horizontalMeasurementActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-measure-horizontal-distance"
});
const horizontalMeasurementDefault = Object.assign({}, polylineMeasurementDefault, {
dashLineOpts: {
width: 2
},
dashLinePrimitiveOpts: Object.assign({}, polylinePrimitiveOptsDefault, {
appearance: {
type: "PolylineMaterialAppearance",
options: {
material: {
fabric: {
type: "PolylineDash",
uniforms: {
color: [255, 255, 0, 255]
}
}
}
}
},
depthFailAppearance: {
type: "PolylineMaterialAppearance",
options: {
material: {
fabric: {
type: "PolylineDash",
uniforms: {
color: [255, 255, 0, 255]
}
}
}
}
}
}),
labelOpts: Object.assign({}, labelOptsDefault, {
horizontalOrigin: 1,
verticalOrigin: 1,
pixelOffset: [10, -10]
}),
labelsOpts: Object.assign({}, labelOptsDefault, {
scale: 0.8,
horizontalOrigin: 1,
// left
verticalOrigin: -1,
// tOP,
pixelOffset: [5, 5]
}),
showDashedLine: true
});
const verticalMeasurementActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-measure-vertical-distance"
});
const verticalMeasurementDefault = Object.assign({}, segmentDrawingDefault, {
labelOpts: Object.assign({}, labelOptsDefault, {
horizontalOrigin: 1,
// left
verticalOrigin: -1,
// top
pixelOffset: [10, 10]
}),
measureUnits: new MeasureUnits(),
decimals: {
distance: 2,
angle: 2
},
locale: void 0,
autoUpdateLabelPosition: true
});
const heightMeasurementActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-measure-height-from-terrain"
});
const heightMeasurementDefault = Object.assign({}, pointDrawingDefault, {
polylineOpts: polylineOptsDefault,
labelOpts: Object.assign({}, labelOptsDefault, {
horizontalOrigin: 1,
// left
verticalOrigin: -1,
// top
pixelOffset: [10, 10]
}),
editorOpts: {
pixelOffset: [16, -8],
delay: 1e3,
hideDelay: 1e3,
move: Object.assign({}, editorOptsDefault),
removeAll: Object.assign({}, editorOptsDefault, {
icon: "vc-icons-delete"
})
},
measureUnits: new MeasureUnits(),
decimals: {
distance: 2
},
locale: void 0,
primitiveOpts: polylinePrimitiveOptsDefault
});
const areaMeasurementActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-measure-area"
});
const areaMeasurementDefault = Object.assign({}, polygonDrawingDefault, {
labelOpts: labelOptsDefault,
labelsOpts: Object.assign({}, labelOptsDefault, {
scale: 0.8,
horizontalOrigin: 1,
// left
verticalOrigin: -1,
// tOP,
pixelOffset: [5, 5]
}),
showDistanceLabel: true,
showAngleLabel: true,
showLabel: true,
measureUnits: new MeasureUnits(),
decimals: {
area: 2,
distance: 2,
angle: 2
},
loop: true,
locale: void 0,
autoUpdateLabelPosition: true
});
const pointMeasurementActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-measure-point-coordinates"
});
const pointMeasurementDefault = Object.assign({}, pointDrawingDefault, {
heightReference: 1,
// 0: NONE, 1: CLAMP_TO_GROUND
measureUnits: new MeasureUnits(),
drawtip: {
show: true,
pixelOffset: [32, 48]
},
labelOpts: Object.assign({}, labelOptsDefault, {
horizontalOrigin: 1,
// left
verticalOrigin: 0,
// center
pixelOffset: [10, 0]
}),
decimals: {
lng: 6,
lat: 6,
height: 2,
slope: 3
},
locale: void 0,
showLabel: true
});
const rectangleMeasurementActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-drawing-rectangle"
});
const rectangleMeasurementDefault = Object.assign({}, areaMeasurementDefault, {
pointOpts: Object.assign({}, pointOptsDefault, {
show: false
}),
drawtip: {
show: true,
pixelOffset: [32, 32]
},
editorOpts: {
pixelOffset: [16, -8],
delay: 1e3,
hideDelay: 1e3,
move: Object.assign({}, editorOptsDefault),
removeAll: Object.assign({}, editorOptsDefault, {
icon: "vc-icons-delete"
})
},
edge: 4,
loop: false,
showAngleLabel: false
});
const regularMeasurementDefault = Object.assign({}, rectangleMeasurementDefault, {
edge: 6,
loop: true
});
const circleMeasurementDefault = Object.assign({}, rectangleMeasurementDefault, {
edge: 360,
loop: true,
showDistanceLabel: false,
showAngleLabel: false
});
const fabActionOptsDefault$2 = Object.assign({}, {});
const mainFabDefault$2 = Object.assign({}, actionOptions, {
direction: "right",
icon: "vc-icons-measurement-button",
activeIcon: "vc-icons-measurement-button",
verticalActionsAlign: "center",
hideIcon: false,
persistent: false,
modelValue: true,
hideActionOnClick: false,
color: "info"
});
const measurementType = [
"distance",
"component-distance",
"polyline",
"horizontal",
"vertical",
"height",
"area",
"point",
"rectangle",
"regular",
"circle"
];
const isValidMeasurementType = (measurements) => {
let flag = true;
measurements.forEach((measurement) => {
if (!measurementType.includes(measurement)) {
console.error(`VueCesium: unknown measurement type: ${measurement}`);
flag = false;
}
});
return flag;
};
const measurementsProps = exports('measurementsProps', {
...useDrawingFabProps,
measurements: {
type: Array,
default: () => measurementType,
validator: isValidMeasurementType
},
mainFabOpts: {
type: Object,
default: () => mainFabDefault$2
},
fabActionOpts: {
type: Object,
default: () => fabActionOptsDefault$2
},
distanceActionOpts: {
type: Object,
default: () => distanceMeasurementActionDefault
},
distanceMeasurementOpts: {
type: Object,
default: () => distanceMeasurementDefault
},
componentDistanceActionOpts: {
type: Object,
default: () => componentDistanceMeasurementActionDefault
},
componentDistanceMeasurementOpts: {
type: Object,
default: () => componentDistanceMeasurementDefault
},
polylineActionOpts: {
type: Object,
default: () => polylineMeasurementActionDefault
},
polylineMeasurementOpts: {
type: Object,
default: () => polylineMeasurementDefault
},
horizontalActionOpts: {
type: Object,
default: () => horizontalMeasurementActionDefault
},
horizontalMeasurementOpts: {
type: Object,
default: () => horizontalMeasurementDefault
},
verticalActionOpts: {
type: Object,
default: () => verticalMeasurementActionDefault
},
verticalMeasurementOpts: {
type: Object,
default: () => verticalMeasurementDefault
},
heightActionOpts: {
type: Object,
default: () => heightMeasurementActionDefault
},
heightMeasurementOpts: {
type: Object,
default: () => heightMeasurementDefault
},
areaActionOpts: {
type: Object,
default: () => areaMeasurementActionDefault
},
areaMeasurementOpts: {
type: Object,
default: () => areaMeasurementDefault
},
pointActionOpts: {
type: Object,
default: () => pointMeasurementActionDefault
},
pointMeasurementOpts: {
type: Object,
default: () => pointMeasurementDefault
},
rectangleActionOpts: {
type: Object,
default: () => rectangleMeasurementActionDefault
},
rectangleMeasurementOpts: {
type: Object,
default: () => rectangleMeasurementDefault
},
regularActionOpts: {
type: Object,
default: () => regularDrawingActionDefault
},
regularMeasurementOpts: {
type: Object,
default: () => regularMeasurementDefault
},
circleActionOpts: {
type: Object,
default: () => circleDrawingActionDefault
},
circleMeasurementOpts: {
type: Object,
default: () => circleMeasurementDefault
}
});
const defaultOptions$3 = getDefaultOptionByProps(measurementsProps);
const htmlOverlayProps = exports('htmlOverlayProps', {
...position$1,
...pixelOffset,
...show,
autoHidden: {
type: Boolean,
default: true
},
customClass: String,
teleport: Object
});
const emits$b = {
...commonEmits,
mouseenter: (evt) => true,
mouseleave: (evt) => true,
click: (evt) => true
};
var OverlayHtml = defineComponent({
name: "VcOverlayHtml",
props: htmlOverlayProps,
emits: emits$b,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VcOverlayHtml";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { $services } = commonState;
const canRender = ref(false);
const rootRef = ref(null);
const rootStyle = reactive({});
const offset = ref(null);
const position2 = ref(null);
const lastCanvasPosition = ref(null);
let unwatchFns = [];
unwatchFns.push(
watch(
() => props.position,
(val) => {
position2.value = makeCartesian3(val, $services.viewer.scene.globe.ellipsoid);
}
)
);
unwatchFns.push(
watch(
() => props.pixelOffset,
(val) => {
offset.value = makeCartesian2(val);
}
)
);
unwatchFns.push(
watch(
() => props.show,
(val) => {
rootStyle.display = val ? "block" : "none";
}
)
);
instance.createCesiumObject = async () => {
return $(rootRef);
};
instance.mount = async () => {
const { viewer } = $services;
canRender.value = true;
showPortal();
offset.value = makeCartesian2(props.pixelOffset);
position2.value = makeCartesian3(props.position, viewer.scene.globe.ellipsoid);
viewer.scene.preRender.addEventListener(onPreRender);
return true;
};
instance.unmount = async () => {
const { viewer } = $services;
viewer.scene.preRender.removeEventListener(onPreRender);
canRender.value = false;
hidePortal();
return true;
};
const onPreRender = () => {
const { viewer } = $services;
if (position2.value) {
const canvasPosition = viewer.scene.cartesianToCanvasCoordinates(position2.value, {});
if (Cesium.defined(canvasPosition) && !Cesium.Cartesian2.equals(lastCanvasPosition.value, canvasPosition)) {
rootStyle.left = canvasPosition.x + offset.value.x + "px";
rootStyle.top = canvasPosition.y + offset.value.y + "px";
if (props.autoHidden && viewer.scene.mode !== Cesium.SceneMode.SCENE2D && viewer.scene.mode !== Cesium.SceneMode.MORPHING) {
const cameraPosition = viewer.camera.position;
const cartographicPosition = viewer.scene.globe.ellipsoid.cartesianToCartographic(cameraPosition);
if (Cesium.defined(cartographicPosition)) {
let cameraHeight = cartographicPosition.height;
cameraHeight += 1 * viewer.scene.globe.ellipsoid.maximumRadius;
if (Cesium.Cartesian3.distance(cameraPosition, position2.value) > cameraHeight || !props.show) {
rootStyle.display = "none";
} else {
rootStyle.display = "block";
}
}
} else {
rootStyle.display = "block";
}
} else if (!Cesium.defined(canvasPosition)) {
rootStyle.display = "none";
}
lastCanvasPosition.value = canvasPosition;
}
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
const renderContent = () => {
if (canRender.value) {
return h(
"div",
{
ref: rootRef,
class: `vc-html-container${props.customClass ? " " + props.customClass : ""}`,
style: rootStyle,
onMouseenter,
onMouseleave,
onClick
},
hSlot(ctx.slots.default)
);
} else {
return createCommentVNode("v-if");
}
};
const onClick = (evt) => {
ctx.emit("click", evt);
};
const onMouseenter = (evt) => {
ctx.emit("mouseenter", evt);
};
const onMouseleave = (evt) => {
ctx.emit("mouseleave", evt);
};
const renderPortalContent = () => {
return renderContent();
};
const { showPortal, hidePortal, renderPortal } = usePortal(instance, rootRef, renderPortalContent);
if (props.teleport && props.teleport.to && !props.teleport.disabled) {
return renderPortal;
} else {
return () => renderContent();
}
}
});
var heatmap = {exports: {}};
/*
* heatmap.js v2.0.5 | JavaScript Heatmap Library
*
* Copyright 2008-2016 Patrick Wied <heatmapjs@patrick-wied.at> - All rights reserved.
* Dual licensed under MIT and Beerware license
*
* :: 2016-09-05 01:16
*/
heatmap.exports;
(function (module) {
(function (name, context, factory) {
// Supports UMD. AMD, CommonJS/Node.js and browser context
if (module.exports) {
module.exports = factory();
} else {
context[name] = factory();
}
})("h337", commonjsGlobal, function () {
// Heatmap Config stores default values and will be merged with instance config
var HeatmapConfig = {
defaultRadius: 40,
defaultRenderer: 'canvas2d',
defaultGradient: { 0.25: "rgb(0,0,255)", 0.55: "rgb(0,255,0)", 0.85: "yellow", 1.0: "rgb(255,0,0)"},
defaultMaxOpacity: 1,
defaultMinOpacity: 0,
defaultBlur: .85,
defaultXField: 'x',
defaultYField: 'y',
defaultValueField: 'value',
plugins: {}
};
var Store = (function StoreClosure() {
var Store = function Store(config) {
this._coordinator = {};
this._data = [];
this._radi = [];
this._min = 10;
this._max = 1;
this._xField = config['xField'] || config.defaultXField;
this._yField = config['yField'] || config.defaultYField;
this._valueField = config['valueField'] || config.defaultValueField;
if (config["radius"]) {
this._cfgRadius = config["radius"];
}
};
var defaultRadius = HeatmapConfig.defaultRadius;
Store.prototype = {
// when forceRender = false -> called from setData, omits renderall event
_organiseData: function(dataPoint, forceRender) {
var x = dataPoint[this._xField];
var y = dataPoint[this._yField];
var radi = this._radi;
var store = this._data;
var max = this._max;
var min = this._min;
var value = dataPoint[this._valueField] || 1;
var radius = dataPoint.radius || this._cfgRadius || defaultRadius;
if (!store[x]) {
store[x] = [];
radi[x] = [];
}
if (!store[x][y]) {
store[x][y] = value;
radi[x][y] = radius;
} else {
store[x][y] += value;
}
var storedVal = store[x][y];
if (storedVal > max) {
if (!forceRender) {
this._max = storedVal;
} else {
this.setDataMax(storedVal);
}
return false;
} else if (storedVal < min) {
if (!forceRender) {
this._min = storedVal;
} else {
this.setDataMin(storedVal);
}
return false;
} else {
return {
x: x,
y: y,
value: value,
radius: radius,
min: min,
max: max
};
}
},
_unOrganizeData: function() {
var unorganizedData = [];
var data = this._data;
var radi = this._radi;
for (var x in data) {
for (var y in data[x]) {
unorganizedData.push({
x: x,
y: y,
radius: radi[x][y],
value: data[x][y]
});
}
}
return {
min: this._min,
max: this._max,
data: unorganizedData
};
},
_onExtremaChange: function() {
this._coordinator.emit('extremachange', {
min: this._min,
max: this._max
});
},
addData: function() {
if (arguments[0].length > 0) {
var dataArr = arguments[0];
var dataLen = dataArr.length;
while (dataLen--) {
this.addData.call(this, dataArr[dataLen]);
}
} else {
// add to store
var organisedEntry = this._organiseData(arguments[0], true);
if (organisedEntry) {
// if it's the first datapoint initialize the extremas with it
if (this._data.length === 0) {
this._min = this._max = organisedEntry.value;
}
this._coordinator.emit('renderpartial', {
min: this._min,
max: this._max,
data: [organisedEntry]
});
}
}
return this;
},
setData: function(data) {
var dataPoints = data.data;
var pointsLen = dataPoints.length;
// reset data arrays
this._data = [];
this._radi = [];
for(var i = 0; i < pointsLen; i++) {
this._organiseData(dataPoints[i], false);
}
this._max = data.max;
this._min = data.min || 0;
this._onExtremaChange();
this._coordinator.emit('renderall', this._getInternalData());
return this;
},
removeData: function() {
// TODO: implement
},
setDataMax: function(max) {
this._max = max;
this._onExtremaChange();
this._coordinator.emit('renderall', this._getInternalData());
return this;
},
setDataMin: function(min) {
this._min = min;
this._onExtremaChange();
this._coordinator.emit('renderall', this._getInternalData());
return this;
},
setCoordinator: function(coordinator) {
this._coordinator = coordinator;
},
_getInternalData: function() {
return {
max: this._max,
min: this._min,
data: this._data,
radi: this._radi
};
},
getData: function() {
return this._unOrganizeData();
}/*,
TODO: rethink.
getValueAt: function(point) {
var value;
var radius = 100;
var x = point.x;
var y = point.y;
var data = this._data;
if (data[x] && data[x][y]) {
return data[x][y];
} else {
var values = [];
// radial search for datapoints based on default radius
for(var distance = 1; distance < radius; distance++) {
var neighbors = distance * 2 +1;
var startX = x - distance;
var startY = y - distance;
for(var i = 0; i < neighbors; i++) {
for (var o = 0; o < neighbors; o++) {
if ((i == 0 || i == neighbors-1) || (o == 0 || o == neighbors-1)) {
if (data[startY+i] && data[startY+i][startX+o]) {
values.push(data[startY+i][startX+o]);
}
} else {
continue;
}
}
}
}
if (values.length > 0) {
return Math.max.apply(Math, values);
}
}
return false;
}*/
};
return Store;
})();
var Canvas2dRenderer = (function Canvas2dRendererClosure() {
var _getColorPalette = function(config) {
var gradientConfig = config.gradient || config.defaultGradient;
var paletteCanvas = document.createElement('canvas');
var paletteCtx = paletteCanvas.getContext('2d');
paletteCanvas.width = 256;
paletteCanvas.height = 1;
var gradient = paletteCtx.createLinearGradient(0, 0, 256, 1);
for (var key in gradientConfig) {
gradient.addColorStop(key, gradientConfig[key]);
}
paletteCtx.fillStyle = gradient;
paletteCtx.fillRect(0, 0, 256, 1);
return paletteCtx.getImageData(0, 0, 256, 1).data;
};
var _getPointTemplate = function(radius, blurFactor) {
var tplCanvas = document.createElement('canvas');
var tplCtx = tplCanvas.getContext('2d');
var x = radius;
var y = radius;
tplCanvas.width = tplCanvas.height = radius*2;
if (blurFactor == 1) {
tplCtx.beginPath();
tplCtx.arc(x, y, radius, 0, 2 * Math.PI, false);
tplCtx.fillStyle = 'rgba(0,0,0,1)';
tplCtx.fill();
} else {
var gradient = tplCtx.createRadialGradient(x, y, radius*blurFactor, x, y, radius);
gradient.addColorStop(0, 'rgba(0,0,0,1)');
gradient.addColorStop(1, 'rgba(0,0,0,0)');
tplCtx.fillStyle = gradient;
tplCtx.fillRect(0, 0, 2*radius, 2*radius);
}
return tplCanvas;
};
var _prepareData = function(data) {
var renderData = [];
var min = data.min;
var max = data.max;
var radi = data.radi;
var data = data.data;
var xValues = Object.keys(data);
var xValuesLen = xValues.length;
while(xValuesLen--) {
var xValue = xValues[xValuesLen];
var yValues = Object.keys(data[xValue]);
var yValuesLen = yValues.length;
while(yValuesLen--) {
var yValue = yValues[yValuesLen];
var value = data[xValue][yValue];
var radius = radi[xValue][yValue];
renderData.push({
x: xValue,
y: yValue,
value: value,
radius: radius
});
}
}
return {
min: min,
max: max,
data: renderData
};
};
function Canvas2dRenderer(config) {
var container = config.container;
var shadowCanvas = this.shadowCanvas = document.createElement('canvas');
var canvas = this.canvas = config.canvas || document.createElement('canvas');
this._renderBoundaries = [10000, 10000, 0, 0];
var computed = getComputedStyle(config.container) || {};
canvas.className = 'heatmap-canvas';
this._width = canvas.width = shadowCanvas.width = config.width || +(computed.width.replace(/px/,''));
this._height = canvas.height = shadowCanvas.height = config.height || +(computed.height.replace(/px/,''));
this.shadowCtx = shadowCanvas.getContext('2d');
this.ctx = canvas.getContext('2d');
// @TODO:
// conditional wrapper
canvas.style.cssText = shadowCanvas.style.cssText = 'position:absolute;left:0;top:0;';
container.style.position = 'relative';
container.appendChild(canvas);
this._palette = _getColorPalette(config);
this._templates = {};
this._setStyles(config);
}
Canvas2dRenderer.prototype = {
renderPartial: function(data) {
if (data.data.length > 0) {
this._drawAlpha(data);
this._colorize();
}
},
renderAll: function(data) {
// reset render boundaries
this._clear();
if (data.data.length > 0) {
this._drawAlpha(_prepareData(data));
this._colorize();
}
},
_updateGradient: function(config) {
this._palette = _getColorPalette(config);
},
updateConfig: function(config) {
if (config['gradient']) {
this._updateGradient(config);
}
this._setStyles(config);
},
setDimensions: function(width, height) {
this._width = width;
this._height = height;
this.canvas.width = this.shadowCanvas.width = width;
this.canvas.height = this.shadowCanvas.height = height;
},
_clear: function() {
this.shadowCtx.clearRect(0, 0, this._width, this._height);
this.ctx.clearRect(0, 0, this._width, this._height);
},
_setStyles: function(config) {
this._blur = (config.blur == 0)?0:(config.blur || config.defaultBlur);
if (config.backgroundColor) {
this.canvas.style.backgroundColor = config.backgroundColor;
}
this._width = this.canvas.width = this.shadowCanvas.width = config.width || this._width;
this._height = this.canvas.height = this.shadowCanvas.height = config.height || this._height;
this._opacity = (config.opacity || 0) * 255;
this._maxOpacity = (config.maxOpacity || config.defaultMaxOpacity) * 255;
this._minOpacity = (config.minOpacity || config.defaultMinOpacity) * 255;
this._useGradientOpacity = !!config.useGradientOpacity;
},
_drawAlpha: function(data) {
var min = this._min = data.min;
var max = this._max = data.max;
var data = data.data || [];
var dataLen = data.length;
// on a point basis?
var blur = 1 - this._blur;
while(dataLen--) {
var point = data[dataLen];
var x = point.x;
var y = point.y;
var radius = point.radius;
// if value is bigger than max
// use max as value
var value = Math.min(point.value, max);
var rectX = x - radius;
var rectY = y - radius;
var shadowCtx = this.shadowCtx;
var tpl;
if (!this._templates[radius]) {
this._templates[radius] = tpl = _getPointTemplate(radius, blur);
} else {
tpl = this._templates[radius];
}
// value from minimum / value range
// => [0, 1]
var templateAlpha = (value-min)/(max-min);
// this fixes #176: small values are not visible because globalAlpha < .01 cannot be read from imageData
shadowCtx.globalAlpha = templateAlpha < .01 ? .01 : templateAlpha;
shadowCtx.drawImage(tpl, rectX, rectY);
// update renderBoundaries
if (rectX < this._renderBoundaries[0]) {
this._renderBoundaries[0] = rectX;
}
if (rectY < this._renderBoundaries[1]) {
this._renderBoundaries[1] = rectY;
}
if (rectX + 2*radius > this._renderBoundaries[2]) {
this._renderBoundaries[2] = rectX + 2*radius;
}
if (rectY + 2*radius > this._renderBoundaries[3]) {
this._renderBoundaries[3] = rectY + 2*radius;
}
}
},
_colorize: function() {
var x = this._renderBoundaries[0];
var y = this._renderBoundaries[1];
var width = this._renderBoundaries[2] - x;
var height = this._renderBoundaries[3] - y;
var maxWidth = this._width;
var maxHeight = this._height;
var opacity = this._opacity;
var maxOpacity = this._maxOpacity;
var minOpacity = this._minOpacity;
var useGradientOpacity = this._useGradientOpacity;
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (x + width > maxWidth) {
width = maxWidth - x;
}
if (y + height > maxHeight) {
height = maxHeight - y;
}
var img = this.shadowCtx.getImageData(x, y, width, height);
var imgData = img.data;
var len = imgData.length;
var palette = this._palette;
for (var i = 3; i < len; i+= 4) {
var alpha = imgData[i];
var offset = alpha * 4;
if (!offset) {
continue;
}
var finalAlpha;
if (opacity > 0) {
finalAlpha = opacity;
} else {
if (alpha < maxOpacity) {
if (alpha < minOpacity) {
finalAlpha = minOpacity;
} else {
finalAlpha = alpha;
}
} else {
finalAlpha = maxOpacity;
}
}
imgData[i-3] = palette[offset];
imgData[i-2] = palette[offset + 1];
imgData[i-1] = palette[offset + 2];
imgData[i] = useGradientOpacity ? palette[offset + 3] : finalAlpha;
}
this.ctx.putImageData(img, x, y);
this._renderBoundaries = [1000, 1000, 0, 0];
},
getValueAt: function(point) {
var value;
var shadowCtx = this.shadowCtx;
var img = shadowCtx.getImageData(point.x, point.y, 1, 1);
var data = img.data[3];
var max = this._max;
var min = this._min;
value = (Math.abs(max-min) * (data/255)) >> 0;
return value;
},
getDataURL: function() {
return this.canvas.toDataURL();
}
};
return Canvas2dRenderer;
})();
var Renderer = (function RendererClosure() {
var rendererFn = false;
if (HeatmapConfig['defaultRenderer'] === 'canvas2d') {
rendererFn = Canvas2dRenderer;
}
return rendererFn;
})();
var Util = {
merge: function() {
var merged = {};
var argsLen = arguments.length;
for (var i = 0; i < argsLen; i++) {
var obj = arguments[i];
for (var key in obj) {
merged[key] = obj[key];
}
}
return merged;
}
};
// Heatmap Constructor
var Heatmap = (function HeatmapClosure() {
var Coordinator = (function CoordinatorClosure() {
function Coordinator() {
this.cStore = {};
}
Coordinator.prototype = {
on: function(evtName, callback, scope) {
var cStore = this.cStore;
if (!cStore[evtName]) {
cStore[evtName] = [];
}
cStore[evtName].push((function(data) {
return callback.call(scope, data);
}));
},
emit: function(evtName, data) {
var cStore = this.cStore;
if (cStore[evtName]) {
var len = cStore[evtName].length;
for (var i=0; i<len; i++) {
var callback = cStore[evtName][i];
callback(data);
}
}
}
};
return Coordinator;
})();
var _connect = function(scope) {
var renderer = scope._renderer;
var coordinator = scope._coordinator;
var store = scope._store;
coordinator.on('renderpartial', renderer.renderPartial, renderer);
coordinator.on('renderall', renderer.renderAll, renderer);
coordinator.on('extremachange', function(data) {
scope._config.onExtremaChange &&
scope._config.onExtremaChange({
min: data.min,
max: data.max,
gradient: scope._config['gradient'] || scope._config['defaultGradient']
});
});
store.setCoordinator(coordinator);
};
function Heatmap() {
var config = this._config = Util.merge(HeatmapConfig, arguments[0] || {});
this._coordinator = new Coordinator();
if (config['plugin']) {
var pluginToLoad = config['plugin'];
if (!HeatmapConfig.plugins[pluginToLoad]) {
throw new Error('Plugin \''+ pluginToLoad + '\' not found. Maybe it was not registered.');
} else {
var plugin = HeatmapConfig.plugins[pluginToLoad];
// set plugin renderer and store
this._renderer = new plugin.renderer(config);
this._store = new plugin.store(config);
}
} else {
this._renderer = new Renderer(config);
this._store = new Store(config);
}
_connect(this);
}
// @TODO:
// add API documentation
Heatmap.prototype = {
addData: function() {
this._store.addData.apply(this._store, arguments);
return this;
},
removeData: function() {
this._store.removeData && this._store.removeData.apply(this._store, arguments);
return this;
},
setData: function() {
this._store.setData.apply(this._store, arguments);
return this;
},
setDataMax: function() {
this._store.setDataMax.apply(this._store, arguments);
return this;
},
setDataMin: function() {
this._store.setDataMin.apply(this._store, arguments);
return this;
},
configure: function(config) {
this._config = Util.merge(this._config, config);
this._renderer.updateConfig(this._config);
this._coordinator.emit('renderall', this._store._getInternalData());
return this;
},
repaint: function() {
this._coordinator.emit('renderall', this._store._getInternalData());
return this;
},
getData: function() {
return this._store.getData();
},
getDataURL: function() {
return this._renderer.getDataURL();
},
getValueAt: function(point) {
if (this._store.getValueAt) {
return this._store.getValueAt(point);
} else if (this._renderer.getValueAt) {
return this._renderer.getValueAt(point);
} else {
return null;
}
}
};
return Heatmap;
})();
// core
var heatmapFactory = {
create: function(config) {
return new Heatmap(config);
},
register: function(pluginKey, plugin) {
HeatmapConfig.plugins[pluginKey] = plugin;
}
};
return heatmapFactory;
});
} (heatmap));
var heatmapExports = heatmap.exports;
var h337 = /*@__PURE__*/getDefaultExportFromCjs(heatmapExports);
const entityProps = exports('entityProps', {
id: String,
name: String,
availability: Object,
...show,
description: [String, Object],
...position$1,
orientation: Object,
...viewFrom,
parent: Object,
billboard: Object,
box: Object,
corridor: Object,
cylinder: Object,
ellipse: Object,
ellipsoid: Object,
label: Object,
model: Object,
tileset: Object,
path: Object,
plane: Object,
point: Object,
polygon: Object,
polyline: Object,
properties: Object,
polylineVolume: Object,
rectangle: Object,
wall: Object,
...enableMouseEvent
});
const emits$a = {
...commonEmits,
...pickEventEmits,
definitionChanged: (property) => true,
"update:billboard": (payload) => true,
"update:box": (payload) => true,
"update:corridor": (payload) => true,
"update:cylinder": (payload) => true,
"update:ellipse": (payload) => true,
"update:ellipsoid": (payload) => true,
"update:label": (payload) => true,
"update:model": (payload) => true,
"update:path": (payload) => true,
"update:plane": (payload) => true,
"update:point": (payload) => true,
"update:polygon": (payload) => true,
"update:polyline": (payload) => true,
"update:polylineVolume": (payload) => true,
"update:rectangle": (payload) => true,
"update:tileset": (payload) => true,
"update:wall": (payload) => true
};
var Entity = defineComponent({
name: "VcEntity",
props: entityProps,
emits: emits$a,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "Entity";
instance.cesiumEvents = ["definitionChanged"];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { $services } = commonState;
const { emit } = ctx;
instance.mount = async () => {
var _a;
const entity = (_a = $services == null ? void 0 : $services.entities) == null ? void 0 : _a.add(instance.cesiumObject);
return $services == null ? void 0 : $services.entities.contains(entity);
};
instance.unmount = async () => {
var _a;
return (_a = $services == null ? void 0 : $services.entities) == null ? void 0 : _a.remove(instance.cesiumObject);
};
const updateGraphics = (graphics, emitType) => {
const listener = getInstanceListener(instance, emitType);
if (listener) {
emit(emitType, graphics);
} else {
instance.cesiumObject && (instance.cesiumObject[emitType.substring(7)] = graphics);
}
graphics && (graphics._vcParent = instance.cesiumObject);
return true;
};
Object.assign(instance.proxy, {
// private but needed by VcGraphicsXXX
__updateGraphics: updateGraphics
});
return () => {
var _a, _b;
return ctx.slots.default ? h(
"i",
{
class: kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(((_b = instance.proxy) == null ? void 0 : _b.$options.name) || ""));
};
}
});
Entity.install = (app) => {
app.component(Entity.name, Entity);
};
const _Entity = Entity;
const VcEntity = exports('VcEntity', _Entity);
var defaultProps$1 = {
imageryProvider: Object,
...rectangle,
alpha: {
type: [Number, Function],
default: 1
},
nightAlpha: {
type: [Number, Function],
default: 1
},
dayAlpha: {
type: [Number, Function],
default: 1
},
brightness: {
type: [Number, Function],
default: 1
},
contrast: {
type: [Number, Function],
default: 1
},
hue: {
type: [Number, Function],
default: 0
},
saturation: {
type: [Number, Function],
default: 1
},
gamma: {
type: [Number, Function],
default: 1
},
splitDirection: {
type: [Number, Function],
default: 0
},
minificationFilter: Number,
magnificationFilter: Number,
...show,
maximumAnisotropy: Number,
minimumTerrainLevel: Number,
maximumTerrainLevel: Number,
...cutoutRectangle,
...colorToAlpha,
colorToAlphaThreshold: {
type: Number,
default: 4e-3
},
sortOrder: Number,
vcId: String
};
const emits$9 = {
...commonEmits,
"update:imageryProvider": (payload) => true,
readyEvent: (payload) => true,
errorEvent: (payload) => true
};
const imageryLayerProps = exports('imageryLayerProps', defaultProps$1);
var ImageryLayer = defineComponent({
name: "VcLayerImagery",
props: imageryLayerProps,
emits: emits$9,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "ImageryLayer";
instance.cesiumEvents = ["readyEvent", "errorEvent"];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { $services } = commonState;
const { emit } = ctx;
instance.createCesiumObject = async () => {
const options = commonState.transformProps(props);
if (compareCesiumVersion(Cesium.VERSION, "1.104")) {
const imageryProvider = props.imageryProvider || Cesium.BingMapsImageryProvider.fromUrl(void 0, {
key: ""
});
const imageryLayer = Cesium.ImageryLayer.fromProviderAsync(imageryProvider, options);
imageryLayer.errorEvent.addEventListener((error) => {
});
return imageryLayer;
} else {
const imageryProvider = props.imageryProvider || {};
return new Cesium.ImageryLayer(imageryProvider, options);
}
};
instance.mount = async () => {
const { viewer } = $services;
const imageryLayer = instance.cesiumObject;
imageryLayer.sortOrder = props.sortOrder;
imageryLayer.vcId = props.vcId || Cesium.createGuid();
viewer.imageryLayers.add(imageryLayer);
return !viewer.isDestroyed() && viewer.imageryLayers.contains(imageryLayer);
};
instance.unmount = async () => {
const { viewer } = $services;
const imageryLayer = instance.cesiumObject;
return !viewer.isDestroyed() && viewer.imageryLayers.remove(imageryLayer);
};
const updateProvider = (provider) => {
var _a;
if (isUndefined(provider)) {
return (_a = instance.unmount) == null ? void 0 : _a.call(instance);
} else {
const imageryLayer = instance.cesiumObject;
imageryLayer._imageryProvider = provider;
const listener = getInstanceListener(instance, "update:imageryProvider");
if (listener)
emit("update:imageryProvider", provider);
}
return true;
};
Object.assign(instance.proxy, {
// private but needed by VcProviderXXX
__updateProvider: updateProvider
});
return () => {
var _a, _b;
return ctx.slots.default ? h(
"i",
{
class: kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(((_b = instance.proxy) == null ? void 0 : _b.$options.name) || "v-if"));
};
}
});
ImageryLayer.install = (app) => {
app.component(ImageryLayer.name, ImageryLayer);
};
const _ImageryLayer = ImageryLayer;
const VcLayerImagery = exports('VcLayerImagery', _ImageryLayer);
const classificationPrimitiveProps = exports('classificationPrimitiveProps', {
...geometryInstances,
...appearance,
...show,
...vertexCacheOptimize,
...interleave,
...compressVertices,
...releaseGeometryInstances,
...allowPicking,
...asynchronous,
...classificationType,
...debugShowBoundingVolume,
...debugShowShadowVolume,
...enableMouseEvent
});
var PrimitiveClassification = defineComponent({
name: "VcPrimitiveClassification",
props: classificationPrimitiveProps,
emits: primitiveEmits,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "ClassificationPrimitive";
usePrimitives(props, ctx, instance);
const name = ((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "";
return () => ctx.slots.default ? h(
"i",
{
class: kebabCase(name),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(name));
}
});
const groundPrimitiveProps = exports('groundPrimitiveProps', {
...geometryInstances,
...appearance,
...show,
...vertexCacheOptimize,
...interleave,
...compressVertices,
...releaseGeometryInstances,
...allowPicking,
...asynchronous,
...classificationType,
...debugShowBoundingVolume,
...debugShowShadowVolume,
...enableMouseEvent
});
var PrimitiveGround = defineComponent({
name: "VcPrimitiveGround",
props: groundPrimitiveProps,
emits: primitiveEmits,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "GroundPrimitive";
usePrimitives(props, ctx, instance);
const name = ((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "";
return () => ctx.slots.default ? h(
"i",
{
class: kebabCase(name),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(name));
}
});
const groundPolylinePrimitiveProps = exports('groundPolylinePrimitiveProps', {
...geometryInstances,
...appearance,
...show,
...interleave,
...compressVertices,
...releaseGeometryInstances,
...allowPicking,
...asynchronous,
...classificationType,
...debugShowBoundingVolume,
...debugShowShadowVolume,
...enableMouseEvent
});
var PrimitiveGroundPolyline = defineComponent({
name: "VcPrimitiveGroundPolyline",
props: groundPolylinePrimitiveProps,
emits: primitiveEmits,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "GroundPolylinePrimitive";
usePrimitives(props, ctx, instance);
const name = ((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "";
return () => ctx.slots.default ? h(
"i",
{
class: kebabCase(name),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(name));
}
});
const modelPrimitiveProps = exports('modelPrimitiveProps', {
...url,
basePath: String,
...show,
...modelMatrix,
...scale,
...minimumPixelSize,
...maximumScale,
...id,
...allowPicking,
...incrementallyLoadTextures,
...asynchronous,
...clampAnimations,
...shadows,
...debugShowBoundingVolume,
...debugWireframe,
...heightReference,
...scene,
...distanceDisplayCondition,
...color,
...colorBlendMode,
...colorBlendAmount,
...silhouetteColor,
...silhouetteSize,
...clippingPlanes,
dequantizeInShader: {
type: Boolean,
default: true
},
...imageBasedLightingFactor,
...lightColor,
...luminanceAtZenith,
...sphericalHarmonicCoefficients,
...specularEnvironmentMaps,
...credit,
...backFaceCulling,
showOutline: {
type: Boolean,
default: true
},
...enableMouseEvent
});
var PrimitiveModel = defineComponent({
name: "VcPrimitiveModel",
props: modelPrimitiveProps,
emits: {
...primitiveEmits,
readyEvent: (evt) => true,
texturesReadyEvent: (evt) => true,
errorEvent: (evt) => true
},
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "Model";
instance.cesiumEvents = ["readyEvent", "texturesReadyEvent", "errorEvent"];
const primitivesState = usePrimitives(props, ctx, instance);
instance.createCesiumObject = async () => {
const options = primitivesState == null ? void 0 : primitivesState.transformProps(props);
return compareCesiumVersion(Cesium.VERSION, "1.104") ? await Cesium.Model.fromGltfAsync(options) : Cesium.Model.fromGltf(options);
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const primitiveProps = exports('primitiveProps', {
...geometryInstances,
...appearance,
...depthFailAppearance,
...show,
...modelMatrix,
...vertexCacheOptimize,
...interleave,
...compressVertices,
...releaseGeometryInstances,
...allowPicking,
cull: {
type: Boolean,
default: true
},
...asynchronous,
...debugShowBoundingVolume,
...shadows,
...enableMouseEvent
});
var Primitive = defineComponent({
name: "VcPrimitive",
props: primitiveProps,
emits: primitiveEmits,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "Primitive";
usePrimitives(props, ctx, instance);
const name = ((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "";
return () => {
var _a2;
return ctx.slots.default ? h(
"i",
{
class: kebabCase(name),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(((_a2 = instance.proxy) == null ? void 0 : _a2.$options.name) || ""));
};
}
});
const emits$8 = {
...primitiveEmits,
allTilesLoaded: () => true,
initialTilesLoaded: () => true,
loadProgress: (numberOfPendingRequests, numberOfTilesProcessing) => true,
tileFailed: (url, errorMsg) => true,
tileLoad: (tile) => true,
tileUnload: (tile) => true,
tileVisible: (tile) => true
};
const tilesetPrimitiveProps = exports('tilesetPrimitiveProps', {
url: [String, Object],
...show,
...modelMatrix,
modelUpAxis: {
type: Number
// default: 1 // Cesium.Axis.Y
},
modelForwardAxis: {
type: Number
// default: 0 // Cesium.Axis.X
},
...shadows,
...maximumScreenSpaceError,
// Deprecated
maximumMemoryUsage: {
type: Number
// default: 512
},
cacheBytes: {
type: Number,
default: 536870912
},
maximumCacheOverflowBytes: {
type: Number,
default: 536870912
},
cullWithChildrenBounds: {
type: Boolean,
default: true
},
cullRequestsWhileMoving: {
type: Boolean,
default: true
},
cullRequestsWhileMovingMultiplier: {
type: Number,
default: 60
},
preloadWhenHidden: {
type: Boolean,
default: false
},
preloadFlightDestinations: {
type: Boolean,
default: true
},
preferLeaves: {
type: Boolean,
default: false
},
dynamicScreenSpaceError: {
type: Boolean,
default: false
},
dynamicScreenSpaceErrorDensity: {
type: Number,
default: 278e-5
},
dynamicScreenSpaceErrorFactor: {
type: Number,
default: 4
},
dynamicScreenSpaceErrorHeightFalloff: {
type: Number,
default: 0.25
},
progressiveResolutionHeightFraction: {
type: Number,
default: 0.3
},
foveatedScreenSpaceError: {
type: Boolean,
default: true
},
foveatedConeSize: {
type: Number,
default: 0.1
},
foveatedMinimumScreenSpaceErrorRelaxation: {
type: Number,
default: 0
},
foveatedInterpolationCallback: Function,
foveatedTimeDelay: {
type: Number,
default: 0.2
},
skipLevelOfDetail: {
type: Boolean,
default: false
},
baseScreenSpaceError: {
type: Number,
default: 1024
},
skipScreenSpaceErrorFactor: {
type: Number,
default: 16
},
skipLevels: {
type: Number,
default: 1
},
immediatelyLoadDesiredLevelOfDetail: {
type: Boolean,
default: false
},
loadSiblings: {
type: Boolean,
default: false
},
...clippingPlanes,
...classificationType,
...ellipsoid,
pointCloudShading: Object,
...imageBasedLightingFactor,
...lightColor2,
...luminanceAtZenith,
...sphericalHarmonicCoefficients,
...specularEnvironmentMaps,
...imageBasedLighting,
...backFaceCulling,
enableShowOutline: {
type: Boolean,
default: true
},
showOutline: {
type: Boolean,
default: true
},
...outlineColor,
vectorClassificationOnly: {
type: Boolean,
default: false
},
vectorKeepDecodedPositions: {
type: Boolean,
default: false
},
featureIdIndex: {
type: Number,
default: 0
},
instanceFeatureIdIndex: {
type: Number,
default: 0
},
featureIdLabel: {
type: [String, Number]
},
instanceFeatureIdLabel: {
type: [String, Number]
},
splitDirection: {
type: Number,
default: 0
//Cesium.SplitDirection.NONE
},
projectTo2D: {
type: Boolean,
default: false
},
showCreditsOnScreen: {
type: Boolean,
default: false
},
debugHeatmapTilePropertyName: String,
debugFreezeFrame: {
type: Boolean,
default: false
},
debugColorizeTiles: {
type: Boolean,
default: false
},
...debugWireframe,
...debugShowBoundingVolume,
debugShowContentBoundingVolume: {
type: Boolean,
default: false
},
debugShowViewerRequestVolume: {
type: Boolean,
default: false
},
debugShowGeometricError: {
type: Boolean,
default: false
},
debugShowRenderingStatistics: {
type: Boolean,
default: false
},
debugShowMemoryUsage: {
type: Boolean,
default: false
},
debugShowUrl: {
type: Boolean,
default: false
},
...enableMouseEvent,
enableModelExperimental: {
type: Boolean,
default: false
},
...customShader,
properties: {
type: Array
},
fragmentShader: String,
replaceFS: Boolean,
assetId: Number
});
var PrimitiveTileset = defineComponent({
name: "VcPrimitiveTileset",
props: tilesetPrimitiveProps,
emits: emits$8,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "Cesium3DTileset";
instance.cesiumEvents = ["allTilesLoaded", "initialTilesLoaded", "loadProgress", "tileFailed", "tileLoad", "tileUnload", "tileVisible"];
const primitivesStates = usePrimitives(props, ctx, instance);
instance.proxy.creatingPromise.then((obj) => {
const tileset = obj.cesiumObject;
instance.removeCallbacks.push(tileset.tileVisible.addEventListener(updateTile));
});
const updateTile = (tile) => {
const content = tile.content;
const model = content._model;
for (let i = 0; i < content.featuresLength; i++) {
const feature = content.getFeature(i);
if (props.properties && props.properties.length) {
props.properties.forEach((property) => {
if (feature.hasProperty(property["key"]) && feature.getProperty(property["key"]) === property["keyValue"]) {
feature.setProperty(property["propertyName"], property["propertyValue"]);
}
});
}
}
if (props.fragmentShader && model && model._sourcePrograms && model._rendererResources) {
Object.keys(model._sourcePrograms).forEach((key) => {
var _a;
const program = model._sourcePrograms[key];
const sourceShaders = model._rendererResources.sourceShaders;
if (props.replaceFS) {
sourceShaders[program.fragmentShader] = props.fragmentShader;
} else {
const oldFS = sourceShaders[program.fragmentShader];
const webgl2 = (_a = primitivesStates.$services.viewer.scene.context) == null ? void 0 : _a.webgl2;
sourceShaders[program.fragmentShader] = oldFS.replace(
`${webgl2 ? "out_FragColor" : "gl_FragColor"} = vec4(color, 1.0);
}`,
`${webgl2 ? "out_FragColor" : "gl_FragColor"} = vec4(color, 1.0);
${props.fragmentShader}
}
`
);
}
});
model._shouldRegenerateShaders = true;
}
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const osmBuildingsProps = exports('osmBuildingsProps', {
...defaultColor,
...tileStyle,
enableShowOutline: {
type: Boolean,
default: true
},
showOutline: {
type: Boolean,
default: true
},
...enableMouseEvent
});
var PrimitiveOsmBuildings = defineComponent({
name: "VcPrimitiveOsmBuildings",
props: osmBuildingsProps,
emits: {
...primitiveEmits
},
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VcPrimitiveOsmBuildings";
const primitivesState = usePrimitives(props, ctx, instance);
instance.createCesiumObject = async () => {
const options = primitivesState == null ? void 0 : primitivesState.transformProps(props);
options.style = options.tileStyle;
delete options.tileStyle;
return compareCesiumVersion(Cesium.VERSION, "1.104") ? await Cesium.createOsmBuildingsAsync(options) : Cesium.createOsmBuildings(options);
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const emits$7 = {
...primitiveEmits,
complete: (evt) => true
};
const particlePrimitiveProps = exports('particlePrimitiveProps', {
...show,
updateCallback: Function,
emitter: Object,
...modelMatrix,
emitterModelMatrix: Object,
emissionRate: {
type: Number,
default: 5
},
bursts: Array,
loop: {
type: Boolean,
default: true
},
scale: {
type: Number,
default: 1
},
startScale: Number,
endScale: Number,
...color,
...startColor,
...endColor,
...image,
...imageSize,
...minimumImageSize,
...maximumImageSize,
...sizeInMeters,
speed: {
type: Number,
default: 1
},
minimumSpeed: Number,
maximumSpeed: Number,
lifetime: {
type: Number,
default: Number.MAX_VALUE
},
particleLife: {
type: Number,
default: 5
},
minimumParticleLife: Number,
maximumParticleLife: Number,
mass: {
type: Number,
default: 1
},
minimumMass: Number,
maximumMass: Number,
...enableMouseEvent
});
var PrimitiveParticle = defineComponent({
name: "VcPrimitiveParticle",
props: particlePrimitiveProps,
emits: emits$7,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "ParticleSystem";
instance.cesiumEvents = ["complete"];
usePrimitives(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
var fragmentShader = `
uniform sampler2D colorTexture;
uniform vec4 u_color1;
uniform vec4 u_color2;
uniform float u_isShed;
uniform sampler2D shadowMap_depthTexture;
uniform mat4 shadowMap_matrix;
uniform vec4 shadowMap_lightPositionEC;
uniform vec3 shadowMap_lightDirectionEC;
uniform float u_radius;
uniform vec4 shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness;
uniform vec4 shadowMap_texelSizeDepthBiasAndNormalShadingSmooth;
uniform float czzj;
uniform float dis;
uniform float spzj;
uniform float mixNum;
uniform vec3 shadowMap_lightUp;
uniform vec3 shadowMap_lightDir;
uniform vec3 shadowMap_lightRight;
in vec2 v_textureCoordinates;
vec4 toEye(in vec2 uv, in float depth){
vec2 xy = vec2((uv.x * 2.0 - 1.0),(uv.y * 2.0 - 1.0));
vec4 posInCamera = czm_inverseProjection * vec4(xy, depth, 1.0);
posInCamera =posInCamera / posInCamera.w;
return posInCamera;
}
float getDepth(in vec4 depth){
float z_window = czm_unpackDepth(depth);
z_window = czm_reverseLogDepth(z_window);
float n_range = czm_depthRange.near;
float f_range = czm_depthRange.far;
return (2.0 * z_window - n_range - f_range) / (f_range - n_range);
}
float _czm_sampleShadowMap(sampler2D shadowMap, vec2 uv){
return texture(shadowMap, uv).r;
}
float _czm_shadowDepthCompare(sampler2D shadowMap, vec2 uv, float depth){
return step(depth, _czm_sampleShadowMap(shadowMap, uv));
}
float _czm_shadowVisibility(sampler2D shadowMap, czm_shadowParameters shadowParameters){
float depthBias = shadowParameters.depthBias;
float depth = shadowParameters.depth;
float nDotL = shadowParameters.nDotL;
float normalShadingSmooth = shadowParameters.normalShadingSmooth;
float darkness = shadowParameters.darkness;
vec2 uv = shadowParameters.texCoords;
depth -= depthBias;
vec2 texelStepSize = shadowParameters.texelStepSize;
float radius = 1.0;
float dx0 = -texelStepSize.x * radius;
float dy0 = -texelStepSize.y * radius;
float dx1 = texelStepSize.x * radius;
float dy1 = texelStepSize.y * radius;
float visibility =
(
_czm_shadowDepthCompare(shadowMap, uv, depth)
+_czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, dy0), depth) +
_czm_shadowDepthCompare(shadowMap, uv + vec2(0.0, dy0), depth) +
_czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, dy0), depth) +
_czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, 0.0), depth) +
_czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, 0.0), depth) +
_czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, dy1), depth) +
_czm_shadowDepthCompare(shadowMap, uv + vec2(0.0, dy1), depth) +
_czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, dy1), depth)
) * (1.0 / 9.0)
;
return visibility;
}
vec3 pointProjectOnPlane(in vec3 planeNormal, in vec3 planeOrigin, in vec3 point){
vec3 v01 = point -planeOrigin;
float d = dot(planeNormal, v01) ;
return (point - planeNormal * d);
}
float ptm(vec3 pt){
return sqrt(pt.x*pt.x + pt.y*pt.y + pt.z*pt.z);
}
void main()
{
const float PI = 3.141592653589793;
vec4 color = texture(colorTexture, v_textureCoordinates);
out_FragColor = color;
if ( u_isShed < 0.5 )
return;
vec4 currD = texture(czm_globeDepthTexture, v_textureCoordinates);
if( currD.r >= 1.0 )
return;
float depth = getDepth(currD);
vec4 positionEC = toEye(v_textureCoordinates, depth);
vec3 normalEC = vec3(1.0);
czm_shadowParameters shadowParameters;
shadowParameters.texelStepSize = shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.xy;
shadowParameters.depthBias = shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.z;
shadowParameters.normalShadingSmooth = shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.w;
shadowParameters.darkness = shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness.w;
shadowParameters.depthBias *= max(depth * 0.01, 1.0);
vec3 directionEC = normalize(positionEC.xyz - shadowMap_lightPositionEC.xyz);
float nDotL = clamp(dot(normalEC, -directionEC), 0.0, 1.0);
vec4 shadowPosition = shadowMap_matrix * positionEC;
shadowPosition /= shadowPosition.w;
if (any(lessThan(shadowPosition.xyz, vec3(0.0))) || any(greaterThan(shadowPosition.xyz, vec3(1.0))))
return;
vec4 lw = czm_inverseView* vec4(shadowMap_lightPositionEC.xyz, 1.0);
vec4 vw = czm_inverseView* vec4(positionEC.xyz, 1.0);
if(distance(lw.xyz,vw.xyz)> u_radius)
return;
shadowParameters.texCoords = shadowPosition.xy;
shadowParameters.depth = shadowPosition.z;
shadowParameters.nDotL = nDotL;
float visibility = _czm_shadowVisibility(shadowMap_depthTexture, shadowParameters);
if(visibility > 0.3 ){
out_FragColor = mix(color,vec4(u_color1.rgb, 1.0),mixNum);
}
else{
if(abs(shadowPosition.z-0.0)<0.01){
return;
}
out_FragColor = mix(color,vec4(u_color2.rgb, 1.0),mixNum);
}
}
`;
const viewshedProps = exports('viewshedProps', {
...scene,
fovH: {
type: Number,
default: 90
},
fovV: {
type: Number,
default: 60
},
offsetHeight: {
type: Number,
default: 1.8
},
visibleColor: {
type: [Object, Array, String],
default: "#00ff00"
},
invisibleColor: {
type: [Object, Array, String],
default: "#ff0000"
},
showGridLine: {
type: Boolean,
default: true
},
lineColor: {
type: [Object, Array, String],
default: "rgba(255,255,255,0.4)"
},
faceColor: {
type: [Object, Array, String],
default: "rgba(255,255,255,0.1)"
},
show: {
type: Boolean,
default: true
},
startPosition: {
type: Object
},
endPosition: {
type: Object
},
fragmentShader: {
type: String
},
uniforms: Object
});
var PrimitiveViewshed = defineComponent({
name: "VcViewshed",
props: viewshedProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VcViewshed";
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const unwatchFns = [];
let attachedViewshedStage;
unwatchFns.push(
watch(
[() => props.startPosition, () => props.endPosition],
([newStartPosition, newEndPosition]) => {
if (!instance.mounted) {
return;
}
updateViewshed(newStartPosition, newEndPosition);
},
{
deep: true
}
)
);
unwatchFns.push(
watch(
() => props.fovH,
(val) => {
if (!instance.mounted) {
return;
}
const viewshed = instance.cesiumObject;
viewshed.fovH = val;
}
)
);
unwatchFns.push(
watch(
() => props.fovV,
(val) => {
if (!instance.mounted) {
return;
}
const viewshed = instance.cesiumObject;
viewshed.fovV = val;
}
)
);
unwatchFns.push(
watch(
() => props.fovV,
(val) => {
if (!instance.mounted) {
return;
}
const viewshed = instance.cesiumObject;
viewshed.fovV = val;
}
)
);
unwatchFns.push(
watch(
() => props.offsetHeight,
(val) => {
if (!instance.mounted) {
return;
}
const viewshed = instance.cesiumObject;
viewshed.offsetHeight = val;
}
)
);
unwatchFns.push(
watch(
() => props.visibleColor,
(val) => {
if (!instance.mounted) {
return;
}
const viewshed = instance.cesiumObject;
viewshed.visibleColor = makeColor(val);
}
)
);
unwatchFns.push(
watch(
() => props.invisibleColor,
(val) => {
if (!instance.mounted) {
return;
}
const viewshed = instance.cesiumObject;
viewshed.invisibleColor = makeColor(val);
}
)
);
unwatchFns.push(
watch(
() => props.showGridLine,
(val) => {
if (!instance.mounted) {
return;
}
const viewshed = instance.cesiumObject;
viewshed.showGridLine = val;
}
)
);
unwatchFns.push(
watch(
() => props.show,
(val) => {
if (!instance.mounted) {
return;
}
const viewshed = instance.cesiumObject;
viewshed.enabled = val;
}
)
);
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns.length = 0;
});
instance.createCesiumObject = async () => {
const viewer = commonState.$services.viewer;
const viewshed = new Viewshed(viewer.scene, {
fovH: 120,
fovV: 60,
offsetHeight: 1.8,
visibleColor: makeColor(props.visibleColor),
invisibleColor: makeColor(props.invisibleColor),
showGridLine: props.showGridLine
});
viewshed._viewshedShadowMap.cascadesEnabled = false;
viewshed._viewshedShadowMap.softShadows = false;
viewshed._viewshedShadowMap.normalOffset = false;
viewshed._viewshedShadowMap.fromLightSource = false;
viewshed._viewshedShadowMap.enabled = false;
viewshed.fovH = Cesium.Math.toRadians(props.fovH);
viewshed.fovV = Cesium.Math.toRadians(props.fovV);
viewshed.offsetHeight = props.offsetHeight;
viewshed.showGridLine = props.showGridLine;
viewshed.enabled = props.show;
viewshed.lineColor = makeColor(props.lineColor);
viewshed.faceColor = makeColor(props.faceColor);
return viewshed;
};
instance.mount = async () => {
var _a;
const viewer = commonState.$services.viewer;
const viewshed = instance.cesiumObject;
const { Cartesian4, PostProcessStage, Cartesian2 } = Cesium;
const webgl2 = (_a = commonState.$services.viewer.scene.context) == null ? void 0 : _a.webgl2;
let shaderSourceText = fragmentShader;
if (!webgl2) {
shaderSourceText = shaderSourceText.replace("in vec2 v_textureCoordinates;", "varying vec2 v_textureCoordinates;");
shaderSourceText = shaderSourceText.replace(/texture\(/g, "texture2D(");
shaderSourceText = shaderSourceText.replace(/out_FragColor/g, "gl_FragColor");
}
updateViewshed(props.startPosition, props.endPosition);
attachedViewshedStage = new PostProcessStage({
fragmentShader: props.fragmentShader || shaderSourceText,
uniforms: props.uniforms || {
u_color1: function() {
return viewshed.visibleColor;
},
u_color2: function() {
return viewshed.invisibleColor;
},
u_isShed: function() {
return viewshed.shadowMap.enabled;
},
u_radius: function() {
return viewshed.lightCamera.frustum.far;
},
shadowMap_depthTexture: function() {
return viewshed.shadowMap.enabled ? viewshed.shadowMap._shadowMapTexture : viewer.scene.context.defaultTexture;
},
shadowMap_matrix: function() {
return viewshed.shadowMap._shadowMapMatrix;
},
shadowMap_cascadeSplits: function() {
return viewshed.shadowMap._cascadeSplits;
},
shadowMap_cascadeMatrices: function() {
return viewshed.shadowMap._cascadeMatrices;
},
shadowMap_lightDirectionEC: function() {
return viewshed.shadowMap._lightDirectionEC;
},
shadowMap_lightPositionEC: function() {
return viewshed.shadowMap._lightPositionEC;
},
shadowMap_cascadeDistances: function() {
return viewshed.shadowMap._cascadeDistances;
},
shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness: function() {
const e = viewshed.shadowMap._pointBias;
return Cartesian4.fromElements(e.normalOffsetScale, viewshed.shadowMap._distance, viewshed.shadowMap.maximumDistance, 0, new Cartesian4());
},
shadowMap_texelSizeDepthBiasAndNormalShadingSmooth: function() {
const e = viewshed.shadowMap._pointBias;
const t = new Cartesian2();
t.x = 1 / viewshed.shadowMap._textureSize.x;
t.y = 1 / viewshed.shadowMap._textureSize.y;
return Cartesian4.fromElements(t.x, t.y, e.depthBias, e.normalShadingSmooth, new Cartesian4());
},
czzj: function() {
return viewshed.lightCamera.frustum.fov;
},
spzj: function() {
return viewshed.lightCamera.frustum.fov;
},
mixNum: function() {
return 0.5;
},
shadowMap_lightUp: function() {
return viewshed.lightCamera.up;
},
shadowMap_lightDir: function() {
return viewshed.lightCamera.direction;
},
shadowMap_lightRight: function() {
return viewshed.lightCamera.right;
}
}
});
viewer.scene.postProcessStages.add(attachedViewshedStage);
const primitives = commonState.$services.primitives;
return primitives && primitives.add(viewshed);
};
instance.unmount = async () => {
const viewer = commonState.$services.viewer;
attachedViewshedStage && viewer.scene.postProcessStages.remove(attachedViewshedStage);
const primitives = commonState.$services.primitives;
const viewshed = instance.cesiumObject;
return primitives && primitives.remove(viewshed);
};
const updateViewshed = (startPosition, endPosition) => {
const viewshed = instance.cesiumObject;
const { Cartesian3 } = Cesium;
let diffrence = Cartesian3.subtract(endPosition, startPosition, new Cartesian3());
const magnitudeSquared = Cartesian3.magnitudeSquared(diffrence);
const distance = Cartesian3.distance(endPosition, startPosition);
if (magnitudeSquared < 0.01 || viewshed.frustum.near > distance) {
viewshed.enabled = false;
} else {
viewshed.enabled = true;
diffrence = Cartesian3.normalize(diffrence, diffrence);
const up = Cartesian3.normalize(endPosition, new Cartesian3());
viewshed.setView({
destination: startPosition,
orientation: {
direction: diffrence,
up
}
});
viewshed.frustum.far = Math.max(distance, 1.1);
}
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const timeDynamicPointCloudProps = exports('timeDynamicPointCloudProps', {
...clock,
intervals: Object,
...show,
...modelMatrix,
...shadows,
...maximumMemoryUsage,
shading: Object,
...tileStyle,
...clippingPlanes,
...enableMouseEvent
});
var PrimitiveTimeDynamicPointCloud = defineComponent({
name: "VcPrimitiveTimeDynamicPointCloud",
props: timeDynamicPointCloudProps,
emits: {
...primitiveEmits,
frameChanged: (evt) => true,
frameFailed: (evt) => true
},
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VcPrimitiveTimeDynamicPointCloud";
instance.cesiumEvents = ["frameChanged", "frameFailed"];
const primitivesState = usePrimitives(props, ctx, instance);
instance.createCesiumObject = async () => {
const options = primitivesState == null ? void 0 : primitivesState.transformProps(props);
options.style = options.tileStyle;
delete options.tileStyle;
return new Cesium.TimeDynamicPointCloud(options);
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const i3sDataProviderProps = exports('i3sDataProviderProps', {
...url,
name: String,
...show,
geoidTiledTerrainProvider: {
type: Object
},
traceFetches: {
type: Boolean,
default: false
},
cesium3dTilesetOptions: {
type: Object
},
...enableMouseEvent
});
var PrimitiveI3sDataProvider = defineComponent({
name: "VcPrimitiveI3sDataProvider",
props: i3sDataProviderProps,
emits: primitiveEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "I3SDataProvider";
usePrimitives(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const voxelPromitiveProps = exports('voxelPromitiveProps', {
provider: {
type: Object
},
...modelMatrix,
...customShader,
...clock,
...enableMouseEvent
});
var PrimitiveVoxel = defineComponent({
name: "VcPrimitiveVoxel",
props: voxelPromitiveProps,
emits: primitiveEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VoxelPrimitive";
usePrimitives(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const primitiveClusterProps = exports('primitiveClusterProps', {
...show,
enabled: {
type: Boolean,
default: true
},
pixelRange: {
type: Number,
default: 80
},
minimumClusterSize: {
type: Number,
default: 2
},
clusterBillboards: {
type: Boolean,
default: true
},
clusterLabels: {
type: Boolean,
default: true
},
clusterPoints: {
type: Boolean,
default: true
},
billboards: {
type: Array,
default: () => []
},
labels: {
type: Array,
default: () => []
},
points: {
type: Array,
default: () => []
},
...enableMouseEvent
});
var PrimitiveCluster = defineComponent({
name: "VcPrimitiveCluster",
props: primitiveClusterProps,
emits: {
...primitiveEmits,
clusterEvent: (ids, cluster) => true
},
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "VcPrimitiveCluster";
instance.cesiumEvents = ["clusterEvent"];
const primitivesState = usePrimitives(props, ctx, instance);
const unwatchFns = [];
unwatchFns.push(
watch(
() => props.show,
(val) => {
const primitiveCluster = instance.cesiumObject;
primitiveCluster.show = val;
}
)
);
unwatchFns.push(
watch(
() => props.enabled,
(val) => {
const primitiveCluster = instance.cesiumObject;
primitiveCluster.enabled = val;
}
)
);
unwatchFns.push(
watch(
() => props.minimumClusterSize,
(val) => {
const primitiveCluster = instance.cesiumObject;
primitiveCluster.minimumClusterSize = val;
}
)
);
unwatchFns.push(
watch(
() => props.clusterBillboards,
(val) => {
const primitiveCluster = instance.cesiumObject;
primitiveCluster.clusterBillboards = val;
instance.proxy["reload"]();
}
)
);
unwatchFns.push(
watch(
() => props.clusterLabels,
(val) => {
const primitiveCluster = instance.cesiumObject;
primitiveCluster.clusterLabels = val;
instance.proxy["reload"]();
}
)
);
unwatchFns.push(
watch(
() => props.clusterBillboards,
(val) => {
const primitiveCluster = instance.cesiumObject;
primitiveCluster.clusterPoints = val;
instance.proxy["reload"]();
}
)
);
unwatchFns.push(
watch(
() => cloneDeep(props.billboards),
(newVal, oldVal) => {
if (!instance.mounted) {
return;
}
const primitiveCluster = instance.cesiumObject;
const billboardCollection = primitiveCluster._billboardCollection;
if (newVal.length === oldVal.length) {
const modifies = [];
for (let i = 0; i < newVal.length; i++) {
const options = newVal[i];
const oldOptions = oldVal[i];
if (JSON.stringify(options) !== JSON.stringify(oldOptions)) {
modifies.push({
newOptions: options,
oldOptions
});
}
}
modifies.forEach((modify) => {
const modifyBillboard = billboardCollection._billboards.find((v) => (v == null ? void 0 : v.id) === modify.oldOptions.id);
modifyBillboard && Object.keys(modify.newOptions).forEach((prop) => {
if (modify.oldOptions[prop] !== modify.newOptions[prop]) {
modifyBillboard[prop] = primitivesState == null ? void 0 : primitivesState.transformProp(prop, modify.newOptions[prop]);
}
});
});
} else {
const addeds = differenceBy(newVal, oldVal, "id");
const deletes = differenceBy(oldVal, newVal, "id");
const deleteBillboards = [];
for (let i = 0; i < deletes.length; i++) {
const deleteBillboard = billboardCollection._billboards.find((v) => v.id === deletes[i].id);
deleteBillboard && deleteBillboards.push(deleteBillboard);
}
deleteBillboards.forEach((v) => {
billboardCollection.remove(v);
});
addBillboards(billboardCollection, addeds);
setTimeout(() => {
primitivesState.$services.viewer.scene.camera.changed.raiseEvent();
});
}
},
{
deep: true
}
)
);
unwatchFns.push(
watch(
() => cloneDeep(props.labels),
(newVal, oldVal) => {
if (!instance.mounted) {
return;
}
const primitiveCluster = instance.cesiumObject;
const labelCollection = primitiveCluster._labelCollection;
if (newVal.length === oldVal.length) {
const modifies = [];
for (let i = 0; i < newVal.length; i++) {
const options = newVal[i];
const oldOptions = oldVal[i];
if (JSON.stringify(options) !== JSON.stringify(oldOptions)) {
modifies.push({
newOptions: options,
oldOptions
});
}
}
modifies.forEach((modify) => {
const modifyLabel = labelCollection._labels.find((v) => v.id === modify.oldOptions.id);
modifyLabel && Object.keys(modify.newOptions).forEach((prop) => {
if (modify.oldOptions[prop] !== modify.newOptions[prop]) {
modifyLabel[prop] = primitivesState.transformProp(prop, modify.newOptions[prop]);
}
});
});
} else {
const addeds = differenceBy(newVal, oldVal, "id");
const deletes = differenceBy(oldVal, newVal, "id");
const deleteLabels = [];
for (let i = 0; i < deletes.length; i++) {
const deleteLabel = labelCollection._labels.find((v) => v.id === deletes[i].id);
deleteLabel && deleteLabels.push(deleteLabel);
}
deleteLabels.forEach((v) => {
labelCollection.remove(v);
});
addLabels(labelCollection, addeds);
setTimeout(() => {
primitivesState.$services.viewer.scene.camera.changed.raiseEvent();
});
}
},
{
deep: true
}
)
);
unwatchFns.push(
watch(
() => cloneDeep(props.points),
(newVal, oldVal) => {
if (!instance.mounted) {
return;
}
const primitiveCluster = instance.cesiumObject;
const pointCollection = primitiveCluster._pointCollection;
if (newVal.length === oldVal.length) {
const modifies = [];
for (let i = 0; i < newVal.length; i++) {
const options = newVal[i];
const oldOptions = oldVal[i];
if (JSON.stringify(options) !== JSON.stringify(oldOptions)) {
modifies.push({
newOptions: options,
oldOptions
});
}
}
modifies.forEach((modify) => {
const modifyPoint = pointCollection._pointPrimitives.find((v) => v && v.id === modify.oldOptions.id);
modifyPoint && Object.keys(modify.newOptions).forEach((prop) => {
if (modify.oldOptions[prop] !== modify.newOptions[prop]) {
modifyPoint[prop] = primitivesState.transformProp(prop, modify.newOptions[prop]);
}
});
});
} else {
const addeds = differenceBy(newVal, oldVal, "id");
const deletes = differenceBy(oldVal, newVal, "id");
const deletePoints = [];
for (let i = 0; i < deletes.length; i++) {
const deletePoint = pointCollection._pointPrimitives.find((v) => v.id === deletes[i].id);
deletePoint && deletePoints.push(deletePoint);
}
deletePoints.forEach((v) => {
pointCollection.remove(v);
});
addPoints(pointCollection, addeds);
setTimeout(() => {
primitivesState.$services.viewer.scene.camera.changed.raiseEvent();
});
}
},
{
deep: true
}
)
);
instance.createCesiumObject = async () => {
const primitiveCluster = new PrimitiveCluster$1({
show: props.show,
enabled: props.enabled,
pixelRange: props.pixelRange,
minimumClusterSize: props.minimumClusterSize,
clusterBillboards: props.clusterBillboards,
clusterLabels: props.clusterLabels,
clusterPoints: props.clusterPoints
});
const billboardCollection = new Cesium.BillboardCollection();
addBillboards(billboardCollection, props.billboards);
const labelCollection = new Cesium.LabelCollection();
addLabels(labelCollection, props.labels);
const pointCollection = new Cesium.PointPrimitiveCollection();
addPoints(pointCollection, props.points);
primitiveCluster._billboardCollection = billboardCollection;
primitiveCluster._labelCollection = labelCollection;
primitiveCluster._pointCollection = pointCollection;
primitiveCluster._initialize(primitivesState.$services.viewer.scene);
setTimeout(() => {
primitivesState.$services.viewer.scene.camera.changed.raiseEvent();
});
return primitiveCluster;
};
const addPoints = (pointCollection, points) => {
for (let i = 0; i < points.length; i++) {
const pointOptions = points[i];
pointOptions.id = Cesium.defined(pointOptions.id) ? pointOptions.id : Cesium.createGuid();
const pointOptionsTransform = primitivesState.transformProps(pointOptions);
const point = pointCollection.add(pointOptionsTransform);
addCustomProperty(point, pointOptionsTransform);
}
};
const addBillboards = (billboardCollection, billboards) => {
for (let i = 0; i < billboards.length; i++) {
const billboardOptions = billboards[i];
billboardOptions.id = Cesium.defined(billboardOptions.id) ? billboardOptions.id : Cesium.createGuid();
const billboardOptionsTransform = primitivesState.transformProps(billboardOptions);
const billboard = billboardCollection.add(billboardOptionsTransform);
addCustomProperty(billboard, billboardOptionsTransform);
}
};
const addLabels = (labelCollection, labels) => {
for (let i = 0; i < labels.length; i++) {
const labelOptions = labels[i];
labelOptions.id = Cesium.defined(labelOptions.id) ? labelOptions.id : Cesium.createGuid();
const labelOptionsTransform = primitivesState.transformProps(labelOptions);
const label = labelCollection.add(labelOptionsTransform);
addCustomProperty(label, labelOptionsTransform);
}
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns.length = 0;
});
const name = ((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "";
return () => ctx.slots.default ? h(
"i",
{
class: kebabCase(name),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(name));
}
});
const components$8 = [
PrimitiveClassification,
PrimitiveGround,
PrimitiveGroundPolyline,
PrimitiveModel,
Primitive,
PrimitiveTileset,
PrimitiveOsmBuildings,
PrimitiveI3sDataProvider,
PrimitiveVoxel,
PrimitiveTimeDynamicPointCloud,
PrimitiveParticle,
PrimitiveCluster
];
components$8.forEach((cmp) => {
cmp["install"] = (app) => {
app.component(cmp.name, cmp);
};
});
const VcPrimitiveClassification = exports('VcPrimitiveClassification', PrimitiveClassification);
const VcPrimitiveGround = exports('VcPrimitiveGround', PrimitiveGround);
const VcPrimitiveGroundPolyline = exports('VcPrimitiveGroundPolyline', PrimitiveGroundPolyline);
const VcPrimitiveModel = exports('VcPrimitiveModel', PrimitiveModel);
const VcPrimitive = exports('VcPrimitive', Primitive);
const VcPrimitiveTileset = exports('VcPrimitiveTileset', PrimitiveTileset);
const VcPrimitiveOsmBuildings = exports('VcPrimitiveOsmBuildings', PrimitiveOsmBuildings);
const VcPrimitiveParticle = exports('VcPrimitiveParticle', PrimitiveParticle);
const VcViewshed = exports('VcViewshed', PrimitiveViewshed);
const VcPrimitiveTimeDynamicPointCloud = exports('VcPrimitiveTimeDynamicPointCloud', PrimitiveTimeDynamicPointCloud);
const VcPrimitiveI3sDataProvider = exports('VcPrimitiveI3sDataProvider', PrimitiveI3sDataProvider);
const VcPrimitiveVoxel = exports('VcPrimitiveVoxel', PrimitiveVoxel);
const VcPrimitiveCluster = exports('VcPrimitiveCluster', PrimitiveCluster);
const heatmapOverlayProps = exports('heatmapOverlayProps', {
...show,
...rectangle,
min: {
type: Number,
default: 0
},
max: {
type: Number,
default: 100
},
data: Array,
options: Object,
type: {
type: String,
default: "primitive"
},
segments: {
type: Array,
default: () => []
},
projection: {
type: String,
default: "3857"
// 4326
}
});
var OverlayHeatmap = defineComponent({
name: "VcOverlayHeatmap",
props: heatmapOverlayProps,
emits: commonEmits,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "VcOverlayHeatmap";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const rootRef = ref(null);
const project = ref(null);
const defaultOptions = {
minCanvasSize: 700,
// minimum size (in pixels) for the heatmap canvas
maxCanvasSize: 2e3,
// maximum size (in pixels) for the heatmap canvas
radiusFactor: 60,
// data point size factor used if no radius is given (the greater of height and width divided by this number yields the used radius)
spacingFactor: 1.5,
// extra space around the borders (point radius multiplied by this number yields the spacing)
maxOpacity: 0.8,
// the maximum opacity used if not given in the heatmap options object
minOpacity: 0.1,
// the minimum opacity used if not given in the heatmap options object
blur: 0.85,
// the blur used if not given in the heatmap options object
gradient: {
// the gradient used if not given in the heatmap options object
".3": "blue",
".65": "yellow",
".8": "orange",
".95": "red"
},
xField: "x",
yField: "y",
valueField: "value",
container: void 0
};
const coordinates = ref();
const material = ref();
const image = ref();
const childRef = ref();
const appearance = ref();
const canRender = ref(false);
const config = ref();
const vcParent = getVcParentInstance(instance);
(_a = vcParent.proxy.creatingPromise) == null ? void 0 : _a.then(() => {
canRender.value = true;
});
const options = computed(() => {
return Object.assign({}, defaultOptions, props.options);
});
let unwatchFns = [];
unwatchFns.push(
watch(
() => image,
(val) => {
material.value.fabric.uniforms.image = val.value;
appearance.value.options.material.fabric.uniforms.image = val.value;
},
{
deep: true
}
)
);
unwatchFns.push(
watch(
() => props.data,
(newVal, oldVal) => {
if (!instance.mounted) {
return;
}
const heatmapInstance = instance.cesiumObject;
if (Array.isArray(newVal) && Array.isArray(oldVal)) {
setData(newVal, heatmapInstance);
image.value = heatmapInstance.getDataURL();
} else {
commonState.reload();
}
},
{
deep: true
}
)
);
unwatchFns.push(
watch(
() => [props.max, props.min],
(vals) => {
const heatmapInstance = instance.cesiumObject;
heatmapInstance.setDataMax(vals[0] || 0);
heatmapInstance.setDataMin(vals[1] || 0);
image.value = heatmapInstance.getDataURL();
}
)
);
unwatchFns.push(
watch(
() => [props.type, props.projection, props.rectangle],
(vals) => {
commonState.reload();
}
)
);
unwatchFns.push(
watch(
() => props.options,
(val) => {
const heatmapInstance = instance.cesiumObject;
heatmapInstance.configure(val);
image.value = heatmapInstance.getDataURL();
},
{
deep: true
}
)
);
instance.createCesiumObject = async () => {
const { WebMercatorProjection, GeographicProjection } = Cesium;
project.value = props.projection === "3857" ? new WebMercatorProjection() : new GeographicProjection();
const id = getID();
config.value = getConfig(props.rectangle);
const container = document.createElement("div");
if (Cesium.defined(id)) {
container.setAttribute("id", id);
}
container.setAttribute("style", "width: " + config.value.width + "px; height: " + config.value.height + "px; margin: 0px; display: none;");
document.body.appendChild(container);
options.value.container = container;
if (props.segments.length) {
options.value.gradient = {};
const \u0394 = props.max - props.min;
for (let i = 0; i < props.segments.length; i++) {
options.value.gradient[`${(props.segments[i][0] - props.min) / \u0394}`] = makeColor(props.segments[i][1]).toCssColorString();
}
}
const heatmapInstance = h337.create(options.value);
container.children[0].setAttribute("id", id + "-hm");
if (Array.isArray(props.data)) {
setData(props.data, heatmapInstance);
material.value = {
fabric: {
type: "Image",
uniforms: {
image: image.value,
transparent: true
}
}
};
appearance.value = {
type: "MaterialAppearance",
options: {
material: {
fabric: {
type: "Image",
uniforms: {
image: image.value
}
}
}
}
};
}
return heatmapInstance;
};
instance.unmount = async () => {
document.body.removeChild(instance.cesiumObject._config.container);
return true;
};
const getID = (len) => {
let id = "";
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < (len || 8); i++) {
id += possible.charAt(Math.floor(Math.random() * possible.length));
}
return id;
};
const getConfig = (bounds) => {
const rectangle2 = makeRectangle(bounds);
const swmb = project.value.project(new Cesium.Cartographic(rectangle2.west, rectangle2.south));
const nemb = project.value.project(new Cesium.Cartographic(rectangle2.east, rectangle2.north));
const mbb = {
north: nemb.y,
east: nemb.x,
south: swmb.y,
west: swmb.x
};
let width = mbb.east > 0 && mbb.west < 0 ? mbb.east + Math.abs(mbb.west) : Math.abs(mbb.east - mbb.west);
let height = mbb.north > 0 && mbb.south < 0 ? mbb.north + Math.abs(mbb.south) : Math.abs(mbb.north - mbb.south);
let factor = 1;
if (width > height && width > options.value.maxCanvasSize) {
factor = width / options.value.maxCanvasSize;
if (height / factor < options.value.minCanvasSize) {
factor = height / options.value.minCanvasSize;
}
} else if (height > width && height > options.value.maxCanvasSize) {
factor = height / options.value.maxCanvasSize;
if (height / factor < options.value.minCanvasSize) {
factor = width / options.value.minCanvasSize;
}
} else if (width < height && width < options.value.minCanvasSize) {
factor = width / options.value.minCanvasSize;
if (height / factor > options.value.maxCanvasSize) {
factor = height / options.value.maxCanvasSize;
}
} else if (height < width && height < options.value.minCanvasSize) {
factor = height / options.value.minCanvasSize;
if (width / factor > options.value.maxCanvasSize) {
factor = width / options.value.maxCanvasSize;
}
}
width = width / factor;
height = height / factor;
if (!Cesium.defined(options.value.radius)) {
options.value.radius = width > height ? width / options.value.radiusFactor : height / options.value.radiusFactor;
}
const spacing = (options.value.radius || 1) * options.value.spacingFactor;
const xoffset = mbb.west;
const yoffset = mbb.south;
width = Math.round(width + spacing * 2);
height = Math.round(height + spacing * 2);
mbb.west -= spacing * factor;
mbb.east += spacing * factor;
mbb.south -= spacing * factor;
mbb.north += spacing * factor;
const swmw = project.value.unproject(new Cesium.Cartesian3(mbb.west, mbb.south));
const nemw = project.value.unproject(new Cesium.Cartesian3(mbb.east, mbb.north));
const mwb = {
north: Cesium.Math.toDegrees(nemw.latitude),
east: Cesium.Math.toDegrees(nemw.longitude),
south: Cesium.Math.toDegrees(swmw.latitude),
west: Cesium.Math.toDegrees(swmw.longitude)
};
coordinates.value = mwb;
return {
height,
width,
factor,
xoffset,
yoffset,
spacing
};
};
const setData = (data, heatmapInstance) => {
if (data) {
const { height, xoffset, yoffset, factor, spacing } = config.value;
const xField = options.value.xField || "x";
const yField = options.value.yField || "y";
const valueField = options.value.valueField || "value";
const datas = [];
for (let i = 0; i < data.length; i++) {
const gp = data[i];
if (!Cesium.defined(gp.id)) {
gp.id = i;
}
const mp = project.value.project(Cesium.Cartographic.fromDegrees(gp[xField], gp[yField]));
const hp = {
[xField]: Math.round((mp.x - xoffset) / factor + spacing),
[yField]: Math.round((mp.y - yoffset) / factor + spacing),
[valueField]: void 0
};
hp[yField] = height - hp[yField];
if (gp[valueField] || gp[valueField] === 0) {
hp[valueField] = gp[valueField];
}
if (hp[valueField] > props.max || hp[valueField] < props.min) {
continue;
}
datas.push(hp);
}
heatmapInstance.setData({
min: props.min,
max: props.max,
data: datas
});
image.value = heatmapInstance.getDataURL();
}
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
Object.assign(instance.proxy, {
rootRef,
childRef
});
return () => {
if (canRender.value) {
const child = [];
if (props.type === "entity" && image.value) {
child.push(
h(_Entity, {
ref: childRef,
show: props.show,
rectangle: {
coordinates: coordinates.value,
material: material.value
}
})
);
} else if (props.type === "primitive") {
child.push(
h(VcPrimitiveGround, {
ref: childRef,
show: props.show,
appearance: appearance.value,
releaseGeometryInstances: false,
geometryInstances: new Cesium.GeometryInstance({
geometry: new Cesium.RectangleGeometry({
rectangle: makeRectangle(coordinates.value)
})
})
})
);
} else if (props.type === "imagery-layer" && image.value) {
child.push(
h(_ImageryLayer, {
ref: childRef,
show: props.show,
imageryProvider: new Cesium.SingleTileImageryProvider({
url: image.value,
rectangle: makeRectangle(coordinates.value)
})
})
);
}
return h(
"i",
{
ref: rootRef,
class: "vc-overlay-heatmap",
style: "display: none !important"
},
child
);
} else {
return createCommentVNode("v-if");
}
};
}
});
const echartsOverlayProps = exports('echartsOverlayProps', {
options: {
type: Object,
required: true
},
autoHidden: {
type: Boolean,
default: true
},
customClass: String,
coordinateSystem: {
type: String,
default: "cesium"
}
});
({
...commonEmits,
mouseenter: (evt) => true,
mouseleave: (evt) => true,
click: (evt) => true
});
var OverlayEcharts = defineComponent({
name: "VcOverlayEcharts",
props: echartsOverlayProps,
emits: ["beforeLoad", "ready", "destroyed", "mouseenter", "mouseleave", "click"],
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VcOverlayEcharts";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { $services } = commonState;
const canRender = ref(false);
const rootRef = ref();
const rootStyle = reactive({
left: "0px",
top: "0px",
pointerEvents: "none",
position: "absolute"
});
let chart;
const visible = ref(true);
let unwatchFns = [];
unwatchFns.push(
watch(
() => props.options,
(val) => {
commonState.reload();
}
)
);
instance.createCesiumObject = async () => {
return rootRef.value;
};
instance.mount = async () => {
const { viewer } = $services;
canRender.value = true;
nextTick(() => {
echarts.registerCoordinateSystem(props.coordinateSystem, getE3CoordinateSystem(viewer));
if (rootRef.value) {
chart = echarts.init(rootRef.value);
setCharts();
viewer.scene.postRender.addEventListener(onPreRender);
}
});
return true;
};
instance.unmount = async () => {
const { viewer } = $services;
viewer.scene.postRender.removeEventListener(onPreRender);
canRender.value = false;
return true;
};
const onPreRender = () => {
if (visible.value) {
const { viewer } = $services;
chart.resize({
width: viewer.canvas.width,
height: viewer.canvas.height
});
}
};
const setCharts = () => {
if (visible.value && props.options) {
chart.setOption(props.options);
}
};
const getE3CoordinateSystem = (viewer) => {
const CoordSystem = function CoordSystem2(viewer2) {
this.viewer = viewer2;
this._mapOffset = [0, 0];
};
CoordSystem.create = function(ecModel) {
ecModel.eachSeries(function(seriesModel) {
if (seriesModel.get("coordinateSystem") === props.coordinateSystem) {
seriesModel.coordinateSystem = new CoordSystem(viewer);
}
});
return [];
};
CoordSystem.getDimensionsInfo = function() {
return ["x", "y"];
};
CoordSystem.dimensions = ["x", "y"];
CoordSystem.prototype.dimensions = ["x", "y"];
CoordSystem.prototype.setMapOffset = function setMapOffset(mapOffset) {
this._mapOffset = mapOffset;
};
CoordSystem.prototype.dataToPoint = function(data) {
const result = [];
const cartesian3 = Cesium.Cartesian3.fromDegrees(data[0], data[1]);
if (!cartesian3) {
return result;
}
if (props.autoHidden) {
const up = Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(cartesian3, new Cesium.Cartesian3());
const cd = this.viewer.camera.direction;
if (Cesium.Cartesian3.dot(up, cd) >= 0) {
return result;
}
}
const coords = this.viewer.scene.cartesianToCanvasCoordinates(cartesian3);
if (!coords) {
return result;
}
return [coords.x - this._mapOffset[0], coords.y - this._mapOffset[1]];
};
CoordSystem.prototype.pointToData = function(pt) {
const mapOffset = this._mapOffset;
const ellipsoid = viewer.scene.globe.ellipsoid;
const car3 = new Cesium.Cartesian3(pt[1] + mapOffset[1], pt[2] + mapOffset[2], 0);
const cart = ellipsoid.cartesianToCartographic(car3);
return cart ? [cart.longitude, cart.latitude] : [0, 0];
};
CoordSystem.prototype.getviewerRect = function() {
const canvas = this.viewer.canvas;
return new echarts.graphic.BoundingRect(0, 0, canvas.width, canvas.height);
};
CoordSystem.prototype.getRoamTransform = function() {
return echarts.matrix.create();
};
return CoordSystem;
};
const renderContent = () => {
if (canRender.value) {
return h(
"div",
{
ref: rootRef,
class: `vc-echart-container${props.customClass ? " " + props.customClass : ""}`,
style: rootStyle,
onMouseenter,
onMouseleave,
onClick
},
hSlot(ctx.slots.default)
);
} else {
return createCommentVNode("v-if");
}
};
const onClick = (evt) => {
ctx.emit("click", evt);
};
const onMouseenter = (evt) => {
ctx.emit("mouseenter", evt);
};
const onMouseleave = (evt) => {
ctx.emit("mouseleave", evt);
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
return () => renderContent();
}
});
function getFullscreenQuad() {
const GeometryAttributes = Cesium.GeometryAttributes;
const fullscreenQuad = new Cesium.Geometry({
attributes: new GeometryAttributes({
position: new Cesium.GeometryAttribute({
componentDatatype: Cesium.ComponentDatatype.FLOAT,
componentsPerAttribute: 3,
// v3----v2
// | |
// | |
// v0----v1
// prettier-ignore
values: new Float32Array([
-1,
-1,
0,
// v0
1,
-1,
0,
// v1
1,
1,
0,
// v2
-1,
1,
0
// v3
])
}),
st: new Cesium.GeometryAttribute({
componentDatatype: Cesium.ComponentDatatype.FLOAT,
componentsPerAttribute: 2,
values: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1])
})
}),
indices: new Uint32Array([3, 2, 0, 0, 2, 1])
});
return fullscreenQuad;
}
function createTexture(options, typedArray) {
if (Cesium.defined(typedArray)) {
const source = {};
source.arrayBufferView = typedArray;
options.source = source;
}
const texture = new Cesium.Texture(options);
return texture;
}
function createFramebuffer(context, colorTexture, depthTexture) {
const framebuffer = new Cesium.Framebuffer({
context,
colorTextures: [colorTexture],
depthTexture
});
return framebuffer;
}
function createRawRenderState(options) {
const translucent = true;
const closed = false;
const existing = {
viewport: options.viewport,
depthTest: options.depthTest,
depthMask: options.depthMask,
blending: options.blending
};
const rawRenderState = Cesium.Appearance.getDefaultRenderState(translucent, closed, existing);
return rawRenderState;
}
function viewRectangleToLonLatRange(viewRectangle) {
const range = {};
const postiveWest = Cesium.Math.mod(viewRectangle.west, Cesium.Math.TWO_PI);
const postiveEast = Cesium.Math.mod(viewRectangle.east, Cesium.Math.TWO_PI);
const width = viewRectangle.width;
let longitudeMin;
let longitudeMax;
if (width > Cesium.Math.THREE_PI_OVER_TWO) {
longitudeMin = 0;
longitudeMax = Cesium.Math.TWO_PI;
} else {
if (postiveEast - postiveWest < width) {
longitudeMin = postiveWest;
longitudeMax = postiveWest + width;
} else {
longitudeMin = postiveWest;
longitudeMax = postiveEast;
}
}
range.lon = {
min: Cesium.Math.toDegrees(longitudeMin),
max: Cesium.Math.toDegrees(longitudeMax)
};
const south = viewRectangle.south;
const north = viewRectangle.north;
const height = viewRectangle.height;
const extendHeight = height > Cesium.Math.PI / 12 ? height / 2 : 0;
let extendedSouth = Cesium.Math.clampToLatitudeRange(south - extendHeight);
let extendedNorth = Cesium.Math.clampToLatitudeRange(north + extendHeight);
if (extendedSouth < -Cesium.Math.PI_OVER_THREE) {
extendedSouth = -Cesium.Math.PI_OVER_TWO;
}
if (extendedNorth > Cesium.Math.PI_OVER_THREE) {
extendedNorth = Cesium.Math.PI_OVER_TWO;
}
range.lat = {
min: Cesium.Math.toDegrees(extendedSouth),
max: Cesium.Math.toDegrees(extendedNorth)
};
return range;
}
var calculateSpeedFrag = `
precision highp float;
// the size of UV textures: width = lon, height = lat*lev
uniform sampler2D U; // eastward wind
uniform sampler2D V; // northward wind
uniform sampler2D currentParticlesPosition; // (lon, lat, lev)
uniform vec3 dimension; // (lon, lat, lev)
uniform vec3 minimum; // minimum of each dimension
uniform vec3 maximum; // maximum of each dimension
uniform vec3 interval; // interval of each dimension
// used to calculate the wind norm
uniform vec2 uSpeedRange; // (min, max);
uniform vec2 vSpeedRange;
uniform float pixelSize;
uniform float speedFactor;
in vec2 v_textureCoordinates;
vec2 mapPositionToNormalizedIndex2D(vec3 lonLatLev) {
// ensure the range of longitude and latitude
lonLatLev.x = mod(lonLatLev.x, 360.0);
lonLatLev.y = clamp(lonLatLev.y, -90.0, 90.0);
vec3 index3D = vec3(0.0);
index3D.x = (lonLatLev.x - minimum.x) / interval.x;
index3D.y = (lonLatLev.y - minimum.y) / interval.y;
index3D.z = (lonLatLev.z - minimum.z) / interval.z;
// the st texture coordinate corresponding to (col, row) index
// example
// data array is [0, 1, 2, 3, 4, 5], width = 3, height = 2
// the content of texture will be
// t 1.0
// | 3 4 5
// |
// | 0 1 2
// 0.0------1.0 s
vec2 index2D = vec2(index3D.x, index3D.z * dimension.y + index3D.y);
vec2 normalizedIndex2D = vec2(index2D.x / dimension.x, index2D.y / (dimension.y * dimension.z));
return normalizedIndex2D;
}
float getWindComponent(sampler2D componentTexture, vec3 lonLatLev) {
vec2 normalizedIndex2D = mapPositionToNormalizedIndex2D(lonLatLev);
float result = texture(componentTexture, normalizedIndex2D).r;
return result;
}
float interpolateTexture(sampler2D componentTexture, vec3 lonLatLev) {
float lon = lonLatLev.x;
float lat = lonLatLev.y;
float lev = lonLatLev.z;
float lon0 = floor(lon / interval.x) * interval.x;
float lon1 = lon0 + 1.0 * interval.x;
float lat0 = floor(lat / interval.y) * interval.y;
float lat1 = lat0 + 1.0 * interval.y;
float lon0_lat0 = getWindComponent(componentTexture, vec3(lon0, lat0, lev));
float lon1_lat0 = getWindComponent(componentTexture, vec3(lon1, lat0, lev));
float lon0_lat1 = getWindComponent(componentTexture, vec3(lon0, lat1, lev));
float lon1_lat1 = getWindComponent(componentTexture, vec3(lon1, lat1, lev));
float lon_lat0 = mix(lon0_lat0, lon1_lat0, lon - lon0);
float lon_lat1 = mix(lon0_lat1, lon1_lat1, lon - lon0);
float lon_lat = mix(lon_lat0, lon_lat1, lat - lat0);
return lon_lat;
}
vec3 linearInterpolation(vec3 lonLatLev) {
// https://en.wikipedia.org/wiki/Bilinear_interpolation
float u = interpolateTexture(U, lonLatLev);
float v = interpolateTexture(V, lonLatLev);
float w = 0.0;
return vec3(u, v, w);
}
vec2 lengthOfLonLat(vec3 lonLatLev) {
// unit conversion: meters -> longitude latitude degrees
// see https://en.wikipedia.org/wiki/Geographic_coordinate_system#Length_of_a_degree for detail
// Calculate the length of a degree of latitude and longitude in meters
float latitude = radians(lonLatLev.y);
float term1 = 111132.92;
float term2 = 559.82 * cos(2.0 * latitude);
float term3 = 1.175 * cos(4.0 * latitude);
float term4 = 0.0023 * cos(6.0 * latitude);
float latLength = term1 - term2 + term3 - term4;
float term5 = 111412.84 * cos(latitude);
float term6 = 93.5 * cos(3.0 * latitude);
float term7 = 0.118 * cos(5.0 * latitude);
float longLength = term5 - term6 + term7;
return vec2(longLength, latLength);
}
vec3 convertSpeedUnitToLonLat(vec3 lonLatLev, vec3 speed) {
vec2 lonLatLength = lengthOfLonLat(lonLatLev);
float u = speed.x / lonLatLength.x;
float v = speed.y / lonLatLength.y;
float w = 0.0;
vec3 windVectorInLonLatLev = vec3(u, v, w);
return windVectorInLonLatLev;
}
vec3 calculateSpeedByRungeKutta2(vec3 lonLatLev) {
// see https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods#Second-order_methods_with_two_stages for detail
const float h = 0.5;
float speedScaleFactor = speedFactor * pixelSize;
vec3 y_n = lonLatLev;
vec3 f_n = linearInterpolation(lonLatLev);
vec3 midpoint = y_n + 0.5 * h * convertSpeedUnitToLonLat(y_n, f_n) * speedScaleFactor;
vec3 speed = h * linearInterpolation(midpoint) * speedScaleFactor;
return speed;
}
float calculateWindNorm(vec3 speed) {
vec3 percent = vec3(0.0);
percent.x = (speed.x - uSpeedRange.x) / (uSpeedRange.y - uSpeedRange.x);
percent.y = (speed.y - vSpeedRange.x) / (vSpeedRange.y - vSpeedRange.x);
float norm = length(percent);
return norm;
}
void main() {
// texture coordinate must be normalized
vec3 lonLatLev = texture(currentParticlesPosition, v_textureCoordinates).rgb;
float speedScaleFactor = speedFactor * pixelSize;
vec3 speed = calculateSpeedByRungeKutta2(lonLatLev);
vec3 speedInLonLat = convertSpeedUnitToLonLat(lonLatLev, speed);
vec4 particleSpeed = vec4(speedInLonLat, calculateWindNorm(speed / speedScaleFactor));
out_FragColor = particleSpeed;
}
`;
const text$6 = `
uniform sampler2D currentParticlesPosition; // (lon, lat, lev)
uniform sampler2D particlesSpeed; // (u, v, w, norm) Unit converted to degrees of longitude and latitude
in vec2 v_textureCoordinates;
void main() {
// texture coordinate must be normalized
vec3 lonLatLev = texture(currentParticlesPosition, v_textureCoordinates).rgb;
vec3 speed = texture(particlesSpeed, v_textureCoordinates).rgb;
vec3 nextParticle = lonLatLev + speed;
out_FragColor = vec4(nextParticle, 0.0);
}
`;
const text$5 = `
uniform sampler2D nextParticlesPosition;
uniform sampler2D particlesSpeed; // (u, v, w, norm)
// range (min, max)
uniform vec2 lonRange;
uniform vec2 latRange;
uniform float randomCoefficient; // use to improve the pseudo-random generator
uniform float dropRate; // drop rate is a chance a particle will restart at random position to avoid degeneration
uniform float dropRateBump;
in vec2 v_textureCoordinates;
// pseudo-random generator
const vec3 randomConstants = vec3(12.9898, 78.233, 4375.85453);
const vec2 normalRange = vec2(0.0, 1.0);
float rand(vec2 seed, vec2 range) {
vec2 randomSeed = randomCoefficient * seed;
float temp = dot(randomConstants.xy, randomSeed);
temp = fract(sin(temp) * (randomConstants.z + temp));
return temp * (range.y - range.x) + range.x;
}
vec3 generateRandomParticle(vec2 seed, float lev) {
// ensure the longitude is in [0, 360]
float randomLon = mod(rand(seed, lonRange), 360.0);
float randomLat = rand(-seed, latRange);
return vec3(randomLon, randomLat, lev);
}
bool particleOutbound(vec3 particle) {
return particle.y < -90.0 || particle.y > 90.0;
}
void main() {
vec3 nextParticle = texture(nextParticlesPosition, v_textureCoordinates).rgb;
vec4 nextSpeed = texture(particlesSpeed, v_textureCoordinates);
float speedNorm = nextSpeed.a;
float particleDropRate = dropRate + dropRateBump * speedNorm;
vec2 seed1 = nextParticle.xy + v_textureCoordinates;
vec2 seed2 = nextSpeed.xy + v_textureCoordinates;
vec3 randomParticle = generateRandomParticle(seed1, nextParticle.z);
float randomNumber = rand(seed2, normalRange);
if (randomNumber < particleDropRate || particleOutbound(nextParticle)) {
out_FragColor = vec4(randomParticle, 1.0); // 1.0 means this is a random particle
} else {
out_FragColor = vec4(nextParticle, 0.0);
}
}
`;
class CustomPrimitive {
constructor(options) {
this.commandType = options.commandType;
this.geometry = options.geometry;
this.attributeLocations = options.attributeLocations;
this.primitiveType = options.primitiveType;
this.uniformMap = options.uniformMap;
this.vertexShaderSource = options.vertexShaderSource;
this.fragmentShaderSource = options.fragmentShaderSource;
this.rawRenderState = options.rawRenderState;
this.framebuffer = options.framebuffer;
this.outputTexture = options.outputTexture;
this.autoClear = Cesium.defaultValue(options.autoClear, false);
this.preExecute = options.preExecute;
this.show = true;
this.commandToExecute = void 0;
this.clearCommand = void 0;
if (this.autoClear) {
this.clearCommand = new Cesium.ClearCommand({
color: new Cesium.Color(0, 0, 0, 0),
depth: 1,
framebuffer: this.framebuffer,
pass: Cesium.Pass.OPAQUE
});
}
}
createCommand(context) {
switch (this.commandType) {
case "Draw": {
const vertexArray = Cesium.VertexArray.fromGeometry({
context,
geometry: this.geometry,
attributeLocations: this.attributeLocations,
bufferUsage: Cesium.BufferUsage.STATIC_DRAW
});
const shaderProgram = Cesium.ShaderProgram.fromCache({
context,
attributeLocations: this.attributeLocations,
vertexShaderSource: this.vertexShaderSource,
fragmentShaderSource: this.fragmentShaderSource
});
const renderState = Cesium.RenderState.fromCache(this.rawRenderState);
return new Cesium.DrawCommand({
owner: this,
vertexArray,
primitiveType: this.primitiveType,
uniformMap: this.uniformMap,
modelMatrix: Cesium.Matrix4.IDENTITY,
shaderProgram,
framebuffer: this.framebuffer,
renderState,
pass: Cesium.Pass.OPAQUE
});
}
case "Compute": {
return new Cesium.ComputeCommand({
owner: this,
fragmentShaderSource: this.fragmentShaderSource,
uniformMap: this.uniformMap,
outputTexture: this.outputTexture,
persists: true
});
}
}
}
setGeometry(context, geometry) {
this.geometry = geometry;
const vertexArray = Cesium.VertexArray.fromGeometry({
context,
geometry: this.geometry,
attributeLocations: this.attributeLocations,
bufferUsage: Cesium.BufferUsage.STATIC_DRAW
});
this.commandToExecute.vertexArray = vertexArray;
}
update(frameState) {
if (!this.show) {
return;
}
if (!Cesium.defined(this.commandToExecute)) {
this.commandToExecute = this.createCommand(frameState.context);
}
if (Cesium.defined(this.preExecute)) {
this.preExecute();
}
if (Cesium.defined(this.clearCommand)) {
frameState.commandList.push(this.clearCommand);
}
frameState.commandList.push(this.commandToExecute);
}
isDestroyed() {
return false;
}
destroy() {
if (Cesium.defined(this.commandToExecute)) {
this.commandToExecute.shaderProgram = this.commandToExecute.shaderProgram && this.commandToExecute.shaderProgram.destroy();
}
return Cesium.destroyObject(this);
}
}
class ParticlesComputing {
constructor(context, data, particleSystemOptions, viewerParameters) {
this.data = data;
this.createWindTextures(context, data);
this.createParticlesTextures(context, particleSystemOptions, viewerParameters);
this.createComputingPrimitives(data, particleSystemOptions, viewerParameters, context);
}
createWindTextures(context, data) {
const windTextureOptions = {
context,
width: data.dimensions.lon,
height: data.dimensions.lat * data.dimensions.lev,
pixelFormat: !(context == null ? void 0 : context.webgl2) ? Cesium.PixelFormat.LUMINANCE : Cesium.PixelFormat.RED,
pixelDatatype: Cesium.PixelDatatype.FLOAT,
flipY: false,
sampler: new Cesium.Sampler({
// the values of texture will not be interpolated
minificationFilter: Cesium.TextureMinificationFilter.NEAREST,
magnificationFilter: Cesium.TextureMagnificationFilter.NEAREST
})
};
this.windTextures = {
U: createTexture(windTextureOptions, data.U.array),
V: createTexture(windTextureOptions, data.V.array)
};
}
createParticlesTextures(context, particleSystemOptions, viewerParameters) {
const particlesTextureOptions = {
context,
width: particleSystemOptions.particlesTextureSize,
height: particleSystemOptions.particlesTextureSize,
pixelFormat: Cesium.PixelFormat.RGBA,
pixelDatatype: Cesium.PixelDatatype.FLOAT,
flipY: false,
sampler: new Cesium.Sampler({
// the values of texture will not be interpolated
minificationFilter: Cesium.TextureMinificationFilter.NEAREST,
magnificationFilter: Cesium.TextureMagnificationFilter.NEAREST
})
};
const particlesArray = this.randomizeParticles(particleSystemOptions.maxParticles, viewerParameters);
const zeroArray = new Float32Array(4 * particleSystemOptions.maxParticles).fill(0);
this.particlesTextures = {
previousParticlesPosition: createTexture(particlesTextureOptions, particlesArray),
currentParticlesPosition: createTexture(particlesTextureOptions, particlesArray),
nextParticlesPosition: createTexture(particlesTextureOptions, particlesArray),
postProcessingPosition: createTexture(particlesTextureOptions, particlesArray),
particlesSpeed: createTexture(particlesTextureOptions, zeroArray)
};
}
randomizeParticles(maxParticles, viewerParameters) {
const array = new Float32Array(4 * maxParticles);
for (let i = 0; i < maxParticles; i++) {
array[4 * i] = Cesium.Math.randomBetween(viewerParameters.lonRange.x, viewerParameters.lonRange.y);
array[4 * i + 1] = Cesium.Math.randomBetween(viewerParameters.latRange.x, viewerParameters.latRange.y);
array[4 * i + 2] = Cesium.Math.randomBetween(this.data.lev.min, this.data.lev.max);
array[4 * i + 3] = 0;
}
return array;
}
destroyParticlesTextures() {
Object.keys(this.particlesTextures).forEach((key) => {
this.particlesTextures[key].destroy();
});
}
createComputingPrimitives(data, particleSystemOptions, viewerParameters, context) {
const webgl2 = context == null ? void 0 : context.webgl2;
let calculateSpeedFragText = calculateSpeedFrag;
if (!webgl2) {
calculateSpeedFragText = calculateSpeedFragText.replace("in vec2 v_textureCoordinates;", "varying vec2 v_textureCoordinates;");
calculateSpeedFragText = calculateSpeedFragText.replace(/texture\(/g, "texture2D(");
calculateSpeedFragText = calculateSpeedFragText.replace(/out_FragColor/g, "gl_FragColor");
}
let updatePositionFragText = text$6;
if (!webgl2) {
updatePositionFragText = updatePositionFragText.replace("in vec2 v_textureCoordinates;", "varying vec2 v_textureCoordinates;");
updatePositionFragText = updatePositionFragText.replace(/texture\(/g, "texture2D(");
updatePositionFragText = updatePositionFragText.replace(/out_FragColor/g, "gl_FragColor");
}
let postProcessingPositionFragText = text$5;
if (!webgl2) {
postProcessingPositionFragText = postProcessingPositionFragText.replace("in vec2 v_textureCoordinates;", "varying vec2 v_textureCoordinates;");
postProcessingPositionFragText = postProcessingPositionFragText.replace(/texture\(/g, "texture2D(");
postProcessingPositionFragText = postProcessingPositionFragText.replace(/out_FragColor/g, "gl_FragColor");
}
const dimension = new Cesium.Cartesian3(data.dimensions.lon, data.dimensions.lat, data.dimensions.lev);
const minimum = new Cesium.Cartesian3(data.lon.min, data.lat.min, data.lev.min);
const maximum = new Cesium.Cartesian3(data.lon.max, data.lat.max, data.lev.max);
const interval = new Cesium.Cartesian3(
(maximum.x - minimum.x) / (dimension.x - 1),
(maximum.y - minimum.y) / (dimension.y - 1),
dimension.z > 1 ? (maximum.z - minimum.z) / (dimension.z - 1) : 1
);
const uSpeedRange = new Cesium.Cartesian2(data.U.min, data.U.max);
const vSpeedRange = new Cesium.Cartesian2(data.V.min, data.V.max);
const that = this;
this.primitives = {
calculateSpeed: new CustomPrimitive({
commandType: "Compute",
uniformMap: {
U: function() {
return that.windTextures.U;
},
V: function() {
return that.windTextures.V;
},
currentParticlesPosition: function() {
return that.particlesTextures.currentParticlesPosition;
},
dimension: function() {
return dimension;
},
minimum: function() {
return minimum;
},
maximum: function() {
return maximum;
},
interval: function() {
return interval;
},
uSpeedRange: function() {
return uSpeedRange;
},
vSpeedRange: function() {
return vSpeedRange;
},
pixelSize: function() {
return viewerParameters.pixelSize;
},
speedFactor: function() {
return particleSystemOptions.speedFactor;
}
},
fragmentShaderSource: new Cesium.ShaderSource({
sources: [calculateSpeedFragText]
}),
outputTexture: this.particlesTextures.particlesSpeed,
preExecute: function() {
const temp = that.particlesTextures.previousParticlesPosition;
that.particlesTextures.previousParticlesPosition = that.particlesTextures.currentParticlesPosition;
that.particlesTextures.currentParticlesPosition = that.particlesTextures.postProcessingPosition;
that.particlesTextures.postProcessingPosition = temp;
that.primitives.calculateSpeed.commandToExecute.outputTexture = that.particlesTextures.particlesSpeed;
}
}),
updatePosition: new CustomPrimitive({
commandType: "Compute",
uniformMap: {
currentParticlesPosition: function() {
return that.particlesTextures.currentParticlesPosition;
},
particlesSpeed: function() {
return that.particlesTextures.particlesSpeed;
}
},
fragmentShaderSource: new Cesium.ShaderSource({
sources: [updatePositionFragText]
}),
outputTexture: this.particlesTextures.nextParticlesPosition,
preExecute: function() {
that.primitives.updatePosition.commandToExecute.outputTexture = that.particlesTextures.nextParticlesPosition;
}
}),
postProcessingPosition: new CustomPrimitive({
commandType: "Compute",
uniformMap: {
nextParticlesPosition: function() {
return that.particlesTextures.nextParticlesPosition;
},
particlesSpeed: function() {
return that.particlesTextures.particlesSpeed;
},
lonRange: function() {
return viewerParameters.lonRange;
},
latRange: function() {
return viewerParameters.latRange;
},
randomCoefficient: function() {
const randomCoefficient = Math.random();
return randomCoefficient;
},
dropRate: function() {
return particleSystemOptions.dropRate;
},
dropRateBump: function() {
return particleSystemOptions.dropRateBump;
}
},
fragmentShaderSource: new Cesium.ShaderSource({
sources: [postProcessingPositionFragText]
}),
outputTexture: this.particlesTextures.postProcessingPosition,
preExecute: function() {
that.primitives.postProcessingPosition.commandToExecute.outputTexture = that.particlesTextures.postProcessingPosition;
}
})
};
}
}
const text$4 = `
in vec2 st;
// it is not normal itself, but used to control lines drawing
in vec3 normal; // (point to use, offset sign, not used component)
uniform sampler2D previousParticlesPosition;
uniform sampler2D currentParticlesPosition;
uniform sampler2D postProcessingPosition;
uniform float particleHeight;
uniform float aspect;
uniform float pixelSize;
uniform float lineWidth;
struct adjacentPoints {
vec4 previous;
vec4 current;
vec4 next;
};
vec3 convertCoordinate(vec3 lonLatLev) {
// WGS84 (lon, lat, lev) -> ECEF (x, y, z)
// read https://en.wikipedia.org/wiki/Geographic_coordinate_conversion#From_geodetic_to_ECEF_coordinates for detail
// WGS 84 geometric constants
float a = 6378137.0; // Semi-major axis
float b = 6356752.3142; // Semi-minor axis
float e2 = 6.69437999014e-3; // First eccentricity squared
float latitude = radians(lonLatLev.y);
float longitude = radians(lonLatLev.x);
float cosLat = cos(latitude);
float sinLat = sin(latitude);
float cosLon = cos(longitude);
float sinLon = sin(longitude);
float N_Phi = a / sqrt(1.0 - e2 * sinLat * sinLat);
float h = particleHeight; // it should be high enough otherwise the particle may not pass the terrain depth test
vec3 cartesian = vec3(0.0);
cartesian.x = (N_Phi + h) * cosLat * cosLon;
cartesian.y = (N_Phi + h) * cosLat * sinLon;
cartesian.z = ((b * b) / (a * a) * N_Phi + h) * sinLat;
return cartesian;
}
vec4 calculateProjectedCoordinate(vec3 lonLatLev) {
// the range of longitude in Cesium is [-180, 180] but the range of longitude in the NetCDF file is [0, 360]
// [0, 180] is corresponding to [0, 180] and [180, 360] is corresponding to [-180, 0]
lonLatLev.x = mod(lonLatLev.x + 180.0, 360.0) - 180.0;
vec3 particlePosition = convertCoordinate(lonLatLev);
vec4 projectedCoordinate = czm_modelViewProjection * vec4(particlePosition, 1.0);
return projectedCoordinate;
}
vec4 calculateOffsetOnNormalDirection(vec4 pointA, vec4 pointB, float offsetSign) {
vec2 aspectVec2 = vec2(aspect, 1.0);
vec2 pointA_XY = (pointA.xy / pointA.w) * aspectVec2;
vec2 pointB_XY = (pointB.xy / pointB.w) * aspectVec2;
float offsetLength = lineWidth / 2.0;
vec2 direction = normalize(pointB_XY - pointA_XY);
vec2 normalVector = vec2(-direction.y, direction.x);
normalVector.x = normalVector.x / aspect;
normalVector = offsetLength * normalVector;
vec4 offset = vec4(offsetSign * normalVector, 0.0, 0.0);
return offset;
}
vec4 calculateOffsetOnMiterDirection(adjacentPoints projectedCoordinates, float offsetSign) {
vec2 aspectVec2 = vec2(aspect, 1.0);
vec4 PointA = projectedCoordinates.previous;
vec4 PointB = projectedCoordinates.current;
vec4 PointC = projectedCoordinates.next;
vec2 pointA_XY = (PointA.xy / PointA.w) * aspectVec2;
vec2 pointB_XY = (PointB.xy / PointB.w) * aspectVec2;
vec2 pointC_XY = (PointC.xy / PointC.w) * aspectVec2;
vec2 AB = normalize(pointB_XY - pointA_XY);
vec2 BC = normalize(pointC_XY - pointB_XY);
vec2 normalA = vec2(-AB.y, AB.x);
vec2 tangent = normalize(AB + BC);
vec2 miter = vec2(-tangent.y, tangent.x);
float offsetLength = lineWidth / 2.0;
float projection = dot(miter, normalA);
vec4 offset = vec4(0.0);
// avoid to use values that are too small
if (projection > 0.1) {
float miterLength = offsetLength / projection;
offset = vec4(offsetSign * miter * miterLength, 0.0, 0.0);
offset.x = offset.x / aspect;
} else {
offset = calculateOffsetOnNormalDirection(PointB, PointC, offsetSign);
}
return offset;
}
void main() {
vec2 particleIndex = st;
vec3 previousPosition = texture(previousParticlesPosition, particleIndex).rgb;
vec3 currentPosition = texture(currentParticlesPosition, particleIndex).rgb;
vec3 nextPosition = texture(postProcessingPosition, particleIndex).rgb;
float isAnyRandomPointUsed = texture(postProcessingPosition, particleIndex).a +
texture(currentParticlesPosition, particleIndex).a +
texture(previousParticlesPosition, particleIndex).a;
adjacentPoints projectedCoordinates;
if (isAnyRandomPointUsed > 0.0) {
projectedCoordinates.previous = calculateProjectedCoordinate(previousPosition);
projectedCoordinates.current = projectedCoordinates.previous;
projectedCoordinates.next = projectedCoordinates.previous;
} else {
projectedCoordinates.previous = calculateProjectedCoordinate(previousPosition);
projectedCoordinates.current = calculateProjectedCoordinate(currentPosition);
projectedCoordinates.next = calculateProjectedCoordinate(nextPosition);
}
int pointToUse = int(normal.x);
float offsetSign = normal.y;
vec4 offset = vec4(0.0);
// render lines with triangles and miter joint
// read https://blog.scottlogic.com/2019/11/18/drawing-lines-with-webgl.html for detail
if (pointToUse == -1) {
offset = pixelSize * calculateOffsetOnNormalDirection(projectedCoordinates.previous, projectedCoordinates.current, offsetSign);
gl_Position = projectedCoordinates.previous + offset;
} else {
if (pointToUse == 0) {
offset = pixelSize * calculateOffsetOnMiterDirection(projectedCoordinates, offsetSign);
gl_Position = projectedCoordinates.current + offset;
} else {
if (pointToUse == 1) {
offset = pixelSize * calculateOffsetOnNormalDirection(projectedCoordinates.current, projectedCoordinates.next, offsetSign);
gl_Position = projectedCoordinates.next + offset;
} else {
}
}
}
}
`;
const text$3 = `
void main() {
const vec4 white = vec4(1.0);
out_FragColor = white;
}
`;
const text$2 = `
in vec3 position;
in vec2 st;
out vec2 textureCoordinate;
void main() {
textureCoordinate = st;
gl_Position = vec4(position, 1.0);
}
`;
const text$1 = `
uniform sampler2D segmentsColorTexture;
uniform sampler2D segmentsDepthTexture;
uniform sampler2D currentTrailsColor;
uniform sampler2D trailsDepthTexture;
uniform float fadeOpacity;
in vec2 textureCoordinate;
void main() {
vec4 pointsColor = texture(segmentsColorTexture, textureCoordinate);
vec4 trailsColor = texture(currentTrailsColor, textureCoordinate);
trailsColor = floor(fadeOpacity * 255.0 * trailsColor) / 255.0; // make sure the trailsColor will be strictly decreased
float pointsDepth = texture(segmentsDepthTexture, textureCoordinate).r;
float trailsDepth = texture(trailsDepthTexture, textureCoordinate).r;
float globeDepth = czm_unpackDepth(texture(czm_globeDepthTexture, textureCoordinate));
out_FragColor = vec4(0.0);
if (pointsDepth < globeDepth) {
out_FragColor = out_FragColor + pointsColor;
}
if (trailsDepth < globeDepth) {
out_FragColor = out_FragColor + trailsColor;
}
gl_FragDepth = min(pointsDepth, trailsDepth);
}
`;
const text = `
uniform sampler2D trailsColorTexture;
uniform sampler2D trailsDepthTexture;
in vec2 textureCoordinate;
void main() {
vec4 trailsColor = texture(trailsColorTexture, textureCoordinate);
float trailsDepth = texture(trailsDepthTexture, textureCoordinate).r;
float globeDepth = czm_unpackDepth(texture(czm_globeDepthTexture, textureCoordinate));
if (trailsDepth < globeDepth) {
out_FragColor = trailsColor;
} else {
out_FragColor = vec4(0.0);
}
}
`;
class ParticlesRendering {
constructor(context, data, particleSystemOptions, viewerParameters, particlesComputing) {
this.createRenderingTextures(context, data);
this.createRenderingFramebuffers(context);
this.createRenderingPrimitives(context, particleSystemOptions, viewerParameters, particlesComputing);
}
createRenderingTextures(context, data) {
const colorTextureOptions = {
context,
width: context.drawingBufferWidth,
height: context.drawingBufferHeight,
pixelFormat: Cesium.PixelFormat.RGBA,
pixelDatatype: Cesium.PixelDatatype.UNSIGNED_BYTE
};
const depthTextureOptions = {
context,
width: context.drawingBufferWidth,
height: context.drawingBufferHeight,
pixelFormat: Cesium.PixelFormat.DEPTH_COMPONENT,
pixelDatatype: Cesium.PixelDatatype.UNSIGNED_INT
};
this.textures = {
segmentsColor: createTexture(colorTextureOptions),
segmentsDepth: createTexture(depthTextureOptions),
currentTrailsColor: createTexture(colorTextureOptions),
currentTrailsDepth: createTexture(depthTextureOptions),
nextTrailsColor: createTexture(colorTextureOptions),
nextTrailsDepth: createTexture(depthTextureOptions)
};
}
createRenderingFramebuffers(context) {
this.framebuffers = {
segments: createFramebuffer(context, this.textures.segmentsColor, this.textures.segmentsDepth),
currentTrails: createFramebuffer(context, this.textures.currentTrailsColor, this.textures.currentTrailsDepth),
nextTrails: createFramebuffer(context, this.textures.nextTrailsColor, this.textures.nextTrailsDepth)
};
}
createSegmentsGeometry(particleSystemOptions) {
const repeatVertex = 6;
const typedArray = [];
for (let s = 0; s < particleSystemOptions.particlesTextureSize; s++) {
for (let t = 0; t < particleSystemOptions.particlesTextureSize; t++) {
for (let i = 0; i < repeatVertex; i++) {
typedArray.push(s / particleSystemOptions.particlesTextureSize);
typedArray.push(t / particleSystemOptions.particlesTextureSize);
}
}
}
const st = new Float32Array(typedArray);
const normalArray = [];
const pointToUse = [-1, 0, 1];
const offsetSign = [-1, 1];
for (let i = 0; i < particleSystemOptions.maxParticles; i++) {
for (let j = 0; j < pointToUse.length; j++) {
for (let k = 0; k < offsetSign.length; k++) {
normalArray.push(pointToUse[j]);
normalArray.push(offsetSign[k]);
normalArray.push(0);
}
}
}
const normal = new Float32Array(normalArray);
const indexSize = 12 * particleSystemOptions.maxParticles;
const vertexIndexes = new Uint32Array(indexSize);
for (let i = 0, j = 0, vertex = 0; i < particleSystemOptions.maxParticles; i++) {
vertexIndexes[j++] = vertex + 0;
vertexIndexes[j++] = vertex + 1;
vertexIndexes[j++] = vertex + 2;
vertexIndexes[j++] = vertex + 2;
vertexIndexes[j++] = vertex + 1;
vertexIndexes[j++] = vertex + 3;
vertexIndexes[j++] = vertex + 2;
vertexIndexes[j++] = vertex + 4;
vertexIndexes[j++] = vertex + 3;
vertexIndexes[j++] = vertex + 4;
vertexIndexes[j++] = vertex + 3;
vertexIndexes[j++] = vertex + 5;
vertex += repeatVertex;
}
const GeometryAttributes = Cesium.GeometryAttributes;
const geometry = new Cesium.Geometry({
attributes: new GeometryAttributes({
st: new Cesium.GeometryAttribute({
componentDatatype: Cesium.ComponentDatatype.FLOAT,
componentsPerAttribute: 2,
values: st
}),
normal: new Cesium.GeometryAttribute({
componentDatatype: Cesium.ComponentDatatype.FLOAT,
componentsPerAttribute: 3,
values: normal
})
}),
indices: vertexIndexes
});
return geometry;
}
createRenderingPrimitives(context, particleSystemOptions, viewerParameters, particlesComputing) {
const that = this;
const webgl2 = context == null ? void 0 : context.webgl2;
let segmentDrawVertText = text$4;
if (!webgl2) {
segmentDrawVertText = segmentDrawVertText.replace("in vec2 st;", "attribute vec2 st;");
segmentDrawVertText = segmentDrawVertText.replace("in vec3 normal;", "attribute vec3 normal;");
segmentDrawVertText = segmentDrawVertText.replace(/texture\(/g, "texture2D(");
}
let segmentDrawFragText = text$3;
if (!webgl2) {
segmentDrawFragText = segmentDrawFragText.replace(/out_FragColor/g, "gl_FragColor");
}
let fullscreenVertText = text$2;
if (!webgl2) {
fullscreenVertText = fullscreenVertText.replace("out vec2 textureCoordinate;", "varying vec2 textureCoordinate;");
fullscreenVertText = fullscreenVertText.replace("in vec3 position;", "attribute vec3 position;");
fullscreenVertText = fullscreenVertText.replace("in vec2 st;", "attribute vec2 st;");
}
let trailDrawFragText = text$1;
if (!webgl2) {
trailDrawFragText = trailDrawFragText.replace("in vec2 textureCoordinate;", "varying vec2 textureCoordinate;");
trailDrawFragText = trailDrawFragText.replace(/out_FragColor/g, "gl_FragColor");
trailDrawFragText = trailDrawFragText.replace(/gl_FragDepth/g, "gl_FragDepthEXT");
trailDrawFragText = trailDrawFragText.replace(/texture\(/g, "texture2D(");
}
let screenDrawFragText = text;
if (!webgl2) {
screenDrawFragText = screenDrawFragText.replace("in vec2 textureCoordinate;", "varying vec2 textureCoordinate;");
screenDrawFragText = screenDrawFragText.replace(/out_FragColor/g, "gl_FragColor");
screenDrawFragText = screenDrawFragText.replace(/texture\(/g, "texture2D(");
}
this.primitives = {
segments: new CustomPrimitive({
commandType: "Draw",
attributeLocations: {
st: 0,
normal: 1
},
geometry: this.createSegmentsGeometry(particleSystemOptions),
primitiveType: Cesium.PrimitiveType.TRIANGLES,
uniformMap: {
previousParticlesPosition: function() {
return particlesComputing.particlesTextures.previousParticlesPosition;
},
currentParticlesPosition: function() {
return particlesComputing.particlesTextures.currentParticlesPosition;
},
postProcessingPosition: function() {
return particlesComputing.particlesTextures.postProcessingPosition;
},
aspect: function() {
return context.drawingBufferWidth / context.drawingBufferHeight;
},
pixelSize: function() {
return viewerParameters.pixelSize;
},
lineWidth: function() {
return particleSystemOptions.lineWidth;
},
particleHeight: function() {
return particleSystemOptions.particleHeight;
}
},
vertexShaderSource: new Cesium.ShaderSource({
sources: [segmentDrawVertText]
}),
fragmentShaderSource: new Cesium.ShaderSource({
sources: [segmentDrawFragText]
}),
rawRenderState: createRawRenderState({
// undefined value means let Cesium deal with it
viewport: void 0,
depthTest: {
enabled: true
},
depthMask: true
}),
framebuffer: this.framebuffers.segments,
autoClear: true
}),
trails: new CustomPrimitive({
commandType: "Draw",
attributeLocations: {
position: 0,
st: 1
},
geometry: getFullscreenQuad(),
primitiveType: Cesium.PrimitiveType.TRIANGLES,
uniformMap: {
segmentsColorTexture: function() {
return that.textures.segmentsColor;
},
segmentsDepthTexture: function() {
return that.textures.segmentsDepth;
},
currentTrailsColor: function() {
return that.framebuffers.currentTrails.getColorTexture(0);
},
trailsDepthTexture: function() {
return that.framebuffers.currentTrails.depthTexture;
},
fadeOpacity: function() {
return particleSystemOptions.fadeOpacity;
}
},
// prevent Cesium from writing depth because the depth here should be written manually
vertexShaderSource: new Cesium.ShaderSource({
defines: ["DISABLE_GL_POSITION_LOG_DEPTH"],
sources: [fullscreenVertText]
}),
fragmentShaderSource: new Cesium.ShaderSource({
defines: ["DISABLE_LOG_DEPTH_FRAGMENT_WRITE"],
sources: [trailDrawFragText]
}),
rawRenderState: createRawRenderState({
viewport: void 0,
depthTest: {
enabled: true,
func: Cesium.DepthFunction.ALWAYS
// always pass depth test for full control of depth information
},
depthMask: true
}),
framebuffer: this.framebuffers.nextTrails,
autoClear: true,
preExecute: function() {
const temp = that.framebuffers.currentTrails;
that.framebuffers.currentTrails = that.framebuffers.nextTrails;
that.framebuffers.nextTrails = temp;
that.primitives.trails.commandToExecute.framebuffer = that.framebuffers.nextTrails;
that.primitives.trails.clearCommand.framebuffer = that.framebuffers.nextTrails;
}
}),
screen: new CustomPrimitive({
commandType: "Draw",
attributeLocations: {
position: 0,
st: 1
},
geometry: getFullscreenQuad(),
primitiveType: Cesium.PrimitiveType.TRIANGLES,
uniformMap: {
trailsColorTexture: function() {
return that.framebuffers.nextTrails.getColorTexture(0);
},
trailsDepthTexture: function() {
return that.framebuffers.nextTrails.depthTexture;
}
},
// prevent Cesium from writing depth because the depth here should be written manually
vertexShaderSource: new Cesium.ShaderSource({
defines: ["DISABLE_GL_POSITION_LOG_DEPTH"],
sources: [fullscreenVertText]
}),
fragmentShaderSource: new Cesium.ShaderSource({
defines: ["DISABLE_LOG_DEPTH_FRAGMENT_WRITE"],
sources: [screenDrawFragText]
}),
rawRenderState: createRawRenderState({
viewport: void 0,
depthTest: {
enabled: false
},
depthMask: true,
blending: {
enabled: true
}
}),
framebuffer: void 0
// undefined value means let Cesium deal with it
})
};
}
}
class ParticleSystem {
constructor(context, data, particleSystemOptions, viewerParameters) {
this.context = context;
this.data = data;
this.particleSystemOptions = particleSystemOptions;
this.viewerParameters = viewerParameters;
this.particlesComputing = new ParticlesComputing(this.context, this.data, this.particleSystemOptions, this.viewerParameters);
this.particlesRendering = new ParticlesRendering(
this.context,
this.data,
this.particleSystemOptions,
this.viewerParameters,
this.particlesComputing
);
}
canvasResize(context) {
this.particlesComputing.destroyParticlesTextures();
Object.keys(this.particlesComputing.windTextures).forEach((key) => {
this.particlesComputing.windTextures[key].destroy();
});
Object.keys(this.particlesRendering.framebuffers).forEach((key) => {
this.particlesRendering.framebuffers[key].destroy();
});
this.context = context;
this.particlesComputing = new ParticlesComputing(this.context, this.data, this.particleSystemOptions, this.viewerParameters);
this.particlesRendering = new ParticlesRendering(
this.context,
this.data,
this.particleSystemOptions,
this.viewerParameters,
this.particlesComputing
);
}
clearFramebuffers() {
const clearCommand = new Cesium.ClearCommand({
color: new Cesium.Color(0, 0, 0, 0),
depth: 1,
framebuffer: void 0,
pass: Cesium.Pass.OPAQUE
});
Object.keys(this.particlesRendering.framebuffers).forEach((key) => {
clearCommand.framebuffer = this.particlesRendering.framebuffers[key];
clearCommand.execute(this.context);
});
}
refreshParticles(maxParticlesChanged) {
this.clearFramebuffers();
this.particlesComputing.destroyParticlesTextures();
this.particlesComputing.createParticlesTextures(this.context, this.particleSystemOptions, this.viewerParameters);
if (maxParticlesChanged) {
const geometry = this.particlesRendering.createSegmentsGeometry(this.particleSystemOptions);
this.particlesRendering.primitives.segments.geometry = geometry;
const vertexArray = Cesium.VertexArray.fromGeometry({
context: this.context,
geometry,
attributeLocations: this.particlesRendering.primitives.segments.attributeLocations,
bufferUsage: Cesium.BufferUsage.STATIC_DRAW
});
this.particlesRendering.primitives.segments.commandToExecute.vertexArray = vertexArray;
}
}
applyParticleSystemOptions(particleSystemOptions) {
let maxParticlesChanged = false;
if (this.particleSystemOptions.maxParticles !== particleSystemOptions.maxParticles) {
maxParticlesChanged = true;
}
Object.keys(particleSystemOptions).forEach((key) => {
this.particleSystemOptions[key] = particleSystemOptions[key];
});
this.refreshParticles(maxParticlesChanged);
}
applyViewerParameters(viewerParameters) {
Object.keys(viewerParameters).forEach((key) => {
this.viewerParameters[key] = viewerParameters[key];
});
this.refreshParticles(false);
}
}
function floorMod(v, n) {
const f = v - n * Math.floor(v / n);
return f === n ? 0 : f;
}
function decimalize(x) {
if (typeof x === "string" && x.indexOf("/") >= 0) {
x = x.split("/");
}
return isArrayLike(x) && x.length === 2 ? x[0] / x[1] : +x;
}
function regularGrid(\u03BBaxis, \u03C6axis) {
const nx = Math.floor(\u03BBaxis.size);
const ny = Math.floor(\u03C6axis.size);
const np = nx * ny;
const \u0394\u03BB = decimalize(\u03BBaxis.delta);
const \u0394\u03C6 = decimalize(\u03C6axis.delta);
const \u03BB0 = decimalize(\u03BBaxis.start);
const \u03C60 = decimalize(\u03C6axis.start);
const isCylinder = Math.floor(nx * \u0394\u03BB) >= 360;
function dimensions() {
return {
width: nx,
height: ny
};
}
function isCylindrical() {
return isCylinder;
}
function forEach(cb, start) {
for (let i = start || 0; i < np; i++) {
const x = i % nx;
const y = Math.floor(i / nx);
const \u03BB = \u03BB0 + x * \u0394\u03BB;
const \u03C6 = \u03C60 + y * \u0394\u03C6;
if (cb(\u03BB, \u03C6, i)) {
return i + 1;
}
}
return NaN;
}
function closest(\u03BB, \u03C6) {
if (\u03BB === \u03BB && \u03C6 === \u03C6) {
const x = floorMod(\u03BB - \u03BB0, 360) / \u0394\u03BB;
const y = (\u03C6 - \u03C60) / \u0394\u03C6;
const rx = Math.round(x);
const ry = Math.round(y);
if (0 <= ry && ry < ny && 0 <= rx && (rx < nx || rx === nx && isCylinder)) {
const i = ry * nx + rx;
return rx === nx ? i - nx : i;
}
}
return NaN;
}
function closest4(\u03BB, \u03C6) {
if (\u03BB === \u03BB && \u03C6 === \u03C6) {
const x = floorMod(\u03BB - \u03BB0, 360) / \u0394\u03BB;
const y = (\u03C6 - \u03C60) / \u0394\u03C6;
const fx = Math.floor(x);
const fy = Math.floor(y);
const cx = fx + 1;
const cy = fy + 1;
const \u0394x = x - fx;
const \u0394y = y - fy;
if (0 <= fy && cy < ny && 0 <= fx && (cx < nx || cx === nx && isCylinder)) {
const i00 = fy * nx + fx;
let i10 = i00 + 1;
const i01 = i00 + nx;
let i11 = i01 + 1;
if (cx === nx) {
i10 -= nx;
i11 -= nx;
}
return [i00, i10, i01, i11, \u0394x, \u0394y];
}
}
return [NaN, NaN, NaN, NaN, NaN, NaN];
}
return {
dimensions,
isCylindrical,
forEach,
closest,
closest4
// webgl: webgl,
};
}
const windmapOverlayProps = exports('windmapOverlayProps', {
show: {
type: Boolean,
default: true
},
data: {
type: Object,
required: true
},
options: {
type: Object,
default: () => ({
maxParticles: 64 * 64,
particleHeight: 100,
fadeOpacity: 0.996,
dropRate: 3e-3,
dropRateBump: 0.01,
speedFactor: 1,
lineWidth: 4
})
},
viewerParameters: Object
});
var OverlayWind = defineComponent({
name: "VcOverlayWindmap",
props: windmapOverlayProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VcOverlayHtml";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { $services } = commonState;
let viewerParameters;
let globeBoundingSphere;
let primitiveCollection;
let grid;
const particleSystemOptions = computed(() => {
const particlesTextureSize = Math.ceil(Math.sqrt(props.options.maxParticles));
const maxParticles = particlesTextureSize * particlesTextureSize;
return {
particlesTextureSize,
maxParticles,
particleHeight: props.options.particleHeight,
fadeOpacity: props.options.fadeOpacity,
dropRate: props.options.dropRate,
dropRateBump: props.options.dropRateBump,
speedFactor: props.options.speedFactor,
lineWidth: props.options.lineWidth
};
});
let unwatchFns = [];
unwatchFns.push(
watch(
() => props.show,
(val) => {
primitiveCollection.show = val;
}
)
);
unwatchFns.push(
watch(
() => props.data,
(val) => {
instance.proxy.reload();
}
)
);
unwatchFns.push(
watch(
() => particleSystemOptions.value,
(val) => {
const particleSystem = instance.cesiumObject;
if (!particleSystem)
return;
particleSystem.applyParticleSystemOptions(val);
},
{
deep: true
}
)
);
unwatchFns.push(
watch(
() => props.viewerParameters,
(val) => {
updateViewerParameters();
const particleSystem = instance.cesiumObject;
particleSystem.applyViewerParameters(viewerParameters);
},
{
deep: true
}
)
);
instance.createCesiumObject = async () => {
const { viewer } = $services;
primitiveCollection = new Cesium.PrimitiveCollection();
globeBoundingSphere = new Cesium.BoundingSphere(Cesium.Cartesian3.ZERO, 0.99 * 6378137);
viewerParameters = {
lonRange: new Cesium.Cartesian2(),
latRange: new Cesium.Cartesian2(),
pixelSize: 0
};
const sequenceLon = { start: props.data.lon.array[0], delta: props.data.lon.delta, size: props.data.lon.array.length };
const sequenceLat = { start: props.data.lat.array[0], delta: props.data.lat.delta, size: props.data.lat.array.length };
grid = regularGrid(sequenceLon, sequenceLat);
updateViewerParameters();
return new ParticleSystem(viewer.scene.context, props.data, particleSystemOptions.value, viewerParameters);
};
instance.mount = async () => {
const { viewer } = $services;
viewer.scene.primitives.add(primitiveCollection);
const scene = viewer.scene;
const camera = scene.camera;
addPrimitives();
camera.moveStart.addEventListener(moveStartListener);
camera.moveEnd.addEventListener(moveEndListener);
window.addEventListener("resize", resizeListener);
scene.preRender.addEventListener(preRenderListener);
return true;
};
instance.unmount = async () => {
removePrimitives();
const { viewer } = $services;
const scene = viewer.scene;
const camera = scene.camera;
removePrimitives();
viewer.scene.primitives.remove(primitiveCollection);
camera.moveStart.removeEventListener(moveStartListener);
camera.moveEnd.removeEventListener(moveEndListener);
window.removeEventListener("resize", resizeListener);
scene.preRender.removeEventListener(preRenderListener);
return true;
};
const addPrimitives = () => {
const particleSystem = instance.cesiumObject;
primitiveCollection.add(particleSystem.particlesComputing.primitives.calculateSpeed);
primitiveCollection.add(particleSystem.particlesComputing.primitives.updatePosition);
primitiveCollection.add(particleSystem.particlesComputing.primitives.postProcessingPosition);
primitiveCollection.add(particleSystem.particlesRendering.primitives.segments);
primitiveCollection.add(particleSystem.particlesRendering.primitives.trails);
primitiveCollection.add(particleSystem.particlesRendering.primitives.screen);
};
const removePrimitives = () => {
const particleSystem = instance.cesiumObject;
primitiveCollection.remove(particleSystem.particlesComputing.primitives.calculateSpeed);
primitiveCollection.remove(particleSystem.particlesComputing.primitives.updatePosition);
primitiveCollection.remove(particleSystem.particlesComputing.primitives.postProcessingPosition);
primitiveCollection.remove(particleSystem.particlesRendering.primitives.segments);
primitiveCollection.remove(particleSystem.particlesRendering.primitives.trails);
primitiveCollection.remove(particleSystem.particlesRendering.primitives.screen);
};
const moveStartListener = () => {
primitiveCollection.show = false;
};
const moveEndListener = () => {
updateViewerParameters();
const particleSystem = instance.cesiumObject;
particleSystem.applyViewerParameters(viewerParameters);
primitiveCollection.show = true;
};
let resized = false;
const resizeListener = () => {
resized = true;
primitiveCollection.show = false;
primitiveCollection.removeAll();
};
const preRenderListener = () => {
if (resized) {
const { viewer } = $services;
const scene = viewer.scene;
const particleSystem = instance.cesiumObject;
particleSystem.canvasResize(scene.context);
resized = false;
addPrimitives();
primitiveCollection.show = true;
}
};
const updateViewerParameters = () => {
const { viewer } = $services;
const scene = viewer.scene;
const camera = scene.camera;
if (Cesium.defined(props.viewerParameters) && Cesium.defined(props.viewerParameters.latRange) && Cesium.defined(props.viewerParameters.lonRange)) {
viewerParameters.lonRange = makeCartesian2(props.viewerParameters.lonRange);
viewerParameters.latRange = makeCartesian2(props.viewerParameters.latRange);
} else {
const viewRectangle = camera.computeViewRectangle(scene.globe.ellipsoid);
const lonLatRange = viewRectangleToLonLatRange(viewRectangle);
viewerParameters.lonRange.x = lonLatRange.lon.min;
viewerParameters.lonRange.y = lonLatRange.lon.max;
viewerParameters.latRange.x = lonLatRange.lat.min;
viewerParameters.latRange.y = lonLatRange.lat.max;
}
const pixelSize = Cesium.defined(props.viewerParameters) && Cesium.defined(props.viewerParameters.pixelSize) ? props.viewerParameters.pixelSize : camera.getPixelSize(globeBoundingSphere, scene.drawingBufferWidth, scene.drawingBufferHeight);
if (pixelSize > 0) {
viewerParameters.pixelSize = pixelSize;
}
};
const getNearestUV = (longitude, latitude) => {
const index = grid.closest(longitude, latitude);
if (Cesium.defined(index)) {
return [props.data.U.array[index], props.data.V.array[index]];
}
return void 0;
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
Object.assign(instance.proxy, {
getNearestUV
});
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const dynamicOverlayProps = exports('dynamicOverlayProps', {
...show,
name: {
type: String,
default: "__vc__overlay__dynamic__"
},
startTime: {
type: [Object, String, Date]
},
stopTime: {
type: [Object, String, Date]
},
currentTime: {
type: [Object, String, Date]
},
clockRange: {
type: Number,
default: 0
},
clockStep: {
type: Number,
default: 1
},
shouldAnimate: {
type: Boolean,
default: true
},
canAnimate: {
type: Boolean,
default: true
},
multiplier: {
type: Number,
default: 1
},
dynamicOverlays: {
type: Array,
default: () => []
},
defaultInterval: {
type: Number,
default: 3
},
stopArrivedFlag: {
type: String,
default: "time"
},
positionPrecision: {
type: Number,
default: 1e-7
},
timePrecision: {
type: Number,
default: 0.01
}
});
const emits$6 = {
...commonEmits,
"update:currentTime": (currentTime) => true,
"update:shouldAnimate": (shouldAnimate) => true,
"update:canAnimate": (canAnimate) => true,
"update:clockRange": (clockRange) => true,
"update:clockStep": (clockStep) => true,
"update:multiplier": (multiplier) => true,
"update:startTime": (startTime) => true,
"update:stopTime": (stopTime) => true,
onStop: (clock) => true,
stopArrived: (e) => true
};
var OverlayDynamic = defineComponent({
name: "VcOverlayDynamic",
props: dynamicOverlayProps,
emits: emits$6,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VcOverlayDynamic";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { $services } = commonState;
const overlays = ref([]);
const restoreClockOpts = ref({});
const { emit } = ctx;
const trackingOverlay = ref(null);
const trackView = ref(null);
let lastOffset;
let unwatchFns = [];
unwatchFns.push(
watch(
() => props.show,
(val) => {
const datasource = instance.cesiumObject;
datasource && (datasource.show = val);
}
)
);
unwatchFns.push(
watch(
() => props.name,
(val) => {
const datasource = instance.cesiumObject;
datasource && (datasource.name = val);
}
)
);
unwatchFns.push(
watch(
() => props.startTime,
(val) => {
const { viewer } = $services;
if (Cesium.defined(viewer) && val) {
viewer.clock.startTime = makeJulianDate(val);
}
}
)
);
unwatchFns.push(
watch(
() => props.stopTime,
(val) => {
const { viewer } = $services;
if (Cesium.defined(viewer) && val) {
viewer.clock.stopTime = makeJulianDate(val);
}
}
)
);
unwatchFns.push(
watch(
() => props.currentTime,
(val) => {
const { viewer } = $services;
if (Cesium.defined(viewer) && val) {
viewer.clock.currentTime = makeJulianDate(val);
}
}
)
);
unwatchFns.push(
watch(
() => props.multiplier,
(val) => {
const { viewer } = $services;
if (Cesium.defined(viewer)) {
viewer.clock.multiplier = val;
}
}
)
);
unwatchFns.push(
watch(
() => props.clockStep,
(val) => {
const { viewer } = $services;
if (Cesium.defined(viewer)) {
viewer.clock.clockStep = val;
}
}
)
);
unwatchFns.push(
watch(
() => props.clockRange,
(val) => {
const { viewer } = $services;
if (Cesium.defined(viewer)) {
viewer.clock.clockRange = val;
}
}
)
);
unwatchFns.push(
watch(
() => props.canAnimate,
(val) => {
const { viewer } = $services;
if (Cesium.defined(viewer)) {
viewer.clock.canAnimate = val;
}
}
)
);
unwatchFns.push(
watch(
() => props.shouldAnimate,
(val) => {
const { viewer } = $services;
if (Cesium.defined(viewer)) {
viewer.clock.shouldAnimate = val;
}
}
)
);
unwatchFns.push(
watch(
() => cloneDeep(props.dynamicOverlays),
(newVal, oldVal) => {
if (!instance.mounted) {
return;
}
const datasource = instance.cesiumObject;
if (newVal.length === oldVal.length) {
const modifies = [];
for (let i = 0; i < newVal.length; i++) {
const options = newVal[i];
const oldOptions = oldVal[i];
const testReplace = (key, value) => {
if (key !== "nodeTransformations" && key !== "_definitionChanged") {
return value;
}
};
if (JSON.stringify(options, testReplace) !== JSON.stringify(oldOptions, testReplace)) {
modifies.push({
newOptions: options,
oldOptions
});
}
}
modifies.forEach((v) => {
const modifyEntity = datasource.entities.getById(v.oldOptions.id);
if (Cesium.defined(modifyEntity)) {
if (v.oldOptions.id === v.newOptions.id) {
modifyEntity && Object.keys(v.newOptions).forEach((prop) => {
if (v.oldOptions[prop] !== v.newOptions[prop]) {
modifyEntity[prop] = commonState.transformProp(prop, v.newOptions[prop]);
}
});
} else {
if (modifyEntity) {
datasource.entities.remove(modifyEntity);
remove(overlays.value, (overlay) => overlay.id === modifyEntity.id);
const entityOptions = v.newOptions;
addDynamicOverlays(datasource, [entityOptions]);
}
}
const dynamicOverlay = find(overlays.value, (v2) => v2.id === modifyEntity.id);
if (Cesium.defined(dynamicOverlay)) {
const oldSampledPositions = v.oldOptions.sampledPositions;
const newSampledPositions = v.newOptions.sampledPositions;
const sampledPositionAdds = differenceBy(newSampledPositions, oldSampledPositions, "id");
const sampledPositionDeletes = differenceBy(oldSampledPositions, newSampledPositions, "id");
sampledPositionDeletes.forEach((sampledPosition) => {
sampledPosition.time && dynamicOverlay._sampledPosition.removeSample(sampledPosition.time);
});
sampledPositionAdds.forEach((sampledPosition) => {
if (sampledPosition.time) {
dynamicOverlay.addPosition(sampledPosition.position, sampledPosition.time);
} else if (sampledPosition.interval) {
dynamicOverlay.addPosition(sampledPosition.position, sampledPosition.interval || props.defaultInterval);
}
});
}
}
});
} else {
const adds = differenceBy(newVal, oldVal, "id");
const deletes = differenceBy(oldVal, newVal, "id");
const deletedEntities = [];
for (let i = 0; i < deletes.length; i++) {
const deleteEntity = datasource.entities.getById(deletes[i].id);
deletedEntities.push(deleteEntity);
}
deletedEntities.forEach((v) => {
datasource.entities.remove(v);
remove(overlays.value, (overlay) => overlay.id === v.id);
});
addDynamicOverlays(datasource, adds);
}
},
{
deep: true
}
)
);
instance.createCesiumObject = async () => {
return new Cesium.CustomDataSource(props.name);
};
const onClockTick = (clock) => {
let listener = getInstanceListener(instance, "update:currentTime");
!makeJulianDate(props.currentTime).equalsEpsilon(clock.currentTime, 1e-3) && listener && emit("update:currentTime", clock.currentTime);
listener = getInstanceListener(instance, "update:shouldAnimate");
props.shouldAnimate !== clock.shouldAnimate && listener && emit("update:shouldAnimate", clock.shouldAnimate);
listener = getInstanceListener(instance, "update:canAnimate");
props.canAnimate !== clock.canAnimate && listener && emit("update:canAnimate", clock.canAnimate);
listener = getInstanceListener(instance, "update:clockRange");
props.clockRange !== clock.clockRange && listener && emit("update:clockRange", clock.clockRange);
listener = getInstanceListener(instance, "update:clockStep");
props.clockStep !== clock.clockStep && listener && emit("update:clockStep", clock.clockStep);
listener = getInstanceListener(instance, "update:multiplier");
props.multiplier !== clock.multiplier && listener && emit("update:multiplier", clock.multiplier);
listener = getInstanceListener(instance, "update:startTime");
!makeJulianDate(props.startTime).equalsEpsilon(clock.startTime, 1e-3) && listener && emit("update:startTime", clock.startTime);
listener = getInstanceListener(instance, "update:stopTime");
!makeJulianDate(props.stopTime).equalsEpsilon(clock.stopTime, 1e-3) && listener && emit("update:stopTime", clock.stopTime);
setTrackView(clock);
const { JulianDate, Cartesian3 } = Cesium;
listener = getInstanceListener(instance, "stopArrived");
if (listener && props.shouldAnimate) {
for (let i = 0; i < overlays.value.length; i++) {
const overlay = overlays.value[i];
const currentPosition = overlay._sampledPosition.getValue(clock.currentTime);
const dynamicOverlayOpts = props.dynamicOverlays[i];
for (let j = 0; j < dynamicOverlayOpts.sampledPositions.length; j++) {
const sampledPosition = dynamicOverlayOpts.sampledPositions[j];
const stopPostion = makeCartesian3(sampledPosition.position);
const stopTime = makeJulianDate(sampledPosition.time);
const positionFlag = Cartesian3.equalsEpsilon(currentPosition, stopPostion, props.positionPrecision);
const timeFlag = JulianDate.equalsEpsilon(clock.currentTime, stopTime, props.timePrecision);
let arrivedFlag = false;
switch (props.stopArrivedFlag) {
case "time":
arrivedFlag = timeFlag;
break;
case "position":
arrivedFlag = positionFlag;
break;
case "both":
arrivedFlag = timeFlag && positionFlag;
break;
case "or":
arrivedFlag = timeFlag || positionFlag;
break;
}
if (arrivedFlag) {
emit("stopArrived", {
overlay,
position: sampledPosition,
offset: lastOffset,
clock,
indexOverlay: i,
indexPosition: j
});
break;
}
}
}
}
};
const addDynamicOverlays = (datasource, dynamicOverlays) => {
for (let i = 0; i < dynamicOverlays.length; i++) {
const entityOptions = dynamicOverlays[i];
const entityOptionsTransform = commonState.transformProps(entityOptions);
const dynamicOverlay = new DynamicOverlay(entityOptionsTransform);
overlays.value.push(dynamicOverlay);
const entity = datasource.entities.add(dynamicOverlay._entity);
entityOptionsTransform.sampledPositions.forEach((sampledPosition) => {
if (sampledPosition.time) {
dynamicOverlay.addPosition(sampledPosition.position, sampledPosition.time);
} else if (sampledPosition.interval) {
sampledPosition.time = dynamicOverlay.addPosition(sampledPosition.position, sampledPosition.interval || props.defaultInterval);
}
});
entityOptions.id !== entity.id && (entityOptions.id = entity.id);
addCustomProperty(entity, entityOptionsTransform, ["id"]);
}
};
instance.mount = async () => {
const { viewer } = $services;
const datasource = instance.cesiumObject;
datasource.show = props.show;
addDynamicOverlays(datasource, props.dynamicOverlays);
return viewer.dataSources.add(datasource).then(() => {
restoreClockOpts.value.startTime = viewer.clock.startTime;
restoreClockOpts.value.stopTime = viewer.clock.stopTime;
restoreClockOpts.value.currentTime = viewer.clock.currentTime;
restoreClockOpts.value.multiplier = viewer.clock.multiplier;
restoreClockOpts.value.clockStep = viewer.clock.clockStep;
restoreClockOpts.value.clockRange = viewer.clock.clockRange;
restoreClockOpts.value.canAnimate = viewer.clock.canAnimate;
restoreClockOpts.value.shouldAnimate = viewer.clock.shouldAnimate;
if (props.startTime) {
viewer.clock.startTime = makeJulianDate(props.startTime);
}
if (props.stopTime) {
viewer.clock.stopTime = makeJulianDate(props.stopTime);
}
if (props.currentTime) {
viewer.clock.currentTime = makeJulianDate(props.currentTime);
}
viewer.clock.multiplier = props.multiplier;
viewer.clock.clockStep = props.clockStep;
viewer.clock.clockRange = props.clockRange;
viewer.clock.canAnimate = false;
viewer.clock.shouldAnimate = props.shouldAnimate;
viewer.clock.onTick.addEventListener(onClockTick);
const listener = getInstanceListener(instance, "onStop");
listener && viewer.clock.onStop.addEventListener(listener);
return true;
});
};
instance.unmount = async () => {
const { viewer } = $services;
const datasource = instance.cesiumObject;
viewer.dataSources.remove(datasource, true);
viewer.clock.startTime = restoreClockOpts.value.startTime;
viewer.clock.stopTime = restoreClockOpts.value.stopTime;
viewer.clock.multiplier = restoreClockOpts.value.multiplier;
viewer.clock.clockStep = restoreClockOpts.value.clockStep;
viewer.clock.clockRange = restoreClockOpts.value.clockRange;
viewer.clock.canAnimate = restoreClockOpts.value.canAnimate;
viewer.clock.shouldAnimate = restoreClockOpts.value.shouldAnimate;
overlays.value.length = 0;
viewer.clock.onTick.removeEventListener(onClockTick);
const listener = getInstanceListener(instance, "onStop");
listener && viewer.clock.onStop.removeEventListener(listener);
trackingOverlay.value && (viewer.trackedEntity = void 0);
return true;
};
const setTrackView = (clock) => {
var _a, _b, _c, _d, _e, _f, _g, _h;
if (trackView.value && trackingOverlay.value) {
const { viewer } = $services;
if (Cesium.JulianDate.greaterThan(clock.currentTime, clock.stopTime)) {
trackingOverlay.value = null;
return;
}
const position = trackingOverlay.value._sampledPosition.getValue(clock.currentTime);
let offset = new Cesium.HeadingPitchRange();
switch (trackView.value.mode) {
case "TP":
offset.heading = 0;
offset.pitch = ((_b = (_a = trackView.value) == null ? void 0 : _a.offset) == null ? void 0 : _b.pitch) || Cesium.Math.toRadians(-90);
offset.range = ((_d = (_c = trackView.value) == null ? void 0 : _c.offset) == null ? void 0 : _d.range) || 1e3;
break;
case "FP": {
const nextTickTime = Cesium.JulianDate.addSeconds(clock.currentTime, 1 / 60, new Cesium.JulianDate());
const nextTickPosition = trackingOverlay.value._sampledPosition.getValue(nextTickTime) || position;
if (position.equals(nextTickPosition) && lastOffset) {
offset = lastOffset;
} else {
offset.heading = Cesium.Math.toRadians(getPolylineSegmentHeading(position, nextTickPosition));
offset.pitch = (((_f = (_e = trackView.value) == null ? void 0 : _e.offset) == null ? void 0 : _f.pitch) || Cesium.Math.toRadians(-45)) + getPolylineSegmentPitch(position, nextTickPosition);
offset.range = ((_h = (_g = trackView.value) == null ? void 0 : _g.offset) == null ? void 0 : _h.range) || 500;
}
break;
}
case "CUSTOM":
offset = makeHeadingPitchRang(trackView.value.offset);
}
lastOffset = offset;
viewer.camera.lookAt(position, offset);
}
};
const trackOverlay = (trackOverlay2, trackViewOpts) => {
var _a;
const { viewer } = $services;
trackViewOpts = trackViewOpts || {
mode: trackView.value === null ? "FP" : "FREE"
};
if (trackViewOpts.mode === "FREE") {
viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
if (trackingOverlay.value) {
viewer.trackedEntity = void 0;
trackingOverlay.value = null;
trackView.value = null;
}
return;
}
trackingOverlay.value = getOverlay(trackOverlay2);
viewer.trackedEntity = toRaw(trackingOverlay.value._entity);
if (trackViewOpts.mode === "TRACKED") {
if ((_a = trackViewOpts == null ? void 0 : trackViewOpts.viewFrom) == null ? void 0 : _a.length) {
viewer.trackedEntity.viewFrom = new Cesium.Cartesian3(
trackViewOpts.viewFrom[0],
trackViewOpts.viewFrom[1],
trackViewOpts.viewFrom[2]
);
}
trackView.value = null;
} else {
trackView.value = trackViewOpts;
}
};
const getOverlay = (e) => {
if (e instanceof DynamicOverlay) {
return e;
} else if (typeof e === "string") {
return find(overlays.value, (v) => v.id === e);
} else if (typeof e === "number") {
return overlays.value[e];
} else {
return overlays.value[0];
}
};
const flyToOverlay = (overlays2, options) => {
const { viewer } = $services;
if (trackingOverlay.value) {
viewer.trackedEntity = void 0;
trackingOverlay.value = null;
}
let target;
if (Cesium.defined(overlays2)) {
if (Array.isArray(overlays2)) {
if (overlays2.length) {
const targets = [];
overlays2.forEach((viewOverlay) => {
const target2 = toRaw(getOverlay(viewOverlay)._entity);
targets.push(target2);
});
target = targets;
} else {
target = instance.cesiumObject;
}
} else {
target = toRaw(getOverlay(overlays2)._entity);
}
} else {
target = instance.cesiumObject;
}
options = options || {
duration: 3
};
if (Cesium.defined(options.offset)) {
options.offset = makeHeadingPitchRang(options.offset);
}
return viewer.flyTo(target, options);
};
const zoomToOverlay = (overlays2, offset) => {
const { viewer } = $services;
if (trackingOverlay.value) {
viewer.trackedEntity = void 0;
trackingOverlay.value = null;
}
let target;
if (Cesium.defined(overlays2)) {
if (Array.isArray(overlays2)) {
if (overlays2.length) {
const targets = [];
overlays2.forEach((viewOverlay) => {
const target2 = toRaw(getOverlay(viewOverlay)._entity);
targets.push(target2);
});
target = targets;
} else {
target = instance.cesiumObject;
}
} else {
target = toRaw(getOverlay(overlays2)._entity);
}
} else {
target = instance.cesiumObject;
}
return viewer.zoomTo(target, Cesium.defined(offset) ? makeHeadingPitchRang(offset) : void 0);
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
Object.assign(instance.proxy, { getOverlays: () => overlays.value, getOverlay, trackOverlay, zoomToOverlay, flyToOverlay });
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const billboardCollectionProps = exports('billboardCollectionProps', {
...scene,
...blendOption,
...show,
...enableMouseEvent,
...modelMatrix,
...debugShowBoundingVolume,
billboards: {
type: Array,
default: () => []
}
});
var CollectionBillboard = defineComponent({
name: "VcCollectionBillboard",
props: billboardCollectionProps,
emits: primitiveCollectionEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "BillboardCollection";
const primitiveCollectionsState = usePrimitiveCollections(props, ctx, instance);
let unwatchFns = [];
unwatchFns.push(
watch(
() => cloneDeep(props.billboards),
(newVal, oldVal) => {
if (!instance.mounted) {
return;
}
const billboardCollection = instance.cesiumObject;
if (newVal.length === oldVal.length) {
const modifies = [];
for (let i = 0; i < newVal.length; i++) {
const options = newVal[i];
const oldOptions = oldVal[i];
if (JSON.stringify(options) !== JSON.stringify(oldOptions)) {
modifies.push({
newOptions: options,
oldOptions
});
}
}
modifies.forEach((modify) => {
const modifyBillboard = billboardCollection._billboards.find((v) => (v == null ? void 0 : v.id) === modify.oldOptions.id);
modifyBillboard && Object.keys(modify.newOptions).forEach((prop) => {
if (modify.oldOptions[prop] !== modify.newOptions[prop]) {
modifyBillboard[prop] = primitiveCollectionsState == null ? void 0 : primitiveCollectionsState.transformProp(prop, modify.newOptions[prop]);
}
});
});
} else {
const addeds = differenceBy(newVal, oldVal, "id");
const deletes = differenceBy(oldVal, newVal, "id");
const deleteBillboards = [];
for (let i = 0; i < deletes.length; i++) {
const deleteBillboard = billboardCollection._billboards.find((v) => v.id === deletes[i].id);
deleteBillboard && deleteBillboards.push(deleteBillboard);
}
deleteBillboards.forEach((v) => {
billboardCollection.remove(v);
});
addBillboards(billboardCollection, addeds);
}
},
{
deep: true
}
)
);
instance.alreadyListening.push("billboards");
const addBillboards = (billboardCollection, billboards) => {
for (let i = 0; i < billboards.length; i++) {
const billboardOptions = billboards[i];
billboardOptions.id = Cesium.defined(billboardOptions.id) ? billboardOptions.id : Cesium.createGuid();
const billboardOptionsTransform = primitiveCollectionsState == null ? void 0 : primitiveCollectionsState.transformProps(billboardOptions);
const billboard = billboardCollection.add(billboardOptionsTransform);
addCustomProperty(billboard, billboardOptionsTransform);
}
};
instance.createCesiumObject = async () => {
const options = primitiveCollectionsState == null ? void 0 : primitiveCollectionsState.transformProps(props);
const billboardCollection = new Cesium.BillboardCollection(options);
addBillboards(billboardCollection, props.billboards);
return billboardCollection;
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
return () => {
var _a, _b;
return ctx.slots.default ? h(
"i",
{
class: kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(((_b = instance.proxy) == null ? void 0 : _b.$options.name) || ""));
};
}
});
const billboardProps = exports('billboardProps', {
...alignedAxis,
...color,
...disableDepthTestDistance,
...distanceDisplayCondition,
...eyeOffset,
...height,
...heightReference,
...horizontalOrigin,
...id,
...image,
...pixelOffset,
...pixelOffsetScaleByDistance,
...position$1,
...rotation,
...scale,
...scaleByDistance,
...show,
...sizeInMeters,
...translucencyByDistance,
...verticalOrigin,
...width,
...enableMouseEvent
});
var Billboard = defineComponent({
name: "VcBillboard",
props: billboardProps,
emits: primitiveCollectionEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "Billboard";
usePrimitiveCollectionItems(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const cumulusCloudProps = exports('cumulusCloudProps', {
brightness: {
type: Number,
default: 1
},
...color,
maximumSize: {
type: Object,
watcherOptions: {
cesiumObjectBuilder: makeCartesian3
}
},
...position$1,
scale: {
type: Object,
watcherOptions: {
cesiumObjectBuilder: makeCartesian2
}
},
...show,
slice: {
type: Number,
default: -1
}
});
var CumulusCloud = defineComponent({
name: "VcCumulusCloud",
props: cumulusCloudProps,
emits: primitiveCollectionEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "CumulusCloud";
usePrimitiveCollectionItems(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const cloudCollectionProps = exports('cloudCollectionProps', {
...show,
noiseDetail: {
type: Number,
default: 16
},
noiseOffset: {
type: Object
},
debugBillboards: {
type: Boolean,
default: false
},
debugEllipsoids: {
type: Boolean,
default: false
},
clouds: {
type: Array,
default: () => []
}
});
var CollectionCloud = defineComponent({
name: "VcCollectionCloud",
props: cloudCollectionProps,
emits: commonEmits,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "CloudCollection";
const primitiveCollectionsState = usePrimitiveCollections(props, ctx, instance);
if (primitiveCollectionsState === void 0) {
return;
}
instance.alreadyListening.push("clouds");
let unwatchFns = [];
unwatchFns.push(
watch(
() => cloneDeep(props.clouds),
(newVal, oldVal) => {
if (!instance.mounted) {
return;
}
const cloudCollection = instance.cesiumObject;
if (newVal.length === oldVal.length) {
const modifies = [];
for (let i = 0; i < newVal.length; i++) {
const options = newVal[i];
const oldOptions = oldVal[i];
if (JSON.stringify(options) !== JSON.stringify(oldOptions)) {
modifies.push({
newOptions: options,
oldOptions
});
}
}
modifies.forEach((modify) => {
const modifyCloud = cloudCollection._clouds.find((v) => v.id === modify.oldOptions.id);
modifyCloud && Object.keys(modify.newOptions).forEach((prop) => {
if (modify.oldOptions[prop] !== modify.newOptions[prop]) {
modifyCloud[prop] = primitiveCollectionsState.transformProp(prop, modify.newOptions[prop]);
}
});
});
} else {
const addeds = differenceBy(newVal, oldVal, "id");
const deletes = differenceBy(oldVal, newVal, "id");
const deleteClouds = [];
for (let i = 0; i < deletes.length; i++) {
const deleteCloud = cloudCollection._clouds.find((v) => v.id === deletes[i].id);
deleteCloud && deleteClouds.push(deleteCloud);
}
deleteClouds.forEach((v) => {
cloudCollection.remove(v);
});
addClouds(cloudCollection, addeds);
}
},
{
deep: true
}
)
);
const addClouds = (cloudCollection, clouds) => {
for (let i = 0; i < clouds.length; i++) {
const cloudOptions = clouds[i];
cloudOptions.id = Cesium.defined(cloudOptions.id) ? cloudOptions.id : Cesium.createGuid();
const cloudOptionsTransform = primitiveCollectionsState.transformProps(cloudOptions, CumulusCloud.props);
const cloud = cloudCollection.add(cloudOptionsTransform);
addCustomProperty(cloud, cloudOptionsTransform);
}
};
instance.createCesiumObject = async () => {
const options = primitiveCollectionsState.transformProps(props, CumulusCloud.props);
const cloudCollection = new Cesium.CloudCollection(options);
addClouds(cloudCollection, props.clouds);
return cloudCollection;
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
const name = ((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "";
return () => ctx.slots.default ? h(
"i",
{
class: kebabCase(name),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(name));
}
});
const labelCollectionProps = exports('labelCollectionProps', {
...modelMatrix,
...debugShowBoundingVolume,
...scene,
...blendOption,
...show,
...enableMouseEvent,
labels: {
type: Array,
default: () => []
}
});
var CollectionLabel = defineComponent({
name: "VcCollectionLabel",
props: labelCollectionProps,
emits: primitiveCollectionEmits,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "LabelCollection";
const primitiveCollectionsState = usePrimitiveCollections(props, ctx, instance);
if (primitiveCollectionsState === void 0) {
return;
}
instance.alreadyListening.push("labels");
let unwatchFns = [];
unwatchFns.push(
watch(
() => cloneDeep(props.labels),
(newVal, oldVal) => {
if (!instance.mounted) {
return;
}
const labelCollection = instance.cesiumObject;
if (newVal.length === oldVal.length) {
const modifies = [];
for (let i = 0; i < newVal.length; i++) {
const options = newVal[i];
const oldOptions = oldVal[i];
if (JSON.stringify(options) !== JSON.stringify(oldOptions)) {
modifies.push({
newOptions: options,
oldOptions
});
}
}
modifies.forEach((modify) => {
const modifyLabel = labelCollection._labels.find((v) => v.id === modify.oldOptions.id);
modifyLabel && Object.keys(modify.newOptions).forEach((prop) => {
if (modify.oldOptions[prop] !== modify.newOptions[prop]) {
modifyLabel[prop] = primitiveCollectionsState.transformProp(prop, modify.newOptions[prop]);
}
});
});
} else {
const addeds = differenceBy(newVal, oldVal, "id");
const deletes = differenceBy(oldVal, newVal, "id");
const deleteLabels = [];
for (let i = 0; i < deletes.length; i++) {
const deleteLabel = labelCollection._labels.find((v) => v.id === deletes[i].id);
deleteLabel && deleteLabels.push(deleteLabel);
}
deleteLabels.forEach((v) => {
labelCollection.remove(v);
});
addLabels(labelCollection, addeds);
}
},
{
deep: true
}
)
);
const addLabels = (labelCollection, labels) => {
for (let i = 0; i < labels.length; i++) {
const labelOptions = labels[i];
labelOptions.id = Cesium.defined(labelOptions.id) ? labelOptions.id : Cesium.createGuid();
const labelOptionsTransform = primitiveCollectionsState.transformProps(labelOptions);
const label = labelCollection.add(labelOptionsTransform);
addCustomProperty(label, labelOptionsTransform);
}
};
instance.createCesiumObject = async () => {
const options = primitiveCollectionsState.transformProps(props);
const labelCollection = new Cesium.LabelCollection(options);
addLabels(labelCollection, props.labels);
return labelCollection;
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
const name = ((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "";
return () => ctx.slots.default ? h(
"i",
{
class: kebabCase(name),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(name));
}
});
const labelProps = exports('labelProps', {
...backgroundColor,
...backgroundPadding,
...disableDepthTestDistance,
...distanceDisplayCondition,
...eyeOffset,
...fillColor,
...font,
...heightReference,
...horizontalOrigin,
...id,
...outlineColor,
...outlineWidth,
...pixelOffset,
...pixelOffsetScaleByDistance,
...position$1,
...scale,
...scaleByDistance,
...show,
...showBackground,
...labelStyle,
...text$7,
totalScale: {
type: Number,
default: 1
},
...translucencyByDistance,
...verticalOrigin,
...enableMouseEvent
});
var Label = defineComponent({
name: "VcLabel",
props: labelProps,
emits: primitiveCollectionEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "Label";
usePrimitiveCollectionItems(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const pointCollectionProps = exports('pointCollectionProps', {
...modelMatrix,
...debugShowBoundingVolume,
...blendOption,
...show,
...enableMouseEvent,
points: {
type: Array,
default: () => []
}
});
var CollectionPoint = defineComponent({
name: "VcCollectionPoint",
props: pointCollectionProps,
emits: primitiveCollectionEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PointPrimitiveCollection";
const primitiveCollectionsState = usePrimitiveCollections(props, ctx, instance);
if (primitiveCollectionsState === void 0) {
return;
}
instance.alreadyListening.push("points");
let unwatchFns = [];
unwatchFns.push(
watch(
() => cloneDeep(props.points),
(newVal, oldVal) => {
if (!instance.mounted) {
return;
}
const pointCollection = instance.cesiumObject;
if (newVal.length === oldVal.length) {
const modifies = [];
for (let i = 0; i < newVal.length; i++) {
const options = newVal[i];
const oldOptions = oldVal[i];
if (JSON.stringify(options) !== JSON.stringify(oldOptions)) {
modifies.push({
newOptions: options,
oldOptions
});
}
}
modifies.forEach((modify) => {
const modifyPoint = pointCollection._pointPrimitives.find((v) => v && v.id === modify.oldOptions.id);
modifyPoint && Object.keys(modify.newOptions).forEach((prop) => {
if (modify.oldOptions[prop] !== modify.newOptions[prop]) {
modifyPoint[prop] = primitiveCollectionsState.transformProp(prop, modify.newOptions[prop]);
}
});
});
} else {
const addeds = differenceBy(newVal, oldVal, "id");
const deletes = differenceBy(oldVal, newVal, "id");
const deletePoints = [];
for (let i = 0; i < deletes.length; i++) {
const deletePoint = pointCollection._pointPrimitives.find((v) => v.id === deletes[i].id);
deletePoint && deletePoints.push(deletePoint);
}
deletePoints.forEach((v) => {
pointCollection.remove(v);
});
addPoints(pointCollection, addeds);
}
},
{
deep: true
}
)
);
const addPoints = (pointCollection, points) => {
for (let i = 0; i < points.length; i++) {
const pointOptions = points[i];
pointOptions.id = Cesium.defined(pointOptions.id) ? pointOptions.id : Cesium.createGuid();
const pointOptionsTransform = primitiveCollectionsState.transformProps(pointOptions);
const point = pointCollection.add(pointOptionsTransform);
addCustomProperty(point, pointOptionsTransform);
}
};
instance.createCesiumObject = async () => {
const options = primitiveCollectionsState.transformProps(props);
const pointCollection = new Cesium.PointPrimitiveCollection(options);
addPoints(pointCollection, props.points);
return pointCollection;
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
return () => {
var _a, _b;
return ctx.slots.default ? h(
"i",
{
class: kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(((_b = instance.proxy) == null ? void 0 : _b.$options.name) || ""));
};
}
});
const pointProps = exports('pointProps', {
...color,
...disableDepthTestDistance,
...distanceDisplayCondition,
...id,
...outlineColor,
...outlineWidth,
...pixelSize,
...position$1,
...scaleByDistance,
...show,
...translucencyByDistance,
...enableMouseEvent
});
var Point$1 = defineComponent({
name: "VcPoint",
props: pointProps,
emits: primitiveCollectionEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PointPrimitive";
usePrimitiveCollectionItems(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const polylineCollectionProps = {
...modelMatrix,
...debugShowBoundingVolume,
...show,
...enableMouseEvent,
polylines: {
type: Array,
default: () => []
}
};
var CollectionPolyline = defineComponent({
name: "VcCollectionPolyline",
props: polylineCollectionProps,
emits: primitiveCollectionEmits,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "PolylineCollection";
const primitiveCollectionsState = usePrimitiveCollections(props, ctx, instance);
if (primitiveCollectionsState === void 0) {
return;
}
instance.alreadyListening.push("polylines");
let unwatchFns = [];
unwatchFns.push(
watch(
() => cloneDeep(props.polylines),
(newVal, oldVal) => {
if (!instance.mounted) {
return;
}
const polylineCollection = instance.cesiumObject;
if (newVal.length === oldVal.length) {
const modifies = [];
for (let i = 0; i < newVal.length; i++) {
const options = newVal[i];
const oldOptions = oldVal[i];
if (JSON.stringify(options) !== JSON.stringify(oldOptions)) {
modifies.push({
newOptions: options,
oldOptions
});
}
}
modifies.forEach((modify) => {
const modifyPolyline = polylineCollection._polylines.find((v) => v.id === modify.oldOptions.id);
modifyPolyline && Object.keys(modify.newOptions).forEach((prop) => {
if (modify.oldOptions[prop] !== modify.newOptions[prop]) {
modifyPolyline[prop] = primitiveCollectionsState.transformProp(prop, modify.newOptions[prop]);
}
});
});
} else {
const addeds = differenceBy(newVal, oldVal, "id");
const deletes = differenceBy(oldVal, newVal, "id");
const deletePolylines = [];
for (let i = 0; i < deletes.length; i++) {
const deletePolyline = polylineCollection._polylines.find((v) => v.id === deletes[i].id);
deletePolyline && deletePolylines.push(deletePolyline);
}
deletePolylines.forEach((v) => {
polylineCollection.remove(v);
});
addPolylines(polylineCollection, addeds);
}
},
{
deep: true
}
)
);
const addPolylines = (polylineCollection, polylines) => {
for (let i = 0; i < polylines.length; i++) {
const polylineOptions = polylines[i];
polylineOptions.id = Cesium.defined(polylineOptions.id) ? polylineOptions.id : Cesium.createGuid();
const polylineOptionsTransform = primitiveCollectionsState.transformProps(polylineOptions);
const polyline = polylineCollection.add(polylineOptionsTransform);
addCustomProperty(polyline, polylineOptionsTransform);
}
};
instance.createCesiumObject = async () => {
const options = primitiveCollectionsState.transformProps(props);
const polylineCollection = new Cesium.PolylineCollection(options);
addPolylines(polylineCollection, props.polylines);
return polylineCollection;
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
const name = ((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "";
return () => ctx.slots.default ? h(
"i",
{
class: kebabCase(name),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(name));
}
});
const polylineProps = exports('polylineProps', {
...distanceDisplayCondition,
...id,
...loop,
...material,
...positions,
...show,
...width,
...enableMouseEvent
});
var Polyline = defineComponent({
name: "VcPolyline",
props: polylineProps,
emits: primitiveCollectionEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "Polyline";
usePrimitiveCollectionItems(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const primitiveCollectionProps = exports('primitiveCollectionProps', {
...show,
destroyPrimitives: {
type: Boolean,
default: true
},
...enableMouseEvent,
polygons: {
type: Array,
default: () => []
}
});
var CollectionPrimitive = defineComponent({
name: "VcCollectionPrimitive",
props: primitiveCollectionProps,
emits: primitiveCollectionEmits,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "PrimitiveCollection";
const primitiveCollectionsState = usePrimitiveCollections(props, ctx, instance);
if (primitiveCollectionsState === void 0) {
return;
}
instance.alreadyListening.push("polygons");
let unwatchFns = [];
unwatchFns.push(
watch(
() => cloneDeep(props.polygons),
(newVal, oldVal) => {
if (!instance.mounted) {
return;
}
const primitiveCollection = instance.cesiumObject;
if (newVal.length === oldVal.length) {
const modifies = [];
for (let i = 0; i < newVal.length; i++) {
const options = newVal[i];
const oldOptions = oldVal[i];
if (JSON.stringify(options) !== JSON.stringify(oldOptions)) {
modifies.push({
newOptions: options,
oldOptions
});
}
}
modifies.forEach((modify) => {
const modifyPolygon = primitiveCollection._primitives.find((v) => v._id === modify.oldOptions.id);
modifyPolygon && Object.keys(modify.newOptions).forEach((prop) => {
if (modify.oldOptions[prop] !== modify.newOptions[prop]) {
modifyPolygon[prop] = primitiveCollectionsState.transformProp(prop, modify.newOptions[prop]);
}
});
});
} else {
const addeds = differenceBy(newVal, oldVal, "id");
const deletes = differenceBy(oldVal, newVal, "id");
const deletePolygons = [];
for (let i = 0; i < deletes.length; i++) {
const deletePolygon = primitiveCollection._primitives.find((v) => v.id === deletes[i].id);
deletePolygon && deletePolygons.push(deletePolygon);
}
deletePolygons.forEach((v) => {
primitiveCollection.remove(v);
});
addPolygons(primitiveCollection, addeds);
}
},
{
deep: true
}
)
);
const addPolygons = (primitiveCollection, polygons) => {
for (let i = 0; i < polygons.length; i++) {
const polygonOptions = polygons[i];
polygonOptions.id = Cesium.defined(polygonOptions.id) ? polygonOptions.id : Cesium.createGuid();
const polygonOptionsTransform = primitiveCollectionsState.transformProps(polygonOptions);
const polygonPrimitive = new PolygonPrimitive(polygonOptionsTransform);
polygonPrimitive._vcParent = primitiveCollection;
addCustomProperty(polygonPrimitive, polygonOptionsTransform);
primitiveCollection.add(polygonPrimitive);
}
};
instance.createCesiumObject = async () => {
const options = primitiveCollectionsState.transformProps(props);
const primitiveCollection = new Cesium.PrimitiveCollection(options);
addPolygons(primitiveCollection, props.polygons);
return primitiveCollection;
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
const name = ((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "";
return () => ctx.slots.default ? h(
"i",
{
class: kebabCase(name),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(name));
}
});
const polygonProps = exports('polygonProps', {
...positions,
...polygonHierarchy,
...appearance,
...depthFailAppearance,
...show,
...id,
...arcType,
...classificationType,
...clampToGround,
...ellipsoid,
...allowPicking,
...asynchronous,
...enableMouseEvent
});
var Polygon = defineComponent({
name: "VcPolygon",
props: polygonProps,
emits: primitiveCollectionEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PolygonPrimitive";
const primitiveCollectionItemsState = usePrimitiveCollectionItems(props, ctx, instance);
if (primitiveCollectionItemsState === void 0) {
return;
}
let unwatchFns = [];
unwatchFns.push(
watch(
() => props.clampToGround,
(val) => {
const polygonPrimitive = instance.cesiumObject;
polygonPrimitive && (polygonPrimitive.clampToGround = val);
}
)
);
unwatchFns.push(
watch(
() => props.positions,
(val) => {
const polygonPrimitive = instance.cesiumObject;
polygonPrimitive && (polygonPrimitive.positions = makeCartesian3Array(val));
}
)
);
unwatchFns.push(
watch(
() => props.polygonHierarchy,
(val) => {
const polygonPrimitive = instance.cesiumObject;
polygonPrimitive && (polygonPrimitive.polygonHierarchy = makePolygonHierarchy(val));
}
)
);
unwatchFns.push(
watch(
() => props.appearance,
(val) => {
const polygonPrimitive = instance.cesiumObject;
polygonPrimitive && (polygonPrimitive.appearance = makeAppearance.call(instance, val));
}
)
);
unwatchFns.push(
watch(
() => props.depthFailAppearance,
(val) => {
const polygonPrimitive = instance.cesiumObject;
polygonPrimitive && (polygonPrimitive.depthFailAppearance = makeAppearance.call(instance, val));
}
)
);
unwatchFns.push(
watch(
() => props.show,
(val) => {
const polygonPrimitive = instance.cesiumObject;
polygonPrimitive && (polygonPrimitive.show = val);
}
)
);
unwatchFns.push(
watch(
() => props.classificationType,
(val) => {
const polygonPrimitive = instance.cesiumObject;
polygonPrimitive && (polygonPrimitive.classificationType = val);
}
)
);
instance.createCesiumObject = async () => {
const options = primitiveCollectionItemsState.transformProps(props);
return new PolygonPrimitive(options);
};
instance.mount = async () => {
const primitives = primitiveCollectionItemsState.$services.primitives;
const collectionItem = instance.cesiumObject;
collectionItem._vcParent = primitives;
return primitives && primitives.add(collectionItem);
};
instance.unmount = async () => {
const primitives = primitiveCollectionItemsState.$services.primitives;
const collectionItem = instance.cesiumObject;
return primitives && !primitives.isDestroyed() && primitives.remove(collectionItem);
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const components$7 = [
CollectionBillboard,
CollectionCloud,
CollectionLabel,
CollectionPoint,
CollectionPolyline,
CollectionPrimitive,
CumulusCloud,
Billboard,
Label,
Point$1,
Polyline,
Polygon
];
components$7.forEach((cmp) => {
cmp["install"] = (app) => {
app.component(cmp.name, cmp);
};
});
const VcCollectionBillboard = exports('VcCollectionBillboard', CollectionBillboard);
const VcCollectionCloud = exports('VcCollectionCloud', CollectionCloud);
const VcCollectionLabel = exports('VcCollectionLabel', CollectionLabel);
const VcCollectionPoint = exports('VcCollectionPoint', CollectionPoint);
const VcCollectionPolyline = exports('VcCollectionPolyline', CollectionPolyline);
const VcCollectionPrimitive = exports('VcCollectionPrimitive', CollectionPrimitive);
const VcBillboard = exports('VcBillboard', Billboard);
const VcCumulusCloud = exports('VcCumulusCloud', CumulusCloud);
const VcLabel = exports('VcLabel', Label);
const VcPoint = exports('VcPoint', Point$1);
const VcPolyline = exports('VcPolyline', Polyline);
const VcPolygon = exports('VcPolygon', Polygon);
const geometryInstanceProps = exports('geometryInstanceProps', {
geometry: Object,
...modelMatrix,
...id,
attributes: Object
});
const emits$5 = {
...commonEmits,
"update:geometry": (payload) => true
};
var GeometryInstance = defineComponent({
name: "VcGeometryInstance",
props: geometryInstanceProps,
emits: emits$5,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.renderByParent = true;
instance.cesiumClass = "GeometryInstance";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { emit } = ctx;
const vcIndex = ref(0);
instance.createCesiumObject = async () => {
const options = commonState.transformProps(props);
if (!options.geometry) {
options.geometry = new Cesium.Geometry({ attributes: new Cesium.GeometryAttributes() });
}
return new Cesium.GeometryInstance(options);
};
instance.mount = async () => {
var _a;
const parentVM = getVcParentInstance(instance).proxy;
if (parentVM.__childCount !== void 0) {
vcIndex.value = parentVM.__childCount.value || 0;
parentVM.__childCount.value += 1;
}
const geometryInstance = instance.cesiumObject;
(_a = parentVM.__updateGeometryInstances) == null ? void 0 : _a.call(parentVM, geometryInstance, vcIndex.value);
return true;
};
instance.unmount = async () => {
var _a;
const geometryInstance = instance.cesiumObject;
const parentVM = getVcParentInstance(instance).proxy;
(_a = parentVM.__removeGeometryInstances) == null ? void 0 : _a.call(parentVM, geometryInstance);
return true;
};
const updateGeometry = (geometry) => {
const listener = getInstanceListener(instance, "update:geometry");
if (listener) {
emit("update:geometry", geometry);
} else {
const geometryInstance = instance.cesiumObject;
geometryInstance.geometry = geometry;
}
return true;
};
const getServices = () => {
return mergeDescriptors(commonState.getServices(), {
get geometryInstance() {
return instance.cesiumObject;
}
});
};
provide(vcKey, getServices());
Object.assign(instance.proxy, {
// private but needed by VcGeometryXXX
__updateGeometry: updateGeometry
});
return () => {
var _a, _b;
return ctx.slots.default ? h(
"i",
{
class: kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(((_b = instance.proxy) == null ? void 0 : _b.$options.name) || "v-if"));
};
}
});
GeometryInstance.install = (app) => {
app.component(GeometryInstance.name, GeometryInstance);
};
const _GeometryInstance = GeometryInstance;
const VcGeometryInstance = exports('VcGeometryInstance', _GeometryInstance);
const boxGeometryProps = exports('boxGeometryProps', {
...dimensions,
...vertexFormat
});
var GeometryBox = defineComponent({
name: "VcGeometryBox",
props: boxGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "BoxGeometry";
const geometriesState = useGeometries(props, ctx, instance);
instance.createCesiumObject = async () => {
const options = geometriesState == null ? void 0 : geometriesState.transformProps(props);
return Cesium.BoxGeometry.fromDimensions(options);
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const boxOutlineGeometryProps = exports('boxOutlineGeometryProps', {
...dimensions
});
var GeometryBoxOutline = defineComponent({
name: "VcGeometryBoxOutline",
props: boxOutlineGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "BoxOutlineGeometry";
const geometriesState = useGeometries(props, ctx, instance);
instance.createCesiumObject = async () => {
const options = geometriesState == null ? void 0 : geometriesState.transformProps(props);
return Cesium.BoxOutlineGeometry.fromDimensions(options);
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const circleGeometryProps = exports('circleGeometryProps', {
...center,
...radius,
...ellipsoid,
...height,
...granularity,
...vertexFormat,
...extrudedHeight,
...stRotation
});
var GeometryCircle = defineComponent({
name: "VcGeometryCircle",
props: circleGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "CircleGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const circleOutlineGeometryProps = exports('circleOutlineGeometryProps', {
...center,
...radius,
...ellipsoid,
...height,
...granularity,
...extrudedHeight,
...numberOfVerticalLines
});
var GeometryCircleOutline = defineComponent({
name: "VcGeometryCircleOutline",
props: circleOutlineGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "CircleOutlineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const polygonCoplanarProps = exports('polygonCoplanarProps', {
...polygonHierarchy,
...ellipsoid,
...vertexFormat,
...stRotation
});
var GeometryPolygonCoplanar = defineComponent({
name: "VcGeometryPolygonCoplanar",
props: polygonCoplanarProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "CoplanarPolygonGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const polygonCoplanarOutlineProps = exports('polygonCoplanarOutlineProps', {
...polygonHierarchy
});
var GeometryPolygonCoplanarOutline = defineComponent({
name: "VcGeometryPolygonCoplanarOutline",
props: polygonCoplanarOutlineProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "CoplanarPolygonOutlineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const corridorGeometryProps = exports('corridorGeometryProps', {
...positions,
...width,
...ellipsoid,
...granularity,
...height,
...extrudedHeight,
...vertexFormat,
...cornerType
});
var GeometryCorridor = defineComponent({
name: "VcGeometryCorridor",
props: corridorGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "CorridorGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const corridorOutlineGeometryProps = exports('corridorOutlineGeometryProps', {
...positions,
...width,
...ellipsoid,
...granularity,
...height,
...extrudedHeight,
...cornerType
});
var GeometryCorridorOutline = defineComponent({
name: "VcGeometryCorridorOutline",
props: corridorOutlineGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "CorridorOutlineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const cylinderGeometryProps = exports('cylinderGeometryProps', {
...length,
...topRadius,
...bottomRadius,
...slices,
...vertexFormat
});
var GeometryCylinder = defineComponent({
name: "VcGeometryCylinder",
props: cylinderGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "CylinderGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const cylinderOutlineGeometryProps = exports('cylinderOutlineGeometryProps', {
...length,
...topRadius,
...bottomRadius,
...slices,
...numberOfVerticalLines
});
var GeometryCylinderOutline = defineComponent({
name: "VcGeometryCylinderOutline",
props: cylinderOutlineGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "CylinderOutlineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const ellipseGeometryProps = exports('ellipseGeometryProps', {
...center,
...semiMajorAxis,
...semiMinorAxis,
...ellipsoid,
...height,
...extrudedHeight,
...rotation,
...stRotation,
...granularity,
...vertexFormat
});
var GeometryEllipse = defineComponent({
name: "VcGeometryEllipse",
props: ellipseGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "EllipseGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const ellipseOutlineGeometryProps = exports('ellipseOutlineGeometryProps', {
...center,
...semiMajorAxis,
...semiMinorAxis,
...ellipsoid,
...height,
...extrudedHeight,
...rotation,
...stRotation,
...granularity,
...numberOfVerticalLines
});
var GeometryEllipseOutline = defineComponent({
name: "VcGeometryEllipseOutline",
props: ellipseOutlineGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "EllipseOutlineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const ellipsoidGeometryProps = exports('ellipsoidGeometryProps', {
...radii,
...innerRadii,
...minimumClock,
...maximumClock,
...minimumCone,
...maximumCone,
...stackPartitions,
...slicePartitions,
...vertexFormat
});
var GeometryEllipsoid = defineComponent({
name: "VcGeometryEllipsoid",
props: ellipsoidGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "EllipsoidGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const ellipsoidOutlineProps = {
...radii,
...innerRadii,
...minimumClock,
...maximumClock,
...minimumCone,
...maximumCone,
...stackPartitions,
...slicePartitions,
...subdivisions
};
var GeometryEllipsoidOutline = defineComponent({
name: "VcGeometryEllipsoidOutline",
props: ellipsoidOutlineProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "EllipsoidOutlineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const frustumGeometryProps = exports('frustumGeometryProps', {
...frustum,
...origin,
...orientation,
...vertexFormat
});
var GeometryFrustum = defineComponent({
name: "VcGeometryFrustum",
props: frustumGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "FrustumGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const frustumOutlineGeometryProps = exports('frustumOutlineGeometryProps', {
...frustum,
...origin,
...orientation
});
var GeometryFrustumOutline = defineComponent({
name: "VcGeometryFrustumOutline",
props: frustumOutlineGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "FrustumOutlineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const groundPolylineGeometryProps = exports('groundPolylineGeometryProps', {
...positions,
...width,
...granularity,
...loop,
...arcType
});
var GeometryGroundPolyline = defineComponent({
name: "VcGeometryGroundPolyline",
props: groundPolylineGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "GroundPolylineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const planeGeometryProps = exports('planeGeometryProps', {
...vertexFormat
});
var GeometryPlane = defineComponent({
name: "VcGeometryPlane",
props: planeGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PlaneGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
var GeometryPlaneOutline = defineComponent({
name: "VcGeometryPlaneOutline",
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PlaneOutlineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const polygonGeometryProps = exports('polygonGeometryProps', {
...polygonHierarchy,
...height,
...extrudedHeight,
...vertexFormat,
...stRotation,
...ellipsoid,
...granularity,
...perPositionHeight,
...closeTop,
...closeBottom,
...arcType
});
var GeometryPolygon = defineComponent({
name: "VcGeometryPolygon",
props: polygonGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PolygonGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const polygonOutlineGeometryProps = exports('polygonOutlineGeometryProps', {
...polygonHierarchy,
...height,
...extrudedHeight,
...vertexFormat,
...ellipsoid,
...granularity,
...perPositionHeight,
...arcType
});
var GeometryPolygonOutline = defineComponent({
name: "VcGeometryPolygonOutline",
props: polygonOutlineGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PolygonOutlineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const polylineGeometryProps = exports('polylineGeometryProps', {
...positions,
...width,
...colors,
colorsPerVertex: {
type: Boolean,
default: false
},
...arcType,
...granularity,
...vertexFormat,
...ellipsoid
});
var GeometryPolyline = defineComponent({
name: "VcGeometryPolyline",
props: polylineGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PolylineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const polylineVolumeGeometryProps = exports('polylineVolumeGeometryProps', {
...polylinePositions,
...shapePositions,
...ellipsoid,
...granularity,
...vertexFormat,
...cornerType
});
var GeometryPolylineVolume = defineComponent({
name: "VcGeometryPolylineVolume",
props: polylineVolumeGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PolylineVolumeGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const polylineVolumeOutlineGeometryProps = exports('polylineVolumeOutlineGeometryProps', {
...polylinePositions,
...shapePositions,
...ellipsoid,
...granularity,
...cornerType
});
var GeometryPolylineVolumeOutline = defineComponent({
name: "VcGeometryPolylineVolumeOutline",
props: polylineVolumeOutlineGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PolylineVolumeOutlineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const rectangleGeometryProps = exports('rectangleGeometryProps', {
...rectangle,
...vertexFormat,
...ellipsoid,
...granularity,
...height,
...rotation,
...stRotation,
...extrudedHeight
});
var GeometryRectangle = defineComponent({
name: "VcGeometryRectangle",
props: rectangleGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "RectangleGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const rectangleOutlineGeometryProps = exports('rectangleOutlineGeometryProps', {
...rectangle,
...ellipsoid,
...granularity,
...height,
...rotation,
...extrudedHeight
});
var GeometryRectangleOutline = defineComponent({
name: "VcGeometryRectangleOutline",
props: rectangleOutlineGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "RectangleOutlineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const simplePolylineGeometryProps = exports('simplePolylineGeometryProps', {
...positions,
...colors,
colorsPerVertex: {
type: Boolean,
default: false
},
...arcType,
...granularity,
...ellipsoid
});
var GeometrySimplePolyline = defineComponent({
name: "VcGeometrySimplePolyline",
props: simplePolylineGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "SimplePolylineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const sphereGeometryProps = exports('sphereGeometryProps', {
...radius,
...stackPartitions,
...slicePartitions,
...vertexFormat
});
var GeometrySphere = defineComponent({
name: "VcGeometrySphere",
props: sphereGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "SphereGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const sphereGeometryOutlineProps = exports('sphereGeometryOutlineProps', {
...radius,
...stackPartitions,
...slicePartitions,
...subdivisions
});
var GeometrySphereOutline = defineComponent({
name: "VcGeometrySphereOutline",
props: sphereGeometryOutlineProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "SphereOutlineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const wallGeometryProps = exports('wallGeometryProps', {
...positions,
...granularity,
...maximumHeights,
...minimumHeights,
...ellipsoid,
...vertexFormat
});
var GeometryWall = defineComponent({
name: "VcGeometryWall",
props: wallGeometryProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "WallGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const wallOutlineProps = exports('wallOutlineProps', {
...positions,
...granularity,
...maximumHeights,
...minimumHeights,
...ellipsoid
});
var GeometryWallOutline = defineComponent({
name: "VcGeometryWallOutline",
props: wallOutlineProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "WallOutlineGeometry";
useGeometries(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const components$6 = [
GeometryBox,
GeometryBoxOutline,
GeometryCircle,
GeometryCircleOutline,
GeometryPolygonCoplanar,
GeometryPolygonCoplanarOutline,
GeometryCorridor,
GeometryCorridorOutline,
GeometryCylinder,
GeometryCylinderOutline,
GeometryEllipse,
GeometryEllipseOutline,
GeometryEllipsoid,
GeometryEllipsoidOutline,
GeometryFrustum,
GeometryFrustumOutline,
GeometryGroundPolyline,
GeometryPlane,
GeometryPlaneOutline,
GeometryPolygon,
GeometryPolygonOutline,
GeometryPolyline,
GeometryPolylineVolume,
GeometryPolylineVolumeOutline,
GeometryRectangle,
GeometryRectangleOutline,
GeometrySimplePolyline,
GeometrySphere,
GeometrySphereOutline,
GeometryWall,
GeometryWallOutline
];
components$6.forEach((cmp) => {
cmp["install"] = (app) => {
app.component(cmp.name, cmp);
};
});
const VcGeometryBox = exports('VcGeometryBox', GeometryBox);
const VcGeometryBoxOutline = exports('VcGeometryBoxOutline', GeometryBoxOutline);
const VcGeometryCircle = exports('VcGeometryCircle', GeometryCircle);
const VcGeometryCircleOutline = exports('VcGeometryCircleOutline', GeometryCircleOutline);
const VcGeometryPolygonCoplanar = exports('VcGeometryPolygonCoplanar', GeometryPolygonCoplanar);
const VcGeometryPolygonCoplanarOutline = exports('VcGeometryPolygonCoplanarOutline', GeometryPolygonCoplanarOutline);
const VcGeometryCorridor = exports('VcGeometryCorridor', GeometryCorridor);
const VcGeometryCorridorOutline = exports('VcGeometryCorridorOutline', GeometryCorridorOutline);
const VcGeometryCylinder = exports('VcGeometryCylinder', GeometryCylinder);
const VcGeometryCylinderOutline = exports('VcGeometryCylinderOutline', GeometryCylinderOutline);
const VcGeometryEllipse = exports('VcGeometryEllipse', GeometryEllipse);
const VcGeometryEllipseOutline = exports('VcGeometryEllipseOutline', GeometryEllipseOutline);
const VcGeometryEllipsoid = exports('VcGeometryEllipsoid', GeometryEllipsoid);
const VcGeometryEllipsoidOutline = exports('VcGeometryEllipsoidOutline', GeometryEllipsoidOutline);
const VcGeometryFrustum = exports('VcGeometryFrustum', GeometryFrustum);
const VcGeometryFrustumOutline = exports('VcGeometryFrustumOutline', GeometryFrustumOutline);
const VcGeometryGroundPolyline = exports('VcGeometryGroundPolyline', GeometryGroundPolyline);
const VcGeometryPlane = exports('VcGeometryPlane', GeometryPlane);
const VcGeometryPlaneOutline = exports('VcGeometryPlaneOutline', GeometryPlaneOutline);
const VcGeometryPolygon = exports('VcGeometryPolygon', GeometryPolygon);
const VcGeometryPolygonOutline = exports('VcGeometryPolygonOutline', GeometryPolygonOutline);
const VcGeometryPolyline = exports('VcGeometryPolyline', GeometryPolyline);
const VcGeometryPolylineVolume = exports('VcGeometryPolylineVolume', GeometryPolylineVolume);
const VcGeometryPolylineVolumeOutline = exports('VcGeometryPolylineVolumeOutline', GeometryPolylineVolumeOutline);
const VcGeometryRectangle = exports('VcGeometryRectangle', GeometryRectangle);
const VcGeometryRectangleOutline = exports('VcGeometryRectangleOutline', GeometryRectangleOutline);
const VcGeometrySimplePolyline = exports('VcGeometrySimplePolyline', GeometrySimplePolyline);
const VcGeometrySphere = exports('VcGeometrySphere', GeometrySphere);
const VcGeometrySphereOutline = exports('VcGeometrySphereOutline', GeometrySphereOutline);
const VcGeometryWall = exports('VcGeometryWall', GeometryWall);
const VcGeometryWallOutline = exports('VcGeometryWallOutline', GeometryWallOutline);
/**
* @module helpers
*/
/**
* Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.
*
* @memberof helpers
* @type {number}
*/
var earthRadius = 6371008.8;
/**
* Unit of measurement factors using a spherical (non-ellipsoid) earth radius.
*
* @memberof helpers
* @type {Object}
*/
var factors = {
centimeters: earthRadius * 100,
centimetres: earthRadius * 100,
degrees: earthRadius / 111325,
feet: earthRadius * 3.28084,
inches: earthRadius * 39.37,
kilometers: earthRadius / 1000,
kilometres: earthRadius / 1000,
meters: earthRadius,
metres: earthRadius,
miles: earthRadius / 1609.344,
millimeters: earthRadius * 1000,
millimetres: earthRadius * 1000,
nauticalmiles: earthRadius / 1852,
radians: 1,
yards: earthRadius * 1.0936,
};
/**
* Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.
*
* @name feature
* @param {Geometry} geometry input geometry
* @param {Object} [properties={}] an Object of key-value pairs to add as properties
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
* @param {string|number} [options.id] Identifier associated with the Feature
* @returns {Feature} a GeoJSON Feature
* @example
* var geometry = {
* "type": "Point",
* "coordinates": [110, 50]
* };
*
* var feature = turf.feature(geometry);
*
* //=feature
*/
function feature(geom, properties, options) {
if (options === void 0) { options = {}; }
var feat = { type: "Feature" };
if (options.id === 0 || options.id) {
feat.id = options.id;
}
if (options.bbox) {
feat.bbox = options.bbox;
}
feat.properties = properties || {};
feat.geometry = geom;
return feat;
}
/**
* Creates a {@link Point} {@link Feature} from a Position.
*
* @name point
* @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)
* @param {Object} [properties={}] an Object of key-value pairs to add as properties
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
* @param {string|number} [options.id] Identifier associated with the Feature
* @returns {Feature<Point>} a Point feature
* @example
* var point = turf.point([-75.343, 39.984]);
*
* //=point
*/
function point(coordinates, properties, options) {
if (options === void 0) { options = {}; }
if (!coordinates) {
throw new Error("coordinates is required");
}
if (!Array.isArray(coordinates)) {
throw new Error("coordinates must be an Array");
}
if (coordinates.length < 2) {
throw new Error("coordinates must be at least 2 numbers long");
}
if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) {
throw new Error("coordinates must contain numbers");
}
var geom = {
type: "Point",
coordinates: coordinates,
};
return feature(geom, properties, options);
}
/**
* Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.
*
* @name polygon
* @param {Array<Array<Array<number>>>} coordinates an array of LinearRings
* @param {Object} [properties={}] an Object of key-value pairs to add as properties
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
* @param {string|number} [options.id] Identifier associated with the Feature
* @returns {Feature<Polygon>} Polygon Feature
* @example
* var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });
*
* //=polygon
*/
function polygon(coordinates, properties, options) {
if (options === void 0) { options = {}; }
for (var _i = 0, coordinates_1 = coordinates; _i < coordinates_1.length; _i++) {
var ring = coordinates_1[_i];
if (ring.length < 4) {
throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");
}
for (var j = 0; j < ring[ring.length - 1].length; j++) {
// Check if first point of Polygon contains two numbers
if (ring[ring.length - 1][j] !== ring[0][j]) {
throw new Error("First and last Position are not equivalent.");
}
}
}
var geom = {
type: "Polygon",
coordinates: coordinates,
};
return feature(geom, properties, options);
}
/**
* Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians
* Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet
*
* @name lengthToRadians
* @param {number} distance in real units
* @param {string} [units="kilometers"] can be degrees, radians, miles, inches, yards, metres,
* meters, kilometres, kilometers.
* @returns {number} radians
*/
function lengthToRadians(distance, units) {
if (units === void 0) { units = "kilometers"; }
var factor = factors[units];
if (!factor) {
throw new Error(units + " units is invalid");
}
return distance / factor;
}
/**
* Converts an angle in radians to degrees
*
* @name radiansToDegrees
* @param {number} radians angle in radians
* @returns {number} degrees between 0 and 360 degrees
*/
function radiansToDegrees(radians) {
var degrees = radians % (2 * Math.PI);
return (degrees * 180) / Math.PI;
}
/**
* Converts an angle in degrees to radians
*
* @name degreesToRadians
* @param {number} degrees angle between 0 and 360 degrees
* @returns {number} angle in radians
*/
function degreesToRadians(degrees) {
var radians = degrees % 360;
return (radians * Math.PI) / 180;
}
/**
* isNumber
*
* @param {*} num Number to validate
* @returns {boolean} true/false
* @example
* turf.isNumber(123)
* //=true
* turf.isNumber('foo')
* //=false
*/
function isNumber(num) {
return !isNaN(num) && num !== null && !Array.isArray(num);
}
/**
* Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.
*
* @name getCoord
* @param {Array<number>|Geometry<Point>|Feature<Point>} coord GeoJSON Point or an Array of numbers
* @returns {Array<number>} coordinates
* @example
* var pt = turf.point([10, 10]);
*
* var coord = turf.getCoord(pt);
* //= [10, 10]
*/
function getCoord(coord) {
if (!coord) {
throw new Error("coord is required");
}
if (!Array.isArray(coord)) {
if (coord.type === "Feature" &&
coord.geometry !== null &&
coord.geometry.type === "Point") {
return coord.geometry.coordinates;
}
if (coord.type === "Point") {
return coord.coordinates;
}
}
if (Array.isArray(coord) &&
coord.length >= 2 &&
!Array.isArray(coord[0]) &&
!Array.isArray(coord[1])) {
return coord;
}
throw new Error("coord must be GeoJSON Point or an Array of numbers");
}
// http://en.wikipedia.org/wiki/Haversine_formula
/**
* Takes a {@link Point} and calculates the location of a destination point given a distance in
* degrees, radians, miles, or kilometers; and bearing in degrees.
* This uses the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to account for global curvature.
*
* @name destination
* @param {Coord} origin starting point
* @param {number} distance distance from the origin point
* @param {number} bearing ranging from -180 to 180
* @param {Object} [options={}] Optional parameters
* @param {string} [options.units='kilometers'] miles, kilometers, degrees, or radians
* @param {Object} [options.properties={}] Translate properties to Point
* @returns {Feature<Point>} destination point
* @example
* var point = turf.point([-75.343, 39.984]);
* var distance = 50;
* var bearing = 90;
* var options = {units: 'miles'};
*
* var destination = turf.destination(point, distance, bearing, options);
*
* //addToMap
* var addToMap = [point, destination]
* destination.properties['marker-color'] = '#f00';
* point.properties['marker-color'] = '#0f0';
*/
function destination(origin, distance, bearing, options) {
if (options === void 0) { options = {}; }
// Handle input
var coordinates1 = getCoord(origin);
var longitude1 = degreesToRadians(coordinates1[0]);
var latitude1 = degreesToRadians(coordinates1[1]);
var bearingRad = degreesToRadians(bearing);
var radians = lengthToRadians(distance, options.units);
// Main
var latitude2 = Math.asin(Math.sin(latitude1) * Math.cos(radians) +
Math.cos(latitude1) * Math.sin(radians) * Math.cos(bearingRad));
var longitude2 = longitude1 +
Math.atan2(Math.sin(bearingRad) * Math.sin(radians) * Math.cos(latitude1), Math.cos(radians) - Math.sin(latitude1) * Math.sin(latitude2));
var lng = radiansToDegrees(longitude2);
var lat = radiansToDegrees(latitude2);
return point([lng, lat], options.properties);
}
/**
* Takes a {@link Point} and calculates the circle polygon given a radius in degrees, radians, miles, or kilometers; and steps for precision.
*
* @name circle
* @param {Feature<Point>|number[]} center center point
* @param {number} radius radius of the circle
* @param {Object} [options={}] Optional parameters
* @param {number} [options.steps=64] number of steps
* @param {string} [options.units='kilometers'] miles, kilometers, degrees, or radians
* @param {Object} [options.properties={}] properties
* @returns {Feature<Polygon>} circle polygon
* @example
* var center = [-75.343, 39.984];
* var radius = 5;
* var options = {steps: 10, units: 'kilometers', properties: {foo: 'bar'}};
* var circle = turf.circle(center, radius, options);
*
* //addToMap
* var addToMap = [turf.point(center), circle]
*/
function circle(center, radius, options) {
if (options === void 0) { options = {}; }
// default params
var steps = options.steps || 64;
var properties = options.properties
? options.properties
: !Array.isArray(center) && center.type === "Feature" && center.properties
? center.properties
: {};
// main
var coordinates = [];
for (var i = 0; i < steps; i++) {
coordinates.push(destination(center, radius, (i * -360) / steps, options).geometry
.coordinates);
}
coordinates.push(coordinates[0]);
return polygon([coordinates], properties);
}
const defaultPointProps = {
color: "#409eff",
pixelSize: 8,
outlineColor: "rgba(0,0,0,0.6)",
outlineWidth: 1,
disableDepthTestDistance: Number.POSITIVE_INFINITY
};
const defaultLinePrimitiveProps = {
enableMouseEvent: false,
asynchronous: false,
allowPicking: true
};
const defaultLineGeometryProps = {
width: 2,
show: true
};
const defaultLabelProps = {
pixelOffset: [20, 0],
showBackground: true,
backgroundColor: "rgba(0,0,0,1)",
enableMouseEvent: false
};
const typhoonOverlayProps = exports('typhoonOverlayProps', {
typhoonRoutes: {
type: Array
},
clampToGround: {
type: Boolean,
default: false
},
radius7Color: {
type: String,
default: "rgba(68, 255, 230, 0.3)"
},
radius10Color: {
type: String,
default: "rgba(32, 237, 39, 0.3)"
},
radius12Color: {
type: String,
default: "rgba(255, 247, 16, 0.3)"
},
pointProps: {
type: [Object, Function],
default: () => defaultPointProps
},
linePrimitiveProps: {
type: [Object, Function],
default: () => defaultLinePrimitiveProps
},
lineGeometryProps: {
type: [Object, Function],
default: () => defaultLineGeometryProps
},
labelProps: {
type: [Object, Function],
default: () => defaultLabelProps
},
circleOverlayPosition: {
type: [String, Function],
default: "-175px"
},
setsArray: {
type: Array,
default: () => ["\u4E2D\u592E\u53F0", "\u65E5\u672C", "\u7F8E\u56FD", "\u97E9\u56FD", "\u4E2D\u56FD\u9999\u6E2F"]
}
});
const emits$4 = {
...commonEmits,
mouseover: (e) => true,
mouseout: (e) => true,
click: (e) => true,
clickout: (e) => true,
forecastRouteAdded: (e) => true
};
var OverlayTyphoon = defineComponent({
name: "VcOverlayTyphoon",
props: typhoonOverlayProps,
emits: emits$4,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VcOverlayTyphoon";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { $services } = commonState;
const logger = useLog(instance);
const { t } = useLocale();
const primitiveCollectionRef = ref(null);
const typhoonDatasources = reactive([]);
instance.createCesiumObject = async () => {
return primitiveCollectionRef;
};
const addTyphoonPath = (index, datasource) => {
datasource.playIndex = index;
const point = datasource.typhoonRoute.points[index];
point.type = "live";
point.index = index;
point.tfbh = datasource.name;
const position = [point.lng, point.lat];
datasource.positions.push(position);
const pointProps = typeof props.pointProps === "function" ? deepMerge(cloneDeep(defaultPointProps), props.pointProps(point)) : props.pointProps;
datasource.points.push({
id: point.id || Cesium.createGuid(),
position,
onMouseover(evt) {
ctx.emit("mouseover", evt);
},
onMouseout(evt) {
ctx.emit("mouseout", evt);
},
onClick(evt) {
showForecast(point, datasource, index, true);
datasource.playIndex = point.index;
ctx.emit("click", evt);
},
onClickout(evt) {
ctx.emit("clickout", evt);
},
...pointProps,
...point
});
const lastPoint = datasource.points[index];
lastPoint && datasource.colors.push(lastPoint.color);
if (index === datasource.typhoonRoute.points.length - 1) {
showForecast(point, datasource, index);
}
};
const playTyphoonRoute = (tfbh) => {
const typhoonDatasourceIndex = typhoonDatasources.findIndex((datasource) => datasource.name === tfbh);
if (typhoonDatasourceIndex >= 0) {
let index = 0;
const datasource = typhoonDatasources[typhoonDatasourceIndex];
datasource.points.length = 0;
datasource.positions.length = 0;
const typhoonData = datasource.typhoonRoute;
addTyphoonPath(index, datasource);
cancelAnimationFrame(datasource.playInterval);
const animation = () => {
index++;
if (index >= typhoonData.points.length) {
cancelAnimationFrame(datasource.playInterval);
} else {
addTyphoonPath(index, datasource);
}
datasource.playInterval = requestAnimationFrame(animation);
};
datasource.playInterval = requestAnimationFrame(animation);
} else {
logger.warn(t(`vc.typhoon.warn`) || "\u64AD\u653E\u53F0\u98CE\u5931\u8D25\uFF0C\u539F\u56E0\uFF1A\u672A\u627E\u5230\u5BF9\u5E94\u7F16\u53F7\u7684\u53F0\u98CE\u6570\u636E\u3002");
}
};
const showForecast = (livePoint, datasource, index, fromClick = false) => {
datasource.children.length = 0;
let forecast = fromClick ? livePoint.forecast || [] : [];
if (!fromClick) {
for (let i = 0; i < props.setsArray.length; i++) {
const f = (livePoint2, index2) => {
const forecastRaw = (livePoint2 == null ? void 0 : livePoint2.forecast) || [];
forecast.push(...forecastRaw);
if (fromClick) {
return;
}
forecast = uniqWith(forecast, (a, b) => a.sets === b.sets);
const sets = props.setsArray[i];
const setsIndex = forecast.findIndex((v) => v.sets === sets);
if (setsIndex > -1) {
if (!forecast[setsIndex].unshifted) {
forecast[setsIndex].points.unshift({
lat: livePoint2.lat,
lng: livePoint2.lng
});
forecast[setsIndex].unshifted = true;
}
} else if (index2 > 0) {
const preLivePoint = datasource.typhoonRoute.points[index2 - 1];
f(preLivePoint, index2 - 1);
}
};
f(livePoint, index);
}
}
if (!forecast || forecast.length <= 0) {
return;
}
for (let i = 0; i < forecast.length; i++) {
const typhoonRouteBySet = forecast[i];
const points = [];
const positions = [];
const datasourceBySet = {
name: datasource.name + "_" + typhoonRouteBySet.sets,
typhoonRoute: typhoonRouteBySet,
show: true,
positions,
points,
type: "forc"
};
datasource.children.push(datasourceBySet);
typhoonRouteBySet.points.forEach((point, index2) => {
const position = [point.lng, point.lat];
datasourceBySet.positions.push(position);
if (index2 === 0 && fromClick) {
datasourceBySet.positions.unshift([livePoint.lng, livePoint.lat]);
}
point.sets = typhoonRouteBySet.sets;
point.type = "forc";
point.index = index2;
const pointProps = typeof props.pointProps === "function" ? props.pointProps(point) : props.pointProps;
index2 !== 0 && datasourceBySet.points.push({
id: point.id || Cesium.createGuid(),
position,
onMouseover(evt) {
ctx.emit("mouseover", evt);
},
onMouseout(evt) {
ctx.emit("mouseout", evt);
},
onClick(evt) {
ctx.emit("click", evt);
},
...pointProps,
...point
});
});
}
ctx.emit("forecastRouteAdded", {
livePoint,
datasource,
addedByClick: fromClick
});
};
const addTyphoonRoute = (typhoonRoute) => {
const points = [];
const positions = [];
const typhoonDatasource = {
name: typhoonRoute.tfbh,
typhoonRoute,
show: true,
positions,
points,
children: [],
colors: [],
type: "live"
};
typhoonDatasources.push(typhoonDatasource);
playTyphoonRoute(typhoonRoute.tfbh);
return typhoonDatasource;
};
const flyToTyphoonRoute = (typhoon, options) => {
const names = [];
if (typeof typhoon === "string") {
names.push(typhoon);
} else {
names.push(...typhoon);
}
let boundingSphereUnion = null;
names.forEach((name) => {
var _a;
const positions = [];
const typhoonDatasource = typhoonDatasources.find((v) => v.name === name);
if (typhoonDatasource && typhoonDatasource.typhoonRoute.points) {
typhoonDatasource.typhoonRoute.points.forEach((point) => {
positions.push([point.lng, point.lat]);
});
}
if ((_a = typhoonDatasource == null ? void 0 : typhoonDatasource.children) == null ? void 0 : _a.length) {
typhoonDatasource.children.forEach((v) => {
v.typhoonRoute.points.forEach((point) => {
positions.push([point.lng, point.lat]);
});
});
}
const cartesian3Array = makeCartesian3Array(positions);
const boundingSphere = Cesium.BoundingSphere.fromPoints(cartesian3Array);
if (null === boundingSphereUnion) {
boundingSphereUnion = boundingSphere;
} else {
boundingSphereUnion = Cesium.BoundingSphere.union(boundingSphereUnion, boundingSphere);
}
});
$services.viewer.camera.flyToBoundingSphere(new Cesium.BoundingSphere(boundingSphereUnion.center, boundingSphereUnion.radius), {
...options
});
};
const removeTyphoonData = (datasource) => {
const index = typhoonDatasources.indexOf(datasource);
if (index >= 0) {
clearInterval(datasource.playInterval);
typhoonDatasources.splice(index, 1);
}
};
const removeAllTyphoonData = () => {
typhoonDatasources.forEach((datasource) => {
clearInterval(datasource.playInterval);
});
typhoonDatasources.length = 0;
};
const getTyphoonCirclePostions = (center, radiusData) => {
let positions = [];
if (typeof radiusData === "number") {
positions = circle(center, radiusData * 1e3, {
units: "meters"
}).geometry.coordinates;
} else if (radiusData["ne"]) {
const _angInterval = 6;
const _pointNums = 360 / (_angInterval * 4);
const quadrant = {
// 逆时针算角度
"0": "ne",
"1": "nw",
"2": "sw",
"3": "se"
};
for (let i = 0; i < 4; i++) {
let _r = parseFloat(radiusData[quadrant[i]]) * 1e3;
if (!_r)
_r = 0;
for (let j = i * _pointNums; j <= (i + 1) * _pointNums; j++) {
const _ang = _angInterval * j;
const x = center[0] + _r * Math.cos(_ang * Math.PI / 180) / 111e3;
const y = center[1] + _r * Math.sin(_ang * Math.PI / 180) / 111e3;
positions.push([x, y]);
}
}
}
return positions;
};
const getChildren = (datasources, centerPointCircle) => {
const children = [];
datasources.forEach((typhoonDatasource) => {
if (typhoonDatasource.positions.length > 1) {
const linePrimitiveProps = typeof props.linePrimitiveProps === "function" ? deepMerge(cloneDeep(defaultLinePrimitiveProps), props.linePrimitiveProps(typhoonDatasource)) : props.linePrimitiveProps;
const lineGeometryProps = typeof props.lineGeometryProps === "function" ? deepMerge(cloneDeep(defaultLineGeometryProps), props.lineGeometryProps(typhoonDatasource)) : props.lineGeometryProps;
children.push(
h(
VcPrimitive,
{
show: typhoonDatasource.show,
appearance: {
type: typhoonDatasource.type === "live" ? "PolylineColorAppearance" : "PolylineMaterialAppearance",
options: {
material: typhoonDatasource.type === "live" ? void 0 : {
fabric: {
type: "PolylineDash",
uniforms: {
color: "#000000"
}
}
},
translucent: true
}
},
onMouseover: (evt) => {
ctx.emit("mouseover", evt);
},
onMouseout: (evt) => {
ctx.emit("mouseout", evt);
},
onClick: (evt) => {
ctx.emit("click", evt);
},
onClickout: (evt) => {
ctx.emit("clickout", evt);
},
...linePrimitiveProps
},
() => h(
VcGeometryInstance,
{
id: typhoonDatasource.name || Cesium.createGuid()
},
() => h(VcGeometryPolyline, {
positions: makeCartesian3Array(typhoonDatasource.positions),
colors: typhoonDatasource.colors,
...lineGeometryProps
})
)
)
);
}
typhoonDatasource.points.length && children.push(
h(VcCollectionPoint, {
show: typhoonDatasource.show,
points: typhoonDatasource.points,
onReady: (e) => {
const { cesiumObject: pointPrimitiveCollection } = e;
const originalUpdate = pointPrimitiveCollection.update;
pointPrimitiveCollection.update = function(frameState) {
const originalLength = frameState.commandList.length;
originalUpdate.call(this, frameState);
const endLength = frameState.commandList.length;
for (let i = originalLength; i < endLength; ++i) {
frameState.commandList[i].pass = Cesium["Pass"].TRANSLUCENT;
frameState.commandList[i].renderState = Cesium["RenderState"].fromCache({
depthTest: {
enabled: false
},
depthMask: false
});
}
};
}
})
);
if (typhoonDatasource.type === "live") {
const labelProps = typeof props.labelProps === "function" ? deepMerge(cloneDeep(defaultLabelProps), props.labelProps(typhoonDatasource)) : props.labelProps;
children.push(
h(VcCollectionLabel, {
show: typhoonDatasource.show,
enableMouseEvent: false,
labels: [
{
text: typhoonDatasource.typhoonRoute.name,
position: typhoonDatasource.positions[0],
...labelProps
}
]
})
);
const point = typhoonDatasource.points[typhoonDatasource.playIndex];
centerPointCircle.length = // 旋转图形
centerPointCircle.push(
h(
OverlayHtml,
{ show: typhoonDatasource.show, position: point.position, autoHidden: true },
() => h("div", {
class: "vc-typhoon-circle",
style: {
backgroundPosition: typeof props.circleOverlayPosition == "function" ? props.circleOverlayPosition(point) : props.circleOverlayPosition
}
})
)
);
if ((point == null ? void 0 : point.radius7) > 0) {
children.push(
h(VcPolygon, {
show: typhoonDatasource.show,
positions: getTyphoonCirclePostions(point.position, point.radius7_quad),
clampToGround: props.clampToGround,
asynchronous: false,
allowPicking: false,
enableMouseEvent: false,
classificationType: 2,
appearance: {
type: "MaterialAppearance",
options: {
material: {
fabric: {
type: "Color",
uniforms: {
color: props.radius7Color
}
}
}
}
},
onReady: onVcPolygonReady
})
);
}
if ((point == null ? void 0 : point.radius10) > 0) {
children.push(
h(VcPolygon, {
show: typhoonDatasource.show,
positions: getTyphoonCirclePostions(point.position, point.radius10_quad),
clampToGround: props.clampToGround,
asynchronous: false,
allowPicking: false,
enableMouseEvent: false,
classificationType: 2,
appearance: {
type: "MaterialAppearance",
options: {
material: {
fabric: {
type: "Color",
uniforms: {
color: props.radius10Color
}
}
}
}
},
onReady: onVcPolygonReady
})
);
}
if ((point == null ? void 0 : point.radius12) > 0) {
children.push(
h(VcPolygon, {
show: typhoonDatasource.show,
positions: getTyphoonCirclePostions(point.position, point.radius12_quad),
clampToGround: props.clampToGround,
asynchronous: false,
allowPicking: false,
enableMouseEvent: false,
classificationType: 2,
appearance: {
type: "MaterialAppearance",
options: {
material: {
fabric: {
type: "Color",
uniforms: {
color: props.radius12Color
}
}
}
}
},
onReady: onVcPolygonReady
})
);
}
}
if (typhoonDatasource.children) {
children.push(...getChildren(typhoonDatasource.children, centerPointCircle));
}
});
return children;
};
const onVcPolygonReady = (e) => {
const primitive = e.cesiumObject;
const originalPrimitiveUpdate = primitive.update;
primitive.update = function(frameState) {
const originalLength = frameState.commandList.length;
originalPrimitiveUpdate.call(this, frameState);
const endLength = frameState.commandList.length;
for (let i = originalLength; i < endLength; ++i) {
if (frameState.commandList[i].pass !== Cesium["Pass"].TRANSLUCENT) {
continue;
}
frameState.commandList[i].pass = Cesium["Pass"].OPAQUE;
frameState.commandList[i].renderState = Cesium["RenderState"].fromCache({
depthTest: {
enabled: false
},
depthMask: false,
blending: Cesium.BlendingState.ALPHA_BLEND
});
}
};
};
Object.assign(instance.proxy, {
addTyphoonRoute,
playTyphoonRoute,
flyToTyphoonRoute,
showForecast,
removeTyphoonData,
removeAllTyphoonData,
getTyphoonDatasources: () => typhoonDatasources
});
props.typhoonRoutes.forEach((typhoonData) => {
addTyphoonRoute(typhoonData);
});
return () => {
const centerPointCircle = [];
const children = getChildren(typhoonDatasources, centerPointCircle);
return [
h(
VcCollectionPrimitive,
{
ref: primitiveCollectionRef,
show: true
// onReady: e => {
// ctx.emit('ready', e)
// }
},
() => children
),
...centerPointCircle
];
};
}
});
const components$5 = [OverlayHtml, OverlayHeatmap, OverlayEcharts, OverlayWind, OverlayDynamic, OverlayTyphoon];
components$5.forEach((cmp) => {
cmp["install"] = (app) => {
app.component(cmp.name, cmp);
};
});
const VcOverlayHtml = exports('VcOverlayHtml', OverlayHtml);
const VcOverlayHeatmap = exports('VcOverlayHeatmap', OverlayHeatmap);
const VcOverlayEcharts = exports('VcOverlayEcharts', OverlayEcharts);
const VcOverlayWind = exports('VcOverlayWind', OverlayWind);
const VcOverlayDynamic = exports('VcOverlayDynamic', OverlayDynamic);
const VcOverlayTyphoon = exports('VcOverlayTyphoon', OverlayTyphoon);
function useDrawingAction(props, ctx, instance, cmpName, $services) {
instance.cesiumClass = cmpName;
instance.cesiumEvents = [];
const { t } = useLocale();
const { emit } = ctx;
const tips = kebabCase(cmpName).split("-");
if (cmpName === "VcMeasurementDistance" && props.showComponentLines) {
tips[2] = "component-distance";
}
if (cmpName === "VcDrawingRegular" || cmpName === "VcMeasurementRegular") {
if (props.edge === 4) {
tips[2] = "rectangle";
}
if (props.edge === 360) {
tips[2] = "circle";
}
}
let drawingType = tips[2];
tips[3] && (drawingType = `${tips[2]}-${tips[3]}`);
const drawTip = ref("");
const drawTipOpts = computed(() => {
return {
drawingTipStart: props.drawtip.drawingTipStart || t(`${tips[0]}.${tips[1]}.${tips[2]}.drawingTipStart`),
drawingTipEnd: props.drawtip.drawingTipEnd || t(`${tips[0]}.${tips[1]}.${tips[2]}.drawingTipEnd`),
drawingTipEditing: props.drawtip.drawingTipEditing || t(`${tips[0]}.${tips[1]}.${tips[2]}.drawingTipEditing`)
};
});
const drawStatus = ref(DrawStatus.BeforeDraw);
const canShowDrawTip = ref(false);
const drawTipPosition = ref([0, 0, 0]);
const showEditor = ref(false);
const editorPosition = ref([0, 0, 0]);
const mouseoverPoint = ref(null);
const editingPoint = ref(null);
const primitiveCollectionRef = ref(null);
const editorType = ref("");
const { registerTimeout, removeTimeout } = useTimeout();
instance.createCesiumObject = async () => {
return primitiveCollectionRef;
};
const onMouseoverPoints = (e) => {
var _a, _b;
const { drawingHandlerActive, viewer } = $services;
if (props.editable && drawStatus.value !== DrawStatus.Drawing && drawingHandlerActive) {
e.pickedFeature.primitive.pixelSize = ((_a = props.pointOpts) == null ? void 0 : _a.pixelSize) * 1.5;
removeTimeout();
registerTimeout(() => {
mouseoverPoint.value = e.pickedFeature.primitive;
editorPosition.value = e.pickedFeature.primitive.position;
showEditor.value = true;
canShowDrawTip.value = false;
drawTipPosition.value = [0, 0, 0];
}, (_b = props.editorOpts) == null ? void 0 : _b.delay);
}
emit(
"mouseEvt",
{
type: e.type,
name: drawingType,
target: e
},
viewer
);
};
const onMouseoutPoints = (e) => {
var _a, _b;
const { viewer, selectedDrawingActionInstance } = $services;
if (props.editable) {
e.pickedFeature.primitive.pixelSize = ((_a = props.pointOpts) == null ? void 0 : _a.pixelSize) * 1;
removeTimeout();
registerTimeout(() => {
editorPosition.value = [0, 0, 0];
mouseoverPoint.value = void 0;
showEditor.value = false;
}, (_b = props.editorOpts) == null ? void 0 : _b.hideDelay);
selectedDrawingActionInstance && (canShowDrawTip.value = true);
}
emit(
"mouseEvt",
{
type: e.type,
name: drawingType,
target: e
},
viewer
);
};
const onMouseenterEditor = (evt) => {
removeTimeout();
};
const onMouseleaveEditor = (evt) => {
var _a;
removeTimeout();
registerTimeout(() => {
var _a2;
editorPosition.value = [0, 0, 0];
mouseoverPoint.value.pixelSize = ((_a2 = props.pointOpts) == null ? void 0 : _a2.pixelSize) * 1;
mouseoverPoint.value = void 0;
showEditor.value = false;
}, (_a = props.editorOpts) == null ? void 0 : _a.hideDelay);
};
const onPrimitiveCollectionReady = (readyObj) => {
readyObj.cesiumObject._vcId = cmpName;
};
const onVcCollectionPointReady = function(e) {
const { cesiumObject: pointPrimitiveCollection } = e;
const originalUpdate = pointPrimitiveCollection.update;
pointPrimitiveCollection.update = function(frameState) {
const originalLength = frameState.commandList.length;
originalUpdate.call(this, frameState);
const endLength = frameState.commandList.length;
for (let i = originalLength; i < endLength; ++i) {
frameState.commandList[i].pass = Cesium["Pass"].TRANSLUCENT;
frameState.commandList[i].renderState = Cesium["RenderState"].fromCache({
depthTest: {
enabled: false
},
depthMask: false
});
}
};
};
const onVcCollectionLabelReady = (e) => {
if (props.disableDepthTest)
return;
const labelCollection = e.cesiumObject;
const originalUpdate = labelCollection.update;
labelCollection.update = function(frameState) {
const originalLength = frameState.commandList.length;
originalUpdate.call(this, frameState);
const endLength = frameState.commandList.length;
for (let i = originalLength; i < endLength; ++i) {
frameState.commandList[i].pass = Cesium["Pass"].OVERLAY;
frameState.commandList[i].renderState = Cesium["RenderState"].fromCache({
depthTest: {
enabled: false
},
depthMask: false,
blending: Cesium.BlendingState.ALPHA_BLEND
});
}
};
};
const onVcPrimitiveReady = (e) => {
if (props.disableDepthTest)
return;
const primitive = e.cesiumObject;
const originalPrimitiveUpdate = primitive.update;
primitive.update = function(frameState) {
const originalLength = frameState.commandList.length;
originalPrimitiveUpdate.call(this, frameState);
const endLength = frameState.commandList.length;
for (let i = originalLength; i < endLength; ++i) {
if (frameState.commandList[i].pass !== Cesium["Pass"].TRANSLUCENT) {
continue;
}
frameState.commandList[i].pass = Cesium["Pass"].OPAQUE;
frameState.commandList[i].renderState = Cesium["RenderState"].fromCache({
depthTest: {
enabled: false
},
depthMask: false,
blending: Cesium.BlendingState.ALPHA_BLEND
});
}
};
};
return {
drawingType,
drawTip,
drawTipOpts,
drawStatus,
canShowDrawTip,
drawTipPosition,
showEditor,
editorPosition,
mouseoverPoint,
editingPoint,
primitiveCollectionRef,
editorType,
onMouseoverPoints,
onMouseoutPoints,
onMouseenterEditor,
onMouseleaveEditor,
onPrimitiveCollectionReady,
onVcCollectionPointReady,
onVcPrimitiveReady,
onVcCollectionLabelReady
};
}
function useDrawingSegment(props, ctx, cmpName) {
const instance = getCurrentInstance();
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { t } = useLocale();
const $services = commonState.$services;
const { emit } = ctx;
const {
drawingType,
drawTip,
drawTipOpts,
drawStatus,
canShowDrawTip,
drawTipPosition,
showEditor,
editorPosition,
mouseoverPoint,
editingPoint,
primitiveCollectionRef,
editorType,
onMouseoverPoints,
onMouseoutPoints,
onMouseenterEditor,
onMouseleaveEditor,
onPrimitiveCollectionReady,
onVcCollectionPointReady,
onVcCollectionLabelReady,
onVcPrimitiveReady
} = useDrawingAction(props, ctx, instance, cmpName, $services);
const renderDatas = ref([]);
if (props.preRenderDatas && props.preRenderDatas.length) {
props.preRenderDatas.forEach((preRenderData) => {
const segmentDrawing = {
positions: makeCartesian3Array(preRenderData),
show: true,
drawStatus: DrawStatus.AfterDraw,
distance: 0,
labels: [],
pointOpts: {},
labelOpts: {},
labelsOpts: {},
polylineOpts: {},
primitiveOpts: {},
polygonOpts: {}
};
cmpName === "VcMeasurementVertical" && Object.assign(segmentDrawing, {
draggingPlane: new Cesium.Plane(Cesium.Cartesian3.UNIT_X, 0),
surfaceNormal: new Cesium.Cartesian3()
});
renderDatas.value.push(segmentDrawing);
});
}
let restorePosition;
const computedRenderDatas = computed(() => {
const polylines = [];
const { Cartesian3, Cartographic, Rectangle, createGuid, defined, Math: CesiumMath, Ray } = Cesium;
const { viewer } = $services;
renderDatas.value.forEach((polylineSegment) => {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
const startPosition = polylineSegment.positions[0];
const endPosition = polylineSegment.positions[1];
if (Cartesian3.equals(startPosition, endPosition)) {
return;
}
const labels = reactive([]);
const distance = ((_a = props.polylineOpts) == null ? void 0 : _a.arcType) === 0 ? Cartesian3.distance(startPosition, endPosition) : getGeodesicDistance(startPosition, endPosition, $services.viewer.scene.globe.ellipsoid);
const labelPosition = Cartesian3.midpoint(startPosition, endPosition, {});
const heading = getPolylineSegmentHeading(startPosition, endPosition);
const pitch = getPolylineSegmentPitch(startPosition, endPosition);
polylineSegment.points = polylineSegment.positions.map((v) => {
return {
position: v
};
});
const polyline = {
...polylineSegment,
distance,
heading,
pitch
};
const labelOpts = Object.assign({}, props.labelOpts, polyline.labelOpts);
if (cmpName === "VcDrawingRectangle" || cmpName === "VcMeasurementRectangle") {
const startCartographic = Cartographic.fromCartesian(startPosition, viewer.scene.globe.ellipsoid);
const endCartographic = Cartographic.fromCartesian(endPosition, viewer.scene.globe.ellipsoid);
const height = startCartographic.height;
!props.clampToGround && (endCartographic.height = height);
const rectangle = Rectangle.fromCartesianArray(polylineSegment.positions, viewer.scene.globe.ellipsoid);
const rectangleArr = [
rectangle.west,
rectangle.north,
height,
rectangle.east,
rectangle.north,
height,
rectangle.east,
rectangle.south,
height,
rectangle.west,
rectangle.south,
height,
rectangle.west,
rectangle.north,
height
];
const polygonPositions = Cartesian3.fromRadiansArrayHeights(rectangleArr, viewer.scene.globe.ellipsoid);
Object.assign(polyline, {
polygonPositions,
height
});
} else if (cmpName === "VcDrawingRegular" || cmpName === "VcMeasurementRegular") {
const startPosition2 = polylineSegment.positions[0];
const endPosition2 = polylineSegment.positions[1];
const hpr = getHeadingPitchRoll(startPosition2, endPosition2, viewer.scene);
if (!isUndefined(hpr) && defined(hpr)) {
const polygonPositions = [];
const startCartographic = Cartographic.fromCartesian(startPosition2, viewer.scene.globe.ellipsoid);
const endCartographic = Cartographic.fromCartesian(endPosition2, viewer.scene.globe.ellipsoid);
!props.clampToGround && (endCartographic.height = startCartographic.height);
polygonPositions.push(Cartographic.toCartesian(endCartographic, viewer.scene.globe.ellipsoid));
for (let i = 0; i < (props.edge || 4) - 1; i++) {
const position = getPolylineSegmentEndpoint(
startPosition2,
hpr.heading += Math.PI * 2 / (props.edge || 4),
distance,
viewer.scene.globe.ellipsoid
);
polygonPositions.push(position);
}
Object.assign(polyline, {
polygonPositions,
height: startCartographic.height
});
}
} else if (cmpName === "VcAnalysisViewshed") {
Object.assign(polyline.viewshedOpts, { startPosition, endPosition });
} else if (cmpName === "VcAnalysisSightline") {
if (props.sightlineType === "segment") {
const positionsNew = [];
positionsNew.push(startPosition);
const objectsToExclude = [];
const primitiveCollection = primitiveCollectionRef.value.cesiumObject._primitives;
primitiveCollection.forEach((primitive) => {
if (primitive instanceof Cesium.PointPrimitiveCollection) {
objectsToExclude.push(...primitive._pointPrimitives);
}
if (primitive instanceof Cesium.Primitive) {
objectsToExclude.push(primitive);
}
});
const intersection = getFirstIntersection(startPosition, endPosition, $services.viewer, objectsToExclude);
if (defined(intersection)) {
positionsNew.push(intersection);
}
positionsNew.push(endPosition);
let distance2 = 0;
for (let i = 0; i < positionsNew.length - 1; i++) {
const s = Cartesian3.distance(positionsNew[i], positionsNew[i + 1]);
distance2 = distance2 + s;
}
Object.assign(polyline, {
positions: positionsNew,
distance: distance2
});
} else if (props.sightlineType === "circle") ;
} else {
labels.push({
position: labelPosition,
id: createGuid(),
text: MeasureUnits.distanceToString(distance, (_b = props.measureUnits) == null ? void 0 : _b.distanceUnits, props.locale, (_c = props.decimals) == null ? void 0 : _c.distance),
...labelOpts
});
}
if (polyline.polygonPositions && polyline.polygonPositions.length) {
const labelsOpts = Object.assign({}, props.labelsOpts, polyline.labelsOpts);
const positions = polyline.polygonPositions.slice();
props.loop && positions.length > 2 && positions.push(positions[0]);
for (let i = 0; i < positions.length - 1; i++) {
let s = 0;
if (((_d = props.polylineOpts) == null ? void 0 : _d.arcType) === 0) {
s = getGeodesicDistance(positions[i], positions[i + 1], $services.viewer.scene.globe.ellipsoid);
} else {
s = Cartesian3.distance(positions[i], positions[i + 1]);
}
if (s > 0 && positions.length > 2 && props.showDistanceLabel) {
labels.push({
text: MeasureUnits.distanceToString(s, (_e = props.measureUnits) == null ? void 0 : _e.distanceUnits, props.locale, (_f = props.decimals) == null ? void 0 : _f.distance),
position: Cartesian3.midpoint(positions[i], positions[i + 1], {}),
id: createGuid(),
...labelsOpts
});
}
if (positions.length > 2 && props.showAngleLabel) {
if (i > 0 || props.loop) {
const point0 = positions[i === 0 ? positions.length - 2 : i - 1];
const point1 = positions[i];
const point2 = positions[i + 1];
const diffrence1 = Cartesian3.subtract(point0, point1, {});
const diffrence2 = Cartesian3.subtract(point2, point1, {});
let angle = 0;
if (!(Cartesian3.ZERO.equals(diffrence1) || Cartesian3.ZERO.equals(diffrence2))) {
angle = Cartesian3.angleBetween(diffrence1, diffrence2);
}
labels.push({
text: MeasureUnits.angleToString(angle, (_g = props.measureUnits) == null ? void 0 : _g.angleUnits, props.locale, (_h = props.decimals) == null ? void 0 : _h.angle),
position: point1,
id: createGuid(),
...labelsOpts
});
}
}
}
const area = calculateAreaByPostions(positions);
props.showLabel && labels.push({
text: MeasureUnits.areaToString(area, (_i = props.measureUnits) == null ? void 0 : _i.areaUnits, props.locale, (_j = props.decimals) == null ? void 0 : _j.area),
position: polylineSegment.positions[0],
id: createGuid(),
...labelOpts
});
}
if (props.showComponentLines) {
Object.assign(polyline, {
xyPolylinePositions: [new Cartesian3(), new Cartesian3(), new Cartesian3()],
xyBoxPositions: [new Cartesian3(), new Cartesian3(), new Cartesian3()],
xDistance: 0,
yDistance: 0,
xAngle: 0,
yAngle: 0
});
updateComponents(polyline);
labels.push({
position: polyline.xLabelPosition,
id: createGuid(),
text: MeasureUnits.distanceToString(polyline.xDistance || 0, (_k = props.measureUnits) == null ? void 0 : _k.distanceUnits, props.locale, (_l = props.decimals) == null ? void 0 : _l.distance),
...props.xLabelOpts
});
labels.push({
position: polyline.yLabelPosition,
id: createGuid(),
text: MeasureUnits.distanceToString(polyline.yDistance || 0, (_m = props.measureUnits) == null ? void 0 : _m.distanceUnits, props.locale, (_n = props.decimals) == null ? void 0 : _n.distance),
...props.yLabelOpts
});
labels.push({
position: polyline.xAnglePosition,
id: createGuid(),
text: MeasureUnits.angleToString(polyline.xAngle || 0, (_o = props.measureUnits) == null ? void 0 : _o.angleUnits, props.locale, (_p = props.decimals) == null ? void 0 : _p.angle),
...props.xAngleLabelOpts
});
labels.push({
position: polyline.yAnglePosition,
id: createGuid(),
text: MeasureUnits.angleToString(polyline.yAngle || 0, (_q = props.measureUnits) == null ? void 0 : _q.angleUnits, props.locale, (_r = props.decimals) == null ? void 0 : _r.angle),
...props.yAngleLabelOpts
});
}
Object.assign(polyline, {
labels
});
polyline.positionsDegreesArray = polyline.positions.map((v) => {
const cart = Cesium.Cartographic.fromCartesian(v, viewer.scene.globe.ellipsoid);
return [CesiumMath.toDegrees(cart.longitude), CesiumMath.toDegrees(cart.latitude), cart.height];
});
((_s = polyline == null ? void 0 : polyline.polygonPositions) == null ? void 0 : _s.length) && (polyline.polygonPositionsDegreesArray = polyline.polygonPositions.map((v) => {
const cart = Cesium.Cartographic.fromCartesian(v, viewer.scene.globe.ellipsoid);
return [CesiumMath.toDegrees(cart.longitude), CesiumMath.toDegrees(cart.latitude), cart.height];
}));
polylines.push(polyline);
});
return polylines;
});
instance.createCesiumObject = async () => {
return primitiveCollectionRef;
};
instance.mount = async () => {
const { viewer } = $services;
if (props.autoUpdateLabelPosition) {
cmpName === "VcMeasurementDistance" && viewer.scene.preRender.addEventListener(updateLabelPosition);
(cmpName === "VcMeasurementRegular" || cmpName === "VcMeasurementRectangle" || cmpName === "VcDrawingRegular" || cmpName === "VcDrawingRectangle") && viewer.scene.preRender.addEventListener(updateLabelPositionPolygon);
}
return true;
};
instance.unmount = async () => {
const { viewer } = $services;
if (props.autoUpdateLabelPosition) {
cmpName === "VcMeasurementDistance" && viewer.scene.preRender.removeEventListener(updateLabelPosition);
(cmpName === "VcMeasurementRegular" || cmpName === "VcMeasurementRectangle" || cmpName === "VcDrawingRegular" || cmpName === "VcDrawingRectangle") && viewer.scene.preRender.removeEventListener(updateLabelPositionPolygon);
}
return true;
};
const getHeightPosition = (polyline, movement) => {
const { defined, SceneMode, Cartesian3, IntersectionTests, Plane, SceneTransforms, Ray } = Cesium;
const { viewer } = $services;
const scene = viewer.scene;
const camera = scene.camera;
const direction = camera.direction;
const ellipsoid = scene.frameState.mapProjection.ellipsoid;
const positions = polyline.positions;
const p1 = positions[0];
let startPoint = p1;
let endPoint = positions[1];
let draggingPlane = polyline.draggingPlane;
let surfaceNormal = polyline.surfaceNormal;
let normal = surfaceNormal;
if (scene.mode === SceneMode.COLUMBUS_VIEW) {
normal = Cartesian3.UNIT_X;
const startPointCartographic = ellipsoid.cartesianToCartographic(p1, {});
startPoint = scene.mapProjection.project(startPointCartographic, {});
Cartesian3.fromElements(startPoint.z, startPoint.x, startPoint.y, startPoint);
}
let forward = Cartesian3.cross(normal, direction, {});
forward = Cartesian3.cross(normal, forward, forward);
forward = Cartesian3.normalize(forward, forward);
draggingPlane = Plane.fromPointNormal(startPoint, forward, draggingPlane);
const ray = camera.getPickRay(movement, new Ray());
endPoint = IntersectionTests.rayPlane(ray, draggingPlane, {});
if (defined(endPoint)) {
if (scene.mode === SceneMode.COLUMBUS_VIEW) {
endPoint = Cartesian3.fromElements(endPoint.y, endPoint.z, endPoint.x, endPoint);
const endPointCartographic = scene.mapProjection.unproject(endPoint, {});
endPoint = ellipsoid.cartographicToCartesian(endPointCartographic, endPoint);
}
if (SceneTransforms.wgs84ToWindowCoordinates(scene, positions[0], {}).y < movement.y) {
surfaceNormal = Cartesian3.negate(surfaceNormal, {});
}
let diffrence = Cartesian3.subtract(endPoint, p1, {});
diffrence = Cartesian3.projectVector(diffrence, surfaceNormal, diffrence);
endPoint = Cartesian3.add(p1, diffrence, endPoint);
return endPoint;
}
};
const updateComponents = (polyline) => {
const { Cartesian3, Math: CesiumMath, defined } = Cesium;
const { viewer } = $services;
const ellipsoid = viewer.scene.frameState.mapProjection.ellipsoid;
const startPosition = polyline.positions[0];
const endPosition = polyline.positions[1];
const startCartographic = ellipsoid.cartesianToCartographic(startPosition, {});
if (!defined(startCartographic)) {
return;
}
const endCartographic = ellipsoid.cartesianToCartographic(endPosition, {});
const startHeight = startCartographic.height;
const endHeight = endCartographic.height;
let startPoint, endPoint, height1, height2;
if (startHeight < endHeight) {
startPoint = startPosition;
endPoint = endPosition;
height2 = endHeight;
height1 = startHeight;
} else {
startPoint = endPosition;
endPoint = startPosition;
height2 = startHeight;
height1 = endHeight;
}
const xyPolylinePositions = polyline.xyPolylinePositions;
if (xyPolylinePositions === void 0) {
return;
}
xyPolylinePositions[0] = startPoint;
xyPolylinePositions[2] = endPoint;
let normal = ellipsoid.geodeticSurfaceNormal(startPoint, {});
normal = Cartesian3.multiplyByScalar(normal, height2 - height1, normal);
const xyPoint = Cartesian3.add(startPoint, normal, xyPolylinePositions[1]);
if (!(Cartesian3.equalsEpsilon(xyPoint, endPoint, CesiumMath.EPSILON10) && Cartesian3.equalsEpsilon(xyPoint, startPoint, CesiumMath.EPSILON10))) {
let diffrenceX = Cartesian3.subtract(endPoint, xyPoint, {});
let diffrenceY = Cartesian3.subtract(startPoint, xyPoint, {});
const distanceMin = Math.min(Cartesian3.magnitude(diffrenceX), Cartesian3.magnitude(diffrenceY));
const factor = 15 < distanceMin ? 0.15 * distanceMin : 0.25 * distanceMin;
diffrenceX = Cartesian3.normalize(diffrenceX, diffrenceX);
diffrenceY = Cartesian3.normalize(diffrenceY, diffrenceY);
diffrenceX = Cartesian3.multiplyByScalar(diffrenceX, factor, diffrenceX);
diffrenceY = Cartesian3.multiplyByScalar(diffrenceY, factor, diffrenceY);
const xyBoxPositions = polyline.xyBoxPositions;
if (xyBoxPositions === void 0) {
return;
}
Cartesian3.add(xyPoint, diffrenceX, xyBoxPositions[0]);
Cartesian3.add(xyBoxPositions[0], diffrenceY, xyBoxPositions[1]);
Cartesian3.add(xyPoint, diffrenceY, xyBoxPositions[2]);
polyline.xLabelPosition = Cartesian3.midpoint(xyPoint, endPoint, {});
polyline.yLabelPosition = Cartesian3.midpoint(startPoint, xyPoint, {});
polyline.xAnglePosition = endPoint;
polyline.yAnglePosition = startPoint;
const diffrence1 = Cartesian3.subtract(xyPoint, endPoint, {});
const diffrence2 = Cartesian3.subtract(xyPoint, startPoint, {});
let diffrence3 = Cartesian3.subtract(endPoint, startPoint, {});
polyline.yAngle = Cartesian3.angleBetween(diffrence2, diffrence3);
diffrence3 = Cartesian3.negate(diffrence3, diffrence3);
polyline.xAngle = Cartesian3.angleBetween(diffrence1, diffrence3);
polyline.xDistance = Cartesian3.magnitude(diffrence1);
polyline.yDistance = Cartesian3.magnitude(diffrence2);
}
};
const updateLabelPositionPolygon = () => {
computedRenderDatas.value.forEach((polyline, index) => {
var _a;
const positions = polyline.polygonPositions;
if (!(positions.length < 2)) {
const { defined, SceneTransforms, Cartesian2, HorizontalOrigin } = Cesium;
const { viewer } = $services;
const scene = viewer.scene;
let startPosition = polyline.positions[0];
const positionWindow = SceneTransforms.wgs84ToWindowCoordinates(scene, startPosition, {});
let startPositionWindow = defined(positionWindow) ? Cartesian2.clone(positionWindow, {}) : Cartesian2.fromElements(Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, {});
let startY = startPositionWindow.y;
const primitiveCollection = (_a = primitiveCollectionRef.value) == null ? void 0 : _a.cesiumObject;
const labelCollection = primitiveCollection._primitives.filter(
(v) => v instanceof Cesium.LabelCollection
);
const labels = labelCollection[index]._labels;
const labelTotalLength = labels[labels.length - 1];
if (!labelTotalLength)
return;
for (let i = 1; i < positions.length; i++) {
const positionWindow2 = SceneTransforms.wgs84ToWindowCoordinates(scene, positions[i], {});
if (defined(positionWindow2)) {
const l = (startPositionWindow.y - positionWindow2.y) / (positionWindow2.x - startPositionWindow.x);
const label = labels[i - 1];
if (label && label !== labelTotalLength) {
label.horizontalOrigin = 0 < l ? HorizontalOrigin.LEFT : HorizontalOrigin.RIGHT;
}
if (positionWindow2.y < startY) {
startY = positionWindow2.y;
startPosition = positions[i];
}
startPositionWindow = Cartesian2.clone(positionWindow2, startPositionWindow);
}
polyline.drawStatus === DrawStatus.AfterDraw && (labelTotalLength.position = startPosition);
}
}
});
};
const updateLabelPosition = () => {
computedRenderDatas.value.forEach((polyline, index) => {
var _a, _b, _c;
const { defined, SceneTransforms, HorizontalOrigin } = Cesium;
const { viewer } = $services;
const scene = viewer.scene;
const primitiveCollection = (_a = primitiveCollectionRef.value) == null ? void 0 : _a.cesiumObject;
const positions = polyline.positions;
const startPosition = positions[0];
const endPosition = positions[1];
const startPositionWindow = SceneTransforms.wgs84ToWindowCoordinates(scene, startPosition, {});
const endPositionWindow = SceneTransforms.wgs84ToWindowCoordinates(scene, endPosition, {});
if (defined(startPositionWindow) && defined(endPositionWindow)) {
const labelCollection = primitiveCollection._primitives.filter(
(v) => v instanceof Cesium.LabelCollection
);
if (labelCollection.length) {
const label = labelCollection[index].get(0);
let yLabel, xAngleLabel, yPixelOffset, xPixelOffset;
if (props.showComponentLines) {
yLabel = labelCollection[index].get(2);
xAngleLabel = labelCollection[index].get(3);
yPixelOffset = makeCartesian2((_b = props.yLabelOpts) == null ? void 0 : _b.pixelOffset);
xPixelOffset = makeCartesian2((_c = props.xAngleLabelOpts) == null ? void 0 : _c.pixelOffset);
}
if ((startPositionWindow.y - endPositionWindow.y) / (endPositionWindow.x - startPositionWindow.x) > 0) {
if (!isUndefined(yLabel) && !isUndefined(yPixelOffset)) {
yPixelOffset.x = -9;
yLabel.pixelOffset = yPixelOffset;
yLabel.horizontalOrigin = HorizontalOrigin.RIGHT;
}
if (!isUndefined(xAngleLabel) && !isUndefined(xPixelOffset)) {
xPixelOffset.x = 12;
xAngleLabel.pixelOffset = xPixelOffset;
xAngleLabel.horizontalOrigin = HorizontalOrigin.LEFT;
}
label.horizontalOrigin = HorizontalOrigin.LEFT;
} else {
if (!isUndefined(yLabel) && !isUndefined(yPixelOffset)) {
yPixelOffset.x = 9;
yLabel.pixelOffset = yPixelOffset;
yLabel.horizontalOrigin = HorizontalOrigin.LEFT;
}
if (!isUndefined(xAngleLabel) && !isUndefined(xPixelOffset)) {
xPixelOffset.x = -12;
xAngleLabel.pixelOffset = xPixelOffset;
xAngleLabel.horizontalOrigin = HorizontalOrigin.RIGHT;
}
label.horizontalOrigin = HorizontalOrigin.RIGHT;
}
}
}
});
};
const makeHeightPositions = (polyline, position) => {
const { defined, defaultValue, Cartesian3 } = Cesium;
const { viewer } = $services;
const scene = viewer.scene;
const positions = polyline.positions;
positions[0] = position;
const ellipsoid = scene.frameState.mapProjection.ellipsoid;
const postionCartographic = ellipsoid.cartesianToCartographic(position, {});
const globe = scene.globe;
postionCartographic.height = defined(globe) ? defaultValue(globe.getHeight(postionCartographic), 0) : 0;
positions[1] = ellipsoid.cartographicToCartesian(postionCartographic, {});
polyline.distance = Cartesian3.distance(positions[0], positions[1]);
polyline.labelPosition = Cartesian3.midpoint(positions[0], positions[1], {});
};
const startNew = () => {
const { Cartesian3, Plane } = Cesium;
const polyline = {
positions: [new Cartesian3(), new Cartesian3()],
show: false,
drawStatus: DrawStatus.BeforeDraw,
distance: 0,
labels: [],
pointOpts: {},
labelOpts: {},
labelsOpts: {},
polylineOpts: {},
primitiveOpts: {},
polygonOpts: {}
};
cmpName === "VcMeasurementVertical" && Object.assign(polyline, {
draggingPlane: new Plane(Cartesian3.UNIT_X, 0),
surfaceNormal: new Cartesian3()
});
renderDatas.value.push(polyline);
drawStatus.value = DrawStatus.BeforeDraw;
canShowDrawTip.value = true;
drawTip.value = drawTipOpts.value.drawingTipStart;
};
const stop = (removeLatest = true) => {
if (removeLatest && drawStatus.value === DrawStatus.Drawing) {
renderDatas.value.pop();
}
const index = editingPoint.value ? editingPoint.value._vcPolylineIndx : renderDatas.value.length - 1;
const polyline = renderDatas.value[index];
if (polyline) {
polyline.drawStatus = DrawStatus.AfterDraw;
}
drawStatus.value = DrawStatus.AfterDraw;
canShowDrawTip.value = false;
drawTipPosition.value = [0, 0, 0];
};
const handleMouseClick = (movement, options) => {
var _a;
const { viewer, drawingFabInstance, selectedDrawingActionInstance, getWorldPosition } = $services;
const drawingFabInstanceVm = drawingFabInstance == null ? void 0 : drawingFabInstance.proxy;
if (options.button === 2 && options.ctrl) {
const drawingsOption = drawingFabInstanceVm.getDrawingActionInstance(drawingType);
drawingFabInstanceVm.toggleAction(drawingsOption);
nextTick(() => {
emit(
"drawEvt",
{
name: drawingType,
finished: true,
windowPoistion: movement,
type: "cancel"
},
viewer
);
});
return;
}
if (drawStatus.value === DrawStatus.AfterDraw) {
startNew();
}
const index = editingPoint.value ? editingPoint.value._vcPolylineIndx : renderDatas.value.length - 1;
const polyline = renderDatas.value[index];
const positions = polyline.positions;
const pointIndex = editingPoint.value ? editingPoint.value._index : polyline.positions.length - 1;
if (options.button === 2 && editingPoint.value) {
drawingFabInstanceVm.editingActionName = void 0;
polyline.positions[editingPoint.value._index] = restorePosition;
drawStatus.value = DrawStatus.AfterDraw;
polyline.drawStatus = DrawStatus.AfterDraw;
editingPoint.value = void 0;
drawTip.value = drawTipOpts.value.drawingTipStart;
if (cmpName === "VcMeasurementHeight") {
makeHeightPositions(polyline, restorePosition);
}
nextTick(() => {
emit(
"drawEvt",
Object.assign(
{
name: drawingType,
index,
pointIndex,
renderDatas,
finished: true,
windowPoistion: movement,
type: "cancel"
},
computedRenderDatas.value[index]
),
viewer
);
});
return;
}
if (options.button !== 0) {
return;
}
const { defined } = Cesium;
let type = "new";
let emitPosition;
let finished = false;
const scene = viewer.scene;
if (drawStatus.value === DrawStatus.BeforeDraw) {
const position = getWorldPosition(scene, movement, {});
if (!defined(position)) {
return;
}
positions[0] = position;
positions[1] = position;
polyline.show = true;
drawStatus.value = DrawStatus.Drawing;
polyline.drawStatus = DrawStatus.Drawing;
drawTip.value = drawTipOpts.value.drawingTipEnd;
emitPosition = position;
finished = false;
if (cmpName === "VcMeasurementVertical") {
const ellipsoid = scene.frameState.mapProjection.ellipsoid;
polyline.surfaceNormal = ellipsoid.geodeticSurfaceNormal(position, polyline.surfaceNormal);
}
if (cmpName === "VcMeasurementHeight") {
makeHeightPositions(polyline, position);
finished = true;
polyline.drawStatus = DrawStatus.AfterDraw;
drawStatus.value = DrawStatus.AfterDraw;
drawTip.value = drawTipOpts.value.drawingTipStart;
if (props.mode === 1) {
drawingFabInstanceVm.toggleAction(selectedDrawingActionInstance);
}
}
if (cmpName === "VcAnalysisViewshed") {
polyline.viewshedOpts = {
...props.viewshedOpts
};
}
} else {
polyline.drawStatus = DrawStatus.AfterDraw;
drawStatus.value = DrawStatus.AfterDraw;
if (editingPoint.value) {
if (platform().hasTouch === true) {
const position = getWorldPosition(scene, movement, {});
if (defined(position)) {
const positions2 = polyline.positions;
positions2.splice(editingPoint.value._index, 1, position);
editingPoint.value.pixelSize = ((_a = props.pointOpts) == null ? void 0 : _a.pixelSize) * 1;
}
}
editingPoint.value = void 0;
drawingFabInstanceVm.editingActionName = void 0;
canShowDrawTip.value = false;
drawTipPosition.value = [0, 0, 0];
type = editorType.value;
if (selectedDrawingActionInstance) {
drawTip.value = drawTipOpts.value.drawingTipStart;
canShowDrawTip.value = true;
}
} else {
if (cmpName !== "VcMeasurementVertical") {
if (platform().hasTouch === true) {
const position = getWorldPosition(scene, movement, {});
if (defined(position)) {
const positions2 = polyline.positions;
positions2[1] = position;
}
}
}
if (props.mode === 1) {
drawingFabInstanceVm.toggleAction(selectedDrawingActionInstance);
}
}
finished = true;
emitPosition = polyline.positions[1];
}
nextTick(() => {
emit(
"drawEvt",
Object.assign(
{
index,
pointIndex,
renderDatas,
name: drawingType,
finished,
position: emitPosition,
windowPoistion: movement,
type
},
computedRenderDatas.value[index]
),
viewer
);
});
};
const handleMouseMove = (movement) => {
const { viewer, getWorldPosition } = $services;
const scene = viewer.scene;
const position = getWorldPosition(scene, movement, {});
const { defined, Cartographic } = Cesium;
if (!defined(position)) {
return;
}
drawTipPosition.value = position;
if (drawStatus.value !== DrawStatus.Drawing) {
return;
}
if (cmpName === "VcMeasurementVertical" && scene.mode === Cesium.SceneMode.SCENE2D) {
return;
}
const index = editingPoint.value ? editingPoint.value._vcPolylineIndx : renderDatas.value.length - 1;
const polyline = renderDatas.value[index];
const pointIndex = editingPoint.value ? editingPoint.value._index : polyline.positions.length - 1;
if (cmpName === "VcMeasurementVertical") {
const heightPostion = getHeightPosition(polyline, movement);
if (!isUndefined(heightPostion)) {
const positions = polyline.positions.slice();
positions[editingPoint.value ? editingPoint.value._index : 1] = heightPostion;
polyline.positions = positions;
}
} else if (cmpName === "VcMeasurementHeight") {
makeHeightPositions(polyline, position);
} else if (cmpName === "VcDrawingRectangle" || cmpName === "VcDrawingRegular" || cmpName === "VcMeasurementRegular" || cmpName === "VcMeasurementRectangle") {
const positions = polyline.positions;
const startPosition = positions[0];
const startCartographic = Cartographic.fromCartesian(startPosition, viewer.scene.globe.ellipsoid);
const endCartographic = Cartographic.fromCartesian(position, viewer.scene.globe.ellipsoid);
!props.clampToGround && (endCartographic.height = startCartographic.height);
positions[editingPoint.value ? editingPoint.value._index : 1] = Cartographic.toCartesian(endCartographic, viewer.scene.globe.ellipsoid);
} else if (cmpName === "VcAnalysisSightline") {
const positions = polyline.positions;
if (editingPoint.value) {
const index2 = editingPoint.value._index > 0 ? 1 : 0;
positions[index2] = position;
} else {
positions[1] = position;
}
} else {
const positions = polyline.positions.slice();
positions[editingPoint.value ? editingPoint.value._index : 1] = position;
polyline.positions = positions;
}
nextTick(() => {
emit(
"drawEvt",
Object.assign(
{
index,
pointIndex,
renderDatas,
name: drawingType,
finished: false,
position: polyline.positions[1],
windowPoistion: movement,
type: editingPoint.value ? editorType : "new"
},
computedRenderDatas.value[index]
),
viewer
);
});
};
const onEditorClick = (e) => {
var _a, _b, _c;
editorPosition.value = [0, 0, 0];
showEditor.value = false;
if (!props.editable) {
return;
}
editorType.value = e;
const { viewer, drawingFabInstance } = $services;
if (e === "move") {
drawTip.value = drawTipOpts.value.drawingTipEditing;
drawStatus.value = DrawStatus.Drawing;
editingPoint.value = mouseoverPoint.value;
restorePosition = renderDatas.value[editingPoint.value._vcPolylineIndx].positions[editingPoint.value._index];
canShowDrawTip.value = true;
const drawingFabInstanceVm = drawingFabInstance == null ? void 0 : drawingFabInstance.proxy;
drawingFabInstanceVm.editingActionName = drawingType;
} else if (e === "remove") {
const index = mouseoverPoint.value._vcPolylineIndx;
const polyline = renderDatas.value[index];
polyline.positions.splice(mouseoverPoint.value._index, 1);
} else if (e === "removeAll") {
const index = mouseoverPoint.value._vcPolylineIndx;
renderDatas.value.splice(index, 1);
} else {
const index = mouseoverPoint.value._vcPolylineIndx;
const polyline = renderDatas.value[index];
(_c = (_b = (_a = props.editorOpts) == null ? void 0 : _a[e]) == null ? void 0 : _b.callback) == null ? void 0 : _c.call(_b, index, polyline);
}
emit(
"editorEvt",
{
type: e,
renderDatas,
name: drawingType,
index: mouseoverPoint.value._vcPolylineIndx,
pointIndex: mouseoverPoint.value._index,
point: mouseoverPoint.value
},
viewer
);
};
const clear = () => {
renderDatas.value = [];
stop();
};
const publicMethods = { computedRenderDatas, renderDatas, startNew, stop, clear, handleMouseClick, handleMouseMove };
Object.assign(instance.proxy, publicMethods);
return () => {
var _a, _b, _c;
const { createGuid } = Cesium;
const children = [];
computedRenderDatas.value.forEach((polyline, index) => {
var _a2;
const isRegular = cmpName === "VcDrawingRectangle" || cmpName === "VcDrawingRegular" || cmpName === "VcMeasurementRegular" || cmpName === "VcMeasurementRectangle";
const positions = isRegular ? (_a2 = polyline.polygonPositions) == null ? void 0 : _a2.slice() : polyline.positions;
isRegular && (positions == null ? void 0 : positions.push(positions[0]));
const polylineOpts = Object.assign({}, props.polylineOpts, polyline.polylineOpts);
props.clampToGround && delete polylineOpts.arcType;
const primitiveOpts = Object.assign({}, props.primitiveOpts, polyline.primitiveOpts);
if ((positions == null ? void 0 : positions.length) && (positions == null ? void 0 : positions.length) > 1) {
children.push(
h(
props.clampToGround ? VcPrimitiveGroundPolyline : VcPrimitive,
{
...primitiveOpts,
show: polyline.show && primitiveOpts.show || props.editable || polyline.drawStatus === DrawStatus.Drawing,
onReady: (readyObject) => {
var _a3;
(_a3 = primitiveOpts == null ? void 0 : primitiveOpts.onReady) == null ? void 0 : _a3.call(primitiveOpts, readyObject);
readyObject.cesiumObject._vcPolylineIndex = index;
}
},
() => h(
VcGeometryInstance,
{
id: createGuid()
},
() => h(props.clampToGround ? VcGeometryGroundPolyline : VcGeometryPolyline, {
positions,
...polylineOpts
})
)
)
);
if (cmpName === "VcAnalysisViewshed") {
children.push(h(VcViewshed, { ...polyline.viewshedOpts }));
}
}
if (polyline.polygonPositions && polyline.polygonPositions.length > 2) {
const polygonOpts = Object.assign({}, props == null ? void 0 : props.polygonOpts, polyline == null ? void 0 : polyline.polygonOpts);
polygonOpts.clampToGround = props.clampToGround;
children.push(
h(VcPolygon, {
positions,
show: polyline.show && (polygonOpts == null ? void 0 : polygonOpts.show),
...polygonOpts,
onReady: (readyObject) => {
var _a3;
onVcPrimitiveReady(readyObject);
(_a3 = polygonOpts == null ? void 0 : polygonOpts.onReady) == null ? void 0 : _a3.call(polygonOpts, readyObject);
readyObject.cesiumObject._vcPolylineIndex = index;
}
})
);
}
if (polyline.xyPolylinePositions && polyline.xyPolylinePositions.length > 1) {
children.push(
h(
VcPrimitive,
{
show: polyline.show && primitiveOpts || props.editable || polyline.drawStatus === DrawStatus.Drawing,
...primitiveOpts,
onReady: (readyObject) => {
var _a3;
(_a3 = primitiveOpts == null ? void 0 : primitiveOpts.onReady) == null ? void 0 : _a3.call(primitiveOpts, readyObject);
readyObject.cesiumObject._vcPolylineIndex = index;
}
},
() => h(
VcGeometryInstance,
{
id: createGuid()
},
() => h(VcGeometryPolyline, {
positions: polyline.xyPolylinePositions,
...polylineOpts
})
)
)
);
}
if (polyline.xyBoxPositions && polyline.xyBoxPositions.length > 1) {
children.push(
h(
VcPrimitive,
{
show: polyline.show && primitiveOpts || props.editable || polyline.drawStatus === DrawStatus.Drawing,
...primitiveOpts
},
() => h(
VcGeometryInstance,
{
id: createGuid()
},
() => h(VcGeometryPolyline, {
positions: polyline.xyBoxPositions,
...polylineOpts
})
)
)
);
}
const polylinePointOpts = Object.assign({}, props.pointOpts, polyline.pointOpts);
children.push(
h(VcCollectionPoint, {
enableMouseEvent: props.enableMouseEvent,
show: polyline.show,
points: polyline.points.map((point, subIndex) => {
const position = point.position;
const pointOpts = Object.assign({}, polylinePointOpts, point);
return {
position,
id: createGuid(),
_vcPolylineIndx: index,
// for editor
...pointOpts,
show: ((pointOpts == null ? void 0 : pointOpts.show) || props.editable || polyline.drawStatus === DrawStatus.Drawing) && (cmpName === "VcAnalysisSightline" && polyline.positions.length === 3 ? subIndex !== 1 : true)
};
}),
onMouseover: onMouseoverPoints,
onMouseout: onMouseoutPoints,
onReady: onVcCollectionPointReady
})
);
children.push(
h(VcCollectionLabel, {
enableMouseEvent: props.enableMouseEvent,
show: polyline.show,
labels: polyline.labels,
onReady: onVcCollectionLabelReady
})
);
});
if (((_a = props.drawtip) == null ? void 0 : _a.show) && canShowDrawTip.value) {
const { viewer } = $services;
children.push(
h(
VcOverlayHtml,
{
position: drawTipPosition.value,
pixelOffset: (_b = props.drawtip) == null ? void 0 : _b.pixelOffset,
teleport: {
to: viewer.container
}
},
() => h(
"div",
{
class: "vc-drawtip vc-tooltip--style"
},
drawTip.value
)
)
);
}
if (showEditor.value) {
const buttons = [];
if (mouseoverPoint.value) {
const editorOpts = props.editorOpts;
for (const key in editorOpts) {
if (!Array.isArray(editorOpts[key]) && typeof editorOpts[key] !== "number") {
const opts = {
...editorOpts[key]
};
delete opts.color;
buttons.push(
h(
VcBtn,
{
style: { color: editorOpts[key].color, background: editorOpts[key].background },
...opts,
onclick: onEditorClick.bind(void 0, key)
},
() => h(
VcTooltip,
{
...editorOpts[key].tooltip
},
() => {
var _a2;
return h("strong", null, ((_a2 = editorOpts[key].tooltip) == null ? void 0 : _a2.tip) || t(`vc.measurement.editor.${key}`));
}
)
)
);
}
}
}
const { viewer } = $services;
children.push(
h(
VcOverlayHtml,
{
position: editorPosition.value,
pixelOffset: (_c = props.editorOpts) == null ? void 0 : _c.pixelOffset,
teleport: {
to: viewer.container
},
onMouseenter: onMouseenterEditor,
onMouseleave: onMouseleaveEditor
},
() => h(
"div",
{
class: "vc-editor"
},
buttons
)
)
);
}
return h(
VcCollectionPrimitive,
{
ref: primitiveCollectionRef,
show: props.show,
onReady: onPrimitiveCollectionReady
},
() => children
);
};
}
var VcMeasurementDistance = exports('VcMeasurementDistance', defineComponent({
name: "VcMeasurementDistance",
props: {
...useDrawingActionProps,
showComponentLines: {
type: Boolean,
default: false
},
measureUnits: Object,
polylineOpts: Object,
primitiveOpts: Object,
labelOpts: Object,
xLabelOpts: Object,
xAngleLabelOpts: Object,
yLabelOpts: Object,
yAngleLabelOpts: Object,
locale: String,
decimals: Object,
autoUpdateLabelPosition: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingSegment(props, ctx, "VcMeasurementDistance");
}
}));
function useDrawingPolyline(props, ctx, cmpName) {
const instance = getCurrentInstance();
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { t } = useLocale();
const $services = commonState.$services;
const { emit } = ctx;
const {
drawingType,
drawTip,
drawTipOpts,
drawStatus,
canShowDrawTip,
drawTipPosition,
showEditor,
editorPosition,
mouseoverPoint,
editingPoint,
primitiveCollectionRef,
editorType,
onMouseoverPoints,
onMouseoutPoints,
onMouseenterEditor,
onMouseleaveEditor,
onPrimitiveCollectionReady,
onVcCollectionPointReady,
onVcCollectionLabelReady,
onVcPrimitiveReady
} = useDrawingAction(props, ctx, instance, cmpName, $services);
let lastClickPosition;
let restorePosition;
const mouseDelta = 10;
const renderDatas = ref([]);
if (props.preRenderDatas && props.preRenderDatas.length) {
props.preRenderDatas.forEach((preRenderData) => {
const polylineDrawing = {
show: true,
positions: makeCartesian3Array(preRenderData),
tempPositions: [],
drawStatus: DrawStatus.AfterDraw,
loop: props.loop,
distance: 0,
area: 0,
distances: [],
labels: [],
angles: [],
polylineOpts: {},
pointOpts: {},
labelOpts: {},
labelsOpts: {},
primitiveOpts: {},
polygonOpts: {}
};
renderDatas.value.push(polylineDrawing);
});
}
const computedRenderDatas = computed(() => {
const { Cartesian3, createGuid, defined, Math: CesiumMath } = Cesium;
const polylines = [];
const { viewer } = $services;
renderDatas.value.forEach((polyline, index) => {
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
const labels = reactive([]);
const distances = [];
const angles = [];
let distance = 0;
const dashedLines = [];
polyline.points = polyline.positions.map((v) => {
return {
position: v
};
});
const positions = polyline.positions.slice();
if (cmpName === "VcAnalysisSightline") {
const observationPoint = positions.shift();
const destinationPoints = positions;
observationPoint && destinationPoints.forEach((destinationPoint) => {
const positionsNew = [];
positionsNew.push(observationPoint);
const objectsToExclude = [];
const primitiveCollection = primitiveCollectionRef.value.cesiumObject._primitives;
primitiveCollection.forEach((primitive) => {
if (primitive instanceof Cesium.PointPrimitiveCollection) {
objectsToExclude.push(...primitive._pointPrimitives);
}
if (primitive instanceof Cesium.Primitive) {
objectsToExclude.push(primitive);
}
});
const intersection = getFirstIntersection(observationPoint, destinationPoint, $services.viewer, objectsToExclude);
if (defined(intersection)) {
positionsNew.push(intersection);
}
positionsNew.push(destinationPoint);
let distance2 = 0;
const distances2 = [];
for (let i = 0; i < positionsNew.length - 1; i++) {
const s = Cartesian3.distance(positionsNew[i], positionsNew[i + 1]);
distances2.push(s);
distance2 = distance2 + s;
}
polylines.push({
...polyline,
positions: positionsNew,
distance: distance2,
distances: distances2
});
});
} else {
props.loop && positions.length > 2 && positions.push(positions[0]);
for (let i = 0; i < positions.length - 1; i++) {
let s = 0;
if (((_a = props.polylineOpts) == null ? void 0 : _a.arcType) === 0) {
s = getGeodesicDistance(positions[i], positions[i + 1], $services.viewer.scene.globe.ellipsoid);
} else {
s = Cartesian3.distance(positions[i], positions[i + 1]);
}
distances.push(s);
distance = distance + s;
const polylineLabelsOpts = Object.assign({}, props.labelsOpts, polyline.labelsOpts);
if (s > 0 && positions.length > 2 && props.showDistanceLabel) {
labels.push({
text: MeasureUnits.distanceToString(s, (_b = props.measureUnits) == null ? void 0 : _b.distanceUnits, props.locale, (_c = props.decimals) == null ? void 0 : _c.distance),
position: Cartesian3.midpoint(positions[i], positions[i + 1], {}),
id: createGuid(),
...polylineLabelsOpts
});
}
if (positions.length > 2 && props.showAngleLabel) {
if (i > 0 || props.loop) {
const point0 = positions[i === 0 ? positions.length - 2 : i - 1];
const point1 = positions[i];
const point2 = positions[i + 1];
const diffrence1 = Cartesian3.subtract(point0, point1, {});
const diffrence2 = Cartesian3.subtract(point2, point1, {});
let angle = 0;
if (!(Cartesian3.ZERO.equals(diffrence1) || Cartesian3.ZERO.equals(diffrence2))) {
angle = Cartesian3.angleBetween(diffrence1, diffrence2);
}
angles.push(angle);
labels.push({
text: MeasureUnits.angleToString(angle, (_d = props.measureUnits) == null ? void 0 : _d.angleUnits, props.locale, (_e = props.decimals) == null ? void 0 : _e.angle),
position: point1,
id: createGuid(),
...polylineLabelsOpts
});
}
}
if (props.showDashedLine) {
dashedLines.push({
positions: [positions[i], getEndPostion(positions[i])]
});
if (i === positions.length - 2) {
dashedLines.push({
positions: [positions[i + 1], getEndPostion(positions[i + 1])]
});
}
}
}
const area = calculateAreaByPostions(positions);
const polylineLabelOpts = Object.assign({}, props.labelOpts, polyline.labelOpts);
if (props.showLabel && positions.length) {
if (cmpName.includes("Area")) {
labels.push({
text: MeasureUnits.areaToString(area, (_f = props.measureUnits) == null ? void 0 : _f.areaUnits, props.locale, (_g = props.decimals) == null ? void 0 : _g.area),
position: positions[positions.length - 1],
id: createGuid(),
...polylineLabelOpts
});
} else {
labels.push({
text: MeasureUnits.distanceToString(distance, (_h = props.measureUnits) == null ? void 0 : _h.distanceUnits, props.locale, (_i = props.decimals) == null ? void 0 : _i.distance),
position: positions[positions.length - 1],
id: createGuid(),
...polylineLabelOpts
});
}
}
polyline.positionsDegreesArray = polyline.positions.map((v) => {
const cart = Cesium.Cartographic.fromCartesian(v, viewer.scene.globe.ellipsoid);
return [CesiumMath.toDegrees(cart.longitude), CesiumMath.toDegrees(cart.latitude), cart.height];
});
polylines.push({
...polyline,
labels,
distance,
distances,
area,
angles,
dashedLines
});
}
});
return polylines;
});
instance.mount = async () => {
const { viewer } = $services;
props.autoUpdateLabelPosition && viewer.scene.preRender.addEventListener(updateLabelPosition);
return true;
};
instance.unmount = async () => {
const { viewer } = $services;
props.autoUpdateLabelPosition && viewer.scene.preRender.removeEventListener(updateLabelPosition);
return true;
};
const getEndPostion = (position) => {
const { defined, defaultValue } = Cesium;
const { viewer } = $services;
const scene = viewer.scene;
const globe = scene.globe;
const ellipsoid = scene.frameState.mapProjection.ellipsoid;
const positionCartographic = ellipsoid.cartesianToCartographic(position);
positionCartographic.height = defined(globe) ? defaultValue(globe.getHeight(positionCartographic), 0) : 0;
return ellipsoid.cartographicToCartesian(positionCartographic);
};
const updateLabelPosition = () => {
computedRenderDatas.value.forEach((polyline, index) => {
var _a;
const positions = polyline.positions;
if (!(positions.length < 2)) {
const { defined, SceneTransforms, Cartesian2, HorizontalOrigin } = Cesium;
const { viewer } = $services;
const scene = viewer.scene;
let startPosition = positions[0];
const positionWindow = SceneTransforms.wgs84ToWindowCoordinates(scene, startPosition, {});
let startPositionWindow = defined(positionWindow) ? Cartesian2.clone(positionWindow, {}) : Cartesian2.fromElements(Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, {});
let startY = startPositionWindow.y;
const primitiveCollection = (_a = primitiveCollectionRef.value) == null ? void 0 : _a.cesiumObject;
const labelCollection = primitiveCollection._primitives.filter(
(v) => v instanceof Cesium.LabelCollection
);
const labels = labelCollection[index]._labels;
const labelTotalLength = labels[labels.length - 1];
for (let i = 1; i < positions.length; i++) {
const positionWindow2 = SceneTransforms.wgs84ToWindowCoordinates(scene, positions[i], {});
if (defined(positionWindow2)) {
const l = (startPositionWindow.y - positionWindow2.y) / (positionWindow2.x - startPositionWindow.x);
if (labels[i - 1] !== labelTotalLength) {
labels[i - 1].horizontalOrigin = 0 < l ? HorizontalOrigin.LEFT : HorizontalOrigin.RIGHT;
}
if (positionWindow2.y < startY) {
startY = positionWindow2.y;
startPosition = positions[i];
}
startPositionWindow = Cartesian2.clone(positionWindow2, startPositionWindow);
}
polyline.drawStatus === DrawStatus.AfterDraw && (labelTotalLength.position = startPosition);
}
}
});
};
const startNew = () => {
const polyline = {
show: false,
positions: [],
tempPositions: [],
drawStatus: DrawStatus.BeforeDraw,
loop: props.loop,
distance: 0,
area: 0,
distances: [],
labels: [],
angles: [],
polylineOpts: {},
pointOpts: {},
labelOpts: {},
labelsOpts: {},
primitiveOpts: {},
polygonOpts: {}
};
if (cmpName === "VcMeasurementHorizontal") {
const { Cartesian3, Plane } = Cesium;
Object.assign(polyline, {
dashedLines: [],
heightPlane: new Plane(Cartesian3.UNIT_X, 0),
heightPlaneCV: new Plane(Cartesian3.UNIT_X, 0),
height: 0,
firstMove: false,
tempNextPos: new Cartesian3()
});
}
drawStatus.value = DrawStatus.BeforeDraw;
renderDatas.value.push(polyline);
canShowDrawTip.value = true;
drawTip.value = drawTipOpts.value.drawingTipStart;
};
const stop = (removeLatest = true) => {
if (removeLatest && drawStatus.value === DrawStatus.Drawing) {
renderDatas.value.pop();
}
const index = editingPoint.value ? editingPoint.value._vcPolylineIndex : renderDatas.value.length - 1;
const polyline = renderDatas.value[index];
if (polyline) {
polyline.positions = polyline.tempPositions;
polyline.drawStatus = DrawStatus.AfterDraw;
}
drawStatus.value = DrawStatus.AfterDraw;
canShowDrawTip.value = false;
drawTipPosition.value = [0, 0, 0];
};
const handleMouseClick = (movement, options) => {
var _a;
const { viewer, drawingFabInstance, getWorldPosition, selectedDrawingActionInstance } = $services;
const drawingFabInstanceVm = drawingFabInstance == null ? void 0 : drawingFabInstance.proxy;
if (options.button === 2 && options.ctrl) {
const drawingsOption = drawingFabInstanceVm.getDrawingActionInstance(drawingType);
drawingFabInstanceVm.toggleAction(drawingsOption);
nextTick(() => {
emit(
"drawEvt",
{
name: drawingType,
finished: true,
windowPoistion: movement,
type: "cancel"
},
viewer
);
});
return;
}
if (drawStatus.value === DrawStatus.AfterDraw) {
startNew();
}
const { defined, Cartesian2, Plane, Cartesian3 } = Cesium;
const index = editingPoint.value ? editingPoint.value._vcPolylineIndex : renderDatas.value.length - 1;
const polyline = renderDatas.value[index];
const tempPositions = polyline.tempPositions;
const pointIndex = editingPoint.value ? editingPoint.value._index : polyline.positions.length - 1;
if (options.button === 2 && editingPoint.value) {
if (editorType.value === "insert") {
polyline.positions.splice(editingPoint.value._index, 1);
} else {
polyline.positions[editingPoint.value._index] = restorePosition;
}
drawStatus.value = DrawStatus.AfterDraw;
polyline.drawStatus = DrawStatus.AfterDraw;
editingPoint.value = void 0;
drawTip.value = drawTipOpts.value.drawingTipStart;
drawingFabInstanceVm.editingActionName = void 0;
canShowDrawTip.value = defined(selectedDrawingActionInstance);
nextTick(() => {
emit(
"drawEvt",
Object.assign(
{
index,
pointIndex,
name: drawingType,
renderDatas,
finished: true,
windowPoistion: movement,
type: "cancel"
},
computedRenderDatas.value[index]
),
viewer
);
});
return;
}
lastClickPosition = lastClickPosition || new Cesium.Cartesian2(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
if (Cartesian2.magnitude(Cartesian2.subtract(lastClickPosition, movement, {})) < mouseDelta) {
return;
}
if (options.button === 2 && drawStatus.value === DrawStatus.Drawing) {
if (tempPositions.length > 1) {
tempPositions.pop();
handleMouseMove(movement);
}
}
if (options.button !== 0) {
return;
}
const scene = viewer.scene;
const position = getWorldPosition(scene, movement, {});
if (!defined(position)) {
return;
}
let finished = false;
let type = "new";
if (cmpName === "VcMeasurementHorizontal") {
if (editingPoint.value) {
drawStatus.value = DrawStatus.AfterDraw;
editingPoint.value = void 0;
finished = true;
type = editorType.value;
drawTip.value = drawTipOpts.value.drawingTipStart;
} else if (tempPositions.length === 0) {
const ellipsoid = scene.frameState.mapProjection.ellipsoid;
tempPositions.push(position);
polyline.positions = tempPositions;
polyline.heightPlane = Plane.fromPointNormal(position, ellipsoid.geodeticSurfaceNormal(position, {}), polyline.heightPlane);
const positionCartographic = ellipsoid.cartesianToCartographic(position, {});
const positionProject = scene.mapProjection.project(positionCartographic, {});
const positionCV = Cartesian3.fromElements(positionProject.z, positionProject.x, positionProject.y, positionProject);
polyline.heightPlaneCV = Plane.fromPointNormal(positionCV, Cartesian3.UNIT_X, polyline.heightPlaneCV);
polyline.height = positionCartographic.height;
polyline.firstMove = true;
polyline.drawStatus = DrawStatus.Drawing;
polyline.show = true;
drawStatus.value = DrawStatus.Drawing;
} else {
tempPositions.push(polyline.tempNextPos);
polyline.positions = tempPositions;
polyline.firstMove = true;
}
drawTip.value = drawTipOpts.value.drawingTipEnd;
} else {
if (editingPoint.value) {
if (platform().hasTouch === true) {
const position2 = getWorldPosition(scene, movement, {});
if (defined(position2)) {
const positions = polyline.positions;
positions.splice(editingPoint.value._index, 1, position2);
editingPoint.value.pixelSize = ((_a = props.pointOpts) == null ? void 0 : _a.pixelSize) * 1;
}
}
drawStatus.value = DrawStatus.AfterDraw;
editingPoint.value = void 0;
finished = true;
type = editorType.value;
drawTip.value = drawTipOpts.value.drawingTipStart;
} else {
tempPositions.push(position);
polyline.positions = tempPositions;
polyline.show = true;
polyline.drawStatus = DrawStatus.Drawing;
drawStatus.value = DrawStatus.Drawing;
canShowDrawTip.value = true;
drawTip.value = drawTipOpts.value.drawingTipEnd;
}
if (type !== "new") {
drawingFabInstanceVm.editingActionName = void 0;
canShowDrawTip.value = defined(selectedDrawingActionInstance);
}
}
Cartesian2.clone(movement, lastClickPosition);
nextTick(() => {
emit(
"drawEvt",
Object.assign(
{
index,
pointIndex,
name: drawingType,
renderDatas,
finished,
position: cmpName === "VcMeasurementHorizontal" ? polyline.positions[polyline.positions.length - 1] : position,
windowPoistion: movement,
type
},
computedRenderDatas.value[index]
),
viewer
);
});
};
const handleMouseMove = (movement, options) => {
const { viewer, getWorldPosition } = $services;
const scene = viewer.scene;
const position = getWorldPosition(scene, movement, {});
const { defined } = Cesium;
if (!defined(position)) {
return;
}
drawTipPosition.value = position;
if (drawStatus.value !== DrawStatus.Drawing) {
return;
}
const index = editingPoint.value ? editingPoint.value._vcPolylineIndex : renderDatas.value.length - 1;
const polyline = renderDatas.value[index];
const pointIndex = editingPoint.value ? editingPoint.value._index : polyline.positions.length - 1;
let type = "new";
if (cmpName === "VcMeasurementHorizontal") {
const { SceneMode, IntersectionTests, Cartesian3 } = Cesium;
const ellipsoid = scene.frameState.mapProjection.ellipsoid;
const positions = polyline.positions;
const cameraRay = scene.camera.getPickRay(movement);
let intersectionPosition, unprojectPosition;
if (scene.mode === SceneMode.SCENE3D && polyline.heightPlane) {
intersectionPosition = IntersectionTests.rayPlane(cameraRay, polyline.heightPlane);
} else if (scene.mode === SceneMode.COLUMBUS_VIEW && polyline.heightPlaneCV) {
intersectionPosition = IntersectionTests.rayPlane(cameraRay, polyline.heightPlaneCV);
intersectionPosition = Cartesian3.fromElements(intersectionPosition.y, intersectionPosition.z, intersectionPosition.x, intersectionPosition);
unprojectPosition = scene.mapProjection.unproject(intersectionPosition);
intersectionPosition = ellipsoid.cartographicToCartesian(unprojectPosition);
} else {
intersectionPosition = scene.camera.pickEllipsoid(movement, ellipsoid);
if (defined(intersectionPosition)) {
const cartographicPosition = ellipsoid.cartesianToCartographic(intersectionPosition);
cartographicPosition.height = polyline.height || 0;
intersectionPosition = ellipsoid.cartographicToCartesian(cartographicPosition, intersectionPosition);
}
}
if (!defined(intersectionPosition)) {
return;
}
if (!polyline.firstMove && (options == null ? void 0 : options.shift)) {
const lastPosition = positions[positions.length - 2];
const tempNextPos = polyline.tempNextPos;
const d1 = Cartesian3.subtract(tempNextPos, lastPosition, {});
let d2 = Cartesian3.subtract(intersectionPosition, lastPosition, {});
d2 = Cartesian3.projectVector(d2, d1, d2);
intersectionPosition = Cartesian3.add(lastPosition, d2, intersectionPosition);
}
if (editingPoint.value) {
const positions2 = polyline.positions;
positions2.splice(editingPoint.value._index, 1, intersectionPosition);
type = editorType.value;
} else {
const tempPositions = polyline.tempPositions.slice();
tempPositions.push(intersectionPosition);
polyline.positions = tempPositions;
polyline.firstMove = false;
polyline.tempNextPos = Object.assign(intersectionPosition);
drawTip.value = drawTipOpts.value.drawingTipEnd;
}
} else {
if (editingPoint.value) {
const positions = polyline.positions;
positions.splice(editingPoint.value._index, 1, position);
type = editorType.value;
} else {
const tempPositions = polyline.tempPositions.slice();
tempPositions.push(position);
polyline.positions = tempPositions;
}
}
nextTick(() => {
emit(
"drawEvt",
Object.assign(
{
index,
pointIndex,
name: drawingType,
renderDatas,
finished: false,
position: cmpName === "VcMeasurementHorizontal" ? polyline.positions[polyline.positions.length - 1] : position,
windowPoistion: movement,
type
},
computedRenderDatas.value[index]
),
viewer
);
});
};
const handleDoubleClick = (movement) => {
const { drawingFabInstance, selectedDrawingActionInstance, viewer } = $services;
if (drawStatus.value === DrawStatus.Drawing) {
const index = editingPoint.value ? editingPoint.value._vcPolylineIndex : renderDatas.value.length - 1;
const polyline = renderDatas.value[index];
const pointIndex = editingPoint.value ? editingPoint.value._index : polyline.positions.length - 1;
stop(false);
drawTip.value = drawTipOpts.value.drawingTipStart;
nextTick(() => {
emit(
"drawEvt",
Object.assign(
{
index,
pointIndex,
name: drawingType,
renderDatas,
finished: true,
position: polyline.positions[polyline.positions.length - 1],
windowPoistion: movement,
type: "new"
},
computedRenderDatas.value[index]
),
viewer
);
if (props.mode === 1) {
const drawingFabInstanceVm = drawingFabInstance == null ? void 0 : drawingFabInstance.proxy;
drawingFabInstanceVm.toggleAction(selectedDrawingActionInstance);
}
});
}
};
const getPointIndexes = () => {
let polylineIndex = editingPoint.value._vcPolylineIndex;
let pointIndex = editingPoint.value._index;
if (cmpName === "VcAnalysisSightline") {
for (let i = 0; i < renderDatas.value.length; i++) {
const polyline = renderDatas.value[i];
for (let j = 0; j < polyline.positions.length; j++) {
const position = polyline.positions[j];
if (editingPoint.value.position.equals(position)) {
polylineIndex = i;
pointIndex = j;
}
}
}
}
return [polylineIndex, pointIndex];
};
const onEditorClick = (e) => {
var _a, _b, _c;
editorPosition.value = [0, 0, 0];
showEditor.value = false;
if (!props.editable) {
return;
}
const { viewer, drawingFabInstance } = $services;
const drawingFabInstanceVm = drawingFabInstance == null ? void 0 : drawingFabInstance.proxy;
editorType.value = e;
if (e === "move") {
drawTip.value = drawTipOpts.value.drawingTipEditing;
drawStatus.value = DrawStatus.Drawing;
editingPoint.value = mouseoverPoint.value;
canShowDrawTip.value = true;
const indexes = getPointIndexes();
editingPoint.value._vcPolylineIndex = indexes[0];
editingPoint.value._index = indexes[1];
restorePosition = renderDatas.value[indexes[0]].positions[indexes[1]];
drawingFabInstanceVm.editingActionName = drawingType;
} else if (e === "insert") {
const index = mouseoverPoint.value._vcPolylineIndex;
const polyline = renderDatas.value[index];
polyline.positions.splice(mouseoverPoint.value._index, 0, mouseoverPoint.value.position);
editingPoint.value = mouseoverPoint.value;
canShowDrawTip.value = true;
drawStatus.value = DrawStatus.Drawing;
drawTip.value = drawTipOpts.value.drawingTipEditing;
drawingFabInstanceVm.editingActionName = drawingType;
} else if (e === "remove") {
const index = mouseoverPoint.value._vcPolylineIndex;
const polyline = renderDatas.value[index];
polyline.positions.length > 2 && polyline.positions.splice(mouseoverPoint.value._index, 1);
} else if (e === "removeAll") {
const index = mouseoverPoint.value._vcPolylineIndex;
renderDatas.value.splice(index, 1);
} else {
const index = mouseoverPoint.value._vcPolylineIndex;
const polyline = renderDatas.value[index];
(_c = (_b = (_a = props.editorOpts) == null ? void 0 : _a[e]) == null ? void 0 : _b.callback) == null ? void 0 : _c.call(_b, index, polyline);
}
emit(
"editorEvt",
{
type: e,
renderDatas,
name: drawingType,
polylineIndex: mouseoverPoint.value._vcPolylineIndex,
pointIndex: mouseoverPoint.value._index,
point: mouseoverPoint.value
},
viewer
);
};
const clear = () => {
renderDatas.value = [];
stop();
};
const publicMethods = {
computedRenderDatas,
renderDatas,
startNew,
stop,
clear,
handleMouseClick,
handleMouseMove,
handleDoubleClick
};
Object.assign(instance.proxy, publicMethods);
return () => {
var _a, _b;
const { createGuid, Cartesian3 } = Cesium;
const children = [];
const points = [];
computedRenderDatas.value.forEach((polyline, index) => {
var _a2, _b2;
const positions = polyline.positions.slice();
if (positions.length > 1) {
polyline.loop && positions.push(positions[0]);
const polylineOpts = Object.assign({}, props.polylineOpts, polyline.polylineOpts);
props.clampToGround && delete polylineOpts.arcType;
const primitiveOpts = Object.assign({}, props.primitiveOpts, polyline.primitiveOpts);
children.push(
h(
props.clampToGround ? VcPrimitiveGroundPolyline : VcPrimitive,
{
show: polyline.show && primitiveOpts.show || props.editable || polyline.drawStatus === DrawStatus.Drawing,
...primitiveOpts,
onReady: (readyObject) => {
var _a3;
(_a3 = primitiveOpts == null ? void 0 : primitiveOpts.onReady) == null ? void 0 : _a3.call(primitiveOpts, readyObject);
readyObject.cesiumObject._vcPolylineIndex = index;
}
},
() => h(
VcGeometryInstance,
{
id: createGuid()
},
() => h(props.clampToGround ? VcGeometryGroundPolyline : VcGeometryPolyline, {
positions,
...polylineOpts
})
)
)
);
}
const dashLineOpts = Object.assign({}, props.dashLineOpts, polyline.dashLineOpts);
const dashLinePrimitiveOpts = Object.assign({}, props.dashLinePrimitiveOpts, polyline.dashLinePrimitiveOpts);
(_a2 = polyline.dashedLines) == null ? void 0 : _a2.forEach((dashedLine) => {
children.push(
h(
VcPrimitive,
{
show: polyline.show && props.dashLinePrimitiveOpts.show || props.editable || polyline.drawStatus === DrawStatus.Drawing,
...dashLinePrimitiveOpts
},
() => h(
VcGeometryInstance,
{
id: createGuid()
},
() => h(VcGeometryPolyline, {
positions: dashedLine.positions,
...dashLineOpts
})
)
)
);
});
const polylinePointOpts = Object.assign({}, props.pointOpts, polyline.pointOpts);
children.push(
h(VcCollectionPoint, {
enableMouseEvent: props.enableMouseEvent,
show: polyline.show,
points: polyline.points.map((point, subIndex) => {
var _a3;
const position = point.position;
let includes = false;
for (let i = 0; i < points.length; i++) {
Cartesian3.equals(position, points[i]) && (includes = true);
}
const show = (((_a3 = props.pointOpts) == null ? void 0 : _a3.show) || props.editable || polyline.drawStatus === DrawStatus.Drawing) && (cmpName === "VcAnalysisSightline" && polyline.positions.length === 3 ? subIndex !== 1 : true) && !includes;
if (cmpName === "VcAnalysisSightline") {
points.push(position);
}
const pointOpts = Object.assign({}, polylinePointOpts, point);
return {
position,
id: createGuid(),
_vcPolylineIndex: index,
// for editor
show,
...pointOpts
};
}),
onMouseover: onMouseoverPoints,
onMouseout: onMouseoutPoints,
onReady: onVcCollectionPointReady
})
);
children.push(
h(VcCollectionLabel, {
enableMouseEvent: props.enableMouseEvent,
show: polyline.show,
labels: polyline.labels,
onReady: onVcCollectionLabelReady
})
);
if (positions.length > 2 && (cmpName.includes("Polygon") || cmpName.includes("Area"))) {
const polygonOpts = Object.assign({}, props.polygonOpts, polyline.polygonOpts);
children.push(
h(VcPolygon, {
positions,
clampToGround: props.clampToGround,
show: polyline.show && ((_b2 = props.polygonOpts) == null ? void 0 : _b2.show),
...polygonOpts,
onReady: (readyObject) => {
var _a3;
onVcPrimitiveReady(readyObject);
(_a3 = polygonOpts == null ? void 0 : polygonOpts.onReady) == null ? void 0 : _a3.call(polygonOpts, readyObject);
readyObject.cesiumObject._vcPolylineIndex = index;
}
})
);
}
});
if (((_a = props.drawtip) == null ? void 0 : _a.show) && canShowDrawTip.value) {
const { viewer } = $services;
children.push(
h(
VcOverlayHtml,
{
position: drawTipPosition.value,
pixelOffset: props.drawtip.pixelOffset,
teleport: {
to: viewer.container
}
},
() => h(
"div",
{
class: "vc-drawtip vc-tooltip--style"
},
drawTip.value
)
)
);
}
if (showEditor.value) {
const buttons = [];
if (mouseoverPoint.value) {
const editorOpts = props.editorOpts;
for (const key in editorOpts) {
if (!Array.isArray(editorOpts[key]) && typeof editorOpts[key] !== "number") {
const opts = {
...editorOpts[key]
};
delete opts.color;
buttons.push(
h(
VcBtn,
{
style: { color: editorOpts[key].color, background: editorOpts[key].background },
...opts,
onclick: onEditorClick.bind("polyline", key)
},
() => h(
VcTooltip,
{
...editorOpts[key].tooltip
},
() => {
var _a2;
return h("strong", null, ((_a2 = editorOpts[key].tooltip) == null ? void 0 : _a2.tip) || t(`vc.drawing.editor.${key}`));
}
)
)
);
}
}
}
const { viewer } = $services;
children.push(
h(
VcOverlayHtml,
{
position: editorPosition.value,
pixelOffset: (_b = props.editorOpts) == null ? void 0 : _b.pixelOffset,
teleport: {
to: viewer.container
},
onMouseenter: onMouseenterEditor,
onMouseleave: onMouseleaveEditor
},
() => h(
"div",
{
class: "vc-editor"
},
buttons
)
)
);
}
return h(
VcCollectionPrimitive,
{
ref: primitiveCollectionRef,
show: props.show,
onReady: onPrimitiveCollectionReady
},
() => children
);
};
}
var VcMeasurementPolyline = exports('VcMeasurementPolyline', defineComponent({
name: "VcMeasurementPolyline",
props: {
...useDrawingActionProps,
polylineOpts: Object,
primitiveOpts: Object,
loop: Boolean,
clampToGround: Boolean,
measureUnits: Object,
labelOpts: Object,
labelsOpts: Object,
locale: String,
decimals: Object,
showLabel: Boolean,
showAngleLabel: Boolean,
showDistanceLabel: Boolean,
autoUpdateLabelPosition: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingPolyline(props, ctx, "VcMeasurementPolyline");
}
}));
var VcMeasurementHorizontal = exports('VcMeasurementHorizontal', defineComponent({
name: "VcMeasurementHorizontal",
props: {
...useDrawingActionProps,
measureUnits: Object,
polylineOpts: Object,
primitiveOpts: Object,
dashLineOpts: Object,
dashLinePrimitiveOpts: Object,
labelOpts: Object,
labelsOpts: Object,
locale: String,
decimals: Object,
showLabel: Boolean,
showAngleLabel: Boolean,
showDashedLine: Boolean,
showDistanceLabel: Boolean,
autoUpdateLabelPosition: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingPolyline(props, ctx, "VcMeasurementHorizontal");
}
}));
var VcMeasurementVertical = exports('VcMeasurementVertical', defineComponent({
name: "VcMeasurementVertical",
props: {
...useDrawingActionProps,
measureUnits: Object,
polylineOpts: Object,
primitiveOpts: Object,
labelOpts: Object,
locale: String,
decimals: Object,
autoUpdateLabelPosition: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingSegment(props, ctx, "VcMeasurementVertical");
}
}));
var VcMeasurementHeight = exports('VcMeasurementHeight', defineComponent({
name: "VcMeasurementHeight",
props: {
...useDrawingActionProps,
measureUnits: Object,
polylineOpts: Object,
primitiveOpts: Object,
labelOpts: Object,
locale: String,
decimals: Object,
autoUpdateLabelPosition: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingSegment(props, ctx, "VcMeasurementHeight");
}
}));
function useDrawingPoint(props, ctx, cmpName) {
const instance = getCurrentInstance();
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { t } = useLocale();
const $services = commonState.$services;
const { emit } = ctx;
const {
drawingType,
drawTip,
drawTipOpts,
drawStatus,
canShowDrawTip,
drawTipPosition,
showEditor,
editorPosition,
mouseoverPoint,
editingPoint,
primitiveCollectionRef,
editorType,
onMouseoverPoints,
onMouseoutPoints,
onMouseenterEditor,
onMouseleaveEditor,
onPrimitiveCollectionReady,
onVcCollectionPointReady,
onVcCollectionLabelReady
} = useDrawingAction(props, ctx, instance, cmpName, $services);
const renderDatas = ref([]);
let restorePosition;
let unwatchFns = [];
if (cmpName === "VcDrawingPin" && props.billboardOpts.image === "") {
props.billboardOpts.image = Cesium.buildModuleUrl("Assets/Textures/pin.svg");
}
unwatchFns.push(
watch(
() => props.editable,
(val) => {
const { drawingFabInstance, selectedDrawingActionInstance } = $services;
if (val && (selectedDrawingActionInstance == null ? void 0 : selectedDrawingActionInstance.name) === drawingType) {
const drawingFabInstanceVm = drawingFabInstance == null ? void 0 : drawingFabInstance.proxy;
drawingFabInstanceVm.toggleAction(selectedDrawingActionInstance);
}
}
)
);
const convert2Degrees = (position, point, scene) => {
const cart = Cesium.Cartographic.fromCartesian(position, scene.globe.ellipsoid);
const positionDegrees = [Cesium.Math.toDegrees(cart.longitude), Cesium.Math.toDegrees(cart.latitude), cart.height];
point.positionDegrees = positionDegrees;
};
const startNew = () => {
const { Cartesian3 } = Cesium;
const point = {
drawStatus: DrawStatus.Drawing,
show: false,
position: new Cartesian3(),
lng: 0,
lat: 0,
height: 0,
slope: 0,
pointOpts: {},
labelOpts: {},
billboardOpts: {}
};
renderDatas.value.push(point);
drawStatus.value = DrawStatus.Drawing;
canShowDrawTip.value = true;
drawTip.value = drawTipOpts.value.drawingTipStart;
};
const stop = (removeLatest = true) => {
if (removeLatest && drawStatus.value === DrawStatus.Drawing) {
renderDatas.value.pop();
}
const index = editingPoint.value ? editingPoint.value._vcPolylineIndx : renderDatas.value.length - 1;
const point = renderDatas.value[index];
if (point) {
point.drawStatus = DrawStatus.AfterDraw;
}
drawStatus.value = DrawStatus.AfterDraw;
canShowDrawTip.value = false;
drawTipPosition.value = [0, 0, 0];
};
const handleMouseClick = (movement, options) => {
const { viewer, drawingFabInstance, getWorldPosition, selectedDrawingActionInstance } = $services;
const drawingFabInstanceVm = drawingFabInstance == null ? void 0 : drawingFabInstance.proxy;
if (options.button === 2 && options.ctrl) {
const drawingsOption = drawingFabInstanceVm == null ? void 0 : drawingFabInstanceVm.getDrawingActionInstance(drawingType);
drawingFabInstanceVm == null ? void 0 : drawingFabInstanceVm.toggleAction(drawingsOption);
nextTick(() => {
emit(
"drawEvt",
{
name: drawingType,
finished: true,
windowPoistion: movement,
type: "cancel"
},
viewer
);
});
return;
}
const index = editingPoint.value ? editingPoint.value._vcPolylineIndx : renderDatas.value.length - 1;
const point = renderDatas.value[index];
if (options.button === 2 && editingPoint.value) {
drawingFabInstanceVm.editingActionName = void 0;
renderDatas.value[index] = restorePosition;
drawStatus.value = DrawStatus.AfterDraw;
renderDatas.value[index].drawStatus = DrawStatus.AfterDraw;
editingPoint.value = void 0;
drawTip.value = drawTipOpts.value.drawingTipStart;
nextTick(() => {
emit(
"drawEvt",
{
name: drawingType,
index,
renderDatas,
finished: true,
windowPoistion: movement,
type: "cancel"
},
viewer
);
});
return;
}
if (options.button !== 0) {
return;
}
const { defined } = Cesium;
let type = "new";
if (drawStatus.value === DrawStatus.BeforeDraw) {
const scene = viewer.scene;
const position = getWorldPosition(scene, movement, {});
if (!defined(position)) {
return;
}
point.position = position;
point.show = true;
point.drawStatus = DrawStatus.AfterDraw;
drawStatus.value = DrawStatus.AfterDraw;
drawTip.value = drawTipOpts.value.drawingTipStart;
nextTick(() => {
emit(
"drawEvt",
{
index,
renderDatas,
name: drawingType,
finished: true,
position,
windowPoistion: movement,
type
},
viewer
);
});
} else {
drawStatus.value = DrawStatus.AfterDraw;
point.drawStatus = DrawStatus.AfterDraw;
const scene = viewer.scene;
if (platform().hasTouch === true) {
const position = getWorldPosition(scene, movement, {});
convert2Degrees(position, point, scene);
if (defined(position)) {
point.position = position;
point.show = true;
}
}
if (editingPoint.value) {
editingPoint.value = void 0;
drawingFabInstanceVm.editingActionName = void 0;
canShowDrawTip.value = false;
type = editorType.value;
} else {
if (props.mode === 1) {
nextTick(() => {
drawingFabInstanceVm.toggleAction(selectedDrawingActionInstance);
});
}
}
if (selectedDrawingActionInstance) {
drawTip.value = drawTipOpts.value.drawingTipStart;
canShowDrawTip.value = true;
}
nextTick(() => {
emit(
"drawEvt",
{
index,
renderDatas,
name: drawingType,
finished: true,
position: renderDatas.value[index].position,
positionDegrees: renderDatas.value[index].positionDegrees,
windowPoistion: movement,
type
},
viewer
);
});
}
};
const handleMouseMove = (movement) => {
const { viewer, getWorldPosition } = $services;
const scene = viewer.scene;
const { defined, SceneMode } = Cesium;
if (scene.mode !== SceneMode.MORPHING) {
const position = getWorldPosition(scene, movement, {});
if (!defined(position)) {
return;
}
drawTipPosition.value = position;
if (drawStatus.value === DrawStatus.AfterDraw) {
startNew();
}
if (drawStatus.value !== DrawStatus.Drawing) {
return;
}
const index = editingPoint.value ? editingPoint.value._vcPolylineIndx : renderDatas.value.length - 1;
const point = renderDatas.value[index];
point.position = position;
convert2Degrees(position, point, scene);
getMeasurementResult(point, movement);
const type = editingPoint.value ? editorType.value : "new";
nextTick(() => {
emit(
"drawEvt",
{
index,
renderDatas,
name: drawingType,
finished: false,
position,
positionDegrees: point.positionDegrees,
windowPoistion: movement,
type
},
viewer
);
});
}
};
const getMeasurementResult = (point, movement) => {
const { viewer } = $services;
const scene = viewer.scene;
const { defined, defaultValue, Math: CesiumMath, SceneMode } = Cesium;
const ellipsoid = scene.frameState.mapProjection.ellipsoid;
const positionCartographic = ellipsoid.cartesianToCartographic(point.position, {});
const globe = scene.globe;
let height = defined(globe) ? defaultValue(globe.getHeight(positionCartographic), 0) : 0;
height = props.heightReference === 0 ? positionCartographic.height : positionCartographic.height - height;
CesiumMath.equalsEpsilon(height, 0, CesiumMath.EPSILON3) && (height = 0);
let slope = 0;
if (scene.mode !== SceneMode.SCENE2D) {
if (!movement) {
movement = scene.cartesianToCanvasCoordinates(point.position, {});
}
slope = getSlope(scene, movement);
}
point.show = true;
point.lng = positionCartographic.longitude;
point.lat = positionCartographic.latitude;
point.height = height;
point.slope = slope;
};
const getSlope = (scene, movement) => {
const { getWorldPosition } = $services;
const { defined, Cartesian2, Cartesian3, Math: CesiumMath } = Cesium;
const position = getWorldPosition(scene, movement, {});
if (defined(position)) {
const cameraPosition = scene.camera.position;
const distance = Cartesian3.distance(position, cameraPosition);
const scratchCartesian3s = [new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3()];
const normalScratch = new Cartesian3();
const surfaceNormalScratch = new Cartesian3();
if (!(1e4 < distance)) {
const p0 = scratchCartesian3s[0];
const p1 = scratchCartesian3s[1];
const p2 = scratchCartesian3s[2];
const p3 = scratchCartesian3s[3];
let surfaceNormal = scene.frameState.mapProjection.ellipsoid.geodeticSurfaceNormal(position, normalScratch);
surfaceNormal = Cartesian3.negate(surfaceNormal, surfaceNormal);
const u = Cartesian2.clone(movement, scratchCartesian3s[0]);
u.x -= 2;
u.y -= 2;
const d = Cartesian2.clone(movement, scratchCartesian3s[1]);
d.x -= 2;
d.y += 2;
const h2 = Cartesian2.clone(movement, scratchCartesian3s[2]);
h2.x += 2;
h2.y += 2;
const p = Cartesian2.clone(movement, scratchCartesian3s[3]);
p.x += 2;
p.y -= 2;
const T = getWorldPosition(scene, u, p0);
const x = getWorldPosition(scene, d, p1);
const b = getWorldPosition(scene, h2, p2);
const E = getWorldPosition(scene, p, p3);
let m, f, g, _, y, C, v, S;
if (defined(T)) {
m = Cartesian3.subtract(T, position, p0);
f = Cartesian3.magnitude(m) / distance <= 0.05 ? Cartesian3.normalize(m, p0) : void 0;
}
if (defined(x)) {
g = Cartesian3.subtract(x, position, p1);
_ = Cartesian3.magnitude(g) / distance <= 0.05 ? Cartesian3.normalize(g, p1) : void 0;
}
if (defined(b)) {
y = Cartesian3.subtract(b, position, p2);
C = Cartesian3.magnitude(y) / distance <= 0.05 ? Cartesian3.normalize(y, p2) : void 0;
}
if (defined(E)) {
v = Cartesian3.subtract(E, position, p3);
S = Cartesian3.magnitude(v) / distance <= 0.05 ? Cartesian3.normalize(v, p3) : void 0;
}
let P = Cartesian3.clone(Cartesian3.ZERO, surfaceNormalScratch);
let A = scratchCartesian3s[4];
if (defined(f) && defined(_)) {
A = Cartesian3.normalize(Cartesian3.cross(f, _, A), A);
P = Cartesian3.add(P, A, P);
}
if (defined(_) && defined(C)) {
A = Cartesian3.normalize(Cartesian3.cross(_, C, A), A);
P = Cartesian3.add(P, A, P);
}
if (defined(C) && defined(S)) {
A = Cartesian3.normalize(Cartesian3.cross(C, S, A), A);
P = Cartesian3.add(P, A, P);
}
if (defined(S) && defined(f)) {
A = Cartesian3.normalize(Cartesian3.cross(S, f, A), A);
P = Cartesian3.add(P, A, P);
}
if (!P.equals(Cartesian3.ZERO)) {
P = Cartesian3.normalize(P, P);
return CesiumMath.asinClamped(Math.abs(Math.sin(Cartesian3.angleBetween(P, surfaceNormal))));
}
}
}
return 0;
};
const onEditorClick = (e) => {
var _a, _b, _c;
editorPosition.value = [0, 0, 0];
showEditor.value = false;
if (!props.editable) {
return;
}
editorType.value = e;
const { viewer, drawingFabInstance } = $services;
const drawingFabInstanceVm = drawingFabInstance == null ? void 0 : drawingFabInstance.proxy;
if (e === "move") {
drawTip.value = drawTipOpts.value.drawingTipEditing;
drawStatus.value = DrawStatus.Drawing;
editingPoint.value = mouseoverPoint.value;
canShowDrawTip.value = true;
restorePosition = Object.assign({}, renderDatas.value[editingPoint.value._vcPolylineIndx]);
drawingFabInstanceVm.editingActionName = drawingType;
} else if (e === "remove") {
const index = mouseoverPoint.value._vcPolylineIndx;
renderDatas.value.splice(index, 1);
} else {
const index = mouseoverPoint.value._vcPolylineIndx;
const polyline = renderDatas.value[index];
(_c = (_b = (_a = props.editorOpts) == null ? void 0 : _a[e]) == null ? void 0 : _b.callback) == null ? void 0 : _c.call(_b, index, polyline);
}
emit(
"editorEvt",
{
type: e,
name: drawingType,
renderDatas,
index: mouseoverPoint.value._vcPolylineIndx,
pointIndex: mouseoverPoint.value._index,
point: mouseoverPoint.value
},
viewer
);
};
const clear = () => {
renderDatas.value = [];
stop();
};
const getLabelText = (point) => {
var _a, _b, _c, _d, _e, _f, _g, _h;
const { viewer } = $services;
const scene = viewer.scene;
const positionCartographic = scene.frameState.mapProjection.ellipsoid.cartesianToCartographic(point.position, {});
if (!Cesium.defined(positionCartographic)) {
return "";
}
return `${t("vc.measurement.point.lng")}${MeasureUnits.angleToString(
positionCartographic.longitude,
(_a = props.measureUnits) == null ? void 0 : _a.angleUnits,
props.locale,
(_b = props.decimals) == null ? void 0 : _b.lng
)}
${t("vc.measurement.point.lat")}${MeasureUnits.angleToString(
positionCartographic.latitude,
(_c = props.measureUnits) == null ? void 0 : _c.angleUnits,
props.locale,
(_d = props.decimals) == null ? void 0 : _d.lat
)}
${t("vc.measurement.point.height")}${MeasureUnits.distanceToString(
point.height,
(_e = props.measureUnits) == null ? void 0 : _e.distanceUnits,
props.locale,
(_f = props.decimals) == null ? void 0 : _f.height
)}
${t("vc.measurement.point.slope")}${MeasureUnits.angleToString(
point.slope,
(_g = props.measureUnits) == null ? void 0 : _g.slopeUnits,
props.locale,
(_h = props.decimals) == null ? void 0 : _h.slope
)}`;
};
if (props.preRenderDatas && props.preRenderDatas.length) {
const { viewer } = $services;
props.preRenderDatas.forEach((preRenderData) => {
const pointDrawing = {
drawStatus: DrawStatus.AfterDraw,
show: true,
position: makeCartesian3(preRenderData),
lng: 0,
lat: 0,
height: 0,
slope: 0,
pointOpts: {},
labelOpts: {},
billboardOpts: {}
};
const cart = Cesium.Cartographic.fromCartesian(pointDrawing.position, viewer.scene.globe.ellipsoid);
pointDrawing.positionDegrees = [Cesium.Math.toDegrees(cart.longitude), Cesium.Math.toDegrees(cart.latitude), cart.height];
getMeasurementResult(pointDrawing);
renderDatas.value.push(pointDrawing);
});
}
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
const publicMethods = { renderDatas, startNew, stop, clear, handleMouseClick, handleMouseMove };
Object.assign(instance.proxy, publicMethods);
return () => {
var _a, _b, _c;
const { createGuid } = Cesium;
const children = [];
const pointsRender = [];
const labelsRender = [];
const billboardsRender = [];
renderDatas.value.forEach((point, index) => {
var _a2;
const pointOpts = Object.assign({}, props.pointOpts, point.pointOpts);
pointsRender.push({
position: point.position,
id: createGuid(),
_vcPolylineIndx: index,
// for editor
...pointOpts,
show: point.show && ((_a2 = props.pointOpts) == null ? void 0 : _a2.show) || props.editable || point.drawStatus === DrawStatus.Drawing
});
const labelsOpts = Object.assign({}, props.labelOpts, point.labelOpts);
if (props.showLabel) {
if (cmpName === "VcDrawingPin") {
const billboardOpts = Object.assign({}, props.billboardOpts, point.billboardOpts);
billboardsRender.push({
position: point.position,
id: createGuid(),
_vcPolylineIndx: index,
// for editor
...billboardOpts
});
labelsOpts.text && labelsRender.push({
position: point.position,
id: createGuid(),
...labelsOpts
});
} else {
labelsRender.push({
position: point.position,
id: createGuid(),
text: getLabelText(point),
...labelsOpts
});
}
}
});
children.push(
h(VcCollectionPoint, {
enableMouseEvent: props.enableMouseEvent,
points: pointsRender,
onMouseover: onMouseoverPoints,
onMouseout: onMouseoutPoints,
onReady: onVcCollectionPointReady
})
);
children.push(
h(VcCollectionLabel, {
enableMouseEvent: props.enableMouseEvent,
labels: labelsRender,
onReady: onVcCollectionLabelReady
})
);
cmpName === "VcDrawingPin" && children.push(
h(VcCollectionBillboard, {
enableMouseEvent: props.enableMouseEvent,
billboards: billboardsRender
})
);
if (((_a = props.drawtip) == null ? void 0 : _a.show) && canShowDrawTip.value) {
const { viewer } = $services;
children.push(
h(
VcOverlayHtml,
{
position: drawTipPosition.value,
pixelOffset: (_b = props.drawtip) == null ? void 0 : _b.pixelOffset,
teleport: {
to: viewer.container
}
},
() => h(
"div",
{
class: "vc-drawtip vc-tooltip--style"
},
drawTip.value
)
)
);
}
if (showEditor.value) {
const buttons = [];
if (mouseoverPoint.value) {
const editorOpts = props.editorOpts;
for (const key in editorOpts) {
if (!Array.isArray(editorOpts[key]) && typeof editorOpts[key] !== "number") {
const opts = {
...editorOpts[key]
};
delete opts.color;
buttons.push(
h(
VcBtn,
{
style: { color: editorOpts[key].color, background: editorOpts[key].background },
...opts,
onclick: onEditorClick.bind(void 0, key)
},
() => h(
VcTooltip,
{
...editorOpts[key].tooltip
},
() => {
var _a2;
return h("strong", null, ((_a2 = editorOpts[key].tooltip) == null ? void 0 : _a2.tip) || t(`vc.drawing.editor.${key}`));
}
)
)
);
}
}
}
const { viewer } = $services;
children.push(
h(
VcOverlayHtml,
{
position: editorPosition.value,
pixelOffset: (_c = props.editorOpts) == null ? void 0 : _c.pixelOffset,
teleport: {
to: viewer.container
},
onMouseenter: onMouseenterEditor,
onMouseleave: onMouseleaveEditor
},
() => h(
"div",
{
class: "vc-editor"
},
buttons
)
)
);
}
return h(
VcCollectionPrimitive,
{
ref: primitiveCollectionRef,
show: props.show,
onReady: onPrimitiveCollectionReady
},
() => children
);
};
}
var VcMeasurementPoint = exports('VcMeasurementPoint', defineComponent({
name: "VcMeasurementPoint",
props: {
...useDrawingActionProps,
measureUnits: Object,
labelOpts: Object,
locale: String,
decimals: Object,
heightReference: Number,
showLabel: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingPoint(props, ctx, "VcMeasurementPoint");
}
}));
var VcMeasurementArea = exports('VcMeasurementArea', defineComponent({
name: "VcMeasurementArea",
props: {
...useDrawingActionProps,
measureUnits: Object,
polylineOpts: Object,
primitiveOpts: Object,
polygonOpts: Object,
labelOpts: Object,
labelsOpts: Object,
locale: String,
decimals: Object,
showDistanceLabel: Boolean,
showAngleLabel: Boolean,
showLabel: Boolean,
loop: Boolean,
clampToGround: Boolean,
autoUpdateLabelPosition: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingPolyline(props, ctx, "VcMeasurementArea");
}
}));
var VcMeasurementRectangle = exports('VcMeasurementRectangle', defineComponent({
name: "VcMeasurementRectangle",
props: {
...useDrawingActionProps,
measureUnits: Object,
polylineOpts: Object,
primitiveOpts: Object,
polygonOpts: Object,
labelOpts: Object,
labelsOpts: Object,
clampToGround: Boolean,
edge: Number,
locale: String,
decimals: Object,
showLabel: Boolean,
showDistanceLabel: Boolean,
showAngleLabel: Boolean,
loop: Boolean,
autoUpdateLabelPosition: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingSegment(props, ctx, "VcMeasurementRectangle");
}
}));
var VcMeasurementRegular = exports('VcMeasurementRegular', defineComponent({
name: "VcMeasurementRegular",
props: {
...useDrawingActionProps,
polylineOpts: Object,
primitiveOpts: Object,
polygonOpts: Object,
labelOpts: Object,
labelsOpts: Object,
clampToGround: Boolean,
edge: Number,
measureUnits: Object,
locale: String,
decimals: Object,
showLabel: Boolean,
showDistanceLabel: Boolean,
showAngleLabel: Boolean,
loop: Boolean,
autoUpdateLabelPosition: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingSegment(props, ctx, "VcMeasurementRegular");
}
}));
function useDrawingFab(props, ctx, instance, drawingActionInstances, mainFabOpts, clearActionOpts, cmpName) {
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { t } = useLocale();
const { $services } = commonState;
const { emit } = ctx;
const canRender = ref(false);
const containerStyle = reactive({});
const positionState = usePosition(props);
const containerRef = ref(null);
const fabRef = ref(null);
const mounted = ref(false);
const primitiveCollection = ref(null);
let visibilityState;
let selectedDrawingActionInstance = void 0;
const handleMouseClick = (movement, options) => {
var _a, _b;
const cmp = selectedDrawingActionInstance == null ? void 0 : selectedDrawingActionInstance.cmpRef.value;
(_a = cmp == null ? void 0 : cmp.handleMouseClick) == null ? void 0 : _a.call(cmp, movement.position, options);
let drawingActionOpts;
const instanceVm = instance.proxy;
if (instanceVm.editingActionName) {
drawingActionOpts = getDrawingActionInstance(instanceVm.editingActionName);
}
if (drawingActionOpts && drawingActionOpts !== selectedDrawingActionInstance) {
const cmp2 = drawingActionOpts.cmpRef.value;
(_b = cmp2 == null ? void 0 : cmp2.handleMouseClick) == null ? void 0 : _b.call(cmp2, movement.position, options);
}
};
const handleMouseMove = (movement, options) => {
var _a, _b;
const cmp = selectedDrawingActionInstance == null ? void 0 : selectedDrawingActionInstance.cmpRef.value;
(_a = cmp == null ? void 0 : cmp.handleMouseMove) == null ? void 0 : _a.call(cmp, movement.endPosition, options);
let drawingActionOpts;
const instanceVm = instance.proxy;
if (instanceVm.editingActionName) {
drawingActionOpts = getDrawingActionInstance(instanceVm.editingActionName);
}
if (drawingActionOpts && drawingActionOpts !== selectedDrawingActionInstance) {
const cmp2 = drawingActionOpts.cmpRef.value;
(_b = cmp2 == null ? void 0 : cmp2.handleMouseMove) == null ? void 0 : _b.call(cmp2, movement.endPosition, options);
}
};
const handleDoubleClick = (movement, options) => {
var _a, _b;
const cmp = selectedDrawingActionInstance == null ? void 0 : selectedDrawingActionInstance.cmpRef.value;
(_a = cmp == null ? void 0 : cmp.handleDoubleClick) == null ? void 0 : _a.call(cmp, movement.position, options);
let drawingActionOpts;
const instanceVm = instance.proxy;
if (instanceVm.editingActionName) {
drawingActionOpts = getDrawingActionInstance(instanceVm.editingActionName);
}
if (drawingActionOpts && drawingActionOpts !== selectedDrawingActionInstance) {
const cmp2 = drawingActionOpts.cmpRef.value;
(_b = cmp2 == null ? void 0 : cmp2.handleDoubleClick) == null ? void 0 : _b.call(cmp2, movement.position, options);
}
};
const {
activate,
deactivate,
destroy: destroyHandler,
isActive
} = useHandler($services, {
handleMouseClick,
handleMouseMove,
handleDoubleClick
});
instance.createCesiumObject = async () => {
canRender.value = true;
visibilityState = new VisibilityState();
return drawingActionInstances.value;
};
instance.mount = async () => {
updateRootStyle();
mounted.value = true;
activate();
return true;
};
instance.unmount = async () => {
if (selectedDrawingActionInstance) {
toggleAction(selectedDrawingActionInstance);
selectedDrawingActionInstance = void 0;
}
deactivate();
destroyHandler();
mounted.value = false;
return true;
};
const getWorldPosition = (scene, windowPosition, result) => {
const { Cesium3DTileFeature, Cesium3DTileset, Cartesian3, defined, Model, Ray } = Cesium;
if (Cesium.SuperMapVersion) {
return scene.pickPosition(windowPosition);
}
let position;
const cartesianScratch = {};
const rayScratch = new Ray();
if (scene.pickPositionSupported) {
visibilityState.hide(scene);
const pickObj = scene.pick(windowPosition, 1, 1);
visibilityState.restore(scene);
if (defined(pickObj)) {
if (pickObj instanceof Cesium3DTileFeature || pickObj.primitive instanceof Cesium3DTileset || pickObj.primitive instanceof Model || Cesium.S3MTilesLayer && pickObj.primitive instanceof Cesium.S3MTilesLayer) {
position = scene.pickPosition(windowPosition, cartesianScratch);
if (defined(position)) {
return Cartesian3.clone(position, result);
}
}
}
}
if (defined(scene.globe)) {
const ray = scene.camera.getPickRay(windowPosition, rayScratch);
position = scene.globe.pick(ray, scene, cartesianScratch);
return defined(position) ? Cartesian3.clone(position, result) : void 0;
}
return void 0;
};
const updateRootStyle = () => {
var _a;
const css = positionState.style.value;
containerStyle.left = css.left;
containerStyle.top = css.top;
containerStyle.transform = css.transform;
const side = positionState.attach.value;
const fabTarget = (_a = $(fabRef)) == null ? void 0 : _a.$el;
if (fabTarget !== void 0) {
const clientRect = fabTarget.getBoundingClientRect();
css.width = `${clientRect.width}px`;
css.height = `${clientRect.height}px`;
if ((side.bottom || side.top) && !side.left && !side.right) {
css.left = "50%";
css.transform = "translate(-50%, 0)";
}
if ((side.left || side.right) && !side.top && !side.bottom) {
css.top = "50%";
css.transform = "translate(0, -50%)";
}
}
Object.assign(containerStyle, css);
};
const restoreColor = ref(null);
const toggleAction = (drawingOption) => {
var _a;
const { viewer } = $services;
if (isString(drawingOption)) {
drawingOption = getDrawingActionInstance(drawingOption);
}
if (!drawingOption) {
commonState.logger.error("Invalid drawingActionOption or drawingActionOption name");
return;
}
const index = getDrawingActionInstanceIndex(drawingOption.name);
if (index === -1) {
return;
}
if (selectedDrawingActionInstance !== void 0) {
selectedDrawingActionInstance.actionOpts.color = restoreColor.value || "";
const cmp = selectedDrawingActionInstance.cmpRef.value;
(_a = cmp.stop) == null ? void 0 : _a.call(cmp);
selectedDrawingActionInstance.isActive = false;
emit(
"activeEvt",
{
type: selectedDrawingActionInstance.name,
option: selectedDrawingActionInstance,
isActive: false
},
viewer
);
}
if ((selectedDrawingActionInstance == null ? void 0 : selectedDrawingActionInstance.name) === (drawingOption == null ? void 0 : drawingOption.name)) {
selectedDrawingActionInstance = void 0;
drawingActionInstances.value[index].actionOpts.color = restoreColor.value || "red";
} else {
nextTick(() => {
const cmp = drawingActionInstances.value[index].cmpRef.value;
cmp.startNew();
restoreColor.value = drawingActionInstances.value[index].actionOpts.color;
drawingActionInstances.value[index].actionOpts.color = props.activeColor;
drawingActionInstances.value[index].isActive = true;
selectedDrawingActionInstance = drawingActionInstances.value[index];
emit(
"activeEvt",
{
type: selectedDrawingActionInstance.name,
option: selectedDrawingActionInstance,
isActive: true
},
viewer
);
});
}
};
const getDrawingActionInstance = (drawingName) => {
return drawingActionInstances.value.find((v) => v.name === drawingName);
};
const getDrawingActionInstanceIndex = (drawingName) => {
return drawingActionInstances.value.findIndex((v) => v.name === drawingName);
};
const onUpdateFab = (value) => {
if (value) {
activate();
} else {
if (selectedDrawingActionInstance) {
toggleAction(selectedDrawingActionInstance);
}
deactivate();
}
mainFabOpts.modelValue = value;
emit("fabUpdated", value);
};
const clearAll = () => {
drawingActionInstances.value.forEach((drawingActionOpts) => {
var _a;
(_a = drawingActionOpts.cmpRef.value) == null ? void 0 : _a.clear();
});
selectedDrawingActionInstance && toggleAction(selectedDrawingActionInstance);
const { viewer } = $services;
emit(
"clearEvt",
{
type: "clear",
option: clearActionOpts
},
viewer
);
};
const getServices = () => {
return mergeDescriptors(commonState.getServices(), {
get drawingFabInstance() {
return instance;
},
get selectedDrawingActionInstance() {
return selectedDrawingActionInstance;
},
get getWorldPosition() {
return getWorldPosition;
},
get drawingHandlerActive() {
return isActive;
}
});
};
const onPrimitiveCollectionReady = ({ cesiumObject }) => {
cesiumObject._vcId = cmpName;
};
provide(vcKey, getServices());
Object.assign(instance.proxy, {
clearAll,
deactivate,
activate,
toggleAction,
getFabRef: () => fabRef.value,
getDrawingActionInstance,
getDrawingActionInstances: () => drawingActionInstances.value,
getSelectedDrawingActionInstance: () => selectedDrawingActionInstance
});
const renderContent = () => {
if (canRender.value) {
const fabActionChildren = [];
const drawingChildren = [];
drawingActionInstances.value.forEach((drawingActionInstance) => {
fabActionChildren.push(
h(
VcFabAction,
{
ref: drawingActionInstance.actionRef,
style: drawingActionInstance.actionStyle,
class: drawingActionInstance.actionClass,
...drawingActionInstance.actionOpts,
onClick: () => {
toggleAction(drawingActionInstance);
}
},
() => h(
VcTooltip,
{
...drawingActionInstance.actionOpts.tooltip
},
() => h("strong", null, drawingActionInstance.tip)
)
)
);
drawingActionInstance.cmp && drawingChildren.push(
h(drawingActionInstance.cmp, {
ref: drawingActionInstance.cmpRef,
editable: props.editable,
clampToGround: props.clampToGround,
mode: props.mode,
onDrawEvt: (e, viewer) => {
emit("drawEvt", e, viewer);
},
onEditorEvt: (e, viewer) => {
emit("editorEvt", e, viewer);
},
onMouseEvt: (e, viewer) => {
emit("mouseEvt", e, viewer);
},
...drawingActionInstance.cmpOpts
})
);
});
drawingActionInstances.value.length && fabActionChildren.push(
h(
VcFabAction,
{
style: {
background: clearActionOpts.color,
color: clearActionOpts.textColor
},
class: "vc-draw-button vc-draw-clear",
...clearActionOpts,
onClick: clearAll
},
() => h(
VcTooltip,
{
...clearActionOpts.tooltip
},
() => h("strong", null, clearActionOpts.tooltip.tip || t(`vc.${cmpName}.clear.tip`))
)
)
);
const root = [];
if (mounted.value) {
root.push(
h(
"div",
{
ref: containerRef,
class: "vc-drawings-container " + positionState.classes.value,
style: containerStyle
},
ctx.slots.body !== void 0 ? ctx.slots.body(drawingActionInstances.value) : h(
VcFab,
{
ref: fabRef,
class: "vc-draw-button",
style: {
background: mainFabOpts.color,
color: mainFabOpts.textColor
},
...mainFabOpts,
"onUpdate:modelValue": onUpdateFab
},
{
default: () => fabActionChildren,
tooltip: () => h(
VcTooltip,
{
...mainFabOpts.tooltip
},
() => h("strong", null, mainFabOpts.tooltip.tip || (mainFabOpts.modelValue ? t("vc.drawing.collapse") : t("vc.drawing.expand")))
)
}
)
)
);
}
root.push(
h(
VcCollectionPrimitive,
{
ref: primitiveCollection,
show: props.show,
onReady: onPrimitiveCollectionReady
},
() => drawingChildren
)
);
return root;
} else {
return createCommentVNode("v-if");
}
};
return {
renderContent
};
}
const emits$3 = {
...drawingEmit,
fabUpdated: (value) => true,
clearEvt: (e, viewer) => true
};
var Measurements = defineComponent({
name: "VcMeasurements",
props: measurementsProps,
emits: emits$3,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "VcMeasurements";
const { t } = useLocale();
const clearActionOpts = reactive(Object.assign({}, defaultOptions$3.clearActionOpts, props.clearActionOpts));
const mainFabOpts = reactive(Object.assign({}, defaultOptions$3.mainFabOpts, props.mainFabOpts));
const fabActionOpts = reactive(Object.assign({}, defaultOptions$3.fabActionOpts, props.fabActionOpts));
const distanceActionOpts = reactive(
Object.assign({}, defaultOptions$3.distanceActionOpts, mergeActionOpts("distanceActionOpts"))
);
const distanceMeasurementOpts = reactive(
deepMerge(cloneDeep(defaultOptions$3.distanceMeasurementOpts), props.distanceMeasurementOpts)
);
const componentDistanceActionOpts = reactive(
Object.assign({}, defaultOptions$3.componentDistanceActionOpts, mergeActionOpts("componentDistanceActionOpts"))
);
const componentDistanceMeasurementOpts = reactive(
deepMerge(cloneDeep(defaultOptions$3.componentDistanceMeasurementOpts), props.componentDistanceMeasurementOpts)
);
const polylineActionOpts = reactive(
Object.assign({}, defaultOptions$3.polylineActionOpts, mergeActionOpts("polylineActionOpts"))
);
const polylineMeasurementOpts = reactive(
deepMerge(cloneDeep(defaultOptions$3.polylineMeasurementOpts), props.polylineMeasurementOpts)
);
const horizontalActionOpts = reactive(
Object.assign({}, defaultOptions$3.horizontalActionOpts, mergeActionOpts("horizontalActionOpts"))
);
const horizontalMeasurementOpts = reactive(
deepMerge(cloneDeep(defaultOptions$3.horizontalMeasurementOpts), props.horizontalMeasurementOpts)
);
const verticalActionOpts = reactive(
Object.assign({}, defaultOptions$3.verticalActionOpts, mergeActionOpts("verticalActionOpts"))
);
const verticalMeasurementOpts = reactive(
deepMerge(cloneDeep(defaultOptions$3.verticalMeasurementOpts), props.verticalMeasurementOpts)
);
const heightActionOpts = reactive(Object.assign({}, defaultOptions$3.heightActionOpts, mergeActionOpts("heightActionOpts")));
const heightMeasurementOpts = reactive(deepMerge(cloneDeep(defaultOptions$3.heightMeasurementOpts), props.heightMeasurementOpts));
const areaActionOpts = reactive(Object.assign({}, defaultOptions$3.areaActionOpts, mergeActionOpts("areaActionOpts")));
const areaMeasurementOpts = reactive(
deepMerge(cloneDeep(defaultOptions$3.areaMeasurementOpts), props.areaMeasurementOpts)
);
const pointActionOpts = reactive(Object.assign({}, defaultOptions$3.pointActionOpts, mergeActionOpts("pointActionOpts")));
const pointMeasurementOpts = reactive(deepMerge(cloneDeep(defaultOptions$3.pointMeasurementOpts), props.pointMeasurementOpts));
const rectangleActionOpts = reactive(
Object.assign({}, defaultOptions$3.rectangleActionOpts, mergeActionOpts("rectangleActionOpts"))
);
const rectangleMeasurementOpts = reactive(
deepMerge(cloneDeep(defaultOptions$3.rectangleMeasurementOpts), props.rectangleMeasurementOpts)
);
const regularActionOpts = reactive(
Object.assign({}, defaultOptions$3.regularActionOpts, mergeActionOpts("regularActionOpts"))
);
const regularMeasurementOpts = reactive(
deepMerge(cloneDeep(defaultOptions$3.regularMeasurementOpts), props.regularMeasurementOpts)
);
const circleActionOpts = reactive(Object.assign({}, defaultOptions$3.circleActionOpts, mergeActionOpts("circleActionOpts")));
const circleMeasurementOpts = reactive(
deepMerge(cloneDeep(defaultOptions$3.circleMeasurementOpts), props.circleMeasurementOpts)
);
const options = {};
options.distanceActionOpts = distanceActionOpts;
options.distanceMeasurementOpts = distanceMeasurementOpts;
options.componentDistanceActionOpts = componentDistanceActionOpts;
options.componentDistanceMeasurementOpts = componentDistanceMeasurementOpts;
options.polylineActionOpts = polylineActionOpts;
options.polylineMeasurementOpts = polylineMeasurementOpts;
options.horizontalActionOpts = horizontalActionOpts;
options.horizontalMeasurementOpts = horizontalMeasurementOpts;
options.verticalActionOpts = verticalActionOpts;
options.verticalMeasurementOpts = verticalMeasurementOpts;
options.heightActionOpts = heightActionOpts;
options.heightMeasurementOpts = heightMeasurementOpts;
options.areaActionOpts = areaActionOpts;
options.areaMeasurementOpts = areaMeasurementOpts;
options.pointActionOpts = pointActionOpts;
options.pointMeasurementOpts = pointMeasurementOpts;
options.rectangleActionOpts = rectangleActionOpts;
options.rectangleMeasurementOpts = rectangleMeasurementOpts;
options.regularActionOpts = regularActionOpts;
options.regularMeasurementOpts = regularMeasurementOpts;
options.circleActionOpts = circleActionOpts;
options.circleMeasurementOpts = circleMeasurementOpts;
options.clearActionOpts = clearActionOpts;
const drawingActionInstances = computed(() => {
return props.measurements.map((measurement) => ({
name: measurement,
type: "measurement",
actionStyle: {
background: options[`${camelize(measurement)}ActionOpts`].color,
color: options[`${camelize(measurement)}ActionOpts`].textColor
},
actionClass: `vc-measure-${measurement} vc-measure-button`,
actionRef: ref(null),
actionOpts: options[`${camelize(measurement)}ActionOpts`],
cmp: getMeasurementCmp(measurement),
cmpRef: ref(null),
cmpOpts: options[`${camelize(measurement)}MeasurementOpts`],
tip: options[`${camelize(measurement)}ActionOpts`].tooltip.tip || t(`vc.measurement.${measurement}.tip`),
isActive: false
}));
});
function getMeasurementCmp(name) {
switch (name) {
case "distance":
case "component-distance":
return VcMeasurementDistance;
case "polyline":
return VcMeasurementPolyline;
case "horizontal":
return VcMeasurementHorizontal;
case "vertical":
return VcMeasurementVertical;
case "height":
return VcMeasurementHeight;
case "point":
return VcMeasurementPoint;
case "area":
return VcMeasurementArea;
case "rectangle":
return VcMeasurementRectangle;
case "regular":
case "circle":
return VcMeasurementRegular;
default:
return void 0;
}
}
function mergeActionOpts(actionName) {
return isEqual(defaultOptions$3[actionName], props[actionName]) ? fabActionOpts : Object.assign({}, fabActionOpts, props[actionName]);
}
return (_a = useDrawingFab(props, ctx, instance, drawingActionInstances, mainFabOpts, clearActionOpts, "measurement")) == null ? void 0 : _a.renderContent;
}
});
Measurements.install = (app) => {
app.component(Measurements.name, Measurements);
};
const _Measurements = Measurements;
const VcMeasurements = exports('VcMeasurements', _Measurements);
const pointDrawingActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-drawing-point"
});
const polylineDrawingActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-drawing-polyline"
});
const polygonDrawingActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-drawing-polygon"
});
const rectangleDrawingActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-drawing-rectangle"
});
const pinDrawingActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-drawing-pin"
});
const pinDrawingDefault = Object.assign({}, pointDrawingDefault, {
pointOpts: Object.assign({}, pointOptsDefault, {
show: false
}),
billboardOpts: billboardOptsDefault,
labelOpts: Object.assign({}, labelOptsDefault, {
pixelOffset: [0, -30],
verticalOrigin: 1
}),
showLabel: true
});
const fabActionOptsDefault$1 = Object.assign({}, {});
const mainFabDefault$1 = Object.assign({}, actionOptions, {
direction: "right",
icon: "vc-icons-drawing-button",
activeIcon: "vc-icons-drawing-button",
verticalActionsAlign: "center",
hideIcon: false,
persistent: false,
modelValue: true,
hideActionOnClick: false,
color: "info"
});
const drawingType = ["pin", "point", "polyline", "polygon", "rectangle", "regular", "circle"];
const isValidDrawingType = (drawings) => {
let flag = true;
drawings.forEach((drawing) => {
if (!drawingType.includes(drawing)) {
console.error(`VueCesium: unknown drawing type: ${drawing}`);
flag = false;
}
});
return flag;
};
const drawingsProps = exports('drawingsProps', {
...useDrawingFabProps,
drawings: {
type: Array,
default: () => drawingType,
validator: isValidDrawingType
},
mainFabOpts: {
type: Object,
default: () => mainFabDefault$1
},
fabActionOpts: {
type: Object,
default: () => fabActionOptsDefault$1
},
pinActionOpts: {
type: Object,
default: () => pinDrawingActionDefault
},
pinDrawingOpts: {
type: Object,
default: () => pinDrawingDefault
},
pointActionOpts: {
type: Object,
default: () => pointDrawingActionDefault
},
pointDrawingOpts: {
type: Object,
default: () => pointDrawingDefault
},
polylineActionOpts: {
type: Object,
default: () => polylineDrawingActionDefault
},
polylineDrawingOpts: {
type: Object,
default: () => polylineDrawingDefault
},
polygonActionOpts: {
type: Object,
default: () => polygonDrawingActionDefault
},
polygonDrawingOpts: {
type: Object,
default: () => polygonDrawingDefault
},
rectangleActionOpts: {
type: Object,
default: () => rectangleDrawingActionDefault
},
rectangleDrawingOpts: {
type: Object,
default: () => rectangleDrawingDefault
},
circleActionOpts: {
type: Object,
default: () => circleDrawingActionDefault
},
circleDrawingOpts: {
type: Object,
default: () => circleDrawingDefault
},
regularActionOpts: {
type: Object,
default: () => regularDrawingActionDefault
},
regularDrawingOpts: {
type: Object,
default: () => regularDrawingDefault
}
});
const defaultOptions$2 = getDefaultOptionByProps(drawingsProps);
var VcDrawingPin = exports('VcDrawingPin', defineComponent({
name: "VcDrawingPin",
props: {
...useDrawingActionProps,
billboardOpts: Object,
labelOpts: Object,
heightReference: Number,
showLabel: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingPoint(props, ctx, "VcDrawingPin");
}
}));
var VcDrawingPoint = exports('VcDrawingPoint', defineComponent({
name: "VcDrawingPoint",
props: {
...useDrawingActionProps,
heightReference: Number,
labelOpts: Object,
showLabel: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingPoint(props, ctx, "VcDrawingPoint");
}
}));
var VcDrawingPolyline = exports('VcDrawingPolyline', defineComponent({
name: "VcDrawingPolyline",
props: {
...useDrawingActionProps,
polylineOpts: Object,
primitiveOpts: Object,
loop: Boolean,
clampToGround: Boolean,
showLabel: Boolean,
showDistanceLabel: Boolean,
showAngleLabel: Boolean,
labelOpts: Object,
labelsOpts: Object,
autoUpdateLabelPosition: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingPolyline(props, ctx, "VcDrawingPolyline");
}
}));
var VcDrawingPolygon = exports('VcDrawingPolygon', defineComponent({
name: "VcDrawingPolygon",
props: {
...useDrawingActionProps,
polylineOpts: Object,
primitiveOpts: Object,
polygonOpts: Object,
loop: Boolean,
clampToGround: Boolean,
showLabel: Boolean,
showDistanceLabel: Boolean,
showAngleLabel: Boolean,
labelOpts: Object,
labelsOpts: Object,
autoUpdateLabelPosition: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingPolyline(props, ctx, "VcDrawingPolygon");
}
}));
var VcDrawingRegular = exports('VcDrawingRegular', defineComponent({
name: "VcDrawingRegular",
props: {
...useDrawingActionProps,
polylineOpts: Object,
polygonOpts: Object,
primitiveOpts: Object,
clampToGround: Boolean,
edge: Number,
showLabel: Boolean,
showDistanceLabel: Boolean,
showAngleLabel: Boolean,
labelOpts: Object,
labelsOpts: Object,
loop: Boolean,
autoUpdateLabelPosition: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingSegment(props, ctx, "VcDrawingRegular");
}
}));
var VcDrawingRectangle = exports('VcDrawingRectangle', defineComponent({
name: "VcDrawingRectangle",
props: {
...useDrawingActionProps,
polylineOpts: Object,
primitiveOpts: Object,
polygonOpts: Object,
clampToGround: Boolean,
showLabel: Boolean,
showDistanceLabel: Boolean,
showAngleLabel: Boolean,
labelOpts: Object,
labelsOpts: Object,
loop: Boolean,
autoUpdateLabelPosition: Boolean
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingSegment(props, ctx, "VcDrawingRectangle");
}
}));
const emits$2 = {
...drawingEmit,
fabUpdated: (value) => true,
clearEvt: (e, viewer) => true
};
var Drawings = defineComponent({
name: "VcDrawings",
props: drawingsProps,
emits: emits$2,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "VcDrawings";
const { t } = useLocale();
const options = {};
const clearActionOpts = reactive(Object.assign({}, defaultOptions$2.clearActionOpts, props.clearActionOpts));
const mainFabOpts = reactive(Object.assign({}, defaultOptions$2.mainFabOpts, props.mainFabOpts));
const fabActionOpts = reactive(Object.assign({}, defaultOptions$2.fabActionOpts, props.fabActionOpts));
const pointActionOpts = reactive(Object.assign({}, defaultOptions$2.pointActionOpts, mergeActionOpts("pointActionOpts")));
const pointDrawingOpts = reactive(deepMerge(cloneDeep(defaultOptions$2.pointDrawingOpts), props.pointDrawingOpts));
const polylineActionOpts = reactive(
Object.assign({}, defaultOptions$2.polylineActionOpts, mergeActionOpts("polylineActionOpts"))
);
const polylineDrawingOpts = reactive(deepMerge(cloneDeep(defaultOptions$2.polylineDrawingOpts), props.polylineDrawingOpts));
const polygonActionOpts = reactive(
Object.assign({}, defaultOptions$2.polygonActionOpts, mergeActionOpts("polygonActionOpts"))
);
const polygonDrawingOpts = reactive(deepMerge(cloneDeep(defaultOptions$2.polygonDrawingOpts), props.polygonDrawingOpts));
const rectangleActionOpts = reactive(
Object.assign({}, defaultOptions$2.rectangleActionOpts, mergeActionOpts("rectangleActionOpts"))
);
const rectangleDrawingOpts = reactive(deepMerge(cloneDeep(defaultOptions$2.rectangleDrawingOpts), props.rectangleDrawingOpts));
const circleActionOpts = reactive(Object.assign({}, defaultOptions$2.circleActionOpts, mergeActionOpts("circleActionOpts")));
const circleDrawingOpts = reactive(deepMerge(cloneDeep(defaultOptions$2.circleDrawingOpts), props.circleDrawingOpts));
const regularActionOpts = reactive(
Object.assign({}, defaultOptions$2.regularActionOpts, mergeActionOpts("regularActionOpts"))
);
const regularDrawingOpts = reactive(deepMerge(cloneDeep(defaultOptions$2.regularDrawingOpts), props.regularDrawingOpts));
const pinActionOpts = reactive(Object.assign({}, defaultOptions$2.pinActionOpts, mergeActionOpts("pinActionOpts")));
const pinDrawingOpts = reactive(deepMerge(cloneDeep(defaultOptions$2.pinDrawingOpts), props.pinDrawingOpts));
options.pointActionOpts = pointActionOpts;
options.pointDrawingOpts = pointDrawingOpts;
options.polylineActionOpts = polylineActionOpts;
options.polylineDrawingOpts = polylineDrawingOpts;
options.polygonActionOpts = polygonActionOpts;
options.polygonDrawingOpts = polygonDrawingOpts;
options.rectangleActionOpts = rectangleActionOpts;
options.rectangleDrawingOpts = rectangleDrawingOpts;
options.circleActionOpts = circleActionOpts;
options.circleDrawingOpts = circleDrawingOpts;
options.regularActionOpts = regularActionOpts;
options.regularDrawingOpts = regularDrawingOpts;
options.pinActionOpts = pinActionOpts;
options.pinDrawingOpts = pinDrawingOpts;
options.clearActionOpts = clearActionOpts;
const drawingActionInstances = computed(() => {
return props.drawings.map((drawing) => ({
name: drawing,
type: "drawing",
actionStyle: {
background: options[`${camelize(drawing)}ActionOpts`].color,
color: options[`${camelize(drawing)}ActionOpts`].textColor
},
actionClass: `vc-draw-${drawing} vc-draw-button`,
actionRef: ref(null),
actionOpts: options[`${camelize(drawing)}ActionOpts`],
cmp: getDrawingCmp(drawing),
cmpRef: ref(null),
cmpOpts: options[`${camelize(drawing)}DrawingOpts`],
tip: options[`${camelize(drawing)}ActionOpts`].tooltip.tip || t(`vc.drawing.${camelize(drawing)}.tip`),
isActive: false
}));
});
function getDrawingCmp(name) {
switch (name) {
case "pin":
return VcDrawingPin;
case "point":
return VcDrawingPoint;
case "polyline":
return VcDrawingPolyline;
case "polygon":
return VcDrawingPolygon;
case "rectangle":
if (rectangleDrawingOpts.regular) {
return VcDrawingRegular;
} else {
return VcDrawingRectangle;
}
case "circle":
case "regular":
return VcDrawingRegular;
default:
return void 0;
}
}
function mergeActionOpts(actionName) {
return isEqual(defaultOptions$2[actionName], props[actionName]) ? fabActionOpts : Object.assign({}, fabActionOpts, props[actionName]);
}
return (_a = useDrawingFab(props, ctx, instance, drawingActionInstances, mainFabOpts, clearActionOpts, "drawing")) == null ? void 0 : _a.renderContent;
}
});
Drawings.install = (app) => {
app.component(Drawings.name, Drawings);
};
const _Drawings = Drawings;
const VcDrawings = exports('VcDrawings', _Drawings);
class AMapImageryProvider {
constructor(options) {
const { Resource, defaultValue, Credit, Event } = Cesium;
this._url = options.url;
const resource = Resource.createIfNeeded(this._url);
resource.appendForwardSlash();
this._ready = false;
this._resource = resource;
this._tileDiscardPolicy = options.tileDiscardPolicy;
this._tileWidth = 256;
this._tileHeight = 256;
this._minimumLevel = options.minimumLevel || 0;
this._maximumLevel = options.maximumLevel || 20;
this._tilingScheme = options.tilingScheme || new Cesium.WebMercatorTilingScheme();
this._rectangle = options.rectangle || this._tilingScheme.rectangle;
let credit = options.credit;
if (typeof credit === "string") {
credit = new Credit(credit);
}
this._credit = credit;
this.enablePickFeatures = defaultValue(options.enablePickFeatures, false);
this._hasAlphaChannel = defaultValue(options.hasAlphaChannel, true);
this._errorEvent = new Event();
this._readyPromise = defer();
this._ready = true;
this._readyPromise.resolve(true);
this._subdomains = options.subdomains || ["01", "02", "03", "04"];
this._domain = options.domain || "webst";
this._style = options.mapStyle || "6";
this._lang = options.lang || "zh_cn";
this._scl = options.scl || "1";
this._ltype = options.ltype || "0";
}
get url() {
return this._resource._url;
}
get proxy() {
return this._resource.proxy;
}
get tileWidth() {
if (!this._ready) {
throw new Cesium.DeveloperError("tileWidth must not be called before the imagery provider is ready.");
}
return this._tileWidth;
}
get tileHeight() {
if (!this._ready) {
throw new Cesium.DeveloperError("tileHeight must not be called before the imagery provider is ready.");
}
return this._tileHeight;
}
get maximumLevel() {
if (!this._ready) {
throw new Cesium.DeveloperError("maximumLevel must not be called before the imagery provider is ready.");
}
return this._maximumLevel;
}
get minimumLevel() {
if (!this.ready) {
throw new Cesium.DeveloperError("minimumLevel must not be called before the imagery provider is ready.");
}
return this._minimumLevel;
}
get tilingScheme() {
if (!this._ready) {
throw new Cesium.DeveloperError("tilingScheme must not be called before the imagery provider is ready.");
}
return this._tilingScheme;
}
get rectangle() {
if (!this.ready) {
throw new Cesium.DeveloperError("rectangle must not be called before the imagery provider is ready.");
}
return this._rectangle;
}
get tileDiscardPolicy() {
if (!this.ready) {
throw new Cesium.DeveloperError("tileDiscardPolicy must not be called before the imagery provider is ready.");
}
return this._tileDiscardPolicy;
}
get errorEvent() {
return this._errorEvent;
}
get ready() {
return this._ready;
}
get readyPromise() {
return this._readyPromise.promise;
}
get credit() {
if (!this.ready) {
throw new Cesium.DeveloperError("credit must not be called before the imagery provider is ready.");
}
return this._credit;
}
get hasAlphaChannel() {
if (!this.ready) {
throw new Cesium.DeveloperError("hasAlphaChannel must not be called before the imagery provider is ready.");
}
return this._hasAlphaChannel;
}
getTileCredits(x, y, level) {
if (!this.ready) {
throw new Cesium.DeveloperError("getTileCredits must not be called before the imagery provider is ready.");
}
return void 0;
}
requestImage(x, y, level, request) {
if (!this.ready) {
throw new Cesium.DeveloperError("requestImage must not be called before the imagery provider is ready.");
}
return Cesium.ImageryProvider.loadImage(this, buildImageResource$4.call(this, x, y, level, request));
}
pickFeatures(x, y, level, longitude, latitude) {
return void 0;
}
}
function buildImageResource$4(x, y, level, request) {
let url = this._url;
const subdomains = this._subdomains;
url = url.replace("{domain}", this._domain).replace("{s}", subdomains[(x + y + level) % subdomains.length]).replace("{lang}", this._lang).replace("{style}", this._style).replace("{scl}", this._scl).replace("{ltype}", this._ltype).replace("{x}", x).replace("{y}", y).replace("{z}", level);
const resource = this._resource.getDerivedResource({
url,
request
});
return resource;
}
const amapImageryProviderProps = exports('amapImageryProviderProps', {
url: {
type: String,
default: "https://{domain}{s}.is.autonavi.com/appmaptile?lang={lang}&size=1&style={style}&scl={scl}<ype={ltype}&x={x}&y={y}&z={z}"
},
subdomains: {
type: Array,
default: () => ["01", "02", "03", "04"]
},
domain: {
type: String,
default: "webst"
},
lang: {
type: String,
default: "zh_cn"
},
mapStyle: {
// 地图类型控制,6卫星图(st),7简图(st rd),8详图(不透明rd,透明图st)
type: String,
default: "6"
},
scl: {
// 尺寸控制,1=256,2=512
type: String,
default: "1"
},
ltype: {
// 线性控制,只对地图要素进行控制,没有文字注记,要素多少,是否透明
// 纯道路 ltype=11 mapStyle=8
// 纯地标 ltype=4 mapStyle=8
// 道路标注 ltype=0 mapStyle=8
type: String,
default: "0"
},
...credit,
...minimumLevel,
...maximumLevel,
...rectangle,
...tilingScheme,
...projectionTransforms
});
var ImageryProviderAmap = defineComponent({
name: "VcImageryProviderAmap",
props: amapImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "AMapImageryProvider";
const providersState = useProviders(props, ctx, instance);
if (void 0 === providersState) {
return;
}
instance.createCesiumObject = async () => {
Cesium.AMapImageryProvider = Cesium.AMapImageryProvider || AMapImageryProvider;
if (providersState.unwatchFns.length === 0) {
providersState.setPropsWatcher(true);
}
const options = providersState.transformProps(props);
return new Cesium.AMapImageryProvider(options);
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const arcgisImageryProviderProps = exports('arcgisImageryProviderProps', {
url: {
type: [String, Object],
default: "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer"
},
...token,
...tileDiscardPolicy,
usePreCachedTilesIfAvailable: {
type: Boolean,
default: true
},
...layers,
...enablePickFeatures,
...rectangle,
...tilingScheme,
...ellipsoid,
...credit,
...tileWidth,
...tileHeight,
...maximumLevel
});
var ImageryProviderArcgis = defineComponent({
name: "VcImageryProviderArcgis",
props: arcgisImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "ArcGisMapServerImageryProvider";
useProviders(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
class Point {
constructor(lng, lat) {
if (isNaN(lng)) {
lng = isNaN(lng) ? 0 : lng;
}
if (isString(lng)) {
lng = parseFloat(lng);
}
if (isNaN(lat)) {
lat = isNaN(lat) ? 0 : lat;
}
if (isString(lat)) {
lat = parseFloat(lat);
}
this.lng = lng;
this.lat = lat;
}
equals(other) {
return other && this.lat === other.lat && this.lng === other.lng;
}
}
Point.isInRange = function(pt) {
return pt && pt.lng <= 180 && pt.lng >= -180 && pt.lat <= 74 && pt.lat >= -74;
};
class Pixel {
constructor(x, y) {
this.x = x || 0;
this.y = y || 0;
}
equals(other) {
return other && other.x === this.x && other.y === this.y;
}
}
const _BaiduMapMercatorProjection = class _BaiduMapMercatorProjection {
/**
* 经纬度变换至墨卡托坐标
* @param Point 经纬度
* @return Point 墨卡托
*/
lngLatToMercator(point, curCity) {
return _BaiduMapMercatorProjection.convertLL2MC(point);
}
/**
* 球面到平面坐标
* @param Point 球面坐标
* @return Pixel 平面坐标
*/
lngLatToPoint(point) {
const mercator = _BaiduMapMercatorProjection.convertLL2MC(point);
return new Pixel(mercator.lng, mercator.lat);
}
/**
* 墨卡托变换至经纬度
* @param Point 墨卡托
* @returns Point 经纬度
*/
mercatorToLngLat(point, curCity) {
return _BaiduMapMercatorProjection.convertMC2LL(point);
}
/**
* 平面到球面坐标
* @param Pixel 平面坐标
* @returns Point 球面坐标
*/
pointToLngLat(point) {
const mercator = new Point(point.x, point.y);
return _BaiduMapMercatorProjection.convertMC2LL(mercator);
}
/**
* 地理坐标转换至像素坐标
* @param Point 地理坐标
* @param Number 级别
* @param Point 地图中心点,注意为了保证没有误差,这里需要传递墨卡托坐标
* @param Size 地图容器大小
* @return Pixel 像素坐标
*/
pointToPixel(point, zoom, mapCenter, mapSize, curCity) {
if (!point) {
return;
}
point = this.lngLatToMercator(point, curCity);
mapCenter = this.lngLatToMercator(mapCenter);
const zoomUnits = this.getZoomUnits(zoom);
const x = Math.round((point.lng - mapCenter.lng) / zoomUnits + mapSize.width / 2);
const y = Math.round((mapCenter.lat - point.lat) / zoomUnits + mapSize.height / 2);
return new Pixel(x, y);
}
/**
* 像素坐标转换至地理坐标
* @param Pixel 像素坐标
* @param Number 级别
* @param Point 地图中心点,注意为了保证没有误差,这里需要传递墨卡托坐标
* @param Size 地图容器大小
* @return Point 地理坐标
*/
pixelToPoint(pixel, zoom, mapCenter, mapSize, curCity) {
if (!pixel) {
return;
}
const zoomUnits = this.getZoomUnits(zoom);
const lng = mapCenter.lng + zoomUnits * (pixel.x - mapSize.width / 2);
const lat = mapCenter.lat - zoomUnits * (pixel.y - mapSize.height / 2);
const point = new Point(lng, lat);
return this.mercatorToLngLat(point, curCity);
}
getZoomUnits(zoom) {
return Math.pow(2, 18 - zoom);
}
};
// constructor () {
// super()
// }
_BaiduMapMercatorProjection.EARTHRADIUS = 637099681e-2;
_BaiduMapMercatorProjection.MCBAND = [1289059486e-2, 836237787e-2, 5591021, 348198983e-2, 167804312e-2, 0];
_BaiduMapMercatorProjection.LLBAND = [75, 60, 45, 30, 15, 0];
_BaiduMapMercatorProjection.MC2LL = [
[
1410526172116255e-23,
898305509648872e-20,
-1.9939833816331,
200.9824383106796,
-187.2403703815547,
91.6087516669843,
-23.38765649603339,
2.57121317296198,
-0.03801003308653,
173379812e-1
],
[
-7435856389565537e-24,
8983055097726239e-21,
-0.78625201886289,
96.32687599759846,
-1.85204757529826,
-59.36935905485877,
47.40033549296737,
-16.50741931063887,
2.28786674699375,
1026014486e-2
],
[
-3030883460898826e-23,
898305509983578e-20,
0.30071316287616,
59.74293618442277,
7.357984074871,
-25.38371002664745,
13.45380521110908,
-3.29883767235584,
0.32710905363475,
685681737e-2
],
[
-1981981304930552e-23,
8983055099779535e-21,
0.03278182852591,
40.31678527705744,
0.65659298677277,
-4.44255534477492,
0.85341911805263,
0.12923347998204,
-0.04625736007561,
448277706e-2
],
[
309191371068437e-23,
8983055096812155e-21,
6995724062e-14,
23.10934304144901,
-23663490511e-14,
-0.6321817810242,
-0.00663494467273,
0.03430082397953,
-0.00466043876332,
25551644e-1
],
[
2890871144776878e-24,
8983055095805407e-21,
-3068298e-14,
7.47137025468032,
-353937994e-14,
-0.02145144861037,
-1234426596e-14,
10322952773e-14,
-323890364e-14,
826088.5
]
];
_BaiduMapMercatorProjection.LL2MC = [
[
-0.0015702102444,
111320.7020616939,
1704480524535203,
-10338987376042340,
26112667856603880,
-35149669176653700,
26595700718403920,
-10725012454188240,
1800819912950474,
82.5
],
[
8277824516172526e-19,
111320.7020463578,
// eslint-disable-next-line no-loss-of-precision
// eslint-disable-next-line @typescript-eslint/no-loss-of-precision
6477955746671607e-7,
-4082003173641316e-6,
1077490566351142e-5,
-1517187553151559e-5,
1205306533862167e-5,
-5124939663577472e-6,
9133119359512032e-7,
67.5
],
[
0.00337398766765,
111320.7020202162,
4481351045890365e-9,
-2339375119931662e-8,
7968221547186455e-8,
-1159649932797253e-7,
9723671115602145e-8,
-4366194633752821e-8,
8477230501135234e-9,
52.5
],
[
0.00220636496208,
111320.7020209128,
51751.86112841131,
3796837749470245e-9,
992013.7397791013,
-122195221711287e-8,
1340652697009075e-9,
-620943.6990984312,
144416.9293806241,
37.5
],
[
-3441963504368392e-19,
111320.7020576856,
278.2353980772752,
2485758690035394e-9,
6070.750963243378,
54821.18345352118,
9540.606633304236,
-2710.55326746645,
1405.483844121726,
22.5
],
[
-3218135878613132e-19,
111320.7020701615,
0.00369383431289,
823725.6402795718,
0.46104986909093,
2351.343141331292,
1.58060784298199,
8.77738589078284,
0.37238884252424,
7.45
]
];
/**
* 根据平面直角坐标计算两点间距离;
* @param {Point} point1 平面直角点坐标1
* @param {Point} point2 平面直角点坐标2;
* @return {Number} 返回两点间的距离
*/
_BaiduMapMercatorProjection.getDistanceByMC = function(point1, point2) {
if (!point1 || !point2)
return 0;
point1 = _BaiduMapMercatorProjection.convertMC2LL(point1);
if (!point1)
return 0;
const x1 = _BaiduMapMercatorProjection.toRadians(point1.lng);
const y1 = _BaiduMapMercatorProjection.toRadians(point1.lat);
point2 = _BaiduMapMercatorProjection.convertMC2LL(point2);
if (!point2)
return 0;
const x2 = _BaiduMapMercatorProjection.toRadians(point2.lng);
const y2 = _BaiduMapMercatorProjection.toRadians(point2.lat);
return _BaiduMapMercatorProjection.getDistance(x1, x2, y1, y2);
};
/**
* 根据经纬度坐标计算两点间距离;
* @param {Point} point1 经纬度点坐标1
* @param {Point} point2 经纬度点坐标2;
* @return {Number} 返回两点间的距离
*/
_BaiduMapMercatorProjection.getDistanceByLL = function(point1, point2) {
if (!point1 || !point2)
return 0;
point1.lng = _BaiduMapMercatorProjection.getLoop(point1.lng, -180, 180);
point1.lat = _BaiduMapMercatorProjection.getRange(point1.lat, -74, 74);
point2.lng = _BaiduMapMercatorProjection.getLoop(point2.lng, -180, 180);
point2.lat = _BaiduMapMercatorProjection.getRange(point2.lat, -74, 74);
const x1 = _BaiduMapMercatorProjection.toRadians(point1.lng);
const y1 = _BaiduMapMercatorProjection.toRadians(point1.lat);
const x2 = _BaiduMapMercatorProjection.toRadians(point2.lng);
const y2 = _BaiduMapMercatorProjection.toRadians(point2.lat);
return _BaiduMapMercatorProjection.getDistance(x1, x2, y1, y2);
};
/**
* 平面直角坐标转换成经纬度坐标;
* @param {Point} point 平面直角坐标
* @return {Point} 返回经纬度坐标
*/
_BaiduMapMercatorProjection.convertMC2LL = function(point) {
let factor;
const temp = new Point(Math.abs(point.lng), Math.abs(point.lat));
for (let i = 0; i < _BaiduMapMercatorProjection.MCBAND.length; i++) {
if (temp.lat >= _BaiduMapMercatorProjection.MCBAND[i]) {
factor = _BaiduMapMercatorProjection.MC2LL[i];
break;
}
}
const lnglat = _BaiduMapMercatorProjection.convertor(point, factor);
return new Point(lnglat == null ? void 0 : lnglat.lng.toFixed(6), lnglat == null ? void 0 : lnglat.lat.toFixed(6));
};
/**
* 经纬度坐标转换成平面直角坐标;
* @param {Point} point 经纬度坐标
* @return {Point} 返回平面直角坐标
*/
_BaiduMapMercatorProjection.convertLL2MC = function(point) {
let factor;
point.lng = _BaiduMapMercatorProjection.getLoop(point.lng, -180, 180);
point.lat = _BaiduMapMercatorProjection.getRange(point.lat, -74, 74);
const temp = new Point(point.lng, point.lat);
for (let i = 0; i < _BaiduMapMercatorProjection.LLBAND.length; i++) {
if (temp.lat >= _BaiduMapMercatorProjection.LLBAND[i]) {
factor = _BaiduMapMercatorProjection.LL2MC[i];
break;
}
}
if (!factor) {
for (let i = _BaiduMapMercatorProjection.LLBAND.length - 1; i >= 0; i--) {
if (temp.lat <= -_BaiduMapMercatorProjection.LLBAND[i]) {
factor = _BaiduMapMercatorProjection.LL2MC[i];
break;
}
}
}
const mc = _BaiduMapMercatorProjection.convertor(point, factor);
return new Point(mc == null ? void 0 : mc.lng.toFixed(2), mc == null ? void 0 : mc.lat.toFixed(2));
};
_BaiduMapMercatorProjection.convertor = function(fromPoint, factor) {
if (!fromPoint || !factor) {
return;
}
let x = factor[0] + factor[1] * Math.abs(fromPoint.lng);
const temp = Math.abs(fromPoint.lat) / factor[9];
let y = factor[2] + factor[3] * temp + factor[4] * temp * temp + factor[5] * temp * temp * temp + factor[6] * temp * temp * temp * temp + factor[7] * temp * temp * temp * temp * temp + factor[8] * temp * temp * temp * temp * temp * temp;
x *= fromPoint.lng < 0 ? -1 : 1;
y *= fromPoint.lat < 0 ? -1 : 1;
return new Point(x, y);
};
_BaiduMapMercatorProjection.getDistance = function(x1, x2, y1, y2) {
return _BaiduMapMercatorProjection.EARTHRADIUS * Math.acos(Math.sin(y1) * Math.sin(y2) + Math.cos(y1) * Math.cos(y2) * Math.cos(x2 - x1));
};
_BaiduMapMercatorProjection.toRadians = function(angdeg) {
return Math.PI * angdeg / 180;
};
_BaiduMapMercatorProjection.toDegrees = function(angrad) {
return 180 * angrad / Math.PI;
};
_BaiduMapMercatorProjection.getRange = function(v, a, b) {
if (a != null) {
v = Math.max(v, a);
}
if (b != null) {
v = Math.min(v, b);
}
return v;
};
_BaiduMapMercatorProjection.getLoop = function(v, a, b) {
while (v > b) {
v -= b - a;
}
while (v < a) {
v += b - a;
}
return v;
};
let BaiduMapMercatorProjection = _BaiduMapMercatorProjection;
class BaiduMapMercatorTilingScheme {
constructor(options) {
const { defaultValue, Ellipsoid, WebMercatorProjection, Cartesian2, Cartographic, Math: CesiumMath, Rectangle } = Cesium;
options = options || {};
this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
this._projection = new WebMercatorProjection(this._ellipsoid);
const projection = new BaiduMapMercatorProjection();
this._projection.project = function(cartographic, result) {
result = result || {};
if (options.projectionTransforms && options.projectionTransforms.from !== options.projectionTransforms.to) {
if (options.projectionTransforms.to.toUpperCase() === "WGS84") {
result = wgs84togcj02(CesiumMath.toDegrees(cartographic.longitude), CesiumMath.toDegrees(cartographic.latitude));
result = gcj02tobd09(result[0], result[1]);
} else {
result = gcj02tobd09(CesiumMath.toDegrees(cartographic.longitude), CesiumMath.toDegrees(cartographic.latitude));
}
}
result[0] = Math.min(result[0], 180);
result[0] = Math.max(result[0], -180);
result[1] = Math.min(result[1], 74.000022);
result[1] = Math.max(result[1], -71.988531);
result = projection.lngLatToPoint(new Point(result[0], result[1]));
return new Cartesian2(result.x, result.y);
};
this._projection.unproject = function(cartographic, result) {
result = result || {};
result = projection.mercatorToLngLat(new Point(cartographic.x, cartographic.y));
result[0] = (result[0] + 180) % 360 - 180;
if (options.projectionTransforms && options.projectionTransforms.from !== options.projectionTransforms.to) {
if (options.projectionTransforms.to.toUpperCase() === "WGS84") {
result = bd09togcj02(result.lng, result.lat);
result = gcj02towgs84(result[0], result[1]);
} else {
result = bd09togcj02(result.lng, result.lat);
}
}
return new Cartographic(Cesium.Math.toRadians(result[0]), Cesium.Math.toRadians(result[1]));
};
this._rectangleSouthwestInMeters = new Cartesian2(-2003772637e-2, -1247410417e-2);
this._rectangleNortheastInMeters = new Cartesian2(2003772637e-2, 1247410417e-2);
const rectangleSouthwestInMeters = this._projection.unproject(this._rectangleSouthwestInMeters);
const rectangleNortheastInMeters = this._projection.unproject(this._rectangleNortheastInMeters);
this._rectangle = new Rectangle(
rectangleSouthwestInMeters.longitude,
rectangleSouthwestInMeters.latitude,
rectangleNortheastInMeters.longitude,
rectangleNortheastInMeters.latitude
);
this.resolutions = [];
for (let i = 0; i < 19; i++) {
this.resolutions[i] = 256 * Math.pow(2, 18 - i);
}
}
getNumberOfXTilesAtLevel(level) {
return 1 << level;
}
getNumberOfYTilesAtLevel(level) {
return 1 << level;
}
rectangleToNativeRectangle(rectangle, result) {
const { defined, Rectangle } = Cesium;
const projection = this._projection;
const southwest = projection.project(Rectangle.southwest(rectangle));
const northeast = projection.project(Rectangle.northeast(rectangle));
if (!defined(result)) {
return new Rectangle(southwest.x, southwest.y, northeast.x, northeast.y);
}
result.west = southwest.x;
result.south = southwest.y;
result.east = northeast.x;
result.north = northeast.y;
return result;
}
tileXYToNativeRectangle(x, y, level, result) {
const { defined, Rectangle } = Cesium;
const tileWidth = this.resolutions[level];
const west = x * tileWidth;
const east = (x + 1) * tileWidth;
const north = ((y = -y) + 1) * tileWidth;
const south = y * tileWidth;
if (!defined(result)) {
return new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
}
tileXYToRectangle(x, y, level, result) {
const { Cartesian2 } = Cesium;
const nativeRectangle = this.tileXYToNativeRectangle(x, y, level, result);
const projection = this._projection;
const southwest = projection.unproject(new Cartesian2(nativeRectangle.west, nativeRectangle.south));
const northeast = projection.unproject(new Cartesian2(nativeRectangle.east, nativeRectangle.north));
nativeRectangle.west = southwest.longitude;
nativeRectangle.south = southwest.latitude;
nativeRectangle.east = northeast.longitude;
nativeRectangle.north = northeast.latitude;
return nativeRectangle;
}
positionToTileXY(position, level, result) {
const { Rectangle, defined, Cartesian2 } = Cesium;
const rectangle = this._rectangle;
if (!Rectangle.contains(rectangle, position)) {
return void 0;
}
const projection = this._projection;
const webMercatorPosition = projection.project(position);
if (!defined(webMercatorPosition)) {
return void 0;
}
const tileWidth = this.resolutions[level];
const xTileCoordinate = Math.floor(webMercatorPosition.x / tileWidth);
const yTileCoordinate = -Math.floor(webMercatorPosition.y / tileWidth);
if (!defined(result)) {
return new Cartesian2(xTileCoordinate, yTileCoordinate);
}
result.x = xTileCoordinate;
result.y = yTileCoordinate;
return result;
}
get ellipsoid() {
return this._ellipsoid;
}
get rectangle() {
return this._rectangle;
}
get projection() {
return this._projection;
}
}
class BaiduMapImageryProvider {
constructor(options) {
const { Resource, defaultValue, Credit, Event } = Cesium;
this._subdomains = defaultValue(options.subdomains, ["0", "1", "2", "3"]);
if (options.url) {
this._url = options.url;
} else {
if (options.mapStyle === "img") {
this._url = `//maponline{s}.bdimg.com/starpic/u=x={x};y={y};z={z};v=009;type=sate&qt=satepc&app=webearth2&udt={udt}&fm=46&v=009`;
} else if (options.mapStyle === "vec") {
this._url = `//maponline{s}.bdimg.com/tile/?qt={qt}&x={x}&y={y}&z={z}&styles={styles}&scaler={scale}&udt={udt}&from=jsapi2_0&showtext={showtext}`;
} else if (options.mapStyle === "traffic") {
this._url = `https://its.map.baidu.com/traffic/TrafficTileService?time={time}&label={labelStyle}&v=016&level={z}&x={x}&y={y}&scaler={scale}`;
} else {
this._url = `//api.map.baidu.com/customimage/tile?&x={x}&y={y}&z={z}&udt={udt}&scale={scale}&ak={ak}&customid={mapStyle}`;
}
}
const resource = Resource.createIfNeeded(this._url);
resource.appendForwardSlash();
this._ready = false;
this._resource = resource;
this._tileDiscardPolicy = options.tileDiscardPolicy;
this._tileWidth = 256;
this._tileHeight = 256;
this._minimumLevel = options.minimumLevel || 0;
this._maximumLevel = options.maximumLevel || 18;
this._tilingScheme = new BaiduMapMercatorTilingScheme(options);
this._rectangle = defaultValue(options.rectangle, this._tilingScheme.rectangle);
let credit = options.credit;
if (typeof credit === "string") {
credit = new Credit(credit);
}
this._credit = credit;
this.enablePickFeatures = defaultValue(options.enablePickFeatures, false);
this._hasAlphaChannel = defaultValue(options.hasAlphaChannel, true);
this._errorEvent = new Event();
this._ready = true;
this._labelStyle = options.labelStyle || "web2D";
this._showtext = options.showtext || "1";
this._qt = options.qt;
this._styles = options.styles;
this._scale = options.scale;
this._ak = options.ak;
this._mapStyle = options.mapStyle;
}
get url() {
return this._resource.url;
}
get proxy() {
return this._resource.proxy;
}
get tileWidth() {
if (!this._ready) {
throw new Cesium.DeveloperError("tileWidth must not be called before the imagery provider is ready.");
}
return this._tileWidth;
}
get tileHeight() {
if (!this._ready) {
throw new Cesium.DeveloperError("tileHeight must not be called before the imagery provider is ready.");
}
return this._tileHeight;
}
get maximumLevel() {
if (!this._ready) {
throw new Cesium.DeveloperError("maximumLevel must not be called before the imagery provider is ready.");
}
return this._maximumLevel;
}
get minimumLevel() {
if (!this.ready) {
throw new Cesium.DeveloperError("minimumLevel must not be called before the imagery provider is ready.");
}
return this._minimumLevel;
}
get tilingScheme() {
if (!this._ready) {
throw new Cesium.DeveloperError("tilingScheme must not be called before the imagery provider is ready.");
}
return this._tilingScheme;
}
get rectangle() {
if (!this.ready) {
throw new Cesium.DeveloperError("rectangle must not be called before the imagery provider is ready.");
}
return this._rectangle;
}
get tileDiscardPolicy() {
if (!this.ready) {
throw new Cesium.DeveloperError("tileDiscardPolicy must not be called before the imagery provider is ready.");
}
return this._tileDiscardPolicy;
}
get errorEvent() {
return this._errorEvent;
}
get ready() {
return this._ready;
}
// get readyPromise() {
// return this._readyPromise.promise
// }
get credit() {
if (!this.ready) {
throw new Cesium.DeveloperError("credit must not be called before the imagery provider is ready.");
}
return this._credit;
}
get hasAlphaChannel() {
if (!this.ready) {
throw new Cesium.DeveloperError("hasAlphaChannel must not be called before the imagery provider is ready.");
}
return this._hasAlphaChannel;
}
getTileCredits(x, y, level) {
if (!this.ready) {
throw new Cesium.DeveloperError("getTileCredits must not be called before the imagery provider is ready.");
}
return void 0;
}
requestImage(x, y, level, request) {
if (!this.ready) {
throw new Cesium.DeveloperError("requestImage must not be called before the imagery provider is ready.");
}
return Cesium.ImageryProvider.loadImage(this, buildImageResource$3.call(this, x, y, level, request));
}
pickFeatures(x, y, level, longitude, latitude) {
return void 0;
}
}
function buildImageResource$3(x, y, level, request) {
let url = this._url;
const subdomains = this._subdomains;
url = url.replace("{s}", subdomains[(x + y + level) % subdomains.length]).replace("{qt}", this._qt).replace("{x}", x).replace("{y}", -y).replace("{z}", level).replace("{styles}", this._styles).replace("{scale}", this._scale).replace("{mapStyle}", this._mapStyle).replace("{labelStyle}", this._labelStyle).replace("{ak}", this._ak).replace("{time}", String((/* @__PURE__ */ new Date()).getTime())).replace("{udt}", String((/* @__PURE__ */ new Date()).getTime())).replace("{showtext}", this._showtext);
const resource = this._resource.getDerivedResource({
url,
request
});
return resource;
}
const baiduImageryProviderProps = exports('baiduImageryProviderProps', {
...url,
...rectangle,
...ellipsoid,
...tileDiscardPolicy,
...credit,
...minimumLevel,
...maximumLevel,
projectionTransforms: {
type: [Boolean, Object],
default: () => {
return {
from: "BD09",
to: "WGS84"
};
}
},
scale: {
type: String,
default: "2"
},
ak: {
type: String,
default: "5ieMMexWmzB9jivTq6oCRX9j"
},
subdomains: {
type: Array,
default: () => ["0", "1", "2", "3"]
},
// https://lbsyun.baidu.com/custom/list.htm
mapStyle: {
type: String,
default: "vec"
// img vec traffic normal light dark redalert googlelite grassgreen midnight pink darkgreen bluish grayscale hardedge
},
qt: {
type: String,
default: "vtile"
},
styles: {
type: String,
// sl 背景透明 pl 正常 ph 大字体
default: "pl"
},
showtext: {
type: String,
// 0 不显示, 1 显示
default: "1"
}
});
var ImageryProviderBaidu = defineComponent({
name: "VcImageryProviderBaidu",
props: baiduImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "BaiduMapImageryProvider";
const providersState = useProviders(props, ctx, instance);
if (void 0 === providersState) {
return;
}
instance.createCesiumObject = async () => {
Cesium.BaiduMapImageryProvider = Cesium.BaiduMapImageryProvider || BaiduMapImageryProvider;
if (providersState.unwatchFns.length === 0) {
providersState.setPropsWatcher(true);
}
const options = providersState.transformProps(props);
return new Cesium.BaiduMapImageryProvider(options);
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const bingImageryProviderProps = exports('bingImageryProviderProps', {
url: {
type: [String, Object],
default: "https://dev.virtualearth.net"
},
bmKey: String,
tileProtocol: String,
mapStyle: {
type: String,
default: "Aerial"
},
culture: {
type: String,
default: ""
},
...ellipsoid,
...tileDiscardPolicy
});
var ImageryProviderBing = defineComponent({
name: "VcImageryProviderBing",
props: bingImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "BingMapsImageryProvider";
useProviders(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const googleImageryProviderProps = exports('googleImageryProviderProps', {
...url,
...ellipsoid,
...tileDiscardPolicy,
...credit,
metadata: Object
});
var ImageryProviderGoogle = defineComponent({
name: "VcImageryProviderGoogle",
props: googleImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "GoogleEarthEnterpriseImageryProvider";
useProviders(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const gridImageryProviderProps = exports('gridImageryProviderProps', {
...tilingScheme,
...ellipsoid,
cells: {
type: Number,
default: 8
},
color: {
type: [String, Object, Array],
default: () => [1, 1, 1, 0.4],
watcherOptions: {
cesiumObjectBuilder: makeColor
}
},
...glowColor,
glowWidth: {
type: Number,
default: 6
},
backgroundColor: {
type: [String, Array, Object],
default: () => [0, 0.5, 0, 0.2],
watcherOptions: {
cesiumObjectBuilder: makeColor
}
},
...tileWidth,
...tileHeight,
canvasSize: {
type: Number,
default: 256
}
});
var ImageryProviderGrid = defineComponent({
name: "VcImageryProviderGrid",
props: gridImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "GridImageryProvider";
useProviders(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const ionImageryProviderProps = exports('ionImageryProviderProps', {});
var ImageryProviderIon = defineComponent({
name: "VcImageryProviderIon",
props: {
assetId: Number,
...accessToken,
server: [String, Object]
},
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "IonImageryProvider";
const providersState = useProviders(props, ctx, instance);
if (void 0 === providersState) {
return;
}
instance.createCesiumObject = async () => {
const options = providersState.transformProps(props);
if (compareCesiumVersion(Cesium.VERSION, "1.104") && typeof Cesium[instance.cesiumClass].fromAssetId === "function") {
return await Cesium.IonImageryProvider.fromAssetId(options.assetId, options);
} else {
return new Cesium.IonImageryProvider(options);
}
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const mapboxImageryProviderProps = exports('mapboxImageryProviderProps', {
url: {
type: [String, Object],
default: "https://api.mapbox.com/styles/v1/"
},
username: {
type: String,
default: "mapbox"
},
styleId: String,
...accessToken,
tilesize: {
type: Number,
default: 512
},
scaleFactor: Boolean,
...ellipsoid,
...minimumLevel,
...maximumLevel,
...rectangle,
...credit
});
var ImageryProviderMapbox = defineComponent({
name: "VcImageryProviderMapbox",
props: mapboxImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "MapboxStyleImageryProvider";
useProviders(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const osmImageryProviderProps = exports('osmImageryProviderProps', {
url: {
type: String,
default: "https://a.tile.openstreetmap.org"
},
...fileExtension,
...rectangle,
...minimumLevel,
...maximumLevel,
...ellipsoid,
credit: {
type: [String, Object],
default: "MapQuest, Open Street Map and contributors, CC-BY-SA"
}
});
var ImageryProviderOsm = defineComponent({
name: "VcImageryProviderOsm",
props: osmImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "OpenStreetMapImageryProvider";
useProviders(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const singletileImageryProviderProps = exports('singletileImageryProviderProps', {
...url,
...rectangle,
...credit,
...ellipsoid,
...tileWidth,
...tileHeight
});
var ImageryProviderSingletile = defineComponent({
name: "VcImageryProviderSingletile",
props: singletileImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "SingleTileImageryProvider";
useProviders(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const Status = {
NONE: 0,
STORING: 1,
STORED: 2,
FAILED: 3
};
class IndexedDBScheduler {
/**
*
* @param {Object} options
*/
constructor(options) {
if (!Cesium.defined(options.name)) {
throw new Cesium.DeveloperError("options.name is required.");
}
const dbRequest = window.indexedDB.open(this.dbname);
this.layer = options.layer || null;
this.storageType = options.storageType || "arrayBuffer";
this.creatingTable = false;
this.cachestatus = {};
this.dbname = options.name;
const that = this;
return new Promise((resolve, reject) => {
dbRequest.onsuccess = (event) => {
that.db = event.target.result;
that.version = that.db.version;
that.cachestatus = that.cachestatus || {};
resolve(that);
};
dbRequest.onupgradeneeded = (event) => {
that.db = event.target.result;
that.version = that.db.version;
resolve(that);
};
dbRequest.onerror = (event) => {
that.db = null;
reject("create database fail, error code : " + event.target.errorcode);
};
});
}
/**
* 检查对象仓库是否存在。
* @param {String} storeName 对象仓库(表)名称
*/
checkObjectStoreExist(storeName) {
return Cesium.defined(this.db) ? this.db.objectStoreNames.contains(storeName) : false;
}
/**
* 创建 IndexedDB 浏对象仓库,IndexedDB 是浏览器提供的本地数据库
* @param {String} storeName 对象仓库(表)名称
* @returns {Promise}
*/
createObjectStore(storeName) {
return new Promise((resolve, reject) => {
if (this.creatingTable) {
reject(false);
} else {
if (this.db.objectStoreNames.contains(storeName)) {
reject(false);
return;
}
this.creatingTable = true;
const version = parseInt(this.db.version);
this.db.close();
const that = this;
const dbRequest = window.indexedDB.open(this.dbname, version + 1);
dbRequest.onupgradeneeded = (event) => {
const db = event.target.result;
that.db = db;
const objectStore = db.createObjectStore(storeName, {
keyPath: "id"
});
if (Cesium.defined(objectStore)) {
objectStore.createIndex("value", "value", {
unique: false
});
that.creatingTable = false;
that.cachestatus = that.cachestatus || {};
that.cachestatus[storeName] = {};
that.db.close();
const dbRequest2 = window.indexedDB.open(that.dbname);
dbRequest2.onsuccess = (event2) => {
that.db = event2.target.result;
resolve(true);
};
} else {
that.creatingTable = false;
resolve(false);
}
};
dbRequest.onsuccess = (event) => {
event.target.result.close();
resolve(true);
};
dbRequest.onerror = (event) => {
that.creatingTable = false;
reject(false);
};
}
});
}
/**
* 向对象仓库写入数据记录。
* @param {String} storeName 对象仓库(表)名称
* @param {Number} id 主键
* @param {*} value 值
* @returns {Promise}
*/
putElementInDB(storeName, id, value) {
return new Promise((resolve, reject) => {
if (!Cesium.defined(this.db)) {
reject(false);
return;
}
const { cachestatus, db } = this;
if (Cesium.defined(cachestatus[storeName]) && Cesium.defined(cachestatus[storeName][id] && (cachestatus[storeName][id] === Status.STORING || cachestatus[storeName][id] === Status.STORED))) {
resolve(false);
return;
}
if (db.objectStoreNames.contains(storeName)) {
cachestatus[storeName] = cachestatus[storeName] || {};
try {
const request = db.transaction([storeName], "readwrite").objectStore(storeName).add({
id,
value
});
cachestatus[storeName][id] = Status.STORING;
request.onsuccess = (event) => {
cachestatus[storeName][id] = Status.STORED;
resolve(true);
};
request.onerror = (event) => {
cachestatus[storeName][id] = Status.FAILED;
resolve(false);
};
} catch (error) {
reject(null);
return;
}
} else {
this.createObjectStore(storeName).then(
() => {
const request = db.transaction([storeName], "readwrite").objectStore(storeName).add({
id,
value
});
request.onsuccess = function(e) {
resolve(true);
};
request.onerror = function(e) {
reject(false);
};
},
() => {
reject(false);
}
);
}
});
}
/**
* 向对象仓库读取数据。
* @param {String} storeName 对象仓库(表)名称
* @param {Number} id 主键
* @returns {Promise}
*/
getElementFromDB(storeName, id) {
return new Promise((resolve, reject) => {
const { db } = this;
if (!Cesium.defined(db)) {
return null;
}
if (!db.objectStoreNames.contains(storeName)) {
return null;
}
try {
const transaction = db.transaction([storeName]);
const objectStore = transaction.objectStore(storeName);
const request = objectStore.get(id);
request.onsuccess = (e) => {
return Cesium.defined(e.target.result) ? resolve(e.target.result.value) : reject(null);
};
request.onerror = (e) => {
reject(null);
};
} catch (error) {
reject(null);
}
});
}
/**
* 更新数据。
* @param {String} storeName
* @param {Number} id
* @param {*} value
* @returns {Promise}
*/
updateElementInDB(storeName, id, value) {
return new Promise((resolve, reject) => {
const { db } = this;
if (!Cesium.defined(db)) {
resolve(false);
return;
}
if (!db.objectStoreNames.contains(storeName)) {
resolve(false);
return;
}
try {
const request = db.transaction([storeName], "readwrite").objectStore(storeName).put({ id, value });
request.onsuccess = () => {
resolve(true);
};
request.onerror = () => {
resolve(false);
};
} catch (e) {
resolve(false);
}
});
}
/**
* 移除数据。
* @param {String} storeName
* @param {Number} id
* @returns {Promise}
*/
removeElementFromDB(storeName, id) {
return new Promise((resolve, reject) => {
const { db } = this;
if (!Cesium.defined(db)) {
resolve(false);
return;
}
if (!db.objectStoreNames.contains(storeName)) {
resolve(false);
return;
}
try {
const request = db.transaction([storeName], "readwrite").objectStore(storeName).delete(id);
request.onsuccess = () => {
resolve(true);
};
request.onerror = () => {
resolve(false);
};
} catch (e) {
resolve(false);
}
});
}
/**
* 清空对象仓库
* @param {String} storeName
*/
clear(storeName) {
return new Promise((resolve, reject) => {
const { db } = this;
if (!Cesium.defined(db)) {
resolve(false);
return;
}
if (!db.objectStoreNames.contains(storeName)) {
resolve(false);
return;
}
try {
const request = db.transaction([storeName], "readwrite").objectStore(storeName).clear();
request.onsuccess = () => {
resolve(true);
};
request.onerror = () => {
resolve(false);
};
} catch (e) {
resolve(false);
}
});
}
}
class SuperMapImageryProvider {
constructor(options) {
const { appendForwardSlash, Credit, defaultValue, defined, DeveloperError, Event, Resource, Math: Math2 } = Cesium;
options = defaultValue(options, {});
const { url } = options;
if (!defined(url)) {
throw new DeveloperError("options.url is required.");
}
const rootNodeUrlRealspace3D = url.substring(0, url.indexOf("datas"));
this.tablename = url.substring(0, url.indexOf("datas/") + 6, url.length);
const that = this;
const dbPromise = new IndexedDBScheduler({
name: rootNodeUrlRealspace3D + this.tablename
});
dbPromise.then((e) => {
that._indexedDBScheduler = e;
});
this._indexedDBSetting = {
isOpen: false,
clear: () => {
that._indexedDBScheduler.clear(that.tablename);
}
};
this.isSci = false;
this.isTileMap = false;
const forwardSlashUrl = appendForwardSlash(url);
if (forwardSlashUrl.indexOf("rest/maps") > -1) {
this.isTileMap = true;
this.layersID = options.layersID;
} else {
if (!(forwardSlashUrl.indexOf("rest/realspace") > -1)) {
throw new DeveloperError("The url type is not supported!");
}
this.isSci = true;
this.layersID = void 0;
}
this._url = forwardSlashUrl;
this._resource = Resource.createIfNeeded(forwardSlashUrl);
this._transparent = defaultValue(options.transparent, true);
this._name = options.name || "";
this._urlTemplate = void 0;
this._errorEvent = new Event();
this._fileExtension = "png";
this._tileWidth = 256;
this._tileHeight = 256;
this._minimumLevel = defaultValue(options.minimumLevel, 0);
this._maximumLevel = options.maximumLevel;
this._rectangle = void 0;
this._tilingScheme = void 0;
this._tileDiscardPolicy = options.tileDiscardPolicy;
this._fRatio = defaultValue(options.ratio, Math2.DEGREES_PER_RADIAN / 6378137);
this._scales = [];
this._coordUnit = "DEGREE";
let credit = defaultValue(options.credit, new Credit("MapQuest, SuperMap iServer Imagery"));
if (typeof credit === "string") {
credit = new Credit(credit);
}
this._credit = credit;
this._ready = false;
this._readyPromise = defer();
this._options = options;
}
get url() {
return this._url;
}
get name() {
return this._name;
}
set name(val) {
this._name = val;
}
get tileWidth() {
if (!this._ready) {
throw new Cesium.DeveloperError("tileWidth must not be called before the imagery provider is ready.");
}
return this._tileWidth;
}
get tileHeight() {
if (!this._ready) {
throw new Cesium.DeveloperError("tileHeight must not be called before the imagery provider is ready.");
}
return this._tileHeight;
}
get maximumLevel() {
if (!this._ready) {
throw new Cesium.DeveloperError("maximumLevel must not be called before the imagery provider is ready.");
}
return this._maximumLevel;
}
get minimumLevel() {
if (!this._ready) {
throw new Cesium.DeveloperError("minimumLevel must not be called before the imagery provider is ready.");
}
return this._minimumLevel;
}
get tilingScheme() {
if (!this._ready) {
throw new Cesium.DeveloperError("tilingScheme must not be called before the imagery provider is ready.");
}
return this._tilingScheme;
}
get rectangle() {
if (!this._ready) {
throw new Cesium.DeveloperError("rectangle must not be called before the imagery provider is ready.");
}
return this._rectangle;
}
get errorEvent() {
return this._errorEvent;
}
get ready() {
return this._ready;
}
get credit() {
return this._credit;
}
get hasAlphaChannel() {
return true;
}
get readyPromise() {
return this._readyPromise.promise;
}
get ratio() {
return this._fRatio;
}
set ratio(val) {
this._fRatio = val;
}
get tileDiscardPolicy() {
return this._tileDiscardPolicy;
}
getTileCredits(x, y, level) {
if (!this.ready) {
throw new Cesium.DeveloperError("getTileCredits must not be called before the imagery provider is ready.");
}
return void 0;
}
requestImage(x, y, level, request) {
const { defined, DeveloperError, ImageryProvider } = Cesium;
if (!this.ready) {
throw new DeveloperError("requestImage must not be called before the imagery provider is ready.");
}
const url = buildImageResource$2.call(this, x, y, level);
const resource = this._resource.getDerivedResource({
url,
request
});
const that = this;
if (this._indexedDBSetting.isOpen) {
if (defined(this._indexedDBScheduler)) {
const promise = this._indexedDBScheduler.getElementFromDB(this.tablename, url);
try {
return promise.then((value) => {
if (defined(value)) {
const image = new Image();
image.src = value;
return image;
}
return ImageryProvider.loadImage(that, resource);
});
} catch (e) {
return ImageryProvider.loadImage(that, resource);
}
}
} else {
return ImageryProvider.loadImage(this, resource);
}
}
pickFeatures(x, y, level, longitude, latitude) {
return void 0;
}
async init() {
await init.call(this);
}
}
let previousError = {};
const ScaleTexts = [
"1.690163571602655E-9",
"3.3803271432053056E-9",
"6.760654286410611E-9",
"1.3521308572821242E-8",
"2.7042617145642484E-8",
"5.408523429128511E-8",
"1.0817046858256998E-7",
"2.1634093716513974E-7",
"4.3268187433028044E-7",
"8.653637486605571E-7",
"1.7307274973211203E-6",
"3.4614549946422405E-6",
"6.9229099892844565E-6",
"1.3845819978568952E-5",
"2.7691639957137904E-5",
"5.53832799142758E-5",
"1.107665598285516E-4",
"2.215331196571032E-4",
"4.430662393142064E-4",
"8.861324786284128E-4",
"1.772264957256826E-3",
"3.544529914513652E-3"
];
const Scales = [
1690163571602655e-24,
33803271432053056e-25,
6760654286410611e-24,
13521308572821242e-24,
27042617145642484e-24,
5408523429128511e-23,
10817046858256998e-23,
21634093716513974e-23,
43268187433028044e-23,
8653637486605571e-22,
17307274973211203e-22,
34614549946422405e-22,
69229099892844565e-22,
13845819978568952e-21,
27691639957137904e-21,
553832799142758e-19,
1107665598285516e-19,
2215331196571032e-19,
4430662393142064e-19,
8861324786284128e-19,
0.001772264957256826,
0.003544529914513652
];
function buildImageResource$2(x, y, level) {
let url;
if (this.isTileMap) {
if (this._coordUnit === "DEGREE") {
const scaleText = ScaleTexts[level + 1] || ScaleTexts[level];
url = this._urlTemplate.replace("{x}", x).replace("{y}", y).replace("{scale}", scaleText);
} else if (this._coordUnit === "METER") {
const scaleText = ScaleTexts[level];
url = this._urlTemplate.replace("{x}", x).replace("{y}", y).replace("{scale}", scaleText);
}
} else {
url = this._urlTemplate.replace("{x}", x).replace("{y}", y).replace("{level}", level).replace("{fileExtension}", this._fileExtension);
}
return url;
}
async function init() {
const { Resource } = Cesium;
if (this.isTileMap) {
const promise = Resource.fetchJsonp({
url: this._options.url + ".jsonp",
queryParameters: {
f: "json"
}
});
try {
promise.then((e) => {
onFulfilledTileMap.call(this, e);
});
} catch (e) {
onRejected.call(this);
}
} else {
try {
const e = await Resource.fetchText({
url: this.url + "config"
});
onFulfilledRest3D.call(this, e);
} catch (e) {
onRejected.call(this);
}
}
}
function getMaximumLevelbyScale(scale) {
for (let t = Scales.length; t--; ) {
if (scale[t] <= scale) {
return t;
}
}
}
function onFulfilledRest3D(xmlText) {
const options = parseConfigFromXmlText.call(this, xmlText);
const { defaultValue, defined, GeographicTilingScheme, Math: Math2, Rectangle } = Cesium;
this._fileExtension = defaultValue(options.fileExtentName, "png");
this._tileWidth = defaultValue(options.imageSizeWidth, 256);
this._tileHeight = defaultValue(options.imageSizeHeight, 256);
const levels = options.levels;
const length = levels.length;
this._minimumLevel = defaultValue(levels[0], 0);
this._maximumLevel = defaultValue(levels[length - 1], length - 1);
if (!defined(this._tilingScheme)) {
this._tilingScheme = new GeographicTilingScheme({
ellipsoid: this._options.ellipsoid
});
}
if (!defined(this._rectangle)) {
if (options.left && options.right && options.top && options.bottom) {
const left = Math2.toRadians(options.left);
const right = Math2.toRadians(options.right);
const bottom = Math2.toRadians(options.bottom);
const top = Math2.toRadians(options.top);
this._rectangle = new Rectangle(left, bottom, right, top);
}
}
const tilingScheme = this._tilingScheme;
this._rectangle.west < tilingScheme.rectangle.west && (this._rectangle.west = tilingScheme.rectangle.west);
this._rectangle.east > tilingScheme.rectangle.east && (this._rectangle.east = tilingScheme.rectangle.east);
this._rectangle.south < tilingScheme.rectangle.south && (this._rectangle.south = tilingScheme.rectangle.south);
this._rectangle.north > tilingScheme.rectangle.north && (this._rectangle.north = tilingScheme.rectangle.north);
const swTile = tilingScheme.positionToTileXY(Rectangle.southwest(this._rectangle), this._minimumLevel);
const neTile = tilingScheme.positionToTileXY(Rectangle.northeast(this._rectangle), this._minimumLevel);
const tileCount = (window.Math.abs(neTile.x - swTile.x) + 1) * (window.Math.abs(neTile.y - swTile.y) + 1);
tileCount > 4 && (this._minimumLevel = 0);
this._tilingScheme = tilingScheme;
this._urlTemplate = this._url + "data/index/{y}/{x}.{fileExtension}?level={level}";
this._ready = true;
this._readyPromise.resolve(true);
}
function parseConfigFromXmlText(xmlText) {
const domParser = new DOMParser();
xmlText = domParser.parseFromString(xmlText, "application/xml");
const namespaceURI = "http://www.supermap.com/SuperMapCache/sci3d";
const rootNode = xmlText.childNodes[0];
const levelsNode = queryFirstNode(rootNode, "Levels", namespaceURI);
const levelsNodes = queryNodes(levelsNode, "Level", namespaceURI) || [];
const levels = [];
for (let i = 0; i < levelsNodes.length; i++) {
levels.push(parseInt(levelsNodes[i].textContent, 10));
}
const boundsNode = queryFirstNode(rootNode, "Bounds", namespaceURI);
const left = queryNumericAttribute(boundsNode, "Left", namespaceURI);
const right = queryNumericAttribute(boundsNode, "Right", namespaceURI);
const top = queryNumericAttribute(boundsNode, "Top", namespaceURI);
const bottom = queryNumericAttribute(boundsNode, "Bottom", namespaceURI);
const fileExtentName = queryStringValue(rootNode, "FileExtentName", namespaceURI);
const cellWidth = queryNumericAttribute(rootNode, "CellWidth", namespaceURI);
const cellHeight = queryNumericAttribute(rootNode, "CellHeight", namespaceURI);
const cacheName = queryStringValue(rootNode, "CacheName", namespaceURI);
this._name = cacheName || "";
return {
left,
right,
top,
bottom,
fileExtentName,
levels,
imageSizeWidth: cellWidth,
imageSizeHeight: cellHeight
};
}
function queryStringValue(xmlNode, attribute, namespaceURI) {
const node = queryFirstNode(xmlNode, attribute, namespaceURI);
return Cesium.defined(node) ? node.textContent.trim() : void 0;
}
function queryNumericAttribute(xmlNode, attribute, namespaceURI) {
const node = queryFirstNode(xmlNode, attribute, namespaceURI);
if (Cesium.defined(node)) {
const number = parseFloat(node.textContent);
return isNaN(number) ? void 0 : number;
}
}
function queryFirstNode(xmlNode, attribute, namespaceURI) {
if (Cesium.defined(xmlNode)) {
const nodes = xmlNode.childNodes;
const length = nodes.length;
for (let i = 0; i < length; i++) {
const node = nodes[i];
if (node.localName === attribute && namespaceURI.indexOf(node.namespaceURI) !== -1) {
return node;
}
}
}
}
function queryNodes(xmlNode, attribute, namespaceURI) {
if (Cesium.defined(xmlNode)) {
const nodes = [];
const nodeList = xmlNode.getElementsByTagNameNS("*", attribute);
const length = nodeList.length;
for (let i = 0; i < length; i++) {
const node = nodeList[i];
node.localName === attribute && namespaceURI.indexOf(node.namespaceURI) !== -1 && nodes.push(node);
}
return nodes;
}
}
function onFulfilledTileMap(response) {
const { Cartesian3, defaultValue, defined, GeographicTilingScheme, Math: CesiumMath, Rectangle, WebMercatorTilingScheme } = Cesium;
const coordUnit = response.prjCoordSys.coordUnit;
this._coordUnit = coordUnit;
const bounds = response.bounds;
const visibleScales = response.visibleScales;
if (defined(visibleScales) && visibleScales.length > 1 && defined(this._maximumLevel)) {
const lastVisibleScale = visibleScales[visibleScales.length - 1];
this._maximumLevel = getMaximumLevelbyScale(lastVisibleScale);
}
if (coordUnit === "DEGREE") {
this._tilingScheme = new GeographicTilingScheme();
bounds.left = CesiumMath.clamp(bounds.left, -180, 180);
bounds.bottom = CesiumMath.clamp(bounds.bottom, -90, 90);
bounds.right = CesiumMath.clamp(bounds.right, -180, 180);
bounds.top = CesiumMath.clamp(bounds.top, -90, 90);
this._rectangle = Rectangle.fromDegrees(bounds.left, bounds.bottom, bounds.right, bounds.top);
this._urlTemplate = this._url + 'tileImage.png?transparent={transparent}&cacheEnabled=true&width=256&height=256&x={x}&y={y}&scale={scale}&redirect=false&overlapDisplayed=false&origin={"x":-180,"y":90}';
} else {
const pointLB = new Cartesian3(bounds.left, bounds.bottom, 0);
pointLB.x = Math.max(-20037508342789244e-9, pointLB.x);
pointLB.y = Math.max(-20037508342789244e-9, pointLB.y);
const pointRT = new Cartesian3(bounds.right, bounds.top, 0);
pointRT.x = Math.min(20037508342789244e-9, pointRT.x);
pointRT.y = Math.min(20037508342789244e-9, pointRT.y);
this._tilingScheme = new WebMercatorTilingScheme();
const f = this._tilingScheme.projection.unproject(pointLB);
const p = this._tilingScheme.projection.unproject(pointRT);
this._rectangle = new Rectangle(f.longitude, f.latitude, p.longitude, p.latitude);
this._urlTemplate = this._url + 'tileImage.png?transparent={transparent}&cacheEnabled=true&width=256&height=256&x={x}&y={y}&scale={scale}&redirect=false&overlapDisplayed=false&origin={"x":-20037508.342789248 ,"y":20037508.342789095}';
}
this._urlTemplate = this._urlTemplate.replace("{transparent}", this._transparent);
this.layersID && (this._urlTemplate = this._urlTemplate + "&layersID=" + this.layersID);
this._rectangle || (this._rectangle = defaultValue(this._options.rectangle, this._tilingScheme.rectangle));
this._ready = true;
this._readyPromise.resolve(true);
}
function onRejected() {
const { TileProviderError, RuntimeError } = Cesium;
const message = "An error occurred while accessing " + this._url + ".";
previousError = TileProviderError.reportError(previousError, this, this._errorEvent, message, 0, 0, 0, new Error(message));
this._readyPromise.reject(new RuntimeError(message));
}
const supermapImageryProviderProps = exports('supermapImageryProviderProps', {
url: String,
...minimumLevel,
...maximumLevel,
name: String,
transparent: {
type: Boolean,
default: true
},
credit: {
type: [String, Object],
default: "MapQuest, SuperMap iServer Imagery"
},
...projectionTransforms
});
var ImageryProviderSupermap = defineComponent({
name: "VcImageryProviderSupermap",
props: supermapImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "SuperMapImageryProvider";
const providersState = useProviders(props, ctx, instance);
if (void 0 === providersState) {
return;
}
instance.createCesiumObject = async () => {
Cesium.SuperMapImageryProvider = Cesium.SuperMapImageryProvider || SuperMapImageryProvider;
if (providersState.unwatchFns.length === 0) {
providersState.setPropsWatcher(true);
}
const options = providersState.transformProps(props);
const provider = new Cesium.SuperMapImageryProvider(options);
if (!Cesium.SuperMapVersion) {
await provider.init();
}
return provider;
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const TILE_URL = {
img: "//p{s}.map.gtimg.com/sateTiles/{z}/{sx}/{sy}/{x}_{reverseY}.jpg&scene=0",
terrain: "//p{s}.map.gtimg.com/demTiles/{z}/{sx}/{sy}/{x}_{reverseY}.jpg&scene=0",
vector: "//rt{s}.map.gtimg.com/tile?z={z}&x={x}&y={reverseY}&type=vector&styleid={style}&scene=0"
};
class TencentImageryProvider {
constructor(options) {
const { Resource, defaultValue, Credit, Event } = Cesium;
this._subdomains = options.subdomains || ["1", "2", "3"];
this._url = options.url || [options.protocol || "", TILE_URL[options.mapStyle] || TILE_URL["vector"]].join("");
const resource = Resource.createIfNeeded(this._url);
resource.appendForwardSlash();
this._ready = false;
this._resource = resource;
this._tileDiscardPolicy = options.tileDiscardPolicy;
this._tileWidth = 256;
this._tileHeight = 256;
this._minimumLevel = options.minimumLevel || 0;
this._maximumLevel = options.maximumLevel || 20;
this._tilingScheme = new Cesium.WebMercatorTilingScheme();
this._rectangle = defaultValue(options.rectangle, this._tilingScheme.rectangle);
let credit = options.credit;
if (typeof credit === "string") {
credit = new Credit(credit);
}
this._credit = credit;
this.enablePickFeatures = defaultValue(options.enablePickFeatures, false);
this._hasAlphaChannel = defaultValue(options.hasAlphaChannel, true);
this._errorEvent = new Event();
this._readyPromise = defer();
this._ready = true;
this._readyPromise.resolve(true);
this._style = options.styleId;
}
get url() {
return this._resource._url;
}
get proxy() {
return this._resource.proxy;
}
get tileWidth() {
if (!this._ready) {
throw new Cesium.DeveloperError("tileWidth must not be called before the imagery provider is ready.");
}
return this._tileWidth;
}
get tileHeight() {
if (!this._ready) {
throw new Cesium.DeveloperError("tileHeight must not be called before the imagery provider is ready.");
}
return this._tileHeight;
}
get maximumLevel() {
if (!this._ready) {
throw new Cesium.DeveloperError("maximumLevel must not be called before the imagery provider is ready.");
}
return this._maximumLevel;
}
get minimumLevel() {
if (!this.ready) {
throw new Cesium.DeveloperError("minimumLevel must not be called before the imagery provider is ready.");
}
return this._minimumLevel;
}
get tilingScheme() {
if (!this._ready) {
throw new Cesium.DeveloperError("tilingScheme must not be called before the imagery provider is ready.");
}
return this._tilingScheme;
}
get rectangle() {
if (!this.ready) {
throw new Cesium.DeveloperError("rectangle must not be called before the imagery provider is ready.");
}
return this._rectangle;
}
get tileDiscardPolicy() {
if (!this.ready) {
throw new Cesium.DeveloperError("tileDiscardPolicy must not be called before the imagery provider is ready.");
}
return this._tileDiscardPolicy;
}
get errorEvent() {
return this._errorEvent;
}
get ready() {
return this._ready;
}
get readyPromise() {
return this._readyPromise.promise;
}
get credit() {
if (!this.ready) {
throw new Cesium.DeveloperError("credit must not be called before the imagery provider is ready.");
}
return this._credit;
}
get hasAlphaChannel() {
if (!this.ready) {
throw new Cesium.DeveloperError("hasAlphaChannel must not be called before the imagery provider is ready.");
}
return this._hasAlphaChannel;
}
getTileCredits(x, y, level) {
if (!this.ready) {
throw new Cesium.DeveloperError("getTileCredits must not be called before the imagery provider is ready.");
}
return void 0;
}
requestImage(x, y, level, request) {
if (!this.ready) {
throw new Cesium.DeveloperError("requestImage must not be called before the imagery provider is ready.");
}
return Cesium.ImageryProvider.loadImage(this, buildImageResource$1.call(this, x, y, level, request));
}
pickFeatures(x, y, level, longitude, latitude) {
return void 0;
}
}
function buildImageResource$1(x, y, level, request) {
let url = this._url;
const subdomains = this._subdomains;
const reverseY = this.tilingScheme.getNumberOfYTilesAtLevel(level) - y - 1;
url = url.replace("{s}", subdomains[(x + y + level) % subdomains.length]).replace("{style}", this._style).replace("{x}", x).replace("{y}", -y).replace("{z}", level).replace("{sx}", x >> 4).replace("{sy}", (1 << level) - y >> 4).replace("{reverseY}", reverseY);
const resource = this._resource.getDerivedResource({
url,
request
});
return resource;
}
const tencentImageryProviderProps = exports('tencentImageryProviderProps', {
...url,
subdomains: {
type: Array,
default: () => ["1", "2", "3"]
},
mapStyle: {
type: String,
default: "vector"
},
styleId: {
// 1: 经典; 2: 标签; 3: 标签; 4: 墨渊; 8: 白浅; 9: 灰色;
type: String,
default: "1"
},
protocol: String,
...credit,
...minimumLevel,
...maximumLevel,
...rectangle,
...tilingScheme,
...projectionTransforms
});
var ImageryProviderTencent = defineComponent({
name: "VcImageryProviderTencent",
props: tencentImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "TencentImageryProvider";
const providersState = useProviders(props, ctx, instance);
if (void 0 === providersState) {
return;
}
instance.createCesiumObject = async () => {
Cesium.TencentImageryProvider = Cesium.TencentImageryProvider || TencentImageryProvider;
if (providersState.unwatchFns.length === 0) {
providersState.setPropsWatcher(true);
}
const options = providersState.transformProps(props);
return new Cesium.TencentImageryProvider(options);
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const TiandituMapsStyle = {
IMG_W: "img_w",
IMG_C: "img_c",
CIA_W: "cia_w",
CIA_C: "cia_c",
VEC_W: "vec_w",
VEC_C: "vec_c",
TER_W: "ter_w",
TER_C: "ter_c",
CVA_W: "cva_w",
CVA_C: "cva_c",
CTA_W: "cta_w",
CTA_C: "cta_c",
EIA_W: "eia_w",
EIA_C: "eia_c",
EVA_W: "eva_w",
EVA_C: "eva_c",
IBO_C: "ibo_c",
IBO_W: "ibo_w"
};
var URI = {exports: {}};
var punycode = {exports: {}};
/*! https://mths.be/punycode v1.4.0 by @mathias */
punycode.exports;
var hasRequiredPunycode;
function requirePunycode () {
if (hasRequiredPunycode) return punycode.exports;
hasRequiredPunycode = 1;
(function (module, exports) {
(function(root) {
/** Detect free variables */
var freeExports = exports &&
!exports.nodeType && exports;
var freeModule = module &&
!module.nodeType && module;
var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal;
if (
freeGlobal.global === freeGlobal ||
freeGlobal.window === freeGlobal ||
freeGlobal.self === freeGlobal
) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
var result = [];
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.3.2',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (freeExports && freeModule) {
if (module.exports == freeExports) {
// in Node.js, io.js, or RingoJS v0.8.0+
freeModule.exports = punycode;
} else {
// in Narwhal or RingoJS v0.7.0-
for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
}
}
} else {
// in Rhino or a web browser
root.punycode = punycode;
}
}(commonjsGlobal));
} (punycode, punycode.exports));
return punycode.exports;
}
var IPv6 = {exports: {}};
/*!
* URI.js - Mutating URLs
* IPv6 Support
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
IPv6.exports;
var hasRequiredIPv6;
function requireIPv6 () {
if (hasRequiredIPv6) return IPv6.exports;
hasRequiredIPv6 = 1;
(function (module) {
(function (root, factory) {
// https://github.com/umdjs/umd/blob/master/returnExports.js
if (module.exports) {
// Node
module.exports = factory();
} else {
// Browser globals (root is window)
root.IPv6 = factory(root);
}
}(commonjsGlobal, function (root) {
/*
var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156";
var _out = IPv6.best(_in);
var _expected = "fe80::204:61ff:fe9d:f156";
console.log(_in, _out, _expected, _out === _expected);
*/
// save current IPv6 variable, if any
var _IPv6 = root && root.IPv6;
function bestPresentation(address) {
// based on:
// Javascript to test an IPv6 address for proper format, and to
// present the "best text representation" according to IETF Draft RFC at
// http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04
// 8 Feb 2010 Rich Brown, Dartware, LLC
// Please feel free to use this code as long as you provide a link to
// http://www.intermapper.com
// http://intermapper.com/support/tools/IPV6-Validator.aspx
// http://download.dartware.com/thirdparty/ipv6validator.js
var _address = address.toLowerCase();
var segments = _address.split(':');
var length = segments.length;
var total = 8;
// trim colons (:: or ::a:b:c… or …a:b:c::)
if (segments[0] === '' && segments[1] === '' && segments[2] === '') {
// must have been ::
// remove first two items
segments.shift();
segments.shift();
} else if (segments[0] === '' && segments[1] === '') {
// must have been ::xxxx
// remove the first item
segments.shift();
} else if (segments[length - 1] === '' && segments[length - 2] === '') {
// must have been xxxx::
segments.pop();
}
length = segments.length;
// adjust total segments for IPv4 trailer
if (segments[length - 1].indexOf('.') !== -1) {
// found a "." which means IPv4
total = 7;
}
// fill empty segments them with "0000"
var pos;
for (pos = 0; pos < length; pos++) {
if (segments[pos] === '') {
break;
}
}
if (pos < total) {
segments.splice(pos, 1, '0000');
while (segments.length < total) {
segments.splice(pos, 0, '0000');
}
}
// strip leading zeros
var _segments;
for (var i = 0; i < total; i++) {
_segments = segments[i].split('');
for (var j = 0; j < 3 ; j++) {
if (_segments[0] === '0' && _segments.length > 1) {
_segments.splice(0,1);
} else {
break;
}
}
segments[i] = _segments.join('');
}
// find longest sequence of zeroes and coalesce them into one segment
var best = -1;
var _best = 0;
var _current = 0;
var current = -1;
var inzeroes = false;
// i; already declared
for (i = 0; i < total; i++) {
if (inzeroes) {
if (segments[i] === '0') {
_current += 1;
} else {
inzeroes = false;
if (_current > _best) {
best = current;
_best = _current;
}
}
} else {
if (segments[i] === '0') {
inzeroes = true;
current = i;
_current = 1;
}
}
}
if (_current > _best) {
best = current;
_best = _current;
}
if (_best > 1) {
segments.splice(best, _best, '');
}
length = segments.length;
// assemble remaining segments
var result = '';
if (segments[0] === '') {
result = ':';
}
for (i = 0; i < length; i++) {
result += segments[i];
if (i === length - 1) {
break;
}
result += ':';
}
if (segments[length - 1] === '') {
result += ':';
}
return result;
}
function noConflict() {
/*jshint validthis: true */
if (root.IPv6 === this) {
root.IPv6 = _IPv6;
}
return this;
}
return {
best: bestPresentation,
noConflict: noConflict
};
}));
} (IPv6));
return IPv6.exports;
}
var SecondLevelDomains = {exports: {}};
/*!
* URI.js - Mutating URLs
* Second Level Domain (SLD) Support
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
SecondLevelDomains.exports;
var hasRequiredSecondLevelDomains;
function requireSecondLevelDomains () {
if (hasRequiredSecondLevelDomains) return SecondLevelDomains.exports;
hasRequiredSecondLevelDomains = 1;
(function (module) {
(function (root, factory) {
// https://github.com/umdjs/umd/blob/master/returnExports.js
if (module.exports) {
// Node
module.exports = factory();
} else {
// Browser globals (root is window)
root.SecondLevelDomains = factory(root);
}
}(commonjsGlobal, function (root) {
// save current SecondLevelDomains variable, if any
var _SecondLevelDomains = root && root.SecondLevelDomains;
var SLD = {
// list of known Second Level Domains
// converted list of SLDs from https://github.com/gavingmiller/second-level-domains
// ----
// publicsuffix.org is more current and actually used by a couple of browsers internally.
// downside is it also contains domains like "dyndns.org" - which is fine for the security
// issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js
// ----
list: {
'ac':' com gov mil net org ',
'ae':' ac co gov mil name net org pro sch ',
'af':' com edu gov net org ',
'al':' com edu gov mil net org ',
'ao':' co ed gv it og pb ',
'ar':' com edu gob gov int mil net org tur ',
'at':' ac co gv or ',
'au':' asn com csiro edu gov id net org ',
'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ',
'bb':' biz co com edu gov info net org store tv ',
'bh':' biz cc com edu gov info net org ',
'bn':' com edu gov net org ',
'bo':' com edu gob gov int mil net org tv ',
'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ',
'bs':' com edu gov net org ',
'bz':' du et om ov rg ',
'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ',
'ck':' biz co edu gen gov info net org ',
'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ',
'co':' com edu gov mil net nom org ',
'cr':' ac c co ed fi go or sa ',
'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ',
'do':' art com edu gob gov mil net org sld web ',
'dz':' art asso com edu gov net org pol ',
'ec':' com edu fin gov info med mil net org pro ',
'eg':' com edu eun gov mil name net org sci ',
'er':' com edu gov ind mil net org rochest w ',
'es':' com edu gob nom org ',
'et':' biz com edu gov info name net org ',
'fj':' ac biz com info mil name net org pro ',
'fk':' ac co gov net nom org ',
'fr':' asso com f gouv nom prd presse tm ',
'gg':' co net org ',
'gh':' com edu gov mil org ',
'gn':' ac com gov net org ',
'gr':' com edu gov mil net org ',
'gt':' com edu gob ind mil net org ',
'gu':' com edu gov net org ',
'hk':' com edu gov idv net org ',
'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ',
'id':' ac co go mil net or sch web ',
'il':' ac co gov idf k12 muni net org ',
'in':' ac co edu ernet firm gen gov i ind mil net nic org res ',
'iq':' com edu gov i mil net org ',
'ir':' ac co dnssec gov i id net org sch ',
'it':' edu gov ',
'je':' co net org ',
'jo':' com edu gov mil name net org sch ',
'jp':' ac ad co ed go gr lg ne or ',
'ke':' ac co go info me mobi ne or sc ',
'kh':' com edu gov mil net org per ',
'ki':' biz com de edu gov info mob net org tel ',
'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ',
'kn':' edu gov net org ',
'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ',
'kw':' com edu gov net org ',
'ky':' com edu gov net org ',
'kz':' com edu gov mil net org ',
'lb':' com edu gov net org ',
'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ',
'lr':' com edu gov net org ',
'lv':' asn com conf edu gov id mil net org ',
'ly':' com edu gov id med net org plc sch ',
'ma':' ac co gov m net org press ',
'mc':' asso tm ',
'me':' ac co edu gov its net org priv ',
'mg':' com edu gov mil nom org prd tm ',
'mk':' com edu gov inf name net org pro ',
'ml':' com edu gov net org presse ',
'mn':' edu gov org ',
'mo':' com edu gov net org ',
'mt':' com edu gov net org ',
'mv':' aero biz com coop edu gov info int mil museum name net org pro ',
'mw':' ac co com coop edu gov int museum net org ',
'mx':' com edu gob net org ',
'my':' com edu gov mil name net org sch ',
'nf':' arts com firm info net other per rec store web ',
'ng':' biz com edu gov mil mobi name net org sch ',
'ni':' ac co com edu gob mil net nom org ',
'np':' com edu gov mil net org ',
'nr':' biz com edu gov info net org ',
'om':' ac biz co com edu gov med mil museum net org pro sch ',
'pe':' com edu gob mil net nom org sld ',
'ph':' com edu gov i mil net ngo org ',
'pk':' biz com edu fam gob gok gon gop gos gov net org web ',
'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ',
'pr':' ac biz com edu est gov info isla name net org pro prof ',
'ps':' com edu gov net org plo sec ',
'pw':' belau co ed go ne or ',
'ro':' arts com firm info nom nt org rec store tm www ',
'rs':' ac co edu gov in org ',
'sb':' com edu gov net org ',
'sc':' com edu gov net org ',
'sh':' co com edu gov net nom org ',
'sl':' com edu gov net org ',
'st':' co com consulado edu embaixada gov mil net org principe saotome store ',
'sv':' com edu gob org red ',
'sz':' ac co org ',
'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ',
'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ',
'tw':' club com ebiz edu game gov idv mil net org ',
'mu':' ac co com gov net or org ',
'mz':' ac co edu gov org ',
'na':' co com ',
'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ',
'pa':' abo ac com edu gob ing med net nom org sld ',
'pt':' com edu gov int net nome org publ ',
'py':' com edu gov mil net org ',
'qa':' com edu gov mil net org ',
're':' asso com nom ',
'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ',
'rw':' ac co com edu gouv gov int mil net ',
'sa':' com edu gov med net org pub sch ',
'sd':' com edu gov info med net org tv ',
'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ',
'sg':' com edu gov idn net org per ',
'sn':' art com edu gouv org perso univ ',
'sy':' com edu gov mil net news org ',
'th':' ac co go in mi net or ',
'tj':' ac biz co com edu go gov info int mil name net nic org test web ',
'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ',
'tz':' ac co go ne or ',
'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ',
'ug':' ac co go ne or org sc ',
'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ',
'us':' dni fed isa kids nsn ',
'uy':' com edu gub mil net org ',
've':' co com edu gob info mil net org web ',
'vi':' co com k12 net org ',
'vn':' ac biz com edu gov health info int name net org pro ',
'ye':' co com gov ltd me net org plc ',
'yu':' ac co edu gov org ',
'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ',
'zm':' ac co com edu gov net org sch ',
// https://en.wikipedia.org/wiki/CentralNic#Second-level_domains
'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ',
'net': 'gb jp se uk ',
'org': 'ae',
'de': 'com '
},
// gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost
// in both performance and memory footprint. No initialization required.
// http://jsperf.com/uri-js-sld-regex-vs-binary-search/4
// Following methods use lastIndexOf() rather than array.split() in order
// to avoid any memory allocations.
has: function(domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
return false;
}
var sldOffset = domain.lastIndexOf('.', tldOffset-1);
if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
return false;
}
var sldList = SLD.list[domain.slice(tldOffset+1)];
if (!sldList) {
return false;
}
return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0;
},
is: function(domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
return false;
}
var sldOffset = domain.lastIndexOf('.', tldOffset-1);
if (sldOffset >= 0) {
return false;
}
var sldList = SLD.list[domain.slice(tldOffset+1)];
if (!sldList) {
return false;
}
return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0;
},
get: function(domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
return null;
}
var sldOffset = domain.lastIndexOf('.', tldOffset-1);
if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
return null;
}
var sldList = SLD.list[domain.slice(tldOffset+1)];
if (!sldList) {
return null;
}
if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) {
return null;
}
return domain.slice(sldOffset+1);
},
noConflict: function(){
if (root.SecondLevelDomains === this) {
root.SecondLevelDomains = _SecondLevelDomains;
}
return this;
}
};
return SLD;
}));
} (SecondLevelDomains));
return SecondLevelDomains.exports;
}
/*!
* URI.js - Mutating URLs
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
URI.exports;
(function (module) {
(function (root, factory) {
// https://github.com/umdjs/umd/blob/master/returnExports.js
if (module.exports) {
// Node
module.exports = factory(requirePunycode(), requireIPv6(), requireSecondLevelDomains());
} else {
// Browser globals (root is window)
root.URI = factory(root.punycode, root.IPv6, root.SecondLevelDomains, root);
}
}(commonjsGlobal, function (punycode, IPv6, SLD, root) {
/*global location, escape, unescape */
// FIXME: v2.0.0 renamce non-camelCase properties to uppercase
/*jshint camelcase: false */
// save current URI variable, if any
var _URI = root && root.URI;
function URI(url, base) {
var _urlSupplied = arguments.length >= 1;
var _baseSupplied = arguments.length >= 2;
// Allow instantiation without the 'new' keyword
if (!(this instanceof URI)) {
if (_urlSupplied) {
if (_baseSupplied) {
return new URI(url, base);
}
return new URI(url);
}
return new URI();
}
if (url === undefined) {
if (_urlSupplied) {
throw new TypeError('undefined is not a valid argument for URI');
}
if (typeof location !== 'undefined') {
url = location.href + '';
} else {
url = '';
}
}
if (url === null) {
if (_urlSupplied) {
throw new TypeError('null is not a valid argument for URI');
}
}
this.href(url);
// resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor
if (base !== undefined) {
return this.absoluteTo(base);
}
return this;
}
function isInteger(value) {
return /^[0-9]+$/.test(value);
}
URI.version = '1.19.11';
var p = URI.prototype;
var hasOwn = Object.prototype.hasOwnProperty;
function escapeRegEx(string) {
// https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963
return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
function getType(value) {
// IE8 doesn't return [Object Undefined] but [Object Object] for undefined value
if (value === undefined) {
return 'Undefined';
}
return String(Object.prototype.toString.call(value)).slice(8, -1);
}
function isArray(obj) {
return getType(obj) === 'Array';
}
function filterArrayValues(data, value) {
var lookup = {};
var i, length;
if (getType(value) === 'RegExp') {
lookup = null;
} else if (isArray(value)) {
for (i = 0, length = value.length; i < length; i++) {
lookup[value[i]] = true;
}
} else {
lookup[value] = true;
}
for (i = 0, length = data.length; i < length; i++) {
/*jshint laxbreak: true */
var _match = lookup && lookup[data[i]] !== undefined
|| !lookup && value.test(data[i]);
/*jshint laxbreak: false */
if (_match) {
data.splice(i, 1);
length--;
i--;
}
}
return data;
}
function arrayContains(list, value) {
var i, length;
// value may be string, number, array, regexp
if (isArray(value)) {
// Note: this can be optimized to O(n) (instead of current O(m * n))
for (i = 0, length = value.length; i < length; i++) {
if (!arrayContains(list, value[i])) {
return false;
}
}
return true;
}
var _type = getType(value);
for (i = 0, length = list.length; i < length; i++) {
if (_type === 'RegExp') {
if (typeof list[i] === 'string' && list[i].match(value)) {
return true;
}
} else if (list[i] === value) {
return true;
}
}
return false;
}
function arraysEqual(one, two) {
if (!isArray(one) || !isArray(two)) {
return false;
}
// arrays can't be equal if they have different amount of content
if (one.length !== two.length) {
return false;
}
one.sort();
two.sort();
for (var i = 0, l = one.length; i < l; i++) {
if (one[i] !== two[i]) {
return false;
}
}
return true;
}
function trimSlashes(text) {
var trim_expression = /^\/+|\/+$/g;
return text.replace(trim_expression, '');
}
URI._parts = function() {
return {
protocol: null,
username: null,
password: null,
hostname: null,
urn: null,
port: null,
path: null,
query: null,
fragment: null,
// state
preventInvalidHostname: URI.preventInvalidHostname,
duplicateQueryParameters: URI.duplicateQueryParameters,
escapeQuerySpace: URI.escapeQuerySpace
};
};
// state: throw on invalid hostname
// see https://github.com/medialize/URI.js/pull/345
// and https://github.com/medialize/URI.js/issues/354
URI.preventInvalidHostname = false;
// state: allow duplicate query parameters (a=1&a=1)
URI.duplicateQueryParameters = false;
// state: replaces + with %20 (space in query strings)
URI.escapeQuerySpace = true;
// static properties
URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i;
URI.idn_expression = /[^a-z0-9\._-]/i;
URI.punycode_expression = /(xn--)/i;
// well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care?
URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
// credits to Rich Brown
// source: http://forums.intermapper.com/viewtopic.php?p=1096#1096
// specification: http://www.ietf.org/rfc/rfc4291.txt
URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
// expression used is "gruber revised" (@gruber v2) determined to be the
// best solution in a regex-golf we did a couple of ages ago at
// * http://mathiasbynens.be/demo/url-regex
// * http://rodneyrehm.de/t/url-regex.html
URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig;
URI.findUri = {
// valid "scheme://" or "www."
start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,
// everything up to the next whitespace
end: /[\s\r\n]|$/,
// trim trailing punctuation captured by end RegExp
trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/,
// balanced parens inclusion (), [], {}, <>
parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g,
};
URI.leading_whitespace_expression = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
URI.ascii_tab_whitespace = /[\u0009\u000A\u000D]+/g;
// http://www.iana.org/assignments/uri-schemes.html
// http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports
URI.defaultPorts = {
http: '80',
https: '443',
ftp: '21',
gopher: '70',
ws: '80',
wss: '443'
};
// list of protocols which always require a hostname
URI.hostProtocols = [
'http',
'https'
];
// allowed hostname characters according to RFC 3986
// ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded
// I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _
URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/;
// map DOM Elements to their URI attribute
URI.domAttributes = {
'a': 'href',
'blockquote': 'cite',
'link': 'href',
'base': 'href',
'script': 'src',
'form': 'action',
'img': 'src',
'area': 'href',
'iframe': 'src',
'embed': 'src',
'source': 'src',
'track': 'src',
'input': 'src', // but only if type="image"
'audio': 'src',
'video': 'src'
};
URI.getDomAttribute = function(node) {
if (!node || !node.nodeName) {
return undefined;
}
var nodeName = node.nodeName.toLowerCase();
// <input> should only expose src for type="image"
if (nodeName === 'input' && node.type !== 'image') {
return undefined;
}
return URI.domAttributes[nodeName];
};
function escapeForDumbFirefox36(value) {
// https://github.com/medialize/URI.js/issues/91
return escape(value);
}
// encoding / decoding according to RFC3986
function strictEncodeURIComponent(string) {
// see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
return encodeURIComponent(string)
.replace(/[!'()*]/g, escapeForDumbFirefox36)
.replace(/\*/g, '%2A');
}
URI.encode = strictEncodeURIComponent;
URI.decode = decodeURIComponent;
URI.iso8859 = function() {
URI.encode = escape;
URI.decode = unescape;
};
URI.unicode = function() {
URI.encode = strictEncodeURIComponent;
URI.decode = decodeURIComponent;
};
URI.characters = {
pathname: {
encode: {
// RFC3986 2.1: For consistency, URI producers and normalizers should
// use uppercase hexadecimal digits for all percent-encodings.
expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig,
map: {
// -._~!'()*
'%24': '$',
'%26': '&',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '=',
'%3A': ':',
'%40': '@'
}
},
decode: {
expression: /[\/\?#]/g,
map: {
'/': '%2F',
'?': '%3F',
'#': '%23'
}
}
},
reserved: {
encode: {
// RFC3986 2.1: For consistency, URI producers and normalizers should
// use uppercase hexadecimal digits for all percent-encodings.
expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,
map: {
// gen-delims
'%3A': ':',
'%2F': '/',
'%3F': '?',
'%23': '#',
'%5B': '[',
'%5D': ']',
'%40': '@',
// sub-delims
'%21': '!',
'%24': '$',
'%26': '&',
'%27': '\'',
'%28': '(',
'%29': ')',
'%2A': '*',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '='
}
}
},
urnpath: {
// The characters under `encode` are the characters called out by RFC 2141 as being acceptable
// for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but
// these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also
// note that the colon character is not featured in the encoding map; this is because URI.js
// gives the colons in URNs semantic meaning as the delimiters of path segements, and so it
// should not appear unencoded in a segment itself.
// See also the note above about RFC3986 and capitalalized hex digits.
encode: {
expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,
map: {
'%21': '!',
'%24': '$',
'%27': '\'',
'%28': '(',
'%29': ')',
'%2A': '*',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '=',
'%40': '@'
}
},
// These characters are the characters called out by RFC2141 as "reserved" characters that
// should never appear in a URN, plus the colon character (see note above).
decode: {
expression: /[\/\?#:]/g,
map: {
'/': '%2F',
'?': '%3F',
'#': '%23',
':': '%3A'
}
}
}
};
URI.encodeQuery = function(string, escapeQuerySpace) {
var escaped = URI.encode(string + '');
if (escapeQuerySpace === undefined) {
escapeQuerySpace = URI.escapeQuerySpace;
}
return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped;
};
URI.decodeQuery = function(string, escapeQuerySpace) {
string += '';
if (escapeQuerySpace === undefined) {
escapeQuerySpace = URI.escapeQuerySpace;
}
try {
return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string);
} catch(e) {
// we're not going to mess with weird encodings,
// give up and return the undecoded original string
// see https://github.com/medialize/URI.js/issues/87
// see https://github.com/medialize/URI.js/issues/92
return string;
}
};
// generate encode/decode path functions
var _parts = {'encode':'encode', 'decode':'decode'};
var _part;
var generateAccessor = function(_group, _part) {
return function(string) {
try {
return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) {
return URI.characters[_group][_part].map[c];
});
} catch (e) {
// we're not going to mess with weird encodings,
// give up and return the undecoded original string
// see https://github.com/medialize/URI.js/issues/87
// see https://github.com/medialize/URI.js/issues/92
return string;
}
};
};
for (_part in _parts) {
URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]);
URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]);
}
var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) {
return function(string) {
// Why pass in names of functions, rather than the function objects themselves? The
// definitions of some functions (but in particular, URI.decode) will occasionally change due
// to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure
// that the functions we use here are "fresh".
var actualCodingFunc;
if (!_innerCodingFuncName) {
actualCodingFunc = URI[_codingFuncName];
} else {
actualCodingFunc = function(string) {
return URI[_codingFuncName](URI[_innerCodingFuncName](string));
};
}
var segments = (string + '').split(_sep);
for (var i = 0, length = segments.length; i < length; i++) {
segments[i] = actualCodingFunc(segments[i]);
}
return segments.join(_sep);
};
};
// This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions.
URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment');
URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment');
URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');
URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');
URI.encodeReserved = generateAccessor('reserved', 'encode');
URI.parse = function(string, parts) {
var pos;
if (!parts) {
parts = {
preventInvalidHostname: URI.preventInvalidHostname
};
}
string = string.replace(URI.leading_whitespace_expression, '');
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
string = string.replace(URI.ascii_tab_whitespace, '');
// [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment]
// extract fragment
pos = string.indexOf('#');
if (pos > -1) {
// escaping?
parts.fragment = string.substring(pos + 1) || null;
string = string.substring(0, pos);
}
// extract query
pos = string.indexOf('?');
if (pos > -1) {
// escaping?
parts.query = string.substring(pos + 1) || null;
string = string.substring(0, pos);
}
// slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws)
string = string.replace(/^(https?|ftp|wss?)?:+[/\\]*/i, '$1://');
// slashes and backslashes have lost all meaning for scheme relative URLs
string = string.replace(/^[/\\]{2,}/i, '//');
// extract protocol
if (string.substring(0, 2) === '//') {
// relative-scheme
parts.protocol = null;
string = string.substring(2);
// extract "user:pass@host:port"
string = URI.parseAuthority(string, parts);
} else {
pos = string.indexOf(':');
if (pos > -1) {
parts.protocol = string.substring(0, pos) || null;
if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {
// : may be within the path
parts.protocol = undefined;
} else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') {
string = string.substring(pos + 3);
// extract "user:pass@host:port"
string = URI.parseAuthority(string, parts);
} else {
string = string.substring(pos + 1);
parts.urn = true;
}
}
}
// what's left must be the path
parts.path = string;
// and we're done
return parts;
};
URI.parseHost = function(string, parts) {
if (!string) {
string = '';
}
// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124
// See: https://code.google.com/p/chromium/issues/detail?id=25916
// https://github.com/medialize/URI.js/pull/233
string = string.replace(/\\/g, '/');
// extract host:port
var pos = string.indexOf('/');
var bracketPos;
var t;
if (pos === -1) {
pos = string.length;
}
if (string.charAt(0) === '[') {
// IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6
// I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts
// IPv6+port in the format [2001:db8::1]:80 (for the time being)
bracketPos = string.indexOf(']');
parts.hostname = string.substring(1, bracketPos) || null;
parts.port = string.substring(bracketPos + 2, pos) || null;
if (parts.port === '/') {
parts.port = null;
}
} else {
var firstColon = string.indexOf(':');
var firstSlash = string.indexOf('/');
var nextColon = string.indexOf(':', firstColon + 1);
if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) {
// IPv6 host contains multiple colons - but no port
// this notation is actually not allowed by RFC 3986, but we're a liberal parser
parts.hostname = string.substring(0, pos) || null;
parts.port = null;
} else {
t = string.substring(0, pos).split(':');
parts.hostname = t[0] || null;
parts.port = t[1] || null;
}
}
if (parts.hostname && string.substring(pos).charAt(0) !== '/') {
pos++;
string = '/' + string;
}
if (parts.preventInvalidHostname) {
URI.ensureValidHostname(parts.hostname, parts.protocol);
}
if (parts.port) {
URI.ensureValidPort(parts.port);
}
return string.substring(pos) || '/';
};
URI.parseAuthority = function(string, parts) {
string = URI.parseUserinfo(string, parts);
return URI.parseHost(string, parts);
};
URI.parseUserinfo = function(string, parts) {
// extract username:password
var _string = string;
var firstBackSlash = string.indexOf('\\');
if (firstBackSlash !== -1) {
string = string.replace(/\\/g, '/');
}
var firstSlash = string.indexOf('/');
var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1);
var t;
// authority@ must come before /path or \path
if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) {
t = string.substring(0, pos).split(':');
parts.username = t[0] ? URI.decode(t[0]) : null;
t.shift();
parts.password = t[0] ? URI.decode(t.join(':')) : null;
string = _string.substring(pos + 1);
} else {
parts.username = null;
parts.password = null;
}
return string;
};
URI.parseQuery = function(string, escapeQuerySpace) {
if (!string) {
return {};
}
// throw out the funky business - "?"[name"="value"&"]+
string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, '');
if (!string) {
return {};
}
var items = {};
var splits = string.split('&');
var length = splits.length;
var v, name, value;
for (var i = 0; i < length; i++) {
v = splits[i].split('=');
name = URI.decodeQuery(v.shift(), escapeQuerySpace);
// no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters
value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null;
if (name === '__proto__') {
// ignore attempt at exploiting JavaScript internals
continue;
} else if (hasOwn.call(items, name)) {
if (typeof items[name] === 'string' || items[name] === null) {
items[name] = [items[name]];
}
items[name].push(value);
} else {
items[name] = value;
}
}
return items;
};
URI.build = function(parts) {
var t = '';
var requireAbsolutePath = false;
if (parts.protocol) {
t += parts.protocol + ':';
}
if (!parts.urn && (t || parts.hostname)) {
t += '//';
requireAbsolutePath = true;
}
t += (URI.buildAuthority(parts) || '');
if (typeof parts.path === 'string') {
if (parts.path.charAt(0) !== '/' && requireAbsolutePath) {
t += '/';
}
t += parts.path;
}
if (typeof parts.query === 'string' && parts.query) {
t += '?' + parts.query;
}
if (typeof parts.fragment === 'string' && parts.fragment) {
t += '#' + parts.fragment;
}
return t;
};
URI.buildHost = function(parts) {
var t = '';
if (!parts.hostname) {
return '';
} else if (URI.ip6_expression.test(parts.hostname)) {
t += '[' + parts.hostname + ']';
} else {
t += parts.hostname;
}
if (parts.port) {
t += ':' + parts.port;
}
return t;
};
URI.buildAuthority = function(parts) {
return URI.buildUserinfo(parts) + URI.buildHost(parts);
};
URI.buildUserinfo = function(parts) {
var t = '';
if (parts.username) {
t += URI.encode(parts.username);
}
if (parts.password) {
t += ':' + URI.encode(parts.password);
}
if (t) {
t += '@';
}
return t;
};
URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) {
// according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html
// being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed
// the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax!
// URI.js treats the query string as being application/x-www-form-urlencoded
// see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type
var t = '';
var unique, key, i, length;
for (key in data) {
if (key === '__proto__') {
// ignore attempt at exploiting JavaScript internals
continue;
} else if (hasOwn.call(data, key)) {
if (isArray(data[key])) {
unique = {};
for (i = 0, length = data[key].length; i < length; i++) {
if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) {
t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace);
if (duplicateQueryParameters !== true) {
unique[data[key][i] + ''] = true;
}
}
}
} else if (data[key] !== undefined) {
t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace);
}
}
}
return t.substring(1);
};
URI.buildQueryParameter = function(name, value, escapeQuerySpace) {
// http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded
// don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization
return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : '');
};
URI.addQuery = function(data, name, value) {
if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
URI.addQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
if (data[name] === undefined) {
data[name] = value;
return;
} else if (typeof data[name] === 'string') {
data[name] = [data[name]];
}
if (!isArray(value)) {
value = [value];
}
data[name] = (data[name] || []).concat(value);
} else {
throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
}
};
URI.setQuery = function(data, name, value) {
if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
URI.setQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
data[name] = value === undefined ? null : value;
} else {
throw new TypeError('URI.setQuery() accepts an object, string as the name parameter');
}
};
URI.removeQuery = function(data, name, value) {
var i, length, key;
if (isArray(name)) {
for (i = 0, length = name.length; i < length; i++) {
data[name[i]] = undefined;
}
} else if (getType(name) === 'RegExp') {
for (key in data) {
if (name.test(key)) {
data[key] = undefined;
}
}
} else if (typeof name === 'object') {
for (key in name) {
if (hasOwn.call(name, key)) {
URI.removeQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
if (value !== undefined) {
if (getType(value) === 'RegExp') {
if (!isArray(data[name]) && value.test(data[name])) {
data[name] = undefined;
} else {
data[name] = filterArrayValues(data[name], value);
}
} else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) {
data[name] = undefined;
} else if (isArray(data[name])) {
data[name] = filterArrayValues(data[name], value);
}
} else {
data[name] = undefined;
}
} else {
throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter');
}
};
URI.hasQuery = function(data, name, value, withinArray) {
switch (getType(name)) {
case 'String':
// Nothing to do here
break;
case 'RegExp':
for (var key in data) {
if (hasOwn.call(data, key)) {
if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) {
return true;
}
}
}
return false;
case 'Object':
for (var _key in name) {
if (hasOwn.call(name, _key)) {
if (!URI.hasQuery(data, _key, name[_key])) {
return false;
}
}
}
return true;
default:
throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter');
}
switch (getType(value)) {
case 'Undefined':
// true if exists (but may be empty)
return name in data; // data[name] !== undefined;
case 'Boolean':
// true if exists and non-empty
var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]);
return value === _booly;
case 'Function':
// allow complex comparison
return !!value(data[name], name, data);
case 'Array':
if (!isArray(data[name])) {
return false;
}
var op = withinArray ? arrayContains : arraysEqual;
return op(data[name], value);
case 'RegExp':
if (!isArray(data[name])) {
return Boolean(data[name] && data[name].match(value));
}
if (!withinArray) {
return false;
}
return arrayContains(data[name], value);
case 'Number':
value = String(value);
/* falls through */
case 'String':
if (!isArray(data[name])) {
return data[name] === value;
}
if (!withinArray) {
return false;
}
return arrayContains(data[name], value);
default:
throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter');
}
};
URI.joinPaths = function() {
var input = [];
var segments = [];
var nonEmptySegments = 0;
for (var i = 0; i < arguments.length; i++) {
var url = new URI(arguments[i]);
input.push(url);
var _segments = url.segment();
for (var s = 0; s < _segments.length; s++) {
if (typeof _segments[s] === 'string') {
segments.push(_segments[s]);
}
if (_segments[s]) {
nonEmptySegments++;
}
}
}
if (!segments.length || !nonEmptySegments) {
return new URI('');
}
var uri = new URI('').segment(segments);
if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') {
uri.path('/' + uri.path());
}
return uri.normalize();
};
URI.commonPath = function(one, two) {
var length = Math.min(one.length, two.length);
var pos;
// find first non-matching character
for (pos = 0; pos < length; pos++) {
if (one.charAt(pos) !== two.charAt(pos)) {
pos--;
break;
}
}
if (pos < 1) {
return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : '';
}
// revert to last /
if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') {
pos = one.substring(0, pos).lastIndexOf('/');
}
return one.substring(0, pos + 1);
};
URI.withinString = function(string, callback, options) {
options || (options = {});
var _start = options.start || URI.findUri.start;
var _end = options.end || URI.findUri.end;
var _trim = options.trim || URI.findUri.trim;
var _parens = options.parens || URI.findUri.parens;
var _attributeOpen = /[a-z0-9-]=["']?$/i;
_start.lastIndex = 0;
while (true) {
var match = _start.exec(string);
if (!match) {
break;
}
var start = match.index;
if (options.ignoreHtml) {
// attribut(e=["']?$)
var attributeOpen = string.slice(Math.max(start - 3, 0), start);
if (attributeOpen && _attributeOpen.test(attributeOpen)) {
continue;
}
}
var end = start + string.slice(start).search(_end);
var slice = string.slice(start, end);
// make sure we include well balanced parens
var parensEnd = -1;
while (true) {
var parensMatch = _parens.exec(slice);
if (!parensMatch) {
break;
}
var parensMatchEnd = parensMatch.index + parensMatch[0].length;
parensEnd = Math.max(parensEnd, parensMatchEnd);
}
if (parensEnd > -1) {
slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, '');
} else {
slice = slice.replace(_trim, '');
}
if (slice.length <= match[0].length) {
// the extract only contains the starting marker of a URI,
// e.g. "www" or "http://"
continue;
}
if (options.ignore && options.ignore.test(slice)) {
continue;
}
end = start + slice.length;
var result = callback(slice, start, end, string);
if (result === undefined) {
_start.lastIndex = end;
continue;
}
result = String(result);
string = string.slice(0, start) + result + string.slice(end);
_start.lastIndex = start + result.length;
}
_start.lastIndex = 0;
return string;
};
URI.ensureValidHostname = function(v, protocol) {
// Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986)
// they are not part of DNS and therefore ignored by URI.js
var hasHostname = !!v; // not null and not an empty string
var hasProtocol = !!protocol;
var rejectEmptyHostname = false;
if (hasProtocol) {
rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol);
}
if (rejectEmptyHostname && !hasHostname) {
throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol);
} else if (v && v.match(URI.invalid_hostname_characters)) {
// test punycode
if (!punycode) {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');
}
if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]');
}
}
};
URI.ensureValidPort = function (v) {
if (!v) {
return;
}
var port = Number(v);
if (isInteger(port) && (port > 0) && (port < 65536)) {
return;
}
throw new TypeError('Port "' + v + '" is not a valid port');
};
// noConflict
URI.noConflict = function(removeAll) {
if (removeAll) {
var unconflicted = {
URI: this.noConflict()
};
if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') {
unconflicted.URITemplate = root.URITemplate.noConflict();
}
if (root.IPv6 && typeof root.IPv6.noConflict === 'function') {
unconflicted.IPv6 = root.IPv6.noConflict();
}
if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') {
unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict();
}
return unconflicted;
} else if (root.URI === this) {
root.URI = _URI;
}
return this;
};
p.build = function(deferBuild) {
if (deferBuild === true) {
this._deferred_build = true;
} else if (deferBuild === undefined || this._deferred_build) {
this._string = URI.build(this._parts);
this._deferred_build = false;
}
return this;
};
p.clone = function() {
return new URI(this);
};
p.valueOf = p.toString = function() {
return this.build(false)._string;
};
function generateSimpleAccessor(_part){
return function(v, build) {
if (v === undefined) {
return this._parts[_part] || '';
} else {
this._parts[_part] = v || null;
this.build(!build);
return this;
}
};
}
function generatePrefixAccessor(_part, _key){
return function(v, build) {
if (v === undefined) {
return this._parts[_part] || '';
} else {
if (v !== null) {
v = v + '';
if (v.charAt(0) === _key) {
v = v.substring(1);
}
}
this._parts[_part] = v;
this.build(!build);
return this;
}
};
}
p.protocol = generateSimpleAccessor('protocol');
p.username = generateSimpleAccessor('username');
p.password = generateSimpleAccessor('password');
p.hostname = generateSimpleAccessor('hostname');
p.port = generateSimpleAccessor('port');
p.query = generatePrefixAccessor('query', '?');
p.fragment = generatePrefixAccessor('fragment', '#');
p.search = function(v, build) {
var t = this.query(v, build);
return typeof t === 'string' && t.length ? ('?' + t) : t;
};
p.hash = function(v, build) {
var t = this.fragment(v, build);
return typeof t === 'string' && t.length ? ('#' + t) : t;
};
p.pathname = function(v, build) {
if (v === undefined || v === true) {
var res = this._parts.path || (this._parts.hostname ? '/' : '');
return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res;
} else {
if (this._parts.urn) {
this._parts.path = v ? URI.recodeUrnPath(v) : '';
} else {
this._parts.path = v ? URI.recodePath(v) : '/';
}
this.build(!build);
return this;
}
};
p.path = p.pathname;
p.href = function(href, build) {
var key;
if (href === undefined) {
return this.toString();
}
this._string = '';
this._parts = URI._parts();
var _URI = href instanceof URI;
var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname);
if (href.nodeName) {
var attribute = URI.getDomAttribute(href);
href = href[attribute] || '';
_object = false;
}
// window.location is reported to be an object, but it's not the sort
// of object we're looking for:
// * location.protocol ends with a colon
// * location.query != object.search
// * location.hash != object.fragment
// simply serializing the unknown object should do the trick
// (for location, not for everything...)
if (!_URI && _object && href.pathname !== undefined) {
href = href.toString();
}
if (typeof href === 'string' || href instanceof String) {
this._parts = URI.parse(String(href), this._parts);
} else if (_URI || _object) {
var src = _URI ? href._parts : href;
for (key in src) {
if (key === 'query') { continue; }
if (hasOwn.call(this._parts, key)) {
this._parts[key] = src[key];
}
}
if (src.query) {
this.query(src.query, false);
}
} else {
throw new TypeError('invalid input');
}
this.build(!build);
return this;
};
// identification accessors
p.is = function(what) {
var ip = false;
var ip4 = false;
var ip6 = false;
var name = false;
var sld = false;
var idn = false;
var punycode = false;
var relative = !this._parts.urn;
if (this._parts.hostname) {
relative = false;
ip4 = URI.ip4_expression.test(this._parts.hostname);
ip6 = URI.ip6_expression.test(this._parts.hostname);
ip = ip4 || ip6;
name = !ip;
sld = name && SLD && SLD.has(this._parts.hostname);
idn = name && URI.idn_expression.test(this._parts.hostname);
punycode = name && URI.punycode_expression.test(this._parts.hostname);
}
switch (what.toLowerCase()) {
case 'relative':
return relative;
case 'absolute':
return !relative;
// hostname identification
case 'domain':
case 'name':
return name;
case 'sld':
return sld;
case 'ip':
return ip;
case 'ip4':
case 'ipv4':
case 'inet4':
return ip4;
case 'ip6':
case 'ipv6':
case 'inet6':
return ip6;
case 'idn':
return idn;
case 'url':
return !this._parts.urn;
case 'urn':
return !!this._parts.urn;
case 'punycode':
return punycode;
}
return null;
};
// component specific input validation
var _protocol = p.protocol;
var _port = p.port;
var _hostname = p.hostname;
p.protocol = function(v, build) {
if (v) {
// accept trailing ://
v = v.replace(/:(\/\/)?$/, '');
if (!v.match(URI.protocol_expression)) {
throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]');
}
}
return _protocol.call(this, v, build);
};
p.scheme = p.protocol;
p.port = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v !== undefined) {
if (v === 0) {
v = null;
}
if (v) {
v += '';
if (v.charAt(0) === ':') {
v = v.substring(1);
}
URI.ensureValidPort(v);
}
}
return _port.call(this, v, build);
};
p.hostname = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v !== undefined) {
var x = { preventInvalidHostname: this._parts.preventInvalidHostname };
var res = URI.parseHost(v, x);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
v = x.hostname;
if (this._parts.preventInvalidHostname) {
URI.ensureValidHostname(v, this._parts.protocol);
}
}
return _hostname.call(this, v, build);
};
// compound accessors
p.origin = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
var protocol = this.protocol();
var authority = this.authority();
if (!authority) {
return '';
}
return (protocol ? protocol + '://' : '') + this.authority();
} else {
var origin = URI(v);
this
.protocol(origin.protocol())
.authority(origin.authority())
.build(!build);
return this;
}
};
p.host = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
return this._parts.hostname ? URI.buildHost(this._parts) : '';
} else {
var res = URI.parseHost(v, this._parts);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
this.build(!build);
return this;
}
};
p.authority = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
return this._parts.hostname ? URI.buildAuthority(this._parts) : '';
} else {
var res = URI.parseAuthority(v, this._parts);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
this.build(!build);
return this;
}
};
p.userinfo = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
var t = URI.buildUserinfo(this._parts);
return t ? t.substring(0, t.length -1) : t;
} else {
if (v[v.length-1] !== '@') {
v += '@';
}
URI.parseUserinfo(v, this._parts);
this.build(!build);
return this;
}
};
p.resource = function(v, build) {
var parts;
if (v === undefined) {
return this.path() + this.search() + this.hash();
}
parts = URI.parse(v);
this._parts.path = parts.path;
this._parts.query = parts.query;
this._parts.fragment = parts.fragment;
this.build(!build);
return this;
};
// fraction accessors
p.subdomain = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
// convenience, return "www" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
// grab domain and add another segment
var end = this._parts.hostname.length - this.domain().length - 1;
return this._parts.hostname.substring(0, end) || '';
} else {
var e = this._parts.hostname.length - this.domain().length;
var sub = this._parts.hostname.substring(0, e);
var replace = new RegExp('^' + escapeRegEx(sub));
if (v && v.charAt(v.length - 1) !== '.') {
v += '.';
}
if (v.indexOf(':') !== -1) {
throw new TypeError('Domains cannot contain colons');
}
if (v) {
URI.ensureValidHostname(v, this._parts.protocol);
}
this._parts.hostname = this._parts.hostname.replace(replace, v);
this.build(!build);
return this;
}
};
p.domain = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v === 'boolean') {
build = v;
v = undefined;
}
// convenience, return "example.org" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
// if hostname consists of 1 or 2 segments, it must be the domain
var t = this._parts.hostname.match(/\./g);
if (t && t.length < 2) {
return this._parts.hostname;
}
// grab tld and add another segment
var end = this._parts.hostname.length - this.tld(build).length - 1;
end = this._parts.hostname.lastIndexOf('.', end -1) + 1;
return this._parts.hostname.substring(end) || '';
} else {
if (!v) {
throw new TypeError('cannot set domain empty');
}
if (v.indexOf(':') !== -1) {
throw new TypeError('Domains cannot contain colons');
}
URI.ensureValidHostname(v, this._parts.protocol);
if (!this._parts.hostname || this.is('IP')) {
this._parts.hostname = v;
} else {
var replace = new RegExp(escapeRegEx(this.domain()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.tld = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v === 'boolean') {
build = v;
v = undefined;
}
// return "org" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
var pos = this._parts.hostname.lastIndexOf('.');
var tld = this._parts.hostname.substring(pos + 1);
if (build !== true && SLD && SLD.list[tld.toLowerCase()]) {
return SLD.get(this._parts.hostname) || tld;
}
return tld;
} else {
var replace;
if (!v) {
throw new TypeError('cannot set TLD empty');
} else if (v.match(/[^a-zA-Z0-9-]/)) {
if (SLD && SLD.is(v)) {
replace = new RegExp(escapeRegEx(this.tld()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
} else {
throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]');
}
} else if (!this._parts.hostname || this.is('IP')) {
throw new ReferenceError('cannot set TLD on non-domain host');
} else {
replace = new RegExp(escapeRegEx(this.tld()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.directory = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined || v === true) {
if (!this._parts.path && !this._parts.hostname) {
return '';
}
if (this._parts.path === '/') {
return '/';
}
var end = this._parts.path.length - this.filename().length - 1;
var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : '');
return v ? URI.decodePath(res) : res;
} else {
var e = this._parts.path.length - this.filename().length;
var directory = this._parts.path.substring(0, e);
var replace = new RegExp('^' + escapeRegEx(directory));
// fully qualifier directories begin with a slash
if (!this.is('relative')) {
if (!v) {
v = '/';
}
if (v.charAt(0) !== '/') {
v = '/' + v;
}
}
// directories always end with a slash
if (v && v.charAt(v.length - 1) !== '/') {
v += '/';
}
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
this.build(!build);
return this;
}
};
p.filename = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v !== 'string') {
if (!this._parts.path || this._parts.path === '/') {
return '';
}
var pos = this._parts.path.lastIndexOf('/');
var res = this._parts.path.substring(pos+1);
return v ? URI.decodePathSegment(res) : res;
} else {
var mutatedDirectory = false;
if (v.charAt(0) === '/') {
v = v.substring(1);
}
if (v.match(/\.?\//)) {
mutatedDirectory = true;
}
var replace = new RegExp(escapeRegEx(this.filename()) + '$');
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
if (mutatedDirectory) {
this.normalizePath(build);
} else {
this.build(!build);
}
return this;
}
};
p.suffix = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined || v === true) {
if (!this._parts.path || this._parts.path === '/') {
return '';
}
var filename = this.filename();
var pos = filename.lastIndexOf('.');
var s, res;
if (pos === -1) {
return '';
}
// suffix may only contain alnum characters (yup, I made this up.)
s = filename.substring(pos+1);
res = (/^[a-z0-9%]+$/i).test(s) ? s : '';
return v ? URI.decodePathSegment(res) : res;
} else {
if (v.charAt(0) === '.') {
v = v.substring(1);
}
var suffix = this.suffix();
var replace;
if (!suffix) {
if (!v) {
return this;
}
this._parts.path += '.' + URI.recodePath(v);
} else if (!v) {
replace = new RegExp(escapeRegEx('.' + suffix) + '$');
} else {
replace = new RegExp(escapeRegEx(suffix) + '$');
}
if (replace) {
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.segment = function(segment, v, build) {
var separator = this._parts.urn ? ':' : '/';
var path = this.path();
var absolute = path.substring(0, 1) === '/';
var segments = path.split(separator);
if (segment !== undefined && typeof segment !== 'number') {
build = v;
v = segment;
segment = undefined;
}
if (segment !== undefined && typeof segment !== 'number') {
throw new Error('Bad segment "' + segment + '", must be 0-based integer');
}
if (absolute) {
segments.shift();
}
if (segment < 0) {
// allow negative indexes to address from the end
segment = Math.max(segments.length + segment, 0);
}
if (v === undefined) {
/*jshint laxbreak: true */
return segment === undefined
? segments
: segments[segment];
/*jshint laxbreak: false */
} else if (segment === null || segments[segment] === undefined) {
if (isArray(v)) {
segments = [];
// collapse empty elements within array
for (var i=0, l=v.length; i < l; i++) {
if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) {
continue;
}
if (segments.length && !segments[segments.length -1].length) {
segments.pop();
}
segments.push(trimSlashes(v[i]));
}
} else if (v || typeof v === 'string') {
v = trimSlashes(v);
if (segments[segments.length -1] === '') {
// empty trailing elements have to be overwritten
// to prevent results such as /foo//bar
segments[segments.length -1] = v;
} else {
segments.push(v);
}
}
} else {
if (v) {
segments[segment] = trimSlashes(v);
} else {
segments.splice(segment, 1);
}
}
if (absolute) {
segments.unshift('');
}
return this.path(segments.join(separator), build);
};
p.segmentCoded = function(segment, v, build) {
var segments, i, l;
if (typeof segment !== 'number') {
build = v;
v = segment;
segment = undefined;
}
if (v === undefined) {
segments = this.segment(segment, v, build);
if (!isArray(segments)) {
segments = segments !== undefined ? URI.decode(segments) : undefined;
} else {
for (i = 0, l = segments.length; i < l; i++) {
segments[i] = URI.decode(segments[i]);
}
}
return segments;
}
if (!isArray(v)) {
v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v;
} else {
for (i = 0, l = v.length; i < l; i++) {
v[i] = URI.encode(v[i]);
}
}
return this.segment(segment, v, build);
};
// mutating query string
var q = p.query;
p.query = function(v, build) {
if (v === true) {
return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
} else if (typeof v === 'function') {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
var result = v.call(this, data);
this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
this.build(!build);
return this;
} else if (v !== undefined && typeof v !== 'string') {
this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
this.build(!build);
return this;
} else {
return q.call(this, v, build);
}
};
p.setQuery = function(name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
if (typeof name === 'string' || name instanceof String) {
data[name] = value !== undefined ? value : null;
} else if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
data[key] = name[key];
}
}
} else {
throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
}
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.addQuery = function(name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
URI.addQuery(data, name, value === undefined ? null : value);
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.removeQuery = function(name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
URI.removeQuery(data, name, value);
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.hasQuery = function(name, value, withinArray) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
return URI.hasQuery(data, name, value, withinArray);
};
p.setSearch = p.setQuery;
p.addSearch = p.addQuery;
p.removeSearch = p.removeQuery;
p.hasSearch = p.hasQuery;
// sanitizing URLs
p.normalize = function() {
if (this._parts.urn) {
return this
.normalizeProtocol(false)
.normalizePath(false)
.normalizeQuery(false)
.normalizeFragment(false)
.build();
}
return this
.normalizeProtocol(false)
.normalizeHostname(false)
.normalizePort(false)
.normalizePath(false)
.normalizeQuery(false)
.normalizeFragment(false)
.build();
};
p.normalizeProtocol = function(build) {
if (typeof this._parts.protocol === 'string') {
this._parts.protocol = this._parts.protocol.toLowerCase();
this.build(!build);
}
return this;
};
p.normalizeHostname = function(build) {
if (this._parts.hostname) {
if (this.is('IDN') && punycode) {
this._parts.hostname = punycode.toASCII(this._parts.hostname);
} else if (this.is('IPv6') && IPv6) {
this._parts.hostname = IPv6.best(this._parts.hostname);
}
this._parts.hostname = this._parts.hostname.toLowerCase();
this.build(!build);
}
return this;
};
p.normalizePort = function(build) {
// remove port of it's the protocol's default
if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) {
this._parts.port = null;
this.build(!build);
}
return this;
};
p.normalizePath = function(build) {
var _path = this._parts.path;
if (!_path) {
return this;
}
if (this._parts.urn) {
this._parts.path = URI.recodeUrnPath(this._parts.path);
this.build(!build);
return this;
}
if (this._parts.path === '/') {
return this;
}
_path = URI.recodePath(_path);
var _was_relative;
var _leadingParents = '';
var _parent, _pos;
// handle relative paths
if (_path.charAt(0) !== '/') {
_was_relative = true;
_path = '/' + _path;
}
// handle relative files (as opposed to directories)
if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') {
_path += '/';
}
// resolve simples
_path = _path
.replace(/(\/(\.\/)+)|(\/\.$)/g, '/')
.replace(/\/{2,}/g, '/');
// remember leading parents
if (_was_relative) {
_leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || '';
if (_leadingParents) {
_leadingParents = _leadingParents[0];
}
}
// resolve parents
while (true) {
_parent = _path.search(/\/\.\.(\/|$)/);
if (_parent === -1) {
// no more ../ to resolve
break;
} else if (_parent === 0) {
// top level cannot be relative, skip it
_path = _path.substring(3);
continue;
}
_pos = _path.substring(0, _parent).lastIndexOf('/');
if (_pos === -1) {
_pos = _parent;
}
_path = _path.substring(0, _pos) + _path.substring(_parent + 3);
}
// revert to relative
if (_was_relative && this.is('relative')) {
_path = _leadingParents + _path.substring(1);
}
this._parts.path = _path;
this.build(!build);
return this;
};
p.normalizePathname = p.normalizePath;
p.normalizeQuery = function(build) {
if (typeof this._parts.query === 'string') {
if (!this._parts.query.length) {
this._parts.query = null;
} else {
this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace));
}
this.build(!build);
}
return this;
};
p.normalizeFragment = function(build) {
if (!this._parts.fragment) {
this._parts.fragment = null;
this.build(!build);
}
return this;
};
p.normalizeSearch = p.normalizeQuery;
p.normalizeHash = p.normalizeFragment;
p.iso8859 = function() {
// expect unicode input, iso8859 output
var e = URI.encode;
var d = URI.decode;
URI.encode = escape;
URI.decode = decodeURIComponent;
try {
this.normalize();
} finally {
URI.encode = e;
URI.decode = d;
}
return this;
};
p.unicode = function() {
// expect iso8859 input, unicode output
var e = URI.encode;
var d = URI.decode;
URI.encode = strictEncodeURIComponent;
URI.decode = unescape;
try {
this.normalize();
} finally {
URI.encode = e;
URI.decode = d;
}
return this;
};
p.readable = function() {
var uri = this.clone();
// removing username, password, because they shouldn't be displayed according to RFC 3986
uri.username('').password('').normalize();
var t = '';
if (uri._parts.protocol) {
t += uri._parts.protocol + '://';
}
if (uri._parts.hostname) {
if (uri.is('punycode') && punycode) {
t += punycode.toUnicode(uri._parts.hostname);
if (uri._parts.port) {
t += ':' + uri._parts.port;
}
} else {
t += uri.host();
}
}
if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') {
t += '/';
}
t += uri.path(true);
if (uri._parts.query) {
var q = '';
for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) {
var kv = (qp[i] || '').split('=');
q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace)
.replace(/&/g, '%26');
if (kv[1] !== undefined) {
q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace)
.replace(/&/g, '%26');
}
}
t += '?' + q.substring(1);
}
t += URI.decodeQuery(uri.hash(), true);
return t;
};
// resolving relative and absolute URLs
p.absoluteTo = function(base) {
var resolved = this.clone();
var properties = ['protocol', 'username', 'password', 'hostname', 'port'];
var basedir, i, p;
if (this._parts.urn) {
throw new Error('URNs do not have any generally defined hierarchical components');
}
if (!(base instanceof URI)) {
base = new URI(base);
}
if (resolved._parts.protocol) {
// Directly returns even if this._parts.hostname is empty.
return resolved;
} else {
resolved._parts.protocol = base._parts.protocol;
}
if (this._parts.hostname) {
return resolved;
}
for (i = 0; (p = properties[i]); i++) {
resolved._parts[p] = base._parts[p];
}
if (!resolved._parts.path) {
resolved._parts.path = base._parts.path;
if (!resolved._parts.query) {
resolved._parts.query = base._parts.query;
}
} else {
if (resolved._parts.path.substring(-2) === '..') {
resolved._parts.path += '/';
}
if (resolved.path().charAt(0) !== '/') {
basedir = base.directory();
basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : '';
resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path;
resolved.normalizePath();
}
}
resolved.build();
return resolved;
};
p.relativeTo = function(base) {
var relative = this.clone().normalize();
var relativeParts, baseParts, common, relativePath, basePath;
if (relative._parts.urn) {
throw new Error('URNs do not have any generally defined hierarchical components');
}
base = new URI(base).normalize();
relativeParts = relative._parts;
baseParts = base._parts;
relativePath = relative.path();
basePath = base.path();
if (relativePath.charAt(0) !== '/') {
throw new Error('URI is already relative');
}
if (basePath.charAt(0) !== '/') {
throw new Error('Cannot calculate a URI relative to another relative URI');
}
if (relativeParts.protocol === baseParts.protocol) {
relativeParts.protocol = null;
}
if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) {
return relative.build();
}
if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) {
return relative.build();
}
if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) {
relativeParts.hostname = null;
relativeParts.port = null;
} else {
return relative.build();
}
if (relativePath === basePath) {
relativeParts.path = '';
return relative.build();
}
// determine common sub path
common = URI.commonPath(relativePath, basePath);
// If the paths have nothing in common, return a relative URL with the absolute path.
if (!common) {
return relative.build();
}
var parents = baseParts.path
.substring(common.length)
.replace(/[^\/]*$/, '')
.replace(/.*?\//g, '../');
relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './';
return relative.build();
};
// comparing URIs
p.equals = function(uri) {
var one = this.clone();
var two = new URI(uri);
var one_map = {};
var two_map = {};
var checked = {};
var one_query, two_query, key;
one.normalize();
two.normalize();
// exact match
if (one.toString() === two.toString()) {
return true;
}
// extract query string
one_query = one.query();
two_query = two.query();
one.query('');
two.query('');
// definitely not equal if not even non-query parts match
if (one.toString() !== two.toString()) {
return false;
}
// query parameters have the same length, even if they're permuted
if (one_query.length !== two_query.length) {
return false;
}
one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace);
two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace);
for (key in one_map) {
if (hasOwn.call(one_map, key)) {
if (!isArray(one_map[key])) {
if (one_map[key] !== two_map[key]) {
return false;
}
} else if (!arraysEqual(one_map[key], two_map[key])) {
return false;
}
checked[key] = true;
}
}
for (key in two_map) {
if (hasOwn.call(two_map, key)) {
if (!checked[key]) {
// two contains a parameter not present in one
return false;
}
}
}
return true;
};
// state
p.preventInvalidHostname = function(v) {
this._parts.preventInvalidHostname = !!v;
return this;
};
p.duplicateQueryParameters = function(v) {
this._parts.duplicateQueryParameters = !!v;
return this;
};
p.escapeQuerySpace = function(v) {
this._parts.escapeQuerySpace = !!v;
return this;
};
return URI;
}));
} (URI));
var URIExports = URI.exports;
var Uri = /*@__PURE__*/getDefaultExportFromCjs(URIExports);
const TiandituMapsStyleUrl = {};
const TiandituMapsStyleLayer = {};
const TiandituMapsStyleID = {};
const TiandituMapsStyleFormat = {};
const TiandituMapsStyleEPSG = {};
const TiandituMapsStyleLabels = {};
class TiandituImageryProvider {
constructor(options) {
Object.keys(TiandituMapsStyle).forEach((key) => {
TiandituMapsStyleUrl[TiandituMapsStyle[key]] = options.protocol + "://{s}.tianditu.gov.cn/" + TiandituMapsStyle[key] + "/wmts";
TiandituMapsStyleLayer[TiandituMapsStyle[key]] = TiandituMapsStyle[key].slice(0, 3);
TiandituMapsStyleID[TiandituMapsStyle[key]] = TiandituMapsStyle[key].slice(4);
TiandituMapsStyleFormat[TiandituMapsStyle[key]] = "tiles";
if (TiandituMapsStyleID[TiandituMapsStyle[key]] === "w") {
TiandituMapsStyleEPSG[TiandituMapsStyle[key]] = "900913";
} else {
TiandituMapsStyleEPSG[TiandituMapsStyle[key]] = "4490";
}
switch (TiandituMapsStyle[key]) {
case "img_w":
case "img_c":
case "cia_w":
case "cia_c":
case "cta_w":
case "cta_c":
TiandituMapsStyleLabels[TiandituMapsStyle[key]] = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18"
];
break;
case "vec_w":
case "vec_c":
case "cva_w":
case "cva_c":
TiandituMapsStyleLabels[TiandituMapsStyle[key]] = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19"
];
break;
case "ter_w":
case "ter_c":
TiandituMapsStyleLabels[TiandituMapsStyle[key]] = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"];
break;
case "eia_w":
case "eia_c":
case "eva_w":
case "eva_c":
case "ibo_c":
case "ibo_w":
TiandituMapsStyleLabels[TiandituMapsStyle[key]] = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
break;
}
});
const { Credit, Resource, defaultValue, Event, GeographicTilingScheme, WebMercatorTilingScheme } = Cesium;
options = defaultValue(options, {});
this._mapStyle = defaultValue(options.mapStyle, TiandituMapsStyle.IMG_W);
this._url = options.url || defaultValue(options.url, TiandituMapsStyleUrl[this._mapStyle]);
const resource = Resource.createIfNeeded(this._url);
resource.appendForwardSlash();
this._ready = false;
this._resource = resource;
this._token = options.token;
this._layer = defaultValue(options.layer, TiandituMapsStyleLayer[this._mapStyle]);
this._style = defaultValue(options.style, "default");
this._tileMatrixSetID = defaultValue(options.tileMatrixSetID, TiandituMapsStyleID[this._mapStyle]);
this._tileMatrixLabels = defaultValue(options.tileMatrixLabels, TiandituMapsStyleLabels[this._mapStyle]);
this._format = defaultValue(options.format, TiandituMapsStyleFormat[this._mapStyle]);
this._epsgCode = TiandituMapsStyleEPSG[this._mapStyle];
this._tilingScheme = this._epsgCode === "900913" ? new WebMercatorTilingScheme() : new GeographicTilingScheme();
this._tileWidth = defaultValue(options.tileWidth, 256);
this._tileHeight = defaultValue(options.tileHeight, 256);
this._minimumLevel = defaultValue(options.minimumLevel, 0);
this._maximumLevel = defaultValue(options.maximumLevel, TiandituMapsStyleLabels[this._mapStyle].length);
this._rectangle = defaultValue(options.rectangle, this._tilingScheme.rectangle);
this._errorEvent = new Event();
const credit = defaultValue(options.credit, "\u5929\u5730\u56FE\u5168\u7403\u5F71\u50CF\u670D\u52A1");
this._credit = typeof credit === "string" ? new Credit(credit) : credit;
this._subdomains = defaultValue(options.subdomains, ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"]);
this._tileDiscardPolicy = options.tileDiscardPolicy;
this._ready = true;
}
getTileCredits(x, y, level) {
if (!this.ready) {
throw new Cesium.DeveloperError("getTileCredits must not be called before the imagery provider is ready.");
}
return void 0;
}
requestImage(x, y, level, request) {
if (!this.ready) {
throw new Cesium.DeveloperError("requestImage must not be called before the imagery provider is ready.");
}
const url = buildImageResource.call(this, x, y, level, request);
return Cesium.ImageryProvider.loadImage(this, url);
}
pickFeatures(x, y, level, longitude, latitude) {
return void 0;
}
get url() {
return this._resource.url;
}
get proxy() {
return this._resource.proxy;
}
get mapStyle() {
return this._mapStyle;
}
get tileWidth() {
return this._tileWidth;
}
get tileHeight() {
return this._tileHeight;
}
get maximumLevel() {
return this._maximumLevel;
}
get minimumLevel() {
return this._minimumLevel;
}
get tilingScheme() {
return this._tilingScheme;
}
get rectangle() {
return this._rectangle;
}
get errorEvent() {
return this._errorEvent;
}
get ready() {
return true;
}
// get readyPromise() {
// // return this._readyPromise
// }
get credit() {
return this._credit;
}
get hasAlphaChannel() {
return true;
}
get tileDiscardPolicy() {
return this._tileDiscardPolicy;
}
}
function buildImageResource(x, y, level, request) {
var _a;
const { combine, defined, defaultValue, queryToObject, objectToQuery } = Cesium;
const freezeObject = Object.freeze;
const options = freezeObject({
service: "WMTS",
version: "1.0.0",
request: "GetTile"
});
this._epsgCode === "900913" && (level -= 1);
const tileMatrixLabels = this._tileMatrixLabels;
const tileMatrixLabel = defined(tileMatrixLabels) ? tileMatrixLabels[level] : level.toString();
const subdomains = this._subdomains;
let url = this._url.replace("{s}", subdomains[(x + y + level) % subdomains.length]);
const uri = new Uri(url);
let obj = queryToObject(defaultValue((_a = uri.query) == null ? void 0 : _a.call(uri), ""));
obj = combine(options, obj);
obj.tilematrix = tileMatrixLabel;
obj.layer = this._layer;
obj.style = this._style;
obj.tilerow = y;
obj.tilecol = x;
obj.tilematrixset = this._tileMatrixSetID;
obj.format = this._format;
const query = objectToQuery(obj);
url = uri.toString() + "?" + query;
defined(this._proxy) && (url = this._proxy.getURL(url));
defined(this._token) && (url += "&tk=" + this._token);
const resource = this._resource.getDerivedResource({
url,
request
});
return resource;
}
const tiandituImageryProviderProps = exports('tiandituImageryProviderProps', {
...url,
...minimumLevel,
...maximumLevel,
...rectangle,
mapStyle: {
type: String,
default: "img_w",
validator: (v) => [
"cia_c",
"cia_w",
"cta_c",
"cta_w",
"cva_c",
"cva_w",
"eia_c",
"eia_w",
"eva_c",
"eva_w",
"img_c",
"img_w",
"ter_c",
"ter_w",
"vec_c",
"vec_w",
"ibo_c",
"ibo_w"
].includes(v)
},
token: String,
protocol: {
type: String,
default: "https"
},
credit: {
type: [String, Object],
default: "\u5929\u5730\u56FE\u5168\u7403\u5F71\u50CF\u670D\u52A1"
},
...projectionTransforms
});
var ImageryProviderTianditu = defineComponent({
name: "VcImageryProviderTianditu",
props: tiandituImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "TiandituImageryProvider";
const providersState = useProviders(props, ctx, instance);
if (void 0 === providersState) {
return;
}
instance.createCesiumObject = async () => {
Cesium.TiandituImageryProvider = Cesium.TiandituImageryProvider || TiandituImageryProvider;
if (providersState.unwatchFns.length === 0) {
providersState.setPropsWatcher(true);
}
const options = providersState.transformProps(props);
return new Cesium.TiandituImageryProvider(options);
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const tileCoordinatesImageryProviderProps = exports('tileCoordinatesImageryProviderProps', {
...tilingScheme,
...ellipsoid,
color: {
type: [Object, String, Array],
default: "YELLOW"
},
...tileWidth,
...tileHeight
});
var ImageryProviderTileCoordinates = defineComponent({
name: "VcImageryProviderTileCoordinates",
props: tileCoordinatesImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "TileCoordinatesImageryProvider";
useProviders(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const tmsImageryProviderProps = exports('tmsImageryProviderProps', {
url: [String, Object],
...fileExtension,
...credit,
...minimumLevel,
...maximumLevel,
...rectangle,
...tilingScheme,
...ellipsoid,
...tileWidth,
...tileHeight,
flipXY: Boolean,
...projectionTransforms
});
var ImageryProviderTms = defineComponent({
name: "VcImageryProviderTms",
props: tmsImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "TileMapServiceImageryProvider";
useProviders(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const tiledcacheImageryProviderProps = exports('tiledcacheImageryProviderProps', {
...url,
...format,
...credit,
...minimumLevel,
...maximumLevel,
...rectangle,
...tilingScheme,
...ellipsoid,
...tileWidth,
...tileHeight,
dir: {
type: String,
reqiured: true
},
scales: {
type: Array,
default: () => {
return [
1 / 295829355,
1 / 147914678,
1 / 73957339,
1 / 36978669,
1 / 18489335,
1 / 9244667,
1 / 4622334,
1 / 2311167,
1 / 1155583,
1 / 577792,
1 / 288896,
1 / 144448,
1 / 72224,
1 / 36112,
1 / 18056,
1 / 9026,
1 / 4514
];
}
}
});
var ImageryProviderTiledcache = defineComponent({
name: "VcImageryProviderTiledcache",
props: tiledcacheImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "UrlTemplateImageryProvider";
const providersState = useProviders(props, ctx, instance);
if (void 0 === providersState) {
return;
}
instance.createCesiumObject = async () => {
const options = providersState.transformProps(props);
const { Credit, defined, defaultValue, DeveloperError, Ellipsoid, GeographicTilingScheme, Rectangle, Resource, UrlTemplateImageryProvider } = Cesium;
const { url: url2, dir, format: format2 } = options;
if (!defined(url2)) {
throw new DeveloperError("options.url is required.");
}
if (!defined(dir)) {
throw new DeveloperError("options.dir is required.");
}
const resource = Resource.createIfNeeded(url2);
resource.url += `?dir=${dir}&scale={scale}&col={x}&row={y}&format=${format2}`;
const tilingScheme2 = defaultValue(
options.tilingScheme,
new GeographicTilingScheme({
ellipsoid: defaultValue(options.ellipsoid, Ellipsoid.WGS84),
numberOfLevelZeroTilesX: 2,
numberOfLevelZeroTilesY: 1
})
);
const tileWidth2 = defaultValue(options.tileWidth, 256);
const tileHeight2 = defaultValue(options.tileHeight, 256);
const maximumLevel2 = options.maximumLevel;
const minimumLevel2 = defaultValue(options.minimumLevel, 0);
const rectangle2 = defaultValue(options.rectangle, tilingScheme2.rectangle);
const swTile = tilingScheme2.positionToTileXY(Rectangle.southwest(rectangle2), minimumLevel2);
const neTile = tilingScheme2.positionToTileXY(Rectangle.northeast(rectangle2), minimumLevel2);
const tileCount = (Math.abs(neTile.x - swTile.x) + 1) * (Math.abs(neTile.y - swTile.y) + 1);
if (tileCount > 4) {
throw new DeveloperError(
"The rectangle and minimumLevel indicate that there are " + tileCount + " tiles at the minimum level. Imagery providers with more than four tiles at the minimum level are not supported."
);
}
let credit2 = defaultValue(options.credit, "");
if (typeof credit2 === "string") {
credit2 = new Credit(credit2);
}
return new UrlTemplateImageryProvider({
url: resource,
credit: credit2,
tilingScheme: tilingScheme2,
tileWidth: tileWidth2,
tileHeight: tileHeight2,
minimumLevel: minimumLevel2,
maximumLevel: maximumLevel2,
rectangle: rectangle2,
customTags: {
scale: (imageryProvider, x, y, level) => {
const s = 1 / props.scales[level];
return padWithZerosIfNecessary(imageryProvider, "{scale}", s);
}
}
});
};
const padWithZerosIfNecessary = (imageryProvider, key, value) => {
if (imageryProvider && imageryProvider.urlSchemeZeroPadding && Object.prototype.hasOwnProperty.call(imageryProvider.urlSchemeZeroPadding, key)) {
const paddingTemplate = imageryProvider.urlSchemeZeroPadding[key];
if (typeof paddingTemplate === "string") {
const paddingTemplateWidth = paddingTemplate.length;
if (paddingTemplateWidth > 1) {
value = value.length >= paddingTemplateWidth ? value : new Array(paddingTemplateWidth - value.toString().length + 1).join("0") + value;
}
}
}
return value;
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const urltemplateImageryProviderProps = exports('urltemplateImageryProviderProps', {
...url,
pickFeaturesUrl: [String, Object],
urlSchemeZeroPadding: Object,
...subdomains,
...credit,
...minimumLevel,
...maximumLevel,
...rectangle,
...tilingScheme,
...ellipsoid,
...tileWidth,
...tileHeight,
hasAlphaChannel: {
type: Boolean,
default: true
},
...getFeatureInfoFormats,
...enablePickFeatures,
customTags: Object,
...projectionTransforms
});
var ImageryProviderUrltemplate = defineComponent({
name: "VcImageryProviderUrltemplate",
props: urltemplateImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "UrlTemplateImageryProvider";
useProviders(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const wmsImageryProviderProps = exports('wmsImageryProviderProps', {
...url,
...layers,
parameters: Object,
getFeatureInfoParameters: Object,
...enablePickFeatures,
...getFeatureInfoFormats,
...rectangle,
...tilingScheme,
...ellipsoid,
...tileWidth,
...tileHeight,
...minimumLevel,
...maximumLevel,
crs: String,
srs: String,
...credit,
...subdomains,
...clock,
...times,
getFeatureInfoUrl: [String, Object]
});
var ImageryProviderWms = defineComponent({
name: "VcImageryProviderWms",
props: wmsImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "WebMapServiceImageryProvider";
useProviders(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const wmtsImageryProviderProps = exports('wmtsImageryProviderProps', {
...url,
...format,
layer: {
type: String,
required: true
},
wmtsStyle: {
type: String,
required: true
},
tileMatrixSetID: {
type: String,
required: true
},
tileMatrixLabels: Array,
...clock,
...times,
dimensions: Object,
...tileWidth,
...tileHeight,
...tilingScheme,
...rectangle,
...minimumLevel,
...maximumLevel,
...ellipsoid,
...credit,
...subdomains
});
var ImageryProviderWmts = defineComponent({
name: "VcImageryProviderWmts",
props: wmtsImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "WebMapTileServiceImageryProvider";
useProviders(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const cesiumTerrainProviderProps = exports('cesiumTerrainProviderProps', {
url: [String, Object],
requestVertexNormals: {
type: Boolean,
default: false
},
requestWaterMask: {
type: Boolean,
default: false
},
requestMetadata: {
type: Boolean,
default: true
},
assetId: Number,
...ellipsoid,
...credit
});
var TerrainProviderCesium = defineComponent({
name: "VcTerrainProviderCesium",
props: cesiumTerrainProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "CesiumTerrainProvider";
const providersState = useProviders(props, ctx, instance);
if (void 0 === providersState) {
return;
}
instance.createCesiumObject = async () => {
if (providersState.unwatchFns.length === 0) {
providersState.setPropsWatcher(true);
}
const options = providersState.transformProps(props);
if (Cesium.defined(props.assetId) && typeof Cesium[instance.cesiumClass].fromIonAssetId === "function") {
return await Cesium.CesiumTerrainProvider.fromIonAssetId(props.assetId, options);
} else {
if (typeof Cesium[instance.cesiumClass].fromUrl === "function") {
return Cesium.defined(options.url) ? await Cesium.CesiumTerrainProvider.fromUrl(options.url, options) : await Cesium.createWorldTerrainAsync({ requestVertexNormals: options.requestVertexNormals, requestWaterMask: options.requestWaterMask });
} else {
return Cesium.defined(options.url) ? new Cesium.CesiumTerrainProvider(options) : Cesium.createWorldTerrain({ requestVertexNormals: options.requestVertexNormals, requestWaterMask: options.requestWaterMask });
}
}
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const arcgisTerrainProviderProps = exports('arcgisTerrainProviderProps', {
url: {
type: [String, Object],
default: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"
},
...ellipsoid,
...token
});
var TerrainProviderArcgis = defineComponent({
name: "VcTerrainProviderArcgis",
props: arcgisTerrainProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "ArcGISTiledElevationTerrainProvider";
useProviders(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const vrTheworldImageryProviderProps = exports('vrTheworldImageryProviderProps', {
url: {
type: [String, Object],
default: "https://www.vr-theworld.com/vr-theworld/tiles1.0.0/73/"
},
...ellipsoid,
...credit
});
var TerrainProviderVrTheworld = defineComponent({
name: "VcTerrainProviderVrTheworld",
props: vrTheworldImageryProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VRTheWorldTerrainProvider";
useProviders(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const tiandituTerrainProviderProps = exports('tiandituTerrainProviderProps', {
url: {
type: String,
default: "https://{s}.tianditu.gov.cn/"
},
subdomains: {
type: Array,
default: () => ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"]
},
pluginPath: {
type: String,
default: "https://api.tianditu.gov.cn/cdn/plugins/cesium/cesiumTdt.js"
},
dataType: {
type: String,
default: "int",
validator: (v) => ["int", "float"].includes(v)
},
tileType: {
type: String,
default: "heightmap",
validator: (v) => ["heightmap", "quantized-mesh"].includes(v)
},
token: String
});
var TerrainProviderTianditu = defineComponent({
name: "VcTerrainProviderTianditu",
props: tiandituTerrainProviderProps,
emits: providerEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "GeoTerrainProvider";
const providersState = useProviders(props, ctx, instance);
if (void 0 === providersState) {
return;
}
const { emit } = ctx;
const vc = useVueCesium();
let $script;
instance.createCesiumObject = async () => {
return new Promise((resolve, reject) => {
$script = document.createElement("script");
document.body.appendChild($script);
$script.src = props.pluginPath;
$script.onload = () => {
if (providersState.unwatchFns.length === 0) {
providersState.setPropsWatcher(true);
}
const terrainUrls = [];
for (let i = 0; i < props.subdomains.length; i++) {
const url = props.url.replace("{s}", props.subdomains[i]) + "mapservice/swdx?tk=" + props.token;
terrainUrls.push(url);
}
resolve(
new Cesium.GeoTerrainProvider({
urls: terrainUrls
})
);
};
});
};
instance.unmount = async () => {
var _a;
const terrainProvider = new Cesium.EllipsoidTerrainProvider();
(_a = terrainProvider == null ? void 0 : terrainProvider.readyPromise) == null ? void 0 : _a.then(() => {
const listener = getInstanceListener(instance, "readyPromise");
listener && emit("readyPromise", terrainProvider, vc == null ? void 0 : vc.viewer, instance.proxy);
});
vc && (vc.viewer.terrainProvider = terrainProvider);
$script == null ? void 0 : $script.parentNode.removeChild($script);
return true;
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const components$4 = [
ImageryProviderAmap,
ImageryProviderArcgis,
ImageryProviderBaidu,
ImageryProviderBing,
ImageryProviderGoogle,
ImageryProviderGrid,
ImageryProviderIon,
ImageryProviderMapbox,
ImageryProviderOsm,
ImageryProviderSingletile,
ImageryProviderSupermap,
ImageryProviderTencent,
ImageryProviderTianditu,
ImageryProviderTileCoordinates,
ImageryProviderTms,
ImageryProviderTiledcache,
ImageryProviderUrltemplate,
ImageryProviderWms,
ImageryProviderWmts,
TerrainProviderCesium,
TerrainProviderArcgis,
TerrainProviderVrTheworld,
TerrainProviderTianditu
];
components$4.forEach((cmp) => {
cmp["install"] = (app) => {
app.component(cmp.name, cmp);
};
});
const VcImageryProviderAmap = exports('VcImageryProviderAmap', ImageryProviderAmap);
const VcImageryProviderArcgis = exports('VcImageryProviderArcgis', ImageryProviderArcgis);
const VcImageryProviderBaidu = exports('VcImageryProviderBaidu', ImageryProviderBaidu);
const VcImageryProviderBing = exports('VcImageryProviderBing', ImageryProviderBing);
const VcImageryProviderGoogle = exports('VcImageryProviderGoogle', ImageryProviderGoogle);
const VcImageryProviderGrid = exports('VcImageryProviderGrid', ImageryProviderGrid);
const VcImageryProviderIon = exports('VcImageryProviderIon', ImageryProviderIon);
const VcImageryProviderMapbox = exports('VcImageryProviderMapbox', ImageryProviderMapbox);
const VcImageryProviderOsm = exports('VcImageryProviderOsm', ImageryProviderOsm);
const VcImageryProviderSingletile = exports('VcImageryProviderSingletile', ImageryProviderSingletile);
const VcImageryProviderSupermap = exports('VcImageryProviderSupermap', ImageryProviderSupermap);
const VcImageryProviderTencent = exports('VcImageryProviderTencent', ImageryProviderTencent);
const VcImageryProviderTianditu = exports('VcImageryProviderTianditu', ImageryProviderTianditu);
const VcImageryProviderTileCoordinates = exports('VcImageryProviderTileCoordinates', ImageryProviderTileCoordinates);
const VcImageryProviderTms = exports('VcImageryProviderTms', ImageryProviderTms);
const VcImageryProviderTiledcache = exports('VcImageryProviderTiledcache', ImageryProviderTiledcache);
const VcImageryProviderUrltemplate = exports('VcImageryProviderUrltemplate', ImageryProviderUrltemplate);
const VcImageryProviderWms = exports('VcImageryProviderWms', ImageryProviderWms);
const VcImageryProviderWmts = exports('VcImageryProviderWmts', ImageryProviderWmts);
const VcTerrainProviderCesium = exports('VcTerrainProviderCesium', TerrainProviderCesium);
const VcTerrainProviderArcgis = exports('VcTerrainProviderArcgis', TerrainProviderArcgis);
const VcTerrainProviderVrTheworld = exports('VcTerrainProviderVrTheworld', TerrainProviderVrTheworld);
const VcTerrainProviderTianditu = exports('VcTerrainProviderTianditu', TerrainProviderTianditu);
const customDatasourceProps = exports('customDatasourceProps', {
...show,
...enableMouseEvent,
entities: {
type: Array,
default: () => []
},
name: String,
destroy: {
type: Boolean,
default: false
}
});
var DatasourceCustom = defineComponent({
name: "VcDatasourceCustom",
props: customDatasourceProps,
emits: datasourceEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "CustomDataSource";
useDatasources(props, ctx, instance);
instance.createCesiumObject = async () => {
return new Cesium.CustomDataSource(props.name);
};
return () => {
var _a, _b;
return ctx.slots.default ? h(
"i",
{
class: kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(((_b = instance.proxy) == null ? void 0 : _b.$options.name) || ""));
};
}
});
const czmlDatasourceProps = exports('czmlDatasourceProps', {
...show,
...enableMouseEvent,
entities: {
type: Array,
default: () => []
},
czml: {
type: [String, Object, Array],
required: true
},
...sourceUri,
...credit,
destroy: {
type: Boolean,
default: false
}
});
var DatasourceCzml = defineComponent({
name: "VcDatasourceCzml",
props: czmlDatasourceProps,
emits: datasourceEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "CzmlDataSource";
const datasourcesState = useDatasources(props, ctx, instance);
if (void 0 === datasourcesState) {
return;
}
instance.createCesiumObject = async () => {
const options = datasourcesState.transformProps(props);
return Cesium.CzmlDataSource.load(props.czml, options);
};
return () => {
var _a, _b;
return ctx.slots.default ? h(
"i",
{
class: kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(((_b = instance.proxy) == null ? void 0 : _b.$options.name) || ""));
};
}
});
const geojsonDatasourceProps = exports('geojsonDatasourceProps', {
...show,
...enableMouseEvent,
entities: {
type: Array,
default: () => []
},
...data,
...sourceUri,
describe: [Function, Object],
markerSize: {
type: Number,
default: 48
},
markerSymbol: String,
markerColor: {
type: [Object, String, Array],
default: () => ({ x: 0.2549019607843137, y: 0.4117647058823529, z: 0.8823529411764706 }),
watcherOptions: {
cesiumObjectBuilder: makeColor
}
},
stroke: {
type: [Object, String, Array],
default: () => ({ x: 1, y: 1, z: 0 }),
watcherOptions: {
cesiumObjectBuilder: makeColor
}
},
strokeWidth: {
type: Number,
default: 2
},
fill: {
type: [Object, String, Array],
default: () => ({ x: 1, y: 1, z: 0, w: 0.39215686274509803 }),
watcherOptions: {
cesiumObjectBuilder: makeColor
}
},
...clampToGround,
...credit,
destroy: {
type: Boolean,
default: false
}
});
var DatasourceGeojson = defineComponent({
name: "VcDatasourceGeojson",
props: geojsonDatasourceProps,
emits: datasourceEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "GeoJsonDataSource";
const datasourcesState = useDatasources(props, ctx, instance);
if (void 0 === datasourcesState) {
return;
}
instance.createCesiumObject = async () => {
const options = datasourcesState.transformProps(props);
return Cesium.GeoJsonDataSource.load(props.data, options);
};
return () => {
var _a, _b;
return ctx.slots.default ? h(
"i",
{
class: kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(((_b = instance.proxy) == null ? void 0 : _b.$options.name) || ""));
};
}
});
const kmlDatasourceProps = exports('kmlDatasourceProps', {
...show,
...enableMouseEvent,
entities: {
type: Array,
default: () => []
},
...data,
camera: Object,
canvas: HTMLCanvasElement,
...sourceUri,
...clampToGround,
...ellipsoid,
...credit,
destroy: {
type: Boolean,
default: false
},
screenOverlayContainer: [Element, String]
});
var DatasourceKml = defineComponent({
name: "VcDatasourceKml",
props: kmlDatasourceProps,
emits: datasourceEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "KmlDataSource";
const datasourcesState = useDatasources(props, ctx, instance);
const vc = useVueCesium();
instance.createCesiumObject = async () => {
const options = datasourcesState == null ? void 0 : datasourcesState.transformProps(props);
if (!options.camera) {
options.camera = vc == null ? void 0 : vc.viewer.camera;
}
if (!options.canvas) {
options.canvas = vc == null ? void 0 : vc.viewer.canvas;
}
return Cesium.KmlDataSource.load(props.data || "", options);
};
return () => {
var _a, _b;
return ctx.slots.default ? h(
"i",
{
class: kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(((_b = instance.proxy) == null ? void 0 : _b.$options.name) || ""));
};
}
});
const components$3 = [DatasourceCustom, DatasourceCzml, DatasourceGeojson, DatasourceKml];
components$3.forEach((cmp) => {
cmp["install"] = (app) => {
app.component(cmp.name, cmp);
};
});
const VcDatasourceCustom = exports('VcDatasourceCustom', DatasourceCustom);
const VcDatasourceCzml = exports('VcDatasourceCzml', DatasourceCzml);
const VcDatasourceGeojson = exports('VcDatasourceGeojson', DatasourceGeojson);
const VcDatasourceKml = exports('VcDatasourceKml', DatasourceKml);
const billboarGraphicsProps = exports('billboarGraphicsProps', {
...image,
...scale,
...pixelOffset,
...eyeOffset,
...horizontalOrigin,
...verticalOrigin,
...heightReference,
...color,
...rotation,
...alignedAxis,
...sizeInMeters,
...width,
...height,
...scaleByDistance,
...translucencyByDistance,
...pixelOffsetScaleByDistance,
...disableDepthTestDistance,
...show,
...distanceDisplayCondition,
...imageSubRegion
});
var GraphicsBillboard = defineComponent({
name: "VcGraphicsBillboard",
props: billboarGraphicsProps,
emits: graphicsEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "BillboardGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const boxGraphicsProps = exports('boxGraphicsProps', {
...show,
...dimensions,
...heightReference,
...fill,
...material,
...outline,
...outlineColor,
...outlineWidth,
...shadows,
...distanceDisplayCondition
});
var GraphicsBox = defineComponent({
name: "VcGraphicsBox",
props: boxGraphicsProps,
emits: graphicsEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "BoxGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const corridorGraphicsProps = {
...show,
...positions,
...width,
...height,
...heightReference,
...extrudedHeight,
...extrudedHeightReference,
...cornerType,
...granularity,
...fill,
...material,
...outline,
...outlineColor,
...outlineWidth,
...shadows,
...distanceDisplayCondition,
...classificationType,
...zIndex
};
var GraphicsCorridor = defineComponent({
name: "VcGraphicsCorridor",
props: corridorGraphicsProps,
emits: graphicsEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "CorridorGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const cylinderGraphicsProps = exports('cylinderGraphicsProps', {
...show,
...length,
...topRadius,
...bottomRadius,
...heightReference,
...fill,
...material,
...outline,
...outlineColor,
...outlineWidth,
...numberOfVerticalLines,
...slices,
...shadows,
...distanceDisplayCondition
});
var GraphicsCylinder = defineComponent({
name: "VcGraphicsCylinder",
props: cylinderGraphicsProps,
emits: graphicsEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "CylinderGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const ellipseGraphicsProps = exports('ellipseGraphicsProps', {
...show,
...semiMajorAxis,
...semiMinorAxis,
...height,
...heightReference,
...extrudedHeight,
...extrudedHeightReference,
...rotation,
...stRotation,
...granularity,
...fill,
...material,
...outline,
...outlineColor,
...outlineWidth,
...numberOfVerticalLines,
...shadows,
...distanceDisplayCondition,
...classificationType,
...zIndex
});
var GraphicsEllipse = defineComponent({
name: "VcGraphicsEllipse",
props: ellipseGraphicsProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "EllipseGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const ellipsoidGraphicsProps = exports('ellipsoidGraphicsProps', {
...show,
...radii,
...innerRadii,
...minimumClock,
...maximumClock,
...minimumCone,
...maximumCone,
...heightReference,
...fill,
...material,
...outline,
...outlineColor,
...outlineWidth,
...stackPartitions,
...slicePartitions,
...subdivisions,
...shadows,
...distanceDisplayCondition
});
var GraphicsEllipsoid = defineComponent({
name: "VcGraphicsEllipsoid",
props: ellipsoidGraphicsProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "EllipsoidGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const labelGraphicsProps = exports('labelGraphicsProps', {
...show,
...text$7,
...font,
...labelStyle,
...scale,
...showBackground,
...backgroundColor,
...backgroundPadding,
...pixelOffset,
...eyeOffset,
...horizontalOrigin,
...verticalOrigin,
...heightReference,
...fillColor,
...outlineColor,
...outlineWidth,
...translucencyByDistance,
...pixelOffsetScaleByDistance,
...scaleByDistance,
...distanceDisplayCondition,
...disableDepthTestDistance
});
var GraphicsLabel = defineComponent({
name: "VcGraphicsLabel",
props: labelGraphicsProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "LabelGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const modelGraphicsProps = exports('modelGraphicsProps', {
...show,
...uri,
...scale,
...minimumPixelSize,
...maximumScale,
...incrementallyLoadTextures,
...runAnimations,
...clampAnimations,
...shadows,
...heightReference,
...silhouetteColor,
...silhouetteSize,
...color,
...colorBlendMode,
...colorBlendAmount,
...imageBasedLightingFactor,
...lightColor,
...distanceDisplayCondition,
...nodeTransformations,
...articulations,
...clippingPlanes
});
var GraphicsModel = defineComponent({
name: "VcGraphicsModel",
props: modelGraphicsProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "ModelGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const pathGraphicsProps = exports('pathGraphicsProps', {
...show,
leadTime: [Number, Object, Function],
trailTime: [Number, Object, Function],
...width,
resolution: {
type: [Number, Object, Function],
default: 60
},
...material,
...distanceDisplayCondition
});
var GraphicsPath = defineComponent({
name: "VcGraphicsPath",
props: pathGraphicsProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PathGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
const planeGraphicsProps = exports('planeGraphicsProps', {
...show,
...plane,
// 和 BoxGraphics.dimensions 区分
dimensions: {
type: [Object, Array, Function],
watcherOptions: {
cesiumObjectBuilder: makeCartesian2
}
},
...fill,
...material,
...outline,
...outlineColor,
...outlineWidth,
...shadows,
...distanceDisplayCondition
});
var GraphicsPlane = defineComponent({
name: "VcGraphicsPlane",
props: planeGraphicsProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PlaneGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const pointGraphicsProps = exports('pointGraphicsProps', {
...show,
...pixelSize,
...heightReference,
...color,
...outlineColor,
...outlineWidth,
...scaleByDistance,
...translucencyByDistance,
...distanceDisplayCondition,
...disableDepthTestDistance
});
var GraphicsPoint = defineComponent({
name: "VcGraphicsPoint",
props: pointGraphicsProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PointGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const polygonGraphicsProps = exports('polygonGraphicsProps', {
...show,
...hierarchy,
...height,
...heightReference,
...extrudedHeight,
...extrudedHeightReference,
...stRotation,
...granularity,
...fill,
...material,
...outline,
...outlineColor,
...outlineWidth,
...perPositionHeight,
...closeTop,
...closeBottom,
...arcType,
...shadows,
...distanceDisplayCondition,
...classificationType,
...zIndex
});
var GraphicsPolygon = defineComponent({
name: "VcGraphicsPolygon",
props: polygonGraphicsProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PolygonGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const polylineGraphicsProps = exports('polylineGraphicsProps', {
...show,
...positions,
...width,
...granularity,
...material,
...depthFailMaterial,
...arcType,
...clampToGround,
...shadows,
...distanceDisplayCondition,
...classificationType,
...zIndex
});
var GraphicsPolyline = defineComponent({
name: "VcGraphicsPolyline",
props: polylineGraphicsProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PolylineGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const polylineVolumeGraphicsProps = exports('polylineVolumeGraphicsProps', {
...show,
...positions,
...shape,
...cornerType,
...granularity,
...fill,
...material,
...outline,
...outlineColor,
...outlineWidth,
...shadows,
...distanceDisplayCondition
});
var GraphicsPolylineVolume = defineComponent({
name: "VcGraphicsPolylineVolume",
props: polylineVolumeGraphicsProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PolylineVolumeGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const rectangleGraphicsProps = exports('rectangleGraphicsProps', {
...show,
...coordinates,
...height,
...heightReference,
...extrudedHeight,
...extrudedHeightReference,
...rotation,
...stRotation,
...granularity,
...fill,
...material,
...outline,
...outlineColor,
...outlineWidth,
...shadows,
...distanceDisplayCondition,
...classificationType,
...zIndex
});
var GraphicsRectangle = defineComponent({
name: "VcGraphicsRectangle",
props: rectangleGraphicsProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "RectangleGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const tilesetGraphicsProps = exports('tilesetGraphicsProps', {
...show,
...uri,
...maximumScreenSpaceError
});
var GraphicsTileset = defineComponent({
name: "VcGraphicsTileset",
props: tilesetGraphicsProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "Cesium3DTilesetGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const wallGraphicsProps = exports('wallGraphicsProps', {
...show,
...positions,
...minimumHeights,
...maximumHeights,
...granularity,
...fill,
...material,
...outline,
...outlineColor,
...outlineWidth,
...shadows,
...distanceDisplayCondition
});
var GraphicsWall = defineComponent({
name: "VcGraphicsWall",
props: wallGraphicsProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "WallGraphics";
useGraphics(props, ctx, instance);
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || "v-if"));
};
}
});
const components$2 = [
GraphicsBillboard,
GraphicsBox,
GraphicsCorridor,
GraphicsCylinder,
GraphicsEllipse,
GraphicsEllipsoid,
GraphicsLabel,
GraphicsModel,
GraphicsPath,
GraphicsPlane,
GraphicsPoint,
GraphicsPolygon,
GraphicsPolyline,
GraphicsPolylineVolume,
GraphicsRectangle,
GraphicsTileset,
GraphicsWall
];
components$2.forEach((cmp) => {
cmp["install"] = (app) => {
app.component(cmp.name, cmp);
};
});
const VcGraphicsBillboard = exports('VcGraphicsBillboard', GraphicsBillboard);
const VcGraphicsBox = exports('VcGraphicsBox', GraphicsBox);
const VcGraphicsCorridor = exports('VcGraphicsCorridor', GraphicsCorridor);
const VcGraphicsCylinder = exports('VcGraphicsCylinder', GraphicsCylinder);
const VcGraphicsEllipse = exports('VcGraphicsEllipse', GraphicsEllipse);
const VcGraphicsEllipsoid = exports('VcGraphicsEllipsoid', GraphicsEllipsoid);
const VcGraphicsLabel = exports('VcGraphicsLabel', GraphicsLabel);
const VcGraphicsModel = exports('VcGraphicsModel', GraphicsModel);
const VcGraphicsPath = exports('VcGraphicsPath', GraphicsPath);
const VcGraphicsPlane = exports('VcGraphicsPlane', GraphicsPlane);
const VcGraphicsPoint = exports('VcGraphicsPoint', GraphicsPoint);
const VcGraphicsPolygon = exports('VcGraphicsPolygon', GraphicsPolygon);
const VcGraphicsPolyline = exports('VcGraphicsPolyline', GraphicsPolyline);
const VcGraphicsPolylineVolume = exports('VcGraphicsPolylineVolume', GraphicsPolylineVolume);
const VcGraphicsRectangle = exports('VcGraphicsRectangle', GraphicsRectangle);
const VcGraphicsTileset = exports('VcGraphicsTileset', GraphicsTileset);
const VcGraphicsWall = exports('VcGraphicsWall', GraphicsWall);
const defaultProps = {
fragmentShader: String,
uniforms: Object,
textureScale: {
type: Number,
default: 1
},
forcePowerOfTwo: {
type: Boolean,
default: false
},
sampleMode: Number,
pixelFormat: Number,
pixelDatatype: Number,
...clearColor,
...scissorRectangle,
name: String
};
const postProcessStageProps = exports('postProcessStageProps', defaultProps);
var PostProcessStage = defineComponent({
name: "VcPostProcessStage",
props: postProcessStageProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PostProcessStage";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { $services } = commonState;
instance.mount = async () => {
const { postProcessStages } = $services;
const stage = postProcessStages.add(instance.cesiumObject);
return postProcessStages.contains(stage);
};
instance.unmount = async () => {
const { postProcessStages } = $services;
return postProcessStages == null ? void 0 : postProcessStages.remove(instance.cesiumObject);
};
return () => {
var _a;
return createCommentVNode(kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
};
}
});
var shaderSource$1 = `
uniform sampler2D colorTexture;
uniform sampler2D depthTexture;
in vec2 v_textureCoordinates;
uniform vec4 u_scanCenterEC;
uniform vec3 u_scanPlaneNormalEC;
uniform vec3 u_scanLineNormalEC;
uniform float u_radius;
uniform vec4 u_scanColor;
vec4 toEye(in vec2 uv, in float depth)
{
vec2 xy = vec2((uv.x * 2.0 - 1.0),(uv.y * 2.0 - 1.0));
vec4 posInCamera =czm_inverseProjection * vec4(xy, depth, 1.0);
posInCamera =posInCamera / posInCamera.w;
return posInCamera;
}
bool isPointOnLineRight(in vec3 ptOnLine, in vec3 lineNormal, in vec3 testPt)
{
vec3 v01 = testPt - ptOnLine;
normalize(v01);
vec3 temp = cross(v01, lineNormal);
float d = dot(temp, u_scanPlaneNormalEC);
return d > 0.5;
}
vec3 pointProjectOnPlane(in vec3 planeNormal, in vec3 planeOrigin, in vec3 point)
{
vec3 v01 = point -planeOrigin;
float d = dot(planeNormal, v01) ;
return (point - planeNormal * d);
}
float distancePointToLine(in vec3 ptOnLine, in vec3 lineNormal, in vec3 testPt)
{
vec3 tempPt = pointProjectOnPlane(lineNormal, ptOnLine, testPt);
return length(tempPt - ptOnLine);
}
float getDepth(in vec4 depth)
{
float z_window = czm_unpackDepth(depth);
z_window = czm_reverseLogDepth(z_window);
float n_range = czm_depthRange.near;
float f_range = czm_depthRange.far;
return (2.0 * z_window - n_range - f_range) / (f_range - n_range);
}
void main()
{
out_FragColor = texture(colorTexture, v_textureCoordinates);
float depth = getDepth( texture(depthTexture, v_textureCoordinates));
vec4 viewPos = toEye(v_textureCoordinates, depth);
vec3 prjOnPlane = pointProjectOnPlane(u_scanPlaneNormalEC.xyz, u_scanCenterEC.xyz, viewPos.xyz);
float dis = length(prjOnPlane.xyz - u_scanCenterEC.xyz);
float twou_radius = u_radius * 2.0;
if(dis < u_radius)
{
float f0 = 1.0 -abs(u_radius - dis) / u_radius;
f0 = pow(f0, 64.0);
vec3 lineEndPt = vec3(u_scanCenterEC.xyz) + u_scanLineNormalEC * u_radius;
float f = 0.0;
if(isPointOnLineRight(u_scanCenterEC.xyz, u_scanLineNormalEC.xyz, prjOnPlane.xyz))
{
float dis1= length(prjOnPlane.xyz - lineEndPt);
f = abs(twou_radius -dis1) / twou_radius;
f = pow(f, 3.0);
}
out_FragColor = mix(out_FragColor, u_scanColor, f + f0);
}
}
`;
function useRadar($services) {
const webgl = (options) => {
var _a;
const { viewer } = $services;
const webgl2 = (_a = $services.viewer.scene.context) == null ? void 0 : _a.webgl2;
let shaderSourceText = shaderSource$1;
if (!webgl2) {
shaderSourceText = shaderSourceText.replace("in vec2 v_textureCoordinates;", "varying vec2 v_textureCoordinates;");
shaderSourceText = shaderSourceText.replace(/texture\(/g, "texture2D(");
shaderSourceText = shaderSourceText.replace(/out_FragColor/g, "gl_FragColor");
}
const cartographicCenter = Cesium.Cartographic.fromCartesian(options.position, viewer.scene.globe.ellipsoid);
const _Cartesian3Center = Cesium.Cartographic.toCartesian(cartographicCenter, viewer.scene.globe.ellipsoid);
const _Cartesian4Center = new Cesium.Cartesian4(_Cartesian3Center.x, _Cartesian3Center.y, _Cartesian3Center.z, 1);
const _CartographicCenter1 = new Cesium.Cartographic(cartographicCenter.longitude, cartographicCenter.latitude, cartographicCenter.height + 500);
const _Cartesian3Center1 = Cesium.Cartographic.toCartesian(_CartographicCenter1, viewer.scene.globe.ellipsoid);
const _Cartesian4Center1 = new Cesium.Cartesian4(_Cartesian3Center1.x, _Cartesian3Center1.y, _Cartesian3Center1.z, 1);
const _CartographicCenter2 = new Cesium.Cartographic(
cartographicCenter.longitude + Cesium.Math.toRadians(1e-3),
cartographicCenter.latitude,
cartographicCenter.height
);
const _Cartesian3Center2 = Cesium.Cartographic.toCartesian(_CartographicCenter2, viewer.scene.globe.ellipsoid);
const _Cartesian4Center2 = new Cesium.Cartesian4(_Cartesian3Center2.x, _Cartesian3Center2.y, _Cartesian3Center2.z, 1);
const _RotateQ = new Cesium.Quaternion();
const _RotateM = new Cesium.Matrix3();
const _time = (/* @__PURE__ */ new Date()).getTime();
const _scratchCartesian4Center = new Cesium.Cartesian4();
const _scratchCartesian4Center1 = new Cesium.Cartesian4();
const _scratchCartesian4Center2 = new Cesium.Cartesian4();
const _scratchCartesian3Normal = new Cesium.Cartesian3();
const _scratchCartesian3Normal1 = new Cesium.Cartesian3();
const uniforms = {
u_scanCenterEC: function() {
return Cesium.Matrix4.multiplyByVector(viewer.camera.viewMatrix, _Cartesian4Center, _scratchCartesian4Center);
},
u_scanPlaneNormalEC: function() {
const temp = Cesium.Matrix4.multiplyByVector(viewer.camera.viewMatrix, _Cartesian4Center, _scratchCartesian4Center);
const temp1 = Cesium.Matrix4.multiplyByVector(viewer.camera.viewMatrix, _Cartesian4Center1, _scratchCartesian4Center1);
_scratchCartesian3Normal.x = temp1.x - temp.x;
_scratchCartesian3Normal.y = temp1.y - temp.y;
_scratchCartesian3Normal.z = temp1.z - temp.z;
Cesium.Cartesian3.normalize(_scratchCartesian3Normal, _scratchCartesian3Normal);
return _scratchCartesian3Normal;
},
u_radius: options.radius,
u_scanLineNormalEC: function() {
const temp = Cesium.Matrix4.multiplyByVector(viewer.camera.viewMatrix, _Cartesian4Center, _scratchCartesian4Center);
const temp1 = Cesium.Matrix4.multiplyByVector(viewer.camera.viewMatrix, _Cartesian4Center1, _scratchCartesian4Center1);
const temp2 = Cesium.Matrix4.multiplyByVector(viewer.camera.viewMatrix, _Cartesian4Center2, _scratchCartesian4Center2);
_scratchCartesian3Normal.x = temp1.x - temp.x;
_scratchCartesian3Normal.y = temp1.y - temp.y;
_scratchCartesian3Normal.z = temp1.z - temp.z;
Cesium.Cartesian3.normalize(_scratchCartesian3Normal, _scratchCartesian3Normal);
_scratchCartesian3Normal1.x = temp2.x - temp.x;
_scratchCartesian3Normal1.y = temp2.y - temp.y;
_scratchCartesian3Normal1.z = temp2.z - temp.z;
const tempTime = ((/* @__PURE__ */ new Date()).getTime() - _time) % options.interval / options.interval;
Cesium.Quaternion.fromAxisAngle(_scratchCartesian3Normal, tempTime * Cesium.Math.PI * 2, _RotateQ);
Cesium.Matrix3.fromQuaternion(_RotateQ, _RotateM);
Cesium.Matrix3.multiplyByVector(_RotateM, _scratchCartesian3Normal1, _scratchCartesian3Normal1);
Cesium.Cartesian3.normalize(_scratchCartesian3Normal1, _scratchCartesian3Normal1);
return _scratchCartesian3Normal1;
},
u_scanColor: options.color
};
return {
shaderSource: shaderSourceText,
uniforms
};
};
return {
webgl
};
}
var shaderSource = `
uniform sampler2D colorTexture;
uniform sampler2D depthTexture;
in vec2 v_textureCoordinates;
uniform vec4 u_scanCenterEC;
uniform vec3 u_scanPlaneNormalEC;
uniform float u_radius;
uniform vec4 u_scanColor;
vec4 toEye(in vec2 uv, in float depth)
{
vec2 xy = vec2((uv.x * 2.0 - 1.0),(uv.y * 2.0 - 1.0));
vec4 posInCamera =czm_inverseProjection * vec4(xy, depth, 1.0);
posInCamera =posInCamera / posInCamera.w;
return posInCamera;
}
vec3 pointProjectOnPlane(in vec3 planeNormal, in vec3 planeOrigin, in vec3 point)
{
vec3 v01 = point -planeOrigin;
float d = dot(planeNormal, v01) ;
return (point - planeNormal * d);
}
float getDepth(in vec4 depth)
{
float z_window = czm_unpackDepth(depth);
z_window = czm_reverseLogDepth(z_window);
float n_range = czm_depthRange.near;
float f_range = czm_depthRange.far;
return (2.0 * z_window - n_range - f_range) / (f_range - n_range);
}
void main()
{
out_FragColor = texture(colorTexture, v_textureCoordinates);
float depth = getDepth( texture(depthTexture, v_textureCoordinates));
vec4 viewPos = toEye(v_textureCoordinates, depth);
vec3 prjOnPlane = pointProjectOnPlane(u_scanPlaneNormalEC.xyz, u_scanCenterEC.xyz, viewPos.xyz);
float dis = length(prjOnPlane.xyz - u_scanCenterEC.xyz);
if(dis < u_radius)
{
float f = 1.0 -abs(u_radius - dis) / u_radius;
f = pow(f, 4.0);
out_FragColor = mix(out_FragColor, u_scanColor, f);
}
}
`;
function useCircle($services) {
const webgl = (options) => {
var _a;
const { viewer } = $services;
const webgl2 = (_a = viewer.scene.context) == null ? void 0 : _a.webgl2;
let shaderSourceText = shaderSource;
if (!webgl2) {
shaderSourceText = shaderSourceText.replace("in vec2 v_textureCoordinates;", "varying vec2 v_textureCoordinates;");
shaderSourceText = shaderSourceText.replace(/texture\(/g, "texture2D(");
shaderSourceText = shaderSourceText.replace(/out_FragColor/g, "gl_FragColor");
}
const cartographicCenter = Cesium.Cartographic.fromCartesian(options.position, viewer.scene.globe.ellipsoid);
const _Cartesian3Center = Cesium.Cartographic.toCartesian(cartographicCenter, viewer.scene.globe.ellipsoid);
const _Cartesian4Center = new Cesium.Cartesian4(_Cartesian3Center.x, _Cartesian3Center.y, _Cartesian3Center.z, 1);
const _CartographicCenter1 = new Cesium.Cartographic(cartographicCenter.longitude, cartographicCenter.latitude, cartographicCenter.height + 500);
const _Cartesian3Center1 = Cesium.Cartographic.toCartesian(_CartographicCenter1, viewer.scene.globe.ellipsoid);
const _Cartesian4Center1 = new Cesium.Cartesian4(_Cartesian3Center1.x, _Cartesian3Center1.y, _Cartesian3Center1.z, 1);
const _time = (/* @__PURE__ */ new Date()).getTime();
const _scratchCartesian4Center = new Cesium.Cartesian4();
const _scratchCartesian4Center1 = new Cesium.Cartesian4();
const _scratchCartesian3Normal = new Cesium.Cartesian3();
const uniforms = {
u_scanCenterEC: function() {
return Cesium.Matrix4.multiplyByVector(viewer.camera.viewMatrix, _Cartesian4Center, _scratchCartesian4Center);
},
u_scanPlaneNormalEC: function() {
const temp = Cesium.Matrix4.multiplyByVector(viewer.camera.viewMatrix, _Cartesian4Center, _scratchCartesian4Center);
const temp1 = Cesium.Matrix4.multiplyByVector(viewer.camera.viewMatrix, _Cartesian4Center1, _scratchCartesian4Center1);
_scratchCartesian3Normal.x = temp1.x - temp.x;
_scratchCartesian3Normal.y = temp1.y - temp.y;
_scratchCartesian3Normal.z = temp1.z - temp.z;
Cesium.Cartesian3.normalize(_scratchCartesian3Normal, _scratchCartesian3Normal);
return _scratchCartesian3Normal;
},
u_radius: function() {
return options.radius * (((/* @__PURE__ */ new Date()).getTime() - _time) % options.interval) / options.interval;
},
u_scanColor: options.color
};
return {
shaderSource: shaderSourceText,
uniforms
};
};
return {
webgl
};
}
const defaultOptions$1 = {
position: [0, 0],
radius: 1500,
interval: 3500,
color: [0, 0, 0, 255]
};
const postProcessStageScanProps = exports('postProcessStageScanProps', {
type: {
type: String,
default: "radar"
// radar, circle
},
options: Object
});
var PostProcessStageScan = defineComponent({
name: "VcPostProcessStageScan",
props: postProcessStageScanProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "VcPostProcessStageScan";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const fragmentShader = ref("");
const uniforms = ref(null);
const { $services } = commonState;
const useRadarState = useRadar($services);
const useCircleState = useCircle($services);
let unwatchFns = [];
const options = computed(() => {
return Object.assign({}, defaultOptions$1, props.options);
});
unwatchFns.push(
watch(
() => options,
(val) => {
if (instance.mounted) {
instance.proxy.reload();
}
},
{ deep: true }
)
);
instance.createCesiumObject = async () => {
const opts = commonState.transformProps(options.value);
let result;
if (props.type === "radar") {
result = useRadarState.webgl(opts);
} else if (props.type === "circle") {
result = useCircleState.webgl(opts);
}
fragmentShader.value = result.shaderSource;
uniforms.value = result.uniforms;
return true;
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
return () => {
return h(PostProcessStage, {
fragmentShader: fragmentShader.value,
uniforms: uniforms.value
});
};
}
});
const postProcessStageCollectionProps = exports('postProcessStageCollectionProps', {
postProcesses: {
type: Array,
default: () => []
}
});
var PostProcessStageCollection = defineComponent({
name: "VcPostProcessStageCollection",
props: postProcessStageCollectionProps,
emits: commonEmits,
setup(props, ctx) {
const instance = getCurrentInstance();
instance.cesiumClass = "PostProcessStageCollection";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { $services } = commonState;
const stages = [];
let unwatchFns = [];
unwatchFns.push(
watch(
() => props.postProcesses,
(val) => {
var _a, _b;
if (instance.mounted) {
(_b = (_a = instance.proxy).reload) == null ? void 0 : _b.call(_a);
}
},
{ deep: true }
)
);
instance.createCesiumObject = async () => {
return stages;
};
instance.mount = async () => {
const { postProcessStages } = $services;
props.postProcesses.forEach((postProcess) => {
const opts = commonState.transformProps(postProcess);
stages.push(postProcessStages.add(new Cesium.PostProcessStage(opts)));
});
return true;
};
instance.unmount = async () => {
const { postProcessStages } = $services;
stages.forEach((stage) => {
postProcessStages.remove(stage);
});
stages.length = 0;
return true;
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
return () => {
var _a, _b;
return ctx.slots.default ? h(
"i",
{
class: kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""),
style: { display: "none !important" }
},
hSlot(ctx.slots.default)
) : createCommentVNode(kebabCase(((_b = instance.proxy) == null ? void 0 : _b.$options.name) || ""));
};
}
});
const components$1 = [PostProcessStage, PostProcessStageScan, PostProcessStageCollection];
components$1.forEach((cmp) => {
cmp["install"] = (app) => {
app.component(cmp.name, cmp);
};
});
const VcPostProcessStage = exports('VcPostProcessStage', PostProcessStage);
const VcPostProcessStageScan = exports('VcPostProcessStageScan', PostProcessStageScan);
const VcPostProcessStageCollection = exports('VcPostProcessStageCollection', PostProcessStageCollection);
var ConfigProvider = defineComponent({
name: "VcConfigProvider",
props: {
locale: {
type: Object,
default: () => Chinese
},
cesiumPath: {
type: String,
default: "https://unpkg.com/cesium@latest/Build/Cesium/Cesium.js"
},
accessToken: {
type: String,
default: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2OGE2MjZlOC1mMzhiLTRkZjQtOWEwZi1jZTE0MWY0YzhlMTAiLCJpZCI6MjU5LCJpYXQiOjE2NDM3MjU1NzZ9.ptZ5tVXvMmuWRC0WhjtYTg-17nQh14fgxBsx0HJiVXQ"
},
reloadMode: {
type: String,
default: "all"
}
},
setup(props, { slots }) {
const config = provideGlobalConfig(props);
return () => renderSlot(slots, "default", { config: config == null ? void 0 : config.value });
}
});
ConfigProvider.install = (app) => {
app.component(ConfigProvider.name, ConfigProvider);
};
const _ConfigProvider = ConfigProvider;
const VcConfigProvider = exports('VcConfigProvider', _ConfigProvider);
const emits$1 = {
...commonEmits,
stop: (evt) => true
};
var AnalysisFlood = defineComponent({
name: "VcAnalysisFlood",
props: {
minHeight: {
type: Number,
default: -1
},
maxHeight: {
type: Number,
default: 8888
},
speed: {
type: Number,
default: 10
},
loop: {
type: Boolean,
default: false
},
color: {
type: [Object, Array, String],
default: "rgba(40,150,200,0.6)"
},
...polygonHierarchy
},
emits: emits$1,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "VcAnalysisFlood";
instance.cesiumEvents = [];
const commonState = useCommon(props, ctx, instance);
if (commonState === void 0) {
return;
}
const { emit } = ctx;
const canRender = ref(false);
const vcParent = getVcParentInstance(instance);
(_a = vcParent.proxy.creatingPromise) == null ? void 0 : _a.then(() => {
canRender.value = true;
});
const flooding = ref(false);
const attributes = ref(null);
const extrudedHeight = ref(-1);
const childRef = ref(null);
let stoped = false;
let unwatchFns = [];
unwatchFns.push(
watch(
() => props.minHeight,
(val) => {
extrudedHeight.value = val;
}
)
);
instance.createCesiumObject = async () => {
const { ColorGeometryInstanceAttribute } = Cesium;
attributes.value = {
color: ColorGeometryInstanceAttribute.fromColor(makeColor(props.color))
};
return childRef.value;
};
instance.mount = async () => {
const { viewer } = commonState.$services;
viewer.clock.onTick.addEventListener(onClockTick);
return true;
};
instance.unmount = async () => {
const { viewer } = commonState.$services;
viewer.clock.onTick.removeEventListener(onClockTick);
extrudedHeight.value = -1;
flooding.value = false;
return true;
};
const onClockTick = () => {
if (flooding.value) {
if (extrudedHeight.value <= props.maxHeight) {
extrudedHeight.value += props.speed;
stoped = false;
} else {
const listener = getInstanceListener(instance, "stop");
listener && emit("stop", childRef.value);
stoped = true;
if (props.loop) {
extrudedHeight.value = props.minHeight;
} else {
flooding.value = false;
}
}
}
};
const start = (height) => {
extrudedHeight.value = Cesium.defined(height) ? height : props.minHeight;
flooding.value = true;
};
const pause = () => {
flooding.value = !flooding.value;
if (stoped) {
extrudedHeight.value = props.minHeight;
}
};
const stop = () => {
extrudedHeight.value = -1;
flooding.value = false;
};
onUnmounted(() => {
unwatchFns.forEach((item) => item());
unwatchFns = [];
});
Object.assign(instance.proxy, {
start,
pause,
stop,
getCurrentHeight: () => extrudedHeight.value
});
return () => {
if (canRender.value) {
const { createGuid } = Cesium;
return h(
VcPrimitiveClassification,
{
asynchronous: false,
ref: childRef
},
() => h(
VcGeometryInstance,
{
id: createGuid(),
attributes: attributes.value
},
() => h(VcGeometryPolygon, {
extrudedHeight: extrudedHeight.value,
polygonHierarchy: props.polygonHierarchy
})
)
);
} else {
return createCommentVNode("v-if");
}
};
}
});
const sightlineAnalysisActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-analysis-sightline"
});
const sightlineAnalysisDefault = Object.assign({}, segmentDrawingDefault, {
polylineOpts: Object.assign({}, polylineOptsDefault, {
colors: ["#51ff00", "red"]
}),
primitiveOpts: Object.assign({}, polylinePrimitiveOptsDefault, {
appearance: {
type: "PolylineColorAppearance"
},
depthFailAppearance: {
type: "PolylineColorAppearance"
}
}),
sightlineType: "polyline"
// segment polyline
});
const viewshedAnalysisActionDefault = Object.assign({}, actionOptions, {
icon: "vc-icons-analysis-viewshed"
});
const viewshedAnalysisDefault = Object.assign({}, polygonDrawingDefault, {
pointOpts: Object.assign({}, pointOptsDefault, {
show: false
}),
polylineOpts: Object.assign({}, polylineOptsDefault, {
width: 15
}),
primitiveOpts: Object.assign({}, polylinePrimitiveOptsDefault, {
show: false,
appearance: {
type: "PolylineMaterialAppearance",
options: {
material: {
fabric: {
type: "PolylineArrow",
uniforms: {
color: [255, 255, 0, 255]
}
}
}
}
},
depthFailAppearance: {
type: "PolylineMaterialAppearance",
options: {
material: {
fabric: {
type: "PolylineArrow",
uniforms: {
color: [255, 255, 0, 255]
}
}
}
}
}
}),
editorOpts: {
pixelOffset: [16, -8],
delay: 1e3,
hideDelay: 1e3,
move: Object.assign({}, editorOptsDefault),
removeAll: Object.assign({}, editorOptsDefault, {
icon: "vc-icons-delete"
})
},
viewshedOpts: {
fovH: 90,
fovV: 60,
offsetHeight: 1.8,
visibleColor: "#00ff00",
invisibleColor: "#ff0000",
showGridLine: true,
faceColor: "rgba(255,255,255,0.1)",
lineColor: "rgba(255,255,255,0.4)"
}
});
const fabActionOptsDefault = Object.assign({}, {});
const mainFabDefault = Object.assign({}, actionOptions, {
direction: "right",
icon: "vc-icons-analysis-button",
activeIcon: "vc-icons-analysis-button",
verticalActionsAlign: "center",
hideIcon: false,
persistent: false,
modelValue: true,
hideActionOnClick: false,
color: "info"
});
const analysisType = ["sightline", "viewshed"];
const isValidAnalysisType = (drawings) => {
let flag = true;
drawings.forEach((drawing) => {
if (!analysisType.includes(drawing)) {
console.error(`VueCesium: unknown analysis type: ${drawing}`);
flag = false;
}
});
return flag;
};
const analysesProps = exports('analysesProps', {
...useDrawingFabProps,
analyses: {
type: Array,
default: () => analysisType,
validator: isValidAnalysisType
},
mainFabOpts: {
type: Object,
default: () => mainFabDefault
},
fabActionOpts: {
type: Object,
default: () => fabActionOptsDefault
},
sightlineActionOpts: {
type: Object,
default: () => sightlineAnalysisActionDefault
},
sightlineAnalysisOpts: {
type: Object,
default: () => sightlineAnalysisDefault
},
viewshedActionOpts: {
type: Object,
default: () => viewshedAnalysisActionDefault
},
viewshedAnalysisOpts: {
type: Object,
default: () => viewshedAnalysisDefault
}
});
const defaultOptions = getDefaultOptionByProps(analysesProps);
var VcAnalysisSightline = exports('VcAnalysisSightline', defineComponent({
name: "VcAnalysisSightline",
props: {
...useDrawingActionProps,
polylineOpts: Object,
polygonOpts: Object,
primitiveOpts: Object,
sightlineType: {
type: String,
default: "polyline"
}
},
emits: drawingEmit,
setup(props, ctx) {
if (props.sightlineType === "segment" || props.sightlineType === "circle") {
return useDrawingSegment(props, ctx, "VcAnalysisSightline");
} else if (props.sightlineType === "polyline") {
return useDrawingPolyline(props, ctx, "VcAnalysisSightline");
}
}
}));
var VcAnalysisViewshed = exports('VcAnalysisViewshed', defineComponent({
name: "VcAnalysisViewshed",
props: {
...useDrawingActionProps,
polylineOpts: Object,
primitiveOpts: Object,
viewshedOpts: Object
},
emits: drawingEmit,
setup(props, ctx) {
return useDrawingSegment(props, ctx, "VcAnalysisViewshed");
}
}));
const emits = {
...drawingEmit,
fabUpdated: (value) => true,
clearEvt: (e, viewer) => true
};
var Analyses = defineComponent({
name: "VcAnalyses",
props: analysesProps,
emits,
setup(props, ctx) {
var _a;
const instance = getCurrentInstance();
instance.cesiumClass = "VcAnalyses";
const { t } = useLocale();
const options = {};
const clearActionOpts = reactive(Object.assign({}, defaultOptions.clearActionOpts, props.clearActionOpts));
const mainFabOpts = reactive(Object.assign({}, defaultOptions.mainFabOpts, props.mainFabOpts));
const fabActionOpts = reactive(Object.assign({}, defaultOptions.fabActionOpts, props.fabActionOpts));
const sightlineActionOpts = reactive(
Object.assign({}, defaultOptions.sightlineActionOpts, mergeActionOpts("sightlineActionOpts"))
);
const sightlineAnalysisOpts = reactive(deepMerge(cloneDeep(defaultOptions.sightlineAnalysisOpts), props.sightlineAnalysisOpts));
const viewshedActionOpts = reactive(
Object.assign({}, defaultOptions.viewshedActionOpts, mergeActionOpts("viewshedActionOpts"))
);
const viewshedAnalysisOpts = reactive(
deepMerge(cloneDeep(defaultOptions.viewshedAnalysisOpts), props.viewshedAnalysisOpts)
);
options.sightlineActionOpts = sightlineActionOpts;
options.sightlineAnalysisOpts = sightlineAnalysisOpts;
options.viewshedActionOpts = viewshedActionOpts;
options.viewshedAnalysisOpts = viewshedAnalysisOpts;
options.clearActionOpts = clearActionOpts;
const drawingActionInstances = computed(() => {
return props.analyses.map((analysisName) => ({
name: analysisName,
type: "analysis",
actionStyle: {
background: options[`${camelize(analysisName)}ActionOpts`].color,
color: options[`${camelize(analysisName)}ActionOpts`].textColor
},
actionClass: `vc-analysis-${analysisName} vc-analysis-button`,
actionRef: ref(null),
actionOpts: options[`${camelize(analysisName)}ActionOpts`],
cmp: getDrawingCmp(analysisName),
cmpRef: ref(null),
cmpOpts: options[`${camelize(analysisName)}AnalysisOpts`],
tip: options[`${camelize(analysisName)}ActionOpts`].tooltip.tip || t(`vc.analysis.${camelize(analysisName)}.tip`),
isActive: false
}));
});
function getDrawingCmp(name) {
switch (name) {
case "sightline":
return VcAnalysisSightline;
case "viewshed":
return VcAnalysisViewshed;
default:
return void 0;
}
}
function mergeActionOpts(actionName) {
return isEqual(defaultOptions[actionName], props[actionName]) ? fabActionOpts : Object.assign({}, fabActionOpts, props[actionName]);
}
return (_a = useDrawingFab(props, ctx, instance, drawingActionInstances, mainFabOpts, clearActionOpts, "analysis")) == null ? void 0 : _a.renderContent;
}
});
const components = [AnalysisFlood, Analyses];
components.forEach((cmp) => {
cmp["install"] = (app) => {
app.component(cmp.name, cmp);
};
});
const VcAnalysisFlood = exports('VcAnalysisFlood', AnalysisFlood);
const VcAnalyses = exports('VcAnalyses', Analyses);
var Components = [
VcViewer,
VcCompass,
VcZoomControl,
VcPrint,
VcMyLocation,
VcStatusBar,
VcDistanceLegend,
VcNavigation,
VcCompassSm,
VcZoomControlSm,
VcNavigationSm,
VcOverviewMap,
VcSelectionIndicator,
_Measurements,
_Drawings,
_ImageryLayer,
VcImageryProviderAmap,
VcImageryProviderArcgis,
VcImageryProviderBaidu,
VcImageryProviderBing,
VcImageryProviderGoogle,
VcImageryProviderGrid,
VcImageryProviderIon,
VcImageryProviderMapbox,
VcImageryProviderOsm,
VcImageryProviderSingletile,
VcImageryProviderSupermap,
VcImageryProviderTencent,
VcImageryProviderTianditu,
VcImageryProviderTileCoordinates,
VcImageryProviderTms,
VcImageryProviderTiledcache,
VcImageryProviderUrltemplate,
VcImageryProviderWms,
VcImageryProviderWmts,
VcTerrainProviderCesium,
VcTerrainProviderArcgis,
VcTerrainProviderVrTheworld,
VcTerrainProviderTianditu,
VcDatasourceCustom,
VcDatasourceCzml,
VcDatasourceGeojson,
VcDatasourceKml,
_Entity,
VcGraphicsBillboard,
VcGraphicsBox,
VcGraphicsCorridor,
VcGraphicsCylinder,
VcGraphicsEllipse,
VcGraphicsEllipsoid,
VcGraphicsLabel,
VcGraphicsModel,
VcGraphicsPath,
VcGraphicsPlane,
VcGraphicsPoint,
VcGraphicsPolygon,
VcGraphicsPolyline,
VcGraphicsPolylineVolume,
VcGraphicsRectangle,
VcGraphicsTileset,
VcGraphicsWall,
VcPrimitiveClassification,
VcPrimitiveGround,
VcPrimitiveGroundPolyline,
VcPrimitiveModel,
VcPrimitive,
VcPrimitiveTileset,
VcPrimitiveOsmBuildings,
VcPrimitiveTimeDynamicPointCloud,
VcPrimitiveI3sDataProvider,
VcPrimitiveVoxel,
VcPrimitiveParticle,
VcPrimitiveCluster,
VcCollectionBillboard,
VcCollectionCloud,
VcCollectionLabel,
VcCollectionPoint,
VcCollectionPolyline,
VcCollectionPrimitive,
VcBillboard,
VcCumulusCloud,
VcLabel,
VcPoint,
VcPolyline,
VcPolygon,
_GeometryInstance,
VcGeometryBox,
VcGeometryBoxOutline,
VcGeometryCircle,
VcGeometryCircleOutline,
VcGeometryPolygonCoplanar,
VcGeometryPolygonCoplanarOutline,
VcGeometryCorridor,
VcGeometryCorridorOutline,
VcGeometryCylinder,
VcGeometryCylinderOutline,
VcGeometryEllipse,
VcGeometryEllipseOutline,
VcGeometryEllipsoid,
VcGeometryEllipsoidOutline,
VcGeometryFrustum,
VcGeometryFrustumOutline,
VcGeometryGroundPolyline,
VcGeometryPlane,
VcGeometryPlaneOutline,
VcGeometryPolygon,
VcGeometryPolygonOutline,
VcGeometryPolyline,
VcGeometryPolylineVolume,
VcGeometryPolylineVolumeOutline,
VcGeometryRectangle,
VcGeometryRectangleOutline,
VcGeometrySimplePolyline,
VcGeometrySphere,
VcGeometrySphereOutline,
VcGeometryWall,
VcGeometryWallOutline,
VcOverlayHtml,
VcOverlayHeatmap,
VcOverlayWind,
VcOverlayDynamic,
VcOverlayEcharts,
VcOverlayTyphoon,
VcPostProcessStage,
VcPostProcessStageScan,
VcPostProcessStageCollection,
VcBtn,
VcIcon,
VcTooltip,
VcAjaxBar,
VcSkeleton,
VcSpinnerBall,
VcSpinnerBars,
VcSpinnerDots,
VcSpinnerGears,
VcSpinnerHourglass,
VcSpinnerIos,
VcSpinnerOrbit,
VcSpinnerOval,
VcSpinnerPuff,
VcSpinnerRings,
VcSpinnerTail,
VcSpinner,
VcFab,
VcFabAction,
VcSlider,
_ConfigProvider,
VcAnalysisFlood,
VcAnalyses
];
var installer = exports('default', makeInstaller([...Components]));
const install = exports('install', installer.install);
const version = exports('version', installer.version);
})
};
}));