Class: SparkleMotion::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/sparkle_motion/node.rb

Overview

Base class representing the state of an ordered set of lights, with an ability to debug things via PNG dump.

Constant Summary collapse

FRAME_PERIOD =
0.04
DEBUG_SCALE =
Vector2.new(x: 2, y: 1)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lights:) ⇒ Node

Returns a new instance of Node.



12
13
14
15
16
17
18
# File 'lib/sparkle_motion/node.rb', line 12

def initialize(lights:)
  @lights   = lights
  @state    = Array.new(@lights)
  lights.times do |n|
    @state[n] = 0.0
  end
end

Instance Attribute Details

#debugObject

Returns the value of attribute debug.



10
11
12
# File 'lib/sparkle_motion/node.rb', line 10

def debug
  @debug
end

#historyObject

Returns the value of attribute history.



10
11
12
# File 'lib/sparkle_motion/node.rb', line 10

def history
  @history
end

#lightsObject

Returns the value of attribute lights.



10
11
12
# File 'lib/sparkle_motion/node.rb', line 10

def lights
  @lights
end

Instance Method Details

#[](n) ⇒ Object



25
# File 'lib/sparkle_motion/node.rb', line 25

def [](n); @state[n]; end

#[]=(n, val) ⇒ Object



26
# File 'lib/sparkle_motion/node.rb', line 26

def []=(n, val); @state[n] = val; end

#snapshot_to!(fname) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/sparkle_motion/node.rb', line 37

def snapshot_to!(fname)
  enrich_history!
  png = new_image
  history.inject(0) do |y, snapshot|
    next_y = y + (snapshot[:y] || 0)
    colors = snapshot[:state].map { |z| to_color(z) }
    (y..(next_y - 1)).each do |yy|
      colors.each_with_index do |c, x|
        x1 = (x * DEBUG_SCALE.x).to_i
        x2 = ((x + 1) * DEBUG_SCALE.x).to_i - 1
        (x1..x2).each do |xx|
          png[xx, yy] = c
        end
      end
    end
    next_y
  end
  png.save(fname, interlace: false)
end

#update(t) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/sparkle_motion/node.rb', line 28

def update(t)
  return unless @debug
  prev_t  = @history.last
  prev_t  = prev_t ? prev_t[:t] : t
  @history << { t:     t,
                dt:    t - prev_t,
                state: (0..(@lights - 1)).map { |n| self[n] } }
end