[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.6 The Python Behaviour Layer

One of the predefined behaviour layers in Crystal Entity Layer is the BLPYTHON behaviour layer. In this behaviour layer PYTHON is used as simple scripting language. This allows one to create game logic using PYTHON, and thus creating full scripting games without need of recompilation.

CS and CEL python bindings

There are several python modules for Crystal Space and CEL:

Also it has to be noted pycel is automatically imported into each behaviour namespace, so you need not import it unless to import * from it.

Behaviours

When using the BLPYTHON behaviour layer you basically create scripts. Every script corresponds to a behaviour for an entity (multiple entities can use it of course).

Every script must include a behaviour of the same name.

A python behaviour has the following structure:

 
# file fovcontrol.py
from pycel import *

class fovcontrol:
        api_version = 2
        def __init__(self,celEntity):
                print "Initializing fovcontrol...",celEntity.Name
		# get camera from main actor (called camera in this case)
                self.camera = celGetDefaultCamera(Entities["camera"]).Camera
                self.initfov = self.camera.GetFOV ()
		# get/create a pcinput.standard
                self.input = celCommandInput(celEntity)
                self.input.Bind("z","zoomin")
                self.input.Bind("x","zoomout")
                self.input.Bind("c","zoom0")
		# get/create a timer
                self.timer = celTimer(celEntity)
                self.timer.WakeUpFrame(CEL_EVENT_PRE)
		# define some initial values
                self.zoomin = False
                self.zoomout = False
		# get initial time
                self.time = Clock.GetCurrentTicks()

	# property class message callbacks
        def pctimer_wakeupframe(self,pc,args):
                self.time = Clock.GetCurrentTicks() - self.time
                if self.zoomin:
                        self.camera.SetFOV(int(self.camera.GetFOV()+(5*(self.time/1000.0))),Graphics2D.GetWidth())
                if self.zoomout:
                        self.camera.SetFOV(int(self.camera.GetFOV()-(5*(self.time/1000.0))),Graphics2D.GetWidth())
        def pccommandinput_zoomin1(self,pc,args):
                self.zoomin = True
        def pccommandinput_zoomout1(self,pc,args):
                self.zoomout = True
        def pccommandinput_zoomin0(self,pc,args):
                self.zoomin = False
        def pccommandinput_zoomout0(self,pc,args):
                self.zoomout = False
        def pccommandinput_zoom01(self,pc,args):
                self.camera.SetFOV(self.initfov,Graphics2D.GetWidth())

As can be seen we have a class with several methods.

First we have the constructor (__init__ function) that gets a pointer to the entity it's being attached to (celEntity). As usual in python all methods in the class get a first parameter that points to the own python class instance (self) of the behaviour, we can use it to save variables for the instance.

After this we have some callback functions, in many situations CEL will call certain functions in our python behaviours so we may react to events. For example pctimer_wakeup is got when the entity receives a wakeup event from a timer, pctrigger_entertrigger is got when the entity enters some trigger's area.

Note also de api_version = 2 variable, it specifies the message callback version to use. Version 2 is new in 1.2 and is recommended although version 1 is still default for backward compatibility reasons.

Python behaviours at XML worldfiles

Python behaviours can be set directly in CEL XML format as seen elsewhere in this manual.

Here is an example entity with some property classes and a python behaviour set to it:

 
<addon entityname="camera" plugin="cel.addons.celentity">
  <propclass name="pcobject.mesh">
    <action name="SetMesh">
      <par name="name" string="ActorMesh"/>
    </action>
  </propclass>
  <propclass name="pccamera.old">
    <action name="SetCamera">
      <par name="modename" string="thirdperson"/>
    </action>
  </propclass>
  <propclass name="pcinput.standard"/>
  <propclass name="pcobject.mesh.select">
    <action name="SetCamera">
      <par name="entity" string="camera"/>
    </action>
    <action name="SetMouseButtons">
      <par name="buttons" long="2"/>
    </action>
  </propclass>
  <behaviour layer='blpython' name='actor'/>
</addon>

Note the python behaviour will be loaded from the ‘actor.py’ file that must lie somewhere in PYTHONPATH (note ‘celstart’ will add the main folder of your ZIP file to the PYTHONPATH if you're using it).

Usually the celentity addon is placed in a Crystal Space sector inside the world files.

pycel

pycel is a high level layer which defines some aliases for some of the most accessed things:

The PhysicalLayer

The physical layer is your main pointer to CEL functionality, and you'll require this to create entities, destroy them, get string IDs.... It can be accessed from python at ‘pycel.PhysicalLayer’.

PhysicalLayer dictionaries

All the physical layer dictionaries can be accessed directly from pycel:

Crystal Space plugins

Some often used plugins in CS are ready to use (if present). These are:

getid / fromid and other StringID related functions.

Functions to transform from string to stringid and back.

parblock

Function to create a celParameterBlock from a python dict or list. This is described in detail later.

CreateEntity / RemoveEntity

These can be accessed directly from pycel to create and destroy entities. Use them in the same way as the physical layer functions of the same name.

Property Class accessors

Some functions are defined to easily create CEL property classes for entities, or access the pre existent ones. This will be described in the next section of this manual.

Accessing entity property classes

Property classes are objects we can create attached to an entity, and which augment the entity with some functionality (see section Property Classes).

For each property class there are several functions in pycel module that allow easily fetching or creating of the appropiate property class from an entity object:

Where ‘PropertyClass’ would be substituted for the appropiate name, like in celGetTimer, celAddCommandInput...

As an example at the initialization section we could do:

 
    def __init__(self,celEntity):
          self.input = celCommandInput(celEntity)
          self.timer = celAddTimer(celEntity)
          self.timer.WakeUpFrame (CEL_EVENT_POST)
          self.select = celMeshSelect(celEntity)

Accessing property class properties.

To access property class properties from python you can use standard python syntax. For example to query/set jitter for a pctrigger:

 
    oldjitter = trigger.jitter
    trigger.jitter = 100

Messages

Each property class in CEL can generate a number of messages. A python behaviour receives this messages as python function calls with the same name as the message. We can use this calls to respond to events from the different property classes appropiately.

In the first example we're receiving a pctimer_wakeupframe function call each frame, due to the activated pctimer.

Also there are some pccommandinput_* functions, that are triggered by the pccommandinput binds. Notice for each input bind we make through pccommandinput, the behaviour will receive three different events named pccommandinput_bind1, pccommandinput_bind0 and pccommandinput_bind_, respectively for the key press, release and maintain events.

Other property classes like pcphysics.object, pcobject.mesh.select, pc2d.billboard, pclogic.damage, pcmove.linear also generate their own special messages.

Message function calls get three parameters. The first is the behaviour class instance, the second the property class sending the message, and the last a celParameterBlock that holds all message specific values.

You can access the values from the parameter block as a python dict with CEL StringIDs or python strings for index. Using StringIDs directly is slightly more efficient.

 
# a pcbillboard select message
def pcbillboard_select(self,pc,args):
       print pc.Tag
       bx = args["x"]
       by = args["y"]
       button = args["button"]

It is possible to test for existence of a certain parameter, or iterate over the values. Also note for efficiency you would save the StringIDs for later use instead of querying them each time.

A final snippet for printing all parameters to a message:

 
def pcbillboard_select(self,pc,args):
       for strid in args.keys():
		print fromid(strid),args[strid]

New PcClass Messages Callback Style

There is a new style for receiving message callbacks from pcclasses in cel 1.2 to address some design errors in previous version. This new style is the one present in this documentation and also in all behaviour examples in cel.

By specifying api_version = 2 at the body of a behaviour class you can use the new message callback style (see initial example in this chapter).

Old message callback style was:

 
def pcbillboard_select(self,celEntity,args):
        ...

And the new one in cel 1.2 is:

 
def pcbillboard_select(self,pc,args):
        ...

Although the old style is still default due to backwards compatibility reasons, you are recommended to start using the new one, as it gives access to the pc sending the message, required in case you want to discriminate among similar pc classes present in the entity.

Note specifying api_version is required in cel 1.2 so as to be able to maintain backwards compatibility in future releases when default callback style is changed.

If you need access to the entity parameter, you should now save it in the behaviour constructor.

Sending Messages

Some messages (like __init__ and messages from property classes) are automatically called but you can also define your own messages and call them using the iCelBehaviour.SendMessage function.

To send a message/event to another entity, we must create the same kind of parameter list. There exists a helper function in the physical layer to do this called CreateParameterBlock, and also the ‘pycel’ alias parblock. It accepts either a dict, list or tuple as arguments. If we provide a dict, it will initialize the IDs and values in the parameter block; if we provide a list or tuple, it will only fill the IDs and will require filling the values later:

 
#Creating a parameter block from a list. This is more similar to the c++ method
pars = parblock(["control","x","y"])
pars["control"] = "specular"
pars["x"] = 15
pars["y"] = 200

#Creating a parameter block from a dictionary.
pars2 = parblock({"control":"shininess","x":30,"y":200})

The difference is in speed, usually if you'll be sending the same kind of parameter block many times, you'll want to build it in the constructor from the behaviour, and just fill values before sending. In other situations it can be appropriate to create the entire parameter block from a dict when needed.

After this, the message is sent using SendMessage in the target entity behaviour:

 
Entities["player"].Behaviour.SendMessage("control_variable", None, pars)

A python world for ‘celstart’

The best way to run python (or XML and python) only CEL worlds is to use the ‘celstart’ CEL application (see section celstart).

For this you will need to load the python behaviourlayer from the celstart configuration file. Another common procedure is to define some starting entity to be created with an app behaviour. From here it is possible to load the map entirely from python although note other setups are possible.

In order to do do this, we would add something like the following to the config file:

 
CelStart.BehaviourLayer.blpython = cel.behaviourlayer.python
CelStart.Entity.bootstrap = bootstrap
CelStart.EntityBehaviour.bootstrap = appinit
CelStart.EntityBehaviourLayer.bootstrap = blpython

This would create a starting entity and load the python behaviour appinit, which would be loaded from the file ‘appinit.py’.

From this behaviour you can load a map using either CS or CEL API, an usual way of doing this is through a celZoneManager property class (see section Zone Manager) at the initial entity:

 
def __init__(self,celEntity):
	zoneMgr = celZoneManager(celEntity)
	Vfs.ChDirAuto("/tmp/celstart/")
	zoneMgr.Load("/tmp/celstart","level.xml")

Note ‘/tmp/celstart/’ is the VFS path where ‘celstart’ maps the ZIP file initially, so this doesn't change depending on operating system or real file location.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated using texi2html 1.76.