Exploring 3D Volumes with VoxelLayer in the ArcGIS Maps SDK for JavaScript 5.2

In this post we load a voxel scene layer with the ArcGIS Maps SDK for JavaScript 5.2, list its variables, switch the displayed variable, cut into the volume with slices and dynamic sections, draw an isosurface, and read voxel values through popups and hit tests.

The problem

Volumetric data (ocean temperature and salinity, geological subsurface models, atmospheric measurements, space-time cubes) does not fit into features. Every cell of a 3D grid has a value, often for several variables at once. The questions people ask are about the inside of the volume: where salinity crosses a threshold, what lies under a construction site, how a layer of clay runs between two boreholes. The VoxelLayer class has been in the SDK since 4.22 and is built for exactly this. The code below targets @arcgis/core 5.2.9 with the <arcgis-scene> component, and it type-checks under strict TypeScript.

Requirements before you start

  • Local scene. The VoxelLayer reference says the layer is visualized in a SceneView with viewingMode set to local. The official samples either set viewing-mode="local" on the component or load a web scene that is already local.
  • GPU features. The layer needs the WebGL extension EXT_color_buffer_float. INT16/UINT16 data also needs EXT_texture_norm16, which the reference says is currently supported only in Chrome, and FLOAT32 data needs OES_texture_float_linear. Esri does not recommend voxel layers on mobile.
  • Opacity. Layer opacity cannot be changed for a VoxelLayer in a SceneView. Transparency is controlled per value through opacity stops instead.

How the volume is addressed

A voxel layer stores one or more volumes, each a regular grid with a volumeType of xyz, xyt (time as the third axis) or xyzt. Slices and sections are positioned in voxel index space: point is a column, row and level index, not a map coordinate. getVolume(null).sizeInVoxels gives you the grid size, and the code below uses half of it, rounded down to a whole index, to find the centre.

VoxelSlice at x = sizeX/2 one side is discarded Volume ("volume" render mode) z (levels) x "surfaces" render mode blue/green: VoxelDynamicSection planes red: VoxelIsosurface (value = threshold)

Slices remove part of the volume in either render mode; sections and isosurfaces only draw in "surfaces" mode.

Step 1: load a voxel layer

The service URL and the basemap below come from the official Intro to VoxelLayer sample (layers-voxel). The data is the Ecological Marine Units model for the Caribbean. It lies below sea level, so the ground's navigationConstraint is turned off to let the camera go underwater.

All services in this post are public and load without an API key. The .ts script tags assume a bundler such as Vite serves the page.

<arcgis-scene viewing-mode="local"></arcgis-scene>
<script type="module" src="./p3-load.ts"></script>
import "@arcgis/map-components/components/arcgis-scene";
import Map from "@arcgis/core/Map.js";
import VoxelLayer from "@arcgis/core/layers/VoxelLayer.js";
import VectorTileLayer from "@arcgis/core/layers/VectorTileLayer.js";

const sceneEl = document.querySelector("arcgis-scene")!;

// Ecological Marine Units, Caribbean (from the "Intro to VoxelLayer" sample).
const voxels = new VoxelLayer({
  url: "https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/EMU_Caribbean_Voxel/SceneServer",
});

sceneEl.map = new Map({
  layers: [voxels],
  basemap: {
    baseLayers: [
      new VectorTileLayer({
        url: "https://basemaps.arcgis.com/arcgis/rest/services/OpenStreetMap_GCS_v2/VectorTileServer",
      }),
    ],
  },
  // The data is below sea level: allow the camera underground.
  ground: { navigationConstraint: { type: "none" } },
});

await sceneEl.viewOnReady();
await voxels.load();

// What is inside the volume?
const volume = voxels.getVolume(null);
console.log("volume type:", volume?.volumeType, "size in voxels:", volume?.sizeInVoxels);
for (const variable of voxels.variables) {
  const style = voxels.getVariableStyle(variable.id);
  console.log(variable.id, variable.name, variable.unit, style?.label);
}

variables is a collection of VoxelVariable objects, each with an id, name, unit, description and the volumeId of the volume it belongs to. The display label lives on the matching VoxelVariableStyle. Look that style up with getVariableStyle(variable.id) rather than assuming the two collections line up by index.

Step 2: variables, render mode, slices, sections, isosurfaces

For the exploration code I use the web scene 3a922ed0c7a8489ea4fbe8747ac560ba. It is used by the official VoxelLayer slices, dynamic sections and isosurface samples and already contains a local scene with a voxel layer.

<arcgis-scene item-id="3a922ed0c7a8489ea4fbe8747ac560ba">
  <select id="variable" slot="top-right"></select>
