Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 1ac051dd07
Fetching contributors…

Cannot retrieve contributors at this time

executable file 261 lines (217 sloc) 6.719 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
#!/usr/bin/ruby

require 'yaml'
require 'RMagick'

ROOT2 = Math.sqrt(2)

begin
  $filename = ARGV[0] or raise
rescue
  puts "convert a raw greyscale bitmap to raster g-code\nusage: ruby raster.rb <bitmap-file> <width> <height>"
  exit 1
end

raise "can't find graster.yml in the current directory or the default location" unless
  $config_filename = ['./graster.yml', File.join(File.dirname(__FILE__), 'graster.yml')].find {|pn| File.exist? pn }
  
$config = YAML.load_file($config_filename)

$threshold = $config["threshold"].to_i
$negative = $config["negative"]
$zon = $config["zon"].to_f
$zoff = $config["zoff"].to_f
$power = $config["power"].to_f
$zdelta = ($zoff-$zon).abs
$step = 1.0/$config["dpi"].to_i
$linestep = $config["linestep"].to_i
$leftmargin = $config["leftmargin"].to_f
$bottommargin = $config["bottommargin"].to_f
$feed = $config["feed"].to_f
$whitefeed = $config["whitefeed"].to_f
$greyscale = $config["greyscale"]
$mask = $config["mask"]

$tile_size = $config["tile_size"].map {|n| n && n.to_f }
$tile_count = $config["tile_count"].map {|n| n.to_i }

$laser_ctl = ["M63 P0","M62 P0"]
# $laser_ctl = ["",""]

### monochrome rastering

def draw? pix, param
  if $greyscale
    pix == param
  elsif $negative
    pix >= $threshold
  else
    pix < $threshold
  end
end

def gx n, params
  res = "G#{n}"
  params.has_key?(:l) and res << " #{$laser_ctl[params[:l]?1:0]}"
  [:x,:y,:z,:w].each {|a| params[a] and res << " #{a.to_s.upcase}%.03f" % params[a] }
  res << "\n"
  res
end

def g1 params; gx 1, params; end
def g0 params; gx 0, params; end

def draw_span x1, x2
  if $mask
    if x1 < x2
      $mask_file.puts "0 0 1 #{x1}"
      $mask_file.puts "0 1 1 #{x2}"
    else
      $mask_file.puts "0 0 0 #{x1}"
      $mask_file.puts "0 1 0 #{x2}"
    end
  end

  g1(:x => x1, :l => false) +
  g1(:x => x2, :l => true)
end

def draw_spans spans, y, margin
  if spans.empty?
    ""
  else
    g0(:y => y, :x => spans.first[0]-margin) +
    spans.map{|span| draw_span(span[0], span[1]) }.join +
    g1(:x => spans.last[1]+margin, :l => false)
  end
end

class Array
  def find_index_after i, &b
    a = slice(i..-1)
    if x = a.find(&b)
      x = a.index(x)
      i + x
    else
      nil
    end
  end
end

def draw_pix xorig, yorig, pix, param, step, margin
  spans = []
  b = 0

  while b < pix.size && a = pix.find_index_after(b) {|p| draw? p, param }
    b = pix.find_index_after(a+1) {|p| !draw? p, param } || pix.size
    spans << [xorig+a*step, xorig+b*step]
  end

   #"(" + spans.map{|s| "#{s[0]}-#{s[1]}"}.join(" ") + ")\n" +
  draw_spans(spans, yorig, margin)
end

def make_spans xorig, pix, param, step
  spans = []
  b = 0

  while b < pix.size && a = pix.find_index_after(b) {|p| draw? p, param }
    b = pix.find_index_after(a+1) {|p| !draw? p, param } || pix.size
    spans << [xorig+a*step, xorig+b*step]
  end

  return spans
end

def tile_spans spans, interval, count, forward
  a = []
  count.times do |tile|
    offset = if forward
               tile*interval
             else
               (count-1-tile)*interval
             end

    spans.each do |span|
      a << span.map{|x| x + offset}
    end
  end
  return a
