laser-cutter 2.0.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/pages.yml +44 -0
  3. data/.gitignore +2 -0
  4. data/.openlanes/config.yml +106 -0
  5. data/.plans/004.00/342/224/201/342/224/201/342/232/252/342/224/201/342/224/201/342/235/257can-we-create-an-angled-box-where-angle-is-configurable-like-in-spec-wishes-image-shows/spec.md +40 -0
  6. data/.plans/004.00/342/224/201/342/224/201/342/232/252/342/224/201/342/224/201/342/235/257can-we-create-an-angled-box-where-angle-is-configurable-like-in-spec-wishes-image-shows/state.json +337 -0
  7. data/.plans/004.01/342/224/201/342/224/201/342/232/252/342/224/201/342/224/201/342/235/257sloped-box-panels/plan.md +91 -0
  8. data/.plans/decisions.md +11 -0
  9. data/CHANGELOG.md +134 -0
  10. data/CLAUDE.md +18 -6
  11. data/Gemfile +2 -1
  12. data/README.md +223 -50
  13. data/Rakefile +11 -7
  14. data/docs/badges/coverage_badge.svg +2 -2
  15. data/docs/decisions/decisions-on-angled-box.md +93 -0
  16. data/docs/decisions/stack.md +6 -0
  17. data/docs/images/box-3d.avif +0 -0
  18. data/docs/images/box-sloped-3d.avif +0 -0
  19. data/docs/images/box-sloped.avif +0 -0
  20. data/justfile +24 -8
  21. data/laser-cutter.gemspec +1 -1
  22. data/lib/laser/cutter/aggregator.rb +28 -0
  23. data/lib/laser/cutter/box.rb +95 -5
  24. data/lib/laser/cutter/box_factory.rb +15 -0
  25. data/lib/laser/cutter/cli/command.rb +27 -1
  26. data/lib/laser/cutter/cli/config_file.rb +2 -0
  27. data/lib/laser/cutter/cli/examples.rb +3 -0
  28. data/lib/laser/cutter/cli/generate.rb +37 -6
  29. data/lib/laser/cutter/cli/help.rb +4 -0
  30. data/lib/laser/cutter/cli/page_sizes.rb +3 -0
  31. data/lib/laser/cutter/cli/version.rb +2 -0
  32. data/lib/laser/cutter/cli.rb +23 -4
  33. data/lib/laser/cutter/configuration.rb +38 -4
  34. data/lib/laser/cutter/geometry/dimensions.rb +7 -0
  35. data/lib/laser/cutter/geometry/line.rb +42 -0
  36. data/lib/laser/cutter/geometry/loop.rb +138 -0
  37. data/lib/laser/cutter/geometry/point.rb +3 -0
  38. data/lib/laser/cutter/geometry/rect.rb +25 -0
  39. data/lib/laser/cutter/geometry/shape.rb +19 -1
  40. data/lib/laser/cutter/geometry/transform.rb +50 -0
  41. data/lib/laser/cutter/geometry/tuple.rb +47 -11
  42. data/lib/laser/cutter/launcher.rb +14 -1
  43. data/lib/laser/cutter/missing_option.rb +2 -0
  44. data/lib/laser/cutter/notching/angled_edge.rb +67 -0
  45. data/lib/laser/cutter/notching/base.rb +8 -0
  46. data/lib/laser/cutter/notching/edge.rb +44 -4
  47. data/lib/laser/cutter/notching/infinite_iterator.rb +11 -1
  48. data/lib/laser/cutter/notching/path_generator.rb +40 -6
  49. data/lib/laser/cutter/notching/shift.rb +4 -0
  50. data/lib/laser/cutter/options.rb +25 -4
  51. data/lib/laser/cutter/page_manager.rb +12 -2
  52. data/lib/laser/cutter/renderer/base.rb +19 -3
  53. data/lib/laser/cutter/renderer/box_renderer.rb +14 -1
  54. data/lib/laser/cutter/renderer/layout_renderer.rb +10 -0
  55. data/lib/laser/cutter/renderer/line_renderer.rb +6 -0
  56. data/lib/laser/cutter/renderer/meta_renderer.rb +33 -9
  57. data/lib/laser/cutter/renderer/rect_renderer.rb +5 -0
  58. data/lib/laser/cutter/renderer/svg_renderer.rb +9 -1
  59. data/lib/laser/cutter/renderer.rb +2 -0
  60. data/lib/laser/cutter/sloped/box.rb +90 -0
  61. data/lib/laser/cutter/sloped/corners.rb +58 -0
  62. data/lib/laser/cutter/sloped/layout.rb +97 -0
  63. data/lib/laser/cutter/sloped/notcher.rb +53 -0
  64. data/lib/laser/cutter/sloped/panels.rb +121 -0
  65. data/lib/laser/cutter/sloped/placement.rb +36 -0
  66. data/lib/laser/cutter/sloped/profile.rb +176 -0
  67. data/lib/laser/cutter/sloped/request.rb +31 -0
  68. data/lib/laser/cutter/sloped/ring_panel.rb +120 -0
  69. data/lib/laser/cutter/sloped/side_panel.rb +89 -0
  70. data/lib/laser/cutter/types.rb +3 -0
  71. data/lib/laser/cutter/units_converter.rb +5 -0
  72. data/lib/laser/cutter/version.rb +2 -1
  73. data/lib/laser/cutter/zero_value_not_allowed.rb +2 -0
  74. data/lib/laser/cutter.rb +2 -0
  75. data/spec/laser/cutter/angled_edge_spec.rb +103 -0
  76. data/spec/laser/cutter/box_factory_spec.rb +19 -0
  77. data/spec/laser/cutter/cli_spec.rb +87 -7
  78. data/spec/laser/cutter/configuration_spec.rb +37 -0
  79. data/spec/laser/cutter/loop_spec.rb +107 -0
  80. data/spec/laser/cutter/options_spec.rb +51 -9
  81. data/spec/laser/cutter/renderer/layout_renderer_spec.rb +18 -0
  82. data/spec/laser/cutter/renderer/meta_renderer_spec.rb +82 -0
  83. data/spec/laser/cutter/renderer/svg_renderer_spec.rb +34 -0
  84. data/spec/laser/cutter/sloped/assembly_spec.rb +78 -0
  85. data/spec/laser/cutter/sloped/box_spec.rb +151 -0
  86. data/spec/laser/cutter/sloped/corners_spec.rb +45 -0
  87. data/spec/laser/cutter/sloped/layout_spec.rb +77 -0
  88. data/spec/laser/cutter/sloped/notcher_spec.rb +57 -0
  89. data/spec/laser/cutter/sloped/panels_spec.rb +175 -0
  90. data/spec/laser/cutter/sloped/placement_spec.rb +50 -0
  91. data/spec/laser/cutter/sloped/request_spec.rb +48 -0
  92. data/spec/laser/cutter/sloped/ring_panel_spec.rb +102 -0
  93. data/spec/laser/cutter/sloped/side_panel_spec.rb +98 -0
  94. data/spec/laser/cutter/sloped_profile_spec.rb +156 -0
  95. data/spec/laser/cutter/transform_spec.rb +53 -0
  96. data/spec/spec_helper.rb +4 -0
  97. data/spec/support/loops.rb +106 -0
  98. data/spec/support/sloped.rb +26 -0
  99. data/spec/support/solid.rb +95 -0
  100. data/spec/wishes/wish-tilted-box.png +0 -0
  101. metadata +55 -9
  102. /data/.plans/{001.00-dry-cli-migration/plan.md → 001.00/342/224/201/342/224/201/342/232/252/342/224/201/342/224/201/342/235/257dry-cli-migration/plan.md"} +0 -0
  103. /data/.plans/{002.00-lid-options/plan.md → 002.00/342/224/201/342/224/201/342/232/252/342/224/201/342/224/201/342/235/257lid-options/plan.md"} +0 -0
  104. /data/.plans/{003.00-ruby-api/plan.md → 003.00/342/224/201/342/224/201/342/232/252/342/224/201/342/224/201/342/235/257ruby-api/plan.md"} +0 -0
@@ -3,9 +3,12 @@
3
3
  module Laser
4
4
  module Cutter
5
5
  module CLI
6
+ # The generate command: draws a box into a PDF or an SVG, with a
7
+ # progress bar, and saves or reads its settings as JSON.
6
8
  class Generate < Command
7
9
  desc 'Draw the panels of a box into a PDF or an SVG file'
8
10
 
11
+ # The first line of the opening box.
9
12
  BANNER = "Laser-Cutter (ruby gem) Version #{Laser::Cutter::VERSION}, © 2015-2026 Konstantin Gredeskoul".freeze
10
13
 
11
14
  # Columns a box spends on its borders and padding.
@@ -17,16 +20,18 @@ module Laser
17
20
  # Options that describe the run rather than the box, kept out of a saved configuration.
18
21
  RUN_ONLY = %i[verbose read write open format args].freeze
19
22
 
20
- option :box, aliases: ['-b'], desc: 'WxHxD/T[/N]: width, height, depth, thickness and optional notch, in one'
23
+ option :box, aliases: ['-b'], desc: 'WxHxD/T[/N]: width, height, depth, thickness and optional notch, in one expression'
21
24
  option :width, aliases: ['-w'], desc: 'Internal width of the box'
22
25
  option :height, aliases: ['-H'], desc: 'Internal height of the box'
23
26
  option :depth, aliases: ['-d'], desc: 'Internal depth of the box'
24
27
  option :thickness, aliases: ['-t'], desc: 'Thickness of the material'
28
+ option :slope, aliases: ['-S'], desc: 'When provided, changes the shape of the enclosure from a parallilepiped to one with a side sloped, for mounting an LCD or any other screen. This options defines the angle above horizontal (0º), in degrees. This option requires --front-height'
29
+ option :front_height, aliases: ['-F'], desc: 'Used with --slope: internal height at the front of a sloped box, where the slope begins. Please refer to images in the README, or 3D projections on https://makeabox.io'
30
+ option :lid, values: %w[full back plain], aliases: ['-L'],
31
+ desc: 'Lid: notched on every side, into the back wall only (not with --slope), or on no side (default: full)'
25
32
  option :notch, aliases: ['-n'], desc: 'Notch length, a guide only (default: three times the thickness)'
26
33
  option :kerf, aliases: ['-k'], desc: 'Kerf, the width of the cut (default: 0.0024in)'
27
34
  # No default here: one would override the lid a saved configuration asks for.
28
- option :lid, values: %w[full back plain], aliases: ['-L'],
29
- desc: 'Lid: notched on every side, into the back wall only, or on no side (default: full)'
30
35
  option :units, default: 'in', values: %w[in mm], aliases: ['-u'], desc: 'Units every dimension is in'
31
36
 
32
37
  option :file, aliases: ['-o'], desc: 'File to write (required)'
@@ -42,16 +47,22 @@ module Laser
42
47
  option :inside_box, type: :boolean, default: false, aliases: ['-B'],
43
48
  desc: 'Also draw the box without kerf, in red, to check the kerf'
44
49
  option :open, type: :boolean, default: false, aliases: ['-O'], desc: 'Open the file once it is written'
45
- option :write, aliases: ['-W'], desc: "Save the configuration to a file, or to STDOUT with '-'"
46
- option :read, aliases: ['-R'], desc: "Read the configuration from a file, or from STDIN with '-'"
50
+ option :write, aliases: ['-W'], desc: "Save the configuration to a file or to STDOUT with '-'"
51
+ option :read, aliases: ['-R'], desc: "Read the configuration from a file or from STDIN with '-'"
47
52
 
48
53
  example [
49
54
  '-b 3x2x2/0.125 -o box.pdf # a box in inches',
50
55
  '-b 3x2x2/0.125 -f svg -o box.svg # as an SVG',
51
56
  '-b 3x2x2/0.125 --lid plain -o box.pdf # with a lid that lifts off',
57
+ '-b 4x3x5/0.125 --slope 45 --front-height 1 -o box.pdf # with a front that slopes back',
52
58
  '-u mm -w 70 -H 20 -d 50 -t 4.3 -o box.pdf'
53
59
  ]
54
60
 
61
+ # @param format [String] "pdf" or "svg"
62
+ # @param verbose [Boolean] whether to print the configuration first
63
+ # @param options [Hash] the other options, by name
64
+ # @return [void]
65
+ # @raise [MissingOption, InvalidOption, Error] when the settings do not make a box
55
66
  def call(format:, verbose:, **options)
56
67
  config = configuration(options)
57
68
  ui.debug('Configuration:', JSON.pretty_generate(config.to_hash)) if verbose
@@ -72,11 +83,18 @@ module Laser
72
83
 
73
84
  # A box wraps in the middle of a word, which would break a path nobody
74
85
  # could then copy, so this one widens to fit a path longer than it.
86
+ #
87
+ # @param format [String]
88
+ # @param path [String] the full path of the file written
89
+ # @return [void]
75
90
  def report(format, path)
76
91
  ui.success("Generated #{format.upcase} file:", path, width: [CLI.help_width, path.length + BOX_CHROME].max)
77
92
  end
78
93
 
79
94
  # What was read from a file, overridden by what the command line gave.
95
+ #
96
+ # @param options [Hash] the options of the command
97
+ # @return [Configuration]
80
98
  def configuration(options)
81
99
  given = options.except(*RUN_ONLY).compact
82
100
  saved = options[:read] ? ConfigFile.new(options[:read]).read : {}
@@ -85,10 +103,23 @@ module Laser
85
103
  end
86
104
 
87
105
  # One line per dimension, aligned, in the units of the box, then the lid.
106
+ #
107
+ # @param config [Configuration]
108
+ # @return [String]
88
109
  def dimensions(config)
89
- rows = DIMENSIONS.map { |name| [name, "#{config[name]} #{config.units}"] } << [:lid, config.lid]
110
+ rows = (DIMENSIONS.map { |name| [name, "#{config[name]} #{config.units}"] } + slope(config)) << [:lid, config.lid]
90
111
  rows.map { |name, value| "#{"#{name.capitalize}:".ljust(11)} #{value}" }.join("\n")
91
112
  end
113
+
114
+ # The two lines a sloped box adds: the height of its front, and the angle.
115
+ #
116
+ # @param config [Configuration]
117
+ # @return [Array<Array(Symbol, String)>] none for a box without a slope
118
+ def slope(config)
119
+ return [] unless config.slope
120
+
121
+ [[:front, "#{config.front_height} #{config.units}"], [:slope, "#{config.slope}°"]]
122
+ end
92
123
  end
93
124
  end
94
125
  end
@@ -3,6 +3,7 @@
3
3
  module Laser
4
4
  module Cutter
5
5
  module CLI
6
+ # The help command: help for the program, or for one command.
6
7
  class Help < Command
7
8
  desc 'Show help, for the program or for one command'
8
9
 
@@ -11,6 +12,9 @@ module Laser
11
12
  example ['', 'generate']
12
13
 
13
14
  # Asks dry-cli for the help it prints on --help, which exits by itself.
15
+ #
16
+ # @param command [String, nil] the command to explain; nil for the program
17
+ # @return [void]
14
18
  def call(command: nil, **)
15
19
  Dry::CLI.new(CLI).call(arguments: [command, '--help'].compact, out: out, err: err)
16
20
  end
@@ -3,6 +3,7 @@
3
3
  module Laser
4
4
  module Cutter
5
5
  module CLI
6
+ # The page-sizes command: lists every page size a PDF can take.
6
7
  class PageSizes < Command
7
8
  desc 'List every page size, with its dimensions'
8
9
 
@@ -10,6 +11,8 @@ module Laser
10
11
 
11
12
  example ['', '--units mm']
12
13
 
14
+ # @param units [String] "in" or "mm"
15
+ # @return [void]
13
16
  def call(units:, **)
14
17
  out.puts PageManager.new(units).all_page_sizes
15
18
  end
@@ -3,9 +3,11 @@
3
3
  module Laser
4
4
  module Cutter
5
5
  module CLI
6
+ # The version command: prints the version of the gem.
6
7
  class Version < Command
7
8
  desc 'Print the version'
8
9
 
10
+ # @return [void]
9
11
  def call(**)
10
12
  out.puts Laser::Cutter::VERSION
11
13
  end
@@ -6,25 +6,43 @@ module Laser
6
6
  module CLI
7
7
  extend Dry::CLI::Registry
8
8
 
9
+ # The name of the executable, as help and completion print it.
9
10
  PROGRAM = 'laser-cutter'
10
11
 
11
12
  # Help and boxes are never wider than this, however wide the terminal is.
12
- HELP_WIDTH = 90
13
+ HELP_WIDTH = 100
13
14
 
14
15
  # Columns assumed when there is no terminal, or it reports none.
15
- DEFAULT_COLUMNS = 80
16
+ DEFAULT_COLUMNS = 90
16
17
 
18
+ # `COLUMNS` wins over the console, as it does for dry-cli-help, so a test can pin the width.
19
+ #
20
+ # @param columns [Integer, nil] the width of the terminal; nil or 0 for {DEFAULT_COLUMNS}
17
21
  # @return [Integer] columns help wraps at, and a box takes: the terminal's less 6,
18
22
  # capped at HELP_WIDTH
19
- def self.help_width(columns = IO.console&.winsize&.last)
23
+ def self.help_width(columns = Dry::CLI::Help::Terminal.width)
20
24
  columns = DEFAULT_COLUMNS unless columns&.positive?
21
25
  [columns - 6, HELP_WIDTH].min
22
26
  end
23
27
 
28
+ # Boxes as wide as help. dry-cli-ui assumes 80 columns on a stream that is
29
+ # not a tty, such as a pipe, so it is told the terminal's width.
30
+ #
31
+ # @param out [IO] where info and success boxes go
32
+ # @param err [IO] where error boxes go
33
+ # @return [Dry::CLI::UI::Console]
34
+ def self.console(out:, err:)
35
+ Dry::CLI::UI::Console.new(out: out, err: err, width: Dry::CLI::Help::Terminal.width, box_width: help_width)
36
+ end
37
+
24
38
  Dry::CLI::Help.configure do
39
+ pastel = Pastel.new
40
+
25
41
  title "laser-cutter #{Laser::Cutter::VERSION}"
26
42
  description 'Draws the notched panels of a box, ready to cut on a laser cutter, as a PDF or an SVG.'
27
- epilogue 'Documentation: https://github.com/kigster/laser-cutter'
43
+ epilogue "Source Code ━━━━━━━━▶ #{pastel.cyan.underline('https://github.com/kigster/laser-cutter')}\n\n" \
44
+ "API Documentation ━━▶ #{pastel.cyan.underline('https://kigster.github.io/laser-cutter/')}\n\n" \
45
+ "Make An Enclosure ━━▶ #{pastel.cyan.underline('https://makeabox.io/')}"
28
46
 
29
47
  width CLI.help_width
30
48
  exit_code_without_arguments 0
@@ -34,6 +52,7 @@ module Laser
34
52
  usage :yellow
35
53
  example :yellow
36
54
  option :green
55
+ title :bold, :yellow, :underline
37
56
  example_comment :bright_black
38
57
  end
39
58
  end
@@ -2,20 +2,38 @@
2
2
 
3
3
  module Laser
4
4
  module Cutter
5
+ # The settings of one box, as the renderers take them: a Hash with
6
+ # Symbol keys, read as methods (config.width). It expands the
7
+ # --box WxHxD/T[/N] shorthand, casts numeric Strings to Floats, and fills
8
+ # in the kerf, margin, padding and stroke for the units, and a notch of
9
+ # three times the thickness.
5
10
  class Configuration < Hashie::Mash
6
11
  include ::Hashie::Extensions::Mash::SymbolizeKeys
7
12
 
13
+ # The --box shorthand: WxHxD/T, or WxHxD/T/N with a notch.
8
14
  SIZE_REGEXP = %r{[\d.]+x[\d.]+x[\d.]+/[\d.]+(/[\d.]+)?}
9
15
 
10
- FLOATS = %i(width height depth thickness notch margin padding stroke kerf).freeze
16
+ # Distances, in the units of the box: cast to floats, and converted with the units.
17
+ FLOATS = %i(width height depth front_height thickness notch margin padding stroke kerf).freeze
18
+ # Angles, in degrees: cast to floats, and left alone when the units change.
19
+ ANGLES = %i(slope).freeze
20
+ # Settings that must not be zero.
11
21
  NON_ZERO = %i(width height depth thickness stroke).freeze
22
+ # Settings that must be given.
12
23
  REQUIRED = %i(width height depth thickness notch file).freeze
13
24
 
14
25
  @mutex = Mutex.new
15
26
 
16
27
  class << self
28
+ # @!attribute [rw] mutex
29
+ # @return [Mutex] guards the computing of {.defaults}
30
+ # @!attribute [rw] defaults
31
+ # @return [Hashie::Mash] the defaults, with the distances for :in and :mm
17
32
  attr_accessor :mutex, :defaults
18
33
 
34
+ # Computes the defaults once.
35
+ #
36
+ # @return [Hashie::Mash] a copy of the defaults
19
37
  def compute_defaults!
20
38
  mutex.synchronize do
21
39
  if defined?(@defaults)
@@ -26,6 +44,8 @@ module Laser
26
44
  end.dup
27
45
  end
28
46
 
47
+ # @return [Hashie::Mash] the defaults, with the distances for inches
48
+ # and the same converted to millimetres
29
49
  def compute_metric_units!
30
50
  defaults = Hashie::Mash.new({
31
51
  units: :in,
@@ -47,6 +67,8 @@ module Laser
47
67
 
48
68
  compute_defaults!
49
69
 
70
+ # @param options [Hash] the settings, by String or Symbol key; nil
71
+ # values, a blank lid and units it does not know are dropped
50
72
  def initialize(options = {})
51
73
  ::Hashie::Extensions::SymbolizeKeys.symbolize_keys!(options)
52
74
 
@@ -66,13 +88,19 @@ module Laser
66
88
  self[:width], self[:height], self[:depth] = dim.split('x')
67
89
  delete(:box)
68
90
  end
69
- FLOATS.each do |k|
91
+ (FLOATS + ANGLES).each do |k|
70
92
  self[k] = self[k].to_f if self[k].is_a?(String)
71
93
  end
72
94
  merge!(self.class.defaults[self[:units].to_sym].merge(self))
73
95
  self[:notch] = (self[:thickness] * 3.0).round(5) if self[:thickness] && self[:notch].nil?
74
96
  end
75
97
 
98
+ # Checks that the settings make a box.
99
+ #
100
+ # @return [void]
101
+ # @raise [MissingOption] when a required setting is missing
102
+ # @raise [ZeroValueNotAllowed] when a setting that must not be zero is
103
+ # @raise [InvalidOption] for a lid it does not know, or a slope that does not make a box
76
104
  def validate!
77
105
  missing = []
78
106
  REQUIRED.each { |k| missing << k if self[k].nil? }
@@ -82,11 +110,17 @@ module Laser
82
110
  NON_ZERO.each { |k| zeros << k if self[k] == 0 }
83
111
  raise ZeroValueNotAllowed, "#{zeros.join(', ')} #{zeros.size > 1 ? 'are' : 'is'} required, but is zero." unless zeros.empty?
84
112
 
85
- return if Box::LIDS.include?(lid.to_s.to_sym)
113
+ unless Box::LIDS.include?(lid.to_s.to_sym)
114
+ raise InvalidOption, "lid is #{lid.to_s.inspect}, but must be one of: #{Box::LIDS.join(', ')}."
115
+ end
86
116
 
87
- raise InvalidOption, "lid is #{lid.to_s.inspect}, but must be one of: #{Box::LIDS.join(', ')}."
117
+ Sloped::Request.validate!(self)
88
118
  end
89
119
 
120
+ # Converts every distance to other units, and leaves angles alone.
121
+ #
122
+ # @param new_units [String, Symbol] "in" or "mm"
123
+ # @return [Symbol, nil] the new units, or nil when nothing changed
90
124
  def change_units(new_units)
91
125
  new_units = new_units.to_sym
92
126
  return if new_units == units.to_sym
@@ -2,24 +2,31 @@
2
2
 
3
3
  module Laser
4
4
  module Cutter
5
+ # Unitless planar geometry: points, lines, rectangles and closed loops.
5
6
  module Geometry
7
+ # The width, height and depth of a box, written as "WxHxD".
6
8
  class Dimensions < Tuple
9
+ # @return [Float] the width
7
10
  def w
8
11
  coords.[](0)
9
12
  end
10
13
 
14
+ # @return [Float] the height
11
15
  def h
12
16
  coords.[](1)
13
17
  end
14
18
 
19
+ # @return [Float] the depth
15
20
  def d
16
21
  coords.[](2)
17
22
  end
18
23
 
24
+ # @return [String] the separator between the values in a String
19
25
  def separator
20
26
  'x'
21
27
  end
22
28
 
29
+ # @return [Array<Symbol>] the keys a Hash of dimensions uses
23
30
  def hash_keys
24
31
  [:w, :h, :d]
25
32
  end
@@ -3,13 +3,25 @@
3
3
  module Laser
4
4
  module Cutter
5
5
  module Geometry
6
+ # A straight line between two points. Two lines are equal whichever
7
+ # way they run.
6
8
  class Line < Shape
9
+ # @param array [Array] whatever {#initialize} accepts
10
+ # @return [Line]
7
11
  def self.[](*array)
8
12
  new(*array)
9
13
  end
10
14
 
15
+ # @!attribute [rw] p1
16
+ # @return [Point] where the line starts
17
+ # @!attribute [rw] p2
18
+ # @return [Point] where the line ends
11
19
  attr_accessor :p1, :p2
12
20
 
21
+ # @param point1 [Point, Hash] where the line starts, or a Hash with
22
+ # :from and :to, each anything {Point} accepts
23
+ # @param point2 [Point, nil] where the line ends, unless point1 is a Hash
24
+ # @raise [RuntimeError] when a point is missing
13
25
  def initialize(point1, point2 = nil)
14
26
  if point1.is_a?(Hash)
15
27
  options = point1
@@ -23,6 +35,9 @@ module Laser
23
35
  raise 'Both points are required for line definition' unless p1 && p2
24
36
  end
25
37
 
38
+ # @param another [Line]
39
+ # @return [Boolean] whether both lines lie on one horizontal or vertical
40
+ # line and share at least a point
26
41
  def overlaps?(another)
27
42
  xs, ys = sorted_coords(another)
28
43
  return false unless xs.all?{ |x| x == xs[0] } || ys.all?{ |y| y == ys[0] }
@@ -32,12 +47,19 @@ module Laser
32
47
  true
33
48
  end
34
49
 
50
+ # @param another [Line]
51
+ # @return [Array(Array, Array)] the x and then the y ranges of both lines,
52
+ # each range sorted
35
53
  def sorted_coords(another)
36
54
  xs = [[p1.x, p2.x].sort, [another.p1.x, another.p2.x].sort]
37
55
  ys = [[p1.y, p2.y].sort, [another.p1.y, another.p2.y].sort]
38
56
  [xs, ys]
39
57
  end
40
58
 
59
+ # The parts of two overlapping lines that only one of them covers.
60
+ #
61
+ # @param another [Line]
62
+ # @return [Array(Line, Line), nil] nil when the lines do not overlap
41
63
  def xor(another)
42
64
  return nil unless overlaps?(another)
43
65
 
@@ -49,6 +71,10 @@ module Laser
49
71
  Line.new(Point[xs[2], ys[2]], Point[xs[3], ys[3]])]
50
72
  end
51
73
 
74
+ # Moves the line so that it starts at its position, keeping its
75
+ # length and direction.
76
+ #
77
+ # @return [Line] self
52
78
  def relocate!
53
79
  dx = p2.x - p1.x
54
80
  dy = p2.y - p1.y
@@ -58,45 +84,61 @@ module Laser
58
84
  self
59
85
  end
60
86
 
87
+ # @return [Point] the middle of the line
61
88
  def center
62
89
  Point.new((p2.x + p1.x) / 2, (p2.y + p1.y) / 2)
63
90
  end
64
91
 
92
+ # @return [Float]
65
93
  def length
66
94
  Math.sqrt(((p2.x - p1.x)**2) + ((p2.y - p1.y)**2))
67
95
  end
68
96
 
97
+ # @return [String] the class and both points, such as "line {0,0}=>{1,0}"
69
98
  def to_s
70
99
  "#{self.class.name.gsub(/.*::/, '').downcase} #{p1}=>#{p2}"
71
100
  end
72
101
 
102
+ # @param other [Line]
103
+ # @return [Boolean] whether the lines join the same two points, either way round
73
104
  def eql?(other)
74
105
  (other.p1.eql?(p1) && other.p2.eql?(p2)) ||
75
106
  (other.p2.eql?(p1) && other.p1.eql?(p2))
76
107
  end
77
108
 
109
+ # @return [Line] the same line, running from the lesser point to the greater
78
110
  def normalized
79
111
  p1 < p2 ? Line.new(p1, p2) : Line.new(p2, p1)
80
112
  end
81
113
 
114
+ # Orders lines by their normalized points.
115
+ #
116
+ # @param other [Line]
117
+ # @return [Integer, nil]
82
118
  def <=>(other)
83
119
  n1 = normalized
84
120
  n2 = other.normalized
85
121
  n1.p1.eql?(n2.p1) ? n1.p2 <=> n2.p2 : n1.p1 <=> n2.p1
86
122
  end
87
123
 
124
+ # @param other [Line]
125
+ # @return [Boolean] whether this line comes first, by p1 and then by p2
88
126
  def <(other)
89
127
  p1 == other.p1 ? p2 < other.p2 : p1 < other.p1
90
128
  end
91
129
 
130
+ # @param other [Line]
131
+ # @return [Boolean] whether this line comes last, by p1 and then by p2
92
132
  def >(other)
93
133
  p1 == other.p1 ? p2 > other.p2 : p1 > other.p1
94
134
  end
95
135
 
136
+ # @return [Integer] the same for a line and its reverse
96
137
  def hash
97
138
  [p1.to_a, p2.to_a].sort.hash
98
139
  end
99
140
 
141
+ # @return [Line] a copy with copies of both points
100
142
  def clone
101
143
  self.class.new(p1, p2)
102
144
  end
@@ -0,0 +1,138 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Laser
4
+ module Cutter
5
+ module Geometry
6
+ # A closed outline: points in order, the last joined back to the first.
7
+ #
8
+ # A panel is drawn by walking its edges in turn, which leaves the walk
9
+ # with points it does not need: the same point twice where two edges
10
+ # meet, a spike where one edge steps out and the next steps straight
11
+ # back, and points in the middle of a straight run. A Loop drops all
12
+ # three, so what is left has one point for each corner.
13
+ #
14
+ # It cannot be changed: #grow and #map return a new Loop.
15
+ class Loop
16
+ # Lengths this close to zero, relative to the lines measured, are zero.
17
+ EPSILON = 1e-9
18
+
19
+ # @param points [Array<Point>] the walk around the outline
20
+ # @raise [ArgumentError] when fewer than three corners are left, or they enclose nothing
21
+ def initialize(points)
22
+ @corners = tidy(points.map(&:clone)).freeze
23
+ raise ArgumentError, "an outline needs three corners, got #{@corners.size}" if @corners.size < 3
24
+ raise ArgumentError, 'an outline needs an area, but its corners lie on one line' if area <= EPSILON
25
+
26
+ freeze
27
+ end
28
+
29
+ # @return [Array<Point>] a copy of the corners, in the order given
30
+ def points
31
+ @corners.map(&:clone)
32
+ end
33
+
34
+ # @return [Array<Line>] one line for each side, end to end
35
+ def lines
36
+ @corners.each_with_index.map { |point, index| Line.new(point, @corners[(index + 1) % @corners.size]) }
37
+ end
38
+
39
+ # @return [Float] the area enclosed, positive whichever way the points run
40
+ def area
41
+ signed_area.abs
42
+ end
43
+
44
+ # The outline moved outwards by a distance on every side, the corners
45
+ # kept sharp. Half the kerf makes a panel cut to size.
46
+ #
47
+ # @param distance [Numeric] outwards when positive
48
+ # @return [Loop]
49
+ def grow(distance)
50
+ return self if distance.zero?
51
+
52
+ side = signed_area.positive? ? 1 : -1
53
+ normals = lines.map { |line| outward(line, side) }
54
+ Loop.new(@corners.each_with_index.map { |point, index| mitre(point, normals[index - 1], normals[index], distance) })
55
+ end
56
+
57
+ # @yieldparam point [Point]
58
+ # @yieldreturn [Point]
59
+ # @return [Loop] the outline with every corner mapped
60
+ def map(&)
61
+ Loop.new(@corners.map(&))
62
+ end
63
+
64
+ private
65
+
66
+ # The shoelace formula.
67
+ #
68
+ # @return [Float] positive when the points run counter-clockwise
69
+ def signed_area
70
+ lines.sum { |line| (line.p1.x * line.p2.y) - (line.p2.x * line.p1.y) } / 2.0
71
+ end
72
+
73
+ # The unit normal of a line that points out of the outline.
74
+ #
75
+ # @param line [Line] a side of the outline
76
+ # @param side [Integer] 1 when the points run counter-clockwise, -1 otherwise
77
+ # @return [Vector]
78
+ def outward(line, side)
79
+ length = line.length
80
+ Vector[side * (line.p2.y - line.p1.y) / length, side * (line.p1.x - line.p2.x) / length]
81
+ end
82
+
83
+ # Where the two sides that meet at a corner cross once each has moved out.
84
+ #
85
+ # @param point [Point] the corner
86
+ # @param before [Vector] the outward normal of the side that ends at the corner
87
+ # @param after [Vector] the outward normal of the side that starts there
88
+ # @param distance [Numeric] how far each side moves
89
+ # @return [Point]
90
+ def mitre(point, before, after, distance)
91
+ point.plus((before + after) * (distance / (1 + before.inner_product(after))))
92
+ end
93
+
94
+ # Drops what a walk leaves behind until nothing more can go.
95
+ #
96
+ # @param points [Array<Point>] the walk
97
+ # @return [Array<Point>] the corners, or fewer than three when the walk
98
+ # encloses nothing
99
+ def tidy(points)
100
+ loop do
101
+ kept = points.each_with_index.reject { |_point, index| needless?(points, index) }.map(&:first)
102
+ return kept if kept.size == points.size || kept.size < 3
103
+
104
+ points = kept
105
+ end
106
+ end
107
+
108
+ # Only the first of two such points in a row goes in one pass, since
109
+ # dropping one changes the neighbours of the other.
110
+ #
111
+ # @param points [Array<Point>]
112
+ # @param index [Integer]
113
+ # @return [Boolean] whether to drop the point at index in this pass
114
+ def needless?(points, index)
115
+ removable?(points, index) && !removable?(points, index - 1)
116
+ end
117
+
118
+ # Whether a point repeats the one before it, or lies on the straight
119
+ # line through its neighbours: in the middle of a run, or at the tip
120
+ # of a spike.
121
+ #
122
+ # @param points [Array<Point>]
123
+ # @param index [Integer]
124
+ # @return [Boolean]
125
+ def removable?(points, index)
126
+ before = points[index - 1]
127
+ point = points[index]
128
+ after = points[(index + 1) % points.size]
129
+ incoming = Math.hypot(point.x - before.x, point.y - before.y)
130
+ return true if incoming <= EPSILON
131
+
132
+ cross = ((point.x - before.x) * (after.y - point.y)) - ((point.y - before.y) * (after.x - point.x))
133
+ cross.abs <= EPSILON * incoming * Math.hypot(after.x - point.x, after.y - point.y)
134
+ end
135
+ end
136
+ end
137
+ end
138
+ end
@@ -3,7 +3,10 @@
3
3
  module Laser
4
4
  module Cutter
5
5
  module Geometry
6
+ # A point in the plane, given by its x and y.
6
7
  class Point < Tuple
8
+ # @param array [Array] whatever {Tuple#initialize} accepts
9
+ # @return [Point]
7
10
  def self.[](*array)
8
11
  Point.new(*array)
9
12
  end