| 1 | package Term::Fabulous::Chart::Radial; | ||
| 2 | |||
| 3 | use v5.32; | ||
| 4 | use warnings; | ||
| 5 | use feature 'signatures'; | ||
| 6 | no warnings 'experimental::signatures'; | ||
| 7 | |||
| 8 | our $VERSION = '0.05'; | ||
| 9 | |||
| 10 | use Exporter 'import'; | ||
| 11 | our @EXPORT_OK = qw(CELL_ASPECT TAU circle_frame polar_of point_at); | ||
| 12 | |||
| 13 | use List::Util qw(min); | ||
| 14 | |||
| 15 | # A terminal cell is about twice as high as it is wide; round charts | ||
| 16 | # measure in cell widths and stretch rows by this factor. | ||
| 17 | use constant CELL_ASPECT => 2; | ||
| 18 | use constant TAU => 8 * atan2( 1, 1 ); | ||
| 19 | |||
| 20 | # How far from a whole number a coordinate may be and still count as it. | ||
| 21 | use constant WHOLE_TOLERANCE => 1e-9; | ||
| 22 | |||
| 23 | # The largest circle that fits an area of cells: its center in cells | ||
| 24 | # (continuous) and its radius in cell widths. $margin cell widths stay | ||
| 25 | # free around it. | ||
| 26 | sub circle_frame ( $x, $y, $width, $height, $margin = 0 ) { | ||
| 27 | my $radius = min( $width / 2, $height * CELL_ASPECT / 2 ) - $margin; | ||
| 28 | return { center_x => $x + $width / 2, center_y => $y + $height / 2, radius => $radius > 0 ? $radius : 0 }; | ||
| 29 | } | ||
| 30 | |||
| 31 | # The polar coordinates of a point in cells: the distance from the | ||
| 32 | # center in cell widths and the angle in turns (0 to 1) clockwise from | ||
| 33 | # $start (in turns; 0 is 12 o'clock). | ||
| 34 | sub polar_of ( $frame, $x, $y, $start = 0 ) { | ||
| 35 | my $dx = $x - $frame->{center_x}; | ||
| 36 | my $dy = ( $y - $frame->{center_y} ) * CELL_ASPECT; | ||
| 37 | my $angle = atan2( $dx, -$dy ) / TAU - $start; | ||
| 38 | $angle -= int($angle); | ||
| 39 | $angle += 1 if $angle < 0; | ||
| 40 | return ( sqrt( $dx**2 + $dy**2 ), $angle ); | ||
| 41 | } | ||
| 42 | |||
| 43 | # The point in cells at a distance (cell widths) and an angle (turns | ||
| 44 | # clockwise from 12 o'clock, after $start). | ||
| 45 | # A coordinate that is mathematically whole comes back whole: the | ||
| 46 | # rounding noise of sin and cos at a quarter turn differs between | ||
| 47 | # platforms (long double perls get the other sign), and a label or | ||
| 48 | # point must not land in the cell before or after its own for that. | ||
| 49 | sub point_at ( $frame, $distance, $angle, $start = 0 ) { | ||
| 50 | my $radians = ( $angle + $start ) * TAU; | ||
| 51 | return map { _whole_when_close($_) } $frame->{center_x} + $distance * sin($radians), $frame->{center_y} - $distance * cos($radians) / CELL_ASPECT; | ||
| 52 | } | ||
| 53 | |||
| 54 | sub _whole_when_close ($coordinate) { | ||
| 55 | my $nearest = sprintf '%.0f', $coordinate; | ||
| 56 | return abs( $coordinate - $nearest ) < WHOLE_TOLERANCE ? $nearest + 0 : $coordinate; | ||
| 57 | } | ||
| 58 | |||
| 59 | 1; | ||
| 60 | |||
| 61 | __END__ |