INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Translate by an offset ( x y z ).
def translate(offset, dtype=None): """Translate by an offset (x, y, z) . Parameters ---------- offset : array-like, shape (3,) Translation in x, y, z. dtype : dtype | None Output type (if None, don't cast). Returns ------- M : ndarray Transformation matrix descr...
Non - uniform scaling along the x y and z axes
def scale(s, dtype=None): """Non-uniform scaling along the x, y, and z axes Parameters ---------- s : array-like, shape (3,) Scaling in x, y, z. dtype : dtype | None Output type (if None, don't cast). Returns ------- M : ndarray Transformation matrix describing ...
The 3x3 rotation matrix for rotation about a vector.
def rotate(angle, axis, dtype=None): """The 3x3 rotation matrix for rotation about a vector. Parameters ---------- angle : float The angle of rotation, in degrees. axis : ndarray The x, y, z coordinates of the axis direction vector. """ angle = np.radians(angle) assert l...
Create perspective projection matrix
def perspective(fovy, aspect, znear, zfar): """Create perspective projection matrix Parameters ---------- fovy : float The field of view along the y axis. aspect : float Aspect ratio of the view. znear : float Near coordinate of the field of view. zfar : float ...
Find a 3D transformation matrix that maps points1 onto points2.
def affine_map(points1, points2): """ Find a 3D transformation matrix that maps points1 onto points2. Arguments are specified as arrays of four 3D coordinates, shape (4, 3). """ A = np.ones((4, 4)) A[:, :3] = points1 B = np.ones((4, 4)) B[:, :3] = points2 # solve 3 sets of linear equat...
Add a final message ; flush the message list if no parent profiler.
def finish(self, msg=None): """Add a final message; flush the message list if no parent profiler. """ if self._finished or self.disable: return self._finished = True if msg is not None: self(msg) self._new_msg("< Exiting %s, total time: %0....
Create global Config object parse command flags
def _init(): """ Create global Config object, parse command flags """ global config, _data_path, _allowed_config_keys app_dir = _get_vispy_app_dir() if app_dir is not None: _data_path = op.join(app_dir, 'data') _test_data_path = op.join(app_dir, 'test_data') else: _data_...
Transform vispy specific command line args to vispy config. Put into a function so that any variables dont leak in the vispy namespace.
def _parse_command_line_arguments(): """ Transform vispy specific command line args to vispy config. Put into a function so that any variables dont leak in the vispy namespace. """ global config # Get command line args for vispy argnames = ['vispy-backend=', 'vispy-gl-debug', 'vispy-glir-file=',...
Helper to get the default directory for storing vispy data
def _get_vispy_app_dir(): """Helper to get the default directory for storing vispy data""" # Define default user directory user_dir = os.path.expanduser('~') # Get system app data dir path = None if sys.platform.startswith('win'): path1, path2 = os.getenv('LOCALAPPDATA'), os.getenv('APP...
Helper for the vispy config file
def _get_config_fname(): """Helper for the vispy config file""" directory = _get_vispy_app_dir() if directory is None: return None fname = op.join(directory, 'vispy.json') if os.environ.get('_VISPY_CONFIG_TESTING', None) is not None: fname = op.join(_TempDir(), 'vispy.json') retu...
Helper to load prefs from ~/. vispy/ vispy. json
def _load_config(): """Helper to load prefs from ~/.vispy/vispy.json""" fname = _get_config_fname() if fname is None or not op.isfile(fname): return dict() with open(fname, 'r') as fid: config = json.load(fid) return config
Save configuration keys to vispy config file
def save_config(**kwargs): """Save configuration keys to vispy config file Parameters ---------- **kwargs : keyword arguments Key/value pairs to save to the config file. """ if kwargs == {}: kwargs = config._config current_config = _load_config() current_config.update(**...
Set vispy data download directory
def set_data_dir(directory=None, create=False, save=False): """Set vispy data download directory Parameters ---------- directory : str | None The directory to use. create : bool If True, create directory if it doesn't exist. save : bool If True, save the configuration to...
Start profiling and register callback to print stats when the program exits.
def _enable_profiling(): """ Start profiling and register callback to print stats when the program exits. """ import cProfile import atexit global _profiler _profiler = cProfile.Profile() _profiler.enable() atexit.register(_profile_atexit)
Get relevant system and debugging information
def sys_info(fname=None, overwrite=False): """Get relevant system and debugging information Parameters ---------- fname : str | None Filename to dump info to. Use None to simply print. overwrite : bool If True, overwrite file (if it exists). Returns ------- out : str ...
Compact vertices and indices within given tolerance
def compact(vertices, indices, tolerance=1e-3): """ Compact vertices and indices within given tolerance """ # Transform vertices into a structured array for np.unique to work n = len(vertices) V = np.zeros(n, dtype=[("pos", np.float32, 3)]) V["pos"][:, 0] = vertices[:, 0] V["pos"][:, 1] = verti...
Compute normals over a triangulated surface
def normals(vertices, indices): """ Compute normals over a triangulated surface Parameters ---------- vertices : ndarray (n,3) triangles vertices indices : ndarray (p,3) triangles indices """ # Compact similar vertices vertices, indices, mapping = compact(vertices...
Create the native widget if not already done so. If the widget is already created this function does nothing.
def create_native(self): """ Create the native widget if not already done so. If the widget is already created, this function does nothing. """ if self._backend is not None: return # Make sure that the app is active assert self._app.native # Instantiat...
Connect a function to an event
def connect(self, fun): """ Connect a function to an event The name of the function should be on_X, with X the name of the event (e.g. 'on_draw'). This method is typically used as a decorator on a function definition for an event handler. Parameters ---------- ...
The size of canvas/ window
def size(self): """ The size of canvas/window """ size = self._backend._vispy_get_size() return (size[0] // self._px_scale, size[1] // self._px_scale)
Show or hide the canvas
def show(self, visible=True, run=False): """Show or hide the canvas Parameters ---------- visible : bool Make the canvas visible. run : bool Run the backend event loop. """ self._backend._vispy_set_visible(visible) if run: ...
Close the canvas
def close(self): """Close the canvas Notes ----- This will usually destroy the GL context. For Qt, the context (and widget) will be destroyed only if the widget is top-level. To avoid having the widget destroyed (more like standard Qt behavior), consider making t...
Update the fps after every window
def _update_fps(self, event): """Update the fps after every window""" self._frame_count += 1 diff = time() - self._basetime if (diff > self._fps_window): self._fps = self._frame_count / diff self._basetime = time() self._frame_count = 0 sel...
Measure the current FPS
def measure_fps(self, window=1, callback='%1.1f FPS'): """Measure the current FPS Sets the update window, connects the draw event to update_fps and sets the callback function. Parameters ---------- window : float The time-window (in seconds) to calculate FPS...
Render the canvas to an offscreen buffer and return the image array.
def render(self): """ Render the canvas to an offscreen buffer and return the image array. Returns ------- image : array Numpy array of type ubyte and shape (h, w, 4). Index [0, 0] is the upper-left corner of the rendered region. """ ...
Return a list of all mouse events in the current drag operation.
def drag_events(self): """ Return a list of all mouse events in the current drag operation. Returns None if there is no current drag operation. """ if not self.is_dragging: return None event = self events = [] while True: # mouse_press ev...
Return an ( N 2 ) array of mouse coordinates for every event in the current mouse drag operation.
def trail(self): """ Return an (N, 2) array of mouse coordinates for every event in the current mouse drag operation. Returns None if there is no current drag operation. """ events = self.drag_events() if events is None: return None trail = np.empty(...
Set the minimum height of the widget
def width_min(self, width_min): """Set the minimum height of the widget Parameters ---------- height_min: float the minimum height of the widget """ if width_min is None: self._width_limits[0] = 0 return width_min = float(wi...
Set the maximum width of the widget.
def width_max(self, width_max): """Set the maximum width of the widget. Parameters ---------- width_max: None | float the maximum width of the widget. if None, maximum width is unbounded """ if width_max is None: self._width_limits[1] ...
Set the minimum height of the widget
def height_min(self, height_min): """Set the minimum height of the widget Parameters ---------- height_min: float the minimum height of the widget """ if height_min is None: self._height_limits[0] = 0 return height_min = floa...
Set the maximum height of the widget.
def height_max(self, height_max): """Set the maximum height of the widget. Parameters ---------- height_max: None | float the maximum height of the widget. if None, maximum height is unbounded """ if height_max is None: self._height_li...
The rectangular area inside the margin border and padding.
def inner_rect(self): """The rectangular area inside the margin, border, and padding. Generally widgets should avoid drawing or placing sub-widgets outside this rectangle. """ m = self.margin + self._border_width + self.padding if not self.border_color.is_blank: ...
Called whenever the clipper for this widget may need to be updated.
def _update_clipper(self): """Called whenever the clipper for this widget may need to be updated. """ if self.clip_children and self._clipper is None: self._clipper = Clipper() elif not self.clip_children: self._clipper = None if self._clipper is None: ...
Update border line to match new shape
def _update_line(self): """ Update border line to match new shape """ w = self._border_width m = self.margin # border is drawn within the boundaries of the widget: # # size = (8, 7) margin=2 # internal rect = (3, 3, 2, 1) # ........ # ...........
Add a Widget as a managed child of this Widget.
def add_widget(self, widget): """ Add a Widget as a managed child of this Widget. The child will be automatically positioned and sized to fill the entire space inside this Widget (unless _update_child_widgets is redefined). Parameters ---------- widget :...
Create a new Grid and add it as a child widget.
def add_grid(self, *args, **kwargs): """ Create a new Grid and add it as a child widget. All arguments are given to Grid(). """ from .grid import Grid grid = Grid(*args, **kwargs) return self.add_widget(grid)
Create a new ViewBox and add it as a child widget.
def add_view(self, *args, **kwargs): """ Create a new ViewBox and add it as a child widget. All arguments are given to ViewBox(). """ from .viewbox import ViewBox view = ViewBox(*args, **kwargs) return self.add_widget(view)
Remove a Widget as a managed child of this Widget.
def remove_widget(self, widget): """ Remove a Widget as a managed child of this Widget. Parameters ---------- widget : instance of Widget The widget to remove. """ self._widgets.remove(widget) widget.parent = None self._update_child_wi...
Packs float values between [ 0 1 ] into 4 unsigned int8
def pack_unit(value): """Packs float values between [0,1] into 4 unsigned int8 Returns ------- pack: array packed interpolation kernel """ pack = np.zeros(value.shape + (4,), dtype=np.ubyte) for i in range(4): value, pack[..., i] = np.modf(value * 256.) return pack
Packs float ieee binary representation into 4 unsigned int8
def pack_ieee(value): """Packs float ieee binary representation into 4 unsigned int8 Returns ------- pack: array packed interpolation kernel """ return np.fromstring(value.tostring(), np.ubyte).reshape((value.shape + (4,)))
Load spatial - filters kernel
def load_spatial_filters(packed=True): """Load spatial-filters kernel Parameters ---------- packed : bool Whether or not the data should be in "packed" representation for use in GLSL code. Returns ------- kernel : array 16x1024x4 (packed float in rgba) or 16...
List system fonts
def list_fonts(): """List system fonts Returns ------- fonts : list of str List of system fonts. """ vals = _list_fonts() for font in _vispy_fonts: vals += [font] if font not in vals else [] vals = sorted(vals, key=lambda s: s.lower()) return vals
A decorator ensuring that the decorated function tun time does not exceeds the argument limit.
def timeout(limit, handler): """A decorator ensuring that the decorated function tun time does not exceeds the argument limit. :args limit: the time limit :type limit: int :args handler: the handler function called when the decorated function times out. :type handler: callable Example...
Simple utility to retrieve kwargs in predetermined order. Also checks whether the values of the backend arguments do not violate the backend capabilities.
def _process_backend_kwargs(self, kwargs): """ Simple utility to retrieve kwargs in predetermined order. Also checks whether the values of the backend arguments do not violate the backend capabilities. """ # Verify given argument with capability of the backend app = self....
Reset the view.
def _set_range(self, init): """ Reset the view. """ #PerspectiveCamera._set_range(self, init) # Stop moving self._speed *= 0.0 # Get window size (and store factor now to sync with resizing) w, h = self._viewbox.size w, h = float(w), float(h) # ...
Timer event handler
def on_timer(self, event): """Timer event handler Parameters ---------- event : instance of Event The event. """ # Set relative speed and acceleration rel_speed = event.dt rel_acc = 0.1 # Get what's forward pf, pr, pl, pu = s...
ViewBox key event handler
def viewbox_key_event(self, event): """ViewBox key event handler Parameters ---------- event : instance of Event The event. """ PerspectiveCamera.viewbox_key_event(self, event) if event.handled or not self.interactive: return # E...
ViewBox mouse event handler
def viewbox_mouse_event(self, event): """ViewBox mouse event handler Parameters ---------- event : instance of Event The event. """ PerspectiveCamera.viewbox_mouse_event(self, event) if event.handled or not self.interactive: return ...
Return True if there s something to read on stdin ( posix version ).
def _stdin_ready_posix(): """Return True if there's something to read on stdin (posix version).""" infds, outfds, erfds = select.select([sys.stdin],[],[],0) return bool(infds)
Set PyOS_InputHook to callback and return the previous one.
def set_inputhook(self, callback): """Set PyOS_InputHook to callback and return the previous one.""" # On platforms with 'readline' support, it's all too likely to # have a KeyboardInterrupt signal delivered *even before* an # initial ``try:`` clause in the callback can be executed, so ...
Set PyOS_InputHook to NULL and return the previous one.
def clear_inputhook(self, app=None): """Set PyOS_InputHook to NULL and return the previous one. Parameters ---------- app : optional, ignored This parameter is allowed only so that clear_inputhook() can be called with a similar interface as all the ``enable_*`` metho...
Clear IPython s internal reference to an application instance.
def clear_app_refs(self, gui=None): """Clear IPython's internal reference to an application instance. Whenever we create an app for a user on qt4 or wx, we hold a reference to the app. This is needed because in some cases bad things can happen if a user doesn't hold a reference themsel...
Register a class to provide the event loop for a given GUI. This is intended to be used as a class decorator. It should be passed the names with which to register this GUI integration. The classes themselves should subclass: class: InputHookBase.::
def register(self, toolkitname, *aliases): """Register a class to provide the event loop for a given GUI. This is intended to be used as a class decorator. It should be passed the names with which to register this GUI integration. The classes themselves should subclass :class:`I...
Switch amongst GUI input hooks by name.
def enable_gui(self, gui=None, app=None): """Switch amongst GUI input hooks by name. This is a higher level method than :meth:`set_inputhook` - it uses the GUI name to look up a registered object which enables the input hook for that GUI. Parameters ---------- g...
Disable GUI event loop integration. If an application was registered this sets its _in_event_loop attribute to False. It then calls: meth: clear_inputhook.
def disable_gui(self): """Disable GUI event loop integration. If an application was registered, this sets its ``_in_event_loop`` attribute to False. It then calls :meth:`clear_inputhook`. """ gui = self._current_gui if gui in self.apps: self.apps[gui]...
Make a canvas active. Used primarily by the canvas itself.
def set_current_canvas(canvas): """ Make a canvas active. Used primarily by the canvas itself. """ # Notify glir canvas.context._do_CURRENT_command = True # Try to be quick if canvasses and canvasses[-1]() is canvas: return # Make this the current cc = [c() for c in canvasses if...
Forget about the given canvas. Used by the canvas when closed.
def forget_canvas(canvas): """ Forget about the given canvas. Used by the canvas when closed. """ cc = [c() for c in canvasses if c() is not None] while canvas in cc: cc.remove(canvas) canvasses[:] = [weakref.ref(c) for c in cc]
For the app backends to create the GLShared object.
def create_shared(self, name, ref): """ For the app backends to create the GLShared object. Parameters ---------- name : str The name. ref : object The reference. """ if self._shared is not None: raise RuntimeError('Can only se...
Flush
def flush_commands(self, event=None): """ Flush Parameters ---------- event : instance of Event The event. """ if self._do_CURRENT_command: self._do_CURRENT_command = False canvas = get_current_canvas() if canvas and hasatt...
Add a reference for the backend object that gives access to the low level context. Used in vispy. app. canvas. backends. The given name must match with that of previously added references.
def add_ref(self, name, ref): """ Add a reference for the backend object that gives access to the low level context. Used in vispy.app.canvas.backends. The given name must match with that of previously added references. """ if self._name is None: self._name = ...
A reference ( stored internally via a weakref ) to an object that the backend system can use to obtain the low - level information of the reference context. In Vispy this will typically be the CanvasBackend object.
def ref(self): """ A reference (stored internally via a weakref) to an object that the backend system can use to obtain the low-level information of the "reference context". In Vispy this will typically be the CanvasBackend object. """ # Clean self._refs = [r for ...
Get screen DPI from the OS
def get_dpi(raise_error=True): """Get screen DPI from the OS Parameters ---------- raise_error : bool If True, raise an error if DPI could not be determined. Returns ------- dpi : float Dots per inch of the primary screen. """ display = quartz.CGMainDisplayID() ...
Link this Varying to another object from which it will derive its dtype. This method is used internally when assigning an attribute to a varying using syntax Function [ varying ] = attr.
def link(self, var): """ Link this Varying to another object from which it will derive its dtype. This method is used internally when assigning an attribute to a varying using syntax ``Function[varying] = attr``. """ assert self._dtype is not None or hasattr(var, 'dtype') ...
Two Dimensional Shubert Function
def obj(x): """Two Dimensional Shubert Function""" j = np.arange(1, 6) tmp1 = np.dot(j, np.cos((j+1)*x[0] + j)) tmp2 = np.dot(j, np.cos((j+1)*x[1] + j)) return tmp1 * tmp2
Function BESJ calculates Bessel function of first kind of order n Arguments: n - an integer ( > = 0 ) the order x - value at which the Bessel function is required -------------------- C ++ Mathematical Library Converted from equivalent FORTRAN library Converted by Gareth Walker for use by course 392 computational proje...
def besj(self, x, n): ''' Function BESJ calculates Bessel function of first kind of order n Arguments: n - an integer (>=0), the order x - value at which the Bessel function is required -------------------- C++ Mathematical Library Converted from e...
Create an exact copy of this quaternion.
def copy(self): """ Create an exact copy of this quaternion. """ return Quaternion(self.w, self.x, self.y, self.z, False)
Returns the norm of the quaternion norm = w ** 2 + x ** 2 + y ** 2 + z ** 2
def norm(self): """ Returns the norm of the quaternion norm = w**2 + x**2 + y**2 + z**2 """ tmp = self.w**2 + self.x**2 + self.y**2 + self.z**2 return tmp**0.5
Make the quaternion unit length.
def _normalize(self): """ Make the quaternion unit length. """ # Get length L = self.norm() if not L: raise ValueError('Quaternion cannot have 0-length.') # Correct self.w /= L self.x /= L self.y /= L self.z /= L
Obtain the conjugate of the quaternion. This is simply the same quaternion but with the sign of the imaginary ( vector ) parts reversed.
def conjugate(self): """ Obtain the conjugate of the quaternion. This is simply the same quaternion but with the sign of the imaginary (vector) parts reversed. """ new = self.copy() new.x *= -1 new.y *= -1 new.z *= -1 return new
returns q. conjugate ()/ q. norm () ** 2 So if the quaternion is unit length it is the same as the conjugate.
def inverse(self): """ returns q.conjugate()/q.norm()**2 So if the quaternion is unit length, it is the same as the conjugate. """ new = self.conjugate() tmp = self.norm()**2 new.w /= tmp new.x /= tmp new.y /= tmp new.z /= tmp ...
Returns the exponent of the quaternion. ( not tested )
def exp(self): """ Returns the exponent of the quaternion. (not tested) """ # Init vecNorm = self.x**2 + self.y**2 + self.z**2 wPart = np.exp(self.w) q = Quaternion() # Calculate q.w = wPart * np.cos(vecNorm) q.x ...
Returns the natural logarithm of the quaternion. ( not tested )
def log(self): """ Returns the natural logarithm of the quaternion. (not tested) """ # Init norm = self.norm() vecNorm = self.x**2 + self.y**2 + self.z**2 tmp = self.w / norm q = Quaternion() # Calculate q.w = np.log(norm...
Rotate a Point instance using this quaternion.
def rotate_point(self, p): """ Rotate a Point instance using this quaternion. """ # Prepare p = Quaternion(0, p[0], p[1], p[2], False) # Do not normalize! q1 = self.normalize() q2 = self.inverse() # Apply rotation r = (q1*p)*q2 # Make point and r...
Create a 4x4 homography matrix that represents the rotation of the quaternion.
def get_matrix(self): """ Create a 4x4 homography matrix that represents the rotation of the quaternion. """ # Init matrix (remember, a matrix, not an array) a = np.zeros((4, 4), dtype=np.float32) w, x, y, z = self.w, self.x, self.y, self.z # First row a[0...
Get the axis - angle representation of the quaternion. ( The angle is in radians )
def get_axis_angle(self): """ Get the axis-angle representation of the quaternion. (The angle is in radians) """ # Init angle = 2 * np.arccos(max(min(self.w, 1.), -1.)) scale = (self.x**2 + self.y**2 + self.z**2)**0.5 # Calc axis if scale: ...
Classmethod to create a quaternion from an axis - angle representation. ( angle should be in radians ).
def create_from_axis_angle(cls, angle, ax, ay, az, degrees=False): """ Classmethod to create a quaternion from an axis-angle representation. (angle should be in radians). """ if degrees: angle = np.radians(angle) while angle < 0: angle += np.pi*2 ...
Classmethod to create a quaternion given the euler angles.
def create_from_euler_angles(cls, rx, ry, rz, degrees=False): """ Classmethod to create a quaternion given the euler angles. """ if degrees: rx, ry, rz = np.radians([rx, ry, rz]) # Obtain quaternions qx = Quaternion(np.cos(rx/2), 0, 0, np.sin(rx/2)) qy = Quate...
Turn a possibly string enum into an integer enum.
def as_enum(enum): """ Turn a possibly string enum into an integer enum. """ if isinstance(enum, string_types): try: enum = getattr(gl, 'GL_' + enum.upper()) except AttributeError: try: enum = _internalformats['GL_' + enum.upper()] except K...
Modify shading code so that we can write code once and make it run everywhere.
def convert_shaders(convert, shaders): """ Modify shading code so that we can write code once and make it run "everywhere". """ # New version of the shaders out = [] if convert == 'es2': for isfragment, shader in enumerate(shaders): has_version = False has_prec...
Modify a desktop command so it works on es2.
def as_es2_command(command): """ Modify a desktop command so it works on es2. """ if command[0] == 'FUNC': return (command[0], re.sub(r'^gl([A-Z])', lambda m: m.group(1).lower(), command[1])) + command[2:] if command[0] == 'SHADERS': return command[:2] + convert_shaders(...
Helper to ensure users have OpenGL for 3D texture support ( for now )
def _check_pyopengl_3D(): """Helper to ensure users have OpenGL for 3D texture support (for now)""" global USE_TEX_3D USE_TEX_3D = True try: import OpenGL.GL as _gl except ImportError: raise ImportError('PyOpenGL is required for 3D texture support') return _gl
Print the list of commands currently in the queue. If filter is given print only commands that match the filter.
def show(self, filter=None): """ Print the list of commands currently in the queue. If filter is given, print only commands that match the filter. """ for command in self._commands: if command[0] is None: # or command[1] in self._invalid_objects: continue # ...
Flush all current commands to the GLIR interpreter.
def flush(self, parser): """ Flush all current commands to the GLIR interpreter. """ if self._verbose: show = self._verbose if isinstance(self._verbose, str) else None self.show(show) parser.parse(self._filter(self.clear(), parser))
Filter DATA/ SIZE commands that are overridden by a SIZE command.
def _filter(self, commands, parser): """ Filter DATA/SIZE commands that are overridden by a SIZE command. """ resized = set() commands2 = [] for command in reversed(commands): if command[0] == 'SHADERS': convert = parser.convert_shaders() ...
Merge this queue with another.
def associate(self, queue): """Merge this queue with another. Both queues will use a shared command list and either one can be used to fill or flush the shared queue. """ assert isinstance(queue, GlirQueue) if queue._shared is self._shared: return # ...
Parse a single command.
def _parse(self, command): """ Parse a single command. """ cmd, id_, args = command[0], command[1], command[2:] if cmd == 'CURRENT': # This context is made current self.env.clear() self._gl_initialize() self.env['fbo'] = args[0] ...
Parse a list of commands.
def parse(self, commands): """ Parse a list of commands. """ # Get rid of dummy objects that represented deleted objects in # the last parsing round. to_delete = [] for id_, val in self._objects.items(): if val == JUST_DELETED: to_delete.appen...
Deal with compatibility ; desktop does not have sprites enabled by default. ES has.
def _gl_initialize(self): """ Deal with compatibility; desktop does not have sprites enabled by default. ES has. """ if '.es' in gl.current_backend.__name__: pass # ES2: no action required else: # Desktop, enable sprites GL_VERTEX_PROGRAM_POIN...
Avoid overhead in calling glUseProgram with same arg. Warning: this will break if glUseProgram is used somewhere else. Per context we keep track of one current program.
def activate(self): """ Avoid overhead in calling glUseProgram with same arg. Warning: this will break if glUseProgram is used somewhere else. Per context we keep track of one current program. """ if self._handle != self._parser.env.get('current_program', False): self...
Avoid overhead in calling glUseProgram with same arg. Warning: this will break if glUseProgram is used somewhere else. Per context we keep track of one current program.
def deactivate(self): """ Avoid overhead in calling glUseProgram with same arg. Warning: this will break if glUseProgram is used somewhere else. Per context we keep track of one current program. """ if self._parser.env.get('current_program', 0) != 0: self._parser.env[...
This function takes care of setting the shading code and compiling + linking it into a working program object that is ready to use.
def set_shaders(self, vert, frag): """ This function takes care of setting the shading code and compiling+linking it into a working program object that is ready to use. """ self._linked = False # Create temporary shader objects vert_handle = gl.glCreateShader(gl.G...
Retrieve active attributes and uniforms to be able to check that all uniforms/ attributes are set by the user. Other GLIR implementations may omit this.
def _get_active_attributes_and_uniforms(self): """ Retrieve active attributes and uniforms to be able to check that all uniforms/attributes are set by the user. Other GLIR implementations may omit this. """ # This match a name of the form "name[size]" (= array) regex = re...
Parses a single GLSL error and extracts the linenr and description Other GLIR implementations may omit this.
def _parse_error(self, error): """ Parses a single GLSL error and extracts the linenr and description Other GLIR implementations may omit this. """ error = str(error) # Nvidia # 0(7): error C1008: undefined variable "MV" m = re.match(r'(\d+)\((\d+)\)\s*:\s(.*)', e...
Get error and show the faulty line + some context Other GLIR implementations may omit this.
def _get_error(self, code, errors, indentation=0): """Get error and show the faulty line + some context Other GLIR implementations may omit this. """ # Init results = [] lines = None if code is not None: lines = [line.strip() for line in code.split('\n...
Set a texture sampler. Value is the id of the texture to link.
def set_texture(self, name, value): """ Set a texture sampler. Value is the id of the texture to link. """ if not self._linked: raise RuntimeError('Cannot set uniform when program has no code') # Get handle for the uniform, first try cache handle = self._handles.get(n...
Set a uniform value. Value is assumed to have been checked.
def set_uniform(self, name, type_, value): """ Set a uniform value. Value is assumed to have been checked. """ if not self._linked: raise RuntimeError('Cannot set uniform when program has no code') # Get handle for the uniform, first try cache handle = self._handles.g...
Set an attribute value. Value is assumed to have been checked.
def set_attribute(self, name, type_, value): """ Set an attribute value. Value is assumed to have been checked. """ if not self._linked: raise RuntimeError('Cannot set attribute when program has no code') # Get handle for the attribute, first try cache handle = self._...
Draw program in given mode with given selection ( IndexBuffer or first count ).
def draw(self, mode, selection): """ Draw program in given mode, with given selection (IndexBuffer or first, count). """ if not self._linked: raise RuntimeError('Cannot draw program if code has not been set') # Init gl.check_error('Check before draw') ...
Simplify a transform to a single matrix transform which makes it a lot faster to compute transformations.
def as_matrix_transform(transform): """ Simplify a transform to a single matrix transform, which makes it a lot faster to compute transformations. Raises a TypeError if the transform cannot be simplified. """ if isinstance(transform, ChainTransform): matrix = np.identity(4) for ...
Places all nodes on a single circle.
def circular(adjacency_mat, directed=False): """Places all nodes on a single circle. Parameters ---------- adjacency_mat : matrix or sparse The graph adjacency matrix directed : bool Whether the graph is directed. If this is True, is will also generate the vertices for arrow...