1use kurbo::{Affine, BezPath, Shape};
2use pax_engine::api::LocalProperty;
3use pax_engine::api::Size;
4use pax_engine::*;
5use pax_runtime::api as pax_runtime_api;
6#[cfg(test)]
7use pax_runtime::api::drawing::stroke_utils::stroked_outline_path;
8use pax_runtime::api::{use_RefCell, Layer, RenderContext, Stroke};
9use pax_runtime::BaseInstance;
10use pax_runtime::{ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext};
11
12use crate::common::to_kurbo_point;
13
14use_RefCell!();
15use std::rc::Rc;
16
17#[pax]
23#[engine_import_path("pax_engine")]
24#[primitive("pax_std::drawing::line::LineInstance")]
25pub struct Line {
26 pub x1: Property<Size>,
28 pub y1: Property<Size>,
30 pub x2: Property<Size>,
32 pub y2: Property<Size>,
34 pub stroke: Property<Vec<Stroke>>,
36}
37
38pub struct LineInstance {
40 base: BaseInstance,
41}
42
43impl InstanceNode for LineInstance {
44 fn supports_alpha_source_render(&self) -> bool {
45 true
46 }
47
48 fn instantiate(args: InstantiationArgs) -> Rc<Self>
49 where
50 Self: Sized,
51 {
52 Rc::new(Self {
53 base: BaseInstance::new(
54 args,
55 InstanceFlags {
56 invisible_to_slot: false,
57 invisible_to_raycasting: false,
58 layer: Layer::Canvas,
59 is_component: false,
60 is_slot: false,
61 },
62 ),
63 })
64 }
65
66 fn handle_mount(
67 self: Rc<Self>,
68 expanded_node: &Rc<ExpandedNode>,
69 context: &Rc<RuntimeContext>,
70 ) {
71 let tab = expanded_node.transform_and_bounds.clone();
72 let (x1, y1, x2, y2, stroke) =
73 expanded_node.with_properties_unwrapped(|properties: &mut Line| {
74 (
75 properties.x1.local(),
76 properties.y1.local(),
77 properties.x2.local(),
78 properties.y2.local(),
79 properties.stroke.local(),
80 )
81 });
82
83 let appearance = crate::common::watch_appearance(
84 expanded_node,
85 context,
86 LocalProperty::new(Vec::new()),
87 stroke.clone(),
88 );
89 let deps = &[
90 appearance.untyped(),
91 tab.untyped(),
92 x1.untyped(),
93 y1.untyped(),
94 x2.untyped(),
95 y2.untyped(),
96 stroke.untyped(),
97 expanded_node.computed_opacity.untyped(),
98 expanded_node.computed_opacity_scopes.untyped(),
99 ];
100 let cloned_expanded_node = expanded_node.clone();
101 let cloned_context = context.clone();
102
103 expanded_node
104 .changed_listener
105 .replace_with(LocalProperty::computed(
106 move || {
107 appearance.get();
108 cloned_context.mark_canvas_node_dirty(cloned_expanded_node.id);
109 cloned_context
110 .set_canvas_dirty(cloned_expanded_node.occlusion.get().render_layer_id)
111 },
112 deps,
113 ));
114 }
115
116 fn ray_cast_test(
117 &self,
118 expanded_node: &ExpandedNode,
119 ray: pax_runtime::api::math::Point2<pax_runtime::api::Window>,
120 ) -> bool {
121 self.resolve_coverage_path(expanded_node)
122 .is_some_and(|path| {
123 path_contains_with_tolerance(&path, kurbo::Point::new(ray.x, ray.y))
124 })
125 }
126
127 fn resolve_coverage_path(&self, expanded_node: &ExpandedNode) -> Option<BezPath> {
128 expanded_node.with_properties_unwrapped(|properties: &mut Line| {
129 let tab = expanded_node.transform_and_bounds.get();
130 let (start, end) = resolve_points(properties, tab.bounds);
131 let stroke = properties.stroke.local().get();
132 Some(
133 Affine::from(tab.transform)
134 * crate::common::appearance_coverage_path(
135 ¢erline_path(start, end),
136 &[],
137 &stroke,
138 ),
139 )
140 })
141 }
142
143 fn resolve_alpha_mask_paints(
144 &self,
145 node: &ExpandedNode,
146 ) -> Vec<pax_runtime_api::AlphaMaskPaint> {
147 node.with_properties_unwrapped(|p: &mut Line| {
148 let (start, end) = resolve_points(p, node.transform_and_bounds.get().bounds);
149 crate::common::alpha_mask_paints(
150 node,
151 centerline_path(start, end),
152 Vec::new(),
153 p.stroke.local().get(),
154 )
155 })
156 }
157
158 fn resolve_coverage_opacity(&self, expanded_node: &ExpandedNode) -> f64 {
159 expanded_node.with_properties_unwrapped(|properties: &mut Line| {
160 let stroke = properties.stroke.local().get();
161 (crate::common::appearance_coverage_alpha(&[], &stroke)
162 * expanded_node.computed_opacity.get())
163 .clamp(0.0, 1.0)
164 })
165 }
166
167 fn prepare_canvas_geometry(
168 &self,
169 node: &ExpandedNode,
170 ) -> pax_runtime::scene_geometry::CanvasGeometry {
171 let bounds = node.transform_and_bounds.get().bounds;
172 let local_bounds = node.with_properties_unwrapped(|p: &mut Line| {
173 let (start, end) = resolve_points(p, bounds);
174 crate::common::stroke_coverage_bounds(
175 centerline_path(start, end).bounding_box(),
176 &p.stroke.local().get(),
177 )
178 });
179 pax_runtime::scene_geometry::CanvasGeometry {
180 local_bounds: Some(local_bounds),
181 path: None,
182 }
183 }
184
185 fn render(
186 &self,
187 expanded_node: &ExpandedNode,
188 rtc: &Rc<RuntimeContext>,
189 rc: &mut dyn RenderContext,
190 ) {
191 if rc.alpha_source_layer().is_none() && !rtc.is_canvas_node_dirty(&expanded_node.id) {
192 return;
193 }
194
195 let Some(scope) = crate::common::begin_bounded_canvas_node(rc, expanded_node, rtc) else {
196 return;
197 };
198
199 expanded_node.with_properties_unwrapped(|properties: &mut Line| {
200 let (start, end) = resolve_points(properties, scope.bounds);
201 rc.save(scope.layer_id);
202 rc.transform(scope.layer_id, scope.surface_transform);
203 crate::common::draw_appearance(
204 rc,
205 scope.layer_id,
206 centerline_path(start, end),
207 &[],
208 &properties.stroke.local().get(),
209 scope.paint_opacity,
210 pax_runtime_api::PathSmoothing::None,
211 0.0,
212 1.0,
213 );
214 rc.restore(scope.layer_id);
215 });
216
217 if rc.end_node(scope.layer_id, scope.node_id) {
218 rtc.clear_canvas_node_dirty(&expanded_node.id);
219 }
220 }
221
222 fn resolve_debug(
223 &self,
224 f: &mut std::fmt::Formatter,
225 expanded_node: Option<&ExpandedNode>,
226 ) -> std::fmt::Result {
227 match expanded_node {
228 Some(expanded_node) => expanded_node.with_properties_unwrapped(|line: &mut Line| {
229 f.debug_struct("Line")
230 .field("x1", &line.x1.local().get())
231 .field("y1", &line.y1.local().get())
232 .field("x2", &line.x2.local().get())
233 .field("y2", &line.y2.local().get())
234 .finish()
235 }),
236 None => f.debug_struct("Line").finish_non_exhaustive(),
237 }
238 }
239
240 fn base(&self) -> &BaseInstance {
241 &self.base
242 }
243}
244
245fn resolve_points(line: &Line, bounds: (f64, f64)) -> (kurbo::Point, kurbo::Point) {
246 (
247 to_kurbo_point(line.x1.local().get(), line.y1.local().get(), bounds),
248 to_kurbo_point(line.x2.local().get(), line.y2.local().get(), bounds),
249 )
250}
251
252fn centerline_path(start: kurbo::Point, end: kurbo::Point) -> BezPath {
253 let mut path = BezPath::new();
254 path.move_to(start);
255 path.line_to(end);
256 path
257}
258
259#[cfg(test)]
260fn line_coverage_path(
261 start: kurbo::Point,
262 end: kurbo::Point,
263 stroke: &pax_runtime_api::ResolvedStroke,
264) -> Option<BezPath> {
265 stroked_outline_path(¢erline_path(start, end), stroke)
266}
267
268fn path_contains_with_tolerance(path: &BezPath, point: kurbo::Point) -> bool {
269 if path.contains(point) {
270 return true;
271 }
272
273 const HIT_TEST_EPSILON: f64 = 1e-3;
274 [
275 (HIT_TEST_EPSILON, 0.0),
276 (-HIT_TEST_EPSILON, 0.0),
277 (0.0, HIT_TEST_EPSILON),
278 (0.0, -HIT_TEST_EPSILON),
279 ]
280 .into_iter()
281 .any(|(dx, dy)| path.contains(kurbo::Point::new(point.x + dx, point.y + dy)))
282}
283
284#[cfg(test)]
285mod tests {
286 use super::{line_coverage_path, path_contains_with_tolerance};
287 use kurbo::{Point, Shape};
288 use pax_runtime::api::{Property, Size, Stroke, StrokeCap, StrokeJoin};
289
290 fn test_stroke(width: f64, cap: StrokeCap) -> pax_runtime::api::ResolvedStroke {
291 Stroke {
292 paint: Property::new(pax_runtime::api::Color::BLACK.into()),
293 width: Property::new(Size::Pixels(width.into())),
294 cap: Property::new(cap),
295 join: Property::new(StrokeJoin::default()),
296
297 ..Stroke::default()
298 }
299 .snapshot()
300 }
301
302 #[test]
303 fn horizontal_line_coverage_has_area() {
304 let path = line_coverage_path(
305 Point::new(0.0, 0.0),
306 Point::new(10.0, 0.0),
307 &test_stroke(2.0, StrokeCap::Butt),
308 )
309 .unwrap();
310 assert!(!path.bounding_box().is_zero_area());
311 }
312
313 #[test]
314 fn zero_length_line_coverage_has_area() {
315 let path = line_coverage_path(
316 Point::new(4.0, 8.0),
317 Point::new(4.0, 8.0),
318 &test_stroke(6.0, StrokeCap::Round),
319 )
320 .unwrap();
321 assert!(!path.bounding_box().is_zero_area());
322 }
323
324 #[test]
325 fn line_coverage_contains_points_inside_stroke() {
326 let path = line_coverage_path(
327 Point::new(0.0, 0.0),
328 Point::new(20.0, 0.0),
329 &test_stroke(6.0, StrokeCap::Butt),
330 )
331 .unwrap();
332 assert!(path.contains(Point::new(10.0, 1.0)));
333 assert!(!path.contains(Point::new(10.0, 4.0)));
334 }
335
336 #[test]
337 fn round_caps_extend_beyond_segment_endpoints() {
338 let path = line_coverage_path(
339 Point::new(0.0, 0.0),
340 Point::new(20.0, 0.0),
341 &test_stroke(6.0, StrokeCap::Round),
342 )
343 .unwrap();
344 assert!(path_contains_with_tolerance(&path, Point::new(-2.0, 0.0)));
345 assert!(path_contains_with_tolerance(&path, Point::new(22.0, 0.0)));
346 }
347}