C++ to Python Converter (useful hack) (with code!)


04-08-2009 06:51:03

I guess I haven't really introduced myself around here. I'm developing an as-of-yet unnamed game project alongside an unreal/quake style python-ogre framework (which would make developing Ogre games a lot like developing Quake mods). Still very much undecided about licensing, although I'm leaning towards LGPL. Anyway, on topic:

I've noticed that while looking for any sort of example code for Ogre, it's all C++, very very little is Python, so it can be tricky to figure out how to do things more advanced than the tutorials. I've written an extremely simple python script to convert c++ ogre samples to python-ogre.

I should be clear, this isn't really a language converter. It's actually more like a fancy find/replace with a bit of logic. I'm also a bit embarrassed for this to be the first piece of my own code I'm releasing, because it was written at 1 in the morning very quickly so I could move on and get some code working :) It's not very pretty or efficient. That being said, it's helpful. For instance,

Ogre::Light *light = mgr.sceneMgr->createLight("flashLight");
light->setDiffuseColour(Ogre::ColourValue(1, 1, 1));
light->setSpecularColour(Ogre::ColourValue(1, 1, 1));
light->setAttenuation(30, 1, 1, 1); // meter range. the others our shader ignores
light->setDirection(Ogre::Vector3(0, 0, -1));
node = rootNode->createChildSceneNode("flashLightNode");

gets converted to:

ogre.Light *light = mgr.sceneMgr.createLight("flashLight")
light.setDiffuseColour(ogre.ColourValue(1, 1, 1))
light.setSpecularColour(ogre.ColourValue(1, 1, 1))
light.setAttenuation(30, 1, 1, 1); # meter range. the others our shader ignores
light.setDirection(ogre.Vector3(0, 0, -1))
node = rootNode.createChildSceneNode("flashLightNode")

Obviously it doesn't handle everything - as I said, it's basically a find/replace, it doesn't understand language constructs. But across large pieces of code, despite the fact that you still have to do some manual tweaking, it saves me a lot of time when I'm trying to use some C++ sample code. You still need a half-decent understanding of both C++ and Python to do this, it doesn't convert classes or methods completely, just saves time with the syntax conversion.

Fair warning: this is a hack. A nice time-saving hack, but still a hack :)

The code:

If anyone has any improvements they can make, or even a preexisting way to do this (I couldn't find anything at all on Google), I'd love to hear your ideas/code.