mln-rs-engine 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! The GLSL (for Vulkan, D3D12, OpenGL, and OpenGL ES) of the terrain's
//! programs, and the snippets of the ground that other programs include.

use mln_gfx::shaders::source::{GlslEsDeclarations, GlslEsSource, GlslSource};

/// The DEM, which GL ES samples at `highp`.
const TERRAIN_DECLARATIONS: GlslEsDeclarations =
    GlslEsDeclarations { highp_samplers: &["ground_dem"], ..GlslEsDeclarations::DEFAULT };

/// What the terrain variant of a program that hides behind the ground in
/// front of it reads of the ground's depth, within `#ifdef TERRAIN` of its
/// vertex stage: whether that ground hides a point (`ground_visibility`).
#[doc(hidden)]
#[macro_export]
macro_rules! terrain_glsl_ground_visibility {
    () => {
        r"
#ifdef TERRAIN
// 1 where a point `w` from the eye, at `ndc`, is in front of the ground drawn
// there, fading to 0 behind it over a short ramp of its NDC depth, which
// `depth_factor` scales; 1 where no ground is drawn there or `ndc` is outside
// the view. GL stores rows from the bottom; Vulkan/D3D12 from the top.
highp float ground_depth_opacity(highp vec2 ndc, highp float w, highp float depth_factor) {
    if (any(greaterThan(abs(ndc), vec2(1.0)))) {
        return 1.0;
    }
    ivec2 size = textureSize(u_ground_depth, 0);
#ifdef MLN_GL
    highp vec2 pos = (ndc * 0.5 + 0.5) * vec2(size);
#else
    highp vec2 pos = (vec2(ndc.x, -ndc.y) * 0.5 + 0.5) * vec2(size);
#endif
    ivec2 texel = clamp(ivec2(floor(pos)), ivec2(0), size - 1);
    highp uvec4 bytes = uvec4(round(texelFetch(u_ground_depth, texel, 0) * 255.0));
    highp float ground = uintBitsToFloat(bytes.x | (bytes.y << 8u) | (bytes.z << 16u) | (bytes.w << 24u));
    if (!(ground > 0.0)) {
        return 1.0;
    }
    highp float d = depth_factor * (1.0 / w - 1.0 / ground) + 0.0001;
    return 1.0 - clamp(-500.0 * d, 0.0, 1.0);
}

// The visibility of the point at `clip`: 1 where the ground drawn in front
// doesn't hide it, 0 where it does, averaged with the point 0.01 NDC above it
// where it is partly hidden. The ramp's scale is `2n` of a near plane `n` a
// fiftieth of the view's height, in pixels, a `GlobalPaintParamsUBO`'s
// `world_size.y / pixel_ratio`.
highp float ground_visibility(highp vec4 clip, highp float view_height) {
    if (clip.w <= 0.0) {
        return 1.0;
    }
    highp vec2 ndc = clip.xy / clip.w;
    highp float depth_factor = view_height / 25.0;
    highp float visibility = ground_depth_opacity(ndc, clip.w, depth_factor);
    if (visibility > 0.95) {
        return 1.0;
    }
    return (visibility + ground_depth_opacity(ndc + vec2(0.0, 0.01), clip.w, depth_factor)) / 2.0;
}
#endif
"
    };
}

