Experiments with ruby-processing (processing-2.2.1) and JRubyArt for processing-3.0

Wednesday 25 March 2015

Implicit isosurface sketch re-worked for JRubyArt

Since the release of the toxiclibs gem (example below use gem version 0.3.0.pre), it is now quite easy to work with the toxiclibs libraries in JRubyArt see sketch below. This being a bare sketch should be run with 'k9 run implicit.rb'

#
# This example implements a custom VolumetricSpace uMath.sing an implicit function
# to calculate each voxel. This is slower than the default array or HashMap
# based implementations, but also has much less memory requirements and so might
# be an interesting and more viable approach for very highres voxel spaces
# (e.g. >32 million voxels). This implementation here also demonstrates how to
# achieve an upper boundary on the iso value (in addition to the one given and
# acting as lower threshold when computing the iso surface)
#
# Usage:
# drag mouse to rotate camera
# mouse wheel zoom in/out
# l: apply laplacian mesh smooth
# 
#

# 
# Copyright (c) 2010 Karsten Schmidt & ruby-procesMath.sing version Martin Prout 2013
# This sketch relies on a custom ruby-procesMath.sing mesh_to_vbo library
# 
# This library is free software you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation either
# version 2.1 of the License, or (at your option) any later version.
# 
# http://creativecommons.org/licenses/LGPL/2.1/
# 
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
# 
# You should have received a copy of the GNU Lesser General Public
# License along with this library if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

require 'toxiclibs'

load_library :mesh_to_vbo

RES = 64
ISO = 0.2
MAX_ISO = 0.66

attr_reader :mesh, :vbo, :curr_zoom, :implicit

def setup
  size(720,720, P3D)
  Processing::ArcBall.init(self)
  @vbo = MeshToVBO.new(self)
  @curr_zoom = 1
  vol = EvaluatingVolume.new(TVec3D.new(400,400,400), RES, RES, RES, MAX_ISO)
  surface = Volume::HashIsoSurface.new(vol)
  @mesh = Toxi::WETriangleMesh.new
  surface.compute_surface_mesh(mesh, ISO)
  @is_wire_frame = false
  no_stroke
  @implicit = vbo.meshToVBO(mesh, true)
  implicit.setFill(color(222, 222, 222))
  implicit.setAmbient(color(50, 50, 50))
  implicit.setShininess(color(10, 10, 10))
  implicit.setSpecular(color(50, 50, 50))
end

def draw
  background(0)
  lights
  define_lights
  shape(implicit)
end

def key_pressed
  case key
  when 'l', 'L'
    Toxi::LaplacianSmooth.new.filter(mesh, 1)
    @implicit = vbo.meshToVBO(mesh, true)
    # new mesh so need to set finish
    implicit.setFill(color(222, 222, 222))
    implicit.setAmbient(color(50, 50, 50))
    implicit.setShininess(color(10, 10, 10))
    implicit.setSpecular(color(50, 50, 50))
  when 's', 'S'
    save_frame("implicit.png")
  end
end

def define_lights
  ambient_light(50, 50, 50)
  point_light(30, 30, 30, 200, -150, 0)
  directional_light(0, 30, 50, 1, 0, 0)
  spot_light(30, 30, 30, 0, 40, 200, 0, -0.5, -0.5, PI / 2, 2)
end

class EvaluatingVolume < Volume::VolumetricSpace

  attr_reader :upper_bound, :lut
  FREQ = Math::PI * 3.8

  def initialize(scal_vec, resX, resY, resZ, upper_limit)
    super(scal_vec, resX, resY, resZ)
    @upper_bound = upper_limit
  end

  def clear
    # nothing to do here
  end

  def getVoxelAt(i)
    getVoxel(i % resX, (i % sliceRes) / resX, i / sliceRes)
  end

  def getVoxel(x, y, z)  # can't overload so we renamed
    val = 0
    if (x > 0 && x < resX1 && y > 0 && y < resY1 && z > 0 && z < resZ1)
      xx = x * 1.0 / resX - 0.5  # NB: careful about integer division !!!
      yy = y * 1.0 / resY - 0.5
      zz = z * 1.0 / resZ - 0.5
      #val = Math.sin(xx * FREQ) + Math.cos(yy * FREQ) + Math.sin(zz * FREQ)
      val = Math.cos(xx * FREQ) * Math.sin(yy* FREQ) + Math.cos(yy* FREQ) * Math.sin(zz* FREQ) + Math.cos(zz* FREQ)* Math.sin(xx* FREQ)
      if (val > upper_bound)
        val = 0
      end
    end
    return val
  end
