TGEPython - Prairie Games
by Prairie Games · 10/10/2002 (10:58 am) · 19 comments
<a href="/static/pg/resource/3345.tgepython1a.zip">Download Code File</a>
I have written some front matter for TGEPython - an industrial strength Torque/Python binding.
*** Sorry, over the years we've lost this file. Please forward to Support@PrairieGames.com, thank you!
You can find it: HERE
Cheers,
-Joshua Ritter
Prairie Games, Inc.
I have written some front matter for TGEPython - an industrial strength Torque/Python binding.
*** Sorry, over the years we've lost this file. Please forward to Support@PrairieGames.com, thank you!
You can find it: HERE
Cheers,
-Joshua Ritter
Prairie Games, Inc.
---------------------
[b]TGEPython
An industrial strength Torque Game Engine/Python binding
v .1a
---------------------
(c)2002 Joshua Ritter
---------------------[/b]
---------------------
[b]Front Matter[/b]
---------------------
First things first:
"Wenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput!"
1) What is this?
I am a big fan of Python (www.python.org). I want to use it with the incredible Torque Game Engine!
2) Why?
Python's dynamic elegance, vast libraries, the choice of several real GUI builders for tools programming,
internet connectivity, it's code seperation via modules and packages... it's maturity, planning, army of developers...
on and on and on and on... suffice to say, it is NOT just another scripting language for Torque!!!
3) What version of Python does it use?
This release has been developed under Python 2.2.1
4) What version of Torque does it use?
The HEAD CVS near on or about 10/01/02
5) How to install?
READ INSTALLATION.TXT ... carefully...
6) What is the LICENSE
Please see the license in license.txt or on the bottom of this document.
7) Contacting me
I can be contacted at ritterjoshua@msn.com ... please contact me if you make this better or see
a way it could be! But please, try not to email me with tech support type stuff...
8) If you aren't using BOA as your Python editor... please CHECK IT OUT...
GET THE LATEST CVS VERSION... I am using v0.1.3a ... it ROCKS.. and has an awesome wxPython GUI
builder to boot! http://boa-constructor.sourceforge.net/
-----------------------------------------------------------------------------------
[b]"DOCS"[/b]
-----------------------------------------------------------------------------------
All right, here's where I start rambling... when all else fails LOOK AT THE EXAMPLES PROVIDED...
[b]OVERVIEW[/b]
-----------------------------------------------------------------------------------
This is a Python Module for TGE... no C++ engine source code was harmed in this production... as in zero modifications.. muahahaa
The main idea is to do the BULK of game logic in Python, with a quick and efficient interface to set
the TGE ***Where you need to***... inheritance of SimObjects AND SimDataBlocks is a major time saver.. as is Python's just
flat out elegance.. I am especially keen on 2.2's Generator support for flow control... yummy
TGEPython hasn't been tested in production yet, check the version number... though, so far it has proven quite robust... it is the third
rewrite/design of such a system
There may seem like a fair bit of rules here... there really isn't... the goal has been in making a small and efficient way to use Python
with TGE... I will be using this A LOT...
It isn't meant as a replacement for the common, rw, of fps folders... that is your job... though, I may release my framework once I have one
worked out ...
I hope to see Python libraries of Torque coolness being made (eventually)... and maybe an infusion from the ever GROWING Python Community!
-----------------------------------------------------------------------------------
[b]TO DO[/b]
-----------------------------------------------------------------------------------
Support for network string id's
Convenience (wrapper) classes/functions could be plentiful... in the release we are talking meat and potatos...
Add the additional math classes in tgepython/tgetypes .. right now vec3 is hooked up... want to use matrix and quat -> TGE String transforms
A simulation system not too unlike what is found at: http://simpy.sourceforge.net/
Some other stuff...
[b]FROM TGE[/b]
-----------------------------------------------------------------------------------
From TGE you can call:
PyInit(); <---- create the Python 2.2 interpreter (once at init see INSTALLATION.TXT)
PyExit(); <---- destroy the Python 2.2 interpreter (once at exit see INSTALLATION.TXT)
### Note on PyInit(); and PyExit(); -> you only need to initialize the interpreter IF YOU USE IT
For instance, your server may use Python but your client may not!
Executing Python code:
PyExec("some.py",["function()"]);
Internally this imports the module some.py and optionally runs the function specified! If no function is given is defaults to
executing a function called PyExec() .. so that you can just do PyExec("some.py") with a common entry point for your scripts!
You can also call:
PySimpleString("print 1+1"); <---- you guessed it... this will run a string of python code
*Small Note* In a previous version I had PyEvaluate(); <---- which would evaluate a Python string and return a value to TGE ... so far
this hasn't been needed... will probably be added though..
[b]IN PYTHON[/b]
------------------------------------------------------------------------------------
Here's where things get interesting:
In Python you can define new Datablocks and new SimObjects ...
***You can also MIX and MATCH these with objects created in native C++ AND TGEScript***
This _includes_ function callbacks into Python! What you want inheritance? YOU GOT IT!
But first, a few rules:
***IMPORTANT THE STRING RULE***
STRING RULE defined: return values from TGE are always strings... you will need to typecast like you were in a C++ TorqueScript function...
The STRING RULE only applies to out values! Check out the demo code, you'll even see a nice Vec3 class being handed directly to TGE!
***IMPORTANT ARRAYS***
You can programmically access TGE arrays with tuples OR a __Index notation...
Setting:
dataBlock[("stateName",0)]="Fire" or
dataBlock.stateName__0 = "Fire"
and Getting:
print dataBlock[("stateName",0)] or
print dataBlock.stateName__0
***IMPORTANT .registerObject() ***
For Python created TGE SimDataBlocks and SimObjects you must call .registerObject(class) ... with the class as an argument...
This is best done in the __init__ function for your class.
!!!!THIS MUST BE DONE AFTER YOU SET ALL YOUR FIELDS!!!!
Example:
class TestTrigger(TriggerData):
def __init__(self,objectname="TestTrigger"):
TriggerData.__init__(self,objectname)
self._tge.tickPeriodMS = 1000
self.registerObject(TestTrigger) <--- ONLY AFTER ALL FIELDS ARE SET!
[b]tgenative Module[/b]
-------------------------------------------------------------------------------------
1) The "public" tgenative module functions (this is the C++ extension stuff)
____1a: Global Vars
TGE Console Globals are accessed thus:
TGESetGlobal("$SomeGlobalVar",100) <--- set global to 100 .. notice nonstring value going in...
var=int(TGEGetGlobal("$SomeGlobalVar")) <--- get global... if after above call var will equal the 100 ... notice the typecast to int...
____1b: Printing
TGEPrint("Hey there") <--- prints to console
____1c: Calling Arbitrary TGE code
var=TGECall("somefunction",100,"whewp",.01") <--- sets var to the (STRING RULE) return of the TGE Console function somefunction...
using args 100,"whewp", and .01 ... how cool is this! You can pass a Tuple instead: so TGECall("somefunction",(100,"whewp",.01)) is
just as good!
var=TGEEval("echo("Hey From Python!"") <--- evaluate some arbitrary TGEScript code with (STRING RULE) return
____1d: Introduction to the extension type TGEObject
***IMPORTANT TGEObjects***
When you are in the midst of a TGEScript callback like the argc argv stuff in C++ ... OR you are accessing the underlying TGE C++
SimObject via a Python SimObjects._tge field... You use a TGEObject...This is the workhorse...
---TGEObject given a string
You can get any SimDataBlock or SimObject , either created in TGE or in Python using it's name or id ... for instance
pd=TGEObject("LightMaleHumanArmor") #This grabs the SimDataBlock for the player
pd.jumpForce = 200.3 * 90 #this adjusts the jump force
pd=TGEObject(42) #This grabs the SimObject with id 42
print pd.getId() #this prints 42
---TGEObject in a function call (handed an id)
When calling into Python code from TGE you are given a Tuple with all your nice STRING arguments
in it... this is EXACTLY like in C++:
So lets say you are passed a player object as argument 3 ... you would do this:
def PythonMethodCalledFromTGE(self,args):
player=TGEobject(args[2])
v=TGEVec3(player.getVelocity())
v*=1.1
v[2]+=20
player.setVelocity(v)
Notice the STRING RULE with a handy conversion to a Vec3 (decent vector class) ... notice also you can just pass the vec3 into
TGE!!!!
---TGEObject in a Python created SimObject instance
When you create a new SimObject or SimDataBlock from Python... your new (Python) instance has a remarkable little field ._tge
This field is the TGEObject bound to the SimObject... you access it exactly like above... here is a snippet to give flavor
p=SimObject("Projectile","anonymous") #classname and objectname arguments
tge=p._tge
tge.dataBlock="CrossbowProjectile" #note ANY DATABLOCK can be accessed as a string... whoa!
tge.initialVelocity = muzzleVector
tge.initialPosition = obj.getMuzzlePoint(slot)
tge.sourceObject = obj
tge.sourceSlot = slot
tge.client = obj.client
p.registerObject(SimObject) #REMEMBER TO DO THIS!
_____1e Exposing Functions
You can export Python functions to TGE with the TGEExport function pretty much exactly how you AddCommand them from C++
---Exporting class methods
TGEExport(TestWeaponImage.onFire,objectname,"onFire","onFire()",4,4) <---- a method ... notice the objectname convention used in
the samples... this is to support inheritance... you don't need to do this.. but it is recommended...
---Exporting unbound functions
TGEExport can also be used to Export unbound functions from Python ---->
def somefunction(args):
print args[0], args[1] # note the TGE convention on args.. they are always a Tuple of strings in Python
TGEExport(somefunction,None,"somefunction","somefunction()",2,2) <--- you just pass None in the namespace part..
Now if we do a somefunction(100); in TGE we will get Python printing: somefunction 100
--------------------------------------------------------------------------------------
[b]NOTES[/b]
--------------------------------------------------------------------------------------
The tgepython module functions
You can find samples of creating SimObject and SimDataBlock classe, functions etc in the example stuff in the distrib...
And now some random thoughts on using this:
--- REMEMBER to call .registerObject(class) on your new instances and datablocks!!!!!
--- Any TGEScript datablock (TGECreated or Python) can be accessed simply by specifying it with a string... for instance "CrossbowProjectile"
or "CrossbowAmmo" mixing and matching TGEScript and Python works well and is natural... though if unwanted... just code the appropriate
stuff in Python (like the inventory system) and you won't need to...
--- Dynamic fields are fully supported... you can even specify them in Python!
--- Python created SimObjects are derived from the SimObject and SimDataBlock classes... class instances have a _tge member which is simply
a bound TGEObject() ... you can use this exactly like a "cast" TGEObject() from TGE
--- Generally (know your arguments!) it is safe to pass TGE: int, float, str, vec3(or a ListType of form [0,0,0], TGEObject instances, True, False.
Passing in None leaves the field UNCHANGED
--- Check out the tgetypes folder in the tgepython module ... right now vec3 is used and can convert TGE vector string returns via the TGEVec3()
helper function
--- TGE may delete your SimObjects!!!! Take the instance of a Projectile... you create it and send it on it's way... well, when it hits something
TGE blows it up and DELETES IT!!!! This screws everything up and you will crash... um, heh... actually I used the notification system and
TGE will automatically call in and get rid of your Python SimObject for you... if you need to use the _tge field of SimObjects like this
(ones that the engine can delete without your control) simply add a notification to your Python class... woot!
--- In your (python) SimObject derived classes there is a variable _tgedeleted ... this is set to True when an object is deleted deleted from TGE...
You can use this to detect deleted objects in your containers during updates.. something like
for p in projectiles:
if p._tgedeleted:
projectiles.remove(p)
else:
p.doSomething()
I may implement some kind of callback system here... but for now this is quite good enough!
--- Python output and exceptions are directed to your TGE Console... for your pleasure
--- Lots of other stuff...
[b]CREDITS[/b]
---------------------------------------
Joshua Ritter - me
Jason Asbahr - Inspiration was found in Jason Asbahr's Nebula Device npython module -> www.asbahr.com
Matthias Baas - Some code in tgetypes is: Copyright (C) 2002, Matthias Baas (baas@ira.uka.de)
====================================================================================================
Start Of TGEPython Licensing Terms
====================================================================================================
This software is copyrighted by the Joshua Ritter (the Authors) and other parties.
The following terms apply to all files associated with the software unless explicitly disclaimed in
individual files.
The Authors hereby grant permission to use, copy, modify, distribute, and license this software and
its documentation for any purpose, provided that existing copyright notices are retained in all
copies and that this notice is included verbatim in any distributions. No written agreement,
license, or royalty fee is required for any of the authorized uses. Modifications to this software
may be copyrighted by their authors and need not follow the licensing terms described here, provided
that the new terms are clearly indicated on the first page of each file where they apply.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR
ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION
TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
====================================================================================================
End Of TGEPython Licensing Terms
====================================================================================================
#2
10/10/2002 (11:50 am)
Awesome. Thanks for working on this and submitting it, Josh.
#3
I may start up a CVS for this in the not too distant future...
I am currently working on a TGEPython based distributed content system which will help shake the system out...
I would ask that significant improvements/bug fixes find there way back into TGEPython ... though, this isn't mandatory... use it, have fun, make coolness...
Rock on rebel warriors,
-J
10/11/2002 (2:38 am)
:)I may start up a CVS for this in the not too distant future...
I am currently working on a TGEPython based distributed content system which will help shake the system out...
I would ask that significant improvements/bug fixes find there way back into TGEPython ... though, this isn't mandatory... use it, have fun, make coolness...
Rock on rebel warriors,
-J
#4
(that high jump and test weapon were right on the money Joshua ! ;))
Didn't go as nice as I would have liked, but all in all not too shabby...
Have a good one,
n.
10/12/2002 (5:56 pm)
Looks like I might have "converted" a few guys attending the Montreal Blender party to go for Torque licenses, and the clincher for them was the tgePython module... 8p(that high jump and test weapon were right on the money Joshua ! ;))
Didn't go as nice as I would have liked, but all in all not too shabby...
Have a good one,
n.
#5
...anyway, that python binding is great. This will definitely make Torque even more attractive for new developers.
10/23/2002 (12:44 pm)
Coming soon to a CVS near you: QBasic for Torque :P...anyway, that python binding is great. This will definitely make Torque even more attractive for new developers.
#6
I've put the python code in the proper locations, just under gorpe instead of rw. I did a file grep for all occurances of "rw" in the python code and replaced it with "gorpe". Oddly enough if I put the python files in the "rw" tree I still get the same errors.
Is there something I need to do to point the internal python engine to the proper directory tree?
11/20/2002 (5:46 am)
I've managed to partialy integrate TGEPython into our GORPE project. I can call Python code from the console just fine however the imports don't work for me. I get errors stating that Python couldn't find "gorpe.server.server" and the like. I've put the python code in the proper locations, just under gorpe instead of rw. I did a file grep for all occurances of "rw" in the python code and replaced it with "gorpe". Oddly enough if I put the python files in the "rw" tree I still get the same errors.
Is there something I need to do to point the internal python engine to the proper directory tree?
#7
You can find it: HERE
Cheers,
-Joshua Ritter
ActionRPG Evangelist
Did you test with the included sample stuff?
Try doing it with a clean install... there is a seperate installation.txt describing this...
You have __init__.py in your module folders?
There is nothing special about TGEPython's embedded interpretor... certainly nothing that would affect importing :)
Try importing gorpe.server.server from the console...
-J
11/26/2002 (1:21 am)
I have written some front matter for TGEPython - an industrial strength Torque/Python binding.You can find it: HERE
Cheers,
-Joshua Ritter
ActionRPG Evangelist
Did you test with the included sample stuff?
Try doing it with a clean install... there is a seperate installation.txt describing this...
You have __init__.py in your module folders?
There is nothing special about TGEPython's embedded interpretor... certainly nothing that would affect importing :)
Try importing gorpe.server.server from the console...
-J
#8
05/28/2003 (11:14 pm)
great work.
#10
(Haven't done much of testing yet though).
08/24/2005 (3:10 am)
FYI. I've successfully compiled this resource with Python 2.4.(Haven't done much of testing yet though).
#11
12/30/2005 (7:19 pm)
Does it work with TGE 1.4?
#12
Don
01/08/2006 (12:10 pm)
I have this working in TGE 1.4 with Python 2.4. The only change was in tgePyObject.cc. There is a switch statement in the method tgePythonBuildPythonObject that has to be changed to a series of if statements since console types are no longer enum in 1.4. I'd certainly be interested in any enhancements Josh has made now that MoM is out.Don
#13
I'd also be interested. I'm wondering if we could pay Josh just for the Python integration part. I'd be willing to fork over some cash to have the code for 1.4.
Steve
01/22/2006 (10:23 am)
@Don,I'd also be interested. I'm wondering if we could pay Josh just for the Python integration part. I'd be willing to fork over some cash to have the code for 1.4.
Steve
#14
I didn't look at the code too deeply so am just sort of assuming it's right, I'll post
another message if there are any other problems.
Because I didn't compile python from source I didn't have a python24_d.lib file so I needed to add the following pre-compiler statements to the top of both .cc files to get the debug build to work:
It's amazing how little integration was required and how well the code stands up after 3+ years of changes to TGE.
03/25/2006 (2:17 pm)
Seems to work for me with 1.4 on windows with the following replacement of to tgePythonBuildPythonObject in tgePyObject.cc (Which Don mentioned above).I didn't look at the code too deeply so am just sort of assuming it's right, I'll post
another message if there are any other problems.
PyObject* tgePythonBuildPythonObject(U32 ftype,const char* value)
{
if(ftype == TypeS8 || ftype == TypeS32) {
return PyInt_FromLong(strtol(value,NULL,10));
}
else if(ftype == TypeF32) {
return PyFloat_FromDouble(strtod(value,NULL));
}
else if(ftype == TypeBool) {
if (!dStricmp("1",value))
return PyInt_FromLong(1);
else
return PyInt_FromLong(0);
}
else {
return PyString_FromString(value);
}
}Because I didn't compile python from source I didn't have a python24_d.lib file so I needed to add the following pre-compiler statements to the top of both .cc files to get the debug build to work:
#ifdef _DEBUG #undef _DEBUG #include "Python.h" #define _DEBUG #else #include "Python.h" #endif
It's amazing how little integration was required and how well the code stands up after 3+ years of changes to TGE.
#15
05/03/2006 (7:03 pm)
I would like to get this up and running for TSE I wonder if Josh is still monitoring this post.....I have just gotten into the python language and find it great and would like to see this resource updated...maybe i should shoot him an email.....prarie games is it?...anyone???
#16
08/08/2006 (8:44 pm)
Uh... the link to the site seems... outdated. I get some ads spam site thing...
#17
11/28/2006 (12:30 pm)
archive.org is your friend, http://web.archive.org/web/20040205085906/http://www.actionrpg.com/twiki/bin/view.cgi/Main/TorquePython
#18
02/04/2007 (11:44 pm)
I just wanted to chime in with my experience getting this resource to work under TGE 1.5. I started out with the base copy of TGE 1.5 + AFX. I installed Python 2.5, and followed Josh's instructions included with the resource. I did have to apply the changes Pascal listed above. Everything compiled fine under VC2005 express. I didn't test it out yet besides adding in PyInit() and PyExit() into my main.cs file and verifying the console log showed that python was initialized. If I encounter and trouble with python 2.5 under TGE 1.5 with this resource I'll follow up here, but sofar so good.
#19
Step #1c in the INSTALLATION.txt file is unnecessary as 1.5.1 has Multithreaded set already.
04/14/2007 (9:31 am)
This works with TGE 1.5.1 and Python 2.5 using Pascal's changes.Step #1c in the INSTALLATION.txt file is unnecessary as 1.5.1 has Multithreaded set already.

Torque Owner Nicolas Quijano
So far, built it on HEAD from few days ago, worked on the first try, updated HEAD yesterday, recompiled, no trouble at all... :)
Haven't tried it with RW CVS yet, but that should work, as all the examples/tests so far are for the rw mod.
Great work Joshua, keep it up !!!
And, thank you very much !!! (again ;))
n.