Tuesday, March 31, 2009

Resumable IPython inside Blender Terminal

Would it not be nice if IPython could run inside the Blender terminal in such way that it will remember the namespace history in between sessions? Why IPython? It gives you auto completion, deep reloads, object introspection, input history, access to your operating system commands with python variables, auto indent, ... In case you are not convinced, read this tutorial, reference or watch these screencasts on showmedo.

Most Linux distributions ship IPython in their repositories. For example installing on Ubuntu is as easy as:
$ sudo apt-get install ipython
Getting IPython on Windows or Mac is simple if you have setuptools installed:
$ easy_install IPython
Windows users should install pyreadline as well for autocompletion. Check first in a terminal if IPython is correctly installed:
$ ipython
Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49)
Type "copyright", "credits" or "license" for more information.

IPython 0.8.4 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.

In [1]:
Save the following code as 'ipython_terminal.py' in your blender home script folder (~/.blender/scripts).
#!BPY

"""
Name: 'IPython (Terminal) - Enhanced Interactive Python Shell in Terminal'
Blender: 248
Group: 'System'
Tooltip: 'Interactive Python Console in terminal'
"""

__author__ = "Stani (SPE Python IDE)"
__url__ = ["pythonide.stani.be", "www.blender.org", "www.python.org"]
__bpydoc__ = """\
This only works if you started Blender from a terminal.
Otherwise Blender will freeze. The IPython console will
appear in the terminal. The namespace will be persistent
between console sessions within one Blender session.

Press Ctrl-D to pause the IPython session and return to Blender.
"""

# -*- coding: UTF-8 -*-

# ar - ARchitecture library
# Copyright (C) 2009 www.stani.be
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses/

import sys

from IPython.Shell import IPShell

import bpy
import Blender

try:
shell = Blender.Registry.GetKey('ipython.terminal')['shell']
shell.IP.exit_now = False # resume
except TypeError:
sys_argv = sys.argv
sys.argv = ['/usr/bin/ipython']
shell = IPShell(user_ns={'Blender':Blender, 'bpy':bpy})
sys.argv = sys_argv
def pre_prompt_hook(ip, Blender=Blender, shell=shell):
Blender.Redraw()
Blender.Registry.SetKey('ipython.terminal', {'shell':shell})
shell.IP.set_hook('pre_prompt_hook',pre_prompt_hook)

shell.mainloop(banner=shell.IP.BANNER + shell.IP.banner2 +\
'\nPress Ctrl-D to pause the IPython session and ' +\
'return to Blender.\n')

Make sure you start Blender from a terminal and not from the start menu, as IPython will run in the terminal. You can start the IPython terminal from the Script window in Blender. (Scripts > System > Ipython (Terminal) ) Just like in my previous blog post, each time a Python statement is entered, the Blender window is updated. So you can move a cube and see the result, if you type:
In [1]: cube = bpy.data.objects['Cube']

In [2]: cube.LocX = -1
When you want to return to Blender, press Ctrl-D. If you restart later the IPython terminal, it will remember any commands you have typed or any variables you have declared (like cube in the example).

IPython has a different prompt which makes it easy to go back to previous input statements or output values:
In [1]: a=1

In [2]: print a
1

In [3]: a
Out[3]: 1

In [4]: exec _i2 # execute second command
1

In [5]: exec In[2:4] # execute multiple previous commands
1

In [6]: b=_3 # third ouput value

In [7]: a==b
Out[7]: True
If you prefer a standard python prompt (>>>), just enter '%doctest_mode':
In [1]: %doctest_mode
*** Pasting of code with ">>>" or "..." has been enabled.
Exception reporting mode: Plain
Doctest mode is: ON

>>>
For auto completion, press the TAB key:
In [1]: bpy.data.
bpy.data.__class__ bpy.data.curves
bpy.data.__delattr__ bpy.data.fonts
bpy.data.__dict__ bpy.data.groups
bpy.data.__doc__ bpy.data.images
bpy.data.__getattribute__ bpy.data.ipos
bpy.data.__hash__ bpy.data.lamps
bpy.data.__init__ bpy.data.lattices
bpy.data.__name__ bpy.data.materials
bpy.data.__new__ bpy.data.meshes
bpy.data.__reduce__ bpy.data.metaballs
bpy.data.__reduce_ex__ bpy.data.objects
bpy.data.__repr__ bpy.data.scenes
bpy.data.__setattr__ bpy.data.sounds
bpy.data.__str__ bpy.data.texts
bpy.data.actions bpy.data.textures
bpy.data.armatures bpy.data.worlds
bpy.data.cameras

In [1]: bpy.data.m
bpy.data.materials bpy.data.meshes bpy.data.metaballs

In [1]: from Blender import M
Material Mathutils Mesh Metaball Modifier
As shown in the last example auto completion works even for import statements.

Altough the Blender window updates itself, the Blender user interface is still irresponsive when running an IPython session. In a future blog post I'll show how to run IPython inside the Blender window in such way that the user interface stays fully responsive.

Friday, March 27, 2009

Free software python coin on national French television

A while ago I blogged about my winning coin design. As an architect and artist I have switched some years ago to free software. A lot of so called experts would tell me that is impossible. They need Photoshop, Illustrator, Maya, ... on a fancy Macbook. However if I look to what they produce, I see no problem in making that with Gimp, Inkscape, Blender, ... even on an underpowered netbook. I did mainly this blogpost to proof not only that they are wrong, but also to showcase a design, which they even wouldn't be able to make with any proprietary software.

The reactions were overwhelming both from the free software world and outside. The Dutch architecture site did a competition for who could read all the names of the architects. I've been told the design featured in a popular Dutch comic Fokke & Sukke. (Anyone has a reference to this?) Rem Koolhaas was happy he was number one. Also typography sites showed a lot of interest. The Ministry of Finance promoted the coin on national Dutch television with this clip. (Unfortunately I was not involved in the production of the clip, otherwise it would have been 'Blendered'.) The more this kind of success stories pop up, the more people will be convinced to switch to free software.

Last month a French television crew of Avenue de l'Europe (FR3) came to interview me about the coin. They are making a documentary about the 10 years existence of the euro. They chose my design as one of the most remarkable in the history of the euro. As the documentary is about the total history of the euro, I will probably get not more than one minute or maybe just some seconds. The emission is tomorrow 28/3 at 18h30 at FR3: http://info.france3.fr/avenue-europe

In the preparation emails for the interview, I felt they were more interested in the design than in free software. So in order to give some publicity, I wore an Ubuntu T-shirt for the interview. As a location I chose the Fablab in Amsterdam. (They are still looking for people experienced with (graphical) free software or writing 3d printer drivers. If you want to help out, contact alex*waag.org). I guess the television crew really have never heard about free software design, because one of them asked me if I went for holiday in South Africa recently when she saw my Ubuntu T-shirt.

Monday, March 23, 2009

Standard Python Console inside Blender

Blender did not provide an interactive shell by default in the past. This changed a bit with the Interactive Python Console of Campbell Barton (aka ideasman42), which is accessible from the script window (Scripts > System > Interactive Python Console). Unfortunately this console does not support copy&paste, word wrapping, prompts, ...

I wrote a quick script in case you want to interact with Blender from a real Python console. Save it in your Blender home scripts folder (~/.Blender/scripts) as "terminal.py".
#!BPY

"""
Name: 'Terminal - Interactive Python Console in terminal'
Blender: 248
Group: 'System'
Tooltip: 'Interactive Python Console in terminal'
"""

__author__ = "Stani (SPE Python IDE)"
__url__ = ["pythonide.stani.be", "www.blender.org", "www.python.org"]
__bpydoc__ = """\
This only works if you started Blender from a terminal.
Otherwise Blender will freeze. The Python console will
appear in the terminal. The namespace will be persistent
between console sessions within one Blender session.

Press Ctrl-D to quit.
"""

# -*- coding: UTF-8 -*-

# ar - ARchitecture library
# Copyright (C) 2009 www.stani.be
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses/

import code, sys
import Blender, bpy

class InteractiveConsole(code.InteractiveConsole):
def interact(self, banner=None):
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
cprt = 'Type "help", "copyright", "credits" or "license"'+\
' for more information.'
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
else:
self.write("%s\n" % str(banner))
self.write('Press Ctrl-D to quit.\n')
more = 0
while 1:
try:
if more:
prompt = sys.ps2
else:
prompt = sys.ps1
try:
line = self.raw_input(prompt)
except EOFError:
self.write("\n")
break
else:
more = self.push(line)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
Blender.Redraw()
Blender.Registry.SetKey('terminal.locals', self.locals)

locals = Blender.Registry.GetKey('terminal.locals')
if not locals:
locals = {'Blender':Blender, 'bpy':bpy}
console = InteractiveConsole(locals=locals)
console.interact()
To use it, you need to start Blender from a terminal (with compiz turned off):
$ blender -w
This is very important, otherwise Blender will be blocked waiting for input at an invisible terminal. The terminal console can be started from the script window: Scripts > System > Terminal. The modules 'Blender' and 'bpy' are preloaded into the console, so you don't need to import them manually. Each time a Python statement is entered, the Blender window is updated. So you can move a cube and see the result, if you type:
>>> cube = bpy.data.objects['Cube']
>>> cube.LocX = -1
You can quit the interactive console by pressing Ctrl-D. You can restart the terminal as many times as you wish and automagically all your local variables will be kept (such as 'cube' in the example).

The disadvantage is that the Blender window itself becomes unresponsive. For example you can not rotate the view during a Python console session. Also it would be much nicer to use IPython instead of the standard Python shell. However in a future blog post I'll have good news, if you want IPython integration inside Blender.

Sunday, March 8, 2009

Vector rendering with Blender in Ubuntu

PantoGraph is a prototype for a vector rendering engine, developed in python by Severn Clay Studio. This can be nice for architectural presentations. It is still beta, which means it gets quite slow for heavy drawings.

It features two engines under the hood:
  • cairo for svg, pdf and png output
  • ming for animated flash output (.swf)
Current features :
  • Hidden- line rendering
  • Solid colors (with- and without alpha) only
  • The ability to use simple closed, convex volumes to do a boolean “cut-away”
  • Control over lineweight and color for:
    • Silhouette
    • Crease
    • Mesh
    • Hidden lines
    • Curves

  • A simple GUI that allows the saving of pens and pen settings

It can be loaded as a python script from Blender. Don't bother with the installation instructions on the Pantograph homepage (like fiddling with your PYTHONPATH), as I wrote the following install script which takes care of everything (at least in Ubuntu Intrepid). Open a new text file with the name 'install_pantograph' and copy the following content inside:
#!/bin/bash
#install most dependencies
sudo apt-get install -y python-ming python-cairo python-scipy
#install Polygon (python bindings)
wget http://download.dezentral.de/soft/Python/Polygon/Polygon-1.17.tar.gz
gzip -dc Polygon-1.17.tar.gz | tar xf -
rm Polygon-1.17.tar.gz
cd Polygon-1.17
python setup.py build
sudo python setup.py install
cd ..
rm -rf Polygon-1.17
#go to home blender dir
HOMEDIR=$HOME/.blender/scripts/
cd $HOMEDIR
#remove previous pantograph
rm pantograph*
rm progressImage.png
#install pantograph (progress image)
wget http://home.earthlink.net/~severnclay/pantograph_0.5.zip
unzip -o -j pantograph_0.5.zip progressImage.png -d ~/.blender/scripts
rm pantograph_0.5.zip
#install pantograph (bleeding edge)
wget http://home.earthlink.net/~severnclay/pantograph_bleedingEdge.zip
unzip -o -j pantograph_bleedingEdge.zip -d ~/.blender/scripts
rm pantograph_bleedingEdge.zip
#set homedir in config
cat pantographConfig.py | sed -e "s%/home/sclay/Work/Projects/pantograph/%$HOMEDIR%" > pantographConfig.py

Make the script executable, with right click (properties>permissions) in the file browser or from the terminal:
$ chmod +x install_pantograph
And run the script in the terminal as you will need to give your password to install the dependencies.
$ ./install_pantograph
After that you can access the pantograph renderer from the script window in Blender. First try it out with the default cube scene, before you let it crunch your heavy drawings.

If you want follow the progress of the render, you can better disable compiz and start Blender from a terminal, where the progress will be shown:
$ metacity --replace
$ blender -w
For feedback you can contact the developer at the blenderartists forum.
Filter by topic: spe, python, ubuntu