File: ReadMap.cpp

package info (click to toggle)
spring 88.0%2Bdfsg1-1.1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 41,524 kB
  • sloc: cpp: 343,114; ansic: 38,414; python: 12,257; java: 12,203; awk: 5,748; sh: 1,204; xml: 997; perl: 405; objc: 192; makefile: 181; php: 134; sed: 2
file content (502 lines) | stat: -rwxr-xr-x 16,161 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */


#include <cstdlib>
#include "System/mmgr.h"

#include "ReadMap.h"
#include "MapDamage.h"
#include "MapInfo.h"
#include "MetalMap.h"
#include "SM3/SM3Map.h"
#include "SMF/SMFReadMap.h"
#include "lib/gml/gmlmut.h"
#include "Game/LoadScreen.h"
#include "System/bitops.h"
#include "System/EventHandler.h"
#include "System/Exceptions.h"
#include "System/myMath.h"
#include "System/TimeProfiler.h"
#include "System/FileSystem/ArchiveScanner.h"
#include "System/FileSystem/FileHandler.h"
#include "System/FileSystem/FileSystem.h"
#include "System/LoadSave/LoadSaveInterface.h"
#include "System/Misc/RectangleOptimizer.h"

#ifdef USE_UNSYNCED_HEIGHTMAP
#include "Game/GlobalUnsynced.h"
#include "Sim/Misc/LosHandler.h"
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

// assigned to in CGame::CGame ("readmap = CReadMap::LoadMap(mapname)")
CReadMap* readmap = 0;

CR_BIND_INTERFACE(CReadMap)
CR_REG_METADATA(CReadMap, (
	CR_SERIALIZER(Serialize)
));


CReadMap* CReadMap::LoadMap(const std::string& mapname)
{
	if (mapname.length() < 3)
		throw content_error("CReadMap::LoadMap(): mapname '" + mapname + "' too short");

	const std::string extension = FileSystem::GetExtension(mapname);

	CReadMap* rm = NULL;

	if (extension == "sm3") {
		rm = new CSM3ReadMap(mapname);
	} else {
		rm = new CSMFReadMap(mapname);
	}

	if (!rm) {
		return NULL;
	}

	/* Read metal map */
	MapBitmapInfo mbi;
	unsigned char* metalmapPtr = rm->GetInfoMap("metal", &mbi);

	assert(mbi.width == (rm->width >> 1));
	assert(mbi.height == (rm->height >> 1));

	rm->metalMap = new CMetalMap(metalmapPtr, mbi.width, mbi.height, mapInfo->map.maxMetal);

	if (metalmapPtr != NULL) {
		rm->FreeInfoMap("metal", metalmapPtr);
	}


	/* Read type map */
	MapBitmapInfo tbi;
	unsigned char* typemapPtr = rm->GetInfoMap("type", &tbi);

	if (typemapPtr && tbi.width == (rm->width >> 1) && tbi.height == (rm->height >> 1)) {
		assert(gs->hmapx == tbi.width && gs->hmapy == tbi.height);
		rm->typeMap.resize(tbi.width * tbi.height);
		memcpy(&rm->typeMap[0], typemapPtr, tbi.width * tbi.height);
	} else
		throw content_error("Bad/no terrain type map.");

	if (typemapPtr)
		rm->FreeInfoMap("type", typemapPtr);

	return rm;
}


void CReadMap::Serialize(creg::ISerializer& s)
{
	// remove the const
	const float* cshm = GetCornerHeightMapSynced();
	      float*  shm = const_cast<float*>(cshm);

	s.Serialize(shm, 4 * gs->mapxp1 * gs->mapyp1);

	if (!s.IsWriting())
		mapDamage->RecalcArea(2, gs->mapx - 3, 2, gs->mapy - 3);
}


CReadMap::CReadMap()
	: metalMap(NULL)
	, width(0)
	, height(0)
	, initMinHeight(0.0f)
	, initMaxHeight(0.0f)
	, currMinHeight(0.0f)
	, currMaxHeight(0.0f)
	, mapChecksum(0)
	, heightMapSynced(NULL)
	, heightMapUnsynced(NULL)
{
}


CReadMap::~CReadMap()
{
	delete metalMap;
}


