vue#onBeforeUnmount JavaScript Examples

The following examples show how to use vue#onBeforeUnmount. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: useResizeWidth.js    From ant-simple-pro with MIT License 6 votes vote down vote up
// eslint-disable-next-line
export function useResizeWidth(fn = () => {}) {
  // eslint-disable-line
  const state = reactive({
    width: getWindowtWidth(),
    height: getWindowHeight()
  })

  function onResize() {
    state.width = getWindowtWidth()
    state.height = getWindowHeight()
    fn()
  }

  const onResizeThrottled = throttle(onResize, 300)

  onMounted(() => {
    window.addEventListener('resize', onResizeThrottled)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', onResizeThrottled)
  })

  return {
    ...toRefs(state)
  }
}
Example #2
Source File: useChartResize.js    From ant-simple-pro with MIT License 6 votes vote down vote up
export function useChartResize(chartIns) {
  function onResize() {
    chartIns.value && chartIns.value.resize()
  }

  let timer = null

  watch(
    () => store.getters.collapsed,
    () => {
      timer = window.setTimeout(() => {
        onResize()
      }, 500)
    }
  )

  onMounted(() => {
    window.addEventListener('resize', onResize)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', onResize)
    timer && clearTimeout(timer)
  })
}
Example #3
Source File: useEcharts.js    From ant-simple-pro with MIT License 5 votes vote down vote up
// import store from '@/store'

export function useEcharts(chartDOM, option) {
  const chartInstance = ref(null)

  watch(chartDOM, () => {
    renderChart() // eslint-disable-line
  })

  watch(option, () => {
    renderChart() // eslint-disable-line
  })

  onBeforeUnmount(() => {
    chartInstance.value && chartInstance.value.dispose()
  })

  function renderChart() {
    if (!chartDOM.value) {
      return
    }
    const renderedInstance = window.echarts.getInstanceByDom(chartDOM.value)
    if (renderedInstance) {
      chartInstance.value = renderedInstance
    } else {
      chartInstance.value = window.echarts.init(chartDOM.value)
    }
    if (!option.value) {
      return
    }
    chartInstance.value.setOption(option.value)
  }

  // let timer: number | null = null

  // watch(() => store.getters.collapsed, () => {
  //   timer = window.setTimeout(() => {
  //     onResize()
  //   }, 500)
  // })

  // onMounted(() => {
  //   window.addEventListener('resize', onResize)
  // })

  // onBeforeUnmount(() => {
  //   window.removeEventListener('resize', onResize)
  //   timer && clearTimeout(timer)
  // })

  // function onResize() {
  //   chartInstance && chartInstance.resize()
  // }

  return {
    chartInstance,
    renderChart
  }
}
Example #4
Source File: use-touch-ripple.js    From konsta with MIT License 5 votes vote down vote up
useTouchRipple = (elRef, props, addCondition) => {
  const context = inject('KonstaContext');
  const ripple = ref(null);
  let eventsAttached = false;

  const getEl = () => {
    if (!elRef || !elRef.value) return null;
    let el = elRef.value;
    if (el.$el) el = el.$el;
    return el;
  };

  const theme = () => {
    let value = context.value.theme || 'ios';
    if (props.ios) value = 'ios';
    if (props.material) value = 'material';
    return value;
  };
  const needsTouchRipple = () => {
    return (
      theme() === 'material' &&
      props.touchRipple &&
      (addCondition ? addCondition() : true)
    );
  };
  const removeRipple = () => {
    if (ripple.value) ripple.value.remove();
    ripple.value = null;
  };

  const onPointerDown = (e) => {
    ripple.value = new TouchRipple(getEl(), e.pageX, e.pageY);
  };
  const onPointerMove = () => {
    removeRipple();
  };
  const onPointerUp = () => {
    removeRipple();
  };

  const attachEvents = () => {
    if (!context.value.touchRipple || eventsAttached) return;
    eventsAttached = true;
    const el = getEl();
    el.addEventListener('pointerdown', onPointerDown);
    el.addEventListener('pointermove', onPointerMove);
    el.addEventListener('pointerup', onPointerUp);
  };
  const detachEvents = () => {
    eventsAttached = false;
    const el = getEl();
    el.removeEventListener('pointerdown', onPointerDown);
    el.removeEventListener('pointermove', onPointerMove);
    el.removeEventListener('pointerup', onPointerUp);
  };

  watch(
    () => needsTouchRipple(),
    (newV) => {
      if (newV) attachEvents();
      else detachEvents();
    }
  );

  onMounted(() => {
    if (!getEl() || !needsTouchRipple()) return;
    attachEvents();
  });

  onBeforeUnmount(() => {
    if (!getEl() || !needsTouchRipple()) return;
    detachEvents();
  });
}
Example #5
Source File: spatial-query3d.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
function spatialQuery3d(props) {

    // 设置默认值数据
    let state = reactive({
        layerNames: [],   //当前存在的可选择图层
        selectedLayerName: null,  //默认选择图层名称
        scale: 3,   //缩放
        positionMode: "intersects",   //位置模式

        Xpitch: 0,   //x旋转
        Yroll: 0,     //y旋转
        Zheading: 0,     //z旋转
        geometryType: "box",   //选择模型类型
        drawType: "Fill_And_WireFrame",   //模型显示类型
        FillColor: "rgba(192,211,25,0.5)",   //模型填充颜色
        WireFrameColor: "rgba(89,129,228,0.8)",  // 模型线框颜色
        searchColor: "rgba(255, 186, 1, 1)",   //查询结果颜色
        GeometryBodyNames: [], //场景存在的天际线体对象等存在的数组
        //默认geometry参数
        boxParameters: [100, 100, 100],
        sphereParameters: [100],
        coneParameters: [100, 200],
        cylinderParameters: [100, 100, 200],
        ellicpseParameters: [100, 50, 50],
        rotateOrigin: null,
    });

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let scene, tipFlag = true;
    let layers, spatialQuery;
    let geometry, GeometryBodys = [];

    let editEntity, s3mInstanceColc;
    let modelUrl = 'public/data/s3m/box.s3m';
    let modelEditor;

    if (storeState.isViewer) {
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
        init();
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
            init();
        }
    });
    //监听图层加载完成
    watch(() => storeState.changeLayers, val => {
        getLayerNames();
    });
    if (storeState.changeGeometrys) {
        setGeometryBodys()
    }
    //监听场景存在其他三维体
    watch(() => storeState.changeGeometrys, val => {
        setGeometryBodys()
    });

    function setGeometryBodys() {
        state.GeometryBodyNames = [];
        GeometryBodys = [];
        if (storeDate.geometrys) {
            for (const key in storeDate.geometrys) {
                GeometryBodys.push(key);
                let name = storeDate.geometrys[key].name;
                if (!state.GeometryBodyNames.includes(name)) {
                    state.GeometryBodyNames.push(name)
                }
            }
        }
        if (state.GeometryBodyNames.length === 0) {
            if (props && props.geometryType) {
                state.geometryType = props.geometryType
            } else {
                state.geometryType = 'box'
            }

        }
    }


    function init() {
        scene = viewer.scene;
        layers = viewer.scene.layers.layerQueue;
        spatialQuery = new Cesium.SpatialQuery3D(scene);
        spatialQuery.outlineColor = Cesium.Color.fromCssColorString(
            state.WireFrameColor
        );
        spatialQuery.fillColor = Cesium.Color.fromCssColorString(
            state.FillColor
        );
        spatialQuery.fillStyle = Cesium.FillStyle[state.drawType];
        getGeometry(state.geometryType);
        getPositionMode(state.positionMode);
        spatialQuery.build();
        setTimeout(() => {
            if (state.layerNames.length === 0) {
                getLayerNames();
            }
        }, 1000);
        
        s3mInstanceColc = new Cesium.S3MInstanceCollection(scene._context);
        viewer.scene.primitives.add(s3mInstanceColc);
    };

    function getLayerNames() {
        let layer = getLayer(state.selectedLayerName);
        if (spatialQuery && spatialQuery.layers) {
            spatialQuery.layers = layer ? [layer] : []
        }
        state.layerNames.length = 0;
        if (layers && layers.length > 0) {
            layers.forEach((element, index) => {
                if (!state.layerNames.includes(element._name)) {
                    state.layerNames.push(element._name);
                }
            });
            if (!state.selectedLayerName) {
                state.selectedLayerName = state.layerNames[0]
            }
        }
    }


    /*
     ***分析模块***
    */


    //分析
    function analysis() {
        try {
            let layer = getLayer(state.selectedLayerName);
            if (!layer) {
                tool.Message.warnMsg('请选择需要查询的图层!')
                return;
            }
            spatialQuery.layers = [layer];
            tooltip.setVisible(false);
            layer.selectedColor = Cesium.Color.fromCssColorString(state.searchColor);
            layer.selectColorType = Cesium.SelectColorType.REPLACE;
            layer.selectEnabled = false;
            console.log(spatialQuery.geometry)
            if (typeof (state.geometryType) === 'number') {      //三维体查询,目前只支持这两种
                getGeometry(state.geometryType);
                spatialQuery.build();
                return;
            }
            spatialQuery.build();
            viewer.enableCursorStyle = false;
            viewer._element.style.cursor = "";
            document.body.classList.add("measureCur");
            if (tipFlag) {   //只提示一次
                window.tooltip.showAt(' <p>点击鼠标左键确认查询位置</p>', '300px');
                tipFlag = false
            }
            //鼠标左键事件监听
            viewer.eventManager.addEventListener("CLICK", LEFT_CLICK, true);
        } catch (err) {
            console.error(err)
        }
    };

    function LEFT_CLICK(e) {
        document.body.classList.remove("measureCur");
        // 获取鼠标点击的笛卡尔坐标
        let cartesian = scene.pickPosition(e.message.position);
        let position = tool.CartesiantoDegrees(cartesian) // 将获取的点的位置转化成经纬度
        setPosition(position);
        // let h = position[2] + 60;
        // addModel(Cesium.Cartesian3.fromDegrees(position[0], position[1], h)); //添加编辑模型
        tooltip.setVisible(false);
        viewer.eventManager.removeEventListener("CLICK", LEFT_CLICK); //移除鼠标点击事件监听
    }

    function getLayer(layerName) {
        return layers.find(function (item, index) {
            return item._name === layerName
        })
    };
    function getQueryIDs() {
        return spatialQuery.getQueryIDs();
    };

    function getGeometry(geometryType) {
        switch (geometryType) {
            case "box":
                {
                    let p = state.boxParameters;
                    geometry = new Cesium.GeoBox(p[0], p[1], p[2]);
                }
                break;
            case "sphere":
                {
                    let p = state.sphereParameters;
                    geometry = new Cesium.GeoSphere(p[0]);
                }
                break;
            case "cone":
                {
                    let p = state.coneParameters;
                    geometry = new Cesium.GeoCone(p[0], p[1]);
                    if (state.rotateOrigin) {
                        geometry.rotateOrigin = getRotateOrigin();
                    }
                }
                break;
            case "cylinder":
                {
                    let p = state.cylinderParameters;
                    geometry = new Cesium.GeoCylinder(p[0], p[1], p[2]);
                }
                break;
            case "ellicpse":
                {
                    let p = state.ellicpseParameters;
                    geometry = new Cesium.GeoEllipsoid(p[0], p[1], p[2]);
                }
                break;
            default:
                {
                    geometry = new Cesium.GeoModel3D();
                    geometry.geoModel = storeDate.geometrys['SkyLineBody'];
                    spatialQuery.clear()
                }
                break;

        }
        spatialQuery.geometry = geometry;
    };
    //获取圆锥绕点旋转方式
    function getRotateOrigin() {
        let r = state.rotateOrigin;
        if (r == "APEX") {
            return Cesium.RotationOrigin.APEX;
        } else {
            return Cesium.RotationOrigin.CENTER;
        }
    };
    function getPositionMode(positionMode) {
        let mode;
        switch (positionMode) {
            case "intersects":
                mode = Cesium.PositionMode.Intersects;
                break;
            case "disjoint":
                mode = Cesium.PositionMode.Disjoint;
                break;
            case "contains":
                mode = Cesium.PositionMode.Contains;
                break;
            default:
                mode = Cesium.PositionMode.Intersects;
                break;
        }
        spatialQuery.positionMode = mode;
    };

    //设置查询中心点位置,可用于动态改变如机场预警范例
    function setPosition(newPosArr) {
        //传入经纬度数组
        if (spatialQuery && spatialQuery.geometry) {
            spatialQuery.geometry.geoPosition = new Cesium.Point3D(
                newPosArr[0],
                newPosArr[1],
                newPosArr[2]
            );
        }
    };

    function addModel(centerPositions) {
        s3mInstanceColc.add(modelUrl, {
            id: 'spatialQuery-model',
            position: centerPositions,
            // hpr: new Cesium.HeadingPitchRoll(heading, 0, 0),
            // color:Cesium.Color.RED,
            scale: new Cesium.Cartesian3(0.1, 0.1, 0.1),
        });
        editEntity = s3mInstanceColc.getInstance(modelUrl, 'spatialQuery-model');
        if (!modelEditor) addModelEditor(editEntity);
        else {
            modelEditor.setEditObject(editEntity);
            modelEditor.activate();
        }
    }

    function addModelEditor(model) {
        modelEditor = new Cesium.ModelEditor({
            model: model,
            scene: viewer.scene,
            axesShow: {
                "translation": true,
                "rotation": true,
                "scale": false
            }
        });
        modelEditor.activate();
        modelEditor.changedEvt.addEventListener((param) => {
            console.log(param)
            let Cartesian3 = new Cesium.Cartesian3();
            Cesium.Matrix4.getTranslation(param.modelMatrix, Cartesian3);
            if (Cartesian3) {
            
            }
        })
    }

    // 清除
    function clear() {
        let layer = getLayer(state.selectedLayerName);
        console.log(layer)
        if (layer) {
            layer.selectedColor = new Cesium.Color(0.7, 0.7, 1, 1);
            layer.setSelection([]);
            layer.selectColorType = Cesium.SelectColorType.MIX;
        }
        spatialQuery.clear();
        tooltip.setVisible(false);
        document.body.classList.remove("measureCur");
        spatialQuery.geometry.geoPosition = new Cesium.Point3D(0, 0, 0);
        viewer.eventManager.removeEventListener("CLICK", LEFT_CLICK); //移除鼠标点击事件监听
    };

    // 监听
    watch(() => state.Xpitch, val => {
        if (val == "") return;
        geometry.geoRotationX = parseFloat(val);
    });
    watch(() => state.Yroll, val => {
        if (val == "") return;
        geometry.geoRotationY = parseFloat(val);
    });
    watch(() => state.Zheading, val => {
        if (val == "") return;
        geometry.geoRotationZ = parseFloat(val);
    });
    watch(() => state.scale, val => {
        if (val == "") return;
        geometry.geoScaleX = parseFloat(val);
        geometry.geoScaleY = parseFloat(val);
        geometry.geoScaleZ = parseFloat(val);
    });
    watch(() => state.positionMode, val => {
        if (val == "") return;
        getPositionMode(val)
    });
    watch(() => state.geometryType, val => {
        if (val === "") return;
        getGeometry(val)
    });
    watch(() => state.drawType, val => {
        if (val == "") return;
        spatialQuery.fillStyle = Cesium.FillStyle[val];
    });
    watch(() => state.FillColor, val => {
        if (val == "") return;
        spatialQuery.fillColor = Cesium.Color.fromCssColorString(val);
    });
    watch(() => state.WireFrameColor, val => {
        if (val == "") return;
        spatialQuery.outlineColor = Cesium.Color.fromCssColorString(val);
    });
    watch(() => state.searchColor, val => {
        if (val == "") return;
        getLayer(state.selectedLayerName).selectedColor = Cesium.Color.fromCssColorString(val);
    });
    watch(() => state.selectedLayerName, (val, oldval) => {
        let layer = getLayer(oldval);
        if (layer) {
            layer.selectedColor = new Cesium.Color(0.7, 0.7, 1, 1);
            layer.setSelection([]);
            layer.selectColorType = Cesium.SelectColorType.MIX;
        }
        clear()
    });

    // 销毁
    onBeforeUnmount(() => {
        spatialQuery.destroy();
        spatialQuery = undefined;
        layers = undefined;
        geometry = undefined;
    })

    return {
        ...toRefs(state),
        setPosition,
        getQueryIDs,
        analysis,
        clear
    };
}
Example #6
Source File: s3mlayer-operation.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
//语言资源

function s3mlayerOperation(props) {

    // 设置默认值数据
    let state = reactive({
        layerNames: [],   //当前存在的可选择s3m图层
        selectedLayerName: 'none',  //默认选择图层名称
        selectedoffset: false,  //选中偏移
        offsetX: 0,  //沿X轴偏移
        offsetY: 0,  //沿Y轴偏移
        offsetZ: 0,  //沿Z轴偏移
        polygonOffset: false,  //多边形偏移
        polygonOffsetFactor: 0,  //偏移因子
        polygonOffsetUnit: 0,  //偏移单位
    })

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let layers, scene, selectedLayer;
    if (storeState.isViewer) {
        getLayerNames();
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            getLayerNames();
        }
    });

    //监听图层加载完成
    watch(() => storeState.changeLayers, val => {
        getLayerNames();
    });

    //初始化图层
    function getLayerNames() {
        scene = viewer.scene;
        layers = viewer.scene.layers.layerQueue;
        if (layers && layers.length > 0) {
            layers.forEach((element, index) => {
                if (!state.layerNames.includes(element._name)) {
                    state.layerNames.push(element._name);
                }
            });
            if (state.selectedLayerName = 'none') {
                state.selectedLayerName = state.layerNames[0];
                selectedLayer = layers[0];
            }
        }
    }

    function setObjsOffset() {
        let ids = selectedLayer.getSelection()
        selectedLayer.removeAllObjsOffset(); // 移除所有图元的偏移
        if (ids.length > 0) {
            selectedLayer.setObjsOffset(ids);
        }
    }

    // 销毁
    onBeforeUnmount(() => {
        layers = scene = null;
    });


    // 监听
    watch(() => state.selectedLayerName, val => {
        let index = state.layerNames.indexOf(val)
        if (index == -1) return;
        selectedLayer = layers[index];
    });
    watch(() => state.selectedoffset, val => {
        if (!selectedLayer) return;
        if (val) {
            let xOffset = Number(state.offsetX);
            let yOffset = Number(state.offsetY);
            let zOffset = Number(state.offsetZ);
            selectedLayer.selectedTranslate = new Cesium.Cartesian3(
                xOffset,
                yOffset,
                zOffset
            );
            viewer.eventManager.addEventListener("CLICK", setObjsOffset, true);
            setObjsOffset()
        } else {
            viewer.eventManager.removeEventListener("CLICK", setObjsOffset);
            selectedLayer.selectedTranslate = new Cesium.Cartesian3(0, 0, 0);
            selectedLayer.removeAllObjsOffset();
            selectedLayer.releaseSelection(); // 释放选择集
        }
    });
    watch(() => state.offsetX, val => {
        if (state.selectedoffset) {
            let xOffset = Number(val);
            let yOffset = Number(state.offsetY);
            let zOffset = Number(state.offsetZ);
            selectedLayer.selectedTranslate = new Cesium.Cartesian3(
                xOffset,
                yOffset,
                zOffset
            );
        }
    });
    watch(() => state.offsetY, val => {
        if (state.selectedoffset) {
            let xOffset = Number(state.offsetX);
            let yOffset = Number(state.offsetY);
            let zOffset = Number(state.offsetZ);
            selectedLayer.selectedTranslate = new Cesium.Cartesian3(
                xOffset,
                yOffset,
                zOffset
            );
        }
    });
    watch(() => state.offsetZ, val => {
        if (state.selectedoffset) {
            let xOffset = Number(state.offsetX);
            let yOffset = Number(state.offsetY);
            let zOffset = Number(state.offsetZ);
            selectedLayer.selectedTranslate = new Cesium.Cartesian3(
                xOffset,
                yOffset,
                zOffset
            );
        }
    });
    watch(() => state.polygonOffset, val => {
        if (!selectedLayer) return;
        if (val) {
            selectedLayer.setPolygonoffset(
                Number(state.polygonOffsetFactor),
                Number(val)
            );
        } else {
            selectedLayer.setPolygonoffset(0, 0);
        }
    });

    watch(() => state.polygonOffsetFactor, val => {
        if (selectedLayer && state.polygonOffset)
            selectedLayer.setPolygonoffset(
                Number(val),
                Number(state.polygonOffsetUnit)
            );
    });
    watch(() => state.polygonOffsetUnit, val => {
        if (selectedLayer && state.polygonOffset)
            selectedLayer.setPolygonoffset(
                Number(state.polygonOffsetFactor),
                Number(val)
            );
    });


    return {
        ...toRefs(state),
    };
}
Example #7
Source File: s3mlayer-style.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
//语言资源

function s3mlayerStyle(props) {

    // 设置默认值数据
    let state = reactive({
        layerNames: [],   //当前存在的可选择s3m图层
        selectedLayerName: 'none',  //默认选择图层名称
        foreColor: "#ffffff",  //前景色
        lineColor: "rgba(27, 27, 27, 1)",  //线颜色
        selectedColor: "#A40FF4",  //选中色
        selectColorMode: 'mix',  //选中色模式
        bottomAltitude: 0,  //底部高程
        LODScale: 5,  //LOD
        layerTrans: 1,  //图层透明度
        fillStyle: 'fill',//填充风格
        visibleDistanceMin: 0,  //最小可见距离
        visibleDistanceMax: 10000,  //最大可见距离
    })

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let layers, scene, selectedLayer;


    if (storeState.isViewer) {
        getLayerNames();
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            getLayerNames();
        }
    });

    //监听图层加载完成
    watch(() => storeState.changeLayers, val => {
        getLayerNames();
    });

    //初始化图层
    function getLayerNames() {
        scene = viewer.scene;
        layers = viewer.scene.layers.layerQueue;
        if (layers && layers.length > 0) {
            layers.forEach((element, index) => {
                if (!state.layerNames.includes(element._name)) {
                    state.layerNames.push(element._name);
                }
            });
            if (state.selectedLayerName = 'none') {
                state.selectedLayerName = state.layerNames[0];
                selectedLayer = layers[0];
            }
        }
    }


    // 销毁
    onBeforeUnmount(() => {
        layers = scene = null;
    });


    // 监听
    watch(() => state.selectedLayerName, val => {
        let index = state.layerNames.indexOf(val)
        if (index == -1) return;
        selectedLayer = layers[index];
    });
    watch(() => state.foreColor, val => {
        if (selectedLayer)
            selectedLayer.style3D.fillForeColor = Cesium.Color.fromCssColorString(
                val
            );
    });
    watch(() => state.lineColor, val => {
        if (selectedLayer)
            selectedLayer.style3D.lineColor = Cesium.Color.fromCssColorString(
                val
            );
    });
    watch(() => state.selectedColor, val => {
        if (selectedLayer)
            selectedLayer.selectedColor = Cesium.Color.fromCssColorString(
                val
            );
    });
    watch(() => state.selectColorMode, val => {
        if (selectedLayer)
            selectedLayer.selectColorType = val === 'mix' ? 0 : 1;
    });
    watch(() => state.bottomAltitude, val => {
        if (selectedLayer)
            selectedLayer.style3D.bottomAltitude = Number(val);
        selectedLayer.refresh();
    });
    watch(() => state.fillStyle, val => {
        if (selectedLayer)
            switch (val) {
                case "fill":
                    selectedLayer.style3D.fillStyle = Cesium.FillStyle.Fill;
                    break;
                case "wireframe":
                    selectedLayer.style3D.fillStyle = Cesium.FillStyle.WireFrame;
                    selectedLayer.style3D.lineColor = Cesium.Color.fromCssColorString(
                        state.lineColor
                    );
                    break;
                case "fill-and-wireframe":
                    selectedLayer.style3D.fillStyle =
                        Cesium.FillStyle.Fill_And_WireFrame;
                    selectedLayer.style3D.lineColor = Cesium.Color.fromCssColorString(
                        state.lineColor
                    );
                    break;
                default:
                    break;
            }
        selectedLayer.refresh();
    });
    watch(() => state.LODScale, val => {
        if (selectedLayer)
            selectedLayer.lodRangeScale = Number(val);
    });
    watch(() => state.layerTrans, val => {
        if (selectedLayer)
            selectedLayer.style3D.fillForeColor.alpha = Number(val);
    });
    watch(() => state.visibleDistanceMin, val => {
        if (val == "") {
            val = 0.0;
        }
        if (selectedLayer)
            selectedLayer.visibleDistanceMin = Number(val);
    });

    watch(() => state.visibleDistanceMax, val => {
        if (val == "") {
            val = this.maxNumber;
        }
        if (selectedLayer)
            selectedLayer.cullEnabled = val;
        selectedLayer.visibleDistanceMax = Number(val);

    });



    return {
        ...toRefs(state),
    };
}
Example #8
Source File: geological-body.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
// import models from './models.js'


