Scripting examples for 2.5 - update: Mar 26th 2010

calli: I just tested all the scripts (except the twitter one) with svn revision 23406 and they all worked correctly. Usually when things go wrong, some output can be found in the console (not the window inside blender, but the extra dos-like box on windows). I think they are planning to display output inside blender’s console window, but it’s not implemented yet.

pildanovak: I had some trouble getting your script to run. I had to override the object_OT_vsketch to return True from its polling function, or else the button was disabled (grey). I tested with build 23406. Any ideas?
What do you mean with the ‘options’?

This post has been updated for Blender 2.55 build 32738

Icons

Since it is hard to find which icons there are to use, I’ve written a script to display them along with their names (mouse-over for a tooltip, click to print to the console). These are the names that are used to draw them in the GUI (take a look at the “Hello world” script for an example).

# ##### BEGIN GPL LICENSE BLOCK #####
#
#  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 2
#  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, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####

# <pep8 compliant>


bl_addon_info = {
    'name': 'Icons',
    'author': 'Crouch, N.tox, PKHG',
    'version': (1, 3, 1),
    'blender': (2, 5, 5),
    'api': 32738,
    'location': 'Properties window > Object tab',
    'warning': '',
    'description': 'Creates a panel displaying all icons and their names.',
    'wiki_url': '',
    'tracker_url': '',
    'category': 'System'}


import bpy
import urllib.request


# create list with all icon names
def createIcons():
    # retrieving the masterlist with all icon names
    try:
        file = urllib.request.urlopen('https://svn.blender.org/svnroot/'\
        'bf-blender/trunk/blender/source/blender/editors/include/UI_icons.h')
    except:
        print("Couldn't find the urllib module or was unable to connect to"\
        " the internet")
        file = ''
    # get the icon names of existing non-blank icons
    icons = [str(l)[11:(-4 if l[-2]==b')' else (l.index(b')')+2))] for l in \
        file if ( (l[:9]==b'DEF_ICON(') and (l[9:19]!=b'ICON_BLANK') )]
    icons.sort()
    return icons


# create custom operator for each icon
def createOperators(icons):
    for i in icons:
        class custom_op(bpy.types.Operator):
            bl_idname = "ICONDISPLAY_OT_"+i
            bl_label = "ICONDISPLAY_OT_"+i
            bl_description = i
        
            def invoke(self, context, event):
                print(self.bl_description)
                return {'FINISHED'}


# main function that calls subroutines
def main():
    icons = createIcons()
    createOperators(icons)


# draw the panel with the icons
class OBJECT_PT_icons(bpy.types.Panel):
    bl_space_type = "PROPERTIES"
    bl_region_type = "WINDOW"
    bl_context = "object"
    bl_label = "All icons"
    
    icons = createIcons()
    
    def draw(self, context):
        amount = 10
        cols = []
        layout = self.layout
        split = layout.split(percentage=1.0/amount)
        for i,icon in enumerate(self.icons):
            if i<amount: cols.append(split.column())
            col = cols[i%amount].row()
            try:
                col.operator("icondisplay."+icon, text="", icon=icon)
            except:
                col.operator("icondisplay."+icon, text="new")


main()


def register():
    pass


def unregister():
    pass

http://sites.google.com/site/bartiuscrouch/images/25_05.png

The script needs a connection to the internet (to retrieve the source file in which all icons are named) and might need a full python install. The result can be seen at the bottom of the Object properties (just like the “Hello world” and “Ping pong” scripts), in its own panel called “All icons”.

Analysis
There isn’t much new in this script, but I’ll do a quick rundown on it.
createIcons() is a function to retrieve the source file from the internet and get the icon names in a list. This list (named ‘icons’) is used by the rest of the script.

