MATLAB : tracking state change in imufilter object - c++

I am creating a function in MATLAB that I want to export as a c++ library. The function takes in accelerometer and gyroscope data, and calculates orientation via imufilter. Here is how it works:
% when 10 samples come in, call below function
function [orientation] = runtime_get_orientation(accelerometer, gyro)
FUSE = imufilter('SampleRate', 50, 'AccelerometerNoise', 0.002, ...
'LinearAccelerationNoise', 0.003, ...
'GyroscopeNoise', 0.444, 'GyroscopeDriftNoise', 0.445);
[orientation,~] = FUSE(accelerometer, gyro);
end
Note: I am creating a realtime system which will call this function over time. Ex: 10 samples come in, and then I call this function. 10 more come in, and I call it again.
The problem I see is that the FUSE object state is re-set every time I make a call to the function. Meaning, the matrix that retain the error state over time and adjust to it, are wiped. If I pass the FUSE object to the function, as demonstrated below, the state is kept and I can view orientation that makes sense.
% define FUSE object outside of the function
FUSE = imufilter('SampleRate', 50, 'AccelerometerNoise', 0.002, ...
'LinearAccelerationNoise', 0.003, ...
'GyroscopeNoise', 0.444, 'GyroscopeDriftNoise', 0.445);
% when 10 samples come in, call below function
function [orientation] = runtime_get_orientation(accelerometer, gyro, FUSE)
[orientation,~] = FUSE(accelerometer, gyro);
end
I'd like to return the object state of the FUSE object back to the calling function, so that I can pass it as an argument back in. I expect that this is some sort of a matrix object. I want to do that because I will eventually want to export it as a c++ function, and exporting a FUSE object might not be possible from what I can tell.
What can I do to keep the state of the FUSE object, in a way that is codegen / c++ friendly?

One simple solution is to make the data a static variable in the function. That way, you can create the filter only the first time the function is called, and you don’t need to know about it outside of the function.
To declare a static variable in MATLAB, use the persistent keyword.

Related

Maintaining lua/c++ variables through through multiple script calls

I'm pretty new to lua scripting, but want to incorporate scripting into my game engine. Currently I have lua linked up to c++ in a basic manner where I can call methods from c++ classes and vise-versa. Lua scripts are setup as components and you can essentially attach scripts to a game object. However, I'm having an issue where my variables are being reset each time a script is called. Here is a basic example of a script:
--lua script--
input = InputManager()
function initalize()
end
function update()
if(input:KeyDown(KEY_SPACE)) then
print("Random before: ", input.random)
input.random = input.random + 10
print("Random after: ", input.random)
end
end
Initialize is called when the script component is attached and update is called every frame. In this example, in my c++ InputManager class that I bind up to lua, I have a integer random that is initialized to 5. I'm using lunafive properties to control the getting and setting of variables.
When I hit space i expect the first iteration to print out:
Random before: 5
Random after: 15
And then the next iteration:
Random before: 15
Random after: 25
However, every iteration I get that first result of 5 and 15. I realize this is because I'm loading the script each update method so it is probably just creating a new instance of InputManager.
How do I go about creating an instance of an object (i.e InputManager) and maintain that same instance every time I call update.
That way I could do something like this:
input = nil
function initalize()
input = InputManager()
end
function update()
print(input.random)
end
and not have an undefined instance of input once update is called. Hopefully this all makes sense, if not I can clarify! Any help is much appreciated!

Efficient way to pass gui variables to classes?

I'm using the program Maya to make a rather large project in python. I have numerous options that will be determined by a GUI and input by the user.
One example of an option is what dimensions to render at. However I did not make a GUI yet and am still in the testing faze.
What I ultimately want is a way to have variables be able to be looked up and used by various classes/methods within multiple modules. And also that there be a way that I can test all the code without having an actual GUI.
Should I directly pass all data to each method? My issue with this is if method foo relies on variable A, but method bar needs to call foo, it could get real annoying passing these variables to Foo from everywhere its called.
Another way I saw was passing all variables through to each class instance itself and using instance variables to access. But what if an option changes, then i'd have to put reload imports every time it runs.
For testing what I use now is a module that gets variables from a config file with the variables, and i import that module and use the instance variables throughout the script.
def __init__(self):
# Get and assign all instance variables.
options = config_section_map('Attrs', '%s\\ui_options.ini' %(data_path))
for k, v in options.items():
if v.lower() == 'none':
options[k] = None
self.check_all = int(options['check_all'])
self.control_group = options['control_group']
Does anyone have advice or can point me in the right direction dealing with getting/using ui variables?
If the options list is not overly long and won't change, you can simply set member variables in the class initializer, which makes the initialization easy for readers to understand:
class OptionData(object):
def __init___(self):
#set the options on startup
self.initial_path = "//network"
self.initial_name = "filename"
self.use_hdr = True
# ... etc
If you expect the initializations to change often you can split out the initial values into the constructor for the class:
class OptionData(object):
def __init___(self, path = "//network", name = "filename", hdr=True)
self.initial_path = path
self.initial_name = name
self.use_hdr = hdr
If you need to persist the data, you can fill out the class reading the cfg file as you're doing, or store it in some other way. Persisting makes things harder because you can't guarantee that the user won't open two Maya's at the same time, potentially changing the saved data in unpredictable ways. You can store per-file copies of the data using Maya's fileInfo.
In both of these cases I'd make the actual GUI take the data object (the OptionData or whatever you call yours) as an initializer. That way you can read and write the data from the GUI. Then have the actual functional code read the OptionData:
def perform_render(optiondata):
#.... etc
That way you can run a batch process without the gui at all and the functional code will be none the wiser. The GUI's only job is to be a custom editor for the data object and then to pass it on to the final function in a valid state.

Lua preserving global values

I use Lua for my game engine logic. My main game loop is not done in Lua. Only special nodes in my scene hierarchy have Lua scripts attached. These scripts are executed every frame. The problem I face is that I need to keep global variable values from one frame to another.
My temporary solution looks like this:
finish = useBool("finish", false)
timer = useInt("timer", 0)
showTimer = useBool("showTimer", true)
startTimer = useInt("startTimer", 0)
play0 = useBool("play0", false)
play1 = useBool("play1", false)
play2 = useBool("play2", false)
play3 = useBool("play3", false)
delta = useInt("delta", 0)
gameOverTime = useInt("gameOverTime", 5000)
finishTime = useInt("finishTime", 5000)
checkPoint = useInt("checkPoint", 255)
<...> Game logic <...>
setInt("message", message);
setInt("checkPoint", checkPoint)
setInt("finishTime", finishTime)
setInt("gameOverTime", gameOverTime)
setInt("timer", timer)
setBool("play3", play3)
setBool("play2", play2)
setBool("play1", play1)
setBool("play0", play0)
setInt("startTimer", startTimer)
setBool("showTimer", showTimer)
setInt("timer", timer)
setBool("finish", finish);
I call special methods that retrieve global variables from hash maps in C++ at the beginning and I set them again at the end of the script.
Is there a way to do this implicitly?
Is it a bad design to use Lua not as the main game loop?
Well, while there is nothing technically wrong with your solution, you might start to notice some performance issues if you end up with a lot of global variables (something you should, in general, avoid).
With that said, there is room for improvement. For example:
At the beginning of the script, check if your global variable is nil. If it is, then you can initialize it, if not, this is probably not the first time you're running the script, so leave it unmodified. But that means a lot of pesky if-else statements, which one can easily forget about. We can do better!
I would recommend looking at Chapter 14: The Environment, from the Programming in Lua book. Here's a quick quote from the intro:
Lua keeps all its global variables in a regular table, called the environment. ... The other (actually the main) advantage is that we can manipulate this table as any other table. To facilitate such manipulations, Lua stores the environment itself in a global variable _G. (Yes, _G._G is equal to _G.)
Since _G is a table, it also has a metatable, so you can define __index and __newindex metamethods to handle access to and creation of global variables. You can find examples of this in section 14.2. Go read the whole chapter, it's not that long (if you're unfamiliar with metamethods and metatables, also look through chapter 13 - this is where Lua really shines in terms of flexibility).
Now that we've covered the trivial and normal methods, let's look at the overkill end of the spectrum. As an example I'll look at Unity's approach to scripting. A Unity javascript usually defines variables, functions, and types. Any variables defined outside of the scope of methods or types are persisted between frames because the script itself is not executed every frame. Instead, they let the script define functions and call the functions at the appropriate time. So if you want something executed every frame - you put it in the Update function. Every script can define it's own Update function because it has it's own scope. So every frame the scripting engine goes through all objects, checks if the script's scope has an Update method and calls it.
Back to Lua - a solution like this would involve creating separate environments for each object/script/whatever your node is. Then, instead of executing the script attached to your node every frame, your main loop will go through all the nodes and run a function inside of their environment. You can also switch environments, so you can set the global environment to your node's env before executing it, and then switch back when you're done. This allows your scripts to use globals as they see fit, have them persisted between frames and excludes the possibility of name collisions or global namespace pollution. Additionally you can use metamethods to nest the node's environment inside the actual global environment or inside an API environment with helper methods (basically, if __index does not find something it looks it up in a parent).

Delayed execution of member functions in Lua/C++ / luabind / Interaction with other lua behavior scripts

I have a game with a mainloop - on each loop i call for every NPC in the game ->ProcessAI() to execute any actions.
This is a server so the call to ProcessAI is not executed on every frame like on a client game! Its also singlethreaded.
Now i wanted to extend the C++ codebase with lua using luabind (maybe, even with boost overhead). So i expose some functions of my NPC class to LUA.
I wanted to create actor scripts for example - boss battles which have more sophisticated behaviour - whenever in my c++ ProcessAI function an event happens - i would delegate this to the corresponding lua script for the specific NPC.
i imagined in my boss.lua script i would have something like this
function OnEngageCombat(NPC)
NPC:say ("Some taunts...")
ScheduleEvent(CastEvilSpell,/*time*/2000,/*numExecutions*/1,)
end
function CastEvilSpell(NPC)
NPC:CastSpell("someSpell")
end
However - i have no idea how to do this - i gather ScheduleEvent should be some C++ function exported to Lua - but what would be the best approach to keep the object reference of the NPC (boss) with this and call a function in that script about 2 seconds later ?
Furthmore along with this delayed execution - i want that NPCs can interact with each other - my current idea is to have an actor behavior script for each special NPC.
Now what i imagined is to initiate a conversation between two NPCs e.g.
function DoGossip(NPC)
// check if NPC1 is close to NPC2
if NPC:DistanceToNpc("SomeGuy") < 10 then
StartConversation1()
end
function StartConversation1(NPC)
NPC:Say("Hello ...")
// wait a moment now trigger NPC2 to reply
????
end
Basically - how do i call a function from lua scriptA which exists in lua scriptB which is the behavior script for NPC2.
What would be a good design?
Thanks
If you use LuaBind, you can set a global scriptable object that refers to a wrapper class around your game engine that you expose to your script.
So, whenever you set up your lua engine, you can register a global you want all scripts to have access to, like this in your C++ code:
luabind::globals(m_pLuaState)["Game"] = m_pGameWrapperClass;
Then, in your script, you could simply refer to the Game object to get at game specific functionality, like this:
Game:ScheduleEvent(...)
Your C++ game wrapper class would just implement a ScheduleEvent function that you'd bind with LuaBind. You could add/register as many game-y specific functions as you'd need on that object.
To lead into your question 2, you could simply register a function on your Game class called FindNPC(), that takes a string argument or id or something that would look up an npc in your engine, and return a reference to it. You'd probably want to write a wrapper class around the npc object that exposes npc-y functionality just like you would do with your Game class, and FindNPC() would return userdata that represents an NPC, and exposes whatever functionality that is necessary to use it, or to make it do stuff in the Game itself.

How can a script retain its values through different script loading in Lua?

My current problem is that I have several enemies share the same A.I. script, and one other object that does something different. The function in the script is called AILogic. I want these enemies to move independently, but this is proving to be an issue. Here is what I've tried.
1) Calling dofile in the enemy's constructor, and then calling its script function in its Update function which happens in every game loop. The problem with this is that Lua just uses the script of the last enemy constructed, so all of the enemies are running the same script in the Update function. Thus, the object I described above that doesn't use the same script for it's A.I. is using the other enemies' script.
2) Calling dofile in the Update function, and then calling its script function immediately after. The problem with this is that dofile is called in every object's update function, so after the AILogic function runs and data for that script is updated, the whole thing just gets reset when dofile is called again for another enemy. My biggest question here is whether there is some way to retain the values in the script, even when I switch to running a different one.
I've read about function environments in Lua, but I'm not quite sure how to implement them correctly. Is this the right direction? Any advice is appreciated, thanks.
Edit: I've also considered creating a separate place to store that data rather than doing it in the Lua script.
Edit2: Added some sample code. (Just a test to get the functionality working).
-- Slime's Script
local count = 0;
function AILogic( Slime )
--Make the slime move in circles(err a square)
if count < 4 then
Slime:MoveDir( 0 );
elseif count < 8 then
Slime:MoveDir( 2 );
elseif count < 12 then
Slime:MoveDir( 1 );
elseif count < 16 then
Slime:MoveDir( 3 );
else
count = 0;
end
count = count + 1;
end
The lua interpreter runs each line as its own chunk which means that locals have line scope, so the example code can't be run as-is. It either needs to be run all at once (no line breaks), without locals, or run in a do ... end block.
As to the question in the OP. If you want to share the exact same function (that is the same function at runtime) then the function needs to take the data as arguments. If, however, you are ok with using the same code but different (runtime) functions than you can use closures to hold the local/individual data.
local function make_counter()
local count = 0
return function ()
local c = count
count = count + 1
return c
end
end
c1 = make_counter()
c2 = make_counter()
c3 = make_counter()
print(c1())
print(c1())
print(c1())
print(c1())
print(c2())
print(c3())
print(c2())
print(c3())
print(c2())
print(c3())
Alternatively, you could play with the environment of the function each time it is called, but that will only work correctly for some cases (depends on what the internals of the function are).
The canonical reference for this is link text. Explaining this briefly we'll work off the following code from the site:
a = 1
local newgt = {} -- create new environment
setmetatable(newgt, {__index = _G})
setfenv(1, newgt) -- set it
The first line sets up the (global) variable "a". You can view this as setting default values for your code. (Keep in mind that in Lua all variables are global unless you declare them with "local".)
The next line creates a table that will be your new environment. It is local to the function/chunk you're executing in so it won't be trashed by anything else that runs now or later.
The third line is the beginnings of the magic. To understand it you're going to have to understand metamethods In essence, however, you're using Lua's metamagic to ensure that any global names that aren't defined in your soon-to-be function environment get resolved in the context of your old global environment. Basically it means if you use a name that's not in your function environment, Lua will automagically hunt in the global environment you used to have to find the name. (In a word: inheritance.)
The fourth line is where you get what you're looking for. Setfenv(1,...) means that this changes the environment for your current function. (You could use 2 for the calling function, 3 for the calling function's caller, etc. on up the line.) The second parameter is the table you just set up, complete with inheritance of the old behaviour. Your function is now executing in a new global environment. It has all the names and values of the old environment handy (including functions and that global variable "a" you put in). If, however, you WRITE to a name it will not overwrite the global state. It will overwrite your local copy of it.
Consider the following subsequent code:
a = 10
b = 20
What you have done now is made your function environment table look like this:
{a = 10, b=20}
Your "global" environment, in short, contains two variables only: a (value 10) and b (value 20). When you access "a" later you'll get your local copy with 10 -- the old global value stored in your metatable is shadowed now and is still set to 1 -- and if you access "b" you'll get 20, despite the original global state likely not even having a variable "b" to access. And you'll still be able to access all the functions, etc. you've defined before this point as well.
Edited to add test code to debug OP's problem.
I put the following code into "junk.lua":
a = 1
local newgt = {}
setmetatable(newgt, {__index = _G})
setfenv(1, newgt)
print(a)
a = 10
print(a)
print(newgt)
The output of it is as follows:
$ lua junk.lua
1
10
table: 0x976d040
This is using Lua 5.1.4. What is the output you're seeing?