1use super::expr::{eval_filter, eval_property, is_data_driven, Color, Ctx, Kind, Val};
11use super::gl::{
12 raster_gl_line, raster_polygon, raster_triangle, smoothstep, Cap, Clip, Dash, Framebuffer, Join,
13 LineBuilder, Vert, ATLAS_W, EXTENT,
14};
15use super::mvt::{self, Feature, Geometry, Tile};
16use super::svg;
17use super::symbol::{self, SymbolAssets, SymbolTile};
18use crate::tile_fetcher::TileCoord;
19use serde_json::Value as Json;
20
21const EARTH_HALF: f64 = 20_037_508.342_789_244;
22const EARTH_CIRC: f64 = 2.0 * EARTH_HALF;
23pub const TILE_PX: f64 = 512.0;
25
26pub fn scale_zoom(bbox: [f64; 4], width: u32) -> f64 {
28 let mpp = (bbox[2] - bbox[0]) / width as f64;
29 let z = (EARTH_CIRC / (TILE_PX * mpp)).log2();
30 if (z - z.round()).abs() < 1e-3 {
33 z.round()
34 } else {
35 z
36 }
37}
38
39pub fn covering_tiles(bbox: [f64; 4], z: u8) -> Vec<(TileCoord, i32)> {
43 let n = 1i64 << z;
44 let col = |x: f64| ((x + EARTH_HALF) / EARTH_CIRC * n as f64).floor() as i64;
45 let row = |y: f64| (((EARTH_HALF - y) / EARTH_CIRC * n as f64).floor() as i64).clamp(0, n - 1);
46 let (x0, x1) = (col(bbox[0]), col(bbox[2]));
47 let (y0, y1) = (row(bbox[3]), row(bbox[1]));
48 let mut out = Vec::new();
49 for x in x0..=x1 {
50 for y in y0..=y1 {
51 let c = TileCoord { z, x: x.rem_euclid(n) as u32, y: y as u32 };
52 out.push((c, x.div_euclid(n) as i32));
53 }
54 }
55 out
56}
57
58pub fn tile_zoom(scale_zoom: f64, source_maxzoom: Option<u8>) -> u8 {
60 let z = scale_zoom.floor().clamp(0.0, 22.0) as u8;
61 source_maxzoom.map_or(z, |m| z.min(m))
62}
63
64struct PlacedTile {
65 coord: TileCoord,
66 wrap: i32,
68 tile: Tile,
69 ox: f64,
71 oy: f64,
72 unit_px: f64,
74 clip: Clip,
75 overscaling: f64,
76 ratio: f64,
79}
80
81pub fn device_px(css: u32, ratio: f64) -> u32 {
84 ((css as f64 * ratio).round() as u32).max(1)
85}
86
87pub struct RasterTiles {
89 pub zoom: u8,
90 pub tiles: Vec<(TileCoord, Vec<u8>)>,
91}
92
93#[derive(Default)]
96pub struct SourceTiles {
97 pub vector: std::collections::HashMap<String, Vec<(TileCoord, i32, Vec<u8>)>>,
98 pub raster: std::collections::HashMap<String, RasterTiles>,
99 pub dem: std::collections::HashMap<String, super::hillshade::DemTiles>,
101}
102
103impl SourceTiles {
104 pub fn single_vector(id: &str, tiles: Vec<(TileCoord, i32, Vec<u8>)>) -> Self {
106 let mut s = SourceTiles::default();
107 s.vector.insert(id.to_owned(), tiles);
108 s
109 }
110}
111
112type Placed = std::collections::HashMap<String, Vec<PlacedTile>>;
114
115fn layer_tiles<'a>(placed: &'a Placed, layer: &Json) -> &'a [PlacedTile] {
117 layer["source"].as_str().and_then(|s| placed.get(s)).map_or(&[], |v| v.as_slice())
118}
119
120pub struct RenderOutput {
121 pub width: u32,
123 pub height: u32,
124 pub pixels: Vec<u8>,
125 pub skipped_layer_types: Vec<String>,
127}
128
129fn prepare(sources: &SourceTiles, bbox: [f64; 4], width: u32, height: u32, ratio: f64) -> (f64, Placed) {
133 let zoom = scale_zoom(bbox, width);
134 let placed = sources
135 .vector
136 .iter()
137 .map(|(id, tiles)| (id.clone(), place_tiles(tiles, bbox, width, height, ratio, zoom)))
138 .collect();
139 (zoom, placed)
140}
141
142fn place_tiles(
143 tiles: &[(TileCoord, i32, Vec<u8>)],
144 bbox: [f64; 4],
145 width: u32,
146 height: u32,
147 ratio: f64,
148 zoom: f64,
149) -> Vec<PlacedTile> {
150 let world_px = TILE_PX * 2f64.powf(zoom);
151 let cx = ((bbox[0] + bbox[2]) / 2.0 + EARTH_HALF) / EARTH_CIRC * world_px;
152 let cy = (EARTH_HALF - (bbox[1] + bbox[3]) / 2.0) / EARTH_CIRC * world_px;
153 let view_x0 = cx - width as f64 / 2.0;
154 let view_y0 = cy - height as f64 / 2.0;
155 let mut placed = Vec::with_capacity(tiles.len());
156 for (c, wrap, bytes) in tiles {
157 let tile = match mvt::decode(bytes) {
158 Ok(t) => t,
159 Err(e) => {
160 log::warn!("skipping undecodable tile {}/{}/{}: {e}", c.z, c.x, c.y);
161 continue;
162 }
163 };
164 let tile_px = world_px / 2f64.powi(c.z as i32);
165 let ox = (c.x as f64 + (*wrap as f64) * 2f64.powi(c.z as i32)) * tile_px - view_x0;
166 let oy = c.y as f64 * tile_px - view_y0;
167 placed.push(PlacedTile {
168 coord: *c,
169 wrap: *wrap,
170 tile,
171 ox: ox * ratio,
172 oy: oy * ratio,
173 unit_px: tile_px / EXTENT * ratio,
174 clip: Clip { x0: ox * ratio, y0: oy * ratio, x1: (ox + tile_px) * ratio, y1: (oy + tile_px) * ratio },
175 overscaling: 2f64.powi((zoom.floor() as i32 - c.z as i32).max(0)),
176 ratio,
177 });
178 }
179 placed
180}
181
182fn symbol_tiles(placed: &Placed) -> Vec<SymbolTile<'_>> {
183 let mut ids: Vec<&String> = placed.keys().collect();
184 ids.sort();
185 ids.into_iter()
186 .flat_map(|id| placed[id].iter().map(move |p| (id, p)))
187 .map(|(id, p)| SymbolTile {
188 source: id.as_str(),
189 coord: (p.coord.z, p.coord.x, p.coord.y),
190 wrap: p.wrap,
191 tile: &p.tile,
192 ox: p.ox / p.ratio,
193 oy: p.oy / p.ratio,
194 unit_px: p.unit_px / p.ratio,
195 overscaling: p.overscaling,
196 })
197 .collect()
198}
199
200#[allow(clippy::too_many_arguments)]
206pub fn render(
207 style: &Json,
208 sources: &SourceTiles,
209 assets: &SymbolAssets,
210 bbox: [f64; 4],
211 width: u32,
212 height: u32,
213 ratio: f64,
214) -> Result<RenderOutput, String> {
215 let (zoom, placed) = prepare(sources, bbox, width, height, ratio);
216 let (dw, dh) = (device_px(width, ratio), device_px(height, ratio));
217 let mut fb = Framebuffer::new(dw as usize, dh as usize);
218 let mut depth3d: Vec<f64> = Vec::new();
219
220 let placement = symbol::place(style, &symbol_tiles(&placed), assets, zoom, width as f64, height as f64);
222
223 let mut skipped: Vec<String> = Vec::new();
224 for (layer_idx, layer) in style["layers"].as_array().map(|v| v.as_slice()).unwrap_or(&[]).iter().enumerate() {
225 let ltype = layer["type"].as_str().unwrap_or("");
226 if layer["layout"]["visibility"] == "none" {
227 continue;
228 }
229 if layer["minzoom"].as_f64().map_or(false, |mz| zoom < mz)
230 || layer["maxzoom"].as_f64().map_or(false, |mz| zoom >= mz)
231 {
232 continue;
233 }
234 match ltype {
235 "background" => draw_background(&mut fb, layer, zoom),
236 "fill" => draw_fill_layer(&mut fb, layer, zoom, layer_tiles(&placed, layer), ratio, assets),
237 "line" => draw_line_layer(&mut fb, layer, zoom, layer_tiles(&placed, layer), ratio, assets),
238 "circle" => draw_circle_layer(&mut fb, layer, zoom, layer_tiles(&placed, layer), ratio),
239 "fill-extrusion" => {
240 let view = ExtrusionView::new(style, bbox, width, height, ratio, zoom);
241 draw_fill_extrusion_layer(&mut fb, layer, zoom, layer_tiles(&placed, layer), &view, assets, &mut depth3d);
242 }
243 "raster" => {
244 if let Some(rt) = layer["source"].as_str().and_then(|s| sources.raster.get(s)) {
245 draw_raster_layer(&mut fb, layer, zoom, rt, bbox, ratio);
246 }
247 }
248 "hillshade" => {
249 if let Some(dem) = layer["source"].as_str().and_then(|s| sources.dem.get(s)) {
250 let nearest = super::hillshade::source_nearest(style, layer["source"].as_str().unwrap_or(""), zoom);
251 super::hillshade::draw_layer(&mut fb, layer, zoom, dem, bbox, width, height, ratio, nearest);
252 }
253 }
254 "symbol" => symbol::draw_layer(
255 &mut fb,
256 layer,
257 layer_idx,
258 &placement,
259 assets,
260 ratio,
261 (width as usize, height as usize),
262 ),
263 other => {
264 if !skipped.iter().any(|s| s == other) {
265 skipped.push(other.to_owned());
266 }
267 }
268 }
269 }
270
271 Ok(RenderOutput { width: dw, height: dh, pixels: fb.into_straight_rgba(), skipped_layer_types: skipped })
272}
273
274fn features<'a>(layer: &'a Json, pt: &'a PlacedTile, zoom: f64) -> impl Iterator<Item = (&'a Feature, f64)> + 'a {
277 let src = pt.tile.layers.get(mvt::source_layer(layer));
278 let scale = src.map_or(1.0, |l| EXTENT / l.extent as f64);
279 let feats = src.map(|l| l.features.as_slice()).unwrap_or(&[]);
280 feats.iter().filter_map(move |f| {
281 let ctx = Ctx { zoom, feature: Some(f) };
282 match layer.get("filter") {
283 Some(filter) if !eval_filter(filter, &ctx) => None,
284 _ => Some((f, scale)),
285 }
286 })
287}
288
289#[inline]
291fn to_extent(p: (f32, f32), scale: f64) -> (f64, f64) {
292 ((p.0 as f64 * scale + 0.5).floor(), (p.1 as f64 * scale + 0.5).floor())
293}
294
295enum Prop<'a> {
300 Const(Val),
301 Data(&'a Json, Kind),
302 Absent,
303}
304
305impl<'a> Prop<'a> {
306 fn new(j: Option<&'a Json>, kind: Kind, zoom: f64) -> Self {
307 match j {
308 None | Some(Json::Null) => Prop::Absent,
309 Some(j) if is_data_driven(j) => Prop::Data(j, kind),
310 Some(j) => Prop::Const(eval_property(j, kind, &Ctx { zoom, feature: None })),
311 }
312 }
313
314 fn get(&self, ctx: &Ctx) -> Option<Val> {
315 match self {
316 Prop::Const(v) => Some(v.clone()),
317 Prop::Data(j, k) => Some(eval_property(j, *k, ctx)),
318 Prop::Absent => None,
319 }
320 }
321
322 fn num(&self, ctx: &Ctx, default: f64) -> f64 {
323 self.get(ctx).and_then(|v| v.as_num()).unwrap_or(default)
324 }
325
326 fn color(&self, ctx: &Ctx, default: Color) -> Color {
329 let c = self.get(ctx).and_then(|v| v.as_color()).unwrap_or(default);
330 if matches!(self, Prop::Data(..)) {
331 let q = |v: f32| (v * 255.0).floor().clamp(0.0, 255.0) / 255.0;
332 Color::new(q(c.r), q(c.g), q(c.b), q(c.a))
333 } else {
334 c
335 }
336 }
337
338 fn is_set(&self) -> bool {
339 !matches!(self, Prop::Absent)
340 }
341
342 fn translate(&self, ctx: &Ctx) -> (f64, f64) {
343 match self.get(ctx).and_then(|v| v.as_num_array()) {
344 Some(t) if t.len() == 2 => (t[0], t[1]),
345 _ => (0.0, 0.0),
346 }
347 }
348
349 fn translate_px(&self, ctx: &Ctx, ratio: f64) -> (f64, f64) {
351 let (x, y) = self.translate(ctx);
352 (x * ratio, y * ratio)
353 }
354}
355
356#[inline]
357fn rgba(c: Color, k: f64) -> [f32; 4] {
358 let k = k as f32;
359 [c.r * k, c.g * k, c.b * k, c.a * k]
360}
361
362#[inline]
363fn scaled(c: [f32; 4], a: f64) -> [f32; 4] {
364 let a = a as f32;
365 [c[0] * a, c[1] * a, c[2] * a, c[3] * a]
366}
367
368fn draw_background(fb: &mut Framebuffer, layer: &Json, zoom: f64) {
371 let ctx = Ctx { zoom, feature: None };
372 let p = &layer["paint"];
373 let color = Prop::new(p.get("background-color"), Kind::Color, zoom).color(&ctx, Color::BLACK);
374 let opacity = Prop::new(p.get("background-opacity"), Kind::Number, zoom).num(&ctx, 1.0);
375 let c = rgba(color, opacity);
376 if c[3] <= 0.0 {
377 return;
378 }
379 for y in 0..fb.h {
380 for x in 0..fb.w {
381 fb.blend(x, y, c);
382 }
383 }
384}
385
386type Rings = Vec<Vec<(f64, f64)>>;
389
390fn polys_px(pt: &PlacedTile, f: &Feature, scale: f64, t: (f64, f64)) -> Vec<Rings> {
391 let Geometry::Polygons(polys) = &f.geometry else { return Vec::new() };
392 polys
393 .iter()
394 .map(|poly| {
395 poly.iter()
396 .map(|ring| {
397 ring.iter()
398 .map(|&q| {
399 let (x, y) = to_extent(q, scale);
400 (pt.ox + x * pt.unit_px + t.0, pt.oy + y * pt.unit_px + t.1)
401 })
402 .collect()
403 })
404 .collect()
405 })
406 .collect()
407}
408
409struct PatternFrame {
415 ox: f64,
416 oy: f64,
417 unit_px: f64,
418 tile_ratio: f64,
419 world_x: f64,
420 world_y: f64,
421}
422
423impl PatternFrame {
424 fn new(pt: &PlacedTile) -> Self {
425 let n = 2f64.powi(pt.coord.z as i32);
426 let tile_px = TILE_PX * pt.overscaling;
427 PatternFrame {
428 ox: pt.ox,
429 oy: pt.oy,
430 unit_px: pt.unit_px,
431 tile_ratio: tile_px / EXTENT,
432 world_x: tile_px * (pt.coord.x as f64 + pt.wrap as f64 * n),
433 world_y: tile_px * pt.coord.y as f64,
434 }
435 }
436
437 fn coord(&self, img: &symbol::SpriteImage, x: f64, y: f64, t: (f64, f64)) -> (f64, f64) {
440 let size = (img.w as f64 / img.pixel_ratio, img.h as f64 / img.pixel_ratio);
441 let pos = ((x - t.0 - self.ox) / self.unit_px, (y - t.1 - self.oy) / self.unit_px);
442 (
443 (self.tile_ratio * pos.0 + self.world_x.rem_euclid(size.0)) / size.0,
444 (self.tile_ratio * pos.1 + self.world_y.rem_euclid(size.1)) / size.1,
445 )
446 }
447
448 fn sample(&self, img: &symbol::SpriteImage, x: usize, y: usize, t: (f64, f64)) -> [f64; 4] {
450 let v = self.coord(img, x as f64 + 0.5, y as f64 + 0.5, t);
451 let s = img.sample_wrapped(v.0.rem_euclid(1.0) * img.w as f64, v.1.rem_euclid(1.0) * img.h as f64);
452 [s[0] / 255.0, s[1] / 255.0, s[2] / 255.0, s[3] / 255.0]
453 }
454}
455
456fn draw_fill_layer(fb: &mut Framebuffer, layer: &Json, zoom: f64, placed: &[PlacedTile], dpr: f64, assets: &SymbolAssets) {
457 let p = &layer["paint"];
458 let color = Prop::new(p.get("fill-color"), Kind::Color, zoom);
459 let opacity = Prop::new(p.get("fill-opacity"), Kind::Number, zoom);
460 let outline = Prop::new(p.get("fill-outline-color"), Kind::Color, zoom);
461 let translate = Prop::new(p.get("fill-translate"), Kind::Array, zoom);
462 let antialias = p["fill-antialias"].as_bool().unwrap_or(true);
463 let pattern = Prop::new(p.get("fill-pattern"), Kind::Enum, zoom);
464 if pattern.is_set() {
465 return draw_fill_pattern_layer(fb, layer, zoom, placed, dpr, assets, &pattern, &opacity, &outline, &translate, antialias);
466 }
467
468 let opaque = matches!(&color, Prop::Const(v) if v.as_color().map_or(false, |c| c.a == 1.0))
471 && match &opacity {
472 Prop::Absent => true,
473 Prop::Const(v) => v.as_num() == Some(1.0),
474 Prop::Data(..) => false,
475 };
476 let cull_outline = opaque && !outline.is_set();
477 let (w, h) = (fb.w, fb.h);
478 let mut covered = if cull_outline { vec![false; w * h] } else { Vec::new() };
479
480 for pt in placed {
482 for (f, scale) in features(layer, pt, zoom) {
483 let ctx = Ctx { zoom, feature: Some(f) };
484 let c = rgba(color.color(&ctx, Color::BLACK), opacity.num(&ctx, 1.0));
485 if c[3] <= 0.0 {
486 continue;
487 }
488 for poly in polys_px(pt, f, scale, translate.translate_px(&ctx, dpr)) {
489 raster_polygon(w, h, &poly, &pt.clip, |x, y| {
490 fb.blend(x, y, c);
491 if cull_outline {
492 covered[y * w + x] = true;
493 }
494 });
495 }
496 }
497 }
498
499 if !antialias {
501 return;
502 }
503 for pt in placed {
504 for (f, scale) in features(layer, pt, zoom) {
505 let ctx = Ctx { zoom, feature: Some(f) };
506 let oc = if outline.is_set() { outline.color(&ctx, Color::BLACK) } else { color.color(&ctx, Color::BLACK) };
507 let base = rgba(oc, opacity.num(&ctx, 1.0));
508 if base[3] <= 0.0 {
509 continue;
510 }
511 for poly in polys_px(pt, f, scale, translate.translate_px(&ctx, dpr)) {
512 for ring in &poly {
513 for seg in ring.windows(2) {
514 raster_gl_line(w, h, seg[0], seg[1], &pt.clip, |x, y, d| {
515 if cull_outline && covered[y * w + x] {
516 return;
517 }
518 fb.blend(x, y, scaled(base, 1.0 - smoothstep(0.0, 1.0, d)));
519 });
520 }
521 }
522 }
523 }
524 }
525}
526
527#[allow(clippy::too_many_arguments)]
532fn draw_fill_pattern_layer(
533 fb: &mut Framebuffer,
534 layer: &Json,
535 zoom: f64,
536 placed: &[PlacedTile],
537 dpr: f64,
538 assets: &SymbolAssets,
539 pattern: &Prop,
540 opacity: &Prop,
541 outline: &Prop,
542 translate: &Prop,
543 antialias: bool,
544) {
545 let (w, h) = (fb.w, fb.h);
546 let image_of = |ctx: &Ctx| -> Option<&symbol::SpriteImage> {
547 match pattern.get(ctx)? {
548 Val::Str(name) => assets.sprite.images.get(&name),
549 _ => None,
550 }
551 };
552 for pass_outline in [false, true] {
553 if pass_outline && !antialias {
554 break;
555 }
556 for pt in placed {
557 let frame = PatternFrame::new(pt);
558 for (f, scale) in features(layer, pt, zoom) {
559 let ctx = Ctx { zoom, feature: Some(f) };
560 let Some(img) = image_of(&ctx) else { continue };
561 let op = opacity.num(&ctx, 1.0);
562 if op <= 0.0 {
563 continue;
564 }
565 let t = translate.translate_px(&ctx, dpr);
566 let polys = polys_px(pt, f, scale, t);
567 if !pass_outline {
568 for poly in &polys {
569 raster_polygon(w, h, poly, &pt.clip, |x, y| {
570 let c = frame.sample(img, x, y, t);
571 fb.blend(x, y, [(c[0] * op) as f32, (c[1] * op) as f32, (c[2] * op) as f32, (c[3] * op) as f32]);
572 });
573 }
574 continue;
575 }
576 let plain = outline.is_set().then(|| rgba(outline.color(&ctx, Color::BLACK), op));
577 for poly in &polys {
578 for ring in poly {
579 for seg in ring.windows(2) {
580 raster_gl_line(w, h, seg[0], seg[1], &pt.clip, |x, y, d| {
581 let k = 1.0 - smoothstep(0.0, 1.0, d);
582 let c = match plain {
583 Some(c) => scaled(c, k),
584 None => {
585 let s = frame.sample(img, x, y, t);
586 let m = op * k;
587 [(s[0] * m) as f32, (s[1] * m) as f32, (s[2] * m) as f32, (s[3] * m) as f32]
588 }
589 };
590 fb.blend(x, y, c);
591 });
592 }
593 }
594 }
595 }
596 }
597 }
598}
599
600fn draw_line_layer(fb: &mut Framebuffer, layer: &Json, zoom: f64, placed: &[PlacedTile], dpr: f64, assets: &SymbolAssets) {
603 let p = &layer["paint"];
604 let pattern = Prop::new(p.get("line-pattern"), Kind::Enum, zoom);
606 let l = &layer["layout"];
607 let color = Prop::new(p.get("line-color"), Kind::Color, zoom);
608 let opacity = Prop::new(p.get("line-opacity"), Kind::Number, zoom);
609 let width = Prop::new(p.get("line-width"), Kind::Number, zoom);
610 let floor_width = Prop::new(p.get("line-width"), Kind::Number, zoom.floor());
611 let gap = Prop::new(p.get("line-gap-width"), Kind::Number, zoom);
612 let offset = Prop::new(p.get("line-offset"), Kind::Number, zoom);
613 let blur = Prop::new(p.get("line-blur"), Kind::Number, zoom);
614 let translate = Prop::new(p.get("line-translate"), Kind::Array, zoom);
615 let dasharray = Prop::new(p.get("line-dasharray"), Kind::Enum, zoom);
618 let tz = zoom.floor();
619 let cap = match super::expr::layout_enum(l, "line-cap", tz).as_deref() {
620 Some("round") => Cap::Round,
621 Some("square") => Cap::Square,
622 _ => Cap::Butt,
623 };
624 let join = match super::expr::layout_enum(l, "line-join", tz).as_deref() {
625 Some("round") => Join::Round,
626 Some("bevel") => Join::Bevel,
627 _ => Join::Miter,
628 };
629 let miter_limit = l["line-miter-limit"].as_f64().unwrap_or(2.0);
630 let round_limit = l["line-round-limit"].as_f64().unwrap_or(1.05);
631
632 let dash = match &dasharray {
635 Prop::Const(v) => v
636 .as_num_array()
637 .filter(|d| d.len() >= 2 && d.iter().sum::<f64>() > 0.0)
638 .map(|d| Dash::new(&d, cap == Cap::Round)),
639 _ => None,
640 };
641 let from_scale = if zoom > zoom.floor() { 2.0 } else { 0.5 };
642
643 let (w, h) = (fb.w, fb.h);
644 for pt in placed {
645 for (f, scale) in features(layer, pt, zoom) {
646 let ctx = Ctx { zoom, feature: Some(f) };
647 let fctx = Ctx { zoom: zoom.floor(), feature: Some(f) };
648 let (lines, is_polygon): (Vec<&Vec<(f32, f32)>>, bool) = match &f.geometry {
649 Geometry::Lines(ls) => (ls.iter().collect(), false),
650 Geometry::Polygons(ps) => (ps.iter().flatten().collect(), true),
651 Geometry::Points(_) => continue,
652 };
653 let image = if pattern.is_set() {
654 match pattern.get(&ctx) {
655 Some(Val::Str(name)) => match assets.sprite.images.get(&name) {
656 Some(img) => Some(img),
657 None => continue,
658 },
659 _ => continue,
660 }
661 } else {
662 None
663 };
664 let op = opacity.num(&ctx, 1.0);
665 let c = if image.is_some() { [op as f32; 4] } else { rgba(color.color(&ctx, Color::BLACK), op) };
666 if c[3] <= 0.0 {
667 continue;
668 }
669 let lw_css = width.num(&ctx, 1.0);
672 let lw = lw_css * dpr;
673 let gapw = gap.num(&ctx, 0.0) * dpr / 2.0;
675 let halfwidth = lw / 2.0;
676 let line_offset = -offset.num(&ctx, 0.0) * dpr;
677 let aa = 0.5; let inset = gapw + if gapw > 0.0 { aa } else { 0.0 };
679 let outset =
680 gapw + halfwidth * if gapw > 0.0 { 2.0 } else { 1.0 } + if halfwidth == 0.0 { 0.0 } else { aa };
681 if outset <= 0.0 {
682 continue;
683 }
684 let blur2 = blur.num(&ctx, 0.0) * dpr + 1.0;
685 let floorwidth = floor_width.num(&fctx, lw_css);
687 let (tx, ty) = translate.translate_px(&ctx, dpr);
688
689 let pattern_params = image.map(|img| {
694 let tile_ratio = TILE_PX * pt.overscaling / EXTENT;
695 let (dw, dh) = (img.w as f64 / img.pixel_ratio, img.h as f64 / img.pixel_ratio);
696 (img, tile_ratio * dh / (dw * floorwidth))
697 });
698 let dash_params = dash.as_ref().filter(|_| image.is_none()).map(|d| {
699 let width_b = d.width;
700 let width_a = d.width * from_scale;
701 let sdfgamma = ATLAS_W as f64 / (width_a.min(width_b) * 256.0 * dpr) / 2.0;
702 let tile_ratio = TILE_PX * pt.overscaling / EXTENT;
705 (d, tile_ratio / width_b / floorwidth, sdfgamma / floorwidth)
706 });
707
708 let mut b = LineBuilder::new(pt.overscaling);
709 for line in &lines {
710 let pts: Vec<(f64, f64)> = line.iter().map(|&q| to_extent(q, scale)).collect();
711 b.add_line(&pts, is_polygon, join, cap, miter_limit, round_limit);
712 }
713
714 let verts: Vec<Vert<3>> = b
716 .verts
717 .iter()
718 .map(|v| {
719 let ny = if v.up { 1.0 } else { -1.0 };
720 let u = 0.5 * v.dir;
721 let t = 1.0 - u.abs();
722 let (ox, oy) = (line_offset * v.ex * ny, line_offset * v.ey * ny);
723 let offset2 = (ox * t - oy * u, ox * u + oy * t);
724 let dist = (outset * v.ex, outset * v.ey);
725 Vert {
726 x: pt.ox + v.x * pt.unit_px + offset2.0 + dist.0 + tx,
727 y: pt.oy + v.y * pt.unit_px + offset2.1 + dist.1 + ty,
728 v: [if v.round { 1.0 } else { 0.0 }, ny, v.linesofar],
729 }
730 })
731 .collect();
732
733 for tri in &b.tris {
734 let t = [verts[tri[0] as usize], verts[tri[1] as usize], verts[tri[2] as usize]];
735 raster_triangle(w, h, t, &pt.clip, |x, y, var| {
736 let d = (var[0] * var[0] + var[1] * var[1]).sqrt() * outset;
738 let mut alpha = ((d - (inset - blur2)).min(outset - d) / blur2).clamp(0.0, 1.0);
739 if let Some((dash, sx, g)) = dash_params {
740 let sdf = dash.sample(var[2] * sx, dash.n as f64 * (1.0 - var[1]));
741 alpha *= smoothstep(0.5 - g, 0.5 + g, sdf);
742 }
743 if alpha > 0.0 {
744 if let Some((img, k)) = pattern_params {
745 let xb = (var[2] * k).rem_euclid(1.0);
746 let yb = 0.5 * var[1] + 0.5;
747 let s = img.sample_atlas_pattern((img.w as f64 + 2.0) * xb, (img.h as f64 + 2.0) * yb);
748 let m = alpha * op / 255.0;
749 fb.blend(x, y, [(s[0] * m) as f32, (s[1] * m) as f32, (s[2] * m) as f32, (s[3] * m) as f32]);
750 } else {
751 fb.blend(x, y, scaled(c, alpha));
752 }
753 }
754 });
755 }
756 }
757 }
758}
759
760struct ExtrusionView {
768 cx: f64,
770 cy: f64,
771 d: f64,
773 px_per_m: f64,
775 light_pos: [f64; 3],
777 light_color: [f64; 3],
778 light_intensity: f64,
779}
780
781impl ExtrusionView {
782 fn new(style: &Json, bbox: [f64; 4], width: u32, height: u32, ratio: f64, zoom: f64) -> Self {
783 let world = TILE_PX * 2f64.powf(zoom);
784 let lat = (2.0 * (((bbox[1] + bbox[3]) / 2.0) / (EARTH_CIRC / (2.0 * std::f64::consts::PI))).exp().atan()
785 - std::f64::consts::FRAC_PI_2)
786 .to_degrees();
787 let maplibre_circ = 2.0 * std::f64::consts::PI * 6_371_008.8;
788 let fov: f64 = 0.643_501_108_793_284_4;
789 let light = &style["light"];
790 let ctx = Ctx { zoom, feature: None };
791 let pos = light.get("position").map(|j| eval_property(j, Kind::Array, &ctx)).and_then(|v| v.as_num_array());
792 let pos = pos.filter(|p| p.len() == 3).unwrap_or_else(|| vec![1.15, 210.0, 30.0]);
793 let az = (pos[1] + 90.0).to_radians();
795 let polar = pos[2].to_radians();
796 let light_pos = [pos[0] * az.cos() * polar.sin(), pos[0] * az.sin() * polar.sin(), pos[0] * polar.cos()];
797 let color = light
798 .get("color")
799 .map(|j| eval_property(j, Kind::Color, &ctx))
800 .and_then(|v| v.as_color())
801 .unwrap_or(Color::new(1.0, 1.0, 1.0, 1.0));
802 let intensity = light.get("intensity").map(|j| eval_property(j, Kind::Number, &ctx)).and_then(|v| v.as_num()).unwrap_or(0.5);
803 ExtrusionView {
804 cx: width as f64 * ratio / 2.0,
805 cy: height as f64 * ratio / 2.0,
806 d: 0.5 / (fov / 2.0).tan() * height as f64,
807 px_per_m: world / (maplibre_circ * lat.to_radians().cos()),
808 light_pos,
809 light_color: [color.r as f64, color.g as f64, color.b as f64],
810 light_intensity: intensity,
811 }
812 }
813
814 fn project(&self, p: (f64, f64), h: f64) -> (f64, f64, f64) {
817 let z = h * self.px_per_m;
818 let s = self.d / (self.d - z);
819 (self.cx + (p.0 - self.cx) * s, self.cy + (p.1 - self.cy) * s, 1.0 / (self.d - z))
820 }
821
822 #[allow(clippy::too_many_arguments)]
825 fn shade(&self, color: [f64; 4], normal: (f64, f64, f64), t: f64, base: f64, height: f64, vertical_gradient: bool) -> [f64; 3] {
826 let i = self.light_intensity;
827 let colorvalue = color[0] * 0.2126 + color[1] * 0.7152 + color[2] * 0.0722;
828 let c = [color[0] + 0.03, color[1] + 0.03, color[2] + 0.03];
829 let lp = self.light_pos;
830 let mut directional = (normal.0 * lp[0] + normal.1 * lp[1] + normal.2 * lp[2]).clamp(0.0, 1.0);
831 let hi = (1.0 - colorvalue + i).max(1.0);
832 directional = (1.0 - i) * (1.0 - directional) + hi * directional;
833 if normal.1 != 0.0 {
834 let vg = if vertical_gradient { 1.0 } else { 0.0 };
835 let lo = 0.7 * i + 0.98 * (1.0 - i);
836 directional *= (1.0 - vg) + vg * ((t + base) * (height / 150.0).sqrt()).clamp(lo, 1.0);
837 }
838 let mut out = [0.0; 3];
839 for k in 0..3 {
840 let lc = self.light_color[k];
841 out[k] = (c[k] * directional * lc).clamp(0.3 * (1.0 - lc), 1.0);
842 }
843 out
844 }
845}
846
847impl ExtrusionView {
848 fn shade_pattern(&self, normal: (f64, f64, f64), t: f64, base: f64, height: f64, vertical_gradient: bool) -> [f64; 3] {
851 let i = self.light_intensity;
852 let lp = self.light_pos;
853 let mut directional = (normal.0 * lp[0] + normal.1 * lp[1] + normal.2 * lp[2]).clamp(0.0, 1.0);
854 let hi = (0.5 + i).max(1.0);
855 directional = (1.0 - i) * (1.0 - directional) + hi * directional;
856 if normal.1 != 0.0 {
857 let vg = if vertical_gradient { 1.0 } else { 0.0 };
858 let lo = 0.7 * i + 0.98 * (1.0 - i);
859 directional *= (1.0 - vg) + vg * ((t + base) * (height / 150.0).sqrt()).clamp(lo, 1.0);
860 }
861 let mut out = [0.0; 3];
862 for k in 0..3 {
863 let lc = self.light_color[k];
864 out[k] = (directional * lc).clamp(0.3 * (1.0 - lc), 1.0);
865 }
866 out
867 }
868
869 fn unproject(&self, x: f64, y: f64, h: f64) -> (f64, f64) {
872 let s = self.d / (self.d - h * self.px_per_m);
873 (self.cx + (x - self.cx) / s, self.cy + (y - self.cy) / s)
874 }
875}
876
877fn ring_entirely_outside(ring: &[(f64, f64)]) -> bool {
879 let e = EXTENT;
880 ring.iter().all(|p| p.0 < 0.0) || ring.iter().all(|p| p.0 > e) || ring.iter().all(|p| p.1 < 0.0) || ring.iter().all(|p| p.1 > e)
881}
882
883#[allow(clippy::too_many_arguments)]
889fn draw_fill_extrusion_layer(
890 fb: &mut Framebuffer,
891 layer: &Json,
892 zoom: f64,
893 placed: &[PlacedTile],
894 view: &ExtrusionView,
895 assets: &SymbolAssets,
896 depth: &mut Vec<f64>,
897) {
898 let p = &layer["paint"];
899 let color = Prop::new(p.get("fill-extrusion-color"), Kind::Color, zoom);
900 let height = Prop::new(p.get("fill-extrusion-height"), Kind::Number, zoom);
901 let base = Prop::new(p.get("fill-extrusion-base"), Kind::Number, zoom);
902 let opacity = Prop::new(p.get("fill-extrusion-opacity"), Kind::Number, zoom).num(&Ctx { zoom, feature: None }, 1.0);
903 let vertical_gradient = p["fill-extrusion-vertical-gradient"].as_bool().unwrap_or(true);
904 let pattern = Prop::new(p.get("fill-extrusion-pattern"), Kind::Enum, zoom);
907 let patterned = pattern.is_set();
908 if opacity <= 0.0 {
909 return;
910 }
911 let (w, h) = (fb.w, fb.h);
912 let full = Clip { x0: 0.0, y0: 0.0, x1: w as f64, y1: h as f64 };
913
914 let mut tris: Vec<[Vert<6>; 3]> = Vec::new();
917 let mut tops: Vec<(Rings, f64, [f64; 3], f64)> = Vec::new();
920 type Pat<'a> = Option<(Option<&'a symbol::SpriteImage>, usize)>;
922 let mut frames: Vec<PatternFrame> = Vec::new();
923 enum Piece<'a> {
925 Tris(usize, usize, Pat<'a>),
926 Top(usize, Pat<'a>),
927 }
928 let mut order: Vec<Piece> = Vec::new();
929 for pt in placed {
930 let frame = PatternFrame::new(pt);
931 let height_factor = -(2f64.powi(pt.coord.z as i32)) / TILE_PX / 8.0;
935 let world = (frame.world_x, frame.world_y);
936 let tile_ratio = frame.tile_ratio;
937 frames.push(frame);
938 let fi = frames.len() - 1;
939 for (f, scale) in features(layer, pt, zoom) {
940 let Geometry::Polygons(polys) = &f.geometry else { continue };
941 let ctx = Ctx { zoom, feature: Some(f) };
942 let img = match pattern.get(&ctx) {
945 Some(Val::Str(name)) if patterned => assets.sprite.images.get(&name),
946 _ => None,
947 };
948 let pat: Pat = patterned.then_some((img, fi));
949 let size = img.map_or((1.0, 1.0), |i| (i.w as f64 / i.pixel_ratio, i.h as f64 / i.pixel_ratio));
950 let pattern_pos = |pos: (f64, f64)| {
951 (
952 (tile_ratio * pos.0 + world.0.rem_euclid(size.0)) / size.0,
953 (tile_ratio * pos.1 + world.1.rem_euclid(size.1)) / size.1,
954 )
955 };
956 let c = color.color(&ctx, Color::BLACK);
957 let col = [c.r as f64, c.g as f64, c.b as f64, c.a as f64];
958 let hgt = height.num(&ctx, 0.0).max(0.0);
959 let bse = base.num(&ctx, 0.0).max(0.0);
960 for poly in polys {
961 let rings: Vec<Vec<(f64, f64)>> = poly.iter().map(|r| r.iter().map(|&q| to_extent(q, scale)).collect()).collect();
962 if rings.first().map_or(true, |r| ring_entirely_outside(r)) {
963 continue;
964 }
965 let to_px = |q: (f64, f64)| (pt.ox + q.0 * pt.unit_px, pt.oy + q.1 * pt.unit_px);
966 let first = tris.len();
967 for ring in &rings {
968 if ring_entirely_outside(ring) {
969 continue;
970 }
971 let mut edge_distance = 0.0f64;
972 for e in ring.windows(2) {
973 let (p1, p2) = (e[1], e[0]);
975 if (p1.0 == p2.0 && (p1.0 < 0.0 || p1.0 > EXTENT)) || (p1.1 == p2.1 && (p1.1 < 0.0 || p1.1 > EXTENT)) {
976 continue; }
978 let (dx, dy) = (p1.0 - p2.0, p1.1 - p2.1);
979 let len = (dx * dx + dy * dy).sqrt();
980 if edge_distance + len > 32768.0 {
981 edge_distance = 0.0;
982 }
983 let ed1 = edge_distance.trunc();
986 edge_distance += len;
987 let ed2 = (edge_distance.trunc() as i64 as i16) as f64;
988 if len == 0.0 {
989 continue;
990 }
991 let n = (-dy / len, dx / len, 0.0);
993 let ny = (n.1 * 16384.0).trunc() / 16384.0;
994 let vert = |q: (f64, f64), t: f64, ed: f64| -> Vert<6> {
995 let elevation = if t > 0.0 { hgt } else { bse };
996 let (x, y, iw) = view.project(to_px(q), elevation);
997 let s = if patterned {
998 view.shade_pattern((n.0, ny, n.2), t, bse, hgt, vertical_gradient)
999 } else {
1000 view.shade(col, (n.0, ny, n.2), t, bse, hgt, vertical_gradient)
1001 };
1002 let (u, v) = pattern_pos((ed, elevation * height_factor));
1003 Vert { x, y, v: [s[0] * iw, s[1] * iw, s[2] * iw, u * iw, v * iw, iw] }
1004 };
1005 let v = [vert(p1, 0.0, ed1), vert(p1, 1.0, ed1), vert(p2, 0.0, ed2), vert(p2, 1.0, ed2)];
1006 tris.push([v[0], v[2], v[1]]);
1007 tris.push([v[1], v[2], v[3]]);
1008 }
1009 }
1010 order.push(Piece::Tris(first, tris.len(), pat));
1011 let (_, _, iw) = view.project((0.0, 0.0), hgt);
1012 let top: Rings = rings
1013 .iter()
1014 .map(|r| r.iter().map(|&q| { let (x, y, _) = view.project(to_px(q), hgt); (x, y) }).collect())
1015 .collect();
1016 let light = if patterned {
1017 view.shade_pattern((0.0, 0.0, 1.0), 1.0, bse, hgt, vertical_gradient)
1018 } else {
1019 view.shade(col, (0.0, 0.0, 1.0), 1.0, bse, hgt, vertical_gradient)
1020 };
1021 tops.push((top, iw, light, hgt));
1022 order.push(Piece::Top(tops.len() - 1, pat));
1023 }
1024 }
1025 }
1026
1027 if depth.len() != w * h {
1029 *depth = vec![0.0f64; w * h];
1030 }
1031 let mut drawn = vec![false; w * h];
1032 let translucent = opacity < 1.0 || patterned;
1033 let passes: &[bool] = if translucent { &[true, false] } else { &[false] };
1034 for &depth_only in passes {
1035 for piece in &order {
1036 let mut frag = |x: usize, y: usize, iw: f64, rgba: [f64; 4], fb: &mut Framebuffer| {
1037 let k = y * w + x;
1038 if depth_only {
1039 if iw > depth[k] {
1040 depth[k] = iw;
1041 }
1042 return;
1043 }
1044 if translucent {
1045 if iw < depth[k] || drawn[k] {
1046 return;
1047 }
1048 drawn[k] = true;
1049 } else {
1050 if iw < depth[k] {
1051 return;
1052 }
1053 depth[k] = iw;
1054 }
1055 let a = opacity;
1056 fb.blend(x, y, [(rgba[0] * a) as f32, (rgba[1] * a) as f32, (rgba[2] * a) as f32, (rgba[3] * a) as f32]);
1057 };
1058 match piece {
1059 Piece::Tris(a, b, pat) => {
1060 for t in &tris[*a..*b] {
1061 let cross = (t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x);
1064 if cross > 0.0 {
1065 continue;
1066 }
1067 raster_triangle(w, h, *t, &full, |x, y, v| {
1068 let iw = v[5];
1069 if iw > 0.0 {
1070 let c = if depth_only {
1071 [0.0; 4]
1072 } else {
1073 extrusion_texel(*pat, v[3] / iw, v[4] / iw, [v[0] / iw, v[1] / iw, v[2] / iw])
1074 };
1075 frag(x, y, iw, c, fb);
1076 }
1077 });
1078 }
1079 }
1080 Piece::Top(i, pat) => {
1081 let (rings, iw, rgb, hgt) = &tops[*i];
1082 raster_polygon(w, h, rings, &full, |x, y| {
1083 let c = match pat {
1084 Some((Some(img), fi)) if !depth_only => {
1085 let m = view.unproject(x as f64 + 0.5, y as f64 + 0.5, *hgt);
1087 let (u, v) = frames[*fi].coord(img, m.0, m.1, (0.0, 0.0));
1088 extrusion_texel(*pat, u, v, *rgb)
1089 }
1090 _ if depth_only => [0.0; 4],
1091 _ => extrusion_texel(*pat, 0.0, 0.0, *rgb),
1092 };
1093 frag(x, y, *iw, c, fb)
1094 });
1095 }
1096 }
1097 }
1098 }
1099}
1100
1101fn extrusion_texel(pat: Option<(Option<&symbol::SpriteImage>, usize)>, u: f64, v: f64, rgb: [f64; 3]) -> [f64; 4] {
1104 match pat {
1105 Some((None, _)) => [0.0; 4],
1106 Some((Some(img), _)) => {
1107 let s = img.sample_wrapped(u.rem_euclid(1.0) * img.w as f64, v.rem_euclid(1.0) * img.h as f64);
1108 [s[0] / 255.0 * rgb[0], s[1] / 255.0 * rgb[1], s[2] / 255.0 * rgb[2], s[3] / 255.0]
1109 }
1110 None => [rgb[0], rgb[1], rgb[2], 1.0],
1111 }
1112}
1113
1114fn svg_fill_extrusion(out: &mut String, layer: &Json, zoom: f64, placed: &[PlacedTile], view: &ExtrusionView) {
1120 use std::fmt::Write as _;
1121 let p = &layer["paint"];
1122 let color = Prop::new(p.get("fill-extrusion-color"), Kind::Color, zoom);
1123 let height = Prop::new(p.get("fill-extrusion-height"), Kind::Number, zoom);
1124 let base = Prop::new(p.get("fill-extrusion-base"), Kind::Number, zoom);
1125 let opacity = Prop::new(p.get("fill-extrusion-opacity"), Kind::Number, zoom).num(&Ctx { zoom, feature: None }, 1.0);
1126 let vertical_gradient = p["fill-extrusion-vertical-gradient"].as_bool().unwrap_or(true);
1127 if opacity <= 0.0 {
1128 return;
1129 }
1130 let mut faces: Vec<(f64, String, [f64; 3])> = Vec::new();
1132 for pt in placed {
1133 for (f, scale) in features(layer, pt, zoom) {
1134 let Geometry::Polygons(polys) = &f.geometry else { continue };
1135 let ctx = Ctx { zoom, feature: Some(f) };
1136 let c = color.color(&ctx, Color::BLACK);
1137 let col = [c.r as f64, c.g as f64, c.b as f64, c.a as f64];
1138 let hgt = height.num(&ctx, 0.0).max(0.0);
1139 let bse = base.num(&ctx, 0.0).max(0.0);
1140 for poly in polys {
1141 let rings: Vec<Vec<(f64, f64)>> = poly.iter().map(|r| r.iter().map(|&q| to_extent(q, scale)).collect()).collect();
1142 if rings.first().map_or(true, |r| ring_entirely_outside(r)) {
1143 continue;
1144 }
1145 let to_px = |q: (f64, f64)| (pt.ox + q.0 * pt.unit_px, pt.oy + q.1 * pt.unit_px);
1146 for ring in &rings {
1147 if ring_entirely_outside(ring) {
1148 continue;
1149 }
1150 for e in ring.windows(2) {
1151 let (p1, p2) = (e[1], e[0]);
1152 if (p1.0 == p2.0 && (p1.0 < 0.0 || p1.0 > EXTENT)) || (p1.1 == p2.1 && (p1.1 < 0.0 || p1.1 > EXTENT)) {
1153 continue;
1154 }
1155 let (dx, dy) = (p1.0 - p2.0, p1.1 - p2.1);
1156 let len = (dx * dx + dy * dy).sqrt();
1157 if len == 0.0 {
1158 continue;
1159 }
1160 let n = (-dy / len, ((dx / len) * 16384.0).trunc() / 16384.0, 0.0);
1161 let a = view.project(to_px(p1), bse);
1162 let b = view.project(to_px(p1), hgt);
1163 let c2 = view.project(to_px(p2), bse);
1164 let d2 = view.project(to_px(p2), hgt);
1165 let cross = (c2.0 - a.0) * (b.1 - a.1) - (c2.1 - a.1) * (b.0 - a.0);
1167 if cross > 0.0 {
1168 continue;
1169 }
1170 let s0 = view.shade(col, n, 0.0, bse, hgt, vertical_gradient);
1171 let s1 = view.shade(col, n, 1.0, bse, hgt, vertical_gradient);
1172 let rgb = [(s0[0] + s1[0]) / 2.0, (s0[1] + s1[1]) / 2.0, (s0[2] + s1[2]) / 2.0];
1173 let quad = vec![(a.0, a.1), (c2.0, c2.1), (d2.0, d2.1), (b.0, b.1)];
1174 faces.push(((a.2 + b.2 + c2.2 + d2.2) / 4.0, svg::path_data(&[quad], true), rgb));
1175 }
1176 }
1177 let top: Vec<Vec<(f64, f64)>> = rings
1178 .iter()
1179 .map(|r| r.iter().map(|&q| { let (x, y, _) = view.project(to_px(q), hgt); (x, y) }).collect())
1180 .collect();
1181 let (_, _, iw) = view.project((0.0, 0.0), hgt);
1182 faces.push((iw + 1e-12, svg::path_data(&top, true), view.shade(col, (0.0, 0.0, 1.0), 1.0, bse, hgt, vertical_gradient)));
1183 }
1184 }
1185 }
1186 faces.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
1187 let _ = write!(out, r#"<g opacity="{}" fill-rule="evenodd">"#, svg::alpha(opacity.min(1.0)));
1188 for (_, d, rgb) in faces {
1189 let hex = format!(
1190 "#{:02x}{:02x}{:02x}",
1191 (rgb[0].clamp(0.0, 1.0) * 255.0).round() as u8,
1192 (rgb[1].clamp(0.0, 1.0) * 255.0).round() as u8,
1193 (rgb[2].clamp(0.0, 1.0) * 255.0).round() as u8
1194 );
1195 let _ = write!(out, r#"<path d="{d}" fill="{hex}"/>"#);
1196 }
1197 out.push_str("</g>");
1198}
1199
1200fn raster_factors(saturation: f64, contrast: f64, hue_deg: f64) -> (f64, f64, [f64; 3]) {
1204 let sat = if saturation > 0.0 { 1.0 - 1.0 / (1.001 - saturation) } else { -saturation };
1205 let con = if contrast > 0.0 { 1.0 / (1.0 - contrast) } else { 1.0 + contrast };
1206 let a = hue_deg.to_radians();
1207 let (s, c) = (a.sin(), a.cos());
1208 let spin = [(2.0 * c + 1.0) / 3.0, (-(3f64.sqrt()) * s - c + 1.0) / 3.0, (3f64.sqrt() * s - c + 1.0) / 3.0];
1209 (sat, con, spin)
1210}
1211
1212fn raster_image(rt: &RasterTiles, bbox: [f64; 4], w: usize, h: usize, ratio: f64) -> Option<image::RgbaImage> {
1216 crate::renderer::composite_raster_tiles(&rt.tiles, bbox, rt.zoom, w as u32, h as u32, true, ratio)
1217 .map_err(|e| log::warn!("raster layer: {e}"))
1218 .ok()
1219}
1220
1221fn draw_raster_layer(fb: &mut Framebuffer, layer: &Json, zoom: f64, rt: &RasterTiles, bbox: [f64; 4], ratio: f64) {
1225 let ctx = Ctx { zoom, feature: None };
1226 let p = &layer["paint"];
1227 let num = |k: &str, d: f64| Prop::new(p.get(k), Kind::Number, zoom).num(&ctx, d);
1228 let opacity = num("raster-opacity", 1.0);
1229 if opacity <= 0.0 {
1230 return;
1231 }
1232 let (sat, con, spin) = raster_factors(num("raster-saturation", 0.0), num("raster-contrast", 0.0), num("raster-hue-rotate", 0.0));
1233 let (lo, hi) = (num("raster-brightness-min", 0.0), num("raster-brightness-max", 1.0));
1234 let identity = sat == 0.0 && con == 1.0 && spin == [1.0, 0.0, 0.0] && lo == 0.0 && hi == 1.0;
1235 let Some(img) = raster_image(rt, bbox, fb.w, fb.h, ratio) else { return };
1236 for (x, y, px) in img.enumerate_pixels() {
1237 let a = px[3] as f64 / 255.0;
1238 if a <= 0.0 {
1239 continue;
1240 }
1241 let mut rgb = [px[0] as f64 / 255.0, px[1] as f64 / 255.0, px[2] as f64 / 255.0];
1242 if !identity {
1243 let r = rgb;
1244 rgb = [
1245 r[0] * spin[0] + r[1] * spin[1] + r[2] * spin[2],
1246 r[0] * spin[2] + r[1] * spin[0] + r[2] * spin[1],
1247 r[0] * spin[1] + r[1] * spin[2] + r[2] * spin[0],
1248 ];
1249 let avg = (r[0] + r[1] + r[2]) / 3.0;
1250 for c in rgb.iter_mut() {
1251 *c += (avg - *c) * sat;
1252 *c = (*c - 0.5) * con + 0.5;
1253 *c = lo + (hi - lo) * *c;
1254 }
1255 }
1256 let a = a * opacity;
1257 fb.blend(x as usize, y as usize, [(rgb[0] * a) as f32, (rgb[1] * a) as f32, (rgb[2] * a) as f32, a as f32]);
1258 }
1259}
1260
1261fn draw_circle_layer(fb: &mut Framebuffer, layer: &Json, zoom: f64, placed: &[PlacedTile], dpr: f64) {
1264 let p = &layer["paint"];
1265 let radius = Prop::new(p.get("circle-radius"), Kind::Number, zoom);
1266 let color = Prop::new(p.get("circle-color"), Kind::Color, zoom);
1267 let opacity = Prop::new(p.get("circle-opacity"), Kind::Number, zoom);
1268 let blur = Prop::new(p.get("circle-blur"), Kind::Number, zoom);
1269 let stroke_width = Prop::new(p.get("circle-stroke-width"), Kind::Number, zoom);
1270 let stroke_color = Prop::new(p.get("circle-stroke-color"), Kind::Color, zoom);
1271 let stroke_opacity = Prop::new(p.get("circle-stroke-opacity"), Kind::Number, zoom);
1272 let translate = Prop::new(p.get("circle-translate"), Kind::Array, zoom);
1273 let (w, h) = (fb.w, fb.h);
1274 let full = Clip { x0: 0.0, y0: 0.0, x1: w as f64, y1: h as f64 };
1275
1276 for pt in placed {
1277 for (f, scale) in features(layer, pt, zoom) {
1278 let Geometry::Points(points) = &f.geometry else { continue };
1279 let ctx = Ctx { zoom, feature: Some(f) };
1280 let r = radius.num(&ctx, 5.0) * dpr;
1281 let sw = stroke_width.num(&ctx, 0.0) * dpr;
1282 let fill = rgba(color.color(&ctx, Color::BLACK), opacity.num(&ctx, 1.0));
1283 let stroke = rgba(stroke_color.color(&ctx, Color::BLACK), stroke_opacity.num(&ctx, 1.0));
1284 let aablur = -(1.0 / (r + sw)).max(blur.num(&ctx, 0.0));
1287 let (tx, ty) = translate.translate_px(&ctx, dpr);
1288 let ext = r + sw;
1289 for &q in points {
1290 let (x, y) = to_extent(q, scale);
1291 if x < 0.0 || x >= EXTENT || y < 0.0 || y >= EXTENT {
1293 continue;
1294 }
1295 let (cx, cy) = (pt.ox + x * pt.unit_px + tx, pt.oy + y * pt.unit_px + ty);
1296 let corner = |ex: f64, ey: f64| Vert { x: cx + ex * ext, y: cy + ey * ext, v: [ex, ey] };
1297 let quad = [corner(-1.0, -1.0), corner(1.0, -1.0), corner(1.0, 1.0), corner(-1.0, 1.0)];
1298 for tri in [[0, 1, 2], [0, 2, 3]] {
1299 raster_triangle(w, h, [quad[tri[0]], quad[tri[1]], quad[tri[2]]], &full, |px, py, v| {
1300 let el = (v[0] * v[0] + v[1] * v[1]).sqrt();
1302 let opacity_t = smoothstep(0.0, aablur, el - 1.0);
1303 let color_t = if sw < 0.01 { 0.0 } else { smoothstep(aablur, 0.0, el - r / (r + sw)) };
1304 if opacity_t > 0.0 {
1305 let mut out = [0f32; 4];
1306 for i in 0..4 {
1307 out[i] = ((fill[i] as f64 * (1.0 - color_t) + stroke[i] as f64 * color_t)
1308 * opacity_t) as f32;
1309 }
1310 fb.blend(px, py, out);
1311 }
1312 });
1313 }
1314 }
1315 }
1316 }
1317}
1318
1319#[cfg(test)]
1320mod tests {
1321 use super::*;
1322
1323 #[test]
1324 fn scale_zoom_matches_maplibre_convention() {
1325 let z = scale_zoom([-12459252.0, 4963454.0, -12451608.0, 4969187.0], 800);
1327 assert_eq!(z, 13.0);
1328 assert_eq!(tile_zoom(13.7, None), 13);
1329 assert_eq!(tile_zoom(13.7, Some(12)), 12);
1330 }
1331}
1332
1333
1334pub struct SvgParts {
1339 pub defs: String,
1340 pub body: String,
1341 pub skipped_layer_types: Vec<String>,
1342}
1343
1344pub fn render_svg(
1349 style: &Json,
1350 sources: &SourceTiles,
1351 assets: &SymbolAssets,
1352 bbox: [f64; 4],
1353 width: u32,
1354 height: u32,
1355 id_prefix: &str,
1356 text_mode: super::fonts::SvgText,
1357 fonts: Option<&super::fonts::SvgFonts>,
1358) -> Result<SvgParts, String> {
1359 use std::fmt::Write as _;
1360 let (zoom, placed) = prepare(sources, bbox, width, height, 1.0);
1361 let placement = symbol::place(style, &symbol_tiles(&placed), assets, zoom, width as f64, height as f64);
1362 let mut defs = String::new();
1363 let mut source_ids: Vec<&String> = placed.keys().collect();
1365 source_ids.sort();
1366 let clip_prefix: std::collections::HashMap<&str, String> =
1367 source_ids.iter().enumerate().map(|(k, id)| (id.as_str(), format!("{id_prefix}{k}"))).collect();
1368 for id in &source_ids {
1369 let cp = &clip_prefix[id.as_str()];
1370 for (i, pt) in placed[*id].iter().enumerate() {
1371 let _ = write!(
1372 defs,
1373 r#"<clipPath id="{cp}t{i}"><rect x="{}" y="{}" width="{}" height="{}" shape-rendering="crispEdges"/></clipPath>"#,
1374 svg::num(pt.clip.x0),
1375 svg::num(pt.clip.y0),
1376 svg::num(pt.clip.x1 - pt.clip.x0),
1377 svg::num(pt.clip.y1 - pt.clip.y0)
1378 );
1379 }
1380 }
1381 let mut pattern_ids: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1382 let mut depth3d: Vec<f64> = Vec::new();
1383 let layer_clip = |layer: &Json| -> String {
1384 layer["source"].as_str().and_then(|s| clip_prefix.get(s)).cloned().unwrap_or_default()
1385 };
1386 let mut body = String::new();
1387 let mut skipped: Vec<String> = Vec::new();
1388 for (layer_idx, layer) in style["layers"].as_array().map(|v| v.as_slice()).unwrap_or(&[]).iter().enumerate() {
1389 let ltype = layer["type"].as_str().unwrap_or("");
1390 if !symbol::layer_visible(layer, zoom) {
1391 continue;
1392 }
1393 let id = svg::xml_escape(layer["id"].as_str().unwrap_or(""));
1394 let mut out = String::new();
1395 match ltype {
1396 "background" => {
1397 let ctx = Ctx { zoom, feature: None };
1398 let p = &layer["paint"];
1399 let c = Prop::new(p.get("background-color"), Kind::Color, zoom).color(&ctx, Color::BLACK);
1400 let o = Prop::new(p.get("background-opacity"), Kind::Number, zoom).num(&ctx, 1.0);
1401 if let Some((hex, a)) = svg::paint(c, o) {
1402 let _ = write!(out, r#"<rect width="{width}" height="{height}" fill="{hex}" fill-opacity="{}"/>"#, svg::alpha(a));
1403 }
1404 }
1405 "fill" => svg_fill(&mut out, &mut defs, layer, zoom, layer_tiles(&placed, layer), &layer_clip(layer), assets, &mut pattern_ids),
1406 "line" if layer["paint"].get("line-pattern").map_or(false, |v| !v.is_null()) => {
1407 let mut lfb = Framebuffer::new(width as usize, height as usize);
1409 draw_line_layer(&mut lfb, layer, zoom, layer_tiles(&placed, layer), 1.0, assets);
1410 if lfb.px.iter().any(|p| p[3] > 0 || p[0] > 0 || p[1] > 0 || p[2] > 0) {
1411 let px = lfb.into_straight_rgba();
1412 let _ = write!(out, r#"<image width="{width}" height="{height}" href="{}"/>"#, svg::png_data_uri(width, height, &px));
1413 }
1414 }
1415 "line" => svg_line(&mut out, layer, zoom, layer_tiles(&placed, layer), &layer_clip(layer)),
1416 "circle" => svg_circle(&mut out, layer, zoom, layer_tiles(&placed, layer)),
1417 "fill-extrusion" => {
1418 let view = ExtrusionView::new(style, bbox, width, height, 1.0, zoom);
1419 if layer["paint"].get("fill-extrusion-pattern").map_or(false, |v| !v.is_null()) {
1420 let mut lfb = Framebuffer::new(width as usize, height as usize);
1422 draw_fill_extrusion_layer(&mut lfb, layer, zoom, layer_tiles(&placed, layer), &view, assets, &mut depth3d);
1423 if lfb.px.iter().any(|p| p[3] > 0 || p[0] > 0 || p[1] > 0 || p[2] > 0) {
1424 let px = lfb.into_straight_rgba();
1425 let _ = write!(out, r#"<image width="{width}" height="{height}" href="{}"/>"#, svg::png_data_uri(width, height, &px));
1426 }
1427 } else {
1428 svg_fill_extrusion(&mut out, layer, zoom, layer_tiles(&placed, layer), &view);
1429 }
1430 }
1431 "raster" => {
1432 if let Some(rt) = layer["source"].as_str().and_then(|s| sources.raster.get(s)) {
1434 let ctx = Ctx { zoom, feature: None };
1435 let op = Prop::new(layer["paint"].get("raster-opacity"), Kind::Number, zoom).num(&ctx, 1.0);
1436 if let Some(img) = raster_image(rt, bbox, width as usize, height as usize, 1.0) {
1437 let _ = write!(
1438 out,
1439 r#"<image width="{width}" height="{height}" opacity="{}" href="{}"/>"#,
1440 svg::alpha(op.clamp(0.0, 1.0)),
1441 svg::png_data_uri(width, height, img.as_raw())
1442 );
1443 }
1444 }
1445 }
1446 "hillshade" => {
1447 if let Some(dem) = layer["source"].as_str().and_then(|s| sources.dem.get(s)) {
1449 let mut lfb = Framebuffer::new(width as usize, height as usize);
1450 let nearest = super::hillshade::source_nearest(style, layer["source"].as_str().unwrap_or(""), zoom);
1451 super::hillshade::draw_layer(&mut lfb, layer, zoom, dem, bbox, width, height, 1.0, nearest);
1452 if lfb.px.iter().any(|p| p[3] > 0 || p[0] > 0 || p[1] > 0 || p[2] > 0) {
1453 let px = lfb.into_straight_rgba();
1454 let _ = write!(out, r#"<image width="{width}" height="{height}" href="{}"/>"#, svg::png_data_uri(width, height, &px));
1455 }
1456 }
1457 }
1458 "symbol" => symbol::svg_layer(&mut out, &mut defs, layer, layer_idx, &placement, assets, width as usize, height as usize, id_prefix, text_mode, fonts),
1459 other => {
1460 if !skipped.iter().any(|x| x == other) {
1461 skipped.push(other.to_owned());
1462 }
1463 }
1464 }
1465 if !out.is_empty() {
1466 let _ = write!(body, r#"<g id="{id_prefix}{id}">{out}</g>"#);
1467 }
1468 }
1469 Ok(SvgParts { defs, body, skipped_layer_types: skipped })
1470}
1471
1472#[allow(clippy::too_many_arguments)]
1481fn svg_fill(
1482 out: &mut String,
1483 defs: &mut String,
1484 layer: &Json,
1485 zoom: f64,
1486 placed: &[PlacedTile],
1487 prefix: &str,
1488 assets: &SymbolAssets,
1489 pattern_ids: &mut std::collections::HashMap<String, String>,
1490) {
1491 use std::fmt::Write as _;
1492 let p = &layer["paint"];
1493 let color = Prop::new(p.get("fill-color"), Kind::Color, zoom);
1494 let opacity = Prop::new(p.get("fill-opacity"), Kind::Number, zoom);
1495 let outline = Prop::new(p.get("fill-outline-color"), Kind::Color, zoom);
1496 let translate = Prop::new(p.get("fill-translate"), Kind::Array, zoom);
1497 let antialias = p["fill-antialias"].as_bool().unwrap_or(true);
1498 let pattern = Prop::new(p.get("fill-pattern"), Kind::Enum, zoom);
1499 let mut pattern_paint = |ctx: &Ctx, pt: &PlacedTile| -> Option<String> {
1503 let Some(Val::Str(name)) = pattern.get(ctx) else { return None };
1504 let img = assets.sprite.images.get(&name)?;
1505 let frame = PatternFrame::new(pt);
1506 let k = pt.unit_px / frame.tile_ratio; let (sw, sh) = (img.w as f64 / img.pixel_ratio * k, img.h as f64 / img.pixel_ratio * k);
1508 let (x0, y0) = (pt.ox - frame.world_x * k, pt.oy - frame.world_y * k);
1509 let key = format!("{name}@{}", svg::num(k * 1000.0));
1510 let n = pattern_ids.len();
1511 let id = pattern_ids
1512 .entry(key)
1513 .or_insert_with(|| {
1514 let id = format!("{prefix}pat{n}");
1515 let _ = write!(
1516 defs,
1517 r#"<pattern id="{id}" patternUnits="userSpaceOnUse" x="{}" y="{}" width="{}" height="{}"><image width="{}" height="{}" preserveAspectRatio="none" href="{}"/></pattern>"#,
1518 svg::num(x0.rem_euclid(sw)),
1519 svg::num(y0.rem_euclid(sh)),
1520 sw,
1521 sh,
1522 sw,
1523 sh,
1524 img.png_data_uri()
1525 );
1526 id
1527 })
1528 .clone();
1529 Some(format!("url(#{id})"))
1530 };
1531 let opaque = matches!(&color, Prop::Const(v) if v.as_color().map_or(false, |c| c.a == 1.0))
1532 && match &opacity {
1533 Prop::Absent => true,
1534 Prop::Const(v) => v.as_num() == Some(1.0),
1535 Prop::Data(..) => false,
1536 };
1537 let outline_beneath = opaque && !outline.is_set() && !pattern.is_set();
1538
1539 let mut fills = String::new();
1540 let mut outlines = String::new();
1541 for (i, pt) in placed.iter().enumerate() {
1542 let (mut gf, mut go) = (String::new(), String::new());
1543 for (f, scale) in features(layer, pt, zoom) {
1544 let ctx = Ctx { zoom, feature: Some(f) };
1545 let op = opacity.num(&ctx, 1.0);
1546 let polys = polys_px(pt, f, scale, translate.translate(&ctx));
1547 if polys.is_empty() {
1548 continue;
1549 }
1550 if pattern.is_set() {
1551 let Some(paint) = pattern_paint(&ctx, pt) else { continue };
1553 if op <= 0.0 {
1554 continue;
1555 }
1556 for poly in &polys {
1557 let _ = write!(gf, r#"<path d="{}" fill="{paint}" fill-opacity="{}"/>"#, svg::path_data(poly, true), svg::alpha(op.min(1.0)));
1558 }
1559 if antialias {
1560 let rings: Vec<Vec<(f64, f64)>> = polys.into_iter().flatten().collect();
1561 let stroke = match outline.is_set().then(|| svg::paint(outline.color(&ctx, Color::BLACK), op)).flatten() {
1562 Some((hex, a)) => format!(r#"stroke="{hex}" stroke-opacity="{}""#, svg::alpha(a)),
1563 None => format!(r#"stroke="{paint}" stroke-opacity="{}""#, svg::alpha(op.min(1.0))),
1564 };
1565 let _ = write!(go, r#"<path d="{}" {stroke}/>"#, svg::path_data(&rings, true));
1566 }
1567 continue;
1568 }
1569 if let Some((hex, a)) = svg::paint(color.color(&ctx, Color::BLACK), op) {
1570 for poly in &polys {
1571 let _ = write!(gf, r#"<path d="{}" fill="{hex}" fill-opacity="{}"/>"#, svg::path_data(poly, true), svg::alpha(a));
1572 }
1573 }
1574 if antialias {
1575 let oc = if outline.is_set() { outline.color(&ctx, Color::BLACK) } else { color.color(&ctx, Color::BLACK) };
1576 if let Some((hex, a)) = svg::paint(oc, op) {
1577 let rings: Vec<Vec<(f64, f64)>> = polys.into_iter().flatten().collect();
1578 let _ = write!(go, r#"<path d="{}" stroke="{hex}" stroke-opacity="{}"/>"#, svg::path_data(&rings, true), svg::alpha(a));
1579 }
1580 }
1581 }
1582 if !gf.is_empty() {
1583 let _ = write!(fills, r#"<g clip-path="url(#{prefix}t{i})">{gf}</g>"#);
1584 }
1585 if !go.is_empty() {
1586 let _ = write!(outlines, r#"<g clip-path="url(#{prefix}t{i})">{go}</g>"#);
1587 }
1588 }
1589 let fills = format!(r#"<g fill-rule="evenodd" shape-rendering="crispEdges">{fills}</g>"#);
1590 let outlines = if outlines.is_empty() { outlines } else { format!(r#"<g fill="none" stroke-width="0.8">{outlines}</g>"#) };
1591 if outline_beneath {
1592 out.push_str(&outlines);
1593 out.push_str(&fills);
1594 } else {
1595 out.push_str(&fills);
1596 out.push_str(&outlines);
1597 }
1598}
1599
1600
1601fn even_dash_pattern(d: &[f64]) -> Option<(Vec<f64>, f64)> {
1608 match d.len() {
1609 0 | 1 => None,
1610 n if n % 2 == 0 => Some((d.to_vec(), 0.0)),
1611 n => {
1612 let last = d[n - 1];
1613 let mut p = vec![d[0] + last];
1614 p.extend_from_slice(&d[1..n - 1]);
1615 Some((p, last))
1616 }
1617 }
1618}
1619
1620fn offset_polyline(pts: &[(f64, f64)], d: f64, closed: bool, join: &str, miter_limit: f64, round_limit: f64) -> Vec<(f64, f64)> {
1625 if pts.len() < 2 || d == 0.0 {
1626 return pts.to_vec();
1627 }
1628 let normal = |a: (f64, f64), b: (f64, f64)| {
1629 let (dx, dy) = (b.0 - a.0, b.1 - a.1);
1630 let len = (dx * dx + dy * dy).sqrt();
1631 if len == 0.0 { (0.0, 0.0) } else { (-dy / len, dx / len) }
1632 };
1633 let n = pts.len();
1634 let mut out = Vec::with_capacity(n + 8);
1635 for i in 0..n {
1636 let p = pts[i];
1637 let n1 = if i > 0 {
1638 normal(pts[i - 1], p)
1639 } else if closed {
1640 normal(pts[n - 1], p)
1641 } else {
1642 normal(p, pts[1])
1643 };
1644 let n2 = if i + 1 < n {
1645 normal(p, pts[i + 1])
1646 } else if closed {
1647 normal(p, pts[0])
1648 } else {
1649 n1
1650 };
1651 let (mut mx, mut my) = (n1.0 + n2.0, n1.1 + n2.1);
1652 let m = (mx * mx + my * my).sqrt();
1653 if m < 1e-9 {
1654 mx = n2.0;
1655 my = n2.1;
1656 } else {
1657 mx /= m;
1658 my /= m;
1659 }
1660 let cos = (mx * n2.0 + my * n2.1).max(1e-6);
1661 let miter_len = 1.0 / cos;
1662 let dir2 = (n2.1, -n2.0);
1665 let outer = (dir2.0 * n1.0 + dir2.1 * n1.1) * d < -1e-9;
1666 let shape = if !outer {
1671 "miter"
1672 } else {
1673 match join {
1674 "round" if miter_len >= round_limit => "round",
1675 "round" => "miter",
1676 "bevel" => "bevel",
1677 _ if miter_len > miter_limit => "bevel",
1678 _ => "miter",
1679 }
1680 };
1681 match shape {
1682 "round" => {
1683 let a0 = n1.1.atan2(n1.0);
1684 let mut sweep = n2.1.atan2(n2.0) - a0;
1685 while sweep > std::f64::consts::PI {
1686 sweep -= 2.0 * std::f64::consts::PI;
1687 }
1688 while sweep < -std::f64::consts::PI {
1689 sweep += 2.0 * std::f64::consts::PI;
1690 }
1691 let steps = ((sweep.abs() / (std::f64::consts::PI / 12.0)).ceil() as usize).max(1);
1692 for k in 0..=steps {
1693 let a = a0 + sweep * k as f64 / steps as f64;
1694 out.push((p.0 + a.cos() * d, p.1 + a.sin() * d));
1695 }
1696 }
1697 "bevel" => {
1698 out.push((p.0 + n1.0 * d, p.1 + n1.1 * d));
1699 out.push((p.0 + n2.0 * d, p.1 + n2.1 * d));
1700 }
1701 _ => {
1702 let k = if cos > 0.1 { d / cos } else { d };
1703 out.push((p.0 + mx * k, p.1 + my * k));
1704 }
1705 }
1706 }
1707 out
1708}
1709
1710fn svg_line(out: &mut String, layer: &Json, zoom: f64, placed: &[PlacedTile], prefix: &str) {
1711 use std::fmt::Write as _;
1712 let p = &layer["paint"];
1713 let l = &layer["layout"];
1714 let color = Prop::new(p.get("line-color"), Kind::Color, zoom);
1715 let opacity = Prop::new(p.get("line-opacity"), Kind::Number, zoom);
1716 let width = Prop::new(p.get("line-width"), Kind::Number, zoom);
1717 let floor_width = Prop::new(p.get("line-width"), Kind::Number, zoom.floor());
1718 let gap = Prop::new(p.get("line-gap-width"), Kind::Number, zoom);
1719 let offset = Prop::new(p.get("line-offset"), Kind::Number, zoom);
1720 let translate = Prop::new(p.get("line-translate"), Kind::Array, zoom);
1721 let dasharray = Prop::new(p.get("line-dasharray"), Kind::Enum, zoom);
1722 let blur = Prop::new(p.get("line-blur"), Kind::Number, zoom);
1723 let cap_s = super::expr::layout_enum(l, "line-cap", zoom.floor()).unwrap_or_else(|| "butt".into());
1724 let join_s = super::expr::layout_enum(l, "line-join", zoom.floor()).unwrap_or_else(|| "miter".into());
1725 let (cap, join) = (cap_s.as_str(), join_s.as_str());
1726 let miter = l["line-miter-limit"].as_f64().unwrap_or(2.0);
1727 let round_limit = l["line-round-limit"].as_f64().unwrap_or(1.05);
1728 let dash = match &dasharray {
1729 Prop::Const(v) => v.as_num_array().filter(|d| d.len() >= 2 && d.iter().sum::<f64>() > 0.0),
1730 _ => None,
1731 };
1732 for (i, pt) in placed.iter().enumerate() {
1733 let mut g = String::new();
1734 for (f, scale) in features(layer, pt, zoom) {
1735 let ctx = Ctx { zoom, feature: Some(f) };
1736 let fctx = Ctx { zoom: zoom.floor(), feature: Some(f) };
1737 let (lines, closed): (Vec<&Vec<(f32, f32)>>, bool) = match &f.geometry {
1740 Geometry::Lines(ls) => (ls.iter().collect(), false),
1741 Geometry::Polygons(ps) => (ps.iter().flatten().collect(), true),
1742 Geometry::Points(_) => continue,
1743 };
1744 let lw = width.num(&ctx, 1.0);
1745 if lw <= 0.0 {
1746 continue;
1747 }
1748 let Some((hex, a)) = svg::paint(color.color(&ctx, Color::BLACK), opacity.num(&ctx, 1.0)) else { continue };
1749 let (tx, ty) = translate.translate(&ctx);
1750 let px: Vec<Vec<(f64, f64)>> = lines
1751 .iter()
1752 .map(|ln| {
1753 let mut v: Vec<(f64, f64)> = ln
1754 .iter()
1755 .map(|&q| {
1756 let (x, y) = to_extent(q, scale);
1757 (pt.ox + x * pt.unit_px + tx, pt.oy + y * pt.unit_px + ty)
1758 })
1759 .collect();
1760 if closed && v.len() > 2 && v.first() == v.last() {
1761 v.pop();
1762 }
1763 v
1764 })
1765 .collect();
1766 let off = offset.num(&ctx, 0.0);
1767 let gw = gap.num(&ctx, 0.0);
1768 let offsets: Vec<f64> = if gw > 0.0 { vec![off - (gw / 2.0 + lw / 2.0), off + (gw / 2.0 + lw / 2.0)] } else { vec![off] };
1769 let mut dash_attr = String::new();
1770 if let Some((pattern, phase)) = dash.as_deref().and_then(even_dash_pattern) {
1771 let fw = floor_width.num(&fctx, lw) * pt.unit_px * EXTENT / (TILE_PX * pt.overscaling);
1777 let vals: Vec<String> = pattern.iter().map(|&v| svg::num(v * fw)).collect();
1778 let offset = phase * fw;
1779 dash_attr = format!(r#" stroke-dasharray="{}""#, vals.join(" "));
1780 if offset != 0.0 {
1781 dash_attr += &format!(r#" stroke-dashoffset="{}""#, svg::num(offset));
1782 }
1783 }
1784 let stroke_w = if lw < 1.0 { (lw + 1.0).powi(2) / 4.0 } else { lw };
1788 let b = blur.num(&ctx, 0.0).max(0.0);
1793 let bands: Vec<(f64, f64)> = if b > 0.0 {
1794 let n = 3;
1795 let mut below = 0.0;
1796 (1..=n)
1797 .map(|k| {
1798 let y = (k as f64 - 0.5) / n as f64;
1799 let half = (lw / 2.0 - b / 2.0 + b * (0.5 - y)).max(0.05);
1800 let target = a * k as f64 / n as f64;
1801 let layer = if below >= 1.0 { 0.0 } else { ((target - below) / (1.0 - below)).clamp(0.0, 1.0) };
1802 below = target;
1803 (2.0 * half, layer)
1804 })
1805 .collect()
1806 } else {
1807 vec![(stroke_w, a)]
1808 };
1809 for (sw, op) in bands {
1812 if op <= 0.0 {
1813 continue;
1814 }
1815 let _ = write!(
1816 g,
1817 r#"<g fill="none" stroke="{hex}" stroke-opacity="{}" stroke-width="{}" stroke-linecap="{cap}" stroke-linejoin="{join}" stroke-miterlimit="{}"{dash_attr}>"#,
1818 svg::alpha(op),
1819 svg::num(sw),
1820 svg::num(miter)
1821 );
1822 for o in &offsets {
1823 for r in &px {
1824 let line = offset_polyline(r, *o, closed, join, miter, round_limit);
1825 let _ = write!(g, r#"<path d="{}"/>"#, svg::path_data(std::slice::from_ref(&line), closed));
1826 }
1827 }
1828 g.push_str("</g>");
1829 }
1830 }
1831 if !g.is_empty() {
1832 let _ = write!(out, r#"<g clip-path="url(#{prefix}t{i})">{g}</g>"#);
1833 }
1834 }
1835}
1836
1837fn svg_circle(out: &mut String, layer: &Json, zoom: f64, placed: &[PlacedTile]) {
1838 use std::fmt::Write as _;
1839 let p = &layer["paint"];
1840 let radius = Prop::new(p.get("circle-radius"), Kind::Number, zoom);
1841 let color = Prop::new(p.get("circle-color"), Kind::Color, zoom);
1842 let opacity = Prop::new(p.get("circle-opacity"), Kind::Number, zoom);
1843 let stroke_width = Prop::new(p.get("circle-stroke-width"), Kind::Number, zoom);
1844 let stroke_color = Prop::new(p.get("circle-stroke-color"), Kind::Color, zoom);
1845 let stroke_opacity = Prop::new(p.get("circle-stroke-opacity"), Kind::Number, zoom);
1846 let translate = Prop::new(p.get("circle-translate"), Kind::Array, zoom);
1847 for pt in placed {
1848 for (f, scale) in features(layer, pt, zoom) {
1849 let Geometry::Points(points) = &f.geometry else { continue };
1850 let ctx = Ctx { zoom, feature: Some(f) };
1851 let r = radius.num(&ctx, 5.0);
1852 let sw = stroke_width.num(&ctx, 0.0);
1853 let (tx, ty) = translate.translate(&ctx);
1854 for &q in points {
1855 let (x, y) = to_extent(q, scale);
1856 if x < 0.0 || x >= EXTENT || y < 0.0 || y >= EXTENT {
1857 continue;
1858 }
1859 let (cx, cy) = (pt.ox + x * pt.unit_px + tx, pt.oy + y * pt.unit_px + ty);
1860 if let Some((hex, a)) = svg::paint(color.color(&ctx, Color::BLACK), opacity.num(&ctx, 1.0)) {
1861 let _ = write!(out, r#"<circle cx="{}" cy="{}" r="{}" fill="{hex}" fill-opacity="{}"/>"#, svg::num(cx), svg::num(cy), svg::num(r), svg::alpha(a));
1862 }
1863 if sw > 0.0 {
1864 if let Some((hex, a)) = svg::paint(stroke_color.color(&ctx, Color::BLACK), stroke_opacity.num(&ctx, 1.0)) {
1865 let _ = write!(
1866 out,
1867 r#"<circle cx="{}" cy="{}" r="{}" fill="none" stroke="{hex}" stroke-opacity="{}" stroke-width="{}"/>"#,
1868 svg::num(cx),
1869 svg::num(cy),
1870 svg::num(r + sw / 2.0),
1871 svg::alpha(a),
1872 svg::num(sw)
1873 );
1874 }
1875 }
1876 }
1877 }
1878 }
1879}