Skip to content

NF: refactor webgl lighting - #679

Merged
mvdoc merged 4 commits into
mainfrom
enh/topleft-lighting-option
Aug 21, 2026
Merged

mvdoc merged 4 commits into
mainfrom
enh/topleft-lighting-option

Conversation

@mvdoc

@mvdoc mvdoc commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Splits the lighting change out of #310 (which has been sitting since 2019 and no longer merges cleanly), and makes it opt-in.

What it does

Rationalize the lighting system. Now lighting options are controlled through a new "lighting" submenu under the surface GUI. This menu contains three options: topleft_lighting, uniform_illumination (moved here), and specularity (moved here):

  • topleft_lighting fades between two light setups: the standard VTK-inspired 3-light setup (at zero) and a single light from above and to the left of the camera (at one), following the top-left lighting convention used for shaded-relief topographic maps. This makes sulci read as valleys and gyri as ridges, which is what makes bumpy flatmaps legible — see @alexhuth's before/after screenshots in bumpy flatmap fixes #310. There is a switch for this in the config file, but it should probably be ignored and removed.
  • uniform_illumination fades between the standard lighting model (at zero) and uniform emissive shading for the surface (at one).
  • specularity smoothly adjusts the amount of specular reflection. There is a switch in the config that sets the default specularity to on or off.

Each of these controls will automatically change as the surface morphs into its flattened mode, depending on whether bumpy_flatmap is turned on or not.

If bumpy_flatmap is turned off:

  • topleft_lighting will always stay off
  • uniform_illumination will go to 1.0 as the surface flattens, and then back to 0.0 as it folds up again
  • specularity will go to 0.0 as the surface flattens, then back to its default value (0 or 1) as it folds up

If bumpy_flatmap is turned on:

  • topleft_lighting will go to 1.0 as the surface flattens (giving nice hillshading), and back to 0.0 as it folds up
  • uniform_illumination will always stay at 0.0
  • specularity will always stay at the default value

@mvdoc mvdoc mentioned this pull request Aug 20, 2026
mvdoc and others added 2 commits August 21, 2026 14:56
Adds an opt-in single grazing light from the upper left, following the
top-left lighting convention used for shaded-relief topographic maps.
This makes sulci read as valleys and gyri as ridges, which is what makes
bumpy flatmaps legible.

#310 made this the unconditional default, but the lighting setup applies
to every view, not just flatmaps, while bumpy_flatmap itself defaults to
false -- and a single near-tangential light is noticeably dimmer than the
existing three-light setup. Putting it behind a config flag alongside
uniform_illumination keeps the default rendering untouched.

Default and missing-key paths produce the same three lights, positions
and intensities as before.

Split out of #310.

Co-Authored-By: alexhuth <alex.huth@gmail.com>
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@mvdoc
mvdoc force-pushed the enh/topleft-lighting-option branch from 5f4514f to 885b87a Compare August 21, 2026 21:56
@alexhuth alexhuth changed the title NF: add webgl_viewopts.topleft_lighting config option NF: refactor webgl lighting Aug 21, 2026
The bump displacement and the flatBumpNorms normal perturbation only ever
existed in Shaders.surface_pixel, so toggling bumpy_flatmap while showing a
Vertex dataview did nothing at all: no HASFLAT define, no flatheight
attribute, and vNormal left as the unperturbed surface normal, which is what
made the flatmap read as a flat sheet even though the geometry underneath it
had already been displaced.

Port the HASFLAT blocks from surface_pixel into surface_vertex verbatim, so
the two shaders now displace and shade the flatmap identically and the new
lighting controls behave the same way for volume and vertex data.

Note that the pick and depth shaders still use the old thickness-based
displacement and are unaware of the bump, so picking on a bumpy flatmap
tests against undisplaced geometry. That was already true for volume data
before this change and is left alone here.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@mvdoc
mvdoc merged commit 0fa99b3 into main Aug 21, 2026
13 checks passed
@mvdoc
mvdoc deleted the enh/topleft-lighting-option branch August 21, 2026 23:10
kroq-gar78 pushed a commit to kroq-gar78/pycortex that referenced this pull request Aug 25, 2026
The surface shaders sit right up against the 16 vertex attribute slots
WebGL guarantees, and gallantlab#679 added two more of them (flatheight and
flatBumpNorms) to the vertex data shader so that bumpy_flatmap would work
for Vertex dataviews. 2D vertex data needs four data attributes rather
than two, which pushed surface_vertex to 17: it still compiles, but it
fails to link with "Too many attributes", and three.js only reports that
on the browser console, so the viewer just draws a black screen. The same
overflow hits plain Vertex data as soon as equivolume sampling is on.

Rather than giving these values slots of their own, pack them into the
spare components of attributes that are already bound:

- the white matter and pial vertex areas, which only the equivolume depth
  sampling reads, move into auxdat.zw (auxdat.x is the medial wall mask
  and .y the curvature; z and w were left at zero by brainctm)
- the flatmap bump height moves into the fourth component of the bumped
  flatmap normals, so the two become a single vec4 flatbump attribute

