CLodHandler.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. #define VCMI_DLL
  2. #include "../stdafx.h"
  3. #include "zlib.h"
  4. #include "CLodHandler.h"
  5. #include <sstream>
  6. #include <algorithm>
  7. #include <cctype>
  8. #include <cstring>
  9. #include <iostream>
  10. #include "boost/filesystem/operations.hpp"
  11. #include <boost/algorithm/string.hpp>
  12. #include <boost/algorithm/string/replace.hpp>
  13. #include <boost/thread.hpp>
  14. #include <boost/foreach.hpp>
  15. #include <SDL_endian.h>
  16. #ifdef max
  17. #undef max
  18. #endif
  19. /*
  20. * CLodHandler.cpp, part of VCMI engine
  21. *
  22. * Authors: listed in file AUTHORS in main folder
  23. *
  24. * License: GNU General Public License v2.0 or later
  25. * Full text of license available in license.txt file, in main folder
  26. *
  27. */
  28. int readNormalNr (const unsigned char * bufor, int pos, int bytCon, bool cyclic)
  29. {
  30. int ret=0;
  31. int amp=1;
  32. for (int ir=0; ir<bytCon; ir++)
  33. {
  34. ret+=bufor[pos+ir]*amp;
  35. amp*=256;
  36. }
  37. if(cyclic && bytCon<4 && ret>=amp/2)
  38. {
  39. ret = ret-amp;
  40. }
  41. return ret;
  42. }
  43. char readChar(const unsigned char * bufor, int &i)
  44. {
  45. return bufor[i++];
  46. }
  47. std::string readString(const unsigned char * bufor, int &i)
  48. {
  49. int len = readNormalNr(bufor,i); i+=4;
  50. assert(len >= 0 && len <= 500000); //not too long
  51. std::string ret; ret.reserve(len);
  52. for(int gg=0; gg<len; ++gg)
  53. {
  54. ret += bufor[i++];
  55. }
  56. return ret;
  57. }
  58. Entry CLodHandler::getEntry(const std::string name, LodFileType type)
  59. {
  60. Entry ret;
  61. std::set<Entry>::iterator it = entries.find(Entry(name, type));
  62. if (it!=entries.end())
  63. ret = *it;
  64. return ret;
  65. }
  66. unsigned char * CLodHandler::giveFile(const std::string defName, LodFileType type, int * length)
  67. {
  68. std::string fname = defName;
  69. std::transform(fname.begin(), fname.end(), fname.begin(), (int(*)(int))toupper);
  70. int dotPos = fname.find_last_of('.');
  71. if ( dotPos != -1 )
  72. fname.erase(dotPos);
  73. Entry ourEntry = getEntry(fname, type);
  74. if(!vstd::contains(entries, ourEntry)) //nothing's been found
  75. {
  76. tlog1 << "Cannot find file: " << fname << std::endl;
  77. return NULL;
  78. }
  79. if(length) *length = ourEntry.realSize;
  80. mutex->lock();
  81. unsigned char * outp;
  82. if (ourEntry.offset<0) //file is in the sprites/ folder; no compression
  83. {
  84. int result;
  85. unsigned char * outp = new unsigned char[ourEntry.realSize];
  86. FILE * f = fopen((myDir + "/" + ourEntry.realName).c_str(), "rb");
  87. if (f) {
  88. result = fread(outp,1,ourEntry.realSize,f);
  89. fclose(f);
  90. } else
  91. result = -1;
  92. mutex->unlock();
  93. if(result<0) {
  94. tlog1<<"Error in file reading: " << myDir << "/" << ourEntry.name << std::endl;
  95. delete[] outp;
  96. return NULL;
  97. } else
  98. return outp;
  99. }
  100. else if (ourEntry.size==0) //file is not compressed
  101. {
  102. outp = new unsigned char[ourEntry.realSize];
  103. LOD.seekg(ourEntry.offset, std::ios::beg);
  104. LOD.read((char*)outp, ourEntry.realSize);
  105. mutex->unlock();
  106. return outp;
  107. }
  108. else //we will decompress file
  109. {
  110. outp = new unsigned char[ourEntry.size];
  111. LOD.seekg(ourEntry.offset, std::ios::beg);
  112. LOD.read((char*)outp, ourEntry.size);
  113. unsigned char * decomp = NULL;
  114. infs2(outp, ourEntry.size, ourEntry.realSize, decomp);
  115. mutex->unlock();
  116. delete[] outp;
  117. return decomp;
  118. }
  119. return NULL;
  120. }
  121. bool CLodHandler::haveFile(const std::string name, LodFileType type)
  122. {
  123. std::string fname = name;
  124. std::transform(fname.begin(), fname.end(), fname.begin(), (int(*)(int))toupper);
  125. int dotPos = fname.find_last_of('.');
  126. if ( dotPos != -1 )
  127. fname.erase(dotPos);
  128. return vstd::contains(entries, Entry(fname, type));
  129. }
  130. DLL_EXPORT int CLodHandler::infs2(unsigned char * in, int size, int realSize, unsigned char *& out, int wBits)
  131. {
  132. int ret;
  133. unsigned have;
  134. z_stream strm;
  135. out = new unsigned char [realSize];
  136. int latPosOut = 0;
  137. /* allocate inflate state */
  138. strm.zalloc = Z_NULL;
  139. strm.zfree = Z_NULL;
  140. strm.opaque = Z_NULL;
  141. strm.avail_in = 0;
  142. strm.next_in = Z_NULL;
  143. ret = inflateInit2(&strm, wBits);
  144. if (ret != Z_OK)
  145. return ret;
  146. int chunkNumber = 0;
  147. do
  148. {
  149. if(size < chunkNumber * NLoadHandlerHelp::fCHUNK)
  150. break;
  151. strm.avail_in = std::min(NLoadHandlerHelp::fCHUNK, size - chunkNumber * NLoadHandlerHelp::fCHUNK);
  152. if (strm.avail_in == 0)
  153. break;
  154. strm.next_in = in + chunkNumber * NLoadHandlerHelp::fCHUNK;
  155. /* run inflate() on input until output buffer not full */
  156. do
  157. {
  158. strm.avail_out = realSize - latPosOut;
  159. strm.next_out = out + latPosOut;
  160. ret = inflate(&strm, Z_NO_FLUSH);
  161. //assert(ret != Z_STREAM_ERROR); /* state not clobbered */
  162. bool breakLoop = false;
  163. switch (ret)
  164. {
  165. case Z_STREAM_END:
  166. breakLoop = true;
  167. break;
  168. case Z_NEED_DICT:
  169. ret = Z_DATA_ERROR; /* and fall through */
  170. case Z_DATA_ERROR:
  171. case Z_MEM_ERROR:
  172. (void)inflateEnd(&strm);
  173. return ret;
  174. }
  175. if(breakLoop)
  176. break;
  177. have = realSize - latPosOut - strm.avail_out;
  178. latPosOut += have;
  179. } while (strm.avail_out == 0);
  180. ++chunkNumber;
  181. /* done when inflate() says it's done */
  182. } while (ret != Z_STREAM_END);
  183. /* clean up and return */
  184. (void)inflateEnd(&strm);
  185. return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
  186. }
  187. void CLodHandler::extractFile(const std::string FName, const std::string name)
  188. {
  189. int len; //length of file to write
  190. unsigned char * outp = giveFile(name, FILE_ANY, &len);
  191. std::ofstream out;
  192. out.open(FName.c_str(), std::ios::binary);
  193. if(!out.is_open())
  194. {
  195. tlog1<<"Unable to create "<<FName<<std::endl;
  196. }
  197. else
  198. {
  199. out.write(reinterpret_cast<char*>(outp), len);
  200. out.close();
  201. }
  202. }
  203. void CLodHandler::initEntry(Entry &e, const std::string name)
  204. {
  205. e.name = name;
  206. //file names stored in upper case without extension
  207. std::transform(e.name.begin(), e.name.end(), e.name.begin(), toupper);
  208. std::string ext;
  209. size_t dotPos = e.name.find_last_of('.');
  210. if ( dotPos < e.name.size() )
  211. {
  212. ext = e.name.substr(dotPos);
  213. e.name.erase(dotPos);
  214. }
  215. std::map<std::string, LodFileType>::iterator it = extMap.find(ext);
  216. if (it == extMap.end())
  217. e.type = FILE_OTHER;
  218. else
  219. e.type = it->second;
  220. }
  221. void CLodHandler::init(const std::string lodFile, const std::string dirName)
  222. {
  223. #define EXT(NAME, TYPE) extMap.insert(std::pair<std::string, LodFileType>(NAME, TYPE));
  224. EXT(".TXT", FILE_TEXT);
  225. EXT(".DEF", FILE_ANIMATION);
  226. EXT(".MSK", FILE_MASK);
  227. EXT(".MSG", FILE_MASK);
  228. EXT(".H3C", FILE_CAMPAIGN);
  229. EXT(".H3M", FILE_MAP);
  230. EXT(".FNT", FILE_FONT);
  231. EXT(".BMP", FILE_GRAPHICS);
  232. EXT(".JPG", FILE_GRAPHICS);
  233. EXT(".PCX", FILE_GRAPHICS);
  234. EXT(".PNG", FILE_GRAPHICS);
  235. #undef EXT
  236. myDir = dirName;
  237. LOD.open(lodFile.c_str(), std::ios::in | std::ios::binary);
  238. if (!LOD.is_open())
  239. {
  240. tlog1 << "Cannot open " << lodFile << std::endl;
  241. return;
  242. }
  243. Uint32 temp;
  244. LOD.seekg(8);
  245. LOD.read((char *)&temp, 4);
  246. totalFiles = SDL_SwapLE32(temp);
  247. LOD.seekg(0x5c, std::ios::beg);
  248. struct LodEntry *lodEntries = new struct LodEntry[totalFiles];
  249. LOD.read((char *)lodEntries, sizeof(struct LodEntry) * totalFiles);
  250. for (unsigned int i=0; i<totalFiles; i++)
  251. {
  252. Entry entry;
  253. initEntry(entry, lodEntries[i].filename);
  254. entry.offset= SDL_SwapLE32(lodEntries[i].offset);
  255. entry.realSize = SDL_SwapLE32(lodEntries[i].uncompressedSize);
  256. entry.size = SDL_SwapLE32(lodEntries[i].size);
  257. entries.insert(entry);
  258. }
  259. delete [] lodEntries;
  260. boost::filesystem::directory_iterator enddir;
  261. if(boost::filesystem::exists(dirName))
  262. {
  263. for (boost::filesystem::directory_iterator dir(dirName);dir!=enddir;dir++)
  264. {
  265. if(boost::filesystem::is_regular(dir->status()))
  266. {
  267. Entry e;
  268. e.realName = dir->path().leaf();
  269. initEntry(e, e.realName);
  270. if(vstd::contains(entries, e)) //file present in .lod - overwrite its entry
  271. entries.erase(e);
  272. e.offset = -1;
  273. e.realSize = e.size = boost::filesystem::file_size(dir->path());
  274. entries.insert(e);
  275. }
  276. }
  277. }
  278. else
  279. {
  280. tlog1<<"Warning: No "+dirName+"/ folder!"<<std::endl;
  281. }
  282. }
  283. std::string CLodHandler::getTextFile(const std::string name, LodFileType type)
  284. {
  285. int length=-1;
  286. unsigned char* data = giveFile(name, type, &length);
  287. if (!data) {
  288. tlog1<<"Fatal error. Missing game file: " << name << ". Aborting!"<<std::endl;
  289. exit(1);
  290. }
  291. std::string ret(data, data+length);
  292. delete [] data;
  293. return ret;
  294. }
  295. CLodHandler::CLodHandler()
  296. {
  297. mutex = new boost::mutex;
  298. totalFiles = 0;
  299. }
  300. CLodHandler::~CLodHandler()
  301. {
  302. delete mutex;
  303. }
  304. unsigned char * CLodHandler::getUnpackedFile( const std::string & path, int * sizeOut )
  305. {
  306. const int bufsize = 65536;
  307. int mapsize = 0;
  308. gzFile map = gzopen(path.c_str(), "rb");
  309. assert(map);
  310. std::vector<unsigned char *> mapstr;
  311. // Read a map by chunks
  312. // We could try to read the map size directly (cf RFC 1952) and then read
  313. // directly the whole map, but that would create more problems.
  314. do {
  315. unsigned char *buf = new unsigned char[bufsize];
  316. int ret = gzread(map, buf, bufsize);
  317. if (ret == 0 || ret == -1) {
  318. delete [] buf;
  319. break;
  320. }
  321. mapstr.push_back(buf);
  322. mapsize += ret;
  323. } while(1);
  324. gzclose(map);
  325. // Now that we know the uncompressed size, reassemble the chunks
  326. unsigned char *initTable = new unsigned char[mapsize];
  327. std::vector<unsigned char *>::iterator it;
  328. int offset;
  329. int tocopy = mapsize;
  330. for (it = mapstr.begin(), offset = 0;
  331. it != mapstr.end();
  332. it++, offset+=bufsize ) {
  333. memcpy(&initTable[offset], *it, tocopy > bufsize ? bufsize : tocopy);
  334. tocopy -= bufsize;
  335. delete [] *it;
  336. }
  337. *sizeOut = mapsize;
  338. return initTable;
  339. }