Cesium近地天空盒,解决图片旋转问题

前言
当我们使用官网的例子设置天空盒后,会发现天空云彩是斜的,比如下边这张图:
通过查阅网上资料,需要修改cesium的源码,以下是修改后skybox的源码,在自己的项目中引入即可:
实现代码
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\
";
/**
/**
 * A sky box around the scene to draw stars.  The sky box is defined using the True Equator Mean Equinox (TEME) axes.
 * <p>
 * This is only supported in 3D.  The sky box is faded out when morphing to 2D or Columbus view.  The size of
 * the sky box must not exceed {@link Scene#maximumCubeMapSize}.
 * </p>
 *
 * @alias SkyBox
 * @constructor
 *
 * @param {Object} options Object with the following properties:
 * @param {Object} [options.sources] The source URL or <code>Image</code> object for each of the six cube map faces.  See the example below.
 * @param {Boolean} [options.show=true] Determines if this primitive will be shown.
 *
 *
 * @example
 * scene.skyBox = new Cesium.SkyBox({
 *   sources : {
 *     positiveX : 'skybox_px.png',
 *     negativeX : 'skybox_nx.png',
 *     positiveY : 'skybox_py.png',
 *     negativeY : 'skybox_ny.png',
 *     positiveZ : 'skybox_pz.png',
 *     negativeZ : 'skybox_nz.png'
 *   }
 * });
 *
 * @see Scene#skyBox
 * @see Transforms.computeTemeToPseudoFixedMatrix
 */
function SkyBox(options) {
  /**
   * The sources used to create the cube map faces: an object
   * with <code>positiveX</code>, <code>negativeX</code>, <code>positiveY</code>,
   * <code>negativeY</code>, <code>positiveZ</code>, and <code>negativeZ</code> properties.
   * These can be either URLs or <code>Image</code> objects.
   *
   * @type Object
   * @default undefined
   */
  this.sources = options.sources;
  this._sources = undefined;
  /**
      * 是否开启近地模式
      */
  this.nearGround = options.nearGround;
  /**
   * 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;
}
/**
 * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
 * get the draw commands needed to render this primitive.
 * <p>
 * Do not call this function directly.  This is documented just to
 * list the exceptions that may be propagated when the scene is rendered:
 * </p>
 *
 * @exception {DeveloperError} this.sources is required and must have positiveX, negativeX, positiveY, negativeY, positiveZ, and negativeZ properties.
 * @exception {DeveloperError} this.sources properties must all be the same type.
 */
SkyBox.prototype.update = function (frameState, useHdr) {
  const that = this;
  if (!this.show) {
    return undefined;
  }
  if (
    frameState.mode !== SceneMode.SCENE3D &&
    frameState.mode !== SceneMode.MORPHING
  ) {
    return undefined;
  }
  // The sky box is only rendered during the render pass; it is not pickable, it doesn't cast shadows, etc.
  if (!frameState.passes.render) {
    return undefined;
  }
  const context = frameState.context;
  if (this._sources !== this.sources) {
    this._sources = this.sources;
    const sources = this.sources;
    //>>includeStart('debug', pragmas.debug);
    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."
      );
    }
    //>>includeEnd('debug');
    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;
  if (!defined(command.vertexArray)) {
    command.uniformMap = {
      u_cubeMap: function () {
        return that._cubeMap;
      },
      u_rotateMatrix: function () {
        return that.nearGround ? (command.modelMatrix = Transforms.eastNorthUpToFixedFrame(frameState.camera._positionWC),
          Matrix4.getMatrix3(command.modelMatrix, new Matrix3)) : Matrix3.IDENTITY;
      }
    };
    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.STATIC_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;
};
/**
 * Returns true if this object was destroyed; otherwise, false.
 * <br /><br />
 * If this object was destroyed, it should not be used; calling any function other than
 * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
 *
 * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
 *
 * @see SkyBox#destroy
 */
SkyBox.prototype.isDestroyed = function () {
  return false;
};
/**
 * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
 * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
 * <br /><br />
 * Once an object is destroyed, it should not be used; calling any function other than
 * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
 * assign the return value (<code>undefined</code>) to the object as done in the example.
 *
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 *
 *
 * @example
 * skyBox = skyBox && skyBox.destroy();
 *
 * @see SkyBox#isDestroyed
 */
SkyBox.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);
};
export default SkyBox;
修改代码的关键点:
1、添加近地属性,方便扩展
//......
function SkyBox(options) {
  this.sources = options.sources;
  this._sources = undefined;
  /**
      * 是否开启近地模式
      */
  this.nearGround = options.nearGround;
//......
}
2、修改顶点着色器
//顶点着色器有修改,主要是乘了一个旋转矩阵
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\
";
/**
3、修改command.uniformMap
command.uniformMap = {
      u_cubeMap: function () {
        return that._cubeMap;
      },
      u_rotateMatrix: function () {
        return that.nearGround ? (command.modelMatrix = Transforms.eastNorthUpToFixedFrame(frameState.camera._positionWC),
          Matrix4.getMatrix3(command.modelMatrix, new Matrix3)) : Matrix3.IDENTITY;
      }
    };
使用
import { default as SkyBox } from "@/lib/cesium/sky-SkyBox"
// 定义
const blueSkySkybox = new SkyBox({
  sources: {
    positiveX: fileUtil.getAssetsFile("skybox/blueSky/Right.jpg"),
    negativeX: fileUtil.getAssetsFile("skybox/blueSky/Left.jpg"),
    positiveY: fileUtil.getAssetsFile("skybox/blueSky/Front.jpg"),
    negativeY: fileUtil.getAssetsFile("skybox/blueSky/Back.jpg"),
    positiveZ: fileUtil.getAssetsFile("skybox/blueSky/Up.jpg"),
    negativeZ: fileUtil.getAssetsFile("skybox/blueSky/Down.jpg")
  },
  nearGround: true
})
// 使用
viewer.scene.postRender.addEventListener(function () {
    const e = viewer.camera.position;
    if (Cesium.Cartographic.fromCartesian(e).height < 2000) {
      viewer.scene.skyBox.nearGround = true;
      viewer.scene.skyBox = blueSkySkybox;
      viewer.scene.skyAtmosphere.show = false;
    } else {
      viewer.scene.skyBox = defaultSkyBox;
      viewer.scene.skyAtmosphere.show = true;
    }
  });
												
											Cesium近地天空盒,解决图片旋转问题的更多相关文章
- js获取图片的EXIF,解决图片旋转问题
		
相信大家在做项目的时候会遇到在canvas里加入图片时,图片发生90°,180°的旋转.当时的你肯定时懵逼的,为毛. 其实这就是图片的EXIF搞的鬼. 什么是EXIF 简单来说,Exif 信息就是由数 ...
 - flex 图片旋转(解决公转和自转问题)
		
在Flex中图片的旋转是既有公转和自转的.这样在图片旋转的时候就有一定小麻烦: 为了更好地说明问题,先引入两个概念:“自转”和“公转”.想象一下,地球在绕着太阳公转的同时,它自己也在自转.Flash应 ...
 - JQuery插件让图片旋转任意角度且代码极其简单
		
引入下方的jquery.rotate.js文件,然后通过$("选择器").rotate(角度);可以旋转任意角度, 例如$("#rotate-image").r ...
 - div内部实现图片旋转、放大、缩小、拖拽
		
药药,切克闹,一人我编码累,累把那bug写成堆.秋高气爽空气干燥你一定dei多喝水,过完了这周我就要回去.趁还有几天.你尽情的来跟我怼~~~ 新的一年,很久没更博客了,眼看十一要来了,听说过了十一就等 ...
 - JS实现图片base64转blob对象,压缩图片,预览图片,图片旋转到正确角度
		
base64转blob对象 /** 将base64转换为文件对象 * @param {String} base64 base64字符串 * */ var convertBase64ToBlob = f ...
 - file上传图片,base64转换、压缩图片、预览图片、将图片旋转到正确的角度
		