Every shader variant now links: the worst case, 2D vertex data on a
subject with a flatmap, goes from 19 attributes to 16. Renders of the
paths that did work before -- volume data with equivolume sampling, and
the bumpy flatmap -- are pixel-identical to what they were.

Fixes gallantlabgh-714.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013wiUP7TLgDqSfnv4n9ySZj
kroq-gar78 added a commit to kroq-gar78/pycortex that referenced this pull request Aug 25, 2026
700 KiB of lossless WebP across two sets -- alpha_dataviews (alpha-
bearing data) and nan_dataviews (NaN standing in for missing data) --
each with all six public dataview classes rendered via cortex.quickshow
and cortex.export.plot_panels.

Generated on main at 5af26a8, matching the commit the previous code
commit already targets; the vertex-flatmap regression from gallantlab#679 is on
main only after that commit, so these renders predate and are
unaffected by it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
kroq-gar78 added a commit to kroq-gar78/pycortex that referenced this pull request Aug 25, 2026
Twenty of the twenty-four images. Vertex2D's webgl render raises before either
reference is written, so its four files (quickflat + webgl, alpha + nan) are
still at the thresholded settings; the xfail comment records that whoever fixes
gallantlab#679 has to regenerate them in the same change.

CAVEAT, needs a decision: regenerating captured the *current* Vertex and
VertexRGB renders, which include the 2px-wider trim bounding box caused by gallantlab#679.
Their references therefore now encode that regression, the shape mismatch is
gone, and those four cases XPASS instead of xfailing. The gallantlab#679 shape symptom is
no longer detected -- exactly the "regenerating is how a real regression gets
silently blessed" failure mode this directory's README warns about. XPASS does
not fail a run, so it will not announce itself.

Either their references get reverted to the pre-gallantlab#679 renders (keeping the
regression visible, at the cost of them being the only images on the old
curvature settings), or the xfail comes off those four cases and the shape change
is accepted deliberately rather than by accident.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
kroq-gar78 added a commit to kroq-gar78/pycortex that referenced this pull request Aug 25, 2026
Rebasing onto the Vertex2D webgl fix makes all six dataviews render, so the
xfail marks come off and the four Vertex2D references -- which the crash had
prevented REGENERATE_REFERENCE_IMAGES from refreshing -- are regenerated onto
the un-thresholded curvature settings the other twenty already use.

Both changes have to land together: dropping the marks without the refreshed
Vertex2D references, or vice versa, leaves the suite red.

Worth recording why the 2px-wider bounding box was blessed rather than treated
as an outstanding regression. With the fix applied, Vertex2D's webgl render is
still 596px wide against its untouched 594px reference, so the wider trim is the
gallantlab#679 shader change's intended new geometry, not something the fix reverts. The
references were regenerated to match it deliberately.

12 passed, no xfails or xpasses; test_webgl_headless.py 43 passed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
kroq-gar78 added a commit to kroq-gar78/pycortex that referenced this pull request Aug 25, 2026
The existing mean and fraction>16 limits are both weak against a change that
moves a small number of pixels a long way, which is what a geometry or contour
shift looks like. The gallantlab#679 vertex-shader change is the worked example: it moved
2.8% of pixels by a median of 67/255, yet scored 1.574 against a mean limit of
2.0 -- it would have passed that criterion outright, and cleared the fraction
one by only 1.4x. The mean is diluted by the ~97% of pixels that did not move.

Adds two criteria that cover the gap, measured against simulated cosmetic drift
(a 596<->594 resample, +-1 LSB quantisation, gamma 1.02) versus gallantlab#679:

    metric            cosmetic      gallantlab#679    limit
    mean                 0.596     1.574    2.0     <- would have passed
    fraction > 16        0.48%     2.79%    2%
    fraction > 64        0.00%     1.460%   0.1%    <- new, 14.6x margin
    SSIM loss           0.00215   0.03933   0.01    <- new, 3.9x margin

All four are checked because they are complementary, not ranked. Gamma 1.25
scores 6.68 mean and 47.96% on fraction>16 but 0.00% on fraction>64; an R/B
channel swap scores 21.75 mean but 0.00000 SSIM loss, since SSIM is computed on
luminance and is blind to a channel permutation. SSIM adds sensitivity alongside
the others and cannot replace them.

SSIM is implemented on scipy (already a dependency) rather than scikit-image,
and calibrated against the shipped implementation -- scipy and OpenCV differ
slightly at the boundary. Verified end to end by swapping the pre-gallantlab#679 reference
back in: the check fails naming fraction>16, fraction>64 and SSIM, and correctly
omits the mean.

The cosmetic figures are simulated, not measured across a real Chromium or
matplotlib upgrade; a genuine bump changes anti-aliasing, which can move a few
pixels a long way and does show up in fraction>64. Both new limits sit well
above the simulated drift rather than at it, to leave room for that.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
kroq-gar78 added a commit to kroq-gar78/pycortex that referenced this pull request Aug 25, 2026
Evaluating the suite against six closed-issue fixes turned up a second worked
example. cb97627 ("unify NaN and alpha handling") changes four quickflat
volumetric renders via premultiplied-alpha thickness averaging, and at a
threshold of 64 every one scores 0.000% -- missed entirely, by all four criteria.

