原文链接及内容

示例介绍:在Cesium场景中渲染体素数据,使用ProceduralSingleTileVoxelProviderProceduralMultiTileVoxelProvider生成单瓦片或多瓦片的体素内容,体素形状包括椭球(ELLIPSOID)、圆柱(CYLINDER)和立方体(BOX)。自定义着色器通过 HSL 颜色和透明度模拟光散射效果,并启用体素检查器(viewerVoxelInspectorMixin)和帧率显示。用户可通过工具栏切换体素类型,鼠标点击支持拾取体素信息。

注:Voxel:可以翻译为体素(或立体像素),是体积像素(Volume Pixel)的简称。在计算机领域,体素(voxel)是三维规则网格上的数值表示,类似于二维的像素。体素常用于医学和科学数据的可视化与分析(例如地理信息系统 GIS)。
一组堆叠的体素,其中单个体素被着色
有些真正的三维显示器运用体素来描述它们的分辨率,举例来说:可以显示512×512×512体素的显示器。关于体素的理解请查看知乎上的一篇文章:https://zhuanlan.zhihu.com/p/348563616

效果如下图所示:右上角组件为投影选择器,分为正交投影和透视投影,默认为透视投影。

示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<style>
@import url(../templates/bucket.css);

.cesium-performanceDisplay-defaultContainer {
top: 5px;
right: 50px;
}

.cesium-viewer-voxelInspectorContainer {
top: 60px;
}
</style>
<div id="cesiumContainer" class="fullSize"></div>
<div id="loadingOverlay"><h1>加载中...</h1></div>
<div id="toolbar"></div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
const viewer = new Cesium.Viewer("cesiumContainer", {
geocoder: false,
homeButton: false,
sceneModePicker: false,
navigationHelpButton: false,
navigationInstructionsInitiallyVisible: false,
animation: false,
timeline: false,
fullscreenButton: false,
skyBox: false,
shouldAnimate: true,
baseLayerPicker: false,
shadows: true,
projectionPicker: true,//启用投影选择器(正交投影和透视投影)
baseLayer: Cesium.ImageryLayer.fromProviderAsync(
Cesium.TileMapServiceImageryProvider.fromUrl(
Cesium.buildModuleUrl("Assets/Textures/NaturalEarthII")
)
),
});
viewer.cesiumWidget.creditContainer.style.display = "none";

// viewerVoxelInspectorMixin:体素检查器,调试体素渲染。
viewer.extend(Cesium.viewerVoxelInspectorMixin);
viewer.scene.debugShowFramesPerSecond = true;//显示帧率,监控性能。

// 定义全局缩放矩阵,将体素数据缩放到 WGS84 椭球的最大半径。
// fromScale方法:创建均匀缩放矩阵,x/y/z 轴均缩放至地球尺度
const globalTransform = Cesium.Matrix4.fromScale(
Cesium.Cartesian3.fromElements(
Cesium.Ellipsoid.WGS84.maximumRadius,//地球椭球的最大半径(约 6378137 米)
Cesium.Ellipsoid.WGS84.maximumRadius,
Cesium.Ellipsoid.WGS84.maximumRadius
)
);

/**
* 定义单瓦片体素提供者(ProceduralSingleTileVoxelProvider),生成 8x8x8 的体素网格
*
*/
function ProceduralSingleTileVoxelProvider(shape) {
this.shape = shape;//体素形状
// minBounds 和 maxBounds:根据形状类型获取边界
this.minBounds = Cesium.VoxelShapeType.getMinBounds(shape).clone();
this.maxBounds = Cesium.VoxelShapeType.getMaxBounds(shape).clone();
this.dimensions = new Cesium.Cartesian3(8, 8, 8);//体素分辨率为 8x8x8
this.names = ["color"];
this.types = [Cesium.MetadataType.VEC4];//颜色为 4 通道向量(RGBA)
this.componentTypes = [Cesium.MetadataComponentType.FLOAT32];//每个通道为 32 位浮点数。
this.globalTransform = globalTransform;//应用全局缩放矩阵
}

