-
Notifications
You must be signed in to change notification settings - Fork 6
/
17_vertex_input.py
846 lines (647 loc) · 27.7 KB
/
17_vertex_input.py
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
# -*- coding: UTF-8 -*-
import sys
import array
from vulkan import *
from PySide2 import (QtGui, QtCore)
validationLayers = [
'VK_LAYER_LUNARG_standard_validation'
]
deviceExtensions = [
VK_KHR_SWAPCHAIN_EXTENSION_NAME
]
enableValidationLayers = True
class InstanceProcAddr(object):
T = None
def __init__(self, func):
self.__func = func
def __call__(self, *args, **kwargs):
funcName = self.__func.__name__
func = InstanceProcAddr.procfunc(funcName)
if func:
return func(*args, **kwargs)
else:
return VK_ERROR_EXTENSION_NOT_PRESENT
@staticmethod
def procfunc(funcName):
return vkGetInstanceProcAddr(InstanceProcAddr.T, funcName)
class DeviceProcAddr(InstanceProcAddr):
@staticmethod
def procfunc(funcName):
return vkGetDeviceProcAddr(InstanceProcAddr.T, funcName)
# instance ext functions
@InstanceProcAddr
def vkCreateDebugReportCallbackEXT(instance, pCreateInfo, pAllocator):
pass
@InstanceProcAddr
def vkDestroyDebugReportCallbackEXT(instance, pCreateInfo, pAllocator):
pass
@InstanceProcAddr
def vkCreateWin32SurfaceKHR(instance, pCreateInfo, pAllocator):
pass
@InstanceProcAddr
def vkDestroySurfaceKHR(instance, surface, pAllocator):
pass
@InstanceProcAddr
def vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, queueFamilyIndex, surface):
pass
@InstanceProcAddr
def vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface):
pass
@InstanceProcAddr
def vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface):
pass
@InstanceProcAddr
def vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface):
pass
# device ext functions
@DeviceProcAddr
def vkCreateSwapchainKHR(device, pCreateInfo, pAllocator):
pass
@DeviceProcAddr
def vkDestroySwapchainKHR(device, swapchain, pAllocator):
pass
@DeviceProcAddr
def vkGetSwapchainImagesKHR(device, swapchain):
pass
@DeviceProcAddr
def vkAcquireNextImageKHR(device, swapchain, timeout, semaphore, fence):
pass
@DeviceProcAddr
def vkQueuePresentKHR(queue, pPresentInfo):
pass
def debugCallback(*args):
print('DEBUG: {} {}'.format(args[5], args[6]))
return 0
class Win32misc(object):
@staticmethod
def getInstance(hWnd):
from cffi import FFI as _FFI
_ffi = _FFI()
_ffi.cdef('long __stdcall GetWindowLongA(void* hWnd, int nIndex);')
_lib = _ffi.dlopen('User32.dll')
return _lib.GetWindowLongA(_ffi.cast('void*', hWnd), -6) # GWL_HINSTANCE
class QueueFamilyIndices(object):
def __init__(self):
self.graphicsFamily = -1
self.presentFamily = -1
@property
def isComplete(self):
return self.graphicsFamily >= 0 and self.presentFamily >= 0
class SwapChainSupportDetails(object):
def __init__(self):
self.capabilities = None
self.formats = None
self.presentModes = None
class Vertex(object):
POS = array.array('f', [0, 0])
COLOR = array.array('f', [0, 0, 0])
# def __init__(self):
# self.pos = []
# self.color = []
@staticmethod
def getBindingDescription():
bindingDescription = VkVertexInputBindingDescription(
binding=0,
stride=len(Vertex.POS) * Vertex.POS.itemsize,
inputRate=VK_VERTEX_INPUT_RATE_VERTEX
)
return bindingDescription
@staticmethod
def getAttributeDescriptions():
pos = VkVertexInputAttributeDescription(
location=0,
binding=0,
format=VK_FORMAT_R32G32_SFLOAT,
offset=0
)
color = VkVertexInputAttributeDescription(
location=1,
binding=0,
format=VK_FORMAT_R32G32B32_SFLOAT,
offset=len(Vertex.POS) * Vertex.POS.itemsize,
)
return [pos, color]
class HelloTriangleApplication(QtGui.QWindow):
def __init__(self):
super(HelloTriangleApplication, self).__init__()
self.setWidth(1280)
self.setHeight(720)
self.setMinimumWidth(40)
self.setMinimumHeight(40)
self.setTitle("Vulkan Python - PySide2")
# self.setSurfaceType(self.OpenGLSurface)
self.__instance = None
self.__callbcak = None
self.__surface = None
self.__physicalDevice = None
self.__device = None
self.__graphicQueue = None
self.__presentQueue = None
self.__swapChain = None
self.__swapChainImages = []
self.__swapChainImageFormat = None
self.__swapChainExtent = None
self.__swapChainImageViews = []
self.__swapChainFramebuffers = []
self.__renderpass = None
self.__pipeline = None
self.__pipelineLayout = None
self.__commandPool = None
self.__commandBuffers = []
self.__imageAvailableSemaphore = None
self.__renderFinishedSemaphore = None
self.__vertices = array.array('f', [
# pos color
0, -.5, 1, 0, 0,
.5, .5, 0, 1, 0,
-.5, .5, 0, 0, 1
])
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.drawFrame)
self.initVulkan()
self.timer.start()
def __del__(self):
vkDeviceWaitIdle(self.__device)
if self.__imageAvailableSemaphore:
vkDestroySemaphore(self.__device, self.__imageAvailableSemaphore, None)
if self.__renderFinishedSemaphore:
vkDestroySemaphore(self.__device, self.__renderFinishedSemaphore, None)
self.__cleanupSwapChain()
if self.__commandPool:
vkDestroyCommandPool(self.__device, self.__commandPool, None)
if self.__device:
vkDestroyDevice(self.__device, None)
if self.__callbcak:
vkDestroyDebugReportCallbackEXT(self.__instance, self.__callbcak, None)
if self.__surface:
vkDestroySurfaceKHR(self.__instance, self.__surface, None)
if self.__instance:
vkDestroyInstance(self.__instance, None)
print('instance destroyed')
self.destroy()
def __cleanupSwapChain(self):
[vkDestroyFramebuffer(self.__device, i, None) for i in self.__swapChainFramebuffers]
self.__swapChainFramebuffers = []
vkFreeCommandBuffers(self.__device, self.__commandPool, len(self.__commandBuffers), self.__commandBuffers)
self.__swapChainFramebuffers = []
vkDestroyPipeline(self.__device, self.__pipeline, None)
vkDestroyPipelineLayout(self.__device, self.__pipelineLayout, None)
vkDestroyRenderPass(self.__device, self.__renderpass, None)
[vkDestroyImageView(self.__device, i, None) for i in self.__swapChainImageViews]
self.__swapChainImageViews = []
vkDestroySwapchainKHR(self.__device, self.__swapChain, None)
def __recreateSwapChain(self):
vkDeviceWaitIdle(self.__device)
self.__cleanupSwapChain()
self.__createSwapChain()
self.__createImageViews()
self.__createRenderPass()
self.__createGraphicsPipeline()
self.__createFrambuffers()
self.__createCommandBuffers()
def initVulkan(self):
self.__cretaeInstance()
self.__setupDebugCallback()
self.__createSurface()
self.__pickPhysicalDevice()
self.__createLogicalDevice()
self.__createSwapChain()
self.__createImageViews()
self.__createRenderPass()
self.__createGraphicsPipeline()
self.__createFrambuffers()
self.__createCommandPool()
self.__createCommandBuffers()
self.__createSemaphores()
def __cretaeInstance(self):
if enableValidationLayers and not self.__checkValidationLayerSupport():
raise Exception("validation layers requested, but not available!")
appInfo = VkApplicationInfo(
# sType=VK_STRUCTURE_TYPE_APPLICATION_INFO,
pApplicationName='Python VK',
applicationVersion=VK_MAKE_VERSION(1, 0, 0),
pEngineName='pyvulkan',
engineVersion=VK_MAKE_VERSION(1, 0, 0),
apiVersion=VK_API_VERSION
)
extenstions = self.__getRequiredExtensions()
if enableValidationLayers:
instanceInfo = VkInstanceCreateInfo(
pApplicationInfo=appInfo,
# enabledLayerCount=len(validationLayers),
ppEnabledLayerNames=validationLayers,
# enabledExtensionCount=len(extenstions),
ppEnabledExtensionNames=extenstions
)
else:
instanceInfo = VkInstanceCreateInfo(
pApplicationInfo=appInfo,
enabledLayerCount=0,
# enabledExtensionCount=len(extenstions),
ppEnabledExtensionNames=extenstions
)
self.__instance = vkCreateInstance(instanceInfo, None)
InstanceProcAddr.T = self.__instance
def __setupDebugCallback(self):
if not enableValidationLayers:
return
createInfo = VkDebugReportCallbackCreateInfoEXT(
flags=VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_ERROR_BIT_EXT,
pfnCallback=debugCallback
)
self.__callbcak = vkCreateDebugReportCallbackEXT(self.__instance, createInfo, None)
def __createSurface(self):
if sys.platform == 'win32':
hwnd = self.winId()
hinstance = Win32misc.getInstance(hwnd)
createInfo = VkWin32SurfaceCreateInfoKHR(
hinstance=hinstance,
hwnd=hwnd
)
self.__surface = vkCreateWin32SurfaceKHR(self.__instance, createInfo, None)
# elif sys.platform == 'linux':
# pass
def __pickPhysicalDevice(self):
physicalDevices = vkEnumeratePhysicalDevices(self.__instance)
for device in physicalDevices:
if self.__isDeviceSuitable(device):
self.__physicalDevice = device
break
assert self.__physicalDevice != None
def __createLogicalDevice(self):
self.__indices = self.__findQueueFamilies(self.__physicalDevice)
uniqueQueueFamilies = {}.fromkeys([self.__indices.graphicsFamily, self.__indices.presentFamily])
queueCreateInfos = []
for i in uniqueQueueFamilies:
queueCreateInfo = VkDeviceQueueCreateInfo(
queueFamilyIndex=i,
queueCount=1,
pQueuePriorities=[1.0]
)
queueCreateInfos.append(queueCreateInfo)
deviceFeatures = VkPhysicalDeviceFeatures()
if enableValidationLayers:
createInfo = VkDeviceCreateInfo(
# queueCreateInfoCount=len(queueCreateInfos),
pQueueCreateInfos=queueCreateInfos,
# enabledExtensionCount=len(deviceExtensions),
ppEnabledExtensionNames=deviceExtensions,
# enabledLayerCount=len(validationLayers),
ppEnabledLayerNames=validationLayers,
pEnabledFeatures=deviceFeatures
)
else:
createInfo = VkDeviceCreateInfo(
queueCreateInfoCount=1,
pQueueCreateInfos=queueCreateInfo,
# enabledExtensionCount=len(deviceExtensions),
ppEnabledExtensionNames=deviceExtensions,
enabledLayerCount=0,
pEnabledFeatures=deviceFeatures
)
self.__device = vkCreateDevice(self.__physicalDevice, createInfo, None)
DeviceProcAddr.T = self.__device
self.__graphicQueue = vkGetDeviceQueue(self.__device, self.__indices.graphicsFamily, 0)
self.__presentQueue = vkGetDeviceQueue(self.__device, self.__indices.presentFamily, 0)
def __createSwapChain(self):
swapChainSupport = self.__querySwapChainSupport(self.__physicalDevice)
surfaceFormat = self.__chooseSwapSurfaceFormat(swapChainSupport.formats)
presentMode = self.__chooseSwapPresentMode(swapChainSupport.presentModes)
extent = self.__chooseSwapExtent(swapChainSupport.capabilities)
imageCount = swapChainSupport.capabilities.minImageCount + 1
if swapChainSupport.capabilities.maxImageCount > 0 and imageCount > swapChainSupport.capabilities.maxImageCount:
imageCount = swapChainSupport.capabilities.maxImageCount
indices = self.__findQueueFamilies(self.__physicalDevice)
queueFamily = {}.fromkeys([indices.graphicsFamily, indices.presentFamily])
queueFamilies = list(queueFamily.keys())
if len(queueFamilies) > 1:
createInfo = VkSwapchainCreateInfoKHR(
surface=self.__surface,
minImageCount=imageCount,
imageFormat=surfaceFormat.format,
imageColorSpace=surfaceFormat.colorSpace,
imageExtent=extent,
imageArrayLayers=1,
imageUsage=VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
# queueFamilyIndexCount=len(queueFamilies),
pQueueFamilyIndices=queueFamilies,
imageSharingMode=VK_SHARING_MODE_CONCURRENT,
preTransform=swapChainSupport.capabilities.currentTransform,
compositeAlpha=VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
presentMode=presentMode,
clipped=True
)
else:
createInfo = VkSwapchainCreateInfoKHR(
surface=self.__surface,
minImageCount=imageCount,
imageFormat=surfaceFormat.format,
imageColorSpace=surfaceFormat.colorSpace,
imageExtent=extent,
imageArrayLayers=1,
imageUsage=VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
# queueFamilyIndexCount=len(queueFamilies),
pQueueFamilyIndices=queueFamilies,
imageSharingMode=VK_SHARING_MODE_EXCLUSIVE,
preTransform=swapChainSupport.capabilities.currentTransform,
compositeAlpha=VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
presentMode=presentMode,
clipped=True
)
self.__swapChain = vkCreateSwapchainKHR(self.__device, createInfo, None)
assert self.__swapChain != None
self.__swapChainImages = vkGetSwapchainImagesKHR(self.__device, self.__swapChain)
self.__swapChainImageFormat = surfaceFormat.format
self.__swapChainExtent = extent
def __createImageViews(self):
self.__swapChainImageViews = []
for i, image in enumerate(self.__swapChainImages):
ssr = VkImageSubresourceRange(
VK_IMAGE_ASPECT_COLOR_BIT,
0, 1, 0, 1
)
createInfo = VkImageViewCreateInfo(
image=image,
viewType=VK_IMAGE_VIEW_TYPE_2D,
format=self.__swapChainImageFormat,
components=[VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY],
subresourceRange=ssr
)
self.__swapChainImageViews.append(vkCreateImageView(self.__device, createInfo, None))
def __createRenderPass(self):
colorAttachment = VkAttachmentDescription(
format=self.__swapChainImageFormat,
samples=VK_SAMPLE_COUNT_1_BIT,
loadOp=VK_ATTACHMENT_LOAD_OP_CLEAR,
storeOp=VK_ATTACHMENT_STORE_OP_STORE,
stencilLoadOp=VK_ATTACHMENT_LOAD_OP_DONT_CARE,
stencilStoreOp=VK_ATTACHMENT_STORE_OP_DONT_CARE,
initialLayout=VK_IMAGE_LAYOUT_UNDEFINED,
finalLayout=VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
)
colorAttachmentRef = VkAttachmentReference(
0,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
)
subpass = VkSubpassDescription(
pipelineBindPoint=VK_PIPELINE_BIND_POINT_GRAPHICS,
pColorAttachments=[colorAttachmentRef]
)
renderPassInfo = VkRenderPassCreateInfo(
pAttachments=[colorAttachment],
pSubpasses=[subpass]
)
self.__renderpass = vkCreateRenderPass(self.__device, renderPassInfo, None)
def __createGraphicsPipeline(self):
vertexShaderMode = self.__createShaderModule('shader/vert.spv')
fragmentShaderMode = self.__createShaderModule('shader/frag.spv')
vertexShaderStageInfo = VkPipelineShaderStageCreateInfo(
stage=VK_SHADER_STAGE_VERTEX_BIT,
module=vertexShaderMode,
pName='main'
)
fragmentShaderStageInfo = VkPipelineShaderStageCreateInfo(
stage=VK_SHADER_STAGE_FRAGMENT_BIT,
module=fragmentShaderMode,
pName='main'
)
shaderStageInfos = [vertexShaderStageInfo, fragmentShaderStageInfo]
bindingDescription = Vertex.getBindingDescription()
attributeDescription = Vertex.getAttributeDescriptions()
vertexInputInfo = VkPipelineVertexInputStateCreateInfo(
# vertexBindingDescriptionCount=0,
pVertexBindingDescriptions=[bindingDescription],
# vertexAttributeDescriptionCount=0,
pVertexAttributeDescriptions=attributeDescription,
)
inputAssembly = VkPipelineInputAssemblyStateCreateInfo(
topology=VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
primitiveRestartEnable=False
)
viewport = VkViewport(0.0, 0.0,
float(self.__swapChainExtent.width),
float(self.__swapChainExtent.height),
0.0, 1.0)
scissor = VkRect2D([0, 0], self.__swapChainExtent)
viewportStage = VkPipelineViewportStateCreateInfo(
viewportCount=1,
pViewports=viewport,
scissorCount=1,
pScissors=scissor
)
rasterizer = VkPipelineRasterizationStateCreateInfo(
depthClampEnable=False,
rasterizerDiscardEnable=False,
polygonMode=VK_POLYGON_MODE_FILL,
lineWidth=1.0,
cullMode=VK_CULL_MODE_BACK_BIT,
frontFace=VK_FRONT_FACE_CLOCKWISE,
depthBiasEnable=False
)
multisampling = VkPipelineMultisampleStateCreateInfo(
sampleShadingEnable=False,
rasterizationSamples=VK_SAMPLE_COUNT_1_BIT
)
colorBlendAttachment = VkPipelineColorBlendAttachmentState(
colorWriteMask=VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT,
blendEnable=False
)
colorBending = VkPipelineColorBlendStateCreateInfo(
logicOpEnable=False,
logicOp=VK_LOGIC_OP_COPY,
attachmentCount=1,
pAttachments=colorBlendAttachment,
blendConstants=[0.0, 0.0, 0.0, 0.0]
)
pipelineLayoutInfo = VkPipelineLayoutCreateInfo(
setLayoutCount=0,
pushConstantRangeCount=0
)
self.__pipelineLayout = vkCreatePipelineLayout(self.__device, pipelineLayoutInfo, None)
pipelineInfo = VkGraphicsPipelineCreateInfo(
# stageCount=len(shaderStageInfos),
pStages=shaderStageInfos,
pVertexInputState=vertexInputInfo,
pInputAssemblyState=inputAssembly,
pViewportState=viewportStage,
pRasterizationState=rasterizer,
pMultisampleState=multisampling,
pColorBlendState=colorBending,
layout=self.__pipelineLayout,
renderPass=self.__renderpass,
subpass=0,
basePipelineHandle=VK_NULL_HANDLE
)
self.__pipeline = vkCreateGraphicsPipelines(self.__device, VK_NULL_HANDLE, 1, pipelineInfo, None)#[0]
vkDestroyShaderModule(self.__device, vertexShaderMode, None)
vkDestroyShaderModule(self.__device, fragmentShaderMode, None)
def __createFrambuffers(self):
self.__swapChainFramebuffers = []
for i, iv in enumerate(self.__swapChainImageViews):
framebufferInfo = VkFramebufferCreateInfo(
renderPass=self.__renderpass,
pAttachments=[iv],
width=self.__swapChainExtent.width,
height=self.__swapChainExtent.height,
layers=1
)
self.__swapChainFramebuffers.append(vkCreateFramebuffer(self.__device, framebufferInfo, None))
def __createCommandPool(self):
queueFamilyIndices = self.__findQueueFamilies(self.__physicalDevice)
createInfo = VkCommandPoolCreateInfo(
queueFamilyIndex=queueFamilyIndices.graphicsFamily
)
self.__commandPool = vkCreateCommandPool(self.__device, createInfo, None)
def __createCommandBuffers(self):
self.__commandBuffers = []
allocInfo = VkCommandBufferAllocateInfo(
commandPool=self.__commandPool,
level=VK_COMMAND_BUFFER_LEVEL_PRIMARY,
commandBufferCount=len(self.__swapChainFramebuffers)
)
self.__commandBuffers = vkAllocateCommandBuffers(self.__device, allocInfo)
for i, buffer in enumerate(self.__commandBuffers):
beginInfo = VkCommandBufferBeginInfo(flags=VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT)
vkBeginCommandBuffer(buffer, beginInfo)
renderArea = VkRect2D([0, 0], self.__swapChainExtent)
clearColor = VkClearValue(color=[[0.0, 0.0, 0.0, 1.0]])
renderPassInfo = VkRenderPassBeginInfo(
renderPass=self.__renderpass,
framebuffer=self.__swapChainFramebuffers[i],
renderArea=renderArea,
pClearValues=[clearColor]
)
vkCmdBeginRenderPass(buffer, renderPassInfo, VK_SUBPASS_CONTENTS_INLINE)
vkCmdBindPipeline(buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, self.__pipeline)
vkCmdDraw(buffer, 3, 1, 0, 0)
vkCmdEndRenderPass(buffer)
vkEndCommandBuffer(buffer)
def __createSemaphores(self):
semaphoreInfo = VkSemaphoreCreateInfo()
self.__imageAvailableSemaphore = vkCreateSemaphore(self.__device, semaphoreInfo, None)
self.__renderFinishedSemaphore = vkCreateSemaphore(self.__device, semaphoreInfo, None)
def drawFrame(self):
if not self.isExposed():
return
try:
imageIndex = vkAcquireNextImageKHR(self.__device, self.__swapChain, 18446744073709551615,
self.__imageAvailableSemaphore, VK_NULL_HANDLE)
except VkErrorSurfaceLostKhr:
self.__recreateSwapChain()
return
# else:
# raise Exception('faild to acquire next image.')
waitSemaphores = [self.__imageAvailableSemaphore]
signalSemaphores = [self.__renderFinishedSemaphore]
waitStages = [VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT]
submit = VkSubmitInfo(
pWaitSemaphores=waitSemaphores,
pWaitDstStageMask=waitStages,
pCommandBuffers=[self.__commandBuffers[imageIndex]],
pSignalSemaphores=signalSemaphores
)
vkQueueSubmit(self.__graphicQueue, 1, submit, VK_NULL_HANDLE)
presenInfo = VkPresentInfoKHR(
pWaitSemaphores=signalSemaphores,
pSwapchains=[self.__swapChain],
pImageIndices=[imageIndex]
)
try:
vkQueuePresentKHR(self.__presentQueue, presenInfo)
except VkErrorOutOfDateKhr:
self.__recreateSwapChain()
if enableValidationLayers:
vkQueueWaitIdle(self.__presentQueue)
def __createShaderModule(self, shaderFile):
with open(shaderFile, 'rb') as sf:
code = sf.read()
createInfo = VkShaderModuleCreateInfo(
codeSize=len(code),
pCode=code
)
return vkCreateShaderModule(self.__device, createInfo, None)
def __chooseSwapSurfaceFormat(self, formats):
if len(formats) == 1 and formats[0].format == VK_FORMAT_UNDEFINED:
return [VK_FORMAT_B8G8R8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR]
for i in formats:
if i.format == VK_FORMAT_B8G8R8_UNORM and i.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
return i
return formats[0]
def __chooseSwapPresentMode(self, presentModes):
bestMode = VK_PRESENT_MODE_FIFO_KHR
for i in presentModes:
if i == VK_PRESENT_MODE_FIFO_KHR:
return i
elif i == VK_PRESENT_MODE_MAILBOX_KHR:
return i
elif i == VK_PRESENT_MODE_IMMEDIATE_KHR:
return i
return bestMode
def __chooseSwapExtent(self, capabilities):
width = max(capabilities.minImageExtent.width, min(capabilities.maxImageExtent.width, self.width()))
height = max(capabilities.minImageExtent.height, min(capabilities.maxImageExtent.height, self.height()))
return VkExtent2D(width, height)
def __querySwapChainSupport(self, device):
detail = SwapChainSupportDetails()
detail.capabilities = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, self.__surface)
detail.formats = vkGetPhysicalDeviceSurfaceFormatsKHR(device, self.__surface)
detail.presentModes = vkGetPhysicalDeviceSurfacePresentModesKHR(device, self.__surface)
return detail
def __isDeviceSuitable(self, device):
indices = self.__findQueueFamilies(device)
extensionsSupported = self.__checkDeviceExtensionSupport(device)
swapChainAdequate = False
if extensionsSupported:
swapChainSupport = self.__querySwapChainSupport(device)
swapChainAdequate = (swapChainSupport.formats is not None) and (swapChainSupport.presentModes is not None)
return indices.isComplete and extensionsSupported and swapChainAdequate
def __checkDeviceExtensionSupport(self, device):
availableExtensions = vkEnumerateDeviceExtensionProperties(device, None)
aen = [i.extensionName for i in availableExtensions]
for i in deviceExtensions:
if i not in aen:
return False
return True
def __findQueueFamilies(self, device):
indices = QueueFamilyIndices()
familyProperties = vkGetPhysicalDeviceQueueFamilyProperties(device)
for i, prop in enumerate(familyProperties):
if prop.queueCount > 0 and prop.queueFlags & VK_QUEUE_GRAPHICS_BIT:
indices.graphicsFamily = i
presentSupport = vkGetPhysicalDeviceSurfaceSupportKHR(device, i, self.__surface)
if prop.queueCount > 0 and presentSupport:
indices.presentFamily = i
if indices.isComplete:
break
return indices
def __getRequiredExtensions(self):
extenstions = [e.extensionName for e in vkEnumerateInstanceExtensionProperties(None)]
if enableValidationLayers:
extenstions.append(VK_EXT_DEBUG_REPORT_EXTENSION_NAME)
return extenstions
def __checkValidationLayerSupport(self):
availableLayers = vkEnumerateInstanceLayerProperties()
for layer in validationLayers:
layerfound = False
for layerProp in availableLayers:
if layer == layerProp.layerName:
layerfound = True
break
return layerfound
return False
def resizeEvent(self, event):
if event.size() != event.oldSize():
self.__recreateSwapChain()
super(HelloTriangleApplication, self).resizeEvent(event)
if __name__ == '__main__':
import sys
app = QtGui.QGuiApplication(sys.argv)
win = HelloTriangleApplication()
win.show()
def clenaup():
global win
win.timer.stop()
del win
app.aboutToQuit.connect(clenaup)
sys.exit(app.exec_())