File: ai_building.cpp

package info (click to toggle)
boswars 2.8-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 96,652 kB
  • sloc: cpp: 57,250; python: 1,715; sh: 25; makefile: 17
file content (434 lines) | stat: -rw-r--r-- 10,904 bytes parent folder | download | duplicates (5)
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
//     ____                _       __               
//    / __ )____  _____   | |     / /___ ___________
//   / __  / __ \/ ___/   | | /| / / __ `/ ___/ ___/
//  / /_/ / /_/ (__  )    | |/ |/ / /_/ / /  (__  ) 
// /_____/\____/____/     |__/|__/\__,_/_/  /____/  
//                                              
//       A futuristic real-time strategy game.
//          This file is part of Bos Wars.
//
/**@name ai_building.cpp - AI building functions. */
//
//      (c) Copyright 2001-2009 by Lutz Sammer
//
//      This program 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; only version 2 of the License.
//
//      This program 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 this program; if not, write to the Free Software
//      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
//      02111-1307, USA.
//

//@{

/*----------------------------------------------------------------------------
--  Includes
----------------------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>

#include "stratagus.h"
#include "unit.h"
#include "unittype.h"
#include "map.h"
#include "pathfinder.h"
#include "ai_local.h"
#include "player.h"

/*----------------------------------------------------------------------------
--  Types
----------------------------------------------------------------------------*/

enum
{
	AiBuildingPlaceTried  = 0x01, // tried to place a building there
	AiBuildingPlaceBlock  = 0x02, // worker cannot walk there
	AiBuildingPlaceWalked = 0x04, // worker can walk there
	AiBuildingPlaceEdge   = 0x62  // = 98, which InitMatrix uses
};

/*----------------------------------------------------------------------------
--  Functions
----------------------------------------------------------------------------*/

/**
**  Check if the surroundings are free. Depending on the value of flag, it will check:
**  0: the building will not block any way
**  1: all surrounding is free
**
**  @param worker    Worker to build.
**  @param type      Type of building.
**  @param x         X map tile position for the building.
**  @param y         Y map tile position for the building.
**  @param backupok  Location can be used as a backup
**
**  @return          True if the surrounding is free, false otherwise.
**
**  @note            Can be faster written.
*/
static int AiCheckSurrounding(const CUnit *worker, const CUnitType *type, int x, int y, bool &backupok)
{
	static int dirs[5][2] = {{1,0},{0,1},{-1,0},{0,-1},{0,0}};
	int surrounding[1024]; // Max circumference for building
	int surroundingnb;
	int x0, y0, x1, y1;
	int i;
	int lastval;
	int dir;
	int obstacle;

	x0 = x - 1;
	y0 = y - 1;
	x1 = x0 + type->TileWidth + 1;
	y1 = y0 + type->TileWidth + 1;


	x = x0;
	y = y0;
	dir = -1;
	surroundingnb = 0;
	while (dir < 4)
	{
		if (x >= 0 && x < Map.Info.MapWidth &&
			y >= 0 && y < Map.Info.MapHeight &&
			(Map.Field(x, y)->Flags & (MapFieldUnpassable | MapFieldBuilding)) == 0)
		{
			surrounding[surroundingnb++] = 1;
		}
		else
		{
			surrounding[surroundingnb++] = 0;
		}

		if ((x == x0 || x == x1) && (y == y0 || y == y1))
		{
			dir++;
		}

		x += dirs[dir][0];
		y += dirs[dir][1];
	}

	lastval = surrounding[surroundingnb - 1];
	obstacle = 0;
	for (i = 0 ; i < surroundingnb; ++i)
	{
		if (lastval && !surrounding[i])
		{
			++obstacle;
		}
		lastval = surrounding[i];
	}

	if (obstacle == 0)
	{
		obstacle = !surrounding[0];
	}

	if (!type->ShoreBuilding)
	{
		backupok = obstacle < 5;
	}
	else
	{
		// Shore building have at least 2 obstacles : sea->ground & ground->sea
		backupok = obstacle < 3;
	}
	return obstacle == 0;
}

