TextureAtlasReader.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 Microsoft.Xna.Framework;
  18. using Microsoft.Xna.Framework.Content;
  19. using Microsoft.Xna.Framework.Graphics;
  20. using nkast.Aether.Graphics;
  21. namespace nkast.Aether.Graphics.Content
  22. {
  23. public class TextureAtlasReader : ContentTypeReader<TextureAtlas>
  24. {
  25. protected override TextureAtlas Read(ContentReader input, TextureAtlas existingInstance)
  26. {
  27. IGraphicsDeviceService graphicsDeviceService = (IGraphicsDeviceService)input.ContentManager.ServiceProvider.GetService(typeof(IGraphicsDeviceService));
  28. var device = graphicsDeviceService.GraphicsDevice;
  29. TextureAtlas output = existingInstance ?? new TextureAtlas();
  30. // read standard Texture2D
  31. output.Texture = ReadTexture2D(input, output.Texture);
  32. // read Sprites
  33. var count = input.ReadInt32();
  34. for (int i = 0; i < count; i++)
  35. {
  36. var name = input.ReadString();
  37. var bounds = new Rectangle(input.ReadInt32(), input.ReadInt32(), input.ReadInt32(), input.ReadInt32());
  38. output.Sprites[name] = new Sprite(output.Texture, bounds);
  39. }
  40. return output;
  41. }
  42. private Texture2D ReadTexture2D(ContentReader input, Texture2D existingInstance)
  43. {
  44. Texture2D output = null;
  45. try
  46. {
  47. output = input.ReadRawObject<Texture2D>(existingInstance);
  48. }
  49. catch(NotSupportedException)
  50. {
  51. var assembly = typeof(Microsoft.Xna.Framework.Content.ContentTypeReader).Assembly;
  52. var texture2DReaderType = assembly.GetType("Microsoft.Xna.Framework.Content.Texture2DReader");
  53. var texture2DReader = (ContentTypeReader)Activator.CreateInstance(texture2DReaderType, true);
  54. output = input.ReadRawObject<Texture2D>(texture2DReader, existingInstance);
  55. }
  56. return output;
  57. }
  58. }
  59. }