Ejemplo n.º 1
0
static Mix_Music *loadMusic(const std::string &filename)
{
    ResourceManager *resman = ResourceManager::getInstance();
    std::string path = resman->getPath(paths.getStringValue("music") + filename);

    if (path.find(".zip/") != std::string::npos ||
        path.find(".zip\\") != std::string::npos)
    {
        // Music file is a virtual file inside a zip archive - we have to copy
        // it to a temporary physical file so that SDL_mixer can stream it.
        logger->log("Loading music \"%s\" from temporary file tempMusic.ogg",
                    path.c_str());
        bool success = resman->copyFile(
                               paths.getStringValue("music")
                               + filename, "tempMusic.ogg");
        if (success)
            path = resman->getPath("tempMusic.ogg");
        else
            return NULL;
    }
    else
    {
        logger->log("Loading music \"%s\"", path.c_str());
    }

    Mix_Music *music = Mix_LoadMUS(path.c_str());

    if (!music)
    {
        logger->log("Mix_LoadMUS() Error loading '%s': %s", path.c_str(),
                    Mix_GetError());
    }

    return music;
}
Ejemplo n.º 2
0
Gui::Gui(Graphics *graphics):
    mCustomCursor(false),
    mMouseCursors(NULL),
    mMouseCursorAlpha(1.0f),
    mMouseInactivityTimer(0),
    mCursorType(CURSOR_POINTER)
{
    logger->log("Initializing GUI...");
    // Set graphics
    setGraphics(graphics);

    // Set image loader
    static ImageLoader imageLoader;
    gcn::Image::setImageLoader(&imageLoader);

    // Set input
    guiInput = new SDLInput;
    setInput(guiInput);

    // Set focus handler
    delete mFocusHandler;
    mFocusHandler = new FocusHandler;

    // Initialize top GUI widget
    WindowContainer *guiTop = new WindowContainer;
    guiTop->setFocusable(true);
    guiTop->setSize(graphics->getWidth(), graphics->getHeight());
    guiTop->setOpaque(false);
    Window::setWindowContainer(guiTop);
    setTop(guiTop);

    ResourceManager *resman = ResourceManager::getInstance();

    // Set global font
    const int fontSize = config.getValue("fontSize", 11);
    std::string fontFile = branding.getValue("font", "fonts/dejavusans.ttf");
    std::string path = resman->getPath(fontFile);

    try
    {
        mGuiFont = new TrueTypeFont(path, fontSize);
        mInfoParticleFont = new TrueTypeFont(path, fontSize, TTF_STYLE_BOLD);
    }
    catch (gcn::Exception e)
    {
        logger->error(std::string("Unable to load '") + fontFile +
                      std::string("': ") + e.getMessage());
    }

    // Set bold font
    fontFile = branding.getValue("boldFont", "fonts/dejavusans-bold.ttf");
    path = resman->getPath(fontFile);
    try
    {
        boldFont = new TrueTypeFont(path, fontSize);
    }
    catch (gcn::Exception e)
    {
        logger->error(std::string("Unable to load '") + fontFile +
                      std::string("': ") + e.getMessage());
    }

    // Set mono font
    fontFile = branding.getValue("monoFont", "fonts/dejavusans-mono.ttf");
    path = resman->getPath(fontFile);
    try
    {
        monoFont = new TrueTypeFont(path, fontSize);
    }
    catch (gcn::Exception e)
    {
        logger->error(std::string("Unable to load '") + fontFile +
                      std::string("': ") + e.getMessage());
    }

    gcn::Widget::setGlobalFont(mGuiFont);

    // Initialize mouse cursor and listen for changes to the option
    setUseCustomCursor(config.getBoolValue("customcursor"));
    mConfigListener = new GuiConfigListener(this);
    mConfigListener->listen(Event::ConfigChannel);
}
Ejemplo n.º 3
0
Client::Client(const Options &options):
    mOptions(options),
    mGame(0),
    mCurrentDialog(0),
    mQuitDialog(0),
    mDesktop(0),
    mSetupButton(0),
    mState(STATE_CHOOSE_SERVER),
    mOldState(STATE_START),
    mStateAfterOkDialog(mState),
    mIcon(0),
    mLogicCounterId(0),
    mSecondsCounterId(0),
    mLimitFps(false)
{
    assert(!mInstance);
    mInstance = this;

    logger = new Logger;

    // Set default values for configuration files
    branding.setDefaultValues(getBrandingDefaults());
    paths.setDefaultValues(getPathsDefaults());
    config.setDefaultValues(getConfigDefaults());

    // Load branding information
    if (!options.brandingPath.empty())
    {
        branding.init(options.brandingPath);
    }

    initRootDir();
    initHomeDir();
    initConfiguration();

    chatLogger = new ChatLogger;
    if (options.chatLogDir.empty())
        chatLogger->setLogDir(mLocalDataDir + std::string("/logs/"));
    else
        chatLogger->setLogDir(options.chatLogDir);

    // Configure logger
    logger->setLogFile(mLocalDataDir + std::string("/mana.log"));
    logger->setLogToStandardOut(config.getBoolValue("logToStandardOut"));

    // Log the mana version
    logger->log("Mana %s", FULL_VERSION);

    initScreenshotDir();

    // Initialize SDL
    logger->log("Initializing SDL...");
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0)
    {
        logger->error(strprintf("Could not initialize SDL: %s",
                      SDL_GetError()));
    }
    atexit(SDL_Quit);

    SDL_EnableUNICODE(1);
    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

    SDL_WM_SetCaption(branding.getValue("appName", "Mana").c_str(), NULL);

    ResourceManager *resman = ResourceManager::getInstance();

    if (!resman->setWriteDir(mLocalDataDir))
    {
        logger->error(strprintf("%s couldn't be set as home directory! "
                                "Exiting.", mLocalDataDir.c_str()));
    }

    Image::SDLsetEnableAlphaCache(config.getValue("alphaCache", true));