const scratchColor = new Cesium.Color();// 暂存颜色值
/**
* 单瓦片(层级)数据请求:生成动态颜色体素,模拟渐变效果。
*/
ProceduralSingleTileVoxelProvider.prototype.requestData = function (options) {
// 仅支持级别 0,超出则拒绝请求
if (options.tileLevel >= 1) {
return Promise.reject(`0 级以上的瓦片不可用`);
}

const dimensions = this.dimensions;
const voxelCount = dimensions.x * dimensions.y * dimensions.z;//总'体素'数(8x8x8=512)
const type = this.types[0];
const channelCount = Cesium.MetadataType.getComponentCount(type);//4(RGBA)
const dataColor = new Float32Array(voxelCount * channelCount);//存储颜色数据的 Float32Array(512*4=2048)

/**
* 颜色计算:
* 1. 使用随机种子(randomSeed)生成基色调(hue)
* 2. 根据体素坐标(lerperX, lerperY, lerperZ)调整 HSL 参数
* 3. 透明度:固定为 0.75。
*/
const randomSeed = dimensions.y * dimensions.x + dimensions.x;
Cesium.Math.setRandomNumberSeed(randomSeed);
const hue = Cesium.Math.nextRandomNumber();

for (let z = 0; z < dimensions.z; z++) {
for (let y = 0; y < dimensions.y; y++) {
const indexZY = z * dimensions.y * dimensions.x + y * dimensions.x;
for (let x = 0; x < dimensions.x; x++) {
const lerperX = x / (dimensions.x - 1);
const lerperY = y / (dimensions.y - 1);
const lerperZ = z / (dimensions.z - 1);

const h = hue + lerperX * 0.5 - lerperY * 0.3 + lerperZ * 0.2;
const s = 1.0 - lerperY * 0.2;
const v = 0.5 + 2.0 * (lerperZ - 0.5) * 0.2;
const color = Cesium.Color.fromHsl(h, s, v, 1.0, scratchColor);

const index = (indexZY + x) * channelCount;
dataColor[index + 0] = color.red;
dataColor[index + 1] = color.green;
dataColor[index + 2] = color.blue;
dataColor[index + 3] = 0.75;
}
}
}

// VoxelContent.fromMetadataArray:将颜色数据封装为体素内容
const content = Cesium.VoxelContent.fromMetadataArray([dataColor]);
return Promise.resolve(content);
};

/**
* 定义多瓦片(层级)体素提供者(ProceduralMultiTileVoxelProvider),
* 生成 4x4x4 的体素网格,支持 2 级瓦片
*/
function ProceduralMultiTileVoxelProvider(shape) {
this.shape = shape;//同单瓦片
this.minBounds = Cesium.VoxelShapeType.getMinBounds(shape).clone();
this.maxBounds = Cesium.VoxelShapeType.getMaxBounds(shape).clone();
this.dimensions = new Cesium.Cartesian3(4, 4, 4);//基础分辨率为 4x4x4
// paddingBefore 和 paddingAfter:每轴增加 1 个体素的填充,平滑瓦片边界
this.paddingBefore = new Cesium.Cartesian3(1, 1, 1);
this.paddingAfter = new Cesium.Cartesian3(1, 1, 1);
this.names = ["color"];
this.types = [Cesium.MetadataType.VEC4];
this.componentTypes = [Cesium.MetadataComponentType.FLOAT32];
this.globalTransform = globalTransform;

this._levelCount = 2;//支持 0 和 1 级瓦片。
this._allVoxelData = new Array(this._levelCount);//预计算每级瓦片的颜色数据

const allVoxelData = this._allVoxelData;
const channelCount = Cesium.MetadataType.getComponentCount(this.types[0]);
const { dimensions } = this;

for (let level = 0; level < this._levelCount; level++) {
const dimAtLevel = Math.pow(2, level);
const voxelCountX = dimensions.x * dimAtLevel;
const voxelCountY = dimensions.y * dimAtLevel;
const voxelCountZ = dimensions.z * dimAtLevel;
const voxelsPerLevel = voxelCountX * voxelCountY * voxelCountZ;
const levelData = (allVoxelData[level] = new Array(
voxelsPerLevel * channelCount
));

for (let z = 0; z < voxelCountX; z++) {
for (let y = 0; y < voxelCountY; y++) {
const indexZY = z * voxelCountY * voxelCountX + y * voxelCountX;
for (let x = 0; x < voxelCountZ; x++) {
const index = (indexZY + x) * channelCount;
levelData[index + 0] = x / (voxelCountX - 1);
levelData[index + 1] = y / (voxelCountY - 1);
levelData[index + 2] = z / (voxelCountZ - 1);
levelData[index + 3] = 0.5;
}
}
}
}
}

