# ruby-processing sketch # http://qiita.com/norioc/items/99514cb659aad03ab7d7 # http://aidiary.hatenablog.com/entry/20050402/1251514618 N = 15 attr_reader :rows, :cols def setup sketch_title 'Bresenham`s Algorithm' @rows = height / N @cols = width / N end def settings size 400, 400 end def build_line(from:, to:) next_x = from.x next_y = from.y delta_x = to.x - from.x delta_y = to.y - from.y step_x = delta_x < 0 ? -1 : 1 step_y = delta_y < 0 ? -1 : 1 delta_x = (delta_x * 2).abs delta_y = (delta_y * 2).abs b_line = Array.new(1, Vec2D.new(next_x, next_y)) if delta_x > delta_y fraction = delta_y - delta_x / 2 while next_x != to.x if fraction >= 0 next_y += step_y fraction -= delta_x end next_x += step_x fraction += delta_y b_line << Vec2D.new(next_x, next_y) end else fraction = delta_x - delta_y / 2 while next_y != to.y if fraction >= 0 next_x += step_x fraction -= delta_y end next_y += step_y fraction += delta_x b_line << Vec2D.new(next_x, next_y) end end b_line end def draw background 255 translate width / 2, height / 2 rect_mode CENTER no_fill stroke 60 (0..rows).each do |i| (0..cols).each do |j| rect((j - cols / 2) * N, (i - rows / 2) * N, N, N) end end x = mouse_x - width / 2 + N / 2 y = mouse_y - height / 2 + N / 2 b_line = build_line(from: Vec2D.new, to: Vec2D.new(x / N, y / N)) unless b_line.empty? fill color('#C7B097') b_line.each { |v| rect(v.x * N, v.y * N, N, N) } end stroke color('#0000FF') stroke_width 2 line 0, 0, mouse_x - width / 2, mouse_y - height / 2 stroke 0 stroke_width 1 end
Experiments with ruby-processing (processing-2.2.1) and JRubyArt for processing-3.0
Showing posts with label jruby. Show all posts
Showing posts with label jruby. Show all posts
Tuesday, 15 September 2015
Bresenham's Algorithm in JRubyArt
After ruby-processing version, published by norioc on qiita
Labels:
Bresenhams algorithm,
jruby,
JRubyArt
Monday, 17 August 2015
Java-8-lambda and jruby extensions
Should we be getting excited about java-8-lambda for jruby extensions (working in NetBeans I got this suggestion when updating source from java-7 to java-8 having listened to Charlies talk at JVMLS2015
perhaps we should?
// Java seven public static void createVec2(final Ruby runtime) { RubyClass vec2Cls = runtime.defineClass("Vec2D", runtime.getObject(), new ObjectAllocator() { @Override public IRubyObject allocate(Ruby runtime, RubyClass rubyClass) { return new Vec2(runtime, rubyClass); } }); vec2Cls.defineAnnotatedMethods(Vec2.class); } // Java eight public static void createVec2(final Ruby runtime) { RubyClass vec2Cls = runtime.defineClass("Vec2D", runtime.getObject(), (Ruby runtime1, RubyClass rubyClass) -> new Vec2(runtime1, rubyClass)); vec2Cls.defineAnnotatedMethods(Vec2.class); }Update 22 August 2015 just released JRubyArt 0.5.0 featuring java8lambda in production...
Labels:
java-8-lambdas,
jruby,
JRubyArt
Thursday, 2 July 2015
Experimenting with standalone app using jruby
On the jruby wiki there is an explanation of how to create standalone JRuby apps, it appears to be v. old referring to since JRuby-1.6 but I have found it still works with JRuby-9.0.0.0-SNAPSHOT (as of 2 July 2015) see steps I took:-
output was as expected 'hello'. Perhaps I could harness this for JRubyArt app export?
Here is what my myapp.jar MANIFEST.MF looks like:-
Apparently you can also embed additional .rb files into the jar, and the root of the jar file will be used as an implicit LOAD_PATH entry. Warbler is another option to consider.
cp jruby/lib/jruby.jar myapp.jar # adjust path to jruby.jar echo "puts 'hello'" >> jar-bootstrap.rb jar ufe myapp.jar org.jruby.JarBootstrapMain jar-bootstrap.rb java -jar myapp.jar
output was as expected 'hello'. Perhaps I could harness this for JRubyArt app export?
Here is what my myapp.jar MANIFEST.MF looks like:-
Manifest-Version: 1.0 Archiver-Version: Plexus Archiver Built-By: tux Created-By: Apache Maven 3.3.3 Build-Jdk: 1.8.0_45 Main-Class: org.jruby.JarBootstrapMain
Apparently you can also embed additional .rb files into the jar, and the root of the jar file will be used as an implicit LOAD_PATH entry. Warbler is another option to consider.
Labels:
executable,
jar,
jruby,
ruby
Wednesday, 17 June 2015
This Hemesh Sketch Forced me to use JRuby Edges
New improved, updated and dried since 22 September 2015
load_library :hemesh # Module used to include java packages module MS include_package 'wblut.math' include_package 'wblut.processing' include_package 'wblut.hemesh' include_package 'wblut.geom' end NUM = 50 attr_reader :mesh, :render, :points def setup sketch_title 'Sponge' ArcBall.init(self) create_mesh @render = MS::WB_Render3D.new(self) end def draw background(255) directional_light(255, 255, 255, 1, 1, -1) directional_light(127, 127, 127, -1, -1, 1) stroke(0) render.draw_edges(mesh) no_stroke render.draw_faces(mesh) end def mouse_pressed create_mesh end def create_mesh rs = MS::WB_RandomOnSphere.new creator = MS::HEC_ConvexHull.new @points = (0..NUM).map { rs.next_point.mul_self(300.0) } creator.set_points(points) creator.setN(NUM) @mesh = MS::HE_Mesh.new(creator) @mesh = MS::HE_Mesh.new(MS::HEC_Dual.new(mesh)) ext = MS::HEM_Extrude.new.set_chamfer(25).set_relative(false) mesh.modify(ext) sel = ext.extruded ext = MS::HEM_Extrude.new.set_distance(-40) mesh.modify_selected(ext, sel) mesh.smooth(2) end def settings size(800, 800, P3D) smooth(8) end
Labels:
hemesh,
jruby,
JRubyArt,
processing-3.0
Sunday, 11 January 2015
A simplified ASCII video capture sketch in ruby processing
In ruby it is often easier to see wood from trees, and code is somewhat self documenting:-
Character placement might be somewhat more regimented in this version, but it saves a heap of push pop matrix calls.
Character placement might be somewhat more regimented in this version, but it saves a heap of push pop matrix calls.
# # Simplified ASCII Video capture sketch in ruby-processing # by Martin Prout after a Ben Fry original # # # Text chars have been used to represent images since the earliest computers. # This sketch is a simple homage that re-interprets live video as ASCII text. # See the key_pressed function for more options, like changing the font size. # load_library :video include_package 'processing.video' attr_reader :bright, :char, :cheat_screen, :font, :font_size, :letters, :video # All ASCII characters, sorted according to their visual density LETTER_STRING = %q{ .`-_':,;^=+/\"|)\\<>)iv%xclrs{*}I?!][1taeo7zjLunT#JCwfy325Fp6mqSghVd4EgXPGZbYkOA&8U$@KHDBWNMR0Q} LETTER_ORDER = LETTER_STRING.scan(/./) def setup size(640, 480) init_video @font_size = 1.5 @font = load_font(data_path('UniversLTStd-Light-48.vlw')) # for the 256 levels of brightness, distribute the letters across # the an array of 256 elements to use for the lookup @letters = (0...256).map do |i| LETTER_ORDER[map1d(i, (0...256), (0...LETTER_ORDER.length))] end # current brightness for each point @bright = Array.new(video.width * video.height, 128) end def init_video # This the default video input, see the test_capture # example if it creates an error @video = Capture.new(self, 160, 120) # Start capturing the images from the camera video.start @cheat_screen = false end def capture # captureEvent does not work like vanilla processing @video.read background 0 end def draw return unless (video.available == true) capture hgap = width / video.width vgap = height / video.height scale([hgap, vgap].max * font_size) text_font(font, font_size) index = 0 video.load_pixels (0...video.height).each do |y| # Move down for next line (0...video.width).each do |x| pixel_color = video.pixels[index] # Faster method of calculating r, g, b than red(), green(), blue() r = pixel_color >> 16 & 0xff g = pixel_color >> 8 & 0xff b = pixel_color & 0xff # Calculate brightness as luminance: # luminance = 0.3*red + 0.59*green + 0.11*blue # Or you could instead red + green + blue, and make the the values[] array # 256*3 elements long instead of just 256. pixel_bright = [0.3 * r, 0.59 * g, 0.11 * b].max # The 0.1 value is used to damp the changes so that letters flicker less diff = pixel_bright - bright[index] bright[index] += diff * 0.1 fill(pixel_color) text(letters[bright[index]], x / font_size, y / font_size) # Move to the next pixel index += 1 end end set(0, height - video.height, video) if cheat_screen end MESSAGE = <<-EOS Controls are: g to save_frame, f & F to set font size c to toggle cheat screen display EOS def key_pressed case key when 'g' then save_frame when 'c' then @cheat_screen = !cheat_screen when 'f' then @font_size *= 1.1 when 'F' then @font_size *= 0.9 else warn MESSAGE end end
Labels:
ascii,
Ben Fry,
jruby,
ruby-processing,
video capture
Wednesday, 29 October 2014
Toxiclibs (or any other processing library) as a rubygem
As a proof of principle I have created gem that wraps some of Karsten Schmidts (aka toxi @toxi, aka postspectacular k@thi.ng) toxiclibs as a ruby-gem. This gem has been shown to usable with ruby-processing (or its development version JRubyArt) but if yokolet is right it can also be used with clojure, and other jvm languages (by using JRuby Embed, formerly RedBridge). Here is more on RedBridge and clojure.
Here is another example running a JRubyArt sketch from netbeans.
require 'toxiclibs' include Toxi # # <p>GrayScottToneMap shows how to use the ColorGradient & ToneMap classes of the # colorutils package to create a tone map for rendering the results of # the Gray-Scott reaction-diffusion.</p> # # <p><strong>Usage:</strong><ul> # <li>click + drag mouse to draw dots used as simulation seed</li> # <li>press any key to reset</li> # </ul></p> # # # Copyright (c) 2010 Karsten Schmidt # # This demo & 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 # NUM_ITERATIONS = 10 attr_reader :gs, :tone_map def setup size(256,256) @gs= Toxi::GrayScott.new width,height, false @gs.set_coefficients 0.021, 0.076, 0.12, 0.06 # create a color gradient for 256 values grad = Toxi::ColorGradient.new # NamedColors are preset colors, but any TColor can be added # see javadocs for list of names: # http://toxiclibs.org/docs/colorutils/toxi/color/NamedColor.html # NB: use '::' in place of '.' here for these java constants grad.add_color_at(0, Toxi::NamedColor::BLACK) grad.add_color_at(128, Toxi::NamedColor::RED) grad.add_color_at(192, Toxi::NamedColor::YELLOW) grad.add_color_at(255, Toxi::NamedColor::WHITE) # this gradient is used to map simulation values to colors # the first 2 parameters define the min/max values of the # input range (Gray-Scott produces values in the interval of 0.0 - 0.5) # setting the max = 0.33 increases the contrast @tone_map = Toxi::ToneMap.new 0, 0.33, grad end def draw @gs.set_rect(mouse_x, mouse_y, 20, 20) if mouse_pressed? load_pixels # update the simulation a few time steps NUM_ITERATIONS.times { @gs.update(1) } # read out the V result array # and use tone map to render colours gs.v.length.times do |i| pixels[i]=tone_map.getARGBToneFor(gs.v[i]) # NB: don't camel case convert here end update_pixels end def key_pressed @gs.reset end
Here is another example running a JRubyArt sketch from netbeans.
Labels:
gems,
jruby,
jruby-art,
red-bridge,
ruby-processing,
toxiclibs
Wednesday, 9 July 2014
Exploring PApplet with jruby
There is a lot of clever stuff that goes on in jruby, that allows you to treat java objects as if they were ruby. Recently I had been interested in refactoring the ruby-processings library loader, but that may be premature since changes seem to be afoot with the jruby class loader?
Anyway what is the current situation?
You can simply 'require a jar' to add the jar contents to your CLASSPATH, you can then start using the java classes as if they were ruby objects see PApplet example below:-
Output:-
Alternatively you can make use of the global CLASSPATH directly:-
There is yet another way to do it using classloader directly:-
In ruby-processing exported sketches, the jars are currently added to the java CLASSPATH (ie on the java side) this may not be necessary anymore (no Applets), the current export process can mess with nested libraries (on the plus side you only need specify a directory to include the contained jars).
Anyway what is the current situation?
You can simply 'require a jar' to add the jar contents to your CLASSPATH, you can then start using the java classes as if they were ruby objects see PApplet example below:-
require 'java' require '/home/tux/processing-2.2.1/core/library/core.jar' app = Java::ProcessingCore::PApplet.new puts "inspect: #{app.inspect}" app.set_size(200, 200) puts "\nto_s: #{app.to_s}" # print the default renderer puts "\nrenderer: #{app.sketch_renderer}" # prints a list of methods including '_size' puts "\nmethods:\n #{ app.methods.reject{ |method| /_size/ !~ method.to_s} }"
Output:-
inspect: #<Java::ProcessingCore::PApplet:0x4656c38e> to_s: processing.core.PApplet[panel0,0,0,200x200,invalid,layout=java.awt.FlowLayout] renderer: processing.core.PGraphicsJava2D methods: [:text_size, :unregister_size, :register_size, :preferred_size_set?, :preferred_size=, :maximum_size=, :set_size, :is_minimum_size_set, :preferred_size, :set_preferred_size, :is_minimum_size_set?, :is_maximum_size_set?, :preferred_size_set, :set_maximum_size, :get_size, :minimum_size_set, :maximum_size_set?, :minimum_size=, :get_maximum_size, :get_minimum_size, :is_preferred_size_set?, :maximum_size, :minimum_size_set?, :maximum_size_set, :set_minimum_size, :is_preferred_size_set, :minimum_size, :get_preferred_size, :is_maximum_size_set]
Alternatively you can make use of the global CLASSPATH directly:-
require 'java' $CLASSPATH << '/home/tux/processing-2.2.1/core/library/core.jar' app = Java::ProcessingCore::PApplet.new puts "inspect: #{app.inspect}" app.set_size(200, 200) puts "\nto_s: #{app.to_s}" # print the default renderer puts "\nrenderer: #{app.sketch_renderer}" # prints a list of methods including '_size' puts "\nmethods:\n #{ app.methods.reject{ |method| /_size/ !~ method.to_s} }"
There is yet another way to do it using classloader directly:-
require 'java' F = java.io.File class_loader = JRuby.runtime.jruby_class_loader class_loader.add_url(F.new('/home/tux/processing-2.2.1/core/library/core.jar').to_url) app = Java::ProcessingCore::PApplet.new puts "inspect: #{app.inspect}" app.set_size(200, 200) puts "\nto_s: #{app.to_s}" # print the default renderer puts "\nrenderer: #{app.sketch_renderer}" # prints a list of methods including '_size' puts "\nmethods:\n #{ app.methods.reject{ |method| /_size/ !~ method.to_s} }"
In ruby-processing exported sketches, the jars are currently added to the java CLASSPATH (ie on the java side) this may not be necessary anymore (no Applets), the current export process can mess with nested libraries (on the plus side you only need specify a directory to include the contained jars).
java -cp ".:../lib/ruby/*:../lib/*:../lib/library/*" org.jruby.Main ../lib/ruby-processing/runners/run.rb drawolver.rb
Monday, 7 July 2014
Development plans for ruby-processing
The next release of ruby-processing will likely be version 2.5.0 (current release 2.4.4 using jruby-1.7.12). The reason why this will not be a minor release is that I intend to incorporate my pre-compiled vecmath and fastmath libraries as developed on JRubyArt. Both these libraries have been created as jruby extensions (they are written in java, but can be loaded into the jruby runtime as ruby). Apart from the possible efficiency gains of using pre-compiled code, the compiled version of vecmath greatly simplifies the use of my ArcBall utility (only one line of code is required to include ArcBall functionality in a sketch). What I propose to do is to roll back ruby processing commits to the 2.4.4 release, and set that as the stable branch (for the foreseeable future). I see no compelling reasons to issue anymore 2.4 point releases (eg to bump to jruby-1.7.13, and there seems no likelihood of any further processing 2.0 releases, now development has switched up to version 3.0).
JRubyArt has been using the much heralded jruby-9000, but that will only be at a preview release this summer, see tweet:-
Drawolver featuring new libraries, degree precision look up tables, and to_vertex utility for Vec3D:-
Sketch demonstrating use of ShapeRender (ShapeRender and AppRender both implement the Render interface which is used by Vec3D (and Vec2D) to_vertex, to_vertex_uv and to_normal methods, see here for earlier version without using ShapeRender, NB: the FastMath of that version has not survived:
Sketch demonstrating new ArcBall utility, all that's needed to allow mousewheel zoom, and mouse drag to rotate the cube (this form uses camera 'under the hood' to centralize the cube in sketch viewpane, alternative form translates the sketch to provided coordinates):-
JRubyArt has been using the much heralded jruby-9000, but that will only be at a preview release this summer, see tweet:-
@williamthurston We always said "summer 2014"...but we need a bit more for a final version. Preview for August.
— Charles Nutter (@headius) July 7, 2014
Drawolver featuring new libraries, degree precision look up tables, and to_vertex utility for Vec3D:-
# Drawolver: draw 2D & revolve 3D # Example shows how to use the vecmath library, including AppRender utility. # On the ruby side features the use each_cons, a possibly a rare use for this # ruby Enumerable method? # 2010-03-22 - fjenett (somewhat revised by Martin Prout 2014-07-06) load_library :vecmath, :fastmath attr_reader :drawing_mode, :points, :rot_x, :rot_y, :vertices, :renderer def setup size 1024, 768, P3D @renderer = Java::ProcessingVecmath::AppRender.new(self) frame_rate 30 reset_scene end def draw background 0 if (!drawing_mode) translate(width/2, height/2) rotate_x rot_x rotate_y rot_y @rot_x += 0.01 @rot_y += 0.02 translate(-width/2, -height/2) end no_fill stroke 255 points.each_cons(2) { |ps, pe| line ps.x, ps.y, pe.x, pe.y} if (!drawing_mode) stroke 125 fill 120 lights ambient_light 120, 120, 120 vertices.each_cons(2) do |r1, r2| begin_shape(TRIANGLE_STRIP) r1.zip(r2).each { |v1, v2| v1.to_vertex(renderer); v2.to_vertex(renderer)} end_shape end end end def reset_scene @drawing_mode = true @points = [] @rot_x = 0.0 @rot_y = 0.0 end def mouse_pressed reset_scene points << Vec3D.new(mouse_x, mouse_y) end def mouse_dragged points << Vec3D.new(mouse_x, mouse_y) end def mouse_released points << Vec3D.new(mouse_x, mouse_y) recalculate_shape end def recalculate_shape @vertices = [] points.each_cons(2) do |ps, pe| b = (points.last - points.first).normalize! a = ps - points.first dot_product = a.dot b b *= dot_product normal = points.first + b c = ps - normal vertices << [] (0..360).step(12) do |ang| e = normal + c * DegLut.cos(ang) e.z = c.mag * DegLut.sin(ang) vertices.last << e end end @drawing_mode = false end
Sketch demonstrating use of ShapeRender (ShapeRender and AppRender both implement the Render interface which is used by Vec3D (and Vec2D) to_vertex, to_vertex_uv and to_normal methods, see here for earlier version without using ShapeRender, NB: the FastMath of that version has not survived:
# Trefoil, by Andres Colubri # A parametric surface is textured procedurally # by drawing on an offscreen PGraphics surface. # # Features (Vec3D).to_normal(renderer) and (Vec3D).to_vertex_uv(renderer, u, v) # see line 62 for inititialization of renderer where obj is an instance of PShape # renderer = Java::ProcessingVecmath::ShapeRender.new(obj) load_library :vecmath attr_reader :pg, :trefoil def setup size(1024, 768, P3D) texture_mode(NORMAL) noStroke # Creating offscreen surface for 3D rendering. @pg = create_graphics(32, 512, P3D) pg.begin_draw pg.background(0, 0) pg.noStroke pg.fill(255, 0, 0, 200) pg.end_draw # Saving trefoil surface into a PShape3D object @trefoil = create_trefoil(350, 60, 15, pg) end def draw background(0) pg.begin_draw pg.ellipse(rand(0.0 .. pg.width), rand(0.0 .. pg.height), 4, 4) pg.end_draw ambient(250, 250, 250) pointLight(255, 255, 255, 0, 0, 200) push_matrix translate(width/2, height/2, -200) rotate_x(frame_count * PI / 500) rotate_y(frame_count * PI / 500) shape(trefoil) pop_matrix end # Code to draw a trefoil knot surface, with normals and texture # coordinates. Makes of the Vec3D Render interface (uses ShapeRender here). # Adapted from the parametric equations example by Philip Rideout: # http://iphone-3d-programming.labs.oreilly.com/ch03.html # This function draws a trefoil knot surface as a triangle mesh derived # from its parametric equation. def create_trefoil(s, ny, nx, tex) obj = create_shape() obj.begin_shape(TRIANGLES) obj.texture(tex) renderer = Java::ProcessingVecmath::ShapeRender.new(obj) (0 ... nx).each do |j| u0 = j.to_f / nx u1 = (j + 1).to_f / nx (0 ... ny).each do |i| v0 = i.to_f / ny v1 = (i + 1).to_f / ny p0 = eval_point(u0, v0) n0 = eval_normal(u0, v0) p1 = eval_point(u0, v1) n1 = eval_normal(u0, v1) p2 = eval_point(u1, v1) n2 = eval_normal(u1, v1) # Triangle p0-p1-p2 n0.to_normal(renderer) (p0 * s).to_vertex_uv(renderer, u0, v0) n1.to_normal(renderer) (p1 * s).to_vertex_uv(renderer, u0, v1) n2.to_normal(renderer) (p2 * s).to_vertex_uv(renderer, u1, v1) p1 = eval_point(u1, v0) n1 = eval_normal(u1, v0) # Triangle p0-p2-p1 n0.to_normal(renderer) (p0 * s).to_vertex_uv(renderer, u0, v0) n2.to_normal(renderer) (p2 * s).to_vertex_uv(renderer, u1, v1) n1.to_normal(renderer) (p1 * s).to_vertex_uv(renderer, u1, v0) end end obj.end_shape return obj end # Evaluates the surface normal corresponding to normalized # parameters (u, v) def eval_normal(u, v) # Compute the tangents and their cross product. p = eval_point(u, v) tangU = eval_point(u + 0.01, v) tangV = eval_point(u, v + 0.01) tangU -= p tangV -= p tangV.cross(tangU).normalize! # it is easy to chain Vec3D operations end # Evaluates the surface point corresponding to normalized # parameters (u, v) def eval_point(u, v) a = 0.5 b = 0.3 c = 0.5 d = 0.1 s = TAU * u t = (TAU * (1 - v)) * 2 sint = sin(t) cost = cos(t) sint15 = sin(1.5 * t) cost15 = cos(1.5 * t) r = a + b * cost15 x = r * cost y = r * sint z = c * sint15 dv = Vec3D.new( -1.5 * b * sint15 * cost - y, -1.5 * b * sint15 * sint + x, 1.5 * c * cost15) q = dv.normalize # regular normalize creates a new Vec3D for us qvn = Vec3D.new(q.y, -q.x, 0).normalize! # chained Vec3D operations ww = q.cross(qvn) coss = cos(s) sins = sin(s) Vec3D.new( x + d * (qvn.x * coss + ww.x * sins), y + d * (qvn.y * coss + ww.y * sins), z + d * ww.z * sins) end
Sketch demonstrating new ArcBall utility, all that's needed to allow mousewheel zoom, and mouse drag to rotate the cube (this form uses camera 'under the hood' to centralize the cube in sketch viewpane, alternative form translates the sketch to provided coordinates):-
load_library :vecmath attr_reader :my_cube def setup size(600, 600, P3D) smooth(16) ArcBall.init(self) @my_cube = create_shape(BOX, 300, 300, 300) my_cube.set_fill(color(100, 10, 100)) end def draw background(50, 50, 100) define_lights lights stroke(0) shape(my_cube) end def define_lights ambient(20, 20, 20) 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
Labels:
jruby,
processing,
release,
ruby-processing
Friday, 25 April 2014
Experiments with JRuby Integration (for ruby-processing)
Here is the Vec2 class (I wanted to have Vec2D but that doesn't play too well with JRuby, well at least not for me), very loosely based on yokolets Fraction example.
Here is the Vec2Service class
Here is the Rakefile jruby -S rake compile
Here is vec2.rb
Here are some sample usages:-
Here is the output:-
package processing.vec2; import org.apache.commons.math3.util.FastMath; import org.jruby.Ruby; import org.jruby.RubyBoolean; import org.jruby.RubyClass; import org.jruby.RubyFloat; import org.jruby.RubyObject; import org.jruby.anno.JRubyClass; import org.jruby.anno.JRubyMethod; import org.jruby.runtime.Arity; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; /** * * @author Martin Prout */ @JRubyClass(name = "Processing::Vec2") public class Vec2 extends RubyObject { static final double EPSILON = 1.0e-04; // matches processing.org EPSILON double jx = 0; double jy = 0; /** * * @param context * @param klazz * @param args optional (no args jx = 0, jy = 0) * @return new Vec2 object (ruby) */ @JRubyMethod(name = "new", meta = true, rest = true) public static IRubyObject rbNew(ThreadContext context, IRubyObject klazz, IRubyObject[] args) { Vec2 vec2 = (Vec2) ((RubyClass) klazz).allocate(); vec2.init(context, args); return vec2; } /** * * @param runtime * @param klass */ public Vec2(Ruby runtime, RubyClass klass) { super(runtime, klass); } void init(ThreadContext context, IRubyObject[] args) { if (Arity.checkArgumentCount(context.getRuntime(), args, Arity.OPTIONAL.getValue(), 2) == 2) { jx = (Double) args[0].toJava(Double.class); jy = (Double) args[1].toJava(Double.class); } } /** * * @param context * @return */ @JRubyMethod(name = "x") public RubyFloat getX(ThreadContext context) { return context.getRuntime().newFloat(jx); } /** * * @param context * @return */ @JRubyMethod(name = "y") public RubyFloat getY(ThreadContext context) { return context.getRuntime().newFloat(jy); } /** * * @param context * @param other * @return */ @JRubyMethod(name = "set_x") public RubyFloat setX(ThreadContext context, IRubyObject other) { double scalar = (Double) other.toJava(Double.class); jx = scalar; return context.getRuntime().newFloat(jx); } /** * * @param context * @param other * @return */ @JRubyMethod(name = "set_y") public RubyFloat setY(ThreadContext context, IRubyObject other) { double scalar = (Double) other.toJava(Double.class); jy = scalar; return context.getRuntime().newFloat(jy); } /** * * @param context * @param other * @return */ @JRubyMethod(name = "dist") public IRubyObject dist(ThreadContext context, IRubyObject other) { Vec2 b = (Vec2) other.toJava(Vec2.class); double result = FastMath.sqrt((jx - b.jx) * (jx - b.jx) + (jy - b.jy) * (jy - b.jy)); return context.getRuntime().newFloat(result); } /** * * @param context * @param other * @return */ @JRubyMethod(name = "dist_squared") public IRubyObject dist_squared(ThreadContext context, IRubyObject other) { Vec2 b = (Vec2) other.toJava(Vec2.class); double result = (jx - b.jx) * (jx - b.jx) + (jy - b.jy) * (jy - b.jy); return context.getRuntime().newFloat(result); } /** * * @param context * @param other * @return */ @JRubyMethod(name = "cross") public IRubyObject cross(ThreadContext context, IRubyObject other) { Vec2 b = (Vec2) other.toJava(Vec2.class); return context.getRuntime().newFloat(jx * b.jy - jy * b.jx); } /** * * @param context * @param other * @return */ @JRubyMethod(name = "dot") public IRubyObject dot(ThreadContext context, IRubyObject other) { Vec2 b = (Vec2) other.toJava(Vec2.class); return context.getRuntime().newFloat(jx * b.jx + jy * b.jy); } /** * * @param context * @param other * @return new Vec2 object (ruby) */ @JRubyMethod(name = "add") public IRubyObject add(ThreadContext context, IRubyObject other) { Vec2 b = (Vec2) other.toJava(Vec2.class); RubyFloat[] input = {context.getRuntime().newFloat(jx + b.jx), context.getRuntime().newFloat(jy + b.jy)}; return Vec2.rbNew(context, other.getMetaClass(), input); } /** * * @param context * @param other * @return new Vec2 object (ruby) */ @JRubyMethod(name = "sub") public IRubyObject sub(ThreadContext context, IRubyObject other) { Vec2 b = (Vec2) other.toJava(Vec2.class); RubyFloat[] input = {context.getRuntime().newFloat(jx - b.jx), context.getRuntime().newFloat(jy - b.jy)}; return Vec2.rbNew(context, other.getMetaClass(), input); } /** * * @param context * @param other * @return new Vec2 object (ruby) */ @JRubyMethod(name = "mult") public IRubyObject mult(ThreadContext context, IRubyObject other) { double scalar = (Double) other.toJava(Double.class); RubyFloat[] input = {context.getRuntime().newFloat(jx * scalar), context.getRuntime().newFloat(jy * scalar)}; return Vec2.rbNew(context, this.getMetaClass(), input); } /** * * @param context * @param other * @return new Vec2 object (ruby) */ @JRubyMethod(name = "div") public IRubyObject div(ThreadContext context, IRubyObject other) { double scalar = (Double) other.toJava(Double.class); if (FastMath.abs(scalar) < Vec2.EPSILON) { return this; } RubyFloat[] input = {context.getRuntime().newFloat(jx / scalar), context.getRuntime().newFloat(jy / scalar)}; return Vec2.rbNew(context, this.getMetaClass(), input); } /** * * @param context * @return */ @JRubyMethod(name = "heading") public IRubyObject heading(ThreadContext context) { return context.getRuntime().newFloat(FastMath.atan2(-jy, jx) * -1.0); } /** * * @param context * @return */ @JRubyMethod(name = "mag_squared") public IRubyObject mag_squared(ThreadContext context) { return context.getRuntime().newFloat(jx * jx + jy * jy); } /** * * @param context * @return */ @JRubyMethod(name = "mag") public IRubyObject mag(ThreadContext context) { return context.getRuntime().newFloat(FastMath.hypot(jx, jy)); } /** * * @param context * @param scalar * @return * @todo have optional conditional block (evaluate to boolean) */ @JRubyMethod(name = "set_mag") public IRubyObject set_mag(ThreadContext context, IRubyObject scalar) { double new_mag = (Double) scalar.toJava(Double.class); double current = FastMath.sqrt(FastMath.pow(jx, 2) + FastMath.pow(jy, 2)); jx *= new_mag / current; jy *= new_mag / current; return this; } /** * * @param context * @return this as a ruby object */ @JRubyMethod(name = "normalize!") public IRubyObject normalize_bang(ThreadContext context) { double mag = FastMath.sqrt(FastMath.pow(jx, 2) + FastMath.pow(jy, 2)); jx /= mag; jy /= mag; return this; } /** * * @param context * @return new Vec2 object (ruby) */ @JRubyMethod(name = "normalize") public IRubyObject normalize(ThreadContext context) { double mag = FastMath.sqrt(FastMath.pow(jx, 2) + FastMath.pow(jy, 2)); RubyFloat[] input = {context.getRuntime().newFloat(jx / mag), context.getRuntime().newFloat(jy / mag)}; return Vec2.rbNew(context, this.getMetaClass(), input); } /** * Example of a regular ruby class method * * @param context * @param klazz the klazz of object we are creating * @param other input angle in radians * @return new Vec2 object (ruby) */ @JRubyMethod(name = "from_angle", meta = true) public static IRubyObject from_angle(ThreadContext context, IRubyObject klazz, IRubyObject other) { final double scalar = (Double) other.toJava(Double.class); RubyFloat[] args = {context.getRuntime().newFloat(FastMath.cos(scalar)), context.getRuntime().newFloat(FastMath.sin(scalar))}; Vec2 vec2 = (Vec2) ((RubyClass) klazz).allocate(); vec2.init(context, args); return vec2; } /** * * @param context * @param other * @return this Vec2 object rotated */ @JRubyMethod(name = "rotate!") public IRubyObject rotate_bang(ThreadContext context, IRubyObject other) { double theta = (Double) other.toJava(Double.class); double x = (jx * FastMath.cos(theta) - jy * FastMath.sin(theta)); double y = (jx * FastMath.sin(theta) + jy * FastMath.cos(theta)); jx = x; jy = y; return this; } /** * * @param context * @param other * @return a new Vec2 object rotated */ @JRubyMethod(name = "rotate") public IRubyObject rotate(ThreadContext context, IRubyObject other) { double theta = (Double) other.toJava(Double.class); double x = (jx * FastMath.cos(theta) - jy * FastMath.sin(theta)); double y = (jx * FastMath.sin(theta) + jy * FastMath.cos(theta)); RubyFloat[] input = {context.getRuntime().newFloat(x), context.getRuntime().newFloat(y)}; return Vec2.rbNew(context, this.getMetaClass(), input); } /** * * @param context * @param args * @return as a new Vec2 object (ruby) */ @JRubyMethod(name = "lerp", rest = true) public IRubyObject lerp(ThreadContext context, IRubyObject[] args) { Arity.checkArgumentCount(context.getRuntime(), args, 2, 2); Vec2 vec = (Vec2) args[0].toJava(Vec2.class); double scalar = (Double) args[1].toJava(Double.class); assert (scalar >= 0 && scalar < 1.0) : "Lerp value " + scalar + " out of range 0 .. 1.0"; double x0 = jx + (vec.jx - jx) * scalar; double y0 = jx + (vec.jx - jx) * scalar; RubyFloat[] input = {context.getRuntime().newFloat(x0), context.getRuntime().newFloat(y0)}; return Vec2.rbNew(context, this.getMetaClass(), input); } /** * * @param context * @param args * @return this */ @JRubyMethod(name = "lerp!", rest = true) public IRubyObject lerp_bang(ThreadContext context, IRubyObject[] args) { Arity.checkArgumentCount(context.getRuntime(), args, 2, 2); Vec2 vec = (Vec2) args[0].toJava(Vec2.class); double scalar = (Double) args[1].toJava(Double.class); assert (scalar >= 0 && scalar < 1.0) : "Lerp value " + scalar + " out of range 0 .. 1.0"; double x0 = jx + (vec.jx - jx) * scalar; double y0 = jx + (vec.jx - jx) * scalar; jx = x0; jy = y0; return this; } /** * * @param context * @return */ @JRubyMethod(name = "copy") public IRubyObject copy(ThreadContext context) { double x0 = jx; double y0 = jy; RubyFloat[] input = {context.getRuntime().newFloat(x0), context.getRuntime().newFloat(y0)}; return Vec2.rbNew(context, this.getMetaClass(), input); } /** * * @param context * @return */ @JRubyMethod(name = "to_a") public IRubyObject toArray(ThreadContext context) { RubyFloat[] output = {context.getRuntime().newFloat(jx), context.getRuntime().newFloat(jy)}; return context.getRuntime().newArray(output); } /** * * @param context * @return */ @JRubyMethod(name = "to_s") public IRubyObject to_s(ThreadContext context) { return context.getRuntime().newString(String.format("Vec2(x = %4.4f, y = %4.4f)", jx, jy)); } /** * * @return */ @Override public int hashCode() { int hash = 5; hash = 53 * hash + (int) (Double.doubleToLongBits(this.jx) ^ (Double.doubleToLongBits(this.jx) >>> 32)); hash = 53 * hash + (int) (Double.doubleToLongBits(this.jy) ^ (Double.doubleToLongBits(this.jy) >>> 32)); return hash; } /** * * @param obj * @return */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Vec2 other = (Vec2) obj; if (Double.doubleToLongBits(this.jx) != Double.doubleToLongBits(other.jx)) { return false; } return (Double.doubleToLongBits(this.jy) == Double.doubleToLongBits(other.jy)); } /** * * @param context * @param other * @return */ @JRubyMethod(name = "almost_eql?") public IRubyObject almost_eql_p(ThreadContext context, IRubyObject other) { Vec2 v = (other instanceof Vec2) ? (Vec2) other.toJava(Vec2.class) : null; IRubyObject result = (v == null) ? RubyBoolean.newBoolean(context.getRuntime(), false) : (FastMath.abs(jx - v.jx) > Vec2.EPSILON) ? RubyBoolean.newBoolean(context.getRuntime(), false) : (FastMath.abs(jy - v.jy) > Vec2.EPSILON) ? RubyBoolean.newBoolean(context.getRuntime(), false) : RubyBoolean.newBoolean(context.getRuntime(), true); return result; // return false as default unless not null && values equal } }
Here is the Vec2Service class
package processing.vec2; import java.io.IOException; import org.jruby.Ruby; import org.jruby.RubyClass; import org.jruby.RubyModule; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.runtime.load.BasicLibraryService; public class Vec2Service implements BasicLibraryService { @Override public boolean basicLoad(final Ruby runtime) throws IOException { RubyModule processing = runtime.defineModule("Processing"); RubyModule vec2Module = processing.defineModuleUnder("Vec2"); RubyClass vec2 = vec2Module.defineClassUnder(Vec2.class.getSimpleName(), runtime.getObject(), VEC_ALLOCATOR); vec2.defineAnnotatedMethods(Vec2.class); return true; } private static final ObjectAllocator VEC_ALLOCATOR = new ObjectAllocator() { @Override public IRubyObject allocate(Ruby runtime, RubyClass klazz) { return new Vec2(runtime, klazz); } }; }
Here is the Rakefile jruby -S rake compile
# -*- ruby -*- require 'java' require 'rake/javaextensiontask' Rake::JavaExtensionTask.new('processing/vec2') do |ext| jars = FileList['lib/*.jar'] ext.classpath = jars.map {|x| File.expand_path x}.join ':' ext.name = 'processing/vecmath' ext.debug=true ext.source_version='1.7' ext.target_version='1.7' end
Here is vec2.rb
require_relative './vecmath' require 'processing/vec2/vec2' module Processing module Vec2 class Vec2 alias_method :*, :mult alias_method :/, :div alias_method :+, :add alias_method :-, :sub alias_method :==, :eql? end end end
Here are some sample usages:-
require 'java' require_relative '../lib/processing_vecmath' include Processing::Vec2 vec = Vec2.new(0, 0) vec1 = Vec2.new(0, 0) vec2 = Vec2.new(3.0, 4.0) vec3 =Vec2.new(1.00000000000, 1.000000000000) puts vec3.normalize puts "mult #{vec3}" puts "add #{vec2 + vec3}" puts "original #{vec2}" puts vec == vec1 puts vec2.almost_eql? Vec2.new(3.0, 4.0) puts vec.almost_eql? Vec2.new(0, 0) puts vec.dist(vec2) puts vec2.mag
Here is the output:-
Vec2(x = 0.7071, y = 0.7071) mult Vec2(x = 1.0000, y = 1.0000) add Vec2(x = 4.0000, y = 5.0000) original Vec2(x = 3.0000, y = 4.0000) true true true 5.0 5.0Interesting working in Netbeans the rake build script was unecessary, but size of compiled jar was much smaller with the script (however I had linked jruby-9000 in Netbeans). See repository on github for Vec3 and spec tests.
Labels:
jruby,
netbeans-8.0,
rake-compile
Tuesday, 8 April 2014
Ruby-Processing Architecture
Recently I watched a presentation by Hisaro Asari on JRuby
The interesting from this talk was the future direction of JRuby including replacing the current the Lexical Analysis parsing to an AST with a Semantic Analysis to an Intermediate Representation. This will allow for optimization, before passing to compiler (via Control Flow Graph, and Data Flow Graph analysis?). In the further future there may be foreign function interface support at the jvm level (Charlie has submitted an ffi proposal, 2016 at earliest), and there is the experimental truffle and graaal. What is clear is there will be no further support for ruby-2.0.0 (experimental in JRuby 1.7) with JRuby-9000 aiming at ruby-2.1.0 support.
Seems we may not need to wait too long to test the new Intermediate Representation runtime (and then we might also be able to start using ruby-2.1.0 syntax?).
In case you missed it: my @rubyconf_au talk video is up https://t.co/elc6DnJeuJ and so are the slides https://t.co/bGzT5sf2VU
— あさり (@hiro_asari) April 7, 2014
which inspired me to produce this for ruby-processing:-The interesting from this talk was the future direction of JRuby including replacing the current the Lexical Analysis parsing to an AST with a Semantic Analysis to an Intermediate Representation. This will allow for optimization, before passing to compiler (via Control Flow Graph, and Data Flow Graph analysis?). In the further future there may be foreign function interface support at the jvm level (Charlie has submitted an ffi proposal, 2016 at earliest), and there is the experimental truffle and graaal. What is clear is there will be no further support for ruby-2.0.0 (experimental in JRuby 1.7) with JRuby-9000 aiming at ruby-2.1.0 support.
Seems we may not need to wait too long to test the new Intermediate Representation runtime (and then we might also be able to start using ruby-2.1.0 syntax?).
JRuby master now has a working mixed-mode (interpret + JIT) for the new IR-based runtime. Master will switch to IR very soon .
— Charles Nutter (@headius) April 9, 2014
Labels:
architecture,
AST,
CFG,
DFG,
IR,
jruby,
ruby-processing
Subscribe to:
Posts (Atom)
Followers
About Me
- monkstone
- I have developed JRubyArt and propane new versions of ruby-processing for JRuby-9.1.5.0 and processing-3.2.2




