aboutsummaryrefslogtreecommitdiff
path: root/engines/sword25/math/region.cpp
blob: d873d627f0748c44e3431bd9d413ed5b46c3a87d (plain)
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
// -----------------------------------------------------------------------------
// This file is part of Broken Sword 2.5
// Copyright (c) Malte Thiesen, Daniel Queteschiner and Michael Elsd�rfer
//
// Broken Sword 2.5 is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// Broken Sword 2.5 is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Broken Sword 2.5; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
// -----------------------------------------------------------------------------

#include "sword25/kernel/inputpersistenceblock.h"
#include "sword25/kernel/outputpersistenceblock.h"

#include "sword25/math/region.h"
#include "sword25/math/walkregion.h"
#include "sword25/math/regionregistry.h"

#define BS_LOG_PREFIX "REGION"

// Konstruktion/Destruktion
// ------------------------

BS_Region::BS_Region() : m_Valid(false), m_Type(RT_REGION)
{
	BS_RegionRegistry::GetInstance().RegisterObject(this);
}

// -----------------------------------------------------------------------------

BS_Region::BS_Region(BS_InputPersistenceBlock & Reader, unsigned int Handle) : m_Valid(false), m_Type(RT_REGION)
{
	BS_RegionRegistry::GetInstance().RegisterObject(this, Handle);
	Unpersist(Reader);
}

// -----------------------------------------------------------------------------

unsigned int BS_Region::Create(REGION_TYPE Type)
{
	BS_Region * RegionPtr;
	switch (Type)
	{
		case RT_REGION:
			RegionPtr = new BS_Region();
			break;

		case RT_WALKREGION:
			RegionPtr = new BS_WalkRegion();
			break;

		default:
			BS_ASSERT(true);
	}

	return BS_RegionRegistry::GetInstance().ResolvePtr(RegionPtr);
}

// -----------------------------------------------------------------------------

unsigned int BS_Region::Create(BS_InputPersistenceBlock & Reader, unsigned int Handle)
{
	// Typ einlesen.
	unsigned int Type;
	Reader.Read(Type);

	// Je nach Typ ein neues BS_Region oder BS_WalkRegion Objekt erstellen.
	BS_Region * RegionPtr;
	if (Type == RT_REGION)
	{
		RegionPtr = new BS_Region(Reader, Handle);
	}
	else if (Type == RT_WALKREGION)
	{
		RegionPtr = new BS_WalkRegion(Reader, Handle);
	}
	else
	{
		BS_ASSERT(false);
	}

	return BS_RegionRegistry::GetInstance().ResolvePtr(RegionPtr);
}

// -----------------------------------------------------------------------------

BS_Region::~BS_Region()
{
	BS_RegionRegistry::GetInstance().DeregisterObject(this);
}

// -----------------------------------------------------------------------------

bool BS_Region::Init(const BS_Polygon& Contour, const std::vector<BS_Polygon>* pHoles)
{
	// Objektzustand zur�cksetzen.
	m_Valid = false;
	m_Position = BS_Vertex(0, 0);
	m_Polygons.clear();

	// Gen�gend Platz f�r Kontur und L�cher im Polygon-Vektor reservieren
	if (pHoles)
		m_Polygons.reserve(1 + pHoles->size());
	else
		m_Polygons.reserve(1);

	// Kontur an die erste Position im Polygon-Vektor kopieren
	m_Polygons.push_back(BS_Polygon());
	m_Polygons[0].Init(Contour.VertexCount, Contour.Vertecies);
	// Sicherstellen, dass die Vertecies der Contour im Uhrzeigersinn angeordnet sind.
	m_Polygons[0].EnsureCWOrder();

	// �bergebene Lochpolygone an die folgenden Positionen im Polygon-Vektor kopieren
	if (pHoles)
	{
		for (unsigned int i = 0; i< pHoles->size(); ++i)
		{
			m_Polygons.push_back(BS_Polygon());
			m_Polygons[i + 1].Init((*pHoles)[i].VertexCount, (*pHoles)[i].Vertecies);
			m_Polygons[i + 1].EnsureCWOrder();
		}
	}


	// Bounding-Box initialisieren.
	UpdateBoundingBox();

	m_Valid = true;
	return true;
}

// -----------------------------------------------------------------------------

void BS_Region::UpdateBoundingBox()
{
	if (m_Polygons[0].VertexCount)
	{
		int MinX = m_Polygons[0].Vertecies[0].X;
		int MaxX = m_Polygons[0].Vertecies[0].X;
		int MinY = m_Polygons[0].Vertecies[0].Y;
		int MaxY = m_Polygons[0].Vertecies[0].Y;

		for (int i = 1; i < m_Polygons[0].VertexCount; i++)
		{
			if (m_Polygons[0].Vertecies[i].X < MinX) MinX = m_Polygons[0].Vertecies[i].X;
			else if (m_Polygons[0].Vertecies[i].X > MaxX) MaxX = m_Polygons[0].Vertecies[i].X;
			if (m_Polygons[0].Vertecies[i].Y < MinY) MinY = m_Polygons[0].Vertecies[i].Y;
			else if (m_Polygons[0].Vertecies[i].Y > MaxY) MaxY = m_Polygons[0].Vertecies[i].Y;
		}

		m_BoundingBox = BS_Rect(MinX, MinY, MaxX + 1, MaxY + 1);
	}
}

