1 /* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
2 
3 #include <assert.h>
4 #include <zlib.h>
5 
6 #include "GameData.h"
7 
8 #include "Net/Protocol/BaseNetProtocol.h"
9 #include "System/Net/PackPacket.h"
10 #include "System/Net/UnpackPacket.h"
11 
12 using namespace netcode;
13 
GameData()14 GameData::GameData()
15 	: mapChecksum(0)
16 	, modChecksum(0)
17 	, randomSeed(0)
18 {
19 }
20 
GameData(boost::shared_ptr<const RawPacket> pckt)21 GameData::GameData(boost::shared_ptr<const RawPacket> pckt)
22 {
23 	assert(pckt->data[0] == NETMSG_GAMEDATA);
24 
25 	UnpackPacket packet(pckt, 3);
26 	boost::uint16_t compressedSize;
27 	packet >> compressedSize;
28 	compressed.resize(compressedSize);
29 	packet >> compressed;
30 
31 	// "the LSB does not describe any mechanism by which a
32 	// compressor can communicate the size required to the
33 	// uncompressor" ==> we must reserve some fixed-length
34 	// buffer (starting at 256K bytes to handle very large
35 	// scripts) for each new decompression attempt
36 	unsigned long bufSize = 256 * 1024;
37 	unsigned long rawSize = bufSize;
38 
39 	std::vector<boost::uint8_t> buffer(bufSize);
40 
41 	int ret;
42 	while ((ret = uncompress(&buffer[0], &rawSize, &compressed[0], compressed.size())) == Z_BUF_ERROR) {
43 		bufSize *= 2;
44 		rawSize  = bufSize;
45 
46 		buffer.resize(bufSize);
47 	}
48 	if (ret != Z_OK)
49 		throw netcode::UnpackPacketException("Error while decompressing GameData");
50 
51 	setupText = reinterpret_cast<char*>(&buffer[0]);
52 
53 	packet >> mapChecksum;
54 	packet >> modChecksum;
55 	packet >> randomSeed;
56 }
57 
Pack() const58 const netcode::RawPacket* GameData::Pack() const
59 {
60 	if (compressed.empty())
61 	{
62 		long unsigned bufsize = compressBound(setupText.size());
63 		compressed.resize(bufsize);
64 		const int error = compress(&compressed[0], &bufsize, reinterpret_cast<const boost::uint8_t*>(setupText.c_str()), setupText.length());
65 		compressed.resize(bufsize);
66 		assert(error == Z_OK);
67 	}
68 
69 	unsigned short size = 3 + 2*sizeof(unsigned) + compressed.size()+2 + 4;
70 	PackPacket* buffer = new PackPacket(size, NETMSG_GAMEDATA);
71 	*buffer << size;
72 	*buffer << boost::uint16_t(compressed.size());
73 	*buffer << compressed;
74 	*buffer << mapChecksum;
75 	*buffer << modChecksum;
76 	*buffer << randomSeed;
77 	return buffer;
78 }
79 
SetSetup(const std::string & newSetup)80 void GameData::SetSetup(const std::string& newSetup)
81 {
82 	setupText = newSetup;
83 	compressed.clear();
84 }
85 
SetMapChecksum(const unsigned checksum)86 void GameData::SetMapChecksum(const unsigned checksum)
87 {
88 	mapChecksum = checksum;
89 }
90 
SetModChecksum(const unsigned checksum)91 void GameData::SetModChecksum(const unsigned checksum)
92 {
93 	modChecksum = checksum;
94 }
95 
SetRandomSeed(const unsigned seed)96 void GameData::SetRandomSeed(const unsigned seed)
97 {
98 	randomSeed = seed;
99 }
100