CLodHandler.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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.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. void CLodHandler::convertName(std::string &filename, std::string *extension)
  59. {
  60. std::transform(filename.begin(), filename.end(), filename.begin(), toupper);
  61. size_t dotPos = filename.find_last_of("/.");
  62. if ( dotPos != std::string::npos && filename[dotPos] == '.')
  63. {
  64. if (extension)
  65. *extension = filename.substr(dotPos);
  66. filename.erase(dotPos);
  67. }
  68. }
  69. unsigned char * CLodHandler::giveFile(std::string fname, LodFileType type, int * length)
  70. {
  71. convertName(fname);
  72. boost::unordered_set<Entry>::const_iterator en_it = entries.find(Entry(fname, type));
  73. if(en_it == entries.end()) //nothing's been found
  74. {
  75. tlog1 << "Cannot find file: " << fname << std::endl;
  76. return NULL;
  77. }
  78. Entry ourEntry = *en_it;
  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. outp = new unsigned char[ourEntry.realSize];
  86. FILE * f = fopen((myDir + "/" + ourEntry.realName).c_str(), "rb");
  87. if (f)
  88. {
  89. result = fread(outp,1,ourEntry.realSize,f);
  90. fclose(f);
  91. }
  92. else
  93. result = -1;
  94. mutex->unlock();
  95. if(result<0)
  96. {
  97. tlog1<<"Error in file reading: " << myDir << "/" << ourEntry.name << std::endl;
  98. delete[] outp;
  99. return NULL;
  100. }
  101. else
  102. return outp;
  103. }
  104. else if (ourEntry.size==0) //file is not compressed
  105. {
  106. outp = new unsigned char[ourEntry.realSize];
  107. LOD.seekg(ourEntry.offset, std::ios::beg);
  108. LOD.read((char*)outp, ourEntry.realSize);
  109. mutex->unlock();
  110. return outp;
  111. }
  112. else //we will decompress file
  113. {
  114. outp = new unsigned char[ourEntry.size];
  115. LOD.seekg(ourEntry.offset, std::ios::beg);
  116. LOD.read((char*)outp, ourEntry.size);
  117. unsigned char * decomp = NULL;
  118. infs2(outp, ourEntry.size, ourEntry.realSize, decomp);
  119. mutex->unlock();
  120. delete[] outp;
  121. return decomp;
  122. }
  123. return NULL;
  124. }
  125. std::string CLodHandler::getFileName(std::string lodFile, LodFileType type)
  126. {
  127. convertName(lodFile);
  128. boost::unordered_set<Entry>::const_iterator it = entries.find(Entry(lodFile, type));
  129. if (it != entries.end())
  130. return it->realName;
  131. return "";
  132. }
  133. bool CLodHandler::haveFile(std::string name, LodFileType type)
  134. {
  135. convertName(name);
  136. return vstd::contains(entries, Entry(name, type));
  137. }
  138. DLL_EXPORT int CLodHandler::infs2(unsigned char * in, int size, int realSize, unsigned char *& out, int wBits)
  139. {
  140. int ret;
  141. unsigned have;
  142. z_stream strm;
  143. out = new unsigned char [realSize];
  144. int latPosOut = 0;
  145. /* allocate inflate state */
  146. strm.zalloc = Z_NULL;
  147. strm.zfree = Z_NULL;
  148. strm.opaque = Z_NULL;
  149. strm.avail_in = 0;
  150. strm.next_in = Z_NULL;
  151. ret = inflateInit2(&strm, wBits);
  152. if (ret != Z_OK)
  153. return ret;
  154. int chunkNumber = 0;
  155. do
  156. {
  157. if(size < chunkNumber * NLoadHandlerHelp::fCHUNK)
  158. break;
  159. strm.avail_in = std::min(NLoadHandlerHelp::fCHUNK, size - chunkNumber * NLoadHandlerHelp::fCHUNK);
  160. if (strm.avail_in == 0)
  161. break;
  162. strm.next_in = in + chunkNumber * NLoadHandlerHelp::fCHUNK;
  163. /* run inflate() on input until output buffer not full */
  164. do
  165. {
  166. strm.avail_out = realSize - latPosOut;
  167. strm.next_out = out + latPosOut;
  168. ret = inflate(&strm, Z_NO_FLUSH);
  169. //assert(ret != Z_STREAM_ERROR); /* state not clobbered */
  170. bool breakLoop = false;
  171. switch (ret)
  172. {
  173. case Z_STREAM_END:
  174. breakLoop = true;
  175. break;
  176. case Z_NEED_DICT:
  177. ret = Z_DATA_ERROR; /* and fall through */
  178. case Z_DATA_ERROR:
  179. case Z_MEM_ERROR:
  180. (void)inflateEnd(&strm);
  181. return ret;
  182. }
  183. if(breakLoop)
  184. break;
  185. have = realSize - latPosOut - strm.avail_out;
  186. latPosOut += have;
  187. } while (strm.avail_out == 0);
  188. ++chunkNumber;
  189. /* done when inflate() says it's done */
  190. } while (ret != Z_STREAM_END);
  191. /* clean up and return */
  192. (void)inflateEnd(&strm);
  193. return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
  194. }
  195. void CLodHandler::extractFile(const std::string FName, const std::string name)
  196. {
  197. int len; //length of file to write
  198. unsigned char * outp = giveFile(name, FILE_ANY, &len);
  199. std::ofstream out;
  200. out.open(FName.c_str(), std::ios::binary);
  201. if(!out.is_open())
  202. {
  203. tlog1<<"Unable to create "<<FName<<std::endl;
  204. }
  205. else
  206. {
  207. out.write(reinterpret_cast<char*>(outp), len);
  208. out.close();
  209. }
  210. }
  211. void CLodHandler::initEntry(Entry &e, std::string name)
  212. {
  213. std::string ext;
  214. convertName(name, &ext);
  215. e.name = name;
  216. std::map<std::string, LodFileType>::iterator it = extMap.find(ext);
  217. if (it == extMap.end())
  218. e.type = FILE_OTHER;
  219. else
  220. e.type = it->second;
  221. }
  222. void CLodHandler::init(const std::string lodFile, const std::string dirName)
  223. {
  224. #define EXT(NAME, TYPE) extMap.insert(std::pair<std::string, LodFileType>(NAME, TYPE));
  225. EXT(".TXT", FILE_TEXT);
  226. EXT(".JSON",FILE_TEXT);
  227. EXT(".DEF", FILE_ANIMATION);
  228. EXT(".MSK", FILE_MASK);
  229. EXT(".MSG", FILE_MASK);
  230. EXT(".H3C", FILE_CAMPAIGN);
  231. EXT(".H3M", FILE_MAP);
  232. EXT(".FNT", FILE_FONT);
  233. EXT(".BMP", FILE_GRAPHICS);
  234. EXT(".JPG", FILE_GRAPHICS);
  235. EXT(".PCX", FILE_GRAPHICS);
  236. EXT(".PNG", FILE_GRAPHICS);
  237. EXT(".TGA", FILE_GRAPHICS);
  238. #undef EXT
  239. myDir = dirName;
  240. LOD.open(lodFile.c_str(), std::ios::in | std::ios::binary);
  241. if (!LOD.is_open())
  242. {
  243. tlog1 << "Cannot open " << lodFile << std::endl;
  244. }
  245. else
  246. {
  247. Uint32 temp;
  248. LOD.seekg(8);
  249. LOD.read((char *)&temp, 4);
  250. totalFiles = SDL_SwapLE32(temp);
  251. LOD.seekg(0x5c, std::ios::beg);
  252. if(!LOD)
  253. {
  254. tlog2 << lodFile << " doesn't store anything!\n";
  255. return;
  256. }
  257. struct LodEntry *lodEntries = new struct LodEntry[totalFiles];
  258. LOD.read((char *)lodEntries, sizeof(struct LodEntry) * totalFiles);
  259. for (unsigned int i=0; i<totalFiles; i++)
  260. {
  261. Entry entry;
  262. initEntry(entry, lodEntries[i].filename);
  263. entry.offset= SDL_SwapLE32(lodEntries[i].offset);
  264. entry.realSize = SDL_SwapLE32(lodEntries[i].uncompressedSize);
  265. entry.size = SDL_SwapLE32(lodEntries[i].size);
  266. entries.insert(entry);
  267. }
  268. delete [] lodEntries;
  269. }
  270. boost::filesystem::recursive_directory_iterator enddir;
  271. if(boost::filesystem::exists(dirName))
  272. {
  273. std::vector<std::string> path;
  274. for (boost::filesystem::recursive_directory_iterator dir(dirName); dir!=enddir; dir++)
  275. {
  276. //If a directory was found - add name to vector to recreate full path later
  277. if (boost::filesystem::is_directory(dir->status()))
  278. {
  279. path.resize(dir.level()+1);
  280. path.back() = dir->path().leaf();
  281. }
  282. if(boost::filesystem::is_regular(dir->status()))
  283. {
  284. Entry e;
  285. //we can't get relative path with boost at the moment - need to create path to file manually
  286. for (size_t i=0; i<dir.level() && i<path.size(); i++)
  287. e.realName += path[i] + '/';
  288. e.realName += dir->path().leaf();
  289. initEntry(e, e.realName);
  290. if(vstd::contains(entries, e)) //file present in .lod - overwrite its entry
  291. entries.erase(e);
  292. e.offset = -1;
  293. e.realSize = e.size = boost::filesystem::file_size(dir->path());
  294. entries.insert(e);
  295. }
  296. }
  297. }
  298. else
  299. {
  300. tlog1<<"Warning: No "+dirName+"/ folder!"<<std::endl;
  301. }
  302. }
  303. std::string CLodHandler::getTextFile(std::string name, LodFileType type)
  304. {
  305. int length=-1;
  306. unsigned char* data = giveFile(name, type, &length);
  307. if (!data) {
  308. tlog1<<"Fatal error. Missing game file: " << name << ". Aborting!"<<std::endl;
  309. exit(1);
  310. }
  311. std::string ret(data, data+length);
  312. delete [] data;
  313. return ret;
  314. }
  315. CLodHandler::CLodHandler()
  316. {
  317. mutex = new boost::mutex;
  318. totalFiles = 0;
  319. }
  320. CLodHandler::~CLodHandler()
  321. {
  322. delete mutex;
  323. }
  324. unsigned char * CLodHandler::getUnpackedFile( const std::string & path, int * sizeOut )
  325. {
  326. const int bufsize = 65536;
  327. int mapsize = 0;
  328. gzFile map = gzopen(path.c_str(), "rb");
  329. assert(map);
  330. std::vector<unsigned char *> mapstr;
  331. // Read a map by chunks
  332. // We could try to read the map size directly (cf RFC 1952) and then read
  333. // directly the whole map, but that would create more problems.
  334. do {
  335. unsigned char *buf = new unsigned char[bufsize];
  336. int ret = gzread(map, buf, bufsize);
  337. if (ret == 0 || ret == -1) {
  338. delete [] buf;
  339. break;
  340. }
  341. mapstr.push_back(buf);
  342. mapsize += ret;
  343. } while(1);
  344. gzclose(map);
  345. // Now that we know the uncompressed size, reassemble the chunks
  346. unsigned char *initTable = new unsigned char[mapsize];
  347. std::vector<unsigned char *>::iterator it;
  348. int offset;
  349. int tocopy = mapsize;
  350. for (it = mapstr.begin(), offset = 0;
  351. it != mapstr.end();
  352. it++, offset+=bufsize ) {
  353. memcpy(&initTable[offset], *it, tocopy > bufsize ? bufsize : tocopy);
  354. tocopy -= bufsize;
  355. delete [] *it;
  356. }
  357. *sizeOut = mapsize;
  358. return initTable;
  359. }