function scanEffect(props) {
    // 设置默认值数据
    let state = reactive({
        operationType: 'stretch_cut',  //操作类型
        stretchHeight: 1,  //拉伸高度
        modelUrls: null,  //模型配置
        digHeight: 500,
        drillRadius: 400,
        drillHeight: 2000,
        clipType: 'drawClip',
        drawClipMode: 'KeepInside',
    });
    state.modelUrls = [
        {
            id: 1,
            model: "http://www.supermapol.com/realspace/services/data-dizhiti/rest/data/datasources/%E5%9C%B0%E8%B4%A8%E4%BD%93/datasets/Layer1/features/1.stream",
            color: new Cesium.Color(179 / 255, 179 / 255, 179 / 255, 1)
        },
        {
            id: 2,
            model:  "http://www.supermapol.com/realspace/services/data-dizhiti/rest/data/datasources/%E5%9C%B0%E8%B4%A8%E4%BD%93/datasets/Layer2/features/1.stream",
            color: new Cesium.Color(94 / 255, 179 / 255, 59 / 255, 1)
        },
        {
            id: 3,
            model: "http://www.supermapol.com/realspace/services/data-dizhiti/rest/data/datasources/%E5%9C%B0%E8%B4%A8%E4%BD%93/datasets/Layer3/features/1.stream",
            color: new Cesium.Color(52 / 255, 94 / 255, 35 / 255, 1)
        },
        {
            id: 4,
            model: "http://www.supermapol.com/realspace/services/data-dizhiti/rest/data/datasources/%E5%9C%B0%E8%B4%A8%E4%BD%93/datasets/Layer4/features/1.stream",
            color: new Cesium.Color(115 / 255, 115 / 255, 115 / 255, 1)
        },
        {
            id: 5,
            model: "http://www.supermapol.com/realspace/services/data-dizhiti/rest/data/datasources/%E5%9C%B0%E8%B4%A8%E4%BD%93/datasets/Layer5/features/1.stream",
            color: new Cesium.Color(171 / 255, 85 / 255, 66 / 255, 1)
        },
        {
            id: 6,
            model:  "http://www.supermapol.com/realspace/services/data-dizhiti/rest/data/datasources/%E5%9C%B0%E8%B4%A8%E4%BD%93/datasets/Layer6/features/1.stream",
            color: new Cesium.Color(68 / 255, 68 / 255, 68 / 255, 1)
        }
    ];

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let scene, solidModelsProfile, entitie_ids = [];  //剖切
    let drillConeCounts = 0, drillPoints = [];  //钻孔
    let editorBox, geoBox;  //裁剪

    if (storeState.isViewer) {
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
        init()
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
            init()
        }
    });

    function init() {
        scene = viewer.scene;
        scene.logarithmicDepthBuffer = true;
        scene.camera.frustum.near = 0.1;
        scene.globe.show = false;
        viewer.scene.skyAtmosphere.show = false;
        solidModelsProfile = new Cesium.SolidModelsProfile(scene);
        solidModelsProfile.addModels(state.modelUrls);
        console.log(solidModelsProfile)
        solidModelsProfile.addedEvent.addEventListener((param)=>{
            console.log(solidModelsProfile._s3mInstanceCollection.getInstance(state.modelUrls[2].model,3))
        })
          viewer.scene.camera.setView({
            destination: new Cesium.Cartesian3(-2167835.4408299956, 4423497.534529096, 4095839.2845661934),
            orientation: {
                heading: 4.029329438295484,
                pitch: -0.23796647219353817,
                roll: 8.994289757424667e-10
            }
        });
    };

    // 拉伸剖切
    function drawLine() {
        if (!window.handlerPolyline) {
            initHandler("Polyline");
        }
        window.tooltip.showAt(' <p>点击鼠标左键开始绘制</p><p>鼠标右键结束绘制</p><p>可以绘制多条线段</p>', '350px');
        handlerDrawing("Polyline").then(
            res => {
                addCutLine(res.result.object.positions)
                let handlerPolyline = window.handlerPolyline;
                handlerPolyline.polyline.show = false;
                // window.polylineTransparent.show = false; //半透线隐藏
                handlerPolyline.deactivate();
                tooltip.setVisible(false);

                let id = 'geologicalbody_cutline-' + new Date().getTime()
                entitie_ids.push(id);
                viewer.entities.add({
                    id: id,
                    polyline: {
                        positions: res.result.object.positions,
                        width: 2,
                        material: Cesium.Color.fromCssColorString('#51ff00'),
                        // clampToGround: true, //线贴地
                        // classificationType: Cesium.ClassificationType.S3M_TILE, //线面贴对象
                    },
                });
            },
            (err) => {
                console.log(err);
            }
        );
        window.handlerPolyline.activate();

    }
    function addCutLine(positions) {
        let pointArray = [];
        if (positions.length < 2) return;
        for (let i = 0; i < positions.length - 1; i++) {
            pointArray.length = 0;
            pointArray.push(positions[i]);
            pointArray.push(positions[i + 1]);
            solidModelsProfile.addProfileGeometry(pointArray);
        }
    }
    function startCut() {
        tooltip.setVisible(false);
        clearHandlerDrawing('Polyline');
        if (entitie_ids.length === 0) {
            window.tooltip.showAt(' <p>请先绘制剖切的线段</p>', '350px');
            return;
        }
        solidModelsProfile.build();
    }
    function clearCut() {
        tooltip.setVisible(false);
        solidModelsProfile.clearProfile();
        clearHandlerDrawing('Polyline');
        entitie_ids.forEach((id) => { viewer.entities.removeById(id); })
        entitie_ids.length = 0;
    }


    //开挖

    function addProfileGeometry(positions) {
        let point3ds = new Cesium.Point3Ds();
        let points = tool.CartesiantoDegreesObjs(positions);
        points.forEach((point) => {
            let point3d = new Cesium.Point3D(point.longitude, point.latitude, point.height + 1000);
            point3ds.add(point3d);
        })
        let geometry = new Cesium.GeoRegion3D([point3ds]);
        if (state.operationType === 'dig') {
            solidModelsProfile.clippingType = Cesium.ClippingType.KeepOutside;
            geometry.extrudedHeight = -Number(state.digHeight);
            //封底
            let geometry2 = new Cesium.GeoRegion3D([point3ds]);
            geometry2.isLatLon = false;
            geometry2.bottomAltitude = geometry.extrudedHeight;
            solidModelsProfile.addProfileGeometry(geometry2);
        } else {
            // solidModelsProfile.clippingType = Cesium.ClippingType.KeepOutside;
            geometry.extrudedHeight = -7000;
        }
        geometry.isLatLon = false;
        solidModelsProfile.setClipGeometry(geometry);
        //封边
        for (let i = 0; i < positions.length; i++) {
            let singleA = [];
            singleA.push(positions[i]);
            if (i == positions.length - 1) {
                singleA.push(positions[0]);
            } else {
                singleA.push(positions[i + 1]);
            }
            solidModelsProfile.addProfileGeometry(singleA);
            solidModelsProfile.build();
        }
    }

    function drawPolygon() {
        if (!window.handlerPolygon) {
            initHandler("Polygon");
        }
        handlerDrawing("Polygon", false).then(
            res => {
                let handlerPolygon = window.handlerPolygon;
                addProfileGeometry(res.result.object.positions);
                handlerPolygon.polygon.show = false;
                handlerPolygon.polyline.show = false;
                handlerPolygon.deactivate();
            },
            err => {
                console.log(err);
            }
        );
        window.handlerPolygon.activate();
    };

    function startDig() {
        clearDig();
        drawPolygon()
    }

    function clearDig() {
        tooltip.setVisible(false);
        solidModelsProfile.clearProfile();
        clearHandlerDrawing();
    }

    //钻孔
    function startDrilling() {
        clearDrilling();
        viewer.enableCursorStyle = false;
        viewer._element.style.cursor = "";
        document.body.classList.add("measureCur");
        window.tooltip.showAt(' <p>点击鼠标左键确认钻孔位置</p><p>鼠标右键结束绘制并执行钻孔</p>', '350px');
        console.log(1)
        viewer.eventManager.addEventListener("CLICK", click_point, true);
        viewer.eventManager.addEventListener("RIGHT_CLICK", click_right, true);
    };

    function click_point(e) {
        let position = viewer.scene.pickPosition(e.message.position);
        addDrillCone(position);
        drillPoints.push(position)
    }

    function click_right(e) {
        window.tooltip.setVisible(false);
        document.body.classList.remove("measureCur");
        let points = tool.CartesiantoDegreesObjs(drillPoints);
        points.forEach((point) => {
            let geoCylinder = new Cesium.GeoCylinder(Number(state.drillRadius), Number(state.drillRadius), Number(state.drillHeight));
            let height = Number(state.drillHeight)/2;
            geoCylinder.geoPosition = new Cesium.Point3D(point.longitude, point.latitude, point.height-height);
            solidModelsProfile.addProfileGeometry(geoCylinder);
        })
        for (let i = 1; i <= drillConeCounts; i++) {
            viewer.entities.removeById('Drill_Point-' + i);
        }
        solidModelsProfile.build();
        viewer.eventManager.removeEventListener("CLICK", click_point);
        viewer.eventManager.removeEventListener("RIGHT_CLICK", click_right);
    }

    function clearDrilling() {
        tooltip.setVisible(false);
        solidModelsProfile.clearProfile();
        document.body.classList.remove("measureCur");
        for (let i = 1; i <= drillConeCounts; i++) {
            viewer.entities.removeById('Drill_Point-' + i);
        }
        viewer.eventManager.removeEventListener("CLICK", click_point);
        viewer.eventManager.removeEventListener("RIGHT_CLICK", click_right);
        drillConeCounts = 0;
        drillPoints.length = 0;
    }
    // 绘制转空点
    function addDrillCone(position) {
        drillConeCounts++;
        viewer.entities.add({
            id: 'Drill_Point-' + drillConeCounts,
            position: position,
            cylinder: {
                length: 100,
                topRadius: Number(state.drillRadius),
                bottomRadius: Number(state.drillRadius),
                material: Cesium.Color.fromCssColorString("#d60000"),
            }
        });
    }

    //裁剪
    function startClip() {
        clearClip();
        solidModelsProfile.clippingType = Cesium.ClippingType[state.drawClipMode];
        if (state.clipType === 'drawClip') {
            drawPolygon()
            return;
        }
        BoxClipByEitor()
    }

    function clearClip() {
        clearDig();
        clearHandlerDrawing('Box');
        if (editorBox) {
            editorBox.deactivate();
            editorBox.destroy()
            editorBox = null;
        }
    }

    //box裁剪

    function BoxClipByEitor() {
        if (editorBox) {
            editorBox.deactivate();
        }
        tooltip.showAt(' <p>点击鼠标左键开始绘制box底面</p><p>然后移动鼠标绘制box高度</p><p>点击鼠标右键结束绘制</p>', '350px');
        if (!window.handlerBox) {
            initHandler("Box");
        }
        handlerDrawing("Box", false).then(
            res => {
                let handlerBox = window.handlerBox;
                updateClipBox(res.result.object);
                handlerBox.deactivate();
            },
            err => {
                console.log(err);
            }
        );
        window.handlerBox.activate();
    };

    function updateClipBox(object) {
        object.show = false;
        //绘制的盒子裁剪模型
        let newDim = object.box.dimensions.getValue();
        let position = Cesium.Cartographic.fromCartesian(object.position.getValue(0));
        geoBox = new Cesium.GeoBox(newDim.x, newDim.y, newDim.z);
        geoBox.geoPosition = new Cesium.Point3D(Cesium.Math.toDegrees(position.longitude),
            Cesium.Math.toDegrees(position.latitude), position.height);
        solidModelsProfile.addProfileGeometry(geoBox);
        solidModelsProfile.build();
        // 编辑盒子
        if(!editorBox){
            editorBox = new Cesium.BoxEditor(viewer, object);
            editorBox.color = Cesium.Color.WHITE.withAlpha(0.0);//设置盒子透明
            editorBox.hoverColor = Cesium.Color.BLUE;//设置编辑轴的选中色
            let editBoxEvt = function (e) {
                let newDim = e.dimensions;
                geoBox.geoWidth = newDim.y;
                geoBox.geoHeight = newDim.z;
                geoBox.geoLength = newDim.x;
                let position = tool.CartesiantoDegrees(e.position);
                geoBox.geoPosition = new Cesium.Point3D(position[0],position[1],position[2]);
                geoBox.geoRotationZ = editorBox.hpr.heading  * (180 / Cesium.Math.PI);
            };
            editorBox.editEvt.addEventListener(editBoxEvt);
        }else{
            editorBox.setEditObject(object) //
        }
        editorBox.activate();
    }


    //叠加体元



    function clearAll() {
        clearCut();
        clearClip();
        clearDrilling()
    }

    // 监听
    watch(() => state.modelUrls, val => {
        solidModelsProfile.addModels(val);
    });
    watch(() => state.stretchHeight, val => {
        if (!state.modelUrls || state.modelUrls.length == 0) return;
        for (let model of state.modelUrls) {
            let url = model.model;
            let instance = solidModelsProfile._s3mInstanceCollection._group[url].instances._array[0];
            instance.updateScale(new Cesium.Cartesian3(1, 1, Number(val)));
        }
    });
    watch(() => state.operationType, val => {
        clearAll();
    });
    watch(() => state.drawClipMode, val => {
        solidModelsProfile.clippingType = Cesium.ClippingType[val];
    });
    watch(() => state.clipType, val => {
        clearClip()
    });
    // 销毁
    onBeforeUnmount(() => {
        solidModelsProfile.clear()
        viewer.scene.globe.show = true;
        viewer.scene.skyAtmosphere.show = true;
        clearAll();
        scene = null;
        solidModelsProfile = null;
        geoBox= null;
    });


    return {
        ...toRefs(state),
        drawLine,
        startCut,
        clearCut,
        startDig,
        clearDig,
        startDrilling,
        clearDrilling,
        startClip,
        clearClip,
    };
}
Example #9
Source File: compass.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
//语言资源

