diff --git a/JGE/include/JResourceManager.h b/JGE/include/JResourceManager.h index 398c8b637..b9dcaef73 100644 --- a/JGE/include/JResourceManager.h +++ b/JGE/include/JResourceManager.h @@ -26,8 +26,6 @@ using namespace std; #define INVALID_ID -1 class JRenderer; -class JParticleEffect; -class JMotionEmitter; class JSample; class JMusic; class JTexture; @@ -38,33 +36,30 @@ class JResourceManager { public: JResourceManager(); - ~JResourceManager(); + virtual ~JResourceManager(); //void SetResourceRoot(const string& resourceRoot); bool LoadResource(const string& resourceName); void RemoveAll(); - void RemoveGraphics(); - void RemoveSound(); - void RemoveFont(); - int CreateTexture(const string &textureName); + virtual int CreateTexture(const string &textureName); JTexture* GetTexture(const string &textureName); JTexture* GetTexture(int id); - int CreateQuad(const string &quadName, const string &textureName, float x, float y, float width, float height); + virtual int CreateQuad(const string &quadName, const string &textureName, float x, float y, float width, float height); JQuad* GetQuad(const string &quadName); JQuad* GetQuad(int id); - int LoadJLBFont(const string &fontName, int height); + virtual int LoadJLBFont(const string &fontName, int height); JLBFont* GetJLBFont(const string &fontName); JLBFont* GetJLBFont(int id); - int LoadMusic(const string &musicName); + virtual int LoadMusic(const string &musicName); JMusic* GetMusic(const string &musicName); JMusic* GetMusic(int id); - int LoadSample(const string &sampleName); + virtual int LoadSample(const string &sampleName); JSample* GetSample(const string &sampleName); JSample* GetSample(int id); @@ -76,7 +71,7 @@ public: // JMotionEmitter* GetMotionEmitter(const string &emitterName); // JMotionEmitter* GetMotionEmitter(int id); -private: +protected: //JRenderer *mRenderer; diff --git a/JGE/src/JResourceManager.cpp b/JGE/src/JResourceManager.cpp index c67c69caa..003b19924 100644 --- a/JGE/src/JResourceManager.cpp +++ b/JGE/src/JResourceManager.cpp @@ -16,6 +16,13 @@ #include "../include/JLBFont.h" #include "tinyxml/tinyxml.h" +#if defined (_DEBUG) && defined (WIN32) +#include "crtdbg.h" +#define NEW new(_NORMAL_BLOCK, __FILE__, __LINE__) +#else +#define NEW new +#endif + JResourceManager::JResourceManager() { //mResourceRoot = "Res/"; // default root folder @@ -299,7 +306,7 @@ int JResourceManager::CreateQuad(const string &quadName, const string &textureNa printf("creating quad:%s\n", quadName.c_str()); int id = mQuadList.size(); - mQuadList.push_back(new JQuad(tex, x, y, width, height)); + mQuadList.push_back(NEW JQuad(tex, x, y, width, height)); mQuadMap[quadName] = id; @@ -343,7 +350,7 @@ int JResourceManager::LoadJLBFont(const string &fontName, int height) int id = mFontList.size(); /////////////////////////////////////// - mFontList.push_back(new JLBFont(path.c_str(), height, true)); + mFontList.push_back(NEW JLBFont(path.c_str(), height, true)); mFontMap[fontName] = id; diff --git a/projects/mtg/Makefile b/projects/mtg/Makefile index f4bf76f29..cf8e5ec3e 100644 --- a/projects/mtg/Makefile +++ b/projects/mtg/Makefile @@ -1,4 +1,4 @@ -OBJS = objs/ActionElement.o objs/ActionLayer.o objs/ActionStack.o objs/AIMomirPlayer.o objs/AIPlayer.o objs/AIStats.o objs/Blocker.o objs/CardGui.o objs/CardDescriptor.o objs/CardDisplay.o objs/CardEffect.o objs/CardSelector.o objs/ConstraintResolver.o objs/Counters.o objs/Credits.o objs/Damage.o objs/DamagerDamaged.o objs/DeckDataWrapper.o objs/DeckStats.o objs/DuelLayers.o objs/Effects.o objs/ExtraCost.o objs/GameApp.o objs/GameLauncher.o objs/GameObserver.o objs/GameOptions.o objs/GameState.o objs/GameStateDuel.o objs/GameStateMenu.o objs/GameStateOptions.o objs/GameStateShop.o objs/GuiAvatars.o objs/GuiBackground.o objs/GuiCardsController.o objs/GuiCombat.o objs/GuiFrame.o objs/GuiHand.o objs/GuiLayers.o objs/GuiMana.o objs/GuiPhaseBar.o objs/GuiPlay.o objs/GuiStatic.o objs/Logger.o objs/ManaCost.o objs/ManaCostHybrid.o objs/MenuItem.o objs/MTGAbility.o objs/MTGCardInstance.o objs/MTGCard.o objs/MTGDeck.o objs/MTGDefinitions.o objs/MTGGamePhase.o objs/MTGGameZones.o objs/MTGRules.o objs/OptionItem.o objs/PhaseRing.o objs/Player.o objs/PlayerData.o objs/PlayGuiObjectController.o objs/PlayGuiObject.o objs/Pos.o objs/PriceList.o objs/ReplacementEffects.o objs/ShopItem.o objs/SimpleMenu.o objs/SimpleMenuItem.o objs/Subtypes.o objs/TargetChooser.o objs/TargetsList.o objs/TextScroller.o objs/TexturesCache.o objs/SimplePad.o objs/Token.o objs/Translate.o objs/utils.o objs/WEvent.o objs/WResourceManager.o +OBJS = objs/ActionElement.o objs/ActionLayer.o objs/ActionStack.o objs/AIMomirPlayer.o objs/AIPlayer.o objs/AIStats.o objs/Blocker.o objs/CardGui.o objs/CardDescriptor.o objs/CardDisplay.o objs/CardEffect.o objs/CardSelector.o objs/ConstraintResolver.o objs/Counters.o objs/Credits.o objs/Damage.o objs/DamagerDamaged.o objs/DeckDataWrapper.o objs/DeckStats.o objs/DuelLayers.o objs/Effects.o objs/ExtraCost.o objs/GameApp.o objs/GameLauncher.o objs/GameObserver.o objs/GameOptions.o objs/GameState.o objs/GameStateDuel.o objs/GameStateMenu.o objs/GameStateOptions.o objs/GameStateShop.o objs/GuiAvatars.o objs/GuiBackground.o objs/GuiCardsController.o objs/GuiCombat.o objs/GuiFrame.o objs/GuiHand.o objs/GuiLayers.o objs/GuiMana.o objs/GuiPhaseBar.o objs/GuiPlay.o objs/GuiStatic.o objs/Logger.o objs/ManaCost.o objs/ManaCostHybrid.o objs/MenuItem.o objs/MTGAbility.o objs/MTGCardInstance.o objs/MTGCard.o objs/MTGDeck.o objs/MTGDefinitions.o objs/MTGGamePhase.o objs/MTGGameZones.o objs/MTGRules.o objs/OptionItem.o objs/PhaseRing.o objs/Player.o objs/PlayerData.o objs/PlayGuiObjectController.o objs/PlayGuiObject.o objs/Pos.o objs/PriceList.o objs/ReplacementEffects.o objs/ShopItem.o objs/SimpleMenu.o objs/SimpleMenuItem.o objs/Subtypes.o objs/TargetChooser.o objs/TargetsList.o objs/TextScroller.o objs/SimplePad.o objs/Token.o objs/Translate.o objs/utils.o objs/WEvent.o objs/WResourceManager.o DEPS = $(patsubst objs/%.o, deps/%.d, $(OBJS)) RESULT = $(shell psp-config --psp-prefix 2> Makefile.cache) diff --git a/projects/mtg/include/GameApp.h b/projects/mtg/include/GameApp.h index db6381f14..dc437a8f2 100644 --- a/projects/mtg/include/GameApp.h +++ b/projects/mtg/include/GameApp.h @@ -29,8 +29,6 @@ #include "../include/MTGCard.h" #include "../include/MTGGameZones.h" -#include "../include/TexturesCache.h" - #include "../include/CardEffect.h" #define MAX_STATE 6 @@ -47,11 +45,6 @@ #define GAME_TYPE_RANDOM2 3 class MTGAllCards; -class TexturesCache; - - - - class GameApp: public JApp { @@ -83,7 +76,6 @@ class GameApp: public JApp void LoadGameStates(); void SetNextState(int state); - static WResourceManager * CommonRes; static hgeParticleSystem * Particles[6]; static int HasMusic; static string systemError; diff --git a/projects/mtg/include/GameStateDeckViewer.h b/projects/mtg/include/GameStateDeckViewer.h index ef6cc1494..225952797 100644 --- a/projects/mtg/include/GameStateDeckViewer.h +++ b/projects/mtg/include/GameStateDeckViewer.h @@ -8,7 +8,7 @@ #include "../include/GameState.h" #include "../include/SimpleMenu.h" -#include "../include/TexturesCache.h" +#include "../include/WResourceManager.h" #include "../include/CardGui.h" #include "../include/GameOptions.h" #include "../include/PriceList.h" @@ -144,13 +144,11 @@ class GameStateDeckViewer: public GameState, public JGuiListener pricelist = NEW PriceList(RESPATH"/settings/prices.dat",mParent->collection); playerdata = NEW PlayerData(mParent->collection); sellMenu = NULL; - myCollection = NEW DeckDataWrapper(NEW MTGDeck(options.profileFile(PLAYER_COLLECTION,"",false).c_str(), &cache,mParent->collection)); + myCollection = NEW DeckDataWrapper(NEW MTGDeck(options.profileFile(PLAYER_COLLECTION,"",false).c_str(), mParent->collection)); displayed_deck = myCollection; myDeck = NULL; - menuFont = GameApp::CommonRes->GetJLBFont(Constants::MENU_FONT); - mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); - - + menuFont = resources.GetJLBFont(Constants::MENU_FONT); + mFont = resources.GetJLBFont(Constants::MAIN_FONT); menu = NEW SimpleMenu(11,this,menuFont,SCREEN_WIDTH/2-100,20); @@ -160,29 +158,29 @@ class GameStateDeckViewer: public GameState, public JGuiListener //icon images - mIcons[Constants::MTG_COLOR_ARTIFACT] = GameApp::CommonRes->GetQuad("c_artifact"); - mIcons[Constants::MTG_COLOR_LAND] = GameApp::CommonRes->GetQuad("c_land"); - mIcons[Constants::MTG_COLOR_WHITE] = GameApp::CommonRes->GetQuad("c_white"); - mIcons[Constants::MTG_COLOR_RED] = GameApp::CommonRes->GetQuad("c_red"); - mIcons[Constants::MTG_COLOR_BLACK] = GameApp::CommonRes->GetQuad("c_black"); - mIcons[Constants::MTG_COLOR_BLUE] = GameApp::CommonRes->GetQuad("c_blue"); - mIcons[Constants::MTG_COLOR_GREEN] = GameApp::CommonRes->GetQuad("c_green"); + mIcons[Constants::MTG_COLOR_ARTIFACT] = resources.GetQuad("c_artifact"); + mIcons[Constants::MTG_COLOR_LAND] = resources.GetQuad("c_land"); + mIcons[Constants::MTG_COLOR_WHITE] = resources.GetQuad("c_white"); + mIcons[Constants::MTG_COLOR_RED] = resources.GetQuad("c_red"); + mIcons[Constants::MTG_COLOR_BLACK] = resources.GetQuad("c_black"); + mIcons[Constants::MTG_COLOR_BLUE] = resources.GetQuad("c_blue"); + mIcons[Constants::MTG_COLOR_GREEN] = resources.GetQuad("c_green"); for (int i=0; i < 7; i++){ mIcons[i]->SetHotSpot(16,16); } - - - pspIconsTexture = GameApp::CommonRes->LoadTexture("iconspsp.png", TEX_TYPE_USE_VRAM); + + //Grab a texture in VRAM. + pspIconsTexture = resources.RetrieveTexture("iconspsp.png",RETRIEVE_VRAM); for (int i=0; i < 8; i++){ - pspIcons[i] = NEW JQuad(pspIconsTexture, i*32, 0, 32, 32); + pspIcons[i] = resources.RetrieveQuad("iconspsp.png", i*32, 0, 32, 32); pspIcons[i]->SetHotSpot(16,16); } - backQuad = GameApp::CommonRes->GetQuad("back"); + backQuad = resources.GetQuad("back"); //menuFont = NEW JLBFont("graphics/f3",16); - menuFont = GameApp::CommonRes->GetJLBFont("f3"); + menuFont = resources.GetJLBFont("f3"); welcome_menu = NEW SimpleMenu(10,this,menuFont,20,20); int nbDecks = fillDeckMenu(welcome_menu,options.profileFile()); welcome_menu->Add(nbDecks+1, "--NEW--"); @@ -193,7 +191,7 @@ class GameStateDeckViewer: public GameState, public JGuiListener JSoundSystem::GetInstance()->StopMusic(GameApp::music); SAFE_DELETE(GameApp::music); } - GameApp::music = GameApp::CommonRes->ssLoadMusic("track1.mp3"); + GameApp::music = resources.ssLoadMusic("track1.mp3"); if (GameApp::music){ JSoundSystem::GetInstance()->PlayMusic(GameApp::music, true); } @@ -225,9 +223,10 @@ class GameStateDeckViewer: public GameState, public JGuiListener } SAFE_DELETE(welcome_menu); SAFE_DELETE(menu); - SAFE_DELETE(pspIconsTexture); + + resources.Release(pspIconsTexture); for (int i=0; i < 8; i++){ - SAFE_DELETE(pspIcons[i]); + pspIcons[i] = NULL; //The quads these point to are released with the texture. } SAFE_DELETE(myCollection); SAFE_DELETE(myDeck); @@ -505,7 +504,7 @@ class GameStateDeckViewer: public GameState, public JGuiListener } void renderOnScreenMenu(){ - JLBFont * font = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * font = resources.GetJLBFont(Constants::MAIN_FONT); font->SetColor(ARGB(255,255,255,255)); JRenderer * r = JRenderer::GetInstance(); float pspIconsSize = 0.5; @@ -617,15 +616,10 @@ class GameStateDeckViewer: public GameState, public JGuiListener JQuad * quad = backQuad; int showName = 1; - if (cache.isInCache(card) || last_user_activity > (abs(2-id) + 1)* NO_USER_ACTIVITY_SHOWCARD_DELAY){ - quad = cache.getQuad(card); - showName = 0; - } - - - + quad = resources.RetrieveCard(card); if (quad){ + showName = 0; int quadAlpha = alpha; if ( !displayed_deck->cards[card]) quadAlpha /=2; quad->SetColor(ARGB(mAlpha,quadAlpha,quadAlpha,quadAlpha)); @@ -641,7 +635,7 @@ class GameStateDeckViewer: public GameState, public JGuiListener }else{ Pos pos = Pos(x, y, scale* 285/250, 0.0, 255); CardGui::alternateRender(card, pos); - quad = cache.getThumb(card); + quad = resources.RetrieveCard(card,CACHE_THUMB); if (quad){ float _scale = 285 * scale / quad->mHeight; quad->SetColor(ARGB(40,255,255,255)); @@ -727,12 +721,12 @@ class GameStateDeckViewer: public GameState, public JGuiListener int loadDeck(int deckid){ SAFE_DELETE(myCollection); string profile = options[Options::ACTIVE_PROFILE].str; - myCollection = NEW DeckDataWrapper(NEW MTGDeck(options.profileFile(PLAYER_COLLECTION,"",false).c_str(), &cache,mParent->collection)); + myCollection = NEW DeckDataWrapper(NEW MTGDeck(options.profileFile(PLAYER_COLLECTION,"",false).c_str(), mParent->collection)); displayed_deck = myCollection; char deckname[256]; sprintf(deckname,"deck%i.txt",deckid); SAFE_DELETE(myDeck); - myDeck = NEW DeckDataWrapper(NEW MTGDeck(options.profileFile(deckname).c_str(), &cache,mParent->collection)); + myDeck = NEW DeckDataWrapper(NEW MTGDeck(options.profileFile(deckname).c_str(), mParent->collection)); MTGCard * current = myDeck->getNext(); while (current){ int howmanyinDeck = myDeck->cards[current]; diff --git a/projects/mtg/include/GameStateMenu.h b/projects/mtg/include/GameStateMenu.h index eff9a661e..d1616e478 100644 --- a/projects/mtg/include/GameStateMenu.h +++ b/projects/mtg/include/GameStateMenu.h @@ -17,13 +17,10 @@ class GameStateMenu: public GameState, public JGuiListener SimpleMenu* gameTypeMenu; int hasChosenGameType; JQuad * mIcons[10]; - JTexture * mIconsTexture; JTexture * bgTexture; JTexture * movingWTexture; JQuad * mBg; JQuad * mMovingW; - JTexture * splashTex; - JQuad * splashQuad; float mCreditsYPos; int currentState; //JMusic * bgMusic; diff --git a/projects/mtg/include/MTGCardInstance.h b/projects/mtg/include/MTGCardInstance.h index 3fdad75e0..0f3969bc3 100644 --- a/projects/mtg/include/MTGCardInstance.h +++ b/projects/mtg/include/MTGCardInstance.h @@ -4,7 +4,7 @@ #include "MTGCard.h" #include "MTGGameZones.h" #include "MTGAbility.h" -#include "TexturesCache.h" +#include "WResourceManager.h" #include "ManaCost.h" #include "Blocker.h" #include "Damage.h" @@ -15,7 +15,6 @@ class MTGCardInstance; class MTGPlayerCards; class MTGAbility; class MTGCard; -class TexturesCache; class ManaCost; class UntapBlockers; class CardDescriptor; diff --git a/projects/mtg/include/MTGDeck.h b/projects/mtg/include/MTGDeck.h index 763238044..aa5808711 100644 --- a/projects/mtg/include/MTGDeck.h +++ b/projects/mtg/include/MTGDeck.h @@ -5,7 +5,7 @@ #include "../include/MTGDefinitions.h" #include "../include/GameApp.h" -#include "../include/TexturesCache.h" +#include "../include/WResourceManager.h" #include @@ -48,16 +48,13 @@ private: void initCounters(); public: - TexturesCache * mCache; vector ids; map collection; MTGAllCards(); ~MTGAllCards(); - MTGAllCards(TexturesCache * cache); MTGCard * _(int id); void destroyAllCards(); MTGAllCards(const char * config_file, const char * set_name); - MTGAllCards(const char * config_file, const char * set_name, TexturesCache * cache); MTGCard * getCardById(int id); MTGCard * getCardByName(string name); int load(const char * config_file, const char * setName, int autoload = 1); @@ -80,14 +77,13 @@ class MTGDeck{ int total_cards; public: - TexturesCache * mCache; MTGAllCards * database; map cards; string meta_desc; string meta_name; int totalCards(); - MTGDeck(TexturesCache * cache, MTGAllCards * _allcards); - MTGDeck(const char * config_file, TexturesCache * cache, MTGAllCards * _allcards, int meta_only = 0); + MTGDeck(MTGAllCards * _allcards); + MTGDeck(const char * config_file, MTGAllCards * _allcards, int meta_only = 0); int addRandomCards(int howmany, int * setIds = NULL, int nbSets = 0, int rarity = -1, const char * subtype = NULL, int * colors = NULL, int nbcolors = 0); int add(int cardid); int add(MTGDeck * deck); // adds the contents of "deck" into myself diff --git a/projects/mtg/include/TexturesCache.h b/projects/mtg/include/TexturesCache.h deleted file mode 100644 index 709565d07..000000000 --- a/projects/mtg/include/TexturesCache.h +++ /dev/null @@ -1,84 +0,0 @@ -#ifndef _TEXTURES_CACHE_H -#define _TEXTURES_CACHE_H - -#define CACHE_SIZE_PIXELS 2000000 - -#define CACHE_CARD 1 -#define CACHE_THUMB 2 - -#include -#include - -#include - -using std::map; - -#include "MTGDeck.h" - -class MTGCard; - -class CachedTexture{ - protected: - JTexture* tex; - JQuad* quad; - public: - int lastTime; - int nbpixels; - - - JQuad * getQuad(); - - void init(string filename); - CachedTexture(MTGCard * card, int type); - CachedTexture(string filename); - ~CachedTexture(); -}; - - -class TexturesCache{ - protected: - int lastTime; - int nb_textures; - int delete_previous; - int totalsize; - map cache; - public: - int isInCache(MTGCard * card, int type=CACHE_CARD); - TexturesCache(); - ~TexturesCache(); - int removeOldestQuad(); - void removeQuad(string id); - int cleanup(); - CachedTexture * getCacheByCard(MTGCard * card, int type=CACHE_CARD); - JQuad * getQuad(MTGCard * card, int type=CACHE_CARD); - JQuad * getThumb(MTGCard * card){return getQuad(card, CACHE_THUMB);}; - JQuad * getQuad(string path,MTGCard * card = NULL, int type=0); -}; -extern TexturesCache cache; - - -class SampleCached{ -public: - int lastTime; - JSample * sample; - SampleCached(int _lastTime, JSample * _sample):lastTime(_lastTime),sample(_sample){}; - ~SampleCached(){SAFE_DELETE(sample);}; -}; - -class SampleCache{ -protected: - int lastTime; - map cache; - static SampleCache * mInstance; - void cleanCache(); - void cleanOldest(); - ~SampleCache(); -public: - static SampleCache * GetInstance(); - static void DestroyInstance(); - SampleCache(){lastTime = 0;}; - JSample * getSample(string filename); - -}; - -#endif diff --git a/projects/mtg/include/WResourceManager.h b/projects/mtg/include/WResourceManager.h index e1efd7d89..8b5f4db28 100644 --- a/projects/mtg/include/WResourceManager.h +++ b/projects/mtg/include/WResourceManager.h @@ -1,57 +1,127 @@ #ifndef _WRESOURCEMANAGER_H_ #define _WRESOURCEMANAGER_H_ #include +#include #include +#include "MTGDeck.h" +#include "MTGCard.h" + +#define CACHE_SIZE_PIXELS 2000000 + +class WCachedResource{ +public: + friend class WResourceManager; + bool isLocked(); //Is the resource locked? + void lock(); //Lock it. + void unlock(bool force = false); //Unlock it. If force, then set locks to 0. + void hit(); //Update resource last used time. + + WCachedResource(); + +protected: + unsigned int lastTime; + unsigned char locks; //Remember to unlock when we're done using locked stuff, or else this'll be useless. +}; + +class WCachedTexture: public WCachedResource{ +public: + friend class WResourceManager; + WCachedTexture(); + ~WCachedTexture(); + + JTexture * GetTexture(); //Return this texture as is. Does not make a new one. + JQuad * GetQuad(float offX=0.0f, float offY=0.0f, float width=0.0f, float height=0.0f); //Get us a new/existing quad. + JQuad * GetCard(float offX=0.0f, float offY=0.0f, float width=0.0f, float height=0.0f); //Same as above, but centered when new. + bool ReleaseQuad(JQuad* quad); //We're done with this quad, so delete and stop tracking. True if existed. +protected: + JTexture * texture; + vector trackedQuads; +}; + +class WCachedSample: public WCachedResource{ +public: + friend class WResourceManager; + WCachedSample(); + ~WCachedSample(); + + JSample * GetSample(); //Return this sample. +protected: + JSample * sample; +}; + +enum ENUM_RETRIEVE_STYLE{ + RETRIEVE_EXISTING, //Only returns a resource if it already exists. Does not lock or unlock. + RETRIEVE_NORMAL, //Returns or creates a resource. Does not change lock status. + RETRIEVE_LOCK, //As above, locks cached resource. + RETRIEVE_UNLOCK, //As above, unlocks cached resource. + RETRIEVE_RESOURCE, //Only retrieves a managed resource. + RETRIEVE_VRAM, //If we create the texture, use vram. + RETRIEVE_MANAGE, //Permanently adds retrieved resource to resource manager. +}; + +enum ENUM_CACHE_SUBTYPE{ + CACHE_CARD, + CACHE_THUMB +}; + //This class is a wrapper for JResourceManager -class WResourceManager +class WResourceManager: public JResourceManager { public: WResourceManager(); ~WResourceManager(); - - //Wrapped from JResourceManager - void RemoveAll(){jrm->RemoveAll();} - void RemoveGraphics(){jrm->RemoveGraphics();} - void RemoveSound(){jrm->RemoveSound();} - void RemoveFont(){jrm->RemoveFont();} + JQuad * RetrieveCard(MTGCard * card, int type = CACHE_CARD, int style = RETRIEVE_NORMAL); + JSample * RetrieveSample(string filename, int style = RETRIEVE_NORMAL); + JTexture * RetrieveTexture(string filename, int style = RETRIEVE_NORMAL); + JQuad * RetrieveQuad(string filename, float offX=0.0f, float offY=0.0f, float width=0.0f, float height=0.0f, string resname="", int style = RETRIEVE_NORMAL); + void Release(JTexture * tex); + void Release(JQuad * quad); + void Release(JSample * sample); - int CreateTexture(const string &textureName); - JTexture* GetTexture(const string &textureName); - JTexture* GetTexture(int id); + unsigned int nowTime(); - int CreateQuad(const string &quadName, const string &textureName, float x, float y, float width, float height); - JQuad* GetQuad(const string &quadName); - JQuad* GetQuad(int id); - - int LoadJLBFont(const string &fontName, int height); - JLBFont* GetJLBFont(const string &fontName); - JLBFont* GetJLBFont(int id); - - int LoadMusic(const string &musicName); - JMusic* GetMusic(const string &musicName); - JMusic* GetMusic(int id); - - int LoadSample(const string &sampleName); - JSample* GetSample(const string &sampleName); - JSample* GetSample(int id); - - //Wrapped from other bits, if we want them. - JTexture* LoadTexture(const char* filename, int mode = 0, int textureFormat = TEXTURE_FORMAT); - //Wrapped from JSoundSystem - JMusic * ssLoadMusic(const char *fileName); - JSample * ssLoadSample(const char *fileName); - - //Our New redirect system. - string graphicsFile(const string filename, const string specific = "", bool bFont = false); + //Our file redirect system. + string graphicsFile(const string filename, const string specific = ""); + string cardFile(const string filename, const string setname, const string specific = ""); string musicFile(const string filename, const string specific = ""); string sfxFile(const string filename, const string specific = ""); int fileOK(string filename, bool relative = false); -private: - JResourceManager * jrm; - map stopgap; -}; + + //Not part of our interface, but left public to maintain JResourceManager compatibility + //These are for managed resources only. + int CreateTexture(const string &textureName); + int CreateQuad(const string &quadName, const string &textureName, float x=0.0f, float y=0.0f, float width=0.0f, float height=0.0f); + int LoadJLBFont(const string &fontName, int height); + int LoadMusic(const string &musicName); + int LoadSample(const string &sampleName); + //Wrapped from JSoundSystem. TODO: Privatize. + JMusic * ssLoadMusic(const char *fileName); + JSample * ssLoadSample(const char *fileName); + +private: + bool RemoveOldestTexture(); + bool RemoveOldestSample(); + bool cleanup(); + + WCachedTexture * getCachedTexture(string filename, bool makenew = true, int mode = 0, int format = TEXTURE_FORMAT); + WCachedTexture * getCachedCard(MTGCard * card, int type = CACHE_CARD, bool makenew = true); + WCachedSample * getCachedSample(string filename, bool makenew = true); + + void FlattenTimes(); //To prevent bad cache timing on int overflow + //For cached stuff + map textureCache; + map sampleCache; + + //Current access time. + int lastTime; + //Statistics of record. + int nb_textures; + int totalsize; +}; + +extern WResourceManager resources; #endif \ No newline at end of file diff --git a/projects/mtg/src/AIPlayer.cpp b/projects/mtg/src/AIPlayer.cpp index c4d4e049b..feb457502 100644 --- a/projects/mtg/src/AIPlayer.cpp +++ b/projects/mtg/src/AIPlayer.cpp @@ -587,7 +587,7 @@ AIPlayer * AIPlayerFactory::createAIPlayer(MTGAllCards * collection, Player * op } - MTGDeck * tempDeck = NEW MTGDeck(deckFile, NULL, collection); + MTGDeck * tempDeck = NEW MTGDeck(deckFile, collection); MTGPlayerCards * deck = NEW MTGPlayerCards(collection,tempDeck); delete tempDeck; AIPlayerBaka * baka = NEW AIPlayerBaka(deck,deckFile, deckFileSmall, avatarFile); diff --git a/projects/mtg/src/ActionLayer.cpp b/projects/mtg/src/ActionLayer.cpp index d46fac986..b58c4d363 100644 --- a/projects/mtg/src/ActionLayer.cpp +++ b/projects/mtg/src/ActionLayer.cpp @@ -215,7 +215,7 @@ void ActionLayer::setMenuObject(Targetable * object){ SAFE_DELETE(abilitiesMenu); - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); abilitiesMenu = NEW SimpleMenu(10, this, mFont, 100, 100); for (int i=0;igetCurrentGamePhase() + 1) % Constants::MTG_PHASE_CLEANUP; - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); mFont->SetBase(0); mFont->SetScale(DEFAULT_MAIN_FONT_SCALE); char buffer[200]; @@ -50,14 +50,14 @@ int StackAbility::resolve(){ return (ability->resolve()); } void StackAbility::Render(){ - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); mFont->SetBase(0); mFont->SetScale(DEFAULT_MAIN_FONT_SCALE); char buffer[200]; sprintf(buffer, "%s", _(ability->getMenuText()).c_str()); mFont->DrawString(buffer, x + 30 , y, JGETEXT_LEFT); JRenderer * renderer = JRenderer::GetInstance(); - JQuad * quad = cache.getThumb(ability->source); + JQuad * quad = resources.RetrieveCard(ability->source,CACHE_THUMB); if (quad){ quad->SetColor(ARGB(255,255,255,255)); float scale = 30 / quad->mHeight; @@ -183,12 +183,12 @@ MTGCardInstance * Spell::getNextCardTarget(MTGCardInstance * previous){ } void Spell::Render(){ - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); mFont->SetBase(0); mFont->SetScale(DEFAULT_MAIN_FONT_SCALE); mFont->DrawString(_(source->name).c_str(), x + 30 , y, JGETEXT_LEFT); JRenderer * renderer = JRenderer::GetInstance(); - JQuad * quad = cache.getThumb(source); + JQuad * quad = resources.RetrieveCard(source,CACHE_THUMB); if (quad){ quad->SetColor(ARGB(255,255,255,255)); float scale = mHeight / quad->mHeight; @@ -205,7 +205,7 @@ void Spell::Render(){ // just overwrites it. // I stole the render code from RenderBig() in CardGUI.cpp - quad = cache.getQuad(source); + quad = resources.RetrieveCard(source); if (quad){ quad->SetColor(ARGB(220,255,255,255)); float scale = 257.f / quad->mHeight; @@ -217,7 +217,7 @@ void Spell::Render(){ Pos pos = Pos(10 + 90, 20 + 130, 0.9f, 0.0, 255); CardGui::alternateRender(mtgcard, pos); - quad = cache.getThumb(source); + quad = resources.RetrieveCard(source,CACHE_THUMB); if (quad){ float scale = 250 / quad->mHeight; quad->SetColor(ARGB(40,255,255,255)); @@ -268,7 +268,7 @@ int PutInGraveyard::resolve(){ } void PutInGraveyard::Render(){ - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); mFont->SetBase(0); mFont->SetScale(DEFAULT_MAIN_FONT_SCALE); if (!removeFromGame){ @@ -277,7 +277,7 @@ void PutInGraveyard::Render(){ mFont->DrawString(_("is exiled").c_str(), x + 30 , y, JGETEXT_LEFT); } JRenderer * renderer = JRenderer::GetInstance(); - JQuad * quad = cache.getThumb(card); + JQuad * quad = resources.RetrieveCard(card,CACHE_THUMB); if (quad){ quad->SetColor(ARGB(255,255,255,255)); float scale = 30 / quad->mHeight; @@ -305,7 +305,7 @@ int DrawAction::resolve(){ } void DrawAction::Render(){ - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); mFont->SetBase(0); mFont->SetScale(DEFAULT_MAIN_FONT_SCALE); char buffer[200]; @@ -789,13 +789,13 @@ void ActionStack::Render(){ if (current->state==NOT_RESOLVED) height += current->mHeight; } - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); mFont->SetBase(0); mFont->SetScale(DEFAULT_MAIN_FONT_SCALE); mFont->SetColor(ARGB(255,255,255,255)); JRenderer * renderer = JRenderer::GetInstance(); - //JQuad * back = GameApp::CommonRes->GetQuad("interrupt"); + //JQuad * back = resources.GetQuad("interrupt"); //float xScale = width / back->mWidth; //float yScale = height / back->mHeight; renderer->FillRoundRect(x0 + 16 ,y0 + 16 ,width +2 ,height +2 , 10, ARGB(128,0,0,0)); @@ -845,7 +845,7 @@ void ActionStack::Render(){ if (current->display) height += current->mHeight; } - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); mFont->SetBase(0); mFont->SetScale(DEFAULT_MAIN_FONT_SCALE); diff --git a/projects/mtg/src/CardGui.cpp b/projects/mtg/src/CardGui.cpp index b0334ffe5..b6b06a925 100644 --- a/projects/mtg/src/CardGui.cpp +++ b/projects/mtg/src/CardGui.cpp @@ -32,7 +32,7 @@ void CardGui::Update(float dt) void CardGui::Render() { - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); JRenderer * renderer = JRenderer::GetInstance(); GameObserver * game = GameObserver::GetInstance(); @@ -40,31 +40,31 @@ void CardGui::Render() TargetChooser * tc = NULL; if (game) tc = game->getCurrentTargetChooser(); - JQuad * quad = cache.getThumb(card); + JQuad * quad = resources.RetrieveCard(card,CACHE_THUMB); if (quad) { const float scale = actZ * 40 / quad->mHeight; - renderer->RenderQuad(GameApp::CommonRes->GetQuad("shadow"), actX + (scale-1)*15, actY + (scale-1)*15, actT, 28*scale, 40*scale); + renderer->RenderQuad(resources.GetQuad("shadow"), actX + (scale-1)*15, actY + (scale-1)*15, actT, 28*scale, 40*scale); quad->SetColor(ARGB(static_cast(actA),255,255,255)); renderer->RenderQuad(quad, actX, actY, actT, scale, scale); } else { const float scale = actZ; - renderer->RenderQuad(GameApp::CommonRes->GetQuad("shadow"), actX + (scale-1)*15, actY + (scale-1)*15, actT, 28*scale, 40*scale); + renderer->RenderQuad(resources.GetQuad("shadow"), actX + (scale-1)*15, actY + (scale-1)*15, actT, 28*scale, 40*scale); mFont->SetColor(ARGB(static_cast(actA), 0, 0, 0)); JQuad * icon = NULL; if (card->hasSubtype("plains")) - icon = GameApp::CommonRes->GetQuad("c_white"); + icon = resources.GetQuad("c_white"); else if (card->hasSubtype("swamp")) - icon = GameApp::CommonRes->GetQuad("c_black"); + icon = resources.GetQuad("c_black"); else if (card->hasSubtype("forest")) - icon = GameApp::CommonRes->GetQuad("c_green"); + icon = resources.GetQuad("c_green"); else if (card->hasSubtype("mountain")) - icon = GameApp::CommonRes->GetQuad("c_red"); + icon = resources.GetQuad("c_red"); else if (card->hasSubtype("island")) - icon = GameApp::CommonRes->GetQuad("c_blue"); + icon = resources.GetQuad("c_blue"); if (icon) icon->SetHotSpot(16,16); JQuad* q = alternateThumbQuad(card); @@ -96,13 +96,15 @@ JQuad * CardGui::alternateThumbQuad(MTGCard * card){ JQuad * q; switch(card->getColor()) { - case Constants::MTG_COLOR_GREEN: q = cache.getQuad("sets/green_thumb.jpg");break; - case Constants::MTG_COLOR_BLUE : q = cache.getQuad("sets/blue_thumb.jpg");break; - case Constants::MTG_COLOR_RED : q = cache.getQuad("sets/red_thumb.jpg");break; - case Constants::MTG_COLOR_BLACK: q = cache.getQuad("sets/black_thumb.jpg");break; - case Constants::MTG_COLOR_WHITE: q = cache.getQuad("sets/white_thumb.jpg");break; - default: q = cache.getQuad("sets/black_thumb.jpg");break; + case Constants::MTG_COLOR_GREEN: q = resources.RetrieveQuad("green_thumb.jpg");break; + case Constants::MTG_COLOR_BLUE : q = resources.RetrieveQuad("blue_thumb.jpg");break; + case Constants::MTG_COLOR_RED : q = resources.RetrieveQuad("red_thumb.jpg");break; + case Constants::MTG_COLOR_BLACK: q = resources.RetrieveQuad("black_thumb.jpg");break; + case Constants::MTG_COLOR_WHITE: q = resources.RetrieveQuad("white_thumb.jpg");break; + default: q = resources.RetrieveQuad("black_thumb.jpg");break; } + if(q && q->mTex) + q->SetHotSpot(q->mTex->mWidth/2,q->mTex->mHeight/2); return q; } @@ -112,19 +114,22 @@ void CardGui::alternateRender(MTGCard * card, const Pos& pos){ JQuad * q; switch(card->getColor()) { - case Constants::MTG_COLOR_GREEN: q = cache.getQuad("sets/green.jpg");break; - case Constants::MTG_COLOR_BLUE : q = cache.getQuad("sets/blue.jpg");break; - case Constants::MTG_COLOR_RED : q = cache.getQuad("sets/red.jpg");break; - case Constants::MTG_COLOR_BLACK: q = cache.getQuad("sets/black.jpg");break; - case Constants::MTG_COLOR_WHITE: q = cache.getQuad("sets/white.jpg");break; - default: q = cache.getQuad("sets/black.jpg");break; + case Constants::MTG_COLOR_GREEN: q = resources.RetrieveQuad("green.jpg");break; + case Constants::MTG_COLOR_BLUE : q = resources.RetrieveQuad("blue.jpg");break; + case Constants::MTG_COLOR_RED : q = resources.RetrieveQuad("red.jpg");break; + case Constants::MTG_COLOR_BLACK: q = resources.RetrieveQuad("black.jpg");break; + case Constants::MTG_COLOR_WHITE: q = resources.RetrieveQuad("white.jpg");break; + default: q = resources.RetrieveQuad("black.jpg");break; } + if(q && q->mTex) + q->SetHotSpot(q->mTex->mWidth/2,q->mTex->mHeight/2); + float scale = pos.actZ * 250 / q->mHeight; q->SetColor(ARGB((int)pos.actA,255,255,255)); renderer->RenderQuad(q, pos.actX, pos.actY, pos.actT, scale, scale); // Write the title - JLBFont * font = GameApp::CommonRes->GetJLBFont("magic"); + JLBFont * font = resources.GetJLBFont("magic"); float backup_scale = font->GetScale(); font->SetColor(ARGB((int)pos.actA, 0, 0, 0)); font->SetScale(0.8 * pos.actZ); @@ -217,7 +222,7 @@ void CardGui::alternateRender(MTGCard * card, const Pos& pos){ void CardGui::RenderBig(const Pos& pos){ JRenderer * renderer = JRenderer::GetInstance(); - JQuad * quad = cache.getQuad(card); + JQuad * quad = resources.RetrieveCard(card); if (quad){ quad->SetColor(ARGB((int)pos.actA,255,255,255)); float scale = pos.actZ * 257.f / quad->mHeight; @@ -226,7 +231,7 @@ void CardGui::RenderBig(const Pos& pos){ } JQuad * q; - if ((q = cache.getThumb(card))) + if ((q = resources.RetrieveCard(card,CACHE_THUMB))) { float scale = pos.actZ * 250 / q->mHeight; q->SetColor(ARGB((int)pos.actA,255,255,255)); diff --git a/projects/mtg/src/Credits.cpp b/projects/mtg/src/Credits.cpp index 8cea0e115..aca53f361 100644 --- a/projects/mtg/src/Credits.cpp +++ b/projects/mtg/src/Credits.cpp @@ -27,8 +27,7 @@ } Credits::~Credits(){ - SAFE_DELETE(unlockedTex); - SAFE_DELETE(unlockedQuad); + resources.Release(unlockedTex); for (unsigned int i = 0; iLoadTexture("unlocked.png", TEX_TYPE_USE_VRAM); - unlockedQuad = NEW JQuad(unlockedTex, 2, 2, 396, 96); + unlockedTex = resources.RetrieveTexture("unlocked.png", RETRIEVE_VRAM); + unlockedQuad = resources.RetrieveQuad("unlocked.png", 2, 2, 396, 96); options[Options::DIFFICULTY_MODE_UNLOCKED] = GameOption(1); options.save(); } else if ((unlocked = isMomirUnlocked())) { - unlockedTex = GameApp::CommonRes->LoadTexture("momir_unlocked.png", TEX_TYPE_USE_VRAM); - unlockedQuad = NEW JQuad(unlockedTex, 2, 2, 396, 96); + unlockedTex = resources.RetrieveTexture("momir_unlocked.png", RETRIEVE_VRAM); + unlockedQuad = resources.RetrieveQuad("momir_unlocked.png", 2, 2, 396, 96); options[Options::MOMIR_MODE_UNLOCKED] = GameOption(1); options.save(); } else if ((unlocked = isEvilTwinUnlocked())) { - unlockedTex = GameApp::CommonRes->LoadTexture("eviltwin_unlocked.png", TEX_TYPE_USE_VRAM); - unlockedQuad = NEW JQuad(unlockedTex, 2, 2, 396, 96); + unlockedTex = resources.RetrieveTexture("eviltwin_unlocked.png", RETRIEVE_VRAM); + unlockedQuad = resources.RetrieveQuad("eviltwin_unlocked.png", 2, 2, 396, 96); options[Options::EVILTWIN_MODE_UNLOCKED] = GameOption(1); options.save(); }else if((unlocked = isRandomDeckUnlocked())) { - unlockedTex = GameApp::CommonRes->LoadTexture("randomdeck_unlocked.png", TEX_TYPE_USE_VRAM); - unlockedQuad = NEW JQuad(unlockedTex, 2, 2, 396, 96); + unlockedTex = resources.RetrieveTexture("randomdeck_unlocked.png", RETRIEVE_VRAM); + unlockedQuad = resources.RetrieveQuad("randomdeck_unlocked.png", 2, 2, 396, 96); options[Options::RANDOMDECK_MODE_UNLOCKED] = GameOption(1); options.save(); }else if((unlocked = unlockRandomSet())) { - unlockedTex = GameApp::CommonRes->LoadTexture("set_unlocked.png", TEX_TYPE_USE_VRAM); - unlockedQuad = NEW JQuad(unlockedTex, 2, 2, 396, 96); + unlockedTex = resources.RetrieveTexture("set_unlocked.png", RETRIEVE_VRAM); + unlockedQuad = resources.RetrieveQuad("set_unlocked.png", 2, 2, 396, 96); char buffer[4096]; unlockedString = MtgSets::SetsList->values[unlocked -1]; sprintf(buffer,"unlocked_%s", unlockedString.c_str()); @@ -103,7 +102,7 @@ void Credits::compute(Player * _p1, Player * _p2, GameApp * _app){ options.save(); } if (unlocked){ - JSample * sample = SampleCache::GetInstance()->getSample("bonus.wav"); + JSample * sample = resources.RetrieveSample("bonus.wav"); if (sample) JSoundSystem::GetInstance()->PlaySample(sample); } } @@ -131,9 +130,9 @@ void Credits::compute(Player * _p1, Player * _p2, GameApp * _app){ void Credits::Render(){ GameObserver * g = GameObserver::GetInstance(); JRenderer * r = JRenderer::GetInstance(); - JLBFont * f = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); - JLBFont * f2 = GameApp::CommonRes->GetJLBFont(Constants::MENU_FONT); - JLBFont * f3 = GameApp::CommonRes->GetJLBFont(Constants::MAGIC_FONT); + JLBFont * f = resources.GetJLBFont(Constants::MAIN_FONT); + JLBFont * f2 = resources.GetJLBFont(Constants::MENU_FONT); + JLBFont * f3 = resources.GetJLBFont(Constants::MAGIC_FONT); f->SetScale(1); f2->SetScale(1); f3->SetScale(1); diff --git a/projects/mtg/src/Damage.cpp b/projects/mtg/src/Damage.cpp index 527b8135a..b4b60258f 100644 --- a/projects/mtg/src/Damage.cpp +++ b/projects/mtg/src/Damage.cpp @@ -4,7 +4,7 @@ #include "../include/Counters.h" #include "../include/WEvent.h" #include "../include/Translate.h" -#include "../include/TexturesCache.h" +#include "../include/WResourceManager.h" Damage::Damage(MTGCardInstance * source, Damageable * target) { init(source, target, source->getPower()); @@ -62,14 +62,14 @@ int Damage::resolve(){ } void Damage::Render(){ - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); mFont->SetBase(0); mFont->SetScale(DEFAULT_MAIN_FONT_SCALE); char buffer[200]; sprintf(buffer, _("Deals %i damage to").c_str(), damage); mFont->DrawString(buffer, x + 20 , y, JGETEXT_LEFT); JRenderer * renderer = JRenderer::GetInstance(); - JQuad * quad = cache.getThumb(source); + JQuad * quad = resources.RetrieveCard(source,CACHE_THUMB); if (quad){ float scale = 30 / quad->mHeight; renderer->RenderQuad(quad, x , y , 0,scale,scale); diff --git a/projects/mtg/src/DamagerDamaged.cpp b/projects/mtg/src/DamagerDamaged.cpp index b54494a18..1948c318d 100644 --- a/projects/mtg/src/DamagerDamaged.cpp +++ b/projects/mtg/src/DamagerDamaged.cpp @@ -51,7 +51,7 @@ void DamagerDamaged::clearDamage() void DamagerDamaged::Render(CombatStep mode) { TransientCardView::Render(); - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); mFont->SetBase(0); switch (mode) diff --git a/projects/mtg/src/ExtraCost.cpp b/projects/mtg/src/ExtraCost.cpp index 6ee619fff..970e9f42e 100644 --- a/projects/mtg/src/ExtraCost.cpp +++ b/projects/mtg/src/ExtraCost.cpp @@ -59,7 +59,7 @@ int SacrificeCost::doPay(){ void SacrificeCost::Render(){ //TODO : real stuff - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); mFont->SetScale(DEFAULT_MAIN_FONT_SCALE); char buffer[200]; sprintf(buffer, _("sacrifice").c_str()); diff --git a/projects/mtg/src/GameApp.cpp b/projects/mtg/src/GameApp.cpp index 9c1246b78..66ab5cc7c 100644 --- a/projects/mtg/src/GameApp.cpp +++ b/projects/mtg/src/GameApp.cpp @@ -18,7 +18,6 @@ #include "../include/Translate.h" const char * const GameState::menuTexts[]= {"--NEW--","Deck 1", "Deck 2", "Deck 3", "Deck 4", "Deck 5", "Deck 6"} ; -WResourceManager* GameApp::CommonRes = NEW WResourceManager(); hgeParticleSystem* GameApp::Particles[] = {NULL,NULL,NULL,NULL,NULL,NULL}; int GameApp::HasMusic = 1; JMusic * GameApp::music = NULL; @@ -67,7 +66,7 @@ void GameApp::Create() //Test for Music files presence string filepath = RESPATH; - filepath = filepath + "/" + CommonRes->musicFile("Track0.mp3"); + filepath = filepath + "/" + resources.musicFile("Track0.mp3"); std::ifstream file(filepath.c_str()); if (file) file.close(); @@ -75,76 +74,70 @@ void GameApp::Create() HasMusic = 0; filepath = RESPATH; - filepath = filepath + "/" + CommonRes->musicFile("Track1.mp3"); + filepath = filepath + "/" + resources.musicFile("Track1.mp3"); std::ifstream file2(filepath.c_str()); if (file2) file2.close(); else HasMusic = 0; - CommonRes->CreateTexture("menuicons.png"); + resources.RetrieveTexture("menuicons.png",RETRIEVE_MANAGE); //Creating thes quad in this specific order allows us to have them in the correct order to call them by integer id - CommonRes->CreateQuad("c_artifact", "menuicons.png", 2 + 6*36, 38, 32, 32); - CommonRes->CreateQuad("c_green", "menuicons.png", 2 + 0*36, 38, 32, 32); - CommonRes->CreateQuad("c_blue", "menuicons.png", 2 + 1*36, 38, 32, 32); - CommonRes->CreateQuad("c_red", "menuicons.png", 2 + 3*36, 38, 32, 32); - CommonRes->CreateQuad("c_black", "menuicons.png", 2 + 2*36, 38, 32, 32); - CommonRes->CreateQuad("c_white", "menuicons.png", 2 + 4*36, 38, 32, 32); - CommonRes->CreateQuad("c_land", "menuicons.png", 2 + 5*36, 38, 32, 32); - manaIcons[Constants::MTG_COLOR_ARTIFACT] = GameApp::CommonRes->GetQuad("c_artifact"); - manaIcons[Constants::MTG_COLOR_LAND] = GameApp::CommonRes->GetQuad("c_land"); - manaIcons[Constants::MTG_COLOR_WHITE] = GameApp::CommonRes->GetQuad("c_white"); - manaIcons[Constants::MTG_COLOR_RED] = GameApp::CommonRes->GetQuad("c_red"); - manaIcons[Constants::MTG_COLOR_BLACK] = GameApp::CommonRes->GetQuad("c_black"); - manaIcons[Constants::MTG_COLOR_BLUE] = GameApp::CommonRes->GetQuad("c_blue"); - manaIcons[Constants::MTG_COLOR_GREEN] = GameApp::CommonRes->GetQuad("c_green"); + manaIcons[Constants::MTG_COLOR_GREEN] = resources.RetrieveQuad("menuicons.png", 2 + 0*36, 38, 32, 32, "c_green",RETRIEVE_MANAGE); + manaIcons[Constants::MTG_COLOR_BLUE] = resources.RetrieveQuad("menuicons.png", 2 + 1*36, 38, 32, 32, "c_blue",RETRIEVE_MANAGE); + manaIcons[Constants::MTG_COLOR_RED] = resources.RetrieveQuad("menuicons.png", 2 + 3*36, 38, 32, 32, "c_red",RETRIEVE_MANAGE); + manaIcons[Constants::MTG_COLOR_BLACK] = resources.RetrieveQuad("menuicons.png", 2 + 2*36, 38, 32, 32, "c_black",RETRIEVE_MANAGE); + manaIcons[Constants::MTG_COLOR_WHITE] = resources.RetrieveQuad("menuicons.png", 2 + 4*36, 38, 32, 32, "c_white",RETRIEVE_MANAGE); + manaIcons[Constants::MTG_COLOR_LAND] = resources.RetrieveQuad("menuicons.png", 2 + 5*36, 38, 32, 32, "c_land",RETRIEVE_MANAGE); + manaIcons[Constants::MTG_COLOR_ARTIFACT] = resources.RetrieveQuad("menuicons.png", 2 + 6*36, 38, 32, 32, "c_artifact",RETRIEVE_MANAGE); + for (int i = sizeof(manaIcons)/sizeof(manaIcons[0]) - 1; i >= 0; --i) manaIcons[i]->SetHotSpot(16,16); - CommonRes->CreateTexture("back.jpg"); - CommonRes->CreateQuad("back", "back.jpg", 0, 0, 200, 285); - CommonRes->GetQuad("back")->SetHotSpot(100, 145); + resources.RetrieveTexture("back.jpg",RETRIEVE_MANAGE); + resources.RetrieveQuad("back.jpg", 0, 0, 200, 285, "back",RETRIEVE_MANAGE); + resources.GetQuad("back")->SetHotSpot(100, 145); - CommonRes->CreateTexture("back_thumb.jpg"); - CommonRes->CreateQuad("back_thumb", "back_thumb.jpg", 0, 0, MTG_MINIIMAGE_WIDTH, MTG_MINIIMAGE_HEIGHT); + resources.RetrieveTexture("back_thumb.jpg",RETRIEVE_MANAGE); + resources.RetrieveQuad("back_thumb.jpg", 0, 0, MTG_MINIIMAGE_WIDTH, MTG_MINIIMAGE_HEIGHT, "back_thumb",RETRIEVE_MANAGE); - CommonRes->CreateTexture("particles.png"); - CommonRes->CreateQuad("particles", "particles.png", 0, 0, 32, 32); - CommonRes->GetQuad("particles")->SetHotSpot(16,16); + resources.RetrieveTexture("particles.png",RETRIEVE_MANAGE); + resources.RetrieveQuad("particles.png", 0, 0, 32, 32, "particles",RETRIEVE_MANAGE); + resources.GetQuad("particles")->SetHotSpot(16,16); + resources.RetrieveQuad("particles.png", 64, 0, 32, 32, "stars",RETRIEVE_MANAGE); + resources.GetQuad("stars")->SetHotSpot(16,16); - CommonRes->CreateQuad("stars", "particles.png", 64, 0, 32, 32); - CommonRes->GetQuad("stars")->SetHotSpot(16,16); - - CommonRes->LoadJLBFont("simon",11); - CommonRes->GetJLBFont("simon")->SetTracking(-1); - CommonRes->LoadJLBFont("f3",16); - CommonRes->LoadJLBFont("magic",16); + resources.LoadJLBFont("simon",11); + resources.GetJLBFont("simon")->SetTracking(-1); + resources.LoadJLBFont("f3",16); + resources.LoadJLBFont("magic",16); - CommonRes->CreateTexture("phasebar.png"); - CommonRes->CreateTexture("wood.png"); - CommonRes->CreateTexture("gold.png"); - CommonRes->CreateTexture("goldglow.png"); - CommonRes->CreateTexture("backdrop.jpg"); - CommonRes->CreateTexture("handback.png"); + resources.RetrieveTexture("phasebar.png",RETRIEVE_MANAGE); + resources.RetrieveTexture("wood.png",RETRIEVE_MANAGE); + resources.RetrieveTexture("gold.png",RETRIEVE_MANAGE); + resources.RetrieveTexture("goldglow.png",RETRIEVE_MANAGE); + resources.RetrieveTexture("backdrop.jpg",RETRIEVE_MANAGE); + resources.RetrieveTexture("handback.png",RETRIEVE_MANAGE); + resources.RetrieveTexture("BattleIcon.png",RETRIEVE_MANAGE); + resources.RetrieveTexture("DefenderIcon.png",RETRIEVE_MANAGE); + resources.RetrieveTexture("shadow.png",RETRIEVE_MANAGE); - CommonRes->CreateTexture("BattleIcon.png"); - CommonRes->CreateTexture("DefenderIcon.png"); - CommonRes->CreateTexture("shadow.png"); - CommonRes->CreateQuad("BattleIcon", "BattleIcon.png", 0, 0, 25, 25); - CommonRes->CreateQuad("DefenderIcon", "DefenderIcon.png", 0, 0, 24, 23); - CommonRes->CreateQuad("shadow", "shadow.png", 0, 0, 1, 1); - CommonRes->GetQuad("BattleIcon")->SetHotSpot(12, 12); - CommonRes->GetQuad("DefenderIcon")->SetHotSpot(12, 12); - CommonRes->GetQuad("shadow")->SetHotSpot(0.5, 0.5); + resources.RetrieveQuad("BattleIcon.png", 0, 0, 25, 25,"BattleIcon",RETRIEVE_MANAGE); + resources.RetrieveQuad("DefenderIcon.png", 0, 0, 24, 23,"DefenderIcon",RETRIEVE_MANAGE); + resources.RetrieveQuad("shadow.png", 0, 0, 1, 1,"shadow",RETRIEVE_MANAGE); + + resources.GetQuad("BattleIcon")->SetHotSpot(12, 12); + resources.GetQuad("DefenderIcon")->SetHotSpot(12, 12); + resources.GetQuad("shadow")->SetHotSpot(0.5, 0.5); - collection = NEW MTGAllCards(&cache); + collection = NEW MTGAllCards(); - Particles[0] = NEW hgeParticleSystem("graphics/particle1.psi", CommonRes->GetQuad("particles")); - Particles[1] = NEW hgeParticleSystem("graphics/particle2.psi", CommonRes->GetQuad("particles")); - Particles[2] = NEW hgeParticleSystem("graphics/particle3.psi", CommonRes->GetQuad("particles")); - Particles[3] = NEW hgeParticleSystem("graphics/particle4.psi", CommonRes->GetQuad("particles")); - Particles[4] = NEW hgeParticleSystem("graphics/particle5.psi", CommonRes->GetQuad("particles")); - Particles[5] = NEW hgeParticleSystem("graphics/particle7.psi", CommonRes->GetQuad("particles")); + Particles[0] = NEW hgeParticleSystem("graphics/particle1.psi", resources.GetQuad("particles")); + Particles[1] = NEW hgeParticleSystem("graphics/particle2.psi", resources.GetQuad("particles")); + Particles[2] = NEW hgeParticleSystem("graphics/particle3.psi", resources.GetQuad("particles")); + Particles[3] = NEW hgeParticleSystem("graphics/particle4.psi", resources.GetQuad("particles")); + Particles[4] = NEW hgeParticleSystem("graphics/particle5.psi", resources.GetQuad("particles")); + Particles[5] = NEW hgeParticleSystem("graphics/particle7.psi", resources.GetQuad("particles")); mGameStates[GAME_STATE_DECK_VIEWER] = NEW GameStateDeckViewer(this); mGameStates[GAME_STATE_DECK_VIEWER]->Create(); @@ -197,12 +190,8 @@ void GameApp::Destroy() collection->destroyAllCards(); SAFE_DELETE(collection); } - SampleCache::DestroyInstance(); delete(DeckStats::GetInstance()); - SAFE_DELETE(CommonRes); - - SAFE_DELETE(Subtypes::subtypesList); SAFE_DELETE(MtgSets::SetsList); @@ -274,7 +263,7 @@ void GameApp::Render() { if (systemError.size()){ fprintf(stderr, systemError.c_str()); - JLBFont * mFont= CommonRes->GetJLBFont("simon"); + JLBFont * mFont= resources.GetJLBFont("simon"); if (mFont) mFont->DrawString(systemError.c_str(),1,1); return; } diff --git a/projects/mtg/src/GameObserver.cpp b/projects/mtg/src/GameObserver.cpp index b084d96f5..30cc36820 100644 --- a/projects/mtg/src/GameObserver.cpp +++ b/projects/mtg/src/GameObserver.cpp @@ -189,8 +189,8 @@ void GameObserver::startGame(int shuffle, int draw){ //Preload images from hand if (!players[0]->isAI()){ for (i=0; i< players[0]->game->hand->nb_cards; i++){ - cache.getThumb(players[0]->game->hand->cards[i]); - cache.getQuad(players[0]->game->hand->cards[i]); + resources.RetrieveCard(players[0]->game->hand->cards[i],CACHE_THUMB); + resources.RetrieveCard(players[0]->game->hand->cards[i]); } } turn = 0; diff --git a/projects/mtg/src/GameOptions.cpp b/projects/mtg/src/GameOptions.cpp index f08bbea29..840cb4499 100644 --- a/projects/mtg/src/GameOptions.cpp +++ b/projects/mtg/src/GameOptions.cpp @@ -300,7 +300,7 @@ void GameSettings::checkProfile(){ //Validation of collection, etc, only happens if the game is up. if(theGame == NULL || theGame->collection == NULL) return; - + if(profileFile(PLAYER_COLLECTION) == "") { //If we had any default settings, we'd set them here. @@ -335,7 +335,7 @@ void GameSettings::createUsersFirstDeck(int setId){ if(theGame == NULL || theGame->collection == NULL) return; - MTGDeck *mCollection = NEW MTGDeck(options.profileFile(PLAYER_COLLECTION,"",false).c_str(), &cache, theGame->collection); + MTGDeck *mCollection = NEW MTGDeck(options.profileFile(PLAYER_COLLECTION,"",false).c_str(), theGame->collection); //10 lands of each int sets[] = {setId}; if (!mCollection->addRandomCards(10, sets,1, Constants::RARITY_L,"Forest")){ diff --git a/projects/mtg/src/GameState.cpp b/projects/mtg/src/GameState.cpp index 03044d055..8ec0ad4c2 100644 --- a/projects/mtg/src/GameState.cpp +++ b/projects/mtg/src/GameState.cpp @@ -16,7 +16,7 @@ int GameState::fillDeckMenu(SimpleMenu * _menu, string path, string smallDeckPre char deckDesc[512]; sprintf(buffer, "%s/deck%i.txt",path.c_str(),nbDecks+1); if(fileExists(buffer)){ - MTGDeck * mtgd = NEW MTGDeck(buffer,NULL,NULL,1); + MTGDeck * mtgd = NEW MTGDeck(buffer,NULL,1); found = 1; nbDecks++; sprintf(smallDeckName, "%s_deck%i",smallDeckPrefix.c_str(),nbDecks); diff --git a/projects/mtg/src/GameStateDuel.cpp b/projects/mtg/src/GameStateDuel.cpp index 68f8d6c8b..eef3440df 100644 --- a/projects/mtg/src/GameStateDuel.cpp +++ b/projects/mtg/src/GameStateDuel.cpp @@ -75,7 +75,7 @@ void GameStateDuel::Start() mGamePhase = DUEL_STATE_CHOOSE_DECK1; credits = NEW Credits(); - mFont = GameApp::CommonRes->GetJLBFont(Constants::MENU_FONT); + mFont = resources.GetJLBFont(Constants::MENU_FONT); mFont->SetBase(0); opponentMenuFont = mFont; @@ -115,7 +115,7 @@ void GameStateDuel::loadPlayerRandom(int playerId, int isAI, int mode){ string lands[] = {"forest", "forest", "island", "mountain", "swamp", "plains", "forest"}; - MTGDeck * tempDeck = NEW MTGDeck(NULL, mParent->collection); + MTGDeck * tempDeck = NEW MTGDeck(mParent->collection); tempDeck->addRandomCards(9,0,0,-1,lands[color1].c_str()); tempDeck->addRandomCards(9,0,0,-1,lands[color2].c_str()); tempDeck->addRandomCards(1,0,0,'U',"land",colors,nbcolors); @@ -141,7 +141,7 @@ void GameStateDuel::loadPlayerRandom(int playerId, int isAI, int mode){ void GameStateDuel::loadPlayerMomir(int playerId, int isAI){ string deckFileSmall = "momir"; char empty[] = ""; - MTGDeck * tempDeck = NEW MTGDeck(options.profileFile("momir.txt").c_str(), NULL, mParent->collection); + MTGDeck * tempDeck = NEW MTGDeck(options.profileFile("momir.txt").c_str(), mParent->collection); deck[playerId] = NEW MTGPlayerCards(mParent->collection, tempDeck); if (!isAI) // Human Player mPlayers[playerId] = NEW HumanPlayer(deck[playerId], options.profileFile("momir.txt").c_str(), deckFileSmall); @@ -160,7 +160,7 @@ void GameStateDuel::loadPlayer(int playerId, int decknb, int isAI){ sprintf(deckFile, "%s/deck%i.txt",options.profileFile().c_str(), decknb); char deckFileSmall[255]; sprintf(deckFileSmall, "player_deck%i",decknb); - MTGDeck * tempDeck = NEW MTGDeck(deckFile, NULL, mParent->collection); + MTGDeck * tempDeck = NEW MTGDeck(deckFile, mParent->collection); deck[playerId] = NEW MTGPlayerCards(mParent->collection,tempDeck); delete tempDeck; mPlayers[playerId] = NEW HumanPlayer(deck[playerId],deckFile, deckFileSmall); diff --git a/projects/mtg/src/GameStateMenu.cpp b/projects/mtg/src/GameStateMenu.cpp index 4f54430fc..3554fdb35 100644 --- a/projects/mtg/src/GameStateMenu.cpp +++ b/projects/mtg/src/GameStateMenu.cpp @@ -64,60 +64,50 @@ GameStateMenu::GameStateMenu(GameApp* parent): GameState(parent) mGuiController = NULL; subMenuController = NULL; gameTypeMenu = NULL; - mIconsTexture = NULL; //bgMusic = NULL; timeIndex = 0; angleMultiplier = MIN_ANGLE_MULTIPLIER; yW = 55; mVolume = 0; - splashTex = NULL; - splashQuad = NULL; scroller = NULL; } GameStateMenu::~GameStateMenu() {} + void GameStateMenu::Create() { mDip = NULL; mReadConf = 0; mCurrentSetName[0] = 0; - mIconsTexture = GameApp::CommonRes->LoadTexture("menuicons.png", TEX_TYPE_USE_VRAM); - bgTexture = GameApp::CommonRes->LoadTexture("menutitle.png", TEX_TYPE_USE_VRAM); - movingWTexture = GameApp::CommonRes->LoadTexture("movingW.png", TEX_TYPE_USE_VRAM); - mBg = NEW JQuad(bgTexture, 0, 0, 256, 166); // Create background quad for rendering. - mMovingW = NEW JQuad(movingWTexture, 2, 2, 84, 62); - if (fileExists(GameApp::CommonRes->graphicsFile("splash.jpg").c_str())){ - splashTex = GameApp::CommonRes->LoadTexture("splash.jpg", TEX_TYPE_USE_VRAM); - splashQuad = NEW JQuad(splashTex, 0, 0, 480, 272); - } - mBg->SetHotSpot(105,50); - mMovingW->SetHotSpot(72,16); - //load all the icon images + //load all the icon images. Menu icons are managed, so we can do this here. int n = 0; + char buf[512]; + for (int i=0;i<5;i++){ for (int j=0;j<2;j++){ - mIcons[n] = NEW JQuad(mIconsTexture, 2 + i*36, 2 + j*36, 32, 32); + sprintf(buf,"menuicons%d%d",i,j); + mIcons[n] = resources.RetrieveQuad("menuicons.png", 2 + i*36, 2 + j*36, 32, 32,buf); mIcons[n]->SetHotSpot(16,16); n++; } } - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MENU_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MENU_FONT); mFont->SetColor(options[Metrics::LOADING_TC].asColor()); mGuiController = NEW JGuiController(100, this); if (mGuiController) { - mGuiController->Add(NEW MenuItem(MENUITEM_PLAY, mFont, "Play", 80, 50 + SCREEN_HEIGHT/2, mIcons[8], mIcons[9],"graphics/particle1.psi",GameApp::CommonRes->GetQuad("particles"), true)); - mGuiController->Add(NEW MenuItem(MENUITEM_DECKEDITOR, mFont, "Deck Editor", 160, 50 + SCREEN_HEIGHT/2, mIcons[2], mIcons[3],"graphics/particle2.psi",GameApp::CommonRes->GetQuad("particles"))); - mGuiController->Add(NEW MenuItem(MENUITEM_SHOP, mFont, "Shop", 240, 50 + SCREEN_HEIGHT/2, mIcons[0], mIcons[1],"graphics/particle3.psi",GameApp::CommonRes->GetQuad("particles"))); - mGuiController->Add(NEW MenuItem(MENUITEM_OPTIONS, mFont, "Options", 320, 50 + SCREEN_HEIGHT/2, mIcons[6], mIcons[7],"graphics/particle4.psi",GameApp::CommonRes->GetQuad("particles"))); - mGuiController->Add(NEW MenuItem(MENUITEM_EXIT, mFont, "Exit", 400, 50 + SCREEN_HEIGHT/2, mIcons[4], mIcons[5],"graphics/particle5.psi",GameApp::CommonRes->GetQuad("particles"))); + mGuiController->Add(NEW MenuItem(MENUITEM_PLAY, mFont, "Play", 80, 50 + SCREEN_HEIGHT/2, mIcons[8], mIcons[9],"graphics/particle1.psi",resources.GetQuad("particles"), true)); + mGuiController->Add(NEW MenuItem(MENUITEM_DECKEDITOR, mFont, "Deck Editor", 160, 50 + SCREEN_HEIGHT/2, mIcons[2], mIcons[3],"graphics/particle2.psi",resources.GetQuad("particles"))); + mGuiController->Add(NEW MenuItem(MENUITEM_SHOP, mFont, "Shop", 240, 50 + SCREEN_HEIGHT/2, mIcons[0], mIcons[1],"graphics/particle3.psi",resources.GetQuad("particles"))); + mGuiController->Add(NEW MenuItem(MENUITEM_OPTIONS, mFont, "Options", 320, 50 + SCREEN_HEIGHT/2, mIcons[6], mIcons[7],"graphics/particle4.psi",resources.GetQuad("particles"))); + mGuiController->Add(NEW MenuItem(MENUITEM_EXIT, mFont, "Exit", 400, 50 + SCREEN_HEIGHT/2, mIcons[4], mIcons[5],"graphics/particle5.psi",resources.GetQuad("particles"))); } currentState = MENU_STATE_MAJOR_LOADING_CARDS | MENU_STATE_MINOR_NONE; - scroller = NEW TextScroller(GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT), SCREEN_WIDTH/2 - 90 , SCREEN_HEIGHT-17,180); + scroller = NEW TextScroller(resources.GetJLBFont(Constants::MAIN_FONT), SCREEN_WIDTH/2 - 90 , SCREEN_HEIGHT-17,180); scrollerSet = 0; } @@ -128,29 +118,16 @@ void GameStateMenu::Destroy() SAFE_DELETE(mGuiController); SAFE_DELETE(subMenuController); SAFE_DELETE(gameTypeMenu); - SAFE_DELETE(mIconsTexture); - - for (int i = 0; i < 10 ; i++){ - SAFE_DELETE(mIcons[i]); - } - - SAFE_DELETE(mBg); - SAFE_DELETE(mMovingW); - SAFE_DELETE(movingWTexture); - SAFE_DELETE(bgTexture); + resources.Release(bgTexture); + resources.Release(movingWTexture); SAFE_DELETE(scroller); - } - - void GameStateMenu::Start(){ - JRenderer::GetInstance()->ResetPrivateVRAM(); - JRenderer::GetInstance()->EnableVSync(true); subMenuController = NULL; if (GameApp::HasMusic && !GameApp::music && options[Options::MUSICVOLUME].number > 0){ - GameApp::music = GameApp::CommonRes->ssLoadMusic("Track0.mp3"); + GameApp::music = resources.ssLoadMusic("Track0.mp3"); JSoundSystem::GetInstance()->PlayMusic(GameApp::music, true); } @@ -162,6 +139,16 @@ void GameStateMenu::Start(){ hasChosenGameType = 1; if (options[Options::MOMIR_MODE_UNLOCKED].number) hasChosenGameType = 0; if (options[Options::RANDOMDECK_MODE_UNLOCKED].number) hasChosenGameType = 0; + + bgTexture = resources.RetrieveTexture("menutitle.png", RETRIEVE_VRAM); + movingWTexture = resources.RetrieveTexture("movingW.png", RETRIEVE_VRAM); + mBg = resources.RetrieveQuad("menutitle.png"); // Create background quad for rendering. + mMovingW = resources.RetrieveQuad("movingW.png"); + + mBg->SetHotSpot(105,50); + mMovingW->SetHotSpot(72,16); + JRenderer::GetInstance()->ResetPrivateVRAM(); + JRenderer::GetInstance()->EnableVSync(true); } @@ -217,7 +204,7 @@ void GameStateMenu::fillScroller(){ sprintf(buff2, _("You have unlocked %i expansions out of %i").c_str(),nbunlocked, MtgSets::SetsList->nb_items); scroller->Add(buff2); - DeckDataWrapper* ddw = NEW DeckDataWrapper(NEW MTGDeck(options.profileFile(PLAYER_COLLECTION,"",false).c_str(), &cache,mParent->collection)); + DeckDataWrapper* ddw = NEW DeckDataWrapper(NEW MTGDeck(options.profileFile(PLAYER_COLLECTION,"",false).c_str(), mParent->collection)); int totalCards = ddw->getCount(); if (totalCards){ sprintf(buff2, _("You have a total of %i cards in your collection").c_str(),totalCards); @@ -274,8 +261,10 @@ int GameStateMenu::nextDirectory(const char * root, const char * file){ void GameStateMenu::End() { - JRenderer::GetInstance()->EnableVSync(false); + + resources.Release(bgTexture); + resources.Release(movingWTexture); } @@ -316,9 +305,7 @@ void GameStateMenu::Update(float dt) } } resetDirectory(); - SAFE_DELETE(splashQuad); - SAFE_DELETE(splashTex); - } + } break; case MENU_STATE_MAJOR_FIRST_TIME : options.checkProfile(); @@ -338,7 +325,7 @@ void GameStateMenu::Update(float dt) { if (!hasChosenGameType){ currentState = MENU_STATE_MAJOR_SUBMENU; - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MENU_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MENU_FONT); subMenuController = NEW SimpleMenu(102, this, mFont, 150,60); if (subMenuController){ subMenuController->Add(SUBMENUITEM_CLASSIC,"Classic"); @@ -402,8 +389,9 @@ void GameStateMenu::Render() { JRenderer * renderer = JRenderer::GetInstance(); renderer->ClearScreen(ARGB(0,0,0,0)); - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MENU_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MENU_FONT); if ((currentState & MENU_STATE_MAJOR) == MENU_STATE_MAJOR_LOADING_CARDS){ + JQuad* splashQuad = resources.RetrieveQuad("splash.jpg"); if (splashQuad){ renderer->RenderQuad(splashQuad,0,0); }else{ @@ -412,7 +400,7 @@ void GameStateMenu::Render() mFont->DrawString(text,SCREEN_WIDTH/2,SCREEN_HEIGHT/2,JGETEXT_CENTER); } }else{ - mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + mFont = resources.GetJLBFont(Constants::MAIN_FONT); PIXEL_TYPE colors[] = { ARGB(255, 3, 2, 0), @@ -447,7 +435,7 @@ void GameStateMenu::Render() void GameStateMenu::ButtonPressed(int controllerId, int controlId) { -JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MENU_FONT); +JLBFont * mFont = resources.GetJLBFont(Constants::MENU_FONT); #if defined (WIN32) || defined (LINUX) char buf[4096]; sprintf(buf, "cnotrollerId: %i", controllerId); @@ -558,13 +546,10 @@ ostream& GameStateMenu::toString(ostream& out) const << " ; gameTypeMenu : " << gameTypeMenu << " ; hasChosenGameType : " << hasChosenGameType << " ; mIcons : " << mIcons - << " ; mIconsTexture : " << mIconsTexture << " ; bgTexture : " << bgTexture << " ; movingWTexture : " << movingWTexture << " ; mBg : " << mBg << " ; mMovingW : " << mMovingW - << " ; splashTex : " << splashTex - << " ; splashQuad : " << splashQuad << " ; mCreditsYPos : " << mCreditsYPos << " ; currentState : " << currentState << " ; mVolume : " << mVolume diff --git a/projects/mtg/src/GameStateOptions.cpp b/projects/mtg/src/GameStateOptions.cpp index 7a6eb6259..878c887ab 100644 --- a/projects/mtg/src/GameStateOptions.cpp +++ b/projects/mtg/src/GameStateOptions.cpp @@ -54,7 +54,7 @@ void GameStateOptions::Start() optionsList->failMsg = ""; optionsTabs->Add(optionsList); - JLBFont * mFont = GameApp::CommonRes->GetJLBFont("f3"); + JLBFont * mFont = resources.GetJLBFont("f3"); optionsMenu = NEW SimpleMenu(102, this,mFont, 50,170); optionsMenu->Add(1, "Save & Back to Main Menu"); optionsMenu->Add(2, "Back to Main Menu"); @@ -135,7 +135,7 @@ void GameStateOptions::Render() "Please support this project with donations at http://wololo.net/wagic", }; - JLBFont * mFont = GameApp::CommonRes->GetJLBFont("magic"); + JLBFont * mFont = resources.GetJLBFont("magic"); mFont->SetColor(ARGB(255,200,200,200)); mFont->SetScale(1.0); float startpos = 272 - timer * 10; diff --git a/projects/mtg/src/GameStateShop.cpp b/projects/mtg/src/GameStateShop.cpp index 66f621514..200ad5b8d 100644 --- a/projects/mtg/src/GameStateShop.cpp +++ b/projects/mtg/src/GameStateShop.cpp @@ -26,19 +26,16 @@ void GameStateShop::Create(){ void GameStateShop::Start() { - - - menu = NULL; - menuFont = GameApp::CommonRes->GetJLBFont(Constants::MENU_FONT); - itemFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + menuFont = resources.GetJLBFont(Constants::MENU_FONT); + itemFont = resources.GetJLBFont(Constants::MAIN_FONT); mStage = STAGE_SHOP_SHOP; - bgTexture = GameApp::CommonRes->LoadTexture("shop.jpg", TEX_TYPE_USE_VRAM); - mBg = NEW JQuad(bgTexture, 0, 0, 480, 272); // Create background quad for rendering. - mBack = GameApp::CommonRes->GetQuad("back"); + bgTexture = resources.RetrieveTexture("shop.jpg", RETRIEVE_VRAM); + mBg = resources.RetrieveQuad("shop.jpg"); + mBack = resources.GetQuad("back"); JRenderer::GetInstance()->ResetPrivateVRAM(); JRenderer::GetInstance()->EnableVSync(true); @@ -99,7 +96,7 @@ void GameStateShop::load(){ setIds[i] = (rand() % MtgSets::SetsList->nb_items); } } - JQuad * mBackThumb = GameApp::CommonRes->GetQuad("back_thumb"); + JQuad * mBackThumb = resources.GetQuad("back_thumb"); @@ -109,7 +106,7 @@ void GameStateShop::load(){ shop->Add(setNames[i],mBack,mBackThumb, 700); } - MTGDeck * tempDeck = NEW MTGDeck(NULL,mParent->collection); + MTGDeck * tempDeck = NEW MTGDeck(mParent->collection); tempDeck->addRandomCards(8,sets,nbsets); for (map::iterator it = tempDeck->cards.begin(); it!=tempDeck->cards.end(); it++){ for (int j = 0; j < it->second; j++){ @@ -122,11 +119,9 @@ void GameStateShop::load(){ void GameStateShop::End() { JRenderer::GetInstance()->EnableVSync(false); + resources.Release(bgTexture); SAFE_DELETE(shop); - SAFE_DELETE(bgTexture); - SAFE_DELETE(mBg); SAFE_DELETE(menu); - } void GameStateShop::Destroy(){ diff --git a/projects/mtg/src/GuiBackground.cpp b/projects/mtg/src/GuiBackground.cpp index 784537540..1eedb9561 100644 --- a/projects/mtg/src/GuiBackground.cpp +++ b/projects/mtg/src/GuiBackground.cpp @@ -4,7 +4,7 @@ GuiBackground::GuiBackground() { - JTexture* texture = GameApp::CommonRes->GetTexture("backdrop.jpg"); + JTexture* texture = resources.GetTexture("backdrop.jpg"); if (texture) quad = NEW JQuad(texture, 0, 0, 480, 255); else diff --git a/projects/mtg/src/GuiCombat.cpp b/projects/mtg/src/GuiCombat.cpp index 9f8205b98..9f4d4a6c8 100644 --- a/projects/mtg/src/GuiCombat.cpp +++ b/projects/mtg/src/GuiCombat.cpp @@ -21,12 +21,7 @@ GuiCombat::GuiCombat(GameObserver* go) : GuiLayer(), go(go), active(false), acti { if (NULL == ok_quad) { - if (!GameApp::CommonRes->GetTexture("Ok.png")) - { - GameApp::CommonRes->CreateTexture("Ok.png"); - GameApp::CommonRes->CreateQuad("OK", "Ok.png", 0, 0, 56, 45); - } - ok_quad = GameApp::CommonRes->GetQuad("OK"); + ok_quad = resources.RetrieveQuad("OK.png"); if (ok_quad) ok_quad->SetHotSpot(28, 22); } } @@ -226,7 +221,7 @@ void GuiCombat::Render() { go->opponent()->mAvatar->SetHotSpot(18, 25); enemy_avatar.Render(go->opponent()->mAvatar); - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); mFont->SetColor(ARGB(255, 255, 64, 0)); { char buf[10]; sprintf(buf, "%i", damage); @@ -238,7 +233,7 @@ void GuiCombat::Render() renderer->DrawLine(0, SCREEN_HEIGHT / 2 + 10, SCREEN_WIDTH, SCREEN_HEIGHT / 2 + 10, ARGB(255, 255, 64, 0)); if (FIRST_STRIKE == step) { - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); mFont->SetColor(ARGB(255, 64, 255, 64)); mFont->DrawString("First strike damage", 370, 2); } @@ -338,6 +333,7 @@ int GuiCombat::receiveEventMinus(WEvent* e) } else if (WEventPhaseChange* event = dynamic_cast(e)) { + event = event; step = BLOCKERS; } else if (WEventCombatStepChange* event = dynamic_cast(e)) diff --git a/projects/mtg/src/GuiFrame.cpp b/projects/mtg/src/GuiFrame.cpp index c1b916131..06e3eb88d 100644 --- a/projects/mtg/src/GuiFrame.cpp +++ b/projects/mtg/src/GuiFrame.cpp @@ -4,26 +4,26 @@ GuiFrame::GuiFrame() { - if (JTexture* woodTex = GameApp::CommonRes->GetTexture("wood.png")) - wood = NEW JQuad(woodTex, 0, 0, SCREEN_WIDTH, 16); + if (resources.GetTexture("wood.png")) + wood = resources.RetrieveQuad("wood.png", 0, 0, SCREEN_WIDTH, 16); else { wood = NULL; GameApp::systemError += "Can't load wood texture : " __FILE__ "\n"; } - if (JTexture* goldTex = GameApp::CommonRes->GetTexture("gold.png")) + if (resources.GetTexture("gold.png")) { - gold1 = NEW JQuad(goldTex, 0, 0, SCREEN_WIDTH, 6); - gold2 = NEW JQuad(goldTex, 0, 6, SCREEN_WIDTH, 6); + gold1 = resources.RetrieveQuad("gold.png", 0, 0, SCREEN_WIDTH, 6, "gold1"); + gold2 = resources.RetrieveQuad("gold.png", 0, 6, SCREEN_WIDTH, 6, "gold2"); } else { gold1 = gold2 = NULL; GameApp::systemError += "Can't load gold texture : " __FILE__ "\n"; } - if (JTexture* goldGlowTex = GameApp::CommonRes->GetTexture("goldglow.png")) - goldGlow = NEW JQuad(goldGlowTex, 0, 1, SCREEN_WIDTH, 18); + if (resources.GetTexture("goldglow.png")) + goldGlow = resources.RetrieveQuad("goldglow.png", 0, 1, SCREEN_WIDTH, 18); else { goldGlow = NULL; @@ -38,10 +38,10 @@ GuiFrame::GuiFrame() GuiFrame::~GuiFrame() { - delete(gold2); - delete(gold1); - delete(wood); - SAFE_DELETE(goldGlow); + resources.Release(gold2); + resources.Release(gold1); + resources.Release(wood); + resources.Release(goldGlow); } void GuiFrame::Render() diff --git a/projects/mtg/src/GuiHand.cpp b/projects/mtg/src/GuiHand.cpp index 8c8263251..3c4ef1c47 100644 --- a/projects/mtg/src/GuiHand.cpp +++ b/projects/mtg/src/GuiHand.cpp @@ -24,7 +24,7 @@ HandLimitor::HandLimitor(GuiHand* hand) : hand(hand) {} GuiHand::GuiHand(CardSelector* cs, MTGHand* hand) : GuiLayer(), hand(hand), cs(cs) { - JTexture* texture = GameApp::CommonRes->GetTexture("handback.png"); + JTexture* texture = resources.GetTexture("handback.png"); if (texture) { back = NEW JQuad(texture, 0, 0, 101, 250); @@ -54,7 +54,7 @@ GuiHandOpponent::GuiHandOpponent(CardSelector* cs, MTGHand* hand) : GuiHand(cs, void GuiHandOpponent::Render() { - JQuad * quad = GameApp::CommonRes->GetQuad("back_thumb"); + JQuad * quad = resources.GetQuad("back_thumb"); float x = 45; for (vector::iterator it = cards.begin(); it != cards.end(); ++it) diff --git a/projects/mtg/src/GuiMana.cpp b/projects/mtg/src/GuiMana.cpp index befe38121..a396f6928 100644 --- a/projects/mtg/src/GuiMana.cpp +++ b/projects/mtg/src/GuiMana.cpp @@ -13,22 +13,22 @@ ManaIcon::ManaIcon(int color, float x, float y) : Pos(x, y, 0.5, 0.0, 255), f(-1 switch (color) { case Constants::MTG_COLOR_RED : - particleSys = NEW hgeParticleSystem("graphics/manared.psi", GameApp::CommonRes->GetQuad("stars")); + particleSys = NEW hgeParticleSystem("graphics/manared.psi", resources.GetQuad("stars")); break; case Constants::MTG_COLOR_BLUE : - particleSys = NEW hgeParticleSystem("graphics/manablue.psi", GameApp::CommonRes->GetQuad("stars")); + particleSys = NEW hgeParticleSystem("graphics/manablue.psi", resources.GetQuad("stars")); break; case Constants::MTG_COLOR_GREEN : - particleSys = NEW hgeParticleSystem("graphics/managreen.psi", GameApp::CommonRes->GetQuad("stars")); + particleSys = NEW hgeParticleSystem("graphics/managreen.psi", resources.GetQuad("stars")); break; case Constants::MTG_COLOR_BLACK : - particleSys = NEW hgeParticleSystem("graphics/manablack.psi", GameApp::CommonRes->GetQuad("stars")); + particleSys = NEW hgeParticleSystem("graphics/manablack.psi", resources.GetQuad("stars")); break; case Constants::MTG_COLOR_WHITE : - particleSys = NEW hgeParticleSystem("graphics/manawhite.psi", GameApp::CommonRes->GetQuad("stars")); + particleSys = NEW hgeParticleSystem("graphics/manawhite.psi", resources.GetQuad("stars")); break; default : - particleSys = NEW hgeParticleSystem("graphics/mana.psi", GameApp::CommonRes->GetQuad("stars")); + particleSys = NEW hgeParticleSystem("graphics/mana.psi", resources.GetQuad("stars")); } icon = manaIcons[color]; diff --git a/projects/mtg/src/GuiPhaseBar.cpp b/projects/mtg/src/GuiPhaseBar.cpp index e621d33e1..48dcaa412 100644 --- a/projects/mtg/src/GuiPhaseBar.cpp +++ b/projects/mtg/src/GuiPhaseBar.cpp @@ -22,7 +22,7 @@ static int colors[] = GuiPhaseBar::GuiPhaseBar() : phase(GameObserver::GetInstance()->phaseRing->getCurrentPhase()), angle(0.0f) { - JTexture* texture = GameApp::CommonRes->GetTexture("phasebar.png"); + JTexture* texture = resources.GetTexture("phasebar.png"); if (texture) quad = NEW JQuad(texture, 0, 0, Width, Height); else diff --git a/projects/mtg/src/GuiPlay.cpp b/projects/mtg/src/GuiPlay.cpp index 9a73a7376..8a839066b 100644 --- a/projects/mtg/src/GuiPlay.cpp +++ b/projects/mtg/src/GuiPlay.cpp @@ -70,7 +70,7 @@ void GuiPlay::BattleField::EnstackAttacker(CardView* card) GameObserver* game = GameObserver::GetInstance(); card->x = currentAttacker * (HORZWIDTH-20) / (attackers + 1); card->y = baseY + (game->players[0] == card->card->controller() ? 20 + y : -20 - y); ++currentAttacker; - // JRenderer::GetInstance()->RenderQuad(GameApp::CommonRes->GetQuad("BattleIcon"), card->actX, card->actY, 0, 0.5 + 0.1 * sinf(JGE::GetInstance()->GetTime()), 0.5 + 0.1 * sinf(JGE::GetInstance()->GetTime())); + // JRenderer::GetInstance()->RenderQuad(resources.GetQuad("BattleIcon"), card->actX, card->actY, 0, 0.5 + 0.1 * sinf(JGE::GetInstance()->GetTime()), 0.5 + 0.1 * sinf(JGE::GetInstance()->GetTime())); } void GuiPlay::BattleField::EnstackBlocker(CardView* card) { diff --git a/projects/mtg/src/GuiStatic.cpp b/projects/mtg/src/GuiStatic.cpp index 3ac5d2e3c..76b3282bb 100644 --- a/projects/mtg/src/GuiStatic.cpp +++ b/projects/mtg/src/GuiStatic.cpp @@ -21,7 +21,7 @@ void GuiAvatar::Render() GameObserver * game = GameObserver::GetInstance(); JRenderer * r = JRenderer::GetInstance(); int life = player->life; - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); mFont->SetScale(DEFAULT_MAIN_FONT_SCALE); //Avatar int lifeDiff = life - currentLife; @@ -97,14 +97,14 @@ void GuiGameZone::toggleDisplay(){ void GuiGameZone::Render(){ //Texture - JQuad * quad = GameApp::CommonRes->GetQuad("back_thumb"); + JQuad * quad = resources.GetQuad("back_thumb"); float scale = defaultHeight / quad->mHeight; quad->SetColor(ARGB((int)(actA/2),255,255,255)); JRenderer::GetInstance()->RenderQuad(quad, actX, actY, 0.0, scale, scale); //Number of cards - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MAIN_FONT); mFont->SetScale(DEFAULT_MAIN_FONT_SCALE); char buffer[11]; sprintf(buffer,"%i", zone->nb_cards); diff --git a/projects/mtg/src/MTGAbility.cpp b/projects/mtg/src/MTGAbility.cpp index 3d4bf1a4f..4a172cc27 100644 --- a/projects/mtg/src/MTGAbility.cpp +++ b/projects/mtg/src/MTGAbility.cpp @@ -2344,7 +2344,7 @@ AManaProducer::AManaProducer(int id, MTGCardInstance * card, ManaCost * _output, if (tap) source->tap(); if (options[Options::SFXVOLUME].number > 0){ - JSample * sample = SampleCache::GetInstance()->getSample("mana.wav"); + JSample * sample = resources.RetrieveSample("mana.wav"); if (sample) JSoundSystem::GetInstance()->PlaySample(sample); } return resolve(); diff --git a/projects/mtg/src/MTGCardInstance.cpp b/projects/mtg/src/MTGCardInstance.cpp index df24ea13f..303606486 100644 --- a/projects/mtg/src/MTGCardInstance.cpp +++ b/projects/mtg/src/MTGCardInstance.cpp @@ -593,7 +593,7 @@ JSample * MTGCardInstance::getSample(){ #ifdef WIN32 OutputDebugString(type.c_str()); #endif - if (fileExists(GameApp::CommonRes->sfxFile(type).c_str())){ + if (fileExists(resources.sfxFile(type).c_str())){ sample = string(type); break; } @@ -605,7 +605,7 @@ JSample * MTGCardInstance::getSample(){ if (!basicAbilities[i]) continue; string type = Constants::MTGBasicAbilities[i]; type = type + ".wav"; - if (fileExists(GameApp::CommonRes->sfxFile(type).c_str())){ + if (fileExists(resources.sfxFile(type).c_str())){ sample = type; break; } @@ -614,12 +614,12 @@ JSample * MTGCardInstance::getSample(){ if (!sample.size()){ string type = Subtypes::subtypesList->find(types[0]); type = type + ".wav"; - if (fileExists(GameApp::CommonRes->sfxFile(type).c_str())){ + if (fileExists(resources.sfxFile(type).c_str())){ sample = type; } } - if (sample.size()) return SampleCache::GetInstance()->getSample(sample); + if (sample.size()) return resources.RetrieveSample(sample); return NULL; } diff --git a/projects/mtg/src/MTGDeck.cpp b/projects/mtg/src/MTGDeck.cpp index 98b4e66d0..00ddb2a62 100644 --- a/projects/mtg/src/MTGDeck.cpp +++ b/projects/mtg/src/MTGDeck.cpp @@ -157,7 +157,6 @@ void MTGAllCards::initCounters(){ void MTGAllCards::init(){ tempCard = NULL; - mCache = NULL; total_cards = 0; initCounters(); srand(time(0)); // initialize random @@ -197,17 +196,7 @@ void MTGAllCards::destroyAllCards(){ } MTGAllCards::MTGAllCards(const char * config_file, const char * set_name){ - MTGAllCards(config_file, set_name, NULL); -} - -MTGAllCards::MTGAllCards(TexturesCache * cache){ init(); - mCache = cache; -} - -MTGAllCards::MTGAllCards(const char * config_file, const char * set_name, TexturesCache * cache){ - init(); - mCache = cache; load(config_file,set_name, 0); } @@ -350,16 +339,14 @@ MTGCard * MTGAllCards::getCardByName(string name){ -MTGDeck::MTGDeck(TexturesCache * cache, MTGAllCards * _allcards){ - mCache = cache; +MTGDeck::MTGDeck(MTGAllCards * _allcards){ total_cards = 0; database = _allcards; filename =""; meta_name = ""; } -MTGDeck::MTGDeck(const char * config_file, TexturesCache * cache, MTGAllCards * _allcards, int meta_only){ - mCache = cache; +MTGDeck::MTGDeck(const char * config_file, MTGAllCards * _allcards, int meta_only){ total_cards = 0; database = _allcards; filename = config_file; diff --git a/projects/mtg/src/MTGGamePhase.cpp b/projects/mtg/src/MTGGamePhase.cpp index 702d17422..dbc62f1d6 100644 --- a/projects/mtg/src/MTGGamePhase.cpp +++ b/projects/mtg/src/MTGGamePhase.cpp @@ -5,7 +5,7 @@ MTGGamePhase::MTGGamePhase(int id):ActionElement(id){ animation = 0; currentState = -1; - mFont= GameApp::CommonRes->GetJLBFont("simon"); + mFont= resources.GetJLBFont("simon"); mFont->SetBase(0); // using 2nd font } diff --git a/projects/mtg/src/MTGGameZones.cpp b/projects/mtg/src/MTGGameZones.cpp index 64eeac66a..ce6672739 100644 --- a/projects/mtg/src/MTGGameZones.cpp +++ b/projects/mtg/src/MTGGameZones.cpp @@ -150,7 +150,7 @@ MTGCardInstance * MTGPlayerCards::putInZone(MTGCardInstance * card, MTGGameZone if (options[Options::SFXVOLUME].number > 0){ if (to == g->players[0]->game->graveyard || to == g->players[1]->game->graveyard){ if (card->isCreature()){ - JSample * sample = SampleCache::GetInstance()->getSample("graveyard.wav"); + JSample * sample = resources.RetrieveSample("graveyard.wav"); if (sample) JSoundSystem::GetInstance()->PlaySample(sample); } } diff --git a/projects/mtg/src/MTGRules.cpp b/projects/mtg/src/MTGRules.cpp index 3f0f12357..b8dbf2532 100644 --- a/projects/mtg/src/MTGRules.cpp +++ b/projects/mtg/src/MTGRules.cpp @@ -299,7 +299,7 @@ void MTGMomirRule::Update(float dt){ void MTGMomirRule::Render(){ if (!textAlpha) return; - JLBFont * mFont = GameApp::CommonRes->GetJLBFont(Constants::MENU_FONT); + JLBFont * mFont = resources.GetJLBFont(Constants::MENU_FONT); mFont->SetScale(2 - (float)textAlpha/130); mFont->SetColor(ARGB(textAlpha,255,255,255)); mFont->DrawString(text.c_str(),SCREEN_WIDTH/2,SCREEN_HEIGHT/2,JGETEXT_CENTER); @@ -395,7 +395,7 @@ void HUDDisplay::Render(){ HUDDisplay::HUDDisplay(int _id):MTGAbility(_id, NULL){ timestamp = 0; popdelay = 2; - f = GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT); + f = resources.GetJLBFont(Constants::MAIN_FONT); maxWidth = 0; } diff --git a/projects/mtg/src/ManaCost.cpp b/projects/mtg/src/ManaCost.cpp index 865b38067..c197efceb 100644 --- a/projects/mtg/src/ManaCost.cpp +++ b/projects/mtg/src/ManaCost.cpp @@ -1,453 +1,453 @@ -#include "../include/config.h" -#include "../include/ManaCost.h" -#include "../include/ManaCostHybrid.h" -#include "../include/ExtraCost.h" -#include "../include/TargetChooser.h" -#include "../include/Targetable.h" -#include "../include/Player.h" -#include "../include/WEvent.h" - -#if defined (WIN32) - -#include -#endif - -ManaCost * ManaCost::parseManaCost(string s, ManaCost * _manaCost, MTGCardInstance * c){ - ManaCost * manaCost; - if (_manaCost){ - manaCost = _manaCost; - }else{ - manaCost = NEW ManaCost(); - } - int state = 0; - unsigned int start = 0; - unsigned int end = 0; - while (!s.empty() && state != -1){ - switch(state){ - case 0: - start = s.find_first_of("{"); - if (start == string::npos){ - return manaCost; - }else{ - state = 1; - } - break; - case 1: - end = s.find_first_of("}"); - if (end == string::npos){ - state = -1; - }else{ - string value = s.substr(start+1, end - 1 - start); - if (value == "u"){ - manaCost->add(Constants::MTG_COLOR_BLUE, 1); - }else if (value == "b"){ - manaCost->add(Constants::MTG_COLOR_BLACK, 1); - }else if (value == "w"){ - manaCost->add(Constants::MTG_COLOR_WHITE, 1); - }else if (value == "g"){ - manaCost->add(Constants::MTG_COLOR_GREEN, 1); - }else if (value == "r"){ - manaCost->add(Constants::MTG_COLOR_RED, 1); - }else if (value == "x"){ - manaCost->x(); - }else if (value == "t"){ - //Tap is handled outside of Manacost - }else if (value[0] == 's'){ - //sacrifice - OutputDebugString("Sacrifice\n"); - TargetChooserFactory tcf; - TargetChooser * tc = NULL; - size_t target_start = value.find("("); - size_t target_end = value.find(")"); - if (target_start!=string::npos && target_end!=string::npos){ - string target = value.substr(target_start+1, target_end-1 - target_start); - tc = tcf.createTargetChooser(target,c); - } - manaCost->addExtraCost(NEW SacrificeCost(tc)); - }else{ - int intvalue = atoi(value.c_str()); - int colors[2]; - int values[2]; - if (intvalue < 10 && value.size() > 1){ - for (int i = 0; i < 2; i++){ - char c = value[i]; - if (c >='0' && c <='9'){ - colors[i] = Constants::MTG_COLOR_ARTIFACT; - values[i] = c - '0'; - }else{ - for (int j = 0; j < Constants::MTG_NB_COLORS; j++){ - if (c == Constants::MTGColorChars[j]){ - colors[i] = j; - values[i] = 1; - } - } - } - } - manaCost->addHybrid(colors[0], values[0], colors[1], values[1]); - }else{ - manaCost->add(Constants::MTG_COLOR_ARTIFACT, intvalue); - } - } - s = s.substr(end + 1); - state = 0; - } - break; - default: - break; - } - } - - return manaCost; -} - -ManaCost::ManaCost(){ - init(); -} -ManaCost::ManaCost(int _cost[], int nb_elems){ - init(); - int i; - int total = nb_elems; - for (i = 0; i < total; i++){ - cost[_cost[i*2]] = _cost[i*2 + 1]; - } - -} - -ManaCost::ManaCost(ManaCost * _manaCost){ - init(); - int i; - for (i=0; i<= Constants::MTG_NB_COLORS; i++){ - cost[i] = _manaCost->getCost(i); - } -} - -ManaCost::~ManaCost(){ - for (unsigned int i = 0; i < nbhybrids ; i++){ - SAFE_DELETE(hybrids[i]); - } - if (!extraCostsIsCopy) { - SAFE_DELETE(extraCosts); - } -} - -void ManaCost::x(){ - cost[Constants::MTG_NB_COLORS] = 1; -} - -void ManaCost::init(){ - int i; - for (i=0; i<= Constants::MTG_NB_COLORS; i++){ - cost[i] = 0; - } - nbhybrids = 0; - extraCosts = NULL; - extraCostsIsCopy = 0; -} - - -void ManaCost::copy(ManaCost * _manaCost){ - for (unsigned int i = 0; i <= Constants::MTG_NB_COLORS; i++){ - cost[i] = _manaCost->getCost(i); - } - for (unsigned int i = 0; i < _manaCost->nbhybrids; i++){ - hybrids[i] = NEW ManaCostHybrid((*_manaCost->hybrids[i])); - } - nbhybrids = _manaCost->nbhybrids; - - if (_manaCost->extraCosts){ - //TODO Deep copy ? - if(!extraCostsIsCopy) SAFE_DELETE(extraCosts); - extraCosts = _manaCost->extraCosts; - extraCostsIsCopy = 1; - } -} - -int ManaCost::getCost(int color){ - return cost[color]; -} - -ManaCostHybrid * ManaCost::getHybridCost(unsigned int i){ - if (nbhybrids <= i) return NULL; - return hybrids[i]; -} - -int ManaCost::getMainColor(){ - for (int i=0; i< Constants::MTG_NB_COLORS; i++){ - if (cost[i]) return i; - } - return 0; -} - -int ManaCost::hasColor(int color){ - if (cost[color]) return 1; - for (unsigned int i = 0; i < nbhybrids; i++){ - if (hybrids[i]->hasColor(color)) return 1; - } - return 0; -} - -int ManaCost::isNull(){ - if (getConvertedCost()) return 0; - if (extraCosts) return 0; - return 1; -} - -int ManaCost::getConvertedCost(){ - int result = 0; - for (unsigned int i = 0; i < Constants::MTG_NB_COLORS; i++){ - result += cost[i]; - } - for (unsigned int i = 0; i < nbhybrids; i++){ - result+= hybrids[i]->getConvertedCost(); - } - return result; -} - -int ManaCost::remove(int color, int value){ - cost[color] -= value; - return 1; -} - -int ManaCost::add(int color, int value){ - cost[color] += value; - return 1; -} - -int ManaCost::add(ManaCost * _cost){ - if(!_cost) return 0; - for (unsigned int i = 0; i < Constants::MTG_NB_COLORS; i++){ - cost[i]+= _cost->getCost(i); - } - for (unsigned int i = 0; i < _cost->nbhybrids; i++){ - hybrids[nbhybrids] = NEW ManaCostHybrid((*_cost->hybrids[i])); - nbhybrids++; - } - return 1; -} - -string ManaCost::toString(){ - return "ManaCost - Todo"; -} - - -int ManaCost::addHybrid(int c1, int v1, int c2, int v2){ - ManaCostHybrid * h = NEW ManaCostHybrid(c1,v1,c2,v2); - hybrids[nbhybrids] = h; - nbhybrids++; - return nbhybrids; -} - -int ManaCost::addExtraCost(ExtraCost * _cost){ - if (!extraCosts) extraCosts = NEW ExtraCosts(); - extraCosts->costs.push_back(_cost); - OutputDebugString("Adding Sacrifice\n"); - return 1; -} - - -int ManaCost::isExtraPaymentSet(){ - if (!extraCosts) return 1; - OutputDebugString("Checking costs\n"); - return extraCosts->isPaymentSet(); -} - -int ManaCost::resetExtraPayment(){ - if (!extraCosts) return 1; - return extraCosts->reset(); -} - -int ManaCost::doPayExtra(){ - if (!extraCosts) return 0; - return extraCosts->doPay(); //TODO reset ? -} - -int ManaCost::setExtraCostsAction(MTGAbility * action, MTGCardInstance * card){ - if (extraCosts) extraCosts->setAction(action, card); - return 1; -} - -int ManaCost::pay(ManaCost * _cost){ - ManaCost * diff = Diff(_cost); - for (int i=0; i < Constants::MTG_NB_COLORS; i++){ - cost[i] = diff->getCost(i); - } - delete diff; - return 1; - //TODO return 0 if can't afford the cost! -} - -//return 1 if _cost can be paid with current data, 0 otherwise -int ManaCost::canAfford(ManaCost * _cost){ - ManaCost * diff = Diff(_cost); - int positive = diff->isPositive(); - delete diff; - if (positive){ - return 1; - } - return 0; -} - -int ManaCost::isPositive(){ - for (int i=0; i < Constants::MTG_NB_COLORS; i++){ - - if (cost[i] < 0){ - return 0; - } - } - return 1; - -} - - -void ManaCost::randomDiffHybrids(ManaCost * _cost, int diff[]){ - int _nbhybrids = _cost->nbhybrids; - for (int i = 0; i < _nbhybrids; i++){ - ManaCostHybrid * h = _cost->hybrids[i]; - diff[h->color1 * 2 +1]-= h->value1; - } -} - -int ManaCost::tryToPayHybrids(ManaCostHybrid * _hybrids[], int _nbhybrids, int diff[]){ - if (!_nbhybrids) return 1; - int result = 0; - ManaCostHybrid * h = _hybrids[_nbhybrids -1]; - if (diff[h->color1 * 2 +1] >= h->value1){ - diff[h->color1 * 2 +1]-= h->value1; - result = tryToPayHybrids(_hybrids,_nbhybrids -1, diff); - if (result) return 1; - diff[h->color1 * 2 +1]+= h->value1; - } - if (diff[h->color2 * 2 +1] >= h->value2){ - diff[h->color2 * 2 +1]-= h->value2; - result = tryToPayHybrids(_hybrids,_nbhybrids -1, diff); - if (result) return 1; - diff[h->color2 * 2 +1]+= h->value2; - } - return 0; -} - -//compute the difference between two mana costs -ManaCost * ManaCost::Diff(ManaCost * _cost){ - int diff[(Constants::MTG_NB_COLORS + 1 )* 2]; - diff[Constants::MTG_NB_COLORS * 2] = Constants::MTG_NB_COLORS; - for (int i=0; i < Constants::MTG_NB_COLORS; i++){ - diff[i*2] = i; - diff[i*2 +1] = cost[i] - _cost->getCost(i); - } - int hybridResult = tryToPayHybrids(_cost->hybrids, _cost->nbhybrids, diff); - if (!hybridResult) randomDiffHybrids(_cost,diff); - - //Colorless mana, special case - int colorless_idx = Constants::MTG_COLOR_ARTIFACT * 2 + 1; - if (diff[colorless_idx] < 0){ - for (int i=0; i < Constants::MTG_NB_COLORS; i++){ - if (diff[i*2 + 1] > 0){ - if (diff[i*2 + 1] + diff[colorless_idx] > 0){ - diff[i*2 + 1] += diff[colorless_idx]; - diff[colorless_idx] = 0; - break; - }else{ - diff[colorless_idx] += diff[i*2 + 1]; - diff[i*2 + 1] = 0; - } - } - } - } - - //Cost X - if (_cost->getCost(Constants::MTG_NB_COLORS)){ - diff[Constants::MTG_NB_COLORS * 2 + 1] = 0; - for (int i=0; i < Constants::MTG_NB_COLORS; i++){ - if (diff[i*2 + 1] > 0){ - diff[Constants::MTG_NB_COLORS * 2 + 1] += diff[i*2 + 1]; - diff[i*2 + 1] = 0; - } - } - } - - ManaCost * result = NEW ManaCost(diff, Constants::MTG_NB_COLORS +1); - return result; - -} - -#ifdef WIN32 -void ManaCost::Dump(){ - char buf[4096]; - OutputDebugString("\n===ManaCost===\n"); - for (int i=0; i<= Constants::MTG_NB_COLORS; i++){ - if (cost[i]) { - sprintf(buf, "%c:%i - ", Constants::MTGColorChars[i],cost[i]); - OutputDebugString(buf); - } - } - - for (unsigned int i=0; i< nbhybrids; i++){ - ManaCostHybrid * h = hybrids[i]; - - sprintf(buf, "H:{%c:%i}/{%c:%i}", Constants::MTGColorChars[h->color1], h->value1, Constants::MTGColorChars[h->color2], h->value2); - OutputDebugString(buf); - } - OutputDebugString("\n=============\n"); -} - -#endif - -ostream& operator<<(ostream& out, const ManaCost& m) -{ - return out << "(manacost)"; -} - - -void ManaPool::init(){ - ManaCost::init(); +#include "../include/config.h" +#include "../include/ManaCost.h" +#include "../include/ManaCostHybrid.h" +#include "../include/ExtraCost.h" +#include "../include/TargetChooser.h" +#include "../include/Targetable.h" +#include "../include/Player.h" +#include "../include/WEvent.h" + +#if defined (WIN32) + +#include +#endif + +ManaCost * ManaCost::parseManaCost(string s, ManaCost * _manaCost, MTGCardInstance * c){ + ManaCost * manaCost; + if (_manaCost){ + manaCost = _manaCost; + }else{ + manaCost = NEW ManaCost(); + } + int state = 0; + unsigned int start = 0; + unsigned int end = 0; + while (!s.empty() && state != -1){ + switch(state){ + case 0: + start = s.find_first_of("{"); + if (start == string::npos){ + return manaCost; + }else{ + state = 1; + } + break; + case 1: + end = s.find_first_of("}"); + if (end == string::npos){ + state = -1; + }else{ + string value = s.substr(start+1, end - 1 - start); + if (value == "u"){ + manaCost->add(Constants::MTG_COLOR_BLUE, 1); + }else if (value == "b"){ + manaCost->add(Constants::MTG_COLOR_BLACK, 1); + }else if (value == "w"){ + manaCost->add(Constants::MTG_COLOR_WHITE, 1); + }else if (value == "g"){ + manaCost->add(Constants::MTG_COLOR_GREEN, 1); + }else if (value == "r"){ + manaCost->add(Constants::MTG_COLOR_RED, 1); + }else if (value == "x"){ + manaCost->x(); + }else if (value == "t"){ + //Tap is handled outside of Manacost + }else if (value[0] == 's'){ + //sacrifice + OutputDebugString("Sacrifice\n"); + TargetChooserFactory tcf; + TargetChooser * tc = NULL; + size_t target_start = value.find("("); + size_t target_end = value.find(")"); + if (target_start!=string::npos && target_end!=string::npos){ + string target = value.substr(target_start+1, target_end-1 - target_start); + tc = tcf.createTargetChooser(target,c); + } + manaCost->addExtraCost(NEW SacrificeCost(tc)); + }else{ + int intvalue = atoi(value.c_str()); + int colors[2]; + int values[2]; + if (intvalue < 10 && value.size() > 1){ + for (int i = 0; i < 2; i++){ + char c = value[i]; + if (c >='0' && c <='9'){ + colors[i] = Constants::MTG_COLOR_ARTIFACT; + values[i] = c - '0'; + }else{ + for (int j = 0; j < Constants::MTG_NB_COLORS; j++){ + if (c == Constants::MTGColorChars[j]){ + colors[i] = j; + values[i] = 1; + } + } + } + } + manaCost->addHybrid(colors[0], values[0], colors[1], values[1]); + }else{ + manaCost->add(Constants::MTG_COLOR_ARTIFACT, intvalue); + } + } + s = s.substr(end + 1); + state = 0; + } + break; + default: + break; + } + } + + return manaCost; +} + +ManaCost::ManaCost(){ + init(); +} +ManaCost::ManaCost(int _cost[], int nb_elems){ + init(); + int i; + int total = nb_elems; + for (i = 0; i < total; i++){ + cost[_cost[i*2]] = _cost[i*2 + 1]; + } + +} + +ManaCost::ManaCost(ManaCost * _manaCost){ + init(); + int i; + for (i=0; i<= Constants::MTG_NB_COLORS; i++){ + cost[i] = _manaCost->getCost(i); + } +} + +ManaCost::~ManaCost(){ + for (unsigned int i = 0; i < nbhybrids ; i++){ + SAFE_DELETE(hybrids[i]); + } + if (!extraCostsIsCopy) { + SAFE_DELETE(extraCosts); + } +} + +void ManaCost::x(){ + cost[Constants::MTG_NB_COLORS] = 1; +} + +void ManaCost::init(){ + int i; + for (i=0; i<= Constants::MTG_NB_COLORS; i++){ + cost[i] = 0; + } + nbhybrids = 0; + extraCosts = NULL; + extraCostsIsCopy = 0; +} + + +void ManaCost::copy(ManaCost * _manaCost){ + for (unsigned int i = 0; i <= Constants::MTG_NB_COLORS; i++){ + cost[i] = _manaCost->getCost(i); + } + for (unsigned int i = 0; i < _manaCost->nbhybrids; i++){ + hybrids[i] = NEW ManaCostHybrid((*_manaCost->hybrids[i])); + } + nbhybrids = _manaCost->nbhybrids; + + if (_manaCost->extraCosts){ + //TODO Deep copy ? + if(!extraCostsIsCopy) SAFE_DELETE(extraCosts); + extraCosts = _manaCost->extraCosts; + extraCostsIsCopy = 1; + } +} + +int ManaCost::getCost(int color){ + return cost[color]; +} + +ManaCostHybrid * ManaCost::getHybridCost(unsigned int i){ + if (nbhybrids <= i) return NULL; + return hybrids[i]; +} + +int ManaCost::getMainColor(){ + for (int i=0; i< Constants::MTG_NB_COLORS; i++){ + if (cost[i]) return i; + } + return 0; +} + +int ManaCost::hasColor(int color){ + if (cost[color]) return 1; + for (unsigned int i = 0; i < nbhybrids; i++){ + if (hybrids[i]->hasColor(color)) return 1; + } + return 0; +} + +int ManaCost::isNull(){ + if (getConvertedCost()) return 0; + if (extraCosts) return 0; + return 1; +} + +int ManaCost::getConvertedCost(){ + int result = 0; + for (unsigned int i = 0; i < Constants::MTG_NB_COLORS; i++){ + result += cost[i]; + } + for (unsigned int i = 0; i < nbhybrids; i++){ + result+= hybrids[i]->getConvertedCost(); + } + return result; +} + +int ManaCost::remove(int color, int value){ + cost[color] -= value; + return 1; +} + +int ManaCost::add(int color, int value){ + cost[color] += value; + return 1; +} + +int ManaCost::add(ManaCost * _cost){ + if(!_cost) return 0; + for (unsigned int i = 0; i < Constants::MTG_NB_COLORS; i++){ + cost[i]+= _cost->getCost(i); + } + for (unsigned int i = 0; i < _cost->nbhybrids; i++){ + hybrids[nbhybrids] = NEW ManaCostHybrid((*_cost->hybrids[i])); + nbhybrids++; + } + return 1; +} + +string ManaCost::toString(){ + return "ManaCost - Todo"; +} + + +int ManaCost::addHybrid(int c1, int v1, int c2, int v2){ + ManaCostHybrid * h = NEW ManaCostHybrid(c1,v1,c2,v2); + hybrids[nbhybrids] = h; + nbhybrids++; + return nbhybrids; +} + +int ManaCost::addExtraCost(ExtraCost * _cost){ + if (!extraCosts) extraCosts = NEW ExtraCosts(); + extraCosts->costs.push_back(_cost); + OutputDebugString("Adding Sacrifice\n"); + return 1; +} + + +int ManaCost::isExtraPaymentSet(){ + if (!extraCosts) return 1; + OutputDebugString("Checking costs\n"); + return extraCosts->isPaymentSet(); +} + +int ManaCost::resetExtraPayment(){ + if (!extraCosts) return 1; + return extraCosts->reset(); +} + +int ManaCost::doPayExtra(){ + if (!extraCosts) return 0; + return extraCosts->doPay(); //TODO reset ? +} + +int ManaCost::setExtraCostsAction(MTGAbility * action, MTGCardInstance * card){ + if (extraCosts) extraCosts->setAction(action, card); + return 1; +} + +int ManaCost::pay(ManaCost * _cost){ + ManaCost * diff = Diff(_cost); + for (int i=0; i < Constants::MTG_NB_COLORS; i++){ + cost[i] = diff->getCost(i); + } + delete diff; + return 1; + //TODO return 0 if can't afford the cost! +} + +//return 1 if _cost can be paid with current data, 0 otherwise +int ManaCost::canAfford(ManaCost * _cost){ + ManaCost * diff = Diff(_cost); + int positive = diff->isPositive(); + delete diff; + if (positive){ + return 1; + } + return 0; +} + +int ManaCost::isPositive(){ + for (int i=0; i < Constants::MTG_NB_COLORS; i++){ + + if (cost[i] < 0){ + return 0; + } + } + return 1; + +} + + +void ManaCost::randomDiffHybrids(ManaCost * _cost, int diff[]){ + int _nbhybrids = _cost->nbhybrids; + for (int i = 0; i < _nbhybrids; i++){ + ManaCostHybrid * h = _cost->hybrids[i]; + diff[h->color1 * 2 +1]-= h->value1; + } +} + +int ManaCost::tryToPayHybrids(ManaCostHybrid * _hybrids[], int _nbhybrids, int diff[]){ + if (!_nbhybrids) return 1; + int result = 0; + ManaCostHybrid * h = _hybrids[_nbhybrids -1]; + if (diff[h->color1 * 2 +1] >= h->value1){ + diff[h->color1 * 2 +1]-= h->value1; + result = tryToPayHybrids(_hybrids,_nbhybrids -1, diff); + if (result) return 1; + diff[h->color1 * 2 +1]+= h->value1; + } + if (diff[h->color2 * 2 +1] >= h->value2){ + diff[h->color2 * 2 +1]-= h->value2; + result = tryToPayHybrids(_hybrids,_nbhybrids -1, diff); + if (result) return 1; + diff[h->color2 * 2 +1]+= h->value2; + } + return 0; +} + +//compute the difference between two mana costs +ManaCost * ManaCost::Diff(ManaCost * _cost){ + int diff[(Constants::MTG_NB_COLORS + 1 )* 2]; + diff[Constants::MTG_NB_COLORS * 2] = Constants::MTG_NB_COLORS; + for (int i=0; i < Constants::MTG_NB_COLORS; i++){ + diff[i*2] = i; + diff[i*2 +1] = cost[i] - _cost->getCost(i); + } + int hybridResult = tryToPayHybrids(_cost->hybrids, _cost->nbhybrids, diff); + if (!hybridResult) randomDiffHybrids(_cost,diff); + + //Colorless mana, special case + int colorless_idx = Constants::MTG_COLOR_ARTIFACT * 2 + 1; + if (diff[colorless_idx] < 0){ + for (int i=0; i < Constants::MTG_NB_COLORS; i++){ + if (diff[i*2 + 1] > 0){ + if (diff[i*2 + 1] + diff[colorless_idx] > 0){ + diff[i*2 + 1] += diff[colorless_idx]; + diff[colorless_idx] = 0; + break; + }else{ + diff[colorless_idx] += diff[i*2 + 1]; + diff[i*2 + 1] = 0; + } + } + } + } + + //Cost X + if (_cost->getCost(Constants::MTG_NB_COLORS)){ + diff[Constants::MTG_NB_COLORS * 2 + 1] = 0; + for (int i=0; i < Constants::MTG_NB_COLORS; i++){ + if (diff[i*2 + 1] > 0){ + diff[Constants::MTG_NB_COLORS * 2 + 1] += diff[i*2 + 1]; + diff[i*2 + 1] = 0; + } + } + } + + ManaCost * result = NEW ManaCost(diff, Constants::MTG_NB_COLORS +1); + return result; + +} + +#ifdef WIN32 +void ManaCost::Dump(){ + char buf[4096]; + OutputDebugString("\n===ManaCost===\n"); + for (int i=0; i<= Constants::MTG_NB_COLORS; i++){ + if (cost[i]) { + sprintf(buf, "%c:%i - ", Constants::MTGColorChars[i],cost[i]); + OutputDebugString(buf); + } + } + + for (unsigned int i=0; i< nbhybrids; i++){ + ManaCostHybrid * h = hybrids[i]; + + sprintf(buf, "H:{%c:%i}/{%c:%i}", Constants::MTGColorChars[h->color1], h->value1, Constants::MTGColorChars[h->color2], h->value2); + OutputDebugString(buf); + } + OutputDebugString("\n=============\n"); +} + +#endif + +ostream& operator<<(ostream& out, const ManaCost& m) +{ + return out << "(manacost)"; +} + + +void ManaPool::init(){ + ManaCost::init(); WEvent * e = NEW WEventEmptyManaPool(this); - GameObserver::GetInstance()->receiveEvent(e); -} - -ManaPool::ManaPool(Player * player):ManaCost(),player(player){} -ManaPool::ManaPool(ManaCost * _manaCost,Player * player):ManaCost(_manaCost),player(player){} - -int ManaPool::remove (int color, int value){ - int result = ManaCost::remove(color, value); - for (int i = 0; i < value; ++i){ - WEvent * e = NEW WEventConsumeMana(color, this); - GameObserver::GetInstance()->receiveEvent(e); - } - return result; -} - -int ManaPool::add(int color, int value, MTGCardInstance * source ){ - int result = ManaCost::add(color, value); - for (int i = 0; i < value; ++i){ - WEvent * e = NEW WEventEngageMana(color, source,this); - GameObserver::GetInstance()->receiveEvent(e); - } - return result; -} - -int ManaPool::add(ManaCost * _cost, MTGCardInstance * source){ - if(!_cost) return 0; - int result = ManaCost::add(_cost); - for (unsigned int i = 0; i < Constants::MTG_NB_COLORS; i++){ - for (int j = 0; j < _cost->getCost(i); j++){ - WEvent * e = NEW WEventEngageMana(i, source, this); - GameObserver::GetInstance()->receiveEvent(e); - } - } - return result; -} -int ManaPool::pay (ManaCost * _cost){ - int current[Constants::MTG_NB_COLORS]; - for (unsigned int i = 0; i < Constants::MTG_NB_COLORS; i++){ - current[i] = cost[i]; - } - int result = ManaCost::pay(_cost); - for (unsigned int i = 0; i < Constants::MTG_NB_COLORS; i++){ - int value = current[i] - cost[i]; - for (int j = 0; j receiveEvent(e); - } - } - return result; + GameObserver::GetInstance()->receiveEvent(e); +} + +ManaPool::ManaPool(Player * player):ManaCost(),player(player){} +ManaPool::ManaPool(ManaCost * _manaCost,Player * player):ManaCost(_manaCost),player(player){} + +int ManaPool::remove (int color, int value){ + int result = ManaCost::remove(color, value); + for (int i = 0; i < value; ++i){ + WEvent * e = NEW WEventConsumeMana(color, this); + GameObserver::GetInstance()->receiveEvent(e); + } + return result; +} + +int ManaPool::add(int color, int value, MTGCardInstance * source ){ + int result = ManaCost::add(color, value); + for (int i = 0; i < value; ++i){ + WEvent * e = NEW WEventEngageMana(color, source,this); + GameObserver::GetInstance()->receiveEvent(e); + } + return result; +} + +int ManaPool::add(ManaCost * _cost, MTGCardInstance * source){ + if(!_cost) return 0; + int result = ManaCost::add(_cost); + for (unsigned int i = 0; i < Constants::MTG_NB_COLORS; i++){ + for (int j = 0; j < _cost->getCost(i); j++){ + WEvent * e = NEW WEventEngageMana(i, source, this); + GameObserver::GetInstance()->receiveEvent(e); + } + } + return result; +} +int ManaPool::pay (ManaCost * _cost){ + int current[Constants::MTG_NB_COLORS]; + for (unsigned int i = 0; i < Constants::MTG_NB_COLORS; i++){ + current[i] = cost[i]; + } + int result = ManaCost::pay(_cost); + for (unsigned int i = 0; i < Constants::MTG_NB_COLORS; i++){ + int value = current[i] - cost[i]; + for (int j = 0; j receiveEvent(e); + } + } + return result; } \ No newline at end of file diff --git a/projects/mtg/src/OptionItem.cpp b/projects/mtg/src/OptionItem.cpp index f3ea23bf6..0d26be1a8 100644 --- a/projects/mtg/src/OptionItem.cpp +++ b/projects/mtg/src/OptionItem.cpp @@ -46,7 +46,7 @@ OptionItem::OptionItem( string _id, string _displayValue) { //Option Integer void OptionInteger::Render(){ - JLBFont * mFont = GameApp::CommonRes->GetJLBFont("f3"); + JLBFont * mFont = resources.GetJLBFont("f3"); if (hasFocus){ mFont->SetColor(options[Metrics::OPTION_ITEM_TCH].asColor(ARGB(255,255,255,0))); }else{ @@ -106,7 +106,7 @@ void OptionSelect::initSelections(){ } void OptionSelect::Render(){ - JLBFont * mFont = GameApp::CommonRes->GetJLBFont("f3"); + JLBFont * mFont = resources.GetJLBFont("f3"); if (hasFocus){ mFont->SetColor(options[Metrics::OPTION_ITEM_TCH].asColor(ARGB(255,255,255,0))); }else{ @@ -148,7 +148,7 @@ ostream& OptionSelect::toString(ostream& out) const //OptionHeader void OptionHeader::Render(){ - JLBFont * mFont = GameApp::CommonRes->GetJLBFont("f3"); + JLBFont * mFont = resources.GetJLBFont("f3"); mFont->SetColor(options[Metrics::OPTION_HEADER_TC].asColor()); JRenderer * renderer = JRenderer::GetInstance(); @@ -157,7 +157,7 @@ void OptionHeader::Render(){ } void OptionText::Render(){ - JLBFont * mFont = GameApp::CommonRes->GetJLBFont("f3"); + JLBFont * mFont = resources.GetJLBFont("f3"); mFont->SetScale(.8); mFont->SetColor(options[Metrics::OPTION_TEXT_TC].asColor()); @@ -245,7 +245,7 @@ void OptionProfile::populate(){ void OptionProfile::Render(){ JRenderer * renderer = JRenderer::GetInstance(); - JLBFont * mFont = GameApp::CommonRes->GetJLBFont("f3"); + JLBFont * mFont = resources.GetJLBFont("f3"); mFont->SetScale(1); int spacing = 2+(int)mFont->GetHeight(); @@ -430,7 +430,7 @@ void OptionsList::Render(){ //List is empty. if (!nbitems && failMsg != ""){ - JLBFont * mFont = GameApp::CommonRes->GetJLBFont("f3"); + JLBFont * mFont = resources.GetJLBFont("f3"); mFont->SetColor(options[Metrics::MSG_FAIL_TC].asColor(ARGB(255,155,155,155))); mFont->DrawString(failMsg.c_str(),SCREEN_WIDTH/2, 40, JGETEXT_RIGHT); return; @@ -623,7 +623,7 @@ void OptionsMenu::Update(float dt){ OptionsMenu::OptionsMenu(){ nbitems=0; current=0; - mFont = GameApp::CommonRes->GetJLBFont("f3"); + mFont = resources.GetJLBFont("f3"); for(int x=0;xGetJLBFont("f3"); + JLBFont * mFont = resources.GetJLBFont("f3"); if (hasFocus){ mFont->SetColor(options[Metrics::OPTION_ITEM_TCH].asColor(ARGB(255,255,255,0))); }else{ diff --git a/projects/mtg/src/PlayerData.cpp b/projects/mtg/src/PlayerData.cpp index 365bab163..95bd964c9 100644 --- a/projects/mtg/src/PlayerData.cpp +++ b/projects/mtg/src/PlayerData.cpp @@ -21,7 +21,7 @@ PlayerData::PlayerData(MTGAllCards * allcards){ } //COLLECTION - collection = NEW MTGDeck(options.profileFile(PLAYER_COLLECTION,"",false).c_str(), allcards->mCache, allcards); + collection = NEW MTGDeck(options.profileFile(PLAYER_COLLECTION,"",false).c_str(), allcards); } diff --git a/projects/mtg/src/ShopItem.cpp b/projects/mtg/src/ShopItem.cpp index eed34d069..dd31e5a90 100644 --- a/projects/mtg/src/ShopItem.cpp +++ b/projects/mtg/src/ShopItem.cpp @@ -2,7 +2,7 @@ #include "../include/ShopItem.h" #include "../include/GameStateShop.h" #include "../include/CardGui.h" -#include "../include/TexturesCache.h" +#include "../include/WResourceManager.h" #include "../include/Translate.h" #include @@ -69,7 +69,7 @@ ShopItem::ShopItem(int id, JLBFont *font, int _cardid, float _xy[], bool hasFocu if (card->getRarity() == Constants::RARITY_L) quantity = 50; quad = NULL; - thumb = cache.getThumb(card); + thumb = resources.RetrieveCard(card,CACHE_THUMB); if (!thumb) thumb = CardGui::alternateThumbQuad(card); @@ -157,7 +157,7 @@ void ShopItem::Render(){ //NOTHING } if (mHasFocus){ - if (card) quad = cache.getQuad(card); + if (card) quad = resources.RetrieveCard(card); if (quad){ quad->SetColor(ARGB(255,255,255,255)); renderer->RenderQuad(quad,SCREEN_WIDTH - 105,SCREEN_HEIGHT/2 - 5,0, 0.9f,0.9f); @@ -169,9 +169,6 @@ void ShopItem::Render(){ } } - - - void ShopItem::Update(float dt) { if (mScale < mTargetScale){ @@ -231,7 +228,7 @@ ShopItems::ShopItems(int id, JGuiListener* listener, JLBFont* font, int x, int y for (int i=0; i < SHOP_BOOSTERS; i++){ setIds[i] = _setIds[i]; }; - myCollection = NEW DeckDataWrapper(NEW MTGDeck(options.profileFile(PLAYER_COLLECTION).c_str(), NULL,_collection)); + myCollection = NEW DeckDataWrapper(NEW MTGDeck(options.profileFile(PLAYER_COLLECTION).c_str(), _collection)); } @@ -262,7 +259,7 @@ void ShopItems::Update(float dt){ char buffer[4096]; sprintf(buffer,"%s : %i credits",item->getText(),price); if(!dialog){ - dialog = NEW SimpleMenu(1,this,GameApp::CommonRes->GetJLBFont(Constants::MENU_FONT),SCREEN_WIDTH-300,SCREEN_HEIGHT/2,buffer); + dialog = NEW SimpleMenu(1,this,resources.GetJLBFont(Constants::MENU_FONT),SCREEN_WIDTH-300,SCREEN_HEIGHT/2,buffer); dialog->Add(1,"Yes"); dialog->Add(2,"No"); } @@ -336,7 +333,7 @@ void ShopItems::ButtonPressed(int controllerId, int controlId){ safeDeleteDisplay(); display = NEW CardDisplay(12,NULL, SCREEN_WIDTH - 200, SCREEN_HEIGHT/2,this,NULL,5); - MTGDeck * tempDeck = NEW MTGDeck(NULL,playerdata->collection->database); + MTGDeck * tempDeck = NEW MTGDeck(playerdata->collection->database); int rare_or_mythic = Constants::RARITY_R; int rnd = rand() % 8; if (rnd == 0) rare_or_mythic = Constants::RARITY_M; diff --git a/projects/mtg/src/SimpleMenu.cpp b/projects/mtg/src/SimpleMenu.cpp index fe3def6a6..4eb0efe72 100644 --- a/projects/mtg/src/SimpleMenu.cpp +++ b/projects/mtg/src/SimpleMenu.cpp @@ -43,21 +43,21 @@ SimpleMenu::SimpleMenu(int id, JGuiListener* listener, JLBFont* font, int x, int JRenderer* renderer = JRenderer::GetInstance(); - if (!spadeLTex) spadeLTex= GameApp::CommonRes->LoadTexture("spade_ul.png", TEX_TYPE_USE_VRAM); - if (!spadeRTex) spadeRTex = GameApp::CommonRes->LoadTexture("spade_ur.png", TEX_TYPE_USE_VRAM); + if (!spadeLTex) spadeLTex= resources.RetrieveTexture("spade_ul.png", RETRIEVE_MANAGE); + if (!spadeRTex) spadeRTex = resources.RetrieveTexture("spade_ur.png", RETRIEVE_MANAGE); if (!jewelTex) jewelTex= renderer->CreateTexture(5, 5, TEX_TYPE_USE_VRAM); - if (!sideTex) sideTex = GameApp::CommonRes->LoadTexture("menuside.png", TEX_TYPE_USE_VRAM); -if (NULL == spadeL) spadeL = NEW JQuad(spadeLTex, 2, 1, 16, 13); - if (NULL == spadeR) spadeR = NEW JQuad(spadeRTex, 2, 1, 16, 13); + if (!sideTex) sideTex = resources.RetrieveTexture("menuside.png", RETRIEVE_MANAGE); +if (NULL == spadeL) spadeL = resources.RetrieveQuad("spade_ul.png", 2, 1, 16, 13, "spade_ul", RETRIEVE_MANAGE); + if (NULL == spadeR) spadeR = resources.RetrieveQuad("spade_ur.png", 2, 1, 16, 13, "spade_ur", RETRIEVE_MANAGE); if (NULL == jewel) jewel = NEW JQuad(jewelTex, 1, 1, 3, 3); - if (NULL == side) side = NEW JQuad(sideTex, 1, 1, 1, 7); + if (NULL == side) side = resources.RetrieveQuad("menuside.png", 1, 1, 1, 7,"menuside", RETRIEVE_MANAGE); if (NULL == titleFont) { - GameApp::CommonRes->LoadJLBFont("smallface", 7); - titleFont = GameApp::CommonRes->GetJLBFont("smallface"); + resources.LoadJLBFont("smallface", 7); + titleFont = resources.GetJLBFont("smallface"); } - if (NULL == stars) stars = NEW hgeParticleSystem("graphics/stars.psi", GameApp::CommonRes->GetQuad("stars")); + if (NULL == stars) stars = NEW hgeParticleSystem("graphics/stars.psi", resources.GetQuad("stars")); stars->MoveTo(mX, mY); } @@ -129,7 +129,7 @@ void SimpleMenu::Render(){ if ((static_cast(mObjects[i]))->mY - LINE_HEIGHT * startId < mY + height - LINE_HEIGHT + 7) { if (static_cast(mObjects[i])->hasFocus()){ - GameApp::CommonRes->GetJLBFont(Constants::MAIN_FONT)->DrawString(static_cast(mObjects[i])->desc.c_str(),mX+mWidth+10,mY+15); + resources.GetJLBFont(Constants::MAIN_FONT)->DrawString(static_cast(mObjects[i])->desc.c_str(),mX+mWidth+10,mY+15); mFont->SetColor(options[Metrics::POPUP_MENU_TCH].asColor(ARGB(255,255,255,0))); } else @@ -178,13 +178,13 @@ void SimpleMenu::Close() } void SimpleMenu::destroy(){ - SAFE_DELETE(SimpleMenu::spadeR); - SAFE_DELETE(SimpleMenu::spadeL); + resources.Release(SimpleMenu::spadeR); + resources.Release(SimpleMenu::spadeL); + resources.Release(SimpleMenu::side); + resources.Release(SimpleMenu::spadeRTex); + resources.Release(SimpleMenu::spadeLTex); + resources.Release(SimpleMenu::sideTex); SAFE_DELETE(SimpleMenu::jewel); - SAFE_DELETE(SimpleMenu::side); - SAFE_DELETE(SimpleMenu::spadeRTex); - SAFE_DELETE(SimpleMenu::spadeLTex); - SAFE_DELETE(SimpleMenu::jewelTex); - SAFE_DELETE(SimpleMenu::sideTex); SAFE_DELETE(SimpleMenu::stars); + SAFE_DELETE(SimpleMenu::jewelTex); } \ No newline at end of file diff --git a/projects/mtg/src/SimplePad.cpp b/projects/mtg/src/SimplePad.cpp index 72c666b4f..c41034005 100644 --- a/projects/mtg/src/SimplePad.cpp +++ b/projects/mtg/src/SimplePad.cpp @@ -278,7 +278,7 @@ string SimplePad::Finish() { void SimplePad::Render(){ //This could use some cleaning up to make margins more explicit - JLBFont * mFont = GameApp::CommonRes->GetJLBFont("f3"); + JLBFont * mFont = resources.GetJLBFont("f3"); int offX = 0, offY = 0; int kH = mFont->GetHeight(); diff --git a/projects/mtg/src/TestSuiteAI.cpp b/projects/mtg/src/TestSuiteAI.cpp index 452071a28..2e19423f6 100644 --- a/projects/mtg/src/TestSuiteAI.cpp +++ b/projects/mtg/src/TestSuiteAI.cpp @@ -296,7 +296,7 @@ void TestSuite::initGame(){ for (int k = 0; k < initState.playerData[i].zones[j].nbitems; k++){ MTGCardInstance * card = getCardByMTGId(initState.playerData[i].zones[j].cards[k]); char buf[4096]; - sprintf(buf, "QUAD : %p\n", cache.getQuad(card)); + sprintf(buf, "QUAD : %p\n", resources.RetrieveCard(card)); OutputDebugString(buf); if (card && zone != p->game->library){ if (zone == p->game->inPlay){ diff --git a/projects/mtg/src/TexturesCache.cpp b/projects/mtg/src/TexturesCache.cpp deleted file mode 100644 index 98ce2def3..000000000 --- a/projects/mtg/src/TexturesCache.cpp +++ /dev/null @@ -1,227 +0,0 @@ -#include "../include/config.h" -#include "../include/TexturesCache.h" -#include "../include/GameOptions.h" -#include - -TexturesCache cache; - -TexturesCache::TexturesCache(){ - nb_textures = 0; - totalsize = 0; - delete_previous = 0; - lastTime = 0; -#ifdef WIN32 - char buf [4096]; - sprintf(buf, " Init TextureCache : %p\n", this); - OutputDebugString(buf); -#endif -} - -TexturesCache::~TexturesCache(){ - LOG("==Destroying TexturesCache=="); - for (map::iterator it = cache.begin(); it != cache.end(); ++it){ - delete it->second; - } - LOG("==Destroying TexturesCache Successful=="); -} - -int TexturesCache::isInCache(MTGCard * card, int type){ - CachedTexture * tex = getCacheByCard(card, type); - if (tex) return 1; - return 0; -} - -CachedTexture * TexturesCache::getCacheByCard(MTGCard *card, int type){ - char _filename[512]; - if (type == CACHE_THUMB){ - sprintf(_filename, "sets/%s/thumbnails/%s", card->getSetName(), card->getImageName()); - }else{ - sprintf(_filename, "sets/%s/%s", card->getSetName(), card->getImageName()); - } - string filename = _filename; - return cache[filename]; -} - - -int TexturesCache::removeOldestQuad(){ - int oldest = -1; - string result = ""; - for (map::iterator it = cache.begin(); it != cache.end(); ++it){ - if (it->second && (oldest == -1 || oldest > it->second->lastTime)){ - oldest = it->second->lastTime; - result = it->first; - } - } - if (oldest != -1){ - removeQuad(result); - return 1; - } - return 0; -} - -void TexturesCache::removeQuad(string id){ - totalsize -= cache[id]->nbpixels; - delete cache[id]; - cache.erase(id); - nb_textures--; -} - -int TexturesCache::cleanup(){ - int maxSize = options[Options::CACHESIZE].number * 100000; - if (!maxSize) maxSize = CACHE_SIZE_PIXELS; - while (totalsize > maxSize){ - int result = removeOldestQuad(); - if (!result) return 0; - } - return 1; -} - -JQuad * TexturesCache::getQuad(string filename,MTGCard * card, int type){ - CachedTexture * ctex = cache[filename]; - if (!ctex){ - if (cleanup()){ - if (card) cache[filename] = NEW CachedTexture(card,type); - else cache[filename] = NEW CachedTexture(filename); - totalsize+= cache[filename]->nbpixels; - fprintf(stderr, "Total Size of cache in pixels: %i\n", totalsize); - nb_textures++; - }else{ - //Error - return NULL; - } - } - cache[filename]->lastTime = lastTime++; - return cache[filename]->getQuad(); -} - -JQuad * TexturesCache::getQuad(MTGCard * card, int type){ - char _filename[512]; - if (type == CACHE_THUMB){ - sprintf(_filename, "sets/%s/thumbnails/%s", card->getSetName(), card->getImageName()); - }else{ - sprintf(_filename, "sets/%s/%s", card->getSetName(), card->getImageName()); - } - string filename = _filename; - return getQuad(filename,card,type); -} - - -CachedTexture::CachedTexture(string filename){ - quad = NULL; - tex = NULL; - nbpixels = 0; - lastTime = 0; - if (fileExists(filename.c_str())) init(filename); -} - -CachedTexture::CachedTexture(MTGCard * card, int type){ - LOG("==Creating CardTexture Object"); - JFileSystem* fs = JFileSystem::GetInstance(); - char filename[100]; - quad = NULL; - tex = NULL; - nbpixels = 0; - lastTime = 0; - if (type == CACHE_THUMB){ - sprintf(filename, "sets/%s/thumbnails/%s", card->getSetName(), card->getImageName()); - }else{ - sprintf(filename, "sets/%s/%s", card->getSetName(), card->getImageName()); - } - - if (fileExists(filename)){ - fs->DetachZipFile(); - init(filename); - }else{ - char zipname[100]; - sprintf(zipname, "Res/sets/%s/%s.zip", card->getSetName(),card->getSetName()); - if (fileExists(zipname)){ - fs->AttachZipFile(zipname); - if (type == CACHE_THUMB){ - sprintf(filename, "thumbnails/%s", card->getImageName()); - }else{ - sprintf(filename, "%s", card->getImageName()); - } - init(filename); - } - } - - LOG("CardTexture Object Creation succesful"); -} - -void CachedTexture::init(string filename){ - tex = JRenderer::GetInstance()->LoadTexture(filename.c_str(), false,GU_PSM_5551); - if (tex){ - quad = NEW JQuad(tex, 0.0f, 0.0f, tex->mWidth, tex->mHeight); - quad->SetHotSpot(tex->mWidth / 2, tex->mHeight / 2); - nbpixels = tex->mTexHeight * tex->mTexWidth; - } -} -JQuad * CachedTexture::getQuad(){ - return quad; -} - -CachedTexture::~CachedTexture(){ - LOG("==Deleting CardTexture Object"); - SAFE_DELETE(quad); - SAFE_DELETE(tex); - LOG("CardTexture Object deletion Succesful"); -} - - -SampleCache * SampleCache::mInstance = NULL; - -SampleCache * SampleCache::GetInstance(){ - if (!mInstance) mInstance = NEW SampleCache(); - return mInstance; -} - -JSample * SampleCache::getSample(string filename){ - lastTime++; - map::iterator it = cache.find(filename); - if (it == cache.end()){ - if (cache.size() >10) cleanOldest(); //Poor man's limit - JSample * sample = GameApp::CommonRes->ssLoadSample(filename.c_str()); - if (!sample && fileExists(GameApp::CommonRes->sfxFile(filename).c_str())){ //Out of Ram ?? - cleanCache(); - sample = GameApp::CommonRes->ssLoadSample(filename.c_str()); - } - - cache[filename] = NEW SampleCached(lastTime, sample); - return sample; - }else{ - it->second->lastTime = lastTime; - return (it->second->sample); - } -} - -void SampleCache::cleanOldest(){ - int smallest = lastTime; - map::iterator found = cache.end(); - map::iterator it; - for (it = cache.begin(); it != cache.end(); it++){ - if(it->second->lastTime <= smallest){ - smallest = it->second->lastTime; - found = it; - } - } - if (found != cache.end()){ - delete (found->second); - cache.erase(found); - } -} - -void SampleCache::cleanCache(){ - map::iterator it; - for (it = cache.begin(); it != cache.end(); it++){ - delete(it->second); - } - cache.clear(); -} - -SampleCache::~SampleCache(){ - cleanCache(); -} - -void SampleCache::DestroyInstance(){ - SAFE_DELETE(mInstance); -} diff --git a/projects/mtg/src/WResourceManager.cpp b/projects/mtg/src/WResourceManager.cpp index 3e37a2e00..29799fbcf 100644 --- a/projects/mtg/src/WResourceManager.cpp +++ b/projects/mtg/src/WResourceManager.cpp @@ -6,39 +6,582 @@ #include #include #include +#include #include "../include/WResourceManager.h" -WResourceManager::WResourceManager(){ - jrm = NEW JResourceManager(); +WResourceManager resources; + +WCachedResource::WCachedResource(){ + locks = 0; + lastTime = resources.nowTime(); +} + +bool WCachedResource::isLocked(){ + return (locks != 0); +} + +void WCachedResource::lock(){ + if(locks < 255) + locks++; +} + +void WCachedResource::unlock(bool force){ + if(force) + locks = 0; + else if(locks > 0) + locks--; +} + +void WCachedResource::hit(){ + lastTime = resources.nowTime(); +} + +WCachedTexture::WCachedTexture(){ + texture = NULL; +} + +WCachedTexture::~WCachedTexture(){ + SAFE_DELETE(texture); + for(vector::iterator i = trackedQuads.begin();i!=trackedQuads.end();i++) + SAFE_DELETE((*i)); +} + +JTexture * WCachedTexture::GetTexture(){ + return texture; +} + +bool WCachedTexture::ReleaseQuad(JQuad* quad){ + SAFE_DELETE(texture); + for(vector::iterator i = trackedQuads.begin();i!=trackedQuads.end();i++){ + if((*i) == quad){ + SAFE_DELETE(quad); + trackedQuads.erase(i); + return true; + } + } + return false; +} + +JQuad * WCachedTexture::GetQuad(float offX, float offY, float width, float height){ + if(texture == NULL) + return NULL; + + if(width == 0.0f) + width = texture->mWidth; + if(height == 0.0f) + height = texture->mHeight; + + vector::iterator it; + for(it = trackedQuads.begin();it!=trackedQuads.end();it++) + if((*it)->mHeight == height && (*it)->mWidth == width + && (*it)->mX == offX && (*it)->mY == offY) + return (*it); + + JQuad * jq = NEW JQuad(texture,offX,offY,width,height); + trackedQuads.push_back(jq); + return jq; +} + +JQuad * WCachedTexture::GetCard(float offX, float offY, float width, float height){ + if(texture == NULL) + return NULL; + + if(width == 0.0f) + width = texture->mWidth; + if(height == 0.0f) + height = texture->mHeight; + + vector::iterator it; + for(it = trackedQuads.begin();it!=trackedQuads.end();it++) + if((*it)->mHeight == height && (*it)->mWidth == width + && (*it)->mX == offX && (*it)->mY == offY) + return (*it); + + JQuad * jq = NEW JQuad(texture,offX,offY,width,height); + jq->SetHotSpot(jq->mTex->mWidth / 2, jq->mTex->mHeight / 2); + trackedQuads.push_back(jq); + return jq; +} + +WCachedSample::WCachedSample(){ + sample = NULL; +} + +WCachedSample::~WCachedSample(){ + SAFE_DELETE(sample); +} + +JSample * WCachedSample::GetSample(){ + return sample; +} + +bool WResourceManager::cleanup(){ + int maxSize = options[Options::CACHESIZE].number * 100000; + if (!maxSize) maxSize = CACHE_SIZE_PIXELS; + while (totalsize > maxSize){ + int result = RemoveOldestTexture(); + if (!result) return false; + } + return true; +} + + +unsigned int WResourceManager::nowTime(){ + if(lastTime == 65535) + FlattenTimes(); + + return ++lastTime; +} + +WCachedSample * WResourceManager::getCachedSample(string filename, bool makenew){ + WCachedSample * csample = sampleCache[filename]; + + //Failed to cache it! + if(!csample && makenew){ + csample = NEW WCachedSample(); + + //Space in cache, make new sample + if(cleanup()){ + csample->sample = ssLoadSample(filename.c_str()); + //Failed. + if(!csample->sample){ + for(map::iterator it=sampleCache.begin();it!=sampleCache.end();it++) + if(it->second == NULL){ + sampleCache.erase(it); + break; + } + SAFE_DELETE(csample); + return NULL; + } + csample->hit(); + sampleCache[filename] = csample; + } + else + return NULL; //Error. + } + + return csample; +} + +WCachedTexture * WResourceManager::getCachedTexture(string filename, bool makenew, int mode, int format){ + WCachedTexture * ctex = textureCache[filename]; + //Failed to cache it! + if(!ctex && makenew){ + ctex = NEW WCachedTexture(); + //Space in cache, make new texture + if(cleanup()){ + ctex->texture = JRenderer::GetInstance()->LoadTexture(graphicsFile(filename).c_str(),mode,format); + + //Couldn't create texture, so fail. + if(!ctex->texture){ + for(map::iterator it=textureCache.begin();it!=textureCache.end();it++) + if(it->second == NULL){ + textureCache.erase(it); + break; + } + + SAFE_DELETE(ctex); + return NULL; + } + ctex->hit(); + textureCache[filename] = ctex; + } + else + return NULL; //Error. + } + + return ctex; +} + +WCachedTexture * WResourceManager:: getCachedCard(MTGCard * card, int type, bool makenew){ + string filename = card->getImageName(); + if(type == CACHE_THUMB) + filename = "thumbnails/"+filename; + + WCachedTexture * ctex = textureCache[filename]; + //Failed to cache it! + if(!ctex && makenew){ + ctex = NEW WCachedTexture(); + //Space in cache, make new texture + if(cleanup()){ + ctex->texture = JRenderer::GetInstance()->LoadTexture(cardFile(filename,card->getSetName()).c_str()); + + //Couldn't create texture, so fail. + if(!ctex->texture){ + for(map::iterator it=textureCache.begin();it!=textureCache.end();it++) + if(it->second == NULL){ + textureCache.erase(it); + break; + } + + SAFE_DELETE(ctex); + return NULL; + } + ctex->hit(); + textureCache[filename] = ctex; + } + else + return NULL; //Error. + } + + return ctex; +} + +void WResourceManager::FlattenTimes(){ + unsigned int youngest = 65535; + unsigned int oldest = 0; + + for (map::iterator it = textureCache.begin(); it != textureCache.end(); ++it){ + if(!it->second) continue; + if(it->second->lastTime < youngest) youngest = it->second->lastTime; + if(it->second->lastTime > oldest) oldest = it->second->lastTime; + } + for (map::iterator it = sampleCache.begin(); it != sampleCache.end(); ++it){ + if(!it->second) continue; + if(it->second->lastTime < youngest) youngest = it->second->lastTime; + if(it->second->lastTime > oldest) oldest = it->second->lastTime; + } + + for (map::iterator it = sampleCache.begin(); it != sampleCache.end(); ++it){ + if(!it->second) continue; + it->second->lastTime -= youngest; + } + for (map::iterator it = textureCache.begin(); it != textureCache.end(); ++it){ + if(!it->second) continue; + it->second->lastTime -= youngest; + } + + lastTime = oldest; +} + +bool WResourceManager::RemoveOldestTexture(){ + map::iterator oldest; + for(map::iterator it = textureCache.begin();it!=textureCache.end();it++){ + if(it->second && (it->second->lastTime < oldest->second->lastTime + || (oldest->second->isLocked() && !it->second->isLocked()))) + oldest = it; + } + + if(oldest != textureCache.end()){ + SAFE_DELETE(oldest->second) + textureCache.erase(oldest); + return true; + } + + return false; +} + +bool WResourceManager::RemoveOldestSample(){ + map::iterator it, saved; + saved = sampleCache.begin(); + + for(it = sampleCache.begin();it!=sampleCache.end();it++){ + if(it->second->lastTime < saved->second->lastTime) + saved = it; + } + + if(saved != sampleCache.end()){ + SAFE_DELETE(saved->second); + sampleCache.erase(saved); + return true; + } + return false; +} +WResourceManager::WResourceManager(){ + + #ifdef WIN32 + char buf [4096]; + sprintf(buf, " Init WResourceManager : %p\n", this); + OutputDebugString(buf); + #endif + + mTextureList.clear(); + mTextureList.reserve(16); + mTextureMap.clear(); + + mQuadList.clear(); + mQuadList.reserve(128); + mQuadMap.clear(); + + mFontList.clear(); + mFontList.reserve(4); + mFontMap.clear(); + + mMusicList.clear(); + mMusicList.reserve(4); + mMusicMap.clear(); + + mSampleList.clear(); + mSampleList.reserve(8); + mSampleMap.clear(); + + nb_textures = 0; + totalsize = 0; + lastTime = 0; } WResourceManager::~WResourceManager(){ - SAFE_DELETE(jrm); + + LOG("==Destroying WResourceManager=="); + for (map::iterator it = textureCache.begin(); it != textureCache.end(); ++it){ + delete it->second; + } + for (map::iterator it = sampleCache.begin(); it != sampleCache.end(); ++it){ + delete it->second; + } + + textureCache.clear(); + sampleCache.clear(); + + RemoveAll(); + LOG("==Successfully Destroyed WResourceManager=="); + } -string WResourceManager::graphicsFile(const string filename, const string specific, bool bFont){ - char buf[512]; - char file[512]; - char lookup[512]; - - if(bFont) - sprintf(file,"%s.dat",filename.c_str()); +JQuad * WResourceManager::RetrieveCard(MTGCard * card, int type, int style){ + //Cards are never, ever resource managed, so just check cache. + WCachedTexture * tc; + if(style == RETRIEVE_EXISTING) + tc = getCachedCard(card,type,false); + else + tc = getCachedCard(card,type,true); + + //Perform lock or unlock on entry. + if(style == RETRIEVE_LOCK) tc->lock(); + else if(style == RETRIEVE_UNLOCK) tc->unlock(); + + //Texture exists! Get quad. + if(tc && tc->texture != NULL){ + tc->hit(); + return tc->GetCard(); + } + + return NULL; +} + +JQuad * WResourceManager::RetrieveQuad(string filename, float offX, float offY, float width, float height, string resname, int style){ +//Check our resources. + if(resname == "") + resname = filename; + + //No exactly existant quad + JQuad * retval = GetQuad(resname); + if(retval != NULL || style == RETRIEVE_RESOURCE) + return retval; + + //We have a managed resource named this! + JTexture * jtex = GetTexture(filename); + if(jtex){ + //Check for an existing quad with this name and stats + JQuad * jq = GetQuad(resname); + if(jq && jq->mHeight == height && jq->mWidth == width && jq->mX == offX && jq->mY == offY) + return jq; + + //Find a quad with these stats, regardless of name + for(vector::iterator it=mQuadList.begin();it!=mQuadList.end();it++){ + if((*it)->mHeight == height && (*it)->mWidth == width && (*it)->mX == offX && (*it)->mY == offY) + return (*it); + } + + //Overwrite the existing quad, if any. + CreateQuad(resname,filename,offX,offY,width,height); + return GetQuad(resname); + } + + //If we don't have an existing texture, check cache. + WCachedTexture * tc = NULL; + if(style != RETRIEVE_MANAGE){ + if(style == RETRIEVE_EXISTING) + tc = getCachedTexture(filename,false); + else if(style == RETRIEVE_VRAM) + tc = getCachedTexture(filename,true,TEX_TYPE_USE_VRAM); + else + tc = getCachedTexture(filename); + } + + //Quads never mess with locks. Ever. + if(style == RETRIEVE_MANAGE){ + //Remove cache hit from cache + map::iterator it = textureCache.end(); + tc = textureCache[filename]; + for(it = textureCache.begin();it!=textureCache.end();it++){ + if(it->second == tc) + break; + } + + SAFE_DELETE(tc); + if(it != textureCache.end()) + textureCache.erase(it); + //Pop texture & quad into resource manager + CreateQuad(resname,filename,offX,offY,width,height); + return GetQuad(resname); + } + + //Texture exists! Get quad. + if(tc && tc->texture != NULL){ + tc->hit(); + return tc->GetQuad(offX,offY,width,height); + } + + return NULL; +} +void WResourceManager::Release(JTexture * tex){ + if(tex == NULL) + return; + map::iterator it; + for(it = textureCache.begin();it!=textureCache.end();it++){ + if(it->second && it->second->texture == tex) + break; + } + + if(it != textureCache.end()){ + it->second->unlock(); + if(!it->second->isLocked()){ + SAFE_DELETE(it->second); + textureCache.erase(it); + } + } +} + +void WResourceManager::Release(JQuad * quad){ + map::iterator it; + if(quad == NULL) + return; + + for(it = textureCache.begin();it!=textureCache.end();it++){ + if(it->second && it->second->ReleaseQuad(quad)) + break; + } + + if(it != textureCache.end()){ + it->second->unlock(); + if(!it->second->isLocked()){ + SAFE_DELETE(it->second); + textureCache.erase(it); + } + } +} + +void WResourceManager::Release(JSample * sample){ + if(sample == NULL) + return; + + map::iterator it; + for(it = sampleCache.begin();it!=sampleCache.end();it++){ + if(it->second && it->second->sample == sample) + break; + } + + if(it != sampleCache.end()){ + it->second->unlock(); + if(!it->second->isLocked()){ + SAFE_DELETE(it->second); + sampleCache.erase(it); + } + } +} + +JTexture * WResourceManager::RetrieveTexture(string filename, int style){ +//Check our resources. + JTexture * retval = GetTexture(filename); + if(retval != NULL || style == RETRIEVE_RESOURCE) + return retval; + + //Check cache. + WCachedTexture * tc = NULL; + if(style != RETRIEVE_MANAGE){ + if(style == RETRIEVE_EXISTING) + tc = getCachedTexture(filename,false); + else if(style == RETRIEVE_VRAM) + tc = getCachedTexture(filename,true,TEX_TYPE_USE_VRAM); + else + tc = getCachedTexture(filename); + } + + //Perform lock or unlock on entry. + if(style == RETRIEVE_LOCK || style == RETRIEVE_VRAM) tc->lock(); + else if(style == RETRIEVE_UNLOCK) tc->unlock(); + //Make a new managed resource + else if(style == RETRIEVE_MANAGE){ + //Remove cache hit from cache + tc = textureCache[filename]; + map::iterator it = textureCache.end(); + for(it = textureCache.begin();it!=textureCache.end();it++){ + if(it->second == tc) + break; + } + + SAFE_DELETE(tc); + if(it != textureCache.end()) + textureCache.erase(it); + //Pop texture into resource manager + CreateTexture(filename); + return GetTexture(filename); + } + + //Texture exists! Get it. + if(tc->texture != NULL){ + tc->hit(); + return tc->GetTexture(); + } + + return retval; +} + +JSample * WResourceManager::RetrieveSample(string filename, int style){ +//Check our resources. + JSample * retval = GetSample(filename); + if(retval != NULL || style == RETRIEVE_RESOURCE) + return retval; + + //Check cache. + WCachedSample * tc; + + if(style != RETRIEVE_MANAGE){ + if(style == RETRIEVE_EXISTING) + tc = getCachedSample(filename,false); else - sprintf(file,"%s",filename.c_str()); + tc = getCachedSample(filename); + } + //Perform lock or unlock on entry. + if(style == RETRIEVE_LOCK) tc->lock(); + else if(style == RETRIEVE_UNLOCK) tc->unlock(); + //Make a new managed resource + else if(style == RETRIEVE_MANAGE){ + //Remove cache hit from cache + tc = sampleCache[filename]; + map::iterator it; + for(it = sampleCache.begin();it!=sampleCache.end();it++){ + if(it->second == tc) + break; + } - if(stopgap.find(filename) != stopgap.end()) - return stopgap[filename]; + SAFE_DELETE(tc); + if(it != sampleCache.end()) + sampleCache.erase(it); + //Pop sample into resource manager + LoadSample(filename); + return GetSample(filename); + } + //Sample exists! Get it. + if(tc->sample != NULL){ + tc->hit(); + return tc->GetSample(); + } + return retval; +} + +string WResourceManager::graphicsFile(const string filename, const string specific){ + char buf[512]; + //Check the specific location, if any. if(specific != ""){ - sprintf(buf,"%s/%s",specific.c_str(),file); - sprintf(lookup,"%s/%s",specific.c_str(),file); - if(fileOK(lookup,true)){ - stopgap[filename] = buf; + sprintf(buf,"%s/%s",specific.c_str(),filename.c_str()); + if(fileOK(buf,true)) return buf; - } } //Check the theme folder. @@ -46,12 +589,9 @@ string WResourceManager::graphicsFile(const string filename, const string specif std::transform(theme.begin(), theme.end(), theme.begin(), ::tolower); if(theme != "" || theme != "default"){ - sprintf(buf,"themes/%s/%s",theme.c_str(),filename.c_str()); - sprintf(lookup,"themes/%s/%s",theme.c_str(),file); - if(fileOK(lookup,true)){ - stopgap[filename] = buf; + sprintf(buf,"themes/%s/%s",theme.c_str(),filename.c_str()); + if(fileOK(buf,true)) return buf; - } } //Failure. Check mode graphics @@ -60,34 +600,82 @@ string WResourceManager::graphicsFile(const string filename, const string specif if(mode != "" && mode != "defualt"){ sprintf(buf,"modes/%s/graphics/%s",mode.c_str(),filename.c_str()); - sprintf(lookup,"modes/%s/graphics/%s",mode.c_str(),file); - if(fileOK(lookup,true)){ - stopgap[filename] = buf; + if(fileOK(buf,true)) return buf; - } } //Failure. Check graphics char graphdir[512]; sprintf(graphdir,"graphics/%s",filename.c_str()); - sprintf(lookup,"graphics/%s",file); - if(fileOK(lookup,true)){ - stopgap[filename] = graphdir; + if(fileOK(graphdir,true)) return graphdir; - } //Failure. Check sets. sprintf(buf,"sets/%s",filename.c_str()); - sprintf(lookup,"sets/%s",file); - if(fileOK(lookup,true)){ - stopgap[filename] = buf; + if(fileOK(buf,true)) return buf; - } //Complete abject failure. Probably a crash... return graphdir; } +string WResourceManager::cardFile(const string filename, const string setname, const string specific){ + JFileSystem* fs = JFileSystem::GetInstance(); + char buf[512]; + char sets[512]; + + fs->DetachZipFile(); + + if(setname != "") + sprintf(sets,"sets/%s",setname.c_str()); + else + sprintf(sets,"sets"); + + //Check the specific location, if any. + if(specific != ""){ + sprintf(buf,"%s/%s/%s",specific.c_str(),sets,filename.c_str()); + if(fileOK(buf,true)) + return buf; + } + + //Check the theme folder. + string theme = options[Options::ACTIVE_THEME].str; + std::transform(theme.begin(), theme.end(), theme.begin(), ::tolower); + + if(theme != "" || theme != "default"){ + sprintf(buf,"themes/%s/%s/%s",theme.c_str(),sets,filename.c_str()); + if(fileOK(buf,true)) + return buf; + } + + //Failure. Check mode + string mode = options[Options::ACTIVE_MODE].str; + std::transform(mode.begin(), mode.end(), mode.begin(), ::tolower); + + if(mode != "" && mode != "defualt"){ + sprintf(buf,"modes/%s/%s/%s",mode.c_str(),sets,filename.c_str()); + if(fileOK(buf,true)) + return buf; + } + + //Failure. Check sets + char defdir[512]; + sprintf(defdir,"%s/%s",sets,filename.c_str()); + if(fileOK(defdir,true)) + return defdir; + + //Failure. Assume it's in a zip file? + char zipname[100]; + sprintf(zipname, "Res/sets/%s/%s.zip", setname.c_str(),setname.c_str()); + if (fileExists(zipname)){ + fs->AttachZipFile(zipname); + return filename; + } + + //Complete abject failure. Probably a crash... + return defdir; +} + string WResourceManager::musicFile(const string filename, const string specific){ char buf[512]; @@ -179,58 +767,95 @@ int WResourceManager::fileOK(string filename, bool relative){ } int WResourceManager::CreateTexture(const string &textureName) { - return jrm->CreateTexture(graphicsFile(textureName)); -} -JTexture* WResourceManager::GetTexture(const string &textureName) { - return jrm->GetTexture(graphicsFile(textureName)); -} -JTexture* WResourceManager::GetTexture(int id) { - return jrm->GetTexture(id); -} + map::iterator itr = mTextureMap.find(textureName); -int WResourceManager::CreateQuad(const string &quadName, const string &textureName, float x, float y, float width, float height){ - return jrm->CreateQuad(quadName, graphicsFile(textureName), x, y, width, height); -} -JQuad* WResourceManager::GetQuad(const string &quadName){ - return jrm->GetQuad(quadName); -} -JQuad* WResourceManager::GetQuad(int id){ - return jrm->GetQuad(id); + if (itr == mTextureMap.end()) + { + string path = graphicsFile(textureName); + + printf("creating texture:%s\n", path.c_str()); + + JTexture *tex = JRenderer::GetInstance()->LoadTexture(path.c_str()); + + if (tex == NULL) + return INVALID_ID; + + int id = mTextureList.size(); + mTextureList.push_back(tex); + mTextureMap[textureName] = id; + + return id; + } + else + return itr->second; } int WResourceManager::LoadJLBFont(const string &fontName, int height){ - return jrm->LoadJLBFont(graphicsFile(fontName), height); -} -JLBFont* WResourceManager::GetJLBFont(const string &fontName){ - return jrm->GetJLBFont(graphicsFile(fontName, "", true)); -} + map::iterator itr = mFontMap.find(fontName); -JLBFont* WResourceManager::GetJLBFont(int id){ - return jrm->GetJLBFont(id); + if (itr == mFontMap.end()) + { + string path = graphicsFile(fontName); + + printf("creating font:%s\n", path.c_str()); + + int id = mFontList.size(); + mFontList.push_back(NEW JLBFont(path.c_str(), height, true)); + + mFontMap[fontName] = id; + + return id; + } + else + return itr->second; } int WResourceManager::LoadMusic(const string &musicName){ - return jrm->LoadMusic(musicFile(musicName)); -} -JMusic* WResourceManager::GetMusic(const string &musicName){ - return jrm->GetMusic(musicFile(musicName)); -} -JMusic* WResourceManager::GetMusic(int id){ - return jrm->GetMusic(id); + map::iterator itr = mMusicMap.find(musicName); + + if (itr == mMusicMap.end()) + { + string path = musicFile(musicName); + + printf("creating music:%s\n", path.c_str()); + + JMusic *music = JSoundSystem::GetInstance()->LoadMusic(path.c_str()); + if (music == NULL) + return INVALID_ID; + + int id = mMusicList.size(); + mMusicList.push_back(music); + + mMusicMap[musicName] = id; + + return id; + } + else + return itr->second; } int WResourceManager::LoadSample(const string &sampleName){ - return jrm->LoadSample(sfxFile(sampleName)); -} -JSample* WResourceManager::GetSample(const string &sampleName){ - return jrm->GetSample(sfxFile(sampleName)); -} -JSample* WResourceManager::GetSample(int id){ - return jrm->GetSample(id); -} + map::iterator itr = mSampleMap.find(sampleName); -JTexture* WResourceManager::LoadTexture(const char* filename, int mode, int textureFormat){ - return JRenderer::GetInstance()->LoadTexture(graphicsFile(filename).c_str(),mode,textureFormat); + if (itr == mSampleMap.end()) + { + string path = sfxFile(sampleName); + + printf("creating sample:%s\n", path.c_str()); + + JSample *sample = JSoundSystem::GetInstance()->LoadSample(path.c_str()); + if (sample == NULL) + return INVALID_ID; + + int id = mSampleList.size(); + mSampleList.push_back(sample); + + mSampleMap[sampleName] = id; + + return id; + } + else + return itr->second; } JMusic * WResourceManager::ssLoadMusic(const char *fileName){ @@ -239,3 +864,40 @@ JMusic * WResourceManager::ssLoadMusic(const char *fileName){ JSample * WResourceManager::ssLoadSample(const char *fileName){ return JSoundSystem::GetInstance()->LoadSample(sfxFile(fileName).c_str()); } + + +//Unmodified from JResourceManager + +int WResourceManager::CreateQuad(const string &quadName, const string &textureName, float x, float y, float width, float height){ + map::iterator itr = mQuadMap.find(quadName); + + if (itr == mQuadMap.end()) + { + JTexture *tex = GetTexture(textureName); + if (tex == NULL) + { + int texId = CreateTexture(textureName); // load texture if necessary + tex = GetTexture(texId); + } + + if (tex == NULL) // no texture, no quad... + return INVALID_ID; + + printf("creating quad:%s\n", quadName.c_str()); + + int id = mQuadList.size(); + if(width == 0.0f) + width = tex->mWidth; + if(height == 0.0f) + height = tex->mHeight; + + mQuadList.push_back(NEW JQuad(tex, x, y, width, height)); + + mQuadMap[quadName] = id; + + return id; + + } + else + return itr->second; +}