/**
**  Try to place a building in each position within a rectangle,
**  except positions that have already been tried in earlier calls.
**
**  @param worker  Worker to build building.
**  @param type    Type of building.
**  @param matrix  Origin in a 2d array that shows which positions
**                 have already been tried.
**  @param minx    Smallest X position to try building
**  @param miny    Smallest Y position to try building
**  @param maxx    Greatest X position to try building
**  @param maxy    Greatest Y position to try building
**  @param chosenx Pointer for good X position returned.
**  @param choseny Pointer for good Y position returned.
**  @param backupx Pointer for worse X position returned.
**  @param backupx Pointer for worse Y position returned.
**
**  @return        True if good position found, false if not found.
**
**  This function ignores TileWidth and TileHeight of the building,
**  so the caller should adjust maxx and maxy accordingly.
*/
static inline bool AiTryBuildingPlacesRect(const CUnit *worker, const CUnitType* type,
					   unsigned char *matrix, int mwidth,
					   int minx, int miny, int maxx, int maxy,
					   int *chosenx, int *choseny,
					   int *backupx, int *backupy)
{
	for (int y = miny; y <= maxy; y++)
	{
		for (int x = minx; x <= maxx; x++)
		{
			unsigned char *ptr = matrix + x + y * mwidth;
			if (!(*ptr & AiBuildingPlaceTried))
			{
				CUnit *ontop = CanBuildUnitType(worker, type, x, y, 1);
				if (ontop)
				{
					bool backupok;
					if ((ontop != (CUnit *)1 && ontop != worker) ||
					    AiCheckSurrounding(worker, type, x, y, backupok))
					{
						*chosenx = x;
						*choseny = y;
						return true;
					}
					else if (backupok && *backupx == -1)
					{
						*backupx = x;
						*backupy = y;
					}
				}

				*ptr |= AiBuildingPlaceTried;
			} // if not tried
		} // for x
	} // for y

	return false;
}