function compass(props) {

    // 设置默认值数据
    let state = reactive({
        resetPosition: '',  //重置初始位置fromDegrees
        isfull: false,  //全屏标志
    });

    state.resetPosition = new Cesium.Cartesian3.fromDegrees(
        110.60396458865515,
        34.54408834959379,
        30644793.325518917
    );

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }
    if (state.isfull) fullscreenchange()

    // 初始化数据
    let scene, scratchWindowPosition;
    let compass_dom = ref(null);
    let zoomIn_timer, zoomOut_timer;
    let isFlyCircle = false;

    if (storeState.isViewer) {
        scene = viewer.scene;
        initCompass()
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            scene = viewer.scene;
            initCompass()
        }
    });

    //初始化控件
    function initCompass() {
        scratchWindowPosition = new Cesium.Cartesian2();  //获取屏幕中心点
        scratchWindowPosition.x = scene.canvas.clientWidth / 2;
        scratchWindowPosition.y = scene.canvas.clientHeight / 2;
        scene.postRender.addEventListener(listener);  //监听指北针转动
        window.addEventListener('resize', function () {
            scratchWindowPosition.x = scene.canvas.clientWidth / 2;
            scratchWindowPosition.y = scene.canvas.clientHeight / 2;
        });
    };

    //监听指北针转动
    function listener() {
        let heading = scene.camera.heading;
        let x = -Cesium.Math.toDegrees(heading);
        let degrees = "rotate(" + x + "deg)";
        compass_dom.value.style.transform = degrees;
        if (!isFlyCircle) return;
        if (heading <= 0.05 || heading >= 6.23) {
            scene.camera.stopFlyCircle();
            heading = 0;
            isFlyCircle = false;
        }
    };

    /**
   * 分析
   */
    //相机指北
    function reduceCompass() {
        let heading = scene.camera.heading;
        let speed = 8;
        if (heading <= 0.05 || heading >= 6.23) return;
        if (heading <= 0.5 || heading >= 5.8) speed = 2;
        isFlyCircle = true;
        let viewCenter = scene.pickPosition(scratchWindowPosition);
        if (scene.camera.heading - Cesium.Math.PI >= 0) {
            scene.camera.speedRatio = speed;
            scene.camera.flyCircle(viewCenter);
            return;
        }
        scene.camera.speedRatio = -speed;
        scene.camera.flyCircle(viewCenter);
    };

    //重置
    function reset() {
        viewer.camera.flyTo({ destination: state.resetPosition });
    };

    // 放大缩进
    function zoomIn() {
        let speed = 10;
        clearInterval(zoomIn_timer);
        zoomIn_timer = setInterval(() => {
            speed = zoomSpeed();
            viewer.camera.zoomIn(speed);
        }, 30)
    };
    // 鼠标抬起暂停缩进
    function mouseup_zoomIn() {
        clearInterval(zoomIn_timer)
    };
    //缩小远离
    function zoomOut() {
        let speed = 10;
        clearInterval(zoomOut_timer);
        zoomOut_timer = setInterval(() => {
            speed = zoomSpeed();
            viewer.camera.zoomOut(speed);
        }, 30)
    };

    function mouseup_zoomOut() {
        clearInterval(zoomOut_timer)
    };

    // 缩放速度控制
    function zoomSpeed() {
        let viewCenter = scene.pickPosition(scratchWindowPosition);
        let camera_position = viewer.camera.position;
        let distance = Cesium.Cartesian3.distance(viewCenter, camera_position);
        if (distance >= 1000) return distance / 30;
        if (distance >= 20) return distance / 20;
        if (distance > 0) return 0.5;
        return 0
    };


    /**
     * 进入全屏模式。
     */

    function fullscreenchange() {
        if (!document.fullscreenElement) {
            state.isfull = true;
            launchFullscreen(document.documentElement);
        } else {
            state.isfull = false;
            exitFullscreen();
        }
    };

    function launchFullscreen(element) {
        if (element.requestFullscreen) {
            element.requestFullscreen();
        } else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
        } else if (element.msRequestFullscreen) {
            element.msRequestFullscreen();
        } else if (element.webkitRequestFullscreen) {
            element.webkitRequestFullscreen();
        }
    };
    /**
     * 退出全屏模式。兼容模式。
     */
    function exitFullscreen() {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        }
    };

    // 销毁
    onBeforeUnmount(() => {
        scene.postRender.removeEventListener(listener);
    });


    return {
        ...toRefs(state),
        compass_dom,
        reduceCompass,
        reset,
        fullscreenchange,
        zoomIn,
        mouseup_zoomIn,
        zoomOut,
        mouseup_zoomOut
    };
}
Example #10
Source File: facade.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
function s3mlayerAttribute(props) {

    // 设置默认值数据
    let state = reactive({
        maxDistance: 200,  //最大距离
        maxHeight: 100,  //最大高度
        setLodrange: false,
        layerNames: [],   //当前存在的可选择s3m图层
        selectedLayerName: 'none',  //默认选择图层名称
        lodrange: 0.01, //设置图层的lOD层级切换距离缩放系数
    });


    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let facade
    let layers, scene, selectedLayer;
    if (storeState.isViewer) {
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
        facade = new Cesium.Facade(viewer.scene);
        facade.build();
        getLayerNames();
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
            facade = new Cesium.Facade(viewer.scene);
            facade.build();
            getLayerNames()
        };
    });

    //监听图层加载完成
    watch(() => storeState.changeLayers, val => {
        getLayerNames();
    });

    //初始化图层
    function getLayerNames() {
        scene = viewer.scene;
        layers = viewer.scene.layers.layerQueue;
        if (layers && layers.length > 0) {
            layers.forEach((element, index) => {
                if (!state.layerNames.includes(element._name)) {
                    state.layerNames.push(element._name);
                }
            });
            if (state.selectedLayerName = 'none') {
                state.selectedLayerName = state.layerNames[0];
                selectedLayer = layers[0];
            }
        }
    }

    //分析

    function setRegion() {
        tooltip.showAt(' <p>点击鼠标左键开始绘制起点</p><p>绘制两点确定区域宽度</p> <p>单击右键结束分析</p><p>设置模型精细度调整图片清晰度</p>', '350px');
        if (!window.handlerPolyline) {
            initHandler("Polyline");
        }
        handlerDrawing("Polyline").then(
            res => {
                let startPoint = res.result.object.positions[0];
                let endPoint = res.result.object.positions[1];
                facade.startPoint = startPoint;
                facade.endPoint = endPoint;
                let handlerPolyline = window.handlerPolyline;
                handlerPolyline.polyline.show = false;
                window.polylineTransparent.show = false; //半透线隐藏
                handlerPolyline.deactivate();
                tooltip.setVisible(false);
            },
            (err) => {
                console.log(err);
            }
        );
        window.handlerPolyline.activate();
    };

    function execute() {
        facade.readyPromise.then(function (base64data) {
            download(base64data);
        });
    };

    function clear() {
        facade.clear();
        clearHandlerDrawing("Polyline");
        tooltip.setVisible(false);
    }


    /* 根据图片生成画布
    */
    function convertImageToCanvas(image) {
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        canvas.getContext("2d").drawImage(image, 0, 0);
        return canvas;
    }
    /**
     * 下载图片
     */
    function download(base64data) {
        let image = new Image();
        image.src = base64data;
        image.onload = function () {
            let canvas = convertImageToCanvas(image);
            let url = canvas.toDataURL("image/jpeg");
            let a = document.createElement('a');
            let event = new MouseEvent('click');
            a.download = (new Date()).getTime() + ".jpg"; // 指定下载图片的名称
            a.href = url;
            a.dispatchEvent(event); // 触发超链接的点击事件
        }
    }

    // 销毁
    onBeforeUnmount(() => {
        clear();
        facade.destroy();
    });

    // 监听
    watch(() => state.maxDistance, val => {
        facade.farDistance = Number(val);
    });
    watch(() => state.maxHeight, val => {
        facade.maxHeight = Number(val);
    });
    // 监听
    watch(() => state.selectedLayerName, val => {
        let index = state.layerNames.indexOf(val)
        if (index == -1) return;
        selectedLayer = layers[index];
    });

    watch(() => state.lodrange, val => {
       if(selectedLayer) selectedLayer.setLodRangeScale(Number(val));
    });
    watch(() => state.setLodrange, val => {
        if(!selectedLayer) return;
        if(val){
            selectedLayer.setLodRangeScale(Number(state.lodrange));
        }else{
            selectedLayer.setLodRangeScale(1);
        }
    });
    


    return {
        ...toRefs(state),
        setRegion,
        execute,
        clear
    };
}
Example #11
Source File: light.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
function addPointSymbol(props) {
    // 设置默认值数据
    let state = reactive({
        lightSelectId: 0,
        lightColor: "#FFFFFF",
        cutoffDistance: 200,
        lightDecay: 5,
        lightIntensity: 5,
        spotLightAngle: 30,
        visibleModel: true,
        dockFontShow: true, //停靠图标显示
        modelPosition: [0, 0, 0],
        modelLongitude: '',
        modelLatitude: '',
        modelHeight: '',
        bubbleShow: false,
        visiblePositions:false,
    })

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let currentSelectedEntity, selectdeLightSource, s3mInstanceColc;
    let isAddPointLight = false;
    let entityLightPairs = new Map(); // Entity和点光源对象的键值对
    let modelUrl = 'public/data/s3m/light.s3m';
    let modelEditor;
    const bubble = ref(null);

    if (storeState.isViewer) {
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
        s3mInstanceColc = new Cesium.S3MInstanceCollection(scene._context);
        viewer.scene.primitives.add(s3mInstanceColc);

    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
            s3mInstanceColc = new Cesium.S3MInstanceCollection(scene._context);
            viewer.scene.primitives.add(s3mInstanceColc);
        }
    });

    function addModel(position, pointLight) {
        let id = "light-model-" + new Date().getTime();
        s3mInstanceColc.add(modelUrl, {
            id: id,
            position: position,
            scale: new Cesium.Cartesian3(2, 2, 2),
        });
        currentSelectedEntity = s3mInstanceColc.getInstance(modelUrl, id);
        entityLightPairs.set(id, pointLight);
    }

    function getTooltipText() {
        if (state.lightSelectId === 0) {
            return '<p>点击确认点光源位置</p><p>选中光源模型可编辑与删除</p>'
        }
        return '<p>点击第一点确认光源位置</p><p>第二点确认光源方向</p><p>选中光源模型可编辑与删除</p>'
    }

    let isModelMoving = false;
    function addModelEditor(model) {
        modelEditor = new Cesium.ModelEditor({
            model: model,
            scene: viewer.scene,
            axesShow: {
                "translation": true,
                "rotation": false,
                "scale": true
            }
        });
        modelEditor.activate();
        modelEditor.changedEvt.addEventListener((param) => {
            let Cartesian3 = new Cesium.Cartesian3();
            Cesium.Matrix4.getTranslation(param.modelMatrix, Cartesian3);
            if (Cartesian3) {
                selectdeLightSource.position = Cartesian3;
                isModelMoving = true;
                changeSlider(() => isModelMoving = false)
                let position= tool.CartesiantoDegrees(Cartesian3);
                state.modelPosition.length = 0;
                state.modelPosition.push(...[position[0].toFixed(6),position[1].toFixed(6),position[2].toFixed(2)])
            }
        })
    }

    function drawPolyline() {
        if (!window.handlerPolyline) {
            initHandler("Polyline");
        }
        handlerDrawing("Polyline").then(
            res => {
                if (state.lightSelectId === 1) {
                    addSpotLight(res.result.object.positions)
                } else {
                    addDirectionalLight(res.result.object.positions)
                }
                let handlerPolyline = window.handlerPolyline;
                handlerPolyline.polyline.show = false;
                window.polylineTransparent.show = false; //半透线隐藏
                handlerPolyline.deactivate();
                tooltip.setVisible(false);
            },
            (err) => {
                console.log(err);
            }
        );
        window.handlerPolyline.activate();
    }

    function addLight() {
        let test = getTooltipText()
        window.tooltip.showAt(test, '400px');
        viewer.eventManager.addEventListener("CLICK", click_light, true);
        if (state.lightSelectId === 0) {
            viewer.enableCursorStyle = false;
            viewer._element.style.cursor = "";
            document.body.classList.add("measureCur");
            isAddPointLight = true;
            return;
        }
        drawPolyline();
    }

    function click_light(e) {
        if (isAddPointLight) {
            isAddPointLight = false;
            viewer.enableCursorStyle = true;
            document.body.classList.remove("measureCur");
            let targetPosition = scene.pickPosition(e.message.position);
            addPointLight(targetPosition);
            tooltip.setVisible(false);
        } else {
            let symbol = viewer.scene.pick(e.message.position) || viewer.selectedEntity;
            if (symbol && symbol.id && typeof (symbol.id) === 'string' && symbol.id.indexOf("light-model-") != -1) {
                if (currentSelectedEntity && currentSelectedEntity.id === symbol.id.id) return;
                currentSelectedEntity = symbol;
                selectdeLightSource = entityLightPairs.get(symbol.id);
                if (!modelEditor) addModelEditor(symbol.primitive)
                else modelEditor.setEditObject(symbol.primitive);
                //
                bubble.value.style.top = (e.message.position.y - 160) + 'px';
                bubble.value.style.left = (e.message.position.x) + 'px';
                console.log(modelEditor)
                let position = tool.CartesiantoDegrees(modelEditor._position);
                state.modelPosition.length = 0;
                state.modelPosition.push(...[position[0].toFixed(6),position[1].toFixed(6),position[2].toFixed(2)]);
                state.bubbleShow = true;
                return;
            }
            currentSelectedEntity = undefined;
            selectdeLightSource = undefined;
            if (modelEditor) modelEditor.deactivate();
            state.bubbleShow = false
        }
    }

    function addPointLight(position0) {
        let position = addModleHeight(position0);
        let options = {
            color: Cesium.Color.fromCssColorString(state.lightColor),
            cutoffDistance: Number(state.cutoffDistance),
            decay: Number(state.lightDecay),
            intensity: Number(state.lightIntensity),
        };
        let pointLight = new Cesium.PointLight(position, options);
        selectdeLightSource = pointLight;
        viewer.scene.addLightSource(pointLight);
        addModel(position, pointLight)
    }

    function addSpotLight(positions) {
        let position1 = addModleHeight(positions[0]);
        let position2 = positions[1];
        let options = {
            color: Cesium.Color.fromCssColorString(state.lightColor),
            distance: Number(state.cutoffDistance),
            decay: Number(state.lightDecay),
            intensity: Number(state.lightIntensity),
            angle: Cesium.Math.toRadians(Number(state.spotLightAngle))
        };
        let spotLight = new Cesium.SpotLight(
            position1,
            position2,
            options
        );
        selectdeLightSource = spotLight;
        viewer.scene.addLightSource(spotLight);
        addModel(position1, spotLight)
    }

    function addDirectionalLight(positions) {
        let position1 = addModleHeight(positions[0]);
        let position2 = positions[1];
        let options = {
            targetPosition: position2,
            color: Cesium.Color.fromCssColorString(state.lightColor),
            intensity: Number(state.lightIntensity),
        };
        let directionalLight = new Cesium.DirectionalLight(
            position1,
            options
        );
        selectdeLightSource = directionalLight;
        viewer.scene.addLightSource(directionalLight);
        addModel(position1, directionalLight)
    }

    function addModleHeight(Cartesian3) {
        let Cartographic = Cesium.Cartographic.fromCartesian(Cartesian3);
        Cartographic.height += 0.5;
        return Cesium.Cartographic.toCartesian(Cartographic)
    }

    function clearLight() {
        if (currentSelectedEntity) {
            entityLightPairs.delete(currentSelectedEntity.id);
            s3mInstanceColc.removeInstance(modelUrl, currentSelectedEntity.id);
            currentSelectedEntity = null;
        }
        if (selectdeLightSource) viewer.scene.removeLightSource(selectdeLightSource);
        if (entityLightPairs.size === 0) viewer.eventManager.removeEventListener("CLICK", click_light);
        if (modelEditor) modelEditor.deactivate();
        isAddPointLight = false;
        selectdeLightSource = null;
        clearHandlerDrawing();
        viewer.enableCursorStyle = true;
        document.body.classList.remove("measureCur");
        tooltip.setVisible(false);
        closeBubble();
    }

    //关闭气泡
    function closeBubble() {
        state.bubbleShow = false
    }
    //悬停气泡
    function dockBubble(val) {
        if (val) {
            bubble.value.classList.add('bubbleDock');
            state.dockFontShow = false
        } else {
            bubble.value.classList.remove('bubbleDock');
            state.dockFontShow = true
        }
    }

    watch(() => state.lightColor, val => {
        if (!selectdeLightSource) return;
        let color = Cesium.Color.fromCssColorString(val);
        selectdeLightSource.color = color;
    })
    watch(() => state.cutoffDistance, val => {
        if (!selectdeLightSource) return;
        if (selectdeLightSource.lightType === 1) {
            selectdeLightSource.cutoffDistance = Number(val);
            return;
        }
        if (selectdeLightSource.lightType === 2) {
            selectdeLightSource.distance = Number(val);
            return;
        }
    })
    watch(() => state.lightDecay, val => {
        if (!selectdeLightSource) return;
        if (selectdeLightSource.lightType !== 0) {
            selectdeLightSource.decay = Number(val);
        }
    })
    watch(() => state.lightIntensity, val => {
        if (!selectdeLightSource) return;
        selectdeLightSource.intensity = Number(val);
    })
    watch(() => state.spotLightAngle, val => {
        if (!selectdeLightSource) return;
        if (selectdeLightSource.lightType === 2) {
            selectdeLightSource.angle = Cesium.Math.toRadians(Number(val));
        }
    })
    watch(() => state.visibleModel, val => {
        if (!currentSelectedEntity) return;
        if (modelEditor) modelEditor.deactivate();
        s3mInstanceColc.visible = val
    })


    watch(() => state.modelPosition, val => {
        if (!currentSelectedEntity || isModelMoving) return;
        changeSlider(() => {
            let lon = Number(val[0]);
            let lat = Number(val[1]);
            let hei = Number(val[2]);
            let position = Cesium.Cartesian3.fromDegrees(lon, lat, hei);
            selectdeLightSource.position = position;
            currentSelectedEntity.primitive.updatePosition(position);
            if (modelEditor) modelEditor.setEditObject(currentSelectedEntity.primitive);
        })
    },
        {
            deep: true
        })

    let timer;
    // 防止滑块快速滑动的多次执行
    function changeSlider(callback) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(function () {
            callback()
        }, 1000);

    }




    // 销毁
    onBeforeUnmount(() => {
        // if (viewer) viewer.eventManager.removeEventListener("CLICK", click_light);
    });


    return {
        ...toRefs(state),
        config,
        addLight,
        clearLight,

        bubble,
        closeBubble,
        dockBubble
    };
}
Example #12
Source File: projection-image.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
function projectionImage(props) {
    // 设置默认值数据
    let state = reactive({
        viewlongitude: "",
        viewlatitude: "",
        viewheight: "",
        direction: "",
        pitch: "",
        horizontal: 20,
        vertical: 10,
        distance: 200,
        hintLineColor: "rgba(251,250,248,1)",
        clipMode: "clip-inside",
        visibleLine: true,
        fileText: "",
        fromInfo: null,
    })

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let layers, scene;
    let currentProject;
    let vedioFile_dom = ref(null)
    let modelIdProjectPairs = new Map(); // 模型id和视频投放对象对象的键值对
    let s3mInstanceColc, modelEditor;
    let modelUrl = 'public/data/s3m/projector.s3m';
    let isActive = false;
    let currentSelectedSymbol = null;
    let reader = new FileReader();
    let currntVideoDom, isClip = false;
    if (storeState.isViewer) {
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
        scene = viewer.scene;
        layers = viewer.scene.layers.layerQueue;
        s3mInstanceColc = new Cesium.S3MInstanceCollection(scene._context);
        viewer.scene.primitives.add(s3mInstanceColc);
        viewer.eventManager.addEventListener("CLICK", click_set_target, true);
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
            scene = viewer.scene;
            layers = viewer.scene.layers.layerQueue;
            s3mInstanceColc = new Cesium.S3MInstanceCollection(scene._context);
            viewer.scene.primitives.add(s3mInstanceColc);
        }
    });

    //监听图层加载完成
    watch(() => storeState.changeLayers, val => {
        for (let i = 0; i < layers.length; i++) {
            layers[i].selectEnabled = false;
        }
    });
    onMounted(() => {
        fileChange();
        currntVideoDom = document.getElementById("trailer-0");
    })

    // 点击选择文件函数
    function chooseFile() {
        vedioFile_dom.value.click();
    }

    //文件夹改变文件触发
    function fileChange() {
        vedioFile_dom.value.addEventListener("change", evt => {
            let file = evt.target.files[0];
            if (!file) return;
            state.fileText = vedioFile_dom.value.value;
            const aBlob = new Blob([file], { type: 'video/mp4' })
            reader.readAsDataURL(aBlob)
            reader.onload = function (e) {
                let vedio = e.target.result;
                let index = document.querySelectorAll('#videoContain>video').length;
                creatVideo_dom(vedio, index).then((res) => {
                    currntVideoDom = document.getElementById("trailer-" + index)
                });
            };
        });
    }

    function creatVideo_dom(src, index) {
        return new Promise((resolve, reject) => {
            let videoContain = document.getElementById("videoContain");
            let video = document.createElement("video");
            let source = document.createElement("source");
            source.src = src;
            video.appendChild(source);
            video.id = "trailer-" + index;
            video.classList.add("videoBox");
            video.setAttribute("autoplay", "autoplay");
            video.setAttribute("loop", "loop");
            video.setAttribute("crossorigin", "crossorigin");
            video.setAttribute("controls", "controls");
            video.setAttribute("muted", "muted");
            videoContain.appendChild(video);
            setTimeout(() => {
                resolve(video);
            }, 500);
        });
    };


    function startProjection() {
        viewer.enableCursorStyle = false;
        viewer._element.style.cursor = "";
        document.body.classList.add("measureCur");
        let viewPosition = viewer.scene.camera.position;
        currntVideoDom.play();
        currentProject = new Cesium.ProjectionImage(scene);
        currentProject.setImage({ video: currntVideoDom });
        currentProject.distance = Number(state.distance);
        currentProject.horizontalFov = Number(state.horizontal);
        currentProject.verticalFov = Number(state.vertical);
        currentProject.viewPosition = tool.CartesiantoDegrees(viewPosition);
        currentProject.build();
        isActive = true;
        window.tooltip.showAt(' <p>选中投放模型进行编辑和清除</p>', '400px');
        viewer.eventManager.addEventListener("MOUSE_MOVE", move_set_target);
        viewer.eventManager.addEventListener("CLICK", click_set_target, true);

    }

    function click_set_target(e) {
        if (isClip) return;
        if (isActive) {
            viewer.enableCursorStyle = true;
            document.body.classList.remove("measureCur");
            let Cartesian3 = Cesium.Cartesian3.fromDegrees(currentProject.viewPosition[0], currentProject.viewPosition[1], currentProject.viewPosition[2]);
            let viewPosition = JSON.parse(JSON.stringify(Cartesian3));
            viewer.eventManager.removeEventListener("MOUSE_MOVE", move_set_target);
            addModel(viewPosition);
            isActive = false;
            return;
        }
        let symbol = viewer.scene.pick(e.message.position) || viewer.selectedEntity;
        if (symbol && symbol.id && typeof (symbol.id) === 'string' && symbol.id.indexOf("projector-") != -1) {
            // if (currentSelectedSymbol && currentSelectedSymbol.id === symbol.id) return;
            if (modelEditor) modelEditor.destroy();
            currentSelectedSymbol = symbol;
            currentProject = modelIdProjectPairs.get(symbol.id);
            if (currentProject) {
                state.horizontal = currentProject.horizontalFov;
                state.vertical = currentProject.verticalFov;
                state.distance = currentProject.distance;
            }
            // modelEditor = new Cesium.ModelEditor({
            //     model: symbol.primitive,
            //     scene: viewer.scene,
            //     // offset: new Cesium.Cartesian3(0, 0, 2)
            // });
            // modelEditor.activate();
            // console.log(modelEditor)
            return;
        }
        // if (modelEditor) modelEditor.destroy();
        // modelEditor = null;
        currentSelectedSymbol = null;
        currentProject = null;
    }

    function move_set_target(e) {
        let distance = 0;
        let viewPosition = viewer.scene.camera.position;
        let targetPosition = scene.pickPosition(e.message.endPosition);
        if (targetPosition)
            distance = Cesium.Cartesian3.distance(viewPosition, targetPosition);
        if (distance > 0 && distance < 1000)
            currentProject.setDistDirByPoint(tool.CartesiantoDegrees(targetPosition));
    }

    function addModel(position, position2) {
        let id = 'projector-' + new Date().getTime();
        let direction = currentProject.direction;
        let pitch = currentProject.pitch;
        let radians = Cesium.Math.toRadians(direction);
        let heading = radians >= Cesium.Math.PI ? radians - Cesium.Math.PI : radians + Cesium.Math.PI;
        let pitch2 = -Cesium.Math.toRadians(pitch)
        s3mInstanceColc.add(modelUrl, {
            id: id,
            position: position,
            hpr: {
                heading: heading,
                pitch: 0,
                roll: pitch2,
            },
            // scale: new Cesium.Cartesian3(2, 2, 2),
            // offset: new Cesium.Cartesian3(0, 0, 0.1)
        });
        currentSelectedSymbol = s3mInstanceColc.getInstance(modelUrl, id);
        modelIdProjectPairs.set(id, currentProject);
    }

    // 裁剪
    function clipProjectImg() {
        isClip = true;
        tooltip.setVisible(false);
        window.tooltip.showAt(' <p>点击鼠标左键绘制裁剪区域</p><p>点击鼠标右键结束绘制</p><p>注:只能裁剪当前选中投放对象</p>', '400px');
        if (!window.handlerPolygon) {
            initHandler("Polygon");
        }
        handlerDrawing("Polygon").then(
            res => {
                isClip = false;
                let handlerPolygon = window.handlerPolygon;
                updateClipImg(res.positions)
                handlerPolygon.polygon.show = false;
                handlerPolygon.polyline.show = false;
                window.polylineTransparent.show = false; //半透线隐藏
                handlerPolygon.deactivate();
            },
            err => {
                console.log(err);
            }
        );
        window.handlerPolygon.activate();
    }

    function updateClipImg(position) {
        if (!currentProject) return;
        currentProject.addClipRegion({
            name: "clip-Projector" + new Date().getTime(),
            position: position,
        });
    }

    function clear() {
        viewer.eventManager.removeEventListener("MOUSE_MOVE", move_set_target);
        if (currentSelectedSymbol) {
            modelIdProjectPairs.delete(currentSelectedSymbol.id);
            s3mInstanceColc.removeInstance(modelUrl, currentSelectedSymbol.id);
            currentSelectedSymbol = null;
        }
        if (currentProject) {
            currentProject.removeAllClipRegion()
            currentProject.destroy();}
        if (modelIdProjectPairs.size === 0)
            viewer.eventManager.removeEventListener("CLICK", click_set_target);
        if (modelEditor) modelEditor.destroy();
        modelEditor = null;
        currentProject = null;
        window.tooltip.setVisible(false);
        clearHandlerDrawing();
        viewer.enableCursorStyle = true;
        document.body.classList.remove("measureCur");
    }


    watch(() => state.fileText, val => {
        if (val.indexOf("http") === -1) return;
        let index = document.querySelectorAll('#videoContain>video').length;
        creatVideo_dom(val, index).then((res) => {
            currntVideoDom = document.getElementById("trailer-" + index)
        });
    })
    watch(() => state.horizontal, val => {
        if (val == "" || !currentProject) return;
        currentProject.horizontalFov = Number(val);
    })
    watch(() => state.vertical, val => {
        if (val == "" || !currentProject) return;
        currentProject.verticalFov = Number(val);
    })
    watch(() => state.distance, val => {
        if (val == "" || !currentProject) return;
        currentProject.distance = Number(val);
    })

    watch(() => state.visibleLine, val => {
        if (!currentProject) return;
        // currentProject.hintLineVisible = val;
        s3mInstanceColc.visible = val; //隐藏所有模型
        modelIdProjectPairs.forEach((projector) => { //隐藏所有投放线
            projector.hintLineVisible = val
        })
    })
    watch(() => state.hintLineColor, val => {
        if (!currentProject) return;
        currentProject.hintLineColor = Cesium.Color.fromCssColorString(val);
    })
    watch(() => state.clipMode, val => {
        if (!currentProject) return;
        let clipMode =
            val === "clip-outside"
                ? Cesium.ModifyRegionMode.CLIP_INSIDE
                : Cesium.ModifyRegionMode.CLIP_OUTSIDE;
        currentProject.setClipMode(clipMode);
    })

    watch(() => state.viewlongitude, val => {
        if (!currentProject || val == "") return;
        currentProject.viewPosition[0] = val;
    })
    watch(() => state.viewlatitude, val => {
        if (!currentProject || val == "") return;
        currentProject.viewPosition[1] = val;
    })
    watch(() => state.viewheight, val => {
        if (!currentProject || val == "") return;
        currentProject.viewPosition[2] = val;
    })
    watch(() => state.direction, val => {
        if (!currentProject || val == "") return;
        currentProject.direction = Number(val);
    })
    watch(() => state.pitch, val => {
        if (!currentProject || val == "") return;
        currentProject.pitch = Number(val);
    });
    watch(() => state.fromInfo, val => {
        if (!val || val == "") return;
        Cesium.ProjectionImage.fromInfo(scene, state.fromInfo.infoUrl, state.fromInfo.baseUrl)
    })

    // 销毁
    onBeforeUnmount(() => {
        for (let i = 0; i < layers.length; i++) {
            layers[i].selectEnabled = true;
        }
    });


    return {
        ...toRefs(state),
        chooseFile,
        vedioFile_dom,
        startProjection,
        clear,
        clipProjectImg
    };
}
Example #13
Source File: roller.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
//简单局部状态管理


function roller(props) {

    // 设置默认值数据
    let state = reactive({
        useRoller: false,  //使用卷帘
        rollerMode: "lrRoller",   //卷帘模式
        lrRoller: "1",  //左右卷帘时默认屏蔽左边
        tbRoller: "4",  //上下卷帘时默认屏蔽上面
        TreeDatas: [],   //图层树
    })
    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }
    // 初始化数据
    let layers, imgLayers, terrainLayers, mvtLayers;
    let dom = document.getElementById('cesiumContainer');
    let wide = document.body.clientWidth - dom.clientWidth;  //定位矫正
    let heide = document.body.clientHeight- dom.clientHeight;
    let width = dom.clientWidth; // 界面宽度
    let height = dom.clientHeight; // 界面高度
    let tree = ref(null);
    let verticalSliderLeft = ref(null);
    let verticalSliderRight = ref(null);
    let horizontalSliderTop = ref(null);
    let horizontalSliderBottom = ref(null);
    let scratchSwipeRegion = new Cesium.BoundingRectangle();
    // 卷帘配置参数,以对象方式实现地址传递
    let rollerShutterConfig = {
        startX: 0.33,  //x方向左卷帘条比例
        startY: 0.33,  //y方向上卷帘条比例
        endX: 0.66,  //x方向右卷帘条比例
        endY: 0.66,  //y方向下卷帘条比例
        index: 1,  //当前控制卷帘条
        mode: 1,  //卷帘模式
    };

    
    //监听图层加载完成
    watch(() => storeState.changeLayers, val => {
        initLayers()
    });

    onMounted(() => {
        bindSliderEvt();  //绑定事件
        setTimeout(() => {
            initLayers()
        }, 500)
    });

    //初始化图层
    function initLayers() {
        layers = viewer.scene.layers.layerQueue;
        imgLayers = viewer.imageryLayers._layers;
        mvtLayers = viewer.scene._vectorTileMaps._layerQueue;
        terrainLayers = viewer.terrainProvider;
        state.TreeDatas.length = 0;
        updataS3MLayer();
        updataImgLayers();
        updataMvtLayers();
        updataTerrainLayers();
        setTimeout(() => {
            tree.value.setCheckedNodes(state.TreeDatas); //默认全部勾选参与卷帘
        }, 500)
    };

    // 分析

    // updatS3M图层
    function updataS3MLayer() {
        if (layers.length == 0) {
            return;
        }
        let S3MLayersObj = {
            id: 's3m',
            label: "S3M图层",
            children: []
        };
        layers.forEach((layer, index) => {
            let S3Mlayer = {
                id: 's3m-' + index,
                label: layer._name,
            };
            S3MLayersObj.children.push(S3Mlayer);
        });
        state.TreeDatas[0] = S3MLayersObj;

    };

    //updatImg
    function updataImgLayers() {
        if (imgLayers.length == 1) {
            return;
        }
        let imgLayersObj = {
            id: 'img',
            label: "IMG图层",
            children: []
        };
        imgLayers.forEach((layer, index) => {
            if (index === 0) return true;
            let isMvt = layer._imageryProvider instanceof Cesium.MvtProviderGL;
            if (isMvt) return true;
            let IMGlayer = {
                id: 'img-' + index,
                label: resource.BaseMapImg,
            };
            if (layer._imageryProvider.tablename) {
                IMGlayer.label = layer._imageryProvider.tablename;
            }
            imgLayersObj.children.unshift(IMGlayer);
        });
        if (imgLayersObj.children.length > 0) state.TreeDatas[1] = imgLayersObj;
    };

    //updatMVT
    function updataMvtLayers() {
        if (mvtLayers.length == 0) {
            return;
        }
        let mvtLayersObj = {
            id: 'mvt',
            label: "MVT图层",
            children: []
        };
        mvtLayers.forEach((layer, index) => {
            let IMGlayer = {
                id: 'mvt-' + index,
                label: layer.name,
            };
            mvtLayersObj.children.unshift(IMGlayer);
        });
        state.TreeDatas[2] = mvtLayersObj;
    };

    //updatTerrain(地表)
    function updataTerrainLayers() {
        // if (!terrainLayers.tablename) {
        //     return;
        // }
        let terrainLayersObj = {
            id: 'globe',
            label: "地球",
            children: []
        };
        let TerrainLayer = {
            id: 'globe-0',
            label: '地表',
        };
        terrainLayersObj.children.push(TerrainLayer);
        state.TreeDatas[4] = terrainLayersObj;
    };

    //勾选节点函数
    function checkNode(data) {
        let node = tree.value.getNode(data)
        let ids = data.id.split('-');
        setLayersRoller(ids, node.checked)
    };


    /**
         * 设置卷帘的分割方向及分割条的位置。
         *
    */
    function setRollerShutterSplit() {
        let startX = rollerShutterConfig.startX;
        let startY = rollerShutterConfig.startY;
        let endX = rollerShutterConfig.endX;
        let endY = rollerShutterConfig.endY;
        let mode = rollerShutterConfig.mode;
        // 左右卷帘使用left slider滑动,上下卷帘使用top slider滑动
        switch (mode) {
            case 1:
                Cesium.BoundingRectangle.unpack([startX, 0, 1, 1], 0, scratchSwipeRegion);
                break;
            case 2:
                Cesium.BoundingRectangle.unpack([0, 0, startX, 1], 0, scratchSwipeRegion);
                break;
            case 4:
                Cesium.BoundingRectangle.unpack([0, startY, 1, 1], 0, scratchSwipeRegion);
                break;
            case 8:
                Cesium.BoundingRectangle.unpack([0, 0, 1, startY], 0, scratchSwipeRegion);
                break;
            case 15:
                Cesium.BoundingRectangle.unpack([startX, startY, endX - startX, endY - startY], 0, scratchSwipeRegion);
                break;
            default:
                Cesium.BoundingRectangle.unpack([0, 0, 1, 1], 0, scratchSwipeRegion);
                break;
        }

        let checkedKeys = tree.value.getCheckedKeys(true);
        checkedKeys.forEach((key) => {
            let ids = key.split('-');
            setLayersRoller(ids, true);
        })
    };

    //设置各类图层的卷帘
    function setLayersRoller(ids, checked) {
        let type = ids[0];
        let index = ids[1];
        switch (type) {
            case 's3m':
                if (!index) {
                    for (let i = 0; i < layers.length; i++) {
                        layers[i].swipeEnabled = checked;
                        layers[i].swipeRegion = scratchSwipeRegion;
                    }
                    return;
                }
                layers[index].swipeEnabled = checked;
                layers[index].swipeRegion = scratchSwipeRegion;
                break;
            case 'img':
                if (!index) {
                    for (let i = 1; i < imgLayers.length; i++) {
                        imgLayers[i].swipeEnabled = checked;
                        imgLayers[i].swipeRegion = scratchSwipeRegion;
                    }
                    return;
                }
                imgLayers[index].swipeEnabled = checked;
                imgLayers[index].swipeRegion = scratchSwipeRegion;
                break;
            case 'mvt':
                if (!index) {
                    for (let i = 0; i < mvtLayers.length; i++) {
                        mvtLayers[i].swipeEnabled = checked;
                        mvtLayers[i].swipeRegion = scratchSwipeRegion;
                    }
                    return;
                }
                mvtLayers[index].swipeEnabled = checked;
                mvtLayers[index].swipeRegion = scratchSwipeRegion;
                break;
            case 'globe':
                viewer.scene.globe.swipeEnabled = checked;
                viewer.scene.globe.swipeRegion = scratchSwipeRegion;
                break;
            default: null
        }
    };

    // 取消所有图层的卷帘
    function cancelLayersRoller() {
        setLayersRoller(['s3m'], false);
        setLayersRoller(['img'], false);
        setLayersRoller(['mvt'], false);
        setLayersRoller(['globe'], false);
    }

    //设置卷帘条显隐
    function enableSlider(index) {
        verticalSliderLeft.value.style.display = 'none';
        verticalSliderRight.value.style.display = 'none';
        horizontalSliderTop.value.style.display = 'none';
        horizontalSliderBottom.value.style.display = 'none';
        if (index & 1) {
            verticalSliderLeft.value.style.display = 'block';
        }
        if (index & 2) {
            verticalSliderRight.value.style.display = 'block';
        }
        if (index & 4) {
            horizontalSliderTop.value.style.display = 'block';
        }
        if (index & 8) {
            horizontalSliderBottom.value.style.display = 'block';
        }
    }


    /**
     * 注册卷帘分割条的拖拽事件。
     */
    function bindSliderEvt() {
        verticalSliderLeft.value.addEventListener('mousedown', function (e) {
            mouseDown(e, 1);
        }, false);
        verticalSliderRight.value.onmousedown = function (e) {
            mouseDown(e, 3);
        };
        horizontalSliderTop.value.onmousedown = function (e) {
            mouseDown(e, 2);
        };
        horizontalSliderBottom.value.onmousedown = function (e) {
            mouseDown(e, 4);
        };
        window.addEventListener('resize', function () {
            width = document.body.clientWidth - wide; // 窗口宽度
            height = document.body.clientHeight - heide; // 窗口高度
        });

        document.addEventListener('mouseup', mouseUp, false);
        function mouseUp(e) {
            document.removeEventListener('mousemove', sliderMove, false);
        }

        function mouseDown(e, index) {
            rollerShutterConfig.index = index;
            document.addEventListener('mousemove', sliderMove, false);
        }

        function sliderMove(e) {
            if (e.preventDefault) {
                e.preventDefault();
            } else {
                e.returnValue = false;
            }

            switch (rollerShutterConfig.index) {
                case 1:
                    verticalSliderLeft.value.style.left = e.clientX - wide + 'px';
                    rollerShutterConfig.startX = (e.clientX - wide) / width;
                    break;
                case 2:
                    horizontalSliderTop.value.style.top = e.clientY - heide+ 'px';
                    rollerShutterConfig.startY = (e.clientY- heide) / height;
                    break;
                case 3:
                    verticalSliderRight.value.style.left = e.clientX- wide + 'px';
                    rollerShutterConfig.endX = (e.clientX- wide) / width;
                    break;
                case 4:
                    horizontalSliderBottom.value.style.top = e.clientY- heide + 'px';
                    rollerShutterConfig.endY = (e.clientY- heide) / height;
                    break;
            }
            setRollerShutterSplit();
        }

    }

    //监听
    watch(() => state.multiViewport, val => {
        viewer.scene.multiViewportMode = Cesium.MultiViewportMode[val];
    });

    watch(() => state.selectedViewport, (val, oldval) => {
        let keys = tree.value.getCheckedKeys(true);
        state['KeysViewport' + oldval] = keys;
        tree.value.setCheckedKeys(state['KeysViewport' + val], true);
    });

    watch(() => state.useRoller, val => {
        if (val) {
            if (rollerShutterConfig.mode == 1 || rollerShutterConfig.mode == 2)
                enableSlider(1);
            if (rollerShutterConfig.mode == 4 || rollerShutterConfig.mode == 8)
                enableSlider(4);
            if (rollerShutterConfig.mode == 15)
                enableSlider(15);
            setRollerShutterSplit();
        } else {
            enableSlider(0);
            cancelLayersRoller()
        }
    });

    watch(() => state.rollerMode, val => {
        switch (val) {
            case "lrRoller":
                if (state.useRoller) enableSlider(1);
                rollerShutterConfig.mode = Number(state.lrRoller);
                break;
            case "tbRoller":
                if (state.useRoller) enableSlider(4);
                rollerShutterConfig.mode = Number(state.tbRoller);
                break;
            case "customRoller":
                if (state.useRoller) enableSlider(15);
                rollerShutterConfig.mode = 15;
                break;
            default:
                break;
        }
        if (!state.useRoller) return;
        setRollerShutterSplit();
    });
    watch(() => state.lrRoller, val => {
        if (!state.useRoller) return;
        rollerShutterConfig.mode = Number(val);
        setRollerShutterSplit();
    });
    watch(() => state.tbRoller, val => {
        if (!state.useRoller) return;
        rollerShutterConfig.mode = Number(val);
        setRollerShutterSplit();
    });

    // 销毁
    onBeforeUnmount(() => {
        layers = undefined;
        imgLayers = undefined;
        terrainLayers = undefined;
        mvtLayers = undefined;
    })

    return {
        ...toRefs(state),
        tree,
        checkNode,
        verticalSliderLeft,
        verticalSliderRight,
        horizontalSliderTop,
        horizontalSliderBottom
    };
}
Example #14
Source File: scene-attribute.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
//语言资源

