Browse Source

Im happy to anounce the first revesion that features scripting. Its using python exposed through boost python library

Panagiotis Christopoulos Charitos 15 years ago
parent
commit
b8ed62ced6

+ 1 - 1
.cproject

@@ -20,7 +20,7 @@
 <option id="cdt.managedbuild.option.gnu.cross.prefix.124248385" name="Prefix" superClass="cdt.managedbuild.option.gnu.cross.prefix"/>
 <option id="cdt.managedbuild.option.gnu.cross.path.568633506" name="Path" superClass="cdt.managedbuild.option.gnu.cross.path"/>
 <targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.targetPlatform.gnu.cross.2099631" isAbstract="false" osList="all" superClass="cdt.managedbuild.targetPlatform.gnu.cross"/>
-<builder arguments="make -j 4" autoBuildTarget="all" buildPath="${workspace_loc:/anki/build/debug}" cleanBuildTarget="clean" command="nice" enableAutoBuild="false" enableCleanBuild="true" enabledIncrementalBuild="true" id="cdt.managedbuild.toolchain.gnu.cross.base.1593777304.618553305" incrementalBuildTarget="all" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" parallelizationNumber="1" superClass="org.eclipse.cdt.build.core.settings.default.builder">
+<builder arguments="make -j 3" autoBuildTarget="all" buildPath="${workspace_loc:/anki/build/debug}" cleanBuildTarget="clean" command="nice" enableAutoBuild="false" enableCleanBuild="true" enabledIncrementalBuild="true" id="cdt.managedbuild.toolchain.gnu.cross.base.1593777304.618553305" incrementalBuildTarget="all" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" parallelizationNumber="1" superClass="org.eclipse.cdt.build.core.settings.default.builder">
 <outputEntries>
 <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="outputPath" name="build/debug"/>
 </outputEntries>

+ 1 - 1
.project

@@ -27,7 +27,7 @@
 				</dictionary>
 				<dictionary>
 					<key>org.eclipse.cdt.make.core.buildArguments</key>
-					<value>make -j 4</value>
+					<value>make -j 3</value>
 				</dictionary>
 				<dictionary>
 					<key>org.eclipse.cdt.make.core.buildCommand</key>

File diff suppressed because it is too large
+ 515 - 306
build/debug/Makefile


+ 4 - 4
build/debug/gen.cfg.py

@@ -1,9 +1,9 @@
-sourcePaths = ["../../src/Math/", "../../src/Util/Tokenizer/", "../../src/Misc/", "../../src/", "../../src/Renderer/", "../../src/Scene/", "../../src/Ui/", "../../src/Resources/", "../../src/Util/", "../../src/Scene/Controllers/", "../../src/Physics/", "../../src/Renderer/BufferObjects/", "../../src/Resources/Helpers/", "../../src/Resources/Core/"]
+sourcePaths = ["../../src/Math/", "../../src/Util/Tokenizer/", "../../src/Misc/", "../../src/", "../../src/Renderer/", "../../src/Scene/", "../../src/Ui/", "../../src/Resources/", "../../src/Util/", "../../src/Scene/Controllers/", "../../src/Physics/", "../../src/Renderer/BufferObjects/", "../../src/Resources/Helpers/", "../../src/Resources/Core/", "../../src/Core/", "../../src/Scripting/", "../../src/Scripting/Math", "../../src/Scripting/Util", "../../src/Scripting/Core", "../../src/Scripting/Scene"]
 
 includePaths = []
 includePaths.append("./")
 includePaths.extend(list(sourcePaths))
-includePaths.extend(["../../extern/include", "../../extern/include/bullet"])
+includePaths.extend(["../../extern/include", "../../extern/include/bullet", "/usr/include/python2.6"])
 
 #precompiledHeaders = ["../../src/Util/Common.h", "/usr/include/boost/filesystem.hpp", "/usr/include/boost/ptr_container/ptr_vector.hpp"]
 precompiledHeaders = []
@@ -14,8 +14,8 @@ compiler = "g++"
 
 defines__ = "-DDEBUG_ENABLED -DPLATFORM_LINUX -DREVISION=\\\"`svnversion -c ../..`\\\""
 
-precompiledHeadersFlags = defines__ + " -c -pedantic-errors -pedantic -ansi -Wall -Wextra -W -pipe -O0 -g3 -pg"
+precompiledHeadersFlags = defines__ + " -c -pedantic-errors -pedantic -ansi -Wall -Wextra -W -Wno-long-long -pipe -O0 -g3 -pg"
 
 compilerFlags = precompiledHeadersFlags + " -fsingle-precision-constant"
 