Its mean cannot be tightened into a catch: at 0.19 it sits *below* the simulated
cosmetic floor of 0.60, so a tighter mean produces false positives before it
produces a catch. A boundary-restricted metric was also tried and refuted --
restricting to the alpha edge band *reduces* the signal tenfold, because the
thickness-averaging change is interior, not at the silhouette.

Lowering the threshold does work. At 32 the cb97627 signal is 0.256% against
the 0.1% limit, while the worst simulated cosmetic drift is 0.0052%, 19x below
it. It also strengthens the gallantlab#679 catch, 1.46% -> 2.16%. Currently-passing tests
cannot be disturbed: their within-renderer difference is exactly zero.

The cost is headroom. At 64 no cosmetic perturbation registered at all; at 32 a
real Chromium or matplotlib bump has 19x of room rather than effectively
unlimited, and anti-aliasing changes are exactly what produce the mid-amplitude
pixels the lower threshold newly counts. Worth it to convert a demonstrated
blind spot into a 2.6x catch.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
kroq-gar78 added a commit to kroq-gar78/pycortex that referenced this pull request Aug 25, 2026
The NaN suite only ever put NaNs in the data channels. Alpha is a separate path:
it is not colour-mapped but used directly as a blend weight, so a NaN there
reaches the compositing arithmetic rather than a colormap lookup. Adds four
references for VolumeRGB and VertexRGB -- the only dataviews taking an explicit
alpha= -- with NaNs in the alpha map and clean colour channels.

