Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/std/src/lib/util/loading/resource_manager.cc @ 7207

Last change on this file since 7207 was 7207, checked in by bensch, 18 years ago

orxonox/trunk: evil was within

File size: 30.2 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Benjamin Grauer
13   co-programmer: Patrick Boenzli
14*/
15
16#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_LOAD
17
18#include "util/loading/resource_manager.h"
19
20#include "substring.h"
21#include "debug.h"
22
23#include <algorithm>
24#include <assert.h>
25
26// different resource Types
27#ifndef NO_MODEL
28#include "objModel.h"
29#include "primitive_model.h"
30#include "md2Model.h"
31#endif /* NO_MODEL */
32#ifndef NO_TEXTURES
33#include "texture.h"
34#endif /* NO_TEXTURES */
35#ifndef NO_TEXT
36#include "font.h"
37#endif /* NO_TEXT */
38#ifndef NO_AUDIO
39#include "sound_buffer.h"
40#include "ogg_player.h"
41#endif /* NO_AUDIO */
42#ifndef NO_SHADERS
43#include "shader.h"
44#endif /* NO_SHADERS */
45
46// File Handling Includes
47#include <sys/types.h>
48#include <sys/stat.h>
49#include <unistd.h>
50
51using namespace std;
52
53/**
54 * @brief standard constructor
55*/
56ResourceManager::ResourceManager ()
57{
58  this->setClassID(CL_RESOURCE_MANAGER, "ResourceManager");
59  this->setName("ResourceManager");
60
61  this->dataDir = "./";
62  this->_cwd = "";
63  this->tryDataDir("./data");
64}
65
66//! Singleton Reference to the ResourceManager
67ResourceManager* ResourceManager::singletonRef = NULL;
68
69/**
70 * @brief standard destructor
71*/
72ResourceManager::~ResourceManager ()
73{
74  // deleting the Resources-List
75  this->unloadAllByPriority(RP_GAME);
76
77  if (!this->resourceList.empty())
78    PRINTF(1)("Not removed all Resources, since there are still %d resources registered\n", this->resourceList.size());
79
80  ResourceManager::singletonRef = NULL;
81}
82
83/**
84 * @brief sets the data main directory
85 * @param dataDir the DataDirectory.
86 */
87bool ResourceManager::setDataDir(const std::string& dataDir)
88{
89  std::string realDir = ResourceManager::homeDirCheck(dataDir);
90  if (isDir(realDir))
91  {
92    if (dataDir[dataDir.size()-1] == '/' || dataDir[dataDir.size()-1] == '\\')
93    {
94      this->dataDir = realDir;
95    }
96    else
97    {
98      this->dataDir = realDir;
99      this->dataDir += '/';
100    }
101    return true;
102  }
103  else
104  {
105    PRINTF(1)("%s is not a Directory, and can not be the Data Directory, leaving as %s \n", realDir.c_str(), this->dataDir.c_str());
106    return false;
107  }
108}
109
110/**
111 * @brief sets the data main directory
112 * @param dataDir the DataDirectory.
113 *
114 * this is essentially the same as setDataDir, but it ommits the error-message
115 */
116bool ResourceManager::tryDataDir(const std::string& dataDir)
117{
118  std::string realDir = ResourceManager::homeDirCheck(dataDir);
119  if (isDir(realDir))
120  {
121    if (dataDir[dataDir.size()-1] == '/' || dataDir[dataDir.size()-1] == '\\')
122    {
123      this->dataDir = realDir;
124    }
125    else
126    {
127      this->dataDir = realDir;
128      this->dataDir += '/';
129    }
130    return true;
131  }
132  return false;
133}
134
135
136/**
137 * @brief checks for the DataDirectory, by looking if
138 * @param fileInside is iniside of the given directory.
139*/
140bool ResourceManager::verifyDataDir(const std::string& fileInside)
141{
142  bool retVal;
143  if (!isDir(this->dataDir))
144  {
145    PRINTF(1)("%s is not a directory\n", this->dataDir.c_str());
146    return false;
147  }
148
149  std::string testFile = this->dataDir + fileInside;
150  retVal = isFile(testFile);
151  return retVal;
152}
153
154#ifndef NO_TEXTURES
155/**
156 * @brief adds a new Path for Images
157 * @param imageDir The path to insert
158 * @returns true, if the Path was well and injected (or already existent within the list)
159   false otherwise
160*/
161bool ResourceManager::addImageDir(const std::string& imageDir)
162{
163  std::string newDir;
164  if (imageDir[imageDir.size()-1] == '/' || imageDir[imageDir.size()-1] == '\\')
165  {
166    newDir = imageDir;
167  }
168  else
169  {
170    newDir = imageDir;
171    newDir += '/';
172  }
173  // check if the param is a Directory
174  if (isDir(newDir))
175  {
176    // check if the Directory has been added before
177    std::vector<std::string>::const_iterator imageDir;
178    for (imageDir = this->imageDirs.begin(); imageDir != this->imageDirs.end(); imageDir++)
179    {
180      if (*imageDir == newDir)
181      {
182        PRINTF(3)("Path %s already loaded\n", newDir.c_str());
183        return true;
184      }
185    }
186    // adding the directory to the List
187    this->imageDirs.push_back(newDir);
188    return true;
189  }
190  else
191  {
192    PRINTF(1)("%s is not a Directory, and can not be added to the Paths of Images\n", newDir.c_str());
193    return false;
194  }
195}
196#endif /* NO_TEXTURES */
197
198/**
199 * @brief loads resources
200 * @param fileName: The fileName of the resource to load
201 * @param prio: The ResourcePriority of this resource (will only be increased)
202 * @param param0: an additional option to parse (see the constuctors for more help)
203 * @param param1: an additional option to parse (see the constuctors for more help)
204 * @param param2: an additional option to parse (see the constuctors for more help)
205 * @returns a pointer to a desired Resource.
206*/
207BaseObject* ResourceManager::load(const std::string& fileName, ResourcePriority prio,
208                                  const MultiType& param0, const MultiType& param1, const MultiType& param2)
209{
210  ResourceType tmpType;
211#ifndef NO_MODEL
212#define __IF_OK
213  if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".obj", 4))
214    tmpType = OBJ;
215  else if (!strncmp(fileName.c_str()+(fileName.size()-4), ".md2", 4))
216    tmpType = MD2;
217  else if (!strcasecmp(fileName.c_str(), "cube") ||
218            !strcasecmp(fileName.c_str(), "sphere") ||
219            !strcasecmp(fileName.c_str(), "plane") ||
220            !strcasecmp(fileName.c_str(), "cylinder") ||
221            !strcasecmp(fileName.c_str(), "cone"))
222    tmpType = PRIM;
223#endif /* NO_MODEL */
224#ifndef NO_AUDIO
225#ifdef __IF_OK
226  else
227#endif
228#define __IF_OK
229    if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".wav", 4))
230      tmpType = WAV;
231    else if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".mp3", 4))
232      tmpType = MP3;
233    else if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".ogg", 4))
234      tmpType = OGG;
235#endif /* NO_AUDIO */
236#ifndef NO_TEXT
237#ifdef __IF_OK
238    else
239#endif
240#define __IF_OK
241      if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".ttf", 4))
242        tmpType = TTF;
243#endif /* NO_TEXT */
244#ifndef NO_SHADERS
245#ifdef __IF_OK
246      else
247#endif
248#define __IF_OK
249        if (!strncasecmp(fileName.c_str()+(fileName.size()-5), ".vert", 5))
250          tmpType = SHADER;
251#endif /* NO_SHADERS */
252#ifndef NO_TEXTURES
253#ifdef __IF_OK
254        else
255#else
256  if
257#endif
258          tmpType = IMAGE;
259#endif /* NO_TEXTURES */
260#undef __IF_OK
261  return this->load(fileName, tmpType, prio, param0, param1, param2);
262}
263
264/**
265 * @brief caches a Resource
266 *
267 * @see load;
268 *
269 * @brief returns true if ok, false otherwise.
270 * This function loads a Resource without applying it to an Object.
271 * This is for loading purposes, e.g, when the user is loading a Resource
272 * during the initialisation instead of at Runtime.
273 */
274bool ResourceManager::cache(const std::string& fileName, ResourceType type, ResourcePriority prio,
275                            const MultiType& param0, const MultiType& param1, const MultiType& param2)
276{
277  // searching if the resource was loaded before.
278  Resource* tmpResource;
279  // check if we already loaded this Resource
280  tmpResource = this->locateResourceByInfo(fileName, type, param0, param1, param2);
281  // otherwise load it
282  if (tmpResource == NULL)
283    tmpResource = this->loadResource(fileName, type, prio, param0, param1, param2);
284  // return cached pointer.
285  if (tmpResource != NULL) // if the resource was loaded before.
286  {
287    if(tmpResource->prio < prio)
288      tmpResource->prio = prio;
289    return true;
290  }
291  else
292    return false;
293}
294
295/**
296 * tells the ResourceManager to generate a Copy of the Resource.
297 * @brief resourcePointer: The Pointer to the resource to copy
298 * @returns the Resource pointed to resourcePointer.
299 */
300BaseObject* ResourceManager::copy(BaseObject* resourcePointer)
301{
302  Resource* tmp = locateResourceByPointer(resourcePointer);
303  if (tmp!=NULL)
304  {
305    tmp->count++;
306    return tmp->pointer;
307  }
308  else
309    return NULL;
310}
311
312
313/**
314 * @brief loads resources
315 * @param fileName: The fileName of the resource to load
316 * @param type: The Type of Resource to load.
317 * @param prio: The ResourcePriority of this resource (will only be increased)
318 * @param param0: an additional option to parse (see the constuctors for more help)
319 * @param param1: an additional option to parse (see the constuctors for more help)
320 * @param param2: an additional option to parse (see the constuctors for more help)
321 * @returns a pointer to a desired Resource.
322*/
323BaseObject* ResourceManager::load(const std::string& fileName, ResourceType type, ResourcePriority prio,
324                                  const MultiType& param0, const MultiType& param1, const MultiType& param2)
325{
326  // searching if the resource was loaded before.
327  Resource* tmpResource;
328  // check if we already loaded this Resource
329  tmpResource = this->locateResourceByInfo(fileName, type, param0, param1, param2);
330  // otherwise load it
331  if (tmpResource == NULL)
332  {
333    tmpResource = this->loadResource(fileName, type, prio, param0, param1, param2);
334  }
335  // return cached pointer.
336  if (tmpResource != NULL) // if the resource was loaded before.
337  {
338    tmpResource->count++;
339    if(tmpResource->prio < prio)
340      tmpResource->prio = prio;
341
342    return tmpResource->pointer;
343  }
344  else
345    return NULL;
346}
347
348
349/**
350 * @brief loads resources for internal purposes
351 * @param fileName: The fileName of the resource to load
352 * @param type: The Type of Resource to load.
353 * @param prio: The ResourcePriority of this resource (will only be increased)
354 * @param param0: an additional option to parse (see the constuctors for more help)
355 * @param param1: an additional option to parse (see the constuctors for more help)
356 * @param param2: an additional option to parse (see the constuctors for more help)
357 * @returns a pointer to a desired Resource.
358 */
359Resource* ResourceManager::loadResource(const std::string& fileName, ResourceType type, ResourcePriority prio,
360                                        const MultiType& param0, const MultiType& param1, const MultiType& param2)
361{
362  // Setting up the new Resource
363  Resource* tmpResource = new Resource;
364  tmpResource->count = 0;
365  tmpResource->type = type;
366  tmpResource->prio = prio;
367  tmpResource->pointer = NULL;
368  tmpResource->name = fileName;
369
370  // creating the full name. (directoryName + FileName)
371  std::string fullName = ResourceManager::getFullName(fileName);
372  // Checking for the type of resource \see ResourceType
373  switch(type)
374  {
375#ifndef NO_MODEL
376    case OBJ:
377      if (param0.getType() != MT_NULL)
378        tmpResource->param[0] = param0;
379      else
380        tmpResource->param[0] = 1.0f;
381
382      if(ResourceManager::isFile(fullName))
383        tmpResource->pointer = new OBJModel(fullName, tmpResource->param[0].getFloat());
384      else
385      {
386        PRINTF(2)("File %s in %s does not exist. Loading a cube-Model instead\n", fileName.c_str(), dataDir.c_str());
387        tmpResource->pointer = ResourceManager::load("cube", PRIM, prio, tmpResource->param[0].getFloat());
388      }
389      break;
390    case PRIM:
391      if (param0 != MT_NULL)
392        tmpResource->param[0] = param0;
393      else
394        tmpResource->param[0] = 1.0f;
395
396      if (tmpResource->name == "cube")
397        tmpResource->pointer = new PrimitiveModel(PRIM_CUBE, tmpResource->param[0].getFloat());
398      else if (tmpResource->name == "sphere")
399        tmpResource->pointer = new PrimitiveModel(PRIM_SPHERE, tmpResource->param[0].getFloat());
400      else if (tmpResource->name == "plane")
401        tmpResource->pointer = new PrimitiveModel(PRIM_PLANE, tmpResource->param[0].getFloat());
402      else if (tmpResource->name == "cylinder")
403        tmpResource->pointer = new PrimitiveModel(PRIM_CYLINDER, tmpResource->param[0].getFloat());
404      else if (tmpResource->name == "cone")
405        tmpResource->pointer = new PrimitiveModel(PRIM_CONE, tmpResource->param[0].getFloat());
406      break;
407    case MD2:
408      if(ResourceManager::isFile(fullName))
409      {
410        tmpResource->param[0] = param0;
411        tmpResource->param[1] = param1;
412        tmpResource->pointer = new MD2Data(fullName, tmpResource->param[0].getCString(), tmpResource->param[1].getFloat());
413      }
414      break;
415#endif /* NO_MODEL */
416#ifndef NO_TEXT
417    case TTF:
418      if (param0 != MT_NULL)
419      {
420        assert(param0.getInt() >= 0);
421        tmpResource->param[0] = param0;
422      }
423      else
424        tmpResource->param[0] = FONT_DEFAULT_RENDER_SIZE;
425
426      if(isFile(fullName))
427        tmpResource->pointer = new Font(fullName, (unsigned int) tmpResource->param[0].getInt());
428      else
429        PRINTF(2)("%s does not exist in %s. Not loading Font\n", fileName.c_str(), this->dataDir.c_str());
430      break;
431#endif /* NO_TEXT */
432#ifndef NO_AUDIO
433    case WAV:
434      if(isFile(fullName))
435        tmpResource->pointer = new SoundBuffer(fullName);
436      break;
437    case OGG:
438      if (isFile(fullName))
439        tmpResource->pointer = new OggPlayer(fullName);
440      break;
441#endif /* NO_AUDIO */
442#ifndef NO_TEXTURES
443    case IMAGE:
444      if (param0 != MT_NULL)
445        tmpResource->param[0] = param0;
446      else
447        tmpResource->param[0] = GL_TEXTURE_2D;
448      if(isFile(fullName))
449      {
450        PRINTF(4)("Image %s resides to %s\n", fileName, fullName);
451        tmpResource->pointer = new Texture(fullName, tmpResource->param[0].getInt());
452      }
453      else
454      {
455        std::vector<std::string>::iterator imageDir;
456        for (imageDir = this->imageDirs.begin(); imageDir != this->imageDirs.end(); imageDir++)
457        {
458          std::string imgName = *imageDir + fileName;
459          if(isFile(imgName))
460          {
461            PRINTF(4)("Image %s resides to %s\n", fileName, imgName);
462            tmpResource->pointer = new Texture(imgName, tmpResource->param[0].getInt());
463            break;
464          }
465        }
466      }
467      if(!tmpResource)
468        PRINTF(2)("!!Image %s not Found!!\n", fileName.c_str());
469      break;
470#endif /* NO_TEXTURES */
471#ifndef NO_SHADERS
472    case SHADER:
473      if(ResourceManager::isFile(fullName))
474      {
475        if (param0 != MT_NULL)
476        {
477          MultiType param = param0; /// HACK
478          std::string secFullName = ResourceManager::getFullName(param.getCString());
479          if (ResourceManager::isFile(secFullName))
480          {
481            tmpResource->param[0] = secFullName;
482            tmpResource->pointer = new Shader(fullName, secFullName);
483          }
484        }
485        else
486        {
487          tmpResource->param[0] = param0;
488          tmpResource->pointer = new Shader(fullName, "");
489        }
490      }
491      break;
492#endif /* NO_SHADERS */
493    default:
494      tmpResource->pointer = NULL;
495      PRINTF(1)("No type found for %s.\n   !!This should not happen unless the Type is not supported yet. JUST DO IT!!\n", tmpResource->name.c_str());
496      break;
497  }
498  if (tmpResource->pointer != NULL)
499    this->resourceList.push_back(tmpResource);
500
501  if (tmpResource->pointer != NULL)
502    return tmpResource;
503  else
504  {
505    PRINTF(2)("Resource %s could not be loaded\n", fileName.c_str());
506    delete tmpResource;
507    return NULL;
508  }
509}
510
511/**
512 * @brief unloads a Resource
513 * @param pointer: The pointer to free
514 * @param prio: the PriorityLevel to unload this resource
515 * @returns true if successful (pointer found, and deleted), false otherwise
516*/
517bool ResourceManager::unload(BaseObject* pointer, ResourcePriority prio)
518{
519  if (pointer == NULL)
520    return false;
521  // if pointer is existent. and only one resource of this type exists.
522  Resource* tmpResource = this->locateResourceByPointer(pointer);
523  if (tmpResource != NULL)
524    return unload(tmpResource, prio);
525  else
526  {
527    PRINTF(2)("Resource not Found %p\n", pointer);
528    return false;
529  }
530}
531
532/**
533 * @brief unloads a Resource
534 * @param resource: The resource to unloade
535 * @param prio the PriorityLevel to unload this resource
536 * @returns true on success, false otherwise.
537*/
538bool ResourceManager::unload(Resource* resource, ResourcePriority prio)
539{
540  if (resource == NULL)
541    return false;
542  if (resource->count > 0)
543    resource->count--;
544
545  if (resource->prio <= prio)
546  {
547    if (resource->count == 0)
548    {
549      delete resource->pointer;
550      // deleting the List Entry:
551      PRINTF(4)("Resource %s safely removed.\n", resource->name.c_str());
552      std::vector<Resource*>::iterator resourceIT = std::find(this->resourceList.begin(), this->resourceList.end(), resource);
553      this->resourceList.erase(resourceIT);
554      delete resource;
555    }
556    else
557      PRINTF(4)("Resource %s not removed, because there are still %d References to it.\n", resource->name.c_str(), resource->count);
558  }
559  else
560    PRINTF(4)("not deleting resource %s because DeleteLevel to high\n", resource->name.c_str());
561  return true;
562}
563
564
565/**
566 * @brief unloads all alocated Memory of Resources with a pririty lower than prio
567 * @param prio The priority to delete
568*/
569bool ResourceManager::unloadAllByPriority(ResourcePriority prio)
570{
571  unsigned int removeCount;
572  for (unsigned int round = 0; round < 3; round++)
573  {
574    int index = this->resourceList.size() - 1;
575    removeCount = 0;
576    while (index >= 0)
577    {
578      if (this->resourceList[index]->prio <= prio)
579      {
580        if (this->resourceList[index]->count == 0)
581          unload(this->resourceList[index], prio);
582        else
583        {
584          if (round == 3)
585            PRINTF(2)("unable to unload %s because there are still %d references to it\n",
586                      this->resourceList[index]->name.c_str(), this->resourceList[index]->count);
587          removeCount++;
588        }
589      }
590      index--;
591    }
592    if (removeCount == 0) break;
593  }
594}
595
596
597/**
598 * @brief Searches for a Resource by some information
599 * @param fileName: The name to look for
600 * @param type the Type of resource to locate.
601 * @param param0: an additional option to parse (see the constuctors for more help)
602 * @param param1: an additional option to parse (see the constuctors for more help)
603 * @param param2: an additional option to parse (see the constuctors for more help)
604 * @returns a Pointer to the Resource if found, NULL otherwise.
605*/
606Resource* ResourceManager::locateResourceByInfo(const std::string& fileName, ResourceType type,
607    const MultiType& param0, const MultiType& param1, const MultiType& param2) const
608{
609  std::vector<Resource*>::const_iterator resource;
610  for (resource = this->resourceList.begin(); resource != this->resourceList.end(); resource++)
611  {
612    if ((*resource)->type == type && fileName == (*resource)->name)
613    {
614      bool match = false;
615      switch (type)
616      {
617#ifndef NO_MODEL
618        case PRIM:
619        case OBJ:
620          if (param0 == MT_NULL)
621          {
622            if ((*resource)->param[0] == 1.0f)
623              match = true;
624          }
625          else if ((*resource)->param[0] == param0.getFloat())
626            match = true;
627          break;
628        case MD2:
629          if (param0 == MT_NULL && ((*resource)->param[0] == "") && param1 == MT_NULL && ((*resource)->param[0] == 1.0f))
630              match = true;
631          else if ((*resource)->param[0] == ((MultiType)param0).getString() && (*resource)->param[1] == ((MultiType)param1).getFloat())
632            match = true;
633          break;
634#endif /* NO_MODEL */
635#ifndef NO_TEXT
636        case TTF:
637          if (param0 == MT_NULL)
638          {
639            if ((*resource)->param[0] == FONT_DEFAULT_RENDER_SIZE)
640              match = true;
641          }
642          else if ((*resource)->param[0] == param0.getInt())
643            match = true;
644          break;
645#endif /* NO_TEXT */
646#ifndef NO_SHADERS
647        case SHADER:
648          if (param0 == MT_NULL)
649          {
650            if ((*resource)->param[0] == "")
651              match = true;
652          }
653          else if ((*resource)->param[0] == ((MultiType)param0).getString())
654            match = true;
655          break;
656#endif /* NO_SHADERS */
657#ifndef NO_TEXTURES
658        case IMAGE:
659          if (param0 == MT_NULL)
660          {
661            if ((*resource)->param[0] == GL_TEXTURE_2D)
662              match = true;
663          }
664          else if ((*resource)->param[0] ==  param0.getInt())
665            match = true;
666          break;
667#endif /* NO_TEXTURES */
668        default:
669          match = true;
670          break;
671      }
672      if (match)
673      {
674        return (*resource);
675      }
676    }
677  }
678  return NULL;
679}
680
681/**
682 * @brief Searches for a Resource by Pointer
683 * @param pointer the Pointer to search for
684 * @returns a Pointer to the Resource if found, NULL otherwise.
685 */
686Resource* ResourceManager::locateResourceByPointer(const void* pointer) const
687{
688  //  Resource* enumRes = resourceList->enumerate();
689  std::vector<Resource*>::const_iterator resource;
690  for (resource = this->resourceList.begin(); resource != this->resourceList.end(); resource++)
691    if (pointer == (*resource)->pointer)
692      return (*resource);
693  return NULL;
694}
695
696std::string ResourceManager::toResourcableString(unsigned int i)
697{
698/*  int len = strlen(ResourceManager::ResourceTypeToChar(this->resourceList[i]->type));
699  len += this->resourceList[i]->name.size();
700  if (this->resourceList[i]->param[0].getCString()) len += strlen(this->resourceList[i]->param[0].getCString()) +1;
701  if (this->resourceList[i]->param[1].getCString()) len += strlen(this->resourceList[i]->param[1].getCString()) +1;
702  if (this->resourceList[i]->param[2].getCString()) len += strlen(this->resourceList[i]->param[2].getCString()) +1;
703  len += 10;
704  std::string tmp = new char[len];
705  tmp[0] = '\0';
706  strcat(tmp, ResourceManager::ResourceTypeToChar(this->resourceList[i]->type));
707  strcat(tmp,",");
708  strcat (tmp, this->resourceList[i]->name);
709  if (this->resourceList[i]->param[0].getCString() && this->resourceList[i]->param[0].getCString() != '\0')
710  {
711    strcat(tmp,",");
712    strcat( tmp, this->resourceList[i]->param[0].getCString());
713  }
714  if (this->resourceList[i]->param[1].getCString() && this->resourceList[i]->param[1].getCString() != '\0')
715  {
716    strcat(tmp,",");
717    strcat( tmp, this->resourceList[i]->param[1].getCString());
718  }
719  if (this->resourceList[i]->param[2].getCString() && this->resourceList[i]->param[2].getCString() != '\0')
720  {
721    strcat(tmp,",");
722    strcat( tmp, this->resourceList[i]->param[2].getCString());
723  }
724  return tmp;*/
725}
726
727/**
728 * @brief caches a Resource from a ResourceableString created with the toResourcableString-function
729 * @param resourceableString the String to cache the resource from.
730 */
731bool ResourceManager::fromResourceableString(const std::string& resourceableString)
732{
733/*  SubString splits(resourceableString, ',');
734  splits.debug();
735  if (splits.getCount() == 2)
736    this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),
737                RP_LEVEL);
738  else if (splits.getCount() == 3)
739    return this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),
740                RP_LEVEL, splits[2]);
741  else if (splits.getCount() == 4)
742    return this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),
743                RP_LEVEL, splits[2], splits[3]);
744  else if (splits.getCount() == 5)
745    return this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),
746                RP_LEVEL, splits[2], splits[3], splits[4]);*/
747}
748
749
750/**
751 * @brief Checks if it is a Directory
752 * @param directoryName the Directory to check for
753 * @returns true if it is a directory/symlink false otherwise
754*/
755bool ResourceManager::isDir(const std::string& directoryName)
756{
757  std::string tmpDirName = directoryName;
758  struct stat status;
759
760  // checking for the termination of the string given. If there is a "/" at the end cut it away
761  if (directoryName[directoryName.size()-1] == '/' ||
762      directoryName[directoryName.size()-1] == '\\')
763  {
764    tmpDirName.erase(tmpDirName.size()-1);
765  }
766
767  if(!stat(tmpDirName.c_str(), &status))
768  {
769    if (status.st_mode & (S_IFDIR
770#ifndef __WIN32__
771                          | S_IFLNK
772#endif
773                         ))
774    {
775      return true;
776    }
777    else
778      return false;
779  }
780  else
781    return false;
782}
783
784/**
785 * @brief Checks if the file is either a Regular file or a Symlink
786 * @param fileName the File to check for
787 * @returns true if it is a regular file/symlink, false otherwise
788*/
789bool ResourceManager::isFile(const std::string& fileName)
790{
791  if (fileName.empty())
792    return false;
793  std::string tmpFileName = ResourceManager::homeDirCheck(fileName);
794  // actually checks the File
795  struct stat status;
796  if (!stat(tmpFileName.c_str(), &status))
797  {
798    if (status.st_mode & (S_IFREG
799#ifndef __WIN32__
800                          | S_IFLNK
801#endif
802                         ))
803    {
804      return true;
805    }
806    else
807      return false;
808  }
809  else
810    return false;
811}
812
813/**
814 * @brief touches a File on the disk (thereby creating it)
815 * @param fileName The file to touch
816*/
817bool ResourceManager::touchFile(const std::string& fileName)
818{
819  std::string tmpName = ResourceManager::homeDirCheck(fileName);
820  if (tmpName.empty())
821    return false;
822  FILE* stream;
823  if( (stream = fopen (tmpName.c_str(), "w")) == NULL)
824  {
825    PRINTF(1)("could not open %s fro writing\n", fileName.c_str());
826    return false;
827  }
828  fclose(stream);
829}
830
831/**
832 * @brief deletes a File from disk
833 * @param fileName the File to delete
834*/
835bool ResourceManager::deleteFile(const std::string& fileName)
836{
837  std::string tmpName = ResourceManager::homeDirCheck(fileName);
838  unlink(tmpName.c_str());
839}
840
841/**
842 * @param name the Name of the file to check
843 * @returns The name of the file, including the HomeDir
844 */
845std::string ResourceManager::homeDirCheck(const std::string& name)
846{
847  if (name.size() >= 2 && name[0] == '~' && name[1] == '/')
848  {
849    std::string homeDir;
850    std::string newName = name.substr(1, name.size()-1);
851#ifdef __WIN32__
852    homeDir = getenv("USERPROFILE");
853#else
854    homeDir = getenv("HOME");
855#endif
856    return homeDir + newName;
857  }
858  else
859    return name;
860}
861
862/**
863 * @param name the relative name of the File/Directory.
864 * @returns a new std::string with the name in abs-dir-format
865 */
866std::string ResourceManager::getAbsDir(const std::string& name)
867{
868  if (name.empty())
869    return "";
870  std::string retName = name;
871  if (strncmp(name.c_str(), "/", 1))
872  {
873    if (name[0] == '.' && name[1] != '.')
874      retName.erase(0);
875    const std::string& absDir = ResourceManager::cwd();
876    retName = absDir + retName;
877  }
878  return retName;
879}
880
881
882/**
883 * @param fileName the Name of the File to check
884 * @returns The full name of the file, including the DataDir, and NULL if the file does not exist
885 * !!IMPORTANT: this has to be deleted from the outside!!
886*/
887std::string ResourceManager::getFullName(const std::string& fileName)
888{
889  if (fileName.empty() || ResourceManager::getInstance()->getDataDir().empty())
890    return "";
891
892  std::string retName = ResourceManager::getInstance()->getDataDir() +fileName;
893  if (ResourceManager::isFile(retName) || ResourceManager::isDir(retName))
894    return retName;
895  else
896    return "";
897}
898
899#ifdef __unix__
900  #include <unistd.h>
901#elif __WIN32__ || _MS_DOS_
902  #include <dir.h>
903#else
904  #include <direct.h> /* Visual C++ */
905#endif
906/**
907 * @returns the Current Woring Directory
908 */
909const std::string& ResourceManager::cwd()
910{
911  if (ResourceManager::getInstance()->_cwd.empty())
912  {
913    char cwd[1024];
914    char* errorCode = getcwd(cwd, 1024);
915    if (errorCode == 0)
916      return ResourceManager::getInstance()->_cwd;
917
918    ResourceManager::getInstance()->_cwd = cwd;
919  }
920  return ResourceManager::getInstance()->_cwd;
921}
922
923
924/**
925 * @brief checks wether a file is in the DataDir.
926 * @param fileName the File to check if it is in the Data-Dir structure.
927 * @returns true if the file exists, false otherwise
928 */
929bool ResourceManager::isInDataDir(const std::string& fileName)
930{
931  if (fileName.empty() || ResourceManager::getInstance()->getDataDir().empty())
932    return false;
933
934  bool retVal = false;
935  std::string checkFile = ResourceManager::getInstance()->getDataDir() + fileName;
936
937  if (ResourceManager::isFile(checkFile) || ResourceManager::isDir(checkFile))
938    retVal = true;
939  else
940    retVal = false;
941  return retVal;
942}
943
944
945/**
946 * @brief outputs debug information about the ResourceManager
947 */
948void ResourceManager::debug() const
949{
950  PRINT(0)("=RM===================================\n");
951  PRINT(0)("= RESOURCE-MANAGER DEBUG INFORMATION =\n");
952  PRINT(0)("======================================\n");
953  // if it is not initialized
954  PRINT(0)(" Reference is: %p\n", ResourceManager::singletonRef);
955  PRINT(0)(" Data-Directory is: %s\n", this->dataDir.c_str());
956  PRINT(0)(" List of Image-Directories: ");
957  std::vector<std::string>::const_iterator imageDir;
958  for (imageDir = this->imageDirs.begin(); imageDir != this->imageDirs.end(); imageDir++)
959    PRINT(0)("%s ", (*imageDir).c_str());
960  PRINT(0)("\n");
961
962  PRINT(0)("List of all stored Resources:\n");
963  std::vector<Resource*>::const_iterator resource;
964  for (resource = this->resourceList.begin(); resource != this->resourceList.end(); resource++)
965
966  {
967    PRINT(0)("-----------------------------------------\n");
968    PRINT(0)("Name: %s; References: %d; Type: %s ", (*resource)->name.c_str(), (*resource)->count, ResourceManager::ResourceTypeToChar((*resource)->type));
969
970    PRINT(0)("gets deleted at ");
971    switch((*resource)->prio)
972    {
973      default:
974      case RP_NO:
975        PRINT(0)("first posibility (0)\n");
976        break;
977      case RP_LEVEL:
978        PRINT(0)("the end of the Level (1)\n");
979        break;
980      case RP_CAMPAIGN:
981        PRINT(0)("the end of the campaign (2)\n");
982        break;
983      case RP_GAME:
984        PRINT(0)("when leaving the game (3)\n");
985        break;
986    }
987  }
988
989
990
991  PRINT(0)("==================================RM==\n");
992}
993
994
995/**
996 * @brief converts a ResourceType into the corresponding String
997 * @param type the ResourceType to translate
998 * @returns the converted String.
999 */
1000const char* ResourceManager::ResourceTypeToChar(ResourceType type)
1001{
1002  return ResourceManager::resourceNames[type];
1003}
1004
1005/**
1006 * @brief converts a String into a ResourceType (good for loading)
1007 * @param resourceType the name of the Type
1008 * @returns the Number of the Type, or 0 (defautl) if not found.
1009 */
1010ResourceType ResourceManager::stringToResourceType(const char* resourceType)
1011{
1012  assert(resourceType != NULL);
1013  for (unsigned int i = 0; i < RESOURCE_TYPE_SIZE; i++)
1014    if (!strcmp(resourceType, ResourceManager::resourceNames[i]))
1015      return (ResourceType)i;
1016  return (ResourceType)0;
1017}
1018
1019/**
1020 * The Names of the ResourceTypes
1021 */
1022const char* ResourceManager::resourceNames[] =
1023  {
1024#ifndef NO_MODEL
1025    "ObjectModel",
1026    "PrimitiveModel",
1027    "MD2-Data",
1028#endif
1029#ifndef NO_TEXT
1030    "Font",
1031#endif
1032#ifndef NO_AUDIO
1033    "Wav",
1034    "mp3",
1035    "ogg",
1036#endif
1037#ifndef NO_TEXTURES
1038    "Texture",
1039#endif
1040#ifndef NO_SHADERS
1041    "Shader",
1042#endif
1043
1044  };
Note: See TracBrowser for help on using the repository browser.