function s3mlayerAttribute(props) {

    // 设置默认值数据
    let state = reactive({
        earthShow: true,  //地球显影
        shadows: false,  //场景阴影
        cloud: false,    //云层
        skyBox: false,   //天空盒
        sunShow: false,   //太阳
        timeline: false,   //时间轴
        depthAgainst: true,  //深度检测
        atomsphereRender: true,  //大气渲染
        fogEffect: true,   //雾化效果
        underground: true,   //开启地下
        frameRate: false,   //帧率
        rain: false,
        snow: false,
        // Facade: false,  //立面图
        surfaceTransparency: 1,  //地表透明度
        cloudsUrl: 'public/img/skyboxs/clouds/clouds1.png',  //云层纹理路径
        skyboxSources: null, //天空盒资源
        skyboxType: 'bluesky', //天空盒类型
        uspeed: 0,  //获取或者设置天空盒子绕x轴运动的动画速度。设置为1时表示0.01弧度每秒
        vspeed: 0,  //获取或者设置天空盒子绕y轴运动的动画速度。
        wspeed: 0.5,  //获取或者设置天空盒子绕z轴运动的动画速度。
        viewMode: '3D',  //视图模式
        rainAngle: 45,
        rainSpeed: 8,
        snowDesity: 10,
        snowSpeed: 4,
        snowAngle: 10,
        snowType: '0',
        compass:false,
        isCompass:''
    });
    // 设置天空盒默认值
    state.skyboxSources = {
        bluesky: {
            positiveX: 'public/img/skyboxs/bluesky/Right.jpg',
            negativeX: 'public/img/skyboxs/bluesky/Left.jpg',
            positiveY: 'public/img/skyboxs/bluesky/Front.jpg',
            negativeY: 'public/img/skyboxs/bluesky/Back.jpg',
            positiveZ: 'public/img/skyboxs/bluesky/Up.jpg',
            negativeZ: 'public/img/skyboxs/bluesky/Down.jpg'
        },
        sunsetglow: {
            positiveX: 'public/img/skyboxs/sunsetglow/Right.jpg',
            negativeX: 'public/img/skyboxs/sunsetglow/Left.jpg',
            positiveY: 'public/img/skyboxs/sunsetglow/Front.jpg',
            negativeY: 'public/img/skyboxs/sunsetglow/Back.jpg',
            positiveZ: 'public/img/skyboxs/sunsetglow/Up.jpg',
            negativeZ: 'public/img/skyboxs/sunsetglow/Down.jpg'
        }
    };

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let cloudBox = new Cesium.CloudBox({ url: state.cloudsUrl });
    let skyboxs = {}, defaultSkybox;
    for (let key in state.skyboxSources) {
        let skybox = new Cesium.SkyBox({ sources: state.skyboxSources[key] });
        skybox.USpeed = state.uspeed;
        skybox.VSpeed = state.vspeed;
        skybox.WSpeed = state.wspeed;
        skyboxs[key] = skybox;
    };
    function initialSkyBox() {
        if (viewer.scene.frameState.passes.render) {
            for (let key in skyboxs) {
                skyboxs[key].update(viewer.scene.frameState, true);
                skyboxs[key].show = false;
            }
            viewer.scene.postRender.removeEventListener(initialSkyBox);
        }
    };

    function watchCameraHeight() {
        if (state.skyBox) {
            let cameraHeight = viewer.scene.camera.positionCartographic.height;
            if (cameraHeight > 22e4) {
                viewer.scene.skyBox.show = false;
                state.atomsphereRender = true;
            } else {
                viewer.scene.skyBox.show = true;
                state.atomsphereRender = false;
            }
        }
    }

    if (storeState.isViewer) {
        defaultSkybox = viewer.scene.skyBox;
        viewer.scene.postRender.addEventListener(initialSkyBox);
        viewer.scene.postProcessStages.snow.uniforms.density = parseFloat(state.snowDesity);
        viewer.scene.postProcessStages.snow.uniforms.speed = parseFloat(state.snowSpeed);
        viewer.scene.postProcessStages.rain.uniforms.speed = parseFloat(state.rainSpeed);
        watchCameraHeight();
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            defaultSkybox = viewer.scene.skyBox;
            viewer.scene.postRender.addEventListener(initialSkyBox);
            viewer.scene.postProcessStages.snow.uniforms.density = parseFloat(state.snowDesity);
            viewer.scene.postProcessStages.snow.uniforms.speed = parseFloat(state.snowSpeed);
            viewer.scene.postProcessStages.rain.uniforms.speed = parseFloat(state.rainSpeed);
            watchCameraHeight();
        }
    });

    // 销毁
    onBeforeUnmount(() => {
        cloudBox.destroy();
        for (let key in skyboxs) {
            skyboxs[key].destroy();
        };
        viewer.scene.skyBox = defaultSkybox;
    });

    // 监听
    watch(() => state.earthShow, val => {
        viewer.scene.globe.show = val;
    });
    watch(() => state.shadows, val => {
        viewer.scene.shadows = val;
    });
    watch(() => state.sunShow, val => {
        viewer.scene.globe.enableLighting = val;
    });
    watch(() => state.timeline, val => {
        let timeline = document.getElementsByClassName(
            "cesium-viewer-timelineContainer"
        )[0];
        if (val) {
            timeline.style.visibility = "visible";
        } else {
            timeline.style.visibility = "hidden";
        }
    });
    watch(() => state.depthAgainst, val => {
        viewer.scene.globe.depthTestAgainstTerrain = val;
    });
    watch(() => state.atomsphereRender, val => {
        viewer.scene.skyAtmosphere.show = val;
    });
    watch(() => state.fogEffect, val => {
        viewer.scene.fog.enabled = val;
    });
    watch(() => state.surfaceTransparency, val => {
        viewer.scene.globe.globeAlpha = parseFloat(val);
    });
    watch(() => state.underground, val => {
        viewer.scene.undergroundMode = val;
    });
    watch(() => state.frameRate, val => {
        viewer.scene.debugShowFramesPerSecond = val;
    });
    watch(() => state.cloud, val => {
        if (val) {
            viewer.scene.cloudBox = cloudBox;
        } else {
            viewer.scene.cloudBox = null;
        }
    });
    watch(() => state.cloudsUrl, val => {
        viewer.scene.cloudBox.url = val;
    });
    watch(() => state.skyBox, val => {
        if (val) {
            let cameraHeight = viewer.scene.camera.positionCartographic.height;
            viewer.scene.postRender.addEventListener(watchCameraHeight);
            viewer.scene.skyBox = skyboxs[state.skyboxType];
            if (cameraHeight < 22e4) {
                viewer.scene.skyBox.show = true;
                state.atomsphereRender = false
            } else {
                state.atomsphereRender = true
            }
        } else {
            state.atomsphereRender = true;
            viewer.scene.skyBox.show = false;
            viewer.scene.skyBox = defaultSkybox;
            viewer.scene.postRender.removeEventListener(watchCameraHeight);
        }
    });
    watch(() => state.skyboxType, val => {
        if (state.skyBox) {
            skyboxs[val].show = true;
            viewer.scene.skyBox = skyboxs[val];
        }
    });
    watch(() => state.uspeed, val => {
        skyboxs[state.skyboxType].USpeed = Number(val);
        if (state.skyBox) {
            viewer.scene.skyBox.USpeed = Number(val);
        }
    });
    watch(() => state.vspeed, val => {
        skyboxs[state.skyboxType].VSpeed = Number(val);
        if (state.skyBox) {
            viewer.scene.skyBox.VSpeed = Number(val);
        }
    });
    watch(() => state.wspeed, val => {
        skyboxs[state.skyboxType].WSpeed = Number(val);
        if (state.skyBox) {
            viewer.scene.skyBox.WSpeed = Number(val);
        }
    });
    watch(() => state.viewMode, val => {
        if (val === "2D") {
            viewer.scene.mode = Cesium.SceneMode.SCENE2D;
        } else if (val === "3D") {
            viewer.scene.mode = Cesium.SceneMode.SCENE3D;
        } else {
            viewer.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW;
        }
    });
    watch(() => state.rain, val => {
        viewer.scene.postProcessStages.rain.enabled = val;
    });
    watch(() => state.snow, val => {
        viewer.scene.postProcessStages.snow.enabled = val;
        console.log(viewer.scene.postProcessStages.snow.uniforms)
    });
    watch(() => state.rainAngle, val => {
        viewer.scene.postProcessStages.rain.uniforms.angle = parseFloat(val);
    });
    watch(() => state.rainSpeed, val => {
        viewer.scene.postProcessStages.rain.uniforms.speed = parseFloat(val)
    });
    watch(() => state.snowDesity, val => {
        viewer.scene.postProcessStages.snow.uniforms.density = parseFloat(val);
    });
    watch(() => state.snowSpeed, val => {
        viewer.scene.postProcessStages.snow.uniforms.speed = parseFloat(val);
    });
    watch(() => state.snowAngle, val => {
        viewer.scene.postProcessStages.snow.uniforms.angle = parseFloat(val);
    });
    watch(() => state.snowType, val => {
        switch (val) {
            case '0':
                state.snowDesity = 5;
                state.snowSpeed = 2;
                break;
            case '1':
                state.snowDesity = 10;
                state.snowSpeed = 4;
                break;
            case '2':
                state.snowDesity = 15;
                state.snowSpeed = 6;
                break;
            case '3':
                state.snowDesity = 20;
                state.snowSpeed = 10;
                break;
            default:
                state.snowDesity = 5;
                state.snowSpeed = 2;
                break;
        }
    });
    watch(() => state.isCompass, val => {
        if(val){
            state.compass = 'Sm3dCompass'
        }else{
            state.compass = ''
        }
        
    });
    

    return {
        ...toRefs(state),
    };
}
Example #15
Source File: split-screen.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
//简单局部状态管理

function splitScreen(props) {

    // 设置默认值数据
    let state = reactive({
        multiViewport: "NONE", //
        selectedViewport: '0', //
        TreeDatas: [],
    })
    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }
    // 初始化数据
    let layers, imgLayers, terrainLayers, mvtLayers;
    let tree = ref(null);
    //记录视口的选中状态
    let KeysViewports = {
        KeysViewport1: [],
        KeysViewport2: [],
        KeysViewport3: [],
        KeysViewport4: []
    };

    onMounted(() => {
        setTimeout(() => {
            initLayers()
        }, 500)
    });

    //监听图层加载完成
    watch(() => storeState.changeLayers, val => {
        initLayers()
    });

    //初始化图层
    function initLayers() {
        layers = viewer.scene.layers.layerQueue;
        imgLayers = viewer.imageryLayers._layers;
        mvtLayers = viewer.scene._vectorTileMaps._layerQueue;
        terrainLayers = viewer.terrainProvider;
        state.TreeDatas.length = 0;
        updataS3MLayer();
        updataImgLayers();
        updataMvtLayers();
        setTimeout(() => {
            tree.value.setCheckedNodes(state.TreeDatas);
            let keys = tree.value.getCheckedKeys(true);
            KeysViewports.KeysViewport1 = [...keys];
            KeysViewports.KeysViewport2 = [...keys];
            KeysViewports.KeysViewport3 = [...keys];
            KeysViewports.KeysViewport4 = [...keys];
        }, 500)
    }


    // 分析

    // updatS3M图层
    function updataS3MLayer() {
        if (layers.length == 0) {
            return;
        }
        let S3MLayersObj = {
            id: 's3m',
            label: "S3M图层",
            children: []
        };
        layers.forEach((layer, index) => {
            let S3Mlayer = {
                id: 's3m-' + index,
                label: layer._name,
            };
            S3MLayersObj.children.push(S3Mlayer);
        });
        state.TreeDatas[0] = S3MLayersObj;

    }

    //updatImg
    function updataImgLayers() {
        if (imgLayers.length == 1) {
            return;
        }
        let imgLayersObj = {
            id: 'img',
            label: "IMG图层",
            children: []
        };
        imgLayers.forEach((layer, index) => {
            let isMvt = layer._imageryProvider instanceof Cesium.MvtProviderGL;
            if (index === 0 || isMvt) return true;
            let IMGlayer = {
                id: 'img-' + index,
                label: resource.BaseMapImg,
            };
            if (layer._imageryProvider.tablename) {
                IMGlayer.label = layer._imageryProvider.tablename;
            }
            imgLayersObj.children.unshift(IMGlayer);
        });
        if (imgLayersObj.children.length > 0) state.TreeDatas[1] = imgLayersObj;
    }

    //updatMVT
    function updataMvtLayers() {
        console.log(mvtLayers)
        if (mvtLayers.length == 0) {
            return;
        }
        let mvtLayersObj = {
            id: 'mvt',
            label: "MVT图层",
            children: []
        };
        mvtLayers.forEach((layer, index) => {
            let IMGlayer = {
                id: 'mvt-' + index,
                label: layer.name,
            };
            mvtLayersObj.children.unshift(IMGlayer);
        });
        state.TreeDatas[2] = mvtLayersObj;
    }

    //updatTerrain
    function updataTerrainLayers() {
        if (!terrainLayers.tablename) {
            return;
        }
        let terrainLayersObj = {
            id: 'terrain',
            label: "地形图层",
            children: []
        };
        let TerrainLayer = {
            id: 'terrain-0',
            label: terrainLayers.tablename,
        };
        terrainLayersObj.children.push(TerrainLayer);
        state.TreeDatas[4] = terrainLayersObj;

    }

    //勾选节点函数
    function checkNode(data) {
        let node = tree.value.getNode(data)
        let ids = data.id.split('-');
        setVisibleInViewport(ids, node.checked)
    }

    //设置图层视口显隐
    function setVisibleInViewport(ids, checked) {
        let type = ids[0];
        let index = ids[1];
        switch (type) {
            case 's3m':
                if (!index) {
                    for (let i = 0; i < layers.length; i++) {
                        layers[i].setVisibleInViewport(Number(state.selectedViewport), checked);
                    }
                    return;
                }
                layers[index].setVisibleInViewport(Number(state.selectedViewport), checked)
                break;
            case 'img':
                if (!index) {
                    for (let i = 0; i < imgLayers.length; i++) {
                        imgLayers[i].setVisibleInViewport(Number(state.selectedViewport), checked)
                    }
                    return;
                }
                imgLayers[index].setVisibleInViewport(Number(state.selectedViewport), checked)
                break;
            case 'mvt':
                if (!index) {
                    for (let i = 0; i < mvtLayers.length; i++) {
                        mvtLayers[i].setVisibleInViewport(Number(state.selectedViewport), checked)
                    }
                    return;
                }
                mvtLayers[index].setVisibleInViewport(Number(state.selectedViewport), checked)
                break;
            default: null
        }
    }


    //监听
    watch(() => state.multiViewport, val => {
        viewer.scene.multiViewportMode = Cesium.MultiViewportMode[val];
    });

    watch(() => state.selectedViewport, (val, oldval) => {
        let keys = tree.value.getCheckedKeys(true);
        KeysViewports['KeysViewport' + oldval] = keys;
        tree.value.setCheckedKeys(KeysViewports['KeysViewport' + val], true);
    });


    // 销毁
    onBeforeUnmount(() => {
        layers = null;
        imgLayers = null;
        terrainLayers = null;
        mvtLayers = null;
        KeysViewports = null;
    })

    return {
        ...toRefs(state),
        tree,
        checkNode,
    };
}
Example #16
Source File: volume-render.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
function volume(props) {

    // 设置默认值数据
    let state = reactive({
        dataUrl:'',
        operationType: 'addDate',
        dimensions: [],
        variables: [],
        selectedDateName: null,
        xDim: null,
        yDim: null,
        zDim: null,
        timeDim: null,
        //数值模式
        drawMode: 'volume',
        opacityInterval: [0, 1],
        useGradientOpacity: false,
        gradientOpacityValue: [0, 1],
        gradientOpacity: [0, 1],
        showClipPlane: false,
        clipX: 0.5,
        clipY: 0.5,
        clipRotate: 0,
        //剖切
        xOffset: 0.5,
        yOffset: 0.5,
        zOffset: 0.5,
        //等值面
        contourValue: 1,
        contourRange:[0,1],
        // 公共部分
        zScale: 0,
        colorInterval: [0, 1],
        timeOrder: 0,
        timeRange: [0,24],
        openLight: false,
    });


    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let gridLayer;
    let scaleScratch = new Cesium.Cartesian3(1, 1, 1); //z拉伸
    let scratchCartesian3 = new Cesium.Cartesian3(0.5, 0.5, 0.5); //偏移
    let scratchClipPlane = Cesium.Plane.fromPointNormal(new Cesium.Cartesian3(0, 0, 0), new Cesium.Cartesian3(1, 0, 0)); //裁剪面
    let colorTable;

    if (storeState.isViewer) {
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
        init()
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
            init()
        };
    });

    function init() {
        if(!state.dataUrl) return tool.Message.warnMsg('请先定义数据路径!');
        // let promise = viewer.scene.addVoxelGridLayer("public/data/netcdf/Ningxia_24.nc", "test");
        // let promise = scene.addVoxelGridLayer("public/data/netcdf/result_100_200_9_40.nc", );
        let promise = viewer.scene.addVoxelGridLayer(state.dataUrl,"test");
        Cesium.when(promise, function (layer) {
            gridLayer = layer;
            state.dimensions = gridLayer._NetCDFInfo.dimensions; 
            state.variables = gridLayer._NetCDFInfo.variables;
            state.selectedDateName = state.variables[0].name;
            state.xDim = state.dimensions[0].name;
            state.yDim = state.dimensions[0].name;
            state.zDim = state.dimensions[0].name;
            state.timeDim = state.dimensions[0].name;
            //默认体渲染位置
            gridLayer.layerBounds = new Cesium.Rectangle(99.95422, 32.25671, 107.1912, 37.1386);
            gridLayer.zBounds = new Cesium.Cartesian2(500, 50000);
        })
    }

    // 加载数据开始渲染
    function startRender() {
        if (!gridLayer) {
            init();
            return;
        }
        if (state.xDim == state.yDim || state.xDim == state.zDim || state.yDim == state.zDim) {
            tool.Message.warnMsg("各维度名不能一样")
            return;
        }
        colorTable = new ColorTable({
            opacityMinValue: 0.0,
            opacityMaxValue: 0.8,
            gradientMinOpacity: 1.0,
            gradientMaxOpacity: 1.0,
            visibleMinValue: 0,
            visibleMaxValue: 0.37
        });
        colorTable.setColorTable(gridLayer, 0);
        gridLayer.startRender({
            variableName: state.selectedDateName,
            xDimName: state.xDim,
            yDimName: state.yDim,
            zDimName: state.zDim,
            timeDimName: state.timeDim
        });
        changeAttrbute();
        viewer.scene.camera.flyTo({
            destination: {x: -1688158.0372444934, y: 6654029.431965283, z: 2998692.1265170774},
            orientation: {
                heading: 0.028840576504810755,
                pitch: -0.8994386458052253,
                roll:6.283185307179586
              }
        })
    }

    // 加载数据后再修改部分最大最小属性值
    function changeAttrbute(){
        state.contourRange = [Math.ceil(gridLayer.minValue),Math.ceil(gridLayer.maxValue)];
        state.contourValue = Math.ceil(gridLayer.minValue);
        let recordDimension = gridLayer._NetCDFInfo.recordDimension;
        if(recordDimension && recordDimension.length>0){
            state.timeRange=[0,recordDimension.length]
        }
    }

    // 添加裁剪面
    function addClipPlane() {
        if (!Cesium.defined(gridLayer) || gridLayer.getNumberOfClipPlanes() > 0) {
            return;
        }
        state.showClipPlane = true;
        gridLayer.addClipPlane(scratchClipPlane);
        addPoint();
    }

    //在裁剪时增加点标志
    function addPoint() {
        let lat = gridLayer.layerBounds.west + (gridLayer.layerBounds.east - gridLayer.layerBounds.west) * Number(state.clipX);
        let lng = gridLayer.layerBounds.south + (gridLayer.layerBounds.north - gridLayer.layerBounds.south) * Number(state.clipY);
        viewer.entities.removeById('volume-clip-plane');
        viewer.entities.add({
            id: 'volume-clip-plane',
            position: Cesium.Cartesian3.fromDegrees(lat, lng, 50000),
            point: {
                color: Cesium.Color.YELLOW,
                pixelSize: 10
            }
        });
    }

    // 移除裁剪面
    function removeClipPlane() {
        if (!Cesium.defined(gridLayer) || gridLayer.getNumberOfClipPlanes() === 0) {
            return;
        }
        state.showClipPlane = false;
        gridLayer.removeAllClipPlanes();
        viewer.entities.removeById('volume-clip-plane');
    }

    function clear(){
        if (!gridLayer) {
            return;
        }
        viewer.scene.layers.remove(gridLayer.name);
        gridLayer = null;
        init();
    }

    // 销毁
    onBeforeUnmount(() => {
        viewer.scene.layers.remove(gridLayer.name);
        gridLayer = null;
    });

    // 监听
    // 数值部分
    watch(() => state.drawMode, val => {
        if (!gridLayer) return;
        if (val === 'slice') {
            gridLayer.volumeRenderMode = 1;
        } else if (val === 'gradient') {
            gridLayer.volumeRenderMode = 2;
        } else {
            gridLayer.volumeRenderMode = 0;
        }
    });
    watch(() => state.useGradientOpacity, val => {
        if (!gridLayer) return;
        gridLayer.useGradientOpacity = val;
    });
    watch(() => state.gradientOpacityValue, val => {
        if (!gridLayer) return;
        colorTable.gradientMinOpacity = val[0];
        colorTable.gradientMaxOpacity = val[1];
        colorTable.setGradientOpacityValue(gridLayer);
    });
    watch(() => state.opacityInterval, val => {
        if (!gridLayer) return;
        colorTable.opacityMinValue = val[0];
        colorTable.opacityMaxValue = val[1];
        colorTable.setColorTable(gridLayer);
    });
    watch(() => state.gradientOpacity, val => {
        if (!gridLayer) return;
        gridLayer.gradientOpacityMinOpacity = val[0];
        gridLayer.gradientOpacityMaxOpacity = val[1];
    });

    watch(() => state.zScale, val => {
        if (!gridLayer) return;
        scaleScratch.z = parseFloat(val);
        gridLayer.scale = scaleScratch;
    });
    watch(() => state.colorInterval, val => {
        if (!gridLayer) return;
        colorTable.visibleMinValue = val[0];
        colorTable.visibleMaxValue = val[1];
        colorTable.setColorTable(gridLayer);
    });
    watch(() => state.timeOrder, val => {
        if (!gridLayer) return;
        gridLayer.frameIndex = Number(val);
    });
    watch(() => state.openLight, val => {
        if (!gridLayer) return;
        gridLayer.enableLighting = val;
    });
    watch(() => state.clipX, val => {
        if (!gridLayer) return;
        addPoint();
        let newPosX = parseFloat(val);
        let newPosY = parseFloat(state.clipY);
        let newRot = Cesium.Math.toRadians(state.clipRotate);
        let qua = Cesium.Quaternion.fromAxisAngle(Cesium.Cartesian3.UNIT_Z, newRot);
        let pos = new Cesium.Cartesian3(newPosX, newPosY, 0.0);
        let transRotScale = new Cesium.TranslationRotationScale(pos, qua);
        let transformMatrix = Cesium.Matrix4.fromTranslationRotationScale(transRotScale);
        Cesium.Plane.fromPointNormal(new Cesium.Cartesian3(0, 0, 0), new Cesium.Cartesian3(1, 0, 0), scratchClipPlane);
        Cesium.Plane.transform(scratchClipPlane, transformMatrix, scratchClipPlane);
    });
    watch(() => state.clipY, val => {
        if (!gridLayer) return;
        addPoint();
        var newPosX = parseFloat(state.clipX);
        var newPosY = parseFloat(val);
        var pos = new Cesium.Cartesian3(newPosX, newPosY, 0.0);
        Cesium.Plane.fromPointNormal(pos, new Cesium.Cartesian3(0, 1, 0), scratchClipPlane);
    });
    watch(() => state.clipRotate, val => {
        if (!gridLayer) return;
        var newPosX = parseFloat(state.clipX);
        var newPosY = parseFloat(state.clipY);
        var newRot = Cesium.Math.toRadians(val);
        var qua = Cesium.Quaternion.fromAxisAngle(Cesium.Cartesian3.UNIT_Z, newRot);
        var pos = new Cesium.Cartesian3(newPosX, newPosY, 0.0);
        var rotMatrix3 = Cesium.Matrix3.fromQuaternion(qua);
        var rotMatrix4 = Cesium.Matrix4.fromRotationTranslation(rotMatrix3);
        var normal = new Cesium.Cartesian3(1, 0, 0);
        normal = Cesium.Matrix4.multiplyByPoint(rotMatrix4, normal, new Cesium.Cartesian3());
        Cesium.Plane.fromPointNormal(pos, normal, scratchClipPlane);
    });
    // 剖切模式
    watch(() => state.xOffset, val => {
        if (!gridLayer) return;
        scratchCartesian3.x = parseFloat(val);
        gridLayer.sliceCoordinate = scratchCartesian3;
    });
    watch(() => state.yOffset, val => {
        if (!gridLayer) return;
        scratchCartesian3.y = parseFloat(val);
        gridLayer.sliceCoordinate = scratchCartesian3;
    });
    watch(() => state.zOffset, val => {
        if (!gridLayer) return;
        scratchCartesian3.z = parseFloat(val);
        gridLayer.sliceCoordinate = scratchCartesian3;
    });
    watch(() => state.contourValue, val => {
        if (!gridLayer) return;
        gridLayer.contourValue = parseFloat(val);;
    });

   
    return {
        ...toRefs(state),
        startRender,
        addClipPlane,
        removeClipPlane,
        clear
    };
}
Example #17
Source File: s3mlayer-attribute.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
//语言资源

