Ruby-PovRay Tutorial

Ruby is a programming and scripting language, with an elegant syntax, which is designed to be simple and pleasant to use.

Let's start this tutorial with a small script, that defines a function, with one parameter, which prints a message in the console:

def hello(msg)
  puts "Hello, #{msg}"
end

# call of the function
hello("Ruby!")

Running this script in the console:

$ ruby hello.rb
Hello, Ruby!

There is a first tutorial with ruby and svg, this one is with PovRay.

Now let's see how to create, and instantiate an object, in order to create a .pov scene with PovRay:

class Pov
  def initialize()
    @buffer = <<~POV
  \n
  POV
  end

  def add_background(r, g, b)
    str = "background { color rgb <#{r}, #{g}, #{b}> }\n\n"

    @buffer << str
  end

  def add_camera(location, look_at)

    lx, ly, lz = location
    ax, ay, az = look_at

    str = <<~POV
  camera {
    location <#{lx}, #{ly}, #{lz}>
    look_at  <#{ax}, #{ay}, #{az}>
  }\n
  POV
    @buffer << str
  end

  def print
    puts @buffer
  end
end

location = [1.8, 4.8, 2.4]
look_at = [0, 0.6, 0]

# Instantiation of the object, and call some methods
pov = Pov.new()
pov.add_background(0.2, 0.1, 0.4)
pov.add_camera(location, look_at)
pov.print

Running the code:

$ ruby RbPov.rb

background { color rgb <0.2, 0.1, 0.4> }

camera {
  location <1.8, 4.8, 2.4>
  look_at  <0, 0.6, 0>
}

Then you can redirect this output to a .pov file:

$ ruby RbPov.rb > my_pov.pov

If you already installed povray, you can then create the rendered result:

$ povray +W640 +H420 -V +A +Imy_pov.pov

It should create the image file: my_pov.png.

You can also probably create a Makefile file, in the same directory, to automate the creation of the .png results:

%.png: %.pov
        povray +W680 +H440 -V $(AA) +I$<

And you can do the same to create your .pov files:

%.pov: %.rb
        ruby $< > $@

(replace the 8 spaces by a tabulation)

Then the commands:

make my_pov.pov
make my_pov.png

Will appropriatly create the respective files.