lib/Graphics/Penplotter/GcodeXY/Anamorphic.pm untested

filter: Statementstmt 0.0% 0 / 161 Branchbran 0.0% 0 / 52 Conditioncond 0.0% 0 / 23 MC/DCmcdc 0.0% 0 / 14 Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 269 CC 27 SCAR 41.5
CC
27
Cov
0%
anamorphic
156.0
_ana_transform_point
42.0
_ana_ray_cylinder
30.0
CRAP 63.5
1 package Graphics::Penplotter::GcodeXY::Anamorphic v0.9.4;
2  
3 # Role::Tiny role adding anamorphic cylindrical mirror projection to GcodeXY.
4 #
5 # An anamorphic image is a distorted drawing that appears correct only when
6 # viewed in a curved mirror. The caller first populates the GcodeXY segment
7 # path using any available drawing primitives, then calls anamorphic() to
8 # replace that path in-place with a distorted version such that a reflective
9 # cylindrical mirror placed at the given position will show the observer the
10 # original image.
11 #
12 # Physical model
13 # --------------
14 # The cylinder stands upright (axis parallel to z) with its base on the paper
15 # (z = 0). The observer is at world position
16 #
17 # E = ( cx + D*cos(alpha), cy + D*sin(alpha), H )
18 #
19 # where D = obs_dist, H = obs_height, and alpha = obs_angle (in radians).
20 #
21 # For every pixel of the source image at normalised coordinates (s, t):
22 # 1. Compute the 3-D viewing direction from E corresponding to (s, t).
23 # 2. Find where that ray first hits the cylinder surface (mirror point M).
24 # 3. Reflect the incident direction off the cylinder's outward normal at M.
25 # 4. Follow the reflected ray until it hits z = 0 (the paper).
26 # 5. The paper hit point is where the distorted drawing must be made.
27 #
28 # Coordinate conventions
29 # ----------------------
30 # SVG coordinates: u increases to the right, v increases downward (standard
31 # SVG). The image is laid out such that:
32 # * Horizontal centre of image (s = 0) aligns with the observer looking
33 # directly at the cylinder.
34 # * Image left (s < 0) is the observer's right side of the mirror.
35 # * Image right (s > 0) is the observer's left side of the mirror.
36 # * Image top (t < 0) is the upper part of the mirror.
37 # * Image bottom(t > 0) is the lower part (closer to the paper).
38  
39 use v5.38.2;
40 use strict;
41 use warnings;
42 use Role::Tiny;
43 use Carp qw( croak );
44 use List::Util qw( min max );
45 use POSIX qw( ceil );
46  
47 # ---------------------------------------------------------------------------
48 # The consuming class must provide these primitive hooks
49 # ---------------------------------------------------------------------------
50 requires qw(
51 _croak
52 stroke
53 );
54  
55 # ---------------------------------------------------------------------------
56 # Module-private constants
57 # ---------------------------------------------------------------------------
58  
59 my $PI = 3.14159265358979323846;
60 my $D2R = $PI / 180.0;
61  
62 # ===========================================================================
63 # PURE MATH HELPERS
64 # All functions below are plain subs (not methods) so that test code can call
65 # them without a host object. They are all prefixed _ana_ for namespacing.
66 # ===========================================================================
67  
68 # ---------------------------------------------------------------------------
69 # _ana_ray_cylinder
70 #
71 # Find the smallest positive parameter t at which the ray
72 #
73 # P(t) = ( ex + t*dx, ey + t*dy, ez + t*dz )
74 #
75 # intersects the infinite vertical cylinder of radius R whose axis passes
76 # through ( cx, cy ). Only the horizontal components (dx, dy) are used for
77 # the cylinder test; the ray also advances along z but the cylinder is
78 # infinite in that direction.
79 #
80 # Returns t on success, undef if the ray is parallel to the axis or misses
81 # the cylinder, or if both intersections are behind the ray origin.
82 # ---------------------------------------------------------------------------
83 sub _ana_ray_cylinder {
84 my ($ex, $ey, $ez, $dx, $dy, $dz, $cx, $cy, $R) = @_;
85  
86 my $qx = $ex - $cx;
87 my $qy = $ey - $cy;
88 my $A = $dx*$dx + $dy*$dy;
89 return undef if $A < 1e-14; # ray runs parallel to cylinder axis
90  
91 my $B = 2.0 * ($qx*$dx + $qy*$dy);
92 my $C = $qx*$qx + $qy*$qy - $R*$R;
93 my $disc = $B*$B - 4.0*$A*$C;
94 return undef if $disc < 0; # ray misses cylinder entirely
95  
96 my $sq = sqrt($disc);
97 my $t1 = (-$B - $sq) / (2.0 * $A);
98 my $t2 = (-$B + $sq) / (2.0 * $A);
99  
100 return $t1 if $t1 > 1e-9; # prefer the nearer (entry) intersection
101 return $t2 if $t2 > 1e-9;
102 return undef; # both intersections are behind the origin
103 }
104  
105 # ---------------------------------------------------------------------------
106 # _ana_reflect
107 #
108 # Reflect the (already unit-length) incident direction vector D = (dx,dy,dz)
109 # off the surface whose outward unit normal is N = (nx,ny,nz).
110 #
111 # Formula: D_ref = D - 2 * (D.N) * N
112 #
113 # Returns (rx, ry, rz). The reflected vector has the same magnitude as D.
114 # ---------------------------------------------------------------------------
115 sub _ana_reflect {
116 my ($dx, $dy, $dz, $nx, $ny, $nz) = @_;
117 my $dot2 = 2.0 * ($dx*$nx + $dy*$ny + $dz*$nz);
118 return ($dx - $dot2*$nx,
119 $dy - $dot2*$ny,
120 $dz - $dot2*$nz);
121 }
122  
123 # ---------------------------------------------------------------------------
124 # _ana_build_config
125 #
126 # Compute the observer and image-mapping configuration hash from the cylinder
127 # parameters ($cx, $cy, $R) and optional user overrides (%opts).
128 #
129 # Returned hash keys:
130 # ex, ey, ez - observer world position
131 # phi_fwd - azimuth of the direction FROM observer TOWARD cylinder
132 # ang_rad - total horizontal angular range of the image (radians)
133 # beta0 - centre elevation (radians below horizontal)
134 # elev_rad - total vertical angular range (radians)
135 # cx, cy, R - cylinder parameters (passed through)
136 # ---------------------------------------------------------------------------
137 sub _ana_build_config {
138 my ($cx, $cy, $R, %opts) = @_;
139 croak 'cylinder radius R must be > 0' if $R <= 0;
140  
141 my $obs_dist = $opts{obs_dist} // (5.0 * $R);
142 my $obs_height = $opts{obs_height} // (5.0 * $R);
143 my $obs_angle = ($opts{obs_angle} // 0.0) * $D2R;
144  
145 croak 'obs_dist must be > R (observer must be outside the cylinder)'
146 if $obs_dist <= $R;
147  
148 # Observer world position
149 my $ex = $cx + $obs_dist * cos($obs_angle);
150 my $ey = $cy + $obs_dist * sin($obs_angle);
151 my $ez = $obs_height;
152  
153 # Forward azimuth: direction from observer E toward cylinder centre
154 my $phi_fwd = atan2($cy - $ey, $cx - $ex);
155  
156 # Maximum azimuthal half-angle that can hit the cylinder.
157 # sin(half_max) = R / obs_dist => half_max = asin(R / obs_dist).
158 # Implemented via atan2 to avoid a POSIX::asin dependency.
159 my $ratio = min($R / $obs_dist, 1.0);
160 my $half_max = atan2($ratio, sqrt(1.0 - $ratio*$ratio));
161  
162 my $ang_rad;
163 if (defined $opts{angle_range}) {
164 $ang_rad = $opts{angle_range} * $D2R;
165 }
166 else {
167 $ang_rad = 2.0 * $half_max * 0.90; # 90 % of the full visible cone
168 }
169  
170 # Centre elevation: the angle below horizontal that looks at the base of
171 # the cylinder (z = 0) from the observer's position.
172 my $beta0 = atan2($obs_height, $obs_dist);
173  
174 my $elev_rad;
175 if (defined $opts{elev_range}) {
176 $elev_rad = $opts{elev_range} * $D2R;
177 }
178 else {
179 $elev_rad = $beta0 * 0.80; # 80 % of the base elevation
180 }
181  
182 return (
183 ex => $ex,
184 ey => $ey,
185 ez => $ez,
186 phi_fwd => $phi_fwd,
187 ang_rad => $ang_rad,
188 beta0 => $beta0,
189 elev_rad => $elev_rad,
190 cx => $cx,
191 cy => $cy,
192 R => $R,
193 );
194 }
195  
196 # ---------------------------------------------------------------------------
197 # _ana_transform_point
198 #
199 # Map one image point (u, v) within the image bounding box
200 # ($u0, $v0) -- ($u1, $v1) to paper coordinates (px, py), using the
201 # prebuilt configuration hash %cfg (from _ana_build_config).
202 #
203 # SVG coordinate convention: u increases right, v increases downward.
204 #
205 # Returns (px, py) on success, or an empty list () if the viewing ray misses
206 # the cylinder, or if the reflected ray travels upward (away from the paper).
207 # ---------------------------------------------------------------------------
208 sub _ana_transform_point {
209 my ($u, $v, $u0, $v0, $u1, $v1, %cfg) = @_;
210  
211 my $iw = $u1 - $u0;
212 my $ih = $v1 - $v0;
213 return () if $iw < 1e-12 || $ih < 1e-12;
214  
215 # Normalise to [-0.5, +0.5]: s = horizontal (right +), t = vertical (down +)
216 my $s = ($u - $u0) / $iw - 0.5;
217 my $t = ($v - $v0) / $ih - 0.5;
218  
219 # Map to viewing angles from the observer.
220 # phi: azimuth of the viewing ray. Right side of image (s > 0) means the
221 # observer looks more counterclockwise (toward their left).
222 my $phi = $cfg{phi_fwd} + $s * $cfg{ang_rad};
223  
224 # beta: elevation angle below horizontal. Image bottom (t > 0 in SVG)
225 # maps to looking further downward.
226 my $beta = $cfg{beta0} + $t * $cfg{elev_rad};
227  
228 # Unit viewing direction from observer toward the mirror
229 my $cos_b = cos($beta);
230 my $dx = $cos_b * cos($phi);
231 my $dy = $cos_b * sin($phi);
232 my $dz = -sin($beta); # negative z = downward toward paper
233  
234 # Intersect the viewing ray with the cylinder surface
235 my $t_cyl = _ana_ray_cylinder(
236 $cfg{ex}, $cfg{ey}, $cfg{ez},
237 $dx, $dy, $dz,
238 $cfg{cx}, $cfg{cy}, $cfg{R},
239 );
240 return () unless defined $t_cyl;
241  
242 # Mirror surface point M
243 my $mx = $cfg{ex} + $t_cyl * $dx;
244 my $my = $cfg{ey} + $t_cyl * $dy;
245 my $mz = $cfg{ez} + $t_cyl * $dz;
246  
247 # The cylinder hit must be at or above the paper (z >= 0)
248 return () if $mz < -1e-9;
249  
250 # Outward unit normal at M (horizontal, pointing away from cylinder axis)
251 my $nx = ($mx - $cfg{cx}) / $cfg{R};
252 my $ny = ($my - $cfg{cy}) / $cfg{R};
253  
254 # Reflect the incident ray off the cylinder surface (nz = 0 for a vertical
255 # cylinder, so the z component of the reflected ray is unchanged)
256 my ($rx, $ry, $rz) = _ana_reflect($dx, $dy, $dz, $nx, $ny, 0.0);
257  
258 # The reflected ray must travel downward (rz < 0) to reach the paper
259 return () if $rz >= -1e-9;
260  
261 # Intersect the reflected ray with the paper plane (z = 0)
262 my $t_paper = -$mz / $rz;
263 return () if $t_paper < 0;
264  
265 my $px = $mx + $t_paper * $rx;
266 my $py = $my + $t_paper * $ry;
267 return ($px, $py);
268 }
269  
270 # ---------------------------------------------------------------------------
271 # _ana_resample_segment
272 #
273 # Given endpoints (x0,y0) and (x1,y1) in image space, return a list of
274 # [ x, y ] sample-point arrayrefs spaced at most $step apart. The start
275 # point is NOT included (the caller holds it); the end point IS included.
276 # ---------------------------------------------------------------------------
277 sub _ana_resample_segment {
278 my ($x0, $y0, $x1, $y1, $step) = @_;
279 my $ddx = $x1 - $x0;
280 my $ddy = $y1 - $y0;
281 my $dist = sqrt($ddx*$ddx + $ddy*$ddy);
282 if ($dist < 1e-12) { return ([$x1, $y1]) }
283 my $n = ceil($dist / $step);
284 $n = 1 if $n < 1;
285 my @pts;
286 for my $i (1 .. $n) {
287 my $f = $i / $n;
288 push @pts, [$x0 + $f*$ddx, $y0 + $f*$ddy];
289 }
290 return @pts;
291 }
292  
293 # ===========================================================================
294 # PUBLIC ENTRY POINT
295 # ===========================================================================
296  
297  
298  
299 # ---------------------------------------------------------------------------
300 # anamorphic
301 #
302 # Transform the current segment path through the cylindrical mirror model.
303 #
304 # Usage:
305 # $g->anamorphic( $cx, $cy, $R, %opts );
306 #
307 # $cx, $cy Centre of the cylindrical mirror in drawing coordinates.
308 # $R Radius of the cylindrical mirror in the same units.
309 # %opts Optional parameters (see POD / _ana_build_config).
310 #
311 # The method reads the existing psegments, uses their bounding box as the
312 # image extent, projects every sample point through the mirror model, writes
313 # the transformed segments back into psegments, then calls stroke() to flush.
314 # ---------------------------------------------------------------------------
315 sub anamorphic {
316 my ($self, $cx, $cy, $R, %opts) = @_;
317  
318 $self->_croak('anamorphic: cylinder radius R must be > 0') unless $R > 0;
319  
320 my $step = delete $opts{step} // 1.0;
321  
322 # ------------------------------------------------------------------
323 # Collect all drawable segment endpoints and compute the image bbox.
324 # ------------------------------------------------------------------
325 my @segs = @{ $self->{psegments} };
326  
327 my (@xs, @ys);
328 for my $s (@segs) {
329 my $k = $s->{key} // '';
330 next unless $k eq 'm' || $k eq 'l';
331 push @xs, $s->{sx}, $s->{dx};
332 push @ys, $s->{sy}, $s->{dy};
333 }
334 $self->_croak('anamorphic: segment path is empty') unless @xs;
335  
336 my ($u0, $v0) = (min(@xs), min(@ys));
337 my ($u1, $v1) = (max(@xs), max(@ys));
338  
339 $self->_croak('anamorphic: segment path has zero width or height')
340 if $u1 - $u0 < 1e-12 || $v1 - $v0 < 1e-12;
341  
342 # ------------------------------------------------------------------
343 # Build observer / image-mapping configuration.
344 # ------------------------------------------------------------------
345 my %cfg = _ana_build_config($cx, $cy, $R, %opts);
346  
347 # ------------------------------------------------------------------
348 # Extract polylines from the segment path.
349 # Each 'm' entry starts a new polyline; 'l' entries continue it,
350 # resampled at most $step apart so the non-linear transform stays
351 # accurate along longer segments.
352 # ------------------------------------------------------------------
353 my @polylines;
354 my @cur;
355 for my $s (@segs) {
356 my $k = $s->{key} // '';
357 if ($k eq 'm') {
358 push @polylines, [@cur] if @cur > 1;
359 @cur = ([$s->{dx}, $s->{dy}]);
360 }
361 elsif ($k eq 'l') {
362 push @cur,
363 _ana_resample_segment($s->{sx}, $s->{sy},
364 $s->{dx}, $s->{dy}, $step);
365 }
366 # penup / pendown / comment entries are ignored
367 }
368 push @polylines, [@cur] if @cur > 1;
369  
370 $self->_croak('anamorphic: segment path contains no drawable segments')
371 unless @polylines;
372  
373 # ------------------------------------------------------------------
374 # Replace the segment path with the transformed version, then flush.
375 # ------------------------------------------------------------------
376 @{ $self->{psegments} } = ();
377  
378 for my $poly (@polylines) {
379 my $pen_is_down = 0;
380 my ($prev_px, $prev_py);
381  
382 for my $pt (@$poly) {
383 my ($px, $py) = _ana_transform_point(
384 $pt->[0], $pt->[1],
385 $u0, $v0, $u1, $v1,
386 %cfg,
387 );
388 unless (defined $px) {
389 $pen_is_down = 0; # ray missed; lift pen before next valid point
390 next;
391 }
392 if (!$pen_is_down) {
393 # Insert an explicit PU / move / PD triple and mark it preserved
394 push @{ $self->{psegments} },
395 { key => 'u', sx => -1, sy => -1, dx => -1, dy => -1 };
396 push @{ $self->{psegments} },
397 { key => 'm', sx => $px, sy => $py, dx => $px, dy => $py, preserve => 1 };
398 push @{ $self->{psegments} },
399 { key => 'd', sx => -1, sy => -1, dx => -1, dy => -1 };
400 $pen_is_down = 1;
401 }
402 else {
403 push @{ $self->{psegments} },
404 { key => 'l', sx => $prev_px, sy => $prev_py,
405 dx => $px, dy => $py };
406 }
407 ($prev_px, $prev_py) = ($px, $py);
408 }
409 }
410  
411 $self->stroke();
412 return 1;
413 }
414  
415  
416 1;
417  
418 __END__