CLodHandler.cpp 9.7 KB

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