MetalKit

RSS for tag

Render graphics in a standard Metal view, load textures from many sources, and work efficiently with models provided by Model I/O using MetalKit.

Posts under MetalKit tag

200 Posts

Post

Replies

Boosts

Views

Activity

Showing photo from PHPickerViewController in "HDR" mode
How to show photos from PHPickerViewController the way they are shown in Apple's Photos with "View Full HDR" enabled? I've found all EDR-related talks, rendering CIImage into MTKView already... nothing helps, image is same as in UIImageView. How?! :–) What I do now: I get photo URL (copy) via provider.loadFileRepresentation(forTypeIdentifier: UTType.image.identifier I create MTKView with metalLayer.wantsExtendedDynamicRangeContent = true and other recommended settings I load CIImage from URL provided earlier. I render CIImage via CIContext backed with mtlCommandQueue with option .useSoftwareRenderer: false. And I still get "normal" image. Exact same image is being displayed in Photos app with much brighter whites, and this is exactly what I want to achieve. Please help :) Thanks!
4
0
1.8k
Dec ’22
Draw `MTLTexture` to `CAMetalLayer`
I am drawing stuff onto an off-screen MTLTexture. (using Skia Canvas) At a later point, I want to render this MTLTexture into a CAMetalLayer to display it on the screen. Since I was using Skia for the off-screen drawing operations, my code is quite simple and I don't have the typical Metal setup (no MTLLibrary, MTLRenderPipelineDescriptor, MTLRenderPassDescriptor, MTLRenderEncoder, etc). I now simply want to draw that MTLTexture into a CAMetalLayer, but haven't figured out how to do so simply. This is where I draw my stuff to the MTLTexture _texture (Skia code): - (void) renderNewFrameToCanvas(Frame frame) { if (_skContext == nullptr) { GrContextOptions grContextOptions; _skContext = GrDirectContext::MakeMetal((__bridge void*)_device, // TODO: Use separate command queue for this context? (__bridge void*)_commandQueue, grContextOptions); } @autoreleasepool { // Lock Mutex to block the runLoop from overwriting the _texture std::lock_guard lockGuard(_textureMutex); auto texture = _texture; // Get & Lock the writeable Texture from the Metal Drawable GrMtlTextureInfo fbInfo; fbInfo.fTexture.retain((__bridge void*)texture); GrBackendRenderTarget backendRT(texture.width, texture.height, 1, fbInfo); // Create a Skia Surface from the writable Texture auto skSurface = SkSurface::MakeFromBackendRenderTarget(_skContext.get(), backendRT, kTopLeft_GrSurfaceOrigin, kBGRA_8888_SkColorType, nullptr, nullptr); auto canvas = skSurface->getCanvas(); auto surface = canvas->getSurface(); // Clear anything that's currently on the Texture canvas->clear(SkColors::kBlack); // Converts the Frame to an SkImage - RGB. auto image = SkImageHelpers::convertFrameToSkImage(_skContext.get(), frame); canvas->drawImage(image, 0, 0); // Flush all appended operations on the canvas and commit it to the SkSurface canvas->flush(); // TODO: Do I need to commit? /* id<MTLCommandBuffer> commandBuffer([_commandQueue commandBuffer]); [commandBuffer commit]; */ } } Now, since I have the MTLTexture _texture in memory, I want to draw it to the CAMetalLayer _layer. This is what I have so far: - (void) setup { // I set up a runLoop that calls render() 60 times a second. // [removed to simplify] _renderPassDescriptor = [[MTLRenderPassDescriptor alloc] init]; // Load the compiled Metal shader (PassThrough.metal) auto baseBundle = [NSBundle mainBundle]; auto resourceBundleUrl = [baseBundle URLForResource:@"VisionCamera" withExtension:@"bundle"]; auto resourceBundle = [[NSBundle alloc] initWithURL:resourceBundleUrl]; auto shaderLibraryUrl = [resourceBundle URLForResource:@"PassThrough" withExtension:@"metallib"]; id<MTLLibrary> defaultLibrary = [_device newLibraryWithURL:shaderLibraryUrl error:nil]; id<MTLFunction> vertexFunction = [defaultLibrary newFunctionWithName:@"vertexPassThrough"]; id<MTLFunction> fragmentFunction = [defaultLibrary newFunctionWithName:@"fragmentPassThrough"]; // Create a Pipeline Descriptor that connects the CPU draw operations to the GPU Metal context auto pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init]; pipelineDescriptor.label = @"VisionCamera: Frame Texture -> Layer Pipeline"; pipelineDescriptor.vertexFunction = vertexFunction; pipelineDescriptor.fragmentFunction = fragmentFunction; pipelineDescriptor.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm; _pipelineState = [_device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:nil]; } - (void) render() { @autoreleasepool { // Blocks until the next Frame is ready (16ms at 60 FPS) auto drawable = [_layer nextDrawable]; std::unique_lock lock(_textureMutex); auto texture = _texture; MTLRenderPassDescriptor* renderPassDescriptor = [[MTLRenderPassDescriptor alloc] init]; renderPassDescriptor.colorAttachments[0].texture = drawable.texture; renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear; renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(); id<MTLCommandBuffer> commandBuffer([_commandQueue commandBuffer]); auto renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor]; [renderEncoder setLabel:@"VisionCamera: PreviewView Texture -> Layer"]; [renderEncoder setRenderPipelineState:_pipelineState]; [renderEncoder setFragmentTexture:texture atIndex:0]; [renderEncoder endEncoding]; [commandBuffer presentDrawable:drawable]; [commandBuffer commit]; lock.unlock(); } } And along with that, I have created the PassThrough.metal shader which is just for passing through a texture: #include <metal_stdlib> using namespace metal; // Vertex input/output structure for passing results from vertex shader to fragment shader struct VertexIO { float4 position [[position]]; float2 textureCoord [[user(texturecoord)]]; }; // Vertex shader for a textured quad vertex VertexIO vertexPassThrough(const device packed_float4 *pPosition [[ buffer(0) ]], const device packed_float2 *pTexCoords [[ buffer(1) ]], uint vid [[ vertex_id ]]) { VertexIO outVertex; outVertex.position = pPosition[vid]; outVertex.textureCoord = pTexCoords[vid]; return outVertex; } // Fragment shader for a textured quad fragment half4 fragmentPassThrough(VertexIO inputFragment [[ stage_in ]], texture2d<half> inputTexture [[ texture(0) ]], sampler samplr [[ sampler(0) ]]) { return inputTexture.sample(samplr, inputFragment.textureCoord); } Running this crashes the app with the following exception: validateRenderPassDescriptor:782: failed assertion `RenderPass Descriptor Validation Texture at colorAttachment[0] has usage (0x01) which doesn't specify MTLTextureUsageRenderTarget (0x04) This now raises three questions for me: Do I have to do all of that Metal setting up, packing along the PassThrough.metal shader, render pass stuff, etc just to draw the MTLTexture to the CAMetalLayer? Is there no simpler way? Why is the code above failing? When is the drawing from Skia actually committed to the MTLTexture? Do I need to commit the command buffer (as seen in my TODO)?
1
0
2.2k
Dec ’22
DRHT > error > MTLTextureDescriptor
my code: guard let drawable = view.currentDrawable else { return }     let renderPassDescriptor = MTLRenderPassDescriptor()     renderPassDescriptor.colorAttachments[0].texture = drawable.texture //There is a crash     renderPassDescriptor.colorAttachments[0].loadAction = .clear     renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 0) error info: MTLTextureDescriptor has height (9964) greater than the maximum allowed size of 8192. > validateTextureDimensions > validateTextureDimensions:1075: failed assertion `MTLTextureDescriptor has height (9964) greater than the maximum allowed size of 8192.' please help: I try to put a canvas on an image,as you can see,the size of this canvas is too large to exceed the GPU processing limit。Is there a better way that don't change size to solve this problem
2
0
1.8k
Dec ’22
Cannot Get Size of CAMetal Drawable Texture
I am having trouble with getting the size of the texture belonging to a CAMetalLayer Drawable. When I use view.drawableSize.width, it returns 2560x1440, however, when I use the Metal Debugger, I get the correct value of 2660x1432. If I hardcode my size to 2660x1432, my application works perfectly fine (except that I can't resize the window without it breaking), but when I try to use view.drawableSize.width, it doesn't work at all. I can see my scene being rendered in the debugger, but if I don't hardcode my screen size, it is not being displayed on the CAMetalLayer Drawable. How can I get the correct size using code?
0
1
1.1k
Dec ’22
CIImage generate CGImage is unavailable
I want to use CIFilter to create a CGImageRef, but when I get cgimage buffer , it is empty CIFilter<CITextImageGenerator> * filter = [CIFilter textImageGeneratorFilter];   filter.text = @"This is a test text";   filter.fontName = @"HoeflerText-Regula";   filter.fontSize = 12;   filter.scaleFactor = 1.0;   CIImage *image = filter.outputImage;   CIContext *context = [CIContext contextWithOptions:nil];   CGImageRef resultRef = [context createCGImage:image fromRect:image.extent];   UIImage *resultImage = [UIImage imageWithCGImage:resultRef];       CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(resultRef));   const unsigned char * buffer = CFDataGetBytePtr(data); And then I could not generate MTLTexture with this cgimage  MTKTextureLoader *loader = [[MTKTextureLoader alloc] initWithDevice:self.device];   NSError*error;   id<MTLTexture> fontTexture = [loader newTextureWithCGImage:resultRef                      options:@{     MTKTextureLoaderOptionOrigin : MTKTextureLoaderOriginFlippedVertically,     MTKTextureLoaderOptionSRGB : @(NO)   }                       error:&error];    How can I finish my work? Any suggestions about this question I am appreciate.
4
0
1.5k
Nov ’22
[Swift] Converting between Data, Buffers, variable types efficiently.
Ahoy Developrs, I was wondering if someone might be able to help me, regarding working with Data, Buffers and Pointers, as I am working with Metal, ModelIO and large arrays of vertex data. Are there ways of converting/accessing Data instances as their original variable type without having to map/duplicate the data into a new variable? and visa-vera. I have to convert arrays into MDLMeshBuffer to pass them into ModelIO, from custom geometry that I have made at runtime. This can be quite convoluted as I have my own array of structs for geometric topology. This gets converted into MetalBuffer for GPU drawing, but I want to leverage ModelIO for importing/exporting. To leverage ModelIO I need to convert to and from the ModelIO Mesh Buffers, which can be converted into Data objects, and then convert those into data specific All this conversion to and from create quite a bit of memory bloat. The following are 3 examples of how I have been interacting with the different types, are there better /more efficient ways of doing this? // Converts Data to variable var positions = Array<simd_float3>(repeating: simd_float3.zero, count: data2.count/MemoryLayout<simd_float3>.stride)   _ = arr2.withUnsafeMutableBytes { data.copyBytes(to: $0) } // Example ModelIO vert conversion for i in 0..<mdlMesh.vertexBuffers.count {       let vBuff = mdlMesh.vertexBuffers[i]       let buffLyt = mdlMesh.vertexDescriptor.layouts[i] as! MDLVertexBufferLayout       let vertCount = vBuff.length / buffLyt.stride       let buffermap:MDLMeshBufferMap = vBuff.map()       let rawBasePtr:UnsafeMutableRawPointer = buffermap.bytes               for vertIndex in 0..<vertCount {         let b = rawBasePtr.load(fromByteOffset: buffLyt.stride * vertIndex, as: (simd_float3).self)         vertices.append(b)       }     } // Example ModelIO submesh conversion /// The layout of the face indicies var topologyVertCount:Array<UInt8> = [] if subMesh.topology != nil {    let topology = subMesh.topology!    let faceBuffer = topology.faceTopology!    print("Topology Buffer : \(topology)")    print(" face count: \(topology.faceCount)")    print(" hole count: \(topology.holeCount)")    for faceIndex in 0..<topology.faceCount {           let b = faceBuffer.map().bytes.load(fromByteOffset: MemoryLayout<UInt8>.stride * faceIndex, as: UInt8.self)           topologyVertCount.append(b)    } } Thank you for the help, Simon
0
0
1.5k
Nov ’22
Programmatically Get Pipeline Statistics
As part of my automated testing on real devices I would like to get the pipeline statistics from my compute kernels (ALU, Memory, Control Flow, Occupancy, etc). I'm able to generate a GPU trace in code without issue but that requires manually opening up the trace to find the values I'm interested in. What I would like is an API to read that trace or some counter set which provides the statistics I'm interested in. Is this possible?
0
0
836
Oct ’22
ModelIO - Accessing original Obj data
Hi Devs, I have been trying to access the original obj data from an asset I loaded in using ModelIO. I import the asset using the MDLAsset(url: vertexDescriptor: bufferAllocator: preserveTopology: error:) I set preserve topology to true, which from my understanding should keep all the data consistent with the original. My question is how does one correlate the submesh face data to the vertex data and the index data? I have read the documents which mention you should use the order of the faceTopologyBuffer, which will result in a 3D object that does look correct but all the points have unique vertices (non welded edges). I can make an assumption and loop over all the vertices and remove any duplicates, there by creating my own index buffer, but that would create an assumption that all faces have been welded which is also not correct. Is there a way to get the original data out of MDLAsset, or should I look to other avenues like assimp? Thank you for the help, Simon
0
0
983
Oct ’22
Why use dispatch_semaphore to explicitly synchronize MTLbuffer updates?
Hi. I'm new to Metal(actually any type of software development run on apple products). I have many questions about using MTL::Buffer and dispatch_semaphore, and drawInMTKView(). I read README.md, but I need some more help understanding it. Full code of 03-animation in metal-cpp sample This is sample code in metal-cpp sample code by apple(I downloaded here). In this code, _pFrameData is an array of MTLBuffer, and kMaxFramesInFlight is the size of this array. Its type is static const int, and the value is 3. When Renderer is created, _pFrameData are initialized like that. void Renderer::buildFrameData() {     for ( int i = 0; i < Renderer::kMaxFramesInFlight; ++i )     {         _pFrameData[ i ]= _pDevice->newBuffer( sizeof( FrameData ), MTL::ResourceStorageModeManaged );     } } draw method, call by drawInMTKView. void Renderer::draw( MTK::View* pView ) {     NS::AutoreleasePool* pPool = NS::AutoreleasePool::alloc()->init();     _frame = (_frame + 1) % Renderer::kMaxFramesInFlight; MTL::Buffer* pFrameDataBuffer = _pFrameData[ _frame ];     MTL::CommandBuffer* pCmd = _pCommandQueue->commandBuffer();     dispatch_semaphore_wait( _semaphore, DISPATCH_TIME_FOREVER );     Renderer* pRenderer = this;     pCmd->addCompletedHandler( ^void( MTL::CommandBuffer* pCmd ){         dispatch_semaphore_signal( pRenderer->_semaphore );     });     reinterpret_cast< FrameData * >( pFrameDataBuffer->contents() )->angle = (_angle += 0.01f);     pFrameDataBuffer->didModifyRange( NS::Range::Make( 0, sizeof( FrameData ) ) );     MTL::RenderPassDescriptor* pRpd = pView->currentRenderPassDescriptor();     MTL::RenderCommandEncoder* pEnc = pCmd->renderCommandEncoder( pRpd );     pEnc->setRenderPipelineState( _pPSO );     pEnc->setVertexBuffer( _pArgBuffer, 0, 0 );     pEnc->useResource( _pVertexPositionsBuffer, MTL::ResourceUsageRead );     pEnc->useResource( _pVertexColorsBuffer, MTL::ResourceUsageRead );     pEnc->setVertexBuffer( pFrameDataBuffer, 0, 1 );     pEnc->drawPrimitives( MTL::PrimitiveType::PrimitiveTypeTriangle, NS::UInteger(0), NS::UInteger(3) );     pEnc->endEncoding();     pCmd->presentDrawable( pView->currentDrawable() );     pCmd->commit();     pPool->release(); } Q1. what is the meaning of kMaxFramesInFlight's name and value? Q2. how are dispatch_semaphore_wait() and drawInMTKView() working? At first, I guess if the count of dispatch_semaphore change 0, the Renderer::draw are blocked by dispatch_semaphore_wait() until GPU read the buffer and execute dispatch_semaphore_signal. But now I think it's not a correct understanding because I don't know about drawInMTKView. How much drawInMTKView is called in 1 second and when? Q3. and.... why use dispatch_semaphore for here? I try to change my code to use a single MTLBuffer for the same work. Just changing some code(add a single buffer, remove code for dispatch_semaphore), the changed code works same.
1
0
1.2k
Oct ’22
Convert SceneKit/matrix/transform code into pure Metal/MetalKit
Hi, I'm trying to convert my SceneKit code into pure Metal/MetalKit and I feel confused about this code and how I should rewrite it. I've made the code simple for this case with some pseudocode. The part where it says "SceneKit magic" is where I feel lost. The SCNNode is just an empty placeholder just as it is – and it works for the calculations it is doing inside. Any help and pointers are much appreciated :-) class Scene { let ball = Ball() let scnNode = SCNNode() var quaternionAngleVelocity = float2(0, 0) func update() { // pseudocode, the user press the up key quaternionAngleVelocity.x -= 3 // pseudocode, the user press the down key quaternionAngleVelocity.x += 3 // pseudocode, the user press the left key quaternionAngleVelocity.y -= 3 // pseudocode, the user press the right key quaternionAngleVelocity.y += 3 ... // apply friction quaternionAngleVelocity *= (1 - 0.05) // i.e. decrease with 5% // rotate let newQuaternionAxisX = simd_quatf(angle: quaternionAngleVelocity.x.degreesToRadians, axis: simd_float3(x: 1, y: 0, z: 0)) let newQuaternionAxisY = simd_quatf(angle: quaternionAngleVelocity.y.degreesToRadians, axis: simd_float3(x: 0, y: 1, z: 0)) let finalQuaternion = simd_normalize(newQuaternionAxisX * newQuaternionAxisY) // SceneKit magic…? let matrix4 = SCNMatrix4Mult(scnNode.worldTransform, SCNMatrix4(simd_float4x4(finalQuaternion))) scnNode.transform = matrix4 ball.quaternion = scnNode.simdWorldOrientation } } class Ball { var position: float3 = [0, 0, 0] var rotation: float3 = [0, 0, 0] { didSet { let rotationMatrix = float4x4(rotation: rotation) quaternion = simd_quatf(rotationMatrix) } } var scale: float3 = [1, 1, 1] var forwardVector: float3 { return normalize([sin(rotation.y), 0, cos(rotation.y)]) } var rightVector: float3 { return [forwardVector.z, forwardVector.y, -forwardVector.x] } var upVector: float3 { return [0, forwardVector.z, 0] } var quaternion = simd_quatf() var modelMatrix: float4x4 { let translateMatrix = float4x4(translation: position) // let rotateMatrix = float4x4(rotation: rotation) let rotateMatrix = float4x4(quaternion) let scaleMatrix = float4x4(scaling: scale) return (translateMatrix * rotateMatrix * scaleMatrix) } var worldTransform: float4x4 { return modelMatrix } }
3
0
1.8k
Oct ’22
GPU trace metal Unable to create shader debug session on MacBook Pro (16-inch, 2021) M1 max
When trying to debug my compute shaders by pressing the ladyBird button inside of GPU trace, the error "Unable to create shader debug session" occurs. This only happens on my M1 MAX mbp, the exact same project does not have this error on my old intel mbp. I have tried reinstalling the past 3 generations of Xcode yet I cannot fix this error. It is making it impossible for me to develop my program as there is no information online about how to fix this error.
2
1
1.2k
Sep ’22
Can't define the matrix_double3x3 in a c header
I tried to define the matrix_double3x3 properties but the compiler don't allow me to do. I can define the matrix_float3x3 or matrix_half3x3 but not for the matrix_double3x3. But I saw the matrix_types.h, it has typedef simd_double3x3 matrix_double3x3 My goal is to send the matrix_double3x3 to Metal for computing the rectified image. Environment Xcode 14.0 (14A309) Destination: macOS (Minimum Deployments: 12.3) macOS 12.6 (21G115)
1
0
2.2k
Sep ’22
M1 M2 webgl.ALIASED_POINT_SIZE_RANGE
I'm currently using gl.points to render sprites (lens flares, explosions, etc) looks like M1 / M2 hardware (ipad, macbook pro) limits the point size to 64. Every other device has minimum of 512, usually 1024, and many even provide 2048. wondering if this is a was a choice or oversight? Also, not sure where to file this type of bug/request as its specific to M1/M2 hardware that affects multiple devices? many thanks, -Dm
1
0
1k
Sep ’22
BGProcessingTask Using GPU in Background
I was wondering if it was possible for a BGProcessingTask to use the GPU in the background. My use case would be to modify a video file. I know normally that this is not allowed, but was wondering if by using a BGProcessingTask I get special access. I have tried in a demo project, and have gotten some confusing results. Sometimes it appears that it works (the GPU operation completes like it would in the foreground) and sometimes it does not work (the GPU operation does not write anything to the output texture). Was wondering if Apple has any specific guidance.
0
0
893
Sep ’22
Render video in metal.
So I wanted to render video from .mov file in MTKView. Short algorithm: Read CMSampleBuffer from .mov using AVAssetReader and AVAssetReaderTrackOutput. Convert CMSampleBuffer from step 1 to MTLTexture and pass it to renderer I did those 2 steps and got the picture with twitches and I don’t know why. Link to .mov https://www.dropbox.com/s/gmzxd8j94pjhc1q/2.MOV?dl=0. Link to result https://www.dropbox.com/s/exgf1tk7oqvon25/result.mov?dl=0. The code. ViewController.swift VideoReader.swift SampleConverter.swift TextureModel.swift Renderer.swift MyMetal.metal
1
0
2.7k
Sep ’22
MacOs Metal antialiasing
I'm making an app for MacOs, but I'm having problems with the antialiasing implementation in Metal. When compiling I get the following error: validateAttachmentOnDevice:540: failed assertion MTLRenderPassDescriptor render targets have inconsistent sample counts.' This is the code I use to implement the textures: - (void)makeTextures {     if ([depthTexture width] != drawableSize.width || [depthTexture height] != drawableSize.height)     {         MTLTextureDescriptor *colorDescriptor = [MTLTextureDescriptor new];         colorDescriptor.textureType = MTLTextureType2DMultisample;         colorDescriptor.sampleCount = 4;         colorDescriptor.pixelFormat = vista.colorPixelFormat;         colorDescriptor.width = drawableSize.width;         colorDescriptor.height = drawableSize.height;         colorDescriptor.usage = MTLTextureUsageRenderTarget;         colorDescriptor.storageMode = MTLStorageModePrivate;         msaaColorTexture = [view.device newTextureWithDescriptor:colorDescriptor];         MTLTextureDescriptor *resolveDescriptor = [MTLTextureDescriptor new];         resolveDescriptor.textureType = MTLTextureType2D;         resolveDescriptor.pixelFormat = vista.colorPixelFormat;         resolveDescriptor.width = drawableSize.width;         resolveDescriptor.height = drawableSize.height;         resolveDescriptor.storageMode = MTLStorageModePrivate;         msaaResolveColorTexture = [view.device newTextureWithDescriptor:resolveDescriptor];         MTLTextureDescriptor *desc = [MTLTextureDescriptor new];         desc.textureType = MTLTextureType2DMultisample;         desc.sampleCount = 4;         desc.pixelFormat = MTLPixelFormatDepth32Float;         desc.width = drawableSize.width;         desc.height = drawableSize.height;         desc.usage = MTLTextureUsageRenderTarget;         desc.storageMode = MTLStorageModePrivate;         depthTexture = [view.device newTextureWithDescriptor:desc];     } } If at the time of creating the MTLRenderPipelineDescriptor I add .samplecount = 4;, the error disappears, but nothing is drawing in the view. This are de PipelineDescriptor creation: MTLRenderPipelineDescriptor *pipelineStateDescriptor = [MTLRenderPipelineDescriptor new];     pipelineStateDescriptor.label = @"Simple Pipeline";     pipelineStateDescriptor.vertexFunction = vertexFunction;     pipelineStateDescriptor.fragmentFunction = fragmentFunction;     pipelineStateDescriptor.colorAttachments[0].pixelFormat = vista.colorPixelFormat;     pipelineStateDescriptor.depthAttachmentPixelFormat = MTLPixelFormatDepth32Float; // No error but black view.     //pipelineStateDescriptor.sampleCount = 4;     NSError *error;     pipelineState = [view.device newRenderPipelineStateWithDescriptor:pipelineStateDescriptor error:&error];     // Depth stencil.     MTLDepthStencilDescriptor *depthStencilDescriptor = [MTLDepthStencilDescriptor new];     depthStencilDescriptor.depthCompareFunction = MTLCompareFunctionLess;     depthStencilDescriptor.depthWriteEnabled = YES;     depthStencilState = [view.device newDepthStencilStateWithDescriptor:depthStencilDescriptor]; And passDescriptor: if (passDescriptor != nil) {         passDescriptor.colorAttachments[0].texture = msaaColorTexture;         passDescriptor.colorAttachments[0].resolveTexture = msaaResolveColorTexture;         passDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(1.0f, 1.0f, 1.0f, 1.0f);         passDescriptor.colorAttachments[0].storeAction = MTLStoreActionMultisampleResolve;         passDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear;         passDescriptor.depthAttachment.texture = depthTexture;         passDescriptor.depthAttachment.clearDepth = 1.0;         passDescriptor.depthAttachment.loadAction = MTLLoadActionClear;         passDescriptor.depthAttachment.storeAction = MTLStoreActionStore; . . . Any suggestion. Thanks by advice. Manuel C.
0
0
964
Aug ’22
Anchor of big objects in open area
I am just starting to learn AR. Thanks for the help. I am trying to bind large objects to a certain location in an open area. I tried to bind using an image, an object in a reality composer. After snapping, when moving, objects do not remain in the same place. ARGeoTrackingConfiguration is not available in my region. If you scan the world around you and then define it, then with a rainy day or the slightest change in the area (for example, mowing the lawn), the terrain will not be determined. What do you advise?
3
0
1.8k
Aug ’22
Showing photo from PHPickerViewController in "HDR" mode
How to show photos from PHPickerViewController the way they are shown in Apple's Photos with "View Full HDR" enabled? I've found all EDR-related talks, rendering CIImage into MTKView already... nothing helps, image is same as in UIImageView. How?! :–) What I do now: I get photo URL (copy) via provider.loadFileRepresentation(forTypeIdentifier: UTType.image.identifier I create MTKView with metalLayer.wantsExtendedDynamicRangeContent = true and other recommended settings I load CIImage from URL provided earlier. I render CIImage via CIContext backed with mtlCommandQueue with option .useSoftwareRenderer: false. And I still get "normal" image. Exact same image is being displayed in Photos app with much brighter whites, and this is exactly what I want to achieve. Please help :) Thanks!
Replies
4
Boosts
0
Views
1.8k
Activity
Dec ’22
Draw `MTLTexture` to `CAMetalLayer`
I am drawing stuff onto an off-screen MTLTexture. (using Skia Canvas) At a later point, I want to render this MTLTexture into a CAMetalLayer to display it on the screen. Since I was using Skia for the off-screen drawing operations, my code is quite simple and I don't have the typical Metal setup (no MTLLibrary, MTLRenderPipelineDescriptor, MTLRenderPassDescriptor, MTLRenderEncoder, etc). I now simply want to draw that MTLTexture into a CAMetalLayer, but haven't figured out how to do so simply. This is where I draw my stuff to the MTLTexture _texture (Skia code): - (void) renderNewFrameToCanvas(Frame frame) { if (_skContext == nullptr) { GrContextOptions grContextOptions; _skContext = GrDirectContext::MakeMetal((__bridge void*)_device, // TODO: Use separate command queue for this context? (__bridge void*)_commandQueue, grContextOptions); } @autoreleasepool { // Lock Mutex to block the runLoop from overwriting the _texture std::lock_guard lockGuard(_textureMutex); auto texture = _texture; // Get & Lock the writeable Texture from the Metal Drawable GrMtlTextureInfo fbInfo; fbInfo.fTexture.retain((__bridge void*)texture); GrBackendRenderTarget backendRT(texture.width, texture.height, 1, fbInfo); // Create a Skia Surface from the writable Texture auto skSurface = SkSurface::MakeFromBackendRenderTarget(_skContext.get(), backendRT, kTopLeft_GrSurfaceOrigin, kBGRA_8888_SkColorType, nullptr, nullptr); auto canvas = skSurface->getCanvas(); auto surface = canvas->getSurface(); // Clear anything that's currently on the Texture canvas->clear(SkColors::kBlack); // Converts the Frame to an SkImage - RGB. auto image = SkImageHelpers::convertFrameToSkImage(_skContext.get(), frame); canvas->drawImage(image, 0, 0); // Flush all appended operations on the canvas and commit it to the SkSurface canvas->flush(); // TODO: Do I need to commit? /* id<MTLCommandBuffer> commandBuffer([_commandQueue commandBuffer]); [commandBuffer commit]; */ } } Now, since I have the MTLTexture _texture in memory, I want to draw it to the CAMetalLayer _layer. This is what I have so far: - (void) setup { // I set up a runLoop that calls render() 60 times a second. // [removed to simplify] _renderPassDescriptor = [[MTLRenderPassDescriptor alloc] init]; // Load the compiled Metal shader (PassThrough.metal) auto baseBundle = [NSBundle mainBundle]; auto resourceBundleUrl = [baseBundle URLForResource:@"VisionCamera" withExtension:@"bundle"]; auto resourceBundle = [[NSBundle alloc] initWithURL:resourceBundleUrl]; auto shaderLibraryUrl = [resourceBundle URLForResource:@"PassThrough" withExtension:@"metallib"]; id<MTLLibrary> defaultLibrary = [_device newLibraryWithURL:shaderLibraryUrl error:nil]; id<MTLFunction> vertexFunction = [defaultLibrary newFunctionWithName:@"vertexPassThrough"]; id<MTLFunction> fragmentFunction = [defaultLibrary newFunctionWithName:@"fragmentPassThrough"]; // Create a Pipeline Descriptor that connects the CPU draw operations to the GPU Metal context auto pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init]; pipelineDescriptor.label = @"VisionCamera: Frame Texture -> Layer Pipeline"; pipelineDescriptor.vertexFunction = vertexFunction; pipelineDescriptor.fragmentFunction = fragmentFunction; pipelineDescriptor.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm; _pipelineState = [_device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:nil]; } - (void) render() { @autoreleasepool { // Blocks until the next Frame is ready (16ms at 60 FPS) auto drawable = [_layer nextDrawable]; std::unique_lock lock(_textureMutex); auto texture = _texture; MTLRenderPassDescriptor* renderPassDescriptor = [[MTLRenderPassDescriptor alloc] init]; renderPassDescriptor.colorAttachments[0].texture = drawable.texture; renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear; renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(); id<MTLCommandBuffer> commandBuffer([_commandQueue commandBuffer]); auto renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor]; [renderEncoder setLabel:@"VisionCamera: PreviewView Texture -> Layer"]; [renderEncoder setRenderPipelineState:_pipelineState]; [renderEncoder setFragmentTexture:texture atIndex:0]; [renderEncoder endEncoding]; [commandBuffer presentDrawable:drawable]; [commandBuffer commit]; lock.unlock(); } } And along with that, I have created the PassThrough.metal shader which is just for passing through a texture: #include <metal_stdlib> using namespace metal; // Vertex input/output structure for passing results from vertex shader to fragment shader struct VertexIO { float4 position [[position]]; float2 textureCoord [[user(texturecoord)]]; }; // Vertex shader for a textured quad vertex VertexIO vertexPassThrough(const device packed_float4 *pPosition [[ buffer(0) ]], const device packed_float2 *pTexCoords [[ buffer(1) ]], uint vid [[ vertex_id ]]) { VertexIO outVertex; outVertex.position = pPosition[vid]; outVertex.textureCoord = pTexCoords[vid]; return outVertex; } // Fragment shader for a textured quad fragment half4 fragmentPassThrough(VertexIO inputFragment [[ stage_in ]], texture2d<half> inputTexture [[ texture(0) ]], sampler samplr [[ sampler(0) ]]) { return inputTexture.sample(samplr, inputFragment.textureCoord); } Running this crashes the app with the following exception: validateRenderPassDescriptor:782: failed assertion `RenderPass Descriptor Validation Texture at colorAttachment[0] has usage (0x01) which doesn't specify MTLTextureUsageRenderTarget (0x04) This now raises three questions for me: Do I have to do all of that Metal setting up, packing along the PassThrough.metal shader, render pass stuff, etc just to draw the MTLTexture to the CAMetalLayer? Is there no simpler way? Why is the code above failing? When is the drawing from Skia actually committed to the MTLTexture? Do I need to commit the command buffer (as seen in my TODO)?
Replies
1
Boosts
0
Views
2.2k
Activity
Dec ’22
DRHT > error > MTLTextureDescriptor
my code: guard let drawable = view.currentDrawable else { return }     let renderPassDescriptor = MTLRenderPassDescriptor()     renderPassDescriptor.colorAttachments[0].texture = drawable.texture //There is a crash     renderPassDescriptor.colorAttachments[0].loadAction = .clear     renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 0) error info: MTLTextureDescriptor has height (9964) greater than the maximum allowed size of 8192. > validateTextureDimensions > validateTextureDimensions:1075: failed assertion `MTLTextureDescriptor has height (9964) greater than the maximum allowed size of 8192.' please help: I try to put a canvas on an image,as you can see,the size of this canvas is too large to exceed the GPU processing limit。Is there a better way that don't change size to solve this problem
Replies
2
Boosts
0
Views
1.8k
Activity
Dec ’22
Cannot Get Size of CAMetal Drawable Texture
I am having trouble with getting the size of the texture belonging to a CAMetalLayer Drawable. When I use view.drawableSize.width, it returns 2560x1440, however, when I use the Metal Debugger, I get the correct value of 2660x1432. If I hardcode my size to 2660x1432, my application works perfectly fine (except that I can't resize the window without it breaking), but when I try to use view.drawableSize.width, it doesn't work at all. I can see my scene being rendered in the debugger, but if I don't hardcode my screen size, it is not being displayed on the CAMetalLayer Drawable. How can I get the correct size using code?
Replies
0
Boosts
1
Views
1.1k
Activity
Dec ’22
Dashed Line in Metal
How can I create a dashed line using a Metal shader? I'm thinking something similar to the CoreGraphics "lineDash" property.
Replies
3
Boosts
0
Views
2.4k
Activity
Nov ’22
CIImage generate CGImage is unavailable
I want to use CIFilter to create a CGImageRef, but when I get cgimage buffer , it is empty CIFilter<CITextImageGenerator> * filter = [CIFilter textImageGeneratorFilter];   filter.text = @"This is a test text";   filter.fontName = @"HoeflerText-Regula";   filter.fontSize = 12;   filter.scaleFactor = 1.0;   CIImage *image = filter.outputImage;   CIContext *context = [CIContext contextWithOptions:nil];   CGImageRef resultRef = [context createCGImage:image fromRect:image.extent];   UIImage *resultImage = [UIImage imageWithCGImage:resultRef];       CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(resultRef));   const unsigned char * buffer = CFDataGetBytePtr(data); And then I could not generate MTLTexture with this cgimage  MTKTextureLoader *loader = [[MTKTextureLoader alloc] initWithDevice:self.device];   NSError*error;   id<MTLTexture> fontTexture = [loader newTextureWithCGImage:resultRef                      options:@{     MTKTextureLoaderOptionOrigin : MTKTextureLoaderOriginFlippedVertically,     MTKTextureLoaderOptionSRGB : @(NO)   }                       error:&error];    How can I finish my work? Any suggestions about this question I am appreciate.
Replies
4
Boosts
0
Views
1.5k
Activity
Nov ’22
eGPU support on Apple Silicon?
We are spending a lot of time optimizing or Metal work for discrete graphics cards and external GPUs with eGPU support. Is this going to be something Apple Silicon will support since Thunderbolt 3 won't be part of these machines? I am worried.
Replies
8
Boosts
4
Views
15k
Activity
Nov ’22
[Swift] Converting between Data, Buffers, variable types efficiently.
Ahoy Developrs, I was wondering if someone might be able to help me, regarding working with Data, Buffers and Pointers, as I am working with Metal, ModelIO and large arrays of vertex data. Are there ways of converting/accessing Data instances as their original variable type without having to map/duplicate the data into a new variable? and visa-vera. I have to convert arrays into MDLMeshBuffer to pass them into ModelIO, from custom geometry that I have made at runtime. This can be quite convoluted as I have my own array of structs for geometric topology. This gets converted into MetalBuffer for GPU drawing, but I want to leverage ModelIO for importing/exporting. To leverage ModelIO I need to convert to and from the ModelIO Mesh Buffers, which can be converted into Data objects, and then convert those into data specific All this conversion to and from create quite a bit of memory bloat. The following are 3 examples of how I have been interacting with the different types, are there better /more efficient ways of doing this? // Converts Data to variable var positions = Array<simd_float3>(repeating: simd_float3.zero, count: data2.count/MemoryLayout<simd_float3>.stride)   _ = arr2.withUnsafeMutableBytes { data.copyBytes(to: $0) } // Example ModelIO vert conversion for i in 0..<mdlMesh.vertexBuffers.count {       let vBuff = mdlMesh.vertexBuffers[i]       let buffLyt = mdlMesh.vertexDescriptor.layouts[i] as! MDLVertexBufferLayout       let vertCount = vBuff.length / buffLyt.stride       let buffermap:MDLMeshBufferMap = vBuff.map()       let rawBasePtr:UnsafeMutableRawPointer = buffermap.bytes               for vertIndex in 0..<vertCount {         let b = rawBasePtr.load(fromByteOffset: buffLyt.stride * vertIndex, as: (simd_float3).self)         vertices.append(b)       }     } // Example ModelIO submesh conversion /// The layout of the face indicies var topologyVertCount:Array<UInt8> = [] if subMesh.topology != nil {    let topology = subMesh.topology!    let faceBuffer = topology.faceTopology!    print("Topology Buffer : \(topology)")    print(" face count: \(topology.faceCount)")    print(" hole count: \(topology.holeCount)")    for faceIndex in 0..<topology.faceCount {           let b = faceBuffer.map().bytes.load(fromByteOffset: MemoryLayout<UInt8>.stride * faceIndex, as: UInt8.self)           topologyVertCount.append(b)    } } Thank you for the help, Simon
Replies
0
Boosts
0
Views
1.5k
Activity
Nov ’22
Programmatically Get Pipeline Statistics
As part of my automated testing on real devices I would like to get the pipeline statistics from my compute kernels (ALU, Memory, Control Flow, Occupancy, etc). I'm able to generate a GPU trace in code without issue but that requires manually opening up the trace to find the values I'm interested in. What I would like is an API to read that trace or some counter set which provides the statistics I'm interested in. Is this possible?
Replies
0
Boosts
0
Views
836
Activity
Oct ’22
ModelIO - Accessing original Obj data
Hi Devs, I have been trying to access the original obj data from an asset I loaded in using ModelIO. I import the asset using the MDLAsset(url: vertexDescriptor: bufferAllocator: preserveTopology: error:) I set preserve topology to true, which from my understanding should keep all the data consistent with the original. My question is how does one correlate the submesh face data to the vertex data and the index data? I have read the documents which mention you should use the order of the faceTopologyBuffer, which will result in a 3D object that does look correct but all the points have unique vertices (non welded edges). I can make an assumption and loop over all the vertices and remove any duplicates, there by creating my own index buffer, but that would create an assumption that all faces have been welded which is also not correct. Is there a way to get the original data out of MDLAsset, or should I look to other avenues like assimp? Thank you for the help, Simon
Replies
0
Boosts
0
Views
983
Activity
Oct ’22
How to get vertex position in MDLMesh and modify it
I'm new to swift mesh operation. I wonder how to get vertex position in MDLMesh and modify it(used for mesh deformation). Can any one help me and thanks very much.
Replies
0
Boosts
0
Views
667
Activity
Oct ’22
Why use dispatch_semaphore to explicitly synchronize MTLbuffer updates?
Hi. I'm new to Metal(actually any type of software development run on apple products). I have many questions about using MTL::Buffer and dispatch_semaphore, and drawInMTKView(). I read README.md, but I need some more help understanding it. Full code of 03-animation in metal-cpp sample This is sample code in metal-cpp sample code by apple(I downloaded here). In this code, _pFrameData is an array of MTLBuffer, and kMaxFramesInFlight is the size of this array. Its type is static const int, and the value is 3. When Renderer is created, _pFrameData are initialized like that. void Renderer::buildFrameData() {     for ( int i = 0; i < Renderer::kMaxFramesInFlight; ++i )     {         _pFrameData[ i ]= _pDevice->newBuffer( sizeof( FrameData ), MTL::ResourceStorageModeManaged );     } } draw method, call by drawInMTKView. void Renderer::draw( MTK::View* pView ) {     NS::AutoreleasePool* pPool = NS::AutoreleasePool::alloc()->init();     _frame = (_frame + 1) % Renderer::kMaxFramesInFlight; MTL::Buffer* pFrameDataBuffer = _pFrameData[ _frame ];     MTL::CommandBuffer* pCmd = _pCommandQueue->commandBuffer();     dispatch_semaphore_wait( _semaphore, DISPATCH_TIME_FOREVER );     Renderer* pRenderer = this;     pCmd->addCompletedHandler( ^void( MTL::CommandBuffer* pCmd ){         dispatch_semaphore_signal( pRenderer->_semaphore );     });     reinterpret_cast< FrameData * >( pFrameDataBuffer->contents() )->angle = (_angle += 0.01f);     pFrameDataBuffer->didModifyRange( NS::Range::Make( 0, sizeof( FrameData ) ) );     MTL::RenderPassDescriptor* pRpd = pView->currentRenderPassDescriptor();     MTL::RenderCommandEncoder* pEnc = pCmd->renderCommandEncoder( pRpd );     pEnc->setRenderPipelineState( _pPSO );     pEnc->setVertexBuffer( _pArgBuffer, 0, 0 );     pEnc->useResource( _pVertexPositionsBuffer, MTL::ResourceUsageRead );     pEnc->useResource( _pVertexColorsBuffer, MTL::ResourceUsageRead );     pEnc->setVertexBuffer( pFrameDataBuffer, 0, 1 );     pEnc->drawPrimitives( MTL::PrimitiveType::PrimitiveTypeTriangle, NS::UInteger(0), NS::UInteger(3) );     pEnc->endEncoding();     pCmd->presentDrawable( pView->currentDrawable() );     pCmd->commit();     pPool->release(); } Q1. what is the meaning of kMaxFramesInFlight's name and value? Q2. how are dispatch_semaphore_wait() and drawInMTKView() working? At first, I guess if the count of dispatch_semaphore change 0, the Renderer::draw are blocked by dispatch_semaphore_wait() until GPU read the buffer and execute dispatch_semaphore_signal. But now I think it's not a correct understanding because I don't know about drawInMTKView. How much drawInMTKView is called in 1 second and when? Q3. and.... why use dispatch_semaphore for here? I try to change my code to use a single MTLBuffer for the same work. Just changing some code(add a single buffer, remove code for dispatch_semaphore), the changed code works same.
Replies
1
Boosts
0
Views
1.2k
Activity
Oct ’22
Convert SceneKit/matrix/transform code into pure Metal/MetalKit
Hi, I'm trying to convert my SceneKit code into pure Metal/MetalKit and I feel confused about this code and how I should rewrite it. I've made the code simple for this case with some pseudocode. The part where it says "SceneKit magic" is where I feel lost. The SCNNode is just an empty placeholder just as it is – and it works for the calculations it is doing inside. Any help and pointers are much appreciated :-) class Scene { let ball = Ball() let scnNode = SCNNode() var quaternionAngleVelocity = float2(0, 0) func update() { // pseudocode, the user press the up key quaternionAngleVelocity.x -= 3 // pseudocode, the user press the down key quaternionAngleVelocity.x += 3 // pseudocode, the user press the left key quaternionAngleVelocity.y -= 3 // pseudocode, the user press the right key quaternionAngleVelocity.y += 3 ... // apply friction quaternionAngleVelocity *= (1 - 0.05) // i.e. decrease with 5% // rotate let newQuaternionAxisX = simd_quatf(angle: quaternionAngleVelocity.x.degreesToRadians, axis: simd_float3(x: 1, y: 0, z: 0)) let newQuaternionAxisY = simd_quatf(angle: quaternionAngleVelocity.y.degreesToRadians, axis: simd_float3(x: 0, y: 1, z: 0)) let finalQuaternion = simd_normalize(newQuaternionAxisX * newQuaternionAxisY) // SceneKit magic…? let matrix4 = SCNMatrix4Mult(scnNode.worldTransform, SCNMatrix4(simd_float4x4(finalQuaternion))) scnNode.transform = matrix4 ball.quaternion = scnNode.simdWorldOrientation } } class Ball { var position: float3 = [0, 0, 0] var rotation: float3 = [0, 0, 0] { didSet { let rotationMatrix = float4x4(rotation: rotation) quaternion = simd_quatf(rotationMatrix) } } var scale: float3 = [1, 1, 1] var forwardVector: float3 { return normalize([sin(rotation.y), 0, cos(rotation.y)]) } var rightVector: float3 { return [forwardVector.z, forwardVector.y, -forwardVector.x] } var upVector: float3 { return [0, forwardVector.z, 0] } var quaternion = simd_quatf() var modelMatrix: float4x4 { let translateMatrix = float4x4(translation: position) // let rotateMatrix = float4x4(rotation: rotation) let rotateMatrix = float4x4(quaternion) let scaleMatrix = float4x4(scaling: scale) return (translateMatrix * rotateMatrix * scaleMatrix) } var worldTransform: float4x4 { return modelMatrix } }
Replies
3
Boosts
0
Views
1.8k
Activity
Oct ’22
GPU trace metal Unable to create shader debug session on MacBook Pro (16-inch, 2021) M1 max
When trying to debug my compute shaders by pressing the ladyBird button inside of GPU trace, the error "Unable to create shader debug session" occurs. This only happens on my M1 MAX mbp, the exact same project does not have this error on my old intel mbp. I have tried reinstalling the past 3 generations of Xcode yet I cannot fix this error. It is making it impossible for me to develop my program as there is no information online about how to fix this error.
Replies
2
Boosts
1
Views
1.2k
Activity
Sep ’22
Can't define the matrix_double3x3 in a c header
I tried to define the matrix_double3x3 properties but the compiler don't allow me to do. I can define the matrix_float3x3 or matrix_half3x3 but not for the matrix_double3x3. But I saw the matrix_types.h, it has typedef simd_double3x3 matrix_double3x3 My goal is to send the matrix_double3x3 to Metal for computing the rectified image. Environment Xcode 14.0 (14A309) Destination: macOS (Minimum Deployments: 12.3) macOS 12.6 (21G115)
Replies
1
Boosts
0
Views
2.2k
Activity
Sep ’22
M1 M2 webgl.ALIASED_POINT_SIZE_RANGE
I'm currently using gl.points to render sprites (lens flares, explosions, etc) looks like M1 / M2 hardware (ipad, macbook pro) limits the point size to 64. Every other device has minimum of 512, usually 1024, and many even provide 2048. wondering if this is a was a choice or oversight? Also, not sure where to file this type of bug/request as its specific to M1/M2 hardware that affects multiple devices? many thanks, -Dm
Replies
1
Boosts
0
Views
1k
Activity
Sep ’22
BGProcessingTask Using GPU in Background
I was wondering if it was possible for a BGProcessingTask to use the GPU in the background. My use case would be to modify a video file. I know normally that this is not allowed, but was wondering if by using a BGProcessingTask I get special access. I have tried in a demo project, and have gotten some confusing results. Sometimes it appears that it works (the GPU operation completes like it would in the foreground) and sometimes it does not work (the GPU operation does not write anything to the output texture). Was wondering if Apple has any specific guidance.
Replies
0
Boosts
0
Views
893
Activity
Sep ’22
Render video in metal.
So I wanted to render video from .mov file in MTKView. Short algorithm: Read CMSampleBuffer from .mov using AVAssetReader and AVAssetReaderTrackOutput. Convert CMSampleBuffer from step 1 to MTLTexture and pass it to renderer I did those 2 steps and got the picture with twitches and I don’t know why. Link to .mov https://www.dropbox.com/s/gmzxd8j94pjhc1q/2.MOV?dl=0. Link to result https://www.dropbox.com/s/exgf1tk7oqvon25/result.mov?dl=0. The code. ViewController.swift VideoReader.swift SampleConverter.swift TextureModel.swift Renderer.swift MyMetal.metal
Replies
1
Boosts
0
Views
2.7k
Activity
Sep ’22
MacOs Metal antialiasing
I'm making an app for MacOs, but I'm having problems with the antialiasing implementation in Metal. When compiling I get the following error: validateAttachmentOnDevice:540: failed assertion MTLRenderPassDescriptor render targets have inconsistent sample counts.' This is the code I use to implement the textures: - (void)makeTextures {     if ([depthTexture width] != drawableSize.width || [depthTexture height] != drawableSize.height)     {         MTLTextureDescriptor *colorDescriptor = [MTLTextureDescriptor new];         colorDescriptor.textureType = MTLTextureType2DMultisample;         colorDescriptor.sampleCount = 4;         colorDescriptor.pixelFormat = vista.colorPixelFormat;         colorDescriptor.width = drawableSize.width;         colorDescriptor.height = drawableSize.height;         colorDescriptor.usage = MTLTextureUsageRenderTarget;         colorDescriptor.storageMode = MTLStorageModePrivate;         msaaColorTexture = [view.device newTextureWithDescriptor:colorDescriptor];         MTLTextureDescriptor *resolveDescriptor = [MTLTextureDescriptor new];         resolveDescriptor.textureType = MTLTextureType2D;         resolveDescriptor.pixelFormat = vista.colorPixelFormat;         resolveDescriptor.width = drawableSize.width;         resolveDescriptor.height = drawableSize.height;         resolveDescriptor.storageMode = MTLStorageModePrivate;         msaaResolveColorTexture = [view.device newTextureWithDescriptor:resolveDescriptor];         MTLTextureDescriptor *desc = [MTLTextureDescriptor new];         desc.textureType = MTLTextureType2DMultisample;         desc.sampleCount = 4;         desc.pixelFormat = MTLPixelFormatDepth32Float;         desc.width = drawableSize.width;         desc.height = drawableSize.height;         desc.usage = MTLTextureUsageRenderTarget;         desc.storageMode = MTLStorageModePrivate;         depthTexture = [view.device newTextureWithDescriptor:desc];     } } If at the time of creating the MTLRenderPipelineDescriptor I add .samplecount = 4;, the error disappears, but nothing is drawing in the view. This are de PipelineDescriptor creation: MTLRenderPipelineDescriptor *pipelineStateDescriptor = [MTLRenderPipelineDescriptor new];     pipelineStateDescriptor.label = @"Simple Pipeline";     pipelineStateDescriptor.vertexFunction = vertexFunction;     pipelineStateDescriptor.fragmentFunction = fragmentFunction;     pipelineStateDescriptor.colorAttachments[0].pixelFormat = vista.colorPixelFormat;     pipelineStateDescriptor.depthAttachmentPixelFormat = MTLPixelFormatDepth32Float; // No error but black view.     //pipelineStateDescriptor.sampleCount = 4;     NSError *error;     pipelineState = [view.device newRenderPipelineStateWithDescriptor:pipelineStateDescriptor error:&error];     // Depth stencil.     MTLDepthStencilDescriptor *depthStencilDescriptor = [MTLDepthStencilDescriptor new];     depthStencilDescriptor.depthCompareFunction = MTLCompareFunctionLess;     depthStencilDescriptor.depthWriteEnabled = YES;     depthStencilState = [view.device newDepthStencilStateWithDescriptor:depthStencilDescriptor]; And passDescriptor: if (passDescriptor != nil) {         passDescriptor.colorAttachments[0].texture = msaaColorTexture;         passDescriptor.colorAttachments[0].resolveTexture = msaaResolveColorTexture;         passDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(1.0f, 1.0f, 1.0f, 1.0f);         passDescriptor.colorAttachments[0].storeAction = MTLStoreActionMultisampleResolve;         passDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear;         passDescriptor.depthAttachment.texture = depthTexture;         passDescriptor.depthAttachment.clearDepth = 1.0;         passDescriptor.depthAttachment.loadAction = MTLLoadActionClear;         passDescriptor.depthAttachment.storeAction = MTLStoreActionStore; . . . Any suggestion. Thanks by advice. Manuel C.
Replies
0
Boosts
0
Views
964
Activity
Aug ’22
Anchor of big objects in open area
I am just starting to learn AR. Thanks for the help. I am trying to bind large objects to a certain location in an open area. I tried to bind using an image, an object in a reality composer. After snapping, when moving, objects do not remain in the same place. ARGeoTrackingConfiguration is not available in my region. If you scan the world around you and then define it, then with a rainy day or the slightest change in the area (for example, mowing the lawn), the terrain will not be determined. What do you advise?
Replies
3
Boosts
0
Views
1.8k
Activity
Aug ’22