VulkanTimelineSemaphore.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using Avalonia.Platform;
  4. using Silk.NET.Vulkan;
  5. using Silk.NET.Vulkan.Extensions.EXT;
  6. using SilkNetDemo;
  7. namespace GpuInterop.VulkanDemo;
  8. class VulkanTimelineSemaphore : IDisposable
  9. {
  10. private VulkanContext _resources;
  11. public unsafe VulkanTimelineSemaphore(VulkanContext resources)
  12. {
  13. _resources = resources;
  14. var mtlEvent = new ExportMetalObjectCreateInfoEXT
  15. {
  16. SType = StructureType.ExportMetalObjectCreateInfoExt,
  17. ExportObjectType = ExportMetalObjectTypeFlagsEXT.SharedEventBitExt
  18. };
  19. var semaphoreTypeInfo = new SemaphoreTypeCreateInfoKHR()
  20. {
  21. SType = StructureType.SemaphoreTypeCreateInfo,
  22. SemaphoreType = SemaphoreType.Timeline,
  23. PNext = &mtlEvent
  24. };
  25. var semaphoreCreateInfo = new SemaphoreCreateInfo
  26. {
  27. SType = StructureType.SemaphoreCreateInfo,
  28. PNext = &semaphoreTypeInfo,
  29. };
  30. resources.Api.CreateSemaphore(resources.Device, semaphoreCreateInfo, null, out var semaphore).ThrowOnError();
  31. Handle = semaphore;
  32. }
  33. public Semaphore Handle { get; }
  34. public unsafe void Dispose()
  35. {
  36. _resources.Api.DestroySemaphore(_resources.Device, Handle, null);
  37. }
  38. public unsafe IntPtr ExportSharedEvent()
  39. {
  40. if (!_resources.Api.TryGetDeviceExtension<ExtMetalObjects>(_resources.Instance, _resources.Device, out var ext))
  41. throw new InvalidOperationException();
  42. var eventExport = new ExportMetalSharedEventInfoEXT()
  43. {
  44. SType = StructureType.ExportMetalSharedEventInfoExt,
  45. Semaphore = Handle,
  46. };
  47. var export = new ExportMetalObjectsInfoEXT()
  48. {
  49. SType = StructureType.ExportMetalObjectsInfoExt,
  50. PNext = &eventExport
  51. };
  52. ext.ExportMetalObjects(_resources.Device, ref export);
  53. if (eventExport.MtlSharedEvent == IntPtr.Zero)
  54. throw new Exception("Unable to export IOSurfaceRef");
  55. return eventExport.MtlSharedEvent;
  56. }
  57. public IPlatformHandle Export()
  58. {
  59. if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  60. return new PlatformHandle(ExportSharedEvent(),
  61. KnownPlatformGraphicsExternalSemaphoreHandleTypes.MetalSharedEvent);
  62. throw new PlatformNotSupportedException();
  63. }
  64. }