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

Showing posts with label block. Show all posts
Showing posts with label block. Show all posts

Tuesday, 29 April 2014

Implementing my ruby Vecmath library in java (as a JRuby extension)

Well finally I've done it, no compromises, no dodgy fixes, I've 100% implemented my ruby-library in java, as a jruby extension, so it behaves exactly as the original library. The last thing I implemented was the attr_accessors (well just the setters, the getters are obvious) and methods with an optional block. The setters was the easiest it was as simple as @JRubyMethod(name = "x=") instead of @JRubyMethod(name = "set_x") in the method annotation.
Here is the Vec3D version of set_mag that takes an optional block
Using the Vec3D name was a simple as Vec3D = Processing::Vec2::Vec2
/**
* Call yield if block given, do nothing if yield == false
* else set_mag to given scalar
* @param context
* @param scalar double value to set
* @param block should return a boolean (optional)
* @return
*/
@JRubyMethod(name = "set_mag")
public IRubyObject set_mag(ThreadContext context, IRubyObject scalar, Block block) {
 if (block.isGiven()) {
  if (!(boolean) block.yield(context, scalar).toJava(Boolean.class)) {
   return this;
  }
 }
 double new_mag = (Double) scalar.toJava(Double.class);
 double current = FastMath.sqrt(FastMath.pow(jx, 2) + FastMath.pow(jy, 2) + FastMath.pow(jz, 2));
 jx *= new_mag / current;
 jy *= new_mag / current;
 jz *= new_mag / current;
 return this;
}

See the full code here.

Friday, 23 August 2013

File Chooser Library For ruby-processing

Well here it is in action my ruby-processing file_chooser library, that like control panel takes a block the fc.display returns a a string that you can use in load_image etc to load a file, you can do all this in a block if you like (see below). Is a replacement for vanilla processing selectInput function that relies on reflection (and the chooser cannot be so easily customised). PS the my_file temporary variable is not required. The chooser starts in the users home folder on unix (mac/linux) or the working directory on windoes.
load_library :file_chooser
attr_reader :img

###########
# Example file chooser (in this case image file chooser)
# the image loading and resizing is encapsulated in the block,
# borrows heavily off control_panel. 
###########

def setup
  size 600, 600
  file_chooser do |fc|
    fc.look_feel "Nimbus"
    fc.set_filter "Image Files",  [".png", ".jpg"]
    my_file = fc.display
    @img = load_image(my_file)
    img.resize(width, height)
  end
end

def draw
  image img, 0, 0
end

The Chooser (a customised JFileChooser)
The Sketch

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