/** * 将base64转换为文件对象 * (即用文件上传输入框上传文件得到的对象) * @param {String} base64 base64字符串 */ function convertBa ...
 - JQuery插件让图片旋转任意角度且代码极其简单 - 摘自网友
		
JQuery插件让图片旋转任意角度且代码极其简单 2012-04-01 09:57:03 我来说两句 收藏 我要投稿 引入下方的jquery.rotate.js文件,然后通过$ ...
 - drawable-实现图片旋转
		
今天因为需要,所以要让一个图片随着某种需要进行旋转.但是,又不能一张张的做动态图片.所以就在网上找了这么个方法.但是,这个方法有个问题,就是虽然能实现图片的旋转.但是,图片旋转以后会进行缩放.具体原因 ...
 - ios手机竖屏拍照图片旋转90°问题解决方法
		
手机拍照会给图片添加一个Orientaion信息(即拍照方向),如下: 用ios手机拍照,系统会给图片加上一个方向的属性, ios相机默认的拍照方向是后摄Home键在右为正,前摄Home键在左为正. ...
 - H5 拍照图片旋转、压缩和上传
		
原文地址:github.com/whinc/blog/… 最近接到一个“发表评论”的需求:用户输入评论并且可以拍照或从相册选择图片上传,即支持图文评论.需要同时在 H5 和小程序两端实现,该需求处理图 ...
 
随机推荐
- 「SOL」射命丸文的笔记 (洛谷)
			
讲题人:"这是一个很经典的模型,大家应该都会" 我:"???" # 题面 给出 \(m\),求所有 \(m\) 个点的有标号强联通竞赛图的哈密顿回路数量的平均数 ...
 - https://ghproxy.com/ 下载代理
			
https://github.com/microsoft/PowerToys/releases/tag/v0.58.0 https://github.com/jgraph/drawio-desktop ...
 - 使用C++进行冒泡排序
			
#include "pch.h" #include <iostream> using namespace std;手动输入10个数,进行冒泡排序 int main() ...
 - HDFS Shell 操作
			
HDFS Shell 操作 HDFS Shell 命令行格式 格式一:hadoop fs –命令名 参数 格式二:hdfs dfs –命令名 参数 HDFS 常用命令及参数 ls:查看 hdfs 中的 ...
 - oracle修改表中的列
			
declare v_Count1 int := 0; v_Count2 int := 0; v_Count3 int := 0; v_Count4 int := 0; v_Count5 int := ...
 - tomcat任务部署
			
tomcat项目部署 主机 IP 需求 web-1 192.168.78.144 tomcat+jenkins web-2 192.168.78.145 tomcat 在RHEL-1主机上部署的jen ...
 - PHP接口跨域问题的解决方案
			
先来看一下问题 请求头有多余的参数 解决方案是配置允许 详细代码如下: // 可跨域域名列表$domains = [ 'http://localhost:8080', 'http://test.qqq ...
 - Tomcat和Maven安装与配置
			
链接:https://pan.baidu.com/s/1aezz2pfCn0DCCPw8udQFXA 提取码:wd4f 一.网站发布1.1.为什么要用tomcat网页开发好了,该如何发布呢?我们需要一 ...
 - C#.NET系列●接口抽象类
			
一.接口基本概念 (1)接口:是把公共方法和属性组合起来,以封装特定功能的一个集合.创建接口时,一般一大写的I开头,接口中的成员都是公有的. 接口定义如下: interface IClown //写一 ...
 - python中的异常类