ajout des fonts.
[minwii.git] / src / minwii / widgets / playingscreen.py
1 # -*- coding: utf-8 -*-
2 """
3 Écran de jeu MinWii :
4 bandes arc-en-ciel représentant un clavier.
5
6 $Id$
7 $URL$
8 """
9 import pygame
10 from cursors import WarpingCursor
11 from column import Column
12 import events
13 from eventutils import event_handler, EventDispatcher, EventHandlerMixin
14 import types
15 from musicxml import Tone
16
17 from config import FRAMERATE
18 from config import FIRST_HUE
19 from config import MIDI_VELOCITY_RANGE
20 from config import MIDI_PAN_RANGE
21 from config import MIDI_VELOCITY_WRONG_NOTE_ATTN
22
23 from globals import BACKGROUND_LAYER
24 from globals import CURSOR_LAYER
25 from globals import PLAYING_MODES_DICT
26
27 class PlayingScreenBase(pygame.sprite.LayeredDirty, EventHandlerMixin) :
28
29 def __init__(self, synth, distinctNotes=[]) :
30 """
31 distinctNotes : notes disctinctes présentes dans la chanson
32 triées du plus grave au plus aigu.
33 """
34 super(PlayingScreenBase, self).__init__()
35 self.synth = synth
36 self.distinctNotes = distinctNotes
37 self.keyboardLength = 0
38 self.keyboardRects = []
39 self.cursor = None
40 self._initRects()
41 self.columns = {}
42 self._initColumns()
43 self._running = False
44 self.draw(pygame.display.get_surface())
45 self._initCursor()
46
47 def _initRects(self) :
48 """ création des espaces réservés pour
49 afficher les colonnes.
50 """
51 self.keyboardLength = len(self.distinctNotes)
52
53 screen = pygame.display.get_surface()
54
55 self.dispWidth = dispWidth = screen.get_width()
56 self.dispHeight = dispHeight = screen.get_height()
57
58 columnWidth = int(round(float(dispWidth) / self.keyboardLength))
59
60 rects = []
61 for i in range(self.keyboardLength) :
62 upperLeftCorner = (i*columnWidth, 0)
63 rect = pygame.Rect(upperLeftCorner, (columnWidth, dispHeight))
64 rects.append(rect)
65
66 self.keyboardRects = rects
67
68 def _initColumns(self) :
69
70 hueStep = FIRST_HUE / (self.keyboardLength - 1)
71 for i, rect in enumerate(self.keyboardRects) :
72 hue = FIRST_HUE - hueStep * i
73 tone = self.distinctNotes[i]
74 c = Column(self, i, hue, rect, tone)
75 self.add(c, layer=BACKGROUND_LAYER)
76 self.columns[tone.midi] = c
77
78
79 def _initCursor(self) :
80 self.cursor = WarpingCursor(blinkMode=True)
81 self.add(self.cursor, layer=CURSOR_LAYER)
82
83 def run(self):
84 self._running = True
85 clock = pygame.time.Clock()
86 pygame.display.flip()
87 pygame.mouse.set_visible(False)
88 while self._running :
89 EventDispatcher.dispatchEvents()
90 dirty = self.draw(pygame.display.get_surface())
91 pygame.display.update(dirty)
92 clock.tick(FRAMERATE)
93
94 def stop(self) :
95 self._running = False
96 self.synth.system_reset()
97 pygame.mouse.set_visible(True)
98 self.cursor._stopBlink()
99
100 @event_handler(pygame.KEYDOWN)
101 def handleKeyDown(self, event) :
102 if event.key == pygame.K_q or event.unicode == u'q':
103 self.stop()
104
105 @event_handler(pygame.MOUSEBUTTONDOWN)
106 def onMouseDown(self, event) :
107 # TODO à cleaner : on vire le dernier élément
108 # parce qu'il s'agit du curseur
109 for col in reversed(self.sprites()[:-1]) :
110 if col.rect.collidepoint(*event.pos):
111 self.raiseColDown(col, event)
112 break
113
114 @event_handler(pygame.MOUSEBUTTONUP)
115 def onMouseUp(self, event) :
116 for col in reversed(self.sprites()[:-1]) :
117 if col.rect.collidepoint(*event.pos) :
118 self.raiseColUp(col, event)
119 break
120
121 @event_handler(pygame.MOUSEMOTION)
122 def onMouseMove(self, event) :
123 for col in reversed(self.sprites()[:-1]) :
124 if col.rect.collidepoint(*event.pos) :
125 self.raiseColOver(col, event)
126 break
127
128 def raiseColDown(self, col, mouseEvent) :
129 evt = pygame.event.Event(events.COLDOWN, column=col, pos=mouseEvent.pos)
130 pygame.event.post(evt)
131
132 def raiseColUp(self, col, mouseEvent) :
133 evt = pygame.event.Event(events.COLUP, column=col, pos=mouseEvent.pos)
134 pygame.event.post(evt)
135
136 def raiseColOver(self, col, mouseEvent) :
137 evt = pygame.event.Event(events.COLOVER, column=col, pos=mouseEvent.pos, mouseEvent=mouseEvent)
138 pygame.event.post(evt)
139
140 def getVelocity(self, pos) :
141 vel = (float(self.dispWidth) - pos[1]) / self.dispWidth
142 vel = int(vel * (MIDI_VELOCITY_RANGE[1] - MIDI_VELOCITY_RANGE[0])) + MIDI_VELOCITY_RANGE[0]
143 return vel
144
145 def getPan(self, index) :
146 pan = float(index) / (self.keyboardLength -1)
147 pan = int(pan * (MIDI_PAN_RANGE[1] - MIDI_PAN_RANGE[0])) + MIDI_PAN_RANGE[0]
148 return pan
149
150 def playnote(self, col, pos, vel=None) :
151 pan = self.getPan(col.index)
152 self.synth.cc(0, 10, pan)
153 vel = vel or self.getVelocity(pos)
154 self.synth.noteon(0, col.tone.midi, vel)
155
156 class PlayingScreen(PlayingScreenBase) :
157 "fenêtre de jeu pour improvisation"
158
159 scale = [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
160
161 def __init__(self, synth) :
162 distinctNotes = []
163 for midi in self.scale :
164 tone = Tone(midi)
165 distinctNotes.append(tone)
166
167 super(PlayingScreen, self).__init__(synth, distinctNotes)
168
169 @event_handler(events.NOTEON)
170 def noteon(self, evt) :
171 tone = evt.tone
172 self.synth.noteon(0, tone.midi, 96)
173
174 @event_handler(events.NOTEOFF)
175 def noteoff(self, evt) :
176 tone = evt.tone
177 self.synth.noteoff(0, tone.midi)
178
179
180 class SongPlayingScreen(PlayingScreenBase) :
181
182 def __init__(self, synth, song, mode=PLAYING_MODES_DICT['NORMAL']) :
183 super(SongPlayingScreen, self).__init__(synth, song.distinctNotes)
184 self.song = song
185 self.quarterNoteDuration = song.quarterNoteDuration
186 self.currentColumn = None
187 self.noteIterator = self.song.iterNotes()
188 self.displayNext()
189 self._plugListeners(mode)
190
191 def _plugListeners(self, mode) :
192 "initialisation des gestionnaires d'événements en fonction du mode"
193
194 if mode == PLAYING_MODES_DICT['BEGINNER'] :
195 EventDispatcher.addEventListener(events.COLOVER, self.handleBeginnerColumnOver)
196
197 elif mode == PLAYING_MODES_DICT['EASY'] :
198 EventDispatcher.addEventListener(events.COLDOWN, self.handleEasyColumnDown)
199 EventDispatcher.addEventListener(events.COLOVER, self.handleEasyColumnOver)
200
201 elif mode == PLAYING_MODES_DICT['NORMAL'] :
202 EventDispatcher.addEventListener(events.COLOVER, self.handleNormalColumnOver)
203 EventDispatcher.addEventListener(events.COLDOWN, self.handleColumnDown)
204 EventDispatcher.addEventListener(events.COLUP, self.handleColumnUp)
205
206 elif mode == PLAYING_MODES_DICT['ADVANCED'] :
207 EventDispatcher.addEventListener(events.COLDOWN, self.handleColumnDown)
208 EventDispatcher.addEventListener(events.COLUP, self.handleColumnUp)
209
210 elif mode == PLAYING_MODES_DICT['EXPERT'] :
211 EventDispatcher.addEventListener(events.COLDOWN, self.handleExpertColumnDown)
212 EventDispatcher.addEventListener(events.COLUP, self.handleExpertColumnUp)
213
214
215 # --- HID listeners ---
216 def handleBeginnerColumnOver(self, event) :
217 col = event.column
218 if col.state and not self.currentNotePlayed :
219 self.playnote(col, event.pos)
220 SongPlayingScreen.setNoteTimeout(
221 int(self.currentNote.duration * \
222 self.quarterNoteDuration)
223 )
224 self.currentNotePlayed = True
225
226 def handleEasyColumnOver(self, event) :
227 col = event.column
228 if col.state and \
229 any(event.mouseEvent.buttons) and \
230 not self.currentNotePlayed :
231 self.playnote(col, event.pos)
232 SongPlayingScreen.setNoteTimeout(
233 int(self.currentNote.duration * \
234 self.quarterNoteDuration)
235 )
236 self.currentNotePlayed = True
237
238
239 def handleNormalColumnOver(self, event) :
240 col = event.column
241 if col.state and \
242 any(event.mouseEvent.buttons) and \
243 not self.currentNotePlayed :
244 self.playnote(col, event.pos)
245 self.currentNotePlayed = True
246
247 def handleColumnDown(self, event) :
248 col = event.column
249 if col.state:
250 self.playnote(col, event.pos)
251 self.currentNotePlayed = True
252
253 def handleEasyColumnDown(self, event) :
254 col = event.column
255 if col.state and \
256 not self.currentNotePlayed :
257 self.playnote(col, event.pos)
258 SongPlayingScreen.setNoteTimeout(
259 int(self.currentNote.duration * \
260 self.quarterNoteDuration)
261 )
262 self.currentNotePlayed = True
263
264
265 def handleExpertColumnDown(self, event) :
266 col = event.column
267 if col.state :
268 self.playnote(col, event.pos)
269 self.currentNotePlayed = True
270 else :
271 vel = self.getVelocity(event.pos) * MIDI_VELOCITY_WRONG_NOTE_ATTN
272 vel = int(vel)
273 self.playnote(col, event.pos, vel=vel)
274 self.alternateColumn = col
275 self.currentNotePlayed = False
276
277 def handleColumnUp(self, event) :
278 if self.currentNotePlayed :
279 self.synth.noteoff(0, self.currentColumn.tone.midi)
280 self.displayNext()
281
282 def handleExpertColumnUp(self, event) :
283 if self.currentNotePlayed :
284 self.synth.noteoff(0, self.currentColumn.tone.midi)
285 self.displayNext()
286 else :
287 self.synth.noteoff(0, self.alternateColumn.tone.midi)
288
289 # --- End HID listeners ---
290
291
292 def displayNext(self, event=None) :
293 if self.currentColumn:
294 self.currentColumn.update(False)
295 note, verseIndex = self.noteIterator.next()
296 syllabus = note.lyrics[verseIndex].syllabus()
297 column = self.columns[note.midi]
298 column.update(True, syllabus)
299 self.currentColumn = column
300 self.currentNote = note
301 self.currentNotePlayed = False
302
303 @event_handler(events.NOTEEND)
304 def clearTimeOutAndDisplayNext(self, evt) :
305 pygame.time.set_timer(evt.type, 0)
306 self.synth.noteoff(0, self.currentNote.midi)
307 self.displayNext()
308
309 @staticmethod
310 def setNoteTimeout(delay) :
311 pygame.time.set_timer(events.NOTEEND, delay)
312
313 def stop(self) :
314 pygame.time.set_timer(events.NOTEEND, 0)
315 super(SongPlayingScreen, self).stop()
316
317