SlideShare une entreprise Scribd logo
1  sur  37
Télécharger pour lire hors ligne
Python-Programming in
Katana
for beginner's
M.Kedarnath
Structure of the book
Overview
The following documentation will give basic understanding of the below topics. After
going through this one can be able to script small programs using python. Which also gives a
basic understanding how Katana works inside and will be able to automate Katana as per
requirement.
• Understanding scripting
• Python-programming
• Understanding Katana
• Katana Scripting
Prerequisite
Knowledge of Katana to understand scripting for Katana
Programming and Scripting
Scripting languages are languages that don't require an explicit compilation step. For
example, you have to compile a C program before you can run it. But in the normal case, you
don't have to compile a JavaScript program before you run it. So JavaScript is sometimes
called a "scripting" language.
Some examples of "scripting" languages (languages that are traditionally used without
an explicit compilation step):
• Python
• JavaScript
• VBScript
And examples which traditionally used with an explicit compilation step:
• C
• C++
• Java
• Fortan
Few advantages of Scripting/ programming
• Automation
• creating new tools
• extending the capability of a software
Different programming Types
Procedural programming: is a programming paradigm, derived from structured
programming, based upon the concept of the procedure call. Procedures, also known as
routines, subroutines, methods or functions, simply contain a series of computational steps to
be carried out.
Object-oriented programming (OOP): is a programming paradigm based on the concept of
"objects", which are data structures that contain data, in the form of fields, often known as
attributes, and code, in the form methods. object-oriented programming that uses classes is
sometimes called class-based programming.
Few features of OOPs
• Inheritance
• Abstraction
• Polymorphism
• Instances
Overview of OOPs Terminology
• Class: A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes and methods, accessed via dot
notation.
• Class variable: A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods.
• Data member: A class variable or instance variable that holds data associated with a
class and its objects.
• Function overloading: The assignment of more than one behavior to a particular
function. The operation performed varies by the types of objects (arguments) involved.
• Instance variable: A variable that is defined inside a method and belongs only to the
current instance of a class.
• Inheritance : The transfer of the characteristics of a class to other classes that are
derived from it.
• Instance: An individual object of a certain class. An object obj that belongs to a class
Circle, for example, is an instance of the class Circle.
• Instantiation : The creation of an instance of a class.
• Object : An object is instance of a data structure that's defined by its class. An object
has data members and methods.
Python
Python can do almost all types of things except creating OS. For python we can use
words - scripting and programming interchangeably. Python runs through interpreter and also
can be compiled and used. Python supports multiple programming paradigms, including
object-oriented, imperative and functional programming or procedural styles. It features a
dynamic type system and automatic memory management and has a large and
comprehensive standard library
Python is used in various developments.
• GIS Programmings
• Web developments
• Desktop applications
• Network programming
• In VFX it can be used for Pipeline development as well as it can be used in
Maya/Katana/Nuke etc.
About python
Python is an interpreted programming language .Also it is open source software,
making it freely usable and distributable, version 3.4.3 is the latest version available and
freely downloadable through www.python.org .
Most current Linux distributions and Macs are still using 2.x as default. Also most of
the VFX Houses use 2.x, so we are going to concentrate in 2.x. There is a syntax differences
in 2.x and 3.x.
Why Python
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python was designed to be highly readable which uses English keywords frequently where
as other languages use punctuation and it has fewer syntactical constructions than other
languages.
• Python is Interpreted: This means that it is processed at run time by the interpreter and
we do not need to compile our program before executing it. This is similar to PERL
and PHP.
• Python is Interactive: This means that you can actually us Python prompt and interact
with the interpreter using python statements directly to write your programs.
• Python is Object-Oriented: This means that Python supports Object-Oriented style or
technique of programming which allows to use OOPs concepts like encapsulation,
inheritance etc.
• Python is Beginner's Language: Python is a great language for the beginner
programmers and with easy syntax, and also supports the development of a wide
range of applications
We have IDLE ((Integrated DeveLopment Environment ) to write scripts. We can also
use any text editor to write python scripts.
Few definitions related to python
Pyside: Python bindings for QT (similar to pyqt4)
Pymel: Python binding for MEL
Modules: A module is a python file that generally has only definitions of variables,
functions, and classes. Modules in Python are simply Python files with the .py
extension,
Functions: Functions are programs that perform a specific task, which you can incorporate
into your own, larger programs. After you have created a function, you can use
it at any time, in any place.
Packages: A package is a set of modules or sub-packages. A package is actually a
directory containing either .py files or sub-directories defining other packages.
When loading a package, the __init__.py file is executed
Getting into Python
Download and install python. By default python is installed in linux distributions. Get
into shell and type python to start python directly in shell.
[abc@localhost]# python
Here we can find which version of python we are using on which version GCC. To get
out of python use command exit()
>>>exit()
Syntax of python
Identifier is the name given to entities like class, functions, variables etc. in Python. It
helps differentiating one entity from another. Python is a case sensitive programming
language. Thus, name and Name are two different identifiers in Python.
Here are following naming convention for Python:
• Class names start with an uppercase letter and all other identifiers with a lowercase
letter.
• Starting an identifier with a single leading underscore indicates by convention that the
identifier is private.
Reserved words
The following list shows the reserved words in Python. These reserved words may not
be used as constant or variable or any other identifier names. All the Python keywords
contain lowercase letters only.
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Lines and Indentation:
There are no braces to indicate blocks of code for class and function definitions or flow
control. Blocks of code are denoted by line indentation, which is important to keep in mind.
The number of spaces in the indentation is variable, but all statements within the block must
be indented the same amount. In the below example the indentation is different for If and else
, this is wrong in python
if True:
print "True"
else:
print "False"
Multi-Line Statements:
Statements in python are usually one liners. Python allows the use of the line
continuation character () to denote that the line should continue. For example:
>>> total = 5+ 
6 + 
8
Quotation in Python:
Python accepts single ('), double (") and triple (''' or """) quotes to denote strings , as
long as the same type of quotes ends the string. In the below example all are correct.
>>> a = 'hi'
>>> a= “hi”
>>> a= ''' hi'''
Comments in Python:
A hash sign (#) begins a comment. All characters after the # and up to the physical line
end are part of the comment and the Python interpreter ignores them.
Multiple Statements on a Single Line:
The semicolon ( ; ) allows multiple statements. Here is a sample snip using the
semicolon:
>>>import sys; x = 'foo'; sys.stdout.write(x + 'n')
Writing Python scripts
Lets get into command line python / Interactive mode, where we can directly type
python statements/ commands. To print anything use print command with quotes. You can
see both types of quotes are working.
We can do all mathematical operations directly in python console interactively.
Data types in Python:
• Numbers : Python supports different numerical types:
• int (signed integers)
• long (long integers [can also be represented in octal and hexadecimal])
• float (floating point real values)
• complex (complex numbers)
• String : Strings in Python are identified as a set of characters in between quotations.
• List : Lists are Python's compound data types. A list contains items separated by
commas and enclosed within square brackets ([]). To some extent, lists are similar to
arrays in C. One difference between them is that all the items belonging to a list can
be of different data type. The values stored in a list can be accessed using the slice
operator ( [ ] and [ : ] ) with indexe starting at 0.
• Tuple : A tuple is another data type that is similar to the list. A tuple consists of a
number of values separated by commas. The main differences between lists and
tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be
changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
Tuples can be thought of as read-only lists.
• Dictionary : can store any number of Python objects, including other container types.
Dictionaries consist of pairs (called items) of keys and their corresponding values.
>>>dict = { 'abc': 123, 'bb': 37 };
Along with the command line statements we can save .py file and run it through
command line. Different commands / statements can be combined in a python file and which
can be executed using 'python' command in shell.
[abc@localhost]# python firstscript.py
Now lets write a script which takes input from user and does some mathematical
calculations. The script ask user to input radius of sphere and it calculates circumference and
prints it.
Operators
There are several types of operators available in scripting and programming language.
Lets look at operators can be used in python-programming.
Mathematical operators
• + Addition
• - Subtraction
• * Multiplication
• / Division
• % Reminder
• ** exponent 10**20 is 10 to the power 20
• // floor division 9//2 is equal to 4
Comparison operators
• == equal
• != not equal
• <> not equal
• > greater than
• < less than
• >= greater than or equal
• <= less than or equal
Assignment operators
• = equal
• += c +=a is equivalent to c = c+a
• -= c-=a is equivalent to c=c-a
• *= c =a is equivalent to c= c*a
• /= c/=a is equivalent to c =c/a
• %= c%=a is equivalent to c=c%a
• **= c**=a is equivalent to c=c**a
• //= c//=a is equivalent to c=c//a
Logical operators
• and (a and b) is true
• or (a or b) is true
• not not (a )
Membership operators
• in x in y, result is 1 if x is a member of y
• not in x not in y, results 1 if x is not a member of y
Decision Making
if statements:An if statement consists of a expression followed by one or more
statements.
if...else : An if statement can be followed by an optional else statement, which executes
when the boolean expression is false.
nested if: You can use one if or else if statement inside another if or else if statement(s).
# syntax for input and operator if, elseif and else
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
Loops
while loop: Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.
# the sum of two elements defines the next
a, b = 0, 1
while b < 200:
print b,
b = a+b
for loop: Executes a sequence of statements multiple times and abbreviates the code
that manages the loop variable.
Nested loops:You can use one or more loop inside any another while, for or do..while loop.
Break: Terminates the loop statement
Continue: Causes the loop to skip the remainder of its body and immediately retest its
condition before to reiterating.
Pass: The pass statement in Python is used when a statement is required
but you do not want any command to execute.
# using loops and break operator
for n in range(2, 1000):
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
# loop fell through without finding a factor
print n, 'is a prime number'
Functions:
You can define functions to create the required functionality. Here are few
rules to define a function in Python.
• Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. we
can also define parameters inside these parentheses.
• The code in every function starts with a colon (:) and is indented.
• IT returns value [expression] .
#syntax of a function
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Global vs. Local variables:
Variables that are defined inside a function body are local, and those defined outside
are global variables. Global variables can be used in other functions as well. Writing a
function for equiation wtith arguments
#Writing a sample function
def myfunc(n):
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
# Now call the function we just defined:
>>>myfunc(20)
Modules
A module is an organised Python code. Adding related code into a module makes the
code easier to understand and use. Simply, a module is a file consisting of Python code. A
module can define functions, classes and variables. A module can also include runnable
code.
The from...import Statement
Python's from statement lets us import specific attributes from a module into the current
scripts The from...import has the following syntax:
from modulename import name
We can use 'import' in python to import different modules.
Examples :
from Katana import Nodes3DAPI
from PyQT4 import UI4
Syntax of module
### EXAMPLE
# Define variables:
one = 1
pi = 3.14
# defining functions
def printhello():
print "hello"
def circumf(input):
print input * 2*pi
# define a class
class mytest:
def __init__(self):
self.name = input("Name class? ")
self.num = input("number of students")
self.section = input("section of class")
def printdetails(self):
print "name of class is " + self.name
print self.section, "has, " + self.num +”of students
once we have run the above module it created .pyc file. Now in the folder we can see
firstmodule.py and firstmodule.pyc.
.pyc contain the compiled bytecode of Python source files. The Python interpreter
loads .pyc files before .py files, so if they're present, it can save some time by not having to
re-compile the Python source code
Locating Modules:
When we import a module, the Python interpreter searches for the module in the
following sequences. One can write own python modules and keep at PYTHONPATH
location and use import to use the functions and classes
• The current directory.
• If the module isn't found, Python then searches each directory in the shell variable
called PYTHONPATH.
• Both fails, Python checks the default path which is /usr/local/lib/python/. In linux
The PYTHONPATH is an environment variable, which has list of directories.
We can set the path location using the below statement in windows using environment
variables.
PYTHONPATH=D:python20lib;
we can set location in linux using the below statement in shell/bash
set PYTHONPATH=/usr/local/lib/python
File I/O in Python
Using python we can create and edit the text data in any file. For example we can
store the any specific connections data of a maya scene file to a text file and it can be reused
in another file.
Opening A File
To open a file, we use the open() function to create a file object. Open takes two
arguments: the name of the file and the mode for which we'd like to open the file.
A file can be opened for reading ("r") or writing ("w"), just as with most other languages.
filename = “myfile.txt”
file = open(filename,'r')
Reading From A File
Read the file and print it using the below code
content = file.read()
print content
print line by line
lines = file.readlines()
for line in lines:
print line
Closing The File
We can close the file using close() function.
file.close()
writing the text to a file
filename = 'myfile.txt'
file = open(filename, 'w')
file.write(“hi this is my file”)
file.close()
Appending To An Existing File
We can append file using 'a' instead of write
file = open(filename, 'a')
file.write(' this is appending text')
file.close()
OOPs concepts in Python
Class are blueprint of the programme. It describes how to make something. You can
create lots of objects in class. And there can be lots of classes in a programme. We can
create classes using 'class' . Below is the syntax of a class
# Defining a class
class myclass:
[statement 1]
[statement 2]
[statement 3]
Another example of class
#An example of a class
class Shape:
def __init__(self,x,y):
self.x = x
self.y = y
def area(self):
return self.x * self.y
def perimeter(self):
return 2 * self.x + 2 * self.y
def scaleSize(self,scale):
self.x = self.x * scale
The first method __init__() is a special method, which is called class constructor or
initialization method that Python calls when you create a new instance of this class.
We can use inheritance to inherit one class from another.
We can write several programs using python. Below are the few examples which we
can try to write using different modules available online, which we can download and use.
Examples scripts can be written :
• Small raytracer using python
• Autmating Maya/ Katana/ Nuke
• Android game using python
• Download youtube files from internet
• Automating facebook and linkdin responses
By now we understood the basics of python and its uses. Lets understand Katana
Katana
Katana is a 3D appliction designed for lookdev and lighting. Katana mainly consists of
SceneGraph: A data tree containing all the information needed to render a scene.All data of
the scene graph is stored in Attributes. Scenegraphs heirarchical structure is made up of
locations that can be referenced by their path.
NodeGraph:A recepie in katana is an arrangement of instructions int the form of connected
nodes to manipulate 3d scene. Katana constructs a scene graph of scene data from the
content of the NodeGraph.and the SceneGraph data is sent to renderer to render it.
Before going deep into Katana scripting lets understand Groups/Macros/Supertools
Group : Group nodes are nodes that can contain a number of child nodes. They are used to
simplify the nodegraph by collecting nodes.
Group node can be created by selecting on or more nodes and pressing Ctrl+G
Macros: Macros are nodes that can contain a number of child nodes, and publish them so
that they can be saved and recalled in other projects.
SuperTools: Super tools are compound nodes where the internal structure of nodes is
dynamically created using python scripting. Internal nodes can be created and deleted using
user actions.
Creating a Macro:
Lets create a sample macro step by step, which prunes object based on location in
scenegraph. This macro will prune lights having name “ML0” and “ML1” internally, and shows
the parameter which are exposed to user.
• Create prune node and a switch which will prune *ML0* location from scene graph.
• Similarly create another prune node and a switch which will prune *ML1* location from
scene graph
• We can create as many as prune nodes and switches based on our requirement
• Now we need to create a group out of these 4 nodes
• Use ctrl+ Middle click to go inside the group node and using python scripting we
create input and output port for the node Group.
test = NodegraphAPI.GetNode('Group')
test.addOutputPort('Out')
test.addInputPort('In')
• We can see if the switch value is 1 then the location is not pruned and if it is 0 then
location is pruned
• Now expose the parameters to the group
• Use Alt+E to go to the parameters tab of Group node.
• Use edit node button to add user parameters tab.
• Now click add to add new parameters
• Rename the parameters name to ML0 and ML1
• Now select Widget Type -> Boolean to set the type of the parameter to boolean
• now using Shift select both merge node parameters along with group parameters
• Copy parameter from 'ML0', and paste expression to 'ML0Switch' parameter of Group
node
• Copy parameter from 'ML1', and paste expression to 'ML1Switch' parameter of Group
node
This will set link between the two values and if we edit the parameter from Group node
then the value of the merge node will change automatically.
• To change group node appearance we can use
Editnode -> Toggle Group node Appearance
• Now go to Group node and click ' Finish editing user parameters' to finish the editing
• Now you can set the parameters to yes / no to prune the location
• Once everything is done we can publish the 'Group' node using editNode-> save as
Macro and give the name prune.macro
• Now we can use prune_User macro in any project/ scene
• We can also create this macro through nodeGraph -> New->macro->_User-
>Prune_User
• We can re-edit the macro if required and republish it with the same name prune.macro
and can be used again
Once the macro is published it can be used in different scenes and recipes as per our
requirement.
Now lets jump into scripting in Katana
Katana Scripting
Now we can work with python to create and edit nodes in katana. Use python tab in
katana to write scripts.
Attribute types in Katana:
• int
• float
• double
• string
• group
We have noticed that while we can manually edit parameters on nodes in Nodegraph,
we cont edit attributes on scene graph location, this is because the flow of information from
Nodegraph to Scenegraph is strictly one way. This an important concept to keep mind when
writing attribute script nodes.
The following code shows how to get the full list of all the available node types using
the GetNodeTypes method in the NodegraphAPI module:
nodetypes = NodegraphAPI.GetNodeTypes()
nodetypes.sort()
for nodetype in nodetypes:
print nodetype
NodegraphAPI : The Nodegraph API is a Python interface for creating Katana recipes by
adding and connecting nodes, and setting Parameters. The Nodegraph API
cannot access the Scene Graph . The Node Graph API can be accessed by Python scripts in
the Python tab, Super Tools, plug-ins, shelves and other custom UI.
Getting help of different modules
To get help on package – NodegraphAPI, use command help, we can use help to
know about the nodes, APIs etc
help(NodegraphAPI)
help(Nodes3DAPI)
help(UI4)
• Similarly help can be used for other node types aswell. In UI4 we have other
classes/packages called Util.
help(UI4.Util)
• Try out help on other nodes as well. Also print can be used to print to know about the
nodes
help(GeoAPI)
print(NodegraphAPI)
print(NodegraphaAPI.GetAllFlavors())
# to get the help on classGroupStackNode in module
NodegraphAPI.GroupStack
help(NodegraphAPI.GroupStack.GroupStackNode)
Creating a new Node:
As we know we need to create a node at root, we need to get the root and then create
any node. The below script will create GroupStack node and Rename the node.
root=NodegraphAPI.GetRootNode()
mynode = NodegraphAPI.CreateNode('GroupStack',root)
#get the help on mynode and find out its attributes
help(mynode)
#rename the node
mynode.setName('mystack)'
• Now lets create a prman object settings node, rename it and stack it in mystack node
#create node
myprman = NodegraphAPI.CreateNode('PrmanObjectSettings', root)
#rename node
mprman.setName('myprmanobj1')
#put node in groupstack
mynode.buildChildNode(myprman)
#check the child nodes available
mynode.getChildren()
Adjusting the attributes using scripts
We can adjust the attributes of any node through script. We need to enable the local
assignment and we can set the value of any attribute. The below script will create a
prmanGlobalSettings node and set the pixelVariance value.
root = NodegraphAPI.GetRootNode()
myprman = NodegraphAPI.CreateNode('PrmanGlobalSettings', root)
en = myprman.getParameter
('args.prmanGlobalStatements.pixelVariance.enable')
#enable assignment to True
en.setValue(1,0)
#set pixelVariance value to 2 at frame 0
val = myprman.getParameter
('args.prmanGlobalStatments.pixelVariance.value')
val.setValue(2,0)
If we already have the node PrmanGlobalSettings then we can use the below script to
select the node (using GetNode) and the other script remains same
#get the node wiht name 'PrmanGlobalSettings' and store it in
myprman to edit its values
myprman = NodegrapAPI.GetNode('PrmanGlobalSettings')
#editing of the value is same as above script
Selecting nodes:
Select nodes and run the below script to get selected nodes.
sel = NodegraphAPI.GetAllSelectedNodes()
print sel
Create a prman global settings node and use the below script to get child parameters
of the node
sel = NodegraphAPI.GetNode('PrmanGlobalSettings')
for p in sel.getParameters().getChildren():
print p
Delete nodes
sel = NodegraphAPI.GetNode('PrmanGlobalSettings')
sel.delete()
Delete selected nodes through script, select the nodes and save in list, to get the
items from list and delete use for loop
sel = NodegraphAPI.GetAllSelectedNodes()
for i in sel:
i.delete()
Get list of selected locations
l
list = ScenegraphManager.getActiveScenegraph().getSeletedLocations()
print list
Producers
Another concept which we need to understand before writing scripts is Producer. As
we already discussed about the sceneGraph, it only shows locations currently expanded in
the scenegraph tab. SceneGraph changes with the current viewed node in NodeGraph.
Scenegraph gives different locations with different nodes selected in nodeGraph. To get
appropriate scene data at a given node we can use Producer. Using a Producer is the correct
way to iterate the Scenegraph if you ever need to. It’s available through the Nodes3DAPI.
In any scene we can getnode which is in the end of a nodegraph and use producer to
get the accurate scene graph at that node. Below is the script to select objects through CEL
statement using python. Create a collection named bone to get the CEL command working
for the below script.
mynode = NodegraphAPI.GetNode('PrmanGlobalSettings')
prodcuer = Nodes3DAPI.GetGeometryProducer(mynode, 0)
cel = GeoAPI.Util.CollectPathsFromCELStatement(producer,
'(FLATTEN(//$bone))')
sg = ScenegraphManager.getActiveScenegraph()
sg.selectAndCreateLocations(cel)
Example Script
Lets create a script which creates an prmanObjectSettings node and add the selected
objects from the scene graph. In UI we can define the name of the node . Along with this we
can set the attributes of the PrmanObjectSettings. For now if the node exists then it replaces
the selected objects
class Example(QtGui.QDialog):
def __init__(self, parent =
UI4.App.MainWindow.CurrentMainWindow()):
super(Example, self).__init__(parent)
#########UI Design###########
self.setWindowTitle('ObjSettings')
layout = QtGui.QGridLayout()
label = QtGui.QLabel("name",self)
self._labelInput = QtGui.QLineEdit(self)
self._labelInput.setText(QtGui.QApplication.translate("MainW
indow","",None, QtGui.QApplication.UnicodeUTF8))
self._labelInput.move(100,150)
label.move(20,150)
createButton = QtGui.QPushButton("create",self)
layout.addWidget(createButton , 3, 0, 1, 2)
createButton.setDefault(1)
createButton.clicked.connect(self.prmanobj)
createButton.move(30, 200)
qbtn = QtGui.QPushButton('Quit', self)
qbtn.clicked.connect(self.close)
qbtn.resize(qbtn.sizeHint())
qbtn.move(120, 200)
layout.addWidget(qbtn, 4,0,1,2)
self.setGeometry(500, 300, 350, 350)
def prmanobj (self):
name = str(self._labelInput.text())
selected =
ScenegraphManager.getActiveScenegraph().getSelectedLocations()
root = NodegraphAPI.GetRootNode()
if NodegraphAPI.GetNode(name):
print('Exists')
else:
groupnode =
NodegraphAPI.CreateNode('PrmanObjectSettings', root)
groupnode.setName(name)
sel = NodegraphAPI.GetNode(name)
selection = sel.getParameter('CEL')
selection.setValue('('+' '.join(selected)+')', 0)
window = Example()
window.show()
Attribute Scripts:
Attribute scripts are similar to attribute modifiers, where we can modify the attributes
through python scripts. Through attribute script we can modify attribute at any given location.
We can create attribute scripts which run only on certain type of locations. AttributeSet will be
much faster than AttributeScript if all you're doing is setting attributes. AttributeScript can do a
lot more than set attributes.
Lets create an attributescript which changes the maxTimeSamples using python script.
MaxTimeSamples is an option which is not an object based setting, which is scene based or
layer based. So we need to apply the script at '/root' location. It wont work on any other
location or on object.
• Create an AttributeScript node.
• Set location to '/root'
• Put the below script in script box in the node.
setAttr(“renderSettings.maxTimeSamples”,[4])
Similarly we can write different types of attribute scripts which can do lot of
manipulation in the scene/Nodegraph. We can set visibility setting using script which wont be
rendering.
Lets write a small script which checks the shutterclose, if it is 1 then make
maxtimeSamples to 4, and if shutterclose isn't 1 then it sets maxTimeSamples to 1
motionblur = GetAttr('renderSettings.shutterClose')
if motionblur == [1]:
SetAttr('renderSettings.maxTimeSamples',[4])
else:
SetAttr('renderSettings.maxTimeSamples',[3])
We can set anything based on conditions, Get the value of any attribute and based on
the value we can set any attributes value on the fly. Below examples can be created using
AttributeScripts
• Disabling Deep AOVs using Attribute Script
• Disable indirect specular
• Disable material
SuperTools:
Super tools are compound nodes where the internal structure of nodes is dynamically
created using python scripting. Internal nodes can be created and deleted using user actions.
Many of Katana's common user level nodes (such as Importomatic, Gaffer and
lookfileManager) are actually super tools.
We can Ctrl+middle click to see the internal structure of SuperTool
In general super tool consist of:
• A python script written using Katana NodegraphAPI that declares how the super tool
creates its internal structure.
• A python script using PyQt that declares how the super tool creates its UI in the
Parameters tab
• Another python script for common shared utility functions needed by the both the
nodes and UI scripts
• Plugin registry is required to use super tool, which can be performed through init.py
Other APIs available in katana:
AttributeAPI
RanderfarmAPI
ImportometiAPI
Viewer manipulaterAPI
RendererAPI
Few Major changes in Katana 2
There are several enhancements and changes are being made in Katana2.x
compared to Katana 1.x. Lets have a look of few major changes.
Gaffer3 : New gaffer node is introduced in Katana2.x, has been created to provide improved
performance when dealing with large number of lights in the scene.
Lua OpScripts: Katana 2.x introduces a Lua based Opscript node which can be used
instead of python based AttributeScript nodes. It is recommended to use OpScript where
ever possible.
Keyboard Shortcut manager: A new module has been added to assign keyboard shortcuts
in Katana which was not available in the earlier versions.
Geolib3 : It is Katana's new scene graph processing library. It works at Katana's core to
support large data sets. In the earlier versions Geolib2 reconstructed the whole scene graph
on every edit, Where as Geolib3 allows inter-cook scene data re-use.
Python Tab: Tab has been enhanced for user friendly usage.
###################
Katana references
There are very few resources available on katana and its scripting.
Katana documentation
http://tomcowland.com/katana
http://community.thefoundry.co.uk/discussion/katana/
Python Reference:
There is a huge list of resources available online for Python. Advanced python-
programming can be learned through internet.
www.python.org
Please write your suggestions and comments to Email: m_kedar_nath@yahoo.com

Contenu connexe

Tendances

Tendances (20)

Python
PythonPython
Python
 
Python-Functions.pptx
Python-Functions.pptxPython-Functions.pptx
Python-Functions.pptx
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Generators In Python
Generators In PythonGenerators In Python
Generators In Python
 
Python 2 vs. Python 3
Python 2 vs. Python 3Python 2 vs. Python 3
Python 2 vs. Python 3
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
Adobe Photoshop CS6 tutorial 2013
Adobe Photoshop CS6 tutorial 2013Adobe Photoshop CS6 tutorial 2013
Adobe Photoshop CS6 tutorial 2013
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Golang Book - Go Programlama Dili Temelleri
Golang Book - Go Programlama Dili TemelleriGolang Book - Go Programlama Dili Temelleri
Golang Book - Go Programlama Dili Temelleri
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
What is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaWhat is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | Edureka
 
Python
PythonPython
Python
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
 
An introduction to Maven
An introduction to MavenAn introduction to Maven
An introduction to Maven
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with Python
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
Java 8 Date-Time API
Java 8 Date-Time APIJava 8 Date-Time API
Java 8 Date-Time API
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
 
Python by Rj
Python by RjPython by Rj
Python by Rj
 

Similaire à Python for katana

Similaire à Python for katana (20)

Python 01.pptx
Python 01.pptxPython 01.pptx
Python 01.pptx
 
Summer Training Project On Python Programming
Summer Training Project On Python ProgrammingSummer Training Project On Python Programming
Summer Training Project On Python Programming
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
 
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdfPy-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
Python Course In Chandigarh
Python Course In ChandigarhPython Course In Chandigarh
Python Course In Chandigarh
 
Python Programming 1.pptx
Python Programming 1.pptxPython Programming 1.pptx
Python Programming 1.pptx
 
Python intro
Python introPython intro
Python intro
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3
 
Python presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, BiharPython presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, Bihar
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning
 
About python
About pythonAbout python
About python
 
prakash ppt (2).pdf
prakash ppt (2).pdfprakash ppt (2).pdf
prakash ppt (2).pdf
 
Fundamentals of python
Fundamentals of pythonFundamentals of python
Fundamentals of python
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
 
intro to python.pptx
intro to python.pptxintro to python.pptx
intro to python.pptx
 
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdfCSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
 
Python PPT.pptx
Python PPT.pptxPython PPT.pptx
Python PPT.pptx
 

Dernier

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Dernier (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 

Python for katana

  • 2. Structure of the book Overview The following documentation will give basic understanding of the below topics. After going through this one can be able to script small programs using python. Which also gives a basic understanding how Katana works inside and will be able to automate Katana as per requirement. • Understanding scripting • Python-programming • Understanding Katana • Katana Scripting Prerequisite Knowledge of Katana to understand scripting for Katana
  • 3. Programming and Scripting Scripting languages are languages that don't require an explicit compilation step. For example, you have to compile a C program before you can run it. But in the normal case, you don't have to compile a JavaScript program before you run it. So JavaScript is sometimes called a "scripting" language. Some examples of "scripting" languages (languages that are traditionally used without an explicit compilation step): • Python • JavaScript • VBScript And examples which traditionally used with an explicit compilation step: • C • C++ • Java • Fortan Few advantages of Scripting/ programming • Automation • creating new tools • extending the capability of a software Different programming Types Procedural programming: is a programming paradigm, derived from structured programming, based upon the concept of the procedure call. Procedures, also known as routines, subroutines, methods or functions, simply contain a series of computational steps to be carried out. Object-oriented programming (OOP): is a programming paradigm based on the concept of "objects", which are data structures that contain data, in the form of fields, often known as attributes, and code, in the form methods. object-oriented programming that uses classes is sometimes called class-based programming. Few features of OOPs • Inheritance • Abstraction • Polymorphism • Instances
  • 4. Overview of OOPs Terminology • Class: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes and methods, accessed via dot notation. • Class variable: A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. • Data member: A class variable or instance variable that holds data associated with a class and its objects. • Function overloading: The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects (arguments) involved. • Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class. • Inheritance : The transfer of the characteristics of a class to other classes that are derived from it. • Instance: An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle. • Instantiation : The creation of an instance of a class. • Object : An object is instance of a data structure that's defined by its class. An object has data members and methods.
  • 5. Python Python can do almost all types of things except creating OS. For python we can use words - scripting and programming interchangeably. Python runs through interpreter and also can be compiled and used. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library Python is used in various developments. • GIS Programmings • Web developments • Desktop applications • Network programming • In VFX it can be used for Pipeline development as well as it can be used in Maya/Katana/Nuke etc. About python Python is an interpreted programming language .Also it is open source software, making it freely usable and distributable, version 3.4.3 is the latest version available and freely downloadable through www.python.org . Most current Linux distributions and Macs are still using 2.x as default. Also most of the VFX Houses use 2.x, so we are going to concentrate in 2.x. There is a syntax differences in 2.x and 3.x. Why Python Python is a high-level, interpreted, interactive and object-oriented scripting language. Python was designed to be highly readable which uses English keywords frequently where as other languages use punctuation and it has fewer syntactical constructions than other languages. • Python is Interpreted: This means that it is processed at run time by the interpreter and we do not need to compile our program before executing it. This is similar to PERL and PHP. • Python is Interactive: This means that you can actually us Python prompt and interact with the interpreter using python statements directly to write your programs. • Python is Object-Oriented: This means that Python supports Object-Oriented style or technique of programming which allows to use OOPs concepts like encapsulation, inheritance etc. • Python is Beginner's Language: Python is a great language for the beginner programmers and with easy syntax, and also supports the development of a wide range of applications
  • 6. We have IDLE ((Integrated DeveLopment Environment ) to write scripts. We can also use any text editor to write python scripts. Few definitions related to python Pyside: Python bindings for QT (similar to pyqt4) Pymel: Python binding for MEL Modules: A module is a python file that generally has only definitions of variables, functions, and classes. Modules in Python are simply Python files with the .py extension, Functions: Functions are programs that perform a specific task, which you can incorporate into your own, larger programs. After you have created a function, you can use it at any time, in any place. Packages: A package is a set of modules or sub-packages. A package is actually a directory containing either .py files or sub-directories defining other packages. When loading a package, the __init__.py file is executed
  • 7. Getting into Python Download and install python. By default python is installed in linux distributions. Get into shell and type python to start python directly in shell. [abc@localhost]# python Here we can find which version of python we are using on which version GCC. To get out of python use command exit() >>>exit() Syntax of python Identifier is the name given to entities like class, functions, variables etc. in Python. It helps differentiating one entity from another. Python is a case sensitive programming language. Thus, name and Name are two different identifiers in Python. Here are following naming convention for Python: • Class names start with an uppercase letter and all other identifiers with a lowercase letter. • Starting an identifier with a single leading underscore indicates by convention that the identifier is private.
  • 8. Reserved words The following list shows the reserved words in Python. These reserved words may not be used as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only. and exec not assert finally or break for pass class from print continue global raise def if return del import try elif in while else is with except lambda yield Lines and Indentation: There are no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is important to keep in mind. The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. In the below example the indentation is different for If and else , this is wrong in python if True: print "True" else: print "False" Multi-Line Statements: Statements in python are usually one liners. Python allows the use of the line continuation character () to denote that the line should continue. For example: >>> total = 5+ 6 + 8 Quotation in Python: Python accepts single ('), double (") and triple (''' or """) quotes to denote strings , as long as the same type of quotes ends the string. In the below example all are correct. >>> a = 'hi' >>> a= “hi” >>> a= ''' hi'''
  • 9. Comments in Python: A hash sign (#) begins a comment. All characters after the # and up to the physical line end are part of the comment and the Python interpreter ignores them. Multiple Statements on a Single Line: The semicolon ( ; ) allows multiple statements. Here is a sample snip using the semicolon: >>>import sys; x = 'foo'; sys.stdout.write(x + 'n') Writing Python scripts Lets get into command line python / Interactive mode, where we can directly type python statements/ commands. To print anything use print command with quotes. You can see both types of quotes are working. We can do all mathematical operations directly in python console interactively.
  • 10. Data types in Python: • Numbers : Python supports different numerical types: • int (signed integers) • long (long integers [can also be represented in octal and hexadecimal]) • float (floating point real values) • complex (complex numbers) • String : Strings in Python are identified as a set of characters in between quotations. • List : Lists are Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type. The values stored in a list can be accessed using the slice operator ( [ ] and [ : ] ) with indexe starting at 0. • Tuple : A tuple is another data type that is similar to the list. A tuple consists of a number of values separated by commas. The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. • Dictionary : can store any number of Python objects, including other container types. Dictionaries consist of pairs (called items) of keys and their corresponding values. >>>dict = { 'abc': 123, 'bb': 37 }; Along with the command line statements we can save .py file and run it through command line. Different commands / statements can be combined in a python file and which can be executed using 'python' command in shell. [abc@localhost]# python firstscript.py
  • 11. Now lets write a script which takes input from user and does some mathematical calculations. The script ask user to input radius of sphere and it calculates circumference and prints it.
  • 12. Operators There are several types of operators available in scripting and programming language. Lets look at operators can be used in python-programming. Mathematical operators • + Addition • - Subtraction • * Multiplication • / Division • % Reminder • ** exponent 10**20 is 10 to the power 20 • // floor division 9//2 is equal to 4 Comparison operators • == equal • != not equal • <> not equal • > greater than • < less than • >= greater than or equal • <= less than or equal Assignment operators • = equal • += c +=a is equivalent to c = c+a • -= c-=a is equivalent to c=c-a • *= c =a is equivalent to c= c*a • /= c/=a is equivalent to c =c/a • %= c%=a is equivalent to c=c%a • **= c**=a is equivalent to c=c**a • //= c//=a is equivalent to c=c//a Logical operators • and (a and b) is true • or (a or b) is true • not not (a ) Membership operators • in x in y, result is 1 if x is a member of y • not in x not in y, results 1 if x is not a member of y
  • 13. Decision Making if statements:An if statement consists of a expression followed by one or more statements. if...else : An if statement can be followed by an optional else statement, which executes when the boolean expression is false. nested if: You can use one if or else if statement inside another if or else if statement(s). # syntax for input and operator if, elseif and else x = int(input("Please enter an integer: ")) if x < 0: x = 0 print 'Negative changed to zero' elif x == 0: print 'Zero' elif x == 1: print 'Single' else: print 'More' Loops while loop: Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. # the sum of two elements defines the next a, b = 0, 1 while b < 200: print b, b = a+b for loop: Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. Nested loops:You can use one or more loop inside any another while, for or do..while loop. Break: Terminates the loop statement Continue: Causes the loop to skip the remainder of its body and immediately retest its condition before to reiterating. Pass: The pass statement in Python is used when a statement is required but you do not want any command to execute.
  • 14. # using loops and break operator for n in range(2, 1000): for x in range(2, n): if n % x == 0: print n, 'equals', x, '*', n/x break else: # loop fell through without finding a factor print n, 'is a prime number' Functions: You can define functions to create the required functionality. Here are few rules to define a function in Python. • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). • Any input parameters or arguments should be placed within these parentheses. we can also define parameters inside these parentheses. • The code in every function starts with a colon (:) and is indented. • IT returns value [expression] . #syntax of a function def functionname( parameters ): "function_docstring" function_suite return [expression] Global vs. Local variables: Variables that are defined inside a function body are local, and those defined outside are global variables. Global variables can be used in other functions as well. Writing a function for equiation wtith arguments #Writing a sample function def myfunc(n): a, b = 0, 1 while b < n: print b, a, b = b, a+b # Now call the function we just defined: >>>myfunc(20)
  • 15. Modules A module is an organised Python code. Adding related code into a module makes the code easier to understand and use. Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code. The from...import Statement Python's from statement lets us import specific attributes from a module into the current scripts The from...import has the following syntax: from modulename import name We can use 'import' in python to import different modules. Examples : from Katana import Nodes3DAPI from PyQT4 import UI4 Syntax of module ### EXAMPLE # Define variables: one = 1 pi = 3.14 # defining functions def printhello(): print "hello" def circumf(input): print input * 2*pi # define a class class mytest: def __init__(self): self.name = input("Name class? ") self.num = input("number of students") self.section = input("section of class") def printdetails(self): print "name of class is " + self.name print self.section, "has, " + self.num +”of students
  • 16. once we have run the above module it created .pyc file. Now in the folder we can see firstmodule.py and firstmodule.pyc. .pyc contain the compiled bytecode of Python source files. The Python interpreter loads .pyc files before .py files, so if they're present, it can save some time by not having to re-compile the Python source code Locating Modules: When we import a module, the Python interpreter searches for the module in the following sequences. One can write own python modules and keep at PYTHONPATH location and use import to use the functions and classes • The current directory. • If the module isn't found, Python then searches each directory in the shell variable called PYTHONPATH. • Both fails, Python checks the default path which is /usr/local/lib/python/. In linux The PYTHONPATH is an environment variable, which has list of directories. We can set the path location using the below statement in windows using environment variables. PYTHONPATH=D:python20lib; we can set location in linux using the below statement in shell/bash set PYTHONPATH=/usr/local/lib/python
  • 17. File I/O in Python Using python we can create and edit the text data in any file. For example we can store the any specific connections data of a maya scene file to a text file and it can be reused in another file. Opening A File To open a file, we use the open() function to create a file object. Open takes two arguments: the name of the file and the mode for which we'd like to open the file. A file can be opened for reading ("r") or writing ("w"), just as with most other languages. filename = “myfile.txt” file = open(filename,'r') Reading From A File Read the file and print it using the below code content = file.read() print content print line by line lines = file.readlines() for line in lines: print line Closing The File We can close the file using close() function. file.close() writing the text to a file filename = 'myfile.txt' file = open(filename, 'w') file.write(“hi this is my file”) file.close() Appending To An Existing File We can append file using 'a' instead of write file = open(filename, 'a') file.write(' this is appending text') file.close()
  • 18. OOPs concepts in Python Class are blueprint of the programme. It describes how to make something. You can create lots of objects in class. And there can be lots of classes in a programme. We can create classes using 'class' . Below is the syntax of a class # Defining a class class myclass: [statement 1] [statement 2] [statement 3] Another example of class #An example of a class class Shape: def __init__(self,x,y): self.x = x self.y = y def area(self): return self.x * self.y def perimeter(self): return 2 * self.x + 2 * self.y def scaleSize(self,scale): self.x = self.x * scale The first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class. We can use inheritance to inherit one class from another. We can write several programs using python. Below are the few examples which we can try to write using different modules available online, which we can download and use. Examples scripts can be written : • Small raytracer using python • Autmating Maya/ Katana/ Nuke • Android game using python • Download youtube files from internet • Automating facebook and linkdin responses By now we understood the basics of python and its uses. Lets understand Katana
  • 19. Katana Katana is a 3D appliction designed for lookdev and lighting. Katana mainly consists of SceneGraph: A data tree containing all the information needed to render a scene.All data of the scene graph is stored in Attributes. Scenegraphs heirarchical structure is made up of locations that can be referenced by their path. NodeGraph:A recepie in katana is an arrangement of instructions int the form of connected nodes to manipulate 3d scene. Katana constructs a scene graph of scene data from the content of the NodeGraph.and the SceneGraph data is sent to renderer to render it. Before going deep into Katana scripting lets understand Groups/Macros/Supertools Group : Group nodes are nodes that can contain a number of child nodes. They are used to simplify the nodegraph by collecting nodes. Group node can be created by selecting on or more nodes and pressing Ctrl+G Macros: Macros are nodes that can contain a number of child nodes, and publish them so that they can be saved and recalled in other projects. SuperTools: Super tools are compound nodes where the internal structure of nodes is dynamically created using python scripting. Internal nodes can be created and deleted using user actions. Creating a Macro: Lets create a sample macro step by step, which prunes object based on location in scenegraph. This macro will prune lights having name “ML0” and “ML1” internally, and shows the parameter which are exposed to user. • Create prune node and a switch which will prune *ML0* location from scene graph. • Similarly create another prune node and a switch which will prune *ML1* location from scene graph • We can create as many as prune nodes and switches based on our requirement
  • 20. • Now we need to create a group out of these 4 nodes • Use ctrl+ Middle click to go inside the group node and using python scripting we create input and output port for the node Group. test = NodegraphAPI.GetNode('Group') test.addOutputPort('Out') test.addInputPort('In')
  • 21. • We can see if the switch value is 1 then the location is not pruned and if it is 0 then location is pruned • Now expose the parameters to the group • Use Alt+E to go to the parameters tab of Group node. • Use edit node button to add user parameters tab. • Now click add to add new parameters
  • 22. • Rename the parameters name to ML0 and ML1 • Now select Widget Type -> Boolean to set the type of the parameter to boolean
  • 23. • now using Shift select both merge node parameters along with group parameters • Copy parameter from 'ML0', and paste expression to 'ML0Switch' parameter of Group node • Copy parameter from 'ML1', and paste expression to 'ML1Switch' parameter of Group node This will set link between the two values and if we edit the parameter from Group node then the value of the merge node will change automatically.
  • 24. • To change group node appearance we can use Editnode -> Toggle Group node Appearance • Now go to Group node and click ' Finish editing user parameters' to finish the editing • Now you can set the parameters to yes / no to prune the location
  • 25. • Once everything is done we can publish the 'Group' node using editNode-> save as Macro and give the name prune.macro • Now we can use prune_User macro in any project/ scene • We can also create this macro through nodeGraph -> New->macro->_User- >Prune_User • We can re-edit the macro if required and republish it with the same name prune.macro and can be used again Once the macro is published it can be used in different scenes and recipes as per our requirement. Now lets jump into scripting in Katana
  • 26. Katana Scripting Now we can work with python to create and edit nodes in katana. Use python tab in katana to write scripts. Attribute types in Katana: • int • float • double • string • group We have noticed that while we can manually edit parameters on nodes in Nodegraph, we cont edit attributes on scene graph location, this is because the flow of information from Nodegraph to Scenegraph is strictly one way. This an important concept to keep mind when writing attribute script nodes. The following code shows how to get the full list of all the available node types using the GetNodeTypes method in the NodegraphAPI module: nodetypes = NodegraphAPI.GetNodeTypes() nodetypes.sort() for nodetype in nodetypes: print nodetype
  • 27. NodegraphAPI : The Nodegraph API is a Python interface for creating Katana recipes by adding and connecting nodes, and setting Parameters. The Nodegraph API cannot access the Scene Graph . The Node Graph API can be accessed by Python scripts in the Python tab, Super Tools, plug-ins, shelves and other custom UI. Getting help of different modules To get help on package – NodegraphAPI, use command help, we can use help to know about the nodes, APIs etc help(NodegraphAPI) help(Nodes3DAPI) help(UI4) • Similarly help can be used for other node types aswell. In UI4 we have other classes/packages called Util. help(UI4.Util)
  • 28. • Try out help on other nodes as well. Also print can be used to print to know about the nodes help(GeoAPI) print(NodegraphAPI) print(NodegraphaAPI.GetAllFlavors()) # to get the help on classGroupStackNode in module NodegraphAPI.GroupStack help(NodegraphAPI.GroupStack.GroupStackNode) Creating a new Node: As we know we need to create a node at root, we need to get the root and then create any node. The below script will create GroupStack node and Rename the node.
  • 29. root=NodegraphAPI.GetRootNode() mynode = NodegraphAPI.CreateNode('GroupStack',root) #get the help on mynode and find out its attributes help(mynode) #rename the node mynode.setName('mystack)' • Now lets create a prman object settings node, rename it and stack it in mystack node #create node myprman = NodegraphAPI.CreateNode('PrmanObjectSettings', root) #rename node mprman.setName('myprmanobj1') #put node in groupstack mynode.buildChildNode(myprman) #check the child nodes available mynode.getChildren()
  • 30. Adjusting the attributes using scripts We can adjust the attributes of any node through script. We need to enable the local assignment and we can set the value of any attribute. The below script will create a prmanGlobalSettings node and set the pixelVariance value. root = NodegraphAPI.GetRootNode() myprman = NodegraphAPI.CreateNode('PrmanGlobalSettings', root) en = myprman.getParameter ('args.prmanGlobalStatements.pixelVariance.enable') #enable assignment to True en.setValue(1,0) #set pixelVariance value to 2 at frame 0 val = myprman.getParameter ('args.prmanGlobalStatments.pixelVariance.value') val.setValue(2,0) If we already have the node PrmanGlobalSettings then we can use the below script to select the node (using GetNode) and the other script remains same
  • 31. #get the node wiht name 'PrmanGlobalSettings' and store it in myprman to edit its values myprman = NodegrapAPI.GetNode('PrmanGlobalSettings') #editing of the value is same as above script Selecting nodes: Select nodes and run the below script to get selected nodes. sel = NodegraphAPI.GetAllSelectedNodes() print sel Create a prman global settings node and use the below script to get child parameters of the node sel = NodegraphAPI.GetNode('PrmanGlobalSettings') for p in sel.getParameters().getChildren(): print p Delete nodes sel = NodegraphAPI.GetNode('PrmanGlobalSettings') sel.delete() Delete selected nodes through script, select the nodes and save in list, to get the items from list and delete use for loop sel = NodegraphAPI.GetAllSelectedNodes() for i in sel: i.delete() Get list of selected locations l list = ScenegraphManager.getActiveScenegraph().getSeletedLocations() print list Producers Another concept which we need to understand before writing scripts is Producer. As we already discussed about the sceneGraph, it only shows locations currently expanded in the scenegraph tab. SceneGraph changes with the current viewed node in NodeGraph. Scenegraph gives different locations with different nodes selected in nodeGraph. To get appropriate scene data at a given node we can use Producer. Using a Producer is the correct
  • 32. way to iterate the Scenegraph if you ever need to. It’s available through the Nodes3DAPI. In any scene we can getnode which is in the end of a nodegraph and use producer to get the accurate scene graph at that node. Below is the script to select objects through CEL statement using python. Create a collection named bone to get the CEL command working for the below script. mynode = NodegraphAPI.GetNode('PrmanGlobalSettings') prodcuer = Nodes3DAPI.GetGeometryProducer(mynode, 0) cel = GeoAPI.Util.CollectPathsFromCELStatement(producer, '(FLATTEN(//$bone))') sg = ScenegraphManager.getActiveScenegraph() sg.selectAndCreateLocations(cel)
  • 33. Example Script Lets create a script which creates an prmanObjectSettings node and add the selected objects from the scene graph. In UI we can define the name of the node . Along with this we can set the attributes of the PrmanObjectSettings. For now if the node exists then it replaces the selected objects class Example(QtGui.QDialog): def __init__(self, parent = UI4.App.MainWindow.CurrentMainWindow()): super(Example, self).__init__(parent) #########UI Design########### self.setWindowTitle('ObjSettings') layout = QtGui.QGridLayout() label = QtGui.QLabel("name",self) self._labelInput = QtGui.QLineEdit(self) self._labelInput.setText(QtGui.QApplication.translate("MainW indow","",None, QtGui.QApplication.UnicodeUTF8)) self._labelInput.move(100,150) label.move(20,150) createButton = QtGui.QPushButton("create",self) layout.addWidget(createButton , 3, 0, 1, 2) createButton.setDefault(1) createButton.clicked.connect(self.prmanobj) createButton.move(30, 200) qbtn = QtGui.QPushButton('Quit', self) qbtn.clicked.connect(self.close) qbtn.resize(qbtn.sizeHint()) qbtn.move(120, 200) layout.addWidget(qbtn, 4,0,1,2) self.setGeometry(500, 300, 350, 350) def prmanobj (self): name = str(self._labelInput.text()) selected = ScenegraphManager.getActiveScenegraph().getSelectedLocations() root = NodegraphAPI.GetRootNode()
  • 34. if NodegraphAPI.GetNode(name): print('Exists') else: groupnode = NodegraphAPI.CreateNode('PrmanObjectSettings', root) groupnode.setName(name) sel = NodegraphAPI.GetNode(name) selection = sel.getParameter('CEL') selection.setValue('('+' '.join(selected)+')', 0) window = Example() window.show() Attribute Scripts: Attribute scripts are similar to attribute modifiers, where we can modify the attributes through python scripts. Through attribute script we can modify attribute at any given location. We can create attribute scripts which run only on certain type of locations. AttributeSet will be much faster than AttributeScript if all you're doing is setting attributes. AttributeScript can do a lot more than set attributes. Lets create an attributescript which changes the maxTimeSamples using python script. MaxTimeSamples is an option which is not an object based setting, which is scene based or layer based. So we need to apply the script at '/root' location. It wont work on any other location or on object. • Create an AttributeScript node. • Set location to '/root' • Put the below script in script box in the node. setAttr(“renderSettings.maxTimeSamples”,[4]) Similarly we can write different types of attribute scripts which can do lot of manipulation in the scene/Nodegraph. We can set visibility setting using script which wont be rendering. Lets write a small script which checks the shutterclose, if it is 1 then make maxtimeSamples to 4, and if shutterclose isn't 1 then it sets maxTimeSamples to 1 motionblur = GetAttr('renderSettings.shutterClose') if motionblur == [1]: SetAttr('renderSettings.maxTimeSamples',[4]) else: SetAttr('renderSettings.maxTimeSamples',[3])
  • 35. We can set anything based on conditions, Get the value of any attribute and based on the value we can set any attributes value on the fly. Below examples can be created using AttributeScripts • Disabling Deep AOVs using Attribute Script • Disable indirect specular • Disable material SuperTools: Super tools are compound nodes where the internal structure of nodes is dynamically created using python scripting. Internal nodes can be created and deleted using user actions. Many of Katana's common user level nodes (such as Importomatic, Gaffer and lookfileManager) are actually super tools. We can Ctrl+middle click to see the internal structure of SuperTool In general super tool consist of: • A python script written using Katana NodegraphAPI that declares how the super tool creates its internal structure. • A python script using PyQt that declares how the super tool creates its UI in the Parameters tab • Another python script for common shared utility functions needed by the both the nodes and UI scripts • Plugin registry is required to use super tool, which can be performed through init.py Other APIs available in katana: AttributeAPI RanderfarmAPI ImportometiAPI Viewer manipulaterAPI RendererAPI Few Major changes in Katana 2 There are several enhancements and changes are being made in Katana2.x compared to Katana 1.x. Lets have a look of few major changes. Gaffer3 : New gaffer node is introduced in Katana2.x, has been created to provide improved performance when dealing with large number of lights in the scene. Lua OpScripts: Katana 2.x introduces a Lua based Opscript node which can be used instead of python based AttributeScript nodes. It is recommended to use OpScript where ever possible.
  • 36. Keyboard Shortcut manager: A new module has been added to assign keyboard shortcuts in Katana which was not available in the earlier versions. Geolib3 : It is Katana's new scene graph processing library. It works at Katana's core to support large data sets. In the earlier versions Geolib2 reconstructed the whole scene graph on every edit, Where as Geolib3 allows inter-cook scene data re-use. Python Tab: Tab has been enhanced for user friendly usage. ###################
  • 37. Katana references There are very few resources available on katana and its scripting. Katana documentation http://tomcowland.com/katana http://community.thefoundry.co.uk/discussion/katana/ Python Reference: There is a huge list of resources available online for Python. Advanced python- programming can be learned through internet. www.python.org Please write your suggestions and comments to Email: m_kedar_nath@yahoo.com