CLodHandler.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 "vcmi_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. std::string readString(const unsigned char * bufor, int &i)
  29. {
  30. int len = read_le_u32(bufor + i); i+=4;
  31. assert(len >= 0 && len <= 500000); //not too long
  32. std::string ret; ret.reserve(len);
  33. for(int gg=0; gg<len; ++gg)
  34. {
  35. ret += bufor[i++];
  36. }
  37. return ret;
  38. }
  39. void CLodHandler::convertName(std::string &filename, std::string *extension)
  40. {
  41. std::transform(filename.begin(), filename.end(), filename.begin(), toupper);
  42. size_t dotPos = filename.find_last_of("/.");
  43. if ( dotPos != std::string::npos && filename[dotPos] == '.')
  44. {
  45. if (extension)
  46. *extension = filename.substr(dotPos);
  47. filename.erase(dotPos);
  48. }
  49. }
  50. unsigned char * CLodHandler::giveFile(std::string fname, LodFileType type, int * length)
  51. {
  52. convertName(fname);
  53. boost::unordered_set<Entry>::const_iterator en_it = entries.find(Entry(fname, type));
  54. if(en_it == entries.end()) //nothing's been found
  55. {
  56. tlog1 << "Cannot find file: " << fname << std::endl;
  57. return NULL;
  58. }
  59. Entry ourEntry = *en_it;
  60. if(length) *length = ourEntry.realSize;
  61. mutex->lock();
  62. unsigned char * outp;
  63. if (ourEntry.offset<0) //file is in the sprites/ folder; no compression
  64. {
  65. int result;
  66. outp = new unsigned char[ourEntry.realSize];
  67. FILE * f = fopen((myDir + "/" + ourEntry.realName).c_str(), "rb");
  68. if (f)
  69. {
  70. result = fread(outp,1,ourEntry.realSize,f);
  71. fclose(f);
  72. }
  73. else
  74. result = -1;
  75. mutex->unlock();
  76. if(result<0)
  77. {
  78. tlog1<<"Error in file reading: " << myDir << "/" << ourEntry.name << std::endl;
  79. delete[] outp;
  80. return NULL;
  81. }
  82. else
  83. return outp;
  84. }
  85. else if (ourEntry.size==0) //file is not compressed
  86. {
  87. outp = new unsigned char[ourEntry.realSize];
  88. LOD.seekg(ourEntry.offset, std::ios::beg);
  89. LOD.read((char*)outp, ourEntry.realSize);
  90. mutex->unlock();
  91. return outp;
  92. }
  93. else //we will decompress file
  94. {
  95. outp = new unsigned char[ourEntry.size];
  96. LOD.seekg(ourEntry.offset, std::ios::beg);
  97. LOD.read((char*)outp, ourEntry.size);
  98. unsigned char * decomp = NULL;
  99. infs2(outp, ourEntry.size, ourEntry.realSize, decomp);
  100. mutex->unlock();
  101. delete[] outp;
  102. return decomp;
  103. }
  104. return NULL;
  105. }
  106. std::string CLodHandler::getFileName(std::string lodFile, LodFileType type)
  107. {
  108. convertName(lodFile);
  109. boost::unordered_set<Entry>::const_iterator it = entries.find(Entry(lodFile, type));
  110. if (it != entries.end())
  111. return it->realName;
  112. return "";
  113. }
  114. bool CLodHandler::haveFile(std::string name, LodFileType type)
  115. {
  116. convertName(name);
  117. return vstd::contains(entries, Entry(name, type));
  118. }
  119. DLL_EXPORT int CLodHandler::infs2(unsigned char * in, int size, int realSize, unsigned char *& out, int wBits)
  120. {
  121. int ret;
  122. unsigned have;
  123. z_stream strm;
  124. out = new unsigned char [realSize];
  125. int latPosOut = 0;
  126. /* allocate inflate state */
  127. strm.zalloc = Z_NULL;
  128. strm.zfree = Z_NULL;
  129. strm.opaque = Z_NULL;
  130. strm.avail_in = 0;
  131. strm.next_in = Z_NULL;
  132. ret = inflateInit2(&strm, wBits);
  133. if (ret != Z_OK)
  134. return ret;
  135. int chunkNumber = 0;
  136. do
  137. {
  138. if(size < chunkNumber * NLoadHandlerHelp::fCHUNK)
  139. break;
  140. strm.avail_in = std::min(NLoadHandlerHelp::fCHUNK, size - chunkNumber * NLoadHandlerHelp::fCHUNK);
  141. if (strm.avail_in == 0)
  142. break;
  143. strm.next_in = in + chunkNumber * NLoadHandlerHelp::fCHUNK;
  144. /* run inflate() on input until output buffer not full */
  145. do
  146. {
  147. strm.avail_out = realSize - latPosOut;
  148. strm.next_out = out + latPosOut;
  149. ret = inflate(&strm, Z_NO_FLUSH);
  150. //assert(ret != Z_STREAM_ERROR); /* state not clobbered */
  151. bool breakLoop = false;
  152. switch (ret)
  153. {
  154. case Z_STREAM_END:
  155. breakLoop = true;
  156. break;
  157. case Z_NEED_DICT:
  158. ret = Z_DATA_ERROR; /* and fall through */
  159. case Z_DATA_ERROR:
  160. case Z_MEM_ERROR:
  161. (void)inflateEnd(&strm);
  162. return ret;
  163. }
  164. if(breakLoop)
  165. break;
  166. have = realSize - latPosOut - strm.avail_out;
  167. latPosOut += have;
  168. } while (strm.avail_out == 0);
  169. ++chunkNumber;
  170. /* done when inflate() says it's done */
  171. } while (ret != Z_STREAM_END);
  172. /* clean up and return */
  173. (void)inflateEnd(&strm);
  174. return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
  175. }
  176. void CLodHandler::extractFile(const std::string FName, const std::string name, LodFileType type)
  177. {
  178. int len; //length of file to write
  179. unsigned char * outp = giveFile(name, type, &len);
  180. std::ofstream out;
  181. out.open(FName.c_str(), std::ios::binary);
  182. if(!out.is_open())
  183. {
  184. tlog1<<"Unable to create "<<FName<<std::endl;
  185. }
  186. else
  187. {
  188. out.write(reinterpret_cast<char*>(outp), len);
  189. out.close();
  190. }
  191. }
  192. void CLodHandler::initEntry(Entry &e, std::string name)
  193. {
  194. std::string ext;
  195. convertName(name, &ext);
  196. e.name = name;
  197. std::map<std::string, LodFileType>::iterator it = extMap.find(ext);
  198. if (it == extMap.end())
  199. e.type = FILE_OTHER;
  200. else
  201. e.type = it->second;
  202. }
  203. void CLodHandler::init(const std::string lodFile, const std::string dirName)
  204. {
  205. #define EXT(NAME, TYPE) extMap.insert(std::pair<std::string, LodFileType>(NAME, TYPE));
  206. EXT(".TXT", FILE_TEXT);
  207. EXT(".JSON",FILE_TEXT);
  208. EXT(".DEF", FILE_ANIMATION);
  209. EXT(".MSK", FILE_MASK);
  210. EXT(".MSG", FILE_MASK);
  211. EXT(".H3C", FILE_CAMPAIGN);
  212. EXT(".H3M", FILE_MAP);
  213. EXT(".FNT", FILE_FONT);
  214. EXT(".BMP", FILE_GRAPHICS);
  215. EXT(".JPG", FILE_GRAPHICS);
  216. EXT(".PCX", FILE_GRAPHICS);
  217. EXT(".PNG", FILE_GRAPHICS);
  218. EXT(".TGA", FILE_GRAPHICS);
  219. #undef EXT
  220. myDir = dirName;
  221. LOD.open(lodFile.c_str(), std::ios::in | std::ios::binary);
  222. if (!LOD.is_open())
  223. {
  224. tlog1 << "Cannot open " << lodFile << std::endl;
  225. return;
  226. }
  227. Uint32 temp;
  228. LOD.seekg(8);
  229. LOD.read((char *)&temp, 4);
  230. totalFiles = SDL_SwapLE32(temp);
  231. LOD.seekg(0x5c, std::ios::beg);
  232. if(!LOD)
  233. {
  234. tlog2 << lodFile << " doesn't store anything!\n";
  235. return;
  236. }
  237. struct LodEntry *lodEntries = new struct LodEntry[totalFiles];
  238. LOD.read((char *)lodEntries, sizeof(struct LodEntry) * totalFiles);
  239. for (unsigned int i=0; i<totalFiles; i++)
  240. {
  241. Entry entry;
  242. initEntry(entry, lodEntries[i].filename);
  243. entry.offset= SDL_SwapLE32(lodEntries[i].offset);
  244. entry.realSize = SDL_SwapLE32(lodEntries[i].uncompressedSize);
  245. entry.size = SDL_SwapLE32(lodEntries[i].size);
  246. entries.insert(entry);
  247. }
  248. delete [] lodEntries;
  249. boost::filesystem::recursive_directory_iterator enddir;
  250. if(boost::filesystem::exists(dirName))
  251. {
  252. std::vector<std::string> path;
  253. for (boost::filesystem::recursive_directory_iterator dir(dirName); dir!=enddir; dir++)
  254. {
  255. //If a directory was found - add name to vector to recreate full path later
  256. if (boost::filesystem::is_directory(dir->status()))
  257. {
  258. path.resize(dir.level()+1);
  259. path.back() = dir->path().leaf();
  260. }
  261. if(boost::filesystem::is_regular(dir->status()))
  262. {
  263. Entry e;
  264. //we can't get relative path with boost at the moment - need to create path to file manually
  265. for (size_t i=0; i<dir.level() && i<path.size(); i++)
  266. e.realName += path[i] + '/';
  267. e.realName += dir->path().leaf();
  268. initEntry(e, e.realName);
  269. if(vstd::contains(entries, e)) //file present in .lod - overwrite its entry
  270. entries.erase(e);
  271. e.offset = -1;
  272. e.realSize = e.size = boost::filesystem::file_size(dir->path());
  273. entries.insert(e);
  274. }
  275. }
  276. }
  277. else
  278. {
  279. if (!dirName.empty())
  280. tlog1<<"Warning: No "+dirName+"/ folder!"<<std::endl;
  281. }
  282. }
  283. std::string CLodHandler::getTextFile(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. }