// 为多瓦片(多个瓦片层级)体素提供颜色数据:支持多分辨率体素渲染
ProceduralMultiTileVoxelProvider.prototype.requestData = function (options) {
const { tileLevel, tileX, tileY, tileZ } = options;

if (tileLevel >= this._levelCount) {
return Promise.reject(
`${this._levelCount - 1}级以上的瓦片不可用`
);
}

const type = this.types[0];
const channelCount = Cesium.MetadataType.getComponentCount(type);
const { dimensions, paddingBefore, paddingAfter } = this;
// paddedDimensions:考虑填充的瓦片尺寸(6x6x6,含前后各 1 填充)
const paddedDimensions = Cesium.Cartesian3.fromElements(
dimensions.x + paddingBefore.x + paddingAfter.x,
dimensions.y + paddingBefore.y + paddingAfter.y,
dimensions.z + paddingBefore.z + paddingAfter.z
);
const dimAtLevel = Math.pow(2, tileLevel);
// dimensionsGlobal:全局体素分辨率(级别 0 为 4x4x4,级别 1 为 8x8x8)
const dimensionsGlobal = Cesium.Cartesian3.fromElements(
dimensions.x * dimAtLevel,
dimensions.y * dimAtLevel,
dimensions.z * dimAtLevel
);

const minimumGlobalCoord = Cesium.Cartesian3.ZERO;
const maximumGlobalCoord = new Cesium.Cartesian3(
dimensionsGlobal.x - 1,
dimensionsGlobal.y - 1,
dimensionsGlobal.z - 1
);
let coordGlobal = new Cesium.Cartesian3();

const dataGlobal = this._allVoxelData;
// dataTile:存储瓦片颜色数据,含填充体素
const dataTile = new Float32Array(
paddedDimensions.x * paddedDimensions.y * paddedDimensions.z * channelCount
);

// 坐标映射:将瓦片坐标(tileX, tileY, tileZ)转换为全局坐标,提取预计算的颜色数据。
for (let z = 0; z < paddedDimensions.z; z++) {
const indexZ = z * paddedDimensions.y * paddedDimensions.x;
for (let y = 0; y < paddedDimensions.y; y++) {
const indexZY = indexZ + y * paddedDimensions.x;
for (let x = 0; x < paddedDimensions.x; x++) {
const indexTile = indexZY + x;

coordGlobal = Cesium.Cartesian3.clamp(
Cesium.Cartesian3.fromElements(
tileX * dimensions.x + (x - paddingBefore.x),
tileY * dimensions.y + (y - paddingBefore.y),
tileZ * dimensions.z + (z - paddingBefore.z),
coordGlobal
),
minimumGlobalCoord,
maximumGlobalCoord,
coordGlobal
);

const indexGlobal =
coordGlobal.z * dimensionsGlobal.y * dimensionsGlobal.x +
coordGlobal.y * dimensionsGlobal.x +
coordGlobal.x;

for (let c = 0; c < channelCount; c++) {
dataTile[indexTile * channelCount + c] =
dataGlobal[tileLevel][indexGlobal * channelCount + c];
}
}
}
}
const content = Cesium.VoxelContent.fromMetadataArray([dataTile]);
return Promise.resolve(content);
};

