commit 1df257ea917e916dda02f7d0e03d8f8b19abd3f7 Author: jiannibang <271381693@qq.com> Date: Mon Oct 17 10:54:38 2022 +0800 init diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..8edf281 Binary files /dev/null and b/.DS_Store differ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5726835 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/node_modules +./package-lock.json \ No newline at end of file diff --git a/app.js b/app.js new file mode 100644 index 0000000..814b880 --- /dev/null +++ b/app.js @@ -0,0 +1,89 @@ +import { getMapData } from "./getMapData"; +export const post = (url, data) => + new Promise((resolve, reject) => { + wx.request({ + url: "https://huiju.mapais.com/bjyj" + url, + method: "POST", + data, + success({ data, statusCode }) { + if (statusCode !== 200) return reject(); + resolve(data); + }, + }); + }); +const floors = [ + { + name: "-3F", + floorOrder: 0, + url: true, + floorId: "B3", + isPark: true, + }, + { + name: "-2F", + floorOrder: 1, + url: true, + floorId: "B2", + isPark: true, + }, + { + name: "-1F", + floorOrder: 2, + url: true, + floorId: "B1", + isPark: true, + }, + { + name: "1F", + floorOrder: 3, + url: true, + floorId: "F1", + isPark: false, + }, + { + name: "2F", + floorOrder: 4, + url: true, + floorId: "F2", + isPark: false, + }, + { + name: "3F", + floorOrder: 5, + url: true, + floorId: "F3", + isPark: false, + }, +]; +App({ + async onLaunch() { + // 展示本地存储能力 + getMapData(); + try { + const { code } = await new Promise((resolve, reject) => { + wx.login({ + success: resolve, + fail: reject, + }); + }); + const { data } = await post("/api/wxmp/session", { + code, + }); + this.globalData.openid = data ? data.openid : null; + } catch (error) { + console.warn(error); + } + this.openidCbs.forEach((cb) => cb(this.globalData.openid)); + }, + onOpenid(cb) { + this.openidCbs.push(cb); + }, + openidCbs: [], + globalData: { + floors, + floorIdFloorOrderMap: floors.reduce( + (acc, nxt) => ({ ...acc, [nxt.floorId]: nxt.floorOrder }), + {} + ), + }, +}); diff --git a/app.json b/app.json new file mode 100644 index 0000000..533ed0b --- /dev/null +++ b/app.json @@ -0,0 +1,21 @@ +{ + "pages": [ + "pages/h5map/index", + "pages/index/index", + "pages/agreement/index", + "pages/privacy/index" + ], + "window": { + "navigationStyle": "custom", + "navigationBarBackgroundColor": "#F0F0F0", + "navigationBarTitleText": "无锡荟聚", + "navigationBarTextStyle": "black" + }, + "style": "v2", + "sitemapLocation": "sitemap.json", + "permission": { + "scope.userLocation": { + "desc": "你的位置信息将用于小程序位置接口的效果展示" + } + } +} diff --git a/app.wxss b/app.wxss new file mode 100644 index 0000000..e2c30fa --- /dev/null +++ b/app.wxss @@ -0,0 +1,16 @@ +/**app.wxss**/ +.container { + height: 100%; + display: flex; + flex-direction: column; + align-items: center; + justify-content: space-between; + padding: 200rpx 0; + box-sizing: border-box; +} + +view, +input, +scroll-view { + box-sizing: border-box; +} diff --git a/data-helper.js b/data-helper.js new file mode 100644 index 0000000..2a1b554 --- /dev/null +++ b/data-helper.js @@ -0,0 +1,387 @@ +const FacilityCodeMap = { + ft: 0, + upft: 0, + downft: 0, + mys: 3, + xsj: 4, + fwt: 7, + dt: 5, + lt: 88, + dit: 89, + cjr: 10, + tcc: 8, + xsjn: 12, + xsjv: 13, + xxt: 14, + tczl: 8, + fcjcg: 7, + door: 39, + czc: 500, + vip: 34, + pq: 40, + ksgj: 30, + xcgc: 57, + tthy: 58, + bc: 26, + etxsj: 69, + sjcd: 25, +}; +const defaultFacilityTypeMap = { + 0: "扶梯", + 1: "扶梯", + 2: "扶梯", + 3: "母婴室", + 4: "卫生间", + 5: "直梯", + 6: "厕所", + 7: "服务台", + 8: "停车场", + 9: "儿童厕所", + 10: "无障碍卫生间", + 11: "吸烟室", + 12: "男洗手间", + 13: "女洗手间", + 14: "信息台", + 16: "饮水处", + 21: "地铁", + 25: "新能源充电站", + 26: "泊车", + 28: "家庭洗手间(男)", + 29: "家庭洗手间", + 30: "公交", + 34: "VIP", + 39: "出入口", + 40: "喷泉", + 35: "男洗手间", + 36: "女洗手间", + 57: "下沉广场", + 58: "天台花园", + 69: "儿童洗手间", + 88: "楼梯", + 89: "地铁", + 93: "男更衣室", + 94: "女更衣室", + 500: "出租车", +}; +export const attachGraphSingle = ({ graph, key, value }) => { + graph[key] = { + ...graph[key], + ...value, + }; +}; +export const attachGraph = ({ + graph, + leftKey, + rightKey, + leftValue, + rightValue, +}) => { + graph[leftKey] = { + ...graph[leftKey], + ...leftValue, + }; + graph[rightKey] = { + ...graph[rightKey], + ...rightValue, + }; +}; + +export const getDataNew = async (map) => { + const { + mall: { shopInfo, mapData }, + } = map; + return { + serverShopInfo: shopInfo, + mapData, + }; +}; + +export const handleData = ( + shopInfo, + mapData, + ftData, + excludeNodes, + extraCosts, + portals, + mall +) => { + const { floors } = mall; + let shopMap = {}; + let shopNavSet = new Set(); + const parkingSpaceByFloor = []; + const excludeSet = excludeNodes + ? excludeNodes.reduce((acc, nxt) => { + acc.add(nxt); + return acc; + }, new Set()) + : new Set(); + shopInfo.forEach(({ shopList }, floorOrder) => { + shopList.forEach((shop) => { + shopMap[shop.houseNum] = shop; + shopNavSet.add(floorOrder + "_" + shop.yaxis); + }); + }); + const noUpMap = {}; + const noDownMap = {}; + const list = mapData.buildArr + .map(({ mapData }) => mapData) + .map(({ icons, path, stairs, shopArea, floorArea, parkArea }, i) => { + const nodes = path ? path.nodes : []; + let points = []; + let routes = []; + let height = Number(floorArea ? floorArea.toHeight : 0); + nodes.forEach(({ id, list, x, y }) => { + points[id] = { + name: id, + position: [x, height + 0.1, y], + }; + list.forEach((node) => { + const needIncrease = extraCosts[`${i}_${id}_${node.id}`]; + routes.push({ + src: id, + des: node.id, + cost: needIncrease ? 1000 : node.cost, + }); + }); + }); + let facilities = []; + icons.forEach(({ navCode, facCode, Type }) => { + if (points[Number(navCode)]) + facilities.push({ + Escalator: 0, + NavPoint: Number(navCode), + Type: FacilityCodeMap[facCode], + Images: facCode, + point: points[Number(navCode)].position, + }); + }); + stairs.forEach(({ navCode, facCode, no, downState, upState }) => { + if (points[Number(navCode)]) { + const NavPoint = Number(navCode); + const key = `${i}_${NavPoint}`; + const value = ftData[key]; + if (downState) noDownMap[key] = true; + if (upState) noUpMap[key] = true; + facilities.push({ + Escalator: Number(no), + NavPoint: NavPoint, + Type: FacilityCodeMap[facCode], + Images: facCode, + point: points[Number(navCode)].position, + entrances: value ? Object.keys(value) : [], + }); + } + }); + shopArea.forEach(({ name, shopNav, xaxis, yaxis }) => { + if (shopMap[name]) { + shopMap[name].yaxis = shopNav; + shopMap[name].xaxis = [xaxis, height, yaxis]; + } + }); + parkingSpaceByFloor[i] = parkArea; + return { + facilities, + points, + routes, + }; + }); + + const facilities = list.map(({ facilities }) => facilities); + facilities.forEach((facilitiesOnSameFloor, floorOrder) => { + facilitiesOnSameFloor.forEach((facility) => { + facility.floorOrder = floorOrder; + }); + }); + + const flatFacilities = facilities.reduce((acc, nxt) => acc.concat(nxt), []); + flatFacilities.forEach((fac) => { + fac.isFac = true; + fac.floorName = floors[fac.floorOrder][1]; + fac.name = fac.floorName + defaultFacilityTypeMap[fac.Type]; + fac.xaxis = fac.point; + fac.yaxis = Number(fac.NavPoint); + fac.id = `${fac.floorOrder}_${fac.Type}_${fac.NavPoint}`; + }); + + const facilityLiftMap = flatFacilities.reduce( + (acc, nxt) => + !(nxt.Type === 0 || nxt.Type === 5) + ? acc + : { + ...acc, + [`${nxt.floorOrder}_${nxt.NavPoint}`]: nxt, + }, + {} + ); + const facilityMap = flatFacilities.reduce( + (acc, nxt) => ({ + ...acc, + [nxt.id]: nxt, + }), + {} + ); + const routes = list.map(({ routes }) => routes); + const points = list.map(({ points }) => points); + const graph = {}; + routes.forEach((route, floorOrder) => { + route.forEach(({ src, des, cost }) => { + const srcId = floorOrder + "_" + src; + const desId = floorOrder + "_" + des; + if (excludeSet.has(srcId) || excludeSet.has(desId)) return; + graph[srcId] = { + ...graph[srcId], + [desId]: cost, + }; + graph[desId] = { + ...graph[desId], + [srcId]: cost, + }; + }); + }); + const graphDt = JSON.parse(JSON.stringify(graph)); + const graphFt = JSON.parse(JSON.stringify(graph)); + let escalatorMap = flatFacilities.reduce( + (acc, { NavPoint, Escalator, Type, floorOrder }) => { + if (NavPoint !== undefined && (Type === 0 || Type === 5)) { + if (acc[`${Type}_${Escalator}`]) + acc[`${Type}_${Escalator}`].push({ + NavPoint, + floorOrder, + Type, + }); + else + acc[`${Type}_${Escalator}`] = [ + { + NavPoint, + floorOrder, + Type, + }, + ]; + acc[`${Type}_${Escalator}`].isEscalator = Type === 0; + } + return acc; + }, + {} + ); + + Object.values(ftData).forEach((value) => { + Object.entries(value).forEach(([key, dsts]) => { + dsts.forEach((dst) => { + const value = { + [dst]: 6000, + }; + attachGraphSingle({ + graph, + key, + value, + }); + attachGraphSingle({ + graph: graphFt, + key, + value, + }); + }); + }); + }); + Object.values(escalatorMap).forEach((list) => { + for (let i = 0; i < list.length - 1; i++) { + for (let j = i + 1; j < list.length; j++) { + const { floorOrder: floorOrderI, NavPoint: src } = list[i]; + const { floorOrder: floorOrderJ, NavPoint: des } = list[j]; + const leftKey = floorOrderI + "_" + src; + const rightKey = floorOrderJ + "_" + des; + const floorDiff = Math.abs(floorOrderI - floorOrderJ); + const isUp = Number(floorOrderJ) > Number(floorOrderI); + if (ftData[leftKey]) return; + if (ftData[rightKey]) return; + const leftValue = { + [rightKey]: + (isUp && noUpMap[leftKey]) || (!isUp && noDownMap[leftKey]) + ? Infinity + : list.isEscalator + ? 7000 * floorDiff + : 10000 + floorDiff * 1000, + }; + const rightValue = { + [leftKey]: + (!isUp && noUpMap[rightKey]) || (isUp && noDownMap[rightKey]) + ? Infinity + : list.isEscalator + ? 7000 * floorDiff + : 10000 + floorDiff * 1000, + }; + attachGraph({ + graph, + leftKey, + rightKey, + leftValue, + rightValue, + }); + if (list.isEscalator) + attachGraph({ + graph: graphFt, + leftKey, + rightKey, + leftValue, + rightValue, + }); + else + attachGraph({ + graph: graphDt, + leftKey, + rightKey, + leftValue, + rightValue, + }); + } + } + }); + const grahps = [graph, graphDt, graphFt]; + portals.forEach(({ leftKey, rightKey, leftValue, rightValue }) => + grahps.forEach((graph) => + attachGraph({ + graph, + leftKey, + rightKey, + leftValue, + rightValue, + }) + ) + ); + return { + points, + routes, + graph, + graphDt, + graphFt, + facilities, + flatFacilities, + excludeSet, + parkingSpaceByFloor, + facilityLiftMap, + facilityMap, + }; +}; + +const dataHelper = async (map) => { + const { + ftData = {}, + excludeNodes, + extraCosts = {}, + portals = [], + serverShopInfo, + mapData, + mall, + } = map; + + return handleData( + serverShopInfo, + mapData, + ftData, + excludeNodes, + extraCosts, + portals, + mall + ); +}; +export default dataHelper; diff --git a/getMapData.js b/getMapData.js new file mode 100644 index 0000000..3d97220 --- /dev/null +++ b/getMapData.js @@ -0,0 +1,114 @@ +import { get, post } from "./pages/map2d/util"; +import dataHelper from "./data-helper"; +let mapDataAndShop = null; +export const mall = { + isNew: true, + name: "荟聚", + city: "无锡", + code: "ef2c0bd1-6751-41be-86b7-df4b9ef49bad", + mapFileUrl: `https://hjcdn.cdn.bcebos.com/livatbeijing/Aeditor/Aeditor.json?t=${new Date().getTime()}`, + mapDataUrl: "https://huiju.mapais.com/bjyj/api/CDN/GetMapInfo", + shopInfoUrl: `https://hjcdn.cdn.bcebos.com/livatbeijing/QueryShopListForMap/QueryShopListForMap.json?t=${new Date().getTime()}`, + groundFloorIndex: 1, + floors: [ + [true, "-3F"], + [true, "-2F"], + [true, "-1F"], + [true, "1F"], + [true, "2F"], + [true, "3F"], + ], +}; +export const getMapData = async () => { + if (mapDataAndShop) return mapDataAndShop; + try { + const { mapUrl, shopUrl } = await get( + `https://hjcdn.cdn.bcebos.com/livatbeijing/config.json?t=${new Date().getTime()}` + ); + if (mapUrl) mall.mapFileUrl = mapUrl; + if (shopUrl) mall.shopInfoUrl = shopUrl; + } catch (error) { + console.log("获取config失败"); + } + + let [mapData, serverShopInfo, ...rest] = await Promise.all([ + get(mall.mapFileUrl), + get(mall.shopInfoUrl), + ...mall.floors.map((_, i) => + post(mall.mapDataUrl, { + mallCode: mall.code, + key: i, + }) + ), + ]); + mapData = JSON.parse(mapData.data.mapData)[0]; + const map2dData = rest.map(({ data: { mapData } }) => JSON.parse(mapData)); + mall.floors.forEach((floor, i) => { + floor[2] = map2dData[i]; + }); + serverShopInfo = serverShopInfo.data; + const floors = mall.floors; + console.log(mall.floors); + let shopMap = {}; + serverShopInfo.forEach(({ shopList }) => { + shopList.forEach((shop) => { + shop.floorName = floors[shop.floorOrder][1]; + shopMap[shop.houseNum] = shop; + }); + }); + mapData.buildArr.forEach(({ mapData: { path } }, i) => { + if (i <= 2) + path.nodes.forEach((node) => + node.list.forEach((adj) => { + adj.cost *= 3; + }) + ); + }); + const dataHelperResponse = await dataHelper({ + serverShopInfo, + mapData, + mall, + }); + const pMap = mapData.buildArr + .map(({ mapData: { parkArea } }, i) => { + return Object.entries( + parkArea.reduce((acc, { parkNum, shopNav }) => { + const key = `${i}_${shopNav}`; + return { + ...acc, + [key]: [...(acc[key] ? acc[key] : []), parkNum], + }; + }, {}) + ).map(([key, parkNo]) => { + const [floorOrder, pathNo] = key.split("_"); + return { floorOrder, pathNo, parkNo }; + }); + }) + .reduce((acc, nxt) => [...acc, ...nxt], []) + .reduce((acc, { floorOrder, pathNo, parkNo }) => { + if (pathNo == -1 || !pathNo) return acc; + acc = { ...acc }; + parkNo.forEach((name) => { + acc[name] = { + name, + navPoint: pathNo, + floorOrder, + floorName: floors[floorOrder][1], + xaxis: dataHelperResponse.points[floorOrder][pathNo] + ? dataHelperResponse.points[floorOrder][pathNo].position + : null, + yaxis: pathNo, + }; + }); + return acc; + }, {}); + mapDataAndShop = { + ...dataHelperResponse, + serverShopInfo, + mapData, + mall, + shopMap, + pMap, + }; + return mapDataAndShop; +}; diff --git a/images/2dmap.jpg b/images/2dmap.jpg new file mode 100644 index 0000000..8e686b1 Binary files /dev/null and b/images/2dmap.jpg differ diff --git a/images/location.png b/images/location.png new file mode 100644 index 0000000..b9e731e Binary files /dev/null and b/images/location.png differ diff --git a/loader/gltfLoader.js b/loader/gltfLoader.js new file mode 100644 index 0000000..66bf7e5 --- /dev/null +++ b/loader/gltfLoader.js @@ -0,0 +1,3498 @@ +export function registerGLTFLoader(THREE) { + + /** + * @author Rich Tibbett / https://github.com/richtr + * @author mrdoob / http://mrdoob.com/ + * @author Tony Parisi / http://www.tonyparisi.com/ + * @author Takahiro / https://github.com/takahirox + * @author Don McCurdy / https://www.donmccurdy.com + */ + + THREE.GLTFLoader = (function () { + + /** ****************************** */ + /** ******** EXTENSIONS ********** */ + /** ****************************** */ + + var EXTENSIONS = { + KHR_BINARY_GLTF: 'KHR_binary_glTF', + KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression', + KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual', + KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness', + KHR_MATERIALS_UNLIT: 'KHR_materials_unlit', + KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform', + MSFT_TEXTURE_DDS: 'MSFT_texture_dds', + }; + + /* BINARY EXTENSION */ + var BINARY_EXTENSION_HEADER_MAGIC = 'glTF'; + let BINARY_EXTENSION_HEADER_LENGTH = 12; + let BINARY_EXTENSION_CHUNK_TYPES = { + JSON: 0x4E4F534A, + BIN: 0x004E4942, + }; + /* ATTRIBUTES */ + var ATTRIBUTES = { + POSITION: 'position', + NORMAL: 'normal', + TANGENT: 'tangent', + TEXCOORD_0: 'uv', + TEXCOORD_1: 'uv2', + COLOR_0: 'color', + WEIGHTS_0: 'skinWeight', + JOINTS_0: 'skinIndex', + }; + /* WEBGL_COMPONENT_TYPES */ + var WEBGL_COMPONENT_TYPES = { + 5120: Int8Array, + 5121: Uint8Array, + 5122: Int16Array, + 5123: Uint16Array, + 5125: Uint32Array, + 5126: Float32Array, + }; + + function GLTFLoader(manager) { + + this.manager = (manager !== undefined) ? + manager : THREE.DefaultLoadingManager; + this.dracoLoader = null; + this.ddsLoader = null; + + } + + GLTFLoader.prototype = { + + constructor: GLTFLoader, + + crossOrigin: 'anonymous', + + load: function (url, onLoad, onProgress, onError) { + + let scope = this; + + let resourcePath; + + if (this.resourcePath !== undefined) { + + resourcePath = this.resourcePath; + + } else if (this.path !== undefined) { + + resourcePath = this.path; + + } else { + + resourcePath = THREE.LoaderUtils.extractUrlBase(url); + + } + + // Tells the LoadingManager to track an extra item, which resolves after + // the model is fully loaded. This means the count of items loaded will + // be incorrect, but ensures manager.onLoad() does not fire early. + scope.manager.itemStart(url); + + let _onError = function (e) { + + if (onError) { + + onError(e); + + } else { + + console.error(e); + + } + + scope.manager.itemError(url); + scope.manager.itemEnd(url); + + }; + + let loader = new THREE.FileLoader(scope.manager); + + loader.setPath(this.path); + loader.setResponseType('arraybuffer'); + + if (scope.crossOrigin === 'use-credentials') { + + loader.setWithCredentials(true); + + } + + loader.load(url, function (data) { + + try { + + scope.parse(data, resourcePath, function (gltf) { + + onLoad(gltf); + + scope.manager.itemEnd(url); + + }, _onError); + + } catch (e) { + + _onError(e); + + } + + }, onProgress, _onError); + + }, + + setCrossOrigin: function (value) { + + this.crossOrigin = value; + return this; + + }, + + setPath: function (value) { + + this.path = value; + return this; + + }, + + setResourcePath: function (value) { + + this.resourcePath = value; + return this; + + }, + + setDRACOLoader: function (dracoLoader) { + + this.dracoLoader = dracoLoader; + return this; + + }, + + setDDSLoader: function (ddsLoader) { + + this.ddsLoader = ddsLoader; + return this; + + }, + + parse: function (data, path, onLoad, onError) { + + let content; + let extensions = {}; + + if (typeof data === 'string') { + + content = data; + + } else { + + let magic = THREE.LoaderUtils.decodeText(new Uint8Array(data, 0, 4)); + + if (magic === BINARY_EXTENSION_HEADER_MAGIC) { + + try { + + extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data); + + } catch (error) { + + if (onError) { + onError(error); + } + return; + + } + + content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content; + + } else { + + content = THREE.LoaderUtils.decodeText(new Uint8Array(data)); + + } + + } + + let json = JSON.parse(content); + + if (json.asset === undefined || json.asset.version[0] < 2) { + + if (onError) { + onError(new Error( + 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' + )); + } + return; + + } + + if (json.extensionsUsed) { + + for (let i = 0; i < json.extensionsUsed.length; ++i) { + + let extensionName = json.extensionsUsed[i]; + let extensionsRequired = json.extensionsRequired || []; + + switch (extensionName) { + + case EXTENSIONS.KHR_LIGHTS_PUNCTUAL: + extensions[extensionName] = + new GLTFLightsExtension(json); + break; + + case EXTENSIONS.KHR_MATERIALS_UNLIT: + extensions[extensionName] = + new GLTFMaterialsUnlitExtension(); + break; + + case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: + extensions[extensionName] = + new GLTFMaterialsPbrSpecularGlossinessExtension(); + break; + + case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: + extensions[extensionName] = + new GLTFDracoMeshCompressionExtension(json, this.dracoLoader); + break; + + case EXTENSIONS.MSFT_TEXTURE_DDS: + extensions[EXTENSIONS.MSFT_TEXTURE_DDS] = + new GLTFTextureDDSExtension(this.ddsLoader); + break; + + case EXTENSIONS.KHR_TEXTURE_TRANSFORM: + extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] = + new GLTFTextureTransformExtension(); + break; + + default: + + if (extensionsRequired.indexOf(extensionName) >= 0) { + + console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".'); + + } + + } + + } + + } + + let parser = new GLTFParser(json, extensions, { + + path: path || this.resourcePath || '', + crossOrigin: this.crossOrigin, + manager: this.manager, + + }); + + parser.parse(onLoad, onError); + + }, + + }; + + /* GLTFREGISTRY */ + + function GLTFRegistry() { + + let objects = {}; + + return { + + get: function (key) { + + return objects[key]; + + }, + + add: function (key, object) { + + objects[key] = object; + + }, + + remove: function (key) { + + delete objects[key]; + + }, + + removeAll: function () { + + objects = {}; + + }, + + }; + + } + + // /** ****************************** */ + // /** ******** EXTENSIONS ********** */ + // /** ****************************** */ + + // var EXTENSIONS = { + // KHR_BINARY_GLTF: 'KHR_binary_glTF', + // KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression', + // KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual', + // KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness', + // KHR_MATERIALS_UNLIT: 'KHR_materials_unlit', + // KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform', + // MSFT_TEXTURE_DDS: 'MSFT_texture_dds', + // }; + + /** + * DDS Texture Extension + * + * Specification: + * https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds + * + */ + function GLTFTextureDDSExtension(ddsLoader) { + + if (!ddsLoader) { + + throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader'); + + } + + this.name = EXTENSIONS.MSFT_TEXTURE_DDS; + this.ddsLoader = ddsLoader; + + } + + /** + * Lights Extension + * + * Specification: PENDING + */ + function GLTFLightsExtension(json) { + + this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; + + let extension = (json.extensions && + json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL]) || {}; + this.lightDefs = extension.lights || []; + + } + + GLTFLightsExtension.prototype.loadLight = function (lightIndex) { + + let lightDef = this.lightDefs[lightIndex]; + let lightNode; + + let color = new THREE.Color(0xffffff); + if (lightDef.color !== undefined) { + color.fromArray(lightDef.color); + } + + let range = lightDef.range !== undefined ? lightDef.range : 0; + + switch (lightDef.type) { + + case 'directional': + lightNode = new THREE.DirectionalLight(color); + lightNode.target.position.set(0, 0, -1); + lightNode.add(lightNode.target); + break; + + case 'point': + lightNode = new THREE.PointLight(color); + lightNode.distance = range; + break; + + case 'spot': + lightNode = new THREE.SpotLight(color); + lightNode.distance = range; + // Handle spotlight properties. + lightDef.spot = lightDef.spot || {}; + lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== + undefined ? lightDef.spot.innerConeAngle : 0; + lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== + undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0; + lightNode.angle = lightDef.spot.outerConeAngle; + lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle; + lightNode.target.position.set(0, 0, -1); + lightNode.add(lightNode.target); + break; + + default: + throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".'); + + } + + // Some lights (e.g. spot) default to a position other than the origin. Reset the position + // here, because node-level parsing will only override position if explicitly specified. + lightNode.position.set(0, 0, 0); + + lightNode.decay = 2; + + if (lightDef.intensity !== undefined) { + lightNode.intensity = lightDef.intensity; + } + + lightNode.name = lightDef.name || ('light_' + lightIndex); + + return Promise.resolve(lightNode); + + }; + + /** + * Unlit Materials Extension (pending) + * + * PR: https://github.com/KhronosGroup/glTF/pull/1163 + */ + function GLTFMaterialsUnlitExtension() { + + this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; + + } + + GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () { + + return THREE.MeshBasicMaterial; + + }; + + GLTFMaterialsUnlitExtension.prototype.extendParams = + function (materialParams, materialDef, parser) { + + let pending = []; + + materialParams.color = new THREE.Color(1.0, 1.0, 1.0); + materialParams.opacity = 1.0; + + let metallicRoughness = materialDef.pbrMetallicRoughness; + + if (metallicRoughness) { + + if (Array.isArray(metallicRoughness.baseColorFactor)) { + + let array = metallicRoughness.baseColorFactor; + + materialParams.color.fromArray(array); + materialParams.opacity = array[3]; + + } + + if (metallicRoughness.baseColorTexture !== undefined) { + + pending.push(parser.assignTexture(materialParams, + 'map', metallicRoughness.baseColorTexture)); + + } + + } + + return Promise.all(pending); + + }; + + // /* BINARY EXTENSION */ + // var BINARY_EXTENSION_HEADER_MAGIC = 'glTF'; + // let BINARY_EXTENSION_HEADER_LENGTH = 12; + // let BINARY_EXTENSION_CHUNK_TYPES = { + // JSON: 0x4E4F534A, + // BIN: 0x004E4942, + // }; + + function GLTFBinaryExtension(data) { + + this.name = EXTENSIONS.KHR_BINARY_GLTF; + this.content = null; + this.body = null; + + let headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH); + + this.header = { + magic: THREE.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))), + version: headerView.getUint32(4, true), + length: headerView.getUint32(8, true), + }; + + if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) { + + throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.'); + + } else if (this.header.version < 2.0) { + + throw new Error('THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.'); + + } + + let chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH); + let chunkIndex = 0; + + while (chunkIndex < chunkView.byteLength) { + + let chunkLength = chunkView.getUint32(chunkIndex, true); + chunkIndex += 4; + + let chunkType = chunkView.getUint32(chunkIndex, true); + chunkIndex += 4; + + if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) { + + let contentArray = new Uint8Array(data, + BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength); + this.content = THREE.LoaderUtils.decodeText(contentArray); + + } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) { + + let byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; + this.body = data.slice(byteOffset, byteOffset + chunkLength); + + } + + // Clients must ignore chunks with unknown types. + + chunkIndex += chunkLength; + + } + + if (this.content === null) { + + throw new Error('THREE.GLTFLoader: JSON content not found.'); + + } + + } + + /** + * DRACO Mesh Compression Extension + * + * Specification: https://github.com/KhronosGroup/glTF/pull/874 + */ + function GLTFDracoMeshCompressionExtension(json, dracoLoader) { + + if (!dracoLoader) { + + throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.'); + + } + + this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; + this.json = json; + this.dracoLoader = dracoLoader; + + } + + GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = + function (primitive, parser) { + + let json = this.json; + let dracoLoader = this.dracoLoader; + let bufferViewIndex = primitive.extensions[this.name].bufferView; + let gltfAttributeMap = primitive.extensions[this.name].attributes; + let threeAttributeMap = {}; + let attributeNormalizedMap = {}; + let attributeTypeMap = {}; + + for (var attributeName in gltfAttributeMap) { + + var threeAttributeName = ATTRIBUTES[attributeName] || + attributeName.toLowerCase(); + + threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName]; + + } + + for (attributeName in primitive.attributes) { + + var threeAttributeName = ATTRIBUTES[attributeName] || + attributeName.toLowerCase(); + + if (gltfAttributeMap[attributeName] !== undefined) { + + let accessorDef = json.accessors[primitive.attributes[attributeName]]; + let componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; + + attributeTypeMap[threeAttributeName] = componentType; + attributeNormalizedMap[threeAttributeName] = + accessorDef.normalized === true; + + } + + } + + return parser.getDependency('bufferView', + bufferViewIndex).then(function (bufferView) { + + return new Promise(function (resolve) { + + dracoLoader.decodeDracoFile(bufferView, function (geometry) { + + for (let attributeName in geometry.attributes) { + + let attribute = geometry.attributes[attributeName]; + let normalized = attributeNormalizedMap[attributeName]; + + if (normalized !== undefined) { + attribute.normalized = normalized; + } + + } + + resolve(geometry); + + }, threeAttributeMap, attributeTypeMap); + + }); + + }); + + }; + + /** + * Texture Transform Extension + * + * Specification: + */ + function GLTFTextureTransformExtension() { + + this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; + + } + + GLTFTextureTransformExtension.prototype.extendTexture = + function (texture, transform) { + + texture = texture.clone(); + + if (transform.offset !== undefined) { + + texture.offset.fromArray(transform.offset); + + } + + if (transform.rotation !== undefined) { + + texture.rotation = transform.rotation; + + } + + if (transform.scale !== undefined) { + + texture.repeat.fromArray(transform.scale); + + } + + if (transform.texCoord !== undefined) { + + console.warn('THREE.GLTFLoader: Custom UV sets in "' + + this.name + '" extension not yet supported.'); + + } + + texture.needsUpdate = true; + + return texture; + + }; + + /** + * Specular-Glossiness Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness + */ + function GLTFMaterialsPbrSpecularGlossinessExtension() { + + return { + + name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS, + + specularGlossinessParams: [ + 'color', + 'map', + 'lightMap', + 'lightMapIntensity', + 'aoMap', + 'aoMapIntensity', + 'emissive', + 'emissiveIntensity', + 'emissiveMap', + 'bumpMap', + 'bumpScale', + 'normalMap', + 'displacementMap', + 'displacementScale', + 'displacementBias', + 'specularMap', + 'specular', + 'glossinessMap', + 'glossiness', + 'alphaMap', + 'envMap', + 'envMapIntensity', + 'refractionRatio', + ], + + getMaterialType: function () { + + return THREE.ShaderMaterial; + + }, + + extendParams: function (materialParams, materialDef, parser) { + + let pbrSpecularGlossiness = materialDef.extensions[this.name]; + + let shader = THREE.ShaderLib.standard; + + let uniforms = THREE.UniformsUtils.clone(shader.uniforms); + + let specularMapParsFragmentChunk = [ + '#ifdef USE_SPECULARMAP', + ' uniform sampler2D specularMap;', + '#endif', + ].join('\n'); + + let glossinessMapParsFragmentChunk = [ + '#ifdef USE_GLOSSINESSMAP', + ' uniform sampler2D glossinessMap;', + '#endif', + ].join('\n'); + + let specularMapFragmentChunk = [ + 'vec3 specularFactor = specular;', + '#ifdef USE_SPECULARMAP', + ' vec4 texelSpecular = texture2D( specularMap, vUv );', + ' texelSpecular = sRGBToLinear( texelSpecular );', + ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', + ' specularFactor *= texelSpecular.rgb;', + '#endif', + ].join('\n'); + + let glossinessMapFragmentChunk = [ + 'float glossinessFactor = glossiness;', + '#ifdef USE_GLOSSINESSMAP', + ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', + ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', + ' glossinessFactor *= texelGlossiness.a;', + '#endif', + ].join('\n'); + + let lightPhysicalFragmentChunk = [ + 'PhysicalMaterial material;', + 'material.diffuseColor = diffuseColor.rgb;', + 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', + 'material.specularColor = specularFactor.rgb;', + ].join('\n'); + + let fragmentShader = shader.fragmentShader + .replace('uniform float roughness;', 'uniform vec3 specular;') + .replace('uniform float metalness;', 'uniform float glossiness;') + .replace('#include ', specularMapParsFragmentChunk) + .replace('#include ', glossinessMapParsFragmentChunk) + .replace('#include ', specularMapFragmentChunk) + .replace('#include ', glossinessMapFragmentChunk) + .replace('#include ', lightPhysicalFragmentChunk); + + delete uniforms.roughness; + delete uniforms.metalness; + delete uniforms.roughnessMap; + delete uniforms.metalnessMap; + + uniforms.specular = { + value: new THREE.Color().setHex(0x111111), + }; + uniforms.glossiness = { + value: 0.5, + }; + uniforms.specularMap = { + value: null, + }; + uniforms.glossinessMap = { + value: null, + }; + + materialParams.vertexShader = shader.vertexShader; + materialParams.fragmentShader = fragmentShader; + materialParams.uniforms = uniforms; + materialParams.defines = { + 'STANDARD': '', + }; + + materialParams.color = new THREE.Color(1.0, 1.0, 1.0); + materialParams.opacity = 1.0; + + let pending = []; + + if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) { + + let array = pbrSpecularGlossiness.diffuseFactor; + + materialParams.color.fromArray(array); + materialParams.opacity = array[3]; + + } + + if (pbrSpecularGlossiness.diffuseTexture !== undefined) { + + pending.push(parser.assignTexture(materialParams, + 'map', pbrSpecularGlossiness.diffuseTexture)); + + } + + materialParams.emissive = new THREE.Color(0.0, 0.0, 0.0); + materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== + undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0; + materialParams.specular = new THREE.Color(1.0, 1.0, 1.0); + + if (Array.isArray(pbrSpecularGlossiness.specularFactor)) { + + materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor); + + } + + if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) { + + let specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture; + pending.push(parser.assignTexture(materialParams, + 'glossinessMap', specGlossMapDef)); + pending.push(parser.assignTexture(materialParams, + 'specularMap', specGlossMapDef)); + + } + + return Promise.all(pending); + + }, + + createMaterial: function (params) { + + // setup material properties based on MeshStandardMaterial for Specular-Glossiness + + let material = new THREE.ShaderMaterial({ + defines: params.defines, + vertexShader: params.vertexShader, + fragmentShader: params.fragmentShader, + uniforms: params.uniforms, + fog: true, + lights: true, + opacity: params.opacity, + transparent: params.transparent, + }); + + material.isGLTFSpecularGlossinessMaterial = true; + + material.color = params.color; + + material.map = params.map === undefined ? null : params.map; + + material.lightMap = null; + material.lightMapIntensity = 1.0; + + material.aoMap = params.aoMap === undefined ? null : params.aoMap; + material.aoMapIntensity = 1.0; + + material.emissive = params.emissive; + material.emissiveIntensity = 1.0; + material.emissiveMap = params.emissiveMap === + undefined ? null : params.emissiveMap; + + material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap; + material.bumpScale = 1; + + material.normalMap = params.normalMap === + undefined ? null : params.normalMap; + + if (params.normalScale) { + material.normalScale = params.normalScale; + } + + material.displacementMap = null; + material.displacementScale = 1; + material.displacementBias = 0; + + material.specularMap = params.specularMap === + undefined ? null : params.specularMap; + material.specular = params.specular; + + material.glossinessMap = params.glossinessMap === + undefined ? null : params.glossinessMap; + material.glossiness = params.glossiness; + + material.alphaMap = null; + + material.envMap = params.envMap === undefined ? null : params.envMap; + material.envMapIntensity = 1.0; + + material.refractionRatio = 0.98; + + material.extensions.derivatives = true; + + return material; + + }, + + /** + * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can + * copy only properties it knows about or inherits, and misses many properties that would + * normally be defined by MeshStandardMaterial. + * + * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of + * loading a glTF model, but cloning later (e.g. by the user) would require these changes + * AND also updating `.onBeforeRender` on the parent mesh. + * + * @param {THREE.ShaderMaterial} source + * @return {THREE.ShaderMaterial} + */ + cloneMaterial: function (source) { + + let target = source.clone(); + + target.isGLTFSpecularGlossinessMaterial = true; + + let params = this.specularGlossinessParams; + + for (let i = 0, il = params.length; i < il; i++) { + + let value = source[params[i]]; + target[params[i]] = (value && value.isColor) ? value.clone() : value; + + } + + return target; + + }, + + // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer. + refreshUniforms: function (renderer, scene, camera, geometry, material) { + + if (material.isGLTFSpecularGlossinessMaterial !== true) { + + return; + + } + + let uniforms = material.uniforms; + let defines = material.defines; + + uniforms.opacity.value = material.opacity; + + uniforms.diffuse.value.copy(material.color); + uniforms.emissive.value.copy(material.emissive) + .multiplyScalar(material.emissiveIntensity); + + uniforms.map.value = material.map; + uniforms.specularMap.value = material.specularMap; + uniforms.alphaMap.value = material.alphaMap; + + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; + + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + + // uv repeat and offset setting priorities + // 1. color map + // 2. specular map + // 3. normal map + // 4. bump map + // 5. alpha map + // 6. emissive map + + let uvScaleMap; + + if (material.map) { + + uvScaleMap = material.map; + + } else if (material.specularMap) { + + uvScaleMap = material.specularMap; + + } else if (material.displacementMap) { + + uvScaleMap = material.displacementMap; + + } else if (material.normalMap) { + + uvScaleMap = material.normalMap; + + } else if (material.bumpMap) { + + uvScaleMap = material.bumpMap; + + } else if (material.glossinessMap) { + + uvScaleMap = material.glossinessMap; + + } else if (material.alphaMap) { + + uvScaleMap = material.alphaMap; + + } else if (material.emissiveMap) { + + uvScaleMap = material.emissiveMap; + + } + + if (uvScaleMap !== undefined) { + + // backwards compatibility + if (uvScaleMap.isWebGLRenderTarget) { + + uvScaleMap = uvScaleMap.texture; + + } + + if (uvScaleMap.matrixAutoUpdate === true) { + + uvScaleMap.updateMatrix(); + + } + + uniforms.uvTransform.value.copy(uvScaleMap.matrix); + + } + + if (material.envMap) { + + uniforms.envMap.value = material.envMap; + uniforms.envMapIntensity.value = material.envMapIntensity; + + // don't flip CubeTexture envMaps, flip everything else: + // WebGLRenderTargetCube will be flipped for backwards compatibility + // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture + // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future + uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1; + + uniforms.reflectivity.value = material.reflectivity; + uniforms.refractionRatio.value = material.refractionRatio; + + uniforms.maxMipLevel.value = renderer.properties + .get(material.envMap).__maxMipLevel; + + } + + uniforms.specular.value.copy(material.specular); + uniforms.glossiness.value = material.glossiness; + + uniforms.glossinessMap.value = material.glossinessMap; + + uniforms.emissiveMap.value = material.emissiveMap; + uniforms.bumpMap.value = material.bumpMap; + uniforms.normalMap.value = material.normalMap; + + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + + if (uniforms.glossinessMap.value !== null && + defines.USE_GLOSSINESSMAP === undefined) { + + defines.USE_GLOSSINESSMAP = ''; + // set USE_ROUGHNESSMAP to enable vUv + defines.USE_ROUGHNESSMAP = ''; + + } + + if (uniforms.glossinessMap.value === null && + defines.USE_GLOSSINESSMAP !== undefined) { + + delete defines.USE_GLOSSINESSMAP; + delete defines.USE_ROUGHNESSMAP; + + } + + }, + + }; + + } + + /** ****************************** */ + /** ******** INTERPOLATION ******* */ + /** ****************************** */ + + // Spline Interpolation + // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation + function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, + sampleSize, resultBuffer) { + + THREE.Interpolant.call(this, parameterPositions, + sampleValues, sampleSize, resultBuffer); + + } + + GLTFCubicSplineInterpolant.prototype = Object.create(THREE.Interpolant.prototype); + GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant; + + GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) { + + // Copies a sample value to the result buffer. See description of glTF + // CUBICSPLINE values layout in interpolate_() function below. + + let result = this.resultBuffer; + let values = this.sampleValues; + let valueSize = this.valueSize; + let offset = index * valueSize * 3 + valueSize; + + for (let i = 0; i !== valueSize; i++) { + + result[i] = values[offset + i]; + + } + + return result; + + }; + + GLTFCubicSplineInterpolant.prototype.beforeStart_ = + GLTFCubicSplineInterpolant.prototype.copySampleValue_; + + GLTFCubicSplineInterpolant.prototype.afterEnd_ = + GLTFCubicSplineInterpolant.prototype.copySampleValue_; + + GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) { + + let result = this.resultBuffer; + let values = this.sampleValues; + let stride = this.valueSize; + + let stride2 = stride * 2; + let stride3 = stride * 3; + + let td = t1 - t0; + + let p = (t - t0) / td; + let pp = p * p; + let ppp = pp * p; + + let offset1 = i1 * stride3; + let offset0 = offset1 - stride3; + + let s2 = -2 * ppp + 3 * pp; + let s3 = ppp - pp; + let s0 = 1 - s2; + let s1 = s3 - pp + p; + + // Layout of keyframe output values for CUBICSPLINE animations: + // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ] + for (let i = 0; i !== stride; i++) { + + let p0 = values[offset0 + i + stride]; // splineVertex_k + let m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k) + let p1 = values[offset1 + i + stride]; // splineVertex_k+1 + let m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k) + + result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; + + } + + return result; + + }; + + /** ****************************** */ + /** ******** INTERNALS *********** */ + /** ****************************** */ + + /* CONSTANTS */ + + let WEBGL_CONSTANTS = { + FLOAT: 5126, + // FLOAT_MAT2: 35674, + FLOAT_MAT3: 35675, + FLOAT_MAT4: 35676, + FLOAT_VEC2: 35664, + FLOAT_VEC3: 35665, + FLOAT_VEC4: 35666, + LINEAR: 9729, + REPEAT: 10497, + SAMPLER_2D: 35678, + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6, + UNSIGNED_BYTE: 5121, + UNSIGNED_SHORT: 5123, + }; + + // var WEBGL_COMPONENT_TYPES = { + // 5120: Int8Array, + // 5121: Uint8Array, + // 5122: Int16Array, + // 5123: Uint16Array, + // 5125: Uint32Array, + // 5126: Float32Array, + // }; + + let WEBGL_FILTERS = { + 9728: THREE.NearestFilter, + 9729: THREE.LinearFilter, + 9984: THREE.NearestMipmapNearestFilter, + 9985: THREE.LinearMipmapNearestFilter, + 9986: THREE.NearestMipmapLinearFilter, + 9987: THREE.LinearMipmapLinearFilter, + }; + + let WEBGL_WRAPPINGS = { + 33071: THREE.ClampToEdgeWrapping, + 33648: THREE.MirroredRepeatWrapping, + 10497: THREE.RepeatWrapping, + }; + + let WEBGL_TYPE_SIZES = { + 'SCALAR': 1, + 'VEC2': 2, + 'VEC3': 3, + 'VEC4': 4, + 'MAT2': 4, + 'MAT3': 9, + 'MAT4': 16, + }; + + // var ATTRIBUTES = { + // POSITION: 'position', + // NORMAL: 'normal', + // TANGENT: 'tangent', + // TEXCOORD_0: 'uv', + // TEXCOORD_1: 'uv2', + // COLOR_0: 'color', + // WEIGHTS_0: 'skinWeight', + // JOINTS_0: 'skinIndex', + // }; + + let PATH_PROPERTIES = { + scale: 'scale', + translation: 'position', + rotation: 'quaternion', + weights: 'morphTargetInfluences', + }; + + let INTERPOLATION = { + CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each + // keyframe track will be initialized with a default interpolation type, then modified. + LINEAR: THREE.InterpolateLinear, + STEP: THREE.InterpolateDiscrete, + }; + + let ALPHA_MODES = { + OPAQUE: 'OPAQUE', + MASK: 'MASK', + BLEND: 'BLEND', + }; + + let MIME_TYPE_FORMATS = { + 'image/png': THREE.RGBAFormat, + 'image/jpeg': THREE.RGBFormat, + }; + + /* UTILITY FUNCTIONS */ + + function resolveURL(url, path) { + + // Invalid URL + if (typeof url !== 'string' || url === '') { + return ''; + } + + // Host Relative URL + if (/^https?:\/\//i.test(path) && /^\//.test(url)) { + + path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1'); + + } + + // Absolute URL http://,https://,// + if (/^(https?:)?\/\//i.test(url)) { + return url; + } + + // Data URI + if (/^data:.*,.*$/i.test(url)) { + return url; + } + + // Blob URL + if (/^blob:.*$/i.test(url)) { + return url; + } + + // Relative URL + return path + url; + + } + + let defaultMaterial; + + /** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material + */ + function createDefaultMaterial() { + + defaultMaterial = defaultMaterial || new THREE.MeshStandardMaterial({ + color: 0xFFFFFF, + emissive: 0x000000, + metalness: 1, + roughness: 1, + transparent: false, + depthTest: true, + side: THREE.FrontSide, + }); + + return defaultMaterial; + + } + + function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) { + + // Add unknown glTF extensions to an object's userData. + + for (let name in objectDef.extensions) { + + if (knownExtensions[name] === undefined) { + + object.userData.gltfExtensions = object.userData.gltfExtensions || {}; + object.userData.gltfExtensions[name] = objectDef.extensions[name]; + + } + + } + + } + + /** + * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object + * @param {GLTF.definition} gltfDef + */ + function assignExtrasToUserData(object, gltfDef) { + + if (gltfDef.extras !== undefined) { + + if (typeof gltfDef.extras === 'object') { + + Object.assign(object.userData, gltfDef.extras); + + } else { + + console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + + gltfDef.extras); + + } + + } + + } + + /** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets + * + * @param {THREE.BufferGeometry} geometry + * @param {Array} targets + * @param {GLTFParser} parser + * @return {Promise} + */ + function addMorphTargets(geometry, targets, parser) { + + let hasMorphPosition = false; + let hasMorphNormal = false; + + for (var i = 0, il = targets.length; i < il; i++) { + + var target = targets[i]; + + if (target.POSITION !== undefined) { + hasMorphPosition = true; + } + if (target.NORMAL !== undefined) { + hasMorphNormal = true; + } + + if (hasMorphPosition && hasMorphNormal) { + break; + } + + } + + if (!hasMorphPosition && !hasMorphNormal) { + return Promise.resolve(geometry); + } + + let pendingPositionAccessors = []; + let pendingNormalAccessors = []; + + for (var i = 0, il = targets.length; i < il; i++) { + + var target = targets[i]; + + if (hasMorphPosition) { + + var pendingAccessor = target.POSITION !== undefined ? + parser.getDependency('accessor', target.POSITION) : + geometry.attributes.position; + + pendingPositionAccessors.push(pendingAccessor); + + } + + if (hasMorphNormal) { + + var pendingAccessor = target.NORMAL !== undefined ? + parser.getDependency('accessor', target.NORMAL) : + geometry.attributes.normal; + + pendingNormalAccessors.push(pendingAccessor); + + } + + } + + return Promise.all([ + Promise.all(pendingPositionAccessors), + Promise.all(pendingNormalAccessors), + ]).then(function (accessors) { + + let morphPositions = accessors[0]; + let morphNormals = accessors[1]; + + // Clone morph target accessors before modifying them. + + for (var i = 0, il = morphPositions.length; i < il; i++) { + + if (geometry.attributes.position === morphPositions[i]) { + continue; + } + + morphPositions[i] = cloneBufferAttribute(morphPositions[i]); + + } + + for (var i = 0, il = morphNormals.length; i < il; i++) { + + if (geometry.attributes.normal === morphNormals[i]) { + continue; + } + + morphNormals[i] = cloneBufferAttribute(morphNormals[i]); + + } + + for (var i = 0, il = targets.length; i < il; i++) { + + let target = targets[i]; + let attributeName = 'morphTarget' + i; + + if (hasMorphPosition) { + + // Three.js morph position is absolute value. The formula is + // basePosition + // + weight0 * ( morphPosition0 - basePosition ) + // + weight1 * ( morphPosition1 - basePosition ) + // ... + // while the glTF one is relative + // basePosition + // + weight0 * glTFmorphPosition0 + // + weight1 * glTFmorphPosition1 + // ... + // then we need to convert from relative to absolute here. + + if (target.POSITION !== undefined) { + + let positionAttribute = morphPositions[i]; + positionAttribute.name = attributeName; + + let position = geometry.attributes.position; + + for (var j = 0, jl = positionAttribute.count; j < jl; j++) { + + positionAttribute.setXYZ( + j, + positionAttribute.getX(j) + position.getX(j), + positionAttribute.getY(j) + position.getY(j), + positionAttribute.getZ(j) + position.getZ(j) + ); + + } + + } + + } + + if (hasMorphNormal) { + + // see target.POSITION's comment + + if (target.NORMAL !== undefined) { + + let normalAttribute = morphNormals[i]; + normalAttribute.name = attributeName; + + let normal = geometry.attributes.normal; + + for (var j = 0, jl = normalAttribute.count; j < jl; j++) { + + normalAttribute.setXYZ( + j, + normalAttribute.getX(j) + normal.getX(j), + normalAttribute.getY(j) + normal.getY(j), + normalAttribute.getZ(j) + normal.getZ(j) + ); + + } + + } + + } + + } + + if (hasMorphPosition) { + geometry.morphAttributes.position = morphPositions; + } + if (hasMorphNormal) { + geometry.morphAttributes.normal = morphNormals; + } + + return geometry; + + }); + + } + + /** + * @param {THREE.Mesh} mesh + * @param {GLTF.Mesh} meshDef + */ + function updateMorphTargets(mesh, meshDef) { + + mesh.updateMorphTargets(); + + if (meshDef.weights !== undefined) { + + for (var i = 0, il = meshDef.weights.length; i < il; i++) { + + mesh.morphTargetInfluences[i] = meshDef.weights[i]; + + } + + } + + // .extras has user-defined data, so check that .extras.targetNames is an array. + if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) { + + let targetNames = meshDef.extras.targetNames; + + if (mesh.morphTargetInfluences.length === targetNames.length) { + + mesh.morphTargetDictionary = {}; + + for (var i = 0, il = targetNames.length; i < il; i++) { + + mesh.morphTargetDictionary[targetNames[i]] = i; + + } + + } else { + + console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.'); + + } + + } + + } + + function createPrimitiveKey(primitiveDef) { + + let dracoExtension = primitiveDef.extensions && + primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]; + let geometryKey; + + if (dracoExtension) { + + geometryKey = 'draco:' + dracoExtension.bufferView + + ':' + dracoExtension.indices + + ':' + createAttributesKey(dracoExtension.attributes); + + } else { + + geometryKey = primitiveDef.indices + ':' + + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode; + + } + + return geometryKey; + + } + + function createAttributesKey(attributes) { + + let attributesKey = ''; + + let keys = Object.keys(attributes).sort(); + + for (let i = 0, il = keys.length; i < il; i++) { + + attributesKey += keys[i] + ':' + attributes[keys[i]] + ';'; + + } + + return attributesKey; + + } + + function cloneBufferAttribute(attribute) { + + if (attribute.isInterleavedBufferAttribute) { + + let count = attribute.count; + let itemSize = attribute.itemSize; + let array = attribute.array.slice(0, count * itemSize); + + for (let i = 0, j = 0; i < count; ++i) { + + array[j++] = attribute.getX(i); + if (itemSize >= 2) { + array[j++] = attribute.getY(i); + } + if (itemSize >= 3) { + array[j++] = attribute.getZ(i); + } + if (itemSize >= 4) { + array[j++] = attribute.getW(i); + } + + } + + return new THREE.BufferAttribute(array, itemSize, attribute.normalized); + + } + + return attribute.clone(); + + } + + /* GLTF PARSER */ + + function GLTFParser(json, extensions, options) { + + this.json = json || {}; + this.extensions = extensions || {}; + this.options = options || {}; + + // loader object cache + this.cache = new GLTFRegistry(); + + // BufferGeometry caching + this.primitiveCache = {}; + + this.textureLoader = new THREE.TextureLoader(this.options.manager); + this.textureLoader.setCrossOrigin(this.options.crossOrigin); + + this.fileLoader = new THREE.FileLoader(this.options.manager); + this.fileLoader.setResponseType('arraybuffer'); + + if (this.options.crossOrigin === 'use-credentials') { + + this.fileLoader.setWithCredentials(true); + + } + + } + + GLTFParser.prototype.parse = function (onLoad, onError) { + + let parser = this; + let json = this.json; + let extensions = this.extensions; + + // Clear the loader cache + this.cache.removeAll(); + + // Mark the special nodes/meshes in json for efficient parse + this.markDefs(); + + Promise.all([ + + this.getDependencies('scene'), + this.getDependencies('animation'), + this.getDependencies('camera'), + + ]).then(function (dependencies) { + + let result = { + scene: dependencies[0][json.scene || 0], + scenes: dependencies[0], + animations: dependencies[1], + cameras: dependencies[2], + asset: json.asset, + parser: parser, + userData: {}, + }; + + addUnknownExtensionsToUserData(extensions, result, json); + + assignExtrasToUserData(result, json); + + onLoad(result); + + }).catch(onError); + + }; + + /** + * Marks the special nodes/meshes in json for efficient parse. + */ + GLTFParser.prototype.markDefs = function () { + + let nodeDefs = this.json.nodes || []; + let skinDefs = this.json.skins || []; + let meshDefs = this.json.meshes || []; + + let meshReferences = {}; + let meshUses = {}; + + // Nothing in the node definition indicates whether it is a Bone or an + // Object3D. Use the skins' joint references to mark bones. + for (let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) { + + let joints = skinDefs[skinIndex].joints; + + for (let i = 0, il = joints.length; i < il; i++) { + + nodeDefs[joints[i]].isBone = true; + + } + + } + + // Meshes can (and should) be reused by multiple nodes in a glTF asset. To + // avoid having more than one THREE.Mesh with the same name, count + // references and rename instances below. + // + // Example: CesiumMilkTruck sample model reuses "Wheel" meshes. + for (let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) { + + let nodeDef = nodeDefs[nodeIndex]; + + if (nodeDef.mesh !== undefined) { + + if (meshReferences[nodeDef.mesh] === undefined) { + + meshReferences[nodeDef.mesh] = meshUses[nodeDef.mesh] = 0; + + } + + meshReferences[nodeDef.mesh]++; + + // Nothing in the mesh definition indicates whether it is + // a SkinnedMesh or Mesh. Use the node's mesh reference + // to mark SkinnedMesh if node has skin. + if (nodeDef.skin !== undefined) { + + meshDefs[nodeDef.mesh].isSkinnedMesh = true; + + } + + } + + } + + this.json.meshReferences = meshReferences; + this.json.meshUses = meshUses; + + }; + + /** + * Requests the specified dependency asynchronously, with caching. + * @param {string} type + * @param {number} index + * @return {Promise} + */ + GLTFParser.prototype.getDependency = function (type, index) { + + let cacheKey = type + ':' + index; + let dependency = this.cache.get(cacheKey); + + if (!dependency) { + + switch (type) { + + case 'scene': + dependency = this.loadScene(index); + break; + + case 'node': + dependency = this.loadNode(index); + break; + + case 'mesh': + dependency = this.loadMesh(index); + break; + + case 'accessor': + dependency = this.loadAccessor(index); + break; + + case 'bufferView': + dependency = this.loadBufferView(index); + break; + + case 'buffer': + dependency = this.loadBuffer(index); + break; + + case 'material': + dependency = this.loadMaterial(index); + break; + + case 'texture': + dependency = this.loadTexture(index); + break; + + case 'skin': + dependency = this.loadSkin(index); + break; + + case 'animation': + dependency = this.loadAnimation(index); + break; + + case 'camera': + dependency = this.loadCamera(index); + break; + + case 'light': + dependency = this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] + .loadLight(index); + break; + + default: + throw new Error('Unknown type: ' + type); + + } + + this.cache.add(cacheKey, dependency); + + } + + return dependency; + + }; + + /** + * Requests all dependencies of the specified type asynchronously, with caching. + * @param {string} type + * @return {Promise>} + */ + GLTFParser.prototype.getDependencies = function (type) { + + let dependencies = this.cache.get(type); + + if (!dependencies) { + + let parser = this; + let defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || []; + + dependencies = Promise.all(defs.map(function (def, index) { + + return parser.getDependency(type, index); + + })); + + this.cache.add(type, dependencies); + + } + + return dependencies; + + }; + + /** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views + * @param {number} bufferIndex + * @return {Promise} + */ + GLTFParser.prototype.loadBuffer = function (bufferIndex) { + + let bufferDef = this.json.buffers[bufferIndex]; + let loader = this.fileLoader; + + if (bufferDef.type && bufferDef.type !== 'arraybuffer') { + + throw new Error('THREE.GLTFLoader: ' + + bufferDef.type + ' buffer type is not supported.'); + + } + + // If present, GLB container is required to be the first buffer. + if (bufferDef.uri === undefined && bufferIndex === 0) { + + return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body); + + } + + let options = this.options; + + return new Promise(function (resolve, reject) { + + loader.load(resolveURL(bufferDef.uri, options.path), + resolve, undefined, + function () { + + reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + + bufferDef.uri + '".')); + + }); + + }); + + }; + + /** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views + * @param {number} bufferViewIndex + * @return {Promise} + */ + GLTFParser.prototype.loadBufferView = function (bufferViewIndex) { + + let bufferViewDef = this.json.bufferViews[bufferViewIndex]; + + return this.getDependency('buffer', bufferViewDef.buffer) + .then(function (buffer) { + + let byteLength = bufferViewDef.byteLength || 0; + let byteOffset = bufferViewDef.byteOffset || 0; + return buffer.slice(byteOffset, byteOffset + byteLength); + + }); + + }; + + /** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors + * @param {number} accessorIndex + * @return {Promise} + */ + GLTFParser.prototype.loadAccessor = function (accessorIndex) { + + let parser = this; + let json = this.json; + + let accessorDef = this.json.accessors[accessorIndex]; + + if (accessorDef.bufferView === undefined && + accessorDef.sparse === undefined) { + + // Ignore empty accessors, which may be used to declare runtime + // information about attributes coming from another source (e.g. Draco + // compression extension). + return Promise.resolve(null); + + } + + let pendingBufferViews = []; + + if (accessorDef.bufferView !== undefined) { + + pendingBufferViews.push(this.getDependency('bufferView', + accessorDef.bufferView)); + + } else { + + pendingBufferViews.push(null); + + } + + if (accessorDef.sparse !== undefined) { + + pendingBufferViews.push(this.getDependency('bufferView', + accessorDef.sparse.indices.bufferView)); + pendingBufferViews.push(this.getDependency('bufferView', + accessorDef.sparse.values.bufferView)); + + } + + return Promise.all(pendingBufferViews).then(function (bufferViews) { + + let bufferView = bufferViews[0]; + + let itemSize = WEBGL_TYPE_SIZES[accessorDef.type]; + let TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; + + // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12. + let elementBytes = TypedArray.BYTES_PER_ELEMENT; + let itemBytes = elementBytes * itemSize; + let byteOffset = accessorDef.byteOffset || 0; + let byteStride = accessorDef.bufferView !== + undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined; + let normalized = accessorDef.normalized === true; + let array; + let bufferAttribute; + + // The buffer is not interleaved if the stride is the item size in bytes. + if (byteStride && byteStride !== itemBytes) { + + // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer + // This makes sure that IBA.count reflects accessor.count properly + let ibSlice = Math.floor(byteOffset / byteStride); + let ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count; + let ib = parser.cache.get(ibCacheKey); + + if (!ib) { + + array = new TypedArray(bufferView, ibSlice * byteStride, + accessorDef.count * byteStride / elementBytes); + + // Integer parameters to IB/IBA are in array elements, not bytes. + ib = new THREE.InterleavedBuffer(array, byteStride / elementBytes); + + parser.cache.add(ibCacheKey, ib); + + } + + bufferAttribute = new THREE.InterleavedBufferAttribute(ib, itemSize, + (byteOffset % byteStride) / elementBytes, normalized); + + } else { + + if (bufferView === null) { + + array = new TypedArray(accessorDef.count * itemSize); + + } else { + + array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize); + + } + + bufferAttribute = new THREE.BufferAttribute(array, itemSize, normalized); + + } + + // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors + if (accessorDef.sparse !== undefined) { + + let itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR; + let TypedArrayIndices = + WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType]; + + let byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0; + let byteOffsetValues = accessorDef.sparse.values.byteOffset || 0; + + let sparseIndices = new TypedArrayIndices(bufferViews[1], + byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices); + let sparseValues = new TypedArray(bufferViews[2], + byteOffsetValues, accessorDef.sparse.count * itemSize); + + if (bufferView !== null) { + + // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes. + bufferAttribute.setArray(bufferAttribute.array.slice()); + + } + + for (let i = 0, il = sparseIndices.length; i < il; i++) { + + let index = sparseIndices[i]; + + bufferAttribute.setX(index, sparseValues[i * itemSize]); + if (itemSize >= 2) { + bufferAttribute.setY(index, sparseValues[i * itemSize + 1]); + } + if (itemSize >= 3) { + bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]); + } + if (itemSize >= 4) { + bufferAttribute.setW(index, sparseValues[i * itemSize + 3]); + } + if (itemSize >= 5) { + throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.'); + } + + } + + } + + return bufferAttribute; + + }); + + }; + + /** + * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures + * @param {number} textureIndex + * @return {Promise} + */ + GLTFParser.prototype.loadTexture = function (textureIndex) { + + let parser = this; + let json = this.json; + let options = this.options; + let textureLoader = this.textureLoader; + + // var URL = window.URL || window.webkitURL; + + let URL = {}; + + let textureDef = json.textures[textureIndex]; + + let textureExtensions = textureDef.extensions || {}; + + let source; + + if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) { + + source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source]; + + } else { + + source = json.images[textureDef.source]; + + } + + let sourceURI = source.uri; + let isObjectURL = false; + + if (source.bufferView !== undefined) { + + // Load binary image data from bufferView, if provided. + + sourceURI = parser.getDependency('bufferView', source.bufferView) + .then(function (bufferView) { + + isObjectURL = true; + let blob = new Blob([bufferView], { + type: source.mimeType, + }); + sourceURI = URL.createObjectURL(blob); + return sourceURI; + + }); + + } + + return Promise.resolve(sourceURI).then(function (sourceURI) { + + // Load Texture resource. + + let loader = THREE.Loader.Handlers.get(sourceURI); + + if (!loader) { + + loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? + parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : + textureLoader; + + } + + return new Promise(function (resolve, reject) { + + loader.load(resolveURL(sourceURI, options.path), + resolve, undefined, reject); + + }); + + }).then(function (texture) { + + // Clean up resources and configure Texture. + + if (isObjectURL === true) { + + URL.revokeObjectURL(sourceURI); + + } + + texture.flipY = false; + + if (textureDef.name !== undefined) { + texture.name = textureDef.name; + } + + // Ignore unknown mime types, like DDS files. + if (source.mimeType in MIME_TYPE_FORMATS) { + + texture.format = MIME_TYPE_FORMATS[source.mimeType]; + + } + + let samplers = json.samplers || {}; + let sampler = samplers[textureDef.sampler] || {}; + + texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || + THREE.LinearFilter; + texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || + THREE.LinearMipmapLinearFilter; + texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || + THREE.RepeatWrapping; + texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || + THREE.RepeatWrapping; + + return texture; + + }); + + }; + + /** + * Asynchronously assigns a texture to the given material parameters. + * @param {Object} materialParams + * @param {string} mapName + * @param {Object} mapDef + * @return {Promise} + */ + GLTFParser.prototype.assignTexture = + function (materialParams, mapName, mapDef) { + + let parser = this; + + return this.getDependency('texture', mapDef.index) + .then(function (texture) { + + if (!texture.isCompressedTexture) { + + switch (mapName) { + + case 'aoMap': + case 'emissiveMap': + case 'metalnessMap': + case 'normalMap': + case 'roughnessMap': + texture.format = THREE.RGBFormat; + break; + + } + + } + + if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) { + + let transform = mapDef.extensions !== + undefined ? + mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined; + + if (transform) { + + texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] + .extendTexture(texture, transform); + + } + + } + + materialParams[mapName] = texture; + + }); + + }; + + /** + * Assigns final material to a Mesh, Line, or Points instance. The instance + * already has a material (generated from the glTF material options alone) + * but reuse of the same glTF material may require multiple threejs materials + * to accomodate different primitive types, defines, etc. New materials will + * be created if necessary, and reused from a cache. + * @param {THREE.Object3D} mesh Mesh, Line, or Points instance. + */ + GLTFParser.prototype.assignFinalMaterial = function (mesh) { + + let geometry = mesh.geometry; + let material = mesh.material; + let extensions = this.extensions; + + let useVertexTangents = geometry.attributes.tangent !== undefined; + let useVertexColors = geometry.attributes.color !== undefined; + let useFlatShading = geometry.attributes.normal === undefined; + let useSkinning = mesh.isSkinnedMesh === true; + let useMorphTargets = Object.keys(geometry.morphAttributes).length > 0; + let useMorphNormals = useMorphTargets && + geometry.morphAttributes.normal !== undefined; + + if (mesh.isPoints) { + + var cacheKey = 'PointsMaterial:' + material.uuid; + + let pointsMaterial = this.cache.get(cacheKey); + + if (!pointsMaterial) { + + pointsMaterial = new THREE.PointsMaterial(); + THREE.Material.prototype.copy.call(pointsMaterial, material); + pointsMaterial.color.copy(material.color); + pointsMaterial.map = material.map; + pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet + pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px + + this.cache.add(cacheKey, pointsMaterial); + + } + + material = pointsMaterial; + + } else if (mesh.isLine) { + + var cacheKey = 'LineBasicMaterial:' + material.uuid; + + let lineMaterial = this.cache.get(cacheKey); + + if (!lineMaterial) { + + lineMaterial = new THREE.LineBasicMaterial(); + THREE.Material.prototype.copy.call(lineMaterial, material); + lineMaterial.color.copy(material.color); + lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet + + this.cache.add(cacheKey, lineMaterial); + + } + + material = lineMaterial; + + } + + // Clone the material if it will be modified + if (useVertexTangents || useVertexColors || + useFlatShading || useSkinning || useMorphTargets) { + + var cacheKey = 'ClonedMaterial:' + material.uuid + ':'; + + if (material.isGLTFSpecularGlossinessMaterial) { + cacheKey += 'specular-glossiness:'; + } + if (useSkinning) { + cacheKey += 'skinning:'; + } + if (useVertexTangents) { + cacheKey += 'vertex-tangents:'; + } + if (useVertexColors) { + cacheKey += 'vertex-colors:'; + } + if (useFlatShading) { + cacheKey += 'flat-shading:'; + } + if (useMorphTargets) { + cacheKey += 'morph-targets:'; + } + if (useMorphNormals) { + cacheKey += 'morph-normals:'; + } + + let cachedMaterial = this.cache.get(cacheKey); + + if (!cachedMaterial) { + + cachedMaterial = material.isGLTFSpecularGlossinessMaterial ? + extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS] + .cloneMaterial(material) : + material.clone(); + + if (useSkinning) { + cachedMaterial.skinning = true; + } + if (useVertexTangents) { + cachedMaterial.vertexTangents = true; + } + if (useVertexColors) { + cachedMaterial.vertexColors = THREE.VertexColors; + } + if (useFlatShading) { + cachedMaterial.flatShading = true; + } + if (useMorphTargets) { + cachedMaterial.morphTargets = true; + } + if (useMorphNormals) { + cachedMaterial.morphNormals = true; + } + + this.cache.add(cacheKey, cachedMaterial); + + } + + material = cachedMaterial; + + } + + // workarounds for mesh and geometry + + if (material.aoMap && geometry.attributes.uv2 === + undefined && geometry.attributes.uv !== undefined) { + + console.log('THREE.GLTFLoader: Duplicating UVs to support aoMap.'); + geometry.addAttribute('uv2', + new THREE.BufferAttribute(geometry.attributes.uv.array, 2)); + + } + + if (material.isGLTFSpecularGlossinessMaterial) { + + // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update + mesh.onBeforeRender = extensions[ + EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].refreshUniforms; + + } + + mesh.material = material; + + }; + + /** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials + * @param {number} materialIndex + * @return {Promise} + */ + GLTFParser.prototype.loadMaterial = function (materialIndex) { + + let parser = this; + let json = this.json; + let extensions = this.extensions; + let materialDef = json.materials[materialIndex]; + + let materialType; + let materialParams = {}; + let materialExtensions = materialDef.extensions || {}; + + let pending = []; + + if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) { + + let sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]; + materialType = sgExtension.getMaterialType(); + pending.push(sgExtension.extendParams(materialParams, materialDef, parser)); + + } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) { + + let kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT]; + materialType = kmuExtension.getMaterialType(); + pending.push(kmuExtension.extendParams(materialParams, materialDef, parser)); + + } else { + + // Specification: + // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material + + materialType = THREE.MeshStandardMaterial; + + let metallicRoughness = materialDef.pbrMetallicRoughness || {}; + + materialParams.color = new THREE.Color(1.0, 1.0, 1.0); + materialParams.opacity = 1.0; + + if (Array.isArray(metallicRoughness.baseColorFactor)) { + + let array = metallicRoughness.baseColorFactor; + + materialParams.color.fromArray(array); + materialParams.opacity = array[3]; + + } + + if (metallicRoughness.baseColorTexture !== undefined) { + + pending.push(parser.assignTexture(materialParams, + 'map', metallicRoughness.baseColorTexture)); + + } + + materialParams.metalness = metallicRoughness.metallicFactor !== + undefined ? metallicRoughness.metallicFactor : 1.0; + materialParams.roughness = + metallicRoughness.roughnessFactor !== + undefined ? metallicRoughness.roughnessFactor : 1.0; + + if (metallicRoughness.metallicRoughnessTexture !== undefined) { + + pending.push(parser.assignTexture(materialParams, + 'metalnessMap', metallicRoughness.metallicRoughnessTexture)); + pending.push(parser.assignTexture(materialParams, + 'roughnessMap', metallicRoughness.metallicRoughnessTexture)); + + } + + } + + if (materialDef.doubleSided === true) { + + materialParams.side = THREE.DoubleSide; + + } + + let alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE; + + if (alphaMode === ALPHA_MODES.BLEND) { + + materialParams.transparent = true; + + } else { + + materialParams.transparent = false; + + if (alphaMode === ALPHA_MODES.MASK) { + + materialParams.alphaTest = materialDef.alphaCutoff !== + undefined ? materialDef.alphaCutoff : 0.5; + + } + + } + + if (materialDef.normalTexture !== undefined && + materialType !== THREE.MeshBasicMaterial) { + + pending.push(parser.assignTexture(materialParams, 'normalMap', + materialDef.normalTexture)); + + materialParams.normalScale = new THREE.Vector2(1, 1); + + if (materialDef.normalTexture.scale !== undefined) { + + materialParams.normalScale.set(materialDef.normalTexture.scale, + materialDef.normalTexture.scale); + + } + + } + + if (materialDef.occlusionTexture !== undefined && + materialType !== THREE.MeshBasicMaterial) { + + pending.push(parser.assignTexture(materialParams, 'aoMap', + materialDef.occlusionTexture)); + + if (materialDef.occlusionTexture.strength !== undefined) { + + materialParams.aoMapIntensity = materialDef.occlusionTexture.strength; + + } + + } + + if (materialDef.emissiveFactor !== undefined && + materialType !== THREE.MeshBasicMaterial) { + + materialParams.emissive = new THREE.Color().fromArray(materialDef.emissiveFactor); + + } + + if (materialDef.emissiveTexture !== undefined && + materialType !== THREE.MeshBasicMaterial) { + + pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture)); + + } + + return Promise.all(pending).then(function () { + + let material; + + if (materialType === THREE.ShaderMaterial) { + + material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS] + .createMaterial(materialParams); + + } else { + + material = new materialType(materialParams); + + } + + if (materialDef.name !== undefined) { + material.name = materialDef.name; + } + + // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding. + if (material.map) { + material.map.encoding = THREE.sRGBEncoding; + } + if (material.emissiveMap) { + material.emissiveMap.encoding = THREE.sRGBEncoding; + } + if (material.specularMap) { + material.specularMap.encoding = THREE.sRGBEncoding; + } + + assignExtrasToUserData(material, materialDef); + + if (materialDef.extensions) { + addUnknownExtensionsToUserData(extensions, material, materialDef); + } + + return material; + + }); + + }; + + /** + * @param {THREE.BufferGeometry} geometry + * @param {GLTF.Primitive} primitiveDef + * @param {GLTFParser} parser + * @return {Promise} + */ + function addPrimitiveAttributes(geometry, primitiveDef, parser) { + + let attributes = primitiveDef.attributes; + + let pending = []; + + function assignAttributeAccessor(accessorIndex, attributeName) { + + return parser.getDependency('accessor', accessorIndex) + .then(function (accessor) { + + geometry.addAttribute(attributeName, accessor); + + }); + + } + + for (let gltfAttributeName in attributes) { + + let threeAttributeName = ATTRIBUTES[gltfAttributeName] || + gltfAttributeName.toLowerCase(); + + // Skip attributes already provided by e.g. Draco extension. + if (threeAttributeName in geometry.attributes) { + continue; + } + + pending.push(assignAttributeAccessor(attributes[gltfAttributeName], + threeAttributeName)); + + } + + if (primitiveDef.indices !== undefined && !geometry.index) { + + let accessor = parser.getDependency('accessor', primitiveDef.indices) + .then(function (accessor) { + + geometry.setIndex(accessor); + + }); + + pending.push(accessor); + + } + + assignExtrasToUserData(geometry, primitiveDef); + + return Promise.all(pending).then(function () { + + return primitiveDef.targets !== undefined ? + addMorphTargets(geometry, primitiveDef.targets, parser) : + geometry; + + }); + + } + + /** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry + * + * Creates BufferGeometries from primitives. + * + * @param {Array} primitives + * @return {Promise>} + */ + GLTFParser.prototype.loadGeometries = function (primitives) { + + let parser = this; + let extensions = this.extensions; + let cache = this.primitiveCache; + + function createDracoPrimitive(primitive) { + + return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION] + .decodePrimitive(primitive, parser) + .then(function (geometry) { + + return addPrimitiveAttributes(geometry, primitive, parser); + + }); + + } + + let pending = []; + + for (let i = 0, il = primitives.length; i < il; i++) { + + let primitive = primitives[i]; + let cacheKey = createPrimitiveKey(primitive); + + // See if we've already created this geometry + let cached = cache[cacheKey]; + + if (cached) { + + // Use the cached geometry if it exists + pending.push(cached.promise); + + } else { + + var geometryPromise; + + if (primitive.extensions && + primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) { + + // Use DRACO geometry if available + geometryPromise = createDracoPrimitive(primitive); + + } else { + + // Otherwise create a new geometry + geometryPromise = addPrimitiveAttributes(new THREE.BufferGeometry(), + primitive, parser); + + } + + // Cache this geometry + cache[cacheKey] = { + primitive: primitive, + promise: geometryPromise, + }; + + pending.push(geometryPromise); + + } + + } + + return Promise.all(pending); + + }; + + /** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes + * @param {number} meshIndex + * @return {Promise} + */ + GLTFParser.prototype.loadMesh = function (meshIndex) { + + let parser = this; + let json = this.json; + + let meshDef = json.meshes[meshIndex]; + let primitives = meshDef.primitives; + + let pending = []; + + for (let i = 0, il = primitives.length; i < il; i++) { + + let material = primitives[i].material === undefined ? + createDefaultMaterial() : + this.getDependency('material', primitives[i].material); + + pending.push(material); + + } + + return Promise.all(pending).then(function (originalMaterials) { + + return parser.loadGeometries(primitives).then(function (geometries) { + + let meshes = []; + + for (var i = 0, il = geometries.length; i < il; i++) { + + let geometry = geometries[i]; + let primitive = primitives[i]; + + // 1. create Mesh + + var mesh; + + let material = originalMaterials[i]; + + if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || + primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || + primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || + primitive.mode === undefined) { + + // .isSkinnedMesh isn't in glTF spec. See .markDefs() + mesh = meshDef.isSkinnedMesh === true ? + new THREE.SkinnedMesh(geometry, material) : + new THREE.Mesh(geometry, material); + + if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) { + + // we normalize floating point skin weight array to fix malformed assets (see #15319) + // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs + mesh.normalizeSkinWeights(); + + } + + if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) { + + mesh.drawMode = THREE.TriangleStripDrawMode; + + } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) { + + mesh.drawMode = THREE.TriangleFanDrawMode; + + } + + } else if (primitive.mode === WEBGL_CONSTANTS.LINES) { + + mesh = new THREE.LineSegments(geometry, material); + + } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) { + + mesh = new THREE.Line(geometry, material); + + } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) { + + mesh = new THREE.LineLoop(geometry, material); + + } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) { + + mesh = new THREE.Points(geometry, material); + + } else { + + throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode); + + } + + if (Object.keys(mesh.geometry.morphAttributes).length > 0) { + + updateMorphTargets(mesh, meshDef); + + } + + mesh.name = meshDef.name || ('mesh_' + meshIndex); + + if (geometries.length > 1) { + mesh.name += '_' + i; + } + + assignExtrasToUserData(mesh, meshDef); + + parser.assignFinalMaterial(mesh); + + meshes.push(mesh); + + } + + if (meshes.length === 1) { + + return meshes[0]; + + } + + let group = new THREE.Group(); + + for (var i = 0, il = meshes.length; i < il; i++) { + + group.add(meshes[i]); + + } + + return group; + + }); + + }); + + }; + + /** + * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras + * @param {number} cameraIndex + * @return {Promise} + */ + GLTFParser.prototype.loadCamera = function (cameraIndex) { + + let camera; + let cameraDef = this.json.cameras[cameraIndex]; + let params = cameraDef[cameraDef.type]; + + if (!params) { + + console.warn('THREE.GLTFLoader: Missing camera parameters.'); + return; + + } + + if (cameraDef.type === 'perspective') { + + camera = new THREE.PerspectiveCamera( + THREE.Math.radToDeg(params.yfov), + params.aspectRatio || 1, + params.znear || 1, + params.zfar || 2e6); + + } else if (cameraDef.type === 'orthographic') { + + camera = new THREE.OrthographicCamera(params.xmag / -2, params.xmag / 2, + params.ymag / 2, params.ymag / -2, params.znear, params.zfar); + + } + + if (cameraDef.name !== undefined) { + camera.name = cameraDef.name; + } + + assignExtrasToUserData(camera, cameraDef); + + return Promise.resolve(camera); + + }; + + /** + * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins + * @param {number} skinIndex + * @return {Promise} + */ + GLTFParser.prototype.loadSkin = function (skinIndex) { + + let skinDef = this.json.skins[skinIndex]; + + let skinEntry = { + joints: skinDef.joints, + }; + + if (skinDef.inverseBindMatrices === undefined) { + + return Promise.resolve(skinEntry); + + } + + return this.getDependency('accessor', skinDef.inverseBindMatrices) + .then(function (accessor) { + + skinEntry.inverseBindMatrices = accessor; + + return skinEntry; + + }); + + }; + + /** + * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations + * @param {number} animationIndex + * @return {Promise} + */ + GLTFParser.prototype.loadAnimation = function (animationIndex) { + + let json = this.json; + + let animationDef = json.animations[animationIndex]; + + let pendingNodes = []; + let pendingInputAccessors = []; + let pendingOutputAccessors = []; + let pendingSamplers = []; + let pendingTargets = []; + + for (let i = 0, il = animationDef.channels.length; i < il; i++) { + + let channel = animationDef.channels[i]; + let sampler = animationDef.samplers[channel.sampler]; + let target = channel.target; + let name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated. + let input = animationDef.parameters !== + undefined ? animationDef.parameters[sampler.input] : sampler.input; + let output = animationDef.parameters !== + undefined ? animationDef.parameters[sampler.output] : sampler.output; + + pendingNodes.push(this.getDependency('node', name)); + pendingInputAccessors.push(this.getDependency('accessor', input)); + pendingOutputAccessors.push(this.getDependency('accessor', output)); + pendingSamplers.push(sampler); + pendingTargets.push(target); + + } + + return Promise.all([ + + Promise.all(pendingNodes), + Promise.all(pendingInputAccessors), + Promise.all(pendingOutputAccessors), + Promise.all(pendingSamplers), + Promise.all(pendingTargets), + + ]).then(function (dependencies) { + + let nodes = dependencies[0]; + let inputAccessors = dependencies[1]; + let outputAccessors = dependencies[2]; + let samplers = dependencies[3]; + let targets = dependencies[4]; + + let tracks = []; + + for (let i = 0, il = nodes.length; i < il; i++) { + + let node = nodes[i]; + let inputAccessor = inputAccessors[i]; + let outputAccessor = outputAccessors[i]; + let sampler = samplers[i]; + let target = targets[i]; + + if (node === undefined) { + continue; + } + + node.updateMatrix(); + node.matrixAutoUpdate = true; + + var TypedKeyframeTrack; + + switch (PATH_PROPERTIES[target.path]) { + + case PATH_PROPERTIES.weights: + + TypedKeyframeTrack = THREE.NumberKeyframeTrack; + break; + + case PATH_PROPERTIES.rotation: + + TypedKeyframeTrack = THREE.QuaternionKeyframeTrack; + break; + + case PATH_PROPERTIES.position: + case PATH_PROPERTIES.scale: + default: + + TypedKeyframeTrack = THREE.VectorKeyframeTrack; + break; + + } + + let targetName = node.name ? node.name : node.uuid; + + let interpolation = sampler.interpolation !== + undefined ? INTERPOLATION[sampler.interpolation] : THREE.InterpolateLinear; + + var targetNames = []; + + if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) { + + // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh. + node.traverse(function (object) { + + if (object.isMesh === true && object.morphTargetInfluences) { + + targetNames.push(object.name ? object.name : object.uuid); + + } + + }); + + } else { + + targetNames.push(targetName); + + } + + let outputArray = outputAccessor.array; + + if (outputAccessor.normalized) { + + var scale; + + if (outputArray.constructor === Int8Array) { + + scale = 1 / 127; + + } else if (outputArray.constructor === Uint8Array) { + + scale = 1 / 255; + + } else if (outputArray.constructor === Int16Array) { + + scale = 1 / 32767; + + } else if (outputArray.constructor === Uint16Array) { + + scale = 1 / 65535; + + } else { + + throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.'); + + } + + let scaled = new Float32Array(outputArray.length); + + for (var j = 0, jl = outputArray.length; j < jl; j++) { + + scaled[j] = outputArray[j] * scale; + + } + + outputArray = scaled; + + } + + for (var j = 0, jl = targetNames.length; j < jl; j++) { + + let track = new TypedKeyframeTrack( + targetNames[j] + '.' + PATH_PROPERTIES[target.path], + inputAccessor.array, + outputArray, + interpolation + ); + + // Override interpolation with custom factory method. + if (sampler.interpolation === 'CUBICSPLINE') { + + track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) { + + // A CUBICSPLINE keyframe in glTF has three output values for each input value, + // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize() + // must be divided by three to get the interpolant's sampleSize argument. + + return new GLTFCubicSplineInterpolant(this.times, this.values, + this.getValueSize() / 3, result); + + }; + + // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants. + track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true; + + } + + tracks.push(track); + + } + + } + + let name = animationDef.name !== + undefined ? animationDef.name : 'animation_' + animationIndex; + + return new THREE.AnimationClip(name, undefined, tracks); + + }); + + }; + + /** + * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy + * @param {number} nodeIndex + * @return {Promise} + */ + GLTFParser.prototype.loadNode = function (nodeIndex) { + + let json = this.json; + let extensions = this.extensions; + let parser = this; + + let meshReferences = json.meshReferences; + let meshUses = json.meshUses; + + let nodeDef = json.nodes[nodeIndex]; + + return (function () { + + let pending = []; + + if (nodeDef.mesh !== undefined) { + + pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) { + + let node; + + if (meshReferences[nodeDef.mesh] > 1) { + + let instanceNum = meshUses[nodeDef.mesh]++; + + node = mesh.clone(); + node.name += '_instance_' + instanceNum; + + // onBeforeRender copy for Specular-Glossiness + node.onBeforeRender = mesh.onBeforeRender; + + for (let i = 0, il = node.children.length; i < il; i++) { + + node.children[i].name += '_instance_' + instanceNum; + node.children[i].onBeforeRender = mesh.children[i].onBeforeRender; + + } + + } else { + + node = mesh; + + } + + // if weights are provided on the node, override weights on the mesh. + if (nodeDef.weights !== undefined) { + + node.traverse(function (o) { + + if (!o.isMesh) { + return; + } + + for (let i = 0, il = nodeDef.weights.length; i < il; i++) { + + o.morphTargetInfluences[i] = nodeDef.weights[i]; + + } + + }); + + } + + return node; + + })); + + } + + if (nodeDef.camera !== undefined) { + + pending.push(parser.getDependency('camera', nodeDef.camera)); + + } + + if (nodeDef.extensions && + nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] && + nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light !== undefined) { + + pending.push(parser.getDependency('light', + nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light)); + + } + + return Promise.all(pending); + + }()).then(function (objects) { + + let node; + + // .isBone isn't in glTF spec. See .markDefs + if (nodeDef.isBone === true) { + + node = new THREE.Bone(); + + } else if (objects.length > 1) { + + node = new THREE.Group(); + + } else if (objects.length === 1) { + + node = objects[0]; + + } else { + + node = new THREE.Object3D(); + + } + + if (node !== objects[0]) { + + for (let i = 0, il = objects.length; i < il; i++) { + + node.add(objects[i]); + + } + + } + + if (nodeDef.name !== undefined) { + + node.userData.name = nodeDef.name; + node.name = THREE.PropertyBinding.sanitizeNodeName(nodeDef.name); + + } + + assignExtrasToUserData(node, nodeDef); + + if (nodeDef.extensions) { + addUnknownExtensionsToUserData(extensions, node, nodeDef); + } + + if (nodeDef.matrix !== undefined) { + + let matrix = new THREE.Matrix4(); + matrix.fromArray(nodeDef.matrix); + node.applyMatrix(matrix); + + } else { + + if (nodeDef.translation !== undefined) { + + node.position.fromArray(nodeDef.translation); + + } + + if (nodeDef.rotation !== undefined) { + + node.quaternion.fromArray(nodeDef.rotation); + + } + + if (nodeDef.scale !== undefined) { + + node.scale.fromArray(nodeDef.scale); + + } + + } + + return node; + + }); + + }; + + /** + * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes + * @param {number} sceneIndex + * @return {Promise} + */ + GLTFParser.prototype.loadScene = (function () { + + // scene node hierachy builder + + function buildNodeHierachy(nodeId, parentObject, json, parser) { + + let nodeDef = json.nodes[nodeId]; + + return parser.getDependency('node', nodeId).then(function (node) { + + if (nodeDef.skin === undefined) { + return node; + } + + // build skeleton here as well + + let skinEntry; + + return parser.getDependency('skin', nodeDef.skin).then(function (skin) { + + skinEntry = skin; + + let pendingJoints = []; + + for (let i = 0, il = skinEntry.joints.length; i < il; i++) { + + pendingJoints.push(parser.getDependency('node', skinEntry.joints[i])); + + } + + return Promise.all(pendingJoints); + + }).then(function (jointNodes) { + + node.traverse(function (mesh) { + + if (!mesh.isMesh) { + return; + } + + let bones = []; + let boneInverses = []; + + for (let j = 0, jl = jointNodes.length; j < jl; j++) { + + let jointNode = jointNodes[j]; + + if (jointNode) { + + bones.push(jointNode); + + let mat = new THREE.Matrix4(); + + if (skinEntry.inverseBindMatrices !== undefined) { + + mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16); + + } + + boneInverses.push(mat); + + } else { + + console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', + skinEntry.joints[j]); + + } + + } + + mesh.bind(new THREE.Skeleton(bones, boneInverses), mesh.matrixWorld); + + }); + + return node; + + }); + + }).then(function (node) { + + // build node hierachy + + parentObject.add(node); + + let pending = []; + + if (nodeDef.children) { + + let children = nodeDef.children; + + for (let i = 0, il = children.length; i < il; i++) { + + let child = children[i]; + pending.push(buildNodeHierachy(child, node, json, parser)); + + } + + } + + return Promise.all(pending); + + }); + + } + + return function loadScene(sceneIndex) { + + let json = this.json; + let extensions = this.extensions; + let sceneDef = this.json.scenes[sceneIndex]; + let parser = this; + + let scene = new THREE.Scene(); + if (sceneDef.name !== undefined) { + scene.name = sceneDef.name; + } + + assignExtrasToUserData(scene, sceneDef); + + if (sceneDef.extensions) { + addUnknownExtensionsToUserData(extensions, scene, sceneDef); + } + + let nodeIds = sceneDef.nodes || []; + + let pending = []; + + for (let i = 0, il = nodeIds.length; i < il; i++) { + + pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser)); + + } + + return Promise.all(pending).then(function () { + + return scene; + + }); + + }; + + }()); + + return GLTFLoader; + + })(); +} \ No newline at end of file diff --git a/miniprogram_npm/ais-h5-location/index.js b/miniprogram_npm/ais-h5-location/index.js new file mode 100644 index 0000000..1e1b65f --- /dev/null +++ b/miniprogram_npm/ais-h5-location/index.js @@ -0,0 +1,14 @@ +module.exports = (function() { +var __MODS__ = {}; +var __DEFINE__ = function(modId, func, req) { var m = { exports: {}, _tempexports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; }; +var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = __MODS__[modId].m; m._exports = m._tempexports; var desp = Object.getOwnPropertyDescriptor(m, "exports"); if (desp && desp.configurable) Object.defineProperty(m, "exports", { set: function (val) { if(typeof val === "object" && val !== m._exports) { m._exports.__proto__ = val.__proto__; Object.keys(val).forEach(function (k) { m._exports[k] = val[k]; }); } m._tempexports = val }, get: function () { return m._tempexports; } }); __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); } return __MODS__[modId].m.exports; }; +var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } }; +var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; }; +__DEFINE__(1657198795609, function(require, module, exports) { +var __TEMP__ = require('crypto-js');var enc = __TEMP__['enc'];var pad = __TEMP__['pad'];var AES = __TEMP__['AES'];const{encrypt,decrypt}=AES,encUtf8=enc.Utf8,padPkcs7=pad.Pkcs7,AESKey=4662573785223888,AESIv=0x9092593b7ae34,createrandkey=a=>{var t,o="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",n=o.length;let r="";for(let e=0;e{a=encUtf8.parse(a),t=encUtf8.parse(t);let o=encrypt(e,a,{iv:t,padding:padPkcs7});return o.toString()},decjson=(e,a=AESKey,t=AESIv)=>{a=encUtf8.parse(a),t=encUtf8.parse(t);let o=decrypt(e,a,{iv:t,padding:padPkcs7});return o.toString(encUtf8)},encparam=function(e,a,t){e=aesEncrypt(JSON.stringify(e),a,t),a=createrandkey(16);return{encparam:aesEncrypt(e,a,t),enckey:a}};let intervalTimer=null,beacons=null;const fakeImei=createrandkey(16),host="https://aispace.baidu.com",getProjectBasicInfo=o=>new Promise((a,t)=>{var e=encparam({project_id:o});wx.request({url:host+"/aispace/api/location/getprojectinfo",method:"GET",data:e,success:e=>{0===e.data.errno?e.data.data&&0{let o="";if(a.length{const{latitude:t,longitude:o}=e;e=[t,o,"wgs84"].join("|");let s="",n={ver:"1.0",trace:!1,prod:"test_loc_api",src:"baidu_loc_api",key:"5LONsKCadGA8T5r7gRPxoue37pFEXm8A",body:[{accesstype:3,imei:fakeImei,blelp:e,ctime:Math.ceil((new Date).getTime()/1e3).toString()}]};return a.forEach((e,a)=>{var t=e.major.toString(16).toUpperCase(),o=e.minor.toString(16).toUpperCase();const n=[e.uuid.toUpperCase(),addAddtionCodeLength(t),addAddtionCodeLength(o),e.accuracy].join("_"),r=Math.abs(e.rssi),c=Math.ceil((new Date).getTime()/1e3);s+=0{wx.startBeaconDiscovery({uuids:e,success:e=>{console.log("startBeaconDiscovery success >>>>>>")},fail:e=>{a(e)}})},realGetLocation=(a,e,t,o)=>{intervalTimer=setInterval(()=>{var e;!beacons||((e=processRequestQuery(a,beacons)).body[0].bleios||e.body[0].bleand)&&(e=encparam(e),wx.request({url:host+"/aispace/api/location/encrypt",method:"GET",data:e,success:e=>{e.data.data&&0{o(e)}}))},e)},getLocation=e=>{const{ak:a,intervalTime:t=1e3,successCb:o,failCb:n}=e;getProjectBasicInfo(a).then(e=>{startBeaconDiscovery(e.uuid,n),wx.onBeaconUpdate(e=>{beacons=e.beacons,console.log("onBeaconUpdate >>>>>>>>",beacons)}),realGetLocation(e,t,o,n)},e=>{n(e)})},stopBeaconScan=()=>{wx.stopBeaconDiscovery(),intervalTimer&&clearInterval(intervalTimer)};if (!exports.__esModule) Object.defineProperty(exports, "__esModule", { value: true });Object.defineProperty(exports, 'getLocation', { enumerable: true, configurable: true, get: function() { return getLocation; } });Object.defineProperty(exports, 'stopBeaconScan', { enumerable: true, configurable: true, get: function() { return stopBeaconScan; } }); + +}, function(modId) {var map = {}; return __REQUIRE__(map[modId], modId); }) +return __REQUIRE__(1657198795609); +})() +//miniprogram-npm-outsideDeps=["crypto-js"] +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/miniprogram_npm/ais-h5-location/index.js.map b/miniprogram_npm/ais-h5-location/index.js.map new file mode 100644 index 0000000..2a04150 --- /dev/null +++ b/miniprogram_npm/ais-h5-location/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["index.es.js"],"names":[],"mappings":";;;;;;;AAAA;AACA","file":"index.js","sourcesContent":["var __TEMP__ = require('crypto-js');var enc = __TEMP__['enc'];var pad = __TEMP__['pad'];var AES = __TEMP__['AES'];const{encrypt,decrypt}=AES,encUtf8=enc.Utf8,padPkcs7=pad.Pkcs7,AESKey=4662573785223888,AESIv=0x9092593b7ae34,createrandkey=a=>{var t,o=\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\",n=o.length;let r=\"\";for(let e=0;e{a=encUtf8.parse(a),t=encUtf8.parse(t);let o=encrypt(e,a,{iv:t,padding:padPkcs7});return o.toString()},decjson=(e,a=AESKey,t=AESIv)=>{a=encUtf8.parse(a),t=encUtf8.parse(t);let o=decrypt(e,a,{iv:t,padding:padPkcs7});return o.toString(encUtf8)},encparam=function(e,a,t){e=aesEncrypt(JSON.stringify(e),a,t),a=createrandkey(16);return{encparam:aesEncrypt(e,a,t),enckey:a}};let intervalTimer=null,beacons=null;const fakeImei=createrandkey(16),host=\"https://aispace.baidu.com\",getProjectBasicInfo=o=>new Promise((a,t)=>{var e=encparam({project_id:o});wx.request({url:host+\"/aispace/api/location/getprojectinfo\",method:\"GET\",data:e,success:e=>{0===e.data.errno?e.data.data&&0{let o=\"\";if(a.length{const{latitude:t,longitude:o}=e;e=[t,o,\"wgs84\"].join(\"|\");let s=\"\",n={ver:\"1.0\",trace:!1,prod:\"test_loc_api\",src:\"baidu_loc_api\",key:\"5LONsKCadGA8T5r7gRPxoue37pFEXm8A\",body:[{accesstype:3,imei:fakeImei,blelp:e,ctime:Math.ceil((new Date).getTime()/1e3).toString()}]};return a.forEach((e,a)=>{var t=e.major.toString(16).toUpperCase(),o=e.minor.toString(16).toUpperCase();const n=[e.uuid.toUpperCase(),addAddtionCodeLength(t),addAddtionCodeLength(o),e.accuracy].join(\"_\"),r=Math.abs(e.rssi),c=Math.ceil((new Date).getTime()/1e3);s+=0{wx.startBeaconDiscovery({uuids:e,success:e=>{console.log(\"startBeaconDiscovery success >>>>>>\")},fail:e=>{a(e)}})},realGetLocation=(a,e,t,o)=>{intervalTimer=setInterval(()=>{var e;!beacons||((e=processRequestQuery(a,beacons)).body[0].bleios||e.body[0].bleand)&&(e=encparam(e),wx.request({url:host+\"/aispace/api/location/encrypt\",method:\"GET\",data:e,success:e=>{e.data.data&&0{o(e)}}))},e)},getLocation=e=>{const{ak:a,intervalTime:t=1e3,successCb:o,failCb:n}=e;getProjectBasicInfo(a).then(e=>{startBeaconDiscovery(e.uuid,n),wx.onBeaconUpdate(e=>{beacons=e.beacons,console.log(\"onBeaconUpdate >>>>>>>>\",beacons)}),realGetLocation(e,t,o,n)},e=>{n(e)})},stopBeaconScan=()=>{wx.stopBeaconDiscovery(),intervalTimer&&clearInterval(intervalTimer)};if (!exports.__esModule) Object.defineProperty(exports, \"__esModule\", { value: true });Object.defineProperty(exports, 'getLocation', { enumerable: true, configurable: true, get: function() { return getLocation; } });Object.defineProperty(exports, 'stopBeaconScan', { enumerable: true, configurable: true, get: function() { return stopBeaconScan; } });\n"]} \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/CONTRIBUTING.md b/miniprogram_npm/crypto-js/CONTRIBUTING.md new file mode 100644 index 0000000..09bf774 --- /dev/null +++ b/miniprogram_npm/crypto-js/CONTRIBUTING.md @@ -0,0 +1,28 @@ +# Contribution + +# Git Flow + +The crypto-js project uses [git flow](https://github.com/nvie/gitflow) to manage branches. +Do your changes on the `develop` or even better on a `feature/*` branch. Don't do any changes on the `master` branch. + +# Pull request + +Target your pull request on `develop` branch. Other pull request won't be accepted. + +# How to build + +1. Clone + +2. Run + + ```sh + npm install + ``` + +3. Run + + ```sh + npm run build + ``` + +4. Check `build` folder \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/LICENSE b/miniprogram_npm/crypto-js/LICENSE new file mode 100644 index 0000000..b0828e5 --- /dev/null +++ b/miniprogram_npm/crypto-js/LICENSE @@ -0,0 +1,24 @@ +# License + +[The MIT License (MIT)](http://opensource.org/licenses/MIT) + +Copyright (c) 2009-2013 Jeff Mott +Copyright (c) 2013-2016 Evan Vosberg + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/miniprogram_npm/crypto-js/README.md b/miniprogram_npm/crypto-js/README.md new file mode 100644 index 0000000..23795aa --- /dev/null +++ b/miniprogram_npm/crypto-js/README.md @@ -0,0 +1,261 @@ +# crypto-js [![Build Status](https://travis-ci.org/brix/crypto-js.svg?branch=develop)](https://travis-ci.org/brix/crypto-js) + +JavaScript library of crypto standards. + +## Node.js (Install) + +Requirements: + +- Node.js +- npm (Node.js package manager) + +```bash +npm install crypto-js +``` + +### Usage + +ES6 import for typical API call signing use case: + +```javascript +import sha256 from 'crypto-js/sha256'; +import hmacSHA512 from 'crypto-js/hmac-sha512'; +import Base64 from 'crypto-js/enc-base64'; + +const message, nonce, path, privateKey; // ... +const hashDigest = sha256(nonce + message); +const hmacDigest = Base64.stringify(hmacSHA512(path + hashDigest, privateKey)); +``` + +Modular include: + +```javascript +var AES = require("crypto-js/aes"); +var SHA256 = require("crypto-js/sha256"); +... +console.log(SHA256("Message")); +``` + +Including all libraries, for access to extra methods: + +```javascript +var CryptoJS = require("crypto-js"); +console.log(CryptoJS.HmacSHA1("Message", "Key")); +``` + +## Client (browser) + +Requirements: + +- Node.js +- Bower (package manager for frontend) + +```bash +bower install crypto-js +``` + +### Usage + +Modular include: + +```javascript +require.config({ + packages: [ + { + name: 'crypto-js', + location: 'path-to/bower_components/crypto-js', + main: 'index' + } + ] +}); + +require(["crypto-js/aes", "crypto-js/sha256"], function (AES, SHA256) { + console.log(SHA256("Message")); +}); +``` + +Including all libraries, for access to extra methods: + +```javascript +// Above-mentioned will work or use this simple form +require.config({ + paths: { + 'crypto-js': 'path-to/bower_components/crypto-js/crypto-js' + } +}); + +require(["crypto-js"], function (CryptoJS) { + console.log(CryptoJS.HmacSHA1("Message", "Key")); +}); +``` + +### Usage without RequireJS + +```html + + +``` + +## API + +See: https://cryptojs.gitbook.io/docs/ + +### AES Encryption + +#### Plain text encryption + +```javascript +var CryptoJS = require("crypto-js"); + +// Encrypt +var ciphertext = CryptoJS.AES.encrypt('my message', 'secret key 123').toString(); + +// Decrypt +var bytes = CryptoJS.AES.decrypt(ciphertext, 'secret key 123'); +var originalText = bytes.toString(CryptoJS.enc.Utf8); + +console.log(originalText); // 'my message' +``` + +#### Object encryption + +```javascript +var CryptoJS = require("crypto-js"); + +var data = [{id: 1}, {id: 2}] + +// Encrypt +var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'secret key 123').toString(); + +// Decrypt +var bytes = CryptoJS.AES.decrypt(ciphertext, 'secret key 123'); +var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8)); + +console.log(decryptedData); // [{id: 1}, {id: 2}] +``` + +### List of modules + + +- ```crypto-js/core``` +- ```crypto-js/x64-core``` +- ```crypto-js/lib-typedarrays``` + +--- + +- ```crypto-js/md5``` +- ```crypto-js/sha1``` +- ```crypto-js/sha256``` +- ```crypto-js/sha224``` +- ```crypto-js/sha512``` +- ```crypto-js/sha384``` +- ```crypto-js/sha3``` +- ```crypto-js/ripemd160``` + +--- + +- ```crypto-js/hmac-md5``` +- ```crypto-js/hmac-sha1``` +- ```crypto-js/hmac-sha256``` +- ```crypto-js/hmac-sha224``` +- ```crypto-js/hmac-sha512``` +- ```crypto-js/hmac-sha384``` +- ```crypto-js/hmac-sha3``` +- ```crypto-js/hmac-ripemd160``` + +--- + +- ```crypto-js/pbkdf2``` + +--- + +- ```crypto-js/aes``` +- ```crypto-js/tripledes``` +- ```crypto-js/rc4``` +- ```crypto-js/rabbit``` +- ```crypto-js/rabbit-legacy``` +- ```crypto-js/evpkdf``` + +--- + +- ```crypto-js/format-openssl``` +- ```crypto-js/format-hex``` + +--- + +- ```crypto-js/enc-latin1``` +- ```crypto-js/enc-utf8``` +- ```crypto-js/enc-hex``` +- ```crypto-js/enc-utf16``` +- ```crypto-js/enc-base64``` + +--- + +- ```crypto-js/mode-cfb``` +- ```crypto-js/mode-ctr``` +- ```crypto-js/mode-ctr-gladman``` +- ```crypto-js/mode-ofb``` +- ```crypto-js/mode-ecb``` + +--- + +- ```crypto-js/pad-pkcs7``` +- ```crypto-js/pad-ansix923``` +- ```crypto-js/pad-iso10126``` +- ```crypto-js/pad-iso97971``` +- ```crypto-js/pad-zeropadding``` +- ```crypto-js/pad-nopadding``` + + +## Release notes + +### 4.1.1 + +Fix module order in bundled release. + +Include the browser field in the released package.json. + +### 4.1.0 + +Added url safe variant of base64 encoding. [357](https://github.com/brix/crypto-js/pull/357) + +Avoid webpack to add crypto-browser package. [364](https://github.com/brix/crypto-js/pull/364) + +### 4.0.0 + +This is an update including breaking changes for some environments. + +In this version `Math.random()` has been replaced by the random methods of the native crypto module. + +For this reason CryptoJS might not run in some JavaScript environments without native crypto module. Such as IE 10 or before or React Native. + +### 3.3.0 + +Rollback, `3.3.0` is the same as `3.1.9-1`. + +The move of using native secure crypto module will be shifted to a new `4.x.x` version. As it is a breaking change the impact is too big for a minor release. + +### 3.2.1 + +The usage of the native crypto module has been fixed. The import and access of the native crypto module has been improved. + +### 3.2.0 + +In this version `Math.random()` has been replaced by the random methods of the native crypto module. + +For this reason CryptoJS might does not run in some JavaScript environments without native crypto module. Such as IE 10 or before. + +If it's absolute required to run CryptoJS in such an environment, stay with `3.1.x` version. Encrypting and decrypting stays compatible. But keep in mind `3.1.x` versions still use `Math.random()` which is cryptographically not secure, as it's not random enough. + +This version came along with `CRITICAL` `BUG`. + +DO NOT USE THIS VERSION! Please, go for a newer version! + +### 3.1.x + +The `3.1.x` are based on the original CryptoJS, wrapped in CommonJS modules. + + diff --git a/miniprogram_npm/crypto-js/aes.js b/miniprogram_npm/crypto-js/aes.js new file mode 100644 index 0000000..166e3ea --- /dev/null +++ b/miniprogram_npm/crypto-js/aes.js @@ -0,0 +1,234 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + // Lookup tables + var SBOX = []; + var INV_SBOX = []; + var SUB_MIX_0 = []; + var SUB_MIX_1 = []; + var SUB_MIX_2 = []; + var SUB_MIX_3 = []; + var INV_SUB_MIX_0 = []; + var INV_SUB_MIX_1 = []; + var INV_SUB_MIX_2 = []; + var INV_SUB_MIX_3 = []; + + // Compute lookup tables + (function () { + // Compute double table + var d = []; + for (var i = 0; i < 256; i++) { + if (i < 128) { + d[i] = i << 1; + } else { + d[i] = (i << 1) ^ 0x11b; + } + } + + // Walk GF(2^8) + var x = 0; + var xi = 0; + for (var i = 0; i < 256; i++) { + // Compute sbox + var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; + SBOX[x] = sx; + INV_SBOX[sx] = x; + + // Compute multiplication + var x2 = d[x]; + var x4 = d[x2]; + var x8 = d[x4]; + + // Compute sub bytes, mix columns tables + var t = (d[sx] * 0x101) ^ (sx * 0x1010100); + SUB_MIX_0[x] = (t << 24) | (t >>> 8); + SUB_MIX_1[x] = (t << 16) | (t >>> 16); + SUB_MIX_2[x] = (t << 8) | (t >>> 24); + SUB_MIX_3[x] = t; + + // Compute inv sub bytes, inv mix columns tables + var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); + INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); + INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); + INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); + INV_SUB_MIX_3[sx] = t; + + // Compute next counter + if (!x) { + x = xi = 1; + } else { + x = x2 ^ d[d[d[x8 ^ x2]]]; + xi ^= d[d[xi]]; + } + } + }()); + + // Precomputed Rcon lookup + var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; + + /** + * AES block cipher algorithm. + */ + var AES = C_algo.AES = BlockCipher.extend({ + _doReset: function () { + var t; + + // Skip reset of nRounds has been set before and key did not change + if (this._nRounds && this._keyPriorReset === this._key) { + return; + } + + // Shortcuts + var key = this._keyPriorReset = this._key; + var keyWords = key.words; + var keySize = key.sigBytes / 4; + + // Compute number of rounds + var nRounds = this._nRounds = keySize + 6; + + // Compute number of key schedule rows + var ksRows = (nRounds + 1) * 4; + + // Compute key schedule + var keySchedule = this._keySchedule = []; + for (var ksRow = 0; ksRow < ksRows; ksRow++) { + if (ksRow < keySize) { + keySchedule[ksRow] = keyWords[ksRow]; + } else { + t = keySchedule[ksRow - 1]; + + if (!(ksRow % keySize)) { + // Rot word + t = (t << 8) | (t >>> 24); + + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; + + // Mix Rcon + t ^= RCON[(ksRow / keySize) | 0] << 24; + } else if (keySize > 6 && ksRow % keySize == 4) { + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; + } + + keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; + } + } + + // Compute inv key schedule + var invKeySchedule = this._invKeySchedule = []; + for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { + var ksRow = ksRows - invKsRow; + + if (invKsRow % 4) { + var t = keySchedule[ksRow]; + } else { + var t = keySchedule[ksRow - 4]; + } + + if (invKsRow < 4 || ksRow <= 4) { + invKeySchedule[invKsRow] = t; + } else { + invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ + INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; + } + } + }, + + encryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); + }, + + decryptBlock: function (M, offset) { + // Swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + + this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); + + // Inv swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + }, + + _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { + // Shortcut + var nRounds = this._nRounds; + + // Get input, add round key + var s0 = M[offset] ^ keySchedule[0]; + var s1 = M[offset + 1] ^ keySchedule[1]; + var s2 = M[offset + 2] ^ keySchedule[2]; + var s3 = M[offset + 3] ^ keySchedule[3]; + + // Key schedule row counter + var ksRow = 4; + + // Rounds + for (var round = 1; round < nRounds; round++) { + // Shift rows, sub bytes, mix columns, add round key + var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; + var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; + var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; + var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; + + // Update state + s0 = t0; + s1 = t1; + s2 = t2; + s3 = t3; + } + + // Shift rows, sub bytes, add round key + var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; + var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; + var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; + var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; + + // Set output + M[offset] = t0; + M[offset + 1] = t1; + M[offset + 2] = t2; + M[offset + 3] = t3; + }, + + keySize: 256/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); + */ + C.AES = BlockCipher._createHelper(AES); + }()); + + + return CryptoJS.AES; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/bower.json b/miniprogram_npm/crypto-js/bower.json new file mode 100644 index 0000000..1e12fdc --- /dev/null +++ b/miniprogram_npm/crypto-js/bower.json @@ -0,0 +1,39 @@ +{ + "name": "crypto-js", + "version": "4.1.1", + "description": "JavaScript library of crypto standards.", + "license": "MIT", + "homepage": "http://github.com/brix/crypto-js", + "repository": { + "type": "git", + "url": "http://github.com/brix/crypto-js.git" + }, + "keywords": [ + "security", + "crypto", + "Hash", + "MD5", + "SHA1", + "SHA-1", + "SHA256", + "SHA-256", + "RC4", + "Rabbit", + "AES", + "DES", + "PBKDF2", + "HMAC", + "OFB", + "CFB", + "CTR", + "CBC", + "Base64", + "Base64url" + ], + "main": "index.js", + "dependencies": {}, + "browser": { + "crypto": false + }, + "ignore": [] +} diff --git a/miniprogram_npm/crypto-js/cipher-core.js b/miniprogram_npm/crypto-js/cipher-core.js new file mode 100644 index 0000000..c560c9e --- /dev/null +++ b/miniprogram_npm/crypto-js/cipher-core.js @@ -0,0 +1,890 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./evpkdf")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./evpkdf"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * Cipher core components. + */ + CryptoJS.lib.Cipher || (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; + var C_enc = C.enc; + var Utf8 = C_enc.Utf8; + var Base64 = C_enc.Base64; + var C_algo = C.algo; + var EvpKDF = C_algo.EvpKDF; + + /** + * Abstract base cipher template. + * + * @property {number} keySize This cipher's key size. Default: 4 (128 bits) + * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) + * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. + * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. + */ + var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + * + * @property {WordArray} iv The IV to use for this operation. + */ + cfg: Base.extend(), + + /** + * Creates this cipher in encryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); + */ + createEncryptor: function (key, cfg) { + return this.create(this._ENC_XFORM_MODE, key, cfg); + }, + + /** + * Creates this cipher in decryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); + */ + createDecryptor: function (key, cfg) { + return this.create(this._DEC_XFORM_MODE, key, cfg); + }, + + /** + * Initializes a newly created cipher. + * + * @param {number} xformMode Either the encryption or decryption transormation mode constant. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @example + * + * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); + */ + init: function (xformMode, key, cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); + + // Store transform mode and key + this._xformMode = xformMode; + this._key = key; + + // Set initial values + this.reset(); + }, + + /** + * Resets this cipher to its initial state. + * + * @example + * + * cipher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-cipher logic + this._doReset(); + }, + + /** + * Adds data to be encrypted or decrypted. + * + * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. + * + * @return {WordArray} The data after processing. + * + * @example + * + * var encrypted = cipher.process('data'); + * var encrypted = cipher.process(wordArray); + */ + process: function (dataUpdate) { + // Append + this._append(dataUpdate); + + // Process available blocks + return this._process(); + }, + + /** + * Finalizes the encryption or decryption process. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. + * + * @return {WordArray} The data after final processing. + * + * @example + * + * var encrypted = cipher.finalize(); + * var encrypted = cipher.finalize('data'); + * var encrypted = cipher.finalize(wordArray); + */ + finalize: function (dataUpdate) { + // Final data update + if (dataUpdate) { + this._append(dataUpdate); + } + + // Perform concrete-cipher logic + var finalProcessedData = this._doFinalize(); + + return finalProcessedData; + }, + + keySize: 128/32, + + ivSize: 128/32, + + _ENC_XFORM_MODE: 1, + + _DEC_XFORM_MODE: 2, + + /** + * Creates shortcut functions to a cipher's object interface. + * + * @param {Cipher} cipher The cipher to create a helper for. + * + * @return {Object} An object with encrypt and decrypt shortcut functions. + * + * @static + * + * @example + * + * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); + */ + _createHelper: (function () { + function selectCipherStrategy(key) { + if (typeof key == 'string') { + return PasswordBasedCipher; + } else { + return SerializableCipher; + } + } + + return function (cipher) { + return { + encrypt: function (message, key, cfg) { + return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); + }, + + decrypt: function (ciphertext, key, cfg) { + return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); + } + }; + }; + }()) + }); + + /** + * Abstract base stream cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) + */ + var StreamCipher = C_lib.StreamCipher = Cipher.extend({ + _doFinalize: function () { + // Process partial blocks + var finalProcessedBlocks = this._process(!!'flush'); + + return finalProcessedBlocks; + }, + + blockSize: 1 + }); + + /** + * Mode namespace. + */ + var C_mode = C.mode = {}; + + /** + * Abstract base block cipher mode template. + */ + var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ + /** + * Creates this mode for encryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); + */ + createEncryptor: function (cipher, iv) { + return this.Encryptor.create(cipher, iv); + }, + + /** + * Creates this mode for decryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); + */ + createDecryptor: function (cipher, iv) { + return this.Decryptor.create(cipher, iv); + }, + + /** + * Initializes a newly created mode. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @example + * + * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); + */ + init: function (cipher, iv) { + this._cipher = cipher; + this._iv = iv; + } + }); + + /** + * Cipher Block Chaining mode. + */ + var CBC = C_mode.CBC = (function () { + /** + * Abstract base CBC mode. + */ + var CBC = BlockCipherMode.extend(); + + /** + * CBC encryptor. + */ + CBC.Encryptor = CBC.extend({ + /** + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example + * + * mode.processBlock(data.words, offset); + */ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // XOR and encrypt + xorBlock.call(this, words, offset, blockSize); + cipher.encryptBlock(words, offset); + + // Remember this block to use with next block + this._prevBlock = words.slice(offset, offset + blockSize); + } + }); + + /** + * CBC decryptor. + */ + CBC.Decryptor = CBC.extend({ + /** + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example + * + * mode.processBlock(data.words, offset); + */ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // Remember this block to use with next block + var thisBlock = words.slice(offset, offset + blockSize); + + // Decrypt and XOR + cipher.decryptBlock(words, offset); + xorBlock.call(this, words, offset, blockSize); + + // This block becomes the previous block + this._prevBlock = thisBlock; + } + }); + + function xorBlock(words, offset, blockSize) { + var block; + + // Shortcut + var iv = this._iv; + + // Choose mixing block + if (iv) { + block = iv; + + // Remove IV for subsequent blocks + this._iv = undefined; + } else { + block = this._prevBlock; + } + + // XOR blocks + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= block[i]; + } + } + + return CBC; + }()); + + /** + * Padding namespace. + */ + var C_pad = C.pad = {}; + + /** + * PKCS #5/7 padding strategy. + */ + var Pkcs7 = C_pad.Pkcs7 = { + /** + * Pads data using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to pad. + * @param {number} blockSize The multiple that the data should be padded to. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.pad(wordArray, 4); + */ + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; + + // Create padding word + var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; + + // Create padding + var paddingWords = []; + for (var i = 0; i < nPaddingBytes; i += 4) { + paddingWords.push(paddingWord); + } + var padding = WordArray.create(paddingWords, nPaddingBytes); + + // Add padding + data.concat(padding); + }, + + /** + * Unpads data that had been padded using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to unpad. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.unpad(wordArray); + */ + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + /** + * Abstract base block cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) + */ + var BlockCipher = C_lib.BlockCipher = Cipher.extend({ + /** + * Configuration options. + * + * @property {Mode} mode The block mode to use. Default: CBC + * @property {Padding} padding The padding strategy to use. Default: Pkcs7 + */ + cfg: Cipher.cfg.extend({ + mode: CBC, + padding: Pkcs7 + }), + + reset: function () { + var modeCreator; + + // Reset cipher + Cipher.reset.call(this); + + // Shortcuts + var cfg = this.cfg; + var iv = cfg.iv; + var mode = cfg.mode; + + // Reset block mode + if (this._xformMode == this._ENC_XFORM_MODE) { + modeCreator = mode.createEncryptor; + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + modeCreator = mode.createDecryptor; + // Keep at least one block in the buffer for unpadding + this._minBufferSize = 1; + } + + if (this._mode && this._mode.__creator == modeCreator) { + this._mode.init(this, iv && iv.words); + } else { + this._mode = modeCreator.call(mode, this, iv && iv.words); + this._mode.__creator = modeCreator; + } + }, + + _doProcessBlock: function (words, offset) { + this._mode.processBlock(words, offset); + }, + + _doFinalize: function () { + var finalProcessedBlocks; + + // Shortcut + var padding = this.cfg.padding; + + // Finalize + if (this._xformMode == this._ENC_XFORM_MODE) { + // Pad data + padding.pad(this._data, this.blockSize); + + // Process final blocks + finalProcessedBlocks = this._process(!!'flush'); + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + // Process final blocks + finalProcessedBlocks = this._process(!!'flush'); + + // Unpad data + padding.unpad(finalProcessedBlocks); + } + + return finalProcessedBlocks; + }, + + blockSize: 128/32 + }); + + /** + * A collection of cipher parameters. + * + * @property {WordArray} ciphertext The raw ciphertext. + * @property {WordArray} key The key to this ciphertext. + * @property {WordArray} iv The IV used in the ciphering operation. + * @property {WordArray} salt The salt used with a key derivation function. + * @property {Cipher} algorithm The cipher algorithm. + * @property {Mode} mode The block mode used in the ciphering operation. + * @property {Padding} padding The padding scheme used in the ciphering operation. + * @property {number} blockSize The block size of the cipher. + * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. + */ + var CipherParams = C_lib.CipherParams = Base.extend({ + /** + * Initializes a newly created cipher params object. + * + * @param {Object} cipherParams An object with any of the possible cipher parameters. + * + * @example + * + * var cipherParams = CryptoJS.lib.CipherParams.create({ + * ciphertext: ciphertextWordArray, + * key: keyWordArray, + * iv: ivWordArray, + * salt: saltWordArray, + * algorithm: CryptoJS.algo.AES, + * mode: CryptoJS.mode.CBC, + * padding: CryptoJS.pad.PKCS7, + * blockSize: 4, + * formatter: CryptoJS.format.OpenSSL + * }); + */ + init: function (cipherParams) { + this.mixIn(cipherParams); + }, + + /** + * Converts this cipher params object to a string. + * + * @param {Format} formatter (Optional) The formatting strategy to use. + * + * @return {string} The stringified cipher params. + * + * @throws Error If neither the formatter nor the default formatter is set. + * + * @example + * + * var string = cipherParams + ''; + * var string = cipherParams.toString(); + * var string = cipherParams.toString(CryptoJS.format.OpenSSL); + */ + toString: function (formatter) { + return (formatter || this.formatter).stringify(this); + } + }); + + /** + * Format namespace. + */ + var C_format = C.format = {}; + + /** + * OpenSSL formatting strategy. + */ + var OpenSSLFormatter = C_format.OpenSSL = { + /** + * Converts a cipher params object to an OpenSSL-compatible string. + * + * @param {CipherParams} cipherParams The cipher params object. + * + * @return {string} The OpenSSL-compatible string. + * + * @static + * + * @example + * + * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); + */ + stringify: function (cipherParams) { + var wordArray; + + // Shortcuts + var ciphertext = cipherParams.ciphertext; + var salt = cipherParams.salt; + + // Format + if (salt) { + wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); + } else { + wordArray = ciphertext; + } + + return wordArray.toString(Base64); + }, + + /** + * Converts an OpenSSL-compatible string to a cipher params object. + * + * @param {string} openSSLStr The OpenSSL-compatible string. + * + * @return {CipherParams} The cipher params object. + * + * @static + * + * @example + * + * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); + */ + parse: function (openSSLStr) { + var salt; + + // Parse base64 + var ciphertext = Base64.parse(openSSLStr); + + // Shortcut + var ciphertextWords = ciphertext.words; + + // Test for salt + if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { + // Extract salt + salt = WordArray.create(ciphertextWords.slice(2, 4)); + + // Remove salt from ciphertext + ciphertextWords.splice(0, 4); + ciphertext.sigBytes -= 16; + } + + return CipherParams.create({ ciphertext: ciphertext, salt: salt }); + } + }; + + /** + * A cipher wrapper that returns ciphertext as a serializable cipher params object. + */ + var SerializableCipher = C_lib.SerializableCipher = Base.extend({ + /** + * Configuration options. + * + * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL + */ + cfg: Base.extend({ + format: OpenSSLFormatter + }), + + /** + * Encrypts a message. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Encrypt + var encryptor = cipher.createEncryptor(key, cfg); + var ciphertext = encryptor.finalize(message); + + // Shortcut + var cipherCfg = encryptor.cfg; + + // Create and return serializable cipher params + return CipherParams.create({ + ciphertext: ciphertext, + key: key, + iv: cipherCfg.iv, + algorithm: cipher, + mode: cipherCfg.mode, + padding: cipherCfg.padding, + blockSize: cipher.blockSize, + formatter: cfg.format + }); + }, + + /** + * Decrypts serialized ciphertext. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); + + // Decrypt + var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); + + return plaintext; + }, + + /** + * Converts serialized ciphertext to CipherParams, + * else assumed CipherParams already and returns ciphertext unchanged. + * + * @param {CipherParams|string} ciphertext The ciphertext. + * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. + * + * @return {CipherParams} The unserialized ciphertext. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); + */ + _parse: function (ciphertext, format) { + if (typeof ciphertext == 'string') { + return format.parse(ciphertext, this); + } else { + return ciphertext; + } + } + }); + + /** + * Key derivation function namespace. + */ + var C_kdf = C.kdf = {}; + + /** + * OpenSSL key derivation function. + */ + var OpenSSLKdf = C_kdf.OpenSSL = { + /** + * Derives a key and IV from a password. + * + * @param {string} password The password to derive from. + * @param {number} keySize The size in words of the key to generate. + * @param {number} ivSize The size in words of the IV to generate. + * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. + * + * @return {CipherParams} A cipher params object with the key, IV, and salt. + * + * @static + * + * @example + * + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); + */ + execute: function (password, keySize, ivSize, salt) { + // Generate random salt + if (!salt) { + salt = WordArray.random(64/8); + } + + // Derive key and IV + var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); + + // Separate key and IV + var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); + key.sigBytes = keySize * 4; + + // Return params + return CipherParams.create({ key: key, iv: iv, salt: salt }); + } + }; + + /** + * A serializable cipher wrapper that derives the key from a password, + * and returns ciphertext as a serializable cipher params object. + */ + var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ + /** + * Configuration options. + * + * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL + */ + cfg: SerializableCipher.cfg.extend({ + kdf: OpenSSLKdf + }), + + /** + * Encrypts a message using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Derive key and other params + var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); + + // Add IV to config + cfg.iv = derivedParams.iv; + + // Encrypt + var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); + + // Mix in derived params + ciphertext.mixIn(derivedParams); + + return ciphertext; + }, + + /** + * Decrypts serialized ciphertext using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); + + // Derive key and other params + var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); + + // Add IV to config + cfg.iv = derivedParams.iv; + + // Decrypt + var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); + + return plaintext; + } + }); + }()); + + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/core.js b/miniprogram_npm/crypto-js/core.js new file mode 100644 index 0000000..e3a498b --- /dev/null +++ b/miniprogram_npm/crypto-js/core.js @@ -0,0 +1,807 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(); + } + else if (typeof define === "function" && define.amd) { + // AMD + define([], factory); + } + else { + // Global (browser) + root.CryptoJS = factory(); + } +}(this, function () { + + /*globals window, global, require*/ + + /** + * CryptoJS core components. + */ + var CryptoJS = CryptoJS || (function (Math, undefined) { + + var crypto; + + // Native crypto from window (Browser) + if (typeof window !== 'undefined' && window.crypto) { + crypto = window.crypto; + } + + // Native crypto in web worker (Browser) + if (typeof self !== 'undefined' && self.crypto) { + crypto = self.crypto; + } + + // Native crypto from worker + if (typeof globalThis !== 'undefined' && globalThis.crypto) { + crypto = globalThis.crypto; + } + + // Native (experimental IE 11) crypto from window (Browser) + if (!crypto && typeof window !== 'undefined' && window.msCrypto) { + crypto = window.msCrypto; + } + + // Native crypto from global (NodeJS) + if (!crypto && typeof global !== 'undefined' && global.crypto) { + crypto = global.crypto; + } + + // Native crypto import via require (NodeJS) + if (!crypto && typeof require === 'function') { + try { + crypto = require('crypto'); + } catch (err) {} + } + + /* + * Cryptographically secure pseudorandom number generator + * + * As Math.random() is cryptographically not safe to use + */ + var cryptoSecureRandomInt = function () { + if (crypto) { + // Use getRandomValues method (Browser) + if (typeof crypto.getRandomValues === 'function') { + try { + return crypto.getRandomValues(new Uint32Array(1))[0]; + } catch (err) {} + } + + // Use randomBytes method (NodeJS) + if (typeof crypto.randomBytes === 'function') { + try { + return crypto.randomBytes(4).readInt32LE(); + } catch (err) {} + } + } + + throw new Error('Native crypto module could not be used to get secure random number.'); + }; + + /* + * Local polyfill of Object.create + + */ + var create = Object.create || (function () { + function F() {} + + return function (obj) { + var subtype; + + F.prototype = obj; + + subtype = new F(); + + F.prototype = null; + + return subtype; + }; + }()); + + /** + * CryptoJS namespace. + */ + var C = {}; + + /** + * Library namespace. + */ + var C_lib = C.lib = {}; + + /** + * Base object for prototypal inheritance. + */ + var Base = C_lib.Base = (function () { + + + return { + /** + * Creates a new object that inherits from this object. + * + * @param {Object} overrides Properties to copy into the new object. + * + * @return {Object} The new object. + * + * @static + * + * @example + * + * var MyType = CryptoJS.lib.Base.extend({ + * field: 'value', + * + * method: function () { + * } + * }); + */ + extend: function (overrides) { + // Spawn + var subtype = create(this); + + // Augment + if (overrides) { + subtype.mixIn(overrides); + } + + // Create default initializer + if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { + subtype.init = function () { + subtype.$super.init.apply(this, arguments); + }; + } + + // Initializer's prototype is the subtype object + subtype.init.prototype = subtype; + + // Reference supertype + subtype.$super = this; + + return subtype; + }, + + /** + * Extends this object and runs the init method. + * Arguments to create() will be passed to init(). + * + * @return {Object} The new object. + * + * @static + * + * @example + * + * var instance = MyType.create(); + */ + create: function () { + var instance = this.extend(); + instance.init.apply(instance, arguments); + + return instance; + }, + + /** + * Initializes a newly created object. + * Override this method to add some logic when your objects are created. + * + * @example + * + * var MyType = CryptoJS.lib.Base.extend({ + * init: function () { + * // ... + * } + * }); + */ + init: function () { + }, + + /** + * Copies properties into this object. + * + * @param {Object} properties The properties to mix in. + * + * @example + * + * MyType.mixIn({ + * field: 'value' + * }); + */ + mixIn: function (properties) { + for (var propertyName in properties) { + if (properties.hasOwnProperty(propertyName)) { + this[propertyName] = properties[propertyName]; + } + } + + // IE won't copy toString using the loop above + if (properties.hasOwnProperty('toString')) { + this.toString = properties.toString; + } + }, + + /** + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = instance.clone(); + */ + clone: function () { + return this.init.prototype.extend(this); + } + }; + }()); + + /** + * An array of 32-bit words. + * + * @property {Array} words The array of 32-bit words. + * @property {number} sigBytes The number of significant bytes in this word array. + */ + var WordArray = C_lib.WordArray = Base.extend({ + /** + * Initializes a newly created word array. + * + * @param {Array} words (Optional) An array of 32-bit words. + * @param {number} sigBytes (Optional) The number of significant bytes in the words. + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.create(); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); + */ + init: function (words, sigBytes) { + words = this.words = words || []; + + if (sigBytes != undefined) { + this.sigBytes = sigBytes; + } else { + this.sigBytes = words.length * 4; + } + }, + + /** + * Converts this word array to a string. + * + * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex + * + * @return {string} The stringified word array. + * + * @example + * + * var string = wordArray + ''; + * var string = wordArray.toString(); + * var string = wordArray.toString(CryptoJS.enc.Utf8); + */ + toString: function (encoder) { + return (encoder || Hex).stringify(this); + }, + + /** + * Concatenates a word array to this word array. + * + * @param {WordArray} wordArray The word array to append. + * + * @return {WordArray} This word array. + * + * @example + * + * wordArray1.concat(wordArray2); + */ + concat: function (wordArray) { + // Shortcuts + var thisWords = this.words; + var thatWords = wordArray.words; + var thisSigBytes = this.sigBytes; + var thatSigBytes = wordArray.sigBytes; + + // Clamp excess bits + this.clamp(); + + // Concat + if (thisSigBytes % 4) { + // Copy one byte at a time + for (var i = 0; i < thatSigBytes; i++) { + var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); + } + } else { + // Copy one word at a time + for (var j = 0; j < thatSigBytes; j += 4) { + thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2]; + } + } + this.sigBytes += thatSigBytes; + + // Chainable + return this; + }, + + /** + * Removes insignificant bits. + * + * @example + * + * wordArray.clamp(); + */ + clamp: function () { + // Shortcuts + var words = this.words; + var sigBytes = this.sigBytes; + + // Clamp + words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); + words.length = Math.ceil(sigBytes / 4); + }, + + /** + * Creates a copy of this word array. + * + * @return {WordArray} The clone. + * + * @example + * + * var clone = wordArray.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + clone.words = this.words.slice(0); + + return clone; + }, + + /** + * Creates a word array filled with random bytes. + * + * @param {number} nBytes The number of random bytes to generate. + * + * @return {WordArray} The random word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.random(16); + */ + random: function (nBytes) { + var words = []; + + for (var i = 0; i < nBytes; i += 4) { + words.push(cryptoSecureRandomInt()); + } + + return new WordArray.init(words, nBytes); + } + }); + + /** + * Encoder namespace. + */ + var C_enc = C.enc = {}; + + /** + * Hex encoding strategy. + */ + var Hex = C_enc.Hex = { + /** + * Converts a word array to a hex string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The hex string. + * + * @static + * + * @example + * + * var hexString = CryptoJS.enc.Hex.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var hexChars = []; + for (var i = 0; i < sigBytes; i++) { + var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + hexChars.push((bite >>> 4).toString(16)); + hexChars.push((bite & 0x0f).toString(16)); + } + + return hexChars.join(''); + }, + + /** + * Converts a hex string to a word array. + * + * @param {string} hexStr The hex string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Hex.parse(hexString); + */ + parse: function (hexStr) { + // Shortcut + var hexStrLength = hexStr.length; + + // Convert + var words = []; + for (var i = 0; i < hexStrLength; i += 2) { + words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); + } + + return new WordArray.init(words, hexStrLength / 2); + } + }; + + /** + * Latin1 encoding strategy. + */ + var Latin1 = C_enc.Latin1 = { + /** + * Converts a word array to a Latin1 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Latin1 string. + * + * @static + * + * @example + * + * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var latin1Chars = []; + for (var i = 0; i < sigBytes; i++) { + var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + latin1Chars.push(String.fromCharCode(bite)); + } + + return latin1Chars.join(''); + }, + + /** + * Converts a Latin1 string to a word array. + * + * @param {string} latin1Str The Latin1 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); + */ + parse: function (latin1Str) { + // Shortcut + var latin1StrLength = latin1Str.length; + + // Convert + var words = []; + for (var i = 0; i < latin1StrLength; i++) { + words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); + } + + return new WordArray.init(words, latin1StrLength); + } + }; + + /** + * UTF-8 encoding strategy. + */ + var Utf8 = C_enc.Utf8 = { + /** + * Converts a word array to a UTF-8 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-8 string. + * + * @static + * + * @example + * + * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); + */ + stringify: function (wordArray) { + try { + return decodeURIComponent(escape(Latin1.stringify(wordArray))); + } catch (e) { + throw new Error('Malformed UTF-8 data'); + } + }, + + /** + * Converts a UTF-8 string to a word array. + * + * @param {string} utf8Str The UTF-8 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); + */ + parse: function (utf8Str) { + return Latin1.parse(unescape(encodeURIComponent(utf8Str))); + } + }; + + /** + * Abstract buffered block algorithm template. + * + * The property blockSize must be implemented in a concrete subtype. + * + * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 + */ + var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ + /** + * Resets this block algorithm's data buffer to its initial state. + * + * @example + * + * bufferedBlockAlgorithm.reset(); + */ + reset: function () { + // Initial values + this._data = new WordArray.init(); + this._nDataBytes = 0; + }, + + /** + * Adds new data to this block algorithm's buffer. + * + * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. + * + * @example + * + * bufferedBlockAlgorithm._append('data'); + * bufferedBlockAlgorithm._append(wordArray); + */ + _append: function (data) { + // Convert string to WordArray, else assume WordArray already + if (typeof data == 'string') { + data = Utf8.parse(data); + } + + // Append + this._data.concat(data); + this._nDataBytes += data.sigBytes; + }, + + /** + * Processes available data blocks. + * + * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. + * + * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. + * + * @return {WordArray} The processed data. + * + * @example + * + * var processedData = bufferedBlockAlgorithm._process(); + * var processedData = bufferedBlockAlgorithm._process(!!'flush'); + */ + _process: function (doFlush) { + var processedWords; + + // Shortcuts + var data = this._data; + var dataWords = data.words; + var dataSigBytes = data.sigBytes; + var blockSize = this.blockSize; + var blockSizeBytes = blockSize * 4; + + // Count blocks ready + var nBlocksReady = dataSigBytes / blockSizeBytes; + if (doFlush) { + // Round up to include partial blocks + nBlocksReady = Math.ceil(nBlocksReady); + } else { + // Round down to include only full blocks, + // less the number of blocks that must remain in the buffer + nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); + } + + // Count words ready + var nWordsReady = nBlocksReady * blockSize; + + // Count bytes ready + var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); + + // Process blocks + if (nWordsReady) { + for (var offset = 0; offset < nWordsReady; offset += blockSize) { + // Perform concrete-algorithm logic + this._doProcessBlock(dataWords, offset); + } + + // Remove processed words + processedWords = dataWords.splice(0, nWordsReady); + data.sigBytes -= nBytesReady; + } + + // Return processed words + return new WordArray.init(processedWords, nBytesReady); + }, + + /** + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = bufferedBlockAlgorithm.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + clone._data = this._data.clone(); + + return clone; + }, + + _minBufferSize: 0 + }); + + /** + * Abstract hasher template. + * + * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) + */ + var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + */ + cfg: Base.extend(), + + /** + * Initializes a newly created hasher. + * + * @param {Object} cfg (Optional) The configuration options to use for this hash computation. + * + * @example + * + * var hasher = CryptoJS.algo.SHA256.create(); + */ + init: function (cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); + + // Set initial values + this.reset(); + }, + + /** + * Resets this hasher to its initial state. + * + * @example + * + * hasher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-hasher logic + this._doReset(); + }, + + /** + * Updates this hasher with a message. + * + * @param {WordArray|string} messageUpdate The message to append. + * + * @return {Hasher} This hasher. + * + * @example + * + * hasher.update('message'); + * hasher.update(wordArray); + */ + update: function (messageUpdate) { + // Append + this._append(messageUpdate); + + // Update the hash + this._process(); + + // Chainable + return this; + }, + + /** + * Finalizes the hash computation. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} messageUpdate (Optional) A final message update. + * + * @return {WordArray} The hash. + * + * @example + * + * var hash = hasher.finalize(); + * var hash = hasher.finalize('message'); + * var hash = hasher.finalize(wordArray); + */ + finalize: function (messageUpdate) { + // Final message update + if (messageUpdate) { + this._append(messageUpdate); + } + + // Perform concrete-hasher logic + var hash = this._doFinalize(); + + return hash; + }, + + blockSize: 512/32, + + /** + * Creates a shortcut function to a hasher's object interface. + * + * @param {Hasher} hasher The hasher to create a helper for. + * + * @return {Function} The shortcut function. + * + * @static + * + * @example + * + * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); + */ + _createHelper: function (hasher) { + return function (message, cfg) { + return new hasher.init(cfg).finalize(message); + }; + }, + + /** + * Creates a shortcut function to the HMAC's object interface. + * + * @param {Hasher} hasher The hasher to use in this HMAC helper. + * + * @return {Function} The shortcut function. + * + * @static + * + * @example + * + * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); + */ + _createHmacHelper: function (hasher) { + return function (message, key) { + return new C_algo.HMAC.init(hasher, key).finalize(message); + }; + } + }); + + /** + * Algorithm namespace. + */ + var C_algo = C.algo = {}; + + return C; + }(Math)); + + + return CryptoJS; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/crypto-js.js b/miniprogram_npm/crypto-js/crypto-js.js new file mode 100644 index 0000000..27f0a62 --- /dev/null +++ b/miniprogram_npm/crypto-js/crypto-js.js @@ -0,0 +1,6191 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(); + } + else if (typeof define === "function" && define.amd) { + // AMD + define([], factory); + } + else { + // Global (browser) + root.CryptoJS = factory(); + } +}(this, function () { + + /*globals window, global, require*/ + + /** + * CryptoJS core components. + */ + var CryptoJS = CryptoJS || (function (Math, undefined) { + + var crypto; + + // Native crypto from window (Browser) + if (typeof window !== 'undefined' && window.crypto) { + crypto = window.crypto; + } + + // Native crypto in web worker (Browser) + if (typeof self !== 'undefined' && self.crypto) { + crypto = self.crypto; + } + + // Native crypto from worker + if (typeof globalThis !== 'undefined' && globalThis.crypto) { + crypto = globalThis.crypto; + } + + // Native (experimental IE 11) crypto from window (Browser) + if (!crypto && typeof window !== 'undefined' && window.msCrypto) { + crypto = window.msCrypto; + } + + // Native crypto from global (NodeJS) + if (!crypto && typeof global !== 'undefined' && global.crypto) { + crypto = global.crypto; + } + + // Native crypto import via require (NodeJS) + if (!crypto && typeof require === 'function') { + try { + crypto = require('crypto'); + } catch (err) {} + } + + /* + * Cryptographically secure pseudorandom number generator + * + * As Math.random() is cryptographically not safe to use + */ + var cryptoSecureRandomInt = function () { + if (crypto) { + // Use getRandomValues method (Browser) + if (typeof crypto.getRandomValues === 'function') { + try { + return crypto.getRandomValues(new Uint32Array(1))[0]; + } catch (err) {} + } + + // Use randomBytes method (NodeJS) + if (typeof crypto.randomBytes === 'function') { + try { + return crypto.randomBytes(4).readInt32LE(); + } catch (err) {} + } + } + + throw new Error('Native crypto module could not be used to get secure random number.'); + }; + + /* + * Local polyfill of Object.create + + */ + var create = Object.create || (function () { + function F() {} + + return function (obj) { + var subtype; + + F.prototype = obj; + + subtype = new F(); + + F.prototype = null; + + return subtype; + }; + }()); + + /** + * CryptoJS namespace. + */ + var C = {}; + + /** + * Library namespace. + */ + var C_lib = C.lib = {}; + + /** + * Base object for prototypal inheritance. + */ + var Base = C_lib.Base = (function () { + + + return { + /** + * Creates a new object that inherits from this object. + * + * @param {Object} overrides Properties to copy into the new object. + * + * @return {Object} The new object. + * + * @static + * + * @example + * + * var MyType = CryptoJS.lib.Base.extend({ + * field: 'value', + * + * method: function () { + * } + * }); + */ + extend: function (overrides) { + // Spawn + var subtype = create(this); + + // Augment + if (overrides) { + subtype.mixIn(overrides); + } + + // Create default initializer + if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { + subtype.init = function () { + subtype.$super.init.apply(this, arguments); + }; + } + + // Initializer's prototype is the subtype object + subtype.init.prototype = subtype; + + // Reference supertype + subtype.$super = this; + + return subtype; + }, + + /** + * Extends this object and runs the init method. + * Arguments to create() will be passed to init(). + * + * @return {Object} The new object. + * + * @static + * + * @example + * + * var instance = MyType.create(); + */ + create: function () { + var instance = this.extend(); + instance.init.apply(instance, arguments); + + return instance; + }, + + /** + * Initializes a newly created object. + * Override this method to add some logic when your objects are created. + * + * @example + * + * var MyType = CryptoJS.lib.Base.extend({ + * init: function () { + * // ... + * } + * }); + */ + init: function () { + }, + + /** + * Copies properties into this object. + * + * @param {Object} properties The properties to mix in. + * + * @example + * + * MyType.mixIn({ + * field: 'value' + * }); + */ + mixIn: function (properties) { + for (var propertyName in properties) { + if (properties.hasOwnProperty(propertyName)) { + this[propertyName] = properties[propertyName]; + } + } + + // IE won't copy toString using the loop above + if (properties.hasOwnProperty('toString')) { + this.toString = properties.toString; + } + }, + + /** + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = instance.clone(); + */ + clone: function () { + return this.init.prototype.extend(this); + } + }; + }()); + + /** + * An array of 32-bit words. + * + * @property {Array} words The array of 32-bit words. + * @property {number} sigBytes The number of significant bytes in this word array. + */ + var WordArray = C_lib.WordArray = Base.extend({ + /** + * Initializes a newly created word array. + * + * @param {Array} words (Optional) An array of 32-bit words. + * @param {number} sigBytes (Optional) The number of significant bytes in the words. + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.create(); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); + */ + init: function (words, sigBytes) { + words = this.words = words || []; + + if (sigBytes != undefined) { + this.sigBytes = sigBytes; + } else { + this.sigBytes = words.length * 4; + } + }, + + /** + * Converts this word array to a string. + * + * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex + * + * @return {string} The stringified word array. + * + * @example + * + * var string = wordArray + ''; + * var string = wordArray.toString(); + * var string = wordArray.toString(CryptoJS.enc.Utf8); + */ + toString: function (encoder) { + return (encoder || Hex).stringify(this); + }, + + /** + * Concatenates a word array to this word array. + * + * @param {WordArray} wordArray The word array to append. + * + * @return {WordArray} This word array. + * + * @example + * + * wordArray1.concat(wordArray2); + */ + concat: function (wordArray) { + // Shortcuts + var thisWords = this.words; + var thatWords = wordArray.words; + var thisSigBytes = this.sigBytes; + var thatSigBytes = wordArray.sigBytes; + + // Clamp excess bits + this.clamp(); + + // Concat + if (thisSigBytes % 4) { + // Copy one byte at a time + for (var i = 0; i < thatSigBytes; i++) { + var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); + } + } else { + // Copy one word at a time + for (var j = 0; j < thatSigBytes; j += 4) { + thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2]; + } + } + this.sigBytes += thatSigBytes; + + // Chainable + return this; + }, + + /** + * Removes insignificant bits. + * + * @example + * + * wordArray.clamp(); + */ + clamp: function () { + // Shortcuts + var words = this.words; + var sigBytes = this.sigBytes; + + // Clamp + words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); + words.length = Math.ceil(sigBytes / 4); + }, + + /** + * Creates a copy of this word array. + * + * @return {WordArray} The clone. + * + * @example + * + * var clone = wordArray.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + clone.words = this.words.slice(0); + + return clone; + }, + + /** + * Creates a word array filled with random bytes. + * + * @param {number} nBytes The number of random bytes to generate. + * + * @return {WordArray} The random word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.random(16); + */ + random: function (nBytes) { + var words = []; + + for (var i = 0; i < nBytes; i += 4) { + words.push(cryptoSecureRandomInt()); + } + + return new WordArray.init(words, nBytes); + } + }); + + /** + * Encoder namespace. + */ + var C_enc = C.enc = {}; + + /** + * Hex encoding strategy. + */ + var Hex = C_enc.Hex = { + /** + * Converts a word array to a hex string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The hex string. + * + * @static + * + * @example + * + * var hexString = CryptoJS.enc.Hex.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var hexChars = []; + for (var i = 0; i < sigBytes; i++) { + var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + hexChars.push((bite >>> 4).toString(16)); + hexChars.push((bite & 0x0f).toString(16)); + } + + return hexChars.join(''); + }, + + /** + * Converts a hex string to a word array. + * + * @param {string} hexStr The hex string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Hex.parse(hexString); + */ + parse: function (hexStr) { + // Shortcut + var hexStrLength = hexStr.length; + + // Convert + var words = []; + for (var i = 0; i < hexStrLength; i += 2) { + words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); + } + + return new WordArray.init(words, hexStrLength / 2); + } + }; + + /** + * Latin1 encoding strategy. + */ + var Latin1 = C_enc.Latin1 = { + /** + * Converts a word array to a Latin1 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Latin1 string. + * + * @static + * + * @example + * + * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var latin1Chars = []; + for (var i = 0; i < sigBytes; i++) { + var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + latin1Chars.push(String.fromCharCode(bite)); + } + + return latin1Chars.join(''); + }, + + /** + * Converts a Latin1 string to a word array. + * + * @param {string} latin1Str The Latin1 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); + */ + parse: function (latin1Str) { + // Shortcut + var latin1StrLength = latin1Str.length; + + // Convert + var words = []; + for (var i = 0; i < latin1StrLength; i++) { + words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); + } + + return new WordArray.init(words, latin1StrLength); + } + }; + + /** + * UTF-8 encoding strategy. + */ + var Utf8 = C_enc.Utf8 = { + /** + * Converts a word array to a UTF-8 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-8 string. + * + * @static + * + * @example + * + * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); + */ + stringify: function (wordArray) { + try { + return decodeURIComponent(escape(Latin1.stringify(wordArray))); + } catch (e) { + throw new Error('Malformed UTF-8 data'); + } + }, + + /** + * Converts a UTF-8 string to a word array. + * + * @param {string} utf8Str The UTF-8 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); + */ + parse: function (utf8Str) { + return Latin1.parse(unescape(encodeURIComponent(utf8Str))); + } + }; + + /** + * Abstract buffered block algorithm template. + * + * The property blockSize must be implemented in a concrete subtype. + * + * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 + */ + var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ + /** + * Resets this block algorithm's data buffer to its initial state. + * + * @example + * + * bufferedBlockAlgorithm.reset(); + */ + reset: function () { + // Initial values + this._data = new WordArray.init(); + this._nDataBytes = 0; + }, + + /** + * Adds new data to this block algorithm's buffer. + * + * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. + * + * @example + * + * bufferedBlockAlgorithm._append('data'); + * bufferedBlockAlgorithm._append(wordArray); + */ + _append: function (data) { + // Convert string to WordArray, else assume WordArray already + if (typeof data == 'string') { + data = Utf8.parse(data); + } + + // Append + this._data.concat(data); + this._nDataBytes += data.sigBytes; + }, + + /** + * Processes available data blocks. + * + * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. + * + * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. + * + * @return {WordArray} The processed data. + * + * @example + * + * var processedData = bufferedBlockAlgorithm._process(); + * var processedData = bufferedBlockAlgorithm._process(!!'flush'); + */ + _process: function (doFlush) { + var processedWords; + + // Shortcuts + var data = this._data; + var dataWords = data.words; + var dataSigBytes = data.sigBytes; + var blockSize = this.blockSize; + var blockSizeBytes = blockSize * 4; + + // Count blocks ready + var nBlocksReady = dataSigBytes / blockSizeBytes; + if (doFlush) { + // Round up to include partial blocks + nBlocksReady = Math.ceil(nBlocksReady); + } else { + // Round down to include only full blocks, + // less the number of blocks that must remain in the buffer + nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); + } + + // Count words ready + var nWordsReady = nBlocksReady * blockSize; + + // Count bytes ready + var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); + + // Process blocks + if (nWordsReady) { + for (var offset = 0; offset < nWordsReady; offset += blockSize) { + // Perform concrete-algorithm logic + this._doProcessBlock(dataWords, offset); + } + + // Remove processed words + processedWords = dataWords.splice(0, nWordsReady); + data.sigBytes -= nBytesReady; + } + + // Return processed words + return new WordArray.init(processedWords, nBytesReady); + }, + + /** + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = bufferedBlockAlgorithm.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + clone._data = this._data.clone(); + + return clone; + }, + + _minBufferSize: 0 + }); + + /** + * Abstract hasher template. + * + * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) + */ + var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + */ + cfg: Base.extend(), + + /** + * Initializes a newly created hasher. + * + * @param {Object} cfg (Optional) The configuration options to use for this hash computation. + * + * @example + * + * var hasher = CryptoJS.algo.SHA256.create(); + */ + init: function (cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); + + // Set initial values + this.reset(); + }, + + /** + * Resets this hasher to its initial state. + * + * @example + * + * hasher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-hasher logic + this._doReset(); + }, + + /** + * Updates this hasher with a message. + * + * @param {WordArray|string} messageUpdate The message to append. + * + * @return {Hasher} This hasher. + * + * @example + * + * hasher.update('message'); + * hasher.update(wordArray); + */ + update: function (messageUpdate) { + // Append + this._append(messageUpdate); + + // Update the hash + this._process(); + + // Chainable + return this; + }, + + /** + * Finalizes the hash computation. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} messageUpdate (Optional) A final message update. + * + * @return {WordArray} The hash. + * + * @example + * + * var hash = hasher.finalize(); + * var hash = hasher.finalize('message'); + * var hash = hasher.finalize(wordArray); + */ + finalize: function (messageUpdate) { + // Final message update + if (messageUpdate) { + this._append(messageUpdate); + } + + // Perform concrete-hasher logic + var hash = this._doFinalize(); + + return hash; + }, + + blockSize: 512/32, + + /** + * Creates a shortcut function to a hasher's object interface. + * + * @param {Hasher} hasher The hasher to create a helper for. + * + * @return {Function} The shortcut function. + * + * @static + * + * @example + * + * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); + */ + _createHelper: function (hasher) { + return function (message, cfg) { + return new hasher.init(cfg).finalize(message); + }; + }, + + /** + * Creates a shortcut function to the HMAC's object interface. + * + * @param {Hasher} hasher The hasher to use in this HMAC helper. + * + * @return {Function} The shortcut function. + * + * @static + * + * @example + * + * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); + */ + _createHmacHelper: function (hasher) { + return function (message, key) { + return new C_algo.HMAC.init(hasher, key).finalize(message); + }; + } + }); + + /** + * Algorithm namespace. + */ + var C_algo = C.algo = {}; + + return C; + }(Math)); + + + (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var X32WordArray = C_lib.WordArray; + + /** + * x64 namespace. + */ + var C_x64 = C.x64 = {}; + + /** + * A 64-bit word. + */ + var X64Word = C_x64.Word = Base.extend({ + /** + * Initializes a newly created 64-bit word. + * + * @param {number} high The high 32 bits. + * @param {number} low The low 32 bits. + * + * @example + * + * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); + */ + init: function (high, low) { + this.high = high; + this.low = low; + } + + /** + * Bitwise NOTs this word. + * + * @return {X64Word} A new x64-Word object after negating. + * + * @example + * + * var negated = x64Word.not(); + */ + // not: function () { + // var high = ~this.high; + // var low = ~this.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise ANDs this word with the passed word. + * + * @param {X64Word} word The x64-Word to AND with this word. + * + * @return {X64Word} A new x64-Word object after ANDing. + * + * @example + * + * var anded = x64Word.and(anotherX64Word); + */ + // and: function (word) { + // var high = this.high & word.high; + // var low = this.low & word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise ORs this word with the passed word. + * + * @param {X64Word} word The x64-Word to OR with this word. + * + * @return {X64Word} A new x64-Word object after ORing. + * + * @example + * + * var ored = x64Word.or(anotherX64Word); + */ + // or: function (word) { + // var high = this.high | word.high; + // var low = this.low | word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise XORs this word with the passed word. + * + * @param {X64Word} word The x64-Word to XOR with this word. + * + * @return {X64Word} A new x64-Word object after XORing. + * + * @example + * + * var xored = x64Word.xor(anotherX64Word); + */ + // xor: function (word) { + // var high = this.high ^ word.high; + // var low = this.low ^ word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Shifts this word n bits to the left. + * + * @param {number} n The number of bits to shift. + * + * @return {X64Word} A new x64-Word object after shifting. + * + * @example + * + * var shifted = x64Word.shiftL(25); + */ + // shiftL: function (n) { + // if (n < 32) { + // var high = (this.high << n) | (this.low >>> (32 - n)); + // var low = this.low << n; + // } else { + // var high = this.low << (n - 32); + // var low = 0; + // } + + // return X64Word.create(high, low); + // }, + + /** + * Shifts this word n bits to the right. + * + * @param {number} n The number of bits to shift. + * + * @return {X64Word} A new x64-Word object after shifting. + * + * @example + * + * var shifted = x64Word.shiftR(7); + */ + // shiftR: function (n) { + // if (n < 32) { + // var low = (this.low >>> n) | (this.high << (32 - n)); + // var high = this.high >>> n; + // } else { + // var low = this.high >>> (n - 32); + // var high = 0; + // } + + // return X64Word.create(high, low); + // }, + + /** + * Rotates this word n bits to the left. + * + * @param {number} n The number of bits to rotate. + * + * @return {X64Word} A new x64-Word object after rotating. + * + * @example + * + * var rotated = x64Word.rotL(25); + */ + // rotL: function (n) { + // return this.shiftL(n).or(this.shiftR(64 - n)); + // }, + + /** + * Rotates this word n bits to the right. + * + * @param {number} n The number of bits to rotate. + * + * @return {X64Word} A new x64-Word object after rotating. + * + * @example + * + * var rotated = x64Word.rotR(7); + */ + // rotR: function (n) { + // return this.shiftR(n).or(this.shiftL(64 - n)); + // }, + + /** + * Adds this word with the passed word. + * + * @param {X64Word} word The x64-Word to add with this word. + * + * @return {X64Word} A new x64-Word object after adding. + * + * @example + * + * var added = x64Word.add(anotherX64Word); + */ + // add: function (word) { + // var low = (this.low + word.low) | 0; + // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; + // var high = (this.high + word.high + carry) | 0; + + // return X64Word.create(high, low); + // } + }); + + /** + * An array of 64-bit words. + * + * @property {Array} words The array of CryptoJS.x64.Word objects. + * @property {number} sigBytes The number of significant bytes in this word array. + */ + var X64WordArray = C_x64.WordArray = Base.extend({ + /** + * Initializes a newly created word array. + * + * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. + * @param {number} sigBytes (Optional) The number of significant bytes in the words. + * + * @example + * + * var wordArray = CryptoJS.x64.WordArray.create(); + * + * var wordArray = CryptoJS.x64.WordArray.create([ + * CryptoJS.x64.Word.create(0x00010203, 0x04050607), + * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) + * ]); + * + * var wordArray = CryptoJS.x64.WordArray.create([ + * CryptoJS.x64.Word.create(0x00010203, 0x04050607), + * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) + * ], 10); + */ + init: function (words, sigBytes) { + words = this.words = words || []; + + if (sigBytes != undefined) { + this.sigBytes = sigBytes; + } else { + this.sigBytes = words.length * 8; + } + }, + + /** + * Converts this 64-bit word array to a 32-bit word array. + * + * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. + * + * @example + * + * var x32WordArray = x64WordArray.toX32(); + */ + toX32: function () { + // Shortcuts + var x64Words = this.words; + var x64WordsLength = x64Words.length; + + // Convert + var x32Words = []; + for (var i = 0; i < x64WordsLength; i++) { + var x64Word = x64Words[i]; + x32Words.push(x64Word.high); + x32Words.push(x64Word.low); + } + + return X32WordArray.create(x32Words, this.sigBytes); + }, + + /** + * Creates a copy of this word array. + * + * @return {X64WordArray} The clone. + * + * @example + * + * var clone = x64WordArray.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + + // Clone "words" array + var words = clone.words = this.words.slice(0); + + // Clone each X64Word object + var wordsLength = words.length; + for (var i = 0; i < wordsLength; i++) { + words[i] = words[i].clone(); + } + + return clone; + } + }); + }()); + + + (function () { + // Check if typed arrays are supported + if (typeof ArrayBuffer != 'function') { + return; + } + + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + + // Reference original init + var superInit = WordArray.init; + + // Augment WordArray.init to handle typed arrays + var subInit = WordArray.init = function (typedArray) { + // Convert buffers to uint8 + if (typedArray instanceof ArrayBuffer) { + typedArray = new Uint8Array(typedArray); + } + + // Convert other array views to uint8 + if ( + typedArray instanceof Int8Array || + (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || + typedArray instanceof Int16Array || + typedArray instanceof Uint16Array || + typedArray instanceof Int32Array || + typedArray instanceof Uint32Array || + typedArray instanceof Float32Array || + typedArray instanceof Float64Array + ) { + typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); + } + + // Handle Uint8Array + if (typedArray instanceof Uint8Array) { + // Shortcut + var typedArrayByteLength = typedArray.byteLength; + + // Extract bytes + var words = []; + for (var i = 0; i < typedArrayByteLength; i++) { + words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); + } + + // Initialize this word array + superInit.call(this, words, typedArrayByteLength); + } else { + // Else call normal init + superInit.apply(this, arguments); + } + }; + + subInit.prototype = WordArray; + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * UTF-16 BE encoding strategy. + */ + var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { + /** + * Converts a word array to a UTF-16 BE string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-16 BE string. + * + * @static + * + * @example + * + * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var utf16Chars = []; + for (var i = 0; i < sigBytes; i += 2) { + var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; + utf16Chars.push(String.fromCharCode(codePoint)); + } + + return utf16Chars.join(''); + }, + + /** + * Converts a UTF-16 BE string to a word array. + * + * @param {string} utf16Str The UTF-16 BE string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); + */ + parse: function (utf16Str) { + // Shortcut + var utf16StrLength = utf16Str.length; + + // Convert + var words = []; + for (var i = 0; i < utf16StrLength; i++) { + words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); + } + + return WordArray.create(words, utf16StrLength * 2); + } + }; + + /** + * UTF-16 LE encoding strategy. + */ + C_enc.Utf16LE = { + /** + * Converts a word array to a UTF-16 LE string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-16 LE string. + * + * @static + * + * @example + * + * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var utf16Chars = []; + for (var i = 0; i < sigBytes; i += 2) { + var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); + utf16Chars.push(String.fromCharCode(codePoint)); + } + + return utf16Chars.join(''); + }, + + /** + * Converts a UTF-16 LE string to a word array. + * + * @param {string} utf16Str The UTF-16 LE string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); + */ + parse: function (utf16Str) { + // Shortcut + var utf16StrLength = utf16Str.length; + + // Convert + var words = []; + for (var i = 0; i < utf16StrLength; i++) { + words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); + } + + return WordArray.create(words, utf16StrLength * 2); + } + }; + + function swapEndian(word) { + return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); + } + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * Base64 encoding strategy. + */ + var Base64 = C_enc.Base64 = { + /** + * Converts a word array to a Base64 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Base64 string. + * + * @static + * + * @example + * + * var base64String = CryptoJS.enc.Base64.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + var map = this._map; + + // Clamp excess bits + wordArray.clamp(); + + // Convert + var base64Chars = []; + for (var i = 0; i < sigBytes; i += 3) { + var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; + var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; + + var triplet = (byte1 << 16) | (byte2 << 8) | byte3; + + for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { + base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); + } + } + + // Add padding + var paddingChar = map.charAt(64); + if (paddingChar) { + while (base64Chars.length % 4) { + base64Chars.push(paddingChar); + } + } + + return base64Chars.join(''); + }, + + /** + * Converts a Base64 string to a word array. + * + * @param {string} base64Str The Base64 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Base64.parse(base64String); + */ + parse: function (base64Str) { + // Shortcuts + var base64StrLength = base64Str.length; + var map = this._map; + var reverseMap = this._reverseMap; + + if (!reverseMap) { + reverseMap = this._reverseMap = []; + for (var j = 0; j < map.length; j++) { + reverseMap[map.charCodeAt(j)] = j; + } + } + + // Ignore padding + var paddingChar = map.charAt(64); + if (paddingChar) { + var paddingIndex = base64Str.indexOf(paddingChar); + if (paddingIndex !== -1) { + base64StrLength = paddingIndex; + } + } + + // Convert + return parseLoop(base64Str, base64StrLength, reverseMap); + + }, + + _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' + }; + + function parseLoop(base64Str, base64StrLength, reverseMap) { + var words = []; + var nBytes = 0; + for (var i = 0; i < base64StrLength; i++) { + if (i % 4) { + var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); + var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); + var bitsCombined = bits1 | bits2; + words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8); + nBytes++; + } + } + return WordArray.create(words, nBytes); + } + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * Base64url encoding strategy. + */ + var Base64url = C_enc.Base64url = { + /** + * Converts a word array to a Base64url string. + * + * @param {WordArray} wordArray The word array. + * + * @param {boolean} urlSafe Whether to use url safe + * + * @return {string} The Base64url string. + * + * @static + * + * @example + * + * var base64String = CryptoJS.enc.Base64url.stringify(wordArray); + */ + stringify: function (wordArray, urlSafe=true) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + var map = urlSafe ? this._safe_map : this._map; + + // Clamp excess bits + wordArray.clamp(); + + // Convert + var base64Chars = []; + for (var i = 0; i < sigBytes; i += 3) { + var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; + var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; + + var triplet = (byte1 << 16) | (byte2 << 8) | byte3; + + for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { + base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); + } + } + + // Add padding + var paddingChar = map.charAt(64); + if (paddingChar) { + while (base64Chars.length % 4) { + base64Chars.push(paddingChar); + } + } + + return base64Chars.join(''); + }, + + /** + * Converts a Base64url string to a word array. + * + * @param {string} base64Str The Base64url string. + * + * @param {boolean} urlSafe Whether to use url safe + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Base64url.parse(base64String); + */ + parse: function (base64Str, urlSafe=true) { + // Shortcuts + var base64StrLength = base64Str.length; + var map = urlSafe ? this._safe_map : this._map; + var reverseMap = this._reverseMap; + + if (!reverseMap) { + reverseMap = this._reverseMap = []; + for (var j = 0; j < map.length; j++) { + reverseMap[map.charCodeAt(j)] = j; + } + } + + // Ignore padding + var paddingChar = map.charAt(64); + if (paddingChar) { + var paddingIndex = base64Str.indexOf(paddingChar); + if (paddingIndex !== -1) { + base64StrLength = paddingIndex; + } + } + + // Convert + return parseLoop(base64Str, base64StrLength, reverseMap); + + }, + + _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', + _safe_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', + }; + + function parseLoop(base64Str, base64StrLength, reverseMap) { + var words = []; + var nBytes = 0; + for (var i = 0; i < base64StrLength; i++) { + if (i % 4) { + var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); + var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); + var bitsCombined = bits1 | bits2; + words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8); + nBytes++; + } + } + return WordArray.create(words, nBytes); + } + }()); + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Constants table + var T = []; + + // Compute constants + (function () { + for (var i = 0; i < 64; i++) { + T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; + } + }()); + + /** + * MD5 hash algorithm. + */ + var MD5 = C_algo.MD5 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0x67452301, 0xefcdab89, + 0x98badcfe, 0x10325476 + ]); + }, + + _doProcessBlock: function (M, offset) { + // Swap endian + for (var i = 0; i < 16; i++) { + // Shortcuts + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } + + // Shortcuts + var H = this._hash.words; + + var M_offset_0 = M[offset + 0]; + var M_offset_1 = M[offset + 1]; + var M_offset_2 = M[offset + 2]; + var M_offset_3 = M[offset + 3]; + var M_offset_4 = M[offset + 4]; + var M_offset_5 = M[offset + 5]; + var M_offset_6 = M[offset + 6]; + var M_offset_7 = M[offset + 7]; + var M_offset_8 = M[offset + 8]; + var M_offset_9 = M[offset + 9]; + var M_offset_10 = M[offset + 10]; + var M_offset_11 = M[offset + 11]; + var M_offset_12 = M[offset + 12]; + var M_offset_13 = M[offset + 13]; + var M_offset_14 = M[offset + 14]; + var M_offset_15 = M[offset + 15]; + + // Working varialbes + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + + // Computation + a = FF(a, b, c, d, M_offset_0, 7, T[0]); + d = FF(d, a, b, c, M_offset_1, 12, T[1]); + c = FF(c, d, a, b, M_offset_2, 17, T[2]); + b = FF(b, c, d, a, M_offset_3, 22, T[3]); + a = FF(a, b, c, d, M_offset_4, 7, T[4]); + d = FF(d, a, b, c, M_offset_5, 12, T[5]); + c = FF(c, d, a, b, M_offset_6, 17, T[6]); + b = FF(b, c, d, a, M_offset_7, 22, T[7]); + a = FF(a, b, c, d, M_offset_8, 7, T[8]); + d = FF(d, a, b, c, M_offset_9, 12, T[9]); + c = FF(c, d, a, b, M_offset_10, 17, T[10]); + b = FF(b, c, d, a, M_offset_11, 22, T[11]); + a = FF(a, b, c, d, M_offset_12, 7, T[12]); + d = FF(d, a, b, c, M_offset_13, 12, T[13]); + c = FF(c, d, a, b, M_offset_14, 17, T[14]); + b = FF(b, c, d, a, M_offset_15, 22, T[15]); + + a = GG(a, b, c, d, M_offset_1, 5, T[16]); + d = GG(d, a, b, c, M_offset_6, 9, T[17]); + c = GG(c, d, a, b, M_offset_11, 14, T[18]); + b = GG(b, c, d, a, M_offset_0, 20, T[19]); + a = GG(a, b, c, d, M_offset_5, 5, T[20]); + d = GG(d, a, b, c, M_offset_10, 9, T[21]); + c = GG(c, d, a, b, M_offset_15, 14, T[22]); + b = GG(b, c, d, a, M_offset_4, 20, T[23]); + a = GG(a, b, c, d, M_offset_9, 5, T[24]); + d = GG(d, a, b, c, M_offset_14, 9, T[25]); + c = GG(c, d, a, b, M_offset_3, 14, T[26]); + b = GG(b, c, d, a, M_offset_8, 20, T[27]); + a = GG(a, b, c, d, M_offset_13, 5, T[28]); + d = GG(d, a, b, c, M_offset_2, 9, T[29]); + c = GG(c, d, a, b, M_offset_7, 14, T[30]); + b = GG(b, c, d, a, M_offset_12, 20, T[31]); + + a = HH(a, b, c, d, M_offset_5, 4, T[32]); + d = HH(d, a, b, c, M_offset_8, 11, T[33]); + c = HH(c, d, a, b, M_offset_11, 16, T[34]); + b = HH(b, c, d, a, M_offset_14, 23, T[35]); + a = HH(a, b, c, d, M_offset_1, 4, T[36]); + d = HH(d, a, b, c, M_offset_4, 11, T[37]); + c = HH(c, d, a, b, M_offset_7, 16, T[38]); + b = HH(b, c, d, a, M_offset_10, 23, T[39]); + a = HH(a, b, c, d, M_offset_13, 4, T[40]); + d = HH(d, a, b, c, M_offset_0, 11, T[41]); + c = HH(c, d, a, b, M_offset_3, 16, T[42]); + b = HH(b, c, d, a, M_offset_6, 23, T[43]); + a = HH(a, b, c, d, M_offset_9, 4, T[44]); + d = HH(d, a, b, c, M_offset_12, 11, T[45]); + c = HH(c, d, a, b, M_offset_15, 16, T[46]); + b = HH(b, c, d, a, M_offset_2, 23, T[47]); + + a = II(a, b, c, d, M_offset_0, 6, T[48]); + d = II(d, a, b, c, M_offset_7, 10, T[49]); + c = II(c, d, a, b, M_offset_14, 15, T[50]); + b = II(b, c, d, a, M_offset_5, 21, T[51]); + a = II(a, b, c, d, M_offset_12, 6, T[52]); + d = II(d, a, b, c, M_offset_3, 10, T[53]); + c = II(c, d, a, b, M_offset_10, 15, T[54]); + b = II(b, c, d, a, M_offset_1, 21, T[55]); + a = II(a, b, c, d, M_offset_8, 6, T[56]); + d = II(d, a, b, c, M_offset_15, 10, T[57]); + c = II(c, d, a, b, M_offset_6, 15, T[58]); + b = II(b, c, d, a, M_offset_13, 21, T[59]); + a = II(a, b, c, d, M_offset_4, 6, T[60]); + d = II(d, a, b, c, M_offset_11, 10, T[61]); + c = II(c, d, a, b, M_offset_2, 15, T[62]); + b = II(b, c, d, a, M_offset_9, 21, T[63]); + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + + var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); + var nBitsTotalL = nBitsTotal; + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( + (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | + (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) + ); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | + (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) + ); + + data.sigBytes = (dataWords.length + 1) * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var hash = this._hash; + var H = hash.words; + + // Swap endian + for (var i = 0; i < 4; i++) { + // Shortcut + var H_i = H[i]; + + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + function FF(a, b, c, d, x, s, t) { + var n = a + ((b & c) | (~b & d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function GG(a, b, c, d, x, s, t) { + var n = a + ((b & d) | (c & ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function HH(a, b, c, d, x, s, t) { + var n = a + (b ^ c ^ d) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function II(a, b, c, d, x, s, t) { + var n = a + (c ^ (b | ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.MD5('message'); + * var hash = CryptoJS.MD5(wordArray); + */ + C.MD5 = Hasher._createHelper(MD5); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacMD5(message, key); + */ + C.HmacMD5 = Hasher._createHmacHelper(MD5); + }(Math)); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Reusable object + var W = []; + + /** + * SHA-1 hash algorithm. + */ + var SHA1 = C_algo.SHA1 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0x67452301, 0xefcdab89, + 0x98badcfe, 0x10325476, + 0xc3d2e1f0 + ]); + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var H = this._hash.words; + + // Working variables + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + + // Computation + for (var i = 0; i < 80; i++) { + if (i < 16) { + W[i] = M[offset + i] | 0; + } else { + var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + W[i] = (n << 1) | (n >>> 31); + } + + var t = ((a << 5) | (a >>> 27)) + e + W[i]; + if (i < 20) { + t += ((b & c) | (~b & d)) + 0x5a827999; + } else if (i < 40) { + t += (b ^ c ^ d) + 0x6ed9eba1; + } else if (i < 60) { + t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; + } else /* if (i < 80) */ { + t += (b ^ c ^ d) - 0x359d3e2a; + } + + e = d; + d = c; + c = (b << 30) | (b >>> 2); + b = a; + a = t; + } + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + H[4] = (H[4] + e) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Return final computed hash + return this._hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA1('message'); + * var hash = CryptoJS.SHA1(wordArray); + */ + C.SHA1 = Hasher._createHelper(SHA1); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA1(message, key); + */ + C.HmacSHA1 = Hasher._createHmacHelper(SHA1); + }()); + + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Initialization and round constants tables + var H = []; + var K = []; + + // Compute constants + (function () { + function isPrime(n) { + var sqrtN = Math.sqrt(n); + for (var factor = 2; factor <= sqrtN; factor++) { + if (!(n % factor)) { + return false; + } + } + + return true; + } + + function getFractionalBits(n) { + return ((n - (n | 0)) * 0x100000000) | 0; + } + + var n = 2; + var nPrime = 0; + while (nPrime < 64) { + if (isPrime(n)) { + if (nPrime < 8) { + H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); + } + K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); + + nPrime++; + } + + n++; + } + }()); + + // Reusable object + var W = []; + + /** + * SHA-256 hash algorithm. + */ + var SHA256 = C_algo.SHA256 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init(H.slice(0)); + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var H = this._hash.words; + + // Working variables + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + var f = H[5]; + var g = H[6]; + var h = H[7]; + + // Computation + for (var i = 0; i < 64; i++) { + if (i < 16) { + W[i] = M[offset + i] | 0; + } else { + var gamma0x = W[i - 15]; + var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ + ((gamma0x << 14) | (gamma0x >>> 18)) ^ + (gamma0x >>> 3); + + var gamma1x = W[i - 2]; + var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ + ((gamma1x << 13) | (gamma1x >>> 19)) ^ + (gamma1x >>> 10); + + W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; + } + + var ch = (e & f) ^ (~e & g); + var maj = (a & b) ^ (a & c) ^ (b & c); + + var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); + var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); + + var t1 = h + sigma1 + ch + K[i] + W[i]; + var t2 = sigma0 + maj; + + h = g; + g = f; + f = e; + e = (d + t1) | 0; + d = c; + c = b; + b = a; + a = (t1 + t2) | 0; + } + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + H[4] = (H[4] + e) | 0; + H[5] = (H[5] + f) | 0; + H[6] = (H[6] + g) | 0; + H[7] = (H[7] + h) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Return final computed hash + return this._hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA256('message'); + * var hash = CryptoJS.SHA256(wordArray); + */ + C.SHA256 = Hasher._createHelper(SHA256); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA256(message, key); + */ + C.HmacSHA256 = Hasher._createHmacHelper(SHA256); + }(Math)); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var SHA256 = C_algo.SHA256; + + /** + * SHA-224 hash algorithm. + */ + var SHA224 = C_algo.SHA224 = SHA256.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 + ]); + }, + + _doFinalize: function () { + var hash = SHA256._doFinalize.call(this); + + hash.sigBytes -= 4; + + return hash; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA224('message'); + * var hash = CryptoJS.SHA224(wordArray); + */ + C.SHA224 = SHA256._createHelper(SHA224); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA224(message, key); + */ + C.HmacSHA224 = SHA256._createHmacHelper(SHA224); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Hasher = C_lib.Hasher; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var X64WordArray = C_x64.WordArray; + var C_algo = C.algo; + + function X64Word_create() { + return X64Word.create.apply(X64Word, arguments); + } + + // Constants + var K = [ + X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), + X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), + X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), + X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), + X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), + X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), + X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), + X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), + X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), + X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), + X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), + X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), + X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), + X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), + X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), + X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), + X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), + X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), + X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), + X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), + X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), + X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), + X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), + X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), + X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), + X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), + X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), + X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), + X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), + X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), + X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), + X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), + X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), + X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), + X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), + X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), + X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), + X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), + X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), + X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) + ]; + + // Reusable objects + var W = []; + (function () { + for (var i = 0; i < 80; i++) { + W[i] = X64Word_create(); + } + }()); + + /** + * SHA-512 hash algorithm. + */ + var SHA512 = C_algo.SHA512 = Hasher.extend({ + _doReset: function () { + this._hash = new X64WordArray.init([ + new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), + new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), + new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), + new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) + ]); + }, + + _doProcessBlock: function (M, offset) { + // Shortcuts + var H = this._hash.words; + + var H0 = H[0]; + var H1 = H[1]; + var H2 = H[2]; + var H3 = H[3]; + var H4 = H[4]; + var H5 = H[5]; + var H6 = H[6]; + var H7 = H[7]; + + var H0h = H0.high; + var H0l = H0.low; + var H1h = H1.high; + var H1l = H1.low; + var H2h = H2.high; + var H2l = H2.low; + var H3h = H3.high; + var H3l = H3.low; + var H4h = H4.high; + var H4l = H4.low; + var H5h = H5.high; + var H5l = H5.low; + var H6h = H6.high; + var H6l = H6.low; + var H7h = H7.high; + var H7l = H7.low; + + // Working variables + var ah = H0h; + var al = H0l; + var bh = H1h; + var bl = H1l; + var ch = H2h; + var cl = H2l; + var dh = H3h; + var dl = H3l; + var eh = H4h; + var el = H4l; + var fh = H5h; + var fl = H5l; + var gh = H6h; + var gl = H6l; + var hh = H7h; + var hl = H7l; + + // Rounds + for (var i = 0; i < 80; i++) { + var Wil; + var Wih; + + // Shortcut + var Wi = W[i]; + + // Extend message + if (i < 16) { + Wih = Wi.high = M[offset + i * 2] | 0; + Wil = Wi.low = M[offset + i * 2 + 1] | 0; + } else { + // Gamma0 + var gamma0x = W[i - 15]; + var gamma0xh = gamma0x.high; + var gamma0xl = gamma0x.low; + var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); + var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); + + // Gamma1 + var gamma1x = W[i - 2]; + var gamma1xh = gamma1x.high; + var gamma1xl = gamma1x.low; + var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); + var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7 = W[i - 7]; + var Wi7h = Wi7.high; + var Wi7l = Wi7.low; + + var Wi16 = W[i - 16]; + var Wi16h = Wi16.high; + var Wi16l = Wi16.low; + + Wil = gamma0l + Wi7l; + Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); + Wil = Wil + gamma1l; + Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); + Wil = Wil + Wi16l; + Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); + + Wi.high = Wih; + Wi.low = Wil; + } + + var chh = (eh & fh) ^ (~eh & gh); + var chl = (el & fl) ^ (~el & gl); + var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); + var majl = (al & bl) ^ (al & cl) ^ (bl & cl); + + var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); + var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); + var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); + var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); + + // t1 = h + sigma1 + ch + K[i] + W[i] + var Ki = K[i]; + var Kih = Ki.high; + var Kil = Ki.low; + + var t1l = hl + sigma1l; + var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); + var t1l = t1l + chl; + var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); + var t1l = t1l + Kil; + var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); + var t1l = t1l + Wil; + var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); + + // t2 = sigma0 + maj + var t2l = sigma0l + majl; + var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); + + // Update working variables + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; + } + + // Intermediate hash value + H0l = H0.low = (H0l + al); + H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); + H1l = H1.low = (H1l + bl); + H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); + H2l = H2.low = (H2l + cl); + H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); + H3l = H3.low = (H3l + dl); + H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); + H4l = H4.low = (H4l + el); + H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); + H5l = H5.low = (H5l + fl); + H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); + H6l = H6.low = (H6l + gl); + H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); + H7l = H7.low = (H7l + hl); + H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Convert hash to 32-bit word array before returning + var hash = this._hash.toX32(); + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + }, + + blockSize: 1024/32 + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA512('message'); + * var hash = CryptoJS.SHA512(wordArray); + */ + C.SHA512 = Hasher._createHelper(SHA512); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA512(message, key); + */ + C.HmacSHA512 = Hasher._createHmacHelper(SHA512); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var X64WordArray = C_x64.WordArray; + var C_algo = C.algo; + var SHA512 = C_algo.SHA512; + + /** + * SHA-384 hash algorithm. + */ + var SHA384 = C_algo.SHA384 = SHA512.extend({ + _doReset: function () { + this._hash = new X64WordArray.init([ + new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), + new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), + new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), + new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) + ]); + }, + + _doFinalize: function () { + var hash = SHA512._doFinalize.call(this); + + hash.sigBytes -= 16; + + return hash; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA384('message'); + * var hash = CryptoJS.SHA384(wordArray); + */ + C.SHA384 = SHA512._createHelper(SHA384); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA384(message, key); + */ + C.HmacSHA384 = SHA512._createHmacHelper(SHA384); + }()); + + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var C_algo = C.algo; + + // Constants tables + var RHO_OFFSETS = []; + var PI_INDEXES = []; + var ROUND_CONSTANTS = []; + + // Compute Constants + (function () { + // Compute rho offset constants + var x = 1, y = 0; + for (var t = 0; t < 24; t++) { + RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; + + var newX = y % 5; + var newY = (2 * x + 3 * y) % 5; + x = newX; + y = newY; + } + + // Compute pi index constants + for (var x = 0; x < 5; x++) { + for (var y = 0; y < 5; y++) { + PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; + } + } + + // Compute round constants + var LFSR = 0x01; + for (var i = 0; i < 24; i++) { + var roundConstantMsw = 0; + var roundConstantLsw = 0; + + for (var j = 0; j < 7; j++) { + if (LFSR & 0x01) { + var bitPosition = (1 << j) - 1; + if (bitPosition < 32) { + roundConstantLsw ^= 1 << bitPosition; + } else /* if (bitPosition >= 32) */ { + roundConstantMsw ^= 1 << (bitPosition - 32); + } + } + + // Compute next LFSR + if (LFSR & 0x80) { + // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 + LFSR = (LFSR << 1) ^ 0x71; + } else { + LFSR <<= 1; + } + } + + ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); + } + }()); + + // Reusable objects for temporary values + var T = []; + (function () { + for (var i = 0; i < 25; i++) { + T[i] = X64Word.create(); + } + }()); + + /** + * SHA-3 hash algorithm. + */ + var SHA3 = C_algo.SHA3 = Hasher.extend({ + /** + * Configuration options. + * + * @property {number} outputLength + * The desired number of bits in the output hash. + * Only values permitted are: 224, 256, 384, 512. + * Default: 512 + */ + cfg: Hasher.cfg.extend({ + outputLength: 512 + }), + + _doReset: function () { + var state = this._state = [] + for (var i = 0; i < 25; i++) { + state[i] = new X64Word.init(); + } + + this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; + }, + + _doProcessBlock: function (M, offset) { + // Shortcuts + var state = this._state; + var nBlockSizeLanes = this.blockSize / 2; + + // Absorb + for (var i = 0; i < nBlockSizeLanes; i++) { + // Shortcuts + var M2i = M[offset + 2 * i]; + var M2i1 = M[offset + 2 * i + 1]; + + // Swap endian + M2i = ( + (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | + (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) + ); + M2i1 = ( + (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | + (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) + ); + + // Absorb message into state + var lane = state[i]; + lane.high ^= M2i1; + lane.low ^= M2i; + } + + // Rounds + for (var round = 0; round < 24; round++) { + // Theta + for (var x = 0; x < 5; x++) { + // Mix column lanes + var tMsw = 0, tLsw = 0; + for (var y = 0; y < 5; y++) { + var lane = state[x + 5 * y]; + tMsw ^= lane.high; + tLsw ^= lane.low; + } + + // Temporary values + var Tx = T[x]; + Tx.high = tMsw; + Tx.low = tLsw; + } + for (var x = 0; x < 5; x++) { + // Shortcuts + var Tx4 = T[(x + 4) % 5]; + var Tx1 = T[(x + 1) % 5]; + var Tx1Msw = Tx1.high; + var Tx1Lsw = Tx1.low; + + // Mix surrounding columns + var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); + var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); + for (var y = 0; y < 5; y++) { + var lane = state[x + 5 * y]; + lane.high ^= tMsw; + lane.low ^= tLsw; + } + } + + // Rho Pi + for (var laneIndex = 1; laneIndex < 25; laneIndex++) { + var tMsw; + var tLsw; + + // Shortcuts + var lane = state[laneIndex]; + var laneMsw = lane.high; + var laneLsw = lane.low; + var rhoOffset = RHO_OFFSETS[laneIndex]; + + // Rotate lanes + if (rhoOffset < 32) { + tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); + tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); + } else /* if (rhoOffset >= 32) */ { + tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); + tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); + } + + // Transpose lanes + var TPiLane = T[PI_INDEXES[laneIndex]]; + TPiLane.high = tMsw; + TPiLane.low = tLsw; + } + + // Rho pi at x = y = 0 + var T0 = T[0]; + var state0 = state[0]; + T0.high = state0.high; + T0.low = state0.low; + + // Chi + for (var x = 0; x < 5; x++) { + for (var y = 0; y < 5; y++) { + // Shortcuts + var laneIndex = x + 5 * y; + var lane = state[laneIndex]; + var TLane = T[laneIndex]; + var Tx1Lane = T[((x + 1) % 5) + 5 * y]; + var Tx2Lane = T[((x + 2) % 5) + 5 * y]; + + // Mix rows + lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); + lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); + } + } + + // Iota + var lane = state[0]; + var roundConstant = ROUND_CONSTANTS[round]; + lane.high ^= roundConstant.high; + lane.low ^= roundConstant.low; + } + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + var blockSizeBits = this.blockSize * 32; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); + dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var state = this._state; + var outputLengthBytes = this.cfg.outputLength / 8; + var outputLengthLanes = outputLengthBytes / 8; + + // Squeeze + var hashWords = []; + for (var i = 0; i < outputLengthLanes; i++) { + // Shortcuts + var lane = state[i]; + var laneMsw = lane.high; + var laneLsw = lane.low; + + // Swap endian + laneMsw = ( + (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | + (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) + ); + laneLsw = ( + (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | + (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) + ); + + // Squeeze state to retrieve hash + hashWords.push(laneLsw); + hashWords.push(laneMsw); + } + + // Return final computed hash + return new WordArray.init(hashWords, outputLengthBytes); + }, + + clone: function () { + var clone = Hasher.clone.call(this); + + var state = clone._state = this._state.slice(0); + for (var i = 0; i < 25; i++) { + state[i] = state[i].clone(); + } + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA3('message'); + * var hash = CryptoJS.SHA3(wordArray); + */ + C.SHA3 = Hasher._createHelper(SHA3); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA3(message, key); + */ + C.HmacSHA3 = Hasher._createHmacHelper(SHA3); + }(Math)); + + + /** @preserve + (c) 2012 by Cédric Mesnil. All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Constants table + var _zl = WordArray.create([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); + var _zr = WordArray.create([ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); + var _sl = WordArray.create([ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); + var _sr = WordArray.create([ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); + + var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); + var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); + + /** + * RIPEMD160 hash algorithm. + */ + var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ + _doReset: function () { + this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); + }, + + _doProcessBlock: function (M, offset) { + + // Swap endian + for (var i = 0; i < 16; i++) { + // Shortcuts + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + // Swap + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } + // Shortcut + var H = this._hash.words; + var hl = _hl.words; + var hr = _hr.words; + var zl = _zl.words; + var zr = _zr.words; + var sl = _sl.words; + var sr = _sr.words; + + // Working variables + var al, bl, cl, dl, el; + var ar, br, cr, dr, er; + + ar = al = H[0]; + br = bl = H[1]; + cr = cl = H[2]; + dr = dl = H[3]; + er = el = H[4]; + // Computation + var t; + for (var i = 0; i < 80; i += 1) { + t = (al + M[offset+zl[i]])|0; + if (i<16){ + t += f1(bl,cl,dl) + hl[0]; + } else if (i<32) { + t += f2(bl,cl,dl) + hl[1]; + } else if (i<48) { + t += f3(bl,cl,dl) + hl[2]; + } else if (i<64) { + t += f4(bl,cl,dl) + hl[3]; + } else {// if (i<80) { + t += f5(bl,cl,dl) + hl[4]; + } + t = t|0; + t = rotl(t,sl[i]); + t = (t+el)|0; + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = t; + + t = (ar + M[offset+zr[i]])|0; + if (i<16){ + t += f5(br,cr,dr) + hr[0]; + } else if (i<32) { + t += f4(br,cr,dr) + hr[1]; + } else if (i<48) { + t += f3(br,cr,dr) + hr[2]; + } else if (i<64) { + t += f2(br,cr,dr) + hr[3]; + } else {// if (i<80) { + t += f1(br,cr,dr) + hr[4]; + } + t = t|0; + t = rotl(t,sr[i]) ; + t = (t+er)|0; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = t; + } + // Intermediate hash value + t = (H[1] + cl + dr)|0; + H[1] = (H[2] + dl + er)|0; + H[2] = (H[3] + el + ar)|0; + H[3] = (H[4] + al + br)|0; + H[4] = (H[0] + bl + cr)|0; + H[0] = t; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | + (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) + ); + data.sigBytes = (dataWords.length + 1) * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var hash = this._hash; + var H = hash.words; + + // Swap endian + for (var i = 0; i < 5; i++) { + // Shortcut + var H_i = H[i]; + + // Swap + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + + function f1(x, y, z) { + return ((x) ^ (y) ^ (z)); + + } + + function f2(x, y, z) { + return (((x)&(y)) | ((~x)&(z))); + } + + function f3(x, y, z) { + return (((x) | (~(y))) ^ (z)); + } + + function f4(x, y, z) { + return (((x) & (z)) | ((y)&(~(z)))); + } + + function f5(x, y, z) { + return ((x) ^ ((y) |(~(z)))); + + } + + function rotl(x,n) { + return (x<>>(32-n)); + } + + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.RIPEMD160('message'); + * var hash = CryptoJS.RIPEMD160(wordArray); + */ + C.RIPEMD160 = Hasher._createHelper(RIPEMD160); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacRIPEMD160(message, key); + */ + C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); + }(Math)); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var C_enc = C.enc; + var Utf8 = C_enc.Utf8; + var C_algo = C.algo; + + /** + * HMAC algorithm. + */ + var HMAC = C_algo.HMAC = Base.extend({ + /** + * Initializes a newly created HMAC. + * + * @param {Hasher} hasher The hash algorithm to use. + * @param {WordArray|string} key The secret key. + * + * @example + * + * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); + */ + init: function (hasher, key) { + // Init hasher + hasher = this._hasher = new hasher.init(); + + // Convert string to WordArray, else assume WordArray already + if (typeof key == 'string') { + key = Utf8.parse(key); + } + + // Shortcuts + var hasherBlockSize = hasher.blockSize; + var hasherBlockSizeBytes = hasherBlockSize * 4; + + // Allow arbitrary length keys + if (key.sigBytes > hasherBlockSizeBytes) { + key = hasher.finalize(key); + } + + // Clamp excess bits + key.clamp(); + + // Clone key for inner and outer pads + var oKey = this._oKey = key.clone(); + var iKey = this._iKey = key.clone(); + + // Shortcuts + var oKeyWords = oKey.words; + var iKeyWords = iKey.words; + + // XOR keys with pad constants + for (var i = 0; i < hasherBlockSize; i++) { + oKeyWords[i] ^= 0x5c5c5c5c; + iKeyWords[i] ^= 0x36363636; + } + oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; + + // Set initial values + this.reset(); + }, + + /** + * Resets this HMAC to its initial state. + * + * @example + * + * hmacHasher.reset(); + */ + reset: function () { + // Shortcut + var hasher = this._hasher; + + // Reset + hasher.reset(); + hasher.update(this._iKey); + }, + + /** + * Updates this HMAC with a message. + * + * @param {WordArray|string} messageUpdate The message to append. + * + * @return {HMAC} This HMAC instance. + * + * @example + * + * hmacHasher.update('message'); + * hmacHasher.update(wordArray); + */ + update: function (messageUpdate) { + this._hasher.update(messageUpdate); + + // Chainable + return this; + }, + + /** + * Finalizes the HMAC computation. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} messageUpdate (Optional) A final message update. + * + * @return {WordArray} The HMAC. + * + * @example + * + * var hmac = hmacHasher.finalize(); + * var hmac = hmacHasher.finalize('message'); + * var hmac = hmacHasher.finalize(wordArray); + */ + finalize: function (messageUpdate) { + // Shortcut + var hasher = this._hasher; + + // Compute HMAC + var innerHash = hasher.finalize(messageUpdate); + hasher.reset(); + var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); + + return hmac; + } + }); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var SHA1 = C_algo.SHA1; + var HMAC = C_algo.HMAC; + + /** + * Password-Based Key Derivation Function 2 algorithm. + */ + var PBKDF2 = C_algo.PBKDF2 = Base.extend({ + /** + * Configuration options. + * + * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) + * @property {Hasher} hasher The hasher to use. Default: SHA1 + * @property {number} iterations The number of iterations to perform. Default: 1 + */ + cfg: Base.extend({ + keySize: 128/32, + hasher: SHA1, + iterations: 1 + }), + + /** + * Initializes a newly created key derivation function. + * + * @param {Object} cfg (Optional) The configuration options to use for the derivation. + * + * @example + * + * var kdf = CryptoJS.algo.PBKDF2.create(); + * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); + * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); + */ + init: function (cfg) { + this.cfg = this.cfg.extend(cfg); + }, + + /** + * Computes the Password-Based Key Derivation Function 2. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * + * @return {WordArray} The derived key. + * + * @example + * + * var key = kdf.compute(password, salt); + */ + compute: function (password, salt) { + // Shortcut + var cfg = this.cfg; + + // Init HMAC + var hmac = HMAC.create(cfg.hasher, password); + + // Initial values + var derivedKey = WordArray.create(); + var blockIndex = WordArray.create([0x00000001]); + + // Shortcuts + var derivedKeyWords = derivedKey.words; + var blockIndexWords = blockIndex.words; + var keySize = cfg.keySize; + var iterations = cfg.iterations; + + // Generate key + while (derivedKeyWords.length < keySize) { + var block = hmac.update(salt).finalize(blockIndex); + hmac.reset(); + + // Shortcuts + var blockWords = block.words; + var blockWordsLength = blockWords.length; + + // Iterations + var intermediate = block; + for (var i = 1; i < iterations; i++) { + intermediate = hmac.finalize(intermediate); + hmac.reset(); + + // Shortcut + var intermediateWords = intermediate.words; + + // XOR intermediate with block + for (var j = 0; j < blockWordsLength; j++) { + blockWords[j] ^= intermediateWords[j]; + } + } + + derivedKey.concat(block); + blockIndexWords[0]++; + } + derivedKey.sigBytes = keySize * 4; + + return derivedKey; + } + }); + + /** + * Computes the Password-Based Key Derivation Function 2. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * @param {Object} cfg (Optional) The configuration options to use for this computation. + * + * @return {WordArray} The derived key. + * + * @static + * + * @example + * + * var key = CryptoJS.PBKDF2(password, salt); + * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); + * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); + */ + C.PBKDF2 = function (password, salt, cfg) { + return PBKDF2.create(cfg).compute(password, salt); + }; + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var MD5 = C_algo.MD5; + + /** + * This key derivation function is meant to conform with EVP_BytesToKey. + * www.openssl.org/docs/crypto/EVP_BytesToKey.html + */ + var EvpKDF = C_algo.EvpKDF = Base.extend({ + /** + * Configuration options. + * + * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) + * @property {Hasher} hasher The hash algorithm to use. Default: MD5 + * @property {number} iterations The number of iterations to perform. Default: 1 + */ + cfg: Base.extend({ + keySize: 128/32, + hasher: MD5, + iterations: 1 + }), + + /** + * Initializes a newly created key derivation function. + * + * @param {Object} cfg (Optional) The configuration options to use for the derivation. + * + * @example + * + * var kdf = CryptoJS.algo.EvpKDF.create(); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); + */ + init: function (cfg) { + this.cfg = this.cfg.extend(cfg); + }, + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * + * @return {WordArray} The derived key. + * + * @example + * + * var key = kdf.compute(password, salt); + */ + compute: function (password, salt) { + var block; + + // Shortcut + var cfg = this.cfg; + + // Init hasher + var hasher = cfg.hasher.create(); + + // Initial values + var derivedKey = WordArray.create(); + + // Shortcuts + var derivedKeyWords = derivedKey.words; + var keySize = cfg.keySize; + var iterations = cfg.iterations; + + // Generate key + while (derivedKeyWords.length < keySize) { + if (block) { + hasher.update(block); + } + block = hasher.update(password).finalize(salt); + hasher.reset(); + + // Iterations + for (var i = 1; i < iterations; i++) { + block = hasher.finalize(block); + hasher.reset(); + } + + derivedKey.concat(block); + } + derivedKey.sigBytes = keySize * 4; + + return derivedKey; + } + }); + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * @param {Object} cfg (Optional) The configuration options to use for this computation. + * + * @return {WordArray} The derived key. + * + * @static + * + * @example + * + * var key = CryptoJS.EvpKDF(password, salt); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); + */ + C.EvpKDF = function (password, salt, cfg) { + return EvpKDF.create(cfg).compute(password, salt); + }; + }()); + + + /** + * Cipher core components. + */ + CryptoJS.lib.Cipher || (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; + var C_enc = C.enc; + var Utf8 = C_enc.Utf8; + var Base64 = C_enc.Base64; + var C_algo = C.algo; + var EvpKDF = C_algo.EvpKDF; + + /** + * Abstract base cipher template. + * + * @property {number} keySize This cipher's key size. Default: 4 (128 bits) + * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) + * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. + * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. + */ + var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + * + * @property {WordArray} iv The IV to use for this operation. + */ + cfg: Base.extend(), + + /** + * Creates this cipher in encryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); + */ + createEncryptor: function (key, cfg) { + return this.create(this._ENC_XFORM_MODE, key, cfg); + }, + + /** + * Creates this cipher in decryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); + */ + createDecryptor: function (key, cfg) { + return this.create(this._DEC_XFORM_MODE, key, cfg); + }, + + /** + * Initializes a newly created cipher. + * + * @param {number} xformMode Either the encryption or decryption transormation mode constant. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @example + * + * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); + */ + init: function (xformMode, key, cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); + + // Store transform mode and key + this._xformMode = xformMode; + this._key = key; + + // Set initial values + this.reset(); + }, + + /** + * Resets this cipher to its initial state. + * + * @example + * + * cipher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-cipher logic + this._doReset(); + }, + + /** + * Adds data to be encrypted or decrypted. + * + * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. + * + * @return {WordArray} The data after processing. + * + * @example + * + * var encrypted = cipher.process('data'); + * var encrypted = cipher.process(wordArray); + */ + process: function (dataUpdate) { + // Append + this._append(dataUpdate); + + // Process available blocks + return this._process(); + }, + + /** + * Finalizes the encryption or decryption process. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. + * + * @return {WordArray} The data after final processing. + * + * @example + * + * var encrypted = cipher.finalize(); + * var encrypted = cipher.finalize('data'); + * var encrypted = cipher.finalize(wordArray); + */ + finalize: function (dataUpdate) { + // Final data update + if (dataUpdate) { + this._append(dataUpdate); + } + + // Perform concrete-cipher logic + var finalProcessedData = this._doFinalize(); + + return finalProcessedData; + }, + + keySize: 128/32, + + ivSize: 128/32, + + _ENC_XFORM_MODE: 1, + + _DEC_XFORM_MODE: 2, + + /** + * Creates shortcut functions to a cipher's object interface. + * + * @param {Cipher} cipher The cipher to create a helper for. + * + * @return {Object} An object with encrypt and decrypt shortcut functions. + * + * @static + * + * @example + * + * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); + */ + _createHelper: (function () { + function selectCipherStrategy(key) { + if (typeof key == 'string') { + return PasswordBasedCipher; + } else { + return SerializableCipher; + } + } + + return function (cipher) { + return { + encrypt: function (message, key, cfg) { + return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); + }, + + decrypt: function (ciphertext, key, cfg) { + return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); + } + }; + }; + }()) + }); + + /** + * Abstract base stream cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) + */ + var StreamCipher = C_lib.StreamCipher = Cipher.extend({ + _doFinalize: function () { + // Process partial blocks + var finalProcessedBlocks = this._process(!!'flush'); + + return finalProcessedBlocks; + }, + + blockSize: 1 + }); + + /** + * Mode namespace. + */ + var C_mode = C.mode = {}; + + /** + * Abstract base block cipher mode template. + */ + var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ + /** + * Creates this mode for encryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); + */ + createEncryptor: function (cipher, iv) { + return this.Encryptor.create(cipher, iv); + }, + + /** + * Creates this mode for decryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); + */ + createDecryptor: function (cipher, iv) { + return this.Decryptor.create(cipher, iv); + }, + + /** + * Initializes a newly created mode. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @example + * + * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); + */ + init: function (cipher, iv) { + this._cipher = cipher; + this._iv = iv; + } + }); + + /** + * Cipher Block Chaining mode. + */ + var CBC = C_mode.CBC = (function () { + /** + * Abstract base CBC mode. + */ + var CBC = BlockCipherMode.extend(); + + /** + * CBC encryptor. + */ + CBC.Encryptor = CBC.extend({ + /** + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example + * + * mode.processBlock(data.words, offset); + */ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // XOR and encrypt + xorBlock.call(this, words, offset, blockSize); + cipher.encryptBlock(words, offset); + + // Remember this block to use with next block + this._prevBlock = words.slice(offset, offset + blockSize); + } + }); + + /** + * CBC decryptor. + */ + CBC.Decryptor = CBC.extend({ + /** + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example + * + * mode.processBlock(data.words, offset); + */ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // Remember this block to use with next block + var thisBlock = words.slice(offset, offset + blockSize); + + // Decrypt and XOR + cipher.decryptBlock(words, offset); + xorBlock.call(this, words, offset, blockSize); + + // This block becomes the previous block + this._prevBlock = thisBlock; + } + }); + + function xorBlock(words, offset, blockSize) { + var block; + + // Shortcut + var iv = this._iv; + + // Choose mixing block + if (iv) { + block = iv; + + // Remove IV for subsequent blocks + this._iv = undefined; + } else { + block = this._prevBlock; + } + + // XOR blocks + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= block[i]; + } + } + + return CBC; + }()); + + /** + * Padding namespace. + */ + var C_pad = C.pad = {}; + + /** + * PKCS #5/7 padding strategy. + */ + var Pkcs7 = C_pad.Pkcs7 = { + /** + * Pads data using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to pad. + * @param {number} blockSize The multiple that the data should be padded to. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.pad(wordArray, 4); + */ + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; + + // Create padding word + var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; + + // Create padding + var paddingWords = []; + for (var i = 0; i < nPaddingBytes; i += 4) { + paddingWords.push(paddingWord); + } + var padding = WordArray.create(paddingWords, nPaddingBytes); + + // Add padding + data.concat(padding); + }, + + /** + * Unpads data that had been padded using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to unpad. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.unpad(wordArray); + */ + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + /** + * Abstract base block cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) + */ + var BlockCipher = C_lib.BlockCipher = Cipher.extend({ + /** + * Configuration options. + * + * @property {Mode} mode The block mode to use. Default: CBC + * @property {Padding} padding The padding strategy to use. Default: Pkcs7 + */ + cfg: Cipher.cfg.extend({ + mode: CBC, + padding: Pkcs7 + }), + + reset: function () { + var modeCreator; + + // Reset cipher + Cipher.reset.call(this); + + // Shortcuts + var cfg = this.cfg; + var iv = cfg.iv; + var mode = cfg.mode; + + // Reset block mode + if (this._xformMode == this._ENC_XFORM_MODE) { + modeCreator = mode.createEncryptor; + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + modeCreator = mode.createDecryptor; + // Keep at least one block in the buffer for unpadding + this._minBufferSize = 1; + } + + if (this._mode && this._mode.__creator == modeCreator) { + this._mode.init(this, iv && iv.words); + } else { + this._mode = modeCreator.call(mode, this, iv && iv.words); + this._mode.__creator = modeCreator; + } + }, + + _doProcessBlock: function (words, offset) { + this._mode.processBlock(words, offset); + }, + + _doFinalize: function () { + var finalProcessedBlocks; + + // Shortcut + var padding = this.cfg.padding; + + // Finalize + if (this._xformMode == this._ENC_XFORM_MODE) { + // Pad data + padding.pad(this._data, this.blockSize); + + // Process final blocks + finalProcessedBlocks = this._process(!!'flush'); + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + // Process final blocks + finalProcessedBlocks = this._process(!!'flush'); + + // Unpad data + padding.unpad(finalProcessedBlocks); + } + + return finalProcessedBlocks; + }, + + blockSize: 128/32 + }); + + /** + * A collection of cipher parameters. + * + * @property {WordArray} ciphertext The raw ciphertext. + * @property {WordArray} key The key to this ciphertext. + * @property {WordArray} iv The IV used in the ciphering operation. + * @property {WordArray} salt The salt used with a key derivation function. + * @property {Cipher} algorithm The cipher algorithm. + * @property {Mode} mode The block mode used in the ciphering operation. + * @property {Padding} padding The padding scheme used in the ciphering operation. + * @property {number} blockSize The block size of the cipher. + * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. + */ + var CipherParams = C_lib.CipherParams = Base.extend({ + /** + * Initializes a newly created cipher params object. + * + * @param {Object} cipherParams An object with any of the possible cipher parameters. + * + * @example + * + * var cipherParams = CryptoJS.lib.CipherParams.create({ + * ciphertext: ciphertextWordArray, + * key: keyWordArray, + * iv: ivWordArray, + * salt: saltWordArray, + * algorithm: CryptoJS.algo.AES, + * mode: CryptoJS.mode.CBC, + * padding: CryptoJS.pad.PKCS7, + * blockSize: 4, + * formatter: CryptoJS.format.OpenSSL + * }); + */ + init: function (cipherParams) { + this.mixIn(cipherParams); + }, + + /** + * Converts this cipher params object to a string. + * + * @param {Format} formatter (Optional) The formatting strategy to use. + * + * @return {string} The stringified cipher params. + * + * @throws Error If neither the formatter nor the default formatter is set. + * + * @example + * + * var string = cipherParams + ''; + * var string = cipherParams.toString(); + * var string = cipherParams.toString(CryptoJS.format.OpenSSL); + */ + toString: function (formatter) { + return (formatter || this.formatter).stringify(this); + } + }); + + /** + * Format namespace. + */ + var C_format = C.format = {}; + + /** + * OpenSSL formatting strategy. + */ + var OpenSSLFormatter = C_format.OpenSSL = { + /** + * Converts a cipher params object to an OpenSSL-compatible string. + * + * @param {CipherParams} cipherParams The cipher params object. + * + * @return {string} The OpenSSL-compatible string. + * + * @static + * + * @example + * + * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); + */ + stringify: function (cipherParams) { + var wordArray; + + // Shortcuts + var ciphertext = cipherParams.ciphertext; + var salt = cipherParams.salt; + + // Format + if (salt) { + wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); + } else { + wordArray = ciphertext; + } + + return wordArray.toString(Base64); + }, + + /** + * Converts an OpenSSL-compatible string to a cipher params object. + * + * @param {string} openSSLStr The OpenSSL-compatible string. + * + * @return {CipherParams} The cipher params object. + * + * @static + * + * @example + * + * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); + */ + parse: function (openSSLStr) { + var salt; + + // Parse base64 + var ciphertext = Base64.parse(openSSLStr); + + // Shortcut + var ciphertextWords = ciphertext.words; + + // Test for salt + if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { + // Extract salt + salt = WordArray.create(ciphertextWords.slice(2, 4)); + + // Remove salt from ciphertext + ciphertextWords.splice(0, 4); + ciphertext.sigBytes -= 16; + } + + return CipherParams.create({ ciphertext: ciphertext, salt: salt }); + } + }; + + /** + * A cipher wrapper that returns ciphertext as a serializable cipher params object. + */ + var SerializableCipher = C_lib.SerializableCipher = Base.extend({ + /** + * Configuration options. + * + * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL + */ + cfg: Base.extend({ + format: OpenSSLFormatter + }), + + /** + * Encrypts a message. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Encrypt + var encryptor = cipher.createEncryptor(key, cfg); + var ciphertext = encryptor.finalize(message); + + // Shortcut + var cipherCfg = encryptor.cfg; + + // Create and return serializable cipher params + return CipherParams.create({ + ciphertext: ciphertext, + key: key, + iv: cipherCfg.iv, + algorithm: cipher, + mode: cipherCfg.mode, + padding: cipherCfg.padding, + blockSize: cipher.blockSize, + formatter: cfg.format + }); + }, + + /** + * Decrypts serialized ciphertext. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); + + // Decrypt + var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); + + return plaintext; + }, + + /** + * Converts serialized ciphertext to CipherParams, + * else assumed CipherParams already and returns ciphertext unchanged. + * + * @param {CipherParams|string} ciphertext The ciphertext. + * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. + * + * @return {CipherParams} The unserialized ciphertext. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); + */ + _parse: function (ciphertext, format) { + if (typeof ciphertext == 'string') { + return format.parse(ciphertext, this); + } else { + return ciphertext; + } + } + }); + + /** + * Key derivation function namespace. + */ + var C_kdf = C.kdf = {}; + + /** + * OpenSSL key derivation function. + */ + var OpenSSLKdf = C_kdf.OpenSSL = { + /** + * Derives a key and IV from a password. + * + * @param {string} password The password to derive from. + * @param {number} keySize The size in words of the key to generate. + * @param {number} ivSize The size in words of the IV to generate. + * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. + * + * @return {CipherParams} A cipher params object with the key, IV, and salt. + * + * @static + * + * @example + * + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); + */ + execute: function (password, keySize, ivSize, salt) { + // Generate random salt + if (!salt) { + salt = WordArray.random(64/8); + } + + // Derive key and IV + var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); + + // Separate key and IV + var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); + key.sigBytes = keySize * 4; + + // Return params + return CipherParams.create({ key: key, iv: iv, salt: salt }); + } + }; + + /** + * A serializable cipher wrapper that derives the key from a password, + * and returns ciphertext as a serializable cipher params object. + */ + var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ + /** + * Configuration options. + * + * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL + */ + cfg: SerializableCipher.cfg.extend({ + kdf: OpenSSLKdf + }), + + /** + * Encrypts a message using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Derive key and other params + var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); + + // Add IV to config + cfg.iv = derivedParams.iv; + + // Encrypt + var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); + + // Mix in derived params + ciphertext.mixIn(derivedParams); + + return ciphertext; + }, + + /** + * Decrypts serialized ciphertext using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); + + // Derive key and other params + var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); + + // Add IV to config + cfg.iv = derivedParams.iv; + + // Decrypt + var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); + + return plaintext; + } + }); + }()); + + + /** + * Cipher Feedback block mode. + */ + CryptoJS.mode.CFB = (function () { + var CFB = CryptoJS.lib.BlockCipherMode.extend(); + + CFB.Encryptor = CFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); + + // Remember this block to use with next block + this._prevBlock = words.slice(offset, offset + blockSize); + } + }); + + CFB.Decryptor = CFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // Remember this block to use with next block + var thisBlock = words.slice(offset, offset + blockSize); + + generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); + + // This block becomes the previous block + this._prevBlock = thisBlock; + } + }); + + function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { + var keystream; + + // Shortcut + var iv = this._iv; + + // Generate keystream + if (iv) { + keystream = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } else { + keystream = this._prevBlock; + } + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + + return CFB; + }()); + + + /** + * Counter block mode. + */ + CryptoJS.mode.CTR = (function () { + var CTR = CryptoJS.lib.BlockCipherMode.extend(); + + var Encryptor = CTR.Encryptor = CTR.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var counter = this._counter; + + // Generate keystream + if (iv) { + counter = this._counter = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + var keystream = counter.slice(0); + cipher.encryptBlock(keystream, 0); + + // Increment counter + counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + CTR.Decryptor = Encryptor; + + return CTR; + }()); + + + /** @preserve + * Counter block mode compatible with Dr Brian Gladman fileenc.c + * derived from CryptoJS.mode.CTR + * Jan Hruby jhruby.web@gmail.com + */ + CryptoJS.mode.CTRGladman = (function () { + var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); + + function incWord(word) + { + if (((word >> 24) & 0xff) === 0xff) { //overflow + var b1 = (word >> 16)&0xff; + var b2 = (word >> 8)&0xff; + var b3 = word & 0xff; + + if (b1 === 0xff) // overflow b1 + { + b1 = 0; + if (b2 === 0xff) + { + b2 = 0; + if (b3 === 0xff) + { + b3 = 0; + } + else + { + ++b3; + } + } + else + { + ++b2; + } + } + else + { + ++b1; + } + + word = 0; + word += (b1 << 16); + word += (b2 << 8); + word += b3; + } + else + { + word += (0x01 << 24); + } + return word; + } + + function incCounter(counter) + { + if ((counter[0] = incWord(counter[0])) === 0) + { + // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 + counter[1] = incWord(counter[1]); + } + return counter; + } + + var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var counter = this._counter; + + // Generate keystream + if (iv) { + counter = this._counter = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + + incCounter(counter); + + var keystream = counter.slice(0); + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + CTRGladman.Decryptor = Encryptor; + + return CTRGladman; + }()); + + + + + /** + * Output Feedback block mode. + */ + CryptoJS.mode.OFB = (function () { + var OFB = CryptoJS.lib.BlockCipherMode.extend(); + + var Encryptor = OFB.Encryptor = OFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var keystream = this._keystream; + + // Generate keystream + if (iv) { + keystream = this._keystream = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + OFB.Decryptor = Encryptor; + + return OFB; + }()); + + + /** + * Electronic Codebook block mode. + */ + CryptoJS.mode.ECB = (function () { + var ECB = CryptoJS.lib.BlockCipherMode.extend(); + + ECB.Encryptor = ECB.extend({ + processBlock: function (words, offset) { + this._cipher.encryptBlock(words, offset); + } + }); + + ECB.Decryptor = ECB.extend({ + processBlock: function (words, offset) { + this._cipher.decryptBlock(words, offset); + } + }); + + return ECB; + }()); + + + /** + * ANSI X.923 padding strategy. + */ + CryptoJS.pad.AnsiX923 = { + pad: function (data, blockSize) { + // Shortcuts + var dataSigBytes = data.sigBytes; + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; + + // Compute last byte position + var lastBytePos = dataSigBytes + nPaddingBytes - 1; + + // Pad + data.clamp(); + data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); + data.sigBytes += nPaddingBytes; + }, + + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + + /** + * ISO 10126 padding strategy. + */ + CryptoJS.pad.Iso10126 = { + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; + + // Pad + data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). + concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); + }, + + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + + /** + * ISO/IEC 9797-1 Padding Method 2. + */ + CryptoJS.pad.Iso97971 = { + pad: function (data, blockSize) { + // Add 0x80 byte + data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); + + // Zero pad the rest + CryptoJS.pad.ZeroPadding.pad(data, blockSize); + }, + + unpad: function (data) { + // Remove zero padding + CryptoJS.pad.ZeroPadding.unpad(data); + + // Remove one more byte -- the 0x80 byte + data.sigBytes--; + } + }; + + + /** + * Zero padding strategy. + */ + CryptoJS.pad.ZeroPadding = { + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Pad + data.clamp(); + data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); + }, + + unpad: function (data) { + // Shortcut + var dataWords = data.words; + + // Unpad + var i = data.sigBytes - 1; + for (var i = data.sigBytes - 1; i >= 0; i--) { + if (((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { + data.sigBytes = i + 1; + break; + } + } + } + }; + + + /** + * A noop padding strategy. + */ + CryptoJS.pad.NoPadding = { + pad: function () { + }, + + unpad: function () { + } + }; + + + (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var CipherParams = C_lib.CipherParams; + var C_enc = C.enc; + var Hex = C_enc.Hex; + var C_format = C.format; + + var HexFormatter = C_format.Hex = { + /** + * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. + * + * @param {CipherParams} cipherParams The cipher params object. + * + * @return {string} The hexadecimally encoded string. + * + * @static + * + * @example + * + * var hexString = CryptoJS.format.Hex.stringify(cipherParams); + */ + stringify: function (cipherParams) { + return cipherParams.ciphertext.toString(Hex); + }, + + /** + * Converts a hexadecimally encoded ciphertext string to a cipher params object. + * + * @param {string} input The hexadecimally encoded string. + * + * @return {CipherParams} The cipher params object. + * + * @static + * + * @example + * + * var cipherParams = CryptoJS.format.Hex.parse(hexString); + */ + parse: function (input) { + var ciphertext = Hex.parse(input); + return CipherParams.create({ ciphertext: ciphertext }); + } + }; + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + // Lookup tables + var SBOX = []; + var INV_SBOX = []; + var SUB_MIX_0 = []; + var SUB_MIX_1 = []; + var SUB_MIX_2 = []; + var SUB_MIX_3 = []; + var INV_SUB_MIX_0 = []; + var INV_SUB_MIX_1 = []; + var INV_SUB_MIX_2 = []; + var INV_SUB_MIX_3 = []; + + // Compute lookup tables + (function () { + // Compute double table + var d = []; + for (var i = 0; i < 256; i++) { + if (i < 128) { + d[i] = i << 1; + } else { + d[i] = (i << 1) ^ 0x11b; + } + } + + // Walk GF(2^8) + var x = 0; + var xi = 0; + for (var i = 0; i < 256; i++) { + // Compute sbox + var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; + SBOX[x] = sx; + INV_SBOX[sx] = x; + + // Compute multiplication + var x2 = d[x]; + var x4 = d[x2]; + var x8 = d[x4]; + + // Compute sub bytes, mix columns tables + var t = (d[sx] * 0x101) ^ (sx * 0x1010100); + SUB_MIX_0[x] = (t << 24) | (t >>> 8); + SUB_MIX_1[x] = (t << 16) | (t >>> 16); + SUB_MIX_2[x] = (t << 8) | (t >>> 24); + SUB_MIX_3[x] = t; + + // Compute inv sub bytes, inv mix columns tables + var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); + INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); + INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); + INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); + INV_SUB_MIX_3[sx] = t; + + // Compute next counter + if (!x) { + x = xi = 1; + } else { + x = x2 ^ d[d[d[x8 ^ x2]]]; + xi ^= d[d[xi]]; + } + } + }()); + + // Precomputed Rcon lookup + var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; + + /** + * AES block cipher algorithm. + */ + var AES = C_algo.AES = BlockCipher.extend({ + _doReset: function () { + var t; + + // Skip reset of nRounds has been set before and key did not change + if (this._nRounds && this._keyPriorReset === this._key) { + return; + } + + // Shortcuts + var key = this._keyPriorReset = this._key; + var keyWords = key.words; + var keySize = key.sigBytes / 4; + + // Compute number of rounds + var nRounds = this._nRounds = keySize + 6; + + // Compute number of key schedule rows + var ksRows = (nRounds + 1) * 4; + + // Compute key schedule + var keySchedule = this._keySchedule = []; + for (var ksRow = 0; ksRow < ksRows; ksRow++) { + if (ksRow < keySize) { + keySchedule[ksRow] = keyWords[ksRow]; + } else { + t = keySchedule[ksRow - 1]; + + if (!(ksRow % keySize)) { + // Rot word + t = (t << 8) | (t >>> 24); + + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; + + // Mix Rcon + t ^= RCON[(ksRow / keySize) | 0] << 24; + } else if (keySize > 6 && ksRow % keySize == 4) { + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; + } + + keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; + } + } + + // Compute inv key schedule + var invKeySchedule = this._invKeySchedule = []; + for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { + var ksRow = ksRows - invKsRow; + + if (invKsRow % 4) { + var t = keySchedule[ksRow]; + } else { + var t = keySchedule[ksRow - 4]; + } + + if (invKsRow < 4 || ksRow <= 4) { + invKeySchedule[invKsRow] = t; + } else { + invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ + INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; + } + } + }, + + encryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); + }, + + decryptBlock: function (M, offset) { + // Swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + + this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); + + // Inv swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + }, + + _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { + // Shortcut + var nRounds = this._nRounds; + + // Get input, add round key + var s0 = M[offset] ^ keySchedule[0]; + var s1 = M[offset + 1] ^ keySchedule[1]; + var s2 = M[offset + 2] ^ keySchedule[2]; + var s3 = M[offset + 3] ^ keySchedule[3]; + + // Key schedule row counter + var ksRow = 4; + + // Rounds + for (var round = 1; round < nRounds; round++) { + // Shift rows, sub bytes, mix columns, add round key + var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; + var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; + var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; + var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; + + // Update state + s0 = t0; + s1 = t1; + s2 = t2; + s3 = t3; + } + + // Shift rows, sub bytes, add round key + var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; + var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; + var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; + var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; + + // Set output + M[offset] = t0; + M[offset + 1] = t1; + M[offset + 2] = t2; + M[offset + 3] = t3; + }, + + keySize: 256/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); + */ + C.AES = BlockCipher._createHelper(AES); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + // Permuted Choice 1 constants + var PC1 = [ + 57, 49, 41, 33, 25, 17, 9, 1, + 58, 50, 42, 34, 26, 18, 10, 2, + 59, 51, 43, 35, 27, 19, 11, 3, + 60, 52, 44, 36, 63, 55, 47, 39, + 31, 23, 15, 7, 62, 54, 46, 38, + 30, 22, 14, 6, 61, 53, 45, 37, + 29, 21, 13, 5, 28, 20, 12, 4 + ]; + + // Permuted Choice 2 constants + var PC2 = [ + 14, 17, 11, 24, 1, 5, + 3, 28, 15, 6, 21, 10, + 23, 19, 12, 4, 26, 8, + 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, + 30, 40, 51, 45, 33, 48, + 44, 49, 39, 56, 34, 53, + 46, 42, 50, 36, 29, 32 + ]; + + // Cumulative bit shift constants + var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; + + // SBOXes and round permutation constants + var SBOX_P = [ + { + 0x0: 0x808200, + 0x10000000: 0x8000, + 0x20000000: 0x808002, + 0x30000000: 0x2, + 0x40000000: 0x200, + 0x50000000: 0x808202, + 0x60000000: 0x800202, + 0x70000000: 0x800000, + 0x80000000: 0x202, + 0x90000000: 0x800200, + 0xa0000000: 0x8200, + 0xb0000000: 0x808000, + 0xc0000000: 0x8002, + 0xd0000000: 0x800002, + 0xe0000000: 0x0, + 0xf0000000: 0x8202, + 0x8000000: 0x0, + 0x18000000: 0x808202, + 0x28000000: 0x8202, + 0x38000000: 0x8000, + 0x48000000: 0x808200, + 0x58000000: 0x200, + 0x68000000: 0x808002, + 0x78000000: 0x2, + 0x88000000: 0x800200, + 0x98000000: 0x8200, + 0xa8000000: 0x808000, + 0xb8000000: 0x800202, + 0xc8000000: 0x800002, + 0xd8000000: 0x8002, + 0xe8000000: 0x202, + 0xf8000000: 0x800000, + 0x1: 0x8000, + 0x10000001: 0x2, + 0x20000001: 0x808200, + 0x30000001: 0x800000, + 0x40000001: 0x808002, + 0x50000001: 0x8200, + 0x60000001: 0x200, + 0x70000001: 0x800202, + 0x80000001: 0x808202, + 0x90000001: 0x808000, + 0xa0000001: 0x800002, + 0xb0000001: 0x8202, + 0xc0000001: 0x202, + 0xd0000001: 0x800200, + 0xe0000001: 0x8002, + 0xf0000001: 0x0, + 0x8000001: 0x808202, + 0x18000001: 0x808000, + 0x28000001: 0x800000, + 0x38000001: 0x200, + 0x48000001: 0x8000, + 0x58000001: 0x800002, + 0x68000001: 0x2, + 0x78000001: 0x8202, + 0x88000001: 0x8002, + 0x98000001: 0x800202, + 0xa8000001: 0x202, + 0xb8000001: 0x808200, + 0xc8000001: 0x800200, + 0xd8000001: 0x0, + 0xe8000001: 0x8200, + 0xf8000001: 0x808002 + }, + { + 0x0: 0x40084010, + 0x1000000: 0x4000, + 0x2000000: 0x80000, + 0x3000000: 0x40080010, + 0x4000000: 0x40000010, + 0x5000000: 0x40084000, + 0x6000000: 0x40004000, + 0x7000000: 0x10, + 0x8000000: 0x84000, + 0x9000000: 0x40004010, + 0xa000000: 0x40000000, + 0xb000000: 0x84010, + 0xc000000: 0x80010, + 0xd000000: 0x0, + 0xe000000: 0x4010, + 0xf000000: 0x40080000, + 0x800000: 0x40004000, + 0x1800000: 0x84010, + 0x2800000: 0x10, + 0x3800000: 0x40004010, + 0x4800000: 0x40084010, + 0x5800000: 0x40000000, + 0x6800000: 0x80000, + 0x7800000: 0x40080010, + 0x8800000: 0x80010, + 0x9800000: 0x0, + 0xa800000: 0x4000, + 0xb800000: 0x40080000, + 0xc800000: 0x40000010, + 0xd800000: 0x84000, + 0xe800000: 0x40084000, + 0xf800000: 0x4010, + 0x10000000: 0x0, + 0x11000000: 0x40080010, + 0x12000000: 0x40004010, + 0x13000000: 0x40084000, + 0x14000000: 0x40080000, + 0x15000000: 0x10, + 0x16000000: 0x84010, + 0x17000000: 0x4000, + 0x18000000: 0x4010, + 0x19000000: 0x80000, + 0x1a000000: 0x80010, + 0x1b000000: 0x40000010, + 0x1c000000: 0x84000, + 0x1d000000: 0x40004000, + 0x1e000000: 0x40000000, + 0x1f000000: 0x40084010, + 0x10800000: 0x84010, + 0x11800000: 0x80000, + 0x12800000: 0x40080000, + 0x13800000: 0x4000, + 0x14800000: 0x40004000, + 0x15800000: 0x40084010, + 0x16800000: 0x10, + 0x17800000: 0x40000000, + 0x18800000: 0x40084000, + 0x19800000: 0x40000010, + 0x1a800000: 0x40004010, + 0x1b800000: 0x80010, + 0x1c800000: 0x0, + 0x1d800000: 0x4010, + 0x1e800000: 0x40080010, + 0x1f800000: 0x84000 + }, + { + 0x0: 0x104, + 0x100000: 0x0, + 0x200000: 0x4000100, + 0x300000: 0x10104, + 0x400000: 0x10004, + 0x500000: 0x4000004, + 0x600000: 0x4010104, + 0x700000: 0x4010000, + 0x800000: 0x4000000, + 0x900000: 0x4010100, + 0xa00000: 0x10100, + 0xb00000: 0x4010004, + 0xc00000: 0x4000104, + 0xd00000: 0x10000, + 0xe00000: 0x4, + 0xf00000: 0x100, + 0x80000: 0x4010100, + 0x180000: 0x4010004, + 0x280000: 0x0, + 0x380000: 0x4000100, + 0x480000: 0x4000004, + 0x580000: 0x10000, + 0x680000: 0x10004, + 0x780000: 0x104, + 0x880000: 0x4, + 0x980000: 0x100, + 0xa80000: 0x4010000, + 0xb80000: 0x10104, + 0xc80000: 0x10100, + 0xd80000: 0x4000104, + 0xe80000: 0x4010104, + 0xf80000: 0x4000000, + 0x1000000: 0x4010100, + 0x1100000: 0x10004, + 0x1200000: 0x10000, + 0x1300000: 0x4000100, + 0x1400000: 0x100, + 0x1500000: 0x4010104, + 0x1600000: 0x4000004, + 0x1700000: 0x0, + 0x1800000: 0x4000104, + 0x1900000: 0x4000000, + 0x1a00000: 0x4, + 0x1b00000: 0x10100, + 0x1c00000: 0x4010000, + 0x1d00000: 0x104, + 0x1e00000: 0x10104, + 0x1f00000: 0x4010004, + 0x1080000: 0x4000000, + 0x1180000: 0x104, + 0x1280000: 0x4010100, + 0x1380000: 0x0, + 0x1480000: 0x10004, + 0x1580000: 0x4000100, + 0x1680000: 0x100, + 0x1780000: 0x4010004, + 0x1880000: 0x10000, + 0x1980000: 0x4010104, + 0x1a80000: 0x10104, + 0x1b80000: 0x4000004, + 0x1c80000: 0x4000104, + 0x1d80000: 0x4010000, + 0x1e80000: 0x4, + 0x1f80000: 0x10100 + }, + { + 0x0: 0x80401000, + 0x10000: 0x80001040, + 0x20000: 0x401040, + 0x30000: 0x80400000, + 0x40000: 0x0, + 0x50000: 0x401000, + 0x60000: 0x80000040, + 0x70000: 0x400040, + 0x80000: 0x80000000, + 0x90000: 0x400000, + 0xa0000: 0x40, + 0xb0000: 0x80001000, + 0xc0000: 0x80400040, + 0xd0000: 0x1040, + 0xe0000: 0x1000, + 0xf0000: 0x80401040, + 0x8000: 0x80001040, + 0x18000: 0x40, + 0x28000: 0x80400040, + 0x38000: 0x80001000, + 0x48000: 0x401000, + 0x58000: 0x80401040, + 0x68000: 0x0, + 0x78000: 0x80400000, + 0x88000: 0x1000, + 0x98000: 0x80401000, + 0xa8000: 0x400000, + 0xb8000: 0x1040, + 0xc8000: 0x80000000, + 0xd8000: 0x400040, + 0xe8000: 0x401040, + 0xf8000: 0x80000040, + 0x100000: 0x400040, + 0x110000: 0x401000, + 0x120000: 0x80000040, + 0x130000: 0x0, + 0x140000: 0x1040, + 0x150000: 0x80400040, + 0x160000: 0x80401000, + 0x170000: 0x80001040, + 0x180000: 0x80401040, + 0x190000: 0x80000000, + 0x1a0000: 0x80400000, + 0x1b0000: 0x401040, + 0x1c0000: 0x80001000, + 0x1d0000: 0x400000, + 0x1e0000: 0x40, + 0x1f0000: 0x1000, + 0x108000: 0x80400000, + 0x118000: 0x80401040, + 0x128000: 0x0, + 0x138000: 0x401000, + 0x148000: 0x400040, + 0x158000: 0x80000000, + 0x168000: 0x80001040, + 0x178000: 0x40, + 0x188000: 0x80000040, + 0x198000: 0x1000, + 0x1a8000: 0x80001000, + 0x1b8000: 0x80400040, + 0x1c8000: 0x1040, + 0x1d8000: 0x80401000, + 0x1e8000: 0x400000, + 0x1f8000: 0x401040 + }, + { + 0x0: 0x80, + 0x1000: 0x1040000, + 0x2000: 0x40000, + 0x3000: 0x20000000, + 0x4000: 0x20040080, + 0x5000: 0x1000080, + 0x6000: 0x21000080, + 0x7000: 0x40080, + 0x8000: 0x1000000, + 0x9000: 0x20040000, + 0xa000: 0x20000080, + 0xb000: 0x21040080, + 0xc000: 0x21040000, + 0xd000: 0x0, + 0xe000: 0x1040080, + 0xf000: 0x21000000, + 0x800: 0x1040080, + 0x1800: 0x21000080, + 0x2800: 0x80, + 0x3800: 0x1040000, + 0x4800: 0x40000, + 0x5800: 0x20040080, + 0x6800: 0x21040000, + 0x7800: 0x20000000, + 0x8800: 0x20040000, + 0x9800: 0x0, + 0xa800: 0x21040080, + 0xb800: 0x1000080, + 0xc800: 0x20000080, + 0xd800: 0x21000000, + 0xe800: 0x1000000, + 0xf800: 0x40080, + 0x10000: 0x40000, + 0x11000: 0x80, + 0x12000: 0x20000000, + 0x13000: 0x21000080, + 0x14000: 0x1000080, + 0x15000: 0x21040000, + 0x16000: 0x20040080, + 0x17000: 0x1000000, + 0x18000: 0x21040080, + 0x19000: 0x21000000, + 0x1a000: 0x1040000, + 0x1b000: 0x20040000, + 0x1c000: 0x40080, + 0x1d000: 0x20000080, + 0x1e000: 0x0, + 0x1f000: 0x1040080, + 0x10800: 0x21000080, + 0x11800: 0x1000000, + 0x12800: 0x1040000, + 0x13800: 0x20040080, + 0x14800: 0x20000000, + 0x15800: 0x1040080, + 0x16800: 0x80, + 0x17800: 0x21040000, + 0x18800: 0x40080, + 0x19800: 0x21040080, + 0x1a800: 0x0, + 0x1b800: 0x21000000, + 0x1c800: 0x1000080, + 0x1d800: 0x40000, + 0x1e800: 0x20040000, + 0x1f800: 0x20000080 + }, + { + 0x0: 0x10000008, + 0x100: 0x2000, + 0x200: 0x10200000, + 0x300: 0x10202008, + 0x400: 0x10002000, + 0x500: 0x200000, + 0x600: 0x200008, + 0x700: 0x10000000, + 0x800: 0x0, + 0x900: 0x10002008, + 0xa00: 0x202000, + 0xb00: 0x8, + 0xc00: 0x10200008, + 0xd00: 0x202008, + 0xe00: 0x2008, + 0xf00: 0x10202000, + 0x80: 0x10200000, + 0x180: 0x10202008, + 0x280: 0x8, + 0x380: 0x200000, + 0x480: 0x202008, + 0x580: 0x10000008, + 0x680: 0x10002000, + 0x780: 0x2008, + 0x880: 0x200008, + 0x980: 0x2000, + 0xa80: 0x10002008, + 0xb80: 0x10200008, + 0xc80: 0x0, + 0xd80: 0x10202000, + 0xe80: 0x202000, + 0xf80: 0x10000000, + 0x1000: 0x10002000, + 0x1100: 0x10200008, + 0x1200: 0x10202008, + 0x1300: 0x2008, + 0x1400: 0x200000, + 0x1500: 0x10000000, + 0x1600: 0x10000008, + 0x1700: 0x202000, + 0x1800: 0x202008, + 0x1900: 0x0, + 0x1a00: 0x8, + 0x1b00: 0x10200000, + 0x1c00: 0x2000, + 0x1d00: 0x10002008, + 0x1e00: 0x10202000, + 0x1f00: 0x200008, + 0x1080: 0x8, + 0x1180: 0x202000, + 0x1280: 0x200000, + 0x1380: 0x10000008, + 0x1480: 0x10002000, + 0x1580: 0x2008, + 0x1680: 0x10202008, + 0x1780: 0x10200000, + 0x1880: 0x10202000, + 0x1980: 0x10200008, + 0x1a80: 0x2000, + 0x1b80: 0x202008, + 0x1c80: 0x200008, + 0x1d80: 0x0, + 0x1e80: 0x10000000, + 0x1f80: 0x10002008 + }, + { + 0x0: 0x100000, + 0x10: 0x2000401, + 0x20: 0x400, + 0x30: 0x100401, + 0x40: 0x2100401, + 0x50: 0x0, + 0x60: 0x1, + 0x70: 0x2100001, + 0x80: 0x2000400, + 0x90: 0x100001, + 0xa0: 0x2000001, + 0xb0: 0x2100400, + 0xc0: 0x2100000, + 0xd0: 0x401, + 0xe0: 0x100400, + 0xf0: 0x2000000, + 0x8: 0x2100001, + 0x18: 0x0, + 0x28: 0x2000401, + 0x38: 0x2100400, + 0x48: 0x100000, + 0x58: 0x2000001, + 0x68: 0x2000000, + 0x78: 0x401, + 0x88: 0x100401, + 0x98: 0x2000400, + 0xa8: 0x2100000, + 0xb8: 0x100001, + 0xc8: 0x400, + 0xd8: 0x2100401, + 0xe8: 0x1, + 0xf8: 0x100400, + 0x100: 0x2000000, + 0x110: 0x100000, + 0x120: 0x2000401, + 0x130: 0x2100001, + 0x140: 0x100001, + 0x150: 0x2000400, + 0x160: 0x2100400, + 0x170: 0x100401, + 0x180: 0x401, + 0x190: 0x2100401, + 0x1a0: 0x100400, + 0x1b0: 0x1, + 0x1c0: 0x0, + 0x1d0: 0x2100000, + 0x1e0: 0x2000001, + 0x1f0: 0x400, + 0x108: 0x100400, + 0x118: 0x2000401, + 0x128: 0x2100001, + 0x138: 0x1, + 0x148: 0x2000000, + 0x158: 0x100000, + 0x168: 0x401, + 0x178: 0x2100400, + 0x188: 0x2000001, + 0x198: 0x2100000, + 0x1a8: 0x0, + 0x1b8: 0x2100401, + 0x1c8: 0x100401, + 0x1d8: 0x400, + 0x1e8: 0x2000400, + 0x1f8: 0x100001 + }, + { + 0x0: 0x8000820, + 0x1: 0x20000, + 0x2: 0x8000000, + 0x3: 0x20, + 0x4: 0x20020, + 0x5: 0x8020820, + 0x6: 0x8020800, + 0x7: 0x800, + 0x8: 0x8020000, + 0x9: 0x8000800, + 0xa: 0x20800, + 0xb: 0x8020020, + 0xc: 0x820, + 0xd: 0x0, + 0xe: 0x8000020, + 0xf: 0x20820, + 0x80000000: 0x800, + 0x80000001: 0x8020820, + 0x80000002: 0x8000820, + 0x80000003: 0x8000000, + 0x80000004: 0x8020000, + 0x80000005: 0x20800, + 0x80000006: 0x20820, + 0x80000007: 0x20, + 0x80000008: 0x8000020, + 0x80000009: 0x820, + 0x8000000a: 0x20020, + 0x8000000b: 0x8020800, + 0x8000000c: 0x0, + 0x8000000d: 0x8020020, + 0x8000000e: 0x8000800, + 0x8000000f: 0x20000, + 0x10: 0x20820, + 0x11: 0x8020800, + 0x12: 0x20, + 0x13: 0x800, + 0x14: 0x8000800, + 0x15: 0x8000020, + 0x16: 0x8020020, + 0x17: 0x20000, + 0x18: 0x0, + 0x19: 0x20020, + 0x1a: 0x8020000, + 0x1b: 0x8000820, + 0x1c: 0x8020820, + 0x1d: 0x20800, + 0x1e: 0x820, + 0x1f: 0x8000000, + 0x80000010: 0x20000, + 0x80000011: 0x800, + 0x80000012: 0x8020020, + 0x80000013: 0x20820, + 0x80000014: 0x20, + 0x80000015: 0x8020000, + 0x80000016: 0x8000000, + 0x80000017: 0x8000820, + 0x80000018: 0x8020820, + 0x80000019: 0x8000020, + 0x8000001a: 0x8000800, + 0x8000001b: 0x0, + 0x8000001c: 0x20800, + 0x8000001d: 0x820, + 0x8000001e: 0x20020, + 0x8000001f: 0x8020800 + } + ]; + + // Masks that select the SBOX input + var SBOX_MASK = [ + 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, + 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f + ]; + + /** + * DES block cipher algorithm. + */ + var DES = C_algo.DES = BlockCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + + // Select 56 bits according to PC1 + var keyBits = []; + for (var i = 0; i < 56; i++) { + var keyBitPos = PC1[i] - 1; + keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; + } + + // Assemble 16 subkeys + var subKeys = this._subKeys = []; + for (var nSubKey = 0; nSubKey < 16; nSubKey++) { + // Create subkey + var subKey = subKeys[nSubKey] = []; + + // Shortcut + var bitShift = BIT_SHIFTS[nSubKey]; + + // Select 48 bits according to PC2 + for (var i = 0; i < 24; i++) { + // Select from the left 28 key bits + subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); + + // Select from the right 28 key bits + subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); + } + + // Since each subkey is applied to an expanded 32-bit input, + // the subkey can be broken into 8 values scaled to 32-bits, + // which allows the key to be used without expansion + subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); + for (var i = 1; i < 7; i++) { + subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); + } + subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); + } + + // Compute inverse subkeys + var invSubKeys = this._invSubKeys = []; + for (var i = 0; i < 16; i++) { + invSubKeys[i] = subKeys[15 - i]; + } + }, + + encryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._subKeys); + }, + + decryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._invSubKeys); + }, + + _doCryptBlock: function (M, offset, subKeys) { + // Get input + this._lBlock = M[offset]; + this._rBlock = M[offset + 1]; + + // Initial permutation + exchangeLR.call(this, 4, 0x0f0f0f0f); + exchangeLR.call(this, 16, 0x0000ffff); + exchangeRL.call(this, 2, 0x33333333); + exchangeRL.call(this, 8, 0x00ff00ff); + exchangeLR.call(this, 1, 0x55555555); + + // Rounds + for (var round = 0; round < 16; round++) { + // Shortcuts + var subKey = subKeys[round]; + var lBlock = this._lBlock; + var rBlock = this._rBlock; + + // Feistel function + var f = 0; + for (var i = 0; i < 8; i++) { + f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; + } + this._lBlock = rBlock; + this._rBlock = lBlock ^ f; + } + + // Undo swap from last round + var t = this._lBlock; + this._lBlock = this._rBlock; + this._rBlock = t; + + // Final permutation + exchangeLR.call(this, 1, 0x55555555); + exchangeRL.call(this, 8, 0x00ff00ff); + exchangeRL.call(this, 2, 0x33333333); + exchangeLR.call(this, 16, 0x0000ffff); + exchangeLR.call(this, 4, 0x0f0f0f0f); + + // Set output + M[offset] = this._lBlock; + M[offset + 1] = this._rBlock; + }, + + keySize: 64/32, + + ivSize: 64/32, + + blockSize: 64/32 + }); + + // Swap bits across the left and right words + function exchangeLR(offset, mask) { + var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; + this._rBlock ^= t; + this._lBlock ^= t << offset; + } + + function exchangeRL(offset, mask) { + var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; + this._lBlock ^= t; + this._rBlock ^= t << offset; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); + */ + C.DES = BlockCipher._createHelper(DES); + + /** + * Triple-DES block cipher algorithm. + */ + var TripleDES = C_algo.TripleDES = BlockCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + // Make sure the key length is valid (64, 128 or >= 192 bit) + if (keyWords.length !== 2 && keyWords.length !== 4 && keyWords.length < 6) { + throw new Error('Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.'); + } + + // Extend the key according to the keying options defined in 3DES standard + var key1 = keyWords.slice(0, 2); + var key2 = keyWords.length < 4 ? keyWords.slice(0, 2) : keyWords.slice(2, 4); + var key3 = keyWords.length < 6 ? keyWords.slice(0, 2) : keyWords.slice(4, 6); + + // Create DES instances + this._des1 = DES.createEncryptor(WordArray.create(key1)); + this._des2 = DES.createEncryptor(WordArray.create(key2)); + this._des3 = DES.createEncryptor(WordArray.create(key3)); + }, + + encryptBlock: function (M, offset) { + this._des1.encryptBlock(M, offset); + this._des2.decryptBlock(M, offset); + this._des3.encryptBlock(M, offset); + }, + + decryptBlock: function (M, offset) { + this._des3.decryptBlock(M, offset); + this._des2.encryptBlock(M, offset); + this._des1.decryptBlock(M, offset); + }, + + keySize: 192/32, + + ivSize: 64/32, + + blockSize: 64/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); + */ + C.TripleDES = BlockCipher._createHelper(TripleDES); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + /** + * RC4 stream cipher algorithm. + */ + var RC4 = C_algo.RC4 = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + var keySigBytes = key.sigBytes; + + // Init sbox + var S = this._S = []; + for (var i = 0; i < 256; i++) { + S[i] = i; + } + + // Key setup + for (var i = 0, j = 0; i < 256; i++) { + var keyByteIndex = i % keySigBytes; + var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; + + j = (j + S[i] + keyByte) % 256; + + // Swap + var t = S[i]; + S[i] = S[j]; + S[j] = t; + } + + // Counters + this._i = this._j = 0; + }, + + _doProcessBlock: function (M, offset) { + M[offset] ^= generateKeystreamWord.call(this); + }, + + keySize: 256/32, + + ivSize: 0 + }); + + function generateKeystreamWord() { + // Shortcuts + var S = this._S; + var i = this._i; + var j = this._j; + + // Generate keystream word + var keystreamWord = 0; + for (var n = 0; n < 4; n++) { + i = (i + 1) % 256; + j = (j + S[i]) % 256; + + // Swap + var t = S[i]; + S[i] = S[j]; + S[j] = t; + + keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); + } + + // Update counters + this._i = i; + this._j = j; + + return keystreamWord; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); + */ + C.RC4 = StreamCipher._createHelper(RC4); + + /** + * Modified RC4 stream cipher algorithm. + */ + var RC4Drop = C_algo.RC4Drop = RC4.extend({ + /** + * Configuration options. + * + * @property {number} drop The number of keystream words to drop. Default 192 + */ + cfg: RC4.cfg.extend({ + drop: 192 + }), + + _doReset: function () { + RC4._doReset.call(this); + + // Drop + for (var i = this.cfg.drop; i > 0; i--) { + generateKeystreamWord.call(this); + } + } + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); + */ + C.RC4Drop = StreamCipher._createHelper(RC4Drop); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + // Reusable objects + var S = []; + var C_ = []; + var G = []; + + /** + * Rabbit stream cipher algorithm + */ + var Rabbit = C_algo.Rabbit = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var K = this._key.words; + var iv = this.cfg.iv; + + // Swap endian + for (var i = 0; i < 4; i++) { + K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | + (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); + } + + // Generate initial state values + var X = this._X = [ + K[0], (K[3] << 16) | (K[2] >>> 16), + K[1], (K[0] << 16) | (K[3] >>> 16), + K[2], (K[1] << 16) | (K[0] >>> 16), + K[3], (K[2] << 16) | (K[1] >>> 16) + ]; + + // Generate initial counter values + var C = this._C = [ + (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), + (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), + (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), + (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) + ]; + + // Carry bit + this._b = 0; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + + // Modify the counters + for (var i = 0; i < 8; i++) { + C[i] ^= X[(i + 4) & 7]; + } + + // IV setup + if (iv) { + // Shortcuts + var IV = iv.words; + var IV_0 = IV[0]; + var IV_1 = IV[1]; + + // Generate four subvectors + var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); + var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); + var i1 = (i0 >>> 16) | (i2 & 0xffff0000); + var i3 = (i2 << 16) | (i0 & 0x0000ffff); + + // Modify counter values + C[0] ^= i0; + C[1] ^= i1; + C[2] ^= i2; + C[3] ^= i3; + C[4] ^= i0; + C[5] ^= i1; + C[6] ^= i2; + C[7] ^= i3; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + } + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var X = this._X; + + // Iterate the system + nextState.call(this); + + // Generate four keystream words + S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); + S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); + S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); + S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); + + for (var i = 0; i < 4; i++) { + // Swap endian + S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | + (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); + + // Encrypt + M[offset + i] ^= S[i]; + } + }, + + blockSize: 128/32, + + ivSize: 64/32 + }); + + function nextState() { + // Shortcuts + var X = this._X; + var C = this._C; + + // Save old counter values + for (var i = 0; i < 8; i++) { + C_[i] = C[i]; + } + + // Calculate new counter values + C[0] = (C[0] + 0x4d34d34d + this._b) | 0; + C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; + C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; + C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; + C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; + C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; + C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; + C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; + this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; + + // Calculate the g-values + for (var i = 0; i < 8; i++) { + var gx = X[i] + C[i]; + + // Construct high and low argument for squaring + var ga = gx & 0xffff; + var gb = gx >>> 16; + + // Calculate high and low result of squaring + var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; + var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); + + // High XOR low + G[i] = gh ^ gl; + } + + // Calculate new state values + X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; + X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; + X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; + X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; + X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; + X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; + X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; + X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); + * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); + */ + C.Rabbit = StreamCipher._createHelper(Rabbit); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + // Reusable objects + var S = []; + var C_ = []; + var G = []; + + /** + * Rabbit stream cipher algorithm. + * + * This is a legacy version that neglected to convert the key to little-endian. + * This error doesn't affect the cipher's security, + * but it does affect its compatibility with other implementations. + */ + var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var K = this._key.words; + var iv = this.cfg.iv; + + // Generate initial state values + var X = this._X = [ + K[0], (K[3] << 16) | (K[2] >>> 16), + K[1], (K[0] << 16) | (K[3] >>> 16), + K[2], (K[1] << 16) | (K[0] >>> 16), + K[3], (K[2] << 16) | (K[1] >>> 16) + ]; + + // Generate initial counter values + var C = this._C = [ + (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), + (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), + (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), + (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) + ]; + + // Carry bit + this._b = 0; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + + // Modify the counters + for (var i = 0; i < 8; i++) { + C[i] ^= X[(i + 4) & 7]; + } + + // IV setup + if (iv) { + // Shortcuts + var IV = iv.words; + var IV_0 = IV[0]; + var IV_1 = IV[1]; + + // Generate four subvectors + var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); + var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); + var i1 = (i0 >>> 16) | (i2 & 0xffff0000); + var i3 = (i2 << 16) | (i0 & 0x0000ffff); + + // Modify counter values + C[0] ^= i0; + C[1] ^= i1; + C[2] ^= i2; + C[3] ^= i3; + C[4] ^= i0; + C[5] ^= i1; + C[6] ^= i2; + C[7] ^= i3; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + } + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var X = this._X; + + // Iterate the system + nextState.call(this); + + // Generate four keystream words + S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); + S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); + S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); + S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); + + for (var i = 0; i < 4; i++) { + // Swap endian + S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | + (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); + + // Encrypt + M[offset + i] ^= S[i]; + } + }, + + blockSize: 128/32, + + ivSize: 64/32 + }); + + function nextState() { + // Shortcuts + var X = this._X; + var C = this._C; + + // Save old counter values + for (var i = 0; i < 8; i++) { + C_[i] = C[i]; + } + + // Calculate new counter values + C[0] = (C[0] + 0x4d34d34d + this._b) | 0; + C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; + C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; + C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; + C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; + C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; + C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; + C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; + this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; + + // Calculate the g-values + for (var i = 0; i < 8; i++) { + var gx = X[i] + C[i]; + + // Construct high and low argument for squaring + var ga = gx & 0xffff; + var gb = gx >>> 16; + + // Calculate high and low result of squaring + var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; + var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); + + // High XOR low + G[i] = gh ^ gl; + } + + // Calculate new state values + X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; + X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; + X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; + X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; + X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; + X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; + X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; + X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); + */ + C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); + }()); + + + return CryptoJS; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/docs/QuickStartGuide.wiki b/miniprogram_npm/crypto-js/docs/QuickStartGuide.wiki new file mode 100644 index 0000000..2bee35d --- /dev/null +++ b/miniprogram_npm/crypto-js/docs/QuickStartGuide.wiki @@ -0,0 +1,470 @@ + + +---- + += Quick-start Guide = + +== Hashers == + +=== The Hasher Algorithms === + +==== MD5 ==== + +MD5 is a widely used hash function. It's been used in a variety of security applications and is also commonly used to check the integrity of files. Though, MD5 is not collision resistant, and it isn't suitable for applications like SSL certificates or digital signatures that rely on this property. + +{{{ + + +}}} + +==== SHA-1 ==== + +The SHA hash functions were designed by the National Security Agency (NSA). SHA-1 is the most established of the existing SHA hash functions, and it's used in a variety of security applications and protocols. Though, SHA-1's collision resistance has been weakening as new attacks are discovered or improved. + +{{{ + + +}}} + +==== SHA-2 ==== + +SHA-256 is one of the four variants in the SHA-2 set. It isn't as widely used as SHA-1, though it appears to provide much better security. + +{{{ + + +}}} + +SHA-512 is largely identical to SHA-256 but operates on 64-bit words rather than 32. + +{{{ + + +}}} + +CryptoJS also supports SHA-224 and SHA-384, which are largely identical but truncated versions of SHA-256 and SHA-512 respectively. + +==== SHA-3 ==== + +SHA-3 is the winner of a five-year competition to select a new cryptographic hash algorithm where 64 competing designs were evaluated. + +{{{ + + +}}} + +SHA-3 can be configured to output hash lengths of one of 224, 256, 384, or 512 bits. The default is 512 bits. + +{{{ + + +}}} + +==== RIPEMD-160 ==== + +{{{ + + +}}} + +=== The Hasher Input === + +The hash algorithms accept either strings or instances of CryptoJS.lib.WordArray. A WordArray object represents an array of 32-bit words. When you pass a string, it's automatically converted to a WordArray encoded as UTF-8. + +=== The Hasher Output === + +The hash you get back isn't a string yet. It's a WordArray object. When you use a WordArray object in a string context, it's automatically converted to a hex string. + +{{{ + + +}}} + +You can convert a WordArray object to other formats by explicitly calling the toString method and passing an encoder. + +{{{ + + + +}}} + +=== Progressive Hashing === + +{{{ + + +}}} + +== HMAC == + +Keyed-hash message authentication codes (HMAC) is a mechanism for message authentication using cryptographic hash functions. + +HMAC can be used in combination with any iterated cryptographic hash function. + +{{{ + + + + + +}}} + +=== Progressive HMAC Hashing === + +{{{ + + +}}} + +== PBKDF2 == + +PBKDF2 is a password-based key derivation function. In many applications of cryptography, user security is ultimately dependent on a password, and because a password usually can't be used directly as a cryptographic key, some processing is required. + +A salt provides a large set of keys for any given password, and an iteration count increases the cost of producing keys from a password, thereby also increasing the difficulty of attack. + +{{{ + + +}}} + +== Ciphers == + +=== The Cipher Algorithms === + +==== AES ==== + +The Advanced Encryption Standard (AES) is a U.S. Federal Information Processing Standard (FIPS). It was selected after a 5-year process where 15 competing designs were evaluated. + +{{{ + + +}}} + +CryptoJS supports AES-128, AES-192, and AES-256. It will pick the variant by the size of the key you pass in. If you use a passphrase, then it will generate a 256-bit key. + +==== DES, Triple DES ==== + +DES is a previously dominant algorithm for encryption, and was published as an official Federal Information Processing Standard (FIPS). DES is now considered to be insecure due to the small key size. + +{{{ + + +}}} + +Triple DES applies DES three times to each block to increase the key size. The algorithm is believed to be secure in this form. + +{{{ + + +}}} + +==== Rabbit ==== + +Rabbit is a high-performance stream cipher and a finalist in the eSTREAM Portfolio. It is one of the four designs selected after a 3 1/2-year process where 22 designs were evaluated. + +{{{ + + +}}} + +==== RC4, RC4Drop ==== + +RC4 is a widely-used stream cipher. It's used in popular protocols such as SSL and WEP. Although remarkable for its simplicity and speed, the algorithm's history doesn't inspire confidence in its security. + +{{{ + + +}}} + +It was discovered that the first few bytes of keystream are strongly non-random and leak information about the key. We can defend against this attack by discarding the initial portion of the keystream. This modified algorithm is traditionally called RC4-drop. + +By default, 192 words (768 bytes) are dropped, but you can configure the algorithm to drop any number of words. + +{{{ + + +}}} + +=== Custom Key and IV === + +{{{ + + +}}} + +=== Block Modes and Padding === + +{{{ + + + + +}}} + +CryptoJS supports the following modes: + + * CBC (the default) + * CFB + * CTR + * OFB + * ECB + +And CryptoJS supports the following padding schemes: + + * Pkcs7 (the default) + * Iso97971 + * AnsiX923 + * Iso10126 + * ZeroPadding + * NoPadding + +=== The Cipher Input === + +For the plaintext message, the cipher algorithms accept either strings or instances of CryptoJS.lib.WordArray. + +For the key, when you pass a string, it's treated as a passphrase and used to derive an actual key and IV. Or you can pass a WordArray that represents the actual key. If you pass the actual key, you must also pass the actual IV. + +For the ciphertext, the cipher algorithms accept either strings or instances of CryptoJS.lib.CipherParams. A CipherParams object represents a collection of parameters such as the IV, a salt, and the raw ciphertext itself. When you pass a string, it's automatically converted to a CipherParams object according to a configurable format strategy. + +=== The Cipher Output === + +The plaintext you get back after decryption is a WordArray object. See Hashers' Output for more detail. + +The ciphertext you get back after encryption isn't a string yet. It's a CipherParams object. A CipherParams object gives you access to all the parameters used during encryption. When you use a CipherParams object in a string context, it's automatically converted to a string according to a format strategy. The default is an OpenSSL-compatible format. + +{{{ + + +}}} + +You can define your own formats in order to be compatible with other crypto implementations. A format is an object with two methods—stringify and parse—that converts between CipherParams objects and ciphertext strings. + +Here's how you might write a JSON formatter: + +{{{ + + +}}} + +=== Progressive Ciphering === + +{{{ + + +}}} + +=== Interoperability === + +==== With OpenSSL ==== + +Encrypt with OpenSSL: + +{{{ +openssl enc -aes-256-cbc -in infile -out outfile -pass pass:"Secret Passphrase" -e -base64 +}}} + +Decrypt with CryptoJS: + +{{{ + + +}}} + +== Encoders == + +CryptoJS can convert from encoding formats such as Base64, Latin1 or Hex to WordArray objects and vica versa. + +{{{ + + + + +}}} \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/enc-base64.js b/miniprogram_npm/crypto-js/enc-base64.js new file mode 100644 index 0000000..0ffcd53 --- /dev/null +++ b/miniprogram_npm/crypto-js/enc-base64.js @@ -0,0 +1,136 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * Base64 encoding strategy. + */ + var Base64 = C_enc.Base64 = { + /** + * Converts a word array to a Base64 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Base64 string. + * + * @static + * + * @example + * + * var base64String = CryptoJS.enc.Base64.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + var map = this._map; + + // Clamp excess bits + wordArray.clamp(); + + // Convert + var base64Chars = []; + for (var i = 0; i < sigBytes; i += 3) { + var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; + var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; + + var triplet = (byte1 << 16) | (byte2 << 8) | byte3; + + for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { + base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); + } + } + + // Add padding + var paddingChar = map.charAt(64); + if (paddingChar) { + while (base64Chars.length % 4) { + base64Chars.push(paddingChar); + } + } + + return base64Chars.join(''); + }, + + /** + * Converts a Base64 string to a word array. + * + * @param {string} base64Str The Base64 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Base64.parse(base64String); + */ + parse: function (base64Str) { + // Shortcuts + var base64StrLength = base64Str.length; + var map = this._map; + var reverseMap = this._reverseMap; + + if (!reverseMap) { + reverseMap = this._reverseMap = []; + for (var j = 0; j < map.length; j++) { + reverseMap[map.charCodeAt(j)] = j; + } + } + + // Ignore padding + var paddingChar = map.charAt(64); + if (paddingChar) { + var paddingIndex = base64Str.indexOf(paddingChar); + if (paddingIndex !== -1) { + base64StrLength = paddingIndex; + } + } + + // Convert + return parseLoop(base64Str, base64StrLength, reverseMap); + + }, + + _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' + }; + + function parseLoop(base64Str, base64StrLength, reverseMap) { + var words = []; + var nBytes = 0; + for (var i = 0; i < base64StrLength; i++) { + if (i % 4) { + var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); + var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); + var bitsCombined = bits1 | bits2; + words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8); + nBytes++; + } + } + return WordArray.create(words, nBytes); + } + }()); + + + return CryptoJS.enc.Base64; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/enc-base64url.js b/miniprogram_npm/crypto-js/enc-base64url.js new file mode 100644 index 0000000..2468912 --- /dev/null +++ b/miniprogram_npm/crypto-js/enc-base64url.js @@ -0,0 +1,140 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * Base64url encoding strategy. + */ + var Base64url = C_enc.Base64url = { + /** + * Converts a word array to a Base64url string. + * + * @param {WordArray} wordArray The word array. + * + * @param {boolean} urlSafe Whether to use url safe + * + * @return {string} The Base64url string. + * + * @static + * + * @example + * + * var base64String = CryptoJS.enc.Base64url.stringify(wordArray); + */ + stringify: function (wordArray, urlSafe=true) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + var map = urlSafe ? this._safe_map : this._map; + + // Clamp excess bits + wordArray.clamp(); + + // Convert + var base64Chars = []; + for (var i = 0; i < sigBytes; i += 3) { + var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; + var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; + + var triplet = (byte1 << 16) | (byte2 << 8) | byte3; + + for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { + base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); + } + } + + // Add padding + var paddingChar = map.charAt(64); + if (paddingChar) { + while (base64Chars.length % 4) { + base64Chars.push(paddingChar); + } + } + + return base64Chars.join(''); + }, + + /** + * Converts a Base64url string to a word array. + * + * @param {string} base64Str The Base64url string. + * + * @param {boolean} urlSafe Whether to use url safe + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Base64url.parse(base64String); + */ + parse: function (base64Str, urlSafe=true) { + // Shortcuts + var base64StrLength = base64Str.length; + var map = urlSafe ? this._safe_map : this._map; + var reverseMap = this._reverseMap; + + if (!reverseMap) { + reverseMap = this._reverseMap = []; + for (var j = 0; j < map.length; j++) { + reverseMap[map.charCodeAt(j)] = j; + } + } + + // Ignore padding + var paddingChar = map.charAt(64); + if (paddingChar) { + var paddingIndex = base64Str.indexOf(paddingChar); + if (paddingIndex !== -1) { + base64StrLength = paddingIndex; + } + } + + // Convert + return parseLoop(base64Str, base64StrLength, reverseMap); + + }, + + _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', + _safe_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', + }; + + function parseLoop(base64Str, base64StrLength, reverseMap) { + var words = []; + var nBytes = 0; + for (var i = 0; i < base64StrLength; i++) { + if (i % 4) { + var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); + var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); + var bitsCombined = bits1 | bits2; + words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8); + nBytes++; + } + } + return WordArray.create(words, nBytes); + } + }()); + + return CryptoJS.enc.Base64url; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/enc-hex.js b/miniprogram_npm/crypto-js/enc-hex.js new file mode 100644 index 0000000..88161ff --- /dev/null +++ b/miniprogram_npm/crypto-js/enc-hex.js @@ -0,0 +1,18 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.enc.Hex; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/enc-latin1.js b/miniprogram_npm/crypto-js/enc-latin1.js new file mode 100644 index 0000000..ade56dc --- /dev/null +++ b/miniprogram_npm/crypto-js/enc-latin1.js @@ -0,0 +1,18 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.enc.Latin1; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/enc-utf16.js b/miniprogram_npm/crypto-js/enc-utf16.js new file mode 100644 index 0000000..7de6245 --- /dev/null +++ b/miniprogram_npm/crypto-js/enc-utf16.js @@ -0,0 +1,149 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * UTF-16 BE encoding strategy. + */ + var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { + /** + * Converts a word array to a UTF-16 BE string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-16 BE string. + * + * @static + * + * @example + * + * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var utf16Chars = []; + for (var i = 0; i < sigBytes; i += 2) { + var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; + utf16Chars.push(String.fromCharCode(codePoint)); + } + + return utf16Chars.join(''); + }, + + /** + * Converts a UTF-16 BE string to a word array. + * + * @param {string} utf16Str The UTF-16 BE string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); + */ + parse: function (utf16Str) { + // Shortcut + var utf16StrLength = utf16Str.length; + + // Convert + var words = []; + for (var i = 0; i < utf16StrLength; i++) { + words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); + } + + return WordArray.create(words, utf16StrLength * 2); + } + }; + + /** + * UTF-16 LE encoding strategy. + */ + C_enc.Utf16LE = { + /** + * Converts a word array to a UTF-16 LE string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-16 LE string. + * + * @static + * + * @example + * + * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var utf16Chars = []; + for (var i = 0; i < sigBytes; i += 2) { + var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); + utf16Chars.push(String.fromCharCode(codePoint)); + } + + return utf16Chars.join(''); + }, + + /** + * Converts a UTF-16 LE string to a word array. + * + * @param {string} utf16Str The UTF-16 LE string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); + */ + parse: function (utf16Str) { + // Shortcut + var utf16StrLength = utf16Str.length; + + // Convert + var words = []; + for (var i = 0; i < utf16StrLength; i++) { + words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); + } + + return WordArray.create(words, utf16StrLength * 2); + } + }; + + function swapEndian(word) { + return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); + } + }()); + + + return CryptoJS.enc.Utf16; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/enc-utf8.js b/miniprogram_npm/crypto-js/enc-utf8.js new file mode 100644 index 0000000..e7a251d --- /dev/null +++ b/miniprogram_npm/crypto-js/enc-utf8.js @@ -0,0 +1,18 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.enc.Utf8; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/evpkdf.js b/miniprogram_npm/crypto-js/evpkdf.js new file mode 100644 index 0000000..578974a --- /dev/null +++ b/miniprogram_npm/crypto-js/evpkdf.js @@ -0,0 +1,134 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./sha1", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var MD5 = C_algo.MD5; + + /** + * This key derivation function is meant to conform with EVP_BytesToKey. + * www.openssl.org/docs/crypto/EVP_BytesToKey.html + */ + var EvpKDF = C_algo.EvpKDF = Base.extend({ + /** + * Configuration options. + * + * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) + * @property {Hasher} hasher The hash algorithm to use. Default: MD5 + * @property {number} iterations The number of iterations to perform. Default: 1 + */ + cfg: Base.extend({ + keySize: 128/32, + hasher: MD5, + iterations: 1 + }), + + /** + * Initializes a newly created key derivation function. + * + * @param {Object} cfg (Optional) The configuration options to use for the derivation. + * + * @example + * + * var kdf = CryptoJS.algo.EvpKDF.create(); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); + */ + init: function (cfg) { + this.cfg = this.cfg.extend(cfg); + }, + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * + * @return {WordArray} The derived key. + * + * @example + * + * var key = kdf.compute(password, salt); + */ + compute: function (password, salt) { + var block; + + // Shortcut + var cfg = this.cfg; + + // Init hasher + var hasher = cfg.hasher.create(); + + // Initial values + var derivedKey = WordArray.create(); + + // Shortcuts + var derivedKeyWords = derivedKey.words; + var keySize = cfg.keySize; + var iterations = cfg.iterations; + + // Generate key + while (derivedKeyWords.length < keySize) { + if (block) { + hasher.update(block); + } + block = hasher.update(password).finalize(salt); + hasher.reset(); + + // Iterations + for (var i = 1; i < iterations; i++) { + block = hasher.finalize(block); + hasher.reset(); + } + + derivedKey.concat(block); + } + derivedKey.sigBytes = keySize * 4; + + return derivedKey; + } + }); + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * @param {Object} cfg (Optional) The configuration options to use for this computation. + * + * @return {WordArray} The derived key. + * + * @static + * + * @example + * + * var key = CryptoJS.EvpKDF(password, salt); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); + */ + C.EvpKDF = function (password, salt, cfg) { + return EvpKDF.create(cfg).compute(password, salt); + }; + }()); + + + return CryptoJS.EvpKDF; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/format-hex.js b/miniprogram_npm/crypto-js/format-hex.js new file mode 100644 index 0000000..2e9a861 --- /dev/null +++ b/miniprogram_npm/crypto-js/format-hex.js @@ -0,0 +1,66 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var CipherParams = C_lib.CipherParams; + var C_enc = C.enc; + var Hex = C_enc.Hex; + var C_format = C.format; + + var HexFormatter = C_format.Hex = { + /** + * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. + * + * @param {CipherParams} cipherParams The cipher params object. + * + * @return {string} The hexadecimally encoded string. + * + * @static + * + * @example + * + * var hexString = CryptoJS.format.Hex.stringify(cipherParams); + */ + stringify: function (cipherParams) { + return cipherParams.ciphertext.toString(Hex); + }, + + /** + * Converts a hexadecimally encoded ciphertext string to a cipher params object. + * + * @param {string} input The hexadecimally encoded string. + * + * @return {CipherParams} The cipher params object. + * + * @static + * + * @example + * + * var cipherParams = CryptoJS.format.Hex.parse(hexString); + */ + parse: function (input) { + var ciphertext = Hex.parse(input); + return CipherParams.create({ ciphertext: ciphertext }); + } + }; + }()); + + + return CryptoJS.format.Hex; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/format-openssl.js b/miniprogram_npm/crypto-js/format-openssl.js new file mode 100644 index 0000000..3373edc --- /dev/null +++ b/miniprogram_npm/crypto-js/format-openssl.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.format.OpenSSL; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/hmac-md5.js b/miniprogram_npm/crypto-js/hmac-md5.js new file mode 100644 index 0000000..ad7a90a --- /dev/null +++ b/miniprogram_npm/crypto-js/hmac-md5.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./md5"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./md5", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacMD5; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/hmac-ripemd160.js b/miniprogram_npm/crypto-js/hmac-ripemd160.js new file mode 100644 index 0000000..73d55a7 --- /dev/null +++ b/miniprogram_npm/crypto-js/hmac-ripemd160.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./ripemd160"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./ripemd160", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacRIPEMD160; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/hmac-sha1.js b/miniprogram_npm/crypto-js/hmac-sha1.js new file mode 100644 index 0000000..0b570cb --- /dev/null +++ b/miniprogram_npm/crypto-js/hmac-sha1.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./sha1", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacSHA1; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/hmac-sha224.js b/miniprogram_npm/crypto-js/hmac-sha224.js new file mode 100644 index 0000000..3778863 --- /dev/null +++ b/miniprogram_npm/crypto-js/hmac-sha224.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./sha256"), require("./sha224"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./sha256", "./sha224", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacSHA224; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/hmac-sha256.js b/miniprogram_npm/crypto-js/hmac-sha256.js new file mode 100644 index 0000000..33b0c9f --- /dev/null +++ b/miniprogram_npm/crypto-js/hmac-sha256.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./sha256"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./sha256", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacSHA256; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/hmac-sha3.js b/miniprogram_npm/crypto-js/hmac-sha3.js new file mode 100644 index 0000000..1248804 --- /dev/null +++ b/miniprogram_npm/crypto-js/hmac-sha3.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha3"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./x64-core", "./sha3", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacSHA3; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/hmac-sha384.js b/miniprogram_npm/crypto-js/hmac-sha384.js new file mode 100644 index 0000000..0036e2b --- /dev/null +++ b/miniprogram_npm/crypto-js/hmac-sha384.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha512"), require("./sha384"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./x64-core", "./sha512", "./sha384", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacSHA384; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/hmac-sha512.js b/miniprogram_npm/crypto-js/hmac-sha512.js new file mode 100644 index 0000000..c1005b6 --- /dev/null +++ b/miniprogram_npm/crypto-js/hmac-sha512.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha512"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./x64-core", "./sha512", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacSHA512; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/hmac.js b/miniprogram_npm/crypto-js/hmac.js new file mode 100644 index 0000000..8c09851 --- /dev/null +++ b/miniprogram_npm/crypto-js/hmac.js @@ -0,0 +1,143 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var C_enc = C.enc; + var Utf8 = C_enc.Utf8; + var C_algo = C.algo; + + /** + * HMAC algorithm. + */ + var HMAC = C_algo.HMAC = Base.extend({ + /** + * Initializes a newly created HMAC. + * + * @param {Hasher} hasher The hash algorithm to use. + * @param {WordArray|string} key The secret key. + * + * @example + * + * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); + */ + init: function (hasher, key) { + // Init hasher + hasher = this._hasher = new hasher.init(); + + // Convert string to WordArray, else assume WordArray already + if (typeof key == 'string') { + key = Utf8.parse(key); + } + + // Shortcuts + var hasherBlockSize = hasher.blockSize; + var hasherBlockSizeBytes = hasherBlockSize * 4; + + // Allow arbitrary length keys + if (key.sigBytes > hasherBlockSizeBytes) { + key = hasher.finalize(key); + } + + // Clamp excess bits + key.clamp(); + + // Clone key for inner and outer pads + var oKey = this._oKey = key.clone(); + var iKey = this._iKey = key.clone(); + + // Shortcuts + var oKeyWords = oKey.words; + var iKeyWords = iKey.words; + + // XOR keys with pad constants + for (var i = 0; i < hasherBlockSize; i++) { + oKeyWords[i] ^= 0x5c5c5c5c; + iKeyWords[i] ^= 0x36363636; + } + oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; + + // Set initial values + this.reset(); + }, + + /** + * Resets this HMAC to its initial state. + * + * @example + * + * hmacHasher.reset(); + */ + reset: function () { + // Shortcut + var hasher = this._hasher; + + // Reset + hasher.reset(); + hasher.update(this._iKey); + }, + + /** + * Updates this HMAC with a message. + * + * @param {WordArray|string} messageUpdate The message to append. + * + * @return {HMAC} This HMAC instance. + * + * @example + * + * hmacHasher.update('message'); + * hmacHasher.update(wordArray); + */ + update: function (messageUpdate) { + this._hasher.update(messageUpdate); + + // Chainable + return this; + }, + + /** + * Finalizes the HMAC computation. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} messageUpdate (Optional) A final message update. + * + * @return {WordArray} The HMAC. + * + * @example + * + * var hmac = hmacHasher.finalize(); + * var hmac = hmacHasher.finalize('message'); + * var hmac = hmacHasher.finalize(wordArray); + */ + finalize: function (messageUpdate) { + // Shortcut + var hasher = this._hasher; + + // Compute HMAC + var innerHash = hasher.finalize(messageUpdate); + hasher.reset(); + var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); + + return hmac; + } + }); + }()); + + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/index.js b/miniprogram_npm/crypto-js/index.js new file mode 100644 index 0000000..7235391 --- /dev/null +++ b/miniprogram_npm/crypto-js/index.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./x64-core"), require("./lib-typedarrays"), require("./enc-utf16"), require("./enc-base64"), require("./enc-base64url"), require("./md5"), require("./sha1"), require("./sha256"), require("./sha224"), require("./sha512"), require("./sha384"), require("./sha3"), require("./ripemd160"), require("./hmac"), require("./pbkdf2"), require("./evpkdf"), require("./cipher-core"), require("./mode-cfb"), require("./mode-ctr"), require("./mode-ctr-gladman"), require("./mode-ofb"), require("./mode-ecb"), require("./pad-ansix923"), require("./pad-iso10126"), require("./pad-iso97971"), require("./pad-zeropadding"), require("./pad-nopadding"), require("./format-hex"), require("./aes"), require("./tripledes"), require("./rc4"), require("./rabbit"), require("./rabbit-legacy")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./enc-base64url", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory); + } + else { + // Global (browser) + root.CryptoJS = factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/lib-typedarrays.js b/miniprogram_npm/crypto-js/lib-typedarrays.js new file mode 100644 index 0000000..264b210 --- /dev/null +++ b/miniprogram_npm/crypto-js/lib-typedarrays.js @@ -0,0 +1,76 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Check if typed arrays are supported + if (typeof ArrayBuffer != 'function') { + return; + } + + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + + // Reference original init + var superInit = WordArray.init; + + // Augment WordArray.init to handle typed arrays + var subInit = WordArray.init = function (typedArray) { + // Convert buffers to uint8 + if (typedArray instanceof ArrayBuffer) { + typedArray = new Uint8Array(typedArray); + } + + // Convert other array views to uint8 + if ( + typedArray instanceof Int8Array || + (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || + typedArray instanceof Int16Array || + typedArray instanceof Uint16Array || + typedArray instanceof Int32Array || + typedArray instanceof Uint32Array || + typedArray instanceof Float32Array || + typedArray instanceof Float64Array + ) { + typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); + } + + // Handle Uint8Array + if (typedArray instanceof Uint8Array) { + // Shortcut + var typedArrayByteLength = typedArray.byteLength; + + // Extract bytes + var words = []; + for (var i = 0; i < typedArrayByteLength; i++) { + words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); + } + + // Initialize this word array + superInit.call(this, words, typedArrayByteLength); + } else { + // Else call normal init + superInit.apply(this, arguments); + } + }; + + subInit.prototype = WordArray; + }()); + + + return CryptoJS.lib.WordArray; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/md5.js b/miniprogram_npm/crypto-js/md5.js new file mode 100644 index 0000000..12b0fdd --- /dev/null +++ b/miniprogram_npm/crypto-js/md5.js @@ -0,0 +1,268 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Constants table + var T = []; + + // Compute constants + (function () { + for (var i = 0; i < 64; i++) { + T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; + } + }()); + + /** + * MD5 hash algorithm. + */ + var MD5 = C_algo.MD5 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0x67452301, 0xefcdab89, + 0x98badcfe, 0x10325476 + ]); + }, + + _doProcessBlock: function (M, offset) { + // Swap endian + for (var i = 0; i < 16; i++) { + // Shortcuts + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } + + // Shortcuts + var H = this._hash.words; + + var M_offset_0 = M[offset + 0]; + var M_offset_1 = M[offset + 1]; + var M_offset_2 = M[offset + 2]; + var M_offset_3 = M[offset + 3]; + var M_offset_4 = M[offset + 4]; + var M_offset_5 = M[offset + 5]; + var M_offset_6 = M[offset + 6]; + var M_offset_7 = M[offset + 7]; + var M_offset_8 = M[offset + 8]; + var M_offset_9 = M[offset + 9]; + var M_offset_10 = M[offset + 10]; + var M_offset_11 = M[offset + 11]; + var M_offset_12 = M[offset + 12]; + var M_offset_13 = M[offset + 13]; + var M_offset_14 = M[offset + 14]; + var M_offset_15 = M[offset + 15]; + + // Working varialbes + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + + // Computation + a = FF(a, b, c, d, M_offset_0, 7, T[0]); + d = FF(d, a, b, c, M_offset_1, 12, T[1]); + c = FF(c, d, a, b, M_offset_2, 17, T[2]); + b = FF(b, c, d, a, M_offset_3, 22, T[3]); + a = FF(a, b, c, d, M_offset_4, 7, T[4]); + d = FF(d, a, b, c, M_offset_5, 12, T[5]); + c = FF(c, d, a, b, M_offset_6, 17, T[6]); + b = FF(b, c, d, a, M_offset_7, 22, T[7]); + a = FF(a, b, c, d, M_offset_8, 7, T[8]); + d = FF(d, a, b, c, M_offset_9, 12, T[9]); + c = FF(c, d, a, b, M_offset_10, 17, T[10]); + b = FF(b, c, d, a, M_offset_11, 22, T[11]); + a = FF(a, b, c, d, M_offset_12, 7, T[12]); + d = FF(d, a, b, c, M_offset_13, 12, T[13]); + c = FF(c, d, a, b, M_offset_14, 17, T[14]); + b = FF(b, c, d, a, M_offset_15, 22, T[15]); + + a = GG(a, b, c, d, M_offset_1, 5, T[16]); + d = GG(d, a, b, c, M_offset_6, 9, T[17]); + c = GG(c, d, a, b, M_offset_11, 14, T[18]); + b = GG(b, c, d, a, M_offset_0, 20, T[19]); + a = GG(a, b, c, d, M_offset_5, 5, T[20]); + d = GG(d, a, b, c, M_offset_10, 9, T[21]); + c = GG(c, d, a, b, M_offset_15, 14, T[22]); + b = GG(b, c, d, a, M_offset_4, 20, T[23]); + a = GG(a, b, c, d, M_offset_9, 5, T[24]); + d = GG(d, a, b, c, M_offset_14, 9, T[25]); + c = GG(c, d, a, b, M_offset_3, 14, T[26]); + b = GG(b, c, d, a, M_offset_8, 20, T[27]); + a = GG(a, b, c, d, M_offset_13, 5, T[28]); + d = GG(d, a, b, c, M_offset_2, 9, T[29]); + c = GG(c, d, a, b, M_offset_7, 14, T[30]); + b = GG(b, c, d, a, M_offset_12, 20, T[31]); + + a = HH(a, b, c, d, M_offset_5, 4, T[32]); + d = HH(d, a, b, c, M_offset_8, 11, T[33]); + c = HH(c, d, a, b, M_offset_11, 16, T[34]); + b = HH(b, c, d, a, M_offset_14, 23, T[35]); + a = HH(a, b, c, d, M_offset_1, 4, T[36]); + d = HH(d, a, b, c, M_offset_4, 11, T[37]); + c = HH(c, d, a, b, M_offset_7, 16, T[38]); + b = HH(b, c, d, a, M_offset_10, 23, T[39]); + a = HH(a, b, c, d, M_offset_13, 4, T[40]); + d = HH(d, a, b, c, M_offset_0, 11, T[41]); + c = HH(c, d, a, b, M_offset_3, 16, T[42]); + b = HH(b, c, d, a, M_offset_6, 23, T[43]); + a = HH(a, b, c, d, M_offset_9, 4, T[44]); + d = HH(d, a, b, c, M_offset_12, 11, T[45]); + c = HH(c, d, a, b, M_offset_15, 16, T[46]); + b = HH(b, c, d, a, M_offset_2, 23, T[47]); + + a = II(a, b, c, d, M_offset_0, 6, T[48]); + d = II(d, a, b, c, M_offset_7, 10, T[49]); + c = II(c, d, a, b, M_offset_14, 15, T[50]); + b = II(b, c, d, a, M_offset_5, 21, T[51]); + a = II(a, b, c, d, M_offset_12, 6, T[52]); + d = II(d, a, b, c, M_offset_3, 10, T[53]); + c = II(c, d, a, b, M_offset_10, 15, T[54]); + b = II(b, c, d, a, M_offset_1, 21, T[55]); + a = II(a, b, c, d, M_offset_8, 6, T[56]); + d = II(d, a, b, c, M_offset_15, 10, T[57]); + c = II(c, d, a, b, M_offset_6, 15, T[58]); + b = II(b, c, d, a, M_offset_13, 21, T[59]); + a = II(a, b, c, d, M_offset_4, 6, T[60]); + d = II(d, a, b, c, M_offset_11, 10, T[61]); + c = II(c, d, a, b, M_offset_2, 15, T[62]); + b = II(b, c, d, a, M_offset_9, 21, T[63]); + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + + var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); + var nBitsTotalL = nBitsTotal; + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( + (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | + (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) + ); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | + (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) + ); + + data.sigBytes = (dataWords.length + 1) * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var hash = this._hash; + var H = hash.words; + + // Swap endian + for (var i = 0; i < 4; i++) { + // Shortcut + var H_i = H[i]; + + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + function FF(a, b, c, d, x, s, t) { + var n = a + ((b & c) | (~b & d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function GG(a, b, c, d, x, s, t) { + var n = a + ((b & d) | (c & ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function HH(a, b, c, d, x, s, t) { + var n = a + (b ^ c ^ d) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function II(a, b, c, d, x, s, t) { + var n = a + (c ^ (b | ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.MD5('message'); + * var hash = CryptoJS.MD5(wordArray); + */ + C.MD5 = Hasher._createHelper(MD5); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacMD5(message, key); + */ + C.HmacMD5 = Hasher._createHmacHelper(MD5); + }(Math)); + + + return CryptoJS.MD5; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/mode-cfb.js b/miniprogram_npm/crypto-js/mode-cfb.js new file mode 100644 index 0000000..444c9cb --- /dev/null +++ b/miniprogram_npm/crypto-js/mode-cfb.js @@ -0,0 +1,80 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * Cipher Feedback block mode. + */ + CryptoJS.mode.CFB = (function () { + var CFB = CryptoJS.lib.BlockCipherMode.extend(); + + CFB.Encryptor = CFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); + + // Remember this block to use with next block + this._prevBlock = words.slice(offset, offset + blockSize); + } + }); + + CFB.Decryptor = CFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // Remember this block to use with next block + var thisBlock = words.slice(offset, offset + blockSize); + + generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); + + // This block becomes the previous block + this._prevBlock = thisBlock; + } + }); + + function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { + var keystream; + + // Shortcut + var iv = this._iv; + + // Generate keystream + if (iv) { + keystream = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } else { + keystream = this._prevBlock; + } + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + + return CFB; + }()); + + + return CryptoJS.mode.CFB; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/mode-ctr-gladman.js b/miniprogram_npm/crypto-js/mode-ctr-gladman.js new file mode 100644 index 0000000..bbc5687 --- /dev/null +++ b/miniprogram_npm/crypto-js/mode-ctr-gladman.js @@ -0,0 +1,116 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** @preserve + * Counter block mode compatible with Dr Brian Gladman fileenc.c + * derived from CryptoJS.mode.CTR + * Jan Hruby jhruby.web@gmail.com + */ + CryptoJS.mode.CTRGladman = (function () { + var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); + + function incWord(word) + { + if (((word >> 24) & 0xff) === 0xff) { //overflow + var b1 = (word >> 16)&0xff; + var b2 = (word >> 8)&0xff; + var b3 = word & 0xff; + + if (b1 === 0xff) // overflow b1 + { + b1 = 0; + if (b2 === 0xff) + { + b2 = 0; + if (b3 === 0xff) + { + b3 = 0; + } + else + { + ++b3; + } + } + else + { + ++b2; + } + } + else + { + ++b1; + } + + word = 0; + word += (b1 << 16); + word += (b2 << 8); + word += b3; + } + else + { + word += (0x01 << 24); + } + return word; + } + + function incCounter(counter) + { + if ((counter[0] = incWord(counter[0])) === 0) + { + // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 + counter[1] = incWord(counter[1]); + } + return counter; + } + + var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var counter = this._counter; + + // Generate keystream + if (iv) { + counter = this._counter = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + + incCounter(counter); + + var keystream = counter.slice(0); + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + CTRGladman.Decryptor = Encryptor; + + return CTRGladman; + }()); + + + + + return CryptoJS.mode.CTRGladman; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/mode-ctr.js b/miniprogram_npm/crypto-js/mode-ctr.js new file mode 100644 index 0000000..c3d470a --- /dev/null +++ b/miniprogram_npm/crypto-js/mode-ctr.js @@ -0,0 +1,58 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * Counter block mode. + */ + CryptoJS.mode.CTR = (function () { + var CTR = CryptoJS.lib.BlockCipherMode.extend(); + + var Encryptor = CTR.Encryptor = CTR.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var counter = this._counter; + + // Generate keystream + if (iv) { + counter = this._counter = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + var keystream = counter.slice(0); + cipher.encryptBlock(keystream, 0); + + // Increment counter + counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + CTR.Decryptor = Encryptor; + + return CTR; + }()); + + + return CryptoJS.mode.CTR; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/mode-ecb.js b/miniprogram_npm/crypto-js/mode-ecb.js new file mode 100644 index 0000000..ff06921 --- /dev/null +++ b/miniprogram_npm/crypto-js/mode-ecb.js @@ -0,0 +1,40 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * Electronic Codebook block mode. + */ + CryptoJS.mode.ECB = (function () { + var ECB = CryptoJS.lib.BlockCipherMode.extend(); + + ECB.Encryptor = ECB.extend({ + processBlock: function (words, offset) { + this._cipher.encryptBlock(words, offset); + } + }); + + ECB.Decryptor = ECB.extend({ + processBlock: function (words, offset) { + this._cipher.decryptBlock(words, offset); + } + }); + + return ECB; + }()); + + + return CryptoJS.mode.ECB; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/mode-ofb.js b/miniprogram_npm/crypto-js/mode-ofb.js new file mode 100644 index 0000000..c01314c --- /dev/null +++ b/miniprogram_npm/crypto-js/mode-ofb.js @@ -0,0 +1,54 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * Output Feedback block mode. + */ + CryptoJS.mode.OFB = (function () { + var OFB = CryptoJS.lib.BlockCipherMode.extend(); + + var Encryptor = OFB.Encryptor = OFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var keystream = this._keystream; + + // Generate keystream + if (iv) { + keystream = this._keystream = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + OFB.Decryptor = Encryptor; + + return OFB; + }()); + + + return CryptoJS.mode.OFB; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/package.json b/miniprogram_npm/crypto-js/package.json new file mode 100644 index 0000000..3ebde34 --- /dev/null +++ b/miniprogram_npm/crypto-js/package.json @@ -0,0 +1,45 @@ +{ + "name": "crypto-js", + "version": "4.1.1", + "description": "JavaScript library of crypto standards.", + "license": "MIT", + "author": { + "name": "Evan Vosberg", + "url": "http://github.com/evanvosberg" + }, + "homepage": "http://github.com/brix/crypto-js", + "repository": { + "type": "git", + "url": "http://github.com/brix/crypto-js.git" + }, + "keywords": [ + "security", + "crypto", + "Hash", + "MD5", + "SHA1", + "SHA-1", + "SHA256", + "SHA-256", + "RC4", + "Rabbit", + "AES", + "DES", + "PBKDF2", + "HMAC", + "OFB", + "CFB", + "CTR", + "CBC", + "Base64", + "Base64url" + ], + "main": "index.js", + "dependencies": {}, + "browser": { + "crypto": false + }, + "__npminstall_done": "Mon Oct 10 2022 16:06:55 GMT+0800 (中国标准时间)", + "_from": "crypto-js@4.1.1", + "_resolved": "https://registry.npmmirror.com/crypto-js/-/crypto-js-4.1.1.tgz" +} \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/pad-ansix923.js b/miniprogram_npm/crypto-js/pad-ansix923.js new file mode 100644 index 0000000..f01f21e --- /dev/null +++ b/miniprogram_npm/crypto-js/pad-ansix923.js @@ -0,0 +1,49 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * ANSI X.923 padding strategy. + */ + CryptoJS.pad.AnsiX923 = { + pad: function (data, blockSize) { + // Shortcuts + var dataSigBytes = data.sigBytes; + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; + + // Compute last byte position + var lastBytePos = dataSigBytes + nPaddingBytes - 1; + + // Pad + data.clamp(); + data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); + data.sigBytes += nPaddingBytes; + }, + + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + + return CryptoJS.pad.Ansix923; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/pad-iso10126.js b/miniprogram_npm/crypto-js/pad-iso10126.js new file mode 100644 index 0000000..6e2aefd --- /dev/null +++ b/miniprogram_npm/crypto-js/pad-iso10126.js @@ -0,0 +1,44 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * ISO 10126 padding strategy. + */ + CryptoJS.pad.Iso10126 = { + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; + + // Pad + data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). + concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); + }, + + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + + return CryptoJS.pad.Iso10126; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/pad-iso97971.js b/miniprogram_npm/crypto-js/pad-iso97971.js new file mode 100644 index 0000000..41049b4 --- /dev/null +++ b/miniprogram_npm/crypto-js/pad-iso97971.js @@ -0,0 +1,40 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * ISO/IEC 9797-1 Padding Method 2. + */ + CryptoJS.pad.Iso97971 = { + pad: function (data, blockSize) { + // Add 0x80 byte + data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); + + // Zero pad the rest + CryptoJS.pad.ZeroPadding.pad(data, blockSize); + }, + + unpad: function (data) { + // Remove zero padding + CryptoJS.pad.ZeroPadding.unpad(data); + + // Remove one more byte -- the 0x80 byte + data.sigBytes--; + } + }; + + + return CryptoJS.pad.Iso97971; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/pad-nopadding.js b/miniprogram_npm/crypto-js/pad-nopadding.js new file mode 100644 index 0000000..c7787c9 --- /dev/null +++ b/miniprogram_npm/crypto-js/pad-nopadding.js @@ -0,0 +1,30 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * A noop padding strategy. + */ + CryptoJS.pad.NoPadding = { + pad: function () { + }, + + unpad: function () { + } + }; + + + return CryptoJS.pad.NoPadding; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/pad-pkcs7.js b/miniprogram_npm/crypto-js/pad-pkcs7.js new file mode 100644 index 0000000..3555168 --- /dev/null +++ b/miniprogram_npm/crypto-js/pad-pkcs7.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.pad.Pkcs7; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/pad-zeropadding.js b/miniprogram_npm/crypto-js/pad-zeropadding.js new file mode 100644 index 0000000..a1a459e --- /dev/null +++ b/miniprogram_npm/crypto-js/pad-zeropadding.js @@ -0,0 +1,47 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * Zero padding strategy. + */ + CryptoJS.pad.ZeroPadding = { + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Pad + data.clamp(); + data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); + }, + + unpad: function (data) { + // Shortcut + var dataWords = data.words; + + // Unpad + var i = data.sigBytes - 1; + for (var i = data.sigBytes - 1; i >= 0; i--) { + if (((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { + data.sigBytes = i + 1; + break; + } + } + } + }; + + + return CryptoJS.pad.ZeroPadding; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/pbkdf2.js b/miniprogram_npm/crypto-js/pbkdf2.js new file mode 100644 index 0000000..1258251 --- /dev/null +++ b/miniprogram_npm/crypto-js/pbkdf2.js @@ -0,0 +1,145 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./sha1", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var SHA1 = C_algo.SHA1; + var HMAC = C_algo.HMAC; + + /** + * Password-Based Key Derivation Function 2 algorithm. + */ + var PBKDF2 = C_algo.PBKDF2 = Base.extend({ + /** + * Configuration options. + * + * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) + * @property {Hasher} hasher The hasher to use. Default: SHA1 + * @property {number} iterations The number of iterations to perform. Default: 1 + */ + cfg: Base.extend({ + keySize: 128/32, + hasher: SHA1, + iterations: 1 + }), + + /** + * Initializes a newly created key derivation function. + * + * @param {Object} cfg (Optional) The configuration options to use for the derivation. + * + * @example + * + * var kdf = CryptoJS.algo.PBKDF2.create(); + * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); + * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); + */ + init: function (cfg) { + this.cfg = this.cfg.extend(cfg); + }, + + /** + * Computes the Password-Based Key Derivation Function 2. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * + * @return {WordArray} The derived key. + * + * @example + * + * var key = kdf.compute(password, salt); + */ + compute: function (password, salt) { + // Shortcut + var cfg = this.cfg; + + // Init HMAC + var hmac = HMAC.create(cfg.hasher, password); + + // Initial values + var derivedKey = WordArray.create(); + var blockIndex = WordArray.create([0x00000001]); + + // Shortcuts + var derivedKeyWords = derivedKey.words; + var blockIndexWords = blockIndex.words; + var keySize = cfg.keySize; + var iterations = cfg.iterations; + + // Generate key + while (derivedKeyWords.length < keySize) { + var block = hmac.update(salt).finalize(blockIndex); + hmac.reset(); + + // Shortcuts + var blockWords = block.words; + var blockWordsLength = blockWords.length; + + // Iterations + var intermediate = block; + for (var i = 1; i < iterations; i++) { + intermediate = hmac.finalize(intermediate); + hmac.reset(); + + // Shortcut + var intermediateWords = intermediate.words; + + // XOR intermediate with block + for (var j = 0; j < blockWordsLength; j++) { + blockWords[j] ^= intermediateWords[j]; + } + } + + derivedKey.concat(block); + blockIndexWords[0]++; + } + derivedKey.sigBytes = keySize * 4; + + return derivedKey; + } + }); + + /** + * Computes the Password-Based Key Derivation Function 2. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * @param {Object} cfg (Optional) The configuration options to use for this computation. + * + * @return {WordArray} The derived key. + * + * @static + * + * @example + * + * var key = CryptoJS.PBKDF2(password, salt); + * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); + * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); + */ + C.PBKDF2 = function (password, salt, cfg) { + return PBKDF2.create(cfg).compute(password, salt); + }; + }()); + + + return CryptoJS.PBKDF2; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/rabbit-legacy.js b/miniprogram_npm/crypto-js/rabbit-legacy.js new file mode 100644 index 0000000..e118b6b --- /dev/null +++ b/miniprogram_npm/crypto-js/rabbit-legacy.js @@ -0,0 +1,190 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + // Reusable objects + var S = []; + var C_ = []; + var G = []; + + /** + * Rabbit stream cipher algorithm. + * + * This is a legacy version that neglected to convert the key to little-endian. + * This error doesn't affect the cipher's security, + * but it does affect its compatibility with other implementations. + */ + var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var K = this._key.words; + var iv = this.cfg.iv; + + // Generate initial state values + var X = this._X = [ + K[0], (K[3] << 16) | (K[2] >>> 16), + K[1], (K[0] << 16) | (K[3] >>> 16), + K[2], (K[1] << 16) | (K[0] >>> 16), + K[3], (K[2] << 16) | (K[1] >>> 16) + ]; + + // Generate initial counter values + var C = this._C = [ + (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), + (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), + (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), + (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) + ]; + + // Carry bit + this._b = 0; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + + // Modify the counters + for (var i = 0; i < 8; i++) { + C[i] ^= X[(i + 4) & 7]; + } + + // IV setup + if (iv) { + // Shortcuts + var IV = iv.words; + var IV_0 = IV[0]; + var IV_1 = IV[1]; + + // Generate four subvectors + var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); + var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); + var i1 = (i0 >>> 16) | (i2 & 0xffff0000); + var i3 = (i2 << 16) | (i0 & 0x0000ffff); + + // Modify counter values + C[0] ^= i0; + C[1] ^= i1; + C[2] ^= i2; + C[3] ^= i3; + C[4] ^= i0; + C[5] ^= i1; + C[6] ^= i2; + C[7] ^= i3; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + } + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var X = this._X; + + // Iterate the system + nextState.call(this); + + // Generate four keystream words + S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); + S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); + S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); + S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); + + for (var i = 0; i < 4; i++) { + // Swap endian + S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | + (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); + + // Encrypt + M[offset + i] ^= S[i]; + } + }, + + blockSize: 128/32, + + ivSize: 64/32 + }); + + function nextState() { + // Shortcuts + var X = this._X; + var C = this._C; + + // Save old counter values + for (var i = 0; i < 8; i++) { + C_[i] = C[i]; + } + + // Calculate new counter values + C[0] = (C[0] + 0x4d34d34d + this._b) | 0; + C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; + C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; + C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; + C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; + C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; + C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; + C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; + this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; + + // Calculate the g-values + for (var i = 0; i < 8; i++) { + var gx = X[i] + C[i]; + + // Construct high and low argument for squaring + var ga = gx & 0xffff; + var gb = gx >>> 16; + + // Calculate high and low result of squaring + var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; + var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); + + // High XOR low + G[i] = gh ^ gl; + } + + // Calculate new state values + X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; + X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; + X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; + X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; + X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; + X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; + X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; + X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); + */ + C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); + }()); + + + return CryptoJS.RabbitLegacy; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/rabbit.js b/miniprogram_npm/crypto-js/rabbit.js new file mode 100644 index 0000000..1b06833 --- /dev/null +++ b/miniprogram_npm/crypto-js/rabbit.js @@ -0,0 +1,192 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + // Reusable objects + var S = []; + var C_ = []; + var G = []; + + /** + * Rabbit stream cipher algorithm + */ + var Rabbit = C_algo.Rabbit = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var K = this._key.words; + var iv = this.cfg.iv; + + // Swap endian + for (var i = 0; i < 4; i++) { + K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | + (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); + } + + // Generate initial state values + var X = this._X = [ + K[0], (K[3] << 16) | (K[2] >>> 16), + K[1], (K[0] << 16) | (K[3] >>> 16), + K[2], (K[1] << 16) | (K[0] >>> 16), + K[3], (K[2] << 16) | (K[1] >>> 16) + ]; + + // Generate initial counter values + var C = this._C = [ + (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), + (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), + (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), + (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) + ]; + + // Carry bit + this._b = 0; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + + // Modify the counters + for (var i = 0; i < 8; i++) { + C[i] ^= X[(i + 4) & 7]; + } + + // IV setup + if (iv) { + // Shortcuts + var IV = iv.words; + var IV_0 = IV[0]; + var IV_1 = IV[1]; + + // Generate four subvectors + var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); + var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); + var i1 = (i0 >>> 16) | (i2 & 0xffff0000); + var i3 = (i2 << 16) | (i0 & 0x0000ffff); + + // Modify counter values + C[0] ^= i0; + C[1] ^= i1; + C[2] ^= i2; + C[3] ^= i3; + C[4] ^= i0; + C[5] ^= i1; + C[6] ^= i2; + C[7] ^= i3; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + } + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var X = this._X; + + // Iterate the system + nextState.call(this); + + // Generate four keystream words + S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); + S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); + S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); + S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); + + for (var i = 0; i < 4; i++) { + // Swap endian + S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | + (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); + + // Encrypt + M[offset + i] ^= S[i]; + } + }, + + blockSize: 128/32, + + ivSize: 64/32 + }); + + function nextState() { + // Shortcuts + var X = this._X; + var C = this._C; + + // Save old counter values + for (var i = 0; i < 8; i++) { + C_[i] = C[i]; + } + + // Calculate new counter values + C[0] = (C[0] + 0x4d34d34d + this._b) | 0; + C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; + C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; + C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; + C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; + C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; + C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; + C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; + this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; + + // Calculate the g-values + for (var i = 0; i < 8; i++) { + var gx = X[i] + C[i]; + + // Construct high and low argument for squaring + var ga = gx & 0xffff; + var gb = gx >>> 16; + + // Calculate high and low result of squaring + var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; + var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); + + // High XOR low + G[i] = gh ^ gl; + } + + // Calculate new state values + X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; + X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; + X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; + X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; + X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; + X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; + X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; + X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); + * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); + */ + C.Rabbit = StreamCipher._createHelper(Rabbit); + }()); + + + return CryptoJS.Rabbit; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/rc4.js b/miniprogram_npm/crypto-js/rc4.js new file mode 100644 index 0000000..0e4bdff --- /dev/null +++ b/miniprogram_npm/crypto-js/rc4.js @@ -0,0 +1,139 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + /** + * RC4 stream cipher algorithm. + */ + var RC4 = C_algo.RC4 = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + var keySigBytes = key.sigBytes; + + // Init sbox + var S = this._S = []; + for (var i = 0; i < 256; i++) { + S[i] = i; + } + + // Key setup + for (var i = 0, j = 0; i < 256; i++) { + var keyByteIndex = i % keySigBytes; + var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; + + j = (j + S[i] + keyByte) % 256; + + // Swap + var t = S[i]; + S[i] = S[j]; + S[j] = t; + } + + // Counters + this._i = this._j = 0; + }, + + _doProcessBlock: function (M, offset) { + M[offset] ^= generateKeystreamWord.call(this); + }, + + keySize: 256/32, + + ivSize: 0 + }); + + function generateKeystreamWord() { + // Shortcuts + var S = this._S; + var i = this._i; + var j = this._j; + + // Generate keystream word + var keystreamWord = 0; + for (var n = 0; n < 4; n++) { + i = (i + 1) % 256; + j = (j + S[i]) % 256; + + // Swap + var t = S[i]; + S[i] = S[j]; + S[j] = t; + + keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); + } + + // Update counters + this._i = i; + this._j = j; + + return keystreamWord; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); + */ + C.RC4 = StreamCipher._createHelper(RC4); + + /** + * Modified RC4 stream cipher algorithm. + */ + var RC4Drop = C_algo.RC4Drop = RC4.extend({ + /** + * Configuration options. + * + * @property {number} drop The number of keystream words to drop. Default 192 + */ + cfg: RC4.cfg.extend({ + drop: 192 + }), + + _doReset: function () { + RC4._doReset.call(this); + + // Drop + for (var i = this.cfg.drop; i > 0; i--) { + generateKeystreamWord.call(this); + } + } + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); + */ + C.RC4Drop = StreamCipher._createHelper(RC4Drop); + }()); + + + return CryptoJS.RC4; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/ripemd160.js b/miniprogram_npm/crypto-js/ripemd160.js new file mode 100644 index 0000000..24feb47 --- /dev/null +++ b/miniprogram_npm/crypto-js/ripemd160.js @@ -0,0 +1,267 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** @preserve + (c) 2012 by Cédric Mesnil. All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Constants table + var _zl = WordArray.create([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); + var _zr = WordArray.create([ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); + var _sl = WordArray.create([ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); + var _sr = WordArray.create([ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); + + var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); + var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); + + /** + * RIPEMD160 hash algorithm. + */ + var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ + _doReset: function () { + this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); + }, + + _doProcessBlock: function (M, offset) { + + // Swap endian + for (var i = 0; i < 16; i++) { + // Shortcuts + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + // Swap + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } + // Shortcut + var H = this._hash.words; + var hl = _hl.words; + var hr = _hr.words; + var zl = _zl.words; + var zr = _zr.words; + var sl = _sl.words; + var sr = _sr.words; + + // Working variables + var al, bl, cl, dl, el; + var ar, br, cr, dr, er; + + ar = al = H[0]; + br = bl = H[1]; + cr = cl = H[2]; + dr = dl = H[3]; + er = el = H[4]; + // Computation + var t; + for (var i = 0; i < 80; i += 1) { + t = (al + M[offset+zl[i]])|0; + if (i<16){ + t += f1(bl,cl,dl) + hl[0]; + } else if (i<32) { + t += f2(bl,cl,dl) + hl[1]; + } else if (i<48) { + t += f3(bl,cl,dl) + hl[2]; + } else if (i<64) { + t += f4(bl,cl,dl) + hl[3]; + } else {// if (i<80) { + t += f5(bl,cl,dl) + hl[4]; + } + t = t|0; + t = rotl(t,sl[i]); + t = (t+el)|0; + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = t; + + t = (ar + M[offset+zr[i]])|0; + if (i<16){ + t += f5(br,cr,dr) + hr[0]; + } else if (i<32) { + t += f4(br,cr,dr) + hr[1]; + } else if (i<48) { + t += f3(br,cr,dr) + hr[2]; + } else if (i<64) { + t += f2(br,cr,dr) + hr[3]; + } else {// if (i<80) { + t += f1(br,cr,dr) + hr[4]; + } + t = t|0; + t = rotl(t,sr[i]) ; + t = (t+er)|0; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = t; + } + // Intermediate hash value + t = (H[1] + cl + dr)|0; + H[1] = (H[2] + dl + er)|0; + H[2] = (H[3] + el + ar)|0; + H[3] = (H[4] + al + br)|0; + H[4] = (H[0] + bl + cr)|0; + H[0] = t; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | + (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) + ); + data.sigBytes = (dataWords.length + 1) * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var hash = this._hash; + var H = hash.words; + + // Swap endian + for (var i = 0; i < 5; i++) { + // Shortcut + var H_i = H[i]; + + // Swap + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + + function f1(x, y, z) { + return ((x) ^ (y) ^ (z)); + + } + + function f2(x, y, z) { + return (((x)&(y)) | ((~x)&(z))); + } + + function f3(x, y, z) { + return (((x) | (~(y))) ^ (z)); + } + + function f4(x, y, z) { + return (((x) & (z)) | ((y)&(~(z)))); + } + + function f5(x, y, z) { + return ((x) ^ ((y) |(~(z)))); + + } + + function rotl(x,n) { + return (x<>>(32-n)); + } + + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.RIPEMD160('message'); + * var hash = CryptoJS.RIPEMD160(wordArray); + */ + C.RIPEMD160 = Hasher._createHelper(RIPEMD160); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacRIPEMD160(message, key); + */ + C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); + }(Math)); + + + return CryptoJS.RIPEMD160; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/sha1.js b/miniprogram_npm/crypto-js/sha1.js new file mode 100644 index 0000000..6691149 --- /dev/null +++ b/miniprogram_npm/crypto-js/sha1.js @@ -0,0 +1,150 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Reusable object + var W = []; + + /** + * SHA-1 hash algorithm. + */ + var SHA1 = C_algo.SHA1 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0x67452301, 0xefcdab89, + 0x98badcfe, 0x10325476, + 0xc3d2e1f0 + ]); + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var H = this._hash.words; + + // Working variables + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + + // Computation + for (var i = 0; i < 80; i++) { + if (i < 16) { + W[i] = M[offset + i] | 0; + } else { + var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + W[i] = (n << 1) | (n >>> 31); + } + + var t = ((a << 5) | (a >>> 27)) + e + W[i]; + if (i < 20) { + t += ((b & c) | (~b & d)) + 0x5a827999; + } else if (i < 40) { + t += (b ^ c ^ d) + 0x6ed9eba1; + } else if (i < 60) { + t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; + } else /* if (i < 80) */ { + t += (b ^ c ^ d) - 0x359d3e2a; + } + + e = d; + d = c; + c = (b << 30) | (b >>> 2); + b = a; + a = t; + } + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + H[4] = (H[4] + e) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Return final computed hash + return this._hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA1('message'); + * var hash = CryptoJS.SHA1(wordArray); + */ + C.SHA1 = Hasher._createHelper(SHA1); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA1(message, key); + */ + C.HmacSHA1 = Hasher._createHmacHelper(SHA1); + }()); + + + return CryptoJS.SHA1; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/sha224.js b/miniprogram_npm/crypto-js/sha224.js new file mode 100644 index 0000000..d8ce988 --- /dev/null +++ b/miniprogram_npm/crypto-js/sha224.js @@ -0,0 +1,80 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./sha256")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./sha256"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var SHA256 = C_algo.SHA256; + + /** + * SHA-224 hash algorithm. + */ + var SHA224 = C_algo.SHA224 = SHA256.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 + ]); + }, + + _doFinalize: function () { + var hash = SHA256._doFinalize.call(this); + + hash.sigBytes -= 4; + + return hash; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA224('message'); + * var hash = CryptoJS.SHA224(wordArray); + */ + C.SHA224 = SHA256._createHelper(SHA224); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA224(message, key); + */ + C.HmacSHA224 = SHA256._createHmacHelper(SHA224); + }()); + + + return CryptoJS.SHA224; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/sha256.js b/miniprogram_npm/crypto-js/sha256.js new file mode 100644 index 0000000..de2d7fc --- /dev/null +++ b/miniprogram_npm/crypto-js/sha256.js @@ -0,0 +1,199 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Initialization and round constants tables + var H = []; + var K = []; + + // Compute constants + (function () { + function isPrime(n) { + var sqrtN = Math.sqrt(n); + for (var factor = 2; factor <= sqrtN; factor++) { + if (!(n % factor)) { + return false; + } + } + + return true; + } + + function getFractionalBits(n) { + return ((n - (n | 0)) * 0x100000000) | 0; + } + + var n = 2; + var nPrime = 0; + while (nPrime < 64) { + if (isPrime(n)) { + if (nPrime < 8) { + H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); + } + K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); + + nPrime++; + } + + n++; + } + }()); + + // Reusable object + var W = []; + + /** + * SHA-256 hash algorithm. + */ + var SHA256 = C_algo.SHA256 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init(H.slice(0)); + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var H = this._hash.words; + + // Working variables + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + var f = H[5]; + var g = H[6]; + var h = H[7]; + + // Computation + for (var i = 0; i < 64; i++) { + if (i < 16) { + W[i] = M[offset + i] | 0; + } else { + var gamma0x = W[i - 15]; + var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ + ((gamma0x << 14) | (gamma0x >>> 18)) ^ + (gamma0x >>> 3); + + var gamma1x = W[i - 2]; + var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ + ((gamma1x << 13) | (gamma1x >>> 19)) ^ + (gamma1x >>> 10); + + W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; + } + + var ch = (e & f) ^ (~e & g); + var maj = (a & b) ^ (a & c) ^ (b & c); + + var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); + var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); + + var t1 = h + sigma1 + ch + K[i] + W[i]; + var t2 = sigma0 + maj; + + h = g; + g = f; + f = e; + e = (d + t1) | 0; + d = c; + c = b; + b = a; + a = (t1 + t2) | 0; + } + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + H[4] = (H[4] + e) | 0; + H[5] = (H[5] + f) | 0; + H[6] = (H[6] + g) | 0; + H[7] = (H[7] + h) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Return final computed hash + return this._hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA256('message'); + * var hash = CryptoJS.SHA256(wordArray); + */ + C.SHA256 = Hasher._createHelper(SHA256); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA256(message, key); + */ + C.HmacSHA256 = Hasher._createHmacHelper(SHA256); + }(Math)); + + + return CryptoJS.SHA256; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/sha3.js b/miniprogram_npm/crypto-js/sha3.js new file mode 100644 index 0000000..34ad86c --- /dev/null +++ b/miniprogram_npm/crypto-js/sha3.js @@ -0,0 +1,326 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./x64-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./x64-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var C_algo = C.algo; + + // Constants tables + var RHO_OFFSETS = []; + var PI_INDEXES = []; + var ROUND_CONSTANTS = []; + + // Compute Constants + (function () { + // Compute rho offset constants + var x = 1, y = 0; + for (var t = 0; t < 24; t++) { + RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; + + var newX = y % 5; + var newY = (2 * x + 3 * y) % 5; + x = newX; + y = newY; + } + + // Compute pi index constants + for (var x = 0; x < 5; x++) { + for (var y = 0; y < 5; y++) { + PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; + } + } + + // Compute round constants + var LFSR = 0x01; + for (var i = 0; i < 24; i++) { + var roundConstantMsw = 0; + var roundConstantLsw = 0; + + for (var j = 0; j < 7; j++) { + if (LFSR & 0x01) { + var bitPosition = (1 << j) - 1; + if (bitPosition < 32) { + roundConstantLsw ^= 1 << bitPosition; + } else /* if (bitPosition >= 32) */ { + roundConstantMsw ^= 1 << (bitPosition - 32); + } + } + + // Compute next LFSR + if (LFSR & 0x80) { + // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 + LFSR = (LFSR << 1) ^ 0x71; + } else { + LFSR <<= 1; + } + } + + ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); + } + }()); + + // Reusable objects for temporary values + var T = []; + (function () { + for (var i = 0; i < 25; i++) { + T[i] = X64Word.create(); + } + }()); + + /** + * SHA-3 hash algorithm. + */ + var SHA3 = C_algo.SHA3 = Hasher.extend({ + /** + * Configuration options. + * + * @property {number} outputLength + * The desired number of bits in the output hash. + * Only values permitted are: 224, 256, 384, 512. + * Default: 512 + */ + cfg: Hasher.cfg.extend({ + outputLength: 512 + }), + + _doReset: function () { + var state = this._state = [] + for (var i = 0; i < 25; i++) { + state[i] = new X64Word.init(); + } + + this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; + }, + + _doProcessBlock: function (M, offset) { + // Shortcuts + var state = this._state; + var nBlockSizeLanes = this.blockSize / 2; + + // Absorb + for (var i = 0; i < nBlockSizeLanes; i++) { + // Shortcuts + var M2i = M[offset + 2 * i]; + var M2i1 = M[offset + 2 * i + 1]; + + // Swap endian + M2i = ( + (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | + (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) + ); + M2i1 = ( + (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | + (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) + ); + + // Absorb message into state + var lane = state[i]; + lane.high ^= M2i1; + lane.low ^= M2i; + } + + // Rounds + for (var round = 0; round < 24; round++) { + // Theta + for (var x = 0; x < 5; x++) { + // Mix column lanes + var tMsw = 0, tLsw = 0; + for (var y = 0; y < 5; y++) { + var lane = state[x + 5 * y]; + tMsw ^= lane.high; + tLsw ^= lane.low; + } + + // Temporary values + var Tx = T[x]; + Tx.high = tMsw; + Tx.low = tLsw; + } + for (var x = 0; x < 5; x++) { + // Shortcuts + var Tx4 = T[(x + 4) % 5]; + var Tx1 = T[(x + 1) % 5]; + var Tx1Msw = Tx1.high; + var Tx1Lsw = Tx1.low; + + // Mix surrounding columns + var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); + var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); + for (var y = 0; y < 5; y++) { + var lane = state[x + 5 * y]; + lane.high ^= tMsw; + lane.low ^= tLsw; + } + } + + // Rho Pi + for (var laneIndex = 1; laneIndex < 25; laneIndex++) { + var tMsw; + var tLsw; + + // Shortcuts + var lane = state[laneIndex]; + var laneMsw = lane.high; + var laneLsw = lane.low; + var rhoOffset = RHO_OFFSETS[laneIndex]; + + // Rotate lanes + if (rhoOffset < 32) { + tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); + tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); + } else /* if (rhoOffset >= 32) */ { + tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); + tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); + } + + // Transpose lanes + var TPiLane = T[PI_INDEXES[laneIndex]]; + TPiLane.high = tMsw; + TPiLane.low = tLsw; + } + + // Rho pi at x = y = 0 + var T0 = T[0]; + var state0 = state[0]; + T0.high = state0.high; + T0.low = state0.low; + + // Chi + for (var x = 0; x < 5; x++) { + for (var y = 0; y < 5; y++) { + // Shortcuts + var laneIndex = x + 5 * y; + var lane = state[laneIndex]; + var TLane = T[laneIndex]; + var Tx1Lane = T[((x + 1) % 5) + 5 * y]; + var Tx2Lane = T[((x + 2) % 5) + 5 * y]; + + // Mix rows + lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); + lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); + } + } + + // Iota + var lane = state[0]; + var roundConstant = ROUND_CONSTANTS[round]; + lane.high ^= roundConstant.high; + lane.low ^= roundConstant.low; + } + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + var blockSizeBits = this.blockSize * 32; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); + dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var state = this._state; + var outputLengthBytes = this.cfg.outputLength / 8; + var outputLengthLanes = outputLengthBytes / 8; + + // Squeeze + var hashWords = []; + for (var i = 0; i < outputLengthLanes; i++) { + // Shortcuts + var lane = state[i]; + var laneMsw = lane.high; + var laneLsw = lane.low; + + // Swap endian + laneMsw = ( + (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | + (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) + ); + laneLsw = ( + (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | + (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) + ); + + // Squeeze state to retrieve hash + hashWords.push(laneLsw); + hashWords.push(laneMsw); + } + + // Return final computed hash + return new WordArray.init(hashWords, outputLengthBytes); + }, + + clone: function () { + var clone = Hasher.clone.call(this); + + var state = clone._state = this._state.slice(0); + for (var i = 0; i < 25; i++) { + state[i] = state[i].clone(); + } + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA3('message'); + * var hash = CryptoJS.SHA3(wordArray); + */ + C.SHA3 = Hasher._createHelper(SHA3); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA3(message, key); + */ + C.HmacSHA3 = Hasher._createHmacHelper(SHA3); + }(Math)); + + + return CryptoJS.SHA3; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/sha384.js b/miniprogram_npm/crypto-js/sha384.js new file mode 100644 index 0000000..a0b95bf --- /dev/null +++ b/miniprogram_npm/crypto-js/sha384.js @@ -0,0 +1,83 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha512")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./x64-core", "./sha512"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var X64WordArray = C_x64.WordArray; + var C_algo = C.algo; + var SHA512 = C_algo.SHA512; + + /** + * SHA-384 hash algorithm. + */ + var SHA384 = C_algo.SHA384 = SHA512.extend({ + _doReset: function () { + this._hash = new X64WordArray.init([ + new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), + new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), + new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), + new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) + ]); + }, + + _doFinalize: function () { + var hash = SHA512._doFinalize.call(this); + + hash.sigBytes -= 16; + + return hash; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA384('message'); + * var hash = CryptoJS.SHA384(wordArray); + */ + C.SHA384 = SHA512._createHelper(SHA384); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA384(message, key); + */ + C.HmacSHA384 = SHA512._createHmacHelper(SHA384); + }()); + + + return CryptoJS.SHA384; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/sha512.js b/miniprogram_npm/crypto-js/sha512.js new file mode 100644 index 0000000..d274ab0 --- /dev/null +++ b/miniprogram_npm/crypto-js/sha512.js @@ -0,0 +1,326 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./x64-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./x64-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Hasher = C_lib.Hasher; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var X64WordArray = C_x64.WordArray; + var C_algo = C.algo; + + function X64Word_create() { + return X64Word.create.apply(X64Word, arguments); + } + + // Constants + var K = [ + X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), + X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), + X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), + X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), + X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), + X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), + X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), + X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), + X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), + X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), + X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), + X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), + X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), + X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), + X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), + X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), + X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), + X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), + X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), + X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), + X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), + X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), + X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), + X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), + X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), + X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), + X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), + X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), + X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), + X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), + X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), + X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), + X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), + X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), + X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), + X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), + X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), + X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), + X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), + X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) + ]; + + // Reusable objects + var W = []; + (function () { + for (var i = 0; i < 80; i++) { + W[i] = X64Word_create(); + } + }()); + + /** + * SHA-512 hash algorithm. + */ + var SHA512 = C_algo.SHA512 = Hasher.extend({ + _doReset: function () { + this._hash = new X64WordArray.init([ + new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), + new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), + new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), + new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) + ]); + }, + + _doProcessBlock: function (M, offset) { + // Shortcuts + var H = this._hash.words; + + var H0 = H[0]; + var H1 = H[1]; + var H2 = H[2]; + var H3 = H[3]; + var H4 = H[4]; + var H5 = H[5]; + var H6 = H[6]; + var H7 = H[7]; + + var H0h = H0.high; + var H0l = H0.low; + var H1h = H1.high; + var H1l = H1.low; + var H2h = H2.high; + var H2l = H2.low; + var H3h = H3.high; + var H3l = H3.low; + var H4h = H4.high; + var H4l = H4.low; + var H5h = H5.high; + var H5l = H5.low; + var H6h = H6.high; + var H6l = H6.low; + var H7h = H7.high; + var H7l = H7.low; + + // Working variables + var ah = H0h; + var al = H0l; + var bh = H1h; + var bl = H1l; + var ch = H2h; + var cl = H2l; + var dh = H3h; + var dl = H3l; + var eh = H4h; + var el = H4l; + var fh = H5h; + var fl = H5l; + var gh = H6h; + var gl = H6l; + var hh = H7h; + var hl = H7l; + + // Rounds + for (var i = 0; i < 80; i++) { + var Wil; + var Wih; + + // Shortcut + var Wi = W[i]; + + // Extend message + if (i < 16) { + Wih = Wi.high = M[offset + i * 2] | 0; + Wil = Wi.low = M[offset + i * 2 + 1] | 0; + } else { + // Gamma0 + var gamma0x = W[i - 15]; + var gamma0xh = gamma0x.high; + var gamma0xl = gamma0x.low; + var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); + var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); + + // Gamma1 + var gamma1x = W[i - 2]; + var gamma1xh = gamma1x.high; + var gamma1xl = gamma1x.low; + var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); + var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7 = W[i - 7]; + var Wi7h = Wi7.high; + var Wi7l = Wi7.low; + + var Wi16 = W[i - 16]; + var Wi16h = Wi16.high; + var Wi16l = Wi16.low; + + Wil = gamma0l + Wi7l; + Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); + Wil = Wil + gamma1l; + Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); + Wil = Wil + Wi16l; + Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); + + Wi.high = Wih; + Wi.low = Wil; + } + + var chh = (eh & fh) ^ (~eh & gh); + var chl = (el & fl) ^ (~el & gl); + var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); + var majl = (al & bl) ^ (al & cl) ^ (bl & cl); + + var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); + var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); + var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); + var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); + + // t1 = h + sigma1 + ch + K[i] + W[i] + var Ki = K[i]; + var Kih = Ki.high; + var Kil = Ki.low; + + var t1l = hl + sigma1l; + var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); + var t1l = t1l + chl; + var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); + var t1l = t1l + Kil; + var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); + var t1l = t1l + Wil; + var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); + + // t2 = sigma0 + maj + var t2l = sigma0l + majl; + var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); + + // Update working variables + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; + } + + // Intermediate hash value + H0l = H0.low = (H0l + al); + H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); + H1l = H1.low = (H1l + bl); + H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); + H2l = H2.low = (H2l + cl); + H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); + H3l = H3.low = (H3l + dl); + H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); + H4l = H4.low = (H4l + el); + H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); + H5l = H5.low = (H5l + fl); + H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); + H6l = H6.low = (H6l + gl); + H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); + H7l = H7.low = (H7l + hl); + H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Convert hash to 32-bit word array before returning + var hash = this._hash.toX32(); + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + }, + + blockSize: 1024/32 + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA512('message'); + * var hash = CryptoJS.SHA512(wordArray); + */ + C.SHA512 = Hasher._createHelper(SHA512); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA512(message, key); + */ + C.HmacSHA512 = Hasher._createHmacHelper(SHA512); + }()); + + + return CryptoJS.SHA512; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/tripledes.js b/miniprogram_npm/crypto-js/tripledes.js new file mode 100644 index 0000000..1a92477 --- /dev/null +++ b/miniprogram_npm/crypto-js/tripledes.js @@ -0,0 +1,779 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + // Permuted Choice 1 constants + var PC1 = [ + 57, 49, 41, 33, 25, 17, 9, 1, + 58, 50, 42, 34, 26, 18, 10, 2, + 59, 51, 43, 35, 27, 19, 11, 3, + 60, 52, 44, 36, 63, 55, 47, 39, + 31, 23, 15, 7, 62, 54, 46, 38, + 30, 22, 14, 6, 61, 53, 45, 37, + 29, 21, 13, 5, 28, 20, 12, 4 + ]; + + // Permuted Choice 2 constants + var PC2 = [ + 14, 17, 11, 24, 1, 5, + 3, 28, 15, 6, 21, 10, + 23, 19, 12, 4, 26, 8, + 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, + 30, 40, 51, 45, 33, 48, + 44, 49, 39, 56, 34, 53, + 46, 42, 50, 36, 29, 32 + ]; + + // Cumulative bit shift constants + var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; + + // SBOXes and round permutation constants + var SBOX_P = [ + { + 0x0: 0x808200, + 0x10000000: 0x8000, + 0x20000000: 0x808002, + 0x30000000: 0x2, + 0x40000000: 0x200, + 0x50000000: 0x808202, + 0x60000000: 0x800202, + 0x70000000: 0x800000, + 0x80000000: 0x202, + 0x90000000: 0x800200, + 0xa0000000: 0x8200, + 0xb0000000: 0x808000, + 0xc0000000: 0x8002, + 0xd0000000: 0x800002, + 0xe0000000: 0x0, + 0xf0000000: 0x8202, + 0x8000000: 0x0, + 0x18000000: 0x808202, + 0x28000000: 0x8202, + 0x38000000: 0x8000, + 0x48000000: 0x808200, + 0x58000000: 0x200, + 0x68000000: 0x808002, + 0x78000000: 0x2, + 0x88000000: 0x800200, + 0x98000000: 0x8200, + 0xa8000000: 0x808000, + 0xb8000000: 0x800202, + 0xc8000000: 0x800002, + 0xd8000000: 0x8002, + 0xe8000000: 0x202, + 0xf8000000: 0x800000, + 0x1: 0x8000, + 0x10000001: 0x2, + 0x20000001: 0x808200, + 0x30000001: 0x800000, + 0x40000001: 0x808002, + 0x50000001: 0x8200, + 0x60000001: 0x200, + 0x70000001: 0x800202, + 0x80000001: 0x808202, + 0x90000001: 0x808000, + 0xa0000001: 0x800002, + 0xb0000001: 0x8202, + 0xc0000001: 0x202, + 0xd0000001: 0x800200, + 0xe0000001: 0x8002, + 0xf0000001: 0x0, + 0x8000001: 0x808202, + 0x18000001: 0x808000, + 0x28000001: 0x800000, + 0x38000001: 0x200, + 0x48000001: 0x8000, + 0x58000001: 0x800002, + 0x68000001: 0x2, + 0x78000001: 0x8202, + 0x88000001: 0x8002, + 0x98000001: 0x800202, + 0xa8000001: 0x202, + 0xb8000001: 0x808200, + 0xc8000001: 0x800200, + 0xd8000001: 0x0, + 0xe8000001: 0x8200, + 0xf8000001: 0x808002 + }, + { + 0x0: 0x40084010, + 0x1000000: 0x4000, + 0x2000000: 0x80000, + 0x3000000: 0x40080010, + 0x4000000: 0x40000010, + 0x5000000: 0x40084000, + 0x6000000: 0x40004000, + 0x7000000: 0x10, + 0x8000000: 0x84000, + 0x9000000: 0x40004010, + 0xa000000: 0x40000000, + 0xb000000: 0x84010, + 0xc000000: 0x80010, + 0xd000000: 0x0, + 0xe000000: 0x4010, + 0xf000000: 0x40080000, + 0x800000: 0x40004000, + 0x1800000: 0x84010, + 0x2800000: 0x10, + 0x3800000: 0x40004010, + 0x4800000: 0x40084010, + 0x5800000: 0x40000000, + 0x6800000: 0x80000, + 0x7800000: 0x40080010, + 0x8800000: 0x80010, + 0x9800000: 0x0, + 0xa800000: 0x4000, + 0xb800000: 0x40080000, + 0xc800000: 0x40000010, + 0xd800000: 0x84000, + 0xe800000: 0x40084000, + 0xf800000: 0x4010, + 0x10000000: 0x0, + 0x11000000: 0x40080010, + 0x12000000: 0x40004010, + 0x13000000: 0x40084000, + 0x14000000: 0x40080000, + 0x15000000: 0x10, + 0x16000000: 0x84010, + 0x17000000: 0x4000, + 0x18000000: 0x4010, + 0x19000000: 0x80000, + 0x1a000000: 0x80010, + 0x1b000000: 0x40000010, + 0x1c000000: 0x84000, + 0x1d000000: 0x40004000, + 0x1e000000: 0x40000000, + 0x1f000000: 0x40084010, + 0x10800000: 0x84010, + 0x11800000: 0x80000, + 0x12800000: 0x40080000, + 0x13800000: 0x4000, + 0x14800000: 0x40004000, + 0x15800000: 0x40084010, + 0x16800000: 0x10, + 0x17800000: 0x40000000, + 0x18800000: 0x40084000, + 0x19800000: 0x40000010, + 0x1a800000: 0x40004010, + 0x1b800000: 0x80010, + 0x1c800000: 0x0, + 0x1d800000: 0x4010, + 0x1e800000: 0x40080010, + 0x1f800000: 0x84000 + }, + { + 0x0: 0x104, + 0x100000: 0x0, + 0x200000: 0x4000100, + 0x300000: 0x10104, + 0x400000: 0x10004, + 0x500000: 0x4000004, + 0x600000: 0x4010104, + 0x700000: 0x4010000, + 0x800000: 0x4000000, + 0x900000: 0x4010100, + 0xa00000: 0x10100, + 0xb00000: 0x4010004, + 0xc00000: 0x4000104, + 0xd00000: 0x10000, + 0xe00000: 0x4, + 0xf00000: 0x100, + 0x80000: 0x4010100, + 0x180000: 0x4010004, + 0x280000: 0x0, + 0x380000: 0x4000100, + 0x480000: 0x4000004, + 0x580000: 0x10000, + 0x680000: 0x10004, + 0x780000: 0x104, + 0x880000: 0x4, + 0x980000: 0x100, + 0xa80000: 0x4010000, + 0xb80000: 0x10104, + 0xc80000: 0x10100, + 0xd80000: 0x4000104, + 0xe80000: 0x4010104, + 0xf80000: 0x4000000, + 0x1000000: 0x4010100, + 0x1100000: 0x10004, + 0x1200000: 0x10000, + 0x1300000: 0x4000100, + 0x1400000: 0x100, + 0x1500000: 0x4010104, + 0x1600000: 0x4000004, + 0x1700000: 0x0, + 0x1800000: 0x4000104, + 0x1900000: 0x4000000, + 0x1a00000: 0x4, + 0x1b00000: 0x10100, + 0x1c00000: 0x4010000, + 0x1d00000: 0x104, + 0x1e00000: 0x10104, + 0x1f00000: 0x4010004, + 0x1080000: 0x4000000, + 0x1180000: 0x104, + 0x1280000: 0x4010100, + 0x1380000: 0x0, + 0x1480000: 0x10004, + 0x1580000: 0x4000100, + 0x1680000: 0x100, + 0x1780000: 0x4010004, + 0x1880000: 0x10000, + 0x1980000: 0x4010104, + 0x1a80000: 0x10104, + 0x1b80000: 0x4000004, + 0x1c80000: 0x4000104, + 0x1d80000: 0x4010000, + 0x1e80000: 0x4, + 0x1f80000: 0x10100 + }, + { + 0x0: 0x80401000, + 0x10000: 0x80001040, + 0x20000: 0x401040, + 0x30000: 0x80400000, + 0x40000: 0x0, + 0x50000: 0x401000, + 0x60000: 0x80000040, + 0x70000: 0x400040, + 0x80000: 0x80000000, + 0x90000: 0x400000, + 0xa0000: 0x40, + 0xb0000: 0x80001000, + 0xc0000: 0x80400040, + 0xd0000: 0x1040, + 0xe0000: 0x1000, + 0xf0000: 0x80401040, + 0x8000: 0x80001040, + 0x18000: 0x40, + 0x28000: 0x80400040, + 0x38000: 0x80001000, + 0x48000: 0x401000, + 0x58000: 0x80401040, + 0x68000: 0x0, + 0x78000: 0x80400000, + 0x88000: 0x1000, + 0x98000: 0x80401000, + 0xa8000: 0x400000, + 0xb8000: 0x1040, + 0xc8000: 0x80000000, + 0xd8000: 0x400040, + 0xe8000: 0x401040, + 0xf8000: 0x80000040, + 0x100000: 0x400040, + 0x110000: 0x401000, + 0x120000: 0x80000040, + 0x130000: 0x0, + 0x140000: 0x1040, + 0x150000: 0x80400040, + 0x160000: 0x80401000, + 0x170000: 0x80001040, + 0x180000: 0x80401040, + 0x190000: 0x80000000, + 0x1a0000: 0x80400000, + 0x1b0000: 0x401040, + 0x1c0000: 0x80001000, + 0x1d0000: 0x400000, + 0x1e0000: 0x40, + 0x1f0000: 0x1000, + 0x108000: 0x80400000, + 0x118000: 0x80401040, + 0x128000: 0x0, + 0x138000: 0x401000, + 0x148000: 0x400040, + 0x158000: 0x80000000, + 0x168000: 0x80001040, + 0x178000: 0x40, + 0x188000: 0x80000040, + 0x198000: 0x1000, + 0x1a8000: 0x80001000, + 0x1b8000: 0x80400040, + 0x1c8000: 0x1040, + 0x1d8000: 0x80401000, + 0x1e8000: 0x400000, + 0x1f8000: 0x401040 + }, + { + 0x0: 0x80, + 0x1000: 0x1040000, + 0x2000: 0x40000, + 0x3000: 0x20000000, + 0x4000: 0x20040080, + 0x5000: 0x1000080, + 0x6000: 0x21000080, + 0x7000: 0x40080, + 0x8000: 0x1000000, + 0x9000: 0x20040000, + 0xa000: 0x20000080, + 0xb000: 0x21040080, + 0xc000: 0x21040000, + 0xd000: 0x0, + 0xe000: 0x1040080, + 0xf000: 0x21000000, + 0x800: 0x1040080, + 0x1800: 0x21000080, + 0x2800: 0x80, + 0x3800: 0x1040000, + 0x4800: 0x40000, + 0x5800: 0x20040080, + 0x6800: 0x21040000, + 0x7800: 0x20000000, + 0x8800: 0x20040000, + 0x9800: 0x0, + 0xa800: 0x21040080, + 0xb800: 0x1000080, + 0xc800: 0x20000080, + 0xd800: 0x21000000, + 0xe800: 0x1000000, + 0xf800: 0x40080, + 0x10000: 0x40000, + 0x11000: 0x80, + 0x12000: 0x20000000, + 0x13000: 0x21000080, + 0x14000: 0x1000080, + 0x15000: 0x21040000, + 0x16000: 0x20040080, + 0x17000: 0x1000000, + 0x18000: 0x21040080, + 0x19000: 0x21000000, + 0x1a000: 0x1040000, + 0x1b000: 0x20040000, + 0x1c000: 0x40080, + 0x1d000: 0x20000080, + 0x1e000: 0x0, + 0x1f000: 0x1040080, + 0x10800: 0x21000080, + 0x11800: 0x1000000, + 0x12800: 0x1040000, + 0x13800: 0x20040080, + 0x14800: 0x20000000, + 0x15800: 0x1040080, + 0x16800: 0x80, + 0x17800: 0x21040000, + 0x18800: 0x40080, + 0x19800: 0x21040080, + 0x1a800: 0x0, + 0x1b800: 0x21000000, + 0x1c800: 0x1000080, + 0x1d800: 0x40000, + 0x1e800: 0x20040000, + 0x1f800: 0x20000080 + }, + { + 0x0: 0x10000008, + 0x100: 0x2000, + 0x200: 0x10200000, + 0x300: 0x10202008, + 0x400: 0x10002000, + 0x500: 0x200000, + 0x600: 0x200008, + 0x700: 0x10000000, + 0x800: 0x0, + 0x900: 0x10002008, + 0xa00: 0x202000, + 0xb00: 0x8, + 0xc00: 0x10200008, + 0xd00: 0x202008, + 0xe00: 0x2008, + 0xf00: 0x10202000, + 0x80: 0x10200000, + 0x180: 0x10202008, + 0x280: 0x8, + 0x380: 0x200000, + 0x480: 0x202008, + 0x580: 0x10000008, + 0x680: 0x10002000, + 0x780: 0x2008, + 0x880: 0x200008, + 0x980: 0x2000, + 0xa80: 0x10002008, + 0xb80: 0x10200008, + 0xc80: 0x0, + 0xd80: 0x10202000, + 0xe80: 0x202000, + 0xf80: 0x10000000, + 0x1000: 0x10002000, + 0x1100: 0x10200008, + 0x1200: 0x10202008, + 0x1300: 0x2008, + 0x1400: 0x200000, + 0x1500: 0x10000000, + 0x1600: 0x10000008, + 0x1700: 0x202000, + 0x1800: 0x202008, + 0x1900: 0x0, + 0x1a00: 0x8, + 0x1b00: 0x10200000, + 0x1c00: 0x2000, + 0x1d00: 0x10002008, + 0x1e00: 0x10202000, + 0x1f00: 0x200008, + 0x1080: 0x8, + 0x1180: 0x202000, + 0x1280: 0x200000, + 0x1380: 0x10000008, + 0x1480: 0x10002000, + 0x1580: 0x2008, + 0x1680: 0x10202008, + 0x1780: 0x10200000, + 0x1880: 0x10202000, + 0x1980: 0x10200008, + 0x1a80: 0x2000, + 0x1b80: 0x202008, + 0x1c80: 0x200008, + 0x1d80: 0x0, + 0x1e80: 0x10000000, + 0x1f80: 0x10002008 + }, + { + 0x0: 0x100000, + 0x10: 0x2000401, + 0x20: 0x400, + 0x30: 0x100401, + 0x40: 0x2100401, + 0x50: 0x0, + 0x60: 0x1, + 0x70: 0x2100001, + 0x80: 0x2000400, + 0x90: 0x100001, + 0xa0: 0x2000001, + 0xb0: 0x2100400, + 0xc0: 0x2100000, + 0xd0: 0x401, + 0xe0: 0x100400, + 0xf0: 0x2000000, + 0x8: 0x2100001, + 0x18: 0x0, + 0x28: 0x2000401, + 0x38: 0x2100400, + 0x48: 0x100000, + 0x58: 0x2000001, + 0x68: 0x2000000, + 0x78: 0x401, + 0x88: 0x100401, + 0x98: 0x2000400, + 0xa8: 0x2100000, + 0xb8: 0x100001, + 0xc8: 0x400, + 0xd8: 0x2100401, + 0xe8: 0x1, + 0xf8: 0x100400, + 0x100: 0x2000000, + 0x110: 0x100000, + 0x120: 0x2000401, + 0x130: 0x2100001, + 0x140: 0x100001, + 0x150: 0x2000400, + 0x160: 0x2100400, + 0x170: 0x100401, + 0x180: 0x401, + 0x190: 0x2100401, + 0x1a0: 0x100400, + 0x1b0: 0x1, + 0x1c0: 0x0, + 0x1d0: 0x2100000, + 0x1e0: 0x2000001, + 0x1f0: 0x400, + 0x108: 0x100400, + 0x118: 0x2000401, + 0x128: 0x2100001, + 0x138: 0x1, + 0x148: 0x2000000, + 0x158: 0x100000, + 0x168: 0x401, + 0x178: 0x2100400, + 0x188: 0x2000001, + 0x198: 0x2100000, + 0x1a8: 0x0, + 0x1b8: 0x2100401, + 0x1c8: 0x100401, + 0x1d8: 0x400, + 0x1e8: 0x2000400, + 0x1f8: 0x100001 + }, + { + 0x0: 0x8000820, + 0x1: 0x20000, + 0x2: 0x8000000, + 0x3: 0x20, + 0x4: 0x20020, + 0x5: 0x8020820, + 0x6: 0x8020800, + 0x7: 0x800, + 0x8: 0x8020000, + 0x9: 0x8000800, + 0xa: 0x20800, + 0xb: 0x8020020, + 0xc: 0x820, + 0xd: 0x0, + 0xe: 0x8000020, + 0xf: 0x20820, + 0x80000000: 0x800, + 0x80000001: 0x8020820, + 0x80000002: 0x8000820, + 0x80000003: 0x8000000, + 0x80000004: 0x8020000, + 0x80000005: 0x20800, + 0x80000006: 0x20820, + 0x80000007: 0x20, + 0x80000008: 0x8000020, + 0x80000009: 0x820, + 0x8000000a: 0x20020, + 0x8000000b: 0x8020800, + 0x8000000c: 0x0, + 0x8000000d: 0x8020020, + 0x8000000e: 0x8000800, + 0x8000000f: 0x20000, + 0x10: 0x20820, + 0x11: 0x8020800, + 0x12: 0x20, + 0x13: 0x800, + 0x14: 0x8000800, + 0x15: 0x8000020, + 0x16: 0x8020020, + 0x17: 0x20000, + 0x18: 0x0, + 0x19: 0x20020, + 0x1a: 0x8020000, + 0x1b: 0x8000820, + 0x1c: 0x8020820, + 0x1d: 0x20800, + 0x1e: 0x820, + 0x1f: 0x8000000, + 0x80000010: 0x20000, + 0x80000011: 0x800, + 0x80000012: 0x8020020, + 0x80000013: 0x20820, + 0x80000014: 0x20, + 0x80000015: 0x8020000, + 0x80000016: 0x8000000, + 0x80000017: 0x8000820, + 0x80000018: 0x8020820, + 0x80000019: 0x8000020, + 0x8000001a: 0x8000800, + 0x8000001b: 0x0, + 0x8000001c: 0x20800, + 0x8000001d: 0x820, + 0x8000001e: 0x20020, + 0x8000001f: 0x8020800 + } + ]; + + // Masks that select the SBOX input + var SBOX_MASK = [ + 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, + 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f + ]; + + /** + * DES block cipher algorithm. + */ + var DES = C_algo.DES = BlockCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + + // Select 56 bits according to PC1 + var keyBits = []; + for (var i = 0; i < 56; i++) { + var keyBitPos = PC1[i] - 1; + keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; + } + + // Assemble 16 subkeys + var subKeys = this._subKeys = []; + for (var nSubKey = 0; nSubKey < 16; nSubKey++) { + // Create subkey + var subKey = subKeys[nSubKey] = []; + + // Shortcut + var bitShift = BIT_SHIFTS[nSubKey]; + + // Select 48 bits according to PC2 + for (var i = 0; i < 24; i++) { + // Select from the left 28 key bits + subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); + + // Select from the right 28 key bits + subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); + } + + // Since each subkey is applied to an expanded 32-bit input, + // the subkey can be broken into 8 values scaled to 32-bits, + // which allows the key to be used without expansion + subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); + for (var i = 1; i < 7; i++) { + subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); + } + subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); + } + + // Compute inverse subkeys + var invSubKeys = this._invSubKeys = []; + for (var i = 0; i < 16; i++) { + invSubKeys[i] = subKeys[15 - i]; + } + }, + + encryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._subKeys); + }, + + decryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._invSubKeys); + }, + + _doCryptBlock: function (M, offset, subKeys) { + // Get input + this._lBlock = M[offset]; + this._rBlock = M[offset + 1]; + + // Initial permutation + exchangeLR.call(this, 4, 0x0f0f0f0f); + exchangeLR.call(this, 16, 0x0000ffff); + exchangeRL.call(this, 2, 0x33333333); + exchangeRL.call(this, 8, 0x00ff00ff); + exchangeLR.call(this, 1, 0x55555555); + + // Rounds + for (var round = 0; round < 16; round++) { + // Shortcuts + var subKey = subKeys[round]; + var lBlock = this._lBlock; + var rBlock = this._rBlock; + + // Feistel function + var f = 0; + for (var i = 0; i < 8; i++) { + f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; + } + this._lBlock = rBlock; + this._rBlock = lBlock ^ f; + } + + // Undo swap from last round + var t = this._lBlock; + this._lBlock = this._rBlock; + this._rBlock = t; + + // Final permutation + exchangeLR.call(this, 1, 0x55555555); + exchangeRL.call(this, 8, 0x00ff00ff); + exchangeRL.call(this, 2, 0x33333333); + exchangeLR.call(this, 16, 0x0000ffff); + exchangeLR.call(this, 4, 0x0f0f0f0f); + + // Set output + M[offset] = this._lBlock; + M[offset + 1] = this._rBlock; + }, + + keySize: 64/32, + + ivSize: 64/32, + + blockSize: 64/32 + }); + + // Swap bits across the left and right words + function exchangeLR(offset, mask) { + var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; + this._rBlock ^= t; + this._lBlock ^= t << offset; + } + + function exchangeRL(offset, mask) { + var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; + this._lBlock ^= t; + this._rBlock ^= t << offset; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); + */ + C.DES = BlockCipher._createHelper(DES); + + /** + * Triple-DES block cipher algorithm. + */ + var TripleDES = C_algo.TripleDES = BlockCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + // Make sure the key length is valid (64, 128 or >= 192 bit) + if (keyWords.length !== 2 && keyWords.length !== 4 && keyWords.length < 6) { + throw new Error('Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.'); + } + + // Extend the key according to the keying options defined in 3DES standard + var key1 = keyWords.slice(0, 2); + var key2 = keyWords.length < 4 ? keyWords.slice(0, 2) : keyWords.slice(2, 4); + var key3 = keyWords.length < 6 ? keyWords.slice(0, 2) : keyWords.slice(4, 6); + + // Create DES instances + this._des1 = DES.createEncryptor(WordArray.create(key1)); + this._des2 = DES.createEncryptor(WordArray.create(key2)); + this._des3 = DES.createEncryptor(WordArray.create(key3)); + }, + + encryptBlock: function (M, offset) { + this._des1.encryptBlock(M, offset); + this._des2.decryptBlock(M, offset); + this._des3.encryptBlock(M, offset); + }, + + decryptBlock: function (M, offset) { + this._des3.decryptBlock(M, offset); + this._des2.encryptBlock(M, offset); + this._des1.decryptBlock(M, offset); + }, + + keySize: 192/32, + + ivSize: 64/32, + + blockSize: 64/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); + */ + C.TripleDES = BlockCipher._createHelper(TripleDES); + }()); + + + return CryptoJS.TripleDES; + +})); \ No newline at end of file diff --git a/miniprogram_npm/crypto-js/x64-core.js b/miniprogram_npm/crypto-js/x64-core.js new file mode 100644 index 0000000..57dcc14 --- /dev/null +++ b/miniprogram_npm/crypto-js/x64-core.js @@ -0,0 +1,304 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var X32WordArray = C_lib.WordArray; + + /** + * x64 namespace. + */ + var C_x64 = C.x64 = {}; + + /** + * A 64-bit word. + */ + var X64Word = C_x64.Word = Base.extend({ + /** + * Initializes a newly created 64-bit word. + * + * @param {number} high The high 32 bits. + * @param {number} low The low 32 bits. + * + * @example + * + * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); + */ + init: function (high, low) { + this.high = high; + this.low = low; + } + + /** + * Bitwise NOTs this word. + * + * @return {X64Word} A new x64-Word object after negating. + * + * @example + * + * var negated = x64Word.not(); + */ + // not: function () { + // var high = ~this.high; + // var low = ~this.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise ANDs this word with the passed word. + * + * @param {X64Word} word The x64-Word to AND with this word. + * + * @return {X64Word} A new x64-Word object after ANDing. + * + * @example + * + * var anded = x64Word.and(anotherX64Word); + */ + // and: function (word) { + // var high = this.high & word.high; + // var low = this.low & word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise ORs this word with the passed word. + * + * @param {X64Word} word The x64-Word to OR with this word. + * + * @return {X64Word} A new x64-Word object after ORing. + * + * @example + * + * var ored = x64Word.or(anotherX64Word); + */ + // or: function (word) { + // var high = this.high | word.high; + // var low = this.low | word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise XORs this word with the passed word. + * + * @param {X64Word} word The x64-Word to XOR with this word. + * + * @return {X64Word} A new x64-Word object after XORing. + * + * @example + * + * var xored = x64Word.xor(anotherX64Word); + */ + // xor: function (word) { + // var high = this.high ^ word.high; + // var low = this.low ^ word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Shifts this word n bits to the left. + * + * @param {number} n The number of bits to shift. + * + * @return {X64Word} A new x64-Word object after shifting. + * + * @example + * + * var shifted = x64Word.shiftL(25); + */ + // shiftL: function (n) { + // if (n < 32) { + // var high = (this.high << n) | (this.low >>> (32 - n)); + // var low = this.low << n; + // } else { + // var high = this.low << (n - 32); + // var low = 0; + // } + + // return X64Word.create(high, low); + // }, + + /** + * Shifts this word n bits to the right. + * + * @param {number} n The number of bits to shift. + * + * @return {X64Word} A new x64-Word object after shifting. + * + * @example + * + * var shifted = x64Word.shiftR(7); + */ + // shiftR: function (n) { + // if (n < 32) { + // var low = (this.low >>> n) | (this.high << (32 - n)); + // var high = this.high >>> n; + // } else { + // var low = this.high >>> (n - 32); + // var high = 0; + // } + + // return X64Word.create(high, low); + // }, + + /** + * Rotates this word n bits to the left. + * + * @param {number} n The number of bits to rotate. + * + * @return {X64Word} A new x64-Word object after rotating. + * + * @example + * + * var rotated = x64Word.rotL(25); + */ + // rotL: function (n) { + // return this.shiftL(n).or(this.shiftR(64 - n)); + // }, + + /** + * Rotates this word n bits to the right. + * + * @param {number} n The number of bits to rotate. + * + * @return {X64Word} A new x64-Word object after rotating. + * + * @example + * + * var rotated = x64Word.rotR(7); + */ + // rotR: function (n) { + // return this.shiftR(n).or(this.shiftL(64 - n)); + // }, + + /** + * Adds this word with the passed word. + * + * @param {X64Word} word The x64-Word to add with this word. + * + * @return {X64Word} A new x64-Word object after adding. + * + * @example + * + * var added = x64Word.add(anotherX64Word); + */ + // add: function (word) { + // var low = (this.low + word.low) | 0; + // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; + // var high = (this.high + word.high + carry) | 0; + + // return X64Word.create(high, low); + // } + }); + + /** + * An array of 64-bit words. + * + * @property {Array} words The array of CryptoJS.x64.Word objects. + * @property {number} sigBytes The number of significant bytes in this word array. + */ + var X64WordArray = C_x64.WordArray = Base.extend({ + /** + * Initializes a newly created word array. + * + * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. + * @param {number} sigBytes (Optional) The number of significant bytes in the words. + * + * @example + * + * var wordArray = CryptoJS.x64.WordArray.create(); + * + * var wordArray = CryptoJS.x64.WordArray.create([ + * CryptoJS.x64.Word.create(0x00010203, 0x04050607), + * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) + * ]); + * + * var wordArray = CryptoJS.x64.WordArray.create([ + * CryptoJS.x64.Word.create(0x00010203, 0x04050607), + * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) + * ], 10); + */ + init: function (words, sigBytes) { + words = this.words = words || []; + + if (sigBytes != undefined) { + this.sigBytes = sigBytes; + } else { + this.sigBytes = words.length * 8; + } + }, + + /** + * Converts this 64-bit word array to a 32-bit word array. + * + * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. + * + * @example + * + * var x32WordArray = x64WordArray.toX32(); + */ + toX32: function () { + // Shortcuts + var x64Words = this.words; + var x64WordsLength = x64Words.length; + + // Convert + var x32Words = []; + for (var i = 0; i < x64WordsLength; i++) { + var x64Word = x64Words[i]; + x32Words.push(x64Word.high); + x32Words.push(x64Word.low); + } + + return X32WordArray.create(x32Words, this.sigBytes); + }, + + /** + * Creates a copy of this word array. + * + * @return {X64WordArray} The clone. + * + * @example + * + * var clone = x64WordArray.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + + // Clone "words" array + var words = clone.words = this.words.slice(0); + + // Clone each X64Word object + var wordsLength = words.length; + for (var i = 0; i < wordsLength; i++) { + words[i] = words[i].clone(); + } + + return clone; + } + }); + }()); + + + return CryptoJS; + +})); \ No newline at end of file diff --git a/miniprogram_npm/dijkstrajs/index.js b/miniprogram_npm/dijkstrajs/index.js new file mode 100644 index 0000000..18795fb --- /dev/null +++ b/miniprogram_npm/dijkstrajs/index.js @@ -0,0 +1,178 @@ +module.exports = (function() { +var __MODS__ = {}; +var __DEFINE__ = function(modId, func, req) { var m = { exports: {}, _tempexports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; }; +var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = __MODS__[modId].m; m._exports = m._tempexports; var desp = Object.getOwnPropertyDescriptor(m, "exports"); if (desp && desp.configurable) Object.defineProperty(m, "exports", { set: function (val) { if(typeof val === "object" && val !== m._exports) { m._exports.__proto__ = val.__proto__; Object.keys(val).forEach(function (k) { m._exports[k] = val[k]; }); } m._tempexports = val }, get: function () { return m._tempexports; } }); __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); } return __MODS__[modId].m.exports; }; +var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } }; +var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; }; +__DEFINE__(1629248775416, function(require, module, exports) { + + +/****************************************************************************** + * Created 2008-08-19. + * + * Dijkstra path-finding functions. Adapted from the Dijkstar Python project. + * + * Copyright (C) 2008 + * Wyatt Baldwin + * All rights reserved + * + * Licensed under the MIT license. + * + * http://www.opensource.org/licenses/mit-license.php + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + *****************************************************************************/ +var dijkstra = { + single_source_shortest_paths: function(graph, s, d) { + // Predecessor map for each node that has been encountered. + // node ID => predecessor node ID + var predecessors = {}; + + // Costs of shortest paths from s to all nodes encountered. + // node ID => cost + var costs = {}; + costs[s] = 0; + + // Costs of shortest paths from s to all nodes encountered; differs from + // `costs` in that it provides easy access to the node that currently has + // the known shortest path from s. + // XXX: Do we actually need both `costs` and `open`? + var open = dijkstra.PriorityQueue.make(); + open.push(s, 0); + + var closest, + u, v, + cost_of_s_to_u, + adjacent_nodes, + cost_of_e, + cost_of_s_to_u_plus_cost_of_e, + cost_of_s_to_v, + first_visit; + while (!open.empty()) { + // In the nodes remaining in graph that have a known cost from s, + // find the node, u, that currently has the shortest path from s. + closest = open.pop(); + u = closest.value; + cost_of_s_to_u = closest.cost; + + // Get nodes adjacent to u... + adjacent_nodes = graph[u] || {}; + + // ...and explore the edges that connect u to those nodes, updating + // the cost of the shortest paths to any or all of those nodes as + // necessary. v is the node across the current edge from u. + for (v in adjacent_nodes) { + if (adjacent_nodes.hasOwnProperty(v)) { + // Get the cost of the edge running from u to v. + cost_of_e = adjacent_nodes[v]; + + // Cost of s to u plus the cost of u to v across e--this is *a* + // cost from s to v that may or may not be less than the current + // known cost to v. + cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e; + + // If we haven't visited v yet OR if the current known cost from s to + // v is greater than the new cost we just found (cost of s to u plus + // cost of u to v across e), update v's cost in the cost list and + // update v's predecessor in the predecessor list (it's now u). + cost_of_s_to_v = costs[v]; + first_visit = (typeof costs[v] === 'undefined'); + if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) { + costs[v] = cost_of_s_to_u_plus_cost_of_e; + open.push(v, cost_of_s_to_u_plus_cost_of_e); + predecessors[v] = u; + } + } + } + } + + if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') { + var msg = ['Could not find a path from ', s, ' to ', d, '.'].join(''); + throw new Error(msg); + } + + return predecessors; + }, + + extract_shortest_path_from_predecessor_list: function(predecessors, d) { + var nodes = []; + var u = d; + var predecessor; + while (u) { + nodes.push(u); + predecessor = predecessors[u]; + u = predecessors[u]; + } + nodes.reverse(); + return nodes; + }, + + find_path: function(graph, s, d) { + var predecessors = dijkstra.single_source_shortest_paths(graph, s, d); + return dijkstra.extract_shortest_path_from_predecessor_list( + predecessors, d); + }, + + /** + * A very naive priority queue implementation. + */ + PriorityQueue: { + make: function (opts) { + var T = dijkstra.PriorityQueue, + t = {}, + key; + opts = opts || {}; + for (key in T) { + if (T.hasOwnProperty(key)) { + t[key] = T[key]; + } + } + t.queue = []; + t.sorter = opts.sorter || T.default_sorter; + return t; + }, + + default_sorter: function (a, b) { + return a.cost - b.cost; + }, + + /** + * Add a new item to the queue and ensure the highest priority element + * is at the front of the queue. + */ + push: function (value, cost) { + var item = {value: value, cost: cost}; + this.queue.push(item); + this.queue.sort(this.sorter); + }, + + /** + * Return the highest priority element in the queue. + */ + pop: function () { + return this.queue.shift(); + }, + + empty: function () { + return this.queue.length === 0; + } + } +}; + + +// node.js module exports +if (typeof module !== 'undefined') { + module.exports = dijkstra; +} + +}, function(modId) {var map = {}; return __REQUIRE__(map[modId], modId); }) +return __REQUIRE__(1629248775416); +})() +//miniprogram-npm-outsideDeps=[] +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/miniprogram_npm/dijkstrajs/index.js.map b/miniprogram_npm/dijkstrajs/index.js.map new file mode 100644 index 0000000..49ad7f7 --- /dev/null +++ b/miniprogram_npm/dijkstrajs/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["dijkstra.js"],"names":[],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"index.js","sourcesContent":["\n\n/******************************************************************************\n * Created 2008-08-19.\n *\n * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.\n *\n * Copyright (C) 2008\n * Wyatt Baldwin \n * All rights reserved\n *\n * Licensed under the MIT license.\n *\n * http://www.opensource.org/licenses/mit-license.php\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *****************************************************************************/\nvar dijkstra = {\n single_source_shortest_paths: function(graph, s, d) {\n // Predecessor map for each node that has been encountered.\n // node ID => predecessor node ID\n var predecessors = {};\n\n // Costs of shortest paths from s to all nodes encountered.\n // node ID => cost\n var costs = {};\n costs[s] = 0;\n\n // Costs of shortest paths from s to all nodes encountered; differs from\n // `costs` in that it provides easy access to the node that currently has\n // the known shortest path from s.\n // XXX: Do we actually need both `costs` and `open`?\n var open = dijkstra.PriorityQueue.make();\n open.push(s, 0);\n\n var closest,\n u, v,\n cost_of_s_to_u,\n adjacent_nodes,\n cost_of_e,\n cost_of_s_to_u_plus_cost_of_e,\n cost_of_s_to_v,\n first_visit;\n while (!open.empty()) {\n // In the nodes remaining in graph that have a known cost from s,\n // find the node, u, that currently has the shortest path from s.\n closest = open.pop();\n u = closest.value;\n cost_of_s_to_u = closest.cost;\n\n // Get nodes adjacent to u...\n adjacent_nodes = graph[u] || {};\n\n // ...and explore the edges that connect u to those nodes, updating\n // the cost of the shortest paths to any or all of those nodes as\n // necessary. v is the node across the current edge from u.\n for (v in adjacent_nodes) {\n if (adjacent_nodes.hasOwnProperty(v)) {\n // Get the cost of the edge running from u to v.\n cost_of_e = adjacent_nodes[v];\n\n // Cost of s to u plus the cost of u to v across e--this is *a*\n // cost from s to v that may or may not be less than the current\n // known cost to v.\n cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;\n\n // If we haven't visited v yet OR if the current known cost from s to\n // v is greater than the new cost we just found (cost of s to u plus\n // cost of u to v across e), update v's cost in the cost list and\n // update v's predecessor in the predecessor list (it's now u).\n cost_of_s_to_v = costs[v];\n first_visit = (typeof costs[v] === 'undefined');\n if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {\n costs[v] = cost_of_s_to_u_plus_cost_of_e;\n open.push(v, cost_of_s_to_u_plus_cost_of_e);\n predecessors[v] = u;\n }\n }\n }\n }\n\n if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {\n var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');\n throw new Error(msg);\n }\n\n return predecessors;\n },\n\n extract_shortest_path_from_predecessor_list: function(predecessors, d) {\n var nodes = [];\n var u = d;\n var predecessor;\n while (u) {\n nodes.push(u);\n predecessor = predecessors[u];\n u = predecessors[u];\n }\n nodes.reverse();\n return nodes;\n },\n\n find_path: function(graph, s, d) {\n var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);\n return dijkstra.extract_shortest_path_from_predecessor_list(\n predecessors, d);\n },\n\n /**\n * A very naive priority queue implementation.\n */\n PriorityQueue: {\n make: function (opts) {\n var T = dijkstra.PriorityQueue,\n t = {},\n key;\n opts = opts || {};\n for (key in T) {\n if (T.hasOwnProperty(key)) {\n t[key] = T[key];\n }\n }\n t.queue = [];\n t.sorter = opts.sorter || T.default_sorter;\n return t;\n },\n\n default_sorter: function (a, b) {\n return a.cost - b.cost;\n },\n\n /**\n * Add a new item to the queue and ensure the highest priority element\n * is at the front of the queue.\n */\n push: function (value, cost) {\n var item = {value: value, cost: cost};\n this.queue.push(item);\n this.queue.sort(this.sorter);\n },\n\n /**\n * Return the highest priority element in the queue.\n */\n pop: function () {\n return this.queue.shift();\n },\n\n empty: function () {\n return this.queue.length === 0;\n }\n }\n};\n\n\n// node.js module exports\nif (typeof module !== 'undefined') {\n module.exports = dijkstra;\n}\n"]} \ No newline at end of file diff --git a/miniprogram_npm/threejs-miniprogram/index.js b/miniprogram_npm/threejs-miniprogram/index.js new file mode 100644 index 0000000..6677109 --- /dev/null +++ b/miniprogram_npm/threejs-miniprogram/index.js @@ -0,0 +1,3 @@ +!function(t,e){for(var r in e)t[r]=e[r]}(exports,function(t){var e={};function r(n){if(e[n])return e[n].exports;var i=e[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)r.d(n,i,function(e){return t[e]}.bind(null,i));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=4)}([function(t,e,r){"use strict";const n=r(1),i=r(2);t.exports={atob:n,btoa:i}},function(t,e,r){"use strict";function n(t){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(t);return e<0?void 0:e}t.exports=function(t){if((t=(t=""+t).replace(/[ \t\n\f\r]/g,"")).length%4==0&&(t=t.replace(/==?$/,"")),t.length%4==1||/[^+/0-9A-Za-z]/.test(t))return null;let e="",r=0,i=0;for(let a=0;a>16),e+=String.fromCharCode((65280&r)>>8),e+=String.fromCharCode(255&r),r=i=0);return 12===i?(r>>=4,e+=String.fromCharCode(r)):18===i&&(r>>=2,e+=String.fromCharCode((65280&r)>>8),e+=String.fromCharCode(255&r)),e}},function(t,e,r){"use strict";function n(t){if(t>=0&&t<64)return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[t]}t.exports=function(t){let e;for(t=""+t,e=0;e255)return null;let r="";for(e=0;e>2,i[1]=(3&t.charCodeAt(e))<<4,t.length>e+1&&(i[1]|=t.charCodeAt(e+1)>>4,i[2]=(15&t.charCodeAt(e+1))<<2),t.length>e+2&&(i[2]|=t.charCodeAt(e+2)>>6,i[3]=63&t.charCodeAt(e+2));for(let t=0;t2&&void 0!==arguments[2]?arguments[2]:{},n=l.get(this);n||(n={},l.set(this,n)),n[t]||(n[t]=[]),n[t].push(e),r.capture,r.once,r.passive}},{key:"removeEventListener",value:function(t,e){var r=l.get(this);if(r){var n=r[t];if(n&&n.length>0)for(var i=n.length;i--;i>0)if(n[i]===e){n.splice(i,1);break}}}},{key:"dispatchEvent",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"function"!=typeof t.preventDefault&&(t.preventDefault=function(){}),"function"!=typeof t.stopPropagation&&(t.stopPropagation=function(){});var e=l.get(this)[t.type];if(e)for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},e=a({},this),r={changedTouches:t.changedTouches.map((function(t){return new h(t)})),touches:t.touches.map((function(t){return new h(t)})),targetTouches:Array.prototype.slice.call(t.touches.map((function(t){return new h(t)}))),timeStamp:t.timeStamp,target:e,currentTarget:e,type:t.type,cancelBubble:!1,cancelable:!1};this.dispatchEvent(r)}}])&&s(e.prototype,r),n&&s(e,n),t}();function p(t){return(p="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function d(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:{};e.target=e.target||this,"function"==typeof this["on".concat(t)]&&this["on".concat(t)].call(this,e)}function M(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.readyState=t,e.readyState=t,_.call(this,"readystatechange",e)}function S(t){return!/^(http|https|ftp|wxfile):\/\/.*/i.test(t)}var T=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&f(t,e)}(a,t);var e,r,n,i=m(a);function a(){var t;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,a),(t=i.call(this)).onabort=null,t.onerror=null,t.onload=null,t.onloadstart=null,t.onprogress=null,t.ontimeout=null,t.onloadend=null,t.onreadystatechange=null,t.readyState=0,t.response=null,t.responseText=null,t.responseType="text",t.dataType="string",t.responseXML=null,t.status=0,t.statusText="",t.upload={},t.withCredentials=!1,x.set(v(t),{"content-type":"application/x-www-form-urlencoded"}),b.set(v(t),{}),t}return e=a,(r=[{key:"abort",value:function(){var t=w.get(this);t&&t.abort()}},{key:"getAllResponseHeaders",value:function(){var t=b.get(this);return Object.keys(t).map((function(e){return"".concat(e,": ").concat(t[e])})).join("\n")}},{key:"getResponseHeader",value:function(t){return b.get(this)[t]}},{key:"open",value:function(t,e){this._method=t,this._url=e,M.call(this,a.OPENED)}},{key:"overrideMimeType",value:function(){}},{key:"send",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";if(this.readyState!==a.OPENED)throw new Error("Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.");var r,n=this._url,i=x.get(this),o=this.responseType,s=this.dataType,c=S(n);"arraybuffer"===o||(r="utf8"),delete this.response,this.response=null;var l=function(e){var r=e.data,n=e.statusCode,i=e.header;if(n=void 0===n?200:n,"string"!=typeof r&&!(r instanceof ArrayBuffer))try{r=JSON.stringify(r)}catch(t){}t.status=n,i&&b.set(t,i),_.call(t,"loadstart"),M.call(t,a.HEADERS_RECEIVED),M.call(t,a.LOADING),t.response=r,r instanceof ArrayBuffer?Object.defineProperty(t,"responseText",{enumerable:!0,configurable:!0,get:function(){throw"InvalidStateError : responseType is "+this.responseType}}):t.responseText=r,M.call(t,a.DONE),_.call(t,"load"),_.call(t,"loadend")},h=function(e){var r=e.errMsg;-1!==r.indexOf("abort")?_.call(t,"abort"):_.call(t,"error",{message:r}),_.call(t,"loadend"),c&&console.warn(r)};if(c){var u=wx.getFileSystemManager(),p={filePath:n,success:l,fail:h};return r&&(p.encoding=r),void u.readFile(p)}wx.request({data:e,url:n,method:this._method,header:i,dataType:s,responseType:o,success:l,fail:h})}},{key:"setRequestHeader",value:function(t,e){var r=x.get(this);r[t]=e,x.set(this,r)}},{key:"addEventListener",value:function(t,e){var r=this;"function"==typeof e&&(this["on"+t]=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.target=t.target||r,e.call(r,t)})}},{key:"removeEventListener",value:function(t,e){this["on"+t]===e&&(this["on"+t]=null)}}])&&d(e.prototype,r),n&&d(e,n),a}(u);function E(t,e){var r;if("undefined"==typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(r=function(t,e){if(!t)return;if("string"==typeof t)return A(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return A(t,e)}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0,i=function(){};return{s:i,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,o=!0,s=!1;return{s:function(){r=t[Symbol.iterator]()},n:function(){var t=r.next();return o=t.done,t},e:function(t){s=!0,a=t},f:function(){try{o||null==r.return||r.return()}finally{if(s)throw a}}}}function A(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0?1:+t}),"name"in Function.prototype==0&&Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1]}}),void 0===Object.assign&&(Object.assign=function(t){if(null==t)throw new TypeError("Cannot convert undefined or null to object");for(var e=Object(t),r=1;r>8&255]+r[t>>16&255]+r[t>>24&255]+"-"+r[255&e]+r[e>>8&255]+"-"+r[e>>16&15|64]+r[e>>24&255]+"-"+r[63&n|128]+r[n>>8&255]+"-"+r[n>>16&255]+r[n>>24&255]+r[255&i]+r[i>>8&255]+r[i>>16&255]+r[i>>24&255]).toUpperCase()},clamp:function(t,e,r){return Math.max(e,Math.min(r,t))},euclideanModulo:function(t,e){return(t%e+e)%e},mapLinear:function(t,e,r,n,i){return n+(t-e)*(i-n)/(r-e)},lerp:function(t,e,r){return(1-r)*t+r*e},smoothstep:function(t,e,r){return t<=e?0:t>=r?1:(t=(t-e)/(r-e))*t*(3-2*t)},smootherstep:function(t,e,r){return t<=e?0:t>=r?1:(t=(t-e)/(r-e))*t*t*(t*(6*t-15)+10)},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},degToRad:function(t){return t*s.DEG2RAD},radToDeg:function(t){return t*s.RAD2DEG},isPowerOfTwo:function(t){return 0==(t&t-1)&&0!==t},ceilPowerOfTwo:function(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},floorPowerOfTwo:function(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}};function l(t,e){this.x=t||0,this.y=e||0}function h(t,e,r,n){this._x=t||0,this._y=e||0,this._z=r||0,this._w=void 0!==n?n:1}Object.defineProperties(l.prototype,{width:{get:function(){return this.x},set:function(t){this.x=t}},height:{get:function(){return this.y},set:function(t){this.y=t}}}),Object.assign(l.prototype,{isVector2:!0,set:function(t,e){return this.x=t,this.y=e,this},setScalar:function(t){return this.x=t,this.y=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(t){return this.x=t.x,this.y=t.y,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this)},addScalar:function(t){return this.x+=t,this.y+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this)},subScalar:function(t){return this.x-=t,this.y-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this},multiplyScalar:function(t){return this.x*=t,this.y*=t,this},divide:function(t){return this.x/=t.x,this.y/=t.y,this},divideScalar:function(t){return this.multiplyScalar(1/t)},applyMatrix3:function(t){var e=this.x,r=this.y,n=t.elements;return this.x=n[0]*e+n[3]*r+n[6],this.y=n[1]*e+n[4]*r+n[7],this},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this},clampScalar:function(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this},clampLength:function(t,e){var r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(t,Math.min(e,r)))},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this},negate:function(){return this.x=-this.x,this.y=-this.y,this},dot:function(t){return this.x*t.x+this.y*t.y},cross:function(t){return this.x*t.y-this.y*t.x},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length()||1)},angle:function(){var t=Math.atan2(this.y,this.x);return t<0&&(t+=2*Math.PI),t},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,r=this.y-t.y;return e*e+r*r},manhattanDistanceTo:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)},setLength:function(t){return this.normalize().multiplyScalar(t)},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this},lerpVectors:function(t,e,r){return this.subVectors(e,t).multiplyScalar(r).add(t)},equals:function(t){return t.x===this.x&&t.y===this.y},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t},fromBufferAttribute:function(t,e,r){return void 0!==r&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute()."),this.x=t.getX(e),this.y=t.getY(e),this},rotateAround:function(t,e){var r=Math.cos(e),n=Math.sin(e),i=this.x-t.x,a=this.y-t.y;return this.x=i*r-a*n+t.x,this.y=i*n+a*r+t.y,this}}),Object.assign(h,{slerp:function(t,e,r,n){return r.copy(t).slerp(e,n)},slerpFlat:function(t,e,r,n,i,a,o){var s=r[n+0],c=r[n+1],l=r[n+2],h=r[n+3],u=i[a+0],p=i[a+1],d=i[a+2],f=i[a+3];if(h!==f||s!==u||c!==p||l!==d){var m=1-o,g=s*u+c*p+l*d+h*f,v=g>=0?1:-1,y=1-g*g;if(y>Number.EPSILON){var x=Math.sqrt(y),b=Math.atan2(x,g*v);m=Math.sin(m*b)/x,o=Math.sin(o*b)/x}var w=o*v;if(s=s*m+u*w,c=c*m+p*w,l=l*m+d*w,h=h*m+f*w,m===1-o){var _=1/Math.sqrt(s*s+c*c+l*l+h*h);s*=_,c*=_,l*=_,h*=_}}t[e]=s,t[e+1]=c,t[e+2]=l,t[e+3]=h}}),Object.defineProperties(h.prototype,{x:{get:function(){return this._x},set:function(t){this._x=t,this._onChangeCallback()}},y:{get:function(){return this._y},set:function(t){this._y=t,this._onChangeCallback()}},z:{get:function(){return this._z},set:function(t){this._z=t,this._onChangeCallback()}},w:{get:function(){return this._w},set:function(t){this._w=t,this._onChangeCallback()}}}),Object.assign(h.prototype,{isQuaternion:!0,set:function(t,e,r,n){return this._x=t,this._y=e,this._z=r,this._w=n,this._onChangeCallback(),this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._w)},copy:function(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this},setFromEuler:function(t,e){if(!t||!t.isEuler)throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var r=t._x,n=t._y,i=t._z,a=t.order,o=Math.cos,s=Math.sin,c=o(r/2),l=o(n/2),h=o(i/2),u=s(r/2),p=s(n/2),d=s(i/2);return"XYZ"===a?(this._x=u*l*h+c*p*d,this._y=c*p*h-u*l*d,this._z=c*l*d+u*p*h,this._w=c*l*h-u*p*d):"YXZ"===a?(this._x=u*l*h+c*p*d,this._y=c*p*h-u*l*d,this._z=c*l*d-u*p*h,this._w=c*l*h+u*p*d):"ZXY"===a?(this._x=u*l*h-c*p*d,this._y=c*p*h+u*l*d,this._z=c*l*d+u*p*h,this._w=c*l*h-u*p*d):"ZYX"===a?(this._x=u*l*h-c*p*d,this._y=c*p*h+u*l*d,this._z=c*l*d-u*p*h,this._w=c*l*h+u*p*d):"YZX"===a?(this._x=u*l*h+c*p*d,this._y=c*p*h+u*l*d,this._z=c*l*d-u*p*h,this._w=c*l*h-u*p*d):"XZY"===a&&(this._x=u*l*h-c*p*d,this._y=c*p*h-u*l*d,this._z=c*l*d+u*p*h,this._w=c*l*h+u*p*d),!1!==e&&this._onChangeCallback(),this},setFromAxisAngle:function(t,e){var r=e/2,n=Math.sin(r);return this._x=t.x*n,this._y=t.y*n,this._z=t.z*n,this._w=Math.cos(r),this._onChangeCallback(),this},setFromRotationMatrix:function(t){var e,r=t.elements,n=r[0],i=r[4],a=r[8],o=r[1],s=r[5],c=r[9],l=r[2],h=r[6],u=r[10],p=n+s+u;return p>0?(e=.5/Math.sqrt(p+1),this._w=.25/e,this._x=(h-c)*e,this._y=(a-l)*e,this._z=(o-i)*e):n>s&&n>u?(e=2*Math.sqrt(1+n-s-u),this._w=(h-c)/e,this._x=.25*e,this._y=(i+o)/e,this._z=(a+l)/e):s>u?(e=2*Math.sqrt(1+s-n-u),this._w=(a-l)/e,this._x=(i+o)/e,this._y=.25*e,this._z=(c+h)/e):(e=2*Math.sqrt(1+u-n-s),this._w=(o-i)/e,this._x=(a+l)/e,this._y=(c+h)/e,this._z=.25*e),this._onChangeCallback(),this},setFromUnitVectors:function(t,e){var r=t.dot(e)+1;return r<1e-6?(r=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=r):(this._x=0,this._y=-t.z,this._z=t.y,this._w=r)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=r),this.normalize()},angleTo:function(t){return 2*Math.acos(Math.abs(s.clamp(this.dot(t),-1,1)))},rotateTowards:function(t,e){var r=this.angleTo(t);if(0===r)return this;var n=Math.min(1,e/r);return this.slerp(t,n),this},inverse:function(){return this.conjugate()},conjugate:function(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this},dot:function(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(t,e)):this.multiplyQuaternions(this,t)},premultiply:function(t){return this.multiplyQuaternions(t,this)},multiplyQuaternions:function(t,e){var r=t._x,n=t._y,i=t._z,a=t._w,o=e._x,s=e._y,c=e._z,l=e._w;return this._x=r*l+a*o+n*c-i*s,this._y=n*l+a*s+i*o-r*c,this._z=i*l+a*c+r*s-n*o,this._w=a*l-r*o-n*s-i*c,this._onChangeCallback(),this},slerp:function(t,e){if(0===e)return this;if(1===e)return this.copy(t);var r=this._x,n=this._y,i=this._z,a=this._w,o=a*t._w+r*t._x+n*t._y+i*t._z;if(o<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,o=-o):this.copy(t),o>=1)return this._w=a,this._x=r,this._y=n,this._z=i,this;var s=1-o*o;if(s<=Number.EPSILON){var c=1-e;return this._w=c*a+e*this._w,this._x=c*r+e*this._x,this._y=c*n+e*this._y,this._z=c*i+e*this._z,this.normalize(),this._onChangeCallback(),this}var l=Math.sqrt(s),h=Math.atan2(l,o),u=Math.sin((1-e)*h)/l,p=Math.sin(e*h)/l;return this._w=a*u+this._w*p,this._x=r*u+this._x*p,this._y=n*u+this._y*p,this._z=i*u+this._z*p,this._onChangeCallback(),this},equals:function(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w},fromArray:function(t,e){return void 0===e&&(e=0),this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t},_onChange:function(t){return this._onChangeCallback=t,this},_onChangeCallback:function(){}});var u=new d,p=new h;function d(t,e,r){this.x=t||0,this.y=e||0,this.z=r||0}Object.assign(d.prototype,{isVector3:!0,set:function(t,e,r){return this.x=t,this.y=e,this.z=r,this},setScalar:function(t){return this.x=t,this.y=t,this.z=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setZ:function(t){return this.z=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this)},addScalar:function(t){return this.x+=t,this.y+=t,this.z+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this)},subScalar:function(t){return this.x-=t,this.y-=t,this.z-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(t,e)):(this.x*=t.x,this.y*=t.y,this.z*=t.z,this)},multiplyScalar:function(t){return this.x*=t,this.y*=t,this.z*=t,this},multiplyVectors:function(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this},applyEuler:function(t){return t&&t.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),this.applyQuaternion(p.setFromEuler(t))},applyAxisAngle:function(t,e){return this.applyQuaternion(p.setFromAxisAngle(t,e))},applyMatrix3:function(t){var e=this.x,r=this.y,n=this.z,i=t.elements;return this.x=i[0]*e+i[3]*r+i[6]*n,this.y=i[1]*e+i[4]*r+i[7]*n,this.z=i[2]*e+i[5]*r+i[8]*n,this},applyMatrix4:function(t){var e=this.x,r=this.y,n=this.z,i=t.elements,a=1/(i[3]*e+i[7]*r+i[11]*n+i[15]);return this.x=(i[0]*e+i[4]*r+i[8]*n+i[12])*a,this.y=(i[1]*e+i[5]*r+i[9]*n+i[13])*a,this.z=(i[2]*e+i[6]*r+i[10]*n+i[14])*a,this},applyQuaternion:function(t){var e=this.x,r=this.y,n=this.z,i=t.x,a=t.y,o=t.z,s=t.w,c=s*e+a*n-o*r,l=s*r+o*e-i*n,h=s*n+i*r-a*e,u=-i*e-a*r-o*n;return this.x=c*s+u*-i+l*-o-h*-a,this.y=l*s+u*-a+h*-i-c*-o,this.z=h*s+u*-o+c*-a-l*-i,this},project:function(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)},unproject:function(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)},transformDirection:function(t){var e=this.x,r=this.y,n=this.z,i=t.elements;return this.x=i[0]*e+i[4]*r+i[8]*n,this.y=i[1]*e+i[5]*r+i[9]*n,this.z=i[2]*e+i[6]*r+i[10]*n,this.normalize()},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this},clampScalar:function(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this},clampLength:function(t,e){var r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(t,Math.min(e,r)))},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(t){return this.normalize().multiplyScalar(t)},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this},lerpVectors:function(t,e,r){return this.subVectors(e,t).multiplyScalar(r).add(t)},cross:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(t,e)):this.crossVectors(this,t)},crossVectors:function(t,e){var r=t.x,n=t.y,i=t.z,a=e.x,o=e.y,s=e.z;return this.x=n*s-i*o,this.y=i*a-r*s,this.z=r*o-n*a,this},projectOnVector:function(t){var e=t.dot(this)/t.lengthSq();return this.copy(t).multiplyScalar(e)},projectOnPlane:function(t){return u.copy(this).projectOnVector(t),this.sub(u)},reflect:function(t){return this.sub(u.copy(t).multiplyScalar(2*this.dot(t)))},angleTo:function(t){var e=this.dot(t)/Math.sqrt(this.lengthSq()*t.lengthSq());return Math.acos(s.clamp(e,-1,1))},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,r=this.y-t.y,n=this.z-t.z;return e*e+r*r+n*n},manhattanDistanceTo:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)},setFromSpherical:function(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)},setFromSphericalCoords:function(t,e,r){var n=Math.sin(e)*t;return this.x=n*Math.sin(r),this.y=Math.cos(e)*t,this.z=n*Math.cos(r),this},setFromCylindrical:function(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)},setFromCylindricalCoords:function(t,e,r){return this.x=t*Math.sin(e),this.y=r,this.z=t*Math.cos(e),this},setFromMatrixPosition:function(t){var e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this},setFromMatrixScale:function(t){var e=this.setFromMatrixColumn(t,0).length(),r=this.setFromMatrixColumn(t,1).length(),n=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=r,this.z=n,this},setFromMatrixColumn:function(t,e){return this.fromArray(t.elements,4*e)},equals:function(t){return t.x===this.x&&t.y===this.y&&t.z===this.z},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this.z=t[e+2],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t},fromBufferAttribute:function(t,e,r){return void 0!==r&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute()."),this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}});var f=new d;function m(){this.elements=[1,0,0,0,1,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}Object.assign(m.prototype,{isMatrix3:!0,set:function(t,e,r,n,i,a,o,s,c){var l=this.elements;return l[0]=t,l[1]=n,l[2]=o,l[3]=e,l[4]=i,l[5]=s,l[6]=r,l[7]=a,l[8]=c,this},identity:function(){return this.set(1,0,0,0,1,0,0,0,1),this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(t){var e=this.elements,r=t.elements;return e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=r[3],e[4]=r[4],e[5]=r[5],e[6]=r[6],e[7]=r[7],e[8]=r[8],this},setFromMatrix4:function(t){var e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this},applyToBufferAttribute:function(t){for(var e=0,r=t.count;e1)switch(this.wrapS){case 1e3:t.x=t.x-Math.floor(t.x);break;case 1001:t.x=t.x<0?0:1;break;case 1002:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case 1e3:t.y=t.y-Math.floor(t.y);break;case 1001:t.y=t.y<0?0:1;break;case 1002:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}return this.flipY&&(t.y=1-t.y),t}}),Object.defineProperty(y.prototype,"needsUpdate",{set:function(t){!0===t&&this.version++}}),Object.defineProperties(x.prototype,{width:{get:function(){return this.z},set:function(t){this.z=t}},height:{get:function(){return this.w},set:function(t){this.w=t}}}),Object.assign(x.prototype,{isVector4:!0,set:function(t,e,r,n){return this.x=t,this.y=e,this.z=r,this.w=n,this},setScalar:function(t){return this.x=t,this.y=t,this.z=t,this.w=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setZ:function(t){return this.z=t,this},setW:function(t){return this.w=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y,this.z,this.w)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=void 0!==t.w?t.w:1,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this)},addScalar:function(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this)},subScalar:function(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this},multiplyScalar:function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},applyMatrix4:function(t){var e=this.x,r=this.y,n=this.z,i=this.w,a=t.elements;return this.x=a[0]*e+a[4]*r+a[8]*n+a[12]*i,this.y=a[1]*e+a[5]*r+a[9]*n+a[13]*i,this.z=a[2]*e+a[6]*r+a[10]*n+a[14]*i,this.w=a[3]*e+a[7]*r+a[11]*n+a[15]*i,this},divideScalar:function(t){return this.multiplyScalar(1/t)},setAxisAngleFromQuaternion:function(t){this.w=2*Math.acos(t.w);var e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this},setAxisAngleFromRotationMatrix:function(t){var e,r,n,i,a=t.elements,o=a[0],s=a[4],c=a[8],l=a[1],h=a[5],u=a[9],p=a[2],d=a[6],f=a[10];if(Math.abs(s-l)<.01&&Math.abs(c-p)<.01&&Math.abs(u-d)<.01){if(Math.abs(s+l)<.1&&Math.abs(c+p)<.1&&Math.abs(u+d)<.1&&Math.abs(o+h+f-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;var m=(o+1)/2,g=(h+1)/2,v=(f+1)/2,y=(s+l)/4,x=(c+p)/4,b=(u+d)/4;return m>g&&m>v?m<.01?(r=0,n=.707106781,i=.707106781):(n=y/(r=Math.sqrt(m)),i=x/r):g>v?g<.01?(r=.707106781,n=0,i=.707106781):(r=y/(n=Math.sqrt(g)),i=b/n):v<.01?(r=.707106781,n=.707106781,i=0):(r=x/(i=Math.sqrt(v)),n=b/i),this.set(r,n,i,e),this}var w=Math.sqrt((d-u)*(d-u)+(c-p)*(c-p)+(l-s)*(l-s));return Math.abs(w)<.001&&(w=1),this.x=(d-u)/w,this.y=(c-p)/w,this.z=(l-s)/w,this.w=Math.acos((o+h+f-1)/2),this},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this.w=Math.max(t.w,Math.min(e.w,this.w)),this},clampScalar:function(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this.w=Math.max(t,Math.min(e,this.w)),this},clampLength:function(t,e){var r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(t,Math.min(e,r)))},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this.w=this.w<0?Math.ceil(this.w):Math.floor(this.w),this},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(t){return this.normalize().multiplyScalar(t)},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this},lerpVectors:function(t,e,r){return this.subVectors(e,t).multiplyScalar(r).add(t)},equals:function(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t},fromBufferAttribute:function(t,e,r){return void 0!==r&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute()."),this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),this}}),b.prototype=Object.assign(Object.create(e.prototype),{constructor:b,isWebGLRenderTarget:!0,setSize:function(t,e){this.width===t&&this.height===e||(this.width=t,this.height=e,this.texture.image.width=t,this.texture.image.height=e,this.dispose()),this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.width=t.width,this.height=t.height,this.viewport.copy(t.viewport),this.texture=t.texture.clone(),this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,this.depthTexture=t.depthTexture,this},dispose:function(){this.dispatchEvent({type:"dispose"})}}),w.prototype=Object.assign(Object.create(b.prototype),{constructor:w,isWebGLMultisampleRenderTarget:!0,copy:function(t){return b.prototype.copy.call(this,t),this.samples=t.samples,this}});var _=new d,M=new P,S=new d(0,0,0),T=new d(1,1,1),E=new d,A=new d,L=new d;function P(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}Object.assign(P.prototype,{isMatrix4:!0,set:function(t,e,r,n,i,a,o,s,c,l,h,u,p,d,f,m){var g=this.elements;return g[0]=t,g[4]=e,g[8]=r,g[12]=n,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=h,g[14]=u,g[3]=p,g[7]=d,g[11]=f,g[15]=m,this},identity:function(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this},clone:function(){return(new P).fromArray(this.elements)},copy:function(t){var e=this.elements,r=t.elements;return e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=r[3],e[4]=r[4],e[5]=r[5],e[6]=r[6],e[7]=r[7],e[8]=r[8],e[9]=r[9],e[10]=r[10],e[11]=r[11],e[12]=r[12],e[13]=r[13],e[14]=r[14],e[15]=r[15],this},copyPosition:function(t){var e=this.elements,r=t.elements;return e[12]=r[12],e[13]=r[13],e[14]=r[14],this},extractBasis:function(t,e,r){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),r.setFromMatrixColumn(this,2),this},makeBasis:function(t,e,r){return this.set(t.x,e.x,r.x,0,t.y,e.y,r.y,0,t.z,e.z,r.z,0,0,0,0,1),this},extractRotation:function(t){var e=this.elements,r=t.elements,n=1/_.setFromMatrixColumn(t,0).length(),i=1/_.setFromMatrixColumn(t,1).length(),a=1/_.setFromMatrixColumn(t,2).length();return e[0]=r[0]*n,e[1]=r[1]*n,e[2]=r[2]*n,e[3]=0,e[4]=r[4]*i,e[5]=r[5]*i,e[6]=r[6]*i,e[7]=0,e[8]=r[8]*a,e[9]=r[9]*a,e[10]=r[10]*a,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},makeRotationFromEuler:function(t){t&&t.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var e=this.elements,r=t.x,n=t.y,i=t.z,a=Math.cos(r),o=Math.sin(r),s=Math.cos(n),c=Math.sin(n),l=Math.cos(i),h=Math.sin(i);if("XYZ"===t.order){var u=a*l,p=a*h,d=o*l,f=o*h;e[0]=s*l,e[4]=-s*h,e[8]=c,e[1]=p+d*c,e[5]=u-f*c,e[9]=-o*s,e[2]=f-u*c,e[6]=d+p*c,e[10]=a*s}else if("YXZ"===t.order){var m=s*l,g=s*h,v=c*l,y=c*h;e[0]=m+y*o,e[4]=v*o-g,e[8]=a*c,e[1]=a*h,e[5]=a*l,e[9]=-o,e[2]=g*o-v,e[6]=y+m*o,e[10]=a*s}else if("ZXY"===t.order)m=s*l,g=s*h,v=c*l,y=c*h,e[0]=m-y*o,e[4]=-a*h,e[8]=v+g*o,e[1]=g+v*o,e[5]=a*l,e[9]=y-m*o,e[2]=-a*c,e[6]=o,e[10]=a*s;else if("ZYX"===t.order)u=a*l,p=a*h,d=o*l,f=o*h,e[0]=s*l,e[4]=d*c-p,e[8]=u*c+f,e[1]=s*h,e[5]=f*c+u,e[9]=p*c-d,e[2]=-c,e[6]=o*s,e[10]=a*s;else if("YZX"===t.order){var x=a*s,b=a*c,w=o*s,_=o*c;e[0]=s*l,e[4]=_-x*h,e[8]=w*h+b,e[1]=h,e[5]=a*l,e[9]=-o*l,e[2]=-c*l,e[6]=b*h+w,e[10]=x-_*h}else"XZY"===t.order&&(x=a*s,b=a*c,w=o*s,_=o*c,e[0]=s*l,e[4]=-h,e[8]=c*l,e[1]=x*h+_,e[5]=a*l,e[9]=b*h-w,e[2]=w*h-b,e[6]=o*l,e[10]=_*h+x);return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},makeRotationFromQuaternion:function(t){return this.compose(S,t,T)},lookAt:function(t,e,r){var n=this.elements;return L.subVectors(t,e),0===L.lengthSq()&&(L.z=1),L.normalize(),E.crossVectors(r,L),0===E.lengthSq()&&(1===Math.abs(r.z)?L.x+=1e-4:L.z+=1e-4,L.normalize(),E.crossVectors(r,L)),E.normalize(),A.crossVectors(L,E),n[0]=E.x,n[4]=A.x,n[8]=L.x,n[1]=E.y,n[5]=A.y,n[9]=L.y,n[2]=E.z,n[6]=A.z,n[10]=L.z,this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(t,e)):this.multiplyMatrices(this,t)},premultiply:function(t){return this.multiplyMatrices(t,this)},multiplyMatrices:function(t,e){var r=t.elements,n=e.elements,i=this.elements,a=r[0],o=r[4],s=r[8],c=r[12],l=r[1],h=r[5],u=r[9],p=r[13],d=r[2],f=r[6],m=r[10],g=r[14],v=r[3],y=r[7],x=r[11],b=r[15],w=n[0],_=n[4],M=n[8],S=n[12],T=n[1],E=n[5],A=n[9],L=n[13],R=n[2],P=n[6],C=n[10],O=n[14],D=n[3],N=n[7],I=n[11],z=n[15];return i[0]=a*w+o*T+s*R+c*D,i[4]=a*_+o*E+s*P+c*N,i[8]=a*M+o*A+s*C+c*I,i[12]=a*S+o*L+s*O+c*z,i[1]=l*w+h*T+u*R+p*D,i[5]=l*_+h*E+u*P+p*N,i[9]=l*M+h*A+u*C+p*I,i[13]=l*S+h*L+u*O+p*z,i[2]=d*w+f*T+m*R+g*D,i[6]=d*_+f*E+m*P+g*N,i[10]=d*M+f*A+m*C+g*I,i[14]=d*S+f*L+m*O+g*z,i[3]=v*w+y*T+x*R+b*D,i[7]=v*_+y*E+x*P+b*N,i[11]=v*M+y*A+x*C+b*I,i[15]=v*S+y*L+x*O+b*z,this},multiplyScalar:function(t){var e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this},applyToBufferAttribute:function(t){for(var e=0,r=t.count;e1){for(var e=0;e1){for(var e=0;e0)for(n.children=[],s=0;s0&&(r.geometries=u),p.length>0&&(r.materials=p),d.length>0&&(r.textures=d),f.length>0&&(r.images=f),o.length>0&&(r.shapes=o)}return r.object=n,r;function m(t){var e=[];for(var r in t){var n=t[r];delete n.metadata,e.push(n)}return e}},clone:function(t){return(new this.constructor).copy(this,t)},copy:function(t,e){if(void 0===e&&(e=!0),this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(var r=0;rs)return!1}return!0}Object.assign(ct.prototype,{isBox3:!0,set:function(t,e){return this.min.copy(t),this.max.copy(e),this},setFromArray:function(t){for(var e=1/0,r=1/0,n=1/0,i=-1/0,a=-1/0,o=-1/0,s=0,c=t.length;si&&(i=l),h>a&&(a=h),u>o&&(o=u)}return this.min.set(e,r,n),this.max.set(i,a,o),this},setFromBufferAttribute:function(t){for(var e=1/0,r=1/0,n=1/0,i=-1/0,a=-1/0,o=-1/0,s=0,c=t.count;si&&(i=l),h>a&&(a=h),u>o&&(o=u)}return this.min.set(e,r,n),this.max.set(i,a,o),this},setFromPoints:function(t){this.makeEmpty();for(var e=0,r=t.length;ethis.max.x||t.ythis.max.y||t.zthis.max.z)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z},getParameter:function(t,e){return void 0===e&&(console.warn("THREE.Box3: .getParameter() target is now required"),e=new d),e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y||t.max.zthis.max.z)},intersectsSphere:function(t){return this.clampPoint(t.center,Q),Q.distanceToSquared(t.center)<=t.radius*t.radius},intersectsPlane:function(t){var e,r;return t.normal.x>0?(e=t.normal.x*this.min.x,r=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,r=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,r+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,r+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,r+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,r+=t.normal.z*this.min.z),e<=-t.constant&&r>=-t.constant},intersectsTriangle:function(t){if(this.isEmpty())return!1;this.getCenter(it),at.subVectors(this.max,it),K.subVectors(t.a,it),$.subVectors(t.b,it),tt.subVectors(t.c,it),et.subVectors($,K),rt.subVectors(tt,$),nt.subVectors(K,tt);var e=[0,-et.z,et.y,0,-rt.z,rt.y,0,-nt.z,nt.y,et.z,0,-et.x,rt.z,0,-rt.x,nt.z,0,-nt.x,-et.y,et.x,0,-rt.y,rt.x,0,-nt.y,nt.x,0];return!!lt(e,K,$,tt,at)&&!!lt(e=[1,0,0,0,1,0,0,0,1],K,$,tt,at)&&(ot.crossVectors(et,rt),lt(e=[ot.x,ot.y,ot.z],K,$,tt,at))},clampPoint:function(t,e){return void 0===e&&(console.warn("THREE.Box3: .clampPoint() target is now required"),e=new d),e.copy(t).clamp(this.min,this.max)},distanceToPoint:function(t){return Q.copy(t).clamp(this.min,this.max).sub(t).length()},getBoundingSphere:function(t){return void 0===t&&console.error("THREE.Box3: .getBoundingSphere() target is now required"),this.getCenter(t.center),t.radius=.5*this.getSize(Q).length(),t},intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},applyMatrix4:function(t){return this.isEmpty()||(Z[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Z[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Z[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Z[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Z[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Z[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Z[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Z[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Z)),this},translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}});var ht=new ct;function ut(t,e){this.center=void 0!==t?t:new d,this.radius=void 0!==e?e:0}Object.assign(ut.prototype,{set:function(t,e){return this.center.copy(t),this.radius=e,this},setFromPoints:function(t,e){var r=this.center;void 0!==e?r.copy(e):ht.setFromPoints(t).getCenter(r);for(var n=0,i=0,a=t.length;ithis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e},getBoundingBox:function(t){return void 0===t&&(console.warn("THREE.Sphere: .getBoundingBox() target is now required"),t=new ct),t.set(this.center,this.center),t.expandByScalar(this.radius),t},applyMatrix4:function(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this},translate:function(t){return this.center.add(t),this},equals:function(t){return t.center.equals(this.center)&&t.radius===this.radius}});var pt=new d,dt=new d,ft=new d,mt=new d,gt=new d,vt=new d,yt=new d;function xt(t,e){this.origin=void 0!==t?t:new d,this.direction=void 0!==e?e:new d}Object.assign(xt.prototype,{set:function(t,e){return this.origin.copy(t),this.direction.copy(e),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this},at:function(t,e){return void 0===e&&(console.warn("THREE.Ray: .at() target is now required"),e=new d),e.copy(this.direction).multiplyScalar(t).add(this.origin)},lookAt:function(t){return this.direction.copy(t).sub(this.origin).normalize(),this},recast:function(t){return this.origin.copy(this.at(t,pt)),this},closestPointToPoint:function(t,e){void 0===e&&(console.warn("THREE.Ray: .closestPointToPoint() target is now required"),e=new d),e.subVectors(t,this.origin);var r=e.dot(this.direction);return r<0?e.copy(this.origin):e.copy(this.direction).multiplyScalar(r).add(this.origin)},distanceToPoint:function(t){return Math.sqrt(this.distanceSqToPoint(t))},distanceSqToPoint:function(t){var e=pt.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(pt.copy(this.direction).multiplyScalar(e).add(this.origin),pt.distanceToSquared(t))},distanceSqToSegment:function(t,e,r,n){dt.copy(t).add(e).multiplyScalar(.5),ft.copy(e).sub(t).normalize(),mt.copy(this.origin).sub(dt);var i,a,o,s,c=.5*t.distanceTo(e),l=-this.direction.dot(ft),h=mt.dot(this.direction),u=-mt.dot(ft),p=mt.lengthSq(),d=Math.abs(1-l*l);if(d>0)if(a=l*h-u,s=c*d,(i=l*u-h)>=0)if(a>=-s)if(a<=s){var f=1/d;o=(i*=f)*(i+l*(a*=f)+2*h)+a*(l*i+a+2*u)+p}else a=c,o=-(i=Math.max(0,-(l*a+h)))*i+a*(a+2*u)+p;else a=-c,o=-(i=Math.max(0,-(l*a+h)))*i+a*(a+2*u)+p;else a<=-s?o=-(i=Math.max(0,-(-l*c+h)))*i+(a=i>0?-c:Math.min(Math.max(-c,-u),c))*(a+2*u)+p:a<=s?(i=0,o=(a=Math.min(Math.max(-c,-u),c))*(a+2*u)+p):o=-(i=Math.max(0,-(l*c+h)))*i+(a=i>0?c:Math.min(Math.max(-c,-u),c))*(a+2*u)+p;else a=l>0?-c:c,o=-(i=Math.max(0,-(l*a+h)))*i+a*(a+2*u)+p;return r&&r.copy(this.direction).multiplyScalar(i).add(this.origin),n&&n.copy(ft).multiplyScalar(a).add(dt),o},intersectSphere:function(t,e){pt.subVectors(t.center,this.origin);var r=pt.dot(this.direction),n=pt.dot(pt)-r*r,i=t.radius*t.radius;if(n>i)return null;var a=Math.sqrt(i-n),o=r-a,s=r+a;return o<0&&s<0?null:o<0?this.at(s,e):this.at(o,e)},intersectsSphere:function(t){return this.distanceSqToPoint(t.center)<=t.radius*t.radius},distanceToPlane:function(t){var e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;var r=-(this.origin.dot(t.normal)+t.constant)/e;return r>=0?r:null},intersectPlane:function(t,e){var r=this.distanceToPlane(t);return null===r?null:this.at(r,e)},intersectsPlane:function(t){var e=t.distanceToPoint(this.origin);return 0===e||t.normal.dot(this.direction)*e<0},intersectBox:function(t,e){var r,n,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,h=1/this.direction.z,u=this.origin;return c>=0?(r=(t.min.x-u.x)*c,n=(t.max.x-u.x)*c):(r=(t.max.x-u.x)*c,n=(t.min.x-u.x)*c),l>=0?(i=(t.min.y-u.y)*l,a=(t.max.y-u.y)*l):(i=(t.max.y-u.y)*l,a=(t.min.y-u.y)*l),r>a||i>n?null:((i>r||r!=r)&&(r=i),(a=0?(o=(t.min.z-u.z)*h,s=(t.max.z-u.z)*h):(o=(t.max.z-u.z)*h,s=(t.min.z-u.z)*h),r>s||o>n?null:((o>r||r!=r)&&(r=o),(s=0?r:n,e)))},intersectsBox:function(t){return null!==this.intersectBox(t,pt)},intersectTriangle:function(t,e,r,n,i){gt.subVectors(e,t),vt.subVectors(r,t),yt.crossVectors(gt,vt);var a,o=this.direction.dot(yt);if(o>0){if(n)return null;a=1}else{if(!(o<0))return null;a=-1,o=-o}mt.subVectors(this.origin,t);var s=a*this.direction.dot(vt.crossVectors(mt,vt));if(s<0)return null;var c=a*this.direction.dot(gt.cross(mt));if(c<0)return null;if(s+c>o)return null;var l=-a*mt.dot(yt);return l<0?null:this.at(l/o,i)},applyMatrix4:function(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this},equals:function(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}});var bt=new d,wt=new d,_t=new d,Mt=new d,St=new d,Tt=new d,Et=new d,At=new d,Lt=new d,Rt=new d;function Pt(t,e,r){this.a=void 0!==t?t:new d,this.b=void 0!==e?e:new d,this.c=void 0!==r?r:new d}Object.assign(Pt,{getNormal:function(t,e,r,n){void 0===n&&(console.warn("THREE.Triangle: .getNormal() target is now required"),n=new d),n.subVectors(r,e),bt.subVectors(t,e),n.cross(bt);var i=n.lengthSq();return i>0?n.multiplyScalar(1/Math.sqrt(i)):n.set(0,0,0)},getBarycoord:function(t,e,r,n,i){bt.subVectors(n,e),wt.subVectors(r,e),_t.subVectors(t,e);var a=bt.dot(bt),o=bt.dot(wt),s=bt.dot(_t),c=wt.dot(wt),l=wt.dot(_t),h=a*c-o*o;if(void 0===i&&(console.warn("THREE.Triangle: .getBarycoord() target is now required"),i=new d),0===h)return i.set(-2,-1,-1);var u=1/h,p=(c*s-o*l)*u,f=(a*l-o*s)*u;return i.set(1-p-f,f,p)},containsPoint:function(t,e,r,n){return Pt.getBarycoord(t,e,r,n,Mt),Mt.x>=0&&Mt.y>=0&&Mt.x+Mt.y<=1},getUV:function(t,e,r,n,i,a,o,s){return this.getBarycoord(t,e,r,n,Mt),s.set(0,0),s.addScaledVector(i,Mt.x),s.addScaledVector(a,Mt.y),s.addScaledVector(o,Mt.z),s},isFrontFacing:function(t,e,r,n){return bt.subVectors(r,e),wt.subVectors(t,e),bt.cross(wt).dot(n)<0}}),Object.assign(Pt.prototype,{set:function(t,e,r){return this.a.copy(t),this.b.copy(e),this.c.copy(r),this},setFromPointsAndIndices:function(t,e,r,n){return this.a.copy(t[e]),this.b.copy(t[r]),this.c.copy(t[n]),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this},getArea:function(){return bt.subVectors(this.c,this.b),wt.subVectors(this.a,this.b),.5*bt.cross(wt).length()},getMidpoint:function(t){return void 0===t&&(console.warn("THREE.Triangle: .getMidpoint() target is now required"),t=new d),t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},getNormal:function(t){return Pt.getNormal(this.a,this.b,this.c,t)},getPlane:function(t){return void 0===t&&(console.warn("THREE.Triangle: .getPlane() target is now required"),t=new d),t.setFromCoplanarPoints(this.a,this.b,this.c)},getBarycoord:function(t,e){return Pt.getBarycoord(t,this.a,this.b,this.c,e)},getUV:function(t,e,r,n,i){return Pt.getUV(t,this.a,this.b,this.c,e,r,n,i)},containsPoint:function(t){return Pt.containsPoint(t,this.a,this.b,this.c)},isFrontFacing:function(t){return Pt.isFrontFacing(this.a,this.b,this.c,t)},intersectsBox:function(t){return t.intersectsTriangle(this)},closestPointToPoint:function(t,e){void 0===e&&(console.warn("THREE.Triangle: .closestPointToPoint() target is now required"),e=new d);var r,n,i=this.a,a=this.b,o=this.c;St.subVectors(a,i),Tt.subVectors(o,i),At.subVectors(t,i);var s=St.dot(At),c=Tt.dot(At);if(s<=0&&c<=0)return e.copy(i);Lt.subVectors(t,a);var l=St.dot(Lt),h=Tt.dot(Lt);if(l>=0&&h<=l)return e.copy(a);var u=s*h-l*c;if(u<=0&&s>=0&&l<=0)return r=s/(s-l),e.copy(i).addScaledVector(St,r);Rt.subVectors(t,o);var p=St.dot(Rt),f=Tt.dot(Rt);if(f>=0&&p<=f)return e.copy(o);var m=p*c-s*f;if(m<=0&&c>=0&&f<=0)return n=c/(c-f),e.copy(i).addScaledVector(Tt,n);var g=l*f-p*h;if(g<=0&&h-l>=0&&p-f>=0)return Et.subVectors(o,a),n=(h-l)/(h-l+(p-f)),e.copy(a).addScaledVector(Et,n);var v=1/(g+m+u);return r=m*v,n=u*v,e.copy(i).addScaledVector(St,r).addScaledVector(Tt,n)},equals:function(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}});var Ct={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Ot={h:0,s:0,l:0},Dt={h:0,s:0,l:0};function Nt(t,e,r){return void 0===e&&void 0===r?this.set(t):this.setRGB(t,e,r)}function It(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+6*(e-t)*(2/3-r):t}function zt(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function Bt(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}function Ft(t,e,r,n,i,a){this.a=t,this.b=e,this.c=r,this.normal=n&&n.isVector3?n:new d,this.vertexNormals=Array.isArray(n)?n:[],this.color=i&&i.isColor?i:new Nt,this.vertexColors=Array.isArray(i)?i:[],this.materialIndex=void 0!==a?a:0}Object.assign(Nt.prototype,{isColor:!0,r:1,g:1,b:1,set:function(t){return t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t),this},setScalar:function(t){return this.r=t,this.g=t,this.b=t,this},setHex:function(t){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,this},setRGB:function(t,e,r){return this.r=t,this.g=e,this.b=r,this},setHSL:function(t,e,r){if(t=s.euclideanModulo(t,1),e=s.clamp(e,0,1),r=s.clamp(r,0,1),0===e)this.r=this.g=this.b=r;else{var n=r<=.5?r*(1+e):r+e-r*e,i=2*r-n;this.r=It(i,n,t+1/3),this.g=It(i,n,t),this.b=It(i,n,t-1/3)}return this},setStyle:function(t){function e(e){void 0!==e&&parseFloat(e)<1&&console.warn("THREE.Color: Alpha component of "+t+" will be ignored.")}var r;if(r=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(t)){var n,i=r[1],a=r[2];switch(i){case"rgb":case"rgba":if(n=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(a))return this.r=Math.min(255,parseInt(n[1],10))/255,this.g=Math.min(255,parseInt(n[2],10))/255,this.b=Math.min(255,parseInt(n[3],10))/255,e(n[5]),this;if(n=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(a))return this.r=Math.min(100,parseInt(n[1],10))/100,this.g=Math.min(100,parseInt(n[2],10))/100,this.b=Math.min(100,parseInt(n[3],10))/100,e(n[5]),this;break;case"hsl":case"hsla":if(n=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(a)){var o=parseFloat(n[1])/360,s=parseInt(n[2],10)/100,c=parseInt(n[3],10)/100;return e(n[5]),this.setHSL(o,s,c)}}}else if(r=/^\#([A-Fa-f0-9]+)$/.exec(t)){var l,h=(l=r[1]).length;if(3===h)return this.r=parseInt(l.charAt(0)+l.charAt(0),16)/255,this.g=parseInt(l.charAt(1)+l.charAt(1),16)/255,this.b=parseInt(l.charAt(2)+l.charAt(2),16)/255,this;if(6===h)return this.r=parseInt(l.charAt(0)+l.charAt(1),16)/255,this.g=parseInt(l.charAt(2)+l.charAt(3),16)/255,this.b=parseInt(l.charAt(4)+l.charAt(5),16)/255,this}return t&&t.length>0&&(void 0!==(l=Ct[t])?this.setHex(l):console.warn("THREE.Color: Unknown color "+t)),this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},copyGammaToLinear:function(t,e){return void 0===e&&(e=2),this.r=Math.pow(t.r,e),this.g=Math.pow(t.g,e),this.b=Math.pow(t.b,e),this},copyLinearToGamma:function(t,e){void 0===e&&(e=2);var r=e>0?1/e:1;return this.r=Math.pow(t.r,r),this.g=Math.pow(t.g,r),this.b=Math.pow(t.b,r),this},convertGammaToLinear:function(t){return this.copyGammaToLinear(this,t),this},convertLinearToGamma:function(t){return this.copyLinearToGamma(this,t),this},copySRGBToLinear:function(t){return this.r=zt(t.r),this.g=zt(t.g),this.b=zt(t.b),this},copyLinearToSRGB:function(t){return this.r=Bt(t.r),this.g=Bt(t.g),this.b=Bt(t.b),this},convertSRGBToLinear:function(){return this.copySRGBToLinear(this),this},convertLinearToSRGB:function(){return this.copyLinearToSRGB(this),this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(t){void 0===t&&(console.warn("THREE.Color: .getHSL() target is now required"),t={h:0,s:0,l:0});var e,r,n=this.r,i=this.g,a=this.b,o=Math.max(n,i,a),s=Math.min(n,i,a),c=(s+o)/2;if(s===o)e=0,r=0;else{var l=o-s;switch(r=c<=.5?l/(o+s):l/(2-o-s),o){case n:e=(i-a)/l+(ie&&(e=t[r]);return e}Ut.prototype=Object.assign(Object.create(e.prototype),{constructor:Ut,isMaterial:!0,onBeforeCompile:function(){},setValues:function(t){if(void 0!==t)for(var e in t){var r=t[e];if(void 0!==r)if("shading"!==e){var n=this[e];void 0!==n?n&&n.isColor?n.set(r):n&&n.isVector3&&r&&r.isVector3?n.copy(r):this[e]=r:console.warn("THREE."+this.type+": '"+e+"' is not a property of this material.")}else console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=1===r;else console.warn("THREE.Material: '"+e+"' parameter is undefined.")}},toJSON:function(t){var e=void 0===t||"string"==typeof t;e&&(t={textures:{},images:{}});var r={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};function n(t){var e=[];for(var r in t){var n=t[r];delete n.metadata,e.push(n)}return e}if(r.uuid=this.uuid,r.type=this.type,""!==this.name&&(r.name=this.name),this.color&&this.color.isColor&&(r.color=this.color.getHex()),void 0!==this.roughness&&(r.roughness=this.roughness),void 0!==this.metalness&&(r.metalness=this.metalness),this.emissive&&this.emissive.isColor&&(r.emissive=this.emissive.getHex()),this.emissiveIntensity&&1!==this.emissiveIntensity&&(r.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(r.specular=this.specular.getHex()),void 0!==this.shininess&&(r.shininess=this.shininess),void 0!==this.clearcoat&&(r.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(r.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(r.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,r.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.map&&this.map.isTexture&&(r.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(r.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(r.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(r.lightMap=this.lightMap.toJSON(t).uuid),this.aoMap&&this.aoMap.isTexture&&(r.aoMap=this.aoMap.toJSON(t).uuid,r.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(r.bumpMap=this.bumpMap.toJSON(t).uuid,r.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(r.normalMap=this.normalMap.toJSON(t).uuid,r.normalMapType=this.normalMapType,r.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(r.displacementMap=this.displacementMap.toJSON(t).uuid,r.displacementScale=this.displacementScale,r.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(r.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(r.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(r.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(r.specularMap=this.specularMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(r.envMap=this.envMap.toJSON(t).uuid,r.reflectivity=this.reflectivity,r.refractionRatio=this.refractionRatio,void 0!==this.combine&&(r.combine=this.combine),void 0!==this.envMapIntensity&&(r.envMapIntensity=this.envMapIntensity)),this.gradientMap&&this.gradientMap.isTexture&&(r.gradientMap=this.gradientMap.toJSON(t).uuid),void 0!==this.size&&(r.size=this.size),void 0!==this.sizeAttenuation&&(r.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(r.blending=this.blending),!0===this.flatShading&&(r.flatShading=this.flatShading),0!==this.side&&(r.side=this.side),0!==this.vertexColors&&(r.vertexColors=this.vertexColors),this.opacity<1&&(r.opacity=this.opacity),!0===this.transparent&&(r.transparent=this.transparent),r.depthFunc=this.depthFunc,r.depthTest=this.depthTest,r.depthWrite=this.depthWrite,r.stencilWrite=this.stencilWrite,r.stencilFunc=this.stencilFunc,r.stencilRef=this.stencilRef,r.stencilMask=this.stencilMask,r.stencilFail=this.stencilFail,r.stencilZFail=this.stencilZFail,r.stencilZPass=this.stencilZPass,this.rotation&&0!==this.rotation&&(r.rotation=this.rotation),!0===this.polygonOffset&&(r.polygonOffset=!0),0!==this.polygonOffsetFactor&&(r.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(r.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth&&1!==this.linewidth&&(r.linewidth=this.linewidth),void 0!==this.dashSize&&(r.dashSize=this.dashSize),void 0!==this.gapSize&&(r.gapSize=this.gapSize),void 0!==this.scale&&(r.scale=this.scale),!0===this.dithering&&(r.dithering=!0),this.alphaTest>0&&(r.alphaTest=this.alphaTest),!0===this.premultipliedAlpha&&(r.premultipliedAlpha=this.premultipliedAlpha),!0===this.wireframe&&(r.wireframe=this.wireframe),this.wireframeLinewidth>1&&(r.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(r.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(r.wireframeLinejoin=this.wireframeLinejoin),!0===this.morphTargets&&(r.morphTargets=!0),!0===this.morphNormals&&(r.morphNormals=!0),!0===this.skinning&&(r.skinning=!0),!1===this.visible&&(r.visible=!1),!1===this.toneMapped&&(r.toneMapped=!1),"{}"!==JSON.stringify(this.userData)&&(r.userData=this.userData),e){var i=n(t.textures),a=n(t.images);i.length>0&&(r.textures=i),a.length>0&&(r.images=a)}return r},clone:function(){return(new this.constructor).copy(this)},copy:function(t){this.name=t.name,this.fog=t.fog,this.lights=t.lights,this.blending=t.blending,this.side=t.side,this.flatShading=t.flatShading,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWrite=t.stencilWrite,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilMask=t.stencilMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.premultipliedAlpha=t.premultipliedAlpha,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this.clipShadows=t.clipShadows,this.clipIntersection=t.clipIntersection;var e=t.clippingPlanes,r=null;if(null!==e){var n=e.length;r=new Array(n);for(var i=0;i!==n;++i)r[i]=e[i].clone()}return this.clippingPlanes=r,this.shadowSide=t.shadowSide,this},dispose:function(){this.dispatchEvent({type:"dispose"})}}),Ht.prototype=Object.create(Ut.prototype),Ht.prototype.constructor=Ht,Ht.prototype.isMeshBasicMaterial=!0,Ht.prototype.copy=function(t){return Ut.prototype.copy.call(this,t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.skinning=t.skinning,this.morphTargets=t.morphTargets,this},Object.defineProperty(Vt.prototype,"needsUpdate",{set:function(t){!0===t&&this.version++}}),Object.assign(Vt.prototype,{isBufferAttribute:!0,onUploadCallback:function(){},setArray:function(t){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");return this.count=void 0!==t?t.length/this.itemSize:0,this.array=t,this},setDynamic:function(t){return this.dynamic=t,this},copy:function(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.dynamic=t.dynamic,this},copyAt:function(t,e,r){t*=this.itemSize,r*=e.itemSize;for(var n=0,i=this.itemSize;n0,o=i[1]&&i[1].length>0,s=t.morphTargets,c=s.length;if(c>0){e=[];for(var h=0;h0){for(u=[],h=0;h0&&0===r.length&&console.error("THREE.DirectGeometry: Faceless geometries are not supported."),h=0;h65535?Jt:Xt)(t,1):this.index=t},addAttribute:function(t,e){return e&&e.isBufferAttribute||e&&e.isInterleavedBufferAttribute?"index"===t?(console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),this.setIndex(e),this):(this.attributes[t]=e,this):(console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),this.addAttribute(t,new Vt(arguments[1],arguments[2])))},getAttribute:function(t){return this.attributes[t]},removeAttribute:function(t){return delete this.attributes[t],this},addGroup:function(t,e,r){this.groups.push({start:t,count:e,materialIndex:void 0!==r?r:0})},clearGroups:function(){this.groups=[]},setDrawRange:function(t,e){this.drawRange.start=t,this.drawRange.count=e},applyMatrix:function(t){var e=this.attributes.position;void 0!==e&&(t.applyToBufferAttribute(e),e.needsUpdate=!0);var r=this.attributes.normal;void 0!==r&&((new m).getNormalMatrix(t).applyToBufferAttribute(r),r.needsUpdate=!0);var n=this.attributes.tangent;return void 0!==n&&((new m).getNormalMatrix(t).applyToBufferAttribute(n),n.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this},rotateX:function(t){return ee.makeRotationX(t),this.applyMatrix(ee),this},rotateY:function(t){return ee.makeRotationY(t),this.applyMatrix(ee),this},rotateZ:function(t){return ee.makeRotationZ(t),this.applyMatrix(ee),this},translate:function(t,e,r){return ee.makeTranslation(t,e,r),this.applyMatrix(ee),this},scale:function(t,e,r){return ee.makeScale(t,e,r),this.applyMatrix(ee),this},lookAt:function(t){return re.lookAt(t),re.updateMatrix(),this.applyMatrix(re.matrix),this},center:function(){return this.computeBoundingBox(),this.boundingBox.getCenter(ne).negate(),this.translate(ne.x,ne.y,ne.z),this},setFromObject:function(t){var e=t.geometry;if(t.isPoints||t.isLine){var r=new Zt(3*e.vertices.length,3),n=new Zt(3*e.colors.length,3);if(this.addAttribute("position",r.copyVector3sArray(e.vertices)),this.addAttribute("color",n.copyColorsArray(e.colors)),e.lineDistances&&e.lineDistances.length===e.vertices.length){var i=new Zt(e.lineDistances.length,1);this.addAttribute("lineDistance",i.copyArray(e.lineDistances))}null!==e.boundingSphere&&(this.boundingSphere=e.boundingSphere.clone()),null!==e.boundingBox&&(this.boundingBox=e.boundingBox.clone())}else t.isMesh&&e&&e.isGeometry&&this.fromGeometry(e);return this},setFromPoints:function(t){for(var e=[],r=0,n=t.length;r0){var r=new Float32Array(3*t.normals.length);this.addAttribute("normal",new Vt(r,3).copyVector3sArray(t.normals))}if(t.colors.length>0){var n=new Float32Array(3*t.colors.length);this.addAttribute("color",new Vt(n,3).copyColorsArray(t.colors))}if(t.uvs.length>0){var i=new Float32Array(2*t.uvs.length);this.addAttribute("uv",new Vt(i,2).copyVector2sArray(t.uvs))}if(t.uvs2.length>0){var a=new Float32Array(2*t.uvs2.length);this.addAttribute("uv2",new Vt(a,2).copyVector2sArray(t.uvs2))}for(var o in this.groups=t.groups,t.morphTargets){for(var s=[],c=t.morphTargets[o],l=0,h=c.length;l0){var d=new Zt(4*t.skinIndices.length,4);this.addAttribute("skinIndex",d.copyVector4sArray(t.skinIndices))}if(t.skinWeights.length>0){var f=new Zt(4*t.skinWeights.length,4);this.addAttribute("skinWeight",f.copyVector4sArray(t.skinWeights))}return null!==t.boundingSphere&&(this.boundingSphere=t.boundingSphere.clone()),null!==t.boundingBox&&(this.boundingBox=t.boundingBox.clone()),this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new ct);var t=this.attributes.position,e=this.morphAttributes.position;if(void 0!==t){if(this.boundingBox.setFromBufferAttribute(t),e)for(var r=0,n=e.length;r0&&(t.userData=this.userData),void 0!==this.parameters){var e=this.parameters;for(var r in e)void 0!==e[r]&&(t[r]=e[r]);return t}t.data={attributes:{}};var n=this.index;null!==n&&(t.data.index={type:n.array.constructor.name,array:Array.prototype.slice.call(n.array)});var i=this.attributes;for(var r in i){var a=(p=i[r]).toJSON();""!==p.name&&(a.name=p.name),t.data.attributes[r]=a}var o={},s=!1;for(var r in this.morphAttributes){for(var c=this.morphAttributes[r],l=[],h=0,u=c.length;h0&&(o[r]=l,s=!0)}s&&(t.data.morphAttributes=o);var d=this.groups;d.length>0&&(t.data.groups=JSON.parse(JSON.stringify(d)));var f=this.boundingSphere;return null!==f&&(t.data.boundingSphere={center:f.center.toArray(),radius:f.radius}),t},clone:function(){return(new se).copy(this)},copy:function(t){var e,r,n;this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.name=t.name;var i=t.index;null!==i&&this.setIndex(i.clone());var a=t.attributes;for(e in a){var o=a[e];this.addAttribute(e,o.clone())}var s=t.morphAttributes;for(e in s){var c=[],l=s[e];for(r=0,n=l.length;rr.far?null:{distance:c,point:Se.clone(),object:t}}function Ae(t,e,r,n,i,a,o,s,c,h,u){ue.fromBufferAttribute(i,c),pe.fromBufferAttribute(i,h),de.fromBufferAttribute(i,u);var p=t.morphTargetInfluences;if(e.morphTargets&&a&&p){ve.set(0,0,0),ye.set(0,0,0),xe.set(0,0,0);for(var d=0,f=a.length;d0){var o=i[a[0]];if(void 0!==o)for(this.morphTargetInfluences=[],this.morphTargetDictionary={},t=0,e=o.length;t0&&console.error("THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}},raycast:function(t,e){var r,n=this.geometry,i=this.material,a=this.matrixWorld;if(void 0!==i&&(null===n.boundingSphere&&n.computeBoundingSphere(),he.copy(n.boundingSphere),he.applyMatrix4(a),!1!==t.ray.intersectsSphere(he)&&(ce.getInverse(a),le.copy(t.ray).applyMatrix4(ce),null===n.boundingBox||!1!==le.intersectsBox(n.boundingBox))))if(n.isBufferGeometry){var o,s,c,h,u,p,d,f,m,g=n.index,v=n.attributes.position,y=n.morphAttributes.position,x=n.attributes.uv,b=n.attributes.uv2,w=n.groups,_=n.drawRange;if(null!==g)if(Array.isArray(i))for(h=0,p=w.length;h0&&(E=P);for(var C=0,O=R.length;C0?1:-1,l.push(P.x,P.y,P.z),h.push(x/g),h.push(1-b/v),L+=1}}for(b=0;b0)for(h=0;h0&&(this.normalsNeedUpdate=!0)},computeFlatVertexNormals:function(){var t,e,r;for(this.computeFaceNormals(),t=0,e=this.faces.length;t0&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var t,e,r,n,i;for(r=0,n=this.faces.length;r=0;r--){var f=p[r];for(this.faces.splice(f,1),o=0,s=this.faceVertexUvs.length;o0,g=d.vertexNormals.length>0,v=1!==d.color.r||1!==d.color.g||1!==d.color.b,y=d.vertexColors.length>0,x=0;if(x=M(x,0,0),x=M(x,1,!0),x=M(x,2,!1),x=M(x,3,f),x=M(x,4,m),x=M(x,5,g),x=M(x,6,v),x=M(x,7,y),o.push(x),o.push(d.a,d.b,d.c),o.push(d.materialIndex),f){var b=this.faceVertexUvs[0][i];o.push(E(b[0]),E(b[1]),E(b[2]))}if(m&&o.push(S(d.normal)),g){var w=d.vertexNormals;o.push(S(w[0]),S(w[1]),S(w[2]))}if(v&&o.push(T(d.color)),y){var _=d.vertexColors;o.push(T(_[0]),T(_[1]),T(_[2]))}}function M(t,e,r){return r?t|1<0&&(t.data.colors=l),u.length>0&&(t.data.uvs=[u]),t.data.faces=o,t},clone:function(){return(new Oe).copy(this)},copy:function(t){var e,r,n,i,a,o;this.vertices=[],this.colors=[],this.faces=[],this.faceVertexUvs=[[]],this.morphTargets=[],this.morphNormals=[],this.skinWeights=[],this.skinIndices=[],this.lineDistances=[],this.boundingBox=null,this.boundingSphere=null,this.name=t.name;var s=t.vertices;for(e=0,r=s.length;e0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader;var i={};for(var a in this.extensions)!0===this.extensions[a]&&(i[a]=!0);return Object.keys(i).length>0&&(e.extensions=i),e},Ge.prototype=Object.assign(Object.create(Y.prototype),{constructor:Ge,isCamera:!0,copy:function(t,e){return Y.prototype.copy.call(this,t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this},getWorldDirection:function(t){void 0===t&&(console.warn("THREE.Camera: .getWorldDirection() target is now required"),t=new d),this.updateMatrixWorld(!0);var e=this.matrixWorld.elements;return t.set(-e[8],-e[9],-e[10]).normalize()},updateMatrixWorld:function(t){Y.prototype.updateMatrixWorld.call(this,t),this.matrixWorldInverse.getInverse(this.matrixWorld)},clone:function(){return(new this.constructor).copy(this)}}),Ue.prototype=Object.assign(Object.create(Ge.prototype),{constructor:Ue,isPerspectiveCamera:!0,copy:function(t,e){return Ge.prototype.copy.call(this,t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=null===t.view?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this},setFocalLength:function(t){var e=.5*this.getFilmHeight()/t;this.fov=2*s.RAD2DEG*Math.atan(e),this.updateProjectionMatrix()},getFocalLength:function(){var t=Math.tan(.5*s.DEG2RAD*this.fov);return.5*this.getFilmHeight()/t},getEffectiveFOV:function(){return 2*s.RAD2DEG*Math.atan(Math.tan(.5*s.DEG2RAD*this.fov)/this.zoom)},getFilmWidth:function(){return this.filmGauge*Math.min(this.aspect,1)},getFilmHeight:function(){return this.filmGauge/Math.max(this.aspect,1)},setViewOffset:function(t,e,r,n,i,a){this.aspect=t/e,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=r,this.view.offsetY=n,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()},clearViewOffset:function(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()},updateProjectionMatrix:function(){var t=this.near,e=t*Math.tan(.5*s.DEG2RAD*this.fov)/this.zoom,r=2*e,n=this.aspect*r,i=-.5*n,a=this.view;if(null!==this.view&&this.view.enabled){var o=a.fullWidth,c=a.fullHeight;i+=a.offsetX*n/o,e-=a.offsetY*r/c,n*=a.width/o,r*=a.height/c}var l=this.filmOffset;0!==l&&(i+=t*l/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+n,e,e-r,t,this.far),this.projectionMatrixInverse.getInverse(this.projectionMatrix)},toJSON:function(t){var e=Y.prototype.toJSON.call(this,t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,null!==this.view&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}),He.prototype=Object.create(Y.prototype),He.prototype.constructor=He,Ve.prototype=Object.create(b.prototype),Ve.prototype.constructor=Ve,Ve.prototype.isWebGLRenderTargetCube=!0,Ve.prototype.fromEquirectangularTexture=function(t,e){this.texture.type=e.type,this.texture.format=e.format,this.texture.encoding=e.encoding;var r=new J,n={uniforms:{tEquirect:{value:null}},vertexShader:["varying vec3 vWorldDirection;","vec3 transformDirection( in vec3 dir, in mat4 matrix ) {","\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );","}","void main() {","\tvWorldDirection = transformDirection( position, modelMatrix );","\t#include ","\t#include ","}"].join("\n"),fragmentShader:["uniform sampler2D tEquirect;","varying vec3 vWorldDirection;","#define RECIPROCAL_PI 0.31830988618","#define RECIPROCAL_PI2 0.15915494","void main() {","\tvec3 direction = normalize( vWorldDirection );","\tvec2 sampleUV;","\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;","\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;","\tgl_FragColor = texture2D( tEquirect, sampleUV );","}"].join("\n")},i=new Fe({type:"CubemapFromEquirect",uniforms:Ie(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=e;var a=new Te(new Ne(5,5,5),i);r.add(a);var o=new He(1,10,1);return o.renderTarget=this,o.renderTarget.texture.name="CubeCameraTexture",o.update(t,r),a.geometry.dispose(),a.material.dispose(),this},je.prototype=Object.create(y.prototype),je.prototype.constructor=je,je.prototype.isDataTexture=!0;var ke=new d,We=new d,qe=new m;function Xe(t,e){this.normal=void 0!==t?t:new d(1,0,0),this.constant=void 0!==e?e:0}Object.assign(Xe.prototype,{isPlane:!0,set:function(t,e){return this.normal.copy(t),this.constant=e,this},setComponents:function(t,e,r,n){return this.normal.set(t,e,r),this.constant=n,this},setFromNormalAndCoplanarPoint:function(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this},setFromCoplanarPoints:function(t,e,r){var n=ke.subVectors(r,e).cross(We.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(n,t),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.normal.copy(t.normal),this.constant=t.constant,this},normalize:function(){var t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this},negate:function(){return this.constant*=-1,this.normal.negate(),this},distanceToPoint:function(t){return this.normal.dot(t)+this.constant},distanceToSphere:function(t){return this.distanceToPoint(t.center)-t.radius},projectPoint:function(t,e){return void 0===e&&(console.warn("THREE.Plane: .projectPoint() target is now required"),e=new d),e.copy(this.normal).multiplyScalar(-this.distanceToPoint(t)).add(t)},intersectLine:function(t,e){void 0===e&&(console.warn("THREE.Plane: .intersectLine() target is now required"),e=new d);var r=t.delta(ke),n=this.normal.dot(r);if(0===n)return 0===this.distanceToPoint(t.start)?e.copy(t.start):void 0;var i=-(t.start.dot(this.normal)+this.constant)/n;return i<0||i>1?void 0:e.copy(r).multiplyScalar(i).add(t.start)},intersectsLine:function(t){var e=this.distanceToPoint(t.start),r=this.distanceToPoint(t.end);return e<0&&r>0||r<0&&e>0},intersectsBox:function(t){return t.intersectsPlane(this)},intersectsSphere:function(t){return t.intersectsPlane(this)},coplanarPoint:function(t){return void 0===t&&(console.warn("THREE.Plane: .coplanarPoint() target is now required"),t=new d),t.copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(t,e){var r=e||qe.getNormalMatrix(t),n=this.coplanarPoint(ke).applyMatrix4(t),i=this.normal.applyMatrix3(r).normalize();return this.constant=-n.dot(i),this},translate:function(t){return this.constant-=t.dot(this.normal),this},equals:function(t){return t.normal.equals(this.normal)&&t.constant===this.constant}});var Ye=new ut,Je=new d;function Ze(t,e,r,n,i,a){this.planes=[void 0!==t?t:new Xe,void 0!==e?e:new Xe,void 0!==r?r:new Xe,void 0!==n?n:new Xe,void 0!==i?i:new Xe,void 0!==a?a:new Xe]}Object.assign(Ze.prototype,{set:function(t,e,r,n,i,a){var o=this.planes;return o[0].copy(t),o[1].copy(e),o[2].copy(r),o[3].copy(n),o[4].copy(i),o[5].copy(a),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){for(var e=this.planes,r=0;r<6;r++)e[r].copy(t.planes[r]);return this},setFromMatrix:function(t){var e=this.planes,r=t.elements,n=r[0],i=r[1],a=r[2],o=r[3],s=r[4],c=r[5],l=r[6],h=r[7],u=r[8],p=r[9],d=r[10],f=r[11],m=r[12],g=r[13],v=r[14],y=r[15];return e[0].setComponents(o-n,h-s,f-u,y-m).normalize(),e[1].setComponents(o+n,h+s,f+u,y+m).normalize(),e[2].setComponents(o+i,h+c,f+p,y+g).normalize(),e[3].setComponents(o-i,h-c,f-p,y-g).normalize(),e[4].setComponents(o-a,h-l,f-d,y-v).normalize(),e[5].setComponents(o+a,h+l,f+d,y+v).normalize(),this},intersectsObject:function(t){var e=t.geometry;return null===e.boundingSphere&&e.computeBoundingSphere(),Ye.copy(e.boundingSphere).applyMatrix4(t.matrixWorld),this.intersectsSphere(Ye)},intersectsSprite:function(t){return Ye.center.set(0,0,0),Ye.radius=.7071067811865476,Ye.applyMatrix4(t.matrixWorld),this.intersectsSphere(Ye)},intersectsSphere:function(t){for(var e=this.planes,r=t.center,n=-t.radius,i=0;i<6;i++)if(e[i].distanceToPoint(r)0?t.max.x:t.min.x,Je.y=n.normal.y>0?t.max.y:t.min.y,Je.z=n.normal.z>0?t.max.z:t.min.z,n.distanceToPoint(Je)<0)return!1}return!0},containsPoint:function(t){for(var e=this.planes,r=0;r<6;r++)if(e[r].distanceToPoint(t)<0)return!1;return!0}});var Qe={alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",alphatest_fragment:"#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",begin_vertex:"vec3 transformed = vec3( position );",beginnormal_vertex:"vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif",bsdfs:"vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif",bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif",clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif",color_fragment:"#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif",color_vertex:"#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif",common:"#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV( sampler2D envMap, vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = normalMatrix * objectTangent;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",encodings_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",encodings_pars_fragment:"\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t vec3 reflectVec = reflect( -viewDir, normal );\n\t\t reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t vec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryReflectVec, roughness );\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif",lightmap_fragment:"#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_vertex:"vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif",lights_pars_begin:"uniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = saturate( clearcoat );\tmaterial.clearcoatRoughness = clamp( clearcoatRoughness, 0.04, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectDiffuse += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\tgl_Position.z *= gl_Position.w;\n\t#endif\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif",map_particle_pars_fragment:"#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif",normal_fragment_begin:"#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;",normal_fragment_maps:"#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\t#ifdef USE_TANGENT\n\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, normalScale, normalMap );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 normalScale, in sampler2D normalMap ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy *= normalScale;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvec3 NfromST = cross( S, T );\n\t\t\tif( dot( NfromST, N ) > 0.0 ) {\n\t\t\t\tS *= -1.0;\n\t\t\t\tT *= -1.0;\n\t\t\t}\n\t\t#else\n\t\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 vTBN = mat3( tangent, bitangent, clearcoatNormal );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = clearcoatNormalScale * mapN.xy;\n\t\tclearcoatNormal = normalize( vTBN * mapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatNormalScale, clearcoatNormalMap );\n\t#endif\n#endif",clearcoat_normalmap_pars_fragment:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 encodeHalfRGBA ( vec2 v ) {\n\tvec4 encoded = vec4( 0.0 );\n\tconst vec2 offset = vec2( 1.0 / 255.0, 0.0 );\n\tencoded.xy = vec2( v.x, fract( v.x * 255.0 ) );\n\tencoded.xy = encoded.xy - ( encoded.yy * offset );\n\tencoded.zw = vec2( v.y, fract( v.y * 255.0 ) );\n\tencoded.zw = encoded.zw - ( encoded.ww * offset );\n\treturn encoded;\n}\nvec2 decodeHalfRGBA( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn decodeHalfRGBA( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = ( floor( uv * size - 0.5 ) + 0.5 ) * texelSize;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif",shadowmap_pars_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n\t#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( ( color * ( 2.51 * color + 0.03 ) ) / ( color * ( 2.43 * color + 0.59 ) + 0.14 ) );\n}",uv_pars_fragment:"#ifdef USE_UV\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#ifdef USE_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif",uv_vertex:"#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif",uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif",background_frag:"uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include \n\t#include \n}",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include \n\t#include \n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_frag:"uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSPARENCY\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSPARENCY\n\tuniform float transparency;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSPARENCY\n\t\tdiffuseColor.a *= saturate( 1. - transparency + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}",normal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}",normal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}",points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n}",shadow_vert:"#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"},Ke={common:{diffuse:{value:new Nt(15658734)},opacity:{value:1},map:{value:null},uvTransform:{value:new m},alphaMap:{value:null}},specularmap:{specularMap:{value:null}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},refractionRatio:{value:.98},maxMipLevel:{value:0}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new l(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Nt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}}},points:{diffuse:{value:new Nt(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},uvTransform:{value:new m}},sprite:{diffuse:{value:new Nt(15658734)},opacity:{value:1},center:{value:new l(.5,.5)},rotation:{value:0},map:{value:null},uvTransform:{value:new m}}},$e={basic:{uniforms:ze([Ke.common,Ke.specularmap,Ke.envmap,Ke.aomap,Ke.lightmap,Ke.fog]),vertexShader:Qe.meshbasic_vert,fragmentShader:Qe.meshbasic_frag},lambert:{uniforms:ze([Ke.common,Ke.specularmap,Ke.envmap,Ke.aomap,Ke.lightmap,Ke.emissivemap,Ke.fog,Ke.lights,{emissive:{value:new Nt(0)}}]),vertexShader:Qe.meshlambert_vert,fragmentShader:Qe.meshlambert_frag},phong:{uniforms:ze([Ke.common,Ke.specularmap,Ke.envmap,Ke.aomap,Ke.lightmap,Ke.emissivemap,Ke.bumpmap,Ke.normalmap,Ke.displacementmap,Ke.gradientmap,Ke.fog,Ke.lights,{emissive:{value:new Nt(0)},specular:{value:new Nt(1118481)},shininess:{value:30}}]),vertexShader:Qe.meshphong_vert,fragmentShader:Qe.meshphong_frag},standard:{uniforms:ze([Ke.common,Ke.envmap,Ke.aomap,Ke.lightmap,Ke.emissivemap,Ke.bumpmap,Ke.normalmap,Ke.displacementmap,Ke.roughnessmap,Ke.metalnessmap,Ke.fog,Ke.lights,{emissive:{value:new Nt(0)},roughness:{value:.5},metalness:{value:.5},envMapIntensity:{value:1}}]),vertexShader:Qe.meshphysical_vert,fragmentShader:Qe.meshphysical_frag},matcap:{uniforms:ze([Ke.common,Ke.bumpmap,Ke.normalmap,Ke.displacementmap,Ke.fog,{matcap:{value:null}}]),vertexShader:Qe.meshmatcap_vert,fragmentShader:Qe.meshmatcap_frag},points:{uniforms:ze([Ke.points,Ke.fog]),vertexShader:Qe.points_vert,fragmentShader:Qe.points_frag},dashed:{uniforms:ze([Ke.common,Ke.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Qe.linedashed_vert,fragmentShader:Qe.linedashed_frag},depth:{uniforms:ze([Ke.common,Ke.displacementmap]),vertexShader:Qe.depth_vert,fragmentShader:Qe.depth_frag},normal:{uniforms:ze([Ke.common,Ke.bumpmap,Ke.normalmap,Ke.displacementmap,{opacity:{value:1}}]),vertexShader:Qe.normal_vert,fragmentShader:Qe.normal_frag},sprite:{uniforms:ze([Ke.sprite,Ke.fog]),vertexShader:Qe.sprite_vert,fragmentShader:Qe.sprite_frag},background:{uniforms:{uvTransform:{value:new m},t2D:{value:null}},vertexShader:Qe.background_vert,fragmentShader:Qe.background_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Qe.cube_vert,fragmentShader:Qe.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Qe.equirect_vert,fragmentShader:Qe.equirect_frag},distanceRGBA:{uniforms:ze([Ke.common,Ke.displacementmap,{referencePosition:{value:new d},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Qe.distanceRGBA_vert,fragmentShader:Qe.distanceRGBA_frag},shadow:{uniforms:ze([Ke.lights,Ke.fog,{color:{value:new Nt(0)},opacity:{value:1}}]),vertexShader:Qe.shadow_vert,fragmentShader:Qe.shadow_frag}};function tr(){var t=null,e=!1,r=null;function n(i,a){!1!==e&&(r(i,a),t.requestAnimationFrame(n))}return{start:function(){!0!==e&&null!==r&&(t.requestAnimationFrame(n),e=!0)},stop:function(){e=!1},setAnimationLoop:function(t){r=t},setContext:function(e){t=e}}}function er(t){var e=new WeakMap;return{get:function(t){return t.isInterleavedBufferAttribute&&(t=t.data),e.get(t)},remove:function(r){r.isInterleavedBufferAttribute&&(r=r.data);var n=e.get(r);n&&(t.deleteBuffer(n.buffer),e.delete(r))},update:function(r,n){r.isInterleavedBufferAttribute&&(r=r.data);var i=e.get(r);void 0===i?e.set(r,function(e,r){var n=e.array,i=e.dynamic?35048:35044,a=t.createBuffer();t.bindBuffer(r,a),t.bufferData(r,n,i),e.onUploadCallback();var o=5126;return n instanceof Float32Array?o=5126:n instanceof Float64Array?console.warn("THREE.WebGLAttributes: Unsupported data buffer format: Float64Array."):n instanceof Uint16Array?o=5123:n instanceof Int16Array?o=5122:n instanceof Uint32Array?o=5125:n instanceof Int32Array?o=5124:n instanceof Int8Array?o=5120:n instanceof Uint8Array&&(o=5121),{buffer:a,type:o,bytesPerElement:n.BYTES_PER_ELEMENT,version:e.version}}(r,n)):i.version0&&t.getShaderPrecisionFormat(35632,36338).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(35633,36337).precision>0&&t.getShaderPrecisionFormat(35632,36337).precision>0?"mediump":"lowp"}var a="undefined"!=typeof WebGL2RenderingContext&&t instanceof WebGL2RenderingContext,o=void 0!==r.precision?r.precision:"highp",s=i(o);s!==o&&(console.warn("THREE.WebGLRenderer:",o,"not supported, using",s,"instead."),o=s);var c=!0===r.logarithmicDepthBuffer,l=t.getParameter(34930),h=t.getParameter(35660),u=t.getParameter(3379),p=t.getParameter(34076),d=t.getParameter(34921),f=t.getParameter(36347),m=t.getParameter(36348),g=t.getParameter(36349),v=h>0,y=a||!!e.get("OES_texture_float");return{isWebGL2:a,getMaxAnisotropy:function(){if(void 0!==n)return n;var r=e.get("EXT_texture_filter_anisotropic");return n=null!==r?t.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0},getMaxPrecision:i,precision:o,logarithmicDepthBuffer:c,maxTextures:l,maxVertexTextures:h,maxTextureSize:u,maxCubemapSize:p,maxAttributes:d,maxVertexUniforms:f,maxVaryings:m,maxFragmentUniforms:g,vertexTextures:v,floatFragmentTextures:y,floatVertexTextures:v&&y,maxSamples:a?t.getParameter(36183):0}}function sr(){var t=this,e=null,r=0,n=!1,i=!1,a=new Xe,o=new m,s={value:null,needsUpdate:!1};function c(){s.value!==e&&(s.value=e,s.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0}function l(e,r,n,i){var c=null!==e?e.length:0,l=null;if(0!==c){if(l=s.value,!0!==i||null===l){var h=n+4*c,u=r.matrixWorldInverse;o.getNormalMatrix(u),(null===l||l.length65535?Jt:Xt)(r,1);d.version=o,e.update(d,34963);var f=i.get(t);f&&e.remove(f),i.set(t,d)}return{get:function(t,e){var i=n.get(e);return i||(e.addEventListener("dispose",a),e.isBufferGeometry?i=e:e.isGeometry&&(void 0===e._bufferGeometry&&(e._bufferGeometry=(new se).setFromObject(t)),i=e._bufferGeometry),n.set(e,i),r.memory.geometries++,i)},update:function(t){var r=t.index,n=t.attributes;for(var i in null!==r&&e.update(r,34963),n)e.update(n[i],34962);var a=t.morphAttributes;for(var i in a)for(var o=a[i],s=0,c=o.length;s0)return t;var i=e*r,a=_r[i];if(void 0===a&&(a=new Float32Array(i),_r[i]=a),0!==e){n.toArray(a,0);for(var o=1,s=0;o!==e;++o)s+=r,t[o].toArray(a,s)}return a}function Lr(t,e){if(t.length!==e.length)return!1;for(var r=0,n=t.length;r/gm,(function(t,e){var r=Qe[e];if(void 0===r)throw new Error("Can not resolve #include <"+e+">");return _n(r)}))}function Mn(t){return t.replace(/#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,(function(t,e,r,n){for(var i="",a=parseInt(e);a0?t.gammaFactor:1,w=o.isWebGL2?"":function(t,e,r){return[(t=t||{}).derivatives||e.envMapCubeUV||e.bumpMap||e.tangentSpaceNormalMap||e.clearcoatNormalMap||e.flatShading?"#extension GL_OES_standard_derivatives : enable":"",(t.fragDepth||e.logarithmicDepthBuffer)&&r.get("EXT_frag_depth")?"#extension GL_EXT_frag_depth : enable":"",t.drawBuffers&&r.get("WEBGL_draw_buffers")?"#extension GL_EXT_draw_buffers : require":"",(t.shaderTextureLOD||e.envMap)&&r.get("EXT_shader_texture_lod")?"#extension GL_EXT_shader_texture_lod : enable":""].filter(xn).join("\n")}(n.extensions,a,e),_=function(t){var e=[];for(var r in t){var n=t[r];!1!==n&&e.push("#define "+r+" "+n)}return e.join("\n")}(c),M=s.createProgram();if(n.isRawShaderMaterial?((m=[_].filter(xn).join("\n")).length>0&&(m+="\n"),(g=[w,_].filter(xn).join("\n")).length>0&&(g+="\n")):(m=["precision "+a.precision+" float;","precision "+a.precision+" int;","highp"===a.precision?"#define HIGH_PRECISION":"","#define SHADER_NAME "+i.name,_,a.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+b,"#define MAX_BONES "+a.maxBones,a.useFog&&a.fog?"#define USE_FOG":"",a.useFog&&a.fogExp2?"#define FOG_EXP2":"",a.map?"#define USE_MAP":"",a.envMap?"#define USE_ENVMAP":"",a.envMap?"#define "+d:"",a.lightMap?"#define USE_LIGHTMAP":"",a.aoMap?"#define USE_AOMAP":"",a.emissiveMap?"#define USE_EMISSIVEMAP":"",a.bumpMap?"#define USE_BUMPMAP":"",a.normalMap?"#define USE_NORMALMAP":"",a.normalMap&&a.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",a.normalMap&&a.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",a.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",a.displacementMap&&a.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",a.specularMap?"#define USE_SPECULARMAP":"",a.roughnessMap?"#define USE_ROUGHNESSMAP":"",a.metalnessMap?"#define USE_METALNESSMAP":"",a.alphaMap?"#define USE_ALPHAMAP":"",a.vertexTangents?"#define USE_TANGENT":"",a.vertexColors?"#define USE_COLOR":"",a.vertexUvs?"#define USE_UV":"",a.flatShading?"#define FLAT_SHADED":"",a.skinning?"#define USE_SKINNING":"",a.useVertexTexture?"#define BONE_TEXTURE":"",a.morphTargets?"#define USE_MORPHTARGETS":"",a.morphNormals&&!1===a.flatShading?"#define USE_MORPHNORMALS":"",a.doubleSided?"#define DOUBLE_SIDED":"",a.flipSided?"#define FLIP_SIDED":"",a.shadowMapEnabled?"#define USE_SHADOWMAP":"",a.shadowMapEnabled?"#define "+u:"",a.sizeAttenuation?"#define USE_SIZEATTENUATION":"",a.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",a.logarithmicDepthBuffer&&(o.isWebGL2||e.get("EXT_frag_depth"))?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(xn).join("\n"),g=[w,"precision "+a.precision+" float;","precision "+a.precision+" int;","highp"===a.precision?"#define HIGH_PRECISION":"","#define SHADER_NAME "+i.name,_,a.alphaTest?"#define ALPHATEST "+a.alphaTest+(a.alphaTest%1?"":".0"):"","#define GAMMA_FACTOR "+b,a.useFog&&a.fog?"#define USE_FOG":"",a.useFog&&a.fogExp2?"#define FOG_EXP2":"",a.map?"#define USE_MAP":"",a.matcap?"#define USE_MATCAP":"",a.envMap?"#define USE_ENVMAP":"",a.envMap?"#define "+p:"",a.envMap?"#define "+d:"",a.envMap?"#define "+f:"",a.lightMap?"#define USE_LIGHTMAP":"",a.aoMap?"#define USE_AOMAP":"",a.emissiveMap?"#define USE_EMISSIVEMAP":"",a.bumpMap?"#define USE_BUMPMAP":"",a.normalMap?"#define USE_NORMALMAP":"",a.normalMap&&a.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",a.normalMap&&a.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",a.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",a.specularMap?"#define USE_SPECULARMAP":"",a.roughnessMap?"#define USE_ROUGHNESSMAP":"",a.metalnessMap?"#define USE_METALNESSMAP":"",a.alphaMap?"#define USE_ALPHAMAP":"",a.sheen?"#define USE_SHEEN":"",a.vertexTangents?"#define USE_TANGENT":"",a.vertexColors?"#define USE_COLOR":"",a.vertexUvs?"#define USE_UV":"",a.gradientMap?"#define USE_GRADIENTMAP":"",a.flatShading?"#define FLAT_SHADED":"",a.doubleSided?"#define DOUBLE_SIDED":"",a.flipSided?"#define FLIP_SIDED":"",a.shadowMapEnabled?"#define USE_SHADOWMAP":"",a.shadowMapEnabled?"#define "+u:"",a.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",a.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",a.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",a.logarithmicDepthBuffer&&(o.isWebGL2||e.get("EXT_frag_depth"))?"#define USE_LOGDEPTHBUF_EXT":"",(n.extensions&&n.extensions.shaderTextureLOD||a.envMap)&&(o.isWebGL2||e.get("EXT_shader_texture_lod"))?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",0!==a.toneMapping?"#define TONE_MAPPING":"",0!==a.toneMapping?Qe.tonemapping_pars_fragment:"",0!==a.toneMapping?yn("toneMapping",a.toneMapping):"",a.dithering?"#define DITHERING":"",a.outputEncoding||a.mapEncoding||a.matcapEncoding||a.envMapEncoding||a.emissiveMapEncoding?Qe.encodings_pars_fragment:"",a.mapEncoding?vn("mapTexelToLinear",a.mapEncoding):"",a.matcapEncoding?vn("matcapTexelToLinear",a.matcapEncoding):"",a.envMapEncoding?vn("envMapTexelToLinear",a.envMapEncoding):"",a.emissiveMapEncoding?vn("emissiveMapTexelToLinear",a.emissiveMapEncoding):"",a.outputEncoding?(v="linearToOutputTexel",y=a.outputEncoding,x=mn(y),"vec4 "+v+"( vec4 value ) { return LinearTo"+x[0]+x[1]+"; }"):"",a.depthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(xn).join("\n")),l=wn(l=bn(l=_n(l),a),a),h=wn(h=bn(h=_n(h),a),a),l=Mn(l),h=Mn(h),o.isWebGL2&&!n.isRawShaderMaterial){var S=!1,T=/^\s*#version\s+300\s+es\s*\n/;n.isShaderMaterial&&null!==l.match(T)&&null!==h.match(T)&&(S=!0,l=l.replace(T,""),h=h.replace(T,"")),m=["#version 300 es\n","#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+m,g=["#version 300 es\n","#define varying in",S?"":"out highp vec4 pc_fragColor;",S?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+g}var E,A,L=g+h,R=dn(s,35633,m+l),P=dn(s,35632,L);if(s.attachShader(M,R),s.attachShader(M,P),void 0!==n.index0AttributeName?s.bindAttribLocation(M,0,n.index0AttributeName):!0===a.morphTargets&&s.bindAttribLocation(M,0,"position"),s.linkProgram(M),t.debug.checkShaderErrors){var C=s.getProgramInfoLog(M).trim(),O=s.getShaderInfoLog(R).trim(),D=s.getShaderInfoLog(P).trim(),N=!0,I=!0;if(!1===s.getProgramParameter(M,35714)){N=!1;var z=gn(s,R,"vertex"),B=gn(s,P,"fragment");console.error("THREE.WebGLProgram: shader error: ",s.getError(),"35715",s.getProgramParameter(M,35715),"gl.getProgramInfoLog",C,z,B)}else""!==C?console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",C):""!==O&&""!==D||(I=!1);I&&(this.diagnostics={runnable:N,material:n,programLog:C,vertexShader:{log:O,prefix:m},fragmentShader:{log:D,prefix:g}})}return s.deleteShader(R),s.deleteShader(P),this.getUniforms=function(){return void 0===E&&(E=new pn(s,M)),E},this.getAttributes=function(){return void 0===A&&(A=function(t,e){for(var r={},n=t.getProgramParameter(e,35721),i=0;i0,maxBones:p,useVertexTexture:r.floatVertexTextures,morphTargets:e.morphTargets,morphNormals:e.morphNormals,maxMorphTargets:t.maxMorphTargets,maxMorphNormals:t.maxMorphNormals,numDirLights:n.directional.length,numPointLights:n.point.length,numSpotLights:n.spot.length,numRectAreaLights:n.rectArea.length,numHemiLights:n.hemi.length,numDirLightShadows:n.directionalShadowMap.length,numPointLightShadows:n.pointShadowMap.length,numSpotLightShadows:n.spotShadowMap.length,numClippingPlanes:c,numClipIntersection:l,dithering:e.dithering,shadowMapEnabled:t.shadowMap.enabled&&h.receiveShadow&&a.length>0,shadowMapType:t.shadowMap.type,toneMapping:e.toneMapped?t.toneMapping:0,physicallyCorrectLights:t.physicallyCorrectLights,premultipliedAlpha:e.premultipliedAlpha,alphaTest:e.alphaTest,doubleSided:2===e.side,flipSided:1===e.side,depthPacking:void 0!==e.depthPacking&&e.depthPacking}},this.getProgramCode=function(e,r){var n=[];if(r.shaderID?n.push(r.shaderID):(n.push(e.fragmentShader),n.push(e.vertexShader)),void 0!==e.defines)for(var i in e.defines)n.push(i),n.push(e.defines[i]);for(var o=0;o1&&r.sort(An),n.length>1&&n.sort(Ln)}}}function Pn(){var t=new WeakMap;function e(r){var n=r.target;n.removeEventListener("dispose",e),t.delete(n)}return{get:function(r,n){var i,a=t.get(r);return void 0===a?(i=new Rn,t.set(r,new WeakMap),t.get(r).set(n,i),r.addEventListener("dispose",e)):void 0===(i=a.get(n))&&(i=new Rn,a.set(n,i)),i},dispose:function(){t=new WeakMap}}}function Cn(){var t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];var r;switch(e.type){case"DirectionalLight":r={direction:new d,color:new Nt,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new l};break;case"SpotLight":r={position:new d,direction:new d,color:new Nt,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new l};break;case"PointLight":r={position:new d,color:new Nt,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new l,shadowCameraNear:1,shadowCameraFar:1e3};break;case"HemisphereLight":r={direction:new d,skyColor:new Nt,groundColor:new Nt};break;case"RectAreaLight":r={color:new Nt,position:new d,halfWidth:new d,halfHeight:new d}}return t[e.id]=r,r}}}var On=0;function Dn(t,e){return(e.castShadow?1:0)-(t.castShadow?1:0)}function Nn(){for(var t=new Cn,e={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1},r=0;r<9;r++)e.probe.push(new d);var n=new d,i=new P,a=new P;return{setup:function(r,o,s){for(var c=0,l=0,h=0,u=0;u<9;u++)e.probe[u].set(0,0,0);var p=0,d=0,f=0,m=0,g=0,v=0,y=0,x=0,b=s.matrixWorldInverse;r.sort(Dn),u=0;for(var w=r.length;u\nvoid main() {\n float mean = 0.0;\n float squared_mean = 0.0;\n \n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n #ifdef HORIZONAL_PASS\n vec2 distribution = decodeHalfRGBA ( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean * HALF_SAMPLE_RATE;\n squared_mean = squared_mean * HALF_SAMPLE_RATE;\n float std_dev = pow( squared_mean - mean * mean, 0.5 );\n gl_FragColor = encodeHalfRGBA( vec2( mean, std_dev ) );\n}"}),d=p.clone();d.defines.HORIZONAL_PASS=1;var f=new se;f.addAttribute("position",new Vt(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));for(var m=new Te(f,p),g=0;4!==g;++g){var v=0!=(1&g),y=0!=(2&g),w=new Bn({depthPacking:3201,morphTargets:v,skinning:y});s[g]=w;var _=new Fn({morphTargets:v,skinning:y});c[g]=_}var M=this;function S(r,n){var i=e.update(m);p.uniforms.shadow_pass.value=r.map.texture,p.uniforms.resolution.value=r.mapSize,p.uniforms.radius.value=r.radius,t.setRenderTarget(r.mapPass),t.clear(),t.renderBufferDirect(n,null,i,p,m,null),d.uniforms.shadow_pass.value=r.mapPass.texture,d.uniforms.resolution.value=r.mapSize,d.uniforms.radius.value=r.radius,t.setRenderTarget(r.map),t.clear(),t.renderBufferDirect(n,null,i,d,m,null)}function T(e,r,n,i,a,o){var l=e.geometry,p=null,d=s,f=e.customDepthMaterial;if(n.isPointLight&&(d=c,f=e.customDistanceMaterial),f)p=f;else{var m=!1;r.morphTargets&&(l&&l.isBufferGeometry?m=l.morphAttributes&&l.morphAttributes.position&&l.morphAttributes.position.length>0:l&&l.isGeometry&&(m=l.morphTargets&&l.morphTargets.length>0)),e.isSkinnedMesh&&!1===r.skinning&&console.warn("THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:",e);var g=0;m&&(g|=1),e.isSkinnedMesh&&r.skinning&&(g|=2),p=d[g]}if(t.localClippingEnabled&&!0===r.clipShadows&&0!==r.clippingPlanes.length){var v=p.uuid,y=r.uuid,x=h[v];void 0===x&&(x={},h[v]=x);var b=x[y];void 0===b&&(b=p.clone(),x[y]=b),p=b}return p.visible=r.visible,p.wireframe=r.wireframe,p.side=3===o?null!=r.shadowSide?r.shadowSide:r.side:null!=r.shadowSide?r.shadowSide:u[r.side],p.clipShadows=r.clipShadows,p.clippingPlanes=r.clippingPlanes,p.clipIntersection=r.clipIntersection,p.wireframeLinewidth=r.wireframeLinewidth,p.linewidth=r.linewidth,n.isPointLight&&p.isMeshDistanceMaterial&&(p.referencePosition.setFromMatrixPosition(n.matrixWorld),p.nearDistance=i,p.farDistance=a),p}function E(r,i,a,o,s){if(!1!==r.visible){if(r.layers.test(i.layers)&&(r.isMesh||r.isLine||r.isPoints)&&(r.castShadow||r.receiveShadow&&3===s)&&(!r.frustumCulled||n.intersectsObject(r))){r.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,r.matrixWorld);var c=e.update(r),l=r.material;if(Array.isArray(l))for(var h=c.groups,u=0,p=h.length;ur||i.y>r)&&(console.warn("THREE.WebGLShadowMap:",m,"has shadow exceeding max texture size, reducing"),i.x>r&&(a.x=Math.floor(r/v.x),i.x=a.x*v.x,g.mapSize.x=a.x),i.y>r&&(a.y=Math.floor(r/v.y),i.y=a.y*v.y,g.mapSize.y=a.y)),null===g.map&&!g.isPointLightShadow&&3===this.type){var y={minFilter:1006,magFilter:1006,format:1023};g.map=new b(i.x,i.y,y),g.map.texture.name=m.name+".shadowMap",g.mapPass=new b(i.x,i.y,y),g.camera.updateProjectionMatrix()}null===g.map&&(y={minFilter:1003,magFilter:1003,format:1023},g.map=new b(i.x,i.y,y),g.map.texture.name=m.name+".shadowMap",g.camera.updateProjectionMatrix()),t.setRenderTarget(g.map),t.clear();for(var x=g.getViewportCount(),w=0;w=1):-1!==O.indexOf("OpenGL ES")&&(C=parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(O)[1]),P=C>=2);var D=null,N={},I=new x,z=new x;function B(e,r,n){var i=new Uint8Array(4),a=t.createTexture();t.bindTexture(e,a),t.texParameteri(e,10241,9728),t.texParameteri(e,10240,9728);for(var o=0;on||t.height>n)&&(i=n/Math.max(t.width,t.height)),i<1||!0===e){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){var a=e?s.floorPowerOfTwo:Math.floor,o=a(i*t.width),c=a(i*t.height);void 0===l&&(l=p(o,c));var h=r?p(o,c):l;return h.width=o,h.height=c,h.getContext("2d").drawImage(t,0,0,o,c),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+t.width+"x"+t.height+") to ("+o+"x"+c+")."),h}return"data"in t&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+t.width+"x"+t.height+")."),t}return t}function f(t){return s.isPowerOfTwo(t.width)&&s.isPowerOfTwo(t.height)}function m(t,e){return t.generateMipmaps&&e&&1003!==t.minFilter&&1006!==t.minFilter}function g(e,r,i,a){t.generateMipmap(e),n.get(r).__maxMipLevel=Math.log(Math.max(i,a))*Math.LOG2E}function v(t,r){if(!a.isWebGL2)return t;var n=t;return 6403===t&&(5126===r&&(n=33326),5131===r&&(n=33325),5121===r&&(n=33321)),6407===t&&(5126===r&&(n=34837),5131===r&&(n=34843),5121===r&&(n=32849)),6408===t&&(5126===r&&(n=34836),5131===r&&(n=34842),5121===r&&(n=32856)),33325===n||33326===n||34842===n||34836===n?e.get("EXT_color_buffer_float"):34843!==n&&34837!==n||console.warn("THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead."),n}function y(t){return 1003===t||1004===t||1005===t?9728:9729}function x(e){var r=e.target;r.removeEventListener("dispose",x),function(e){var r=n.get(e);void 0!==r.__webglInit&&(t.deleteTexture(r.__webglTexture),n.remove(e))}(r),r.isVideoTexture&&h.delete(r),c.memory.textures--}function b(e){var r=e.target;r.removeEventListener("dispose",b),function(e){var r=n.get(e),i=n.get(e.texture);if(e){if(void 0!==i.__webglTexture&&t.deleteTexture(i.__webglTexture),e.depthTexture&&e.depthTexture.dispose(),e.isWebGLRenderTargetCube)for(var a=0;a<6;a++)t.deleteFramebuffer(r.__webglFramebuffer[a]),r.__webglDepthbuffer&&t.deleteRenderbuffer(r.__webglDepthbuffer[a]);else t.deleteFramebuffer(r.__webglFramebuffer),r.__webglDepthbuffer&&t.deleteRenderbuffer(r.__webglDepthbuffer);n.remove(e.texture),n.remove(e)}}(r),c.memory.textures--}var w=0;function _(t,e){var i=n.get(t);if(t.isVideoTexture&&function(t){var e=c.render.frame;h.get(t)!==e&&(h.set(t,e),t.update())}(t),t.version>0&&i.__version!==t.version){var a=t.image;if(void 0===a)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined");else{if(!1!==a.complete)return void A(i,t,e);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}r.activeTexture(33984+e),r.bindTexture(3553,i.__webglTexture)}function M(e,i){if(6===e.image.length){var s=n.get(e);if(e.version>0&&s.__version!==e.version){E(s,e),r.activeTexture(33984+i),r.bindTexture(34067,s.__webglTexture),t.pixelStorei(37440,e.flipY);for(var c=e&&e.isCompressedTexture,l=e.image[0]&&e.image[0].isDataTexture,h=[],u=0;u<6;u++)h[u]=c||l?l?e.image[u].image:e.image[u]:d(e.image[u],!1,!0,a.maxCubemapSize);var p,y=h[0],x=f(y)||a.isWebGL2,b=o.convert(e.format),w=o.convert(e.type),_=v(b,w);if(T(34067,e,x),c){for(u=0;u<6;u++){p=h[u].mipmaps;for(var M=0;M-1?r.compressedTexImage2D(34069+u,M,_,S.width,S.height,0,S.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):r.texImage2D(34069+u,M,_,S.width,S.height,0,b,w,S.data)}}s.__maxMipLevel=p.length-1}else{for(p=e.mipmaps,u=0;u<6;u++)if(l)for(r.texImage2D(34069+u,0,_,h[u].width,h[u].height,0,b,w,h[u].data),M=0;M1||n.get(i).__currentAnisotropy)&&(t.texParameterf(r,c.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(i.anisotropy,a.getMaxAnisotropy())),n.get(i).__currentAnisotropy=i.anisotropy)}}function E(e,r){void 0===e.__webglInit&&(e.__webglInit=!0,r.addEventListener("dispose",x),e.__webglTexture=t.createTexture(),c.memory.textures++)}function A(e,n,i){var s=3553;n.isDataTexture2DArray&&(s=35866),n.isDataTexture3D&&(s=32879),E(e,n),r.activeTexture(33984+i),r.bindTexture(s,e.__webglTexture),t.pixelStorei(37440,n.flipY),t.pixelStorei(37441,n.premultiplyAlpha),t.pixelStorei(3317,n.unpackAlignment);var c=function(t){return!a.isWebGL2&&(1001!==t.wrapS||1001!==t.wrapT||1003!==t.minFilter&&1006!==t.minFilter)}(n)&&!1===f(n.image),l=d(n.image,c,!1,a.maxTextureSize),h=f(l)||a.isWebGL2,u=o.convert(n.format),p=o.convert(n.type),y=v(u,p);T(s,n,h);var x,b=n.mipmaps;if(n.isDepthTexture){if(y=6402,1015===n.type){if(!a.isWebGL2)throw new Error("Float Depth Texture only supported in WebGL2.0");y=36012}else a.isWebGL2&&(y=33189);1026===n.format&&6402===y&&1012!==n.type&&1014!==n.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),n.type=1012,p=o.convert(n.type)),1027===n.format&&(y=34041,1020!==n.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),n.type=1020,p=o.convert(n.type))),r.texImage2D(3553,0,y,l.width,l.height,0,u,p,null)}else if(n.isDataTexture)if(b.length>0&&h){for(var w=0,_=b.length;w<_;w++)x=b[w],r.texImage2D(3553,w,y,x.width,x.height,0,u,p,x.data);n.generateMipmaps=!1,e.__maxMipLevel=b.length-1}else r.texImage2D(3553,0,y,l.width,l.height,0,u,p,l.data),e.__maxMipLevel=0;else if(n.isCompressedTexture){for(w=0,_=b.length;w<_;w++)x=b[w],1023!==n.format&&1022!==n.format?r.getCompressedTextureFormats().indexOf(u)>-1?r.compressedTexImage2D(3553,w,y,x.width,x.height,0,x.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):r.texImage2D(3553,w,y,x.width,x.height,0,u,p,x.data);e.__maxMipLevel=b.length-1}else if(n.isDataTexture2DArray)r.texImage3D(35866,0,y,l.width,l.height,l.depth,0,u,p,l.data),e.__maxMipLevel=0;else if(n.isDataTexture3D)r.texImage3D(32879,0,y,l.width,l.height,l.depth,0,u,p,l.data),e.__maxMipLevel=0;else if(b.length>0&&h){for(w=0,_=b.length;w<_;w++)x=b[w],r.texImage2D(3553,w,y,u,p,x);n.generateMipmaps=!1,e.__maxMipLevel=b.length-1}else r.texImage2D(3553,0,y,u,p,l),e.__maxMipLevel=0;m(n,h)&&g(3553,n,l.width,l.height),e.__version=n.version,n.onUpdate&&n.onUpdate(n)}function L(e,i,a,s){var c=o.convert(i.texture.format),l=o.convert(i.texture.type),h=v(c,l);r.texImage2D(s,0,h,i.width,i.height,0,c,l,null),t.bindFramebuffer(36160,e),t.framebufferTexture2D(36160,a,s,n.get(i.texture).__webglTexture,0),t.bindFramebuffer(36160,null)}function R(e,r,n){if(t.bindRenderbuffer(36161,e),r.depthBuffer&&!r.stencilBuffer){if(n){var i=C(r);t.renderbufferStorageMultisample(36161,i,33189,r.width,r.height)}else t.renderbufferStorage(36161,33189,r.width,r.height);t.framebufferRenderbuffer(36160,36096,36161,e)}else if(r.depthBuffer&&r.stencilBuffer)n?(i=C(r),t.renderbufferStorageMultisample(36161,i,35056,r.width,r.height)):t.renderbufferStorage(36161,34041,r.width,r.height),t.framebufferRenderbuffer(36160,33306,36161,e);else{var a=v(o.convert(r.texture.format),o.convert(r.texture.type));n?(i=C(r),t.renderbufferStorageMultisample(36161,i,a,r.width,r.height)):t.renderbufferStorage(36161,a,r.width,r.height)}t.bindRenderbuffer(36161,null)}function P(e){var r=n.get(e),i=!0===e.isWebGLRenderTargetCube;if(e.depthTexture){if(i)throw new Error("target.depthTexture not supported in Cube render targets");!function(e,r){if(r&&r.isWebGLRenderTargetCube)throw new Error("Depth Texture with cube render targets is not supported");if(t.bindFramebuffer(36160,e),!r.depthTexture||!r.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");n.get(r.depthTexture).__webglTexture&&r.depthTexture.image.width===r.width&&r.depthTexture.image.height===r.height||(r.depthTexture.image.width=r.width,r.depthTexture.image.height=r.height,r.depthTexture.needsUpdate=!0),_(r.depthTexture,0);var i=n.get(r.depthTexture).__webglTexture;if(1026===r.depthTexture.format)t.framebufferTexture2D(36160,36096,3553,i,0);else{if(1027!==r.depthTexture.format)throw new Error("Unknown depthTexture format");t.framebufferTexture2D(36160,33306,3553,i,0)}}(r.__webglFramebuffer,e)}else if(i){r.__webglDepthbuffer=[];for(var a=0;a<6;a++)t.bindFramebuffer(36160,r.__webglFramebuffer[a]),r.__webglDepthbuffer[a]=t.createRenderbuffer(),R(r.__webglDepthbuffer[a],e)}else t.bindFramebuffer(36160,r.__webglFramebuffer),r.__webglDepthbuffer=t.createRenderbuffer(),R(r.__webglDepthbuffer,e);t.bindFramebuffer(36160,null)}function C(t){return a.isWebGL2&&t.isWebGLMultisampleRenderTarget?Math.min(a.maxSamples,t.samples):0}var O=!1,D=!1;this.allocateTextureUnit=function(){var t=w;return t>=a.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+t+" texture units while this GPU supports only "+a.maxTextures),w+=1,t},this.resetTextureUnits=function(){w=0},this.setTexture2D=_,this.setTexture2DArray=function(t,e){var i=n.get(t);t.version>0&&i.__version!==t.version?A(i,t,e):(r.activeTexture(33984+e),r.bindTexture(35866,i.__webglTexture))},this.setTexture3D=function(t,e){var i=n.get(t);t.version>0&&i.__version!==t.version?A(i,t,e):(r.activeTexture(33984+e),r.bindTexture(32879,i.__webglTexture))},this.setTextureCube=M,this.setTextureCubeDynamic=S,this.setupRenderTarget=function(e){var i=n.get(e),s=n.get(e.texture);e.addEventListener("dispose",b),s.__webglTexture=t.createTexture(),c.memory.textures++;var l=!0===e.isWebGLRenderTargetCube,h=!0===e.isWebGLMultisampleRenderTarget,u=f(e)||a.isWebGL2;if(l){i.__webglFramebuffer=[];for(var p=0;p<6;p++)i.__webglFramebuffer[p]=t.createFramebuffer()}else if(i.__webglFramebuffer=t.createFramebuffer(),h)if(a.isWebGL2){i.__webglMultisampledFramebuffer=t.createFramebuffer(),i.__webglColorRenderbuffer=t.createRenderbuffer(),t.bindRenderbuffer(36161,i.__webglColorRenderbuffer);var d=v(o.convert(e.texture.format),o.convert(e.texture.type)),y=C(e);t.renderbufferStorageMultisample(36161,y,d,e.width,e.height),t.bindFramebuffer(36160,i.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(36160,36064,36161,i.__webglColorRenderbuffer),t.bindRenderbuffer(36161,null),e.depthBuffer&&(i.__webglDepthRenderbuffer=t.createRenderbuffer(),R(i.__webglDepthRenderbuffer,e,!0)),t.bindFramebuffer(36160,null)}else console.warn("THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.");if(l){for(r.bindTexture(34067,s.__webglTexture),T(34067,e.texture,u),p=0;p<6;p++)L(i.__webglFramebuffer[p],e,36064,34069+p);m(e.texture,u)&&g(34067,e.texture,e.width,e.height),r.bindTexture(34067,null)}else r.bindTexture(3553,s.__webglTexture),T(3553,e.texture,u),L(i.__webglFramebuffer,e,36064,3553),m(e.texture,u)&&g(3553,e.texture,e.width,e.height),r.bindTexture(3553,null);e.depthBuffer&&P(e)},this.updateRenderTargetMipmap=function(t){var e=t.texture;if(m(e,f(t)||a.isWebGL2)){var i=t.isWebGLRenderTargetCube?34067:3553,o=n.get(e).__webglTexture;r.bindTexture(i,o),g(i,e,t.width,t.height),r.bindTexture(i,null)}},this.updateMultisampleRenderTarget=function(e){if(e.isWebGLMultisampleRenderTarget)if(a.isWebGL2){var r=n.get(e);t.bindFramebuffer(36008,r.__webglMultisampledFramebuffer),t.bindFramebuffer(36009,r.__webglFramebuffer);var i=e.width,o=e.height,s=16384;e.depthBuffer&&(s|=256),e.stencilBuffer&&(s|=1024),t.blitFramebuffer(0,0,i,o,0,0,i,o,s,9728)}else console.warn("THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.")},this.safeSetTexture2D=function(t,e){t&&t.isWebGLRenderTarget&&(!1===O&&(console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead."),O=!0),t=t.texture),_(t,e)},this.safeSetTextureCube=function(t,e){t&&t.isWebGLRenderTargetCube&&(!1===D&&(console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead."),D=!0),t=t.texture),t&&t.isCubeTexture||Array.isArray(t.image)&&6===t.image.length?M(t,e):S(t,e)}}function Vn(t,e,r){return{convert:function(t){var n;if(1e3===t)return 10497;if(1001===t)return 33071;if(1002===t)return 33648;if(1003===t)return 9728;if(1004===t)return 9984;if(1005===t)return 9986;if(1006===t)return 9729;if(1007===t)return 9985;if(1008===t)return 9987;if(1009===t)return 5121;if(1017===t)return 32819;if(1018===t)return 32820;if(1019===t)return 33635;if(1010===t)return 5120;if(1011===t)return 5122;if(1012===t)return 5123;if(1013===t)return 5124;if(1014===t)return 5125;if(1015===t)return 5126;if(1016===t){if(r.isWebGL2)return 5131;if(null!==(n=e.get("OES_texture_half_float")))return n.HALF_FLOAT_OES}if(1021===t)return 6406;if(1022===t)return 6407;if(1023===t)return 6408;if(1024===t)return 6409;if(1025===t)return 6410;if(1026===t)return 6402;if(1027===t)return 34041;if(1028===t)return 6403;if(100===t)return 32774;if(101===t)return 32778;if(102===t)return 32779;if(200===t)return 0;if(201===t)return 1;if(202===t)return 768;if(203===t)return 769;if(204===t)return 770;if(205===t)return 771;if(206===t)return 772;if(207===t)return 773;if(208===t)return 774;if(209===t)return 775;if(210===t)return 776;if((33776===t||33777===t||33778===t||33779===t)&&null!==(n=e.get("WEBGL_compressed_texture_s3tc"))){if(33776===t)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===t)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===t)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===t)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}if((35840===t||35841===t||35842===t||35843===t)&&null!==(n=e.get("WEBGL_compressed_texture_pvrtc"))){if(35840===t)return n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===t)return n.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===t)return n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===t)return n.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===t&&null!==(n=e.get("WEBGL_compressed_texture_etc1")))return n.COMPRESSED_RGB_ETC1_WEBGL;if((37808===t||37809===t||37810===t||37811===t||37812===t||37813===t||37814===t||37815===t||37816===t||37817===t||37818===t||37819===t||37820===t||37821===t)&&null!==(n=e.get("WEBGL_compressed_texture_astc")))return t;if(103===t||104===t){if(r.isWebGL2){if(103===t)return 32775;if(104===t)return 32776}if(null!==(n=e.get("EXT_blend_minmax"))){if(103===t)return n.MIN_EXT;if(104===t)return n.MAX_EXT}}if(1020===t){if(r.isWebGL2)return 34042;if(null!==(n=e.get("WEBGL_depth_texture")))return n.UNSIGNED_INT_24_8_WEBGL}return 0}}}function jn(){Y.call(this),this.type="Group"}function kn(t){Ue.call(this),this.cameras=t||[]}Bn.prototype=Object.create(Ut.prototype),Bn.prototype.constructor=Bn,Bn.prototype.isMeshDepthMaterial=!0,Bn.prototype.copy=function(t){return Ut.prototype.copy.call(this,t),this.depthPacking=t.depthPacking,this.skinning=t.skinning,this.morphTargets=t.morphTargets,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this},Fn.prototype=Object.create(Ut.prototype),Fn.prototype.constructor=Fn,Fn.prototype.isMeshDistanceMaterial=!0,Fn.prototype.copy=function(t){return Ut.prototype.copy.call(this,t),this.referencePosition.copy(t.referencePosition),this.nearDistance=t.nearDistance,this.farDistance=t.farDistance,this.skinning=t.skinning,this.morphTargets=t.morphTargets,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this},jn.prototype=Object.assign(Object.create(Y.prototype),{constructor:jn,isGroup:!0}),kn.prototype=Object.assign(Object.create(Ue.prototype),{constructor:kn,isArrayCamera:!0});var Wn,qn=new d,Xn=new d;function Yn(t,e,r){qn.setFromMatrixPosition(e.matrixWorld),Xn.setFromMatrixPosition(r.matrixWorld);var n=qn.distanceTo(Xn),i=e.projectionMatrix.elements,a=r.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],h=(i[8]-1)/i[0],u=(a[8]+1)/a[0],p=o*h,d=o*u,f=n/(-h+u),m=f*-h;e.matrixWorld.decompose(t.position,t.quaternion,t.scale),t.translateX(m),t.translateZ(f),t.matrixWorld.compose(t.position,t.quaternion,t.scale),t.matrixWorldInverse.getInverse(t.matrixWorld);var g=o+f,v=s+f,y=p-m,x=d+(n-m),b=c*s/v*g,w=l*s/v*g;t.projectionMatrix.makePerspective(y,x,b,w,g,v)}function Jn(t){var e,r,n=this,i=null,o=null,s=null,c=[],u=new P,p=new P,f=1,m="local-floor";void 0!==a&&"VRFrameData"in a&&(o=new a.VRFrameData,a.addEventListener("vrdisplaypresentchange",E,!1));var g=new P,v=new h,y=new d,b=new Ue;b.viewport=new x,b.layers.enable(1);var w=new Ue;w.viewport=new x,w.layers.enable(2);var _=new kn([b,w]);function M(){return null!==i&&!0===i.isPresenting}_.layers.enable(1),_.layers.enable(2);var S,T=new l;function E(){if(M()){var a=i.getEyeParameters("left");e=2*a.renderWidth*f,r=a.renderHeight*f,S=t.getPixelRatio(),t.getSize(T),t.setDrawingBufferSize(e,r,1),b.viewport.set(0,0,e/2,r),w.viewport.set(e/2,0,e/2,r),C.start(),n.dispatchEvent({type:"sessionstart"})}else n.enabled&&t.setDrawingBufferSize(T.width,T.height,S),C.stop(),n.dispatchEvent({type:"sessionend"})}var A=[];function L(t){for(var e=navigator.getGamepads&&navigator.getGamepads(),r=0,n=0,i=e.length;r=0){var c=n[o];if(void 0!==c){var l=c.normalized,h=c.itemSize,u=E.get(c);if(void 0===u)continue;var p=u.buffer,d=u.type,f=u.bytesPerElement;if(c.isInterleavedBufferAttribute){var m=c.data,g=m.stride,v=c.offset;m&&m.isInstancedInterleavedBuffer?(_.enableAttributeAndDivisor(s,m.meshPerAttribute),void 0===r.maxInstancedCount&&(r.maxInstancedCount=m.meshPerAttribute*m.count)):_.enableAttribute(s),y.bindBuffer(34962,p),y.vertexAttribPointer(s,h,d,l,g*f,v*f)}else c.isInstancedBufferAttribute?(_.enableAttributeAndDivisor(s,c.meshPerAttribute),void 0===r.maxInstancedCount&&(r.maxInstancedCount=c.meshPerAttribute*c.count)):_.enableAttribute(s),y.bindBuffer(34962,p),y.vertexAttribPointer(s,h,d,l,0,0)}else if(void 0!==a){var x=a[o];if(void 0!==x)switch(x.length){case 2:y.vertexAttrib2fv(s,x);break;case 3:y.vertexAttrib3fv(s,x);break;case 4:y.vertexAttrib4fv(s,x);break;default:y.vertexAttrib1fv(s,x)}}}}_.disableUnusedAttributes()}}(n,s,r),null!==h&&y.bindBuffer(34963,l.buffer));var f=1/0;null!==h?f=h.count:void 0!==u&&(f=u.count);var m=r.drawRange.start*p,g=r.drawRange.count*p,v=null!==a?a.start*p:0,x=null!==a?a.count*p:1/0,M=Math.max(m,v),S=Math.min(f,m+g,v+x)-1,T=Math.max(0,S-M+1);if(0!==T){if(i.isMesh)if(!0===n.wireframe)_.setLineWidth(n.wireframeLinewidth*ht()),d.setMode(1);else switch(i.drawMode){case 0:d.setMode(4);break;case 1:d.setMode(5);break;case 2:d.setMode(6)}else if(i.isLine){var L=n.linewidth;void 0===L&&(L=1),_.setLineWidth(L*ht()),i.isLineSegments?d.setMode(1):i.isLineLoop?d.setMode(2):d.setMode(3)}else i.isPoints?d.setMode(0):i.isSprite&&d.setMode(4);r&&r.isInstancedBufferGeometry?r.maxInstancedCount>0&&d.renderInstances(r,M,T):d.render(M,T)}},this.compile=function(t,e){(v=O.get(t,e)).init(),t.traverse((function(t){t.isLight&&(v.pushLight(t),t.castShadow&&v.pushShadow(t))})),v.setupLights(e),t.traverse((function(e){if(e.material)if(Array.isArray(e.material))for(var r=0;r=0&&t.numSupportedMorphTargets++}if(t.morphNormals)for(t.numSupportedMorphNormals=0,d=0;d=0&&t.numSupportedMorphNormals++;var f=n.shader.uniforms;(t.isShaderMaterial||t.isRawShaderMaterial)&&!0!==t.clipping||(n.numClippingPlanes=at.numPlanes,n.numIntersection=at.numIntersection,f.clippingPlanes=at.uniform),n.fog=e,n.lightsStateVersion=o,t.lights&&(f.ambientLightColor.value=i.state.ambient,f.lightProbe.value=i.state.probe,f.directionalLights.value=i.state.directional,f.spotLights.value=i.state.spot,f.rectAreaLights.value=i.state.rectArea,f.pointLights.value=i.state.point,f.hemisphereLights.value=i.state.hemi,f.directionalShadowMap.value=i.state.directionalShadowMap,f.directionalShadowMatrix.value=i.state.directionalShadowMatrix,f.spotShadowMap.value=i.state.spotShadowMap,f.spotShadowMatrix.value=i.state.spotShadowMatrix,f.pointShadowMap.value=i.state.pointShadowMap,f.pointShadowMatrix.value=i.state.pointShadowMatrix);var m=n.program.getUniforms(),g=pn.seqWithValue(m.seq,f);n.uniformsList=g}function Tt(t,e,r,n){T.resetTextureUnits();var i=S.get(r),a=v.state.lights;if(ot&&(st||t!==X)){var o=t===X&&r.id===W;at.setState(r.clippingPlanes,r.clipIntersection,r.clipShadows,t,i,o)}!1===r.needsUpdate&&(void 0===i.program||r.fog&&i.fog!==e||r.lights&&i.lightsStateVersion!==a.state.version?r.needsUpdate=!0:void 0===i.numClippingPlanes||i.numClippingPlanes===at.numPlanes&&i.numIntersection===at.numIntersection||(r.needsUpdate=!0)),r.needsUpdate&&(St(r,e,n),r.needsUpdate=!1);var c,l,h=!1,u=!1,p=!1,d=i.program,f=d.getUniforms(),m=i.shader.uniforms;if(_.useProgram(d.program)&&(h=!0,u=!0,p=!0),r.id!==W&&(W=r.id,u=!0),h||X!==t){if(f.setValue(y,"projectionMatrix",t.projectionMatrix),w.logarithmicDepthBuffer&&f.setValue(y,"logDepthBufFC",2/(Math.log(t.far+1)/Math.LN2)),X!==t&&(X=t,u=!0,p=!0),r.isShaderMaterial||r.isMeshPhongMaterial||r.isMeshStandardMaterial||r.envMap){var g=f.map.cameraPosition;void 0!==g&&g.setValue(y,lt.setFromMatrixPosition(t.matrixWorld))}(r.isMeshPhongMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial||r.skinning)&&f.setValue(y,"viewMatrix",t.matrixWorldInverse)}if(r.skinning){f.setOptional(y,n,"bindMatrix"),f.setOptional(y,n,"bindMatrixInverse");var x=n.skeleton;if(x){var b=x.bones;if(w.floatVertexTextures){if(void 0===x.boneTexture){var M=Math.sqrt(4*b.length);M=s.ceilPowerOfTwo(M),M=Math.max(M,4);var E=new Float32Array(M*M*4);E.set(x.boneMatrices);var A=new je(E,M,M,1023,1015);A.needsUpdate=!0,x.boneMatrices=E,x.boneTexture=A,x.boneTextureSize=M}f.setValue(y,"boneTexture",x.boneTexture,T),f.setValue(y,"boneTextureSize",x.boneTextureSize)}else f.setOptional(y,x,"boneMatrices")}}return u&&(f.setValue(y,"toneMappingExposure",F.toneMappingExposure),f.setValue(y,"toneMappingWhitePoint",F.toneMappingWhitePoint),r.lights&&(l=p,(c=m).ambientLightColor.needsUpdate=l,c.lightProbe.needsUpdate=l,c.directionalLights.needsUpdate=l,c.pointLights.needsUpdate=l,c.spotLights.needsUpdate=l,c.rectAreaLights.needsUpdate=l,c.hemisphereLights.needsUpdate=l),e&&r.fog&&function(t,e){t.fogColor.value.copy(e.color),e.isFog?(t.fogNear.value=e.near,t.fogFar.value=e.far):e.isFogExp2&&(t.fogDensity.value=e.density)}(m,e),r.isMeshBasicMaterial?Et(m,r):r.isMeshLambertMaterial?(Et(m,r),function(t,e){e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap)}(m,r)):r.isMeshPhongMaterial?(Et(m,r),r.isMeshToonMaterial?function(t,e){At(t,e),e.gradientMap&&(t.gradientMap.value=e.gradientMap)}(m,r):At(m,r)):r.isMeshStandardMaterial?(Et(m,r),r.isMeshPhysicalMaterial?function(t,e){Lt(t,e),t.reflectivity.value=e.reflectivity,t.clearcoat.value=e.clearcoat,t.clearcoatRoughness.value=e.clearcoatRoughness,e.sheen&&t.sheen.value.copy(e.sheen),e.clearcoatNormalMap&&(t.clearcoatNormalScale.value.copy(e.clearcoatNormalScale),t.clearcoatNormalMap.value=e.clearcoatNormalMap,1===e.side&&t.clearcoatNormalScale.value.negate()),t.transparency.value=e.transparency}(m,r):Lt(m,r)):r.isMeshMatcapMaterial?(Et(m,r),function(t,e){e.matcap&&(t.matcap.value=e.matcap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale,1===e.side&&(t.bumpScale.value*=-1)),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale),1===e.side&&t.normalScale.value.negate()),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}(m,r)):r.isMeshDepthMaterial?(Et(m,r),function(t,e){e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}(m,r)):r.isMeshDistanceMaterial?(Et(m,r),function(t,e){e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias),t.referencePosition.value.copy(e.referencePosition),t.nearDistance.value=e.nearDistance,t.farDistance.value=e.farDistance}(m,r)):r.isMeshNormalMaterial?(Et(m,r),function(t,e){e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale,1===e.side&&(t.bumpScale.value*=-1)),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale),1===e.side&&t.normalScale.value.negate()),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}(m,r)):r.isLineBasicMaterial?(function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity}(m,r),r.isLineDashedMaterial&&function(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}(m,r)):r.isPointsMaterial?function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.size.value=e.size*tt,t.scale.value=.5*$,t.map.value=e.map,null!==e.map&&(!0===e.map.matrixAutoUpdate&&e.map.updateMatrix(),t.uvTransform.value.copy(e.map.matrix))}(m,r):r.isSpriteMaterial?function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.rotation.value=e.rotation,t.map.value=e.map,null!==e.map&&(!0===e.map.matrixAutoUpdate&&e.map.updateMatrix(),t.uvTransform.value.copy(e.map.matrix))}(m,r):r.isShadowMaterial&&(m.color.value.copy(r.color),m.opacity.value=r.opacity),void 0!==m.ltc_1&&(m.ltc_1.value=Ke.LTC_1),void 0!==m.ltc_2&&(m.ltc_2.value=Ke.LTC_2),pn.upload(y,i.uniformsList,m,T)),r.isShaderMaterial&&!0===r.uniformsNeedUpdate&&(pn.upload(y,i.uniformsList,m,T),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&f.setValue(y,"center",n.center),f.setValue(y,"modelViewMatrix",n.modelViewMatrix),f.setValue(y,"normalMatrix",n.normalMatrix),f.setValue(y,"modelMatrix",n.matrixWorld),d}function Et(t,e){var r;t.opacity.value=e.opacity,e.color&&t.diffuse.value.copy(e.color),e.emissive&&t.emissive.value.copy(e.emissive).multiplyScalar(e.emissiveIntensity),e.map&&(t.map.value=e.map),e.alphaMap&&(t.alphaMap.value=e.alphaMap),e.specularMap&&(t.specularMap.value=e.specularMap),e.envMap&&(t.envMap.value=e.envMap,t.flipEnvMap.value=e.envMap.isCubeTexture?-1:1,t.reflectivity.value=e.reflectivity,t.refractionRatio.value=e.refractionRatio,t.maxMipLevel.value=S.get(e.envMap).__maxMipLevel),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.aoMap&&(t.aoMap.value=e.aoMap,t.aoMapIntensity.value=e.aoMapIntensity),e.map?r=e.map:e.specularMap?r=e.specularMap:e.displacementMap?r=e.displacementMap:e.normalMap?r=e.normalMap:e.bumpMap?r=e.bumpMap:e.roughnessMap?r=e.roughnessMap:e.metalnessMap?r=e.metalnessMap:e.alphaMap?r=e.alphaMap:e.emissiveMap&&(r=e.emissiveMap),void 0!==r&&(r.isWebGLRenderTarget&&(r=r.texture),!0===r.matrixAutoUpdate&&r.updateMatrix(),t.uvTransform.value.copy(r.matrix))}function At(t,e){t.specular.value.copy(e.specular),t.shininess.value=Math.max(e.shininess,1e-4),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale,1===e.side&&(t.bumpScale.value*=-1)),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale),1===e.side&&t.normalScale.value.negate()),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}function Lt(t,e){t.roughness.value=e.roughness,t.metalness.value=e.metalness,e.roughnessMap&&(t.roughnessMap.value=e.roughnessMap),e.metalnessMap&&(t.metalnessMap.value=e.metalnessMap),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale,1===e.side&&(t.bumpScale.value*=-1)),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale),1===e.side&&t.normalScale.value.negate()),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias),e.envMap&&(t.envMapIntensity.value=e.envMapIntensity)}bt.setAnimationLoop((function(t){dt.isPresenting()||xt&&xt(t)})),void 0!==a&&bt.setContext(a),this.setAnimationLoop=function(t){xt=t,dt.setAnimationLoop(t),bt.start()},this.render=function(t,e){var r,n;if(void 0!==arguments[2]&&(console.warn("THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead."),r=arguments[2]),void 0!==arguments[3]&&(console.warn("THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead."),n=arguments[3]),e&&e.isCamera){if(!G){q.geometry=null,q.program=null,q.wireframe=!1,W=-1,X=null,!0===t.autoUpdate&&t.updateMatrixWorld(),null===e.parent&&e.updateMatrixWorld(),dt.enabled&&(e=dt.getCamera(e)),(v=O.get(t,e)).init(),t.onBeforeRender(F,t,e,r||j),ct.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),it.setFromMatrix(ct),st=this.localClippingEnabled,ot=at.init(this.clippingPlanes,st,e),(g=C.get(t,e)).init(),wt(t,e,0,F.sortObjects),!0===F.sortObjects&&g.sort(),ot&&at.beginShadows();var i=v.state.shadowsArray;ft.render(i,t,e),v.setupLights(e),ot&&at.endShadows(),this.info.autoReset&&this.info.reset(),void 0!==r&&this.setRenderTarget(r),D.render(g,t,e,n);var a=g.opaque,o=g.transparent;if(t.overrideMaterial){var s=t.overrideMaterial;a.length&&_t(a,t,e,s),o.length&&_t(o,t,e,s)}else a.length&&_t(a,t,e),o.length&&_t(o,t,e);t.onAfterRender(F,t,e),null!==j&&(T.updateRenderTargetMipmap(j),T.updateMultisampleRenderTarget(j)),_.buffers.depth.setTest(!0),_.buffers.depth.setMask(!0),_.buffers.color.setMask(!0),_.setPolygonOffset(!1),dt.enabled&&dt.submitFrame(),g=null,v=null}}else console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.")},this.setFramebuffer=function(t){U!==t&&y.bindFramebuffer(36160,t),U=t},this.getActiveCubeFace=function(){return H},this.getActiveMipmapLevel=function(){return V},this.getRenderTarget=function(){return j},this.setRenderTarget=function(t,e,r){j=t,H=e,V=r,t&&void 0===S.get(t).__webglFramebuffer&&T.setupRenderTarget(t);var n=U,i=!1;if(t){var a=S.get(t).__webglFramebuffer;t.isWebGLRenderTargetCube?(n=a[e||0],i=!0):n=t.isWebGLMultisampleRenderTarget?S.get(t).__webglMultisampledFramebuffer:a,J.copy(t.viewport),Z.copy(t.scissor),Q=t.scissorTest}else J.copy(et).multiplyScalar(tt).floor(),Z.copy(rt).multiplyScalar(tt).floor(),Q=nt;if(k!==n&&(y.bindFramebuffer(36160,n),k=n),_.viewport(J),_.scissor(Z),_.setScissorTest(Q),i){var o=S.get(t.texture);y.framebufferTexture2D(36160,36064,34069+(e||0),o.__webglTexture,r||0)}},this.readRenderTargetPixels=function(t,e,r,n,i,a,o){if(t&&t.isWebGLRenderTarget){var s=S.get(t).__webglFramebuffer;if(t.isWebGLRenderTargetCube&&void 0!==o&&(s=s[o]),s){var c=!1;s!==k&&(y.bindFramebuffer(36160,s),c=!0);try{var l=t.texture,h=l.format,u=l.type;if(1023!==h&&B.convert(h)!==y.getParameter(35739))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!(1009===u||B.convert(u)===y.getParameter(35738)||1015===u&&(w.isWebGL2||b.get("OES_texture_float")||b.get("WEBGL_color_buffer_float"))||1016===u&&(w.isWebGL2?b.get("EXT_color_buffer_float"):b.get("EXT_color_buffer_half_float"))))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");36053===y.checkFramebufferStatus(36160)?e>=0&&e<=t.width-n&&r>=0&&r<=t.height-i&&y.readPixels(e,r,n,i,B.convert(h),B.convert(u),a):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.")}finally{c&&y.bindFramebuffer(36160,k)}}}else console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.")},this.copyFramebufferToTexture=function(t,e,r){var n=e.image.width,i=e.image.height,a=B.convert(e.format);T.setTexture2D(e,0),y.copyTexImage2D(3553,r||0,a,t.x,t.y,n,i,0)},this.copyTextureToTexture=function(t,e,r,n){var i=e.image.width,a=e.image.height,o=B.convert(r.format),s=B.convert(r.type);T.setTexture2D(r,0),e.isDataTexture?y.texSubImage2D(3553,n||0,t.x,t.y,i,a,o,s,e.image.data):y.texSubImage2D(3553,n||0,t.x,t.y,o,s,e.image)},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}function Kn(t,e){this.name="",this.color=new Nt(t),this.density=void 0!==e?e:25e-5}function $n(t,e,r){this.name="",this.color=new Nt(t),this.near=void 0!==e?e:1,this.far=void 0!==r?r:1e3}function ti(t,e){this.array=t,this.stride=e,this.count=void 0!==t?t.length/e:0,this.dynamic=!1,this.updateRange={offset:0,count:-1},this.version=0}function ei(t,e,r,n){this.data=t,this.itemSize=e,this.offset=r,this.normalized=!0===n}function ri(t){Ut.call(this),this.type="SpriteMaterial",this.color=new Nt(16777215),this.map=null,this.rotation=0,this.sizeAttenuation=!0,this.lights=!1,this.transparent=!0,this.setValues(t)}Object.assign(Jn.prototype,e.prototype),Object.assign(Zn.prototype,e.prototype),Object.assign(Kn.prototype,{isFogExp2:!0,clone:function(){return new Kn(this.color,this.density)},toJSON:function(){return{type:"FogExp2",color:this.color.getHex(),density:this.density}}}),Object.assign($n.prototype,{isFog:!0,clone:function(){return new $n(this.color,this.near,this.far)},toJSON:function(){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}}}),Object.defineProperty(ti.prototype,"needsUpdate",{set:function(t){!0===t&&this.version++}}),Object.assign(ti.prototype,{isInterleavedBuffer:!0,onUploadCallback:function(){},setArray:function(t){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");return this.count=void 0!==t?t.length/this.stride:0,this.array=t,this},setDynamic:function(t){return this.dynamic=t,this},copy:function(t){return this.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.dynamic=t.dynamic,this},copyAt:function(t,e,r){t*=this.stride,r*=e.stride;for(var n=0,i=this.stride;nt.far||e.push({distance:s,point:ni.clone(),uv:Pt.getUV(ni,li,hi,ui,pi,di,fi,new l),face:null,object:this})}},clone:function(){return new this.constructor(this.material).copy(this)},copy:function(t){return Y.prototype.copy.call(this,t),void 0!==t.center&&this.center.copy(t.center),this}});var vi=new d,yi=new d;function xi(){Y.call(this),this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}function bi(t,e){t&&t.isGeometry&&console.error("THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead."),Te.call(this,t,e),this.type="SkinnedMesh",this.bindMode="attached",this.bindMatrix=new P,this.bindMatrixInverse=new P}xi.prototype=Object.assign(Object.create(Y.prototype),{constructor:xi,isLOD:!0,copy:function(t){Y.prototype.copy.call(this,t,!1);for(var e=t.levels,r=0,n=e.length;r1){vi.setFromMatrixPosition(t.matrixWorld),yi.setFromMatrixPosition(this.matrixWorld);var r=vi.distanceTo(yi);e[0].object.visible=!0;for(var n=1,i=e.length;n=e[n].distance;n++)e[n-1].object.visible=!1,e[n].object.visible=!0;for(;no||(h.applyMatrix4(this.matrixWorld),(_=t.ray.origin.distanceTo(h))t.far||e.push({distance:_,point:l.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else for(g=0,v=f.length/3-1;go||(h.applyMatrix4(this.matrixWorld),(_=t.ray.origin.distanceTo(h))t.far||e.push({distance:_,point:l.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else if(n.isGeometry){var b=n.vertices,w=b.length;for(g=0;go||(h.applyMatrix4(this.matrixWorld),(_=t.ray.origin.distanceTo(h))t.far||e.push({distance:_,point:l.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}},clone:function(){return new this.constructor(this.geometry,this.material).copy(this)}});var Oi=new d,Di=new d;function Ni(t,e){Ci.call(this,t,e),this.type="LineSegments"}function Ii(t,e){Ci.call(this,t,e),this.type="LineLoop"}function zi(t){Ut.call(this),this.type="PointsMaterial",this.color=new Nt(16777215),this.map=null,this.size=1,this.sizeAttenuation=!0,this.morphTargets=!1,this.lights=!1,this.setValues(t)}Ni.prototype=Object.assign(Object.create(Ci.prototype),{constructor:Ni,isLineSegments:!0,computeLineDistances:function(){var t=this.geometry;if(t.isBufferGeometry)if(null===t.index){for(var e=t.attributes.position,r=[],n=0,i=e.count;ni.far)return;a.push({distance:l,distanceToRay:Math.sqrt(s),point:c,index:e,face:null,object:o})}}function ji(t,e,r,n,i,a,o,s,c){y.call(this,t,e,r,n,i,a,o,s,c),this.format=void 0!==o?o:1022,this.minFilter=void 0!==a?a:1006,this.magFilter=void 0!==i?i:1006,this.generateMipmaps=!1}function ki(t,e,r,n,i,a,o,s,c,l,h,u){y.call(this,null,a,o,s,c,l,n,i,h,u),this.image={width:e,height:r},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}function Wi(t,e,r,n,i,a,o,s,c){y.call(this,t,e,r,n,i,a,o,s,c),this.needsUpdate=!0}function qi(t,e,r,n,i,a,o,s,c,l){if(1026!==(l=void 0!==l?l:1026)&&1027!==l)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===r&&1026===l&&(r=1012),void 0===r&&1027===l&&(r=1020),y.call(this,null,n,i,a,o,s,l,r,c),this.image={width:t,height:e},this.magFilter=void 0!==o?o:1003,this.minFilter=void 0!==s?s:1003,this.flipY=!1,this.generateMipmaps=!1}function Xi(t){se.call(this),this.type="WireframeGeometry";var e,r,n,i,a,o,s,c,l,h,u=[],p=[0,0],f={},m=["a","b","c"];if(t&&t.isGeometry){var g=t.faces;for(e=0,n=g.length;e=0?(t(y-l,v,p),f.subVectors(u,p)):(t(y+l,v,p),f.subVectors(p,u)),v-l>=0?(t(y,v-l,p),m.subVectors(u,p)):(t(y,v+l,p),m.subVectors(p,u)),h.crossVectors(f,m).normalize(),s.push(h.x,h.y,h.z),c.push(y,v)}}for(n=0;n.9&&o<.1&&(e<.2&&(a[t+0]+=1),r<.2&&(a[t+2]+=1),n<.2&&(a[t+4]+=1))}}()}(),this.addAttribute("position",new Zt(i,3)),this.addAttribute("normal",new Zt(i.slice(),3)),this.addAttribute("uv",new Zt(a,2)),0===n?this.computeVertexNormals():this.normalizeNormals()}function Ki(t,e){Oe.call(this),this.type="TetrahedronGeometry",this.parameters={radius:t,detail:e},this.fromBufferGeometry(new $i(t,e)),this.mergeVertices()}function $i(t,e){Qi.call(this,[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],t,e),this.type="TetrahedronBufferGeometry",this.parameters={radius:t,detail:e}}function ta(t,e){Oe.call(this),this.type="OctahedronGeometry",this.parameters={radius:t,detail:e},this.fromBufferGeometry(new ea(t,e)),this.mergeVertices()}function ea(t,e){Qi.call(this,[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],t,e),this.type="OctahedronBufferGeometry",this.parameters={radius:t,detail:e}}function ra(t,e){Oe.call(this),this.type="IcosahedronGeometry",this.parameters={radius:t,detail:e},this.fromBufferGeometry(new na(t,e)),this.mergeVertices()}function na(t,e){var r=(1+Math.sqrt(5))/2,n=[-1,r,0,1,r,0,-1,-r,0,1,-r,0,0,-1,r,0,1,r,0,-1,-r,0,1,-r,r,0,-1,r,0,1,-r,0,-1,-r,0,1];Qi.call(this,n,[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],t,e),this.type="IcosahedronBufferGeometry",this.parameters={radius:t,detail:e}}function ia(t,e){Oe.call(this),this.type="DodecahedronGeometry",this.parameters={radius:t,detail:e},this.fromBufferGeometry(new aa(t,e)),this.mergeVertices()}function aa(t,e){var r=(1+Math.sqrt(5))/2,n=1/r,i=[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-n,-r,0,-n,r,0,n,-r,0,n,r,-n,-r,0,-n,r,0,n,-r,0,n,r,0,-r,0,-n,r,0,-n,-r,0,n,r,0,n];Qi.call(this,i,[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],t,e),this.type="DodecahedronBufferGeometry",this.parameters={radius:t,detail:e}}function oa(t,e,r,n,i,a){Oe.call(this),this.type="TubeGeometry",this.parameters={path:t,tubularSegments:e,radius:r,radialSegments:n,closed:i},void 0!==a&&console.warn("THREE.TubeGeometry: taper has been removed.");var o=new sa(t,e,r,n,i);this.tangents=o.tangents,this.normals=o.normals,this.binormals=o.binormals,this.fromBufferGeometry(o),this.mergeVertices()}function sa(t,e,r,n,i){se.call(this),this.type="TubeBufferGeometry",this.parameters={path:t,tubularSegments:e,radius:r,radialSegments:n,closed:i},e=e||64,r=r||1,n=n||8,i=i||!1;var a=t.computeFrenetFrames(e,i);this.tangents=a.tangents,this.normals=a.normals,this.binormals=a.binormals;var o,s,c=new d,h=new d,u=new l,p=new d,f=[],m=[],g=[],v=[];function y(i){p=t.getPointAt(i/e,p);var o=a.normals[i],l=a.binormals[i];for(s=0;s<=n;s++){var u=s/n*Math.PI*2,d=Math.sin(u),g=-Math.cos(u);h.x=g*o.x+d*l.x,h.y=g*o.y+d*l.y,h.z=g*o.z+d*l.z,h.normalize(),m.push(h.x,h.y,h.z),c.x=p.x+r*h.x,c.y=p.y+r*h.y,c.z=p.z+r*h.z,f.push(c.x,c.y,c.z)}}!function(){for(o=0;o0){var o=i[a[0]];if(void 0!==o)for(this.morphTargetInfluences=[],this.morphTargetDictionary={},t=0,e=o.length;t0&&console.error("THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.")}},clone:function(){return new this.constructor(this.geometry,this.material).copy(this)}}),ji.prototype=Object.assign(Object.create(y.prototype),{constructor:ji,isVideoTexture:!0,update:function(){var t=this.image;t.readyState>=t.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}),ki.prototype=Object.create(y.prototype),ki.prototype.constructor=ki,ki.prototype.isCompressedTexture=!0,Wi.prototype=Object.create(y.prototype),Wi.prototype.constructor=Wi,Wi.prototype.isCanvasTexture=!0,qi.prototype=Object.create(y.prototype),qi.prototype.constructor=qi,qi.prototype.isDepthTexture=!0,Xi.prototype=Object.create(se.prototype),Xi.prototype.constructor=Xi,Yi.prototype=Object.create(Oe.prototype),Yi.prototype.constructor=Yi,Ji.prototype=Object.create(se.prototype),Ji.prototype.constructor=Ji,Zi.prototype=Object.create(Oe.prototype),Zi.prototype.constructor=Zi,Qi.prototype=Object.create(se.prototype),Qi.prototype.constructor=Qi,Ki.prototype=Object.create(Oe.prototype),Ki.prototype.constructor=Ki,$i.prototype=Object.create(Qi.prototype),$i.prototype.constructor=$i,ta.prototype=Object.create(Oe.prototype),ta.prototype.constructor=ta,ea.prototype=Object.create(Qi.prototype),ea.prototype.constructor=ea,ra.prototype=Object.create(Oe.prototype),ra.prototype.constructor=ra,na.prototype=Object.create(Qi.prototype),na.prototype.constructor=na,ia.prototype=Object.create(Oe.prototype),ia.prototype.constructor=ia,aa.prototype=Object.create(Qi.prototype),aa.prototype.constructor=aa,oa.prototype=Object.create(Oe.prototype),oa.prototype.constructor=oa,sa.prototype=Object.create(se.prototype),sa.prototype.constructor=sa,sa.prototype.toJSON=function(){var t=se.prototype.toJSON.call(this);return t.path=this.parameters.path.toJSON(),t},ca.prototype=Object.create(Oe.prototype),ca.prototype.constructor=ca,la.prototype=Object.create(se.prototype),la.prototype.constructor=la,ha.prototype=Object.create(Oe.prototype),ha.prototype.constructor=ha,ua.prototype=Object.create(se.prototype),ua.prototype.constructor=ua;var pa=function(t,e,r){r=r||2;var n,i,a,o,s,c,l,h=e&&e.length,u=h?e[0]*r:t.length,p=da(t,0,u,r,!0),d=[];if(!p||p.next===p.prev)return d;if(h&&(p=function(t,e,r,n){var i,a,o,s,c,l=[];for(i=0,a=e.length;i80*r){n=a=t[0],i=o=t[1];for(var f=r;fa&&(a=s),c>o&&(o=c);l=0!==(l=Math.max(a-n,o-i))?1/l:0}return ma(p,d,r,n,i,l),d};function da(t,e,r,n,i){var a,o;if(i===function(t,e,r,n){for(var i=0,a=e,o=r-n;a0)for(a=e;a=e;a-=n)o=Ca(a,t[a],t[a+1],o);return o&&Aa(o,o.next)&&(Oa(o),o=o.next),o}function fa(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!Aa(n,n.next)&&0!==Ea(n.prev,n,n.next))n=n.next;else{if(Oa(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function ma(t,e,r,n,i,a,o){if(t){!o&&a&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=_a(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,a,o,s,c,l=1;do{for(r=t,t=null,a=null,o=0;r;){for(o++,n=r,s=0,e=0;e0||c>0&&n;)0!==s&&(0===c||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,c--),a?a.nextZ=i:t=i,i.prevZ=a,a=i;r=n}a.nextZ=null,l*=2}while(o>1)}(i)}(t,n,i,a);for(var s,c,l=t;t.prev!==t.next;)if(s=t.prev,c=t.next,a?va(t,n,i,a):ga(t))e.push(s.i/r),e.push(t.i/r),e.push(c.i/r),Oa(t),t=c.next,l=c.next;else if((t=c)===l){o?1===o?ma(t=ya(t,e,r),e,r,n,i,a,2):2===o&&xa(t,e,r,n,i,a):ma(fa(t),e,r,n,i,a,1);break}}}function ga(t){var e=t.prev,r=t,n=t.next;if(Ea(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(Sa(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&Ea(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function va(t,e,r,n){var i=t.prev,a=t,o=t.next;if(Ea(i,a,o)>=0)return!1;for(var s=i.xa.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,h=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,u=_a(s,c,e,r,n),p=_a(l,h,e,r,n),d=t.prevZ,f=t.nextZ;d&&d.z>=u&&f&&f.z<=p;){if(d!==t.prev&&d!==t.next&&Sa(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&Ea(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,f!==t.prev&&f!==t.next&&Sa(i.x,i.y,a.x,a.y,o.x,o.y,f.x,f.y)&&Ea(f.prev,f,f.next)>=0)return!1;f=f.nextZ}for(;d&&d.z>=u;){if(d!==t.prev&&d!==t.next&&Sa(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&Ea(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;f&&f.z<=p;){if(f!==t.prev&&f!==t.next&&Sa(i.x,i.y,a.x,a.y,o.x,o.y,f.x,f.y)&&Ea(f.prev,f,f.next)>=0)return!1;f=f.nextZ}return!0}function ya(t,e,r){var n=t;do{var i=n.prev,a=n.next.next;!Aa(i,a)&&La(i,n,n.next,a)&&Ra(i,a)&&Ra(a,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(a.i/r),Oa(n),Oa(n.next),n=t=a),n=n.next}while(n!==t);return n}function xa(t,e,r,n,i,a){var o=t;do{for(var s=o.next.next;s!==o.prev;){if(o.i!==s.i&&Ta(o,s)){var c=Pa(o,s);return o=fa(o,o.next),c=fa(c,c.next),ma(o,e,r,n,i,a),void ma(c,e,r,n,i,a)}s=s.next}o=o.next}while(o!==t)}function ba(t,e){return t.x-e.x}function wa(t,e){if(e=function(t,e){var r,n=e,i=t.x,a=t.y,o=-1/0;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){var s=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>o){if(o=s,s===i){if(a===n.y)return n;if(a===n.next.y)return n.next}r=n.x=n.x&&n.x>=h&&i!==n.x&&Sa(ar.x)&&Ra(n,t)&&(r=n,p=c),n=n.next;return r}(t,e)){var r=Pa(e,t);fa(r,r.next)}}function _a(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Ma(t){var e=t,r=t;do{(e.x=0&&(t-o)*(n-s)-(r-o)*(e-s)>=0&&(r-o)*(a-s)-(i-o)*(n-s)>=0}function Ta(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&La(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&Ra(t,e)&&Ra(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)}function Ea(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Aa(t,e){return t.x===e.x&&t.y===e.y}function La(t,e,r,n){return!!(Aa(t,r)&&Aa(e,n)||Aa(t,n)&&Aa(r,e))||Ea(t,e,r)>0!=Ea(t,e,n)>0&&Ea(r,n,t)>0!=Ea(r,n,e)>0}function Ra(t,e){return Ea(t.prev,t,t.next)<0?Ea(t,e,t.next)>=0&&Ea(t,t.prev,e)>=0:Ea(t,e,t.prev)<0||Ea(t,t.next,e)<0}function Pa(t,e){var r=new Da(t.i,t.x,t.y),n=new Da(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function Ca(t,e,r,n){var i=new Da(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Oa(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function Da(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}var Na={area:function(t){for(var e=t.length,r=0,n=e-1,i=0;i2&&t[e-1].equals(t[0])&&t.pop()}function za(t,e){for(var r=0;rNumber.EPSILON){var d=Math.sqrt(u),f=Math.sqrt(c*c+h*h),m=e.x-s/d,g=e.y+o/d,v=((r.x-h/f-m)*h-(r.y+c/f-g)*c)/(o*h-s*c),y=(n=m+o*v-t.x)*n+(i=g+s*v-t.y)*i;if(y<=2)return new l(n,i);a=Math.sqrt(y/2)}else{var x=!1;o>Number.EPSILON?c>Number.EPSILON&&(x=!0):o<-Number.EPSILON?c<-Number.EPSILON&&(x=!0):Math.sign(s)===Math.sign(h)&&(x=!0),x?(n=-s,i=o,a=Math.sqrt(u)):(n=o,i=s,a=Math.sqrt(u/2))}return new l(n/a,i/a)}for(var V=[],j=0,k=C.length,W=k-1,q=j+1;j=0;D--){for(I=D/m,z=u*Math.cos(I*Math.PI/2),N=p*Math.sin(I*Math.PI/2)+f,j=0,k=C.length;j=0;){r=j,(n=j-1)<0&&(n=t.length-1);var i=0,a=s+2*m;for(i=0;i0)&&m.push(M,S,E),(c!==r-1||l0&&x(!0),e>0&&x(!1)),this.setIndex(h),this.addAttribute("position",new Zt(u,3)),this.addAttribute("normal",new Zt(p,3)),this.addAttribute("uv",new Zt(f,2))}function eo(t,e,r,n,i,a,o){$a.call(this,0,t,e,r,n,i,a,o),this.type="ConeGeometry",this.parameters={radius:t,height:e,radialSegments:r,heightSegments:n,openEnded:i,thetaStart:a,thetaLength:o}}function ro(t,e,r,n,i,a,o){to.call(this,0,t,e,r,n,i,a,o),this.type="ConeBufferGeometry",this.parameters={radius:t,height:e,radialSegments:r,heightSegments:n,openEnded:i,thetaStart:a,thetaLength:o}}function no(t,e,r,n){Oe.call(this),this.type="CircleGeometry",this.parameters={radius:t,segments:e,thetaStart:r,thetaLength:n},this.fromBufferGeometry(new io(t,e,r,n)),this.mergeVertices()}function io(t,e,r,n){se.call(this),this.type="CircleBufferGeometry",this.parameters={radius:t,segments:e,thetaStart:r,thetaLength:n},t=t||1,e=void 0!==e?Math.max(3,e):8,r=void 0!==r?r:0,n=void 0!==n?n:2*Math.PI;var i,a,o=[],s=[],c=[],h=[],u=new d,p=new l;for(s.push(0,0,0),c.push(0,0,1),h.push(.5,.5),a=0,i=3;a<=e;a++,i+=3){var f=r+a/e*n;u.x=t*Math.cos(f),u.y=t*Math.sin(f),s.push(u.x,u.y,u.z),c.push(0,0,1),p.x=(s[i]/t+1)/2,p.y=(s[i+1]/t+1)/2,h.push(p.x,p.y)}for(i=1;i<=e;i++)o.push(i,i+1,0);this.setIndex(o),this.addAttribute("position",new Zt(s,3)),this.addAttribute("normal",new Zt(c,3)),this.addAttribute("uv",new Zt(h,2))}Ha.prototype=Object.create(Oe.prototype),Ha.prototype.constructor=Ha,Va.prototype=Object.create(Fa.prototype),Va.prototype.constructor=Va,ja.prototype=Object.create(Oe.prototype),ja.prototype.constructor=ja,ka.prototype=Object.create(se.prototype),ka.prototype.constructor=ka,Wa.prototype=Object.create(Oe.prototype),Wa.prototype.constructor=Wa,qa.prototype=Object.create(se.prototype),qa.prototype.constructor=qa,Xa.prototype=Object.create(Oe.prototype),Xa.prototype.constructor=Xa,Ya.prototype=Object.create(se.prototype),Ya.prototype.constructor=Ya,Ja.prototype=Object.create(Oe.prototype),Ja.prototype.constructor=Ja,Ja.prototype.toJSON=function(){var t=Oe.prototype.toJSON.call(this);return Qa(this.parameters.shapes,t)},Za.prototype=Object.create(se.prototype),Za.prototype.constructor=Za,Za.prototype.toJSON=function(){var t=se.prototype.toJSON.call(this);return Qa(this.parameters.shapes,t)},Ka.prototype=Object.create(se.prototype),Ka.prototype.constructor=Ka,$a.prototype=Object.create(Oe.prototype),$a.prototype.constructor=$a,to.prototype=Object.create(se.prototype),to.prototype.constructor=to,eo.prototype=Object.create($a.prototype),eo.prototype.constructor=eo,ro.prototype=Object.create(to.prototype),ro.prototype.constructor=ro,no.prototype=Object.create(Oe.prototype),no.prototype.constructor=no,io.prototype=Object.create(se.prototype),io.prototype.constructor=io;var ao=Object.freeze({WireframeGeometry:Xi,ParametricGeometry:Yi,ParametricBufferGeometry:Ji,TetrahedronGeometry:Ki,TetrahedronBufferGeometry:$i,OctahedronGeometry:ta,OctahedronBufferGeometry:ea,IcosahedronGeometry:ra,IcosahedronBufferGeometry:na,DodecahedronGeometry:ia,DodecahedronBufferGeometry:aa,PolyhedronGeometry:Zi,PolyhedronBufferGeometry:Qi,TubeGeometry:oa,TubeBufferGeometry:sa,TorusKnotGeometry:ca,TorusKnotBufferGeometry:la,TorusGeometry:ha,TorusBufferGeometry:ua,TextGeometry:Ha,TextBufferGeometry:Va,SphereGeometry:ja,SphereBufferGeometry:ka,RingGeometry:Wa,RingBufferGeometry:qa,PlaneGeometry:rr,PlaneBufferGeometry:nr,LatheGeometry:Xa,LatheBufferGeometry:Ya,ShapeGeometry:Ja,ShapeBufferGeometry:Za,ExtrudeGeometry:Ba,ExtrudeBufferGeometry:Fa,EdgesGeometry:Ka,ConeGeometry:eo,ConeBufferGeometry:ro,CylinderGeometry:$a,CylinderBufferGeometry:to,CircleGeometry:no,CircleBufferGeometry:io,BoxGeometry:De,BoxBufferGeometry:Ne});function oo(t){Ut.call(this),this.type="ShadowMaterial",this.color=new Nt(0),this.transparent=!0,this.setValues(t)}function so(t){Fe.call(this,t),this.type="RawShaderMaterial"}function co(t){Ut.call(this),this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new Nt(16777215),this.roughness=.5,this.metalness=.5,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Nt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new l(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function lo(t){co.call(this),this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.reflectivity=.5,this.clearcoat=0,this.clearcoatRoughness=0,this.sheen=null,this.clearcoatNormalScale=new l(1,1),this.clearcoatNormalMap=null,this.transparency=0,this.setValues(t)}function ho(t){Ut.call(this),this.type="MeshPhongMaterial",this.color=new Nt(16777215),this.specular=new Nt(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Nt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new l(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function uo(t){ho.call(this),this.defines={TOON:""},this.type="MeshToonMaterial",this.gradientMap=null,this.setValues(t)}function po(t){Ut.call(this),this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new l(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function fo(t){Ut.call(this),this.type="MeshLambertMaterial",this.color=new Nt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Nt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function mo(t){Ut.call(this),this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Nt(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new l(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.lights=!1,this.setValues(t)}function go(t){Ti.call(this),this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(t)}oo.prototype=Object.create(Ut.prototype),oo.prototype.constructor=oo,oo.prototype.isShadowMaterial=!0,oo.prototype.copy=function(t){return Ut.prototype.copy.call(this,t),this.color.copy(t.color),this},so.prototype=Object.create(Fe.prototype),so.prototype.constructor=so,so.prototype.isRawShaderMaterial=!0,co.prototype=Object.create(Ut.prototype),co.prototype.constructor=co,co.prototype.isMeshStandardMaterial=!0,co.prototype.copy=function(t){return Ut.prototype.copy.call(this,t),this.defines={STANDARD:""},this.color.copy(t.color),this.roughness=t.roughness,this.metalness=t.metalness,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.roughnessMap=t.roughnessMap,this.metalnessMap=t.metalnessMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapIntensity=t.envMapIntensity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.skinning=t.skinning,this.morphTargets=t.morphTargets,this.morphNormals=t.morphNormals,this},lo.prototype=Object.create(co.prototype),lo.prototype.constructor=lo,lo.prototype.isMeshPhysicalMaterial=!0,lo.prototype.copy=function(t){return co.prototype.copy.call(this,t),this.defines={STANDARD:"",PHYSICAL:""},this.reflectivity=t.reflectivity,this.clearcoat=t.clearcoat,this.clearcoatRoughness=t.clearcoatRoughness,t.sheen?this.sheen=(this.sheen||new Nt).copy(t.sheen):this.sheen=null,this.clearcoatNormalMap=t.clearcoatNormalMap,this.clearcoatNormalScale.copy(t.clearcoatNormalScale),this.transparency=t.transparency,this},ho.prototype=Object.create(Ut.prototype),ho.prototype.constructor=ho,ho.prototype.isMeshPhongMaterial=!0,ho.prototype.copy=function(t){return Ut.prototype.copy.call(this,t),this.color.copy(t.color),this.specular.copy(t.specular),this.shininess=t.shininess,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.skinning=t.skinning,this.morphTargets=t.morphTargets,this.morphNormals=t.morphNormals,this},uo.prototype=Object.create(ho.prototype),uo.prototype.constructor=uo,uo.prototype.isMeshToonMaterial=!0,uo.prototype.copy=function(t){return ho.prototype.copy.call(this,t),this.gradientMap=t.gradientMap,this},po.prototype=Object.create(Ut.prototype),po.prototype.constructor=po,po.prototype.isMeshNormalMaterial=!0,po.prototype.copy=function(t){return Ut.prototype.copy.call(this,t),this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.skinning=t.skinning,this.morphTargets=t.morphTargets,this.morphNormals=t.morphNormals,this},fo.prototype=Object.create(Ut.prototype),fo.prototype.constructor=fo,fo.prototype.isMeshLambertMaterial=!0,fo.prototype.copy=function(t){return Ut.prototype.copy.call(this,t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.skinning=t.skinning,this.morphTargets=t.morphTargets,this.morphNormals=t.morphNormals,this},mo.prototype=Object.create(Ut.prototype),mo.prototype.constructor=mo,mo.prototype.isMeshMatcapMaterial=!0,mo.prototype.copy=function(t){return Ut.prototype.copy.call(this,t),this.defines={MATCAP:""},this.color.copy(t.color),this.matcap=t.matcap,this.map=t.map,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.skinning=t.skinning,this.morphTargets=t.morphTargets,this.morphNormals=t.morphNormals,this},go.prototype=Object.create(Ti.prototype),go.prototype.constructor=go,go.prototype.isLineDashedMaterial=!0,go.prototype.copy=function(t){return Ti.prototype.copy.call(this,t),this.scale=t.scale,this.dashSize=t.dashSize,this.gapSize=t.gapSize,this};var vo=Object.freeze({ShadowMaterial:oo,SpriteMaterial:ri,RawShaderMaterial:so,ShaderMaterial:Fe,PointsMaterial:zi,MeshPhysicalMaterial:lo,MeshStandardMaterial:co,MeshPhongMaterial:ho,MeshToonMaterial:uo,MeshNormalMaterial:po,MeshLambertMaterial:fo,MeshDepthMaterial:Bn,MeshDistanceMaterial:Fn,MeshBasicMaterial:Ht,MeshMatcapMaterial:mo,LineDashedMaterial:go,LineBasicMaterial:Ti,Material:Ut}),yo={arraySlice:function(t,e,r){return yo.isTypedArray(t)?new t.constructor(t.subarray(e,void 0!==r?r:t.length)):t.slice(e,r)},convertArray:function(t,e,r){return!t||!r&&t.constructor===e?t:"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t)},isTypedArray:function(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)},getKeyframeOrder:function(t){for(var e=t.length,r=new Array(e),n=0;n!==e;++n)r[n]=n;return r.sort((function(e,r){return t[e]-t[r]})),r},sortedArray:function(t,e,r){for(var n=t.length,i=new t.constructor(n),a=0,o=0;o!==n;++a)for(var s=r[a]*e,c=0;c!==e;++c)i[o++]=t[s+c];return i},flattenJSON:function(t,e,r,n){for(var i=1,a=t[0];void 0!==a&&void 0===a[n];)a=t[i++];if(void 0!==a){var o=a[n];if(void 0!==o)if(Array.isArray(o))do{void 0!==(o=a[n])&&(e.push(a.time),r.push.apply(r,o)),a=t[i++]}while(void 0!==a);else if(void 0!==o.toArray)do{void 0!==(o=a[n])&&(e.push(a.time),o.toArray(r,r.length)),a=t[i++]}while(void 0!==a);else do{void 0!==(o=a[n])&&(e.push(a.time),r.push(o)),a=t[i++]}while(void 0!==a)}}};function xo(t,e,r,n){this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=void 0!==n?n:new e.constructor(r),this.sampleValues=e,this.valueSize=r}function bo(t,e,r,n){xo.call(this,t,e,r,n),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0}function wo(t,e,r,n){xo.call(this,t,e,r,n)}function _o(t,e,r,n){xo.call(this,t,e,r,n)}function Mo(t,e,r,n){if(void 0===t)throw new Error("THREE.KeyframeTrack: track name is undefined");if(void 0===e||0===e.length)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+t);this.name=t,this.times=yo.convertArray(e,this.TimeBufferType),this.values=yo.convertArray(r,this.ValueBufferType),this.setInterpolation(n||this.DefaultInterpolation)}function So(t,e,r){Mo.call(this,t,e,r)}function To(t,e,r,n){Mo.call(this,t,e,r,n)}function Eo(t,e,r,n){Mo.call(this,t,e,r,n)}function Ao(t,e,r,n){xo.call(this,t,e,r,n)}function Lo(t,e,r,n){Mo.call(this,t,e,r,n)}function Ro(t,e,r,n){Mo.call(this,t,e,r,n)}function Po(t,e,r,n){Mo.call(this,t,e,r,n)}function Co(t,e,r){this.name=t,this.tracks=r,this.duration=void 0!==e?e:-1,this.uuid=s.generateUUID(),this.duration<0&&this.resetDuration()}function Oo(t){if(void 0===t.type)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");var e=function(t){switch(t.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return Eo;case"vector":case"vector2":case"vector3":case"vector4":return Po;case"color":return To;case"quaternion":return Lo;case"bool":case"boolean":return So;case"string":return Ro}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+t)}(t.type);if(void 0===t.times){var r=[],n=[];yo.flattenJSON(t.keys,r,n,"value"),t.times=r,t.values=n}return void 0!==e.parse?e.parse(t):new e(t.name,t.times,t.values,t.interpolation)}Object.assign(xo.prototype,{evaluate:function(t){var e=this.parameterPositions,r=this._cachedIndex,n=e[r],i=e[r-1];t:{e:{var a;r:{n:if(!(t=i)break t;var s=e[1];for(t=(i=e[--r-1]))break e}a=r,r=0}for(;r>>1;te;)--a;if(++a,0!==i||a!==n){i>=a&&(i=(a=Math.max(a,1))-1);var o=this.getValueSize();this.times=yo.arraySlice(r,i,a),this.values=yo.arraySlice(this.values,i*o,a*o)}return this},validate:function(){var t=!0,e=this.getValueSize();e-Math.floor(e)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),t=!1);var r=this.times,n=this.values,i=r.length;0===i&&(console.error("THREE.KeyframeTrack: Track is empty.",this),t=!1);for(var a=null,o=0;o!==i;o++){var s=r[o];if("number"==typeof s&&isNaN(s)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,s),t=!1;break}if(null!==a&&a>s){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,s,a),t=!1;break}a=s}if(void 0!==n&&yo.isTypedArray(n)){o=0;for(var c=n.length;o!==c;++o){var l=n[o];if(isNaN(l)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,l),t=!1;break}}}return t},optimize:function(){for(var t=this.times,e=this.values,r=this.getValueSize(),n=2302===this.getInterpolation(),i=1,a=t.length-1,o=1;o0){for(t[i]=t[a],f=a*r,m=i*r,p=0;p!==r;++p)e[m+p]=e[f+p];++i}return i!==t.length&&(this.times=yo.arraySlice(t,0,i),this.values=yo.arraySlice(e,0,i*r)),this},clone:function(){var t=yo.arraySlice(this.times,0),e=yo.arraySlice(this.values,0),r=new(0,this.constructor)(this.name,t,e);return r.createInterpolant=this.createInterpolant,r}}),So.prototype=Object.assign(Object.create(Mo.prototype),{constructor:So,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0}),To.prototype=Object.assign(Object.create(Mo.prototype),{constructor:To,ValueTypeName:"color"}),Eo.prototype=Object.assign(Object.create(Mo.prototype),{constructor:Eo,ValueTypeName:"number"}),Ao.prototype=Object.assign(Object.create(xo.prototype),{constructor:Ao,interpolate_:function(t,e,r,n){for(var i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=t*o,c=(r-e)/(n-e),l=s+o;s!==l;s+=4)h.slerpFlat(i,0,a,s-o,a,s,c);return i}}),Lo.prototype=Object.assign(Object.create(Mo.prototype),{constructor:Lo,ValueTypeName:"quaternion",DefaultInterpolation:2301,InterpolantFactoryMethodLinear:function(t){return new Ao(this.times,this.values,this.getValueSize(),t)},InterpolantFactoryMethodSmooth:void 0}),Ro.prototype=Object.assign(Object.create(Mo.prototype),{constructor:Ro,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0}),Po.prototype=Object.assign(Object.create(Mo.prototype),{constructor:Po,ValueTypeName:"vector"}),Object.assign(Co,{parse:function(t){for(var e=[],r=t.tracks,n=1/(t.fps||1),i=0,a=r.length;i!==a;++i)e.push(Oo(r[i]).scale(n));return new Co(t.name,t.duration,e)},toJSON:function(t){for(var e=[],r=t.tracks,n={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid},i=0,a=r.length;i!==a;++i)e.push(Mo.toJSON(r[i]));return n},CreateFromMorphTargetSequence:function(t,e,r,n){for(var i=e.length,a=[],o=0;o1){var l=n[u=c[1]];l||(n[u]=l=[]),l.push(s)}}var h=[];for(var u in n)h.push(Co.CreateFromMorphTargetSequence(u,n[u],e,r));return h},parseAnimation:function(t,e){if(!t)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;for(var r=function(t,e,r,n,i){if(0!==r.length){var a=[],o=[];yo.flattenJSON(r,a,o,n),0!==a.length&&i.push(new t(e,a,o))}},n=[],i=t.name||"default",a=t.length||-1,o=t.fps||30,s=t.hierarchy||[],c=0;c0||0===t.search(/^data\:image\/jpeg/);i.format=n?1022:1023,i.needsUpdate=!0,void 0!==e&&e(i)}),r,n),i}}),Object.assign(Wo.prototype,{getPoint:function(){return console.warn("THREE.Curve: .getPoint() not implemented."),null},getPointAt:function(t,e){var r=this.getUtoTmapping(t);return this.getPoint(r,e)},getPoints:function(t){void 0===t&&(t=5);for(var e=[],r=0;r<=t;r++)e.push(this.getPoint(r/t));return e},getSpacedPoints:function(t){void 0===t&&(t=5);for(var e=[],r=0;r<=t;r++)e.push(this.getPointAt(r/t));return e},getLength:function(){var t=this.getLengths();return t[t.length-1]},getLengths:function(t){if(void 0===t&&(t=this.arcLengthDivisions),this.cacheArcLengths&&this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var e,r,n=[],i=this.getPoint(0),a=0;for(n.push(0),r=1;r<=t;r++)a+=(e=this.getPoint(r/t)).distanceTo(i),n.push(a),i=e;return this.cacheArcLengths=n,n},updateArcLengths:function(){this.needsUpdate=!0,this.getLengths()},getUtoTmapping:function(t,e){var r,n=this.getLengths(),i=0,a=n.length;r=e||t*n[a-1];for(var o,s=0,c=a-1;s<=c;)if((o=n[i=Math.floor(s+(c-s)/2)]-r)<0)s=i+1;else{if(!(o>0)){c=i;break}c=i-1}if(n[i=c]===r)return i/(a-1);var l=n[i];return(i+(r-l)/(n[i+1]-l))/(a-1)},getTangent:function(t){var e=t-1e-4,r=t+1e-4;e<0&&(e=0),r>1&&(r=1);var n=this.getPoint(e);return this.getPoint(r).clone().sub(n).normalize()},getTangentAt:function(t){var e=this.getUtoTmapping(t);return this.getTangent(e)},computeFrenetFrames:function(t,e){var r,n,i,a=new d,o=[],c=[],l=[],h=new d,u=new P;for(r=0;r<=t;r++)n=r/t,o[r]=this.getTangentAt(n),o[r].normalize();c[0]=new d,l[0]=new d;var p=Number.MAX_VALUE,f=Math.abs(o[0].x),m=Math.abs(o[0].y),g=Math.abs(o[0].z);for(f<=p&&(p=f,a.set(1,0,0)),m<=p&&(p=m,a.set(0,1,0)),g<=p&&a.set(0,0,1),h.crossVectors(o[0],a).normalize(),c[0].crossVectors(o[0],h),l[0].crossVectors(o[0],c[0]),r=1;r<=t;r++)c[r]=c[r-1].clone(),l[r]=l[r-1].clone(),h.crossVectors(o[r-1],o[r]),h.length()>Number.EPSILON&&(h.normalize(),i=Math.acos(s.clamp(o[r-1].dot(o[r]),-1,1)),c[r].applyMatrix4(u.makeRotationAxis(h,i))),l[r].crossVectors(o[r],c[r]);if(!0===e)for(i=Math.acos(s.clamp(c[0].dot(c[t]),-1,1)),i/=t,o[0].dot(h.crossVectors(c[0],c[t]))>0&&(i=-i),r=1;r<=t;r++)c[r].applyMatrix4(u.makeRotationAxis(o[r],i*r)),l[r].crossVectors(o[r],c[r]);return{tangents:o,normals:c,binormals:l}},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.arcLengthDivisions=t.arcLengthDivisions,this},toJSON:function(){var t={metadata:{version:4.5,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t},fromJSON:function(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}),qo.prototype=Object.create(Wo.prototype),qo.prototype.constructor=qo,qo.prototype.isEllipseCurve=!0,qo.prototype.getPoint=function(t,e){for(var r=e||new l,n=2*Math.PI,i=this.aEndAngle-this.aStartAngle,a=Math.abs(i)n;)i-=n;i0?0:(Math.floor(Math.abs(h)/c)+1)*c:0===u&&h===c-1&&(h=c-2,u=1),this.closed||h>0?r=s[(h-1)%c]:(Jo.subVectors(s[0],s[1]).add(s[0]),r=Jo),n=s[h%c],i=s[(h+1)%c],this.closed||h+2n.length-2?n.length-1:a+1],u=n[a>n.length-3?n.length-1:a+2];return r.set(ts(o,s.x,c.x,h.x,u.x),ts(o,s.y,c.y,h.y,u.y)),r},ls.prototype.copy=function(t){Wo.prototype.copy.call(this,t),this.points=[];for(var e=0,r=t.points.length;e=e){var i=r[n]-e,a=this.curves[n],o=a.getLength(),s=0===o?0:1-i/o;return a.getPointAt(s)}n++}return null},getLength:function(){var t=this.getCurveLengths();return t[t.length-1]},updateArcLengths:function(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var t=[],e=0,r=0,n=this.curves.length;r1&&!r[r.length-1].equals(r[0])&&r.push(r[0]),r},copy:function(t){Wo.prototype.copy.call(this,t),this.curves=[];for(var e=0,r=t.curves.length;e0){var l=c.getPoint(0);l.equals(this.currentPoint)||this.lineTo(l.x,l.y)}this.curves.push(c);var h=c.getPoint(1);this.currentPoint.copy(h)},copy:function(t){return us.prototype.copy.call(this,t),this.currentPoint.copy(t.currentPoint),this},toJSON:function(){var t=us.prototype.toJSON.call(this);return t.currentPoint=this.currentPoint.toArray(),t},fromJSON:function(t){return us.prototype.fromJSON.call(this,t),this.currentPoint.fromArray(t.currentPoint),this}}),ds.prototype=Object.assign(Object.create(ps.prototype),{constructor:ds,getPointsHoles:function(t){for(var e=[],r=0,n=this.holes.length;r0){var a=new Vo(new No(e));a.setCrossOrigin(this.crossOrigin);for(var o=0,s=t.length;o0?new bi(o,s):new Te(o,s),void 0!==t.drawMode&&n.setDrawMode(t.drawMode);break;case"LOD":n=new xi;break;case"Line":n=new Ci(i(t.geometry),a(t.material),t.mode);break;case"LineLoop":n=new Ii(i(t.geometry),a(t.material));break;case"LineSegments":n=new Ni(i(t.geometry),a(t.material));break;case"PointCloud":case"Points":n=new Hi(i(t.geometry),a(t.material));break;case"Sprite":n=new mi(a(t.material));break;case"Group":n=new jn;break;default:n=new Y}if(n.uuid=t.uuid,void 0!==t.name&&(n.name=t.name),void 0!==t.matrix?(n.matrix.fromArray(t.matrix),void 0!==t.matrixAutoUpdate&&(n.matrixAutoUpdate=t.matrixAutoUpdate),n.matrixAutoUpdate&&n.matrix.decompose(n.position,n.quaternion,n.scale)):(void 0!==t.position&&n.position.fromArray(t.position),void 0!==t.rotation&&n.rotation.fromArray(t.rotation),void 0!==t.quaternion&&n.quaternion.fromArray(t.quaternion),void 0!==t.scale&&n.scale.fromArray(t.scale)),void 0!==t.castShadow&&(n.castShadow=t.castShadow),void 0!==t.receiveShadow&&(n.receiveShadow=t.receiveShadow),t.shadow&&(void 0!==t.shadow.bias&&(n.shadow.bias=t.shadow.bias),void 0!==t.shadow.radius&&(n.shadow.radius=t.shadow.radius),void 0!==t.shadow.mapSize&&n.shadow.mapSize.fromArray(t.shadow.mapSize),void 0!==t.shadow.camera&&(n.shadow.camera=this.parseObject(t.shadow.camera))),void 0!==t.visible&&(n.visible=t.visible),void 0!==t.frustumCulled&&(n.frustumCulled=t.frustumCulled),void 0!==t.renderOrder&&(n.renderOrder=t.renderOrder),void 0!==t.userData&&(n.userData=t.userData),void 0!==t.layers&&(n.layers.mask=t.layers),void 0!==t.children)for(var c=t.children,l=0;lNumber.EPSILON){if(l<0&&(o=e[a],c=-c,s=e[i],l=-l),t.ys.y)continue;if(t.y===o.y){if(t.x===o.x)return!0}else{var h=l*(t.x-o.x)-c*(t.y-o.y);if(0===h)return!0;if(h<0)continue;n=!n}}else{if(t.y!==o.y)continue;if(s.x<=t.x&&t.x<=o.x||o.x<=t.x&&t.x<=s.x)return!0}}return n}var i=Na.isClockWise,a=this.subPaths;if(0===a.length)return[];if(!0===e)return r(a);var o,s,c,l=[];if(1===a.length)return s=a[0],(c=new ds).curves=s.curves,l.push(c),l;var h=!i(a[0].getPoints());h=t?!h:h;var u,p,d=[],f=[],m=[],g=0;f[g]=void 0,m[g]=[];for(var v=0,y=a.length;v1){for(var x=!1,b=[],w=0,_=f.length;w<_;w++)d[w]=[];for(w=0,_=f.length;w<_;w++)for(var M=m[w],S=0;S0&&(x||(m=d))}v=0;for(var L=f.length;v0){this.source.connect(this.filters[0]);for(var t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(var t=1,e=this.filters.length;t=.5)for(var a=0;a!==i;++a)t[e+a]=t[r+a]},_slerp:function(t,e,r,n){h.slerpFlat(t,e,t,e,t,r,n)},_lerp:function(t,e,r,n,i){for(var a=1-n,o=0;o!==i;++o){var s=e+o;t[s]=t[s]*a+t[r+o]*n}}});var uc=new RegExp("[\\[\\]\\.:\\/]","g"),pc="[^"+"\\[\\]\\.:\\/".replace("\\.","")+"]",dc=/((?:WC+[\/:])*)/.source.replace("WC","[^\\[\\]\\.:\\/]"),fc=/(WCOD+)?/.source.replace("WCOD",pc),mc=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC","[^\\[\\]\\.:\\/]"),gc=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC","[^\\[\\]\\.:\\/]"),vc=new RegExp("^"+dc+fc+mc+gc+"$"),yc=["material","materials","bones"];function xc(t,e,r){var n=r||bc.parseTrackName(e);this._targetGroup=t,this._bindings=t.subscribe_(e,n)}function bc(t,e,r){this.path=e,this.parsedPath=r||bc.parseTrackName(e),this.node=bc.findNode(t,this.parsedPath.nodeName)||t,this.rootNode=t}function wc(){this.uuid=s.generateUUID(),this._objects=Array.prototype.slice.call(arguments),this.nCachedObjects_=0;var t={};this._indicesByUUID=t;for(var e=0,r=arguments.length;e!==r;++e)t[arguments[e].uuid]=e;this._paths=[],this._parsedPaths=[],this._bindings=[],this._bindingsIndicesByPath={};var n=this;this.stats={objects:{get total(){return n._objects.length},get inUse(){return this.total-n.nCachedObjects_}},get bindingsPerObject(){return n._bindings.length}}}function _c(t,e,r){this._mixer=t,this._clip=e,this._localRoot=r||null;for(var n=e.tracks,i=n.length,a=new Array(i),o={endingStart:2400,endingEnd:2400},s=0;s!==i;++s){var c=n[s].createInterpolant(null);a[s]=c,c.settings=o}this._interpolantSettings=o,this._interpolants=a,this._propertyBindings=new Array(i),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}function Mc(t){this._root=t,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}function Sc(t){"string"==typeof t&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),t=arguments[1]),this.value=t}function Tc(t,e,r){ti.call(this,t,e),this.meshPerAttribute=r||1}function Ec(t,e,r,n){this.ray=new xt(t,e),this.near=r||0,this.far=n||1/0,this.camera=null,this.params={Mesh:{},Line:{},LOD:{},Points:{threshold:1},Sprite:{}},Object.defineProperties(this.params,{PointCloud:{get:function(){return console.warn("THREE.Raycaster: params.PointCloud has been renamed to params.Points."),this.Points}}})}function Ac(t,e){return t.distance-e.distance}function Lc(t,e,r,n){if(!1!==t.visible&&(t.raycast(e,r),!0===n))for(var i=t.children,a=0,o=i.length;a=e){var h=e++,u=t[h];r[u.uuid]=l,t[l]=u,r[c]=h,t[h]=s;for(var p=0,d=i;p!==d;++p){var f=n[p],m=f[h],g=f[l];f[l]=m,f[h]=g}}}this.nCachedObjects_=e},uncache:function(){for(var t=this._objects,e=t.length,r=this.nCachedObjects_,n=this._indicesByUUID,i=this._bindings,a=i.length,o=0,s=arguments.length;o!==s;++o){var c=arguments[o],l=c.uuid,h=n[l];if(void 0!==h)if(delete n[l],h0)for(var c=this._interpolants,l=this._propertyBindings,h=0,u=c.length;h!==u;++h)c[h].evaluate(o),l[h].accumulate(n,s)}else this._updateWeight(t)},_updateWeight:function(t){var e=0;if(this.enabled){e=this.weight;var r=this._weightInterpolant;if(null!==r){var n=r.evaluate(t)[0];e*=n,t>r.parameterPositions[1]&&(this.stopFading(),0===n&&(this.enabled=!1))}}return this._effectiveWeight=e,e},_updateTimeScale:function(t){var e=0;if(!this.paused){e=this.timeScale;var r=this._timeScaleInterpolant;null!==r&&(e*=r.evaluate(t)[0],t>r.parameterPositions[1]&&(this.stopWarping(),0===e?this.paused=!0:this.timeScale=e))}return this._effectiveTimeScale=e,e},_updateTime:function(t){var e=this.time+t,r=this._clip.duration,n=this.loop,i=this._loopCount,a=2202===n;if(0===t)return-1===i?e:a&&1==(1&i)?r-e:e;if(2200===n){-1===i&&(this._loopCount=0,this._setEndings(!0,!0,!1));t:{if(e>=r)e=r;else{if(!(e<0)){this.time=e;break t}e=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=e,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{if(-1===i&&(t>=0?(i=0,this._setEndings(!0,0===this.repetitions,a)):this._setEndings(0===this.repetitions,!0,a)),e>=r||e<0){var o=Math.floor(e/r);e-=r*o,i+=Math.abs(o);var s=this.repetitions-i;if(s<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,e=t>0?r:0,this.time=e,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(1===s){var c=t<0;this._setEndings(c,!c,a)}else this._setEndings(!1,!1,a);this._loopCount=i,this.time=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=e;if(a&&1==(1&i))return r-e}return e},_setEndings:function(t,e,r){var n=this._interpolantSettings;r?(n.endingStart=2401,n.endingEnd=2401):(n.endingStart=t?this.zeroSlopeAtStart?2401:2400:2402,n.endingEnd=e?this.zeroSlopeAtEnd?2401:2400:2402)},_scheduleFading:function(t,e,r){var n=this._mixer,i=n.time,a=this._weightInterpolant;null===a&&(a=n._lendControlInterpolant(),this._weightInterpolant=a);var o=a.parameterPositions,s=a.sampleValues;return o[0]=i,s[0]=e,o[1]=i+t,s[1]=r,this}}),Mc.prototype=Object.assign(Object.create(e.prototype),{constructor:Mc,_bindAction:function(t,e){var r=t._localRoot||this._root,n=t._clip.tracks,i=n.length,a=t._propertyBindings,o=t._interpolants,s=r.uuid,c=this._bindingsByRootAndName,l=c[s];void 0===l&&(l={},c[s]=l);for(var h=0;h!==i;++h){var u=n[h],p=u.name,d=l[p];if(void 0!==d)a[h]=d;else{if(void 0!==(d=a[h])){null===d._cacheIndex&&(++d.referenceCount,this._addInactiveBinding(d,s,p));continue}var f=e&&e._propertyBindings[h].binding.parsedPath;++(d=new hc(bc.create(r,p,f),u.ValueTypeName,u.getValueSize())).referenceCount,this._addInactiveBinding(d,s,p),a[h]=d}o[h].resultBuffer=d.buffer}},_activateAction:function(t){if(!this._isActiveAction(t)){if(null===t._cacheIndex){var e=(t._localRoot||this._root).uuid,r=t._clip.uuid,n=this._actionsByClip[r];this._bindAction(t,n&&n.knownActions[0]),this._addInactiveAction(t,r,e)}for(var i=t._propertyBindings,a=0,o=i.length;a!==o;++a){var s=i[a];0==s.useCount++&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(t)}},_deactivateAction:function(t){if(this._isActiveAction(t)){for(var e=t._propertyBindings,r=0,n=e.length;r!==n;++r){var i=e[r];0==--i.useCount&&(i.restoreOriginalState(),this._takeBackBinding(i))}this._takeBackAction(t)}},_initMemoryManager:function(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;var t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}},_isActiveAction:function(t){var e=t._cacheIndex;return null!==e&&ethis.max.x||t.ythis.max.y)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y},getParameter:function(t,e){return void 0===e&&(console.warn("THREE.Box2: .getParameter() target is now required"),e=new l),e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y)},clampPoint:function(t,e){return void 0===e&&(console.warn("THREE.Box2: .clampPoint() target is now required"),e=new l),e.copy(t).clamp(this.min,this.max)},distanceToPoint:function(t){return Cc.copy(t).clamp(this.min,this.max).sub(t).length()},intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}});var Dc=new d,Nc=new d;function Ic(t,e){this.start=void 0!==t?t:new d,this.end=void 0!==e?e:new d}function zc(t){Y.call(this),this.material=t,this.render=function(){}}Object.assign(Ic.prototype,{set:function(t,e){return this.start.copy(t),this.end.copy(e),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.start.copy(t.start),this.end.copy(t.end),this},getCenter:function(t){return void 0===t&&(console.warn("THREE.Line3: .getCenter() target is now required"),t=new d),t.addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(t){return void 0===t&&(console.warn("THREE.Line3: .delta() target is now required"),t=new d),t.subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(t,e){return void 0===e&&(console.warn("THREE.Line3: .at() target is now required"),e=new d),this.delta(e).multiplyScalar(t).add(this.start)},closestPointToPointParameter:function(t,e){Dc.subVectors(t,this.start),Nc.subVectors(this.end,this.start);var r=Nc.dot(Nc),n=Nc.dot(Dc)/r;return e&&(n=s.clamp(n,0,1)),n},closestPointToPoint:function(t,e,r){var n=this.closestPointToPointParameter(t,e);return void 0===r&&(console.warn("THREE.Line3: .closestPointToPoint() target is now required"),r=new d),this.delta(r).multiplyScalar(n).add(this.start)},applyMatrix4:function(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this},equals:function(t){return t.start.equals(this.start)&&t.end.equals(this.end)}}),zc.prototype=Object.create(Y.prototype),zc.prototype.constructor=zc,zc.prototype.isImmediateRenderObject=!0;var Bc=new d,Fc=new d,Gc=new m,Uc=["a","b","c"];function Hc(t,e,r,n){this.object=t,this.size=void 0!==e?e:1;var i=void 0!==r?r:16711680,a=void 0!==n?n:1,o=0,s=this.object.geometry;s&&s.isGeometry?o=3*s.faces.length:s&&s.isBufferGeometry&&(o=s.attributes.normal.count);var c=new se,l=new Zt(2*o*3,3);c.addAttribute("position",l),Ni.call(this,c,new Ti({color:i,linewidth:a})),this.matrixAutoUpdate=!1,this.update()}Hc.prototype=Object.create(Ni.prototype),Hc.prototype.constructor=Hc,Hc.prototype.update=function(){this.object.updateMatrixWorld(!0),Gc.getNormalMatrix(this.object.matrixWorld);var t=this.object.matrixWorld,e=this.geometry.attributes.position,r=this.object.geometry;if(r&&r.isGeometry)for(var n=r.vertices,i=r.faces,a=0,o=0,s=i.length;o1&&t.multiplyScalar(1/e),this.children[0].material.color.copy(this.material.color)}},Jc.prototype.dispose=function(){this.geometry.dispose(),this.material.dispose(),this.children[0].geometry.dispose(),this.children[0].material.dispose()};var Zc=new d,Qc=new Nt,Kc=new Nt;function $c(t,e,r){Y.call(this),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.color=r;var n=new ea(e);n.rotateY(.5*Math.PI),this.material=new Ht({wireframe:!0,fog:!1}),void 0===this.color&&(this.material.vertexColors=2);var i=n.getAttribute("position"),a=new Float32Array(3*i.count);n.addAttribute("color",new Vt(a,3)),this.add(new Te(n,this.material)),this.update()}function tl(t,e){this.lightProbe=t,this.size=e;var r={GAMMA_OUTPUT:""},n=new Fe({defines:r,uniforms:{sh:{value:this.lightProbe.sh.coefficients},intensity:{value:this.lightProbe.intensity}},vertexShader:["varying vec3 vNormal;","void main() {","\tvNormal = normalize( normalMatrix * normal );","\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );","}"].join("\n"),fragmentShader:["#define RECIPROCAL_PI 0.318309886","vec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {","\t// matrix is assumed to be orthogonal","\treturn normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );","}","vec3 linearToOutput( in vec3 a ) {","\t#ifdef GAMMA_OUTPUT","\t\treturn pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );","\t#else","\t\treturn a;","\t#endif","}","// source: https://graphics.stanford.edu/papers/envmap/envmap.pdf","vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {","\t// normal is assumed to have unit length","\tfloat x = normal.x, y = normal.y, z = normal.z;","\t// band 0","\tvec3 result = shCoefficients[ 0 ] * 0.886227;","\t// band 1","\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;","\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;","\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;","\t// band 2","\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;","\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;","\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );","\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;","\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );","\treturn result;","}","uniform vec3 sh[ 9 ]; // sh coefficients","uniform float intensity; // light probe intensity","varying vec3 vNormal;","void main() {","\tvec3 normal = normalize( vNormal );","\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );","\tvec3 irradiance = shGetIrradianceAt( worldNormal, sh );","\tvec3 outgoingLight = RECIPROCAL_PI * irradiance * intensity;","\toutgoingLight = linearToOutput( outgoingLight );","\tgl_FragColor = vec4( outgoingLight, 1.0 );","}"].join("\n")}),i=new ka(1,32,16);Te.call(this,i,n),this.onBeforeRender()}function el(t,e,r,n){t=t||10,e=e||10,r=new Nt(void 0!==r?r:4473924),n=new Nt(void 0!==n?n:8947848);for(var i=e/2,a=t/e,o=t/2,s=[],c=[],l=0,h=0,u=-o;l<=e;l++,u+=a){s.push(-o,0,u,o,0,u),s.push(u,0,-o,u,0,o);var p=l===i?r:n;p.toArray(c,h),h+=3,p.toArray(c,h),h+=3,p.toArray(c,h),h+=3,p.toArray(c,h),h+=3}var d=new se;d.addAttribute("position",new Zt(s,3)),d.addAttribute("color",new Zt(c,3));var f=new Ti({vertexColors:2});Ni.call(this,d,f)}function rl(t,e,r,n,i,a){t=t||10,e=e||16,r=r||8,n=n||64,i=new Nt(void 0!==i?i:4473924),a=new Nt(void 0!==a?a:8947848);var o,s,c,l,h,u,p,d=[],f=[];for(l=0;l<=e;l++)c=l/e*(2*Math.PI),o=Math.sin(c)*t,s=Math.cos(c)*t,d.push(0,0,0),d.push(o,0,s),p=1&l?i:a,f.push(p.r,p.g,p.b),f.push(p.r,p.g,p.b);for(l=0;l<=r;l++)for(p=1&l?i:a,u=t-t/r*l,h=0;h.99999)this.quaternion.set(0,0,0,1);else if(t.y<-.99999)this.quaternion.set(1,0,0,0);else{_l.set(t.z,0,-t.x).normalize();var e=Math.acos(t.y);this.quaternion.setFromAxisAngle(_l,e)}},Ml.prototype.setLength=function(t,e,r){void 0===e&&(e=.2*t),void 0===r&&(r=.2*e),this.line.scale.set(1,Math.max(0,t-e),1),this.line.updateMatrix(),this.cone.scale.set(r,e,r),this.cone.position.y=t,this.cone.updateMatrix()},Ml.prototype.setColor=function(t){this.line.material.color.set(t),this.cone.material.color.set(t)},Ml.prototype.copy=function(t){return Y.prototype.copy.call(this,t,!1),this.line.copy(t.line),this.cone.copy(t.cone),this},Ml.prototype.clone=function(){return(new this.constructor).copy(this)},Sl.prototype=Object.create(Ni.prototype),Sl.prototype.constructor=Sl,Wo.create=function(t,e){return console.log("THREE.Curve.create() has been deprecated"),t.prototype=Object.create(Wo.prototype),t.prototype.constructor=t,t.prototype.getPoint=e,t},Object.assign(us.prototype,{createPointsGeometry:function(t){console.warn("THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");var e=this.getPoints(t);return this.createGeometry(e)},createSpacedPointsGeometry:function(t){console.warn("THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");var e=this.getSpacedPoints(t);return this.createGeometry(e)},createGeometry:function(t){console.warn("THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");for(var e=new Oe,r=0,n=t.length;r + + 无锡荟聚 + + 荟聚隐私政策提示 + 欢迎您使用无锡荟聚实景导航小程序,为更好地保护您的个人信息安全,请您仔细阅读并理解《隐私政策》 + 我们将严格按照您同意的《隐私政策》中的各项条款使用和保护您的个人信息。 + 为继续使用我们的产品或服务,请您阅读并同意《隐私政策》内容。 + + + 不同意 + 同意 + + + 不同意并退出 + 同意并继续 + + \ No newline at end of file diff --git a/pages/agreement/index.wxss b/pages/agreement/index.wxss new file mode 100644 index 0000000..6d81ffa --- /dev/null +++ b/pages/agreement/index.wxss @@ -0,0 +1,91 @@ +.ag { + display: inline-flex; + flex-direction: column; + width: 100vw; + height: 100vh; + align-items: center; +} +.logo { + width: 86px; + height: 86px; + margin-top: 40px; +} +.name { + font-family: Noto IKEA Simplified Chinese; + font-style: normal; + font-weight: bold; + font-size: 14px; + line-height: 21px; + height: 23px; + display: flex; + align-items: center; + text-align: center; + + /* Font color/深灰 */ + + color: #6a6665; + margin-top: 8px; +} +.desc { + margin-top: 70px; + width: calc(100vw - 102px); + height: 198px; + text-align: left; +} +.title { + font-family: Noto IKEA Simplified Chinese; + font-style: normal; + font-weight: bold; + font-size: 14px; + line-height: 21px; + color: #474747; +} +.p { + font-family: Noto IKEA Simplified Chinese; + font-style: normal; + font-weight: normal; + font-size: 14px; + line-height: 21px; + color: #474747; + margin-top: 16px; + text-indent: 2em; +} +.og { + color: #ef9617; +} +.btns { + width: calc(100vw - 70px); + display: flex; + justify-content: space-between; +} +.btn1 { + width: 140px; + height: 50px; + font-family: Noto IKEA Simplified Chinese; + font-style: normal; + font-weight: bold; + font-size: 16px; + line-height: 50px; + text-align: center; + color: #767571; + border: 1px solid #b3aea7; + box-sizing: border-box; + border-radius: 100px; +} + +.btn2 { + width: 140px; + height: 50px; + font-family: Noto IKEA Simplified Chinese; + font-style: normal; + font-weight: bold; + font-size: 16px; + line-height: 50px; + text-align: center; + color: #474747; + border: 1px solid #ffdb00; + box-sizing: border-box; + background: #ffdb00; + box-shadow: 0px 4px 20px rgba(215, 148, 87, 0.33); + border-radius: 30px; +} diff --git a/pages/agreement/logo.png b/pages/agreement/logo.png new file mode 100644 index 0000000..98c475b Binary files /dev/null and b/pages/agreement/logo.png differ diff --git a/pages/destination/destination.js b/pages/destination/destination.js new file mode 100644 index 0000000..0375480 --- /dev/null +++ b/pages/destination/destination.js @@ -0,0 +1,19 @@ +// pages/destination/destination.js +Component({ + /** + * 组件的属性列表 + */ + properties: { + shop: Object, + }, + + /** + * 组件的初始数据 + */ + data: {}, + + /** + * 组件的方法列表 + */ + methods: {}, +}); diff --git a/pages/destination/destination.json b/pages/destination/destination.json new file mode 100644 index 0000000..e8cfaaf --- /dev/null +++ b/pages/destination/destination.json @@ -0,0 +1,4 @@ +{ + "component": true, + "usingComponents": {} +} \ No newline at end of file diff --git a/pages/destination/destination.wxml b/pages/destination/destination.wxml new file mode 100644 index 0000000..ce1dee6 --- /dev/null +++ b/pages/destination/destination.wxml @@ -0,0 +1,6 @@ + + + {{shop.name}} + {{shop.floorName}} + {{shop.shopFormat}} + \ No newline at end of file diff --git a/pages/destination/destination.wxss b/pages/destination/destination.wxss new file mode 100644 index 0000000..1e881bb --- /dev/null +++ b/pages/destination/destination.wxss @@ -0,0 +1,58 @@ +.destination { + position: fixed; + height: 120px; + left: 8px; + right: 8px; + bottom: 82px; + background: linear-gradient(180deg, #ffffff 0%, #ffffff 100.83%); + z-index: 12 !important; + border-radius: 16px 16px 0 0; +} +.destination > image { + position: absolute; + top: 28px; + left: 20px; + width: 56px; + height: 56px; + border: 2px solid #e2e1df; + border-radius: 50%; +} +.destination > .name { + position: absolute; + top: 28px; + left: 92px; + font-style: normal; + font-weight: 900; + font-size: 24px; + line-height: 34px; + height: 34px; + letter-spacing: 1px; + color: #767571; +} +.destination > .name.noicon { + left: 20px; +} +.destination > .meta { + display: inline-flex; + position: absolute; + top: 64px; + left: 92px; + right: 10px; + font-style: normal; + font-weight: normal; + font-size: 14px; + line-height: 20px; + height: 20px; + color: #6a6665; +} +.destination > .meta.noicon { + left: 20px; +} +.destination > .meta > .sep { + display: inline-block; + width: 1px; + height: 8px; + background: #c4c4c4; + opacity: 0.5; + margin: auto 8px; +} diff --git a/pages/gesture/gesture.js b/pages/gesture/gesture.js new file mode 100644 index 0000000..29e6960 --- /dev/null +++ b/pages/gesture/gesture.js @@ -0,0 +1,17 @@ +Component({ + options: { + addGlobalClass: true, + multipleSlots: true, + }, + properties: { + propagation: { + type: Boolean, + value: true, + }, + requireFailure: { + type: Boolean, + value: true, + }, + }, + methods: {} +}) diff --git a/pages/gesture/gesture.json b/pages/gesture/gesture.json new file mode 100644 index 0000000..a2006db --- /dev/null +++ b/pages/gesture/gesture.json @@ -0,0 +1,5 @@ + +{ + "component": true, + "usingComponents": {} +} \ No newline at end of file diff --git a/pages/gesture/gesture.wxml b/pages/gesture/gesture.wxml new file mode 100644 index 0000000..eb35c79 --- /dev/null +++ b/pages/gesture/gesture.wxml @@ -0,0 +1,12 @@ + + + + \ No newline at end of file diff --git a/pages/gesture/gesture.wxs b/pages/gesture/gesture.wxs new file mode 100644 index 0000000..8598899 --- /dev/null +++ b/pages/gesture/gesture.wxs @@ -0,0 +1,263 @@ + +/* eslint-disable */ +// @ts-ignore +function getLen(v) { + return Math.sqrt(v.x * v.x + v.y * v.y) +} +function dot(v1, v2) { + return v1.x * v2.x + v1.y * v2.y +} +function getAngle(v1, v2) { + var mr = getLen(v1) * getLen(v2) + if (mr === 0) return 0 + var r = dot(v1, v2) / mr + if (r > 1) r = 1 + return Math.acos(r) +} +function cross(v1, v2) { + return v1.x * v2.y - v2.x * v1.y +} +function getRotateAngle(v1, v2) { + var angle = getAngle(v1, v2) + if (cross(v1, v2) > 0) { + angle *= -1 + } + return angle * 180 / Math.PI +} +function _swipeDirection(x1, x2, y1, y2) { + if (Math.abs(x1 - x2) >= Math.abs(y1 - y2)) { + return x1 - x2 > 0 ? 'Left' : 'Right' + } else { + return y1 - y2 > 0 ? 'Up' : 'Down' + } +} +// 实现setTimeout功能 +var setTimeout = function(callback, interval, instance) { + var now = Date.now + var stime = now() + var loop = function() { + if (now() - stime >= interval) { + callback() + } else { + instance.requestAnimationFrame(loop) + } + } + instance.requestAnimationFrame(loop) +} +var start = function(event, ownerInstance) { + var instance = event.instance; + var State = instance.getState() + if(!State._init) { + State.preV = {x: null, y: null} + State.pinchStartLen = null + State.zoom = 1 + State.isDoubleTap = false + State.delta = null + State.last = null + State.now = null + State.x1 = State.x2 = State.y1 = State.y2 = null + State.preTapPosition = {x: null, y: null} + // 控制定时器 + State._cancelLongTap = function() { + State.longTapTimeout = false + } + State._cancelSingleTap = function() { + State.singleTapTimeout = false + } + State._tapTimeout = function() { + State.tapTimeout = false + } + State._swipeTimeout = function() { + State.swipeTimeout = false + } + State._init = true // 表示已经初始化完成 + } + State.tapTimeout = true + State.singleTapTimeout = true + State.longTapTimeout = true + State.swipeTimeout = true + State.now = Date.now() + State.x1 = event.touches[0].pageX + State.y1 = event.touches[0].pageY + State.delta = State.now - (State.last || State.now) + // 触发 touchStart 事件 + ownerInstance.triggerEvent('touchStart', event) + if (State.preTapPosition.x !== null) { + State.isDoubleTap = (State.delta > 0 && + State.delta <= 250 && + Math.abs(State.preTapPosition.x - State.x1) < 30 && + Math.abs(State.preTapPosition.y - State.y1) < 30) + if (State.isDoubleTap) { + State._cancelSingleTap() + } + } + State.preTapPosition.x = State.x1 + State.preTapPosition.y = State.y1 + State.last = State.now + var preV = State.preV + var len = event.touches.length + if (len > 1) { + State._cancelLongTap() + State._cancelSingleTap() + var v = {x: event.touches[1].pageX - State.x1, y: event.touches[1].pageY - State.y1} + preV.x = v.x + preV.y = v.y + State.pinchStartLen = getLen(preV) + // 触发 multipointStart 多指点按 事件 + ownerInstance.triggerEvent('multipointStart', event) + } + State._preventTap = false + setTimeout(function () { + // 触发 longTap(长按) 事件 + if(State.longTapTimeout) { + ownerInstance.triggerEvent('longTap', event) + State._preventTap = true + State.longTapTimeout = true + } + }, 750, instance) + + if (!instance.getDataset()['propagation']) return false +} +var move = function(event, ownerInstance) { + var instance = event.instance; + var State = instance.getState() + var preV = State.preV + var len = event.touches.length + var currentX = event.touches[0].pageX + var currentY = event.touches[0].pageY + State.isDoubleTap = false + if (len > 1) { + var sCurrentX = event.touches[1].pageX + var sCurrentY = event.touches[1].pageY + var v = {x: event.touches[1].pageX - currentX, y: event.touches[1].pageY - currentY} + if (preV.x !== null) { + if (State.pinchStartLen > 0) { + event.zoom = getLen(v) / State.pinchStartLen + // 触发 pinch 事件 + ownerInstance.triggerEvent('pinch', event) + } + event.angle = getRotateAngle(v, preV) + // 触发 rotate 事件 + ownerInstance.triggerEvent('rotate', event) + } + preV.x = v.x + preV.y = v.y + if (State.x2 !== null && State.sx2 !== null) { + event.deltaX = (currentX - State.x2 + sCurrentX - State.sx2) / 2 + event.deltaY = (currentY - State.y2 + sCurrentY - State.sy2) / 2 + } else { + event.deltaX = 0 + event.deltaY = 0 + } + // 触发 twoFingerPressMove 事件 + ownerInstance.triggerEvent('twoFingerPressMove', event) + State.sx2 = sCurrentX + State.sy2 = sCurrentY + } else { + if (State.x2 !== null) { + event.deltaX = currentX - State.x2 + event.deltaY = currentY - State.y2 + // move事件中添加对当前触摸点到初始触摸点的判断, + // 如果曾经大于过某个距离(比如10),就认为是移动到某个地方又移回来,应该不再触发tap事件才对。 + var movedX = Math.abs(State.x1 - State.x2) + var movedY = Math.abs(State.y1 - State.y2) + if (movedX > 10 || movedY > 10) { + State._preventTap = true + } + } else { + event.deltaX = 0 + event.deltaY = 0 + } + // 触发 pressMove 单指点按移动 事件 + ownerInstance.triggerEvent('pressMove', event) + } + // 触发 touchMove 移动事件 + ownerInstance.triggerEvent('touchMove', event) + State._cancelLongTap() + State.x2 = currentX + State.y2 = currentY + // if (len > 1) { + // // event.preventDefault() + // } + if (!instance.getDataset()['propagation']) return false +} +var end = function(event, ownerInstance) { + var instance = event.instance; + var State = instance.getState() + State._cancelLongTap() + if (event.touches.length < 2) { + // 触发 multipointEnd 多指点按结束 事件 + ownerInstance.triggerEvent('multipointEnd', event) + State.sx2 = State.sy2 = null + } + // swipe + if ((State.x2 && Math.abs(State.x1 - State.x2) > 30) || + (State.y2 && Math.abs(State.y1 - State.y2) > 30)) { + event.direction = _swipeDirection(State.x1, State.x2, State.y1, State.y2) + setTimeout(function () { + if(State.swipeTimeout) { + // 触发 swipe 滑动 上下左右 事件 + ownerInstance.triggerEvent('swipe', event) + State.swipeTimeout = true + } + }, 0, instance) + } else { + setTimeout(function () { + if(State.tapTimeout) { + if (!State._preventTap) { + // 触发 tap 事件 + ownerInstance.triggerEvent('tap', event) + } + // trigger double tap immediately + if (State.isDoubleTap) { + // 触发 doubleTap 事件 + ownerInstance.triggerEvent('doubleTap', event) + State.isDoubleTap = false + } + State.tapTimeout = true + } + }, 0, instance) + if (!State.isDoubleTap) { + if (instance.getDataset()['requirefailure']) { // requireFailure + setTimeout(function () { + if(State.singleTapTimeout) { + // 触发 singleTap 事件 + ownerInstance.triggerEvent('singleTap', event) + State.singleTapTimeout = true + } + }, 250, instance) + } else { + ownerInstance.triggerEvent('singleTap', event) + State.singleTapTimeout = true + } + } + } + // 触发 touchEnd 事件 + ownerInstance.triggerEvent('touchEnd', event) + State.preV.x = 0 + State.preV.y = 0 + State.zoom = 1 + State.pinchStartLen = null + State.x1 = State.x2 = null + State.y1 = State.y2 = null + + if (!instance.getDataset()['propagation']) return false +} +var cancel = function(event, ownerInstance) { + var instance = event.instance; + var State = instance.getState() + State._cancelLongTap() + State._cancelSingleTap() + State._tapTimeout() + State._swipeTimeout() + // 触发 touchCancel 事件 + ownerInstance.triggerEvent('touchCancel', event) + + if (!instance.getDataset()['propagation']) return false +} +module.exports = { + start: start, + move: move, + end: end, + cancel: cancel +} diff --git a/pages/h5map/index.js b/pages/h5map/index.js new file mode 100644 index 0000000..adbe94b --- /dev/null +++ b/pages/h5map/index.js @@ -0,0 +1,147 @@ +import { post } from "../../app"; +const baseUrl = "https://huiju.mapais.com/livatbeijing/"; +Page({ + /** + * 页面的初始数据 + */ + data: { + url: "", + }, + + /** + * 生命周期函数--监听页面加载 + */ + async onLoad({ q = "", e = "", s = "", fe, plate = "" }) { + let range = "unauth"; + try { + const { latitude, longitude } = await wx.getLocation(); + if ( + latitude < 39.7411 || + latitude > 39.83099 || + longitude < 116.2608 || + longitude > 116.37891 + ) + range = "out"; + else range = "in"; + } catch (error) { + console.log(error); + } + if (q) { + q = decodeURIComponent(q); + const kvs = q + .split("?") + .pop() + .split("&") + .map((kv) => kv.split("=")); + s = kvs.find(([k]) => k === "s")[1]; + e = kvs.find(([k]) => k === "e")[1]; + } + const app = getApp(); + if (!app.globalData.openid) { + const openid = await new Promise((resolve) => app.onOpenid(resolve)); + const agreed = await this.getAgreement(); + if (!agreed) + return wx.redirectTo({ + url: `/pages/agreement/index?q=${q}&e=${e}&s=${s}&plate=${plate}`, + }); + this.setData({ + url: `${baseUrl}?t=${new Date().getTime()}#/?openid=${openid}&range=${range}${ + e ? "&e=" + e : "" + }${e && s ? "&s=" + s : ""}${plate ? "&plate=" + plate : ""}${ + fe ? "&fe=true" : "" + }`, + }); + } else { + const openid = app.globalData.openid; + const agreed = await this.getAgreement(); + if (!agreed) + return wx.redirectTo({ + url: `/pages/agreement/index?q=${q}&e=${e}&s=${s}&plate=${plate}`, + }); + this.setData({ + url: `${baseUrl}?t=${new Date().getTime()}#/?openid=${openid}&range=${range}${ + e ? "&e=" + e : "" + }${e && s ? "&s=" + s : ""}${plate ? "&plate=" + plate : ""}${ + fe ? "&fe=true" : "" + }`, + }); + } + }, + async getAgreement() { + const app = getApp(); + if (app.globalData.agreed) return true; + const openid = app.globalData.openid; + + try { + const { data } = await post("/api/Privacy/Query", { openid }); + app.globalData.agreed = data; + } catch (error) { + console.warn(error); + } + return app.globalData.agreed; + }, + /** + * 生命周期函数--监听页面初次渲染完成 + */ + onReady: function () {}, + + /** + * 生命周期函数--监听页面显示 + */ + onShow: function () {}, + + /** + * 生命周期函数--监听页面隐藏 + */ + onHide: function () {}, + + /** + * 生命周期函数--监听页面卸载 + */ + onUnload: function () {}, + + /** + * 页面相关事件处理函数--监听用户下拉动作 + */ + onPullDownRefresh: function () {}, + + /** + * 页面上拉触底事件的处理函数 + */ + onReachBottom: function () {}, + + /** + * 用户点击右上角分享 + */ + onShareAppMessage({ webViewUrl: q }) { + let e; + let name; + if (q) { + q = decodeURIComponent(q); + const kvs = q + .split("?") + .pop() + .split("&") + .map((kv) => kv.split("=")); + console.log(kvs); + if (kvs.find(([k]) => k === "e")) { + e = kvs.find(([k]) => k === "e")[1]; + } + if (kvs.find(([k]) => k === "name")) { + name = kvs.find(([k]) => k === "name")[1]; + } + } + + return name + ? { + title: name, + path: `/pages/h5map/index?e=${e}`, + imageUrl: "/pages/h5map/share.png", + } + : { + title: "无锡荟聚实景导航", + path: "/pages/h5map/index", + imageUrl: "/pages/h5map/share.png", + }; + }, +}); diff --git a/pages/h5map/index.json b/pages/h5map/index.json new file mode 100644 index 0000000..8835af0 --- /dev/null +++ b/pages/h5map/index.json @@ -0,0 +1,3 @@ +{ + "usingComponents": {} +} \ No newline at end of file diff --git a/pages/h5map/index.wxml b/pages/h5map/index.wxml new file mode 100644 index 0000000..fa399ce --- /dev/null +++ b/pages/h5map/index.wxml @@ -0,0 +1,2 @@ + + > \ No newline at end of file diff --git a/pages/h5map/index.wxss b/pages/h5map/index.wxss new file mode 100644 index 0000000..f63f996 --- /dev/null +++ b/pages/h5map/index.wxss @@ -0,0 +1 @@ +/* pages/h5map/index.wxss */ \ No newline at end of file diff --git a/pages/h5map/share.png b/pages/h5map/share.png new file mode 100644 index 0000000..653df79 Binary files /dev/null and b/pages/h5map/share.png differ diff --git a/pages/index/.DS_Store b/pages/index/.DS_Store new file mode 100644 index 0000000..e1c3c60 Binary files /dev/null and b/pages/index/.DS_Store differ diff --git a/pages/index/VPASSDK-1.2.2.js b/pages/index/VPASSDK-1.2.2.js new file mode 100644 index 0000000..889acdc --- /dev/null +++ b/pages/index/VPASSDK-1.2.2.js @@ -0,0 +1 @@ +var VPASSDK=function(t){var e={};function i(o){if(e[o])return e[o].exports;var s=e[o]={i:o,l:!1,exports:{}};return t[o].call(s.exports,s,s.exports,i),s.l=!0,s.exports}return i.m=t,i.c=e,i.d=function(t,e,o){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:o})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var o=Object.create(null);if(i.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var s in t)i.d(o,s,function(e){return t[e]}.bind(null,s));return o},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=39)}([function(t,e,i){var o=t.exports,s=i(17);o.LongBits=i(11),o.Long=i(32),o.pool=i(33),o.float=i(34),o.asPromise=i(35),o.EventEmitter=i(36),o.path=i(37),o.base64=i(18),o.utf8=i(8),o.compareFieldsById=function(t,e){return t.id-e.id},o.toArray=function(t){if(t){for(var e=Object.keys(t),i=new Array(e.length),o=0;o-1;--i)if(1===e[t[i]]&&void 0!==this[t[i]]&&null!==this[t[i]])return t[i]}},o.oneOfSetter=function(t){return function(e){for(var i=0;i=65536&&i<=1114111?(o.push(i>>18&7|240),o.push(i>>12&63|128),o.push(i>>6&63|128),o.push(63&i|128)):i>=2048&&i<=65535?(o.push(i>>12&15|224),o.push(i>>6&63|128),o.push(63&i|128)):i>=128&&i<=2047?(o.push(i>>6&31|192),o.push(63&i|128)):o.push(255&i);return o},o.byteToString=function(t){if("string"==typeof t)return t;for(var e="",i=t,o=0;o-1;--i)if(1===e[t[i]]&&void 0!==this[t[i]]&&null!==this[t[i]])return t[i]}}}(this._oneofsArray[i].oneof);o[s]={get:r.getter,set:r.setter}}i&&Object.defineProperties(t.prototype,o)}}}),v.generateConstructor=function(t){return function(e){for(var i,o=0;o=e)return!0;return!1},c.isReservedName=function(t,e){if(t)for(var i=0;i0;){var o=t.shift();if(i.nested&&i.nested[o]){if(!((i=i.nested[o])instanceof c))throw Error("path conflicts with non-namespace objects")}else i.add(i=new c(o))}return e&&i.addJSON(e),i},c.prototype.resolveAll=function(){for(var t=this.nestedArray,e=0;e-1)return o}else if(o instanceof c&&(o=o.lookup(t.slice(1),e,!0)))return o}else for(var s=0;s-1&&this.oneof.splice(e,1),t.partOf=null,this},r.prototype.onAdd=function(t){n.prototype.onAdd.call(this,t);for(var e=0;e191&&o<224?n[r++]=(31&o)<<6|63&t[e++]:o>239&&o<365?(o=((7&o)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,n[r++]=55296+(o>>10),n[r++]=56320+(1023&o)):n[r++]=(15&o)<<12|(63&t[e++])<<6|63&t[e++],r>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,n)),r=0);return s?(r&&s.push(String.fromCharCode.apply(String,n.slice(0,r))),s.join("")):String.fromCharCode.apply(String,n.slice(0,r))},o.write=function(t,e,i){for(var o,s,n=i,r=0;r>6|192,e[i++]=63&o|128):55296==(64512&o)&&56320==(64512&(s=t.charCodeAt(r+1)))?(o=65536+((1023&o)<<10)+(1023&s),++r,e[i++]=o>>18|240,e[i++]=o>>12&63|128,e[i++]=o>>6&63|128,e[i++]=63&o|128):(e[i++]=o>>12|224,e[i++]=o>>6&63|128,e[i++]=63&o|128);return i-n}},function(t,e,i){t.exports=d;var o=i(6);((d.prototype=Object.create(o.prototype)).constructor=d).className="Root";var s,n,r,a=i(2),l=i(1),h=i(7),c=i(0);function d(t){o.call(this,"",t),this.deferred=[],this.files=[],this.names=[]}function f(){}d.fromJSON=function(t,e){return t="string"==typeof t?JSON.parse(t):t,e||(e=new d),t.options&&e.setOptions(t.options),e.addJSON(t.nested)},d.prototype.resolvePath=c.path.resolve,d.prototype.parseFromPbString=function t(e,i,o){"function"==typeof i&&(o=i,i=void 0);var s=this;if(!o)return c.asPromise(t,s,e,i);var a=null;if("string"==typeof e)a=JSON.parse(e);else{if("object"!=typeof e)return void console.log("pb格式转化失败");a=e}function l(t,e){if(o){var i=o;o=null,i(t,e)}}function h(t,e){try{if(c.isString(e)&&"{"===e.charAt(0)&&(e=JSON.parse(e)),c.isString(e)){n.filename=t;var o,r=n(e,s,i),a=0;if(r.imports)for(;a-1||(s.names.push(t),t in r&&h(t,r[t]))}h(a.name,a.pbJsonStr)},d.prototype.load=function t(e,i,o){"function"==typeof i&&(o=i,i=void 0);var s=this;if(!o)return c.asPromise(t,s,e,i);var a=o===f;function l(t,e){if(o){var i=o;if(o=null,a)throw t;i(t,e)}}function h(t,e){try{if(c.isString(e)&&"{"===e.charAt(0)&&(e=JSON.parse(e)),c.isString(e)){n.filename=t;var o,r=n(e,s,i),h=0;if(r.imports)for(;h-1){var n=t.substring(i);n in r&&(t=n)}if(!(s.files.indexOf(t)>-1))if(s.files.push(t),t in r)a?h(t,r[t]):(++u,setTimeout((function(){--u,h(t,r[t])})));else if(a){var d;try{d=c.fs.readFileSync(t).toString("utf8")}catch(t){return void(e||l(t))}h(t,d)}else++u,c.fetch(t,(function(i,n){--u,o&&(i?e?u||l(null,s):l(i):h(t,n))}))}var u=0;c.isString(e)&&(e=[e]);for(var p,y=0;y-1&&this.deferred.splice(e,1)}}else if(t instanceof l)u.test(t.name)&&delete t.parent[t.name];else if(t instanceof o){for(var i=0;i>>0,this.hi=e>>>0}t.exports=i;var o=i.zero=new i(0,0);o.toNumber=function(){return 0},o.zzEncode=o.zzDecode=function(){return this},o.length=function(){return 1};var s=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(t){if(0===t)return o;var e=t<0;e&&(t=-t);var s=t>>>0,n=(t-s)/4294967296>>>0;return e&&(n=~n>>>0,s=~s>>>0,++s>4294967295&&(s=0,++n>4294967295&&(n=0))),new i(s,n)},i.from=function(t){return"number"==typeof t?i.fromNumber(t):"string"==typeof t||t instanceof String?i.fromNumber(parseInt(t,10)):t.low||t.high?new i(t.low>>>0,t.high>>>0):o},i.prototype.toNumber=function(t){if(!t&&this.hi>>>31){var e=1+~this.lo>>>0,i=~this.hi>>>0;return e||(i=i+1>>>0),-(e+4294967296*i)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(t){return{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var n=String.prototype.charCodeAt;i.fromHash=function(t){return t===s?o:new i((n.call(t,0)|n.call(t,1)<<8|n.call(t,2)<<16|n.call(t,3)<<24)>>>0,(n.call(t,4)|n.call(t,5)<<8|n.call(t,6)<<16|n.call(t,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},i.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},i.prototype.length=function(){var t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,i=this.hi>>>24;return 0===i?0===e?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:i<128?9:10}},function(t,e,i){t.exports=r;var o,s,n=i(2);function r(t,e,i,o,r,a){if(n.call(this,t,e,o,void 0,void 0,r,a),!s.isString(i))throw TypeError("keyType must be a string");this.keyType=i,this.resolvedKeyType=null,this.map=!0}((r.prototype=Object.create(n.prototype)).constructor=r).className="MapField",r.fromJSON=function(t,e){return new r(t,e.id,e.keyType,e.type,e.options,e.comment)},r.prototype.toJSON=function(t){var e=!!t&&Boolean(t.keepComments);return s.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",e?this.comment:void 0])},r.prototype.resolve=function(){if(this.resolved)return this;if(void 0===o.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return n.prototype.resolve.call(this)},r.d=function(t,e,i){return"function"==typeof i?i=s.decorateType(i).name:i&&"object"==typeof i&&(i=s.decorateEnum(i).name),function(o,n){s.decorateType(o.constructor).add(new r(n,t,e,i))}},r._configure=function(){o=i(5),s=i(0)}},function(t,e,i){"use strict";t.exports=n;var o,s=i(4);function n(t,e,i,n,r,a,l,h){if(o.isObject(r)?(l=r,r=a=void 0):o.isObject(a)&&(l=a,a=void 0),void 0!==e&&!o.isString(e))throw TypeError("type must be a string");if(!o.isString(i))throw TypeError("requestType must be a string");if(!o.isString(n))throw TypeError("responseType must be a string");s.call(this,t,l),this.type=e||"rpc",this.requestType=i,this.requestStream=!!r||void 0,this.responseType=n,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=h}((n.prototype=Object.create(s.prototype)).constructor=n).className="Method",n.fromJSON=function(t,e){return new n(t,e.type,e.requestType,e.responseType,e.requestStream,e.responseStream,e.options,e.comment)},n.prototype.toJSON=function(t){var e=!!t&&Boolean(t.keepComments);return o.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",e?this.comment:void 0])},n.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),s.prototype.resolve.call(this))},n._configure=function(){o=i(0)}},function(t,e,i){"use strict";var o;function s(t){if(t)for(var e=Object.keys(t),i=0;i>16)+(e>>16)+(i>>16)<<16|65535&i}function r(t,e,i,o,s,r){return n((a=n(n(e,t),n(o,r)))<<(l=s)|a>>>32-l,i);var a,l}function a(t,e,i,o,s,n,a){return r(e&i|~e&o,t,e,s,n,a)}function l(t,e,i,o,s,n,a){return r(e&o|i&~o,t,e,s,n,a)}function h(t,e,i,o,s,n,a){return r(e^i^o,t,e,s,n,a)}function c(t,e,i,o,s,n,a){return r(i^(e|~o),t,e,s,n,a)}function d(t,e){var i,o,s,r,d;t[e>>5]|=128<>>9<<4)]=e;var f=1732584193,u=-271733879,p=-1732584194,y=271733878;for(i=0;i>5]>>>e%32&255);return i}function u(t){var e,i=[];for(i[(t.length>>2)-1]=void 0,e=0;e>5]|=(255&t.charCodeAt(e/8))<>>4&15)+"0123456789abcdef".charAt(15&e);return o}function y(t){return unescape(encodeURIComponent(t))}function m(t){return function(t){return f(d(u(t),8*t.length))}(y(t))}function g(t,e){return function(t,e){var i,o,s=u(t),n=[],r=[];for(n[15]=r[15]=void 0,s.length>16&&(s=d(s,8*t.length)),i=0;i<16;i+=1)n[i]=909522486^s[i],r[i]=1549556828^s[i];return o=d(n.concat(u(e)),512+8*e.length),f(d(r.concat(o),640))}(y(t),y(e))}function v(t,e,i){return e?i?g(e,t):p(g(e,t)):i?m(t):p(m(t))}void 0===(o=function(){return v}.call(e,i,e,t))||(t.exports=o)}()},function(t,e,i){t.exports=h;var o,s=i(0),n=i(8);function r(t,e,i){this.fn=t,this.len=e,this.next=void 0,this.val=i}function a(){}function l(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function h(){this.len=0,this.head=new r(a,0,0),this.tail=this.head,this.states=null}function c(t,e,i){e[i]=255&t}function d(t,e){this.len=t,this.next=void 0,this.val=e}function f(t,e,i){for(;t.hi;)e[i++]=127&t.lo|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[i++]=127&t.lo|128,t.lo=t.lo>>>7;e[i++]=t.lo}function u(t,e,i){e[i]=255&t,e[i+1]=t>>>8&255,e[i+2]=t>>>16&255,e[i+3]=t>>>24}h.create=s.Buffer?function(){return(h.create=function(){return new(void 0)})()}:function(){return new h},h.alloc=function(t){return new s.Array(t)},s.Array!==Array&&(h.alloc=s.pool(h.alloc,s.Array.prototype.subarray)),h.prototype._push=function(t,e,i){return this.tail=this.tail.next=new r(t,e,i),this.len+=e,this},d.prototype=Object.create(r.prototype),d.prototype.fn=function(t,e,i){for(;t>127;)e[i++]=127&t|128,t>>>=7;e[i]=t},h.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new d((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},h.prototype.int32=function(t){return t<0?this._push(f,10,o.fromNumber(t)):this.uint32(t)},h.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},h.prototype.uint64=function(t){var e=o.from(t);return this._push(f,e.length(),e)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(t){var e=o.from(t).zzEncode();return this._push(f,e.length(),e)},h.prototype.bool=function(t){return this._push(c,1,t?1:0)},h.prototype.fixed32=function(t){return this._push(u,4,t>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(t){var e=o.from(t);return this._push(u,4,e.lo)._push(u,4,e.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(t){return this._push(s.float.writeFloatLE,4,t)},h.prototype.double=function(t){return this._push(s.float.writeDoubleLE,8,t)};var p=s.Array.prototype.set?function(t,e,i){e.set(t,i)}:function(t,e,i){for(var o=0;o>>0;if(!e)return this._push(c,1,0);if(s.isString(t)){var i=h.alloc(e=n.length(t));n.write(t,i,0),t=i}return this.uint32(e)._push(p,e,t)},h.prototype.string=function(t){var e=n.length(t);return e?this.uint32(e)._push(n.write,e,t):this._push(c,1,0)},h.prototype.fork=function(){return this.states=new l(this),this.head=this.tail=new r(a,0,0),this.len=0,this},h.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new r(a,0,0),this.len=0),this},h.prototype.ldelim=function(){var t=this.head,e=this.tail,i=this.len;return this.reset().uint32(i),i&&(this.tail.next=t.next,this.tail=e,this.len+=i),this},h.prototype.finish=function(){for(var t=this.head.next,e=this.constructor.alloc(this.len),i=0;t;)t.fn(t.val,e,i),i+=t.len,t=t.next;return e},h._configure=function(){o=i(11),i(18),n=i(8)}},function(t,e){t.exports={}},function(t,e,i){"use strict";var o=t.exports;o.length=function(t){var e=t.length;if(!e)return 0;for(var i=0;--e%4>1&&"="===t.charAt(e);)++i;return Math.ceil(3*t.length)/4-i};for(var s=new Array(64),n=new Array(123),r=0;r<64;)n[s[r]=r<26?r+65:r<52?r+71:r<62?r-4:r-59|43]=r++;o.encode=function(t,e,i){for(var o,n=null,r=[],a=0,l=0;e>2],o=(3&h)<<4,l=1;break;case 1:r[a++]=s[o|h>>4],o=(15&h)<<2,l=2;break;case 2:r[a++]=s[o|h>>6],r[a++]=s[63&h],l=0}a>8191&&((n||(n=[])).push(String.fromCharCode.apply(String,r)),a=0)}return l&&(r[a++]=s[o],r[a++]=61,1===l&&(r[a++]=61)),n?(a&&n.push(String.fromCharCode.apply(String,r.slice(0,a))),n.join("")):String.fromCharCode.apply(String,r.slice(0,a))};o.decode=function(t,e,i){for(var o,s=i,r=0,a=0;a1)break;if(void 0===(l=n[l]))throw Error("invalid encoding");switch(r){case 0:o=l,r=1;break;case 1:e[i++]=o<<2|(48&l)>>4,o=l,r=2;break;case 2:e[i++]=(15&o)<<4|(60&l)>>2,o=l,r=3;break;case 3:e[i++]=(3&o)<<6|l,r=0}}if(1===r)throw Error("invalid encoding");return i-s},o.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},function(t,e,i){"use strict";var o,s,n,r,a,l,h,c,d,f,u;t.exports=T,T.filename=null,T.defaults={keepCase:!1};var p=/^[1-9][0-9]*$/,y=/^-?[1-9][0-9]*$/,m=/^0[x][0-9a-fA-F]+$/,g=/^-?0[x][0-9a-fA-F]+$/,v=/^0[0-7]+$/,w=/^-?0[0-7]+$/,b=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,_=/^[a-zA-Z_][a-zA-Z_0-9]*$/,x=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)+$/,P=/^(?:\.[a-zA-Z][a-zA-Z_0-9]*)+$/;function T(t,e,i){e instanceof s||(i=e,e=new s),i||(i=T.defaults);var A,M,C,S,E,I=o(t,i.alternateCommentMode||!1),O=I.next,k=I.push,R=I.peek,D=I.skip,L=I.cmnt,N=!0,V=!1,B=e,F=i.keepCase?function(t){return t}:u.camelCase;function j(t,e,i){var o=T.filename;return i||(T.filename=null),Error("illegal "+(e||"token")+" '"+t+"' ("+(o?o+", ":"")+"line "+I.line+")")}function W(){var t,e=[];do{if('"'!==(t=O())&&"'"!==t)throw j(t);e.push(O()),D(t),t=R()}while('"'===t||"'"===t);return e.join("")}function z(t){var e=O();switch(e){case"'":case'"':return k(e),W();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return function(t,e){var i=1;"-"===t.charAt(0)&&(i=-1,t=t.substring(1));switch(t){case"inf":case"INF":case"Inf":return i*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(p.test(t))return i*parseInt(t,10);if(m.test(t))return i*parseInt(t,16);if(v.test(t))return i*parseInt(t,8);if(b.test(t))return i*parseFloat(t);throw j(t,"number",e)}(e,!0)}catch(i){if(t&&x.test(e))return e;throw j(e,"value")}}function U(t,e){var i,o;do{!e||'"'!==(i=R())&&"'"!==i?t.push([o=H(O()),D("to",!0)?H(O()):o]):t.push(W())}while(D(",",!0));D(";")}function H(t,e){switch(t){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!e&&"-"===t.charAt(0))throw j(t,"id");if(y.test(t))return parseInt(t,10);if(g.test(t))return parseInt(t,16);if(w.test(t))return parseInt(t,8);throw j(t,"id")}function q(){if(void 0!==A)throw j("package");if(A=O(),!x.test(A))throw j(A,"name");B=B.define(A),D(";")}function J(){var t,e=R();switch(e){case"weak":t=C||(C=[]),O();break;case"public":O();default:t=M||(M=[])}e=W(),D(";"),t.push(e)}function X(){if(D("="),S=W(),!(V="proto3"===S)&&"proto2"!==S)throw j(S,"syntax");D(";")}function $(t,e){switch(e){case"option":return G(t,e),D(";"),!0;case"message":return function(t,e){if(!_.test(e=O()))throw j(e,"type name");var i=new n(e);Z(i,(function(t){if(!$(i,t))switch(t){case"map":!function(t){D("<");var e=O();if(void 0===f.mapKey[e])throw j(e,"type");D(",");var i=O();if(!x.test(i))throw j(i,"type");D(">");var o=O();if(!_.test(o))throw j(o,"name");D("=");var s=new a(F(o),H(O()),e,i);Z(s,(function(t){if("option"!==t)throw j(t);G(s,t),D(";")}),(function(){tt(s)})),t.add(s)}(i);break;case"required":case"optional":case"repeated":Y(i,t);break;case"oneof":!function(t,e){if(!_.test(e=O()))throw j(e,"name");var i=new l(F(e));Z(i,(function(t){"option"===t?(G(i,t),D(";")):(k(t),Y(i,"optional"))})),t.add(i)}(i,t);break;case"extensions":U(i.extensions||(i.extensions=[]));break;case"reserved":U(i.reserved||(i.reserved=[]),!0);break;default:if(!V||!x.test(t))throw j(t);k(t),Y(i,"optional")}})),t.add(i)}(t,e),!0;case"enum":return function(t,e){if(!_.test(e=O()))throw j(e,"name");var i=new h(e);Z(i,(function(t){switch(t){case"option":G(i,t),D(";");break;case"reserved":U(i.reserved||(i.reserved=[]),!0);break;default:!function(t,e){if(!_.test(e))throw j(e,"name");D("=");var i=H(O(),!0),o={};Z(o,(function(t){if("option"!==t)throw j(t);G(o,t),D(";")}),(function(){tt(o)})),t.add(e,i,o.comment)}(i,t)}})),t.add(i)}(t,e),!0;case"service":return function(t,e){if(!_.test(e=O()))throw j(e,"service name");var i=new c(e);Z(i,(function(t){if(!$(i,t)){if("rpc"!==t)throw j(t);!function(t,e){var i=e;if(!_.test(e=O()))throw j(e,"name");var o,s,n,r,a=e;D("("),D("stream",!0)&&(s=!0);if(!x.test(e=O()))throw j(e);o=e,D(")"),D("returns"),D("("),D("stream",!0)&&(r=!0);if(!x.test(e=O()))throw j(e);n=e,D(")");var l=new d(a,i,o,n,s,r);Z(l,(function(t){if("option"!==t)throw j(t);G(l,t),D(";")})),t.add(l)}(i,t)}})),t.add(i)}(t,e),!0;case"extend":return function(t,e){if(!x.test(e=O()))throw j(e,"reference");var i=e;Z(null,(function(e){switch(e){case"required":case"repeated":case"optional":Y(t,e,i);break;default:if(!V||!x.test(e))throw j(e);k(e),Y(t,"optional",i)}}))}(t,e),!0}return!1}function Z(t,e,i){var o=I.line;if(t&&(t.comment=L(),t.filename=T.filename),D("{",!0)){for(var s;"}"!==(s=O());)e(s);D(";",!0)}else i&&i(),D(";"),t&&"string"!=typeof t.comment&&(t.comment=L(o))}function Y(t,e,i){var o=O();if("group"!==o){if(!x.test(o))throw j(o,"type");var s=O();if(!_.test(s))throw j(s,"name");s=F(s),D("=");var a=new r(s,H(O()),o,e,i);Z(a,(function(t){if("option"!==t)throw j(t);G(a,t),D(";")}),(function(){tt(a)})),t.add(a),V||!a.repeated||void 0===f.packed[o]&&void 0!==f.basic[o]||a.setOption("packed",!1,!0)}else!function(t,e){var i=O();if(!_.test(i))throw j(i,"name");var o=u.lcFirst(i);i===o&&(i=u.ucFirst(i));D("=");var s=H(O()),a=new n(i);a.group=!0;var l=new r(o,s,i,e);l.filename=T.filename,Z(a,(function(t){switch(t){case"option":G(a,t),D(";");break;case"required":case"optional":case"repeated":Y(a,t);break;default:throw j(t)}})),t.add(a).add(l)}(t,e)}function G(t,e){var i=D("(",!0);if(!x.test(e=O()))throw j(e,"name");var o=e;i&&(D(")"),o="("+o+")",e=R(),P.test(e)&&(o+=e,O())),D("="),K(t,o)}function K(t,e){if(D("{",!0))do{if(!_.test(E=O()))throw j(E,"name");"{"===R()?K(t,e+"."+E):(D(":"),"{"===R()?K(t,e+"."+E):Q(t,e+"."+E,z(!0)))}while(!D("}",!0));else Q(t,e,z(!0))}function Q(t,e,i){t.setOption&&t.setOption(e,i)}function tt(t){if(D("[",!0)){do{G(t,"option")}while(D(",",!0));D("]")}return t}for(;null!==(E=O());)switch(E){case"package":if(!N)throw j(E);q();break;case"import":if(!N)throw j(E);J();break;case"syntax":if(!N)throw j(E);X();break;case"option":if(!N)throw j(E);G(B,E),D(";");break;default:if($(B,E)){N=!1;continue}throw j(E)}return T.filename=null,{package:A,imports:M,weakImports:C,syntax:S,root:e}}T._configure=function(){o=i(20),s=i(9),n=i(3),r=i(2),a=i(12),l=i(7),h=i(1),c=i(10),d=i(13),f=i(5),u=i(0)}},function(t,e){t.exports=f;var i=/[\s{}=;:[\],'"()<>]/g,o=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,s=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,n=/^ *[*/]+ */,r=/^\s*\*?\/*/,a=/\n/g,l=/\s/,h=/\\(.?)/g,c={0:"\0",r:"\r",n:"\n",t:"\t"};function d(t){return t.replace(h,(function(t,e){switch(e){case"\\":case"":return e;default:return c[e]||""}}))}function f(t,e){t=t.toString();var h=0,c=t.length,f=1,u=null,p=null,y=0,m=!1,g=[],v=null;function w(t){return Error("illegal "+t+" (line "+f+")")}function b(e){return t.charAt(e)}function _(i,o){u=t.charAt(i++),y=f,m=!1;var s,l=i-(e?2:3);do{if(--l<0||"\n"===(s=t.charAt(l))){m=!0;break}}while(" "===s||"\t"===s);for(var h=t.substring(i,o).split(a),c=0;c0)return g.shift();if(v)return function(){var e="'"===v?s:o;e.lastIndex=h-1;var i=e.exec(t);if(!i)throw w("string");return h=e.lastIndex,A(v),v=null,d(i[1])}();var n,r,a,u,p;do{if(h===c)return null;for(n=!1;l.test(a=b(h));)if("\n"===a&&++f,++h===c)return null;if("/"===b(h)){if(++h===c)throw w("comment");if("/"===b(h))if(e){if(u=h,p=!1,x(h)){p=!0;do{if((h=P(h))===c)break;h++}while(x(h))}else h=Math.min(c,P(h)+1);p&&_(u,h),f++,n=!0}else{for(p="/"===b(u=h+1);"\n"!==b(++h);)if(h===c)return null;++h,p&&_(u,h-1),++f,n=!0}else{if("*"!==(a=b(h)))return"/";u=h+1,p=e||"*"===b(u);do{if("\n"===a&&++f,++h===c)throw w("comment");r=a,a=b(h)}while("*"!==r||"/"!==a);++h,p&&_(u,h-2),n=!0}}}while(n);var y=h;if(i.lastIndex=0,!i.test(b(y++)))for(;y "+t.len)}function a(t){this.buf=t,this.pos=0,this.len=t.length}var l,h="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new a(t);if("undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer)return new a(new Uint8Array(t));throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new a(t);throw Error("illegal buffer")};function c(){var t=new o(0,0),e=0;if(!(this.len-this.pos>4)){for(;e<3;++e){if(this.pos>=this.len)throw r(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*e)>>>0,t}for(;e<4;++e)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(e=0,this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw r(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function d(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw r(this,8);return new o(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}a.create=n.Buffer?function(t){return(a.create=function(t){return n.Buffer.isBuffer(t)?new(void 0)(t):h(t)})(t)}:h,a.prototype._slice=n.Array.prototype.subarray||n.Array.prototype.slice,a.prototype.uint32=(l=4294967295,function(){if(l=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return l;if((this.pos+=5)>this.len)throw this.pos=this.len,r(this,10);return l}),a.prototype.int32=function(){return 0|this.uint32()},a.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)|0},a.prototype.bool=function(){return 0!==this.uint32()},a.prototype.fixed32=function(){if(this.pos+4>this.len)throw r(this,4);return d(this.buf,this.pos+=4)},a.prototype.sfixed32=function(){if(this.pos+4>this.len)throw r(this,4);return 0|d(this.buf,this.pos+=4)},a.prototype.float=function(){if(this.pos+4>this.len)throw r(this,4);var t=n.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},a.prototype.double=function(){if(this.pos+8>this.len)throw r(this,4);var t=n.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},a.prototype.bytes=function(){var t=this.uint32(),e=this.pos,i=this.pos+t;if(i>this.len)throw r(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(e,i):e===i?new this.buf.constructor(0):this._slice.call(this.buf,e,i)},a.prototype.string=function(){var t=this.bytes();return s.read(t,0,t.length)},a.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw r(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw r(this)}while(128&this.buf[this.pos++]);return this},a.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;;){if(4==(t=7&this.uint32()))break;this.skipType(t)}break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},a._configure=function(){o=i(11),s=i(8);var t=n.Long?"toLong":"toNumber";n.merge(a.prototype,{int64:function(){return c.call(this)[t](!1)},uint64:function(){return c.call(this)[t](!0)},sint64:function(){return c.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},function(t,e,i){var o,s;function n(t,e){return t.name+": "+e+(t.repeated&&"array"!==e?"[]":t.map&&"object"!==e?"{k:"+t.keyType+"}":"")+" expected"}function r(t,e,i,r){var a=r.types;if(t.resolvedType)if(t.resolvedType instanceof o){if(Object.keys(t.resolvedType.values).indexOf(i)<0)return n(t,"enum value")}else{var l=a[e].verify(i);if(l)return t.name+"."+l}else switch(t.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":if(!s.isInteger(i))return n(t,"integer");break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":if(!(s.isInteger(i)||i&&s.isInteger(i.low)&&s.isInteger(i.high)))return n(t,"integer|Long");break;case"float":case"double":if("number"!=typeof i)return n(t,"number");break;case"bool":if("boolean"!=typeof i)return n(t,"boolean");break;case"string":if(!s.isString(i))return n(t,"string");break;case"bytes":if(!(i&&"number"==typeof i.length||s.isString(i)))return n(t,"buffer")}}function a(t,e){switch(t.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":if(!s.key32Re.test(e))return n(t,"integer key");break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":if(!s.key64Re.test(e))return n(t,"integer|Long key");break;case"bool":if(!s.key2Re.test(e))return n(t,"boolean key")}}function l(t){return function(e){return function(i){var o;if("object"!=typeof i||null===i)return"object expected";var l,h={};t.oneofsArray.length&&(l={});for(var c=0;c>>0).fork().uint32(8|s.mapKey[c.keyType])[c.keyType](y[m]),void 0===u?n[d].encode(p[y[m]],a.uint32(18).fork()).ldelim().ldelim():a.uint32(16|u)[f](p[y[m]]).ldelim()}else if(c.repeated){if(p&&p.length)if(c.packed&&void 0!==s.packed[f]){a.uint32((c.id<<3|2)>>>0).fork();for(var g=0;g>>0)).uint32((c.id<<3|4)>>>0):n[d].encode(p[v],a.uint32((c.id<<3|2)>>>0).fork()).ldelim():a.uint32((c.id<<3|u)>>>0)[f](p[v])}else(!c.optional||null!=p&&e.hasOwnProperty(c.name))&&(c.optional||null!=p&&e.hasOwnProperty(c.name)||console.warn("注意啦!!!很大概率会报错 类型:",e.$type?e.$type.name:"不晓得","没有设置对应的属性:",c.name,"检查是不是proto文件属性设置为了required"),void 0===u?c.resolvedType.group?n[d].encode(p,a.uint32((c.id<<3|3)>>>0)).uint32((c.id<<3|4)>>>0):n[d].encode(p,a.uint32((c.id<<3|2)>>>0).fork()).ldelim():a.uint32((c.id<<3|u)>>>0)[f](p))}return a}}}t.exports=n,n._configure=function(){o=i(1),s=i(5)}},function(t,e,i){var o,s,n;function r(t){return"missing required '"+t.name+"'"}function a(t){return function(e){var i=e.Reader,a=e.types,l=e.util;return function(e,h){e instanceof i||(e=i.create(e));for(var c,d=void 0===h?e.len:e.pos+h,f=new this.ctor;e.pos>>3,y=0,m=!1;y>>0:r[i]=a[i]>>>0;break;case"int32":case"sint32":case"sfixed32":c?r[i][h]=0|a[i][h]:r[i]=0|a[i];break;case"uint64":y=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":s.Long?c?r[i][h]=s.Long.fromValue(a[i][h]).unsigned=y:r[i]=s.Long.fromValue(a[i]).unsigned=y:"string"==typeof(c?a[i][h]:a[i])?c?r[i][h]=parseInt(a[i][h],10):r[i]=parseInt(a[i],10):"number"==typeof(c?a[i][h]:a[i])?c?r[i][h]=a[i][h]:r[i]=a[i]:"object"==typeof(c?a[i][h]:a[i])&&(c?r[i][h]=new s.LongBits(a[i][h].low>>>0,a[i][h].high>>>0).toNumber(y):r[i]=new s.LongBits(a[i].low>>>0,a[i].high>>>0).toNumber(y));break;case"bytes":"string"==typeof(c?a[i][h]:a[i])?c?s.base64.decode(a[i][h],r[i][h]=s.newBuffer(s.base64.length(a[i][h])),0):s.base64.decode(a[i],r[i]=s.newBuffer(s.base64.length(a[i])),0):(c?a[i][h]:a[i]).length&&(c?r[i][h]=a[i][h]:r[i]=a[i]);break;case"string":c?r[i][h]=String(a[i][h]):r[i]=String(a[i]);break;case"bool":c?r[i][h]=Boolean(a[i][h]):r[i]=Boolean(a[i])}}}function a(t,e,i,n){var r=n.m,a=n.d,l=n.types,h=n.ksi,c=n.o,d=void 0!==h;if(t.resolvedType)t.resolvedType instanceof o?d?a[i][h]=c.enums===String?l[e].values[r[i][h]]:r[i][h]:a[i]=c.enums===String?l[e].values[r[i]]:r[i]:d?a[i][h]=l[e].toObject(r[i][h],c):a[i]=l[e].toObject(r[i],c);else{var f=!1;switch(t.type){case"double":case"float":d?a[i][h]=c.json&&!isFinite(r[i][h])?String(r[i][h]):r[i][h]:a[i]=c.json&&!isFinite(r[i])?String(r[i]):r[i];break;case"uint64":f=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":"number"==typeof r[i][h]?d?a[i][h]=c.longs===String?String(r[i][h]):r[i][h]:a[i]=c.longs===String?String(r[i]):r[i]:d?a[i][h]=c.longs===String?s.Long.prototype.toString.call(r[i][h]):c.longs===Number?new s.LongBits(r[i][h].low>>>0,r[i][h].high>>>0).toNumber(f):r[i][h]:a[i]=c.longs===String?s.Long.prototype.toString.call(r[i]):c.longs===Number?new s.LongBits(r[i].low>>>0,r[i].high>>>0).toNumber(f):r[i];break;case"bytes":d?a[i][h]=c.bytes===String?s.base64.encode(r[i][h],0,r[i][h].length):c.bytes===Array?Array.prototype.slice.call(r[i][h]):r[i][h]:a[i]=c.bytes===String?s.base64.encode(r[i],0,r[i].length):c.bytes===Array?Array.prototype.slice.call(r[i]):r[i];break;default:d?a[i][h]=r[i][h]:a[i]=r[i]}}}n._configure=function(){o=i(1),s=i(0)},n.fromObject=function(t){var e=t.fieldsArray;return function(t){return function(i){if(i instanceof this.ctor)return i;if(!e.length)return new this.ctor;for(var n=new this.ctor,a=0;a255)return!1;return!0}return{toBytes:function(i){var o=[],s=0;for(i=encodeURI(i);s>>7==0?(e+=String.fromCharCode(t[i]),i+=1):252==(252&o)?(s=(3&t[i])<<30,s|=(63&t[i+1])<<24,s|=(63&t[i+2])<<18,s|=(63&t[i+3])<<12,s|=(63&t[i+4])<<6,s|=63&t[i+5],e+=String.fromCodePoint(s),i+=6):248==(248&o)?(s=(7&t[i])<<24,s|=(63&t[i+1])<<18,s|=(63&t[i+2])<<12,s|=(63&t[i+3])<<6,s|=63&t[i+4],e+=String.fromCodePoint(s),i+=5):240==(240&o)?(s=(15&t[i])<<18,s|=(63&t[i+1])<<12,s|=(63&t[i+2])<<6,s|=63&t[i+3],e+=String.fromCodePoint(s),i+=4):224==(224&o)?(s=(31&t[i])<<12,s|=(63&t[i+1])<<6,s|=63&t[i+2],e+=String.fromCharCode(s),i+=3):192==(192&o)?(s=(63&t[i])<<6,s|=63&t[i+1],e+=String.fromCharCode(s),i+=2):(e+=String.fromCharCode(t[i]),i+=1)}return e}}}();t.exports=i},function(t,e){var i=function(){const t={width:720,height:1280,intrinstics:[1110.828383,0,360,0,1111.21832,640,0,0,1],undistorts:[1e-5,0,0,0,0]},e={width:720,height:960,intrinstics:[720,0,360,0,720,480,0,0,1],undistorts:[0,0,0,0,0]},i={width:288,height:352,intrinstics:[594.25994,0,237.531106,0,594.825983,313.414084,0,0,1],undistorts:[.184825,-.433983,-.003168,-.010542,0]};function o(t,e){const i=[],o=[];for(var s=0;sn?(e=1200*s/1280,i=e):(e=1200*n/1280,i=e),o=s/2,r=n/2,c.intrinstics=[e,0,o,0,i,r,0,0,1],c.undistorts=t.undistorts,c}return{intrinstics:[],undistorts:[]}}}}();t.exports=i},function(t,e,i){t.exports=function(){var t={};function e(e,i,o){return"function"==typeof i?(o=i,i=new t.Root):i||(i=new t.Root),i.load(e,o)}function o(e,i){return i||(i=new t.Root),i.loadSync(e)}function s(e,i,o){return"function"==typeof i?(o=i,i=new t.Root):i||(i=new t.Root),i.parseFromPbString(e,o)}function n(){t.converter._configure(),t.decoder._configure(),t.encoder._configure(),t.Field._configure(),t.MapField._configure(),t.Message._configure(),t.Namespace._configure(),t.Method._configure(),t.ReflectionObject._configure(),t.OneOf._configure(),t.parse._configure(),t.Reader._configure(),t.Root._configure(),t.Service._configure(),t.verifier._configure(),t.Type._configure(),t.types._configure(),t.wrappers._configure(),t.Writer._configure()}if(t.build="minimal",t.Writer=i(16),t.encoder=i(25),t.Reader=i(23),t.util=i(0),t.rpc=i(21),t.roots=i(17),t.verifier=i(24),t.tokenize=i(20),t.parse=i(19),t.common=i(22),t.ReflectionObject=i(4),t.Namespace=i(6),t.Root=i(9),t.Enum=i(1),t.Type=i(3),t.Field=i(2),t.OneOf=i(7),t.MapField=i(12),t.Service=i(10),t.Method=i(13),t.converter=i(28),t.decoder=i(26),t.Message=i(14),t.wrappers=i(27),t.types=i(5),t.util=i(0),t.configure=n,t.load=e,t.loadSync=o,t.parseFromPbString=s,n(),arguments&&arguments.length)for(var r=0;r>>=0)&&t<256)&&(o=r[t])?o:(i=h(t,(0|t)<0?-1:0,!0),s&&(r[t]=i),i):(s=-128<=(t|=0)&&t<128)&&(o=n[t])?o:(i=h(t,t<0?-1:0,!1),s&&(n[t]=i),i)}function l(t,e){if(isNaN(t))return e?v:g;if(e){if(t<0)return v;if(t>=p)return P}else{if(t<=-y)return T;if(t+1>=y)return x}return t<0?l(-t,e).neg():h(t%u|0,t/u|0,e)}function h(t,e,i){return new o(t,e,i)}o.fromInt=a,o.fromNumber=l,o.fromBits=h;var c=Math.pow;function d(t,e,i){if(0===t.length)throw Error("empty string");if("NaN"===t||"Infinity"===t||"+Infinity"===t||"-Infinity"===t)return g;if("number"==typeof e?(i=e,e=!1):e=!!e,(i=i||10)<2||360)throw Error("interior hyphen");if(0===o)return d(t.substring(1),e,i).neg();for(var s=l(c(i,8)),n=g,r=0;r>>0:this.low},A.toNumber=function(){return this.unsigned?(this.high>>>0)*u+(this.low>>>0):this.high*u+(this.low>>>0)},A.toString=function(t){if((t=t||10)<2||36>>0).toString(t);if((n=a).isZero())return h+r;for(;h.length<6;)h="0"+h;r=""+h+r}},A.getHighBits=function(){return this.high},A.getHighBitsUnsigned=function(){return this.high>>>0},A.getLowBits=function(){return this.low},A.getLowBitsUnsigned=function(){return this.low>>>0},A.getNumBitsAbs=function(){if(this.isNegative())return this.eq(T)?64:this.neg().getNumBitsAbs();for(var t=0!=this.high?this.high:this.low,e=31;e>0&&0==(t&1<=0},A.isOdd=function(){return 1==(1&this.low)},A.isEven=function(){return 0==(1&this.low)},A.equals=function(t){return s(t)||(t=f(t)),(this.unsigned===t.unsigned||this.high>>>31!=1||t.high>>>31!=1)&&(this.high===t.high&&this.low===t.low)},A.eq=A.equals,A.notEquals=function(t){return!this.eq(t)},A.neq=A.notEquals,A.ne=A.notEquals,A.lessThan=function(t){return this.comp(t)<0},A.lt=A.lessThan,A.lessThanOrEqual=function(t){return this.comp(t)<=0},A.lte=A.lessThanOrEqual,A.le=A.lessThanOrEqual,A.greaterThan=function(t){return this.comp(t)>0},A.gt=A.greaterThan,A.greaterThanOrEqual=function(t){return this.comp(t)>=0},A.gte=A.greaterThanOrEqual,A.ge=A.greaterThanOrEqual,A.compare=function(t){if(s(t)||(t=f(t)),this.eq(t))return 0;var e=this.isNegative(),i=t.isNegative();return e&&!i?-1:!e&&i?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},A.comp=A.compare,A.negate=function(){return!this.unsigned&&this.eq(T)?T:this.not().add(w)},A.neg=A.negate,A.add=function(t){s(t)||(t=f(t));var e=this.high>>>16,i=65535&this.high,o=this.low>>>16,n=65535&this.low,r=t.high>>>16,a=65535&t.high,l=t.low>>>16,c=0,d=0,u=0,p=0;return u+=(p+=n+(65535&t.low))>>>16,d+=(u+=o+l)>>>16,c+=(d+=i+a)>>>16,c+=e+r,h((u&=65535)<<16|(p&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},A.subtract=function(t){return s(t)||(t=f(t)),this.add(t.neg())},A.sub=A.subtract,A.multiply=function(t){if(this.isZero())return g;if(s(t)||(t=f(t)),i)return h(i.mul(this.low,this.high,t.low,t.high),i.get_high(),this.unsigned);if(t.isZero())return g;if(this.eq(T))return t.isOdd()?T:g;if(t.eq(T))return this.isOdd()?T:g;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(m)&&t.lt(m))return l(this.toNumber()*t.toNumber(),this.unsigned);var e=this.high>>>16,o=65535&this.high,n=this.low>>>16,r=65535&this.low,a=t.high>>>16,c=65535&t.high,d=t.low>>>16,u=65535&t.low,p=0,y=0,v=0,w=0;return v+=(w+=r*u)>>>16,y+=(v+=n*u)>>>16,v&=65535,y+=(v+=r*d)>>>16,p+=(y+=o*u)>>>16,y&=65535,p+=(y+=n*d)>>>16,y&=65535,p+=(y+=r*c)>>>16,p+=e*u+o*d+n*c+r*a,h((v&=65535)<<16|(w&=65535),(p&=65535)<<16|(y&=65535),this.unsigned)},A.mul=A.multiply,A.divide=function(t){if(s(t)||(t=f(t)),t.isZero())throw Error("division by zero");var e,o,n;if(i)return this.unsigned||-2147483648!==this.high||-1!==t.low||-1!==t.high?h((this.unsigned?i.div_u:i.div_s)(this.low,this.high,t.low,t.high),i.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?v:g;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return v;if(t.gt(this.shru(1)))return b;n=v}else{if(this.eq(T))return t.eq(w)||t.eq(_)?T:t.eq(T)?w:(e=this.shr(1).div(t).shl(1)).eq(g)?t.isNegative()?w:_:(o=this.sub(t.mul(e)),n=e.add(o.div(t)));if(t.eq(T))return this.unsigned?v:g;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();n=g}for(o=this;o.gte(t);){e=Math.max(1,Math.floor(o.toNumber()/t.toNumber()));for(var r=Math.ceil(Math.log(e)/Math.LN2),a=r<=48?1:c(2,r-48),d=l(e),u=d.mul(t);u.isNegative()||u.gt(o);)u=(d=l(e-=a,this.unsigned)).mul(t);d.isZero()&&(d=w),n=n.add(d),o=o.sub(u)}return n},A.div=A.divide,A.modulo=function(t){return s(t)||(t=f(t)),i?h((this.unsigned?i.rem_u:i.rem_s)(this.low,this.high,t.low,t.high),i.get_high(),this.unsigned):this.sub(this.div(t).mul(t))},A.mod=A.modulo,A.rem=A.modulo,A.not=function(){return h(~this.low,~this.high,this.unsigned)},A.and=function(t){return s(t)||(t=f(t)),h(this.low&t.low,this.high&t.high,this.unsigned)},A.or=function(t){return s(t)||(t=f(t)),h(this.low|t.low,this.high|t.high,this.unsigned)},A.xor=function(t){return s(t)||(t=f(t)),h(this.low^t.low,this.high^t.high,this.unsigned)},A.shiftLeft=function(t){return s(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?h(this.low<>>32-t,this.unsigned):h(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):h(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},A.shr=A.shiftRight,A.shiftRightUnsigned=function(t){if(s(t)&&(t=t.toInt()),0===(t&=63))return this;var e=this.high;return t<32?h(this.low>>>t|e<<32-t,e>>>t,this.unsigned):h(32===t?e:e>>>t-32,0,this.unsigned)},A.shru=A.shiftRightUnsigned,A.shr_u=A.shiftRightUnsigned,A.toSigned=function(){return this.unsigned?h(this.low,this.high,!1):this},A.toUnsigned=function(){return this.unsigned?this:h(this.low,this.high,!0)},A.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},A.toBytesLE=function(){var t=this.high,e=this.low;return[255&e,e>>>8&255,e>>>16&255,e>>>24,255&t,t>>>8&255,t>>>16&255,t>>>24]},A.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,255&t,e>>>24,e>>>16&255,e>>>8&255,255&e]},o.fromBytes=function(t,e,i){return i?o.fromBytesLE(t,e):o.fromBytesBE(t,e)},o.fromBytesLE=function(t,e){return new o(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)},o.fromBytesBE=function(t,e){return new o(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)}},function(t,e){t.exports=function(t,e,i){var o=i||8192,s=o>>>1,n=null,r=o;return function(i){if(i<1||i>s)return t(i);r+i>o&&(n=t(o),r=0);var a=e.call(n,r,r+=i);return 7&r&&(r=1+(7|r)),a}}},function(t,e){function i(t){return"undefined"!=typeof Float32Array?function(){var e=new Float32Array([-0]),i=new Uint8Array(e.buffer),o=128===i[3];function s(t,o,s){e[0]=t,o[s]=i[0],o[s+1]=i[1],o[s+2]=i[2],o[s+3]=i[3]}function n(t,o,s){e[0]=t,o[s]=i[3],o[s+1]=i[2],o[s+2]=i[1],o[s+3]=i[0]}function r(t,o){return i[0]=t[o],i[1]=t[o+1],i[2]=t[o+2],i[3]=t[o+3],e[0]}function a(t,o){return i[3]=t[o],i[2]=t[o+1],i[1]=t[o+2],i[0]=t[o+3],e[0]}t.writeFloatLE=o?s:n,t.writeFloatBE=o?n:s,t.readFloatLE=o?r:a,t.readFloatBE=o?a:r}():function(){function e(t,e,i,o){var s=e<0?1:0;if(s&&(e=-e),0===e)t(1/e>0?0:2147483648,i,o);else if(isNaN(e))t(2143289344,i,o);else if(e>34028234663852886e22)t((s<<31|2139095040)>>>0,i,o);else if(e<11754943508222875e-54)t((s<<31|Math.round(e/1401298464324817e-60))>>>0,i,o);else{var n=Math.floor(Math.log(e)/Math.LN2);t((s<<31|n+127<<23|8388607&Math.round(e*Math.pow(2,-n)*8388608))>>>0,i,o)}}function i(t,e,i){var o=t(e,i),s=2*(o>>31)+1,n=o>>>23&255,r=8388607&o;return 255===n?r?NaN:s*(1/0):0===n?1401298464324817e-60*s*r:s*Math.pow(2,n-150)*(r+8388608)}t.writeFloatLE=e.bind(null,o),t.writeFloatBE=e.bind(null,s),t.readFloatLE=i.bind(null,n),t.readFloatBE=i.bind(null,r)}(),"undefined"!=typeof Float64Array?function(){var e=new Float64Array([-0]),i=new Uint8Array(e.buffer),o=128===i[7];function s(t,o,s){e[0]=t,o[s]=i[0],o[s+1]=i[1],o[s+2]=i[2],o[s+3]=i[3],o[s+4]=i[4],o[s+5]=i[5],o[s+6]=i[6],o[s+7]=i[7]}function n(t,o,s){e[0]=t,o[s]=i[7],o[s+1]=i[6],o[s+2]=i[5],o[s+3]=i[4],o[s+4]=i[3],o[s+5]=i[2],o[s+6]=i[1],o[s+7]=i[0]}function r(t,o){return i[0]=t[o],i[1]=t[o+1],i[2]=t[o+2],i[3]=t[o+3],i[4]=t[o+4],i[5]=t[o+5],i[6]=t[o+6],i[7]=t[o+7],e[0]}function a(t,o){return i[7]=t[o],i[6]=t[o+1],i[5]=t[o+2],i[4]=t[o+3],i[3]=t[o+4],i[2]=t[o+5],i[1]=t[o+6],i[0]=t[o+7],e[0]}t.writeDoubleLE=o?s:n,t.writeDoubleBE=o?n:s,t.readDoubleLE=o?r:a,t.readDoubleBE=o?a:r}():function(){function e(t,e,i,o,s,n){var r=o<0?1:0;if(r&&(o=-o),0===o)t(0,s,n+e),t(1/o>0?0:2147483648,s,n+i);else if(isNaN(o))t(0,s,n+e),t(2146959360,s,n+i);else if(o>17976931348623157e292)t(0,s,n+e),t((r<<31|2146435072)>>>0,s,n+i);else{var a;if(o<22250738585072014e-324)t((a=o/5e-324)>>>0,s,n+e),t((r<<31|a/4294967296)>>>0,s,n+i);else{var l=Math.floor(Math.log(o)/Math.LN2);1024===l&&(l=1023),t(4503599627370496*(a=o*Math.pow(2,-l))>>>0,s,n+e),t((r<<31|l+1023<<20|1048576*a&1048575)>>>0,s,n+i)}}}function i(t,e,i,o,s){var n=t(o,s+e),r=t(o,s+i),a=2*(r>>31)+1,l=r>>>20&2047,h=4294967296*(1048575&r)+n;return 2047===l?h?NaN:a*(1/0):0===l?5e-324*a*h:a*Math.pow(2,l-1075)*(h+4503599627370496)}t.writeDoubleLE=e.bind(null,o,0,4),t.writeDoubleBE=e.bind(null,s,4,0),t.readDoubleLE=i.bind(null,n,0,4),t.readDoubleBE=i.bind(null,r,4,0)}(),t}function o(t,e,i){e[i]=255&t,e[i+1]=t>>>8&255,e[i+2]=t>>>16&255,e[i+3]=t>>>24}function s(t,e,i){e[i]=t>>>24,e[i+1]=t>>>16&255,e[i+2]=t>>>8&255,e[i+3]=255&t}function n(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function r(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}t.exports=i(i)},function(t,e,i){"use strict";t.exports=function(t,e){var i=new Array(arguments.length-1),o=0,s=2,n=!0;for(;s0&&".."!==e[n-1]?e.splice(--n,2):i?e.splice(n,1):++n:"."===e[n]?e.splice(n,1):++n;return s+e.join("/")};i.resolve=function(t,e,i){return i||(e=s(e)),o(e)?e:(i||(t=s(t)),(t=t.replace(/(?:\/|^)[^/]+$/,"")).length?s(t+"/"+e):e)}},function(t,e){t.exports={nested:{bdarvps:{nested:{BdarVector12f:{fields:{f1:{type:"float",id:1},f2:{type:"float",id:2},f3:{type:"float",id:3},f4:{type:"float",id:4},f5:{type:"float",id:5},f6:{type:"float",id:6},f7:{type:"float",id:7},f8:{type:"float",id:8},f9:{type:"float",id:9},f10:{type:"float",id:10},f11:{type:"float",id:11},f12:{type:"float",id:12}}},BdarVector9f:{fields:{f1:{type:"float",id:1},f2:{type:"float",id:2},f3:{type:"float",id:3},f4:{type:"float",id:4},f5:{type:"float",id:5},f6:{type:"float",id:6},f7:{type:"float",id:7},f8:{type:"float",id:8},f9:{type:"float",id:9}}},BdarVector5f:{fields:{f1:{type:"float",id:1},f2:{type:"float",id:2},f3:{type:"float",id:3},f4:{type:"float",id:4},f5:{type:"float",id:5}}},BdarVector4f:{fields:{f1:{type:"float",id:1},f2:{type:"float",id:2},f3:{type:"float",id:3},f4:{type:"float",id:4}}},BdarVector3f:{fields:{x:{type:"float",id:1},y:{type:"float",id:2},z:{type:"float",id:3}}},BdarVector2f:{fields:{x:{type:"float",id:1},y:{type:"float",id:2}}},BdarVector2d:{fields:{x:{type:"double",id:1},y:{type:"double",id:2}}},BdarVector3d:{fields:{x:{type:"double",id:1},y:{type:"double",id:2},z:{type:"double",id:3}}},BdarTrackerData:{fields:{pose:{type:"BdarVector12f",id:1},poseOrig:{type:"BdarVector12f",id:2},timestamp:{type:"bytes",id:3},frameId:{type:"int32",id:4},status:{type:"int32",id:5},magnet:{rule:"repeated",type:"double",id:6}}},BdarLocalizerData:{fields:{pose:{type:"BdarVector12f",id:1},timestamp:{type:"bytes",id:2},frameId:{type:"int32",id:3},consistent:{type:"int32",id:4}}},BdarTrackerOptimizeData:{fields:{sampleRate:{type:"int32",id:1},trackerData:{rule:"repeated",type:"BdarTrackerData",id:2},localizerData:{rule:"repeated",type:"BdarLocalizerData",id:3}}},BdarPosePrior:{fields:{type:{type:"int32",id:1},prior:{type:"BdarVector12f",id:2},priorAccuracy:{type:"float",id:3},priorConfidence:{type:"float",id:4}}},BdarOCRPrior:{fields:{status:{type:"bytes",id:1},roiCoordinate:{type:"BdarVector4f",id:2}}},BdarVPSRequestData:{fields:{methodType:{type:"int32",id:1},trackerType:{type:"int32",id:2},phoneType:{type:"bytes",id:3},userId:{type:"bytes",id:4},frameId:{type:"int32",id:5},timestamp:{type:"bytes",id:6},trackerStatus:{type:"bool",id:7},trackerPose:{type:"BdarVector12f",id:8},pointIndices:{rule:"repeated",type:"int32",id:9},points_2d:{rule:"repeated",type:"BdarVector2f",id:10},points_3d:{rule:"repeated",type:"BdarVector3f",id:11},cameraIntrinsics:{type:"BdarVector9f",id:12},cameraDistort:{type:"BdarVector5f",id:13},gps:{type:"BdarVector3d",id:14},gravityDirection:{type:"BdarVector3f",id:15},imu:{type:"BdarVector12f",id:16},frame:{type:"bytes",id:17},frameWidth:{type:"int32",id:18},frameHeight:{type:"int32",id:19},frameChannels:{type:"int32",id:20},frameCompressType:{type:"int32",id:21},requestCorrespondence:{type:"bool",id:22},sessionId:{type:"bytes",id:23},version:{type:"bytes",id:24},sceneType:{type:"int32",id:25},trackerOptimizeData:{type:"BdarTrackerOptimizeData",id:26},posePriors:{rule:"repeated",type:"BdarPosePrior",id:27},floorId:{type:"bytes",id:28},bdarOCRPrior:{type:"BdarOCRPrior",id:29}}},BdarMapInfo:{fields:{mapTag:{type:"bytes",id:1},mapQueryConfidence:{type:"float",id:2}}},BdarClientResult:{fields:{buildingId:{type:"bytes",id:1},floorId:{type:"bytes",id:2},locationPoint:{type:"BdarVector2d",id:3},locationTransform:{type:"BdarVector12f",id:4}}},BdarCoupledPose:{fields:{pose:{type:"BdarVector12f",id:1},trackerPose:{type:"BdarVector12f",id:2},timestamp:{type:"bytes",id:3},frameId:{type:"int32",id:4}}},BdarCoupleResult:{fields:{status:{type:"int32",id:1},coupledPose:{rule:"repeated",type:"BdarCoupledPose",id:2},scale:{type:"float",id:3},transform:{type:"BdarVector12f",id:4}}},BdarVPSResponseData:{fields:{userId:{type:"bytes",id:1},frameId:{type:"int32",id:2},timestamp:{type:"bytes",id:3},trackerPose:{type:"BdarVector12f",id:4},imu:{type:"BdarVector12f",id:5},vpsStatus:{type:"bool",id:6},vpsPose:{type:"BdarVector12f",id:7},scale:{type:"float",id:8},points_2d:{rule:"repeated",type:"BdarVector2f",id:9},points_3d:{rule:"repeated",type:"BdarVector3f",id:10},vpsPosition:{type:"BdarVector3d",id:11},version:{type:"bytes",id:12},vpsPoseAccuracy:{type:"float",id:13},vpsPoseConfidence:{type:"float",id:14},sceneType:{type:"int32",id:15},trackerType:{type:"int32",id:16},mapInfo:{type:"BdarMapInfo",id:17},clientResult:{type:"BdarClientResult",id:18},session:{type:"bytes",id:19},trackerOptimizeData:{type:"BdarTrackerOptimizeData",id:20},coupleResult:{type:"BdarCoupleResult",id:21},vpsStatusMsg:{type:"int32",id:22}}},BdarVPSResponseDataList:{fields:{data:{rule:"repeated",type:"BdarVPSResponseData",id:1}}},LocationResponse:{fields:{errCode:{type:"int32",id:1},errMsg:{type:"string",id:2},data:{type:"bytes",id:3}}},SubBdarVPSRequestData:{fields:{sessionId:{type:"bytes",id:23}}},TrackFrameResp:{fields:{errCode:{type:"int32",id:1},errMsg:{type:"string",id:2},data:{type:"bytes",id:3}}},TrackFrameResp2:{fields:{errCode:{type:"int32",id:1},errMsg:{type:"string",id:2},data:{type:"string",id:3}}}}}}}},function(t,e,i){"use strict";function o(t){return{data:function(t){const e=new t.constructor(t.byteLength);return new Uint8Array(e).set(new Uint8Array(t)),e}(t.data),width:t.width,height:t.height}}i.r(e),i.d(e,"SDKWrapper",(function(){return bt}));const s=i(29),n=i(15);function r(t){return s.toBytes(t)}function a(t){for(var e={},i=0,o=t.length;i{e.floor_id===t.floor_id&&(o=e)}),this.baseURL=this._configData.interface.baseURL,console.log("createSession-this.baseURL",this.baseURL),{task:new Promise((t,s)=>{i=wx.request({url:this.baseURL+this._configData.interface.sessionInterface,method:"POST",data:{app_id:o.app_id,poi_id:o.poi_id,map_id:o.map_id,timestamp:e,sign:h({app_id:o.app_id,poi_id:o.poi_id,map_id:o.map_id,timestamp:e})},headers:{"Content-Type":"application/json; charset=UTF-8",Connection:"keep-alive"},success:e=>{0===e.data.err_code&&(console.log("createSssion",e),k=!1,O=e.data.data.session_id,t(e))},fail(t){s({msg:"创建session请求失败",data:t})}})}),taskController:i}}sendTrackframe(t){let e;return this.baseURL=this._configData.interface.baseURL,{trackframe:new Promise((i,o)=>{e=wx.request({url:this.baseURL+this._configData.interface.trackFrameInterface,method:"POST",data:t,headers:{"Content-Type":"multipart/protobuf",Connection:"keep-alive"},dataType:"protobuf",responseType:"arraybuffer",success:t=>{let e=function(t,e,i){let o=T.decode(t.data);return 0===o.errCode&&o.data?P.decode(o.data):void(i||(e.onError({type:10004,msg:o.errMsg+" err_code:"+o.errCode}),console.log(o.errMsg+" err_code:"+o.errCode+" sessionId = "+C)))}(t,I,k);if(void 0===e)return{undefined:void 0,undefined:void 0};let o={};e.data.map(t=>{t.clientResult&&(o.floor=t.clientResult.floorId?l(t.clientResult.floorId):"",o.buildingId=t.clientResult.buildingId?l(t.clientResult.buildingId):"",o.locPoint=t.clientResult.locationPoint),t.session&&(o.session=l(t.session)),t.mapInfo&&t.mapInfo.mapTag&&(o.mapTag=l(t.mapInfo.mapTag)),o.vpsStatusMsg=t.vpsStatusMsg,!0===t.vpsStatus?(o.vpsStatus=t.vpsStatus,o.vpsPose=t.vpsPose,o.trackerPose=t.trackerPose,i(o)):(o.vpsStatus=!1,i(o))})},fail:t=>{o(t),console.log(t)}})}),trackframeController:e}}destroylocatesession(){this.baseURL=this._configData.interface.baseURL,console.log("destroylocatesession-this.baseURL",this.baseURL);let t,e=(new Date).getTime();if(void 0!==O){return{destroy:new Promise((i,o)=>{t=wx.request({url:this.baseURL+this._configData.interface.destroySessionInterface,method:"POST",data:{session_id:O,timestamp:e,app_id:0,sign:h({session_id:O,timestamp:e,app_id:0})},headers:{"Content-Type":"application/json; charset=UTF-8",Connection:"keep-alive"},success:t=>{console.log("destroylocatesession",t.data),0!==t.data.err_code?(I.onError({type:10006,msg:t.data.err_msg}),console.log(t.data.err_msg)):i(t.data),O=void 0},fail:t=>{o({msg:"销毁session请求失败",data:t}),O=void 0}})}),destroyController:t}}}getMapPoi(t){let e,i=((new Date).getTime()/1e3).toFixed();return{getPoi:new Promise((o,s)=>{e=wx.request({url:this._configData.interface.getMapPoiBaseUrl+this._configData.interface.getMapPoiInterface,method:"POST",data:{case_id:t,timestamp:Number(i),sign:c({case_id:t,timestamp:Number(i)})},headers:{"Content-Type":"application/json; charset=UTF-8",Connection:"keep-alive"},success:t=>{console.log("getMapPoi",t),o(t)},fail(t){s({msg:"获取poi数据失败",data:t})}})}),getPoiController:e}}}function D(t,e){let i=e.x-t.x,o=e.y-t.y;return 0===i&&0===o?0:Math.atan2(o,i)-Math.PI/2}function L(t,e){return Math.sqrt((t.x-e.x)*(t.x-e.x)+(t.y-e.y)*(t.y-e.y))}var N,V,B=null,F=0,j=!1,W=!1,z=!1,U=!1,H=!1,q=!1,J=null,X=0,$="",Z={f1:0,f2:0,f3:0,f4:0},Y=[],G=0,K=0;const Q=i(15);class tt{constructor(t,e,i){this.renderer=e,this._configData=t,this.option=i,void 0===E&&this.initWXwasm(),this.cContex=wx.createCameraContext(),this.initSystemInfo(),this.initAccelerometer(),this.initDevice(),this.initCamera(),this.algorithm=new d,this.severInterface=new R(this._configData),this.isPark=!1,this.hasIndoorLoc=!1,this.ak="",this.minTimeQueryServer=1e3,this.haveReceiveSessionMsg=!0,this.haveTrackFrame=!1,this.minDistanceToFinalThreshold=this._configData.minTriggerDistance.final,this.minDistanceToTransferThreshold=this._configData.minTriggerDistance.transfer,this.btDataPath=null,this.startTime=0,this.geo_map_transform_matrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],this.with_bt_but_not_work=!1,this.userId="default_user"}forEachMap(){let t=this;t._configData.map.forEach(e=>{e.floor_id===t.locationOption.floor_id&&(console.log("item.ak =",e.ak),""===e.ak||void 0===e.ak?t.locationOption.onBluetoothAndScanStatus({type:100,msg:"只开启ocr扫描"}):(t.ak=e.ak,console.log("需要打开蓝牙 ak = ",t.ak),wx.getSetting({success(e){e.authSetting["scope.bluetooth"]?(wx.openBluetoothAdapter({success:e=>{t.locationOption.onBluetoothAndScanStatus({type:1,msg:"蓝牙已打开"}),t.getWxBtLocation()},fail:e=>{console.log("打开蓝牙错误:",e),t.locationOption.onBluetoothAndScanStatus({type:99,msg:"提示打开蓝牙"})}}),wx.onBluetoothAdapterStateChange((function(e){t.locationOption.onBluetoothAndScanStatus({type:e.available,msg:"打开蓝牙"})}))):wx.authorize({scope:"scope.bluetooth",success(){wx.openBluetoothAdapter({success:e=>{t.locationOption.onBluetoothAndScanStatus({type:1,msg:"蓝牙已打开"}),t.getWxBtLocation()},fail:e=>{console.log("打开蓝牙错误:",e),t.locationOption.onBluetoothAndScanStatus({type:99,msg:"提示打开蓝牙"})}}),wx.onBluetoothAdapterStateChange((function(e){t.locationOption.onBluetoothAndScanStatus({type:e.available,msg:"打开蓝牙"})}))}})}})))})}initSystemInfo(){let t;wx.getSystemInfo({success:e=>{this.phonetype=e.system,console.log("phonetype = ",this.phonetype),t=e.platform}}),"ios"===t&&(F=1),function(t){let e=t.getAccountInfoSync().miniProgram.appId;e=Q(e+"*-#-$--%%%=216").toUpperCase();for(let t=0;t{(E=e.instance.exports).set_device_platform(F),t.setAlgoParam(),E.set_date_time(X),console.log("WXWebAssembly-初始化成功",E);let i=E.add_test();console.log("verifyResult = ",i)},t=>{console.log("WXWebAssembly-初始化失败",t)})}initAccelerometer(){wx.startAccelerometer({interval:"ui"}),wx.onAccelerometerChange(t=>{let e=this.algorithm.stepFunc(t.x,t.y,t.z,E);e.acc=[(9.8*t.x).toFixed(2),(9.8*t.y).toFixed(2),(9.8*t.z).toFixed(2)],void 0!==this.orientation?e.orientation=[this.orientation[0].toFixed(2),this.orientation[1].toFixed(2),this.orientation[2].toFixed(2)]:e.orientation=[0,0,0],this.acc=[9.8*t.x,9.8*t.y,9.8*t.z],this.locationOption.onStep(e),void 0!==this.locationOption.onSaveAcc&&this.locationOption.onSaveAcc(this.acc)})}stopAccelerometer(){wx.stopAccelerometer({success:t=>{console.log("success = ",t)},fail:t=>{console.log("fail = ",t)}})}initDevice(){wx.startDeviceMotionListening({interval:"ui"}),wx.onDeviceMotionChange(t=>{B=this.algorithm.odometryFunc(t.alpha,t.beta,t.gamma,E),this.orientation=[t.alpha,t.beta,t.gamma],Math.abs(t.beta)<45&&j&&void 0!==this.locationOption&&this.locationOption.onError({type:10010,msg:"手机姿态异常"})})}stopDevice(){wx.stopDeviceMotionListening({success:t=>{console.log("success = ",t)},fail:t=>{console.log("fail = ",t)}})}setLoactionData(t,e){this.locationOption=t,e.map.forEach(e=>{if(e.floor_id===t.floor_id){if(this.ak=e.ak,this.algorithm.set_map_transform(e.transform_matrix,e.scale),void 0!==e.geo_map_transform_matrix&&(this.geo_map_transform_matrix=e.geo_map_transform_matrix,this.algorithm.set_geo_map_transform(e.geo_map_transform_matrix)),void 0!==E)for(let t=0;t<12;t++)E.set_geo_to_vpas_transform_matrix(1,this.geo_map_transform_matrix[t],t);0===e.is_park||void 0===e.is_park?(this.isPark=!1,$=""):(this.isPark=!0,$="")}}),this.startLocation=!0}setCanvasData(t){this._canvas=t}setGlCanvas(t){this.gl_canvas=t}initCamera(){let t,e;V=(new Date).getTime(),N=V;let i=!1,s=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],n=[-1,-1,0],r=3;t=this.cContex.onCameraFrame(t=>{if(i||void 0!==this._canvas&&(this._canvas.width=t.width,this._canvas.height=t.height,i=!0),i){let i=o(t);if(0===Z.f1&&0===Z.f2&&0===Z.f3&&0===Z.f4&&this.isPark){console.log("canvas size = ",this.gl_canvas.width/3,this.gl_canvas.height/3,i.width,i.height);let t=this.gl_canvas.width/3*4/5,e=this.gl_canvas.height/3*1/10,o=(this.gl_canvas.height/3-e)/2,s=(this.gl_canvas.width/3-t)/2;Z=function(t,e,i,o,s,n,r,a){let l=t-(s-r)/2,h=e-(n-a)/2;return[l,h,i+l,o+h]}(s,o,t,e,this.gl_canvas.width/3,this.gl_canvas.height/3,i.width,i.height)}if(null!==B&&!0===this.startLocation&&void 0!==this._canvas){null===J&&this.haveReceiveSessionMsg&&(this.severInterface.createSession(this.locationOption).task.then(t=>{0===t.data.err_code?J=t.data.data.session_id:(this.locationOption.onError({type:10003,msg:t.data.msg}),console.log(t.data.msg)),this.haveReceiveSessionMsg=!0}),this.haveReceiveSessionMsg=!1);let t=(new Date).getTime(),o=t-V,h=t-N;if(null!==J&&this.haveReceiveSessionMsg){var l={};if(o>this.minTimeQueryServer&&!q&&!this.haveTrackFrame&&void 0!==this.acc){if(this.haveTrackFrame=!0,""!==this.ak&&void 0!==this.ak){if(E.get_vpas_translation_from_geo)for(let t=0;t<3;t++)n[t]=E.get_vpas_translation_from_geo(t);if(-1!==n[0]&&-1!==n[1]&&n[0]!==Number.NaN&&n[1]!==Number.NaN&&""!==n[0]&&""!==n[1]){s[0]=n[0],s[1]=n[1],r=1;let t={type:r,prior:null,priorAccuracy:10,priorConfidence:0},e=a(s),i=1;t.prior=e,t.priorConfidence=i,Y[0]=t,this.with_bt_but_not_work=!1}else this.with_bt_but_not_work=!0,this.haveTrackFrame=!1}if(void 0!==this.renderer.priorCrossFloor&&!j){E.transform_map_coodinate_to_translation(this.renderer.priorCrossFloor[0],this.renderer.priorCrossFloor[1]);let t=[];for(let e=0;e<2;e++)t[e]=E.get_transform_vpas_translation(e);s[0]=t[0],s[1]=t[1],r=1;let e={type:r,prior:null,priorAccuracy:10,priorConfidence:0},i=a(s),o=1;e.prior=i,e.priorConfidence=o,Y[0]=e}e={pixels:i.data,pixelWidth:i.width,pixelHeight:i.height,phonetype:this.phonetype,lng:void 0,lat:void 0,posePriors:Y,odometry:B,ocrStatus:$,ocrCoordinate:Z,acc:this.acc,deviceOrientation:this.orientation,floorId:this.locationOption.floor_id};let t=S(J,this._canvas,e,0,this.locationOption,this.userId);if(t!=={}&&!this.with_bt_but_not_work){let e=this.severInterface.sendTrackframe(t).trackframe;if(void 0===e)return void(this.haveTrackFrame=!1);V=(new Date).getTime(),1,e.then(t=>{if(this.haveTrackFrame=!1,!0===t.vpsStatus&&this.startLocation){$="",t.wasmFunction=E,l.vpsStatus=t.vpsStatus,l.vpsPose=t.vpsPose,l.trackerPose=t.trackerPose;let e=this.algorithm.locationSuccessEvery(E,l);if(null===e)W=!1;else{N=(new Date).getTime(),W=!0,t.locX=e.locX,t.locY=e.locY,t.vpasX=e.vpasX,t.vpasY=e.vpasY,G=e.vpasX,K=e.vpasY,j||(this.locationOption.onFirstSuccess(t),j=!0,this.minTimeQueryServer=1500),1;let i={locStatus:!0,locX:e.locX,locY:e.locY};this.locationOption.onLocateEvent(i)}}else{let t={locStatus:!1};this.locationOption.onLocateEvent(t)}-1===t.vpsStatusMsg&&(console.log("无效的车位号"),this.locationOption.onError({type:10009,msg:"无效的车位号"})),(!1===t.vpsStatus&&!1===j||!1===W)&&(h>5e3&&!1===z&&(this.locationOption.onError({type:10005,msg:"首帧定位超时5s"}),z=!0),h>8e3&&!1===U&&(this.locationOption.onError({type:10007,msg:"首帧定位超时8s"}),U=!0))}),this.haveTrackFrame=!1}}}}if(H&&j&&!q){let t=this.algorithm.locationOnceSuccessFun(E,this.renderer);if(null===t)return;let e={type:t.priorType,prior:null,priorAccuracy:10,priorConfidence:0};e.prior=t.posePriors,e.priorConfidence=t.priorConfidence,Y[0]=e,t.vpasX=G,t.vpasY=K,this.locationOption.distanceOfNextPoint(t.distanceToNextPoint),this.locationOption.onEverySuccess(t),(t.distance=s){let r=n.add(this.segments[i].direction().multiplyScalar(s));e.push(r),n=r.clone(),o+=s,s=t}else s-=a,n=this.segments[i].ep.clone(),i+=1,o=0;i>=this.segments.length&&(r=!0)}return e}}class ot{constructor(t,e,i,o,s){this.THREE=t,this.scene=e,this.camera=i,this.onResLoaded=o,this.onScreenModelInfo=s.onScreenArrow,this.onScreenModel=void 0,this.loadArrowModel(),this.position=new t.Vector3(0,-.05,-.25)}loadArrowModel(){let t=this.THREE,e=this.onScreenModelInfo.arrowURL.split("/");console.log("onScreenModelInfo url = ",e);let i=e[e.length-1],o=this.onScreenModelInfo.arrowURL.replace(i,""),s=this.onScreenModelInfo.arrowPosition,n=this.onScreenModelInfo.arrowRotation,r=this.onScreenModelInfo.arrowScale;const a=(new t.GLTFLoader).setPath(o);let l=this;a.load(i,(function(t){l.onScreenModel=t.scene,l.onScreenModel.position.set(s[0],s[1],s[2]),l.onScreenModel.scale.set(r[0],r[1],r[2]),l.onScreenModel.visible=!1,l.onScreenModel.rotateX(n[0]),l.onResLoaded(),console.log("ARNaviRenderer Res Loaded"),l.camera.add(l.onScreenModel)}))}setScreenArrowPosition(t){this.position=t}reset(t){void 0!==this.onScreenModel&&(this.onScreenModel.visible=!1,t&&(this.camera.remove(this.onScreenModel),this.onScreenModel=void 0))}release(){void 0!==this.onScreenModel&&(this.onScreenModel.visible=!1,this.camera.remove(this.onScreenModel),this.onScreenModel=void 0)}hide(){void 0!==this.onScreenModel&&(this.onScreenModel.visible=!1)}update(t){void 0!==this.onScreenModel?(this.onScreenModel.visible=!0,this.onScreenModel.position.set(this.position.x,this.position.y,this.position.z),this.onScreenModel.quaternion.x=t.x,this.onScreenModel.quaternion.y=t.y,this.onScreenModel.quaternion.z=t.z,this.onScreenModel.quaternion.w=t.w,this.onScreenModel.rotateZ(Math.PI)):console.log("this.onScreenModel === undefined")}}class st{constructor(t,e,i,o,s){this.THREE=t,this.scene=e,this.camera=i,this.onResLoaded=o,this.arrowRenderMode=2,this.arrowInfo=s.arrow,this.finalInfo=s.final,this.onScreenArrowCtrl=new ot(t,e,i,o,s),this.arrows=[],this.allFinalWayPointsModel=[],this.loadArrowModel(),this.loadFinalModel(0,0,0),this.inited=!1,this.oneMaterial=new t.MeshStandardMaterial({color:350973}),this.twoMaterial=new t.MeshStandardMaterial({color:41120}),this.allModels=[],this.allModelsStatus=[1,1,1,1,1,1],this.frameCount=0,this.intervalCount=15,this.showArrowCount=6,this.lastWayPointPosition=void 0,this.speed=s.arrow.arrowMoveSpeed,this.time=[],this.localWayPoints=[],this.destination=[],this.positionKF=null,this.mixer=null,this.clipAction=null,this.clip=null,this.clock=new t.Clock,this.moveArrow=null,this.localNextPoint=[30,0,0],this.localNextNextPoint=[0,20,0],this.localNextNextNextPoint=[0,0,0],this.newLocalNextPoint=[0,0,0],this.newLocalNextNextPoint=[0,0,0],this.cameraPosition=[0,0,0],this.moveStart=!0,this.totalTime=0,this.totalCountTime=0,this.moveArrowRenderMode=!0,this.moveArrowShowDistance=s.arrow.showDistance,this.finalShowDistance=s.final.showDistance,this.startTime=0,this.intervalTime=0,this.lastRadians=0,this.lostUpdateTime=0,this.segmentNum=2,this.locationOption=null,this.timeOut=this.arrowInfo.downloadTimeout}setScreenArrowPosition(t){void 0!==this.onScreenArrowCtrl&&this.onScreenArrowCtrl.setScreenArrowPosition(t)}loadFinalModel(t,e,i){let o=this.THREE,s=this.finalInfo.URL.split("/"),n=s[s.length-1],r=this.finalInfo.URL.replace(n,""),a=this.finalInfo.rotation,l=this.finalInfo.scale;const h=(new o.GLTFLoader).setPath(r);let c=this;h.load(n,(function(o){let s=o.scene;s.position.set(t,e,i),s.scale.set(l[0],l[1],l[2]),s.rotateX(a[0]),s.visible=!1,c.allFinalWayPointsModel.push(s),c.scene.add(s)}))}loadArrowModel(){let t=this.THREE,e=this.arrowInfo.arrowURL.split("/"),i=e[e.length-1],o=this.arrowInfo.arrowURL.replace(i,""),s=this.arrowInfo.arrowPosition,n=this.arrowInfo.arrowRotation,r=(new t.GLTFLoader).setPath(o),a=this;r.load(i,(function(t){a.arrow_prototype=t.scene,a.arrow_prototype.position.set(s[0],s[1],s[2]),a.arrow_prototype.visible=!1,a.arrow_prototype.rotateX(n[0]),a.onResLoaded(),console.log("ARNaviRenderer Res Loaded")}))}setMoveArrow(){if(void 0===this.arrow_prototype)return;let t=this.arrow_prototype.clone();t.scale.set(100,100,100),t.rotateZ(Math.PI/2),t.rotateX(-Math.PI/2),t.visible=!1,this.moveArrow=t.clone(),this.moveArrow.position.set(0,0,0),1!==this.arrowRenderMode&&this.scene.add(this.moveArrow)}setArrow(t){let e=this.arrow_prototype.clone();e.position.set(t.x,t.y,t.z),e.scale.set(this.arrowInfo.arrowScale[0],this.arrowInfo.arrowScale[1],this.arrowInfo.arrowScale[2]),e.rotateZ(this.arrowInfo.arrowRotation[2]),e.rotateX(this.arrowInfo.arrowRotation[0]),e.rotateY(this.arrowInfo.arrowRotation[1]),e.visible=!1,this.arrows.push(e),this.moveArrow=e.clone(),this.moveArrow.position.set(this.arrowInfo.arrowPosition),1!==this.arrowRenderMode&&(this.scene.add(e),this.scene.add(this.moveArrow))}setArrowRenderMode(t){this.arrowRenderMode=t,console.log("this.arrowRenderMode = ",this.arrowRenderMode),0===this.arrowRenderMode&&void 0!==this.onScreenArrowCtrl&&this.onScreenArrowCtrl.reset()}updateRoute(t,e,i){this.lastWayPointPosition=t[t.length-1].clone(),t.push(e),this.locationOption=i;let o=(new Date).getTime(),s=0;for(;void 0===this.arrow_prototype;){if(this.locationOption.onResourceLoaded({status:-1}),(new Date).getTime()-o>=this.timeOut&&(this.loadArrowModel(),o=(new Date).getTime(),s+=1),2===s)return this.locationOption.onResourceLoaded({status:-2}),void console.log("load arrow model time is out")}this.locationOption.onResourceLoaded({status:0}),void 0!==this.allFinalWayPointsModel[0]&&(this.allFinalWayPointsModel[0].position.set(e.x,e.y,e.z-0),this.scene.add(this.allFinalWayPointsModel[0]));let n=new it(t).sampling(1);this.arrows.length=0;for(let t=0;t=t*this.intervalCount&&this.frameCount<(t+1)*this.intervalCount)for(let e=0;e1&&(r=1),Math.acos(r)}getFootOfPerpendicular(t,e,i){let o=this.THREE;const s=e[0]-i[0],n=e[1]-i[1],r=e[2]-i[2];if(Math.abs(s)<1e-8&&Math.abs(n)<1e-8&&Math.abs(r)<1e-8)return e;let a=(t.x-e[0])*(e[0]-i[0])+(t.y-e[1])*(e[1]-i[1])+(t.z-e[2])*(e[2]-i[2]);return a/=Math.pow(s,2)+Math.pow(n,2)+Math.pow(r,2),new o.Vector3(e[0]+a*s,e[1]+a*n,e[2]+a*r)}decidePointBetweenTwo(t,e,i){if(void 0===t||void 0===e||void 0===i)return!1;let o=this.getFootOfPerpendicular(t,e,i),s=new this.THREE.Vector3(e[0],e[1],e[2]),n=new this.THREE.Vector3(i[0],i[1],i[2]);this.distanceCameraToFootPoint=L(o,t),this.segmentLength=L(s,n),this.footPointToFirstPointDistance=L(s,o);let r=new this.THREE.Vector3;r.subVectors(s,o);let a=new this.THREE.Vector3;a.subVectors(n,o);let l=r.dot(a)/(r.length()*a.length());l>1&&(l=1),l<-1&&(l=-1);let h=180*Math.acos(l)/Math.PI;return!(h>=0&&h<90)}update(t,e,i,o,s,n,r,a){if(0===s.length)return console.error("Error:::remainingWayPoints length is 0!"),[void 0,void 0,void 0,void 0];n||r||(this.isAlmostArrive=3===o||4===o||5===o||6===o||7===o||8===o||9===o),0===this.startTime||(this.intervalTime=(new Date).getTime()-this.startTime),this.startTime=(new Date).getTime();let l=this.THREE;if(!this.inited)return[0,void 0,void 0,void 0];if(this.moveArrowRenderMode){if(null!==this.moveArrow&&this.moveStart&&void 0!==this.clock){this.totalCountTime=0,this.moveArrow.visible=!0,this.time=[0],this.localWayPoints=[];let e=Math.sqrt(Math.pow(t.x-s[0][0],2)+Math.pow(t.y-s[0][1],2)),i=0,o=0,n=0,r=0;if(this.localWayPoints.push([t.x,t.y,0]),e>this.moveArrowShowDistance){let e=s[0][0]-t.x,i=s[0][1]-t.y,o=Math.sqrt(e*e+i*i);this.localWayPoints.push([t.x+this.moveArrowShowDistance*e/o,t.y+this.moveArrowShowDistance*i/o,0]),this.time.push(this.moveArrowShowDistance/this.speed),this.totalTime=this.time[1]}else{for(r=1,o=e,this.localWayPoints.push(s[0]),this.time.push(e/this.speed),this.totalTime=this.time[1];os.length-1);)i=Math.sqrt(Math.pow(s[r][0]-s[r-1][0],2)+Math.pow(s[r][1]-s[r-1][1],2)),o+=i,this.localWayPoints.push(s[r]),this.time.push(this.time[r]+i/this.speed),r++;if(o>=this.moveArrowShowDistance){n=this.moveArrowShowDistance-o+i;let t=s[r-1][0]-s[r-2][0],e=s[r-1][1]-s[r-2][1],a=Math.sqrt(t*t+e*e);this.localWayPoints[r][0]=this.localWayPoints[r-1][0]+n*t/a,this.localWayPoints[r][1]=this.localWayPoints[r-1][1]+n*e/a,this.time[r]=this.time[r-1]+n/this.speed,this.totalTime=this.time[r]}else r>1&&(this.localWayPoints.push(s[r-1]),i=Math.sqrt(Math.pow(s[r-1][0]-s[r-2][0],2)+Math.pow(s[r-1][1]-s[r-2][1],2)),this.time.push(this.time[r-1]+i/this.speed),this.totalTime=this.time[r])}let a=[];for(let t=0;t=this.totalTime&&(this.clipAction.stop(),this.mixer.uncacheAction(this.clipAction,this.moveArrow),this.positionKF,this.clip=null,this.moveArrow.position.set(this.camera.position),this.moveStart=!0,this.localWayPoints[1][0]+=1e-7,this.localWayPoints[1][2]=0,t.fromArray(this.localWayPoints),this.moveArrow.lookAt(t),this.moveArrow.rotateX(this.arrowInfo.arrowRotation[0]),this.moveArrow.rotateY(this.arrowInfo.arrowRotation[1]),this.moveArrow.rotateZ(this.arrowInfo.arrowRotation[2])),this.totalCountTime>=this.time[this.time.length-2]&&this.totalCountTime3)for(let e=1;e=this.time[e]&&this.totalCountTime1&&(p.x=this.localWayPoints[this.localWayPoints.length-1][0],p.y=this.localWayPoints[this.localWayPoints.length-1][1]);let y=this.calculateNaviArrowOrientation(t,p,c);f=y[1],u=y[0];let m=new l.Euler(Math.PI/2,u,0,"XYZ"),g=new l.Matrix4,v=new l.Matrix4;v.makeRotationFromEuler(m),g=(new l.Matrix4).getInverse(e),g.multiply(v);let w=new l.Euler;if(w.setFromRotationMatrix(g),0!==this.arrowRenderMode){let t=new l.Quaternion;t.setFromRotationMatrix(g),this.onScreenArrowCtrl.update(t)}if(!this.moveArrowRenderMode&&(fthis.finalShowDistance||7!==o)){for(let t=0;t{t.isMesh&&(t.material=s)}),i.panel=o}))}loadTextFont(){let t=this.THREE,e=this;(new t.FontLoader).load("https://ar-fm.cdn.bcebos.com/home_3d_model/vpas_applet/font/PingFang_SC_Regular_Regular.json",(function(t){e.font=t}))}reset(t){void 0!==this.textMesh&&(this.scene.remove(this.textMesh),t&&(this.textMesh=void 0)),void 0!==this.panel&&(this.scene.remove(this.panel),t&&(this.panel=void 0)),void 0!==this.font&&t&&(this.font=void 0)}createText(t,e,i){let o=this.THREE;if(void 0!==this.panel&&(this.panel.visible=!0),t!==this.last_message){void 0!==this.textMesh&&(this.scene.remove(this.textMesh),this.textMesh.geometry.dispose(),this.textMesh.material.dispose(),this.textMesh=void 0);let e=new o.MeshBasicMaterial({color:this.textColor,transparent:!0,opacity:1,side:o.DoubleSide}),i=this.font.generateShapes(t+"米",.15),s=new o.ShapeBufferGeometry(i);s.computeBoundingBox(),this.textMesh=new o.Mesh(s,e),this.textMesh.rotation.x=-Math.PI/2,this.textMesh.rotation.y=0,this.textMesh.add(this.panel),this.scene.add(this.textMesh),this.last_message=t,s.center()}this.textMesh.position.set(e.x,e.y,e.z-1.7),void 0!==this.textMesh&&void 0!==this.panel&&(this.textMesh.rotation.y=-D(this.textMesh.position,i),this.panel.rotation.x=-1*Math.PI/180,this.panel.position.set(0,0,-.1))}loadTextModel(t,e,i){void 0!==this.font&&this.createText(t,e,i)}hideTextModel(){void 0!==this.textMesh&&(this.textMesh.visible=!1),void 0!==this.panel&&(this.panel.visible=!1)}setVisible(t){void 0!==this.textMesh&&(this.textMesh.visible=t)}}class rt{constructor(t,e,i,o,s,n,r,a){this.THREE=t,this.scene=e,this.configInfo=r,this.isShow=a,this.turnLeftAngleThreshold=this.configInfo.turnLeft.angleThreshold,this.turnRightAngleThreshold=this.configInfo.turnRight.angleThreshold,this.showDistance=15,n?(this.location=new t.Vector3(s.x,s.y,s.z),this.postLocation=new t.Vector3(i.x,i.y,i.z),this.preLocation=new t.Vector3(o.x,o.y,o.z)):(this.location=new t.Vector3(i.x,i.y,i.z),this.postLocation=new t.Vector3(s.x,s.y,s.z),this.preLocation=new t.Vector3(o.x,o.y,o.z)),this.isAppended=n,this.isLeftArrow=!1,this.model=void 0,this.angle=0,this.angleThreshold=15,this.isAppended&&(this.angleThreshold=10),this.isNormalArrow=!1,this.isLeft()?this.angle>this.turnLeftAngleThreshold?(this.loadModelLeft(),this.isLeftArrow=!0):this.isNormalArrow=!0:this.angle>this.turnRightAngleThreshold?(this.loadModelRight(),this.isLeftArrow=!1):this.isNormalArrow=!0,this.arTextCtrl=new nt(t,e,r),this.distance=Number.MAX_VALUE}reset(t){void 0!==this.model&&(this.scene.remove(this.model),t&&(this.model=void 0)),void 0!==this.arTextCtrl&&(this.arTextCtrl.reset(),t&&(this.arTextCtrl=void 0))}loadModelLeft(){let t=this.THREE;this.showDistance=this.configInfo.turnLeft.showDistance;let e=this.configInfo.turnLeft.URL,i=e.split("/"),o=i[i.length-1],s=e.replace(o,""),n=this.configInfo.turnLeft.scale,r=this.configInfo.turnLeft.rotation;const a=(new t.GLTFLoader).setPath(s);let l=this;a.load(o,(function(e){console.log("zuo.gltf loaded");let i=e.scene;i.scale.set(n[0],n[1],n[2]),i.visible=!0,i.rotateX(r[0]),i.rotateY(r[1]),i.rotateZ(r[2]),l.m_model=i;let o=new t.Object3D;o.add(i),l.model=o,l.model.position.set(l.location.x,l.location.y,-1.5),l.scene.add(l.model),l.model.visible=!1}))}loadModelRight(){let t=this.THREE;this.showDistance=this.configInfo.turnRight.showDistance;let e=this.configInfo.turnRight.URL,i=e.split("/"),o=i[i.length-1],s=e.replace(o,""),n=this.configInfo.turnRight.scale,r=this.configInfo.turnRight.rotation;const a=(new t.GLTFLoader).setPath(s);let l=this;a.load(o,(function(e){console.log("you.gltf loaded");let i=e.scene;i.scale.set(n[0],n[1],n[2]),i.visible=!0,i.rotateZ(r[2]),i.rotateX(r[0]),i.rotateY(r[1]),l.m_model=i;let o=new t.Object3D;o.add(i),l.model=o,l.model.position.set(l.location.x,l.location.y,-1.5),l.scene.add(l.model),l.model.visible=!1}))}isLeft(){let t=this.THREE,e=new t.Vector3,i=new t.Vector3;this.isAppended?(e.subVectors(this.location,this.preLocation),i.subVectors(this.postLocation,this.preLocation)):(e.subVectors(this.location,this.preLocation),i.subVectors(this.postLocation,this.location)),e.normalize(),i.normalize();let o=new t.Vector3;o.crossVectors(e,i);let s=e.dot(i)/(e.length()*i.length());s>1?s=1:s<-1&&(s=-1),this.angle=180*Math.acos(s)/Math.PI;let n=!1;return n=this.isAppended?o.z>0:o.z<0,n}setVisible(t){void 0!==this.model&&(t&&this.distancethis.showDistance)this.model.visible=!1,this.arTextCtrl.hideTextModel();else{this.model.visible=!0;let e=Math.round(this.distance);this.arTextCtrl.loadTextModel(e,this.location,t)}return this.model.position.set(this.location.x,this.location.y,-1.5),this.model.rotation.z=D(this.model.position,t),e=null,[this.distance,this.isLeftArrow,this.location]}}class at{constructor(t,e,i,o,s){this.THREE=t,this.scene=e,this.isUp=o,this.configInfo=s,this.showDistance=15,this.location=new t.Vector3(i.x,i.y,i.z),this.model=null,this.isUp?this.loadModelUp():this.loadModelDown(),console.log("Load EscalatorCtrl"),this.arTextCtrl=new nt(t,e,s),this.distance=Number.MAX_VALUE}reset(t){null!==this.model&&(this.scene.remove(this.model),t&&(this.model=null)),void 0!==this.arTextCtrl&&(this.arTextCtrl.reset(),t&&(this.arTextCtrl=void 0))}setVisible(t){null!==this.model&&(t&&this.distancethis.showDistance)this.model.visible=!1,this.arTextCtrl.hideTextModel();else{this.model.visible=!0;let e=Math.round(this.distance);this.arTextCtrl.loadTextModel(e,this.location,t)}return this.model.position.set(this.location.x,this.location.y,-1.5),this.model.rotation.z=D(this.model.position,t),e=null,[this.distance,this.isUp,this.location]}}class lt{constructor(t,e,i,o,s){this.THREE=t,this.scene=e,this.isUp=o,this.configInfo=s,this.showDistance=15,this.location=new t.Vector3(i.x,i.y,i.z),this.model=null,this.isUp?this.loadModelUp():this.loadModelDown(),console.log("Load ElevatorCtrl"),this.arTextCtrl=new nt(t,e,s),this.distance=Number.MAX_VALUE}reset(t){null!==this.model&&(this.scene.remove(this.model),t&&(this.model=null)),void 0!==this.arTextCtrl&&(this.arTextCtrl.reset(),t&&(this.arTextCtrl=void 0))}setVisible(t){null!==this.model&&(t&&this.distancethis.showDistance)this.model.visible=!1,this.arTextCtrl.hideTextModel();else{this.model.visible=!0;let e=Math.round(this.distance);this.arTextCtrl.loadTextModel(e,this.location,t)}return this.model.position.set(this.location.x,this.location.y,-1.5),this.model.rotation.z=D(this.model.position,t),e=null,[this.distance,this.isUp,this.location]}}var ht=1,ct=1;class dt{constructor(t,e,i,o,s){this.THREE=t,this.scene=e,this.camera=i,this.name=null,this.res_type=0,this.res_url=null,this.position=[0,0,0],this.orientation=[0,0,0],this.scale=1,this.event_type=0,this.event_url=null,this.showing=1,this.rotate_type=1,this.poiModel=null,this.box=null,this.eventCallBack=o,this.configInfo=s,this.rayCaster=new t.Raycaster,this.touchPoint=[0,0]}updateData(t,e,i,o,s,n,r,a,l,h){this.THREE;this.name=t,this.res_type="img"===e?0:1,this.res_url=i,console.log("this.res_type = ",this.res_type),this.position=JSON.parse(o),this.orientation=""===s?[0,0,0]:JSON.parse(s),this.event_type=r,this.event_url=a,this.showing=l,this.rotate_type=h,this.scale=n;var c=this;let d=this.res_url.split("://");"http"===d[0]&&(this.res_url=d[0]+"s://"+d[1]),0===this.res_type?wx.getImageInfo({src:this.res_url,success(t){ht=t.width,ct=t.height,c.createPoiContent(c.poiModel)}}):c.createPoiContent(c.poiModel)}createPoiContent(t){let e=this.THREE;switch(this.res_type){case 0:let t=(new e.TextureLoader).load(this.res_url),i=(new e.TextureLoader).load(this.res_url);i.center=new e.Vector2(.5,.5),i.rotation=Math.PI,i.flipY=!1;let o=[new e.MeshBasicMaterial({map:t,side:e.FrontSide}),new e.MeshBasicMaterial({map:i,side:e.BackSide})],s=new e.PlaneGeometry(1,ct/ht);for(let t=0,e=s.faces.length;t0){if(this.intersected=e[0].object,this.intersected.name==="poi"+this.name){console.log("processTouch object = ",this.name);let t={};t.poiName=this.name,t.eventType=this.event_type,t.eventUrl=this.event_url,this.eventCallBack.onPoiEvent(t)}}else this.intersected=null}}update(){if(null===this.poiModel)return;if(!this.showing&&null!==this.poiModel)return this.poiModel.visible=!1,void(null!==this.box&&(this.box.visible=!1));if(L(this.poiModel.position,this.camera.position)>this.configInfo.mapPoi.showDistance)return this.poiModel.visible=!1,void(null!==this.box&&(this.box.visible=!1));switch(this.poiModel.visible=!0,null!==this.box&&(this.box.visible=!0),this.rotate_type){case 1:this.poiModel.rotateY(.1);break;case 2:this.poiModel.rotation.y=-D(this.poiModel.position,this.camera.position),null!==this.box&&(this.box.rotation.y=-D(this.box.position,this.camera.position))}}}class ft{constructor(t,e,i,o,s){this.THREE=t,this.scene=e,this.isParkToMall=o,this.configInfo=s,this.showDistance=15,this.location=new t.Vector3(i.x,i.y,i.z),this.model=null,this.isParkToMall?this.loadPark():this.loadMall(),this.arTextCtrl=new nt(t,e,s),this.distance=Number.MAX_VALUE}reset(t){null!==this.model&&(this.scene.remove(this.model),t&&(this.model=null)),void 0!==this.arTextCtrl&&(this.arTextCtrl.reset(),t&&(this.arTextCtrl=void 0))}setVisible(t){null!==this.model&&(t&&this.distancethis.showDistance)this.model.visible=!1,this.arTextCtrl.hideTextModel();else{this.model.visible=!0;let e=Math.round(this.distance);this.arTextCtrl.loadTextModel(e,this.location,t)}return this.model.position.set(this.location.x,this.location.y,-1.5),this.model.rotation.z=D(this.model.position,t),[this.distance,this.isParkToMall,this.location]}}class ut{constructor(t,e,i,o,s){this.THREE=t,this.scene=e,this.isStepLadderUp=o,this.configInfo=s,this.showDistance=15,this.location=new t.Vector3(i.x,i.y,i.z),this.model=null,this.isStepLadderUp?this.loadStepLadderUp():this.loadStepLadderDown(),this.arTextCtrl=new nt(t,e,s),this.distance=Number.MAX_VALUE}reset(t){null!==this.model&&(this.scene.remove(this.model),t&&(this.model=null)),void 0!==this.arTextCtrl&&(this.arTextCtrl.reset(),t&&(this.arTextCtrl=void 0))}setVisible(t){null!==this.model&&(t&&this.distancethis.showDistance)this.model.visible=!1,this.arTextCtrl.hideTextModel();else{this.model.visible=!0;let e=Math.round(this.distance);this.arTextCtrl.loadTextModel(e,this.location,t)}return this.model.position.set(this.location.x,this.location.y,-1.5),this.model.rotation.z=D(this.model.position,t),[this.distance,this.isStepLadderUp,this.location]}}class pt{constructor(t,e,i){this.THREE=t,this.scene=e,this.location=new t.Vector3(i.x,i.y,i.z),this.distance=Number.MAX_VALUE}reset(){}setVisible(){}update(t){let e=new this.THREE.Vector3;return e.subVectors(this.location,t),e.z=0,this.distance=e.length(),[this.distance,0,this.location]}}var yt,mt;class gt{constructor(t,e,i,o){console.log("ARNaviRenderer constructor..."),this.THREE=t,this.canvas=e,this.onResLoaded=i,this.configInfo=o,this.minCoverPointDistance=this.configInfo.interaction.minCoverPointDistance,this.renderer=null,this.camera=null,this.scene=null,this.initScene(this.THREE,this.canvas),this.arrowCtrl=new st(t,this.scene,this.camera,i,this.configInfo),this.textCtrl=new nt(t,this.scene,this.configInfo,this.camera,i),this.wayPointCtrls=[],this.wayPointCtrlsClone=[],this.wayPointCtrlsStatus=[],this.driftAwayDistanceThreshold=5,this.driftAwayAngleThreshold=60,this.driftAwayAngle=0,this.nextLocation=void 0,this.nextNextLocation=void 0,this.final=void 0,this.finalClone=void 0,this.type=-1,this.way_point_index=0,this.min_distance=Number.MAX_VALUE,this.next_point_distance=Number.MAX_VALUE,this.allMapPois=[],this.touchPoint=[0,0],this.isTouch=!1,this.rayCaster=new t.Raycaster,this.naviData=void 0,this.haveFoundNextPoint=!1,this.cameraToLstFootPointDistance=Number.MAX_VALUE,this.distanceCameraToFootPoint=0,this.segmentLength=0,this.footPointToFirstPointDistance=0,this.nextPointIsFinal=!1,this.threshold_to_next_point=5,this.wayPointIndex=[],this.wayPointindexClone=[],this.nextIsFinal=!1,this.nextIsTransfer=!1,this.lastNextPoint=[0,0,0],this.lostUpdateTime=0,this.testLastNextPoint=void 0,this.newLocalWayPoints=[],this.localWayPoints=[],this.isInited=!1}screenCoordinate(t){this.touchPoint[0]=t.x/(this.canvas.width/2)*2-1,this.touchPoint[1]=-t.y/(this.canvas.height/2)*2+1}touchCancel(){}touchStart(){this.isTouch=!0}setPoiList(t,e){void 0!==t&&this.arrangePoiDatasWithJson(t,e)}renderWebGL(){let t=this.THREE;if(this.isTouch){let e=new t.Vector3(this.touchPoint[0],this.touchPoint[1],.5).unproject(this.camera);this.rayCaster.set(this.camera.position,e.sub(this.camera.position).normalize());let i=this.rayCaster.intersectObjects(this.scene.children,!0);console.log("intersects length = ",i.length,i);for(let t=0;ti){o=640*i/640}else{o=480/(480/i)}this.camera=new t.PerspectiveCamera(62,o,.01,1e3),this.scene=new t.Scene,this.renderer=new t.WebGLRenderer({canvas:e,antialias:!0,alpha:!0}),this.renderer.gammaOutput=!0,this.renderer.gammaFactor=2.2,this.renderer.setSize(2*e.width,2*e.height,!1),this.scene.add(this.camera);let s=new t.Color("#FFFFFF"),n=new t.DirectionalLight(s);n.position.set(1.1,3.1,-12.94),n.intensity=.7,this.scene.add(n);let r=new t.Color("#FFFFFF"),a=new t.AmbientLight(r);a.position.set(0,0,0),a.intensity=.9,this.scene.add(a)}getJson(t,e){wx.request({url:t,header:{"content-type":"application/json"},success:t=>{console.log(t.data),e(t.data)},fail:t=>{console.log("error message = ",t.data)}})}generateOtherRoute(t,e,i,o,s,n){this.THREE;for(let r=s;r3))break;this.generateOtherRoute(t,e,i,o,s,n)}}}updateOnScreenArrowPosition(t){this.arrowCtrl.setScreenArrowPosition(t)}drawRoute(t,e,i,o,s){let n=this.THREE;this.naviData=t,this.arrowCtrl.setArrowRenderMode(o.ArrowRenderMode.mode);let r=o.ThreeDofArrowPosition.position;this.arrowCtrl.setScreenArrowPosition(new n.Vector3(r[0],r[1],r[2])),this.final=new n.Vector3(0,0,0),1===o.InputCoordinateMode.mode?(this.final=e,this.finalClone=new n.Vector3(this.final.x,this.final.y,this.final.z)):(i.transform_map_coodinate_to_translation(e.x,e.y),this.final.x=i.get_transform_vpas_translation(0),this.final.y=i.get_transform_vpas_translation(1),this.finalClone=new n.Vector3(this.final.x,this.final.y,this.final.z));let a=[],l=[];for(let e=0;e0){let s=null,a=null,h=t[e-1],c=void 0;if(c=e===t.length-1?this.final:t[e+1],1===o.InputCoordinateMode.mode)s=new n.Vector3(h.x,h.y,0),a=new n.Vector3(c.x,c.y,0);else{i.transform_map_coodinate_to_translation(h.x,h.y);for(let t=0;t<2;t++)l[t]=i.get_transform_vpas_translation(t);if(s=new n.Vector3(l[0],l[1],0),e===t.length-1)a=new n.Vector3(c.x,c.y,0);else{i.transform_map_coodinate_to_translation(c.x,c.y);for(let t=0;t<2;t++)l[t]=i.get_transform_vpas_translation(t);a=new n.Vector3(l[0],l[1],0)}}let d=new rt(this.THREE,this.scene,r,s,a,!1,this.configInfo),f=new rt(this.THREE,this.scene,r,s,a,!1,this.configInfo);if(d.isNormalArrow){let t=new pt(this.THREE,this.scene,r),e=new pt(this.THREE,this.scene,r);this.wayPointCtrls.push(t),this.wayPointCtrlsClone.push(e)}else this.wayPointCtrls.push(d),this.wayPointCtrlsClone.push(f),this.wayPointIndex.push(this.wayPointCtrls.length-1),this.wayPointindexClone.push(e)}let a=!0,h=!0,c=void 0,d=void 0;switch(s.pointType){case 4:a=!0,c=new at(this.THREE,this.scene,r,a,this.configInfo),d=new at(this.THREE,this.scene,r,a,this.configInfo),this.wayPointCtrls.push(c),this.wayPointCtrlsClone.push(d),this.wayPointIndex.push(this.wayPointCtrls.length-1);break;case 5:a=!1,c=new at(this.THREE,this.scene,r,a,this.configInfo),d=new at(this.THREE,this.scene,r,a,this.configInfo),this.wayPointCtrls.push(c),this.wayPointCtrlsClone.push(d),this.wayPointIndex.push(this.wayPointCtrls.length-1);break;case 2:a=!0,c=new lt(this.THREE,this.scene,r,a,this.configInfo),d=new lt(this.THREE,this.scene,r,a,this.configInfo),this.wayPointCtrls.push(c),this.wayPointCtrlsClone.push(d),this.wayPointIndex.push(this.wayPointCtrls.length-1);break;case 3:a=!1,c=new lt(this.THREE,this.scene,r,a,this.configInfo),d=new lt(this.THREE,this.scene,r,a,this.configInfo),this.wayPointCtrls.push(c),this.wayPointCtrlsClone.push(d),this.wayPointIndex.push(this.wayPointCtrls.length-1);break;case 7:h=!1,c=new ft(this.THREE,this.scene,r,h,this.configInfo),d=new ft(this.THREE,this.scene,r,h,this.configInfo),this.wayPointCtrls.push(c),this.wayPointCtrlsClone.push(d),this.wayPointIndex.push(this.wayPointCtrls.length-1);break;case 8:h=!0,c=new ft(this.THREE,this.scene,r,h,this.configInfo),d=new ft(this.THREE,this.scene,r,h,this.configInfo),this.wayPointCtrls.push(c),this.wayPointCtrlsClone.push(d),this.wayPointIndex.push(this.wayPointCtrls.length-1);break;case 9:a=!0,c=new ut(this.THREE,this.scene,r,a,this.configInfo),d=new ut(this.THREE,this.scene,r,a,this.configInfo),this.wayPointCtrls.push(c),this.wayPointCtrlsClone.push(d),this.wayPointIndex.push(this.wayPointCtrls.length-1);break;case 10:a=!1,c=new ut(this.THREE,this.scene,r,a,this.configInfo),d=new ut(this.THREE,this.scene,r,a,this.configInfo),this.wayPointCtrls.push(c),this.wayPointCtrlsClone.push(d),this.wayPointIndex.push(this.wayPointCtrls.length-1)}}console.log("after regenerate route, this.wayPointCtrls.length = ",this.wayPointCtrls.length),console.log("this.wayPointIndex = ",this.wayPointIndex);for(let t=0;tthis.driftAwayAngleThreshold&&n>this.driftAwayDistanceThreshold){let t=new o.Vector3;if(t.crossVectors(r,a),t.z<0){return 0}return 1}return 2}getFootOfPerpendicular(t,e,i){let o=this.THREE;const s=e.x-i.x,n=e.y-i.y,r=e.z-i.z;if(Math.abs(s)<1e-8&&Math.abs(n)<1e-8&&Math.abs(r)<1e-8)return e;let a=(t.x-e.x)*(e.x-i.x)+(t.y-e.y)*(e.y-i.y)+(t.z-e.z)*(e.z-i.z);return a/=Math.pow(s,2)+Math.pow(n,2)+Math.pow(r,2),new o.Vector3(e.x+a*s,e.y+a*n,e.z+a*r)}decidePointBetweenTwo(t,e,i){if(void 0===t||void 0===e||void 0===i)return[!1,[0,0,0]];let o=this.getFootOfPerpendicular(t,e,i);this.distanceCameraToFootPoint=L(o,t),this.segmentLength=L(e,i),this.footPointToFirstPointDistance=L(e,o);let s=new this.THREE.Vector3;s.subVectors(e,o);let n=new this.THREE.Vector3;n.subVectors(i,o);let r=s.dot(n)/(s.length()*n.length());r>1&&(r=1),r<-1&&(r=-1);let a=180*Math.acos(r)/Math.PI;return a>=0&&a<90?[!1,o]:[!0,o]}updateNewLocalWayPoints(t,e,i){let o,s=this.THREE,n=[0,0,0];if(o=0===this.way_point_index?this.decidePointBetweenTwo(this.camera.position,new s.Vector3(t[0][0],t[0][1],t[0][2]),new s.Vector3(t[1][0],t[1][1],t[1][2])):this.decidePointBetweenTwo(this.camera.position,this.wayPointCtrls[this.way_point_index-1].location,this.wayPointCtrls[this.way_point_index].location),n=o[1],!i){for(let i=0;i0&&this.wayPointIndex.length>1){for(let t=0;tthis.min_distance&&(this.min_distance=p,this.next_point_distance=p),this.min_distance===Number.MAX_VALUE||this.next_point_distance===Number.MAX_VALUE)return this.type=-1,[u,c,this.next_point_distance,this.type,2,this.newLocalWayPoints]}let y=[0,0,0],m=[0,0,0],g=0;if(this.localWayPoints=[],this.wayPointCtrls.length>0){for(let t=this.way_point_index;t1){y=this.updateNewLocalWayPoints(this.localWayPoints,this.newLocalWayPoints,this.isInited),this.isInited=!0;let t=this.localWayPoints[0][0]-y.x,e=this.localWayPoints[0][1]-y.y,i=Math.sqrt(t*t+e*e),o=Math.sqrt(Math.pow(y.x-this.localWayPoints[0][0],2)+Math.pow(y.y-this.localWayPoints[0][1],2));if(m[0]=this.camera.position.x+o*t/i,m[1]=this.camera.position.y+o*e/i,g=Math.sqrt(Math.pow(this.camera.position.x-m[0],2)+Math.pow(this.camera.position.y-m[1],2)),this.min_distance=g,this.min_distancethis.wayPointIndex[this.wayPointIndex.length-1]||this.nextIsFinal)&&(Math.abs(this.final.x-this.wayPointCtrls[this.wayPointCtrls.length-1].location.x)<1e-7&&Math.abs(this.final.y-this.wayPointCtrls[this.wayPointCtrls.length-1].location.y)<1e-7?(this.arrowCtrl.hideFinalModel(),this.arrowCtrl.hideMoveArrowModel()):(this.next_point_distance=u,this.type=7,this.way_point_index===this.wayPointCtrls.length-1&&(this.min_distance=u,this.nextLocation=this.finalClone),void 0!==this.wayPointCtrls[this.way_point_index]&&this.wayPointCtrls[this.way_point_index].setVisible(!1),void 0!==this.wayPointCtrlsClone[this.way_point_index]&&this.wayPointCtrlsClone[this.way_point_index].setVisible(!1)));let v=this.arrowCtrl.update(this.camera.position,a,u,this.type,this.localWayPoints,this.nextIsFinal,this.nextIsTransfer,this.final);v[0];if(void 0!==v[1]){let t=(new s.Matrix4).getInverse(v[1]);h.multiply(t),c.setFromRotationMatrix(h,"XYZ")}let w=0,b=v[2];w=Math.abs(b)>20&&b<0?1:Math.abs(b)>20&&b>0?0:2;for(let t=0;t{this.updateRenderer()}),this.renderer.renderWebGL()}requestVPASLocation(t){!function(t){wx.getNetworkType({success(e){t.onNetWork({type:e.networkType,msg:"获取网络类型"})},fail(e){t.onError({type:10008,msg:"监听网络信号失败"})}}),wx.onNetworkStatusChange((function(e){e.isConnected?t.onNetWork({type:e.networkType,msg:"监听到网络状态发生变化"}):t.onError({type:10008,msg:"监听网络信号失败"})}))}(t),this.platform.setLoactionData(t,this._configData),this.resetARNavigationAgain(),this.requestGetPOi(t)}updateBluetoothLocation(t,e){this.platform.updateBluetoothLocation(t,e)}setUserId(t){this.platform.setUserId(t)}get2DPosition(){}getScreenCoordinate(t){this.renderer.screenCoordinate(t)}touchCancel(t){this.renderer.touchCancel()}touchStart(){this.renderer.touchStart()}requestGetPOi(t){this._configData.map.forEach(e=>{e.floor_id===t.floor_id&&void 0!==e.case_id&&""!==e.case_id&&this.severInterface.getMapPoi(Number(e.case_id)).getPoi.then(e=>{this.renderer.setPoiList(e.data.data.pois,t)})})}setNavigationData(t,e,i,o){console.log("naviData = ",t),this.renderer.drawRoute(t,e,i,this._configData,o)}startARNavigation(){vt=!0,this.platform.startARTrue(vt)}resetARNavigationAgain(){wt=!1,this.platform.resetARTrue(wt)}resetRender(){this.renderer.reset(),void 0!==this.intervalId&&(console.log("resetRender..."),clearInterval(this.intervalId))}releaseRender(){this.renderer&&this.renderer.dispose()}finishARNavigation(t){vt=!1,wt=!0,void 0!==this.platform&&(this.platform.stopARTrue(wt),this.platform.release(t)),void 0!==this.severInterface&&this.severInterface.destroylocatesession(),void 0!==this.renderer&&this.renderer.reset(t)}}function _t(){}function xt(t){wx.createSelectorQuery().select(t).fields({node:!0}).exec(t=>{const e=t[0].node;yt=e,mt.setCanvasData(yt)})}}]);void 0===VPASSDK&&console.error("esm-webpack-plugin: nothing exported!");const _VPASSDK$SDKWrapper=VPASSDK.SDKWrapper;export{_VPASSDK$SDKWrapper as SDKWrapper}; \ No newline at end of file diff --git a/pages/index/config.js b/pages/index/config.js new file mode 100644 index 0000000..3561cd8 --- /dev/null +++ b/pages/index/config.js @@ -0,0 +1,303 @@ +module.exports = { + // 有关接口 + interface: { + // baseURL + baseURL: "https://dusee.baidu.com", + // 创建 session 的接口 + sessionInterface: "/ar-vps-ui/createsession_poi_map", + // trackFrame 定位接口 + trackFrameInterface: "/ar-vps-ui/trackframe", + // 导航结束 销毁 session + destroySessionInterface: "/ar-vps-ui/sessiondestory", + getMapPoiBaseUrl: "https://dusee.baidu.com", + getMapPoiInterface: "/vpastob/inner/get_map_poi", + // 定义定位超时时间 + timeOut: 5 * 1000, + }, + // 有关地图 --- 一层商场使用独立的视觉地图,用map_id和poi_id表示; + map: [ + { + app_id: 0, + map_id: 193, + poi_id: 25, + floor_id: "B3", + transform_matrix: [1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0], // 表示视觉地图和2D地图之间的转换矩阵 + geo_map_transform_matrix: [ + 0.0000117466936564, + 0.000000189887476, + 0, + -0.0000002456396239, + 0.0000090804973974, + 0, + 0, + 0, + 1, + 116.32584837, + 39.78784125, + 0, + ], + scale: 5.6, // 表示视觉地图与2D地图之间的尺度变换 + // 0:表示非车库,1表示为车库 + is_park: 1, + // 不为空表示支持蓝牙定位,否则不支持蓝牙定位;具体数值由百度方提供 + ak: "4HLHLEsOD3OpdwlO", + case_id: "23", + }, + { + app_id: 0, + map_id: 193, + poi_id: 25, + floor_id: "B2", + transform_matrix: [1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0], // 表示视觉地图和2D地图之间的转换矩阵 + geo_map_transform_matrix: [ + 0.0000117257737436, + 0.000000195171089, + 0, + -0.0000002146964509, + 0.0000090049708756, + 0, + 0, + 0, + 1, + 116.32584014, + 39.7879071, + 0, + ], + scale: 5.6, // 表示视觉地图与2D地图之间的尺度变换 + // 0:表示非车库,1表示为车库 + is_park: 1, + // 不为空表示支持蓝牙定位,否则不支持蓝牙定位;具体数值由百度方提供 + ak: "4HLHLEsOD3OpdwlO", + // case_id: "22", + case_id: "58", + }, + { + app_id: 0, + map_id: 193, + poi_id: 25, + floor_id: "B1", + transform_matrix: [1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0], // 表示视觉地图和2D地图之间的转换矩阵 + geo_map_transform_matrix: [ + 0.0000115390412537, + 0.0000001639865905, + 0, + -0.0000002121341793, + 0.0000089200542687, + 0, + 0, + 0, + 1, + 116.32581195, + 39.78789641, + 0, + ], + scale: 5.6, // 表示视觉地图与2D地图之间的尺度变换 + // 0:表示非车库,1表示为车库 + is_park: 1, + // 不为空表示支持蓝牙定位,否则不支持蓝牙定位;具体数值由百度方提供 + ak: "4HLHLEsOD3OpdwlO", + case_id: "21", + }, + { + app_id: 0, + map_id: 193, + poi_id: 25, + floor_id: "F1", + transform_matrix: [ + -0.9650306770413328, + -0.2621369574920047, + 0, + -0.2621369574920047, + 0.9650306770413328, + 0, + 0, + 0, + 1, + 421.28192787, + 31.53136436, + 0, + ], // 表示视觉地图和2D地图之间的转换矩阵 + scale: 5.788425061257576, // 表示视觉地图与2D地图之间的尺度变换 + // 0:表示非车库,1表示为车库 + is_park: 0, + // 不为空表示支持蓝牙定位,否则不支持蓝牙定位;具体数值由百度方提供 + ak: "", + case_id: "66", + }, + { + app_id: 0, + map_id: 193, + poi_id: 25, + floor_id: "F2", + transform_matrix: [ + 0.8891579162272474, + 0.4576004900572795, + 0, + 0.4576004900572795, + -0.8891579162272474, + 0, + 0, + 0, + 1, + 571.10078532, + -245.82877513, + 0, + ], // 表示视觉地图和2D地图之间的转换矩阵 + scale: 5.862545391362199, // 表示视觉地图与2D地图之间的尺度变换 + // 与内容编辑平台绑定,从平台获取 + // 0:表示非车库,1表示为车库 + is_park: 0, + // 不为空表示支持蓝牙定位,否则不支持蓝牙定位;具体数值由百度方提供 + ak: "", + }, + { + app_id: 0, + map_id: 193, + poi_id: 25, + floor_id: "F3", + transform_matrix: [ + 0.8148392200653999, + 0.5796870180613556, + 0, + 0.5796870180613556, + -0.8148392200653999, + 0, + 0, + 0, + 1, + 583.57528358, + -239.44318034, + 0, + ], // 表示视觉地图和2D地图之间的转换矩阵 + scale: 5.858752899058012, // 表示视觉地图与2D地图之间的尺度变换 + // 0:表示非车库,1表示为车库 + is_park: 0, + // 不为空表示支持蓝牙定位,否则不支持蓝牙定位;具体数值由百度方提供 + ak: "", + }, + ], + // 有关渲染随屏箭头的配置 + ArrowRenderMode: { + mode: 2, // 0:只显示贴地箭头 1:只显示3Dof箭头 2:显示贴地箭头和3Dof剪头 + }, + // todo 暂时未开发 + ThreeDofArrowPosition: { + position: [0, -0.05, -0.25], + }, + InputCoordinateMode: { + mode: 0, // 0:表示使用的是2D地图坐标 1:表示使用的是3DVPAS地图坐标 + }, + // 是否需要将translation结果写入到本地文件中 + // 注意:只在Debug时候开启 + WriteCameraPositionForDebug: { + mode: 0, // 0:关闭 1:开启 + }, + arrow: { + // 动画导航箭头 + arrowURL: + "https://ar-fm.cdn.bcebos.com/home_3d_model/vpas_applet/ikea/gltf_20211111/qianjina/qianjina.gltf", + arrowPosition: [0, 0, 0], + arrowRotation: [0, Math.PI, Math.PI / 2], + arrowScale: [50, 50, 50], + arrowMoveSpeed: 8, + showDistance: 15, + }, + onScreenArrow: { + // 随屏3Dof箭头 + arrowURL: + "https://ar-fm.cdn.bcebos.com/home_3d_model/vpas_applet/ikea/gltf_20211111/qianjinb/qianjinb.gltf", + arrowPosition: [0, -0.05, -0.25], + arrowRotation: [Math.PI / 2, 0, 0], + arrowScale: [2.5, 2.5, 2.5], + }, + turnLeft: { + // 左转 + URL: + "https://ar-fm.cdn.bcebos.com/home_3d_model/vpas_applet/ikea/gltf_20211111/zuo/zuo.gltf", + scale: [100, 100, 100], + rotation: [-Math.PI / 2, 0, 0], + showDistance: 15, + angleThreshold: 30, + }, + turnRight: { + // 右转 + URL: + "https://ar-fm.cdn.bcebos.com/home_3d_model/vpas_applet/ikea/gltf_20211111/you/you.gltf", + scale: [100, 100, 100], + rotation: [-Math.PI / 2, 0, 0], + showDistance: 15, + angleThreshold: 30, + }, + escalatorUp: { + // 上扶梯 + URL: + "https://ar-fm.cdn.bcebos.com/home_3d_model/vpas_applet/ikea/gltf_20211111/shang/shang.gltf", + scale: [100, 100, 100], + rotation: [-Math.PI / 2, 0, 0], + showDistance: 15, + }, + escalatorDown: { + // 下扶梯 + URL: + "https://ar-fm.cdn.bcebos.com/home_3d_model/vpas_applet/ikea/gltf_20211111/xia/xia.gltf", + scale: [100, 100, 100], + rotation: [-Math.PI / 2, 0, 0], + showDistance: 15, + }, + elevatorUp: { + // 上电梯 + URL: + "https://ar-fm.cdn.bcebos.com/home_3d_model/vpas_applet/ikea/gltf_20211111/zhiti/zhiti.gltf", + scale: [100, 100, 100], + rotation: [-Math.PI / 2, 0, 0], + showDistance: 15, + }, + elevatorDown: { + // 下电梯 + URL: + "https://ar-fm.cdn.bcebos.com/home_3d_model/vpas_applet/ikea/gltf_20211111/zhiti/zhiti.gltf", + scale: [100, 100, 100], + rotation: [-Math.PI / 2, 0, 0], + showDistance: 15, + }, + mallToPark: { + // 商场到车库入口 + URL: + "https://ar-fm.cdn.bcebos.com/home_3d_model/vpas_applet/ikea/gltf_20211111/park/park.gltf", + scale: [100, 100, 100], + rotation: [-Math.PI / 2, 0, 0], + showDistance: 15, + }, + parkToMall: { + // 车库到商场入口 + URL: + "https://ar-fm.cdn.bcebos.com/home_3d_model/vpas_applet/ikea/gltf_20211111/park/park.gltf", + scale: [100, 100, 100], + rotation: [-Math.PI / 2, 0, 0], + showDistance: 15, + }, + final: { + // 终点 + URL: + "https://ar-fm.cdn.bcebos.com/home_3d_model/vpas_applet/ikea/gltf_20211111/zhongdian/zhongdian.gltf", + scale: [100, 100, 100], + rotation: [-Math.PI / 2, 0, 0], + showDistance: 15, + }, + mapPoi: { + // 地图打点数据 + showDistance: 40, + }, + panel: { + panelColor: 0xf9dc4f, + textColor: 0xffffff, + opacity: 0.8, // 透明度设置,1.0为不透明,0.0为完全透明 + }, + interaction: { + minCoverPointDistance: 4, // 通过路径节点的最短距离阈值 + }, + minTriggerDistance: { + transfer: 5, // 电梯扶梯点最短触发距离 + final: 5, // 终点最短触发距离 + }, +}; diff --git a/pages/index/corner.png b/pages/index/corner.png new file mode 100644 index 0000000..13dbed3 Binary files /dev/null and b/pages/index/corner.png differ diff --git a/pages/index/elevator-down.png b/pages/index/elevator-down.png new file mode 100644 index 0000000..2fa73ea Binary files /dev/null and b/pages/index/elevator-down.png differ diff --git a/pages/index/elevator-up.png b/pages/index/elevator-up.png new file mode 100644 index 0000000..69f2c94 Binary files /dev/null and b/pages/index/elevator-up.png differ diff --git a/pages/index/end.png b/pages/index/end.png new file mode 100644 index 0000000..3a6f793 Binary files /dev/null and b/pages/index/end.png differ diff --git a/pages/index/escalator-down.png b/pages/index/escalator-down.png new file mode 100644 index 0000000..be27114 Binary files /dev/null and b/pages/index/escalator-down.png differ diff --git a/pages/index/escalator-up.png b/pages/index/escalator-up.png new file mode 100644 index 0000000..aac411d Binary files /dev/null and b/pages/index/escalator-up.png differ diff --git a/pages/index/flashoff.png b/pages/index/flashoff.png new file mode 100644 index 0000000..44e88d1 Binary files /dev/null and b/pages/index/flashoff.png differ diff --git a/pages/index/flashon.png b/pages/index/flashon.png new file mode 100644 index 0000000..c56a7e0 Binary files /dev/null and b/pages/index/flashon.png differ diff --git a/pages/index/floor-bg.png b/pages/index/floor-bg.png new file mode 100644 index 0000000..7888159 Binary files /dev/null and b/pages/index/floor-bg.png differ diff --git a/pages/index/index-helper.js b/pages/index/index-helper.js new file mode 100644 index 0000000..a58aba3 --- /dev/null +++ b/pages/index/index-helper.js @@ -0,0 +1,110 @@ +export const STATES = { + selectFloor: "selectFloor", + startScan: "startScan", + fail5s: "fail5s", + fail8s: "fail8s", + successPrompt: "successPrompt", + wrongLocation: "wrongLocation", + badConnection: "badConnection", + arriveEscalator: "arriveEscalator", + arriveElevator: "arriveElevator", + arriveMall: "arriveMall", + arrivePark: "arrivePark", + requestEnd: "requestEnd", + inNav: "inNav", + noCamera: "noCamera", + tomap: "tomap", + arriveEnd: "arriveEnd", + bluetoothRequired: "bluetoothRequired", +}; +export const promptIcons = { + info: "info", + escalator: "escalator", + elevator: "elevator", + question: "question", + tomap: "tomap", + mall: "mall", + park: "park", + end: "end", + bluetooth: "bluetooth", +}; +export const promptStateMap = { + bluetoothRequired: { + icon: promptIcons.bluetooth, + title: "开启蓝牙 精准导航", + meta: "请在系统设置打开蓝牙", + btn3: "退出导航", + }, + noCamera: { + icon: promptIcons.info, + title: "相机未授权", + meta: "AR导航需要相机权限", + btn1: "打开设置", + btn2: "退出导航", + }, + fail8s: { + icon: promptIcons.info, + title: "定位失败", + meta: "请确认您是否在正确楼层", + btn1: "重新定位", + btn2: "选择楼层", + btn3: "退出导航", + }, + wrongLocation: { + icon: promptIcons.info, + title: "当前位置无法导航", + meta: "导航有效区域:无锡荟聚", + btn1: "退出导航", + }, + badConnection: { + icon: promptIcons.info, + title: "网络信号差", + meta: "请检查网络连接是否正常", + btn1: "重新定位", + }, + arriveEscalator: { + icon: promptIcons.escalator, + title: "", + meta: "请注意乘梯安全", + btn1: "已到达目标楼层", + }, + arriveElevator: { + icon: promptIcons.elevator, + title: "", + meta: "请注意乘梯安全", + btn1: "已到达目标楼层", + }, + arriveMall: { + icon: promptIcons.mall, + title: "请步行至商场区域", + meta: "请注意安全", + btn1: "已到达目标商场", + }, + arrivePark: { + icon: promptIcons.park, + title: "请步行至停车场", + meta: "请注意安全", + btn1: "已到达目标停车场", + }, + requestEnd: { + icon: promptIcons.question, + title: "是否退出导航?", + meta: "退出导航后 将返回首页", + btn1: "确定", + btn2: "取消", + }, + tomap: { + icon: promptIcons.tomap, + title: `即将离开AR导航 + 进入模拟导航`, + meta: "是否要继续?", + btn1: "确定", + btn2: "取消", + }, + arriveEnd: { + icon: promptIcons.end, + title: `已到达终点,是否退出导航`, + meta: "退出导航后将返回首页", + btn1: "确定", + }, +}; diff --git a/pages/index/index.js b/pages/index/index.js new file mode 100644 index 0000000..0c6b4db --- /dev/null +++ b/pages/index/index.js @@ -0,0 +1,758 @@ +import * as VPASSDK from "./VPASSDK-1.2.2.js"; +import { stopBeaconScan, getLocation } from "ais-h5-location"; +import { createScopedThreejs } from "threejs-miniprogram"; +import { registerGLTFLoader } from "../../loader/gltfLoader"; +var THREE; +import configData from "./config"; +import { STATES, promptStateMap } from "./index-helper"; +var _canvas; +let map; +let locationOption; +const icons = { + left: "/pages/index/left.png", + straight: "/pages/index/straight.png", + right: "/pages/index/right.png", + end: "/pages/index/end.png", + escalatorUp: "/pages/index/escalator-up.png", + escalatorDown: "/pages/index/escalator-down.png", + elevatorUp: "/pages/index/elevator-up.png", + elevatorDown: "/pages/index/elevator-down.png", +}; +Page({ + /** + * 页面的初始数据 + */ + data: { + inited: false, + isMap: true, + isMeet: true, + locX: 0, + locY: 0, + floors: [], + floorOrder: null, + floorId: null, + floorName: null, + windowHeight: 812, + states: STATES, + state: STATES.selectFloor, + promptStateMap, + map: null, + e: null, + lastLoc: null, + tab: 0, + showTabs: false, + shop: null, + nextFloor: null, + nextNextFloor: null, + navIcon: icons.straight, + distanceToNextPoint: null, + msgTop: "", + nextPointType: null, + msgBottomLeft: "", + msgBottomRight: "", + totalDistance: 0, + distance: 0, + arriveEnd: false, + theta: null, + flash: "off", + parkTop: 0, + parkLeft: 0, + flash_isFilter: "true", + parkWidth: 0, + parkHeight: 0, + session: null, + filteredMallFloors: [], + filteredParkFloors: [], + selectMall: true, + safeTop: 54, + frameSize: "medium", + leftYaw: true, + rightYaw: true, + searchType: 0, + point: null, + resolution: null, + }, + clickScreen(e) { + let detail = e.detail; + if (this.SDK) this.SDK.getScreenCoordinate({ x: detail.x, y: detail.y }); + console.log("点击屏幕x, y:", detail.x, detail.y); + }, + + touchMove(event) { + if (this.SDK) this.SDK.getScreenCoordinate(event.touches[0]); + }, + + touchCancel(event) { + if (this.SDK) this.SDK.touchCancel(); + }, + + touchStart() { + console.log("touch Start"); + if (this.SDK) this.SDK.touchStart(); + }, + + touchEnd() { + console.log("touch End"); + if (this.SDK) this.SDK.touchCancel(); + }, + setSelectMall() { + this.setData({ selectMall: true }); + }, + setSelectPark() { + this.setData({ selectMall: false }); + }, + /** + * 生命周期函数--监听页面加载 + */ + async onLoad({ e, searchType = 0 }) { + this.frameIndex = 0; + this.getSystemInfo(); + wx.setKeepScreenOn({ + keepScreenOn: true, + }); + const { + globalData: { floors }, + } = getApp(); + const { windowHeight } = wx.getSystemInfoSync(); + this.setData({ + floors, + filteredMallFloors: floors.filter( + ({ url, isPark }) => url !== null && !isPark + ), + filteredParkFloors: floors.filter( + ({ url, isPark }) => url !== null && isPark + ), + windowHeight, + e: decodeURIComponent(e), + searchType: Number(searchType), + }); + this.initSDK(); + }, + initSDK() { + this.SDK = new VPASSDK.SDKWrapper(configData); + wx.createSelectorQuery() + .select("#webgl") + .node() + .exec((res) => { + _canvas = res[0].node; + // todo 初始化引擎放到我们系统初始化中 + // 创建一个与 canvas 绑定的 three.js + THREE = createScopedThreejs(_canvas); + // SXC + registerGLTFLoader(THREE); + }); + }, + requestLocation() { + if (!(this.data.inited && this.data.floorOrder !== null)) return; + if (!this.sdkInited) { + try { + this.SDK.initAR( + { + rgba2JpegCanvas: "#capture", // 压缩jpeg的Canvas,必填 + webGLCanvas: "#webgl", // 绘制AR内容canvas,必填 + }, + THREE, + _canvas + ); + } catch (error) { + console.log(error); + } + } + this.sdkInited = true; + locationOption = { + floor_id: this.data.floorId, + onLocateEvent: () => {}, + distanceOfNextPoint: () => {}, + onFirstSuccess: (res) => { + this.firstSuccess(res); + this.setData({ + totalDistance: 0, + lastLoc: [res.locX, res.locY], + state: STATES.successPrompt, + flash: "off", + }); + }, + onBluetoothAndScanStatus: (res) => { + console.log("关于蓝牙和扫描框状态:", res.type); + }, + onError: (e) => { + const { type } = e; + if (type !== 10010) console.log("error:", e); + if (type === 10005) return this.setState(STATES.fail5s); + if (type === 10007) { + this.finishARNavigation(); + return this.setState(STATES.fail8s); + } + if (type === 10008) { + return wx.showModal({ + title: "提示", + content: "断网了,重新链接?", + showCancel: false, + success: (res) => { + if (res.confirm) { + console.log("用户点击确定"); + // 获取网络信号 + wx.getNetworkType({ + success: (res) => { + locationOption.onNetWork({ + type: res.networkType, + msg: "获取网络类型", + }); + if (res.networkType !== "none") { + this.SDK.requestVPASLocation(locationOption); + } else { + locationOption.onError({ + type: 10008, + msg: "监听网络信号失败", + }); + } + }, + fail: (err) => { + locationOption.onError({ + type: 10008, + msg: "监听网络信号失败", + }); + }, + }); + } + }, + }); + } + if (type === 10009) { + return wx.showToast({ + icon: "none", + title: "车位号无效\n换个试试吧", + }); + } + if (type === 10010) { + return wx.showToast({ + icon: "none", + title: "请将手机保持竖屏镜头向前", + }); + } + wx.showToast({ + icon: "none", + title: "定位失败\n错误码:" + type, + }); + }, + onEverySuccess: (res) => { + // 跟踪回调 + const lastLoc = [res.locX, res.locY]; + const { + distance, + distanceToNextPoint, + type: nextPointType, + orientation: theta, + } = res; + if (!this.data.totalDistance) this.setData({ totalDistance: distance }); + this.setData({ + theta, + distance, + distanceToNextPoint, + nextPointType, + msgBottomLeft: "剩余" + Math.floor(distance) + "米", + msgBottomRight: Math.floor(distance / 1.4 / 60) + "分钟", + }); + this.setMsgTopAndIcon(); + if ( + this.data.lastLoc && + this.data.lastLoc[0] === lastLoc[0] && + this.data.lastLoc[1] === lastLoc[1] + ) + return; + this.setData({ + lastLoc, + }); + }, + onNetWork: (status) => { + console.log("network", status); + }, + onArrive: (res) => { + console.log("onArrive", res); + if (res.type === 3 || res.type === 4) { + this.finishARNavigation(); + this.setState(STATES.arriveElevator); + } else if (res.type === 5 || res.type === 6) { + this.finishARNavigation(); + this.setState(STATES.arriveEscalator); + } else if (res.type === 8 || res.type === 9) { + this.finishARNavigation(); + this.setState(res.type === 8 ? STATES.arrivePark : STATES.arriveMall); + } else if (res.type === 7) { + this.setData({ arriveEnd: true }); + this.setMsgTopAndIcon(); + this.setState(STATES.arriveEnd); + } + }, + onResourceLoaded: (res) => { + console.log("AR资源导航加载完成"); + }, + onStep: (res) => { + // console.log(res) + }, + onYaw: ({ type }) => { + this.setData({ + leftYaw: type === 1 || type === 2, + rightYaw: type === 0 || type === 2, + }); + }, + onPoiEvent: ({ eventUrl }) => { + console.log(eventUrl); + if (!eventUrl.includes("***")) return; + let [appId, path] = eventUrl.split("***"); + wx.navigateToMiniProgram({ + appId, + path, + }); + }, + }; + console.log("locationOption:", locationOption); + const floor = this.data.floors.find( + ({ floorId }) => locationOption.floor_id == floorId + ); + + if (floor.isPark) { + this.startBlueTooth(locationOption.floor_id); + } else { + this.stopBlueTooth(); + } + console.log(floor); + this.SDK.requestVPASLocation(locationOption); + this.setData({ + state: STATES.startScan, + arriveEnd: false, + showTabs: false, + }); + }, + stopBlueTooth() { + stopBeaconScan(); + wx.closeBluetoothAdapter(); + }, + startBlueTooth(currentFloor) { + const ak = configData.map.find(({ floor_id }) => floor_id == currentFloor) + .ak; + console.log("ak:", ak); + if (!ak) return console.warn("no ak"); + wx.openBluetoothAdapter({ + success: () => { + getLocation({ + ak, + intervalTime: 1000, // 定时器(请求频率时长) + successCb: (result) => { + const { location, floor, indoor } = result.body && result.body[0]; + const sameFloor = (floor && floor.toUpperCase()) == currentFloor; // 判断是否为同一楼层(避免获取同临楼层定位信息) + // pointX、pointY格式处理 + const splitArray = location && location.split(","); + const pointX = parseFloat(splitArray[0]); + const pointY = parseFloat(splitArray[1]); + + // 过滤蓝牙location 无效值 + let isValidLocation; + if (splitArray && splitArray.length) { + isValidLocation = pointX > 1 && pointY > 1; + } + /** + * vpas updateBluetoothLocation 触发条件: + * 选择楼层 等于 蓝牙返回楼层时 + * indoor = 1(室内) + */ + if (sameFloor && indoor === "1") { + isValidLocation && + this.SDK.updateBluetoothLocation(pointX, pointY); + } + }, + failCb: (err) => { + console.warn("fail-蓝牙位置定位失败", err); + }, + }); + }, + fail: (res) => { + console.warn("蓝牙未开启>>", res); + }, + }); + }, + setMsgTopAndIcon() { + const { + distanceToNextPoint, + nextPointType, + arriveEnd, + nextFloor, + floors, + } = this.data; + if ( + distanceToNextPoint !== null && + nextPointType !== null && + nextPointType !== -1 + ) { + const flooredDistance = Math.floor(distanceToNextPoint); + const nextFloorName = nextFloor ? nextFloor.name : ""; + this.setData({ + msgTop: arriveEnd + ? "已到达" + : distanceToNextPoint > 20 + ? `直行${flooredDistance}米` + : nextPointType === 7 + ? `${flooredDistance}米后 到达终点` + : nextPointType === 8 + ? `${ + distanceToNextPoint < 5 ? "" : `${flooredDistance}米后 ` + }到达停车位入口` + : nextPointType === 9 + ? `${ + distanceToNextPoint < 5 ? "" : `${flooredDistance}米后 ` + }到达商场入口` + : [3, 4, 5, 6].includes(nextPointType) + ? `${ + distanceToNextPoint < 5 ? "" : `${flooredDistance}米后 ` + }乘梯至${nextFloorName}` + : [1, 2].includes(nextPointType) + ? `${ + distanceToNextPoint < 5 + ? nextPointType === 1 + ? "左转" + : "右转" + : `${flooredDistance}米后 ${ + nextPointType === 1 ? "左前方" : "右前方" + }` + }` + : distanceToNextPoint < 5 + ? `${nextPointType === 1 ? "左转" : "右转"}` + : "", + navIcon: arriveEnd + ? icons.end + : distanceToNextPoint > 20 + ? icons.straight + : { + 1: icons.left, + 2: icons.right, + 3: icons.elevatorUp, + 4: icons.elevatorDown, + 5: icons.escalatorUp, + 6: icons.escalatorDown, + 7: icons.end, + }[nextPointType], + }); + } + }, + setFloor({ currentTarget: { id } }) { + const floor = this.data[ + this.data.selectMall ? "filteredMallFloors" : "filteredParkFloors" + ][id]; + this.setData({ + floorOrder: floor.floorOrder, + point: null, + floorId: floor.floorId, + floorName: floor.name, + }); + }, + firstSuccess(res) { + console.log("firstSuccess---", this.data.e); + if (!map) return; + let shop = map.shopMap[this.data.e] + ? map.shopMap[this.data.e] + : map.facilityMap[this.data.e] + ? map.facilityMap[this.data.e] + : map.pMap[this.data.e]; + + if (!shop) { + const endParamList = this.data.e.split("_"); + if (endParamList.length === 3) { + let [efloororder, epoint, ename] = endParamList; + efloororder = Number(efloororder); + epoint = Number(epoint); + shop = { + isDevice: true, + name: ename, + navPoint: epoint, + yaxis: epoint, + floorOrder: efloororder, + floorName: map.mall.floors[efloororder][1], + }; + } + } + console.log("end", shop); + if (!shop) + return wx.showToast({ + icon: "none", + title: `未匹配到该终点:${this.data.e}`, + }); + + this.setData({ + shop: { + ...shop, + logoPath: shop.logoPath ? shop.logoPath.replaceAll("\\", "/") : null, + }, + }); + + const { naviData, nextFloorId, nextNextFloorId } = map.requestRoute( + [res.locX, res.locY, this.data.floorId], + { floorOrder: shop.floorOrder, navPoint: shop.yaxis } + ); + if (!naviData) return; + let nextFloor = this.data.floors.find( + ({ floorId }) => nextFloorId == floorId + ); + let nextNextFloor = this.data.floors.find( + ({ floorId }) => nextNextFloorId == floorId + ); + this.setData({ nextFloor, nextNextFloor }); + + let final = new THREE.Vector3( + naviData[naviData.length - 1].x, + naviData[naviData.length - 1].y, + 0 + ); + if (!nextFloor) { + naviData.pop(); + if (naviData.length === 1) { + naviData.push({ + ...naviData[0], + pointType: 1, + x: (naviData[0].x + final.x) / 2, + y: (naviData[0].y + final.y) / 2, + }); + } + } + console.log("naviData", naviData, "final", final); + const openid = getApp().globalData.openid; + if ( + [ + "oBbmR5c_SWeSyHBQ2YrAnu9W2Zts", + "oBbmR5VLexJ41jtbMsvIKVaiz7vE", + "oBbmR5ecGc_0RmQhR8qbQR1rdpYg", + ].includes(openid) + ) + this.setData({ + session: { + session: res.session, + timestamp: new Date().getTime(), + naviData, + openid, + path: [ + { locX: res.locX, locY: res.locY, timestamp: new Date().getTime() }, + ], + }, + }); + this.SDK.setNavigationData( + naviData, + final, + res.wasmFunction, + locationOption + ); + this.SDK.startARNavigation(); + setTimeout(() => { + this.setState(STATES.inNav); + this.setData({ + showTabs: true, + tab: 0, + }); + }, 1000); + }, + exit() { + wx.redirectTo({ + url: "/pages/h5map/index", + }); + }, + handleToMap() { + this.setState(STATES.tomap); + }, + handlePromptBtn({ detail: { btn } }) { + const { state } = this.data; + if (state === STATES.bluetoothRequired) { + if (btn === "3") return this.exit(); + } + if (state === STATES.fail8s) { + if (btn === "1") return this.requestLocation(); + if (btn === "2") return this.setState(STATES.selectFloor); + if (btn === "3") return this.exit(); + } + if (state === STATES.wrongLocation) return this.exit(); + if (state === STATES.badConnection) return this.requestLocation(); + if ( + state === STATES.arriveEscalator || + state === STATES.arriveElevator || + state === STATES.arriveMall || + state === STATES.arrivePark + ) { + const nextFloor = this.data.nextNextFloor + ? this.data.nextNextFloor + : this.data.nextFloor; + if (nextFloor) + this.setData({ + floorOrder: nextFloor.floorOrder, + point: null, + floorId: nextFloor.floorId, + floorName: nextFloor.name, + }); + return this.requestLocation(); + } + if (state === STATES.requestEnd || state === STATES.arriveEnd) { + if (btn === "1") return this.exit(); + if (btn === "2") return this.setState(STATES.inNav); + } + if (state === STATES.noCamera) { + if (btn === "1") + return wx.openSetting({ + withSubscriptions: true, + success: ({ authSetting }) => { + if (authSetting["scope.camera"]) { + wx.redirectTo({ + url: `/pages/index/index?e=${this.data.e}`, + }); + } + }, + }); + if (btn === "2") return this.exit(); + } + if (state === STATES.tomap) { + if (btn === "1") + return wx.redirectTo({ + url: `/pages/h5map/index?e=${this.data.e}`, + }); + if (btn === "2") return this.setState(STATES.inNav); + } + }, + setState(state) { + if ( + (this.data.state === STATES.arriveEscalator || + this.data.state === STATES.arriveElevator || + this.data.state === STATES.arriveMall || + this.data.state === STATES.arrivePark) && + state === STATES.inNav + ) + return console.log("到达弹窗出现忽略导航中状态变更触发"); + if ( + this.data.state === STATES.bluetoothRequired && + state !== STATES.startScan + ) + return console.log("蓝牙弹窗状态只能进入开始定位状态"); + this.setData({ + state, + }); + }, + handleMap({ detail }) { + map = detail; + this.setData({ + inited: true, + }); + }, + handleTabChange({ detail }) { + this.setData({ + tab: detail, + }); + if (this.SDK) { + this.SDK.updateOnScreenArrowPosition( + detail == 0 + ? new THREE.Vector3(0, -0.015, -0.25) + : new THREE.Vector3(0, -0.06, -0.25) + ); + } + }, + handleRelocate() { + this.SDK.finishARNavigation(); + this.requestLocation(); + }, + handleNavExit() { + this.setState(STATES.requestEnd); + }, + handleNoCamera() { + this.setState(STATES.noCamera); + }, + flashlightBtn() { + if (this.data.flash === "off") { + this.setData({ + flash: "on", + flash_isFilter: "true", + }); + } else { + this.setData({ + flash: "off", + }); + } + }, + getSystemInfo() { + wx.getSystemInfo({ + success: (res) => { + console.log("设备信息:", res); + let parkWidth = 248; + let parkHeight = 70; + let parkTop = res.windowHeight - parkHeight; + let parkLeft = res.windowWidth - parkWidth; + this.setData({ + parkWidth: parkWidth, + parkHeight: parkHeight, + parkTop: parkTop / 2, + parkLeft: parkLeft / 2, + safeTop: res.safeArea.top, + frameSize: res.system.includes("iOS") ? "medium" : "small", + resolution: res.system.includes("iOS") ? "high" : "small", + }); + console.log( + "宽高左上:", + this.data.parkWidth, + this.data.parkHeight, + this.data.parkTop, + this.data.parkLeft + ); + }, + }); + }, + /** + * 生命周期函数--监听页面显示 + */ + onShow: function () { + this.getSystemInfo(); + }, + + /** + * 生命周期函数--监听页面隐藏 + */ + onHide: function () {}, + + /** + * 生命周期函数--监听页面卸载 + */ + onUnload: function () { + this.finishARNavigation(true); + if (this.SDK) this.SDK.releaseRender(); + }, + finishARNavigation(isUnload = false) { + if (this.SDK) this.SDK.finishARNavigation(isUnload); + this.stopBlueTooth(); + this.setData({ totalDistance: 0 }); + }, + + /** + * 页面相关事件处理函数--监听用户下拉动作 + */ + onPullDownRefresh: function () {}, + + /** + * 页面上拉触底事件的处理函数 + */ + onReachBottom: function () {}, + + /** + * 用户点击右上角分享 + */ + onShareAppMessage({ from }) { + const e = + from === "button" && this.data.point !== null + ? `${this.data.floorOrder}_${this.data.point}_来自分享的位置` + : null; + return e === null + ? { + title: "无锡荟聚实景导航", + path: "/pages/h5map/index", + imageUrl: "/pages/h5map/share.png", + } + : { + title: "来自分享的位置", + path: `/pages/h5map/index?e=${e}`, + imageUrl: "/pages/h5map/share.png", + }; + }, + handlePoint({ detail }) { + this.setData({ point: detail }); + }, +}); diff --git a/pages/index/index.json b/pages/index/index.json new file mode 100644 index 0000000..38b5100 --- /dev/null +++ b/pages/index/index.json @@ -0,0 +1,9 @@ +{ + "usingComponents": { + "prompt": "../prompt/prompt", + "map2d": "../map2d/map2d", + "tabs": "../tabs/tabs", + "destination": "../destination/destination", + "nav": "../nav/nav" + } +} \ No newline at end of file diff --git a/pages/index/index.wxml b/pages/index/index.wxml new file mode 100644 index 0000000..10ca951 --- /dev/null +++ b/pages/index/index.wxml @@ -0,0 +1,85 @@ + + + + + + + + + + + +无锡荟聚 + + + + + + + + 为了更精确定位 + 请选择您当前所在楼层 + + + 商场 + 停车场 + + + + {{item.name}} + + + + + + + + + + + + + {{state===states.startScan?'开始定位':'努力定位中'}} + {{state===states.startScan?'请摆正手机扫描临近车位号':'再试试扫描其他车位号'}} + + + 示例 + + + + 您身边的车位号置于此区域,并对齐扫描边缘 + + + + + + + + + + + + + + + {{state===states.startScan?'开始定位':'努力定位中'}} + + + {{state===states.startScan?'请抬起手机,缓慢扫描周围环境。':'请扫描其他区域试试'}} + + 返回 + + + + + 定位成功 + 请跟随路线指示行走 + + + + + + + \ No newline at end of file diff --git a/pages/index/index.wxss b/pages/index/index.wxss new file mode 100644 index 0000000..7756991 --- /dev/null +++ b/pages/index/index.wxss @@ -0,0 +1,621 @@ +/**index.wxss**/ +.btn { + margin-top: 30rpx; +} + +.step { + position: fixed; + top: 0px; + color: red; + font-size: 20px; + z-index: 10 !important; +} + +.pose1 { + position: fixed; + top: 20px; + color: red; + font-size: 20px; + z-index: 10 !important; +} + +.pose2 { + position: fixed; + top: 40px; + color: red; + font-size: 20px; + z-index: 10 !important; +} + +.pose3 { + position: fixed; + top: 60px; + color: red; + font-size: 20px; + z-index: 10 !important; +} + +.pose4 { + position: fixed; + top: 80px; + color: red; + font-size: 20px; + z-index: 10 !important; +} + +.pose5 { + position: fixed; + top: 100px; + color: red; + font-size: 20px; + z-index: 10 !important; +} + +.pose6 { + position: fixed; + top: 120px; + color: red; + font-size: 20px; + z-index: 10 !important; +} + +.pose7 { + position: fixed; + top: 140px; + color: red; + font-size: 20px; + z-index: 10 !important; +} + +.pose8 { + position: fixed; + top: 160px; + color: red; + font-size: 20px; + z-index: 10 !important; +} + +.pose9 { + position: fixed; + top: 180px; + color: red; + font-size: 20px; + z-index: 10 !important; +} + +.pose10 { + position: fixed; + top: 200px; + color: red; + font-size: 20px; + z-index: 10 !important; +} + +.intrinstics { + position: fixed; + top: 200px; + color: red; + font-size: 20px; + z-index: 10 !important; +} + +#map { + /* z-index: 10000 !important; */ + position: relative; +} + +#loc { + width: 50rpx; + height: 50rpx; + position: absolute; + /* bottom: 90px; + right: 80px; */ + z-index: 1000000000 !important; +} + +.floor-modal { + position: fixed; + top: 0; + bottom: 0; + left: 0; + right: 0; + background: rgba(0, 0, 0, 80%); + z-index: 10 !important; +} + +.floor-modal > .content { + position: absolute; + width: 100%; + top: 152px; + bottom: 0; + padding-top: 34px; + background: #ffffff; + font-style: normal; + font-weight: bold; + font-size: 20px; + line-height: 28px; + text-align: center; + letter-spacing: 1px; + color: #554936; + border-radius: 24px 24px 0 0; +} +.floor-modal > .content > .bg { + position: absolute; + top: 0; + left: 0; + width: 100vw; + z-index: 1; +} +.floor-modal > .content > text { + position: absolute; + display: block; + z-index: 2; + left: 0; + right: 0; + top: 34px; +} + +.floor-modal > .content > .floors { + position: absolute; + top: 120px; + left: 0; + right: 0; + bottom: 0; + background: linear-gradient( + 180.1deg, + rgba(250, 245, 240, 0.74) 0.09%, + #ffffff 99.91% + ); + border-radius: 24px 24px 0 0; + z-index: 3; +} +.content > .floors > .tabs { + position: absolute; + display: flex; + width: 236px; + padding: 4px; + left: 0; + right: 0; + top: 20px; + margin: auto; + background: #eee9de; + border-radius: 10px; +} +.content > .floors > .tabs > .tab { + flex: 1; + height: 44px; + line-height: 44px; + font-family: Noto IKEA Simplified Chinese; + font-style: normal; + font-weight: normal; + font-size: 16px; + color: #767571; +} +.content > .floors > .tabs > .tab.active { + background: #ffdb00; + border-radius: 8px; + font-weight: bold; + color: #474747; +} +.content > .floors > .list { + position: absolute; + top: 96px; + left: 16px; + right: 16px; + width: calc(100vw - 32px); + text-align: center; + box-sizing: border-box; +} + +.grid { + display: grid; + width: 232px; + grid-template-columns: 1fr 1fr; + gap: 14px 8px; + margin: auto; +} +.floors > .list .grid .item { + width: 112px; +} +.floors > .list .grid .item + .item { + margin-top: 0; +} +.floors > .list .item { + width: 140px; + height: 40px; + margin: auto; + line-height: 40px; + border: 1px solid #d1c8b9; + box-sizing: border-box; + border-radius: 100px; + font-style: normal; + font-weight: bold; + font-size: 16px; + letter-spacing: 1px; + color: #6a6665; +} + +.floors > .list .item.active { + color: #fff; + background: #ed912b; + box-shadow: 0px 4px 20px rgba(215, 148, 87, 0.33); + border: none; +} + +.floors > .list .item + .item { + margin-top: 16px; +} + +.content > .floors > .btn { + position: absolute; + left: 37px; + right: 37px; + width: auto; + bottom: 77px; + background: #ffdb00; + box-shadow: 0px 6px 12px rgba(255, 219, 0, 0.3); + border-radius: 100px; + font-style: normal; + font-weight: 900; + font-size: 16px; + line-height: 50px; + height: 50px; + text-align: center; + color: #474747; + padding: 0; +} + +.content > .floors > .btn.disabled { + color: #fff; + box-shadow: none; + background: #b3aea7; +} + +.scan-modal { + position: fixed; + top: 0; + bottom: 0; + left: 0; + right: 0; + margin: auto; + width: calc(100vw - 36px - 36px); + height: calc(100vw - 36px - 36px); + border-radius: 16px; + box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.75); + z-index: 10 !important; +} + +.scan-modal > .corner { + position: absolute; + z-index: 1; + width: 32px; + height: 32px; + bottom: -16px; + right: -16px; +} + +.corner.lb { + bottom: -16px; + left: -16px; + transform: rotate(90deg); +} + +.corner.tl { + top: -16px; + left: -16px; + transform: rotate(180deg); +} + +.corner.tr { + top: -16px; + right: -16px; + transform: rotate(270deg); +} + +@keyframes scan { + 0% { + height: 100%; + } + + 100% { + height: 0; + } +} + +.scan-modal > .scaner { + position: absolute; + top: -16px; + bottom: -16px; + left: -16px; + right: -16px; + border-radius: 16px; + overflow: hidden; +} + +.scan-modal > .scaner > .bg { + position: absolute; + left: 0; + right: 0; + bottom: 0; + background: linear-gradient( + 180deg, + rgba(255, 255, 255, 0.48) 0.2%, + rgba(255, 255, 255, 0) 100% + ); + animation: 1s scan infinite ease-in-out; +} + +.scan-modal > .title { + position: absolute; + bottom: -68px; + left: 0; + right: 0; + height: 34px; + font-style: normal; + font-weight: bold; + font-size: 24px; + line-height: 34px; + text-align: center; + letter-spacing: 1px; + color: #eee9de; +} + +.scan-modal > .meta { + position: absolute; + bottom: -97px; + left: 0; + right: 0; + font-style: normal; + font-weight: normal; + font-size: 14px; + line-height: 20px; + text-align: center; + color: #b3aea7; +} + +.scan-modal > .btn { + position: absolute; + bottom: -170px; + left: 0; + right: 0; + margin: auto; + width: 180px; + font-family: PingFang SC; + font-style: normal; + font-weight: 900; + font-size: 16px; + line-height: 50px; + height: 50px; + text-align: center; + color: #333333; + background: #ffdb00; + border-radius: 63px; +} + +.success-prompt { + position: fixed; + top: 0; + bottom: 0; + left: 0; + right: 0; + background: rgba(0, 0, 0, 80%); + z-index: 10 !important; +} + +.success-prompt > image { + position: absolute; + width: 112px; + height: 112px; + top: 267px; + left: 0; + right: 0; + margin: auto; +} + +.success-prompt > .title { + position: absolute; + bottom: 158px; + left: 0; + right: 0; + height: 34px; + font-style: normal; + font-weight: bold; + font-size: 24px; + line-height: 34px; + text-align: center; + letter-spacing: 1px; + color: #eee9de; +} + +.success-prompt > .meta { + position: absolute; + bottom: 130px; + left: 0; + right: 0; + font-style: normal; + font-weight: normal; + font-size: 14px; + line-height: 20px; + text-align: center; + color: #b3aea7; +} +.zzcImg { + width: 100%; + height: 100%; + /* border: 1px solid red; */ + z-index: 10; + position: absolute; + left: 0; + top: 0; +} +.zzcimg_ys { + width: 100%; + height: 100%; +} +.scan_lo_tow { + width: 90%; + z-index: 1000000000000 !important; + position: absolute; + left: 5%; + top: 510rpx; + height: 72.4; +} +.trans-y { + animation: site-transy 2s infinite ease-in-out; +} +@keyframes site-transy { + 0% { + transform: translateY(-410px); + } + + 100% { + transform: translateY(300px); + } +} +.scanning_textnl { + z-index: 1000000000000 !important; + position: absolute; + left: 0; + right: 0; + width: 100%; + text-align: center; + font-family: PingFang SC; + font-style: normal; + font-weight: bold; + font-size: 20px; + line-height: 28px; + color: #eee9de; +} +.scanning_tip { + position: absolute; + left: 0; + right: 0; + width: 100%; + text-align: center; + font-family: Noto IKEA Simplified Chinese; + font-style: normal; + font-weight: normal; + font-size: 14px; + line-height: 21px; + text-align: center; + color: #fdd02f; +} +.scanning_tip > image { + display: flex; + width: 180px; + height: 50px; + margin: auto; + margin-top: 8px; +} +.scanning_text { + position: absolute; + left: 0; + right: 0; + width: 100%; + font-family: PingFang SC; + font-style: normal; + font-weight: bold; + font-size: 12px; + line-height: 17px; + text-align: center; + letter-spacing: 1px; + color: rgba(238, 233, 222, 0.5); +} +.flashlightBtn { + position: fixed; + top: 1086rpx; + left: 50%; + transform: translate(-50rpx); + color: red; + z-index: 1000000000000 !important; +} +.on_img { + width: 112rpx; + height: 96rpx; +} +.logo { + position: fixed; + z-index: 11; + left: 16px; + width: 24px; + height: 24px; +} +.title { + position: fixed; + z-index: 11; + height: 27px; + left: 48px; + font-family: Noto IKEA Simplified Chinese; + font-style: normal; + font-weight: bold; + font-size: 18px; + line-height: 27px; + color: #fff; +} +.tomap { + position: fixed; + z-index: 16; + width: 120px; + height: 40px; + left: 8px; +} +@keyframes pointleft { + from { + left: 8px; + } + 50% { + left: 0; + } + to { + left: 8px; + } +} +@keyframes pointright { + from { + right: 8px; + } + 50% { + right: 0; + } + to { + right: 8px; + } +} +.leftyaw { + position: fixed; + width: 100px; + height: 36px; + top: 0; + bottom: 0; + z-index: 11; + left: 8px; + margin: auto; + animation: pointleft 0.5s infinite ease; +} +.rightyaw { + position: fixed; + width: 100px; + height: 36px; + top: 0; + bottom: 0; + z-index: 11; + right: 8px; + margin: auto; + animation: pointright 0.5s infinite ease; +} +.share { + position: fixed; + z-index: 11; + right: 8px; + width: 40px !important; + height: 54px; + background: none; +} +.share-img { + position: fixed; + z-index: 12; + right: 8px; + width: 40px; + height: 54px; + pointer-events: none; +} diff --git a/pages/index/left.png b/pages/index/left.png new file mode 100644 index 0000000..eefead2 Binary files /dev/null and b/pages/index/left.png differ diff --git a/pages/index/leftyaw.png b/pages/index/leftyaw.png new file mode 100644 index 0000000..d1b2bc3 Binary files /dev/null and b/pages/index/leftyaw.png differ diff --git a/pages/index/logo.png b/pages/index/logo.png new file mode 100644 index 0000000..10a3434 Binary files /dev/null and b/pages/index/logo.png differ diff --git a/pages/index/mask.png b/pages/index/mask.png new file mode 100644 index 0000000..d94f75d Binary files /dev/null and b/pages/index/mask.png differ diff --git a/pages/index/right.png b/pages/index/right.png new file mode 100644 index 0000000..ff2bfd1 Binary files /dev/null and b/pages/index/right.png differ diff --git a/pages/index/rightyaw.png b/pages/index/rightyaw.png new file mode 100644 index 0000000..7dc19ac Binary files /dev/null and b/pages/index/rightyaw.png differ diff --git a/pages/index/scanning-tip.png b/pages/index/scanning-tip.png new file mode 100644 index 0000000..110e0fd Binary files /dev/null and b/pages/index/scanning-tip.png differ diff --git a/pages/index/share.png b/pages/index/share.png new file mode 100644 index 0000000..7906bc7 Binary files /dev/null and b/pages/index/share.png differ diff --git a/pages/index/straight.png b/pages/index/straight.png new file mode 100644 index 0000000..526dacc Binary files /dev/null and b/pages/index/straight.png differ diff --git a/pages/index/success.png b/pages/index/success.png new file mode 100644 index 0000000..5aefbfa Binary files /dev/null and b/pages/index/success.png differ diff --git a/pages/index/tomap.png b/pages/index/tomap.png new file mode 100644 index 0000000..b7fac3a Binary files /dev/null and b/pages/index/tomap.png differ diff --git a/pages/map2d/L1.png b/pages/map2d/L1.png new file mode 100644 index 0000000..e3938bc Binary files /dev/null and b/pages/map2d/L1.png differ diff --git a/pages/map2d/L2.png b/pages/map2d/L2.png new file mode 100644 index 0000000..b5dfa35 Binary files /dev/null and b/pages/map2d/L2.png differ diff --git a/pages/map2d/MAPAPP.js b/pages/map2d/MAPAPP.js new file mode 100644 index 0000000..0ba1f50 --- /dev/null +++ b/pages/map2d/MAPAPP.js @@ -0,0 +1,450 @@ +import { getCrossPoint } from "./util"; +import Events from "./events"; + +import dijkstra from "dijkstrajs"; +import { getMapData, mall } from "../../getMapData"; + +const getDistance = (a, b) => + Math.sqrt((a.x - b.x) * (a.x - b.x) + (a.z - b.z) * (a.z - b.z)); +export const minScale = 0.3; +export const maxScale = 1; + +export default class MAPAPP { + events = new Events(); + mall = mall; + groups = []; + x = null; + y = null; + intervals = []; + shown = false; + theta2s = []; + scale = minScale; + constructor(query, component) { + this.searchType = component.data.searchType; + const canvas = query.node; + const ctx = canvas.getContext("2d"); + const dpr = wx.getSystemInfoSync().pixelRatio; + canvas.width = query.width * dpr; + canvas.height = query.height * dpr; + const start = canvas.createImage(); + start.src = "/pages/map2d/start.png"; + const end = canvas.createImage(); + end.src = "/pages/map2d/end.png"; + const arrow = canvas.createImage(); + arrow.src = "/pages/map2d/arrow.png"; + ctx.scale(dpr, dpr); + Object.assign(this, { + canvas, + ctx, + start, + end, + arrow, + width: query.width, + height: query.height, + }); + this.init(); + } + + on(event, cb) { + return this.events.on(event, cb); + } + once(event, cb) { + return this.events.once(event, cb); + } + off(event, cb) { + return this.events.off(event, cb); + } + dispose() { + console.log("map interval disposed"); + this.intervals && this.intervals.forEach(clearInterval); + this.intervals = []; + } + + async init() { + const data = await getMapData(); + Object.assign(this, data); + const { floors } = this.mall; + const { canvas } = this; + const groups = floors.map(([_, name, map2dData]) => { + const floor = canvas.createImage(); + floor.src = map2dData.data; + return floor; + }); + this.groups = groups; + this.events.dispatch("loaded", this); + this.intervals.push( + setInterval(() => { + this.animate(); + }, 1000 / 30) + ); + } + get shops() { + return !this.serverShopInfo + ? [] + : this.serverShopInfo[this.floorOrder].shopList; + } + get currentFloorObject() { + return this.groups[this.floorOrder]; + } + updateTheta2(rag) { + this.theta2 = rag; + } + setXY(x, y) { + this.x = x; + this.y = y; + } + scaleX(number) { + const { x, width, scale } = this; + return (number - x) * scale + width / 2; + } + scaleY(number) { + const { y, height, scale } = this; + return (number - y) * scale + height / 2; + } + scaleLen(number) { + const { scale } = this; + return number * scale; + } + animate() { + const { shown, ctx, x, y, width, height } = this; + if (!shown) return; + ctx.clearRect(0, 0, width, height); + ctx.save(); + // ctx.translate(this.scaleX(-x) + width / 2, this.scaleY(-y) + height / 2); + this.drawFloor(); + this.drawLines(); + ctx.restore(); + this.drawArrow(); + } + drawArrow() { + const { ctx, arrow, width, height } = this; + ctx.save(); + ctx.translate(width / 2, height / 2); + ctx.drawImage(arrow, -36, -(82 - 36), 72, 82); + ctx.restore(); + } + drawPath() { + const { linePath, ctx } = this; + const start = linePath[0]; + const end = linePath[linePath.length - 1]; + ctx.fillStyle = "#fec210"; + ctx.beginPath(); + ctx.arc( + this.scaleX(start[0]), + this.scaleY(start[1]), + // this.scaleLen(10), + 10, + 0, + 2 * Math.PI + ); + ctx.fill(); + ctx.beginPath(); + ctx.arc( + this.scaleX(end[0]), + this.scaleY(end[1]), + // this.scaleLen(10), + 10, + 0, + 2 * Math.PI + ); + ctx.fill(); + + ctx.beginPath(); + linePath.forEach(([x, y], i) => { + if (i === 0) { + ctx.moveTo(this.scaleX(x), this.scaleY(y)); + } else { + ctx.lineTo(this.scaleX(x), this.scaleY(y)); + } + }); + } + drawLines() { + const { linePath, ctx } = this; + if (!linePath || !linePath.length) return; + this.drawPath(); + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + // ctx.lineWidth = this.scaleLen(11); + ctx.lineWidth = 11; + ctx.strokeStyle = "#fec210"; + ctx.stroke(); + for (let i = 9; i >= 1; i -= 1) { + ctx.lineCap = "butt"; + ctx.lineJoin = "butt"; + // ctx.lineWidth = this.scaleLen(i); + ctx.lineWidth = i; + ctx.strokeStyle = "#fff"; + // ctx.setLineDash([this.scaleLen(4), this.scaleLen(13)]); + ctx.setLineDash([4, 13]); + // ctx.lineDashOffset = this.scaleLen(i - 9); + ctx.lineDashOffset = i - 9; + ctx.stroke(); + ctx.strokeStyle = "#ed912b"; + // ctx.setLineDash([0, this.scaleLen(4), this.scaleLen(13), 0]); + ctx.setLineDash([0, 4, 13, 0]); + // ctx.lineDashOffset = this.scaleLen(i - 9); + ctx.lineDashOffset = i - 9; + ctx.stroke(); + } + const start = linePath[0]; + const end = linePath[linePath.length - 1]; + ctx.fillStyle = "#ed912b"; + // ctx.lineWidth = this.scaleLen(1); + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.arc( + this.scaleX(start[0]), + this.scaleY(start[1]), + // this.scaleLen(9), + 9, + 0, + 2 * Math.PI + ); + ctx.fill(); + ctx.beginPath(); + ctx.arc( + this.scaleX(end[0]), + this.scaleY(end[1]), + // this.scaleLen(9), + 9, + 0, + 2 * Math.PI + ); + ctx.fill(); + ctx.fillStyle = "#fff"; + ctx.beginPath(); + ctx.arc( + this.scaleX(start[0]), + this.scaleY(start[1]), + // this.scaleLen(4.5), + 4.5, + 0, + 2 * Math.PI + ); + ctx.fill(); + ctx.beginPath(); + ctx.arc( + this.scaleX(end[0]), + this.scaleY(end[1]), + // this.scaleLen(4.5), + 4.5, + 0, + 2 * Math.PI + ); + ctx.fill(); + } + + drawFloor() { + const { floorOrder, groups, ctx } = this; + const floor = groups[floorOrder]; + ctx.save(); + ctx.drawImage( + floor, + this.scaleX(-floor.width / 2), + this.scaleY(-floor.height / 2), + this.scaleLen(floor.width), + this.scaleLen(floor.height) + ); + ctx.restore(); + } + + async changeFloor(num) { + this.floorOrder = num; + this.x = null; + this.y = null; + this.events.dispatch("floorchange", Number(num)); + return; + } + + cross({ x, y }) { + const point = { x, y }; + const { positions } = this; + if (!(positions && positions.length)) return point; + let minDisance = Infinity; + let crossPoint = null; + let index = 1; + for (let k = 1; k < positions.length; k++) { + let point1 = positions[k - 1]; + let point2 = positions[k]; + let cross = getCrossPoint(point, point1, point2); + let d = Math.sqrt( + (point.x - cross.x) * (point.x - cross.x) + + (point.y - cross.y) * (point.y - cross.y) + ); + + if (d < minDisance) { + minDisance = d; + crossPoint = cross; + index = k; + if (d < 0.5) break; + } + } + return crossPoint; + } + requestRoute(start, end, draw = true) { + if (!(start && end)) return; + const startFloorId = start[2]; + const startFloorOrder = getApp().globalData.floorIdFloorOrderMap[ + startFloorId + ]; + const { name: sname } = this.getNearestPoint({ + x: start[0], + z: start[1], + floorOrder: startFloorOrder, + }); + const startFloor = startFloorOrder; + const startPoint = Number(sname); + + const endFloor = end.floorOrder; + const endPoint = end.navPoint; + + let path = this.shortestPath( + { + floorOrder: startFloor, + NavPoint: startPoint, + }, + { + floorOrder: endFloor, + NavPoint: endPoint, + } + ); + if (!path) { + console.log("寻路失败", "start", start, "end", end); + return { naviData: null, nextFloorId: null }; + } + let floorIdPoints = path.map((str) => str.split("_")); + const byFirstDiffFloor = ([floorId], i) => + i === 0 ? false : floorIdPoints[i - 1][0] !== floorId; + const index = floorIdPoints.findIndex(byFirstDiffFloor); + console.log("index", index); + const isFloorChange = index !== -1; + const currentFloorOrder = Number(floorIdPoints[0][0]); + const nextFloorOrder = !isFloorChange + ? null + : Number(floorIdPoints[index][0]); + const fac = !isFloorChange ? null : this.facilityLiftMap[path[index - 1]]; + let naviData = floorIdPoints.slice(0, index === -1 ? undefined : index); + naviData = naviData.reduce((acc, [floorOrder, point]) => { + const last = acc[acc.length - 1]; + const x = this.points[floorOrder][point].position[0]; + const y = this.points[floorOrder][point].position[2]; + const floorId = startFloorId; + if (last && Math.abs(last.y - y) <= 3 && Math.abs(last.x - x) <= 3) + return acc; + else return [...acc, { x, y, floorId }]; + }, []); + + if (naviData.length === 1) { + naviData.unshift({ + x: start[0], + y: start[1], + flooorId: naviData[0].flooorId, + }); + } + naviData.forEach((data, i) => { + data.pointType = + i === 0 + ? 0 + : i !== naviData.length - 1 + ? 1 + : !isFloorChange + ? 6 + : nextFloorOrder > currentFloorOrder + ? fac.Type == 5 + ? 2 + : 4 + : fac.Type == 5 + ? 3 + : 5; + }); + this.positions = naviData; + console.log("originalNaviData", naviData); + if (draw && naviData.length) { + this.linePath = naviData.map(({ x, y }) => [x, y]); + } + const nextFloorId = !isFloorChange + ? null + : getApp().globalData.floors[path[index].split("_")[0]].floorId; + console.log("nextFloorId", nextFloorId); + return { + naviData, + nextFloorId, + }; + } + shortestPath( + { floorOrder: floorOrder1, NavPoint: NavPoint1 }, + { floorOrder: floorOrder2, NavPoint: NavPoint2 } + ) { + try { + const { graph, graphDt, graphFt, searchType = 0 } = this; + let currentGraph = + searchType === 0 ? graph : searchType === 1 ? graphFt : graphDt; + const s = floorOrder1 + "_" + NavPoint1; + const d = floorOrder2 + "_" + NavPoint2; + if (currentGraph && currentGraph[s] && currentGraph[d]) { + let path = dijkstra.find_path(currentGraph, s, d); + return path; + } else return null; + } catch (e) { + console.log(e); + return null; + } + } + getNearestPoint({ x, z, floorOrder }) { + const { points } = this; + const [nearest] = points[floorOrder].reduce( + ([last, min], nxt) => { + if (last === null) { + return [ + nxt, + getDistance( + { + x, + z, + }, + { + x: nxt.position[0], + z: nxt.position[2], + } + ), + ]; + } + const dis = getDistance( + { + x, + z, + }, + { + x: nxt.position[0], + z: nxt.position[2], + } + ); + if (dis < min) return [nxt, dis]; + else return [last, min]; + }, + [null, Infinity] + ); + return nearest; + } + getFloorHeightByFloorOrder(floorOrder) { + const { config, groups } = this; + const floor = groups[floorOrder]; + const { floorHeights } = config; + return floorOrder in floorHeights + ? floorHeights[floorOrder] + : floor.floorHeight; + } + getBoxHeightByFloorOrder(floorOrder) { + const { groups } = this; + const floor = groups[floorOrder]; + return floor.boxHeight; + } + getNavIconY(floorOrder) { + const { groups } = this; + const floor = groups[floorOrder]; + if (!floor) return this.getNavIconY(this.floorOrder); + const boxHeight = this.getBoxHeightByFloorOrder(floorOrder); + const radius = PathLine.getPathLineRadius(this, floor); + return boxHeight + radius * 5; + } +} diff --git a/pages/map2d/arrow.png b/pages/map2d/arrow.png new file mode 100644 index 0000000..e2b09ba Binary files /dev/null and b/pages/map2d/arrow.png differ diff --git a/pages/map2d/end.png b/pages/map2d/end.png new file mode 100644 index 0000000..d4c6092 Binary files /dev/null and b/pages/map2d/end.png differ diff --git a/pages/map2d/events.js b/pages/map2d/events.js new file mode 100644 index 0000000..b21f5b6 --- /dev/null +++ b/pages/map2d/events.js @@ -0,0 +1,64 @@ +/* + @ author: leeenx + @ 事件封装 + @ object.on(event, fn) // 监听一个事件 + @ object.off(event, fn) // 取消监听 + @ object.once(event, fn) // 只监听一次事件 + @ object.dispacth(event, arg) // 触发一个事件 +*/ + +export default class Events { + constructor() { + // 定义的事件与回调 + this.defineEvent = {}; + } + // 注册事件 + register(event, cb) { + if (!this.defineEvent[event]) { + this.defineEvent[event] = [cb]; + } else { + this.defineEvent[event].push(cb); + } + } + // 派遣事件 + dispatch(event, arg) { + if (this.defineEvent[event]) { + { + for (let i = 0, len = this.defineEvent[event].length; i < len; ++i) { + this.defineEvent[event][i] && this.defineEvent[event][i](arg); + } + } + } + } + // on 监听 + on(event, cb) { + return this.register(event, cb); + } + // off 方法 + off(event, cb) { + if (this.defineEvent[event]) { + if (typeof cb == "undefined") { + delete this.defineEvent[event]; // 表示全部删除 + } else { + // 遍历查找 + for (let i = 0, len = this.defineEvent[event].length; i < len; ++i) { + if (cb == this.defineEvent[event][i]) { + this.defineEvent[event][i] = null; // 标记为空 - 防止dispath 长度变化 + // 延时删除对应事件 + setTimeout(() => this.defineEvent[event].splice(i, 1), 0); + break; + } + } + } + } + } + + // once 方法,监听一次 + once(event, cb) { + let onceCb = () => { + cb && cb(); + this.off(event, onceCb); + }; + this.register(event, onceCb); + } +} diff --git a/pages/map2d/map2d.js b/pages/map2d/map2d.js new file mode 100644 index 0000000..5850cef --- /dev/null +++ b/pages/map2d/map2d.js @@ -0,0 +1,118 @@ +import MAPAPP, { minScale, maxScale } from "./MAPAPP"; +let map = null; +const compassCbs = []; +let initScale = 1; +Component({ + /** + * 组件的属性列表 + */ + properties: { + floororder: Number, + hidden: Boolean, + loc: Array, + searchType: Number, + }, + data: { + loaded: false, + dpr: wx.getSystemInfoSync().pixelRatio, + shops: [], + floors: [], + pageHidden: false, + sliderValue: 0, + }, + observers: { + hidden(val) { + if (val) { + wx.stopCompass({ fail: console.log }); + if (map) { + map.shown = false; + } + } else { + wx.startCompass({ fail: console.log }); + if (map) { + map.shown = true; + } + } + }, + floororder(num) { + if (map && num !== null && num !== undefined && this.data.loaded) + map.changeFloor(num); + }, + loc([x, y]) { + if (map) { + const crossPoint = map.cross({ x, y }); + map.setXY(crossPoint.x, crossPoint.y); + map.updateTheta2(0); + try { + const { name } = map.getNearestPoint({ + x, + z: y, + floorOrder: this.data.floororder, + }); + this.triggerEvent("point", name); + } catch (error) { + console.log(error); + } + } + }, + }, + lifetimes: { + attached() {}, + detached() { + console.log("map2d detached"); + map.dispose(); + map = null; + compassCbs.forEach((cb) => wx.offCompassChange(cb)); + compassCbs.length = 0; + }, + ready() { + this.createSelectorQuery() + .select(".map2d") + .fields({ + node: true, + size: true, + }) + .exec((res) => { + map = new MAPAPP(res[0], this); + initScale = map.scale; + this.setData({ + floors: map.mall.floors, + sceneIndex: map.mall.groundFloorIndex, + }); + map.on("loaded", (map) => { + this.setData({ loaded: true }); + if (typeof this.data.floororder === "number") + map.changeFloor(this.data.floororder); + this.triggerEvent("map", map); + const compassCb = ({ direction }) => { + map && map.updateTheta2(-(direction / 180) * Math.PI); + }; + compassCbs.push(compassCb); + wx.onCompassChange(compassCb); + }); + }); + }, + moved: function () {}, + }, + pageLifetimes: { + hide() { + this.setData({ pageHidden: true }); + }, + show() { + this.setData({ pageHidden: false }); + }, + }, + methods: { + handlePinch(e) { + if (map) { + let newScale = initScale * e.detail.zoom; + newScale = Math.max(minScale, newScale); + newScale = Math.min(maxScale, newScale); + map.scale = newScale; + } + }, + handleMultitouchstart() { + initScale = map.scale; + }, + }, +}); diff --git a/pages/map2d/map2d.json b/pages/map2d/map2d.json new file mode 100644 index 0000000..85e9d42 --- /dev/null +++ b/pages/map2d/map2d.json @@ -0,0 +1,6 @@ +{ + "component": true, + "usingComponents": { + "gesture": "/pages/gesture/gesture" + } +} \ No newline at end of file diff --git a/pages/map2d/map2d.wxml b/pages/map2d/map2d.wxml new file mode 100644 index 0000000..61fe47b --- /dev/null +++ b/pages/map2d/map2d.wxml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/pages/map2d/map2d.wxss b/pages/map2d/map2d.wxss new file mode 100644 index 0000000..03e865f --- /dev/null +++ b/pages/map2d/map2d.wxss @@ -0,0 +1,33 @@ +.map2d-wrapper { + position: fixed; + bottom: 82px; + left: 8px; + right: 8px; + height: 248px; + border-radius: 16px 16px 0 0; + overflow: hidden; + background: #fff; + z-index: 12 !important; +} + +.map2d-wrapper.hidden { + bottom: -99999999px; +} + +.map2d { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + width: calc(100vw - 8px - 8px); + height: 248px; + z-index: 1; +} +.slider { + position: absolute; + top: 0; + right: 0; + width: 248px; + z-index: 2; +} diff --git a/pages/map2d/start.png b/pages/map2d/start.png new file mode 100644 index 0000000..cc9bf39 Binary files /dev/null and b/pages/map2d/start.png differ diff --git a/pages/map2d/util.js b/pages/map2d/util.js new file mode 100644 index 0000000..938da9e --- /dev/null +++ b/pages/map2d/util.js @@ -0,0 +1,42 @@ +export const get = (url) => + new Promise((resolve) => { + wx.request({ + url, + success({ data }) { + resolve(data); + }, + }); + }); + +export const post = (url, data) => + new Promise((resolve) => { + wx.request({ + url, + method: "POST", + data, + success({ data }) { + resolve(data); + }, + }); + }); + +export const getCrossPoint = (point, point1, point2) => { + const cross = + (point2.x - point1.x) * (point.x - point1.x) + + (point2.y - point1.y) * (point.y - point1.y); + + if (cross <= 0) return point1; + + const d2 = + (point2.x - point1.x) * (point2.x - point1.x) + + (point2.y - point1.y) * (point2.y - point1.y); + + if (cross >= d2) return point2; + + const r = cross / d2; + + const px = point1.x + (point2.x - point1.x) * r; + const py = point1.y + (point2.y - point1.y) * r; + + return { x: px, y: py }; +}; diff --git a/pages/nav/bubble.png b/pages/nav/bubble.png new file mode 100644 index 0000000..99853e6 Binary files /dev/null and b/pages/nav/bubble.png differ diff --git a/pages/nav/close.png b/pages/nav/close.png new file mode 100644 index 0000000..f0237b7 Binary files /dev/null and b/pages/nav/close.png differ diff --git a/pages/nav/nav.js b/pages/nav/nav.js new file mode 100644 index 0000000..8c2f072 --- /dev/null +++ b/pages/nav/nav.js @@ -0,0 +1,33 @@ +Component({ + properties: { + icon: String, + t1: String, + t2: String, + progress: Number, + end: Boolean, + }, + + data: { + progressText: "0%", + progressNum: 0, + }, + + observers: { + progress(val) { + let progressNum = this.data.end ? 1 : val; + if (isNaN(progressNum)) return; + if (progressNum < 0) progressNum = 0; + if (progressNum > 1) progressNum = 1; + this.setData({ + progressText: parseInt(progressNum * 100) + "%", + progressNum, + }); + }, + }, + + methods: { + handleTap() { + this.triggerEvent("exit"); + }, + }, +}); diff --git a/pages/nav/nav.json b/pages/nav/nav.json new file mode 100644 index 0000000..e8cfaaf --- /dev/null +++ b/pages/nav/nav.json @@ -0,0 +1,4 @@ +{ + "component": true, + "usingComponents": {} +} \ No newline at end of file diff --git a/pages/nav/nav.wxml b/pages/nav/nav.wxml new file mode 100644 index 0000000..5a3a7a6 --- /dev/null +++ b/pages/nav/nav.wxml @@ -0,0 +1,13 @@ + + + {{end?'已到达': t1}} + {{end?'': t2}} + + + + + + + {{progressText}} + + \ No newline at end of file diff --git a/pages/nav/nav.wxss b/pages/nav/nav.wxss new file mode 100644 index 0000000..3964f90 --- /dev/null +++ b/pages/nav/nav.wxss @@ -0,0 +1,115 @@ +.nav { + position: fixed; + height: 120px; + left: 8px; + right: 8px; + bottom: 82px; + background: linear-gradient(180deg, #ffffff 0%, #ffffff 100.83%); + z-index: 12 !important; + border-radius: 16px 16px 0 0; +} +.nav > image { + position: absolute; + top: 12px; + left: 12px; + width: 72px; + height: 72px; +} +.nav > .t1 { + position: absolute; + top: 20px; + left: 92px; + right: 40px; + font-family: Noto IKEA Simplified Chinese; + font-style: normal; + font-weight: bold; + font-size: 24px; + line-height: 36px; + height: 36px; + color: #767571; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.nav > .t2 { + position: absolute; + top: 64px; + left: 92px; + right: 70px; + font-family: Noto IKEA Simplified Chinese; + font-style: normal; + font-weight: normal; + font-size: 14px; + opacity: 0.7; + line-height: 20px; + height: 20px; + color: #6a6665; +} +.nav > .exit { + position: absolute; + top: 16px; + left: auto; + right: 16px; + width: 24px; + height: 24px; +} +.progress { + position: absolute; + left: 20px; + right: 20px; + bottom: 10px; + height: 2px; + background: #eee9de; + border-radius: 5px; + z-index: 1; +} +.bar { + position: absolute; + left: 20px; + right: 20px; + bottom: 10px; + height: 2px; + background: #ffdb00; + border-radius: 5px; + z-index: 2; +} +.thumb { + position: absolute; + width: 12px; + height: 12px; + bottom: 5px; + border-radius: 50%; + border: 2px solid rgba(239, 150, 23, 0.5); + background: #fff; + z-index: 3; + transform: translate(-50%, 0); +} +.bubble { + position: absolute; + width: 34px; + height: 14px; + bottom: 18px; + transform: translate(-50%, 0); +} +.bubble image { + position: absolute; + top: 0; + left: 0; + right: 0; + width: 34px; + height: 14px; + z-index: 0; +} +.bubble view { + position: absolute; + top: 1px; + left: 0; + right: 0; + z-index: 1; + text-align: center; + font-style: normal; + font-weight: 900; + font-size: 8px; + line-height: 11px; + color: #6a6665; +} diff --git a/pages/privacy/index.js b/pages/privacy/index.js new file mode 100644 index 0000000..8916456 --- /dev/null +++ b/pages/privacy/index.js @@ -0,0 +1,66 @@ +// pages/privacy/index.js +Page({ + + /** + * 页面的初始数据 + */ + data: { + + }, + + /** + * 生命周期函数--监听页面加载 + */ + onLoad: function (options) { + + }, + + /** + * 生命周期函数--监听页面初次渲染完成 + */ + onReady: function () { + + }, + + /** + * 生命周期函数--监听页面显示 + */ + onShow: function () { + + }, + + /** + * 生命周期函数--监听页面隐藏 + */ + onHide: function () { + + }, + + /** + * 生命周期函数--监听页面卸载 + */ + onUnload: function () { + + }, + + /** + * 页面相关事件处理函数--监听用户下拉动作 + */ + onPullDownRefresh: function () { + + }, + + /** + * 页面上拉触底事件的处理函数 + */ + onReachBottom: function () { + + }, + + /** + * 用户点击右上角分享 + */ + onShareAppMessage: function () { + + } +}) \ No newline at end of file diff --git a/pages/privacy/index.json b/pages/privacy/index.json new file mode 100644 index 0000000..fa30d24 --- /dev/null +++ b/pages/privacy/index.json @@ -0,0 +1,6 @@ +{ + "usingComponents": {}, + "navigationStyle": "default", + "navigationBarTitleText": "隐私政策", + "navigationBarBackgroundColor": "#FFFFFF" +} \ No newline at end of file diff --git a/pages/privacy/index.wxml b/pages/privacy/index.wxml new file mode 100644 index 0000000..ddaf89a --- /dev/null +++ b/pages/privacy/index.wxml @@ -0,0 +1,180 @@ + + 隐私政策 + 最近更新日期:2021年8月20日 + 版本生效日期:2021年8月26日 + + 本政策适用于英格卡购物中心中国提供的各项产品及服务,包括线下、线上所提供的购物、聚会体验、公寓式办公及与其相关的顾客服务、荟聚会员服务、租赁服务、产品目录册及宣传资料投递服务等。 + 如果您有任何疑问、意见或建议,请通过“任何疑问”中所列的方式与我们取得联系。 + + 英格卡购物中心中国(以下简称“我们”或“荟聚中心”)深知个人信息对您的重要性,并会尽全力保护您的个人信息安全可靠。我们致力于维持您对我们的信任,保护您的个人信息;同时,英格卡购物中心中国承诺,我们将按业界成熟的安全标准,采取相应的安全保护措施来保护您的个人信息。 请在使用我们的产品(或服务)前,仔细阅读并了解本《隐私政策》,特别是以粗体或下划线标识的条款。如您选择使用或继续使用我们的产品或服务,即意味着您完全理解本隐私政策的全部内容,并同意我们按照本隐私政策收集、使用、储存和分享您的相关信息。 + 注:本《隐私政策》版本更新日期为2021年8月20日,将于2021年8月26日正式生效,在2021年8月20日至2021年8月25日期间,对于新注册用户,或是您认为更新的《隐私政策》对您更为有利,我们同意双方适用新的《隐私政策》内容。 + + + + 目录 + 定义 + 我们如何收集和使用您的个人信息? + 我们如何使用Cookie和同类技术 + 您的个人信息是否会被共享、转让或披露? + 您的个人信息将被如何保护? + 您的权利 + 我们如何处理未成年人的个人信息 + 您的个人信息如何在全球范围转移 + 本政策如何更新 + 任何疑问 + 定义 + 英格卡集团:指INGKA Holding B.V.及其控制实体。 + 英格卡购物中心中国:指英格卡集团直接或间接在中华人民共和国(以下简称“中国”)境内(为本隐私政策之目的,中国的香港、澳门和台湾地区除外)投资的所有从事英格卡购物中心业务的法人实体。 + 线上渠道:指英格卡购物中心中国(或其指定供应商)所提供的网站、手机应用、社交媒体应用等通过互联网访问使用的渠道,如荟聚云商城等。 + 个人信息:以电子或者其他方式记录的能够单独或者与其他信息结合识别特定自然人身份或者反映特定自然人活动情况的各种信息,包括但不仅限于个人姓名、住址、电话号码、身份证号码等。 + 营销信息:荟聚中心向顾客通过包括但不仅限于电子邮件、即时通讯、社交平台等渠道发送的用于推广、推销商品或服务的信息,如荟聚中心的活动、服务或产品推广等信息,但不包括为了向顾客提供服务而必须发送的信息,如物流信息、服务提示等。 + 我们如何收集和使用您的个人信息? + 我们仅会出于本政策中说明的以下目的,收集和使用您的个人信息。部分收集和使用个人信息的场景在不同的荟聚中心可能不适用。 + 注册荟聚俱乐部会员 + 如您申请注册成为荟聚俱乐部会员,您需要提供您的手机号码,并绑定您的微信账号,以便我们向您提供对应的服务。同时,在您的注册过程中或注册之后,您可以选择额外提供您的姓名、性别、出生日期、婚姻状况、子女数量、子女生日、所在省市区、车辆拥有情况、教育水平、职业、个人月收入范围、购物喜好等,以便我们为您提供个性化的服务及营销信息,如您不提供这些额外的个人信息,并不会影响您注册成为荟聚俱乐部会员。 + 注册并使用荟商在线系统 + 如您作为我们的商户雇员,选择在荟商在线系统中注册成为用户时您将被要求提交姓名、电子邮箱地址、电话号码、雇主名称和岗位名称(“基本信息”)。如您需在我们的线上渠道中注册导购或店长等信息的,您可能会被要求提供姓名、手机号码、雇主名称等。 + 如您需要我们制作出入您所在的荟聚中心的门禁卡,除了提供基本信息外,您还需要提供头像照片。出于安全考虑,我们希望了解进出荟聚中心的工作人员情况,因此我们将存储您是否以及何时持有门禁卡等相关信息,我们亦将保留有关门禁卡发放数量的相关信息。 + + 我们也会通过您提供的基本信息,向您发送您在荟聚中心工作而益于知晓的沟通信息,如与荟聚中心相关的实用信息、活动邀请、新闻、安全沟通信息及优惠折扣等。沟通信息将被用于跟进服务请求、服务预测、对荟聚中心需求的维护以及其他统计目的。作为荟商在线系统的用户,您在系统中的用户活动信息会被存储并用于统计,以便进行系统的优化。 + 我们将收集并存储与您的各项交流信息,如果您使用荟商在线系统提交服务请求,我们还将存储该类请求及与此相关的交流信息。 + + 我们将根据适用的法律、法规,处理、使用您在荟商在线系统中提供的个人信息,以确保一个高效且运作良好的系统,从而与我们的租户和合作伙伴进行沟通,并跟踪和跟进服务请求。您的基本信息将自您终止您的系统账户之日起保存12个月或法律规定的其他时间;您的服务请求(包括第三方进入需求)和相关沟通信息将自服务请求被提出之日起保存12 个月或法律规定的其他时间;门禁卡信息将自卡片被禁用之日起保存12个月或法律规定的其他时间。 + 会员积分及权益 + 为完成会员积分服务,您可在荟聚中心商户结账时提供您的荟聚俱乐部会员信息、通过微信扫描购物小票上积分二维码、使用荟聚中心微信公众号中的会员中心上传购物小票、在荟聚云商城上使用荟聚俱乐部会员卡等方式将您的会员信息与您的消费记录进行关联。我们会根据您的消费记录、其他可以获取或使用积分的行为,提取您必要的消费、积分、停车信息,以便为您提供积分奖励兑换、停车优惠、活动参与等服务。 + 活动登记 + 为了注册参加荟聚中心提供的各类活动,您在注册登记时需要提供您的联系方式、手机号码。在注册时,您可以选择是否接受后续其他活动的通知。 + 在线下单 + 如您在我们的线上渠道中购物,如荟聚微信公众号、荟聚云商城,在您结算购物车内商品时,我们会根据您购买的商品或项目生成您的订单。对于实物商品订单,您需要在订单中至少填写收货人姓名、手机号码及收货地址;同时该订单中会载明您的订单号、您所购买的商品或服务信息、您应支付的货款金额及支付方式;您可以另外填写收货人的固定电话、邮箱地址等更多信息以确保商品可以准确送达,但不填写这些额外信息不影响您订单的生成。 + 上述所有信息构成您的“订单信息”,我们将使用您的订单信息进行身份核验、确定交易、支付结算、完成配送、为您查询订单以及提供客服咨询与售后服务;我们还会使用您的订单信息来判断您的交易是否存在异常以保护您的交易安全。 + 同时,您可以通过我们为您提供的评论、直播或其他信息发布功能公开发布信息,包括发布对购买商品或服务的打分、评级及直播互动的评论,我们将收集、审核您上传或发布的此类信息。您发布的信息中可能会涉及您或他人的个人信息甚至敏感个人信息,请您谨慎考虑是否要发布此类信息。若您发布的信息中涉及儿童个人信息的,您需在发布前征得该儿童监护人的同意。 + 荟聚宝贝儿童乐园 + 为便于我们在儿童游玩荟聚宝贝乐园期间联系家长,及在家长认领儿童时进行核验,在使用我们的荟聚宝贝儿童乐园服务时,我们将向入园儿童的家长或监护人收集儿童姓名、年龄、生日、特殊要求、监护人的姓名、监护人身份证号码、联系电话等基本信息。同时我们会现场拍摄监护人及儿童的照片进行留存。儿童和监护人的个人信息将在收集之日起保存6个月或法律规定的其他时间;此外,我们只会在监护人明示同意的情况下,使用该信息向监护人推送与儿童有关的个性化营销信息。 + 荟聚中心停车服务 + 在荟聚中心的微信公众号中,您可以将您的车牌号与您的荟聚俱乐部会员信息绑定,以便我们为您提供微信快速支付停车费及停车费减免特权、反向寻车等服务。 + 免费Wi-Fi服务 + 根据相关法律法规的要求,当您使用我们提供的免费Wi-Fi时,我们将采取上网手机短信实名认证、上网行为审计、日志留存等网络安全技术措施,并向公安机关提供符合公共安全行业技术标准的联网接口。同时,为了提升您的购物体验,我们会记录您的Wi-Fi使用地点、时长等信息,以用于内部运营数据的分析。 + 开展内部审计、问卷调查、数据分析和研究,改善我们的产品或服务 + 在某些情况下,我们可能会需要您提供您个人的真实姓名、联系方式、联系地址和电子邮箱地址、您在荟聚中心或我们的线上渠道购物的交易记录、您使用荟聚中心在线会员服务设备、所绑定微信账号的唯一识别符和在访问中所使用的IP地址,以及您决定与我们分享的任何其他信息,使我们能够开展内部审计、问卷调查、数据分析和研究。这将会帮助我们改善荟聚中心的产品和服务,以便为您提供更加符合需求的产品和服务。 + 您充分知晓,以下情形中,我们收集、使用个人信息无需征得您的授权同意: + 1.与国家安全、国防安全有关的; + 2.与公共安全、公共卫生、重大公共利益有关的; + 3.与犯罪侦查、起诉、审判和判决执行等有关的; + 4.出于维护个人信息主体或其他个人的生命、财产等重大合法权益但又很难得到本人同意的; + 5.所收集的个人信息是个人信息主体自行向社会公众公开的; + 6.从合法公开披露的信息中收集的您的个人信息的,如合法的新闻报道、政府信息公开等渠道; + 7.根据您的要求签订和履行合同所必需的; + 8.用于维护所提供的产品与/或服务的安全稳定运行所必需的,例如发现、处置产品与/或服务的故障; + 9.法律法规规定的其他情形。 + 我们从第三方获得您个人信息的情形 + 我们可能从第三方获取您授权共享的账户信息(包括但不仅限于头像、昵称等),并在您同意本隐私政策后将您的第三方账户与您在荟聚中心的会员账户绑定,使您可以通过第三方账户直接登录并使用我们的产品与/或服务。我们会将依据与第三方的约定、对个人信息来源的合法性进行确认后,在符合相关法律和法规规定的前提下,使用您的这些个人信息。 + 使用您个人信息的规则 + 如果当我们要将信息用于本政策未载明的其它用途时,会事先征求您的同意。 + 当我们要将基于特定目的收集而来的信息用于其他目的时,会事先征求您的同意。 + 我们如何使用Cookie和同类技术 + Cookie的使用 + 我们网站和移动应用拥有多种实用的Cookie功能,我们会在您的计算机或移动设备上存储名为 Cookie 的小数据文件。Cookie 是小型文件,通常包含标识符、站点名称以及一些号码和字符。借助于 Cookie,我们网站能够记录您在浏览期间的活动信息,以便您下次访问网站时更加轻松快捷。例如,我们会使用Cookie记住您的首选语言等个人浏览偏好、统计网页访问者数量。 + Cookie不可用来"窃取"关于您本人及您所有使用的电脑系统的信息,您不必担心由此引发的个人隐私问题。 我们也不会将Cookie用于本政策所述目的之外的任何用途。您可根据自己的偏好管理或删除 Cookie。有关详情,请参见 AboutCookies.org。 + 网站信标和像素标签 + 除Cookie外,我们还会在网站和移动应用上使用网站信标和像素标签等其他同类技术。 + 我们通过在网站和移动应用上使用网站信标和像素标签,来计算用户访问数量,并统计用户的使用偏好。 + 我们向您发送的电子邮件可能含有链接至我们网站的URL。如果您点击该链接,我们会跟踪此次点击,帮助我们了解您的产品或服务偏好并改善我们的服务。如果您不希望自己的活动以这种方式被追踪,您可随时从我们的寄信名单中退订。 + 您的个人信息是否会被共享、转让或披露? + 共享 + 由于各地的荟聚中心所属的英格卡集团是一家跨国公司,基于集团运营和管理的需要,您的个人信息可能会在英格卡集团内被共享,以便我们为您提供更为优质的服务。 + 我们承诺,所有的共享仅限您的必要个人信息,且受本隐私政策的约束;如果我们要改变个人信息的使用及处理目的,我们将再次征求您的授权同意。同时我们会严格遵守相关法律法规对数据跨境传输的各项要求,具体参见本隐私政策“您的个人信息如何在全球范围转移 “章节。 + + 我们不会与英格卡集团以外的任何公司、组织和个人分享您的个人信息,但以下情况除外: + 1. 在获取明确同意的情况下共享:获得您的明确同意后,我们会与其他方共享您的个人信息。 + 2. 我们可能会根据法律法规规定,或按政府主管部门的强制性要求,对外共享您的个人信息。 + 3. 与授权合作伙伴共享:仅为实现本政策中声明的目的,我们的某些服务将由授权合作伙伴提供。我们可能会与合作伙伴共享您的某些个人信息,以提供更好的客户服务和用户体验。例如,在您网上购买我们的产品时,我们必须与物流服务提供商共享您的个人信息才能安排送货,或者安排合作伙伴提供服务。我们仅会出于合法、正当、必要、特定、明确的目的共享您的个人信息,并且只会共享提供服务所必要的个人信息。我们的合作伙伴无权将共享的个人信息用于任何其他用途。 + + 目前,我们的授权合作伙伴包括以下两大类型: + 1) 广告、分析服务类的授权合作伙伴。除非得到您的许可,否则我们不会将您的个人身份信息(指可以识别您身份的信息,例如姓名或电子邮箱,通过这些信息可以联系到您或识别您的身份)与提供广告、分析服务的合作伙伴分享。我们会向这些合作伙伴提供有关其广告覆盖面和有效性的信息,而不会提供您的个人身份信息,或者我们将这些信息进行汇总,以便它不会识别您个人。 + 2) 供应商、服务提供商和其他合作伙伴。我们会将您的个人信息(指可以识别您身份的信息,例如姓名、联系方式、邮箱地址、设备识别码等)发送给在全球范围内支持我们业务的供应商、服务提供商和其他合作伙伴,这些支持包括提供物流、配送或安装服务、技术基础设施服务、推送营销信息、分析我们服务的使用方式、衡量广告和服务的有效性、提供客户服务(包括提供线上渠道的客户服务)、支付便利或进行学术研究和调查等。对我们与之共享个人信息的公司、组织和个人,我们会与其签署严格的保密协议,要求他们按照我们的说明、本隐私政策以及其他任何相关的保密和安全措施来处理个人信息。 + 转让 + 我们不会将您的个人信息转让给任何公司、组织和个人,但以下情况除外: + 1.在获取明确同意的情况下转让:获得您的明确同意后,我们会向其他方转让您的个人信息; + 2.在涉及合并、收购或破产清算时,如涉及到个人信息转让,我们会要求新的持有您个人信息的公司、组织继续受此政策的约束,否则我们将要求该公司、组织重新向您征求授权同意。 + 公开披露 + 我们仅会在以下情况下,公开披露您的个人信息: + 1.获得您明确同意后。 + 2.基于法律的披露:在法律、法律程序、诉讼或政府主管部门强制性要求的情况下,我们可能会公开披露您的个人信息。 + 3.我们认为披露对检测、防止或以其他方式解决欺诈、安全或技术问题是合理必要的。 + 4.我们认为披露对按法律要求或允许的方式保护我们的用户或公众的权利、财产或安全是合理必要的。 + 您的个人信息将被如何保护? + 我们已使用符合业界标准的安全防护措施保护您提供的个人信息,防止数据遭到未经授权的访问、公开披露、使用、修改、损坏或丢失。我们会采取一切合理可行的措施,保护您的个人信息。 + 我们同时要求可能接触到您个人信息的所有人员履行相应的保密义务。如果未能履行这些义务,可能会被追究法律责任或被中止与我们的合作关系。 + + 我们仅在本政策所述目的所必需的期间和法律法规要求的时限内保留您的个人信息。如果当我们要将信息用于本政策未载明的其它用途时,会事先征求您的同意。 + 互联网并非绝对安全的环境,而且电子邮件、即时通讯、社交软件等与其他用户的交流方式无法确定是否完全加密,我们建议您使用此类工具时请使用复杂密码,并注意保护您的个人信息安全。 + 同时,我们将始终在管理、技术处理等过程中尽力确保信息安全,防止发生个人信息非法泄露,或在未经授权情况下被使用、披露、修改和删减。我们将致力于对您个人信息实施有效、得力的保护措施,使其免受各种可预见事故的危害。 + + 在不幸发生个人信息安全事件后,我们将按照法律法规的要求,及时向您告知:安全事件的基本情况和可能的影响、我们已采取或将要采取的处置措施、您可自主防范和降低风险的建议、对您的补救措施等。我们将及时将事件相关情况以邮件、信函、电话、推送通知等方式告知您,难以逐一告知个人信息主体时,我们会采取合理、有效的方式发布公告。 + 同时,我们还将按照监管部门要求,主动上报个人信息安全事件的处置情况。 + 您的权利 + 我们将采取适当的技术手段,保证您访问、更新、更正或删除您个人信息的权利,提供与您个人信息收集、使用、分享、存储等方面相关的多种选择。 + 访问权与更正权 + 作为荟聚中心的会员,您有权对错误或不完整的信息作出更正或更新,您可以访问您注册会员时所属荟聚中心的微信公众号,通过“荟聚会员”-“会员中心”进入“会员中心”,然后点击页面中的“完善资料”,即可访问并更新您的会员信息;同时,您可以通过微信公众号中提供的其他菜单,查看您在荟聚中心留存的其他信息及记录; + + 作为荟商在线系统的用户,您可登录您的系统账户,在任何时间修改或更正您的个人信息。如果您希望获得一份您的个人信息副本,您可在系统平台上提交服务请求来获得您的个人信息副本。 + + 如您在使用我们的产品与/或服务的过程中需访问或更正其他个人信息的,请根据“任何疑问”中所列的方式与我们联络。我们会根据本隐私政策所列明的方式和期限响应您的请求。但请注意,由于技术限制或安全性考虑,您的部分个人信息我们还无法为您提供访问和更正的服务。 + 删除权 + 如果我们违反法律法规或与您的约定收集、使用、与他人分享您的个人信息,您有权要求我们进行删除。 + 如您是荟商在线系统的用户,您可以通过登录系统账户选择删除您的账户。但请注意,如果您选择删除账户,您将无法访问可能对您在荟聚中心工作有关的重要信息。即使您删除了账户,我们可能仍会保留您在系统中的沟通信息和门禁卡信息。 + 您也可根据“任何疑问”部分所列的方式与我们联络要求删除个人信息。 + 撤销权 + 我们的每个业务功能需要一些基本的信息才能得以完成。您可以通过删除信息、关闭设备功能、在各地荟聚中心微信公众号的“会员中心”中更新隐私设置等方式来改变您授权我们继续收集个人信息的范围或撤回您的授权。您也可以通过注销账户的方式,撤回我们继续收集您个人信息的全部授权。对于我们额外收集的个人信息,您可以随时给予或收回您的授权同意。如果在此过程中,您需要任何帮助,可根据“任何疑问”部分所列的方式与我们联络。 + 注销权 + 您可注销您所注册的荟聚会员, 账户注销将会清除您的所有用户数据和账户信息且不可恢复,如果在您的账户下存在任何的虚拟资产(如账户余额、积分、绑定的礼品卡等),建议您在注销账户前使用完毕,账户删除后将无法恢复。您可根据本隐私政策“任何疑问”部分所列的方式与我们联络以申请冻结账户、注销,或获得更多详情。如您在申请账户冻结后需要重新开通账户,则需携带个人证件至您所在地区的荟聚中心的服务台进行人工办理。 + 但如果根据适用法律法规,我们必须收集、使用或分享您的信息,我们可以在适用法律、法规允许的范围内拒绝您的要求。我们有权根据适用法律法规的规定调整您的上述权利。 + 营销信息的退订 + 您可以选择是否接受我们、我们的关联企业或服务提供商通过电子邮件、短信、印刷材料等发送营销信息。您可以在各地荟聚中心微信公众号的“会员中心”中更新您的营销信息订阅偏好设置。此外,您还可通过这些信息中提供的退订机制退订这些信息(例如对于营销短信,可回复0退订; 对于营销电子邮件,可以通过邮件中的退订链接退订)。对于微信公众号中推送的营销信息,您可以通过微信中提供的公众号“接收文章推送”设置开关关闭推送。您也可以根据以下“任何疑问”部分所列的方式与我们联络,来更新营销信息的订阅选项。 + 响应您的上述请求 + 为保障安全,您可能需要提供书面请求,或以其他方式证明您的身份。我们可能会先要求您验证自己的身份, 然后再处理您的请求。我们将在15天内做出答复。 + 对于您合理的请求,我们原则上不收取费用,但对多次重复、超出合理限度的请求,我们将视情况收取一定成本费用。对于那些无端重复、需要过多技术手段(例如,需要开发新系统或从根本上改变现行惯例)、给他人合法权益带来风险或者非常不切实际的请求,我们可能会予以拒绝。 + 在以下情形中,按照法律法规要求,我们将无法响应您的请求: + 1.与国家安全、国防安全直接相关的; + 2.与公共安全、公共卫生、重大公共利益直接相关的; + 3.与犯罪侦查、起诉、审判和判决执行等直接相关的; + 4.有充分证据表明您存在主观恶意或滥用权利的; + 5.响应您的请求将导致您或其他个人、组织的合法权益受到严重损害的。 + 6.涉及商业秘密的。 + 我们如何处理未成年人的个人信息 + 英格卡购物中心中国不会主动向未满18周岁的未成年人收集个人信息。然而,我们在提供如荟聚宝贝儿童乐园等面向未成年人的服务时,我们会根据目的明确、最少够用的原则,在家长或监护人的明确同意下,直接从家长或监护人处收集未满18周岁未成年人的个人信息。 + 请您在使用我们的服务前,确保自己是成年人,或者在家长、监护人指导下使用我们的服务。家长、监护人在向我们提供未成年人信息前,请仔细阅读我们的隐私政策,以更好的呵护您的孩子。 + + 英格卡购物中心中国将不会向未成年人发送任何营销信息。如果我们发现自己在未事先获得可证实的未成年人的家长或监护人同意的情况下收集了未成年人的个人信息,我们会设法尽快删除相关信息。 + 您的个人信息如何在全球范围转移 + 原则上,我们在中华人民共和国境内收集和产生的个人信息,将存储在中华人民共和国境内。由于英格卡集团是一家跨国公司,基于集团运营和管理的需要,我们通过遍布全球的资源和服务器提供产品或服务,这意味着,在获得您的授权同意后,您的个人信息可能会被转移到您使用产品或服务所在国家/地区的境外管辖区,或者受到来自这些管辖区的访问。 + + 此类管辖区可能设有不同的数据保护法,甚至未设立相关法律。在此类情况下,我们会确保您的个人信息得到在中华人民共和国境内足够同等的保护。我们将始终在管理、技术处理等过程确保信息安全,防止您的个人信息受到各种可预见事故的危害。 + 本政策如何更新 + 我们可能会不定时修改本政策,以便及时反映国家法律法规的变化以及我们服务政策的调整。您继续使用我们的服务将视为您对本隐私政策相关调整的同意。 + 未经您明确同意,我们不会削减您按照本隐私政策所应享有的权利。对于重大变更,我们还会提供更为显著的通知。 + + 本政策所指的重大变更包括但不限于: + 1.我们的服务模式发生重大变化。如处理个人信息的目的、处理的个人信息类型、个人信息的使用方式等; + 2.我们在所有权结构、组织架构等方面发生重大变化。如业务调整、破产并购等引起的所有者变更等; + 3.个人信息共享、转让或公开披露的主要对象发生变化; + 4.您参与个人信息处理方面的权利及其行使方式发生重大变化; + 5.我们负责处理个人信息安全的责任部门、联络方式及投诉渠道发生变化时; + 6.个人信息安全影响评估报告表明存在高风险时。 + 我们还会将本政策的旧版本存档,供您查阅。 + 任何疑问 + 如果您对本政策或我们所拥有的与您相关的个人信息有任何疑问或不满,您可以通过以下方式联系您所在地区的荟聚中心或您服务的雇主所在的荟聚中心。一般情况下,我们将在15天内回复。 + 北京荟聚客服电话:+86 010-60285656 + 北京荟聚客服邮箱:family.bj@livat.cn + 武汉荟聚客服电话:+86 027-83395788 + 武汉荟聚客服邮箱: family.wh@livat.cn + 无锡荟聚客服电话:+86 0510-81167977 + 无锡荟聚客服邮箱: family.wx@livat.cn 长沙荟聚客服电话:+86 0731-85645818 + 长沙荟聚客服邮箱:family.cs@livat.cn + 福州荟聚客服电话:+86 0591-28485188 + 福州荟聚客服邮箱:family.fz@livat.cn 南宁荟聚客服电话:+86 0771-2066689 + 南宁荟聚客服邮箱:family.nn@livat.cn + 本隐私政策以中、英文两种文字书就,两种文本具有同等效力。如中英文文本有不一致之处,应以中文文本为准。 + 您同意因本政策引发的任何您和我们之间的纠纷(以下简称“纠纷”)均适用中华人民共和国法律,冲突规则除外。除非另有禁止,您同意由此引发的直接或间接产生的或与之相关的纠纷、索赔和诉讼均应由上海市徐汇区有管辖权的法院依照中华人民共和国法律解决。 + + \ No newline at end of file diff --git a/pages/privacy/index.wxss b/pages/privacy/index.wxss new file mode 100644 index 0000000..d761e65 --- /dev/null +++ b/pages/privacy/index.wxss @@ -0,0 +1,4 @@ +.content { + display: block; + padding: 20px; +} diff --git a/pages/prompt/bluetooth.png b/pages/prompt/bluetooth.png new file mode 100644 index 0000000..5b6bfca Binary files /dev/null and b/pages/prompt/bluetooth.png differ diff --git a/pages/prompt/elevator.png b/pages/prompt/elevator.png new file mode 100644 index 0000000..6831ba2 Binary files /dev/null and b/pages/prompt/elevator.png differ diff --git a/pages/prompt/end.png b/pages/prompt/end.png new file mode 100644 index 0000000..bc70f42 Binary files /dev/null and b/pages/prompt/end.png differ diff --git a/pages/prompt/escalator.png b/pages/prompt/escalator.png new file mode 100644 index 0000000..a79f045 Binary files /dev/null and b/pages/prompt/escalator.png differ diff --git a/pages/prompt/info.png b/pages/prompt/info.png new file mode 100644 index 0000000..2c80819 Binary files /dev/null and b/pages/prompt/info.png differ diff --git a/pages/prompt/mall.png b/pages/prompt/mall.png new file mode 100644 index 0000000..ec85112 Binary files /dev/null and b/pages/prompt/mall.png differ diff --git a/pages/prompt/park.png b/pages/prompt/park.png new file mode 100644 index 0000000..d928eb2 Binary files /dev/null and b/pages/prompt/park.png differ diff --git a/pages/prompt/prompt.js b/pages/prompt/prompt.js new file mode 100644 index 0000000..7a077f6 --- /dev/null +++ b/pages/prompt/prompt.js @@ -0,0 +1,34 @@ +import { promptIcons } from "../index/index-helper"; + +Component({ + /** + * 组件的属性列表 + */ + properties: { + icon: String, + title: String, + subTitle: String, + meta: String, + btn1: String, + btn2: String, + btn3: String, + }, + + /** + * 组件的初始数据 + */ + data: { + promptIcons, + }, + + /** + * 组件的方法列表 + */ + methods: { + handleTap({ currentTarget: { id } }) { + this.triggerEvent("btn", { + btn: id, + }); + }, + }, +}); diff --git a/pages/prompt/prompt.json b/pages/prompt/prompt.json new file mode 100644 index 0000000..a89ef4d --- /dev/null +++ b/pages/prompt/prompt.json @@ -0,0 +1,4 @@ +{ + "component": true, + "usingComponents": {} +} diff --git a/pages/prompt/prompt.wxml b/pages/prompt/prompt.wxml new file mode 100644 index 0000000..b8fa03b --- /dev/null +++ b/pages/prompt/prompt.wxml @@ -0,0 +1,10 @@ + + + {{title}} + {{subTitle}} + {{title}} + {{meta}} + {{btn1}} + {{btn2}} + {{btn3}} + \ No newline at end of file diff --git a/pages/prompt/prompt.wxss b/pages/prompt/prompt.wxss new file mode 100644 index 0000000..c1369fa --- /dev/null +++ b/pages/prompt/prompt.wxss @@ -0,0 +1,142 @@ +.prompt { + position: absolute; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + background: rgba(0, 0, 0, 80%); + z-index: 20 !important; + text-align: center; +} + +.prompt > .icon { + position: absolute; + width: 112px; + height: 112px; + left: 0; + right: 0; + top: calc(50vh - 112px - 40px - 17px); + margin: auto; +} + +.prompt > .title { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + margin: auto; + font-family: Noto IKEA Simplified Chinese; + font-style: normal; + font-weight: bold; + font-size: 24px; + line-height: 36px; + height: 36px; + text-align: center; + color: #eee9de; +} +.prompt > .title.top { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + margin: auto; + font-family: Noto IKEA Simplified Chinese; + font-style: normal; + font-weight: bold; + font-size: 24px; + line-height: 36px; + height: 36px; + text-align: center; + color: #eee9de; + transform: translateY(-36px); +} + +.prompt > .meta { + position: absolute; + left: 0; + right: 0; + top: calc(50vh + 17px + 8px); + margin: auto; + font-family: Noto IKEA Simplified Chinese; + font-style: normal; + font-weight: normal; + font-size: 14px; + line-height: 21px; + /* identical to box height */ + + text-align: center; + + /* Font color/中灰 */ + + color: #b3aea7; +} + +.prompt > .btn1 { + position: absolute; + height: 50px; + width: 180px; + left: 0; + right: 0; + top: calc(75vh - 10px - 50px); + margin: auto; + border-radius: 63px; + font-family: PingFang SC; + font-style: normal; + font-weight: 900; + font-size: 16px; + line-height: 50px; + text-align: center; + color: #333333; + background: #ffdb00; +} + +.prompt > .btn2 { + position: absolute; + height: 50px; + width: 180px; + left: 0; + right: 0; + top: calc(75vh + 10px); + margin: auto; + border: 1px solid #767571; + box-sizing: border-box; + border-radius: 63px; + font-style: normal; + font-weight: 900; + font-size: 16px; + line-height: 50px; + text-align: center; + color: #d1c8b9; +} + +.prompt > .btn3 { + position: absolute; + width: 56px; + height: 20px; + left: 0; + right: 0; + bottom: 66px; + margin: auto; + font-family: Noto IKEA Simplified Chinese; + font-style: normal; + font-weight: bold; + font-size: 14px; + line-height: 20px; + color: #eee9de; +} + +.prompt > .btn3::after { + display: block; + content: ""; + position: absolute; + bottom: -6px; + left: 0; + right: 0; + height: 2px; + width: 16px; + margin: auto; + background: #eee9de; + border-radius: 20px; +} diff --git a/pages/prompt/question.png b/pages/prompt/question.png new file mode 100644 index 0000000..22e2797 Binary files /dev/null and b/pages/prompt/question.png differ diff --git a/pages/prompt/tomap.png b/pages/prompt/tomap.png new file mode 100644 index 0000000..0d1b23c Binary files /dev/null and b/pages/prompt/tomap.png differ diff --git a/pages/tabs/relocate.png b/pages/tabs/relocate.png new file mode 100644 index 0000000..749cce1 Binary files /dev/null and b/pages/tabs/relocate.png differ diff --git a/pages/tabs/tabs.js b/pages/tabs/tabs.js new file mode 100644 index 0000000..64686ce --- /dev/null +++ b/pages/tabs/tabs.js @@ -0,0 +1,32 @@ +// pages/tabs/tabs.js +Component({ + /** + * 组件的属性列表 + */ + properties: { + tab: Number, + floor: String, + }, + + /** + * 组件的初始数据 + */ + data: { + tabs: ["平面地图", "导航", "目的地"], + }, + + /** + * 组件的方法列表 + */ + methods: { + handleTap({ currentTarget: { id } }) { + this.triggerEvent("change", Number(id)); + }, + handleRelocate() { + this.triggerEvent("relocate"); + }, + handleToMap() { + this.triggerEvent("tomap"); + }, + }, +}); diff --git a/pages/tabs/tabs.json b/pages/tabs/tabs.json new file mode 100644 index 0000000..a89ef4d --- /dev/null +++ b/pages/tabs/tabs.json @@ -0,0 +1,4 @@ +{ + "component": true, + "usingComponents": {} +} diff --git a/pages/tabs/tabs.wxml b/pages/tabs/tabs.wxml new file mode 100644 index 0000000..c730484 --- /dev/null +++ b/pages/tabs/tabs.wxml @@ -0,0 +1,14 @@ + + + {{item}} + + + + + + + + 当前楼层 + {{floor}} + +请按照导航路线行走 \ No newline at end of file diff --git a/pages/tabs/tabs.wxss b/pages/tabs/tabs.wxss new file mode 100644 index 0000000..f4db58f --- /dev/null +++ b/pages/tabs/tabs.wxss @@ -0,0 +1,105 @@ +.tabs { + position: fixed; + display: flex; + bottom: 0; + left: 0; + right: 0; + height: 83px; + z-index: 15 !important; + background: #ffffff; + padding-top: 9px; + box-shadow: 0px -2px 10px rgba(220, 183, 123, 0.3); +} + +.tabs > .tab { + flex: 1; + height: 50px; + text-align: center; +} + +.tabs > .tab > .btn { + width: 76px; + height: 32px; + margin: auto; + border-radius: 64px; + font-style: normal; + font-weight: 900; + font-size: 14px; + line-height: 32px; + text-align: center; + color: #6a6665; +} + +.tabs > .tab > .btn.active { + background: #ffdb00; +} + +.relocate { + position: fixed; + z-index: 15 !important; + right: 4px; + width: 46px; + height: 46px; + bottom: 235px; +} + +.relocate.high { + bottom: 362px; +} + +.floor { + display: inline-flex; + z-index: 15 !important; + position: fixed; + left: 8px; + bottom: 211px; + height: 24px; + padding: 0 12px; + font-style: normal; + font-weight: normal; + font-size: 12px; + line-height: 24px; + color: #6a6665; + background: #fff; + border-radius: 24px; + align-content: center; + justify-content: center; + align-items: center; +} +.floor.high { + bottom: 338px; +} + +.floor > .sep { + height: 12px; + width: 1px; + margin: 0 8px; + background: #e2e1df; +} + +.floor > .value { + font-size: 14px; + color: #ef9617; +} +.tip { + display: inline-flex; + z-index: 15 !important; + position: fixed; + right: 8px; + bottom: 211px; + padding: 0 10px; + height: 25px; + line-height: 25px; + background: #f37b6f; + backdrop-filter: blur(2px); + border-radius: 50px; + font-family: PingFang SC; + font-style: normal; + font-weight: bold; + font-size: 12px; + color: #ffffff; +} + +.tip.high { + bottom: 338px; +} diff --git a/project.config.json b/project.config.json new file mode 100644 index 0000000..94cb990 --- /dev/null +++ b/project.config.json @@ -0,0 +1,54 @@ +{ + "description": "项目配置文件,详见文档:https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html", + "cloudfunctionRoot": "cloudfunctions/", + "setting": { + "urlCheck": true, + "es6": false, + "enhance": true, + "postcss": true, + "preloadBackgroundData": false, + "minified": true, + "newFeature": false, + "coverView": true, + "nodeModules": false, + "autoAudits": false, + "showShadowRootInWxmlPanel": true, + "scopeDataCheck": false, + "uglifyFileName": false, + "checkInvalidKey": true, + "checkSiteMap": true, + "uploadWithSourceMap": true, + "compileHotReLoad": false, + "lazyloadPlaceholderEnable": false, + "useMultiFrameRuntime": true, + "babelSetting": { + "ignore": [], + "disablePlugins": [], + "outputPath": "" + }, + "useIsolateContext": true, + "userConfirmedBundleSwitch": false, + "packNpmManually": false, + "packNpmRelationList": [], + "minifyWXSS": true, + "disableUseStrict": false, + "minifyWXML": true, + "showES6CompileOption": false, + "useCompilerPlugins": false, + "ignoreUploadUnusedFiles": true, + "useStaticServer": true + }, + "compileType": "miniprogram", + "condition": {}, + "editorSetting": { + "tabIndent": "insertSpaces", + "tabSize": 4 + }, + "libVersion": "2.24.3", + "packOptions": { + "ignore": [], + "include": [] + }, + "appid": "wx5a07c26e8c297c6c", + "projectname": "无锡荟聚" +} \ No newline at end of file diff --git a/project.private.config.json b/project.private.config.json new file mode 100644 index 0000000..c1547a6 --- /dev/null +++ b/project.private.config.json @@ -0,0 +1,8 @@ +{ + "setting": { + "compileHotReLoad": true + }, + "condition": {}, + "description": "项目私有配置文件。此文件中的内容将覆盖 project.config.json 中的相同字段。项目的改动优先同步到此文件中。详见文档:https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html", + "projectname": "%E6%97%A0%E9%94%A1%E8%8D%9F%E8%81%9A" +} \ No newline at end of file diff --git a/sitemap.json b/sitemap.json new file mode 100644 index 0000000..ca02add --- /dev/null +++ b/sitemap.json @@ -0,0 +1,7 @@ +{ + "desc": "关于本文件的更多信息,请参考文档 https://developers.weixin.qq.com/miniprogram/dev/framework/sitemap.html", + "rules": [{ + "action": "allow", + "page": "*" + }] +} \ No newline at end of file diff --git a/utils/util.js b/utils/util.js new file mode 100644 index 0000000..061f235 --- /dev/null +++ b/utils/util.js @@ -0,0 +1,25 @@ +const formatTime = (date) => { + const year = date.getFullYear(); + const month = date.getMonth() + 1; + const day = date.getDate(); + const hour = date.getHours(); + const minute = date.getMinutes(); + const second = date.getSeconds(); + + return `${[year, month, day].map(formatNumber).join("/")} ${[ + hour, + minute, + second, + ] + .map(formatNumber) + .join(":")}`; +}; + +const formatNumber = (n) => { + n = n.toString(); + return n[1] ? n : `0${n}`; +}; + +module.exports = { + formatTime, +}; diff --git a/wasm/module_basic.wasm b/wasm/module_basic.wasm new file mode 100644 index 0000000..d5f9375 Binary files /dev/null and b/wasm/module_basic.wasm differ