Both renderers currently draw those elements fully transparent, the same outcome
as a NaN in the data, so this passes rather than xfails. The docstring records
that the behaviour is not settled: cb97627 ("unify NaN and alpha handling",
not in this branch's history) changes how the surviving RGB is blended without
changing the transparency, so expect these four to need regenerating if it lands.

Also corrects the README's provenance, which was actively wrong. It still claimed
the references were generated at 5af26a8; regenerating there and running against
the current tree fails the six vertex-based cases, so anyone following that
instruction would conclude something was broken. gallantlab#679 moved every pure-Vertex
flatmap's trim box from 594 to 596px and that is intended new geometry its
follow-up fix does not revert. The failures are a real content change, not a
resampling artifact: optimal affine alignment removes only 12% of the difference,
and it is concentrated in the interior rather than at the silhouette. All twelve
quickflat references are byte-identical at either commit; only the webgl ones
moved.

Brings the rest of the README up to date while there: three tests rather than
two, four within-renderer criteria rather than two, three reference directories
to regenerate rather than two.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
kroq-gar78 added a commit to kroq-gar78/pycortex that referenced this pull request Aug 26, 2026
Renders each of the six public dataview classes through both paths -- matplotlib
via cortex.quickshow, headless WebGL via cortex.export.plot_panels -- and checks
every render against a stored reference, plus the two renderers directly against
each other. Three suites: alpha-bearing data, NaNs in the data channels, and
NaNs in the alpha map. Split into its own file, out of test_webgl_headless.py,
where the original single test only asserted that a PNG had been written.

Four criteria per within-renderer check, kept because they are complementary
rather than redundant. Calibrated against simulated cosmetic drift (a 596<->594
resample, +-1 LSB quantisation, gamma 1.02) versus the real gallantlab#679 shader change:

    metric            cosmetic      gallantlab#679    limit
    mean                 0.596     1.574    2.0     <- would have passed
    fraction > 16        0.48%     2.79%    2%
    fraction > 32       0.0052%    2.16%    0.1%
    SSIM loss           0.00215   0.03933   0.01

The mean alone is blind to a change that moves a few pixels a long way, which is
what a geometry shift looks like; fraction>32 is blind to a broad low-amplitude
shift (gamma 1.25 scores 6.68 mean but 0.00% there); SSIM is computed on
luminance and so is blind to a channel permutation (an R/B swap scores 21.75
mean but 0.00000 SSIM loss). The 32 threshold rather than 64 comes from
cb97627, whose four changed renders score 0.000% at 64 and 0.256% at 32, and
whose mean of 0.19 sits *below* the cosmetic floor so no tighter mean could
catch it.

The two renderers do not share a pixel grid -- each computes its own trim --
so webgl is corrected onto quickflat's frame by a fixed affine before diffing.
Fitting a full homography returns a projective row of [~0, ~0, 1] and ~0
rotation, so despite webgl using a THREE.PerspectiveCamera there is no
perspective to undo: the flatmap is a planar surface viewed down its normal.
Only an anisotropic scale (0.9690, 0.9365) and a ~7px translation, which drops
curvature-only mean|diff| from 18.9 to 4.4. reference_images/README.md documents
how to re-derive it, and fit_cross_renderer_affine.py does so.

Curvature is rendered un-thresholded on both sides. A thresholded curvature puts
a hard binary edge at curvature=0 whose sub-pixel placement each rasteriser
resolves differently, making it maximally sensitive to residual misalignment;
smooth curvature resamples cleanly. Averaged over a brightness/contrast grid,
thresholded scored 8.50 against 3.66. This is not pycortex's default appearance,
so these references do not cover the default curvature path -- that is the trade
for the tighter floor. A factorial sweep of every other setting on both
renderers found nothing else worth changing: default lighting already ties the
best combination, trilinear beats nearest by ~1%, and depth/thick/layers span
0.38 across the whole grid.

The webgl settings ride along with the angle params as an (name, params) tuple.
plot_panels' viewer_params is forwarded to show(), whose **kwargs silently
swallows anything that is not a named argument, so viewer state passed that way
is a no-op -- a trap worth the comment it carries.

Non-flatmap views are covered in the same suite. Everything above is a flatmap,
which would otherwise leave the 3D views to test_webgl_headless.py's smoke
tests, and those assert the file is over 1000 bytes: enough to catch a render
that never happened, not one that came out wrong. So Volume and Vertex are also
rendered on the inflated and fiducial surfaces at lateral_pivot, both shader
paths, because the flatmap has turned out not to be representative of how they
behave -- both known webgl lighting bugs reproduce on flatmaps only, and gallantlab#679's
vertex-shader change touched only pure-Vertex flatmaps. A 3D view is a genuinely
different regime and was being extrapolated to rather than tested.

Those four are webgl-only, necessarily: cortex.quickshow renders flatmaps and
nothing else, so there is no counterpart to diff against and no cross-renderer
leg to run. Rather than thread a flag through _render_and_check_dataview they
get their own _render_and_check_webgl_only, which does the reference check and
stops. They also keep pycortex's default thresholded curvature, which costs
nothing without a second renderer to disagree with, and recovers coverage of the
default curvature path that the flatmap references give up.

They call save_3d_views directly rather than plot_panels, which composes the
screenshot into a matplotlib figure -- storing matplotlib's interpolation of the
render rather than the render, 507x169 upsampled to 620x232. That blunts
sensitivity and makes figsize, dpi, bbox_inches and the panel extent into
sources of failure that have nothing to do with webgl. The flatmap suites keep
plot_panels deliberately; switching them was tried and reverted, because
save_3d_views output is ~44% transparent while quickshow's figure is fully
opaque, so the cross-renderer check would compare a white background against an
empty one. The affine refit confirmed it, failing to converge with a
plain-resize baseline of 116 against the usual 18.8. Making it work needs
compositing both renderers onto a common background, refitting the affine and
recalibrating every threshold -- more than the extra layer costs.

The images are excluded from the wheel and kept in the source tarball; a missing
reference skips rather than fails, so an installed-wheel run degrades
gracefully, and so does the interval between this commit and the next.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
kroq-gar78 added a commit to kroq-gar78/pycortex that referenced this pull request Aug 26, 2026
Thirty-two lossless WebP images across four directories: alpha_dataviews and
nan_dataviews (six dataview classes x two renderers each), nan_alpha_dataviews
(the two RGB classes, the only ones taking an explicit alpha=), and
nonflat_views (Volume and Vertex, inflated and fiducial, at lateral_pivot,
webgl-only). Lossless WebP is bit-exact after decode and 59% the size of
optimised PNG; AVIF is smaller still but Pillow cannot write it losslessly, and
was measured at max|difference| 27-29, large enough to corrupt the comparison it
feeds.

The nonflat four are save_3d_views screenshots rather than plot_panels figures,
so 507x169 and 503x160 rather than 620x232 and 620x224, with the transparent
background intact instead of composited onto white. Verified to be genuine 3D
renders rather than accidental flatmaps -- the fiducial pair shows gyral relief,
the inflated pair is smooth.

Kept in a separate commit from the code that reads them, since they are opaque
binaries that no diff will ever explain.

Generated on this branch, and note they can *not* be reproduced at 5af26a8,
which the README named for a while. Regenerating there and testing against the
current tree fails the six vertex-based cases: gallantlab#679 moved every pure-Vertex
flatmap's trim box from 594 to 596px, and that is intended new geometry which
its follow-up fix does not revert. The failures are a genuine content change,
not a resampling artifact -- optimal affine alignment removes only 12% of the
difference, and it is concentrated in the interior rather than at the
silhouette. All quickflat references are byte-identical at either commit; only
the webgl ones moved.

Regenerate with REGENERATE_REFERENCE_IMAGES=1, and review the diff before
committing: regenerating is how a real regression gets silently blessed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@claude claude Bot mentioned this pull request Aug 31, 2026
kroq-gar78 pushed a commit to kroq-gar78/pycortex that referenced this pull request Sep 17, 2026
The surface shaders sit right up against the 16 vertex attribute slots
WebGL guarantees, and gallantlab#679 added two more of them (flatheight and
flatBumpNorms) to the vertex data shader so that bumpy_flatmap would work
for Vertex dataviews. 2D vertex data needs four data attributes rather
than two, which pushed surface_vertex to 17: it still compiles, but it
fails to link with "Too many attributes", and three.js only reports that
on the browser console, so the viewer just draws a black screen. The same
overflow hits plain Vertex data as soon as equivolume sampling is on.

Rather than giving these values slots of their own, pack them into the
spare components of attributes that are already bound:

- the white matter and pial vertex areas, which only the equivolume depth
  sampling reads, move into auxdat.zw (auxdat.x is the medial wall mask
  and .y the curvature; z and w were left at zero by brainctm)