/// The height rule of `crate::tile::dem`, over the DEM tile a draw reads: its
/// RGBA8 texels behind a one-texel border, decoded by the terrain's uniform
/// block, `terrain`. A macro, so that `concat!` puts it in the vertex stages
/// that read the DEM.
#[doc(hidden)]
#[macro_export]
macro_rules! terrain_glsl_ground_height {
    () => {
        r"

// The height in meters of the DEM's bordered texel at `texel`, clamped to the
// texture, decoded by `terrain`.
highp float ground_texel_height(ivec2 texel) {
    ivec2 last = textureSize(u_ground_dem, 0) - 1;
    highp vec3 rgb = round(texelFetch(u_ground_dem, clamp(texel, ivec2(0), last), 0).rgb * 255.0);
    highp vec4 unpack = terrain.unpack;
    return (rgb.r * unpack.x + rgb.g * unpack.y + rgb.b * unpack.z + unpack.w) * terrain.unpack_scale;
}

// The height in meters, exaggerated, at `pos` in tile units of a tile that
// reads its DEM at `dem_coords`: the DEM uv's scale and offset, then the
// DEM's width in pixels, 0 for flat ground.
highp float ground_height(highp vec2 pos, highp vec4 dem_coords) {
    highp float dim = dem_coords.w;
    if (dim == 0.0) {
        return 0.0;
    }
    highp vec2 coord = (pos / 8192.0 * dem_coords.x + dem_coords.yz) * dim + 0.5;
    highp vec2 first = floor(coord);
    highp vec2 f = coord - first;
    ivec2 texel = ivec2(first);
    highp float tl = ground_texel_height(texel);
    highp float tr = ground_texel_height(texel + ivec2(1, 0));
    highp float bl = ground_texel_height(texel + ivec2(0, 1));
    highp float br = ground_texel_height(texel + ivec2(1, 1));
    highp float top = tl * (1.0 - f.x) + tr * f.x;
    highp float bottom = bl * (1.0 - f.x) + br * f.x;
    return (top * (1.0 - f.y) + bottom * f.y) * terrain.exaggeration;
}
"
    };
}
pub(crate) use crate::terrain_glsl_ground_height as ground_height;

/// `fogged`, which covers a color of the surface with the fog of the
/// terrain's uniform block, `terrain`.
#[doc(hidden)]
#[macro_export]
macro_rules! terrain_glsl_terrain_fog {
    () => {
        r"

// `color`, premultiplied, of the surface `view_depth` pixels along the view,
// covered by the fog of `terrain`: mixed in linear components toward the fog's
// color by the square of how far past the ground blend the fog's depth is. The
// fog's alpha weighs its color; the coverage stays.
highp vec4 fogged(highp vec4 color, highp float view_depth) {
    highp float near = terrain.depth_range.x;
    highp float far = terrain.depth_range.y;
    highp float depth = min(far / (far - near) * (1.0 - near / view_depth), 1.0);
    if (terrain.ground_blend >= 1.0 || depth <= terrain.ground_blend || color.a == 0.0) {
        return color;
    }
    highp float horizon = smoothstep(0.0, 1.0, (depth - terrain.horizon_blend) / max(1.0 - terrain.horizon_blend, 1e-6));
    highp vec4 tint = mix(terrain.fog_color, terrain.horizon_color, horizon);
    highp float along = (depth - terrain.ground_blend) / (1.0 - terrain.ground_blend);
    highp float strength = along * along;
    highp vec3 surface = pow(color.rgb / color.a, vec3(2.2));
    highp vec3 mixed = surface * (1.0 - strength * tint.a) + tint.rgb * strength;
    return vec4(pow(mixed, vec3(1.0 / 2.2)) * color.a, color.a);
}
"
    };
}
pub(crate) use crate::terrain_glsl_terrain_fog as terrain_fog;

/// The surface's and the probe's vertex prelude: the height rule, and the
/// height of the surface's vertices.
#[doc(hidden)]
#[macro_export]
macro_rules! terrain_glsl_terrain_props {
    () => {
        concat!(
            ground_height!(),
            r"

// The height of the surface's vertex at `pos`, in tile units of a tile that
// reads its DEM at `dem_coords`: the ground's, or sea level at a pole.
highp float surface_height(highp vec2 pos, highp vec4 dem_coords) {
    if (pos.y < GLOBE_POLE_NORTH_Y || pos.y > GLOBE_POLE_SOUTH_Y) {
        return 0.0;
    }
    return ground_height(pos, dem_coords);
}
"
        )
    };
}
pub(crate) use crate::terrain_glsl_terrain_props as terrain_props;