function s3mlayerAttribute(props) {

    // 设置默认值数据
    let state = reactive({
        layerNames: [],   //当前存在的可选择s3m图层
        selectedLayerName: 'none',  //默认选择图层名称
        brightness: 1,
        contrast: 1,
        hue: 0,
        saturation: 1,
        gamma: 1,
        shadowMode: 'noShadow',
        shadowDarkness: 0.3,
        selectEnabled:true,
        multiChoose: false,
        cullEnabled: false,
        visibility: 'showAll',
    })

     // 传入props改变默认值
     if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let layers, scene, selectedLayer;


    if (storeState.isViewer) {
        getLayerNames();
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            getLayerNames();
        }
    });

    //监听图层加载完成
    watch(() => storeState.changeLayers, val => {
        getLayerNames();
    });

    //初始化图层
    function getLayerNames() {
        scene = viewer.scene;
        layers = viewer.scene.layers.layerQueue;
        if (layers && layers.length > 0) {
            layers.forEach((element, index) => {
                if (!state.layerNames.includes(element._name)) {
                    state.layerNames.push(element._name);
                }
            });
            if (state.selectedLayerName = 'none') {
                state.selectedLayerName = state.layerNames[0];
                selectedLayer = layers[0];
            }
        }
    }


    // 销毁
    onBeforeUnmount(() => {
        layers = scene = null;
    });


    // 监听
    watch(() => state.selectedLayerName, val => {
        let index = state.layerNames.indexOf(val)
        if (index == -1) return;
        selectedLayer = layers[index];
    });
    watch(() => state.brightness, val => {
        if (selectedLayer)
            selectedLayer.brightness = Number(val);
    });
    watch(() => state.contrast, val => {
        if (selectedLayer)
            selectedLayer.contrast = Number(val);
    });
    watch(() => state.hue, val => {
        if (selectedLayer)
            selectedLayer.hue = Number(val);
    });
    watch(() => state.saturation, val => {
        if (selectedLayer)
            selectedLayer.saturation = Number(val);
    });
    watch(() => state.gamma, val => {
        if (selectedLayer)
            selectedLayer.gamma = Number(val);
    });
    watch(() => state.shadowMode, val => {
        if (selectedLayer)
            switch (val) {
                case "noShadow":
                    viewer.shadows = false;
                    selectedLayer.shadowType = Cesium.ShadowType.NONE;
                    break;
                case "chooseShadow":
                    viewer.shadows = true;
                    selectedLayer.shadowType = Cesium.ShadowType.SELECTION;
                    selectedLayer.refresh();
                    break;
                case "allShadow":
                    viewer.shadows = true;
                    selectedLayer.shadowType = Cesium.ShadowType.ALL;
                    selectedLayer.refresh();
                    break;
                default:
                    null;
                    break;
            }
    });
    watch(() => state.shadowDarkness, val => {
        viewer.shadowMap.darkness = Number(val);
    });
    watch(() => state.multiChoose, val => {
        if (selectedLayer)
            selectedLayer.multiChoose = val;
    });
    watch(() => state.selectEnabled, val => {
        if (selectedLayer)
            selectedLayer.selectEnabled = val;
    });
    
    watch(() => state.cullEnabled, val => {
        if (selectedLayer)
            selectedLayer.cullEnabled = val;
    });
    watch(() => state.visibility, val => {
        if (selectedLayer)
            switch (val) {
                case "showAll":
                    selectedLayer.setObjsVisible([], false);
                    break;
                case "onlyHideSlection":
                    let chooseIDs = selectedLayer.getSelection();
                    selectedLayer.setObjsVisible(chooseIDs, false);
                    break;
                case "onlyShowSlection":
                    let chooseIDs2 = selectedLayer.getSelection();
                    selectedLayer.setObjsVisible(chooseIDs2, true);
                    break;
                default:
                    null;
                    break;
            }
    });


    return {
        ...toRefs(state),
    };
}
Example #18
Source File: particle-system.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
function particleSystem(props) {
    // 设置默认值数据
    let state = reactive({
        particles: [
            {
                id: 0,
                iconfont: "iconhuoyan",
                particleName: "火焰"
            },
            {
                id: 1,
                iconfont: "iconshui",
                particleName: "水"
            },
            {
                id: 2,
                iconfont: "iconyanhua",
                particleName: "烟花"
            },
          
        ],
        particleSelectedId: 0,
        flameTyle: '0',
        fountainTyle: '0',
        ringRadius: [30, 25],
        emissionRate: 50,
        particleSize: 2,
        particleLife: [1.5, 1.6],
        speed: [3.5, 4],
        startScale: 2.5,
        endScale: 1,
        gravity: 0,
        lifetime: 6,
        particleSystemType: "conical",
        image: 'public/img/particle/基础火焰.png',
        startColor: 'rgba(255, 255, 255, 0.3)',
        endColor: 'rgba(0, 0, 0, 0)',
        visibleModel: true,
        visibleParameter: false,
        emitter: ['ConeEmitter', [60]],
        bursts: []  //爆炸
    })

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let currentSelectedEntity, selectParticleSystem, s3mInstanceColc;
    let isAddParticleSystem = false;
    let entityParticlePairs = new Map(); // Entity和点光源对象的键值对
    let modelUrl = 'public/data/s3m/box.s3m';
    let modelEditor;
    let flowingFires = [];
    //烟花默认参数设置
    let fireWorkSystem;
    let numberOfFireworks = 18;
    let xMin = -600.0;
    let xMax = 600.0;
    let yMin = -600.0;
    let yMax = 600.0;
    let zMin = 0.0;
    let zMax = 200.0;
    let colorOptions = [{
        minimumRed: 0.95,
        green: 0.0,
        minimumBlue: 0.8,
        alpha: 1.0
    }, {
        red: 0.0,
        minimumGreen: 0.75,
        minimumBlue: 0.8,
        alpha: 1.0
    }, {
        red: 0.0,
        green: 0.0,
        minimumBlue: 0.8,
        alpha: 1.0
    }, {
        minimumRed: 0.9,
        minimumGreen: 0.9,
        blue: 0.0,
        alpha: 1.0
    }];




    if (storeState.isViewer) {
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
        init()
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
            init()
        }
    });

    function init() {
        s3mInstanceColc = new Cesium.S3MInstanceCollection(viewer.scene._context);
        viewer.scene.primitives.add(s3mInstanceColc);


    };

    // 火焰
    function addFlame(position) {
        let particleSystem = new ParticleSystem();
        particleSystem.create(state, position);
        addModel(position, particleSystem);
        selectParticleSystem = particleSystem;
        console.log(particleSystem)
    }
    //烟花
    function addFireWork(position) {
        // 参数场景默认
        setSceneForFireWork(true);
        fireWorkSystem = new ParticleSystem();
        for (let i = 0; i < numberOfFireworks; ++i) {
            let x = Cesium.Math.randomBetween(xMin, xMax);
            let y = Cesium.Math.randomBetween(yMin, yMax);
            let z = Cesium.Math.randomBetween(zMin, zMax);
            let offset = new Cesium.Cartesian3(x, y, z);
            let bursts = [];
            for (let j = 0; j < 3; ++j) {
                bursts.push(new Cesium.ParticleBurst({
                    time: Cesium.Math.nextRandomNumber() * 12,
                    minimum: 400,
                    maximum: 400
                }));
            }
            let color = Cesium.Color.fromRandom(colorOptions[i % colorOptions.length]);
            fireWorkSystem.createFirework(offset, color, bursts, position);
        }
        right_click_removeEvent()
    }

    function setSceneForFireWork(isFlage) {
        if (isFlage) {
            // scene.highDynamicRange = true;
            scene.globe.show = false;
            scene.sun.show = false;
            scene.globe.enableLighting = false;
            scene.particlePostRender.quality = 1.0;
            scene.bloomEffect.show = true;
            scene.bloomEffect.threshold = 0.8;
            scene.bloomEffect.bloomIntensity = 3.6;
            viewer.scene.skyAtmosphere.show = false;
            return;
        }
        // scene.highDynamicRange = false;
        scene.globe.show = true;
        scene.sun.show = true;
        scene.globe.enableLighting = true;
        scene.particlePostRender.quality = 0.25;
        scene.bloomEffect.show = false;
        scene.bloomEffect.threshold = 0;
        scene.bloomEffect.bloomIntensity = 1.34;
        viewer.scene.skyAtmosphere.show = true;
    }

    // 喷射火
    function addFJetFire() {
        if (!window.handlerPolyline) {
            initHandler("Polyline");
        }
        let particleSystem = new ParticleSystem();
        handlerDrawing("Polyline").then(
            res => {
                let handlerPolyline = window.handlerPolyline;
                handlerPolyline.polyline.show = false;
                window.polylineTransparent.show = false; //半透线隐藏
                handlerPolyline.deactivate();
                tooltip.setVisible(false);
                let positions = res.result.object.positions;
                particleSystem.create(state, positions[0]);
                selectParticleSystem = particleSystem;
                // let heading0 = tool.getAngleAndRadian(positions[0], positions[1]).radian;
                // heading0 = heading0 >= Cesium.Math.PI ? heading0 - Cesium.Math.PI : heading0 + Cesium.Math.PI;
                // let pitch0 = tool.getPitch(positions[0], positions[1]).radian;
                // pitch0 = pitch0<0?-pitch0:pitch0;
                // addModel(positions[0], selectParticleSystem,{ heading: heading0, pitch: 0, roll: pitch0 });
                addModel(positions[0], selectParticleSystem);
                let heading = tool.getAngleAndRadian(positions[0], positions[1]).angle;
                heading = (heading - 90) >= 0 ? (heading - 90) : heading + 270;
                let pitch = tool.getPitch(positions[0], positions[1]).angle - 90;
                console.log(heading, pitch)
                let hpr = { heading: heading, pitch: pitch, roll: 0 };
                let translation = { x: 0, y: 0, z: 2 }
                selectParticleSystem.particleSystem.emitterModelMatrix = selectParticleSystem.computeEmitterModelMatrix(hpr, translation, true);
            },
            (err) => {
                console.log(err);
            }
        );
        window.handlerPolyline.activate();
    }

    // 流淌火
    function addFlowingFire() {
        flowingFires.forEach((ps) => ps.clear());
        flowingFires.length = 0;
        if (!window.handlerPolygon) {
            initHandler("Polygon");
        }
        handlerDrawing("Polygon", false).then(
            res => {
                tooltip.setVisible(false);
                let handlerPolygon = window.handlerPolygon;
                handlerPolygon.polygon.show = false;
                handlerPolygon.polyline.show = false;
                handlerPolygon.deactivate();
                let particleSystem = new ParticleSystem();
                particleSystem.create(state, undefined, res.result.object.positions);
                selectParticleSystem = particleSystem;
                flowingFires.push(particleSystem);
            },
            err => {
                console.log(err);
            }
        );
        window.handlerPolygon.activate();
    }


    function click_addParticle(e) {
        if (isAddParticleSystem) {
            let centerPosition = viewer.scene.pickPosition(e.message.position);
            if (state.particleSelectedId === 0)
                addFlame(centerPosition);
            else if (state.particleSelectedId === 1)
                addFountain(centerPosition);
            else { addFireWork(centerPosition) }
        } else {
            let symbol = viewer.scene.pick(e.message.position) || viewer.selectedEntity;
            if (symbol && symbol.id && typeof (symbol.id) === 'string' && symbol.id.indexOf("particle-model-") != -1) {
                if (currentSelectedEntity && currentSelectedEntity.id === symbol.id.id) return;
                currentSelectedEntity = symbol;
                selectParticleSystem = entityParticlePairs.get(symbol.id);
                if (!modelEditor) addModelEditor(symbol.primitive)
                else modelEditor.setEditObject(symbol.primitive);
                return;
            }
            currentSelectedEntity = undefined;
            selectParticleSystem = undefined;
            if (modelEditor) modelEditor.deactivate();
        }
    }

    function right_click_removeEvent() {
        window.tooltip.setVisible(false);
        document.body.classList.remove("measureCur");
        // viewer.eventManager.removeEventListener("CLICK", click_addParticle);
        isAddParticleSystem = false;
        viewer.eventManager.removeEventListener("RIGHT_CLICK", right_click_removeEvent); //移除鼠标点击事件监听
    }


    function addParticle() {
        viewer.eventManager.addEventListener("CLICK", click_addParticle, true);
        viewer.eventManager.addEventListener("RIGHT_CLICK", right_click_removeEvent);
        if (state.particleSelectedId == 0 && state.flameTyle == '2') {
            window.tooltip.showAt(' <p>点击鼠标左键开始绘制两点</p><p>右键单击结束绘制</p>', '400px');
            isAddParticleSystem = false;
            addFJetFire();
            return;
        }
        if (state.particleSelectedId == 0 && state.flameTyle == '3') {
            window.tooltip.showAt(' <p>点击鼠标左键绘制区域</p><p>右键单击结束分析</p>', '400px');
            isAddParticleSystem = false;
            addFlowingFire();
            return;
        }
        if (state.particleSelectedId == 1 && state.fountainTyle == '1') {
            window.tooltip.showAt(' <p>点击鼠标左键开始绘制两点</p><p>右键单击结束绘制</p>', '400px');
            isAddParticleSystem = false;
            addFJetFire();
            return;
        }
        viewer.enableCursorStyle = false;
        viewer._element.style.cursor = "";
        document.body.classList.add("measureCur");
        isAddParticleSystem = true;
        if(state.particleSelectedId == 2){
            window.tooltip.showAt(' <p>点击鼠标左键确认烟花中心位置</p>', '400px');
            return;
        }
        window.tooltip.showAt(' <p>点击鼠标左键确认位置</p><p>右键单击结束添加</p><p>选中模型进行删除和编辑</p> ', '400px');

        // if(state.particleSelectedId === 0)
        // addFlame();
    }

    function addModelEditor(model) {
        modelEditor = new Cesium.ModelEditor({
            model: model,
            scene: viewer.scene,
            axesShow: {
                "translation": true,
                "rotation": false,
                "scale": false
            }
        });
        modelEditor.activate();
        modelEditor.changedEvt.addEventListener((param) => {
            let Cartesian3 = new Cesium.Cartesian3();
            Cesium.Matrix4.getTranslation(param.modelMatrix, Cartesian3);
            if (Cartesian3 && selectParticleSystem) {
                selectParticleSystem.particleSystem.modelMatrix = selectParticleSystem.computeModelMatrix(Cartesian3);
                //旋转
                // var Matrix3 = new Cesium.Matrix3();
                // Cesium.Matrix4.getRotation(param.modelMatrix, Matrix3);
                // let quaternion = new Cesium.Quaternion();
                // Cesium.Quaternion.fromRotationMatrix(param.modelMatrix, quaternion);
                // let hpr = new Cesium.HeadingPitchRoll()
                // Cesium.HeadingPitchRoll.fromQuaternion(quaternion, hpr)
                // console.log(hpr)
                // if(hpr)
                selectParticleSystem.particleSystem.emitterModelMatrix = selectParticleSystem.computeEmitterModelMatrixByHpr(param.rotationAddtion)

            }
        })
    }
    function addModel(position, particleSystem, hpr) {
        let id = "particle-model-" + new Date().getTime();
        if (hpr) {
            s3mInstanceColc.add(modelUrl, {
                id: id,
                position: position,
                hpr: hpr
            });

        } else {
            s3mInstanceColc.add(modelUrl, {
                id: id,
                position: position,
                // scale: new Cesium.Cartesian3(6, 6, 6),
                // offset:new Cesium.Cartesian3(0, 0, -3),
            });
        }
        currentSelectedEntity = s3mInstanceColc.getInstance(modelUrl, id);
        entityParticlePairs.set(id, particleSystem);
    }

    function clear() {
        if (selectParticleSystem) selectParticleSystem.clear();
        if (fireWorkSystem) { fireWorkSystem.clearFireWoke(); setSceneForFireWork(false);fireWorkSystem = null };
        if (currentSelectedEntity) {
            entityParticlePairs.delete(currentSelectedEntity.id);
            s3mInstanceColc.removeInstance(modelUrl, currentSelectedEntity.id);
            currentSelectedEntity = null;
        }
        if (entityParticlePairs.size === 0) viewer.eventManager.removeEventListener("CLICK", click_addParticle);
        if (modelEditor) modelEditor.deactivate();
        isAddParticleSystem = false;
        selectParticleSystem = null;
        clearHandlerDrawing();
        viewer.enableCursorStyle = true;
        document.body.classList.remove("measureCur");
        tooltip.setVisible(false);
        clearHandlerDrawing('Polygon');
        flowingFires.forEach((ps) => ps.clear());
        flowingFires.length = 0;
    }

    // 水柱
    function addFountain(position) {
        let particleSystem = new ParticleSystem();
        particleSystem.create(state, position);
        addModel(position, particleSystem);
        selectParticleSystem = particleSystem;
        console.log(particleSystem)
    }

    // 监听

    watch(() => state.particleSelectedId, val => {
        selectParticleSystem = null;
        currentSelectedEntity= null;
        if (val === 2) {state.visibleParameter = false;}
        let particleParameter = {};
        if (val === 0) particleParameter = config[val].particleList[state.flameTyle];
        else if (val === 1) particleParameter = config[val].particleList[state.fountainTyle];
        for (const key in particleParameter) {
            if (state.hasOwnProperty(key)) {
                state[key] = particleParameter[key];
            }
        }
    });
    watch(() => state.flameTyle, val => {
        selectParticleSystem = null;
        currentSelectedEntity= null;
        if (modelEditor) modelEditor.deactivate();
        if (val == '4') state.bursts = [
            new Cesium.ParticleBurst({ time: 1.5, minimum: 80, maximum: 150 }),
            new Cesium.ParticleBurst({ time: 1.7, minimum: 150, maximum: 200 }),
        ];
        else state.bursts = [];
        let particleParameter = config[state.particleSelectedId].particleList[val];
        for (const key in particleParameter) {
            if (state.hasOwnProperty(key)) {
                state[key] = particleParameter[key];
            }
        }
    });
    watch(() => state.fountainTyle, val => {
        selectParticleSystem = null;
        currentSelectedEntity= null;
        if (modelEditor) modelEditor.deactivate();
        let particleParameter = config[state.particleSelectedId].particleList[val];
        for (const key in particleParameter) {
            if (state.hasOwnProperty(key)) {
                state[key] = particleParameter[key];
            }
        }
    });

    watch(() => state.emissionRate, val => {
        if (!selectParticleSystem) return;
        selectParticleSystem.particleSystem.emissionRate = Number(val);
    });
    watch(() => state.particleSize, val => {
        if (!selectParticleSystem) return;
        let particleSize = Number(val);
        selectParticleSystem.particleSystem.minimumImageSize.x = particleSize;
        selectParticleSystem.particleSystem.minimumImageSize.y = particleSize;
        selectParticleSystem.particleSystem.maximumImageSize.x = particleSize;
        selectParticleSystem.particleSystem.maximumImageSize.y = particleSize;
    });
    watch(() => state.particleLife, val => {
        if (!selectParticleSystem) return;
        selectParticleSystem.particleSystem.minimumParticleLife = Number(val[0]);
        selectParticleSystem.particleSystem.maximumParticleLife = Number(val[1]);
    });
    watch(() => state.speed, val => {
        if (!selectParticleSystem) return;
        selectParticleSystem.particleSystem.minimumSpeed = Number(val[0]);
        selectParticleSystem.particleSystem.maximumSpeed = Number(val[1]);
    });
    watch(() => state.startScale, val => {
        if (!selectParticleSystem) return;
        selectParticleSystem.particleSystem.startScale = Number(val);
    });
    watch(() => state.endScale, val => {
        if (!selectParticleSystem) return;
        selectParticleSystem.particleSystem.endScale = Number(val);
    });
    watch(() => state.particleSystemType, val => {
        if (!selectParticleSystem) return;
        switch (val) {
            case "circular":
                selectParticleSystem.particleSystem.emitter = new Cesium.CircleEmitter(2.0);
                break;
            case "spheroid":
                selectParticleSystem.particleSystem.emitter = new Cesium.SphereEmitter(2.5);
                break;
            case "conical":
                selectParticleSystem.particleSystem.emitter = new Cesium.ConeEmitter(Cesium.Math.toRadians(30.0));
                break;
            case "box":
                selectParticleSystem.particleSystem.emitter = new Cesium.BoxEmitter(new Cesium.Cartesian3(10.0, 10.0, 10.0));
                break;
            default:
                break;
        }
    });

    watch(() => state.image, val => {
        if (!selectParticleSystem) return;
        selectParticleSystem.particleSystem.image = val;
    });
    watch(() => state.startColor, val => {
        if (!selectParticleSystem) return;
        selectParticleSystem.particleSystem.startColor = Cesium.Color.fromCssColorString(val)
    });
    watch(() => state.endColor, val => {
        if (!selectParticleSystem) return;
        selectParticleSystem.particleSystem.endColor = Cesium.Color.fromCssColorString(val)
    });
    watch(() => state.visibleModel, val => {
        s3mInstanceColc.visible = val
        if (modelEditor) modelEditor.deactivate();
    })
    watch(() => state.ringRadius, val => {
        if (!selectParticleSystem) return;
        selectParticleSystem.particleSystem.emitter = new Cesium.CircleEmitter(val[1], val[0]);
        if (state.emitter[0] === 'CircleEmitter')
            state.emitter[1] = val;
    })
    watch(() => state.lifetime, val => {
        if (!selectParticleSystem) return;
        selectParticleSystem.particleSystem.lifetime = Number(val);
    })

    watch(() => state.gravity, val => {
        if (!selectParticleSystem) return;
        selectParticleSystem.gravity = (Number(val));
    })






    // 销毁
    onBeforeUnmount(() => {

    });


    return {
        ...toRefs(state),
        addParticle,
        clear
    };
}
Example #19
Source File: scan-effect.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
function scanEffect(props) {
    // 设置默认值数据
    let state = reactive({
        scanMode: "lineMode",
        scanColor: "#0F7AF4",
        scanTextures: [],
        selectedTextureIndex: 0,
        bloomShow: false,  //开启反光
        openHDR: false,  //开启HDR
        threshold: 0.01,  //亮度阈值
        intensity: 0.5,  //泛光强度
        lineWidth: 100,  //获取或设置线状扫描线的宽度,单位:米。
        period: 3.0,  //获取或设置扫描线的运行周期,单位:秒。
        speed: 100,  //获取或设置扫描线的运行速度,单位:米/秒。
        addTextures: null, //[{name:纹理1,type:'line / ring',url:xxx}]
        scanShow: false,
    })

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let lineScanTextures = [
        {
            name: '无纹理',
            type: 'line',
            url: ''
        }
    ];
    let circleScanTextures = [
        {
            name: '无纹理',
            type: 'ring',
            url: ''
        }
    ];
    getTextures(textures);

    function getTextures(arr) {
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].type === 'line') {
                lineScanTextures.push(arr[i])
            } else {
                circleScanTextures.push(arr[i])
            }
        }
        state.scanTextures = state.scanMode === 'lineMode' ? lineScanTextures : circleScanTextures;
    };

    if (storeState.isViewer) {
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
        init()
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
            init()
        }
    });

    function init() {
        viewer.scene.scanEffect.color = Cesium.Color.fromCssColorString(state.scanColor);
        viewer.scene.scanEffect.textureUrl = '';
        viewer.scene.scanEffect.lineWidth = Number(state.lineWidth);
        viewer.scene.scanEffect.period = Number(state.period);
        viewer.scene.scanEffect.speed = Number(state.speed);
        viewer.scene.scanEffect.centerPostion = new Cesium.Cartesian3.fromDegrees(0, 0, 0);
    };

    function drawPolyline() {
        if (!window.handlerPolyline) {
            initHandler("Polyline");
        }
        window.tooltip.showAt(' <p>点击鼠标左键开始绘制</p><p>绘制两点确定扫描线方向</p><p>鼠标右键结束绘制</p>', '350px');
        handlerDrawing("Polyline").then(
            res => {
                addLineScans(res.result.object.positions)
                let handlerPolyline = window.handlerPolyline;
                handlerPolyline.polyline.show = false;
                window.polylineTransparent.show = false; //半透线隐藏
                handlerPolyline.deactivate();
                tooltip.setVisible(false);
            },
            (err) => {
                console.log(err);
            }
        );
        window.handlerPolyline.activate();
    }

    function addLineScans(positions) {
        let dir = new Cesium.Cartesian3();
        Cesium.Cartesian3.subtract(positions[1], positions[0], dir); // 获取扫描方向向量
        if (state.scanShow) {
            viewer.scene.scanEffect.add(positions[0]);
            viewer.scene.scanEffect.lineMoveDirection = dir;
            return;
        }
        viewer.scene.scanEffect.centerPostion = positions[0];
        viewer.scene.scanEffect.lineMoveDirection = dir;
        state.scanShow = true;
    }

    function addCircleScans(e) {
        viewer.enableCursorStyle = true;
        document.body.classList.remove("measureCur");
        let centerPosition = viewer.scene.pickPosition(e.message.position);
        if (state.scanShow) {
            viewer.scene.scanEffect.add(centerPosition);
            return;
        }
        viewer.scene.scanEffect.centerPostion = centerPosition;
        state.scanShow = true;
        viewer.eventManager.removeEventListener("CLICK", addCircleScans);
    }



    function addScans() {
        if (state.scanMode === 'lineMode') {
            drawPolyline();
            return
        }
        viewer.enableCursorStyle = false;
        viewer._element.style.cursor = "";
        document.body.classList.add("measureCur");
        viewer.eventManager.addEventListener("CLICK", addCircleScans, true);
    }


    function clear() {
        state.scanShow = false;
        let index = viewer.scene.scanEffect.count;
        for (let i = 0; i < index; i++) {
            viewer.scene.scanEffect.remove(i);
        }
        viewer.eventManager.removeEventListener("CLICK", addCircleScans);
        clearHandlerDrawing('Polyline');
    }

    // 监听
    watch(() => state.scanShow, val => {
        viewer.scene.scanEffect.show = val;
    });
    watch(() => state.scanMode, val => {
        if(val ==="lineMode"){
            viewer.scene.scanEffect.mode = Cesium.ScanEffectMode.LINE;
            state.scanTextures = lineScanTextures ;
            return
        }
        viewer.scene.scanEffect.mode =  Cesium.ScanEffectMode.CIRCLE;
        state.scanTextures =  circleScanTextures;
    });
    watch(() => state.scanColor, val => {
        viewer.scene.scanEffect.color = Cesium.Color.fromCssColorString(val);
    });
    watch(() => state.selectedTextureIndex, val => {
        viewer.scene.scanEffect.textureUrl = state.scanTextures[val].url;
    });
    watch(() => state.scanTextures, val => {
        state.selectedTextureIndex = 0;
    });
    
    watch(() => state.bloomShow, val => {
        viewer.scene.bloomEffect.show = val;
        viewer.scene.bloomEffect.threshold = Number(state.threshold);
        viewer.scene.bloomEffect.bloomIntensity = Number(state.intensity);
    });
    watch(() => state.openHDR, val => {
        viewer.scene.hdrEnabled = val;
    });
    watch(() => state.threshold, val => {
        viewer.scene.bloomEffect.threshold = Number(val);
    });
    watch(() => state.intensity, val => {
        viewer.scene.bloomEffect.bloomIntensity = Number(val);
    });
    watch(() => state.lineWidth, val => {
        viewer.scene.scanEffect.lineWidth = Number(val);
    });
    watch(() => state.period, val => {
        viewer.scene.scanEffect.period = Number(val);
    });
    watch(() => state.speed, val => {
        viewer.scene.scanEffect.speed = Number(val);
    });
    watch(() => state.scanShow, val => {
        viewer.scene.scanEffect.scanShow = val;
    });
    watch(() => state.addTextures, val => {
        if(typeof(val) === 'object'){
            getTextures(val);
        }else{
            console.log('addTextures类型不是数组!')
        }
    });




    // 销毁
    onBeforeUnmount(() => {

    });


    return {
        ...toRefs(state),
        addScans,
        clear,
    };
}
Example #20
Source File: terrain-flood.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
//语言资源

