Debian Codegraph @

examples/media/soundspace/soundspace.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # ----------------------------------------------------------------------------
3 # pyglet
4 # Copyright (c) 2006-2008 Alex Holkner
5 # All rights reserved.
6 #
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions
9 # are met:
10 #
11 # * Redistributions of source code must retain the above copyright
12 # notice, this list of conditions and the following disclaimer.
13 # * Redistributions in binary form must reproduce the above copyright
14 # notice, this list of conditions and the following disclaimer in
15 # the documentation and/or other materials provided with the
16 # distribution.
17 # * Neither the name of pyglet nor the names of its
18 # contributors may be used to endorse or promote products
19 # derived from this software without specific prior written
20 # permission.
21 #
22 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 # POSSIBILITY OF SUCH DAMAGE.
34 # ----------------------------------------------------------------------------
35 # $Id$
36
37 import math
38
39 import pyglet
40
41 # # Default to OpenAL if available:
42 # pyglet.options['audio'] = 'openal', 'pulse', 'directsound', 'silent'
43
44 from pyglet.gl import glClearColor
45 from pyglet.graphics import Group
46 from pyglet.math import Mat4, Vec3
47
48 import reader
49
50 pyglet.resource.path.append('res')
51 pyglet.resource.reindex()
52
53
54 def orientation_angle(orientation):
55 return math.atan2(orientation[2], orientation[0])
56
57
58 # Shape hack functions
59 def _update_line(line, x, y, x2, y2):
60 line._x = x
61 line._y = y
62 line._x2 = x2
63 line._y2 = y2
64 line._update_translation()
65 line._update_vertices()
66
67
68 def _bordered_rect_alpha(rect, inner_alpha, border_alpha):
69 rect._rgba = rect._rgba[:3] + (inner_alpha,)
70 rect._border_rgba = rect._border_rgba[:3] + (border_alpha,)
71 rect._update_color()
72
73
74 class Handle:
75 tip = ''
76
77 def __init__(self, window, player):
78 self.win = window
79 self.player = player
80
81 def hit_test(self, x, y, z):
82 dx, dy, dz = (a - b for a, b in zip(self.pos(), (x, y, z)))
83 if dx * dx + dy * dy + dz * dz < self.radius * self.radius:
84 return -dx, -dy, -dz
85
86 def pos(self):
87 raise NotImplementedError
88
89 def delete(self):
90 pass
91
92 def update_shapes(self):
93 pass
94
95 def begin_drag(self, offset):
96 self.offset = offset
97 return self
98
99 def on_mouse_press(self, x, y, button, modifiers):
100 self.win.remove_handlers(self)
101
102 def on_mouse_release(self, x, y, button, modifiers):
103 self.win.remove_handlers(self)
104
105
106 class LabelHandle(Handle):
107 def __init__(self, window, player):
108 super().__init__(window, player)
109 txt = getattr(player, 'label', '')
110 self.text = pyglet.text.Label(txt, font_size=10, color=(0, 0, 0, 255),
111 anchor_y='top', anchor_x='center', batch=window.text_batch)
112
113 def delete(self):
114 self.text.delete()
115
116 def update_shapes(self):
117 x, z = self.win.player_transform(self.player)
118 self.text.position = x, z - 5, 0
119
120 def hit_test(self, x, y, z):
121 return None
122
123
124 class PositionHandle(Handle):
125 tip = 'position'
126 radius = .3
127
128 def __init__(self, window, player):
129 super().__init__(window, player)
130 self._triangle = pyglet.shapes.Triangle(
131 0, self.radius,
132 -self.radius * math.sqrt(3.0) / 2.0, -self.radius / 2.0,
133 self.radius * math.sqrt(3.0) / 2.0, -self.radius / 2.0,
134 (255, 0, 0, 255),
135 window.handle_batch,
136 window.hgrp_position)
137 self._triangle.anchor_position = 0.0, -self.radius * 0.75
138
139 def update_shapes(self):
140 self._triangle.position = self.player.position[0], self.player.position[2]
141
142 def delete(self):
143 self._triangle.delete()
144
145 def pos(self):
146 return self.player.position
147
148 def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
149 pos = self.win.mouse_transform(x, y)
150 self.player.position = \
151 (pos[0] - self.offset[0],
152 pos[1] - self.offset[1],
153 pos[2] - self.offset[2])
154
155
156 class OrientationHandle(Handle):
157 radius = .1
158 length = 1.5
159
160 def __init__(self, window, player):
161 super().__init__(window, player)
162 self._line = pyglet.shapes.Line(0, 0, 0, 0,
163 color=(74, 74, 74),
164 batch=window.handle_batch,
165 group=Group(0, window.hgrp_orientation))
166 self._disc = pyglet.shapes.Circle(0, 0, self.radius,
167 color=(255, 255, 0, 255),
168 batch=window.handle_batch,
169 group=Group(1, window.hgrp_orientation))
170
171 def pos(self):
172 x, _, z = self.player.position
173 direction = self.get_orientation()
174 sz = math.sqrt(direction[0] ** 2 + direction[1] ** 2 + direction[2] ** 2) or 1
175 if sz != 0:
176 x += direction[0] / sz * self.length
177 z += direction[2] / sz * self.length
178 return x, 0, z
179
180 def get_orientation(self):
181 return NotImplementedError()
182
183 def update_shapes(self):
184 px, _, py = self.player.position
185 x, _, y = self.pos()
186
187 self._line._thickness = 1.0 / self.win.zoom
188 _update_line(self._line, x, y, px, py)
189
190 self._disc.position = x, y
191
192 def delete(self):
193 self._line.delete()
194 self._disc.delete()
195
196 def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
197 px, py, pz = self.player.position
198 hx, hy, hz = self.win.mouse_transform(x, y)
199 self.set_orientation(
200 (hx - self.offset[0] - px,
201 hy - self.offset[1] - py,
202 hz - self.offset[2] - pz))
203
204
205 class ConeOrientationHandle(OrientationHandle):
206 tip = 'cone_orientation'
207
208 def get_orientation(self):
209 return self.player.cone_orientation
210
211 def set_orientation(self, orientation):
212 self.player.cone_orientation = orientation
213
214
215 class ForwardOrientationHandle(OrientationHandle):
216 tip = 'forward_orientation'
217
218 def get_orientation(self):
219 return self.player.forward_orientation
220
221 def set_orientation(self, orientation):
222 self.player.forward_orientation = orientation
223
224
225 class ConeAngleHandle(Handle):
226 length = .1
227 radius = .1
228
229 def __init__(self, window, player):
230 super().__init__(window, player)
231 self._sector = pyglet.shapes.Sector(0, 0, self.length, color=self.fill_color, batch=window.handle_batch)
232 self._handle = pyglet.shapes.Circle(0, 0, self.radius, color=self.color, batch=window.handle_batch)
233
234 def pos(self):
235 px, py, pz = self.player.position
236 angle = orientation_angle(self.player.cone_orientation)
237 angle += self.get_angle() * math.pi / 180. / 2
238 x = math.cos(angle) * self.length
239 z = math.sin(angle) * self.length
240 return px + x, py, pz + z
241
242 def get_angle(self):
243 raise NotImplementedError
244
245 def update_shapes(self):
246 px, _, py = self.player.position
247 angle = orientation_angle(self.player.cone_orientation)
248 a = math.radians(self.get_angle())
249
250 self._sector.angle = self.get_angle()
251 self._sector.rotation = math.degrees((-angle / 2.0) + (a / 4.0))
252 self._sector.position = px, py
253
254 x, _, y = self.pos()
255 self._handle.radius = self.radius
256 self._handle.position = x, y
257
258 def delete(self):
259 self._sector.delete()
260 self._handle.delete()
261
262 def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
263 px, py, pz = self.player.position
264 hx, hy, hz = self.win.mouse_transform(x, y)
265 angle = orientation_angle(self.player.cone_orientation)
266 hangle = orientation_angle((hx - px, hy - py, hz - pz))
267 if hangle < angle:
268 hangle += math.pi * 2
269 res = min(max((hangle - angle) * 2, 0), math.pi * 2)
270 self.set_angle(res * 180. / math.pi)
271
272
273 class ConeInnerAngleHandle(ConeAngleHandle):
274 tip = 'cone_inner_angle'
275 length = 1.
276 color = (51, 204, 51, 255)
277 fill_color = (0, 255, 0, 26)
278
279 def get_angle(self):
280 return self.player.cone_inner_angle
281
282 def set_angle(self, angle):
283 self.player.cone_inner_angle = angle
284
285
286 class ConeOuterAngleHandle(ConeAngleHandle):
287 tip = 'cone_outer_angle'
288 length = 1.2
289 color = (51, 51, 204, 255)
290 fill_color = (0, 0, 255, 26)
291
292 def get_angle(self):
293 return self.player.cone_outer_angle
294
295 def set_angle(self, angle):
296 self.player.cone_outer_angle = angle
297
298
299 class MoreHandle(Handle):
300 tip = 'More...'
301 radius = .2
302
303 open = False
304 open_width = 1.5
305 open_height = 1.5
306
307 def __init__(self, window, player):
308 super().__init__(window, player)
309 self._box = pyglet.shapes.BorderedRectangle(0, 0, self.open_width, self.open_height, 1,
310 (255, 255, 255), (0, 0, 0),
311 window.handle_batch,
312 Group(0, window.hgrp_label_more_collapsed))
313 # The BorderedRectangle vehemently defends itself from having differing alpha values,
314 # but hack them in case we want them
315 _bordered_rect_alpha(self._box, 201, 255)
316
317 self._circ = pyglet.shapes.Circle(0, 0, self.radius,
318 batch=window.handle_batch,
319 group=Group(0, window.hgrp_label_more_collapsed))
320 self._outline = pyglet.shapes.Arc(0, 0, self.radius,
321 color=(0, 0, 0, 255),
322 batch=window.handle_batch,
323 group=Group(1, window.hgrp_label_more_collapsed))
324 self._line0 = pyglet.shapes.Line(0, 0, 0, 0,
325 color=(0, 0, 0, 255),
326 batch=window.handle_batch,
327 group=Group(2, window.hgrp_label_more_collapsed))
328 self._line1 = pyglet.shapes.Line(0, 0, 0, 0,
329 color=(0, 0, 0, 255),
330 batch=window.handle_batch,
331 group=Group(3, window.hgrp_label_more_collapsed))
332
333 def pos(self):
334 x, y, z = self.player.position
335 return x + 1, y, z + 1
336
337 def get_angle(self):
338 raise NotImplementedError
339
340 def update_shapes(self):
341 self._box.visible = self.open
342 self._circ.visible = not self.open
343 self._outline.visible = not self.open
344 self._line0.visible = not self.open
345 self._line1.visible = not self.open
346
347 x, _, z = self.pos()
348 if self.open:
349 x -= 0.2
350 z += 0.2
351 self._box.border = 1.0 / self.win.zoom
352 self._box.position = x, z - self.open_height
353 else:
354 self._circ.position = x, z
355 self._outline.position = x, z
356 self._outline.thickness = 1.0 / self.win.zoom
357 r = self.radius - 0.1
358 self._line0._thickness = 1.0 / self.win.zoom
359 _update_line(self._line0, x - r, z, x + r, z)
360 self._line1._thickness = 1.0 / self.win.zoom
361 _update_line(self._line1, x, z - r, x, z + r)
362
363 def delete(self):
364 self._box.delete()
365 self._circ.delete()
366 self._outline.delete()
367 self._line0.delete()
368 self._line1.delete()
369
370 def begin_drag(self, offset):
371 self.open = True
372 self.win.set_more_player_handles(self.player)
373 return self
374
375 def on_mouse_press(self, x, y, button, modifiers):
376 x, y, z = self.win.mouse_transform(x, y)
377 for handle in self.win.more_handles:
378 if handle.hit_test(x, y, z):
379 return
380 self.win.set_more_player_handles(None)
381 self.win.remove_handlers(self)
382 self.open = False
383
384 def on_mouse_release(self, x, y, button, modifiers):
385 pass
386
387
388 class SliderHandle(Handle):
389 length = 1.
390 width = .05
391 radius = .1
392
393 def __init__(self, window, player, x, z):
394 super().__init__(window, player)
395 self._groove = pyglet.shapes.Rectangle(0, 0, self.length, self.width,
396 color=(127, 127, 127, 255),
397 batch=window.handle_batch,
398 group=Group(0, window.hgrp_more_expanded))
399 self._thumb = pyglet.shapes.Circle(0, 0, self.radius,
400 color=(51, 51, 51, 255),
401 batch=window.handle_batch,
402 group=Group(1, window.hgrp_more_expanded))
403 self.x = x
404 self.z = z
405
406 def pos(self):
407 x, y, z = self.player.position
408 x += self.x + self.get_value() * self.length
409 z += self.z
410 return x, y, z
411
412 def update_shapes(self):
413 gx = self.x + self.player.position[0]
414 gz = self.z + self.player.position[2]
415 self._groove.position = gx, gz
416
417 x, _, z = self.pos()
418 self._thumb.position = x, z
419
420 def delete(self):
421 self._groove.delete()
422 self._thumb.delete()
423
424 def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
425 px, py, pz = self.player.position
426 hx, hy, hz = self.win.mouse_transform(x, y)
427 value = float(hx - px - self.x) / self.length
428 value = min(max(value, 0), 1)
429 self.set_value(value)
430
431
432 class VolumeHandle(SliderHandle):
433 tip = 'volume'
434
435 def __init__(self, window, player):
436 super().__init__(window, player, 1, .9)
437
438 def get_value(self):
439 return self.player.volume
440
441 def set_value(self, value):
442 self.player.volume = value
443
444
445 class ListenerVolumeHandle(SliderHandle):
446 tip = 'volume'
447
448 def __init__(self, window, player):
449 super().__init__(window, player, -.5, -1)
450
451 def get_value(self):
452 return self.player.volume
453
454 def set_value(self, value):
455 self.player.volume = value
456
457
458 class MinDistanceHandle(SliderHandle):
459 tip = 'min_distance'
460
461 def __init__(self, window, player):
462 super().__init__(window, player, 1, .6)
463
464 def get_value(self):
465 return self.player.min_distance / 5.
466
467 def set_value(self, value):
468 self.player.min_distance = value * 5.
469
470
471 class MaxDistanceHandle(SliderHandle):
472 tip = 'max_distance'
473
474 def __init__(self, window, player):
475 super().__init__(window, player, 1, .3)
476
477 def get_value(self):
478 return min(self.player.max_distance / 5., 1.0)
479
480 def set_value(self, value):
481 self.player.max_distance = value * 5.
482
483
484 class ConeOuterGainHandle(SliderHandle):
485 tip = 'cone_outer_gain'
486
487 def __init__(self, window, player):
488 super().__init__(window, player, 1, 0)
489
490 def get_value(self):
491 return self.player.cone_outer_gain
492
493 def set_value(self, value):
494 self.player.cone_outer_gain = value
495
496
497 class SoundSpaceWindow(pyglet.window.Window):
498 def __init__(self, **kwargs):
499 kwargs.setdefault("caption", "Sound Space")
500 kwargs.setdefault("resizable", True)
501 super().__init__(**kwargs)
502
503 # pixels per unit
504 self.zoom = 40
505 self.tx = self.width/2
506 self.ty = self.height/2
507
508 # The handle batch is drawn with a greatly zoomed view matrix
509 self._grid_batch = pyglet.graphics.Batch()
510 self.handle_batch = pyglet.graphics.Batch()
511 self.text_batch = pyglet.graphics.Batch()
512
513 # Various handle groups for proper rendering order
514 self.hgrp_position = Group(0)
515 self.hgrp_orientation = Group(1)
516 self.hgrp_cone_inner = Group(2)
517 self.hgrp_cone_outer = Group(3)
518 self.hgrp_label_more_collapsed = Group(4)
519 self.hgrp_more_expanded = Group(5)
520
521 self._grid = []
522 self._refresh_grid()
523 self.players = []
524 self.handles = []
525 self.more_handles = []
526
527 listener = pyglet.media.get_audio_driver().get_listener()
528 self.handles.append(PositionHandle(self, listener))
529 self.handles.append(ForwardOrientationHandle(self, listener))
530 self.handles.append(ListenerVolumeHandle(self, listener))
531 self.handles.append(LabelHandle(self, listener))
532
533 self.tip = pyglet.text.Label('', font_size=10, color=(0, 0, 0, 255),
534 anchor_y='top', anchor_x='center')
535 self.tip_player = None
536
537 def add_player(self, player):
538 self.players.append(player)
539 self.handles.append(PositionHandle(self, player))
540 self.handles.append(ConeOrientationHandle(self, player))
541 self.handles.append(ConeInnerAngleHandle(self, player))
542 self.handles.append(ConeOuterAngleHandle(self, player))
543 self.handles.append(LabelHandle(self, player))
544 self.handles.append(MoreHandle(self, player))
545
546 def set_more_player_handles(self, player):
547 if player:
548 self.more_handles = [
549 VolumeHandle(self, player),
550 MinDistanceHandle(self, player),
551 MaxDistanceHandle(self, player),
552 ConeOuterGainHandle(self, player),
553 ]
554 else:
555 for h in self.more_handles:
556 h.delete()
557 self.more_handles = []
558
559 def _refresh_grid(self):
560 for line in self._grid:
561 line.delete()
562 self._grid.clear()
563
564 for x in range(0, self.width, self.zoom):
565 self._grid.append(pyglet.shapes.Line(x, 0, x, self.height, batch=self._grid_batch))
566 for y in range(0, self.height, self.zoom):
567 self._grid.append(pyglet.shapes.Line(0, y, self.width, y, batch=self._grid_batch))
568
569 def mouse_transform(self, x, y):
570 return (float(x - self.tx) / self.zoom,
571 0,
572 float(y - self.ty) / self.zoom)
573
574 def player_transform(self, player):
575 return (player.position[0] * self.zoom + self.tx,
576 player.position[2] * self.zoom + self.ty)
577
578 def hit_test(self, mouse_x, mouse_y):
579 x, y, z = self.mouse_transform(mouse_x, mouse_y)
580 for handle in self.more_handles[::-1] + self.handles[::-1]:
581 offset = handle.hit_test(x, y, z)
582 if offset:
583 return handle, offset
584 return None, None
585
586 def on_draw(self):
587 glClearColor(.8, .8, .8, 1)
588 self.clear()
589
590 for handle in self.handles + self.more_handles:
591 handle.update_shapes()
592
593 self.view = Mat4()
594 self._grid_batch.draw()
595
596 self.view = Mat4().translate(Vec3(self.tx, self.ty, 0)).scale(Vec3(self.zoom, self.zoom, 0))
597 self.handle_batch.draw()
598
599 self.view = Mat4()
600 self.text_batch.draw()
601
602 if self.tip_player:
603 player_pos = self.player_transform(self.tip_player)
604 self.tip.x = player_pos[0]
605 self.tip.y = player_pos[1] - 15
606 self.tip.draw()
607
608 def on_mouse_scroll(self, x, y, dx, dy):
609 self.zoom += dy * 10
610 self.zoom = min(max(self.zoom, 10), 100)
611 self._refresh_grid()
612
613 def on_mouse_press(self, x, y, button, modifiers):
614 handle, offset = self.hit_test(x, y)
615 if handle:
616 self.push_handlers(handle.begin_drag(offset))
617 else:
618 self.push_handlers(
619 on_mouse_press=self._pan_on_mouse_press_or_release,
620 on_mouse_release=self._pan_on_mouse_press_or_release,
621 on_mouse_drag=self._pan_on_mouse_drag,
622 )
623
624 def _pan_on_mouse_press_or_release(self, _x, _y, _b, _m):
625 self.remove_handlers(
626 on_mouse_press=self._pan_on_mouse_press_or_release,
627 on_mouse_release=self._pan_on_mouse_press_or_release,
628 on_mouse_drag=self._pan_on_mouse_drag,
629 )
630
631 def _pan_on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
632 self.tx += dx
633 self.ty += dy
634
635 def on_mouse_motion(self, x, y, dx, dy):
636 handle, offset = self.hit_test(x, y)
637 if handle:
638 self.tip.text = handle.tip
639 pos = self.player_transform(handle.player)
640 self.tip_player = handle.player
641 else:
642 self.tip.text = ''
643
644
645 if __name__ == '__main__':
646 # We swap Y and Z, moving to left-handed system
647 listener = pyglet.media.get_audio_driver().get_listener()
648 listener.up_orientation = (0, -1, 0)
649
650 # Start facing up (er, forwards)
651 listener.forward_orientation = (0, 0, 1)
652
653 listener.label = 'Listener'
654
655 w = SoundSpaceWindow()
656 r = reader.SpaceReader(w)
657 r.read(pyglet.resource.file('space.txt', 'r'))
658 player_group = pyglet.media.PlayerGroup(w.players)
659 player_group.play()
660
661 pyglet.app.run()