Class: RLSL::CodeGenerator::RubyWrapperGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/rlsl/code_generator/ruby_wrapper_generator.rb

Constant Summary collapse

VECTOR_CONSTRUCTORS =
{
  2 => "vec2_new",
  3 => "vec3_new",
  4 => "vec4_new"
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(context) ⇒ RubyWrapperGenerator

Returns a new instance of RubyWrapperGenerator.



12
13
14
# File 'lib/rlsl/code_generator/ruby_wrapper_generator.rb', line 12

def initialize(context)
  @context = context
end

Instance Method Details

#generateObject



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
# File 'lib/rlsl/code_generator/ruby_wrapper_generator.rb', line 16

def generate
  <<~C
    static void render_scanline(uint8_t *pixels, int width, int height, int y, vec2 resolution, Uniforms uniforms) {
      int flipped_y = height - 1 - y;
      for (int x = 0; x < width; x++) {
        vec2 frag_coord = vec2_new((float)x, (float)flipped_y);
        vec3 color = shader_#{@context.name}(frag_coord, resolution, uniforms);
        int idx = (y * width + x) * 4;
        // Output as BGRA (macOS native format)
        pixels[idx] = (uint8_t)(clamp_f(color.z, 0.0f, 1.0f) * 255.0f);
        pixels[idx+1] = (uint8_t)(clamp_f(color.y, 0.0f, 1.0f) * 255.0f);
        pixels[idx+2] = (uint8_t)(clamp_f(color.x, 0.0f, 1.0f) * 255.0f);
        pixels[idx+3] = 255;
      }
    }

    static VALUE shader_#{@context.name}_render(VALUE self, VALUE rb_buffer, VALUE rb_width, VALUE rb_height#{@context.uniform_argument_list}) {
      int width = NUM2INT(rb_width);
      int height = NUM2INT(rb_height);
      vec2 resolution = vec2_new((float)width, (float)height);

      Uniforms uniforms;
      #{uniform_assignments}

      Check_Type(rb_buffer, T_STRING);
      rb_str_modify(rb_buffer);
      uint8_t *pixels = (uint8_t *)RSTRING_PTR(rb_buffer);

      #ifdef __APPLE__
      dispatch_apply(height, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t y) {
        render_scanline(pixels, width, height, (int)y, resolution, uniforms);
      });
      #else
      for (int y = 0; y < height; y++) {
        render_scanline(pixels, width, height, y, resolution, uniforms);
      }
      #endif

      return Qnil;
    }
  C
end