void CReadMap::Initialize()
{
	// set global map info (TODO: move these to ReadMap!)
	gs->mapx = width;
	gs->mapxm1 = width - 1;
	gs->mapxp1 = width + 1;
	gs->mapy = height;
	gs->mapym1 = height - 1;
	gs->mapyp1 = height + 1;
	gs->mapSquares = gs->mapx * gs->mapy;
	gs->hmapx = gs->mapx >> 1;
	gs->hmapy = gs->mapy >> 1;
	gs->pwr2mapx = next_power_of_2(gs->mapx);
	gs->pwr2mapy = next_power_of_2(gs->mapy);

	{
		char loadMsg[512];
		const char* fmtString = "Loading Map (%u MB)";
		unsigned int reqMemFootPrintKB =
			((( gs->mapxp1)   * gs->mapyp1  * 2     * sizeof(float))         / 1024) +   // cornerHeightMap{Synced, Unsynced}
			((( gs->mapxp1)   * gs->mapyp1  *         sizeof(float))         / 1024) +   // originalHeightMap
			((  gs->mapx      * gs->mapy    * 2 * 2 * sizeof(float3))        / 1024) +   // faceNormals{Synced, Unsynced}
			((  gs->mapx      * gs->mapy    * 2     * sizeof(float3))        / 1024) +   // centerNormals{Synced, Unsynced}
			((( gs->mapxp1)   * gs->mapyp1          * sizeof(float3))        / 1024) +   // VisVertexNormals
			((  gs->mapx      * gs->mapy            * sizeof(float))         / 1024) +   // centerHeightMap
			((  gs->hmapx     * gs->hmapy           * sizeof(float))         / 1024) +   // slopeMap
			((  gs->hmapx     * gs->hmapy           * sizeof(float))         / 1024) +   // MetalMap::extractionMap
			((  gs->hmapx     * gs->hmapy           * sizeof(unsigned char)) / 1024);    // MetalMap::metalMap

		// mipCenterHeightMaps[i]
		for (int i = 1; i < numHeightMipMaps; i++) {
			reqMemFootPrintKB += ((((gs->mapx >> i) * (gs->mapy >> i)) * sizeof(float)) / 1024);
		}

		sprintf(loadMsg, fmtString, reqMemFootPrintKB / 1024);
		loadscreen->SetLoadMessage(loadMsg);
	}

	float3::maxxpos = gs->mapx * SQUARE_SIZE - 1;
	float3::maxzpos = gs->mapy * SQUARE_SIZE - 1;

	originalHeightMap.resize(gs->mapxp1 * gs->mapyp1);
	faceNormalsSynced.resize(gs->mapx * gs->mapy * 2);
	faceNormalsUnsynced.resize(gs->mapx * gs->mapy * 2);
	centerNormalsSynced.resize(gs->mapx * gs->mapy);
	centerNormalsUnsynced.resize(gs->mapx * gs->mapy);
	centerHeightMap.resize(gs->mapx * gs->mapy);

	mipCenterHeightMaps.resize(numHeightMipMaps - 1);
	mipPointerHeightMaps.resize(numHeightMipMaps, NULL);
	mipPointerHeightMaps[0] = &centerHeightMap[0];

	for (int i = 1; i < numHeightMipMaps; i++) {
		mipCenterHeightMaps[i - 1].resize((gs->mapx >> i) * (gs->mapy >> i));
		mipPointerHeightMaps[i] = &mipCenterHeightMaps[i - 1][0];
	}

	slopeMap.resize(gs->hmapx * gs->hmapy);
	visVertexNormals.resize(gs->mapxp1 * gs->mapyp1);

	assert(heightMapSynced != NULL);
	assert(heightMapUnsynced != NULL);

	CalcHeightmapChecksum();
	UpdateHeightMapSynced(0, 0, gs->mapx, gs->mapy);
	//FIXME can't call that yet cause sky & skyLight aren't created yet (crashes in SMFReadMap.cpp)
	//UpdateDraw(); 
}


void CReadMap::CalcHeightmapChecksum()
{
	const float* heightmap = GetCornerHeightMapSynced();

	initMinHeight =  std::numeric_limits<float>::max();
	initMaxHeight = -std::numeric_limits<float>::max();

	mapChecksum = 0;
	for (int i = 0; i < (gs->mapxp1 * gs->mapyp1); ++i) {
		originalHeightMap[i] = heightmap[i];
		if (heightmap[i] < initMinHeight) { initMinHeight = heightmap[i]; }
		if (heightmap[i] > initMaxHeight) { initMaxHeight = heightmap[i]; }
		mapChecksum +=  (unsigned int) (heightmap[i] * 100);
		mapChecksum ^= *(unsigned int*) &heightmap[i];
	}

	currMinHeight = initMinHeight;
	currMaxHeight = initMaxHeight;
}

void CReadMap::UpdateDraw() {
	std::list<HeightMapUpdate> ushmu;
	std::list<HeightMapUpdate>::const_iterator ushmuIt;

	{
		GML_STDMUTEX_LOCK(map); // UpdateDraw

		static const float MIN_UNSYNCED_UPDATES_RATIO = 0.0625f;
		static const size_t MIN_UNSYNCED_UPDATES = 32U;
		       const size_t maxUpdates = unsyncedHeightMapUpdates.size();
		       const size_t minUpdates = maxUpdates * MIN_UNSYNCED_UPDATES_RATIO;
		       const size_t numUpdates = std::min(maxUpdates, std::max(MIN_UNSYNCED_UPDATES, minUpdates));

		// process the first <numUpdates> pending updates
		for (size_t n = 0; n < numUpdates; n++) {
			ushmu.push_back(unsyncedHeightMapUpdates.front());
			unsyncedHeightMapUpdates.pop_front();
		}
	}

	SCOPED_TIMER("ReadMap::UpdateHeightMapUnsynced");

	for (ushmuIt = ushmu.begin(); ushmuIt != ushmu.end(); ++ushmuIt) {
		UpdateHeightMapUnsynced(*ushmuIt);

		const SRectangle rect(ushmuIt->x1, ushmuIt->y1, ushmuIt->x2, ushmuIt->y2);
		eventHandler.UnsyncedHeightMapUpdate(rect);
	}
}



void CReadMap::UpdateHeightMapSynced(int x1, int z1, int x2, int z2)
{
	if ((x1 >= x2) || (z1 >= z2)) {
		// do not bother with zero-area updates
		return;
	}

	SCOPED_TIMER("ReadMap::UpdateHeightMapSynced");

	x1 = std::max(         0, x1 - 1);
	z1 = std::max(         0, z1 - 1);
	x2 = std::min(gs->mapxm1, x2 + 1);
	z2 = std::min(gs->mapym1, z2 + 1);

	UpdateCenterHeightmap(x1, z1, x2, z2);
	UpdateMipHeightmaps(x1, z1, x2, z2);
	UpdateFaceNormals(x1, z1, x2, z2);
	UpdateSlopemap(x1, z1, x2, z2); // must happen after UpdateFaceNormals()!

	// push the unsynced update
	PushVisibleHeightMapUpdate(x1, z1,  x2, z2,  false);
}


void CReadMap::UpdateCenterHeightmap(const int x1, const int z1, const int x2, const int z2)
{
	const float* heightmapSynced = GetCornerHeightMapSynced();

	for (int y = z1; y <= z2; y++) {
		for (int x = x1; x <= x2; x++) {
			const int idxTL = (y    ) * gs->mapxp1 + x;
			const int idxTR = (y    ) * gs->mapxp1 + x + 1;
			const int idxBL = (y + 1) * gs->mapxp1 + x;
			const int idxBR = (y + 1) * gs->mapxp1 + x + 1;

			const float height =
				heightmapSynced[idxTL] +
				heightmapSynced[idxTR] +
				heightmapSynced[idxBL] +
				heightmapSynced[idxBR];
			centerHeightMap[y * gs->mapx + x] = height * 0.25f;
		}
	}
}


void CReadMap::UpdateMipHeightmaps(const int x1, const int z1, const int x2, const int z2)
{
	for (int i = 0; i < numHeightMipMaps - 1; i++) {
		const int hmapx = gs->mapx >> i;

		for (int y = ((z1 >> i) & (~1)); y < (z2 >> i); y += 2) {
			for (int x = ((x1 >> i) & (~1)); x < (x2 >> i); x += 2) {
				const float height =
					mipPointerHeightMaps[i][(x    ) + (y    ) * hmapx] +
					mipPointerHeightMaps[i][(x    ) + (y + 1) * hmapx] +
					mipPointerHeightMaps[i][(x + 1) + (y    ) * hmapx] +
					mipPointerHeightMaps[i][(x + 1) + (y + 1) * hmapx];
				mipPointerHeightMaps[i + 1][(x / 2) + (y / 2) * hmapx / 2] = height * 0.25f;
			}
		}
	}
}


