summaryrefslogtreecommitdiffstats
path: root/src/Generating/Prefab.cpp
blob: de2f5f95d5e83c4eb9fc3cc315538faa8d12ef01 (plain) (blame)
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
503
504
505
506
507
508
509
510
511
512

// Prefab.cpp

/*
Implements the cPrefab class, representing a cPiece descendant for the cPieceGenerator that
uses a prefabricate in a cBlockArea for drawing itself.
*/

#include "Globals.h"
#include "Prefab.h"
#include "../WorldStorage/SchematicFileSerializer.h"
#include "ChunkDesc.h"





cPrefab::cPrefab(const cPrefab::sDef & a_Def) :
	m_Size(a_Def.m_SizeX, a_Def.m_SizeY, a_Def.m_SizeZ),
	m_HitBox(
		a_Def.m_HitboxMinX, a_Def.m_HitboxMinY, a_Def.m_HitboxMinZ,
		a_Def.m_HitboxMaxX, a_Def.m_HitboxMaxY, a_Def.m_HitboxMaxZ
	),
	m_AllowedRotations(a_Def.m_AllowedRotations),
	m_MergeStrategy(a_Def.m_MergeStrategy),
	m_ExtendFloorStrategy(a_Def.m_ExtendFloorStrategy),
	m_DefaultWeight(a_Def.m_DefaultWeight),
	m_AddWeightIfSame(a_Def.m_AddWeightIfSame),
	m_MoveToGround(a_Def.m_MoveToGround)
{
	m_BlockArea[0].Create(m_Size);
	CharMap cm;
	ParseCharMap(cm, a_Def.m_CharMap);
	ParseBlockImage(cm, a_Def.m_Image);
	ParseConnectors(a_Def.m_Connectors);
	ParseDepthWeight(a_Def.m_DepthWeight);

	AddRotatedBlockAreas();
}





cPrefab::cPrefab(const cBlockArea & a_Image, int a_AllowedRotations) :
	m_Size(a_Image.GetSize()),
	m_AllowedRotations(a_AllowedRotations),
	m_MergeStrategy(cBlockArea::msOverwrite),
	m_ExtendFloorStrategy(efsNone),
	m_DefaultWeight(1),
	m_AddWeightIfSame(0),
	m_MoveToGround(false)
{
	m_HitBox.p1.Set(0, 0, 0);
	m_HitBox.p2.Set(m_Size.x - 1, m_Size.y - 1, m_Size.z - 1);
	m_BlockArea[0].CopyFrom(a_Image);
	AddRotatedBlockAreas();
}





cPrefab::cPrefab(const cBlockArea & a_Image) :
	m_Size(a_Image.GetSize()),
	m_AllowedRotations(0),
	m_MergeStrategy(cBlockArea::msOverwrite),
	m_ExtendFloorStrategy(efsNone),
	m_DefaultWeight(1),
	m_AddWeightIfSame(0),
	m_MoveToGround(false)
{
	m_HitBox.p1.Set(0, 0, 0);
	m_HitBox.p2.Set(m_Size.x - 1, m_Size.y - 1, m_Size.z - 1);
	m_BlockArea[0].CopyFrom(a_Image);
}





cPrefab::cPrefab(const AString & a_BlockDefinitions, const AString & a_BlockData, int a_SizeX, int a_SizeY, int a_SizeZ) :
	m_Size(a_SizeX, a_SizeY, a_SizeZ),
	m_AllowedRotations(0),
	m_MergeStrategy(cBlockArea::msOverwrite),
	m_ExtendFloorStrategy(efsNone),
	m_DefaultWeight(1),
	m_AddWeightIfSame(0),
	m_MoveToGround(false)
{
	m_HitBox.p1.Set(0, 0, 0);
	m_HitBox.p2.Set(m_Size.x - 1, m_Size.y - 1, m_Size.z - 1);
	m_BlockArea[0].Create(m_Size);
	CharMap cm;
	ParseCharMap(cm, a_BlockDefinitions.c_str());
	ParseBlockImage(cm, a_BlockData.c_str());
}





