SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Lua and Fable Jonathan Shaw
How does Fable use Lua? AI Quest scripts Camera Start-up settings Miscellaneous scripts Debugging Patching
A (very) brief history The original Fable used C++ as its “scripting” language, using macros to make it more “user friendly”. We used micro-threads (or fibres) to give each AI entity and each quest its own non-pre-emptive thread. We liked micro-threads, but didn’t like C++ as a scripting language.
Enter Lua Like all good scripting languages Lua is easy to write, and can give you almost-instant feedback when changing scripts while your game is running. Lua’s first class support for coroutines made Lua an ideal choice for Fable. Fable II and III make extensive use of coroutines. On busy levels we can have upwards of 100 coroutines running.
AI An AI entity in Fable II and III has a brain, defined in Fable’s general game editor. A brain has a list of behaviour groups with priorities (some of which can be the same). A behaviour group has a list of behaviours with priorities (some of which can be the same).
Deciding what behaviour to run Iterate through the behaviour groups, starting with the highest priority – see if they’re valid to run. E.g. a “work in the factory” behaviour group isn’t valid to run if it’s night time. For each valid behaviour group, iterate through the behaviours, starting with the highest priority, to see if they’re valid to run.
Same priority behaviours If some behaviours or behaviour groups have the same priority, we want to iterate through them in a random order. Custom iterators in Lua were the perfect solution for this design. Sadly, very nice to write, but a performance bottleneck, so we moved the logic to C++.
Quests A quest will have one “master” coroutine, with a number of “child” coroutines – when the master coroutine is finished we automatically kill the child coroutines. We have the concept of “entity threads” – these are automatically tied to specific entities and die when the entity dies (or suspend when the entity is unloaded when the player changes level).
Saving quests We wanted players to be able to save the game wherever they were in the game and for it to be a “perfect save” – without quest scripters having to do anything to make it work. Quite a challenge, until we learned about Pluto for Lua, by Ben Sunshine-Hill.
The patch challenge Using Pluto allows you to save coroutines and to resume them where they left off after loading the save game. What if you want to patch a function that a coroutine was yielded in? If you change the line numbering (of the resultant Lua byte code) before the final yield in the function, you can’t.
Nasty tricks This forces you to come up with some “creative” solutions.
Making it a little easier In Fable III some of our scripters have started changing how they format their while loops: while true do   -- Check for various  -- conditions and act  -- on them coroutine.yield() end while true do coroutine.yield()  -- Check for various  -- conditions and act  -- on them end
Bring on the Watch Dogs Lua is extremely flexible and inspectable. Add scripts to run in their own coroutines and inspect the state of the known problem scripts – when they detect the problem, fix it and shut down.
Lua/C++ interface We wanted it to be as easy as possible to register C++ functions in Lua. The more functions exposed to Lua, the more power you have when it comes to debugging and releasing DLC without requiring a Title Update. There were features in Fable II’s second DLC that we had to drop because the one function the scripts needed hadn’t been exposed.
Lua Plus Call Dispatcher We use Joshua Jensen’s Lua Plus Call Dispatcher. This lets you expose a function with any arbitrary signature to Lua (it doesn’t have to be a lua_Cfunction). You can describe to the call dispatcher how to interpret any type you might want to expose to Lua.
Hiding the Lua stack For a C++ programmer used to dealing with objects, it can be useful to be able to treat Lua tables and functions as C++ objects. Using inspiration from LuaPlus we wrote CLuaTable and CLuaFunction classes. These use the Lua registry to keep handles to the table and functions alive even if no handles to them in Lua remain.
A quick example class CEntity; class Vec3; Vec3 CEntity::GetPos() const; luaL_newmetatable(L, “EntityMetaTableName”); lua_pushvalue(L, -1); // Pushes the metatable lua_setfield(L, -2, "__index");// mt.__index = mt CLuaTableentity_mt (L);// This pops the metatable off the stack entity_mt.RegisterDirectMemberFunction<CEntity>( “GetPos", &CEntity::GetPos);
Using that in Lua local hero = GetHero() local trigger = GetEntity(“Trig1”) -- The hero is now within 10 units of the trigger while (hero:GetPos()-trigger:GetPos()):GetLength() > 10 do coroutine.yield() end while IsDistanceBetweenEntitiesOver(hero, trigger, 10) do coroutine.yield() end
Debugging Lua Lua provides debugging hooks to allow the creation of a debugger application without needing to modify any of the Lua source code. Our Lua Debugger supported breakpoints, step into, step over, per-coroutine breakpoints, a watch window and the ability to break into Lua from a C++ assert. Saving a file in the debugger would automatically reload it in the game.
Debugging with Lua Our in-game debug console ran in the game’s Lua environment. This meant everything scripts or AI could do, you could do in the console (including inspecting the current state of the AI and quests). On Fable III we have remote access to this same console (including niceties like auto-complete).
Automation Having remote access to the Lua environment means we can very easily write external scripts (ours are in Python) to drive the game however we like. We change start-up settings (so Lua is one of the first systems in the game we initialise) and test that every level in the game loads successfully, and get performance metrics from the game using this system.
Profiling Lua This is something we struggled with, partly due to our heavy reliance on coroutines. Profilers that hooked into function entries and exits wouldn’t stop the timer during yields, giving very skewed results. For Fable II, we didn’t have anything more sophisticated than manually timing suspected expensive functions and printing times to the debug output channel.
Memory usage When Fable II shipped Lua was using roughly 8 to 15Mb of memory. We had a custom allocator designed for many small, fragmenting allocations. Tracking memory “leaks” in Lua was extremely difficult. We found that pre-compiling our Lua scripts massively reduced fragmentation (in addition to the small improvement in loading time).
Reducing memory footprint Using Lua 5.1’s module system made demand-loading quest scripts very simple. Changing lua_Number to float from double saved us 1 or 2Mb, because those extra 4 bytes exist in every Lua type, whether table, Boolean, function, etc. The problem with floats comes when you want to pass 32 bit hashes or UIDs to and from Lua (because integers above 8 million lose precision when converted to floats).  Light user data was the solution.
Taming the garbage collector We turn the garbage collector off and manually run it once per game frame. We played around with the step size to try to balance the time the collector takes and the collector having enough time to clean up the general memory churn in any given frame. Even when we found a number we were reasonably happy with, the collector would sit at about 3ms, often spiking over 6ms.
Smoothing the spikes One of our colleagues from Turn 10 gave us the solution. To this: double start_time = LHTiming::GetTime(); double end_time = start_time + g_SecondsForGarbageCollection; // 2ms do { lua_gc(L, LUA_GCSTEP, 0); } while(LHTiming::GetTime() < end_time); ,[object Object],lua_gc(L, LUA_GCSTEP, 120);
Lua and Fable III We were very happy with our use of Lua in Fable II, so haven’t really changed that much with Lua in Fable III. Our quest scripts now support mid-quest “skip points” so that when debugging a quest you can now skip (forwards or backwards) to a decent number of points in the middle of quests. We’re using Kore in Fable III, which gives us improved performance and improved tools, including a profiler.
Conclusion Lua lets us develop systems quickly with fast iteration. Performance is an issue and can be too much of a “black box”. Having a rich and full interface between your game and scripting language will serve you well when it comes to extending the game.
References Lua: http://www.lua.org Pluto for Lua: http://luaforge.net/projects/pluto/ LuaPlus: http://luaplus.org Kore http://www.kore.net

Weitere ähnliche Inhalte

Was ist angesagt?

TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011bobmcwhirter
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxbobmcwhirter
 
TorqueBox for Rubyists
TorqueBox for RubyistsTorqueBox for Rubyists
TorqueBox for Rubyistsbobmcwhirter
 
DataMapper on Infinispan
DataMapper on InfinispanDataMapper on Infinispan
DataMapper on InfinispanLance Ball
 
Introduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter NotebooksIntroduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter NotebooksEueung Mulyana
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and SimpleBen Mabey
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread poolsmaksym220889
 
Clojure Fundamentals Course For Beginners
Clojure Fundamentals Course For Beginners Clojure Fundamentals Course For Beginners
Clojure Fundamentals Course For Beginners Paddy Lock
 
Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !Gaurav Behere
 
Redis: Lua scripts - a primer and use cases
Redis: Lua scripts - a primer and use casesRedis: Lua scripts - a primer and use cases
Redis: Lua scripts - a primer and use casesRedis Labs
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyNick Sieger
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011Lance Ball
 
Learning puppet chapter 3
Learning puppet chapter 3Learning puppet chapter 3
Learning puppet chapter 3Vishal Biyani
 
Fiber in the 10th year
Fiber in the 10th yearFiber in the 10th year
Fiber in the 10th yearKoichi Sasada
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2Vishal Biyani
 

Was ist angesagt? (20)

TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
 
J2SE 5
J2SE 5J2SE 5
J2SE 5
 
TorqueBox for Rubyists
TorqueBox for RubyistsTorqueBox for Rubyists
TorqueBox for Rubyists
 
Devignition 2011
Devignition 2011Devignition 2011
Devignition 2011
 
DataMapper on Infinispan
DataMapper on InfinispanDataMapper on Infinispan
DataMapper on Infinispan
 
Introduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter NotebooksIntroduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter Notebooks
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and Simple
 
Pl/Python
Pl/PythonPl/Python
Pl/Python
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 
Clojure Fundamentals Course For Beginners
Clojure Fundamentals Course For Beginners Clojure Fundamentals Course For Beginners
Clojure Fundamentals Course For Beginners
 
Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !
 
Redis: Lua scripts - a primer and use cases
Redis: Lua scripts - a primer and use casesRedis: Lua scripts - a primer and use cases
Redis: Lua scripts - a primer and use cases
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRuby
 
Storm begins
Storm beginsStorm begins
Storm begins
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011
 
Seeking Clojure
Seeking ClojureSeeking Clojure
Seeking Clojure
 
Learning puppet chapter 3
Learning puppet chapter 3Learning puppet chapter 3
Learning puppet chapter 3
 
Fiber in the 10th year
Fiber in the 10th yearFiber in the 10th year
Fiber in the 10th year
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2
 

Andere mochten auch

Peninsula crossroads dec 1 2010 powerpoint presentation
Peninsula crossroads dec 1 2010 powerpoint presentationPeninsula crossroads dec 1 2010 powerpoint presentation
Peninsula crossroads dec 1 2010 powerpoint presentationkrgc
 
Highlighting
HighlightingHighlighting
Highlightingcwwcww23
 
VHCF Annual Report_singlepages
VHCF Annual Report_singlepagesVHCF Annual Report_singlepages
VHCF Annual Report_singlepagesJennifer Donovan
 
Holistic Acres, Chandler, Arizona
Holistic Acres, Chandler, ArizonaHolistic Acres, Chandler, Arizona
Holistic Acres, Chandler, ArizonaRuss Christ
 
The Pocono Equestrian Center
The Pocono Equestrian CenterThe Pocono Equestrian Center
The Pocono Equestrian Centerpoconoequestrian
 
Blaines Haven 2010 presentation
Blaines Haven 2010 presentationBlaines Haven 2010 presentation
Blaines Haven 2010 presentationblaineshaven
 
Rethinking the Horse Business 2014 - How the Economy, the Horse Industry and ...
Rethinking the Horse Business 2014 - How the Economy, the Horse Industry and ...Rethinking the Horse Business 2014 - How the Economy, the Horse Industry and ...
Rethinking the Horse Business 2014 - How the Economy, the Horse Industry and ...Elisabeth McMillan
 
Numero 081 Julio 2007 Oracion Reposo En Dios
Numero 081   Julio 2007 Oracion Reposo En DiosNumero 081   Julio 2007 Oracion Reposo En Dios
Numero 081 Julio 2007 Oracion Reposo En DiosAudioconéctate.org
 
Global and china crystal oscillator industry report, 2010 2011
Global and china crystal oscillator industry report, 2010 2011Global and china crystal oscillator industry report, 2010 2011
Global and china crystal oscillator industry report, 2010 2011ResearchInChina
 
Conocimiento de la neuropedagogía y su relación con el desempeño docente en l...
Conocimiento de la neuropedagogía y su relación con el desempeño docente en l...Conocimiento de la neuropedagogía y su relación con el desempeño docente en l...
Conocimiento de la neuropedagogía y su relación con el desempeño docente en l...Heraclio Raza Torres
 
Seo – was zählt – was nicht!
Seo – was zählt – was nicht!Seo – was zählt – was nicht!
Seo – was zählt – was nicht!Buechel
 
漫畫工作室 Comic Studio 手冊
漫畫工作室 Comic Studio 手冊漫畫工作室 Comic Studio 手冊
漫畫工作室 Comic Studio 手冊filmdoing
 

Andere mochten auch (20)

Peninsula crossroads dec 1 2010 powerpoint presentation
Peninsula crossroads dec 1 2010 powerpoint presentationPeninsula crossroads dec 1 2010 powerpoint presentation
Peninsula crossroads dec 1 2010 powerpoint presentation
 
Highlighting
HighlightingHighlighting
Highlighting
 
VHCF Annual Report_singlepages
VHCF Annual Report_singlepagesVHCF Annual Report_singlepages
VHCF Annual Report_singlepages
 
Holistic Acres, Chandler, Arizona
Holistic Acres, Chandler, ArizonaHolistic Acres, Chandler, Arizona
Holistic Acres, Chandler, Arizona
 
The Pocono Equestrian Center
The Pocono Equestrian CenterThe Pocono Equestrian Center
The Pocono Equestrian Center
 
Blaines Haven 2010 presentation
Blaines Haven 2010 presentationBlaines Haven 2010 presentation
Blaines Haven 2010 presentation
 
Rethink2015 wide
Rethink2015 wideRethink2015 wide
Rethink2015 wide
 
Red Scarf Equestrian
Red Scarf EquestrianRed Scarf Equestrian
Red Scarf Equestrian
 
Rethinking the Horse Business 2014 - How the Economy, the Horse Industry and ...
Rethinking the Horse Business 2014 - How the Economy, the Horse Industry and ...Rethinking the Horse Business 2014 - How the Economy, the Horse Industry and ...
Rethinking the Horse Business 2014 - How the Economy, the Horse Industry and ...
 
Vos's 5 innovation styles
Vos's 5 innovation stylesVos's 5 innovation styles
Vos's 5 innovation styles
 
Actividad 8
Actividad 8Actividad 8
Actividad 8
 
Numero 081 Julio 2007 Oracion Reposo En Dios
Numero 081   Julio 2007 Oracion Reposo En DiosNumero 081   Julio 2007 Oracion Reposo En Dios
Numero 081 Julio 2007 Oracion Reposo En Dios
 
Global and china crystal oscillator industry report, 2010 2011
Global and china crystal oscillator industry report, 2010 2011Global and china crystal oscillator industry report, 2010 2011
Global and china crystal oscillator industry report, 2010 2011
 
Indian patent office publishes patent industrial design journal having inform...
Indian patent office publishes patent industrial design journal having inform...Indian patent office publishes patent industrial design journal having inform...
Indian patent office publishes patent industrial design journal having inform...
 
Conocimiento de la neuropedagogía y su relación con el desempeño docente en l...
Conocimiento de la neuropedagogía y su relación con el desempeño docente en l...Conocimiento de la neuropedagogía y su relación con el desempeño docente en l...
Conocimiento de la neuropedagogía y su relación con el desempeño docente en l...
 
Seo – was zählt – was nicht!
Seo – was zählt – was nicht!Seo – was zählt – was nicht!
Seo – was zählt – was nicht!
 
漫畫工作室 Comic Studio 手冊
漫畫工作室 Comic Studio 手冊漫畫工作室 Comic Studio 手冊
漫畫工作室 Comic Studio 手冊
 
ShannaCrawford Resume
ShannaCrawford ResumeShannaCrawford Resume
ShannaCrawford Resume
 
Colom
ColomColom
Colom
 
T se as
T se asT se as
T se as
 

Ähnlich wie Lua and fable jonathan shaw (lionhead)

Use of Lua in Lab Devices
Use of Lua in Lab DevicesUse of Lua in Lab Devices
Use of Lua in Lab DevicesClaus Kühnel
 
About Functional Programming
About Functional ProgrammingAbout Functional Programming
About Functional ProgrammingAapo Kyrölä
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance Coder Tech
 
Recursion & Erlang, FunctionalConf 14, Bangalore
Recursion & Erlang, FunctionalConf 14, BangaloreRecursion & Erlang, FunctionalConf 14, Bangalore
Recursion & Erlang, FunctionalConf 14, BangaloreBhasker Kode
 
Introduction to Clojure
Introduction to ClojureIntroduction to Clojure
Introduction to ClojureRenzo Borgatti
 
Thinking Functionally - John Stevenson - Codemotion Rome 2017
Thinking Functionally - John Stevenson - Codemotion Rome 2017Thinking Functionally - John Stevenson - Codemotion Rome 2017
Thinking Functionally - John Stevenson - Codemotion Rome 2017Codemotion
 
Thinking Functionally with Clojure
Thinking Functionally with ClojureThinking Functionally with Clojure
Thinking Functionally with ClojureJohn Stevenson
 
PART-3 : Mastering RTOS FreeRTOS and STM32Fx with Debugging
PART-3 : Mastering RTOS FreeRTOS and STM32Fx with DebuggingPART-3 : Mastering RTOS FreeRTOS and STM32Fx with Debugging
PART-3 : Mastering RTOS FreeRTOS and STM32Fx with DebuggingFastBit Embedded Brain Academy
 
Get into Functional Programming with Clojure
Get into Functional Programming with ClojureGet into Functional Programming with Clojure
Get into Functional Programming with ClojureJohn Stevenson
 
Principled io in_scala_2019_distribution
Principled io in_scala_2019_distributionPrincipled io in_scala_2019_distribution
Principled io in_scala_2019_distributionRaymond Tay
 
Fun with Functional Programming in Clojure - John Stevenson - Codemotion Amst...
Fun with Functional Programming in Clojure - John Stevenson - Codemotion Amst...Fun with Functional Programming in Clojure - John Stevenson - Codemotion Amst...
Fun with Functional Programming in Clojure - John Stevenson - Codemotion Amst...Codemotion
 
Airflow based Video Encoding Platform
Airflow based Video Encoding PlatformAirflow based Video Encoding Platform
Airflow based Video Encoding PlatformHotstar
 
Let's Talk Locks!
Let's Talk Locks!Let's Talk Locks!
Let's Talk Locks!C4Media
 
tarea 2 parcial robotica .pdf
tarea 2 parcial robotica .pdftarea 2 parcial robotica .pdf
tarea 2 parcial robotica .pdfluisgabielnavarro
 
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go WrongJDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go WrongPROIDEA
 
Benefits/tutorial of Lua in games
Benefits/tutorial of Lua in gamesBenefits/tutorial of Lua in games
Benefits/tutorial of Lua in gamesaction.vn
 
Fun with Functional Programming in Clojure
Fun with Functional Programming in ClojureFun with Functional Programming in Clojure
Fun with Functional Programming in ClojureCodemotion
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 

Ähnlich wie Lua and fable jonathan shaw (lionhead) (20)

Use of Lua in Lab Devices
Use of Lua in Lab DevicesUse of Lua in Lab Devices
Use of Lua in Lab Devices
 
20120710 - Lua_C
20120710 - Lua_C20120710 - Lua_C
20120710 - Lua_C
 
About Functional Programming
About Functional ProgrammingAbout Functional Programming
About Functional Programming
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance
 
Recursion & Erlang, FunctionalConf 14, Bangalore
Recursion & Erlang, FunctionalConf 14, BangaloreRecursion & Erlang, FunctionalConf 14, Bangalore
Recursion & Erlang, FunctionalConf 14, Bangalore
 
Introduction to Clojure
Introduction to ClojureIntroduction to Clojure
Introduction to Clojure
 
Thinking Functionally - John Stevenson - Codemotion Rome 2017
Thinking Functionally - John Stevenson - Codemotion Rome 2017Thinking Functionally - John Stevenson - Codemotion Rome 2017
Thinking Functionally - John Stevenson - Codemotion Rome 2017
 
Thinking Functionally with Clojure
Thinking Functionally with ClojureThinking Functionally with Clojure
Thinking Functionally with Clojure
 
PART-3 : Mastering RTOS FreeRTOS and STM32Fx with Debugging
PART-3 : Mastering RTOS FreeRTOS and STM32Fx with DebuggingPART-3 : Mastering RTOS FreeRTOS and STM32Fx with Debugging
PART-3 : Mastering RTOS FreeRTOS and STM32Fx with Debugging
 
Get into Functional Programming with Clojure
Get into Functional Programming with ClojureGet into Functional Programming with Clojure
Get into Functional Programming with Clojure
 
Principled io in_scala_2019_distribution
Principled io in_scala_2019_distributionPrincipled io in_scala_2019_distribution
Principled io in_scala_2019_distribution
 
Fun with Functional Programming in Clojure - John Stevenson - Codemotion Amst...
Fun with Functional Programming in Clojure - John Stevenson - Codemotion Amst...Fun with Functional Programming in Clojure - John Stevenson - Codemotion Amst...
Fun with Functional Programming in Clojure - John Stevenson - Codemotion Amst...
 
Airflow based Video Encoding Platform
Airflow based Video Encoding PlatformAirflow based Video Encoding Platform
Airflow based Video Encoding Platform
 
Let's Talk Locks!
Let's Talk Locks!Let's Talk Locks!
Let's Talk Locks!
 
tarea 2 parcial robotica .pdf
tarea 2 parcial robotica .pdftarea 2 parcial robotica .pdf
tarea 2 parcial robotica .pdf
 
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go WrongJDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
 
Benefits/tutorial of Lua in games
Benefits/tutorial of Lua in gamesBenefits/tutorial of Lua in games
Benefits/tutorial of Lua in games
 
Fun with Functional Programming in Clojure
Fun with Functional Programming in ClojureFun with Functional Programming in Clojure
Fun with Functional Programming in Clojure
 
Pig
PigPig
Pig
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 

Mehr von Kore VM

Robotic Testing to the Rescue - Paul Dubois (DoubleFine)
Robotic Testing to the Rescue - Paul Dubois (DoubleFine)Robotic Testing to the Rescue - Paul Dubois (DoubleFine)
Robotic Testing to the Rescue - Paul Dubois (DoubleFine)Kore VM
 
Sony Lua - RJ Mical (SCEA)
Sony Lua - RJ Mical (SCEA)Sony Lua - RJ Mical (SCEA)
Sony Lua - RJ Mical (SCEA)Kore VM
 
A brief history of Lua - Roberto Ierusalimschy (PUC Rio)
A brief history of Lua - Roberto  Ierusalimschy (PUC Rio)A brief history of Lua - Roberto  Ierusalimschy (PUC Rio)
A brief history of Lua - Roberto Ierusalimschy (PUC Rio)Kore VM
 
Optimizing Lua For Consoles - Allen Murphy (Microsoft)
Optimizing Lua For Consoles - Allen Murphy (Microsoft)Optimizing Lua For Consoles - Allen Murphy (Microsoft)
Optimizing Lua For Consoles - Allen Murphy (Microsoft)Kore VM
 
Lua and adaptive audio - Don Veca (Activision)
Lua and adaptive audio - Don Veca (Activision)Lua and adaptive audio - Don Veca (Activision)
Lua and adaptive audio - Don Veca (Activision)Kore VM
 
Lua patient zero bret mogilefsky (scea)
Lua patient zero   bret mogilefsky (scea)Lua patient zero   bret mogilefsky (scea)
Lua patient zero bret mogilefsky (scea)Kore VM
 

Mehr von Kore VM (6)

Robotic Testing to the Rescue - Paul Dubois (DoubleFine)
Robotic Testing to the Rescue - Paul Dubois (DoubleFine)Robotic Testing to the Rescue - Paul Dubois (DoubleFine)
Robotic Testing to the Rescue - Paul Dubois (DoubleFine)
 
Sony Lua - RJ Mical (SCEA)
Sony Lua - RJ Mical (SCEA)Sony Lua - RJ Mical (SCEA)
Sony Lua - RJ Mical (SCEA)
 
A brief history of Lua - Roberto Ierusalimschy (PUC Rio)
A brief history of Lua - Roberto  Ierusalimschy (PUC Rio)A brief history of Lua - Roberto  Ierusalimschy (PUC Rio)
A brief history of Lua - Roberto Ierusalimschy (PUC Rio)
 
Optimizing Lua For Consoles - Allen Murphy (Microsoft)
Optimizing Lua For Consoles - Allen Murphy (Microsoft)Optimizing Lua For Consoles - Allen Murphy (Microsoft)
Optimizing Lua For Consoles - Allen Murphy (Microsoft)
 
Lua and adaptive audio - Don Veca (Activision)
Lua and adaptive audio - Don Veca (Activision)Lua and adaptive audio - Don Veca (Activision)
Lua and adaptive audio - Don Veca (Activision)
 
Lua patient zero bret mogilefsky (scea)
Lua patient zero   bret mogilefsky (scea)Lua patient zero   bret mogilefsky (scea)
Lua patient zero bret mogilefsky (scea)
 

Kürzlich hochgeladen

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

Lua and fable jonathan shaw (lionhead)

  • 1. Lua and Fable Jonathan Shaw
  • 2. How does Fable use Lua? AI Quest scripts Camera Start-up settings Miscellaneous scripts Debugging Patching
  • 3. A (very) brief history The original Fable used C++ as its “scripting” language, using macros to make it more “user friendly”. We used micro-threads (or fibres) to give each AI entity and each quest its own non-pre-emptive thread. We liked micro-threads, but didn’t like C++ as a scripting language.
  • 4. Enter Lua Like all good scripting languages Lua is easy to write, and can give you almost-instant feedback when changing scripts while your game is running. Lua’s first class support for coroutines made Lua an ideal choice for Fable. Fable II and III make extensive use of coroutines. On busy levels we can have upwards of 100 coroutines running.
  • 5. AI An AI entity in Fable II and III has a brain, defined in Fable’s general game editor. A brain has a list of behaviour groups with priorities (some of which can be the same). A behaviour group has a list of behaviours with priorities (some of which can be the same).
  • 6. Deciding what behaviour to run Iterate through the behaviour groups, starting with the highest priority – see if they’re valid to run. E.g. a “work in the factory” behaviour group isn’t valid to run if it’s night time. For each valid behaviour group, iterate through the behaviours, starting with the highest priority, to see if they’re valid to run.
  • 7. Same priority behaviours If some behaviours or behaviour groups have the same priority, we want to iterate through them in a random order. Custom iterators in Lua were the perfect solution for this design. Sadly, very nice to write, but a performance bottleneck, so we moved the logic to C++.
  • 8. Quests A quest will have one “master” coroutine, with a number of “child” coroutines – when the master coroutine is finished we automatically kill the child coroutines. We have the concept of “entity threads” – these are automatically tied to specific entities and die when the entity dies (or suspend when the entity is unloaded when the player changes level).
  • 9. Saving quests We wanted players to be able to save the game wherever they were in the game and for it to be a “perfect save” – without quest scripters having to do anything to make it work. Quite a challenge, until we learned about Pluto for Lua, by Ben Sunshine-Hill.
  • 10. The patch challenge Using Pluto allows you to save coroutines and to resume them where they left off after loading the save game. What if you want to patch a function that a coroutine was yielded in? If you change the line numbering (of the resultant Lua byte code) before the final yield in the function, you can’t.
  • 11. Nasty tricks This forces you to come up with some “creative” solutions.
  • 12. Making it a little easier In Fable III some of our scripters have started changing how they format their while loops: while true do -- Check for various -- conditions and act -- on them coroutine.yield() end while true do coroutine.yield() -- Check for various -- conditions and act -- on them end
  • 13. Bring on the Watch Dogs Lua is extremely flexible and inspectable. Add scripts to run in their own coroutines and inspect the state of the known problem scripts – when they detect the problem, fix it and shut down.
  • 14. Lua/C++ interface We wanted it to be as easy as possible to register C++ functions in Lua. The more functions exposed to Lua, the more power you have when it comes to debugging and releasing DLC without requiring a Title Update. There were features in Fable II’s second DLC that we had to drop because the one function the scripts needed hadn’t been exposed.
  • 15. Lua Plus Call Dispatcher We use Joshua Jensen’s Lua Plus Call Dispatcher. This lets you expose a function with any arbitrary signature to Lua (it doesn’t have to be a lua_Cfunction). You can describe to the call dispatcher how to interpret any type you might want to expose to Lua.
  • 16. Hiding the Lua stack For a C++ programmer used to dealing with objects, it can be useful to be able to treat Lua tables and functions as C++ objects. Using inspiration from LuaPlus we wrote CLuaTable and CLuaFunction classes. These use the Lua registry to keep handles to the table and functions alive even if no handles to them in Lua remain.
  • 17. A quick example class CEntity; class Vec3; Vec3 CEntity::GetPos() const; luaL_newmetatable(L, “EntityMetaTableName”); lua_pushvalue(L, -1); // Pushes the metatable lua_setfield(L, -2, "__index");// mt.__index = mt CLuaTableentity_mt (L);// This pops the metatable off the stack entity_mt.RegisterDirectMemberFunction<CEntity>( “GetPos", &CEntity::GetPos);
  • 18. Using that in Lua local hero = GetHero() local trigger = GetEntity(“Trig1”) -- The hero is now within 10 units of the trigger while (hero:GetPos()-trigger:GetPos()):GetLength() > 10 do coroutine.yield() end while IsDistanceBetweenEntitiesOver(hero, trigger, 10) do coroutine.yield() end
  • 19. Debugging Lua Lua provides debugging hooks to allow the creation of a debugger application without needing to modify any of the Lua source code. Our Lua Debugger supported breakpoints, step into, step over, per-coroutine breakpoints, a watch window and the ability to break into Lua from a C++ assert. Saving a file in the debugger would automatically reload it in the game.
  • 20. Debugging with Lua Our in-game debug console ran in the game’s Lua environment. This meant everything scripts or AI could do, you could do in the console (including inspecting the current state of the AI and quests). On Fable III we have remote access to this same console (including niceties like auto-complete).
  • 21. Automation Having remote access to the Lua environment means we can very easily write external scripts (ours are in Python) to drive the game however we like. We change start-up settings (so Lua is one of the first systems in the game we initialise) and test that every level in the game loads successfully, and get performance metrics from the game using this system.
  • 22. Profiling Lua This is something we struggled with, partly due to our heavy reliance on coroutines. Profilers that hooked into function entries and exits wouldn’t stop the timer during yields, giving very skewed results. For Fable II, we didn’t have anything more sophisticated than manually timing suspected expensive functions and printing times to the debug output channel.
  • 23. Memory usage When Fable II shipped Lua was using roughly 8 to 15Mb of memory. We had a custom allocator designed for many small, fragmenting allocations. Tracking memory “leaks” in Lua was extremely difficult. We found that pre-compiling our Lua scripts massively reduced fragmentation (in addition to the small improvement in loading time).
  • 24. Reducing memory footprint Using Lua 5.1’s module system made demand-loading quest scripts very simple. Changing lua_Number to float from double saved us 1 or 2Mb, because those extra 4 bytes exist in every Lua type, whether table, Boolean, function, etc. The problem with floats comes when you want to pass 32 bit hashes or UIDs to and from Lua (because integers above 8 million lose precision when converted to floats). Light user data was the solution.
  • 25. Taming the garbage collector We turn the garbage collector off and manually run it once per game frame. We played around with the step size to try to balance the time the collector takes and the collector having enough time to clean up the general memory churn in any given frame. Even when we found a number we were reasonably happy with, the collector would sit at about 3ms, often spiking over 6ms.
  • 26.
  • 27. Lua and Fable III We were very happy with our use of Lua in Fable II, so haven’t really changed that much with Lua in Fable III. Our quest scripts now support mid-quest “skip points” so that when debugging a quest you can now skip (forwards or backwards) to a decent number of points in the middle of quests. We’re using Kore in Fable III, which gives us improved performance and improved tools, including a profiler.
  • 28. Conclusion Lua lets us develop systems quickly with fast iteration. Performance is an issue and can be too much of a “black box”. Having a rich and full interface between your game and scripting language will serve you well when it comes to extending the game.
  • 29. References Lua: http://www.lua.org Pluto for Lua: http://luaforge.net/projects/pluto/ LuaPlus: http://luaplus.org Kore http://www.kore.net

Hinweis der Redaktion

  1. Custom iterators allow you to track state between iterations so you construct a hidden table of all behaviours with the same priority, and then for each iteration return a random example from that table.But this is a benefit of Lua – it’s usually very easy to move functions from Lua to C++ if they turn out to be expensive
  2. Talk about the graveyard demon door decapitation bug.Why did we let Lua crash the game? Optimisation!
  3. Adding const overloads.
  4. Define __sub in your metatable to define the behaviour of subtraction for your own typesThe calculation of distance done this way in Lua is actually pretty inefficient, due to the creation and subsequent deletion of three Vec3s on the heap.
  5. When reloading scripts you need to do more than just reload the Lua file.Commercial debuggers at the time just weren’t up to standard, but the situation has now improved. VSLua, Kore
  6. Performance is about 10 times slower on PC, even slower on in-order chips in consoles.
  7. Consistency and predictability is key here.