File: visual.py

package info (click to toggle)
python-vispy 0.6.6-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 21,240 kB
  • sloc: python: 57,407; javascript: 6,810; makefile: 63; sh: 5
file content (680 lines) | stat: -rw-r--r-- 21,697 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
# -*- coding: utf-8 -*-
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""

Definitions
===========

Visual : an object that (1) can be drawn on-screen, (2) can be manipulated
by configuring the coordinate transformations that it uses.

View : a special type of visual that (1) draws the contents of another visual,
(2) using a different set of transforms. Views have only the basic visual
interface (draw, bounds, attach, etc.) and lack access to the specific features
of the visual they are linked to (for example, LineVisual has a ``set_data()``
method, but there is no corresponding method on a view of a LineVisual).


Class Structure
===============

* `BaseVisual` - provides transforms and view creation
  This class lays out the basic API for all visuals: ``draw()``, ``bounds()``,
  ``view()``, and ``attach()`` methods, as well as a `TransformSystem` instance
  that determines where the visual will be drawn.
    * `Visual` - defines a shader program to draw.
      Subclasses are responsible for supplying the shader code and configuring
      program variables, including transforms.
        * `VisualView` - clones the shader program from a Visual instance.
          Instances of `VisualView` contain their own shader program,
          transforms and filter attachments, and generally behave like a normal
          instance of `Visual`.
    * `CompoundVisual` - wraps multiple Visual instances.
      These visuals provide no program of their own, but instead rely on one or
      more internally generated `Visual` instances to do their drawing. For
      example, a PolygonVisual consists of an internal LineVisual and
      MeshVisual.
        * `CompoundVisualView` - wraps multiple VisualView instances.
          This allows a `CompoundVisual` to be viewed with a different set of
          transforms and filters.


Making Visual Subclasses
========================

When making subclasses of `Visual`, it is only necessary to reimplement the
``_prepare_draw()``, ``_prepare_transforms()``, and ``_compute_bounds()``
methods. These methods will be called by the visual automatically when it is
needed for itself or for a view of the visual.

It is important to remember
when implementing these methods that most changes made to the visual's shader
program should also be made to the programs for each view. To make this easier,
the visual uses a `MultiProgram`, which allows all shader programs across the
visual and its views to be accessed simultaneously. For example::

    def _prepare_draw(self, view):
        # This line applies to the visual and all of its views
        self.shared_program['a_position'] = self._vbo

        # This line applies only to the view that is about to be drawn
        view.view_program['u_color'] = (1, 1, 1, 1)

Under most circumstances, it is not necessary to reimplement `VisualView`
because a view will directly access the ``_prepare`` and ``_compute`` methods
from the visual it is viewing. However, if the `Visual` to be viewed is a
subclass that reimplements other methods such as ``draw()`` or ``bounds()``,
then it will be necessary to provide a new matching `VisualView` subclass.


Making CompoundVisual Subclasses
================================

Compound visual subclasses are generally very easy to construct::

    class PlotLineVisual(visuals.CompoundVisual):
        def __init__(self, ...):
            self._line = LineVisual(...)
            self._point = PointVisual(...)
            visuals.CompoundVisual.__init__(self, [self._line, self._point])

