1
2
3 """
4 Blender Python related features
5 ===============================
6
7 L{Back to Main Page<API_intro>}
8
9
10 Introduction:
11 =============
12
13 This page describes special features available to BPython scripts:
14
15 - Command line mode is accessible with the '-P' and '-b' Blender options.
16 - Registration allows scripts to become available from some pre-defined menus
17 in Blender, like Import, Export, Wizards and so on.
18 - Script links are Blender Texts (scripts) executed when a particular event
19 (redraws, .blend file loading, saving, frame changed, etc.) occurs. Now
20 there are also "Space Handlers" to draw onto or get events from a given
21 space (only 3D View now) in some window.
22 - Proper documentation data is used by the 'Scripts Help Browser' script to
23 show help information for any registered script. Your own GUI can use
24 this facility with the L{Blender.ShowHelp} function.
25 - Configuration is for data in your script that can be tweaked according to
26 user taste or needs. Like documentation, this is another helper
27 functionality -- you don't need to provide a GUI yourself to edit config
28 data.
29
30
31 Command line usage:
32 ===================
33
34 Specifying scripts:
35 -------------------
36
37 The '-P' option followed either by:
38 - a script filename (full pathname if not in the same folder where you run
39 the command);
40 - the name of a Text in a .blend file (that must also be specified)
41 will open Blender and immediately run the given script.
42
43 Example::
44
45 # open Blender and execute the given script:
46 blender -P script.py
47
48 Passing parameters:
49 -------------------
50
51 To pass parameters to the script you can:
52 - write them to a file before running Blender, then make your script parse that file;
53 - set environment variables and access them with the 'os' module:
54
55 Examples with parameters being passed to the script via command line::
56
57 # execute a command like:
58
59 myvar=value blender -P script.py
60
61 # and in script.py access myvar with os.getenv
62 # (os.environ and os.setenv are also useful):
63
64 # script.py:
65 import os
66 val = os.getenv('myvar')
67
68 # To pass multiple parameters, simply write them in sequence,
69 # separated by spaces:
70
71 myvar1=value1 myvar2=value2 mystr="some string data" blender -P script.py
72
73 Background mode:
74 ----------------
75
76 In '-b' mode no windows will be opened: the program will run as a command
77 line tool able to render stills and animations and execute any working Python
78 script with complete access to loaded .blend's file contents. Once the task
79 is completed, the program will exit.
80
81 Background mode examples::
82
83 # Open Blender in background mode with file 'myfile.blend'
84 # and run the script 'script.py':
85
86 blender -b myfile.blend -P script.py
87
88 # Note: a .blend file is always required. 'script.py' can be a file
89 # in the file system or a Blender Text stored in 'myfile.blend'.
90
91 # Let's assume 'script.py' has code to render the current frame;
92 # this line will set the [s]tart and [e]nd (and so the current) frame to
93 # frame 44 and call the script:
94
95 blender -b myfile.blend -s 44 -e 44 -P script.py
96
97 # Using now a script written to render animations, we set different
98 # start and end frames and then execute this line:
99
100 blender -b myfile.blend -s 1 -e 10 -P script.py
101
102 # Note: we can also set frames and define if we want a single image or
103 # an animation in the script body itself, naturally.
104
105 The rendered pictures will be written to the default render folder, that can
106 also be set via BPython (take a look at L{Render.RenderData}). Their
107 names will be the equivalent frame number followed by the extension of the
108 chosen image type: 0001.png, for example. To rename them to something else,
109 coders can use the C{rename} function in the standard 'os' Python module.
110
111 Reminder: if you just need to render, it's not necessary to have a script.
112 Blender can create stills and animations with its own command line arguments.
113 Example:
114 - a single image at frame 44: blender -b myfile.blend -f 44
115 - an animation from frame 1 to 10: blender -b myfile.blend -s 1 -e 10 -a
116
117
118 Script links:
119 =============
120
121 Object script links:
122 --------------------
123
124 Users can link Blender Text scripts and objects to have the script
125 code executed when specific events occur to the objects. For example, if a
126 Camera has an script link set to "FrameChanged", the script will be executed
127 whenever the current frame is changed. Links can either be manually added by
128 users on the Buttons window -> Scripts tab or created by another script (see,
129 for example, L{Object.addScriptLink<Object.Object.addScriptLink>}).
130
131 These are the types which can be linked to scripts:
132 - Camera Data;
133 - Lamp Data;
134 - Materials;
135 - Objects;
136 - Scenes;
137 - Worlds.
138
139 And these are the available event choices:
140 - Redraw;
141 - FrameChanged;
142 - Render;
143 - OnLoad (*);
144 - OnSave (*).
145
146 (*) only available for scenes
147
148 There are three L{Blender} module variables that script link authors should
149 be aware of:
150 - B{bylink}: True if the script is running as a script link;
151 - B{link}: the object the running script was linked to (None if this is
152 not a script link);
153 - B{event}: the event type, if the running script is being executed as a
154 script link.
155
156 Example::
157 #script link
158 import Blender
159 if Blender.bylink: # we're running as a script link
160 print "Event: %s for %s" % (Blender.event, Blender.link)
161
162 B{Important note about "Render" events}:
163
164 Each "Render" script link is executed twice: before rendering and after, for
165 reverting changes and for possible clean up actions. Before rendering,
166 'Blender.event' will be "Render" and after rendering it will be "PostRender".
167
168 Example::
169 # render script link
170 import Blender
171 event = Blender.event
172 if event == "Render":
173 # prepare for rendering
174 create_my_very_detailed_mesh_data()
175 elif event == "PostRender":
176 # done rendering, clean up
177 delete_my_very_detailed_mesh_data()
178
179 As suggested by the example above, this is especially useful for script links
180 that need to generate data only useful while rendering, or in case they need
181 to switch between two mesh data objects, one meant for realtime display and
182 the other, more detailed, for renders.
183
184 Space Handler script links:
185 ---------------------------
186
187 This is a new kind of script linked to spaces in a given window. Right now
188 only the 3D View has the necessary hooks, but the plan is to add access to
189 other types, too. Just to clarify naming conventions: in Blender, a screen
190 is partitioned in windows (also called areas) and each window can show any
191 space. Spaces are: 3D View, Text Editor, Scripts, Buttons, User Preferences,
192 Oops, etc.
193
194 Space handlers are texts in the Text Editor, like other script links, but they
195 need to have a special header to be recognized -- B{I{the first line in the
196 text file}} must inform:
197 1. that they are space handlers;
198 2. the space they belong to;
199 3. whether they are EVENT or DRAW handlers.
200
201 Example header for a 3D View EVENT handler::
202
203 # SPACEHANDLER.VIEW3D.EVENT
204
205 Example header for a 3D View DRAW handler::
206
207 # SPACEHANDLER.VIEW3D.DRAW
208
209 Available space handlers can be toggled "on" or "off" in the space header's
210 B{View->Space Handler Scripts} submenu, by the user.
211
212 EVENT space handler scripts are called by that space's event handling callback
213 in Blender. The script receives the event B{before} it is further processed
214 by the program. An EVENT handler script should check Blender.event (compare
215 it against L{Draw} events) and either:
216 - process it (the script must set Blender.event to None then);
217 - ignore it.
218
219 Setting C{Blender.event = None} tells Blender not to go on processing itself
220 the event, because it was grabbed by the script.
221
222 Example::
223
224 # SPACEHANDLER.VIEW3D.EVENT
225
226 import Blender
227 from Blender import Draw
228 evt = Blender.event
229 return_it = False
230
231 if evt == Draw.LEFTMOUSE:
232 print "Swallowing the left mouse button press"
233 elif evt == Draw.AKEY:
234 print "Swallowing an 'a' character"
235 else:
236 print "Let the 3D View itself process this event:", evt
237 return_it = True
238
239 # if Blender should not process itself the passed event:
240 if not return_it: Blender.event = None
241
242 DRAW space handlers are called by that space's drawing callback in Blender.
243 The script is called B{after} the space has been drawn.
244
245 Two of the L{Blender} module variables related to script links assume
246 different roles for space handlers:
247 - B{bylink} is the same: True if the script is running as a script link;
248 - B{link}: integer from the L{Blender}.SpaceHandlers constant dictionary,
249 tells what space this handler belongs to and the handler's type
250 (EVENT, DRAW);
251 - B{event}:
252 - EVENT handlers: an input event (check keys and mouse events in L{Draw})
253 to be processed or ignored.
254 - DRAW handlers: 0 always.
255
256 B{Guidelines (important)}:
257 - EVENT handlers can access and change Blender objects just like any other
258 script, but they should not draw to the screen, B{use a DRAW handler to do
259 that}. Specifically: L{Draw.Image} and the L{BGL} drawing functions
260 should not be used inside an EVENT handler.
261 - DRAW handlers should leave the space in the same state it was before they
262 were executed. OpenGL attributes and the modelview and projection matrices
263 are automatically saved (pushed) before a DRAW handler runs and restored
264 (popped) after it finishes, no need to worry about that. Draw handlers
265 should not grab events;
266 - If script handlers need to pass information to each other (for example an
267 EVENT handler passing info to a DRAW handler), use the L{Registry} module.
268 - in short: use the event handler to deal with events and the draw handler to
269 draw and your script will be following the recommended practices for
270 Blender code.
271
272 Registering scripts:
273 ====================
274
275 To be registered a script needs two things:
276 - to be either in the default scripts directory or in the user defined scripts
277 path (see User Preferences window -> File Paths tab -> Python path);
278 - to have a proper header.
279
280 Try 'blender -d' to know where your default directory for scripts is, it will
281 inform either the directory or the file with that info already parsed, which is
282 in the same directory of the scripts folder.
283
284 The header should be like this one (all double and single apostrophes below
285 are required)::
286 #!BPY
287
288 # \"\"\"
289 # Name: 'Script Name'
290 # Blender: 233
291 # Group: 'Export'
292 # Submenu: 'All' all
293 # Submenu: 'Selected' sel
294 # Submenu: 'Configure (gui)' gui
295 # Tooltip: 'Export to some format.'
296 # \"\"\"
297
298 where:
299 - B{Name} is the string that will appear in the menu;
300 - B{Blender} is the minimum program version required to run the script;
301 - B{Group} defines where the script will be put, see all groups in the
302 Scripts Window's header, menu "Scripts";
303 - B{Submenu} adds optional submenus for further control;
304 - B{Tooltip} is the (short) tooltip string for the menu entry.
305
306 note:
307 - all double and single apostrophes above are required;
308 - you can "comment out" the header above, by starting lines with
309 '#', like we did. This is not required (except for the first line, #!BPY,
310 of course), but this way the header won't conflict with Python tools that
311 you can use to generate documentation for your script code. Just
312 remember to keep this header above any other line with triple
313 double-quotes (\"\"\") in your script.
314
315 Submenu lines are not required, use them if you want to provide extra
316 options. To see which submenu the user chose, check the "__script__"
317 dictionary in your code: __script__['arg'] has the defined keyword (the word
318 after the submenu string name: all, sel or gui in the example above) of the
319 chosen submenu. For example, if the user clicked on submenu 'Selected' above,
320 __script__['arg'] will be "sel".
321
322 If your script requires extra data or configuration files, there is a special
323 folder where they can be saved: see 'datadir' in L{Blender.Get}.
324
325
326 Documenting scripts:
327 ====================
328
329 The "Scripts Help Browser" script in the Help menu can parse special variables
330 from registered scripts and display help information for users. For that,
331 authors only need to add proper information to their scripts, after the
332 registration header.
333
334 The expected variables:
335
336 - __bpydoc__ (or __doc__) (type: string):
337 - The main help text. Write a first short paragraph explaining what the
338 script does, then add the rest of the help text, leaving a blank line
339 between each new paragraph. To force line breaks you can use <br> tags.
340
341 - __author__ (type: string or list of strings):
342 - Author name(s).
343
344 - __version__ (type: string):
345 - Script version. A good recommendation is using a version number followed
346 by the date in the format YYYY/MM/DD: "1.0 2005/12/31".
347
348 - __url__ (type: string or list of strings):
349 - Internet links that are shown as buttons in the help screen. Clicking
350 them opens the user's default browser at the specified location. The
351 expected format for each url entry is e.g.
352 "Author's site, http://www.somewhere.com". The first part, before the
353 comma (','), is used as the button's tooltip. There are two preset
354 options: "blender" and "blenderartists.org", which link to the Python forums at
355 blender.org and blenderartists.org, respectively.
356
357 - __email__ (optional, type: string or list of strings):
358 - Equivalent to __url__, but opens the user's default email client. You
359 can write the email as someone:somewhere*com and the help script will
360 substitute accordingly: [email protected]. This is only a minor help
361 to hide emails from spammers, since your script may be available at some
362 site. "scripts" is the available preset, with the email address of the
363 mailing list devoted to scripting in Blender, [email protected].
364 You should only use this one if you are subscribed to the list:
365 http://projects.blender.org/mailman/listinfo/bf-scripts-dev for more
366 information.
367
368 Example::
369 __author__ = 'Mr. Author'
370 __version__ = '1.0 2005/01/01'
371 __url__ = ["Author's site, http://somewhere.com",
372 "Support forum, http://somewhere.com/forum/", "blender", "blenderartists.org"]
373 __email__ = ["Mr. Author, mrauthor:somewhere*com", "scripts"]
374 __bpydoc__ = \"\"\"\\
375 This script does this and that.
376
377 Explaining better, this script helps you create ...
378
379 You can write as many paragraphs as needed.
380
381 Shortcuts:<br>
382 Esc or Q: quit.<br>
383 etc.
384
385 Supported:<br>
386 Meshes, metaballs.
387
388 Known issues:<br>
389 This is just an example, there's no actual script.
390
391 Notes:<br>
392 You can check scripts bundled with Blender to see more examples of how to
393 add documentation to your own works.
394 \"\"\"
395
396 B{Note}: your own GUI or menu code can display documentation by calling the
397 help browser with the L{Blender.ShowHelp} function.
398
399 Configuring scripts:
400 ====================
401
402 The L{Blender.Registry<Registry>} module provides a simplified way to keep
403 scripts configuration options in memory and also saved in config files.
404 And with the "Scripts Config Editor" script in the System menu users can later
405 view and edit the options easily.
406
407 Let's first clarify what we mean by config options: they are simple data
408 (bools, ints, floats, strings) used by programs to conform to user
409 preferences. The buttons in Blender's User Preferences window are a good
410 example.
411
412 For example, a particular exporter might include:
413 - SEPARATE_MATS = False: a bool variable (True / False) to determine if it
414 should write materials to a separate file;
415 - VERSION = 2: an int to define an specific version of the export format;
416 - TEX_DIR = "/path/to/textures": a default texture dir to prepend to all
417 exported texture filenames instead of their actual paths.
418
419 The script needs to provide users a GUI to configure these options -- or else
420 directly editing the source code would be the only way to change them. And to
421 store changes made to the GUI so they can be reloaded any time the script is
422 executed, programmers have to write and load their own config files (ideally at
423 L{Blender.Get}('udatadir') or, if not available, L{Blender.Get}('datadir')).
424
425 This section describes BPython facilities (based on the L{Registry} module and
426 the config editor) that can take care of this in a simplified (and much
427 recommended) way.
428
429 Here's how it works::
430
431 # sample_exporter.py
432 import Blender
433 from Blender import Registry
434
435 # First define all config variables with their default values:
436 SEPARATE_MATERIALS = True
437 VERSION = True
438 TEX_DIR = ''
439 EXPORT_DIR = ''
440
441 # Then define a function to update the Registry:
442 def registry_update():
443 # populate a dict with current config values:
444 d = {
445 'SEPARATE_MATERIALS': SEPARATE_MATERIALS,
446 'VERSION': VERSION,
447 'TEX_DIR': TEX_DIR,
448 'EXPORT_DIR': EXPORT_DIR
449 }
450 # store the key (optional 3rd arg tells if
451 # the data should also be written to a file):
452 Registry.SetKey('sample_exporter', d, True)
453
454 # (A good convention is to use the script name as Registry key)
455
456 # Now we check if our key is available in the Registry or file system:
457 regdict = Registry.GetKey('sample_exporter', True)
458
459 # If this key already exists, update config variables with its values:
460 if regdict:
461 try:
462 SEPARATE_MATERIALS = regdict['SEPARATE_MATERIALS']
463 VERSION = regdict['VERSION']
464 TEX_DIR = regdict['TEX_DIR']
465 EXPORT_DIR = regdict['EXPORT_DIR']
466
467 # if data was corrupted (or a new version of the script changed
468 # (expanded, removed, renamed) the config vars and users may have
469 # the old config file around):
470 except: update_registry() # rewrite it
471
472 else: # if the key doesn't exist yet, use our function to create it:
473 update_registry()
474
475 # ...
476
477 Hint: nicer code than the simplistic example above can be written by keeping
478 config var names in a list of strings and using the exec function.
479
480 B{Note}: if your script's GUI lets users change config vars, call the
481 registry_update() function in the button events callback to save the changes.
482 On the other hand, you don't need to handle configuration
483 in your own gui, it can be left for the 'Scripts Config Editor',
484 which should have access to your script's config key as soon as the
485 above code is executed once (as soon as SetKey is executed).
486
487 B{Note} (limits for config vars): strings longer than 300 characters are
488 clamped and the number of items in dictionaries, sequences and the config key
489 itself is limited to 60.
490
491
492 Scripts Configuration Editor:
493 -----------------------------
494
495 This script should be available from the System menu in the Scripts window.
496 It provides a GUI to view and edit saved configuration data, both from the
497 Registry dictionary in memory and the scripts config data dir. This is
498 useful for all scripts with config vars, but especially for those without GUIs,
499 like most importers and exporters, since this editor will provide one for them.
500
501 The example above already gives a good idea of how the information can be
502 prepared to be accessible from this editor, but there is more worth knowing:
503
504 1. String vars that end with '_dir' or '_file' (can be upper case, too) are
505 recognized as input boxes for dirs or files and a 'browse' button is added to
506 their right side, to call the file selector.
507
508 2. Both key names and configuration variables names starting with an
509 underscore ('_') are ignored by the editor. Programmers can use this feature
510 for any key or config var that is not meant to be configured by this editor.
511
512 3. The following information refers to extra config variables that may be
513 added specifically to aid the configuration editor script. To clarify, in the
514 example code above these variables (the string 'script' and the dictionaries
515 'tooltips' and 'limits') would appear along with SEPARATE_MATERIALS, VERSION,
516 TEX_DIR and EXPORT_DIR, wherever they are written.
517
518 Minor note: these names are case insensitive: tooltips, TOOLTIPS, etc. are all
519 recognized.
520
521 3.1 The config editor will try to display a 'help' button for a key, to show
522 documentation for the script that owns it. To find this "owner script", it
523 will first look for a config variable called 'script', a string containing
524 the name of the owner Python file (with or without '.py' extension)::
525
526 script = 'sample_exporter.py'
527
528 If there is no such variable, the editor will check if the file formed by the
529 key name and the '.py' extension exists. If both alternatives fail, no help
530 button will be displayed.
531
532 3.2 You can define tooltips for the buttons that the editor creates for your
533 config data (string input, toggle, number sliders). Simply create a dict
534 called 'tooltips', where config var names are keys and their tooltips,
535 values::
536
537 tooltips = {
538 'EXPORT_DIR': 'default folder where exported files should be saved',
539 'VERBOSE': 'print info and warning messages to the console',
540 'SEPARATE_MATERIALS': 'write materials to their own file'
541 }
542
543 3.3 Int and float button sliders need min and max limits. This can be passed
544 to the editor via a dict called 'limits' (ivar1, ivar2 and fvar are meant as
545 extra config vars that might have been in the example code above)::
546
547 limits = {'ivar1': [-10, 10], 'ivar2': [0, 100], 'fvar1': [-12.3, 15.4]}
548
549 4. The Config Editor itself maintains a Registry key called "General", with
550 general options relevant to many scripts, like "verbose" to tell if the user
551 wants messages printed to the console and "confirm overwrite", to know if
552 a script should ask for confirmation before overwriting files (all exporters
553 are recommended to access the General key and check this var -- L{sys.exists
554 <Sys.exists>} tells if files or folders already exist).
555
556 Hint: for actual examples, try the ac3d importer and exporter (it's enough to
557 call them from the menus then cancel with ESC), as those have been updated to
558 use this config system. After calling them their config data will be available
559 in the Config Editor. We also recommend adding a section about config vars
560 in your script's help info, as done in the ac3d ones.
561
562 L{Back to Main Page<API_intro>}
563 ===============================
564 """
565