/// How a hillshade shades its slopes: `hillshade`, which writes to
/// `fragColor` a slope shaded by the lights of `props`, a
/// `HillshadeEvaluatedPropsUBO`. A macro, so that `concat!` puts it in the
/// fragment stages of the hillshade and of the terrain's surface, which shades
/// a drape of a hillshade's slopes.
#[doc(hidden)]
#[macro_export]
macro_rules! terrain_glsl_hillshade_shading {
    () => {
        r"
#define STANDARD 0
#define COMBINED 1
#define IGOR 2
#define MULTIDIRECTIONAL 3
#define BASIC 4

float get_aspect(vec2 deriv) {
    return deriv.x != 0.0 ? atan(deriv.y, -deriv.x) : PI / 2.0 * (deriv.y > 0.0 ? 1.0 : -1.0);
}

// MapLibre's legacy hillshade algorithm (Method 0: STANDARD)
void standard_hillshade(vec2 deriv, float intensity) {
    float azimuth = props.azimuths.x + PI;
    float slope = atan(0.625 * length(deriv));
    float aspect = get_aspect(deriv);

    // Scale the slope exponentially based on intensity
    float base = 1.875 - intensity * 1.75;
    float maxValue = 0.5 * PI;
    float scaledSlope = abs(intensity - 0.5) > 1e-6 ? ((pow(base, slope) - 1.0) / (pow(base, maxValue) - 1.0)) * maxValue : slope;

    float accent = cos(scaledSlope);
    vec4 accent_color = (1.0 - accent) * props.accent * clamp(intensity * 2.0, 0.0, 1.0);

    float shade = abs(mod((aspect + azimuth) / PI + 0.5, 2.0) - 1.0);
    vec4 shade_color = mix(props.shadows[0], props.highlights[0], shade) * sin(scaledSlope) * clamp(intensity * 2.0, 0.0, 1.0);

    fragColor = accent_color * (1.0 - shade_color.a) + shade_color;
}

// Basic directional hillshade (Method 4: BASIC)
void basic_hillshade(vec2 deriv, float exaggeration) {
    deriv = deriv * exaggeration * 2.0;
    float azimuth = props.azimuths.x + PI;
    float cos_az = cos(azimuth);
    float sin_az = sin(azimuth);
    float cos_alt = cos(props.altitudes.x);
    float sin_alt = sin(props.altitudes.x);

    // Calculate the cosine of the angle between the light vector and the surface normal
    float cang = (sin_alt - (deriv.y * cos_az * cos_alt - deriv.x * sin_az * cos_alt)) / sqrt(1.0 + dot(deriv, deriv));
    float shade = clamp(cang, 0.0, 1.0);

    // Blend shadow and highlight based on intensity
    if (shade > 0.5) {
        fragColor = props.highlights[0] * (2.0 * shade - 1.0);
    } else {
        fragColor = props.shadows[0] * (1.0 - 2.0 * shade);
    }
}

// Multidirectional hillshade (Method 3: MULTIDIRECTIONAL)
void multidirectional_hillshade(vec2 deriv, float exaggeration, int num_lights) {
    deriv = deriv * exaggeration * 2.0;
    vec4 total_color = vec4(0.0, 0.0, 0.0, 0.0);

    int count = min(num_lights, 4);

    // Iterate through all light sources
    for (int i = 0; i < 4; i++) {
        if (i >= count) break;

        // Select the light's altitude and azimuth from the vec4 UBOs: a local
        // array indexed by the loop can live in scratch memory.
        float altitude = i == 0 ? props.altitudes.x : i == 1 ? props.altitudes.y : i == 2 ? props.altitudes.z : props.altitudes.w;
        float azimuth = i == 0 ? props.azimuths.x : i == 1 ? props.azimuths.y : i == 2 ? props.azimuths.z : props.azimuths.w;

        float cos_alt = cos(altitude);
        float sin_alt = sin(altitude);
        // Negate cos/sin azimuth for correct light direction
        float cos_az = -cos(azimuth);
        float sin_az = -sin(azimuth);

        // Calculate the cosine of the angle between the light vector and the surface normal
        float cang = (sin_alt - (deriv.y * cos_az * cos_alt - deriv.x * sin_az * cos_alt)) / sqrt(1.0 + dot(deriv, deriv));
        float shade = clamp(cang, 0.0, 1.0);

        // Accumulate shadow/highlight contribution from each light
        if (shade > 0.5) {
            total_color += props.highlights[i] * (2.0 * shade - 1.0) / float(count);
        } else {
            total_color += props.shadows[i] * (1.0 - 2.0 * shade) / float(count);
        }
    }

    fragColor = total_color;
}

// Combined shadow and highlight method (Method 1: COMBINED)
void combined_hillshade(vec2 deriv, float exaggeration) {
    // Only supports one light source (index 0)
    deriv = deriv * exaggeration * 2.0;
    float azimuth = props.azimuths.x + PI;
    float cos_az = cos(azimuth);
    float sin_az = sin(azimuth);
    float cos_alt = cos(props.altitudes.x);
    float sin_alt = sin(props.altitudes.x);

    // Calculate the angle between the light vector and the surface normal
    float cang = acos((sin_alt - (deriv.y * cos_az * cos_alt - deriv.x * sin_az * cos_alt)) / sqrt(1.0 + dot(deriv, deriv)));

    cang = clamp(cang, 0.0, PI / 2.0);

    // Calculate shade and highlight components from angle and slope magnitude
    float shade = cang * atan(length(deriv)) * 4.0 / PI / PI;
    float highlight = (PI / 2.0 - cang) * atan(length(deriv)) * 4.0 / PI / PI;

    fragColor = props.shadows[0] * shade + props.highlights[0] * highlight;
}

// Igor's shadow/highlight method (Method 2: IGOR)
void igor_hillshade(vec2 deriv, float exaggeration) {
    // Only supports one light source (index 0)
    deriv = deriv * exaggeration * 2.0;
    float aspect = get_aspect(deriv);
    float azimuth = props.azimuths.x + PI;

    // Slope strength is magnitude of slope vector, normalized to [0, 1]
    float slope_strength = atan(length(deriv)) * 2.0 / PI;

    // Aspect strength is difference between aspect and light azimuth, normalized to [0, 1]
    float aspect_strength = 1.0 - abs(mod((aspect + azimuth) / PI + 0.5, 2.0) - 1.0);

    float shadow_strength = slope_strength * aspect_strength;
    float highlight_strength = slope_strength * (1.0 - aspect_strength);

    fragColor = props.shadows[0] * shadow_strength + props.highlights[0] * highlight_strength;
}

// Writes to `fragColor` the color of the slope `deriv`, shaded as
// `method`/`exaggeration`/`num_lights` say by the lights of `props`.
void hillshade(vec2 deriv, float exaggeration, int num_lights, int method) {
    if (method == BASIC) {
        basic_hillshade(deriv, exaggeration);
    } else if (method == COMBINED) {
        combined_hillshade(deriv, exaggeration);
    } else if (method == IGOR) {
        igor_hillshade(deriv, exaggeration);
    } else if (method == MULTIDIRECTIONAL) {
        multidirectional_hillshade(deriv, exaggeration, num_lights);
    } else {
        standard_hillshade(deriv, exaggeration);
    }
}
"
    };
}
pub(crate) use crate::terrain_glsl_hillshade_shading as hillshade_shading;

