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