end


The library code:-
############################################
# mesh_to_vbo.rb
# a ruby library to convert toxi.mesh object
# to vbo (PShape) written by Martin Prout
############################################
class MeshToVBO
  PShape = Java::ProcessingCore::PShape
  attr_reader :parent

  def initialize(parent)
    @parent = parent
  end

  def meshToVBO(mesh, smth)
    retained = parent.create_shape
    retained.begin_shape(PShape::TRIANGLES)
    if smth
      mesh.compute_vertex_normals
      mesh.getFaces.each do |f|
        retained.normal(f.a.normal.x, f.a.normal.y, f.a.normal.z)
        retained.vertex(f.a.x, f.a.y, f.a.z)
        retained.normal(f.b.normal.x, f.b.normal.y, f.b.normal.z)
        retained.vertex(f.b.x, f.b.y, f.b.z)
        retained.normal(f.c.normal.x, f.c.normal.y, f.c.normal.z)
        retained.vertex(f.c.x, f.c.y, f.c.z)
      end
    else
      mesh.get_faces.each do |f|
        retained.normal(f.normal.x, f.normal.y, f.normal.z)
        retained.vertex(f.a.x, f.a.y, f.a.z)
        retained.vertex(f.b.x, f.b.y, f.b.z)
        retained.vertex(f.c.x, f.c.y, f.c.z)
      end
    end
    retained.end_shape
    retained
  end

  # variant
  # input array of meshes, output an array of shapes
  def meshToRetained(mesh, smth)
    mesh.map { |m| meshToVBO(m, smth) }
  end
end

Tuesday 24 March 2015

Toxiclibs gem released

I've just released a toxiclibs gem that can be used with JRubyArt or ruby-processing (examples uses gem version 0.3.0.pre))
# A ruby processing sketch (needs re-factoring for jruby_art)
#
#
# This example implements a custom VolumetricSpace using an implicit function
# to calculate each voxel. This is slower than the default array or HashMap
# based implementations, but also has much less memory requirements and so might
# be an interesting and more viable approach for very highres voxel spaces
# (e.g. >32 million voxels). This implementation here also demonstrates how to
# achieve an upper boundary on the iso value (in addition to the one given and
# acting as lower threshold when computing the iso surface)
#
# Usage:
# drag mouse to rotate camera
# w: toggle wireframe on/off
# mouse wheel to zoom in/out
# l: apply laplacian mesh smooth
#
#

#
# Copyright (c) 2010 Karsten Schmidt & ruby-processing version Martin Prout 2012
# This sketch relies on a custom toxiclibscore library for PovRAY export
#
# This library is free software you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation either
# version 2.1 of the License, or (at your option) any later version.
#
# http://creativecommons.org/licenses/LGPL/2.1/
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

require 'toxiclibs'
load_library 'vecmath' # uncomment this line for ruby-processing
RES = 64
ISO = 0.2
MAX_ISO = 0.66
attr_reader :mesh, :gfx, :curr_zoom, :is_wire_frame

def setup
  size(720, 720, P3D)
  ArcBall.init(self)
  @gfx = Gfx::ToxiclibsSupport.new(self)
  vol = EvaluatingVolume.new(Toxi::Vec3D.new(400, 400, 400), RES, RES, RES, MAX_ISO)
  surface = Volume::HashIsoSurface.new(vol)
  @mesh = Toxi::WETriangleMesh.new
  surface.compute_surface_mesh(mesh, ISO)
  @is_wire_frame = false
end

def draw
  background(0)
  if is_wire_frame
    no_fill
    stroke(255)
  else
    fill(255)
    no_stroke
    define_lights
    lights
  end
  @gfx.mesh(mesh, true)
end

def key_pressed
  case key
  when 'w', 'W'
    @is_wire_frame = !is_wire_frame
  when 'l', 'L'
    Toxi::LaplacianSmooth.new.filter(mesh, 1)
  when 's', 'S'
    save_frame('implicit.png')
  end
end

def define_lights
  ambient_light(50, 50, 50)
  point_light(30, 30, 30, 200, -150, 0)
  directional_light(0, 30, 50, 1, 0, 0)
  spot_light(30, 30, 30, 0, 40, 200, 0, -0.5, -0.5, PI / 2, 2)
end