void CReadMap::UpdateFaceNormals(int x1, int z1, int x2, int z2)
{
	const float* heightmapSynced = GetCornerHeightMapSynced();

	z1 = std::max(         0, z1 - 1);
	x1 = std::max(         0, x1 - 1);
	z2 = std::min(gs->mapym1, z2 + 1);
	x2 = std::min(gs->mapxm1, x2 + 1);

	int y;
	#pragma omp parallel for private(y)
	for (y = z1; y <= z2; y++) {
		float3 fnTL;
		float3 fnBR;

		for (int x = x1; x <= x2; x++) {
			const int idxTL = (y    ) * gs->mapxp1 + x; // TL
			const int idxBL = (y + 1) * gs->mapxp1 + x; // BL

			const float& hTL = heightmapSynced[idxTL    ];
			const float& hTR = heightmapSynced[idxTL + 1];
			const float& hBL = heightmapSynced[idxBL    ];
			const float& hBR = heightmapSynced[idxBL + 1];

			// normal of top-left triangle (face) in square
			//
			//  *---> e1
			//  |
			//  |
			//  v
			//  e2
			//const float3 e1( SQUARE_SIZE, hTR - hTL,           0);
			//const float3 e2(           0, hBL - hTL, SQUARE_SIZE);
			//const float3 fnTL = (e2.cross(e1)).Normalize();
			fnTL.y = SQUARE_SIZE;
			fnTL.x = - (hTR - hTL);
			fnTL.z = - (hBL - hTL);
			fnTL.Normalize();

			// normal of bottom-right triangle (face) in square
			//
			//         e3
			//         ^
			//         |
			//         |
			//  e4 <---*
			//const float3 e3(-SQUARE_SIZE, hBL - hBR,           0);
			//const float3 e4(           0, hTR - hBR,-SQUARE_SIZE);
			//const float3 fnBR = (e4.cross(e3)).Normalize();
			fnBR.y = SQUARE_SIZE;
			fnBR.x = (hBL - hBR);
			fnBR.z = (hTR - hBR);
			fnBR.Normalize();

			faceNormalsSynced[(y * gs->mapx + x) * 2    ] = fnTL;
			faceNormalsSynced[(y * gs->mapx + x) * 2 + 1] = fnBR;

			// square-normal
			centerNormalsSynced[y * gs->mapx + x] = (fnTL + fnBR).Normalize();
		}
	}
}


void CReadMap::UpdateSlopemap(const int x1, const int z1, const int x2, const int z2)
{
	for (int y = std::max(0, (z1 / 2) - 1); y <= std::min(gs->hmapy - 1, (z2 / 2) + 1); y++) {
		for (int x = std::max(0, (x1 / 2) - 1); x <= std::min(gs->hmapx - 1, (x2 / 2) + 1); x++) {
			const int idx0 = (y*2    ) * (gs->mapx) + x*2;
			const int idx1 = (y*2 + 1) * (gs->mapx) + x*2;

			float avgslope = 0.0f;
			avgslope += faceNormalsSynced[(idx0    ) * 2    ].y;
			avgslope += faceNormalsSynced[(idx0    ) * 2 + 1].y;
			avgslope += faceNormalsSynced[(idx0 + 1) * 2    ].y;
			avgslope += faceNormalsSynced[(idx0 + 1) * 2 + 1].y;
			avgslope += faceNormalsSynced[(idx1    ) * 2    ].y;
			avgslope += faceNormalsSynced[(idx1    ) * 2 + 1].y;
			avgslope += faceNormalsSynced[(idx1 + 1) * 2    ].y;
			avgslope += faceNormalsSynced[(idx1 + 1) * 2 + 1].y;
			avgslope *= 0.125f;

			float maxslope =              faceNormalsSynced[(idx0    ) * 2    ].y;
			maxslope = std::min(maxslope, faceNormalsSynced[(idx0    ) * 2 + 1].y);
			maxslope = std::min(maxslope, faceNormalsSynced[(idx0 + 1) * 2    ].y);
			maxslope = std::min(maxslope, faceNormalsSynced[(idx0 + 1) * 2 + 1].y);
			maxslope = std::min(maxslope, faceNormalsSynced[(idx1    ) * 2    ].y);
			maxslope = std::min(maxslope, faceNormalsSynced[(idx1    ) * 2 + 1].y);
			maxslope = std::min(maxslope, faceNormalsSynced[(idx1 + 1) * 2    ].y);
			maxslope = std::min(maxslope, faceNormalsSynced[(idx1 + 1) * 2 + 1].y);

			// smooth it a bit, so small holes don't block huge tanks
			const float lerp = maxslope / avgslope;
			const float slope = mix(maxslope, avgslope, lerp);

			slopeMap[y * gs->hmapx + x] = 1.0f - slope;
		}
	}

}


