Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/ruby
- require 'curses'
- require 'matrix'
- require 'pp'
- include Curses
- include Math
- class Fig
- def initialize(matrix)
- @matrix = matrix
- end
- def getPairVertexs
- end
- def transform(trMethod)
- @matrix = trMethod.call(@matrix)
- end
- attr_accessor :matrix
- end
- class Square < Fig
- def initialize(matrix)
- super matrix
- end
- def getPairVertexs
- r = []
- rows = @matrix.row_vectors
- rows.each_cons(2) { |pair|
- r << pair
- }
- r << [rows[-1], rows[0]]
- return r
- end
- end
- class Drawer
- def initialize(primitives)
- @primitives = primitives
- end
- def drawLines(lines)
- lines.each { |v|
- @primitives[:line].call v[0][0], v[0][1], v[1][0], v[1][1]
- }
- end
- end
- def putMsg(x, y, ch)
- setpos y, x
- addstr ch
- end
- def drawLine(x0, y0, x1, y1)
- x0 = x0.round
- y0 = y0.round
- x1 = x1.round
- y1 = y1.round
- points = []
- steep = ((y1-y0).abs) > ((x1-x0).abs)
- if steep
- x0,y0 = y0,x0
- x1,y1 = y1,x1
- end
- if x0 > x1
- x0,x1 = x1,x0
- y0,y1 = y1,y0
- end
- deltax = x1-x0
- deltay = (y1-y0).abs
- error = (deltax / 2).to_i
- y = y0
- ystep = nil
- if y0 < y1
- ystep = 1
- else
- ystep = -1
- end
- for x in x0..x1
- if steep
- points << {:x => y, :y => x}
- else
- points << {:x => x, :y => y}
- end
- error -= deltay
- if error < 0
- y += ystep
- error += deltax
- end
- end
- points.each {|p| putMsg p[:x], p[:y], '.' }
- return points
- end
- def centerOfMass(matrix)
- sVector = Vector[0, 0]
- matrix.row_vectors.each { |v|
- sVector += v
- }
- r = sVector/matrix.row_vectors.size
- return r
- end
- dr = Drawer.new({
- :line => lambda { |x0, y0, x1, y1| drawLine x0, y0, x1, y1 }
- })
- sqSize = 10
- cubes = [
- Square.new(Matrix[[0, 0], [sqSize, 0], [sqSize, sqSize], [0, sqSize]]),
- Square.new(Matrix[[0, 0], [sqSize, 0], [sqSize, sqSize], [0, sqSize]]),
- Square.new(Matrix[[0, 0], [sqSize, 0], [sqSize, sqSize], [0, sqSize]]),
- Square.new(Matrix[[0, 0], [sqSize, 0], [sqSize, sqSize], [0, sqSize]])
- ]
- def genRotateMatrix(angle)
- trRotateAroundMass = lambda { |a|
- c = centerOfMass a
- cMatrix = Matrix.rows(a.row_vectors.map { |v| v - c })
- crMatrix = cMatrix * Matrix[[cos(angle), -sin(angle)], [sin(angle), cos(angle)]]
- crcMatrix = Matrix.rows(crMatrix.row_vectors.map { |v| v + c } )
- }
- end
- def genShiftMatrx(shift)
- lambda { |a|
- Matrix.rows(a.row_vectors.map { |v| v + shift })
- }
- end
- init_screen
- nl
- noecho
- maxy = lines
- maxx = cols
- cubes.each_with_index { |c, index|
- c.transform genShiftMatrx Vector[(index + 1)*maxx/(1 + cubes.size), maxy/2]
- }
- while true
- cubes.each { |sq|
- sq.transform genRotateMatrix 0.1
- dr.drawLines sq.getPairVertexs
- }
- refresh
- sleep 0.03
- clear
- end
- getch
- close_screen
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement