Repository navigation
Conversation
There was a problem hiding this comment.
Pull request overview
Adds drop shadow layer-effect rendering to the psd_tools.composite pipeline so composite(force=True) no longer silently drops the shadow, aligning output closer to Photoshop’s baked preview.
Changes:
- Implement
draw_drop_shadow(...)incomposite/effects.pyusing choke (erosion), gaussian blur, and directional offset. - Apply drop shadow as an “outer effect” in
Compositor.apply()before compositing the layer source (paints behind the layer). - Add unit tests for the mask renderer plus an integration-style fidelity test against
layer_effects.psd.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
tests/psd_tools/composite/test_effects.py |
Adds unit + integration tests covering drop shadow mask behavior and fidelity improvement. |
src/psd_tools/composite/effects.py |
Introduces draw_drop_shadow and updates effects module documentation. |
src/psd_tools/composite/composite.py |
Hooks drop shadow rendering into the compositor before the layer source is blended. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| opacity = effect.opacity / 100.0 | ||
| self._apply_source(shadow_color, mask, mask * opacity, effect.blend_mode) |
|
@omar16100 Thanks. Can you at least address Copilot's suggestions? I have a concern about not having test fixtures to measure fidelity here |
|
This pull request has been marked as stale due to inactivity for 45 days. If you plan to continue it, please leave a comment or push an update. If it is waiting on maintainer review, add or request an |
|
I tested it (as I always wanted to have outer_glow working, #382 ), and it works fine with copilot corrections which are indeed correct (at least the 2 relative to adding the layer opacity). |
composite() read every drop shadow parameter but never drew the effect, so the shadow vanished whenever a document was composited from its layers. Draw it: the layer's silhouette, grown by spread, blurred and cast away from the light, painted beneath the layer before the layer is resolved. - draw_drop_shadow() and drop_shadow_bbox() in composite/effects.py. For a drop shadow the Ckmt key is Photoshop's Spread, which grows the matte before the blur (choke, which shrinks it, is the inner shadow's), and the blur takes what is left of the size. The gaussian treats the canvas edge as empty and is cut off at the remaining radius, so the canvas holds the whole shadow. - The shadow fades with the layer's opacity but not its fill opacity, and "layer knocks out drop shadow" cuts it away under the silhouette it is cast from. - The silhouette is the layer's alpha before opacity and fill, read on the shadow's own box: a group's is its contents composited over nothing, so faded children cast lighter shadows and a knockout inside does not make the shadow depend on the viewport. - The cull and a group's content box include the shadow's reach, and a group's shadow is grown from its content box, its children's effects included. - Painting before the layer is resolved puts the shadow under a pass-through group's contents, which blend with it. The blur sigma, 0.45 x size, is fitted against the four fixtures that carry a drop shadow Photoshop rendered into its preview, and test_drop_shadow.py holds each to it: layer_effects.psd 1.4e-3 -> 4.3e-6 around the shadow, masks.psb 1.8e-4 -> 1.3e-5 over the document, layer_params.psb 2.7e-2 -> 5.2e-3 and layer_comps.psb 6.7e-3 -> 4.5e-3, the rest of those two being an outer glow and a bevel that are not drawn. Contour and noise are not applied. Addresses the review on psd-tools#679: the gaussian's edge mode and the layer opacity, both reported by Copilot.
2f312f5 to
d6dc070
Compare
|
Thanks @kyamagu for the review, and @bertou for testing it and confirming the opacity fix. I've reworked this on top of current Copilot's two suggestions
Other fixes made while porting
Fidelity fixtures Four documents already in
The blur sigma (0.45 x size) is fitted against these; the size/3 I used before scores 4.0e-5 around the layer_effects.psd shadow. layer_params.psb also pins the spread direction: ignoring spread scores 6.6e-3 and eroding by it 9.2e-3. The combinations the corpus doesn't pair with a shadow (layer and fill opacity, knockout off, groups, pass-through groups, a vector-masked pixel layer, a shadow cast into a viewport the layer misses) have targeted tests of their own. Known limits, in the code and the changelog entry: contour and noise are not applied, and the blur is a gaussian approximation of Photoshop's. Spread on a very large soft-edged layer is slower, since it grows up to 16 coverage levels. A pass-through group that knocks out loses its shadow's colour the same way it already loses the colour of every layer beneath it (#707). @bertou the Softer/Precise "Technique" option belongs to Outer Glow (#382), which this PR doesn't render, so I'd keep it out of scope here. It could be a follow-up on the same machinery, and if you're able to share your PSD it would make a good fidelity fixture for it. The full test suite, ruff, ruff format and mypy pass locally. |
kyamagu
left a comment
There was a problem hiding this comment.
Reviewed the full diff, ran the suite, and swept the fixture corpus. The implementation is sound and the test file is unusually strong — viewport independence, pass-through ordering, the group silhouette read from alpha, nesting cost, force parity and unreadable-descriptor degradation are all pinned.
Verification
tests/psd_tools/composite+tests/psd_tools/api: 1880 passed, including all 49 new drop-shadow tests.- Corpus sweep (every fixture in
tests/psd_files,forceboth ways, MSE againstpsd.numpy()), merge-base vs. this head: 8 documents change, all 8 improve, no new exceptions and no shape changes.masks.psb1.76e-4 → 1.27e-5,layer_params.psb1.19e-2 → 4.51e-3,layer_comps.psb6.71e-3 → 4.46e-3,layer_effects.psd6.60e-3 → 6.42e-3. - Runtime cost is modest:
masks.psb0.54 s → 0.67 s,layer_params.psb0.064 s → 0.124 s.
Two issues inline, one on the unclipped shadow canvas and one on the opacity guard.
Not findings, but worth knowing
- The branch is not rebased onto current
main— its merge-base is8f9a25ea, so it is missing #887.git merge-treeshows no textual conflicts, but the fidelity figures in the description were measured on the older base. _cast_bbox()useslayer.is_group()while_cast_shape()usesisinstance(layer, GroupMixin). No fixture in the corpus distinguishes them (all 25 layer classes present were checked), but the module prefersis_group()elsewhere, because the protocolisinstancecan be defeated by a raising property on Python ≤ 3.11.- On a scipy-less install a document with a drop shadow now raises
ImportErrorout ofcomposite()where it previously rendered without the shadow. That matches the existing stroke behaviour exactly —layer_comps.psbalready raised on the base for the same reason — so it reads as intentional.
| continue | ||
| if utils.intersect(self._viewport, bbox) == (0, 0, 0, 0): | ||
| continue | ||
| silhouette = self._cast_shape(layer, bbox) |
There was a problem hiding this comment.
The shadow canvas is never clipped to the viewport, so a large size or distance allocates unboundedly.
drop_shadow_bbox() grows cast_from by ceil(size) + 2 on all four sides and by the full offset on the cast side, with no clamp, and _cast_shape(layer, bbox) here materialises that whole canvas — _spread(), gaussian_filter() and ndimage.shift() then all run on it. The utils.intersect(self._viewport, bbox) guard two lines up never fires, because bbox ⊇ cast_from ⊇ layer.bbox, so any layer visible in the viewport reaches the allocation.
Measured on layer_comps.psb (200x200 document, shadowed layer Фигура 1 at (17, 20, 180, 183)) with a forged Blur:
| forged value | shadow canvas |
|---|---|
Blur=1000 |
2167x2167 = 19 MB |
Blur=20000 |
40167x40167 = 6.4 GB |
Blur=1e9 |
2000000167² = 1.6e19 bytes |
At Blur=1e9, composite() does not raise a caught _UNREADABLE error — it runs until killed. The guards just above cover math.ceil(inf) and nan, but not a finite huge value, and _cast_shape() sits outside both try blocks anyway.
It also costs on values Photoshop itself permits. With Distance=30000 (Photoshop's own maximum) and the light angled so the shadow lands entirely off-canvas, composite(masks.psb) goes from 0.80 s / 176 MB peak to 4.67 s / 550 MB peak (tracemalloc), for a shadow that contributes nothing — the canvas is 187x30187 per shadow.
Suggestion: after computing bbox, intersect it with the viewport unioned with the viewport shifted back by (-dx, -dy), grown by ceil(size) + 2, before handing it to _cast_shape(). Nothing outside that can land in the viewport. _shadow_reach() can stay as it is, since it is only a reach measurement.
| try: | ||
| distance, angle = shadow.distance, shadow.angle | ||
| size, spread = shadow.size, shadow.choke | ||
| effect_opacity = shadow.opacity / 100.0 |
There was a problem hiding this comment.
The finiteness guard on the next line is applied in float64, but the arithmetic downstream is float32, so a finite-but-huge Opct still puts NaN across the whole document.
shadow.opacity is read unclamped from the descriptor. With Opct = 1e300 the check passes, since 1e298 is finite, but coverage * effect_opacity * opacity below is float32, overflows to inf, and _apply_source()'s utils.union turns that into NaN. Measured on masks.psb: composite(psd) returns an alpha canvas that is entirely NaN (np.isfinite(alpha).all() is False) — exactly the failure the docstring says this guard exists to prevent, that "one NaN in the coverage spreads to the whole canvas it is composited on".
Three more values escape it the same way: Opct = 1e39 gives a finite but absurd alpha up to 4.9e36, and Opct = 400 and Opct = -100 give alpha 2.11 and −0.53, both outside [0, 1]. The _UNDRAWABLE table in test_drop_shadow.py covers nan-opacity and infinite-opacity, but not these.
Clamping to Photoshop's own range closes all four at once and makes the explicit isfinite check redundant:
effect_opacity = min(max(shadow.opacity, 0.0), 100.0) / 100.0The pre-existing stroke and overlay paths (lines 1988 and 2019) share the unclamped division, so a shared clamp would be tidier than a shadow-only one.
|
Thank you @omar16100 for this PR. The drop shadow rendering here was the starting point for the work, and I'm closing this in favour of #1069, which takes it over. #1069 keeps your commit (you remain its author), rebases it onto current Thanks also @bertou for testing it. Outer glow (#382) is separate and not covered there. |
feat: render drop shadow layer effect (takes over #679)

Summary
composite()reads every drop shadow parameter but never drew the effect, so the shadow disappeared whenever a document was composited from its layers (force=True,ignore_preview=True, or after an edit). This renders it.Rebased onto current
mainand re-implemented on the new effect pipeline (the June version conflicted with #846 and the reach work in #804, #808 and #815).Approach
composite/effects.py:draw_drop_shadow()grows the layer's silhouette by Spread (the drop shadow'sCkmt; it expands the matte, where the inner shadow's Choke shrinks it), blurs it with a gaussian that takes what is left of Size, and casts it away from the light angle (global light included).drop_shadow_bbox()sizes the canvas. The blur treats the canvas edge as empty and is cut off at the remaining radius.composite/composite.py:Compositor._apply_drop_shadows()paints each shadow beneath the layer, before the layer is resolved, so a pass-through group's contents blend with their own shadow. It fades with layer opacity but not fill opacity, and "Layer Knocks Out Drop Shadow" cuts it by the layer's own alpha. The silhouette is the layer's alpha before opacity and fill, read on the shadow's own box; for a group that is its contents composited over nothing (cached per pass)._effect_reach()adds the shadow's reach to the cull and to a group's content box.Fidelity
Four fixtures in
tests/psd_filescarry a drop shadow rendered by Photoshop into the preview.tests/psd_tools/composite/test_drop_shadow.pyholds each render to it, and checks that the same render with shadows off is clearly worse:main)force=True)The sigma (0.45 x size) is fitted against these. Forged cases cover layer and fill opacity, knockout on and off, groups (including faded children), pass-through groups, a vector-masked pixel layer, and a shadow cast into a viewport the layer misses.
Limits
Checks
Full suite,
ruff check,ruff format --checkandmypypass locally, as does the no-composite job's test selection.