repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/nature/action-types.ts
<reponame>CN-3211/vt-cesium2.0<gh_stars>0 export enum NatureActionTypes { RESET_STATE = 'RESET_STATE', // nature SWITCH_SHOW_SUN = 'SWITCH_SHOW_SUN', SWITCH_SHOW_MOON = 'SWITCH_SHOW_MOON', SWITCH_SHOW_SKY_ATMOSPHERE = 'SWITCH_SHOW_SKY_ATMOSPHERE', SWITCH_ENABLE_LIGHT = 'SWITCH_ENABLE_LIGHT', SWITCH_SHOW_SKY_BOX = 'SWITCH_SHOW_SKY_BOX', SWITCH_SHOW_SHADOW = 'SWITCH_SHOW_SHADOW', }
CN-3211/vt-cesium2.0
src/libs/cesium/cesium-vue.ts
import { App } from 'vue' export type CesiumRef = import('@/@types/shims-cesium-ref').CesiumRef export const CESIUM_REF_KEY = Symbol('cesiumRef') declare module '@vue/runtime-core' { interface ComponentCustomProperties { readonly $cesiumRef: CesiumRef readonly cesiumRef: CesiumRef } } export default { install: function (app: App<Element>): void { const cr: CesiumRef = { viewer: undefined, viewerContainer: undefined, } app.config.globalProperties.$cesiumRef = cr app.provide<CesiumRef>(CESIUM_REF_KEY, cr) }, }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/other/mutation-types.ts
export enum OtherMutationTypes { RESET_STATE = 'RESET_STATE', // other SET_DEPTH_TEST_AGAINST_TERRAIN = 'SET_DEPTH_TEST_AGAINST_TERRAIN', }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/locationbar/mutations.ts
/* * @Date: 2022-03-30 16:34:56 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-02 10:47:57 * @FilePath: /vt-cesium2.0/src/store/modules/jt-cesium-vue/modules/locationbar/mutations.ts */ import { MutationTree } from 'vuex' import { defaultState } from './state' import type { State } from './state' import { LocationbarHandlerEnum } from './enum-constant' export const mutations: MutationTree<State> = { [LocationbarHandlerEnum.RESET_STATE](state: State) { Object.assign(state, defaultState()) }, [LocationbarHandlerEnum.SET_SHOW_CAMERA_LOCATION]( state: State, payload: boolean ) { state.showCameraLocation = payload }, [LocationbarHandlerEnum.SET_SHOW_MOUSE_LOCATION]( state: State, payload: boolean ) { state.showMouseLocation = payload }, [LocationbarHandlerEnum.SET_SHOW_FPS](state: State, payload: boolean) { state.showFPS = payload }, }
CN-3211/vt-cesium2.0
src/components/jt-toolbar/dropdown/index.ts
<filename>src/components/jt-toolbar/dropdown/index.ts /* * @Date: 2022-03-31 21:01:56 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-12 10:10:06 * @FilePath: /vt-cesium2.0/src/components/jt-toolbar/dropdown/index.ts */ import CameraPercentageChangeRate from './camera-percentage-change-rate/index.vue' import SelectViewMode from './select-view-mode/index.vue' import EarthLightSetting from './earth-light-setting/index.vue' // import earthSurfaceColorPicker from './earth-surface-color-picker/index.vue' // import elevationContourSetting from './elevation-contour-setting/index.vue' // import imagerySplitPosition from './imagery-split-position/index.vue' export default { CameraPercentageChangeRate, SelectViewMode, EarthLightSetting, // earthSurfaceColorPicker, // elevationContourSetting, // imagerySplitPosition, }
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/view/groups/view/index.ts
/* * @Date: 2022-03-30 15:49:30 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-06 15:28:29 * @FilePath: /vt-cesium2.0/src/components/jt-toolbar/config/contents/view/groups/view/index.ts */ import { Group, ClickHandlerOption } from '../../../Types' import { LayoutHandlerEnum } from '@/store/modules/jt-cesium-vue/modules/layout/enum-constant' const view: Group = { name: '视图', items: [ { name: '切换视图', icon: 'view-lp', dropdownOnClick: true, dropdown: { componentName: 'select-view-mode', }, }, { name: '相机设置', icon: 'setting-config', clickHandler: (option: ClickHandlerOption): void => { option.store.dispatch( `jtCesiumVue/layout/${LayoutHandlerEnum.ADD_UNIQUE_NAME_OVERLAY_DYNAMIC_VIEW_BY_NAME}`, 'jt-camera-setting' ) }, }, { name: '范围限制', icon: 'rectangle', clickHandler: (option: ClickHandlerOption): void => { option.store.dispatch( `jtCesiumVue/layout/${LayoutHandlerEnum.ADD_UNIQUE_NAME_OVERLAY_DYNAMIC_VIEW_BY_NAME}`, 'jt-cartographic-limit-rectangle' ) }, }, ], invisible: false, disable: false, } export default view
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/imagery/mutation-types.ts
<reponame>CN-3211/vt-cesium2.0 export enum ImageryMutationTypes { RESET_STATE = 'RESET_STATE', // imagery SET_SPLIT = 'SET_SPLIT', }
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/index.ts
<filename>src/components/jt-toolbar/config/contents/index.ts /* * @Date: 2022-03-30 15:49:30 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-08 09:48:33 * @FilePath: /vt-cesium2.0/src/components/jt-toolbar/config/contents/index.ts */ import view from './view' import effect from './effect'; import tool from './tool' import { Content } from './Types' const contents: Array<Content> = [ view, effect, tool ] export default contents
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/other/mutations.ts
<filename>src/store/modules/jt-cesium-vue/modules/toolbar/modules/other/mutations.ts import { MutationTree } from 'vuex' import { defaultState } from './state' import type { OtherState } from './state' import { OtherMutationTypes } from './mutation-types' export const mutations: MutationTree<OtherState> = { [OtherMutationTypes.RESET_STATE](state: OtherState) { Object.assign(state, defaultState()) }, // other [OtherMutationTypes.SET_DEPTH_TEST_AGAINST_TERRAIN]( state: OtherState, payload: boolean ) { state.depthTestAgainstTerrain = payload }, }
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/effect/index.ts
/* * @Date: 2022-04-08 09:44:21 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-08 09:47:28 * @FilePath: /vt-cesium2.0/src/components/jt-toolbar/config/contents/effect/index.ts */ import { Content } from '../Types' import groups from './groups' const content: Content = { name: '效果', groups, } export default content
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/mutations.ts
/* * @Date: 2022-03-30 16:34:56 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-02 10:40:43 * @FilePath: /vt-cesium2.0/src/store/modules/jt-cesium-vue/modules/toolbar/mutations.ts */ import { MutationTree } from 'vuex' import { defaultState } from './state' import type { TerrainSamplingState, State, DropdownState } from './state' import { ToolbarHandlerEnum } from './enum-constant' export const mutations: MutationTree<State> = { [ToolbarHandlerEnum.RESET_STATE](state: State) { Object.assign(state, defaultState()) }, [ToolbarHandlerEnum.SET_VISIBLE](state: State, payload: boolean) { state.visible = payload }, [ToolbarHandlerEnum.SET_DROP_DOWN](state: State, payload: DropdownState) { state.dropdown = payload }, [ToolbarHandlerEnum.SET_DROP_DOWN](state: State, payload: DropdownState) { state.dropdown = payload }, // elevation contour [ToolbarHandlerEnum.SET_ELEVATION_CONTURE_ACTIVE]( state: State, payload: boolean ) { state.elevationContourActive = payload }, // terrain sampling [ToolbarHandlerEnum.SET_TERRAIN_SAMPLING]( state: State, payload: TerrainSamplingState ) { state.terrainSampling = payload }, }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/tool3DTile/mutations.ts
<filename>src/store/modules/jt-cesium-vue/modules/toolbar/modules/tool3DTile/mutations.ts import { MutationTree } from 'vuex' import { defaultState } from './state' import type { Tool3DTileState } from './state' import { Tool3DTileMutationTypes } from './mutation-types' export const mutations: MutationTree<Tool3DTileState> = { [Tool3DTileMutationTypes.RESET_STATE](state: Tool3DTileState) { Object.assign(state, defaultState()) }, // tool3dtile [Tool3DTileMutationTypes.SET_HIGHLIGHT_3DTILE_FEATURE_ACTIVE]( state: Tool3DTileState, payload: boolean ) { state.highlight3DTileFeatureActive = payload }, [Tool3DTileMutationTypes.SET_HOVER_CLASSIFICATION_ACTIVE]( state: Tool3DTileState, payload: boolean ) { state.hoverClassificationActive = payload }, [Tool3DTileMutationTypes.SET_CLICK_CLASSIFICATION_ACTIVE]( state: Tool3DTileState, payload: boolean ) { state.clickClassificationActive = payload }, }
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/view/index.ts
<gh_stars>0 /* * @Date: 2022-03-30 15:49:30 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-30 16:55:22 * @FilePath: /vt-cesium2.0/src/components/jt-toolbar/config/contents/view/index.ts */ import { Content } from '../Types' import groups from './groups' const content: Content = { name: '视图', groups, } export default content
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/imagery/action-types.ts
<gh_stars>0 export enum ImageryActionTypes { RESET_STATE = 'RESET_STATE', // imagery SET_SPLIT = 'SET_SPLIT', }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/other/state.ts
export type OtherState = { depthTestAgainstTerrain: boolean } export const defaultState = (): OtherState => { return { depthTestAgainstTerrain: true, } } export const state: OtherState = defaultState()
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/imagery/mutations.ts
<reponame>CN-3211/vt-cesium2.0 import { MutationTree } from 'vuex' import { defaultState } from './state' import type { ImageryState, SplitType } from './state' import { ImageryMutationTypes } from './mutation-types' export const mutations: MutationTree<ImageryState> = { [ImageryMutationTypes.RESET_STATE](state: ImageryState) { Object.assign(state, defaultState()) }, // imagery [ImageryMutationTypes.SET_SPLIT](state: ImageryState, payload: SplitType) { state.split = payload }, }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/nature/actions.ts
<reponame>CN-3211/vt-cesium2.0 import { ActionTree } from 'vuex' import { RootState } from '@/store' import type { NatureState } from './state' import { NatureMutationTypes } from './mutation-types' import { NatureActionTypes } from './action-types' import { ClickHandlerOption } from '@/components/jt-toolbar/config/contents/Types' import * as Cesium from 'cesium' export const actions: ActionTree<NatureState, RootState> = { async [NatureActionTypes.RESET_STATE]({ commit }) { commit(NatureMutationTypes.RESET_STATE) }, // nature async [NatureActionTypes.SWITCH_SHOW_SUN]( { commit, state }, options: ClickHandlerOption ) { const { viewer } = options if (!viewer) { return } if (!viewer.scene.sun) { viewer.scene.sun = new Cesium.Sun() } const switchTo = !state.showSun viewer.scene.sun.show = switchTo commit(NatureMutationTypes.SET_SHOW_SUN, switchTo) }, async [NatureActionTypes.SWITCH_SHOW_MOON]( { commit, state }, options: ClickHandlerOption ) { const { viewer } = options if (!viewer) { return } if (!viewer.scene.moon) { viewer.scene.moon = new Cesium.Moon() } const switchTo = !state.showMoon viewer.scene.moon.show = switchTo commit(NatureMutationTypes.SET_SHOW_MOON, switchTo) }, async [NatureActionTypes.SWITCH_SHOW_SKY_ATMOSPHERE]( { commit, state }, options: ClickHandlerOption ) { const { viewer } = options if (!viewer) { return } if (!viewer.scene.skyAtmosphere) { viewer.scene.skyAtmosphere = new Cesium.SkyAtmosphere() } const switchTo = !state.showSkyAtmosphere viewer.scene.skyAtmosphere.show = switchTo commit(NatureMutationTypes.SET_SHOW_SKY_ATMOSPHERE, switchTo) }, async [NatureActionTypes.SWITCH_ENABLE_LIGHT]( { commit, state }, options: ClickHandlerOption ) { const { viewer } = options if (!viewer) { return } const switchTo = !state.enableLighting viewer.scene.globe.enableLighting = switchTo commit(NatureMutationTypes.SET_ENABLE_LIGHT, switchTo) }, async [NatureActionTypes.SWITCH_SHOW_SKY_BOX]( { commit, state }, options: ClickHandlerOption ) { const { viewer } = options if (!viewer) { return } // if (!viewer.scene.skyBox) { // viewer.scene.skyBox = new Cesium.SkyBox() // } const switchTo = !state.showSkyBox viewer.scene.skyBox.show = switchTo commit(NatureMutationTypes.SET_SHOW_SKY_BOX, switchTo) }, async [NatureActionTypes.SWITCH_SHOW_SHADOW]( { commit, state }, options: ClickHandlerOption ) { const { viewer } = options if (!viewer) { return } const switchTo = !state.showShadow viewer.shadows = switchTo if (switchTo) { viewer.terrainShadows = Cesium.ShadowMode.ENABLED } else { viewer.terrainShadows = Cesium.ShadowMode.RECEIVE_ONLY } commit(NatureMutationTypes.SET_SHOW_SHADOW, switchTo) }, }
CN-3211/vt-cesium2.0
src/store/modules/template/mutations.ts
import { MutationTree } from 'vuex' import { defaultState } from './state' import type { State } from './state' import { TemplateMutationTypes } from './mutation-types' export const mutations: MutationTree<State> = { [TemplateMutationTypes.RESET_STATE](state: State) { Object.assign(state, defaultState()) }, }
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/index.ts
/* * @Date: 2022-03-30 15:45:26 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-30 16:40:01 * @FilePath: /vt-cesium2.0/src/components/jt-toolbar/config/index.ts */ import contents from './contents' export default contents
CN-3211/vt-cesium2.0
src/libs/cesium/libs/viewshed/Viewshed.ts
<gh_stars>0 import { Viewer, Camera, Math as CesiumMath, PerspectiveFrustum, OrthographicFrustum, ShadowMap, Color, PostProcessStage, PostProcessStageComposite, Cartesian2, Cartesian3, Cartesian4, Matrix3, Matrix4, Quaternion, GeometryInstance, FrustumOutlineGeometry, ColorGeometryInstanceAttribute, ShowGeometryInstanceAttribute, PerInstanceColorAppearance, Primitive, Entity, Transforms, HeadingPitchRoll, CallbackProperty, ConstantProperty, } from 'cesium' import glsl from './glsl' export type Option = { // 观察点位置 viewPosition: Cartesian3 // 观察距离(米,默认100) viewDistance?: number // 水平夹角(度,默认90) horizontalViewAngle?: number // 垂直夹角(度,默认60) verticalViewAngle?: number // 航向角(度,默认0) viewHeading?: number // 俯仰角(度,默认0) viewPitch?: number // 可视区颜色(默认绿色) visibleAreaColor?: Color // 不可视区颜色(默认红色) invisibleAreaColor?: Color // 阴影贴图是否可用 enabled?: boolean // 柔和阴影是否可用 softShadows?: boolean // 每个阴影贴图的大小(默认2048) size?: number } class Viewshed { private viewer: Viewer // option private viewPosition!: Cartesian3 private viewDistance!: number private horizontalViewAngle!: number private verticalViewAngle!: number private viewHeading!: number private viewPitch!: number private visibleAreaColor!: Color private invisibleAreaColor!: Color private enabled!: boolean private softShadows!: boolean private size!: number private lightCamera!: Camera private shadowMap!: ShadowMap private postStage!: PostProcessStage | PostProcessStageComposite | null private frustumOutline!: Primitive | null private sketch!: Entity | null constructor(viewer: Viewer) { this.viewer = viewer } public start({ viewPosition, viewDistance = 500, horizontalViewAngle = 90, verticalViewAngle = 60, viewHeading = 0, viewPitch = 0, visibleAreaColor = Color.GREEN, invisibleAreaColor = Color.RED, enabled = true, softShadows = true, size = 2048, }: Option): void { this.viewPosition = viewPosition this.viewDistance = viewDistance this.horizontalViewAngle = horizontalViewAngle this.verticalViewAngle = verticalViewAngle this.viewHeading = viewHeading this.viewPitch = viewPitch this.visibleAreaColor = visibleAreaColor this.invisibleAreaColor = invisibleAreaColor this.enabled = enabled this.softShadows = softShadows this.size = size this.update() } public add(): void { this.lightCamera = this.createLightCamera() this.shadowMap = this.createShadowMap() this.viewer.scene.shadowMap = this.shadowMap const postStage = this.createPostStage() this.postStage = this.viewer.scene.postProcessStages.add(postStage) const frustumOutline = this.drawFrustumOutline() this.frustumOutline = this.viewer.scene.primitives.add(frustumOutline) const sketch = this.drawSketch() this.sketch = this.viewer.entities.add(sketch) } public update(): void { this.clear() this.add() } public clear(): void { if (this.sketch) { this.viewer.entities.removeById(this.sketch.id) this.sketch = null } if (this.frustumOutline) { this.viewer.scene.primitives.remove(this.frustumOutline) !this.frustumOutline.isDestroyed && this.frustumOutline.destroy() this.frustumOutline = null } if (this.postStage) { this.viewer.scene.postProcessStages.remove(this.postStage) this.postStage = null } } // 创建相机 private createLightCamera(): Camera { const camera = new Camera(this.viewer.scene) camera.position = this.viewPosition // if (this.viewPositionEnd) { // let direction = Cesium.Cartesian3.normalize(Cesium.Cartesian3.subtract(this.viewPositionEnd, this.viewPosition, new Cesium.Cartesian3()), new Cesium.Cartesian3()); // this.lightCamera.direction = direction; // direction是相机面向的方向 // } camera.frustum.near = this.viewDistance * 0.001 camera.frustum.far = this.viewDistance const hr = CesiumMath.toRadians(this.horizontalViewAngle) const vr = CesiumMath.toRadians(this.verticalViewAngle) const aspectRatio = (this.viewDistance * Math.tan(hr / 2) * 2) / (this.viewDistance * Math.tan(vr / 2) * 2) const frustum = camera.frustum as PerspectiveFrustum frustum.aspectRatio = aspectRatio frustum.fov = hr > vr ? hr : vr camera.setView({ destination: this.viewPosition, orientation: { heading: CesiumMath.toRadians(this.viewHeading || 0), pitch: CesiumMath.toRadians(this.viewPitch || 0), roll: 0, }, }) return camera } // 创建Shadow map private createShadowMap(): ShadowMap { // Cesium ShadowMap 参数类型声明错误,只能转any const shadowMap = new (ShadowMap as any)({ context: (this.viewer.scene as any).context, lightCamera: this.lightCamera, enabled: this.enabled, isPointLight: true, pointLightRadius: this.viewDistance, cascadesEnabled: false, size: this.size, softShadows: this.softShadows, normalOffset: false, fromLightSource: false, }) return shadowMap } // 创建PostStage private createPostStage(): PostProcessStage { const fs = glsl const postStage = new PostProcessStage({ fragmentShader: fs, uniforms: { shadowMap_textureCube: () => { ;(this.shadowMap as any).update( Reflect.get(this.viewer.scene, '_frameState') ) return Reflect.get(this.shadowMap, '_shadowMapTexture') }, shadowMap_matrix: () => { ;(this.shadowMap as any).update( Reflect.get(this.viewer.scene, '_frameState') ) return Reflect.get(this.shadowMap, '_shadowMapMatrix') }, shadowMap_lightPositionEC: () => { ;(this.shadowMap as any).update( Reflect.get(this.viewer.scene, '_frameState') ) return Reflect.get(this.shadowMap, '_lightPositionEC') }, shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness: () => { ;(this.shadowMap as any).update( Reflect.get(this.viewer.scene, '_frameState') ) const bias = (this.shadowMap as any)._pointBias return Cartesian4.fromElements( bias.normalOffsetScale, (this.shadowMap as any)._distance, this.shadowMap.maximumDistance, 0.0, new Cartesian4() ) }, shadowMap_texelSizeDepthBiasAndNormalShadingSmooth: () => { ;(this.shadowMap as any).update( Reflect.get(this.viewer.scene, '_frameState') ) const bias = (this.shadowMap as any)._pointBias const scratchTexelStepSize = new Cartesian2() const texelStepSize = scratchTexelStepSize texelStepSize.x = 1.0 / (this.shadowMap as any)._textureSize.x texelStepSize.y = 1.0 / (this.shadowMap as any)._textureSize.y return Cartesian4.fromElements( texelStepSize.x, texelStepSize.y, bias.depthBias, bias.normalShadingSmooth, new Cartesian4() ) }, camera_projection_matrix: this.lightCamera.frustum.projectionMatrix, camera_view_matrix: this.lightCamera.viewMatrix, helsing_viewDistance: () => { return this.viewDistance }, helsing_visibleAreaColor: this.visibleAreaColor, helsing_invisibleAreaColor: this.invisibleAreaColor, }, }) return postStage } // 创建视锥线 private drawFrustumOutline(): Primitive { const scratchRight = new Cartesian3() const scratchRotation = new Matrix3() const scratchOrientation = new Quaternion() // const position = this.lightCamera.positionWC const direction = this.lightCamera.directionWC const up = this.lightCamera.upWC let right = this.lightCamera.rightWC right = Cartesian3.negate(right, scratchRight) const rotation = scratchRotation Matrix3.setColumn(rotation, 0, right, rotation) Matrix3.setColumn(rotation, 1, up, rotation) Matrix3.setColumn(rotation, 2, direction, rotation) const orientation = Quaternion.fromRotationMatrix( rotation, scratchOrientation ) const instance = new GeometryInstance({ geometry: new FrustumOutlineGeometry({ frustum: this.lightCamera.frustum as PerspectiveFrustum, origin: this.viewPosition, orientation: orientation, }), id: Math.random().toString(36).substring(2), attributes: { color: ColorGeometryInstanceAttribute.fromColor(Color.YELLOWGREEN), show: new ShowGeometryInstanceAttribute(true), }, }) const frustumOutline = new Primitive({ geometryInstances: [instance], appearance: new PerInstanceColorAppearance({ flat: true, translucent: false, }), }) return frustumOutline } // 创建视网 private drawSketch(): Entity | Entity.ConstructorOptions { const halfHorizontalAngle = this.horizontalViewAngle / 2 const halfVerticalAngle = this.verticalViewAngle / 2 const entity = { name: 'sketch', position: this.viewPosition, orientation: new ConstantProperty( Transforms.headingPitchRollQuaternion( this.viewPosition, HeadingPitchRoll.fromDegrees( this.viewHeading - this.horizontalViewAngle, this.viewPitch, 0.0 ) ) ), ellipsoid: { radii: new Cartesian3( this.viewDistance, this.viewDistance, this.viewDistance ), // innerRadii: new Cesium.Cartesian3(2.0, 2.0, 2.0), minimumClock: CesiumMath.toRadians(-halfHorizontalAngle), maximumClock: CesiumMath.toRadians(halfHorizontalAngle), minimumCone: CesiumMath.toRadians(90 - halfVerticalAngle), maximumCone: CesiumMath.toRadians(90 + halfVerticalAngle), fill: false, outline: true, subdivisions: 256, stackPartitions: 64, slicePartitions: 64, outlineColor: Color.YELLOWGREEN, }, } return entity } // 获得偏航角 private getHeading(fromPosition: Cartesian3, toPosition: Cartesian3) { const finalPosition = new Cartesian3() const matrix4 = Transforms.eastNorthUpToFixedFrame(fromPosition) Matrix4.inverse(matrix4, matrix4) Matrix4.multiplyByPoint(matrix4, toPosition, finalPosition) Cartesian3.normalize(finalPosition, finalPosition) return CesiumMath.toDegrees(Math.atan2(finalPosition.x, finalPosition.y)) } // 获得俯仰角 private getPitch(fromPosition: Cartesian3, toPosition: Cartesian3) { const finalPosition = new Cartesian3() const matrix4 = Transforms.eastNorthUpToFixedFrame(fromPosition) Matrix4.inverse(matrix4, matrix4) Matrix4.multiplyByPoint(matrix4, toPosition, finalPosition) Cartesian3.normalize(finalPosition, finalPosition) return CesiumMath.toDegrees(Math.asin(finalPosition.z)) } } export default Viewshed
CN-3211/vt-cesium2.0
src/libs/utils/CoordinateTransform.ts
class CoordinateTransform { // 定义一些常量 // eslint-disable-next-line @typescript-eslint/no-loss-of-precision public static x_PI = (3.14159265358979324 * 3000.0) / 180.0 // eslint-disable-next-line @typescript-eslint/no-loss-of-precision public static PI = 3.1415926535897932384626 public static a = 6378245.0 // eslint-disable-next-line @typescript-eslint/no-loss-of-precision public static ee = 0.00669342162296594323 public static bd09togcj02(bd_lng: number, bd_lat: number): [number, number] { const { x_PI } = CoordinateTransform const x = bd_lng - 0.0065 const y = bd_lat - 0.006 const z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_PI) const theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_PI) const gg_lng = z * Math.cos(theta) const gg_lat = z * Math.sin(theta) return [gg_lng, gg_lat] } public static gcj02tobd09(lng: number, lat: number): [number, number] { const { x_PI } = CoordinateTransform const z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI) const theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI) const bd_lng = z * Math.cos(theta) + 0.0065 const bd_lat = z * Math.sin(theta) + 0.006 return [bd_lng, bd_lat] } public static wgs84togcj02(lng: number, lat: number): [number, number] { const { PI, a, ee, out_of_china, transformlat, transformlng } = CoordinateTransform if (out_of_china(lng, lat)) { return [lng, lat] } else { let dlat = transformlat(lng - 105.0, lat - 35.0) let dlng = transformlng(lng - 105.0, lat - 35.0) const radlat = (lat / 180.0) * PI let magic = Math.sin(radlat) magic = 1 - ee * magic * magic const sqrtmagic = Math.sqrt(magic) dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI) dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI) const mglat = lat + dlat const mglng = lng + dlng return [mglng, mglat] } } public static gcj02towgs84(lng: number, lat: number): [number, number] { const { PI, a, ee, out_of_china, transformlat, transformlng } = CoordinateTransform if (out_of_china(lng, lat)) { return [lng, lat] } else { let dlat = transformlat(lng - 105.0, lat - 35.0) let dlng = transformlng(lng - 105.0, lat - 35.0) const radlat = (lat / 180.0) * PI let magic = Math.sin(radlat) magic = 1 - ee * magic * magic const sqrtmagic = Math.sqrt(magic) dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI) dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI) const mglat = lat + dlat const mglng = lng + dlng return [lng * 2 - mglng, lat * 2 - mglat] } } public static transformlat(lng: number, lat: number): number { const { PI } = CoordinateTransform let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng)) ret += ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0) / 3.0 ret += ((20.0 * Math.sin(lat * PI) + 40.0 * Math.sin((lat / 3.0) * PI)) * 2.0) / 3.0 ret += ((160.0 * Math.sin((lat / 12.0) * PI) + 320 * Math.sin((lat * PI) / 30.0)) * 2.0) / 3.0 return ret } public static transformlng(lng: number, lat: number): number { const { PI } = CoordinateTransform let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng)) ret += ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0) / 3.0 ret += ((20.0 * Math.sin(lng * PI) + 40.0 * Math.sin((lng / 3.0) * PI)) * 2.0) / 3.0 ret += ((150.0 * Math.sin((lng / 12.0) * PI) + 300.0 * Math.sin((lng / 30.0) * PI)) * 2.0) / 3.0 return ret } public static out_of_china(lng: number, lat: number): boolean { // 纬度 3.86~53.55, 经度 73.66~135.05 return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55) } } export default CoordinateTransform
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/cesium-data/getter-types.ts
<filename>src/store/modules/jt-cesium-vue/modules/cesium-data/getter-types.ts export enum CesiumDataGetterTypes {}
CN-3211/vt-cesium2.0
src/libs/cesium/libs/draw/Draw.ts
<reponame>CN-3211/vt-cesium2.0 import { Viewer, Color, HeightReference, Cartesian3, Entity, ConstantPositionProperty, ScreenSpaceEventHandler, defined, ScreenSpaceEventType, ColorMaterialProperty, CallbackProperty, PolygonHierarchy, PointPrimitiveCollection, BlendOption, clone, } from 'cesium' export type DrawUserCallBackOption = { started?: () => void beforeStop?: (pickedPositions: Cartesian3[]) => void stoped?: () => void } export type DrawPointOption = DrawUserCallBackOption & { pixelSize?: number color?: Color } type ShapeActivePointOption = { pixelSize?: number color?: Color heightReference?: HeightReference } type DrawShapeEntityPropertyOption = { material?: Color | ColorMaterialProperty clampToGround?: boolean width?: number } type DrawShapeEntityNameAddition = { nameAddition?: string } export type DrawPolylineOption = DrawUserCallBackOption & ShapeActivePointOption & DrawShapeEntityPropertyOption & DrawShapeEntityNameAddition export type DrawPolygonOption = DrawUserCallBackOption & ShapeActivePointOption & DrawShapeEntityPropertyOption & DrawShapeEntityNameAddition type DrawShapeOptionBase = { drawMode: DrawMode } type DrawShapeOption = DrawShapeOptionBase & DrawPolylineOption & DrawPolygonOption export enum DrawMode { Polyline, Polygon, } class Draw { private static DRAWED_POINTS_FLAG = '_DRAWED_POINTS_FLAG' private static DRAWED_SHAPES_FLAG = '_DRAWED_SHAPES_FLAG' private static DRAWED_SHAPES_POLYLINE_FLAG = '_POLYLINE' private static DRAWED_SHAPES_POLYGON_FLAG = '_POLYGON' protected viewer: Viewer private activeShapePoints: Cartesian3[] = [] private drawShapePickedPositions: Cartesian3[] = [] private activeShape: Entity | undefined private mousePoint: Entity | undefined constructor(viewer: Viewer) { this.viewer = viewer } public drawPoint(option?: DrawPointOption): void { const { viewer } = this const { started, stoped, pixelSize = 10, color = Color.RED } = option || {} const { scene } = viewer const pointPrimitives = new PointPrimitiveCollection({ blendOption: BlendOption.TRANSLUCENT, }) ;(pointPrimitives as any).name = Draw.DRAWED_POINTS_FLAG scene.primitives.add(pointPrimitives) const hasDepthTest = scene.globe.depthTestAgainstTerrain const handler = new ScreenSpaceEventHandler(scene.canvas) handler.setInputAction(function (e) { let cartesian if (hasDepthTest) { cartesian = scene.pickPosition(e.position) } else { cartesian = scene.camera.pickEllipsoid( e.position, scene.globe.ellipsoid ) } pointPrimitives.add({ position: cartesian, pixelSize, color, }) }, ScreenSpaceEventType.LEFT_CLICK) handler.setInputAction(function (movement) { handler.destroy() stoped && stoped() }, ScreenSpaceEventType.RIGHT_CLICK) started && started() } public removeDrawedPoints(): void { const { scene } = this.viewer const pris = scene.primitives let index = 0 while (index < pris.length) { const pri = pris.get(index) if (pri.name === Draw.DRAWED_POINTS_FLAG) { pris.remove(pri) } else { index++ } } } private createShapeActivePoint( position: any, option: ShapeActivePointOption ): Entity { const { color = Color.YELLOW, pixelSize = 10, heightReference = HeightReference.CLAMP_TO_GROUND, } = option const { viewer } = this return viewer.entities.add({ position: position, point: { color, pixelSize, heightReference, }, }) } private buildShape( drawMode: DrawMode, data: any, option: DrawShapeEntityPropertyOption ): Entity | undefined { const { viewer } = this if (drawMode === DrawMode.Polyline) { const { clampToGround = true, width = 5, material = Color.RED } = option return viewer.entities.add({ polyline: { positions: data, clampToGround, width, material, }, }) } else if (drawMode === DrawMode.Polygon) { const { material = new ColorMaterialProperty(Color.RED.withAlpha(0.7)) } = option return viewer.entities.add({ polygon: { hierarchy: data, material, }, }) } } private terminateShape( drawMode: DrawMode, option: DrawShapeEntityPropertyOption & DrawShapeEntityNameAddition & DrawUserCallBackOption ): void { const { viewer, activeShapePoints, drawShapePickedPositions, mousePoint, activeShape, drawShapeEntityName, } = this activeShapePoints.pop() option && option.beforeStop && option.beforeStop(drawShapePickedPositions) const entity = this.buildShape(drawMode, activeShapePoints, option) if (!entity) { return } entity.name = drawShapeEntityName(drawMode, option.nameAddition) if (mousePoint) { viewer.entities.remove(mousePoint) } if (activeShape) { viewer.entities.remove(activeShape) } this.mousePoint = undefined this.activeShape = undefined this.activeShapePoints = [] this.drawShapePickedPositions = [] } protected drawShapeEntityName( drawMode: DrawMode, nameAddition: string | undefined = undefined ): string { let entityName: string = Draw.DRAWED_SHAPES_FLAG if (drawMode === DrawMode.Polyline) { entityName += Draw.DRAWED_SHAPES_POLYLINE_FLAG + (nameAddition || '') } else { entityName += Draw.DRAWED_SHAPES_POLYGON_FLAG + (nameAddition || '') } return entityName } private drawShape(option: DrawShapeOption): void { const { started, stoped, drawMode } = option const { viewer } = this const { scene } = viewer const self = this if (!scene.pickPositionSupported) { window.alert('This browser does not support pickPosition.') return } const hasDepthTest = scene.globe.depthTestAgainstTerrain const handler = new ScreenSpaceEventHandler(scene.canvas) handler.setInputAction(function (event) { let position: Cartesian3 | undefined if (hasDepthTest) { position = scene.pickPosition(event.position) } else { position = scene.camera.pickEllipsoid( event.position, scene.globe.ellipsoid ) } if (!position || !defined(position)) { return } if (self.activeShapePoints.length === 0) { self.mousePoint = self.createShapeActivePoint(position, option) self.activeShapePoints.push(position) self.activeShape = self.buildShape( drawMode, new CallbackProperty(() => { if (drawMode === DrawMode.Polygon) { return new PolygonHierarchy(self.activeShapePoints) } return self.activeShapePoints }, false), option ) } self.activeShapePoints.push(position) self.drawShapePickedPositions.push(clone(position)) // createShapeActivePoint(position, option) }, ScreenSpaceEventType.LEFT_CLICK) handler.setInputAction(function (event) { let newPosition if (hasDepthTest) { newPosition = viewer.scene.pickPosition(event.endPosition) } else { newPosition = viewer.scene.camera.pickEllipsoid( event.endPosition, viewer.scene.globe.ellipsoid ) } const { mousePoint } = self if ( !mousePoint || !newPosition || !defined(mousePoint) || !defined(newPosition) ) { return } if (mousePoint.position) { ;(mousePoint.position as ConstantPositionProperty).setValue(newPosition) } self.activeShapePoints.pop() self.activeShapePoints.push(newPosition) }, ScreenSpaceEventType.MOUSE_MOVE) handler.setInputAction(function (event) { self.terminateShape(drawMode, option) handler.destroy() stoped && stoped() }, ScreenSpaceEventType.RIGHT_CLICK) started && started() } private removeDrawedShapes( drawMode: DrawMode, nameAddition: string | undefined = undefined ): void { const { viewer, drawShapeEntityName } = this const entities = viewer.entities.values let index = 0 const entityName = drawShapeEntityName(drawMode, nameAddition) while (index < entities.length) { const model = entities[index] if (model.name === entityName) { viewer.entities.remove(model) } else { index++ } } } public drawPolyline(option?: DrawPolylineOption): void { this.drawShape({ drawMode: DrawMode.Polyline, ...(option || {}), }) } public drawPolygon(option?: DrawPolygonOption): void { this.drawShape({ drawMode: DrawMode.Polygon, ...(option || {}), }) } public removeDrawedPolyline( nameAddition: string | undefined = undefined ): void { this.removeDrawedShapes(DrawMode.Polyline, nameAddition) } public removeDrawedPolygon( nameAddition: string | undefined = undefined ): void { this.removeDrawedShapes(DrawMode.Polygon, nameAddition) } public removeAllDrawed(nameAddition: string | undefined = undefined): void { this.removeDrawedPoints() this.removeDrawedPolyline(nameAddition) this.removeDrawedPolygon(nameAddition) } } export default Draw
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/measure/state.ts
<reponame>CN-3211/vt-cesium2.0 export type MeasureState = { measurePointActive: boolean measurePolylineActive: boolean measurePolygonActive: boolean } export const defaultState = (): MeasureState => { return { measurePointActive: false, measurePolylineActive: false, measurePolygonActive: false, } } export const state: MeasureState = defaultState()
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/locationbar/state.ts
<reponame>CN-3211/vt-cesium2.0 /* * @Date: 2022-03-30 16:34:56 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-01 17:39:18 * @FilePath: /vt-cesium2.0/src/store/modules/jt-cesium-vue/modules/locationbar/state.ts */ export type State = { showCameraLocation: boolean showMouseLocation: boolean showFPS: boolean // 要不要把激活状态也放进来 } /** * @description: 为什么要区分defaultState和State * @param {*} * @return {*} State */ export const defaultState = (): State => { return { showCameraLocation: false, showMouseLocation: false, showFPS: false, } } export const state: State = defaultState()
CN-3211/vt-cesium2.0
src/libs/cesium/libs/highlight/Highlight.ts
import { Viewer, Color, Cartesian2, Cartesian3, Entity, CustomDataSource, DataSource, LabelStyle, VerticalOrigin, HorizontalOrigin, ConstantPositionProperty, ScreenSpaceEventHandler, defined, ScreenSpaceEventType, Cesium3DTileFeature, } from 'cesium' type Highlighted3DTileFeature = { feature: Cesium3DTileFeature | undefined originalColor: Color labelPoint?: Entity } type Highlight3DTileFeatureOption = { color?: Color } class Highlight { private static HIGHLIGHT_LABEL_POINTS_DATASOURCE_NAME = '_HIGHLIGHT_LABEL_POINTS_DATASOURCE_NAME' private viewer: Viewer private highlighted3DTileFeature: Highlighted3DTileFeature = { feature: undefined, originalColor: new Color(), labelPoint: undefined, } constructor(viewer: Viewer) { this.viewer = viewer } private createLabelPoint(ds: DataSource, position: any = undefined): Entity { return ds.entities.add({ position: position || Cartesian3.fromDegrees(0, 0, 0), label: { text: '', font: '16px Source Han Sans CN', fillColor: Color.WHITE, style: LabelStyle.FILL_AND_OUTLINE, outlineWidth: 8, outlineColor: Color.BLACK, verticalOrigin: VerticalOrigin.BOTTOM, horizontalOrigin: HorizontalOrigin.CENTER, pixelOffset: new Cartesian2(0, -10), }, }) } private setLabelPointProperty( point?: Entity, position: Cartesian3 | undefined = undefined, text: string | undefined = undefined ): void { if (!point) { return } if (position && point.position) { ;(point.position as ConstantPositionProperty).setValue(position) } if (text && point.label) { ;(point.label.text as any) = text } } public highlight3DTileFeature( option: Highlight3DTileFeatureOption ): ScreenSpaceEventHandler { const { viewer } = this const { color } = option const { scene } = viewer const toColor = color || Color.YELLOW.withAlpha(0.5) if (!this.highlighted3DTileFeature.labelPoint) { this.highlighted3DTileFeature.labelPoint = this.createLabelPoint( this.highlightLabelPointDataSources() ) } const self = this const handler = new ScreenSpaceEventHandler(scene.canvas) handler.setInputAction(function (movement) { if (scene.pickPositionSupported) { const cartesian = scene.pickPosition(movement.endPosition) if (cartesian && defined(cartesian)) { self.setLabelPointProperty( self.highlighted3DTileFeature.labelPoint, cartesian ) } } const pickedObject = scene.pick(movement.endPosition) if ( !pickedObject || !defined(pickedObject) || !(pickedObject instanceof Cesium3DTileFeature) || pickedObject === self.highlighted3DTileFeature.feature ) { return } self.removeHighlighted3DTileFeature() self.highlighted3DTileFeature.feature = pickedObject Color.clone( pickedObject.color, self.highlighted3DTileFeature.originalColor ) pickedObject.color = toColor const HIEGHT_PROPERTY_NAME = 'height' if (pickedObject.hasProperty(HIEGHT_PROPERTY_NAME)) { const height = pickedObject.getProperty(HIEGHT_PROPERTY_NAME) self.setLabelPointProperty( self.highlighted3DTileFeature.labelPoint, undefined, `${height} m` ) } }, ScreenSpaceEventType.MOUSE_MOVE) return handler } public removeHighlightLabelPointDataSource = (): void => { const ds = this.viewer.dataSources const len = ds.length for (let i = 0; i < len; i++) { const d = ds.get(i) if (d && d.name === Highlight.HIGHLIGHT_LABEL_POINTS_DATASOURCE_NAME) { ds.remove(d) } } } private highlightLabelPointDataSources(): DataSource { const ds = this.viewer.dataSources const len = ds.length for (let i = 0; i < len; i++) { const d = ds.get(i) if (d && d.name === Highlight.HIGHLIGHT_LABEL_POINTS_DATASOURCE_NAME) { return d } } const pds = new CustomDataSource( Highlight.HIGHLIGHT_LABEL_POINTS_DATASOURCE_NAME ) this.viewer.dataSources.add(pds) return pds } public removeHighlighted3DTileFeature(): void { const { feature, originalColor } = this.highlighted3DTileFeature if (feature && defined(feature)) { try { feature.color = originalColor } catch (err) { console.error(err) } finally { this.highlighted3DTileFeature.feature = undefined } } } public removeAll(): void { this.removeHighlighted3DTileFeature() this.removeHighlightLabelPointDataSource() } } export default Highlight
CN-3211/vt-cesium2.0
src/utils/vue-utils/clipping/clipModel.ts
/* * @Date: 2021-06-16 11:00:08 * @LastEditors: huangzh873 * @LastEditTime: 2021-06-25 18:14:03 * @FilePath: \cesium-web-vue\src\utils\vue-utils\clipping\clipModel.ts */ import * as Cesium from 'cesium'; // direction存放表示方向的字符串常量 import { direction } from '@/constant/index'; function createClippingPlanes(planeDirection:string):Cesium.ClippingPlaneCollection { let plansArr:Cesium.ClippingPlane[] = []; switch (planeDirection) { case direction.WEST: plansArr = [new Cesium.ClippingPlane(new Cesium.Cartesian3(1.0, 0.0, 0.0), 0.0),] break; case direction.EAST: plansArr = [new Cesium.ClippingPlane(new Cesium.Cartesian3(-1.0, 0.0, 0.0), 0.0),] break; case direction.TOP: plansArr = [new Cesium.ClippingPlane(new Cesium.Cartesian3(0.0, 0.0, -1.0), 0.0),] break; case direction.BOTTOM: plansArr = [new Cesium.ClippingPlane(new Cesium.Cartesian3(0.0, 0.0, 1.0), 0.0),] break; case direction.SOUTH: plansArr = [new Cesium.ClippingPlane(new Cesium.Cartesian3(0.0, 1.0, 0.0), 0.0),] break; case direction.NORTH: plansArr = [new Cesium.ClippingPlane(new Cesium.Cartesian3(0.0, -1.0, 0.0), 0.0),] break; default: plansArr = [ new Cesium.ClippingPlane(new Cesium.Cartesian3(1.0, 0.0, 0.0), 0.0), new Cesium.ClippingPlane(new Cesium.Cartesian3(-1.0, 0.0, 0.0), 0.0), new Cesium.ClippingPlane(new Cesium.Cartesian3(0.0, 0.0, -1.0), 0.0), new Cesium.ClippingPlane(new Cesium.Cartesian3(0.0, 0.0, 1.0), 0.0), // new Cesium.ClippingPlane(new Cesium.Cartesian3(0.0, 1.0, 0.0), 0.0), // new Cesium.ClippingPlane(new Cesium.Cartesian3(0.0, -1.0, 0.0), 0.0), ] break; } return new Cesium.ClippingPlaneCollection( { planes: plansArr, edgeColor: Cesium.Color.RED, edgeWidth: 2.0, unionClippingRegions: true } ) } function getPlaneDirection(plane:Cesium.ClippingPlane):string { const { x, y, z } = plane.normal; if (x == 1 && y == 0 && z == 0) { return direction.WEST; } else if (x == -1 && y == 0 && z == 0) { return direction.EAST; } else if (x == 0 && y == -1 && z == 0) { return direction.NORTH; } else if (x == 0 && y == 1 && z == 0) { return direction.SOUTH; } else if (x == 0 && y == 0 && z == -1) { return direction.TOP; } else if (x == 0 && y == 0 && z == 1) { return direction.BOTTOM; } throw new Error("获取plane的方向时,发生错误"); } export { createClippingPlanes, getPlaneDirection }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/getters.ts
<reponame>CN-3211/vt-cesium2.0 import { GetterTree } from 'vuex' import { RootState } from '@/store' import { State } from './state' export const getters: GetterTree<State, RootState> = {}
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/layout/actions.ts
import { ActionTree } from 'vuex' import { RootState } from '@/store' import type { State, OverlayDynamicView } from './state' import { LayoutHandlerEnum } from './enum-constant' export const actions: ActionTree<State, RootState> = { async [LayoutHandlerEnum.RESET_STATE]({ commit }) { commit(LayoutHandlerEnum.RESET_STATE) }, async [LayoutHandlerEnum.SET_SHOW_BROWSER_PANEL]( { commit }, payload: boolean ) { commit(LayoutHandlerEnum.SET_SHOW_BROWSER_PANEL, payload) }, async [LayoutHandlerEnum.SET_SHOW_TOOLBAR]({ commit }, payload: boolean) { commit(LayoutHandlerEnum.SET_SHOW_TOOLBAR, payload) }, async [LayoutHandlerEnum.SET_SHOW_SETTING_BUTTON]( { commit }, payload: boolean ) { commit(LayoutHandlerEnum.SET_SHOW_SETTING_BUTTON, payload) }, async [LayoutHandlerEnum.SET_TOOLBAR_HEIGHT]({ commit }, payload: number) { commit(LayoutHandlerEnum.SET_TOOLBAR_HEIGHT, payload) }, async [LayoutHandlerEnum.ADD_UNIQUE_NAME_OVERLAY_DYNAMIC_VIEW_BY_NAME]( { commit }, payload: string ) { commit( LayoutHandlerEnum.ADD_UNIQUE_NAME_OVERLAY_DYNAMIC_VIEW_BY_NAME, payload ) }, async [LayoutHandlerEnum.REMOVE_OVERLAY_DYNAMIC_VIEW_BY_NAME]( { commit }, payload: string ) { commit(LayoutHandlerEnum.REMOVE_OVERLAY_DYNAMIC_VIEW_BY_NAME, payload) }, }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/measure/mutations.ts
import { MutationTree } from 'vuex' import { defaultState } from './state' import type { MeasureState } from './state' import { MeasureMutationTypes } from './mutation-types' export const mutations: MutationTree<MeasureState> = { [MeasureMutationTypes.RESET_STATE](state: MeasureState) { Object.assign(state, defaultState()) }, // measure [MeasureMutationTypes.SET_MEASURE_POINT_ACTIVE]( state: MeasureState, payload: boolean ) { state.measurePointActive = payload }, [MeasureMutationTypes.SET_MEASURE_POLYLINE_ACTIVE]( state: MeasureState, payload: boolean ) { state.measurePolylineActive = payload }, [MeasureMutationTypes.SET_MEASURE_POLYGON_ACTIVE]( state: MeasureState, payload: boolean ) { state.measurePolygonActive = payload }, }
CN-3211/vt-cesium2.0
src/components/viewer/constant.ts
/* * @Date: 2022-03-28 16:19:29 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-28 16:19:30 * @FilePath: /cesium-web-vue/src/components/viewer/constant.ts */ export const LOADED_EVENT = 'loaded';
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/locationbar/actions.ts
/* * @Date: 2022-03-30 16:34:56 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-02 10:47:18 * @FilePath: /vt-cesium2.0/src/store/modules/jt-cesium-vue/modules/locationbar/actions.ts */ import { ActionTree } from 'vuex' import { RootState } from '@/store' import type { State } from './state' import { LocationbarHandlerEnum } from './enum-constant' export const actions: ActionTree<State, RootState> = { async [LocationbarHandlerEnum.RESET_STATE]({ commit }) { commit(LocationbarHandlerEnum.RESET_STATE) }, async [LocationbarHandlerEnum.SET_SHOW_CAMERA_LOCATION]( { commit }, payload: boolean ) { commit(LocationbarHandlerEnum.SET_SHOW_CAMERA_LOCATION, payload) }, async [LocationbarHandlerEnum.SET_SHOW_MOUSE_LOCATION]( { commit }, payload: boolean ) { commit(LocationbarHandlerEnum.SET_SHOW_MOUSE_LOCATION, payload) }, async [LocationbarHandlerEnum.SET_SHOW_FPS]({ commit }, payload: boolean) { commit(LocationbarHandlerEnum.SET_SHOW_FPS, payload) }, }
CN-3211/vt-cesium2.0
src/@types/shims-cesium-ref.d.ts
import * as Cesium from 'cesium' interface CesiumRef { viewer: Cesium.Viewer | undefined viewerContainer: HTMLElement | undefined }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/cesium-data/modules/jt-primitive/mutations.ts
import * as Cesium from 'cesium' import { MutationTree } from 'vuex' import { defaultState } from './state' import type { JTPrimitiveState } from './state' import { JTPrimitiveMutationTypes } from './mutation-types' import { JTPrimitive } from '@/libs/cesium/libs/primitive-manager/PrimitiveManager' export const mutations: MutationTree<JTPrimitiveState> = { [JTPrimitiveMutationTypes.RESET_STATE](state: JTPrimitiveState) { Object.assign(state, defaultState()) }, // primitive [JTPrimitiveMutationTypes.SYNC_JTPRIMITIVES]( state: JTPrimitiveState, payload: JTPrimitive[] ) { state.jtPrimitives.splice(0, state.jtPrimitives.length) state.jtPrimitives.push(...payload) }, }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/state.ts
<filename>src/store/modules/jt-cesium-vue/modules/toolbar/state.ts import type { NatureState } from './modules/nature' import type { Tool3DTileState } from './modules/tool3DTile' import type { OtherState } from './modules/other' import type { DrawState } from './modules/draw' import type { MeasureState } from './modules/measure' import type { ImageryState } from './modules/imagery' export type ToolbarStateAndModule = { visible: boolean dropdown: DropdownState elevationContourActive: boolean terrainSampling: TerrainSamplingState nature: NatureState tool3DTile: Tool3DTileState other: OtherState draw: DrawState measure: MeasureState imagery: ImageryState } export type State = { visible: boolean dropdown: DropdownState elevationContourActive: boolean terrainSampling: TerrainSamplingState } export type DropdownState = { show: boolean componentName: string top: number left: number iconEl?: HTMLElement } export type TerrainSamplingData = { index: number height: number } export type TerrainSamplingState = { show: boolean datas: TerrainSamplingData[] } export const defaultState = (): State => { return { visible: true, dropdown: { show: false, componentName: '', top: 0, left: 0 }, elevationContourActive: false, terrainSampling: { show: false, datas: [], }, } } export const state: State = defaultState()
CN-3211/vt-cesium2.0
src/main.ts
/* * @Date: 2022-03-29 16:52:36 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-31 17:26:59 * @FilePath: /vt-cesium2.0/src/main.ts */ import { createApp } from 'vue' import App from './App.vue' import router from './router' import { store, key } from './store'; import ElementPlus from 'element-plus'; import cesiumVue from './libs/cesium/cesium-vue' import 'cesium/Source/Widgets/widgets.css' import 'element-plus/dist/index.css' import '@/assets/iconfont/iconfont.css' import '@/assets/styles/index.css' import register from './components/jt-global-register' const hub = createApp(App) register(hub) hub.use(store, key).use(router).use(cesiumVue).use(ElementPlus).mount('#app')
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/tool3DTile/state.ts
export type Tool3DTileState = { highlight3DTileFeatureActive: boolean hoverClassificationActive: boolean clickClassificationActive: boolean } export const defaultState = (): Tool3DTileState => { return { highlight3DTileFeatureActive: false, hoverClassificationActive: false, clickClassificationActive: false, } } export const state: Tool3DTileState = defaultState()
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/tool/groups/draw/index.ts
import { Group, ClickHandlerOption, ActiveOption } from '../../../Types' import { DrawActionTypes } from '@/store/modules/jt-cesium-vue/modules/toolbar/modules/draw/action-types' import type { DrawUserCallBackOption } from '@/libs/cesium/libs/draw/Draw' const view: Group = { name: '绘制(左键开始,右键结束)', items: [ { name: '画点', icon: 'point', clickHandler: (option: ClickHandlerOption): void => { if ( !option || !option.viewer || !option.viewer.jt || option.store.state.jtCesiumVue.toolbar.draw.drawPointActive ) { return } const cb: DrawUserCallBackOption = { started: () => { option.store.dispatch( `jtCesiumVue/toolbar/draw/${DrawActionTypes.SET_DRAW_POINT_ACTIVE}`, true ) }, stoped: () => { option.store.dispatch( `jtCesiumVue/toolbar/draw/${DrawActionTypes.SET_DRAW_POINT_ACTIVE}`, false ) }, } option.viewer.jt.draw.drawPoint(cb) }, active: (option: ActiveOption): boolean => { return option.store.state.jtCesiumVue.toolbar.draw.drawPointActive }, }, { name: '画线', icon: 'line', clickHandler: (option: ClickHandlerOption): void => { if ( !option || !option.viewer || !option.viewer.jt || option.store.state.jtCesiumVue.toolbar.draw.drawPolylineActive ) { return } const cb: DrawUserCallBackOption = { started: () => { option.store.dispatch( `jtCesiumVue/toolbar/draw/${DrawActionTypes.SET_DRAW_POLYLINE_ACTIVE}`, true ) }, stoped: () => { option.store.dispatch( `jtCesiumVue/toolbar/draw/${DrawActionTypes.SET_DRAW_POLYLINE_ACTIVE}`, false ) }, } option.viewer.jt.draw.drawPolyline(cb) }, active: (option: ActiveOption): boolean => { return option.store.state.jtCesiumVue.toolbar.draw.drawPolylineActive }, }, { name: '画面', icon: 'polygon', clickHandler: (option: ClickHandlerOption): void => { if ( !option || !option.viewer || !option.viewer.jt || option.store.state.jtCesiumVue.toolbar.draw.drawPolygonActive ) { return } const cb: DrawUserCallBackOption = { started: () => { option.store.dispatch( `jtCesiumVue/toolbar/draw/${DrawActionTypes.SET_DRAW_POLYGON_ACTIVE}`, true ) }, stoped: () => { option.store.dispatch( `jtCesiumVue/toolbar/draw/${DrawActionTypes.SET_DRAW_POLYGON_ACTIVE}`, false ) }, } option.viewer.jt.draw.drawPolygon(cb) }, active: (option: ActiveOption): boolean => { return option.store.state.jtCesiumVue.toolbar.draw.drawPolygonActive }, }, { name: '移除', icon: 'delete', clickHandler: (option: ClickHandlerOption): void => { if (!option || !option.viewer || !option.viewer.jt) { return } option.viewer.jt.draw.removeAllDrawed() }, }, ], } export default view
CN-3211/vt-cesium2.0
src/store/modules/template/getters.ts
import { GetterTree } from 'vuex' import { RootState } from '@/store' import { State } from './state' export const getters: GetterTree<State, RootState> = { // getTestStr: (state) => state.test.toString() + 'str', }
CN-3211/vt-cesium2.0
src/store/modules/template/mutation-types.ts
export enum TemplateMutationTypes { RESET_STATE = 'RESET_STATE', }
CN-3211/vt-cesium2.0
src/libs/cesium/libs/transform/index.ts
<gh_stars>0 import { Cartesian3, Cartographic, Matrix4, Transforms, Math, Matrix3, Cesium3DTileset, } from 'cesium' const transform = function ( longitude: number, latitude: number, height: number, rotateX: number = 0, rotateY: number = 0, rotateZ: number = 0, scale: number = 0 ): Matrix4 { // positon const position = Cartesian3.fromDegrees(longitude, latitude, height) const matrix4 = Transforms.eastNorthUpToFixedFrame(position) // rotate const matrix3X = Matrix3.fromRotationX(Math.toRadians(rotateX)) const matrix3Y = Matrix3.fromRotationY(Math.toRadians(rotateY)) const matrix3Z = Matrix3.fromRotationZ(Math.toRadians(rotateZ)) Matrix4.multiply(matrix4, matrix3X, matrix4) Matrix4.multiply(matrix4, matrix3Y, matrix4) Matrix4.multiply(matrix4, matrix3Z, matrix4) // scale const matrix4Scale = Matrix4.fromUniformScale(scale) Matrix4.multiply(matrix4, matrix4Scale, matrix4) return matrix4 } const calculate3DTilesetTransform = function ( tileset: Cesium3DTileset, toLongitude: number | undefined = undefined, toLatitude: number | undefined = undefined, toHeight: number | undefined = undefined, rotateX: number = 0, rotateY: number = 0, rotateZ: number = 0, scale: number = 0 ): void { tileset.readyPromise.then((self) => { console.log('ready', self.root.transform) // original coordinate const cartographic = Cartographic.fromCartesian(self.boundingSphere.center) const longitude = toLongitude || Math.toDegrees(cartographic.longitude) const latitude = toLatitude || Math.toDegrees(cartographic.latitude) const height = toHeight || cartographic.height // if move needs: change longitude/latitude/height to new position const matrix = transform( longitude, latitude, height, rotateX, rotateY, rotateZ, scale ) self.root.transform = matrix // you can change root 'tileset.json' file: transform value, to define transform in 3d tile file. console.log('changed', self.root.transform) }) } const change3DTilesetHeight = function ( tileset: Cesium3DTileset, heightOffset: number ): void { tileset.readyPromise.then((self) => { const cartographic = Cartographic.fromCartesian(self.boundingSphere.center) const surface = Cartesian3.fromRadians( cartographic.longitude, cartographic.latitude, 0.0 ) const offset = Cartesian3.fromRadians( cartographic.longitude, cartographic.latitude, heightOffset ) const translation = Cartesian3.subtract(offset, surface, new Cartesian3()) self.modelMatrix = Matrix4.fromTranslation(translation) }) } export { transform, calculate3DTilesetTransform, change3DTilesetHeight }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/imagery/state.ts
<filename>src/store/modules/jt-cesium-vue/modules/toolbar/modules/imagery/state.ts export type SplitType = { enable: boolean position: number } export type ImageryState = { split: SplitType } export const defaultState = (): ImageryState => { return { split: { enable: false, position: 0, }, } } export const state: ImageryState = defaultState()
CN-3211/vt-cesium2.0
src/libs/cesium/libs/clipping-plane/ClippingPlane.ts
import { Viewer, Color, Cesium3DTileset, Model, ClippingPlaneCollection, Cartesian3, ClippingPlane as CesiumClippingPlane, } from 'cesium' class ClippingPlane { private viewer: Viewer constructor(viewer: Viewer) { this.viewer = viewer } public createOrUpdateOnly1Plane( primitive: Cesium3DTileset | Model, x: number, y: number, z: number, distance: number, option: { edgeColor: Color edgeWidth: number } = { edgeColor: Color.RED, edgeWidth: 10, } ): void { // not has clippingPlanes if (!primitive.clippingPlanes || primitive.clippingPlanes.isDestroyed()) { primitive.clippingPlanes = new ClippingPlaneCollection({ planes: [new CesiumClippingPlane(new Cartesian3(x, y, z), distance)], edgeWidth: option.edgeWidth, edgeColor: option.edgeColor, }) } else { const cpLen = primitive.clippingPlanes.length // more than 1 clippingPlanes // remove and renew if (cpLen !== 1) { cpLen > 0 && primitive.clippingPlanes.removeAll() ;(primitive as any).clippingPlanes = undefined primitive.clippingPlanes = new ClippingPlaneCollection({ planes: [new CesiumClippingPlane(new Cartesian3(x, y, z), distance)], edgeWidth: option.edgeWidth, edgeColor: option.edgeColor, }) } else { primitive.clippingPlanes.edgeWidth !== option.edgeWidth && (primitive.clippingPlanes.edgeWidth = option.edgeWidth) primitive.clippingPlanes.edgeColor !== option.edgeColor && (primitive.clippingPlanes.edgeColor = option.edgeColor) const cp = primitive.clippingPlanes.get(0) cp.distance !== distance && (cp.distance = distance) cp.normal.x !== x && (cp.normal.x = x) cp.normal.y !== y && (cp.normal.y = y) cp.normal.z !== z && (cp.normal.z = z) } } } public removeAllPrimitiveClippingPlanes( inManagedPrimitiveOnly: boolean = true ): void { const pm = this.viewer.jt?.primitiveManager if (!pm) { return } const jtPris = pm.syncJTPrimitives(inManagedPrimitiveOnly) if (!jtPris) { return } const len = jtPris.length for (let i = 0; i < len; i++) { const primitive = pm.getPrimitiveByJTPrimitive(jtPris[i]) if (primitive instanceof Cesium3DTileset || primitive instanceof Model) { if ( primitive.clippingPlanes && !primitive.clippingPlanes.isDestroyed() ) { primitive.clippingPlanes.removeAll() } ;(primitive as any).clippingPlanes = undefined } } } } export default ClippingPlane
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/cesium-data/modules/jt-primitive/actions.ts
<filename>src/store/modules/jt-cesium-vue/modules/cesium-data/modules/jt-primitive/actions.ts import * as Cesium from 'cesium' import { ActionTree } from 'vuex' import { RootState } from '@/store' import type { JTPrimitiveState } from './state' import { JTPrimitiveMutationTypes } from './mutation-types' import { JTPrimitiveActionTypes } from './action-types' export const actions: ActionTree<JTPrimitiveState, RootState> = { async [JTPrimitiveActionTypes.RESET_STATE]({ commit }) { commit(JTPrimitiveMutationTypes.RESET_STATE) }, // Primitive async [JTPrimitiveActionTypes.SYNC_JTPRIMITIVES]( { commit, state }, payload: Cesium.Viewer ) { if (!payload) { return } const pris = payload.jt?.primitiveManager.syncJTPrimitives() commit(JTPrimitiveMutationTypes.SYNC_JTPRIMITIVES, pris) }, }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/cesium-data/mutation-types.ts
export enum CesiumDataMutationTypes { RESET_STATE = 'RESET_STATE', }
CN-3211/vt-cesium2.0
src/libs/cesium/libs/imagery-layer-coordinate-transform/ImageryLayerCoordinateTransform.ts
import { Cartesian3, Cartographic, Math, ImageryLayer } from 'cesium' import CoordinateTransform from '@/libs/utils/CoordinateTransform' export enum CoordinateType { Wgs84, Gcj02, Bd09, } class ImageryLayerCoordinateTransform { protected layer: ImageryLayer private projectionTransform: (x: number, y: number) => [number, number] private unprojectionTransform: (x: number, y: number) => [number, number] private static OLD_PROJECT_PROPERTY_NAME = 'old_project' private static OLD_UNPROJECT_PROPERTY_NAME = 'old_unproject' private _coordinateType: CoordinateType public get coordinateType(): CoordinateType { return this._coordinateType } private _correctOffset: boolean = false public get correctOffset(): boolean { return this._correctOffset } public set correctOffset(val: boolean) { if (this._correctOffset === val) { return } this._correctOffset = val const { layer } = this const provider = layer.imageryProvider if (val) { const webMercatorTilingScheme = provider.tilingScheme const projection = (webMercatorTilingScheme as any).projection const { projectionTransform, unprojectionTransform } = this ;(projection as any)[ ImageryLayerCoordinateTransform.OLD_PROJECT_PROPERTY_NAME ] = projection.project projection.project = function (cartographic: Cartographic) { const point = projectionTransform( Math.toDegrees(cartographic.longitude), Math.toDegrees(cartographic.latitude) ) return (projection as any)[ ImageryLayerCoordinateTransform.OLD_PROJECT_PROPERTY_NAME ](new Cartographic(Math.toRadians(point[0]), Math.toRadians(point[1]))) } ;(projection as any)[ ImageryLayerCoordinateTransform.OLD_UNPROJECT_PROPERTY_NAME ] = projection.unproject projection.unproject = function (cartesian: Cartesian3) { const cartographic = (projection as any)[ ImageryLayerCoordinateTransform.OLD_UNPROJECT_PROPERTY_NAME ](cartesian) const point = unprojectionTransform( Math.toDegrees(cartographic.longitude), Math.toDegrees(cartographic.latitude) ) return new Cartographic( Math.toRadians(point[0]), Math.toRadians(point[1]) ) } } else { const webMercatorTilingScheme = provider.tilingScheme const projection = webMercatorTilingScheme.projection const oldProject = (projection as any)[ ImageryLayerCoordinateTransform.OLD_PROJECT_PROPERTY_NAME ] if (oldProject) { projection.project = oldProject } const oldUnproject = (projection as any)[ ImageryLayerCoordinateTransform.OLD_UNPROJECT_PROPERTY_NAME ] if (oldUnproject) { projection.unproject = oldUnproject } } } constructor( layer: ImageryLayer, coordinateType: CoordinateType, defaultCorrentOffset: boolean = false ) { this.layer = layer this._coordinateType = coordinateType if (coordinateType === CoordinateType.Gcj02) { this.projectionTransform = CoordinateTransform.wgs84togcj02 this.unprojectionTransform = CoordinateTransform.gcj02towgs84 } else if (coordinateType === CoordinateType.Bd09) { this.projectionTransform = (x, y) => { const [xx, yy] = CoordinateTransform.wgs84togcj02(x, y) return CoordinateTransform.gcj02tobd09(xx, yy) } this.unprojectionTransform = (x, y) => { const [xx, yy] = CoordinateTransform.bd09togcj02(x, y) return CoordinateTransform.gcj02towgs84(xx, yy) } } else { this.projectionTransform = (x, y) => [x, y] this.unprojectionTransform = (x, y) => [x, y] } if (defaultCorrentOffset) { this.correctOffset = defaultCorrentOffset } } } export default ImageryLayerCoordinateTransform
CN-3211/vt-cesium2.0
src/libs/cesium-vue.ts
/* * @Date: 2022-03-28 11:15:48 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-30 22:10:31 * @FilePath: /vt-cesium2.0/src/libs/cesium-vue.ts */ import { App } from 'vue'; import { CesiumRef } from '@/@types/index'; // 为什么要用Symbol export const CESIUM_REF_KEY = Symbol('cesiumRef') declare module '@vue/runtime-core' { interface ComponentCustomProperties { readonly $cesiumRef: CesiumRef readonly cesiumRef: CesiumRef } } export default { install: function (app: App<Element>): void { const cr: CesiumRef = { viewer: undefined, viewerContainer: undefined, } // 在根结点(APP)下通过provide挂载cr,用于获取cesiumRef app.config.globalProperties.$cesiumRef = cr app.provide<CesiumRef>(CESIUM_REF_KEY, cr) }, }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/cesium-data/modules/jt-primitive/state.ts
import { JTPrimitive } from '@/libs/cesium/libs/primitive-manager/PrimitiveManager' export type JTPrimitiveState = { jtPrimitives: JTPrimitive[] } export const defaultState = (): JTPrimitiveState => { return { jtPrimitives: [], } } export const state: JTPrimitiveState = defaultState()
CN-3211/vt-cesium2.0
src/libs/cesium/libs/imagery-manager/imagery-sources.ts
<filename>src/libs/cesium/libs/imagery-manager/imagery-sources.ts import { Viewer, Credit, Math, GeographicTilingScheme, WebMercatorTilingScheme, Rectangle, } from 'cesium' import sampleData from '@/resources/sample-data' import { CoordinateType } from '@/libs/cesium/libs/imagery-layer-coordinate-transform/ImageryLayerCoordinateTransform' export default [ [ { iconImageUrl: 'img_c.jpg', name: '天地图影像底图', options: { url: 'https://{s}.tianditu.gov.cn/img_c/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=feff991159823907566acaa7273472ea', layer: 'img', style: 'default', format: 'tiles', tileMatrixSetID: 'c', tileMatrixLabels: [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', ], tilingScheme: new GeographicTilingScheme(), credit: new Credit('天地图全球影像服务'), subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'], maximumLevel: 18, show: true, }, providerName: 'WebMapTileServiceImageryProvider', }, { iconImageUrl: 'cia_c.png', name: '天地图影像注记', options: { url: 'https://{s}.tianditu.gov.cn/cia_c/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=feff991159823907566acaa7273472ea', layer: 'img', style: 'default', format: 'tiles', tileMatrixSetID: 'c', tileMatrixLabels: [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', ], tilingScheme: new GeographicTilingScheme(), credit: new Credit('天地图全球影像服务'), subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'], maximumLevel: 18, show: true, }, providerName: 'WebMapTileServiceImageryProvider', }, { iconImageUrl: 'vec_c.jpg', name: '天地图矢量底图', options: { url: 'https://{s}.tianditu.gov.cn/vec_c/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=feff991159823907566acaa7273472ea', layer: 'vec', style: 'default', format: 'image/jpeg', tileMatrixSetID: 'c', tileMatrixLabels: [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', ], tilingScheme: new GeographicTilingScheme(), credit: new Credit('天地图全球影像服务'), subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'], maximumLevel: 18, show: true, }, providerName: 'WebMapTileServiceImageryProvider', }, { iconImageUrl: 'cva_c.png', name: '天地图矢量注记', options: { url: 'https://{s}.tianditu.gov.cn/cva_c/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=feff991159823907566acaa7273472ea', layer: 'vec', style: 'default', format: 'image/jpeg', tileMatrixSetID: 'c', tileMatrixLabels: [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', ], tilingScheme: new GeographicTilingScheme(), credit: new Credit('天地图全球影像服务'), subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'], maximumLevel: 18, show: true, }, providerName: 'WebMapTileServiceImageryProvider', }, ], [ { iconImageUrl: 'amap_img.png', name: '高德影像底图', options: { url: 'https://webst{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}', subdomains: ['01', '02', '03', '04'], }, providerName: 'UrlTemplateImageryProvider', coordinateType: CoordinateType.Gcj02, }, { iconImageUrl: 'amap_img.png', name: '高德影像注记', options: { url: 'https://webst{s}.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}', subdomains: ['01', '02', '03', '04'], }, providerName: 'UrlTemplateImageryProvider', coordinateType: CoordinateType.Gcj02, }, { iconImageUrl: 'amap_img.png', name: '高德矢量', options: { url: 'https://webrd{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', subdomains: ['01', '02', '03', '04'], }, providerName: 'UrlTemplateImageryProvider', coordinateType: CoordinateType.Gcj02, }, ], [ { iconImageUrl: 'google_hybrid.jpg', name: 'google混合', options: { url: 'https://mt1.google.cn/vt/lyrs=y&hl=zh-CN&x={x}&y={y}&z={z}', }, providerName: 'UrlTemplateImageryProvider', }, { iconImageUrl: 'google_satellite.jpg', name: 'google影像', options: { url: 'https://mt1.google.cn/vt/lyrs=s&hl=zh-CN&x={x}&y={y}&z={z}', }, providerName: 'UrlTemplateImageryProvider', }, { iconImageUrl: 'google_label.png', name: 'google注记', options: { url: 'https://mt1.google.cn/vt/lyrs=h&hl=zh-CN&x={x}&y={y}&z={z}', }, providerName: 'UrlTemplateImageryProvider', }, { iconImageUrl: 'google_road.jpg', name: 'google道路', options: { url: 'https://mt1.google.com/vt/lyrs=m&hl=zh-CN&x={x}&y={y}&z={z}', }, providerName: 'UrlTemplateImageryProvider', }, { iconImageUrl: 'google_terrain.jpg', name: 'google地形', options: { url: 'https://mt1.google.com/vt/lyrs=p&hl=zh-CN&x={x}&y={y}&z={z}', }, providerName: 'UrlTemplateImageryProvider', }, ], { iconImageUrl: 'img_c.jpg', name: '测试001-影像', options: { url: sampleData.satellite, fileExtension: 'png', rectangle: Rectangle.fromRadians( 1.8735054237781372, 0.5907873200661897, 1.8824726243189496, 0.5956433152060476 ), }, providerName: 'UrlTemplateImageryProvider', afterReady: function (viewer: Viewer, success: boolean): void { const rect = Rectangle.fromRadians( 1.8735054237781372, 0.5907873200661897, 1.8824726243189496, 0.5956433152060476 ) if (viewer && success) { viewer.camera.flyTo({ destination: rect, orientation: { heading: Math.toRadians(0), pitch: Math.toRadians(-90), roll: 0.0, }, }) } }, }, [ { iconImageUrl: 'tile_coordinates.jpg', name: 'WGS84切片网', providerName: 'TileCoordinatesImageryProvider', }, { iconImageUrl: 'tile_coordinates.jpg', name: 'Web Mercator切片网', options: { tilingScheme: new WebMercatorTilingScheme(), }, providerName: 'TileCoordinatesImageryProvider', }, { iconImageUrl: 'tile.jpg', name: 'Web Mercator网', options: { tilingScheme: new WebMercatorTilingScheme(), }, providerName: 'GridImageryProvider', }, { iconImageUrl: 'tile.jpg', name: 'WGS84网', providerName: 'GridImageryProvider', }, ], // [ // { // iconImageUrl: 'tile.jpg', // name: '生态林', // providerName: 'ArcGisMapServerImageryProvider', // options: { // // url: 'http://server.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer', // url: 'http://192.168.0.171/ArcGIS/rest/services/stl/MapServer', // }, // }, // { // iconImageUrl: 'tile.jpg', // name: '行政区乡镇', // providerName: 'ArcGisMapServerImageryProvider', // options: { // // url: 'http://server.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer', // url: 'http://192.168.0.171/ArcGIS/rest/services/xzqxz/MapServer', // }, // }, // { // iconImageUrl: 'tile.jpg', // name: '行政区村', // providerName: 'ArcGisMapServerImageryProvider', // options: { // // url: 'http://server.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer', // url: 'http://192.168.0.171/ArcGIS/rest/services/xzqc/MapServer', // }, // }, // ], ]
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/effect/groups/index.ts
/* * @Date: 2022-04-08 09:44:21 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-08 10:23:52 * @FilePath: /vt-cesium2.0/src/components/jt-toolbar/config/contents/effect/groups/index.ts */ import { Group } from '../../Types' import nature from './nature' import other from './other' const groups: Array<Group> = [nature, other] export default groups
CN-3211/vt-cesium2.0
src/utils/vue-utils/handle3DTiles/index.ts
/* * @Date: 2021-11-26 10:31:50 * @LastEditors: huangzh873 * @LastEditTime: 2021-11-26 10:33:20 * @FilePath: \cesium-web-vue\src\utils\vue-utils\handle3DTiles\index.ts */ import selectTileset from './selectTileset'; export { selectTileset }
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/tool/index.ts
/* * @Date: 2022-04-06 16:45:35 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-06 16:51:59 * @FilePath: /vt-cesium2.0/src/components/jt-toolbar/config/contents/tool/index.ts */ import { Content } from '../Types' import groups from './groups' const content: Content = { name: '工具', groups, disable: false, } export default content
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/cesium-data/modules/jt-primitive/action-types.ts
<filename>src/store/modules/jt-cesium-vue/modules/cesium-data/modules/jt-primitive/action-types.ts export enum JTPrimitiveActionTypes { RESET_STATE = 'RESET_STATE', // Primitive SYNC_JTPRIMITIVES = 'SYNC_JTPRIMITIVES', }
CN-3211/vt-cesium2.0
src/components/toolbarGroup/analysis/virtualDrilling.ts
/* * @Date: 2022-01-10 15:35:51 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-28 19:48:56 * @FilePath: /cesium-web-vue/src/components/toolbarGroup/analysis/virtualDrilling.ts */ import { Math as CMath, Entity ,Viewer, ScreenSpaceEventHandler, ScreenSpaceEventType, Cartographic, Cartesian3, Ray, Color, Cesium3DTileFeature } from 'cesium'; import { ElNotification } from 'element-plus' export default class virtualDrilling { private static _viewer: Viewer; handler: ScreenSpaceEventHandler; barEntities: Entity[] = [] constructor(viewer: Viewer) { virtualDrilling._viewer = viewer; this.handler = new ScreenSpaceEventHandler(viewer.scene.canvas); } startSelectDrill() { this.handler.setInputAction(movement => { const cartesian1 = virtualDrilling._viewer.scene.pickPosition(movement.position); const cartographic = Cartographic.fromCartesian(cartesian1); const startPoint = Cartesian3.fromDegrees( CMath.toDegrees(cartographic.longitude), CMath.toDegrees(cartographic.latitude), cartographic.height + 1000 ); const endPoint = Cartesian3.fromDegrees( CMath.toDegrees(cartographic.longitude), CMath.toDegrees(cartographic.latitude), -9999 ); const greenRhumbLine = virtualDrilling._viewer.entities.add({ name: "Green rhumb line", polyline: { positions: [ startPoint, endPoint, ], width: 5, material: Color.GREEN, }, }); this.barEntities.push(greenRhumbLine); const direction = Cartesian3.normalize( Cartesian3.subtract( endPoint, startPoint, new Cartesian3() ), new Cartesian3() ); const ray1 = new Ray(startPoint, direction); const scene:any = virtualDrilling._viewer.scene; const results = scene.drillPickFromRay(ray1); // 计算交互点 const featureNames:string[] = results.map(result => { if(result.object) { const feature:Cesium3DTileFeature = result.object; return feature.getProperty('地层名称') } }).filter(item => item); console.log(featureNames); if(featureNames.length) { ElNotification({ title: '地层名称', message: featureNames.join(','), }) } else { ElNotification({ title: '错误', message: '未拾取到地层信息', type: 'error', }) } }, ScreenSpaceEventType.LEFT_CLICK) } stopSelectDrill() { this.handler.destroy(); if(this.barEntities.length) { this.barEntities.forEach(item => { virtualDrilling._viewer.entities.remove(item); }) this.barEntities = []; } } }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/index.ts
import { Module } from 'vuex' import { RootState } from '@/store' import { store as nature } from './modules/nature' import { store as tool3DTile } from './modules/tool3DTile' import { store as other } from './modules/other' import { store as draw } from './modules/draw' import { store as measure } from './modules/measure' import { store as imagery } from './modules/imagery' import { state } from './state' import type { ToolbarStateAndModule, State } from './state' export { ToolbarStateAndModule } import { getters } from './getters' import { mutations } from './mutations' import { actions } from './actions' type ToolbarState = ToolbarStateAndModule | State export const store: Module<ToolbarState, RootState> = { namespaced: true, state, getters, mutations, actions, modules: { nature, tool3DTile, other, draw, measure, imagery, }, }
CN-3211/vt-cesium2.0
src/libs/cesium/libs/light/Light.ts
<gh_stars>0 import { Viewer, Color, Cartesian3, Scene, defined, JulianDate, SunLight, DirectionalLight, Matrix3, Transforms, Simon1994PlanetaryPositions, } from 'cesium' class Light { private viewer: Viewer constructor(viewer: Viewer) { this.viewer = viewer } public static updateFlashLightListener(scene: Scene): void { ;(scene.light as any).direction = Cartesian3.clone( scene.camera.directionWC, (scene.light as any).direction ) } public getSunLight(): SunLight { return new SunLight() } public getFlashLight(): DirectionalLight { return new DirectionalLight({ direction: this.viewer.scene.camera.directionWC, }) } public static getMoonDirection(currentTime: JulianDate): Cartesian3 { const icrfToFixed = new Matrix3() const scratchMoonPosition = new Cartesian3() const scratchMoonDirection = new Cartesian3() if ( !defined(Transforms.computeIcrfToFixedMatrix(currentTime, icrfToFixed)) ) { Transforms.computeTemeToPseudoFixedMatrix(currentTime, icrfToFixed) } const moonPosition = Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame( currentTime, scratchMoonPosition ) Matrix3.multiplyByVector(icrfToFixed, moonPosition, moonPosition) const moonDirection = Cartesian3.normalize( moonPosition, scratchMoonDirection ) return Cartesian3.negate(moonDirection, new Cartesian3()) } public getMoonLight(currentTime: JulianDate): DirectionalLight { return new DirectionalLight({ direction: Light.getMoonDirection(currentTime), color: new Color(0.9, 0.925, 1.0), intensity: 1, }) } public static updateMoonLightListener( scene: Scene, currentTime: JulianDate ): void { ;(scene.light as DirectionalLight).direction = Light.getMoonDirection(currentTime) } } export default Light
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/nature/mutation-types.ts
<reponame>CN-3211/vt-cesium2.0<filename>src/store/modules/jt-cesium-vue/modules/toolbar/modules/nature/mutation-types.ts export enum NatureMutationTypes { RESET_STATE = 'RESET_STATE', // nature SET_SHOW_SUN = 'SET_SHOW_SUN', SET_SHOW_MOON = 'SET_SHOW_MOON', SET_SHOW_SKY_ATMOSPHERE = 'SET_SHOW_SKY_ATMOSPHERE', SET_ENABLE_LIGHT = 'SET_ENABLE_LIGHT', SET_SHOW_SKY_BOX = 'SET_SHOW_SKY_BOX', SET_SHOW_SHADOW = 'SET_SHOW_SHADOW', }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/cesium-data/action-types.ts
export enum CesiumDataActionTypes { RESET_STATE = 'RESET_STATE', }
CN-3211/vt-cesium2.0
src/@types/index.ts
<reponame>CN-3211/vt-cesium2.0 /* * @Date: 2022-03-28 11:19:05 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-28 11:19:06 * @FilePath: /cesium-web-vue/src/@types/index.ts */ import type { Viewer } from 'cesium'; interface CesiumRef { viewer: Viewer | undefined viewerContainer: HTMLElement | undefined } export { CesiumRef }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/draw/getters.ts
<gh_stars>0 import { GetterTree } from 'vuex' import { RootState } from '@/store' import { DrawState } from './state' export const getters: GetterTree<DrawState, RootState> = { // getTestStr: (state) => state.test.toString() + 'str', }
CN-3211/vt-cesium2.0
src/libs/cesium/libs/measure/Measure.ts
import { Viewer, Color, HeightReference, Cartesian2, Cartesian3, Entity, CustomDataSource, DataSource, LabelStyle, VerticalOrigin, HorizontalOrigin, ConstantPositionProperty, ScreenSpaceEventHandler, Cartographic, defined, Math, ScreenSpaceEventType, JulianDate, ColorMaterialProperty, CallbackProperty, PolygonHierarchy, } from 'cesium' import * as Cesium from 'cesium' export type MeasureUserCallBackOption = { started?: () => void stoped?: () => void } export type MeasurePointOption = MeasureUserCallBackOption export type MeasurePolylineOption = MeasureUserCallBackOption export type MeasurePolygonOption = MeasureUserCallBackOption enum MeasureMode { Polyline, Polygon, } type MeasureShapeOptionBase = { measureMode: MeasureMode } type MeasureShapeOption = MeasureShapeOptionBase & MeasurePolylineOption & MeasurePolygonOption class Measure { private static MEASURED_POINTS_DATASOURCE_NAME = '_MEASURED_POINTS_DATASOURCE_NAME' private static MEASURED_POLYLINES_DATASOURCE_NAME = '_MEASURED_POLYLINES_DATASOURCE_NAME' private static MEASURED_POLYGONS_DATASOURCE_NAME = '_MEASURED_POLYGONS_DATASOURCE_NAME' protected viewer: Viewer private currentPoint: Entity | undefined private activeShapePoints: Cartesian3[] = [] private activeShape: Entity | undefined private mousePoint: Entity | undefined private preMousePoint: Entity | undefined private firstPoint: Entity | undefined private sumLength = 0 constructor(viewer: Viewer) { this.viewer = viewer } private measurePointDataSources(): DataSource { const ds = this.viewer.dataSources const len = ds.length for (let i = 0; i < len; i++) { const d = ds.get(i) if (d && d.name === Measure.MEASURED_POINTS_DATASOURCE_NAME) { return d } } const pds = new CustomDataSource(Measure.MEASURED_POINTS_DATASOURCE_NAME) this.viewer.dataSources.add(pds) return pds } private createLabelPoint(ds: DataSource, position: any = undefined): Entity { return ds.entities.add({ position: position || Cartesian3.fromDegrees(0, 0, 0), point: { color: Color.RED, pixelSize: 15, }, label: { text: '', font: '16px Source Han Sans CN', fillColor: Color.WHITE, style: LabelStyle.FILL_AND_OUTLINE, outlineWidth: 8, outlineColor: Color.BLACK, verticalOrigin: VerticalOrigin.BOTTOM, horizontalOrigin: HorizontalOrigin.CENTER, pixelOffset: new Cartesian2(0, -30), }, }) } private measurePointText(lon = 0, lat = 0, height = 0): string { return `经度:${lon.toFixed(6)}°\n纬度:${lat.toFixed( 6 )}°\n高度:${height.toFixed(3)}m` } private setPointProperty( point: Entity, position: Cartesian3 | undefined = undefined, text: string | undefined = undefined ): void { if (position && point.position) { ;(point.position as ConstantPositionProperty).setValue(position) } if (text && point.label) { ;(point.label.text as any) = text } } public measurePoint(option: MeasurePointOption): void { const { started, stoped } = option const { scene } = this.viewer const pds = this.measurePointDataSources() const hasDepthTest = this.viewer.scene.globe.depthTestAgainstTerrain const handler = new ScreenSpaceEventHandler(scene.canvas) const self = this handler.setInputAction(function (e) { let position if (hasDepthTest) { position = self.viewer.scene.pickPosition(e.endPosition) } else { position = self.viewer.scene.camera.pickEllipsoid( e.endPosition, self.viewer.scene.globe.ellipsoid ) } if (!position || !defined(position)) { return } if (!self.currentPoint) { self.currentPoint = self.createLabelPoint(pds) } const cartographic = Cartographic.fromCartesian(position) const lon = Math.toDegrees(cartographic.longitude) const lat = Math.toDegrees(cartographic.latitude) const hei = cartographic.height || 0 self.setPointProperty( self.currentPoint, position, self.measurePointText(lon, lat, hei) ) }, ScreenSpaceEventType.MOUSE_MOVE) handler.setInputAction(function (e) { self.currentPoint = undefined }, ScreenSpaceEventType.LEFT_CLICK) handler.setInputAction(function (movement) { if (self.currentPoint) { pds.entities.remove(self.currentPoint) self.currentPoint = undefined } handler.destroy() stoped && stoped() }, ScreenSpaceEventType.RIGHT_CLICK) started && started() } public removeMeasuredPoints(): void { const ds = this.viewer.dataSources const len = ds.length for (let i = 0; i < len; i++) { const d = ds.get(i) if (d && d.name === Measure.MEASURED_POINTS_DATASOURCE_NAME) { ds.remove(d) } } } public removeMeasuredPolylines(): void { const ds = this.viewer.dataSources const len = ds.length for (let i = 0; i < len; i++) { const d = ds.get(i) if (d && d.name === Measure.MEASURED_POLYLINES_DATASOURCE_NAME) { ds.remove(d) } } } public removeMeasuredPolygons(): void { const ds = this.viewer.dataSources const len = ds.length for (let i = 0; i < len; i++) { const d = ds.get(i) if (d && d.name === Measure.MEASURED_POLYGONS_DATASOURCE_NAME) { ds.remove(d) } } } public measurePolyline(option?: MeasurePolylineOption): void { this.measureShape({ measureMode: MeasureMode.Polyline, ...(option || {}), }) } public measurePolygon(option?: MeasurePolygonOption): void { this.measureShape({ measureMode: MeasureMode.Polygon, ...(option || {}), }) } public removeAllMeasured(): void { this.removeMeasuredPoints() this.removeMeasuredPolylines() this.removeMeasuredPolygons() } private datasource(measureMode: MeasureMode): DataSource { let dsName: string if (measureMode === MeasureMode.Polyline) { dsName = Measure.MEASURED_POLYLINES_DATASOURCE_NAME } else if (measureMode === MeasureMode.Polygon) { dsName = Measure.MEASURED_POLYGONS_DATASOURCE_NAME } else { throw new Error('Unknown datasource name.') } const ds = this.viewer.dataSources const len = ds.length for (let i = 0; i < len; i++) { const d = ds.get(i) if (d.name === dsName) { return d } } const pds = new CustomDataSource(dsName) this.viewer.dataSources.add(pds) return pds } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types private buildShape(measureMode: MeasureMode, data: any): Entity { let entity: Entity | Entity.ConstructorOptions if (measureMode === MeasureMode.Polyline) { entity = { polyline: { positions: data, clampToGround: false, width: 5, material: Color.RED, }, } } else if (measureMode === MeasureMode.Polygon) { entity = { polygon: { hierarchy: data, material: new ColorMaterialProperty(Color.RED.withAlpha(0.7)), }, } } else { throw new Error('Unknown datasource name.') } return this.datasource(measureMode).entities.add(entity) } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types private buildShapeLabelPoint( measureMode: MeasureMode, position: any ): Entity { let entity: Entity if (measureMode === MeasureMode.Polyline) { entity = this.createLabelPoint(this.datasource(measureMode), position) } else if (measureMode === MeasureMode.Polygon) { entity = this.viewer.entities.add({ position: position, point: { color: Color.YELLOW, pixelSize: 10, heightReference: HeightReference.CLAMP_TO_GROUND, }, }) } else { throw new Error('Unknown datasource name.') } return entity } private terminateShape(measureMode: MeasureMode): void { this.activeShapePoints.pop() const entity = this.buildShape(measureMode, this.activeShapePoints) if (measureMode === MeasureMode.Polygon) { const area = this.getArea(entity) if (this.mousePoint && this.mousePoint.position && area) { const areaLP = this.createLabelPoint( this.datasource(measureMode), this.mousePoint.position.getValue(new JulianDate()) ) this.setPointProperty(areaLP, undefined, `${area.toFixed(3)}㎡`) } } const entities = this.viewer.entities if (this.mousePoint && entities.contains(this.mousePoint)) { entities.remove(this.mousePoint) } const dses = this.datasource(measureMode).entities if (this.activeShape && dses.contains(this.activeShape)) { dses.remove(this.activeShape) } if (this.mousePoint && dses.contains(this.mousePoint)) { dses.remove(this.mousePoint) } this.mousePoint = undefined this.activeShape = undefined this.activeShapePoints = [] } private measureShape(option: MeasureShapeOption): void { const { started, stoped, measureMode } = option const { scene } = this.viewer if (!scene.pickPositionSupported) { window.alert('This browser does not support pickPosition.') } const hasDepthTest = scene.globe.depthTestAgainstTerrain const handler = new ScreenSpaceEventHandler(scene.canvas) const self = this handler.setInputAction(function (event) { let position: Cartesian3 | undefined if (hasDepthTest) { position = scene.pickPosition(event.position) } else { position = scene.camera.pickEllipsoid( event.position, scene.globe.ellipsoid ) } if (!position || !defined(position)) { return } if (self.activeShapePoints.length === 0) { self.sumLength = 0 self.mousePoint = self.buildShapeLabelPoint(measureMode, position) self.activeShapePoints.push(position) self.activeShape = self.buildShape( measureMode, new CallbackProperty(() => { if (measureMode === MeasureMode.Polygon) { return new PolygonHierarchy(self.activeShapePoints) } return self.activeShapePoints }, false) ) } self.activeShapePoints.push(position) if (measureMode === MeasureMode.Polyline) { const lp = self.buildShapeLabelPoint(measureMode, position) const jd = new JulianDate() if (self.activeShapePoints.length === 2) { self.firstPoint = lp } if (self.activeShapePoints.length > 2 && self.preMousePoint) { if (self.preMousePoint.position && lp.position) { const dis = Cartesian3.distance( self.preMousePoint.position.getValue(jd), lp.position.getValue(jd) ) self.sumLength += dis self.setPointProperty(lp, undefined, `${dis.toFixed(3)}m`) if (self.firstPoint) { self.setPointProperty( self.firstPoint, undefined, `总长:${self.sumLength.toFixed(3)}m` ) } } } self.preMousePoint = lp } }, ScreenSpaceEventType.LEFT_CLICK) handler.setInputAction(function (event) { let newPosition: Cartesian3 | undefined if (hasDepthTest) { newPosition = scene.pickPosition(event.endPosition) } else { newPosition = scene.camera.pickEllipsoid( event.endPosition, scene.globe.ellipsoid ) } if ( !newPosition || !self.mousePoint || !defined(self.mousePoint) || !defined(newPosition) ) { return } if (measureMode === MeasureMode.Polyline) { // setLabelPoint(mousePoint, newPosition, '123') } else { self.mousePoint.position && (self.mousePoint.position as ConstantPositionProperty).setValue( newPosition ) } self.activeShapePoints.pop() self.activeShapePoints.push(newPosition) }, ScreenSpaceEventType.MOUSE_MOVE) handler.setInputAction(function (event) { self.terminateShape(measureMode) handler.destroy() stoped && stoped() }, ScreenSpaceEventType.RIGHT_CLICK) started && started() } private getArea(theEntity: Entity): number | undefined { const polygon = theEntity.polygon if (!polygon || !polygon.hierarchy) { return } const hierarchy = (polygon.hierarchy as any)._value const indices = (Cesium as any).PolygonPipeline.triangulate( hierarchy.positions, hierarchy.holes ) let area = 0 for (let i = 0; i < indices.length; i += 3) { const vector1 = hierarchy.positions[indices[i]] const vector2 = hierarchy.positions[indices[i + 1]] const vector3 = hierarchy.positions[indices[i + 2]] const vectorC = Cartesian3.subtract(vector2, vector1, new Cartesian3()) const vectorD = Cartesian3.subtract(vector3, vector1, new Cartesian3()) const areaVector = Cartesian3.cross(vectorC, vectorD, new Cartesian3()) area += Cartesian3.magnitude(areaVector) / 2.0 } return area } } export default Measure
CN-3211/vt-cesium2.0
src/libs/utils/rgb.ts
<reponame>CN-3211/vt-cesium2.0<filename>src/libs/utils/rgb.ts<gh_stars>0 export type RgbaStruct = { red: number green: number blue: number alpha: number } const rgbaStringToStruct = function (val: string): RgbaStruct { let rgba = val?.match(/(\d(\.\d+)?)+/g) as Array<string> if (!rgba) { rgba = ['0', '0', '0', '0'] } const r = parseFloat(rgba[0]) const g = parseFloat(rgba[1]) const b = parseFloat(rgba[2]) const a = parseFloat(rgba[3]) return { red: r, green: g, blue: b, alpha: a, } } export { rgbaStringToStruct }
CN-3211/vt-cesium2.0
src/store/modules/template/actions.ts
import { ActionTree } from 'vuex' import { RootState } from '@/store' import type { State } from './state' import { TemplateMutationTypes } from './mutation-types' import { TemplateActionTypes } from './action-types' export const actions: ActionTree<State, RootState> = { async [TemplateActionTypes.RESET_STATE]({ commit }) { commit(TemplateMutationTypes.RESET_STATE) }, }
CN-3211/vt-cesium2.0
src/utils/vue-utils/keyboardInteraction/index.ts
<gh_stars>0 /* * @Date: 2021-10-11 15:45:43 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-29 22:16:28 * @FilePath: /vt-cesium2.0/src/utils/vue-utils/keyboardInteraction/index.ts */ import * as Cesium from 'cesium'; import { createHandler } from '@/utils/c-utils'; /** * handler start */ let handler_LEFT_DOWN:Cesium.ScreenSpaceEventHandler let handler_MOUSE_MOVE:Cesium.ScreenSpaceEventHandler let handler_LEFT_UP:Cesium.ScreenSpaceEventHandler /** * handler end */ export default class interaction { static keyboardState: { looking: boolean; moveForward: boolean; moveBackward: boolean; moveUp: boolean; moveDown: boolean; moveLeft: boolean; moveRight: boolean; }; static moveRate: { keyboard: number, mouse: number[] } static viewer: Cesium.Viewer constructor(viewer: Cesium.Viewer) { interaction.keyboardState = { looking: false, moveForward: false, moveBackward: false, moveUp: false, moveDown: false, moveLeft: false, moveRight: false, } interaction.viewer = viewer interaction.moveRate = { keyboard: 0, mouse: [] }; } /** * event function start */ static evKeydown(event: KeyboardEvent) { const keyType = interaction.getKeyType(event.code); if(keyType) { interaction.keyboardState[keyType] = true } } static _evKeydown(event: KeyboardEvent) { interaction.evKeydown(event) } static evKeyup(event: KeyboardEvent) { const keyType = interaction.getKeyType(event.code); if(keyType) { interaction.keyboardState[keyType] = false } } static _evKeyup(event: KeyboardEvent) { interaction.evKeyup(event) } static evOnTick() { interaction.moveRate.keyboard = Cesium.Cartographic.fromCartesian(interaction.viewer.camera.position, interaction.viewer.scene.globe.ellipsoid).height / 100; Object.keys(interaction.keyboardState).forEach(key => { if(!interaction.keyboardState[key]) { return } if(key === "looking") { if(!interaction.moveRate.mouse.length) { return } interaction.viewer.camera.lookRight(interaction.moveRate.mouse[0]) interaction.viewer.camera.lookUp(interaction.moveRate.mouse[1]) return } interaction.viewer.camera[key](interaction.moveRate.keyboard) }) } /** * event function end */ /** * @description: 获取用户输入的keyboard案件,并触发对应move事件 * @param {*} * @return {*} */ keyboardAction() { document.addEventListener('keydown', interaction._evKeydown) document.addEventListener('keyup', interaction._evKeyup) } removeAllEventAndHandler(viewer: Cesium.Viewer) { this.resetDefaultEvents(viewer) document.removeEventListener('keydown', interaction._evKeydown) document.removeEventListener('keyup', interaction._evKeyup) viewer.clock.onTick.removeEventListener(interaction.evOnTick) handler_LEFT_DOWN.destroy() handler_MOUSE_MOVE.destroy() handler_LEFT_UP.destroy() } static getKeyType(keyCode: string) { switch (keyCode) { case 'KeyW': return "moveForward" case 'KeyS': return "moveBackward" case 'KeyQ': return "moveUp" case 'KeyE': return "moveDown" case 'KeyA': return "moveLeft" case 'KeyD': return "moveRight" default: break; } } /** * @description: 获取用户鼠标在canvas上的运动,根据Cartesian2坐标的变化来触发lookUp和lookRight事件 * @param {*} canvas * @return {*} */ mouseAction(canvas: HTMLCanvasElement) { let startPosition: Cesium.Cartesian2; let currentPosition: Cesium.Cartesian2; handler_LEFT_DOWN = createHandler(canvas, event => { interaction.keyboardState.looking = true; startPosition = currentPosition = event.position.clone() }, Cesium.ScreenSpaceEventType.LEFT_DOWN) handler_MOUSE_MOVE = createHandler(canvas, event => { if(!interaction.keyboardState.looking) return currentPosition = event.endPosition; const x = (currentPosition.x - startPosition.x) / canvas.width const y = -(currentPosition.y - startPosition.y) / canvas.height const FACTOR = 0.05; interaction.moveRate.mouse = [x * FACTOR, y * FACTOR]; }, Cesium.ScreenSpaceEventType.MOUSE_MOVE) handler_LEFT_UP = createHandler(canvas, event => { interaction.keyboardState.looking = false; }, Cesium.ScreenSpaceEventType.LEFT_UP) } onClockTick(viewer: Cesium.Viewer) { this.disableMouseEvents(viewer) /* before tick */ this.keyboardAction() this.mouseAction(viewer.canvas) /* before tick */ viewer.clock.onTick.addEventListener(interaction.evOnTick) } disableMouseEvents(viewer: Cesium.Viewer) { // 通过设置属性tabindex来获取焦点 viewer.canvas.setAttribute('tabindex', '0'); viewer.canvas.addEventListener('click', () => { viewer.canvas.focus() }) viewer.scene.screenSpaceCameraController.enableRotate = false; viewer.scene.screenSpaceCameraController.enableTranslate = false; viewer.scene.screenSpaceCameraController.enableZoom = false; viewer.scene.screenSpaceCameraController.enableTilt = false; viewer.scene.screenSpaceCameraController.enableLook = false; } resetDefaultEvents(viewer: Cesium.Viewer) { viewer.scene.screenSpaceCameraController.enableRotate = true; viewer.scene.screenSpaceCameraController.enableTranslate = true; viewer.scene.screenSpaceCameraController.enableZoom = true; viewer.scene.screenSpaceCameraController.enableTilt = true; viewer.scene.screenSpaceCameraController.enableLook = true; } }
CN-3211/vt-cesium2.0
src/utils/vue-utils/handle3DTiles/selectTileset.ts
/* * @Date: 2021-11-26 10:02:19 * @LastEditors: huangzh873 * @LastEditTime: 2021-12-01 08:56:45 * @FilePath: /cesium-web-vue/src/utils/vue-utils/handle3DTiles/selectTileset.ts */ import { Color, Cesium3DTileStyle, Cesium3DTileset , Cesium3DTileFeature ,Viewer, ScreenSpaceEventHandler, ScreenSpaceEventType } from 'cesium'; import { throttle } from '@/utils/index'; export default function pick3Dtiles(viewer: Viewer, callback: (params: Cesium3DTileset) => void) { let tileset:Cesium3DTileset | undefined let blinkInterval const handler: ScreenSpaceEventHandler = new ScreenSpaceEventHandler(viewer.canvas); const blinkStyle = new Cesium3DTileStyle({ color: 'color("yellow")' }) // 防抖,不要多次触发 handler.setInputAction(throttle(movement => { const tilesetFeature = viewer.scene.pick(movement.position); if(tilesetFeature instanceof Cesium3DTileFeature) { // 点击触发模型闪烁 tileset = tilesetFeature.primitive; tileset.style = blinkStyle; setTimeout(() => { if(tileset) { tileset.style = undefined; } }, 300); setTimeout(() => { if(tileset) { tileset.style = blinkStyle; } }, 600); setTimeout(() => { if(tileset) { tileset.style = undefined; } }, 900); callback(tileset) } }, 100), ScreenSpaceEventType.LEFT_CLICK) return handler; }
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/effect/groups/other/index.ts
<reponame>CN-3211/vt-cesium2.0 /* * @Date: 2022-04-08 09:44:21 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-08 09:47:12 * @FilePath: /vt-cesium2.0/src/components/jt-toolbar/config/contents/effect/groups/other/index.ts */ import { Group, ClickHandlerOption, OnMountedOption, ActiveOption, } from '../../../Types' import { OtherActionTypes } from '@/store/modules/jt-cesium-vue/modules/toolbar/modules/other/action-types' import { OtherMutationTypes } from '@/store/modules/jt-cesium-vue/modules/toolbar/modules/other/mutation-types' const view: Group = { name: '其他', items: [ { name: '深度检测', icon: '360', clickHandler: (option: ClickHandlerOption): void => { option.store.dispatch( `jtCesiumVue/toolbar/other/${OtherActionTypes.SWITCH_DEPTH_TEST_AGAINST_TERRAIN}`, option ) }, active: (option: ActiveOption) => option.store.state.jtCesiumVue.toolbar.other.depthTestAgainstTerrain, onMounted: (option: OnMountedOption): void => { const viewer = option?.viewer if (viewer) { option.store.commit( `jtCesiumVue/toolbar/other/${OtherMutationTypes.SET_DEPTH_TEST_AGAINST_TERRAIN}`, viewer.scene.globe.depthTestAgainstTerrain ) } }, }, ], } export default view
CN-3211/vt-cesium2.0
src/components/jt-global-register/index.ts
/* * @Date: 2022-03-28 09:56:52 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-31 19:47:38 * @FilePath: /vt-cesium2.0/src/components/jt-global-register/index.ts */ import { App } from 'vue' const requireComponent = require.context('./components', true, /index.vue$/) const register = (app: App<Element>): void => { requireComponent.keys().forEach((fullpath) => { const componentConfig = requireComponent(fullpath) const pathArr = fullpath.split('/') pathArr.pop() // pop filename(index.vue) let componentName = '' if (pathArr) { componentName = pathArr.pop() as string } if (!componentName) { return } app.component(componentName, componentConfig.default || componentConfig) }) } export default register
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/measure/action-types.ts
<filename>src/store/modules/jt-cesium-vue/modules/toolbar/modules/measure/action-types.ts export enum MeasureActionTypes { RESET_STATE = 'RESET_STATE', // measure SET_MEASURE_POINT_ACTIVE = 'SET_MEASURE_POINT_ACTIVE', SET_MEASURE_POLYLINE_ACTIVE = 'SET_MEASURE_POLYLINE_ACTIVE', SET_MEASURE_POLYGON_ACTIVE = 'SET_MEASURE_POLYGON_ACTIVE', }
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/view/groups/fly-to/index.ts
<gh_stars>0 /* * @Date: 2022-03-30 15:49:30 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-30 22:20:51 * @FilePath: /vt-cesium2.0/src/components/jt-toolbar/config/contents/view/groups/fly-to/index.ts */ import { Group, ClickHandlerOption } from '../../../Types' const view: Group = { name: '快速定位', items: [ { name: '全球', icon: 'earth', clickHandler: (options: ClickHandlerOption | undefined): void => { const viewer = options?.viewer if (!viewer) { return } viewer.jt?.flyTo.flyToEarth() }, }, { name: '中国', icon: 'china_compressed', clickHandler: (options: ClickHandlerOption | undefined): void => { const viewer = options?.viewer if (!viewer) { return } viewer.jt?.flyTo.flyToChina() }, }, ], invisible: false, disable: false, } export default view
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/view/groups/status/index.ts
<reponame>CN-3211/vt-cesium2.0 /* * @Date: 2022-03-30 15:49:30 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-02 11:10:06 * @FilePath: /vt-cesium2.0/src/components/jt-toolbar/config/contents/view/groups/status/index.ts */ import { Group, ClickHandlerOption, ActiveOption } from '../../../Types' import { LocationbarHandlerEnum } from '@/store/modules/jt-cesium-vue/modules/locationbar/enum-constant' const view: Group = { name: '状态栏', items: [ { name: '视角坐标', icon: 'camera2', clickHandler: (option: ClickHandlerOption): void => { const payload: boolean = !option.store.state.jtCesiumVue.locationbar.showCameraLocation option.store.dispatch( `jtCesiumVue/locationbar/${LocationbarHandlerEnum.SET_SHOW_CAMERA_LOCATION}`, payload ) }, active: (option: ActiveOption): boolean => { return ( option.store.state.jtCesiumVue.locationbar.showCameraLocation || false ) }, dropdown: { componentName: 'camera-percentage-change-rate', }, }, { name: '鼠标坐标', icon: 'click', clickHandler: (option: ClickHandlerOption): void => { const payload: boolean = !option.store.state.jtCesiumVue.locationbar.showMouseLocation option.store?.dispatch( `jtCesiumVue/locationbar/${LocationbarHandlerEnum.SET_SHOW_MOUSE_LOCATION}`, payload ) }, active: (option: ActiveOption): boolean => { return option.store.state.jtCesiumVue.locationbar.showMouseLocation! }, }, { name: 'FPS', icon: 'fps', clickHandler: (option: ClickHandlerOption): void => { const payload: boolean = !option.store.state.jtCesiumVue.locationbar.showFPS option.store.dispatch( `jtCesiumVue/locationbar/${LocationbarHandlerEnum.SET_SHOW_FPS}`, payload ) }, active: (option: ActiveOption): boolean => { return option.store.state.jtCesiumVue.locationbar.showFPS! }, }, ], } export default view
OwnYourData/soya-cli
src/utils/range.ts
<filename>src/utils/range.ts export interface Range { } export class NumberRange implements Range { constructor( /** * The minimum value is INCLUDED in the range */ public min?: number, /** * The maximum value is INCLUDED in the range */ public max?: number, ) { } } export class DateRange implements Range { constructor( /** * The minimum value is INCLUDED in the range */ public min?: string, /** * The maximum value is INCLUDED in the range */ public max?: string, ) { } } const isExcluded = (char: string = '') => ['(', ')'].indexOf(char) !== -1; // this is a very stupid date regex const dateRegex = /^\d{4}-\d{2}-\d{2}$/; const numberRegex = /^\d+$/ const parseValue = (value?: string): string | number | undefined => { if (!value) return; if (dateRegex.test(value)) return value; else if (numberRegex.test(value)) return parseInt(value); return; } const rangeRegex = /^([\(\[]?)([^\(\[]+)\.\.([^\)\]]+)([\)\]]?)$/; export const parseRange = (input: string): Range | undefined => { const match = rangeRegex.exec(input); if (!match || match === null || match.length !== 5) return; const excludeMin = isExcluded(match[1]); const excludeMax = isExcluded(match[4]); let minValue = parseValue(match[2]); let maxValue = parseValue(match[3]); if ((minValue === undefined || typeof minValue === 'number') && (maxValue === undefined || typeof maxValue === 'number')) { if (minValue && excludeMin) minValue++; if (maxValue && excludeMax) maxValue--; return new NumberRange(minValue, maxValue); } else if ((minValue === undefined || typeof minValue === 'string') && (maxValue === undefined || typeof maxValue === 'string')) return new DateRange(minValue, maxValue); return undefined; }
OwnYourData/soya-cli
src/overlays/interface.ts
<reponame>OwnYourData/soya-cli export interface Overlay { type: string, '@graph': any[], [key: string]: any, } export interface OverlayResult { data: any, } export interface CommandPlugin { run: (overlay: Overlay, data: any) => Promise<OverlayResult>; }
OwnYourData/soya-cli
src/system/template.ts
import findRoot from 'find-root'; import fs from 'fs/promises' import path from 'path'; import { logger } from '../services/logger'; const possibleFileExtensions = [ 'yml', 'yaml', ]; const TEMPLATES_DIR = path.join(findRoot(__filename), 'res', 'templates'); export const getAvailableTemplates = async (): Promise<string[]> => { const templates: string[] = []; for (const file of await fs.readdir(path.join(TEMPLATES_DIR))) { templates.push(path.parse(file).name); } return templates; } export const tryPrintTemplate = async (name: string) => { for (const fe of possibleFileExtensions) { try { const file = await fs.readFile(path.join(TEMPLATES_DIR, `${name}.${fe}`), { encoding: 'utf-8' }); console.log(file); return; } catch { } } logger.error(`Could not find template with name "${name}"`); }
OwnYourData/soya-cli
src/system/yaml2soya/index.ts
import jsyaml from 'js-yaml'; import { logger } from '../../services/logger'; import { handleOverlay } from './overlays'; const xsTypes = [ 'string', 'decimal', 'integer', 'float', 'boolean', 'date', 'time', ]; export interface SoyaDocument { ['@context']: { ['@version']: number, ['@base']: string, ['@import']: string, [key: string]: string | number, }, // graph is named incorrectly // it should be @graph // however dealng with special characters is not so easy in node // therefore we work with plain "graph" until the end // shortly before plotting the document, we'll rename it to "@graph" graph: any[], } export type PrintableSoyaDocument = Omit<SoyaDocument, 'graph'> & { '@graph': any[] }; const handleBase = (doc: SoyaDocument, base: any) => { const { graph } = doc; graph.push({ '@id': base.name, '@type': "owl:Class", 'subClassOf': 'Base', }); for (const attrName in base.attributes) { const specifiedDataType = base.attributes[attrName]; const specifiedDataTypeLC = specifiedDataType.toLowerCase(); const dataType = xsTypes.indexOf(specifiedDataTypeLC) !== -1 ? `xsd:${specifiedDataTypeLC}` : specifiedDataType; graph.push({ '@id': attrName, '@type': 'owl:DatatypeProperty', 'domain': base.name, 'range': dataType, }) } } export const yaml2soya = async (yamlContent: string, contextUrl: string, baseUrl: string): Promise<PrintableSoyaDocument | undefined> => { const yaml: any = jsyaml.load(yamlContent); if (!yaml || typeof yaml !== 'object') { logger.error('Can not parse YAML!'); return; } const { meta, content } = yaml; const doc: SoyaDocument = { "@context": { "@version": 1.1, "@import": contextUrl, "@base": `${baseUrl}/${meta.name}/`, }, graph: [], } if (meta.namespace && typeof meta.namespace === 'object') { for (const nsKey in meta.namespace) { doc['@context'][nsKey] = meta.namespace[nsKey]; } } if (Array.isArray(content.base)) for (const base of content.base) { handleBase(doc, base); } if (Array.isArray(content.overlays)) for (const overlay of content.overlays) { handleOverlay(doc, overlay, baseUrl); } // this is where the rename of "graph" to "@graph" happens const printable: PrintableSoyaDocument = { '@context': doc['@context'], '@graph': doc.graph, }; return printable; }
OwnYourData/soya-cli
src/utils/cmd.ts
<reponame>OwnYourData/soya-cli import commandLineArgs from 'command-line-args'; import commandLineUsage from 'command-line-usage'; import { getAvailableTemplates } from '../system/template'; import { packageJson } from './package'; type cmdInterface = (commandLineArgs.OptionDefinition & commandLineUsage.OptionDefinition); interface CmdArgs { default?: string[], repo?: string, verbose?: boolean[], help?: false, executable?: string, version: boolean, } const globalDefinition: cmdInterface[] = [ { name: 'default', defaultOption: true, multiple: true, }, { name: 'repo', description: 'Endpoint where SOyA repository is hosted', alias: 'r', }, { name: 'verbose', description: 'Turns on verbose logging\n-vvvv enables most detailled logs', alias: 'v', multiple: true, type: Boolean, }, { name: 'help', description: 'Prints general help page and command specific help page', alias: 'h', type: Boolean, }, { name: 'version', description: 'Show version number of soya-cli', type: Boolean, defaultValue: false, } ]; const commands: string[] = [ 'calculate-dri', 'validate', 'transform', 'template', 'init', 'similar', 'info', 'push', ]; const getGeneralOptions = (): commandLineUsage.Section => { return { header: 'General options', optionList: globalDefinition.filter(x => !x.defaultOption), }; } const getUsageExamples = (command: string): string[] => { return [ `$ soya ${command} [...options]`, `$ cat template.yaml | soya ${command} -vvv`, `$ cat document.json | soya ${command} <DRI> --repo https://example.com`, ]; } const printGeneralHelp = () => { console.log(commandLineUsage([ { header: `${packageJson.name} (${packageJson.version})`, content: 'The swiss army knife for SOyA 🌱 ({bold S}emantic {bold O}verla{bold y} {bold A}rchitecture)' }, { header: 'Usage', content: getUsageExamples('<command>') }, { header: 'Commands', content: commands, }, getGeneralOptions(), ])); } const printSimpleCommandHelp = (command: string) => { console.log(commandLineUsage([ { header: 'Usage', content: getUsageExamples(command), }, getGeneralOptions(), ])); } const printTemplateHelp = async () => { console.log(commandLineUsage([ { header: 'Description', content: 'Gets you started with SOyA by providing pre-defined YAML templates', }, { header: 'Usage', content: [ '$ soya template <template> > my-template.yaml', ] }, { header: 'Available templates', content: (await getAvailableTemplates()).map(x => `* ${x}`), }, getGeneralOptions(), ])); } const printInitHelp = () => { console.log(commandLineUsage([ { header: 'Description', content: 'Transforms a SOyA to its respective JSON-LD representation', }, { header: 'Usage', content: [ '$ my-doc.yaml | soya init > my-doc.soya.jsonld', ] }, getGeneralOptions(), ])); } const printPullHelp = () => { console.log(commandLineUsage([ { header: 'Description', content: 'Pulls a schema from a repository', }, { header: 'Usage', content: [ '$ soya pull <name | DRI> > document.jsonld', ] }, getGeneralOptions(), ])); } const printSimilarHelp = () => { console.log(commandLineUsage([ { header: 'Description', content: 'Finds similar data structures within the repository', }, { header: 'Usage', content: [ '$ document.jsonld | soya similar', ] }, getGeneralOptions(), ])); } const printInfoHelp = () => { console.log(commandLineUsage([ { header: 'Description', content: 'Prints information about a SOyA base', }, { header: 'Usage', content: [ '$ soya info <name | DRI>', ] }, getGeneralOptions(), ])); } const printPushHelp = () => { console.log(commandLineUsage([ { header: 'Description', content: 'Pushes a SOyA document to the repository', }, { header: 'Usage', content: [ '$ cat document.jsonld | soya push', ] }, getGeneralOptions(), ])); } const transformDefinition: cmdInterface[] = [ { name: 'executable', description: 'Defines the executable to use for transformation', alias: 'e', type: String, } ]; const printTransformHelp = () => { console.log(commandLineUsage([ { header: 'Description', content: 'Uses transformation layers to apply transformations on input data', }, { header: 'Usage', content: [ '$ cat input.json | soya transform <name | DRI>', '$ cat input.json | soya transform <name | DRI> --executable "java -jar jolt.jar"', ] }, { header: 'Options', optionList: transformDefinition, }, getGeneralOptions(), ])) } export const printCliHelp = async (command?: string): Promise<never> => { if (!command) printGeneralHelp(); else { switch (command) { case 'template': await printTemplateHelp(); break; case 'init': printInitHelp(); break; case 'pull': printPullHelp(); break; case 'similar': printSimilarHelp(); break; case 'info': printInfoHelp(); break; case 'push': printPushHelp(); break; case 'transform': printTransformHelp(); break; default: if (commands.indexOf(command) !== -1) printSimpleCommandHelp(command); else printGeneralHelp(); } } process.exit(0); } export const cmdArgs = commandLineArgs([ ...globalDefinition, ...transformDefinition, ]) as CmdArgs;
OwnYourData/soya-cli
src/overlays/transform.ts
import proc from 'child_process'; import fs from 'fs/promises'; import * as jq from 'node-jq'; import { Overlay, CommandPlugin, OverlayResult } from './interface'; import { escapeFilename, makeTempDir } from '../utils/core'; import path from 'path'; import { logger } from '../services/logger'; import { cmdArgs } from '../utils/cmd'; export class SoyaTransform implements CommandPlugin { private runJolt = async (spec: any[], data: any): Promise<OverlayResult> => { const specFile = 'jolt-spec.json'; const dataFile = 'jolt-data.json'; logger.debug(`Creating temp dir for jolt spec`); const [removeTempDir, tempDirPath] = await makeTempDir(); const specFilePath = path.join(tempDirPath, specFile); logger.debug(`Writing jolt spec to ${specFilePath}`); await fs.writeFile(specFilePath, JSON.stringify(spec)); const dataFilePath = path.join(tempDirPath, dataFile); logger.debug(`Writing jolt data ${dataFilePath}`); await fs.writeFile(dataFilePath, JSON.stringify(data)); return new Promise<OverlayResult>((resolve, reject) => { const command = cmdArgs.executable ?? 'jolt'; const commandParams = [ 'transform', escapeFilename(specFilePath), escapeFilename(dataFilePath), ]; logger.debug(`Executing jolt ${command} with ${commandParams.toString()}`); proc.exec(command + ' ' + commandParams.join(' '), (_, stdout) => { logger.debug('Removing temp dir'); removeTempDir(); let data: any; try { data = JSON.parse(stdout); } catch (e) { logger.error('Could not apply jolt transformation') reject(e); } resolve({ data, }); }); }); } private runJq = async (filter: string, data: any): Promise<OverlayResult> => { logger.debug('Executing jq'); const jqOut = await jq.run(filter, data, { input: 'json', }); return { data: typeof jqOut === 'string' ? JSON.parse(jqOut) : jqOut, } } run = (overlay: Overlay, data: any): Promise<OverlayResult> => { for (const item of overlay['@graph']) { // not a valid transformation overlay if (!(item.engine && item.value)) continue; switch (item.engine) { case 'jolt': if (Array.isArray(item.value)) { return this.runJolt(item.value, data); } else throw new Error('jolt expects an array as input!'); case 'jq': if (typeof item.value === 'string') { return this.runJq(item.value, data); } else throw new Error('jq expects a string as input!') default: throw new Error(`Transform engine ${item.engine} not supported!`); } } throw new Error('No transform overlay found!'); } }
OwnYourData/soya-cli
src/overlays/validate.ts
import { Overlay, CommandPlugin, OverlayResult } from "./interface"; import SHACLValidator from "rdf-validate-shacl"; import { parseJsonLd } from "../utils/rdf"; import { logger } from "../services/logger"; import rdf from "rdf-ext"; const namedNode = rdf.namedNode; export class SoyaValidate implements CommandPlugin { run = async (overlay: Overlay, data: any): Promise<OverlayResult> => { const dataSet = await parseJsonLd(data); if (dataSet.length === 0) throw new Error('Input data is not valid JSON-LD!'); const layerSet = await parseJsonLd(overlay); const validator = new SHACLValidator(layerSet); const res = await validator.validate(dataSet); // this are some additional class checks // SHACL is not really made to give invalid results if it has an empty set it's applied on // therefore we additionally check for the availabiligy of all classes that are defined as SHACL shapes const requiredClasses = layerSet.match( undefined, namedNode('http://www.w3.org/ns/shacl#targetClass'), undefined, ); const availableClasses = dataSet.match( undefined, namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), undefined, ) const classChecks: any[] = []; // check, if all required node shapes are available for (const required of requiredClasses) { if (availableClasses.match( undefined, namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), required.object, ).length === 0) classChecks.push({ message: 'Missing class', name: required.object.value, }); } logger.debug('Data to validate:', dataSet); logger.debug('SHACL:', layerSet); return { data: { isValid: res.conforms && classChecks.length === 0, results: res.results.map(x => ({ id: x.focusNode, message: x.message, ...x.path, severity: x.severity, })), classChecks, } }; } }
OwnYourData/soya-cli
src/services/logger.ts
<reponame>OwnYourData/soya-cli import { createLogger, format, transports, } from 'winston'; import { cmdArgs } from '../utils/cmd'; const getLogLevel = (): string => { switch ((cmdArgs.verbose ?? []).reduce((prev, curr) => curr === true ? prev + 1 : prev, 0)) { case 1: return 'warn'; case 2: return 'info'; case 3: return 'debug'; case 4: return 'silly'; default: return 'error'; } } export const logger = createLogger({ level: getLogLevel(), format: format.json(), transports: [ new transports.Console({ format: format.combine( format.colorize(), format.simple(), ) }) ] });
OwnYourData/soya-cli
src/system/yaml2soya/overlays.ts
import { SoyaDocument } from "."; import { DateRange, NumberRange, parseRange } from "../../utils/range"; const arrayifyIfLeaf = (obj: any) => { if (obj && typeof obj === 'object' && !Array.isArray(obj)) { for (const key in obj) { obj[key] = arrayifyIfLeaf(obj[key]); } return obj; } else if (Array.isArray(obj)) return obj; else return [obj]; } export const handleOverlay = (doc: SoyaDocument, overlay: any, baseUrl: string) => { switch (overlay.type) { case 'OverlayAnnotation': handleAnnotation(doc, overlay); break; case 'OverlayAlignment': handleAlignment(doc, overlay); break; case 'OverlayClassification': handleClassification(doc, overlay); break; case 'OverlayEncoding': handleEncoding(doc, overlay); break; case 'OverlayFormat': handleFormat(doc, overlay); break; case 'OverlayValidation': handleValidation(doc, overlay); break; case 'OverlayTransformation': handleTransformation(doc, overlay); break; // for unsupported overlays we just return here // all following code will not be executed default: return; } // add an informational element doc.graph.push({ '@id': overlay.type, '@type': overlay.type, 'onBase': `${baseUrl}/${overlay.base}/`, name: overlay.name, }) }; const handleTransformation = (doc: SoyaDocument, overlay: any) => { const { graph } = doc; const item = { '@id': `${overlay.base}Transformation`, 'engine': overlay.engine, 'value': overlay.value, }; graph.push(item); } const handleValidation = (doc: SoyaDocument, overlay: any) => { const { graph } = doc; const shacl = { '@id': `${overlay.base}Shape`, '@type': 'sh:NodeShape', 'sh:targetClass': overlay.base, 'sh:property': [] as any[], }; graph.push(shacl); for (const attrName in overlay.attributes) { const attr = overlay.attributes[attrName]; const constraints: { [key: string]: any } = {}; for (const constraintKey in attr) { const value = attr[constraintKey]; if (constraintKey === 'pattern') { constraints['sh:pattern'] = value; } else if (constraintKey === 'cardinality') { const range = parseRange(value); if (range instanceof NumberRange) { if (range.min) constraints['sh:minCount'] = range.min; if (range.max) constraints['sh:maxCount'] = range.max; } } else if (constraintKey === 'length') { const range = parseRange(value); if (range instanceof NumberRange) { if (range.min) constraints['sh:minLength'] = range.min; if (range.max) constraints['sh:maxLength'] = range.max; } } else if (constraintKey === 'valueRange') { const range = parseRange(value); if (range instanceof NumberRange) { if (range.min) constraints['sh:minRange'] = range.min; if (range.max) constraints['sh:maxRange'] = range.max; } else if (range instanceof DateRange) { if (range.min) constraints['sh:minRange'] = { '@type': 'xsd:date', '@value': range.min, }; if (range.max) constraints['sh:maxRange'] = { '@type': 'xsd:date', '@value': range.max, }; } } } shacl['sh:property'].push({ 'sh:path': `${attrName}`, ...constraints, }); } } const handleFormat = (doc: SoyaDocument, overlay: any) => { const { graph } = doc; for (const attrName in overlay.attributes) { let encoding = overlay.attributes[attrName]; graph.push({ '@id': `${attrName}`, 'format': encoding, }); } } const handleEncoding = (doc: SoyaDocument, overlay: any) => { const { graph } = doc; for (const attrName in overlay.attributes) { let encoding = overlay.attributes[attrName]; graph.push({ '@id': `${attrName}`, 'encoding': encoding, }); } } const handleClassification = (doc: SoyaDocument, overlay: any) => { const { graph } = doc; for (const attrName in overlay.attributes) { let classifications = overlay.attributes[attrName]; if (!Array.isArray(classifications)) classifications = [classifications]; graph.push({ '@id': `${attrName}`, 'classification': classifications, }); } } const handleAnnotation = (doc: SoyaDocument, overlay: any) => { const { graph } = doc; const handleAttribute = (annotation: any, attrName: string, base?: string) => { const attributeObject: any = { '@id': base ? `${attrName}` : attrName, }; graph.push(attributeObject); for (const aTypeKey in annotation) { attributeObject[aTypeKey] = arrayifyIfLeaf(annotation[aTypeKey]); } } handleAttribute(overlay.class, overlay.base); for (const attrName in overlay.attributes) { let annotation = overlay.attributes[attrName]; handleAttribute(annotation, attrName, overlay.base); } } const handleAlignment = (doc: SoyaDocument, overlay: any) => { const { graph } = doc; for (const attrName in overlay.attributes) { let relations = overlay.attributes[attrName]; if (!Array.isArray(relations)) relations = [relations]; graph.push({ '@id': `${attrName}`, 'rdfs:subPropertyOf': relations, }); } }
OwnYourData/soya-cli
src/utils/dri.ts
import DatasetExt from "rdf-ext/lib/Dataset"; import { URL } from "url"; import { crypto } from "vaultifier/dist/main"; import { logger } from "../services/logger"; import { serializeJsonLd } from "./rdf"; export interface JsonLdObject { quads: DatasetExt, json: any, } export interface CalculationResult { dri: string, baseUri: string, } const tryExtractDriFromUris = (value: any): any => { if (typeof value === 'string') { try { // we only try to extract DRIs from URIs new URL(value); } catch { // if it's not an URI, we can already stop here return value; } const match = /\/(zQm[1-9A-HJ-NP-Za-km-z]{44})/.exec(value); if (match) { const dri = match[1]; return dri; } } // obviously there is no DRI return value; } const checkForObjectOrArray = (val: any) => { if (val && typeof val === 'object') removeDRIsFromObject(val); else if (Array.isArray(val)) removeDRIsFromArray(val); } const removeDRIsFromArray = (arr: any[]): any => { for (let i = 0, size = arr.length; i < size; i++) { arr[i] = tryExtractDriFromUris(arr[i]); checkForObjectOrArray(arr[i]); } } const removeDRIsFromObject = (obj: any): any => { for (const prop in obj) { const val = obj[prop] = tryExtractDriFromUris(obj[prop]); checkForObjectOrArray(val); } } export const calculateBaseUri = async (obj: Partial<JsonLdObject>, base?: string): Promise<CalculationResult> => { if (obj.quads) { const context = { ...obj.json['@context'] }; const serialized = await serializeJsonLd(obj.quads.toStream(), { context: context, }); obj.json = JSON.parse(serialized); } // TODO: removed temporarily until we know how to identify layers, bases and instances // remove @id from '@graph' (only for instances) // if (Array.isArray(obj.json['@graph'])) { // const graphItems = obj.json['@graph']; // for (const item of graphItems) { // delete item['@id']; // } // } // go through all properties and check if it is a DRI // if yes, remove the URL so only the DRI remains removeDRIsFromObject(obj.json); // remove @base property from document as we have to calculate DRI without @base delete obj.json['@context']['@base']; // calculate DRI and add it to document logger.debug(`Generating hashlink from document:`); logger.debug(crypto.canonicalize(obj.json)); const dri = await crypto.generateHashlink(obj.json); const fullUri = base ? `${base}/${dri}` : dri; const baseUri = obj.json['@context']['@base'] = fullUri; return { dri, baseUri }; }
OwnYourData/soya-cli
src/services/soya.ts
<reponame>OwnYourData/soya-cli import { Vaultifier, VaultItem } from 'vaultifier/dist/main'; import { logger } from './logger'; // const DEFAULT_REPO = 'http://localhost:8080'; export const DEFAULT_REPO = 'https://soya.data-container.net'; export const DEFAULT_SOYA_NAMESPACE = 'https://ns.ownyourdata.eu/ns/soya-context.json'; export class SoyaService { constructor( public repo: string = DEFAULT_REPO, ) { } private static INSTANCE = new SoyaService(); static getInstance = () => SoyaService.INSTANCE; static initialize = (instance: SoyaService) => SoyaService.INSTANCE = instance; // TODO: implement caching getVaultifier = async (): Promise<Vaultifier> => { const v = new Vaultifier(this.repo); await v.initialize(); return v; } get = async (url: string, usesAuth: boolean): Promise<any> => { logger.debug(`GETting ${url}`); const { data: res } = await (await this.getVaultifier()).get(url, usesAuth); return res; } post = async (url: string, usesAuth: boolean, data?: any): Promise<any> => { logger.debug(`POSTing ${url}`); const { data: res } = await (await this.getVaultifier()).post(url, usesAuth, data); return res; } pull = async (path: string): Promise<any> => { return this.get(`/${path}`, false); } push = async (data: any): Promise<VaultItem> => { const v = await this.getVaultifier(); const meta = await v.postValue(data); logger.debug('Return value of push', meta); logger.debug(`Fetching item with id ${meta.id}`); return v.getItem({ id: meta.id, }); } similar = async (data: any): Promise<any> => { return this.post(`/api/soya/similar`, false, data); } info = async (path: string): Promise<any> => { return this.get(`/${path}/info`, false); } }
OwnYourData/soya-cli
src/utils/package.ts
<reponame>OwnYourData/soya-cli<filename>src/utils/package.ts<gh_stars>1-10 import path from 'path'; import fs from 'fs'; import { logger } from '../services/logger'; interface PackageJson { name: string, version: string, } let json: PackageJson; try { const raw = fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), { encoding: 'utf-8' }); json = JSON.parse(raw); } catch (e) { logger.error('Can not read package.json', e); process.exit(-1); } export const packageJson = json;
OwnYourData/soya-cli
src/interface.ts
<filename>src/interface.ts import { Overlay } from "./overlays/interface"; export interface Stack { '@context': { [key: string]: string, }, import: string[], overlays: Overlay[], }
OwnYourData/soya-cli
src/utils/std.ts
<gh_stars>1-10 export abstract class Std { static in = async () => { return new Promise<string | undefined>(function (resolve, reject) { const stdin = process.stdin; let data = ''; stdin.setEncoding('utf8'); stdin.on('data', function (chunk) { data += chunk; }); stdin.on('end', function () { resolve(data); }); stdin.on('error', reject); }); } }
OwnYourData/soya-cli
src/index.ts
<gh_stars>0 #!/usr/bin/env node import { DEFAULT_SOYA_NAMESPACE, SoyaService } from "./services/soya"; import { cmdArgs, printCliHelp } from "./utils/cmd"; import { Std } from "./utils/std"; import { SoyaTransform } from "./overlays/transform"; import { CommandPlugin, OverlayResult } from "./overlays/interface"; import { logger } from "./services/logger"; import { SoyaValidate } from "./overlays/validate"; import { packageJson } from "./utils/package"; import { parseJsonLd } from "./utils/rdf"; import { calculateBaseUri } from "./utils/dri"; import DatasetExt from "rdf-ext/lib/Dataset"; import { exitWithError } from "./utils/core"; import { tryPrintTemplate } from "./system/template"; import { yaml2soya } from "./system/yaml2soya"; interface CommandObject { [key: string]: CommandPlugin, } const overlayPlugins: CommandObject = { 'transform': new SoyaTransform(), 'validate': new SoyaValidate(), }; (async () => { if (cmdArgs.version) return console.log(packageJson.version); if (!cmdArgs.default || (!cmdArgs.default && cmdArgs.help)) return printCliHelp(); const { repo, default: [command, param1], } = cmdArgs; if (command && cmdArgs.help) return printCliHelp(command); const handleSystemCommands = async (): Promise<boolean> => { switch (command) { case 'template': if (!param1) return exitWithError('No template name specified!'); tryPrintTemplate(param1); break; case 'init': const yamlContent = await Std.in(); if (!yamlContent) return exitWithError('No YAML content provided via stdin!'); const doc = await yaml2soya(yamlContent, DEFAULT_SOYA_NAMESPACE, SoyaService.getInstance().repo); console.log(JSON.stringify(doc, undefined, 2)); break; case 'pull': if (!param1) return exitWithError('No path specified!'); try { const pulledData = await SoyaService.getInstance().pull(param1); console.log(JSON.stringify(pulledData, undefined, 2)); } catch (e: any) { logger.error('Could not fetch resource from repo!'); if (typeof e.response.status === 'number') { logger.error(`Error: ${e.response.status} ${e.response.statusText}`); } } break; case 'push': const contentDocument = await Std.in(); if (!contentDocument) return exitWithError('No content provided via stdin!'); try { const item = await SoyaService.getInstance().push(contentDocument); logger.debug('Pushed item', item); console.log(item.dri); } catch { return exitWithError('Could not push SOyA document'); } break; case 'calculate-dri': const content = await Std.in(); if (!content) return exitWithError('No content provided via stdin!'); let json: any; let quads: DatasetExt; logger.debug('Raw input:'); logger.debug(content); try { json = JSON.parse(content); quads = await parseJsonLd(json); } catch { return exitWithError('Could not parse JSON!'); } try { const result = await calculateBaseUri({ json, quads, }); console.log(result.dri); } catch { return exitWithError('Could not calculate DRI!'); } break; case 'similar': try { const res = await SoyaService.getInstance().similar(await Std.in()); console.log(JSON.stringify(res, undefined, 2)); } catch (e) { console.error(e) return exitWithError('Could not process provided document'); } break; case 'info': if (!param1) return exitWithError('No path specified!'); try { const res = await SoyaService.getInstance().info(param1); console.log(JSON.stringify(res, undefined, 2)); } catch { return exitWithError('Could not fetch SOyA info'); } break; default: return false; } return true; } logger.info(`${packageJson.name} (${packageJson.version})\n`); if (repo) SoyaService.initialize(new SoyaService(repo)); const isSupported = await handleSystemCommands(); if (isSupported) return; let input: string | undefined = await Std.in(); if (!input) return exitWithError('No input data specified!'); if (!param1) return exitWithError('No DRI specified!'); const layer = await SoyaService.getInstance().pull(param1); if (!command) return exitWithError('No command specified!'); const plugin = overlayPlugins[command]; if (!plugin) return exitWithError(`No plugin available for command "${command}"!`); let parsedInput: any; try { parsedInput = JSON.parse(input); } catch { logger.error('Input data is not valid JSON!') return; } logger.debug('Overlay:', layer); logger.debug('Data In:', parsedInput); let res: OverlayResult; try { res = await plugin.run(layer, parsedInput); } catch (e: any) { logger.error(`Plugin "${command}" raised an error: ${e.message}`); return; } logger.debug('Data Out:', res); let output: any = res.data; try { output = JSON.stringify(output, undefined, 2); } catch { } console.log(output); return; })();
caos/zitadel-examples
nextjs/pages/api/auth/[...nextauth].tsx
import NextAuth from 'next-auth'; export default NextAuth({ providers: [ { id: "zitadel", name: "zitadel", type: "oauth", version: "2.0", scope: "openid profile email", params: { grant_type: "authorization_code" }, authorizationParams: { grant_type: "authorization_code", response_type: "code", }, accessTokenUrl: "https://api.zitadel.dev/oauth/v2/token", requestTokenUrl: "https://api.zitadel.dev/oauth/v2/token", authorizationUrl: "https://accounts.zitadel.dev/oauth/v2/authorize", profileUrl: "https://api.zitadel.dev/oauth/v2/userinfo", protection: "pkce", async profile(profile: any, tokens) { return { id: profile.sub, name: profile.name, email: profile.email, image: profile.picture, }; }, clientId: process.env.ZITADEL_CLIENT_ID, clientSecret: "", }, ], });
caos/zitadel-examples
b2b-nextjs/pages/_app.tsx
import '../styles/globals.scss'; import { SessionProvider } from 'next-auth/react'; import Head from 'next/head'; import Layout from '../components/Layout'; export default function MyApp({ Component, pageProps }: any) { return ( <> <Head> {/* pwa */} <title>ZITADEL • B2B Demo</title> <meta name="description" content="This is a ZITADEL Demo" /> {/* fonts */} <link rel="preconnect" href="https://fonts.gstatic.com" /> <link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;0,700;0,900;1,100;1,300;1,400;1,700;1,900&display=swap" rel="stylesheet" ></link> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> <link href="https://fonts.googleapis.com/css2?family=Spartan:wght@100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet" ></link> {/* icons */} <link rel="stylesheet" href="https://maxst.icons8.com/vue-static/landings/line-awesome/line-awesome/1.3.0/css/line-awesome.min.css" /> <link rel="stylesheet" href="https://maxst.icons8.com/vue-static/landings/line-awesome/font-awesome-line-awesome/css/all.min.css" /> </Head> <SessionProvider session={pageProps.session}> <Layout> <Component {...pageProps} /> </Layout> </SessionProvider> </> ); }
caos/zitadel-examples
angular/src/app/app.module.ts
import { HttpClientModule } from '@angular/common/http'; import { APP_INITIALIZER, NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AuthConfig, OAuthModule, OAuthStorage } from 'angular-oauth2-oidc'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HomeComponent } from './components/home/home.component'; import { SignedOutComponent } from './components/signed-out/signed-out.component'; import { UserComponent } from './components/user/user.component'; import { StatehandlerProcessorService, StatehandlerProcessorServiceImpl } from './services/statehandler-processor.service'; import { StatehandlerService, StatehandlerServiceImpl } from './services/statehandler.service'; import { StorageService } from './services/storage.service'; const authConfig: AuthConfig = { scope: 'openid profile email', responseType: 'code', oidc: true, clientId: '<YOUR APPS CLIENT ID HERE>', issuer: 'https://issuer.zitadel.ch', redirectUri: 'http://localhost:4200/auth/callback', postLogoutRedirectUri: 'http://localhost:4200/signedout', requireHttps: false // required for running locally }; const stateHandlerFn = (stateHandler: StatehandlerService) => { return () => { return stateHandler.initStateHandler(); }; }; @NgModule({ declarations: [ AppComponent, SignedOutComponent, UserComponent, HomeComponent, ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, OAuthModule.forRoot({ resourceServer: { allowedUrls: ['https://test.api.zitadel.caos.ch/caos.zitadel.auth.api.v1.AuthService', 'https://test.api.zitadel.caos.ch/oauth/v2/userinfo', 'https://test.api.zitadel.caos.ch/caos.zitadel.management.api.v1.ManagementService/', 'https://preview.api.zitadel.caos.ch'], sendAccessToken: true, }, }), ], providers: [ { provide: APP_INITIALIZER, useFactory: stateHandlerFn, multi: true, deps: [StatehandlerService], }, { provide: AuthConfig, useValue: authConfig, }, { provide: StatehandlerProcessorService, useClass: StatehandlerProcessorServiceImpl, }, { provide: StatehandlerService, useClass: StatehandlerServiceImpl, }, { provide: OAuthStorage, useClass: StorageService, }, ], bootstrap: [AppComponent] }) export class AppModule { }
caos/zitadel-examples
b2b-nextjs/components/ProjectItem.tsx
import { Menu, Transition } from '@headlessui/react'; import { DotsVerticalIcon } from '@heroicons/react/solid'; import dynamic from 'next/dynamic'; import { useRouter } from 'next/router'; import { Fragment } from 'react'; import localizedDate from '../lib/localized-date'; const ReactTooltip = dynamic(() => import("react-tooltip"), { ssr: false, }); export type ZitadelProjectGrant = { details: { sequence: string; creationDate: string; changeDate: string; resourceOwner: string; }; grantId: string; grantedOrgId: string; grantedOrgName: string; grantedRoleKeys: string[]; projectId: string; projectName: string; projectOwnerId: string; projectOwnerName: string; state: string; }; export default function ProjectItem({ project, }: { project: ZitadelProjectGrant; }) { const { locale } = useRouter(); return ( <a data-tip={`Actions coming soon`} className={` ${open ? "" : "text-opacity-90"} h-full w-full transition-all outline-none focus:outline-none border border-gray-200 dark:border-gray-500 dark:hover:bg-opacity-30 flex flex-col rounded-xl bg-white dark:bg-white dark:bg-opacity-20 relative p-4 py-6 pb-8 hover:shadow`} > <p className="dark:text-white text-left mb-4">{project.projectName}</p> {project.state === "PROJECT_GRANT_STATE_ACTIVE" && ( <div className="flex items-center mb-2"> <p>active</p> <div className="mx-2 h-2 w-2 rounded-full bg-green-500 shadow"></div> </div> )} {project.state === "PROJECT_GRANT_STATE_INACTIVE" && ( <div className="flex items-center mb-2"> <p>inactive</p> <div className="mx-2 h-2 w-2 rounded-full bg-red-500 shadow"></div> </div> )} <ReactTooltip backgroundColor={"#5b5d72"} effect="solid" /> <span className="text-sm text-left text-gray-500 dark:text-gray-300"> created: {localizedDate(project.details.creationDate, locale)} </span> <span className="text-sm text-left text-gray-500 dark:text-gray-300"> roles:{" "} {project?.grantedRoleKeys ? project.grantedRoleKeys.join(", ") : ""} </span> <div className="absolute bottom-0 right-0"> <Menu as="div" className="relative inline-block text-left z-10"> <div> <Menu.Button className="inline-flex px-3 py-2 justify-center text-sm font-medium rounded-md bg-opacity-20 hover:bg-opacity-30 focus:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-opacity-75"> <DotsVerticalIcon className="w-5 h-5 ml-2 -mr-1 text-violet-200 hover:text-violet-100" aria-hidden="true" /> </Menu.Button> </div> <Transition as={Fragment} enter="transition ease-out duration-100" enterFrom="transform opacity-0 scale-95" enterTo="transform opacity-30 scale-100" leave="transition ease-in duration-75" leaveFrom="transform opacity-30 scale-100" leaveTo="transform opacity-0 scale-95" > <Menu.Items className="absolute right-0 w-40 mt-2 origin-top-right bg-white dark:bg-gray-500 divide-y divide-gray-100 rounded-md shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"> <div className="px-1 py-1 "> <Menu.Item> {({ active }) => ( <a target="_blank" rel="noreferrer" href={`https://console.zitadel.ch/granted-projects/${project.projectId}/grant/${project.grantId}`} className={`${ active ? "text-black dark:text-white" : "text-gray-600 dark:text-gray-200" } group flex rounded-md items-center w-full px-2 py-2 text-sm`} > {active ? ( <i className={`text-2xl las la-edit mr-2`}></i> ) : ( <i className="text-2xl las la-edit mr-2"></i> )} Open in Console </a> )} </Menu.Item> </div> </Menu.Items> </Transition> </Menu> </div> </a> ); }
caos/zitadel-examples
b2b-nextjs/components/Layout.tsx
import Head from 'next/head'; import React, { useEffect, useState } from 'react'; import Footer from './Footer'; import Nav from './Nav'; declare const window: any; type Props = { children: any; }; type State = {}; class Layout extends React.Component<Props, State> { constructor(props: Props) { super(props); } render() { return ( <> <Head> <title>ZITADEL • B2B Demo</title> </Head> <div className="dark"> <div className="relative flex flex-col min-h-screen w-full bg-zitadelblue-800 text-white"> <Nav></Nav> <main className="flex-grow w-full pt-14"> {this.props.children} </main> <Footer></Footer> </div> </div> </> ); } } export default Layout;
caos/zitadel-examples
b2b-nextjs/pages/api/usergrants.tsx
import { NextApiRequest, NextApiResponse } from "next"; import { BearerToken, hasRole, requestAccessToken } from "../../lib/jwt"; import { handleFetchErrors } from "../../lib/middleware"; function getUserGrants( orgId: string, authorizationHeader: string ): Promise<any> { return hasRole("admin", orgId, authorizationHeader) .then((isAllowed) => { if (isAllowed) { return requestAccessToken().then((token: BearerToken) => { const request = `https://api.zitadel.ch/management/v1/users/grants/_search`; return fetch(request, { headers: { authorization: `Bearer ${token.access_token}`, "x-zitadel-org": process.env.ORG_ID, "content-type": "application/json", }, method: "POST", body: JSON.stringify({ query: { limit: 100, asc: true, }, queries: [ { projectIdQuery: { projectId: process.env.PROJECT_ID, }, }, { withGrantedQuery: { withGranted: true, }, }, ], }), }) .then(handleFetchErrors) .then((resp) => { return resp.json(); }) .then((resp) => { const grants = resp.result ? resp.result.filter((grant) => grant.orgId === orgId) : []; const newResp = { ...resp, result: grants, }; return newResp; }); }); } else { throw new Error("not allowed"); } }) .catch((error) => { throw new Error("not allowed"); }); } const handler = async (req: NextApiRequest, res: NextApiResponse) => { if (req.method === "GET") { const orgId = req.headers.orgid as string; const authorizationHeader = req.headers.authorization as string; return getUserGrants(orgId, authorizationHeader) .then((resp) => { res.status(200).json(resp); }) .catch((error) => { console.error("got an error", error); res.status(500).json(error); }); } }; export default handler;
caos/zitadel-examples
b2b-nextjs/pages/api/auth/[...nextauth].tsx
<reponame>caos/zitadel-examples<gh_stars>1-10 import NextAuth from 'next-auth'; export default NextAuth({ session: { jwt: true, maxAge: 0.5 * 24 * 60 * 60, }, callbacks: { async jwt({ token, user, account, profile, isNewUser }) { if (profile?.sub) { token.sub = profile.sub; } if (account?.accessToken) { token.accessToken = account.accessToken; } if (typeof user !== typeof undefined) { token.user = user; } return token; }, session: async function session({ session, token }) { session.accessToken = token.accessToken; session.id = token.id; session.sub = token.sub; session.user = token.user; return session; }, }, providers: [ { id: "zitadel", name: "zitadel", type: "oauth", version: "2.0", scope: "openid profile email urn:zitadel:iam:org:project:id:69234237810729019:aud", params: { grant_type: "authorization_code" }, authorizationParams: { grant_type: "authorization_code", response_type: "code", }, accessTokenUrl: "https://api.zitadel.ch/oauth/v2/token", requestTokenUrl: "https://api.zitadel.ch/oauth/v2/token", authorizationUrl: "https://accounts.zitadel.ch/oauth/v2/authorize", profileUrl: "https://api.zitadel.ch/oauth/v2/userinfo", checks: "pkce", async profile(profile: any, tokens) { const prof = { id: profile.sub, name: profile.name, email: profile.email, image: profile.picture, roles: profile["urn:zitadel:iam:org:project:roles"], preferred_username: profile.preferred_username, }; return prof; }, clientId: process.env.ZITADEL_CLIENT_ID ?? "", clientSecret: "", }, ], });
caos/zitadel-examples
b2b-nextjs/pages/index.tsx
import { useEffect, useState } from 'react'; import AuthCheck from '../components/AuthCheck'; import GrantedProjects from '../components/GrantedProjects'; import GrantRadio from '../components/GrantRadio'; import RolesCheck from '../components/RoleCheck'; import UserGrant from '../components/UserGrant'; import UserGrantTable from '../components/UserGrantTable'; import orgStore from '../lib/org'; import { ROLES } from '../lib/roles'; export default function Home() { return ( <AuthCheck> <HomePage key="grantedprojects"></HomePage> </AuthCheck> ); } function HomePage() { const org = orgStore((state) => (state as any).org); const [selected, setSelected] = useState(ROLES[0]); return ( <> <div className="py-10 pb-6 bg-gray-50 dark:bg-zitadelblue-700 border-b border-gray-200 dark:border-gray-700"> <div className="container mx-auto max-w-7xl flex justify-between flex-wrap px-6"> <div className="flex flex-col mb-4"> <div className="flex items-center mb-1"> <h1 className="text-3xl"> {org ? `${org.name} ` : null}Granted projects </h1> </div> <p className="text-black dark:text-white text-opacity-80 dark:text-opacity-80"> These are the projects on which your organization has grants (project-grants) </p> {!org && ( <p className="my-4 text-red-500"> Please select an organization in the navbar above! </p> )} <UserGrant></UserGrant> </div> <span className="flex-1"></span> <div className="flex"></div> </div> </div> <RolesCheck> <GrantRadio selected={selected} setSelected={(role) => setSelected(role)} /> {selected === ROLES[0] ? <GrantedProjects /> : null} {selected === ROLES[1] ? <UserGrantTable /> : null} </RolesCheck> </> ); }
caos/zitadel-examples
nextjs/pages/index.tsx
<reponame>caos/zitadel-examples import Head from 'next/head'; import Image from 'next/image'; import Profile from '../components/profile'; import styles from '../styles/Home.module.css'; export default function Home() { return ( <div className={styles.container}> <Head> <title>Create Next App</title> <meta name="description" content="Generated by create next app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main className={styles.main}> <h1 className={styles.title}> Welcome to <a href="https://github.com/caos/zitadel-nextjs-template">Next.js with ZITADEL!</a> </h1> <p className={styles.description}> Get started by editing{' '} <code className={styles.code}>pages/index.tsx</code> </p> <Profile /> </main> <footer className={styles.footer}> <a href="https://zitadel.ch" target="_blank" rel="noopener noreferrer" > Powered by{' '} <span className={styles.logo}> <Image src="/zitadel-logo-dark.svg" alt="Zitadel Logo" height={40} width={147.5} /> </span> </a> </footer> </div> ); }
caos/zitadel-examples
b2b-nextjs/components/AuthCheck.tsx
<gh_stars>1-10 import { signIn, useSession } from 'next-auth/react'; export default function AuthCheck(props: any) { const { data: session } = useSession(); return session && session.accessToken ? props.children : props.fallback || ( <div className="max-w-7xl mx-auto px-6 py-10"> <div className="flex flex-col items-center"> <p className="mb-4">You must be signed in!</p> <button onClick={() => signIn("zitadel" as any, { callbackUrl: "/" })} className="whitespace-nowrap py-2 px-4 md:mr-0 shadow rounded-md bg-black dark:text-white dark:bg-zitadelaccent-500 dark:hover:bg-zitadelaccent-400 text-white text-sm hidden md:block font-normal" > Login </button> </div> </div> ); }
caos/zitadel-examples
b2b-nextjs/components/FooterLink.tsx
<filename>b2b-nextjs/components/FooterLink.tsx import Link from 'next/link'; interface Props { external?: boolean; status?: boolean; href: string; children: any; } export default function FooterLink(props: Props) { return props.external ? <a href={props.href} target="_blank" rel="noreferrer" className={`my-3 ${props.status ? 'sp-status mt-0' : ''} flex items-center hover:text-purple-700 dark:hover:text-zitadelaccent-400`}> {props.children} <i className="text-xl h-5 -mt-2 ml-2 las la-external-link-alt"></i> </a> : <Link href={props.href}> <a href={props.href} className={`flex items-center my-3 hover:text-purple-700 dark:hover:text-zitadelaccent-400`}> {props.children} </a> </Link>; }
caos/zitadel-examples
angular/src/app/components/signed-out/signed-out.component.ts
<filename>angular/src/app/components/signed-out/signed-out.component.ts import { Component, OnInit } from '@angular/core'; import { AuthenticationService } from 'src/app/services/authentication.service'; @Component({ selector: 'app-signed-out', templateUrl: './signed-out.component.html', styleUrls: ['./signed-out.component.scss'] }) export class SignedOutComponent implements OnInit { constructor(private auth: AuthenticationService) { } ngOnInit(): void { } triggerAuthentication(): void { this.auth.authenticate(); } }
caos/zitadel-examples
nextjs/pages/profile.tsx
import Link from 'next/link'; import styles from '../styles/Home.module.css'; export default function ProfileView() { return ( <div className={styles.container}> <h1>Login successful</h1> <Link href="/"><button>Back to Home</button></Link> </div> ); }
caos/zitadel-examples
nextjs/components/profile.tsx
<filename>nextjs/components/profile.tsx import { signIn, signOut, useSession } from 'next-auth/client'; export default function Profile() { const [session, loading] = useSession(); return <> {!session && <> <p>Not signed in</p> <br /> <button onClick={() => signIn('zitadel', { callbackUrl: 'http://localhost:3000/profile' })}> Sign in </button> </>} {session && <> <p>Signed in as {session.user.email} <br /> </p> <button onClick={() => signOut()}>Sign out</button> </>} </>; }
caos/zitadel-examples
b2b-nextjs/components/Header.tsx
export default function Header() { return ( <div className="relative overflow-hidden"> <div className="flex max-w-7xl items-center mx-auto py-4 px-6"> <div className="my-10 md:my-20 md:mt-48 z-10 md:w-7/12"> <h1 className="font-semibold text-5xl w-5/12 md:w-full uppercase my-8"> Always run a <br /> <span className="text-purple-500 dark:text-zitadelaccent-500"> changing </span>{" "} system <span className="text-purple-500 dark:text-zitadelaccent-500"> . </span> </h1> <p className="text-lg opacity-80 dark:opacity-80 mb-8"> CAOS ltd. is a Swiss open source software company, managing, developing and operating the Identity Experience Platform ZITADEL. </p> </div> </div> <img className="z-0 absolute w-2/3 top-0 right-0 block dark:hidden" src="/waves/header-light.png" alt={`background waves`} /> <img className="z-0 absolute w-2/3 top-0 right-0 hidden dark:block" src="/waves/header.png" alt={`background waves`} /> <img className="animate-waves z-0 absolute w-2/3 -top-96 -right-40 block dark:hidden" src="/waves/right-flair-light.png" alt={`background waves`} /> <img className="animate-waves z-0 absolute w-2/3 -top-60 right-0 hidden dark:block" src="/waves/right-flair.png" alt={`background waves`} /> </div> ); }