#Conditional Hooks

$Application: FS2_Open

$On Game Init: [

    glowmap_replacement = gr.createTexture(16, 16, TEXTURE_DYNAMIC)

    if glowmap_replacement == nil or not glowmap_replacement:isValid() then
        ba.warning("Error in initializing glowmap flickering script: could not create helper texture! Flicker effect won't work.")
    else
        gr.setTarget(glowmap_replacement)
        gr.clearScreen()
        gr.setTarget()
    end

    flick_glows = function(shipname, duration)
        ship = mn.Ships[shipname]

        if ship ~= nil and ship:isValid() and glowmap_replacement ~= nil and glowmap_replacement:isValid() then
            textures_num = #ship.Textures
            for i=1,textures_num do
                filename = ship.Textures[i]:getFilename()

                if string.find(filename, "-glow") ~= nil and string.find(filename, "debris-glow") == nil then
                    table.insert(flickering_glowmaps, { ship_signature = ship:getSignature(), flicker_start_time = mn.getMissionTime(), flicker_duration = duration, tex_i = i, tex = ship.Textures[i] } )
                end
            end
        end
    end
]

$On Gameplay Start: [

    flickering_glowmaps = {}

]

$State: GS_STATE_GAME_PLAY

$On Frame: [

    if flickering_glowmaps and table.maxn(flickering_glowmaps) > 0 then
        for i=1,table.maxn(flickering_glowmaps) do
            flicker_time_elapsed = mn.getMissionTime() - flickering_glowmaps[i].flicker_start_time

            if flicker_time_elapsed < flickering_glowmaps[i].flicker_duration then
                ship = mn.getObjectFromSignature(flickering_glowmaps[i].ship_signature)

                if ship == nil or not ship:isValid() or ship.Textures == nil or not ship.Textures:isValid() then
                    table.remove(flickering_glowmaps, i)

                    break;
                end

                if (math.random() * flickering_glowmaps[i].flicker_duration) > flicker_time_elapsed then
                    ship.Textures[flickering_glowmaps[i].tex_i] = flickering_glowmaps[i].tex
                    
                    mn.runSEXP("(set-thrusters-status !true! !" .. ship.Name .. "!)")
                else
                    ship.Textures[flickering_glowmaps[i].tex_i] = glowmap_replacement

                    mn.runSEXP("(set-thrusters-status !false! !" .. ship.Name .. "!)")
                end
            else
                table.remove(flickering_glowmaps, i)

                -- Removing an element might make the loop break, so let's just
                -- bail out for this frame rather than do something fancy...
                break;
            end
        end
    end

]

#End