본문 바로가기

프로그래밍/iOS,macOS

[Metal] 이미지 렌더링~ 여러 텍스처 합치기

 

원본텍스처와 사이즈를 줄인 텍스처, 마스킹용 텍스처를 합치는 간단한 샘플. (어째 원본외에 캡처한 이미지들 색상이 좀 이상..)
이전 예제에서 원본텍스처와 렌더타겟 텍스처가 존재하니 마스킹용 텍스처만 하나 추가로 로드한다.

func initMetal() {
  .
  .
  .
  .

  initRederTarget()
  initSwapRender()

  self.imageTexture = loadTexture(name:"sample", ext:"png")
  self.maskingTexture = loadTexture(name: "masking", ext: "png")
}

 

화면 렌더링용 쉐이더에 3개의 텍스처를 전달한다

func render(view:MTKView) {
  print("render")
  .
  .
  .
  .
  swapEncoder.setFragmentTexture(self.renderTargetTexture, index: 0)
  swapEncoder.setFragmentTexture(self.imageTexture, index: 1)
  swapEncoder.setFragmentTexture(self.maskingTexture, index: 2)
  .
  .
}

 

화면렌더링 프레그먼트 쉐이더

마스킹이 레드로 딱떨어지는 경우이므로 간단~ 

fragment float4 swapFragmentFunction(ImageOut in [[stage_in]],
                                     texture2d<float> texture1 [[texture(0)]],
                                     texture2d<float> texture2 [[texture(1)]],
                                     texture2d<float> texture3 [[texture(2)]]) {
    
    constexpr sampler colorSampler;
    float4 bgColor = texture1.sample(colorSampler, in.texCoord);
    float4 color = texture2.sample(colorSampler, in.texCoord);
    float4 masking = texture3.sample(colorSampler, in.texCoord);
    
    color = float4((bgColor.rgb * masking.r ) + (color.rgb * (1 - masking.r)), 1.0);
    return color;
}