/**
**  Find free building place. (flood fill version)
**
**  @param worker  Worker to build building.
**  @param type    Type of building.
**  @param ox      Original X position to try building
**  @param oy      Original Y position to try building
**  @param dx      Pointer for X position returned.
**  @param dy      Pointer for Y position returned.
**
**  @return        True if place found, false if no found.
*/
static int AiFindBuildingPlace2(const CUnit *worker, const CUnitType *type,
	int ox, int oy, int *dx, int *dy)
{
	static const int xoffset[] = { 0, -1, +1, 0, -1, +1, -1, +1 };
	static const int yoffset[] = { -1, 0, 0, +1, -1, -1, +1, +1 };
	struct p {
		unsigned short X;
		unsigned short Y;
	} *points;
	int size;
	int x;
	int y;
	int rx;
	int ry;
	int mask;
	int wp;
	int rp;
	int ep;
	int i;
	int w;
	unsigned char *m;
	unsigned char *matrix;
	int backupx = -1;
	int backupy = -1;
	bool backupok;
	CUnit *ontop;
	int minoffx;
	int minoffy;
	int maxoffx;
	int maxoffy;

	size = Map.Info.MapWidth * Map.Info.MapHeight / 4;
	points = new p[size];

	x = ox;
	y = oy;
	//
	// Look if we can build at current place.
	//
	if ((ontop = CanBuildUnitType(worker, type, x, y, 1)))
	{
		if ((ontop != (CUnit *)1 && ontop != worker) ||
			AiCheckSurrounding(worker, type, x, y, backupok))
		{
			*dx = x;
			*dy = y;
			delete[] points;
			return 1;
		}
		else if (backupok)
		{
			backupx = x;
			backupy = y;
		}
	}
	//
	//  Make movement matrix.
	//
	matrix = CreateMatrix();
	w = Map.Info.MapWidth + 2;

	mask = worker->Type->MovementMask;
	// Ignore all possible mobile units.
	mask &= ~(MapFieldLandUnit | MapFieldAirUnit | MapFieldSeaUnit);

	points[0].X = x;
	points[0].Y = y;
	// also use the bottom right
	if ((type->TileWidth > 1 || type->TileHeight > 1) &&
		x + type->TileWidth - 1 < Map.Info.MapWidth &&
		y + type->TileHeight - 1 < Map.Info.MapHeight)
	{
		points[1].X = x + type->TileWidth - 1;
		points[1].Y = y + type->TileHeight - 1;
		ep = wp = 2; // start with two points
	}
	else
	{
		ep = wp = 1; // start with one point
	}
	matrix += w + w + 2;
	rp = 0;
	matrix[x + y * w] = 1; // mark start point

	if (mask & ~type->MovementMask || !type->BuildingRules.empty())
	{
		// The worker cannot move to some types of tiles where
		// the building can be built.  For example, the worker
		// can only walk on land and the building needs to be
		// built in water.
		//
		// Or, the building type has some BuildingRules.
		// Some of them might be BuildRestrictionOnTop,
		// which implies there already is a building that
		// would block the worker.
		minoffx = -type->TileWidth;
		minoffy = -type->TileHeight;
		maxoffx = 1;
		maxoffy = 1;
	}
	else
	{
		minoffx = 0;
		minoffy = 0;
		maxoffx = 0;
		maxoffy = 0;
	}

	//
	// Pop a point from stack, push all neighbours which could be entered.
	//
	for (;;)
	{
		while (rp != ep)
		{
			rx = points[rp].X;
			ry = points[rp].Y;
			for (i = 0; i < 8; ++i)
			{
				// mark all neighbors
				x = rx + xoffset[i];
				y = ry + yoffset[i];
				m = matrix + x + y * w;
				if (*m & (AiBuildingPlaceWalked | AiBuildingPlaceBlock))
				{
					// already checked
					continue;
				}

				if (!CanMoveToMask(x, y, mask))
				{
					// unreachable
					*m |= AiBuildingPlaceBlock;
					continue;
				}
				
				//
				// Look if we can build here and no enemies nearby.
				//
				if (!AiEnemyUnitsInDistance(worker->Player, NULL, x, y, 8)
				    && AiTryBuildingPlacesRect(
					    worker, type,
					    matrix, w,
					    std::max(x + minoffx, 0),
					    std::max(y + minoffy, 0),
					    std::min(x + maxoffx, Map.Info.MapWidth - type->TileWidth),
					    std::min(y + maxoffy, Map.Info.MapHeight - type->TileHeight),
					    dx, dy,
					    &backupx, &backupy))
				{
					delete[] points;
					return 1;
				}

				*m |= AiBuildingPlaceWalked;
				points[wp].X = x; // push the point
				points[wp].Y = y;
				if (++wp >= size)
				{
					// round about
					wp = 0;
				}
			} // for i

			if (++rp >= size)
			{
				// round about
				rp = 0;
			}
		}

		//
		// Continue with next frame.
		//
		if (rp == wp)
		{
			// unreachable, no more points available
			break;
		}
		ep = wp;
	}

	delete[] points;

	if (backupx != -1)
	{
		*dx = backupx;
		*dy = backupy;
		return 1;
	}
	return 0;
}

/**
**  Find free building place.
**
**  @param worker  Worker to build building.
**  @param type    Type of building.
**  @param dx      Pointer for X position returned.
**  @param dy      Pointer for Y position returned.
**
**  @return        True if place found, false if no found.
**
**  @todo          Better and faster way to find building place of oil
**                 platforms Special routines for special buildings.
*/
int AiFindBuildingPlace(const CUnit *worker, const CUnitType *type, int *dx, int *dy)
{
	DebugPrint("Want to build a %s(%s)\n" _C_ type->Ident.c_str() _C_ type->Name.c_str());

	return AiFindBuildingPlace2(worker, type, worker->X, worker->Y, dx, dy);
}

//@}