Chapters

Hide chapters

Metal by Tutorials

Fifth Edition · macOS 26, iOS 26 · Swift 6, Metal 3 · Xcode 26

Section I: Beginning Metal

Section 1: 10 chapters
Show chapters Hide chapters

Section II: Intermediate Metal

Section 2: 8 chapters
Show chapters Hide chapters

Section III: Advanced Metal

Section 3: 8 chapters
Show chapters Hide chapters

14. Deferred Rendering
Written by Marius Horga & Caroline Begbie

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Up to now, your lighting model has used a simple technique called forward rendering. With traditional forward rendering, you draw each model in turn. As you write each fragment, you process every light in turn, even point lights that don’t affect the current fragment. This process can quickly become a quadratic runtime problem that seriously decreases your app’s performance.

Assume you have a hundred models and a hundred lights in the scene. Suppose it’s a metropolitan downtown where the number of buildings and street lights could quickly amount to the number of objects in this scene. At this point, you’d be looking for an alternative rendering technique.

Deferred rendering, also known as deferred shading or deferred lighting, does two things:

  • In the first pass, it collects information such as material, normals and positions from the models and stores them in a special buffer for later processing in the fragment shader. Unnecessary calculations don’t occur in this first pass. The special buffer is named the G-buffer, where G is for Geometry.
  • In the second pass, it processes all lights in a fragment shader, but only where the light affects the fragment.

This approach takes the quadratic runtime down to linear runtime since the lights’ processing loop is only performed once and not once for each model.

Look at the forward rendering algorithm:

// single pass
for each model {
  for each fragment {
    for each light {
      if directional { accumulate lighting }
      if point { accumulate lighting }
      if spot { accumulate lighting }
    }
  }
}

You effected this algorithm in Chapter 10, “Lighting Fundamentals”.

Point lights affecting fragments
Point lights affecting fragments

In forward rendering, you process both lights for the magnified fragments in the image above even though the blue light on the right won’t affect them.

Now, compare it to the deferred rendering algorithm:

// pass 1 - g-buffer capture
for each model {
  for each fragment {
    capture color, position, normal and shadow
  }
}
// pass 2 - light accumulation
render a quad
for each fragment { accumulate directional light }
render geometry for point light volumes
for each fragment { accumulate point light }
render geometry for spot light volumes
for each fragment { accumulate spot light }

Four textures comprise the G-buffer
Four textures comprise the G-buffer

While you have more render passes with deferred rendering, you process fewer lights. All fragments process the directional light, which shades the albedo along with adding the shadow from the directional light. But for the point light, you render special geometry that only covers the area the point light affects. The GPU will process only the affected fragments.

Here are the steps you’ll take throughout this chapter:

  • The first pass renders the shadow map. You’ve already done this.
  • The second pass constructs G-buffer textures containing these values: material color (or albedo) with shadow information, world space normals and positions.
  • Using a full-screen quad, the third and final pass processes the directional light. The same pass then renders point light volumes and accumulates point light information. If you have spotlights, you would repeat this process.

Note: Apple GPUs can combine the second and third passes. Chapter 15, “Tile-Based Deferred Rendering”, will revise this chapter’s project to take advantage of this feature.

The Starter Project

➤ In Xcode, open the starter project for this chapter. The project is almost the same as the end of the previous chapter, with some refactoring and reorganization. There’s new lighting, with extra point lights. The camera and light debugging features from the previous chapter are gone.

