Mercurial > games > semicongine
annotate static_utils.nim @ 1182:e9a212e9cdf7 compiletime-tests
sync from bedroom to office
author | sam <sam@basx.dev> |
---|---|
date | Wed, 03 Jul 2024 00:08:19 +0700 |
parents | 6b66e6c837bc |
children | 850450bfe2a2 |
rev | line source |
---|---|
1162 | 1 import std/os |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
2 import std/enumerate |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
3 import std/hashes |
1159 | 4 import std/macros |
1161 | 5 import std/strformat |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
6 import std/strutils |
1164 | 7 import std/sequtils |
1162 | 8 import std/typetraits as tt |
1159 | 9 |
1161 | 10 import semicongine/core/utils |
11 import semicongine/core/imagetypes | |
1159 | 12 import semicongine/core/vector |
13 import semicongine/core/matrix | |
14 import semicongine/core/vulkanapi | |
15 | |
1179 | 16 template VertexAttribute {.pragma.} |
17 template InstanceAttribute {.pragma.} | |
18 template Pass {.pragma.} | |
19 template PassFlat {.pragma.} | |
20 template ShaderOutput {.pragma.} | |
1180 | 21 template VertexIndices {.pragma.} |
1182 | 22 |
23 const INFLIGHTFRAMES = 2'u32 | |
24 const MEMORY_ALIGNMENT = 65536'u64 # Align buffers inside memory along this alignment | |
25 const BUFFER_ALIGNMENT = 64'u64 # align offsets inside buffers along this alignment | |
1159 | 26 |
1179 | 27 # some globals that will (likely?) never change during the life time of the engine |
1159 | 28 type |
1182 | 29 SupportedGPUType = float32 | float64 | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | TVec2[int32] | TVec2[int64] | TVec3[int32] | TVec3[int64] | TVec4[int32] | TVec4[int64] | TVec2[uint32] | TVec2[uint64] | TVec3[uint32] | TVec3[uint64] | TVec4[uint32] | TVec4[uint64] | TVec2[float32] | TVec2[float64] | TVec3[float32] | TVec3[float64] | TVec4[float32] | TVec4[float64] | TMat2[float32] | TMat2[float64] | TMat23[float32] | TMat23[float64] | TMat32[float32] | TMat32[float64] | TMat3[float32] | TMat3[float64] | TMat34[float32] | TMat34[float64] | TMat43[float32] | TMat43[float64] | TMat4[float32] | TMat4[float64] |
30 | |
31 ShaderObject[TShader] = object | |
32 vertexShader: VkShaderModule | |
33 fragmentShader: VkShaderModule | |
34 | |
1179 | 35 VulkanGlobals = object |
36 instance: VkInstance | |
37 device: VkDevice | |
38 physicalDevice: VkPhysicalDevice | |
39 queueFamilyIndex: uint32 | |
40 queue: VkQueue | |
1181 | 41 |
1182 | 42 IndexType = enum |
43 None, UInt8, UInt16, UInt32 | |
44 | |
45 IndirectGPUMemory = object | |
46 vk: VkDeviceMemory | |
47 size: uint64 | |
48 needsTransfer: bool # usually true | |
49 DirectGPUMemory = object | |
50 vk: VkDeviceMemory | |
51 size: uint64 | |
52 data: pointer | |
53 needsFlush: bool # usually true | |
54 GPUMemory = IndirectGPUMemory | DirectGPUMemory | |
55 | |
56 Buffer[TMemory: GPUMemory] = object | |
57 memory: TMemory | |
58 vk: VkBuffer | |
59 offset: uint64 | |
60 size: uint64 | |
61 | |
62 GPUArray[T: SupportedGPUType, TMemory: GPUMemory] = object | |
63 data: seq[T] | |
64 buffer: Buffer[TMemory] | |
65 offset: uint64 | |
66 GPUValue[T: object|array, TMemory: GPUMemory] = object | |
67 data: T | |
68 buffer: Buffer[TMemory] | |
69 offset: uint64 | |
70 GPUData = GPUArray | GPUValue | |
71 | |
72 DescriptorSetType = enum | |
73 GlobalSet | |
74 MaterialSet | |
75 DescriptorSet[T: object, sType: static DescriptorSetType] = object | |
76 data: T | |
77 vk: array[INFLIGHTFRAMES, VkDescriptorSet] | |
78 | |
79 Pipeline[TShader] = object | |
80 vk: VkPipeline | |
81 layout: VkPipelineLayout | |
82 descriptorSetLayouts: array[DescriptorSetType, VkDescriptorSetLayout] | |
83 BufferType = enum | |
84 VertexBuffer, IndexBuffer, UniformBuffer | |
85 RenderData = object | |
86 descriptorPool: VkDescriptorPool | |
87 # tuple is memory and offset to next free allocation in that memory | |
88 indirectMemory: seq[tuple[memory: IndirectGPUMemory, usedOffset: uint64]] | |
89 directMemory: seq[tuple[memory: DirectGPUMemory, usedOffset: uint64]] | |
90 indirectBuffers: seq[tuple[buffer: Buffer[IndirectGPUMemory], btype: BufferType, usedOffset: uint64]] | |
91 directBuffers: seq[tuple[buffer: Buffer[DirectGPUMemory], btype: BufferType, usedOffset: uint64]] | |
1181 | 92 |
1179 | 93 var vulkan: VulkanGlobals |
94 | |
95 func alignedTo[T: SomeInteger](value: T, alignment: T): T = | |
1178 | 96 let remainder = value mod alignment |
97 if remainder == 0: | |
98 return value | |
99 else: | |
100 return value + alignment - remainder | |
101 | |
1159 | 102 func VkType[T: SupportedGPUType](value: T): VkFormat = |
103 when T is float32: VK_FORMAT_R32_SFLOAT | |
104 elif T is float64: VK_FORMAT_R64_SFLOAT | |
105 elif T is int8: VK_FORMAT_R8_SINT | |
106 elif T is int16: VK_FORMAT_R16_SINT | |
107 elif T is int32: VK_FORMAT_R32_SINT | |
108 elif T is int64: VK_FORMAT_R64_SINT | |
109 elif T is uint8: VK_FORMAT_R8_UINT | |
110 elif T is uint16: VK_FORMAT_R16_UINT | |
111 elif T is uint32: VK_FORMAT_R32_UINT | |
112 elif T is uint64: VK_FORMAT_R64_UINT | |
113 elif T is TVec2[int32]: VK_FORMAT_R32G32_SINT | |
114 elif T is TVec2[int64]: VK_FORMAT_R64G64_SINT | |
115 elif T is TVec3[int32]: VK_FORMAT_R32G32B32_SINT | |
116 elif T is TVec3[int64]: VK_FORMAT_R64G64B64_SINT | |
117 elif T is TVec4[int32]: VK_FORMAT_R32G32B32A32_SINT | |
118 elif T is TVec4[int64]: VK_FORMAT_R64G64B64A64_SINT | |
119 elif T is TVec2[uint32]: VK_FORMAT_R32G32_UINT | |
120 elif T is TVec2[uint64]: VK_FORMAT_R64G64_UINT | |
121 elif T is TVec3[uint32]: VK_FORMAT_R32G32B32_UINT | |
122 elif T is TVec3[uint64]: VK_FORMAT_R64G64B64_UINT | |
123 elif T is TVec4[uint32]: VK_FORMAT_R32G32B32A32_UINT | |
124 elif T is TVec4[uint64]: VK_FORMAT_R64G64B64A64_UINT | |
125 elif T is TVec2[float32]: VK_FORMAT_R32G32_SFLOAT | |
126 elif T is TVec2[float64]: VK_FORMAT_R64G64_SFLOAT | |
127 elif T is TVec3[float32]: VK_FORMAT_R32G32B32_SFLOAT | |
128 elif T is TVec3[float64]: VK_FORMAT_R64G64B64_SFLOAT | |
129 elif T is TVec4[float32]: VK_FORMAT_R32G32B32A32_SFLOAT | |
130 elif T is TVec4[float64]: VK_FORMAT_R64G64B64A64_SFLOAT | |
1162 | 131 elif T is TMat2[float32]: VK_FORMAT_R32G32_SFLOAT |
132 elif T is TMat2[float64]: VK_FORMAT_R64G64_SFLOAT | |
133 elif T is TMat23[float32]: VK_FORMAT_R32G32B32_SFLOAT | |
134 elif T is TMat23[float64]: VK_FORMAT_R64G64B64_SFLOAT | |
135 elif T is TMat32[float32]: VK_FORMAT_R32G32_SFLOAT | |
136 elif T is TMat32[float64]: VK_FORMAT_R64G64_SFLOAT | |
137 elif T is TMat3[float32]: VK_FORMAT_R32G32B32_SFLOAT | |
138 elif T is TMat3[float64]: VK_FORMAT_R64G64B64_SFLOAT | |
139 elif T is TMat34[float32]: VK_FORMAT_R32G32B32A32_SFLOAT | |
140 elif T is TMat34[float64]: VK_FORMAT_R64G64B64A64_SFLOAT | |
141 elif T is TMat43[float32]: VK_FORMAT_R32G32B32_SFLOAT | |
142 elif T is TMat43[float64]: VK_FORMAT_R64G64B64_SFLOAT | |
143 elif T is TMat4[float32]: VK_FORMAT_R32G32B32A32_SFLOAT | |
144 elif T is TMat4[float64]: VK_FORMAT_R64G64B64A64_SFLOAT | |
145 else: {.error: "Unsupported data type on GPU".} | |
146 | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
147 func GlslType[T: SupportedGPUType|Texture](value: T): string = |
1162 | 148 when T is float32: "float" |
149 elif T is float64: "double" | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
150 elif T is int8 or T is int16 or T is int32 or T is int64: "int" |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
151 elif T is uint8 or T is uint16 or T is uint32 or T is uint64: "uint" |
1162 | 152 elif T is TVec2[int32]: "ivec2" |
153 elif T is TVec2[int64]: "ivec2" | |
154 elif T is TVec3[int32]: "ivec3" | |
155 elif T is TVec3[int64]: "ivec3" | |
156 elif T is TVec4[int32]: "ivec4" | |
157 elif T is TVec4[int64]: "ivec4" | |
158 elif T is TVec2[uint32]: "uvec2" | |
159 elif T is TVec2[uint64]: "uvec2" | |
160 elif T is TVec3[uint32]: "uvec3" | |
161 elif T is TVec3[uint64]: "uvec3" | |
162 elif T is TVec4[uint32]: "uvec4" | |
163 elif T is TVec4[uint64]: "uvec4" | |
164 elif T is TVec2[float32]: "vec2" | |
165 elif T is TVec2[float64]: "dvec2" | |
166 elif T is TVec3[float32]: "vec3" | |
167 elif T is TVec3[float64]: "dvec3" | |
168 elif T is TVec4[float32]: "vec4" | |
169 elif T is TVec4[float64]: "dvec4" | |
170 elif T is TMat2[float32]: "mat2" | |
171 elif T is TMat2[float64]: "dmat2" | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
172 elif T is TMat23[float32]: "mat23" |
1162 | 173 elif T is TMat23[float64]: "dmat23" |
174 elif T is TMat32[float32]: "mat32" | |
175 elif T is TMat32[float64]: "dmat32" | |
176 elif T is TMat3[float32]: "mat3" | |
177 elif T is TMat3[float64]: "dmat3" | |
178 elif T is TMat34[float32]: "mat34" | |
179 elif T is TMat34[float64]: "dmat34" | |
180 elif T is TMat43[float32]: "mat43" | |
181 elif T is TMat43[float64]: "dmat43" | |
182 elif T is TMat4[float32]: "mat4" | |
183 elif T is TMat4[float64]: "dmat4" | |
184 elif T is Texture: "sampler2D" | |
1159 | 185 else: {.error: "Unsupported data type on GPU".} |
186 | |
1179 | 187 template ForVertexDataFields(shader: typed, fieldname, valuename, isinstancename, body: untyped): untyped = |
188 for theFieldname, value in fieldPairs(shader): | |
1161 | 189 when hasCustomPragma(value, VertexAttribute) or hasCustomPragma(value, InstanceAttribute): |
1159 | 190 when not typeof(value) is seq: |
191 {.error: "field '" & theFieldname & "' needs to be a seq".} | |
192 when not typeof(value) is SupportedGPUType: | |
193 {.error: "field '" & theFieldname & "' is not a supported GPU type".} | |
194 block: | |
1179 | 195 const `fieldname` {.inject.} = theFieldname |
1162 | 196 let `valuename` {.inject.} = value |
1179 | 197 const `isinstancename` {.inject.} = hasCustomPragma(value, InstanceAttribute) |
1159 | 198 body |
199 | |
1179 | 200 template ForDescriptorFields(shader: typed, fieldname, typename, countname, bindingNumber, body: untyped): untyped = |
1173 | 201 var `bindingNumber` {.inject.} = 1'u32 |
1179 | 202 for theFieldname, value in fieldPairs(shader): |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
203 when typeof(value) is Texture: |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
204 block: |
1180 | 205 const `fieldname` {.inject.} = theFieldname |
1179 | 206 const `typename` {.inject.} = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER |
207 const `countname` {.inject.} = 1'u32 | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
208 body |
1173 | 209 `bindingNumber`.inc |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
210 elif typeof(value) is object: |
1161 | 211 block: |
1180 | 212 const `fieldname` {.inject.} = theFieldname |
1179 | 213 const `typename` {.inject.} = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER |
214 const `countname` {.inject.} = 1'u32 | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
215 body |
1173 | 216 `bindingNumber`.inc |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
217 elif typeof(value) is array: |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
218 when elementType(value) is Texture: |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
219 block: |
1180 | 220 const `fieldname` {.inject.} = theFieldname |
1179 | 221 const `typename` {.inject.} = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER |
222 const `countname` {.inject.} = uint32(typeof(value).len) | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
223 body |
1173 | 224 `bindingNumber`.inc |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
225 elif elementType(value) is object: |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
226 block: |
1180 | 227 const `fieldname` {.inject.} = theFieldname |
1179 | 228 const `typename` {.inject.} = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER |
229 const `countname` {.inject.} = uint32(typeof(value).len) | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
230 body |
1173 | 231 `bindingNumber`.inc |
1161 | 232 |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
233 func NumberOfVertexInputAttributeDescriptors[T: SupportedGPUType|Texture](value: T): uint32 = |
1159 | 234 when T is TMat2[float32] or T is TMat2[float64] or T is TMat23[float32] or T is TMat23[float64]: |
235 2 | |
236 elif T is TMat32[float32] or T is TMat32[float64] or T is TMat3[float32] or T is TMat3[float64] or T is TMat34[float32] or T is TMat34[float64]: | |
237 3 | |
238 elif T is TMat43[float32] or T is TMat43[float64] or T is TMat4[float32] or T is TMat4[float64]: | |
239 4 | |
240 else: | |
241 1 | |
242 | |
1162 | 243 func NLocationSlots[T: SupportedGPUType|Texture](value: T): uint32 = |
1159 | 244 #[ |
245 single location: | |
1162 | 246 - any scalar |
247 - any 16-bit vector | |
248 - any 32-bit vector | |
249 - any 64-bit vector that has max. 2 components | |
1159 | 250 16-bit scalar and vector types, and |
251 32-bit scalar and vector types, and | |
252 64-bit scalar and 2-component vector types. | |
253 two locations | |
254 64-bit three- and four-component vectors | |
255 ]# | |
1162 | 256 when T is TVec3[int64] or |
257 T is TVec4[int64] or | |
258 T is TVec3[uint64] or | |
259 T is TVec4[uint64] or | |
260 T is TVec3[float64] or | |
261 T is TVec4[float64] or | |
262 T is TMat23[float64] or | |
263 T is TMat3[float64] or | |
264 T is TMat34[float64] or | |
265 T is TMat43[float64] or | |
266 T is TMat4[float64]: | |
1159 | 267 return 2 |
268 else: | |
269 return 1 | |
270 | |
1182 | 271 template sType(descriptorSet: DescriptorSet): untyped = |
272 get(genericParams(typeof(gpuData)), 1) | |
1178 | 273 |
274 template UsesIndirectMemory(gpuData: GPUData): untyped = | |
275 get(genericParams(typeof(gpuData)), 1) is IndirectGPUMemory | |
276 template UsesDirectMemory(gpuData: GPUData): untyped = | |
277 get(genericParams(typeof(gpuData)), 1) is DirectGPUMemory | |
278 | |
279 template size(gpuArray: GPUArray): uint64 = | |
1179 | 280 (gpuArray.data.len * sizeof(elementType(gpuArray.data))).uint64 |
1178 | 281 template size(gpuValue: GPUValue): uint64 = |
1179 | 282 sizeof(gpuValue.data).uint64 |
283 | |
284 template datapointer(gpuArray: GPUArray): pointer = | |
285 addr(gpuArray.data[0]) | |
286 template datapointer(gpuValue: GPUValue): pointer = | |
287 addr(gpuValue.data) | |
1178 | 288 |
1179 | 289 proc AllocationSize(buffer: Buffer): uint64 = |
290 var req: VkMemoryRequirements | |
291 vkGetBufferMemoryRequirements(vulkan.device, buffer.vk, addr(req)) | |
292 return req.size | |
293 | |
294 proc GetPhysicalDevice(instance: VkInstance): VkPhysicalDevice = | |
1178 | 295 var nDevices: uint32 |
1179 | 296 checkVkResult vkEnumeratePhysicalDevices(instance, addr(nDevices), nil) |
1178 | 297 var devices = newSeq[VkPhysicalDevice](nDevices) |
1179 | 298 checkVkResult vkEnumeratePhysicalDevices(instance, addr(nDevices), devices.ToCPointer) |
1178 | 299 |
1179 | 300 var score = 0'u32 |
1178 | 301 for pDevice in devices: |
302 var props: VkPhysicalDeviceProperties | |
303 vkGetPhysicalDeviceProperties(pDevice, addr(props)) | |
1179 | 304 if props.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU and props.limits.maxImageDimension2D > score: |
305 score = props.limits.maxImageDimension2D | |
1178 | 306 result = pDevice |
307 | |
1179 | 308 if score == 0: |
1178 | 309 for pDevice in devices: |
310 var props: VkPhysicalDeviceProperties | |
311 vkGetPhysicalDeviceProperties(pDevice, addr(props)) | |
1179 | 312 if props.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU and props.limits.maxImageDimension2D > score: |
313 score = props.limits.maxImageDimension2D | |
1178 | 314 result = pDevice |
315 | |
316 assert score > 0, "Unable to find integrated or discrete GPU" | |
317 | |
318 | |
1179 | 319 proc GetDirectMemoryTypeIndex(): uint32 = |
1178 | 320 var physicalProperties: VkPhysicalDeviceMemoryProperties |
1179 | 321 vkGetPhysicalDeviceMemoryProperties(vulkan.physicalDevice, addr(physicalProperties)) |
1178 | 322 |
323 var biggestHeap: uint64 = 0 | |
324 result = high(uint32) | |
325 # try to find host-visible type | |
1179 | 326 for i in 0'u32 ..< physicalProperties.memoryTypeCount: |
1178 | 327 let flags = toEnums(physicalProperties.memoryTypes[i].propertyFlags) |
328 if VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT in flags: | |
329 let size = physicalProperties.memoryHeaps[physicalProperties.memoryTypes[i].heapIndex].size | |
330 if size > biggestHeap: | |
331 biggestHeap = size | |
332 result = i | |
333 assert result != high(uint32), "There is not host visible memory. This is likely a driver bug." | |
334 | |
1179 | 335 proc GetQueueFamily(pDevice: VkPhysicalDevice, qType: VkQueueFlagBits): uint32 = |
1178 | 336 var nQueuefamilies: uint32 |
1179 | 337 vkGetPhysicalDeviceQueueFamilyProperties(pDevice, addr nQueuefamilies, nil) |
1178 | 338 var queuFamilies = newSeq[VkQueueFamilyProperties](nQueuefamilies) |
1179 | 339 vkGetPhysicalDeviceQueueFamilyProperties(pDevice, addr nQueuefamilies, queuFamilies.ToCPointer) |
340 for i in 0'u32 ..< nQueuefamilies: | |
1178 | 341 if qType in toEnums(queuFamilies[i].queueFlags): |
342 return i | |
343 assert false, &"Queue of type {qType} not found" | |
344 | |
1179 | 345 proc GetQueue(device: VkDevice, queueFamilyIndex: uint32, qType: VkQueueFlagBits): VkQueue = |
346 vkGetDeviceQueue( | |
1178 | 347 device, |
1179 | 348 queueFamilyIndex, |
1178 | 349 0, |
350 addr(result), | |
351 ) | |
352 | |
1179 | 353 proc GetSurfaceFormat(): VkFormat = |
354 # EVERY windows driver and almost every linux driver should support this | |
355 VK_FORMAT_B8G8R8A8_SRGB | |
1162 | 356 |
1179 | 357 template WithSingleUseCommandBuffer(device: VkDevice, cmd, body: untyped): untyped = |
1178 | 358 block: |
1179 | 359 var |
360 commandBufferPool: VkCommandPool | |
361 createInfo = VkCommandPoolCreateInfo( | |
1178 | 362 sType: VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, |
363 flags: toBits [VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT], | |
1179 | 364 queueFamilyIndex: vulkan.queueFamilyIndex, |
1178 | 365 ) |
366 checkVkResult vkCreateCommandPool(device, addr createInfo, nil, addr(commandBufferPool)) | |
367 var | |
368 `cmd` {.inject.}: VkCommandBuffer | |
369 allocInfo = VkCommandBufferAllocateInfo( | |
370 sType: VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, | |
371 commandPool: commandBufferPool, | |
372 level: VK_COMMAND_BUFFER_LEVEL_PRIMARY, | |
373 commandBufferCount: 1, | |
374 ) | |
1179 | 375 checkVkResult device.vkAllocateCommandBuffers(addr allocInfo, addr(`cmd`)) |
376 var beginInfo = VkCommandBufferBeginInfo( | |
1178 | 377 sType: VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, |
378 flags: VkCommandBufferUsageFlags(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT), | |
379 ) | |
380 checkVkResult `cmd`.vkBeginCommandBuffer(addr beginInfo) | |
381 | |
382 body | |
383 | |
384 checkVkResult `cmd`.vkEndCommandBuffer() | |
385 var submitInfo = VkSubmitInfo( | |
386 sType: VK_STRUCTURE_TYPE_SUBMIT_INFO, | |
387 commandBufferCount: 1, | |
388 pCommandBuffers: addr(`cmd`), | |
389 ) | |
1179 | 390 |
391 var | |
392 fence: VkFence | |
393 fenceInfo = VkFenceCreateInfo( | |
394 sType: VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, | |
395 # flags: toBits [VK_FENCE_CREATE_SIGNALED_BIT] | |
396 ) | |
397 checkVkResult device.vkCreateFence(addr(fenceInfo), nil, addr(fence)) | |
398 checkVkResult vkQueueSubmit(vulkan.queue, 1, addr(submitInfo), fence) | |
399 checkVkResult vkWaitForFences(device, 1, addr fence, false, high(uint64)) | |
1178 | 400 vkDestroyCommandPool(device, commandBufferPool, nil) |
401 | |
402 | |
1179 | 403 proc UpdateGPUBuffer(gpuData: GPUData) = |
404 if gpuData.size == 0: | |
405 return | |
1178 | 406 when UsesDirectMemory(gpuData): |
1179 | 407 copyMem(cast[pointer](cast[uint64](gpuData.buffer.memory.data) + gpuData.buffer.offset + gpuData.offset), gpuData.datapointer, gpuData.size) |
1178 | 408 else: |
409 var | |
410 stagingBuffer: VkBuffer | |
411 createInfo = VkBufferCreateInfo( | |
412 sType: VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, | |
413 flags: VkBufferCreateFlags(0), | |
414 size: gpuData.size, | |
415 usage: toBits([VK_BUFFER_USAGE_TRANSFER_SRC_BIT]), | |
416 sharingMode: VK_SHARING_MODE_EXCLUSIVE, | |
417 ) | |
418 checkVkResult vkCreateBuffer( | |
1179 | 419 device = vulkan.device, |
1178 | 420 pCreateInfo = addr(createInfo), |
421 pAllocator = nil, | |
422 pBuffer = addr(stagingBuffer), | |
423 ) | |
424 var | |
425 stagingMemory: VkDeviceMemory | |
426 stagingPtr: pointer | |
427 memoryAllocationInfo = VkMemoryAllocateInfo( | |
428 sType: VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, | |
1179 | 429 allocationSize: gpuData.buffer.AllocationSize(), |
1178 | 430 memoryTypeIndex: GetDirectMemoryTypeIndex(), |
431 ) | |
432 checkVkResult vkAllocateMemory( | |
1179 | 433 vulkan.device, |
1178 | 434 addr(memoryAllocationInfo), |
435 nil, | |
436 addr(stagingMemory), | |
437 ) | |
1179 | 438 checkVkResult vkBindBufferMemory(vulkan.device, stagingBuffer, stagingMemory, 0) |
1178 | 439 checkVkResult vkMapMemory( |
1179 | 440 device = vulkan.device, |
1178 | 441 memory = stagingMemory, |
442 offset = 0'u64, | |
443 size = VK_WHOLE_SIZE, | |
444 flags = VkMemoryMapFlags(0), | |
1179 | 445 ppData = addr(stagingPtr) |
1178 | 446 ) |
1179 | 447 copyMem(stagingPtr, gpuData.datapointer, gpuData.size) |
1178 | 448 var stagingRange = VkMappedMemoryRange( |
449 sType: VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, | |
450 memory: stagingMemory, | |
451 size: VK_WHOLE_SIZE, | |
452 ) | |
1179 | 453 checkVkResult vkFlushMappedMemoryRanges(vulkan.device, 1, addr(stagingRange)) |
1178 | 454 |
1179 | 455 WithSingleUseCommandBuffer(vulkan.device, commandBuffer): |
1178 | 456 var copyRegion = VkBufferCopy(size: gpuData.size) |
457 vkCmdCopyBuffer(commandBuffer, stagingBuffer, gpuData.buffer.vk, 1, addr(copyRegion)) | |
458 | |
1179 | 459 vkDestroyBuffer(vulkan.device, stagingBuffer, nil) |
460 vkFreeMemory(vulkan.device, stagingMemory, nil) | |
461 | |
462 proc UpdateAllGPUBuffers[T](value: T) = | |
463 for name, fieldvalue in value.fieldPairs(): | |
464 when typeof(fieldvalue) is GPUData: | |
465 UpdateGPUBuffer(fieldvalue) | |
1177 | 466 |
1182 | 467 proc InitDescriptorSet( |
1180 | 468 renderData: RenderData, |
1182 | 469 layout: VkDescriptorSetLayout, |
470 descriptorSet: var DescriptorSet, | |
471 ) = | |
472 for name, value in descriptorSet.data.fieldPairs: | |
473 when typeof(value) is GPUValue: | |
474 assert value.buffer.vk.valid | |
475 # TODO: | |
476 # when typeof(value) is Texture: | |
477 # assert value.texture.vk.valid | |
1180 | 478 |
1182 | 479 # allocate |
480 var layouts = newSeqWith(descriptorSet.vk.len, layout) | |
1180 | 481 var allocInfo = VkDescriptorSetAllocateInfo( |
482 sType: VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, | |
483 descriptorPool: renderData.descriptorPool, | |
484 descriptorSetCount: uint32(layouts.len), | |
485 pSetLayouts: layouts.ToCPointer, | |
486 ) | |
1182 | 487 checkVkResult vkAllocateDescriptorSets(vulkan.device, addr(allocInfo), descriptorSet.vk.ToCPointer) |
488 | |
489 # write | |
490 var descriptorSetWrites: newSeq[VkWriteDescriptorSet](descriptorSet.vk.len) | |
491 for i in 0 ..< descriptorSet.vk.len: | |
492 descriptorSetWrites.add | |
493 | |
494 | |
495 vkUpdateDescriptorSets(vulkan.device, descriptorSetWrites.len.uint32, descriptorSetWrites.ToCPointer, 0, nil) | |
496 | |
497 #[ | |
498 proc WriteDescriptors[TShader, TUniforms, TGlobals](renderData: RenderData, uniforms: TUniforms, globals: TGlobals) = | |
499 var descriptorSetWrites: seq[VkWriteDescriptorSet] | |
500 ForDescriptorFields(default(TShader), fieldName, descriptorType, descriptorCount, descriptorBindingNumber): | |
501 for frameInFlight in 0 ..< renderData.descriptorSets.len: | |
502 when descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: | |
503 when HasGPUValueField[TUniforms](fieldName): | |
504 WithGPUValueField(uniforms, fieldName, gpuValue): | |
505 let bufferInfo = VkDescriptorBufferInfo( | |
506 buffer: gpuValue.buffer.vk, | |
507 offset: gpuValue.buffer.offset, | |
508 range: gpuValue.buffer.size, | |
509 ) | |
510 descriptorSetWrites.add VkWriteDescriptorSet( | |
511 sType: VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, | |
512 dstSet: renderData.descriptorSets[frameInFlight], | |
513 dstBinding: descriptorBindingNumber, | |
514 dstArrayElement: uint32(0), | |
515 descriptorType: descriptorType, | |
516 descriptorCount: descriptorCount, | |
517 pImageInfo: nil, | |
518 pBufferInfo: addr(bufferInfo), | |
519 ) | |
520 elif HasGPUValueField[TGlobals](fieldName): | |
521 WithGPUValueField(globals, fieldName, theValue): | |
522 let bufferInfo = VkDescriptorBufferInfo( | |
523 buffer: theValue.buffer.vk, | |
524 offset: theValue.buffer.offset, | |
525 range: theValue.buffer.size, | |
526 ) | |
527 descriptorSetWrites.add VkWriteDescriptorSet( | |
528 sType: VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, | |
529 dstSet: renderData.descriptorSets[frameInFlight], | |
530 dstBinding: descriptorBindingNumber, | |
531 dstArrayElement: uint32(0), | |
532 descriptorType: descriptorType, | |
533 descriptorCount: descriptorCount, | |
534 pImageInfo: nil, | |
535 pBufferInfo: addr(bufferInfo), | |
536 ) | |
537 else: | |
538 {.error: "Unable to find field '" & fieldName & "' in uniforms or globals".} | |
539 elif descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: | |
540 # TODO | |
541 let imageInfo = VkDescriptorImageInfo( | |
542 sampler: VkSampler(0), | |
543 imageView: VkImageView(0), | |
544 imageLayout: VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, | |
545 ) | |
546 descriptorSetWrites.add VkWriteDescriptorSet( | |
547 sType: VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, | |
548 dstSet: renderData.descriptorSets[frameInFlight], | |
549 dstBinding: descriptorBindingNumber, | |
550 dstArrayElement: 0'u32, | |
551 descriptorType: descriptorType, | |
552 descriptorCount: descriptorCount, | |
553 pImageInfo: addr(imageInfo), | |
554 pBufferInfo: nil, | |
555 ) | |
556 else: | |
557 assert false, "Unsupported descriptor type" | |
558 vkUpdateDescriptorSets(vulkan.device, uint32(descriptorSetWrites.len), descriptorSetWrites.ToCPointer, 0, nil) | |
559 ]# | |
560 | |
1180 | 561 |
1161 | 562 converter toVkIndexType(indexType: IndexType): VkIndexType = |
563 case indexType: | |
564 of None: VK_INDEX_TYPE_NONE_KHR | |
565 of UInt8: VK_INDEX_TYPE_UINT8_EXT | |
566 of UInt16: VK_INDEX_TYPE_UINT16 | |
567 of UInt32: VK_INDEX_TYPE_UINT32 | |
1159 | 568 |
1179 | 569 proc CreateRenderPass(format: VkFormat): VkRenderPass = |
1172 | 570 var |
571 attachments = @[VkAttachmentDescription( | |
572 format: format, | |
573 samples: VK_SAMPLE_COUNT_1_BIT, | |
574 loadOp: VK_ATTACHMENT_LOAD_OP_CLEAR, | |
575 storeOp: VK_ATTACHMENT_STORE_OP_STORE, | |
576 stencilLoadOp: VK_ATTACHMENT_LOAD_OP_DONT_CARE, | |
577 stencilStoreOp: VK_ATTACHMENT_STORE_OP_DONT_CARE, | |
578 initialLayout: VK_IMAGE_LAYOUT_UNDEFINED, | |
579 finalLayout: VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, | |
580 )] | |
581 dependencies = @[VkSubpassDependency( | |
582 srcSubpass: VK_SUBPASS_EXTERNAL, | |
583 dstSubpass: 0, | |
584 srcStageMask: toBits [VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT], | |
585 srcAccessMask: toBits [VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT], | |
586 dstStageMask: toBits [VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT], | |
587 dstAccessMask: toBits [VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT], | |
588 )] | |
589 outputs = @[ | |
590 VkAttachmentReference( | |
591 attachment: 0, | |
592 layout: VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, | |
593 ) | |
594 ] | |
595 | |
596 var subpassesList = [ | |
597 VkSubpassDescription( | |
598 flags: VkSubpassDescriptionFlags(0), | |
599 pipelineBindPoint: VK_PIPELINE_BIND_POINT_GRAPHICS, | |
600 inputAttachmentCount: 0, | |
601 pInputAttachments: nil, | |
602 colorAttachmentCount: uint32(outputs.len), | |
603 pColorAttachments: outputs.ToCPointer, | |
604 pResolveAttachments: nil, | |
605 pDepthStencilAttachment: nil, | |
606 preserveAttachmentCount: 0, | |
607 pPreserveAttachments: nil, | |
608 ) | |
609 ] | |
610 | |
611 var createInfo = VkRenderPassCreateInfo( | |
612 sType: VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, | |
613 attachmentCount: uint32(attachments.len), | |
614 pAttachments: attachments.ToCPointer, | |
615 subpassCount: uint32(subpassesList.len), | |
616 pSubpasses: subpassesList.ToCPointer, | |
617 dependencyCount: uint32(dependencies.len), | |
618 pDependencies: dependencies.ToCPointer, | |
619 ) | |
1179 | 620 checkVkResult vulkan.device.vkCreateRenderPass(addr(createInfo), nil, addr(result)) |
1172 | 621 |
1162 | 622 proc compileGlslToSPIRV(stage: VkShaderStageFlagBits, shaderSource: string): seq[uint32] {.compileTime.} = |
623 func stage2string(stage: VkShaderStageFlagBits): string {.compileTime.} = | |
624 case stage | |
625 of VK_SHADER_STAGE_VERTEX_BIT: "vert" | |
626 of VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT: "tesc" | |
627 of VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT: "tese" | |
628 of VK_SHADER_STAGE_GEOMETRY_BIT: "geom" | |
629 of VK_SHADER_STAGE_FRAGMENT_BIT: "frag" | |
630 of VK_SHADER_STAGE_COMPUTE_BIT: "comp" | |
631 else: "" | |
1161 | 632 |
1162 | 633 when defined(nimcheck): # will not run if nimcheck is running |
634 return result | |
635 | |
636 let | |
637 stagename = stage2string(stage) | |
638 shaderHash = hash(shaderSource) | |
639 shaderfile = getTempDir() / &"shader_{shaderHash}.{stagename}" | |
640 | |
641 if not shaderfile.fileExists: | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
642 echo "shader of type ", stage |
1162 | 643 for i, line in enumerate(shaderSource.splitlines()): |
644 echo " ", i + 1, " ", line | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
645 # var glslExe = currentSourcePath.parentDir.parentDir.parentDir / "tools" / "glslangValidator" |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
646 var glslExe = currentSourcePath.parentDir / "tools" / "glslangValidator" |
1162 | 647 when defined(windows): |
648 glslExe = glslExe & "." & ExeExt | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
649 let command = &"{glslExe} --entry-point main -V --stdin -S {stagename} -o {shaderfile}" |
1162 | 650 echo "run: ", command |
651 discard StaticExecChecked( | |
652 command = command, | |
653 input = shaderSource | |
654 ) | |
655 else: | |
656 echo &"shaderfile {shaderfile} is up-to-date" | |
657 | |
658 when defined(mingw) and defined(linux): # required for crosscompilation, path separators get messed up | |
659 let shaderbinary = staticRead shaderfile.replace("\\", "/") | |
660 else: | |
661 let shaderbinary = staticRead shaderfile | |
662 | |
663 var i = 0 | |
664 while i < shaderbinary.len: | |
665 result.add( | |
666 (uint32(shaderbinary[i + 0]) shl 0) or | |
667 (uint32(shaderbinary[i + 1]) shl 8) or | |
668 (uint32(shaderbinary[i + 2]) shl 16) or | |
669 (uint32(shaderbinary[i + 3]) shl 24) | |
670 ) | |
671 i += 4 | |
672 | |
673 proc generateShaderSource[TShader](shader: TShader): (string, string) {.compileTime.} = | |
674 const GLSL_VERSION = "450" | |
675 var vsInput: seq[string] | |
676 var vsOutput: seq[string] | |
677 var fsInput: seq[string] | |
678 var fsOutput: seq[string] | |
679 var uniforms: seq[string] | |
680 var samplers: seq[string] | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
681 var vsInputLocation = 0'u32 |
1162 | 682 var passLocation = 0 |
683 var fsOutputLocation = 0 | |
684 | |
1180 | 685 var descriptorSetCount = 0 |
1162 | 686 for fieldname, value in fieldPairs(shader): |
687 # vertex shader inputs | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
688 when hasCustomPragma(value, VertexAttribute) or hasCustomPragma(value, InstanceAttribute): |
1162 | 689 assert typeof(value) is SupportedGPUType |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
690 vsInput.add "layout(location = " & $vsInputLocation & ") in " & GlslType(value) & " " & fieldname & ";" |
1162 | 691 for j in 0 ..< NumberOfVertexInputAttributeDescriptors(value): |
692 vsInputLocation += NLocationSlots(value) | |
1180 | 693 |
1162 | 694 # intermediate values, passed between shaders |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
695 elif hasCustomPragma(value, Pass) or hasCustomPragma(value, PassFlat): |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
696 let flat = if hasCustomPragma(value, PassFlat): "flat " else: "" |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
697 vsOutput.add "layout(location = " & $passLocation & ") " & flat & "out " & GlslType(value) & " " & fieldname & ";" |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
698 fsInput.add "layout(location = " & $passLocation & ") " & flat & "in " & GlslType(value) & " " & fieldname & ";" |
1162 | 699 passLocation.inc |
1180 | 700 |
701 # fragment shader output | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
702 elif hasCustomPragma(value, ShaderOutput): |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
703 fsOutput.add &"layout(location = " & $fsOutputLocation & ") out " & GlslType(value) & " " & fieldname & ";" |
1162 | 704 fsOutputLocation.inc |
1180 | 705 |
706 # descriptor sets | |
707 # need to consider 4 cases: uniform block, texture, uniform block array, texture array | |
1182 | 708 elif typeof(value) is DescriptorSet: |
709 assert descriptorSetCount <= DescriptorSetType.high.int, &"{tt.name(TShader)}: maximum {DescriptorSetType.high} allowed" | |
1180 | 710 |
711 var descriptorBinding = 0 | |
1182 | 712 for descriptorName, descriptorValue in fieldPairs(value.data): |
1180 | 713 |
714 when typeof(descriptorValue) is Texture: | |
715 samplers.add "layout(set=" & $descriptorSetCount & ", binding = " & $descriptorBinding & ") uniform " & GlslType(descriptorValue) & " " & descriptorName & ";" | |
716 descriptorBinding.inc | |
717 | |
718 elif typeof(descriptorValue) is GPUValue: | |
719 uniforms.add "layout(set=" & $descriptorSetCount & ", binding = " & $descriptorBinding & ") uniform T" & descriptorName & " {" | |
720 when typeof(descriptorValue.data) is object: | |
721 for blockFieldName, blockFieldValue in descriptorValue.data.fieldPairs(): | |
722 assert typeof(blockFieldValue) is SupportedGPUType, "uniform block field '" & blockFieldName & "' is not a SupportedGPUType" | |
723 uniforms.add " " & GlslType(blockFieldValue) & " " & blockFieldName & ";" | |
724 uniforms.add "} " & descriptorName & ";" | |
725 elif typeof(descriptorValue.data) is array: | |
726 for blockFieldName, blockFieldValue in default(elementType(descriptorValue.data)).fieldPairs(): | |
727 assert typeof(blockFieldValue) is SupportedGPUType, "uniform block field '" & blockFieldName & "' is not a SupportedGPUType" | |
728 uniforms.add " " & GlslType(blockFieldValue) & " " & blockFieldName & ";" | |
729 uniforms.add "} " & descriptorName & "[" & $descriptorValue.data.len & "];" | |
730 descriptorBinding.inc | |
731 elif typeof(descriptorValue) is array: | |
732 when elementType(descriptorValue) is Texture: | |
733 let arrayDecl = "[" & $typeof(descriptorValue).len & "]" | |
734 samplers.add "layout(set=" & $descriptorSetCount & ", binding = " & $descriptorBinding & ") uniform " & GlslType(default(elementType(descriptorValue))) & " " & descriptorName & "" & arrayDecl & ";" | |
735 descriptorBinding.inc | |
736 else: | |
737 {.error: "Unsupported shader descriptor field " & descriptorName.} | |
738 descriptorSetCount.inc | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
739 elif fieldname in ["vertexCode", "fragmentCode"]: |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
740 discard |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
741 else: |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
742 {.error: "Unsupported shader field '" & tt.name(TShader) & "." & fieldname & "' of type " & tt.name(typeof(value)).} |
1162 | 743 |
744 result[0] = (@[&"#version {GLSL_VERSION}", "#extension GL_EXT_scalar_block_layout : require", ""] & | |
745 vsInput & | |
746 uniforms & | |
747 samplers & | |
748 vsOutput & | |
749 @[shader.vertexCode]).join("\n") | |
750 | |
751 result[1] = (@[&"#version {GLSL_VERSION}", "#extension GL_EXT_scalar_block_layout : require", ""] & | |
752 fsInput & | |
753 uniforms & | |
754 samplers & | |
755 fsOutput & | |
756 @[shader.fragmentCode]).join("\n") | |
757 | |
1179 | 758 proc CompileShader[TShader](shader: static TShader): ShaderObject[TShader] = |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
759 const (vertexShaderSource, fragmentShaderSource) = generateShaderSource(shader) |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
760 |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
761 let vertexBinary = compileGlslToSPIRV(VK_SHADER_STAGE_VERTEX_BIT, vertexShaderSource) |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
762 let fragmentBinary = compileGlslToSPIRV(VK_SHADER_STAGE_FRAGMENT_BIT, fragmentShaderSource) |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
763 |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
764 var createInfoVertex = VkShaderModuleCreateInfo( |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
765 sType: VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
766 codeSize: csize_t(vertexBinary.len * sizeof(uint32)), |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
767 pCode: vertexBinary.ToCPointer, |
1162 | 768 ) |
1179 | 769 checkVkResult vulkan.device.vkCreateShaderModule(addr(createInfoVertex), nil, addr(result.vertexShader)) |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
770 var createInfoFragment = VkShaderModuleCreateInfo( |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
771 sType: VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
772 codeSize: csize_t(fragmentBinary.len * sizeof(uint32)), |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
773 pCode: fragmentBinary.ToCPointer, |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
774 ) |
1179 | 775 checkVkResult vulkan.device.vkCreateShaderModule(addr(createInfoFragment), nil, addr(result.fragmentShader)) |
1162 | 776 |
777 | |
1179 | 778 proc CreatePipeline[TShader]( |
1159 | 779 renderPass: VkRenderPass, |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
780 shader: ShaderObject[TShader], |
1159 | 781 topology: VkPrimitiveTopology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, |
782 polygonMode: VkPolygonMode = VK_POLYGON_MODE_FILL, | |
783 cullMode: VkCullModeFlagBits = VK_CULL_MODE_BACK_BIT, | |
784 frontFace: VkFrontFace = VK_FRONT_FACE_CLOCKWISE, | |
1176 | 785 descriptorPoolLimit = 1024 |
1162 | 786 ): Pipeline[TShader] = |
1164 | 787 # create pipeline |
1180 | 788 |
1182 | 789 for theFieldname, value in fieldPairs(default(TShader)): |
790 when typeof(value) is DescriptorSet: | |
791 var layoutbindings: seq[VkDescriptorSetLayoutBinding] | |
792 ForDescriptorFields(value.data, fieldName, descriptorType, descriptorCount, descriptorBindingNumber): | |
793 layoutbindings.add VkDescriptorSetLayoutBinding( | |
794 binding: descriptorBindingNumber, | |
795 descriptorType: descriptorType, | |
796 descriptorCount: descriptorCount, | |
797 stageFlags: VkShaderStageFlags(VK_SHADER_STAGE_ALL_GRAPHICS), | |
798 pImmutableSamplers: nil, | |
799 ) | |
800 var layoutCreateInfo = VkDescriptorSetLayoutCreateInfo( | |
801 sType: VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, | |
802 bindingCount: layoutbindings.len.uint32, | |
803 pBindings: layoutbindings.ToCPointer | |
1180 | 804 ) |
1182 | 805 checkVkResult vkCreateDescriptorSetLayout( |
806 vulkan.device, | |
807 addr(layoutCreateInfo), | |
808 nil, | |
809 addr(result.descriptorSetLayouts[value.sType]) | |
810 ) | |
1161 | 811 let pipelineLayoutInfo = VkPipelineLayoutCreateInfo( |
812 sType: VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, | |
1179 | 813 setLayoutCount: result.descriptorSetLayouts.len.uint32, |
1180 | 814 pSetLayouts: result.descriptorSetLayouts.ToCPointer, |
1161 | 815 # pushConstantRangeCount: uint32(pushConstants.len), |
816 # pPushConstantRanges: pushConstants.ToCPointer, | |
817 ) | |
1179 | 818 checkVkResult vkCreatePipelineLayout(vulkan.device, addr(pipelineLayoutInfo), nil, addr(result.layout)) |
1159 | 819 |
820 let stages = [ | |
821 VkPipelineShaderStageCreateInfo( | |
822 sType: VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, | |
823 stage: VK_SHADER_STAGE_VERTEX_BIT, | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
824 module: shader.vertexShader, |
1159 | 825 pName: "main", |
826 ), | |
827 VkPipelineShaderStageCreateInfo( | |
828 sType: VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, | |
829 stage: VK_SHADER_STAGE_FRAGMENT_BIT, | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
830 module: shader.fragmentShader, |
1159 | 831 pName: "main", |
832 ), | |
833 ] | |
1162 | 834 var |
835 bindings: seq[VkVertexInputBindingDescription] | |
836 attributes: seq[VkVertexInputAttributeDescription] | |
1159 | 837 var inputBindingNumber = 0'u32 |
1162 | 838 var location = 0'u32 |
839 ForVertexDataFields(default(TShader), fieldname, value, isInstanceAttr): | |
1159 | 840 bindings.add VkVertexInputBindingDescription( |
841 binding: inputBindingNumber, | |
842 stride: sizeof(value).uint32, | |
843 inputRate: if isInstanceAttr: VK_VERTEX_INPUT_RATE_INSTANCE else: VK_VERTEX_INPUT_RATE_VERTEX, | |
844 ) | |
845 # allows to submit larger data structures like Mat44, for most other types will be 1 | |
846 let perDescriptorSize = sizeof(value).uint32 div NumberOfVertexInputAttributeDescriptors(value) | |
847 for i in 0'u32 ..< NumberOfVertexInputAttributeDescriptors(value): | |
848 attributes.add VkVertexInputAttributeDescription( | |
849 binding: inputBindingNumber, | |
1162 | 850 location: location, |
1159 | 851 format: VkType(value), |
852 offset: i * perDescriptorSize, | |
853 ) | |
1162 | 854 location += NLocationSlots(value) |
1159 | 855 inc inputBindingNumber |
856 | |
857 let | |
858 vertexInputInfo = VkPipelineVertexInputStateCreateInfo( | |
859 sType: VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, | |
860 vertexBindingDescriptionCount: uint32(bindings.len), | |
861 pVertexBindingDescriptions: bindings.ToCPointer, | |
862 vertexAttributeDescriptionCount: uint32(attributes.len), | |
863 pVertexAttributeDescriptions: attributes.ToCPointer, | |
864 ) | |
865 inputAssembly = VkPipelineInputAssemblyStateCreateInfo( | |
866 sType: VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, | |
867 topology: topology, | |
868 primitiveRestartEnable: false, | |
869 ) | |
870 viewportState = VkPipelineViewportStateCreateInfo( | |
871 sType: VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, | |
872 viewportCount: 1, | |
873 scissorCount: 1, | |
874 ) | |
875 rasterizer = VkPipelineRasterizationStateCreateInfo( | |
876 sType: VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, | |
877 depthClampEnable: VK_FALSE, | |
878 rasterizerDiscardEnable: VK_FALSE, | |
879 polygonMode: polygonMode, | |
880 lineWidth: 1.0, | |
881 cullMode: toBits [cullMode], | |
882 frontFace: frontFace, | |
883 depthBiasEnable: VK_FALSE, | |
884 depthBiasConstantFactor: 0.0, | |
885 depthBiasClamp: 0.0, | |
886 depthBiasSlopeFactor: 0.0, | |
887 ) | |
888 multisampling = VkPipelineMultisampleStateCreateInfo( | |
889 sType: VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, | |
890 sampleShadingEnable: VK_FALSE, | |
891 rasterizationSamples: VK_SAMPLE_COUNT_1_BIT, | |
892 minSampleShading: 1.0, | |
893 pSampleMask: nil, | |
894 alphaToCoverageEnable: VK_FALSE, | |
895 alphaToOneEnable: VK_FALSE, | |
896 ) | |
897 colorBlendAttachment = VkPipelineColorBlendAttachmentState( | |
898 colorWriteMask: toBits [VK_COLOR_COMPONENT_R_BIT, VK_COLOR_COMPONENT_G_BIT, VK_COLOR_COMPONENT_B_BIT, VK_COLOR_COMPONENT_A_BIT], | |
899 blendEnable: VK_TRUE, | |
900 srcColorBlendFactor: VK_BLEND_FACTOR_SRC_ALPHA, | |
901 dstColorBlendFactor: VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, | |
902 colorBlendOp: VK_BLEND_OP_ADD, | |
903 srcAlphaBlendFactor: VK_BLEND_FACTOR_ONE, | |
904 dstAlphaBlendFactor: VK_BLEND_FACTOR_ZERO, | |
905 alphaBlendOp: VK_BLEND_OP_ADD, | |
906 ) | |
907 colorBlending = VkPipelineColorBlendStateCreateInfo( | |
908 sType: VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, | |
909 logicOpEnable: false, | |
910 attachmentCount: 1, | |
911 pAttachments: addr(colorBlendAttachment), | |
912 ) | |
913 dynamicStates = [VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR] | |
914 dynamicState = VkPipelineDynamicStateCreateInfo( | |
915 sType: VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, | |
916 dynamicStateCount: dynamicStates.len.uint32, | |
917 pDynamicStates: dynamicStates.ToCPointer, | |
918 ) | |
919 let createInfo = VkGraphicsPipelineCreateInfo( | |
920 sType: VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, | |
921 stageCount: 2, | |
1162 | 922 pStages: stages.ToCPointer, |
1159 | 923 pVertexInputState: addr(vertexInputInfo), |
924 pInputAssemblyState: addr(inputAssembly), | |
925 pViewportState: addr(viewportState), | |
926 pRasterizationState: addr(rasterizer), | |
927 pMultisampleState: addr(multisampling), | |
928 pDepthStencilState: nil, | |
929 pColorBlendState: addr(colorBlending), | |
930 pDynamicState: addr(dynamicState), | |
931 layout: result.layout, | |
932 renderPass: renderPass, | |
933 subpass: 0, | |
934 basePipelineHandle: VkPipeline(0), | |
935 basePipelineIndex: -1, | |
936 ) | |
937 checkVkResult vkCreateGraphicsPipelines( | |
1179 | 938 vulkan.device, |
1159 | 939 VkPipelineCache(0), |
940 1, | |
941 addr(createInfo), | |
942 nil, | |
1182 | 943 addr(result.vk) |
1159 | 944 ) |
945 | |
1179 | 946 proc AllocateIndirectMemory(size: uint64): IndirectGPUMemory = |
1176 | 947 # chooses biggest memory type that has NOT VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
1177 | 948 result.size = size |
949 result.needsTransfer = true | |
1176 | 950 |
951 # find a good memory type | |
952 var physicalProperties: VkPhysicalDeviceMemoryProperties | |
1179 | 953 vkGetPhysicalDeviceMemoryProperties(vulkan.physicalDevice, addr physicalProperties) |
1176 | 954 |
1177 | 955 var biggestHeap: uint64 = 0 |
956 var memoryTypeIndex = high(uint32) | |
1176 | 957 # try to find non-host-visible type |
1177 | 958 for i in 0'u32 ..< physicalProperties.memoryTypeCount: |
959 if not (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT in toEnums(physicalProperties.memoryTypes[i].propertyFlags)): | |
1176 | 960 let size = physicalProperties.memoryHeaps[physicalProperties.memoryTypes[i].heapIndex].size |
961 if size > biggestHeap: | |
1177 | 962 biggestHeap = size |
1176 | 963 memoryTypeIndex = i |
964 | |
965 # If we did not found a device-only memory type, let's just take the biggest overall | |
1177 | 966 if memoryTypeIndex == high(uint32): |
967 result.needsTransfer = false | |
968 for i in 0'u32 ..< physicalProperties.memoryTypeCount: | |
969 let size = physicalProperties.memoryHeaps[physicalProperties.memoryTypes[i].heapIndex].size | |
970 if size > biggestHeap: | |
971 biggestHeap = size | |
972 memoryTypeIndex = i | |
1176 | 973 |
1177 | 974 assert memoryTypeIndex != high(uint32), "Unable to find indirect memory type" |
1176 | 975 var allocationInfo = VkMemoryAllocateInfo( |
976 sType: VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, | |
1177 | 977 allocationSize: result.size, |
1176 | 978 memoryTypeIndex: memoryTypeIndex, |
979 ) | |
980 checkVkResult vkAllocateMemory( | |
1179 | 981 vulkan.device, |
1176 | 982 addr allocationInfo, |
983 nil, | |
984 addr result.vk | |
985 ) | |
986 | |
1179 | 987 proc AllocateDirectMemory(size: uint64): DirectGPUMemory = |
1177 | 988 result.size = size |
989 result.needsFlush = true | |
1176 | 990 |
991 # find a good memory type | |
992 var physicalProperties: VkPhysicalDeviceMemoryProperties | |
1179 | 993 vkGetPhysicalDeviceMemoryProperties(vulkan.physicalDevice, addr physicalProperties) |
1164 | 994 |
1177 | 995 var biggestHeap: uint64 = 0 |
996 var memoryTypeIndex = high(uint32) | |
1176 | 997 # try to find host-visible type |
998 for i in 0 ..< physicalProperties.memoryTypeCount: | |
1177 | 999 let flags = toEnums(physicalProperties.memoryTypes[i].propertyFlags) |
1000 if VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT in flags: | |
1176 | 1001 let size = physicalProperties.memoryHeaps[physicalProperties.memoryTypes[i].heapIndex].size |
1002 if size > biggestHeap: | |
1177 | 1003 biggestHeap = size |
1176 | 1004 memoryTypeIndex = i |
1177 | 1005 result.needsFlush = not (VK_MEMORY_PROPERTY_HOST_COHERENT_BIT in flags) |
1164 | 1006 |
1177 | 1007 assert memoryTypeIndex != high(uint32), "Unable to find indirect memory type" |
1176 | 1008 var allocationInfo = VkMemoryAllocateInfo( |
1009 sType: VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, | |
1177 | 1010 allocationSize: result.size, |
1179 | 1011 memoryTypeIndex: GetDirectMemoryTypeIndex(), |
1176 | 1012 ) |
1013 checkVkResult vkAllocateMemory( | |
1179 | 1014 vulkan.device, |
1176 | 1015 addr allocationInfo, |
1016 nil, | |
1017 addr result.vk | |
1018 ) | |
1177 | 1019 checkVkResult vkMapMemory( |
1179 | 1020 device = vulkan.device, |
1176 | 1021 memory = result.vk, |
1022 offset = 0'u64, | |
1023 size = result.size, | |
1024 flags = VkMemoryMapFlags(0), | |
1025 ppData = addr(result.data) | |
1026 ) | |
1027 | |
1179 | 1028 proc AllocateIndirectBuffer(renderData: var RenderData, size: uint64, btype: BufferType) = |
1029 if size == 0: | |
1030 return | |
1177 | 1031 var buffer = Buffer[IndirectGPUMemory](size: size) |
1032 | |
1178 | 1033 let usageFlags = case btype: |
1034 of VertexBuffer: [VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_BUFFER_USAGE_TRANSFER_DST_BIT] | |
1035 of IndexBuffer: [VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_BUFFER_USAGE_TRANSFER_DST_BIT] | |
1036 of UniformBuffer: [VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_BUFFER_USAGE_TRANSFER_DST_BIT] | |
1037 | |
1177 | 1038 # iterate through memory areas to find big enough free space |
1179 | 1039 # TODO: dynamically expand memory allocations |
1040 for (memory, usedOffset) in renderData.indirectMemory.mitems: | |
1041 if memory.size - usedOffset >= size: | |
1042 buffer.offset = usedOffset | |
1177 | 1043 # create buffer |
1044 var createInfo = VkBufferCreateInfo( | |
1045 sType: VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, | |
1046 flags: VkBufferCreateFlags(0), | |
1047 size: buffer.size, | |
1178 | 1048 usage: toBits(usageFlags), |
1177 | 1049 sharingMode: VK_SHARING_MODE_EXCLUSIVE, |
1050 ) | |
1051 checkVkResult vkCreateBuffer( | |
1179 | 1052 device = vulkan.device, |
1177 | 1053 pCreateInfo = addr createInfo, |
1054 pAllocator = nil, | |
1055 pBuffer = addr(buffer.vk) | |
1056 ) | |
1179 | 1057 checkVkResult vkBindBufferMemory(vulkan.device, buffer.vk, memory.vk, buffer.offset) |
1178 | 1058 renderData.indirectBuffers.add (buffer, btype, 0'u64) |
1177 | 1059 # update memory area offset |
1179 | 1060 usedOffset = alignedTo(usedOffset + size, MEMORY_ALIGNMENT) |
1177 | 1061 return |
1062 | |
1063 assert false, "Did not find allocated memory region with enough space" | |
1064 | |
1179 | 1065 proc AllocateDirectBuffer(renderData: var RenderData, size: uint64, btype: BufferType) = |
1066 if size == 0: | |
1067 return | |
1068 | |
1177 | 1069 var buffer = Buffer[DirectGPUMemory](size: size) |
1070 | |
1178 | 1071 let usageFlags = case btype: |
1072 of VertexBuffer: [VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_BUFFER_USAGE_TRANSFER_DST_BIT] | |
1073 of IndexBuffer: [VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_BUFFER_USAGE_TRANSFER_DST_BIT] | |
1074 of UniformBuffer: [VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_BUFFER_USAGE_TRANSFER_DST_BIT] | |
1075 | |
1177 | 1076 # iterate through memory areas to find big enough free space |
1179 | 1077 # TODO: dynamically expand memory allocations |
1078 for (memory, usedOffset) in renderData.directMemory.mitems: | |
1079 if memory.size - usedOffset >= size: | |
1080 buffer.offset = usedOffset | |
1177 | 1081 # create buffer |
1082 var createInfo = VkBufferCreateInfo( | |
1083 sType: VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, | |
1084 flags: VkBufferCreateFlags(0), | |
1085 size: buffer.size, | |
1178 | 1086 usage: toBits(usageFlags), |
1177 | 1087 sharingMode: VK_SHARING_MODE_EXCLUSIVE, |
1088 ) | |
1089 checkVkResult vkCreateBuffer( | |
1179 | 1090 device = vulkan.device, |
1177 | 1091 pCreateInfo = addr createInfo, |
1092 pAllocator = nil, | |
1093 pBuffer = addr(buffer.vk) | |
1094 ) | |
1179 | 1095 checkVkResult vkBindBufferMemory(vulkan.device, buffer.vk, memory.vk, buffer.offset) |
1178 | 1096 renderData.directBuffers.add (buffer, btype, 0'u64) |
1177 | 1097 # update memory area offset |
1179 | 1098 usedOffset = alignedTo(usedOffset + size, MEMORY_ALIGNMENT) |
1177 | 1099 return |
1100 | |
1101 assert false, "Did not find allocated memory region with enough space" | |
1102 | |
1179 | 1103 proc InitRenderData(descriptorPoolLimit = 1024'u32): RenderData = |
1176 | 1104 # allocate descriptor pools |
1105 var poolSizes = [ | |
1177 | 1106 VkDescriptorPoolSize(thetype: VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, descriptorCount: descriptorPoolLimit), |
1107 VkDescriptorPoolSize(thetype: VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, descriptorCount: descriptorPoolLimit), | |
1176 | 1108 ] |
1109 var poolInfo = VkDescriptorPoolCreateInfo( | |
1110 sType: VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, | |
1111 poolSizeCount: poolSizes.len.uint32, | |
1112 pPoolSizes: poolSizes.ToCPointer, | |
1113 maxSets: descriptorPoolLimit, | |
1114 ) | |
1179 | 1115 checkVkResult vkCreateDescriptorPool(vulkan.device, addr(poolInfo), nil, addr(result.descriptorPool)) |
1176 | 1116 |
1117 # allocate some memory | |
1181 | 1118 var initialAllocationSize = 1_000_000_000'u64 # TODO: make this more dynamic or something? |
1179 | 1119 result.indirectMemory = @[(memory: AllocateIndirectMemory(size = initialAllocationSize), usedOffset: 0'u64)] |
1120 result.directMemory = @[(memory: AllocateDirectMemory(size = initialAllocationSize), usedOffset: 0'u64)] | |
1121 | |
1122 proc FlushDirectMemory(renderData: RenderData) = | |
1123 var flushRegions = newSeqOfCap[VkMappedMemoryRange](renderData.directMemory.len) | |
1124 for entry in renderData.directMemory: | |
1125 if entry.usedOffset > 0: | |
1126 flushRegions.add VkMappedMemoryRange( | |
1127 sType: VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, | |
1128 memory: entry.memory.vk, | |
1129 size: entry.usedOffset, | |
1130 ) | |
1131 if flushRegions.len > 0: | |
1132 checkVkResult vkFlushMappedMemoryRanges(vulkan.device, flushRegions.len.uint32, flushRegions.ToCPointer()) | |
1164 | 1133 |
1178 | 1134 # For the Get*BufferSize: |
1135 # BUFFER_ALIGNMENT is just added for a rough estimate, to ensure we have enough space to align when binding | |
1177 | 1136 proc GetIndirectBufferSizes[T](data: T): uint64 = |
1137 for name, value in fieldPairs(data): | |
1178 | 1138 when not hasCustomPragma(value, VertexIndices): |
1139 when typeof(value) is GPUData: | |
1140 when UsesIndirectMemory(value): | |
1141 result += value.size + BUFFER_ALIGNMENT | |
1182 | 1142 proc GetIndirectBufferSizes(data: DescriptorSet): uint64 = |
1143 GetIndirectBufferSizes(data.data) | |
1177 | 1144 proc GetDirectBufferSizes[T](data: T): uint64 = |
1145 for name, value in fieldPairs(data): | |
1178 | 1146 when not hasCustomPragma(value, VertexIndices): |
1147 when typeof(value) is GPUData: | |
1148 when UsesDirectMemory(value): | |
1149 result += value.size + BUFFER_ALIGNMENT | |
1182 | 1150 proc GetDirectBufferSizes(data: DescriptorSet): uint64 = |
1151 GetDirectBufferSizes(data.data) | |
1177 | 1152 proc GetIndirectIndexBufferSizes[T](data: T): uint64 = |
1153 for name, value in fieldPairs(data): | |
1154 when hasCustomPragma(value, VertexIndices): | |
1155 static: assert typeof(value) is GPUArray, "Index buffers must be of type GPUArray" | |
1156 static: assert elementType(value.data) is uint8 or elementType(value.data) is uint16 or elementType(value.data) is uint32 | |
1178 | 1157 when UsesIndirectMemory(value): |
1158 result += value.size + BUFFER_ALIGNMENT | |
1177 | 1159 proc GetDirectIndexBufferSizes[T](data: T): uint64 = |
1160 for name, value in fieldPairs(data): | |
1161 when hasCustomPragma(value, VertexIndices): | |
1162 static: assert typeof(value) is GPUArray, "Index buffers must be of type GPUArray" | |
1163 static: assert elementType(value.data) is uint8 or elementType(value.data) is uint16 or elementType(value.data) is uint32 | |
1178 | 1164 when UsesDirectMemory(value): |
1165 result += value.size + BUFFER_ALIGNMENT | |
1177 | 1166 |
1179 | 1167 proc AssignIndirectBuffers[T](renderdata: var RenderData, btype: BufferType, data: var T) = |
1178 | 1168 for name, value in fieldPairs(data): |
1169 when typeof(value) is GPUData: | |
1170 when UsesIndirectMemory(value): | |
1171 # find next buffer of correct type with enough free space | |
1179 | 1172 if btype == IndexBuffer == value.hasCustomPragma(VertexIndices): |
1173 var foundBuffer = false | |
1174 for (buffer, bt, offset) in renderData.indirectBuffers.mitems: | |
1175 if bt == btype and buffer.size - offset >= value.size: | |
1176 assert not value.buffer.vk.Valid, "GPUData-Buffer has already been assigned" | |
1177 assert buffer.vk.Valid, "RenderData-Buffer has not yet been created" | |
1178 value.buffer = buffer | |
1179 value.offset = offset | |
1180 offset = alignedTo(offset + value.size, BUFFER_ALIGNMENT) | |
1181 foundBuffer = true | |
1182 break | |
1183 assert foundBuffer, &"Unable to find large enough '{btype}' for '{data}'" | |
1182 | 1184 proc AssignIndirectBuffers(renderdata: var RenderData, btype: BufferType, data: var DescriptorSet) = |
1185 AssignIndirectBuffers(renderdata, btype, data.data) | |
1179 | 1186 proc AssignDirectBuffers[T](renderdata: var RenderData, btype: BufferType, data: var T) = |
1178 | 1187 for name, value in fieldPairs(data): |
1188 when typeof(value) is GPUData: | |
1189 when UsesDirectMemory(value): | |
1190 # find next buffer of correct type with enough free space | |
1179 | 1191 if btype == IndexBuffer == value.hasCustomPragma(VertexIndices): |
1192 var foundBuffer = false | |
1193 for (buffer, bt, offset) in renderData.directBuffers.mitems: | |
1194 if bt == btype and buffer.size - offset >= value.size: | |
1195 assert not value.buffer.vk.Valid, "GPUData-Buffer has already been assigned" | |
1196 assert buffer.vk.Valid, "RenderData-Buffer has not yet been created" | |
1197 value.buffer = buffer | |
1198 value.offset = offset | |
1199 offset = alignedTo(offset + value.size, BUFFER_ALIGNMENT) | |
1200 foundBuffer = true | |
1201 break | |
1202 assert foundBuffer, &"Unable to find large enough '{btype}' for '{data}'" | |
1182 | 1203 proc AssignDirectBuffers(renderdata: var RenderData, btype: BufferType, data: var DescriptorSet) = |
1204 AssignDirectBuffers(renderdata, btype, data.data) | |
1177 | 1205 |
1179 | 1206 proc HasGPUValueField[T](name: static string): bool {.compileTime.} = |
1207 for fieldname, value in default(T).fieldPairs(): | |
1208 when typeof(value) is GPUValue and fieldname == name: return true | |
1209 return false | |
1210 | |
1211 template WithGPUValueField(obj: object, name: static string, fieldvalue, body: untyped): untyped = | |
1212 # HasGPUValueField MUST be used to check if this is supported | |
1213 for fieldname, value in obj.fieldPairs(): | |
1214 when fieldname == name: | |
1215 block: | |
1216 let `fieldvalue` {.inject.} = value | |
1217 body | |
1218 | |
1172 | 1219 proc Bind[T](pipeline: Pipeline[T], commandBuffer: VkCommandBuffer, currentFrameInFlight: int) = |
1182 | 1220 commandBuffer.vkCmdBindPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.vk) |
1177 | 1221 #[ |
1222 commandBuffer.vkCmdBindDescriptorSets( | |
1223 VK_PIPELINE_BIND_POINT_GRAPHICS, | |
1224 pipeline.layout, | |
1225 0, | |
1226 1, | |
1227 addr pipeline.descriptorSets[currentFrameInFlight], | |
1228 0, | |
1229 nil, | |
1230 ) | |
1231 ]# | |
1161 | 1232 |
1182 | 1233 proc AssertCompatible(TShader, TMesh, TInstance, TGlobals, TMaterial: typedesc) = |
1181 | 1234 var descriptorSetCount = 0 |
1235 | |
1182 | 1236 for shaderAttributeName, shaderAttribute in default(TShader).fieldPairs: |
1161 | 1237 var foundField = false |
1176 | 1238 |
1239 # Vertex input data | |
1182 | 1240 when hasCustomPragma(shaderAttribute, VertexAttribute): |
1241 assert typeof(shaderAttribute) is SupportedGPUType | |
1161 | 1242 for meshName, meshValue in default(TMesh).fieldPairs: |
1182 | 1243 when meshName == shaderAttributeName: |
1176 | 1244 assert meshValue is GPUArray, "Mesh attribute '" & meshName & "' must be of type 'GPUArray' but is of type " & tt.name(typeof(meshValue)) |
1182 | 1245 assert foundField == false, "Shader input '" & tt.name(TShader) & "." & shaderAttributeName & "' has been found more than once" |
1246 assert elementType(meshValue.data) is typeof(shaderAttribute), "Shader input " & tt.name(TShader) & "." & shaderAttributeName & " is of type '" & tt.name(typeof(shaderAttribute)) & "' but mesh attribute is of type '" & tt.name(elementType(meshValue.data)) & "'" | |
1161 | 1247 foundField = true |
1182 | 1248 assert foundField, "Shader input '" & tt.name(TShader) & "." & shaderAttributeName & ": " & tt.name(typeof(shaderAttribute)) & "' not found in '" & tt.name(TMesh) & "'" |
1176 | 1249 |
1250 # Instance input data | |
1182 | 1251 elif hasCustomPragma(shaderAttribute, InstanceAttribute): |
1252 assert typeof(shaderAttribute) is SupportedGPUType | |
1161 | 1253 for instanceName, instanceValue in default(TInstance).fieldPairs: |
1182 | 1254 when instanceName == shaderAttributeName: |
1176 | 1255 assert instanceValue is GPUArray, "Instance attribute '" & instanceName & "' must be of type 'GPUArray' but is of type " & tt.name(typeof(instanceName)) |
1182 | 1256 assert foundField == false, "Shader input '" & tt.name(TShader) & "." & shaderAttributeName & "' has been found more than once" |
1257 assert elementType(instanceValue.data) is typeof(shaderAttribute), "Shader input " & tt.name(TShader) & "." & shaderAttributeName & " is of type '" & tt.name(typeof(shaderAttribute)) & "' but instance attribute is of type '" & tt.name(elementType(instanceValue.data)) & "'" | |
1161 | 1258 foundField = true |
1182 | 1259 assert foundField, "Shader input '" & tt.name(TShader) & "." & shaderAttributeName & ": " & tt.name(typeof(shaderAttribute)) & "' not found in '" & tt.name(TInstance) & "'" |
1260 | |
1261 # descriptors | |
1262 elif typeof(shaderAttribute) is DescriptorSet: | |
1263 assert descriptorSetCount <= DescriptorSetType.high.int, &"{tt.name(TShader)}: maximum {DescriptorSetType.high} allowed" | |
1264 descriptorSetCount.inc | |
1176 | 1265 |
1181 | 1266 |
1182 | 1267 when shaderAttribute.sType == GlobalSet: |
1268 assert shaderAttribute.sType == default(TGlobals).sType, "Shader has global descriptor set of type '" & $shaderAttribute.sType & "' but matching provided type is '" & $default(TGlobals).sType & "'" | |
1269 assert typeof(shaderAttribute) is TGlobals, "Shader has global descriptor set type '" & tt.name(get(genericParams(typeof(shaderAttribute)), 0)) & "' but provided type is " & tt.name(TGlobals) | |
1270 elif shaderAttribute.sType == MaterialSet: | |
1271 assert shaderAttribute.sType == default(TMaterial).sType, "Shader has material descriptor set of type '" & $shaderAttribute.sType & "' but matching provided type is '" & $default(TMaterial).sType & "'" | |
1272 assert typeof(shaderAttribute) is TMaterial, "Shader has materialdescriptor type '" & tt.name(get(genericParams(typeof(shaderAttribute)), 0)) & "' but provided type is " & tt.name(TMaterial) | |
1181 | 1273 |
1274 | |
1182 | 1275 proc Render[TShader, TGlobals, TMaterial, TMesh, TInstance]( |
1178 | 1276 commandBuffer: VkCommandBuffer, |
1162 | 1277 pipeline: Pipeline[TShader], |
1182 | 1278 globalSet: TGlobals, |
1279 materialSet: TMaterial, | |
1178 | 1280 mesh: TMesh, |
1281 instances: TInstance, | |
1161 | 1282 ) = |
1182 | 1283 static: AssertCompatible(TShader, TMesh, TInstance, TGlobals, TMaterial) |
1178 | 1284 #[ |
1164 | 1285 if renderable.vertexBuffers.len > 0: |
1286 commandBuffer.vkCmdBindVertexBuffers( | |
1287 firstBinding = 0'u32, | |
1288 bindingCount = uint32(renderable.vertexBuffers.len), | |
1289 pBuffers = renderable.vertexBuffers.ToCPointer(), | |
1290 pOffsets = renderable.bufferOffsets.ToCPointer() | |
1291 ) | |
1161 | 1292 if renderable.indexType != None: |
1159 | 1293 commandBuffer.vkCmdBindIndexBuffer( |
1294 renderable.indexBuffer, | |
1295 renderable.indexBufferOffset, | |
1161 | 1296 renderable.indexType, |
1159 | 1297 ) |
1298 commandBuffer.vkCmdDrawIndexed( | |
1161 | 1299 indexCount = renderable.indexCount, |
1300 instanceCount = renderable.instanceCount, | |
1159 | 1301 firstIndex = 0, |
1302 vertexOffset = 0, | |
1303 firstInstance = 0 | |
1304 ) | |
1305 else: | |
1306 commandBuffer.vkCmdDraw( | |
1161 | 1307 vertexCount = renderable.vertexCount, |
1308 instanceCount = renderable.instanceCount, | |
1159 | 1309 firstVertex = 0, |
1310 firstInstance = 0 | |
1311 ) | |
1178 | 1312 ]# |
1161 | 1313 |
1314 when isMainModule: | |
1162 | 1315 import semicongine/platform/window |
1316 import semicongine/vulkan/instance | |
1317 import semicongine/vulkan/device | |
1318 import semicongine/vulkan/physicaldevice | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
1319 import std/options |
1162 | 1320 |
1161 | 1321 type |
1177 | 1322 MeshA = object |
1323 position: GPUArray[Vec3f, IndirectGPUMemory] | |
1324 indices {.VertexIndices.}: GPUArray[uint16, IndirectGPUMemory] | |
1325 InstanceA = object | |
1326 rotation: GPUArray[Vec4f, IndirectGPUMemory] | |
1327 objPosition: GPUArray[Vec3f, IndirectGPUMemory] | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
1328 MaterialA = object |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
1329 reflection: float32 |
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
1330 baseColor: Vec3f |
1176 | 1331 UniformsA = object |
1180 | 1332 defaultTexture: Texture |
1333 defaultMaterial: GPUValue[MaterialA, IndirectGPUMemory] | |
1176 | 1334 materials: GPUValue[array[3, MaterialA], IndirectGPUMemory] |
1335 materialTextures: array[3, Texture] | |
1177 | 1336 ShaderSettings = object |
1180 | 1337 gamma: float32 |
1176 | 1338 GlobalsA = object |
1162 | 1339 fontAtlas: Texture |
1176 | 1340 settings: GPUValue[ShaderSettings, IndirectGPUMemory] |
1161 | 1341 |
1162 | 1342 ShaderA = object |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
1343 # vertex input |
1161 | 1344 position {.VertexAttribute.}: Vec3f |
1176 | 1345 objPosition {.InstanceAttribute.}: Vec3f |
1346 rotation {.InstanceAttribute.}: Vec4f | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
1347 # intermediate |
1162 | 1348 test {.Pass.}: float32 |
1349 test1 {.PassFlat.}: Vec3f | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
1350 # output |
1162 | 1351 color {.ShaderOutput.}: Vec4f |
1180 | 1352 # descriptor sets |
1182 | 1353 globals: DescriptorSet[GlobalsA, GlobalSet] |
1354 uniforms: DescriptorSet[UniformsA, MaterialSet] | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
1355 # code |
1162 | 1356 vertexCode: string = "void main() {}" |
1357 fragmentCode: string = "void main() {}" | |
1161 | 1358 |
1162 | 1359 let w = CreateWindow("test2") |
1360 putEnv("VK_LAYER_ENABLES", "VALIDATION_CHECK_ENABLE_VENDOR_SPECIFIC_AMD,VALIDATION_CHECK_ENABLE_VENDOR_SPECIFIC_NVIDIA,VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXTVK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT,VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT") | |
1179 | 1361 |
1362 # TODO: remove those ugly wrappers | |
1363 let theInstance = w.CreateInstance( | |
1162 | 1364 vulkanVersion = VK_MAKE_API_VERSION(0, 1, 3, 0), |
1365 instanceExtensions = @[], | |
1366 layers = @["VK_LAYER_KHRONOS_validation"], | |
1367 ) | |
1368 | |
1179 | 1369 let dev = theInstance.CreateDevice( |
1370 theInstance.GetPhysicalDevices().FilterBestGraphics(), | |
1162 | 1371 enabledExtensions = @[], |
1179 | 1372 theInstance.GetPhysicalDevices().FilterBestGraphics().FilterForGraphicsPresentationQueues() |
1373 ).vk | |
1173 | 1374 let frameWidth = 100'u32 |
1375 let frameHeight = 100'u32 | |
1162 | 1376 |
1179 | 1377 # TODO: pack this stuff into a setup method and condense everything a bit |
1378 let pDevice = theInstance.vk.GetPhysicalDevice() | |
1379 let qfi = pDevice.GetQueueFamily(VK_QUEUE_GRAPHICS_BIT) | |
1380 vulkan = VulkanGlobals( | |
1381 instance: theInstance.vk, | |
1382 device: dev, | |
1383 physicalDevice: pDevice, | |
1384 queueFamilyIndex: qfi, | |
1385 queue: dev.GetQueue(qfi, VK_QUEUE_GRAPHICS_BIT) | |
1386 ) | |
1387 | |
1176 | 1388 var myMesh1 = MeshA( |
1389 position: GPUArray[Vec3f, IndirectGPUMemory](data: @[NewVec3f(0, 0, ), NewVec3f(0, 0, ), NewVec3f(0, 0, )]), | |
1390 ) | |
1182 | 1391 var uniforms1 = DescriptorSet[UniformsA, MaterialSet]( |
1392 data: UniformsA( | |
1393 materials: GPUValue[array[3, MaterialA], IndirectGPUMemory](data: [ | |
1394 MaterialA(reflection: 0, baseColor: NewVec3f(1, 0, 0)), | |
1395 MaterialA(reflection: 0.1, baseColor: NewVec3f(0, 1, 0)), | |
1396 MaterialA(reflection: 0.5, baseColor: NewVec3f(0, 0, 1)), | |
1176 | 1397 ]), |
1398 materialTextures: [ | |
1399 Texture(isGrayscale: false, colorImage: Image[RGBAPixel](width: 1, height: 1, imagedata: @[[255'u8, 0'u8, 0'u8, 255'u8]])), | |
1400 Texture(isGrayscale: false, colorImage: Image[RGBAPixel](width: 1, height: 1, imagedata: @[[0'u8, 255'u8, 0'u8, 255'u8]])), | |
1401 Texture(isGrayscale: false, colorImage: Image[RGBAPixel](width: 1, height: 1, imagedata: @[[0'u8, 0'u8, 255'u8, 255'u8]])), | |
1402 ] | |
1403 ) | |
1182 | 1404 ) |
1176 | 1405 var instances1 = InstanceA( |
1406 rotation: GPUArray[Vec4f, IndirectGPUMemory](data: @[NewVec4f(1, 0, 0, 0.1), NewVec4f(0, 1, 0, 0.1)]), | |
1407 objPosition: GPUArray[Vec3f, IndirectGPUMemory](data: @[NewVec3f(0, 0, 0), NewVec3f(1, 1, 1)]), | |
1408 ) | |
1182 | 1409 var myGlobals = DescriptorSet[GlobalsA, GlobalSet]() |
1173 | 1410 |
1411 # setup for rendering (TODO: swapchain & framebuffers) | |
1179 | 1412 let renderpass = CreateRenderPass(GetSurfaceFormat()) |
1173 | 1413 |
1414 # shaders | |
1415 const shader = ShaderA() | |
1179 | 1416 let shaderObject = CompileShader(shader) |
1417 var pipeline1 = CreatePipeline(renderPass = renderpass, shader = shaderObject) | |
1176 | 1418 |
1179 | 1419 var renderdata = InitRenderData() |
1176 | 1420 |
1179 | 1421 # TODO: Textures |
1177 | 1422 # upload all textures |
1423 # write descriptors for textures and uniform buffers | |
1161 | 1424 |
1178 | 1425 # buffer allocation |
1177 | 1426 var |
1427 indirectVertexSizes = 0'u64 | |
1428 directVertexSizes = 0'u64 | |
1429 indirectIndexSizes = 0'u64 | |
1430 directIndexSizes = 0'u64 | |
1431 indirectUniformSizes = 0'u64 | |
1432 directUniformSizes = 0'u64 | |
1433 | |
1179 | 1434 # buffer allocation |
1435 | |
1436 echo "Allocating GPU buffers" | |
1177 | 1437 indirectVertexSizes += GetIndirectBufferSizes(myMesh1) |
1438 indirectVertexSizes += GetIndirectBufferSizes(instances1) | |
1179 | 1439 AllocateIndirectBuffer(renderdata, indirectVertexSizes, VertexBuffer) |
1177 | 1440 |
1441 directVertexSizes += GetDirectBufferSizes(myMesh1) | |
1442 directVertexSizes += GetDirectBufferSizes(instances1) | |
1179 | 1443 AllocateDirectBuffer(renderdata, directVertexSizes, VertexBuffer) |
1177 | 1444 |
1445 indirectIndexSizes += GetIndirectIndexBufferSizes(myMesh1) | |
1179 | 1446 AllocateIndirectBuffer(renderdata, indirectIndexSizes, IndexBuffer) |
1177 | 1447 |
1448 directIndexSizes += GetDirectIndexBufferSizes(myMesh1) | |
1179 | 1449 AllocateDirectBuffer(renderdata, directIndexSizes, IndexBuffer) |
1177 | 1450 |
1451 indirectUniformSizes += GetIndirectBufferSizes(uniforms1) | |
1452 indirectUniformSizes += GetIndirectBufferSizes(myGlobals) | |
1179 | 1453 AllocateIndirectBuffer(renderdata, indirectUniformSizes, UniformBuffer) |
1177 | 1454 |
1455 directUniformSizes += GetDirectBufferSizes(uniforms1) | |
1456 directUniformSizes += GetDirectBufferSizes(myGlobals) | |
1179 | 1457 AllocateDirectBuffer(renderdata, directUniformSizes, UniformBuffer) |
1178 | 1458 |
1459 # buffer assignment | |
1179 | 1460 # |
1461 echo "Assigning buffers to GPUData fields" | |
1178 | 1462 |
1179 | 1463 # for meshes we do: |
1464 renderdata.AssignIndirectBuffers(VertexBuffer, myMesh1) | |
1465 renderdata.AssignDirectBuffers(VertexBuffer, myMesh1) | |
1466 renderdata.AssignIndirectBuffers(IndexBuffer, myMesh1) | |
1467 renderdata.AssignDirectBuffers(IndexBuffer, myMesh1) | |
1468 | |
1469 # for instances we do: | |
1470 renderdata.AssignIndirectBuffers(VertexBuffer, instances1) | |
1471 renderdata.AssignDirectBuffers(VertexBuffer, instances1) | |
1178 | 1472 |
1179 | 1473 # for uniforms/globals we do: |
1474 renderdata.AssignIndirectBuffers(UniformBuffer, uniforms1) | |
1475 renderdata.AssignDirectBuffers(UniformBuffer, uniforms1) | |
1476 renderdata.AssignIndirectBuffers(UniformBuffer, myGlobals) | |
1477 renderdata.AssignDirectBuffers(UniformBuffer, myGlobals) | |
1478 | |
1479 # buffer filling | |
1178 | 1480 |
1179 | 1481 echo "Copying all data to GPU memory" |
1482 | |
1483 # copy everything to GPU | |
1484 UpdateAllGPUBuffers(myMesh1) | |
1485 UpdateAllGPUBuffers(instances1) | |
1486 UpdateAllGPUBuffers(uniforms1) | |
1487 UpdateAllGPUBuffers(myGlobals) | |
1488 renderdata.FlushDirectMemory() | |
1177 | 1489 |
1180 | 1490 |
1173 | 1491 # descriptors |
1181 | 1492 # TODO: I think we can write and assign descriptors directly after creation |
1182 | 1493 InitDescriptorSet(renderdata, pipeline1.descriptorSetLayouts[GlobalSet], myGlobals) |
1494 InitDescriptorSet(renderdata, pipeline1.descriptorSetLayouts[MaterialSet], uniforms1) | |
1180 | 1495 # WriteDescriptors[ShaderA, UniformsA, GlobalsA](renderdata, uniforms1, myGlobals) |
1179 | 1496 |
1497 | |
1173 | 1498 # command buffer |
1499 var | |
1500 commandBufferPool: VkCommandPool | |
1501 createInfo = VkCommandPoolCreateInfo( | |
1502 sType: VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, | |
1503 flags: toBits [VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT], | |
1179 | 1504 queueFamilyIndex: vulkan.queueFamilyIndex, |
1173 | 1505 ) |
1179 | 1506 checkVkResult vkCreateCommandPool(vulkan.device, addr createInfo, nil, addr commandBufferPool) |
1178 | 1507 var |
1508 cmdBuffers: array[INFLIGHTFRAMES.int, VkCommandBuffer] | |
1509 allocInfo = VkCommandBufferAllocateInfo( | |
1510 sType: VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, | |
1511 commandPool: commandBufferPool, | |
1512 level: VK_COMMAND_BUFFER_LEVEL_PRIMARY, | |
1513 commandBufferCount: INFLIGHTFRAMES, | |
1514 ) | |
1179 | 1515 checkVkResult vkAllocateCommandBuffers(vulkan.device, addr allocInfo, cmdBuffers.ToCPointer) |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
1516 |
1173 | 1517 # start command buffer |
1518 block: | |
1519 let | |
1520 currentFramebuffer = VkFramebuffer(0) # TODO | |
1521 currentFrameInFlight = 1 | |
1522 cmd = cmdBuffers[currentFrameInFlight] | |
1523 beginInfo = VkCommandBufferBeginInfo( | |
1524 sType: VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, | |
1525 flags: VkCommandBufferUsageFlags(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT), | |
1526 ) | |
1527 checkVkResult cmd.vkResetCommandBuffer(VkCommandBufferResetFlags(0)) | |
1528 checkVkResult cmd.vkBeginCommandBuffer(addr(beginInfo)) | |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
1529 |
1173 | 1530 # start renderpass |
1531 block: | |
1532 var | |
1533 clearColors = [VkClearValue(color: VkClearColorValue(float32: [0, 0, 0, 0]))] | |
1534 renderPassInfo = VkRenderPassBeginInfo( | |
1535 sType: VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, | |
1536 renderPass: renderpass, | |
1178 | 1537 framebuffer: currentFramebuffer, # TODO |
1173 | 1538 renderArea: VkRect2D( |
1539 offset: VkOffset2D(x: 0, y: 0), | |
1540 extent: VkExtent2D(width: frameWidth, height: frameHeight), | |
1541 ), | |
1542 clearValueCount: uint32(clearColors.len), | |
1543 pClearValues: clearColors.ToCPointer(), | |
1544 ) | |
1545 viewport = VkViewport( | |
1546 x: 0.0, | |
1547 y: 0.0, | |
1548 width: frameWidth.float32, | |
1549 height: frameHeight.float32, | |
1550 minDepth: 0.0, | |
1551 maxDepth: 1.0, | |
1552 ) | |
1553 scissor = VkRect2D( | |
1554 offset: VkOffset2D(x: 0, y: 0), | |
1555 extent: VkExtent2D(width: frameWidth, height: frameHeight) | |
1556 ) | |
1179 | 1557 vkCmdBeginRenderPass(cmd, addr(renderPassInfo), VK_SUBPASS_CONTENTS_INLINE) |
1163
438d32d8b14f
add: more static compilation stuff, code is getting a bit crazy, but also super nice API
sam <sam@basx.dev>
parents:
1162
diff
changeset
|
1558 |
1173 | 1559 # setup viewport |
1560 vkCmdSetViewport(cmd, firstViewport = 0, viewportCount = 1, addr(viewport)) | |
1561 vkCmdSetScissor(cmd, firstScissor = 0, scissorCount = 1, addr(scissor)) | |
1562 | |
1563 # bind pipeline, will be loop | |
1564 block: | |
1565 Bind(pipeline1, cmd, currentFrameInFlight = currentFrameInFlight) | |
1566 | |
1567 # render object, will be loop | |
1568 block: | |
1182 | 1569 Render(cmd, pipeline1, myGlobals, uniforms1, myMesh1, instances1) |
1173 | 1570 |
1571 vkCmdEndRenderPass(cmd) | |
1572 checkVkResult cmd.vkEndCommandBuffer() |