-- $LastChangedDate: 2010-02-05 15:06:48 -0600 (Fri, 05 Feb 2010) $
-- Manipulator mode.
-- See module.txt for documentation and pitfalls.
-- Notes: Use Vec3() instead of tables (XX=0).

-- Load subset of scripts necessary for manipulator-mode.
dofile( sim.scriptDir .. "/lib.lua" )
dofile( sim.scriptDir .. "/gfx.lua" )
dofile( sim.scriptDir .. "/defs.lua" )
dofile( sim.scriptDir .. "/sim_generic.lua" )
dofile( sim.scriptDir .. "/events.lua" )
dofile( sim.scriptDir .. "/scene.lua" )
dofile( sim.scriptDir .. "/keyboard_defs.lua" )

-- Load scene.
assert( Scene:Load( defs.SCENE_BASENAME ) )

-- Called by C++ core.
function sim.HandleDestroyObject( objectPtr )
    return 0  -- NOP
end

---------------------
-- ManipulatorMode --
---------------------

ManipulatorMode = {
    Keyboard = { },  -- nested class
}

-- Timer-tick handler.
function ManipulatorMode.Tick()
    -- Handle keyboard events.
    local keyEvent = sim.Keyboard:DequeueKey()
    if ( keyEvent ) then
        ManipulatorMode.Keyboard.Handler( keyEvent )
    end
end

-- Keyboard handler table.
-- Manipulator-mode has a minimal keyboard handler.
ManipulatorMode.Keyboard.handlerTable = {

    -- Exit program.
    [string.byte("c")] =
    function( keyEvent )
        if ( keyEvent.ctrl ) then  -- Ctrl-c
            sim.Program:Exit( 0 )
        end
    end,

    -- Save/restore viewpoint (SPACE).
    [string.byte(" ")] =
    function( keyEvent )
        if ( keyEvent.modifier ) then
            sim.Window:SaveViewpoint()
        else
            sim.Window:RestoreViewpoint()
        end
    end,

    -- Toggle wireframe mode (Mod-F9).
    [KeyDefs.KEY_F9] =
    function( keyEvent )
        if ( keyEvent.modifier ) then
            sim.SceneGraph:ToggleWireframeMode()
        end
    end,

    -- Reload scene (Mod-F11).
    [KeyDefs.KEY_F11] =
    function( keyEvent )
        if ( keyEvent.modifier ) then
            Scene:Reload()
        end
    end,

    -- Save scene graph (Mod-F12).
    [KeyDefs.KEY_F12] =
    function( keyEvent )
        if ( keyEvent.modifier ) then
            sim.SceneGraph:SaveToFile( defs.PROGRAM_NAME_SHORT .. "_scene.osg" )
        end
    end,
}

-- (See keyboard.lua)
function ManipulatorMode.Keyboard.Handler( keyEvent )
    -- Lookup function in handler table by key.  Ignore key release.
    if ( keyEvent.press ) then
        local handler = ManipulatorMode.Keyboard.handlerTable[keyEvent.key]
        if ( handler ) then  -- could be unrecognized key
            handler( keyEvent )
        end
    end
end