end

def render_mask raw, param, gcode, gmask
  gcode.puts "(#{$filename} #{$width} x #{$height})\n(#{$config.inspect})"
  gcode.puts "M63 P0\nG61\nF#{$feed}"
  gcode.puts 'G0 X%0.3f Y%0.3f' % [$leftmargin/2, $bottommargin + $height*$step]
  gcode.puts "M3 S#{$power}"
  gmask.puts "1 0 0 0"
  forward = true

  $tile_count[1].times do |tile|
    $height.times do |y|
      row = raw[y*$width...(y+1)*$width]
      yorig = $bottommargin + tile*$tile_size[1] + ($height-y)*$step

      if y % $linestep == 0
        if forward
          spans = tile_spans(make_spans($leftmargin,row,param,$step),
                             $tile_size[0],
                             $tile_count[0],
                             forward)
          factor = 1
          xop = 1
        else
          spans = tile_spans(make_spans($leftmargin + $width*$step,row.reverse,param,-$step),
                             $tile_size[0],
                             $tile_count[0],
                             forward)
          factor = -1
          xop = 0
        end

        unless spans.empty?
          gcode.puts 'G0 X%0.3f Y%0.3f' % [spans[0][0]-factor*$leftmargin/2, yorig]
          gcode.puts 'G1 X%0.3f' % [spans[-1][1]+factor*$leftmargin/2]

          # wait until we are before the first span, then start the row
          gmask.puts '0 0 %i %0.3f' % [1-xop,spans[0][0]-$step/2]

          spans.each do |s|
            gmask.puts '0 0 %i %0.3f' % [xop,s[0]-$step/2]
            gmask.puts '0 1 %i %0.3f' % [xop,s[1]-$step/2]
          end

          forward = !forward
        end

      end # if y % linestep == 0
    end # $height.times
  end # $tile_count[1].times

  gcode.write "M5\nM2\n"
end

def render raw, param
  res = "(#{$filename} #{$width} x #{$height})\n(#{$config.inspect})\nM63 P0\nG64\nF#{$feed}\nM3 S#{$power}\n"
  forward = true

  $tile_count[1].times do |tile|
    $height.times do |y|
      row = raw[y*$width...(y+1)*$width]

      if y % $linestep == 0
        if forward
          rowg = draw_pix($leftmargin,
                          $bottommargin + tile*$tile_size[1] + ($height-y)*$step,
                          row,
                          param,
                          $step,
                          $leftmargin/2.0)
        else
          rowg = draw_pix($leftmargin + $width*$step,
                          $bottommargin + tile*$tile_size[1] + ($height-y)*$step,
                          row.reverse,
                          param,
                          -$step,
                          -$leftmargin/2.0)
        end

        #puts "(#{y} #{row[0..20].join ' '})"

        unless rowg.empty?
          res << rowg
          forward = !forward
        end
      end # if y % $linestep == 0
    end # $height.times
  end # $tile_count[1].times

  res + "M5\nM2\n"
end


### main loop

def read_image filename
  image = Magick::Image.read(filename)
  image = image[0] or raise "unknown image format"
  $width = image.columns # "columns"? WTF??
  $height = image.rows
  $tile_size[0] ||= $width*$step
  $tile_size[1] ||= $height*$step
  $raw = image.export_pixels(0,0,$width,$height,"I").map{|x| x/256 }
end

read_image $filename

if $greyscale
  $raw.uniq.each do |plane|
    File.open("#{$filename}.#{'%02x'%plane}.ngc","w") do |io|
      io.write render($raw,plane)
    end
  end
elsif $mask
  File.open("#{$filename}.gmask", "w") do |mask_file|
    File.open("#{$filename}.ngc", "w") do |gcode_file|
      render_mask $raw, $threshold, gcode_file, mask_file
    end
  end
else
  print render($raw,$threshold)
end
Something went wrong with that request. Please try again.