<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>/dev/stu</title>
	<atom:link href="http://www.stuartaxon.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.stuartaxon.com</link>
	<description>Adding LOC to the web.</description>
	<lastBuildDate>Sat, 06 Apr 2013 13:57:02 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Shoebot experiment &#8211; perlin noise..</title>
		<link>http://www.stuartaxon.com/2013/04/05/shoebot-experiment-perlin-noise/</link>
		<comments>http://www.stuartaxon.com/2013/04/05/shoebot-experiment-perlin-noise/#comments</comments>
		<pubDate>Fri, 05 Apr 2013 18:22:44 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=362</guid>
		<description><![CDATA[Perlin noise is pretty cool, you can use it to generate realistic looking clouds or mountains. Here&#8217;s a bot for shoebot I made a while back that uses perlin noise to generate some nice circles. You&#8217;ll need shoebot and the &#8230; <a href="http://www.stuartaxon.com/2013/04/05/shoebot-experiment-perlin-noise/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Perlin noise is pretty cool, you can use it to generate realistic looking clouds or mountains.</p>
<p>Here&#8217;s a bot for shoebot I made a while back that uses perlin noise to generate some nice circles.</p>
<p>You&#8217;ll need shoebot and the lib &#8220;noise&#8221; installed into your environment for it to work;</p>
<pre class="brush:shell">
# pip install noise
</pre>
<p>Then to run;</p>
<pre class="brush:shell">
sbot -w perlin-circlescape1.bot
</pre>
<p>Here&#8217;s a video of them in action -<br />
<iframe width="420" height="315" src="http://www.youtube.com/embed/Jx76QZaxTO4" frameborder="0" allowfullscreen></iframe></p>
<p>See below the break for the code -<br />
<span id="more-362"></span></p>
<pre class="brush:python">
import noise

size(1000,1000)
speed(60)

colormode(HSB)

def setup():
    global origx, origy
    origx = 0
    origy = 0    

rows = 8
cols = 9
gap = 100

def draw():
    global origx, origy, gap

    # black background
    background(0)

    # start from 100,100
    translate(100,100)
    # and draw the blocks
    mx = float(1.0 / WIDTH) * (-MOUSEX - (-WIDTH / 2))
    my = float(1.0 / HEIGHT) * (-MOUSEY - (-HEIGHT / 2))
    
    origx += (mx / 8.0)
    origy += (my / 8.0)
    for gx,gy in grid(rows,cols,1,1):
        # height of each block is determined by x,y coordinates
        n = (noise.pnoise2(float(origx + (gx / 10.0)), float(origy + (gy / 10.0)), 2) / cols)
        diam = 50 + (n * 600.0)
        s = (n * 10.0)
        fill(0.1, 1.0 - s, 1)
        x = gx * gap
        y = gy * gap
        oval(x - diam / 2, y - diam / 2, diam, diam)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2013/04/05/shoebot-experiment-perlin-noise/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Animated skulls &#8211; processingjs</title>
		<link>http://www.stuartaxon.com/2013/03/22/animated-skulls-processingjs/</link>
		<comments>http://www.stuartaxon.com/2013/03/22/animated-skulls-processingjs/#comments</comments>
		<pubDate>Fri, 22 Mar 2013 09:30:03 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[creativecoding]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=349</guid>
		<description><![CDATA[Here&#8217;s a little creative coding I did with processingjs a while back. Move the mouse to move the skulls.]]></description>
				<content:encoded><![CDATA[<p>Here&#8217;s a little creative coding I did with processingjs a while back.   Move the mouse to move the skulls.</p>
<p><iframe width="620" height="650" scrolling=no src="http://jsfiddle.net/DCnHF/15/embedded/result/" allowfullscreen="allowfullscreen" frameborder="0"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2013/03/22/animated-skulls-processingjs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Moving things in shoebot &#8211; simple particles&#8230;</title>
		<link>http://www.stuartaxon.com/2013/03/20/natural-movement-in-python-part-3-particles/</link>
		<comments>http://www.stuartaxon.com/2013/03/20/natural-movement-in-python-part-3-particles/#comments</comments>
		<pubDate>Wed, 20 Mar 2013 10:00:32 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[creativecoding]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=331</guid>
		<description><![CDATA[OK, part 3 &#8211; now for something fun &#8211; extending parts 1 + 2 into a simple particle system. Particles, generally means &#8211; a lot of things moving around (the particles) and a way to generate them, an &#8220;emitter&#8221; Here &#8230; <a href="http://www.stuartaxon.com/2013/03/20/natural-movement-in-python-part-3-particles/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>OK, part 3 &#8211; now for something fun &#8211; extending parts 1 + 2 into a simple particle system.</p>
<p>Particles, generally means &#8211; a lot of things moving around (the particles) and a way to generate them, an &#8220;emitter&#8221;</p>
<p>Here we&#8217;re going to take the code from the previous two parts and add a couple of things to make a basic particle system.<br />
Note &#8211; shoebot, isn&#8217;t the fastest; but we do get nice looking results.</p>
<p>Here&#8217;s a video of our arrows as particles (arrowsplosion!):<br />
<iframe width="560" height="315" src="http://www.youtube.com/embed/SWoe_cqBZZ0" frameborder="0" allowfullscreen></iframe></p>
<p><span id="more-331"></span></p>
<p>So the parts needed are the bits that move &#8216;particles&#8217;, this is made by extending the Moveable class to give it an hp, some functions to manage the list of particles (when their hp goes below 0 they are removed from the list).</p>
<pre class="brush:python">
class Particle(Moveable):
    def __init__(self, hp = 250, **kwargs):
        Moveable.__init__(self, draw_func = self.draw_func, **kwargs)
        self.hp = hp

    def update(self):
        super(Particle, self).update()
        self.hp -=1
        return self.hp > 0

    def draw_func(self):
        a = 1.0
        if 0 < self.hp < 250:
           a = self.hp / 250.0
        arrow(0, 0, 80, fill=(1, 0, 0, a))
</pre>
<p>The last part is particle creation, we create a function random_emitter, this just adds a particle to the list of particles.</p>
<pre class="brush:python">
def random_emitter(particles):
    if random() > 0.1:
        p = Particle(
            velocity = random() * 2.0,
            angle = random() * 360,
            controller = inertia_controller)
        particles.append(p)
</pre>
<p>the draw function is modified to call these:</p>
<pre class="brush: python">
def update_particles(particles):
    '''
    Update particles
    
    return: list of particles to update
    '''
    part = []
    for p in particles:
        if p.update():
            part.append(p)
    return part

def draw():
    global particles

    random_emitter(particles)
    particles = update_particles(particles)

    for p in particles:
        p.draw()
</pre>
<p>Complete listing.</p>
<pre class="brush:python">
from random import random

from planar.py import Vec2, Affine
from collections import namedtuple


class Moveable(object):
    """
    Moveable object.

    Controller functions manage the movement and are called on 'update'
    """
    def __init__(self, pos = None, velocity = None, angle = None, controller = None, controllers = None, draw_func = None):
        self.pos = pos or Vec2(WIDTH / 2, HEIGHT / 2)
        self.velocity = velocity or 0.0
        self.angle = angle or 0
        self.draw_func = draw_func
        if controller:
            self.controllers = [ controller ]
        else:
            self.controllers = []
        if controllers:
            self.controllers.extend(controllers)

    def update(self):
        """
        Call all the controllers to update coordinates.
        
        Angles are always wrapped to 360 degrees.
        """
        pos, angle, velocity = self.pos, self.angle, self.velocity
        for controller in self.controllers:
            pos, angle, velocity = controller(pos, angle % 360, velocity)
        self.pos, self.angle, self.velocity = pos, angle % 360, velocity
        self.pos += Vec2.polar(angle = angle, length = velocity)

    def draw(self):
        push()
        translate(self.pos.x, self.pos.y)
        rotate(-self.angle) # nodebox1/shoebot rotation is anticlockwise
        self.draw_func()
        pop()



class Particle(Moveable):
    def __init__(self, hp = 250, **kwargs):
        Moveable.__init__(self, draw_func = self.draw_func, **kwargs)
        self.hp = hp

    def update(self):
        super(Particle, self).update()
        self.hp -=1
        return self.hp > 0

    def draw_func(self):
        a = 1.0
        if 0 < self.hp < 250:
           a = self.hp / 250.0
        arrow(0, 0, 80, fill=(1, 0, 0, a))



def key_controller(pos, angle, velocity):
    if keydown:
        if keycode == KEY_UP:
            velocity += 0.2
        elif keycode == KEY_DOWN:
            velocity -= 0.2
        elif keycode == KEY_LEFT:
            angle -= 5
        elif keycode == KEY_RIGHT:
            angle += 5
        elif keycode == KEY_SPACE:
            velocity *= 0.9
        elif keycode == KEY_RETURN:
            pos = Vec2(WIDTH / 2, HEIGHT / 2)
            velocity = 0.0
            angle = 0
    return pos, angle, velocity


def inertia_controller(pos, angle, velocity):
    return pos, angle, velocity * 0.99


def bounds_controller(pos, angle, velocity):
    if pos.x < 10 or pos.x > WIDTH:
        angle = 180 - angle
    if pos.y < 10 or pos.y > HEIGHT - 10:
        angle = - angle
    return pos, angle, velocity



def random_emitter(particles):
    if random() > 0.1:
        p = Particle(
            velocity = random() * 2.0,
            angle = random() * 360,
            controller = inertia_controller)
        particles.append(p)


def update_particles(particles):
    '''
    Update particles
    
    return: list of particles to update
    '''
    part = []
    for p in particles:
        if p.update():
            part.append(p)
    return part



def setup():
    global particles
    speed(60)
    size(800, 600)
    transform(mode=CENTER)

    particles = []
    

def draw():
    global particles

    random_emitter(particles)
    particles = update_particles(particles)

    for p in particles:
        p.draw()
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2013/03/20/natural-movement-in-python-part-3-particles/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Moving things in shoebot, adding different behaviours..</title>
		<link>http://www.stuartaxon.com/2013/03/19/moving-things-in-shoebot-adding-different-behaviours/</link>
		<comments>http://www.stuartaxon.com/2013/03/19/moving-things-in-shoebot-adding-different-behaviours/#comments</comments>
		<pubDate>Tue, 19 Mar 2013 15:59:38 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[creativecoding]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=326</guid>
		<description><![CDATA[In my last post we made an arrow move around the screen, in this post we&#8217;ll look to extend things so it&#8217;s easy to make many things move around the screen. This will make the code a little more complex, &#8230; <a href="http://www.stuartaxon.com/2013/03/19/moving-things-in-shoebot-adding-different-behaviours/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>In my last post we made an arrow move around the screen, in this post we&#8217;ll look to extend things so it&#8217;s easy to make many things move around the screen.</p>
<p>This will make the code a little more complex, but as usual it makes things simpler later on.</p>
<p>Note:</p>
<p>This python code runs in shoebot, planar.py is used to handle coordinates</p>
<p>https://github.com/shoebot</p>
<p>planar.py</p>
<p>At the end we&#8217;ll have two arrows, a blue one controlled with the keyboard and a pink one that moves on it&#8217;s own:<br />
<iframe width="560" height="315" src="http://www.youtube.com/embed/pnVd_4vX5o4" frameborder="0" allowfullscreen></iframe></p>
<p><span id="more-326"></span><br />
At the moment all movement behaviour is in the draw function (see below) &#8211; we&#8217;re going to move all the movement behaviour into seperate functions.</p>
<p>Current draw function:</p>
<pre class="brush:python>
def draw():
    global pos, angle, velocity
    transform(mode=CENTER)
    if keydown:
        if keycode == KEY_UP:
            velocity += 0.2
        elif keycode == KEY_DOWN:
            velocity -= 0.2
        elif keycode == KEY_LEFT:
            angle -= 5
        elif keycode == KEY_RIGHT:
            angle += 5
        elif keycode == KEY_SPACE:
            velocity *= 0.9
        elif keycode == KEY_RETURN:
            pos = Vec2(WIDTH / 2, HEIGHT / 2)
            velocity = 0.0
            angle = 0
    else:
        velocity *= 0.99
    
    angle = angle % 360
    pos += Vec2.polar(angle = angle, length = velocity)
    
    if pos.x < 10 or pos.x > WIDTH:
        angle = 180 - angle
    if pos.y < 10 or pos.y > HEIGHT - 10:
        angle = - angle

    translate(pos.x, pos.y)
    rotate(-angle) # nodebox1/shoebot rotation is anticlockwise

    arrow(40, 40, 80, fill=(0, 0, 1, 0.2))
</pre>
<p>We&#8217;ll seperate each behaviour into a &#8216;controller&#8217; function:</p>
<pre class="brush:python">
def key_controller(pos, angle, velocity):
    if keydown:
        if keycode == KEY_UP:
            velocity += 0.2
        elif keycode == KEY_DOWN:
            velocity -= 0.2
        elif keycode == KEY_LEFT:
            angle -= 5
        elif keycode == KEY_RIGHT:
            angle += 5
        elif keycode == KEY_SPACE:
            velocity *= 0.9
        elif keycode == KEY_RETURN:
            pos = Vec2(WIDTH / 2, HEIGHT / 2)
            velocity = 0.0
            angle = 0
    return pos, angle, velocity


def inertia_controller(pos, angle, velocity):
    return pos, angle, velocity * 0.99


def bounds_controller(pos, angle, velocity):
    if pos.x < 10 or pos.x > WIDTH:
        angle = 180 - angle
    if pos.y < 10 or pos.y > HEIGHT - 10:
        angle = - angle
    return pos, angle, velocity
</pre>
<p>Then make a class to manage these, along with initial position + velocity &#8211; along with a custom drawing function:</p>
<pre class="brush:python">
class Moveable(object):
    """
    Moveable object.

    Controller functions manage the movement and are called on 'update'
    """
    def __init__(self, pos = None, velocity = None, angle = None, controller = None, controllers = None, draw_func = None):
        self.pos = pos or Vec2(WIDTH / 2, HEIGHT / 2)
        self.velocity = velocity or 0.0
        self.angle = angle or 0
        self.draw_func = draw_func
        if controller:
            self.controllers = [ controller ]
        else:
            self.controllers = []
        if controllers:
            self.controllers.extend(controllers)

    def update(self):
        """
        Call all the controllers to update coordinates.
        
        Angles are always wrapped to 360 degrees.
        """
        pos, angle, velocity = self.pos, self.angle, self.velocity
        for controller in self.controllers:
            pos, angle, velocity = controller(pos, angle % 360, velocity)
        self.pos, self.angle, self.velocity = pos, angle % 360, velocity
        self.pos += Vec2.polar(angle = angle, length = velocity)

    def draw(self):
        push()
        translate(self.pos.x, self.pos.y)
        rotate(-self.angle) # nodebox1/shoebot rotation is anticlockwise
        self.draw_func()
        pop()
</pre>
<p>Since I just want the draw function to draw two different colour arrows, a closure is used to generate these functions:</p>
<pre class="brush:python">
def draw_arrow(fill=None):
    def do_draw():
        arrow(40, 40, 80, fill=fill)
    return do_draw
</pre>
<p>By passing the output of draw_func = draw_arrow(fill=(1,0,0)) a red arrow is will be drawn every time &#8216;draw_func&#8217; is called.</p>
<p>Using all of the above, the setup() function to create the two arrows is fairly straightforward:</p>
<pre class="brush:python">
def setup():
    global auto_arrow, driven_arrow
    speed(60)
    size(800, 600)
    transform(mode=CENTER)
    driven_arrow = Moveable(
        controllers = [key_controller, bounds_controller, inertia_controller], 
        draw_func = draw_arrow(fill=(0, 0, 1, 0.2)))

    auto_arrow = Moveable(
        velocity = 5.0,
        angle = 45,
        controller = bounds_controller,
        draw_func = draw_arrow(fill=(1, 0, 0, 0.2)))
</pre>
<p>driven_arrow and auto_arrow are both instances of &#8216;Moveable&#8217;, they have different behaviours set by their controller functions and their draw functions will draw them in a transparent red and blue colours.</p>
<p>The final draw function, simply calls &#8216;update&#8217; and &#8216;draw&#8217; on auto_arrow and driven_arrow:</p>
<pre class="brush:python">
def draw():
    global auto_arrow, driven_arrow

    driven_arrow.update()
    auto_arrow.update()

    driven_arrow.draw()
    auto_arrow.draw()
</pre>
<p>Using this system it&#8217;s easy to add custom behaviours (controllers) and drawing functions.</p>
<p>This can be extended into a simple particle system &#8211; Particle is just a Moveable with a lifecycle and a factory function (emitter) needs to be added to create the particles, along with a little management code.</p>
<p>Next time &#8211; extending this into a simple particle system.</p>
<p>Full listing:</p>
<pre class="brush:python">
# In this version of the file the concept of a controller is introduced.
#
# A controller takes the position, angle and velocity of the thing to be moved
# and returns a new position, angle and velocity.
#
# The machinery to manage this is wrapper up in the Movable class

from planar.py import Vec2, Affine
from collections import namedtuple


class Moveable(object):
    """
    Moveable object.

    Controller functions manage the movement and are called on 'update'
    """
    def __init__(self, pos = None, velocity = None, angle = None, controller = None, controllers = None, draw_func = None):
        self.pos = pos or Vec2(WIDTH / 2, HEIGHT / 2)
        self.velocity = velocity or 0.0
        self.angle = angle or 0
        self.draw_func = draw_func
        if controller:
            self.controllers = [ controller ]
        else:
            self.controllers = []
        if controllers:
            self.controllers.extend(controllers)

    def update(self):
        """
        Call all the controllers to update coordinates.
        
        Angles are always wrapped to 360 degrees.
        """
        pos, angle, velocity = self.pos, self.angle, self.velocity
        for controller in self.controllers:
            pos, angle, velocity = controller(pos, angle % 360, velocity)
        self.pos, self.angle, self.velocity = pos, angle % 360, velocity
        self.pos += Vec2.polar(angle = angle, length = velocity)

    def draw(self):
        push()
        translate(self.pos.x, self.pos.y)
        rotate(-self.angle) # nodebox1/shoebot rotation is anticlockwise
        self.draw_func()
        pop()



def key_controller(pos, angle, velocity):
    if keydown:
        if keycode == KEY_UP:
            velocity += 0.2
        elif keycode == KEY_DOWN:
            velocity -= 0.2
        elif keycode == KEY_LEFT:
            angle -= 5
        elif keycode == KEY_RIGHT:
            angle += 5
        elif keycode == KEY_SPACE:
            velocity *= 0.9
        elif keycode == KEY_RETURN:
            pos = Vec2(WIDTH / 2, HEIGHT / 2)
            velocity = 0.0
            angle = 0
    return pos, angle, velocity


def inertia_controller(pos, angle, velocity):
    return pos, angle, velocity * 0.99


def bounds_controller(pos, angle, velocity):
    if pos.x < 10 or pos.x > WIDTH:
        angle = 180 - angle
    if pos.y < 10 or pos.y > HEIGHT - 10:
        angle = - angle
    return pos, angle, velocity




def draw_arrow(fill=None):
    def do_draw():
        arrow(40, 40, 80, fill=fill)
    return do_draw


def setup():
    global auto_arrow, driven_arrow
    speed(60)
    size(800, 600)
    transform(mode=CENTER)
    driven_arrow = Moveable(
        controllers = [key_controller, bounds_controller, inertia_controller], 
        draw_func = draw_arrow(fill=(0, 0, 1, 0.2)))

    auto_arrow = Moveable(
        velocity = 5.0,
        angle = 45,
        controller = bounds_controller,
        draw_func = draw_arrow(fill=(1, 0, 0, 0.2)))


def draw():
    global auto_arrow, driven_arrow

    driven_arrow.update()
    auto_arrow.update()

    driven_arrow.draw()
    auto_arrow.draw()
</pre>
<p>Running in shoebot:</p>
<pre class="brush:bash">
sbot -w arrow_controlled.bot
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2013/03/19/moving-things-in-shoebot-adding-different-behaviours/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Natural movement using polar coordinates in shoebot</title>
		<link>http://www.stuartaxon.com/2013/03/18/natural-movement-using-polar-coordinates-in-shoebot/</link>
		<comments>http://www.stuartaxon.com/2013/03/18/natural-movement-using-polar-coordinates-in-shoebot/#comments</comments>
		<pubDate>Mon, 18 Mar 2013 15:06:15 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[creativecoding]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=321</guid>
		<description><![CDATA[Here&#8217;s a little shoebot bot to experiment with natural movement. This uses polar coordinates to decide the direction and velocity of an arrow on the screen. Polar coordinates mean we can give an object a sense of &#8216;forward&#8217;, &#8216;back&#8217;, &#8216;left&#8217; &#8230; <a href="http://www.stuartaxon.com/2013/03/18/natural-movement-using-polar-coordinates-in-shoebot/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Here&#8217;s a little shoebot bot to experiment with natural movement.</p>
<p>This uses polar coordinates to decide the direction and velocity of an arrow on the screen.</p>
<p>Polar coordinates mean we can give an object a sense of &#8216;forward&#8217;, &#8216;back&#8217;, &#8216;left&#8217; and &#8216;right&#8217;</p>
<p><iframe src="http://www.youtube.com/embed/KnpCUUtCT4c" height="315" width="560" allowfullscreen="" frameborder="0"></iframe></p>
<p>The code below works on the current version of shoebot</p>
<p>https://github.com/shoebot/shoebot.git</p>
<p>With planar.py to handle the directions and velocity</p>
<p>https://pypi.python.org/pypi/planar</p>
<p><span id="more-321"></span><br />
There&#8217;s some code to handle edges (the arrow will bounce off the edges). Also, since the nodebox grammar which we are using does anticlockwise rotations we need to handle this.</p>
<pre class="brush:python"># Use cursor keys to move arrow
# space is a brake, return resets

from planar.py import Vec2, Affine

def setup():
    global pos, angle, velocity
    speed(60)
    size(800, 600)
    pos = Vec2(WIDTH / 2, HEIGHT / 2)
    velocity = 0.0
    angle = 0

def draw():
    global pos, angle, velocity
    transform(mode=CENTER)
    if keydown:
        if keycode == KEY_UP:
            velocity += 0.2
        elif keycode == KEY_DOWN:
            velocity -= 0.2
        elif keycode == KEY_LEFT:
            angle -= 5
        elif keycode == KEY_RIGHT:
            angle += 5
        elif keycode == KEY_SPACE:
            velocity *= 0.9
        elif keycode == KEY_RETURN:
            pos = Vec2(WIDTH / 2, HEIGHT / 2)
            velocity = 0.0
            angle = 0
    else:
        velocity *= 0.99

    angle = angle % 360
    pos += Vec2.polar(angle = angle, length = velocity)

    if pos.x &lt; 10 or pos.x &gt; WIDTH:
        angle = 180 - angle
    if pos.y &lt; 10 or pos.y &gt; HEIGHT - 10:
        angle = - angle

    translate(pos.x, pos.y)
    rotate(-angle) # nodebox1/shoebot rotation is anticlockwise

    arrow(40, 40, 80, fill=(0, 0, 1, 0.2))</pre>
<p>Running the code in shoebot:</p>
<pre class="brush:bash">sbot -w arrow_drive.bot.</pre>
<p>This has basic movement, + intertia, it can be used for a number of things (e.g. 2d games)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2013/03/18/natural-movement-using-polar-coordinates-in-shoebot/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding files to the django auto refresh</title>
		<link>http://www.stuartaxon.com/2012/05/10/adding-files-to-the-django-auto-refresh/</link>
		<comments>http://www.stuartaxon.com/2012/05/10/adding-files-to-the-django-auto-refresh/#comments</comments>
		<pubDate>Thu, 10 May 2012 09:34:52 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[troubleshooting]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[postgres]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=304</guid>
		<description><![CDATA[Django runserver and the app django-autotest are both good as they&#8217;ll restart when modifcations are made to files in the app they will restart, however not *all* files will trigger a restart. Wanting to get some other files noticed, I &#8230; <a href="http://www.stuartaxon.com/2012/05/10/adding-files-to-the-django-auto-refresh/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Django runserver and the app django-autotest are both good as they&#8217;ll restart when modifcations are made to files in the app they will restart, however not *all* files will trigger a restart.</p>
<p>Wanting to get some other files noticed, I added some in the __init__.py of my app, so it looked like this:</p>
<pre class="brush:python">try:
    from django.conf import settings

    if settings.DEBUG:
        import forms, util, tests
except:
    pass</pre>
<p>This seemed to be working fine until I swapped to postgres and tried to do syncdb .. and reset, uh oh !</p>
<p>Postgres said (names changed to protect the innocent):</p>
<pre class="brush:sql">2012-05-10 09:47:57 BST STATEMENT:
                    SELECT c.relname
                    FROM pg_catalog.pg_class c
                    LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
                    WHERE c.relkind IN ('r', 'v', '')
                        AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
                        AND pg_catalog.pg_table_is_visible(c.oid)
2012-05-10 09:47:57 BST LOG:  could not receive data from client: Connection reset by peer
2012-05-10 09:47:57 BST LOG:  unexpected EOF on client connection
2012-05-10 09:49:14 BST ERROR:  relation "sandwich_maker_filling" does not exist at character 72
2012-05-10 09:49:14 BST STATEMENT:  SELECT "sandwich_maker_filling"."id", "sandwich_maker_filling"."name" FROM "sandwich_maker_filling"
2012-05-10 09:49:14 BST ERROR:  current transaction is aborted, commands ignored until end of transaction block</pre>
<p>And django wasn&#8217;t too happy either:</p>
<pre>Traceback (most recent call last):
  File "manage.py", line 10, in &lt;module&gt;
    execute_from_command_line(sys.argv)
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
    utility.execute()
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute
    output = self.handle(*args, **options)
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/core/management/base.py", line 371, in handle
    return self.handle_noargs(**options)
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 60, in handle_noargs
    tables = connection.introspection.table_names()
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 896, in table_names
    return self.get_table_list(cursor)
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/introspection.py", line 33, in get_table_list
    AND pg_catalog.pg_table_is_visible(c.oid)""")
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/db/backends/util.py", line 40, in execute
    return self.cursor.execute(sql, params)
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 52, in execute
    return self.cursor.execute(query, args)
django.db.utils.DatabaseError: current transaction is aborted, commands ignored until end of transaction block</pre>
<p>In the end the solution was simple, just check for the args where we need the refresh to happen automatically:</p>
<pre class="brush:python">## Automatically reload when forms or tests changed
try:
    from django.conf import settings

    if settings.DEBUG:
        import sys
        if sys.argv == ['manage.py', 'autotest'] or sys.argv == ['manage.py', 'runserver']:
                # Need to check params as otherwise this can break syncdb, reset and
                # Friends !!
                import forms, util, tests
except:
    pass</pre>
<p>Hopefully this will be helpful to somebody with a similar error or that wants autotest or runserver to see more files.<br />
&nbsp;</p>
<p>This article was particularly helpful in debugging this:  <a title="Debugging django syncdb" href="http://linfiniti.com/2010/03/debugging-django-syncdb/">debugging django syncdb</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2012/05/10/adding-files-to-the-django-auto-refresh/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cairo with python Ctypes</title>
		<link>http://www.stuartaxon.com/2012/01/09/cairo-with-python-ctypes/</link>
		<comments>http://www.stuartaxon.com/2012/01/09/cairo-with-python-ctypes/#comments</comments>
		<pubDate>Mon, 09 Jan 2012 18:11:32 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=299</guid>
		<description><![CDATA[Uploaded some experiments with python and ctypes to here: https://gitorious.org/pycairo-ctypes/pycairo-ctypes &#160; This is a really rough proof of concept that the pycairo API can be implemented with ctypes + metclasses. &#160; &#160; So far only ImageSurface is supported on the &#8230; <a href="http://www.stuartaxon.com/2012/01/09/cairo-with-python-ctypes/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Uploaded some experiments with python and ctypes to here:</p>
<p><a href="https://gitorious.org/pycairo-ctypes/pycairo-ctypes">https://gitorious.org/pycairo-ctypes/pycairo-ctypes</a></p>
<p>&nbsp;</p>
<p>This is a really rough proof of concept that the pycairo API can be implemented with ctypes + metclasses.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>So far only ImageSurface is supported on the SVG backend, along with Contexts.   The nice thing about this is that you can use a pycairo like API on pypy, where things should be faster (in theory).</p>
<p>&nbsp;</p>
<p>There&#8217;s a test that can be run to show the outputs the same for pycairo and cairo ctypes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2012/01/09/cairo-with-python-ctypes/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Using PyCha with Django</title>
		<link>http://www.stuartaxon.com/2011/02/25/using-pycha-with-django/</link>
		<comments>http://www.stuartaxon.com/2011/02/25/using-pycha-with-django/#comments</comments>
		<pubDate>Fri, 25 Feb 2011 00:10:50 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[cairo]]></category>
		<category><![CDATA[charting]]></category>
		<category><![CDATA[charts]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[pycha]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=290</guid>
		<description><![CDATA[A quick post on using Python Charts to generate nice SVG charts for your django website (I&#8217;ve had the code hanging around for ages &#8211; so should just post it). The code is based on the examples there, here I &#8230; <a href="http://www.stuartaxon.com/2011/02/25/using-pycha-with-django/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>A quick post on using <a href="http://bitbucket.org/lgs/pycha/">Python Charts</a> to generate nice SVG charts for your django website (I&#8217;ve had the code hanging around for ages &#8211; so should just post it).  The code is based on the examples there, here I integrate it into Django.</p>
<p>To install you&#8217;ll need to do</p>
<pre>pip install pycha</pre>
<p>Heres the code for a simple view to output a chart directly to SVG:</p>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2011/02/linechart.png"><img class="alignnone size-full wp-image-291" title="linechart" src="http://www.stuartaxon.com/wp-content/uploads/2011/02/linechart.png" alt="" width="401" height="316" /></a></p>
<pre class="brush:python"># views.py

from StringIO import StringIO
from django.http import HttpResponse

import cairo

def colors(request):
    in_req = 1

    svg_buffer = StringIO()

    width, height = (500, 400)
    surface = cairo.SVGSurface(svg_buffer, width, height)

    dataSet = (
     ('dataSet 1', ((0, 1), (1, 3), (2, 2.5))),
     ('dataSet 2', ((0, 2), (1, 4), (2, 3))),
     ('dataSet 3', ((0, 5), (1, 1), (2, 0.5))),
    )

    options = {
       'legend': {'hide': True},
       'background': {'color': '#f0f0f0'},
    }

    #import pycha.bar
    #chart = pycha.bar.VerticalBarChart(surface, options)

    import pycha.line
    chart = pycha.line.LineChart(surface, options)
    chart.addDataset(dataSet)
    chart.render()

    del chart
    del surface

    response = ''
    response = HttpResponse(mimetype='image/svg+xml')
    svg_buffer.seek(0)
    response.write( svg_buffer.read() )
    return response
</pre>
<p>The basic idea is that &#8211; instead of the chart outputting to an svg file, the output goes to a buffer, this is triggered by calling the destructors of the chart and it&#8217;s cairo surface.  Once the data is in the buffer, it is rewound and played back to the Http Response.</p>
<p>&nbsp;</p>
<h2>Inline SVG</h2>
<p>As is, this won&#8217;t work as inline svg, because outputting the XML preamble in the middle of the page will cause problems.  Below is an example that let&#8217;s you decide if you need the preamble (full SVG output), or not (SVG fragment for inclusion in a page or another SVG):</p>
<pre class="brush:python"># Create your views here.

from StringIO import StringIO
from django.http import HttpResponse
from django.shortcuts import render_to_response

import cairo

XML_PREAMBLE = '&lt;?xml version="1.0" encoding="UTF-8"?&gt;'

def colors_chart(inline = False):
    """
    Generate colours chart

    Set inline to True to disable the XML preamble
    """
    in_req = 1

    svg_buffer = StringIO()

    width, height = (500, 400)
    surface = cairo.SVGSurface(svg_buffer, width, height)

    dataSet = (
     ('dataSet 1', ((0, 1), (1, 3), (2, 2.5))),
     ('dataSet 2', ((0, 2), (1, 4), (2, 3))),
     ('dataSet 3', ((0, 5), (1, 1), (2, 0.5))),
    )

    options = {
       'legend': {'hide': True},
       'background': {'color': '#f0f0f0'},
    }

    import pycha.bar
    chart = pycha.bar.VerticalBarChart(surface, options)

    #import pycha.line
    #chart = pycha.line.LineChart(surface, options)
    chart.addDataset(dataSet)
    chart.render()

    del chart
    del surface

    response = ''

    if inline:
        svg_buffer.seek(len(XML_PREAMBLE))
    else:
        svg_buffer.seek(0)
    return svg_buffer.read()

def colors_svg(request):
    """ render a pure SVG chart """
    response = HttpResponse(mimetype='image/svg+xml')
    response.write(colors_chart(inline = False))
    return response

def index(request):
    """ render a chart into the template """
    chart_svg = colors_chart(inline = True)

    return render_to_response(
        'shapes_index.html',
        { "chart" : chart_svg },
        mimetype='application/xhtml+xml')
</pre>
<p>An example project with the above code is available here:<br />
<a href="http://www.stuartaxon.com/wp-content/uploads/2011/02/pycha_django.zip">pycha_django</a></p>
<p>&nbsp;</p>
<p>[EDIT 25/2/2011] Fixed PyCha URL</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2011/02/25/using-pycha-with-django/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title></title>
		<link>http://www.stuartaxon.com/2010/09/30/281/</link>
		<comments>http://www.stuartaxon.com/2010/09/30/281/#comments</comments>
		<pubDate>Thu, 30 Sep 2010 23:59:21 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=281</guid>
		<description><![CDATA[[EDIT: 2010/10/05] Oops, I&#8217;ve been using TCC/LE by JPSoft as my shell&#8230; the following doesn&#8217;t work in the normal command prompt [/EDIT] I just had a look at SET and it lets you set user/system variables: Display, create, modify, or &#8230; <a href="http://www.stuartaxon.com/2010/09/30/281/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>[EDIT: 2010/10/05]</p>
<p>Oops, I&#8217;ve been using TCC/LE by JPSoft as my shell&#8230; the following doesn&#8217;t work in the normal command prompt</p>
<p>[/EDIT]</p>
<p>I just had a look at SET and it lets you set user/system variables:</p>
<pre>Display, create, modify, or delete environment variables.

<span style="color: #404040;"><span style="color: #000000;">SET</span> [/A /D /E /P /R file... /S /U /V /X] [name[=][value ]]
        file:  One or more files containing variable definitions
        /A(rithmetic)           <span style="color: #000000;">/S(ystem variables)</span>
        /D(efault variables)    <span style="color: #000000;">/U(ser variables)
</span>        /E(nv vars)             /V(olatile variables)
        /R(ead from file)       /X override VariableExclude
        /P(ause)</span></pre>
<p>So to set save a variables MYAPP_HOME as the current directory, just do</p>
<pre>SET /U MYAPP_HOME=%CD</pre>
<p>Wish I&#8217;d have looked that up a few years ago, it&#8217;ll save a few seconds next time I need to setup some dev sdk <img src='http://www.stuartaxon.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/09/30/281/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple python spectrograph with shoebot</title>
		<link>http://www.stuartaxon.com/2010/05/17/shoebot-spectrograph/</link>
		<comments>http://www.stuartaxon.com/2010/05/17/shoebot-spectrograph/#comments</comments>
		<pubDate>Mon, 17 May 2010 20:14:02 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[audio]]></category>
		<category><![CDATA[fft spectrograph]]></category>
		<category><![CDATA[nodebox]]></category>
		<category><![CDATA[portaudio]]></category>
		<category><![CDATA[pyaudio]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[shoebot]]></category>
		<category><![CDATA[visualisation]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=264</guid>
		<description><![CDATA[Seeing&#8221;Realtime FFT Graph of Audio WAV File or Microphone Input with Python&#8230;&#8221;  on python.reddit.com reminded me of one I&#8217;d built in python with shoebot. While it works OK, I feel like I&#8217;m missing a higher level audio library (especially having &#8230; <a href="http://www.stuartaxon.com/2010/05/17/shoebot-spectrograph/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Seeing&#8221;<a title="Permanent Link: Realtime FFT Graph of Audio WAV  File or Microphone Input with Python, Scipy, and WCKgraph" rel="bookmark" href="http://www.swharden.com/blog/2010-03-05-realtime-fft-graph-of-audio-wav-file-or-microphone-input-with-python-scipy-and-wckgraph/">Realtime FFT Graph of Audio WAV File or Microphone Input  with Python</a>&#8230;&#8221;  on python.reddit.com reminded me of one I&#8217;d built in python with <a href="http://shoebot.net">shoebot</a>.</p>
<p>While it works OK, I feel like I&#8217;m missing a higher level audio library (especially having seen Minim, for C++ and Java).</p>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2010/05/graphs.gif"><img class="alignnone size-full wp-image-265" title="graphs" src="http://www.stuartaxon.com/wp-content/uploads/2010/05/graphs.gif" alt="" width="358" height="288" /></a></p>
<p>To run it in shoebot:</p>
<pre class="brush:shell">sbot -w audiobot.bot</pre>
<h3>audiobot.bot</h3>
<pre class="brush:python"># Major library imports
import atexit
import pyaudio
from numpy import zeros, short, fromstring, array
from numpy.fft import fft

NUM_SAMPLES = 512
SAMPLING_RATE = 11025

def setup():
    size(350, 260)
    speed(SAMPLING_RATE / NUM_SAMPLES)

_stream = None

def read_fft():
    global _stream
    pa = None

    def cleanup_audio():
        if _stream:
            _stream.stop_stream()
            _stream.close()
        pa.terminate()

    if _stream is None:
        pa = pyaudio.PyAudio()
        _stream = pa.open(format=pyaudio.paInt16, channels=1,
                           rate=SAMPLING_RATE,
                           input=True, frames_per_buffer=NUM_SAMPLES)
        atexit.register(cleanup_audio)

    audio_data  = fromstring(_stream.read(NUM_SAMPLES), dtype=short)
    normalized_data = audio_data / 32768.0

    return fft(normalized_data)[1:1+NUM_SAMPLES/2]

def flatten_fft(scale = 1.0):
    """
    Produces a nicer graph, I'm not sure if this is correct
    """
    for i, v in enumerate(read_fft()):
        yield scale * (i * v) / NUM_SAMPLES

def triple(audio):
    '''return bass/mid/treble'''
    c = audio.copy()
    c.resize(3, 255 / 3)
    return c

def draw():
    '''Draw 3 different colour graphs'''
    global NUM_SAMPLES
    audio = array(list(flatten_fft(scale = 80)))
    freqs = len(audio)
    bass, mid, treble = triple(audio)

    colours = (0.5, 1.0, 0.5), (1, 1, 0), (1, 0.2, 0.5)

    fill(0, 0, 1)
    rect(0, 0, WIDTH, 400)
    translate(50, 200)

    for spectrum, col in zip((bass, mid, treble), colours):
        fill(col)
        for i, s in enumerate(spectrum):
            rect(i, 0, 1, -abs(s))
        else:
            translate(i, 0)

    audio = array(list(flatten_fft(scale = 80)))
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/05/17/shoebot-spectrograph/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
