Cesium

Cesium自定义天空盒1

前言

Cesium近景默认的天空盒在很多场景下无法满足用户的需求,有时需要自定义天空,如果想要不改源码想要改变Cesium近景天空盒就需要重写SkyBox类。

1.引入库

代码如下(示例):

<script src="myurl/MySkyBox.js"></script>

2.重写SkyBox.JS

以下代码复制自Cesium源码的SkyBox,然后做了一点点修改。
MySkyBox.js代码如下:

(function () {
    const Cesium = window.Cesium;
    const BoxGeometry = Cesium.BoxGeometry;
    const Cartesian3 = Cesium.Cartesian3;
    const defaultValue = Cesium.defaultValue;
    const defined = Cesium.defined;
    const destroyObject = Cesium.destroyObject;
    const DeveloperError = Cesium.DeveloperError;
    const GeometryPipeline = Cesium.GeometryPipeline;
    const Matrix3 = Cesium.Matrix3;
    const Matrix4 = Cesium.Matrix4;
    const Transforms = Cesium.Transforms;
    const VertexFormat = Cesium.VertexFormat;
    const BufferUsage = Cesium.BufferUsage;
    const CubeMap = Cesium.CubeMap;
    const DrawCommand = Cesium.DrawCommand;
    const loadCubeMap = Cesium.loadCubeMap;
    const RenderState = Cesium.RenderState;
    const VertexArray = Cesium.VertexArray;
    const BlendingState = Cesium.BlendingState;
    const SceneMode = Cesium.SceneMode;
    const ShaderProgram = Cesium.ShaderProgram;
    const ShaderSource = Cesium.ShaderSource;
    //片元着色器,直接从源码复制
    const SkyBoxFS = "uniform samplerCube u_cubeMap;\n\
  varying vec3 v_texCoord;\n\
  void main()\n\
  {\n\
  vec4 color = textureCube(u_cubeMap, normalize(v_texCoord));\n\
  gl_FragColor = vec4(czm_gammaCorrect(color).rgb, czm_morphTime);\n\
  }\n\
  ";

    //顶点着色器有修改,主要是乘了一个旋转矩阵
    const SkyBoxVS = "attribute vec3 position;\n\
  varying vec3 v_texCoord;\n\
  uniform mat3 u_rotateMatrix;\n\
  void main()\n\
  {\n\
  vec3 p = czm_viewRotation * u_rotateMatrix * (czm_temeToPseudoFixed * (czm_entireFrustum.y * position));\n\
  gl_Position = czm_projection * vec4(p, 1.0);\n\
  v_texCoord = position.xyz;\n\
  }\n\
  ";
     /**
     * 为了兼容高版本的Cesium,因为新版cesium中getRotation被移除
     */
    if (!Cesium.defined(Cesium.Matrix4.getRotation)) {
        Cesium.Matrix4.getRotation = Cesium.Matrix4.getMatrix3
    }
    function SkyBoxOnGround(options) {
        /**
         * 近景天空盒
         * @type Object
         * @default undefined
         */
        this.sources = options.sources;
        this._sources = undefined;

        /**
         * Determines if the sky box will be shown.
         *
         * @type {Boolean}
         * @default true
         */
        this.show = defaultValue(options.show, true);

        this._command = new DrawCommand({
            modelMatrix: Matrix4.clone(Matrix4.IDENTITY),
            owner: this
        });
        this._cubeMap = undefined;

        this._attributeLocations = undefined;
        this._useHdr = undefined;
    }

    const skyboxMatrix3 = new Matrix3();
    SkyBoxOnGround.prototype.update = function (frameState, useHdr) {
        const that = this;

        if (!this.show) {
            return undefined;
        }

        if ((frameState.mode !== SceneMode.SCENE3D) &&
            (frameState.mode !== SceneMode.MORPHING)) {
            return undefined;
        }

        if (!frameState.passes.render) {
            return undefined;
        }

        const context = frameState.context;

        if (this._sources !== this.sources) {
            this._sources = this.sources;
            const sources = this.sources;

            if ((!defined(sources.positiveX)) ||
                (!defined(sources.negativeX)) ||
                (!defined(sources.positiveY)) ||
                (!defined(sources.negativeY)) ||
                (!defined(sources.positiveZ)) ||
                (!defined(sources.negativeZ))) {
                throw new DeveloperError('this.sources is required and must have positiveX, negativeX, positiveY, negativeY, positiveZ, and negativeZ properties.');
            }

            if ((typeof sources.positiveX !== typeof sources.negativeX) ||
                (typeof sources.positiveX !== typeof sources.positiveY) ||
                (typeof sources.positiveX !== typeof sources.negativeY) ||
                (typeof sources.positiveX !== typeof sources.positiveZ) ||
                (typeof sources.positiveX !== typeof sources.negativeZ)) {
                throw new DeveloperError('this.sources properties must all be the same type.');
            }

            if (typeof sources.positiveX === 'string') {
                // Given urls for cube-map images.  Load them.
                loadCubeMap(context, this._sources).then(function (cubeMap) {
                    that._cubeMap = that._cubeMap && that._cubeMap.destroy();
                    that._cubeMap = cubeMap;
                });
            } else {
                this._cubeMap = this._cubeMap && this._cubeMap.destroy();
                this._cubeMap = new CubeMap({
                    context: context,
                    source: sources
                });
            }
        }

        const command = this._command;

        command.modelMatrix = Transforms.eastNorthUpToFixedFrame(frameState.camera._positionWC);
        if (!defined(command.vertexArray)) {
            command.uniformMap = {
                u_cubeMap: function () {
                    return that._cubeMap;
                },
                u_rotateMatrix: function () {
                    return Matrix4.getRotation(command.modelMatrix, skyboxMatrix3);
                },
            };

            const geometry = BoxGeometry.createGeometry(BoxGeometry.fromDimensions({
                dimensions: new Cartesian3(2.0, 2.0, 2.0),
                vertexFormat: VertexFormat.POSITION_ONLY
            }));
            const attributeLocations = this._attributeLocations = GeometryPipeline.createAttributeLocations(geometry);

            command.vertexArray = VertexArray.fromGeometry({
                context: context,
                geometry: geometry,
                attributeLocations: attributeLocations,
                bufferUsage: BufferUsage._DRAW
            });

            command.renderState = RenderState.fromCache({
                blending: BlendingState.ALPHA_BLEND
            });
        }

        if (!defined(command.shaderProgram) || this._useHdr !== useHdr) {
            const fs = new ShaderSource({
                defines: [useHdr ? 'HDR' : ''],
                sources: [SkyBoxFS]
            });
            command.shaderProgram = ShaderProgram.fromCache({
                context: context,
                vertexShaderSource: SkyBoxVS,
                fragmentShaderSource: fs,
                attributeLocations: this._attributeLocations
            });
            this._useHdr = useHdr;
        }

        if (!defined(this._cubeMap)) {
            return undefined;
        }

        return command;
    };
    SkyBoxOnGround.prototype.isDestroyed = function () {
        return false
    };
    SkyBoxOnGround.prototype.destroy = function () {
        const command = this._command;
        command.vertexArray = command.vertexArray && command.vertexArray.destroy();
        command.shaderProgram = command.shaderProgram && command.shaderProgram.destroy();
        this._cubeMap = this._cubeMap && this._cubeMap.destroy();
        return destroyObject(this);
    }
   window.Cesium.GroundSkyBox= SkyBoxOnGround
})();

