src/Graphics.cc
author terom
Mon, 08 Dec 2008 21:29:42 +0000
changeset 313 2562466a946d
parent 312 10743f190aab
child 315 fe9da2d5355e
permissions -rw-r--r--
draw rope behind player, fix LocalPlayer::draw warnings, don't show negative health

#include "Graphics.hh"
#include "GameState.hh"
#include <cmath>

Graphics::Graphics (Engine &engine, GameState &state) :
    CL_DisplayWindow(GRAPHICS_WINDOW_TITLE, GRAPHICS_RESOLUTION_WIDTH, GRAPHICS_RESOLUTION_HEIGHT),
    engine(engine), 
    state(state), 
    resolution(GRAPHICS_RESOLUTION_WIDTH, GRAPHICS_RESOLUTION_HEIGHT),
    update_timer(GRAPHICS_UPDATE_INTERVAL_MS),
    input(get_ic()->get_keyboard()),
    simple_font("Font2", engine.getResourceManager()) 
{

    // connect timer signal
    slots.connect(update_timer.sig_tick(), this, &Graphics::on_update);

    // enable
    update_timer.start();
}

void Graphics::check_input (void) {
    LocalPlayer *player;
    PlayerInput input_mask;
    TimeMS input_dt;
    
    // update gui flags
    this->flags = input.readGuiInput();

    // quit?
    if (flags & GUI_INPUT_QUIT) {
        engine.stop();

        return;
    }
     
    // stop here if we don't have a local player
    if ((player = state.getLocalPlayer()) == NULL)
        return;
    
    // dump debug info on stderr
    if (flags & GUI_INPUT_DEBUG_PLAYER)
        player->printDebugInfo();
    
    // build input_mask
    input.readPlayerInput(input_mask, input_dt);
    
    // apply input if there was any
    if (input_mask)
        player->handleInput(input_mask, input_dt);
}

static PixelDimension value_between (PixelDimension low, PixelDimension value, PixelDimension high) {
    if (value < low)
        return low;

    else if (value > high)
        return high;

    else
        return value;
}

void Graphics::do_redraw (void) {
    CL_GraphicContext *gc = get_gc();
    LocalPlayer *player;

    // calculate camera
    PixelCoordinate camera(0, 0);
    
    // ...to track our local player
    if ((player = state.getLocalPlayer()) != NULL) {
        PixelCoordinate target = player->getCoordinate() - resolution / 2;
        PixelCoordinate max = state.world.getDimensions() - resolution;
        
        // keep the terrain in view
        camera = PixelCoordinate(
            value_between(0, target.x, max.x),
            value_between(0, target.y, max.y)
        );
    }
    
    // Black background
    gc->clear(CL_Color::black);

    // Draw the game
    state.draw(this, camera, flags & GUI_INPUT_DISPLAY_WEAPON);

    // Draw box for player information
    if (player != NULL) {
        player->draw_player_info(this);
    }

    // Flip window buffer, sync
    flip(1);
}

void Graphics::on_update (TimeMS tick_length) {
    (void) tick_length;

    // check keyboard input
    check_input();

    // redraw display
    do_redraw();
}