1use crate::collision_detection::hazards::HazardEntity;
2use crate::collision_detection::hazards::detector::{BasicHazardDetector, HazardDetector};
3use crate::collision_detection::hazards::filter::NoHazardFilter;
4use crate::entities::{Instance, Layout, LayoutSnapshot};
5use crate::geometry::geo_traits::Transformable;
6use crate::geometry::primitives::Edge;
7use crate::geometry::{DTransformation, Transformation};
8use crate::io::export::int_to_ext_transformation;
9use crate::io::svg::svg_util;
10use crate::io::svg::svg_util::SvgDrawOptions;
11use log::warn;
12use std::hash::{DefaultHasher, Hash, Hasher};
13use svg::Document;
14use svg::node::element::{Definitions, Group, Text, Title, Use};
15
16pub fn s_layout_to_svg(
17 s_layout: &LayoutSnapshot,
18 instance: &impl Instance,
19 options: SvgDrawOptions,
20 title: &str,
21) -> Document {
22 let layout = Layout::from_snapshot(s_layout);
23 layout_to_svg(&layout, instance, options, title)
24}
25
26pub fn layout_to_svg(
27 layout: &Layout,
28 instance: &impl Instance,
29 options: SvgDrawOptions,
30 title: &str,
31) -> Document {
32 let container = &layout.container;
33
34 let vbox = container.outer_orig.bbox().scale(1.10);
35
36 let theme = &options.theme;
37
38 let stroke_width =
39 f32::min(vbox.width(), vbox.height()) * 0.001 * theme.stroke_width_multiplier;
40
41 let label = {
42 let bbox = container.outer_orig.bbox();
44
45 let label_content = format!(
46 "height: {:.3} | width: {:.3} | density: {:.3}% | {}",
47 bbox.height(),
48 bbox.width(),
49 layout.density(instance) * 100.0,
50 title,
51 );
52 Text::new(label_content)
53 .set("x", bbox.x_min)
54 .set(
55 "y",
56 bbox.y_min - 0.5 * 0.025 * f32::min(bbox.width(), bbox.height()),
57 )
58 .set("font-size", f32::min(bbox.width(), bbox.height()) * 0.025)
59 .set("font-family", "monospace")
60 .set("font-weight", "500")
61 };
62
63 let highlight_cd_shape_style = &[
64 ("fill", "none"),
65 ("stroke-width", &*format!("{}", 0.5 * stroke_width)),
66 ("stroke", "black"),
67 ("stroke-opacity", "0.3"),
68 (
69 "stroke-dasharray",
70 &*format!("{} {}", 1.0 * stroke_width, 2.0 * stroke_width),
71 ),
72 ("stroke-linecap", "round"),
73 ("stroke-linejoin", "round"),
74 ];
75
76 let container_group = {
78 let container_group = Group::new().set("id", format!("container_{}", container.id));
79 let bbox = container.outer_orig.bbox();
80 let title = Title::new(format!(
81 "container, id: {}, bbox: [x_min: {:.3}, y_min: {:.3}, x_max: {:.3}, y_max: {:.3}]",
82 container.id, bbox.x_min, bbox.y_min, bbox.x_max, bbox.y_max
83 ));
84
85 container_group
87 .add(svg_util::data_to_path(
88 svg_util::original_shape_data(
89 &container.outer_orig,
90 &container.outer_cd,
91 options.draw_cd_shapes,
92 ),
93 &[
94 ("fill", &*format!("{}", theme.container_fill)),
95 ("stroke", "black"),
96 ("stroke-width", &*format!("{}", 2.0 * stroke_width)),
97 ],
98 ))
99 .add(title)
100 };
101
102 let qz_group = {
103 let mut qz_group = Group::new().set("id", "quality_zones");
104
105 for qz in container.quality_zones.iter().rev().flatten() {
107 let color = theme.qz_fill[qz.quality];
108 let stroke_color = svg_util::change_brightness(color, 0.5);
109 for (orig_qz_shape, intern_qz_shape) in qz.shapes_orig.iter().zip(qz.shapes_cd.iter()) {
110 qz_group = qz_group.add(
111 svg_util::data_to_path(
112 svg_util::original_shape_data(
113 orig_qz_shape,
114 intern_qz_shape,
115 options.draw_cd_shapes,
116 ),
117 &[
118 ("fill", &*format!("{color}")),
119 ("fill-opacity", "0.50"),
120 ("stroke", &*format!("{stroke_color}")),
121 ("stroke-width", &*format!("{}", 2.0 * stroke_width)),
122 ("stroke-opacity", &*format!("{}", theme.qz_stroke_opac)),
123 ("stroke-dasharray", &*format!("{}", 5.0 * stroke_width)),
124 ("stroke-linecap", "round"),
125 ("stroke-linejoin", "round"),
126 ],
127 )
128 .add(Title::new(format!("quality zone, q: {}", qz.quality))),
129 );
130 }
131 }
132 qz_group
133 };
134
135 let (items_group, surrogate_group, mut highlight_cd_shape_group) = {
137 let mut item_defs = Definitions::new();
139 let mut surrogate_defs = Definitions::new();
140 for item in instance.items() {
141 let color = match item.min_quality {
142 None => theme.item_fill.to_owned(),
143 Some(q) => svg_util::blend_colors(theme.item_fill, theme.qz_fill[q]),
144 };
145 item_defs = item_defs.add(Group::new().set("id", format!("item_{}", item.id)).add(
146 svg_util::data_to_path(
147 svg_util::original_shape_data(
148 &item.shape_orig,
149 &item.shape_cd,
150 options.draw_cd_shapes,
151 ),
152 &[
153 ("fill", &*format!("{color}")),
154 ("stroke-width", &*format!("{stroke_width}")),
155 ("fill-rule", "nonzero"),
156 ("stroke", "black"),
157 ("fill-opacity", "0.5"),
158 ],
159 ),
160 ));
161
162 let int_transf = match options.draw_cd_shapes {
163 true => Transformation::empty(), false => {
165 let pre_transform = item.shape_orig.pre_transform.compose();
167 pre_transform.inverse()
168 }
169 };
170
171 if options.surrogate {
172 let mut surrogate_group = Group::new().set("id", format!("surrogate_{}", item.id));
173 let poi_style = [
174 ("fill", "black"),
175 ("fill-opacity", "0.1"),
176 ("stroke", "black"),
177 ("stroke-width", &*format!("{stroke_width}")),
178 ("stroke-opacity", "0.8"),
179 ];
180 let ff_style = [
181 ("fill", "none"),
182 ("stroke", "black"),
183 ("stroke-width", &*format!("{stroke_width}")),
184 ("stroke-opacity", "0.8"),
185 ];
186 let no_ff_style = [
187 ("fill", "none"),
188 ("stroke", "black"),
189 ("stroke-width", &*format!("{stroke_width}")),
190 ("stroke-opacity", "0.5"),
191 ("stroke-dasharray", &*format!("{}", 5.0 * stroke_width)),
192 ("stroke-linecap", "round"),
193 ("stroke-linejoin", "round"),
194 ];
195
196 let surrogate = item.shape_cd.surrogate();
197 let poi = &surrogate.poles[0];
198 let ff_poles = surrogate.ff_poles();
199
200 for pole in surrogate.poles.iter() {
201 if pole == poi {
202 let svg_circle =
203 svg_util::circle(pole.transform_clone(&int_transf), &poi_style);
204 surrogate_group = surrogate_group.add(svg_circle);
205 } else if ff_poles.contains(pole) {
206 let svg_circle =
207 svg_util::circle(pole.transform_clone(&int_transf), &ff_style);
208 surrogate_group = surrogate_group.add(svg_circle);
209 } else {
210 let svg_circle =
211 svg_util::circle(pole.transform_clone(&int_transf), &no_ff_style);
212 surrogate_group = surrogate_group.add(svg_circle);
213 }
214 }
215 for pier in &surrogate.piers {
216 surrogate_group = surrogate_group.add(svg_util::data_to_path(
217 svg_util::edge_data(pier.transform_clone(&int_transf)),
218 &ff_style,
219 ));
220 }
221 surrogate_defs = surrogate_defs.add(surrogate_group)
222 }
223
224 if options.highlight_cd_shapes {
225 let t_shape_cd = item.shape_cd.transform_clone(&int_transf);
226 let svg_cd_shape = svg_util::data_to_path(
228 svg_util::simple_polygon_data(&t_shape_cd),
229 highlight_cd_shape_style,
230 )
231 .set("id", format!("cd_shape_{}", item.id));
232 item_defs = item_defs.add(svg_cd_shape);
233 }
234 }
235 let mut items_group = Group::new().set("id", "items").add(item_defs);
236 let mut surrogate_group = Group::new().set("id", "surrogates").add(surrogate_defs);
237 let mut highlight_cd_shapes_group = Group::new().set("id", "highlight_cd_shapes");
238
239 for pi in layout.placed_items.values() {
240 let dtransf = match options.draw_cd_shapes {
241 true => pi.d_transf,
242 false => {
243 let item = instance.item(pi.item_id);
244 int_to_ext_transformation(&pi.d_transf, &item.shape_orig.pre_transform)
245 }
246 };
247 let title = Title::new(format!("item, id: {}, transf: [{}]", pi.item_id, dtransf));
248 let pi_ref = Use::new()
249 .set("transform", transform_to_svg(dtransf))
250 .set("href", format!("#item_{}", pi.item_id))
251 .add(title);
252
253 items_group = items_group.add(pi_ref);
254
255 if options.surrogate {
256 let pi_surr_ref = Use::new()
257 .set("transform", transform_to_svg(dtransf))
258 .set("href", format!("#surrogate_{}", pi.item_id));
259
260 surrogate_group = surrogate_group.add(pi_surr_ref);
261 }
262 if options.highlight_cd_shapes {
263 let pi_cd_ref = Use::new()
264 .set("transform", transform_to_svg(dtransf))
265 .set("href", format!("#cd_shape_{}", pi.item_id));
266 highlight_cd_shapes_group = highlight_cd_shapes_group.add(pi_cd_ref);
267 }
268 }
269
270 (items_group, surrogate_group, highlight_cd_shapes_group)
271 };
272
273 let qt_group = match options.quadtree {
275 false => None,
276 true => {
277 let qt_data = svg_util::quad_tree_data(&layout.cde().quadtree, &NoHazardFilter);
278 let qt_group = Group::new()
279 .set("id", "quadtree")
280 .add(svg_util::data_to_path(
281 qt_data.0,
282 &[
283 ("fill", "red"),
284 ("stroke-width", &*format!("{}", stroke_width * 0.25)),
285 ("fill-rule", "nonzero"),
286 ("fill-opacity", "0.6"),
287 ("stroke", "black"),
288 ],
289 ))
290 .add(svg_util::data_to_path(
291 qt_data.1,
292 &[
293 ("fill", "none"),
294 ("stroke-width", &*format!("{}", stroke_width * 0.25)),
295 ("fill-rule", "nonzero"),
296 ("fill-opacity", "0.3"),
297 ("stroke", "black"),
298 ],
299 ))
300 .add(svg_util::data_to_path(
301 qt_data.2,
302 &[
303 ("fill", "green"),
304 ("fill-opacity", "0.6"),
305 ("stroke-width", &*format!("{}", stroke_width * 0.25)),
306 ("stroke", "black"),
307 ],
308 ));
309 Some(qt_group)
310 }
311 };
312
313 let collision_group = match options.highlight_collisions {
315 false => None,
316 true => {
317 let mut collision_group = Group::new().set("id", "collision_lines");
318 for (pk, pi) in layout.placed_items.iter() {
319 let detector = {
320 let mut detector = BasicHazardDetector::new();
321 layout
322 .cde()
323 .collect_poly_collisions(pi.shape.as_ref(), &mut detector);
324 detector.remove(&HazardEntity::from((pk, pi)));
325 detector
326 };
327 for haz_entity in detector.iter() {
328 match haz_entity {
329 HazardEntity::PlacedItem {
330 pk: colliding_pk, ..
331 } => {
332 let haz_hash = {
333 let mut hasher = DefaultHasher::new();
334 haz_entity.hash(&mut hasher);
335 hasher.finish()
336 };
337 let pi_hash = {
338 let mut hasher = DefaultHasher::new();
339 HazardEntity::from((pk, pi)).hash(&mut hasher);
340 hasher.finish()
341 };
342
343 if haz_hash < pi_hash {
344 let start = pi.shape.poi.center;
346 let end = layout.placed_items[*colliding_pk].shape.poi.center;
347 collision_group = collision_group.add(svg_util::data_to_path(
348 svg_util::edge_data(Edge { start, end }),
349 &[
350 (
351 "stroke",
352 &*format!("{}", theme.collision_highlight_color),
353 ),
354 ("stroke-opacity", "0.75"),
355 ("stroke-width", &*format!("{}", stroke_width * 4.0)),
356 (
357 "stroke-dasharray",
358 &*format!(
359 "{} {}",
360 4.0 * stroke_width,
361 8.0 * stroke_width
362 ),
363 ),
364 ("stroke-linecap", "round"),
365 ("stroke-linejoin", "round"),
366 ],
367 ));
368 }
369 }
370 HazardEntity::Exterior => {
371 collision_group = collision_group.add(svg_util::point(
372 pi.shape.poi.center,
373 Some(&*format!("{}", theme.collision_highlight_color)),
374 Some(3.0 * stroke_width),
375 ));
376 }
377 _ => {
378 warn!("unexpected hazard entity");
379 }
380 }
381 }
382 }
383 Some(collision_group)
384 }
385 };
386
387 let vbox_svg = (vbox.x_min, vbox.y_min, vbox.width(), vbox.height());
388
389 if options.highlight_cd_shapes {
390 highlight_cd_shape_group = highlight_cd_shape_group.add(svg_util::data_to_path(
391 svg_util::simple_polygon_data(&container.outer_cd),
392 highlight_cd_shape_style,
393 ));
394 }
395
396 let optionals = [
397 Some(highlight_cd_shape_group),
398 Some(surrogate_group),
399 qt_group,
400 collision_group,
401 ]
402 .into_iter()
403 .flatten()
404 .fold(Group::new().set("id", "optionals"), |g, opt| g.add(opt));
405
406 Document::new()
407 .set("viewBox", vbox_svg)
408 .add(container_group)
409 .add(items_group)
410 .add(qz_group)
411 .add(optionals)
412 .add(label)
413}
414fn transform_to_svg(dt: DTransformation) -> String {
415 let (tx, ty) = dt.translation();
418 let r = dt.rotation().to_degrees();
419 format!("translate({tx} {ty}), rotate({r})")
420}