function terrainFlood(props) {

    // 设置默认值数据
    let state = reactive({
        maxHeight: 9000, //最大可见高程
        minHeight: 1000, //最小可见高程
        floodHeight: [1000, 9000],
        currentHeight: 1000, //当前高程
        floodTrans: 0.8, //透明度
        cheackedBand: 'band1', //当前选择颜色
        colorBandShow: false, //颜色下拉框显隐
        floodSpeed: 800, //速度
        floodPositions: [],
        lineVisible: true, //是否显示绘制线
    })
    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }
    // 初始化数据
    let floodDisplayMode = Cesium.HypsometricSettingEnum.DisplayMode.FACE;
    let hypFlood = new Cesium.HypsometricSetting();
    let floodColorTable = new Cesium.ColorTable();
    floodColorTable.insert(9000, new Cesium.Color(0, 39 / 255, 148 / 255));
    floodColorTable.insert(0, new Cesium.Color(149 / 255, 232 / 255, 249 / 255));
    let interval;
    let floodPosition = [];
    /*
     ***地形淹没分析模块***
    */


    // 分析
    function floodBegin(e) {
        e.preventDefault();
        hypFlood.DisplayMode = floodDisplayMode;
        hypFlood._lineColor = new Cesium.Color(1.0, 0.0, 0.0, 1.0);
        hypFlood.MinVisibleValue = state.minHeight;
        hypFlood.MaxVisibleValue = 0;
        hypFlood.ColorTableMinKey = 1;
        hypFlood.ColorTableMaxKey = 9000;
        hypFlood.ColorTable = floodColorTable;
        hypFlood.Opacity = state.floodTrans;
        hypFlood.LineInterval = 200.0;
        if (!window.handlerPolygon) {
            common.initHandler("Polygon");
        }
        if (props && props.floodPositions) {
            floodUpdate(props.floodPositions);
            return;
        }
        common.handlerDrawing("Polygon", state.lineVisible).then(
            res => {
                let handlerPolygon = window.handlerPolygon;
                floodUpdate(res.positions);
                handlerPolygon.polygon.show = false;
                // handlerPolygon.polyline.show = false;
                handlerPolygon.deactivate();
            },
            err => {
                console.log(err);
            }
        );
        window.handlerPolygon.activate();
        if (!viewer.scene.pickPositionSupported) {
            tool.Message.errorMsg(resource.NoPickPositionSupported);
        }
    };
    function floodUpdate(positions) {
        if (positions) {
            floodPosition = positions;
        }
        let currentH = parseFloat(state.minHeight);
        hypFlood.CoverageArea = positions;
        interval = setInterval("flood()", 100);
        window.flood = () => {
            if (currentH <= state.maxHeight) {
                state.currentHeight = parseInt(currentH);
            }
            if (currentH > state.maxHeight) {
                state.currentHeight = state.maxHeight;
                clearInterval(interval);
                return;
            }
            hypFlood.MaxVisibleValue = currentH;
            try {
                viewer.scene.globe.HypsometricSetting = {
                    hypsometricSetting: hypFlood,
                    analysisMode:
                        Cesium.HypsometricSettingEnum.AnalysisRegionMode.ARM_REGION
                };
            } catch (err) {
                console.log(err);
                clearInterval(interval);
            };
            currentH += parseFloat(state.floodSpeed) / 10;
        };


    };
    // 清除
    function floodClear(e) {
        e.preventDefault();
        floodPosition = [];
        if (!window.handlerPolygon) return;
        viewer.scene.globe.HypsometricSetting = undefined;
        clearInterval(interval);
        common.clearHandlerDrawing("Polygon");
    };
    //选择颜色带bands
    function changeColor(band) {
        state.colorBandShow = false;
        state.cheackedBand = band;
    };

    //监听
    watch(() => state.floodTrans, val => {
        hypFlood.Opacity = parseFloat(val);
        if (floodPosition.length == 0) {
            return;
        }
        viewer.scene.globe.HypsometricSetting = {
            hypsometricSetting: hypFlood,
            analysisMode:
                Cesium.HypsometricSettingEnum.AnalysisRegionMode.ARM_REGION,
        };
    });
    watch(() => state.floodHeight, val => {
        state.minHeight = val[0];
        state.maxHeight = val[1];
    });
    watch(() => state.minHeight, val => {
        hypFlood.MinVisibleValue = parseInt(val);
        if (floodPosition.length == 0) {
            state.currentHeight = parseInt(val);
            return;
        }
        viewer.scene.globe.HypsometricSetting = {
            hypsometricSetting: hypFlood,
            analysisMode:
                Cesium.HypsometricSettingEnum.AnalysisRegionMode.ARM_REGION,
        };
    });
    watch(() => state.maxHeight, val => {
        hypFlood.MaxVisibleValue = parseInt(val);
        if (floodPosition.length == 0) {
            return;
        }
        viewer.scene.globe.HypsometricSetting = {
            hypsometricSetting: hypFlood,
            analysisMode:
                Cesium.HypsometricSettingEnum.AnalysisRegionMode.ARM_REGION,
        };
    });

    watch(() => state.cheackedBand, val => {
        floodColorTable = colorBandsChange(val);
        hypFlood.ColorTable = floodColorTable;
        if (floodPosition.length == 0) {
            return;
        }
        if (interval) {
            viewer.scene.globe.HypsometricSetting = {
                hypsometricSetting: hypFlood,
                analysisMode:
                    Cesium.HypsometricSettingEnum.AnalysisRegionMode.ARM_REGION
            };
        }
    });

    // 销毁
    onBeforeUnmount(() => {
        hypFlood.destroy();
        floodColorTable.destroy();
        hypFlood = undefined;
        floodColorTable = undefined;
    })

    return {
        ...toRefs(state),
        floodBegin,
        floodClear,
        changeColor,
        floodPosition
    };
}
Example #21
Source File: terrain-isoline.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
//语言资源

function terrainIsoline(props) {

    // 设置默认值数据
    let state = reactive({
        fillMaxHeight: 9000, //最大可见高程
        fillMinHeight: 0, //最小可见高程
        fillHeight: [0, 9000],
        equivalentIsoline: 100, //等值距
        fillOptionsSelected: 'Line', //当前选择模式
        lineColor: "#FF8040", //颜色
        isEdit: false, //是否编辑
        isolinePositions: [],
        lineVisible: true, //是否显示绘制线
    });
    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }
    // 初始化数据
    let hyp = new Cesium.HypsometricSetting();
    let DisplayModeHyp = Cesium.HypsometricSettingEnum.DisplayMode.LINE;  //显示模式
    let colorTable = new Cesium.ColorTable(); //建立颜色表
    colorTableInit(colorTable)
    let isolinePosition = [];  //保存当前分析区域

    /*
     ***等值线分析模块***
    */

    //初始化分析区域 (后面有需要可以添加监听)
    if (props && props.isolinePositions) {
        isolineUpdate(props.isolinePositions);
    }
    // 分析
    function isoLineAnalysis(e) {
        e.preventDefault();
        //参数配置
        hyp.DisplayMode = DisplayModeHyp;
        hyp._lineColor = Cesium.Color.fromCssColorString(state.lineColor);
        hyp.LineInterval = parseFloat(state.equivalentIsoline);
        hyp.MaxVisibleValue = parseFloat(state.fillMaxHeight);
        hyp.MinVisibleValue = parseFloat(state.fillMinHeight);
        hyp.ColorTableMinKey = 2736.88110351563;
        hyp.ColorTableMaxKey = 5597.06640625;
        hyp.ColorTable = colorTable;
        // hyp.Opacity = 0.4;
        if (!window.handlerPolygon) {
            initHandler("Polygon");
        }
        handlerDrawing("Polygon", state.lineVisible).then(
            res => {
                isolinePosition = res.positions;
                let handlerPolygon = window.handlerPolygon;
                //分析区域为指定区域
                isolineUpdate(isolinePosition)
                handlerPolygon.polygon.show = false;
                handlerPolygon.polyline.show = false;
                handlerPolygon.deactivate();
                if (state.isEdit) {
                    Edit(isolinePosition, false, isolineUpdate)
                }
            },
            err => {
                console.log(err);
            }
        );
        window.handlerPolygon.activate();
        if (!scene.pickPositionSupported) {
            tool.Message.errorMsg(resource.NoPickPositionSupported);
        }
    };
    // 更新
    function isolineUpdate(p) {
        if (p) {
            isolinePosition = p;
        }
        if (isolinePosition.length == 0) return;
        if (p) {
            hyp.CoverageArea = p;
        }
        viewer.scene.globe.HypsometricSetting = {
            hypsometricSetting: hyp,
            analysisMode:
                Cesium.HypsometricSettingEnum.AnalysisRegionMode.ARM_REGION
        }
    };
    // 清除
    function clearIsoLine(e) {
        e.preventDefault();
        isolinePosition = [];
        if (!window.handlerPolygon) return;
        viewer.scene.globe.HypsometricSetting = undefined;
        hyp && (hyp.MaxVisibleValue = -1000);
        hyp && (hyp.MinVisibleValue = -1000);
        clearHandlerDrawing("Polygon");
        clearEditHandler("Polygon");
    };
    //监听
    watch(() => state.fillMaxHeight, val => {
        hyp.MaxVisibleValue = parseFloat(val);
        if (isolinePosition.length == 0) {
            return;
        }
        isolineUpdate();
    });
    watch(() => state.fillMinHeight, val => {
        hyp.MinVisibleValue = parseFloat(val);
        if (isolinePosition.length == 0) {
            return;
        }
        isolineUpdate();
    });
    watch(() => state.fillHeight, val => {
        state.fillMinHeight = val[0];
        state.fillMaxHeight = val[1];
    });
    watch(() => state.equivalentIsoline, val => {
        hyp.LineInterval = parseFloat(val);
        if (isolinePosition.length == 0) {
            return;
        }
        isolineUpdate();
    });
    watch(() => state.lineColor, val => {
        if (val) {
            hyp._lineColor = Cesium.Color.fromCssColorString(val);
            // hyp.Opacity  = Number(rgbaNum(val, 3)) ;
            if (isolinePosition.length == 0) {
                return;
            }
            isolineUpdate();
        } else {
            console.warn('err: color is  null')
        }
    });
    watch(() => state.fillOptionsSelected, val => {
        switch (val) {
            case "None":
                {
                    DisplayModeHyp = undefined;
                }
                break;
            case "Line":
                {
                    DisplayModeHyp =
                        Cesium.HypsometricSettingEnum.DisplayMode.LINE;
                    hyp.Opacity = 1;
                }
                break;
            case "Region":
                {
                    DisplayModeHyp =
                        Cesium.HypsometricSettingEnum.DisplayMode.FACE;
                    hyp.Opacity = 0.5;
                }
                break;
            case "Line_Region":
                {
                    DisplayModeHyp =
                        Cesium.HypsometricSettingEnum.DisplayMode.FACE_AND_LINE;
                    hyp.Opacity = 0.5
                }
                break;
            default:
                break;
        }
        hyp.DisplayMode = DisplayModeHyp;
        if (isolinePosition.length == 0) {
            return;
        }
        isolineUpdate(isolinePosition)
    });
    watch(() => state.isEdit, val => {
        if (val && window.handlerPolygon) {
            Edit(isolinePosition, false, isolineUpdate)
        } else {
            clearEditHandler("Polygon");
            if (window.handlerPolygon && window.handlerPolygon.polygon) {
                window.handlerPolygon.polygon.show = false;
            }
        }
    });
    // 销毁
    onBeforeUnmount(() => {
        hyp.destroy();
        colorTable.destroy();
        hyp = undefined;
        colorTable = undefined;
    })

    return {
        ...toRefs(state),
        isoLineAnalysis,
        clearIsoLine,
        isolinePosition
    };
}
Example #22
Source File: terrain-slope.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
//简单局部状态管理

function terrainSlope(props) {
    // 设置默认值数据
    let slopData = reactive({
        analysisArea: 'ARM_REGION',//分析区域
        displayMode: 'FACE_AND_ARROW',//显示模式
        wideMaxR: 90, //最大坡度
        wideMinR: 0, //最小坡度
        slopeInterval:[0,90],
        trans: 0.8, //透明度
        isEdit: false,//是否编辑
        slopePositions:[],
        lineVisible: true,//是否显示绘制线
    });

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (slopData.hasOwnProperty(key)) {
                slopData[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }
    // 初始化数据
    let tipFlag = true;
    let slope = new Cesium.SlopeSetting(); //分析对象
    let wide = Cesium.HypsometricSettingEnum.AnalysisRegionMode[slopData.analysisArea]; //默认分析区域值
    let disMode = Cesium.SlopeSettingEnum.DisplayMode[slopData.displayMode]; //显示模式
    let SlopColorTable = new Cesium.ColorTable();  //颜色
    let slopePosition = [];  //保存当前分析区域
    SlopColorTable.insert(80, new Cesium.Color(255 / 255, 0 / 255, 0 / 255));
    SlopColorTable.insert(
        50,
        new Cesium.Color(221 / 255, 224 / 255, 7 / 255)
    );
    SlopColorTable.insert(
        30,
        new Cesium.Color(20 / 255, 187 / 255, 18 / 255)
    );
    SlopColorTable.insert(20, new Cesium.Color(0, 161 / 255, 1));
    SlopColorTable.insert(0, new Cesium.Color(9 / 255, 9 / 255, 255 / 255));

    /*
     ***坡度分析模块***
    */

    //初始化分析区域 (后面有需要可以添加监听)
    if (props && props.slopePositions) {
        slopeUpdate(props.slopePositions);
    }

    if (storeState.isViewer) {
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
        }
    });

    // 分析
    function startSlope(e) {
        e.preventDefault();
        tooltip.setVisible(false);
        if (tipFlag) {   //只提示一次
            window.tooltip.showAt(' <p>点击鼠标左键绘制分析区域</p><p>点击鼠标右键结束绘制</p><p>坡度坡向分析需要带法线地形</p>', '250px');
            tipFlag = false
        }
        slope.DisplayMode = disMode;
        slope.MaxVisibleValue = slopData.wideMaxR;
        slope.MinVisibleValue = slopData.wideMinR;
        slope.ColorTable = SlopColorTable;
        slope.Opacity = slopData.trans;
        // this.positions = [];
        // viewer.scene.globe.enableLighting = true;
            if (!window.handlerPolygon) {
                initHandler("Polygon");
            }
            handlerDrawing("Polygon", slopData.lineVisible).then(
                (res) => {
                    slopePosition = res.positions;
                    slopeUpdate(slopePosition);
                    let handlerPolygon = window.handlerPolygon;
                    handlerPolygon.polygon.show = false;
                    handlerPolygon.polyline.show = false;
                    handlerPolygon.deactivate();
                    if (slopData.isEdit) {
                        Edit(slopePosition, false, slopeUpdate);
                    }
                },
                (err) => {
                    console.log(err);
                }
            );
            handlerPolygon.activate();
            if (!scene.pickPositionSupported) {
                tool.Message.errorMsg(resource.NoPickPositionSupported);
            }
    };
    // 更新
    function slopeUpdate(p) {
        if (p) {
            slopePosition = p;
        }
        slope.CoverageArea = p;
        viewer.scene.globe.SlopeSetting = {
            slopeSetting: slope,
            analysisMode: wide,
        };
    };
    // 清除
    function clearSlope(e) {
        e.preventDefault();
        slopePosition = [];
        if (!window.handlerPolygon) return;
        viewer.scene.globe.SlopeSetting = {
            analysisMode: Cesium.HypsometricSettingEnum.AnalysisRegionMode.ARM_NONE,
        };
        tooltip.setVisible(false);
        clearHandlerDrawing("Polygon");
        clearEditHandler("Polygon");
    };

    watch(() => slopData.analysisArea, val => {
        switch (val) {
            case "ARM_REGION":
                {
                    wide =
                        Cesium.HypsometricSettingEnum.AnalysisRegionMode.ARM_REGION;
                }
                break;
            case "ARM_ALL":
                {
                    wide =
                        Cesium.HypsometricSettingEnum.AnalysisRegionMode.ARM_ALL;
                }
                break;
            case "ARM_NONE":
                {
                    wide =
                        Cesium.HypsometricSettingEnum.AnalysisRegionMode.ARM_NONE;
                }
                break;
            default:
                break;
        }
        if (slopePosition.length == 0) {
            return;
        }
        slopeUpdate(slopePosition)
    });

    watch(() => slopData.wideMaxR, val => {
        slope.MaxVisibleValue = parseFloat(val);
        if (slopePosition.length == 0) {
            return;
        }
        viewer.scene.globe.SlopeSetting = {
            slopeSetting: slope,
            analysisMode: wide,
        };
    });
    watch(() => slopData.wideMinR, val => {
        slope.MinVisibleValue = parseFloat(val);
        if (slopePosition.length == 0) {
            return;
        }
        viewer.scene.globe.SlopeSetting = {
            slopeSetting: slope,
            analysisMode: wide,
        };
    });
    watch(() => slopData.slopeInterval, val => {
        slopData.wideMinR = val[0];
        slopData.wideMaxR = val[1];
        // slope.MinVisibleValue = parseFloat(val[0]);
        // slope.MaxVisibleValue = parseFloat(val[1]);
        // if (slopePosition.length == 0) {
        //     return;
        // }
        // viewer.scene.globe.SlopeSetting = {
        //     slopeSetting: slope,
        //     analysisMode: wide,
        // };
    });
    

    watch(() => slopData.displayMode, val => {
        switch (val) {
            case "FACE":
                {
                    disMode = Cesium.SlopeSettingEnum.DisplayMode.FACE;
                }
                break;
            case "ARROW":
                {
                    disMode = Cesium.SlopeSettingEnum.DisplayMode.ARROW;
                }
                break;
            case "FACE_AND_ARROW":
                {
                    disMode = Cesium.SlopeSettingEnum.DisplayMode.FACE_AND_ARROW;
                }
                break;
            default:
                break;
        }
        slope.DisplayMode = disMode;
        if (slopePosition.length == 0) {
            return;
        }
        slopeUpdate(slopePosition)
    });

    watch(() => slopData.trans, val => {
        slope.Opacity = parseFloat(val);
        if (slopePosition.length == 0) {
            return;
        }
        viewer.scene.globe.SlopeSetting = {
            slopeSetting: slope,
            analysisMode: wide,
        };
    });
    watch(() => slopData.isEdit, val => {
        if (val && window.handlerPolygon) {
            Edit(slopePosition, false, slopeUpdate);
        } else {
            clearEditHandler("Polygon");
            if (window.handlerPolygon && window.handlerPolygon.polygon) {
                window.handlerPolygon.polygon.show = false;
            }
        }
    });
    // 销毁
    onBeforeUnmount(() => {
        slope.destroy();
        SlopColorTable.destroy();
        slope = undefined;
        SlopColorTable = undefined;
    })

    return {
        ...toRefs(slopData),
        startSlope,
        clearSlope,
        slopePosition
    };
}
Example #23
Source File: viewer.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
//语言资源
//初始化地球 
function initViewer(props, callback) {
  //初始化viewer
  if (window.viewer) {
    // window.viewer.destroy();
    window.viewer = null;
    // return;
  }
  let viewer;
  let isPCBroswer = (window.isPCBroswer = Cesium.FeatureDetection.isPCBroswer());
  if (isPCBroswer) {
    viewer = new Cesium.Viewer("cesiumContainer", {
      selectionIndicator: false,
      timeline: true,
      baseLayerPicker: false,
      //shadows: true,
      infoBox: false,
      // geocoder: true,  //查询
      // skyBox: false, // 关闭天空盒会一同关闭太阳,场景会变暗
      navigation: false,
      // contextOptions: {
      //   requestWebgl2: true
      // }
    });
    // 太阳光默认打开
    // viewer.scene.globe.enableLighting = true;
    //隐藏时间线控件
    document.getElementsByClassName(
      "cesium-viewer-timelineContainer"
    )[0].style.visibility = "hidden";
  } else {
    // 手机端
    viewer = new Cesium.Viewer("cesiumContainer", {
      selectionIndicator: false,
      infoBox: false,
      skyBox: false,
      navigation: false,
      contextOptions: {
        requestWebgl2: true
      }
    });
    let scene = viewer.scene;
    if (Cesium.defined(scene.sun)) {
      scene.globe.enableLighting = false;
    }
    if (Cesium.defined(scene.moon)) {
      scene.moon.show = false;
    }
    document.documentElement.style.height = window.innerHeight + "px";
    document.addEventListener(
      "touchmove",
      function (e) {
        e.preventDefault();
      },
      false
    );
  }

  viewer.scene.debugShowFramesPerSecond = true; //帧率
  viewer.scene.globe.baseColor = Cesium.Color.BLACK; // 没有影像图层时地球的底色
  // viewer.scene.globe.depthTestAgainstTerrain = false; //地形深度
  window.viewer = viewer;
  window.scene = viewer.scene;
  scene.moon.show = false;
  viewer.eventManager = new EventManager(viewer);  //添加事件管理派发
  let widget = viewer.cesiumWidget;
  actions.setIsViewer(true);  //初始化viewer标志 
  if (viewer.geocoder) {
    // 请开发者自行到supermap online官网(http://www.supermapol.com/)申请key
    viewer.geocoder.viewModel.geoKey = "fvV2osxwuZWlY0wJb8FEb2i5";
    // document.querySelector(".cesium-geocoder-input").placeholder =
    //   Resource.searchPlaceHolder;  //语言配置,后面维护
  }
  if (!window.tooltip) {
    window.tooltip = createTooltip(viewer._element);
  }

  function openingAnimation() {
    viewer.camera.flyTo({
      destination: new Cesium.Cartesian3(
        6788287.844465209,
        -41980756.10214644,
        29619220.04004376
      ),
      duration: 0,
      complete: function () {
        viewer.camera.flyTo({
          destination: new Cesium.Cartesian3.fromDegrees(
            110.60396458865515,
            34.54408834959379,
            30644793.325518917
          ),
          duration: 5,
        });

      },
    });
  }

  // 添加图层
  try {
    if (props && props.openingAnimation) {
      openingAnimation();
    }
    if (props && props.afterInitviewer) {
      props.afterInitviewer();
    }
    if (props && props.sceneUrl) {
      addScene(props.sceneUrl, {}, (layer) => {
       
      });
    }
    if (props && props.s3mScps) {
      addS3mLayers(props.s3mScps);
    }
  } catch (e) {
    if (widget._showRenderLoopErrors) {
      let title = resource.showRenderLoopErrors;
      widget.showErrorPanel(title, undefined, e);
    }
  };

  // 销毁
  onBeforeUnmount(() => {
    viewer.destroy();
    window.viewer = undefined;
    window.scene = undefined;
  })
}
Example #24
Source File: atropos-vue.js    From atropos with MIT License 4 votes vote down vote up
Atropos = {
  props: {
    component: { type: String, default: 'div' },
    innerClass: String,
    scaleClass: String,
    rotateClass: String,

    eventsEl: { type: [String, Object], default: undefined },
    alwaysActive: { type: Boolean, default: false },
    activeOffset: { type: Number, default: undefined },
    shadowOffset: { type: Number, default: undefined },
    shadowScale: { type: Number, default: undefined },
    duration: { type: Number, default: undefined },
    rotate: { type: Boolean, default: undefined },
    rotateTouch: { type: Boolean, default: undefined },
    rotateXMax: { type: Number, default: undefined },
    rotateYMax: { type: Number, default: undefined },
    rotateXInvert: { type: Boolean, default: undefined },
    rotateYInvert: { type: Boolean, default: undefined },
    stretchX: { type: Number, default: undefined },
    stretchY: { type: Number, default: undefined },
    stretchZ: { type: Number, default: undefined },
    commonOrigin: { type: Boolean, default: true },
    shadow: { type: Boolean, default: true },
    highlight: { type: Boolean, default: true },
  },
  emits: ['enter', 'leave', 'rotate'],
  setup(props, ctx) {
    const elRef = ref(null);
    const atroposRef = ref(null);
    const { slots, emit } = ctx;

    const init = () => {
      atroposRef.value = AtroposCore({
        el: elRef.value,
        ...props,
        onEnter() {
          emit('enter');
        },
        onLeave() {
          emit('leave');
        },
        onRotate(...args) {
          emit('rotate', ...args);
        },
      });
    };

    const destroy = () => {
      if (atroposRef.value) {
        atroposRef.value.destroy();
        atroposRef.value = null;
      }
    };

    onMounted(() => {
      init();
    });
    onBeforeUnmount(() => {
      destroy();
    });

    const cls = (...args) => {
      return args.filter((c) => !!c).join(' ');
    };

    return () =>
      h(
        props.component,
        {
          class: 'atropos',
          ref: elRef,
        },
        [
          h('span', { class: cls('atropos-scale', props.scaleClass) }, [
            h('span', { class: cls('atropos-rotate', props.rotateClass) }, [
              h('span', { class: cls('atropos-inner', props.innerClass) }, [
                slots.default && slots.default(),
                props.highlight && h('span', { class: 'atropos-highlight' }),
              ]),
              slots.rotate && slots.rotate(),
              props.shadow && h('span', { class: 'atropos-shadow' }),
            ]),
            slots.scale && slots.scale(),
          ]),
          slots.root && slots.root(),
        ],
      );
  },
}
Example #25
Source File: clip-plane2.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
//简单局部状态管理