-linkerFlags = "-rdynamic -L../../extern/lib-x86-64-linux -Wl,-Bstatic -lBulletSoftBody -lBulletDynamics -lBulletCollision -lLinearMath -lGLEW -lGLU -lboost_system -lboost_filesystem -Wl,-Bdynamic -lGL -ljpeg -lSDL -lpng -pg"
+linkerFlags = "-rdynamic -L../../extern/lib-x86-64-linux -Wl,-Bstatic -lBulletSoftBody -lBulletDynamics -lBulletCollision -lLinearMath -lGLEW -lGLU -lboost_system -lboost_python -lboost_filesystem -Wl,-Bdynamic -lGL -ljpeg -lSDL -lpng -lpython2.6 -pg"

+ 3 - 1
src/Util/App.cpp → src/Core/App.cpp

@@ -4,6 +4,7 @@
 #include "App.h"
 #include "Scene.h"
 #include "MainRenderer.h"
+#include "ScriptingEngine.h"
 #include <boost/filesystem.hpp>
 
 bool App::isCreated = false;
@@ -73,8 +74,9 @@ App::App(int argc, char* argv[], Object* parent):
 	filesystem::create_directory(cachePath);
 
 
-	scene = new Scene;
+	scene = new Scene(this);
 	mainRenderer = new MainRenderer;
+	scriptingEngine = new ScriptingEngine(this);
 	activeCam = NULL;
 
 	timerTick = 1000/40; // in ms. 1000/Hz

+ 37 - 2
src/Util/App.h → src/Core/App.h

@@ -7,6 +7,9 @@
 #include "Object.h"
 
 
+class ScriptingEngine;
+
+
 /**
  * This class holds all the global objects of the application and its also responsible for some of the SDL stuff.
  * It should be singleton
@@ -15,16 +18,19 @@ class App: public Object
 {
 	PROPERTY_R(uint, windowW, getWindowWidth) ///< The main window width
 	PROPERTY_R(uint, windowH, getWindowHeight) ///< The main window height
-	PROPERTY_R(bool, terminalColoringEnabled, isTerminalColoringEnabled) ///< Terminal coloring for Unix terminals. Default on
+	//PROPERTY_R(bool, terminalColoringEnabled, isTerminalColoringEnabled)
 	PROPERTY_R(filesystem::path, settingsPath, getSettingsPath)
 	PROPERTY_R(filesystem::path, cachePath, getCachePath)
 
-	PROPERTY_RW(class Scene*, scene, setScene, getScene) ///< Pointer to the current scene
+	//PROPERTY_RW(class Scene*, scene, setScene, getScene) ///< Pointer to the current scene
 	PROPERTY_RW(class MainRenderer*, mainRenderer, setMainRenderer, getMainRenderer) ///< Pointer to the main renderer
 	PROPERTY_RW(class Camera*, activeCam, setActiveCam, getActiveCam) ///< Pointer to the current camera
 
 	private:
 		static bool isCreated; ///< A flag to ensure one @ref App instance
+		bool terminalColoringEnabled; ///< Terminal coloring for Unix terminals. Default on
+		class Scene* scene;
+		ScriptingEngine* scriptingEngine;
 		uint time;
 		SDL_WindowID windowId;
 		SDL_GLContext glContext;
@@ -48,6 +54,15 @@ class App: public Object
 		uint getDesktopWidth() const;
 		uint getDesktopHeight() const;
 
+		/**
+		 * @name Accessors
+		 */
+		/**@{*/
+		bool isTerminalColoringEnabled() const;
+		Scene* getScene();
+		ScriptingEngine& getScriptingEngine();
+		/**@}*/
+
 		/**
 		 * @return Returns the number of milliseconds since SDL library initialization
 		 */
@@ -55,4 +70,24 @@ class App: public Object
 };
 
 
+inline bool App::isTerminalColoringEnabled() const
+{
+	return terminalColoringEnabled;
+}
+
+
+inline Scene* App::getScene()
+{
+	DEBUG_ERR(scene == NULL);
+	return scene;
+}
+
+
+inline ScriptingEngine& App::getScriptingEngine()
+{
+	DEBUG_ERR(scriptingEngine == NULL);
+	return *scriptingEngine;
+}
+
+
 #endif

+ 0 - 0
src/Util/Common.cpp → src/Core/Common.cpp


+ 0 - 0
src/Util/Common.h → src/Core/Common.h


+ 8 - 4
src/Main.cpp

@@ -35,6 +35,7 @@
 #include "DebugDrawer.h"
 #include "PhyCharacter.h"
 #include "RigidBody.h"
+#include "ScriptingEngine.h"
 
 
 App* app = NULL; ///< The only global var. App constructor sets it
@@ -299,6 +300,13 @@ void mainLoop()
 			body->forceActivationState(ACTIVE_TAG);
 		}
 