A compound visual will automatically handle forwarding transform system changes
and filter attachments to its internally-wrapped visuals. To the user, this
will appear to behave as a single visual.
"""

from __future__ import division
import weakref

from .. import gloo
from ..util.event import EmitterGroup, Event
from ..util import logger, Frozen
from .shaders import StatementList, MultiProgram
from .transforms import TransformSystem


class VisualShare(object):
    """Contains data that is shared between all views of a visual.

    This includes:

        * GL state variables (blending, depth test, etc.)
        * A weak dictionary of all views
        * A list of filters that should be applied to all views
        * A cache for bounds.

    """
    def __init__(self):
        # Note: in some cases we will need to compute bounds independently for
        # each view. That will have to be worked out later..
        self.bounds = {}
        self.gl_state = {}
        self.views = weakref.WeakKeyDictionary()
        self.filters = []
        self.visible = True


class BaseVisual(Frozen):
    """Superclass for all visuals.

    This class provides:

        * A TransformSystem.
        * Two events: `update` and `bounds_change`.
        * Minimal framework for creating views of the visual.
        * A data structure that is shared between all views of the visual.
        * Abstract `draw`, `bounds`, `attach`, and `detach` methods.

    Parameters
    ----------
    vshare : instance of VisualShare | None
        The visual share.

    Notes
    -----
    When used in the scenegraph, all Visual classes are mixed with
    `vispy.scene.Node` in order to implement the methods, attributes and
    capabilities required for their usage within it.

    This subclasses Frozen so that subclasses can easily freeze their
    properties.
    """
    def __init__(self, vshare=None):
        self._view_class = getattr(self, '_view_class', VisualView)

        self._vshare = VisualShare() if vshare is None else vshare
        self._vshare.views[self] = None

        self.events = EmitterGroup(source=self,
                                   auto_connect=True,
                                   update=Event,
                                   bounds_change=Event
                                   )

        self._transforms = None
        self.transforms = TransformSystem()

    @property
    def transform(self):
        return self.transforms.visual_transform.transforms[0]

    @transform.setter
    def transform(self, tr):
        self.transforms.visual_transform = tr

    @property
    def transforms(self):
        return self._transforms

    @transforms.setter
    def transforms(self, trs):
        if trs is self._transforms:
            return
        if self._transforms is not None:
            self._transforms.changed.disconnect(self._transform_changed)
        self._transforms = trs
        trs.changed.connect(self._transform_changed)
        self._transform_changed()

    def get_transform(self, map_from='visual', map_to='render'):
        """Return a transform mapping between any two coordinate systems.

        Parameters
        ----------
        map_from : str
            The starting coordinate system to map from. Must be one of: visual,
            scene, document, canvas, framebuffer, or render.
        map_to : str
            The ending coordinate system to map to. Must be one of: visual,
            scene, document, canvas, framebuffer, or render.
        """
        return self.transforms.get_transform(map_from, map_to)

    @property
    def visible(self):
        return self._vshare.visible

    @visible.setter
    def visible(self, v):
        if v != self._vshare.visible:
            self._vshare.visible = v
            self.update()

    def view(self):
        """Return a new view of this visual.
        """
        return self._view_class(self)

    def draw(self):
        raise NotImplementedError(self)

    def attach(self, filt, view=None):
        """Attach a Filter to this visual.

        Each filter modifies the appearance or behavior of the visual.

        Parameters
        ----------
        filt : object
            The filter to attach.
        view : instance of VisualView | None
            The view to use.
        """
        raise NotImplementedError(self)

    def detach(self, filt, view=None):
        """Detach a filter.

        Parameters
        ----------
        filt : object
            The filter to detach.
        view : instance of VisualView | None
            The view to use.
        """
        raise NotImplementedError(self)

    def bounds(self, axis, view=None):
        """Get the bounds of the Visual

        Parameters
        ----------
        axis : int
            The axis.
        view : instance of VisualView
            The view to use.
        """
        if view is None:
            view = self
        if axis not in self._vshare.bounds:
            self._vshare.bounds[axis] = self._compute_bounds(axis, view)
        return self._vshare.bounds[axis]

    def _compute_bounds(self, axis, view):
        raise NotImplementedError(self)

    def _bounds_changed(self):
        self._vshare.bounds.clear()

    def update(self):
        """Update the Visual"""
        self.events.update()

    def _transform_changed(self, event=None):
        self.update()


class BaseVisualView(object):
    """Base class for a view on a visual.

    This class must be mixed with another Visual class to work properly. It
    works mainly by forwarding the calls to _prepare_draw, _prepare_transforms,
    and _compute_bounds to the viewed visual.
    """
    def __init__(self, visual):
        self._visual = visual

    @property
    def visual(self):
        return self._visual

    def _prepare_draw(self, view=None):
        self._visual._prepare_draw(view=view)

    def _prepare_transforms(self, view):
        self._visual._prepare_transforms(view)

    def _compute_bounds(self, axis, view):
        self._visual._compute_bounds(axis, view)

    def __repr__(self):
        return '<%s on %r>' % (self.__class__.__name__, self._visual)


class Visual(BaseVisual):
    """Base class for all visuals that can be drawn using a single shader
    program.

    This class creates a MultiProgram, which is an object that
    behaves like a normal shader program (you can assign shader code, upload
    values, set template variables, etc.) but internally manages multiple
    ModularProgram instances, one per view.

    Subclasses generally only need to reimplement _compute_bounds,
    _prepare_draw, and _prepare_transforms.

    Parameters
    ----------
    vcode : str
        Vertex shader code.
    fcode : str
        Fragment shader code.
    gcode : str or None
        Optional geometry shader code.
    program : instance of Program | None
        The program to use. If None, a program will be constructed using
        ``vcode`` and ``fcode``.
    vshare : instance of VisualShare | None
        The visual share, if necessary.
    """
    def __init__(self, vcode='', fcode='', gcode=None, program=None,
                 vshare=None):
        self._view_class = VisualView
        BaseVisual.__init__(self, vshare)
        if vshare is None:
            self._vshare.draw_mode = None
            self._vshare.index_buffer = None
            if program is None:
                self._vshare.program = MultiProgram(vcode, fcode, gcode)
            else:
                self._vshare.program = program
                if len(vcode) > 0 or len(fcode) > 0:
                    raise ValueError("Cannot specify both program and "
                                     "vcode/fcode arguments.")

        self._program = self._vshare.program.add_program()
        self._prepare_transforms(self)
        self._filters = []
        self._hooks = {}

    def set_gl_state(self, preset=None, **kwargs):
        """Define the set of GL state parameters to use when drawing

        Parameters
        ----------
        preset : str
            Preset to use.
        **kwargs : dict
            Keyword arguments to `gloo.set_state`.
        """
        self._vshare.gl_state = kwargs
        self._vshare.gl_state['preset'] = preset

    def update_gl_state(self, *args, **kwargs):
        """Modify the set of GL state parameters to use when drawing

        Parameters
        ----------
        *args : tuple
            Arguments.
        **kwargs : dict
            Keyword argments.
        """
        if len(args) == 1:
            self._vshare.gl_state['preset'] = args[0]
        elif len(args) != 0:
            raise TypeError("Only one positional argument allowed.")
        self._vshare.gl_state.update(kwargs)

    def _compute_bounds(self, axis, view):
        """Return the (min, max) bounding values of this visual along *axis*
        in the local coordinate system.
        """
        return None

    def _prepare_draw(self, view=None):
        """This visual is about to be drawn.

        Visuals should implement this method to ensure that all program
        and GL state variables are updated immediately before drawing.

        Return False to indicate that the visual should not be drawn.
        """
        return True

    def _prepare_transforms(self, view):
        """This method is called whenever the TransformSystem instance is
        changed for a view.

        Assign a view's transforms to the proper shader template variables
        on the view's shader program.

        Note that each view has its own TransformSystem. In this method we
        connect the appropriate mapping functions from the view's
        TransformSystem to the view's program.
        """
        raise NotImplementedError()
        # Todo: this method can be removed if we somehow enable the shader
        # to specify exactly which transform functions it needs by name. For
        # example:
        #
        #     // mapping function is automatically defined from the
        #     // corresponding transform in the view's TransformSystem
        #     gl_Position = visual_to_render(a_position);
        #

    @property
    def shared_program(self):
        return self._vshare.program

    @property
    def view_program(self):
        return self._program

    @property
    def _draw_mode(self):
        return self._vshare.draw_mode

    @_draw_mode.setter
    def _draw_mode(self, m):
        self._vshare.draw_mode = m

    @property
    def _index_buffer(self):
        return self._vshare.index_buffer

    @_index_buffer.setter
    def _index_buffer(self, buf):
        self._vshare.index_buffer = buf

    def draw(self):
        if not self.visible:
            return
        self._configure_gl_state()
        if self._prepare_draw(view=self) is False:
            return

        if self._vshare.draw_mode is None:
            raise ValueError("_draw_mode has not been set for visual %r" %
                             self)
        try:
            self._program.draw(self._vshare.draw_mode,
                               self._vshare.index_buffer)
        except Exception:
            logger.warning("Error drawing visual %r" % self)
            raise

    def _configure_gl_state(self):
        gloo.set_state(**self._vshare.gl_state)

    def _get_hook(self, shader, name):
        """Return a FunctionChain that Filters may use to modify the program.

        *shader* should be "vert", "geom", or "frag"
        *name* should be "pre" or "post"
        """
        assert name in ('pre', 'post')
        key = (shader, name)
        if key in self._hooks:
            return self._hooks[key]
        hook = StatementList()
        if shader == 'vert':
            self.view_program.vert[name] = hook
        elif shader == 'frag':
            self.view_program.frag[name] = hook
        elif shader == 'geom':
            self.view_program.geom[name] = hook
        else:
            raise ValueError("shader must be vert, geom, or frag")
        self._hooks[key] = hook
        return hook

    def attach(self, filt, view=None):
        """Attach a Filter to this visual

        Each filter modifies the appearance or behavior of the visual.

        Parameters
        ----------
        filt : object
            The filter to attach.
        view : instance of VisualView | None
            The view to use.
        """
        if view is None:
            self._vshare.filters.append(filt)
            for view in self._vshare.views.keys():
                filt._attach(view)
        else:
            view._filters.append(filt)
            filt._attach(view)

    def detach(self, filt, view=None):
        """Detach a filter.

        Parameters
        ----------
        filt : object
            The filter to detach.
        view : instance of VisualView | None
            The view to use.
        """
        if view is None:
            self._vshare.filters.remove(filt)
            for view in self._vshare.views.keys():
                filt._detach(view)
        else:
            view._filters.remove(filt)
            filt._detach(view)


class VisualView(BaseVisualView, Visual):
    """A view on another Visual instance.

    View instances are created by calling ``visual.view()``.

    Because this is a subclass of `Visual`, all instances of `VisualView`
    define their own shader program (which is a clone of the viewed visual's
    program), transforms, and filter attachments.
    """
    def __init__(self, visual):
        BaseVisualView.__init__(self, visual)
        Visual.__init__(self, vshare=visual._vshare)

        # Attach any shared filters
        for filt in self._vshare.filters:
            filt._attach(self)


class CompoundVisual(BaseVisual):
    """Visual consisting entirely of sub-visuals.

    To the user, a compound visual behaves exactly like a normal visual--it
    has a transform system, draw() and bounds() methods, etc. Internally, the
    compound visual automatically manages proxying these transforms and methods
    to its sub-visuals. 

    Parameters
    ----------
    subvisuals : list of BaseVisual instances
        The list of visuals to be combined in this compound visual.
    """
    def __init__(self, subvisuals):
        self._view_class = CompoundVisualView
        self._subvisuals = []
        BaseVisual.__init__(self)
        for v in subvisuals:
            self.add_subvisual(v)
        self.freeze()

    def add_subvisual(self, visual):
        """Add a subvisual

        Parameters
        ----------
        visual : instance of Visual
            The visual to add.
        """
        visual.transforms = self.transforms
        visual._prepare_transforms(visual)
        self._subvisuals.append(visual)
        visual.events.update.connect(self._subv_update)
        self.update()

    def remove_subvisual(self, visual):
        """Remove a subvisual

        Parameters
        ----------
        visual : instance of Visual
            The visual to remove.
        """
        visual.events.update.disconnect(self._subv_update)
        self._subvisuals.remove(visual)
        self.update()

    def _subv_update(self, event):
        self.update()

    def _transform_changed(self, event=None):
        for v in self._subvisuals:
            v.transforms = self.transforms
        BaseVisual._transform_changed(self)

    def draw(self):
        """Draw the visual
        """
        if not self.visible:
            return
        if self._prepare_draw(view=self) is False:
            return

        for v in self._subvisuals:
            if v.visible:
                v.draw()

    def _prepare_draw(self, view):
        pass

    def _prepare_transforms(self, view):
        for v in view._subvisuals:
            v._prepare_transforms(v)

    def set_gl_state(self, preset=None, **kwargs):
        """Define the set of GL state parameters to use when drawing

        Parameters
        ----------
        preset : str
            Preset to use.
        **kwargs : dict
            Keyword arguments to `gloo.set_state`.
        """
        for v in self._subvisuals:
            v.set_gl_state(preset=preset, **kwargs)

    def update_gl_state(self, *args, **kwargs):
        """Modify the set of GL state parameters to use when drawing

        Parameters
        ----------
        *args : tuple
            Arguments.
        **kwargs : dict
            Keyword argments.
        """
        for v in self._subvisuals:
            v.update_gl_state(*args, **kwargs)

    def attach(self, filt, view=None):
        """Attach a Filter to this visual

        Each filter modifies the appearance or behavior of the visual.

        Parameters
        ----------
        filt : object
            The filter to attach.
        view : instance of VisualView | None
            The view to use.
        """
        for v in self._subvisuals:
            v.attach(filt, v)

    def detach(self, filt, view=None):
        """Detach a filter.

        Parameters
        ----------
        filt : object
            The filter to detach.
        view : instance of VisualView | None
            The view to use.
        """
        for v in self._subvisuals:
            v.detach(filt, v)

    def _compute_bounds(self, axis, view):
        bounds = None
        for v in view._subvisuals:
            if v.visible:
                vb = v.bounds(axis)
                if bounds is None:
                    bounds = vb
                elif vb is not None:
                    bounds = [min(bounds[0], vb[0]), max(bounds[1], vb[1])]
        return bounds


class CompoundVisualView(BaseVisualView, CompoundVisual):
    def __init__(self, visual):
        BaseVisualView.__init__(self, visual)
        # Create a view on each sub-visual
        subv = [v.view() for v in visual._subvisuals]
        CompoundVisual.__init__(self, subv)

        # Attach any shared filters
        for filt in self._vshare.filters:
            for v in self._subvisuals:
                filt._attach(v)