Halloween Costume ideas 2015
Articles by "john maeda"
@dorothiar #arttips #interview 101 2 Column Template 2012 mentee 2013 2013 mentee 2014 2014 mentee 2014 Portfolio Winner 2014 SCBWI Portfolio Mentorship Winner 2015 mentee 3 Column Template 360 3d 3d print 3d printing 3delight 8bit Abbey McCulloch abstract acryla gouache acrylic action addon adobe Adobe Flash CS3 Adobe Illustrator Advanced Tutorials advection Advertising advice Agata Wierzbicka agents airplane Al Wiseman ALA Alan E. Cober Alan Lee Alex Ross Alexandra Compain-Tissier Alexandra Lekias Alexandra Levasseur Alexandre Korobov Alexis Winter algorithm alien ALT Amelie Hegardt Amit Shimoni amusement an Ana Aranda analog Andrea Hrjnak Andrea Hrnjak andrea offermann andreaoffermann andreazuill Andy Musser Angela DiTerlizzi Angelika Peißker animal logic animals animation animation nodes anime anisculpt Anja Kroencke Anna Higgie Anna Jensen Anna McKay Annabel Briens AnneBerry Anneke Krull Annu Kilpeläinen anstudy anthology António Soares ar arduino area armature arrange array array modifier arrow art art director art directors Art is fun! art reps art tools Artaksiniya arthictecture arthur rackham artists artwork ase Ashlyn Anstee Asian aspiring asset atom attribute attribute transfer audio Audrey Kawasaki augmented reality aurasma Aurelius Battaglia author illustrator automatic automation Autumn Whitehurst avatar Avrom Yanovsky AW14/15 award awards Babeth Lafon Babies baboon Baby Love Background background color bacteria bake baking ball Bamboo banner Banner images banner making Barbara Dziadosz barcode basic bbox beads beats Bec Winnel beginner Bel Johnstone Ben Denison Bernie Fuchs Berto Martinez Beth Krush better photos bge Bijou Karman Bike biscuit bishop black and white black and white art Blair Breitenstein blam blender blender game engine blender3d blending Blinkie Blinky blob blocks Blog Tips blogger Blogging Friends blogs Blonde blur effect in pixlr and photoshop blur images and pictures bmesh bmesh viewer bolognaragazziaward bombing bone bone modeling bones book book launch books boomerang bottle bounding box bowl bpy brian eno brian ormiston Brian Sanders brian won brick bridge Bridget Davies bright Brooke Boynton Hughes build modifier building burns business Buttons bvh cage Caitlin Shearer caldecott calibration camera camera settings camera tips Candle capcom card career Carole Wilmet cartoony Cassandra Rhodin cast Catherine Campbell Cecilia Carlstedt cell center pivot centipede cg cg photography chair challenge Chanel changin color in pixlr changing color chaos character Character Bible character development charcoal charles Charlie Dot Charlie Hebdo Children children's book illustration chocolate Christina Drejenstam christina forshay Christina K christinaforshay Christmas Cindy Derby circle circle dance city cityengine clock clones cloning cloth Cloud based clover CMYK Coco Chanel Cody and the Fountain of Happiness coffee collect collection Collections collision color color balance color cast color correction color mode color study colorful Commercial Use complexity component compositing composition computational thinking computer concept art Condensed Posts conference connect connect the dot connection Connie Lim Conrad Roset constrain constrast contagion content Contest contracts control converter copy copyright Corinna Luyken count Courtney Brims crack Craft craftsmanship Craig & Karl creative creativity creature cricket Cristina Garcia Martin critic criticism critique Crop Crop Tool cross section crowd csv cubism curve curve modifier custom Custom Blog Design Custom Blog Design Tutorial Custom Blog Designers Custom Illustration custom properties Custom Signature custom xml cut cutting plane cycle cycles dae Damien Florébert Cuypers Dan Hillier dance Daniel Egnéus Daniel Segrove Danny Roberts Daren Newman Dasha Tolstikova data data path David Blossom david diaz David Shrigley David Stone Martin Dean Hardscrabble Debbie debbie ohi debbieohi deform deformer degrees deleting background in pixler demo demoscene desaturation of images design design by numbers design process Design Tips dictionaries dictionary Different Text Writing in Pixlr digital digital paint Digital Scrapbook Freebies Digital Scrapbooking disk distance distractions distribute diversion DIY DIY Contest Dolf Veenvliet Doll Doll Bones dolls domino domino effect doodle Doodles door doraemon Doris Jackson Dorothia Rohner dots dpi draw drawing drill driven driver drivers dual versions dummy duplicate duplicates duplication dupliframe dvd dynamic dynamic paint dynamic text E Simms Campbell Easy easy pixlr Easy Tutorials Ed Graham Ed Vebell editing editing photos editors education effect effects ego Eleanor Dalton electric Elia Fernández eliza wheeler Elizabeth Mayville elizawheeler Emily Forgot Emma Zanelli emoticon happy-face Emotional storytelling empathetic characters empty entoforms envy epicycloid EPS Illustration Epson scanner erasers Erin Armstrong Erin Petson erinoshea ernest shepard Esra Roise euler evaluate line Eveline Tarunadjaja evenly spacing vertex event everywhere door exhibition Expandable Posts experiments explode exploded view export expression extrude eye eye color in pixlr eye trick eyeball face rig facial expressions facial setup factory Faiyaz Jafri Families fashion illustration fashion week fcurve feature Featured Fee Harding Feedback fence Fernanda Guedes fibonacci Fifi Lapin file File Types Finalists Finding Nemo fire fix photos Flash Tutorials flicker flip flip flop floor flop flow flower Flowers fnmatch focal point follow up font Fontaine Anderson Fonts food footage For Sale force form formula fractal fracture frame Frames Francois Berthoud Frank Bellamy Frank Furlong Franklin McMahon freckles Fred Steffen FrederiqueBertrand Free for Commercial Use Free for Personal Use Free Stock Photography Free transform tool Freebies Frenchillustration Fritz Siebel frosted mylar fruit ninja Fumi Mini Nakamura Fun function futurism FW2017 fx Gabriel Moreno Gabriella Ibarra game game animation gameart gamma gangnam style Garance Doré Gary Fernandéz gel medium generate generative generator geometric geometry Gerald Lazare Géraldine Georges GIF Gildo Medina Girl Giuseppe Castellano Giveaway glorar goals golden ratio google google docs Google Tools Grant Young graph graphite graphite transfer grease pencil grid group group node growth Gucci Guest Guil Godier gustave dore hair handbook Harper's Bazaar harpercollins Harvey Schmidt Haute Couture head Headers heat map Helena Hauss hexagon hexagonal grid Hiroshi Mizuno Hiroshi Tanabe Holiday Holly Black homology honeycomb hook horror houdini how to how to blur a face or an object in pixlr How to change eye color how to delete an object how to desaturate an image how to edit a image in pixlr how to erase an object how to fix red eye problem how to fix red eyes in pixlt How to fix the parts in pixlr in photoshop How to make a banner in pixlr How to overlap the nevus how to remove a object How to remove an object in pixlr how to remove red eyes How to Remove the Background of an Image in Pixlr How to remove the parts that you don't want in pixlr and photoshop how to replace color How to write a Patterned Text in Pixlr how-to Hsiao-Ron Cheng hsv hue humor Hyshil I love illustration magazine idea ideas Igor+André illusion illustrating illustration illustration board Illustration Books Illustration Intensive Illustration Now! Fashion illustration process Illustrations Illustrative Berlin illustrator Illustrator Intensive Illustrator Tutorials iloveillustration magazine image ediditing lessons Image Ready image sequences image theft imaginative import import text import vertex color improving photos inbetween index visualizer Info Ingrid Bockting ink inktober input Inspiration inspirational quotes install instance instance switching intensive interaction Intermediate Tutorials internet interoperability interpolation intersect intersect edges intersecting intersection interview introduction invoke subprogram io ipad Irana Doucer Isabella Hemmersbach islam islamic iteration Izzie Klingels Jack Hearne Jack Tremblay James Dignan James Gurney japanese Jason Brooks Jean Kim Jeanne Detallante Jen and Chris Creed Photography jen betton Jen Rofé Jenny Mörtsell Jeremy Combot Jeslyn Kate Jesse Auersalo Jessica Jessica Lanan jessicalanan jewellery jewelry jiggle Jim Schaeffing Joe Bowler Joe Cleary Joe Isom Joe Krush Johanna Goodman john maeda John Vernon Lord joint Jordan Sondler JPEG JPG jpop juana martinez-neal juanamartinezneal Judge Judit Garcia Talavera Judith van den Hoek Judy Byron Schachner Jules Julien Julian Beever Julie Verhoeven Jump Break Tool JW Anderson K-Fai Steele Kaethe Butcher Kareem Iliya karel zeman Kate van Harreveld Kathrin Kuhn Kathryn Ault Noble Kathryn Noble Katie Kath kdtree Kei Meguro Kelly Beeman Kelly Light Kelly Smith kelly sonnack Kelly Thompson keyframe keyframing kidlit kidlitartists kimberlygee Kirkus Review Kisoo Chai Kodak Konstantin Kakanias Korean illustration Kotaro Chiba Kozue Himi Kremos Ksenia Finogeeva KT Smail kuler Kustaa Saksi Lanan Laptop larry gritz lasso tool latte lattice Laura Callaghan Laura Laine Lauren Rille layer layering Layla Holzer layout leaf learning learning blender LED Leendert meets Ingrid lego length Leonard Starr lessons levels LFW A/W 14 liangzhu liero lightbox lighting lightning Lina Bodén Lina Ekstrand Linda Dorn line line connect line drawing lines Links Linky Love Linn Olofsdotter Lionel Gilbert Lisa Anchin Lisa Billvik Lisa Krannichfeld lisaanchin lisbeth zwerger Liselotte Watkins list list comprehension List First Last listing locator lofting logo Logo Design Lola Dupré London Fashion Week loop looping loops looptools Lorraine Fox lossless lossy lost weekend lostweekend lotte reininger Louis Glanzman louis vuitton Luciana Rondolini luciograph LULU* lv Lynnie Zulu Mac macgyver macouno maeda Magda Antoniuk magic Magnus Voll Mathiassen mailing mailings maker Makiko Sugawa making banners Malika Favre MAMP mandala manga map map range maplelam mapping Marcel George Maren Esdar Margot Macé Margot van Huijkelom Maribeth Olson Marie El-Ahmar Marilyn Conover Marina Esmeraldo Marine Marbleindex mario Marlies Niemeijer Marsha Riti Martha Rago Martin Krusche Martine Johanna mask masking material materials math matrix matrix apply matryoshka Matt Baker matte medium Matthew Woodson maya maze mdd Meagan Morrison measure megaman Megan Hess Meizhen Xu Mel Crawford memory mentee mentees mentors mentorship program Mercer Mayer Meridth McKean Gimbel mesh mesh cutter meshlab Meta Tags metal gear rising Meyoko Mia Overgaard Micca mice Michael Sanderson Michela Picchi middle grade midi miku Milan milipede minidom Minima Mio Matsumoto mirror cut Misc Miss Blackbirdy miss maple's seeds Miss Take Mitchell Hooks mixamo mixing Mobile Apps mocap mod model modeling modifier modular modulation modulus mold molecule molly idle Molly Ruttan Molly Ruttan Illustration money monitors monkey mono-zero monster monster university morph morpher mosaic mosquito motion motion capture motion capture mouse motion trail moto360 mountain muji Muriel Wood Murray Tinkelman mushroom Music and Podcasts My dead pony Nadia Flower Naiad Einsel Naja Conrad-Hansen Natalie Brockett Natalie Foss nathan vegdahl nautilus Nav Bar navigation needle-felting negotiating Neil Boyle neon nescbwi14 nested New Blogger Questions New Blogger Template Tutorials new user pixlr new year new york New York Fashion week Newbery nicholas nicholas bishop Nicholas Hong Niki Pilkington Niso Ramponi nla No Software node node-based nodebox noise non linear animation Non-Web Font normal Noumeda Carbone npr number NURBS NYFW object object color change object info octopus offset Ola Volo Olaf Hayek old formats opaque projector open movie open shading language open source openshadinglanguage opensoundcontrol optical organization origami original art show Ornaments osc Oscar Schlienger osipa osl outline outliner output Pages paint paint weight painting painting on illustration board painting on wood painting with movie painting with numbers Pair pandas panorama Paper paper lantern parabola parametric parent parenting particle particle info node particles pat david Pat Zietlow Miller pattern Patterned Text Paul Faassen Paul X. Johnson Paula Sanz Caballero PC pdb pebbles pencil Pencil Sketch pencils Penguin perfume perlin Peter Helck Photo CD.8B photo editing software Photo Reference Photobucket photographing art Photographs photography photomerge photoshop Photoshop Brushes Photoshop CS3 Photoshop elements photoshop pixlr desaturaion Photoshop tips Photoshop Tutorials Picture Book Builders picture books Pierre Louis Mascia Piet Paris Pietari Posti pingpong pinnochio pipes pixar pixel pixel art pixel generator pixlr Pixlr advanced Pixlr blog pixlr desaturate keep a colorful part pixlr editting pixlr express Pixlr forum Pixlr free transform Pixlr Lesson Pixlr lessons Pixlr mobile Pixlr resizing images pixlr shortcuts Pixlr tools pixlr tutorial pixlr tutorial with pictures Pixlr Tutorials pixlr white black pixlr.com plant plot plotting ply PNG PNG Illustration podcast point point color pointilism polka dots polyCut polygon Pomme Chan pop-overs portfolio Portfolio award portfolio showcase portfolio-advice portrait position Post Dividers postcard poster Posting pot powdered graphite powerhousemuseum Prada presentation print printmaking Prize procedular procedural process processing programming projection Promotion property prototype PSD psy publishing pulse puppet puppetry pydriver pydrivers pyhandler pyhandlers pyramide python quad quick select set quick tips qumarion Rabbit Moon Rachel Ryle radians radius ramp random random motion randomization randomize range float raspi Ray Houlihan reading reading XML READY-TO-WEAR realflow Rebecca Clarke rebecca dautremer Rebecka Skog rebuild recursive recursivedrawing red eye remove reducing glare reference referencing release remesh modifier remix removal remove remove red eyes remove unwanted objects Removing backgroung render rendering renderman repeat repeater repeating replace replacement replacing color representation rerouter resample resampling research Resizing image resolutions retopology retro review revolve rgb rib Ricardo Fumanal Richard Scarry rig rigging rigify Rikke Jorgensen ring ripple roadkill Robert Heindel Robert J. Lee Robert McCloskey Robert Shore Roberta Zeta Robin Rosenthal robot robotic rocks Rodolfo Montalvo Roller Coaster rotation Rousseau rsl Rubin Pfeffer ruler tool Russ Mills russian rut S/S14 S/S15 S/S16 Sabine Pieper sadako Saftey Pins Sainte Maria Sale Sam Weber Sanda Suy Sandy Kossin santoso Sara Andreasson Sara Singh Sarah Jacoby saturation artist tools scan scanners scanning scatter scbwi SCBWI 2015 mentee SCBWI conference scbwi germany SCBWI mentorship scbwi-la scratch scratchboards screensaver screw screw modifier script scrub sculpting seamless Seamless Patterns Search Engines select by material select by name select by type SEO sequence series set keyframe set keyframes shader shading shadow Shannon Stirnweis shape grammars shape key shapekeys shapes shards shatter Sheilah Beckett shell ship shipping shipwright Shoes SHOWstudio shuffle Sid Barron Sidebar Titles Signature Silja Goetz silkworm Simon and Schuster Simon Varela simple simplicity simulation sine Site Engine Optimization Sjoukje Bierma sketch Sketches sketching skin skin modifier skinning slice slicing slides sloth slow parent smoke smoothstep SN snake Sneek Peek snippet Snow Snow White Snowflakes soccerball social media Social Media Buttons Social Networking society of illustrators Society6 soft body softbody Sonia Menti sound sound wave space spaceship sparta special spider spiderman spiderweb spin spiral Spiros Halaris Spiros Halaris x Urban Decay spline Spot Healing Tool spreadsheet SS16 stack stacking stair stamp Stan Galli star starfish stencyl step Steven G. Dobson still Stina Persson stone stones storytelling strand strand info strands street art string stripes structure studies studio style stylistic summary Summary Posts Summer sun supplies surface Susan Farrington suzanne Suzanne Kaufman sverchok swatch switch sydney system table table of contents take out background Tal Drori tangent tangled Taschen teaching teapot Template Templates tentacle Tess Jacobson Tex Avery text text editor Text Formats Text Styles in Pixlr texture texturing The Cartorialist The Grudge Keeper The Purple Book thinker1 Thomas B. Sawyer thread TIFF tile tilecam tiling time time code Tina Berning Tina Kugler tips tips for artists Toby Neilan Tom Baxter Tom Bjarnason tombow tomie depaola tool tools topology tower Tracy Turnbull Train transfer drawing transferring sketch transform transformation transit travel triangle wave Tricia Springstubb trigger tris tristan lock tube tubes Tutorials twitter type tool typeface typography unbake unity3d universal unquad utah uv valentine Valentino Valerie Servais vanilla variable variation variety vase vector vectorized Velwyn Yossy venus Veronica Ballart Lilja vertex vertex color vertex group vertex paint vertex weight VFX Victoria Boysen video Videos viewer Vintage virtual virtual studio visualization vivid vividfestival VOGUE volumetric voronoi Vote voxel voxelated voxelation walking teapot Walter Einsel wand tool water soluble graphite watercolor wav wave we need diverse books web webbing Week Themes weight welcome Wendy magazine Wendy Plovmand what casues red eyes What is Pixlr Wherever You Go Wide Awake Bear wiggle Will Davies Winner Winnie Fitch Winnie Truong Winter wire wired wireframe wolfram Woman wood woodwork wool wooly wordpress work workflow World writing writing XML www.pixlr.com XML YA yayoi kusama Yelena Bryksenkova yoda Yoko Furusho Yuliya zaha hadid zen zsphere

