From 7206bbb632cade9b4c245f56106a4546884764cf Mon Sep 17 00:00:00 2001 From: Anton Hvornum Date: Tue, 12 Apr 2016 16:45:22 -0700 Subject: [PATCH] Trying to adapt the code to Python3+ This is a working copy of a version that is working in the sense that it's able to install and run a basic example (without desired results?): http://i.imgur.com/7L8omha.png --- nodebox/ext/psyco/__init__.py | 4 +- nodebox/ext/psyco/core.py | 12 ++--- nodebox/ext/psyco/kdictproxy.py | 6 +-- nodebox/ext/psyco/profiler.py | 2 +- nodebox/ext/psyco/support.py | 12 ++--- nodebox/graphics/__init__.py | 17 ++++--- nodebox/graphics/bezier.py | 14 ++--- nodebox/graphics/context.py | 90 +++++++++++++++++++-------------- nodebox/graphics/geometry.py | 5 +- nodebox/graphics/physics.py | 12 +++-- nodebox/graphics/shader.py | 23 +++++---- nodebox/gui/controls.py | 8 +-- nodebox/sound/osc.py | 50 +++++++++--------- nodebox/sound/process.py | 6 +-- 14 files changed, 141 insertions(+), 120 deletions(-) diff --git a/nodebox/ext/psyco/__init__.py b/nodebox/ext/psyco/__init__.py index d25e197..901c9b8 100644 --- a/nodebox/ext/psyco/__init__.py +++ b/nodebox/ext/psyco/__init__.py @@ -28,7 +28,7 @@ # Try to import the dynamic-loading _psyco and report errors try: import _psyco -except ImportError, e: +except ImportError as e: extramsg = '' import sys, imp try: @@ -43,7 +43,7 @@ extramsg = (" (check that the compiled extension '%s' is for " "the correct Python version; this is Python %s)" % (filename, sys.version.split()[0])) - raise ImportError, str(e) + extramsg + raise ImportError(str(e) + extramsg) # Publish important data by importing them in the package from support import __version__, error, warning, _getrealframe, _getemulframe diff --git a/nodebox/ext/psyco/core.py b/nodebox/ext/psyco/core.py index 42a6c2f..0581afc 100644 --- a/nodebox/ext/psyco/core.py +++ b/nodebox/ext/psyco/core.py @@ -141,12 +141,12 @@ def bind(x, rec=None): if isinstance(o, types.MethodType) or isinstance(o, types.FunctionType)] if not funcs: - raise error, ("nothing bindable found in %s object" % + raise error("nothing bindable found in %s object" % type(x).__name__) for o in funcs: bind(o, rec) return - raise TypeError, "cannot bind %s objects" % type(x).__name__ + raise TypeError("cannot bind %s objects" % type(x).__name__) def unbind(x): @@ -167,7 +167,7 @@ def unbind(x): or isinstance(o, types.FunctionType)): unbind(o) return - raise TypeError, "cannot unbind %s objects" % type(x).__name__ + raise TypeError("cannot unbind %s objects" % type(x).__name__) def proxy(x, rec=None): @@ -186,7 +186,7 @@ def proxy(x, rec=None): if isinstance(x, types.MethodType): p = proxy(x.im_func, rec) return new.instancemethod(p, x.im_self, x.im_class) - raise TypeError, "cannot proxy %s objects" % type(x).__name__ + raise TypeError("cannot proxy %s objects" % type(x).__name__) def unproxy(proxy): @@ -198,7 +198,7 @@ def unproxy(proxy): if isinstance(proxy, types.MethodType): f = unproxy(proxy.im_func) return new.instancemethod(f, proxy.im_self, proxy.im_class) - raise TypeError, "%s objects cannot be proxies" % type(proxy).__name__ + raise TypeError("%s objects cannot be proxies" % type(proxy).__name__) def cannotcompile(x): @@ -211,7 +211,7 @@ def cannotcompile(x): if isinstance(x, types.CodeType): _psyco.cannotcompile(x) else: - raise TypeError, "unexpected %s object" % type(x).__name__ + raise TypeError("unexpected %s object" % type(x).__name__) def dumpcodebuf(): diff --git a/nodebox/ext/psyco/kdictproxy.py b/nodebox/ext/psyco/kdictproxy.py index c764e5e..ea259fa 100644 --- a/nodebox/ext/psyco/kdictproxy.py +++ b/nodebox/ext/psyco/kdictproxy.py @@ -56,8 +56,8 @@ def setdefault(self, key, default): return default def pop(self, key, *args): if len(args) > 1: - raise TypeError, "pop expected at most 2 arguments, got "\ - + repr(1 + len(args)) + raise TypeError("pop expected at most 2 arguments, got "\ + + repr(1 + len(args))) try: value = self[key] except KeyError: @@ -70,7 +70,7 @@ def popitem(self): try: k, v = self.iteritems().next() except StopIteration: - raise KeyError, 'container is empty' + raise KeyError('container is empty') del self[k] return (k, v) def update(self, other): diff --git a/nodebox/ext/psyco/profiler.py b/nodebox/ext/psyco/profiler.py index ef7bf8e..60a0d92 100644 --- a/nodebox/ext/psyco/profiler.py +++ b/nodebox/ext/psyco/profiler.py @@ -189,7 +189,7 @@ def start(self): try: self.do_start() - except error, e: + except error as e: if logger: logger.write('%s: disabled by psyco.error:' % ( self.__class__.__name__), 4) diff --git a/nodebox/ext/psyco/support.py b/nodebox/ext/psyco/support.py index a61224e..f138478 100644 --- a/nodebox/ext/psyco/support.py +++ b/nodebox/ext/psyco/support.py @@ -26,7 +26,7 @@ def warn(msg): # __version__ = 0x010502f0 if _psyco.PSYVER != __version__: - raise error, "version mismatch between Psyco parts, reinstall it" + raise error("version mismatch between Psyco parts, reinstall it") version_info = (__version__ >> 24, (__version__ >> 16) & 0xff, @@ -123,16 +123,16 @@ def __getattr__(self, attr): elif attr == 'f_restricted': result = self.f_builtins is not __builtins__ elif attr == 'f_locals': - raise AttributeError, ("local variables of functions run by Psyco " + raise AttributeError("local variables of functions run by Psyco " "cannot be accessed in any way, sorry") else: - raise AttributeError, ("emulated Psyco frames have " - "no '%s' attribute" % attr) + raise AttributeError("emulated Psyco frames have " + "no '" + str(attr) + "' attribute" ) self.__dict__[attr] = result return result def __setattr__(self, attr, value): - raise AttributeError, "Psyco frame objects are read-only" + raise AttributeError("Psyco frame objects are read-only") def __delattr__(self, attr): if attr == 'f_trace': @@ -140,7 +140,7 @@ def __delattr__(self, attr): # buggy behavior: you can 'del f.f_trace' as often as you like # even without having set it previously. return - raise AttributeError, "Psyco frame objects are read-only" + raise AttributeError("Psyco frame objects are read-only") def embedframe(result): diff --git a/nodebox/graphics/__init__.py b/nodebox/graphics/__init__.py index 392a7dd..b6dd20e 100644 --- a/nodebox/graphics/__init__.py +++ b/nodebox/graphics/__init__.py @@ -1,11 +1,11 @@ -import bezier -import context -import geometry -import physics -import shader +import nodebox.graphics.bezier +import nodebox.graphics.context +import nodebox.graphics.geometry +import nodebox.graphics.physics +import nodebox.graphics.shader -from noise import noise -from context import * +from nodebox.graphics.noise import noise +from nodebox.graphics.context import * physics.line = context.line physics.ellipse = context.ellipse @@ -20,6 +20,9 @@ canvas = Canvas() +def get_canvas(): + return canvas + def size(width=None, height=None): if width is not None: canvas.width = width diff --git a/nodebox/graphics/bezier.py b/nodebox/graphics/bezier.py index ce8883e..af15d41 100644 --- a/nodebox/graphics/bezier.py +++ b/nodebox/graphics/bezier.py @@ -7,7 +7,7 @@ # Thanks to Prof. F. De Smedt at the Vrije Universiteit Brussel. -from context import BezierPath, PathElement, PathError, Point, MOVETO, LINETO, CURVETO, CLOSE +from nodebox.graphics.context import BezierPath, PathElement, PathError, Point, MOVETO, LINETO, CURVETO, CLOSE from math import sqrt, pow class DynamicPathElement(PathElement): @@ -156,7 +156,7 @@ def _locate(path, t, segments=None): if segments == None: segments = segment_lengths(path, relative=True) if len(segments) == 0: - raise PathError, "The given path is empty" + raise PathError("The given path is empty") for i, el in enumerate(path): if i == 0 or el.cmd == MOVETO: closeto = Point(el.x, el.y) @@ -179,7 +179,7 @@ def point(path, t, segments=None): the length during each iteration. """ if len(path) == 0: - raise PathError, "The given path is empty" + raise PathError("The given path is empty") i, t, closeto = _locate(path, t, segments=segments) x0, y0 = path[i].x, path[i].y p1 = path[i+1] @@ -198,14 +198,14 @@ def point(path, t, segments=None): x, y, c1x, c1y, c2x, c2y = curvepoint(t, x0, y0, x1, y1, x2, y2, x3, y3) return DynamicPathElement(CURVETO, ((c1x, c1y), (c2x, c2y), (x, y))) else: - raise PathError, "Unknown cmd '%s' for p1 %s" % (p1.cmd, p1) + raise PathError("Unknown cmd '" + str(p1.cmd) + "' for p1 " + str(p1)) def points(path, amount=100, start=0.0, end=1.0, segments=None): """ Returns an iterator with a list of calculated points for the path. To omit the last point on closed paths: end=1-1.0/amount """ if len(path) == 0: - raise PathError, "The given path is empty" + raise PathError("The given path is empty") n = end - start d = n if amount > 1: @@ -344,7 +344,7 @@ def insert_point(path, t): pt_x, pt_y, pt_c1x, pt_c1y, pt_c2x, pt_c2y, pt_h1x, pt_h1y, pt_h2x, pt_h2y = \ curvepoint(t, x0, y0, x1, y1, x2, y2, x3, y3, True) else: - raise PathError, "Locate should not return a MOVETO" + raise PathError("Locate should not return a MOVETO") # NodeBox for OpenGL modifies the path in place, # NodeBox for Mac OS X returned a path copy (see inactive code below). @@ -357,7 +357,7 @@ def insert_point(path, t): elif pt_cmd == LINETO: path.insert(i+1, PathElement(cmd=LINETO, pts=[(pt_x, pt_y)])) else: - raise PathError, "Didn't expect pt_cmd %s here" % pt_cmd + raise PathError("Didn't expect pt_cmd " + str(pt_cmd) + " here") return path[i+1] #new_path = BezierPath(None) diff --git a/nodebox/graphics/context.py b/nodebox/graphics/context.py index 54d0f64..ccd8385 100644 --- a/nodebox/graphics/context.py +++ b/nodebox/graphics/context.py @@ -17,17 +17,19 @@ from math import cos, sin, radians, pi, floor from time import time from random import seed, choice, shuffle, random as rnd -from new import instancemethod from glob import glob from os import path, remove from sys import getrefcount -from StringIO import StringIO +try: + from StringIO import StringIO +except ImportError: + from io import StringIO from hashlib import md5 from types import FunctionType from datetime import datetime from numbers import Number -import geometry +from nodebox.graphics import geometry #import bezier # Do this at the end, when we have defined BezierPath, which is needed in the bezier module. @@ -118,7 +120,7 @@ def __init__(self, *args, **kwargs): # Transform to base 1: base = float(kwargs.get("base", 1.0)) if base != 1: - r, g, b, a = [ch/base for ch in r, g, b, a] + r, g, b, a = [ch/base for ch in [r, g, b, a]] # Transform to color space RGB: colorspace = kwargs.get("colorspace") if colorspace and colorspace != RGB: @@ -149,7 +151,8 @@ def _set_a(self, v): self[3] = v def _get_rgb(self): return self[0], self[1], self[2] - def _set_rgb(self, (r,g,b)): + def _set_rgb(self, c): + r,g,b = c self[0] = r self[1] = g self[2] = b @@ -158,7 +161,8 @@ def _set_rgb(self, (r,g,b)): def _get_rgba(self): return self[0], self[1], self[2], self[3] - def _set_rgba(self, (r,g,b,a)): + def _set_rgba(self, c): + r,g,b,a = c self[0] = r self[1] = g self[2] = b @@ -197,9 +201,9 @@ def map(self, base=1.0, colorspace=RGB): if colorspace == XYZ: r, g, b = rgb_to_xyz(r, g, b) if colorspace == LAB: r, g, b = rgb_to_lab(r, g, b) if base != 1: - r, g, b, a = [ch*base for ch in r, g, b, a] + r, g, b, a = [ch*base for ch in [r, g, b, a]] if base != 1 and isinstance(base, int): - r, g, b, a = [int(ch) for ch in r, g, b, a] + r, g, b, a = [int(ch) for ch in [r, g, b, a]] return r, g, b, a def blend(self, clr, t=0.5, colorspace=RGB): @@ -337,8 +341,8 @@ def hsb_to_rgb(h, s, v): def rgb_to_xyz(r, g, b): """ Converts the given R,G,B values to CIE X,Y,Z (between 0.0-1.0). """ - r, g, b = [ch > 0.04045 and ((ch+0.055) / 1.055) ** 2.4 or ch / 12.92 for ch in r, g, b] - r, g, b = [ch * 100.0 for ch in r, g, b] + r, g, b = [ch > 0.04045 and ((ch+0.055) / 1.055) ** 2.4 or ch / 12.92 for ch in [r, g, b]] + r, g, b = [ch * 100.0 for ch in [r, g, b]] r, g, b = ( # Observer = 2, Illuminant = D65 r * 0.4124 + g * 0.3576 + b * 0.1805, r * 0.2126 + g * 0.7152 + b * 0.0722, @@ -349,18 +353,18 @@ def xyz_to_rgb(x, y, z): """ Converts the given CIE X,Y,Z color values to R,G,B (between 0.0-1.0). """ x, y, z = x*95.047, y*100.0, z*108.883 - x, y, z = [ch / 100.0 for ch in x, y, z] + x, y, z = [ch / 100.0 for ch in [x, y, z]] r = x * 3.2406 + y * -1.5372 + z * -0.4986 g = x * -0.9689 + y * 1.8758 + z * 0.0415 b = x * -0.0557 + y * -0.2040 + z * 1.0570 - r, g, b = [ch > 0.0031308 and 1.055 * ch**(1/2.4) - 0.055 or ch * 12.92 for ch in r, g, b] + r, g, b = [ch > 0.0031308 and 1.055 * ch**(1/2.4) - 0.055 or ch * 12.92 for ch in [r, g, b]] return r, g, b def rgb_to_lab(r, g, b): """ Converts the given R,G,B values to CIE L,A,B (between 0.0-1.0). """ x, y, z = rgb_to_xyz(r, g, b) - x, y, z = [ch > 0.008856 and ch**(1/3.0) or (ch*7.787) + (16/116.0) for ch in x, y, z] + x, y, z = [ch > 0.008856 and ch**(1/3.0) or (ch*7.787) + (16/116.0) for ch in [x, y, z]] l, a, b = y*116-16, 500*(x-y), 200*(y-z) l, a, b = l/100.0, (a+86)/(86+98), (b+108)/(108+94) return l, a, b @@ -372,7 +376,7 @@ def lab_to_rgb(l, a, b): y = (l+16)/116.0 x = y + a/500.0 z = y - b/200.0 - x, y, z = [ch**3 > 0.008856 and ch**3 or (ch-16/116.0)/7.787 for ch in x, y, z] + x, y, z = [ch**3 > 0.008856 and ch**3 or (ch-16/116.0)/7.787 for ch in [x, y, z]] return xyz_to_rgb(x, y, z) def luminance(r, g, b): @@ -552,7 +556,7 @@ def reset(): CENTER = "center" def transform(mode=None): if mode == CENTER: - raise NotImplementedError, "no center-mode transform" + raise NotImplementedError("no center-mode transform") return CORNER def skew(x, y): @@ -849,7 +853,8 @@ def _set_y(self, v): def _get_xy(self): return (self.x, self.y) - def _set_xy(self, (x,y)): + def _set_xy(self, pos): + x,y = pos self.x = x self.y = y @@ -1509,7 +1514,7 @@ def texture(img, data=None): try: cache(img, pyglet.image.load(img).get_texture()) except IOError: - raise ImageError, "can't load image from %s" % repr(img) + raise ImageError("can't load image from " + repr(img)) return _texture_cache[img] # Image texture, return original. if isinstance(img, pyglet.image.Texture): @@ -1528,7 +1533,7 @@ def texture(img, data=None): if isinstance(data, basestring): return pyglet.image.load("", file=StringIO(data)).get_texture() # Don't know how to handle this image. - raise ImageError, "unknown image type: %s" % repr(img.__class__) + raise ImageError("unknown image type: " + repr(img.__class__)) def cache(id, texture): """ Store the given texture in cache, referenced by id (which can then be passed to image()). @@ -1537,7 +1542,7 @@ def cache(id, texture): if isinstance(texture, (Image, Pixels)): texture = texture.texture if not isinstance(texture, pyglet.image.Texture): - raise ValueError, "can only cache texture, not %s" % repr(texture.__class__.__name__) + raise ValueError("can only cache texture, not " + repr(texture.__class__.__name__)) _texture_cache[id] = texture _texture_cached[_texture_cache[id].id] = id @@ -1661,7 +1666,8 @@ def texture(self): def _get_xy(self): return (self.x, self.y) - def _set_xy(self, (x,y)): + def _set_xy(self, pos): + x, y = pos self.x = x self.y = y @@ -1669,7 +1675,8 @@ def _set_xy(self, (x,y)): def _get_size(self): return (self.width, self.height) - def _set_size(self, (w,h)): + def _set_size(self, dimensions): + w, h = dimensions self.width = w self.height = h @@ -2010,7 +2017,7 @@ def __repr__(self): # The less you change about an offscreen buffer, the faster it runs. # This includes switching it on and off and changing its size. -from shader import * +from nodebox.graphics.shader import * #===================================================================================================== @@ -2194,7 +2201,8 @@ def __init__(self, str, x=0, y=0, width=None, height=None, **kwargs): def _get_xy(self): return (self.x, self.y) - def _set_xy(self, (x,y)): + def _set_xy(self, pos): + x, y = pos self.x = x self.y = y @@ -2202,7 +2210,8 @@ def _set_xy(self, (x,y)): def _get_size(self): return (self.width, self.height) - def _set_size(self, (w,h)): + def _set_size(self, dimensions): + w, h = dimensions self.width = w self.height = h @@ -2232,7 +2241,7 @@ def __getattr__(self, k): if not self._fill: self._fill = Color([ch/255.0 for ch in self._label.color]) return self._fill else: - raise AttributeError, "'Text' object has no attribute '%s'" % k + raise AttributeError("'Text' object has no attribute '" + str(k) + "'") def __setattr__(self, k, v): if k in self.__dict__: @@ -2261,7 +2270,7 @@ def __setattr__(self, k, v): self._fill = v self._label.color = [int(255*ch) for ch in self._fill or (0,0,0,0)] else: - raise AttributeError, "'Text' object has no attribute '%s'" % k + raise AttributeError("'Text' object has no attribute '" + str(k) + "'") def _update(self): # Called from Text.draw(), Text.copy() and Text.metrics. @@ -2432,13 +2441,13 @@ def textmetrics(txt, width=None, **kwargs): class GlyphPathError(Exception): pass -import cPickle +import pickle glyphs = {} try: # Load cached font glyph path information from nodebox/font/glyph.p. # By default, it has glyph path info for Droid Sans, Droid Sans Mono, Droid Serif. glyphs = path.join(path.dirname(__file__), "..", "font", "glyph.p") - glyphs = cPickle.load(open(glyphs)) + glyphs = pickle.load(open(glyphs)) except: pass @@ -2456,7 +2465,7 @@ def textpath(string, x=0, y=0, **kwargs): for ch in string: try: glyph = glyphs[fontname][w][ch] except: - raise GlyphPathError, "no glyph path information for %s %s '%s'" % (w, fontname, ch) + raise GlyphPathError("no glyph path information for " + str(w) + " " + str(fontname) + " '" + str(ch) + "'") for pt in glyph: if pt[0] == MOVETO: p.moveto(x+pt[1]*f, y-pt[2]*f) @@ -2535,7 +2544,8 @@ def __init__(self): def _deepcopy(self, value): if isinstance(value, FunctionType): - return instancemethod(value, self) + return getattr(self, value.__name__) # Replaces instancemethod(value, self) + # Where value is elif hasattr(value, "copy"): return value.copy() elif isinstance(value, (list, tuple)): @@ -2546,7 +2556,7 @@ def _deepcopy(self, value): return value else: # Biggest problem here is how to find/relink circular references. - raise TypeError, "Prototype can't bind %s." % str(value.__class__) + raise TypeError("Prototype can't bind " + str(value.__class__) + ".") def _bind(self, key, value): """ Adds a new method or property to the prototype. @@ -2856,7 +2866,7 @@ def __getattr__(self, key): for layer in self: if layer.name == key: return layer - raise AttributeError, "%s instance has no attribute '%s'" % (self.__class__.__name__, key) + raise AttributeError(str(self.__class__.__name__) + " instance has no attribute '" + str(key) + "'") def _set_container(self, key, value): # If Layer.canvas is set to None, the canvas should no longer contain the layer. @@ -2953,7 +2963,8 @@ def _set_opacity(self, opacity): def _get_xy(self): return (self.x, self.y) - def _set_xy(self, (x,y)): + def _set_xy(self, pos): + x, y = pos self.x = x self.y = y @@ -3125,7 +3136,7 @@ def render(self): """ b = self.bounds if geometry.INFINITE in (b.x, b.y, b.width, b.height): - raise LayerRenderError, "can't render layer of infinite size" + raise LayerRenderError("can't render layer of infinite size") return render(lambda: (translate(-b.x,-b.y), self._draw()), b.width, b.height) def layer_at(self, x, y, clipped=False, enabled=False, transformed=True, _covered=False): @@ -3615,7 +3626,8 @@ def _set_y(self, v): self._window.set_location(self.x, v) def _get_xy(self): return (self.x, self.y) - def _set_xy(self, (x,y)): + def _set_xy(self, pos): + x, y = pos self.x = x self.y = y def _get_width(self): @@ -3628,7 +3640,8 @@ def _set_width(self, v): self._window.width = v def _set_height(self, v): self._window.height = v - def _set_size(self, (w,h)): + def _set_size(self, dimensions): + w, h = dimensions self.width = w self.height = h @@ -3722,7 +3735,8 @@ def _on_mouse_motion(self, x, y, dx, dy): layer = self.layer_at(x, y, enabled=True) # If the layer differs from the layer which currently has the focus, # or the mouse is not over any layer, remove the current focus. - if self._focus is not None and (self._focus != layer or not self._focus.contains(x,y)): + if self._focus is not None and (self._focus != layer or not self._focus.containspos): + x, y = pos self._focus.on_mouse_leave(self._mouse) self._focus.focus = False self._focus = None @@ -4131,4 +4145,4 @@ def ximport(library): #----------------------------------------------------------------------------------------------------- # Linear interpolation math for BezierPath.point() etc. -import bezier +import nodebox.graphics.bezier diff --git a/nodebox/graphics/geometry.py b/nodebox/graphics/geometry.py index 8052407..beb68a7 100644 --- a/nodebox/graphics/geometry.py +++ b/nodebox/graphics/geometry.py @@ -312,7 +312,8 @@ def __init__(self, x=0, y=0): def _get_xy(self): return (self.x, self.y) - def _set_xy(self, (x,y)): + def _set_xy(self, pos): + x, y = pos self.x = x self.y = y @@ -562,7 +563,7 @@ def _tessellate_error(code): while e[i]: s += chr(e[i]) i += 1 - raise TessellationError, s + raise TessellationError(s) _cache = {} diff --git a/nodebox/graphics/physics.py b/nodebox/graphics/physics.py index ec2a2cf..24a1339 100644 --- a/nodebox/graphics/physics.py +++ b/nodebox/graphics/physics.py @@ -66,7 +66,8 @@ def __setitem__(self, i, v): def _get_xyz(self): return (self.x, self.y, self.z) - def _set_xyz(self, (x,y,z)): + def _set_xyz(self, pos): + x, y, z = pos self.x = float(x) self.y = float(y) self.z = float(z) @@ -74,7 +75,8 @@ def _set_xyz(self, (x,y,z)): def _get_xy(self): return (self.x, self.y) - def _set_xy(self, (x,y)): + def _set_xy(self, pos): + x, y = pos self.x = float(x) self.y = float(y) xy = property(_get_xy, _set_xy) @@ -223,7 +225,7 @@ def cross(self, v): self.x*v.y - self.y*v.x) def __neg__(self): - return Vector(-self.x, -self.y, -self.z) + return Vector(-self.x, -self.y, -self.z) def __eq__(self, v): return isinstance(v, Vector) and self.x == v.x and self.y == v.y and self.z == v.z @@ -957,7 +959,7 @@ def deepcopy(o): return o.__class__(deepcopy(v) for v in o) if isinstance(o, dict): return dict((deepcopy(k), deepcopy(v)) for k,v in o.iteritems()) - raise Exception, "don't know how to copy %s" % o.__class__.__name__ + raise Exception("don't know how to copy " + str(o.__class__.__name__)) class Node(object): @@ -1212,7 +1214,7 @@ def __getitem__(self, id): try: return dict.__getitem__(self, id) except KeyError: - raise KeyError, "no node with id '%s' in graph" % id + raise KeyError("no node with id '" + str(id) + "' in graph") def append(self, base, *args, **kwargs): """ Appends a Node or Edge to the graph: Graph.append(Node, id="rabbit"). diff --git a/nodebox/graphics/shader.py b/nodebox/graphics/shader.py index 6f90cd5..9694220 100644 --- a/nodebox/graphics/shader.py +++ b/nodebox/graphics/shader.py @@ -5,13 +5,14 @@ # Copyright (c) 2008-2012 City In A Bottle (cityinabottle.org) # http://cityinabottle.org/nodebox -from pyglet.gl import * -from pyglet.image import Texture, SolidColorImagePattern -from context import Image, texture -from geometry import lerp, clamp -from math import radians -from ctypes import byref, cast, pointer, POINTER -from ctypes import c_char, c_char_p, c_uint, c_int +# TODO: Look over this import syntax, it doesn't look at all standard... +from pyglet.gl import * +from pyglet.image import Texture, SolidColorImagePattern +from math import radians +from ctypes import byref, cast, pointer, POINTER +from ctypes import c_char, c_char_p, c_uint, c_int +from nodebox.graphics.context import Image, texture +from nodebox.graphics.geometry import lerp, clamp def next(generator, default=None): try: @@ -268,7 +269,7 @@ def shader(vertex=DEFAULT_VERTEX_SHADER, fragment=DEFAULT_FRAGMENT_SHADER, silen return Shader(vertex, fragment) try: return Shader(vertex, fragment) - except Exception, e: + except Exception as e: SUPPORTED = False return ShaderFacade() @@ -976,7 +977,7 @@ def __init__(self, width, height): self.id = c_uint(_uid()) try: glGenFramebuffersEXT(1, byref(self.id)) except: - raise OffscreenBufferError, "offscreen buffer not supported." + raise OffscreenBufferError("offscreen buffer not supported.") self.texture = None self._viewport = (None, None, None, None) # The canvas bounds, set in OffscreenBuffer.push(). self._active = False @@ -1018,7 +1019,7 @@ def push(self): # Check after glBindFramebufferEXT() and glFramebufferTexture2DEXT(). if glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) != GL_FRAMEBUFFER_COMPLETE_EXT: msg = self.texture.width == self.texture.height == 0 and "width=0, height=0." or "" - raise OffscreenBufferError, msg + raise OffscreenBufferError(msg) # Separate the offscreen from the onscreen transform state. # Separate the offscreen from the onscreen canvas size. self._viewport = glCurrentViewport() @@ -1081,7 +1082,7 @@ def reset(self, width=None, height=None): between OffscreenBuffer.push() and OffscreenBuffer.pop() is retained. """ if self._active: - raise OffscreenBufferError, "can't reset offscreen buffer when active" + raise OffscreenBufferError("can't reset offscreen buffer when active") if width is None: width = self.width if height is None: diff --git a/nodebox/gui/controls.py b/nodebox/gui/controls.py index bee3aed..edcd0c4 100644 --- a/nodebox/gui/controls.py +++ b/nodebox/gui/controls.py @@ -155,7 +155,7 @@ def __getattr__(self, k): ctrl = nested(self, k) if ctrl is not None: return ctrl - raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, k) + raise AttributeError("'" + str(self.__class__.__name__) + "' object has no attribute '" + str(k) + "'") def __repr__(self): return "%s(id=%s%s)" % ( @@ -668,8 +668,8 @@ def on_mouse_doubleclick(self, mouse): self._editor.set_selection(i, i+1) if i == len(self.value) and self.value != "" and delimiter(self.value[i-1]): self._editor.set_selection(i-1, i) - a = _find(lambda (i,ch): delimiter(ch), enumerate(reversed(self.value[:i]))) - b = _find(lambda (i,ch): delimiter(ch), enumerate(self.value[i:])) + a = _find(lambda i,ch: delimiter(ch), enumerate(reversed(self.value[:i]))) + b = _find(lambda i,ch: delimiter(ch), enumerate(self.value[i:])) a = a and i-a[0] or 0 b = b and i+b[0] or len(self.value) self._editor.set_selection(a, b) @@ -1091,7 +1091,7 @@ def __getattr__(self, k): ctrl = nested(self, k) if ctrl is not None: return ctrl - raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, k) + raise AttributeError("'" + str(self.__class__.__name__) + "' object has no attribute '" + str(k) + "'") def apply(self): """ Adjusts the position and size of the controls to match the layout. diff --git a/nodebox/sound/osc.py b/nodebox/sound/osc.py index 7dde41e..61a9580 100755 --- a/nodebox/sound/osc.py +++ b/nodebox/sound/osc.py @@ -42,10 +42,10 @@ def hexDump(bytes): for i in range(len(bytes)): sys.stdout.write("%2x " % (ord(bytes[i]))) if (i+1) % 8 == 0: - print repr(bytes[i-7:i+1]) + print (repr(bytes[i-7:i+1])) if(len(bytes) % 8 != 0): - print string.rjust("", 11), repr(bytes[i-len(bytes)%8:i+1]) + print (string.rjust("", 11), repr(bytes[i-len(bytes)%8:i+1])) class OSCMessage: @@ -114,7 +114,7 @@ def readBlob(data): def readInt(data): if(len(data)<4): - print "Error: too few bytes for int", data, len(data) + print("Error: too few bytes for int", data, len(data)) rest = data integer = 0 else: @@ -137,7 +137,7 @@ def readLong(data): def readFloat(data): if(len(data)<4): - print "Error: too few bytes for float", data, len(data) + print("Error: too few bytes for float", data, len(data)) rest = data float = 0 else: @@ -191,7 +191,7 @@ def parseArgs(args): possible) as floats or integers.""" parsed = [] for arg in args: - print arg + print(arg) arg = arg.strip() interpretation = None try: @@ -232,7 +232,7 @@ def decodeOSC(data): value, rest = table[tag](rest) decoded.append(value) else: - print "Oops, typetag lacks the magic ," + print("Oops, typetag lacks the magic ,") return decoded @@ -267,15 +267,15 @@ def dispatch(self, message, source = None): for msg in message : self.dispatch(msg, source) - except KeyError, e: + except KeyError as e: # address not found - print 'address %s not found ' % address + print('address ' + str(address) + ' not found') pprint.pprint(message) - except IndexError, e: - print 'got malformed OSC message' + except IndexError as e: + print('got malformed OSC message') pass - except None, e: - print "Exception in", address, "callback :", e + except None as e: + print("Exception in", address, "callback :", e) return @@ -297,7 +297,7 @@ def unbundler(self, messages): if __name__ == "__main__": hexDump("Welcome to the OSC testing program.") - print + print() message = OSCMessage() message.setAddress("/foo/play") message.append(44) @@ -306,7 +306,7 @@ def unbundler(self, messages): message.append("the white cliffs of dover") hexDump(message.getBinary()) - print "Making and unmaking a message.." + print("Making and unmaking a message..") strings = OSCMessage() strings.append("Mary had a little lamb") @@ -321,26 +321,26 @@ def unbundler(self, messages): hexDump(raw) - print "Retrieving arguments..." + print("Retrieving arguments...") data = raw for i in range(6): text, data = readString(data) - print text + print(text) number, data = readFloat(data) - print number + print(number) number, data = readFloat(data) - print number + print(number) number, data = readInt(data) - print number + print(number) hexDump(raw) - print decodeOSC(raw) - print decodeOSC(message.getBinary()) + print(decodeOSC(raw)) + print(decodeOSC(message.getBinary())) - print "Testing Blob types." + print("Testing Blob types.") blob = OSCMessage() blob.append("","b") @@ -353,7 +353,7 @@ def unbundler(self, messages): hexDump(blob.getBinary()) - print decodeOSC(blob.getBinary()) + print(decodeOSC(blob.getBinary())) def printingCallback(*stuff): sys.stdout.write("Got: ") @@ -361,7 +361,7 @@ def printingCallback(*stuff): sys.stdout.write(str(i) + " ") sys.stdout.write("\n") - print "Testing the callback manager." + print("Testing the callback manager.") c = CallbackManager() c.add(printingCallback, "/print") @@ -388,7 +388,7 @@ def printingCallback(*stuff): bundlebinary = bundle.message - print "sending a bundle to the callback manager" + print("sending a bundle to the callback manager") c.handle(bundlebinary) diff --git a/nodebox/sound/process.py b/nodebox/sound/process.py index a67d441..e59ff73 100644 --- a/nodebox/sound/process.py +++ b/nodebox/sound/process.py @@ -227,11 +227,11 @@ def start(self): """ if self.patch is None \ or not os.path.exists(self.patch): - raise PDError, "no PD patch file at '%s'" % self.patch + raise PDError("no PD patch file at '" + str(self.patch) + "'") if not self._path: - raise PDError, "no PD application found" + raise PDError("no PD application found") if not os.path.exists(self._path): - raise PDError, "no PD application at '%s'" % self._path + raise PDError("no PD application at '" + str(self._path) + "'") if not self._process: self._process = Process(program=self._path, options=self._options)