- the flatmap bump height moves into the fourth component of the bumped
  flatmap normals, so the two become a single vec4 flatbump attribute

Every shader variant now links: the worst case, 2D vertex data on a
subject with a flatmap, goes from 19 attributes to 16. Renders of the
paths that did work before -- volume data with equivolume sampling, and
the bumpy flatmap -- are pixel-identical to what they were.

Fixes gallantlabgh-714.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013wiUP7TLgDqSfnv4n9ySZj
kroq-gar78 added a commit that referenced this pull request Sep 21, 2026
* TST: link every webgl shader variant

Nothing caught gh-714: the shader that failed to link compiled fine, no
javascript error was raised, and the screenshot was written -- it was
just empty.

test_webgl_shaders links every combination of options the viewer builds
surface, pick and depth shaders with, through THREE.ShaderMaterial (the
same path DataView.getShader() uses) in a real SwiftShader GL context.
Needs Chromium but no subject database, so it runs in a couple of
seconds and covers variants no render test puts on screen.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013wiUP7TLgDqSfnv4n9ySZj

* FIX: Vertex2D data rendered nothing at all in the webgl viewer

The surface shaders sit right up against the 16 vertex attribute slots
WebGL guarantees, and #679 added two more of them (flatheight and
flatBumpNorms) to the vertex data shader so that bumpy_flatmap would work
for Vertex dataviews. 2D vertex data needs four data attributes rather
than two, which pushed surface_vertex to 17: it still compiles, but it
fails to link with "Too many attributes", and three.js only reports that
on the browser console, so the viewer just draws a black screen. The same
overflow hits plain Vertex data as soon as equivolume sampling is on.

Rather than giving these values slots of their own, pack them into the
spare components of attributes that are already bound:

- the white matter and pial vertex areas, which only the equivolume depth
  sampling reads, move into auxdat.zw (auxdat.x is the medial wall mask
  and .y the curvature; z and w were left at zero by brainctm)
- the flatmap bump height moves into the fourth component of the bumped
  flatmap normals, so the two become a single vec4 flatbump attribute

Every shader variant now links: the worst case, 2D vertex data on a
subject with a flatmap, goes from 19 attributes to 16. Renders of the
paths that did work before -- volume data with equivolume sampling, and
the bumpy flatmap -- are pixel-identical to what they were.

Fixes gh-714.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013wiUP7TLgDqSfnv4n9ySZj

* TST: drop the resolved Vertex2D xfails now that gh-714 is fixed

Regenerated the visual-regression references with the same pinned
chromium/playwright/matplotlib as the rest of the reference set; no
existing reference image changed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* TST: tighten and extend the shader-link diagnostics

- Drop the dead compiled/attributes/max_attributes diagnostics from the
  assert: a compile failure always fails the subsequent link too (its
  error text already lands in the joined log).
- Add test to ensure we catch compile failures.

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Aditya Vaidya <kroq-gar78@users.noreply.github.com>
mvdoc pushed a commit that referenced this pull request Sep 21, 2026
#679 added two vertex attributes to the surface shaders, `flatBumpNorms`
(vec3) and `flatheight` (float), for the bumpy flatmap. That put the 2D
vertex program one over MAX_VERTEX_ATTRIBS, so it failed to link:

    THREE.WebGLProgram: gl.getProgramInfoLog() Too many attributes (mixNorms1)
    THREE.WebGLProgram: Could not initialise shader.
    WebGL: INVALID_OPERATION: drawElements: no valid shader program in use

Vertex2D flatmaps then rendered blank and `save_3d_views` raised, which is
gh-714. This branch had already spent the last free slot on `nanmask`, and
folds the per-vertex alpha map into it for the same reason.

Both of #679's attributes are static per-vertex geometry, computed together
in one block of mriview_surface.js, so they pack into a single vec4 (.xyz
the bump normal, .w the bump height) with no behavioural change and no
per-dataset buffer churn. That returns one slot, which is all that was
needed. `auxdat` has two free components but is deliberately left alone:
it is static geometry, and per-dataset state there would mean rewriting the
buffer on every setData.

Verified on the headless viewer: a Vertex2D flatmap went from a link
failure plus ~140 `no valid shader program in use` errors to none, and the
three `vertex2d_*` cases in test_webgl_nan_alpha_parity.py plus the two
Vertex2D cases in test_webgl_switching.py pass again. Those five passed
before this branch merged main and regressed on the merge.