100% Made in Blender Pixel Art. No mouse, no 3D geometry, just keyboard and Python.

BLENDER BY NUMBERS
Inspired by John Maeda's Design By Numbers


INTRO NOTE, updated 2013.03.13

When starting this "Pixel Art in Blender", I did not think to go this far. I began by borrowing some info and script from Blender Scripting blog (by Dealga McArdle).

Later on as I go along in simplifying the script, I slowly starting to understand what his script is actually doing. I also started to look around everywhere for information to help me understand the process further.

I found this book below is helpful
"Introduction to Computing and Programming in Python - A Multimedia Approach" 
by Mark Guzdial and Barbara Ericson".
http://www.amazon.com/Introduction-Computing-Programming-Python-Edition/dp/0132923513/ref=dp_ob_title_bk/182-7879843-1920335

Similar example:
http://www.csse.monash.edu.au/~berndm/JMSS/python/tutorials/picture%20processing/

It is a basic Computer Science on Image Processing, but applicable for what we are doing: to be able to use Python to create and modify pixel.

For Blender artists with no interest with Python programming (yet!), you can use few scripts down below that allows you to:
  • Draw A Pixel 
  • Import Pixel Art and turn it into 3D
NOTE: There is also a Video Tutorial I just made today. Scroll down to the very bottom.

