Displaying an AR Experience with Metal
通過渲染攝像機圖像和使用位置跟蹤信息來顯示覆蓋內容,構建自定義AR視圖。
arkit包括查看容易顯示AR的經驗與SceneKit或SpriteKit類。但是,如果你建立你自己的渲染引擎(或與第三方引擎集成),ARKit還提供了所有必要的支持,以顯示一個自定義視圖AR體驗。
在任何AR經驗中,第一步是配置一個arsession對象來管理攝像機捕獲和運動處理。會話定義并保持設備所在的真實世界空間與虛擬空間之間的對應關系,并在其中模擬AR內容。要在自定義視圖中顯示AR體驗,您需要:
1.從會話中檢索視頻幀和跟蹤信息。
2.將這些框架圖像渲染為視圖的背景。
3.使用跟蹤信息在相機圖像上方定位和繪制AR內容。
Note
本文介紹Xcode項目模板代碼中找到。對于完整的示例代碼,使用增強現實模板創建新的iOS應用程序,并從“內容技術”彈出菜單中選擇“金屬”菜單。
Get Video Frames and Tracking Data from the Session
創建和維護自己arsession實例,并運行一個會話配置,該會話配置適合于要支持的AR體驗。(要做到這一點,請參見建立一個基本的AR體驗)會話捕獲攝像機的視頻,跟蹤設備的位置和方向在一個模擬的3D空間,并提供arframe物體.每一個這樣的對象都包含一個單獨的視頻幀圖像和從幀被捕獲的時刻的位置跟蹤信息。有兩種訪問方式arframe AR會話產生的對象,取決于您的應用程序是否支持拉或推設計模式。
如果你喜歡控制幀定時(拉設計模式),使用會話的幀屬性獲取當前幀圖像和跟蹤信息每次重畫視圖的內容。使用這種方法的arkit Xcode模板:
// in Renderer class, called from MTKViewDelegate.draw(in:) via Renderer.update()
func updateGameState(){
guardletcurrentFrame = session.currentFrameelse{return}? ? ? ? updateSharedUniforms(frame: currentFrame)? ?
?updateAnchors(frame: currentFrame)? ??
updateCapturedImageTextures(frame: currentFrame)
if viewportSizeDidChange {? ? ? ?
?viewportSizeDidChange =false
?updateImagePlane(frame: currentFrame)? ??
}
}
另外,如果您的應用程序設計有利于推模式,實現會議:didupdateframe:委托方法,該會話將為它捕獲的每個視頻幀調用一次(默認為每秒60幀)。
在獲得一個框架,你需要繪制相機圖像,并更新和渲染任何內容覆蓋你的AR經驗包括。
Draw the Camera Image
創建和維護自己arsession實例,并運行一個會話配置,該會話配置適合于要支持的AR體驗。(要做到這一點,請參見建立一個基本的AR體驗)會話捕獲攝像機的視頻,跟蹤設備的位置和方向在一個模擬的3D空間,并提供arframe物體.每一個這樣的對象都包含一個單獨的視頻幀圖像和從幀被捕獲的時刻的位置跟蹤信息。
有兩種訪問方式arframe AR會話產生的對象,取決于您的應用程序是否支持拉或推設計模式。
如果你喜歡控制幀定時(拉設計模式),使用會話的幀屬性獲取當前幀圖像和跟蹤信息每次重畫視圖的內容。使用這種方法的arkit Xcode模板:
// in Renderer class, called from MTKViewDelegate.draw(in:) via Renderer.update()
func updateGameState(){
guardletcurrentFrame = session.currentFrameelse{return}
updateSharedUniforms(frame: currentFrame)
updateAnchors(frame: currentFrame)
updateCapturedImageTextures(frame: currentFrame)
if viewportSizeDidChange {
viewportSizeDidChange =false
updateImagePlane(frame: currentFrame)
}
}
Draw the Camera Image
每個arframe對象的capturedimage屬性包含從設備照相機捕獲的像素緩沖區。若要將此圖像作為自定義視圖的背景繪制,則需要從圖像內容創建紋理并提交使用這些紋理的GPU渲染命令。
像素緩沖區的內容是biplanar YCbCr編碼(也稱為YUV)數據格式;渲染的圖像就需要將像素數據的圖像的RGB格式。用金屬渲染,可以在GPU著色器代碼中最有效地執行轉換。API的使用cvmetaltexturecache創建從像素緩沖區一個緩沖的亮度兩金屬材質(Y)和色度(CbCr)飛機:
func updateCapturedImageTextures(frame: ARFrame){/
/ Create two textures (Y and CbCr) from the provided frame's captured imageletpixelBuffer = frame.capturedImage
if(CVPixelBufferGetPlaneCount(pixelBuffer) <2) {return}
capturedImageTextureY = createTexture(fromPixelBuffer: pixelBuffer, pixelFormat:.r8Unorm, planeIndex:0)!
capturedImageTextureCbCr = createTexture(fromPixelBuffer: pixelBuffer, pixelFormat:.rg8Unorm, planeIndex:1)!
}
func createTexture(fromPixelBuffer pixelBuffer: CVPixelBuffer, pixelFormat: MTLPixelFormat, planeIndex: Int)->MTLTexture? {
varmtlTexture:MTLTexture? =nilletwidth =CVPixelBufferGetWidthOfPlane(pixelBuffer, planeIndex)letheight =CVPixelBufferGetHeightOfPlane(pixelBuffer, planeIndex)vartexture:CVMetalTexture? =nilletstatus =CVMetalTextureCacheCreateTextureFromImage(nil, capturedImageTextureCache, pixelBuffer,nil, pixelFormat, width, height, planeIndex, &texture)ifstatus == kCVReturnSuccess {
mtlTexture =CVMetalTextureGetTexture(texture!)
}returnmtlTexture
}
其次,編碼渲染命令,畫兩個紋理使用分段函數執行YCbCr到RGB轉換顏色的變換矩陣:
fragment float4 capturedImageFragmentShader(ImageColorInOut in [[stage_in]],
texture2d capturedImageTextureY [[ texture(kTextureIndexY) ]],
texture2d capturedImageTextureCbCr [[ texture(kTextureIndexCbCr) ]]) {
constexpr sampler colorSampler(mip_filter::linear,
mag_filter::linear,
min_filter::linear);
const float4x4 ycbcrToRGBTransform = float4x4(
float4(+1.164380f, +1.164380f, +1.164380f, +0.000000f),
float4(+0.000000f, -0.391762f, +2.017230f, +0.000000f),
float4(+1.596030f, -0.812968f, +0.000000f, +0.000000f),
float4(-0.874202f, +0.531668f, -1.085630f, +1.000000f)
);
// Sample Y and CbCr textures to get the YCbCr color at the given texture coordinate
float4 ycbcr = float4(capturedImageTextureY.sample(colorSampler, in.texCoord).r,
capturedImageTextureCbCr.sample(colorSampler, in.texCoord).rg, 1.0);
// Return converted RGB color
return ycbcrToRGBTransform * ycbcr;
}
Note
使用displaytransformwithviewportsize:定位:方法確保相機圖像覆蓋整個視圖。對于這種方法的例子,以及完整的金屬管道安裝代碼,看到完整的Xcode模板。(創建一個新的iOS應用程序的增強現實模板,并選擇金屬從內容技術彈出菜單。)
Track and Render Overlay Content
AR的經驗通常側重于渲染3D覆蓋內容,使內容似乎是在相機圖像中看到的真實世界的一部分。為了實現這種錯覺,使用aranchor類來模擬你自己3D內容相對于真實世界空間的位置和方向。錨提供轉換,您可以在渲染過程中引用。
例如,Xcode模板創建一個錨位于設備前端約20厘米,每當用戶點擊屏幕
func handleTap(gestureRecognize: UITapGestureRecognizer){
// Create anchor using the camera's current position
if letcurrentFrame = session.currentFrame {// Create a transform with a translation of 0.2 meters in front of the cameravartranslation = matrix_identity_float4x4
translation.columns.3.z = -0.2lettransform = simd_mul(currentFrame.camera.transform, translation)// Add a new anchor to the sessionletanchor =ARAnchor(transform: transform)
session.add(anchor: anchor)
}
}