The strict xfail #672 put on Vertex2D is removed: it was marked
`raises=RuntimeError, strict=True` precisely so that a render which starts
working reports rather than passing silently. Its reference images still
have to be generated, along with a regeneration of the whole stored set for
this branch's NaN/alpha changes; reference_images/README.md now says so.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015yNgwu9miNKAuv79yPMqU8
kroq-gar78 added a commit that referenced this pull request Sep 30, 2026
…views (#695)

* WebGL viewer: make opacity slider and `o` toggle work for Vertex data (#684)

The dat.GUI opacity slider and the `o` shortcut both drive the `dataAlpha`
uniform. The volume shaders apply it (`vColor *= dataAlpha`), but the
`surface_vertex` fragment shader only declared it and never read it, so
opacity was a silent no-op for Vertex, Vertex2D and VertexRGB data.

- shaderlib.js: scale the per-vertex data colour by `dataAlpha` before
  compositing over the curvature. `vColor` is a varying, so scale into a
  local `dColor`. Scaling all four channels keeps the premultiplied-alpha
  convention of the volume path, so opacity 0 shows curvature only.
- mriview_surface.js: `toggleOpacity` now remembers the last visible
  opacity instead of rounding it (0.7 -> 0 -> 0.7, not 0.7 -> 0 -> 1),
  and no longer leaks an implicit global.
- test_webgl_headless.py: regression test rendering a saturated Vertex at
  opacity 1 -> 0 -> 1 and counting coloured pixels. Fails on main
  (53,760 red pixels at opacity 0) and passes with the fix.

Closes #684

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P8oA4mUvTLd7sbs9iFaqM8

* test: replace magic-number thresholds in vertex opacity test with named, image-relative quantities

Address review on #685: the 1000 / 50 / 1000 pixel-count thresholds were
unexplained. The assertions now use named constants derived from the
measured renders and related to the image size or to each other:

- opacity 1: red-dominant pixels must cover >= 10% of the frame
  (measured ~27% at this view; curvature-only renders give 0%).
- opacity 0: at most 1% of the opacity-1 count (measured 0).
- opacity restored to 1: within 5% of the original count, which is a
  stronger check of the round trip than the previous "> 1000".

Re-verified: fails against the pre-fix shader (53,760 red pixels remain
at opacity 0), passes with the fix.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P8oA4mUvTLd7sbs9iFaqM8

* FIX unify NaN and alpha handling across quickflat, WebGL and RGB dataviews

Rule: a NaN anywhere at a voxel/vertex (data, either 2D dimension, any RGB
channel, or the alpha map) renders fully transparent in both renderers;
otherwise the alpha (2D colormap, alpha= kwarg, RGB alpha channel) is honored.

- Volume2D/Vertex2D: alpha= is a real attribute (not an ndarray in attrs,
  which crashed the WebGL viewer with a 500); multiplied into the colormap
  alpha in quickflat for both classes, shipped to WebGL as a normalized float
  brain and applied in the shaders (folded into the nanmask attribute for
  vertex data: 2D vertex views already use 15 of the 16 guaranteed vertex
  attributes and adding more made the program fail to link silently).
  Saved/restored in HDF.
- VolumeRGB/VertexRGB: NaN mask is applied without writing into the
  temporary returned by .volume for masked (linear) alpha Volumes; single-
  frame alpha is broadcast against multi-frame NaN masks (closes #629);
  NaN inside the alpha map -> 0 explicitly; color_voxels no longer mutates
  the caller's alpha array.
- quickflat: RGBA is averaged across thickness in premultiplied space (no
  dark halos around transparent voxels, matching the WebGL compositor);
  make_svg no longer indexes arr[..., 3] on 2-D scalar images.
- Dataview2D.to_json keeps vmin/vmax of exactly 0.
- Package deduplicates byte-identical brains (Vertex2D(x, x) / VertexRGB(r, r, r)
  used to be reordered twice and crash the viewer).
- WebGL hover/click readout shows NaN for masked vertices instead of 0.
- Tests: browser-free NaN/alpha unit tests, quickflat-vs-WebGL parity tests,
  and dataset-switching tests checking that NaN masks and alpha never leak
  between datasets (setData and addData).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdjyZMFXsn6mRMJu9i8ige

* ENH nanmean across layers in the WebGL viewer; quickflat nanmean=True by default

The WebGL multi-layer sampling summed the layer samples, so one NaN voxel at
any depth made the whole fragment transparent (quickflat's nanmean=False).
surface_pixel now averages only the valid (non-NaN) layer samples and is
transparent only when none is valid, matching quickflat's nanmean=True. A
`nanmean` toggle in the surface controls (on by default) restores the old
any-NaN-is-transparent behavior, and quickflat's make_figure /
make_flatmap_image / add_data default to nanmean=True so both renderers agree.
NaN-free data renders identically either way.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdjyZMFXsn6mRMJu9i8ige

* DOC describe the vmin/vmax defaults of Volume2D/Vertex2D

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdjyZMFXsn6mRMJu9i8ige

* FIX address review: nanmean for RGBA paths, movie masks, uint8 alpha, package dedup

- quickflat: nanmean now applies to dataviews that reach the RGBA branch.
  2D/raw conversions carry their NaN mask, so nanmean=True averages the
  valid voxels only and nanmean=False hides any pixel touched by a NaN
  voxel; native RGB (NaN already alpha 0) treats fully transparent voxels
  as missing, like the WebGL RGB textures.
- WebGL surface_pixel: NANMEAN also applies to RGB textures (fully
  transparent layer samples are skipped; validity from the current frame
  since an unbound next-frame sampler reads as opaque black).
- WebGL vertex data: the nanmask combines the masks of both frames being
  blended (next frame only while framemix > 0), so a NaN in the next frame
  no longer interpolates towards a fake 0.
- _mask_alpha: uint8 alpha maps are filled with byte 0 (their inferred
  vmin is a percentile of the bytes, 255 for a constant map).
- Package: same-name brains are deduplicated only when their class,
  subject, transform, shape, dtype and mask match; otherwise raise a
  clear ValueError instead of serving one brain with another's metadata.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdjyZMFXsn6mRMJu9i8ige

* FIX gh-714: pack the flat bump attributes so the 2D vertex shader links

#679 added two vertex attributes to the surface shaders, `flatBumpNorms`
(vec3) and `flatheight` (float), for the bumpy flatmap. That put the 2D
vertex program one over MAX_VERTEX_ATTRIBS, so it failed to link:

    THREE.WebGLProgram: gl.getProgramInfoLog() Too many attributes (mixNorms1)
    THREE.WebGLProgram: Could not initialise shader.
    WebGL: INVALID_OPERATION: drawElements: no valid shader program in use

Vertex2D flatmaps then rendered blank and `save_3d_views` raised, which is
gh-714. This branch had already spent the last free slot on `nanmask`, and
folds the per-vertex alpha map into it for the same reason.

Both of #679's attributes are static per-vertex geometry, computed together
in one block of mriview_surface.js, so they pack into a single vec4 (.xyz
the bump normal, .w the bump height) with no behavioural change and no
per-dataset buffer churn. That returns one slot, which is all that was
needed. `auxdat` has two free components but is deliberately left alone:
it is static geometry, and per-dataset state there would mean rewriting the
buffer on every setData.

Verified on the headless viewer: a Vertex2D flatmap went from a link
failure plus ~140 `no valid shader program in use` errors to none, and the
three `vertex2d_*` cases in test_webgl_nan_alpha_parity.py plus the two
Vertex2D cases in test_webgl_switching.py pass again. Those five passed
before this branch merged main and regressed on the merge.

The strict xfail #672 put on Vertex2D is removed: it was marked
`raises=RuntimeError, strict=True` precisely so that a render which starts
working reports rather than passing silently. Its reference images still
have to be generated, along with a regeneration of the whole stored set for
this branch's NaN/alpha changes; reference_images/README.md now says so.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015yNgwu9miNKAuv79yPMqU8

* Revert our gh-714 shader fix in favour of #715

#715 landed the same fix on main, and did it better. Both pack the bumpy
flatmap's height into the fourth component of its normals, but #715 also
moves the white matter and pial vertex areas into the two unused components
of `auxdat`, which brings the worst case (2D vertex data on a subject with
a flatmap) from 19 attributes down to 16 rather than to 17.

That extra headroom matters: at 17, plain `Vertex` data still overflows as
soon as equivolume sampling is on, which our fix left broken. #715 also
names the packed attribute `flatbump`, factors its declaration into
`utils.flatbump_attr`, and adds test_webgl_shaders.py, which links every
shader variant the viewer can build and would have caught gh-714 in the
first place.

Dropping our version of the JS here so the merge of main takes #715's
wholesale rather than resolving two equivalent edits line by line. The
xfail removals and the reference-image bookkeeping are reconciled in the
merge commit that follows.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015yNgwu9miNKAuv79yPMqU8

* TST cover the 2D alpha map and across-depth NaN averaging

Three gaps this branch's own changes left uncovered.

test_webgl_shaders.py: #715's matrix already covers this branch's extra
`nanmask` attribute -- all 27 variants still link, worst case included --
but not the options this branch adds to the volume-sampling shader.
_nan_alpha_variants adds 20 surface_pixel variants over dataalpha x nanmean
x layers (1 and 32) x the cmap/2d/rgb branches, hasflat and equivolume
pinned on. 47 variants, still under seven seconds, and no subject database
needed.

test_visual_regression.py, the alpha map on 2D dataviews: _dataview grew a
`twod_alpha` switch and NAN_ALPHA_DATAVIEW_NAMES now lists all four classes
that take an explicit `alpha=`, not just the two RGB ones. Volume2D and
Vertex2D accepted the argument before this branch as well, but it went into
`attrs` as a bare ndarray, so quickflat mishandled it and the viewer failed
to load the dataview -- that is the first fix in this PR and nothing in the
visual suite could see it. _build_nan_dataview passes it too, which finally
makes that builder do what its own comment says: NaN every place the rule
names, the alpha map included.

test_visual_regression.py, averaging across depth: a new
multilayer_nan_dataviews suite, the three volumetric classes at both values
of `nanmean`, with quickflat's `thick` and the viewer's `layers` both set
to 32 and NaNs in diagonal slabs two voxels thick, so most surface points
have both NaN and valid samples under them. The other suites NaN whole
columns and leave depth sampling alone -- at their defaults the renderers
do not even sample the same number of depths (quickflat 32, the viewer 1)
-- so none of them can see the change this PR makes to how a column of
samples is combined. Measured on renders from the regenerate path, the
scenario separates cleanly and the renderers agree: data covers 0.797 of
the flatmap with nanmean on and 0.196 with it off in quickflat, 0.815 and
0.185 in the viewer.

The Volume2D case of that suite is flaky, and not because of anything
here. Setting `layers` above 1 intermittently leaves the viewer's RPC proxy
answering `{}` to every later query, so save_3d_views dies on the next
parameter it sets; it never recovers and the browser reports no error.
Building the same dataview inline and running the same sequence reproduces
it on main at about the same rate, roughly one run in four, so it is a
pre-existing viewer/JSProxy bug rather than a gh-695 regression -- this is
just the first test to drive `layers` above 1 on a 2D dataview. Documented
in the test and left in.

References for all of this still have to be generated; see
reference_images/README.md.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015yNgwu9miNKAuv79yPMqU8

* TST regenerate the visual-regression reference images

236e8c9 added the multilayer and nan_alpha 2D cases but none of their
reference images, so those suites could not run: _render_and_check_dataview
fails outright on a missing reference. Adds the 16 that were absent (the 12
multilayer_nan_dataviews/ renders, and the four nan_alpha_dataviews/ ones for
Volume2D and Vertex2D) and refreshes the 18 that had drifted.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J5AMBzUzPKfDfVdjLvxqri

* TST xfail the multilayer suite's cross-renderer leg (gh-749)

quickflat and the WebGL viewer average over the same number of depth samples
here, but not at the same depths: quickflat takes the interior fractions
linspace(0, 1, thick+2)[1:-1] while the shader takes i/(layers-1), which
reaches both the white-matter and pial surfaces. On smooth data that is
invisible -- every cross check outside this suite passes at mean|diff| 1.3-1.9
of 255 -- but the multilayer suite's NaN slabs are two voxels thick, at the
sampling limit, so the offset flips which samples are NaN and the two renders
disagree pixel by pixel. Five of its six parameter sets breach the tolerance.

The disagreement is phase noise rather than a difference in what is drawn:
signed bias within +-2, transparency agreeing to the same 1.19% outline as the
passing suites, and mean|diff| dropping to 1.3 under a sigma=4 blur against a
1.18 floor. Both renderers also respond to nanmean the same way, which is what
the suite exists to cover.

Aligning the two grids would shift every render and invalidate both reference
sets, so that is left to gh-749. Only the cross-renderer leg is conceded: the
reference legs stay strict, and are asserted before the xfail so a real
regression cannot hide behind it. Uses the imperative pytest.xfail rather than
a mark, so the sixth parameter set -- which stays inside the tolerance --
simply passes, and all six will go green on their own once gh-749 is fixed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J5AMBzUzPKfDfVdjLvxqri

* TST stop the nan suite's vertex masks from covering the whole surface

_build_nan_dataview NaN'd the vertex channels over three disjoint index ranges
-- idx >= total/2, idx < total/4, and the quarter between -- which tile the
surface exactly. A NaN in any channel renders an element transparent, so with
no vertex left clean the two classes drawing on all three (Vertex2D, and
VertexRGB through red/green/alpha) came out as bare curvature: 0% of their
opaque pixels carried any color, against 10-100% everywhere else. The four
nan_dataviews references for them pinned an empty flatmap, so they covered
nothing -- a regression in 2D or RGB vertex NaN handling would still render
blank and still pass, and the cross-renderer leg compared one blank flatmap
against another.

The volume regions never had this problem because they are three overlapping
halves on independent axes (x>=50, y>=50, z>=15), whose union is 7/8 and leaves
37500 clean voxels. Splits the vertex regions on the vertex coordinates the
same way, at the median of each axis so the masks stay at half the surface
exactly. That leaves 39784 vertices (13.1%) clean, against 12.1% of the volume,
and Vertex2D and VertexRGB now retain 13.07% all-finite elements rather than
none.

Volume regions are untouched, so only the four nan_dataviews vertex references
need regenerating.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J5AMBzUzPKfDfVdjLvxqri

* TST put the nan suite's clean remainder where the data is visible, and guard it

Two follow-ups to the vertex masks.

Leaving a remainder is not sufficient on its own: it also has to land somewhere
the data can be seen. Vertex2D's visibility is governed by the alpha its 2D
colormap derives from dim2, which is the accuracy bump, and >= on all three
axes put the survivors off it -- mean accuracy 0.23, 3.5% of them above 0.5,
and a render with 1.2% of its opaque pixels colored against Volume2D's 9.9%.
Flipping the z comparison moves the remainder onto the bump (mean accuracy
0.62, 70% above 0.5) for the same 12% of the surface. VertexRGB improves with
it; Vertex is unaffected, since it reads only the primary mask.

Adds test_nan_builders_leave_clean_elements, asserting on the dataviews
themselves that each NaN suite leaves at least 5% of elements free of NaNs in
every channel -- the suites sit at 12% and above, so the floor is not tuned.
Nothing could catch the original fault, because a blank render matches a blank
reference exactly and agrees with the other renderer's blank render exactly as
well; the failure is only visible before rendering. Checked against the masks
as they were: it fails on Vertex2D and VertexRGB at 0.00% and passes the rest.

The check needs no browser, so the playwright skip moves off pytestmark and
onto the five render tests individually. Without playwright this file used to
collect 39 skips and assert nothing; it now runs the 13 builder checks and
skips the 26 renders.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J5AMBzUzPKfDfVdjLvxqri

* Update test images

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AGP6ytTVeCU29FbmuLNBza

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Aditya Vaidya <kroq-gar78@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant