yake-svn Mailing List for Yake Engine (Page 17)
Status: Beta
Brought to you by:
psyclonist
You can subscribe to this list here.
2006 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(17) |
Sep
(51) |
Oct
(2) |
Nov
(18) |
Dec
(66) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2007 |
Jan
(44) |
Feb
(13) |
Mar
(73) |
Apr
(61) |
May
|
Jun
(4) |
Jul
(19) |
Aug
(50) |
Sep
(47) |
Oct
(7) |
Nov
(7) |
Dec
(14) |
2008 |
Jan
(2) |
Feb
|
Mar
(4) |
Apr
(4) |
May
(5) |
Jun
(7) |
Jul
(4) |
Aug
|
Sep
(5) |
Oct
|
Nov
(1) |
Dec
(4) |
2009 |
Jan
|
Feb
(22) |
Mar
(12) |
Apr
(1) |
May
(1) |
Jun
(4) |
Jul
(4) |
Aug
|
Sep
|
Oct
(17) |
Nov
(3) |
Dec
|
2010 |
Jan
|
Feb
|
Mar
(12) |
Apr
(11) |
May
|
Jun
(5) |
Jul
(3) |
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <psy...@us...> - 2007-03-12 23:42:42
|
Revision: 1637 http://svn.sourceforge.net/yake/?rev=1637&view=rev Author: psyclonist Date: 2007-03-12 16:42:40 -0700 (Mon, 12 Mar 2007) Log Message: ----------- disable pch for 'base' Modified Paths: -------------- trunk/yake/scripts/premake/yake.lua Modified: trunk/yake/scripts/premake/yake.lua =================================================================== --- trunk/yake/scripts/premake/yake.lua 2007-03-12 23:35:51 UTC (rev 1636) +++ trunk/yake/scripts/premake/yake.lua 2007-03-12 23:42:40 UTC (rev 1637) @@ -66,8 +66,8 @@ -------------------------------------- makePackage("base") -- we cannot use makeDLLComponent() because of native .cpp addDefine("YAKE_BASE_EXPORTS") - package.pchheader = rootdir.."yake/base/yakePCH.h" - package.pchsource = rootdir.."src/base/yakePCH.cpp" + --package.pchheader = "yake/base/yakePCH.h" + --package.pchsource = rootdir.."src/base/yakePCH.cpp" addMatching("yake/base/*.h") addMatching("yake/base/*.inl") addMatching("yake/base/*.rc") This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-03-12 23:35:51
|
Revision: 1636 http://svn.sourceforge.net/yake/?rev=1636&view=rev Author: psyclonist Date: 2007-03-12 16:35:51 -0700 (Mon, 12 Mar 2007) Log Message: ----------- extended test.lua Modified Paths: -------------- trunk/yake/common/media/samples/scriptingLua/test.lua Modified: trunk/yake/common/media/samples/scriptingLua/test.lua =================================================================== --- trunk/yake/common/media/samples/scriptingLua/test.lua 2007-03-12 23:35:37 UTC (rev 1635) +++ trunk/yake/common/media/samples/scriptingLua/test.lua 2007-03-12 23:35:51 UTC (rev 1636) @@ -1,7 +1,17 @@ -print("from a file"); -a = 1; -b = 3; -print( a .. " + " .. b .. " = " .. a+b ); -print("creating player...\n"); -v = yake.Version( 0, 2, 0 ); -print("reading version numbers... VERSION is " .. v:getMajor() .. "," .. v:getMinor() ); +print("from a file") +a = 1 +b = 3 +print( a .. " + " .. b .. " = " .. a+b .. "\n" ) + +print("creating version object...") +v = yake.Version( 0, 2, 0 ) +print("reading version numbers (via get())... VERSION is " .. v:getMajor() .. "," .. v:getMinor() .. "," .. v:getSub() ) +print("reading version numbers (via props)... VERSION is " .. v.major .. "," .. v.minor .. "," .. v.sub) + +print("\ntesting vector3:") +v = yake.Vector3( 1, 1, 0 ) +print("original vector3 = " .. v.x .. " " .. v.y .. " " .. v.z) +v:normalise() +print("normalised vector3 = " .. v.x .. " " .. v.y .. " " .. v.z) + +print("\ntest done.") \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-03-12 23:35:36
|
Revision: 1635 http://svn.sourceforge.net/yake/?rev=1635&view=rev Author: psyclonist Date: 2007-03-12 16:35:37 -0700 (Mon, 12 Mar 2007) Log Message: ----------- lua bindings: properties for Version Modified Paths: -------------- trunk/yake/src/bindings.lua/detail/base.lua.cpp Modified: trunk/yake/src/bindings.lua/detail/base.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/base.lua.cpp 2007-03-12 23:18:20 UTC (rev 1634) +++ trunk/yake/src/bindings.lua/detail/base.lua.cpp 2007-03-12 23:35:37 UTC (rev 1635) @@ -156,6 +156,9 @@ [ class_< Version >( "Version" ) .def(constructor<uint16,uint16,uint16>()) + .def_readwrite( "major", &Version::mMajor ) + .def_readwrite( "minor", &Version::mMinor ) + .def_readwrite( "sub", &Version::mSub ) .def("getMajor", &yake::Version::getMajor) .def("getMinor", &yake::Version::getMinor) .def("getSub", &yake::Version::getSub) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-03-12 23:18:20
|
Revision: 1634 http://svn.sourceforge.net/yake/?rev=1634&view=rev Author: psyclonist Date: 2007-03-12 16:18:20 -0700 (Mon, 12 Mar 2007) Log Message: ----------- added library extension for YAKE_DYNLIB_NAME macro Modified Paths: -------------- trunk/yake/yake/base/yakePrerequisites.h Modified: trunk/yake/yake/base/yakePrerequisites.h =================================================================== --- trunk/yake/yake/base/yakePrerequisites.h 2007-03-12 23:17:00 UTC (rev 1633) +++ trunk/yake/yake/base/yakePrerequisites.h 2007-03-12 23:18:20 UTC (rev 1634) @@ -157,6 +157,6 @@ # define YAKE_DYNLIB_POSTFIX #endif #define YAKE_DYNLIB_NAME(X) \ - yake::String("yake_" X YAKE_DYNLIB_POSTFIX).c_str() + (yake::String("yake_" X YAKE_DYNLIB_POSTFIX) + "." + LIBRARY_EXTENSION).c_str() #endif // YAKE_BASE_PREREQUISITES_H This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-03-12 23:17:00
|
Revision: 1633 http://svn.sourceforge.net/yake/?rev=1633&view=rev Author: psyclonist Date: 2007-03-12 16:17:00 -0700 (Mon, 12 Mar 2007) Log Message: ----------- readd Added Paths: ----------- trunk/yake/yake/base/yakePrerequisites.h Added: trunk/yake/yake/base/yakePrerequisites.h =================================================================== --- trunk/yake/yake/base/yakePrerequisites.h (rev 0) +++ trunk/yake/yake/base/yakePrerequisites.h 2007-03-12 23:17:00 UTC (rev 1633) @@ -0,0 +1,162 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright \xA9 2004 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#ifndef YAKE_BASE_PREREQUISITES_H +#define YAKE_BASE_PREREQUISITES_H + +//============================================================================ +// IMPLEMENTATION HEADERS +//=========================================================================== +#include <yake/config.h> +#include <yake/base/yakePlatform.h> +#include <assert.h> +#include <ctime> +#include <math.h> +#include <cmath> +// Undef min and max macros on Windows. They're defined in windef.h. +#if (YAKE_PLATFORM == PLATFORM_WIN32) + #ifdef min + #undef min + #endif + #ifdef max + #undef max + #endif +#endif +#include <limits> +#include <cstdio> +#include <stdio.h> +#include <stdarg.h> +#include <string> +#include <stdexcept> +#include <locale> +#include <algorithm> +#include <functional> +#include <vector> +#include <map> +#include <list> +#include <queue> +#include <set> +#include <iostream> +#include <sstream> + +#ifdef __SGI_STL +# include <iterator> +#endif + +// Include platform specific configuration files +#if (YAKE_PLATFORM == PLATFORM_WIN32) && (YAKE_COMPILER == COMPILER_MSVC) +# include <yake/base/prerequisites/yakePrerequisitesVC.h> +#elif (YAKE_PLATFORM == PLATFORM_WIN32) && (YAKE_COMPILER == COMPILER_GNUC) +# include <yake/base/prerequisites/yakePrerequisitesGCCWin.h> +#elif (YAKE_PLATFORM == PLATFORM_LINUX) && (YAKE_COMPILER == COMPILER_GNUC) +# include <yake/base/prerequisites/yakePrerequisitesGCC.h> +#else +# error("Yake: No configuration file set for the selected platform/compiler!") +#endif + +//============================================================================ +// INTERFACE STRUCTURES / UTILITY CLASSES +//============================================================================ +// Yake + +// YAKE_BASE_API +#if defined( YAKE_BASE_EXPORTS ) +# define YAKE_BASE_API DLLEXPORT +#else +# define YAKE_BASE_API DLLIMPORT +#endif + +// YAKE_DEBUG +#if defined(_DEBUG) || defined(DEBUG) +# define YAKE_DEBUG +#endif + +// YAKE_UNICODE: Not supported at the moment! +//#define YAKE_UNICODE + +#if defined(YAKE_UNICODE) +# define __T(X) L ## X +#else +# define __T(X) X +#endif + +// _T(X) Macro for defining strings ( +#define _T(X) __T(X) + +// STL +#if defined(YAKE_DEBUG_BUILD) +//# define _STLP_DEBUG 1 +#endif +#define _STLP_USE_DYNAMIC_LIB + +// Boost / TTL +#if (YAKE_PLATFORM == PLATFORM_WIN32) && (YAKE_COMPILER == COMPILER_GNUC) + #define YAKE_SIGNALS_USE_BOOST +#else + #define YAKE_SIGNALS_USE_BOOST + //#define YAKE_SIGNALS_USE_TTL +#endif + +// YAKE_REAL_PRECISION +// Determines the type used for 'real'. +// YAKE_REAL_SINGLE_PRECISION = float +// YAKE_REAL_DOUBLE_PRECISION = double +//@todo move this into configuration header +#define YAKE_REAL_SINGLE_PRECISION 1 +#define YAKE_REAL_DOUBLE_PRECISION 2 +#define YAKE_REAL_PRECISION YAKE_REAL_SINGLE_PRECISION +#if YAKE_REAL_PRECISION == YAKE_REAL_SINGLE_PRECISION + typedef float real; +#elif YAKE_REAL_PRECISION == YAKE_REAL_DOUBLE_PRECISION + typedef double real; +#else +# pragma error("yake: Unknown type for 'real'!") +#endif + + +// Helper macros +// todo: remove, deprecated, use safe_delete(_array) +#define YAKE_SAFE_RELEASE(ptr) if(ptr) { ptr->release(); ptr = 0; } +#define YAKE_SAFE_DELETE(ptr) if(ptr) { delete ptr; ptr = 0; } +#define YAKE_SAFE_DELETE_ARRAY(ptr_array) if(ptr_array) { delete [] ptr_array; ptr_array = 0; } + +#define YAKE_DECLARE_CLASS(name) static const char * yake_private_currentClass() { return #name; } +#define YAKE_DECLARE_GLOBAL YAKE_DECLARE_CLASS( global ) +#define YAKE_DECLARE_FUNCTION(name) static const char * yake_private_currentFunction = #name "()"; + +#define YAKE_FOR_EACH(ITER_TYPE,ITER_NAME,CTR) \ + for (ITER_TYPE ITER_NAME = CTR.begin(); ITER_NAME != CTR.end(); ++ITER_NAME) + + +#ifdef YAKE_DEBUG +# define YAKE_DYNLIB_POSTFIX "_d" +#else +# define YAKE_DYNLIB_POSTFIX +#endif +#define YAKE_DYNLIB_NAME(X) \ + yake::String("yake_" X YAKE_DYNLIB_POSTFIX).c_str() + +#endif // YAKE_BASE_PREREQUISITES_H This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-03-12 23:11:21
|
Revision: 1632 http://svn.sourceforge.net/yake/?rev=1632&view=rev Author: psyclonist Date: 2007-03-12 16:11:20 -0700 (Mon, 12 Mar 2007) Log Message: ----------- adjusted scripting demo 1, support post build commands in premake 3.3, catch exceptions in scriptingLua, remove an irritating define _ in define LIBRARY_EXTENSION Modified Paths: -------------- trunk/yake/samples/README.TXT trunk/yake/samples/base/scripting/lua/yakeDemo.cpp trunk/yake/scripts/premake/config.lua trunk/yake/scripts/premake/samples.lua trunk/yake/scripts/premake/tools.lua trunk/yake/scripts/premake/yake.lua trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp trunk/yake/yake/base/prerequisites/yakePrerequisitesGCC.h trunk/yake/yake/base/prerequisites/yakePrerequisitesGCCWin.h trunk/yake/yake/base/prerequisites/yakePrerequisitesVC.h trunk/yake/yake/samples/common/configs.h Removed Paths: ------------- trunk/yake/yake/base/yakePrerequisites.h Modified: trunk/yake/samples/README.TXT =================================================================== --- trunk/yake/samples/README.TXT 2007-03-12 21:03:25 UTC (rev 1631) +++ trunk/yake/samples/README.TXT 2007-03-12 23:11:20 UTC (rev 1632) @@ -13,6 +13,7 @@ ent/sampleEntFsm - entity scripting physics/demo - basic physics demo (multiple viewports, simplistic objects) vehicle - different vehicles can be controlled (car,jet, uses RAF, entities and models) +base/scripting/lua - basic scripting demo ---- in flux: (i.e. in process of being added to the main build scripts) Modified: trunk/yake/samples/base/scripting/lua/yakeDemo.cpp =================================================================== --- trunk/yake/samples/base/scripting/lua/yakeDemo.cpp 2007-03-12 21:03:25 UTC (rev 1631) +++ trunk/yake/samples/base/scripting/lua/yakeDemo.cpp 2007-03-12 23:11:20 UTC (rev 1632) @@ -4,72 +4,63 @@ //** //**************************************************************************** -//============================================================================ -// IMPLEMENTATION HEADERS -//============================================================================ // Yake #include <yake/base/yake.h> -#include <yake/samples/common/yakeExampleApplication.h> +#include <yake/scripting/yakeScriptingSystem.h> +#include <yake/bindings.lua/bindings.lua.h> -//============================================================================ -// INTERFACE STRUCTURES / UTILITY CLASSES -//============================================================================ -using namespace yake::base::templates; -using namespace yake::scripting; +using namespace yake; // We don't expect collisions. -//============================================================================ -// Application -//============================================================================ +SharedPtr<base::Library> loadLib( const String & file ) +{ + SharedPtr<base::Library> pDynLib( new base::Library( file ) ); + YAKE_ASSERT( pDynLib ).debug( "Out of memory." ); + return pDynLib; +} -class TheApp : public yake::exapp::ExampleApplication +int main() { -public: - TheApp() : ExampleApplication( false, false, true, false, true, false ) + try { - } - virtual void run() - { - yake::scripting::IVM* pVM = getScriptingSystem().createVM(); - YAKE_ASSERT( pVM ); + SharedPtr<base::Library> lib = loadLib(YAKE_DYNLIB_NAME("scriptingLua")); + YAKE_ASSERT( lib ).debug("Cannot load Lua scripting plugin."); - getScriptingBindings().bind( pVM ); + SharedPtr<base::Library> binderLib = loadLib(YAKE_DYNLIB_NAME("bindings.lua")); + YAKE_ASSERT( binderLib ).debug("Cannot load Lua bindings."); + SharedPtr<scripting::IScriptingSystem> scriptingSys = templates::create_default<scripting::IScriptingSystem>(); + SharedPtr<scripting::IScriptingSystem> scriptingBindings = templates::create_default<scripting::IScriptingSystem>(); + + SharedPtr<scripting::IVM> vm( scriptingSys->createVM() ); + YAKE_ASSERT( vm ); + + bind_all( vm.get() ); + // This prints 'hello from lua scripting ;)' to stdout using // the Lua function print(). - pVM->execute("print('hello from lua scripting ;)');"); + vm->execute("print('hello from lua scripting ;)');"); // Execute a script created from a file. - yake::scripting::IScript* pScript = getScriptingSystem().createScriptFromFile("../../media/samples/scriptingLua/test.lua"); - pVM->execute( pScript ); - delete pScript; + { + SharedPtr<scripting::IScript> script( scriptingSys->createScriptFromFile("../../../common/media/samples/scriptingLua/test.lua") ); + YAKE_ASSERT( script ); + vm->execute( script.get() ); + } - delete pVM; + vm.reset(); + binderLib.reset(); + lib.reset(); } -}; - -//============================================================================ -// IMPLEMENTATION FUNCTIONS -//============================================================================ - -int main() -{ - try - { - TheApp theApp; - theApp.initialise(); - theApp.run(); - -#if defined( YAKE_DEBUG_BUILD ) - std::cout << std::endl << "Waiting for you..."; - std::cin.get(); -#endif - } catch ( yake::Exception & e ) { std::cout << "YAKE EXCEPTION: " << e.getSource() << std::endl; std::cout << "File: " << e.getFile() << " @ " << e.getLine() << std::endl; std::cout << "Reason: " << e.getMessage() << std::endl << std::endl; } +#if defined( YAKE_DEBUG_BUILD ) + std::cout << std::endl << "Waiting for you..."; + std::cin.get(); +#endif return 0; } Modified: trunk/yake/scripts/premake/config.lua =================================================================== --- trunk/yake/scripts/premake/config.lua 2007-03-12 21:03:25 UTC (rev 1631) +++ trunk/yake/scripts/premake/config.lua 2007-03-12 23:11:20 UTC (rev 1632) @@ -16,6 +16,12 @@ LIBFILE_PREFIX = "yake_" EXEFILE_SUFFIX = "" +if windows then + DLL_EXTENSION = "dll" +else + DLL_EXTENSION = "so" +end + -------------------------------------- -- Plugins -------------------------------------- Modified: trunk/yake/scripts/premake/samples.lua =================================================================== --- trunk/yake/scripts/premake/samples.lua 2007-03-12 21:03:25 UTC (rev 1631) +++ trunk/yake/scripts/premake/samples.lua 2007-03-12 23:11:20 UTC (rev 1632) @@ -119,3 +119,9 @@ useComponent("netsvc") addIncludePath("dependencies/boost") addMatching("samples/net/roclient/roclient*") + +-------------------------------------- +makeSample("sampleScripting1","samples/base/scripting/lua") +useComponent("base") +useComponent("scripting") +useComponent("bindings.lua") Modified: trunk/yake/scripts/premake/tools.lua =================================================================== --- trunk/yake/scripts/premake/tools.lua 2007-03-12 21:03:25 UTC (rev 1631) +++ trunk/yake/scripts/premake/tools.lua 2007-03-12 23:11:20 UTC (rev 1632) @@ -33,6 +33,18 @@ tinsert(package.libpaths,rootdir..path) end end +function addPostBuildCommand(cmd) + if (cmd) then + tinsert(package.postbuildcommands,cmd) + end +end +function addPostBuildCopy(args) + if windows then + return "copy " .. args + else + return "cp " .. args + end +end function makeLibProject(name) project.name = name @@ -75,7 +87,7 @@ package.buildflags = {} package.includepaths = {rootdir} package.defines = {} - + if (windows) then addDefine("_CRT_SECURE_NO_DEPRECATE") addDefine("WIN32") @@ -90,6 +102,11 @@ debug.target = targetBaseDir.."debug/"..(LIBFILE_PREFIX)..name..(DEBUG_DLL_SUFFIX) debug.defines = {"_DEBUG"} debug.buildflags = {} + if windows then + local args = debug.target .. "." .. DLL_EXTENSION .. " " .. rootdir .. "samples/bin/debug" + args = string.gsub(args,"/","\\") + debug.postbuildcommands = {"copy /Y " .. args} + end releaseWithSym = package.config.ReleaseWithSymbols releaseWithSym.target = targetBaseDir.."release_sym/"..(LIBFILE_PREFIX)..name.."_sym" @@ -106,6 +123,11 @@ "optimize-speed", "no-frame-pointer" } + if windows then + local args = release.target .. "." .. DLL_EXTENSION .. " " .. rootdir .. "samples/bin/release" + args = string.gsub(args,"/","\\") + release.postbuildcommands = {"copy /Y " .. args} + end debugLib = package.config.DebugLib debugLib.kind = "lib" Modified: trunk/yake/scripts/premake/yake.lua =================================================================== --- trunk/yake/scripts/premake/yake.lua 2007-03-12 21:03:25 UTC (rev 1631) +++ trunk/yake/scripts/premake/yake.lua 2007-03-12 23:11:20 UTC (rev 1632) @@ -46,6 +46,7 @@ f:write("#define YAKE_DEBUG_DLL_SUFFIX \"" .. DEBUG_DLL_SUFFIX .. "\"\n") f:write("#define YAKE_LIBFILE_PREFIX \"" .. LIBFILE_PREFIX .. "\"\n") f:write("#define YAKE_LUA_BINDINGS " .. bool_to_int(LUA_BINDINGS) .. "\n") + f:write("#define YAKE_ENABLE_LUA_BASE " .. bool_to_int(ENABLE_LUA_BASE) .. "\n") f:write("#define YAKE_ENABLE_LUA_ENT " .. bool_to_int(ENABLE_LUA_ENT) .. "\n") f:write("#define YAKE_ENABLE_LUA_MODEL " .. bool_to_int(ENABLE_LUA_MODEL) .. "\n") f:write("#define YAKE_ENABLE_LUA_TASK " .. bool_to_int(ENABLE_LUA_TASK) .. "\n") Modified: trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp =================================================================== --- trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp 2007-03-12 21:03:25 UTC (rev 1631) +++ trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp 2007-03-12 23:11:20 UTC (rev 1632) @@ -81,24 +81,56 @@ //------------------------------------------------------ void LuaVM::execute( const String & rData ) { - if (mLuaState) - luaL_dostring( mLuaState, rData.c_str() ); + try { + if (mLuaState) + luaL_dostring( mLuaState, rData.c_str() ); + } + catch (luabind::error& e) + { + throw Exception(String("LuaVM: caught Luabind error") + e.what()); + } + catch (luabind::cast_failed& e) + { + throw Exception(String("LuaVM: caught Luabind cast_failed") + e.what()); + } + catch (std::exception& e) + { + throw Exception(String("LuaVM: caught exception: ") + e.what()); + } } //------------------------------------------------------ void LuaVM::execute( scripting::IScript* pScript ) { - if ( ( pScript->getCreator()->getLanguage() != scripting::IScriptingSystem::L_LUA ) || - ( 0 == mLuaState ) ) - return; + try { + if ( ( pScript->getCreator()->getLanguage() != scripting::IScriptingSystem::L_LUA ) || + ( 0 == mLuaState ) ) + return; - LuaScript* pLuaScript = static_cast< LuaScript* > ( pScript ); + LuaScript* pLuaScript = static_cast< LuaScript* > ( pScript ); - const String& rFileName = pLuaScript->getData(); + const String& rFileName = pLuaScript->getData(); - const int err = luaL_dofile( mLuaState, rFileName.c_str() ); - if (err) - YAKE_EXCEPT("Failed to execute script! (Does file exist?)"); + const int err = luaL_dofile( mLuaState, rFileName.c_str() ); + if (err) + YAKE_EXCEPT("Failed to execute script! (Does file exist?)"); + } + catch (luabind::error& e) + { + throw Exception(String("LuaVM: caught Luabind error") + e.what()); + } + catch (luabind::cast_failed& e) + { + throw Exception(String("LuaVM: caught Luabind cast_failed") + e.what()); + } + catch (Exception& e) + { + throw; + } + catch (std::exception& e) + { + throw Exception(String("LuaVM: caught exception: ") + e.what()); + } } //------------------------------------------------------ Modified: trunk/yake/yake/base/prerequisites/yakePrerequisitesGCC.h =================================================================== --- trunk/yake/yake/base/prerequisites/yakePrerequisitesGCC.h 2007-03-12 21:03:25 UTC (rev 1631) +++ trunk/yake/yake/base/prerequisites/yakePrerequisitesGCC.h 2007-03-12 23:11:20 UTC (rev 1632) @@ -102,7 +102,7 @@ #define DLLEXPORT #define DLLIMPORT -#define LIBRARY_EXTENSION _( "so" ) +#define LIBRARY_EXTENSION ( "so" ) #ifdef _DEBUG # define YAKE_DEBUG_BUILD Modified: trunk/yake/yake/base/prerequisites/yakePrerequisitesGCCWin.h =================================================================== --- trunk/yake/yake/base/prerequisites/yakePrerequisitesGCCWin.h 2007-03-12 21:03:25 UTC (rev 1631) +++ trunk/yake/yake/base/prerequisites/yakePrerequisitesGCCWin.h 2007-03-12 23:11:20 UTC (rev 1632) @@ -92,7 +92,7 @@ #define DLLEXPORT #define DLLIMPORT -#define LIBRARY_EXTENSION _( "so" ) +#define LIBRARY_EXTENSION ( "so" ) #ifdef _DEBUG # define YAKE_DEBUG_BUILD Modified: trunk/yake/yake/base/prerequisites/yakePrerequisitesVC.h =================================================================== --- trunk/yake/yake/base/prerequisites/yakePrerequisitesVC.h 2007-03-12 21:03:25 UTC (rev 1631) +++ trunk/yake/yake/base/prerequisites/yakePrerequisitesVC.h 2007-03-12 23:11:20 UTC (rev 1632) @@ -71,8 +71,9 @@ #define DLLEXPORT __declspec( dllexport ) #define DLLIMPORT __declspec( dllimport ) -#define LIBRARY_EXTENSION _( "dll" ) +#define LIBRARY_EXTENSION ( "dll" ) + #ifdef _DEBUG # define YAKE_DEBUG_BUILD #endif Deleted: trunk/yake/yake/base/yakePrerequisites.h =================================================================== --- trunk/yake/yake/base/yakePrerequisites.h 2007-03-12 21:03:25 UTC (rev 1631) +++ trunk/yake/yake/base/yakePrerequisites.h 2007-03-12 23:11:20 UTC (rev 1632) @@ -1,162 +0,0 @@ -/* - ------------------------------------------------------------------------------------ - This file is part of YAKE - Copyright \xA9 2004 The YAKE Team - For the latest information visit http://www.yake.org - ------------------------------------------------------------------------------------ - This program is free software; you can redistribute it and/or modify it under - the terms of the GNU Lesser General Public License as published by the Free Software - Foundation; either version 2 of the License, or (at your option) any later - version. - - This program is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License along with - this program; if not, write to the Free Software Foundation, Inc., 59 Temple - Place - Suite 330, Boston, MA 02111-1307, USA, or go to - http://www.gnu.org/copyleft/lesser.txt. - ------------------------------------------------------------------------------------ - If you are interested in another license model contact the Yake Team via - E-Mail: te...@ya.... - For more information see the LICENSE file in the root directory of the - source code distribution. - ------------------------------------------------------------------------------------ -*/ -#ifndef YAKE_BASE_PREREQUISITES_H -#define YAKE_BASE_PREREQUISITES_H - -//============================================================================ -// IMPLEMENTATION HEADERS -//=========================================================================== -#include <yake/config.h> -#include <yake/base/yakePlatform.h> -#include <assert.h> -#include <ctime> -#include <math.h> -#include <cmath> -// Undef min and max macros on Windows. They're defined in windef.h. -#if (YAKE_PLATFORM == PLATFORM_WIN32) - #ifdef min - #undef min - #endif - #ifdef max - #undef max - #endif -#endif -#include <limits> -#include <cstdio> -#include <stdio.h> -#include <stdarg.h> -#include <string> -#include <stdexcept> -#include <locale> -#include <algorithm> -#include <functional> -#include <vector> -#include <map> -#include <list> -#include <queue> -#include <set> -#include <iostream> -#include <sstream> - -#ifdef __SGI_STL -# include <iterator> -#endif - -// Include platform specific configuration files -#if (YAKE_PLATFORM == PLATFORM_WIN32) && (YAKE_COMPILER == COMPILER_MSVC) -# include <yake/base/prerequisites/yakePrerequisitesVC.h> -#elif (YAKE_PLATFORM == PLATFORM_WIN32) && (YAKE_COMPILER == COMPILER_GNUC) -# include <yake/base/prerequisites/yakePrerequisitesGCCWin.h> -#elif (YAKE_PLATFORM == PLATFORM_LINUX) && (YAKE_COMPILER == COMPILER_GNUC) -# include <yake/base/prerequisites/yakePrerequisitesGCC.h> -#else -# error("Yake: No configuration file set for the selected platform/compiler!") -#endif - -//============================================================================ -// INTERFACE STRUCTURES / UTILITY CLASSES -//============================================================================ -// Yake - -// YAKE_BASE_API -#if defined( YAKE_BASE_EXPORTS ) -# define YAKE_BASE_API DLLEXPORT -#else -# define YAKE_BASE_API DLLIMPORT -#endif - -// YAKE_DEBUG -#if defined(_DEBUG) || defined(DEBUG) -# define YAKE_DEBUG -#endif - -// YAKE_UNICODE: Not supported at the moment! -//#define YAKE_UNICODE - -#if defined(YAKE_UNICODE) -# define __T(X) L ## X -#else -# define __T(X) X -#endif - -// _T(X) Macro for defining strings ( -#define _T(X) __T(X) - -// STL -#if defined(YAKE_DEBUG_BUILD) -//# define _STLP_DEBUG 1 -#endif -#define _STLP_USE_DYNAMIC_LIB - -// Boost / TTL -#if (YAKE_PLATFORM == PLATFORM_WIN32) && (YAKE_COMPILER == COMPILER_GNUC) - #define YAKE_SIGNALS_USE_BOOST -#else - #define YAKE_SIGNALS_USE_BOOST - //#define YAKE_SIGNALS_USE_TTL -#endif - -// YAKE_REAL_PRECISION -// Determines the type used for 'real'. -// YAKE_REAL_SINGLE_PRECISION = float -// YAKE_REAL_DOUBLE_PRECISION = double -//@todo move this into configuration header -#define YAKE_REAL_SINGLE_PRECISION 1 -#define YAKE_REAL_DOUBLE_PRECISION 2 -#define YAKE_REAL_PRECISION YAKE_REAL_SINGLE_PRECISION -#if YAKE_REAL_PRECISION == YAKE_REAL_SINGLE_PRECISION - typedef float real; -#elif YAKE_REAL_PRECISION == YAKE_REAL_DOUBLE_PRECISION - typedef double real; -#else -# pragma error("yake: Unknown type for 'real'!") -#endif - - -// Helper macros -// todo: remove, deprecated, use safe_delete(_array) -#define YAKE_SAFE_RELEASE(ptr) if(ptr) { ptr->release(); ptr = 0; } -#define YAKE_SAFE_DELETE(ptr) if(ptr) { delete ptr; ptr = 0; } -#define YAKE_SAFE_DELETE_ARRAY(ptr_array) if(ptr_array) { delete [] ptr_array; ptr_array = 0; } - -#define YAKE_DECLARE_CLASS(name) static const char * yake_private_currentClass() { return #name; } -#define YAKE_DECLARE_GLOBAL YAKE_DECLARE_CLASS( global ) -#define YAKE_DECLARE_FUNCTION(name) static const char * yake_private_currentFunction = #name "()"; - -#define YAKE_FOR_EACH(ITER_TYPE,ITER_NAME,CTR) \ - for (ITER_TYPE ITER_NAME = CTR.begin(); ITER_NAME != CTR.end(); ++ITER_NAME) - - -#ifdef YAKE_DEBUG -# define YAKE_DYNLIB_POSTFIX "_d" -#else -# define YAKE_DYNLIB_POSTFIX -#endif -#define YAKE_DYNLIB_NAME(X) \ - yake::String("yake_" X YAKE_DYNLIB_POSTFIX).c_str() - -#endif // YAKE_BASE_PREREQUISITES_H Modified: trunk/yake/yake/samples/common/configs.h =================================================================== --- trunk/yake/yake/samples/common/configs.h 2007-03-12 21:03:25 UTC (rev 1631) +++ trunk/yake/yake/samples/common/configs.h 2007-03-12 23:11:20 UTC (rev 1632) @@ -53,7 +53,7 @@ { typedef minimum_config config; - // todo: base::native::Load_Library should add YAKE_DLL_POSTFIX (".dll" and the linux equivalent) to the library name + // todo: base::native::Load_Library should add YAKE_DYNLIB_POSTFIX (".dll" and the linux equivalent) to the library name static std::vector<std::string> get_libraries() { return libraries() << "graphicsOGRE.dll"; } }; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-03-12 21:03:27
|
Revision: 1631 http://svn.sourceforge.net/yake/?rev=1631&view=rev Author: psyclonist Date: 2007-03-12 14:03:25 -0700 (Mon, 12 Mar 2007) Log Message: ----------- Modified Paths: -------------- trunk/yake/samples/README.TXT Modified: trunk/yake/samples/README.TXT =================================================================== --- trunk/yake/samples/README.TXT 2007-03-12 21:01:27 UTC (rev 1630) +++ trunk/yake/samples/README.TXT 2007-03-12 21:03:25 UTC (rev 1631) @@ -12,13 +12,13 @@ raf/demo1 - initialisation of graphics and creation of a very basic scene ent/sampleEntFsm - entity scripting physics/demo - basic physics demo (multiple viewports, simplistic objects) +vehicle - different vehicles can be controlled (car,jet, uses RAF, entities and models) ---- in flux: (i.e. in process of being added to the main build scripts) debug scripted_entity custom_entity -vehicle1 sync1 dotlink fsm @@ -29,7 +29,6 @@ sampleScriptedEntity - scripting entities (callbacks, states, events and more) sampleCustomEntity - how to implement a new entity -sampleVehicle1 - different vehicles can be controlled (car,jet, uses RAF, entities and models) sampleSync1 - decoupled, interpolated physics and graphics systems sampleDotLink - how to tie .link, .scene and .xode together sampleFSM - simple finite state machine demo This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-03-12 21:01:29
|
Revision: 1630 http://svn.sourceforge.net/yake/?rev=1630&view=rev Author: psyclonist Date: 2007-03-12 14:01:27 -0700 (Mon, 12 Mar 2007) Log Message: ----------- added library 'task', refactored Lua binding organisation, improved premake based build scripts, various fixes Modified Paths: -------------- trunk/yake/scripts/msvc80/build.cmd trunk/yake/scripts/premake/config.lua trunk/yake/scripts/premake/plugins.lua trunk/yake/scripts/premake/samples.lua trunk/yake/scripts/premake/yake.lua trunk/yake/src/ent/object_mgr.cpp trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp trunk/yake/yake/base/yakePrerequisites.h trunk/yake/yake/ent/object_mgr.h trunk/yake/yake/physics/yakePhysicsPrerequisites.h trunk/yake/yake/physics/yakePhysicsShape.h trunk/yake/yake/scripting/yakeScriptingSystem.h Added Paths: ----------- trunk/yake/src/bindings.lua/ trunk/yake/src/bindings.lua/bindings.lua.cpp trunk/yake/src/bindings.lua/detail/ trunk/yake/src/bindings.lua/detail/base.lua.cpp trunk/yake/src/bindings.lua/detail/ent.lua.cpp trunk/yake/src/bindings.lua/detail/model.lua.cpp trunk/yake/src/bindings.lua/detail/task.lua.cpp trunk/yake/src/task/ trunk/yake/src/task/executor.cpp trunk/yake/src/task/task.cpp trunk/yake/yake/bindings.lua/ trunk/yake/yake/bindings.lua/bindings.lua.ent.h trunk/yake/yake/bindings.lua/bindings.lua.h trunk/yake/yake/bindings.lua/common/ trunk/yake/yake/bindings.lua/common/lua.helpers.cpp trunk/yake/yake/bindings.lua/common/lua.helpers.h trunk/yake/yake/bindings.lua/common/vminfo.lua.cpp trunk/yake/yake/bindings.lua/common/vminfo.lua.h trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h trunk/yake/yake/bindings.lua/common/yake.lua.common.h trunk/yake/yake/bindings.lua/common/yake.lua.shared_ptr.h trunk/yake/yake/bindings.lua/detail/ trunk/yake/yake/bindings.lua/detail/private.h trunk/yake/yake/bindings.lua/prerequisites.h trunk/yake/yake/task/ trunk/yake/yake/task/prerequisites.h trunk/yake/yake/task/task.h Modified: trunk/yake/scripts/msvc80/build.cmd =================================================================== --- trunk/yake/scripts/msvc80/build.cmd 2007-03-12 20:59:12 UTC (rev 1629) +++ trunk/yake/scripts/msvc80/build.cmd 2007-03-12 21:01:27 UTC (rev 1630) @@ -1,7 +1,12 @@ @echo off pushd ..\premake +if not exist premake.exe ( + echo warning: premake.exe not found in yake/scripts/premake. + echo This file is expected to be found in yake/scripts/premake or in global path. +) setlocal set SOLUTION_TARGET_DIR=msvc80 premake --file yake.lua --target vs2005 popd -pause + +pause \ No newline at end of file Modified: trunk/yake/scripts/premake/config.lua =================================================================== --- trunk/yake/scripts/premake/config.lua 2007-03-12 20:59:12 UTC (rev 1629) +++ trunk/yake/scripts/premake/config.lua 2007-03-12 21:01:27 UTC (rev 1630) @@ -21,6 +21,7 @@ -------------------------------------- -- !! UNUSED FOR NOW !! +--PLUGIN_SCRIPTING_LUA = true PLUGIN_AUDIO_OPENAL = true PLUGIN_GRAPHICS_OGRE = true PLUGIN_PHYSICS_ODE = true @@ -28,6 +29,21 @@ --GRAPHICSOGRE_USES_OSM = true +-- If set to true then the ENABLE_LUA_* settings are used. +-- If set to false then the ENABLE_LUA_* settings are ignored. +LUA_BINDINGS = true + +-- Enable/disable specific yake-lua bindings. +-- This only affects the code generation, not what actually gets +-- bound to a specific virtual machine instance! +-- For example, if you do *not* use yake::model then you can disable +-- the compilation of the binding code for this component and thereby +-- save compilation time. +ENABLE_LUA_BASE = true -- includes 'base' and 'math' binders +ENABLE_LUA_ENT = true -- 'ent' binder +ENABLE_LUA_MODEL = true -- 'model' binder +ENABLE_LUA_TASK = true -- 'task' binder (+executor) + -------------------------------------- -- Samples -------------------------------------- Modified: trunk/yake/scripts/premake/plugins.lua =================================================================== --- trunk/yake/scripts/premake/plugins.lua 2007-03-12 20:59:12 UTC (rev 1629) +++ trunk/yake/scripts/premake/plugins.lua 2007-03-12 21:01:27 UTC (rev 1630) @@ -1,39 +1,39 @@ -------------------------------------- -- YAKE build file make script -------------------------------------- - -function addPkgConfigLib(package,lib) - local pkgexists = os.execute("pkg-config --exists "..lib) - print(pkgexists..lib) - if options.target == gnu and pkgexists then - local flags = os.execute("pkg-config --cflags "..lib) - print("flags "..flags) - local cflags = "`pkg-config --cflags " - if not cflags then - print("ERROR: Failed to acquire cflags for library '" .. lib .. "'!") - end - table.insert(package.buildoptions,"`pkg-config --cflags "..lib) - table.insert(package.linkoptions,"`pkg-config --libs "..lib) - else - local path = findlib(lib); - if not path then - print("ERROR: Failed to find library '" .. lib .. "'!") - end - print(path) - table.insert(package.linkoptions,path.."/"..lib) - end -end +function addPkgConfigLib(package,lib) + local pkgexists = os.execute("pkg-config --exists "..lib) + print(pkgexists..lib) + if options.target == gnu and pkgexists then + local flags = os.execute("pkg-config --cflags "..lib) + print("flags "..flags) + local cflags = "`pkg-config --cflags " + if not cflags then + print("ERROR: Failed to acquire cflags for library '" .. lib .. "'!") + end + table.insert(package.buildoptions,"`pkg-config --cflags "..lib) + table.insert(package.linkoptions,"`pkg-config --libs "..lib) + else + local path = findlib(lib); + if not path then + print("ERROR: Failed to find library '" .. lib .. "'!") + end + print(path) + table.insert(package.linkoptions,path.."/"..lib) + end +end + -------------------------------------- makeComponentPlugin("audioOpenAL","YAKE_AUDIO_OPENAL_EXPORTS") addDependency("base") addDependency("audio") - -if (windows) then - useDep("oalpp") -else - addPkgConfigLib(package,"libopenalpp.so") - --addPkgConfigLib(package,"openalpp") --@todo Why does this not pick up the correct lib to link to? + +if (windows) then + useDep("oalpp") +else + addPkgConfigLib(package,"libopenalpp.so") + --addPkgConfigLib(package,"openalpp") --@todo Why does this not pick up the correct lib to link to? end addIncludePath("dependencies/openalpp/include") @@ -41,12 +41,12 @@ makeComponentPlugin("scriptingLua","YAKE_SCRIPTINGLUA_EXPORTS") addDependency("base") addDependency("scripting") - + if (windows) then useDep("lua") - useDep("luabind") -else - addPkgConfigLib(package,"liblua50.so.5") + useDep("luabind") +else + addPkgConfigLib(package,"liblua50.so.5") end -------------------------------------- @@ -57,34 +57,6 @@ useDep("ode") -------------------------------------- -makeComponentPlugin("entLua","YAKE_ENTLUA_EXPORTS") -addDependency("base") -addDependency("ent") -addDependency("scripting") -addDependency("scriptingLua") - -if (windows) then - useDep("lua") - useDep("luabind") -else - addPkgConfigLib(package,"liblua50.so.5") -end - --------------------------------------- -makeComponentPlugin("modelLua","YAKE_MODELLUA_EXPORTS") -addDependency("base") -addDependency("model") -addDependency("scripting") -addDependency("scriptingLua") - -if (windows) then - useDep("lua") - useDep("luabind") -else - addPkgConfigLib(package,"liblua50.so.5") -end - --------------------------------------- makeComponentPlugin("ceguiOgreRendererAdapter","YAKE_CEGUIRENDERERADAPTER_OGRE_EXPORTS") addDependency("base") addDependency("graphics") Modified: trunk/yake/scripts/premake/samples.lua =================================================================== --- trunk/yake/scripts/premake/samples.lua 2007-03-12 20:59:12 UTC (rev 1629) +++ trunk/yake/scripts/premake/samples.lua 2007-03-12 21:01:27 UTC (rev 1630) @@ -103,3 +103,19 @@ addIncludePath("dependencies/boost") addMatching("samples/net/roclient/roclient*") addMatching("samples/net/roserver/roserver*") + +-------------------------------------- +makeSample("sampleNetCommServer","samples/net/commserver") +useComponent("base") +useComponent("net") +useComponent("netsvc") +addIncludePath("dependencies/boost") +addMatching("samples/net/roserver/roserver*") + +-------------------------------------- +makeSample("sampleNetCommClient","samples/net/commclient") +useComponent("base") +useComponent("net") +useComponent("netsvc") +addIncludePath("dependencies/boost") +addMatching("samples/net/roclient/roclient*") Modified: trunk/yake/scripts/premake/yake.lua =================================================================== --- trunk/yake/scripts/premake/yake.lua 2007-03-12 20:59:12 UTC (rev 1629) +++ trunk/yake/scripts/premake/yake.lua 2007-03-12 21:01:27 UTC (rev 1630) @@ -22,6 +22,43 @@ dofile("deps.lua") -------------------------------------- +-- create config.h +-------------------------------------- +function bool_to_int(var) + if var then + return 1 + else + return 0 + end +end +function make_config_h() + local filename = rootdir.."yake/config.h" + local f = io.open(filename, "w") + if not f then + print("ERROR: Unable to create [yake]/yake/config.h") + return false + end + f:write("// This file is auto-generated. Do not modify manually.\n") + f:write("\n") + f:write("#ifndef YAKE_CONFIG_H\n") + f:write("#define YAKE_CONFIG_H\n") + f:write("\n") + f:write("#define YAKE_DEBUG_DLL_SUFFIX \"" .. DEBUG_DLL_SUFFIX .. "\"\n") + f:write("#define YAKE_LIBFILE_PREFIX \"" .. LIBFILE_PREFIX .. "\"\n") + f:write("#define YAKE_LUA_BINDINGS " .. bool_to_int(LUA_BINDINGS) .. "\n") + f:write("#define YAKE_ENABLE_LUA_ENT " .. bool_to_int(ENABLE_LUA_ENT) .. "\n") + f:write("#define YAKE_ENABLE_LUA_MODEL " .. bool_to_int(ENABLE_LUA_MODEL) .. "\n") + f:write("#define YAKE_ENABLE_LUA_TASK " .. bool_to_int(ENABLE_LUA_TASK) .. "\n") + f:write("\n") + f:write("#endif\n") + io.close(f) + return true +end +if not make_config_h() then + return 2 +end + +-------------------------------------- -- create packages -------------------------------------- @@ -146,6 +183,32 @@ --addDependency("base") -------------------------------------- +makeComponent("task","YAKE_TASK_EXPORTS") +addDependency("base") + +-------------------------------------- +if LUA_BINDINGS then + makeComponent("bindings.lua","YAKE_BINDINGS_LUA_EXPORTS") + addDependency("base") + addDependency("scripting") + addDependency("scriptingLua") + if ENABLE_LUA_ENT then + addDependency("ent") + addDependency("model") + end + if ENABLE_LUA_MODEL then + addDependency("model") + end + if ENABLE_LUA_TASK then + addDependency("task") + end + if (windows) then + useDep("lua") + useDep("luabind") + end +end + +-------------------------------------- -- create plugins -------------------------------------- dofile("plugins.lua") Added: trunk/yake/src/bindings.lua/bindings.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/bindings.lua.cpp (rev 0) +++ trunk/yake/src/bindings.lua/bindings.lua.cpp 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,49 @@ +#include <yake/base/templates/yakeSmartAssert.h> +#include <yake/scripting/yakeScriptingSystem.h> +#include <yake/plugins/scriptingLua/ScriptingSystemLua.h> +#include <yake/bindings.lua/bindings.lua.h> +#include <yake/bindings.lua/common/yake.lua.common.h> + +#include <yake/bindings.lua/common/lua.helpers.h> +#include <yake/bindings.lua/common/lua.helpers.cpp> // define here + +#define YAKE_EXPORT_LUA_ANY_CONVERTER +#include <yake/bindings.lua/common/yake.lua.any_converter.h> +#include <yake/bindings.lua/common/yake.lua.any_converter.cpp> + +namespace yake { + void bind_all(lua_State* L) + { + YAKE_ASSERT( L ); + + // + register_any_converter<int>(); + register_any_converter<float>(); + register_any_converter<double>(); + register_any_converter<bool>(); + register_any_converter<String>(); + + // + +#if YAKE_ENABLE_LUA_BASE == 1 + bind_base(L); + bind_math(L); +#endif +#if YAKE_ENABLE_LUA_TASK == 1 + bind_task(L); +#endif +#if YAKE_ENABLE_LUA_MODEL == 1 + bind_model(L); +#endif +#if YAKE_ENABLE_LUA_ENT == 1 + bind_ent(L); +#endif + } + void bind_all(scripting::IVM* vm) + { + scripting::LuaVM* luavm = static_cast<scripting::LuaVM*>(vm); + YAKE_ASSERT( luavm ); + if (luavm) + bind_all(luavm->getLuaState()); + } +} // namespace yake Added: trunk/yake/src/bindings.lua/detail/base.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/base.lua.cpp (rev 0) +++ trunk/yake/src/bindings.lua/detail/base.lua.cpp 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,255 @@ +#include <yake/config.h> +#if YAKE_ENABLE_LUA_BASE == 1 + +#include <yake/base/yake.h> + +#include <yake/bindings.lua/detail/private.h> +#include <yake/bindings.lua/common/lua.helpers.h> +#include <yake/bindings.lua/common/vminfo.lua.h> +#include <yake/bindings.lua/common/yake.lua.shared_ptr.h> +#include <yake/bindings.lua/common/yake.lua.any_converter.h> + +namespace yake { +namespace math { + + void bind(lua_State* L) + { + YAKE_ASSERT(L); + if (!L) + return; + + using namespace luabind; +#define YAKE_MATH_MODULE L, "yake" + + ///TODO Bind most common operators! + + module( YAKE_MATH_MODULE ) + [ + class_<Color>("Color") + .def( constructor<>() ) + .def( constructor<real,real,real,real>() ) + .def( constructor< const Color& >() ) + //FIXME some strange members in anonymous union::struct + /* .def_readwrite( "r", &Color::r ) + .def_readwrite( "g", &Color::g ) + .def_readwrite( "b", &Color::b ) + .def_readwrite( "a", &Color::a )*/ + ]; + + //TODO Bind the whole math::Math class + // Math + module( YAKE_MATH_MODULE ) + [ + class_< Math >( "Math" ) + .enum_( "AngleUnit" ) + [ + value( "AU_DEGREE", 0 ), + value( "AU_RADIAN", 1 ) + ] + .def( constructor< unsigned int >() ) + //,def( "IAbs", &yake::math::Math::IAbs ) + ]; + + // Vector3 + module( YAKE_MATH_MODULE ) + [ + class_< Vector3 >( "Vector3" ) + .def_readwrite( "x", &yake::math::Vector3::x ) + .def_readwrite( "y", &yake::math::Vector3::y ) + .def_readwrite( "z", &yake::math::Vector3::z ) + .def( constructor< real, real, real >() ) + .def( constructor< const real* const >() ) + .def( constructor< Vector3 const& >() ) + .def( "length", &yake::math::Vector3::length ) + .def( "normalise", &yake::math::Vector3::normalise ) + .def( "crossProduct", &yake::math::Vector3::crossProduct ) + .def( "dotProduct", &yake::math::Vector3::dotProduct ) + .def( "reflect", &yake::math::Vector3::reflect ) + .def( "perpendicular", &yake::math::Vector3::perpendicular ) + .def( "getRotationTo", &yake::math::Vector3::getRotationTo ) + ]; + + // Vector4 + module( YAKE_MATH_MODULE ) + [ + class_< Vector4 >( "Vector4" ) + .def( constructor<>() ) + .def( constructor< real, real, real, real >() ) + .def( constructor< const real* const >() ) + .def( constructor< Vector4 const& >() ) + ]; + + // Matrix3 + module( YAKE_MATH_MODULE ) + [ + class_< Matrix3 >( "Matrix3" ) + .def( constructor<>() ) + .def( constructor< Matrix3 const& >() ) + .def( "getColumn", &yake::math::Matrix3::GetColumn ) + ]; + + // Quaternion + module( YAKE_MATH_MODULE ) + [ + class_< Quaternion >( "Quaternion" ) + .def_readwrite( "x", &yake::math::Quaternion::x ) + .def_readwrite( "y", &yake::math::Quaternion::y ) + .def_readwrite( "z", &yake::math::Quaternion::z ) + .def_readwrite( "w", &yake::math::Quaternion::w ) + .def( constructor< real, real, real, real >() ) + .def( constructor< Quaternion const& >() ) + ]; + + // RandomNumberGenerator + typedef RandomNumberGenerator rng_type; + module( YAKE_MATH_MODULE ) + [ + class_< rng_type >( "RandomNumberGenerator" ) + .def( constructor<>() ) + .def( "setSeed", &rng_type::setSeed ) + .def( "getSeed", &rng_type::getSeed ) + .def( "randInt", &rng_type::randInt ) + .def( "randReal", &rng_type::randReal ) + ]; + } + + YAKE_WRAP_BINDER(math,::yake::math::bind); + +} // namespace math +namespace base { + + // short cuts: + + void lua_log_warning(const char* msg) + { + logging::log(logging::S_WARNING, "lua", msg); + } + void lua_log_information(const char* msg) + { + logging::log(logging::S_INFORMATION, "lua", msg); + } + void lua_log_error(const char* msg) + { + logging::log(logging::S_ERROR, "lua", msg); + } + + void bind(lua_State* L) + { + YAKE_ASSERT(L); + if (!L) + return; + + using namespace luabind; +#define YAKE_BASE_MODULE L, "yake" + + module( YAKE_BASE_MODULE ) + [ + class_<Movable>( "Movable" ) + .def( "setPosition", &Movable::setPosition ) + .def( "setOrientation", &Movable::setOrientation ) + .def( "getPosition", &Movable::getPosition ) + .def( "getOrientation", &Movable::getOrientation ) + .def( "translate", &Movable::translate ) + ]; + + module( YAKE_BASE_MODULE ) + [ + class_< Version >( "Version" ) + .def(constructor<uint16,uint16,uint16>()) + .def("getMajor", &yake::Version::getMajor) + .def("getMinor", &yake::Version::getMinor) + .def("getSub", &yake::Version::getSub) + ]; + + // Library + module( YAKE_BASE_MODULE ) + [ + class_< Library >( "Library" ) + .def( constructor< String const& >() ) + //.def( "getSymbol", &yake::base::Library::getSymbol ) + ]; + + // Timer + module( YAKE_BASE_MODULE ) + [ + //def("createTimer", &yake::base::timer::createTimer()) + class_< Timer >( "Timer" ) + .def( "reset", &yake::Timer::reset ) + .def( "getMilliseconds", &yake::Timer::getMilliseconds ) + .def( "getSeconds", &yake::Timer::getSeconds ) + ]; + + module( YAKE_BASE_MODULE ) + [ + //def( "createTimer", &yake::base::timer::createTimer ) + def( "getTime", &yake::native::getTime ) + ]; + + // Log + module( YAKE_BASE_MODULE ) + [ + class_< logging::logger >( "Log" ) + .enum_( "Severity" ) + [ + value( "EMERGENCY", 0 ), + value( "ALERT", 1 ), + value( "CRITICAL", 2 ), + value( "ERROR", 3 ), + value( "WARNING", 4 ), + value( "NOTICE", 5 ), + value( "INFORMATION", 6 ), + value( "DEBUG", 7 ) + ] + .scope + [ + def( "log", (void(*)(const logging::severity_t, const char* logId, const char* msg))&logging::logger::log ), + def( "enableLog", logging::enableLog ), + def( "enableSeverity", logging::enableSeverity ), + def( "setProcessId", logging::setProcessId ) + //def( "addTarget", logging::addTarget ) + ] + ]; + + // Exporting log singleton as logger object + //@todo FIXME pL->execute( "logger = yake.Log.instance();" ); + + // Log shortcuts + module( YAKE_BASE_MODULE ) + [ + def( "log_warning", &yake::base::lua_log_warning ), + def( "log_information", &yake::base::lua_log_information ), + def( "log_error", &yake::base::lua_log_error ) + ]; + + // Plugin + module( YAKE_BASE_MODULE ) + [ + class_< Plugin >( "Plugin" ) + .def( "getName", &yake::base::Plugin::getName ) + .def( "initialise", &yake::base::Plugin::initialise ) + .def( "shutdown", &yake::base::Plugin::shutdown ) + ]; + + // uniqueName::create + module( YAKE_BASE_MODULE ) + [ + def( "createUniqueName", &uniqueName::create ) + ]; + } + + YAKE_WRAP_BINDER(base,::yake::base::bind); + +} // namespace base + void bind_base(lua_State* L) + { + YAKE_ASSERT( L ); + base::bind(L); + } + void bind_math(lua_State* L) + { + YAKE_ASSERT( L ); + math::bind(L); + } +} // namespace yake + +#endif // YAKE_ENABLE_LUA_BASE Added: trunk/yake/src/bindings.lua/detail/ent.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/ent.lua.cpp (rev 0) +++ trunk/yake/src/bindings.lua/detail/ent.lua.cpp 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,210 @@ +/**------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright 2004 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ +*/ +#include <yake/config.h> +#if YAKE_ENABLE_LUA_ENT == 1 + +#include <yake/base/templates/yakeSmartAssert.h> +#include <yake/bindings.lua/bindings.lua.ent.h> + +#include <yake/bindings.lua/common/yake.lua.shared_ptr.h> +#include <yake/bindings.lua/common/yake.lua.any_converter.h> +#include <yake/bindings.lua/detail/private.h> +#include <yake/bindings.lua/bindings.lua.h> + +namespace yake { +namespace ent { + + //------------------------------------------------------------------------- + void bind( lua_State* L ) + { + YAKE_ASSERT( L ); + if (!L) + return; + + using namespace luabind; + using namespace yake::model; + +#define YAKE_MODEL_MODULE L, "yake" + + module( YAKE_MODEL_MODULE ) + [ + class_<Component>( "Component" ) + //.def( constructor<>() ) + ]; + + module( YAKE_MODEL_MODULE ) + [ + class_<Object>( "Object" ) + .def( constructor<>() ) + .def( "setId", &Object::setId ) + .def( "id", &Object::getId ) + ]; + + module( YAKE_MODEL_MODULE ) + [ + class_<Entity,Object>( "Entity" ) + .def( constructor<>() ) + + .def( "setModel", &Entity::setModel ) + .def( "getModel", &Entity::getModel ) + + .def( "addFsmState", &Entity::addFsmState ) + .def( "addFsmTransition", &Entity::addFsmTransition ) + .def( "setFsmState", &Entity::setFsmState ) + .def( "processFsmEvent", &Entity::processFsmEvent ) + .def( "getCurrentFsmState", &Entity::getCurrentFsmState ) + ]; + + module( YAKE_MODEL_MODULE ) + [ + class_<ObjectManager>( "ObjectManager" ) + .def( "makeObject", (Object*(ObjectManager::*)(const String&))&ObjectManager::makeObject ) + .def( "getObject", &ObjectManager::getObject ) + .def( "destroyObject", &ObjectManager::destroyObject ) + .def( "getClassNamesAndIds", &ObjectManager::getClassNamesAndIds ) + ]; + } + + //------------------------------------------------------------------------- + YAKE_WRAP_BINDER(ent,::yake::ent::bind); + + //------------------------------------------------------------------------- + namespace detail { + void executeOfTable_2(scripting::IVM& vm, const std::string& tbl1name, const std::string& tbl2name, const std::string& fn) + { + try { + scripting::LuaVM& luaVM = static_cast<scripting::LuaVM&>(vm); + lua_State* luaState = luaVM.getLuaState(); + YAKE_ASSERT( luaState ); + + luabind::object tbl1 = luabind::globals(luaState)[tbl1name.c_str()]; + if (luabind::type(tbl1) == LUA_TNIL) + //if (!tbl1) + { + std::cerr << "vm error: could not find table '" << tbl1name << "'.\n"; + return; + } + assert( luabind::type(tbl1) == LUA_TTABLE ); + + luabind::object tbl2 = tbl1[tbl2name.c_str()]; + if (luabind::type(tbl2) == LUA_TNIL) + //if (!tbl2) + { + std::cerr << "vm error: could not find table '" << tbl1name << "." << tbl2name << "'.\n"; + return; + } + assert( luabind::type(tbl2) == LUA_TTABLE ); + + luabind::object fnObj = tbl2[fn.c_str()]; + assert( luabind::type(fnObj) == LUA_TFUNCTION ); + + fnObj(); + } + catch (...) + { + YAKE_EXCEPT("executeOfTable_2(): Bad cast! VM is not a Lua VM!"); + } + } + } + + //------------------------------------------------------------------------- + namespace detail { + LuaFsmObjectListener::LuaFsmObjectListener(scripting::IScriptingSystem& scriptingSystem) : + scriptingSystem_(scriptingSystem) + { + startScript_.reset( scriptingSystem_.createScriptFromFile("../../common/media/scripts/o_fsm_test.lua") ); + YAKE_ASSERT( startScript_.get() ); + } + void LuaFsmObjectListener::onInit(Object& obj) + { + Entity* ent = Entity::cast(&obj); + if (ent) + { + YAKE_ASSERT( ent->getFsmVM() ); + ent->getFsmVM()->execute("print('initializing...')"); + ent->getFsmVM()->execute( startScript_.get() ); + + ent->getFsmVM()->execute("c = coroutine.create(main)\ncoroutine.resume(c,1)"); + } + } + void LuaFsmObjectListener::onTick(Object& obj) + { + Entity* ent = Entity::cast(&obj); + if (ent) + { + ent->getFsmVM()->execute("event.on_tick()"); + ent->getFsmVM()->execute("state." + ent->getCurrentFsmState() + ".on_tick()"); + } + } + void LuaFsmObjectListener::onFsmEventHandled(Object& obj, const object_fsm&, const object_fsm::event_type& evt) + { + Entity* ent = Entity::cast(&obj); + if (ent) + { + ent->getFsmVM()->execute("event.on_" + evt + "()"); + } + } + void LuaFsmObjectListener::onFsmEnterState(Object& obj,/*const std::string& fsmName, */const object_fsm&, const object_fsm::state_type& state) + { + Entity* ent = Entity::cast(&obj); + if (ent) + { + scripting::IVM* vm = ent->getFsmVM(); + YAKE_ASSERT( vm ); + detail::executeOfTable_2(*vm,"state",state,"on_enter"); + } + } + void LuaFsmObjectListener::onFsmExitState(Object& obj,/*const std::string& fsmName, */const object_fsm&, const object_fsm::state_type& state) + { + Entity* ent = Entity::cast(&obj); + if (ent) + { + scripting::IVM* vm = ent->getFsmVM(); + YAKE_ASSERT( vm ); + detail::executeOfTable_2(*vm,"state",state,"on_exit"); + } + } + } // namespace detail + + //------------------------------------------------------------------------- + LuaObjectManagerListener::LuaObjectManagerListener(scripting::IScriptingSystem& scriptingSystem) : + fsmListener_(scriptingSystem) + { + } + void LuaObjectManagerListener::onObjectCreated(Object* obj) + { + Entity* ent = Entity::cast(obj); + if (ent) + { + YAKE_ASSERT( ent ); + ent->attachListener( &fsmListener_, "lua_listener", ObjectListenerManager::kKeepOwnership ); + } + } + +} // namespace ent + //------------------------------------------------------------------------- + void bind_ent(lua_State* L) + { + YAKE_ASSERT(L); + ent::bind(L); + } +} // namespace yake +#endif // YAKE_ENABLE_LUA_ENT Added: trunk/yake/src/bindings.lua/detail/model.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/model.lua.cpp (rev 0) +++ trunk/yake/src/bindings.lua/detail/model.lua.cpp 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,92 @@ +/**------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright 2004 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ +*/ +#include <yake/config.h> +#if YAKE_ENABLE_LUA_MODEL == 1 + +#include <yake/base/templates/yakeSmartAssert.h> +#include <yake/base/yake.h> +#include <yake/model/model.h> +#include <yake/bindings.lua/common/yake.lua.shared_ptr.h> +#include <yake/bindings.lua/common/yake.lua.any_converter.h> +#include <yake/bindings.lua/detail/private.h> + +namespace yake { +namespace model { + + void bind( lua_State* L ) + { + YAKE_ASSERT( L ); + if (!L) + return; + + using namespace luabind; + using namespace yake::model; + +#define YAKE_MODEL_MODULE L, "yake" + + module( YAKE_MODEL_MODULE ) + [ + class_<ModelComponent>( "ModelComponent" ) + //.def( constructor<>() ) + ]; + + module( YAKE_MODEL_MODULE ) + [ + class_<Graphical,ModelComponent>( "Graphical" ) + .def( constructor<>() ) + .def( "addSceneNode", &Graphical::addSceneNode ) + //.def( "getSceneNodes", &Graphical::getSceneNodes ) + .def( "getSceneNode", &Graphical::getSceneNode ) + .def( "getEntity", &Graphical::getEntity ) + .def( "getLight", &Graphical::getLight ) + .def( "translate", &Graphical::translate ) + ]; + + module( YAKE_MODEL_MODULE ) + [ + class_<Physical,ModelComponent>( "Physical" ) + .def( constructor<>() ) + .def( "addActor", &Physical::addActor ) + .def( "addBody", &Physical::addBody ) + .def( "addJoint", &Physical::addBody ) + .def( "addAffector", &Physical::addAffector ) + .def( "addAffectorTargetActor", &Physical::addAffectorTargetActor ) + //void addAffectorTargetBody(physics::IBodyAffector*,physics::IBody*); + //void addAffectorTargetBody(physics::IBodyAffector*,const String& bodyXPath); + .def( "getActor", &Physical::getActor ) + .def( "getBody", &Physical::getBody ) + .def( "getJoint", &Physical::getJoint ) + .def( "getAffector", &Physical::getAffector ) + //.def( "translate", &Physical::translate ) + .def( "updateAffectors", &Physical::updateAffectors ) + ]; + } + + YAKE_WRAP_BINDER(model,::yake::model::bind); + +} // namespace model + void bind_model(lua_State* L) + { + YAKE_ASSERT(L); + model::bind(L); + } +} // namespace yake +#endif // YAKE_ENABLE_LUA_MODEL Added: trunk/yake/src/bindings.lua/detail/task.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/task.lua.cpp (rev 0) +++ trunk/yake/src/bindings.lua/detail/task.lua.cpp 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,66 @@ +#include <yake/config.h> +#if YAKE_ENABLE_LUA_TASK == 1 + +#include <yake/base/templates/yakeSmartAssert.h> + +#include <yake/bindings.lua/detail/private.h> +#include <yake/bindings.lua/common/lua.helpers.h> +#include <yake/bindings.lua/common/vminfo.lua.h> +#include <yake/bindings.lua/common/yake.lua.shared_ptr.h> +#include <yake/bindings.lua/common/yake.lua.any_converter.h> + +#include <yake/task/task.h> + +namespace yake { +namespace task { + + namespace detail { + void lua_revive(lua_State* L) + { + std::cout << "resuming..." << std::hex << L << "\n"; + std::cout << "(current thread status: " << (lua_status(L)) << ")\n"; + luabind::resume<void>(L); + } + task_ptr lua_executor_add(executor& exec, luabind::object fn, int ms) + { + assert( fn.interpreter() ); + return exec.add( boost::bind(&lua_run,fn), ms ); + } + void lua_wait(executor& exec, const size_t ms, luabind::object interpreterContainer) + { + assert( interpreterContainer.interpreter() ); + exec.add( boost::bind(&lua_revive,interpreterContainer.interpreter()), ms ); + } + } // namespace detail + + void bind(lua_State* L) + { + assert(L); + if (!L) + return; + using namespace luabind; // we don't expect collisions. + module( L ) + [ + class_<task,task_ptr>("task") + .def("cancel",&task::cancel) + //.def("canceled",&task::canceled) + , + class_<executor,executor_ptr>("executor") + .def("time",&executor::time) + .def("add",&detail::lua_executor_add) + , + def("schedule_revive",&detail::lua_wait) + ]; + } + + YAKE_WRAP_BINDER(task,::yake::task::bind); + +} // namespace task + void bind_task(lua_State* L) + { + YAKE_ASSERT( L ); + task::bind(L); + } +} // namespace yake + +#endif // YAKE_ENABLE_LUA_TASK Modified: trunk/yake/src/ent/object_mgr.cpp =================================================================== --- trunk/yake/src/ent/object_mgr.cpp 2007-03-12 20:59:12 UTC (rev 1629) +++ trunk/yake/src/ent/object_mgr.cpp 2007-03-12 21:01:27 UTC (rev 1630) @@ -30,7 +30,7 @@ namespace yake { namespace ent { - Object* ObjectManager::makeObject(const std::string strClsId) + Object* ObjectManager::makeObject(const String& strClsId) { YAKE_ASSERT( !strClsId.empty() )(strClsId); std::pair<object::ResultCode,ClassId> ret = objMgr_.getClassId(strClsId); Modified: trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp =================================================================== --- trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp 2007-03-12 20:59:12 UTC (rev 1629) +++ trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp 2007-03-12 21:01:27 UTC (rev 1630) @@ -25,14 +25,8 @@ ------------------------------------------------------------------------------------ */ #include <yake/plugins/scriptingLua/yakePCH.h> -extern "C" { -#include <lua.h> -#include <lualib.h> -#include <lauxlib.h> -} -#define LUABIND_NO_HEADERS_ONLY -#include <luabind/luabind.hpp> +#include <yake/bindings.lua/common/yake.lua.common.h> #include <yake/plugins/scriptingLua/ScriptingSystemLua.h> #include <fstream> Added: trunk/yake/src/task/executor.cpp =================================================================== --- trunk/yake/src/task/executor.cpp (rev 0) +++ trunk/yake/src/task/executor.cpp 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,39 @@ +#include <yake/task/task.h> +#include <iostream> // for debug output... //@todo remove + +namespace yake { +namespace task { + + task_ptr executor::add(const void_function& fn, const size_t delayMs) + { + const size_t targetTime = currTime_ + delayMs; + task_ptr t(new task(this->shared_from_this(),fn)); + jobs_[ targetTime ].push_back( t ); + return t; + } + void executor::update(const size_t elapsed) + { + currTime_ += elapsed; + std::cout << "sched @ " << currTime_ << "\n"; + while (true && !jobs_.empty()) + { + job_map::iterator it = jobs_.begin(); + if (it->first > currTime_) + break; + + { + const task_list& fns = jobs_.begin()->second; + for (task_list::const_iterator it = fns.begin(); it != fns.end(); ++it) + { + (*it)->run(); + // if (*it)->periodic() + // @todo reschedule + } + } + jobs_.erase( jobs_.begin() ); + } + //@todo remove canceled + } + +} // namespace task +} // namespace yake Added: trunk/yake/src/task/task.cpp =================================================================== --- trunk/yake/src/task/task.cpp (rev 0) +++ trunk/yake/src/task/task.cpp 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,24 @@ +#include <yake/task/task.h> + +namespace yake { +namespace task { + + task::task(executor_ptr owner, const void_function& fn) : owner_(owner), fn_(fn), canceled_(false) + { + } + void task::cancel() + { + canceled_ = true; + } + void task::run() + { + if (canceled_) + return; + //if (!periodic_) //@todo fixme + canceled_ = true; + if (fn_) + fn_(); + } + +} // namespace task +} // namespace yake Modified: trunk/yake/yake/base/yakePrerequisites.h =================================================================== --- trunk/yake/yake/base/yakePrerequisites.h 2007-03-12 20:59:12 UTC (rev 1629) +++ trunk/yake/yake/base/yakePrerequisites.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -30,6 +30,7 @@ //============================================================================ // IMPLEMENTATION HEADERS //=========================================================================== +#include <yake/config.h> #include <yake/base/yakePlatform.h> #include <assert.h> #include <ctime> Added: trunk/yake/yake/bindings.lua/bindings.lua.ent.h =================================================================== --- trunk/yake/yake/bindings.lua/bindings.lua.ent.h (rev 0) +++ trunk/yake/yake/bindings.lua/bindings.lua.ent.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,37 @@ +#ifndef YAKE_LUA_BINDINGS_ENT_H +#define YAKE_LUA_BINDINGS_ENT_H + +#include <yake/bindings.lua/prerequisites.h> +#include <yake/base/yake.h> +#include <yake/base/templates/yakePointer.h> +#include <yake/ent/ent.h> +#include <yake/scripting/yakeScriptingSystem.h> + +namespace yake { +namespace ent { + struct Object; + namespace detail { + struct YAKE_BINDINGS_LUA_API LuaFsmObjectListener : public ObjectListener + { + LuaFsmObjectListener(scripting::IScriptingSystem& scriptingSystem); + virtual void onInit(Object& obj); + virtual void onTick(Object& obj); + virtual void onFsmEventHandled(Object& obj, const object_fsm&, const object_fsm::event_type& evt); + virtual void onFsmEnterState(Object& obj,/*const std::string& fsmName, */const object_fsm&, const object_fsm::state_type& state); + virtual void onFsmExitState(Object& obj,/*const std::string& fsmName, */const object_fsm&, const object_fsm::state_type& state); + private: + scripting::IScriptingSystem& scriptingSystem_; + boost::shared_ptr<scripting::IScript> startScript_; + }; + } // namespace detail + struct YAKE_BINDINGS_LUA_API LuaObjectManagerListener : public ObjectManagerListener + { + LuaObjectManagerListener(scripting::IScriptingSystem& scriptingSystem); + virtual void onObjectCreated(Object* obj); + private: + detail::LuaFsmObjectListener fsmListener_; + }; +} // namespace ent +} // namespace yake + +#endif Added: trunk/yake/yake/bindings.lua/bindings.lua.h =================================================================== --- trunk/yake/yake/bindings.lua/bindings.lua.h (rev 0) +++ trunk/yake/yake/bindings.lua/bindings.lua.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,25 @@ +#ifndef YAKE_LUA_BINDINGS_H +#define YAKE_LUA_BINDINGS_H + +#include <yake/bindings.lua/prerequisites.h> + +namespace yake { + YAKE_BINDINGS_LUA_API void bind_all(lua_State*); + YAKE_BINDINGS_LUA_API void bind_all(scripting::IVM*); + +#if YAKE_ENABLE_LUA_BASE == 1 + YAKE_BINDINGS_LUA_API void bind_base(lua_State*); + YAKE_BINDINGS_LUA_API void bind_math(lua_State*); +#endif +#if YAKE_ENABLE_LUA_TASK == 1 + YAKE_BINDINGS_LUA_API void bind_task(lua_State*); +#endif +#if YAKE_ENABLE_LUA_MODEL == 1 + YAKE_BINDINGS_LUA_API void bind_model(lua_State*); +#endif +#if YAKE_ENABLE_LUA_ENT == 1 + YAKE_BINDINGS_LUA_API void bind_ent(lua_State*); +#endif +} // namespace yake + +#endif Added: trunk/yake/yake/bindings.lua/common/lua.helpers.cpp =================================================================== --- trunk/yake/yake/bindings.lua/common/lua.helpers.cpp (rev 0) +++ trunk/yake/yake/bindings.lua/common/lua.helpers.cpp 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,21 @@ +#include <yake/bindings.lua/common/lua.helpers.h> + +#include <iostream> +namespace yake { + void lua_run(luabind::object fn) + { + lua_State* L = fn.interpreter(); + assert(L); + std::cout << "resuming (lua_run)..." << std::hex << L << " (create new thread? thread gc'd?)\n"; + std::cout << "(current thread status: " << (lua_status(L)) << ")\n"; + luabind::call_function<void>(fn); // *NOT* resume! + } + void lua_run(luabind::object fn, const boost::any& arg0) + { + lua_State* L = fn.interpreter(); + assert(L); + std::cout << "(lua_run)..." << std::hex << L << "\n"; + //luabind::call_function<void>(fn,arg0); // *NOT* resume! + fn(arg0); + } +} // namespace yake Added: trunk/yake/yake/bindings.lua/common/lua.helpers.h =================================================================== --- trunk/yake/yake/bindings.lua/common/lua.helpers.h (rev 0) +++ trunk/yake/yake/bindings.lua/common/lua.helpers.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,28 @@ +#ifndef YAKE_LUA_HELPERS_H +#define YAKE_LUA_HELPERS_H + +#include <yake/bindings.lua/common/yake.lua.common.h> +#include <boost/any.hpp> + +namespace yake { + + void lua_run(luabind::object fn); + void lua_run(luabind::object fn, const boost::any& arg0); + +} // namespace yake + +#endif +#ifndef YAKE_LUA_HELPERS_H +#define YAKE_LUA_HELPERS_H + +#include <yake/bindings.lua/common/yake.lua.common.h> +#include <boost/any.hpp> + +namespace yake { + + void lua_run(luabind::object fn); + void lua_run(luabind::object fn, const boost::any& arg0); + +} // namespace yake + +#endif Added: trunk/yake/yake/bindings.lua/common/vminfo.lua.cpp =================================================================== --- trunk/yake/yake/bindings.lua/common/vminfo.lua.cpp (rev 0) +++ trunk/yake/yake/bindings.lua/common/vminfo.lua.cpp 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,104 @@ +#include "stdafx.h" +#include "vminfo.lua.h" + +// Lua and Luabind includes: +extern "C" { + #include "lua.h" + #include "lualib.h" + #include "lauxlib.h" +} +#pragma warning(push) +#pragma warning(disable: 4251) +#include <luabind/luabind.hpp> +#pragma warning(pop) + +// @todo autolink? +#pragma comment(lib,"luad.lib") +#pragma comment(lib,"luabindd.lib") + +// +namespace yake { +namespace vminfo_lua { + vm_info::vm_info(lua_State* L) : state(L) + {} + std::string vm_info::info() const + { + std::stringstream out; + this->print(out); + return out.str(); + } + void vm_info::print(std::ostream& out) const + { + out << "vm_info(" << std::hex << state << ")"; + } + void vm_info::print_to_cout() const + { + this->print(std::cout); + } + void bind(lua_State* L) + { + assert(L); + if (!L) + return; + using namespace luabind; // we don't expect collisions. + module( L ) + [ + class_<vm_info>("vm_info") + .def("print",&vm_info::print_to_cout) + .def("info",&vm_info::info) + ]; + } +} // namespace scheduler +} // namespace yake +#include "stdafx.h" +#include "vminfo.lua.h" + +// Lua and Luabind includes: +extern "C" { + #include "lua.h" + #include "lualib.h" + #include "lauxlib.h" +} +#pragma warning(push) +#pragma warning(disable: 4251) +#include <luabind/luabind.hpp> +#pragma warning(pop) + +// @todo autolink? +#pragma comment(lib,"luad.lib") +#pragma comment(lib,"luabindd.lib") + +// +namespace yake { +namespace vminfo_lua { + vm_info::vm_info(lua_State* L) : state(L) + {} + std::string vm_info::info() const + { + std::stringstream out; + this->print(out); + return out.str(); + } + void vm_info::print(std::ostream& out) const + { + out << "vm_info(" << std::hex << state << ")"; + } + void vm_info::print_to_cout() const + { + this->print(std::cout); + } + void bind(lua_State* L) + { + assert(L); + if (!L) + return; + using namespace luabind; // we don't expect collisions. + module( L ) + [ + class_<vm_info>("vm_info") + .def("print",&vm_info::print_to_cout) + .def("info",&vm_info::info) + ]; + } +} // namespace scheduler +} // namespace yake Added: trunk/yake/yake/bindings.lua/common/vminfo.lua.h =================================================================== --- trunk/yake/yake/bindings.lua/common/vminfo.lua.h (rev 0) +++ trunk/yake/yake/bindings.lua/common/vminfo.lua.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,46 @@ +#ifndef YAKE_VMINFO_LUA_H +#define YAKE_VMINFO_LUA_H + +struct lua_State; + +#include <sstream> // for vm_info::info() +#include <iostream> // for vm_info::print() + +namespace yake { +namespace vminfo_lua { + struct vm_info + { + vm_info(lua_State* L = 0); + std::string info() const; + void print(std::ostream& out) const; + void print_to_cout() const; + lua_State* state; + }; + void bind(lua_State* L); +} // namespace vminfo_lua +} // namespace yake + +#endif +#ifndef YAKE_VMINFO_LUA_H +#define YAKE_VMINFO_LUA_H + +struct lua_State; + +#include <sstream> // for vm_info::info() +#include <iostream> // for vm_info::print() + +namespace yake { +namespace vminfo_lua { + struct vm_info + { + vm_info(lua_State* L = 0); + std::string info() const; + void print(std::ostream& out) const; + void print_to_cout() const; + lua_State* state; + }; + void bind(lua_State* L); +} // namespace vminfo_lua +} // namespace yake + +#endif Added: trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp =================================================================== --- trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp (rev 0) +++ trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,96 @@ +#include <yake/bindings.lua/common/yake.lua.any_converter.h> + +any_converter_map& any_converters() +{ + static any_converter_map s_converters; + return s_converters; +} + + + +namespace luabind +{ + namespace converters + { + void convert_cpp_to_lua(lua_State* L, const boost::any& a) + { + typedef void(*conv_t)(lua_State* L, const boost::any&); + const type_info* ti = &a.type(); + + // special case: 'boost::any(void)' is converted to 'nil' + if (ti == &typeid(void)) + { + //std::cout << "(warning: converted void to nil)\n"; + lua_pushnil(L); + return; + } + // lookup converter & run (or bail out if no converter found) + any_converter_map::const_iterator it = any_converters().find(ti); + if (it == any_converters().end()) + throw std::runtime_error(std::string("convert_cpp_to_lua() failed to convert '") + ti->name() + "'."); + conv_t conv = it->second; + conv(L, a); + } + boost::any convert_lua_to_cpp(lua_State* L, by_value<boost::any>, int index) + { + object o(from_stack(L,index)); + switch (luabind::type(o)) + { + case LUA_TBOOLEAN: + return boost::any( object_cast<bool>(o) ); + case LUA_TNUMBER: + return boost::any( object_cast<int>(o) ); + case LUA_TSTRING: + return boost::any( object_cast<std::string>(o) ); //@todo fixme + default: + throw std::exception("encountered unsupported type in convert_lua_to_cpp()"); + } + throw std::exception("encountered unsupported type in convert_lua_to_cpp()"); + } + boost::any convert_lua_to_cpp(lua_State* L, by_const_reference<boost::any>, int index) + { + object o(from_stack(L,index)); + switch (luabind::type(o)) + { + case LUA_TBOOLEAN: + return boost::any( object_cast<bool>(o) ); + case LUA_TNUMBER: + return boost::any( object_cast<int>(o) ); + case LUA_TSTRING: + return boost::any( object_cast<std::string>(o) ); //@todo fixme + default: + throw std::exception("encountered unsupported type in convert_lua_to_cpp()"); + } + throw std::exception("encountered unsupported type in convert_lua_to_cpp()"); + } + int match_lua_to_cpp(lua_State* L, by_value<boost::any>, int index) + { + object o(from_stack(L,index)); + switch (luabind::type(o)) + { + case LUA_TBOOLEAN: + case LUA_TNUMBER: + case LUA_TSTRING: + return 0; + default: + return -1; + } + return -1; + } + int match_lua_to_cpp(lua_State* L, by_const_reference<boost::any>, int index) + { + object o(from_stack(L,index)); + switch (luabind::type(o)) + { + case LUA_TBOOLEAN: + case LUA_TNUMBER: + case LUA_TSTRING: + return 0; + default: + return -1; + } + return -1; + } + } +} + Added: trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h =================================================================== --- trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h (rev 0) +++ trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,114 @@ +#ifndef YAKE_LUA_ANYCONVERTER_H +#define YAKE_LUA_ANYCONVERTER_H + +// +#include <yake/base/yakePrerequisites.h> +#include <yake/bindings.lua/common/yake.lua.common.h> +#include <map> +#include <boost/any.hpp> + + // boost::any bindings + template<class T> + struct convert_any + { + static void convert(lua_State* L, const boost::any& a) + { + //typename luabind::detail::default_policy::template generate_converter<T, luabind::detail::cpp_to_lua>::type conv; + //conv.apply(L, *boost::any_cast<T>(&a)); + luabind::detail::convert_to_lua(L, *boost::any_cast<T>(&a)); + } + }; + + typedef std::map<const std::type_info*, void(*)(lua_State*, const boost::any&)> any_converter_map; + +#if defined(YAKE_EXPORT_LUA_ANY_CONVERTER) +# pragma message("dllexport") +# define YAKE_LUA_ANY_CONVERTER_API DLLEXPORT +#else +# pragma message("dllimport") +# define YAKE_LUA_ANY_CONVERTER_API DLLIMPORT +#endif + + YAKE_LUA_ANY_CONVERTER_API any_converter_map& any_converters(); + + //any_converter_map any_converters; + + template<class T> + void register_any_converter() + { + any_converters()[&typeid(T)] = convert_any<T>::convert; + } + + namespace luabind + { + namespace converters + { + yes_t is_user_defined(by_value<boost::any>); + yes_t is_user_defined(by_const_reference<boost::any>); + + YAKE_LUA_ANY_CONVERTER_API void convert_cpp_to_lua(lua_State* L, const boost::any& a); + YAKE_LUA_ANY_CONVERTER_API boost::any convert_lua_to_cpp(lua_State* L, by_value<boost::any>, int index); + YAKE_LUA_ANY_CONVERTER_API boost::any convert_lua_to_cpp(lua_State* L, by_const_reference<boost::any>, int index); + YAKE_LUA_ANY_CONVERTER_API int match_lua_to_cpp(lua_State* L, by_value<boost::any>, int index); + YAKE_LUA_ANY_CONVERTER_API int match_lua_to_cpp(lua_State* L, by_const_reference<boost::any>, int index); + } + } + +#endif +#ifndef YAKE_LUA_ANYCONVERTER_H +#define YAKE_LUA_ANYCONVERTER_H + +// +#include <yake/base/yakePrerequisites.h> +#include <yake/bindings.lua/common/yake.lua.common.h> +#include <map> +#include <boost/any.hpp> + + // boost::any bindings + template<class T> + struct convert_any + { + static void convert(lua_State* L, const boost::any& a) + { + //typename luabind::detail::default_policy::template generate_converter<T, luabind::detail::cpp_to_lua>::type conv; + //conv.apply(L, *boost::any_cast<T>(&a)); + luabind::detail::convert_to_lua(L, *boost::any_cast<T>(&a)); + } + }; + + typedef std::map<const std::type_info*, void(*)(lua_State*, const boost::any&)> any_converter_map; + +#if defined(YAKE_EXPORT_LUA_ANY_CONVERTER) +# pragma message("dllexport") +# define YAKE_LUA_ANY_CONVERTER_API DLLEXPORT +#else +# pragma message("dllimport") +# define YAKE_LUA_ANY_CONVERTER_API DLLIMPORT +#endif + + YAKE_LUA_ANY_CONVERTER_API any_converter_map& any_converters(); + + //any_converter_map any_converters; + + template<class T> + void register_any_converter() + { + any_converters()[&typeid(T)] = convert_any<T>::convert; + } + + namespace luabind + { + namespace converters + { + yes_t is_user_defined(by_value<boost::any>); + yes_t is_user_defined(by_const_reference<boost::any>); + + YAKE_LUA_ANY_CONVERTER_API void convert_cpp_to_lua(lua_State* L, const boost::any& a); + YAKE_LUA_ANY_CONVERTER_API boost::any convert_lua_to_cpp(lua_State* L, by_value<boost::any>, int index); + YAKE_LUA_ANY_CONVERTER_API boost::any convert_lua_to_cpp(lua_State* L, by_const_reference<boost::any>, int index); + YAKE_LUA_ANY_CONVERTER_API int match_lua_to_cpp(lua_State* L, by_value<boost::any>, int index); + YAKE_LUA_ANY_CONVERTER_API int match_lua_to_cpp(lua_State* L, by_const_reference<boost::any>, int index); + } + } + +#endif Added: trunk/yake/yake/bindings.lua/common/yake.lua.common.h =================================================================== --- trunk/yake/yake/bindings.lua/common/yake.lua.common.h (rev 0) +++ trunk/yake/yake/bindings.lua/common/yake.lua.common.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,32 @@ +#ifndef YAKE_BINDINGS_LUA_COMMON_H +#define YAKE_BINDINGS_LUA_COMMON_H + +// Lua and Luabind includes: +extern "C" { + #include "lua.h" + #include "lualib.h" + #include "lauxlib.h" +} +#pragma warning(push) +#pragma warning(disable: 4251) +#define LUABIND_NO_HEADERS_ONLY +#include <luabind/luabind.hpp> +#pragma warning(pop) + +#endif +#ifndef YAKE_BINDINGS_LUA_COMMON_H +#define YAKE_BINDINGS_LUA_COMMON_H + +// Lua and Luabind includes: +extern "C" { + #include "lua.h" + #include "lualib.h" + #include "lauxlib.h" +} +#pragma warning(push) +#pragma warning(disable: 4251) +#define LUABIND_NO_HEADERS_ONLY +#include <luabind/luabind.hpp> +#pragma warning(pop) + +#endif Added: trunk/yake/yake/bindings.lua/common/yake.lua.shared_ptr.h =================================================================== --- trunk/yake/yake/bindings.lua/common/yake.lua.shared_ptr.h (rev 0) +++ trunk/yake/yake/bindings.lua/common/yake.lua.shared_ptr.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,50 @@ +#ifndef YAKE_LUA_SHAREDPTR_BINDING_H +#define YAKE_LUA_SHAREDPTR_BINDING_H + +#include <boost/shared_ptr.hpp> + +// boost::shared_ptr bindings +namespace luabind { + template<class T> + T* get_pointer(boost::shared_ptr<T>& p) + { + return p.get(); + } + + //typedef boost::shared_ptr<ui::LuaStyleBatcher> LuaStyleBatcherPtr; + //typedef boost::shared_ptr<const ui::LuaStyleBatcher> ConstLuaStyleBatcherPtr; + + template<class A> + boost::shared_ptr<const A>* + get_const_holder(boost::shared_ptr<A>*) + { + return 0; + } +} // namespace luabind + +#endif +#ifndef YAKE_LUA_SHAREDPTR_BINDING_H +#define YAKE_LUA_SHAREDPTR_BINDING_H + +#include <boost/shared_ptr.hpp> + +// boost::shared_ptr bindings +namespace luabind { + template<class T> + T* get_pointer(boost::shared_ptr<T>& p) + { + return p.get(); + } + + //typedef boost::shared_ptr<ui::LuaStyleBatcher> LuaStyleBatcherPtr; + //typedef boost::shared_ptr<const ui::LuaStyleBatcher> ConstLuaStyleBatcherPtr; + + template<class A> + boost::shared_ptr<const A>* + get_const_holder(boost::shared_ptr<A>*) + { + return 0; + } +} // namespace luabind + +#endif Added: trunk/yake/yake/bindings.lua/detail/private.h =================================================================== --- trunk/yake/yake/bindings.lua/detail/private.h (rev 0) +++ trunk/yake/yake/bindings.lua/detail/private.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,42 @@ +#ifndef YAKE_LUA_BINDINGS_PRIVATE_H +#define YAKE_LUA_BINDINGS_PRIVATE_H + +#include <yake/scripting/yakeScriptingSystem.h> +#include <yake/plugins/scriptingLua/ScriptingSystemLua.h> + +#define YAKE_WRAP_BINDER(CLASS,BINDERFN) \ + struct binder_##CLASS : public scripting::IBinder \ + { \ + YAKE_DECLARE_CONCRETE(binder_##CLASS, #CLASS); \ + virtual void bind(scripting::IVM* vm) \ + { \ + YAKE_ASSERT(vm); \ + scripting::LuaVM* luavm = static_cast<scripting::LuaVM*>(vm); \ + lua_State* L = luavm->getLuaState(); \ + BINDERFN(L); \ + } \ + };\ + YAKE_REGISTER_CONCRETE(binder_##CLASS); + +#endif +#ifndef YAKE_LUA_BINDINGS_PRIVATE_H +#define YAKE_LUA_BINDINGS_PRIVATE_H + +#include <yake/scripting/yakeScriptingSystem.h> +#include <yake/plugins/scriptingLua/ScriptingSystemLua.h> + +#define YAKE_WRAP_BINDER(CLASS,BINDERFN) \ + struct binder_##CLASS : public scripting::IBinder \ + { \ + YAKE_DECLARE_CONCRETE(binder_##CLASS, #CLASS); \ + virtual void bind(scripting::IVM* vm) \ + { \ + YAKE_ASSERT(vm); \ + scripting::LuaVM* luavm = static_cast<scripting::LuaVM*>(vm); \ + lua_State* L = luavm->getLuaState(); \ + BINDERFN(L); \ + } \ + };\ + YAKE_REGISTER_CONCRETE(binder_##CLASS); + +#endif Added: trunk/yake/yake/bindings.lua/prerequisites.h =================================================================== --- trunk/yake/yake/bindings.lua/prerequisites.h (rev 0) +++ trunk/yake/yake/bindings.lua/prerequisites.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,21 @@ +#ifndef YAKE_LUA_BINDINGS_PREREQUISITES_H +#define YAKE_LUA_BINDINGS_PREREQUISITES_H + +#include <yake/config.h> +#include <yake/base/yakePrerequisites.h> + +#if defined(YAKE_BINDINGS_LUA_EXPORTS) +# define YAKE_BINDINGS_LUA_API DLLEXPORT +#else +# define YAKE_BINDINGS_LUA_API DLLIMPORT +#endif + +struct lua_State; + +namespace yake { + namespace scripting { + class IVM; + } // namespace scripting +} // namespace yake + +#endif Modified: trunk/yake/yake/ent/object_mgr.h =================================================================== --- trunk/yake/yake/ent/object_mgr.h 2007-03-12 20:59:12 UTC (rev 1629) +++ trunk/yake/yake/ent/object_mgr.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -60,7 +60,7 @@ /** Creates an Object for the given clsId. If the ClassId isn't known (i.e. unregistered) then 0 is returned. */ - Object* makeObject(const String strClsId); + Object* makeObject(const String& strClsId); /** Destroys the given Object. */ void destroyObject(Object*); Modified: trunk/yake/yake/physics/yakePhysicsPrerequisites.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsPrerequisites.h 2007-03-12 20:59:12 UTC (rev 1629) +++ trunk/yake/yake/physics/yakePhysicsPrerequisites.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -30,6 +30,10 @@ #ifndef YAKE_BASE_PREREQUISITES_H # include <yake/base/yakePrerequisites.h> #endif +#include <yake/base/templates/yakeDeque.h> +#include <yake/base/math/yakeMath.h> +#include <yake/base/math/yakeVector3.h> +#include <yake/base/math/yakeMatrix4.h> // C O N F I G U R A T I O N Modified: trunk/yake/yake/physics/yakePhysicsShape.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsShape.h 2007-03-12 20:59:12 UTC (rev 1629) +++ trunk/yake/yake/physics/yakePhysicsShape.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -30,6 +30,7 @@ #ifndef YAKE_PHYSICS_PREQREQUISITES_H # include <yake/physics/yakePhysicsPrerequisites.h> #endif +#include <yake/base/yakeMovable.h> namespace yake { namespace physics { Modified: trunk/yake/yake/scripting/yakeScriptingSystem.h =================================================================== --- trunk/yake/yake/scripting/yakeScriptingSystem.h 2007-03-12 20:59:12 UTC (rev 1629) +++ trunk/yake/yake/scripting/yakeScriptingSystem.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -28,6 +28,12 @@ #define YAKE_SCRIPTINGSYSTEM_H //#include <yakeBase/yake/yakeStableHeaders.h> +#include <yake/config.h> +#include <yake/base/yakePrerequisites.h> +#include <yake/base/yakePlugin.h> +#include <yake/base/templates/yakePointer.h> +#include <yake/base/templates/yakeManager.h> +#include <yake/base/templates/yakeRegistry.h> #if defined( YAKE_SCRIPTING_EXPORTS ) # pragma message("Exporting yake::scripting") Added: trunk/yake/yake/task/prerequisites.h =================================================================== --- trunk/yake/yake/task/prerequisites.h (rev 0) +++ trunk/yake/yake/task/prerequisites.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,24 @@ +#ifndef YAKE_TASK_PREREQUISITES_H +#define YAKE_TASK_PREREQUISITES_H + +#include <yake/base/yakePrerequisites.h> + +#if defined( YAKE_TASK_EXPORTS ) +# define YAKE_TASK_API DLLEXPORT +#else +# define YAKE_TASK_API DLLIMPORT +#endif + +#endif +#ifndef YAKE_TASK_PREREQUISITES_H +#define YAKE_TASK_PREREQUISITES_H + +#include <yake/base/yakePrerequisites.h> + +#if defined( YAKE_TASK_EXPORTS ) +# define YAKE_TASK_API DLLEXPORT +#else +# define YAKE_TASK_API DLLIMPORT +#endif + +#endif Added: trunk/yake/yake/task/task.h =================================================================== --- trunk/yake/yake/task/task.h (rev 0) +++ trunk/yake/yake/task/task.h 2007-03-12 21:01:27 UTC (rev 1630) @@ -0,0 +1,176 @@ +#ifndef YAKE_TASK_H +#define YAKE_TASK_H + +#include <yake/task/prerequisites.h> +#include <yake/base/templates/yakeFunction.h> +#include <boost/noncopyable.hpp> +#include <boost/shared_ptr.hpp> +#include <boost/enable_shared_from_this.hpp> + +namespace yake { +namespace task { + + struct executor; + typedef boost::shared_ptr<executor> executor_ptr; + + /** Represents a task object which can... [truncated message content] |
From: <psy...@us...> - 2007-03-12 20:59:14
|
Revision: 1629 http://svn.sourceforge.net/yake/?rev=1629&view=rev Author: psyclonist Date: 2007-03-12 13:59:12 -0700 (Mon, 12 Mar 2007) Log Message: ----------- refactored Lua binding organisation Removed Paths: ------------- trunk/yake/yake/plugins/modelLua/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-03-12 20:58:53
|
Revision: 1628 http://svn.sourceforge.net/yake/?rev=1628&view=rev Author: psyclonist Date: 2007-03-12 13:58:53 -0700 (Mon, 12 Mar 2007) Log Message: ----------- refactored Lua binding organisation Removed Paths: ------------- trunk/yake/yake/plugins/entLua/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-03-12 20:57:43
|
Revision: 1627 http://svn.sourceforge.net/yake/?rev=1627&view=rev Author: psyclonist Date: 2007-03-12 13:57:42 -0700 (Mon, 12 Mar 2007) Log Message: ----------- refactored Lua binding organisation Removed Paths: ------------- trunk/yake/src/plugins/modelLua/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-03-12 20:57:24
|
Revision: 1626 http://svn.sourceforge.net/yake/?rev=1626&view=rev Author: psyclonist Date: 2007-03-12 13:57:13 -0700 (Mon, 12 Mar 2007) Log Message: ----------- refactored Lua binding organisation Removed Paths: ------------- trunk/yake/src/plugins/entLua/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-03-12 20:49:57
|
Revision: 1625 http://svn.sourceforge.net/yake/?rev=1625&view=rev Author: psyclonist Date: 2007-03-12 13:49:46 -0700 (Mon, 12 Mar 2007) Log Message: ----------- more information on requirements, dependencies and directory layout Modified Paths: -------------- trunk/yake/BUILD Modified: trunk/yake/BUILD =================================================================== --- trunk/yake/BUILD 2007-02-21 22:44:59 UTC (rev 1624) +++ trunk/yake/BUILD 2007-03-12 20:49:46 UTC (rev 1625) @@ -39,9 +39,56 @@ * Install premake and put the premake.exe into /yake/scripts/premake. * Change to /yake/scripts/premake -1.1 Configuration +1.1.0 Installation ---------------------------------------------------------- +Download a source package or checkout the sources from the repository. +Detailed information on available sources can be found at www.yake.org. + +This article assumes that the root directory is 'yake' and the directory +structure looks like this: + yake/ + src/ + yake/ + scripts/ +etc. + +1.1.1 Directory structure +---------------------------------------------------------- + + yake/yake - includes for components (in each subdirectory) + yake/src - implementation for components (in respective subdirectories) + yake/samples - sources to demo applications + yake/common/bin - target directory for dynamic link libraries + yake/common/lib - target directory for .lib/.a (static and dll) + yake/scripts/premake - main build script generation files/scripts + yake/scripts/linux - build script generation for Linux platforms + yake/scripts/msvc71 - build script generation for Windows/MSVC7.1 platform + yake/scripts/msvc80 - build script generation for Windows/MSVC8.0 platform + yake/common/media - common media as used by the demo applications + +1.1.3 Requirements +---------------------------------------------------------- + + * a recent C++ compiler (MSVC7.1+ or GCC 3.3+) + * a good standard template library (STL) + * boost 1.32.x or above (not all libraries are needed) + +For specific components additional dependencies are required. +These include: + * ODE 0.6/0.7 for physicsODE + * OGRE 1.2.x+ for graphicsOGRE + * Lua 5.x for scriptingLua, entLua etc + * Luabind 0.7+ for scriptingLua, entLua etc + * CEGUI 0.5.x + * OpenAL 1.1 SDK for audioAL + * OpenAL++ + * TinyXML + * ... + +1.1.4 Configuration +---------------------------------------------------------- + If you need to configure the build process you find the available options in /yake/scripts/premake/config.lua. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-02-21 22:45:02
|
Revision: 1624 http://svn.sourceforge.net/yake/?rev=1624&view=rev Author: psyclonist Date: 2007-02-21 14:44:59 -0800 (Wed, 21 Feb 2007) Log Message: ----------- default exception types Modified Paths: -------------- trunk/yake/yake/base/yakeException.h Modified: trunk/yake/yake/base/yakeException.h =================================================================== --- trunk/yake/yake/base/yakeException.h 2007-02-11 00:43:08 UTC (rev 1623) +++ trunk/yake/yake/base/yakeException.h 2007-02-21 22:44:59 UTC (rev 1624) @@ -75,6 +75,21 @@ int mLine; }; +// declare/define common exceptions +#define YAKE_DEFINE_EXCEPTION(NAME) \ + struct NAME : public Exception \ + { \ + NAME(const String& msg) : Exception(msg) \ + { \ + } \ + }; + + YAKE_DEFINE_EXCEPTION(NotFoundException); + YAKE_DEFINE_EXCEPTION(AlreadyRegisteredException); + YAKE_DEFINE_EXCEPTION(AllocationFailedException); + +#undef YAKE_DEFINE_EXCEPTION + } // yake #endif // YAKE_BASE_EXCEPTION_H This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-02-11 00:43:11
|
Revision: 1623 http://svn.sourceforge.net/yake/?rev=1623&view=rev Author: psyclonist Date: 2007-02-10 16:43:08 -0800 (Sat, 10 Feb 2007) Log Message: ----------- throw and catch exceptions in createChannel() / destroyChannel() Modified Paths: -------------- trunk/yake/src/netsvc/service/netServerCommService.cpp trunk/yake/yake/netsvc/service/netServerCommService.h Modified: trunk/yake/src/netsvc/service/netServerCommService.cpp =================================================================== --- trunk/yake/src/netsvc/service/netServerCommService.cpp 2007-02-11 00:42:23 UTC (rev 1622) +++ trunk/yake/src/netsvc/service/netServerCommService.cpp 2007-02-11 00:43:08 UTC (rev 1623) @@ -47,14 +47,16 @@ void ServerCommService::createChannel(const String& name, const String& description) { if (channels_.find( name ) != channels_.end()) - YAKE_EXCEPT("channel with this name already exists"); + throw AlreadyExistsException(String("channel '") + name + "' already exists"); channels_[ name ].description_ = description; YAKE_LOG_INFORMATION("server-comm", "server-comm: channel '" << name << "' created."); } void ServerCommService::destroyChannel(const String& name) { ChannelList::iterator it = channels_.find( name ); - if (it != channels_.end()) + if (it == channels_.end()) + throw NotFoundException(String("channel '") + name +"' cannot be destroyed as it doesn't exist, sweety."); + else { YAKE_FOR_EACH(UserList::const_iterator,itUser,it->second.users_) { @@ -107,7 +109,14 @@ YAKE_ASSERT( cmd.size() == 2 || cmd.size() == 3 )(cmd).warning("malformed command."); if (cmd.size() >= 2) { - this->createChannel( cmd.at(1), (cmd.size()>2) ? cmd.at(2) : "" ); + try { + this->createChannel( cmd.at(1), (cmd.size()>2) ? cmd.at(2) : "" ); + } + catch (AlreadyExistsException&) + { + s2cEvtCommMsg msg("#server","server","you","sweety, the channel '" + cmd.at(1) + "' already exists."); + evtConn_->sendEvent(pId, msg, SendOptions().channel(commChannelId_)); + } } } return; Modified: trunk/yake/yake/netsvc/service/netServerCommService.h =================================================================== --- trunk/yake/yake/netsvc/service/netServerCommService.h 2007-02-11 00:42:23 UTC (rev 1622) +++ trunk/yake/yake/netsvc/service/netServerCommService.h 2007-02-11 00:43:08 UTC (rev 1623) @@ -9,6 +9,16 @@ namespace yake { namespace net { + struct NETSVC_API NotFoundException : public Exception + { + NotFoundException(const String& msg) : Exception(msg) + {} + }; + struct NETSVC_API AlreadyExistsException : public Exception + { + AlreadyExistsException(const String& msg) : Exception(msg) + {} + }; struct NETSVC_API ServerCommService : public IService { @@ -17,7 +27,11 @@ virtual void onStop(IServiceHost&); void onClientConnected(const PeerId); void onClientDisconnected(const PeerId); + + /** @exception AlreadyExistsException */ void createChannel(const String& name, const String& description); + + /** @exception NotFoundException */ void destroyChannel(const String& name); private: void onProcessJoinRequest(const PeerId pId, const NetEvent& evt, const ChannelId); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-02-11 00:42:22
|
Revision: 1622 http://svn.sourceforge.net/yake/?rev=1622&view=rev Author: psyclonist Date: 2007-02-10 16:42:23 -0800 (Sat, 10 Feb 2007) Log Message: ----------- added include Modified Paths: -------------- trunk/yake/yake/base/yakeConfigFile.h Modified: trunk/yake/yake/base/yakeConfigFile.h =================================================================== --- trunk/yake/yake/base/yakeConfigFile.h 2007-02-11 00:42:07 UTC (rev 1621) +++ trunk/yake/yake/base/yakeConfigFile.h 2007-02-11 00:42:23 UTC (rev 1622) @@ -31,6 +31,7 @@ #ifndef YAKE_BASE_PREREQUISITES_H # include <yake/base/yakePrerequisites.h> #endif +#include <yake/base/templates/yakePointer.h> // for Configuration #include <boost/property_tree/ptree.hpp> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-02-11 00:42:10
|
Revision: 1621 http://svn.sourceforge.net/yake/?rev=1621&view=rev Author: psyclonist Date: 2007-02-10 16:42:07 -0800 (Sat, 10 Feb 2007) Log Message: ----------- disabled MSVC warning Modified Paths: -------------- trunk/yake/yake/base/templates/yakeSmartAssert.h Modified: trunk/yake/yake/base/templates/yakeSmartAssert.h =================================================================== --- trunk/yake/yake/base/templates/yakeSmartAssert.h 2007-02-11 00:18:07 UTC (rev 1620) +++ trunk/yake/yake/base/templates/yakeSmartAssert.h 2007-02-11 00:42:07 UTC (rev 1621) @@ -130,7 +130,10 @@ private: SmartAssertContext mCtx; public: +#pragma warning(push) +#pragma warning(disable: 4355) // 'this': used in base member initializer list SmartAssert( const char * strExpr ) : YAKE_ASSERT_A(*this), YAKE_ASSERT_B(*this), mCtx(strExpr) {} +#pragma warning(pop) ~SmartAssert(); template< class type > This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-02-11 00:19:00
|
Revision: 1620 http://svn.sourceforge.net/yake/?rev=1620&view=rev Author: psyclonist Date: 2007-02-10 16:18:07 -0800 (Sat, 10 Feb 2007) Log Message: ----------- added samples Modified Paths: -------------- trunk/yake/samples/README.TXT Modified: trunk/yake/samples/README.TXT =================================================================== --- trunk/yake/samples/README.TXT 2007-02-11 00:14:19 UTC (rev 1619) +++ trunk/yake/samples/README.TXT 2007-02-11 00:18:07 UTC (rev 1620) @@ -4,7 +4,9 @@ sampleLog - basic logging net/packet - network packet connections -net/inprocess - client/server: replication objects, communication service, ... +net/inprocess - client/server: replicated objects, communication service, ... +net/commserver - "communication service" server (basic chat server) +net/commclient - "communication service" client (basic chat client) gui/console - graphical scripting console raf/minimal - bare-bones RAF application raf/demo1 - initialisation of graphics and creation of a very basic scene This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-02-11 00:14:21
|
Revision: 1619 http://svn.sourceforge.net/yake/?rev=1619&view=rev Author: psyclonist Date: 2007-02-10 16:14:19 -0800 (Sat, 10 Feb 2007) Log Message: ----------- changes due to modified logging API, two new demos 'commClient' and 'commServer' Modified Paths: -------------- trunk/yake/samples/net/inprocess/common.h trunk/yake/samples/net/roclient/ROClient.cpp trunk/yake/samples/net/roserver/ROServer.cpp Added Paths: ----------- trunk/yake/samples/bin/debug/commclient.cfg trunk/yake/samples/bin/debug/commserver.cfg trunk/yake/samples/net/commclient/ trunk/yake/samples/net/commclient/demo.cpp trunk/yake/samples/net/commserver/ trunk/yake/samples/net/commserver/demo.cpp trunk/yake/samples/net/inprocess/demo.cpp Added: trunk/yake/samples/bin/debug/commclient.cfg =================================================================== --- trunk/yake/samples/bin/debug/commclient.cfg (rev 0) +++ trunk/yake/samples/bin/debug/commclient.cfg 2007-02-11 00:14:19 UTC (rev 1619) @@ -0,0 +1,7 @@ +commclient +{ + client + { + server 192.168.1.33:40000 + } +} Added: trunk/yake/samples/bin/debug/commserver.cfg =================================================================== --- trunk/yake/samples/bin/debug/commserver.cfg (rev 0) +++ trunk/yake/samples/bin/debug/commserver.cfg 2007-02-11 00:14:19 UTC (rev 1619) @@ -0,0 +1,7 @@ +commserver +{ + server + { + bind 192.168.1.33:40000 + } +} Added: trunk/yake/samples/net/commclient/demo.cpp =================================================================== --- trunk/yake/samples/net/commclient/demo.cpp (rev 0) +++ trunk/yake/samples/net/commclient/demo.cpp 2007-02-11 00:14:19 UTC (rev 1619) @@ -0,0 +1,223 @@ +#include <yake/base/yakeConfigFile.h> + +#include <yake/net/net.h> // basic networking +#include <yake/netsvc/netSvc.h> // networking services and service hosts +#include <yake/netsvc/service/netClientCommService.h> + +#include <samples/net/roclient/ROClient.h> + +namespace yake { + struct ThreadedApp : public boost::noncopyable + { + ThreadedApp() : stop_app_(false) + { + } + void requestStop() + { + stop_app_ = true; + } + bool stopRequested() const + { + return stop_app_; + } + void run() + { + try { + this->onRun(); + } + catch (const yake::net::Exception& e) + { + YAKE_LOG_ERROR("app",String("Caught net exception: ") << e.what()); + } + catch (const std::exception& e) + { + YAKE_LOG_ERROR("app",String("Caught exception: ") << e.what()); + } + catch (...) + { + YAKE_LOG_ERROR("app",String("Caught unknown exception.")); + } + } + private: + virtual void onRun() = 0; + private: + volatile bool stop_app_; + }; + struct NetServerApp : public ThreadedApp + { + NetServerApp() + { + } + typedef SignalX<void(void)> StepSignal; + yake::SignalConnection connectToStep(const StepSignal::slot_type& slot) + { + return stepSig_.connect(slot); + } + yake::SignalConnection connectToSynchronizedNetStep(const StepSignal::slot_type& slot) + { + return netStepSig_.connect(slot); + } + private: + virtual void onInit() = 0; + virtual void onStep() = 0; + virtual void onShutdown() = 0; + private: + StepSignal stepSig_; + StepSignal netStepSig_; + virtual void onRun() + { + ::SetThreadAffinityMask( ::GetCurrentThread(), 0x1 ); + this->onInit(); + + // main loop + while (!stopRequested()) + { + net::update(); + { + net::scoped_lock lck; + netStepSig_(); + } + stepSig_(); + this->onStep(); + net::native::sleep(0); + } + + this->onShutdown(); + //stepSig_.disconnectAll(); + } + }; +} // namespace yake + +using namespace yake; + +struct ClientApp : public yake::NetServerApp +{ + ClientApp(const std::string& serverIpAndPort) : host_(net::Address(serverIpAndPort)) + {} +private: + virtual void onInit() + { + // add comm service + commService_.reset(new net::ClientCommService(CHANNELID_COMM)); + host_.addService( net::IServicePtr(commService_), "comm" ); + + // start client + if (!host_.start()) + { + YAKE_LOG_ERROR("client","failed to connect"); + return; + } + + // join a few comm channels... + commService_->joinChannel("#lobby"); + commService_->sendMessageToChannel("#lobby","hello, folks!"); + + commService_->sendMessageToChannel("$svc:comm","createchannel #support GetSupport"); + commService_->sendMessageToChannel("$svc:comm","createchannel #test asd asd asd"); + + // + stepSigConns_.push_back( this->connectToSynchronizedNetStep( + boost::bind(&ro::client::step,boost::ref(host_)) ) ); + } + virtual void onStep() + { + // example of querying & forwarding information (e.g. to UI) + if (commService_->hasMessages("#lobby")) + { + for(net::ClientCommService::const_message_iterator itMsg = + commService_->beginMessages("#lobby"); + itMsg != commService_->endMessages("#lobby"); ++itMsg) + { + //YAKE_LOG("app","#lobby: " << itMsg->from_ << " said: " << itMsg->msg_); + std::cout << '\n' << itMsg->from_ << ": " << itMsg->msg_ << "\n"; + } + commService_->clearMessages("#lobby"); + } + + // + if (_kbhit()) + { + char key = _getch(); + if (key == 'q' || key == 'Q') + { + this->requestStop(); + } + else if (key == '\n' || key == '0x13' || key == '1') + { + commService_->sendMessageToChannel("#lobby",currInput_); + std::cout << '\n' << "I said: " << currInput_ << "\n"; + currInput_.clear(); + } + else + { + currInput_ += key; + std::cout << key;//'\f' << currInput_; + } + } + } + virtual void onShutdown() + { + stepSigConns_.clear(); + + { + net::scoped_lock lck; + host_.stop(); + host_.removeAllServices(); + } + commService_.reset(); + } +private: + ro::client host_; + SharedPtr<net::ClientCommService> commService_; + + typedef std::deque<yake::SignalConnection> SignalConnectionList; + SignalConnectionList stepSigConns_; + + String currInput_; +}; + +int main(int argc, char* argv[]) +{ + try { + Configuration cfg; + + if (argc > 1) + cfg.readFromFile(argv[1]); + else + cfg.readFromFile("commclient.cfg"); + + Configuration clientCfg( cfg, "commclient/client/" ); + + if (!net::initialize()) + throw net::Exception("failed to initialize"); + + // read configuration + const yake::String serverIpAndPort = clientCfg.get("server","127.0.0.1:40000"); + + // start client(s) + SharedPtr<ClientApp> clientObject; + clientObject.reset( new ClientApp(serverIpAndPort) ); + clientObject->run(); + clientObject.reset(); + + // clean up + net::shutdown(); + } + catch (const net::Exception& e) + { + YAKE_LOG_ERROR("demoe",String("Caught net exception: ") << e.what()); + net::shutdown(); + } + catch (const std::exception& e) + { + YAKE_LOG_ERROR("demoe",String("Caught exception: ") << e.what()); + net::shutdown(); + } + catch (...) + { + YAKE_LOG_ERROR("demoe",String("Caught unknown exception.")); + net::shutdown(); + } + return 0; +} + Added: trunk/yake/samples/net/commserver/demo.cpp =================================================================== --- trunk/yake/samples/net/commserver/demo.cpp (rev 0) +++ trunk/yake/samples/net/commserver/demo.cpp 2007-02-11 00:14:19 UTC (rev 1619) @@ -0,0 +1,231 @@ +#include <yake/base/yakeConfigFile.h> +#include <yake/net/net.h> // basic networking +#include <yake/netsvc/netSvc.h> // networking services and service hosts +#include <yake/netsvc/service/netServerCommService.h> + +#include <samples/net/roserver/ROServer.h> + + +namespace yake { + struct ThreadedApp : public boost::noncopyable + { + ThreadedApp() : stop_app_(false) + { + } + void requestStop() + { + stop_app_ = true; + } + bool stopRequested() const + { + return stop_app_; + } + void run() + { + try { + this->onRun(); + } + catch (const net::Exception& e) + { + YAKE_LOG_ERROR("app",String("Caught yake::net exception: ") + e.what()); + } + catch (const Exception& e) + { + YAKE_LOG_ERROR("app",String("Caught yake exception: ") + e.what()); + } + catch (const std::exception& e) + { + YAKE_LOG_ERROR("app",String("Caught exception: ") + e.what()); + } + catch (...) + { + YAKE_LOG_ERROR("app",String("Caught unknown exception.")); + } + } + private: + virtual void onRun() = 0; + private: + volatile bool stop_app_; + }; + struct NetServerApp : public ThreadedApp + { + NetServerApp() + { + } + typedef SignalX<void(void)> StepSignal; + yake::SignalConnection connectToStep(const StepSignal::slot_type& slot) + { + return stepSig_.connect(slot); + } + yake::SignalConnection connectToSynchronizedNetStep(const StepSignal::slot_type& slot) + { + return netStepSig_.connect(slot); + } + private: + virtual void onInit() = 0; + virtual void onStep() = 0; + virtual void onShutdown() = 0; + private: + StepSignal stepSig_; + StepSignal netStepSig_; + virtual void onRun() + { + ::SetThreadAffinityMask( ::GetCurrentThread(), 0x1 ); + this->onInit(); + + // main loop + while (!stopRequested()) + { + net::update(); + { + net::scoped_lock lck; + netStepSig_(); + } + stepSig_(); + this->onStep(); + net::native::sleep(0); + } + + this->onShutdown(); + //stepSig_.disconnectAll(); + } + }; +} // namespace yake + +using namespace yake; + +struct ServerApp : public yake::NetServerApp +{ + ServerApp(const Configuration& cfg) + { + // We need a copy to be threadsafe! + cfg_.copyFrom( cfg ); + } +private: + virtual void onInit() + { + YAKE_LOG("app","starting COMM server..."); + + // register services + { + net::ServerCommService* commService = new net::ServerCommService(CHANNELID_COMM); + host_.subscribeToClientAccepted( + boost::bind(&net::ServerCommService::onClientConnected,commService,_1) ); + host_.subscribeToClientDisconnected( + boost::bind(&net::ServerCommService::onClientDisconnected,commService,_1) ); + host_.addService( net::IServicePtr(commService), "comm" ); + + /* + Configuration::const_iterator itChannelEnd = cfg_.end("comm/autocreate"); + for (Configuration::const_iterator itChannel = cfg_.begin("comm/autocreate"); itChannel != itChannelEnd; ++itChannel) + { + COUTLN(itChannel->first); + const String path = "comm/autocreate/"+itChannel->first+"/"; + const String name = cfg_.get(path+"name",""); + if (name.empty()) + { + COUTLN("server-comm: configuration: invalid channel name"); + continue; + } + const String desc = cfg_.get(path+"description",""); + COUTLN("server-comm: configuration: " << name << " : " << desc); + try { + commService->createChannel(name,desc); + } + catch (yake::Exception& ex) + { + COUTLN("server-comm: failed to create channel '" << name << "': " << ex.what()); + } + } + */ + try { + commService->createChannel("#lobby","Hello, spacemen!"); + } + catch (net::AlreadyExistsException& ex) + { + YAKE_LOG_WARNING("demo",String("createChannel() failed: ") + ex.what()); + } + } + + // start + host_.setInterface( cfg_.get("bind","127.0.0.1:40000") ); + host_.start(); + + stepSigConns_.push_back( this->connectToSynchronizedNetStep( + boost::bind(&ro::server::step,boost::ref(host_)) ) ); + } + virtual void onStep() + { + // most callbacks are triggered by base class' signals + + // + if (_kbhit()) + { + this->requestStop(); + _getch(); + } + } + virtual void onShutdown() + { + { + net::scoped_lock lck; + host_.stop(); + host_.removeAllServices(); + } + stepSigConns_.clear(); + } +private: + ro::server host_; + Configuration cfg_; + + typedef std::deque<yake::SignalConnection> SignalConnectionList; + SignalConnectionList stepSigConns_; +}; + + +int main(int argc, char* argv[]) +{ + try { + Configuration cfg; + if (argc > 1) + cfg.readFromFile(argv[1]); + else + cfg.readFromFile("commserver.cfg"); + + Configuration serverCfg( cfg, "commserver/server/" ); + + if (!net::initialize()) + throw net::Exception("failed to initialize"); + + // start server + SharedPtr<ServerApp> serverObject; + serverObject.reset( new ServerApp(serverCfg) ); + serverObject->run(); + serverObject.reset(); + + // clean up + net::shutdown(); + } + catch (const net::Exception& e) + { + YAKE_LOG("demo",String("Caught yake::net exception: ") + e.what()); + net::shutdown(); + } + catch (const Exception& e) + { + YAKE_LOG("demo",String("Caught yake exception: ") + e.what()); + net::shutdown(); + } + catch (const std::exception& e) + { + YAKE_LOG("demo",String("Caught exception: ") + e.what()); + net::shutdown(); + } + catch (...) + { + YAKE_LOG("demo","Caught unknown exception."); + net::shutdown(); + } + return 0; +} + Modified: trunk/yake/samples/net/inprocess/common.h =================================================================== --- trunk/yake/samples/net/inprocess/common.h 2007-02-10 22:27:29 UTC (rev 1618) +++ trunk/yake/samples/net/inprocess/common.h 2007-02-11 00:14:19 UTC (rev 1619) @@ -7,5 +7,4 @@ #include <yake/net/net.h> #include <yake/samples/net/common/common.h> -#define COUTLN(X) YAKE_LOG_INFORMATION("app",X) #endif Added: trunk/yake/samples/net/inprocess/demo.cpp =================================================================== --- trunk/yake/samples/net/inprocess/demo.cpp (rev 0) +++ trunk/yake/samples/net/inprocess/demo.cpp 2007-02-11 00:14:19 UTC (rev 1619) @@ -0,0 +1,606 @@ +#include <samples/net/inprocess/common.h> + +#include <yake/base/yakeConfigFile.h> + +#include <yake/net/net.h> // basic networking +#include <yake/netsvc/netSvc.h> // networking services and service hosts +#include <yake/netsvc/service/netClientCommService.h> +#include <yake/netsvc/service/netServerCommService.h> +#include <yake/netsvc/service/netClientTimeService.h> +#include <yake/netsvc/service/netServerTimeService.h> + +#include <yake/netrepsvc/netRepSvc.h> + +//#include <samples/net/common/common.h> +#include <samples/net/roserver/ROServer.h> +#include <samples/net/roclient/ROClient.h> + +#include <boost/thread/mutex.hpp> +#include <boost/thread/thread.hpp> + +#include <boost/lexical_cast.hpp> + +namespace yake { + + //server-side, atm. + struct NetObject : public boost::noncopyable + { + virtual ~NetObject() {} + ent::ObjectId objectId() const; + protected: + NetObject(ent::Object*); + }; + struct NetServerObject : public NetObject + { + NetServerObject(ent::Object*); + + void writeCreateData(const net::obitstream&); + void writeUpdateData(const net::obitstream&); + }; + struct NetClientObject : public NetObject + { + NetClientObject(ent::Object*); + + void onCreate(const net::ibitstream&); + void onUpdate(const net::ibitstream&); + }; + typedef SharedPtr<NetObject> NetObjectPtr; + struct NetObjectServer : public boost::noncopyable + { + NetObjectServer(); + ~NetObjectServer(); + + bool empty() const; + void clear(); + + //void addPeer(const net::PeerId); + + /** Queues all replicated objects to be destroyed for this client + and subsequently removes the client id from the manager. + */ + void removePeer(const net::PeerId); + + /** Create a network wrapper for the given ent::Object. */ + NetObjectPtr createObject(ent::Object*); + + /** Destroy the network wrapper. + @note The NetObjectPtr has to have been created using createObject(). + @note Remote objects are destroyed prior to destruction of the network wrapper object. + Note that this can take some time (one or more update()s). + */ + void destroyObject(const NetObjectPtr&); + + /** Queue object for publishing to given client. */ + void publish(const NetObjectPtr&, const net::PeerId); + /** Queue object for "unpublishing" to given client id. */ + void unpublish(const NetObjectPtr&, const net::PeerId); + + /** Execute queued tasks (e.g. publishing, unpublishing ...) */ + void update(); + private: + typedef std::deque<NetObjectPtr> NetObjectPtrList; + NetObjectPtrList netObjs_; + + typedef std::map<net::PeerId,NetObjectPtrList> ClientObjectsMap; + ClientObjectsMap published_; + + ClientObjectsMap qForPublish_; + ClientObjectsMap qForUnpublish_; + }; + struct NetObjectClient : public boost::noncopyable + { + NetObjectClient(); + ~NetObjectClient(); + + //NetObjectPtr create(); + //void destroy(const NetObjectPtr&); + + void update(); + + void onPublishObject(const ent::ObjectId); + void onUnpublishObject(const ent::ObjectId); + + typedef SignalX<void(const ent::ObjectId,const NetObjectPtr&)> ObjectIdPtrSignal; + SignalConnection connectToObjectPublished(const ObjectIdPtrSignal::slot_type&); + SignalConnection connectToObjectUnpublished(const ObjectIdPtrSignal::slot_type&); + private: + }; +namespace net { +namespace svc { // aka services + void initCreateClassTableMessage(yake::ent::ObjectManager& objMgr, s2cEvtClassTable& clsTbl) + { + using namespace yake; + + typedef ent::ObjectManager::ClassNameIdMap ClassNameIdMap; + const ent::ObjectManager::ClassNameIdMap& clsNamesAndIds = objMgr.getClassNamesAndIds(); + for (ClassNameIdMap::const_iterator itCls = clsNamesAndIds.begin(); itCls != clsNamesAndIds.end(); ++itCls) + { + clsTbl.globalClassIds_[ itCls->first ] = itCls->second; + } + } + +} // namespace svc +} // namespace net +} // namespace yake + +struct ThreadedApp : public boost::noncopyable +{ + ThreadedApp() : stop_app_(false) + { + } + void requestStop() + { + stop_app_ = true; + } + bool stopRequested() const + { + return stop_app_; + } + void run() + { + try { + this->onRun(); + } + catch (const yake::net::Exception& e) + { + COUTLN("Caught net exception: " << e.what()); + } + catch (const std::exception& e) + { + COUTLN("Caught exception: " << e.what()); + } + catch (...) + { + COUTLN("Caught unknown exception."); + } + } +private: + virtual void onRun() = 0; +private: + volatile bool stop_app_; +}; +namespace yake { + struct NetServerApp : public ThreadedApp + { + NetServerApp() + { + } + typedef SignalX<void(void)> StepSignal; + yake::SignalConnection connectToStep(const StepSignal::slot_type& slot) + { + return stepSig_.connect(slot); + } + yake::SignalConnection connectToSynchronizedNetStep(const StepSignal::slot_type& slot) + { + return netStepSig_.connect(slot); + } + private: + virtual void onInit() = 0; + virtual void onStep() = 0; + virtual void onShutdown() = 0; + private: + StepSignal stepSig_; + StepSignal netStepSig_; + virtual void onRun() + { + ::SetThreadAffinityMask( ::GetCurrentThread(), 0x1 ); + this->onInit(); + + // main loop + while (!stopRequested()) + { + net::update(); + { + net::scoped_lock lck; + netStepSig_(); + } + stepSig_(); + this->onStep(); + net::native::sleep(0); + } + + this->onShutdown(); + //stepSig_.disconnectAll(); + } + }; +} // namespace yake + +using namespace yake; + +struct ObjectReplicationViewManager +{ + void addPeer(const net::PeerId); + void removePeer(const net::PeerId); +private: + void _checkVisibileObjectsForPeer(const net::PeerId); +}; + +struct ServerApp : public yake::NetServerApp +{ + ServerApp(const Configuration& cfg) + { + // We need a copy to be threadsafe! + cfg_.copyFrom( cfg ); + } +private: + void _onClientSimulationStarted(const net::PeerId pid) + { + YAKE_LOG_INFORMATION("app","client connected - starting replication"); + YAKE_ASSERT( repService_ ); + repService_->startReplicationToClient( pid ); + + // Replicate global objects + //@todo replicates everything, at the moment. restrict to global! + ent::ObjectManager::const_object_iterator itEnd = objMgr_->endObjects(); + for (ent::ObjectManager::const_object_iterator it = objMgr_->beginObjects(); it != itEnd; ++it) + { + YAKE_LOG_INFORMATION("app"," replicating object"); + repService_->publish( pid, (*it)->getId() ); + } + } + virtual void onInit() + { + COUTLN("starting RO server..."); + + ent::RegistrationResult ret; + objMgr_.reset( new ent::ObjectManager() ); + objMgr_->setClassIdGenerationRange( 10000, 19999 ); + ret = objMgr_->registerClass<ent::Entity>("entity"); + objMgr_->makeObject("entity"); + objMgr_->makeObject("entity"); + + // register services + { + repService_ = new net::ServerReplicationService(CHANNELID_CONTROL); + replicationSvr_.addService( net::IServicePtr(repService_), "rep" ); + replicationSvr_.subscribeToClientAccepted( + boost::bind(&ServerApp::_onClientSimulationStarted,this,_1) ); + + net::s2cEvtClassTable clsTbl; + net::svc::initCreateClassTableMessage(*objMgr_,clsTbl); + repService_->setClassTableData(clsTbl); + + stepSigConns_.push_back( this->connectToSynchronizedNetStep( + boost::bind(&net::ServerReplicationService::update,repService_) ) ); + } + { + net::ServerCommService* commService = new net::ServerCommService(CHANNELID_COMM); + replicationSvr_.subscribeToClientAccepted( + boost::bind(&net::ServerCommService::onClientConnected,commService,_1) ); + replicationSvr_.subscribeToClientDisconnected( + boost::bind(&net::ServerCommService::onClientDisconnected,commService,_1) ); + replicationSvr_.addService( net::IServicePtr(commService), "comm" ); + + /* + Configuration::const_iterator itChannelEnd = cfg_.end("comm/autocreate"); + for (Configuration::const_iterator itChannel = cfg_.begin("comm/autocreate"); itChannel != itChannelEnd; ++itChannel) + { + COUTLN(itChannel->first); + const String path = "comm/autocreate/"+itChannel->first+"/"; + const String name = cfg_.get(path+"name",""); + if (name.empty()) + { + COUTLN("server-comm: configuration: invalid channel name"); + continue; + } + const String desc = cfg_.get(path+"description",""); + COUTLN("server-comm: configuration: " << name << " : " << desc); + try { + commService->createChannel(name,desc); + } + catch (yake::Exception& ex) + { + COUTLN("server-comm: failed to create channel '" << name << "': " << ex.what()); + } + } + */ + commService->createChannel("#lobby","Hello, spacemen!"); + } + { + net::ServerTimeService* timeService = new net::ServerTimeService(CHANNELID_CONTROL); + replicationSvr_.subscribeToClientAccepted( + boost::bind(&net::ServerTimeService::onClientConnected,timeService,_1) ); + replicationSvr_.subscribeToClientDisconnected( + boost::bind(&net::ServerTimeService::onClientDisconnected,timeService,_1) ); + replicationSvr_.addService( net::IServicePtr(timeService), "time" ); + + stepSigConns_.push_back( this->connectToSynchronizedNetStep( + boost::bind(&net::ServerTimeService::update,timeService) ) ); + } + + // start + replicationSvr_.setInterface( cfg_.get("bind","127.0.0.1:40000") ); + replicationSvr_.start(); + + stepSigConns_.push_back( this->connectToSynchronizedNetStep( + boost::bind(&ro::server::step,boost::ref(replicationSvr_)) ) ); + } + virtual void onStep() + { + // most callbacks are triggered by base class' signals + } + virtual void onShutdown() + { + repService_ = 0; + { + net::scoped_lock lck; + replicationSvr_.stop(); + replicationSvr_.removeAllServices(); + } + stepSigConns_.clear(); + } +private: + SharedPtr<ent::ObjectManager> objMgr_; + ro::server replicationSvr_; + Configuration cfg_; + net::ServerReplicationService* repService_; + + typedef std::deque<yake::SignalConnection> SignalConnectionList; + SignalConnectionList stepSigConns_; +}; +struct ClientApp : public yake::NetServerApp +{ + ClientApp(const std::string& serverIpAndPort) : client_(net::Address(serverIpAndPort)) + {} +private: + void onUpdateClassTable(const net::s2cEvtClassTable& tbl) + { + YAKE_LOG_INFORMATION("app","Updating class table..."); + COUTLN(" " << int(tbl.globalClassIds_.size()) << " class(es)"); + for (std::map<std::string,ent::ClassId>::const_iterator it = tbl.globalClassIds_.begin(); + it != tbl.globalClassIds_.end(); ++it) + { + const std::string& clsName = it->first; + const ent::ClassId globalClsId = it->second; + COUTLN(" ['" << clsName << "'] = " << int(globalClsId)); + if (!objMgr_) + { + COUTLN(" -> no object manager"); + } + else + { + ent::ObjectManager::ClassIdLookupResult ret = objMgr_->getClassId( clsName ); + if (ret.first) + { + const ent::ClassId localClsId = ret.second; + if (localClsId != it->second) + { + if (objMgr_->registerClassAlias( globalClsId, localClsId )) + { + COUTLN(" -> successfully registered alias"); + } + else + { + YAKE_LOG_ERROR("app"," -> failed to register alias"); + } + } + else + { + COUTLN(" -> no need to register an alias (global id = local id; and names match)"); + } + } + else + { + YAKE_LOG_WARNING("app"," -> class with this name not registered locally!"); + } + } + } + } + void onCreateObject(const ent::ObjectId& id) + { + YAKE_ASSERT( objMgr_.get() ); + + COUTLN("onCreateObject()"); + COUTLN(" object class='" << int(id.classId()) << "' serNo='" << int(id.serialNo()) << "'"); + if (objMgr_) + { + ent::Object* o = objMgr_->makeObject( id ); + if (o) + { + COUTLN(" successfully created! (class='" << o->isA()->name() << "')"); + objMgr_->destroyObject( o ); + } + else + COUTLN(" failed to create!"); + } + } + void onDestroyObject(const ent::ObjectId& id) + { + YAKE_ASSERT( objMgr_.get() ); + + COUTLN("onDestroyObject()"); + if (objMgr_) + { + ent::Object* o = objMgr_->getObject(id); + if (!o) + { + YAKE_LOG_WARNING("app"," object to destroy not found!"); + } + else + objMgr_->destroyObject(o); + } + } + virtual void onInit() + { + objMgr_.reset( new ent::ObjectManager() ); + + // set class id range for local classes. + // global classes will use ids outside of this range. + objMgr_->setClassIdGenerationRange( 1000, 9999 ); + + ent::RegistrationResult ret; + ret = objMgr_->registerClass<ent::Entity>("entity"); + + namespace netsvc = yake::net::svc; + + // add comm service + commService_.reset(new net::ClientCommService(CHANNELID_COMM)); + client_.addService( net::IServicePtr(commService_), "comm" ); + + // add replication service + repService_.reset(new net::ClientReplicationService(CHANNELID_CONTROL)); + client_.addService( net::IServicePtr(repService_), "rep" ); + + stepSigConns_.push_back( this->connectToSynchronizedNetStep( + boost::bind(&net::ClientReplicationService::update,repService_) ) ); + + repService_->connectToUpdateClassTable( boost::bind(&ClientApp::onUpdateClassTable,this,_1) ); + repService_->connectToObjectPublished( boost::bind(&ClientApp::onCreateObject,this,_1) ); + repService_->connectToObjectUnpublished( boost::bind(&ClientApp::onDestroyObject,this,_1) ); + + // start client + if (!client_.start()) + { + COUTLN("client failed to connect"); + objMgr_.reset(); + return; + } + + // add time service + { + net::ClientTimeService* timeService = new net::ClientTimeService(CHANNELID_CONTROL); + client_.addService( net::IServicePtr(timeService), "time" ); + } + + commService_->joinChannel("#lobby"); + commService_->sendMessageToChannel("#lobby","hello, folks!"); + + commService_->sendMessageToChannel("$svc:comm","createchannel #support GetSupport"); + commService_->sendMessageToChannel("$svc:comm","createchannel #test asd asd asd"); + + // + stepSigConns_.push_back( this->connectToSynchronizedNetStep( + boost::bind(&ro::client::step,boost::ref(client_)) ) ); + } + virtual void onStep() + { + // example of querying & forwarding information (e.g. to UI) + if (commService_->hasMessages("#lobby")) + { + for(net::ClientCommService::const_message_iterator itMsg = + commService_->beginMessages("#lobby"); + itMsg != commService_->endMessages("#lobby"); ++itMsg) + { + COUTLN("client: #lobby: " << itMsg->from_ << " said: " << itMsg->msg_); + } + commService_->clearMessages("#lobby"); + } + } + virtual void onShutdown() + { + stepSigConns_.clear(); + + { + net::scoped_lock lck; + client_.stop(); + client_.removeAllServices(); + } + commService_.reset(); + repService_.reset(); + + objMgr_.reset(); + } +private: + SharedPtr<ent::ObjectManager> objMgr_; + ro::client client_; + SharedPtr<net::ClientCommService> commService_; + SharedPtr<net::ClientReplicationService> repService_; + + typedef std::deque<yake::SignalConnection> SignalConnectionList; + SignalConnectionList stepSigConns_; +}; + +int main(int argc, char* argv[]) +{ + ::SetThreadAffinityMask( ::GetCurrentThread(), 0x1 ); + try { + Configuration cfg; +#if 0 + cfg.set("rodemo/server/start",true); + cfg.set("rodemo/client/count",3); + cfg.writeToFile("rodemo.cfg"); + return 0; +#endif + + if (argc > 1) + cfg.readFromFile(argv[1]); + else + cfg.readFromFile("rodemo.cfg"); + //cfg.writeToXML("rodemo.xml.cfg"); + + Configuration serverCfg( cfg, "rodemo/server/" ); + Configuration clientCfg( cfg, "rodemo/client/" ); + + if (!net::initialize()) + throw net::Exception("failed to initialize"); + + typedef SharedPtr<boost::thread> ThreadPtr; + + // start server ? + typedef SharedPtr<ServerApp> ServerAppPtr; + typedef std::pair<ServerAppPtr,ThreadPtr> ServerAppData; + + ServerAppData serverObject; + const bool bStartServer = serverCfg.get("start",false); + if (bStartServer) + { + serverObject.first.reset( new ServerApp(serverCfg) ); + serverObject.second.reset( new boost::thread( + boost::bind(&ServerApp::run,serverObject.first.get())) ); + } + + // start client(s) + typedef SharedPtr<ClientApp> ClientAppPtr; + typedef std::deque<std::pair<ClientAppPtr,ThreadPtr> > ClientAppList; + + ClientAppList clientApps; + const size_t numClients = clientCfg.get("count",1); + const yake::String serverIpAndPort = clientCfg.get("server","127.0.0.1:40000"); + for (size_t i=0; i<numClients; ++i) + { + std::pair<ClientAppPtr,ThreadPtr> appThreadPair; + appThreadPair.first.reset( new ClientApp(serverIpAndPort) ); + appThreadPair.second.reset( new boost::thread( boost::bind(&ClientApp::run,appThreadPair.first.get()) ) ); + clientApps.push_back( appThreadPair ); + } + + while (!_kbhit()) + net::native::sleep(0); + _getch(); + + COUTLN("stopping..."); + YAKE_FOR_EACH(ClientAppList::iterator,itApp,clientApps) + itApp->first->requestStop(); + YAKE_FOR_EACH(ClientAppList::iterator,itApp,clientApps) + itApp->second->join(); + clientApps.clear(); + + // shutdown server + if (bStartServer) + { + if (serverObject.first) + serverObject.first->requestStop(); + if (serverObject.second) + serverObject.second->join(); + } + + net::shutdown(); + } + catch (const net::Exception& e) + { + COUTLN("Caught net exception: " << e.what()); + net::shutdown(); + } + catch (const std::exception& e) + { + COUTLN("Caught exception: " << e.what()); + net::shutdown(); + } + catch (...) + { + COUTLN("Caught unknown exception."); + net::shutdown(); + } + return 0; +} + Modified: trunk/yake/samples/net/roclient/ROClient.cpp =================================================================== --- trunk/yake/samples/net/roclient/ROClient.cpp 2007-02-10 22:27:29 UTC (rev 1618) +++ trunk/yake/samples/net/roclient/ROClient.cpp 2007-02-11 00:14:19 UTC (rev 1619) @@ -25,7 +25,7 @@ conn_->addStartedCallback( boost::bind(&client::onClientStarted,this) ); // attempt to connect to server - COUTLN("trying to connect to '" << serverAddr_.ip() << ":" << serverAddr_.port() << "' ..."); + YAKE_LOG("ClientHost","trying to connect to '" << serverAddr_.ip() << ":" << serverAddr_.port() << "' ..."); /* conn_->connect( serverAddr_, true, 2000 ); */ @@ -39,7 +39,7 @@ } catch (const net::Exception& e) { - COUTLN("Caught net exception: " << e.what()); + YAKE_LOG("ClientHost","Caught net exception: " << e.what()); conn_.reset(); } return false; @@ -127,12 +127,12 @@ } void client::onClientStarted() { - COUTLN("client started."); + YAKE_LOG("ClientHost","client started."); packetConnStarted_ = true; } void client::onTimeOut() { - COUTLN("client could not connect to server. destroying connection object."); + YAKE_LOG("ClientHost","client could not connect to server. destroying connection object."); // Do NOT destroy the connection object here! It may still be inside the callback loop! // We can call disconnect(), though. @@ -141,11 +141,11 @@ } void client::running_onProcessEvent(const net::PeerId, const net::NetEvent& evt, const net::ChannelId) { - COUTLN("client (running) received event (" << (int)evt.id() << ")."); + YAKE_LOG("ClientHost","client (running) received event (" << (int)evt.id() << ")."); } void client::init_onProcessEvent(const net::PeerId, const net::NetEvent& evt, const net::ChannelId) { - COUTLN("client (init) received event (" << (int)evt.id() << ")."); + YAKE_LOG("ClientHost","client (init) received event (" << (int)evt.id() << ")."); if (stage_ == CS_JOINING) { if (evt.id() == s2cEvtJoinReqReply::ID) @@ -153,13 +153,13 @@ const s2cEvtJoinReqReply& reply = static_cast<const s2cEvtJoinReqReply&>( evt ); if (reply.accepted) { - COUTLN("client: CONNECTED TO SERVER."); + YAKE_LOG("ClientHost","client: CONNECTED TO SERVER."); stage_ = CS_RUNNING; currEvtProcessFn_ = boost::bind(&client::running_onProcessEvent,this,_1,_2,_3); } else { - COUTLN("client: SERVER DENIED ACCESS!"); + YAKE_LOG("ClientHost","client: SERVER DENIED ACCESS!"); stage_ = CS_DEAD; currEvtProcessFn_ = boost::bind(&client::init_onProcessEvent,this,_1,_2,_3); } @@ -168,7 +168,7 @@ } void client::onProcessEvent(const net::PeerId pId, const net::NetEvent& evt, const net::ChannelId cId) { - COUTLN("client (dispatcher) received event (" << (int)evt.id() << ")."); + YAKE_LOG("ClientHost","client (dispatcher) received event (" << (int)evt.id() << ")."); if (!currEvtProcessFn_.empty()) currEvtProcessFn_(pId,evt,cId); this->dispatchNetEvent(pId,evt,cId); Modified: trunk/yake/samples/net/roserver/ROServer.cpp =================================================================== --- trunk/yake/samples/net/roserver/ROServer.cpp 2007-02-10 22:27:29 UTC (rev 1618) +++ trunk/yake/samples/net/roserver/ROServer.cpp 2007-02-11 00:14:19 UTC (rev 1619) @@ -104,7 +104,7 @@ const size_t maxClients = 32; const String strServer = bindInterface_.ip() + ":" + boost::lexical_cast<String>(bindInterface_.port()); - YAKE_LOG_INFORMATION("serv-host","starting server at '" << strServer << "' with max. " << maxClients << " clients..."); + YAKE_LOG("ServerHost","starting server at '" << strServer << "' with max. " << maxClients << " clients..."); conn_.reset( net::createServerPacketConnection() ); YAKE_ASSERT( conn_ ); @@ -122,7 +122,7 @@ net::update(); net::native::sleep(0); } - YAKE_LOG_INFORMATION("serv-host","server is up at '" << strServer << "'"); + YAKE_LOG("ServerHost","server is up at '" << strServer << "'"); return true; } void server::onStop() @@ -152,8 +152,8 @@ } void server::onServerStarted() { - COUTLN("server packet connection started."); - COUTLN("server: starting event connection..."); + YAKE_LOG("ServerHost","server packet connection started."); + YAKE_LOG("ServerHost","server: starting event connection..."); YAKE_ASSERT( !evtConn_ ); evtConn_.reset( net::createEventConnection() ); YAKE_ASSERT( evtConn_ ); @@ -170,20 +170,20 @@ evtConn_->setPacketConnection( conn_.get(), net::NetEvent::DIR_ANY ); evtConn_->start(); - COUTLN("server: event connection started."); + YAKE_LOG("ServerHost","server: event connection started."); packetConnStarted_ = true; } void server::onReceivePacket(const net::PeerId peerId, const net::PacketPtr&, const net::ChannelId channel) { - COUTLN("server received packet."); + YAKE_LOG("ServerHost","server received packet."); //echoing... //conn_->send( peerId, data, len, net::SendOptions().channel(channel) ); } void server::onProcessEvent(const net::PeerId peerId, const net::NetEvent& evt, const net::ChannelId channel) { try { - COUTLN("server received event (" << (int)evt.id() << ")."); + YAKE_LOG("ServerHost","server received event (" << (int)evt.id() << ")."); // 1. Let client object handle the event. If no client object exists // for this peer, create it. @@ -210,12 +210,12 @@ } catch (...) { - COUTLN("server: CAUGHT UNHANDLED EXCEPTION!\n"); + YAKE_LOG_ERROR("ServerHost","server: CAUGHT UNHANDLED EXCEPTION!\n"); } } void server::onClientDisconnected(const net::PeerId pId) { - COUTLN("ro::server: client '" << pId << "' disconnected."); + YAKE_LOG("ServerHost","ro::server: client '" << pId << "' disconnected."); ClientPtrMap::iterator it = this->clients_.find( pId ); YAKE_ASSERT(it != this->clients_.end())(pId).warning("unknown client disconnected. lookup failed."); if (it == this->clients_.end()) @@ -234,10 +234,10 @@ if (evt.id() == c2sEvtJoinReq::ID) { const c2sEvtJoinReq& evtJoinReq = static_cast<const c2sEvtJoinReq&>(evt); - COUTLN("server: evt: Join Request"); + YAKE_LOG("ServerHost","server: evt: Join Request"); // send reply: OK - COUTLN("server: accepted join request by client"); + YAKE_LOG("ServerHost","server: accepted join request by client"); s2cEvtJoinReqReply joinReply; joinReply.accepted = true; evtConn->sendEvent( this->id, joinReply, net::SendOptions().channel(CHANNELID_CONTROL).ordered().reliable() ); @@ -247,7 +247,7 @@ #endif // use different event callback for the CS_RUNNING stage: - COUTLN("server: => CLIENT: RUNNING"); + YAKE_LOG("ServerHost","server: => CLIENT: RUNNING"); processEventFn_ = boost::bind(&client::running_onProcessEvent,this,_1,_2); this->stage = CS_RUNNING; @@ -257,7 +257,7 @@ } void client::running_onProcessEvent(const net::NetEvent& evt, const net::ChannelId channel) { - COUTLN("server::client::running_onProcessEvent()"); + YAKE_LOG("ServerHost","server::client::running_onProcessEvent()"); YAKE_ASSERT( stage == CS_RUNNING ); if (stage != CS_RUNNING) return; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-02-10 22:27:30
|
Revision: 1618 http://svn.sourceforge.net/yake/?rev=1618&view=rev Author: psyclonist Date: 2007-02-10 14:27:29 -0800 (Sat, 10 Feb 2007) Log Message: ----------- Linux implementations Modified Paths: -------------- trunk/yake/src/base/native/Linux/yakeApplication.cpp trunk/yake/src/base/native/Linux/yakeDebug.cpp trunk/yake/src/base/native/Linux/yakeNativeLibrary.cpp Modified: trunk/yake/src/base/native/Linux/yakeApplication.cpp =================================================================== --- trunk/yake/src/base/native/Linux/yakeApplication.cpp 2007-02-10 22:26:39 UTC (rev 1617) +++ trunk/yake/src/base/native/Linux/yakeApplication.cpp 2007-02-10 22:27:29 UTC (rev 1618) @@ -69,7 +69,12 @@ return path; } +threadid_t getCurrentThreadId() +{ + return 0; //@todo What's the proper method? gettid(), pthread_self()? +} + } // native } // yake Modified: trunk/yake/src/base/native/Linux/yakeDebug.cpp =================================================================== --- trunk/yake/src/base/native/Linux/yakeDebug.cpp 2007-02-10 22:26:39 UTC (rev 1617) +++ trunk/yake/src/base/native/Linux/yakeDebug.cpp 2007-02-10 22:27:29 UTC (rev 1618) @@ -39,45 +39,25 @@ //============================================================================ // INTERFACE STRUCTURES / UTILITY CLASSES //============================================================================ -namespace yake -{ -namespace native -{ +namespace yake { +namespace native { -static class LogConsole +void debug_Log( const std::string& what, logging::severity_t sev ) { -public: - LogConsole() - { - } - - ~LogConsole() - { - } - - void Print( const char* text ) - { - std::cout << text; - } - -private: - static int niftyCounter_; - static bool consoleApp_; -} logConsole_g; - -void debug_Log( const char* what, logging::Severity eSeverity, const char* source ) -{ - static char szBuffer[ 1024 ]; - - sprintf( szBuffer, "%s: %s", source, what ); - - logConsole_g.Print( szBuffer ); - logConsole_g.Print( "\n" ); + if (sev <= logging::S_ERROR) + std::cout << "<error >"; + else if (sev <= logging::S_WARNING) + std::cout << "<warning>"; + else if (sev < logging::S_LAST) + std::cout << "<info >"; + else + std::cout << "<custom >"; + std::cout << what << "\n"; } void debug_Print( const char* string ) { - logConsole_g.Print( string ); + std::cout << string; } bool debug_AssertFailed( const char* pszMessage, @@ -86,6 +66,8 @@ int nLine, bool& rbIgnoreAlways ) { + std::cerr << "\nASSERTION FAILED: " << pszCondition << "\n"; + std::cerr << " location: " << pszFile << "@" << nLine << "\n\n"; return false; } Modified: trunk/yake/src/base/native/Linux/yakeNativeLibrary.cpp =================================================================== --- trunk/yake/src/base/native/Linux/yakeNativeLibrary.cpp 2007-02-10 22:26:39 UTC (rev 1617) +++ trunk/yake/src/base/native/Linux/yakeNativeLibrary.cpp 2007-02-10 22:27:29 UTC (rev 1618) @@ -37,6 +37,12 @@ #include <dlfcn.h> #include <assert.h> } +#if 1 //defined(HAVE_DLOPEN) && defined(HAVE_WEAK_SYMBOL) && defined(HAVE_DLFCN_H) +#pragma weak dlopen +#pragma weak dlsym +#pragma weak dlclose +#pragma weak dlerror +#endif // Yake #include <yake/base/yakePCH.h> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-02-10 22:26:38
|
Revision: 1617 http://svn.sourceforge.net/yake/?rev=1617&view=rev Author: psyclonist Date: 2007-02-10 14:26:39 -0800 (Sat, 10 Feb 2007) Log Message: ----------- fixed logging interface for Linux Modified Paths: -------------- trunk/yake/yake/base/yakeLog.h Modified: trunk/yake/yake/base/yakeLog.h =================================================================== --- trunk/yake/yake/base/yakeLog.h 2007-02-10 22:24:50 UTC (rev 1616) +++ trunk/yake/yake/base/yakeLog.h 2007-02-10 22:26:39 UTC (rev 1617) @@ -172,13 +172,6 @@ # define TOSTRING(x) STRINGIFY (x) #endif -#if YAKE_COMPILER == COMPILER_GNUC - #define YAKE_LOG_INFORMATION( what ) yake::logging::log( yake::logging::S_INFORMATION, "[File: \"__FILE__\"@\"TOSTRING(__LINE__)+\"] ", what ); - #define YAKE_LOG_WARNING( what ) yake::logging::log( yake::logging::S_WARNING, "[File: \"__FILE__\"@\"TOSTRING(__LINE__)+\"] ", what ); - #define YAKE_LOG_ERROR( what ) yake::logging::log( yake::logging::S_ERROR, "[File: \"__FILE__\"@\"TOSTRING(__LINE__)+\"] ", what ); - #define YAKE_LOG( what ) yake::logging::log( yake::logging::S_INFORMATION, "[File: \"__FILE__\"@\"TOSTRING(__LINE__)+\"] ", what ); -#else - //#define YAKE_LOG_INFORMATION( what ) yake::logging::log( yake::logging::S_INFORMATION, std:"[File: "__FILE__"@"TOSTRING(__LINE__)+"] ", what ); #define YAKE_LOG_X_BASE( LOGID, LOGLVL, WHAT ) \ { \ std::stringstream ss; ss << WHAT; \ @@ -188,7 +181,6 @@ #define YAKE_LOG_WARNING( LOGID, WHAT ) YAKE_LOG_X_BASE( LOGID, yake::logging::S_WARNING, WHAT ) #define YAKE_LOG_ERROR( LOGID, WHAT ) YAKE_LOG_X_BASE( LOGID, yake::logging::S_ERROR, WHAT ) #define YAKE_LOG( LOGID, WHAT ) YAKE_LOG_X_BASE( LOGID, yake::logging::S_INFORMATION, WHAT ); -#endif } // namespace logging } // namespace yake This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-02-10 22:24:54
|
Revision: 1616 http://svn.sourceforge.net/yake/?rev=1616&view=rev Author: psyclonist Date: 2007-02-10 14:24:50 -0800 (Sat, 10 Feb 2007) Log Message: ----------- fixed case-sensitive filename Modified Paths: -------------- trunk/yake/yake/netrepsvc/netPrerequisites.h Modified: trunk/yake/yake/netrepsvc/netPrerequisites.h =================================================================== --- trunk/yake/yake/netrepsvc/netPrerequisites.h 2007-02-10 22:16:39 UTC (rev 1615) +++ trunk/yake/yake/netrepsvc/netPrerequisites.h 2007-02-10 22:24:50 UTC (rev 1616) @@ -4,7 +4,7 @@ #include <yake/base/yakePrerequisites.h> #include <yake/base/yakeString.h> #include <yake/net/net.h> -#include <yake/netsvc/netsvc.h> +#include <yake/netsvc/netSvc.h> #include <yake/ent/ent.h> #if YAKE_PLATFORM == PLATFORM_WIN32 && defined(_USRDLL) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-02-10 22:16:40
|
Revision: 1615 http://svn.sourceforge.net/yake/?rev=1615&view=rev Author: psyclonist Date: 2007-02-10 14:16:39 -0800 (Sat, 10 Feb 2007) Log Message: ----------- changed due to modified logging API Modified Paths: -------------- trunk/yake/samples/net/packet/demo.cpp Modified: trunk/yake/samples/net/packet/demo.cpp =================================================================== --- trunk/yake/samples/net/packet/demo.cpp 2007-02-07 23:34:21 UTC (rev 1614) +++ trunk/yake/samples/net/packet/demo.cpp 2007-02-10 22:16:39 UTC (rev 1615) @@ -57,11 +57,11 @@ YAKE_ASSERT( !started_ ); YAKE_ASSERT( !conn_ ); - YAKE_LOG("creating server...\n"); + YAKE_LOG("demo","creating server...\n"); conn_ = net::createServerPacketConnection(); YAKE_ASSERT( conn_ ); - YAKE_LOG("starting server...\n"); + YAKE_LOG("demo","starting server...\n"); started_ = false; conn_->addStartedCallback(boost::bind(&server::onStarted,this)); try { @@ -69,7 +69,7 @@ } catch (net::Exception& e) { - YAKE_LOG_ERROR( yake::String("NET Exception\n") + e.what() ); + YAKE_LOG_ERROR( "demo", yake::String("NET Exception\n") + e.what() ); YAKE_SAFE_DELETE( conn_ ); return false; } @@ -78,7 +78,7 @@ net::native::sleep(10); net::update(); } - YAKE_LOG_INFORMATION("server is running."); + YAKE_LOG("demo","server is running."); return true; } @@ -94,7 +94,7 @@ { \ std::stringstream ss; \ ss << X; \ -YAKE_LOG_INFORMATION(ss.str()); \ +YAKE_LOG_INFORMATION("demo",(ss.str())); \ } void server::broadcastHello() @@ -121,7 +121,7 @@ return 0; // client(s) - YAKE_LOG("creating clients...\n"); + YAKE_LOG("demo","creating clients...\n"); typedef std::deque<yake::SharedPtr<net::IClientPacketConnection> > ClientConnections; ClientConnections clients; for (size_t i=0; i<3; ++i) @@ -136,7 +136,7 @@ //net::native::sleep(500); // unfortunately, this is still necessary... // main loop - YAKE_LOG("waiting for key press..."); + YAKE_LOG("demo","waiting for key press..."); bool sentHello = false; while (!_kbhit()) { @@ -154,7 +154,7 @@ _getch(); // cleanup - YAKE_LOG("stopping clients...\n"); + YAKE_LOG("demo","stopping clients...\n"); yake::ConstVectorIterator<ClientConnections> itClient(clients); while (itClient.hasMoreElements()) itClient.getNext()->disconnect(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-02-07 23:34:21
|
Revision: 1614 http://svn.sourceforge.net/yake/?rev=1614&view=rev Author: psyclonist Date: 2007-02-07 15:34:21 -0800 (Wed, 07 Feb 2007) Log Message: ----------- Added Paths: ----------- trunk/yake/samples/vehicle/ trunk/yake/samples/vehicle/yakeDemo.cpp trunk/yake/samples/vehicle/yakePCH.cpp trunk/yake/samples/vehicle/yakePCH.h Added: trunk/yake/samples/vehicle/yakeDemo.cpp =================================================================== --- trunk/yake/samples/vehicle/yakeDemo.cpp (rev 0) +++ trunk/yake/samples/vehicle/yakeDemo.cpp 2007-02-07 23:34:21 UTC (rev 1614) @@ -0,0 +1,723 @@ +#include <samples/vehicle/yakePCH.h> +#include <yake/audio/yakeAudio.h> +#include <yake/raf/yakeRaf.h> +#include <yake/model/model.h> +#include <yake/model/model_link.h> +#include <yake/vehicle/yakeVehicle.h> +#include <yake/input/yakeInput.h> + +// temporary stuff (until factory registration issues have been sorted out): +#include <yake/vehicle/yakeNativeOde.h> + +using namespace yake; + +const input::ActionId ACTIONID_BRAKE( input::ACTIONID_USER+1, "brake" ); +const input::ActionId ACTIONID_TOGGLE_VEHICLE( input::ACTIONID_USER+2, "toggle_vehicle" ); +const real razorMeshScale = real(0.1); + +/** Configuration of the application */ +struct TheConfiguration : public raf::ApplicationConfiguration +{ + virtual StringVector getLibraries() + { return MakeStringVector() << YAKE_DYNLIB_NAME("graphicsOgre") << YAKE_DYNLIB_NAME("inputOgre") << YAKE_DYNLIB_NAME("physicsOde"); } + + //virtual StringVector getScriptingSystems() + //{ return MakeStringVector() << "lua"; } + + virtual StringVector getGraphicsSystems() + { return MakeStringVector() << "ogre3d"; } + + virtual StringVector getInputSystems() + { return MakeStringVector() << "ogre"; } + + virtual StringVector getPhysicsSystems() + { return MakeStringVector() << "ode"; } +}; + +class VehicleHumanInputController +{ +public: + void setVehicle(vehicle::IVehicle*); +}; + +/** Main application state */ +class TheMainState : public raf::RtMainState +{ +public: + TheMainState(raf::Application& owner) : + raf::RtMainState(owner), + mGround(0), + mActive(0) + { + enableInstantQuitByKey( input::KC_ESCAPE ); + } + ~TheMainState() + { + } +private: + void onModelComponent_preInit(const model::ComponentCreationContext& ctx, model::ModelComponent&) + { + YAKE_LOG("demo","onModelComponent_preInit()"); + } + void onModelComponent_postInit(const model::ComponentCreationContext& ctx, model::ModelComponent&) + { + YAKE_LOG("demo","onModelComponent_postInit()"); + } +protected: + virtual void onCreateScene() + { + YAKE_LOG_INFORMATION("demo","Creating scene"); + + // create vehicle system + mVehicleSystem.reset(new vehicle::GenericVehicleSystem()); + + // set up the model creation context. + mModelMgr.setCreationContext_GraphicalWorld( getGraphicalWorld() ); + mModelMgr.setCreationContext_PhysicalWorld( getPhysicalWorld() ); + mModelMgr.setCreationContext_CentralController( &mCentralController ); + mModelMgr.setCreationContext_NamedParameter("vehicleSystem",static_cast<vehicle::IVehicleSystem*>(mVehicleSystem.get())); + + // set up model component creation hooks. + mModelMgr.subscribeToPreInitializeComponentSignal( Bind2(&TheMainState::onModelComponent_preInit,this) ); + mModelMgr.subscribeToPostInitializeComponentSignal( Bind2(&TheMainState::onModelComponent_postInit,this) ); + + + + // create a light + graphics::ILight* pLight = getGraphicalWorld()->createLight(); + pLight->setType( graphics::ILight::LT_DIRECTIONAL ); + pLight->setDirection( Vector3(0,-1,1) ); + getGraphicalWorld()->createSceneNode("lightnode0")->attachLight( pLight ); + + getGraphicalWorld()->setShadowsEnabled( true ); + + // set up camera + getDefaultCamera()->setNearClipDistance( 1 ); + getDefaultCamera()->setFixedYawAxis(Vector3::kUnitY); + getDefaultCamera()->setPosition(Vector3(7,4,-7)); + + // + getPhysicalWorld()->setGlobalGravity(Vector3(0,real(-9.81),0)); + getPhysicalWorld()->setCurrentSolverParam("stepsize",real(0.05)); + + // create ground + mGround = new model::Model(); + { + const real groundHeight = -2; + // visual + graphics::ISceneNode* pGroundSN = getGraphicalWorld()->createSceneNode(); + graphics::IEntity* pGroundE = getGraphicalWorld()->createEntity("plane_1x1.mesh"); + pGroundE->setMaterial("box"); + pGroundE->setCastsShadow( false ); + pGroundSN->attachEntity( pGroundE ); + pGroundSN->setScale( Vector3(200,1,200) ); + pGroundSN->setPosition( Vector3(0,groundHeight,0) ); + + model::Graphical* pG = new model::Graphical(); + pG->addSceneNode( pGroundSN, "groundSN" ); + mGround->addComponent( pG ); + + // physical + physics::IActorPtr pGroundPlane = getPhysicalWorld()->createActor( physics::ACTOR_STATIC ); + pGroundPlane->createShape( physics::IShape::PlaneDesc( Vector3(0,1,0), groundHeight ) ); + + model::Physical* pP = new model::Physical(); + pP->addActor( pGroundPlane, "groundPlane" ); + mGround->addComponent( pP ); + } + + // materials @todo read from .physics: + getPhysicalWorld()->createMaterial( physics::IMaterial::Desc( 0.01f, 0.01f, 0.01f ), "chassis" ); + getPhysicalWorld()->createMaterial( physics::IMaterial::Desc( 0.01f, 0.2f, 0.01f ), "chassisTop" ); + getPhysicalWorld()->createMaterial( physics::IMaterial::Desc( 0.01f, 0.5f, 0.01f ), "wheel" ); + + // vehicle(s) + + YAKE_ASSERT( mVehicleSystem.get() ); + mVehicleSystem->loadTemplates("../../../common/media/vehicles/delorean.xml"); + mVehicleSystem->loadTemplates("../../../common/media/vehicles/jet.xml"); + + // It's possible retrieve the template and make further adjustments to it before + // instantiating vehicles. + // e.g.: vehicle::VehicleTemplate* tpl = pVS->getTemplate("delorean"); + + // sky box + getGraphicalWorld()->setSkyBox("Examples/SpaceSkyBox"); + + // create car + mCar.reset( new Car() ); + mCar->init(mCentralController,mModelMgr,*getGraphicalWorld(),*mVehicleSystem); + + // create Jet + mJet.reset( new Jet() ); + mJet->init(mCentralController,mModelMgr,*getGraphicalWorld(),*mVehicleSystem); + } + virtual void onDestroyScene() + { + mCar.reset(); + mJet.reset(); + + mModelMgr.clear(); + mVehicleSystem.reset(); + + YAKE_SAFE_DELETE( mGround ); + } + virtual void onEnter() + { + RtMainState::onEnter(); + + mActionMap.reg( ACTIONID_TOGGLE_VEHICLE, + new input::KeyboardActionCondition( getApp().getKeyboard(), input::KC_T, input::KAM_RELEASED ) ); + mActionMap.subscribeToActionIdV( ACTIONID_TOGGLE_VEHICLE, boost::bind(&TheMainState::toggleVehicle,this) ); + + mActionMap.start(); + + YAKE_ASSERT( !mActive ); + mActive = mCar.get(); + mActive->onEnter(mActionMap,getApp().getKeyboard()); + + getPhysicalWorld()->subscribeToPreStepInternal( + boost::bind(&TheMainState::preStep,this,_1) ); + } + virtual void onExit() + { + mActionMap.stop(); + + YAKE_ASSERT( mActive ); + if (mActive) + { + mActive->onExit(); + mActive = 0; + } + + RtMainState::onExit(); + } + void preStep(real stepSize) + { + std::cout << "demo: preStep (dt=" << stepSize << ")\n"; + const real timeElapsed = stepSize;//1. / 20.; + + mActionMap.update(); + + mCentralController.triggerPhysicsUpdateSignal(timeElapsed); + + if (mCar) + mCar->onFrame( timeElapsed ); + if (mJet) + mJet->onFrame( timeElapsed ); + } + virtual void onFrame(const real timeElapsed) + { + mCentralController.triggerGraphicsUpdateSignal(0,timeElapsed); + + if (mActive) + { + getDefaultCamera()->lookAt(mActive->getPosition()); + } + } +private: + model::Model* mGround; + + model::ModelManager mModelMgr; + model::CentralControllerBase mCentralController; + SharedPtr<vehicle::IVehicleSystem> mVehicleSystem; + + input::ActionMap mActionMap; + + struct GoVehicleBase + { + virtual ~GoVehicleBase() {} + virtual Vector3 getPosition() const = 0; + virtual void onEnter(input::ActionMap& actionMap, input::KeyboardDevice* keyboard) = 0; + virtual void onExit() + { + for( SignalConnectionList::iterator it = mInputSignalConnections.begin(); it != mInputSignalConnections.end(); ++it ) + it->disconnect(); + mInputSignalConnections.clear(); + + for( ConditionConnectionList::iterator it = mInputConditionConnections.begin(); it != mInputConditionConnections.end(); ++it ) + it->disconnect(); + mInputConditionConnections.clear(); + } + virtual void onFrame(const real timeElapsed) = 0; + void addInputSignalConnection(const SignalConnection& conn) + { + mInputSignalConnections.push_back( conn ); + } + void addInputConditionConnection(const input::ConditionConnection& conn) + { + mInputConditionConnections.push_back( conn ); + } + private: + typedef std::deque<SignalConnection> SignalConnectionList; + SignalConnectionList mInputSignalConnections; + typedef std::deque<input::ConditionConnection> ConditionConnectionList; + ConditionConnectionList mInputConditionConnections; + }; + struct Car : public GoVehicleBase + { + Car() : mVehicle(0) + {} + ~Car() + { + destroy(); + } + virtual Vector3 getPosition() const + { + YAKE_ASSERT( mVehicle ); + return mVehicle->getChassisPosition(); + } + + void init(model::CentralControllerBase& centralController,model::ModelManager& modelMgr,graphics::IWorld& gworld,vehicle::IVehicleSystem& vehSys) + { + // instantiate vehicle model (physics + representation containers) + YAKE_ASSERT( !mModel ); + mModel = modelMgr.createModel("theCar", + "physics/empty:name=p" + "|graphics/empty:name=g" + "|yake/dotVehicle:name=veh;template=delorean;physical=p" + ); + YAKE_ASSERT( mModel ); + vehicle::VehicleModelComponent* vehComp = static_cast<vehicle::VehicleModelComponent*>(mModel->getComponentByTag("veh")); + YAKE_ASSERT( vehComp ); + mVehicle = vehComp->getVehicle(); + YAKE_ASSERT( mVehicle ); + + // create visuals + + model::Graphical* pG = dynamic_cast<model::Graphical*>(mModel->getComponentByTag("g")); + YAKE_ASSERT( pG ); + + //mVehicle->enableDebugGeometry( *getGraphicalWorld() ); + + // create visuals + // - ship body + graphics::ISceneNode* pSN = gworld.createSceneNode("root"); + graphics::IEntity* pE = gworld.createEntity("delorean.mesh"); + pE->setCastsShadow( true ); + pSN->attachEntity( pE ); + //pSN->setScale( Vector3::kUnitScale * razorMeshScale ); + pG->addSceneNode(pSN, "delorean_root"); + + // - wheel visuals + if (mVehicle->getWheelInterface("leftFrontWheel")) + { + _createCarWheelVisual( centralController, gworld, "leftFrontWheel", *pSN ); + _createCarWheelVisual( centralController, gworld, "rightFrontWheel", *pSN ); + _createCarWheelVisual( centralController, gworld, "leftRearWheel", *pSN ); + _createCarWheelVisual( centralController, gworld, "rightRearWheel", *pSN ); + } + + // create visual <-> physics links + model::ModelMovableLink* pLink = mModel->createLink( mVehicle->getChassisMovable(), pSN ); + centralController.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableLink::update,pLink) ); + } + void destroy() + { + //@todo + mModel.reset(); + mVehicle = 0; + } + virtual void onEnter(input::ActionMap& actionMap, input::KeyboardDevice* keyboard) + { + using namespace input; + + // front wheel controls + + this->addInputConditionConnection( + actionMap.reg( ACTIONID_LEFT, + new input::KeyboardActionCondition( keyboard, KC_LEFT, KAM_CONTINUOUS ) ) ); + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_LEFT, boost::bind(&Car::onFrontWheelLeft,this) ) ); + + this->addInputConditionConnection( + actionMap.reg( ACTIONID_RIGHT, + new input::KeyboardActionCondition( keyboard, KC_RIGHT, KAM_CONTINUOUS ) ) ); + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_RIGHT, boost::bind(&Car::onFrontWheelRight,this) ) ); + + this->addInputConditionConnection( + actionMap.reg( ACTIONID_FORWARD, + new input::KeyboardActionCondition( keyboard, KC_UP, KAM_CONTINUOUS ) ) ); + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_FORWARD, boost::bind(&Car::onForward,this) ) ); + + this->addInputConditionConnection( + actionMap.reg( ACTIONID_BRAKE, + new input::KeyboardActionCondition( keyboard, KC_DOWN, KAM_CONTINUOUS ) ) ); + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_BRAKE, boost::bind(&Car::onReverse,this) ) ); + } + void onExit() + { + GoVehicleBase::onExit(); + } + virtual void onFrame(const real timeElapsed) + { + vehicle::IEnginePtrList engines = mVehicle->getEngineInterfaces(); + ConstDequeIterator< vehicle::IEnginePtrList > itEngine( engines ); + while (itEngine.hasMoreElements()) + { + vehicle::IEngine* pEngine = itEngine.getNext(); + pEngine->setInputSignal( pEngine->getInputSignal() - timeElapsed * 1.7 ); + } + + real steering0 = 0; + real braking0 = 0; + + ConstDequeIterator< ActionIdList > itAction( mActiveActions ); + while (itAction.hasMoreElements()) + { + const input::ActionId activeId = itAction.getNext(); + if (activeId == input::ACTIONID_FORWARD) + mVehicle->getEngineInterface("main")->setInputSignal(1.); + else if (activeId == ACTIONID_BRAKE) + braking0 = 1.; + else if (activeId == input::ACTIONID_LEFT) + steering0 -= real(0.7); + else if (activeId == input::ACTIONID_RIGHT) + steering0 += real(0.7); + } + mVehicle->setSteering( 0, steering0 ); + mVehicle->getWheelInterface("leftFrontWheel")->brake(braking0); + mVehicle->getWheelInterface("rightFrontWheel")->brake(braking0); + + mVehicle->updateSimulation( timeElapsed ); + + ConstDequeIterator< WheelPsMap > itWheel( mWheelPs ); + while (itWheel.hasMoreElements()) + { + const String wheelId = itWheel.getNext().first; + mWheelPs[ wheelId ]->setEmissionRate( 0, mEmitterEmissionRate[wheelId] * mVehicle->getWheelInterface( wheelId )->getSkid() ); + } + + mActiveActions.clear(); + } + private: + vehicle::IVehicle* mVehicle; + model::ModelPtr mModel; + typedef AssocVector<String,real> EmitterRealMap; + EmitterRealMap mEmitterMinVel; + EmitterRealMap mEmitterMaxVel; + EmitterRealMap mEmitterEmissionRate; + typedef AssocVector<String,graphics::IParticleSystem*> WheelPsMap; + WheelPsMap mWheelPs; + + typedef std::set<input::ActionId> ActionIdList; + ActionIdList mActiveActions; + + private: + void onForward() + { mActiveActions.insert( input::ACTIONID_FORWARD ); } + void onReverse() + { mActiveActions.insert( ACTIONID_BRAKE ); } + void onUp() + { mActiveActions.insert( input::ACTIONID_UP ); } + void onFrontWheelLeft() + { mActiveActions.insert( input::ACTIONID_LEFT ); } + void onFrontWheelRight() + { mActiveActions.insert( input::ACTIONID_RIGHT ); } + void _createCarWheelVisual(model::CentralControllerBase& centralController, graphics::IWorld& gworld, const String& wheelId, graphics::ISceneNode& parentSN) + { + YAKE_ASSERT( mModel ); + YAKE_ASSERT( mVehicle ); + + // scene node + wheel mesh + graphics::ISceneNode* pSN = gworld.createSceneNode(); + graphics::IEntity* pE = gworld.createEntity("wheel1.mesh"); + pE->setCastsShadow( true ); + pSN->attachEntity( pE ); + + model::ModelMovableLink* pLink = mModel->createLink( mVehicle->getWheelInterface(wheelId), pSN ); + centralController.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableLink::update,pLink) ); + + // scene node + particle system for smoke... + pSN = gworld.createSceneNode(); + graphics::IParticleSystem* pPS = gworld.createParticleSystem("SkidSmoke"); + mWheelPs[wheelId] = pPS; + mEmitterEmissionRate[wheelId] = pPS->getEmissionRate(0); + pSN->attachParticleSystem( pPS ); + + pLink = new model::ModelMovableDirectLink(); + pLink->setSource( mVehicle->getWheelInterface(wheelId) ); + pLink->subscribeToPositionChanged( pSN ); //position only! + mModel->addLink( pLink ); + centralController.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableLink::update,pLink) ); + } + }; + + struct Jet : public GoVehicleBase + { + Jet() : mModel(), mVehicle(0) + {} + ~Jet() + { + destroy(); + } + virtual Vector3 getPosition() const + { + YAKE_ASSERT( mVehicle ); + return mVehicle->getChassisPosition(); + } + void init(model::CentralControllerBase& centralController,model::ModelManager& modelMgr,graphics::IWorld& gworld,vehicle::IVehicleSystem& vehSys) + { + YAKE_ASSERT( !mModel ); + mModel = modelMgr.createModel("theJet", + "physics/empty:name=p" + "|graphics/empty:name=g" + "|yake/dotVehicle:name=veh;template=jet;physical=p" + ); + YAKE_ASSERT( mModel ); + vehicle::VehicleModelComponent* vehComp = static_cast<vehicle::VehicleModelComponent*>(mModel->getComponentByTag("veh")); + YAKE_ASSERT( vehComp ); + mVehicle = vehComp->getVehicle(); + YAKE_ASSERT( mVehicle ); + + mVehicle->translate(Vector3(-30,0,30)); + + // create visuals + + model::Graphical* pG = dynamic_cast<model::Graphical*>(mModel->getComponentByTag("g")); + YAKE_ASSERT( pG ); + + // - ship body + graphics::ISceneNode* pSN = gworld.createSceneNode(); + pSN->attachEntity( gworld.createEntity("razor.mesh") ); + pSN->setScale( math::Vector3::kUnitScale * razorMeshScale ); + pG->addSceneNode(pSN,"root"); + + YAKE_LOG( "demo","Creating thruster visuals" ); + // - thruster visuals + _createThrusterVisual( centralController, gworld, "left", "left", *pSN ); + _createThrusterVisual( centralController, gworld, "right", "right", *pSN ); + _createThrusterVisual( centralController, gworld, "front", "backward", *pSN ); + _createThrusterVisual( centralController, gworld, "rear", "forward", *pSN ); + _createThrusterVisual( centralController, gworld, "bottom", "upward", *pSN ); + _createThrusterVisual( centralController, gworld, "top", "downward", *pSN ); + + // - wheel visuals + if (mVehicle->getWheelInterface("frontWheel")) + { + _createWheelVisual( centralController, gworld, "frontWheel", *pSN ); + _createWheelVisual( centralController, gworld, "leftRearWheel", *pSN ); + _createWheelVisual( centralController, gworld, "rightRearWheel", *pSN ); + } + + // create visual <-> physics links + model::ModelMovableLink* pLink = mModel->createLink( mVehicle->getChassisMovable(), pSN ); + centralController.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableLink::update,pLink) ); + } + void destroy() + { + //@todo + mModel.reset(); + mVehicle = 0; + } + virtual void onEnter(input::ActionMap& actionMap, input::KeyboardDevice* keyboard) + { + using namespace input; + + // load key<->action bindings + ActionMap::loadFromFile( actionMap, "../../media/vehicles/demo.actionmap.txt", keyboard, boost::bind(&Jet::addInputConditionConnection,this,_1) ); + + // front wheel controls + + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_LEFT, boost::bind(&Jet::onFrontWheelLeft,this) ) ); + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_RIGHT, boost::bind(&Jet::onFrontWheelRight,this) ) ); + + // thruster controls + + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_STRAFE_LEFT, boost::bind(&Jet::onStrafeLeft,this) ) ); + + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_STRAFE_RIGHT, boost::bind(&Jet::onStrafeRight,this) ) ); + + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_FORWARD, boost::bind(&Jet::onForward,this) ) ); + + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_REVERSE, boost::bind(&Jet::onReverse,this) ) ); + + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_UP, boost::bind(&Jet::onUp,this) ) ); + + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_DOWN, boost::bind(&Jet::onDown,this) ) ); + } + virtual void onExit() + { + GoVehicleBase::onExit(); + } + virtual void onFrame(const real timeElapsed) + { + vehicle::IEnginePtrList engines = mVehicle->getEngineInterfaces(); + ConstDequeIterator< vehicle::IEnginePtrList > itEngine( engines ); + while (itEngine.hasMoreElements()) + { + vehicle::IEngine* pEngine = itEngine.getNext(); + pEngine->setInputSignal( std::max(0., pEngine->getInputSignal() - timeElapsed * 1.7) ); + } + + real steering0 = 0; + + ConstDequeIterator< ActionIdList > itAction( mActiveActions ); + while (itAction.hasMoreElements()) + { + const input::ActionId activeId = itAction.getNext(); + if (activeId == input::ACTIONID_STRAFE_LEFT) + mVehicle->getEngineInterface("right")->setInputSignal(1.); + else if (activeId == input::ACTIONID_STRAFE_RIGHT) + mVehicle->getEngineInterface("left")->setInputSignal(1.); + else if (activeId == input::ACTIONID_FORWARD) + mVehicle->getEngineInterface("forward")->setInputSignal(1.); + else if (activeId == input::ACTIONID_REVERSE) + mVehicle->getEngineInterface("backward")->setInputSignal(1.); + else if (activeId == input::ACTIONID_UP) + mVehicle->getEngineInterface("upward")->setInputSignal(1.); + else if (activeId == input::ACTIONID_DOWN) + mVehicle->getEngineInterface("downward")->setInputSignal(1.); + else if (activeId == input::ACTIONID_LEFT) + steering0 -= 0.3; + else if (activeId == input::ACTIONID_RIGHT) + steering0 += 0.3; + } + mVehicle->setSteering( 0, steering0 ); + + mVehicle->updateSimulation( timeElapsed ); + + _updateThrusterPs(); + + mActiveActions.clear(); + } + private: + vehicle::IVehicle* mVehicle; + model::ModelPtr mModel; + + typedef AssocVector<String,real> EmitterRealMap; + EmitterRealMap mEmitterMinVel; + EmitterRealMap mEmitterMaxVel; + EmitterRealMap mEmitterEmissionRate; + typedef AssocVector<String,graphics::IParticleSystem*> ThrusterPsMap; + ThrusterPsMap mThrusterPs; + input::ActionMap mActionMap; + + typedef std::set<input::ActionId> ActionIdList; + ActionIdList mActiveActions; + + private: + void onStrafeLeft() + { mActiveActions.insert( input::ACTIONID_STRAFE_LEFT ); } + void onStrafeRight() + { mActiveActions.insert( input::ACTIONID_STRAFE_RIGHT ); } + void onForward() + { mActiveActions.insert( input::ACTIONID_FORWARD ); } + void onReverse() + { mActiveActions.insert( input::ACTIONID_REVERSE ); } + void onUp() + { mActiveActions.insert( input::ACTIONID_UP ); } + void onDown() + { mActiveActions.insert( input::ACTIONID_DOWN ); } + void onFrontWheelLeft() + { mActiveActions.insert( input::ACTIONID_LEFT ); } + void onFrontWheelRight() + { mActiveActions.insert( input::ACTIONID_RIGHT ); } + void _createThrusterVisual(model::CentralControllerBase& centralController, graphics::IWorld& gworld, const String& mtPtId, const String& engineId, graphics::ISceneNode& parentSN) + { + graphics::ISceneNode* pSN = parentSN.createChildNode( mtPtId ); + + graphics::IParticleSystem* pPS = gworld.createParticleSystem("thruster2"); + pSN->attachParticleSystem( pPS ); + + YAKE_ASSERT( mModel ); + YAKE_ASSERT( mVehicle ); + model::ModelMovableLink* pLink = mModel->createLink( mVehicle->getMountPoint(mtPtId), pSN ); + centralController.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableLink::update,pLink) ); + + _regThrusterPs( engineId, *pPS ); + } + void _createWheelVisual(model::CentralControllerBase& centralController, graphics::IWorld& gworld, const String& wheelId, graphics::ISceneNode& parentSN) + { + graphics::ISceneNode* pSN = gworld.createSceneNode(); + graphics::IEntity* pE = gworld.createEntity("sphere_d1.mesh"); + pSN->attachEntity( pE ); + const math::Vector3 scale = math::Vector3::kUnitScale * 2.f * mVehicle->getWheelInterface(wheelId)->getRadius(); + pSN->setScale( scale ); + + YAKE_ASSERT( mModel ); + YAKE_ASSERT( mVehicle ); + model::ModelMovableLink* pLink = mModel->createLink( mVehicle->getWheelInterface(wheelId), pSN ); + centralController.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableLink::update,pLink) ); + } + void _regThrusterPs(const String& engineId, graphics::IParticleSystem& ps) + { + mEmitterMinVel[ engineId ] = ps.getMinVelocity(0); + mEmitterMaxVel[ engineId ] = ps.getMaxVelocity(0); + mEmitterEmissionRate[ engineId ] = ps.getEmissionRate(0); + mThrusterPs[ engineId ] = &ps; + } + void _updateThrusterPs() + { + ConstDequeIterator< ThrusterPsMap > itM( mThrusterPs ); + while (itM.hasMoreElements()) + { + std::pair<String,graphics::IParticleSystem*> p = itM.getNext(); + const String mtPtId = p.first; + graphics::IParticleSystem* ps = p.second; + const real throttle = mVehicle->getEngineInterface(mtPtId)->getInputSignal(); + + real rate = throttle * mEmitterEmissionRate[ mtPtId ]; + ps->setEmissionRate( 0, rate ); + //std::cout << "r=" << rate << " t=" << throttle << "\n"; + + real vel = throttle * mEmitterMaxVel[ mtPtId ]; + ps->setMaxVelocity( 0, vel ); + + vel = throttle * mEmitterMinVel[ mtPtId ]; + ps->setMinVelocity( 0, vel ); + } + } + }; + SharedPtr<Jet> mJet; + SharedPtr<Car> mCar; + GoVehicleBase* mActive; + void toggleVehicle() + { + // 1st time + if (!mActive) + mActive = mCar.get(); + else + mActive->onExit(); + + // toggle + if (mActive == static_cast<GoVehicleBase*>(mJet.get())) + mActive = mCar.get(); + else + mActive = mJet.get(); + + mActive->onEnter(mActionMap,getApp().getKeyboard()); + } +}; + +/** The mighty application itself! */ +class TheApp : public raf::ExampleApplication<TheConfiguration> +{ +public: + TheApp() {} +protected: + virtual raf::MainState* createMainState() + { + return new TheMainState(*this); + } +}; + +int main( int argc, char** argv ) +{ + // Use default executor for convenience. + // It's always possible to manually execute TheApp::initialise() etc. + TheApp theApp; + return (raf::runApplication( theApp )) ? 0 : 1; +} + Added: trunk/yake/samples/vehicle/yakePCH.cpp =================================================================== --- trunk/yake/samples/vehicle/yakePCH.cpp (rev 0) +++ trunk/yake/samples/vehicle/yakePCH.cpp 2007-02-07 23:34:21 UTC (rev 1614) @@ -0,0 +1 @@ +//#include <yake/samples/vehicle/yakePCH.h> Added: trunk/yake/samples/vehicle/yakePCH.h =================================================================== --- trunk/yake/samples/vehicle/yakePCH.h (rev 0) +++ trunk/yake/samples/vehicle/yakePCH.h 2007-02-07 23:34:21 UTC (rev 1614) @@ -0,0 +1,9 @@ +//============================================================================ +// IMPLEMENTATION HEADERS +//============================================================================ +// STL +#include <iostream> +// Yake +#include <yake/base/yake.h> +#include <yake/scripting/yakeScriptingSystem.h> +#include <yake/yappbase/yapp.h> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-02-07 23:31:52
|
Revision: 1613 http://svn.sourceforge.net/yake/?rev=1613&view=rev Author: psyclonist Date: 2007-02-07 15:31:46 -0800 (Wed, 07 Feb 2007) Log Message: ----------- Removed Paths: ------------- trunk/yake/samples/misc/cmdrmayhem/yakeDemo.cpp trunk/yake/samples/misc/cmdrmayhem/yakePCH.cpp trunk/yake/samples/misc/cmdrmayhem/yakePCH.h trunk/yake/samples/misc/vehicle/yakeDemo.cpp trunk/yake/samples/misc/vehicle/yakePCH.cpp trunk/yake/samples/misc/vehicle/yakePCH.h Deleted: trunk/yake/samples/misc/cmdrmayhem/yakeDemo.cpp =================================================================== --- trunk/yake/samples/misc/cmdrmayhem/yakeDemo.cpp 2007-02-07 23:26:34 UTC (rev 1612) +++ trunk/yake/samples/misc/cmdrmayhem/yakeDemo.cpp 2007-02-07 23:31:46 UTC (rev 1613) @@ -1,703 +0,0 @@ -#include <yapp/samples/misc/cmdrmayhem/yakePCH.h> -#include <yake/audio/yakeAudio.h> -#include <yapp/raf/yakeRaf.h> -#include <yake/model/model.h> -#include <yake/input/yakeInput.h> -#include <yapp/common/yakeCameraControllers.h> -//#include <yapp/common/yakeCEGUIHelpers.h> -#include <CEGUI/CEGUISystem.h> -#include <CEGUI/CEGUISchemeManager.h> -#include <CEGUI/CEGUIWindowManager.h> -#include <CEGUI/CEGUIWindow.h> -#include <CEGUI/CEGUIExceptions.h> -#include <CEGUI/CEGUIString.h> - -#define DEMO_USES_SPHERE - -using namespace yake; - -const input::ActionId ACTIONID_ZOOM_INOUT( input::ACTIONID_USER + 1, "zoom_inout" ); -const input::ActionId ACTIONID_MOUSE_MOVE( input::ACTIONID_USER + 2, "mouse_move" ); -const input::ActionId ACTIONID_NEXT_CAMERA( input::ACTIONID_USER + 3, "next_camera" ); - -struct CoordSys : public Movable -{ -private: - CoordSys(const CoordSys&); - CoordSys& operator=(const CoordSys&); -public: - CoordSys(graphics::IWorld& w) - { - sn_.reset( w.createSceneNode() ); - for (size_t i=0; i<3; ++i) - { - graphics::ISceneNode* sn = sn_->createChildNode(); - graphics::IEntity* ent = w.createEntity("pyramid_1x1x1.mesh"); - sn->attachEntity( ent ); - Quaternion q; - if (i==0) // x - { - q.FromAngleAxis( 0.5*3.14, Vector3::kUnitY ); - ent->setMaterial( "pyramid_red" ); - } - else if (i==1) // y - { - q.FromAngleAxis( -0.5*3.14, Vector3::kUnitX ); - ent->setMaterial( "pyramid_green" ); - } - else // z - { - q.FromAngleAxis( 0, Vector3::kUnitY ); - ent->setMaterial( "pyramid_blue" ); - } - sn->setOrientation( q ); - sn->setScale(Vector3(1,1,5)); - } - } - ~CoordSys() - { - sn_.reset(); - } - virtual void setPosition( const Vector3& rPosition ) - { - sn_->setPosition( rPosition ); - } - virtual void setOrientation( const Quaternion& rOrientation ) - { - std::cout << "cs.x=" << rOrientation * Vector3::kUnitX << " "; - std::cout << "cs.y=" << rOrientation * Vector3::kUnitY << " "; - std::cout << "cs.z=" << rOrientation * Vector3::kUnitZ << "\n"; - sn_->setOrientation( rOrientation ); - } - virtual Vector3 getPosition() const - { - return sn_->getPosition(); - } - virtual Quaternion getOrientation() const - { - return sn_->getOrientation(); - } - virtual Vector3 getDerivedPosition() const - { - return sn_->getDerivedPosition(); - } - virtual Quaternion getDerivedOrientation() const - { - return sn_->getDerivedOrientation(); - } -private: - SharedPtr<graphics::ISceneNode> sn_; -}; - -/** Configuration of the application */ -struct TheConfiguration : public raf::ApplicationConfiguration -{ - virtual StringVector getLibraries() - { return MakeStringVector() << "graphicsOgre" << "inputOgre" << "physicsODE"; } - - //virtual StringVector getScriptingSystems() - //{ return MakeStringVector() << "lua"; } - - virtual StringVector getGraphicsSystems() - { return MakeStringVector() << "ogre3d"; } - - virtual StringVector getInputSystems() - { return MakeStringVector() << "ogre"; } - - virtual StringVector getPhysicsSystems() - { return MakeStringVector() << "ode"; } - - virtual bool loadCEGUI() - { return true; } -}; - - -class CharacterController -{ -}; - - -struct Env -{ - SharedPtr<model::Model> model_; -}; -void loadEnvironment(Env& env, graphics::IWorld* pGWorld, physics::IWorld* pPWorld, const String& dotSceneFn, const String& dotXodeFn, const String& dotLinkFn) -{ - YAKE_ASSERT( pGWorld ); - YAKE_ASSERT( pPWorld ); - - YAKE_ASSERT( 0 ); -} - -// struct AvatarPhysicsComponent : public ModelComponent -// struct HumanAvatarController : public ModelComponent -// struct AvatarGraphicsComponent : public ModelComponent - -struct ControllableCharacter -{ -public: - ControllableCharacter(model::CentralControllerBase&, graphics::IWorld&, physics::IWorld&); - ~ControllableCharacter(); - void bindInput(input::ActionMap&, input::KeyboardDevice*, input::MouseDevice*); - void unbindInput(); - void update(const real dt); - void setDirection(const Vector3&); - Point3 getPosition() const; - void setPosition(const Point3&); - Quaternion getOrientation() const; -private: - ControllableCharacter(const ControllableCharacter&); - ControllableCharacter& operator=(const ControllableCharacter&); -private: - void addInputSignalConnection(const SignalConnection&); - void addInputConditionConnection(const input::ConditionConnection&); -private: - void onForward() - { mActiveActions.insert( input::ACTIONID_FORWARD ); } - void onReverse() - { mActiveActions.insert( input::ACTIONID_REVERSE ); } - void onUp() - { mActiveActions.insert( input::ACTIONID_UP ); } - void onLeft() - { mActiveActions.insert( input::ACTIONID_LEFT ); } - void onRight() - { mActiveActions.insert( input::ACTIONID_RIGHT ); } - void onCrouch() - { mActiveActions.insert( input::ACTIONID_DOWN ); } - void onRotateLeft() - { mActiveActions.insert( input::ACTIONID_ROTATE_LEFT ); } - void onRotateRight() - { mActiveActions.insert( input::ACTIONID_ROTATE_RIGHT ); } -private: - physics::IAvatarPtr mPlayerRep; - model::Model* mPlayerModel; - - typedef std::deque<SignalConnection> SignalConnectionList; - SignalConnectionList mInputSignalConnections; - - typedef std::deque<input::ConditionConnection> ConditionConnectionList; - ConditionConnectionList mInputConditionConnections; - - typedef std::set<input::ActionId> ActionIdList; - ActionIdList mActiveActions; - Vector3 mMouseMovement; - Quaternion mProjViewRot; - - SharedPtr<CoordSys> mCoordSys; -}; -ControllableCharacter::ControllableCharacter( - model::CentralControllerBase& centralCtrlr, - yake::graphics::IWorld & gworld, - yake::physics::IWorld & pworld) -{ - mPlayerRep = pworld.createAvatar( - physics::IAvatar::Desc( - Vector3(0.5,2,0), // dimensions - Vector3(0,real(0.1),0) // initial position (relative to stable position) - ) - ); - YAKE_ASSERT( mPlayerRep ); - { - mPlayerModel = new model::Model(); - model::Graphical* pG = new model::Graphical(); - mPlayerModel->addComponent( pG ); - graphics::ISceneNode* pSN = gworld.createSceneNode(); - pG->addSceneNode( pSN, "playerSN" ); - graphics::IEntity* pE = gworld.createEntity("sphere_d1.mesh"); - pSN->attachEntity( pE ); - pSN->setScale( 0.5 * Vector3::kUnitScale ); - - model::ModelMovableDirectLink* pLink = new model::ModelMovableDirectLink(); - mPlayerModel->addLink( pLink ); - pLink->setSource( mPlayerRep ); - pLink->subscribeToPositionChanged( pSN ); - pLink->subscribeToOrientationChanged( pSN ); - centralCtrlr.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableDirectLink::update,pLink) ); - } - mCoordSys.reset( new CoordSys(gworld) ); -} -ControllableCharacter::~ControllableCharacter() -{ - unbindInput(); - if (mPlayerRep) - { - mPlayerRep->getCreator().destroyAvatar( mPlayerRep ); - mPlayerRep = 0; - } - YAKE_SAFE_DELETE( mPlayerModel ); -} -void ControllableCharacter::setPosition(const Point3& pos) -{ - YAKE_ASSERT( mPlayerRep ); - mPlayerRep->setPosition( pos ); -} -void ControllableCharacter::bindInput(input::ActionMap& actionMap, - input::KeyboardDevice* keyboard, - input::MouseDevice* mouse) -{ - YAKE_ASSERT( keyboard ); - YAKE_ASSERT( mouse ); - - using namespace input; - - // load key<->action bindings - ActionMap::loadFromFile( actionMap, "../../media/samples/character/demo.actionmap.txt", keyboard, - boost::bind(&ControllableCharacter::addInputConditionConnection,this,_1) ); - - // bind functions/callbacks to input actions - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_LEFT, boost::bind(&ControllableCharacter::onLeft,this) ) ); - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_RIGHT, boost::bind(&ControllableCharacter::onRight,this) ) ); - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_ROTATE_LEFT, boost::bind(&ControllableCharacter::onRotateLeft,this) ) ); - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_ROTATE_RIGHT, boost::bind(&ControllableCharacter::onRotateRight,this) ) ); - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_FORWARD, boost::bind(&ControllableCharacter::onForward,this) ) ); - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_REVERSE, boost::bind(&ControllableCharacter::onReverse,this) ) ); - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_UP, boost::bind(&ControllableCharacter::onUp,this) ) ); - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_DOWN, boost::bind(&ControllableCharacter::onCrouch,this) ) ); -} -void ControllableCharacter::unbindInput() -{ - for( SignalConnectionList::iterator it = mInputSignalConnections.begin(); it != mInputSignalConnections.end(); ++it ) - it->disconnect(); - mInputSignalConnections.clear(); - - for( ConditionConnectionList::iterator it = mInputConditionConnections.begin(); it != mInputConditionConnections.end(); ++it ) - it->disconnect(); - mInputConditionConnections.clear(); -} -void ControllableCharacter::addInputSignalConnection(const SignalConnection& conn) -{ - mInputSignalConnections.push_back( conn ); -} -void ControllableCharacter::addInputConditionConnection(const input::ConditionConnection& conn) -{ - mInputConditionConnections.push_back( conn ); -} -void ControllableCharacter::setDirection(const Vector3& dir) -{ - const Vector3 normalisedDir = dir.normalisedCopy(); - mProjViewRot.FromAxes( normalisedDir.crossProduct( Vector3::kUnitY ), Vector3::kUnitY, -normalisedDir ); -} -void ControllableCharacter::update(const real dt) -{ - // - const real maxAng = 3.14; - real ang = 0.; - Vector3 playerTargetVel; - ConstDequeIterator< ActionIdList > itAction( mActiveActions ); - while (itAction.hasMoreElements()) - { - const input::ActionId activeId = itAction.getNext(); - if (activeId == input::ACTIONID_FORWARD) - playerTargetVel += Vector3(0,0,+1); - else if (activeId == input::ACTIONID_REVERSE) - playerTargetVel += Vector3(0,0,-1); - else if (activeId == input::ACTIONID_LEFT) - playerTargetVel += Vector3(+1,0,0); //x=1 is left vector! - else if (activeId == input::ACTIONID_RIGHT) - playerTargetVel += Vector3(-1,0,0); - else if (activeId == input::ACTIONID_UP) - mPlayerRep->jump(); - else if (activeId == input::ACTIONID_ROTATE_LEFT) - ang += maxAng; - else if (activeId == input::ACTIONID_ROTATE_RIGHT) - ang -= maxAng; - else if (activeId == input::ACTIONID_DOWN) - { - mPlayerRep->duck( !mPlayerRep->isDucking() ); - } - } - if (playerTargetVel.length() > 0.001) - { - playerTargetVel.normalise(); - mPlayerRep->move( playerTargetVel ); // velocity relative to player's orientation - } - else - mPlayerRep->move( Vector3::kZero ); - - // newUp = gravity_source to position -#ifdef DEMO_USES_SPHERE - const Vector3 newGravityVector = (Vector3::kZero/*source of gravity*/ - mPlayerRep->getPosition()).normalisedCopy(); - mPlayerRep->setGravityDirection( newGravityVector ); -#else - mPlayerRep->setGravityDirection( Vector3(0,1,0) ); -#endif - if (fabs(ang) > 0.001) - { - Quaternion rot( ang * dt, mPlayerRep->getOrientation() * Vector3::kUnitY ); - rot = rot * mPlayerRep->getOrientation(); - mPlayerRep->setOrientation( rot ); - } - - // prepare for next step - mActiveActions.clear(); - mMouseMovement = Vector3::kZero; - - // - mCoordSys->setPosition( mPlayerRep->getPosition() ); - mCoordSys->setOrientation( mPlayerRep->getOrientation() ); -} -Vector3 ControllableCharacter::getPosition() const -{ - YAKE_ASSERT( mPlayerRep ); - return mPlayerRep->getPosition(); -} -Quaternion ControllableCharacter::getOrientation() const -{ - YAKE_ASSERT( mPlayerRep ); - return mPlayerRep->getOrientation(); -} - -/** Main application state */ -class TheMainState : public raf::RtMainState -{ -public: - TheMainState(raf::Application& owner) : - raf::RtMainState(owner), - mGround(0), - mEnv(0) - { - enableInstantQuitByKey( input::KC_ESCAPE ); - } - ~TheMainState() - { - } -private: - //@todo cleanup code! - void setupGUI() - { - using namespace CEGUI; - try { - WindowManager& wmgr = WindowManager::getSingleton(); - Window* sheet = wmgr.loadWindowLayout( "cmdr_main.layout" ); - System::getSingleton().setGUISheet(sheet); - } - catch (CEGUI::Exception& ex) - { - YAKE_EXCEPT(yake::String("CEGUI Exception:\n") + ex.getMessage().c_str() ); - } - } -protected: - virtual void onCreateScene() - { - YAKE_LOG_INFORMATION("Creating scene"); - - //getPhysicalWorld()->setGlobalGravity(Vector3(0,real(-9.8),0)); - - // create a light - graphics::ILight* pLight = getGraphicalWorld()->createLight(); - pLight->setType( graphics::ILight::LT_DIRECTIONAL ); - pLight->setDirection( Vector3(0,-1,1) ); - getGraphicalWorld()->createSceneNode("lightnode0")->attachLight( pLight ); - - getGraphicalWorld()->setShadowsEnabled( true ); - - // position camera and look at the ninja - getDefaultCamera()->setNearClipDistance( 1 ); - getDefaultCamera()->setFixedYawAxis(Vector3::kUnitY); - getDefaultCamera()->setPosition(Vector3(7,4,-7)); - - // create ground - mGround = new model::Model(); - { - const real groundHeight = 50; - // visual -#ifndef DEMO_USES_SPHERE - graphics::ISceneNode* pGroundSN = getGraphicalWorld()->createSceneNode(); - graphics::IEntity* pGroundE = getGraphicalWorld()->createEntity("plane_1x1.mesh"); - pGroundE->setMaterial("box"); - pGroundE->setCastsShadow( false ); - pGroundSN->attachEntity( pGroundE ); - pGroundSN->setScale( Vector3(100,1,100) ); - pGroundSN->setPosition( Vector3(0,-groundHeight,0) ); - - model::Graphical* pG = new model::Graphical(); - pG->addSceneNode( pGroundSN, "ground", true ); - mGround->addComponent( pG, "p" ); -#endif - - // physical - physics::IActorPtr pGroundPlane = getPhysicalWorld()->createActor( physics::ACTOR_STATIC ); -#ifdef DEMO_USES_SPHERE - pGroundPlane->createShape( physics::IShape::SphereDesc( real(groundHeight) ) ); -#else - pGroundPlane->createShape( physics::IShape::PlaneDesc( Vector3(0,-1,0), groundHeight ) ); -#endif - - model::Physical* pP = new model::Physical(); - pP->addActor( pGroundPlane, "groundPlane" ); - mGround->addComponent( pP, "g" ); - } - // -#ifdef DEMO_USES_SPHERE - getGraphicalWorld()->load("osm","C:/Programme/Autodesk/3dsMax8/OSM/geo1.osm"); -#endif - - // sky box - getGraphicalWorld()->setSkyBox("Examples/SpaceSkyBox"); - - // graphics / physics environment - mEnv = new Env(); - //const String dirMediaRoot = "../../media/samples/dotLink/DynTest/"; - //const String sceneBaseName = "DotScene1"; - //loadEnvironment( *mEnv, getGraphicalWorld(), getPhysicalWorld(), - // dirMediaRoot+sceneBaseName+".scene", dirMediaRoot+sceneBaseName+".xode", dirMediaRoot+sceneBaseName+".link" ); - - // create player/avatar - mPlayer.reset( new ControllableCharacter(*this,*getGraphicalWorld(),*getPhysicalWorld()) ); - //mPlayer->setPosition( Point3(0,-52,0) ); // 2 meters above the 50 m radius sphere - mPlayer->setPosition( Point3(-25.967,44.376,0.9326) ); - - // camera controllers - { // top-down camera controller - TopDownCameraController* ctrlr = new TopDownCameraController(); - ctrlr->setCamera( getDefaultCamera() ); - ctrlr->setOffset( Vector3(40,0,0) ); - ctrlr->setTargetOffset( Vector3(40,0,0) ); - mCamControllers.push_back( CameraControllerPtr(ctrlr) ); - } - { // 3rd person camera controller - ThirdPersonCameraController* ctrlr = new ThirdPersonCameraController(); - ctrlr->setCamera( getDefaultCamera() ); - - ctrlr->setOffsetFromTarget( Vector3(0,1.5,2) ); - ctrlr->setCurrentOffsetFromTarget( ctrlr->getOffsetFromTarget() ); - - // slightly downwards - ctrlr->setOffsetOrientation( Quaternion( -0.5, Vector3::kUnitX ) ); - ctrlr->setCurrentOffsetOrientation( ctrlr->getOffsetOrientation() ); - - mCamControllers.push_back( CameraControllerPtr(ctrlr) ); - } - mCurrentCamController = 0; - - } - virtual void onDestroyScene() - { - mCamControllers.clear(); - mPlayer.reset(); - YAKE_SAFE_DELETE( mGround ); - YAKE_SAFE_DELETE( mEnv ); - } - virtual void onEnter() - { - RtMainState::onEnter(); - using namespace input; - - // controls - if (mPlayer) - mPlayer->bindInput( mActionMap, getApp().getKeyboard(), getApp().getMouse() ); - - YAKE_ASSERT( !mCamControllers.empty() ); - - // - mActionMap.reg( ACTIONID_NEXT_CAMERA, new KeyboardActionCondition( getApp().getKeyboard(), input::KC_1, input::KAM_RELEASED ) ); - mActionMap.subscribeToActionIdV( ACTIONID_NEXT_CAMERA, BindX(&TheMainState::onNextCamera,this) ); - - // top-down controller - // @todo unsubscribe; move out into top down controller's bindInput() - mActionMap.reg( ACTIONID_ZOOM_INOUT, new MouseMoveActionCondition( getApp().getMouse(), input::MMA_WHEEL, input::MMD_BOTH ) ); - mActionMap.subscribeToActionIdR( ACTIONID_ZOOM_INOUT, Bind1(&TheMainState::onMouseWheel,this) ); - - mActionMap.reg( ACTIONID_MOUSE_MOVE, new MouseMoveActionCondition( getApp().getMouse(), input::MMA_X_AND_Y, input::MMD_BOTH ) ); - mActionMap.subscribeToActionIdR( ACTIONID_MOUSE_MOVE, Bind1(&TheMainState::onMouseMoveXY,this) ); - - // for cursor - getApp().enableMouseInputForCEGUI(true); - getApp().enableKeyboardInputForCEGUI(true); - - setupGUI(); - - mActionMap.start(); - } - virtual void onExit() - { - mActionMap.stop(); - - if (mPlayer) - mPlayer->unbindInput(); - - getApp().enableKeyboardInputForCEGUI(false); - getApp().enableMouseInputForCEGUI(false); - - RtMainState::onExit(); - } - virtual void onFrame(const real timeElapsed) - { - // - mActionMap.update(); - - // - if (mPlayer) - { - /* - Vector3 projViewDir = mTopDownCtrlr.getOffset(); - projViewDir.y = 0.; - if (projViewDir.length() <= 0.01) - projViewDir = Vector3::kUnitZ; - projViewDir.normalise(); - mPlayer->setDirection( projViewDir ); - */ - mPlayer->update( timeElapsed ); - } - - CameraControllerPtr currCamCtrlr = mCamControllers.at(mCurrentCamController); - YAKE_ASSERT( currCamCtrlr.get() ); - - //@todo hide properly - if (TopDownCameraController* topdownCtrlr = dynamic_cast<TopDownCameraController*>(currCamCtrlr.get())) - { // top-down controller - const real dist = timeElapsed * real(4.); - Vector3 offset; - if (this->getApp().getKeyboard()->isKeyDown(input::KC_I)) - offset += dist * Vector3::kUnitZ; - if (this->getApp().getKeyboard()->isKeyDown(input::KC_K)) - offset += - dist * Vector3::kUnitZ; - if (this->getApp().getKeyboard()->isKeyDown(input::KC_J)) - offset += dist * Vector3::kUnitX; - if (this->getApp().getKeyboard()->isKeyDown(input::KC_L)) - offset += - dist * Vector3::kUnitX; - if (this->getApp().getKeyboard()->isKeyDown(input::KC_R)) - offset += dist * Vector3::kUnitY; - if (this->getApp().getKeyboard()->isKeyDown(input::KC_F)) - offset += - dist * Vector3::kUnitY; - topdownCtrlr->setOffset( topdownCtrlr->getOffset() + offset ); - topdownCtrlr->setTargetOffset( topdownCtrlr->getTargetOffset() + offset ); - - topdownCtrlr->setTarget( mPlayer->getPosition() ); - - // Rotate camera around camera's 'up' axis - // when user presses RMB and moves the mouse. - if (this->getApp().getMouse()->isButtonDown( input::MB_RIGHT )) - { - // @todo adjust rotation over several frames for smoother rotation. - const real angle = mMouseMovement.x * real(100.) * timeElapsed; - Matrix3 rot; - rot.FromAxisAngle( Vector3::kUnitY, angle ); - - // NB rotate both 'target offset' and 'current offset' so that - // relative to each other they stay the same. - - Vector3 offset = rot * topdownCtrlr->getTargetOffset(); - topdownCtrlr->setTargetOffset( offset ); - - offset = rot * topdownCtrlr->getOffset(); - topdownCtrlr->setOffset( offset ); - } - } - else if (ThirdPersonCameraController* ctrlr = dynamic_cast<ThirdPersonCameraController*>(currCamCtrlr.get())) - { - ctrlr->setTargetPosition( mPlayer->getPosition() ); - ctrlr->setTargetOrientation( mPlayer->getOrientation() ); - } - - // - currCamCtrlr->update( timeElapsed ); - - // prepare for next step - mActiveActions.clear(); - mMouseMovement = Vector3::kZero; - - //std::cout << this->mPlayerRep->getPosition() << "\n"; - - if (this->getApp().getKeyboard()->isKeyDown(input::KC_ADD)) - { - real physicsTimeFactor = this->getPhysicsTimeFactor(); - physicsTimeFactor += real(0.1) * timeElapsed; - this->setPhysicsTimeFactor( physicsTimeFactor ); - std::cout << "factor = " << this->getPhysicsTimeFactor() << "\n"; - } - if (this->getApp().getKeyboard()->isKeyDown(input::KC_SUBTRACT)) - { - real physicsTimeFactor = this->getPhysicsTimeFactor(); - physicsTimeFactor -= real(0.1) * timeElapsed; - if (physicsTimeFactor < 0.) physicsTimeFactor = 0.; - this->setPhysicsTimeFactor( physicsTimeFactor ); - std::cout << "factor = " << this->getPhysicsTimeFactor() << "\n"; - } - } -private: - void onNextCamera() - { - ++mCurrentCamController; - if (mCurrentCamController >= mCamControllers.size()) - mCurrentCamController = 0; - } - void onMouseMoveXY(const input::ActionMap::ActionResult& ar) - { - mMouseMovement = ar.signal * 10.; - std::swap( mMouseMovement.y, mMouseMovement.z ); - mMouseMovement.y = 0.; - } - void onMouseWheel(const input::ActionMap::ActionResult& ar) - { - /** @todo move out into CameraControllerBase::init() ... - if (fabs(ar.signal.z) < std::numeric_limits<real>::epsilon()) - return; - - const real fac = real(1.0 - 0.1 * ar.signal.z); // either 0.9 or 1.1 - - // scale the target offset - Vector3 targetOffset = mTopDownCtrlr.getTargetOffset() * fac; - - // keep a minimum length - if (targetOffset.length() < 5.) // min length - targetOffset = targetOffset.normalisedCopy() * 5.; - - // apply - mTopDownCtrlr.setTargetOffset( targetOffset ); - */ - } -private: - model::Model* mGround; - input::ActionMap mActionMap; - - typedef std::set<input::ActionId> ActionIdList; - ActionIdList mActiveActions; - - Env* mEnv; - - typedef SharedPtr<CameraControllerBase> CameraControllerPtr; - typedef std::deque<CameraControllerPtr> CameraControllerList; - CameraControllerList mCamControllers; - int mCurrentCamController; - - Vector3 mMouseMovement; - - SharedPtr<ControllableCharacter> mPlayer; -}; - -/** The mighty application itself! */ -class TheApp : public raf::ExampleApplication<TheConfiguration> -{ -public: - TheApp() {} -protected: - virtual raf::MainState* createMainState() - { - return new TheMainState(*this); - } -}; - -#define WIN32_LEAN_AND_MEAN -#include <windows.h> - -int main( int argc, char** argv ) -{ - // @todo fixme: Workaround on windows because of different timers on different cores... - ::SetProcessAffinityMask( ::GetCurrentProcess(), 0x01 ); - ::SetThreadAffinityMask( ::GetCurrentThread(), 0x01 ); - - // Use default executor for convenience. - // It's always possible to manually execute TheApp::initialise() etc. - TheApp theApp; - return (raf::runApplication( theApp )) ? 0 : 1; -} - Deleted: trunk/yake/samples/misc/cmdrmayhem/yakePCH.cpp =================================================================== --- trunk/yake/samples/misc/cmdrmayhem/yakePCH.cpp 2007-02-07 23:26:34 UTC (rev 1612) +++ trunk/yake/samples/misc/cmdrmayhem/yakePCH.cpp 2007-02-07 23:31:46 UTC (rev 1613) @@ -1 +0,0 @@ -#include <yapp/samples/misc/cmdrmayhem/yakePCH.h> Deleted: trunk/yake/samples/misc/cmdrmayhem/yakePCH.h =================================================================== --- trunk/yake/samples/misc/cmdrmayhem/yakePCH.h 2007-02-07 23:26:34 UTC (rev 1612) +++ trunk/yake/samples/misc/cmdrmayhem/yakePCH.h 2007-02-07 23:31:46 UTC (rev 1613) @@ -1,10 +0,0 @@ -//============================================================================ -// IMPLEMENTATION HEADERS -//============================================================================ -// STL -#include <iostream> -// Yake -#include <yake/base/yake.h> -#include <yake/scripting/yakeScriptingSystem.h> -#include <yapp/base/yapp.h> -#include <yake/ent/ent.h> Deleted: trunk/yake/samples/misc/vehicle/yakeDemo.cpp =================================================================== --- trunk/yake/samples/misc/vehicle/yakeDemo.cpp 2007-02-07 23:26:34 UTC (rev 1612) +++ trunk/yake/samples/misc/vehicle/yakeDemo.cpp 2007-02-07 23:31:46 UTC (rev 1613) @@ -1,719 +0,0 @@ -#include <yapp/samples/misc/vehicle/yakePCH.h> -#include <yake/audio/yakeAudio.h> -#include <yapp/raf/yakeRaf.h> -#include <yake/model/model.h> -#include <yake/model/model_link.h> -#include <yapp/vehicle/yakeVehicle.h> -#include <yake/input/yakeInput.h> - -// temporary stuff (until factory registration issues have been sorted out): -#include <yapp/vehicle/yakeNativeOde.h> - -using namespace yake; - -const input::ActionId ACTIONID_BRAKE( input::ACTIONID_USER+1, "brake" ); -const input::ActionId ACTIONID_TOGGLE_VEHICLE( input::ACTIONID_USER+2, "toggle_vehicle" ); -const real razorMeshScale = real(0.1); - -/** Configuration of the application */ -struct TheConfiguration : public raf::ApplicationConfiguration -{ - virtual StringVector getLibraries() - { return MakeStringVector() << "graphicsOgre" << "inputOgre" << "physicsOde"; } - - //virtual StringVector getScriptingSystems() - //{ return MakeStringVector() << "lua"; } - - virtual StringVector getGraphicsSystems() - { return MakeStringVector() << "ogre3d"; } - - virtual StringVector getInputSystems() - { return MakeStringVector() << "ogre"; } - - virtual StringVector getPhysicsSystems() - { return MakeStringVector() << "ode"; } -}; - -class VehicleHumanInputController -{ -public: - void setVehicle(vehicle::IVehicle*); -}; - -/** Main application state */ -class TheMainState : public raf::RtMainState -{ -public: - TheMainState(raf::Application& owner) : - raf::RtMainState(owner), - mGround(0), - mActive(0) - { - enableInstantQuitByKey( input::KC_ESCAPE ); - } - ~TheMainState() - { - } -private: - void onModelComponent_preInit(const model::ComponentCreationContext& ctx, model::ModelComponent&) - { - YAKE_LOG("demo: onModelComponent_preInit()"); - } - void onModelComponent_postInit(const model::ComponentCreationContext& ctx, model::ModelComponent&) - { - YAKE_LOG("demo: onModelComponent_postInit()"); - } -protected: - virtual void onCreateScene() - { - YAKE_LOG_INFORMATION("Creating scene"); - - // create vehicle system - mVehicleSystem.reset(new vehicle::GenericVehicleSystem()); - - // set up the model creation context. - mModelMgr.setCreationContext_GraphicalWorld( getGraphicalWorld() ); - mModelMgr.setCreationContext_PhysicalWorld( getPhysicalWorld() ); - mModelMgr.setCreationContext_CentralController( &mCentralController ); - mModelMgr.setCreationContext_NamedParameter("vehicleSystem",static_cast<vehicle::IVehicleSystem*>(mVehicleSystem.get())); - - // set up model component creation hooks. - mModelMgr.subscribeToPreInitializeComponentSignal( Bind2(&TheMainState::onModelComponent_preInit,this) ); - mModelMgr.subscribeToPostInitializeComponentSignal( Bind2(&TheMainState::onModelComponent_postInit,this) ); - - - - // create a light - graphics::ILight* pLight = getGraphicalWorld()->createLight(); - pLight->setType( graphics::ILight::LT_DIRECTIONAL ); - pLight->setDirection( Vector3(0,-1,1) ); - getGraphicalWorld()->createSceneNode("lightnode0")->attachLight( pLight ); - - getGraphicalWorld()->setShadowsEnabled( true ); - - // set up camera - getDefaultCamera()->setNearClipDistance( 1 ); - getDefaultCamera()->setFixedYawAxis(Vector3::kUnitY); - getDefaultCamera()->setPosition(Vector3(7,4,-7)); - - // - getPhysicalWorld()->setGlobalGravity(Vector3(0,real(-9.81),0)); - getPhysicalWorld()->setCurrentSolverParam("stepsize",real(0.05)); - - // create ground - mGround = new model::Model(); - { - const real groundHeight = -2; - // visual - graphics::ISceneNode* pGroundSN = getGraphicalWorld()->createSceneNode(); - graphics::IEntity* pGroundE = getGraphicalWorld()->createEntity("plane_1x1.mesh"); - pGroundE->setMaterial("box"); - pGroundE->setCastsShadow( false ); - pGroundSN->attachEntity( pGroundE ); - pGroundSN->setScale( Vector3(200,1,200) ); - pGroundSN->setPosition( Vector3(0,groundHeight,0) ); - - model::Graphical* pG = new model::Graphical(); - pG->addSceneNode( pGroundSN, "groundSN" ); - mGround->addComponent( pG ); - - // physical - physics::IActorPtr pGroundPlane = getPhysicalWorld()->createActor( physics::ACTOR_STATIC ); - pGroundPlane->createShape( physics::IShape::PlaneDesc( Vector3(0,1,0), groundHeight ) ); - - model::Physical* pP = new model::Physical(); - pP->addActor( pGroundPlane, "groundPlane" ); - mGround->addComponent( pP ); - } - - // materials @todo read from .physics: - getPhysicalWorld()->createMaterial( physics::IMaterial::Desc( 0.01f, 0.01f, 0.01f ), "chassis" ); - getPhysicalWorld()->createMaterial( physics::IMaterial::Desc( 0.01f, 0.2f, 0.01f ), "chassisTop" ); - getPhysicalWorld()->createMaterial( physics::IMaterial::Desc( 0.01f, 0.5f, 0.01f ), "wheel" ); - - // vehicle(s) - - YAKE_ASSERT( mVehicleSystem.get() ); - mVehicleSystem->loadTemplates("../../media/vehicles/delorean.xml"); - mVehicleSystem->loadTemplates("../../media/vehicles/jet.xml"); - - // It's possible retrieve the template and make further adjustments to it before - // instantiating vehicles. - // e.g.: vehicle::VehicleTemplate* tpl = pVS->getTemplate("delorean"); - - // sky box - getGraphicalWorld()->setSkyBox("Examples/SpaceSkyBox"); - - // create car - mCar.reset( new Car() ); - mCar->init(mCentralController,mModelMgr,*getGraphicalWorld(),*mVehicleSystem); - - // create Jet - mJet.reset( new Jet() ); - mJet->init(mCentralController,mModelMgr,*getGraphicalWorld(),*mVehicleSystem); - } - virtual void onDestroyScene() - { - mCar.reset(); - mJet.reset(); - - mModelMgr.clear(); - mVehicleSystem.reset(); - - YAKE_SAFE_DELETE( mGround ); - } - virtual void onEnter() - { - RtMainState::onEnter(); - - mActionMap.reg( ACTIONID_TOGGLE_VEHICLE, - new input::KeyboardActionCondition( getApp().getKeyboard(), input::KC_T, input::KAM_RELEASED ) ); - mActionMap.subscribeToActionIdV( ACTIONID_TOGGLE_VEHICLE, boost::bind(&TheMainState::toggleVehicle,this) ); - - YAKE_ASSERT( !mActive ); - mActive = mCar.get(); - mActive->onEnter(mActionMap,getApp().getKeyboard()); - - getPhysicalWorld()->subscribeToPreStepInternal( - boost::bind(&TheMainState::preStep,this,_1) ); - } - virtual void onExit() - { - YAKE_ASSERT( mActive ); - if (mActive) - { - mActive->onExit(); - mActive = 0; - } - - RtMainState::onExit(); - } - void preStep(real stepSize) - { - std::cout << "demo: preStep (dt=" << stepSize << ")\n"; - const real timeElapsed = stepSize;//1. / 20.; - - mActionMap.update(); - - mCentralController.triggerPhysicsUpdateSignal(timeElapsed); - - if (mCar) - mCar->onFrame( timeElapsed ); - if (mJet) - mJet->onFrame( timeElapsed ); - } - virtual void onFrame(const real timeElapsed) - { - mCentralController.triggerGraphicsUpdateSignal(0,timeElapsed); - - if (mActive) - { - getDefaultCamera()->lookAt(mActive->getPosition()); - } - } -private: - model::Model* mGround; - - model::ModelManager mModelMgr; - model::CentralControllerBase mCentralController; - SharedPtr<vehicle::IVehicleSystem> mVehicleSystem; - - input::ActionMap mActionMap; - - struct GoVehicleBase - { - virtual ~GoVehicleBase() {} - virtual Vector3 getPosition() const = 0; - virtual void onEnter(input::ActionMap& actionMap, input::KeyboardDevice* keyboard) = 0; - virtual void onExit() - { - for( SignalConnectionList::iterator it = mInputSignalConnections.begin(); it != mInputSignalConnections.end(); ++it ) - it->disconnect(); - mInputSignalConnections.clear(); - - for( ConditionConnectionList::iterator it = mInputConditionConnections.begin(); it != mInputConditionConnections.end(); ++it ) - it->disconnect(); - mInputConditionConnections.clear(); - } - virtual void onFrame(const real timeElapsed) = 0; - void addInputSignalConnection(const SignalConnection& conn) - { - mInputSignalConnections.push_back( conn ); - } - void addInputConditionConnection(const input::ConditionConnection& conn) - { - mInputConditionConnections.push_back( conn ); - } - private: - typedef std::deque<SignalConnection> SignalConnectionList; - SignalConnectionList mInputSignalConnections; - typedef std::deque<input::ConditionConnection> ConditionConnectionList; - ConditionConnectionList mInputConditionConnections; - }; - struct Car : public GoVehicleBase - { - Car() : mVehicle(0) - {} - ~Car() - { - destroy(); - } - virtual Vector3 getPosition() const - { - YAKE_ASSERT( mVehicle ); - return mVehicle->getChassisPosition(); - } - - void init(model::CentralControllerBase& centralController,model::ModelManager& modelMgr,graphics::IWorld& gworld,vehicle::IVehicleSystem& vehSys) - { - // instantiate vehicle model (physics + representation containers) - YAKE_ASSERT( !mModel ); - mModel = modelMgr.createModel("theCar", - "physics/empty:name=p" - "|graphics/empty:name=g" - "|yake/dotVehicle:name=veh;template=delorean;physical=p" - ); - YAKE_ASSERT( mModel ); - vehicle::VehicleModelComponent* vehComp = static_cast<vehicle::VehicleModelComponent*>(mModel->getComponentByTag("veh")); - YAKE_ASSERT( vehComp ); - mVehicle = vehComp->getVehicle(); - YAKE_ASSERT( mVehicle ); - - // create visuals - - model::Graphical* pG = dynamic_cast<model::Graphical*>(mModel->getComponentByTag("g")); - YAKE_ASSERT( pG ); - - //mVehicle->enableDebugGeometry( *getGraphicalWorld() ); - - // create visuals - // - ship body - graphics::ISceneNode* pSN = gworld.createSceneNode("root"); - graphics::IEntity* pE = gworld.createEntity("delorean.mesh"); - pE->setCastsShadow( true ); - pSN->attachEntity( pE ); - //pSN->setScale( Vector3::kUnitScale * razorMeshScale ); - pG->addSceneNode(pSN, "delorean_root"); - - // - wheel visuals - if (mVehicle->getWheelInterface("leftFrontWheel")) - { - _createCarWheelVisual( centralController, gworld, "leftFrontWheel", *pSN ); - _createCarWheelVisual( centralController, gworld, "rightFrontWheel", *pSN ); - _createCarWheelVisual( centralController, gworld, "leftRearWheel", *pSN ); - _createCarWheelVisual( centralController, gworld, "rightRearWheel", *pSN ); - } - - // create visual <-> physics links - model::ModelMovableLink* pLink = mModel->createLink( mVehicle->getChassisMovable(), pSN ); - centralController.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableLink::update,pLink) ); - } - void destroy() - { - //@todo - mModel.reset(); - mVehicle = 0; - } - virtual void onEnter(input::ActionMap& actionMap, input::KeyboardDevice* keyboard) - { - using namespace input; - - // front wheel controls - - this->addInputConditionConnection( - actionMap.reg( ACTIONID_LEFT, - new input::KeyboardActionCondition( keyboard, KC_LEFT, KAM_CONTINUOUS ) ) ); - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_LEFT, boost::bind(&Car::onFrontWheelLeft,this) ) ); - - this->addInputConditionConnection( - actionMap.reg( ACTIONID_RIGHT, - new input::KeyboardActionCondition( keyboard, KC_RIGHT, KAM_CONTINUOUS ) ) ); - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_RIGHT, boost::bind(&Car::onFrontWheelRight,this) ) ); - - this->addInputConditionConnection( - actionMap.reg( ACTIONID_FORWARD, - new input::KeyboardActionCondition( keyboard, KC_UP, KAM_CONTINUOUS ) ) ); - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_FORWARD, boost::bind(&Car::onForward,this) ) ); - - this->addInputConditionConnection( - actionMap.reg( ACTIONID_BRAKE, - new input::KeyboardActionCondition( keyboard, KC_DOWN, KAM_CONTINUOUS ) ) ); - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_BRAKE, boost::bind(&Car::onReverse,this) ) ); - } - void onExit() - { - GoVehicleBase::onExit(); - } - virtual void onFrame(const real timeElapsed) - { - vehicle::IEnginePtrList engines = mVehicle->getEngineInterfaces(); - ConstDequeIterator< vehicle::IEnginePtrList > itEngine( engines ); - while (itEngine.hasMoreElements()) - { - vehicle::IEngine* pEngine = itEngine.getNext(); - pEngine->setInputSignal( pEngine->getInputSignal() - timeElapsed * 1.7 ); - } - - real steering0 = 0; - real braking0 = 0; - - ConstDequeIterator< ActionIdList > itAction( mActiveActions ); - while (itAction.hasMoreElements()) - { - const input::ActionId activeId = itAction.getNext(); - if (activeId == input::ACTIONID_FORWARD) - mVehicle->getEngineInterface("main")->setInputSignal(1.); - else if (activeId == ACTIONID_BRAKE) - braking0 = 1.; - else if (activeId == input::ACTIONID_LEFT) - steering0 -= real(0.7); - else if (activeId == input::ACTIONID_RIGHT) - steering0 += real(0.7); - } - mVehicle->setSteering( 0, steering0 ); - mVehicle->getWheelInterface("leftFrontWheel")->brake(braking0); - mVehicle->getWheelInterface("rightFrontWheel")->brake(braking0); - - mVehicle->updateSimulation( timeElapsed ); - - ConstDequeIterator< WheelPsMap > itWheel( mWheelPs ); - while (itWheel.hasMoreElements()) - { - const String wheelId = itWheel.getNext().first; - mWheelPs[ wheelId ]->setEmissionRate( 0, mEmitterEmissionRate[wheelId] * mVehicle->getWheelInterface( wheelId )->getSkid() ); - } - - mActiveActions.clear(); - } - private: - vehicle::IVehicle* mVehicle; - model::ModelPtr mModel; - typedef AssocVector<String,real> EmitterRealMap; - EmitterRealMap mEmitterMinVel; - EmitterRealMap mEmitterMaxVel; - EmitterRealMap mEmitterEmissionRate; - typedef AssocVector<String,graphics::IParticleSystem*> WheelPsMap; - WheelPsMap mWheelPs; - - typedef std::set<input::ActionId> ActionIdList; - ActionIdList mActiveActions; - - private: - void onForward() - { mActiveActions.insert( input::ACTIONID_FORWARD ); } - void onReverse() - { mActiveActions.insert( ACTIONID_BRAKE ); } - void onUp() - { mActiveActions.insert( input::ACTIONID_UP ); } - void onFrontWheelLeft() - { mActiveActions.insert( input::ACTIONID_LEFT ); } - void onFrontWheelRight() - { mActiveActions.insert( input::ACTIONID_RIGHT ); } - void _createCarWheelVisual(model::CentralControllerBase& centralController, graphics::IWorld& gworld, const String& wheelId, graphics::ISceneNode& parentSN) - { - YAKE_ASSERT( mModel ); - YAKE_ASSERT( mVehicle ); - - // scene node + wheel mesh - graphics::ISceneNode* pSN = gworld.createSceneNode(); - graphics::IEntity* pE = gworld.createEntity("wheel1.mesh"); - pE->setCastsShadow( true ); - pSN->attachEntity( pE ); - - model::ModelMovableLink* pLink = mModel->createLink( mVehicle->getWheelInterface(wheelId), pSN ); - centralController.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableLink::update,pLink) ); - - // scene node + particle system for smoke... - pSN = gworld.createSceneNode(); - graphics::IParticleSystem* pPS = gworld.createParticleSystem("SkidSmoke"); - mWheelPs[wheelId] = pPS; - mEmitterEmissionRate[wheelId] = pPS->getEmissionRate(0); - pSN->attachParticleSystem( pPS ); - - pLink = new model::ModelMovableDirectLink(); - pLink->setSource( mVehicle->getWheelInterface(wheelId) ); - pLink->subscribeToPositionChanged( pSN ); //position only! - mModel->addLink( pLink ); - centralController.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableLink::update,pLink) ); - } - }; - - struct Jet : public GoVehicleBase - { - Jet() : mModel(), mVehicle(0) - {} - ~Jet() - { - destroy(); - } - virtual Vector3 getPosition() const - { - YAKE_ASSERT( mVehicle ); - return mVehicle->getChassisPosition(); - } - void init(model::CentralControllerBase& centralController,model::ModelManager& modelMgr,graphics::IWorld& gworld,vehicle::IVehicleSystem& vehSys) - { - YAKE_ASSERT( !mModel ); - mModel = modelMgr.createModel("theJet", - "physics/empty:name=p" - "|graphics/empty:name=g" - "|yake/dotVehicle:name=veh;template=jet;physical=p" - ); - YAKE_ASSERT( mModel ); - vehicle::VehicleModelComponent* vehComp = static_cast<vehicle::VehicleModelComponent*>(mModel->getComponentByTag("veh")); - YAKE_ASSERT( vehComp ); - mVehicle = vehComp->getVehicle(); - YAKE_ASSERT( mVehicle ); - - mVehicle->translate(Vector3(-30,0,30)); - - // create visuals - - model::Graphical* pG = dynamic_cast<model::Graphical*>(mModel->getComponentByTag("g")); - YAKE_ASSERT( pG ); - - // - ship body - graphics::ISceneNode* pSN = gworld.createSceneNode(); - pSN->attachEntity( gworld.createEntity("razor.mesh") ); - pSN->setScale( math::Vector3::kUnitScale * razorMeshScale ); - pG->addSceneNode(pSN,"root"); - - YAKE_LOG( "Creating thruster visuals" ); - // - thruster visuals - _createThrusterVisual( centralController, gworld, "left", "left", *pSN ); - _createThrusterVisual( centralController, gworld, "right", "right", *pSN ); - _createThrusterVisual( centralController, gworld, "front", "backward", *pSN ); - _createThrusterVisual( centralController, gworld, "rear", "forward", *pSN ); - _createThrusterVisual( centralController, gworld, "bottom", "upward", *pSN ); - _createThrusterVisual( centralController, gworld, "top", "downward", *pSN ); - - // - wheel visuals - if (mVehicle->getWheelInterface("frontWheel")) - { - _createWheelVisual( centralController, gworld, "frontWheel", *pSN ); - _createWheelVisual( centralController, gworld, "leftRearWheel", *pSN ); - _createWheelVisual( centralController, gworld, "rightRearWheel", *pSN ); - } - - // create visual <-> physics links - model::ModelMovableLink* pLink = mModel->createLink( mVehicle->getChassisMovable(), pSN ); - centralController.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableLink::update,pLink) ); - } - void destroy() - { - //@todo - mModel.reset(); - mVehicle = 0; - } - virtual void onEnter(input::ActionMap& actionMap, input::KeyboardDevice* keyboard) - { - using namespace input; - - // load key<->action bindings - ActionMap::loadFromFile( actionMap, "../../media/vehicles/demo.actionmap.txt", keyboard, boost::bind(&Jet::addInputConditionConnection,this,_1) ); - - // front wheel controls - - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_LEFT, boost::bind(&Jet::onFrontWheelLeft,this) ) ); - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_RIGHT, boost::bind(&Jet::onFrontWheelRight,this) ) ); - - // thruster controls - - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_STRAFE_LEFT, boost::bind(&Jet::onStrafeLeft,this) ) ); - - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_STRAFE_RIGHT, boost::bind(&Jet::onStrafeRight,this) ) ); - - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_FORWARD, boost::bind(&Jet::onForward,this) ) ); - - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_REVERSE, boost::bind(&Jet::onReverse,this) ) ); - - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_UP, boost::bind(&Jet::onUp,this) ) ); - - this->addInputSignalConnection( - actionMap.subscribeToActionIdV( ACTIONID_DOWN, boost::bind(&Jet::onDown,this) ) ); - } - virtual void onExit() - { - GoVehicleBase::onExit(); - } - virtual void onFrame(const real timeElapsed) - { - vehicle::IEnginePtrList engines = mVehicle->getEngineInterfaces(); - ConstDequeIterator< vehicle::IEnginePtrList > itEngine( engines ); - while (itEngine.hasMoreElements()) - { - vehicle::IEngine* pEngine = itEngine.getNext(); - pEngine->setInputSignal( std::max(0., pEngine->getInputSignal() - timeElapsed * 1.7) ); - } - - real steering0 = 0; - - ConstDequeIterator< ActionIdList > itAction( mActiveActions ); - while (itAction.hasMoreElements()) - { - const input::ActionId activeId = itAction.getNext(); - if (activeId == input::ACTIONID_STRAFE_LEFT) - mVehicle->getEngineInterface("right")->setInputSignal(1.); - else if (activeId == input::ACTIONID_STRAFE_RIGHT) - mVehicle->getEngineInterface("left")->setInputSignal(1.); - else if (activeId == input::ACTIONID_FORWARD) - mVehicle->getEngineInterface("forward")->setInputSignal(1.); - else if (activeId == input::ACTIONID_REVERSE) - mVehicle->getEngineInterface("backward")->setInputSignal(1.); - else if (activeId == input::ACTIONID_UP) - mVehicle->getEngineInterface("upward")->setInputSignal(1.); - else if (activeId == input::ACTIONID_DOWN) - mVehicle->getEngineInterface("downward")->setInputSignal(1.); - else if (activeId == input::ACTIONID_LEFT) - steering0 -= 0.3; - else if (activeId == input::ACTIONID_RIGHT) - steering0 += 0.3; - } - mVehicle->setSteering( 0, steering0 ); - - mVehicle->updateSimulation( timeElapsed ); - - _updateThrusterPs(); - - mActiveActions.clear(); - } - private: - vehicle::IVehicle* mVehicle; - model::ModelPtr mModel; - - typedef AssocVector<String,real> EmitterRealMap; - EmitterRealMap mEmitterMinVel; - EmitterRealMap mEmitterMaxVel; - EmitterRealMap mEmitterEmissionRate; - typedef AssocVector<String,graphics::IParticleSystem*> ThrusterPsMap; - ThrusterPsMap mThrusterPs; - input::ActionMap mActionMap; - - typedef std::set<input::ActionId> ActionIdList; - ActionIdList mActiveActions; - - private: - void onStrafeLeft() - { mActiveActions.insert( input::ACTIONID_STRAFE_LEFT ); } - void onStrafeRight() - { mActiveActions.insert( input::ACTIONID_STRAFE_RIGHT ); } - void onForward() - { mActiveActions.insert( input::ACTIONID_FORWARD ); } - void onReverse() - { mActiveActions.insert( input::ACTIONID_REVERSE ); } - void onUp() - { mActiveActions.insert( input::ACTIONID_UP ); } - void onDown() - { mActiveActions.insert( input::ACTIONID_DOWN ); } - void onFrontWheelLeft() - { mActiveActions.insert( input::ACTIONID_LEFT ); } - void onFrontWheelRight() - { mActiveActions.insert( input::ACTIONID_RIGHT ); } - void _createThrusterVisual(model::CentralControllerBase& centralController, graphics::IWorld& gworld, const String& mtPtId, const String& engineId, graphics::ISceneNode& parentSN) - { - graphics::ISceneNode* pSN = parentSN.createChildNode( mtPtId ); - - graphics::IParticleSystem* pPS = gworld.createParticleSystem("thruster2"); - pSN->attachParticleSystem( pPS ); - - YAKE_ASSERT( mModel ); - YAKE_ASSERT( mVehicle ); - model::ModelMovableLink* pLink = mModel->createLink( mVehicle->getMountPoint(mtPtId), pSN ); - centralController.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableLink::update,pLink) ); - - _regThrusterPs( engineId, *pPS ); - } - void _createWheelVisual(model::CentralControllerBase& centralController, graphics::IWorld& gworld, const String& wheelId, graphics::ISceneNode& parentSN) - { - graphics::ISceneNode* pSN = gworld.createSceneNode(); - graphics::IEntity* pE = gworld.createEntity("sphere_d1.mesh"); - pSN->attachEntity( pE ); - const math::Vector3 scale = math::Vector3::kUnitScale * 2.f * mVehicle->getWheelInterface(wheelId)->getRadius(); - pSN->setScale( scale ); - - YAKE_ASSERT( mModel ); - YAKE_ASSERT( mVehicle ); - model::ModelMovableLink* pLink = mModel->createLink( mVehicle->getWheelInterface(wheelId), pSN ); - centralController.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableLink::update,pLink) ); - } - void _regThrusterPs(const String& engineId, graphics::IParticleSystem& ps) - { - mEmitterMinVel[ engineId ] = ps.getMinVelocity(0); - mEmitterMaxVel[ engineId ] = ps.getMaxVelocity(0); - mEmitterEmissionRate[ engineId ] = ps.getEmissionRate(0); - mThrusterPs[ engineId ] = &ps; - } - void _updateThrusterPs() - { - ConstDequeIterator< ThrusterPsMap > itM( mThrusterPs ); - while (itM.hasMoreElements()) - { - std::pair<String,graphics::IParticleSystem*> p = itM.getNext(); - const String mtPtId = p.first; - graphics::IParticleSystem* ps = p.second; - const real throttle = mVehicle->getEngineInterface(mtPtId)->getInputSignal(); - - real rate = throttle * mEmitterEmissionRate[ mtPtId ]; - ps->setEmissionRate( 0, rate ); - //std::cout << "r=" << rate << " t=" << throttle << "\n"; - - real vel = throttle * mEmitterMaxVel[ mtPtId ]; - ps->setMaxVelocity( 0, vel ); - - vel = throttle * mEmitterMinVel[ mtPtId ]; - ps->setMinVelocity( 0, vel ); - } - } - }; - SharedPtr<Jet> mJet; - SharedPtr<Car> mCar; - GoVehicleBase* mActive; - void toggleVehicle() - { - // 1st time - if (!mActive) - mActive = mCar.get(); - else - mActive->onExit(); - - // toggle - if (mActive == static_cast<GoVehicleBase*>(mJet.get())) - mActive = mCar.get(); - else - mActive = mJet.get(); - - mActive->onEnter(mActionMap,getApp().getKeyboard()); - } -}; - -/** The mighty application itself! */ -class TheApp : public raf::ExampleApplication<TheConfiguration> -{ -public: - TheApp() {} -protected: - virtual raf::MainState* createMainState() - { - return new TheMainState(*this); - } -}; - -int main( int argc, char** argv ) -{ - // Use default executor for convenience. - // It's always possible to manually execute TheApp::initialise() etc. - TheApp theApp; - return (raf::runApplication( theApp )) ? 0 : 1; -} - Deleted: trunk/yake/samples/misc/vehicle/yakePCH.cpp =================================================================== --- trunk/yake/samples/misc/vehicle/yakePCH.cpp 2007-02-07 23:26:34 UTC (rev 1612) +++ trunk/yake/samples/misc/vehicle/yakePCH.cpp 2007-02-07 23:31:46 UTC (rev 1613) @@ -1 +0,0 @@ -#include <yapp/samples/misc/vehicle/yakePCH.h> Deleted: trunk/yake/samples/misc/vehicle/yakePCH.h =================================================================== --- trunk/yake/samples/misc/vehicle/yakePCH.h 2007-02-07 23:26:34 UTC (rev 1612) +++ trunk/yake/samples/misc/vehicle/yakePCH.h 2007-02-07 23:31:46 UTC (rev 1613) @@ -1,9 +0,0 @@ -//============================================================================ -// IMPLEMENTATION HEADERS -//============================================================================ -// STL -#include <iostream> -// Yake -#include <yake/base/yake.h> -#include <yake/scripting/yakeScriptingSystem.h> -#include <yapp/base/yapp.h> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |