]> Dogcows Code - chaz/carfire/blob - CarFire/CarFire/CarFire/Map.cs
New Map APIs:
[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 public float Zoom
160 {
161 get { return mView.Zoom; }
162 set { mView.Zoom = value; }
163 }
164
165 #endregion
166
167
168 #region Public Methods
169
170 /// <summary>
171 /// Construct a map with the provided map data.
172 /// </summary>
173 /// <param name="metadata">The metadata.</param>
174 /// <param name="grid">The grid.</param>
175 /// <param name="entities">The entities.</param>
176 public Map(Metadata metadata, char[,] grid, char defaultTile,
177 List<RawEntity> entities, Point[] playerPositions)
178 {
179 mData = new Modal(metadata, grid, defaultTile, entities, playerPositions);
180 mView = new View(mData);
181 }
182
183
184 /// <summary>
185 /// Draw a representation of the map to the screen.
186 /// </summary>
187 /// <param name="spriteBatch">The jeewiz.</param>
188 public void Draw(SpriteBatch spriteBatch)
189 {
190 mView.Draw(spriteBatch);
191 }
192
193
194 /// <summary>
195 /// Get a point in screen-space from a coordinate in gridspace.
196 /// </summary>
197 /// <param name="x">X-coordinate.</param>
198 /// <param name="y">Y-coordinate.</param>
199 /// <returns>Transformed point.</returns>
200 public Point GetPointFromCoordinates(float x, float y)
201 {
202 return mView.GetPointFromCoordinates(x, y);
203 }
204
205 /// <summary>
206 /// Get a point in screen-space from a coordinate in gridspace.
207 /// </summary>
208 /// <param name="point">X,Y-coordinates.</param>
209 /// <returns>Transformed point.</returns>
210 public Point GetPointFromCoordinates(Vector2 point)
211 {
212 return mView.GetPointFromCoordinates(point.X, point.Y);
213 }
214
215 /// <summary>
216 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
217 /// </summary>
218 /// <param name="x">X-coordinate.</param>
219 /// <param name="y">Y-coordinate.</param>
220 /// <returns>Transformed rectangle.</returns>
221 public Rectangle GetRectangleFromCoordinates(float x, float y)
222 {
223 return mView.GetRectangleFromCoordinates(x, y);
224 }
225
226 /// <summary>
227 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
228 /// </summary>
229 /// <param name="point">X,Y-coordinates.</param>
230 /// <returns>Transformed rectangle.</returns>
231 public Rectangle GetRectangleFromCoordinates(Vector2 point)
232 {
233 return mView.GetRectangleFromCoordinates(point.X, point.Y);
234 }
235
236
237 /// <summary>
238 /// Determine whether or not a cell can be occupied by a game entity.
239 /// </summary>
240 /// <param name="x">X-coordinate.</param>
241 /// <param name="y">Y-coordinate.</param>
242 /// <returns>True if cell can be occupied, false otherwise.</returns>
243 public bool IsCellOpen(int x, int y)
244 {
245 return mData.IsCellOpen(x, y);
246 }
247
248 /// <summary>
249 /// Determine whether or not a cell can be occupied by a game entity.
250 /// </summary>
251 /// <param name="point">X,Y-coordinates.</param>
252 /// <returns>True if cell can be occupied, false otherwise.</returns>
253 public bool IsCellOpen(Point point)
254 {
255 return mData.IsCellOpen(point.X, point.Y);
256 }
257
258
259 /// <summary>
260 /// Get the starting position of a player.
261 /// </summary>
262 /// <param name="playerNumber">The number of the player (i.e. 1-4).
263 /// This number must be a valid player number.</param>
264 /// <returns>The starting position of the player.</returns>
265 public Point GetStartingPositionForPlayer(int playerNumber)
266 {
267 Debug.Assert(1 <= playerNumber && playerNumber <= NumPlayers.Max());
268 return mData.PlayerPositions[playerNumber];
269 }
270
271
272 /// <summary>
273 /// Get all the entities loaded from the map file. Exceptions could be
274 /// thrown if there are entities without associated classes.
275 /// </summary>
276 /// <returns>List of entity objects loaded.</returns>
277 public List<object> GetAllEntities()
278 {
279 return mData.GetAllEntities();
280 }
281
282 /// <summary>
283 /// Get the entities of a certain type loaded from the map file. Exceptions
284 /// could be thrown if there are entities without associated classes.
285 /// </summary>
286 /// <typeparam name="T">Type of the entity you want a list of.</typeparam>
287 /// <returns>List of entity objects loaded.</returns>
288 public List<T> GetEntities<T>()
289 {
290 return mData.GetEntities<T>();
291 }
292
293
294 /// <summary>
295 /// Set the tile of a cell.
296 /// </summary>
297 /// <param name="x">X-coordinate.</param>
298 /// <param name="y">Y-coordinate.</param>
299 /// <param name="tile">The character representing the tile.</param>
300 public void SetCell(int x, int y, char tile)
301 {
302 mData.SetCell(x, y, tile);
303 }
304
305 /// <summary>
306 /// Set the tile of a cell.
307 /// </summary>
308 /// <param name="point">X,Y-coordinates.</param>
309 /// <param name="tile">The character representing the tile.</param>
310 public void SetCell(Point point, char tile)
311 {
312 mData.SetCell(point.X, point.Y, tile);
313 }
314
315
316 /// <summary>
317 /// Clear a cell to the default tile.
318 /// </summary>
319 /// <param name="x">X-coordinate.</param>
320 /// <param name="y">Y-coordinate.</param>
321 public void ClearCell(int x, int y)
322 {
323 mData.ClearCell(x, y);
324 }
325
326 /// <summary>
327 /// Clear a cell to the default tile.
328 /// </summary>
329 /// <param name="point">X,Y-coordinates.</param>
330 public void ClearCell(Point point)
331 {
332 mData.ClearCell(point.X, point.Y);
333 }
334
335
336 /// <summary>
337 /// Reset the map to the state it was at right after loading.
338 /// </summary>
339 public void Reset()
340 {
341 mData.Reset();
342 mView.Reset();
343 }
344
345 #endregion
346
347
348 #region Private Types
349
350 class Modal
351 {
352 public Metadata Metadata { get { return mMetadata; } }
353 public List<RawEntity> Entities { get { return mEntities; } }
354 public Point[] PlayerPositions { get { return mPlayerPositions; } }
355 public bool[,] Grid { get { return mBooleanGrid; } }
356
357
358 public Modal(Metadata metadata, char[,] grid, char defaultTile,
359 List<RawEntity> entities, Point[] playerPositions)
360 {
361 Debug.Assert(metadata != null);
362 Debug.Assert(grid != null);
363 Debug.Assert(entities != null);
364 Debug.Assert(metadata.GridWidth * metadata.GridHeight == grid.Length);
365
366 mMetadata = metadata;
367 mCleanGrid = grid;
368 mDefaultTile = defaultTile;
369 mEntities = entities;
370 mPlayerPositions = playerPositions;
371
372 Reset();
373
374 #if DEBUG
375 Console.WriteLine("Loaded map {0} of type {1} written by {2}.",
376 metadata.Name,
377 metadata.Type,
378 metadata.Author);
379 #endif
380 }
381
382
383 public void Reset()
384 {
385 mGrid = (char[,])mCleanGrid.Clone();
386
387 mBooleanGrid = new bool[mMetadata.GridWidth, mMetadata.GridHeight];
388 for (int x = 0; x < mMetadata.GridWidth; x++)
389 {
390 for (int y = 0; y < mMetadata.GridHeight; y++)
391 {
392 mBooleanGrid[x, y] = IsCellOpen(x, y);
393 }
394 }
395 }
396
397
398 public bool IsCellOpen(int x, int y)
399 {
400 // TODO: Still need to define characters for types of scenery.
401 if (IsOnMap(x, y)) return mGrid[x, y] == ' ';
402 return false;
403 }
404
405 public void SetCell(int x, int y, char tile)
406 {
407 if (IsOnMap(x, y))
408 {
409 mGrid[x, y] = tile;
410 mBooleanGrid[x, y] = IsCellOpen(x, y);
411 }
412 }
413
414 public void ClearCell(int x, int y)
415 {
416 SetCell(x, y, mDefaultTile);
417 }
418
419 public bool IsOnMap(int x, int y)
420 {
421 return 0 <= x && x < Metadata.GridWidth && 0 <= y && y < Metadata.GridHeight;
422 }
423
424
425 public List<object> GetAllEntities()
426 {
427 List<object> list = new List<object>();
428
429 foreach (RawEntity raw in mEntities)
430 {
431 if (raw.Attributes.ContainsKey("type"))
432 {
433 string typename = raw.Attributes["type"];
434
435 object[] args = new object[3];
436 args[0] = raw.Id;
437 args[1] = raw.Position;
438 args[2] = raw.Attributes;
439
440 try
441 {
442
443 object entity = Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
444 if (entity != null) list.Add(entity);
445 else throw new RuntimeException();
446 }
447 #pragma warning disable 0168
448 catch (System.Exception ex)
449 #pragma warning restore 0168
450 {
451 throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
452 }
453 }
454 else
455 {
456 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
457 }
458 }
459
460 return list;
461 }
462
463 public List<T> GetEntities<T>()
464 {
465 System.Type type = typeof(T);
466 List<T> list = new List<T>();
467
468 string typename = typeof(T).Name;
469 foreach (RawEntity raw in mEntities)
470 {
471 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
472 {
473 object[] args = new object[3];
474 args[0] = raw.Id;
475 args[1] = raw.Position;
476 args[2] = raw.Attributes;
477
478 T entity = (T)Activator.CreateInstance(type, args);
479 if (entity != null) list.Add(entity);
480 else throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
481 }
482 }
483
484 return list;
485 }
486
487
488 Metadata mMetadata;
489 char[,] mGrid;
490 char[,] mCleanGrid;
491 bool[,] mBooleanGrid;
492 char mDefaultTile;
493 List<RawEntity> mEntities;
494 Point[] mPlayerPositions;
495 }
496
497 class View
498 {
499 public Vector2 CenterCell;
500 public float Zoom;
501
502
503 public View(Modal data)
504 {
505 Debug.Assert(data != null);
506 mData = data;
507
508 Reset();
509 }
510
511
512 public void Reset()
513 {
514 CenterCell = Vector2.Zero;
515 Zoom = PixelsToUnitSquares;
516 }
517
518
519 public void Draw(SpriteBatch spriteBatch)
520 {
521 mViewport = spriteBatch.GraphicsDevice.Viewport;
522
523 // TODO: There is no culling yet, but it runs so fast that it probably won't ever need it.
524 for (int y = 0; y < mData.Metadata.GridHeight; y++)
525 {
526 for (int x = 0; x < mData.Metadata.GridWidth; x++)
527 {
528 if (mData.IsCellOpen(x, y))
529 {
530 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.White);
531 }
532 else
533 {
534 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.DarkBlue);
535 }
536 }
537 }
538 }
539
540
541 public Point GetPointFromCoordinates(float x, float y)
542 {
543 Matrix transform = GetTransformation(CenterCell);
544 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
545
546 return new Point((int)point.X, (int)point.Y);
547 }
548
549 public Rectangle GetRectangleFromCoordinates(float x, float y)
550 {
551 Matrix transform = GetTransformation(CenterCell);
552 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
553
554 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));
555 }
556
557
558
559 Matrix GetTransformation(Vector2 center)
560 {
561 float halfRatio = Zoom * 0.5f;
562 Matrix transform = Matrix.CreateTranslation(-center.X, -center.Y, 0.0f);
563 transform *= Matrix.CreateScale(Zoom);
564 transform *= Matrix.CreateTranslation(mViewport.Width * 0.5f - halfRatio,
565 mViewport.Height * 0.5f - halfRatio, 0.0f);
566
567 Vector2 topLeft = Vector2.Transform(new Vector2(0.0f, 0.0f), transform);
568 topLeft.X = Math.Max(mViewport.X, topLeft.X);
569 topLeft.Y = Math.Max(mViewport.Y, topLeft.Y);
570 transform *= Matrix.CreateTranslation(-topLeft.X, -topLeft.Y, 0.0f);
571
572 Vector2 bottomRight = Vector2.Transform(new Vector2((float)mData.Metadata.GridWidth,
573 (float)mData.Metadata.GridHeight), transform);
574 float right = mViewport.X + mViewport.Width;
575 float bottom = mViewport.Y + mViewport.Height;
576 bottomRight.X = Math.Min(right, bottomRight.X) - right;
577 bottomRight.Y = Math.Min(bottom, bottomRight.Y) - bottom;
578 transform *= Matrix.CreateTranslation(-bottomRight.X, -bottomRight.Y, 0.0f);
579
580 return transform;
581 }
582
583
584 Modal mData;
585 Viewport mViewport;
586 }
587
588 #endregion
589
590
591 #region Private Variables
592
593 Modal mData;
594 View mView;
595
596 #endregion
597 }
598 }
This page took 0.060272 seconds and 5 git commands to generate.