Being able to understand how a script works is definitely very rewarding, especially true for newbie Python coder like me. There are tons to discover and it is very exciting.

In near future, I am thinking to further extend this idea, until we are able to:
  • Modify the Color of Pixel using Image Processing Logic
  • Creating transition animation from one pixel to the next, frame by frame like in LED animation
  • How to render it out (save it to disk as well)
Thank you again to Dealga McArdle at Blender Scripting blog for wealth of information there waiting to be discover and John Maeda for truly inspiring way of thinking in simplicity and attention to details.



Continue with our Python journey ....

I was reading and studying some posts from this awesome Blender Scripting Blog by Dealga McArdle and there is one topic that is pretty interesting to me: "Pixels".
http://blenderscripting.blogspot.com.au/search/label/pixels

Dealga wrote and proposed on how we could tell Blender to draw pixels using Python. His example is quite clever and really open for interpretation. I did not get the whole thing yet, but they are interesting, especially the random pixel color it can generate.

I like to take his basic template on how to draw pixels and try to simplify further until we can draw a pixel.

I want to think in term of 2D Computer Graphics ala Design By Numbers (John Maeda) and Processing, and also NodeBox.

Basically let's explore this "Draw A Pixel" idea using Python.

DRAW PIXEL TEMPLATE 
Below is the basic template from Blender Scripting blog:


import bpy
import random

D = bpy.data

width = 10
height = 10

image_object = D.images.new(name='picOut', width=width, height=height)
num_pixels = len(image_object.pixels)

# draw a dot of pixel at certain position based on the number N
# N should not be bigger than (4 * width * height)
# value can be between 0.0 and 1.0

image_object.pixels[N] = 1.0 
image_object.pixels[245] = 1.0 

Let's trace the script above:

  • It tells Blender to create an image object, with the size of Width and Height specified. We use small number for now, like 10x10 grid, total number of 100 pixels.
  • The way it works, apparently the image object itself contain lookup information about Red, Green, Blue, Alpha color pixel value. Which means, for 100 pixels, we are getting the a total length of 400 slots in total (from num_pixels variable).
  • We can color the image object simply by putting a number in correspond to the R, G, B, A slot.


CREATING DRAW A PIXEL FUNCTION

Instead of relying to images.pixels[] function, I am thinking that we need to further break it into a function that is easier to comprehend.
I want to end up with function like this:

drawPixel(x,y, R, G, B, A)
x = coordinate pixel X
y = coordinate pixel Y
R = red value (0.0 - 0.1)
G = green value (0.0 - 0.1)
B = blue value (0.0 - 0.1)

drawPixel(i,j,value) # simplified version, greyscale output
i = coordinate pixel X
j = coordinate pixel Y
value = the value for RGBA

Let see how we can accomplish that.


PIXEL GRID
Firstly, we know that images.pixels[N] is the function we will be using to actually draw a pixel. But what we know is that the value N / the number that we specify, is an index number that is representing RGBA of the actual pixel of an image.

When we create 10 x 10 grid, we get 100 pixels. But inside the images.pixels, there are 400 index slots or 400 items. If we imagine it as a LIST, it will be something like this:

[ r, g, b, a, r, g, b, a, r, g, b, a, r, g, b, a, ..... ] for 100 times (because we have 100 pixels).

When we use the function images.pixels[N] as below:
images.pixels[6] = 1.0

That is basically telling Blender to draw a BLUE with value of 1.0 at Pixel Coordinate [1, 0] and mix it together with whatever value of RED, GREEN, ALPHA (default of 0.0).

How do I know that? From our understanding of LIST above.


(Inside Blender UV/Image Editor panel, if we LMB hold, we get information about that pixel. Above, we see information such as RGBA value and also the XY coordinate).

LIST TO MATRIX GRID



Before I got into the actual function to draw a pixel, I am researching all around on how to turn LIST into GRID ARRAY. Apparently, it is not ARRAY that I am really searching, I need a MATRIX, 2 Dimensional 2D Matrix to represent LIST as a GRID.

So, imagine we have a list  [r,g,b,a,r,g,b,a,r,g,b,a,r,g,b,a .... ] that we want to turn into matrix list [[r,g,b,a][r,g,b,a], [r,g,b,a].....]

Or imagine we have a list representing coordinate 10 x 10, but as a list [0,1,2,3,4,5,6,7,8,......, 99]. Total of 100 numbers.

That list will more useful if we turn it into something like below:
[[0,1,2,3,4,5,6,7,8,9], [10,11,12,13,14,15,16,17,18,19], .... and so on]

Which will be a more representative of (X, Y) grid. So that we can easily point the X and Y, and Python will turn that back into a number. I have few Python solutions that allow us to SPLIT a LIST into MATRIX.

FIRST SOLUTION
I got this awesome answer from Taisuke Tanimura which uses List Comprehension in Python:

##########################

# Taisuke Tanimura solution

r=1.0
g=1.0
b=1.0
a=1.0

origList = [r,g,b,a,r,g,b,a,r,g,b,a]
splitList = [origList[i:i+4] for i in range(0,len(origList),4)]

print (splitList)

##########################

SECOND SOLUTION 
My solution based on eHow solution

r=1.0
g=1.0
b=1.0
a=1.0

origList = [r,g,b,a,r,g,b,a,r,g,b,a]
splitList = []
splitEvery = 4

while origList != []:
    splitList.append(origList[:splitEvery])
    origList = origList[splitEvery:]
    
print (splitList)

##########################

THIRD SOLUTION 
To use NumPy, but I don't know exactly how. Google keeps pointing at NumPy.

NOTE:
While researching about List and Matrix, this is all basic stuff, I can imagine, but I found heaps of information about Python and how it can SLICE a LIST and also do the reverse like FLATTEN LIST within LIST or NESTED LIST into a single LIST. They are all new for me and very interesting.

[UPDATE 20130312: Understanding LIST & GRID]
Read further explanation by my mate, Nemui Kame regarding this kind of LIST and GRID to get a better understanding:
http://alittlegamecode.blogspot.com.au/2013/03/how-to-access-rgba-color-channel-via.html

Anyways, using the above method, we create a function below:


def grid(x,y):


# we have 10 x 10 grid, list will contain the total of it
origList = []

for i in range(width * height):
origList.append(i)

matrix = []

while
origList != []:
splitList.append(list[:width])
origList = list[width:]

return
splitList[y][x]



Taisuke's Method:


def grid(x,y):




origList = []

for i in range(width * height):
origList.append(i)

splitList = [origList[i:i+width] for i in range(0,len(origList),width)]



return splitList[y][x]


So, the function will return N number that actually represent X, Y grid coordinate. We can call it simply by using grid(x,y).

Cool. So the next thing we do is just to apply that into our next problem.

ADDING RED, GREEN, BLUE, ALPHA PATTERN INTO THE MATRIX
Since our pattern is [r,g,b,a, r, g, b, a, ....], my next quick hack solution is simply to do this:

N = red value
N + 1 = green value
N + 2 = blue value
N + 3 = alpha value

That will be how the whole list will be applicable to what we are doing.

BLENDER SUSHI SCRIPT: Draw Me A Pixel


import bpy
import random

D = bpy.data

width = 10
height = 10

image_object = D.images.new(name='picOut', width=width, height=height)
num_pixels = len(image_object.pixels)

def grid(x,y):
# we have 10 x 10 grid, list will contain total of it
origList = []

for i in range(width * height):
origList.append(i)

splitList = [origList[i:i+width] for i in range(0,len(origList),width)]

return splitList[y][x]

def drawPixel(x,y,value):

# multiplied by four because of r, g, b, a pattern
pixelNumber = grid(x,y) * 4

# this is a quick way to iterate
image_object.pixels[pixelNumber] = value
image_object.pixels[pixelNumber+1] = value
image_object.pixels[pixelNumber+2] = value
image_object.pixels[pixelNumber+3] = 1.0

print(pixelNumber)

# NOTE: number cannot go outside the range of image pixel width height

BLENDER SUSHI SCRIPT: Draw Me A Pixel - OPTIMIZED
AS SUGGESTED BY DEEN / updated 2013.03.13


import bpy
import random

D = bpy.data

width = 10
height = 10

image_object = D.images.new(name='picOut', width=width, height=height)
num_pixels = len(image_object.pixels)

def grid(x,y):
return x + width*y

def drawPixel(x,y,value):

# multiplied by four because of r, g, b, a pattern
pixelNumber = grid(x,y) * 4

# this is a quick way to iterate
image_object.pixels[pixelNumber] = value
image_object.pixels[pixelNumber+1] = value
image_object.pixels[pixelNumber+2] = value
image_object.pixels[pixelNumber+3] = 1.0




Thanks to DEEN in the comment below. Apparently we can get easier access to the Linear List from Matrix Grid XY by doing this: grid(x,y) = x + width*y

Much simpler. Why did not I think of that? I must have forgotten my Math!

However, doing it the long complicated way and the hard way, one learned how to SPLIT Linear List into Matrix and how to FLATTEN Matrix into List.


Keep in mind that the script will:
  • Create New Image and start fresh canvas each time you run the script. You can certainly change this behaviour and tell Blender to override the same image instead, but do keep track of your image Width and Height. Remember you cannot draw outside the dimension of your canvas.
  • Draw pixel on top of another pixel in sequences
