update.
[chise/ruby.git] / chise / stroke.rb
1 # Copyright (C) 2002-2004 Kouichirou Eto, All rights reserved.
2 # StrokeFont library by eto 2003-0311
3
4 require "sgl"
5 require "chise/kage"
6 require "chise/csf"
7
8 module StrokeFont
9   class StrokesRenderer
10     def initialize
11       @start_time = nil
12       @strokes = nil
13 #     @hsv = [0, 0, 100] #白
14       @hsv = [0, 0, 0] #黒
15       init
16     end
17     attr_accessor :hsv
18
19     def init() @start_time = Time.now; end
20
21     def set_strokes(strokes)
22       @strokes = strokes
23       init
24     end
25
26     def draw
27       return if @strokes.nil?
28       @strokes.strokes.each_with_index {|stroke, index|
29         #draw_delay(stroke, index)
30         draw_alpha(stroke, 100)
31       }
32     end
33
34     def draw_alpha(stroke, time)
35       px, py = 0, 0
36       span = 0.1
37       time += span*2
38       stroke.points.each {|x, y|
39         a = time / span
40         colorHSV(@hsv[0], @hsv[1], @hsv[2], a*100.0)
41         line(px, py, x, y) if (px != 0 || py != 0) #最初の点ではない
42         px, py = x, y
43         time -= span
44       }
45     end
46
47     def draw_delay(stroke, index)
48       now = Time.now
49       @start_time = Time.now if @start_time == nil
50       diff = now - @start_time #開始からの秒数がはいる
51       draw_alpha(stroke, diff - index*0.3)
52     end
53   end
54
55   class Stroke # a connected line
56     def initialize
57       @points = []
58       @length = nil
59     end
60     attr_reader :points
61
62     def add_point(x, y)
63       @points << [x, y]
64     end
65
66     def length #未チェック
67       return @length if @length
68       len = 0.0
69       px, py = -1, -1
70       @points.each {|x, y|
71         if px != -1
72           len += Math.sqrt((x-px)*(x-px)+(y-py)*(y-py))
73         end
74         px, py = x, y
75       }
76       @length = len
77       return @length
78     end
79   end
80
81   class Strokes # lines
82     def initialize
83       @strokes = []
84       @px1, @py1, @px2, @py2 = 0, 0, 0, 0
85       @x1, @y1, @x2, @y2 = 0, 0, 0, 0
86       @px, @py = -1, -1
87     end
88     attr_reader :strokes
89
90     def add_line(x1, y1, x2, y2)
91       if (@px != x1 || @py != y1) #以前の点とつながっていなかったら、
92         @strokes << Stroke.new
93         @strokes.last.add_point(x1, y1)
94       end
95       @strokes.last.add_point(x2, y2)
96       @px, @py = x2, y2
97     end
98
99   end
100 end