-- $LastChangedDate: 2009-03-07 08:58:38 -0600 (Sat, 07 Mar 2009) $
-- Startup.
-- See module.txt for documentation and pitfalls.

-- Build a map of cmd-line args.
-- The C++ binding provides an array form.
-- The map is convenient but is useless for parsing consecutive args.
sim.argvArray = sim.argv  -- alias
sim.argvMap = { }
for i=1, #sim.argv do
	local arg = sim.argv[i]
	sim.argvMap[arg] = i  -- value is the index for iterating by numeric index
end

-- Reverse-map to numeric index else nil if arg absent.
function sim.GetArgvIdx( arg )
	return sim.argvMap[arg]
end

-- Log.
if ( sim.argvMap["-q"] ) then
	function Log( msg ) end
else
	Log = print
end
Log( "[Lua] startup." );

-- Randomize.
math.randomseed( os.time() )

-- Enable step mode.
-- Although a key can toggle step mode, -step fully enables it.
if ( sim.argvMap["-step"] ) then
	Log( "Fully enabled step mode (disabled physics/stall)." )
	sim.Physics:PermanentlyDisable()
	sim.Physics:EnableStall( false )
end

-- NOP if controlled by trackball.
if ( sim.argvMap["-t"] ) then
	function sim.HandleDestroyObject( objectPtr ) return 0 end  -- NOP but called by C++ core
	return
end

-- Load all Lua scripts.
dofile( sim.Program:GetScriptDir() .. "/lib.lua" )
dofile( sim.Program:GetScriptDir() .. "/gfx.lua" )
dofile( sim.Program:GetScriptDir() .. "/defs.lua" )
dofile( sim.Program:GetScriptDir() .. "/timer.lua" )
dofile( sim.Program:GetScriptDir() .. "/sim.lua" )
dofile( sim.Program:GetScriptDir() .. "/events.lua" )
dofile( sim.Program:GetScriptDir() .. "/replay.lua" )
dofile( sim.Program:GetScriptDir() .. "/game.lua" )  -- before actors
dofile( sim.Program:GetScriptDir() .. "/weapons.lua" )
dofile( sim.Program:GetScriptDir() .. "/actors.lua" )
dofile( sim.Program:GetScriptDir() .. "/views.lua" )
dofile( sim.Program:GetScriptDir() .. "/cmd.lua" )
dofile( sim.Program:GetScriptDir() .. "/keyboard.lua" )
dofile( sim.Program:GetScriptDir() .. "/joystick.lua" )
dofile( sim.Program:GetScriptDir() .. "/hud.lua" )
dofile( sim.Program:GetScriptDir() .. "/sound.lua" )
dofile( sim.Program:GetScriptDir() .. "/scene.lua" )
dofile( sim.Program:GetScriptDir() .. "/mission.lua" )

-- Initialize motion blur if requested (can cause artifacts and slowness).
if ( sim.argvMap["-motion-blur"] ) then
	sim.FX:EnableMotionBlur( 0.15 )
	Log( "Enabled motion blur." )
end

-- Load mission script.
if ( sim.argvMap["-ossim"] ) then
	dofile( sim.Program:GetScriptDir() .. "/mission_ossim.lua" )
else
	dofile( sim.Program:GetScriptDir() .. "/mission_carrier.lua" )
end

-- If step mode, allow free movement of player.
if ( sim.argvMap["-step"] ) then
	PlayerActor.aircraft:SetCollidable( false )
end

-- Optimize scene-graph.
sim.SceneGraph:OptimizeSceneGraph()

-- Save state for when program is reset.
Mission:Save()
Mission:Start()
