Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/util/loading/resource_manager.cc @ 7642

Last change on this file since 7642 was 7460, checked in by bensch, 19 years ago

orxonox/trunk: Namespaces for sound

File size: 30.1 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
327  // searching if the resource was loaded before.
328  Resource* tmpResource;
329  // check if we already loaded this Resource
330  tmpResource = this->locateResourceByInfo(fileName, type, param0, param1, param2);
331  // otherwise load it
332  if (tmpResource == NULL)
333  {
334    tmpResource = this->loadResource(fileName, type, prio, param0, param1, param2);
335  }
336  // return cached pointer.
337  if (tmpResource != NULL) // if the resource was loaded before.
338  {
339    tmpResource->count++;
340    if(tmpResource->prio < prio)
341      tmpResource->prio = prio;
342
343    return tmpResource->pointer;
344  }
345  else
346    return NULL;
347}
348
349
350/**
351 * @brief loads resources for internal purposes
352 * @param fileName: The fileName of the resource to load
353 * @param type: The Type of Resource to load.
354 * @param prio: The ResourcePriority of this resource (will only be increased)
355 * @param param0: an additional option to parse (see the constuctors for more help)
356 * @param param1: an additional option to parse (see the constuctors for more help)
357 * @param param2: an additional option to parse (see the constuctors for more help)
358 * @returns a pointer to a desired Resource.
359 */
360Resource* ResourceManager::loadResource(const std::string& fileName, ResourceType type, ResourcePriority prio,
361                                        const MultiType& param0, const MultiType& param1, const MultiType& param2)
362{
363  // Setting up the new Resource
364  Resource* tmpResource = new Resource;
365  tmpResource->count = 0;
366  tmpResource->type = type;
367  tmpResource->prio = prio;
368  tmpResource->pointer = NULL;
369  tmpResource->name = fileName;
370
371  // creating the full name. (directoryName + FileName)
372  std::string fullName = ResourceManager::getFullName(fileName);
373  // Checking for the type of resource \see ResourceType
374  switch(type)
375  {
376#ifndef NO_MODEL
377    case OBJ:
378      if (param0.getType() != MT_NULL)
379        tmpResource->param[0] = param0;
380      else
381        tmpResource->param[0] = 1.0f;
382
383      if(ResourceManager::isFile(fullName))
384        tmpResource->pointer = new OBJModel(fullName, tmpResource->param[0].getFloat());
385      else
386      {
387        PRINTF(2)("File %s in %s does not exist. Loading a cube-Model instead\n", fileName.c_str(), dataDir.c_str());
388        tmpResource->pointer = ResourceManager::load("cube", PRIM, prio, tmpResource->param[0].getFloat());
389      }
390      break;
391    case PRIM:
392      if (param0 != MT_NULL)
393        tmpResource->param[0] = param0;
394      else
395        tmpResource->param[0] = 1.0f;
396
397      if (tmpResource->name == "cube")
398        tmpResource->pointer = new PrimitiveModel(PRIM_CUBE, tmpResource->param[0].getFloat());
399      else if (tmpResource->name == "sphere")
400        tmpResource->pointer = new PrimitiveModel(PRIM_SPHERE, tmpResource->param[0].getFloat());
401      else if (tmpResource->name == "plane")
402        tmpResource->pointer = new PrimitiveModel(PRIM_PLANE, tmpResource->param[0].getFloat());
403      else if (tmpResource->name == "cylinder")
404        tmpResource->pointer = new PrimitiveModel(PRIM_CYLINDER, tmpResource->param[0].getFloat());
405      else if (tmpResource->name == "cone")
406        tmpResource->pointer = new PrimitiveModel(PRIM_CONE, tmpResource->param[0].getFloat());
407      break;
408    case MD2:
409      if(ResourceManager::isFile(fullName))
410      {
411        tmpResource->param[0] = param0;
412        tmpResource->param[1] = param1;
413        tmpResource->pointer = new MD2Data(fullName, tmpResource->param[0].getCString(), tmpResource->param[1].getFloat());
414      }
415      break;
416#endif /* NO_MODEL */
417#ifndef NO_TEXT
418    case TTF:
419      if (param0 != MT_NULL)
420      {
421        assert(param0.getInt() >= 0);
422        tmpResource->param[0] = param0;
423      }
424      else
425        tmpResource->param[0] = FONT_DEFAULT_RENDER_SIZE;
426
427      if(isFile(fullName))
428        tmpResource->pointer = new Font(fullName, (unsigned int) tmpResource->param[0].getInt());
429      else
430        PRINTF(2)("%s does not exist in %s. Not loading Font\n", fileName.c_str(), this->dataDir.c_str());
431      break;
432#endif /* NO_TEXT */
433#ifndef NO_AUDIO
434    case WAV:
435      if(isFile(fullName))
436        tmpResource->pointer = new OrxSound::SoundBuffer(fullName);
437      break;
438    case OGG:
439      if (isFile(fullName))
440        tmpResource->pointer = new OrxSound::OggPlayer(fullName);
441      break;
442#endif /* NO_AUDIO */
443#ifndef NO_TEXTURES
444    case IMAGE:
445      if (param0 != MT_NULL)
446        tmpResource->param[0] = param0;
447      else
448        tmpResource->param[0] = GL_TEXTURE_2D;
449      if(isFile(fullName))
450      {
451        PRINTF(4)("Image %s resides to %s\n", fileName, fullName);
452        tmpResource->pointer = new Texture(fullName, tmpResource->param[0].getInt());
453      }
454      else
455      {
456        std::vector<std::string>::iterator imageDir;
457        for (imageDir = this->imageDirs.begin(); imageDir != this->imageDirs.end(); imageDir++)
458        {
459          std::string imgName = *imageDir + fileName;
460          if(isFile(imgName))
461          {
462            PRINTF(4)("Image %s resides to %s\n", fileName, imgName);
463            tmpResource->pointer = new Texture(imgName, tmpResource->param[0].getInt());
464            break;
465          }
466        }
467      }
468      if(!tmpResource)
469        PRINTF(2)("!!Image %s not Found!!\n", fileName.c_str());
470      break;
471#endif /* NO_TEXTURES */
472#ifndef NO_SHADERS
473    case SHADER:
474      if(ResourceManager::isFile(fullName))
475      {
476        if (param0 != MT_NULL)
477        {
478          MultiType param = param0; /// HACK
479          std::string secFullName = ResourceManager::getFullName(param.getCString());
480          if (ResourceManager::isFile(secFullName))
481          {
482            tmpResource->param[0] = secFullName;
483            tmpResource->pointer = new Shader(fullName, secFullName);
484          }
485        }
486        else
487        {
488          tmpResource->param[0] = param0;
489          tmpResource->pointer = new Shader(fullName, "");
490        }
491      }
492      break;
493#endif /* NO_SHADERS */
494    default:
495      tmpResource->pointer = NULL;
496      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());
497      break;
498  }
499  if (tmpResource->pointer != NULL)
500    this->resourceList.push_back(tmpResource);
501
502  if (tmpResource->pointer != NULL)
503    return tmpResource;
504  else
505  {
506    PRINTF(2)("Resource %s could not be loaded\n", fileName.c_str());
507    delete tmpResource;
508    return NULL;
509  }
510}
511
512/**
513 * @brief unloads a Resource
514 * @param pointer: The pointer to free
515 * @param prio: the PriorityLevel to unload this resource
516 * @returns true if successful (pointer found, and deleted), false otherwise
517*/
518bool ResourceManager::unload(BaseObject* pointer, ResourcePriority prio)
519{
520  if (pointer == NULL)
521    return false;
522  // if pointer is existent. and only one resource of this type exists.
523  Resource* tmpResource = this->locateResourceByPointer(pointer);
524  if (tmpResource != NULL)
525    return unload(tmpResource, prio);
526  else
527  {
528    PRINTF(2)("Resource not Found %p\n", pointer);
529    return false;
530  }
531}
532
533/**
534 * @brief unloads a Resource
535 * @param resource: The resource to unloade
536 * @param prio the PriorityLevel to unload this resource
537 * @returns true on success, false otherwise.
538*/
539bool ResourceManager::unload(Resource* resource, ResourcePriority prio)
540{
541  if (resource == NULL)
542    return false;
543  if (resource->count > 0)
544    resource->count--;
545
546  if (resource->prio <= prio)
547  {
548    if (resource->count == 0)
549    {
550      delete resource->pointer;
551      // deleting the List Entry:
552      PRINTF(4)("Resource %s safely removed.\n", resource->name.c_str());
553      std::vector<Resource*>::iterator resourceIT = std::find(this->resourceList.begin(), this->resourceList.end(), resource);
554      this->resourceList.erase(resourceIT);
555      delete resource;
556    }
557    else
558      PRINTF(4)("Resource %s not removed, because there are still %d References to it.\n", resource->name.c_str(), resource->count);
559  }
560  else
561    PRINTF(4)("not deleting resource %s because DeleteLevel to high\n", resource->name.c_str());
562  return true;
563}
564
565
566/**
567 * @brief unloads all alocated Memory of Resources with a pririty lower than prio
568 * @param prio The priority to delete
569*/
570bool ResourceManager::unloadAllByPriority(ResourcePriority prio)
571{
572  unsigned int removeCount;
573  for (unsigned int round = 0; round < 3; round++)
574  {
575    int index = this->resourceList.size() - 1;
576    removeCount = 0;
577    while (index >= 0)
578    {
579      if (this->resourceList[index]->prio <= prio)
580      {
581        if (this->resourceList[index]->count == 0)
582          unload(this->resourceList[index], prio);
583        else
584        {
585          if (round == 3)
586            PRINTF(2)("unable to unload %s because there are still %d references to it\n",
587                      this->resourceList[index]->name.c_str(), this->resourceList[index]->count);
588          removeCount++;
589        }
590      }
591      index--;
592    }
593    if (removeCount == 0) break;
594  }
595}
596
597
598/**
599 * @brief Searches for a Resource by some information
600 * @param fileName: The name to look for
601 * @param type the Type of resource to locate.
602 * @param param0: an additional option to parse (see the constuctors for more help)
603 * @param param1: an additional option to parse (see the constuctors for more help)
604 * @param param2: an additional option to parse (see the constuctors for more help)
605 * @returns a Pointer to the Resource if found, NULL otherwise.
606*/
607Resource* ResourceManager::locateResourceByInfo(const std::string& fileName, ResourceType type,
608    const MultiType& param0, const MultiType& param1, const MultiType& param2) const
609{
610  std::vector<Resource*>::const_iterator resource;
611  for (resource = this->resourceList.begin(); resource != this->resourceList.end(); resource++)
612  {
613    if ((*resource)->type == type && fileName == (*resource)->name)
614    {
615      bool match = false;
616      switch (type)
617      {
618#ifndef NO_MODEL
619        case PRIM:
620        case OBJ:
621          if (param0 == MT_NULL)
622          {
623            if ((*resource)->param[0] == 1.0f)
624              match = true;
625          }
626          else if ((*resource)->param[0] == param0.getFloat())
627            match = true;
628          break;
629        case MD2:
630          if (param0 == MT_NULL && ((*resource)->param[0] == "") && param1 == MT_NULL && ((*resource)->param[0] == 1.0f))
631              match = true;
632          else if ((*resource)->param[0] == ((MultiType)param0).getString() && (*resource)->param[1] == ((MultiType)param1).getFloat())
633            match = true;
634          break;
635#endif /* NO_MODEL */
636#ifndef NO_TEXT
637        case TTF:
638          if (param0 == MT_NULL)
639          {
640            if ((*resource)->param[0] == FONT_DEFAULT_RENDER_SIZE)
641              match = true;
642          }
643          else if ((*resource)->param[0] == param0.getInt())
644            match = true;
645          break;
646#endif /* NO_TEXT */
647#ifndef NO_SHADERS
648        case SHADER:
649          if (param0 == MT_NULL)
650          {
651            if ((*resource)->param[0] == "")
652              match = true;
653          }
654          else if ((*resource)->param[0] == ((MultiType)param0).getString())
655            match = true;
656          break;
657#endif /* NO_SHADERS */
658#ifndef NO_TEXTURES
659        case IMAGE:
660          if (param0 == MT_NULL)
661          {
662            if ((*resource)->param[0] == GL_TEXTURE_2D)
663              match = true;
664          }
665          else if ((*resource)->param[0] ==  param0.getInt())
666            match = true;
667          break;
668#endif /* NO_TEXTURES */
669        default:
670          match = true;
671          break;
672      }
673      if (match)
674      {
675        return (*resource);
676      }
677    }
678  }
679  return NULL;
680}
681
682/**
683 * @brief Searches for a Resource by Pointer
684 * @param pointer the Pointer to search for
685 * @returns a Pointer to the Resource if found, NULL otherwise.
686 */
687Resource* ResourceManager::locateResourceByPointer(const void* pointer) const
688{
689  //  Resource* enumRes = resourceList->enumerate();
690  std::vector<Resource*>::const_iterator resource;
691  for (resource = this->resourceList.begin(); resource != this->resourceList.end(); resource++)
692    if (pointer == (*resource)->pointer)
693      return (*resource);
694  return NULL;
695}
696
697std::string ResourceManager::toResourcableString(unsigned int i)
698{
699/*  int len = strlen(ResourceManager::ResourceTypeToChar(this->resourceList[i]->type));
700  len += this->resourceList[i]->name.size();
701  if (this->resourceList[i]->param[0].getCString()) len += strlen(this->resourceList[i]->param[0].getCString()) +1;
702  if (this->resourceList[i]->param[1].getCString()) len += strlen(this->resourceList[i]->param[1].getCString()) +1;
703  if (this->resourceList[i]->param[2].getCString()) len += strlen(this->resourceList[i]->param[2].getCString()) +1;
704  len += 10;
705  std::string tmp = new char[len];
706  tmp[0] = '\0';
707  strcat(tmp, ResourceManager::ResourceTypeToChar(this->resourceList[i]->type));
708  strcat(tmp,",");
709  strcat (tmp, this->resourceList[i]->name);
710  if (this->resourceList[i]->param[0].getCString() && this->resourceList[i]->param[0].getCString() != '\0')
711  {
712    strcat(tmp,",");
713    strcat( tmp, this->resourceList[i]->param[0].getCString());
714  }
715  if (this->resourceList[i]->param[1].getCString() && this->resourceList[i]->param[1].getCString() != '\0')
716  {
717    strcat(tmp,",");
718    strcat( tmp, this->resourceList[i]->param[1].getCString());
719  }
720  if (this->resourceList[i]->param[2].getCString() && this->resourceList[i]->param[2].getCString() != '\0')
721  {
722    strcat(tmp,",");
723    strcat( tmp, this->resourceList[i]->param[2].getCString());
724  }
725  return tmp;*/
726}
727
728/**
729 * @brief caches a Resource from a ResourceableString created with the toResourcableString-function
730 * @param resourceableString the String to cache the resource from.
731 */
732bool ResourceManager::fromResourceableString(const std::string& resourceableString)
733{
734/*  SubString splits(resourceableString, ',');
735  splits.debug();
736  if (splits.getCount() == 2)
737    this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),
738                RP_LEVEL);
739  else if (splits.getCount() == 3)
740    return this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),
741                RP_LEVEL, splits[2]);
742  else if (splits.getCount() == 4)
743    return this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),
744                RP_LEVEL, splits[2], splits[3]);
745  else if (splits.getCount() == 5)
746    return this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),
747                RP_LEVEL, splits[2], splits[3], splits[4]);*/
748}
749
750
751/**
752 * @brief Checks if it is a Directory
753 * @param directoryName the Directory to check for
754 * @returns true if it is a directory/symlink false otherwise
755*/
756bool ResourceManager::isDir(const std::string& directoryName)
757{
758  std::string tmpDirName = directoryName;
759  struct stat status;
760
761  // checking for the termination of the string given. If there is a "/" at the end cut it away
762  if (directoryName[directoryName.size()-1] == '/' ||
763      directoryName[directoryName.size()-1] == '\\')
764  {
765    tmpDirName.erase(tmpDirName.size()-1);
766  }
767
768  if(!stat(tmpDirName.c_str(), &status))
769  {
770    if (status.st_mode & (S_IFDIR
771#ifndef __WIN32__
772                          | S_IFLNK
773#endif
774                         ))
775    {
776      return true;
777    }
778    else
779      return false;
780  }
781  else
782    return false;
783}
784
785/**
786 * @brief Checks if the file is either a Regular file or a Symlink
787 * @param fileName the File to check for
788 * @returns true if it is a regular file/symlink, false otherwise
789*/
790bool ResourceManager::isFile(const std::string& fileName)
791{
792  if (fileName.empty())
793    return false;
794  std::string tmpFileName = ResourceManager::homeDirCheck(fileName);
795  // actually checks the File
796  struct stat status;
797  if (!stat(tmpFileName.c_str(), &status))
798  {
799    if (status.st_mode & (S_IFREG
800#ifndef __WIN32__
801                          | S_IFLNK
802#endif
803                         ))
804    {
805      return true;
806    }
807    else
808      return false;
809  }
810  else
811    return false;
812}
813
814/**
815 * @brief touches a File on the disk (thereby creating it)
816 * @param fileName The file to touch
817*/
818bool ResourceManager::touchFile(const std::string& fileName)
819{
820  std::string tmpName = ResourceManager::homeDirCheck(fileName);
821  if (tmpName.empty())
822    return false;
823  FILE* stream;
824  if( (stream = fopen (tmpName.c_str(), "w")) == NULL)
825  {
826    PRINTF(1)("could not open %s fro writing\n", fileName.c_str());
827    return false;
828  }
829  fclose(stream);
830}
831
832/**
833 * @brief deletes a File from disk
834 * @param fileName the File to delete
835*/
836bool ResourceManager::deleteFile(const std::string& fileName)
837{
838  std::string tmpName = ResourceManager::homeDirCheck(fileName);
839  unlink(tmpName.c_str());
840}
841
842/**
843 * @param name the Name of the file to check
844 * @returns The name of the file, including the HomeDir
845 */
846std::string ResourceManager::homeDirCheck(const std::string& name)
847{
848  if (name.size() >= 2 && name[0] == '~' && name[1] == '/')
849  {
850    std::string homeDir;
851    std::string newName = name.substr(1);
852#ifdef __WIN32__
853    homeDir = getenv("USERPROFILE");
854#else
855    homeDir = getenv("HOME");
856#endif
857    return homeDir + newName;
858  }
859  else
860    return name;
861}
862
863/**
864 * @param name the relative name of the File/Directory.
865 * @returns a new std::string with the name in abs-dir-format
866 */
867std::string ResourceManager::getAbsDir(const std::string& name)
868{
869  if (name.empty())
870    return "";
871  std::string retName = name;
872  if (strncmp(name.c_str(), "/", 1))
873  {
874    if (name[0] == '.' && name[1] != '.')
875      retName.erase(0);
876    const std::string& absDir = ResourceManager::cwd();
877    retName = absDir + retName;
878  }
879  return retName;
880}
881
882
883/**
884 * @param fileName the Name of the File to check
885 * @returns The full name of the file, including the DataDir, and NULL if the file does not exist
886 * !!IMPORTANT: this has to be deleted from the outside!!
887*/
888std::string ResourceManager::getFullName(const std::string& fileName)
889{
890  if (fileName.empty() || ResourceManager::getInstance()->getDataDir().empty())
891    return "";
892
893  std::string retName = ResourceManager::getInstance()->getDataDir() +fileName;
894  if (ResourceManager::isFile(retName) || ResourceManager::isDir(retName))
895    return retName;
896  else
897    return "";
898}
899
900#ifdef __unix__
901  #include <unistd.h>
902#elif __WIN32__ || _MS_DOS_
903  #include <dir.h>
904#else
905  #include <direct.h> /* Visual C++ */
906#endif
907/**
908 * @returns the Current Woring Directory
909 */
910const std::string& ResourceManager::cwd()
911{
912  if (ResourceManager::getInstance()->_cwd.empty())
913  {
914    char cwd[1024];
915    char* errorCode = getcwd(cwd, 1024);
916    if (errorCode == 0)
917      return ResourceManager::getInstance()->_cwd;
918
919    ResourceManager::getInstance()->_cwd = cwd;
920  }
921  return ResourceManager::getInstance()->_cwd;
922}
923
924
925/**
926 * @brief checks wether a file is in the DataDir.
927 * @param fileName the File to check if it is in the Data-Dir structure.
928 * @returns true if the file exists, false otherwise
929 */
930bool ResourceManager::isInDataDir(const std::string& fileName)
931{
932  if (fileName.empty() || ResourceManager::getInstance()->getDataDir().empty())
933    return false;
934
935  bool retVal = false;
936  std::string checkFile = ResourceManager::getInstance()->getDataDir() + fileName;
937
938  if (ResourceManager::isFile(checkFile) || ResourceManager::isDir(checkFile))
939    retVal = true;
940  else
941    retVal = false;
942  return retVal;
943}
944
945
946/**
947 * @brief outputs debug information about the ResourceManager
948 */
949void ResourceManager::debug() const
950{
951  PRINT(0)("=RM===================================\n");
952  PRINT(0)("= RESOURCE-MANAGER DEBUG INFORMATION =\n");
953  PRINT(0)("======================================\n");
954  // if it is not initialized
955  PRINT(0)(" Reference is: %p\n", ResourceManager::singletonRef);
956  PRINT(0)(" Data-Directory is: %s\n", this->dataDir.c_str());
957  PRINT(0)(" List of Image-Directories: ");
958  std::vector<std::string>::const_iterator imageDir;
959  for (imageDir = this->imageDirs.begin(); imageDir != this->imageDirs.end(); imageDir++)
960    PRINT(0)("%s ", (*imageDir).c_str());
961  PRINT(0)("\n");
962
963  PRINT(0)("List of all stored Resources:\n");
964  std::vector<Resource*>::const_iterator resource;
965  for (resource = this->resourceList.begin(); resource != this->resourceList.end(); resource++)
966
967  {
968    PRINT(0)("-----------------------------------------\n");
969    PRINT(0)("Name: %s; References: %d; Type: %s ", (*resource)->name.c_str(), (*resource)->count, ResourceManager::ResourceTypeToChar((*resource)->type));
970
971    PRINT(0)("gets deleted at ");
972    switch((*resource)->prio)
973    {
974      default:
975      case RP_NO:
976        PRINT(0)("first posibility (0)\n");
977        break;
978      case RP_LEVEL:
979        PRINT(0)("the end of the Level (1)\n");
980        break;
981      case RP_CAMPAIGN:
982        PRINT(0)("the end of the campaign (2)\n");
983        break;
984      case RP_GAME:
985        PRINT(0)("when leaving the game (3)\n");
986        break;
987    }
988  }
989
990
991
992  PRINT(0)("==================================RM==\n");
993}
994
995
996/**
997 * @brief converts a ResourceType into the corresponding String
998 * @param type the ResourceType to translate
999 * @returns the converted String.
1000 */
1001const char* ResourceManager::ResourceTypeToChar(ResourceType type)
1002{
1003  return ResourceManager::resourceNames[type];
1004}
1005
1006/**
1007 * @brief converts a String into a ResourceType (good for loading)
1008 * @param resourceType the name of the Type
1009 * @returns the Number of the Type, or 0 (defautl) if not found.
1010 */
1011ResourceType ResourceManager::stringToResourceType(const std::string& resourceType)
1012{
1013  for (unsigned int i = 0; i < RESOURCE_TYPE_SIZE; i++)
1014    if (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.