void CReadMap::PushVisibleHeightMapUpdate(int x1, int z1,  int x2, int z2,  bool losMapCall)
{
	GML_STDMUTEX_LOCK(map); // PushVisibleHeightMapUpdate

	#ifdef USE_UNSYNCED_HEIGHTMAP
	if (gs->frameNum <= 0) {
		// NOTE:
		//     loshandler does not exist on startup when the map is loaded
		//     rather than duplicating LosHandler member variables here to
		//     avoid this special case, just push the entire update at once
		unsyncedHeightMapUpdates.push_back(HeightMapUpdate(x1, x2,  z1, z2,  true));
	} else {
		static const int losSqSizeX = loshandler->losSizeX;
		static const int losSqSizeY = loshandler->losSizeY;
		static const int losSquaresX = (gs->mapx / losSqSizeX);
		static const int losSquaresY = (gs->mapy / losSqSizeY);
		static std::vector<HeightMapUpdateFilter> updateFilters((losSquaresX + 1) * (losSquaresY + 1));

		// split the update into multiple invididual (los-square) chunks:
		// we need to do this because the reduced-rate unsynced updating
		// can mean a chunk has gone out of LOS again by the time it gets
		// processed in UpdateHeightMapUnsynced
		//
		// terrain deformations can overlap, so also check if chunks have
		// have not already been marked before pushing them
		//
		// find the losMap squares covered by the update rectangle
		const int lmxTL = x1 / losSqSizeX, lmxBR = x2 / losSqSizeX;
		const int lmzTL = z1 / losSqSizeY, lmzBR = z2 / losSqSizeY;

		for (int lmx = lmxTL; lmx <= lmxBR; ++lmx) {
			const int hmx = lmx * losSqSizeX;

			for (int lmz = lmzTL; lmz <= lmzBR; ++lmz) {
				HeightMapUpdateFilter& f = updateFilters[lmz * losSquaresX + lmx];

				// if the unsynced heightmap has not actually been modified for this LOS block, skip it
				// (assumes deformations occur first and LOS is obtained *after* ::update has been set)
				if (losMapCall && !f.update)
					continue;

				// note: calls can come from losMap even when spectatingFullView
				const int hmz = lmz * losSqSizeY;
				const bool inlos = losMapCall || gu->spectatingFullView || loshandler->InLos(hmx, hmz, gu->myAllyTeam);

				// create a new filter for this los-square
				HeightMapUpdateFilter fnew(
					Clamp(hmx, x1, x2), Clamp(hmx + losSqSizeX - 1, x1, x2),
					Clamp(hmz, z1, z2), Clamp(hmz + losSqSizeY - 1, z1, z2),
					true
				);

				if (!inlos) {
					// the heightmap has been modified, but the block is not currently in LOS
					// if this block was never visited (ever, or since coming into LOS before)
					// then set a filter for it, otherwise expand (this heightmap update might
					// cover a larger area than the previous)
					if (!f.update) {
						f = fnew;
					} else {
						f.Expand(fnew);
					}
				} else if (losMapCall) {
					// the block has now come into LOS: any subsequent deformations whose area
					// includes this block do not need to update the squares covered by it (so
					// long as it remains visible)
					fnew = f;
					f.update = false;
				}

				HeightMapUpdate hmUpdate = HeightMapUpdate(
					fnew.minx, std::min(gs->mapxm1, fnew.maxx), 
					fnew.miny, std::min(gs->mapym1, fnew.maxy),
					inlos
				);
				unsyncedHeightMapUpdates.push_back(hmUpdate);
			}
		}
	}
	#else
	// only reached from UpdateHeightMapSynced, los-state is irrelevant
	// (however, could still split chunk to save some CPU in UpdateDraw)
	unsyncedHeightMapUpdates.push_back(HeightMapUpdate(x1, x2,  z1, z2));
	#endif
}