-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathViewController.swift
275 lines (217 loc) · 9.49 KB
/
ViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
//
// ViewController.swift
// Quake 3 BSP Renderer
//
// Created by Thomas Brunoli on 26/08/2015.
// Copyright (c) 2015 Thomas Brunoli. All rights reserved.
//
import UIKit
import Metal
import QuartzCore
import GLKit
import MetalKit
struct Uniforms {
var modelMatrix : GLKMatrix4
var viewMatrix : GLKMatrix4
var projectionMatrix : GLKMatrix4
}
class ViewController: UIViewController {
// Main metal objects
let metalLayer = CAMetalLayer()
let device = MTLCreateSystemDefaultDevice()!
var commandQueue : MTLCommandQueue! = nil
var pipeline : MTLRenderPipelineState! = nil
// Resources
var uniformBufferProvider: BufferProvider! = nil
var mapMesh : MapMesh! = nil
var uniforms : Uniforms! = nil
var depthTexture : MTLTexture! = nil
var depthState : MTLDepthStencilState! = nil
var msaaTexture : MTLTexture! = nil
let sampleCount = 2
// Transients
var timer : CADisplayLink! = nil
var lastFrameTimestamp : CFTimeInterval = 0.0
var elapsedTime : CFTimeInterval = 0.0
var aspect : Float = 0.0
var fov : Float = GLKMathDegreesToRadians(65.0)
var camera : Camera = Camera()
func loadMap() {
let pk3 = NSBundle.mainBundle().URLForResource("pak0", withExtension: "pk3")!
let loader = Q3ResourceLoader(dataFilePath: pk3)
let map = loader.loadMap("q3dm6")!
// TESTING SHADER PARSER
let shader = loader.loadShader("scripts/gothic_light.shader")!
let parser = Q3ShaderParser(shaderFile: shader)
let parsedShaders = try! parser.readShaders()
for s in parsedShaders {
print("\n\n\(s)\n\n")
}
// END TESTING
var textures: Dictionary<String, UIImage> = Dictionary()
for textureName in map.textureNames {
if let texture = loader.loadTexture(textureName) {
textures[textureName] = texture
}
}
mapMesh = MapMesh(device: self.device, map: map, textures: textures)
}
func initializeMetal() {
metalLayer.device = device
metalLayer.pixelFormat = .BGRA8Unorm
metalLayer.framebufferOnly = true
metalLayer.frame = view.layer.frame
view.layer.addSublayer(metalLayer)
commandQueue = device.newCommandQueue()
}
func buildPipeline() {
// Shader setup
let library = device.newDefaultLibrary()!
let vertexFunction = library.newFunctionWithName("renderVert")
let fragmentFunction = library.newFunctionWithName("renderFrag")
// Pipeline Descriptor
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.vertexFunction = vertexFunction
pipelineDescriptor.fragmentFunction = fragmentFunction
pipelineDescriptor.vertexDescriptor = MapMesh.vertexDescriptor()
pipelineDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm
pipelineDescriptor.colorAttachments[0].blendingEnabled = true
pipelineDescriptor.colorAttachments[0].rgbBlendOperation = .Add
pipelineDescriptor.colorAttachments[0].alphaBlendOperation = .Add
pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = .SourceAlpha
pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = .SourceAlpha
pipelineDescriptor.colorAttachments[0].destinationRGBBlendFactor = .OneMinusSourceAlpha
pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = .OneMinusSourceAlpha
pipelineDescriptor.depthAttachmentPixelFormat = .Depth32Float
pipelineDescriptor.sampleCount = sampleCount
// Try creating the pipeline
pipeline = try! device.newRenderPipelineStateWithDescriptor(pipelineDescriptor)
}
func buildResources() {
uniforms = Uniforms(
modelMatrix: GLKMatrix4Identity,
viewMatrix: camera.getViewMatrix(),
projectionMatrix: GLKMatrix4MakePerspective(fov, aspect, 0.01, 10000.0)
)
uniformBufferProvider = BufferProvider(
device: device,
inflightBuffersCount: 3,
bufferSize: sizeof(Uniforms)
)
// Depth buffer
let depthTextureDescriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat(
.Depth32Float,
width: Int(self.view.frame.width),
height: Int(self.view.frame.height),
mipmapped: false
)
depthTextureDescriptor.textureType = .Type2DMultisample
depthTextureDescriptor.sampleCount = sampleCount
depthTexture = device.newTextureWithDescriptor(depthTextureDescriptor)
// Depth stencil
let stencilDescriptor = MTLDepthStencilDescriptor()
stencilDescriptor.depthCompareFunction = .LessEqual
stencilDescriptor.depthWriteEnabled = true
depthState = device.newDepthStencilStateWithDescriptor(stencilDescriptor)
// MSAA
let msaaDescriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat(
.BGRA8Unorm,
width: Int(self.view.frame.width),
height: Int(self.view.frame.height),
mipmapped: false
)
msaaDescriptor.textureType = .Type2DMultisample
msaaDescriptor.sampleCount = sampleCount
msaaTexture = device.newTextureWithDescriptor(msaaDescriptor)
}
func generateMipMaps() {
let commandBuffer = commandQueue.commandBuffer()
let commandEncoder = commandBuffer.blitCommandEncoder()
for (_, texture) in mapMesh.textures {
commandEncoder.generateMipmapsForTexture(texture)
}
for lightmap in mapMesh.lightmaps {
commandEncoder.generateMipmapsForTexture(lightmap)
}
commandEncoder.endEncoding()
commandBuffer.commit()
}
func draw() {
if let drawable = metalLayer.nextDrawable() {
uniforms.viewMatrix = camera.getViewMatrix()
let uniformBuffer = uniformBufferProvider.nextBuffer()
// Copy uniforms to GPU
memcpy(uniformBuffer.contents(), &uniforms, sizeof(Uniforms))
// Create Command Buffer
let commandBuffer = commandQueue.commandBuffer()
// Render Pass Descriptor
let renderPassDescriptor = MTLRenderPassDescriptor()
renderPassDescriptor.colorAttachments[0].texture = msaaTexture
renderPassDescriptor.colorAttachments[0].resolveTexture = drawable.texture
renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(0.8, 0.3, 0.2, 1)
renderPassDescriptor.colorAttachments[0].loadAction = .Clear
renderPassDescriptor.colorAttachments[0].storeAction = .MultisampleResolve
renderPassDescriptor.depthAttachment.texture = depthTexture
renderPassDescriptor.depthAttachment.loadAction = .Clear
renderPassDescriptor.depthAttachment.clearDepth = 1.0
// Command Encoder
let commandEncoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor)
commandEncoder.setDepthStencilState(depthState)
commandEncoder.setRenderPipelineState(pipeline)
commandEncoder.setVertexBuffer(uniformBuffer, offset: 0, atIndex: 1)
mapMesh.renderWithEncoder(commandEncoder)
commandEncoder.endEncoding()
commandBuffer.addCompletedHandler { (commandBuffer) -> Void in
self.uniformBufferProvider.finishedWithBuffer()
}
// Commit command buffer
commandBuffer.presentDrawable(drawable)
commandBuffer.commit()
}
}
func redraw() {
autoreleasepool {
self.draw()
}
}
func startDisplayTimer() {
timer = CADisplayLink(target: self, selector: Selector("redraw"))
timer.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
}
func handlePan(gesture: UIPanGestureRecognizer) {
let velocity = gesture.velocityInView(self.view)
let newPitch = GLKMathDegreesToRadians(Float(velocity.y / -100))
let newYaw = GLKMathDegreesToRadians(Float(velocity.x / -100))
camera.pitch(newPitch)
camera.turn(newYaw)
}
func handlePinch(gesture: UIPinchGestureRecognizer) {
let velocity = Float(gesture.velocity / 2)
if velocity.isNaN || velocity < 0.1 { return }
camera.moveForward(velocity)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
aspect = Float(self.view.bounds.size.width / self.view.bounds.size.height)
initializeMetal()
loadMap()
buildPipeline()
buildResources()
generateMipMaps()
startDisplayTimer()
// Set up gesture recognizers
view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "handlePan:"))
view.addGestureRecognizer(UIPinchGestureRecognizer(target: self, action: "handlePinch:"))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
deinit {
timer.invalidate()
}
}