Erwan - cache fixes - Code review highly appreciated, please criticize my code!

- fix issue 65 (quads when no image  load slowly in shop/deck editor)
- Possibly fix issue 92, please let me know if it reproduces
- Fix issue 97 (Deck editor: weird behavior of deck display)
- Fix issue 39 - please verify
- Issue 56 can probably be closed as well
- Fix issue 86
This commit is contained in:
wagic.the.homebrew@gmail.com
2009-10-13 14:16:30 +00:00
parent 90a29437d2
commit 6f159fb39c
25 changed files with 231 additions and 432 deletions

View File

@@ -72,6 +72,11 @@ protected:
public: public:
#if defined (WIN32) || defined (LINUX)
#else
int PixelSize(int textureMode);
#endif
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
/// Get the singleton instance /// Get the singleton instance
/// ///
@@ -540,7 +545,6 @@ private:
int mCurrentTex; int mCurrentTex;
int mCurrentBlend; int mCurrentBlend;
int mCurrentTextureFormat; int mCurrentTextureFormat;
int PixelSize(int textureMode);
#endif #endif
bool mVsync; bool mVsync;

Binary file not shown.

View File

@@ -60,7 +60,6 @@ public:
MOMIR_MODE_UNLOCKED, MOMIR_MODE_UNLOCKED,
EVILTWIN_MODE_UNLOCKED, EVILTWIN_MODE_UNLOCKED,
RANDOMDECK_MODE_UNLOCKED, RANDOMDECK_MODE_UNLOCKED,
CACHESIZE,
//Theme metrics. These will be phased out fairly soon. //Theme metrics. These will be phased out fairly soon.
THEME_METRICS, //Start of theme metrics. THEME_METRICS, //Start of theme metrics.
LOADING_TC = THEME_METRICS, LOADING_TC = THEME_METRICS,
@@ -151,7 +150,7 @@ public:
string str; string str;
//All calls to asColor should include a fallback color for people without a theme. //All calls to asColor should include a fallback color for people without a theme.
PIXEL_TYPE asColor(PIXEL_TYPE fallback = ARGB(255,255,255,255)); PIXEL_TYPE asColor(PIXEL_TYPE fallback = ARGB(255,255,255,255));
bool isDefault(); //Returns true when number is 0 abd string is "" or "default" bool isDefault(); //Returns true when number is 0 abd string is "" or "Default"
GameOption(int value = 0); GameOption(int value = 0);
GameOption(string); GameOption(string);
GameOption(int, string); GameOption(int, string);

View File

@@ -1,7 +1,6 @@
#ifndef _LOGGER_H #ifndef _LOGGER_H
#define _LOGGER_H_ #define _LOGGER_H_
#ifdef DOLOG #ifdef DOLOG
#define LOG(x) Logger::Log(x); #define LOG(x) Logger::Log(x);
#else #else

View File

@@ -52,9 +52,8 @@ public:
~WTrackedQuad(); ~WTrackedQuad();
void Nullify(); void Nullify();
void Trash(); void Trash();
unsigned long size();
bool isGood(); bool isGood();
unsigned long size();
string resname; string resname;
JQuad * quad; JQuad * quad;
}; };
@@ -100,7 +99,8 @@ public:
void Nullify(); void Nullify();
void Trash(); void Trash();
void Refresh(string filename); void Refresh(string filename);
unsigned long size(); unsigned long size();
bool isGood(); bool isGood();
bool Attempt(string filename, int submode, int & error); bool Attempt(string filename, int submode, int & error);
bool compare(hgeParticleSystemInfo * p) {return (p == particles);}; bool compare(hgeParticleSystemInfo * p) {return (p == particles);};

View File

