没有合适的资源?快使用搜索试试~ 我知道了~
Gamebryo简单的入门材料3
4星 · 超过85%的资源 需积分: 12 10 下载量 105 浏览量
2010-03-12
09:47:48
上传
评论
收藏 4.63MB PDF 举报
温馨提示
试读
21页
Gamebryo简单的入门材料3 使用状态机,CEGUI和gamebryo构造一个简单游戏框架,代码简洁易懂,步骤详细.
资源推荐
资源详情
资源评论
ImplementingGameplayElementsUsingGamebryo
Chapter3:ScriptingSystemIntegration1
Chapter3–ScriptingSystemIntegration
WhyScript?
If you ask ten game developers from different studios whetherornottheybelievean upcoming
title will benefit from some sort of scripting language interface, you will likely get ten strong
opinions, with some in favor of scripting and others against. Scripting doesn’t make sense as
standard practice for all
games; however, it would be hard to dispute the immense success that
scriptinghasbroughttothemakersandtheplayersofsomecommercialgames.Therearemany
valid reasons for integrating a scripting system into a game. From a software development
perspective, scripting has the potential to improve productivity
during game construction, for
exampleinthefollowingways:
• Enablesrapid‐prototypingofgameplayelements
• Enables technical level designers and artists to author art and design‐driven behaviors
withouthavingtoinvolvedengineorgameplayprogrammers
In this chapter, we are going tobegin implementing a scripting system in
our gameapplication,
and in Chapter 4 we will continue the scripting system integration, while at the same time
implementingsomescript‐drivengameplay.
Prerequisites
Startingwiththischapter,thesamplegameapplicationrequiresthatyou havethefollowingtwo
softwarepackagesinstalled:
• Arecentversion ofPythonorStacklessPython,availablefromhttp://www.python.organd
http://www.stackless.com respectively. Install it, and configure the Visual Studio include
and library search paths with references to the corresponding
Python installation paths.
Youalsomustadda referencetothestacklessspecificincludepath.Ifyouhaveinstalled
theprebuiltversionofStacklessPython,theStacklessinclude pathwillbethesameasthe
base Python include path with “/Stackless” appended. Note that you may wish to
download source code,
compile, and use your own build of Python/Stackless Python, so
thatyouwillhaveaccesstosourceleveldebugging.
• The latest version of the interface compiler, SWIG, available from http://www.swig.org.
Install SWIG and configure your system PATH environment variable to include the
locationof the SWIGexecutable.
Parts 2 and3of thischapterrequire thatswig.exe be in
thepath.
Part1:BasicScriptingLanguageIntegration
ChoiceofaScriptingLanguage
In the past, game developers would create their own custom scripting system when creating a
gamethatneededscripting.Thoughthereareafewstudiosthatstilluseacustomlanguage,most
ImplementingGameplayElementsUsingGamebryo
Chapter3:ScriptingSystemIntegration2
nowseemtobeusingopensourceinterpretedlanguagesasthebasisfortheirscriptsystems.As
ofearly2008,there arealargeandgrowingnumberofinterpretedlang uagesthataresuitablefor
game scripting, including Python, lua,
Ruby, Java, and GameMonkey. The TIOBE Programming
Community Index (http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html) tracks
the popularity of the top 50 programming languages, many of which are scripting languages.
Whichshouldyouchoose?Shouldyoutrytochoosetheonethatissupposedtobethefastest,or
the one with the smallest runtime?
The one with the best system for debugging, or the one for
whichthebesttoolsforgameintegrationexist?
Forthistutorialseries,wewillbeusingStacklessPython.Thisisnotthefastestscriptengine.Nor
is it the one with the smallest runt ime. But it has all
of the basic features we really need, and
many that we won’t necessarily need. It has good facilities for debugging. It has been used in
commercialgames,iswildlypopular,andhasawidespreadusercommunityforsuppo rt.Further,
anumberofgoodtoolsexistthatfacilitaterapidlyembeddingPython
intoaC++gameengine.
TheScriptSystemObject
To keep our software architecture rather simple, we are going to provide C++ access to the
scriptinglanguageviaanewsingletonobject,PythonScriptSystem.Thisobjectwillinitialize
Python when the game is launched, terminate Python when the game is being
shutdown, and
provide various mechanisms for running scripts and sharing information between C++ engine
codeandPythonscripts.
With Python, it is not difficult to setup a basic script system. The important parts of the
PythonScriptSystemheaderare:
class PythonScriptSystem
{
public:
bool RunScriptFile(const char *pkScriptFilename);
protected:
bool Init();
bool Terminate();
protected:
PyObject *m_pkDictionary;
};
There are member functions to initialize and terminate the script system, as well as a member
function to run Python code contained in a script file. There is also a member variable,
m_pkDictionary,whichstoresapointertoaPython dictionaryobject.Python usesdictionaries
to store name‐value pairs.
They are the mechanism by which Python stores local and global
variableswhilerunningcode.Forexample,ifyouwrite:
X = 3.0;
ImplementingGameplayElementsUsingGamebryo
Chapter3:ScriptingSystemIntegration3
in a Python script, the variable name “X” and its value are stored in a dictionary as a key‐value
pair.Dictionariesalsostorefunctionandclassdefinitions.Ourscriptingsystemobjectcreatesits
dictionary after Python is
initialized. The scripting system will use the dictionary to store
variablesandsomeofthePythoncodethatissharedbetweenC++andPython.
InPythonScriptSystem::Init,youwillseeacalltoPy_Initialize
,afunctionprovided
by the Python API that initializes the Python runtime. Init also creates the dictionary object,
thencallsanotherPythonAPIfunction,PyDict_SetItemString,tosetthevalueofaPython
variable named “__builtins__” on the new dictionary. Once set, this variable references
another Python dictionary, owned
by the Python runtime’s “__builtin__” module, which
containsmanyofthecoredatastructures,classes,types,andfunctionsthatmakeupthePython
language. The reference to the built‐in dictionary is necessary, allowin g Python code that we
execute using our custom dictionary to use basic Python language features. Finally,
PythonScriptSystem::Init calls a secondary function to run a startup script from the file
assets/scripts/startup.py.ThisstartupscriptwillbecomeimportantinPart2.
Next,takealookatPythonScriptSystem::Terminate.Thisfunctiondoesthereverseofthe
initfunction.However,thecall to the Py_XDECREFfunctionmayrequiresomeexplaining. This
function decrements the reference count of the passed‐in object (in this case a pointer to our
dictionary). Python, like Gamebryo, uses reference coun ting to implem ent a form of garbage
collection.Thesurprisingthinghereisthatwehaveareferencecountdecrement,butthereisno
increment on the
dictionary object in the script system class. We did not need the increment
because the function PyDict_New (called in Init to create the dictionary) happens to return
whatPythoncallsanewreference,areferencethathasalreadybeenincrementedforus.Theonly
waytoknowthisisto
readthePythonAPIdocumentation.
Another place in the code where a new reference is returned is in
PythonScriptSystem::RunScriptFile. In this case, we call Py_DECREF, not
Py_XDECREF. The difference between these two functions is that Py_XDECREF checks the
incomingpointertoensureitisnotNULLbeforeproceedingto
reducethereferencecount.Inthe
RunScriptFile member function, we explicitly test the pointer, so there is no need for the
separatetestofPy_XDECREF.
SomePythonAPIfunctionsreturnanobjectreferencewithoutincrementingthereference count.
Python calls these borrowed references. You must not decrement the reference count
of a
borrowed reference, since this may cause the object to be destroyed prematurely, while the
Python runtime expects it to remain valid. If you need to use a Python object with a borrowed
referencebeyondthescopeinwhichyouretrievedthereference,simplycallPy_XINCREFtoturn
it
intoanewreference.
InitializingandTerminatingPython
Our basic scriptingsystem simply provides a singleton object which contains member functions
forinitialization,termination,andrunningsimplePythonscriptsfromafile.ToaccessPython,all
ImplementingGameplayElementsUsingGamebryo
Chapter3:ScriptingSystemIntegration4
ourapplicationneedstodoiscalltheinitializationandterminationfunctionsattheappropriate
times, and call the provided function to run script. The most appropriate place to perform the
initialization and termination is within our GameObject class,
during startup and shutdown of
the game application. The scripting system is initialized inside GameObject::Initialize,
beforeanycustominitializationofthegameoccurs,asillustratedbelow:
1. // Initialize new components to work with the NiEntity reflection framework
2. CharacterComponent::_SDMInit();
3. ThirdPersonCameraComponent::_SDMInit();
4.
5. PythonScriptSystem::InitScripting();
6.
7. if (!NiApplication::Initialize())
8. return(false);
9.
10. // Initialize the state manager and register the 4 game states.
11. m_StateManager.Init();
12. RegisterBaseStates();
Theimporta nceofinitializingthescri pting systembeforethe initializingthegameisthatwecan
now run Python scripts during game initialization, providing a way to customize game startup
withoutwritingC++code.Inthisway,fullgamemodscanultimatelybedevelopedinscript.
The scripting system is terminated
inside GameObject::Terminate, after any custom
terminationcodehasbeenexecuted,incasethatcodeneedstoruncleanupscripts.
RunningtheGamewithBasicStartupandTerminateScripts
It is now time to run the game, to see the basic script system in action. Take a look at the file,
assets/scripts/startup.py,inthesamplecodedirectoryforPart1.Itreads,simply:
PI=3.14159265;
Thecode,obviously,assignsthevalue3.14159265toaPythonvariablenamed“PI”,andaddsitto
thedictionarythatwecreatedinC++.UsingthePythonAPIfunctionPyDict_GetItemString,
we c0uld retrieve the value of “PI” on the C++ side. But, actually, this script isn’t particularly
useful.
Run the
demo executable for Part 1. Place breakpoints if you wish. When the script runs, called
inside of PythonScriptSystem::RunScriptFile, there is no output to screen for you to
see.Thereisnoconsole,andwealsohavenotyetexposedanygameapplicationfunctionalityin a
waythatPythoncanaccess
it,sothegameapplicationcannottakeadvantageofanythingdonein
Python.Ourbasic scriptingsystem isnot very interesting.If youwish to provethatthe script is
beingrun,trywritingsomePythoncodetowritethevalueof“PI”out toatextfile.InPart2,
we
will add features that will immediately enable Python script to begin doing something
constructiveforthegame.
剩余20页未读,继续阅读
资源评论
- d3dxvector32014-01-02是有点简单 不过还是谢谢了!
智匪
- 粉丝: 0
- 资源: 6
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- Python实现MLP时间序列预测(完整源码和数据)
- 已过基于Hadoop+Spark招聘推荐可视化系统 大数据项目 毕业设计(源码下载)
- python爬虫开发题答案及题目-100(1).zip
- Python 小游戏 (贪吃蛇、五子棋、扫雷、俄罗斯方块)-3 (2).zip
- c语言实现的数独小游戏.zip
- 高德地图中国行政区划省、市、县经纬度
- March 2024 Expiration Of The OAM Out Of The Box Certificates
- 二叉搜索树迭代器(java代码).docx
- 解决keil MDK 5.38版本 在Debug配置使用STlink调试时软件闪退的问题
- py小项目:用户登录和注册系统开发欢迎图片
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功