require "luascape.reflect"

reflect.loadReflectors("render")
reflect.makeNamespaceGlobal("scape::render")


render = {}

function render.createDefaultRenderer()
  local renderer = Renderer()
  renderer.passes:clear()
  
  local standardPass = renderer.passes:add(RenderPass())
  standardPass.clearFlags = Display.CLEAR_ALL
  standardPass.clearColor = Color(0.0, 0.0, 0.0)
  return renderer
end

function render.createTextureRenderTarget()
  require "luascape.graphics"
  return Display.instance():createRenderTarget()
end

function render.createColorRenderTarget(width, height, format)
  local renderTarget = render.createTextureRenderTarget()
  local texture = renderTarget.textures:add(DynamicTexture())
  if not format then format = PixelFormat.RGBA8888 end
  if width and height then
    texture:create(width, height, format, texture.pixelBuffer.flags)
    renderTarget.viewport = Rectangle(0, 0, width, height);
  end
  return renderTarget
end

function render.checkDepthTexture(renderTarget, width, height, bits)
  local depthTexture = renderTarget.textures:add(DepthTexture(bits))
  if width and height then
    depthTexture:create(width, height, depthTexture.pixelBuffer.pixelFormat, depthTexture.pixelBuffer.flags)
    renderTarget.viewport = Rectangle(0, 0, width, height);
  end
  if not renderTarget:isSupported() then
    renderTarget.textures:remove(depthTexture)
  else
    return depthTexture
  end
end

function render.addDepthTexture(renderTarget, width, height)
  if not render.checkDepthTexture(renderTarget, width, height, 0) then 
    if not render.checkDepthTexture(renderTarget, width, height, 16) then
      if not render.checkDepthTexture(renderTarget, width, height, 24) then
        error "Could not find a working depth texture format!"
      end
    end
  end
end

function render.createDepthRenderTarget(width, height)
  local renderTarget = render.createTextureRenderTarget()
  render.addDepthTexture(renderTarget, width, height)
  return renderTarget
end

function render.createColorAndDepthRenderTarget(width, height, format)
  local renderTarget = render.createColorRenderTarget(width, height, format)
  render.addDepthTexture(renderTarget, width, height)
  return renderTarget
end
