INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Append a new set of vertices to the collection. | def append(self, P, closed=False, itemsize=None, **kwargs):
"""
Append a new set of vertices to the collection.
For kwargs argument, n is the number of vertices (local) or the number
of item (shared)
Parameters
----------
P : np.array
Vertices posit... |
Draw collection | def draw(self, mode="triangles"):
""" Draw collection """
gl.glDepthMask(0)
Collection.draw(self, mode)
gl.glDepthMask(1) |
Set the data used to display this visual. | def set_data(self, pos=None, symbol='o', size=10., edge_width=1.,
edge_width_rel=None, edge_color='black', face_color='white',
scaling=False):
""" Set the data used to display this visual.
Parameters
----------
pos : array
The array of locat... |
Handle a hook upate. | def hook_changed(self, hook_name, widget, new_data):
"""Handle a hook upate."""
if hook_name == 'song':
self.song_changed(widget, new_data)
elif hook_name == 'state':
self.state_changed(widget, new_data)
elif hook_name == 'elapsed_and_total':
elapsed, ... |
Update the signature of func with the data in self | def update(self, func, **kw):
"Update the signature of func with the data in self"
func.__name__ = self.name
func.__doc__ = getattr(self, 'doc', None)
func.__dict__ = getattr(self, 'dict', {})
func.__defaults__ = getattr(self, 'defaults', ())
func.__kwdefaults__ = getattr... |
Make a new function from a given template and update the signature | def make(self, src_templ, evaldict=None, addsource=False, **attrs):
"Make a new function from a given template and update the signature"
src = src_templ % vars(self) # expand name and signature
evaldict = evaldict or {}
mo = DEF.match(src)
if mo is None:
raise SyntaxE... |
Create a function from the strings name signature and body. evaldict is the evaluation dictionary. If addsource is true an attribute __source__ is added to the result. The attributes attrs are added if any. | def create(cls, obj, body, evaldict, defaults=None,
doc=None, module=None, addsource=True, **attrs):
"""
Create a function from the strings name, signature and body.
evaldict is the evaluation dictionary. If addsource is true an attribute
__source__ is added to the result.... |
Set the scalar array data | def set_data(self, data=None, vertex_colors=None, face_colors=None,
color=None):
""" Set the scalar array data
Parameters
----------
data : ndarray
A 3D array of scalar values. The isosurface is constructed to show
all locations in the scalar fie... |
Get the total bounds based on the visuals present in the scene | def get_scene_bounds(self, dim=None):
"""Get the total bounds based on the visuals present in the scene
Parameters
----------
dim : int | None
Dimension to return.
Returns
-------
bounds : list | tuple
If ``dim is None``, Returns a list o... |
Convert user string or hex color to color array ( length 3 or 4 ) | def _string_to_rgb(color):
"""Convert user string or hex color to color array (length 3 or 4)"""
if not color.startswith('#'):
if color.lower() not in _color_dict:
raise ValueError('Color "%s" unknown' % color)
color = _color_dict[color]
assert color[0] == '#'
# hex color... |
Convert color ( s ) from any set of fmts ( str/ hex/ arr ) to RGB ( A ) array | def _user_to_rgba(color, expand=True, clip=False):
"""Convert color(s) from any set of fmts (str/hex/arr) to RGB(A) array"""
if color is None:
color = np.zeros(4, np.float32)
if isinstance(color, string_types):
color = _string_to_rgb(color)
elif isinstance(color, ColorArray):
col... |
Helper to turn val into array and clip between 0 and 1 | def _array_clip_val(val):
"""Helper to turn val into array and clip between 0 and 1"""
val = np.array(val)
if val.max() > 1 or val.min() < 0:
logger.warning('value will be clipped between 0 and 1')
val[...] = np.clip(val, 0, 1)
return val |
Extend a ColorArray with new colors | def extend(self, colors):
"""Extend a ColorArray with new colors
Parameters
----------
colors : instance of ColorArray
The new colors.
"""
colors = ColorArray(colors)
self._rgba = np.vstack((self._rgba, colors._rgba))
return self |
Set the color using an Nx4 array of RGBA floats | def rgba(self, val):
"""Set the color using an Nx4 array of RGBA floats"""
# Note: all other attribute sets get routed here!
# This method is meant to do the heavy lifting of setting data
rgba = _user_to_rgba(val, expand=False)
if self._rgba is None:
self._rgba = rgba... |
Set the color using an Nx4 array of RGBA uint8 values | def RGBA(self, val):
"""Set the color using an Nx4 array of RGBA uint8 values"""
# need to convert to normalized float
val = np.atleast_1d(val).astype(np.float32) / 255
self.rgba = val |
Set the color using an Nx3 array of RGB uint8 values | def RGB(self, val):
"""Set the color using an Nx3 array of RGB uint8 values"""
# need to convert to normalized float
val = np.atleast_1d(val).astype(np.float32) / 255.
self.rgba = val |
Set the color using length - N array of ( from HSV ) | def value(self, val):
"""Set the color using length-N array of (from HSV)"""
hsv = self._hsv
hsv[:, 2] = _array_clip_val(val)
self.rgba = _hsv_to_rgb(hsv) |
Produce a lighter color ( if possible ) | def lighter(self, dv=0.1, copy=True):
"""Produce a lighter color (if possible)
Parameters
----------
dv : float
Amount to increase the color value by.
copy : bool
If False, operation will be carried out in-place.
Returns
-------
c... |
Produce a darker color ( if possible ) | def darker(self, dv=0.1, copy=True):
"""Produce a darker color (if possible)
Parameters
----------
dv : float
Amount to decrease the color value by.
copy : bool
If False, operation will be carried out in-place.
Returns
-------
col... |
The ViewBox received a mouse event ; update transform accordingly. Default implementation adjusts scale factor when scolling. | def viewbox_mouse_event(self, event):
""" The ViewBox received a mouse event; update transform
accordingly.
Default implementation adjusts scale factor when scolling.
Parameters
----------
event : instance of Event
The event.
"""
BaseCamera.vi... |
Reset the camera view using the known limits. | def _set_range(self, init):
""" Reset the camera view using the known limits.
"""
if init and (self._scale_factor is not None):
return # We don't have to set our scale factor
# Get window size (and store factor now to sync with resizing)
w, h = self._viewbox.size
... |
The viewbox received a mouse event ; update transform accordingly. | def viewbox_mouse_event(self, event):
"""
The viewbox received a mouse event; update transform
accordingly.
Parameters
----------
event : instance of Event
The event.
"""
if event.handled or not self.interactive:
return
Pe... |
Set the camera position and orientation | def _update_camera_pos(self):
""" Set the camera position and orientation"""
# transform will be updated several times; do not update camera
# transform until we are done.
ch_em = self.events.transform_change
with ch_em.blocker(self._update_transform):
tr = self.tran... |
Determine if the user requested interactive mode. | def is_interactive(self):
""" Determine if the user requested interactive mode.
"""
# The Python interpreter sets sys.flags correctly, so use them!
if sys.flags.interactive:
return True
# IPython does not set sys.flags when -i is specified, so first
# check i... |
Enter the native GUI event loop. | def run(self, allow_interactive=True):
""" Enter the native GUI event loop.
Parameters
----------
allow_interactive : bool
Is the application allowed to handle interactive mode for console
terminals? By default, typing ``python -i main.py`` results in
... |
Select a backend by name. See class docstring for details. | def _use(self, backend_name=None):
"""Select a backend by name. See class docstring for details.
"""
# See if we're in a specific testing mode, if so DONT check to see
# if it's a valid backend. If it isn't, it's a good thing we
# get an error later because we should have decorat... |
Set gl configuration | def _set_config(c):
"""Set gl configuration"""
gl_attribs = [glcanvas.WX_GL_RGBA,
glcanvas.WX_GL_DEPTH_SIZE, c['depth_size'],
glcanvas.WX_GL_STENCIL_SIZE, c['stencil_size'],
glcanvas.WX_GL_MIN_RED, c['red_size'],
glcanvas.WX_GL_MIN_GREEN, c... |
Helper to extract list of mods from event | def _get_mods(evt):
"""Helper to extract list of mods from event"""
mods = []
mods += [keys.CONTROL] if evt.ControlDown() else []
mods += [keys.ALT] if evt.AltDown() else []
mods += [keys.SHIFT] if evt.ShiftDown() else []
mods += [keys.META] if evt.MetaDown() else []
return mods |
Helper to convert from wx keycode to vispy keycode | def _process_key(evt):
"""Helper to convert from wx keycode to vispy keycode"""
key = evt.GetKeyCode()
if key in KEYMAP:
return KEYMAP[key], ''
if 97 <= key <= 122:
key -= 32
if key >= 32 and key <= 127:
return keys.Key(chr(key)), chr(key)
else:
return None, None |
Check if a node is a child of the current node | def is_child(self, node):
"""Check if a node is a child of the current node
Parameters
----------
node : instance of Node
The potential child.
Returns
-------
child : bool
Whether or not the node is a child.
"""
if node in... |
The first ancestor of this node that is a SubScene instance or self if no such node exists. | def scene_node(self):
"""The first ancestor of this node that is a SubScene instance, or self
if no such node exists.
"""
if self._scene_node is None:
from .subscene import SubScene
p = self.parent
while True:
if isinstance(p, SubScene)... |
Emit an event to inform listeners that properties of this Node have changed. Also request a canvas update. | def update(self):
"""
Emit an event to inform listeners that properties of this Node have
changed. Also request a canvas update.
"""
self.events.update()
c = getattr(self, 'canvas', None)
if c is not None:
c.update(node=self) |
Create a new transform of * type * and assign it to this node. | def set_transform(self, type_, *args, **kwargs):
""" Create a new transform of *type* and assign it to this node.
All extra arguments are used in the construction of the transform.
Parameters
----------
type_ : str
The transform type.
*args : tuple
... |
Called when has changed. This allows the node and its children to react ( notably VisualNode uses this to update its TransformSystem ). Note that this method is only called when one transform is replaced by another ; it is not called if an existing transform internally changes its state. | def _update_trsys(self, event):
"""Called when has changed.
This allows the node and its children to react (notably, VisualNode
uses this to update its TransformSystem).
Note that this method is only called when one transform is replaced by
another; it is not c... |
Return the list of parents starting from this node. The chain ends at the first node with no parents. | def parent_chain(self):
"""
Return the list of parents starting from this node. The chain ends
at the first node with no parents.
"""
chain = [self]
while True:
try:
parent = chain[-1].parent
except Exception:
break
... |
Helper function to actuall construct the tree | def _describe_tree(self, prefix, with_transform):
"""Helper function to actuall construct the tree"""
extra = ': "%s"' % self.name if self.name is not None else ''
if with_transform:
extra += (' [%s]' % self.transform.__class__.__name__)
output = ''
if len(prefix) > 0... |
Return the common parent of two entities | def common_parent(self, node):
"""
Return the common parent of two entities
If the entities have no common parent, return None.
Parameters
----------
node : instance of Node
The other node.
Returns
-------
parent : instance of Node |... |
Return a list describing the path from this node to a child node | def node_path_to_child(self, node):
"""Return a list describing the path from this node to a child node
If *node* is not a (grand)child of this node, then raise RuntimeError.
Parameters
----------
node : instance of Node
The child node.
Returns
----... |
Return two lists describing the path from this node to another | def node_path(self, node):
"""Return two lists describing the path from this node to another
Parameters
----------
node : instance of Node
The other node.
Returns
-------
p1 : list
First path (see below).
p2 : list
Sec... |
Return the list of transforms along the path to another node. The transforms are listed in reverse order such that the last transform should be applied first when mapping from this node to the other. | def node_path_transforms(self, node):
"""Return the list of transforms along the path to another node.
The transforms are listed in reverse order, such that the last
transform should be applied first when mapping from this node to
the other.
Parameters
-------... |
read ( fname fmt ) | def read(cls, fname):
""" read(fname, fmt)
This classmethod is the entry point for reading OBJ files.
Parameters
----------
fname : str
The name of the file to read.
fmt : str
Can be "obj" or "gz" to specify the file format.
"""
#... |
The method that reads a line and processes it. | def readLine(self):
""" The method that reads a line and processes it.
"""
# Read line
line = self._f.readline().decode('ascii', 'ignore')
if not line:
raise EOFError()
line = line.strip()
if line.startswith('v '):
# self._vertices.append... |
Reads a tuple of numbers. e. g. vertices normals or teture coords. | def readTuple(self, line, n=3):
""" Reads a tuple of numbers. e.g. vertices, normals or teture coords.
"""
numbers = [num for num in line.split(' ') if num]
return [float(num) for num in numbers[1:n + 1]] |
Each face consists of three or more sets of indices. Each set consists of 1 2 or 3 indices to vertices/ normals/ texcords. | def readFace(self, line):
""" Each face consists of three or more sets of indices. Each set
consists of 1, 2 or 3 indices to vertices/normals/texcords.
"""
# Get parts (skip first)
indexSets = [num for num in line.split(' ') if num][1:]
final_face = []
for index... |
Converts gathere lists to numpy arrays and creates BaseMesh instance. | def finish(self):
""" Converts gathere lists to numpy arrays and creates
BaseMesh instance.
"""
self._vertices = np.array(self._vertices, 'float32')
if self._faces:
self._faces = np.array(self._faces, 'uint32')
else:
# Use vertices only
... |
This classmethod is the entry point for writing mesh data to OBJ. | def write(cls, fname, vertices, faces, normals,
texcoords, name='', reshape_faces=True):
""" This classmethod is the entry point for writing mesh data to OBJ.
Parameters
----------
fname : string
The filename to write to. Must end with ".obj" or ".gz".
... |
Writes a tuple of numbers ( on one line ). | def writeTuple(self, val, what):
""" Writes a tuple of numbers (on one line).
"""
# Limit to three values. so RGBA data drops the alpha channel
# Format can handle up to 3 texcords
val = val[:3]
# Make string
val = ' '.join([str(v) for v in val])
# Write l... |
Write the face info to the net line. | def writeFace(self, val, what='f'):
""" Write the face info to the net line.
"""
# OBJ counts from 1
val = [v + 1 for v in val]
# Make string
if self._hasValues and self._hasNormals:
val = ' '.join(['%i/%i/%i' % (v, v, v) for v in val])
elif self._hasN... |
Write the given mesh instance. | def writeMesh(self, vertices, faces, normals, values,
name='', reshape_faces=True):
""" Write the given mesh instance.
"""
# Store properties
self._hasNormals = normals is not None
self._hasValues = values is not None
self._hasFaces = faces is not None
... |
Compute cross product between list of 3D vectors | def _fast_cross_3d(x, y):
"""Compute cross product between list of 3D vectors
Much faster than np.cross() when the number of cross products
becomes large (>500). This is because np.cross() methods become
less memory efficient at this stage.
Parameters
----------
x : array
Input arr... |
Efficiently compute vertex normals for triangulated surface | def _calculate_normals(rr, tris):
"""Efficiently compute vertex normals for triangulated surface"""
# ensure highest precision for our summation/vectorization "trick"
rr = rr.astype(np.float64)
# first, compute triangle normals
r1 = rr[tris[:, 0], :]
r2 = rr[tris[:, 1], :]
r3 = rr[tris[:, 2]... |
Resize an image | def resize(image, shape, kind='linear'):
"""Resize an image
Parameters
----------
image : ndarray
Array of shape (N, M, ...).
shape : tuple
2-element shape.
kind : str
Interpolation, either "linear" or "nearest".
Returns
-------
scaled_image : ndarray
... |
Append a new set of segments to the collection. | def append(self, P0, P1, itemsize=None, **kwargs):
"""
Append a new set of segments to the collection.
For kwargs argument, n is the number of vertices (local) or the number
of item (shared)
Parameters
----------
P : np.array
Vertices positions of t... |
Parse the lines and fill self. line_fields accordingly. | def parse(self):
"""Parse the lines, and fill self.line_fields accordingly."""
for line in self.lines:
# Parse the line
field_defs = self.parse_line(line)
fields = []
# Convert field parameters into Field objects
for (kind, options) in field_d... |
Compute the relative position of the fields on a given line. | def compute_positions(cls, screen_width, line):
"""Compute the relative position of the fields on a given line.
Args:
screen_width (int): the width of the screen
line (mpdlcd.display_fields.Field list): the list of fields on the
line
Returns:
... |
Add the pattern to a screen. | def add_to_screen(self, screen_width, screen):
"""Add the pattern to a screen.
Also fills self.widgets.
Args:
screen_width (int): the width of the screen
screen (lcdprod.Screen): the screen to fill.
"""
for lineno, fields in enumerate(self.line_fields):
... |
Register a field on its target hooks. | def register_hooks(self, field):
"""Register a field on its target hooks."""
for hook, subhooks in field.register_hooks():
self.hooks[hook].append(field)
self.subhooks[hook] |= set(subhooks) |
Called whenever the data for a hook changed. | def hook_changed(self, hook, new_data):
"""Called whenever the data for a hook changed."""
for field in self.hooks[hook]:
widget = self.widgets[field]
field.hook_changed(hook, widget, new_data) |
Parse a line of text. | def parse_line(self, line):
"""Parse a line of text.
A format contains fields, within curly brackets, and free text.
Maximum one 'variable width' field is allowed per line.
You cannot use the '{' or '}' characters in the various text/... fields.
Format:
'''{<field_k... |
Add a pattern to the list. | def add(self, pattern_txt):
"""Add a pattern to the list.
Args:
pattern_txt (str list): the pattern, as a list of lines.
"""
self.patterns[len(pattern_txt)] = pattern_txt
low = 0
high = len(pattern_txt) - 1
while not pattern_txt[low]:
lo... |
Convert x y coordinates to w x y z Quaternion parameters | def _arcball(xy, wh):
"""Convert x,y coordinates to w,x,y,z Quaternion parameters
Adapted from:
linalg library
Copyright (c) 2010-2015, Renaud Blanch <rndblnch at gmail dot com>
Licence at your convenience:
GPLv3 or higher <http://www.gnu.org/licenses/gpl.html>
BSD new <http://opensource.... |
Update rotation parmeters based on mouse movement | def _update_rotation(self, event):
"""Update rotation parmeters based on mouse movement"""
p2 = event.mouse_event.pos
if self._event_value is None:
self._event_value = p2
wh = self._viewbox.size
self._quaternion = (Quaternion(*_arcball(p2, wh)) *
... |
Rotate the transformation matrix based on camera parameters | def _rotate_tr(self):
"""Rotate the transformation matrix based on camera parameters"""
rot, x, y, z = self._quaternion.get_axis_angle()
up, forward, right = self._get_dim_vectors()
self.transform.rotate(180 * rot / np.pi, (x, z, y)) |
Convert mouse x y movement into x y z translations | def _dist_to_trans(self, dist):
"""Convert mouse x, y movement into x, y, z translations"""
rot, x, y, z = self._quaternion.get_axis_angle()
tr = MatrixTransform()
tr.rotate(180 * rot / np.pi, (x, y, z))
dx, dz, dy = np.dot(tr.matrix[:3, :3], (dist[0], dist[1], 0.))
retur... |
Decorator to convert argument to array. | def arg_to_array(func):
"""
Decorator to convert argument to array.
Parameters
----------
func : function
The function to decorate.
Returns
-------
func : function
The decorated function.
"""
def fn(self, arg, *args, **kwargs):
"""Function
Param... |
Convert obj to 4 - element vector ( numpy array with shape [ - 1 ] == 4 ) | def as_vec4(obj, default=(0, 0, 0, 1)):
"""
Convert `obj` to 4-element vector (numpy array with shape[-1] == 4)
Parameters
----------
obj : array-like
Original object.
default : array-like
The defaults to use if the object does not have 4 entries.
Returns
-------
ob... |
Decorator for converting argument to vec4 format suitable for 4x4 matrix multiplication. | def arg_to_vec4(func, self_, arg, *args, **kwargs):
"""
Decorator for converting argument to vec4 format suitable for 4x4 matrix
multiplication.
[x, y] => [[x, y, 0, 1]]
[x, y, z] => [[x, y, z, 1]]
[[x1, y1], [[x1, y1, 0, 1],
[x2, y2], => [x2, y2, 0, 1],
[x3, y3]] ... |
Get a transform from the cache that maps along * path * which must be a list of Transforms to apply in reverse order ( last transform is applied first ). | def get(self, path):
""" Get a transform from the cache that maps along *path*, which must
be a list of Transforms to apply in reverse order (last transform is
applied first).
Accessed items have their age reset to 0.
"""
key = tuple(map(id, path))
item = self._c... |
Increase the age of all items in the cache by 1. Items whose age is greater than self. max_age will be removed from the cache. | def roll(self):
""" Increase the age of all items in the cache by 1. Items whose age
is greater than self.max_age will be removed from the cache.
"""
rem = []
for key, item in self._cache.items():
if item[0] > self.max_age:
rem.append(key)
... |
Calculate and show a histogram of data | def histogram(self, data, bins=10, color='w', orientation='h'):
"""Calculate and show a histogram of data
Parameters
----------
data : array-like
Data to histogram. Currently only 1D data is supported.
bins : int | array-like
Number of bins, or bin edges.... |
Show an image | def image(self, data, cmap='cubehelix', clim='auto', fg_color=None):
"""Show an image
Parameters
----------
data : ndarray
Should have shape (N, M), (N, M, 3) or (N, M, 4).
cmap : str
Colormap name.
clim : str | tuple
Colormap limits. ... |
Show a 3D mesh | def mesh(self, vertices=None, faces=None, vertex_colors=None,
face_colors=None, color=(0.5, 0.5, 1.), fname=None,
meshdata=None):
"""Show a 3D mesh
Parameters
----------
vertices : array
Vertices.
faces : array | None
Face defini... |
Plot a series of data using lines and markers | def plot(self, data, color='k', symbol=None, line_kind='-', width=1.,
marker_size=10., edge_color='k', face_color='b', edge_width=1.,
title=None, xlabel=None, ylabel=None):
"""Plot a series of data using lines and markers
Parameters
----------
data : array | tw... |
Calculate and show a spectrogram | def spectrogram(self, x, n_fft=256, step=None, fs=1., window='hann',
color_scale='log', cmap='cubehelix', clim='auto'):
"""Calculate and show a spectrogram
Parameters
----------
x : array-like
1D signal to operate on. ``If len(x) < n_fft``, x will be
... |
Show a 3D volume | def volume(self, vol, clim=None, method='mip', threshold=None,
cmap='grays'):
"""Show a 3D volume
Parameters
----------
vol : ndarray
Volume to render.
clim : tuple of two floats | None
The contrast limits. The values in the volume are mapp... |
Show a 3D surface plot. | def surface(self, zdata, **kwargs):
"""Show a 3D surface plot.
Extra keyword arguments are passed to `SurfacePlot()`.
Parameters
----------
zdata : array-like
A 2D array of the surface Z values.
"""
self._configure_3d()
surf = scene.SurfaceP... |
Show a ColorBar | def colorbar(self, cmap, position="right",
label="", clim=("", ""),
border_width=0.0, border_color="black",
**kwargs):
"""Show a ColorBar
Parameters
----------
cmap : str | vispy.color.ColorMap
Either the name of the ColorMa... |
Redraw the Vispy canvas | def redraw(self):
"""
Redraw the Vispy canvas
"""
if self._multiscat is not None:
self._multiscat._update()
self.vispy_widget.canvas.update() |
Remove the layer artist from the visualization | def remove(self):
"""
Remove the layer artist from the visualization
"""
if self._multiscat is None:
return
self._multiscat.deallocate(self.id)
self._multiscat = None
self._viewer_state.remove_global_callback(self._update_scatter)
self.state... |
Helper to check valid options | def _check_valid(key, val, valid):
"""Helper to check valid options"""
if val not in valid:
raise ValueError('%s must be one of %s, not "%s"'
% (key, valid, val)) |
Convert to args representation | def _to_args(x):
"""Convert to args representation"""
if not isinstance(x, (list, tuple, np.ndarray)):
x = [x]
return x |
Check for existence of key in dict return value or raise error | def _check_conversion(key, valid_dict):
"""Check for existence of key in dict, return value or raise error"""
if key not in valid_dict and key not in valid_dict.values():
# Only show users the nice string values
keys = [v for v in valid_dict.keys() if isinstance(v, string_types)]
raise V... |
Read pixels from the currently selected buffer. Under most circumstances this function reads from the front buffer. Unlike all other functions in vispy. gloo this function directly executes an OpenGL command. | def read_pixels(viewport=None, alpha=True, out_type='unsigned_byte'):
"""Read pixels from the currently selected buffer.
Under most circumstances, this function reads from the front buffer.
Unlike all other functions in vispy.gloo, this function directly executes
an OpenGL command.
Parameters... |
Read the current gl configuration | def get_gl_configuration():
"""Read the current gl configuration
This function uses constants that are not in the OpenGL ES 2.1
namespace, so only use this on desktop systems.
Returns
-------
config : dict
The currently active OpenGL configuration.
"""
# XXX eventually maybe we... |
Set the OpenGL viewport This is a wrapper for gl. glViewport. Parameters ---------- * args: tuple X and Y coordinates plus width and height. Can be passed in as individual components or as a single tuple with four values. | def set_viewport(self, *args):
"""Set the OpenGL viewport
This is a wrapper for gl.glViewport.
Parameters
----------
*args : tuple
X and Y coordinates, plus width and height. Can be passed in as
individual components, or as a single tuple with fo... |
Set depth values Parameters ---------- near: float Near clipping plane. far: float Far clipping plane. | def set_depth_range(self, near=0., far=1.):
"""Set depth values
Parameters
----------
near : float
Near clipping plane.
far : float
Far clipping plane.
"""
self.glir.command('FUNC', 'glDepthRange', float(near), float(far)) |
Set line width Parameters ---------- width: float The line width. | def set_line_width(self, width=1.):
"""Set line width
Parameters
----------
width : float
The line width.
"""
width = float(width)
if width < 0:
raise RuntimeError('Cannot have width < 0')
self.glir.command('FUNC', 'glLineWidth... |
Set the scale and units used to calculate depth values Parameters ---------- factor: float Scale factor used to create a variable depth offset for each polygon. units: float Multiplied by an implementation - specific value to create a constant depth offset. | def set_polygon_offset(self, factor=0., units=0.):
"""Set the scale and units used to calculate depth values
Parameters
----------
factor : float
Scale factor used to create a variable depth offset for
each polygon.
units : float
Multiplie... |
Clear the screen buffers This is a wrapper for gl. glClear. Parameters ---------- color: bool | str | tuple | instance of Color Clear the color buffer bit. If not bool set_clear_color will be used to set the color clear value. depth: bool | float Clear the depth buffer bit. If float set_clear_depth will be used to set ... | def clear(self, color=True, depth=True, stencil=True):
"""Clear the screen buffers
This is a wrapper for gl.glClear.
Parameters
----------
color : bool | str | tuple | instance of Color
Clear the color buffer bit. If not bool, ``set_clear_color`` will
... |
Set the screen clear color | def set_clear_color(self, color='black', alpha=None):
"""Set the screen clear color
This is a wrapper for gl.glClearColor.
Parameters
----------
color : str | tuple | instance of Color
Color to use. See vispy.color.Color for options.
alpha : float | None
... |
Specify pixel arithmetic for RGB and alpha Parameters ---------- srgb: str Source RGB factor. drgb: str Destination RGB factor. salpha: str | None Source alpha factor. If None srgb is used. dalpha: str Destination alpha factor. If None drgb is used. | def set_blend_func(self, srgb='one', drgb='zero',
salpha=None, dalpha=None):
"""Specify pixel arithmetic for RGB and alpha
Parameters
----------
srgb : str
Source RGB factor.
drgb : str
Destination RGB factor.
salpha : s... |
Specify the equation for RGB and alpha blending Parameters ---------- mode_rgb: str Mode for RGB. mode_alpha: str | None Mode for Alpha. If None mode_rgb is used. Notes ----- See set_blend_equation for valid modes. | def set_blend_equation(self, mode_rgb, mode_alpha=None):
"""Specify the equation for RGB and alpha blending
Parameters
----------
mode_rgb : str
Mode for RGB.
mode_alpha : str | None
Mode for Alpha. If None, ``mode_rgb`` is used.
Notes
... |
Define the scissor box Parameters ---------- x: int Left corner of the box. y: int Lower corner of the box. w: int The width of the box. h: int The height of the box. | def set_scissor(self, x, y, w, h):
"""Define the scissor box
Parameters
----------
x : int
Left corner of the box.
y : int
Lower corner of the box.
w : int
The width of the box.
h : int
The height of the box.
... |
Set front or back function and reference value Parameters ---------- func: str See set_stencil_func. ref: int Reference value for the stencil test. mask: int Mask that is ANDed with ref and stored stencil value. face: str Can be front back or front_and_back. | def set_stencil_func(self, func='always', ref=0, mask=8,
face='front_and_back'):
"""Set front or back function and reference value
Parameters
----------
func : str
See set_stencil_func.
ref : int
Reference value for the stenc... |
Control the front or back writing of individual bits in the stencil Parameters ---------- mask: int Mask that is ANDed with ref and stored stencil value. face: str Can be front back or front_and_back. | def set_stencil_mask(self, mask=8, face='front_and_back'):
"""Control the front or back writing of individual bits in the stencil
Parameters
----------
mask : int
Mask that is ANDed with ref and stored stencil value.
face : str
Can be 'front', 'back',... |
Set front or back stencil test actions Parameters ---------- sfail: str Action to take when the stencil fails. Must be one of keep zero replace incr incr_wrap decr decr_wrap or invert. dpfail: str Action to take when the stencil passes. dppass: str Action to take when both the stencil and depth tests pass or when the s... | def set_stencil_op(self, sfail='keep', dpfail='keep', dppass='keep',
face='front_and_back'):
"""Set front or back stencil test actions
Parameters
----------
sfail : str
Action to take when the stencil fails. Must be one of
'keep', 'zero... |
Toggle writing of frame buffer color components Parameters ---------- red: bool Red toggle. green: bool Green toggle. blue: bool Blue toggle. alpha: bool Alpha toggle. | def set_color_mask(self, red, green, blue, alpha):
"""Toggle writing of frame buffer color components
Parameters
----------
red : bool
Red toggle.
green : bool
Green toggle.
blue : bool
Blue toggle.
alpha : bool
... |
Specify multisample coverage parameters Parameters ---------- value: float Sample coverage value ( will be clamped between 0. and 1. ). invert: bool Specify if the coverage masks should be inverted. | def set_sample_coverage(self, value=1.0, invert=False):
"""Specify multisample coverage parameters
Parameters
----------
value : float
Sample coverage value (will be clamped between 0. and 1.).
invert : bool
Specify if the coverage masks should be inv... |
Set OpenGL rendering state optionally using a preset Parameters ---------- preset: str | None Can be one of ( opaque translucent additive ) to use use reasonable defaults for these typical use cases. ** kwargs: keyword arguments Other supplied keyword arguments will override any preset defaults. Options to be enabled o... | def set_state(self, preset=None, **kwargs):
"""Set OpenGL rendering state, optionally using a preset
Parameters
----------
preset : str | None
Can be one of ('opaque', 'translucent', 'additive') to use
use reasonable defaults for these typical use cases.
... |
Wait for GL commands to to finish This creates a GLIR command for glFinish and then processes the GLIR commands. If the GLIR interpreter is remote ( e. g. WebGL ) this function will return before GL has finished processing the commands. | def finish(self):
"""Wait for GL commands to to finish
This creates a GLIR command for glFinish and then processes the
GLIR commands. If the GLIR interpreter is remote (e.g. WebGL), this
function will return before GL has finished processing the commands.
"""
if ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.