1//go:build linux
2
3package vkdevice
4
5import (
6 "fmt"
7 "math"
8 "unsafe"
9
10 "github.com/bnema/purego-vulkan/vulkan"
11)
12
13type instanceBuffer struct {
14 device *Device
15 Buffer vulkan.Buffer
16 Memory vulkan.DeviceMemory
17 capacity int
18}
19
20func (b *instanceBuffer) Close() {
21 if b == nil {
22 return
23 }
24 if b.Buffer != 0 {
25 b.device.Dispatch.DestroyBuffer(b.device.Logical, b.Buffer, nil)
26 b.Buffer = 0
27 }
28 if b.Memory != 0 {
29 b.device.Dispatch.FreeMemory(b.device.Logical, b.Memory, nil)
30 b.Memory = 0
31 }
32}
33
34func (f *Frame) uploadInstances(instances []Instance) error {
35 if len(instances) > math.MaxInt/int(unsafe.Sizeof(Instance{})) || len(instances) > math.MaxUint32 {
36 return fmt.Errorf("too many instances")
37 }
38 size := vulkan.DeviceSize(len(instances)) * vulkan.DeviceSize(unsafe.Sizeof(Instance{}))
39 if f.instances == nil || len(instances) > f.instances.capacity {
40 // record calls this only after Ready; the old buffer cannot be in GPU use.
41 if f.instances != nil {
42 f.instances.Close()
43 }
44 f.instances = &instanceBuffer{device: f.device}
45 b := f.instances
46 ci := vulkan.BufferCreateInfo{SType: vulkan.StructureTypeBufferCreateInfo, Size: size, Usage: vulkan.BufferUsageVertexBufferBit, SharingMode: vulkan.SharingModeExclusive}
47 if err := vulkan.Check(f.device.Dispatch.CreateBuffer(f.device.Logical, &ci, nil, &b.Buffer)); err != nil {
48 return err
49 }
50 var req vulkan.MemoryRequirements
51 f.device.Dispatch.GetBufferMemoryRequirements(f.device.Logical, b.Buffer, &req)
52 var memory vulkan.PhysicalDeviceMemoryProperties
53 f.device.InstanceDispatch.GetPhysicalDeviceMemoryProperties(f.device.Physical, &memory)
54 want := vulkan.MemoryPropertyFlags(vulkan.MemoryPropertyHostVisibleBit | vulkan.MemoryPropertyHostCoherentBit)
55 index := uint32(math.MaxUint32)
56 for i := uint32(0); i < memory.MemoryTypeCount; i++ {
57 if req.MemoryTypeBits&(1<<i) != 0 && memory.MemoryTypes[i].PropertyFlags&want == want {
58 index = i
59 break
60 }
61 }
62 if index == math.MaxUint32 {
63 return fmt.Errorf("no host-coherent instance memory type")
64 }
65 alloc := vulkan.MemoryAllocateInfo{SType: vulkan.StructureTypeMemoryAllocateInfo, AllocationSize: req.Size, MemoryTypeIndex: index}
66 if err := vulkan.Check(f.device.Dispatch.AllocateMemory(f.device.Logical, &alloc, nil, &b.Memory)); err != nil {
67 return err
68 }
69 if err := vulkan.Check(f.device.Dispatch.BindBufferMemory(f.device.Logical, b.Buffer, b.Memory, 0)); err != nil {
70 return err
71 }
72 b.capacity = len(instances)
73 }
74 ptr := &f.scratch.mapped
75 if err := vulkan.Check(f.device.Dispatch.MapMemory(f.device.Logical, f.instances.Memory, 0, size, 0, ptr)); err != nil {
76 return err
77 }
78 copy(unsafe.Slice((*Instance)(*ptr), len(instances)), instances)
79 f.device.Dispatch.UnmapMemory(f.device.Logical, f.instances.Memory)
80 *ptr = nil
81 return nil
82}