function clipPlaneAnalysis(props) {
    // 设置默认值数据
    let state = reactive({
        isEdit: false,//是否编辑
        isEditZ: false,
        lineVisible: true,//是否显示绘制线
        PlanePositions: []
    });

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let layers;
    let planePosition = [];

    /*
     ***平面分析模块***
    */

    //初始化分析区域 (后面有需要可以添加监听)
    if (props && props.PlanePositions) {
        clipPolygonUpdate(props.PlanePositions);
    }
    if (storeState.isViewer) {
        layers = viewer.scene.layers.layerQueue;
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            layers = viewer.scene.layers.layerQueue;
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
        }
    })
    // 分析
    function clipPlaneStart(e) {
        e.preventDefault();
        tooltip.setVisible(false);
        tooltip.showAt(' <p>点击鼠标左键开始绘制</p><p>绘制三点确定一个平面</p><p>点击鼠标右键结束绘制</p>', '230px');
        if (!layers ) {
            layers = viewer.scene.layers.layerQueue;
        }
        for (let layer of layers) {
            layer.selectEnabled = false;
            // 设置被裁剪对象的颜色
            layer.clipLineColor = new Cesium.Color(1, 1, 1, 0);
        }
        // if (!window.handlerPolygon) {
        //     initHandler("Polygon");
        // }
        // handlerDrawing("Polygon", state.lineVisible).then(
        //     res => {
        //         let position = res.result.object.positions;
        //         clipPlaneUpdate(position);
        //         // handlerPolygon.polygon.show = false;
        //         // handlerPolygon.polyline.show = false;
        //         window.handlerPolygon.deactivate();
        //         tooltip.setVisible(false);
        //         if (state.isEdit) {
        //             Edit(planePosition, state.isEditZ, clipPlaneUpdate);
        //         }
        //     },
        //     err => {
        //         console.log(err);
        //     }
        // );

        if (!scene.pickPositionSupported) {
            alert("不支持深度纹理,无法绘制多边形,裁剪功能无法使用!");
        }
    };
    // 更新
    function clipPlaneUpdate(p) {
        planePosition = p;
        for (let layer of layers) {
            layer.clearCustomClipBox();
            layer.setCustomClipPlane(
                p[0],
                p[1],
                p[2]
            );
        }
    };

    // 清除
    function clearClipPlane(e) {
        e.preventDefault();
        tooltip.setVisible(false);
        planePosition = [];
        if (!window.handlerPolygon) return;
        clearHandlerDrawing("Polygon");
        for (let layer of layers) {
            layer.clearCustomClipBox();
        }
    };

    var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
    let arr = []
    let left_click = false;
    handler.setInputAction(function(e){
        var position = e.position; // 获取鼠标屏幕坐标
        var centerPosition = viewer.scene.pickPosition(position);
        arr[0] = centerPosition;
        left_click = true
        test()
       
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    handler.setInputAction(function(e){
        if(left_click){
            var endPosition = viewer.scene.pickPosition(e.endPosition);
            arr[1] = endPosition
            
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    handler.setInputAction(function(e){
        left_click = false;
        let obj = Cesium.Rectangle.fromCartesianArray(arr)
        let southeast = Cesium.Rectangle.southeast(obj) 
        let southwest = Cesium.Rectangle.southwest(obj) 
        let northwest = Cesium.Rectangle.northwest(obj) 
        let northeast = Cesium.Rectangle.northeast(obj) 
        let arr2 = [southeast,southwest,northwest,northeast];
        let arr4 = []
        arr2.forEach((p)=>{
            let arr3 = tool.CartographictoDegrees(p);
            arr4 =  arr4.concat(arr3)
        })
        console.log(arr4)
        clipPolygonUpdate(arr4)

    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    let shape
    function test(){
        shape = viewer.entities.add({
            name: 'Blue translucent, rotated, and extruded ellipse with outline',
            rectangle : {
                coordinates :  new Cesium.CallbackProperty(function () {
                    var obj=Cesium.Rectangle.fromCartesianArray(arr);
                    return obj;
                }, false),
                material : Cesium.Color.YELLOW.withAlpha(0.2),
                // height:Cesium.Cartographic.fromCartesian(arr[0]).height
            },
            classificationType: Cesium.ClassificationType.S3M_TILE, //面贴对象
        });

    }

        // 更新
        function clipPolygonUpdate(p) {
            for (let layer of layers) {
                layer.setModifyRegions([p], Cesium.ModifyRegionMode.CLIP_OUTSIDE);
            }
        };

    // 监听

    watch(() => state.isEdit, val => {
        if (val && window.handlerPolygon) {
            Edit(planePosition, state.isEditZ, clipPlaneUpdate);
        } else {
            clearEditHandler("Polygon");
            if (window.handlerPolygon && window.handlerPolygon.polygon) {
                window.handlerPolygon.polygon.show = false;
            }
        }
    });
    watch(() => state.isEditZ, val => {
        if (window.editHandler) {
            window.editHandler.isEditZ = val;
        }
    });


    // 销毁
    onBeforeUnmount(() => {
        layers = undefined;
    })

    return {
        ...toRefs(state),
        clipPlaneStart,
        clearClipPlane,
        planePosition
    };
}
Example #26
Source File: openness.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
function openness(props) {

    // 设置默认值数据
    let state = reactive({
        addHeight: 1,  //附加高度
        viewPosition: null,  //分析位置
        viewDomeRadius: 100,   //分析半径
        domeType: "ALLDOME",   //分析类型
        isClosed: false,  //是否封口
        visibleAreaColor: "rgba(9,199,112,0.5)",   //可见区颜色
        hiddenAreaColor: "rgba(238,114,22,0.5)",   //不可见颜色
        startAngle: 0,   //开始角度
        endAngle: 360,    //终止角度
    });

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let scene, viewDome, Entypositions, tipFlag = true;
    if (storeState.isViewer) {
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
        init();
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
            init();
        }
    });
    function init() {
        scene = viewer.scene;
        //初始化
        viewDome = new Cesium.ViewDome(scene); //构造新的开敞度分析对象
        viewDome.viewPosition = [0, 0, 0]; //初始化视点位置
        viewDome.distance = Number(state.viewDomeRadius); //可视距离
        viewDome.domeType = Cesium.ViewDomeType[state.domeType]; //开敞度类型,分为可视部分、不可视部分, 全部显示
        viewDome.visibleAreaColor = Cesium.Color.fromCssColorString(
            state.visibleAreaColor
        ); //可视部颜色
        viewDome.hiddenAreaColor = Cesium.Color.fromCssColorString(
            state.hiddenAreaColor
        ); //隐藏部分颜色
        viewDome.startAngle = Number(state.startAngle); //起始角度
        viewDome.endAngle = Number(state.endAngle); //终止角度
        viewDome.isClosed = state.isClosed; //封口
        viewDome.build(); //执行开敞度分析
    };

    /*
     ***分析模块***
    */


    //分析
   
    function analysis() {
        viewer.enableCursorStyle = false;
        viewer._element.style.cursor = "";
        document.body.classList.add("measureCur");
        if (tipFlag) {   //只提示一次
            window.tooltip.showAt(' <p>点击鼠标左键确认分析位置</p>', '250px');
            tipFlag = false
        }
        addPoint();
        //鼠标左键事件监听
        viewer.eventManager.addEventListener("CLICK", LEFT_CLICK, true);
        viewer.eventManager.addEventListener("MOUSE_MOVE", MOUSE_MOVE, true);
    };

    //   点击左键确认观察者点
    function LEFT_CLICK(e) {
        viewer.enableCursorStyle = true;
        document.body.classList.remove("measureCur");
        //获取点击位置笛卡尔坐标
        let position = scene.pickPosition(e.message.position);
        //将笛卡尔坐标转化为经纬度坐标
        let positions = tool.CartesiantoDegrees(position);
        positions[2] += Number(state.addHeight);
        //点击位置同步到显示框
        state.viewPosition = {
            longitude: positions[0].toFixed(6),
            latitude: positions[1].toFixed(6),
            height: positions[2].toFixed(2),
        };
        viewDome.viewPosition = positions;
        viewDome.build();
        window.tooltip.setVisible(false);
        viewer.eventManager.removeEventListener("CLICK", LEFT_CLICK);
        viewer.eventManager.removeEventListener("MOUSE_MOVE", MOUSE_MOVE);
        viewDome.startAngle = Number(state.startAngle); //改变属性后,加上才能更新效果(应该是缺陷)
    };

    function addPoint() {
        viewer.entities.removeById('opennessPoint');
        viewer.entities.add(new Cesium.Entity({
            id: 'opennessPoint',
            point: new Cesium.PointGraphics({
                color: Cesium.Color.fromCssColorString('rgba(238,114,22,1)'),
                pixelSize: 8
            }),
            // position: p
            position: new Cesium.CallbackProperty(() => {
                return Entypositions;
            }, false),
        }));
    }

    // 鼠标移动实时分析
    function MOUSE_MOVE(e) {
        Entypositions = scene.pickPosition(e.message.endPosition);
    }

    //改变经纬度动态移动
    function move(val) {

    };

    // 清除
    function clear() {
        viewer.entities.removeById('opennessPoint');
        document.body.classList.remove("measureCur");
        window.tooltip.setVisible(false);
        state.viewPosition = null;
        // viewDome.clear()
        viewDome.viewPosition = [0, 0, 0]; //初始化视点位置
        viewDome.startAngle = Number(state.startAngle); //起始角度
    };

    // 监听
    watch(() => state.viewDomeRadius, val => {
        if (val == "") return;
        viewDome.distance = Number(val);
    });
    watch(() => state.domeType, val => {
        if (val == "") return;
        viewDome.domeType = Cesium.ViewDomeType[val];
    });
    watch(() => state.isClosed, val => {
        if (val == "") return;
        viewDome.isClosed = val;
    });
    watch(() => state.startAngle, val => {
        if (val == "") return;
        viewDome.startAngle = Number(val);
    });
    watch(() => state.endAngle, val => {
        if (val == "") return;
        viewDome.endAngle = Number(val);
    });
    watch(() => state.visibleAreaColor, val => {
        if (val == "") return;
        let VisibleColor = Cesium.Color.fromCssColorString(val);
        viewDome.visibleAreaColor = VisibleColor;
    });
    watch(() => state.hiddenAreaColor, val => {
        if (val == "") return;
        let HiddenColor = Cesium.Color.fromCssColorString(val);
        viewDome.hiddenAreaColor = HiddenColor;
    });
    watch(() => state.addHeight, (val,oldval) => {
        let h = val - oldval;
        h = Cesium.defaultValue(h,0);
        viewDome.viewPosition[2] += Number(h);
        Entypositions = Cesium.Cartesian3.fromDegrees(viewDome.viewPosition[0], viewDome.viewPosition[1], viewDome.viewPosition[2]);
        viewDome.startAngle = Number(state.startAngle)
    });
    
  
    // 销毁
    onBeforeUnmount(() => {
        clear();
        viewDome.destroy();
        viewDome = undefined;
    })

    return {
        ...toRefs(state),
        analysis,
        clear
    };
}
Example #27
Source File: profile.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
function profile(props) {

    // 设置默认值数据
    let state = reactive({
        profile2d: false, //显示剖面分析结果
        polylineColor: "rgb(250, 213, 6)", //贴线颜色
        polylineWidth: 5,   //贴线宽度
        initEchartsOption:null,  //初始化自定义echarts配置对象
        updateEchartsOption:null , //自定义更新echarts配置对象
    });

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let myChart, count, //插值点个数
        Entypositions; //当前图标的位置
    let tipFlag = true;  //提示操作提醒一次
    let LatAndLons = []; //所有点的经纬度
    let Cartesians = [];  //所有点的笛卡尔
    let EditPositions= null; //编辑时保存之前位置

    const echarts_box = ref(null);
    onMounted(() => {
        initMyChart();
    });
    if (storeState.isViewer) {
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
        }
    });

    //初始化echarts
    function initMyChart() {
        if (window.echarts) {
            if (!myChart) {
                myChart = window.echarts.init(echarts_box.value);  //初始化echarts
                window.onresize = function () {
                    myChart.resize()  //自适应屏幕
                };
            }
        } else {
            tool.Message.warnMsg(resource.EchartsErr);
            return;
        }
        if(state.initEchartsOption){
            myChart.setOption(state.initEchartsOption);
            return;
        }
        myChart.setOption({
            title: {
                text: "剖面分析",
                textStyle: {
                    fontSize: 14
                }
            },
            grid: {
                left: 30,
                right: 0,
                top: 30,
                bottom: 8
            },
            tooltip: {},
            xAxis: {
                data: [],
            },
            yAxis: {
                data: [],
            },
            series: [
                {
                    type: "bar",
                    data: [],
                },
            ],
        });
    };
    /*
     ***分析模块***
    */

    //分析
    function analysis() {
        if (tipFlag) {   //只提示一次
            tooltip.showAt(' <p>点击鼠标左键开始绘制</p> <p>单击右键结束分析</p><p>选中可进行编辑</p>', '250px');
            tipFlag = false
        }
        if (!window.handlerPolyline) {
            initHandler("Polyline");
        }
        handlerDrawing("Polyline").then(
            res => {
                myChart.showLoading();
                EditPositions = res.positions;
                DrawPolylineUpdate(res.positions); //划线效果
                let handlerPolyline = window.handlerPolyline;
                handlerPolyline.polyline.show = false;
                window.polylineTransparent.show = false; //半透线隐藏
                handlerPolyline.deactivate();
                updataProfile3D('', res.result.object); //更新剖面
                Edit(EditPositions, false, updataProfile3D); //编辑功能
                tooltip.setVisible(false);
            },
            (err) => {
                console.log(err);
            }
        );
        window.handlerPolyline.activate();
    };

    // 绘制剖面分析的线
    function DrawPolylineUpdate(position) {
        viewer.entities.removeById('polyline-profile');
        viewer.entities.removeById('location4');
        let fullLineColor = Cesium.Color.fromCssColorString(state.polylineColor);
        viewer.entities.add({
            id: "polyline-profile",
            polyline: {
                positions: Cesium.Cartesian3.fromDegreesArrayHeights(position),
                width: state.polylineWidth,
                material: fullLineColor,
                clampToGround: true, //线贴地
                // classificationType: Cesium.ClassificationType.S3M_TILE, //线面贴对象
            },
        });
        entityUpdate();
    };

    // 更新剖面分析二维图
    function updataProfile3D(position, line) {
        state.profile2d = true; //打开echarts
        myChart.clear()
        myChart.showLoading();
        //position参数不起作用,是为了edit函数不冲突
        LatAndLons.length = 0; //清空之前的点数据
        Cartesians.length = 0; //清空之前的点数据
        let positions = [];
        //折线实现
        for (let i = 1, j = line._positions.length; i < j; i++) {
            let startPoint = line._positions[i - 1];
            let endPoint = line._positions[i];
            let d = Cesium.Cartesian3.distance(startPoint, endPoint)
            getCount(parseInt(d));
            for (let i = 1, j = count; i <= j; i++) {
                positions.push(
                    Cesium.Cartesian3.lerp(
                        startPoint,
                        endPoint,
                        i / count,
                        new Cesium.Cartesian3()
                    )
                );
            }
        }
        viewer.scene
            .clampToHeightMostDetailed(positions)
            .then((clampedCartesians) => {
                Cartesians = clampedCartesians;  //记录所有点的笛卡尔坐标
                LatAndLons = tool.CartesiantoDegreesObjs(Cartesians);  //记录所有点的经纬度坐标
                echartsOption();  //更新echarts
            });
    };

    //精度计算count插值
    function getCount(distance) {
        if (distance / 10000 > 1) {
            count = parseInt(distance / 100)    //  (>10000)  100m
        } else if (distance / 1000 > 5) {
            count = parseInt(distance / 10)    // (5000-10000)  10m
        } else if (distance / 1000 > 2) {
            count = parseInt(distance / 5)     // (2000-5000)  5m
        } else if (distance / 1000 > 1) {
            count = parseInt(distance / 2)     // (1000-2000)  2m
        } else if (distance / 100 > 5) {
            count = parseInt(distance / 1.5)   //  (500-1000) 1.5m
        } else if (distance / 100 > 2) {
            count = distance                  // (200-500) 1m 
        } else {
            count = distance * 2              //   (<200) 0.5m
        }
    }

    // 更新交互图标
    function entityUpdate() {
        if (viewer.entities.getById("location4")) {
            return;
        }
        viewer.entities.add({
            id: "location4",
            position: new Cesium.CallbackProperty(() => {
                return Entypositions;
            }, false),
            billboard: {
                image: "src/style/images/location4.png",
                width: 30,
                height: 40,
                scaleByDistance: new Cesium.NearFarScalar(10, 1.0, 2000, 0.6),
                eyeOffset :new Cesium.Cartesian3(0, 1, -5)
                // heightReference :Cesium.HeightReference.RELATIVE_TO_GROUND
                // disableDepthTestDistance :5000,
                // pixelOffset : new Cesium.Cartesian2(0.0, 1.0),
                // pixelOffsetScaleByDistance : new Cesium.NearFarScalar(1.5e2, 0.0, 8.0e6, 10.0)
            },
        });
    };

    // 更新图表数据
    function echartsOption() {
        myChart.hideLoading();
        myChart.clear();
        if(state.updateEchartsOption){
            myChart.setOption(state.updateEchartsOption);
            return;
        }
        let option = {
            title: {
                text: "剖面信息",
                textStyle: {
                    fontSize: 14
                }
            },
            // 定位
            grid: {
                left: 50,
                right: 8,
                top: 40,
                bottom: 20,
            },
            // backgroundColor: "rgba(73,139,156,0.0)",
            tooltip: {
                trigger: "axis",
                backgroundColor: "#ffffff",
                textStyle: {
                    color: "#000",
                },
                formatter: (param) => {
                    let dataIndex = param[0].dataIndex;
                    Entypositions = Cartesians[dataIndex];
                    return [
                        "当前位置: " + '<hr size=1 style="margin: 3px 0">',
                        "经度: " +
                        LatAndLons[dataIndex].longitude.toFixed(6) +
                        "<br/>",
                        "纬度: " +
                        LatAndLons[dataIndex].latitude.toFixed(6) +
                        "<br/>",
                        "海拔: " +
                        LatAndLons[dataIndex].height.toFixed(2) +
                        "米" +
                        "<br/>",
                    ].join("");
                },
            },
            xAxis: {
                data: LatAndLons.map(function (item, index) {
                    return index;
                }),
                show: false,
            },
            yAxis: {
                min: function (value) {
                    return value.min < 20 ? 0 : Math.floor(value.min);
                },
                axisLabel: {
                    interval: "auto",
                    formatter: function (value, index) {
                        return value > 999
                            ? (value / 1000).toFixed(2) + "km"
                            : value + "m";
                    },
                },
                splitLine: {
                    show: true,
                },
            },
            toolbox: {
                left: "right",
                feature: {
                    dataZoom: {
                        yAxisIndex: "none",
                    },
                    restore: {},
                    saveAsImage: {},
                },
            },
            dataZoom: [
                {
                    type: "inside",
                    xAxisIndex: 0,
                    filterMode: "filter",
                    start: 0,
                    end: 100,
                },
            ],
            series: {
                name: "height",
                type: "line",
                data: LatAndLons.map(function (item) {
                    return item.height;
                }),
                areaStyle: {},
            },
        };
        myChart.setOption(option);
    };

    // 清除
    function clear() {
        state.profile2d = false;
        viewer.entities.removeById('location4');
        viewer.entities.removeById('polyline-profile');
        myChart.clear();
        LatAndLons.length = 0; //清空之前的点数据
        Cartesians.length = 0; //清空之前的点数据
        clearHandlerDrawing("Polyline");
        clearEditHandler();
        initMyChart();
        tooltip.setVisible(false);
    };

    // 监听
    watch(() => state.profile2d, newValue => {
        if (!newValue || !myChart) {
            state.getSkyline2d = false;
            return;
        }
        setTimeout(() => {
            myChart.resize()  //自适应屏幕
        }, 200)
    });

    // 销毁
    onBeforeUnmount(() => {
        clear();
        myChart.clear();
        LatAndLons.length = 0; //清空之前的点数据
        Cartesians.length = 0; //清空之前的点数据
    })

    return {
        ...toRefs(state),
        echarts_box,
        myChart,
        Entypositions,
        LatAndLons,  //所有点的经纬度
        Cartesians,  //所有点的笛卡尔
        analysis,
        clear
    };
}
Example #28
Source File: shadow-query.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
function shadowquery(props) {

    // 设置默认值数据
    let state = reactive({
        timeValue: [24, 64],  //开始结束时间
        currentDate: new Date(),  //当前日期
        shadowShow: true,   //显示阴影,确定阴影是否由太阳投射形成。
        marks: {    //时间刻度标记
            0: "0:00",
            8: "",
            16: "",
            24: "6:00",
            32: "",
            40: "",
            48: "12:00",
            56: "",
            64: "",
            72: "18:00",
            80: "",
            88: "",
            96: "24:00"
        },
        timeInterval: 60,  //时间间隔
        spacing: 10,     //间距(米)
        bottomHeight: 1,  //底部高程(米)
        extrudeHeight: 30,  //拉伸高度(米)
        shadowQueryRegion: [],  //分析区域
        // shadows: true,   //确定阴影是否由太阳投射形成。
        layerShadowType: Cesium.ShadowType.ALL, // 图层上阴影类型:所有的模型都产生阴影。
        terrainShadows: Cesium.ShadowMode.RECEIVE_ONLY, //确定地形是否投射或接受来自太阳的阴影:(ShadowMode:该对象仅接收阴影)。
        showStartImgForTime: true,  //显示时间轴开始图标
        showStartImgForDate: true,   //显示日期开始图标
        shadowRadio: {  //获取阴影率结果对象
            'shadowRadio': '',
            'longitude': '',
            'latitude': '',
            'height': '',
            'isShow': false
        },
        dockFontShow: true, //停靠图标显示
        legendShow: false,  //图例显示
        shadowBodyShow: false, //阴影率体显示
        shadowBodyFilter: [0, 100]
    });

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化分析区域并执行
    if (props && props.shadowQueryRegion) {
        shadowQueryUpdate(props.shadowQueryRegion)
    }

    // 初始化数据
    let shadowQuery, layers, IntervalForTime,tipFlag = true, IntervalForDate, currentTimeArr = [...state.timeValue];
    const bubble = ref(null);

    let box_s3m = 'public/data/s3m/box.s3m';
    let s3mInstanceCollection, shadowQuery_points = [], setLayersFlag;
    //初始化体显示颜色(根具采光率0-100获取对应颜色值)
    let gradientColors = tool.gradientColors;  // 获取渐变色函数
    let color = ['#0000ff'];
    color = color.concat(gradientColors('#0000ff', '#00ffff', 20))
        .concat(gradientColors('#00ffff', '#00ff00', 20))
        .concat(gradientColors('#00ff00', '#ffff00', 20))
        .concat(gradientColors('#ffff00', '#ff7f00', 20))
        .concat(gradientColors('#ff7f00', '#ff0000', 20));

    if (storeState.isViewer) {
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
        init()
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
            init()
        }
    });
    //监听图层加载完成
    watch(() => storeState.changeLayers, val => {
        setLayerShadowType()
    });

    function init() {   //初始化函数
        let scene = viewer.scene;
        viewer.shadows = state.shadowShow;
        viewer.terrainShadows = state.terrainShadows;
        layers = viewer.scene.layers.layerQueue;
        scene.globe.enableLighting = true;
        scene.skyBox.show = true;
        viewer.clock.multiplier = 1;
        viewer.clock.shouldAnimate = true;
        shadowQuery = new Cesium.ShadowQueryPoints(scene);    //创建阴影查询对象
        s3mInstanceCollection = new Cesium.S3MInstanceCollection(scene._context);
        s3mInstanceCollection.setCullEnabled(box_s3m, true);  //开启单面渲染
        scene.primitives.add(s3mInstanceCollection);
        shadowQuery.queryPointsEvent.addEventListener(function (data) {  //分析完成回调
            shadowQuery_points = data;
            if (state.shadowBodyShow) {
                bodyShow()
            }
        })
        if (storeState.changeLayers) {
            setLayerShadowType()
        }
    }

    function setLayerShadowType() {
        for (let i = 0; i < layers.length; i++) {
            layers[i].shadowType = state.layerShadowType;
            setLayersFlag = true;
        }
    }

    /*
     ***分析模块***
    */

    // 时间轴改变
    function timeChanging(arr) {
        let tm;
        if (currentTimeArr[0] === arr[0]) {
            tm = setCurrentTime(arr[1]);
        } else {
            tm = setCurrentTime(arr[0]);
        }
        viewer.clock.currentTime = Cesium.JulianDate.fromDate(tm);
        currentTimeArr = arr;
    };

    //设置时间轴表示的当前时间
    function setCurrentTime(tm) {
        let h = parseInt(tm / 4);
        let m = parseInt((tm % 4) * 15);
        let d = state.currentDate;
        d.setHours(h);
        d.setMinutes(m);
        return d;
    };

    //时间轴改变后设置shadowQuery(不是实时监听)
    function timeChanged(val) {
        if (state.shadowShow) {
            shadowQuery.startTime = Cesium.JulianDate.fromDate(setCurrentTime(val[0]));
            shadowQuery.endTime = Cesium.JulianDate.fromDate(setCurrentTime(val[1]));
        }
        if(state.showStartImgForTime && state.shadowQueryRegion.length>0){
            shadowQuery.build()
        }
    };

    function filterChanged(val) {
        filterBodyShow(val)
    };

    // 时间轴提示函数
    function formatTooltip(val) {
        if (val === state.timeValue[0]) {
            return (
                "开始时间:" + timeSlice(setCurrentTime(val).toLocaleTimeString())
            );
        } else {
            return (
                "结束时间:" + timeSlice(setCurrentTime(val).toLocaleTimeString())
            );
        };
        function timeSlice(str) {
            let str2 = str.split(':');
            return str2[0] + ':' + str2[1]
        }
    };

    // 播放或暂停时间段内阳光和阴影动画
    function sunLightForTime(flag) {
        if (IntervalForDate) {
            state.showStartImgForDate = true;
            clearInterval(IntervalForDate)
        };
        if (!flag) {
            state.showStartImgForTime = true;
            clearInterval(IntervalForTime);
            return;
        } else {
            state.showStartImgForTime = false;
        }
        let time = [...currentTimeArr];
        let stm = time[0];
        let etm = time[1];
        let ntm = stm;
        IntervalForTime = setInterval(() => {
            if (ntm < etm) {
                ntm += 0.5;
                state.timeValue = [stm, ntm];
            } else {
                state.showStartImgForTime = true;
                clearInterval(IntervalForTime);
            }
        }, 50);
    };

    //播放一年的阳光和阴影动画
    function sunLightForDate(flag) {
        if (IntervalForTime) {
            clearInterval(IntervalForTime);
            state.showStartImgForTime = true;
        };
        if (!flag) {
            state.showStartImgForDate = true;
            clearInterval(IntervalForDate);
            return;
        } else {
            state.showStartImgForDate = false;
        }
        let d = setCurrentTime(currentTimeArr[1]); //时分秒默认按时间轴上结束的时间计算
        let mon = d.getMonth();
        IntervalForDate = setInterval(() => {
            if (mon < 11) {
                mon += 1;
            } else {
                mon = 0;
            }
            d.setMonth(mon);
            // viewer.clock.currentTime = Cesium.JulianDate.fromDate(d);
            state.currentDate = new Date(d)
        }, 1000);
    };

    //   阴影分析
    function analysis() {
        if (!state.shadowShow) {
            // tool.Message.warnMsg(resource.ShadowqueryWarn);
            state.shadowShow = true;
            return;
        }
        tooltip.setVisible(false);
        if (tipFlag) {   //只提示一次
            window.tooltip.showAt(' <p>点击鼠标左键绘制分析区域</p><p>点击鼠标右键结束绘制</p>', '350px');
            tipFlag = false
        }
        if (!setLayersFlag || layers[0].shadowType != state.layerShadowType) {
            setLayerShadowType()
        }
        if (!window.handlerPolygon) {
            initHandler("Polygon");
        }
        handlerDrawing("Polygon").then(
            res => {
                let handlerPolygon = window.handlerPolygon;
                shadowQueryUpdate(res.result.object.positions);
                handlerPolygon.polygon.show = false;
                handlerPolygon.polyline.show = false;
                //   window.polylineTransparent.show = false; //半透线隐藏
                handlerPolygon.deactivate();
                //鼠标左键事件监听
                viewer.eventManager.addEventListener("CLICK", LEFT_CLICK, true);
            },
            err => {
                console.log(err);
            }
        );
        window.handlerPolygon.activate();
        state.legendShow = true
    }

    //更新分析
    function shadowQueryUpdate(p) {
        timeChanged(state.timeValue);
        let position = [];
        shadowQuery.spacing = Number(state.spacing);
        shadowQuery.timeInterval = Number(state.timeInterval);
        let bh = Number(state.bottomHeight);
        let eh = Number(state.extrudeHeight);

        //遍历多边形,取出所有点
        let pos = Cesium.arrayRemoveDuplicates(
            p,
            Cesium.Cartesian3.equalsEpsilon
        );
        for (let i = 0, len = pos.length; i < len; i++) {
            //转化为经纬度,并加入至临时数组
            let cartographic = Cesium.Cartographic.fromCartesian(p[i]);
            let longitude = Cesium.Math.toDegrees(cartographic.longitude);
            let latitude = Cesium.Math.toDegrees(cartographic.latitude);
            position.push(longitude);
            position.push(latitude);
        }
        state.shadowQueryRegion = position;

        shadowQuery.qureyRegion({
            position: position,
            bottom: bh,
            extend: eh
        });
        shadowQuery.build();

    }


    // 鼠标左键事件 点击获取阴影率
    function LEFT_CLICK(e) {
        if (state.shadowBodyShow) {
            let box = scene.pick(e.message.position);
            if (box && box.id) {
                let point = shadowQuery_points[box.id];
                if (!point) return;
                let radio = point.shadowRatio * 100;
                if (radio < state.shadowBodyFilter[0] || radio > state.shadowBodyFilter[1]) state.shadowRadio.isShow = false;
                let position = tool.CartesiantoDegrees(point.position);
                state.shadowRadio = {
                    'shadowRadio': (point.shadowRatio * 100).toFixed(0) + '%',
                    'longitude': position[0].toFixed(8),
                    'latitude': position[1].toFixed(8),
                    'height': position[2].toFixed(8),
                    'isShow': true
                }
                bubble.value.style.top = (e.message.position.y - 160) + 'px';
                bubble.value.style.left = (e.message.position.x) + 'px';
            } else {
                state.shadowRadio.isShow = false
            }

        } else {
            let position1 = scene.pickPosition(e.message.position);
            let cartographic = Cesium.Cartographic.fromCartesian(position1);
            let shadowRadio = shadowQuery.getShadowRadio(cartographic);
            if (shadowRadio != -1) {
                let longitude = Cesium.Math.toDegrees(cartographic.longitude);
                let latitude = Cesium.Math.toDegrees(cartographic.latitude);
                let height = cartographic.height;
                state.shadowRadio = {
                    'shadowRadio': (shadowRadio * 100).toFixed(0) + '%',
                    'longitude': longitude.toFixed(8),
                    'latitude': latitude.toFixed(8),
                    'height': height.toFixed(8),
                    'isShow': true
                }
                bubble.value.style.top = (e.message.position.y - 160) + 'px';
                bubble.value.style.left = (e.message.position.x) + 'px';
            }
            else {
                state.shadowRadio.isShow = false
            }
        }
    }

    //关闭气泡
    function closeBubble() {
        state.shadowRadio.isShow = false
    }
    //悬停气泡
    function dockBubble(val) {
        if (val) {
            bubble.value.classList.add('bubbleDock');
            state.dockFontShow = false
        } else {
            bubble.value.classList.remove('bubbleDock');
            state.dockFontShow = true
        }
    }

    // 清除
    function clear() {
        state.legendShow = false;
        clearHandlerDrawing();
        // viewer.entities.removeAll();
        state.shadowQueryRegion.length = 0;
        tooltip.setVisible(false);
        closeBubble();
        viewer.eventManager.removeEventListener("CLICK", LEFT_CLICK); //移除鼠标点击事件监听
        shadowQuery.clear();
        shadowQuery_points.length = 0;
        s3mInstanceCollection.removeCollection(box_s3m);
        // state.shadowBodyShow = false
        for (let i = 0; i < layers.length; i++) {
            layers[i].shadowType = Cesium.ShadowType.NONE
        }
    };

    //体显示
    function bodyShow() {
        let objs = [];
        if (shadowQuery._bottom < 0 || shadowQuery_points.length == 0) {
            return;
        }
        let width = Number(state.spacing - 0.5);
        for (let i = 0, j = shadowQuery_points.length; i < j; i++) {
            objs.push({
                position: shadowQuery_points[i].position,
                color: getShadowRadioColor(shadowQuery_points[i].shadowRatio),
                scale: new Cesium.Cartesian3(width, width, width)
            })
        };
        if (objs.length > 0) {
            s3mInstanceCollection.add(box_s3m, objs);
        }
        filterBodyShow(state.shadowBodyFilter)
    };

    //体显示获取颜色
    function getShadowRadioColor(shadowRadio) {
        let index = parseInt((shadowRadio * 100));
        let col = color[index];
        return Cesium.Color.fromCssColorString(col);
    };

    //过滤体显示
    function filterBodyShow(arr) {
        if (shadowQuery._bottom <= 0 || shadowQuery_points.length == 0) {
            return;
        }
        for (let i = 0, j = shadowQuery_points.length; i < j; i++) {
            let Ratio = shadowQuery_points[i].shadowRatio * 100;
            if (Ratio < arr[0] || Ratio > arr[1]) {
                s3mInstanceCollection.getInstance(box_s3m, i).visible = false
            } else {
                s3mInstanceCollection.getInstance(box_s3m, i).visible = true
            }
        }
    }


    //   监听
    watch(() => state.timeValue, val => {
        timeChanging(val)
    });
    watch(() => state.currentDate, val => {
        timeChanging(currentTimeArr)
    });
    watch(() => state.timeInterval, val => {
        changeSlider(() => {
            shadowQuery.timeInterval = Number(val);
        })
    });
    watch(() => state.spacing, val => {
        changeSlider(() => {
            shadowQuery.spacing = Number(val);
        })
    });
    watch(() => state.bottomHeight, val => {
        if (state.shadowQueryRegion.length === 0) return;
        changeSlider(() => {
            let bh = Number(val);
            let eh = Number(state.extrudeHeight);
            shadowQuery.qureyRegion({
                position: state.shadowQueryRegion,
                bottom: bh,
                extend: eh
            });
            shadowQuery.build();
        })
    });
    watch(() => state.extrudeHeight, val => {
        if (state.shadowQueryRegion.length === 0) return;
        changeSlider(() => {
            let bh = Number(state.bottomHeight);
            let eh = Number(val);
            shadowQuery.qureyRegion({
                position: state.shadowQueryRegion,
                bottom: bh,
                extend: eh
            });
            shadowQuery.build();
        })
    });
    watch(() => state.shadowShow, val => {
        viewer.shadows = val;
        for (let i = 0, j = layers.length; i < j; i++) {
            if (layers[i].shadowType == state.layerShadowType) break;
            else layers[i].shadowType = state.layerShadowType
        }
    });
    watch(() => state.shadowBodyShow, val => {
        if (val) {
            shadowQuery.isPointsVisible = false;
            bodyShow()
        } else {
            shadowQuery.isPointsVisible = true;
            s3mInstanceCollection.removeCollection(box_s3m);
        }
    });

    let timer;
    // 防止滑块快速滑动的多次执行
    function changeSlider(callback) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(function () {
            callback()
        }, 500);

    }



    // 销毁
    onBeforeUnmount(() => {
        clear();

        shadowQuery.destroy();
        shadowQuery = undefined;
        viewer.shadows = false;
        layers = undefined;
    })

    return {
        ...toRefs(state),
        timeChanged,
        filterChanged,
        formatTooltip,
        sunLightForTime,
        sunLightForDate,
        analysis,
        clear,
        bubble,
        closeBubble,
        dockBubble
    };
}
Example #29
Source File: sight-line.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
function sightLine(props) {

    // 设置默认值数据
    let state = reactive({
        viewPosition: null,
        visibleColor: "rgb(0, 200, 0)",
        hiddenColor: "rgb(200, 0, 0)",
        barrierColor: "rgba(255, 186, 1, 1)",
        highlightBarrier: false,
        lineWidth: 3,
        showBarrierPoints:true
    });

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let scene, sightline, dragEntity
    let timer, tipFlag = true, clickFlag = false, ObjectIds = [];
    let point_index = 0, sightTargetPoints = [], sightBarrierPoints = [],sightBarrierPointsColor = [];
    let viewPointPosition;
    if (storeState.isViewer) {
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
        init();
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
            init();
        }
    });
    function init() {
        scene = viewer.scene;
        sightline = new Cesium.Sightline(scene);
        sightline.visibleColor = Cesium.Color.fromCssColorString(
            state.visibleColor
        );
        sightline.hiddenColor = Cesium.Color.fromCssColorString(state.hiddenColor);
      
        sightline.lineWidth = Number(state.lineWidth);
        dragEntity = new DragEntity(viewer, 'sightPoint_', _moveEndCallBack, _leftUpCallBack)
    };

    /*
     ***分析模块***
    */

    //分析
    function analysis() {
        viewer.enableCursorStyle = false;
        viewer._element.style.cursor = "";
        document.body.classList.add("measureCur");
        if (tipFlag) {   //只提示一次
            window.tooltip.showAt(' <p>点击鼠标左键确认观察者位置</p><p>再点击左键确认目标位置</p> <p>右键单击结束分析</p>', '400px');
            tipFlag = false
        }
        dragEntity.removeEventListener() //清除编辑交互事件
        //鼠标左键事件监听
        viewer.eventManager.addEventListener("CLICK", LEFT_CLICK, true);
        viewer.eventManager.addEventListener("MOUSE_MOVE", MOUSE_MOVE);
        viewer.eventManager.addEventListener("RIGHT_CLICK", RIGHT_CLICK, true);
    };

    //   点击左键确认观察者点和目标点
    function LEFT_CLICK(e) {
        clickFlag = true;
        clearTimeout(timer);
        timer = setTimeout(() => { clickFlag = false }, 20);  //添加点时延迟移动添加目标点
        let position = scene.pickPosition(e.message.position);
        let p = tool.CartesiantoDegrees(position) // 将获取的点的位置转化成经纬度
        if (p[2] < 0) {
            p[2] = 0;
            position = Cesium.Cartesian3.fromDegrees(p[0], p[1], p[2])
        }
        if (state.viewPosition) {
            sightline.addTargetPoint({
                position: p,
                name: "sightPoint_Target" + point_index,
            });
            sightTargetPoints.push(position);
            // 添加障碍点
            requestAnimationFrame(() => {
                requestAnimationFrame(() => {
                    sightline.getBarrierPoint(('sightPoint_Target' + point_index), (obj) => {
                        addSightPoint_Target(point_index);  //添加目标点 
                        if (obj && obj.position) {
                            obj.position.height += 2;
                            let position = Cesium.Cartographic.toCartesian(obj.position);
                            sightBarrierPoints.push(position);  //记录障碍点信息
                            // 记录障碍物id
                            let ObjectId = sightline.getObjectIds();
                            ObjectIds.push(ObjectId);
                            sightBarrierPointsColor.push(state.hiddenColor);
                        } else {
                            sightBarrierPoints.push({ x: 6378137, y: 0, z: 0 });
                            sightBarrierPointsColor.push(state.visibleColor);
                        }
                        addBarrierCone(point_index);  //添加障碍点
                        point_index += 1;
                    })
                })
            })
        } else {
            sightline.viewPosition = p;
            // 观察者信息记录
            state.viewPosition = p;
            sightline.build();
            addSightPoint_view();
            viewPointPosition = position;
        }
    };

    // 添加观察点
    function addSightPoint_view() {
        viewer.entities.add(new Cesium.Entity({
            id: 'sightPoint_view',
            point: new Cesium.PointGraphics({
                color: Cesium.Color.fromCssColorString(state.barrierColor),
                pixelSize: 10
            }),
            position: new Cesium.CallbackProperty(() => {
                return viewPointPosition;
            }, false),
        }));
    }

    function addSightPoint_Target(i) {
        viewer.entities.add(new Cesium.Entity({
            id: 'sightPoint_Target' + i,
            point: new Cesium.PointGraphics({
                // color: Cesium.Color.fromCssColorString(state.barrierColor),
                color:new Cesium.CallbackProperty(() => {
                    return Cesium.Color.fromCssColorString(sightBarrierPointsColor[i]);
                }, false),
                pixelSize: 10
            }),
            position: new Cesium.CallbackProperty(() => {
                return (sightTargetPoints[i]);
            }, false),
        }));
    }
    // 绘制障碍点圆锥
    let barrierCones = [];
    function addBarrierCone(i) {
       let ab = viewer.entities.add({
            name: 'Point_Barrier' + i,
            position: new Cesium.CallbackProperty(() => {
                return (sightBarrierPoints[i]);
            }, false),
            // orientation: Cesium.Transforms.headingPitchRollQuaternion(sightBarrierPoints[i], new Cesium.HeadingPitchRoll(0, 0, Math.PI)),
            cylinder: {
                length: 3,
                topRadius: 2,
                bottomRadius: 0,
                material: Cesium.Color.fromCssColorString("#d60000")
            }
        });
        barrierCones.push(ab)
    }

    // 鼠标移动实时分析
    function MOUSE_MOVE(e) {
        if (!state.viewPosition || clickFlag) return;
        //获取鼠标屏幕坐标,并将其转化成笛卡尔坐标
        let endPosition = scene.pickPosition(e.message.endPosition);
        let p = tool.CartesiantoDegrees(endPosition) // 将获取的点的位置转化成经纬度
        sightline.addTargetPoint({
            position: p,
            name: "point",
        });
    }

    // //鼠标右键确认分析距离和方向,不再执行鼠标移动事件中对可视域的操作
    function RIGHT_CLICK() {
        window.tooltip.setVisible(false);
        document.body.classList.remove("measureCur");
        if (state.highlightBarrier) {
            getHighlightBarriers()
        }
            sightline.removeTargetPoint('point');
            sightline.build()
        //拖拽编辑点
        dragEntity.addEventListener()
        viewer.eventManager.removeEventListener("CLICK", LEFT_CLICK); //移除鼠标点击事件监听
        viewer.eventManager.removeEventListener("MOUSE_MOVE", MOUSE_MOVE); //移除鼠标点击事件监听
        viewer.eventManager.removeEventListener("RIGHT_CLICK", RIGHT_CLICK); //移除鼠标点击事件监听
    };

    function _moveEndCallBack(Entity) {
        if(!Entity.id) return;
        if (Entity.id.includes('sightPoint_Target')) {
            let p = tool.CartesiantoDegrees(Entity.position._value) // 将获取的点的位置转化成经纬度
            sightline.addTargetPoint({
                position: p,
                name: Entity.id,
            });
        } else if (Entity.id.includes('sightPoint_view')) {
            let p = tool.CartesiantoDegrees(Entity.position._value) // 将获取的点的位置转化成经纬度
            sightline.viewPosition = p;
        }
    }

    function _leftUpCallBack(Entity) {
        requestAnimationFrame(() => {
            requestAnimationFrame(() => {
                if (!Entity.id) return;
                if (Entity.id.includes('sightPoint_view')) {
                    for (let i = 0, j = sightBarrierPoints.length; i < j; i++) {
                        setBarrierPoints('sightPoint_Target' + i,true)
                    }
                } else if(Entity.id.includes('sightPoint_Target')){
                    setBarrierPoints(Entity.id)
                }
                function setBarrierPoints(Barrier_id,isPointView) {
                    sightline.getBarrierPoint((Barrier_id), (obj) => {
                        let index = Barrier_id.charAt(Barrier_id.length - 1);
                        if (obj && obj.position) {
                            obj.position.height += 2;
                            let position = Cesium.Cartographic.toCartesian(obj.position);
                            let distance;
                            if(isPointView){
                                let lan_lon = sightline._targetPoints.values[index];
                                let Cartesian = Cesium.Cartesian3.fromDegrees(lan_lon[0], lan_lon[1], lan_lon[2])
                                distance = Cesium.Cartesian3.distance(Cartesian, position);
                            }else{
                                distance = Cesium.Cartesian3.distance(Entity.position._value, position);
                            }
                            if (distance >= 2.5) {
                                sightBarrierPoints[index] = position;  //更新障碍点信息
                                sightBarrierPointsColor[index] = state.hiddenColor;
                            } else {
                                sightBarrierPoints[index] = { x: 6378137, y: 0, z: 0 };  //更新障碍点信息
                                sightBarrierPointsColor[index] = state.visibleColor;
                            }
                            // 更新障碍物id
                            let ObjectId = sightline.getObjectIds();
                            ObjectIds.splice(index, 1, ObjectId);
                            if (state.highlightBarrier) {
                                for (let layer of scene.layers.layerQueue) {
                                    layer.removeAllObjsColor();
                                }
                                getHighlightBarriers()
                            }
                        } else {
                            sightBarrierPoints[index] = { x: 6378137, y: 0, z: 0 };  //更新障碍点信息
                            sightBarrierPointsColor[index] = state.visibleColor;
                        }
                    })
                }
            })
        })
    }
    // 获取障碍物
    function getHighlightBarriers(barrierColor) {
        let color = Cesium.defaultValue(barrierColor,Cesium.Color.fromCssColorString(state.barrierColor));
        try {
            if (ObjectIds.length === 0) return;
            ObjectIds.forEach((ObjectId) => {
                for (let index in ObjectId) {
                    let layer = viewer.scene.layers.findByIndex(Number(index) - 3); // 底层索引从3开始
                    let ids = ObjectId[index];
                    layer.setObjsColor(ids, color);
                }
            })

        } catch (error) {
            console.log(error)
        }
    }



    // 清除
    function clear() {
        sightline.removeAllTargetPoint();
        for (let layer of scene.layers.layerQueue) {
            layer.removeAllObjsColor();
        }
        point_index = 0;
        ObjectIds.length = 0;
        sightTargetPoints.length = 0;
        sightBarrierPoints.length = 0;
        sightBarrierPointsColor.length =0;
        dragEntity.removeEventListener()
        viewer.entities.removeAll();
        document.body.classList.remove("measureCur");
        window.tooltip.setVisible(false);
        state.viewPosition = null;
        barrierCones.length = 0;
        viewer.eventManager.removeEventListener("CLICK", LEFT_CLICK); //移除鼠标点击事件监听
        viewer.eventManager.removeEventListener("MOUSE_MOVE", MOUSE_MOVE); //移除鼠标点击事件监听
        viewer.eventManager.removeEventListener("RIGHT_CLICK", RIGHT_CLICK); //移除鼠标点击事件监听
    };

    // 监听
    watch(() => state.lineWidth, val => {
        if(sightline) sightline.lineWidth = Number(val);
    });
    watch(() => state.visibleColor, val => {
        if(sightline) 
        sightline.visibleColor = Cesium.Color.fromCssColorString(val);
    });
    watch(() => state.hiddenColor, val => {
        if(sightline) 
        sightline.hiddenColor = Cesium.Color.fromCssColorString(val);
    });
    watch(() => state.barrierColor, val => {
        if(ObjectIds.length === 0) return;
        let color  = Cesium.Color.fromCssColorString(val);
        getHighlightBarriers(color);
    });
    
    watch(() => state.highlightBarrier, newValue => {
        if (newValue) {
            getHighlightBarriers()
        } else {
            for (let layer of scene.layers.layerQueue) {
                layer.removeAllObjsColor();
            }
        }
    });
    watch(() => state.showBarrierPoints, val => {
        if(barrierCones.length === 0) return;
        barrierCones.forEach((b)=>{
            b.show = val
        })
    });
    

    // 销毁
    onBeforeUnmount(() => {
        clear();
        sightline = undefined;
    })

    return {
        ...toRefs(state),
        analysis,
        clear
    };
}