void cPrefab::AddRotatedBlockAreas(void)
{
	// 1 CCW rotation:
	if ((m_AllowedRotations & 0x01) != 0)
	{
		m_BlockArea[1].CopyFrom(m_BlockArea[0]);
		m_BlockArea[1].RotateCCW();
	}

	// 2 rotations are the same as mirroring twice; mirroring is faster because it has no reallocations
	if ((m_AllowedRotations & 0x02) != 0)
	{
		m_BlockArea[2].CopyFrom(m_BlockArea[0]);
		m_BlockArea[2].MirrorXY();
		m_BlockArea[2].MirrorYZ();
	}

	// 3 CCW rotations = 1 CW rotation:
	if ((m_AllowedRotations & 0x04) != 0)
	{
		m_BlockArea[3].CopyFrom(m_BlockArea[0]);
		m_BlockArea[3].RotateCW();
	}
}





void cPrefab::Draw(cChunkDesc & a_Dest, const cPlacedPiece * a_Placement) const
{
	Draw(a_Dest, a_Placement->GetCoords(), a_Placement->GetNumCCWRotations());
}




void cPrefab::Draw(cChunkDesc & a_Dest, const Vector3i & a_Placement, int a_NumRotations) const
{
	// Draw the basic image:
	Vector3i Placement(a_Placement);
	int ChunkStartX = a_Dest.GetChunkX() * cChunkDef::Width;
	int ChunkStartZ = a_Dest.GetChunkZ() * cChunkDef::Width;
	Placement.Move(-ChunkStartX, 0, -ChunkStartZ);
	const cBlockArea & Image = m_BlockArea[a_NumRotations];

	// If the placement is outside this chunk, bail out:
	if (
		(Placement.x > cChunkDef::Width) || (Placement.x + Image.GetSizeX() < 0) ||
		(Placement.z > cChunkDef::Width) || (Placement.z + Image.GetSizeZ() < 0)
	)
	{
		return;
	}

	// Write the image:
	a_Dest.WriteBlockArea(Image, Placement.x, Placement.y, Placement.z, m_MergeStrategy);

	// If requested, draw the floor (from the bottom of the prefab down to the nearest non-air)
	switch (m_ExtendFloorStrategy)
	{
		case efsNone: break;  // Nothing needed
		case efsRepeatBottomTillNonAir:
		{
			int MaxX = Image.GetSizeX();
			int MaxZ = Image.GetSizeZ();
			for (int z = 0; z < MaxZ; z++)
			{
				int RelZ = Placement.z + z;
				if ((RelZ < 0) || (RelZ >= cChunkDef::Width))
				{
					// Z coord outside the chunk
					continue;
				}
				for (int x = 0; x < MaxX; x++)
				{
					int RelX = Placement.x + x;
					if ((RelX < 0) || (RelX >= cChunkDef::Width))
					{
						// X coord outside the chunk
						continue;
					}
					BLOCKTYPE BlockType;
					NIBBLETYPE BlockMeta;
					Image.GetRelBlockTypeMeta(x, 0, z, BlockType, BlockMeta);
					if ((BlockType == E_BLOCK_AIR) || (BlockType == E_BLOCK_SPONGE))
					{
						// Do not expand air nor sponge blocks
						continue;
					}
					for (int y = Placement.y - 1; y >= 0; y--)
					{
						BLOCKTYPE ExistingBlock = a_Dest.GetBlockType(RelX, y, RelZ);
						if (ExistingBlock != E_BLOCK_AIR)
						{
							// End the expansion for this column, reached the end
							break;
						}
						a_Dest.SetBlockTypeMeta(RelX, y, RelZ, BlockType, BlockMeta);
					}  // for y
				}  // for x
			}  // for z
			break;
		}  // efsRepeatBottomTillNonAir

		case efsRepeatBottomTillSolid:
		{
			int MaxX = Image.GetSizeX();
			int MaxZ = Image.GetSizeZ();
			for (int z = 0; z < MaxZ; z++)
			{
				int RelZ = Placement.z + z;
				if ((RelZ < 0) || (RelZ >= cChunkDef::Width))
				{
					// Z coord outside the chunk
					continue;
				}
				for (int x = 0; x < MaxX; x++)
				{
					int RelX = Placement.x + x;
					if ((RelX < 0) || (RelX >= cChunkDef::Width))
					{
						// X coord outside the chunk
						continue;
					}
					BLOCKTYPE BlockType;
					NIBBLETYPE BlockMeta;
					Image.GetRelBlockTypeMeta(x, 0, z, BlockType, BlockMeta);
					if ((BlockType == E_BLOCK_AIR) || (BlockType == E_BLOCK_SPONGE))
					{
						// Do not expand air nor sponge blocks
						continue;
					}
					for (int y = Placement.y - 1; y >= 0; y--)
					{
						BLOCKTYPE ExistingBlock = a_Dest.GetBlockType(RelX, y, RelZ);
						if (cBlockInfo::IsSolid(ExistingBlock))
						{
							// End the expansion for this column, reached the end
							break;
						}
						a_Dest.SetBlockTypeMeta(RelX, y, RelZ, BlockType, BlockMeta);
					}  // for y
				}  // for x
			}  // for z
			break;
		}  // efsRepeatBottomTillSolid
	}
}





bool cPrefab::HasConnectorType(int a_ConnectorType) const
{
	for (cConnectors::const_iterator itr = m_Connectors.begin(), end = m_Connectors.end(); itr != end; ++itr)
	{
		if (itr->m_Type == a_ConnectorType)
		{
			return true;
		}
	}  // for itr - m_Connectors[]
	return false;
}





int cPrefab::GetPieceWeight(const cPlacedPiece & a_PlacedPiece, const cPiece::cConnector & a_ExistingConnector) const
{
	// Use the default or per-depth weight:
	cDepthWeight::const_iterator itr = m_DepthWeight.find(a_PlacedPiece.GetDepth() + 1);
	int res = (itr == m_DepthWeight.end()) ? m_DefaultWeight : itr->second;

	// If the piece is the same as the parent, apply the m_AddWeightIfSame modifier:
	const cPiece * ParentPiece = &a_PlacedPiece.GetPiece();
	const cPiece * ThisPiece = this;
	if (ThisPiece == ParentPiece)
	{
		res += m_AddWeightIfSame;
	}
	return res;
}





void cPrefab::SetDefaultWeight(int a_DefaultWeight)
{
	m_DefaultWeight = a_DefaultWeight;
}





void cPrefab::AddConnector(int a_RelX, int a_RelY, int a_RelZ, cPiece::cConnector::eDirection a_Direction, int a_Type)
{
	m_Connectors.push_back(cConnector(a_RelX, a_RelY, a_RelZ, a_Type, a_Direction));
}





void cPrefab::SetAllowedRotations(int a_AllowedRotations)
{
	m_AllowedRotations = a_AllowedRotations;
	AddRotatedBlockAreas();
}





void cPrefab::ParseCharMap(CharMap & a_CharMapOut, const char * a_CharMapDef)
{
	ASSERT(a_CharMapDef != nullptr);

	// Initialize the charmap to all-invalid values:
	for (size_t i = 0; i < ARRAYCOUNT(a_CharMapOut); i++)
	{
		a_CharMapOut[i].m_BlockType = 0;
		a_CharMapOut[i].m_BlockMeta = 16;  // Mark unassigned entries with a meta that is impossible otherwise
	}

	// Process the lines in the definition:
	AStringVector Lines = StringSplitAndTrim(a_CharMapDef, "\n");
	for (AStringVector::const_iterator itr = Lines.begin(), end = Lines.end(); itr != end; ++itr)
	{
		AStringVector CharDef = StringSplitAndTrim(*itr, ":");
		size_t NumElements = CharDef.size();
		if ((NumElements < 2) || CharDef[0].empty() || CharDef[1].empty())
		{
			LOGWARNING("Bad prefab CharMap definition line: \"%s\", skipping.", itr->c_str());
			continue;
		}
		unsigned char Src = static_cast<unsigned char>(CharDef[0][0]);
		ASSERT(a_CharMapOut[Src].m_BlockMeta == 16);  // This letter has not been assigned yet?
		a_CharMapOut[Src].m_BlockType = static_cast<BLOCKTYPE>(atoi(CharDef[1].c_str()));
		NIBBLETYPE BlockMeta = 0;
		if ((NumElements >= 3) && !CharDef[2].empty())
		{
			BlockMeta = static_cast<NIBBLETYPE>(atoi(CharDef[2].c_str()));
			ASSERT((BlockMeta <= 15));
		}
		a_CharMapOut[Src].m_BlockMeta = BlockMeta;
	}  // for itr - Lines[]
}





void cPrefab::ParseBlockImage(const CharMap & a_CharMap, const char * a_BlockImage)
{
	// Map each letter in the a_BlockImage (from the in-source definition) to real blocktype / blockmeta:
	for (int y = 0; y < m_Size.y; y++)
	{
		for (int z = 0; z < m_Size.z; z++)
		{
			const unsigned char * BlockImage = reinterpret_cast<const unsigned char *>(a_BlockImage + y * m_Size.x * m_Size.z + z * m_Size.x);
			for (int x = 0; x < m_Size.x; x++)
			{
				const sBlockTypeDef & MappedValue = a_CharMap[BlockImage[x]];
				ASSERT(MappedValue.m_BlockMeta != 16);  // Using a letter not defined in the CharMap?
				m_BlockArea[0].SetRelBlockTypeMeta(x, y, z, MappedValue.m_BlockType, MappedValue.m_BlockMeta);
			}
		}
	}
}





void cPrefab::ParseConnectors(const char * a_ConnectorsDef)
{
	ASSERT(a_ConnectorsDef != nullptr);

	AStringVector Lines = StringSplitAndTrim(a_ConnectorsDef, "\n");
	for (AStringVector::const_iterator itr = Lines.begin(), end = Lines.end(); itr != end; ++itr)
	{
		if (itr->empty())
		{
			continue;
		}
		// Split into components: "Type: X, Y, Z: Direction":
		AStringVector Defs = StringSplitAndTrim(*itr, ":");
		if (Defs.size() != 3)
		{
			LOGWARNING("Bad prefab Connector definition line: \"%s\", skipping.", itr->c_str());
			continue;
		}
		AStringVector Coords = StringSplitAndTrim(Defs[1], ",");
		if (Coords.size() != 3)
		{
			LOGWARNING("Bad prefab Connector coords definition: \"%s\", skipping.", Defs[1].c_str());
			continue;
		}

		// Check that the Direction is valid:
		cPiece::cConnector::eDirection Direction;
		if (!cPiece::cConnector::StringToDirection(Defs[2], Direction))
		{
			LOGWARNING("Bad prefab Connector direction: \"%s\", skipping.", Defs[2].c_str());
			continue;
		}

		// Add the connector:
		m_Connectors.push_back(cPiece::cConnector(
			atoi(Coords[0].c_str()), atoi(Coords[1].c_str()), atoi(Coords[2].c_str()),  // Connector pos
			atoi(Defs[0].c_str()),  // Connector type
			Direction
		));
	}  // for itr - Lines[]
}





void cPrefab::ParseDepthWeight(const char * a_DepthWeightDef)
{
	// The member needn't be defined at all, if so, skip:
	if (a_DepthWeightDef == nullptr)
	{
		return;
	}

	// Split into individual records: "Record | Record | Record"
	AStringVector Defs = StringSplitAndTrim(a_DepthWeightDef, "|");

	// Add each record's contents:
	for (AStringVector::const_iterator itr = Defs.begin(), end = Defs.end(); itr != end; ++itr)
	{
		// Split into components: "Depth : Weight"
		AStringVector Components = StringSplitAndTrim(*itr, ":");
		if (Components.size() != 2)
		{
			LOGWARNING("Bad prefab DepthWeight record: \"%s\", skipping.", itr->c_str());
			continue;
		}

		// Parse depth:
		int Depth = atoi(Components[0].c_str());
		if ((Depth == 0) && (Components[0] != "0"))
		{
			LOGWARNING("Bad prefab DepthWeight record, cannot parse depth \"%s\", skipping.", Components[0].c_str());
			continue;
		}

		// Parse weight:
		int Weight = atoi(Components[1].c_str());
		if ((Weight == 0) && (Components[1] != "0"))
		{
			LOGWARNING("Bad prefab DepthWeight record, cannot parse weight \"%s\", skipping.", Components[1].c_str());
			continue;
		}

		// Save to map:
		ASSERT(m_DepthWeight.find(Depth) == m_DepthWeight.end());  // Not a duplicate
		m_DepthWeight[Depth] = Weight;
	}  // for itr - Defs[]
}





cPiece::cConnectors cPrefab::GetConnectors(void) const
{
	return m_Connectors;
}





Vector3i cPrefab::GetSize(void) const
{
	return m_Size;
}





cCuboid cPrefab::GetHitBox(void) const
{
	return m_HitBox;
}





bool cPrefab::CanRotateCCW(int a_NumRotations) const
{
	// Either zero rotations
	// Or the proper bit in m_AllowedRotations is set
	return (a_NumRotations == 0) || ((m_AllowedRotations & (1 << ((a_NumRotations + 3) % 4))) != 0);
}