createOperators() creates a custom operator class for each icon and registers it with blender. The reason I did this, is so that each icon can have its own tooltip (bl_description string). It might be dirty and not the best way to achieve this, but it was the only way I could think of.
What is new (compared to revision 22647) is that you can now define operators outside of the predetermined groups (like object, texture, world, ect.). You can create new groups by defining them in the idname of the new operator. It works like this:
bl_idname = MYNEWGROUP_OT_mynewoperatorname
You can then call it by using ‘mynewgroup.mynewoperatorname’ (as seen in line 47). Alternatively you can just store the operator at the highest level (among the operator groups, though this can quickly become a mess with name collisions) by using a random operator name:
bl_idname = mynewoperatorname

The last part is the class that actually draws the panel. I’ve chosen for a simple layout, with the amount of columns defined in line 49 (amount = 10). Any amount will work, but you’ll have to broaden the default panel width a bit to display more than 6 columns correctly.
As you can see I’m using operator() (operator pushbuttons) and not label() (simple labels). label() would also work to display the icons, but can’t display tooltips.

is there a way to save the pic of the icons in local folder or may be blender script fodler and then simply load up the file into 2.5?

i mean instead of getting it form the internet!

not working

Traceback (most recent call last):
File “C:\Users\RJ\0afast\blemd25\23285.blender\io
etrender_init_.py”, lin
e 3, in <module>
import model
File “C:\Users\RJ\0afast\blemd25\23285.blender\io
etrender\model.py”, line 2
, in <module>
import http, http.client, http.server, urllib
File “C:\Users\RJ\0afast\blemd25\23285\python31.zip\http\client.py”, line 69,
in <module>
File “C:\Users\RJ\0afast\blemd25\23285\python31.zip\email\parser.py”, line 12,
in <module>
File “C:\Users\RJ\0afast\blemd25\23285\python31.zip\email\feedparser.py”, line
27, in <module>
File “C:\Users\RJ\0afast\blemd25\23285\python31.zip\email\message.py”, line 17
, in <module>
File “C:\Users\RJ\0afast\blemd25\23285\python31.zip\email\utils.py”, line 27,
in <module>
File “C:\Users\RJ\0afast\blemd25\23285\python31.zip\socket.py”, line 45, in <m
odule>
ImportError: No module named _socket
unable to import C:\Users\RJ\0afast\blemd25\23285.blender\io/netrender
file_init
Couldn’t find the urllib module or was unable to connect to the internet

ater running the script where can we see the icons being drawn - whihc panel
object?

i’ll test with latest 2.5 release

very nice and good idea to see the icons
lot esier to select one in any case

Thanks

The reason an internet connection is needed, is because the UI_icons.h file is needed. It contains the names of all icons. You could also save that file to your harddisk and alter the script to fetch it from there, but the beauty of the current way is that the script will always get the most recent list.

There might be two reasons why the script isn’t working: either it couldn’t connect to the internet (no connection, firewall, etc.) or you don’t have a full python 3.1 install (most likely cause). Theoretically it should work without a full install, as blender comes with a zipped folder containing the main modules, but I’m not certain that’s already working correctly. So better be safe and install it.

The icons will show up at the bottom of the Object panel (Properties window), as I said in my previous post.

so i need to get python 3.1 full install

cause right now i got the one for 2.49C

and the partiel one for 2.5 that came with it
and the one for latest yafaray!

now i re run the script with 2.5 V 23285 hope this is good enough !

and kept an internet page open this time and no error from internet

now and i can see the top left - Icon phrase

but not the icons pics

now after running the script i check out my graphic for internet and did nt see any download done ?

any other suggestions for this file
should i find this icons file and put it somewhere else ?

Thanks

Thank you very much Crouch.

Yeah very helpful indeed:)

Ricky: the icons are already inside blender. The script simply retrieves a list with their names from the internet. Retrieving this list from the internet is usually invisible for the user, unless the firewall catches it and ask whether to block it or not.

mp3man4 and demohero: my pleasure. It’s just great to see all attempts in this forum of people trying to adapt to the new api, and we all learn by studying each other’s code.