@@ -7,24 +7,20 @@
#include "MTGCard.h" #include "MTGCard.h"
#include "WCachedResource.h" #include "WCachedResource.h"
//Soft limits. #define HUGE_CACHE_LIMIT 6000000 // Size of the cache for Windows and Linux
#define HUGE_CACHE_LIMIT 10000000 #define SAMPLES_CACHE_SIZE 1000000 // Size in bytes of the cached samples
#define HUGE_CACHE_ITEMS 300 #define PSI_CACHE_SIZE 500000 // Size in bytes of the cahed particles
#define TEXTURES_CACHE_MINSIZE 2000000 // Minimum size of the cache on the PSP. The program should complain if the cache ever gets smaller than this
#define LARGE_CACHE_LIMIT 5000000 #define OPERATIONAL_SIZE 5000000 // Size required by Wagic for operational stuff. 3MB is not enough. The cache will usually try to take (Total Ram - Operational size)
#define LARGE_CACHE_ITEMS 200
#define SMALL_CACHE_LIMIT 3000000
#define SMALL_CACHE_ITEMS 150
//Hard Limits. //Hard Limits.
#define MAX_CACHE_OBJECTS HUGE_CACHE_ITEMS #define MAX_CACHE_OBJECTS 300
#define MAX_CACHE_ATTEMPTS 10 #define MAX_CACHE_ATTEMPTS 10
#define MAX_CACHE_MISSES 200 #define MAX_CACHE_MISSES 200
#define MAX_CACHED_SAMPLES 4 #define MAX_CACHED_SAMPLES 10
#define MAX_CACHE_GARBAGE 10 #define MAX_CACHE_GARBAGE 10
enum ENUM_WRES_INFO{ enum ENUM_WRES_INFO{
WRES_UNLOCKED = 0, //Resource is unlocked. WRES_UNLOCKED = 0, //Resource is unlocked.
WRES_MAX_LOCK = 250, //Maximum number of locks for a resource. WRES_MAX_LOCK = 250, //Maximum number of locks for a resource.
@@ -38,7 +34,6 @@ enum ENUM_RETRIEVE_STYLE{
RETRIEVE_LOCK, //As above, locks cached resource. Not for quads. RETRIEVE_LOCK, //As above, locks cached resource. Not for quads.
RETRIEVE_UNLOCK, //As above, unlocks cached resource. Not for quads. RETRIEVE_UNLOCK, //As above, unlocks cached resource. Not for quads.
RETRIEVE_RESOURCE, //Only retrieves a managed resource. Does not make a new one. RETRIEVE_RESOURCE, //Only retrieves a managed resource. Does not make a new one.
RETRIEVE_VRAM, //Retrieve it, and use vram if have to we create it. Must still remove it.
RETRIEVE_MANAGE, //Makes resource permanent. RETRIEVE_MANAGE, //Makes resource permanent.
RETRIEVE_THUMB, //Retrieve it as a thumbnail. RETRIEVE_THUMB, //Retrieve it as a thumbnail.
CACHE_THUMB = RETRIEVE_THUMB, //Backwords compatibility. CACHE_THUMB = RETRIEVE_THUMB, //Backwords compatibility.
@@ -51,10 +46,9 @@ enum ENUM_CACHE_SUBTYPE{
//Because these bits only modify how a cached resource's Attempt() is called, //Because these bits only modify how a cached resource's Attempt() is called,
//We can use them over and over for each resource type. //We can use them over and over for each resource type.
TEXTURE_SUB_CARD = (1<<2), //Retrieve using cardFile, not graphicsFile. TEXTURE_SUB_CARD = (1<<2), //Retrieve using cardFile, not graphicsFile.
TEXTURE_SUB_AVATAR = (1<<6), //Retrieve using avatarFile, not graphicsFile. TEXTURE_SUB_AVATAR = (1<<5), //Retrieve using avatarFile, not graphicsFile.
TEXTURE_SUB_THUMB = (1<<3),//Retrieve prepending "thumbnails\" to the filename. TEXTURE_SUB_THUMB = (1<<3),//Retrieve prepending "thumbnails\" to the filename.
TEXTURE_SUB_VRAM = (1<<4), //For textures. If we have to allocate, do it in VRAM. TEXTURE_SUB_5551 = (1<<4), //For textures. If we have to allocate, use RGBA5551.
TEXTURE_SUB_5551 = (1<<5), //For textures. If we have to allocate, use RGBA5551.
}; };
@@ -94,14 +88,12 @@ protected:
bool Delete(cacheItem * item); //SAFE_DELETE and garbage collect. If maxCached == 0, nullify first. (This means you have to free that cacheActual later!) bool Delete(cacheItem * item); //SAFE_DELETE and garbage collect. If maxCached == 0, nullify first. (This means you have to free that cacheActual later!)
cacheItem* Get(string id, int style = RETRIEVE_NORMAL, int submode = CACHE_NORMAL); //Subordinate to Retrieve. cacheItem* Get(string id, int style = RETRIEVE_NORMAL, int submode = CACHE_NORMAL); //Subordinate to Retrieve.
cacheItem* AttemptNew(string filename, int submode); //Attempts a new cache item, progressively clearing cache if it fails. cacheItem* AttemptNew(string filename, int submode); //Attempts a new cache item, progressively clearing cache if it fails.
cacheItem* Recycle(); //Returns a cache item from the trash.
string makeID(string filename, int submode); //Makes an ID appropriate to the submode. string makeID(string filename, int submode); //Makes an ID appropriate to the submode.
string makeFilename(string id, int submode); //Makes a filename from an ID. string makeFilename(string id, int submode); //Makes a filename from an ID.
map<string,cacheItem*> cache; map<string,cacheItem*> cache;
map<string,cacheItem*> managed; //Cache can be arbitrarily large, so managed items are seperate. map<string,cacheItem*> managed; //Cache can be arbitrarily large, so managed items are seperate.
vector<cacheItem*> garbage; //Garbage collection.
unsigned long totalSize; unsigned long totalSize;
unsigned long cacheSize; unsigned long cacheSize;
@@ -126,7 +118,7 @@ public:
WResourceManager(); WResourceManager();
~WResourceManager(); ~WResourceManager();
JQuad * RetrieveCard(MTGCard * card, int style = RETRIEVE_NORMAL, int submode = CACHE_NORMAL); //RetrieveCard is reversed to match current use. JQuad * RetrieveCard(MTGCard * card, int style = RETRIEVE_NORMAL,int submode = CACHE_NORMAL);
JSample * RetrieveSample(string filename, int style = RETRIEVE_NORMAL, int submode = CACHE_NORMAL); JSample * RetrieveSample(string filename, int style = RETRIEVE_NORMAL, int submode = CACHE_NORMAL);
JTexture * RetrieveTexture(string filename, int style = RETRIEVE_NORMAL, int submode = CACHE_NORMAL); JTexture * RetrieveTexture(string filename, int style = RETRIEVE_NORMAL, int submode = CACHE_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_LOCK, int submode = CACHE_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_LOCK, int submode = CACHE_NORMAL);
@@ -177,7 +169,7 @@ public:
//Wrapped from JSoundSystem. TODO: Privatize. //Wrapped from JSoundSystem. TODO: Privatize.
JMusic * ssLoadMusic(const char *fileName); JMusic * ssLoadMusic(const char *fileName);
void CacheForState(int state); void autoResize(); //Recreates the cache size.
void DebugRender(); void DebugRender();

View File

@@ -638,15 +638,15 @@ MTGCardInstance * AIPlayerBaka::FindCardToPlay(ManaCost * pMana, const char * ty
} }
AIPlayerBaka::AIPlayerBaka(MTGPlayerCards * deck, string file, string fileSmall, string avatarFile) : AIPlayer(deck, file, fileSmall) { AIPlayerBaka::AIPlayerBaka(MTGPlayerCards * deck, string file, string fileSmall, string avatarFile) : AIPlayer(deck, file, fileSmall) {
mAvatarTex = resources.RetrieveTexture(avatarFile,RETRIEVE_VRAM,TEXTURE_SUB_AVATAR); mAvatarTex = resources.RetrieveTexture(avatarFile,RETRIEVE_LOCK,TEXTURE_SUB_AVATAR);
if(!mAvatarTex){ if(!mAvatarTex){
avatarFile = "baka.jpg"; avatarFile = "baka.jpg";
mAvatarTex = resources.RetrieveTexture(avatarFile,RETRIEVE_VRAM,TEXTURE_SUB_AVATAR); mAvatarTex = resources.RetrieveTexture(avatarFile,RETRIEVE_LOCK,TEXTURE_SUB_AVATAR);
} }
if(mAvatarTex) if(mAvatarTex)
mAvatar = resources.RetrieveQuad(avatarFile, 0, 0, 35, 50,"bakaAvatar",RETRIEVE_VRAM,TEXTURE_SUB_AVATAR); mAvatar = resources.RetrieveQuad(avatarFile, 0, 0, 35, 50,"bakaAvatar",RETRIEVE_NORMAL,TEXTURE_SUB_AVATAR);
else else
mAvatar = NULL; mAvatar = NULL;

View File

@@ -726,11 +726,11 @@ void ActionStack::Fizzle(Interruptible * action){
} }
void ActionStack::Render(){ void ActionStack::Render(){
int x0 = 250; float x0 = 250;
int y0 = 30; float y0 = 30;
int width = 200; float width = 200;
int height = 90; float height = 90;
int currenty = y0 + 5 ; float currenty = y0 + 5 ;
if (mode == ACTIONSTACK_STANDARD){ if (mode == ACTIONSTACK_STANDARD){
if (!askIfWishesToInterrupt || !askIfWishesToInterrupt->displayStack()) return; if (!askIfWishesToInterrupt || !askIfWishesToInterrupt->displayStack()) return;

View File

@@ -81,27 +81,27 @@ void Credits::compute(Player * _p1, Player * _p2, GameApp * _app){
if (unlocked == -1){ if (unlocked == -1){
unlocked = isDifficultyUnlocked(); unlocked = isDifficultyUnlocked();
if (unlocked){ if (unlocked){
unlockedTex = resources.RetrieveTexture("unlocked.png", RETRIEVE_VRAM); unlockedTex = resources.RetrieveTexture("unlocked.png");
unlockedQuad = resources.RetrieveQuad("unlocked.png", 2, 2, 396, 96); unlockedQuad = resources.RetrieveQuad("unlocked.png", 2, 2, 396, 96);
options[Options::DIFFICULTY_MODE_UNLOCKED] = GameOption(1); options[Options::DIFFICULTY_MODE_UNLOCKED] = GameOption(1);
options.save(); options.save();
} else if ((unlocked = isMomirUnlocked())) { } else if ((unlocked = isMomirUnlocked())) {
unlockedTex = resources.RetrieveTexture("momir_unlocked.png", RETRIEVE_VRAM); unlockedTex = resources.RetrieveTexture("momir_unlocked.png");
unlockedQuad = resources.RetrieveQuad("momir_unlocked.png", 2, 2, 396, 96); unlockedQuad = resources.RetrieveQuad("momir_unlocked.png", 2, 2, 396, 96);
options[Options::MOMIR_MODE_UNLOCKED] = GameOption(1); options[Options::MOMIR_MODE_UNLOCKED] = GameOption(1);
options.save(); options.save();
} else if ((unlocked = isEvilTwinUnlocked())) { } else if ((unlocked = isEvilTwinUnlocked())) {
unlockedTex = resources.RetrieveTexture("eviltwin_unlocked.png", RETRIEVE_VRAM); unlockedTex = resources.RetrieveTexture("eviltwin_unlocked.png");
unlockedQuad = resources.RetrieveQuad("eviltwin_unlocked.png", 2, 2, 396, 96); unlockedQuad = resources.RetrieveQuad("eviltwin_unlocked.png", 2, 2, 396, 96);
options[Options::EVILTWIN_MODE_UNLOCKED] = GameOption(1); options[Options::EVILTWIN_MODE_UNLOCKED] = GameOption(1);
options.save(); options.save();
}else if((unlocked = isRandomDeckUnlocked())) { }else if((unlocked = isRandomDeckUnlocked())) {
unlockedTex = resources.RetrieveTexture("randomdeck_unlocked.png", RETRIEVE_VRAM); unlockedTex = resources.RetrieveTexture("randomdeck_unlocked.png");
unlockedQuad = resources.RetrieveQuad("randomdeck_unlocked.png", 2, 2, 396, 96); unlockedQuad = resources.RetrieveQuad("randomdeck_unlocked.png", 2, 2, 396, 96);
options[Options::RANDOMDECK_MODE_UNLOCKED] = GameOption(1); options[Options::RANDOMDECK_MODE_UNLOCKED] = GameOption(1);
options.save(); options.save();
}else if((unlocked = unlockRandomSet())) { }else if((unlocked = unlockRandomSet())) {
unlockedTex = resources.RetrieveTexture("set_unlocked.png", RETRIEVE_VRAM); unlockedTex = resources.RetrieveTexture("set_unlocked.png");
unlockedQuad = resources.RetrieveQuad("set_unlocked.png", 2, 2, 396, 96); unlockedQuad = resources.RetrieveQuad("set_unlocked.png", 2, 2, 396, 96);
options[Options::optionSet(unlocked - 1)] = GameOption(1); options[Options::optionSet(unlocked - 1)] = GameOption(1);
options.save(); options.save();

View File

@@ -250,19 +250,11 @@ void GameApp::Update()
mCurrentState->End(); mCurrentState->End();
mCurrentState = mNextState; mCurrentState = mNextState;
//Automate cache resizing.
for(int x=0;x<MAX_STATE;x++){
if(mNextState == mGameStates[x]){
resources.CacheForState(x);
break;
}
}
#if defined (WIN32) || defined (LINUX) #if defined (WIN32) || defined (LINUX)
#else #else
/* /*
int maxLinear = ramAvailableLineareMax(); int maxLinear = ramAvailableLineareMax();
int ram = ramAvailable(); int ram = ramAvailable();
char buf[512]; char buf[512];

View File

@@ -46,7 +46,6 @@ const char * Options::optionNames[] = {
"_gprx_rimom", "_gprx_rimom",
"_gprx_eviltwin", "_gprx_eviltwin",
"_gprx_rnddeck", "_gprx_rnddeck",
"_gcacheSize",
//Theme metrics //Theme metrics
"_tLoadingTC", "_tLoadingTC",
"_tStatsTC", "_tStatsTC",
@@ -333,6 +332,8 @@ int GameOptions::load(){
if(file){ if(file){
while(std::getline(file,s)){ while(std::getline(file,s)){
if (!s.size()) continue;
if (s[s.size()-1] == '\r') s.erase(s.size()-1); //Handle DOS files
int found =s.find("="); int found =s.find("=");
string name = s.substr(0,found); string name = s.substr(0,found);
string val = s.substr(found+1); string val = s.substr(found+1);

View File

@@ -123,7 +123,7 @@ void GameStateDeckViewer::Start()
} }
//Grab a texture in VRAM. //Grab a texture in VRAM.
pspIconsTexture = resources.RetrieveTexture("iconspsp.png",RETRIEVE_VRAM); pspIconsTexture = resources.RetrieveTexture("iconspsp.png");
char buf[512]; char buf[512];
for (int i=0; i < 8; i++){ for (int i=0; i < 8; i++){
@@ -201,13 +201,11 @@ void GameStateDeckViewer::addRemove(MTGCard * card){
} }
} }
stw.needUpdate = true; stw.needUpdate = true;
//loadIndexes(cardIndex[0]);
} }
int GameStateDeckViewer::Remove(MTGCard * card){ int GameStateDeckViewer::Remove(MTGCard * card){
if (!card) return 0; if (!card) return 0;
int result = displayed_deck->Remove(card); int result = displayed_deck->Remove(card);
//loadIndexes(currentCard);
return result; return result;
} }
@@ -233,7 +231,6 @@ void GameStateDeckViewer::Update(float dt)
//Prevent screen from updating. //Prevent screen from updating.
return; return;
} }
// mParent->effect->UpdateBig(dt);
hudAlpha = 255-(last_user_activity * 500); hudAlpha = 255-(last_user_activity * 500);
if (hudAlpha < 0) hudAlpha = 0; if (hudAlpha < 0) hudAlpha = 0;
if (sellMenu){ if (sellMenu){
@@ -419,9 +416,9 @@ void GameStateDeckViewer::renderOnScreenBasicInfo(){
void GameStateDeckViewer::renderSlideBar(){ void GameStateDeckViewer::renderSlideBar(){
int total = displayed_deck->getCount(colorFilter); int total = displayed_deck->getCount(colorFilter);
int filler = 15; float filler = 15;
int y = SCREEN_HEIGHT-25; float y = SCREEN_HEIGHT_F-25;
int bar_size = SCREEN_WIDTH - 2*filler; float bar_size = SCREEN_WIDTH_F - 2*filler;
JRenderer * r = JRenderer::GetInstance(); JRenderer * r = JRenderer::GetInstance();
typedef map<MTGCard *,int,Cmp1>::reverse_iterator rit; typedef map<MTGCard *,int,Cmp1>::reverse_iterator rit;
@@ -436,7 +433,7 @@ void GameStateDeckViewer::renderSlideBar(){
for (; it != end; ++it) for (; it != end; ++it)
if (it->first->hasColor(colorFilter)) currentPos += it->second; if (it->first->hasColor(colorFilter)) currentPos += it->second;
} }
int cursor_pos = bar_size * currentPos / total; float cursor_pos = bar_size * currentPos / total;
r->FillRoundRect(filler + 5,y+5,bar_size,0,3,ARGB(hudAlpha/2,0,0,0)); r->FillRoundRect(filler + 5,y+5,bar_size,0,3,ARGB(hudAlpha/2,0,0,0));
r->DrawLine(filler+cursor_pos + 5 ,y+5,filler+cursor_pos + 5,y+10,ARGB(hudAlpha/2,0,0,0)); r->DrawLine(filler+cursor_pos + 5 ,y+5,filler+cursor_pos + 5,y+10,ARGB(hudAlpha/2,0,0,0));
@@ -603,7 +600,7 @@ void GameStateDeckViewer::renderOnScreenMenu(){
font->DrawString(buffer, 10+leftTransition, 10); font->DrawString(buffer, 10+leftTransition, 10);
int nb_letters = 0; int nb_letters = 0;
int posX, posY; float posX, posY;
DWORD graphColor; DWORD graphColor;
graphColor = ARGB(200, 155, 155, 155); graphColor = ARGB(200, 155, 155, 155);

View File

@@ -144,8 +144,8 @@ void GameStateMenu::Start(){
if (options[Options::MOMIR_MODE_UNLOCKED].number) hasChosenGameType = 0; if (options[Options::MOMIR_MODE_UNLOCKED].number) hasChosenGameType = 0;
if (options[Options::RANDOMDECK_MODE_UNLOCKED].number) hasChosenGameType = 0; if (options[Options::RANDOMDECK_MODE_UNLOCKED].number) hasChosenGameType = 0;
bgTexture = resources.RetrieveTexture("menutitle.png", RETRIEVE_VRAM); bgTexture = resources.RetrieveTexture("menutitle.png", RETRIEVE_LOCK);
movingWTexture = resources.RetrieveTexture("movingW.png", RETRIEVE_VRAM); movingWTexture = resources.RetrieveTexture("movingW.png", RETRIEVE_LOCK);
mBg = resources.RetrieveQuad("menutitle.png", 0, 0, 256, 166); // Create background quad for rendering. mBg = resources.RetrieveQuad("menutitle.png", 0, 0, 256, 166); // Create background quad for rendering.
mMovingW = resources.RetrieveQuad("movingW.png", 2, 2, 84, 62); mMovingW = resources.RetrieveQuad("movingW.png", 2, 2, 84, 62);
@@ -162,20 +162,6 @@ void GameStateMenu::Start(){
SAFE_DELETE(playerdata); SAFE_DELETE(playerdata);
#if defined DEBUG_CACHE
/*resources.ClearUnlocked(); //So we can tell if we've any extra locks.
if(!resources.menuCached)
resources.menuCached = resources.CountCached();
if(resources.CountCached() != resources.menuCached){
char buf[512];
unsigned int i = resources.CountCached()-resources.menuCached;
sprintf(buf,"Warning: %u leftover locked items.",i);
resources.debugMessage = buf;
}
*/
#endif
} }
@@ -336,6 +322,8 @@ void GameStateMenu::Update(float dt)
sprintf(nbcardsStr, "Database: %i cards", mParent->collection->totalCards()); sprintf(nbcardsStr, "Database: %i cards", mParent->collection->totalCards());
SAFE_DELETE(playerdata); SAFE_DELETE(playerdata);
resetDirectory(); resetDirectory();
//All major things have been loaded, resize the cache to use it as efficiently as possible
resources.autoResize();
} }
break; break;
case MENU_STATE_MAJOR_FIRST_TIME : case MENU_STATE_MAJOR_FIRST_TIME :

View File

@@ -37,7 +37,6 @@ void GameStateOptions::Start()
optionsList->Add(NEW OptionInteger(Options::INTERRUPT_SECONDS, "Seconds to pause for an Interrupt", 20, 1)); optionsList->Add(NEW OptionInteger(Options::INTERRUPT_SECONDS, "Seconds to pause for an Interrupt", 20, 1));
optionsList->Add(NEW OptionInteger(Options::INTERRUPTMYSPELLS, "Interrupt my spells")); optionsList->Add(NEW OptionInteger(Options::INTERRUPTMYSPELLS, "Interrupt my spells"));
optionsList->Add(NEW OptionInteger(Options::INTERRUPTMYABILITIES, "Interrupt my abilities")); optionsList->Add(NEW OptionInteger(Options::INTERRUPTMYABILITIES, "Interrupt my abilities"));
optionsList->Add(NEW OptionInteger(Options::CACHESIZE, "Use large cache"));
optionsTabs = NEW OptionsMenu(); optionsTabs = NEW OptionsMenu();
optionsTabs->Add(optionsList); optionsTabs->Add(optionsList);

View File

@@ -30,7 +30,7 @@ void GameStateShop::Start()
mStage = STAGE_SHOP_SHOP; mStage = STAGE_SHOP_SHOP;
bgTexture = resources.RetrieveTexture("shop.jpg", RETRIEVE_VRAM); bgTexture = resources.RetrieveTexture("shop.jpg");
//alternateRender doesn't lock, so lock our thumbnails for hgeDistort. //alternateRender doesn't lock, so lock our thumbnails for hgeDistort.
altThumb[0] = resources.RetrieveTexture("artifact_thumb.jpg", RETRIEVE_LOCK); altThumb[0] = resources.RetrieveTexture("artifact_thumb.jpg", RETRIEVE_LOCK);

View File

@@ -96,4 +96,5 @@ void GuiAvatars::Render()
r->FillRect(self->actX - w * self->actZ, self->actY - h * self->actZ, w * self->actZ , h * self->actZ, ARGB(200,0,0,0)); r->FillRect(self->actX - w * self->actZ, self->actY - h * self->actZ, w * self->actZ , h * self->actZ, ARGB(200,0,0,0));
} }
GuiLayer::Render(); GuiLayer::Render();
} }

View File

@@ -28,8 +28,10 @@ GuiCombat::GuiCombat(GameObserver* go) : GuiLayer(), go(go), active(false), acti
GuiCombat::~GuiCombat() GuiCombat::~GuiCombat()
{ {
if(ok_tex) if(ok_tex){
resources.Release(ok_tex); resources.Release(ok_tex);
ok_tex = NULL;
}
for (inner_iterator it = attackers.begin(); it != attackers.end(); ++it) for (inner_iterator it = attackers.begin(); it != attackers.end(); ++it)
{ {

View File

@@ -46,7 +46,7 @@ void GuiPhaseBar::Update(float dt)
void GuiPhaseBar::Render() void GuiPhaseBar::Render()
{ {
static const float ICONSCALE = 1.5; static const float ICONSCALE = 1.5;
static const unsigned CENTER = SCREEN_HEIGHT / 2 + 10; static const float CENTER = SCREEN_HEIGHT_F / 2 + 10;
JRenderer* renderer = JRenderer::GetInstance(); JRenderer* renderer = JRenderer::GetInstance();
GameObserver * g = GameObserver::GetInstance(); GameObserver * g = GameObserver::GetInstance();
unsigned p = (phase->id + Phases - 4) * (Width+1); unsigned p = (phase->id + Phases - 4) * (Width+1);

View File

@@ -42,7 +42,6 @@ void GuiPlay::VertStack::reset(unsigned total, float x, float y)
{ {
GuiPlay::CardStack::reset(total, x - CARD_WIDTH, y); GuiPlay::CardStack::reset(total, x - CARD_WIDTH, y);
count = 0; count = 0;
cout << "reset" << endl;
} }
void GuiPlay::HorzStack::Render(CardView* card, iterator begin, iterator end) void GuiPlay::HorzStack::Render(CardView* card, iterator begin, iterator end)

View File

@@ -4,6 +4,7 @@
#include "../include/GameOptions.h" #include "../include/GameOptions.h"
#include "../include/WEvent.h" #include "../include/WEvent.h"
#include "../include/MTGDeck.h" #include "../include/MTGDeck.h"
#include <assert.h>
#if defined (WIN32) || defined (LINUX) #if defined (WIN32) || defined (LINUX)
#include <time.h> #include <time.h>
@@ -192,6 +193,7 @@ void MTGGameZone::setOwner(Player * player){
} }
MTGCardInstance * MTGGameZone::removeCard(MTGCardInstance * card, int createCopy){ MTGCardInstance * MTGGameZone::removeCard(MTGCardInstance * card, int createCopy){
assert(nb_cards < 10000);
int i; int i;
cardsMap.erase(card); cardsMap.erase(card);
for (i=0; i<(nb_cards); i++) { for (i=0; i<(nb_cards); i++) {

View File

@@ -35,7 +35,7 @@ void PlayGuiObject::Update(float dt){
if (mHeight < defaultHeight) if (mHeight < defaultHeight)
mHeight = defaultHeight; mHeight = defaultHeight;
} }
wave = (wave +2) % 255; wave = (wave +2 * (int) (100 * dt) ) % 255;
for (vector<Effect*>::iterator it = effects.begin(); it != effects.end(); ++it) for (vector<Effect*>::iterator it = effects.begin(); it != effects.end(); ++it)
(*it)->Update(dt); (*it)->Update(dt);
Pos::Update(dt); Pos::Update(dt);

View File

@@ -24,7 +24,6 @@ void Player::End(){
Player::~Player(){ Player::~Player(){
SAFE_DELETE(manaPool); SAFE_DELETE(manaPool);
resources.Release(mAvatar);
resources.Release(mAvatarTex); resources.Release(mAvatarTex);
mAvatar = NULL; mAvatar = NULL;
mAvatarTex = NULL; mAvatarTex = NULL;
@@ -59,9 +58,9 @@ Player * Player::opponent(){
} }
HumanPlayer::HumanPlayer(MTGPlayerCards * deck, string file, string fileSmall) : Player(deck, file, fileSmall) { HumanPlayer::HumanPlayer(MTGPlayerCards * deck, string file, string fileSmall) : Player(deck, file, fileSmall) {
mAvatarTex = resources.RetrieveTexture("avatar.jpg",RETRIEVE_VRAM,TEXTURE_SUB_AVATAR); mAvatarTex = resources.RetrieveTexture("avatar.jpg",RETRIEVE_LOCK,TEXTURE_SUB_AVATAR);
if (mAvatarTex) if (mAvatarTex)
mAvatar = resources.RetrieveQuad("avatar.jpg",0,0,35,50,"playerAvatar",RETRIEVE_VRAM,TEXTURE_SUB_AVATAR); mAvatar = resources.RetrieveQuad("avatar.jpg",0,0,35,50,"playerAvatar",RETRIEVE_NORMAL,TEXTURE_SUB_AVATAR);
else else
mAvatar = NULL; mAvatar = NULL;
} }

View File

@@ -139,30 +139,11 @@ void ShopItem::Render(){
} }
JRenderer * renderer = JRenderer::GetInstance(); JRenderer * renderer = JRenderer::GetInstance();
//float x0 = mX;
//float y0 = mY - (mScale > 1 ? 4 : 0);
/* if (GetId()%2){
float xs[] = {mX, mX, mX+230,mX+230};
float ys[] = {mY-5+17,mY-5+19,mY-5+35,mY-5} ;
renderer->FillPolygon(xs,ys,4,ARGB(200,0,0,0));
x0 = mX + 230 -30;
mFont->DrawString(mText.c_str(), x0, mY + 8,JGETEXT_RIGHT);
}else{
float xs[] = {mX-5, mX-5, mX-5+230,mX-5+230,};
float ys[] = {mY-5,mY-5+35,mY-5+17,mY-5+19} ;
renderer->FillPolygon(xs,ys,4,ARGB(128,0,0,0));
mFont->DrawString(mText.c_str(), mX + 30, mY + 8);
}*/
//renderer->FillRect(mX-5, mY-5,230,35, );
if (mesh){ if (mesh){
mesh->Render(0,0); mesh->Render(0,0);
//renderer->RenderQuad(thumb,x0,y0,0,mScale * 0.45,mScale * 0.45);
}else{ }else{
//NOTHING //ERROR Management
} }
if (mHasFocus){ if (mHasFocus){
if (card) quad = resources.RetrieveCard(card); if (card) quad = resources.RetrieveCard(card);

View File

@@ -128,15 +128,13 @@ bool WCachedTexture::ReleaseQuad(JQuad* quad){
} }
WTrackedQuad * WCachedTexture::GetTrackedQuad(float offX, float offY, float width, float height,string resname){ WTrackedQuad * WCachedTexture::GetTrackedQuad(float offX, float offY, float width, float height,string resname){
if(texture == NULL) if(!texture) return NULL;
return NULL;
bool allocated = false; bool allocated = false;
WTrackedQuad * tq = NULL; WTrackedQuad * tq = NULL;
JQuad * quad = NULL; JQuad * quad = NULL;
vector<WTrackedQuad*>::iterator it; vector<WTrackedQuad*>::iterator it;
std::transform(resname.begin(),resname.end(),resname.begin(),::tolower);
if(width == 0.0f || width > texture->mWidth) if(width == 0.0f || width > texture->mWidth)
width = texture->mWidth; width = texture->mWidth;
@@ -150,24 +148,15 @@ WTrackedQuad * WCachedTexture::GetTrackedQuad(float offX, float offY, float widt
} }
} }
if(tq == NULL){ if(!tq){
allocated = true; allocated = true;
vector<WTrackedQuad*>::iterator gtq = WCachedTexture::garbageTQs.begin(); tq = NEW WTrackedQuad(resname);
if(gtq != WCachedTexture::garbageTQs.end()) if(!tq) return NULL;
{
tq = *gtq;
garbageTQs.erase(gtq);
}
else
tq = NEW WTrackedQuad(resname);
} }
if(tq == NULL)
return NULL;
quad = tq->quad; quad = tq->quad;
if(quad == NULL){ if(!quad){
quad = NEW JQuad(texture,offX,offY,width,height); quad = NEW JQuad(texture,offX,offY,width,height);
if(!quad) { if(!quad) {
//Probably out of memory. Try again. //Probably out of memory. Try again.
@@ -178,20 +167,19 @@ WTrackedQuad * WCachedTexture::GetTrackedQuad(float offX, float offY, float widt
if(!quad){ if(!quad){
if(allocated && tq) if(allocated && tq)
SAFE_DELETE(tq); SAFE_DELETE(tq);
fprintf(stderr, "WCACHEDRESOURCE:GetTrackedQuad - Quad is null\n");
return NULL; //Probably a crash. return NULL; //Probably a crash.
} }
tq->quad = quad; tq->quad = quad;
trackedQuads.push_back(tq); if (allocated) trackedQuads.push_back(tq);
return tq;
}
else{
//Update JQ's values to what we called this with.
quad->SetTextureRect(offX,offY,width,height);
return tq; return tq;
} }
return NULL; //Update JQ's values to what we called this with.
quad->SetTextureRect(offX,offY,width,height);
return tq;
} }
JQuad * WCachedTexture::GetQuad(float offX, float offY, float width, float height,string resname){ JQuad * WCachedTexture::GetQuad(float offX, float offY, float width, float height,string resname){
@@ -206,7 +194,6 @@ JQuad * WCachedTexture::GetQuad(float offX, float offY, float width, float heigh
JQuad * WCachedTexture::GetQuad(string resname){ JQuad * WCachedTexture::GetQuad(string resname){
vector<WTrackedQuad*>::iterator it; vector<WTrackedQuad*>::iterator it;
std::transform(resname.begin(),resname.end(),resname.begin(),::tolower);
for(it = trackedQuads.begin();it!=trackedQuads.end();it++){ for(it = trackedQuads.begin();it!=trackedQuads.end();it++){
if((*it) && (*it)->resname == resname){ if((*it) && (*it)->resname == resname){
@@ -225,17 +212,20 @@ JQuad * WCachedTexture::GetCard(float offX, float offY, float width, float heigh
} }
unsigned long WCachedTexture::size(){ unsigned long WCachedTexture::size(){
if(!texture) if(!texture) return 0;
return 0;
return texture->mTexHeight*texture->mTexWidth; unsigned int pixel_size = 4;
#if defined WIN32 || defined LINUX
#else
pixel_size = JRenderer::GetInstance()->PixelSize(texture->mTextureFormat);
#endif
return texture->mTexHeight*texture->mTexWidth*pixel_size;
} }
bool WCachedTexture::isGood(){ bool WCachedTexture::isGood(){
if(!texture) return (texture != NULL);
return false;
return true;
} }
void WCachedTexture::Refresh(string filename){ void WCachedTexture::Refresh(string filename){
int error = 0; int error = 0;
JTexture* old = texture; JTexture* old = texture;
@@ -287,12 +277,8 @@ bool WCachedTexture::Attempt(string filename, int submode, int & error){
if(submode & TEXTURE_SUB_5551) if(submode & TEXTURE_SUB_5551)
format = GU_PSM_5551; format = GU_PSM_5551;
//Use Vram?
if(submode & TEXTURE_SUB_VRAM){ texture = JRenderer::GetInstance()->LoadTexture(realname.c_str(),TEX_TYPE_USE_VRAM,format);
texture = JRenderer::GetInstance()->LoadTexture(realname.c_str(),TEX_TYPE_USE_VRAM,format);
}
else
texture = JRenderer::GetInstance()->LoadTexture(realname.c_str(),TEX_TYPE_NORMAL,format);
//Failure. //Failure.
if(!texture){ if(!texture){

View File

@@ -9,6 +9,7 @@
#include <JFileSystem.h> #include <JFileSystem.h>
#include "../include/WResourceManager.h" #include "../include/WResourceManager.h"
WResourceManager resources; WResourceManager resources;
unsigned int vTime = 0; unsigned int vTime = 0;
int WResourceManager::RetrieveError(){ int WResourceManager::RetrieveError(){
@@ -36,12 +37,8 @@ void WResourceManager::DebugRender(){
font->SetScale(DEFAULT_MAIN_FONT_SCALE); font->SetScale(DEFAULT_MAIN_FONT_SCALE);
renderer->FillRect(0,0,SCREEN_WIDTH,20,ARGB(128,155,0,0)); renderer->FillRect(0,0,SCREEN_WIDTH,20,ARGB(128,155,0,0));
#ifdef DEBUG_CACHE
if(debugMessage.size()) renderer->FillRect(0,SCREEN_HEIGHT-20,SCREEN_WIDTH,40,ARGB(128,155,0,0));
renderer->FillRect(0,SCREEN_HEIGHT-30,SCREEN_WIDTH,40,ARGB(128,155,0,0));
else
#endif
renderer->FillRect(0,SCREEN_HEIGHT-20,SCREEN_WIDTH,40,ARGB(128,155,0,0));
char buf[512]; char buf[512];
@@ -167,9 +164,9 @@ WResourceManager::WResourceManager(){
mFontList.reserve(4); mFontList.reserve(4);
mFontMap.clear(); mFontMap.clear();
psiWCache.Resize(SMALL_CACHE_LIMIT,6); //Plenty of room for mana symbols, or whatever. psiWCache.Resize(PSI_CACHE_SIZE,20);
sampleWCache.Resize(SMALL_CACHE_LIMIT,MAX_CACHED_SAMPLES); sampleWCache.Resize(SAMPLES_CACHE_SIZE,MAX_CACHED_SAMPLES);
textureWCache.Resize(LARGE_CACHE_LIMIT,MAX_CACHE_OBJECTS); textureWCache.Resize(TEXTURES_CACHE_MINSIZE,MAX_CACHE_OBJECTS);
lastTime = 0; lastTime = 0;
lastError = CACHE_ERROR_NONE; lastError = CACHE_ERROR_NONE;
} }
@@ -192,32 +189,33 @@ WResourceManager::~WResourceManager(){
LOG("==Successfully Destroyed WResourceManager=="); LOG("==Successfully Destroyed WResourceManager==");
} }
JQuad * WResourceManager::RetrieveCard(MTGCard * card, int style, int submode){ JQuad * WResourceManager::RetrieveCard(MTGCard * card, int style, int submode){
//Cards are never, ever resource managed, so just check cache. //Cards are never, ever resource managed, so just check cache.
if(!card || options[Options::DISABLECARDS].number) if(!card || options[Options::DISABLECARDS].number)
return NULL; return NULL;
submode = submode | TEXTURE_SUB_CARD;
string filename = card->getSetName();
filename += "/";
filename += card->getImageName();
JQuad * jq = RetrieveQuad(filename,0,0,0,0,"",style,submode|TEXTURE_SUB_5551);
lastError = textureWCache.mError;
if(jq){
jq->SetHotSpot(jq->mTex->mWidth / 2, jq->mTex->mHeight / 2);
return jq;
}
return NULL;
}
submode = submode | TEXTURE_SUB_CARD;
string filename = card->getSetName();
filename += "/";
filename += card->getImageName();
JQuad * jq = RetrieveQuad(filename,0,0,0,0,"",style,submode|TEXTURE_SUB_5551);
lastError = textureWCache.mError;
if(jq){
jq->SetHotSpot(jq->mTex->mWidth / 2, jq->mTex->mHeight / 2);
return jq;
}
return NULL;
}
int WResourceManager::CreateQuad(const string &quadName, const string &textureName, float x, float y, float width, float height){ int WResourceManager::CreateQuad(const string &quadName, const string &textureName, float x, float y, float width, float height){
if(!quadName.size() || !textureName.size()) if(!quadName.size() || !textureName.size())
return INVALID_ID; return INVALID_ID;
string resname = quadName; string resname = quadName;
std::transform(resname.begin(),resname.end(),resname.begin(),::tolower);
vector<WManagedQuad*>::iterator it; vector<WManagedQuad*>::iterator it;
int pos = 0; int pos = 0;
@@ -253,7 +251,6 @@ int WResourceManager::CreateQuad(const string &quadName, const string &textureNa
JQuad * WResourceManager::GetQuad(const string &quadName){ JQuad * WResourceManager::GetQuad(const string &quadName){
string lookup = quadName; string lookup = quadName;
std::transform(lookup.begin(),lookup.end(),lookup.begin(),::tolower);
for(vector<WManagedQuad*>::iterator it=managedQuads.begin();it!=managedQuads.end();it++){ for(vector<WManagedQuad*>::iterator it=managedQuads.begin();it!=managedQuads.end();it++){
if((*it)->resname == lookup) if((*it)->resname == lookup)
@@ -289,11 +286,7 @@ JQuad * WResourceManager::RetrieveQuad(string filename, float offX, float offY,
} }
//Aliases. //Aliases.
if(style == RETRIEVE_VRAM){ if(style == RETRIEVE_THUMB){
submode = submode | TEXTURE_SUB_VRAM;
style = RETRIEVE_LOCK;
}
else if(style == RETRIEVE_THUMB){
submode = submode | TEXTURE_SUB_THUMB; submode = submode | TEXTURE_SUB_THUMB;
style = RETRIEVE_NORMAL; style = RETRIEVE_NORMAL;
} }
@@ -319,8 +312,7 @@ JQuad * WResourceManager::RetrieveQuad(string filename, float offX, float offY,
if(jtex){ if(jtex){
WTrackedQuad * tq = jtex->GetTrackedQuad(offX,offY,width,height,resname); WTrackedQuad * tq = jtex->GetTrackedQuad(offX,offY,width,height,resname);
if(tq == NULL) if(!tq) return NULL;
return NULL;
if(style == RETRIEVE_MANAGE && resname != ""){ if(style == RETRIEVE_MANAGE && resname != ""){
WManagedQuad * mq = NEW WManagedQuad(); WManagedQuad * mq = NEW WManagedQuad();
@@ -398,11 +390,7 @@ JTexture * WResourceManager::RetrieveTexture(string filename, int style, int sub
WCachedTexture * res = NULL; WCachedTexture * res = NULL;
//Aliases. //Aliases.
if(style == RETRIEVE_VRAM){ if(style == RETRIEVE_THUMB){
submode = submode | TEXTURE_SUB_VRAM;
style = RETRIEVE_LOCK;
}
else if(style == RETRIEVE_THUMB){
submode = submode | TEXTURE_SUB_THUMB; submode = submode | TEXTURE_SUB_THUMB;
style = RETRIEVE_NORMAL; style = RETRIEVE_NORMAL;
} }
@@ -521,9 +509,8 @@ string WResourceManager::graphicsFile(const string filename, const string specif
//Check the theme folder. //Check the theme folder.
string theme = options[Options::ACTIVE_THEME].str; string theme = options[Options::ACTIVE_THEME].str;
std::transform(theme.begin(), theme.end(), theme.begin(), ::tolower);
if(theme != "" && theme != "default"){ if(theme != "" && theme != "Default"){
sprintf(buf,"themes/%s/%s",theme.c_str(),filename.c_str()); sprintf(buf,"themes/%s/%s",theme.c_str(),filename.c_str());
if(fileOK(buf,true)) if(fileOK(buf,true))
return buf; return buf;
@@ -531,9 +518,8 @@ string WResourceManager::graphicsFile(const string filename, const string specif
//Failure. Check mode graphics //Failure. Check mode graphics
string mode = options[Options::ACTIVE_MODE].str; string mode = options[Options::ACTIVE_MODE].str;
std::transform(mode.begin(), mode.end(), mode.begin(), ::tolower);
if(mode != "" && mode != "defualt"){ if(mode != "" && mode != "Default"){
sprintf(buf,"modes/%s/graphics/%s",mode.c_str(),filename.c_str()); sprintf(buf,"modes/%s/graphics/%s",mode.c_str(),filename.c_str());
if(fileOK(buf,true)) if(fileOK(buf,true))
return buf; return buf;
@@ -567,8 +553,8 @@ string WResourceManager::avatarFile(const string filename, const string specific
//Check the profile folder. //Check the profile folder.
string profile = options[Options::ACTIVE_PROFILE].str; string profile = options[Options::ACTIVE_PROFILE].str;
std::transform(profile.begin(), profile.end(), profile.begin(), ::tolower);
if(profile != "" && profile != "default"){ if(profile != "" && profile != "Default"){
sprintf(buf,"profiles/%s/%s",profile.c_str(),filename.c_str()); sprintf(buf,"profiles/%s/%s",profile.c_str(),filename.c_str());
if(fileOK(buf,true)) if(fileOK(buf,true))
return buf; return buf;
@@ -580,9 +566,8 @@ string WResourceManager::avatarFile(const string filename, const string specific
//Check the theme folder. //Check the theme folder.
string theme = options[Options::ACTIVE_THEME].str; string theme = options[Options::ACTIVE_THEME].str;
std::transform(theme.begin(), theme.end(), theme.begin(), ::tolower);
if(theme != "" && theme != "default"){ if(theme != "" && theme != "Default"){
sprintf(buf,"themes/%s/%s",theme.c_str(),filename.c_str()); sprintf(buf,"themes/%s/%s",theme.c_str(),filename.c_str());
if(fileOK(buf,true)) if(fileOK(buf,true))
return buf; return buf;
@@ -590,9 +575,8 @@ string WResourceManager::avatarFile(const string filename, const string specific
//Failure. Check mode graphics //Failure. Check mode graphics
string mode = options[Options::ACTIVE_MODE].str; string mode = options[Options::ACTIVE_MODE].str;
std::transform(mode.begin(), mode.end(), mode.begin(), ::tolower);
if(mode != "" && mode != "defualt"){ if(mode != "" && mode != "Default"){
sprintf(buf,"modes/%s/graphics/%s",mode.c_str(),filename.c_str()); sprintf(buf,"modes/%s/graphics/%s",mode.c_str(),filename.c_str());
if(fileOK(buf,true)) if(fileOK(buf,true))
return buf; return buf;
@@ -615,9 +599,12 @@ string WResourceManager::avatarFile(const string filename, const string specific
string WResourceManager::cardFile(const string filename, const string specific){ string WResourceManager::cardFile(const string filename, const string specific){
JFileSystem* fs = JFileSystem::GetInstance(); JFileSystem* fs = JFileSystem::GetInstance();
//PUT Back the following when we have an actual usage for it (theme, or whatever)
//Right now I'm removing this for performance
/*
char buf[512]; char buf[512];
//Check the specific location, if any. //Check the specific location, if any.
if(specific != ""){ if(specific != ""){
sprintf(buf,"%s/sets/%s",specific.c_str(),filename.c_str()); sprintf(buf,"%s/sets/%s",specific.c_str(),filename.c_str());
@@ -627,9 +614,8 @@ string WResourceManager::cardFile(const string filename, const string specific){
//Check the theme folder. //Check the theme folder.
string theme = options[Options::ACTIVE_THEME].str; string theme = options[Options::ACTIVE_THEME].str;
std::transform(theme.begin(), theme.end(), theme.begin(), ::tolower);
if(theme != "" && theme != "default"){ if(theme != "" && theme != "Default"){
sprintf(buf,"themes/%s/sets/%s",theme.c_str(),filename.c_str()); sprintf(buf,"themes/%s/sets/%s",theme.c_str(),filename.c_str());
if(fileOK(buf,true)) if(fileOK(buf,true))
return buf; return buf;
@@ -637,14 +623,14 @@ string WResourceManager::cardFile(const string filename, const string specific){
//Failure. Check mode //Failure. Check mode
string mode = options[Options::ACTIVE_MODE].str; string mode = options[Options::ACTIVE_MODE].str;
std::transform(mode.begin(), mode.end(), mode.begin(), ::tolower);
if(mode != "" && mode != "defualt"){ if(mode != "" && mode != "Default"){
sprintf(buf,"modes/%s/sets/%s",mode.c_str(),filename.c_str()); sprintf(buf,"modes/%s/sets/%s",mode.c_str(),filename.c_str());
if(fileOK(buf,true)) if(fileOK(buf,true))
return buf; return buf;
} }
*/
//Failure. Check sets //Failure. Check sets
char defdir[512]; char defdir[512];
sprintf(defdir,"sets/%s",filename.c_str()); sprintf(defdir,"sets/%s",filename.c_str());
@@ -687,9 +673,8 @@ string WResourceManager::musicFile(const string filename, const string specific)
//Check the theme folder. //Check the theme folder.
string theme = options[Options::ACTIVE_THEME].str; string theme = options[Options::ACTIVE_THEME].str;
std::transform(theme.begin(), theme.end(), theme.begin(), ::tolower);
if(theme != "" && theme != "default"){ if(theme != "" && theme != "Default"){
sprintf(buf,"themes/%s/sound/%s",theme.c_str(),filename.c_str()); sprintf(buf,"themes/%s/sound/%s",theme.c_str(),filename.c_str());
if(fileOK(buf,true)) if(fileOK(buf,true))
return buf; return buf;
@@ -697,9 +682,8 @@ string WResourceManager::musicFile(const string filename, const string specific)
//Failure. Check mode //Failure. Check mode
string mode = options[Options::ACTIVE_MODE].str; string mode = options[Options::ACTIVE_MODE].str;
std::transform(mode.begin(), mode.end(), mode.begin(), ::tolower);
if(mode != "" && mode != "defualt"){ if(mode != "" && mode != "Default"){
sprintf(buf,"modes/%s/sound/%s",mode.c_str(),filename.c_str()); sprintf(buf,"modes/%s/sound/%s",mode.c_str(),filename.c_str());
if(fileOK(buf,true)) if(fileOK(buf,true))
return buf; return buf;
@@ -727,9 +711,8 @@ string WResourceManager::sfxFile(const string filename, const string specific){
//Check the theme folder. //Check the theme folder.
string theme = options[Options::ACTIVE_THEME].str; string theme = options[Options::ACTIVE_THEME].str;
std::transform(theme.begin(), theme.end(), theme.begin(), ::tolower);
if(theme != "" && theme != "default"){ if(theme != "" && theme != "Default"){
sprintf(buf,"themes/%s/sound/sfx/%s",theme.c_str(),filename.c_str()); sprintf(buf,"themes/%s/sound/sfx/%s",theme.c_str(),filename.c_str());
if(fileOK(buf,true)) if(fileOK(buf,true))
return buf; return buf;
@@ -737,8 +720,7 @@ string WResourceManager::sfxFile(const string filename, const string specific){
//Failure. Check mode //Failure. Check mode
string mode = options[Options::ACTIVE_MODE].str; string mode = options[Options::ACTIVE_MODE].str;
std::transform(mode.begin(), mode.end(), mode.begin(), ::tolower); if(mode != "" && mode != "Default"){
if(mode != "" && mode != "defualt"){
sprintf(buf,"modes/%s/sound/sfx/%s",mode.c_str(),filename.c_str()); sprintf(buf,"modes/%s/sound/sfx/%s",mode.c_str(),filename.c_str());
if(fileOK(buf,true)) if(fileOK(buf,true))
return buf; return buf;
@@ -793,40 +775,20 @@ int WResourceManager::LoadJLBFont(const string &fontName, int height){
else else
return itr->second; return itr->second;
} }
void WResourceManager::CacheForState(int state){
#if (defined WIN32 || defined LINUX) && !defined DEBUG_CACHE
textureWCache.Resize(HUGE_CACHE_LIMIT,HUGE_CACHE_ITEMS);
return;
#else
switch(state){
//Default is not to change cache sizes.
case GAME_STATE_MENU:
case GAME_STATE_OPTIONS:
break;
//Duels use a smaller cache, so there's more room for game stuff.
case GAME_STATE_DUEL:
if (options[Options::CACHESIZE].number)
textureWCache.Resize(LARGE_CACHE_LIMIT,LARGE_CACHE_ITEMS);
else
textureWCache.Resize(SMALL_CACHE_LIMIT,SMALL_CACHE_ITEMS);
sampleWCache.Resize(SMALL_CACHE_LIMIT,MAX_CACHED_SAMPLES);
break;
//Deck editor and shop are entirely cache safe, so give it near infinite resources.
case GAME_STATE_SHOP:
case GAME_STATE_DECK_VIEWER:
textureWCache.Resize(HUGE_CACHE_LIMIT,HUGE_CACHE_ITEMS);
break;
//Anything unknown, use large cache.
default:
textureWCache.Resize(LARGE_CACHE_LIMIT,LARGE_CACHE_ITEMS);
break;
}
//Switching game states clears the cache on PSP.
ClearUnlocked();
void WResourceManager::autoResize(){
#if defined WIN32 || defined LINUX
textureWCache.Resize(HUGE_CACHE_LIMIT,MAX_CACHE_OBJECTS);
#else
unsigned int ram = ramAvailable();
unsigned int myNewSize = ram - OPERATIONAL_SIZE + textureWCache.totalSize;
if (myNewSize < TEXTURES_CACHE_MINSIZE){
fprintf(stderr, "Error, Not enough RAM for Cache: %i - total Ram: %i\n", myNewSize, ram);
}
textureWCache.Resize(myNewSize,MAX_CACHE_OBJECTS);
#endif #endif
return;
} }
JMusic * WResourceManager::ssLoadMusic(const char *fileName){ JMusic * WResourceManager::ssLoadMusic(const char *fileName){
@@ -993,17 +955,6 @@ void WCache<cacheItem, cacheActual>::Resize(unsigned long size, int items){
maxCached = items; maxCached = items;
} }
template <class cacheItem, class cacheActual>
cacheItem* WCache<cacheItem, cacheActual>::Recycle(){
typename vector<cacheItem*>::iterator it = garbage.begin();
if(it == garbage.end())
return NULL;
cacheItem * item = (*it);
garbage.erase(it);
return item;
}
template <class cacheItem, class cacheActual> template <class cacheItem, class cacheActual>
cacheItem* WCache<cacheItem, cacheActual>::AttemptNew(string filename, int submode){ cacheItem* WCache<cacheItem, cacheActual>::AttemptNew(string filename, int submode){
@@ -1012,70 +963,49 @@ cacheItem* WCache<cacheItem, cacheActual>::AttemptNew(string filename, int submo
return NULL; return NULL;
} }
cacheItem* item = NULL; cacheItem* item = NEW cacheItem;
if(!item) {
item = Recycle(); //Try a few times to get an item.
for(int attempt=0;attempt<MAX_CACHE_ATTEMPTS;attempt++){
//There was nothing to recycle. Make absolutely certain we have an item. if(!RemoveOldest() || item)
if(item == NULL){ break;
item = NEW cacheItem; item = NEW cacheItem;
if(item) }
mError = CACHE_ERROR_NONE; //We /really/ shouldn't get this far.
else{ if(!item){
//Try a few times to get an item. resources.ClearUnlocked();
for(int attempt=0;attempt<MAX_CACHE_ATTEMPTS;attempt++){ item = NEW cacheItem;
if(!RemoveOldest() || item)
break;
item = NEW cacheItem;
}
//We /really/ shouldn't get this far.
if(!item){ if(!item){
resources.ClearUnlocked(); //Nothing let us make an item. Failure.
item = NEW cacheItem; mError = CACHE_ERROR_BAD_ALLOC;
if(!item){ return NULL;
//Nothing let us make an item. Failure.
mError = CACHE_ERROR_BAD_ALLOC;
return NULL;
}
} }
} }
} }
//Attempt to populate item.
mError = CACHE_ERROR_NONE; mError = CACHE_ERROR_NONE;
for(int attempts = 0; attempts < MAX_CACHE_ATTEMPTS;attempts++) for(int attempts = 0; attempts < MAX_CACHE_ATTEMPTS;attempts++)
{ {
//We use try/catch so any memory alloc'd in Attempt isn't lost. //We use try/catch so any memory alloc'd in Attempt isn't lost.
try{ try{
//If we don't get a good item, remove oldest cache and continue trying. //If we don't get a good item, remove oldest cache and continue trying.
if(!item->Attempt(filename,submode,mError) || !item->isGood()) if(!item->Attempt(filename,submode,mError) || !item->isGood()) {
//No such file. Fail on first try.
if(mError == CACHE_ERROR_404){
SAFE_DELETE(item);
return NULL;
}
throw std::bad_alloc(); throw std::bad_alloc();
}
} }
catch(std::bad_alloc){ catch(std::bad_alloc){
RemoveOldest(); RemoveOldest();
} }
//No such file. Fail on first try. //Succeeded
if(item && mError == CACHE_ERROR_404){ if(item->isGood())
if(garbage.size() < MAX_CACHE_GARBAGE){ break;
item->Trash();
garbage.push_back(item);
}
else
SAFE_DELETE(item);
return NULL;
}
//Succeeded, so enforce limits and return.
if(item->isGood()){
mError = CACHE_ERROR_NONE;
item->lock();
Cleanup();
item->unlock();
return item;
}
} }
//Still no result, so clear local cache, then try again. //Still no result, so clear local cache, then try again.
@@ -1089,23 +1019,18 @@ cacheItem* WCache<cacheItem, cacheActual>::AttemptNew(string filename, int submo
//Failed, so clear every cache we've got in prep for the next try. //Failed, so clear every cache we've got in prep for the next try.
resources.ClearUnlocked(); resources.ClearUnlocked();
} }
if(!item->isGood()){
try{ try{
if(!item->Attempt(filename,submode,mError) || !item->isGood()) if(!item->Attempt(filename,submode,mError) || !item->isGood())
throw std::bad_alloc(); throw std::bad_alloc();
} }
catch(std::bad_alloc){ catch(std::bad_alloc){
//Complete failure. Trash this object and return NULL. //Complete failure. Trash this object and return NULL.
if(item && !item->isGood()){ if(!item->isGood()){
if(garbage.size() < MAX_CACHE_GARBAGE){
item->Trash();
garbage.push_back(item);
}
else
SAFE_DELETE(item); SAFE_DELETE(item);
mError = CACHE_ERROR_BAD;
mError = CACHE_ERROR_BAD; return NULL;
return NULL; }
} }
} }
} }
@@ -1136,15 +1061,19 @@ cacheItem * WCache<cacheItem, cacheActual>::Retrieve(string filename, int style,
//Perform lock or unlock on entry. //Perform lock or unlock on entry.
if(tc){ if(tc){
if(style == RETRIEVE_LOCK) tc->lock(); switch(style){
else if(style == RETRIEVE_UNLOCK) tc->unlock(); case RETRIEVE_LOCK: tc->lock(); break;
else if(style == RETRIEVE_MANAGE && !tc->isPermanent()) { case RETRIEVE_UNLOCK: tc->unlock(); break;
//Unlink the managed resource from the cache. case RETRIEVE_MANAGE:
UnlinkCache(tc); if (!tc->isPermanent()) {
//Unlink the managed resource from the cache.
//Post it in managed resources. UnlinkCache(tc);
managed[makeID(filename,submode)] = tc;
tc->deadbolt(); //Post it in managed resources.
managed[makeID(filename,submode)] = tc;
tc->deadbolt();
}
break;
} }
} }
@@ -1154,10 +1083,8 @@ cacheItem * WCache<cacheItem, cacheActual>::Retrieve(string filename, int style,
tc->hit(); tc->hit();
return tc; //Everything fine. return tc; //Everything fine.
} }
else{ //Something went wrong.
//Something went wrong. RemoveItem(tc);
RemoveItem(tc);
}
} }
//Record managed failure. Cache failure is recorded in Get(). //Record managed failure. Cache failure is recorded in Get().
@@ -1196,113 +1123,62 @@ cacheItem * WCache<cacheItem, cacheActual>::Get(string id, int style, int submod
//Something is managed. //Something is managed.
if(it != managed.end()) { if(it != managed.end()) {
if(!it->second && style == RETRIEVE_RESOURCE) return it->second; //A hit.
return NULL; //A miss.
else
return it->second; //A hit.
} }
//Failed to find managed resource and won't create one. Record a miss. //Failed to find managed resource and won't create one. Record a miss.
else if(style == RETRIEVE_RESOURCE){ if(style == RETRIEVE_RESOURCE){
managed[lookup] = NULL; managed[lookup] = NULL;
return NULL; return NULL;
} }
//Not managed, so look in cache. //Not managed, so look in cache.
if(it == managed.end() && style != RETRIEVE_MANAGE && style != RETRIEVE_RESOURCE ){ if(style != RETRIEVE_MANAGE){
it = cache.find(lookup); it = cache.find(lookup);
//Well, we've found something... //Well, we've found something...
if(it != cache.end()) { if(it != cache.end()) {
if(!it->second && (submode & CACHE_EXISTING)){ if(!it->second && (submode & CACHE_EXISTING)){
mError = CACHE_ERROR_404; mError = CACHE_ERROR_404;
return NULL; //A miss.
} }
else return it->second; //A hit.
return it->second; //A hit.
} }
} }
cacheItem * item = NULL;
if(style != RETRIEVE_MANAGE)
item = cache[lookup]; //We don't know about this one yet.
//Found something.
if(item){
//Item went bad?
if(!item->isGood()){
//If we're allowed, attempt to revive it.
if(!(submode & CACHE_EXISTING))
item->Attempt(id,submode,mError);
//Still bad, so remove it and return NULL
if(submode & CACHE_EXISTING || !item->isGood()){
if(!item->isLocked()){
RemoveItem(item); //Delete it.
mError = CACHE_ERROR_BAD;
}
//Worst case scenerio. Hopefully never happens.... hasn't so far.
else{
item->Nullify(); //We're giving up on anything allocated here.
mError = CACHE_ERROR_LOST; //This is a potential memory leak, but might prevent a crash.
}
return NULL;
}
}
//Alright, everythings fine!
mError = CACHE_ERROR_NONE;
return item;
}
//Didn't exist in cache. //Didn't exist in cache.
if(submode & CACHE_EXISTING ){ if(submode & CACHE_EXISTING ){
RemoveMiss(lookup);
mError = CACHE_ERROR_NOT_CACHED; mError = CACHE_ERROR_NOT_CACHED;
return NULL; return NULL;
} }
else{
//Space in cache, make new texture
item = AttemptNew(id,submode);
//Couldn't make GOOD new item. //Space in cache, make new texture
if(item && !item->isGood()) cacheItem * item = AttemptNew(id,submode);
{
if(garbage.size() < MAX_CACHE_GARBAGE){
item->Trash();
garbage.push_back(item);
}
else
SAFE_DELETE(item);
}
}
if(style == RETRIEVE_MANAGE){ if(style == RETRIEVE_MANAGE){
managed[lookup] = item; //Record hit or miss if(item){
if(item) managed[lookup] = item; //Record a hit.
item->deadbolt(); //Make permanent. item->deadbolt(); //Make permanent.
}
else{
//Record it, hit or miss.
cache[lookup] = item;
}
//Succeeded in making a new item.
if(item){
unsigned long isize = item->size();
totalSize += isize;
mError = CACHE_ERROR_NONE;
if(style != RETRIEVE_MANAGE){
cacheItems++;
cacheSize += isize;
} }
else if(mError == CACHE_ERROR_404)
return item; managed[lookup] = NULL; //File not found. Record a miss
}
else {
if(item || mError == CACHE_ERROR_404)
cache[lookup] = item;
} }
//Failure. if (!item) return NULL; //Failure
return NULL;
//Succeeded in making a new item.
unsigned long isize = item->size();
totalSize += isize;
mError = CACHE_ERROR_NONE;
if(style != RETRIEVE_MANAGE){
cacheItems++;
cacheSize += isize;
}
return item;
} }
template <class cacheItem, class cacheActual> template <class cacheItem, class cacheActual>
@@ -1327,7 +1203,7 @@ WCache<cacheItem, cacheActual>::WCache(){
cacheSize = 0; cacheSize = 0;
totalSize = 0; totalSize = 0;
maxCacheSize = SMALL_CACHE_LIMIT; maxCacheSize = TEXTURES_CACHE_MINSIZE;
maxCached = MAX_CACHE_OBJECTS; maxCached = MAX_CACHE_OBJECTS;
cacheItems = 0; cacheItems = 0;
@@ -1340,24 +1216,13 @@ WCache<cacheItem, cacheActual>::~WCache(){
//Delete from cache & managed //Delete from cache & managed
for(it=cache.begin();it!=cache.end();it++){ for(it=cache.begin();it!=cache.end();it++){
if(!it->second)
continue;
SAFE_DELETE(it->second); SAFE_DELETE(it->second);
} }
for(it=managed.begin();it!=managed.end();it++){ for(it=managed.begin();it!=managed.end();it++){
if(!it->second)
continue;
SAFE_DELETE(it->second); SAFE_DELETE(it->second);
} }
//Clean up all the garbage
typename vector<cacheItem*>::iterator g;
for(g=garbage.begin();g!=garbage.end();g++){
SAFE_DELETE(*g);
}
} }
@@ -1462,24 +1327,17 @@ bool WCache<cacheItem, cacheActual>::Delete(cacheItem * item){
if(maxCached == 0) if(maxCached == 0)
item->Nullify(); item->Nullify();
unsigned long isize = item->size(); unsigned long isize = item->size();
totalSize -= isize; totalSize -= isize;
cacheSize -= isize; cacheSize -= isize;
#ifdef DEBUG_CACHE #ifdef DEBUG_CACHE
if(cacheItems == 0) if(cacheItems == 0)
OutputDebugString("cacheItems out of sync.\n"); OutputDebugString("cacheItems out of sync.\n");
#endif #endif
cacheItems--; cacheItems--;
if(garbage.size() > MAX_CACHE_GARBAGE) SAFE_DELETE(item);
SAFE_DELETE(item);
else{
item->Trash();
item->lastTime = 0;
item->loadedMode = 0;
garbage.push_back(item);
}
return true; return true;
} }