</arcgis-scene>
<script type="module" src="./p3-explore.ts"></script>
import "@arcgis/map-components/components/arcgis-scene";
import VoxelLayer from "@arcgis/core/layers/VoxelLayer.js";
import VoxelSlice from "@arcgis/core/layers/voxel/VoxelSlice.js";
import VoxelDynamicSection from "@arcgis/core/layers/voxel/VoxelDynamicSection.js";
import VoxelIsosurface from "@arcgis/core/layers/voxel/VoxelIsosurface.js";

const sceneEl = document.querySelector("arcgis-scene")!;
const variableSelect = document.querySelector<HTMLSelectElement>("#variable")!;

await sceneEl.viewOnReady();
const found = sceneEl.map?.layers.find((layer) => layer.type === "voxel");
if (!(found instanceof VoxelLayer)) throw new Error("No VoxelLayer in this web scene");
const voxels: VoxelLayer = found;
await sceneEl.whenLayerView(voxels);

// 1. Variables: fill a <select> and switch the displayed variable.
for (const variable of voxels.variables) {
  const option = document.createElement("option");
  option.value = String(variable.id);
  option.text = voxels.getVariableStyle(variable.id)?.label || variable.name;
  option.selected = variable.id === voxels.currentVariableId;
  variableSelect.add(option);
}
variableSelect.addEventListener("change", () => {
  voxels.currentVariableId = Number(variableSelect.value);
});

// 2. Render mode: the whole volume, or only sections and isosurfaces.
export function setRenderMode(mode: "volume" | "surfaces"): void {
  voxels.renderMode = mode;
}

// Slices, sections and the grid size all work in voxel index space.
const volume = voxels.getVolume(null)!;
const [sizeX, sizeY, sizeZ] = volume.sizeInVoxels;
const mid = (n: number): number => Math.floor(n / 2);
const volumeStyle = voxels.getVolumeStyle(null)!;

// 3. Slice: a vertical West-East cut at column x; the voxels on one side are discarded.
export function sliceAtX(x: number): void {
  volumeStyle.slices = [
    new VoxelSlice({ label: "Vertical slice", orientation: 270, tilt: 90, point: [x, mid(sizeY), mid(sizeZ)] }),
  ];
}

// 4. Dynamic section: a vertical plane through the centre, drawn only in "surfaces" mode.
export function addSection(orientation: number): VoxelDynamicSection {
  const section = new VoxelDynamicSection({
    label: `Section ${orientation}°`,
    orientation,
    tilt: 90,
    point: [mid(sizeX), mid(sizeY), mid(sizeZ)],
  });
  volumeStyle.dynamicSections.add(section);
  return section;
}

// 5. Isosurface: the surface where the current (continuous) variable equals `value`.
export function addIsosurface(value: number): void {
  const variable = voxels.getVariable(voxels.currentVariableId);
  const style = voxels.getVariableStyle(voxels.currentVariableId);
  if (!variable || !style || variable.renderingFormat.continuity !== "continuous") return;
  if (style.isosurfaces.length >= 4) return; // the layer draws at most four
  style.isosurfaces.add(new VoxelIsosurface({ value, color: [102, 136, 248], colorLocked: true }));
}

export function midRange(): number {
  const range = voxels.getVariableStyle(voxels.currentVariableId)?.transferFunction.stretchRange;
  return range ? (range[0] + range[1]) / 2 : 0;
}

setRenderMode("surfaces");
addSection(0);
addSection(90);
addIsosurface(midRange());

Changing the displayed variable

A voxel layer renders one variable at a time, chosen by currentVariableId. The select fills from variables and writes the chosen id back. <select>.value is a string and currentVariableId is typed as a number, so the Number() conversion is required. The id must belong to an existing variable. Continuous variables are coloured through the variable style's transferFunction (stretchRange, colorStops, opacityStops, rangeFilter). Discrete variables use uniqueValues instead.

Volume vs. surfaces

renderMode is either "volume", which draws every voxel, or "surfaces", which draws only dynamic sections and isosurfaces. A volume rendering gives a quick overall picture, but the outer voxels hide everything inside. Surfaces mode is what you use to look inside.

Slices

A VoxelSlice is a plane that discards the voxels on one side of it. It defines an area of interest and works in both render modes. Slices belong to the VoxelVolumeStyle (from getVolumeStyle(null)), and they are saved with the web scene. A vertical West-East slice uses orientation: 270 and tilt: 90, the values the official slices sample uses. Changing point, orientation or tilt on an existing slice redraws in real time, so you can bind them directly to a slider. The <arcgis-slice> component also works on voxel layers, but its plane is temporary and is not stored in the web scene.

Dynamic sections

A VoxelDynamicSection is a plane that shows the variable's values on the cut surface, like a geological cross-section. Sections also live on the volume style, in dynamicSections, and they only draw when renderMode is "surfaces". The code adds two perpendicular vertical sections through the centre of the volume. Each one has its own enabled flag. enableDynamicSections on the layer switches all of them off together, and enableSlices and enableIsosurfaces do the same for slices and isosurfaces.

Isosurfaces

A VoxelIsosurface is the surface where a continuous variable equals a given value, such as the boundary where temperature crosses 10 degrees. Isosurfaces belong to the variable style, not the volume style, so each variable keeps its own. The rules from the reference and the isosurface sample: they only draw in "surfaces" mode, at most four can be drawn, and they only apply to continuous variables. That is why the code checks renderingFormat.continuity and the current count before adding one. With colorLocked: true the isosurface uses its own color. Otherwise it takes the colour from the colour stops at that value. The midpoint of stretchRange makes a reasonable starting value, and the value may lie outside the stretch range.

Step 3: popups and reading values

Voxel layers have no feature query methods such as queryFeatures. What you get instead is per-voxel identification: popups, and hitTest(), which returns a graphic result for the voxel under the cursor. Besides one field per variable, fields contains fixed fields prefixed with Voxel.: Voxel.CurrentVariable, Voxel.Position, Voxel.Depth (xyz and xyzt volumes only), plus Voxel.LocalTime and Voxel.SourceTime for volumes with time. The scene 1d32064a92074560892999c71257f240 and the fields lithok and strat come from the official Configuring the popup of a VoxelLayer sample (layers-voxel-popup-config), which uses the GeoTOP subsurface model of the Netherlands by TNO.

<arcgis-scene item-id="1d32064a92074560892999c71257f240" popup-component-enabled></arcgis-scene>
<script type="module" src="./p3-popup.ts"></script>
import "@arcgis/map-components/components/arcgis-scene";
import VoxelLayer from "@arcgis/core/layers/VoxelLayer.js";
import PopupTemplate from "@arcgis/core/PopupTemplate.js";

const sceneEl = document.querySelector("arcgis-scene")!;
await sceneEl.viewOnReady();

const found = sceneEl.map?.layers.find((layer) => layer.type === "voxel");
if (!(found instanceof VoxelLayer)) throw new Error("No VoxelLayer in this web scene");
const voxels: VoxelLayer = found;
await voxels.load();

// Fixed fields (Voxel.*) plus one field per variable.
console.log(voxels.fields.map((field) => field.name));

voxels.popupTemplate = new PopupTemplate({
  title: "GeoTOP voxel",
  expressionInfos: [
    { name: "depth", title: "Depth", expression: 'Text($voxel["Voxel.Depth"], "#.## m")' },
  ],
  content: [
    { type: "text", text: "Showing: {Voxel.CurrentVariable} at {Voxel.Position}" },
    {
      type: "fields",
      fieldInfos: [
        { fieldName: "lithok", label: "Most likely lithological class" },
        { fieldName: "strat", label: "Geological unit" },
        { fieldName: "expression/depth", label: "Depth" },
      ],
    },
  ],
});
voxels.popupEnabled = true;

// Reading a voxel value in code instead of in a popup.
sceneEl.addEventListener("arcgisViewClick", async (event) => {
  const { results } = await sceneEl.hitTest(event.detail, { include: [voxels] });
  const hit = results.find((result) => result.type === "graphic");
  if (hit?.type === "graphic") console.log(hit.graphic.attributes);
});

The Arcade expression reads a fixed field through $voxel["Voxel.Depth"], with the bracket syntax because the name contains a dot, and formats it in metres. Plain fields go into the fieldInfos of a fields element, and the expression is referenced as expression/depth. popupEnabled defaults to false on a VoxelLayer, so it has to be set. Logging fields first is the quickest way to find out what you can put in the template for an unfamiliar layer.

The click handler shows the programmatic route: hitTest() restricted to the voxel layer returns a "graphic" result. The graphic has no geometry, but its attributes hold the values of the clicked voxel. Use this to drive your own panel or chart instead of the popup.

Summary

  • A VoxelLayer needs a local scene and a GPU with float colour buffer support. Desktop Chrome is the safe target.
  • Switch variables with currentVariableId, and look up labels and styles with getVariableStyle(id).
  • renderMode: "volume" draws everything. "surfaces" draws only dynamic sections and isosurfaces.
  • Slices and dynamic sections live on the volume style and use voxel index coordinates. Isosurfaces live on the variable style, with a maximum of four, continuous variables only.
  • Popups use the Voxel.* fixed fields plus the variable fields. hitTest() gives the same values in code.

Comments

Popular posts from this blog

My Cloud Notes

My CSharp Notes