// Positions�nderungen
// -------------------

void BS_Region::SetPos(int X, int Y)
{
	// Unterschied zwischen alter und neuer Position berechnen.
	BS_Vertex Delta(X - m_Position.X, Y - m_Position.Y);

	// Neue Position im internen Zustand merken.
	m_Position = BS_Vertex(X, Y);

	// Alle Vertecies verschieben.
	for (unsigned int i = 0; i < m_Polygons.size(); ++i)
	{
		m_Polygons[i] += Delta;
	}

	// Bounding-Box aktualisieren
	UpdateBoundingBox();
}

// -----------------------------------------------------------------------------

void BS_Region::SetPosX(int X)
{
	SetPos(X, m_Position.Y);
}

// -----------------------------------------------------------------------------

void BS_Region::SetPosY(int Y)
{
	SetPos(m_Position.X, Y);
}

// Punkt-Region Tests
// ------------------

bool BS_Region::IsPointInRegion(int X, int Y) const
{
	// Testen, ob der Punkt in der Bounding-Box ist.
	if (m_BoundingBox.IsPointInRect(X, Y))
	{
		// Testen, ob der Punkt in der Contour ist.
		if (m_Polygons[0].IsPointInPolygon(X, Y, true))
		{
			// Testen, ob der Punkt in einem Loch ist.
			for (unsigned int i = 1; i < m_Polygons.size(); i++)
			{
				if (m_Polygons[i].IsPointInPolygon(X,Y, false))
					return false;
			}

			return true;
		}
	}

	return false;
}

// -----------------------------------------------------------------------------

bool BS_Region::IsPointInRegion(const BS_Vertex& Vertex) const
{
	return IsPointInRegion(Vertex.X, Vertex.Y);
}

// -----------------------------------------------------------------------------

BS_Vertex BS_Region::FindClosestRegionPoint(const BS_Vertex& Point) const
{
	// Feststellen, ob sich der Punkt innerhalb eines Loches befindet, falls dies der Fall ist wird der dichteste Punkt am Rand des Loches gesucht
	int PolygonIdx = 0;
	{
		for (unsigned int i = 1; i < m_Polygons.size(); ++i)
		{
			if (m_Polygons[i].IsPointInPolygon(Point))
			{
				PolygonIdx = i;
				break;
			}
		}
	}

	const BS_Polygon & Polygon = m_Polygons[PolygonIdx];

	BS_ASSERT(Polygon.VertexCount > 1);

	// F�r jede Linie des Polygons wird der Punkt berechnet, der dem �bergebenen am n�chsten ist.
	// Der Punkt dieser Menge mit dem gerigsten Abstand zum �bergebenen Punkt ist das Ergebnis.
	BS_Vertex ClosestVertex = FindClosestPointOnLine(Polygon.Vertecies[0], Polygon.Vertecies[1], Point);
	int ClosestVertexDistance2 = ClosestVertex.Distance(Point);
	for (int i = 1; i < Polygon.VertexCount; ++i)
	{
		int j = (i + 1) % Polygon.VertexCount;

		BS_Vertex CurVertex = FindClosestPointOnLine(Polygon.Vertecies[i], Polygon.Vertecies[j], Point);
		if (CurVertex.Distance(Point) < ClosestVertexDistance2)
		{
			ClosestVertex = CurVertex;
			ClosestVertexDistance2 = CurVertex.Distance(Point);
		}
	}

	// Feststellen, ob der konstruierte Punkt wirklich von der Methode IsPointInRegion als innerhalb der Region liegend erkannt wird.
	// Dies muss nicht so sein, da aufgrund von Rundungsfehlern am Rand der Polygone Ungenauigkeiten auftreten.
	if (IsPointInRegion(ClosestVertex))
		return ClosestVertex;
	else
	{
		// Es wird versucht einen Punkt innerhalb der Region zu konstruieren indem 8 Punkte getestet werden, die in unmittelbarer Umgebung des
		// berechneten Punktes liegen
		if (IsPointInRegion(ClosestVertex + BS_Vertex(-2, -2)))
			return ClosestVertex + BS_Vertex(-2, -2);
		else if (IsPointInRegion(ClosestVertex + BS_Vertex(0, -2)))
			return ClosestVertex + BS_Vertex(0, -2);
		else if (IsPointInRegion(ClosestVertex + BS_Vertex(2, -2)))
			return ClosestVertex + BS_Vertex(2, -2);
		else if (IsPointInRegion(ClosestVertex + BS_Vertex(-2, 0)))
			return ClosestVertex + BS_Vertex(-2, 0);
		else if (IsPointInRegion(ClosestVertex + BS_Vertex(0, 2)))
			return ClosestVertex + BS_Vertex(0, 2);
		else if (IsPointInRegion(ClosestVertex + BS_Vertex(-2, 2)))
			return ClosestVertex + BS_Vertex(-2, 2);
		else if (IsPointInRegion(ClosestVertex + BS_Vertex(-2, 0)))
			return ClosestVertex + BS_Vertex(2, 2);
		else if (IsPointInRegion(ClosestVertex + BS_Vertex(2, 2)))
			return ClosestVertex + BS_Vertex(2, 2);

		// Falls auch auf diese Weise kein Punkt gefunden werden konnte, der innerhalb der Region liegt wird das Vertex genommen, welches am
		// n�chst an dem Punkt liegt.
		ClosestVertex = Polygon.Vertecies[0];
		int ShortestVertexDistance2 = Polygon.Vertecies[0].Distance2(Point);
		{
			for (int i = 1; i < Polygon.VertexCount; i++)
			{
				int CurDistance2 = Polygon.Vertecies[i].Distance2(Point);
				if (CurDistance2 < ShortestVertexDistance2)
				{
					ClosestVertex = Polygon.Vertecies[i];
					ShortestVertexDistance2 = CurDistance2;
				}
			}
		}
			BS_LOG_WARNINGLN("Clostest vertex forced because edgepoint was outside region.");
			return ClosestVertex;
	}
}

// -----------------------------------------------------------------------------

BS_Vertex BS_Region::FindClosestPointOnLine(const BS_Vertex & LineStart, const BS_Vertex & LineEnd, const BS_Vertex Point) const
{
	float Vector1X = static_cast<float>(Point.X - LineStart.X);
	float Vector1Y = static_cast<float>(Point.Y - LineStart.Y);
	float Vector2X = static_cast<float>(LineEnd.X - LineStart.X);
	float Vector2Y = static_cast<float>(LineEnd.Y - LineStart.Y);
	float Vector2Length = sqrtf(Vector2X * Vector2X + Vector2Y * Vector2Y);
	Vector2X /= Vector2Length;
	Vector2Y /= Vector2Length;
	float Distance = sqrtf(static_cast<float>((LineStart.X - LineEnd.X) * (LineStart.X - LineEnd.X) + 
		(LineStart.Y - LineEnd.Y) * (LineStart.Y - LineEnd.Y)));
	float Dot = Vector1X * Vector2X + Vector1Y * Vector2Y;

	if (Dot <= 0) return LineStart;
	if (Dot >= Distance) return LineEnd;

	BS_Vertex Vector3(static_cast<int>(Vector2X * Dot + 0.5f), static_cast<int>(Vector2Y * Dot + 0.5f));
	return LineStart + Vector3;
}

// -----------------------------------------------------------------------------
// Sichtlinie
// -----------------------------------------------------------------------------

bool BS_Region::IsLineOfSight(const BS_Vertex & a, const BS_Vertex & b) const
{
	BS_ASSERT(m_Polygons.size());

	// Die Linie muss innerhalb des Kontur-Polygons und ausserhalb aller Loch-Polygone sein
	std::vector<BS_Polygon>::const_iterator iter = m_Polygons.begin();
	if (!(*iter).IsLineInterior(a, b)) return false;
	for (iter++; iter != m_Polygons.end(); iter++)
		if (!(*iter).IsLineExterior(a, b)) return false;

	return true;
}

// -----------------------------------------------------------------------------
// Persistenz
// -----------------------------------------------------------------------------

bool BS_Region::Persist(BS_OutputPersistenceBlock & Writer)
{
	bool Result = true;

	Writer.Write(static_cast<unsigned int>(m_Type));
	Writer.Write(m_Valid);
	Writer.Write(m_Position.X);
	Writer.Write(m_Position.Y);
	
	Writer.Write(m_Polygons.size());
	std::vector<BS_Polygon>::iterator It = m_Polygons.begin();
	while (It != m_Polygons.end())
	{
		Result &= It->Persist(Writer);
		++It;
	}

	Writer.Write(m_BoundingBox.left);
	Writer.Write(m_BoundingBox.top);
	Writer.Write(m_BoundingBox.right);
	Writer.Write(m_BoundingBox.bottom);

	return Result;
}

// -----------------------------------------------------------------------------

bool BS_Region::Unpersist(BS_InputPersistenceBlock & Reader)
{
	Reader.Read(m_Valid);
	Reader.Read(m_Position.X);
	Reader.Read(m_Position.Y);

	m_Polygons.clear();
	unsigned int PolygonCount;
	Reader.Read(PolygonCount);
	for (unsigned int i = 0; i < PolygonCount; ++i)
	{
		m_Polygons.push_back(BS_Polygon(Reader));
	}

	Reader.Read(m_BoundingBox.left);
	Reader.Read(m_BoundingBox.top);
	Reader.Read(m_BoundingBox.right);
	Reader.Read(m_BoundingBox.bottom);

	return Reader.IsGood();
}

// -----------------------------------------------------------------------------

BS_Vertex BS_Region::GetCentroid() const
{
	if (m_Polygons.size() > 0)
		return m_Polygons[0].GetCentroid();
	return
		BS_Vertex();
}