]> Dogcows Code - chaz/carfire/blob - CarFire/CarFire/CarFire/Map.cs
git-svn-id: https://bd85.net/svn/cs3505_group@83 92bb83a3-7c8f-8a45-bc97-515c4e399668
[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 = 60.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 Attributes
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 a list of the raw entity containers loaded with the map.
132 /// </summary>
133 public List<RawEntity> RawEntities { get { return mData.Entities; } }
134
135
136 /// <summary>
137 /// Get and set the coordinate of the grid cell that should be in
138 /// the center of the screen when the map is drawn.
139 /// </summary>
140 public Vector2 CenterCell
141 {
142 get { return mView.CenterCell; }
143 set { mView.CenterCell = value; }
144 }
145
146 #endregion
147
148
149 #region Public Methods
150
151 /// <summary>
152 /// Construct a map with the provided map data.
153 /// </summary>
154 /// <param name="metadata">The metadata.</param>
155 /// <param name="grid">The grid.</param>
156 /// <param name="entities">The entities.</param>
157 public Map(Metadata metadata, char[,] grid, List<RawEntity> entities)
158 {
159 mData = new Modal(metadata, grid, entities);
160 mView = new View(mData);
161 }
162
163
164 /// <summary>
165 /// Draw a representation of the map to the screen.
166 /// </summary>
167 /// <param name="spriteBatch">The jeewiz.</param>
168 public void Draw(SpriteBatch spriteBatch)
169 {
170 mView.Draw(spriteBatch);
171 }
172
173
174 /// <summary>
175 /// Get a point in screen-space from a coordinate in gridspace.
176 /// </summary>
177 /// <param name="x">X-coordinate.</param>
178 /// <param name="y">Y-coordinate.</param>
179 /// <returns>Transformed point.</returns>
180 public Point GetPointFromCoordinates(float x, float y)
181 {
182 return mView.GetPointFromCoordinates(x, y);
183 }
184
185 /// <summary>
186 /// Get a point in screen-space from a coordinate in gridspace.
187 /// </summary>
188 /// <param name="point">X,Y-coordinates.</param>
189 /// <returns>Transformed point.</returns>
190 public Point GetPointFromCoordinates(Vector2 point)
191 {
192 return mView.GetPointFromCoordinates(point.X, point.Y);
193 }
194
195 /// <summary>
196 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
197 /// </summary>
198 /// <param name="x">X-coordinate.</param>
199 /// <param name="y">Y-coordinate.</param>
200 /// <returns>Transformed rectangle.</returns>
201 public Rectangle GetRectangleFromCoordinates(float x, float y)
202 {
203 return mView.GetRectangleFromCoordinates(x, y);
204 }
205
206 /// <summary>
207 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
208 /// </summary>
209 /// <param name="point">X,Y-coordinates.</param>
210 /// <returns>Transformed rectangle.</returns>
211 public Rectangle GetRectangleFromCoordinates(Vector2 point)
212 {
213 return mView.GetRectangleFromCoordinates(point.X, point.Y);
214 }
215
216
217 /// <summary>
218 /// Determine whether or not a cell can be occupied by a game entity.
219 /// </summary>
220 /// <param name="x">X-coordinate.</param>
221 /// <param name="y">Y-coordinate.</param>
222 /// <returns>True if cell can be occupied, false otherwise.</returns>
223 public bool IsCellOpen(int x, int y)
224 {
225 return mData.IsCellOpen(x, y);
226 }
227
228 /// <summary>
229 /// Determine whether or not a cell can be occupied by a game entity.
230 /// </summary>
231 /// <param name="point">X,Y-coordinates.</param>
232 /// <returns>True if cell can be occupied, false otherwise.</returns>
233 public bool IsCellOpen(Point point)
234 {
235 return mData.IsCellOpen(point.X, point.Y);
236 }
237
238
239 /// <summary>
240 /// Get all the entities loaded from the map file. Exceptions could be
241 /// thrown if there are entities without associated classes.
242 /// </summary>
243 /// <returns>List of entity objects loaded.</returns>
244 public List<object> GetAllEntities()
245 {
246 return mData.GetAllEntities();
247 }
248
249 /// <summary>
250 /// Get the entities of a certain type loaded from the map file. Exceptions
251 /// could be thrown if there are entities without associated classes.
252 /// </summary>
253 /// <typeparam name="T">Type of the entity you want a list of.</typeparam>
254 /// <returns>List of entity objects loaded.</returns>
255 public List<T> GetEntities<T>()
256 {
257 return mData.GetEntities<T>();
258 }
259
260 #endregion
261
262
263 #region Private Types
264
265 class Modal
266 {
267 Metadata mMetadata;
268 char[,] mGrid;
269 List<RawEntity> mEntities;
270
271 public Modal(Metadata metadata, char[,] grid, List<RawEntity> entities)
272 {
273 Debug.Assert(metadata != null);
274 Debug.Assert(grid != null);
275 Debug.Assert(entities != null);
276 Debug.Assert(metadata.GridWidth * metadata.GridHeight == grid.Length);
277
278 mMetadata = metadata;
279 mGrid = grid;
280 mEntities = entities;
281
282 #if DEBUG
283 Console.WriteLine("Loaded map {0} of type {1} written by {2}.",
284 metadata.Name,
285 metadata.Type,
286 metadata.Author);
287 #endif
288 }
289
290
291 public Metadata Metadata { get { return mMetadata; } }
292 public List<RawEntity> Entities { get { return mEntities; } }
293
294
295 public bool IsCellOpen(int x, int y)
296 {
297 // TODO: Still need to define characters for types of scenery.
298 return mGrid[x, y] == ' ';
299 }
300
301
302 public List<object> GetAllEntities()
303 {
304 List<object> list = new List<object>();
305
306 foreach (RawEntity raw in mEntities)
307 {
308 if (raw.Attributes.ContainsKey("type"))
309 {
310 string typename = raw.Attributes["type"];
311
312 object[] args = new object[3];
313 args[0] = raw.Id;
314 args[1] = raw.Position;
315 args[2] = raw.Attributes;
316
317 try
318 {
319
320 object entity = Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
321 if (entity != null) list.Add(entity);
322 else throw new RuntimeException();
323 }
324 #pragma warning disable 0168
325 catch (System.Exception ex)
326 #pragma warning restore 0168
327 {
328 throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
329 }
330 }
331 else
332 {
333 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
334 }
335 }
336
337 return list;
338 }
339
340 public List<T> GetEntities<T>()
341 {
342 System.Type type = typeof(T);
343 List<T> list = new List<T>();
344
345 string typename = typeof(T).Name;
346 foreach (RawEntity raw in mEntities)
347 {
348 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
349 {
350 object[] args = new object[3];
351 args[0] = raw.Id;
352 args[1] = raw.Position;
353 args[2] = raw.Attributes;
354
355 T entity = (T)Activator.CreateInstance(type, args);
356 if (entity != null) list.Add(entity);
357 else throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
358 }
359 }
360
361 return list;
362 }
363 }
364
365 class View
366 {
367 Modal mData;
368
369 public Vector2 CenterCell;
370 Viewport mViewport;
371
372
373 public View(Modal data)
374 {
375 Debug.Assert(data != null);
376 mData = data;
377 }
378
379 public void Draw(SpriteBatch spriteBatch)
380 {
381 mViewport = spriteBatch.GraphicsDevice.Viewport;
382
383 // TODO: There is no culling yet, but it runs so fast that it probably won't ever need it.
384 for (int y = 0; y < mData.Metadata.GridHeight; y++)
385 {
386 for (int x = 0; x < mData.Metadata.GridWidth; x++)
387 {
388 if (mData.IsCellOpen(x, y))
389 {
390 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.White);
391 }
392 else
393 {
394 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.DarkBlue);
395 }
396 }
397 }
398 }
399
400 /// <summary>
401 /// Get a matrix to transform a point from grid-space to screen coordinates. This
402 /// method uses the viewport to bound the edges of the map such that the camera
403 /// will not show anything outside of the grid.
404 /// </summary>
405 /// <param name="center">The point to put in the center.</param>
406 /// <returns>The transformation matrix.</returns>
407 Matrix GetTransformation(Vector2 center)
408 {
409 float halfRatio = PixelsToUnitSquares * 0.5f;
410 Matrix transform = Matrix.CreateTranslation(-center.X, -center.Y, 0.0f);
411 transform *= Matrix.CreateScale(PixelsToUnitSquares);
412 transform *= Matrix.CreateTranslation(mViewport.Width * 0.5f - halfRatio,
413 mViewport.Height * 0.5f - halfRatio, 0.0f);
414
415 Vector2 topLeft = Vector2.Transform(new Vector2(0.0f, 0.0f), transform);
416 topLeft.X = Math.Max(mViewport.X, topLeft.X);
417 topLeft.Y = Math.Max(mViewport.Y, topLeft.Y);
418 transform *= Matrix.CreateTranslation(-topLeft.X, -topLeft.Y, 0.0f);
419
420 Vector2 bottomRight = Vector2.Transform(new Vector2((float)mData.Metadata.GridWidth,
421 (float)mData.Metadata.GridHeight), transform);
422 float right = mViewport.X + mViewport.Width;
423 float bottom = mViewport.Y + mViewport.Height;
424 bottomRight.X = Math.Min(right, bottomRight.X) - right;
425 bottomRight.Y = Math.Min(bottom, bottomRight.Y) - bottom;
426 transform *= Matrix.CreateTranslation(-bottomRight.X, -bottomRight.Y, 0.0f);
427
428 return transform;
429 }
430
431
432 public Point GetPointFromCoordinates(float x, float y)
433 {
434 Matrix transform = GetTransformation(CenterCell);
435 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
436
437 return new Point((int)point.X, (int)point.Y);
438 }
439
440 public Rectangle GetRectangleFromCoordinates(float x, float y)
441 {
442 Matrix transform = GetTransformation(CenterCell);
443 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
444
445 return new Rectangle((int)point.X, (int)point.Y, (int)PixelsToUnitSquares, (int)PixelsToUnitSquares);
446 }
447 }
448
449 #endregion
450
451
452 #region Private Variables
453
454 Modal mData;
455 View mView;
456
457 #endregion
458 }
459 }
This page took 0.049066 seconds and 5 git commands to generate.