Skip to content

Commit

Permalink
adds new way to add textureholder
Browse files Browse the repository at this point in the history
  • Loading branch information
zimmermannubique committed Jan 25, 2024
1 parent 0c73240 commit e231862
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions ios/graphics/Texture/TextureHolder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,51 @@ public class TextureHolder: NSObject {
let texture = try MetalContext.current.textureLoader.newTexture(data: data, options: options)
self.init(texture, textureUsableSize: textureUsableSize)
}

public convenience init(_ size: CGSize, drawCallback: ((CGContext) -> Void)) throws {
guard size.width > 0, size.height > 0 else {
throw TextureHolderError.emptyData
}

let width : Int = Int(size.width)
let height : Int = Int(size.height)

let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * width

let td = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm, width: width, height: height, mipmapped: false)
td.usage = .shaderRead

guard let texture = MetalContext.current.device.makeTexture(descriptor: td) else {
throw TextureHolderError.emptyData
}

let length = 4 * width * height
guard let imageData = calloc(width * height, 4) else {
throw TextureHolderError.emptyData
}

let data = NSMutableData(bytesNoCopy: imageData, length: length, freeWhenDone: true)

let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue)

guard let context = CGContext(data: data.mutableBytes, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 4 * width, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else {
throw TextureHolderError.emptyData
}

context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)

UIGraphicsPushContext(context)
drawCallback(context)
UIGraphicsPopContext()

let region = MTLRegionMake2D(0, 0, width, height)
texture.replace(region: region, mipmapLevel: 0, withBytes: data.bytes, bytesPerRow: bytesPerRow)

self.init(texture, textureUsableSize: nil)
}
}

extension TextureHolder: MCTextureHolderInterface {
Expand Down

0 comments on commit e231862

Please sign in to comment.