/**
* 体素图元(primitive)创建,绑定提供者和着色器,并聚焦其边界球
*/
function createPrimitive(provider, customShader) {
// 清除现有图元,确保单一体素显示
viewer.scene.primitives.removeAll();

// 配置体素提供者(provider)和自定义着色器(customShader)
const voxelPrimitive = viewer.scene.primitives.add(
new Cesium.VoxelPrimitive({
provider: provider,
customShader: customShader,
})
);

// 将图元绑定到体素检查器,调试渲染
viewer.voxelInspector.viewModel.voxelPrimitive = voxelPrimitive;
// 相机聚焦至体素的边界球
viewer.camera.flyToBoundingSphere(voxelPrimitive.boundingSphere, {
duration: 0.0,
});

return voxelPrimitive;
}

/**
* 定义自定义片段着色器,处理体素颜色和透明度
*/
const customShaderColor = new Cesium.CustomShader({
fragmentShaderText: `void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material)
{
//使用体素的 RGB 颜色作为漫反射颜色
material.diffuse = fsInput.metadata.color.rgb;
//基于体素的 alpha 值计算透明度(1-alpha)
float transparency = 1.0 - fsInput.metadata.color.a;

//体素光线穿越距离(travelDistance)放大16倍
float thickness = fsInput.voxel.travelDistance * 16.0;
//为模拟光线散射效果,请采用指数衰减法,
material.alpha = 1.0 - pow(transparency, thickness);
}`,
});

Sandcastle.addToolbarMenu([
{
text: "椭球-程序化瓦片集(单瓦片层级)",
onselect: function () {
const provider = new ProceduralSingleTileVoxelProvider(
Cesium.VoxelShapeType.ELLIPSOID
);
provider.minBounds.z = 0.0;
provider.maxBounds.z = 1000000.0;
const primitive = createPrimitive(provider, customShaderColor);
},
},
{
text: "圆柱-程序化瓦片集(单瓦片层级)",
onselect: function () {
const provider = new ProceduralSingleTileVoxelProvider(
Cesium.VoxelShapeType.CYLINDER
);
const primitive = createPrimitive(provider, customShaderColor);
},
},
{
text: "立方体-程序化瓦片集(单瓦片层级)",
onselect: function () {
const provider = new ProceduralSingleTileVoxelProvider(
Cesium.VoxelShapeType.BOX
);
const primitive = createPrimitive(provider, customShaderColor);
},
},
{
text: "立方体-程序化瓦片集(多瓦片层级)",
onselect: function () {
const provider = new ProceduralMultiTileVoxelProvider(
Cesium.VoxelShapeType.BOX
);
const primitive = createPrimitive(provider, customShaderColor);
},
},
{
text: "椭球-程序化瓦片集(多瓦片层级)",
onselect: function () {
const provider = new ProceduralMultiTileVoxelProvider(
Cesium.VoxelShapeType.ELLIPSOID
);
provider.minBounds.z = 0.0;
provider.maxBounds.z = 1000000.0;
const primitive = createPrimitive(provider, customShaderColor);
},
},
{
text: "圆柱-程序化瓦片集(多瓦片层级)",
onselect: function () {
const provider = new ProceduralMultiTileVoxelProvider(
Cesium.VoxelShapeType.CYLINDER
);
const primitive = createPrimitive(provider, customShaderColor);
},
},
]);

const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
// 处理鼠标左键点击,拾取体素图元并输出到控制台
handler.setInputAction(function (movement) {
const scene = viewer.scene;
const camera = scene.camera;
const mousePosition = movement.position;
// 根据鼠标位置(mousePosition)拾取图元
const pickedPrimitive = scene.pick(mousePosition);
console.log(pickedPrimitive);
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);