I’ve updated the script (see it here). Two reasons:

  • The script would crash if in SVN a new icon was defined, and it wasn’t available in the blender build from which the script was run. With the updated script it’ll now display ‘new’ for icons that aren’t in the build yet.
  • I’ve grouped all operators in a custom defined group. This is a nice new technique (at least it wasn’t available in the previous build I tested) which prevents pollution of unrelated operator groups. For information on how this works, check my edited post.

i got v 385 release for vista

and copied the new script and tested it

i don’t have any error messages
and i can see on bottom of object window

that the phrase " all Icons " is there
so the script seems working ok except

that i don’t see the icons pictures !

so is there something else to be done to see theses icons?

may be i don’t have the latest version for vista ?

Thanks

I’m really out of ideas of what could be wrong. If nothing shows up in the console, I’m afraid I can’t help you anymore.
There could be a difference in the build for vista, but I’m still on XP and can’t test for other platforms. Sorry.

are you uisng an earlier version or later from 385?

if later than may be my version cannot do that yet !

this morning i was able to unzip the latest version 348
and tried again same thing

i can see the name of the script – " all Icons" at top left corner
but no icons pics?
and no error message on concole

any type of message i could print on the console to tell me if internet is workin on not
or other suggestions ?

Thanks

It seems that several modules have problems when they are in a zipped archive.
Did you unziip the python31.zip file in your blender executable’s folder itself (not in \python31 or in .blend\scripts ) ?

nie one you got it right !

now i can see the icons
that’s impressive

i tough this was done automatically when doing the unzip !

i’ll try to remember that one for other version

Thanks a lot for this info

GREAT, the icons script
I used it just replacing the name in “My new panel” script to a different one ==> Worked!

And thanks to all the other examples …very helpful indeed.
I am getting more and more excited with respect to Blender 2.5!

I’m having some trouble with something that seems really basic. I’m putting together a simple .blend file to demonstrate my problem. I need to automatically go into a specified armature object’s editmode for my rigging script. I toggle the objects “.selected” and “.active” tag and run bpy.ops.object.mode_set(mode=‘EDIT’), and I get a context error. Anyone mind looking at the .blend and telling me what I need to be selecting or what I should do to go into edit mode on a specified armature?

seems like a simple problem but its a bugger… :slight_smile:

blend file

try selecting the camera in the viewer and running the script. The problem should be pretty apparent:)

I decided it was a bug and reported it on the bug tracker, and Campbell posted this explanation of how it should be done as of release 24354.

armOb = bpy.data.objects["armOb"]
rig = bpy.data.armatures["rig"]
for ob in bpy.data.objects: ob.selected = False
armOb.selected = True
bpy.context.scene.objects.active = armOb

bpy.ops.object.mode_set(mode='EDIT')

You’ll get an error if you try this in a much earlier build because the context module doesn’t exist in those builds.

so when converting an existing script to 2.5 do we just need to change all the calls or is there something else?

The entire API and structure of it is different so I’d image that most scripts will have to have extensive reworking…

Noticed this thread is kinda dead, but I went through it yesterday and found it pretty helpful for getting started with the new python scripting API. Anyone following our footsteps should note one thing though. Somewhere along the line the special variables being used by blender for it’s internal ui classes changed their naming convention.

Wherever you find “variable_name” you should rewrite it as “bl_variable_name”. This should allow all of the above scripts to work with the current trunk.

Thank you very much Crouch for the icon script. It seems python scripting for blender 2.5 is a Moving Target, because your version seems to refuse working with my november version.
I did some small changes, including the needed changes suggested by Lockyer above this post.
The updated code is here:
http://www.pasteall.org/9070/python

http://www.pasteall.org/pic/100http://www.pasteall.org/pic/show.php?id=100

At least it now works for me. Thanks again for giving more insight into the
voodoo of 2.5 scripting. :wink: