TextureAtlasReader.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #region License
  2. // Copyright 2016-2021 Kastellanos Nikolaos
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #endregion
  16. using System;
  17. using System.Reflection;
  18. using Microsoft.Xna.Framework;
  19. using Microsoft.Xna.Framework.Content;
  20. using Microsoft.Xna.Framework.Graphics;
  21. using nkast.Aether.Graphics;
  22. namespace nkast.Aether.Graphics.Content
  23. {
  24. public class TextureAtlasReader : ContentTypeReader<TextureAtlas>
  25. {
  26. protected override TextureAtlas Read(ContentReader input, TextureAtlas existingInstance)
  27. {
  28. IGraphicsDeviceService graphicsDeviceService = (IGraphicsDeviceService)input.ContentManager.ServiceProvider.GetService(typeof(IGraphicsDeviceService));
  29. GraphicsDevice device = graphicsDeviceService.GraphicsDevice;
  30. TextureAtlas output = existingInstance ?? new TextureAtlas();
  31. // read standard Texture2D
  32. output.Texture = ReadTexture2D(input, output.Texture);
  33. // read Sprites
  34. int count = input.ReadInt32();
  35. for (int i = 0; i < count; i++)
  36. {
  37. string name = input.ReadString();
  38. Rectangle bounds = new Rectangle(input.ReadInt32(), input.ReadInt32(), input.ReadInt32(), input.ReadInt32());
  39. output.Sprites[name] = new Sprite(output.Texture, bounds);
  40. }
  41. return output;
  42. }
  43. private Texture2D ReadTexture2D(ContentReader input, Texture2D existingInstance)
  44. {
  45. Texture2D output = null;
  46. try
  47. {
  48. output = input.ReadRawObject<Texture2D>(existingInstance);
  49. }
  50. catch(NotSupportedException)
  51. {
  52. Assembly assembly = typeof(ContentTypeReader).Assembly;
  53. Type texture2DReaderType = assembly.GetType("Microsoft.Xna.Framework.Content.Texture2DReader");
  54. ContentTypeReader texture2DReader = (ContentTypeReader)Activator.CreateInstance(texture2DReaderType, true);
  55. output = input.ReadRawObject<Texture2D>(texture2DReader, existingInstance);
  56. }
  57. return output;
  58. }
  59. }
  60. }