]> Dogcows Code - chaz/carfire/blob - CarFire/CarFire/CarFire/Map.cs
SaberMonster loads from map file and walks around using the path finder, and a lot...
[chaz/carfire] / CarFire / CarFire / CarFire / Map.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.IO;
6 using System.Runtime.Serialization;
7 using System.Diagnostics;
8 using Microsoft.Xna.Framework;
9 using Microsoft.Xna.Framework.Graphics;
10 using System.Reflection;
11
12 namespace CarFire
13 {
14 /// <summary>
15 /// A map object represents the map or virtual world where players and other
16 /// game entities exist. The map consists of a grid where each grid space can
17 /// contain static scenery and/or game entities which can move and interact
18 /// with other game entities.
19 /// </summary>
20 public class Map
21 {
22 // DEBUG: Tilesets not implemented at all.
23 public static Texture2D DefaultTile;
24
25 #region Public Exceptions
26
27 /// <summary>
28 /// This exception is thrown during the loading of a map if any
29 /// part of the map file is inconsistent with the expected format
30 /// and order.
31 /// </summary>
32 public class RuntimeException : System.ApplicationException
33 {
34 public RuntimeException() { }
35
36 public RuntimeException(string message) :
37 base(message) { }
38
39 public RuntimeException(string message, System.Exception inner) :
40 base(message, inner) { }
41
42 protected RuntimeException(SerializationInfo info, StreamingContext context) :
43 base(info, context) { }
44 }
45
46 #endregion
47
48
49 #region Public Constants
50
51 public const float PixelsToUnitSquares = 64.0f;
52
53 #endregion
54
55
56 #region Public Types
57
58 /// <summary>
59 /// The type of a map helps determine how the map is intended to be used.
60 /// </summary>
61 public enum Mode
62 {
63 None,
64 Campaign,
65 Battle
66 }
67
68 /// <summary>
69 /// The container class for map metadata.
70 /// </summary>
71 public class Metadata
72 {
73 public string Name;
74 public Mode Type;
75 public string Author;
76 public HashSet<int> NumPlayers = new HashSet<int>();
77 public string Tileset;
78 public int GridWidth;
79 public int GridHeight;
80 }
81
82 /// <summary>
83 /// The container class for information about an entity defined in the map.
84 /// </summary>
85 public class RawEntity
86 {
87 public char Id;
88 public Point Position;
89 public Dictionary<string, string> Attributes = new Dictionary<string, string>();
90 }
91
92 #endregion
93
94
95 #region Public Properties
96
97 /// <summary>
98 /// Get the name of the map.
99 /// </summary>
100 public string Name { get { return mData.Metadata.Name; } }
101
102 /// <summary>
103 /// Get the type of the map.
104 /// </summary>
105 public Mode Type { get { return mData.Metadata.Type; } }
106
107 /// <summary>
108 /// Get the author of the map.
109 /// </summary>
110 public string Author { get { return mData.Metadata.Author; } }
111
112 /// <summary>
113 /// Get a set of integers containing each allowable number of players.
114 /// </summary>
115 public HashSet<int> NumPlayers { get { return mData.Metadata.NumPlayers; } }
116
117 /// <summary>
118 /// Get the width of the map, in grid units.
119 /// </summary>
120 public int Width { get { return mData.Metadata.GridWidth; } }
121
122 /// <summary>
123 /// Get the height of the map, in grid units.
124 /// </summary>
125 public int Height { get { return mData.Metadata.GridHeight; } }
126
127 // TODO: This should return whatever object we end up using for tilesets.
128 public string Tileset { get { return mData.Metadata.Tileset; } }
129
130 /// <summary>
131 /// Get the current grid of open cells. On the grid, true means
132 /// the cell is open (i.e. an entity can occupy that cell), and false
133 /// means the cell is closed. Note that, just like Map.IsCellOpen,
134 /// only static scenery is considered; the grid cannot tell you
135 /// whether or not an entity is already occupying the cell.
136 /// </summary>
137 public bool[,] Grid { get { return mData.Grid; } }
138
139 /// <summary>
140 /// Get a list of the raw entity containers loaded with the map. If you
141 /// want to get the actual entity objects, use Map.GetEntities and
142 /// Map.GetAllEntities instead.
143 /// </summary>
144 public List<RawEntity> RawEntities { get { return mData.Entities; } }
145
146
147 /// <summary>
148 /// Get and set the coordinate of the grid cell that should be in
149 /// the center of the screen when the map is drawn. Setting this
150 /// will change the viewport of the map and will effect the return
151 /// values of Map.GetPointFromCoordinates and Map.GetRectangleFromCoordinates.
152 /// </summary>
153 public Vector2 CenterCell
154 {
155 get { return mView.CenterCell; }
156 set { mView.CenterCell = value; }
157 }
158
159 /// <summary>
160 /// Get and set the zoom of the map view. The default zoom is
161 /// Map.PixelsToUnitSquares.
162 /// </summary>
163 public float Zoom
164 {
165 get { return mView.Zoom; }
166 set { mView.Zoom = value; }
167 }
168
169
170 /// <summary>
171 /// Get and set the associated game object.
172 /// </summary>
173 public Game Game
174 {
175 get { return mData.Game; }
176 set { mData.Game = value; }
177 }
178
179 #endregion
180
181
182 #region Public Methods
183
184 /// <summary>
185 /// Construct a map with the provided map data.
186 /// </summary>
187 /// <param name="metadata">The metadata.</param>
188 /// <param name="grid">The grid.</param>
189 /// <param name="entities">The entities.</param>
190 public Map(Metadata metadata, char[,] grid, char defaultTile,
191 List<RawEntity> entities, Point[] playerPositions)
192 {
193 mData = new Model(metadata, grid, defaultTile, entities, playerPositions);
194 mView = new View(mData);
195 }
196
197
198 /// <summary>
199 /// Draw a representation of the map to the screen.
200 /// </summary>
201 /// <param name="spriteBatch">The jeewiz.</param>
202 public void Draw(SpriteBatch spriteBatch)
203 {
204 mView.Draw(spriteBatch);
205 }
206
207
208 /// <summary>
209 /// Get a point in screen-space from a coordinate in gridspace.
210 /// </summary>
211 /// <param name="x">X-coordinate.</param>
212 /// <param name="y">Y-coordinate.</param>
213 /// <returns>Transformed point.</returns>
214 public Point GetPointFromCoordinates(float x, float y)
215 {
216 return mView.GetPointFromCoordinates(x, y);
217 }
218
219 /// <summary>
220 /// Get a point in screen-space from a coordinate in gridspace.
221 /// </summary>
222 /// <param name="point">X,Y-coordinates.</param>
223 /// <returns>Transformed point.</returns>
224 public Point GetPointFromCoordinates(Vector2 point)
225 {
226 return mView.GetPointFromCoordinates(point.X, point.Y);
227 }
228
229 /// <summary>
230 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
231 /// </summary>
232 /// <param name="x">X-coordinate.</param>
233 /// <param name="y">Y-coordinate.</param>
234 /// <returns>Transformed rectangle.</returns>
235 public Rectangle GetRectangleFromCoordinates(float x, float y)
236 {
237 return mView.GetRectangleFromCoordinates(x, y);
238 }
239
240 /// <summary>
241 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
242 /// </summary>
243 /// <param name="point">X,Y-coordinates.</param>
244 /// <returns>Transformed rectangle.</returns>
245 public Rectangle GetRectangleFromCoordinates(Vector2 point)
246 {
247 return mView.GetRectangleFromCoordinates(point.X, point.Y);
248 }
249
250
251 /// <summary>
252 /// Determine whether or not a cell can be occupied by a game entity.
253 /// </summary>
254 /// <param name="x">X-coordinate.</param>
255 /// <param name="y">Y-coordinate.</param>
256 /// <returns>True if cell can be occupied, false otherwise.</returns>
257 public bool IsCellOpen(int x, int y)
258 {
259 return mData.IsCellOpen(x, y);
260 }
261
262 /// <summary>
263 /// Determine whether or not a cell can be occupied by a game entity.
264 /// </summary>
265 /// <param name="point">X,Y-coordinates.</param>
266 /// <returns>True if cell can be occupied, false otherwise.</returns>
267 public bool IsCellOpen(Point point)
268 {
269 return mData.IsCellOpen(point.X, point.Y);
270 }
271
272
273 /// <summary>
274 /// Get the starting position of a player.
275 /// </summary>
276 /// <param name="playerNumber">The number of the player (i.e. 1-4).
277 /// This number must be a valid player number.</param>
278 /// <returns>The starting position of the player.</returns>
279 public Point GetStartingPositionForPlayer(int playerNumber)
280 {
281 Debug.Assert(1 <= playerNumber && playerNumber <= NumPlayers.Max());
282 return mData.PlayerPositions[playerNumber];
283 }
284
285
286 /// <summary>
287 /// Get all the entities loaded from the map file. Exceptions could be
288 /// thrown if there are entities without associated classes.
289 /// </summary>
290 /// <returns>List of entity objects loaded.</returns>
291 public List<IEntity> GetAllEntities()
292 {
293 return mData.GetAllEntities();
294 }
295
296 /// <summary>
297 /// Get the entities of a certain type loaded from the map file. Exceptions
298 /// could be thrown if there are entities without associated classes.
299 /// </summary>
300 /// <typeparam name="T">Type of the entity you want a list of.</typeparam>
301 /// <returns>List of entity objects loaded.</returns>
302 public List<T> GetEntities<T>()
303 {
304 return mData.GetEntities<T>();
305 }
306
307
308 /// <summary>
309 /// Set the tile of a cell.
310 /// </summary>
311 /// <param name="x">X-coordinate.</param>
312 /// <param name="y">Y-coordinate.</param>
313 /// <param name="tile">The character representing the tile.</param>
314 public void SetCell(int x, int y, char tile)
315 {
316 mData.SetCell(x, y, tile);
317 }
318
319 /// <summary>
320 /// Set the tile of a cell.
321 /// </summary>
322 /// <param name="point">X,Y-coordinates.</param>
323 /// <param name="tile">The character representing the tile.</param>
324 public void SetCell(Point point, char tile)
325 {
326 mData.SetCell(point.X, point.Y, tile);
327 }
328
329
330 /// <summary>
331 /// Clear a cell to the default tile.
332 /// </summary>
333 /// <param name="x">X-coordinate.</param>
334 /// <param name="y">Y-coordinate.</param>
335 public void ClearCell(int x, int y)
336 {
337 mData.ClearCell(x, y);
338 }
339
340 /// <summary>
341 /// Clear a cell to the default tile.
342 /// </summary>
343 /// <param name="point">X,Y-coordinates.</param>
344 public void ClearCell(Point point)
345 {
346 mData.ClearCell(point.X, point.Y);
347 }
348
349
350 /// <summary>
351 /// Reset the map to the state it was at right after loading.
352 /// </summary>
353 public void Reset()
354 {
355 mData.Reset();
356 mView.Reset();
357 }
358
359 #endregion
360
361
362 #region Private Types
363
364 class Model
365 {
366 public Metadata Metadata { get { return mMetadata; } }
367 public List<RawEntity> Entities { get { return mEntities; } }
368 public Point[] PlayerPositions { get { return mPlayerPositions; } }
369 public bool[,] Grid { get { return mBooleanGrid; } }
370
371 public Game Game;
372
373
374 public Model(Metadata metadata, char[,] grid, char defaultTile,
375 List<RawEntity> entities, Point[] playerPositions)
376 {
377 Debug.Assert(metadata != null);
378 Debug.Assert(grid != null);
379 Debug.Assert(entities != null);
380 Debug.Assert(metadata.GridWidth * metadata.GridHeight == grid.Length);
381
382 mMetadata = metadata;
383 mCleanGrid = grid;
384 mDefaultTile = defaultTile;
385 mEntities = entities;
386 mPlayerPositions = playerPositions;
387
388 Reset();
389
390 #if DEBUG
391 Console.WriteLine("Loaded map {0} of type {1} written by {2}.",
392 metadata.Name,
393 metadata.Type,
394 metadata.Author);
395 #endif
396 }
397
398
399 public void Reset()
400 {
401 mGrid = (char[,])mCleanGrid.Clone();
402
403 mBooleanGrid = new bool[mMetadata.GridWidth, mMetadata.GridHeight];
404 for (int x = 0; x < mMetadata.GridWidth; x++)
405 {
406 for (int y = 0; y < mMetadata.GridHeight; y++)
407 {
408 mBooleanGrid[x, y] = IsCellOpen(x, y);
409 }
410 }
411 }
412
413
414 public bool IsCellOpen(int x, int y)
415 {
416 // TODO: Still need to define characters for types of scenery.
417 if (IsOnMap(x, y)) return mGrid[x, y] == ' ';
418 return false;
419 }
420
421 public void SetCell(int x, int y, char tile)
422 {
423 if (IsOnMap(x, y))
424 {
425 mGrid[x, y] = tile;
426 mBooleanGrid[x, y] = IsCellOpen(x, y);
427 }
428 }
429
430 public void ClearCell(int x, int y)
431 {
432 SetCell(x, y, mDefaultTile);
433 }
434
435 public bool IsOnMap(int x, int y)
436 {
437 return 0 <= x && x < Metadata.GridWidth && 0 <= y && y < Metadata.GridHeight;
438 }
439
440
441 public List<IEntity> GetAllEntities()
442 {
443 List<IEntity> list = new List<IEntity>();
444
445 foreach (RawEntity raw in mEntities)
446 {
447 if (raw.Attributes.ContainsKey("type"))
448 {
449 string typename = raw.Attributes["type"];
450
451 object[] args = new object[4];
452 args[0] = raw.Id;
453 args[1] = raw.Position;
454 args[2] = raw.Attributes;
455 args[3] = Game;
456
457 try
458 {
459 IEntity entity = (IEntity)Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
460 if (entity != null)
461 {
462 entity.LoadContent(Game.ContentManager);
463 list.Add(entity);
464 }
465 else throw new RuntimeException();
466 }
467 #pragma warning disable 0168
468 catch (System.Exception ex)
469 #pragma warning restore 0168
470 {
471 throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
472 }
473 }
474 else
475 {
476 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
477 }
478 }
479
480 return list;
481 }
482
483 public List<T> GetEntities<T>()
484 {
485 System.Type type = typeof(T);
486 List<T> list = new List<T>();
487
488 string typename = typeof(T).Name;
489 foreach (RawEntity raw in mEntities)
490 {
491 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
492 {
493 object[] args = new object[4];
494 args[0] = raw.Id;
495 args[1] = raw.Position;
496 args[2] = raw.Attributes;
497 args[3] = Game;
498
499 T entity = (T)Activator.CreateInstance(type, args);
500 if (entity != null)
501 {
502 ((IEntity)entity).LoadContent(Game.ContentManager);
503 list.Add(entity);
504 }
505 else throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
506 }
507 }
508
509 return list;
510 }
511
512
513 Metadata mMetadata;
514 char[,] mGrid;
515 char[,] mCleanGrid;
516 bool[,] mBooleanGrid;
517 char mDefaultTile;
518 List<RawEntity> mEntities;
519 Point[] mPlayerPositions;
520 }
521
522 class View
523 {
524 public Vector2 CenterCell;
525 public float Zoom;
526
527
528 public View(Model data)
529 {
530 Debug.Assert(data != null);
531 mData = data;
532
533 Reset();
534 }
535
536
537 public void Reset()
538 {
539 CenterCell = Vector2.Zero;
540 Zoom = PixelsToUnitSquares;
541 }
542
543
544 public void Draw(SpriteBatch spriteBatch)
545 {
546 mViewport = spriteBatch.GraphicsDevice.Viewport;
547
548 // TODO: There is no culling yet, but it runs so fast that it probably won't ever need it.
549 for (int y = 0; y < mData.Metadata.GridHeight; y++)
550 {
551 for (int x = 0; x < mData.Metadata.GridWidth; x++)
552 {
553 if (mData.IsCellOpen(x, y))
554 {
555 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.White);
556 }
557 else
558 {
559 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.DarkBlue);
560 }
561 }
562 }
563 }
564
565
566 public Point GetPointFromCoordinates(float x, float y)
567 {
568 Matrix transform = GetTransformation(CenterCell);
569 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
570
571 return new Point((int)point.X, (int)point.Y);
572 }
573
574 public Rectangle GetRectangleFromCoordinates(float x, float y)
575 {
576 Matrix transform = GetTransformation(CenterCell);
577 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
578
579 return new Rectangle((int)Math.Round(point.X, 0), (int)Math.Round(point.Y, 0), (int)Math.Round(Zoom, 0), (int)Math.Round(Zoom, 0));
580 }
581
582
583
584 Matrix GetTransformation(Vector2 center)
585 {
586 float halfRatio = Zoom * 0.5f;
587 Matrix transform = Matrix.CreateTranslation(-center.X, -center.Y, 0.0f);
588 transform *= Matrix.CreateScale(Zoom);
589 transform *= Matrix.CreateTranslation(mViewport.Width * 0.5f - halfRatio,
590 mViewport.Height * 0.5f - halfRatio, 0.0f);
591
592 Vector2 topLeft = Vector2.Transform(new Vector2(0.0f, 0.0f), transform);
593 topLeft.X = Math.Max(mViewport.X, topLeft.X);
594 topLeft.Y = Math.Max(mViewport.Y, topLeft.Y);
595 transform *= Matrix.CreateTranslation(-topLeft.X, -topLeft.Y, 0.0f);
596
597 Vector2 bottomRight = Vector2.Transform(new Vector2((float)mData.Metadata.GridWidth,
598 (float)mData.Metadata.GridHeight), transform);
599 float right = mViewport.X + mViewport.Width;
600 float bottom = mViewport.Y + mViewport.Height;
601 bottomRight.X = Math.Min(right, bottomRight.X) - right;
602 bottomRight.Y = Math.Min(bottom, bottomRight.Y) - bottom;
603 transform *= Matrix.CreateTranslation(-bottomRight.X, -bottomRight.Y, 0.0f);
604
605 return transform;
606 }
607
608
609 Model mData;
610 Viewport mViewport;
611 }
612
613 #endregion
614
615
616 #region Private Variables
617
618 Model mData;
619 View mView;
620
621 #endregion
622 }
623 }
This page took 0.062272 seconds and 5 git commands to generate.