/// The terrain's surface: a tile's grid, raised to the heights of the tile's
/// DEM with its skirts lowered and projected through the tile's projection,
/// in the colors of the tile's drape. A pole's vertices stand at sea level.
/// GL stores the drape's rows bottom first, so GL samples it at `1 - v`.
/// Where the tile's `lightVector` has lights, the drape holds a hillshade's
/// slopes, premultiplied by its coverage, which the surface shades with them.
/// The fog of `terrain` covers it.
pub(crate) const TERRAIN: GlslSource = GlslSource {
    vertex: concat!(
        terrain_props!(),
        r"

MLN_LOC(0) out vec2 v_drape_pos;
// How far along the view, in pixels: the clip w.
MLN_LOC(1) out highp float v_view_depth;
// North-to-south position within the tile itself (0..1), for latitude.
MLN_LOC(2) out float v_tile_y;

void main() {
    vec2 pos = vec2(a_pos.xy);
    float skirt = float(a_pos.z);
    float height = surface_height(pos, MLN_ELEM(drawableVector).dem_coords);
    vec2 tile_pos = clamp(pos / 8192.0, vec2(0.0), vec2(1.0));
    gl_Position = projectTileFor3D(pos, height - skirt * terrain.skirt_length);
    vec2 drape_pos = tile_pos * MLN_ELEM(drawableVector).drape_coords.x + MLN_ELEM(drawableVector).drape_coords.yz;
#ifdef MLN_GL
    v_drape_pos = vec2(drape_pos.x, 1.0 - drape_pos.y);
#else
    v_drape_pos = drape_pos;
#endif
    v_view_depth = gl_Position.w;
    v_tile_y = tile_pos.y;
}
"
    ),
    fragment: concat!(
        terrain_fog!(),
        r"

MLN_LOC(0) in vec2 v_drape_pos;
MLN_LOC(1) in highp float v_view_depth;
MLN_LOC(2) in float v_tile_y;

",
        hillshade_shading!(),
        r"
void main() {
    vec4 color = texture(u_drape, v_drape_pos);
    int num_lights = MLN_ELEM(lightVector).num_lights;
    if (num_lights == 0 || color.a == 0.0) {
        fragColor = fogged(color, v_view_depth);
        return;
    }
    // The tile's latitudes run from its north edge, where the drape's rows
    // start.
    float latitude = mix(MLN_ELEM(lightVector).latrange.x, MLN_ELEM(lightVector).latrange.y, v_tile_y);
    vec2 deriv = ((color.rg / color.a - 128.0 / 255.0) * 8.0) / cos(radians(latitude));
    hillshade(deriv, MLN_ELEM(lightVector).exaggeration, num_lights, MLN_ELEM(lightVector).method);
    fragColor = fogged(fragColor * color.a, v_view_depth);
}
"
    ),
};