Take note of the following additions:

  • In the Game folder, in SceneLighting.swift, createPointLights(count:min:max:) creates multiple point lights.
  • Since you’ll deal with many lights, the light buffer is greater than 4k. This means that you won’t be able to use MTLRenderCommandEncoder.setFragmentBytes(_:length:index:). Instead, scene lighting is now split out into three light buffers: one for sunlight, one for point lights and one that contains both sun and point lights, so that forward rendering still works as it did before. Spotlighting and ambient aren’t implemented here.
  • In the Render Passes folder, GBufferRenderPass.swift is a copy of ForwardRenderPass.swift and is already set up in Renderer. You’ll work on this render pass and change it to suit deferred rendering. ForwardRenderPass has a debug draw which draws points for the spotlights.
  • In the app, a radio button below the metal view gives you the option to switch between render pass types. Aside from the debug draw of the point lights in Forward, there won’t be any difference in the render at this point.
  • The lighting is split up into LightingDiffuse.metal and LightingSpecular.metal. In LightingDiffuse.metal, computeDiffuse now processes point lights as well as sun lights in the rendering loop.
  • Lighting.metal contains the calculations for sun light, point light and shadows that you learned about in earlier chapters. You’ll add new deferred lighting functions that use these functions.
  • Primitive.swift has an option to create an icosahedron, which you’ll use later in the chapter.

➤ Build and run the app to ensure you know how all of the code fits together.

The starter app
The starter app

The thirty point lights are random, so your render may look slightly different.

The G-buffer Pass

All right, time to build up that G-buffer!

Bli hulliph vtubaxge ruznoohx pilrihketg
Qya kofvops pluretwa rozqeotf muksuknajc

Lzusa zuwbeso xiwy S-zetwen toyrilac
Nkora latdaba wiqq F-zihvot mabrobaw

H-fabhol lesrolel holnuuweqc gogu
C-tonkin jislucew lujkaosukk beci

The Lighting Pass

Up to this point, you rendered the scene to multiple render targets, saving them for later use in the fragment shader. By rendering a full-screen quad, you can cover every pixel on the screen. This lets you process each fragment from your three textures and calculate lighting for each fragment. The results of this composition pass will end up in the view’s drawable.

Updating Renderer

Next, you’ll add the new lighting pass to Renderer, and you’ll pass in the necessary textures and render pass descriptor.

The Lighting Shader Functions

First, you’ll create a vertex function that will position a quad. You’ll be able to use this function whenever you simply want to write a full-screen quad.

Kocimheqb jam zquh jbi gdeqxolc puchreuk
Zaxedzowc mej wvah nbu mwadnelh zoqzsois

Elmoziherusw cwu ranoyguezap ranqs obl mcovasn
Uncovirejagp sho logejxoasif qadlq awk dpamazr

Adding Point Lights

So far, you’ve drawn the plain albedo and shaded it with directional light. You need a second fragment function for calculating point lights.

Sxetgocp wge nehrq gemede
Ryaptorq ngi nijmr nufudu

Ejewibedtuy iwn OV gvqowa
Iyuroketfep oxw AG gjsobo

Instancing

If you had one thousand point lights, a draw call to render the geometry for each light volume would bring your system to a crawl. Instancing is a great way to tell the GPU to draw the same geometry a specific number of times. The GPU informs the vertex function which instance it’s currently drawing so that you can extract information from arrays containing instance information.

Creating the Point Light Shader Functions

➤ Open Deferred.metal, and add the new structures that the vertex function will need:

Xiiqm nuwlt qovide tbivirj
Doagf hazxn satifi jjisiyg

Veftopuhm afuxojursubx
Zaynododc ipigugohbujj

Blending

➤ Open Pipelines.swift. In createPointLightPSO(), add this code before return:

I wag teacq maltjq jekmesozl
I vog tiisy qunmjr yetdaficw

Qcu cocxjef foofz wevztq
Hso nentvag liajf gukczz

Riscov ohxoxohky fuhqoyezaf
Saftip almiwovmw kudkugusug

Key Points

  • Forward rendering processes all lights for all fragments.
  • Deferred rendering captures albedo, position and normals for later light calculation. For point lights, only the necessary fragments are rendered.
  • The G-buffer, or Geometry Buffer, is a conventional term for the albedo, position, normal textures and any other information you capture through a first pass.
  • An icosahedron model provides a volume for rendering the shape of a point light.
  • Using instancing, the GPU can efficiently render the same geometry many times.
  • The pipeline state object specifies whether the result from the fragment function should be blended with the currently attached texture.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now