废话不多说先上效果图
// 引入3dtileset
var tileSet = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
url: './shanghai/tileset.json'
}))
tileSet.readyPromise.then(function (tileset) {
// 根据tileset的边界球体中心点的笛卡尔坐标得到经纬度坐标
const transform = tileset._root.transform// 从3dtile得到位置矩阵
const m = new Cesium.Matrix4()
Cesium.Matrix4.setTranslation(Cesium.Matrix4.IDENTITY, new Cesium.Cartesian3(430, -230, 0), m)// 构造平移矩阵
tileset._root.transform = Cesium.Matrix4.multiply(transform, m, transform)// 计算平移之后的位置矩阵,然后更新3dtiles的位置
// 样式代码
tileset.style = new Cesium.Cesium3DTileStyle({
color: {
conditions: ['true', 'rgba(0, 0, 0,0.6)']
}
})
tileSet.tileVisible.addEventListener(function (tile) {
const content = tile.content
const featuresLength = content.featuresLength
let feature
for (var i = 0; i < featuresLength; i += 2) {
feature = content.getFeature(i)
const _model = feature.content._model
_model._shouldRegenerateShaders = true
// getOwnPropertyNames:返回指定对象的所有自身属性的属性名组成的数组
// forEach:对数组里的所有元素都执行一遍
// Object.keys:返回
Object.getOwnPropertyNames(_model._sourcePrograms).forEach(function (j) {
const _modelSourceP = _model._sourcePrograms[0]
_model._rendererResources.sourceShaders[_modelSourceP.fragmentShader] =
`varying vec3 v_positionEC;
void main(void){
vec4 position = czm_inverseModelView * vec4(v_positionEC,1); // 位置
float glowRange = 10.0; // 光环的移动范围(高度)
gl_FragColor = vec4(0.0, 0.1, 0.5, 0.8); // 颜色
// 小于20米的低楼都不再变暗
if(position.y > 20.0) {
gl_FragColor *= vec4(vec3(position.y / 20.0), 0.8); // 渐变
}
// 动态光环
float time = fract(czm_frameNumber / 360.0);
time = abs(time - 0.5) * 3.0;
float diff = step(0.005, abs( clamp(position.y / glowRange, 0.0, 1.0) - time));
gl_FragColor.rgb += gl_FragColor.rgb * (1.0 - diff);
}
`
})
_model._shouldRegenerateShaders = true
}
})
}).otherwise(function (error) {
console.log(error)
})
// 实现渐变效果
viewer.scene.primitives.add(tileSet)