pub(crate) const TERRAIN_ES: GlslEsSource = TERRAIN.es(&TERRAIN_DECLARATIONS);

/// The ground's depth: the surface's grid, raised and projected as
/// `TERRAIN` does, writing each pixel's eye distance, an `f32`'s bits,
/// least significant byte first, as the texel's channels.
pub(crate) const TERRAIN_DEPTH: GlslSource = GlslSource {
    vertex: concat!(
        terrain_props!(),
        r"

// The eye distance, which interpolates exactly across a triangle.
MLN_LOC(0) out highp float v_distance;

void main() {
    vec2 pos = vec2(a_pos.xy);
    float skirt = float(a_pos.z);
    float height = surface_height(pos, MLN_ELEM(drawableVector).dem_coords);
    gl_Position = projectTileFor3D(pos, height - skirt * terrain.skirt_length);
    v_distance = gl_Position.w;
}
"
    ),
    fragment: r"

MLN_LOC(0) in highp float v_distance;

void main() {
    highp uint bits = floatBitsToUint(v_distance);
    highp uvec4 bytes = uvec4(bits, bits >> 8u, bits >> 16u, bits >> 24u) & uvec4(255u);
    fragColor = vec4(bytes) / 255.0;
}
",
};

pub(crate) const TERRAIN_DEPTH_ES: GlslEsSource = TERRAIN_DEPTH.es(&TERRAIN_DECLARATIONS);