Skip to main content

spritore_core/
lib.rs

1//! Rasterize SVG icons and build MapLibre-compatible sprite assets.
2//!
3//! Use [`render_icon`] to produce RGBA pixels for one icon, or combine rendered
4//! icons with [`build_sprite_sheet`] and serialize its index with
5//! [`index_to_json`]. The API accepts SVG text and returns in-memory image and
6//! index data, so applications can choose how to read and store their assets.
7
8#![forbid(unsafe_code)]
9#![warn(missing_docs)]
10
11mod png;
12mod potpack;
13
14use std::collections::BTreeMap;
15use std::fmt::Write as _;
16
17/// An error produced while rendering an icon or building a sprite sheet.
18#[derive(Debug, thiserror::Error)]
19pub enum Error {
20	/// The icon source could not be parsed as SVG.
21	#[error("invalid SVG for icon `{id}`: {reason}")]
22	InvalidSvg {
23		/// The caller-provided icon identifier.
24		id: String,
25		/// The parser's description of the failure.
26		reason: String,
27	},
28	/// More than one icon used the same identifier.
29	#[error("duplicate icon id `{0}`")]
30	DuplicateId(String),
31	/// No icons were provided to the sprite builder.
32	#[error("no icons given")]
33	Empty,
34	/// An icon had a zero pixel width or height.
35	#[error("icon `{id}` has zero size")]
36	ZeroSize {
37		/// The caller-provided icon identifier.
38		id: String,
39	},
40}
41
42/// A rasterized icon with straight-alpha RGBA pixels.
43pub struct RenderedIcon {
44	/// The identifier used as the sprite index key.
45	pub id: String,
46	/// The pixel width after applying the requested pixel ratio.
47	pub width: u32,
48	/// The pixel height after applying the requested pixel ratio.
49	pub height: u32,
50	/// Straight (non-premultiplied) RGBA pixels in row-major order.
51	pub pixels: Vec<u8>,
52}
53
54/// Rasterizes one SVG icon at the requested pixel ratio.
55///
56/// This is also suitable for producing individual images for MapLibre's
57/// `map.addImage` API.
58pub fn render_icon(id: &str, svg: &str, pixel_ratio: u8) -> Result<RenderedIcon, Error> {
59	let options = resvg::usvg::Options::default();
60	let tree = resvg::usvg::Tree::from_str(svg, &options).map_err(|error| Error::InvalidSvg {
61		id: id.to_owned(),
62		reason: error.to_string(),
63	})?;
64	let size = tree.size();
65	let ratio = f32::from(pixel_ratio);
66	let width = (size.width() * ratio).ceil() as u32;
67	let height = (size.height() * ratio).ceil() as u32;
68	if width == 0 || height == 0 {
69		return Err(Error::ZeroSize { id: id.to_owned() });
70	}
71
72	let mut pixmap = resvg::tiny_skia::Pixmap::new(width, height)
73		.ok_or_else(|| Error::ZeroSize { id: id.to_owned() })?;
74	resvg::render(
75		&tree,
76		resvg::tiny_skia::Transform::from_scale(ratio, ratio),
77		&mut pixmap.as_mut(),
78	);
79
80	// tiny-skia の内部表現は premultiplied RGBA なので、PNG と公開 API 用に戻す。
81	let mut pixels = Vec::with_capacity(pixmap.data().len());
82	for pixel in pixmap.pixels() {
83		let straight = pixel.demultiply();
84		pixels.extend_from_slice(&[
85			straight.red(),
86			straight.green(),
87			straight.blue(),
88			straight.alpha(),
89		]);
90	}
91
92	Ok(RenderedIcon {
93		id: id.to_owned(),
94		width,
95		height,
96		pixels,
97	})
98}
99
100/// A MapLibre sprite index entry.
101#[derive(Clone, Copy, PartialEq, Eq, Debug)]
102pub struct SpriteIndexEntry {
103	/// The icon's left coordinate in the sprite sheet.
104	pub x: u32,
105	/// The icon's top coordinate in the sprite sheet.
106	pub y: u32,
107	/// The icon's pixel width, excluding its packing margin.
108	pub width: u32,
109	/// The icon's pixel height, excluding its packing margin.
110	pub height: u32,
111	/// The pixel ratio represented by this sheet.
112	pub pixel_ratio: u8,
113}
114
115/// A PNG sprite sheet and its MapLibre index.
116pub struct SpriteSheet {
117	/// The complete encoded PNG file.
118	pub png: Vec<u8>,
119	/// Sprite entries keyed by icon identifier.
120	pub index: BTreeMap<String, SpriteIndexEntry>,
121}
122
123/// Options controlling sprite sheet construction.
124#[derive(Clone, Copy, Default)]
125pub struct BuildOptions {
126	/// Prioritizes generation speed over PNG file size when `true`.
127	pub fast: bool,
128}
129
130struct Deduplicated<'a> {
131	representatives: Vec<&'a RenderedIcon>,
132	representative_for_icon: Vec<usize>,
133}
134
135fn deduplicate<'a>(icons: &[&'a RenderedIcon]) -> Deduplicated<'a> {
136	let mut representatives: Vec<&RenderedIcon> = Vec::new();
137	let mut representative_for_icon = Vec::with_capacity(icons.len());
138
139	for icon in icons {
140		let representative = representatives.iter().position(|candidate| {
141			candidate.width == icon.width
142				&& candidate.height == icon.height
143				&& candidate.pixels == icon.pixels
144		});
145		let representative = representative.unwrap_or_else(|| {
146			representatives.push(icon);
147			representatives.len() - 1
148		});
149		representative_for_icon.push(representative);
150	}
151
152	Deduplicated {
153		representatives,
154		representative_for_icon,
155	}
156}
157
158/// Builds a MapLibre PNG sprite sheet from rasterized icons.
159///
160/// Returns an error when the slice is empty, identifiers are duplicated, or an
161/// icon has a zero width or height.
162pub fn build_sprite_sheet(
163	icons: &[RenderedIcon],
164	pixel_ratio: u8,
165	options: BuildOptions,
166) -> Result<SpriteSheet, Error> {
167	if icons.is_empty() {
168		return Err(Error::Empty);
169	}
170
171	let mut ordered: Vec<&RenderedIcon> = icons.iter().collect();
172	ordered.sort_by(|left, right| left.id.cmp(&right.id));
173	for pair in ordered.windows(2) {
174		if pair[0].id == pair[1].id {
175			return Err(Error::DuplicateId(pair[0].id.clone()));
176		}
177	}
178	for icon in &ordered {
179		if icon.width == 0 || icon.height == 0 {
180			return Err(Error::ZeroSize {
181				id: icon.id.clone(),
182			});
183		}
184	}
185
186	let deduplicated = deduplicate(&ordered);
187	let rectangles = deduplicated
188		.representatives
189		.iter()
190		.enumerate()
191		.map(|(index, icon)| potpack::Rectangle {
192			index,
193			id: &icon.id,
194			width: u64::from(icon.width) + 2,
195			height: u64::from(icon.height) + 2,
196		})
197		.collect();
198	let layout = potpack::pack(rectangles);
199	let mut rgba = vec![0; layout.width as usize * layout.height as usize * 4];
200
201	for (representative, &(packed_x, packed_y)) in
202		deduplicated.representatives.iter().zip(&layout.positions)
203	{
204		let x = packed_x + 1;
205		let y = packed_y + 1;
206		for row in 0..representative.height {
207			let source_start = (row * representative.width * 4) as usize;
208			let source_end = source_start + (representative.width * 4) as usize;
209			let destination_start = (((y + row) * layout.width + x) * 4) as usize;
210			let destination_end = destination_start + (representative.width * 4) as usize;
211			rgba[destination_start..destination_end]
212				.copy_from_slice(&representative.pixels[source_start..source_end]);
213		}
214	}
215
216	let mut index = BTreeMap::new();
217	for (icon, &representative) in ordered.iter().zip(&deduplicated.representative_for_icon) {
218		let (packed_x, packed_y) = layout.positions[representative];
219		index.insert(
220			icon.id.clone(),
221			SpriteIndexEntry {
222				x: packed_x + 1,
223				y: packed_y + 1,
224				width: icon.width,
225				height: icon.height,
226				pixel_ratio,
227			},
228		);
229	}
230
231	let png = png::encode(layout.width, layout.height, &rgba, options.fast);
232	Ok(SpriteSheet { png, index })
233}
234
235/// Serializes a MapLibre sprite index as pretty JSON.
236///
237/// The result uses two-space indentation, the MapLibre field names `x`, `y`,
238/// `width`, `height`, and `pixelRatio`, and a trailing newline.
239pub fn index_to_json(index: &BTreeMap<String, SpriteIndexEntry>) -> String {
240	if index.is_empty() {
241		return "{}\n".to_owned();
242	}
243
244	let mut json = String::from("{\n");
245	for (entry_number, (id, entry)) in index.iter().enumerate() {
246		json.push_str("  ");
247		push_json_string(&mut json, id);
248		json.push_str(": {\n");
249		writeln!(json, "    \"x\": {},", entry.x).expect("writing to a String cannot fail");
250		writeln!(json, "    \"y\": {},", entry.y).expect("writing to a String cannot fail");
251		writeln!(json, "    \"width\": {},", entry.width).expect("writing to a String cannot fail");
252		writeln!(json, "    \"height\": {},", entry.height)
253			.expect("writing to a String cannot fail");
254		writeln!(json, "    \"pixelRatio\": {}", entry.pixel_ratio)
255			.expect("writing to a String cannot fail");
256		json.push_str("  }");
257		if entry_number + 1 != index.len() {
258			json.push(',');
259		}
260		json.push('\n');
261	}
262	json.push_str("}\n");
263	json
264}
265
266fn push_json_string(output: &mut String, value: &str) {
267	output.push('"');
268	for character in value.chars() {
269		match character {
270			'"' => output.push_str("\\\""),
271			'\\' => output.push_str("\\\\"),
272			'\u{08}' => output.push_str("\\b"),
273			'\u{0c}' => output.push_str("\\f"),
274			'\n' => output.push_str("\\n"),
275			'\r' => output.push_str("\\r"),
276			'\t' => output.push_str("\\t"),
277			'\u{00}'..='\u{1f}' => {
278				write!(output, "\\u{:04x}", character as u32)
279					.expect("writing to a String cannot fail");
280			}
281			_ => output.push(character),
282		}
283	}
284	output.push('"');
285}
286
287#[cfg(test)]
288mod tests {
289	use super::*;
290
291	fn icon(id: &str, width: u32, height: u32, pixels: Vec<u8>) -> RenderedIcon {
292		RenderedIcon {
293			id: id.to_owned(),
294			width,
295			height,
296			pixels,
297		}
298	}
299
300	#[test]
301	fn deduplicates_identical_pixels_using_the_first_id() {
302		let icons = vec![
303			icon("z-copy", 1, 1, vec![10, 20, 30, 255]),
304			icon("a-original", 1, 1, vec![10, 20, 30, 255]),
305		];
306		let mut ordered: Vec<_> = icons.iter().collect();
307		ordered.sort_by(|left, right| left.id.cmp(&right.id));
308		let deduplicated = deduplicate(&ordered);
309		assert!(std::ptr::eq(deduplicated.representatives[0], ordered[0]));
310
311		let sheet = build_sprite_sheet(&icons, 1, BuildOptions { fast: true }).unwrap();
312		assert_eq!(sheet.index["a-original"], sheet.index["z-copy"]);
313		assert_eq!(u32::from_be_bytes(sheet.png[16..20].try_into().unwrap()), 3);
314		assert_eq!(u32::from_be_bytes(sheet.png[20..24].try_into().unwrap()), 3);
315	}
316
317	#[test]
318	fn reports_required_error_cases() {
319		assert!(matches!(
320			build_sprite_sheet(&[], 1, BuildOptions::default()),
321			Err(Error::Empty)
322		));
323
324		let duplicate = vec![
325			icon("same", 1, 1, vec![0; 4]),
326			icon("same", 1, 1, vec![255; 4]),
327		];
328		assert!(matches!(
329			build_sprite_sheet(&duplicate, 1, BuildOptions::default()),
330			Err(Error::DuplicateId(id)) if id == "same"
331		));
332
333		let zero = vec![icon("zero", 0, 1, Vec::new())];
334		assert!(matches!(
335			build_sprite_sheet(&zero, 1, BuildOptions::default()),
336			Err(Error::ZeroSize { id }) if id == "zero"
337		));
338
339		assert!(matches!(
340			render_icon("bad", "not svg", 1),
341			Err(Error::InvalidSvg { id, .. }) if id == "bad"
342		));
343		assert!(matches!(
344			render_icon(
345				"zero-ratio",
346				r#"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>"#,
347				0,
348			),
349			Err(Error::ZeroSize { id }) if id == "zero-ratio"
350		));
351	}
352
353	#[test]
354	fn index_json_format_and_escaping_are_fixed() {
355		let index = BTreeMap::from([
356			(
357				"a\n\"".to_owned(),
358				SpriteIndexEntry {
359					x: 1,
360					y: 2,
361					width: 3,
362					height: 4,
363					pixel_ratio: 2,
364				},
365			),
366			(
367				"b".to_owned(),
368				SpriteIndexEntry {
369					x: 5,
370					y: 6,
371					width: 7,
372					height: 8,
373					pixel_ratio: 2,
374				},
375			),
376		]);
377		assert_eq!(
378			index_to_json(&index),
379			concat!(
380				"{\n",
381				"  \"a\\n\\\"\": {\n",
382				"    \"x\": 1,\n",
383				"    \"y\": 2,\n",
384				"    \"width\": 3,\n",
385				"    \"height\": 4,\n",
386				"    \"pixelRatio\": 2\n",
387				"  },\n",
388				"  \"b\": {\n",
389				"    \"x\": 5,\n",
390				"    \"y\": 6,\n",
391				"    \"width\": 7,\n",
392				"    \"height\": 8,\n",
393				"    \"pixelRatio\": 2\n",
394				"  }\n",
395				"}\n",
396			),
397		);
398		assert_eq!(index_to_json(&BTreeMap::new()), "{}\n");
399	}
400}