Once above setup script is ran, we can simply call the function to draw a pixel by using drawPixel(x,y,value). Keep in mind your image dimension (width and height) and do not place the pixel outside the image canvas.

Each drawing will be processed top to bottom, and every pixel will be over-drawn by next pixel.


drawPixel(6,8, 1.0)
# this will draw pixel at X,Y coordinate (6,8) and as a value of 1.0 (RGBA).


Noise pattern.


Stripe of lines drawn pixel by pixel.


Lines with Random Greyscale values.


Using 100 x 100 pixel grid. 


It is starting to take a little longer to create, but still OK. The result is quite interesting.

For 1000 x 1000 grid, that will take quite a loooong time, but that is because this Python script to "Draw A Pixel" is not optimized. There must be a much better and faster way using Blender Python API.

More examples:

Using Width and Height as INPUT for the interaction



Using Random Module for colorful pixels





MARIO MUSHROOM PIXEL ART



Check the newly created image under Image Editor. There is probably a way to change the context and to update the Image Editor screen.


DRAWING PIXEL WITH COLOR (R, G, B, A)
For the colored Pixel, I added the code below:

def drawPixelColor(x,y,R,G,B):
    
    # multiplied by four because of r, g, b, a pattern
    pixelNumber = grid(x,y) * 4
    
    # this is a quick way to iterate
    image_object.pixels[pixelNumber] = R
    image_object.pixels[pixelNumber+1] = G
    image_object.pixels[pixelNumber+2] = B
    image_object.pixels[pixelNumber+3] = 1.0
    
    print(pixelNumber)

Below is the code to draw MARIO RED MUSHROOM, pixel by pixel. See if you can optimize this further.


### DRAW MARIO RED MUSHROOM ###


# draw white background
for i in range(16):
for j in range(16):
drawPixel(i,j,1.0)

# draw mushroom outline
for x in range(4,12): drawPixel(x,0,0.0)
for x in [3,12]: drawPixel(x,1,0.0)
for x in [2,13]: drawPixel(x,2,0.0)
for x in [2,6,9,13]: drawPixel(x,3,0.0)
for x in [1,2,3,6,9,12,13,14]: drawPixel(x,4,0.0)
for x in range(4,12): drawPixel(x,5,0.0)
for x in range(5,11): drawPixel(x,15,0.0)
for y in range(5,11): drawPixel(0,y,0.0)
for y in range(5,11): drawPixel(15,y,0.0)
for y in range(11,13): drawPixel(1,y,0.0)
for y in range(11,13): drawPixel(14,y,0.0)
drawPixel(2,13,0.0)
drawPixel(13,13,0.0)
for x in range(3,5): drawPixel(x,14,0.0)
for x in range(11,13): drawPixel(x,14,0.0)

# draw mushroom inside
for x in range(3,12):
drawPixelColor(x,6,1.0,0.0,0.0)
for x in range(3,12):
drawPixelColor(x,6,1.0,0.0,0.0)
drawPixelColor(14,6,1.0,0.0,0.0)
for x in [2,3,12,13,14]:
drawPixelColor(x,5,1.0,0.0,0.0)
for x in [3,4,9,10]:
drawPixelColor(x,7,1.0,0.0,0.0)
for x in [3,4,9,10]:
drawPixelColor(x,7,1.0,0.0,0.0)
for x in [2,3,10]:
drawPixelColor(x,8,1.0,0.0,0.0)
for x in [1,2,3,10,11,14]:
drawPixelColor(x,9,1.0,0.0,0.0)
for x in [1,2,3,10,11,12,13,14]:
drawPixelColor(x,10,1.0,0.0,0.0)
for x in [3,4,9,10]:
drawPixelColor(x,11,1.0,0.0,0.0)
for x in range(4,10):
drawPixelColor(x,12,1.0,0.0,0.0)
for x in range(5,9):
drawPixelColor(x,13,1.0,0.0,0.0)
for x in range(5,9):
drawPixelColor(x,14,1.0,0.0,0.0)





Try and  draw your own Pixel Art, pixel by pixel, using the code provided above and your understanding of Python. I guarantee that you will start to think further in term of making the code more efficient or how to draw faster.

Use small size Grid for now, for sake of simplicity. 100 x 100 is already quite big and the code can be slow. Try smaller grid size:
  • 10 x 10
  • 16 x 16
  • 32 x 32
  • 64 x 64

UPDATE 2013.03.14 / Saving Out The Image Files

So, you probably end up with some Pixel Art images now and want to save it? You can do that manually, but if you have many images, maybe we need Python.

Below is my attempt to write a script that will save all the Image Files: (that are currently open and displayed on Blender Image Editor)

BLENDER SUSHI SCRIPT: Save All Images



import bpy





allImages = bpy.data.images


filepath = 'C:/' # this is the root path where file will be saved





for image in allImages:


    image.save_render(filepath + image.name +'.png')


    print (filepath+image.name+'.jpg' + ' is saved!')



I figured out about the script and Python method to save the image file by using dir() on Blender Data Images object. I guess this is a good way to search for functions/methods inside an object. Surely Blender Python will have better documentation when it reaches Blender 3.0, but for now, I think this is the way to go apart from Google search or asking at the forum.




Gangnam Style 3D Pixel Art.

REMIX THE CODE 
Modify the code further and extend it as you pleased. As you may notice above, I actually do some modification by adding drawPixelColor() function. Of course the possibility is really endless.

Perhaps, you can create a  QR code in Blender, pixel by pixel?

Maybe you can sample a small Pixel Art that will then create a 3D Pixel Grid all with the correct material? Have someone done that? Very possible. In fact I will just do that now.

REVERSE THE CODE


Here, we are going to "reverse" the process. This is where the fun began.

So instead of Drawing A Pixel, the code below (which I again borrowed from Blender Scripting blog) will read whatever image pixel that you open in Blender (opened in Image Editor) and then take that data back into Blender as LIST and LIST MATRIX.

Inside Blender Image Editor, open up an image. In my case it is called 'mario_musroom.png', change that name with whatever image file you have.

import bpy
D = bpy.data

test_file = 'mario_mushroom.png'
img = D.images[test_file]
pixels = list(img.pixels)
grouped_list = [pixels[ipx:ipx+4] for ipx in range(0, len(pixels), 4)]