#if defined __APPLE__
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
    char path[PATH_MAX];
    if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path,
                                          PATH_MAX))
    {
        fprintf(stderr, "Can't find Resources directory\n");
    }
    CFRelease(resourcesURL);
    strncat(path, "/data", PATH_MAX - 1);
    resman->addToSearchPath(path, false);
    mPackageDir = path;
#else
    resman->addToSearchPath(PKG_DATADIR "data", false);
    mPackageDir = PKG_DATADIR "data";
#endif

    resman->addToSearchPath("data", false);

    // Add branding/data to PhysFS search path
    if (!options.brandingPath.empty())
    {
        std::string path = options.brandingPath;

        // Strip blah.mana from the path
#ifdef _WIN32
        int loc1 = path.find_last_of('/');
        int loc2 = path.find_last_of('\\');
        int loc = std::max(loc1, loc2);
#else
        int loc = path.find_last_of('/');
#endif
        if (loc > 0)
            resman->addToSearchPath(path.substr(0, loc + 1) + "data", false);
    }

    // Add the main data directories to our PhysicsFS search path
    if (!options.dataPath.empty())
        resman->addToSearchPath(options.dataPath, false);

    // Add the local data directory to PhysicsFS search path
    resman->addToSearchPath(mLocalDataDir, false);

    std::string iconFile = branding.getValue("appIcon", "icons/mana");
#ifdef _WIN32
    iconFile += ".ico";
#else
    iconFile += ".png";
#endif
    iconFile = resman->getPath(iconFile);
    logger->log("Loading icon from file: %s", iconFile.c_str());
#ifdef _WIN32
    static SDL_SysWMinfo pInfo;
    SDL_GetWMInfo(&pInfo);
    // Attempt to load icon from .ico file
    HICON icon = (HICON) LoadImage(NULL,
                                   iconFile.c_str(),
                                   IMAGE_ICON, 64, 64, LR_LOADFROMFILE);
    // If it's failing, we load the default resource file.
    if (!icon)
        icon = LoadIcon(GetModuleHandle(NULL), "A");

    if (icon)
        SetClassLong(pInfo.window, GCL_HICON, (LONG) icon);
#else
    mIcon = IMG_Load(iconFile.c_str());
    if (mIcon)
    {
        SDL_SetAlpha(mIcon, SDL_SRCALPHA, SDL_ALPHA_OPAQUE);
        SDL_WM_SetIcon(mIcon, NULL);
    }
#endif

    bool useOpenGL = !mOptions.noOpenGL && (config.getValue("opengl", 1) == 1);

    // Set up the transparency option for low CPU when not using OpenGL.
    if (!useOpenGL && (config.getValue("disableTransparency", 0) == 1))
        Image::SDLdisableTransparency();

#ifdef USE_OPENGL

    // Setup image loading for the right image format
    Image::setLoadAsOpenGL(useOpenGL);

    // Create the graphics context
    graphics = useOpenGL ? new OpenGLGraphics : new Graphics;
#else
    // Create the graphics context
    graphics = new Graphics;
#endif

    const int width = config.getIntValue("screenwidth");
    const int height = config.getIntValue("screenheight");
    const int bpp = 0;
    const bool fullscreen = config.getBoolValue("screen");
    const bool hwaccel = config.getBoolValue("hwaccel");

    // Try to set the desired video mode
    if (!graphics->setVideoMode(width, height, bpp, fullscreen, hwaccel))
    {
        logger->error(strprintf("Couldn't set %dx%dx%d video mode: %s",
            width, height, bpp, SDL_GetError()));
    }

    // Initialize for drawing
    graphics->_beginDraw();

    Theme::prepareThemePath();

    // Initialize the item and emote shortcuts.
    itemShortcut = new ItemShortcut;
    emoteShortcut = new EmoteShortcut;

    gui = new Gui(graphics);

    // Initialize sound engine
    try
    {
        if (config.getBoolValue("sound"))
            sound.init();

        sound.setSfxVolume(config.getIntValue("sfxVolume"));
        sound.setNotificationsVolume(config.getIntValue("notificationsVolume"));
        sound.setMusicVolume(config.getIntValue("musicVolume"));
    }
    catch (const char *err)
    {
        mState = STATE_ERROR;
        errorMessage = err;
        logger->log("Warning: %s", err);
    }

    // Initialize keyboard
    keyboard.init();

    // Initialise player relations
    player_relations.init();

    userPalette = new UserPalette;
    setupWindow = new Setup;

    sound.playMusic(branding.getStringValue("loginMusic"));

    // Initialize default server
    mCurrentServer.hostname = options.serverName;
    mCurrentServer.port = options.serverPort;
    loginData.username = options.username;
    loginData.password = options.password;
    loginData.remember = config.getBoolValue("remember");
    loginData.registerLogin = false;

    if (mCurrentServer.hostname.empty())
        mCurrentServer.hostname = branding.getValue("defaultServer","").c_str();

    if (mCurrentServer.port == 0)
    {
        mCurrentServer.port = (short) branding.getValue("defaultPort",
                                                                  DEFAULT_PORT);
        mCurrentServer.type = ServerInfo::parseType(
                           branding.getValue("defaultServerType", "tmwathena"));
    }

    if (chatLogger)
        chatLogger->setServerName(mCurrentServer.hostname);

    if (loginData.username.empty() && loginData.remember)
        loginData.username = config.getStringValue("username");

    if (mState != STATE_ERROR)
        mState = STATE_CHOOSE_SERVER;

    // Initialize logic and seconds counters
    tick_time = 0;
    mLogicCounterId = SDL_AddTimer(MILLISECONDS_IN_A_TICK, nextTick, NULL);
    mSecondsCounterId = SDL_AddTimer(1000, nextSecond, NULL);

    // Initialize frame limiting
    SDL_initFramerate(&mFpsManager);

    listen(Event::ConfigChannel);

    //TODO: fix having to fake a option changed event
    Event fakeevent(Event::ConfigOptionChanged);
    fakeevent.setString("option", "fpslimit");
    event(Event::ConfigChannel, fakeevent);

    // Initialize PlayerInfo
    PlayerInfo::init();
}
Ejemplo n.º 4
0
/**
 * Do all initialization stuff.
 */
void initEngine()
{
  gcn::SDLImageLoader* sdlImageLoader;

  // Initialize SDL
  logger->log("[SDL] Initializing SDL...");
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) {
    std::cerr << "Could not initialize SDL: " <<
      SDL_GetError() << std::endl;
    exit(1);
  }
  atexit(SDL_Quit);

  SDL_EnableUNICODE(1);
  SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

  std::string title = "particlEd: ";
  title += options.effectFile;

  SDL_WM_SetCaption(title.c_str(), NULL);
  logger->log("[SDL] OK.");

  // Resource Manager
  logger->log("[RM] Initializing Resource Manager");
  ResourceManager *resman = ResourceManager::getInstance();

  logger->log("[RM] adding directory to search path");
  if (options.dataDir.empty()) {
    logger->log("No data directory specified; setting \".\"");
    resman->addToSearchPath(".", false);
  } else {
    resman->addToSearchPath(options.dataDir, false);
  }
  // directory with particlEd's own data:
  resman->addToSearchPath("data", false);

  logger->log("[RM] OK.");

  logger->log("[GFX] Setting up video.");
  int width = options.winWidth;
  int height = options.winHeight+50;
  int bpp = 0;
  bool fullscreen = 0;
  bool hwaccel = 0;

  graphics = new Graphics();

  // Try to set the desired video mode
  if (!graphics->setVideoMode(width, height, bpp, fullscreen, hwaccel))
    {
      std::cerr << "Couldn't set "
		<< width << "x" << height << "x" << bpp << " video mode: "
		<< SDL_GetError() << std::endl;
      exit(1);
    }

  logger->log("[GFX] initializing for drawing");

  // Initialize for drawing
  graphics->_beginDraw();

  logger->log("[GFX] Ok.");

  gui = new gcn::Gui();
  gui->setGraphics(graphics);

  // temporarily use gcn::SDLImageLoader - TMW's ImageLoader doesn't load
  // the font for me
  sdlImageLoader = new gcn::SDLImageLoader();
  gcn::Image::setImageLoader(sdlImageLoader);  
  
  try {
    std::string fontpath = resman->getPath("browserfont.png");
    font = new gcn::ImageFont(fontpath.c_str(), " !\"#$%&'()=+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~|");
  } catch (gcn::Exception e) {
    logger->log("Error: Can't load font.");
    exit(1);
  }
  //gcn::Widget::setGlobalFont(font);
  delete sdlImageLoader;

  // font loaded; go for TMW's ImageLoader
  imageLoader = new ImageLoader();
  gcn::Image::setImageLoader(imageLoader);  

  top = new gcn::Container;
  top->setDimension(gcn::Rectangle(0,0,graphics->getWidth(),
				   graphics->getHeight()));
  gui->setTop(top);

  effectViewer = new EffectViewer();
  top->add(effectViewer);
  effectViewer->setDimension(gcn::Rectangle(0,0,
					    options.winWidth,
					    options.winHeight));

  playControlPanel = new PlayControlPanel();
  playControlPanel->setDimension(gcn::Rectangle(0,0,
						options.winWidth,50));
  playControlPanel->setPosition(0, options.winHeight);
  top->add(playControlPanel);
}