# Creating a volumetric space class
#
class EvaluatingVolume < Volume::VolumetricSpace
  include Processing::Proxy
  attr_reader :upper_bound
  FREQ = PI * 3.8

  def initialize(scal_vec, resX, resY, resZ, upper_limit)
    super(scal_vec, resX, resY, resZ)
    @upper_bound = upper_limit
  end

  def clear
    # nothing to do here
  end

  def getVoxelAt(i)
    getVoxel(i % resX, (i % sliceRes) / resX, i / sliceRes)
  end

  def getVoxel(x, y, z)  # can't overload so we renamed
    val = 0
    if x > 0 && x < resX1 && y > 0 && y < resY1 && z > 0 && z < resZ1
      xx = x * 1.0 / resX - 0.5  # NB: careful about integer division !!!
      yy = y * 1.0 / resY - 0.5
      zz = z * 1.0 / resZ - 0.5
      val = cos(xx * FREQ) * sin(yy * FREQ) + cos(yy * FREQ) * sin(zz* FREQ) + cos(zz * FREQ) * sin(xx * FREQ)
      # val = sin(xx * FREQ) + cos(yy * FREQ) + sin(zz * FREQ)
      # val = sin(xx * FREQ) * (xx * FREQ) + sin(yy * FREQ) * (yy * FREQ) + sin(zz * FREQ) * (zz * FREQ)
      val = 0 if val > upper_bound
    end
    val
  end
end

Monday 9 March 2015

Watch a Handy Sketch in ruby-processing

There is this other attempt at doing ruby-processing called processing.rb (by someone who appears to be allergic to objects) here is their signature sketch in ruby-processing, what is is wrong with 'rp5 watch'? Improvements made to their example (yes I know I cheated with boundary check):-
  • avoid unecessary use of instance eval (it is all over processing.rb examples)
  • use rand(range) this is ruby after all
  • use __persistent__ to warn ruby compiler of a singleton (advisable for jruby 9000)
  • use map to create an array
  • use Struct to create a simple Boundary class
load_library :handy
java_import org.gicentre.handy.HandyRenderer

BALL_NUM = 6
BALL_COLORS = [[255, 0, 0], [255, 255, 0], [64, 64, 255]]
attr_reader :balls, :handy

def setup
  size(400, 400)
  HandyRenderer.__persistent__ = true
  @handy = HandyRenderer.new(self)
  @balls = (0...BALL_NUM).map { |i| Ball.new(i, handy) }
end

def draw
  background(color(234, 215, 182))
  fill(color(0, 255, 0))
  handy.rect(20, 20, 360, 20)
  handy.rect(20, 360, 360, 20)
  handy.rect(20, 40, 20, 320)
  handy.rect(360, 40, 20, 320)
  balls.each(&:draw)
end

# Bouncing ball
class Ball
  include Processing::Proxy
  attr_reader :x, :y, :radius, :size, :renderer, :boundary
  def initialize(id, renderer)
    @renderer = renderer
    @x, @y = rand(100..300), rand(100..300)
    @vx, @vy = rand(-6..6), rand(-6..6)
    @size = rand(60..100)
    @radius = size / 2.0
    @color = color(*BALL_COLORS[id % BALL_COLORS.size])
    @boundary = Boundary.new(40 + radius, 360 - radius)
  end

  def draw
    @x += @vx
    @y += @vy
    @vy += 0.1
    @vx = -@vx unless boundary.include? x
    @vy *= -0.99 unless boundary.include? y
    fill(@color)
    renderer.ellipse(x, y, size, size)
  end
end

Boundary = Struct.new(:lower, :upper) do
  def include?(x)
    (lower...upper).cover? x
  end
end

Friday 6 March 2015

Bezier patch sketch in JRubyArt

Occasionally I see people trawling over really old sketches in this blog, and I wonder what are they thinking? when program versions (ie newer ruby-processing versions) change or there are new opportunities such as JRubyArt, why not look at the "hot" stuff. Anyway I revised this sketch for JRubyArt (no need to import :vecmath it is built in)....
Sketch also makes use of AppRender to make for direct conversion from Vec3D to vertex/normal.
# bezier patch By Marius Watz:
# http://www.openprocessing.org/sketch/57709
# Normal calculation added by Andres Colubri
# Direct port of sample code by Paul Bourke.
# Original code: http://paulbourke.net/geometry/bezier/
#
# hit "spacebar" to generate a new shape and save current
#