print("------LENGTH------")
print( len(img.pixels)//4) 
print("------PIXEL------")
print(pixels)
print("---GROUPED-PIXEL---")
print(grouped_list)
print(grouped_list[255])

Below is List of 4 x 256 Numbers, representing the pixel and RGBA values from the 16x16 Mario Mushroom image:



Below is Grouped Matrix List of 4 x 256 Numbers, representing the pixel and RGBA values from the 16x16 Mario Mushroom image:


What can you do with those data again then? Anything you can think of, actually.

You could manipulate the RGBA pixel color value and pass it back as new picture. Changing the color into greyscale, shifting the color value, create some variations of colors, and all kind of RGBA pixel color manipulation.

From Blender Scripting blog, Dealga suggested "firefly reduction" method, which is clever, kind of like "noise reduction" way of thinking.

We actually have good useful List of Array Matrix that can tell you the location of (X, Y) and also the R, G, B, A, so we can really filter that list and then tell Blender to create grid of xoxes with RGBA value. Although... I imagine many boxes with hundreds of materials will be quite heavy for Blender. Particle and Instance is probably better.

However, regardless of that, it is worth trying out just to further think in Python. 

Let see how we can draw some boxes using the above information...

I have a little help from here in term of applying Material to newly created Cube.

UPDATE 2013.04.09

BLENDER SUSHI X SCRIPT: Import Pixel Art and Create 3D Cubes (OPTIMIZED VERSION)

BIG thanks to MageOfTheForest for optimizing the script! 


import bpy

'''
This is an optimized version of Pixel to 3D Cubes script.

Credits to: mageoftheforest

Last update: April 9, 2013 at 2:08 AM

'''

# Specify your image here, open it inside Blender Image Editor panel
image_file = 'zelda_16_16.png'

img = bpy.data.images[image_file]
pixels = list(img.pixels)

# creates a 2 dimensional array from a 1 dimensional array
# by grouping r, g, b and a for each color
grouped_list = [pixels[ipx:ipx+4] for ipx in range(0, len(pixels), 4)]

# Get width and height of image (in pixel)
width = img.size[0]
height = img.size[1]

bpy.ops.mesh.primitive_cube_add()
obj = bpy.context.active_object
obj.scale = 0.5, 0.5, 0.5

mat = bpy.data.materials.new('pixelColor')
mat.diffuse_intensity = 1.0
mats = {}

for y in range(height):
for x in range(width):
# separate RGBA into each own variables
r = grouped_list[x + y * width][0]
g = grouped_list[x + y * width][1]
b = grouped_list[x + y * width][2]
a = grouped_list[x + y * width][3]

# create cube at location XY
# a new created mesh will always become the active object
copy = obj.copy()
copy.data = obj.data.copy()
copy.location = (x - width / 2, y - height / 2, 0)
copy.name = 'pixelcube.%s' % (x + y * width)

# add material with RGB color as sampled for every pixel
key = str(r) + str(g) + str(b) + str(a)

if key in mats:
copyMat = mats[key]
else:
mats[key] = copyMat = mat.copy()
copyMat.diffuse_color = (r,g,b)

copy.data.materials.append(copyMat)
bpy.context.scene.objects.link(copy)
print ('PixelCube {number} created at:'.format(number=x + y * width), x, y, ', with RGB color', r, g, b)

bpy.context.scene.objects.unlink(obj)
bpy.data.objects.remove(obj)

# Code for join all objects together
# Place the origin to the center and
# Remove all double vertices


'''
bpy.context.scene.objects.active = copy
bpy.ops.object.join()
bpy.ops.object.origin_set(type = 'ORIGIN_GEOMETRY')
bpy.ops.object.mode_set(mode = 'EDIT')
bpy.ops.mesh.remove_doubles()
bpy.ops.object.mode_set(mode = 'OBJECT')
'''

print('Finished')







Although I have not fully studied the optimized script in details, but above should work fine and a lot faster. The script procession will now continue running at full speed and does not slow down like below.

To do 256 x 256 grids, it will take few minutes instead of hours. Mind you, 256 x 256 = 65536 Cube with 65536 Materials. It will also consume around 1.6 GB of RAM. Not recommended.

You might also want to tweak the script above to apply color to a single material with Vertex Color Set, instead of Multiple Materials. Doing it this way is much more efficient and you can easily transfer it to Cycles.

Below is the original script to convert Pixel Art to 3D Cubes.

BLENDER SUSHI SCRIPT: Import Pixel Art and Create 3D Cubes

WARNING NOTE:
  • Use the script only on small Pixel Art ( 64x64 pixel is probably already big )
  • Toggle Blender System Console to see the progress printed out line by line.
  • I have not optimized the script, so 128 x 128 pixels will take a bit of time (few hours?). 1024 x 1024 pixel will probably take .... few days to complete. Do not try that.
  • Remember that you are creating total number of X x Y pixels. For 128 x 128 pixels, you will get 16384 boxes with 16384 materials! It is quite possible Blender may freeze run out of memory.
  • For pixel art with large dimension, it is better to use UV + texture and a single material after all. But for small pixel art, sometimes I prefer each box have its own material and color.
  • My Task Is: to optimize the script...
  • Will try Vertex Color option for more flexibility when using Cycles.

import bpy
D = bpy.data

# Specify your image here, open it inside Blender Image Editor panel
image_file = 'mario_mushroom.png'

img = D.images[image_file]
pixels = list(img.pixels)
grouped_list = [pixels[ipx:ipx+4] for ipx in range(0, len(pixels), 4)]

# Get width and height of image (in pixel)
w = width = img.size[0]
h = height = img.size[1]

print("------LENGTH------")
print( len(img.pixels)//4)
print("------PIXEL------")
print(pixels)
print("---GROUPED-PIXEL---")
print(len(grouped_list))

# Create LIST of GRID XY value
rowColList=[]

for i in range(height):
for j in range(width):
rowColList.append(i)
rowColList.append(j)

# SPLIT the LIST of XY
origList = rowColList
splitList = [origList[i:i+2] for i in range(0,len(origList),2)]

for number in range(len(grouped_list)):

# separate RGBA into each own variables
r = grouped_list[number][0]
g = grouped_list[number][1]
b = grouped_list[number][2]
a = grouped_list[number][3]

# separate XY coordinate
x=splitList[number][0]
y=splitList[number][1]

# create cube at location XY
bpy.ops.mesh.primitive_cube_add(location=(x-width/2, y-width/2, 0))
selectedObject = bpy.context.selected_objects
selectedObject[0].name = 'pixelcube.%s' % number
selectedObject[0].scale = 0.45, 0.45, 0.45

# add material with RGB color as sampled for every pixel
mat = bpy.data.materials.new('pixelColor')
mat.diffuse_color = (r,g,b)
mat.diffuse_shader = 'LAMBERT'
mat.diffuse_intensity = 1.0
#mat.emit=0.5

bpy.context.object.data.materials.append(mat)

print ('PixelCube {number} created at:'.format(number=number), x, y, ', with RGB color', r, g, b)






NOTE:
The actual sampling of image information in Blender is flipped horizontally, so maybe the resulting cube needs to be flipped manually. Or we can change the code to flip the axis.

Image is flipped when read back.
With this setup, we actually have Cubes for each pixel and each one of them is colored properly. We can apply Blender Rigid Body Dynamic to it like below if we like.
Of course you are not limited to 3D Cube shapes, you can also use other 3D Primitives or even Suzanne. Simply switch the Cube with other shapes and see how it looks.

NOTE:
Again I have not yet optimized the script further, unlike what Dealga has been exploring and get into conclusion on his website. So please do your own reading maybe you can improve the script yourself.
http://blenderscripting.blogspot.com.au/2012/08/adjusting-image-pixels-internally-in.html

Check also Dealga's script "Firefly Removal".

I will certainly do some updates whenever I understand something new.

ALTERNATIVE WAY TO RENDERING IT OUT
Use a number of array grid of boxes as you like and then color it using the Cycle material using Object Info Node. Doing it this way is the fastest to map the 2D texture. Using it this way, you get Pixel Colors that is more interpolated.





FURTHER STUDY: John Maeda's Publication, Processing, and NodeBox
Back to Pixel business, try if you could further enhance the code (if you do, please let me know and do give comments below), and make Draw functions such as below:
  • drawLine()
  • drawCircle()
  • drawSquare()
  • drawEllipse()
  • drawRectangle()
See how you would plug in function like Sine and deal with Float value when the grid is expecting Integer value. Things like that. Even I have no idea how to do it.

DEEN: (quoted from his nice suggestion on the Comments down below)
"... before investing time in creating drawLine, drawEllipse, etc, see if you can't use one of the existing Python image manipulation modules for that purpose, like PIL, or pyCairo, etc. I'm reasonably sure you can do drawing in PIL and then transfer the data to the Blender image pixel array in one go."

Perhaps you could further learn and expand this kind of idea using from awesome tools such as:
More Pixel stuff from Processing perspective:
Megaman rocks.

BONUS 2013.03.13 / Video Tutorial On How To Use The Scripts






PIXEL ART IN BLENDER, THE TRADITIONAL WAY...
If you prefer to do it in more traditional way, you can of course use Blender Paint mode. Remember to draw pixel art in a small canvas and a single pixel Brush. 





BONUS INSPIRATIONS

Rendering "pixel" look using Blender Freestyle and disabling Antialiasing by Peripheral Games:

Pixelated Animal Sculptures by Shawn Smith

Laura Bifano // PIXELATED

For more 3D Pixel and Voxel posts, search the particular topic at Blender Sushi.

FUTURE CHALLENGE FOR MYSELF AND YOU

Color Stippling Effects
http://www.joesfer.com/?p=149



The ups and downs state of learning Python. Mostly it goes up.

PYTHON "FILE" COMMAND

You may recall my previous post on Python programming:
http://blendersushi.blogspot.com.au/2012/12/python-importing-and-visualizing-data.html

That is only ONE of MANY WAYS you can import data and use it inside Blender using Python script.

On that post, I am using Blender bpy module and Python csv module. The csv module seems to be specifically designed to read comma separated value data, which I think was the right module to use to read that data.

Apparently we can also use Python FILE command to READ and even to WRITE data.
http://www.blog.pythonlibrary.org/2010/09/04/python-101-how-to-open-a-file-or-program/
http://docs.python.org/release/1.5/tut/node47.html#SECTION008210000000000000000

So, this post is just a quick additional note to that previous post. Hopefully it can be useful.

PYTHON IS UNIVERSAL, I LIKE IT
I am still slowly learning Python here and there. There are still many areas of Python that I do not understand (such as: how this language can be useful inside 3D packages), but I think I started to understand some patterns and some often used terminologies.


At the moment, I am studying Python for use inside Blender and Maya. Also for Houdini, a bit.

I watched many video tutorials that talk about Python for both Blender and Maya.  Also, I read plenty of blogs talking about Python and its usage inside Blender and Maya.


HACKING MAYA PYTHON SCRIPT AND USING IT FOR BLENDER
Something cool I realized today is the flexibility of this language to "talk" to many 3D programs out there that support Python language.

Today, for example, I was studying Maya's Python from this blog:
"Creating Curve from Stock Price Data" - Maya Python Way
http://u2325.com/tutorial/mayapython/3.html

The article talks about how you can READ and IMPORT data from outside into Maya and then PARSE and USE the data to CREATE CURVE.

He explained each step quite well, I definitely recommend you to have a read. Especially those related to Python in general. Also, the steps will help you to understand the whole procedure from getting the original data, passing it into the 3D software using Python, and so on.

In Maya, the full script goes to something like this, as I borrowed from that blog with slight modification and added comments:


import maya.cmds as mc

stockPath = "C:/google_stock.csv"

closePrices = []

dayCount = 0




scale = .01

f = open(stockPath)
line = f.readline()

while line:

if "Date" not in line and line != "":
parts = line.split(",")
closePrices.append(( dayCount * scale, float(parts[4]) * scale, 0))
dayCount = dayCount + 1
line = f.readline()

f.close()

# Create Curve and Rename
mc.curve( p= closePrices, n='priceCurve' )



I recommend you to read the full tutorial details over there to understand the logic behind the code, even though the code is for Maya, we can actually use it for Blender.

From all those Python code, the only real Maya command is down below:
mc.curve( p = closePrices, n='priceCurve')

That command is to CREATE CURVE based on the data passed into it. The rest of commands is really Python script, such as the IMPORT MODULE command at the very top.


I thought, it's pretty cool. Simple example, but very thoughful and useful.

Then, I was wondering if I could simply use the same Python Script inside Blender?

After all, there is only 1 simple Maya command in the end. It should be easy, right? Well.... yes and no. If only Blender Curve command works as SIMPLE as Maya and in similar fashion, we can probably plug in the data like that.

FORTUNATELY, there is another blog talking about Blender Python Scripting and it EXACTLY gives the answer I was looking for, including the explanation:

A quick read, that modified script of Blender "CREATE CURVE" seems to be the perfect for what I am trying to do. Yes, so Blender commands can be modified to work much simpler.

So, I mix and match both code together.

Below is the modified version of the script above, combined with Blender Scripting "CREATE CURVE" code:


import bpy
from mathutils import Vector

# FROM BLENDER SCRIPTING BLOG
# http://blenderscripting.blogspot.com.au/2011/05/blender-25-python-bezier-from-list-of.html

w = 1 # weight
listOfVectors = [Vector((0,0,0)),Vector((1,0,0)),Vector((2,0,0)),Vector((2,3,0)),
Vector((0,2,1))]

def MakePolyLine(objname, curvename, cList):
curvedata = bpy.data.curves.new(name=curvename, type='POLY')
curvedata.dimensions = '3D'

objectdata = bpy.data.objects.new(objname, curvedata)
objectdata.location = (0,0,0) #object origin
bpy.context.scene.objects.link(objectdata)

polyline = curvedata.splines.new('NURBS')
polyline.points.add(len(cList)-1)
for num in range(len(cList)):
x, y, z = cList[num]
polyline.points[num].co = (x, y, z, w)

polyline.order_u = len(polyline.points)-1
polyline.use_endpoint_u = True




# FROM U2325 BLOG
# http://u2325.com/tutorial/mayapython/5.html

stockPath = "C:/google_stock.csv"

closePrices = []

dayCount = 0

scale = .01

f = open(stockPath)
line = f.readline()

while line:

if "Date" not in line and line != "":
parts = line.split(",")
closePrices.append(( dayCount * scale, float(parts[4]) * scale, 0))
dayCount = dayCount + 1
line = f.readline()

f.close()

# Create Curve and Rename - Blender Scripting Style
# MakePolyLine("NameOfMyCurveObject", "NameOfMyCurve", listOfVectors)

MakePolyLine("MyCurveObject", "MyCurveData", closePrices)



When I ran that script, the magic happens: IT WORKS!

Yes, it actually does work right away.

And this is because the data flow and the functions of the the Python script is fundamentally the same. The data imported is the same, it gets processed (parsed), manipulated and turned into a list of 3 values or Vector values, and it simply goes into the Blender modified CREATE CURVE command and ... so it does the job!


Now that we discover a little truth of Python, you might as well want to read this article by Chad about "Python Scripting for Maya Artists":
http://www.chadvernon.com/blog/resources/python-scripting-for-maya-artists/

Any Python scripts that is generic is very likely to be reusable. 

JOHN MAEDA
My next reading will be this book. I had a quick look and read it casually. I like it a lot. Such a SIMPLE way to think of programming, especially for Computer Graphics and Design.

This guy, John Maeda, is not new in my dictionary. He has been quite an INSPIRATION for me quite a while since my student years. But not until recently when I read this book and UNDERSTAND what he is trying to say, I found this guy is really GENIUS.


That book helps to understand the LOGIC and FLOW of programming, visually. The book is pretty old and the program used inside the book is also really old. Luckily, the "Design By Numbers" program is still running on current machine and the book theory is really applicable.
The program is similar to Processing, but A LOT SIMPLER and very VISUAL (suitable for CG artist who wanted to understand CG and its beauty via programming).


In that book, John Maeda talks about procedural way of generating DOT and LINE (with unlimited variations) like no other computer graphic artists/developers, while at the same time explaining the concept of LOOP (repeat) and VARIABLE and ITERATION and COMMAND, and so on.

The cool thing is that he limits the whole thing to 100 x 100 pixel grid. Only. Maybe kind of like the Game of GO and its limitless variations.

So perhaps, we can do the same inside Blender. Why don't we mark around with Python to simply produce 3D position in space and ask Blender to do something with it.

Let say, simply creating bunch of Box or Sphere in certain position of 3D space, based on certain range of values. This code below creates bunch of Spheres in Sine pattern because I use Python MATH module.


import bpy
import math

for item in range(0,100,2):
locx = (item) * 1
locy = math.sin(item*0.1) * 20
#bpy.ops.mesh.primitive_cube_add(location=(locx, locy, 0), rotation=(0, 0, 0))
bpy.ops.mesh.primitive_uv_sphere_add(size=0.5, location=(locx, locy, 0))



I guess, that is another good way to approach Python programming and writing, especially for ARTIST. Do SIMPLE script first, and repeat using all kind of different ways.

EXAMPLE PROCESSING SKETCH CODE TRANSLATED INTO BLENDER PYTHON SCRIPT

Below script is originally written by Ira, the writer of "Processing Creative Coding Computational Foundation". The script is Processing Code to create simple gradient type of 2D artwork:


Book like that often has a lot of really nice conceptual coding, from beginner to advance scripts. Some of them is good and applicable for 3D coding.

SCRIPT: Create Pyramide Tower (from primitive cylinder)



import bpy

# Original script was based on:
# Processing Sketch PDE by Ira Greenberg, Dated: August 7, 2005
# Book Title: "Processing Creative Coding Computational Foundation"
# http://www.amazon.com/Processing-Creative-Coding-Computational-Foundation/dp/159059617X


# Blender's default 20 layers visibility for the object
myLayerDefault = (True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False)

# Setup the Pyramide
numberOfSteps = 20
gradientRadius = 20; 
interval = gradientRadius/numberOfSteps;
sideOfPyramide = 4 # based on cylinder primitive, how many edges you like

# Create gradient of pyramide
for i in range(numberOfSteps):
    bpy.ops.mesh.primitive_cylinder_add(vertices=sideOfPyramide, radius=gradientRadius-(interval*i), depth=1, end_fill_type='NGON', view_align=False, enter_editmode=False, location=(0, 0, i), rotation=(0, 0, 0), layers=myLayerDefault)




IT REALLY WAS NOT EASY AT FIRST
For me, the hardest part learning Python and Blender Python is to see the long Python commands, which is like Object and Method within another Object and Method, within another Object and Method  But I guess that is just how Python works with its Object Oriented Programming (OOP) paradigm.

CREATING POLYGON CUBE as Blender Python Operation, foe example, goes something like this:

bpy.ops.mesh.primitive_cube_add(view_align=False, enter_editmode=False, location=(5.72182, 4.81879, 5.76696), rotation=(0, 0, 0), layers=(True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False))

When I saw that command for the very first time, I was totally confused. The command of course can be reduced to this below (without any additional parameters or values or arguments)

bpy.ops.mesh.primitive_cube_add()

That will work as well, because there is the default values for that operation. But of course it will be more useful if we specified values like LOCATION for example.

bpy.ops.mesh.primitive_cube_add( location=(5.72182, 4.81879, 5.76696) )

You can also kind of turning that long operation command into your own like this:
makeCube = bpy.ops.mesh.primitive_cube_add
# without the parenthesis at the end
# this is called "dynamic function calling" according to below:
http://hetland.org/writing/instant-hacking.html

Below code will work, after you add the above snippet, if you want to change Blender command on the fly:
makeCube ( location=(5.72182, 4.81879, 5.76696) )

Knowing that information, we can then play with the imported data from above and pass it as LOCATION for the new object. I am using the Create Sphere command below, because with Sphere I can easily control the RADIUS SIZE of the Sphere:



CONCLUSION
Ok, so that is pretty much my blog post for today.

My point with this Python post is that once we are confident enough to start looking and reading at other people's "recipes" and understand what they do, we can "mix" and use them for our own problem.

Part of the big frustration in programming is often to find "function" or "procedure" that does thing the way you want it. Before finding that solution, sometimes we actually need to really understand the actual question (breaking the problem into smaller parts).

If we could not find that code, we need to build the function ourselves.

Programming may seem and feel like "not for everyone", but even as someone with non-programmer background myself, I found that understanding programming concept can be really beneficial for everyday life, but especially within this Computer Graphics area. Programming is a must have skill.

Hopefully we can further explore this Python universality from perspective of different 3D packages and use the universal knowledge and understanding for all our benefits. Peace!


FURTHER SELF EXPLORATION
http://wiki.blender.org/index.php/Dev:2.5/Py/Scripts/Cookbook/Code_snippets/Three_ways_to_create_objects
http://www.blenderaddons.com/tuts25/triangle25.php
http://blenderscripting.blogspot.com.au/2011/06/using-frompydata.html

This is another alternative of the above, this time we will pass on Vertex Data and create the graph as Mesh Edges:





import bpy
from mathutils import Vector





# FROM U2325 BLOG
# http://u2325.com/tutorial/mayapython/5.html

stockPath = "C:/google_stock.csv"

closePrices = []

dayCount = 0

scale = .01

f = open(stockPath)
line = f.readline()

while line:

if "Date" not in line and line != "":
parts = line.split(",")
closePrices.append(( dayCount * scale, float(parts[4]) * scale, 0))
dayCount = dayCount + 1
line = f.readline()

f.close()


'''
REFERENCES
http://wiki.blender.org/index.php/Dev:2.5/Py/Scripts/Cookbook/Code_snippets/Three_ways_to_create_objects
http://www.blenderaddons.com/tuts25/triangle25.php
http://blenderscripting.blogspot.com.au/2011/06/using-frompydata.html
'''

### Manually create of Polygon Mesh

scn = bpy.context.scene
graphMesh = bpy.data.meshes.new('graphMesh')

# Pass closePrices data from outside CSV data as Vertex XYZ Coordinate
vertData = closePrices

# Connect pair of Vertices data as Edges based on list order of vertices
edgeData = []

a=[]
b=[]

for number in range(len(closePrices)-1):
a.append(number)
b.append(number+1)

edgeData = list(zip(a, b))

graphMesh.from_pydata(vertData, (edgeData), ())

meshOb = bpy.data.objects.new('graphOb', graphMesh)

scn.objects.link(meshOb)






MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget