Compare commits

...

31 Commits

Author SHA1 Message Date
Alexander Rose
26340bf215 PR feedback
- use arraySet since deps count is small
- cache default params
2026-05-30 21:22:45 -07:00
Alexander Rose
60a7cab28f dynamic state dependencies
- collect from ValueRef/DataRef params
- optional .getDependencies()
- cycle detection
- suspend/resume state tree evaluation
2026-05-23 09:03:54 -07:00
Alexander Rose
27f251e8e4 Merge pull request #1832 from molstar/ssao-multi-fix
Fix SSAO half/quarter resolution textures for multi-scale
2026-05-17 20:15:09 -07:00
Alexander Rose
8d2a44983e remove superfluous enableAnimation param 2026-05-16 22:29:55 -07:00
Alexander Rose
63a585d88a Merge pull request #1830 from josemduarte/ms-fix-omitwater
Fix ModelServer bugs for omitWater param in surroundingLigands endpoint
2026-05-16 22:24:58 -07:00
Alexander Rose
a4b5a16fcd Merge branch 'master' into ms-fix-omitwater 2026-05-16 22:22:42 -07:00
Alexander Rose
86bf859a63 Fix SSAO half/quarter resolution textures for multi-scale 2026-05-16 22:15:12 -07:00
Alexander Rose
1b8117d3f1 Fix Volume and Isosurface getBoundingSphere ignoring instances 2026-05-10 17:18:18 -07:00
Alexander Rose
400e2bbc45 Merge pull request #1822 from corredD/codex/dot-morton-spheres 2026-05-10 08:42:22 -07:00
Jose Duarte
e2e26c7e9c Updating changelog 2026-05-09 22:28:38 -07:00
Jose Duarte
5ca9020cbf mol-model: fix water leak in surroundingLigands query
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 22:21:49 -07:00
Jose Duarte
ea4c411d5c model-server: fix omit_water boolean parsing for REST GET requests
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 22:21:49 -07:00
Alexander Rose
ba7e3fe827 Merge branch 'master' of https://github.com/molstar/molstar into pr/corredD/1822 2026-05-09 16:03:21 -07:00
Alexander Rose
8f20571a17 Merge pull request #1827 from molstar/camera-changed-event
Camera helpers
2026-05-09 16:02:30 -07:00
Alexander Rose
c25a4247e6 Merge branch 'master' of https://github.com/molstar/molstar into camera-changed-event 2026-05-09 15:57:47 -07:00
Alexander Rose
1071d3d8ba Merge pull request #1828 from molstar/instance-granularity-improvements
Instance granularity improvements
2026-05-09 15:56:36 -07:00
Alexander Rose
e8dc046570 Merge branch 'master' of https://github.com/molstar/molstar into instance-granularity-improvements 2026-05-09 15:54:00 -07:00
Alexander Rose
27f9c2aa67 Merge pull request #1829 from molstar/mesoscale-preset
Mesoscale preset
2026-05-09 15:53:29 -07:00
Alexander Rose
a4962231c8 revert 2026-05-09 15:51:05 -07:00
Alexander Rose
8833f29ce5 Merge branch 'master' of https://github.com/molstar/molstar into mesoscale-preset 2026-05-09 15:44:01 -07:00
Alexander Rose
40b6038380 type tweak 2026-05-09 15:43:04 -07:00
Armando Pellegrini
59e16e0187 Fix State.dispose() not invoking transformer dispose for live cells (#1826)
`Transformer.Definition.dispose` is documented as "automatically called
on deleting an object," but `State.dispose()` only disposed its own event
subjects and action manager — it never iterated still-live cells to call
their per-transformer dispose. Cells holding GL buffers, mesh data, etc.
only had their dispose fired on explicit deletion (e.g. `clear()`), so
any consumer that called `plugin.dispose()` without first awaiting
`plugin.clear()` retained the callback chain, the GL buffers it points
at, and any closures captured by it.

In a long-running single-page app where the user navigates between
routes that mount/unmount a Mol* viewer, this leaked roughly 25–50 MB
of process RSS per cycle even with `plugin.dispose()` correctly called.
A 20-cycle E2E mount/unmount harness on a 1AKE structure measured a
+541 MB RSS / +266 MB JS-heap delta in the unconditional-`dispose()`
case; calling `await plugin.clear()` before `plugin.dispose()` halved
the residual leak, confirming the per-cell dispose path was missing on
the unconditional `dispose()` route.

This change walks the cell tree once (post-order via the existing
`StateTree.doPostOrder` helper) and invokes the per-transformer dispose
for every still-live cell, swallowing+warning on errors so a single
faulty transformer can't prevent siblings from cleaning up. The
existing per-cell `dispose` helper is reused for consistency with
`updateNode`/`findDeletes` semantics.

Tests cover: chained transformers, sibling subtrees, throwing-dispose
isolation, and transformers without a dispose definition.

Also adds `useDefineForClassFields: false` to the jest esbuild
transform so tests can construct `State` (the `TransientTree` parameter
property + class field pattern relies on legacy class-field semantics,
which `tsc` honors via `target: es2018` but esbuild's default `esnext`
target does not).

Fixes #1825

Co-authored-by: Armando Pellegrini <tech.tools@boltz.bio>
2026-05-09 22:17:38 +02:00
Alexander Rose
ca5a50bd53 changelog 2026-05-09 12:36:38 -07:00
Alexander Rose
bccf54fabe avoid extra allocations 2026-05-09 12:36:32 -07:00
Alexander Rose
57a790544c Add mesoscale representation preset 2026-05-09 12:31:26 -07:00
Alexander Rose
df0669598c Add presets option to ObjectList param definition 2026-05-09 12:31:11 -07:00
Alexander Rose
fb912036af Merge branch 'master' of https://github.com/molstar/molstar into pr/corredD/1822 2026-05-09 08:25:26 -07:00
Alexander Rose
9efb5cd126 Add Camera.changed event and rotation/translation setter/getter 2026-05-09 08:24:26 -07:00
Alexander Rose
08a56ad6ab Instance granularity improvements
- Add `instanceGranularity: 'auto'` as a memory guard
- Honor `instanceGranularity` in `Visual.getLoci`
2026-05-09 08:10:58 -07:00
Alexander Rose
d7ad5a6e9f Fix empty transforms default in ShapeFromPly 2026-05-04 23:14:02 -07:00
Ludovic Autin
19fec3bbc1 Order DOT spheres by Morton index
Add DOT sphere impostors in Morton order so sphere LOD stride sampling remains spatially distributed.
2026-05-02 10:48:31 -07:00
42 changed files with 1341 additions and 181 deletions

View File

@@ -4,6 +4,17 @@ All notable changes to this project will be documented in this file, following t
Note that since we don't clearly distinguish between a public and private interfaces there will be changes in non-major versions that are potentially breaking. If we make breaking changes to less used interfaces we will highlight it in here.
## [Unreleased]
- Fix empty transforms default in `ShapeFromPly`
- Use morton order for spheres in dot visual with lod-levels
- Add `Camera.changed` event and rotation/translation setter/getter
- Add `instanceGranularity: 'auto'` as a memory guard
- Honor `instanceGranularity` in `Visual.getLoci`
- Add mesoscale representation preset
- Add presets option to `ObjectList` param definition
- Fix memory leak in `State.dispose()` not invoking transformer `dispose` callbacks for live cells
- Fix bugs in ModelServer surroundingLigands endpoint, resulting in omitWater not honored
- Fix `Volume` and `Isosurface` getBoundingSphere ignoring instances
- Fix SSAO half/quarter resolution textures for multi-scale
## [v5.9.0] - 2026-05-03
- Fix edge case when `PluginSpec.animations` is empty

View File

@@ -74,7 +74,7 @@
"js"
],
"transform": {
"\\.ts$": "esbuild-jest-transform"
"\\.ts$": ["esbuild-jest-transform", { "tsconfigRaw": "{\"compilerOptions\":{\"useDefineForClassFields\":false}}" }]
},
"moduleDirectories": [
"node_modules",

View File

@@ -22,7 +22,6 @@ import { Hcl } from '../../../mol-util/color/spaces/hcl';
import { StateObjectCell, StateObjectRef, StateSelection } from '../../../mol-state';
import { ShapeRepresentation3D, StructureRepresentation3D } from '../../../mol-plugin-state/transforms/representation';
import { SpacefillRepresentationProvider } from '../../../mol-repr/structure/representation/spacefill';
import { assertUnreachable } from '../../../mol-util/type-helpers';
import { MesoscaleExplorerState } from '../app';
import { saturate } from '../../../mol-math/interpolate';
import { Material } from '../../../mol-util/material';
@@ -322,38 +321,7 @@ export function getMesoscaleGroupParams(graphicsMode: GraphicsMode): MesoscaleGr
export type LodLevels = typeof SpacefillRepresentationProvider.defaultValues['lodLevels']
export function getLodLevels(graphicsMode: Exclude<GraphicsMode, 'custom'>): LodLevels {
switch (graphicsMode) {
case 'performance':
return [
{ minDistance: 1, maxDistance: 300, overlap: 0, stride: 1, scaleBias: 1 },
{ minDistance: 300, maxDistance: 2000, overlap: 0, stride: 40, scaleBias: 3 },
{ minDistance: 2000, maxDistance: 6000, overlap: 0, stride: 150, scaleBias: 3 },
{ minDistance: 6000, maxDistance: 10000000, overlap: 0, stride: 300, scaleBias: 2.5 },
];
case 'balanced':
return [
{ minDistance: 1, maxDistance: 500, overlap: 0, stride: 1, scaleBias: 1 },
{ minDistance: 500, maxDistance: 2000, overlap: 0, stride: 15, scaleBias: 3 },
{ minDistance: 2000, maxDistance: 6000, overlap: 0, stride: 70, scaleBias: 2.7 },
{ minDistance: 6000, maxDistance: 10000000, overlap: 0, stride: 200, scaleBias: 2.5 },
];
case 'quality':
return [
{ minDistance: 1, maxDistance: 1000, overlap: 0, stride: 1, scaleBias: 1 },
{ minDistance: 1000, maxDistance: 4000, overlap: 0, stride: 10, scaleBias: 3 },
{ minDistance: 4000, maxDistance: 10000, overlap: 0, stride: 50, scaleBias: 2.7 },
{ minDistance: 10000, maxDistance: 10000000, overlap: 0, stride: 200, scaleBias: 2.3 },
];
case 'ultra':
return [
{ minDistance: 1, maxDistance: 5000, overlap: 0, stride: 1, scaleBias: 1 },
{ minDistance: 5000, maxDistance: 10000, overlap: 0, stride: 10, scaleBias: 3 },
{ minDistance: 10000, maxDistance: 30000, overlap: 0, stride: 50, scaleBias: 2.5 },
{ minDistance: 30000, maxDistance: 10000000, overlap: 0, stride: 200, scaleBias: 2 },
];
default:
assertUnreachable(graphicsMode);
}
return Spheres.LodLevelsPresets[graphicsMode];
}
export type GraphicsMode = 'ultra' | 'quality' | 'balanced' | 'performance' | 'custom';

View File

@@ -7,7 +7,7 @@
import { Viewport, cameraProject, cameraUnproject } from './camera/util';
import { CameraTransitionManager } from './camera/transition';
import { BehaviorSubject } from 'rxjs';
import { BehaviorSubject, Subject } from 'rxjs';
import { Scene } from '../mol-gl/scene';
import { assertUnreachable } from '../mol-util/type-helpers';
import { Ray3D } from '../mol-math/geometry/primitives/ray3d';
@@ -15,6 +15,7 @@ import { Mat4 } from '../mol-math/linear-algebra/3d/mat4';
import { Vec4 } from '../mol-math/linear-algebra/3d/vec4';
import { Vec3 } from '../mol-math/linear-algebra/3d/vec3';
import { EPSILON } from '../mol-math/linear-algebra/3d/common';
import { Euler } from '../mol-math/linear-algebra/3d/euler';
export type { ICamera };
@@ -42,6 +43,12 @@ interface ICamera {
}
const tmpClip = Vec4();
const tmpForward = Vec3();
const tmpRight = Vec3();
const tmpUp = Vec3();
const tmpBack = Vec3();
const tmpDelta = Vec3();
const tmpRotMat = Mat4.identity();
export class Camera implements ICamera {
readonly view: Mat4 = Mat4.identity();
@@ -70,6 +77,8 @@ export class Camera implements ICamera {
readonly transition: CameraTransitionManager = new CameraTransitionManager(this);
readonly stateChanged = new BehaviorSubject<Partial<Camera.Snapshot>>(this.state);
/** Fires whenever update() produces a changed view/projection (covers all mutations, including direct ones from controls). */
readonly changed = new Subject<void>();
get position() { return this.state.position; }
set position(v: Vec3) { Vec3.copy(this.state.position, v); }
@@ -123,6 +132,7 @@ export class Camera implements ICamera {
Mat4.copy(this.prevView, this.view);
Mat4.copy(this.prevProjection, this.projection);
this.changed.next();
}
return changed;
@@ -237,6 +247,57 @@ export class Camera implements ICamera {
return out;
}
/** How much the camera is rotated around its target. Uses 'ZYX' order. */
getRotation(out: Euler) {
const { position, target, up } = this.state;
Vec3.normalize(tmpForward, Vec3.sub(tmpForward, target, position));
Vec3.normalize(tmpRight, Vec3.cross(tmpRight, tmpForward, up));
Vec3.cross(tmpUp, tmpRight, tmpForward);
Mat4.setIdentity(tmpRotMat);
tmpRotMat[0] = tmpRight[0]; tmpRotMat[1] = tmpRight[1]; tmpRotMat[2] = tmpRight[2];
tmpRotMat[4] = tmpUp[0]; tmpRotMat[5] = tmpUp[1]; tmpRotMat[6] = tmpUp[2];
tmpRotMat[8] = -tmpForward[0]; tmpRotMat[9] = -tmpForward[1]; tmpRotMat[10] = -tmpForward[2];
return Euler.fromMat4(out, tmpRotMat, 'ZYX');
}
/** Set the camera rotation around its target. Expects 'ZYX' order. */
setRotation(rotation: Euler, durationMs?: number) {
const snapshot = this.state as Camera.Snapshot;
const distance = Vec3.distance(snapshot.position, snapshot.target);
Mat4.fromEuler(tmpRotMat, rotation, 'ZYX');
// back = R * (0,0,1) → column 2 of R
Vec3.set(tmpBack, tmpRotMat[8], tmpRotMat[9], tmpRotMat[10]);
// up = R * (0,1,0) → column 1 of R
Vec3.set(tmpUp, tmpRotMat[4], tmpRotMat[5], tmpRotMat[6]);
const state = Camera.copySnapshot(Camera.createDefaultSnapshot(), snapshot);
Vec3.scaleAndAdd(state.position, snapshot.target, tmpBack, distance);
Vec3.copy(state.up, tmpUp);
this.setState(state, durationMs);
}
/** Translation of the camera target relative to world origin (0, 0, 0) */
getTranslation(out: Vec3) {
return Vec3.copy(out, this.state.target);
}
/** Set the camera target to the given translation, moving position by the same delta so orientation/distance are preserved */
setTranslation(translation: Vec3, durationMs?: number) {
const snapshot = this.state as Camera.Snapshot;
Vec3.sub(tmpDelta, translation, snapshot.target);
const state = Camera.copySnapshot(Camera.createDefaultSnapshot(), snapshot);
Vec3.add(state.position, snapshot.position, tmpDelta);
Vec3.copy(state.target, translation);
this.setState(state, durationMs);
}
constructor(state?: Partial<Camera.Snapshot>, viewport = Viewport.create(0, 0, 128, 128)) {
this.viewport = viewport;
Camera.copySnapshot(this.state, state);

View File

@@ -98,7 +98,6 @@ export const Canvas3DParams = {
transparentBackground: PD.Boolean(false),
checkeredTransparentBackground: PD.Boolean(false),
dpoitIterations: PD.Numeric(2, { min: 1, max: 10, step: 1 }),
enableAnimation: PD.Boolean(true, { description: 'Enable GPU time-based animations (wiggle/tumble).' }),
pickPadding: PD.Numeric(3, { min: 0, max: 10, step: 1 }, { description: 'Extra pixels to around target to check in case target is empty.' }),
userInteractionReleaseMs: PD.Numeric(250, { min: 0, max: 1000, step: 1 }, { description: 'The time before the user is not considered interacting anymore.' }),
@@ -480,7 +479,6 @@ namespace Canvas3D {
const hiZ = new HiZPass(webgl, passes.draw, canvas, p.hiZ);
const renderer = Renderer.create(webgl, p.renderer);
renderer.setProps({ enableAnimation: p.enableAnimation });
renderer.setOcclusionTest(hiZ.isOccluded);
const shaderManager = new ShaderManager(webgl, scene);
@@ -677,7 +675,7 @@ namespace Canvas3D {
const xrChanged = xrManager.update(xrFrame);
if (!xrChanged && xrFrame) return false;
const activeAnimation = p.enableAnimation && scene.hasAnimation;
const activeAnimation = renderer.props.enableAnimation && scene.hasAnimation;
const shouldRender = force || cameraChanged || resized || forceNextRender || xrChanged || activeAnimation;
forceNextRender = false;
@@ -1071,7 +1069,6 @@ namespace Canvas3D {
transparentBackground: p.transparentBackground,
checkeredTransparentBackground: p.checkeredTransparentBackground,
dpoitIterations: p.dpoitIterations,
enableAnimation: p.enableAnimation,
pickPadding: p.pickPadding,
userInteractionReleaseMs: p.userInteractionReleaseMs,
viewport: p.viewport,
@@ -1317,10 +1314,6 @@ namespace Canvas3D {
if (props.transparentBackground !== undefined) p.transparentBackground = props.transparentBackground;
if (props.checkeredTransparentBackground !== undefined) p.checkeredTransparentBackground = props.checkeredTransparentBackground;
if (props.dpoitIterations !== undefined) p.dpoitIterations = props.dpoitIterations;
if (props.enableAnimation !== undefined) {
p.enableAnimation = props.enableAnimation;
renderer.setProps({ enableAnimation: p.enableAnimation });
}
if (props.pickPadding !== undefined) {
p.pickPadding = props.pickPadding;
pickHelper.setPickPadding(p.pickPadding);

View File

@@ -1,5 +1,5 @@
/**
* Copyright (c) 2019-2025 mol* contributors, licensed under MIT, See LICENSE file for more info.
* Copyright (c) 2019-2026 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @author Áron Samuel Kovács <aron.kovacs@mail.muni.cz>
@@ -484,27 +484,45 @@ export class SsaoPass {
if (isTimingMode) this.webgl.timer.markEnd('SSAO.downsample');
}
if (isTimingMode) this.webgl.timer.mark('SSAO.half');
if (multiScale) {
// half-resolution viewport (matches dimensions of depthHalfTarget*)
const hsx = Math.floor(sx * 0.5);
const hsy = Math.floor(sy * 0.5);
const hsw = Math.ceil(sw * 0.5);
const hsh = Math.ceil(sh * 0.5);
state.viewport(hsx, hsy, hsw, hsh);
state.scissor(hsx, hsy, hsw, hsh);
if (isTimingMode) this.webgl.timer.mark('SSAO.half');
this.depthHalfTargetOpaque.bind();
this.depthHalfRenderableOpaque.render();
}
if (multiScale && includeTransparent) {
this.depthHalfTargetTransparent.bind();
this.depthHalfRenderableTransparent.render();
}
if (isTimingMode) this.webgl.timer.markEnd('SSAO.half');
if (includeTransparent) {
this.depthHalfTargetTransparent.bind();
this.depthHalfRenderableTransparent.render();
}
if (isTimingMode) this.webgl.timer.markEnd('SSAO.half');
if (isTimingMode) this.webgl.timer.mark('SSAO.quarter');
if (multiScale) {
// quarter-resolution viewport (matches dimensions of depthQuarterTarget*)
const qsx = Math.floor(sx * 0.25);
const qsy = Math.floor(sy * 0.25);
const qsw = Math.ceil(sw * 0.25);
const qsh = Math.ceil(sh * 0.25);
state.viewport(qsx, qsy, qsw, qsh);
state.scissor(qsx, qsy, qsw, qsh);
if (isTimingMode) this.webgl.timer.mark('SSAO.quarter');
this.depthQuarterTargetOpaque.bind();
this.depthQuarterRenderableOpaque.render();
if (includeTransparent) {
this.depthQuarterTargetTransparent.bind();
this.depthQuarterRenderableTransparent.render();
}
if (isTimingMode) this.webgl.timer.markEnd('SSAO.quarter');
// restore full-scale viewport for SSAO + blur passes
state.viewport(sx, sy, sw, sh);
state.scissor(sx, sy, sw, sh);
}
if (multiScale && includeTransparent) {
this.depthQuarterTargetTransparent.bind();
this.depthQuarterRenderableTransparent.render();
}
if (isTimingMode) this.webgl.timer.markEnd('SSAO.quarter');
if (isTimingMode) this.webgl.timer.mark('SSAO.opaque');
this.ssaoDepthTexture.attachFramebuffer(this.framebuffer, 'color0');

View File

@@ -72,6 +72,25 @@ export function getColorSmoothingProps(smoothColors: PD.Values<ColorSmoothingPar
//
export type InstanceGranularityValue = true | false | 'auto'
export const InstanceGranularityOptions: [InstanceGranularityValue, string][] = [[true, 'On'], [false, 'Off'], ['auto', 'Auto']];
/**
* Threshold (in `groupCount * instanceCount`, e.g. number of marker-texture
* slots) above which `instanceGranularity: 'auto'` resolves to `true`.
*/
export const AutoInstanceGranularityThreshold = 50_000_000;
/**
* Resolves the `instanceGranularity` param value to a boolean.
*/
export function resolveInstanceGranularity(value: InstanceGranularityValue, groupCount: number, instanceCount: number): boolean {
if (value === 'auto') return groupCount * instanceCount > AutoInstanceGranularityThreshold;
return value;
}
//
export namespace BaseGeometry {
export const MaterialCategory: PD.Info = { category: 'Material' };
export const ShadingCategory: PD.Info = { category: 'Shading' };
@@ -88,7 +107,7 @@ export namespace BaseGeometry {
clip: PD.Group(Clip.Params),
emissive: PD.Numeric(0, { min: 0, max: 1, step: 0.01 }),
density: PD.Numeric(0.2, { min: 0, max: 1, step: 0.01 }, { description: 'Density value to estimate object thickness.' }),
instanceGranularity: PD.Boolean(false, { description: 'Use instance granularity for marker, transparency, clipping, overpaint, substance data to save memory.' }),
instanceGranularity: PD.Select<InstanceGranularityValue>('auto', InstanceGranularityOptions, { description: 'Use instance granularity for marker, transparency, clipping, overpaint, substance data to save memory. When set to `auto`, granularity is enabled if `groupCount * instanceCount` exceeds `AutoInstanceGranularityThreshold`.' }),
lod: PD.Vec3(Vec3(), undefined, { ...CullingLodCategory, description: 'Level of detail.', fieldLabels: { x: 'Min Distance', y: 'Max Distance', z: 'Overlap (Shader)' } }),
cellSize: PD.Numeric(200, { min: 0, max: 5000, step: 100 }, { ...CullingLodCategory, description: 'Instance grid cell size.' }),
batchSize: PD.Numeric(2000, { min: 0, max: 50000, step: 500 }, { ...CullingLodCategory, description: 'Instance grid batch size.' }),
@@ -130,7 +149,7 @@ export namespace BaseGeometry {
uClipObjectScale: ValueCell.create(clip.objects.scale),
uClipObjectTransform: ValueCell.create(clip.objects.transform),
instanceGranularity: ValueCell.create(props.instanceGranularity),
instanceGranularity: ValueCell.create(resolveInstanceGranularity(props.instanceGranularity, counts.groupCount, counts.instanceCount)),
uLod: ValueCell.create(Vec4.create(props.lod[0], props.lod[1], props.lod[2], 0)),
};
}
@@ -153,7 +172,7 @@ export namespace BaseGeometry {
ValueCell.update(values.uClipObjectScale, clip.objects.scale);
ValueCell.update(values.uClipObjectTransform, clip.objects.transform);
ValueCell.updateIfChanged(values.instanceGranularity, props.instanceGranularity);
ValueCell.updateIfChanged(values.instanceGranularity, resolveInstanceGranularity(props.instanceGranularity, values.uGroupCount.ref.value, values.instanceCount.ref.value));
ValueCell.update(values.uLod, Vec4.set(values.uLod.ref.value, props.lod[0], props.lod[1], props.lod[2], 0));
}

View File

@@ -19,7 +19,7 @@ import { calculateInvariantBoundingSphere, calculateTransformBoundingSphere } fr
import { Sphere3D } from '../../../mol-math/geometry';
import { Theme } from '../../../mol-theme/theme';
import { Color } from '../../../mol-util/color';
import { BaseGeometry } from '../base';
import { BaseGeometry, resolveInstanceGranularity } from '../base';
import { createEmptyOverpaint } from '../overpaint-data';
import { createEmptyTransparency } from '../transparency-data';
import { hashFnv32a } from '../../../mol-data/util';
@@ -225,7 +225,7 @@ export namespace Cylinders {
const color = createColors(locationIt, positionIt, theme.color);
const size = createSizes(locationIt, positionIt, theme.size);
const marker = props.instanceGranularity
const marker = resolveInstanceGranularity(props.instanceGranularity, groupCount, instanceCount)
? createMarkers(instanceCount, 'instance')
: createMarkers(instanceCount * groupCount, 'groupInstance');
const overpaint = createEmptyOverpaint();

View File

@@ -17,7 +17,7 @@ import { ValueCell } from '../../../mol-util';
import { Color } from '../../../mol-util/color';
import { ParamDefinition as PD } from '../../../mol-util/param-definition';
import { Box } from '../../primitive/box';
import { BaseGeometry } from '../base';
import { BaseGeometry, resolveInstanceGranularity } from '../base';
import { createColors } from '../color-data';
import { GeometryUtils } from '../geometry';
import { createMarkers } from '../marker-data';
@@ -228,7 +228,7 @@ export namespace DirectVolume {
const positionIt = createPositionIterator(directVolume, transform);
const color = createColors(locationIt, positionIt, theme.color);
const marker = props.instanceGranularity
const marker = resolveInstanceGranularity(props.instanceGranularity, groupCount, instanceCount)
? createMarkers(instanceCount, 'instance')
: createMarkers(instanceCount * groupCount, 'groupInstance');
const overpaint = createEmptyOverpaint();

View File

@@ -14,7 +14,7 @@ import { Theme } from '../../../mol-theme/theme';
import { ValueCell } from '../../../mol-util';
import { Color } from '../../../mol-util/color';
import { ParamDefinition as PD } from '../../../mol-util/param-definition';
import { BaseGeometry } from '../base';
import { BaseGeometry, resolveInstanceGranularity } from '../base';
import { createColors } from '../color-data';
import { GeometryUtils } from '../geometry';
import { createMarkers } from '../marker-data';
@@ -201,7 +201,7 @@ namespace Image {
const positionIt = createPositionIterator(image, transform);
const color = createColors(locationIt, positionIt, theme.color);
const marker = props.instanceGranularity
const marker = resolveInstanceGranularity(props.instanceGranularity, groupCount, instanceCount)
? createMarkers(instanceCount, 'instance')
: createMarkers(instanceCount * groupCount, 'groupInstance');
const overpaint = createEmptyOverpaint();

View File

@@ -21,7 +21,7 @@ import { calculateInvariantBoundingSphere, calculateTransformBoundingSphere } fr
import { Sphere3D } from '../../../mol-math/geometry';
import { Theme } from '../../../mol-theme/theme';
import { Color } from '../../../mol-util/color';
import { BaseGeometry } from '../base';
import { BaseGeometry, resolveInstanceGranularity } from '../base';
import { createEmptyOverpaint } from '../overpaint-data';
import { createEmptyTransparency } from '../transparency-data';
import { hashFnv32a } from '../../../mol-data/util';
@@ -232,7 +232,7 @@ export namespace Lines {
const color = createColors(locationIt, positionIt, theme.color);
const size = createSizes(locationIt, positionIt, theme.size);
const marker = props.instanceGranularity
const marker = resolveInstanceGranularity(props.instanceGranularity, groupCount, instanceCount)
? createMarkers(instanceCount, 'instance')
: createMarkers(instanceCount * groupCount, 'groupInstance');
const overpaint = createEmptyOverpaint();

View File

@@ -20,7 +20,7 @@ import { calculateInvariantBoundingSphere, calculateTransformBoundingSphere } fr
import { Theme } from '../../../mol-theme/theme';
import { MeshValues } from '../../../mol-gl/renderable/mesh';
import { Color } from '../../../mol-util/color';
import { BaseGeometry } from '../base';
import { BaseGeometry, resolveInstanceGranularity } from '../base';
import { createEmptyOverpaint } from '../overpaint-data';
import { createEmptyTransparency } from '../transparency-data';
import { createEmptyClipping } from '../clipping-data';
@@ -684,7 +684,7 @@ export namespace Mesh {
const positionIt = createPositionIterator(mesh, transform);
const color = createColors(locationIt, positionIt, theme.color);
const marker = props.instanceGranularity
const marker = resolveInstanceGranularity(props.instanceGranularity, groupCount, instanceCount)
? createMarkers(instanceCount, 'instance')
: createMarkers(instanceCount * groupCount, 'groupInstance');
const overpaint = createEmptyOverpaint();

View File

@@ -20,7 +20,7 @@ import { Theme } from '../../../mol-theme/theme';
import { PointsValues } from '../../../mol-gl/renderable/points';
import { RenderableState } from '../../../mol-gl/renderable';
import { Color } from '../../../mol-util/color';
import { BaseGeometry } from '../base';
import { BaseGeometry, resolveInstanceGranularity } from '../base';
import { createEmptyOverpaint } from '../overpaint-data';
import { createEmptyTransparency } from '../transparency-data';
import { hashFnv32a } from '../../../mol-data/util';
@@ -178,7 +178,7 @@ export namespace Points {
const color = createColors(locationIt, positionIt, theme.color);
const size = createSizes(locationIt, positionIt, theme.size);
const marker = props.instanceGranularity
const marker = resolveInstanceGranularity(props.instanceGranularity, groupCount, instanceCount)
? createMarkers(instanceCount, 'instance')
: createMarkers(instanceCount * groupCount, 'groupInstance');
const overpaint = createEmptyOverpaint();

View File

@@ -17,7 +17,7 @@ import { TextureImage, calculateInvariantBoundingSphere, calculateTransformBound
import { Sphere3D } from '../../../mol-math/geometry';
import { createSizes, getMaxSize } from '../size-data';
import { Color } from '../../../mol-util/color';
import { BaseGeometry } from '../base';
import { BaseGeometry, resolveInstanceGranularity } from '../base';
import { createEmptyOverpaint } from '../overpaint-data';
import { createEmptyTransparency } from '../transparency-data';
import { hashFnv32a } from '../../../mol-data/util';
@@ -249,6 +249,33 @@ export namespace Spheres {
return lodLevels.map(l => getAdjustedStride(l, sizeFactor)).reverse();
}
export const LodLevelsPresets: { [key in 'performance' | 'balanced' | 'quality' | 'ultra']: LodLevels } = {
performance: [
{ minDistance: 1, maxDistance: 300, overlap: 0, stride: 1, scaleBias: 1 },
{ minDistance: 300, maxDistance: 2000, overlap: 0, stride: 40, scaleBias: 3 },
{ minDistance: 2000, maxDistance: 6000, overlap: 0, stride: 150, scaleBias: 3 },
{ minDistance: 6000, maxDistance: 10000000, overlap: 0, stride: 300, scaleBias: 2.5 },
],
balanced: [
{ minDistance: 1, maxDistance: 500, overlap: 0, stride: 1, scaleBias: 1 },
{ minDistance: 500, maxDistance: 2000, overlap: 0, stride: 15, scaleBias: 3 },
{ minDistance: 2000, maxDistance: 6000, overlap: 0, stride: 70, scaleBias: 2.7 },
{ minDistance: 6000, maxDistance: 10000000, overlap: 0, stride: 200, scaleBias: 2.5 },
],
quality: [
{ minDistance: 1, maxDistance: 1000, overlap: 0, stride: 1, scaleBias: 1 },
{ minDistance: 1000, maxDistance: 4000, overlap: 0, stride: 10, scaleBias: 3 },
{ minDistance: 4000, maxDistance: 10000, overlap: 0, stride: 50, scaleBias: 2.7 },
{ minDistance: 10000, maxDistance: 10000000, overlap: 0, stride: 200, scaleBias: 2.3 },
],
ultra: [
{ minDistance: 1, maxDistance: 5000, overlap: 0, stride: 1, scaleBias: 1 },
{ minDistance: 5000, maxDistance: 10000, overlap: 0, stride: 10, scaleBias: 3 },
{ minDistance: 10000, maxDistance: 30000, overlap: 0, stride: 50, scaleBias: 2.5 },
{ minDistance: 30000, maxDistance: 10000000, overlap: 0, stride: 200, scaleBias: 2 },
],
};
export const Params = {
...BaseGeometry.Params,
sizeFactor: PD.Numeric(1, { min: 0, max: 10, step: 0.1 }),
@@ -273,7 +300,8 @@ export namespace Spheres {
scaleBias: PD.Numeric(3, { min: 0.1, max: 10, step: 0.1 }),
}, o => `${o.stride}`, {
...BaseGeometry.CullingLodCategory,
defaultValue: [] as LodLevels
defaultValue: [] as LodLevels,
presets: Object.entries(LodLevelsPresets).map(([k, v]) => [v, k])
})
};
export type Params = typeof Params
@@ -314,7 +342,7 @@ export namespace Spheres {
const color = createColors(locationIt, positionIt, theme.color);
const size = createSizes(locationIt, positionIt, theme.size);
const marker = props.instanceGranularity
const marker = resolveInstanceGranularity(props.instanceGranularity, groupCount, instanceCount)
? createMarkers(instanceCount, 'instance')
: createMarkers(instanceCount * groupCount, 'groupInstance');
const overpaint = createEmptyOverpaint();

View File

@@ -25,7 +25,7 @@ import { FontAtlasParams } from './font-atlas';
import { RenderableState } from '../../../mol-gl/renderable';
import { clamp } from '../../../mol-math/interpolate';
import { createRenderObject as _createRenderObject } from '../../../mol-gl/render-object';
import { BaseGeometry } from '../base';
import { BaseGeometry, resolveInstanceGranularity } from '../base';
import { createEmptyOverpaint } from '../overpaint-data';
import { createEmptyTransparency } from '../transparency-data';
import { hashFnv32a } from '../../../mol-data/util';
@@ -219,7 +219,7 @@ export namespace Text {
const color = createColors(locationIt, positionIt, theme.color);
const size = createSizes(locationIt, positionIt, theme.size);
const marker = props.instanceGranularity
const marker = resolveInstanceGranularity(props.instanceGranularity, groupCount, instanceCount)
? createMarkers(instanceCount, 'instance')
: createMarkers(instanceCount * groupCount, 'groupInstance');
const overpaint = createEmptyOverpaint();

View File

@@ -15,7 +15,7 @@ import { createMarkers } from '../marker-data';
import { GeometryUtils } from '../geometry';
import { Theme } from '../../../mol-theme/theme';
import { Color } from '../../../mol-util/color';
import { BaseGeometry } from '../base';
import { BaseGeometry, resolveInstanceGranularity } from '../base';
import { createEmptyOverpaint } from '../overpaint-data';
import { createEmptyTransparency } from '../transparency-data';
import { TextureMeshValues } from '../../../mol-gl/renderable/texture-mesh';
@@ -203,7 +203,7 @@ export namespace TextureMesh {
const positionIt = Utils.createPositionIterator(textureMesh, transform);
const color = createColors(locationIt, positionIt, theme.color);
const marker = props.instanceGranularity
const marker = resolveInstanceGranularity(props.instanceGranularity, groupCount, instanceCount)
? createMarkers(instanceCount, 'instance')
: createMarkers(instanceCount * groupCount, 'groupInstance');
const overpaint = createEmptyOverpaint();

View File

@@ -167,9 +167,9 @@ namespace Loci {
} else if (loci.kind === 'data-loci') {
return loci.getBoundingSphere?.(boundingSphere);
} else if (loci.kind === 'volume-loci') {
return Volume.getBoundingSphere(loci.volume, boundingSphere);
return Volume.getBoundingSphere(loci.volume, loci.instances, boundingSphere);
} else if (loci.kind === 'isosurface-loci') {
return Volume.Isosurface.getBoundingSphere(loci.volume, loci.isoValue, boundingSphere);
return Volume.Isosurface.getBoundingSphere(loci.volume, loci.isoValue, loci.instances, boundingSphere);
} else if (loci.kind === 'cell-loci') {
return Volume.Cell.getBoundingSphere(loci.volume, loci.elements, boundingSphere);
} else if (loci.kind === 'segment-loci') {

View File

@@ -545,6 +545,12 @@ export function surroundingLigands({ query, radius, includeWater }: SurroundingL
continue;
}
// Water is handled exclusively by the `includeWater` 3D-lookup branch below.
// A single water pulled in via a struct_conn metalc/covale edge would
// otherwise match every other water in the chain (all share label_seq_id
// and label_comp_id) and leak the entire chain.
if (StructureProperties.entity.type(l) === 'water') continue;
residuesIt.setSegment(chainSegment);
while (residuesIt.hasNext) {
const residueSegment = residuesIt.move();

View File

@@ -68,6 +68,36 @@ namespace Grid {
return Sphere3D.fromDimensionsAndTransform(boundingSphere, dimensions, transform);
}
const _isoBbox = Box3D();
export function getIsosurfaceBoundingSphere(grid: Grid, isoValue: number, boundingSphere?: Sphere3D) {
const neg = isoValue < 0;
const c = [0, 0, 0];
const getCoords = grid.cells.space.getCoords;
const d = grid.cells.data;
const [xn, yn, zn] = grid.cells.space.dimensions;
let minx = xn - 1, miny = yn - 1, minz = zn - 1;
let maxx = 0, maxy = 0, maxz = 0;
for (let i = 0, il = d.length; i < il; ++i) {
if ((neg && d[i] <= isoValue) || (!neg && d[i] >= isoValue)) {
getCoords(i, c);
if (c[0] < minx) minx = c[0];
if (c[1] < miny) miny = c[1];
if (c[2] < minz) minz = c[2];
if (c[0] > maxx) maxx = c[0];
if (c[1] > maxy) maxy = c[1];
if (c[2] > maxz) maxz = c[2];
}
}
Vec3.set(_isoBbox.min, minx - 1, miny - 1, minz - 1);
Vec3.set(_isoBbox.max, maxx + 1, maxy + 1, maxz + 1);
const transform = Grid.getGridToCartesianTransform(grid);
Box3D.transform(_isoBbox, _isoBbox, transform);
return Sphere3D.fromBox3D(boundingSphere || Sphere3D(), _isoBbox);
}
/**
* Compute histogram with given bin count.
* Cached on the Grid object.

View File

@@ -6,7 +6,7 @@
*/
import { Grid } from './grid';
import { OrderedSet } from '../../mol-data/int';
import { Interval, OrderedSet } from '../../mol-data/int';
import { Box3D, Sphere3D } from '../../mol-math/geometry';
import { Vec3, Mat4 } from '../../mol-math/linear-algebra';
import { BoundaryHelper } from '../../mol-math/geometry/boundary-helper';
@@ -191,14 +191,14 @@ export namespace Volume {
export function isLociEmpty(loci: Loci) { return isEmpty(loci.volume) || OrderedSet.isEmpty(loci.instances); }
const boundaryHelper = new BoundaryHelper('98');
export function getBoundingSphere(volume: Volume, boundingSphere?: Sphere3D) {
export function getBoundingSphere(volume: Volume, instances: OrderedSet<InstanceIndex>, boundingSphere?: Sphere3D) {
const gs = Grid.getBoundingSphere(volume.grid);
if (!boundingSphere) boundingSphere = Sphere3D();
if (volume.instances.length === 0) return Sphere3D.copy(boundingSphere, gs);
if (OrderedSet.isEmpty(instances)) return Sphere3D.copy(boundingSphere, gs);
const spheres: Sphere3D[] = [];
for (let i = 0, il = volume.instances.length; i < il; ++i) {
const { transform } = volume.instances[i];
for (let i = 0, il = OrderedSet.size(instances); i < il; ++i) {
const { transform } = volume.instances[OrderedSet.getAt(instances, i)];
spheres.push(Sphere3D.transform(Sphere3D(), gs, transform));
}
@@ -220,35 +220,23 @@ export namespace Volume {
export function areLociEqual(a: Loci, b: Loci) { return a.volume === b.volume && Volume.IsoValue.areSame(a.isoValue, b.isoValue, a.volume.grid.stats) && OrderedSet.areEqual(a.instances, b.instances); }
export function isLociEmpty(loci: Loci) { return isEmpty(loci.volume) || OrderedSet.isEmpty(loci.instances); }
const bbox = Box3D();
export function getBoundingSphere(volume: Volume, isoValue: Volume.IsoValue, boundingSphere?: Sphere3D) {
const boundaryHelper = new BoundaryHelper('98');
export function getBoundingSphere(volume: Volume, isoValue: Volume.IsoValue, instances: OrderedSet<InstanceIndex>, boundingSphere?: Sphere3D) {
const value = Volume.IsoValue.toAbsolute(isoValue, volume.grid.stats).absoluteValue;
const neg = value < 0;
const gs = Grid.getIsosurfaceBoundingSphere(volume.grid, value);
const c = [0, 0, 0];
const getCoords = volume.grid.cells.space.getCoords;
const d = volume.grid.cells.data;
const [xn, yn, zn] = volume.grid.cells.space.dimensions;
if (OrderedSet.isEmpty(instances)) return Sphere3D.copy(boundingSphere || Sphere3D(), gs);
let minx = xn - 1, miny = yn - 1, minz = zn - 1;
let maxx = 0, maxy = 0, maxz = 0;
for (let i = 0, il = d.length; i < il; ++i) {
if ((neg && d[i] <= value) || (!neg && d[i] >= value)) {
getCoords(i, c);
if (c[0] < minx) minx = c[0];
if (c[1] < miny) miny = c[1];
if (c[2] < minz) minz = c[2];
if (c[0] > maxx) maxx = c[0];
if (c[1] > maxy) maxy = c[1];
if (c[2] > maxz) maxz = c[2];
}
const spheres: Sphere3D[] = [];
for (let i = 0, il = OrderedSet.size(instances); i < il; ++i) {
spheres.push(Sphere3D.transform(Sphere3D(), gs, volume.instances[OrderedSet.getAt(instances, i)].transform));
}
Vec3.set(bbox.min, minx - 1, miny - 1, minz - 1);
Vec3.set(bbox.max, maxx + 1, maxy + 1, maxz + 1);
const transform = Grid.getGridToCartesianTransform(volume.grid);
Box3D.transform(bbox, bbox, transform);
return Sphere3D.fromBox3D(boundingSphere || Sphere3D(), bbox);
boundaryHelper.reset();
for (const s of spheres) boundaryHelper.includeSphere(s);
boundaryHelper.finishedIncludeStep();
for (const s of spheres) boundaryHelper.radiusSphere(s);
return boundaryHelper.getSphere(boundingSphere);
}
}
@@ -416,7 +404,7 @@ export namespace Volume {
}
return Sphere3D.fromBox3D(boundingSphere || Sphere3D(), bbox);
} else {
return Volume.getBoundingSphere(volume, boundingSphere);
return Volume.getBoundingSphere(volume, Interval.ofLength(volume.instances.length as InstanceIndex), boundingSphere);
}
}

View File

@@ -1,5 +1,5 @@
/**
* Copyright (c) 2018-2024 mol* contributors, licensed under MIT, See LICENSE file for more info.
* Copyright (c) 2018-2026 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
* @author Alexander Rose <alexander.rose@weirdbyte.de>
@@ -436,12 +436,12 @@ export const LoadTrajectory = StateAction.build({
//
const dependsOn = [model.ref, coordinates.ref];
// dependsOn is auto-derived from the `getDependencies` hook on TrajectoryFromModelAndCoordinates
const traj = state.build().toRoot()
.apply(TrajectoryFromModelAndCoordinates, {
modelRef: model.ref,
coordinatesRef: coordinates.ref
}, { dependsOn })
})
.apply(StateTransforms.Model.ModelFromTrajectory, { modelIndex: 0 });
await state.updateTree(traj).runInContext(taskCtx);

View File

@@ -1,5 +1,5 @@
/**
* Copyright (c) 2019-2025 mol* contributors, licensed under MIT, See LICENSE file for more info.
* Copyright (c) 2019-2026 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
* @author Alexander Rose <alexander.rose@weirdbyte.de>
@@ -26,6 +26,7 @@ import { StructConn } from '../../../mol-model-formats/structure/property/bonds/
import { StructureRepresentationRegistry } from '../../../mol-repr/structure/registry';
import { assertUnreachable } from '../../../mol-util/type-helpers';
import { Vec3 } from '../../../mol-math/linear-algebra/3d/vec3';
import { Spheres } from '../../../mol-geo/geometry/spheres/spheres';
export interface StructureRepresentationPresetProvider<P = any, S extends _Result = _Result> extends PresetProvider<PluginStateObject.Molecule.Structure, P, S> { }
export function StructureRepresentationPresetProvider<P, S extends _Result>(repr: StructureRepresentationPresetProvider<P, S>) { return repr; }
@@ -495,6 +496,61 @@ const autoLod = StructureRepresentationPresetProvider({
}
});
type MesoscaleGraphicsMode = keyof typeof Spheres.LodLevelsPresets
const MesoscaleGraphicsOptions = PD.arrayToOptions(Object.keys(Spheres.LodLevelsPresets) as MesoscaleGraphicsMode[]);
function getMesoscaleLodLevels(mode: MesoscaleGraphicsMode) {
return Spheres.LodLevelsPresets[mode];
}
const mesoscale = StructureRepresentationPresetProvider({
id: 'preset-structure-representation-mesoscale',
display: {
name: 'Mesoscale', group: 'Miscellaneous',
description: 'Show everything in spacefill representation with instance-granularity and level-of-detail tuned for large particle scenes.'
},
params: () => ({
...CommonParams,
graphics: PD.Select<MesoscaleGraphicsMode>('quality', MesoscaleGraphicsOptions),
}),
async apply(ref, params, plugin) {
const structureCell = StateObjectRef.resolveAndCheck(plugin.state.data, ref);
if (!structureCell) return {};
const components = {
all: await presetStaticComponent(plugin, structureCell, 'all'),
};
const structure = structureCell.obj!.data;
const { update, builder, typeParams, color } = reprBuilder(plugin, params, structure);
const graphics: MesoscaleGraphicsMode = params.graphics ?? 'quality';
const lodLevels = getMesoscaleLodLevels(graphics);
const approximate = graphics !== 'quality' && graphics !== 'ultra';
const alphaThickness = graphics === 'performance' ? 15 : 12;
const representations = {
all: builder.buildRepresentation(update, components.all, {
type: 'spacefill',
typeParams: {
...typeParams,
instanceGranularity: true,
lodLevels,
approximate,
alphaThickness,
clipPrimitive: true,
},
color: color || 'entity-id',
}, { tag: 'all' }),
};
await update.commit({ revertOnError: true });
await updateFocusRepr(plugin, structure, params.theme?.focus?.name ?? color, params.theme?.focus?.params);
return { components, representations };
}
});
export function presetStaticComponent(plugin: PluginContext, structure: StateObjectRef<PluginStateObject.Molecule.Structure>, type: StaticStructureComponentType, params?: { label?: string, tags?: string[] }) {
return plugin.builders.structure.tryCreateComponentStatic(structure, type, params);
}
@@ -514,5 +570,6 @@ export const PresetStructureRepresentations = {
illustrative,
'molecular-surface': molecularSurface,
'auto-lod': autoLod,
mesoscale,
};
export type PresetStructureRepresentations = typeof PresetStructureRepresentations;

View File

@@ -22,7 +22,7 @@ import { PluginContext } from '../../mol-plugin/context';
import { MolScriptBuilder } from '../../mol-script/language/builder';
import { Expression } from '../../mol-script/language/expression';
import { Script } from '../../mol-script/script';
import { StateObject, StateTransformer } from '../../mol-state';
import { StateObject, StateTransform, StateTransformer } from '../../mol-state';
import { RuntimeContext, Task } from '../../mol-task';
import { deepEqual } from '../../mol-util';
import { ParamDefinition as PD } from '../../mol-util/param-definition';
@@ -247,6 +247,12 @@ const TrajectoryFromModelAndCoordinates = PluginStateTransform.BuiltIn({
coordinatesRef: PD.Text('', { isHidden: true }),
}
})({
getDependencies: ({ modelRef, coordinatesRef }: { modelRef: string, coordinatesRef: string }) => {
const deps: StateTransform.Ref[] = [];
if (modelRef) deps.push(modelRef as StateTransform.Ref);
if (coordinatesRef) deps.push(coordinatesRef as StateTransform.Ref);
return deps;
},
apply({ params, dependencies }) {
return Task.create('Create trajectory from model/topology and coordinates', async ctx => {
const coordinates = dependencies![params.coordinatesRef].data as Coordinates;
@@ -1304,7 +1310,7 @@ const ShapeFromPly = PluginStateTransform.BuiltIn({
to: SO.Shape.Provider,
params(a) {
return {
transforms: PD.Optional(PD.Value<Mat4[]>([], { isHidden: true })),
transforms: PD.Optional(PD.Value([Mat4.identity()], { isHidden: true })),
label: PD.Optional(PD.Text('', { isHidden: true }))
};
}

View File

@@ -18,7 +18,7 @@ import { volumeFromCube } from '../../mol-model-formats/volume/cube';
import { volumeFromDx } from '../../mol-model-formats/volume/dx';
import { Grid, Volume } from '../../mol-model/volume';
import { PluginContext } from '../../mol-plugin/context';
import { StateSelection, StateTransformer } from '../../mol-state';
import { StateSelection, StateTransform, StateTransformer } from '../../mol-state';
import { volumeFromSegmentationData } from '../../mol-model-formats/volume/segmentation';
import { getTransformFromParams, TransformParam, transformParamsNeedCentroid } from './helpers';
@@ -233,7 +233,8 @@ const AssignColorVolume = PluginStateTransform.BuiltIn({
const props = { label: a.label, description: 'Volume + Colors' };
return new SO.Volume.Data(volume, props);
});
}
},
getDependencies: ({ ref }) => ref ? [ref as StateTransform.Ref] : []
});
type VolumeTransform = typeof VolumeTransform;

View File

@@ -1414,8 +1414,8 @@ class ObjectListItem extends React.PureComponent<ObjectListItemProps, { isExpand
}
}
export class ObjectListControl extends React.PureComponent<ParamProps<PD.ObjectList>, { isExpanded: boolean }> {
state = { isExpanded: false };
export class ObjectListControl extends React.PureComponent<ParamProps<PD.ObjectList>, { isExpanded: boolean, showPresets: boolean }> {
state = { isExpanded: false, showPresets: false };
change(value: any) {
this.props.onChange({ name: this.props.name, param: this.props.param, value });
@@ -1459,12 +1459,29 @@ export class ObjectListControl extends React.PureComponent<ParamProps<PD.ObjectL
e.currentTarget.blur();
};
toggleShowPresets = () => this.setState({ showPresets: !this.state.showPresets });
presetItems = memoizeLatest((param: PD.ObjectList) => ActionMenu.createItemsFromSelectOptions(param.presets ?? []));
onSelectPreset: ActionMenu.OnSelect = item => {
this.setState({ showPresets: false });
this.change(item?.value);
};
render() {
const v = this.props.value;
const label = this.props.param.label || camelCaseToWords(this.props.name);
const value = `${v.length} item${v.length !== 1 ? 's' : ''}`;
const hasPresets = !!this.props.param.presets;
const control = hasPresets
? <div className='msp-flex-row'>
<button onClick={this.toggleExpanded} disabled={this.props.isDisabled}>{value}</button>
<IconButton svg={BookmarksOutlinedSvg} onClick={this.toggleShowPresets} toggleState={this.state.showPresets} title='Presets' disabled={this.props.isDisabled} />
</div>
: <button onClick={this.toggleExpanded} disabled={this.props.isDisabled}>{value}</button>;
return <>
<ControlRow label={label} control={<button onClick={this.toggleExpanded} disabled={this.props.isDisabled}>{value}</button>} />
<ControlRow label={label} control={control} />
{hasPresets && this.state.showPresets && <ActionMenu items={this.presetItems(this.props.param)} onSelect={this.onSelectPreset} />}
{this.state.isExpanded && <div className='msp-control-offset'>
{this.props.value.map((v, i) => <ObjectListItem key={i} param={this.props.param} value={v} index={i} actions={this.actions} isDisabled={this.props.isDisabled} />)}
<ControlGroup header='New Item'>

View File

@@ -5,6 +5,7 @@
*/
import { Geometry, GeometryUtils } from '../../mol-geo/geometry/geometry';
import { resolveInstanceGranularity } from '../../mol-geo/geometry/base';
import { Representation } from '../representation';
import { Shape, ShapeGroup } from '../../mol-model/shape';
import { Subject } from 'rxjs';
@@ -129,7 +130,7 @@ export function ShapeRepresentation<D, G extends Geometry, P extends Geometry.Pa
// console.log('update transform')
locationIt = Shape.groupIterator(_shape);
const { instanceCount, groupCount } = locationIt;
if (props.instanceGranularity) {
if (resolveInstanceGranularity(newProps.instanceGranularity, groupCount, instanceCount)) {
createMarkers(instanceCount, 'instance', _renderObject.values);
} else {
createMarkers(instanceCount * groupCount, 'groupInstance', _renderObject.values);
@@ -197,14 +198,15 @@ export function ShapeRepresentation<D, G extends Geometry, P extends Geometry.Pa
}
function lociApply(loci: Loci, apply: (interval: Interval) => boolean) {
const instanceGranularity = resolveInstanceGranularity(currentProps.instanceGranularity, _shape.groupCount, _shape.transforms.length);
if (isEveryLoci(loci) || (Shape.isLoci(loci) && loci.shape === _shape)) {
if (currentProps.instanceGranularity) {
if (instanceGranularity) {
return apply(Interval.ofBounds(0, _shape.transforms.length));
} else {
return apply(Interval.ofBounds(0, _shape.groupCount * _shape.transforms.length));
}
} else {
if (currentProps.instanceGranularity) {
if (instanceGranularity) {
return eachInstance(loci, _shape, apply);
} else {
return eachShapeGroup(loci, _shape, apply);
@@ -226,7 +228,8 @@ export function ShapeRepresentation<D, G extends Geometry, P extends Geometry.Pa
getLoci(pickingId: PickingId) {
const { objectId, groupId, instanceId } = pickingId;
if (_renderObject && _renderObject.id === objectId) {
if (groupId === PickingId.Null) {
const instanceGranularity = resolveInstanceGranularity(currentProps.instanceGranularity, _shape.groupCount, _shape.transforms.length);
if (groupId === PickingId.Null || instanceGranularity) {
return Shape.Loci(_shape);
} else {
return ShapeGroup.Loci(_shape, [{ ids: OrderedSet.ofSingleton(groupId), instance: instanceId }]);

View File

@@ -32,6 +32,7 @@ import { Text } from '../../mol-geo/geometry/text/text';
import { SizeTheme } from '../../mol-theme/size';
import { DirectVolume } from '../../mol-geo/geometry/direct-volume/direct-volume';
import { createMarkers } from '../../mol-geo/geometry/marker-data';
import { resolveInstanceGranularity } from '../../mol-geo/geometry/base';
import { StructureParams, StructureMeshParams, StructureTextParams, StructureDirectVolumeParams, StructureLinesParams, StructureCylindersParams, StructureTextureMeshParams, StructureSpheresParams, StructurePointsParams, StructureImageParams } from './params';
import { Clipping } from '../../mol-theme/clipping';
import { TextureMesh } from '../../mol-geo/geometry/texture-mesh/texture-mesh';
@@ -173,7 +174,7 @@ export function ComplexVisual<G extends Geometry, P extends StructureParams & Ge
if (updateState.updateTransform) {
// console.log('update transform')
const { instanceCount, groupCount } = locationIt;
if (newProps.instanceGranularity) {
if (resolveInstanceGranularity(newProps.instanceGranularity, groupCount, instanceCount)) {
createMarkers(instanceCount, 'instance', renderObject.values);
} else {
createMarkers(instanceCount * groupCount, 'groupInstance', renderObject.values);
@@ -237,14 +238,15 @@ export function ComplexVisual<G extends Geometry, P extends StructureParams & Ge
}
function lociApply(loci: Loci, apply: (interval: Interval) => boolean, isMarking: boolean) {
const instanceGranularity = resolveInstanceGranularity(currentProps.instanceGranularity, locationIt.groupCount, locationIt.instanceCount);
if (lociIsSuperset(loci)) {
if (currentProps.instanceGranularity) {
if (instanceGranularity) {
return apply(Interval.ofBounds(0, locationIt.instanceCount));
} else {
return apply(Interval.ofBounds(0, locationIt.groupCount * locationIt.instanceCount));
}
} else {
if (currentProps.instanceGranularity) {
if (instanceGranularity) {
return eachInstance(loci, currentStructure, apply);
} else {
return eachLocation(loci, currentStructure, apply, isMarking);
@@ -279,7 +281,11 @@ export function ComplexVisual<G extends Geometry, P extends StructureParams & Ge
finalize(ctx);
},
getLoci(pickingId: PickingId) {
return renderObject ? getLoci(pickingId, currentStructure, renderObject.id) : EmptyLoci;
if (!renderObject) return EmptyLoci;
if (resolveInstanceGranularity(currentProps.instanceGranularity, locationIt.groupCount, locationIt.instanceCount)) {
pickingId = { ...pickingId, groupId: PickingId.Null };
}
return getLoci(pickingId, currentStructure, renderObject.id);
},
eachLocation(cb: LocationCallback) {
locationIt.reset();

View File

@@ -20,6 +20,7 @@ import { Interval } from '../../mol-data/int';
import { LocationCallback, VisualUpdateState } from '../util';
import { ColorTheme } from '../../mol-theme/color';
import { createMarkers } from '../../mol-geo/geometry/marker-data';
import { resolveInstanceGranularity } from '../../mol-geo/geometry/base';
import { MarkerAction } from '../../mol-util/marker-action';
import { ValueCell, deepEqual } from '../../mol-util';
import { createSizes } from '../../mol-geo/geometry/size-data';
@@ -214,7 +215,7 @@ export function UnitsVisual<G extends Geometry, P extends StructureParams & Geom
if (updateState.updateTransform) {
// console.log('update transform');
const { instanceCount, groupCount } = locationIt;
if (newProps.instanceGranularity) {
if (resolveInstanceGranularity(newProps.instanceGranularity, groupCount, instanceCount)) {
createMarkers(instanceCount, 'instance', renderObject.values);
} else {
createMarkers(instanceCount * groupCount, 'groupInstance', renderObject.values);
@@ -313,14 +314,15 @@ export function UnitsVisual<G extends Geometry, P extends StructureParams & Geom
}
function lociApply(loci: Loci, apply: (interval: Interval) => boolean, isMarking: boolean) {
const instanceGranularity = resolveInstanceGranularity(currentProps.instanceGranularity, locationIt.groupCount, locationIt.instanceCount);
if (lociIsSuperset(loci)) {
if (currentProps.instanceGranularity) {
if (instanceGranularity) {
return apply(Interval.ofBounds(0, locationIt.instanceCount));
} else {
return apply(Interval.ofBounds(0, locationIt.groupCount * locationIt.instanceCount));
}
} else {
if (currentProps.instanceGranularity) {
if (instanceGranularity) {
return eachInstance(loci, currentStructureGroup, apply);
} else {
return eachLocation(loci, currentStructureGroup, apply, isMarking);
@@ -355,7 +357,11 @@ export function UnitsVisual<G extends Geometry, P extends StructureParams & Geom
finalize(ctx);
},
getLoci(pickingId: PickingId) {
return renderObject ? getLoci(pickingId, currentStructureGroup, renderObject.id) : EmptyLoci;
if (!renderObject) return EmptyLoci;
if (resolveInstanceGranularity(currentProps.instanceGranularity, locationIt.groupCount, locationIt.instanceCount)) {
pickingId = { ...pickingId, groupId: PickingId.Null };
}
return getLoci(pickingId, currentStructureGroup, renderObject.id);
},
eachLocation(cb: LocationCallback) {
locationIt.reset();

View File

@@ -0,0 +1,59 @@
/**
* Copyright (c) 2026 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author Ludovic Autin <autin@scripps.edu>
*/
import { CustomProperties } from '../../../mol-model/custom-property';
import { Grid, Volume } from '../../../mol-model/volume';
import { Mat4, Tensor } from '../../../mol-math/linear-algebra';
import { createVolumeSphereImpostor } from '../dot';
function createTestVolume(dimensions: [number, number, number], data: number[]): Volume {
return {
grid: {
transform: { kind: 'matrix', matrix: Mat4.identity() },
cells: Tensor.create(Tensor.Space(dimensions, [2, 1, 0]), Tensor.Data1(data)),
stats: { min: 0, max: 1, mean: 0.5, sigma: 0.5 },
} satisfies Grid,
instances: [{ transform: Mat4.identity() }],
sourceData: { kind: 'test', name: 'test', data: {} } as any,
customProperties: new CustomProperties(),
_propertyData: Object.create(null),
_localPropertyData: Object.create(null),
};
}
describe('volume dot representation', () => {
it('adds sphere impostor dots in Morton order for LOD sampling', () => {
const volume = createTestVolume([2, 2, 2], [
1, 1,
1, 1,
1, 1,
1, 1,
]);
const spheres = createVolumeSphereImpostor(undefined as any, volume, 0, undefined as any, {
isoValue: Volume.IsoValue.absolute(0.5),
perturbPositions: false,
lodLevels: [{ minDistance: 0, maxDistance: 0, overlap: 0, stride: 0, scaleBias: 3 }],
} as any);
expect(Array.from(spheres.groupBuffer.ref.value)).toEqual([0, 4, 2, 6, 1, 5, 3, 7]);
});
it('adds sphere impostor dots in row-major order when no LOD levels are configured', () => {
const volume = createTestVolume([2, 2, 2], [
1, 1,
1, 1,
1, 1,
1, 1,
]);
const spheres = createVolumeSphereImpostor(undefined as any, volume, 0, undefined as any, {
isoValue: Volume.IsoValue.absolute(0.5),
perturbPositions: false,
lodLevels: [],
} as any);
expect(Array.from(spheres.groupBuffer.ref.value)).toEqual([0, 1, 2, 3, 4, 5, 6, 7]);
});
});

View File

@@ -67,7 +67,8 @@ export function VolumeSphereImpostorVisual(materialId: number): VolumeVisual<Vol
setUpdateState: (state: VisualUpdateState, newVolume: Volume, currentVolume: Volume, newProps: PD.Values<VolumeSphereParams>, currentProps: PD.Values<VolumeSphereParams>, newTheme: Theme, currentTheme: Theme) => {
state.createGeometry = (
!Volume.IsoValue.areSame(newProps.isoValue, currentProps.isoValue, newVolume.grid.stats) ||
newProps.perturbPositions !== currentProps.perturbPositions
newProps.perturbPositions !== currentProps.perturbPositions ||
newProps.lodLevels.length > 0 && currentProps.lodLevels.length === 0
);
},
geometryUtils: Spheres.Utils,
@@ -128,38 +129,71 @@ export function createVolumeSphereImpostor(ctx: VisualContext, volume: Volume, k
const p = Vec3();
const [xn, yn, zn] = space.dimensions;
const count = Math.ceil((xn * yn * zn) / 10);
const builder = SpheresBuilder.create(count, Math.ceil(count / 2), spheres);
const invert = isoVal < 0;
// Precompute basis vectors and largest cell axis length
const basis = props.perturbPositions ? getBasis(gridToCartn) : undefined;
for (let z = 0; z < zn; ++z) {
for (let y = 0; y < yn; ++y) {
for (let x = 0; x < xn; ++x) {
const value = space.get(data, x, y, z);
if (!invert && value < isoVal || invert && value > isoVal) continue;
const count = Math.ceil((xn * yn * zn) / 10);
const builder = SpheresBuilder.create(count, Math.ceil(count / 2), spheres);
const cellIdx = space.dataOffset(x, y, z);
if (basis) {
Vec3.set(p, x, y, z);
Vec3.transformMat4(p, p, gridToCartn);
const offset = getRandomOffsetFromBasis(basis);
Vec3.add(p, p, offset);
} else {
Vec3.set(p, x, y, z);
Vec3.transformMat4(p, p, gridToCartn);
const add = (x: number, y: number, z: number) => {
const value = space.get(data, x, y, z);
if (!invert && value < isoVal || invert && value > isoVal) return;
const cellIdx = space.dataOffset(x, y, z);
Vec3.set(p, x, y, z);
Vec3.transformMat4(p, p, gridToCartn);
if (basis) {
Vec3.add(p, p, getRandomOffsetFromBasis(basis));
}
builder.add(p[0], p[1], p[2], cellIdx);
};
// Morton ordering keeps stride-based LOD sampling spatially balanced.
// Only worthwhile when LOD levels are configured; otherwise use the
// direct row-major path to avoid the extra allocations and sort.
const useMortonOrder = props.lodLevels.length > 0;
if (useMortonOrder) {
// Recursive octree traversal over the bounding power-of-two cube,
// visiting children in Morton order (octant bit2=x, bit1=y, bit0=z).
// Octants whose origin already exceeds the grid extent are pruned,
// so out-of-range subtrees of non-cube grids cost ~O(log) per skip.
let size = 1;
while (size < xn || size < yn || size < zn) size <<= 1;
const visit = (x0: number, y0: number, z0: number, s: number): void => {
if (x0 >= xn || y0 >= yn || z0 >= zn) return;
if (s === 1) {
add(x0, y0, z0);
return;
}
const h = s >> 1;
visit(x0, y0, z0, h);
visit(x0, y0, z0 + h, h);
visit(x0, y0 + h, z0, h);
visit(x0, y0 + h, z0 + h, h);
visit(x0 + h, y0, z0, h);
visit(x0 + h, y0, z0 + h, h);
visit(x0 + h, y0 + h, z0, h);
visit(x0 + h, y0 + h, z0 + h, h);
};
visit(0, 0, 0, size);
} else {
for (let z = 0; z < zn; ++z) {
for (let y = 0; y < yn; ++y) {
for (let x = 0; x < xn; ++x) {
add(x, y, z);
}
builder.add(p[0], p[1], p[2], cellIdx);
}
}
}
const s = builder.getSpheres();
s.setBoundingSphere(Volume.Isosurface.getBoundingSphere(volume, props.isoValue));
s.setBoundingSphere(Grid.getIsosurfaceBoundingSphere(volume.grid, Volume.IsoValue.toAbsolute(props.isoValue, volume.grid.stats).absoluteValue));
return s;
}
@@ -209,7 +243,7 @@ export function createVolumeSphereMesh(ctx: VisualContext, volume: Volume, key:
}
const m = MeshBuilder.getMesh(builderState);
m.setBoundingSphere(Volume.Isosurface.getBoundingSphere(volume, props.isoValue));
m.setBoundingSphere(Grid.getIsosurfaceBoundingSphere(volume.grid, Volume.IsoValue.toAbsolute(props.isoValue, volume.grid.stats).absoluteValue));
return m;
}
@@ -277,7 +311,7 @@ export function createVolumePoint(ctx: VisualContext, volume: Volume, key: numbe
}
const pt = builder.getPoints();
pt.setBoundingSphere(Volume.Isosurface.getBoundingSphere(volume, props.isoValue));
pt.setBoundingSphere(Grid.getIsosurfaceBoundingSphere(volume.grid, Volume.IsoValue.toAbsolute(props.isoValue, volume.grid.stats).absoluteValue));
return pt;
}
@@ -320,6 +354,7 @@ const DotVisuals = {
export const DotParams = {
...VolumeSphereParams,
...VolumePointParams,
sizeFactor: PD.Numeric(1, { min: 0, max: 10, step: 0.1 }),
visuals: PD.MultiSelect(['sphere'], PD.objectToOptions(DotVisuals)),
bumpFrequency: PD.Numeric(1, { min: 0, max: 10, step: 0.1 }, BaseGeometry.ShadingCategory),
};
@@ -346,4 +381,4 @@ export const DotRepresentationProvider = VolumeRepresentationProvider({
defaultSizeTheme: { name: 'uniform' },
locationKinds: ['cell-location', 'position-location'],
isApplicable: (volume: Volume) => !Volume.isEmpty(volume) && !Volume.Segmentation.get(volume)
});
});

View File

@@ -136,7 +136,7 @@ export async function createVolumeIsosurfaceMesh(ctx: VisualContext, volume: Vol
ValueCell.updateIfChanged(surface.varyingGroup, true);
}
surface.setBoundingSphere(Volume.Isosurface.getBoundingSphere(volume, props.isoValue));
surface.setBoundingSphere(Grid.getIsosurfaceBoundingSphere(volume.grid, Volume.IsoValue.toAbsolute(props.isoValue, volume.grid.stats).absoluteValue));
return surface;
}
@@ -318,7 +318,7 @@ export async function createVolumeIsosurfaceWireframe(ctx: VisualContext, volume
const transform = Grid.getGridToCartesianTransform(volume.grid);
Lines.transform(wireframe, transform);
wireframe.setBoundingSphere(Volume.Isosurface.getBoundingSphere(volume, props.isoValue));
wireframe.setBoundingSphere(Grid.getIsosurfaceBoundingSphere(volume.grid, Volume.IsoValue.toAbsolute(props.isoValue, volume.grid.stats).absoluteValue));
return wireframe;
}

View File

@@ -306,7 +306,7 @@ function getSampledImage(volume: Volume, theme: Theme, info: SamplingInfo, isoVa
const isoLevel = clamp(normalize(Volume.IsoValue.toAbsolute(isoValue, stats).absoluteValue, min, max), 0, 1);
const im = Image.create(imageTexture, corners, groupTexture, valueTexture, trim, isoLevel, image);
im.setBoundingSphere(Volume.isPeriodic(volume) ? Volume.getBoundingSphere(volume) : Grid.getBoundingSphere(volume.grid));
im.setBoundingSphere(Volume.isPeriodic(volume) ? Volume.getBoundingSphere(volume, Interval.ofLength(volume.instances.length as Volume.InstanceIndex)) : Grid.getBoundingSphere(volume.grid));
im.meta.mapping = mapping;
return im;
@@ -480,7 +480,7 @@ async function createGridImage(ctx: VisualContext, volume: Volume, key: number,
const isoLevel = clamp(normalize(Volume.IsoValue.toAbsolute(isoValue, stats).absoluteValue, min, max), 0, 1);
const im = Image.create(imageTexture, corners, groupTexture, valueTexture, trim, isoLevel, image);
im.setBoundingSphere(Volume.isPeriodic(volume) ? Volume.getBoundingSphere(volume) : Grid.getBoundingSphere(volume.grid));
im.setBoundingSphere(Volume.isPeriodic(volume) ? Volume.getBoundingSphere(volume, Interval.ofLength(volume.instances.length as Volume.InstanceIndex)) : Grid.getBoundingSphere(volume.grid));
im.meta.mapping = mapping;
return im;

View File

@@ -33,7 +33,7 @@ import { Emissive } from '../../mol-theme/emissive';
import { Wiggle } from '../../mol-theme/wiggle';
import { SizeTheme } from '../../mol-theme/size';
import { Sphere3D } from '../../mol-math/geometry/primitives/sphere3d';
import { BaseGeometry } from '../../mol-geo/geometry/base';
import { BaseGeometry, resolveInstanceGranularity } from '../../mol-geo/geometry/base';
export const VolumeParams = {
...BaseGeometry.Params,
@@ -182,7 +182,7 @@ export function VolumeVisual<G extends Geometry, P extends VolumeParams & Geomet
if (updateState.updateTransform || updateState.updateLocation) {
// console.log('update transform');
const { instanceCount, groupCount } = locationIt;
if (newProps.instanceGranularity) {
if (resolveInstanceGranularity(newProps.instanceGranularity, groupCount, instanceCount)) {
createMarkers(instanceCount, 'instance', renderObject.values);
} else {
createMarkers(instanceCount * groupCount, 'groupInstance', renderObject.values);
@@ -279,14 +279,15 @@ export function VolumeVisual<G extends Geometry, P extends VolumeParams & Geomet
}
function lociApply(loci: Loci, apply: (interval: Interval) => boolean) {
const instanceGranularity = resolveInstanceGranularity(currentProps.instanceGranularity, locationIt.groupCount, locationIt.instanceCount);
if (isEveryLoci(loci)) {
if (currentProps.instanceGranularity) {
if (instanceGranularity) {
return apply(Interval.ofBounds(0, locationIt.instanceCount));
} else {
return apply(Interval.ofBounds(0, locationIt.groupCount * locationIt.instanceCount));
}
} else {
if (currentProps.instanceGranularity) {
if (instanceGranularity) {
return eachInstance(loci, currentVolume, currentKey, apply);
} else {
return eachLocation(loci, currentVolume, currentKey, currentProps, apply, geometry);
@@ -308,7 +309,11 @@ export function VolumeVisual<G extends Geometry, P extends VolumeParams & Geomet
}
},
getLoci(pickingId: PickingId) {
return renderObject ? getLoci(pickingId, currentVolume, currentKey, currentProps, renderObject.id, geometry) : EmptyLoci;
if (!renderObject) return EmptyLoci;
if (resolveInstanceGranularity(currentProps.instanceGranularity, locationIt.groupCount, locationIt.instanceCount)) {
pickingId = { ...pickingId, groupId: PickingId.Null };
}
return getLoci(pickingId, currentVolume, currentKey, currentProps, renderObject.id, geometry);
},
eachLocation(cb: LocationCallback) {
locationIt.reset();

View File

@@ -0,0 +1,324 @@
/**
* Copyright (c) 2026 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author Alexander Rose <alexander.rose@weirdbyte.de>
*/
import { State, StateObject, StateObjectCell, StateTransform, StateTransformer, StateTreeCycleError } from '../../mol-state';
import { Task } from '../../mol-task';
import { ParamDefinition as PD } from '../../mol-util/param-definition';
interface TypeInfo { name: string; typeClass: 'Root' | 'Data' }
const Create = StateObject.factory<TypeInfo>();
class Root extends Create({ name: 'Root', typeClass: 'Root' }) { }
class Leaf extends Create<{ value: number }>({ name: 'Leaf', typeClass: 'Data' }) { }
const NS = 'state-deps-spec';
let counter = 0;
const uniq = (s: string) => `${s}-${counter++}`;
function newState() {
return State.create(new Root({}), { runTask: <T>(t: Task<T>) => t.run() });
}
/** Plain leaf created from Root with a number param. */
function constLeaf() {
return StateTransformer.create<Root, Leaf, { value: number }>(NS, {
name: uniq('const-leaf'),
from: [Root],
to: [Leaf],
display: { name: 'Const Leaf' },
params: () => ({ value: PD.Numeric(0) }) as any,
apply({ params }) { return new Leaf({ value: params.value }); },
update({ oldParams, newParams }) {
return oldParams.value === newParams.value
? StateTransformer.UpdateResult.Unchanged
: StateTransformer.UpdateResult.Recreate;
}
});
}
/** Leaf whose value is read from a single explicit dependsOn ref. */
function deriveFromDep(depRef: string) {
return StateTransformer.create<Root, Leaf, {}>(NS, {
name: uniq('derive-from-dep'),
from: [Root],
to: [Leaf],
display: { name: 'Derive From Dep' },
params: () => ({}) as any,
apply({ dependencies }) {
const dep = dependencies?.[depRef] as Leaf;
if (!dep) throw new Error('missing dep');
return new Leaf({ value: dep.data.value + 100 });
},
update({ b, dependencies }) {
const dep = dependencies?.[depRef] as Leaf;
if (!dep) throw new Error('missing dep');
(b.data as { value: number }).value = dep.data.value + 100;
return StateTransformer.UpdateResult.Updated;
}
});
}
describe('State dependencies - linking', () => {
it('explicit dependsOn establishes an edge and passes the dep object to apply', async () => {
const state = newState();
const A = constLeaf();
const B = deriveFromDep('leaf-a');
const builder = state.build();
builder.toRoot<Root>().apply(A as any, { value: 7 }, { ref: 'leaf-a' });
builder.toRoot<Root>().apply(B as any, {}, { ref: 'leaf-b', dependsOn: ['leaf-a'] });
await state.runTask(state.updateTree(builder));
const b = state.cells.get('leaf-b')!;
expect(b.dependencies.dependsOn.map(c => c.transform.ref)).toEqual(['leaf-a']);
expect((b.obj as Leaf).data.value).toBe(107);
const a = state.cells.get('leaf-a')!;
expect(a.dependencies.dependentBy.map(c => c.transform.ref)).toEqual(['leaf-b']);
});
it('re-evaluates dependents when the source updates', async () => {
const state = newState();
const A = constLeaf();
const B = deriveFromDep('leaf-a');
const builder1 = state.build();
builder1.toRoot<Root>().apply(A as any, { value: 1 }, { ref: 'leaf-a' });
builder1.toRoot<Root>().apply(B as any, {}, { ref: 'leaf-b', dependsOn: ['leaf-a'] });
await state.runTask(state.updateTree(builder1));
expect((state.cells.get('leaf-b')!.obj as Leaf).data.value).toBe(101);
const builder2 = state.build();
builder2.to('leaf-a').update({ value: 5 });
await state.runTask(state.updateTree(builder2));
expect((state.cells.get('leaf-b')!.obj as Leaf).data.value).toBe(105);
});
it('throws when an explicit dependsOn references a non-existent transform', async () => {
const state = newState();
const B = deriveFromDep('missing-ref');
const builder = state.build();
builder.toRoot<Root>().apply(B as any, {}, { ref: 'leaf-b', dependsOn: ['missing-ref'] });
await expect(state.runTask(state.updateTree(builder))).rejects.toThrow(/non-existent transform/);
});
it('honors getDependencies(params) and relinks when params change', async () => {
const state = newState();
const A = constLeaf();
const A2 = constLeaf();
const PickViaParams = StateTransformer.create<Root, Leaf, { which: string }>(NS, {
name: uniq('pick-via-params'),
from: [Root],
to: [Leaf],
display: { name: 'Pick' },
params: () => ({ which: PD.Text('leaf-a') }) as any,
getDependencies(params) { return params.which ? [params.which as StateTransform.Ref] : []; },
apply({ params, dependencies }) {
const dep = dependencies?.[params.which] as Leaf;
return new Leaf({ value: dep ? dep.data.value : -1 });
},
update({ b, newParams, dependencies }) {
const dep = dependencies?.[newParams.which] as Leaf;
(b.data as { value: number }).value = dep ? dep.data.value : -1;
return StateTransformer.UpdateResult.Updated;
}
});
const builder = state.build();
builder.toRoot<Root>().apply(A as any, { value: 11 }, { ref: 'leaf-a' });
builder.toRoot<Root>().apply(A2 as any, { value: 22 }, { ref: 'leaf-a2' });
builder.toRoot<Root>().apply(PickViaParams as any, { which: 'leaf-a' }, { ref: 'pick' });
await state.runTask(state.updateTree(builder));
const pick = state.cells.get('pick')!;
expect(pick.dependencies.dependsOn.map(c => c.transform.ref)).toEqual(['leaf-a']);
expect((pick.obj as Leaf).data.value).toBe(11);
const update = state.build();
update.to('pick').update({ which: 'leaf-a2' });
await state.runTask(state.updateTree(update));
const pick2 = state.cells.get('pick')!;
expect(pick2.dependencies.dependsOn.map(c => c.transform.ref)).toEqual(['leaf-a2']);
expect((pick2.obj as Leaf).data.value).toBe(22);
// Old source no longer reverse-linked.
expect(state.cells.get('leaf-a')!.dependencies.dependentBy.length).toBe(0);
expect(state.cells.get('leaf-a2')!.dependencies.dependentBy.map(c => c.transform.ref)).toEqual(['pick']);
});
it('auto-collects refs from PD.ValueRef parameter values', async () => {
const state = newState();
const A = constLeaf();
const ViaValueRef = StateTransformer.create<Root, Leaf, { target: { ref: string, getValue: () => Leaf } }>(NS, {
name: uniq('via-value-ref'),
from: [Root],
to: [Leaf],
display: { name: 'Via ValueRef' },
params: () => ({
target: PD.ValueRef<Leaf>(() => [], (ref, getData) => getData(ref))
}) as any,
apply({ params, dependencies }) {
const dep = dependencies?.[params.target.ref] as Leaf;
return new Leaf({ value: dep ? dep.data.value * 2 : -1 });
}
});
const builder = state.build();
builder.toRoot<Root>().apply(A as any, { value: 9 }, { ref: 'leaf-a' });
builder.toRoot<Root>().apply(ViaValueRef as any, {
target: { ref: 'leaf-a', getValue: () => null as any }
}, { ref: 'vr' });
await state.runTask(state.updateTree(builder));
const vr = state.cells.get('vr')!;
expect(vr.dependencies.dependsOn.map(c => c.transform.ref)).toEqual(['leaf-a']);
expect((vr.obj as Leaf).data.value).toBe(18);
});
it('falls back to a structural scan when the schema is unavailable', async () => {
const state = newState();
const A = constLeaf();
// No `def.params` - params normalization will drop unknown fields at
// evaluation time, but link-time collection (via the structural
// fallback) still happens against the original transform.params.
const Structural = StateTransformer.create<Root, Leaf, any>(NS, {
name: uniq('structural'),
from: [Root],
to: [Leaf],
display: { name: 'Structural' },
apply({ dependencies }) {
const ref = dependencies ? Object.keys(dependencies)[0] : undefined;
const dep = ref ? dependencies![ref] as Leaf : undefined;
return new Leaf({ value: dep ? dep.data.value + 1000 : -1 });
}
});
const builder = state.build();
builder.toRoot<Root>().apply(A as any, { value: 3 }, { ref: 'leaf-a' });
builder.toRoot<Root>().apply(Structural as any, {
link: { ref: 'leaf-a', getValue: () => null }
}, { ref: 'struct' });
await state.runTask(state.updateTree(builder));
const s = state.cells.get('struct')!;
expect(s.dependencies.dependsOn.map(c => c.transform.ref)).toEqual(['leaf-a']);
expect((s.obj as Leaf).data.value).toBe(1003);
});
it('filters out self and root refs from getDependencies', async () => {
const state = newState();
const SelfRef = StateTransformer.create<Root, Leaf, {}>(NS, {
name: uniq('self-ref'),
from: [Root],
to: [Leaf],
display: { name: 'Self Ref' },
params: () => ({}) as any,
getDependencies() { return ['self', StateTransform.RootRef as any]; },
apply() { return new Leaf({ value: 42 }); }
});
const builder = state.build();
builder.toRoot<Root>().apply(SelfRef as any, {}, { ref: 'self' });
await state.runTask(state.updateTree(builder));
const cell = state.cells.get('self')!;
expect(cell.dependencies.dependsOn.length).toBe(0);
expect((cell.obj as Leaf).data.value).toBe(42);
});
});
describe('State dependencies - cycle detection', () => {
it('throws StateTreeCycleError for a direct A → B → A cycle', async () => {
const state = newState();
// Two transformers, each declaring a getDependencies pointing at the other.
const A = StateTransformer.create<Root, Leaf, {}>(NS, {
name: uniq('cycle-a'),
from: [Root],
to: [Leaf],
display: { name: 'Cycle A' },
params: () => ({}) as any,
getDependencies() { return ['cyc-b' as any]; },
apply() { return new Leaf({ value: 0 }); }
});
const B = StateTransformer.create<Root, Leaf, {}>(NS, {
name: uniq('cycle-b'),
from: [Root],
to: [Leaf],
display: { name: 'Cycle B' },
params: () => ({}) as any,
getDependencies() { return ['cyc-a' as any]; },
apply() { return new Leaf({ value: 0 }); }
});
const builder = state.build();
builder.toRoot<Root>().apply(A as any, {}, { ref: 'cyc-a' });
builder.toRoot<Root>().apply(B as any, {}, { ref: 'cyc-b' });
let caught: unknown;
try {
await state.runTask(state.updateTree(builder));
} catch (e) { caught = e; }
expect(caught).toBeInstanceOf(StateTreeCycleError);
const cycle = (caught as StateTreeCycleError).cycle;
expect(cycle[0]).toBe(cycle[cycle.length - 1]);
expect(cycle).toEqual(expect.arrayContaining(['cyc-a', 'cyc-b']));
});
});
describe('State dependencies - deferred resolution', () => {
/** Force evaluation order: place dependent subtree first under root so
* tree pre-order visits it before its dependency. */
it('resolves cross-subtree deps even when the dependent is scheduled first', async () => {
const state = newState();
const A = constLeaf();
const B = deriveFromDep('leaf-a');
const builder = state.build();
// B added FIRST - so its subtree comes before A's in tree pre-order.
builder.toRoot<Root>().apply(B as any, {}, { ref: 'leaf-b', dependsOn: ['leaf-a'] });
builder.toRoot<Root>().apply(A as any, { value: 4 }, { ref: 'leaf-a' });
await state.runTask(state.updateTree(builder));
expect((state.cells.get('leaf-a')!.obj as Leaf).data.value).toBe(4);
expect((state.cells.get('leaf-b')!.obj as Leaf).data.value).toBe(104);
});
it('propagates a clear error when a dep has errored and cannot resolve', async () => {
const state = newState();
const Boom = StateTransformer.create<Root, Leaf, {}>(NS, {
name: uniq('boom'),
from: [Root],
to: [Leaf],
display: { name: 'Boom' },
params: () => ({}) as any,
apply() { throw new Error('intentional'); }
});
const B = deriveFromDep('boom');
const builder = state.build();
builder.toRoot<Root>().apply(Boom as any, {}, { ref: 'boom' });
builder.toRoot<Root>().apply(B as any, {}, { ref: 'leaf-b', dependsOn: ['boom'] });
// The state surfaces transform errors via console.error; suppress the noise.
const err = jest.spyOn(console, 'error').mockImplementation(() => {});
try {
await state.runTask(state.updateTree(builder));
} finally {
err.mockRestore();
}
const b: StateObjectCell = state.cells.get('leaf-b')!;
expect(b.status).toBe('error');
expect(b.errorText).toMatch(/Unresolved dependency|missing dep|intentional/);
});
});

View File

@@ -0,0 +1,126 @@
/**
* Copyright (c) 2026 mol* contributors, licensed under MIT, See LICENSE file for more info.
*/
import { State, StateObject, StateTransformer } from '../../mol-state';
import { Task } from '../../mol-task';
interface TypeInfo { name: string; typeClass: 'Root' | 'Data' }
const Create = StateObject.factory<TypeInfo>();
class Root extends Create({ name: 'Root', typeClass: 'Root' }) { }
class Leaf extends Create<{ value: number }>({ name: 'Leaf', typeClass: 'Data' }) { }
const NS = 'state-dispose-spec';
let counter = 0;
function leafTransformer(spy: () => void) {
return StateTransformer.create<Root, Leaf, { value: number }>(NS, {
name: `create-leaf-${counter++}`,
from: [Root],
to: [Leaf],
display: { name: 'Create Leaf' },
params: () => ({} as any),
apply({ params }) { return new Leaf({ value: params.value }); },
dispose() { spy(); }
});
}
function chainedTransformer(spy: () => void) {
return StateTransformer.create<Leaf, Leaf, {}>(NS, {
name: `chained-leaf-${counter++}`,
from: [Leaf],
to: [Leaf],
display: { name: 'Chained Leaf' },
apply({ a }) { return new Leaf({ value: a.data.value + 1 }); },
dispose() { spy(); }
});
}
function newState() {
return State.create(new Root({}), { runTask: <T>(t: Task<T>) => t.run() });
}
describe('State.dispose', () => {
it('calls transformer.dispose for every live cell', async () => {
const leafSpy = jest.fn();
const chainSpy = jest.fn();
const A = leafTransformer(leafSpy);
const B = chainedTransformer(chainSpy);
const state = newState();
const builder = state.build();
builder.toRoot<Root>().apply(A as any, { value: 1 }).apply(B as any, {});
await state.runTask(state.updateTree(builder));
// root + 2 transformer outputs.
expect(state.cells.size).toBe(3);
state.dispose();
expect(leafSpy).toHaveBeenCalledTimes(1);
expect(chainSpy).toHaveBeenCalledTimes(1);
});
it('disposes all sibling subtrees', async () => {
const spyA = jest.fn();
const spyB = jest.fn();
const A = leafTransformer(spyA);
const B = leafTransformer(spyB);
const state = newState();
const builder = state.build();
builder.toRoot<Root>().apply(A as any, { value: 1 });
builder.toRoot<Root>().apply(B as any, { value: 2 });
await state.runTask(state.updateTree(builder));
state.dispose();
expect(spyA).toHaveBeenCalledTimes(1);
expect(spyB).toHaveBeenCalledTimes(1);
});
it('does not throw when a transformer dispose throws', async () => {
const goodSpy = jest.fn();
const Throwing = StateTransformer.create<Root, Leaf, { value: number }>(NS, {
name: `throwing-leaf-${counter++}`,
from: [Root],
to: [Leaf],
display: { name: 'Throwing Leaf' },
apply({ params }) { return new Leaf({ value: params.value }); },
dispose() { throw new Error('boom'); }
});
const Good = leafTransformer(goodSpy);
const state = newState();
const builder = state.build();
builder.toRoot<Root>().apply(Throwing as any, { value: 1 });
builder.toRoot<Root>().apply(Good as any, { value: 2 });
await state.runTask(state.updateTree(builder));
const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
try {
expect(() => state.dispose()).not.toThrow();
} finally {
warn.mockRestore();
}
expect(goodSpy).toHaveBeenCalledTimes(1);
});
it('is a no-op for transformers without a dispose definition', async () => {
const NoDispose = StateTransformer.create<Root, Leaf, { value: number }>(NS, {
name: `no-dispose-${counter++}`,
from: [Root],
to: [Leaf],
display: { name: 'No-dispose Leaf' },
apply({ params }) { return new Leaf({ value: params.value }); }
});
const state = newState();
const builder = state.build();
builder.toRoot<Root>().apply(NoDispose as any, { value: 1 });
await state.runTask(state.updateTree(builder));
expect(() => state.dispose()).not.toThrow();
});
});

View File

@@ -1,7 +1,8 @@
/**
* Copyright (c) 2018-2025 mol* contributors, licensed under MIT, See LICENSE file for more info.
* Copyright (c) 2018-2026 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
* @author Alexander Rose <alexander.rose@weirdbyte.de>
*/
import { StateObject, StateObjectCell, StateObjectSelector } from './object';
@@ -24,7 +25,22 @@ import { arraySetAdd, arraySetRemove } from '../mol-util/array';
import { UniqueArray } from '../mol-data/generic/unique-array';
import { assignIfUndefined } from '../mol-util/object';
export { State };
export { State, StateTreeCycleError };
/**
* Thrown when a cycle is detected in the state-tree dependency graph
* (the cross-edges defined by `transform.dependsOn` and effective
* dependencies derived from params). `cycle` holds the closed path,
* e.g. `['A', 'B', 'A']`.
*/
class StateTreeCycleError extends Error {
readonly cycle: StateTransform.Ref[];
constructor(cycle: StateTransform.Ref[]) {
super(`Cyclic state-tree dependency detected: ${cycle.join(' -> ')}`);
this.name = 'StateTreeCycleError';
this.cycle = cycle;
}
}
class State {
private _tree: TransientTree;
@@ -159,6 +175,23 @@ class State {
}
dispose() {
// Dispose every still-live cell so transformer dispose callbacks
// (e.g. WebGL/GL buffer cleanup) actually run. Without this,
// calling dispose() on a State that still has cells leaks any
// resources held by transformer dispose callbacks because they
// would only fire on per-cell deletion (see updateNode/findDeletes).
const refs: StateTransform.Ref[] = [];
StateTree.doPostOrder(this._tree, this._tree.root, { refs }, (n, _, s) => { s.refs.push(n.ref); });
for (let i = refs.length - 1; i >= 0; i--) {
const cell = (this.cells as Map<StateTransform.Ref, StateObjectCell>).get(refs[i]);
if (!cell) continue;
try {
dispose(cell.transform, cell.obj, cell.transform.params, cell.cache, this.globalContext);
} catch (e) {
console.warn('Error in transformer dispose during State.dispose', e);
}
}
this.ev.dispose();
this.actions.dispose();
}
@@ -477,6 +510,21 @@ interface UpdateContext {
wasAborted: boolean,
newCurrent?: Ref,
/**
* Refs that are scheduled to be (re-)evaluated in this update pass:
* the union of every `roots[i]` and its descendants. Used to distinguish
* "dep not yet produced this pass" (defer + retry) from "dep can never
* be produced this pass" (throw).
*/
scheduled?: Set<Ref>,
/**
* Subtree roots that were skipped because at least one of their
* dependencies hadn't been evaluated yet. Drained after the main loop
* makes a fixpoint pass.
*/
deferred?: Ref[],
getCellData: (ref: string) => any
}
@@ -556,11 +604,45 @@ async function update(ctx: UpdateContext) {
// Set status of cells that will be updated to 'pending'.
initCellStatus(ctx, roots);
// Build the set of refs that will be (re-)evaluated this pass so that
// `updateSubtree` can distinguish "dep not produced yet" (defer + retry)
// from "dep can never be produced" (throw via resolveDependencies).
ctx.scheduled = collectScheduled(ctx, roots);
// Sequentially update all the subtrees.
for (const root of roots) {
await updateSubtree(ctx, root);
}
// Drain the deferred queue: nodes whose `dependsOn` cells weren't yet
// evaluated when first visited get retried until either all succeed or
// a full pass makes no forward progress (true deadlock / unresolvable).
if (ctx.deferred && ctx.deferred.length > 0) {
while (ctx.deferred.length > 0) {
const pending = ctx.deferred;
ctx.deferred = [];
let progress = false;
for (const ref of pending) {
const before = ctx.deferred.length;
await updateSubtree(ctx, ref);
// Forward progress = this attempt did not re-defer the same ref.
const reDeferred = ctx.deferred.length > before
&& ctx.deferred[ctx.deferred.length - 1] === ref;
if (!reDeferred) progress = true;
}
if (!progress) {
const stuck = ctx.deferred.map(r => {
const c = ctx.cells.get(r);
if (!c) return r;
const blockers = pendingBlockers(ctx, c);
return `${r} (waiting on: ${blockers.length ? blockers.join(', ') : 'unknown'})`;
});
ctx.deferred = [];
throw new Error(`Unresolved dependency: ${stuck.join('; ')}`);
}
}
}
// Sync cell states
if (!ctx.editInfo) {
syncNewStates(ctx);
@@ -646,7 +728,13 @@ function setCellStatus(ctx: UpdateContext, ref: Ref, status: StateObjectCell.Sta
}
function initCellStatusVisitor(t: StateTransform, _: any, ctx: UpdateContext) {
ctx.cells.get(t.ref)!.transform = t;
const cell = ctx.cells.get(t.ref)!;
cell.transform = t;
if (relinkCells(cell, ctx)) {
// Edges changed (e.g. param update added/removed dependencies) —
// re-verify there is no cycle.
checkDependenciesCycle(cell);
}
setCellStatus(ctx, t.ref, 'pending');
}
@@ -690,9 +778,10 @@ function addCellsVisitor(transform: StateTransform, _: any, { ctx, added, visite
// type LinkCellsCtx = { ctx: UpdateContext, visited: Set<Ref>, dependent: UniqueArray<Ref, StateObjectCell> }
function linkCells(target: StateObjectCell, ctx: UpdateContext) {
if (!target.transform.dependsOn) return;
const effective = StateTransform.getEffectiveDependsOn(target.transform);
if (effective.length === 0) return;
for (const ref of target.transform.dependsOn) {
for (const ref of effective) {
const t = ctx.tree.transforms.get(ref);
if (!t) {
throw new Error(`Cannot depend on a non-existent transform.`);
@@ -704,6 +793,103 @@ function linkCells(target: StateObjectCell, ctx: UpdateContext) {
}
}
/**
* Diff the current outgoing dependency edges of `target` against the effective
* set derived from its (possibly updated) transform. Unlinks stale edges and
* links new ones so the dependency graph reflects param changes. Idempotent
* when nothing has changed. Returns `true` if any edge was added or removed.
*/
function relinkCells(target: StateObjectCell, ctx: UpdateContext): boolean {
const effective = StateTransform.getEffectiveDependsOn(target.transform);
const current = target.dependencies.dependsOn;
// Fast path: same number and all current refs are still in effective.
if (current.length === effective.length) {
let same = true;
for (const c of current) {
if (effective.indexOf(c.transform.ref) < 0) { same = false; break; }
}
if (same) return false;
}
const desired = new Set(effective);
let changed = false;
// Remove stale outgoing edges.
for (let i = current.length - 1; i >= 0; i--) {
const dep = current[i];
if (!desired.has(dep.transform.ref)) {
current.splice(i, 1);
arraySetRemove(dep.dependencies.dependentBy, target);
changed = true;
}
}
// Add new outgoing edges.
const have = new Set(current.map(c => c.transform.ref));
for (const ref of effective) {
if (have.has(ref)) continue;
const t = ctx.tree.transforms.get(ref);
if (!t) {
throw new Error(`Cannot depend on a non-existent transform.`);
}
const cell = ctx.cells.get(ref)!;
arraySetAdd(target.dependencies.dependsOn, cell);
arraySetAdd(cell.dependencies.dependentBy, target);
changed = true;
}
return changed;
}
/**
* Detect a cycle in the `dependsOn` graph reachable from `start`.
*
* Iterative DFS, returning the closed cycle path (first occurrence of the
* repeated ref appended at the end) or `undefined` if none. Operates on the
* already-linked cell graph; safe to call after `linkCells` / `relinkCells`.
*/
function detectDependenciesCycle(start: StateObjectCell): StateTransform.Ref[] | undefined {
if (start.dependencies.dependsOn.length === 0) return void 0;
const stack: { cell: StateObjectCell, idx: number }[] = [{ cell: start, idx: 0 }];
const onPath = new Set<StateTransform.Ref>([start.transform.ref]);
const fully = new Set<StateTransform.Ref>();
while (stack.length > 0) {
const top = stack[stack.length - 1];
const deps = top.cell.dependencies.dependsOn;
if (top.idx >= deps.length) {
onPath.delete(top.cell.transform.ref);
fully.add(top.cell.transform.ref);
stack.pop();
continue;
}
const next = deps[top.idx++];
const ref = next.transform.ref;
if (fully.has(ref)) continue;
if (onPath.has(ref)) {
const path: StateTransform.Ref[] = [];
let started = false;
for (const s of stack) {
if (started || s.cell.transform.ref === ref) {
started = true;
path.push(s.cell.transform.ref);
}
}
path.push(ref);
return path;
}
onPath.add(ref);
stack.push({ cell: next, idx: 0 });
}
return void 0;
}
function checkDependenciesCycle(cell: StateObjectCell) {
const cycle = detectDependenciesCycle(cell);
if (cycle) throw new StateTreeCycleError(cycle);
}
function initCells(ctx: UpdateContext, roots: Ref[]) {
const initCtx: InitCellsCtx = { ctx, visited: new Set(), added: [] };
@@ -717,6 +903,12 @@ function initCells(ctx: UpdateContext, roots: Ref[]) {
linkCells(cell, ctx);
}
// Cycle detection over the dependency cross-edges of newly added cells.
// Parent/child is already a tree, so cycles can only enter via dependsOn.
for (const cell of initCtx.added) {
checkDependenciesCycle(cell);
}
let dependent: UniqueArray<Ref, StateObjectCell>;
// Find dependent cells
@@ -817,7 +1009,54 @@ type UpdateNodeResult =
const ParentNullErrorText = 'Parent is null';
function collectScheduledVisitor(t: StateTransform, _: any, s: Set<Ref>) {
s.add(t.ref);
}
function collectScheduled(ctx: UpdateContext, roots: Ref[]): Set<Ref> {
const out = new Set<Ref>();
for (const root of roots) {
const node = ctx.tree.transforms.get(root);
if (!node) continue;
StateTree.doPreOrder(ctx.tree, node, out, collectScheduledVisitor);
}
return out;
}
/**
* Refs that `cell` depends on which are scheduled for evaluation in this
* pass but haven't produced an object yet (and aren't in an error state).
* An empty result means deps are either ready, in error, or out-of-scope —
* in any of those cases the cell should proceed (and may throw at
* `resolveDependencies` time if the dep is genuinely missing).
*/
function pendingBlockers(ctx: UpdateContext, cell: StateObjectCell): Ref[] {
const blockers: Ref[] = [];
const scheduled = ctx.scheduled;
if (!scheduled) return blockers;
for (const dep of cell.dependencies.dependsOn) {
if (dep.obj) continue;
if (dep.status === 'error') continue;
if (!scheduled.has(dep.transform.ref)) continue;
blockers.push(dep.transform.ref);
}
return blockers;
}
async function updateSubtree(ctx: UpdateContext, root: Ref) {
const cell = ctx.cells.get(root);
if (cell && cell.dependencies.dependsOn.length > 0) {
const blockers = pendingBlockers(ctx, cell);
if (blockers.length > 0) {
// A dependency hasn't been produced yet this pass — defer this
// subtree and retry after other roots have run. Children will be
// visited when the deferred re-attempt succeeds.
if (!ctx.deferred) ctx.deferred = [];
ctx.deferred.push(root);
return;
}
}
setCellStatus(ctx, root, 'processing');
let isNull = false;

View File

@@ -1,12 +1,15 @@
/**
* Copyright (c) 2018-2025 mol* contributors, licensed under MIT, See LICENSE file for more info.
* Copyright (c) 2018-2026 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
* @author Alexander Rose <alexander.rose@weirdbyte.de>
*/
import { StateTransformer } from './transformer';
import { UUID } from '../mol-util';
import { hashMurmur128o } from '../mol-data/util/hash-functions';
import { ParamDefinition as PD } from '../mol-util/param-definition';
import { arraySetAdd, arraySetRemove } from '../mol-util/array';
export { Transform as StateTransform };
@@ -170,6 +173,97 @@ namespace Transform {
return true;
}
/**
* Returns the default param schema for the transform's transformer, caching
* the result on the transform instance. Returns `undefined` if the transformer
* has no `params` definition or if calling it throws.
*/
export function tryGetDefaultParamDefinition(t: Transform): PD.Params | undefined {
const any = t as any;
if (any._defaultSchemaSet) return any._defaultSchema;
any._defaultSchemaSet = true;
try {
const def = t.transformer.definition;
if (def.params) {
any._defaultSchema = def.params(undefined as any, undefined) as PD.Params;
}
} catch {
// Schema could not be obtained.
}
return any._defaultSchema;
}
/**
* Compute the effective set of sibling-like dependencies for a transform.
*
* Combines (in order, de-duplicated):
* 1. Explicit `t.dependsOn` (back-compat / non-param refs).
* 2. Refs from `transformer.definition.getDependencies(params)` if defined.
* 3. Refs collected from `PD.ValueRef` / `PD.DataRef` parameter values.
*
* Self-references and the root ref are filtered out. If the param schema
* can't be obtained, auto-derivation falls back to a structural scan of
* parameter values for `{ ref, getValue }` shaped objects.
*/
export function getEffectiveDependsOn(t: Transform): Ref[] {
const out: string[] = [];
if (t.dependsOn) {
for (const r of t.dependsOn) {
arraySetAdd(out, r);
}
}
const def = t.transformer.definition;
const params = t.params as any;
if (def.getDependencies && params) {
try {
const extra = def.getDependencies(params);
if (extra) {
for (const r of extra) {
arraySetAdd(out, r);
}
}
} catch {
// Keep reconciliation robust if a user hook misbehaves.
}
}
if (params) {
const schema = tryGetDefaultParamDefinition(t);
if (schema) {
PD.collectRefs(schema, params, out);
} else {
collectStructuralRefs(params, out);
}
}
// Filter out self-references and the root ref.
arraySetRemove(out, t.ref);
arraySetRemove(out, RootRef);
return out;
}
function collectStructuralRefs(value: any, out: string[], depth = 0): string[] {
if (!value || typeof value !== 'object' || depth > 6) return out;
if (Array.isArray(value)) {
for (const v of value) {
collectStructuralRefs(v, out, depth + 1);
}
return out;
}
const ref = (value as any).ref;
if (typeof ref === 'string' && typeof (value as any).getValue === 'function') {
arraySetAdd(out, ref);
return out;
}
for (const k of Object.keys(value)) {
collectStructuralRefs(value[k], out, depth + 1);
}
return out;
}
const _emptyParams = {};
/** Updates the version of the transform to be computed as hash of the parameters */
export function setParamsHashVersion(t: Transform) {

View File

@@ -1,7 +1,8 @@
/**
* Copyright (c) 2018-2025 mol* contributors, licensed under MIT, See LICENSE file for more info.
* Copyright (c) 2018-2026 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
* @author Alexander Rose <alexander.rose@weirdbyte.de>
*/
import { Task } from '../mol-task';
@@ -118,6 +119,16 @@ namespace Transformer {
/** Custom conversion to and from JSON */
readonly customSerialization?: { toJSON(params: P, obj?: B): any, fromJSON(data: any): P }
/**
* Derive sibling-like state-tree dependencies (other cells' refs) from the
* current parameter values. Returned refs are merged with explicit
* `dependsOn` and any refs auto-collected from `PD.ValueRef` / `PD.DataRef`
* parameters to form the effective dependency set used by reconciliation.
*
* Return an empty array or undefined to opt out.
*/
getDependencies?(params: P): StateTransform.Ref[] | undefined
}
export interface Definition<A extends StateObject = StateObject, B extends StateObject = StateObject, P extends {} = {}> extends DefinitionBase<A, B, P> {

View File

@@ -1,5 +1,5 @@
/**
* Copyright (c) 2018-2024 mol* contributors, licensed under MIT, See LICENSE file for more info.
* Copyright (c) 2018-2026 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @author David Sehnal <david.sehnal@gmail.com>
@@ -18,6 +18,7 @@ import { getColorListFromName, ColorListName } from './color/lists';
import { Asset } from './assets';
import { ColorListEntry } from './color/color';
import { EPSILON } from '../mol-math/linear-algebra/3d/common';
import { arraySetAdd } from './array';
export namespace ParamDefinition {
export interface Info {
@@ -295,10 +296,13 @@ export namespace ParamDefinition {
type: 'object-list',
element: Params,
ctor(): T,
getLabel(t: T): string
getLabel(t: T): string,
presets?: Select<T[]>['options']
}
export function ObjectList<T>(element: For<T>, getLabel: (e: T) => string, info?: Info & { defaultValue?: T[], ctor?: () => T }): ObjectList<Normalize<T>> {
return setInfo<ObjectList<Normalize<T>>>({ type: 'object-list', element: element as any as Params, getLabel, ctor: _defaultObjectListCtor, defaultValue: (info?.defaultValue) || [] }, info);
export function ObjectList<T>(element: For<T>, getLabel: (e: T) => string, info?: Info & { defaultValue?: T[], ctor?: () => T, presets?: Select<T[]>['options'] }): ObjectList<Normalize<T>> {
const ret = setInfo<ObjectList<Normalize<T>>>({ type: 'object-list', element: element as any as Params, getLabel, ctor: _defaultObjectListCtor, defaultValue: (info?.defaultValue) || [] }, info);
if (info?.presets) ret.presets = info.presets as any;
return ret;
}
function _defaultObjectListCtor(this: ObjectList) { return getDefaultValues(this.element) as any; }
@@ -442,6 +446,47 @@ export namespace ParamDefinition {
}
}
function collectRefValue(p: Any, value: any, out: string[]): string[] {
if (value === undefined || value === null) return out;
if (p.type === 'value-ref' || p.type === 'data-ref') {
const v = value as ValueRef['defaultValue'];
if (v && typeof v.ref === 'string' && v.ref) {
arraySetAdd(out, v.ref);
}
} else if (p.type === 'group') {
collectRefsImpl(p.params, value, out);
} else if (p.type === 'mapped') {
const v = value as NamedParams;
if (!v) return out;
const param = p.map(v.name);
collectRefValue(param, v.params, out);
} else if (p.type === 'object-list') {
if (!hasValueRef(p.element)) return out;
for (const e of value) {
collectRefsImpl(p.element, e, out);
}
}
return out;
}
function collectRefsImpl(params: Params, values: any, out: string[]): string[] {
for (const n of Object.keys(params)) {
collectRefValue(params[n], values?.[n], out);
}
return out;
}
/**
* Collect all non-empty `ref` strings of `value-ref` and `data-ref` parameter
* values into a set. Used by `mol-state` to derive transform dependencies from
* parameter values.
*/
export function collectRefs(params: Params, values: any, out: string[]): string[] {
if (!params || !values) return out;
return collectRefsImpl(params, values, out);
}
export function setDefaultValues<T extends Params>(params: T, defaultValues: Values<T>) {
for (const k of Object.keys(params)) {
if (params[k].isOptional) continue;

View File

@@ -1,3 +1,7 @@
# 0.9.13
* /surroundingLigands: honor `omit_water=true|false` for REST GET requests (boolean parser previously coerced both to `false`)
* /surroundingLigands: stop leaking the asymmetric unit's water chain into the result when `omit_water=true` (water residues pulled in via struct_conn covale/metalc edges no longer match every other water in the chain)
# 0.9.12
* add `health-check` endpoint + `healthCheckPath` config prop to report service health

View File

@@ -295,7 +295,7 @@ function _normalizeQueryParams(params: { [p: string]: string }, paramList: Query
case QueryParamType.String: el = value; break;
case QueryParamType.Integer: el = parseInt(value); break;
case QueryParamType.Float: el = parseFloat(value); break;
case QueryParamType.Boolean: el = Boolean(+value); break;
case QueryParamType.Boolean: el = isTrue(value); break;
}
if (p.validation) p.validation(el);

View File

@@ -4,4 +4,4 @@
* @author David Sehnal <david.sehnal@gmail.com>
*/
export const VERSION = '0.9.12';
export const VERSION = '0.9.13';