+		if(I::keys[SDL_SCANCODE_Y] == 1)
+		{
+			INFO("Exec script");
+			app->getScriptingEngine().exposeVar("app", app);
+			app->getScriptingEngine().execScript("#from Anki import *\nAnki.app.getScene().setAmbientCol(Anki.Vec3(0.5))");
+		}
+
 		mover->getLocalTransform().getRotation().reorthogonalize();
 
 		app->getScene()->getPhysics()->update(crntTime);
@@ -351,10 +359,6 @@ int main(int argc, char* argv[])
 {
 	new App(argc, argv);
 
-/*	Mat3 m(Axisang(-PI/2, Vec3(1,0,0)));
-	PRINT(fixed << m);
-	return 0;*/
-
 	init();
 
 	mainLoop();

+ 2 - 1
src/Physics/Physics.cpp

@@ -7,7 +7,8 @@
 //======================================================================================================================
 // Constructor                                                                                                         =
 //======================================================================================================================
-Physics::Physics():
+Physics::Physics(Object* parent):
+	Object(parent),
 	defaultContactProcessingThreshold(BT_LARGE_FLOAT),
 	time(0.0)
 {

+ 3 - 2
src/Physics/Physics.h

@@ -4,6 +4,7 @@
 #include <btBulletCollisionCommon.h>
 #include <btBulletDynamicsCommon.h>
 #include "Common.h"
+#include "Object.h"
 #include "BtAndAnkiConvertors.h"
 #include "DebugDrawer.h"
 
@@ -15,7 +16,7 @@ class RigidBody;
 /**
  * The master container for all physics related stuff.
  */
-class Physics
+class Physics: public Object
 {
 	friend class PhyCharacter; ///< For registering and unregistering
 	friend class RigidBody;  ///< For registering and unregistering
@@ -33,7 +34,7 @@ class Physics
 		};
 
 	public:
-		Physics();
+		Physics(Object* parent = NULL);
 		void update(float crntTime);
 		void debugDraw();
 

+ 3 - 2
src/Scene/Scene.cpp

@@ -12,12 +12,13 @@
 //======================================================================================================================
 // Constructor                                                                                                         =
 //======================================================================================================================
-Scene::Scene()
+Scene::Scene(Object* parent):
+	Object(parent)
 {
 	ambientCol = Vec3(0.1, 0.05, 0.05)*4;
 	sunPos = Vec3(0.0, 1.0, -1.0) * 50.0;
 
-	phyWorld.reset(new Physics);
+	phyWorld = new Physics(this);
 }
 
 

+ 13 - 10
src/Scene/Scene.h

@@ -3,6 +3,7 @@
 
 #include <memory>
 #include "Common.h"
+#include "Object.h"
 #include "skybox.h"
 #include "Physics.h"
 
@@ -17,13 +18,13 @@ class ParticleEmitter;
 
 
 /**
- * @brief The Scene contains all the dynamic entities
+ * The Scene contains all the dynamic entities
  */
-class Scene
+class Scene: public Object
 {
 	PROPERTY_RW(Vec3, ambientCol, setAmbientCol, getAmbientCol) ///< The global ambient color
 	PROPERTY_RW(Vec3, sunPos, setSunPos, getSunPos)
-	PROPERTY_R(auto_ptr<Physics>, phyWorld, getPhysics) ///< Connection with bullet
+	PROPERTY_R(Physics*, phyWorld, getPhysics) ///< Connection with bullet
 
 	public:
 		/**
@@ -33,17 +34,18 @@ class Scene
 		{};
 
 		// Containers of scene's data
-		Container<SceneNode>       nodes;
-		Container<Light>      lights;
-		Container<Camera>     cameras;
-		Container<MeshNode>   meshNodes;
-		Container<SkelNode>   skelNodes;
+		Container<SceneNode> nodes;
+		Container<Light> lights;
+		Container<Camera> cameras;
+		Container<MeshNode> meshNodes;
+		Container<SkelNode> skelNodes;
 		Container<Controller> controllers;
 		Container<ParticleEmitter> particleEmitters;
-		Skybox                skybox; // ToDo to be removed
+		Skybox skybox; // ToDo to be removed
 
 		// The funcs
-		Scene();
+		Scene(Object* parent = NULL);
+		~Scene() {}
 
 		void registerNode(SceneNode* node); ///< Put a node in the appropriate containers
 		void unregisterNode(SceneNode* node);
@@ -84,4 +86,5 @@ inline void Scene::eraseNode(ContainerType& container, Type* x)
 	container.erase(it);
 }
 
+
 #endif

+ 18 - 0
src/Scripting/BoostPythonInterfaces.cpp

@@ -0,0 +1,18 @@
+#include "Common.h"
+#include <boost/python.hpp>
+#include "Math.h"
+#include "Scene.h"
+#include "App.h"
+
+
+using namespace boost::python;
+using namespace M;
+
+
+BOOST_PYTHON_MODULE(Anki)
+{
+	#include "Vec3.bpi.h"
+	#include "Scene.bpi.h"
+	#include "App.bpi.h"
+}
+

+ 3 - 0
src/Scripting/Core/App.bpi.h

@@ -0,0 +1,3 @@
+
+class_<App, noncopyable>("App", no_init)
+	.def("getScene", &App::getScene, return_value_policy<reference_existing_object>());

+ 7 - 0
src/Scripting/Math/Vec3.bpi.h

@@ -0,0 +1,7 @@
+
+class_<Vec3>("Vec3")
+	.def(init<float, float, float>())
+	.def(init<float>())
+	.def_readwrite("x", &Vec3::x)
+	.def_readwrite("y", &Vec3::y)
+	.def_readwrite("z", &Vec3::z);

+ 3 - 0
src/Scripting/Scene/Scene.bpi.h

@@ -0,0 +1,3 @@
+
+class_<Scene, noncopyable>("Scene", no_init)
+	.def("setAmbientCol", &Scene::setAmbientCol);

+ 45 - 0
src/Scripting/ScriptingEngine.cpp

@@ -0,0 +1,45 @@
+#include <Python.h>
+#include "ScriptingEngine.h"
+
+
+extern "C" void initAnki(); /// Defined in BoostPythonInterfaces.cpp
+
+
+//======================================================================================================================
+// init                                                                                                                =
+//======================================================================================================================
+bool ScriptingEngine::init()
+{
+	INFO("Initializing scripting engine...");
+
+	PyImport_AppendInittab((char*)("Anki"), &initAnki);
+	Py_Initialize();
+	mainModule = python::object(python::handle<>(python::borrowed(PyImport_AddModule("__main__"))));
+	mainNamespace = mainModule.attr("__dict__");
+	ankiModule = python::object(python::handle<>(PyImport_ImportModule("Anki")));
+
+	//execScript("import Anki\n");
+
+	INFO("Scripting engine initialized");
+	return true;
+}
+
+
+//======================================================================================================================
+// execScript                                                                                                          =
+//======================================================================================================================
+bool ScriptingEngine::execScript(const char* script, const char* scriptName)
+{
+	try
+	{
+		python::handle<>ignored(PyRun_String(script, Py_file_input, mainNamespace.ptr(), mainNamespace.ptr()));
+	}
+	catch(python::error_already_set)
+	{
+		ERROR("Script \"" << scriptName << "\" failed with error:");
+		PyErr_Print();
+		return false;
+	}
+	return true;
+}
+

+ 59 - 0
src/Scripting/ScriptingEngine.h

@@ -0,0 +1,59 @@
+#ifndef SCRIPTING_ENGINE_H
+#define SCRIPTING_ENGINE_H
+
+#include <boost/python.hpp>
+#include "Common.h"
+#include "Object.h"
+
+
+/**
+ *
+ */
+class ScriptingEngine: public Object
+{
+	public:
+		ScriptingEngine(Object* parent = NULL);
+		~ScriptingEngine() {}
+
+		/**
+		 * Execute python script
+		 * @param script Script source
+		 * @return true on success
+		 */
+		bool execScript(const char* script, const char* scriptName = "unamed");
+
+		/**
+		 * Expose a C++ variable to python
+		 * @param varName The name to referenced in python
+		 * @param var The actual variable
+		 */
+		template<typename Type>
+		void exposeVar(const char* varName, Type* var);
+
+	private:
+		boost::python::object mainModule;
+		boost::python::object ankiModule;
+		boost::python::object mainNamespace;
+
+		/**
+		 * Init python and modules
+		 */
+		bool init();
+};
+
+
+inline ScriptingEngine::ScriptingEngine(Object* parent):
+	Object(parent)
+{
+	init();
+}
+
+
+template<typename Type>
+inline void ScriptingEngine::exposeVar(const char* varName, Type* var)
+{
+	python::scope(ankiModule).attr(varName) = python::ptr(var);
+}
+
+
+#endif

+ 8 - 3
src/Util/Object.h

@@ -12,6 +12,10 @@ class Object
 {
 	public:
 		Object(Object* parent = NULL);
+
+		/**
+		 * Delete childs from the last entered to the first
+		 */
 		virtual ~Object();
 
 		/**
@@ -34,16 +38,17 @@ class Object
 // Inlines                                                                                                             =
 //======================================================================================================================
 
-inline Object::Object(Object* parent)
+inline Object::Object(Object* parent):
+	objParent(NULL)
 {
-	if(parent)
+	if(parent != NULL)
 		parent->addChild(this);
 }
 
 
 inline Object::~Object()
 {
-	for(Vec<Object*>::iterator it=objChilds.begin(); it!=objChilds.end(); it++)
+	for(Vec<Object*>::reverse_iterator it=objChilds.rbegin(); it!=objChilds.rend(); it++)
 	{
 		delete *it;
 	}

Some files were not shown because too many files changed in this diff