Skip to content

perf(analysis): hillshade lights each cell with a square root, no trigonometry - #2941

Merged
Mavrick-F merged 1 commit into
opengeos:mainfrom
Mavrick-F:perf/hillshade-no-trig
Nov 25, 2026
Merged

Mavrick-F merged 1 commit into
opengeos:mainfrom
Mavrick-F:perf/hillshade-no-trig

Conversation

@Mavrick-F

@Mavrick-F Mavrick-F commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Summary

hillshade_on made six transcendental calls per cell: hypot, atan, cos, sin, atan2 and cos. atan2 alone was about a fifth of the run. The illumination formula (Burrough and McDonnell, Principles of Geographical Information Systems, 1998) is

cos zenith · cos slope + sin zenith · sin slope · cos(azimuth − aspect)

with the slope atan p, p² = gx² + gy², and the aspect atan2(−gx, −gy). The terms can be rewritten algebraically: cos slope = 1/√(1 + p²), sin slope = p/√(1 + p²), cos aspect = −gy/p and sin aspect = −gx/p. Expanding cos(azimuth − aspect) with these gives

(cos zenith − sin zenith · (gy · cos azimuth + gx · sin azimuth)) / √(1 + p²)

So each cell now takes one square root. The sine and cosine of the azimuth are taken once per run. A flat cell (p = 0) gives cos zenith either way. Where 1 + p² overflows, the cell is computed with the angles as before. The gradient (Horn's), the rounding and the 1–255 range are unchanged.

Timing

This is the 25 Nov benchmark case: the 115-million-cell DEM (dem.tif), azimuth 315, altitude 45, Z factor 1. Each figure is the median of 3 runs of the whole rustgis-cli run (read, raster.function hillshade, write) on the same box, through the host queue.

Build Wall CPU (user)
3a5dd41d4 (benchmark baseline) 8.12 s 32.21 s
main at e7f6bcf 8.04 s 31.83 s
This PR 5.95 s 20.20 s

That is 26% less wall time and 37% less CPU time for the whole command. In a profile of the new build, the terrain loop is about 22% of the run and the rounding to whole numbers is another 6%. The rest is reading the GeoTIFF, the band statistics and writing it.

Output

All 115,491,649 cells are the same as main's output, byte for byte. Rounding to whole numbers 1–255 absorbs the last-bit differences between the two forms.

Not changed

slope_on and aspect_on don't have the same waste. They return angles in degrees, so the one atan of slope and the one atan2 of aspect are the result itself, not an intermediate. The per-cell rustgis_map::raster::hillshade that the renderer uses for Shaded Relief still uses the angle form. It is a separate path, left for its own measurement.

Surfaces

The change is in rustgis_analysis::rasterops::hillshade_on. It reaches everything that makes a hillshade raster through raster.function and the Function Editor: desktop, browser, command line, Python, and the Assistant and MCP. Nothing saved changes. The map renderer's own shading is not affected.

Testing

  • cargo fmt --all --check, the private preflight, and the terrain tests in rustgis-analysis: terrain_rows_match_scalar_edges_nodata_and_orientations, terrain_faces_the_right_way_on_a_bottom_up_grid (light from the south and north on a bottom-up grid), hillshade_keeps_zero_for_no_data, terrain_keeps_edge_and_nodata_results and terrain_math_and_classes. All passed.
  • The full gate ran on the fork's CI.
  • The benchmark and the cell-by-cell comparison above.

UI evidence

No visible UI change.

Related issue

Part of #1111.

Summary by CodeRabbit

  • Bug Fixes

    • Hillshade rendering now uses a direct lighting calculation based on terrain gradients, with a fallback calculation for cases where the result would be non-finite.
  • Documentation

    • Updated the hillshade documentation to describe the calculation and fallback behavior.

…gonometry

A cell's light is cos zenith · cos slope + sin zenith · sin slope ·
cos(azimuth − aspect) (Burrough and McDonnell, Principles of
Geographical Information Systems, 1998), with the slope atan p,
p² = gx² + gy², and the aspect atan2(−gx, −gy). Expanding the cosine of
the difference with cos slope = 1/√(1 + p²), sin slope = p/√(1 + p²),
cos aspect = −gy/p and sin aspect = −gx/p gives

  (cos zenith − sin zenith · (gy · cos azimuth + gx · sin azimuth)) / √(1 + p²)

so each cell takes one square root instead of hypot, atan, cos, sin,
atan2 and cos. The sine and cosine of the azimuth are taken once. Where
1 + p² overflows, the angles are taken as before.
@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

hillshade_on now uses a gradient-based cosine-lighting formula when the denominator expression is finite. Otherwise, it uses the previous slope/aspect trigonometric calculation. The documentation describes both calculation paths.

Changes: Hillshade calculation

Layer / File(s) Summary
Gradient formula and fallback
crates/analysis/src/rasterops.rs
hillshade_on calculates lighting from gradient components when the denominator expression is finite. It falls back to the prior slope/aspect calculation otherwise. The documentation describes the formula and fallback.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Refactor

Possibly related PRs

Suggested reviewers: giswqs, choupeanut

Merge Risk: Minimal · up to d0aab

This change speeds up hillshade rendering. Output is reported identical on a large benchmark. At most, rare cells at rounding boundaries could shift by one brightness level. Merge-readiness risk is minimal.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: hillshade computes illumination with one square root and no trigonometry, which is a performance change in rustgis_analysis::rasterops::hillshade_on. The raw summary a…
Description check Passed The description follows the template. It has Summary, Testing, UI evidence, and Related issue sections. The UI evidence section states 'No visible UI change,' which the template allows when no visible…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: hillshade computes illumination with one square root and no trigonometry, which is a performance change in rustgis_analysis::rasterops::hillshade_on. The raw summary and objectives confirm that the trigonometric per-cell calls were replaced with an algebraic cosine-lighting formula. The title is specific and accurate. It is 78 characters, which is acceptable.

Full details: Description check

Explanation

The description follows the template. It has Summary, Testing, UI evidence, and Related issue sections. The UI evidence section states 'No visible UI change,' which the template allows when no visible change exists. The Summary gives the formula, the fallback for overflow, the benchmark, and the output check. The Testing section lists the commands and tests that were run. The Related issue section says 'Part of #1111.' The description is detailed and complete. Minor issue: the Summary uses a dated benchmark label ('the 25 Nov benchmark case') and references internal items such as 'the fork's CI' and 'private preflight' that a reviewer cannot verify. These do not make the description incomplete.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks the shaded ground,
Where gradients guide the light around.
If the denominator fails its test,
The older angles do the rest.
The hills now glow by either way.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: e81bb1aa-da34-4a47-9696-81931d22acaa
Commits

Reviewing files that changed from the base of the PR and between ced7c3d and d0aab2c.

Files selected for processing: 1

  • crates/analysis/src/rasterops.rs

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

Comment on lines +287 to +293
let v = if q.is_finite() {
(cos_zen - sin_zen * (gy * cos_az + gx * sin_az)) / q.sqrt()
} else {
let slope = gx.hypot(gy).atan();
let aspect = (-gx).atan2(-gy);
cos_zen * slope.cos() + sin_zen * slope.sin() * (az - aspect).cos()
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The overflow branch (q not finite, angle form) is not exercised by any test. The existing tests use gradients far below the f64 overflow point, so this path could break without a failing test. I checked the algebra of the square-root form against the angle form by hand, and it matches; the fallback is the part with no coverage.

Suggested test: a small raster with a steep ramp run with a huge Z factor (for example zf = 1e200, so gx * gx overflows), asserting every cell is in 1..=255 and equals the angle form's rounded value. Also a grid of moderate gradients over several azimuths and altitudes, comparing the new form with the angle form within one grey level, which guards the math for the normal path.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass. The fallback is the previous angle form, unchanged. The 115-million-cell comparison covers the algebraic form at one light direction; a test over several azimuths and altitudes and an overflowing Z factor is a reasonable addition then.

/// cos zenith · cos slope + sin zenith · sin slope · cos(azimuth − aspect), the slope atan p with
/// p² = gx² + gy² and the aspect atan2(−gx, −gy). With cos slope = 1/√(1 + p²),
/// sin slope = p/√(1 + p²), cos aspect = −gy/p and sin aspect = −gx/p, that is
/// (cos zenith − sin zenith · (gy · cos azimuth + gx · sin azimuth)) / √(1 + p²): a square root a

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo in the doc comment: "a square root a / cell" should read "a square root per cell".

Suggested change
/// (cos zenith − sin zenith · (gy · cos azimuth + gx · sin azimuth)) / √(1 + p²): a square root a
/// (cos zenith − sin zenith · (gy · cos azimuth + gx · sin azimuth)) / √(1 + p²): a square root per

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass. "A square root a cell" is meant as "per cell" (as in "once a day"), not a typo; the wording can be revisited then.

@github-actions

Copy link
Copy Markdown
Contributor

Code review

I checked the change against the algebra and the surrounding code. I found no bugs, no security issues and no performance problems. I could not run the build or the benchmark (no shell here), so the byte-identical output claim rests on the author's measurement.

Bugs: none found.

  • The rewrite (cos zen − sin zen · (gy·cos az + gx·sin az)) / √(1+p²) matches the angle form. I derived it from cos slope = 1/√(1+p²), sin slope = p/√(1+p²), cos aspect = −gy/p and sin aspect = −gx/p. Flat cells give cos zen, as before.
  • q ≥ 1 whenever it is finite, so sqrt never sees zero or a negative number.
  • NaN and infinite gradients take the fallback branch, which behaves as the old code did (max(0.0) maps NaN to 0, then the 1 floor applies).

Security: none found.

Performance: none found. The change drops four transcendental calls per cell, and the sine and cosine of the azimuth are computed once per run. Threading still goes through terrain_on.

Quality (both buffered as inline comments):

  • The overflow fallback (hillshade_on, rasterops.rs:287-293) has no test. The existing tests use gradients far below f64 overflow. Confidence: medium. A test with a huge Z factor, and a grid comparing the two forms within one grey level, would cover it.
  • Typo in the new doc comment (rasterops.rs:278): "a square root a cell" should be "a square root per cell". Confidence: high.

AGENTS.md: nothing found. No new command, no new memory or thread path, and no surface change that needs a schema, command-surface or limit update.

Prior reviews: no existing threads, so no concerns were left alone.

Unverified: the claim that all 115,491,649 cells match main byte for byte. The two forms differ in the last bits, so a cell sitting on a .5 rounding boundary could flip. The author's measurement is the only evidence.

Change size

Compared with the base branch: the whole PR against main (merge base e7f6bcf to PR head d0aab2c).

Measure Value
Files changed 1 (0 added, 1 modified, 0 removed, 0 renamed)
Size before 158.1 KB
Size after 159.0 KB
Total size change +879 B
Path Before After Change
crates/analysis/src/rasterops.rs 158.1 KB 159.0 KB +879 B

@github-actions

Copy link
Copy Markdown
Contributor

📖 Docs preview

Item Value
Preview https://preview.rustgis.app/pr-2941/
Web app https://preview.rustgis.app/pr-2941/app/
Commit d0aab2c

GitHub Pages takes a minute or two to publish a new commit. Newer commits from the fork aren't published until a maintainer adds the preview label (once per commit).

@Mavrick-F
Mavrick-F added this pull request to the merge queue Nov 25, 2026
Merged via the queue into opengeos:main with commit 231cc84 Nov 25, 2026
28 checks passed
@Mavrick-F
Mavrick-F deleted the perf/hillshade-no-trig branch November 25, 2026 19:00
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