Cesium中DrawCommand使用
viewer.scene.primitives.add(object)方法在添加自定義的物體時,首先會加載object里的update方法,若沒有則會報如下錯誤
代碼如下:
//定義一個Trangles類
function Trangles(options) {
this._viewer = options.viewer
this._modelMatrix = options.modelMatrix
this.arr = options.arr
}
//用prototype給定方法和屬性
Trangles.prototype.getCommand = function(context) {
//頂點着色器
let v = `
attribute vec3 position3DHigh;
attribute vec3 position3DLow;
void main()
{
vec4 p = czm_translateRelativeToEye(position3DHigh, position3DLow);
p = czm_modelViewProjectionRelativeToEye * p;
gl_Position = p;
}
`
//片元着色器
let f = `void main()
{
gl_FragColor = vec4(0,1,0,1);
}
`
//shaderProgram將兩個着色器合並
var shaderProgram = Cesium.ShaderProgram.fromCache({
context: context,
vertexShaderSource: v,
fragmentShaderSource: f
})
//渲染狀態
var renderState = Cesium.RenderState.fromCache({
depthTest: {
enabled: false
},
depthMask: false,
blending: Cesium.BlendingState.ALPHA_BLEND
})
//索引數組Buffer
var indexBuffer = Cesium.Buffer.createIndexBuffer({
context: context,
typedArray: new Uint32Array([0, 1, 2]), //索引順序
usage: Cesium.BufferUsage.STATIC_DRAW,
indexDatatype: Cesium.IndexDatatype.UNSIGNED_INT
})
//頂點數組Buffer
var vertexBuffer = Cesium.Buffer.createVertexBuffer({
context: context,
typedArray: Cesium.ComponentDatatype.createTypedArray(
Cesium.ComponentDatatype.FLOAT,
this.arr //頂點位置數組
),
usage: Cesium.BufferUsage.STATIC_DRAW
})
//用來表示逐個頂點的信息
var attributes = []
attributes.push({
index: 0,
vertexBuffer: vertexBuffer,
componentDatatype: Cesium.ComponentDatatype.FLOAT,
componentsPerAttribute: 3,
normalize: false
})
//頂點數組(設置頂點屬性和索引Buffer)
var vertexArray = new Cesium.VertexArray({
context: context,
attributes: attributes,
indexBuffer: indexBuffer
})
//新建一個DrawCommand
this.pointCommand = new Cesium.DrawCommand({
primitiveType: Cesium.PrimitiveType.TRIANGLES,
shaderProgram: shaderProgram,
renderState: renderState,
vertexArray: vertexArray,
pass: Cesium.Pass.OPAQUE,
modelMatrix: this._modelMatrix
})
}
Trangles.prototype.destroy = function() {
//this.arr = [];
}
Trangles.prototype.update = function(frameState) {
if (this.pointCommand) {
var commandList = frameState.commandList
commandList.push(this.pointCommand)
this._viewer.scene.requestRender()
} else {
this.getCommand(this._viewer.scene.context)
}
}
//模型矩陣
var position = Cesium.Cartesian3.fromDegrees(119, 40, 0)
var heading = Cesium.Math.toRadians(0)
var pitch = Cesium.Math.toRadians(0)
var roll = Cesium.Math.toRadians(0)
var headingPitchRoll = new Cesium.HeadingPitchRoll(heading, pitch, roll)
var modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position, headingPitchRoll, Cesium.Ellipsoid.WGS84, Cesium.Transforms.eastNorthUpToFixedFrame, new Cesium.Matrix4())
//頂點數組
var arr = [0, 0, 0, 0, 100000, 0, 100000, 100000, 0]
var temp = new Trangles({ viewer, modelMatrix, arr })
viewer.scene.primitives.add(temp)
------------------------------------------------------------------------------------------------------
原文鏈接:https://blog.csdn.net/sinat_41537539/article/details/106941041