2d image extruded to 3d as collection of cubes

this rather small and simple code snippet will take the 2d image specified, scan for pixels that do not have a full alpha channel set, and will create a 3d cube in relation to the pixel (including its color value.) ultimately the 2d image is recreated with cubes. some games use this to easily make simple 3d objects from basic 2d images. the collection of cubes could be scaled in any direction, most notably for more depth. i found a need for this, and figured i would share it.

please post any updates or suggestions to the code for others to see.

import direct.directbase.DirectStart
from panda3d.core import PNMImage, Filename, Texture, CardMaker, TextureAttrib, Point3
from direct.interval.IntervalGlobal import Sequence
import sys

#create an image object from file
img = PNMImage()
img.read(Filename("sword.png"))
#create a texture object
tex=Texture()
tex.load(img)

#make a parent node for all the cubes we create for it representing the 2d image
boxel = render.attachNewNode('boxel')

#check the image file for pixel information, create cubes
y = img.getReadYSize() - 1
while y >= 0:
	x = img.getReadXSize() - 1
	while x >= 0:
		if img.getAlpha(x,y) > 0: #not a complete alpha transparent pixel?
			print img.getPixel(x,y)
			#load a generic box
			cube = loader.loadModel("models/box.egg")
			
			cube.setPos(x,0,y)
			r = img.getRed(x,y)
			g = img.getGreen(x,y)
			b = img.getBlue(x,y)
			cube.setTexture(loader.loadTexture("white.png"),1)
			cube.setColor(r,g,b)
			cube.reparentTo(boxel)
		x-=1
	y-=1

#scale it down for visual comparison
boxel.setScale(.25,.25,.25)
boxel.setHpr(0,180,0)
boxel.flattenLight()
boxel.setPos(3,10,5)
#spin it for effect
seq = Sequence(boxel.hprInterval(4.5,Point3(360,0,0)))
seq.loop()


#load the 2d image as a sprite, for a visual comparison
#make a sprite using cardmaker
sprite = CardMaker('card')
sprite = render.attachNewNode(sprite.generate())
sprite.setTexture(tex)
sprite.setPos(-.5,5,5)

base.cam.setPos(0,-15,5)

base.accept('escape',sys.exit)
run()

sword png is at: i40.tinypic.com/34dsu2u.png
and white png(just a single white pixel): i43.tinypic.com/2ds0gfr.jpg

I’m loading the white texture because i don’t want to use the texture that comes with the box.egg file, if there is a better way of doing this please let me know! ofcourse you could also just make a box piecemeal too.