MetalStageBuffer.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /******************************************************************************
  2. Copyright (C) 2024 by Patrick Heyer <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. import Foundation
  15. import Metal
  16. class MetalStageBuffer {
  17. let device: MetalDevice
  18. let buffer: MTLBuffer
  19. let format: MTLPixelFormat
  20. let width: Int
  21. let height: Int
  22. init?(device: MetalDevice, width: Int, height: Int, format: MTLPixelFormat) {
  23. self.device = device
  24. self.width = width
  25. self.height = height
  26. self.format = format
  27. guard let bytesPerPixel = format.bytesPerPixel,
  28. let buffer = device.device.makeBuffer(
  29. length: width * height * bytesPerPixel,
  30. options: .storageModeShared
  31. )
  32. else {
  33. return nil
  34. }
  35. self.buffer = buffer
  36. }
  37. /// Gets an opaque pointer for the ``MetalStageBuffer`` instance and increases its reference count by one
  38. /// - Returns: `OpaquePointer` to class instance
  39. ///
  40. /// > Note: Use this method when the instance is to be shared via an `OpaquePointer` and needs to be retained. Any
  41. /// opaque pointer shared this way needs to be converted into a retained reference again to ensure automatic
  42. /// deinitialization by the Swift runtime.
  43. func getRetained() -> OpaquePointer {
  44. let retained = Unmanaged.passRetained(self).toOpaque()
  45. return OpaquePointer(retained)
  46. }
  47. /// Gets an opaque pointer for the ``MetalStageBuffer`` instance without increasing its reference count
  48. /// - Returns: `OpaquePointer` to class instance
  49. func getUnretained() -> OpaquePointer {
  50. let unretained = Unmanaged.passUnretained(self).toOpaque()
  51. return OpaquePointer(unretained)
  52. }
  53. }