ContentReaderExtensions.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.IO;
  3. using System.Reflection;
  4. using Microsoft.Xna.Framework.Content;
  5. using Microsoft.Xna.Framework.Graphics;
  6. using MonoGame.Extended.Tiled;
  7. namespace MonoGame.Extended.Content
  8. {
  9. public static class ContentReaderExtensions
  10. {
  11. #if FNA
  12. public static GraphicsDevice GetGraphicsDevice(this ContentReader contentReader)
  13. {
  14. var serviceProvider = contentReader.ContentManager.ServiceProvider;
  15. var graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
  16. if (graphicsDeviceService == null)
  17. {
  18. throw new InvalidOperationException("No Graphics Device Service");
  19. }
  20. return graphicsDeviceService.GraphicsDevice;
  21. }
  22. #endif
  23. public static string RemoveExtension(string path)
  24. {
  25. return Path.ChangeExtension(path, null).TrimEnd('.');
  26. }
  27. public static string GetRelativeAssetName(this ContentReader contentReader, string relativeName)
  28. {
  29. var assetDirectory = Path.GetDirectoryName(contentReader.AssetName);
  30. var assetName = RemoveExtension(Path.Combine(assetDirectory, relativeName).Replace('\\', '/'));
  31. return ShortenRelativePath(assetName);
  32. }
  33. public static string ShortenRelativePath(string relativePath)
  34. {
  35. var ellipseIndex = relativePath.IndexOf("/../", StringComparison.Ordinal);
  36. while (ellipseIndex != -1)
  37. {
  38. var lastDirectoryIndex = relativePath.LastIndexOf('/', ellipseIndex - 1) + 1;
  39. relativePath = relativePath.Remove(lastDirectoryIndex, ellipseIndex + 4 - lastDirectoryIndex);
  40. ellipseIndex = relativePath.IndexOf("/../", StringComparison.Ordinal);
  41. }
  42. return relativePath;
  43. }
  44. public static void ReadTiledMapProperties(this ContentReader reader, TiledMapProperties properties)
  45. {
  46. var count = reader.ReadInt32();
  47. for (var i = 0; i < count; i++)
  48. {
  49. var key = reader.ReadString();
  50. var value = new TiledMapPropertyValue(reader.ReadString());
  51. ReadTiledMapProperties(reader, value.Properties);
  52. properties[key] = value;
  53. }
  54. }
  55. }
  56. }