NI = 4
NJ = 5
RESI = NI * 10
RESJ = NJ * 10

attr_accessor :outp, :inp, :normp, :auto_normals, :renderer

def setup
  sketch_title 'Bezier Patch'
  ArcBall.init(self)
  @auto_normals = false
  @renderer = AppRender.new(self)
  build
end

def draw
  background(255)
  smooth(8)
  lights
  no_stroke
  fill(192, 192, 192)
  define_lights
  lights
  (0...RESI - 1).each do |i|
    begin_shape(QUAD_STRIP)
    (0...RESJ).each do |j|
      normp[i][j].to_normal(renderer) unless auto_normals
      outp[i][j].to_vertex(renderer)
      outp[i + 1][j].to_vertex(renderer)
    end
    end_shape
  end
end

def settings
  size(1024, 768, P3D)
end

def define_lights
  ambient_light(60, 60, 60)
  point_light(30, 30, 30, 0, 0, 0)
  directional_light(40, 40, 50, 1, 0, 0)
  spot_light(30, 30, 30, 0, 40, 200, 0, -0.5, 0.5, PI / 2, 2)
end


def key_pressed
  return unless key == ' '
  save_frame('bez_patch.png')
  build
end

def build
  @outp = []
  @normp = []
  @inp = []
  uitang = Vec3D.new
  ujtang = Vec3D.new
  (0...NI).each do |i|
    row = []
    (0...NJ).each do |j|
      row << Vec3D.new(i, j, (rand * 6) - 3)
    end
    inp << row
  end
  (0...RESI).each do |i|
    mui = i.fdiv(RESI - 1)
    row = []
    row_n = []
    (0...RESJ).each do |j|
      muj = j.fdiv(RESJ - 1)
      vect = Vec3D.new
      uitang = Vec3D.new
      ujtang = Vec3D.new
      (0...NI).each do |ki|
        bi = bezier_blend(ki, mui, NI)
        dbi = d_bezier_blend(ki, mui, NI)
        (0...NJ).each do |kj|
          bj = bezier_blend(kj, muj, NJ)
          dbj = d_bezier_blend(kj, muj, NJ)
          vect.x += (inp[ki][kj].x * bi * bj)
          vect.y += (inp[ki][kj].y * bi * bj)
          vect.z += (inp[ki][kj].z * bi * bj)
          uitang.x += (inp[ki][kj].x * dbi * bj)
          uitang.y += (inp[ki][kj].y * dbi * bj)
          uitang.z += (inp[ki][kj].z * dbi * bj)
          ujtang.x += (inp[ki][kj].x * bi * dbj)
          ujtang.y += (inp[ki][kj].y * bi * dbj)
          ujtang.z += (inp[ki][kj].z * bi * dbj)
        end
      end
      vect += Vec3D.new(-NI / 2, -NJ / 2, 0)
      vect *= 100
      row << vect
      uitang.normalize!
      row_n << uitang.cross(ujtang.normalize)
    end
    @outp << row
    @normp << row_n
  end
end

def bezier_blend(k, mu,  n)
  blend = 1.0
  nn = n
  kn = k
  nkn = n - k
  while (nn >= 1)
    blend *= nn
    nn -= 1
    if kn > 1
      blend = blend.fdiv(kn)
      kn -= 1
    end
    if nkn > 1
      blend = blend.fdiv(nkn)
      nkn -= 1
    end
  end
  blend *= mu**k.to_f if k > 0
  return blend * (1 - mu)**(n - k).to_f if n - k > 0
  blend
end

def d_bezier_blend(k, mu,  n)
  dblendf = 1.0
  nn = n
  kn = k
  nkn = n - k
  while (nn >= 1)
    dblendf *= nn
    nn -= 1
    if kn > 1
      dblendf = dblendf.fdiv(kn)
      kn -= 1
    end
    if nkn > 1
      dblendf = dblendf.fdiv(nkn)
      nkn -= 1
    end
  end
  fk = 1
  dk = 0
  fnk = 1
  dnk = 0
  if k > 0
    fk = mu**k.to_f
    dk = k * mu**(k - 1).to_f
  end
  if n - k > 0
    fnk = (1 - mu)**(n - k).to_f
    dnk = (k - n) * (1 - mu)**(n - k - 1).to_f
  end
  dblendf * (dk * fnk + fk * dnk)
end

Followers

About Me

My photo
I have developed JRubyArt and propane new versions of ruby-processing for JRuby-9.1.5.0 and processing-3.2.2