3.使用

以下代码复制自Cesium源码的SkyBox,然后做了一点点修改。
MySkyBox.js代码如下:

    /**
     * 自定义天空盒(扩展,不修改源码)
     */
        let currentSkyBox = new Cesium.GroundSkyBox({
        sources: {
            positiveX: 'img/sky/right.jpg',
            negativeX: 'img/sky/left.jpg',
            positiveY: 'img/sky/back.jpg',
            negativeY: 'img/sky/front.jpg',
            positiveZ: 'img/sky/top.jpg',
            negativeZ: 'img/sky/down.jpg'
            // positiveX: 'img/sky/px.png',
            // negativeX: 'img/sky/nx.png',
            // positiveY: 'img/sky/py.png',
            // negativeY: 'img/sky/ny.png',
            // positiveZ: 'img/sky/pz.png',
            // negativeZ: 'img/sky/nz.png'
        }
    })

    let defaultSkybox = viewer.scene.skyBox;
    viewer.scene.postRender.addEventListener(function () {
        let e = viewer.camera.position;
        //相机高度低于8000显示自定义天空
        if(Cesium.Cartographic.fromCartesian(e).height < 8000){
            viewer.scene.skyBox = currentSkyBox;
            viewer.scene.skyAtmosphere.show = false;
        }else {
            viewer.scene.skyBox = defaultSkybox;
            viewer.scene.skyAtmosphere.show = true;
        }

    })

总结

本文章转载于网络,记录一下方便日后学习。
天空图片链接:https://pan.baidu.com/s/19qnivSq7IS5OIeeUUvNEyg 提取码:zxmc

09-15
Cesium是一个用于创建基于Web的地理信息系统(GIS)应用程序的开源JavaScript库,能够在浏览器中实现全球范围内的三维地理数据可视化。 ### 使用方法 1. **引入Cesium库**:可以通过CDN或本地下载的方式引入Cesium库。使用CDN的方式如下: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"> <title>Cesium Example</title> <script src="https://cesium.com/downloads/cesiumjs/releases/1.91/Build/Cesium/Cesium.js"></script> <link href="https://cesium.com/downloads/cesiumjs/releases/1.91/Build/Cesium/Widgets/widgets.css" rel="stylesheet"> </head> <body> <div id="cesiumContainer"></div> <script> // 初始化Cesium Viewer var viewer = new Cesium.Viewer('cesiumContainer'); </script> </body> </html> ``` 2. **加载数据**:Cesium支持多种数据格式,如3DTiles、glTF、glb等。以加载3DTiles为例: ```javascript var tileset = new Cesium.Cesium3DTileset({ url: 'path/to/your/tileset.json' }); viewer.scene.primitives.add(tileset); ``` ### 功能介绍 1. **数据支持**:Cesium的数据格式主要是3DTiles,由tileset.json和tile组成,tile可以是.b3dm、.i3dm、.pnts、.vctr和.cmpt中的任一种格式文件。此外,还支持其它3D格式,包括glTF、glb、Quantized - mesh(.terrain)等,也支持将obj、BIM等其它数据转换为3DTiles格式后加载 [^1]。 2. **三维可视化**:可以对地形、影像、三维模型等地理数据进行可视化展示,为用户提供逼真的三维地理环境。 3. **交互功能**:支持用户进行缩放、平移、旋转等交互操作,方便用户从不同角度观察地理数据。 4. **分析功能**:可进行距离测量、面积测量、地形分析等功能,为地理信息分析提供支持。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值