// Generated by tools/generate.py from native.c and x11.c; do not edit. #ifndef BV_NATIVE_IMPLEMENTATION #define BV_NATIVE_IMPLEMENTATION // Bend native effect ABI. Only the IO event loop accesses the registry. #define VK_NO_PROTOTYPES #include #include #include #include #include #if !defined(__linux__) || UINTPTR_MAX != UINT64_MAX #error "bend-vulkan currently requires 64-bit Linux" #endif #define BV_INVALID 0x60000002u #define BV_ARGUMENT 0x60000003u #define BV_LIFETIME 0x60000004u #define BV_LIMIT 0x60000005u #define BV_MAX_COPY (16u * 1024u * 1024u) typedef enum { BV_ENTRY, BV_INSTANCE, BV_PHYSICAL, BV_DEVICE, BV_BUFFER, BV_MEMORY, BV_POOL, BV_COMMAND, BV_FENCE, BV_IMAGE, BV_IMAGE_VIEW, BV_RENDER_PASS, BV_FRAMEBUFFER, BV_SHADER, BV_LAYOUT, BV_PIPELINE, BV_WINDOW, BV_SURFACE, BV_SWAPCHAIN, BV_SEMAPHORE, BV_DESCRIPTOR_LAYOUT, BV_DESCRIPTOR_POOL, BV_DESCRIPTOR_SET, BV_SAMPLER, BV_QUERY_POOL, BV_KIND_COUNT } BvKind; typedef struct BvRow BvRow; typedef struct BvLease BvLease; typedef struct { void (*destroy)(BvRow*); } BvWindowContext; typedef enum { BV_INITIAL, BV_RECORDING, BV_EXECUTABLE, BV_PENDING, BV_UNCERTAIN, BV_COMPLETED, BV_COMMAND_INVALID } BvCommandPhase; typedef enum { BV_OUTSIDE, BV_INSIDE } BvRenderTag; typedef struct { BvRenderTag tag; union { struct { BvRow* framebuffer; } inside; } data; } BvRenderScope; typedef struct { BvRenderScope scope; BvRow* pipeline; uint64_t vertices_ready,index_remaining; uint32_t index_width; bool index_ready,viewport_ready,scissor_ready,push_ready; } BvRecording; #define BV_MAX_DESCRIPTOR_SETS 64u #define BV_MAX_DESCRIPTOR_SLOTS 4096u typedef struct { BvLease* lease; uint64_t lease_serial,generation; BvRow* sets[BV_MAX_DESCRIPTOR_SETS]; BvCommandPhase phase; union { BvRecording recording; struct { BvRow* fence; } pending; struct { BvRow* fence; } uncertain; } submission; } BvCommand; typedef enum { BV_CALLER, BV_CONVENIENCE_PRIVATE } BvFenceLifetime; typedef enum { BV_FENCE_FREE, BV_FENCE_ACQUIRE, BV_FENCE_PRESENT } BvFenceUse; typedef struct { BvFenceLifetime lifetime; BvFenceUse use; BvLease* lease; uint64_t serial; } BvFence; typedef enum { BV_HEALTHY, BV_LOST } BvHealth; typedef enum { BV_DEP_RECORDED, BV_DEP_BINDING, BV_DEP_VIEW_IMAGE, BV_DEP_FRAMEBUFFER_PASS, BV_DEP_FRAMEBUFFER_VIEW, BV_DEP_PIPELINE_LAYOUT, BV_DEP_PIPELINE_PASS, BV_DEP_WINDOW, BV_DEP_SURFACE, BV_DEP_SWAPCHAIN, BV_DEP_SUBMIT_WAIT, BV_DEP_SUBMIT_SIGNAL, BV_DEP_LAYOUT_SET, BV_DEP_SET_POOL, BV_DEP_SET_LAYOUT, BV_DEP_UNIFORM, BV_DEP_SAMPLED_VIEW, BV_DEP_SAMPLER } BvDepRole; typedef struct BvDep { BvRow* target; BvDepRole role; union { struct { uint64_t offset; } binding; } data; struct BvDep* next; } BvDep; typedef enum { BV_ALLOCATED_IMAGE, BV_BORROWED_IMAGE } BvImageStorage; typedef struct { VkFormat format; VkExtent2D extent; uint32_t mips,layers; VkImageUsageFlags usage; BvImageStorage storage; BvRow* swapchain; uint32_t index; } BvImage; typedef enum { BV_SEM_UNUSED, BV_SEM_SIGNAL_PENDING, BV_SEM_SIGNALED, BV_SEM_SUBMIT_WAIT, BV_SEM_PRESENT_WAIT, BV_SEM_UNCERTAIN, BV_SEM_QUARANTINED } BvSemaphorePhase; typedef struct { BvSemaphorePhase phase; BvRow* producer; uint64_t producer_serial; } BvSemaphore; typedef enum { BV_LEASE_NONE, BV_LEASE_ACQUIRING, BV_LEASE_ACQUIRED, BV_LEASE_RENDERING, BV_LEASE_RENDERED, BV_LEASE_PRESENTING, BV_LEASE_ACQUIRE_UNCERTAIN, BV_LEASE_RENDER_UNCERTAIN, BV_LEASE_PRESENT_UNCERTAIN, BV_LEASE_ABANDONED } BvLeasePhase; struct BvLease { BvLeasePhase phase; BvRow *swapchain,*fence,*semaphore; uint32_t index; uint64_t serial; }; typedef struct { uint32_t count,lease_count; BvRow** images; BvLease* leases; VkFormat format; VkExtent2D extent; VkImageUsageFlags usage; } BvSwapchain; typedef struct { VkImageViewType type; VkImageSubresourceRange range; } BvImageView; typedef struct { uint32_t colors,count; VkAttachmentDescription* attachments; } BvRenderPass; typedef struct { VkExtent2D extent; uint32_t count; BvDep** attachments; } BvFramebuffer; typedef struct { uint32_t stages,bytes,count; BvRow** sets; } BvPipelineLayout; typedef struct { uint32_t count,slots,uniforms,sampled; VkDescriptorSetLayoutBinding* bindings; } BvDescriptorSchema; typedef enum { BV_POOL_READY, BV_POOL_QUARANTINED } BvDescriptorPoolPhase; typedef struct { BvDescriptorPoolPhase phase; uint32_t max_sets,sets,uniforms,sampled,used_uniforms,used_sampled; } BvDescriptorPool; typedef enum { BV_UNWRITTEN_UNIFORM, BV_UNIFORM_SLOT, BV_UNWRITTEN_SAMPLED, BV_SAMPLED_SLOT } BvDescriptorSlotTag; typedef struct { BvDescriptorSlotTag tag; union { struct { BvRow* buffer; uint64_t offset,range; } uniform; struct { BvRow *view,*sampler; VkImageLayout layout; } sampled; } data; } BvDescriptorSlot; typedef struct { BvDescriptorSlot* slots; } BvDescriptorSet; typedef struct { VkFilter min,mag; VkSamplerMipmapMode mip; } BvSampler; typedef struct { uint32_t binding,stride,rate,alignment,first_end; } BvVertexRequirement; typedef struct { uint32_t count; BvVertexRequirement* required; } BvPipeline; typedef struct { uint32_t command; uint64_t generation; bool written,ready; } BvQuerySlot; typedef struct { uint32_t count; BvQuerySlot* slots; } BvQueries; struct BvRow { uint32_t id; BvKind kind; BvRow *parent, *next; uint64_t handle, size; VkMemoryRequirements requirements; uint32_t flags, memory_type; bool retired; union { BvImage image; BvImageView view; BvRenderPass pass; BvFramebuffer framebuffer; BvPipelineLayout layout; BvPipeline pipeline; BvDescriptorSchema schema; BvDescriptorPool descriptor_pool; BvDescriptorSet set; BvSampler sampler; BvQueries queries; } object; BvCommand command; BvFence fence; BvSemaphore semaphore; void* context; BvDep* deps; }; static BvRow* bv_rows; static uint32_t bv_next_id = 1; typedef struct { void* library; PFN_vkGetInstanceProcAddr get; PFN_vkCreateInstance create; PFN_vkEnumerateInstanceVersion version; PFN_vkEnumerateInstanceLayerProperties layers; PFN_vkEnumerateInstanceExtensionProperties extensions; } BvEntry; typedef struct { VkInstance handle; PFN_vkDestroyInstance destroy; PFN_vkEnumeratePhysicalDevices enumerate; PFN_vkGetPhysicalDeviceProperties properties; PFN_vkGetPhysicalDeviceQueueFamilyProperties queues; PFN_vkGetPhysicalDeviceMemoryProperties memory; PFN_vkEnumerateDeviceExtensionProperties extensions; PFN_vkGetPhysicalDeviceFormatProperties formats; PFN_vkGetPhysicalDeviceImageFormatProperties image_formats; PFN_vkCreateDevice create_device; PFN_vkGetDeviceProcAddr get_device; PFN_vkVoidFunction create_surface; PFN_vkDestroySurfaceKHR destroy_surface; PFN_vkGetPhysicalDeviceSurfaceSupportKHR surface_support; PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR surface_caps; PFN_vkGetPhysicalDeviceSurfaceFormatsKHR surface_formats; PFN_vkGetPhysicalDeviceSurfacePresentModesKHR present_modes; PFN_vkGetPhysicalDeviceFeatures2KHR features2; bool presentation; } BvInstance; #define BV_DEVICE_FUNCTIONS(X) \ X(DestroyDevice) X(DeviceWaitIdle) X(GetDeviceQueue) X(CreateSemaphore) X(DestroySemaphore) \ X(CreateBuffer) X(DestroyBuffer) X(GetBufferMemoryRequirements) \ X(CreateImage) X(DestroyImage) X(GetImageMemoryRequirements) X(BindImageMemory) \ X(CreateImageView) X(DestroyImageView) \ X(CreateRenderPass) X(DestroyRenderPass) X(CreateFramebuffer) X(DestroyFramebuffer) \ X(CmdBeginRenderPass) X(CmdEndRenderPass) \ X(CreateShaderModule) X(DestroyShaderModule) X(CreatePipelineLayout) X(DestroyPipelineLayout) \ X(CreateGraphicsPipelines) X(DestroyPipeline) \ X(CreateDescriptorSetLayout) X(DestroyDescriptorSetLayout) X(CreateDescriptorPool) X(DestroyDescriptorPool) \ X(AllocateDescriptorSets) X(FreeDescriptorSets) X(ResetDescriptorPool) X(UpdateDescriptorSets) \ X(CreateSampler) X(DestroySampler) X(CmdBindDescriptorSets) \ X(CmdBindPipeline) X(CmdSetViewport) X(CmdSetScissor) X(CmdBindVertexBuffers) \ X(CmdBindIndexBuffer) X(CmdPushConstants) X(CmdDrawIndexed) \ X(AllocateMemory) X(FreeMemory) X(BindBufferMemory) X(MapMemory) X(UnmapMemory) \ X(FlushMappedMemoryRanges) X(InvalidateMappedMemoryRanges) \ X(CreateCommandPool) X(DestroyCommandPool) X(AllocateCommandBuffers) \ X(BeginCommandBuffer) X(EndCommandBuffer) X(CmdFillBuffer) \ X(CmdClearColorImage) X(CmdClearDepthStencilImage) X(CmdCopyBufferToImage) X(CmdCopyImageToBuffer) \ X(CmdCopyBuffer) X(CmdPipelineBarrier) X(QueueSubmit) \ X(CreateQueryPool) X(DestroyQueryPool) X(GetQueryPoolResults) X(CmdResetQueryPool) X(CmdWriteTimestamp) \ X(CreateFence) X(DestroyFence) X(GetFenceStatus) X(WaitForFences) X(ResetFences) X(ResetCommandBuffer) typedef struct { VkDevice handle; BvHealth health; BvRow* convenience; VkPhysicalDevice physical; VkQueue queue; VkQueue present_queue; uint32_t present_family; uint64_t lease_serial; bool presentation; PFN_vkCreateSwapchainKHR CreateSwapchainKHR; PFN_vkDestroySwapchainKHR DestroySwapchainKHR; PFN_vkGetSwapchainImagesKHR GetSwapchainImagesKHR; PFN_vkAcquireNextImageKHR AcquireNextImageKHR; PFN_vkQueuePresentKHR QueuePresentKHR; PFN_vkReleaseSwapchainImagesEXT ReleaseSwapchainImagesEXT; uint32_t family, queue_flags; VkQueueFamilyProperties queue_properties; VkPhysicalDeviceLimits limits; VkPhysicalDeviceMemoryProperties memory; #define BV_FIELD(name) PFN_vk##name name; BV_DEVICE_FUNCTIONS(BV_FIELD) #undef BV_FIELD } BvDevice; static void bv_unpack(Env e, Term value, uint32_t count, Term* fields) { spare_free(e, cls_fit(count), ctr_take(e, value, count, fields)); } static uint32_t bv_key(Env e, Term value) { if (term_tag(value) == TAG_PAK) return (uint32_t)term_loc(value); Term fields[1]; bv_unpack(e, value, 1, fields); return (uint32_t)fields[0]; } static uint64_t bv_u64(Env e, Term value) { Term fields[2]; bv_unpack(e, value, 2, fields); return ((uint64_t)(uint32_t)fields[1] << 32) | (uint32_t)fields[0]; } static Term bv_words(Env e, uint64_t value) { return io_tup(e, (uint32_t)value, (uint32_t)(value >> 32)); } static Term bv_node(Env e, uint64_t cid, uint32_t count, Term* fields) { uint64_t location = heap_alloc(e, cls_fit(count)); for (uint32_t j = 0; j < count; j++) e.mem[location+j] = io_seal(e, fields[j], cid); return term_ctr(cid, location); } static Term bv_ok(Env e) { return io_done(e, term_pak(CID(Unit), 0)); } static Term bv_vk_error(Env e, VkResult result, const char* operation) { char message[192]; snprintf(message, sizeof(message), "%s: VkResult %d", operation, (int)result); return io_fail(e, (uint32_t)(int32_t)result, message); } static BvRow* bv_get(uint32_t id, BvKind kind) { for (BvRow* row = bv_rows; row; row = row->next) if (row->id == id) return row->kind == kind ? row : NULL; return NULL; } static BvRow* bv_add(BvKind kind, BvRow* parent) { // Keys never repeat, including after a failed creation or a freed row. if (!bv_next_id) return NULL; BvRow* row = calloc(1, sizeof(*row)); if (!row) return NULL; row->id = bv_next_id++; row->kind = kind; row->parent = parent; row->next = bv_rows; bv_rows = row; return row; } static void bv_remove(BvRow* row) { BvRow** link = &bv_rows; while (*link != row) link = &(*link)->next; *link = row->next; while (row->deps) { BvDep* use = row->deps; row->deps = use->next; free(use); } if (row->kind==BV_RENDER_PASS) free(row->object.pass.attachments); if (row->kind==BV_FRAMEBUFFER) free(row->object.framebuffer.attachments); if (row->kind==BV_PIPELINE) free(row->object.pipeline.required); if (row->kind==BV_LAYOUT) free(row->object.layout.sets); if (row->kind==BV_DESCRIPTOR_LAYOUT) free(row->object.schema.bindings); if (row->kind==BV_DESCRIPTOR_SET) free(row->object.set.slots); if (row->kind==BV_QUERY_POOL) free(row->object.queries.slots); free(row); } static BvRow* bv_child(uint32_t id, BvKind kind, BvRow* owner) { BvRow* row = bv_get(id, kind); return row && row->parent == owner ? row : NULL; } static BvRow* bv_command_device(BvRow* command) { return command ? command->parent->parent : NULL; } static int bv_outside(const BvRow* command) { return command->command.phase==BV_RECORDING && command->command.submission.recording.scope.tag==BV_OUTSIDE; } static BvRow* bv_command_fence(BvRow* command) { if (command->command.phase==BV_PENDING) return command->command.submission.pending.fence; if (command->command.phase==BV_UNCERTAIN) return command->command.submission.uncertain.fence; return NULL; } static BvRow* bv_active(BvRow* owner,BvRow* fence) { for (BvRow* row=bv_rows;row;row=row->next) if (row->kind==BV_COMMAND && bv_command_device(row)==owner && bv_command_fence(row) && (!fence || bv_command_fence(row)==fence)) return row; return NULL; } static int bv_uncertain(BvRow* owner) { for (BvRow* row=bv_rows;row;row=row->next) { if (row->kind==BV_COMMAND && bv_command_device(row)==owner && row->command.phase==BV_UNCERTAIN) return 1; if (row->kind!=BV_SWAPCHAIN || row->parent!=owner) continue; BvSwapchain* target=row->context; for (uint32_t j=0;jlease_count;j++) { BvLeasePhase phase=target->leases[j].phase; if (phase==BV_LEASE_ACQUIRE_UNCERTAIN || phase==BV_LEASE_RENDER_UNCERTAIN || phase==BV_LEASE_PRESENT_UNCERTAIN || phase==BV_LEASE_ABANDONED) return 1; } } return 0; } static BvLease* bv_image_lease(BvRow* image) { if (image->object.image.storage!=BV_BORROWED_IMAGE) return NULL; BvSwapchain* target=image->object.image.swapchain->context; for (uint32_t j=0;jlease_count;j++) if (target->leases[j].phase!=BV_LEASE_NONE && target->leases[j].phase!=BV_LEASE_PRESENTING && target->leases[j].index==image->object.image.index) return &target->leases[j]; return NULL; } static void bv_finish_wsi_fence(BvRow* fence) { BvLease* lease=fence->fence.lease; if (lease && lease->serial==fence->fence.serial) { if (fence->fence.use==BV_FENCE_ACQUIRE) lease->phase=lease->phase==BV_LEASE_ACQUIRING ? BV_LEASE_ACQUIRED : BV_LEASE_ABANDONED; else { if (lease->semaphore) lease->semaphore->semaphore.phase=BV_SEM_UNUSED; *lease=(BvLease){0}; } } fence->fence.use=BV_FENCE_FREE;fence->fence.lease=NULL;fence->fence.serial=0; } static void bv_complete(BvRow* command) { BvDep** link=&command->deps; while (*link) { BvDep* dep=*link; if (dep->role==BV_DEP_SUBMIT_WAIT || dep->role==BV_DEP_SUBMIT_SIGNAL) { dep->target->semaphore.phase=command->command.phase==BV_UNCERTAIN ? BV_SEM_QUARANTINED : dep->role==BV_DEP_SUBMIT_WAIT ? BV_SEM_UNUSED : BV_SEM_SIGNALED; *link=dep->next;free(dep); } else link=&dep->next; } BvLease* lease=command->command.lease; if (lease && lease->serial==command->command.lease_serial) { if (lease->phase==BV_LEASE_RENDERING) lease->phase=BV_LEASE_RENDERED; if (lease->phase==BV_LEASE_RENDER_UNCERTAIN) lease->phase=BV_LEASE_ABANDONED; } for (BvRow* pool=bv_rows;pool;pool=pool->next) if (pool->kind==BV_QUERY_POOL && pool->parent==bv_command_device(command)) { for (uint32_t j=0;jobject.queries.count;j++) { BvQuerySlot* slot=&pool->object.queries.slots[j]; if (slot->command==command->id && slot->generation==command->command.generation) slot->ready=command->command.phase==BV_PENDING; } } command->command.phase=command->command.phase==BV_PENDING ? BV_COMPLETED : BV_COMMAND_INVALID; memset(&command->command.submission,0,sizeof(command->command.submission)); } static VkResult bv_device_result(BvRow* owner,VkResult result) { BvDevice* device=owner->context; if (result==VK_ERROR_DEVICE_LOST) { device->health=BV_LOST; for (BvRow* row=bv_rows;row;row=row->next) if (row->kind==BV_COMMAND && bv_command_device(row)==owner) { row->command.phase=BV_COMMAND_INVALID; memset(&row->command.submission,0,sizeof(row->command.submission)); } } return result; } static Term bv_device_error(Env e,BvRow* owner,VkResult result,const char* operation) { return bv_vk_error(e,bv_device_result(owner,result),operation); } static int bv_lost(BvRow* owner) { return ((BvDevice*)owner->context)->health==BV_LOST; } static VkResult bv_drain_presentation(BvRow* owner); static VkResult bv_idle(BvRow* owner) { if (bv_lost(owner)) return VK_ERROR_DEVICE_LOST; BvDevice* device=owner->context; VkResult result=bv_device_result(owner,device->DeviceWaitIdle(device->handle)); if (result==VK_SUCCESS) { BvRow* command; while ((command=bv_active(owner,NULL))) bv_complete(command); } return result; } static BvDep* bv_dependency(const BvRow* row,BvDepRole role) { for (BvDep* dep=row->deps;dep;dep=dep->next) if (dep->role==role) return dep; return NULL; } static BvRow* bv_bound_memory(const BvRow* row) { BvDep* binding=bv_dependency(row,BV_DEP_BINDING); return binding ? binding->target : NULL; } static int bv_image_available(BvRow* image) { if (image->object.image.storage==BV_ALLOCATED_IMAGE) return bv_bound_memory(image)!=NULL; BvLease* lease=bv_image_lease(image); return lease && lease->phase==BV_LEASE_ACQUIRED; } static uint64_t bv_bound_offset(const BvRow* row) { return bv_dependency(row,BV_DEP_BINDING)->data.binding.offset; } static int bv_may_reach_depth(const BvRow* row,const BvRow* target,unsigned remaining) { if (row==target) return 1; if (!remaining) return row->deps!=NULL; for (BvDep* dep=row->deps;dep;dep=dep->next) if (bv_may_reach_depth(dep->target,target,remaining-1)) return 1; return 0; } static int bv_memory_busy(BvRow* memory) { for (BvRow* command=bv_rows;command;command=command->next) if (command->kind==BV_COMMAND && bv_command_device(command)==memory->parent && bv_command_fence(command) && bv_may_reach_depth(command,memory,BV_KIND_COUNT)) return 1; return 0; } static BvRow* bv_public_fence(uint32_t id) { BvRow* fence=bv_get(id,BV_FENCE); return fence && fence->fence.lifetime==BV_CALLER ? fence : NULL; } static int bv_referenced(BvRow* buffer) { for (BvRow* row = bv_rows; row; row = row->next) for (BvDep* use = row->deps; use; use = use->next) if (use->target == buffer) return 1; return 0; } static void bv_free_refs(BvDep* uses) { while (uses) { BvDep* next=uses->next; free(uses); uses=next; } } static int bv_sealed(const BvRow* row,unsigned remaining) { if (row->retired) return 1; if (!remaining) return row->deps!=NULL; for (BvDep* dep=row->deps;dep;dep=dep->next) if (bv_sealed(dep->target,remaining-1)) return 1; return 0; } static uint32_t bv_prepare_refs(BvRow* command, uint32_t count, BvRow** resources) { BvDep* staged=NULL; BvLease* lease=command->command.lease;uint64_t serial=command->command.lease_serial; BvRow* owner=bv_command_device(command); for (BvRow* image=bv_rows;image;image=image->next) { if (image->kind!=BV_IMAGE || image->parent!=owner || image->object.image.storage!=BV_BORROWED_IMAGE) continue; bool used=false; for (uint32_t j=0;jphase!=BV_LEASE_ACQUIRED || lease!=found || serial!=found->serial) return BV_LIFETIME; lease=found;serial=found->serial; } for (uint32_t j=0;jdeps;u;u=u->next) found |= u->target==resources[j]; for (BvDep* u=staged;u;u=u->next) found |= u->target==resources[j]; if (found) continue; BvDep* use=malloc(sizeof(*use)); if (!use) { bv_free_refs(staged); return BV_LIMIT; } *use=(BvDep){.target=resources[j],.role=BV_DEP_RECORDED,.next=staged};staged=use; } command->command.lease=lease;command->command.lease_serial=serial; while (staged) { BvDep* next=staged->next; staged->next=command->deps; command->deps=staged; staged=next; } return 0; } static uint32_t bv_baseline_stages(BvDevice* device, uint32_t mask) { const uint32_t baseline_graphics=VK_PIPELINE_STAGE_VERTEX_INPUT_BIT|VK_PIPELINE_STAGE_VERTEX_SHADER_BIT| VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT|VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT| VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT|VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; uint32_t allowed=VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT|VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT|VK_PIPELINE_STAGE_HOST_BIT; if (device->queue_flags & VK_QUEUE_GRAPHICS_BIT) allowed |= baseline_graphics; if (device->queue_flags & VK_QUEUE_COMPUTE_BIT) allowed |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; if (device->queue_flags & (VK_QUEUE_GRAPHICS_BIT|VK_QUEUE_COMPUTE_BIT)) allowed |= VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT; if (device->queue_flags & (VK_QUEUE_GRAPHICS_BIT|VK_QUEUE_COMPUTE_BIT|VK_QUEUE_TRANSFER_BIT)) allowed |= VK_PIPELINE_STAGE_TRANSFER_BIT; if (!mask || (mask & ~(allowed|VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT|VK_PIPELINE_STAGE_ALL_COMMANDS_BIT))) return 0; uint32_t expanded=mask & allowed; if (mask & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) { if (!(device->queue_flags & VK_QUEUE_GRAPHICS_BIT)) return 0; expanded |= baseline_graphics|VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT; } if (mask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) expanded |= allowed & ~VK_PIPELINE_STAGE_HOST_BIT; return expanded; } static int bv_access(uint32_t stages, uint32_t access) { const uint32_t shaders=VK_PIPELINE_STAGE_VERTEX_SHADER_BIT|VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT|VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; static const struct { uint32_t access, stages; } table[]={ {VK_ACCESS_INDIRECT_COMMAND_READ_BIT,VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT}, {VK_ACCESS_INDEX_READ_BIT|VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT,VK_PIPELINE_STAGE_VERTEX_INPUT_BIT}, {VK_ACCESS_UNIFORM_READ_BIT|VK_ACCESS_SHADER_READ_BIT|VK_ACCESS_SHADER_WRITE_BIT,0}, {VK_ACCESS_INPUT_ATTACHMENT_READ_BIT,VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT}, {VK_ACCESS_COLOR_ATTACHMENT_READ_BIT|VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}, {VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT|VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT|VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT}, {VK_ACCESS_TRANSFER_READ_BIT|VK_ACCESS_TRANSFER_WRITE_BIT,VK_PIPELINE_STAGE_TRANSFER_BIT}, {VK_ACCESS_HOST_READ_BIT|VK_ACCESS_HOST_WRITE_BIT,VK_PIPELINE_STAGE_HOST_BIT}, {VK_ACCESS_MEMORY_READ_BIT|VK_ACCESS_MEMORY_WRITE_BIT,UINT32_MAX} }; uint32_t supported=0; for (size_t j=0;jnext) if (row->parent == parent && row->kind != ignored) return 1; return 0; } static void bv_destroy_window(BvRow* row) { ((BvWindowContext*)row->context)->destroy(row); } static void bv_destroy_pool(BvRow* pool) { BvDevice* device = pool->parent->context; device->DestroyCommandPool(device->handle, (VkCommandPool)(uintptr_t)pool->handle, NULL); for (BvRow* row = bv_rows, *next; row; row = next) { next = row->next; if (row->parent == pool) bv_remove(row); } bv_remove(pool); } static void bv_swapchain_remove(BvRow* row); static void bv_surface_remove(BvRow* row); static void bv_destroy_device(BvRow* row) { BvDevice* device = row->context; for (;;) { BvRow* pool = NULL; for (BvRow* child = bv_rows; child; child = child->next) if (child->parent == row && child->kind == BV_POOL) { pool = child; break; } if (!pool) break; bv_destroy_pool(pool); } for (BvRow* child=bv_rows,*next;child;child=next) { next=child->next; if (child->parent==row && child->kind==BV_FENCE) { device->DestroyFence(device->handle,(VkFence)(uintptr_t)child->handle,NULL);bv_remove(child); } } device->convenience=NULL; const BvKind order[]={BV_QUERY_POOL,BV_PIPELINE,BV_LAYOUT,BV_DESCRIPTOR_SET,BV_DESCRIPTOR_POOL,BV_DESCRIPTOR_LAYOUT,BV_SAMPLER,BV_SHADER,BV_FRAMEBUFFER,BV_IMAGE_VIEW,BV_RENDER_PASS,BV_IMAGE,BV_BUFFER}; for (unsigned j=0;jnext; if (child->parent!=row || child->kind!=order[j]) continue; if (child->kind==BV_QUERY_POOL) device->DestroyQueryPool(device->handle,(VkQueryPool)(uintptr_t)child->handle,NULL); else if (child->kind==BV_PIPELINE) device->DestroyPipeline(device->handle,(VkPipeline)(uintptr_t)child->handle,NULL); else if (child->kind==BV_LAYOUT) device->DestroyPipelineLayout(device->handle,(VkPipelineLayout)(uintptr_t)child->handle,NULL); else if (child->kind==BV_DESCRIPTOR_SET) {bv_remove(child);continue;} else if (child->kind==BV_DESCRIPTOR_POOL) device->DestroyDescriptorPool(device->handle,(VkDescriptorPool)(uintptr_t)child->handle,NULL); else if (child->kind==BV_DESCRIPTOR_LAYOUT) device->DestroyDescriptorSetLayout(device->handle,(VkDescriptorSetLayout)(uintptr_t)child->handle,NULL); else if (child->kind==BV_SAMPLER) device->DestroySampler(device->handle,(VkSampler)(uintptr_t)child->handle,NULL); else if (child->kind==BV_SHADER) device->DestroyShaderModule(device->handle,(VkShaderModule)(uintptr_t)child->handle,NULL); else if (child->kind==BV_FRAMEBUFFER) device->DestroyFramebuffer(device->handle,(VkFramebuffer)(uintptr_t)child->handle,NULL); else if (child->kind==BV_RENDER_PASS) device->DestroyRenderPass(device->handle,(VkRenderPass)(uintptr_t)child->handle,NULL); else if (child->kind==BV_IMAGE_VIEW) device->DestroyImageView(device->handle,(VkImageView)(uintptr_t)child->handle,NULL); else if (child->kind==BV_IMAGE) {if(child->object.image.storage==BV_BORROWED_IMAGE)continue;device->DestroyImage(device->handle,(VkImage)(uintptr_t)child->handle,NULL);} else device->DestroyBuffer(device->handle,(VkBuffer)(uintptr_t)child->handle,NULL); bv_remove(child); } for (BvRow* child = bv_rows, *next; child; child = next) { next = child->next; if (child->parent == row && child->kind == BV_MEMORY) { device->FreeMemory(device->handle, (VkDeviceMemory)(uintptr_t)child->handle, NULL); bv_remove(child); } } for(BvRow* child=bv_rows,*next;child;child=next) {next=child->next;if(child->parent==row && child->kind==BV_SEMAPHORE) {device->DestroySemaphore(device->handle,(VkSemaphore)(uintptr_t)child->handle,NULL);bv_remove(child);}} for(;;) {BvRow* found=NULL;for(BvRow* child=bv_rows;child;child=child->next)if(child->parent==row && child->kind==BV_SWAPCHAIN) {found=child;break;}if(!found)break;bv_swapchain_remove(found);} device->DestroyDevice(device->handle, NULL); free(device); bv_remove(row); } static void bv_destroy_instance(BvRow* row) { BvInstance* instance = row->context; for (BvRow* child = bv_rows, *next; child; child = next) { next = child->next; if (child->parent == row && child->kind == BV_PHYSICAL) bv_remove(child); } for(BvRow* child=bv_rows,*next;child;child=next) {next=child->next;if(child->parent==row && child->kind==BV_SURFACE)bv_surface_remove(child);} instance->destroy(instance->handle, NULL); free(instance); bv_remove(row); } // Marshal string arrays for Vk*CreateInfo. Every failure still consumes the input. typedef struct { char** values; uint32_t count; int valid; } BvNames; static BvNames bv_names(Env e, Term list) { BvNames names = {NULL, 0, 1}; #ifdef CID(Con) while (term_aux(list) == CID(Con)) { Term fields[2]; bv_unpack(e, list, 2, fields); list = fields[1]; uint64_t length = 0; char* text = io_cstr(e, fields[0], &length); if (io_nul(text, length) || names.count >= 1024) names.valid = 0; char** more = realloc(names.values, (names.count+1)*sizeof(char*)); if (!more) { free(text); term_sink(e, list); names.valid = 0; break; } names.values = more; names.values[names.count++] = text; } #endif return names; } static void bv_names_free(BvNames names) { for (uint32_t j = 0; j < names.count; j++) free(names.values[j]); free(names.values); } #ifdef CID(Entry.load) static Term bv_entry_load(Env e, Term* f, IoWork* w) { void* library = dlopen("libvulkan.so.1", RTLD_NOW | RTLD_LOCAL); if (!library) return io_fail(e, 0x60000001u, dlerror()); BvEntry* entry = calloc(1, sizeof(*entry)); BvRow* row = entry ? bv_add(BV_ENTRY, NULL) : NULL; if (!row) { free(entry); dlclose(library); return io_fail(e, BV_LIMIT, "registry allocation failed"); } entry->library = library; entry->get = (PFN_vkGetInstanceProcAddr)dlsym(library, "vkGetInstanceProcAddr"); if (entry->get) { entry->create = (PFN_vkCreateInstance)entry->get(VK_NULL_HANDLE, "vkCreateInstance"); entry->version = (PFN_vkEnumerateInstanceVersion)entry->get(VK_NULL_HANDLE, "vkEnumerateInstanceVersion"); entry->layers = (PFN_vkEnumerateInstanceLayerProperties)entry->get(VK_NULL_HANDLE, "vkEnumerateInstanceLayerProperties"); entry->extensions = (PFN_vkEnumerateInstanceExtensionProperties)entry->get(VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties"); } if (!entry->get || !entry->create || !entry->layers || !entry->extensions) { bv_remove(row); free(entry); dlclose(library); return io_fail(e, 0x60000001u, "missing Vulkan loader entry points"); } row->context = entry; return io_done(e, term_pak(CID(Entry),row->id)); } #endif #ifdef CID(Entry.close) static Term bv_entry_close(Env e, Term* f, IoWork* w) { BvRow* entry = bv_get(bv_key(e, f[0]), BV_ENTRY); if (!entry) return io_fail(e, BV_INVALID, "Entry.close: invalid entry"); VkResult first = VK_SUCCESS; for (;;) { BvRow* found = NULL; for (BvRow* row = bv_rows; row; row = row->next) if (row->kind == BV_DEVICE && row->parent->parent == entry) { found = row; break; } if (!found) break; VkResult result = bv_idle(found); if(result==VK_SUCCESS)result=bv_drain_presentation(found); if (result != VK_SUCCESS && result != VK_ERROR_DEVICE_LOST) return bv_vk_error(e, result, "Entry.close / completion (entry remains live)"); if (first == VK_SUCCESS && result != VK_SUCCESS) first = result; bv_destroy_device(found); } for (;;) { BvRow* found = NULL; for (BvRow* row = bv_rows; row; row = row->next) if (row->kind == BV_INSTANCE && row->parent == entry) { found = row; break; } if (!found) break; bv_destroy_instance(found); } for(BvRow* child=bv_rows,*next;child;child=next) {next=child->next;if(child->parent==entry && child->kind==BV_WINDOW)bv_destroy_window(child);} BvEntry* context = entry->context; dlclose(context->library); free(context); bv_remove(entry); return first == VK_SUCCESS ? bv_ok(e) : bv_vk_error(e, first, "Entry.close / completion"); } #endif #ifdef CID(Entry.enumerate_instance_version) static Term bv_entry_version(Env e, Term* f, IoWork* w) { BvRow* row = bv_get(bv_key(e, f[0]), BV_ENTRY); if (!row) return io_fail(e, BV_INVALID, "invalid entry"); BvEntry* entry = row->context; uint32_t version = VK_API_VERSION_1_0; VkResult result = entry->version ? entry->version(&version) : VK_SUCCESS; return result == VK_SUCCESS ? io_done(e, version) : bv_vk_error(e, result, "vkEnumerateInstanceVersion"); } #endif #ifdef CID(Entry.create_instance) static Term bv_create_instance(Env e, Term* f, IoWork* w) { BvRow* owner = bv_get(bv_key(e, f[0]), BV_ENTRY); Term info[4]; bv_unpack(e, f[1], 4, info); uint64_t length = 0; char* app = io_cstr(e, info[0], &length); BvNames layers = bv_names(e, info[2]), extensions = bv_names(e, info[3]); int valid = owner && !io_nul(app, length) && layers.valid && extensions.valid; VkInstance handle = VK_NULL_HANDLE; VkResult result = VK_SUCCESS; if (valid) { VkApplicationInfo application = {.sType=VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName=app, .pEngineName="Bend", .apiVersion=(uint32_t)info[1]}; VkInstanceCreateInfo create = {.sType=VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pApplicationInfo=&application, .enabledLayerCount=layers.count, .ppEnabledLayerNames=(const char* const*)layers.values, .enabledExtensionCount=extensions.count, .ppEnabledExtensionNames=(const char* const*)extensions.values}; BvEntry* entry = owner->context; result = entry->create(&create, NULL, &handle); } bool presentation=false; unsigned profile=0; for(uint32_t j=0;jcontext; BvInstance* instance = calloc(1, sizeof(*instance)); PFN_vkDestroyInstance destroy = (PFN_vkDestroyInstance)entry->get(handle, "vkDestroyInstance"); if (!instance) { destroy(handle, NULL); return io_fail(e, BV_LIMIT, "instance allocation failed"); } instance->handle=handle; instance->destroy=destroy;instance->presentation=presentation; #define BV_INSTANCE_LOAD(field, name) instance->field=(PFN_vk##name)entry->get(handle, "vk" #name) BV_INSTANCE_LOAD(enumerate, EnumeratePhysicalDevices); BV_INSTANCE_LOAD(properties, GetPhysicalDeviceProperties); BV_INSTANCE_LOAD(queues, GetPhysicalDeviceQueueFamilyProperties); BV_INSTANCE_LOAD(memory, GetPhysicalDeviceMemoryProperties); BV_INSTANCE_LOAD(extensions, EnumerateDeviceExtensionProperties); BV_INSTANCE_LOAD(formats, GetPhysicalDeviceFormatProperties); BV_INSTANCE_LOAD(image_formats, GetPhysicalDeviceImageFormatProperties); BV_INSTANCE_LOAD(create_device, CreateDevice); BV_INSTANCE_LOAD(get_device, GetDeviceProcAddr); if (presentation) { instance->create_surface=entry->get(handle,"vkCreateXlibSurfaceKHR"); BV_INSTANCE_LOAD(destroy_surface, DestroySurfaceKHR); BV_INSTANCE_LOAD(surface_support, GetPhysicalDeviceSurfaceSupportKHR); BV_INSTANCE_LOAD(surface_caps, GetPhysicalDeviceSurfaceCapabilitiesKHR); BV_INSTANCE_LOAD(surface_formats, GetPhysicalDeviceSurfaceFormatsKHR); BV_INSTANCE_LOAD(present_modes, GetPhysicalDeviceSurfacePresentModesKHR); BV_INSTANCE_LOAD(features2, GetPhysicalDeviceFeatures2KHR); } #undef BV_INSTANCE_LOAD BvRow* row = NULL; if (destroy && instance->enumerate && instance->properties && instance->queues && instance->memory && instance->extensions && instance->formats && instance->image_formats && instance->create_device && instance->get_device && (!presentation || (instance->create_surface && instance->destroy_surface && instance->surface_support && instance->surface_caps && instance->surface_formats && instance->present_modes && instance->features2))) row=bv_add(BV_INSTANCE, owner); if (!row) { if (destroy) destroy(handle,NULL); free(instance); return io_fail(e,BV_LIMIT,"instance dispatch unavailable"); } row->context=instance; row->handle=(uint64_t)(uintptr_t)handle; return io_done(e,term_pak(CID(Instance),row->id)); } #endif #ifdef CID(Instance.destroy) static Term bv_destroy_instance_effect(Env e, Term* f, IoWork* w) { BvRow* row = bv_get(bv_key(e,f[0]),BV_INSTANCE); if (!row) return io_fail(e,BV_INVALID,"invalid instance"); if (bv_has_children(row,BV_PHYSICAL)) return io_fail(e,BV_LIFETIME,"instance still has devices or surfaces"); bv_destroy_instance(row); return bv_ok(e); } #endif #ifdef CID(Instance.enumerate_physical_devices) static Term bv_enumerate_physical_devices(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_INSTANCE); if (!owner) return io_fail(e,BV_INVALID,"invalid instance"); BvInstance* instance=owner->context; VkPhysicalDevice* devices=NULL; uint32_t count=0; VkResult result=VK_INCOMPLETE; for (unsigned retry=0; retry<8 && result==VK_INCOMPLETE; retry++) { free(devices); devices=NULL; result=instance->enumerate(instance->handle,&count,NULL); if (result!=VK_SUCCESS && result!=VK_INCOMPLETE) break; if (!count) {result=VK_SUCCESS;break;} if (count>4096) {free(devices);return io_fail(e,BV_LIMIT,"too many physical devices");} devices=calloc(count,sizeof(*devices)); if (!devices) return io_fail(e,BV_LIMIT,"enumeration allocation failed"); result=instance->enumerate(instance->handle,&count,devices); } if (result!=VK_SUCCESS) {free(devices);return bv_vk_error(e,result,"vkEnumeratePhysicalDevices");} Term list=term_pak(CID(Nil),0); for (uint32_t j=count;j>0;j--) { BvRow* row=NULL; for (BvRow* r=bv_rows;r;r=r->next) if (r->kind==BV_PHYSICAL && r->parent==owner && r->handle==(uint64_t)(uintptr_t)devices[j-1]) {row=r;break;} if (!row) row=bv_add(BV_PHYSICAL,owner); if (!row) {free(devices);term_sink(e,list);return io_fail(e,BV_LIMIT,"physical-device registry full");} row->handle=(uint64_t)(uintptr_t)devices[j-1]; list=io_node(e,CID(Con),term_pak(CID(PhysicalDevice),row->id),list); } free(devices);return io_done(e,list); } #endif #ifdef CID(Instance.get_physical_device_properties) static Term bv_physical_properties(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_INSTANCE); BvRow* physical=bv_child(bv_key(e,f[1]),BV_PHYSICAL,owner); if (!owner || !physical) return io_fail(e,BV_INVALID,"invalid physical device or instance"); BvInstance* instance=owner->context;VkPhysicalDeviceProperties properties; instance->properties((VkPhysicalDevice)(uintptr_t)physical->handle,&properties); Term fields[]={io_str(e,properties.deviceName,strlen(properties.deviceName)), properties.apiVersion, properties.driverVersion,properties.vendorID,properties.deviceID,properties.deviceType}; return io_done(e,bv_node(e,CID(PhysicalDeviceProperties),6,fields)); } #endif #ifdef CID(Instance.get_physical_device_queue_family_properties) static Term bv_queue_properties(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_INSTANCE); BvRow* physical=bv_child(bv_key(e,f[1]),BV_PHYSICAL,owner); if (!owner || !physical) return io_fail(e,BV_INVALID,"invalid physical device or instance"); BvInstance* instance=owner->context;uint32_t count=0; instance->queues((VkPhysicalDevice)(uintptr_t)physical->handle,&count,NULL); if (count>4096) return io_fail(e,BV_LIMIT,"too many queue families"); VkQueueFamilyProperties* values=calloc(count ? count : 1,sizeof(*values)); if (!values) return io_fail(e,BV_LIMIT,"queue allocation failed"); instance->queues((VkPhysicalDevice)(uintptr_t)physical->handle,&count,values); Term list=term_pak(CID(Nil),0); for (uint32_t j=count;j>0;j--) list=io_node(e,CID(Con),io_tup(e,values[j-1].queueFlags,values[j-1].queueCount),list); free(values);return io_done(e,list); } #endif #ifdef CID(Instance.memory_types_raw) static Term bv_memory_types(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_INSTANCE); BvRow* physical=bv_child(bv_key(e,f[1]),BV_PHYSICAL,owner); if (!owner || !physical) return io_fail(e,BV_INVALID,"invalid physical device or instance"); BvInstance* instance=owner->context;VkPhysicalDeviceMemoryProperties properties; instance->memory((VkPhysicalDevice)(uintptr_t)physical->handle,&properties); Term list=term_pak(CID(Nil),0); for (uint32_t j=properties.memoryTypeCount;j>0;j--) list=io_node(e,CID(Con),io_tup(e,properties.memoryTypes[j-1].propertyFlags,properties.memoryTypes[j-1].heapIndex),list); return io_done(e,list); } #endif static char* bv_optional_layer(Env e,Term optional,int* valid) { if (term_aux(optional)==CID(None)) return NULL; Term fields[1];bv_unpack(e,optional,1,fields); uint64_t length=0;char* layer=io_cstr(e,fields[0],&length); if (io_nul(layer,length)) *valid=0; return layer; } typedef enum { BV_LAYERS, BV_INSTANCE_EXTENSIONS, BV_DEVICE_EXTENSIONS } BvEnumerationKind; typedef struct { BvEnumerationKind kind;BvEntry* entry;BvInstance* instance;VkPhysicalDevice physical; } BvEnumeration; static VkResult bv_enumerate_call(BvEnumeration query,const char* layer,uint32_t* count,void* data) { switch (query.kind) { case BV_LAYERS: return query.entry->layers(count,data); case BV_INSTANCE_EXTENSIONS: return query.entry->extensions(layer,count,data); case BV_DEVICE_EXTENSIONS: return query.instance->extensions(query.physical,layer,count,data); } return VK_ERROR_INITIALIZATION_FAILED; } static uint32_t bv_enumerate(BvEnumeration query,const char* layer,size_t stride,uint32_t* count,void** data,VkResult* status) { *data=NULL;*count=0;*status=VK_INCOMPLETE; for (unsigned retry=0;retry<8;retry++) { free(*data);*data=NULL; *status=bv_enumerate_call(query,layer,count,NULL); if (*status!=VK_SUCCESS && *status!=VK_INCOMPLETE) return 0; if (!*count && *status==VK_SUCCESS) return 0; if (*count>4096 || *count>SIZE_MAX/stride) return BV_LIMIT; if (!*count) continue; *data=calloc(*count,stride); if (!*data) return BV_LIMIT; *status=bv_enumerate_call(query,layer,count,*data); if (*status!=VK_INCOMPLETE) return 0; } return 0; } #ifdef CID(Entry.enumerate_instance_layers) static Term bv_instance_layers(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_ENTRY); if (!owner) return io_fail(e,BV_INVALID,"enumerate_instance_layers: invalid entry"); BvEnumeration query={.kind=BV_LAYERS,.entry=owner->context}; uint32_t count=0;void* data=NULL;VkResult status; uint32_t code=bv_enumerate(query,NULL,sizeof(VkLayerProperties),&count,&data,&status); if (code || status!=VK_SUCCESS) {free(data);return code ? io_fail(e,code,"layer enumeration allocation limit") : bv_vk_error(e,status,"vkEnumerateInstanceLayerProperties");} VkLayerProperties* values=data;Term list=term_pak(CID(Nil),0); for (uint32_t j=count;j>0;j--) { VkLayerProperties* p=&values[j-1]; Term fields[]={io_str(e,p->layerName,strnlen(p->layerName,VK_MAX_EXTENSION_NAME_SIZE)),p->specVersion,p->implementationVersion, io_str(e,p->description,strnlen(p->description,VK_MAX_DESCRIPTION_SIZE))}; list=io_node(e,CID(Con),bv_node(e,CID(LayerProperties),4,fields),list); } free(data);return io_done(e,list); } #endif #if defined(CID(Entry.enumerate_instance_extensions)) || defined(CID(Instance.enumerate_device_extensions)) static Term bv_extension_properties(Env e,BvEnumeration query,char* layer,int valid) { if (!valid) {free(layer);return io_fail(e,BV_ARGUMENT,"extension layer contains NUL");} uint32_t count=0;void* data=NULL;VkResult status; uint32_t code=bv_enumerate(query,layer,sizeof(VkExtensionProperties),&count,&data,&status);free(layer); if (code || status!=VK_SUCCESS) {free(data);return code ? io_fail(e,code,"extension enumeration allocation limit") : bv_vk_error(e,status,query.kind==BV_INSTANCE_EXTENSIONS ? "vkEnumerateInstanceExtensionProperties" : "vkEnumerateDeviceExtensionProperties");} VkExtensionProperties* values=data;Term list=term_pak(CID(Nil),0); for (uint32_t j=count;j>0;j--) { VkExtensionProperties* p=&values[j-1]; Term fields[]={io_str(e,p->extensionName,strnlen(p->extensionName,VK_MAX_EXTENSION_NAME_SIZE)),p->specVersion}; list=io_node(e,CID(Con),bv_node(e,CID(ExtensionProperties),2,fields),list); } free(data);return io_done(e,list); } #endif #ifdef CID(Entry.enumerate_instance_extensions) static Term bv_instance_extensions(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_ENTRY);int valid=1;char* layer=bv_optional_layer(e,f[1],&valid); if (!owner) {free(layer);return io_fail(e,BV_INVALID,"enumerate_instance_extensions: invalid entry");} return bv_extension_properties(e,(BvEnumeration){.kind=BV_INSTANCE_EXTENSIONS,.entry=owner->context},layer,valid); } #endif #ifdef CID(Instance.enumerate_device_extensions) static Term bv_device_extensions(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_INSTANCE);BvRow* physical=bv_child(bv_key(e,f[1]),BV_PHYSICAL,owner); int valid=1;char* layer=bv_optional_layer(e,f[2],&valid); if (!owner || !physical) {free(layer);return io_fail(e,BV_INVALID,"enumerate_device_extensions: invalid physical device");} return bv_extension_properties(e,(BvEnumeration){.kind=BV_DEVICE_EXTENSIONS,.instance=owner->context, .physical=(VkPhysicalDevice)(uintptr_t)physical->handle},layer,valid); } #endif #ifdef CID(Instance.memory_heaps_raw) static Term bv_memory_heaps(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_INSTANCE);BvRow* physical=bv_child(bv_key(e,f[1]),BV_PHYSICAL,owner); if (!owner || !physical) return io_fail(e,BV_INVALID,"memory_heaps: invalid physical device"); BvInstance* instance=owner->context;VkPhysicalDeviceMemoryProperties properties; instance->memory((VkPhysicalDevice)(uintptr_t)physical->handle,&properties); Term list=term_pak(CID(Nil),0); for (uint32_t j=properties.memoryHeapCount;j>0;j--) list=io_node(e,CID(Con),io_tup(e,bv_words(e,properties.memoryHeaps[j-1].size),properties.memoryHeaps[j-1].flags),list); return io_done(e,list); } #endif #ifdef CID(Instance.get_physical_device_format_properties) static Term bv_format_properties(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_INSTANCE);BvRow* physical=bv_child(bv_key(e,f[1]),BV_PHYSICAL,owner); if (!owner || !physical) return io_fail(e,BV_INVALID,"format_properties: invalid physical device"); if ((uint32_t)f[2]>VK_FORMAT_ASTC_12x12_SRGB_BLOCK) return io_fail(e,BV_ARGUMENT,"format_properties: expected core Vulkan 1.0 format"); BvInstance* instance=owner->context;VkFormatProperties properties; instance->formats((VkPhysicalDevice)(uintptr_t)physical->handle,(VkFormat)(uint32_t)f[2],&properties); Term fields[]={properties.linearTilingFeatures,properties.optimalTilingFeatures,properties.bufferFeatures}; return io_done(e,bv_node(e,CID(FormatProperties),3,fields)); } #endif #ifdef CID(Instance.limits_raw) static Term bv_physical_limits(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_INSTANCE);BvRow* physical=bv_child(bv_key(e,f[1]),BV_PHYSICAL,owner); if (!owner || !physical) return io_fail(e,BV_INVALID,"limits: invalid physical device"); BvInstance* instance=owner->context;VkPhysicalDeviceProperties properties; instance->properties((VkPhysicalDevice)(uintptr_t)physical->handle,&properties);VkPhysicalDeviceLimits* p=&properties.limits; uint32_t values[]={p->maxImageDimension2D,p->maxFramebufferWidth,p->maxFramebufferHeight,p->maxColorAttachments,p->maxPushConstantsSize, p->maxVertexInputAttributes,p->maxVertexInputBindings,p->maxVertexInputAttributeOffset,p->maxVertexInputBindingStride,p->maxMemoryAllocationCount}; Term result=io_tup(e,bv_words(e,p->nonCoherentAtomSize),io_tup(e,bv_words(e,p->optimalBufferCopyOffsetAlignment),io_tup(e,bv_words(e,p->optimalBufferCopyRowPitchAlignment),bv_words(e,p->bufferImageGranularity)))); for (unsigned j=10;j>0;j--) result=io_tup(e,values[j-1],result); return io_done(e,result); } #endif static int bv_device_extension(BvInstance* instance,VkPhysicalDevice physical,const char* wanted) { VkExtensionProperties* values=NULL;VkResult result=VK_INCOMPLETE;uint32_t count=0;int found=0; for(unsigned retry=0;retry<8 && result==VK_INCOMPLETE;retry++) { free(values);values=NULL;result=instance->extensions(physical,NULL,&count,NULL); if(result!=VK_SUCCESS && result!=VK_INCOMPLETE)break; if(!count || count>4096)break; values=calloc(count,sizeof(*values));if(!values)break; result=instance->extensions(physical,NULL,&count,values); } if(result==VK_SUCCESS && values)for(uint32_t j=0;jcontext; if(!instance->presentation || !instance->features2 || !instance->surface_support || !instance->surface_caps || !instance->surface_formats || !instance->present_modes)return 0; VkPhysicalDevice handle=(VkPhysicalDevice)(uintptr_t)physical->handle; if(!bv_device_extension(instance,handle,"VK_KHR_swapchain") || !bv_device_extension(instance,handle,"VK_EXT_swapchain_maintenance1"))return 0; VkPhysicalDeviceSwapchainMaintenance1FeaturesEXT maintenance={.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_EXT}; VkPhysicalDeviceFeatures2 features={.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2,.pNext=&maintenance};instance->features2(handle,&features); return maintenance.swapchainMaintenance1==VK_TRUE; } #ifdef CID(Instance.presentation_supported) static Term bv_presentation_supported_run(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_INSTANCE),*physical=bv_child(bv_key(e,f[1]),BV_PHYSICAL,owner); if(!owner || !physical)return io_fail(e,BV_INVALID,"presentation support ownership"); return io_done(e,term_pak(bv_presentation_supported(owner,physical) ? CID(True) : CID(False),0)); } #endif static void bv_surface_remove(BvRow* row) { BvInstance* instance=row->parent->context;instance->destroy_surface(instance->handle,(VkSurfaceKHR)(uintptr_t)row->handle,NULL);bv_remove(row); } #ifdef CID(Instance.destroy_surface) static Term bv_destroy_surface(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_INSTANCE),*row=bv_child(bv_key(e,f[1]),BV_SURFACE,owner); if(!owner || !row)return io_fail(e,BV_INVALID,"surface ownership"); if(bv_referenced(row))return io_fail(e,BV_LIFETIME,"surface retained by swapchain"); bv_surface_remove(row);return bv_ok(e); } #endif static int bv_surface_args(Env e,Term* f,BvRow** owner,BvRow** physical,BvRow** surface) { *owner=bv_get(bv_key(e,f[0]),BV_INSTANCE);*physical=bv_child(bv_key(e,f[1]),BV_PHYSICAL,*owner);*surface=bv_child(bv_key(e,f[2]),BV_SURFACE,*owner); return *owner && *physical && *surface; } #ifdef CID(Instance.surface_capabilities) static Term bv_surface_capabilities(Env e,Term* f,IoWork* w) { BvRow *owner,*physical,*surface;if(!bv_surface_args(e,f,&owner,&physical,&surface))return io_fail(e,BV_INVALID,"surface query ownership"); BvInstance* instance=owner->context;VkSurfaceCapabilitiesKHR out;VkResult result=instance->surface_caps((VkPhysicalDevice)(uintptr_t)physical->handle,(VkSurfaceKHR)(uintptr_t)surface->handle,&out); if(result!=VK_SUCCESS)return bv_vk_error(e,result,"vkGetPhysicalDeviceSurfaceCapabilitiesKHR"); Term p[]={out.minImageCount,out.maxImageCount,out.currentExtent.width,out.currentExtent.height,out.minImageExtent.width,out.minImageExtent.height,out.maxImageExtent.width,out.maxImageExtent.height,out.supportedTransforms,out.currentTransform,out.supportedCompositeAlpha,out.supportedUsageFlags}; return io_done(e,bv_node(e,CID(SurfaceCapabilities),12,p)); } #endif static VkResult bv_query_formats(BvInstance* instance,VkPhysicalDevice physical,VkSurfaceKHR surface,uint32_t* count,VkSurfaceFormatKHR** values) { VkResult result=VK_INCOMPLETE;*values=NULL; for(unsigned retry=0;retry<8 && result==VK_INCOMPLETE;retry++) { free(*values);*values=NULL;result=instance->surface_formats(physical,surface,count,NULL); if(result!=VK_SUCCESS && result!=VK_INCOMPLETE)break; if(!*count)break;if(*count>4096)return VK_ERROR_OUT_OF_HOST_MEMORY; *values=calloc(*count,sizeof(**values));if(!*values)return VK_ERROR_OUT_OF_HOST_MEMORY; result=instance->surface_formats(physical,surface,count,*values); }return result; } static VkResult bv_query_modes(BvInstance* instance,VkPhysicalDevice physical,VkSurfaceKHR surface,uint32_t* count,VkPresentModeKHR** values) { VkResult result=VK_INCOMPLETE;*values=NULL; for(unsigned retry=0;retry<8 && result==VK_INCOMPLETE;retry++) { free(*values);*values=NULL;result=instance->present_modes(physical,surface,count,NULL); if(result!=VK_SUCCESS && result!=VK_INCOMPLETE)break; if(!*count)break;if(*count>4096)return VK_ERROR_OUT_OF_HOST_MEMORY; *values=calloc(*count,sizeof(**values));if(!*values)return VK_ERROR_OUT_OF_HOST_MEMORY; result=instance->present_modes(physical,surface,count,*values); }return result; } #ifdef CID(Instance.surface_formats) static Term bv_surface_formats(Env e,Term* f,IoWork* w) { BvRow *owner,*physical,*surface;if(!bv_surface_args(e,f,&owner,&physical,&surface))return io_fail(e,BV_INVALID,"surface query ownership"); uint32_t count=0;VkSurfaceFormatKHR* values=NULL;VkResult result=bv_query_formats(owner->context,(VkPhysicalDevice)(uintptr_t)physical->handle,(VkSurfaceKHR)(uintptr_t)surface->handle,&count,&values); if(result!=VK_SUCCESS) {free(values);return bv_vk_error(e,result,"surface formats");} Term list=term_pak(CID(Nil),0);for(uint32_t j=count;j;j--)list=io_node(e,CID(Con),io_tup(e,values[j-1].format,values[j-1].colorSpace),list); free(values);return io_done(e,list); } #endif #ifdef CID(Instance.present_modes) static Term bv_present_modes(Env e,Term* f,IoWork* w) { BvRow *owner,*physical,*surface;if(!bv_surface_args(e,f,&owner,&physical,&surface))return io_fail(e,BV_INVALID,"surface query ownership"); uint32_t count=0;VkPresentModeKHR* values=NULL;VkResult result=bv_query_modes(owner->context,(VkPhysicalDevice)(uintptr_t)physical->handle,(VkSurfaceKHR)(uintptr_t)surface->handle,&count,&values); if(result!=VK_SUCCESS) {free(values);return bv_vk_error(e,result,"present modes");} Term list=term_pak(CID(Nil),0);for(uint32_t j=count;j;j--)list=io_node(e,CID(Con),(uint32_t)values[j-1],list); free(values);return io_done(e,list); } #endif #ifdef CID(Instance.present_support) static Term bv_present_support(Env e,Term* f,IoWork* w) { BvRow *owner,*physical,*surface;if(!bv_surface_args(e,f,&owner,&physical,&surface))return io_fail(e,BV_INVALID,"surface query ownership"); BvInstance* instance=owner->context;uint32_t count=0;instance->queues((VkPhysicalDevice)(uintptr_t)physical->handle,&count,NULL); if((uint32_t)f[3]>=count)return io_fail(e,BV_ARGUMENT,"present family out of range");VkBool32 supported=0; VkResult result=instance->surface_support((VkPhysicalDevice)(uintptr_t)physical->handle,f[3],(VkSurfaceKHR)(uintptr_t)surface->handle,&supported); return result==VK_SUCCESS ? io_done(e,term_pak(supported ? CID(True) : CID(False),0)) : bv_vk_error(e,result,"present support"); } #endif #if defined(CID(Instance.create_device)) || defined(CID(Instance.create_presentation_device)) static Term bv_create_device_engine(Env e, Term* f, IoWork* w,bool presentation) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_INSTANCE); BvRow* physical=bv_child(bv_key(e,f[1]),BV_PHYSICAL,owner); Term info[3];bv_unpack(e,f[2],presentation ? 3 : 2,info); Term names=presentation ? io_node(e,CID(Con),io_str(e,"VK_KHR_swapchain",16),io_node(e,CID(Con),io_str(e,"VK_EXT_swapchain_maintenance1",29),term_pak(CID(Nil),0))) : info[1]; BvNames extensions=bv_names(e,names); uint32_t present_family=presentation ? (uint32_t)info[1] : (uint32_t)info[0]; BvRow* surface=presentation ? bv_child((uint32_t)info[2],BV_SURFACE,owner) : NULL; if(presentation && (!owner || !physical || !surface || !bv_presentation_supported(owner,physical))) {bv_names_free(extensions);return io_fail(e,BV_ARGUMENT,"presentation requires swapchain maintenance1 and surface profile");} if (!owner || !physical || !extensions.valid) { bv_names_free(extensions);return io_fail(e,BV_INVALID,"invalid physical device or extensions"); } BvInstance* instance=owner->context;uint32_t count=0; VkPhysicalDevice handle=(VkPhysicalDevice)(uintptr_t)physical->handle; instance->queues(handle,&count,NULL); if ((uint32_t)info[0]>=count || present_family>=count || count>4096) {bv_names_free(extensions);return io_fail(e,BV_ARGUMENT,"queue family out of range");} VkQueueFamilyProperties* queues=calloc(count,sizeof(*queues)); if (!queues) {bv_names_free(extensions);return io_fail(e,BV_LIMIT,"queue allocation failed");} instance->queues(handle,&count,queues); int valid=queues[(uint32_t)info[0]].queueCount>0 && queues[present_family].queueCount>0; VkBool32 supported=0; if(presentation) {VkResult r=instance->surface_support(handle,present_family,(VkSurfaceKHR)(uintptr_t)surface->handle,&supported);valid &= r==VK_SUCCESS && supported && (queues[(uint32_t)info[0]].queueFlags&VK_QUEUE_GRAPHICS_BIT);} VkQueueFamilyProperties queue_properties=queues[(uint32_t)info[0]]; uint32_t queue_flags=queue_properties.queueFlags;free(queues); if (!valid) {bv_names_free(extensions);return io_fail(e,BV_ARGUMENT,"empty queue family");} float priority=1.0f; VkDeviceQueueCreateInfo queue={.sType=VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, .queueFamilyIndex=(uint32_t)info[0],.queueCount=1,.pQueuePriorities=&priority}; VkDeviceQueueCreateInfo requested[2]={queue,queue};requested[1].queueFamilyIndex=present_family; VkPhysicalDeviceSwapchainMaintenance1FeaturesEXT maintenance={.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_EXT,.swapchainMaintenance1=VK_TRUE}; VkDeviceCreateInfo create={.sType=VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,.pNext=presentation ? &maintenance : NULL, .queueCreateInfoCount=present_family==(uint32_t)info[0] ? 1 : 2,.pQueueCreateInfos=requested,.enabledExtensionCount=extensions.count, .ppEnabledExtensionNames=(const char* const*)extensions.values}; VkDevice device;VkResult result=instance->create_device(handle,&create,NULL,&device); bv_names_free(extensions); if (result!=VK_SUCCESS) return bv_vk_error(e,result,"vkCreateDevice"); BvDevice* context=calloc(1,sizeof(*context)); PFN_vkDestroyDevice destroy=(PFN_vkDestroyDevice)instance->get_device(device,"vkDestroyDevice"); if (!context) {destroy(device,NULL);return io_fail(e,BV_LIMIT,"device allocation failed");} context->handle=device;context->physical=handle;context->presentation=presentation;context->present_family=present_family;context->family=(uint32_t)info[0];context->queue_flags=queue_flags;context->queue_properties=queue_properties; VkPhysicalDeviceProperties properties;instance->properties(handle,&properties);context->limits=properties.limits; int complete=1; #define BV_LOAD(name) context->name=(PFN_vk##name)instance->get_device(device,"vk" #name); complete &= context->name!=NULL; BV_DEVICE_FUNCTIONS(BV_LOAD) if(presentation) { BV_LOAD(CreateSwapchainKHR) BV_LOAD(DestroySwapchainKHR) BV_LOAD(GetSwapchainImagesKHR) BV_LOAD(AcquireNextImageKHR) BV_LOAD(QueuePresentKHR) BV_LOAD(ReleaseSwapchainImagesEXT) BV_LOAD(CreateSemaphore) BV_LOAD(DestroySemaphore) } #undef BV_LOAD BvRow* row=complete ? bv_add(BV_DEVICE,owner) : NULL; if (!row) {if(destroy)destroy(device,NULL);free(context);return io_fail(e,BV_LIMIT,"device dispatch unavailable");} context->GetDeviceQueue(device,context->family,0,&context->queue); context->GetDeviceQueue(device,context->present_family,0,&context->present_queue); instance->memory(handle,&context->memory);row->context=context; return io_done(e,term_pak(CID(Device),row->id)); } #endif #ifdef CID(Instance.create_device) static Term bv_create_device(Env e,Term* f,IoWork* w) {return bv_create_device_engine(e,f,w,false);} #endif #ifdef CID(Instance.create_presentation_device) static Term bv_create_presentation_device(Env e,Term* f,IoWork* w) {return bv_create_device_engine(e,f,w,true);} #endif #ifdef CID(Device.destroy) static Term bv_destroy_device_effect(Env e, Term* f, IoWork* w) { BvRow* row=bv_get(bv_key(e,f[0]),BV_DEVICE); if (!row) return io_fail(e,BV_INVALID,"invalid device"); BvDevice* device=row->context; for (BvRow* child=bv_rows;child;child=child->next) if (child->parent==row && child!=device->convenience) return io_fail(e,BV_LIFETIME,"device still has resources"); VkResult result=bv_idle(row); if (result!=VK_SUCCESS && result!=VK_ERROR_DEVICE_LOST) return bv_vk_error(e,result,"vkDeviceWaitIdle"); bv_destroy_device(row); return result==VK_SUCCESS ? bv_ok(e) : bv_vk_error(e,result,"Device.destroy"); } #endif #ifdef CID(Device.wait_idle) static Term bv_device_wait_idle(Env e, Term* f, IoWork* w) { BvRow* row=bv_get(bv_key(e,f[0]),BV_DEVICE); if (!row) return io_fail(e,BV_INVALID,"invalid device"); VkResult result=bv_idle(row); return result==VK_SUCCESS ? bv_ok(e) : bv_vk_error(e,result,"vkDeviceWaitIdle"); } #endif #ifdef CID(Device.create_buffer) static Term bv_create_buffer(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE); // The compiler flattens BufferCreateInfo's single-constructor U64 field. Term info[3];bv_unpack(e,f[1],3,info); uint64_t size=((uint64_t)(uint32_t)info[1]<<32)|(uint32_t)info[0]; if (!owner) return io_fail(e,BV_INVALID,"invalid device"); if (!size || !(uint32_t)info[2]) return io_fail(e,BV_ARGUMENT,"buffer size and usage must be nonzero"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"bv_create_buffer"); BvDevice* device=owner->context; VkBufferCreateInfo create={.sType=VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size=size,.usage=(uint32_t)info[2],.sharingMode=VK_SHARING_MODE_EXCLUSIVE}; VkBuffer buffer;VkResult result=device->CreateBuffer(device->handle,&create,NULL,&buffer); if (result!=VK_SUCCESS) return bv_device_error(e,owner,result,"vkCreateBuffer"); BvRow* row=bv_add(BV_BUFFER,owner); if (!row) {device->DestroyBuffer(device->handle,buffer,NULL);return io_fail(e,BV_LIMIT,"buffer registry full");} row->handle=(uint64_t)(uintptr_t)buffer;row->size=size;row->flags=(uint32_t)info[2]; device->GetBufferMemoryRequirements(device->handle,buffer,&row->requirements); return io_done(e,term_pak(CID(Buffer),row->id)); } #endif #ifdef CID(Device.destroy_buffer) static Term bv_destroy_buffer(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE); BvRow* buffer=bv_child(bv_key(e,f[1]),BV_BUFFER,owner); if (!owner || !buffer) return io_fail(e,BV_INVALID,"invalid buffer or device"); if (buffer->retired || bv_referenced(buffer)) return io_fail(e,BV_LIFETIME,"command pool still references buffer"); BvDevice* device=owner->context; device->DestroyBuffer(device->handle,(VkBuffer)(uintptr_t)buffer->handle,NULL); bv_remove(buffer);return bv_ok(e); } #endif typedef struct { BvRow* buffer; BvRow* memory; } BvRetirement; static uint32_t bv_validate_retirement(BvRow* owner,BvRetirement item) { BvRow* buffer=item.buffer,*memory=item.memory; if (!buffer || !memory || buffer->parent!=owner || memory->parent!=owner) return BV_INVALID; if (bv_bound_memory(buffer)!=memory || bv_bound_offset(buffer)!=0) return BV_ARGUMENT; for (BvRow* row=bv_rows;row;row=row->next) if (row->kind==BV_COMMAND && bv_command_device(row)==owner && row->command.phase==BV_RECORDING && bv_may_reach_depth(row,buffer,BV_KIND_COUNT)) return BV_LIFETIME; for (BvRow* row=bv_rows;row;row=row->next) for (BvDep* dep=row->deps;dep;dep=dep->next) if (dep->target==memory && row!=buffer) return BV_LIFETIME; return 0; } #ifdef CID(Device.retire_buffers) static Term bv_retire_buffers(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE); uint32_t code=!owner ? BV_INVALID : bv_lost(owner) ? (uint32_t)VK_ERROR_DEVICE_LOST : 0; BvRetirement local[8],*items=local;size_t count=0,capacity=8; Term list=f[1]; while (term_aux(list)==CID(Con)) { Term node[2],pair[2];bv_unpack(e,list,2,node);list=node[1];bv_unpack(e,node[0],2,pair); uint32_t buffer=bv_key(e,pair[0]),memory=bv_key(e,pair[1]); if (code) continue; if (count==capacity) { if (capacity>SIZE_MAX/2/sizeof(*items)) {code=BV_LIMIT;continue;} size_t next=capacity*2; BvRetirement* grown=items==local ? malloc(next*sizeof(*items)) : realloc(items,next*sizeof(*items)); if (!grown) {code=BV_LIMIT;continue;} if (items==local) memcpy(grown,local,count*sizeof(*items)); items=grown;capacity=next; } items[count++]=(BvRetirement){bv_child(buffer,BV_BUFFER,owner),bv_child(memory,BV_MEMORY,owner)}; } if (!code && term_aux(list)!=CID(Nil)) code=BV_ARGUMENT; for (size_t j=0;!code && jretired=true;items[j].memory->retired=true;} if (items!=local) free(items); return code ? io_fail(e,code,"retire_buffers rejected complete allocation set before sealing") : bv_ok(e); } #endif #ifdef CID(Device.collect_retired) static Term bv_collect_retired(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE); if (!owner) return io_fail(e,BV_INVALID,"collect_retired device"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"collect_retired"); BvDevice* device=owner->context; for (BvRow* row=bv_rows,*next;row;row=next) { next=row->next; if (row->parent!=owner || row->kind!=BV_BUFFER || !row->retired || bv_referenced(row)) continue; BvRow* memory=bv_bound_memory(row); device->DestroyBuffer(device->handle,(VkBuffer)(uintptr_t)row->handle,NULL); bv_remove(row); if (next==memory) next=memory->next; device->FreeMemory(device->handle,(VkDeviceMemory)(uintptr_t)memory->handle,NULL); bv_remove(memory); } return bv_ok(e); } #endif #ifdef CID(Device.buffer_requirements_raw) static Term bv_buffer_requirements(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE); BvRow* buffer=bv_child(bv_key(e,f[1]),BV_BUFFER,owner); if (!owner || !buffer) return io_fail(e,BV_INVALID,"invalid buffer or device"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"bv_buffer_requirements"); BvDevice* device=owner->context;VkMemoryRequirements requirements; requirements=buffer->requirements; return io_done(e,io_tup(e,bv_words(e,requirements.size), io_tup(e,bv_words(e,requirements.alignment),requirements.memoryTypeBits))); } #endif #ifdef CID(Device.allocate_memory) static Term bv_allocate_memory(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);uint64_t size=bv_u64(e,f[1]); if (!owner) return io_fail(e,BV_INVALID,"invalid device"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"bv_allocate_memory"); BvDevice* device=owner->context;uint32_t index=(uint32_t)f[2]; if (!size || index>=device->memory.memoryTypeCount) return io_fail(e,BV_ARGUMENT,"invalid allocation size or memory type"); VkMemoryAllocateInfo info={.sType=VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,.allocationSize=size,.memoryTypeIndex=index}; VkDeviceMemory memory;VkResult result=device->AllocateMemory(device->handle,&info,NULL,&memory); if (result!=VK_SUCCESS) return bv_device_error(e,owner,result,"vkAllocateMemory"); BvRow* row=bv_add(BV_MEMORY,owner); if (!row) {device->FreeMemory(device->handle,memory,NULL);return io_fail(e,BV_LIMIT,"memory registry full");} row->handle=(uint64_t)(uintptr_t)memory;row->size=size; row->flags=device->memory.memoryTypes[index].propertyFlags;row->memory_type=index; return io_done(e,term_pak(CID(DeviceMemory),row->id)); } #endif #ifdef CID(Device.free_memory) static Term bv_free_memory(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE); BvRow* memory=bv_child(bv_key(e,f[1]),BV_MEMORY,owner); if (!owner || !memory) return io_fail(e,BV_INVALID,"invalid memory or device"); if (memory->retired || bv_referenced(memory)) return io_fail(e,BV_LIFETIME,"destroy bound resources before freeing memory"); BvDevice* device=owner->context; device->FreeMemory(device->handle,(VkDeviceMemory)(uintptr_t)memory->handle,NULL); bv_remove(memory);return bv_ok(e); } #endif static uint32_t bv_binding_check(BvRow* resource,BvRow* memory,uint64_t offset) { if (resource->retired || memory->retired) return BV_LIFETIME; if ((resource->kind==BV_IMAGE && resource->object.image.storage==BV_BORROWED_IMAGE) || bv_bound_memory(resource)) return BV_LIFETIME; VkMemoryRequirements r=resource->requirements; if (!r.size || !r.alignment || offset>memory->size || r.size>memory->size-offset || offset%r.alignment || !(r.memoryTypeBits & (1u<memory_type))) return BV_ARGUMENT; uint64_t end=offset+r.size; BvDevice* device=resource->parent->context; uint64_t g=device->limits.bufferImageGranularity; for (BvRow* peer=bv_rows;peer;peer=peer->next) { if (peer==resource || bv_bound_memory(peer)!=memory || (peer->kind!=BV_IMAGE && resource->kind!=BV_IMAGE)) continue; uint64_t a=bv_bound_offset(peer),b=a+peer->requirements.size; if (offsetkind!=resource->kind && g && (offset/g<=(b-1)/g && a/g<=(end-1)/g)) return BV_ARGUMENT; } return 0; } static Term bv_bind_resource(Env e,Term* f,BvKind kind) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE); BvRow* resource=bv_child(bv_key(e,f[1]),kind,owner); BvRow* memory=bv_child(bv_key(e,f[2]),BV_MEMORY,owner);uint64_t offset=bv_u64(e,f[3]); if (!owner || !resource || !memory) return io_fail(e,BV_INVALID,"resource and memory must belong to device"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"bind memory"); uint32_t code=bv_binding_check(resource,memory,offset); if (code) return io_fail(e,code,"binding violates lifetime, requirements, overlap or granularity"); BvDep* binding=malloc(sizeof(*binding)); if (!binding) return io_fail(e,BV_LIMIT,"binding allocation failed"); *binding=(BvDep){.target=memory,.role=BV_DEP_BINDING,.data.binding={offset}}; BvDevice* device=owner->context; VkResult result=kind==BV_BUFFER ? device->BindBufferMemory(device->handle,(VkBuffer)(uintptr_t)resource->handle, (VkDeviceMemory)(uintptr_t)memory->handle,offset) : device->BindImageMemory(device->handle,(VkImage)(uintptr_t)resource->handle, (VkDeviceMemory)(uintptr_t)memory->handle,offset); if (result!=VK_SUCCESS) {free(binding);return bv_device_error(e,owner,result,"vkBind resource memory");} resource->deps=binding;return bv_ok(e); } #ifdef CID(Device.bind_buffer_memory) static Term bv_bind_buffer_memory(Env e,Term* f,IoWork* w) { return bv_bind_resource(e,f,BV_BUFFER); } #endif #ifdef CID(Device.bind_image_memory) static Term bv_bind_image_memory(Env e,Term* f,IoWork* w) { return bv_bind_resource(e,f,BV_IMAGE); } #endif typedef struct { VkFormat format; VkImageAspectFlags aspect; uint32_t bytes; } BvFormat; static const BvFormat bv_formats[]={ {VK_FORMAT_R8G8B8A8_UNORM,VK_IMAGE_ASPECT_COLOR_BIT,4}, {VK_FORMAT_R8G8B8A8_SRGB,VK_IMAGE_ASPECT_COLOR_BIT,4}, {VK_FORMAT_B8G8R8A8_UNORM,VK_IMAGE_ASPECT_COLOR_BIT,4}, {VK_FORMAT_B8G8R8A8_SRGB,VK_IMAGE_ASPECT_COLOR_BIT,4}, {VK_FORMAT_D16_UNORM,VK_IMAGE_ASPECT_DEPTH_BIT,2}, {VK_FORMAT_D32_SFLOAT,VK_IMAGE_ASPECT_DEPTH_BIT,4} }; static const BvFormat* bv_format(VkFormat format) { for (unsigned j=0;jVK_FORMAT_ASTC_12x12_SRGB_BLOCK || type>VK_IMAGE_TYPE_3D || tiling>VK_IMAGE_TILING_LINEAR || !usage || (usage&~255u) || (flags&~31u)) return 0; if ((flags&(VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT|VK_IMAGE_CREATE_SPARSE_ALIASED_BIT)) && !(flags&VK_IMAGE_CREATE_SPARSE_BINDING_BIT)) return 0; if ((flags&VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT) && type!=VK_IMAGE_TYPE_2D) return 0; if ((usage&VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) && (!(usage&(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT|VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT|VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)) || (usage&~(VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT|VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT|VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT|VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)))) return 0; return 1; } static int bv_image_features(BvInstance* instance,VkPhysicalDevice physical,VkFormat format,VkImageUsageFlags usage) { VkFormatProperties p;instance->formats(physical,format,&p); VkFormatFeatureFlags required=0; if (usage&VK_IMAGE_USAGE_SAMPLED_BIT) required|=VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT; if (usage&VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) required|=VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT; if (usage&VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) required|=VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT; return (p.optimalTilingFeatures&required)==required; } static uint32_t bv_mip_dimension(uint32_t base,uint32_t level) { return level>=32 || !(base>>level) ? 1 : base>>level; } static int bv_range_contains(uint32_t limit,uint32_t base,uint32_t count) { return count && baseobject.image; return r.aspectMask==bv_format(i->format)->aspect && bv_range_contains(i->mips,r.baseMipLevel,r.levelCount) && bv_range_contains(i->layers,r.baseArrayLayer,r.layerCount); } #ifdef CID(Instance.image_format_properties_raw) static Term bv_image_format_properties(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_INSTANCE),*physical=bv_child(bv_key(e,f[1]),BV_PHYSICAL,owner); Term p[5];bv_unpack(e,f[2],5,p); if (!owner || !physical) return io_fail(e,BV_INVALID,"image format query ownership"); if (!bv_image_configuration(p[0],p[1],p[2],p[3],p[4])) return io_fail(e,BV_ARGUMENT,"invalid core image configuration"); BvInstance* instance=owner->context;VkImageFormatProperties out; VkResult result=instance->image_formats((VkPhysicalDevice)(uintptr_t)physical->handle,p[0],p[1],p[2],p[3],p[4],&out); if (result!=VK_SUCCESS) return bv_vk_error(e,result,"vkGetPhysicalDeviceImageFormatProperties"); return io_done(e,io_tup(e,io_tup(e,out.maxExtent.width,out.maxExtent.height), io_tup(e,io_tup(e,out.maxExtent.depth,out.maxMipLevels),io_tup(e,io_tup(e,out.maxArrayLayers,out.sampleCounts),bv_words(e,out.maxResourceSize))))); } #endif #ifdef CID(Device.create_image) static Term bv_create_image(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);Term p[6];bv_unpack(e,f[1],6,p); if (!owner) return io_fail(e,BV_INVALID,"invalid device"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"create image"); const BvFormat* format=bv_format((VkFormat)(uint32_t)p[0]); uint32_t usage=p[5],width=p[1],height=p[2],mips=p[3],layers=p[4]; const uint32_t allowed=VK_IMAGE_USAGE_TRANSFER_SRC_BIT|VK_IMAGE_USAGE_TRANSFER_DST_BIT|VK_IMAGE_USAGE_SAMPLED_BIT| VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT|VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; if (!format || !width || !height || !mips || !layers || !usage || (usage&~allowed) || ((usage&VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) && format->aspect!=VK_IMAGE_ASPECT_COLOR_BIT) || ((usage&VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) && format->aspect!=VK_IMAGE_ASPECT_DEPTH_BIT)) return io_fail(e,BV_ARGUMENT,"unsupported image profile"); uint32_t levels=1;for (uint32_t size=width>height ? width : height;size>1;size>>=1) levels++; if (mips>levels) return io_fail(e,BV_ARGUMENT,"mip count exceeds full chain"); BvDevice* device=owner->context;BvInstance* instance=owner->parent->context;VkImageFormatProperties supported; VkResult result=instance->image_formats(device->physical,format->format,VK_IMAGE_TYPE_2D,VK_IMAGE_TILING_OPTIMAL,usage,0,&supported); if (result!=VK_SUCCESS) return bv_vk_error(e,result,"vkGetPhysicalDeviceImageFormatProperties"); if (width>supported.maxExtent.width || height>supported.maxExtent.height || !supported.maxExtent.depth || mips>supported.maxMipLevels || layers>supported.maxArrayLayers || !(supported.sampleCounts&VK_SAMPLE_COUNT_1_BIT) || !bv_image_features(instance,device->physical,format->format,usage)) return io_fail(e,BV_ARGUMENT,"image configuration limits or features"); VkImageCreateInfo create={.sType=VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,.imageType=VK_IMAGE_TYPE_2D,.format=format->format, .extent={width,height,1},.mipLevels=mips,.arrayLayers=layers,.samples=VK_SAMPLE_COUNT_1_BIT,.tiling=VK_IMAGE_TILING_OPTIMAL, .usage=usage,.sharingMode=VK_SHARING_MODE_EXCLUSIVE,.initialLayout=VK_IMAGE_LAYOUT_UNDEFINED}; VkImage handle;result=device->CreateImage(device->handle,&create,NULL,&handle); if (result!=VK_SUCCESS) return bv_device_error(e,owner,result,"vkCreateImage"); BvRow* row=bv_add(BV_IMAGE,owner); if (!row) {device->DestroyImage(device->handle,handle,NULL);return io_fail(e,BV_LIMIT,"image registry full");} row->handle=(uint64_t)(uintptr_t)handle;row->object.image=(BvImage){format->format,{width,height},mips,layers,usage}; device->GetImageMemoryRequirements(device->handle,handle,&row->requirements); return io_done(e,term_pak(CID(ImageHandle),row->id)); } #endif #ifdef CID(Device.image_requirements_raw) static Term bv_image_requirements(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*image=bv_child(bv_key(e,f[1]),BV_IMAGE,owner); if (!owner || !image) return io_fail(e,BV_INVALID,"image requirements ownership"); if (image->object.image.storage==BV_BORROWED_IMAGE) return io_fail(e,BV_LIFETIME,"borrowed image has no memory requirements"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"image requirements"); VkMemoryRequirements r=image->requirements; return io_done(e,io_tup(e,bv_words(e,r.size),io_tup(e,bv_words(e,r.alignment),r.memoryTypeBits))); } #endif #ifdef CID(Device.destroy_image) static Term bv_destroy_image(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*image=bv_child(bv_key(e,f[1]),BV_IMAGE,owner); if (!owner || !image) return io_fail(e,BV_INVALID,"destroy image ownership"); if (image->object.image.storage==BV_BORROWED_IMAGE || bv_referenced(image)) return io_fail(e,BV_LIFETIME,"borrowed image or incoming dependencies"); BvDevice* device=owner->context;device->DestroyImage(device->handle,(VkImage)(uintptr_t)image->handle,NULL); bv_remove(image);return bv_ok(e); } #endif #ifdef CID(Device.create_image_view) static Term bv_create_image_view(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);Term p[7];bv_unpack(e,f[1],7,p); BvRow* image=bv_child((uint32_t)p[0],BV_IMAGE,owner); if (!owner || !image) return io_fail(e,BV_INVALID,"image view ownership"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"create image view"); if (image->object.image.storage==BV_ALLOCATED_IMAGE && !bv_bound_memory(image)) return io_fail(e,BV_LIFETIME,"image view requires binding"); VkImageSubresourceRange range=bv_image_range(p+2);BvImage* i=&image->object.image; if (!bv_image_range_valid(image,range) || ((uint32_t)p[1]!=VK_IMAGE_VIEW_TYPE_2D && (uint32_t)p[1]!=VK_IMAGE_VIEW_TYPE_2D_ARRAY) || ((uint32_t)p[1]==VK_IMAGE_VIEW_TYPE_2D && range.layerCount!=1) || !(i->usage&(VK_IMAGE_USAGE_SAMPLED_BIT|VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT|VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT))) return io_fail(e,BV_ARGUMENT,"image view range, type or usage"); BvDep* dep=malloc(sizeof(*dep));if (!dep) return io_fail(e,BV_LIMIT,"image view dependency allocation"); *dep=(BvDep){.target=image,.role=BV_DEP_VIEW_IMAGE}; VkImageViewCreateInfo create={.sType=VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,.image=(VkImage)(uintptr_t)image->handle, .viewType=(VkImageViewType)(uint32_t)p[1],.format=i->format,.subresourceRange=range}; BvDevice* device=owner->context;VkImageView handle;VkResult result=device->CreateImageView(device->handle,&create,NULL,&handle); if (result!=VK_SUCCESS) {free(dep);return bv_device_error(e,owner,result,"vkCreateImageView");} BvRow* row=bv_add(BV_IMAGE_VIEW,owner); if (!row) {device->DestroyImageView(device->handle,handle,NULL);free(dep);return io_fail(e,BV_LIMIT,"view registry full");} row->handle=(uint64_t)(uintptr_t)handle;row->deps=dep;row->object.view=(BvImageView){create.viewType,range}; return io_done(e,term_pak(CID(ImageView),row->id)); } #endif #ifdef CID(Device.destroy_image_view) static Term bv_destroy_image_view(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*view=bv_child(bv_key(e,f[1]),BV_IMAGE_VIEW,owner); if (!owner || !view) return io_fail(e,BV_INVALID,"destroy image view ownership"); if (bv_referenced(view)) return io_fail(e,BV_LIFETIME,"view has incoming dependencies"); BvDevice* device=owner->context;device->DestroyImageView(device->handle,(VkImageView)(uintptr_t)view->handle,NULL); bv_remove(view);return bv_ok(e); } #endif static int bv_ranges_overlap(VkImageSubresourceRange a,VkImageSubresourceRange b) { return (a.aspectMask&b.aspectMask) && a.baseMipLevelobject.image;uint32_t aspect=bv_format(i->format)->aspect; switch (layout) { case VK_IMAGE_LAYOUT_UNDEFINED:return old; case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:return i->storage==BV_BORROWED_IMAGE; case VK_IMAGE_LAYOUT_GENERAL:return 1; case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:return aspect==VK_IMAGE_ASPECT_COLOR_BIT && (i->usage&VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:return aspect==VK_IMAGE_ASPECT_DEPTH_BIT && (i->usage&VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:return i->usage&VK_IMAGE_USAGE_SAMPLED_BIT; case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:return i->usage&VK_IMAGE_USAGE_TRANSFER_SRC_BIT; case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:return i->usage&VK_IMAGE_USAGE_TRANSFER_DST_BIT; default:return 0; } } static int bv_attachment(VkAttachmentDescription* out,uint32_t format,uint32_t load,uint32_t store,int depth) { const BvFormat* f=bv_format(format); if (!f || f->aspect!=(depth ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT) || load>VK_ATTACHMENT_LOAD_OP_DONT_CARE || store>VK_ATTACHMENT_STORE_OP_DONT_CARE) return 0; VkImageLayout layout=depth ? VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; *out=(VkAttachmentDescription){.format=format,.samples=VK_SAMPLE_COUNT_1_BIT,.loadOp=load,.storeOp=store, .stencilLoadOp=VK_ATTACHMENT_LOAD_OP_DONT_CARE,.stencilStoreOp=VK_ATTACHMENT_STORE_OP_DONT_CARE,.initialLayout=layout,.finalLayout=layout}; return 1; } #ifdef CID(Device.create_render_pass) static Term bv_create_render_pass(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);Term info[5];bv_unpack(e,f[1],5,info); BvDevice* device=owner ? owner->context : NULL; uint32_t code=!owner ? BV_INVALID : !(device->queue_flags&VK_QUEUE_GRAPHICS_BIT) ? BV_ARGUMENT : 0; VkAttachmentDescription* attachments=NULL;VkAttachmentReference* colors=NULL;uint32_t count=0;Term list=info[0]; while (term_aux(list)==CID(Con)) { Term item[2],p[3];bv_unpack(e,list,2,item);list=item[1];bv_unpack(e,item[0],3,p); if (code) continue; VkAttachmentDescription a; if (!bv_attachment(&a,p[0],p[1],p[2],0) || !bv_image_features(owner->parent->context,device->physical,p[0],VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT)) {code=BV_ARGUMENT;continue;} if (count>=device->limits.maxColorAttachments || count>=4095) {code=BV_LIMIT;continue;} VkAttachmentDescription* more=realloc(attachments,(count+1)*sizeof(*attachments)); if (!more) {code=BV_LIMIT;continue;}attachments=more;attachments[count++]=a; } uint32_t color_count=count;VkAttachmentReference depth={0}; if (!code && info[1]) { VkAttachmentDescription a; if (info[1]!=1 || !bv_attachment(&a,info[2],info[3],info[4],1) || !bv_image_features(owner->parent->context,device->physical,info[2],VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) code=BV_ARGUMENT; else { VkAttachmentDescription* more=realloc(attachments,(count+1)*sizeof(*attachments)); if (!more) code=BV_LIMIT; else {attachments=more;depth=(VkAttachmentReference){count,VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL};attachments[count++]=a;} } } if (!code && !count) code=BV_ARGUMENT; if (!code && color_count) { colors=malloc(color_count*sizeof(*colors));if (!colors) code=BV_LIMIT; else for (uint32_t j=0;jCreateRenderPass(device->handle,&create,NULL,&handle);free(colors); if (result!=VK_SUCCESS) {free(attachments);return bv_device_error(e,owner,result,"vkCreateRenderPass");} BvRow* row=bv_add(BV_RENDER_PASS,owner); if (!row) {device->DestroyRenderPass(device->handle,handle,NULL);free(attachments);return io_fail(e,BV_LIMIT,"render pass registry full");} row->handle=(uint64_t)(uintptr_t)handle;row->object.pass=(BvRenderPass){color_count,count,attachments}; return io_done(e,term_pak(CID(RenderPass),row->id)); } #endif #ifdef CID(Device.destroy_render_pass) static Term bv_destroy_render_pass(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*pass=bv_child(bv_key(e,f[1]),BV_RENDER_PASS,owner); if (!owner || !pass) return io_fail(e,BV_INVALID,"destroy render pass ownership"); if (bv_referenced(pass)) return io_fail(e,BV_LIFETIME,"render pass has incoming dependencies"); BvDevice* device=owner->context;device->DestroyRenderPass(device->handle,(VkRenderPass)(uintptr_t)pass->handle,NULL); bv_remove(pass);return bv_ok(e); } #endif #ifdef CID(Device.create_framebuffer) static Term bv_create_framebuffer(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);Term info[4];bv_unpack(e,f[1],4,info); BvRow* pass=bv_child((uint32_t)info[0],BV_RENDER_PASS,owner);BvDevice* device=owner ? owner->context : NULL; uint32_t code=(!owner || !pass) ? BV_INVALID : 0;uint32_t count=pass ? pass->object.pass.count : 0,n=0; uint32_t width=info[2],height=info[3]; if (!code && (!width || !height || width>device->limits.maxFramebufferWidth || height>device->limits.maxFramebufferHeight)) code=BV_ARGUMENT; BvDep* staged=NULL;BvDep** attachments=NULL;VkImageView* views=NULL; if (!code) { attachments=malloc(count*sizeof(*attachments));views=malloc(count*sizeof(*views)); if (!attachments || !views) code=BV_LIMIT; } Term list=info[1]; while (term_aux(list)==CID(Con)) { Term item[2];bv_unpack(e,list,2,item);list=item[1];uint32_t id=bv_key(e,item[0]); if (code) continue; if (n>=count) {code=BV_ARGUMENT;continue;} BvRow* view=bv_child(id,BV_IMAGE_VIEW,owner); if (!view) {code=BV_INVALID;continue;} BvRow* image=bv_dependency(view,BV_DEP_VIEW_IMAGE)->target;BvImageView* v=&view->object.view;BvImage* i=&image->object.image; VkAttachmentDescription a=pass->object.pass.attachments[n];int depth=n>=pass->object.pass.colors; if (v->type!=VK_IMAGE_VIEW_TYPE_2D || v->range.levelCount!=1 || v->range.layerCount!=1 || i->format!=a.format || v->range.aspectMask!=(depth ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT) || !(i->usage&(depth ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT)) || width>bv_mip_dimension(i->extent.width,v->range.baseMipLevel) || height>bv_mip_dimension(i->extent.height,v->range.baseMipLevel)) {code=BV_ARGUMENT;continue;} for (uint32_t j=0;jtarget; if (bv_dependency(previous,BV_DEP_VIEW_IMAGE)->target==image && bv_ranges_overlap(previous->object.view.range,v->range)) code=BV_ARGUMENT; } if (code) continue; BvDep* dep=malloc(sizeof(*dep));if (!dep) {code=BV_LIMIT;continue;} *dep=(BvDep){.target=view,.role=BV_DEP_FRAMEBUFFER_VIEW,.next=staged};staged=dep;attachments[n]=dep;views[n++]=(VkImageView)(uintptr_t)view->handle; } if (!code && n!=count) code=BV_ARGUMENT; if (!code) { BvDep* dep=malloc(sizeof(*dep));if (!dep) code=BV_LIMIT; else {*dep=(BvDep){.target=pass,.role=BV_DEP_FRAMEBUFFER_PASS,.next=staged};staged=dep;} } if (owner && bv_lost(owner)) {free(attachments);free(views);bv_free_refs(staged);return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"create framebuffer");} if (code) {free(attachments);free(views);bv_free_refs(staged);return io_fail(e,code,"framebuffer ownership, attachments, extent, overlap or allocation");} VkFramebufferCreateInfo create={.sType=VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,.renderPass=(VkRenderPass)(uintptr_t)pass->handle, .attachmentCount=count,.pAttachments=views,.width=width,.height=height,.layers=1}; VkFramebuffer handle;VkResult result=device->CreateFramebuffer(device->handle,&create,NULL,&handle);free(views); if (result!=VK_SUCCESS) {free(attachments);bv_free_refs(staged);return bv_device_error(e,owner,result,"vkCreateFramebuffer");} BvRow* row=bv_add(BV_FRAMEBUFFER,owner); if (!row) {device->DestroyFramebuffer(device->handle,handle,NULL);free(attachments);bv_free_refs(staged);return io_fail(e,BV_LIMIT,"framebuffer registry full");} row->handle=(uint64_t)(uintptr_t)handle;row->deps=staged;row->object.framebuffer=(BvFramebuffer){{width,height},count,attachments}; return io_done(e,term_pak(CID(Framebuffer),row->id)); } #endif #ifdef CID(Device.destroy_framebuffer) static Term bv_destroy_framebuffer(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*framebuffer=bv_child(bv_key(e,f[1]),BV_FRAMEBUFFER,owner); if (!owner || !framebuffer) return io_fail(e,BV_INVALID,"destroy framebuffer ownership"); if (bv_referenced(framebuffer)) return io_fail(e,BV_LIFETIME,"framebuffer has incoming dependencies"); BvDevice* device=owner->context;device->DestroyFramebuffer(device->handle,(VkFramebuffer)(uintptr_t)framebuffer->handle,NULL); bv_remove(framebuffer);return bv_ok(e); } #endif #ifdef CID(CommandBuffer.begin_render_pass) static Term bv_cmd_begin_render_pass(Env e,Term* f,IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND),*owner=bv_command_device(command); BvRow* framebuffer=bv_child(bv_key(e,f[1]),BV_FRAMEBUFFER,owner);Term area[4];bv_unpack(e,f[2],4,area); BvDevice* device=owner ? owner->context : NULL; uint32_t code=(!command || !framebuffer) ? BV_INVALID : !bv_outside(command) ? BV_LIFETIME : !(device->queue_flags&VK_QUEUE_GRAPHICS_BIT) ? BV_ARGUMENT : 0; BvRow* pass=framebuffer ? bv_dependency(framebuffer,BV_DEP_FRAMEBUFFER_PASS)->target : NULL; uint32_t count=pass ? pass->object.pass.count : 0,n=0;VkClearValue* clears=NULL; if (!code) { VkExtent2D extent=framebuffer->object.framebuffer.extent;uint32_t x=area[0],y=area[1],w=area[2],h=area[3]; if (x>INT32_MAX || y>INT32_MAX || !w || !h || w>INT32_MAX || h>INT32_MAX || x>extent.width || w>extent.width-x || y>extent.height || h>extent.height-y) code=BV_ARGUMENT; else {clears=calloc(count,sizeof(*clears));if (!clears) code=BV_LIMIT;} } Term list=f[3]; while (term_aux(list)==CID(Con)) { Term item[2];bv_unpack(e,list,2,item);list=item[1]; if (code) {term_sink(e,item[0]);continue;} if (n>=count) {term_sink(e,item[0]);code=BV_ARGUMENT;continue;} VkAttachmentDescription a=pass->object.pass.attachments[n];uint64_t tag=term_aux(item[0]); if (a.loadOp!=VK_ATTACHMENT_LOAD_OP_CLEAR) {if (tag!=CID(UnusedClear)) code=BV_ARGUMENT;term_sink(e,item[0]);} else if (nobject.pass.colors && tag==CID(ColorClear)) { Term lanes[4];bv_unpack(e,item[0],4,lanes); for (unsigned j=0;j<4;j++) {clears[n].color.float32[j]=f32_unbox(lanes[j]);if (!isfinite(clears[n].color.float32[j])) code=BV_ARGUMENT;} } else if (n>=pass->object.pass.colors && tag==CID(DepthClear)) { float depth=f32_unbox(bv_key(e,item[0]));if (!isfinite(depth) || depth<0 || depth>1) code=BV_ARGUMENT; clears[n].depthStencil=(VkClearDepthStencilValue){depth,0}; } else {term_sink(e,item[0]);code=BV_ARGUMENT;} n++; } if (!code && n!=count) code=BV_ARGUMENT; if (owner && bv_lost(owner)) {free(clears);return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"begin render pass");} if (!code)for(uint32_t j=0;jobject.framebuffer.count;j++)if(!bv_image_available(bv_dependency(framebuffer->object.framebuffer.attachments[j]->target,BV_DEP_VIEW_IMAGE)->target))code=BV_LIFETIME; if (!code) code=bv_prepare_refs(command,1,&framebuffer); if (!code) { VkRenderPassBeginInfo begin={.sType=VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,.renderPass=(VkRenderPass)(uintptr_t)pass->handle, .framebuffer=(VkFramebuffer)(uintptr_t)framebuffer->handle,.renderArea={{area[0],area[1]},{area[2],area[3]}},.clearValueCount=count,.pClearValues=clears}; device->CmdBeginRenderPass((VkCommandBuffer)(uintptr_t)command->handle,&begin,VK_SUBPASS_CONTENTS_INLINE); command->command.submission.recording.scope=(BvRenderScope){.tag=BV_INSIDE,.data.inside={framebuffer}}; } free(clears);return code ? io_fail(e,code,"begin render pass ownership, scope, area, typed clears or allocation") : bv_ok(e); } #endif #ifdef CID(CommandBuffer.end_render_pass) static Term bv_cmd_end_render_pass(Env e,Term* f,IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND); if (!command) return io_fail(e,BV_INVALID,"invalid command buffer"); BvRow* owner=bv_command_device(command);BvDevice* device=owner->context; if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"end render pass"); if (command->command.phase!=BV_RECORDING || command->command.submission.recording.scope.tag!=BV_INSIDE) return io_fail(e,BV_LIFETIME,"end render pass requires Inside recording scope"); device->CmdEndRenderPass((VkCommandBuffer)(uintptr_t)command->handle); command->command.submission.recording.scope=(BvRenderScope){.tag=BV_OUTSIDE};return bv_ok(e); } #endif #if defined(CID(Device.create_shader_module)) || defined(CID(CommandBuffer.push_constants)) typedef struct { uint32_t* data,count,code; } BvWordList; static BvWordList bv_word_list(Env e,Term list,uint32_t limit) { BvWordList words={0};uint32_t capacity=0; while (term_aux(list)==CID(Con)) { Term item[2];bv_unpack(e,list,2,item);list=item[1]; if (words.code) continue; if (words.count==limit) {words.code=BV_ARGUMENT;continue;} if (words.count==capacity) { uint32_t next=capacity ? capacity*2 : 32;if (next>limit) next=limit; uint32_t* more=realloc(words.data,next*sizeof(*more)); if (!more) {words.code=BV_LIMIT;continue;}words.data=more;capacity=next; } words.data[words.count++]=(uint32_t)item[0]; } return words; } #endif #ifdef CID(Device.create_shader_module) static Term bv_create_shader_module(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE); BvWordList words=bv_word_list(e,f[1],BV_MAX_COPY/4); uint32_t code=!owner ? BV_INVALID : words.code; if (!code && (words.count<5 || words.data[0]!=0x07230203 || words.data[1]!=0x00010000 || !words.data[3] || words.data[4])) code=BV_ARGUMENT; if (owner && bv_lost(owner)) {free(words.data);return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"create shader");} BvRow* row=NULL;if (!code && !(row=bv_add(BV_SHADER,owner))) code=BV_LIMIT; if (code) {free(words.data);return io_fail(e,code,"shader owner, SPIR-V 1.0 header, size or allocation");} BvDevice* device=owner->context;VkShaderModule handle=VK_NULL_HANDLE; VkShaderModuleCreateInfo info={.sType=VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,.codeSize=(size_t)words.count*4,.pCode=words.data}; VkResult result=device->CreateShaderModule(device->handle,&info,NULL,&handle);free(words.data); if (result!=VK_SUCCESS) {bv_remove(row);return bv_device_error(e,owner,result,"vkCreateShaderModule");} row->handle=(uint64_t)(uintptr_t)handle;return io_done(e,term_pak(CID(ShaderModule),row->id)); } #endif static int bv_stage_counts(BvDevice* d,uint64_t uniforms,uint64_t sampled) { return uniforms<=d->limits.maxDescriptorSetUniformBuffers && sampled<=d->limits.maxDescriptorSetSamplers && sampled<=d->limits.maxDescriptorSetSampledImages; } static int bv_per_stage_counts(BvDevice* d,uint64_t uniforms,uint64_t sampled) { return uniforms<=d->limits.maxPerStageDescriptorUniformBuffers && sampled<=d->limits.maxPerStageDescriptorSamplers && sampled<=d->limits.maxPerStageDescriptorSampledImages && uniforms+sampled<=d->limits.maxPerStageResources; } static int bv_stage_edge(BvDep** deps,BvRow* target,BvDepRole role) { for(BvDep* dep=*deps;dep;dep=dep->next)if(dep->target==target && dep->role==role)return 1; BvDep* dep=malloc(sizeof(*dep));if(!dep)return 0; *dep=(BvDep){.target=target,.role=role,.next=*deps};*deps=dep;return 1; } static int bv_schema_equal(const BvDescriptorSchema* a,const BvDescriptorSchema* b) { if(a->count!=b->count)return 0; for(uint32_t j=0;jcount;j++) { const VkDescriptorSetLayoutBinding *x=&a->bindings[j],*y=&b->bindings[j]; if(x->binding!=y->binding || x->descriptorType!=y->descriptorType || x->descriptorCount!=y->descriptorCount || x->stageFlags!=y->stageFlags)return 0; } return 1; } static BvRow* bv_set_layout(BvRow* set) {return bv_dependency(set,BV_DEP_SET_LAYOUT)->target;} static BvRow* bv_set_pool(BvRow* set) {return bv_dependency(set,BV_DEP_SET_POOL)->target;} static int bv_descriptor_pool_referenced(BvRow* pool) { for(BvRow* set=bv_rows;set;set=set->next) if(set->kind==BV_DESCRIPTOR_SET && bv_set_pool(set)==pool && bv_referenced(set))return 1; return 0; } static void bv_descriptor_pool_clear(BvRow* pool) { for(BvRow* set=bv_rows,*next;set;set=next) { next=set->next;if(set->kind==BV_DESCRIPTOR_SET && bv_set_pool(set)==pool)bv_remove(set); } BvDescriptorPool* p=&pool->object.descriptor_pool;p->sets=p->used_uniforms=p->used_sampled=0; } #ifdef CID(Device.descriptor_set_layout_raw) static Term bv_create_descriptor_set_layout(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);Term p[1];bv_unpack(e,f[1],1,p); uint32_t code=!owner ? BV_INVALID : bv_lost(owner) ? (uint32_t)VK_ERROR_DEVICE_LOST : 0; VkDescriptorSetLayoutBinding* bindings=NULL;uint32_t count=0,slots=0,uniforms=0,sampled=0;uint64_t stage[2][2]={{0}}; if(!code && !(bindings=calloc(BV_MAX_DESCRIPTOR_SLOTS,sizeof(*bindings))))code=BV_LIMIT; Term list=p[0]; while(term_aux(list)==CID(Con)) { Term item[2],b[4];bv_unpack(e,list,2,item);list=item[1];bv_unpack(e,item[0],4,b); if(code)continue; if(b[1]>1 || !b[2] || !b[3] || (b[3]&~17u) || (count && bindings[count-1].binding>=b[0]) || b[2]>BV_MAX_DESCRIPTOR_SLOTS-slots) {code=BV_ARGUMENT;continue;} VkDescriptorType kind=b[1] ? VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER : VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; bindings[count++]=(VkDescriptorSetLayoutBinding){.binding=b[0],.descriptorType=kind,.descriptorCount=b[2],.stageFlags=b[3]};slots+=b[2]; if(b[1])sampled+=b[2];else uniforms+=b[2]; if(b[3]&1)stage[0][b[1]]+=b[2];if(b[3]&16)stage[1][b[1]]+=b[2]; } if(!code && (!bv_stage_counts(owner->context,uniforms,sampled) || !bv_per_stage_counts(owner->context,stage[0][0],stage[0][1]) || !bv_per_stage_counts(owner->context,stage[1][0],stage[1][1])))code=BV_LIMIT; BvRow* row=NULL;if(!code && !(row=bv_add(BV_DESCRIPTOR_LAYOUT,owner)))code=BV_LIMIT; if(code) {free(bindings);return io_fail(e,code,"descriptor schema ownership, sorted unique bindings, count, stages or limits");} BvDevice* d=owner->context;VkDescriptorSetLayout handle=VK_NULL_HANDLE; VkDescriptorSetLayoutCreateInfo info={.sType=VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,.bindingCount=count,.pBindings=bindings}; VkResult result=d->CreateDescriptorSetLayout(d->handle,&info,NULL,&handle); if(result!=VK_SUCCESS) {bv_remove(row);free(bindings);return bv_device_error(e,owner,result,"vkCreateDescriptorSetLayout");} row->handle=(uint64_t)(uintptr_t)handle;row->object.schema=(BvDescriptorSchema){count,slots,uniforms,sampled,bindings}; return io_done(e,term_pak(CID(DescriptorSetLayout),row->id)); } #endif #ifdef CID(Device.create_descriptor_pool) static Term bv_create_descriptor_pool(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);Term p[2];bv_unpack(e,f[1],2,p); uint32_t code=!owner ? BV_INVALID : bv_lost(owner) ? (uint32_t)VK_ERROR_DEVICE_LOST : !p[0] ? BV_ARGUMENT : 0; uint32_t capacities[2]={0},seen=0;Term list=p[1]; while(term_aux(list)==CID(Con)) { Term item[2],size[2];bv_unpack(e,list,2,item);list=item[1];bv_unpack(e,item[0],2,size); if(code)continue; if(size[0]>1 || !size[1] || (seen&(1u<context;VkDescriptorPool handle=VK_NULL_HANDLE;VkResult result=d->CreateDescriptorPool(d->handle,&info,NULL,&handle); if(result!=VK_SUCCESS) {bv_remove(row);return bv_device_error(e,owner,result,"vkCreateDescriptorPool");} row->handle=(uint64_t)(uintptr_t)handle;row->object.descriptor_pool=(BvDescriptorPool){.phase=BV_POOL_READY,.max_sets=p[0],.uniforms=capacities[0],.sampled=capacities[1]}; return io_done(e,term_pak(CID(DescriptorPool),row->id)); } #endif #ifdef CID(Device.allocate_descriptor_set) static Term bv_allocate_descriptor_set(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*pool=bv_child(bv_key(e,f[1]),BV_DESCRIPTOR_POOL,owner),*layout=bv_child(bv_key(e,f[2]),BV_DESCRIPTOR_LAYOUT,owner); if(!owner || !pool || !layout)return io_fail(e,BV_INVALID,"descriptor allocation ownership"); if(bv_lost(owner))return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"allocate descriptor set"); BvDescriptorPool* p=&pool->object.descriptor_pool;BvDescriptorSchema* schema=&layout->object.schema; if(p->phase!=BV_POOL_READY)return io_fail(e,BV_LIFETIME,"descriptor pool quarantined"); if(p->sets==p->max_sets || schema->uniforms>p->uniforms-p->used_uniforms || schema->sampled>p->sampled-p->used_sampled)return io_fail(e,BV_LIMIT,"descriptor pool exhausted"); BvDescriptorSlot* slots=calloc(schema->slots ? schema->slots : 1,sizeof(*slots));BvDep* deps=NULL;BvRow* row=NULL; if(!slots || !bv_stage_edge(&deps,pool,BV_DEP_SET_POOL) || !bv_stage_edge(&deps,layout,BV_DEP_SET_LAYOUT) || !(row=bv_add(BV_DESCRIPTOR_SET,owner))) { free(slots);bv_free_refs(deps);return io_fail(e,BV_LIMIT,"descriptor set metadata"); } uint32_t at=0;for(uint32_t j=0;jcount;j++)for(uint32_t k=0;kbindings[j].descriptorCount;k++)slots[at++].tag=schema->bindings[j].descriptorType==VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER ? BV_UNWRITTEN_UNIFORM : BV_UNWRITTEN_SAMPLED; BvDevice* d=owner->context;VkDescriptorSetLayout native_layout=(VkDescriptorSetLayout)(uintptr_t)layout->handle;VkDescriptorSet handle=VK_NULL_HANDLE; VkDescriptorSetAllocateInfo info={.sType=VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,.descriptorPool=(VkDescriptorPool)(uintptr_t)pool->handle,.descriptorSetCount=1,.pSetLayouts=&native_layout}; VkResult result=d->AllocateDescriptorSets(d->handle,&info,&handle); if(result!=VK_SUCCESS) {bv_remove(row);free(slots);bv_free_refs(deps);return bv_device_error(e,owner,result,"vkAllocateDescriptorSets");} row->handle=(uint64_t)(uintptr_t)handle;row->deps=deps;row->object.set.slots=slots;p->sets++;p->used_uniforms+=schema->uniforms;p->used_sampled+=schema->sampled; return io_done(e,term_pak(CID(DescriptorSet),row->id)); } #endif static Term bv_descriptor_pool_operation(Env e,Term* f,int reset) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*pool=bv_child(bv_key(e,f[1]),BV_DESCRIPTOR_POOL,owner); if(!owner || !pool)return io_fail(e,BV_INVALID,"descriptor pool ownership"); if(bv_descriptor_pool_referenced(pool))return io_fail(e,BV_LIFETIME,"descriptor pool contains recorded sets"); BvDevice* d=owner->context; if(reset) { if(bv_lost(owner))return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"reset descriptor pool"); if(pool->object.descriptor_pool.phase!=BV_POOL_READY)return io_fail(e,BV_LIFETIME,"descriptor pool quarantined"); VkResult result=d->ResetDescriptorPool(d->handle,(VkDescriptorPool)(uintptr_t)pool->handle,0); if(result!=VK_SUCCESS) {pool->object.descriptor_pool.phase=BV_POOL_QUARANTINED;return bv_device_error(e,owner,result,"vkResetDescriptorPool");} bv_descriptor_pool_clear(pool); } else {d->DestroyDescriptorPool(d->handle,(VkDescriptorPool)(uintptr_t)pool->handle,NULL);bv_descriptor_pool_clear(pool);bv_remove(pool);} return bv_ok(e); } #ifdef CID(Device.reset_descriptor_pool) static Term bv_reset_descriptor_pool(Env e,Term* f,IoWork* w) {return bv_descriptor_pool_operation(e,f,1);} #endif #ifdef CID(Device.destroy_descriptor_pool) static Term bv_destroy_descriptor_pool(Env e,Term* f,IoWork* w) {return bv_descriptor_pool_operation(e,f,0);} #endif #ifdef CID(Device.free_descriptor_set) static Term bv_free_descriptor_set(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*set=bv_child(bv_key(e,f[1]),BV_DESCRIPTOR_SET,owner); if(!owner || !set)return io_fail(e,BV_INVALID,"descriptor free ownership"); if(bv_lost(owner))return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"free descriptor set"); BvRow* pool=bv_set_pool(set);BvDescriptorPool* p=&pool->object.descriptor_pool; if(p->phase!=BV_POOL_READY || bv_referenced(set))return io_fail(e,BV_LIFETIME,"descriptor set recorded or pool quarantined"); BvDevice* d=owner->context;VkDescriptorSet handle=(VkDescriptorSet)(uintptr_t)set->handle; VkResult result=d->FreeDescriptorSets(d->handle,(VkDescriptorPool)(uintptr_t)pool->handle,1,&handle); if(result!=VK_SUCCESS) {p->phase=BV_POOL_QUARANTINED;return bv_device_error(e,owner,result,"vkFreeDescriptorSets");} BvDescriptorSchema* schema=&bv_set_layout(set)->object.schema;p->sets--;p->used_uniforms-=schema->uniforms;p->used_sampled-=schema->sampled;bv_remove(set);return bv_ok(e); } #endif #ifdef CID(Device.create_sampler) static Term bv_create_sampler(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);Term p[9];bv_unpack(e,f[1],9,p); if(!owner)return io_fail(e,BV_INVALID,"sampler ownership"); if(bv_lost(owner))return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"create sampler"); float minimum=f32_unbox(p[6]),maximum=f32_unbox(p[7]); if(p[0]>1 || p[1]>1 || p[2]>1 || p[3]>3 || p[4]>3 || p[5]>3 || p[8]>5 || !isfinite(minimum) || !isfinite(maximum) || minimum<0 || maximumcontext; for(BvRow* row=bv_rows;row;row=row->next)if(row->parent==owner && row->kind==BV_SAMPLER)count++; if(count>=device->limits.maxSamplerAllocationCount)return io_fail(e,BV_LIMIT,"sampler allocation limit"); BvRow* row=bv_add(BV_SAMPLER,owner);if(!row)return io_fail(e,BV_LIMIT,"sampler metadata"); VkSamplerCreateInfo info={.sType=VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,.minFilter=p[0],.magFilter=p[1],.mipmapMode=p[2],.addressModeU=p[3],.addressModeV=p[4],.addressModeW=p[5],.minLod=minimum,.maxLod=maximum,.borderColor=p[8]}; BvDevice* d=owner->context;VkSampler handle=VK_NULL_HANDLE;VkResult result=d->CreateSampler(d->handle,&info,NULL,&handle); if(result!=VK_SUCCESS) {bv_remove(row);return bv_device_error(e,owner,result,"vkCreateSampler");} row->handle=(uint64_t)(uintptr_t)handle;row->object.sampler=(BvSampler){p[0],p[1],p[2]};return io_done(e,term_pak(CID(Sampler),row->id)); } #endif static Term bv_destroy_descriptor_resource(Env e,Term* f,BvKind kind) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*row=bv_child(bv_key(e,f[1]),kind,owner); if(!owner || !row)return io_fail(e,BV_INVALID,"descriptor resource ownership"); if(bv_referenced(row))return io_fail(e,BV_LIFETIME,"descriptor resource retained"); BvDevice* d=owner->context; if(kind==BV_SAMPLER)d->DestroySampler(d->handle,(VkSampler)(uintptr_t)row->handle,NULL); else d->DestroyDescriptorSetLayout(d->handle,(VkDescriptorSetLayout)(uintptr_t)row->handle,NULL); bv_remove(row);return bv_ok(e); } #ifdef CID(Device.destroy_descriptor_set_layout) static Term bv_destroy_descriptor_set_layout(Env e,Term* f,IoWork* w) {return bv_destroy_descriptor_resource(e,f,BV_DESCRIPTOR_LAYOUT);} #endif #ifdef CID(Device.destroy_sampler) static Term bv_destroy_sampler(Env e,Term* f,IoWork* w) {return bv_destroy_descriptor_resource(e,f,BV_SAMPLER);} #endif static uint32_t bv_sampled_slot(BvRow* owner,BvRow* view,BvRow* sampler,uint32_t layout) { if(!view || !sampler)return BV_INVALID; BvRow* image=bv_dependency(view,BV_DEP_VIEW_IMAGE)->target;BvImage* i=&image->object.image;BvSampler* s=&sampler->object.sampler; if(i->storage!=BV_ALLOCATED_IMAGE || !bv_bound_memory(image))return BV_LIFETIME; if(!(i->usage&VK_IMAGE_USAGE_SAMPLED_BIT) || !bv_image_layout(image,layout,0) || (layout!=VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL && layout!=VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL && layout!=VK_IMAGE_LAYOUT_GENERAL) || (layout==VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL && view->object.view.range.aspectMask!=VK_IMAGE_ASPECT_DEPTH_BIT))return BV_ARGUMENT; BvDevice* d=owner->context;BvInstance* instance=owner->parent->context;VkFormatProperties props;instance->formats(d->physical,i->format,&props); if(!(props.optimalTilingFeatures&VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) || ((s->min==VK_FILTER_LINEAR || s->mag==VK_FILTER_LINEAR || s->mip==VK_SAMPLER_MIPMAP_MODE_LINEAR) && !(props.optimalTilingFeatures&VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)))return BV_ARGUMENT; return 0; } #ifdef CID(Device.update_descriptor_set) static Term bv_update_descriptor_set(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*set=bv_child(bv_key(e,f[1]),BV_DESCRIPTOR_SET,owner); uint32_t code=!owner || !set ? BV_INVALID : bv_lost(owner) ? (uint32_t)VK_ERROR_DEVICE_LOST : bv_referenced(set) || bv_set_pool(set)->object.descriptor_pool.phase!=BV_POOL_READY ? BV_LIFETIME : 0; BvDescriptorSchema* schema=set ? &bv_set_layout(set)->object.schema : NULL;uint32_t n=schema ? schema->slots : 0,count=0; BvDescriptorSlot* slots=NULL;bool* touched=NULL;VkWriteDescriptorSet* writes=NULL;VkDescriptorBufferInfo* buffers=NULL;VkDescriptorImageInfo* images=NULL;BvDep* deps=NULL; if(!code) { slots=malloc((n ? n : 1)*sizeof(*slots));touched=calloc(n ? n : 1,sizeof(*touched));writes=calloc(n ? n : 1,sizeof(*writes));buffers=calloc(n ? n : 1,sizeof(*buffers));images=calloc(n ? n : 1,sizeof(*images)); if(!slots || !touched || !writes || !buffers || !images)code=BV_LIMIT; else memcpy(slots,set->object.set.slots,n*sizeof(*slots)); } Term list=f[2]; while(term_aux(list)==CID(Con)) { Term item[2],p[3];bv_unpack(e,list,2,item);list=item[1];uint64_t tag=term_aux(item[0]);bv_unpack(e,item[0],3,p); uint32_t base=0,binding=0,first=p[1],values=0;int uniform=tag==CID(UniformWrite); if(!code) { if(tag!=CID(UniformWrite) && tag!=CID(SampledWrite))code=BV_ARGUMENT; while(bindingcount && schema->bindings[binding].binding!=p[0])base+=schema->bindings[binding++].descriptorCount; if(binding==schema->count || schema->bindings[binding].descriptorType!=(uniform ? VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER : VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER))code=BV_ARGUMENT; } Term value_list=p[2]; while(term_aux(value_list)==CID(Con)) { Term value[2],v[5];bv_unpack(e,value_list,2,value);value_list=value[1];bv_unpack(e,value[0],uniform ? 5 : 3,v);values++; if(code)continue; if(first>=schema->bindings[binding].descriptorCount || touched[base+first]) {code=BV_ARGUMENT;continue;} uint32_t at=base+first++;touched[at]=true; writes[count]=(VkWriteDescriptorSet){.sType=VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,.dstSet=(VkDescriptorSet)(uintptr_t)set->handle,.dstBinding=p[0],.dstArrayElement=first-1,.descriptorCount=1,.descriptorType=schema->bindings[binding].descriptorType}; if(uniform) { BvRow* buffer=bv_child(v[0],BV_BUFFER,owner);uint64_t offset=((uint64_t)(uint32_t)v[2]<<32)|(uint32_t)v[1],range=((uint64_t)(uint32_t)v[4]<<32)|(uint32_t)v[3];BvDevice* d=owner->context; if(!buffer)code=BV_INVALID; else if(buffer->retired || bv_sealed(buffer,BV_KIND_COUNT) || !bv_bound_memory(buffer))code=BV_LIFETIME; else if(!(buffer->flags&VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT) || !range || range>d->limits.maxUniformBufferRange || offset>buffer->size || range>buffer->size-offset || (d->limits.minUniformBufferOffsetAlignment && offset%d->limits.minUniformBufferOffsetAlignment))code=BV_ARGUMENT; else {slots[at]=(BvDescriptorSlot){.tag=BV_UNIFORM_SLOT,.data.uniform={buffer,offset,range}};buffers[count]=(VkDescriptorBufferInfo){(VkBuffer)(uintptr_t)buffer->handle,offset,range};writes[count].pBufferInfo=&buffers[count];} } else { BvRow* view=bv_child(v[0],BV_IMAGE_VIEW,owner),*sampler=bv_child(v[1],BV_SAMPLER,owner);code=bv_sampled_slot(owner,view,sampler,v[2]); if(!code) {slots[at]=(BvDescriptorSlot){.tag=BV_SAMPLED_SLOT,.data.sampled={view,sampler,v[2]}};images[count]=(VkDescriptorImageInfo){(VkSampler)(uintptr_t)sampler->handle,(VkImageView)(uintptr_t)view->handle,v[2]};writes[count].pImageInfo=&images[count];} } count++; } if(!values && !code)code=BV_ARGUMENT; } if(!code && !count)code=BV_ARGUMENT; if(!code && (!bv_stage_edge(&deps,bv_set_pool(set),BV_DEP_SET_POOL) || !bv_stage_edge(&deps,bv_set_layout(set),BV_DEP_SET_LAYOUT)))code=BV_LIMIT; for(uint32_t j=0;!code && jtag==BV_UNIFORM_SLOT && !bv_stage_edge(&deps,slot->data.uniform.buffer,BV_DEP_UNIFORM))code=BV_LIMIT; if(slot->tag==BV_SAMPLED_SLOT && (!bv_stage_edge(&deps,slot->data.sampled.view,BV_DEP_SAMPLED_VIEW) || !bv_stage_edge(&deps,slot->data.sampled.sampler,BV_DEP_SAMPLER)))code=BV_LIMIT; } if(!code) { BvDevice* d=owner->context;d->UpdateDescriptorSets(d->handle,count,writes,0,NULL); BvDescriptorSlot* old=set->object.set.slots;BvDep* old_deps=set->deps;set->object.set.slots=slots;slots=old;set->deps=deps;deps=old_deps; } free(slots);free(touched);free(writes);free(buffers);free(images);bv_free_refs(deps); return code ? io_fail(e,code,"descriptor update ownership, frozen state, typed destinations, resource range/filter/layout or metadata") : bv_ok(e); } #endif static int bv_descriptor_feedback(BvRow* set,BvRow* framebuffer) { BvDescriptorSchema* schema=&bv_set_layout(set)->object.schema; for(uint32_t j=0;jslots;j++) { BvDescriptorSlot* slot=&set->object.set.slots[j];if(slot->tag!=BV_SAMPLED_SLOT)continue; BvRow* view=slot->data.sampled.view,*image=bv_dependency(view,BV_DEP_VIEW_IMAGE)->target; for(uint32_t k=0;kobject.framebuffer.count;k++) { BvRow* attachment=framebuffer->object.framebuffer.attachments[k]->target; if(bv_dependency(attachment,BV_DEP_VIEW_IMAGE)->target==image && bv_ranges_overlap(view->object.view.range,attachment->object.view.range))return 1; } } return 0; } #ifdef CID(Device.create_pipeline_layout) static Term bv_create_pipeline_layout(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);Term p[4];bv_unpack(e,f[1],4,p); uint32_t code=!owner ? BV_INVALID : bv_lost(owner) ? (uint32_t)VK_ERROR_DEVICE_LOST : 0; BvRow** sets=NULL;BvDep* deps=NULL;VkDescriptorSetLayout handles[BV_MAX_DESCRIPTOR_SETS];uint32_t count=0; uint64_t uniforms=0,sampled=0,stage[2][2]={{0}};BvDevice* d=owner ? owner->context : NULL; if(!code && (p[1]>1 || (p[1] && (!p[2] || (p[2]&~17u) || !p[3] || (p[3]&3) || p[3]>128 || p[3]>d->limits.maxPushConstantsSize))))code=BV_ARGUMENT; Term list=p[0]; if(!code && term_aux(list)==CID(Con) && !(sets=calloc(BV_MAX_DESCRIPTOR_SETS,sizeof(*sets))))code=BV_LIMIT; while(term_aux(list)==CID(Con)) { Term item[2];bv_unpack(e,list,2,item);list=item[1];BvRow* layout=bv_child(bv_key(e,item[0]),BV_DESCRIPTOR_LAYOUT,owner); if(code)continue; if(!layout) {code=BV_INVALID;continue;} if(count>=BV_MAX_DESCRIPTOR_SETS || count>=d->limits.maxBoundDescriptorSets) {code=BV_LIMIT;continue;} BvDescriptorSchema* schema=&layout->object.schema;uniforms+=schema->uniforms;sampled+=schema->sampled; for(uint32_t j=0;jcount;j++) { VkDescriptorSetLayoutBinding* b=&schema->bindings[j];unsigned kind=b->descriptorType==VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; if(b->stageFlags&1)stage[0][kind]+=b->descriptorCount;if(b->stageFlags&16)stage[1][kind]+=b->descriptorCount; } sets[count]=layout;handles[count++]=(VkDescriptorSetLayout)(uintptr_t)layout->handle; if(!bv_stage_edge(&deps,layout,BV_DEP_LAYOUT_SET))code=BV_LIMIT; } if(!code && (!bv_stage_counts(d,uniforms,sampled) || !bv_per_stage_counts(d,stage[0][0],stage[0][1]) || !bv_per_stage_counts(d,stage[1][0],stage[1][1])))code=BV_LIMIT; BvRow* row=NULL;if(!code && !(row=bv_add(BV_LAYOUT,owner)))code=BV_LIMIT; if(code) {free(sets);bv_free_refs(deps);return io_fail(e,code,"pipeline layout owner, push range, ordered schemas, limits or metadata");} VkPushConstantRange push={p[2],0,p[3]};VkPipelineLayout handle=VK_NULL_HANDLE; VkPipelineLayoutCreateInfo info={.sType=VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,.setLayoutCount=count,.pSetLayouts=handles,.pushConstantRangeCount=p[1],.pPushConstantRanges=p[1] ? &push : NULL}; VkResult result=d->CreatePipelineLayout(d->handle,&info,NULL,&handle); if(result!=VK_SUCCESS) {bv_remove(row);free(sets);bv_free_refs(deps);return bv_device_error(e,owner,result,"vkCreatePipelineLayout");} row->handle=(uint64_t)(uintptr_t)handle;row->object.layout=(BvPipelineLayout){p[1] ? p[2] : 0,p[1] ? p[3] : 0,count,sets};row->deps=deps; return io_done(e,term_pak(CID(PipelineLayout),row->id)); } #endif #ifdef CID(Device.create_graphics_pipeline) static int bv_vertex_format(BvRow* owner,uint32_t format,uint32_t* bytes,uint32_t* alignment) { switch (format) { case VK_FORMAT_R32_SFLOAT:*bytes=4;break; case VK_FORMAT_R32G32_SFLOAT:*bytes=8;break; case VK_FORMAT_R32G32B32_SFLOAT:*bytes=12;break; case VK_FORMAT_R32G32B32A32_SFLOAT:*bytes=16;break; case VK_FORMAT_R8G8B8A8_UNORM:*bytes=4;break; default:return 0; } *alignment=format==VK_FORMAT_R8G8B8A8_UNORM ? 1 : 4; BvDevice* d=owner->context;BvInstance* i=owner->parent->context;VkFormatProperties properties; i->formats(d->physical,format,&properties);return (properties.bufferFeatures&VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT)!=0; } static Term bv_create_graphics_pipeline(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);Term p[14];bv_unpack(e,f[1],14,p); BvRow* layout=bv_child(p[0],BV_LAYOUT,owner),*pass=bv_child(p[1],BV_RENDER_PASS,owner); BvRow* vertex=bv_child(p[2],BV_SHADER,owner),*fragment=bv_child(p[3],BV_SHADER,owner); BvDevice* d=owner ? owner->context : NULL; uint32_t code=(!owner || !layout || !pass || !vertex || !fragment) ? BV_INVALID : !(d->queue_flags&VK_QUEUE_GRAPHICS_BIT) ? BV_ARGUMENT : 0; VkVertexInputBindingDescription bindings[64];BvVertexRequirement required[64];uint32_t nb=0,na=0; VkVertexInputAttributeDescription attributes[256];Term list=p[4]; while (term_aux(list)==CID(Con)) { Term item[2],b[3];bv_unpack(e,list,2,item);list=item[1];bv_unpack(e,item[0],3,b); if (code) continue; if (nb==64 || nb>=d->limits.maxVertexInputBindings) {code=BV_LIMIT;continue;} if (b[0]>=d->limits.maxVertexInputBindings || b[1]>d->limits.maxVertexInputBindingStride || b[2]>VK_VERTEX_INPUT_RATE_INSTANCE) {code=BV_ARGUMENT;continue;} for(uint32_t j=0;j=d->limits.maxVertexInputAttributes) {code=BV_LIMIT;continue;} if (a[0]>=d->limits.maxVertexInputAttributes || a[3]>d->limits.maxVertexInputAttributeOffset || !bv_vertex_format(owner,a[2],&bytes,&align)) {code=BV_ARGUMENT;continue;} for(uint32_t j=0;jUINT32_MAX-bytes) {code=BV_ARGUMENT;continue;} if (required[binding].stride%align) {code=BV_ARGUMENT;continue;} if (code) continue; if (required[binding].alignmentVK_FRONT_FACE_CLOCKWISE || p[9]>1 || p[10]>1 || p[11]>1 || p[12]>VK_COMPARE_OP_ALWAYS || (p[13]&~15u) || (p[9] && (p[10] || p[11]) && pass->object.pass.count==pass->object.pass.colors))) code=BV_ARGUMENT; if (owner && bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"create graphics pipeline"); if (code) return io_fail(e,code,"graphics pipeline owner, vertex schema, formats, state or limits"); BvVertexRequirement* requirements=nb ? malloc(nb*sizeof(*requirements)) : NULL; VkPipelineColorBlendAttachmentState* colors=pass->object.pass.colors ? calloc(pass->object.pass.colors,sizeof(*colors)) : NULL; if ((nb && !requirements) || (pass->object.pass.colors && !colors)) {free(requirements);free(colors);return io_fail(e,BV_LIMIT,"pipeline metadata allocation");} if (nb) memcpy(requirements,required,nb*sizeof(*requirements)); for(uint32_t j=0;jobject.pass.colors;j++) colors[j].colorWriteMask=p[13]; BvRow* row=bv_add(BV_PIPELINE,owner);BvDep* layout_dep=malloc(sizeof(*layout_dep)),*pass_dep=malloc(sizeof(*pass_dep)); if (!row || !layout_dep || !pass_dep) {if(row)bv_remove(row);free(layout_dep);free(pass_dep);free(requirements);free(colors);return io_fail(e,BV_LIMIT,"pipeline registry allocation");} *layout_dep=(BvDep){.target=layout,.role=BV_DEP_PIPELINE_LAYOUT,.next=pass_dep};*pass_dep=(BvDep){.target=pass,.role=BV_DEP_PIPELINE_PASS}; row->deps=layout_dep;row->object.pipeline=(BvPipeline){nb,requirements}; VkPipelineShaderStageCreateInfo stages[2]={ {.sType=VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,.stage=VK_SHADER_STAGE_VERTEX_BIT,.module=(VkShaderModule)(uintptr_t)vertex->handle,.pName="main"}, {.sType=VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,.stage=VK_SHADER_STAGE_FRAGMENT_BIT,.module=(VkShaderModule)(uintptr_t)fragment->handle,.pName="main"}}; VkPipelineVertexInputStateCreateInfo vi={.sType=VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,.vertexBindingDescriptionCount=nb,.pVertexBindingDescriptions=bindings,.vertexAttributeDescriptionCount=na,.pVertexAttributeDescriptions=attributes}; VkPipelineInputAssemblyStateCreateInfo ia={.sType=VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,.topology=p[6]}; VkPipelineViewportStateCreateInfo vp={.sType=VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,.viewportCount=1,.scissorCount=1}; VkPipelineRasterizationStateCreateInfo rs={.sType=VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,.polygonMode=VK_POLYGON_MODE_FILL,.cullMode=p[7],.frontFace=p[8],.lineWidth=1}; VkPipelineMultisampleStateCreateInfo ms={.sType=VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,.rasterizationSamples=VK_SAMPLE_COUNT_1_BIT}; VkPipelineDepthStencilStateCreateInfo depth={.sType=VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,.depthTestEnable=p[9] && p[10],.depthWriteEnable=p[9] && p[11],.depthCompareOp=p[12]}; VkPipelineColorBlendStateCreateInfo blend={.sType=VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,.attachmentCount=pass->object.pass.colors,.pAttachments=colors}; VkDynamicState states[]={VK_DYNAMIC_STATE_VIEWPORT,VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic={.sType=VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,.dynamicStateCount=2,.pDynamicStates=states}; VkGraphicsPipelineCreateInfo info={.sType=VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,.stageCount=2,.pStages=stages,.pVertexInputState=&vi,.pInputAssemblyState=&ia,.pViewportState=&vp,.pRasterizationState=&rs,.pMultisampleState=&ms,.pDepthStencilState=&depth,.pColorBlendState=&blend,.pDynamicState=&dynamic,.layout=(VkPipelineLayout)(uintptr_t)layout->handle,.renderPass=(VkRenderPass)(uintptr_t)pass->handle,.basePipelineIndex=-1}; VkPipeline handle=VK_NULL_HANDLE;VkResult result=d->CreateGraphicsPipelines(d->handle,VK_NULL_HANDLE,1,&info,NULL,&handle);free(colors); if (result!=VK_SUCCESS) {if (handle) d->DestroyPipeline(d->handle,handle,NULL);bv_remove(row);return bv_device_error(e,owner,result,"vkCreateGraphicsPipelines");} row->handle=(uint64_t)(uintptr_t)handle;return io_done(e,term_pak(CID(GraphicsPipeline),row->id)); } #endif #if defined(CID(Device.destroy_shader_module)) || defined(CID(Device.destroy_pipeline_layout)) || defined(CID(Device.destroy_graphics_pipeline)) static Term bv_destroy_graphics_resource(Env e,Term* f,BvKind kind) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*row=bv_child(bv_key(e,f[1]),kind,owner); if (!owner || !row) return io_fail(e,BV_INVALID,"graphics resource ownership"); if (bv_referenced(row)) return io_fail(e,BV_LIFETIME,"graphics resource has incoming dependencies"); BvDevice* d=owner->context; if (kind==BV_SHADER) d->DestroyShaderModule(d->handle,(VkShaderModule)(uintptr_t)row->handle,NULL); else if (kind==BV_LAYOUT) d->DestroyPipelineLayout(d->handle,(VkPipelineLayout)(uintptr_t)row->handle,NULL); else d->DestroyPipeline(d->handle,(VkPipeline)(uintptr_t)row->handle,NULL); bv_remove(row);return bv_ok(e); } #endif #ifdef CID(Device.destroy_shader_module) static Term bv_destroy_shader_module(Env e,Term* f,IoWork* w) {return bv_destroy_graphics_resource(e,f,BV_SHADER);} #endif #ifdef CID(Device.destroy_pipeline_layout) static Term bv_destroy_pipeline_layout(Env e,Term* f,IoWork* w) {return bv_destroy_graphics_resource(e,f,BV_LAYOUT);} #endif #ifdef CID(Device.destroy_graphics_pipeline) static Term bv_destroy_graphics_pipeline(Env e,Term* f,IoWork* w) {return bv_destroy_graphics_resource(e,f,BV_PIPELINE);} #endif static uint32_t bv_graphics_recording(BvRow* command) { if (!command) return BV_INVALID; BvRow* owner=bv_command_device(command);BvDevice* d=owner->context; if (bv_lost(owner)) return (uint32_t)VK_ERROR_DEVICE_LOST; if (command->command.phase!=BV_RECORDING) return BV_LIFETIME; return d->queue_flags&VK_QUEUE_GRAPHICS_BIT ? 0 : BV_ARGUMENT; } #ifdef CID(CommandBuffer.bind_graphics_pipeline) static Term bv_cmd_bind_graphics_pipeline(Env e,Term* f,IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND),*owner=bv_command_device(command); BvRow* pipeline=bv_child(bv_key(e,f[1]),BV_PIPELINE,owner);uint32_t code=bv_graphics_recording(command); if (!code && !pipeline) code=BV_INVALID; if (!code) code=bv_prepare_refs(command,1,&pipeline); if (code) return io_fail(e,code,"bind pipeline owner, recording or reference allocation"); BvDevice* d=owner->context;d->CmdBindPipeline((VkCommandBuffer)(uintptr_t)command->handle,VK_PIPELINE_BIND_POINT_GRAPHICS,(VkPipeline)(uintptr_t)pipeline->handle); BvRecording* r=&command->command.submission.recording;r->pipeline=pipeline;r->vertices_ready=0; memset(command->command.sets,0,sizeof(command->command.sets)); r->push_ready=!bv_dependency(pipeline,BV_DEP_PIPELINE_LAYOUT)->target->object.layout.bytes;return bv_ok(e); } #endif #ifdef CID(CommandBuffer.bind_descriptor_sets) static Term bv_cmd_bind_descriptor_sets(Env e,Term* f,IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND),*owner=bv_command_device(command);uint32_t code=bv_graphics_recording(command),first=f[1],count=0; BvRecording* r=command ? &command->command.submission.recording : NULL; BvRow* layout=!code && r->pipeline ? bv_dependency(r->pipeline,BV_DEP_PIPELINE_LAYOUT)->target : NULL; if(!code && !layout)code=BV_LIFETIME; BvRow* sets[BV_MAX_DESCRIPTOR_SETS];VkDescriptorSet handles[BV_MAX_DESCRIPTOR_SETS];Term list=f[2]; while(term_aux(list)==CID(Con)) { Term item[2];bv_unpack(e,list,2,item);list=item[1];BvRow* set=bv_child(bv_key(e,item[0]),BV_DESCRIPTOR_SET,owner); if(code)continue; if(!set) {code=BV_INVALID;continue;} if(first>=layout->object.layout.count || count>=layout->object.layout.count-first) {code=BV_ARGUMENT;continue;} if(bv_set_pool(set)->object.descriptor_pool.phase!=BV_POOL_READY) {code=BV_LIFETIME;continue;} BvDescriptorSchema* schema=&bv_set_layout(set)->object.schema; if(!bv_schema_equal(schema,&layout->object.layout.sets[first+count]->object.schema)) {code=BV_ARGUMENT;continue;} for(uint32_t j=0;jslots;j++)if(set->object.set.slots[j].tag==BV_UNWRITTEN_UNIFORM || set->object.set.slots[j].tag==BV_UNWRITTEN_SAMPLED)code=BV_LIFETIME; if(!code && r->scope.tag==BV_INSIDE && bv_descriptor_feedback(set,r->scope.data.inside.framebuffer))code=BV_LIFETIME; sets[count]=set;handles[count++]=(VkDescriptorSet)(uintptr_t)set->handle; } if(!code && !count)code=BV_ARGUMENT; if (!code) code=bv_prepare_refs(command,count,sets); if(code)return io_fail(e,code,"descriptor bind recording, complete compatible schemas, feedback or metadata"); BvDevice* d=owner->context;d->CmdBindDescriptorSets((VkCommandBuffer)(uintptr_t)command->handle,VK_PIPELINE_BIND_POINT_GRAPHICS,(VkPipelineLayout)(uintptr_t)layout->handle,first,count,handles,0,NULL); for(uint32_t j=0;jcommand.sets[first+j]=sets[j];return bv_ok(e); } #endif #ifdef CID(CommandBuffer.set_viewport) static Term bv_cmd_set_viewport(Env e,Term* f,IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND);Term p[6];bv_unpack(e,f[1],6,p);uint32_t code=bv_graphics_recording(command); VkViewport v={f32_unbox(p[0]),f32_unbox(p[1]),f32_unbox(p[2]),f32_unbox(p[3]),f32_unbox(p[4]),f32_unbox(p[5])}; for(unsigned j=0;j<6;j++) if(!isfinite(f32_unbox(p[j]))) code=code ? code : BV_ARGUMENT; if (code) return io_fail(e,code,"viewport recording or finite values"); BvDevice* d=bv_command_device(command)->context;VkPhysicalDeviceLimits* l=&d->limits; if (v.width<=0 || v.height<=0 || v.width>l->maxViewportDimensions[0] || v.height>l->maxViewportDimensions[1] || v.xviewportBoundsRange[0] || v.yviewportBoundsRange[0] || (double)v.x+v.width>l->viewportBoundsRange[1] || (double)v.y+v.height>l->viewportBoundsRange[1] || v.minDepth<0 || v.minDepth>1 || v.maxDepth<0 || v.maxDepth>1) return io_fail(e,BV_ARGUMENT,"viewport dimensions, bounds or depth range"); d->CmdSetViewport((VkCommandBuffer)(uintptr_t)command->handle,0,1,&v);command->command.submission.recording.viewport_ready=true;return bv_ok(e); } #endif #ifdef CID(CommandBuffer.set_scissor) static Term bv_cmd_set_scissor(Env e,Term* f,IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND);Term p[4];bv_unpack(e,f[1],4,p);uint32_t code=bv_graphics_recording(command); if (!code && (p[0]>INT32_MAX || p[1]>INT32_MAX || p[2]>INT32_MAX-(uint32_t)p[0] || p[3]>INT32_MAX-(uint32_t)p[1])) code=BV_ARGUMENT; if (code) return io_fail(e,code,"scissor recording, nonnegative offsets or signed extent overflow"); VkRect2D area={{p[0],p[1]},{p[2],p[3]}};BvDevice* d=bv_command_device(command)->context; d->CmdSetScissor((VkCommandBuffer)(uintptr_t)command->handle,0,1,&area);command->command.submission.recording.scissor_ready=true;return bv_ok(e); } #endif #ifdef CID(CommandBuffer.bind_vertex_buffer) static Term bv_cmd_bind_vertex_buffer(Env e,Term* f,IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND),*owner=bv_command_device(command); uint32_t binding=f[1],code=bv_graphics_recording(command);BvRow* buffer=bv_child(bv_key(e,f[2]),BV_BUFFER,owner);uint64_t offset=bv_u64(e,f[3]); if (!code && !buffer) code=BV_INVALID; BvRecording* r=command ? &command->command.submission.recording : NULL; if (!code && (!r->pipeline || !bv_bound_memory(buffer))) code=BV_LIFETIME; uint32_t ordinal=0; if (!code) { BvPipeline* pipeline=&r->pipeline->object.pipeline; while (ordinalcount && pipeline->required[ordinal].binding!=binding) ordinal++; if (ordinal==pipeline->count) code=BV_ARGUMENT; else { BvVertexRequirement* req=&pipeline->required[ordinal]; if (!(buffer->flags&VK_BUFFER_USAGE_VERTEX_BUFFER_BIT) || offset>=buffer->size || (bv_bound_offset(buffer)%req->alignment+offset%req->alignment)%req->alignment || req->first_end>buffer->size-offset) code=BV_ARGUMENT; } } if (!code) code=bv_prepare_refs(command,1,&buffer); if (code) return io_fail(e,code,"vertex binding owner, pipeline, memory, usage, alignment, first record or allocation"); BvDevice* d=owner->context;VkBuffer handle=(VkBuffer)(uintptr_t)buffer->handle; d->CmdBindVertexBuffers((VkCommandBuffer)(uintptr_t)command->handle,binding,1,&handle,&offset); r->vertices_ready|=UINT64_C(1)<VK_INDEX_TYPE_UINT32 || !(buffer->flags&VK_BUFFER_USAGE_INDEX_BUFFER_BIT) || offset>=buffer->size || (bv_bound_offset(buffer)%width+offset%width)%width)) code=BV_ARGUMENT; if (!code) code=bv_prepare_refs(command,1,&buffer); if (code) return io_fail(e,code,"index binding owner, memory, type, usage, alignment, range or allocation"); BvDevice* d=owner->context;d->CmdBindIndexBuffer((VkCommandBuffer)(uintptr_t)command->handle,(VkBuffer)(uintptr_t)buffer->handle,offset,type); BvRecording* r=&command->command.submission.recording;r->index_ready=true;r->index_remaining=buffer->size-offset;r->index_width=width;return bv_ok(e); } #endif #ifdef CID(CommandBuffer.push_constants) static Term bv_cmd_push_constants(Env e,Term* f,IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND);BvWordList words=bv_word_list(e,f[1],32);uint32_t code=bv_graphics_recording(command); BvRecording* r=command ? &command->command.submission.recording : NULL; if (!code && !r->pipeline) code=BV_LIFETIME; BvRow* layout=!code ? bv_dependency(r->pipeline,BV_DEP_PIPELINE_LAYOUT)->target : NULL; if (!code) code=words.code; if (!code && (!layout->object.layout.bytes || words.count*4!=layout->object.layout.bytes)) code=BV_ARGUMENT; if (!code) { BvDevice* d=bv_command_device(command)->context; d->CmdPushConstants((VkCommandBuffer)(uintptr_t)command->handle,(VkPipelineLayout)(uintptr_t)layout->handle,layout->object.layout.stages,0,layout->object.layout.bytes,words.data); r->push_ready=true; } free(words.data);return code ? io_fail(e,code,"push constants require bound pipeline and complete declared word block") : bv_ok(e); } #endif #ifdef CID(CommandBuffer.draw_indexed) static Term bv_cmd_draw_indexed(Env e,Term* f,IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND);Term p[5];bv_unpack(e,f[1],5,p);uint32_t code=bv_graphics_recording(command); if (code) return io_fail(e,code,"indexed draw requires graphics recording"); BvRecording* r=&command->command.submission.recording; if (r->scope.tag!=BV_INSIDE || !r->pipeline || !r->index_ready || !r->viewport_ready || !r->scissor_ready || !r->push_ready) return io_fail(e,BV_LIFETIME,"indexed draw requires pass, pipeline, index, dynamic state and complete pushes"); BvPipelineLayout* layout=&bv_dependency(r->pipeline,BV_DEP_PIPELINE_LAYOUT)->target->object.layout; for(uint32_t j=0;jcount;j++) { BvRow* set=command->command.sets[j]; if((layout->sets[j]->object.schema.slots && !set) || (set && (bv_set_pool(set)->object.descriptor_pool.phase!=BV_POOL_READY || bv_descriptor_feedback(set,r->scope.data.inside.framebuffer)))) return io_fail(e,BV_LIFETIME,"draw requires complete descriptors without attachment feedback"); } BvPipeline* pipeline=&r->pipeline->object.pipeline; uint64_t mask=pipeline->count==64 ? UINT64_MAX : (UINT64_C(1)<count)-1; if ((r->vertices_ready&mask)!=mask || bv_dependency(r->pipeline,BV_DEP_PIPELINE_PASS)->target!=bv_dependency(r->scope.data.inside.framebuffer,BV_DEP_FRAMEBUFFER_PASS)->target) return io_fail(e,BV_LIFETIME,"indexed draw vertex readiness or exact pass identity"); if ((uint64_t)(uint32_t)p[2]+(uint32_t)p[0]>r->index_remaining/r->index_width) return io_fail(e,BV_ARGUMENT,"indexed draw index span"); uint32_t bits=p[3];int32_t base;memcpy(&base,&bits,sizeof(base)); BvDevice* d=bv_command_device(command)->context;d->CmdDrawIndexed((VkCommandBuffer)(uintptr_t)command->handle,p[0],p[1],p[2],base,p[4]);return bv_ok(e); } #endif // Map whole allocations so cache ranges satisfy nonCoherentAtomSize alignment. static int bv_map_range(BvRow* memory,uint64_t offset,uint32_t count) { return (memory->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) && offset<=memory->size && count<=memory->size-offset && offset<=SIZE_MAX && count<=SIZE_MAX-(size_t)offset; } static VkResult bv_map(BvRow* owner,BvRow* memory,void** mapped) { BvDevice* device=owner->context; return device->MapMemory(device->handle,(VkDeviceMemory)(uintptr_t)memory->handle,0,VK_WHOLE_SIZE,0,mapped); } #ifdef CID(Device.write_memory) static Term bv_write_memory(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE); BvRow* memory=bv_child(bv_key(e,f[1]),BV_MEMORY,owner);uint64_t offset=bv_u64(e,f[2]); uint32_t count=0,capacity=64;int valid=1;uint8_t* bytes=malloc(capacity);Term list=f[3]; if (!bytes) {term_sink(e,list);return io_fail(e,BV_LIMIT,"copy allocation failed");} while (term_aux(list)==CID(Con)) { Term fields[2];bv_unpack(e,list,2,fields);list=fields[1]; if ((uint32_t)fields[0]>255 || count>=BV_MAX_COPY) valid=0; if (count>=BV_MAX_COPY) {term_sink(e,list);break;} if (count==capacity) { capacity*=2;uint8_t* grown=realloc(bytes,capacity); if (!grown) {term_sink(e,list);free(bytes);return io_fail(e,BV_LIMIT,"copy allocation failed");}bytes=grown; } bytes[count++]=(uint8_t)fields[0]; } if (!owner || !memory || !valid) {free(bytes);return io_fail(e,valid ? BV_INVALID : BV_ARGUMENT,"invalid memory, byte value, or copy length");} if (bv_lost(owner)) {free(bytes);return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"write_memory");} if (memory->retired || bv_memory_busy(memory)) {free(bytes);return io_fail(e,BV_LIFETIME,"write_memory: allocation is in use");} if (!bv_map_range(memory,offset,count)) {free(bytes);return io_fail(e,BV_ARGUMENT,"write needs host-visible memory and an in-bounds range");} if (!count) {free(bytes);return offset<=memory->size ? bv_ok(e) : io_fail(e,BV_ARGUMENT,"copy offset out of range");} void* mapped=NULL;VkResult result=bv_map(owner,memory,&mapped);BvDevice* device=owner->context; if (result==VK_SUCCESS) { memcpy((uint8_t*)mapped+(size_t)offset,bytes,count); if (!(memory->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) { VkMappedMemoryRange range={.sType=VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, .memory=(VkDeviceMemory)(uintptr_t)memory->handle,.offset=0,.size=VK_WHOLE_SIZE}; result=device->FlushMappedMemoryRanges(device->handle,1,&range); } device->UnmapMemory(device->handle,(VkDeviceMemory)(uintptr_t)memory->handle); } free(bytes);return result==VK_SUCCESS ? bv_ok(e) : bv_device_error(e,owner,result,"write_memory / map or flush"); } #endif #ifdef CID(Device.write_memory_words) static Term bv_write_memory_words(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE); BvRow* memory=bv_child(bv_key(e,f[1]),BV_MEMORY,owner); uint64_t offset=bv_u64(e,f[2]), source=bv_u64(e,f[3]), count=bv_u64(e,f[4]); Term words=f[5], result; if (!owner || !memory) result=io_fail(e,BV_INVALID,"write_memory_words: invalid device or memory"); else if (bv_lost(owner)) result=bv_vk_error(e,VK_ERROR_DEVICE_LOST,"write_memory_words"); else if (memory->retired || bv_memory_busy(memory)) result=io_fail(e,BV_LIFETIME,"write_memory_words: allocation is in use"); else if (term_tag(words)!=TAG_BUF && term_tag(words)!=TAG_ARR) result=io_fail(e,BV_ARGUMENT,"write_memory_words: expected U32 array"); else if (count>BV_MAX_COPY || count>SIZE_MAX) result=io_fail(e,BV_LIMIT,"write_memory_words: 16 MiB chunk limit"); else if (source>(UINT64_C(1)<(UINT64_C(1)<context; VkResult status=bv_map(owner,memory,&mapped); if (status==VK_SUCCESS) { uint64_t location=blk_loc(e.mem,words); bool terms=term_tag(words)==TAG_ARR; for (uint32_t j=0;j<(uint32_t)count;j++) { uint32_t value=(uint32_t)blk_read(e.mem,terms,location,(source+j)/4); ((uint8_t*)mapped)[(size_t)offset+j]=(uint8_t)(value>>(8*((source+j)%4))); } if (!(memory->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) { VkMappedMemoryRange range={.sType=VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, .memory=(VkDeviceMemory)(uintptr_t)memory->handle,.offset=0,.size=VK_WHOLE_SIZE}; status=device->FlushMappedMemoryRanges(device->handle,1,&range); } device->UnmapMemory(device->handle,(VkDeviceMemory)(uintptr_t)memory->handle); } result=status==VK_SUCCESS ? bv_ok(e) : bv_device_error(e,owner,status,"write_memory_words / map or flush"); } return io_tup(e,words,result); } #endif #ifdef CID(Device.read_memory) static Term bv_read_memory(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE); BvRow* memory=bv_child(bv_key(e,f[1]),BV_MEMORY,owner);uint64_t offset=bv_u64(e,f[2]);uint32_t count=(uint32_t)f[3]; if (!owner || !memory) return io_fail(e,BV_INVALID,"invalid memory or device"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"read_memory"); if (memory->retired || bv_memory_busy(memory)) return io_fail(e,BV_LIFETIME,"read_memory: allocation is in use"); if (count>BV_MAX_COPY) return io_fail(e,BV_LIMIT,"read exceeds 16 MiB chunk limit"); if (!bv_map_range(memory,offset,count)) return io_fail(e,BV_ARGUMENT,"read needs host-visible memory and an in-bounds range"); if (!count) return offset<=memory->size ? io_done(e,term_pak(CID(Nil),0)) : io_fail(e,BV_ARGUMENT,"copy offset out of range"); void* mapped=NULL;VkResult result=bv_map(owner,memory,&mapped);BvDevice* device=owner->context; Term list=term_pak(CID(Nil),0); if (result==VK_SUCCESS) { if (!(memory->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) { VkMappedMemoryRange range={.sType=VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, .memory=(VkDeviceMemory)(uintptr_t)memory->handle,.offset=0,.size=VK_WHOLE_SIZE}; result=device->InvalidateMappedMemoryRanges(device->handle,1,&range); } if (result==VK_SUCCESS) for (uint32_t j=count;j>0;j--) list=io_node(e,CID(Con),((uint8_t*)mapped)[(size_t)offset+j-1],list); device->UnmapMemory(device->handle,(VkDeviceMemory)(uintptr_t)memory->handle); } return result==VK_SUCCESS ? io_done(e,list) : bv_device_error(e,owner,result,"read_memory / map or invalidate"); } #endif #ifdef CID(Device.create_command_pool) static Term bv_create_command_pool(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE); if (!owner) return io_fail(e,BV_INVALID,"invalid device"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"bv_create_command_pool"); BvDevice* device=owner->context; if (!(device->queue_flags & (VK_QUEUE_GRAPHICS_BIT|VK_QUEUE_COMPUTE_BIT|VK_QUEUE_TRANSFER_BIT))) return io_fail(e,BV_ARGUMENT,"command pool needs a transfer-capable queue family"); VkCommandPoolCreateInfo info={.sType=VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,.queueFamilyIndex=device->family,.flags=VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT}; VkCommandPool pool;VkResult result=device->CreateCommandPool(device->handle,&info,NULL,&pool); if (result!=VK_SUCCESS) return bv_device_error(e,owner,result,"vkCreateCommandPool"); BvRow* row=bv_add(BV_POOL,owner); if (!row) {device->DestroyCommandPool(device->handle,pool,NULL);return io_fail(e,BV_LIMIT,"command pool registry full");} row->handle=(uint64_t)(uintptr_t)pool; return io_done(e,term_pak(CID(CommandPool),row->id)); } #endif #ifdef CID(Device.destroy_command_pool) static Term bv_destroy_command_pool(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);BvRow* pool=bv_child(bv_key(e,f[1]),BV_POOL,owner); if (!owner || !pool) return io_fail(e,BV_INVALID,"invalid command pool or device"); for (BvRow* row=bv_rows;row;row=row->next) if (row->parent==pool && bv_command_fence(row)) return io_fail(e,BV_LIFETIME,"pool has active commands"); bv_destroy_pool(pool);return bv_ok(e); } #endif #ifdef CID(Device.allocate_command_buffer) static Term bv_allocate_command_buffer(Env e, Term* f, IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);BvRow* pool=bv_child(bv_key(e,f[1]),BV_POOL,owner); if (!owner || !pool) return io_fail(e,BV_INVALID,"invalid command pool or device"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"bv_allocate_command_buffer"); BvDevice* device=owner->context;BvRow* row=bv_add(BV_COMMAND,pool); if (!row) return io_fail(e,BV_LIMIT,"command buffer registry full"); VkCommandBufferAllocateInfo info={.sType=VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .commandPool=(VkCommandPool)(uintptr_t)pool->handle,.level=VK_COMMAND_BUFFER_LEVEL_PRIMARY,.commandBufferCount=1}; VkCommandBuffer command;VkResult result=device->AllocateCommandBuffers(device->handle,&info,&command); if (result!=VK_SUCCESS) {bv_remove(row);return bv_device_error(e,owner,result,"vkAllocateCommandBuffers");} row->handle=(uint64_t)(uintptr_t)command; return io_done(e,term_pak(CID(CommandBuffer),row->id)); } #endif #ifdef CID(CommandBuffer.begin) static Term bv_begin_command_buffer(Env e, Term* f, IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND); if (!command) return io_fail(e,BV_INVALID,"invalid command buffer"); if (bv_lost(bv_command_device(command))) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"bv_begin_command_buffer"); if (command->command.phase!=BV_INITIAL) return io_fail(e,BV_LIFETIME,"begin requires Initial; reset before re-recording"); if (command->command.generation==UINT64_MAX) return io_fail(e,BV_LIMIT,"command recording sequence exhausted"); BvDevice* device=bv_command_device(command)->context; VkCommandBufferBeginInfo info={.sType=VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,.flags=VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; VkResult result=device->BeginCommandBuffer((VkCommandBuffer)(uintptr_t)command->handle,&info); if (result!=VK_SUCCESS) {command->command.phase=BV_COMMAND_INVALID;memset(&command->command.submission,0,sizeof(command->command.submission));return bv_device_error(e,bv_command_device(command),result,"vkBeginCommandBuffer");} memset(&command->command.submission,0,sizeof(command->command.submission)); command->command.generation++; command->command.phase=BV_RECORDING;command->command.submission.recording.scope=(BvRenderScope){.tag=BV_OUTSIDE};return bv_ok(e); } #endif #ifdef CID(CommandBuffer.fill_buffer) static Term bv_cmd_fill_buffer(Env e, Term* f, IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND);uint32_t id=bv_key(e,f[1]); uint64_t offset=bv_u64(e,f[2]),size=bv_u64(e,f[3]); BvRow* owner=bv_command_device(command);BvRow* buffer=bv_child(id,BV_BUFFER,owner); if (!command || !buffer) return io_fail(e,BV_INVALID,"command and buffer must belong to same device"); if (bv_lost(bv_command_device(command))) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"bv_cmd_fill_buffer"); if (!bv_outside(command) || !bv_bound_memory(buffer)) return io_fail(e,BV_LIFETIME,"fill needs recording command and bound buffer"); if (size==VK_WHOLE_SIZE && offsetsize) size=(buffer->size-offset)&~UINT64_C(3); if (!size || offset>buffer->size || size>buffer->size-offset || ((offset|size)&3) || !(buffer->flags & VK_BUFFER_USAGE_TRANSFER_DST_BIT)) return io_fail(e,BV_ARGUMENT,"invalid fill offset, size, alignment, or usage"); uint32_t refs=bv_prepare_refs(command,1,&buffer); if (refs) return io_fail(e,refs,"command reference allocation or retired resource"); BvDevice* device=owner->context; device->CmdFillBuffer((VkCommandBuffer)(uintptr_t)command->handle,(VkBuffer)(uintptr_t)buffer->handle,offset,size,(uint32_t)f[4]); return bv_ok(e); } #endif static int bv_overlap(uint64_t a, uint64_t na, uint64_t b, uint64_t nb) { return a<=b ? b-aflags & VK_BUFFER_USAGE_TRANSFER_SRC_BIT) || !(dst->flags & VK_BUFFER_USAGE_TRANSFER_DST_BIT)) ? BV_ARGUMENT : 0; VkBufferCopy* regions=NULL; uint32_t count=0; Term list=f[3]; while (term_aux(list)==CID(Con)) { Term item[2],fields[6]; bv_unpack(e,list,2,item);list=item[1];bv_unpack(e,item[0],6,fields); if (code) continue; uint64_t a=((uint64_t)(uint32_t)fields[1]<<32)|(uint32_t)fields[0]; uint64_t b=((uint64_t)(uint32_t)fields[3]<<32)|(uint32_t)fields[2]; uint64_t n=((uint64_t)(uint32_t)fields[5]<<32)|(uint32_t)fields[4]; if (!n || a>src->size || n>src->size-a || b>dst->size || n>dst->size-b) {code=BV_ARGUMENT;continue;} if (count>=4096) {code=BV_LIMIT;continue;} VkBufferCopy* more=realloc(regions,(count+1)*sizeof(*regions)); if (!more) {code=BV_LIMIT;continue;} regions=more; regions[count++]=(VkBufferCopy){.srcOffset=a,.dstOffset=b,.size=n}; } if (!code && !count) code=BV_ARGUMENT; for (uint32_t j=0;!code && jcontext; device->CmdCopyBuffer((VkCommandBuffer)(uintptr_t)command->handle,(VkBuffer)(uintptr_t)src->handle, (VkBuffer)(uintptr_t)dst->handle,count,regions); } free(regions); return code ? io_fail(e,code,"copy_buffer: invalid state, usage, range, alias overlap, or allocation") : bv_ok(e); } #endif #ifdef CID(CommandBuffer.pipeline_barrier) static Term bv_cmd_pipeline_barrier(Env e, Term* f, IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND); BvRow* owner=bv_command_device(command); BvDevice* device=owner ? owner->context : NULL; uint32_t src=device ? bv_baseline_stages(device,(uint32_t)f[1]) : 0; uint32_t dst=device ? bv_baseline_stages(device,(uint32_t)f[2]) : 0; uint32_t code=!command ? BV_INVALID : !bv_outside(command) ? BV_LIFETIME : (!src || !dst) ? BV_ARGUMENT : 0; VkMemoryBarrier* memory=NULL; VkBufferMemoryBarrier* buffers=NULL; VkImageMemoryBarrier* images=NULL; BvRow** resources=NULL; uint32_t nm=0,nb=0,ni=0; Term list=f[3]; while (term_aux(list)==CID(Con)) { Term item[2],fields[2]; bv_unpack(e,list,2,item); list=item[1]; bv_unpack(e,item[0],2,fields); if (code) continue; if (nm>=4096) {code=BV_LIMIT;continue;} if (!bv_access(src,(uint32_t)fields[0]) || !bv_access(dst,(uint32_t)fields[1])) {code=BV_ARGUMENT;continue;} VkMemoryBarrier* more=realloc(memory,(nm+1)*sizeof(*memory)); if (!more) {code=BV_LIMIT;continue;} memory=more; memory[nm++]=(VkMemoryBarrier){.sType=VK_STRUCTURE_TYPE_MEMORY_BARRIER,.srcAccessMask=(uint32_t)fields[0],.dstAccessMask=(uint32_t)fields[1]}; } list=f[4]; while (term_aux(list)==CID(Con)) { Term item[2],fields[7]; bv_unpack(e,list,2,item);list=item[1];bv_unpack(e,item[0],7,fields); if (code) continue; BvRow* buffer=bv_child((uint32_t)fields[0],BV_BUFFER,owner); uint64_t offset=((uint64_t)(uint32_t)fields[2]<<32)|(uint32_t)fields[1]; uint64_t size=((uint64_t)(uint32_t)fields[4]<<32)|(uint32_t)fields[3]; if (!buffer) {code=BV_INVALID;continue;} if (!bv_bound_memory(buffer)) {code=BV_LIFETIME;continue;} if (size==VK_WHOLE_SIZE && offsetsize) size=buffer->size-offset; if (!size || offset>buffer->size || size>buffer->size-offset || !bv_access(src,(uint32_t)fields[5]) || !bv_access(dst,(uint32_t)fields[6])) {code=BV_ARGUMENT;continue;} if (nb>=4096) {code=BV_LIMIT;continue;} VkBufferMemoryBarrier* more=realloc(buffers,(nb+1)*sizeof(*buffers)); if (!more) {code=BV_LIMIT;continue;} buffers=more; BvRow** refs=realloc(resources,(nb+1)*sizeof(*resources)); if (!refs) {code=BV_LIMIT;continue;} resources=refs; resources[nb]=buffer; buffers[nb++]=(VkBufferMemoryBarrier){.sType=VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, .srcAccessMask=(uint32_t)fields[5],.dstAccessMask=(uint32_t)fields[6], .srcQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED,.dstQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED, .buffer=(VkBuffer)(uintptr_t)buffer->handle,.offset=offset,.size=size}; } list=f[5]; while (term_aux(list)==CID(Con)) { Term item[2],p[10];bv_unpack(e,list,2,item);list=item[1];bv_unpack(e,item[0],10,p); if (code) continue; BvRow* image=bv_child((uint32_t)p[0],BV_IMAGE,owner); if (!image) {code=BV_INVALID;continue;} if (!bv_image_available(image)) {code=BV_LIFETIME;continue;} VkImageSubresourceRange range=bv_image_range(p+1); if (!bv_image_range_valid(image,range) || !bv_image_layout(image,p[6],1) || !bv_image_layout(image,p[7],0) || (!p[6] && p[8]) || !bv_access(src,p[8]) || !bv_access(dst,p[9])) {code=BV_ARGUMENT;continue;} for (uint32_t j=0;jhandle && bv_ranges_overlap(images[j].subresourceRange,range)) code=BV_ARGUMENT; if (code) continue; if (ni>=4096) {code=BV_LIMIT;continue;} VkImageMemoryBarrier* more=realloc(images,(ni+1)*sizeof(*images)); if (!more) {code=BV_LIMIT;continue;}images=more; BvRow** refs=realloc(resources,(nb+ni+1)*sizeof(*resources)); if (!refs) {code=BV_LIMIT;continue;}resources=refs;resources[nb+ni]=image; images[ni++]=(VkImageMemoryBarrier){.sType=VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .srcAccessMask=p[8],.dstAccessMask=p[9],.oldLayout=p[6],.newLayout=p[7], .srcQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED,.dstQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED, .image=(VkImage)(uintptr_t)image->handle,.subresourceRange=range}; } if (owner && bv_lost(owner)) {free(memory);free(buffers);free(images);free(resources);return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"pipeline_barrier");} if (!code) code=bv_prepare_refs(command,nb+ni,resources); if (!code) device->CmdPipelineBarrier((VkCommandBuffer)(uintptr_t)command->handle, (uint32_t)f[1],(uint32_t)f[2],0,nm,memory,nb,buffers,ni,images); free(memory);free(buffers);free(images);free(resources); return code ? io_fail(e,code,"pipeline_barrier: invalid state, stages, access, layout, range, or allocation") : bv_ok(e); } #endif static int bv_add64(uint64_t a,uint64_t b,uint64_t* out) { if (b>UINT64_MAX-a) return 0; *out=a+b;return 1; } static int bv_mul64(uint64_t a,uint64_t b,uint64_t* out) { if (b && a>UINT64_MAX/b) return 0; *out=a*b;return 1; } static int bv_copy_end(uint64_t offset,uint32_t row_length,uint32_t image_height,uint32_t width,uint32_t height,uint32_t layers,uint32_t bytes,uint64_t* end) { uint64_t row,layer,last_layer,last_row,payload,total; uint32_t r=row_length ? row_length : width,h=image_height ? image_height : height; return width && height && layers && bytes && r>=width && h>=height && bv_mul64(r,bytes,&row) && bv_mul64(h,row,&layer) && bv_mul64(layers-1,layer,&last_layer) && bv_mul64(height-1,row,&last_row) && bv_mul64(width,bytes,&payload) && bv_add64(last_layer,last_row,&total) && bv_add64(total,payload,&total) && bv_add64(offset,total,end); } static int bv_transfer_axis(uint32_t offset,uint32_t extent,uint32_t limit,uint32_t granularity) { return !granularity ? (!offset && extent==limit) : !(offset%granularity) && (!(extent%granularity) || extent==limit-offset); } static uint32_t bv_image_command_state(BvRow* command,BvRow* image,uint32_t usage,uint32_t layout) { if (!command || !image) return BV_INVALID; if (!bv_outside(command) || !bv_image_available(image)) return BV_LIFETIME; if (!(image->object.image.usage&usage) || (layout!=VK_IMAGE_LAYOUT_GENERAL && layout!=(usage==VK_IMAGE_USAGE_TRANSFER_SRC_BIT ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL))) return BV_ARGUMENT; return 0; } #if defined(CID(CommandBuffer.clear_color_image)) || defined(CID(CommandBuffer.clear_depth_image)) static Term bv_clear_image(Env e,Term* f,int depth) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND),*owner=bv_command_device(command); BvRow* image=bv_child(bv_key(e,f[1]),BV_IMAGE,owner);uint32_t layout=f[2]; uint32_t code=bv_image_command_state(command,image,VK_IMAGE_USAGE_TRANSFER_DST_BIT,layout); VkClearColorValue color={0};VkClearDepthStencilValue value={0}; if (depth) {value.depth=f32_unbox(f[3]);if (!isfinite(value.depth) || value.depth<0 || value.depth>1) code=BV_ARGUMENT;} else { Term lanes[4];bv_unpack(e,f[3],4,lanes); for (unsigned j=0;j<4;j++) {color.float32[j]=f32_unbox(lanes[j]);if (!isfinite(color.float32[j])) code=BV_ARGUMENT;} } BvDevice* device=owner ? owner->context : NULL; if (!code && (bv_format(image->object.image.format)->aspect!=(depth ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT) || !(device->queue_flags&(depth ? VK_QUEUE_GRAPHICS_BIT : VK_QUEUE_GRAPHICS_BIT|VK_QUEUE_COMPUTE_BIT)))) code=BV_ARGUMENT; VkImageSubresourceRange* ranges=NULL;uint32_t count=0;Term list=f[4]; while (term_aux(list)==CID(Con)) { Term item[2],p[5];bv_unpack(e,list,2,item);list=item[1];bv_unpack(e,item[0],5,p); if (code) continue; VkImageSubresourceRange range=bv_image_range(p); if (!bv_image_range_valid(image,range)) {code=BV_ARGUMENT;continue;} for (uint32_t j=0;j=4096) {code=BV_LIMIT;continue;} VkImageSubresourceRange* more=realloc(ranges,(count+1)*sizeof(*ranges)); if (!more) {code=BV_LIMIT;continue;}ranges=more;ranges[count++]=range; } if (!code && !count) code=BV_ARGUMENT; if (owner && bv_lost(owner)) {free(ranges);return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"clear image");} if (!code) code=bv_prepare_refs(command,1,&image); if (!code) { if (depth) device->CmdClearDepthStencilImage((VkCommandBuffer)(uintptr_t)command->handle,(VkImage)(uintptr_t)image->handle,layout,&value,count,ranges); else device->CmdClearColorImage((VkCommandBuffer)(uintptr_t)command->handle,(VkImage)(uintptr_t)image->handle,layout,&color,count,ranges); } free(ranges);return code ? io_fail(e,code,"clear image state, queue, layout, values, ranges or allocation") : bv_ok(e); } #endif #ifdef CID(CommandBuffer.clear_color_image) static Term bv_cmd_clear_color_image(Env e,Term* f,IoWork* w) {return bv_clear_image(e,f,0);} #endif #ifdef CID(CommandBuffer.clear_depth_image) static Term bv_cmd_clear_depth_image(Env e,Term* f,IoWork* w) {return bv_clear_image(e,f,1);} #endif #if defined(CID(CommandBuffer.copy_buffer_to_image)) || defined(CID(CommandBuffer.copy_image_to_buffer)) static Term bv_copy_image_buffer(Env e,Term* f,int upload) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND),*owner=bv_command_device(command); BvRow* image=bv_child(bv_key(e,f[upload ? 2 : 1]),BV_IMAGE,owner); BvRow* buffer=bv_child(bv_key(e,f[upload ? 1 : 3]),BV_BUFFER,owner); uint32_t layout=f[upload ? 3 : 2],usage=upload ? VK_IMAGE_USAGE_TRANSFER_DST_BIT : VK_IMAGE_USAGE_TRANSFER_SRC_BIT; uint32_t code=bv_image_command_state(command,image,usage,layout); BvDevice* device=owner ? owner->context : NULL;const BvFormat* format=image ? bv_format(image->object.image.format) : NULL; if (!buffer) code=BV_INVALID; else if (!bv_bound_memory(buffer)) code=BV_LIFETIME; else if (!(buffer->flags&(upload ? VK_BUFFER_USAGE_TRANSFER_SRC_BIT : VK_BUFFER_USAGE_TRANSFER_DST_BIT))) code=BV_ARGUMENT; if (!code && (!(device->queue_flags&(VK_QUEUE_GRAPHICS_BIT|VK_QUEUE_COMPUTE_BIT|VK_QUEUE_TRANSFER_BIT)) || (format->aspect==VK_IMAGE_ASPECT_DEPTH_BIT && !(device->queue_flags&VK_QUEUE_GRAPHICS_BIT)))) code=BV_ARGUMENT; VkBufferImageCopy* regions=NULL;uint32_t count=0;Term list=f[4]; while (term_aux(list)==CID(Con)) { Term item[2],p[12];bv_unpack(e,list,2,item);list=item[1];bv_unpack(e,item[0],12,p); if (code) continue; VkBufferImageCopy r={.bufferOffset=((uint64_t)(uint32_t)p[1]<<32)|(uint32_t)p[0],.bufferRowLength=p[2],.bufferImageHeight=p[3], .imageSubresource={p[4],p[5],p[6],p[7]},.imageOffset={(int32_t)(uint32_t)p[8],(int32_t)(uint32_t)p[9],0},.imageExtent={p[10],p[11],1}}; BvImage* i=&image->object.image;uint32_t mip=r.imageSubresource.mipLevel; uint32_t w=bv_mip_dimension(i->extent.width,mip),h=bv_mip_dimension(i->extent.height,mip);uint64_t end,row; if (r.imageSubresource.aspectMask!=format->aspect || mip>=i->mips || !bv_range_contains(i->layers,r.imageSubresource.baseArrayLayer,r.imageSubresource.layerCount) || (uint32_t)p[8]>INT32_MAX || (uint32_t)p[9]>INT32_MAX || r.imageExtent.width>INT32_MAX || r.imageExtent.height>INT32_MAX || (uint32_t)p[8]>w || r.imageExtent.width>w-(uint32_t)p[8] || (uint32_t)p[9]>h || r.imageExtent.height>h-(uint32_t)p[9] || (r.bufferOffset&3) || !bv_copy_end(r.bufferOffset,r.bufferRowLength,r.bufferImageHeight,r.imageExtent.width,r.imageExtent.height, r.imageSubresource.layerCount,format->bytes,&end) || end>buffer->size || !bv_mul64(r.bufferRowLength ? r.bufferRowLength : r.imageExtent.width,format->bytes,&row) || row>INT32_MAX) {code=BV_ARGUMENT;continue;} VkExtent3D g=device->queue_properties.minImageTransferGranularity; if (!bv_transfer_axis(p[8],r.imageExtent.width,w,g.width) || !bv_transfer_axis(p[9],r.imageExtent.height,h,g.height) || !bv_transfer_axis(0,1,1,g.depth)) {code=BV_ARGUMENT;continue;} for (uint32_t j=0;jbytes,&previous); if (bv_overlap(a.bufferOffset,previous-a.bufferOffset,r.bufferOffset,end-r.bufferOffset)) code=BV_ARGUMENT; } } if (code) continue; if (count>=4096) {code=BV_LIMIT;continue;} VkBufferImageCopy* more=realloc(regions,(count+1)*sizeof(*regions)); if (!more) {code=BV_LIMIT;continue;}regions=more;regions[count++]=r; } if (!code && !count) code=BV_ARGUMENT; if (owner && bv_lost(owner)) {free(regions);return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"copy image buffer");} BvRow* roots[]={buffer,image};if (!code) code=bv_prepare_refs(command,2,roots); if (!code) { if (upload) device->CmdCopyBufferToImage((VkCommandBuffer)(uintptr_t)command->handle,(VkBuffer)(uintptr_t)buffer->handle,(VkImage)(uintptr_t)image->handle,layout,count,regions); else device->CmdCopyImageToBuffer((VkCommandBuffer)(uintptr_t)command->handle,(VkImage)(uintptr_t)image->handle,layout,(VkBuffer)(uintptr_t)buffer->handle,count,regions); } free(regions);return code ? io_fail(e,code,"copy image buffer state, queue, layout, region, overlap or allocation") : bv_ok(e); } #endif #ifdef CID(CommandBuffer.copy_buffer_to_image) static Term bv_cmd_copy_buffer_to_image(Env e,Term* f,IoWork* w) {return bv_copy_image_buffer(e,f,1);} #endif #ifdef CID(CommandBuffer.copy_image_to_buffer) static Term bv_cmd_copy_image_to_buffer(Env e,Term* f,IoWork* w) {return bv_copy_image_buffer(e,f,0);} #endif #ifdef CID(CommandBuffer.end) static Term bv_end_command_buffer(Env e, Term* f, IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND); if (!command) return io_fail(e,BV_INVALID,"invalid command buffer"); if (bv_lost(bv_command_device(command))) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"bv_end_command_buffer"); if (!bv_outside(command)) return io_fail(e,BV_LIFETIME,"command buffer is not recording"); BvDevice* device=bv_command_device(command)->context; VkResult result=device->EndCommandBuffer((VkCommandBuffer)(uintptr_t)command->handle); if (result!=VK_SUCCESS) {command->command.phase=BV_COMMAND_INVALID;memset(&command->command.submission,0,sizeof(command->command.submission));return bv_device_error(e,bv_command_device(command),result,"vkEndCommandBuffer");} command->command.phase=BV_EXECUTABLE;memset(&command->command.submission,0,sizeof(command->command.submission));return bv_ok(e); } #endif static uint32_t bv_new_fence(BvRow* owner,int signaled,BvFenceLifetime lifetime,BvRow** out,VkResult* status) { BvDevice* device=owner->context; VkFenceCreateInfo info={.sType=VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,.flags=signaled ? VK_FENCE_CREATE_SIGNALED_BIT : 0}; VkFence handle; *status=bv_device_result(owner,device->CreateFence(device->handle,&info,NULL,&handle)); if (*status!=VK_SUCCESS) return 0; BvRow* fence=bv_add(BV_FENCE,owner); if (!fence) {device->DestroyFence(device->handle,handle,NULL);return BV_LIMIT;} fence->handle=(uint64_t)(uintptr_t)handle;fence->fence.lifetime=lifetime;*out=fence;return 0; } static Term bv_submit_core_impl(Env e,BvRow* owner,BvRow* command,BvRow* fence,const VkSubmitInfo* synced) { if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"submit"); if (fence->fence.use!=BV_FENCE_FREE) return io_fail(e,BV_LIFETIME,"submit fence has WSI association"); if (bv_sealed(command,BV_KIND_COUNT)) return io_fail(e,BV_LIFETIME,"submit references retired resources"); if (command->command.phase!=BV_EXECUTABLE || bv_active(owner,fence) || bv_uncertain(owner)) return io_fail(e,BV_LIFETIME,"submit needs executable command, free fence and certain device"); BvDevice* device=owner->context; for(BvDep* dep=command->deps;dep;dep=dep->next) if(dep->target->kind==BV_DESCRIPTOR_SET && bv_set_pool(dep->target)->object.descriptor_pool.phase!=BV_POOL_READY) return io_fail(e,BV_LIFETIME,"submit descriptor pool quarantined"); BvLease* lease=command->command.lease; if (lease && (lease->serial!=command->command.lease_serial || lease->phase!=BV_LEASE_ACQUIRED)) return io_fail(e,BV_LIFETIME,"submit acquisition generation is stale or incomplete"); for(BvRow* image=bv_rows;image;image=image->next)if(image->kind==BV_IMAGE && image->parent==owner && image->object.image.storage==BV_BORROWED_IMAGE && bv_may_reach_depth(command,image,BV_KIND_COUNT) && (!bv_image_available(image) || bv_image_lease(image)!=lease))return io_fail(e,BV_LIFETIME,"submit borrowed image does not match completed acquisition"); VkResult result=bv_device_result(owner,device->GetFenceStatus(device->handle,(VkFence)(uintptr_t)fence->handle)); if (result==VK_SUCCESS) return io_fail(e,BV_LIFETIME,"submit fence must be unsignaled"); if (result!=VK_NOT_READY) return bv_vk_error(e,result,"submit / vkGetFenceStatus"); VkCommandBuffer handle=(VkCommandBuffer)(uintptr_t)command->handle; VkSubmitInfo submit={.sType=VK_STRUCTURE_TYPE_SUBMIT_INFO,.commandBufferCount=1,.pCommandBuffers=&handle}; result=bv_device_result(owner,device->QueueSubmit(device->queue,1,synced ? synced : &submit,(VkFence)(uintptr_t)fence->handle)); if (result==VK_SUCCESS) { memset(&command->command.submission,0,sizeof(command->command.submission)); command->command.phase=BV_PENDING;command->command.submission.pending.fence=fence; if (lease) lease->phase=BV_LEASE_RENDERING; } else if (result!=VK_ERROR_OUT_OF_HOST_MEMORY && result!=VK_ERROR_OUT_OF_DEVICE_MEMORY && result!=VK_ERROR_DEVICE_LOST) { memset(&command->command.submission,0,sizeof(command->command.submission)); command->command.phase=BV_UNCERTAIN;command->command.submission.uncertain.fence=fence; if (lease) lease->phase=BV_LEASE_RENDER_UNCERTAIN; } return result==VK_SUCCESS ? bv_ok(e) : bv_vk_error(e,result,"vkQueueSubmit"); } static Term bv_submit_core(Env e,BvRow* owner,BvRow* command,BvRow* fence) {return bv_submit_core_impl(e,owner,command,fence,NULL);} #ifdef CID(Device.submit_synced) static Term bv_submit_synced(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*command=bv_get(bv_key(e,f[1]),BV_COMMAND),*fence=bv_public_fence(bv_key(e,f[2])); BvDevice* device=owner ? owner->context : NULL;uint32_t code=(!owner || bv_command_device(command)!=owner || !fence || fence->parent!=owner) ? BV_INVALID : 0; VkSemaphore waits[64],signals[64];VkPipelineStageFlags stages[64];BvRow* rows[128];uint32_t nw=0,ns=0,n=0;BvDep* staged=NULL; for(unsigned list_index=0;list_index<2;list_index++) { Term list=f[3+list_index]; while(term_aux(list)==CID(Con)) { Term pair[2];bv_unpack(e,list,2,pair);list=pair[1];uint32_t id,mask=0; if(!list_index) {Term p[2];bv_unpack(e,pair[0],2,p);id=p[0];mask=p[1];}else id=bv_key(e,pair[0]); BvRow* semaphore=bv_child(id,BV_SEMAPHORE,owner); if(code)continue; if(!semaphore) {code=BV_INVALID;continue;} if((!list_index && nw==64) || (list_index && ns==64)) {code=BV_LIMIT;continue;} for(uint32_t j=0;jsemaphore.phase!=BV_SEM_SIGNALED || !bv_baseline_stages(device,mask) || (mask&VK_PIPELINE_STAGE_HOST_BIT))) || (list_index && semaphore->semaphore.phase!=BV_SEM_UNUSED)) {code=BV_LIFETIME;continue;} BvDep* dep=malloc(sizeof(*dep));if(!dep) {code=BV_LIMIT;continue;} *dep=(BvDep){.target=semaphore,.role=list_index ? BV_DEP_SUBMIT_SIGNAL : BV_DEP_SUBMIT_WAIT,.next=staged};staged=dep;rows[n++]=semaphore; if(list_index)signals[ns++]=(VkSemaphore)(uintptr_t)semaphore->handle; else {waits[nw]=(VkSemaphore)(uintptr_t)semaphore->handle;stages[nw++]=mask;} } } if(code) {bv_free_refs(staged);return io_fail(e,code,"submission semaphore ownership, state, duplicates, stage or metadata");} VkCommandBuffer handle=(VkCommandBuffer)(uintptr_t)command->handle; VkSubmitInfo submit={.sType=VK_STRUCTURE_TYPE_SUBMIT_INFO,.waitSemaphoreCount=nw,.pWaitSemaphores=waits,.pWaitDstStageMask=stages,.commandBufferCount=1,.pCommandBuffers=&handle,.signalSemaphoreCount=ns,.pSignalSemaphores=signals}; BvCommandPhase before=command->command.phase; Term result=bv_submit_core_impl(e,owner,command,fence,&submit); if(before==BV_EXECUTABLE && (command->command.phase==BV_PENDING || command->command.phase==BV_UNCERTAIN)) { while(staged) { BvDep* next=staged->next;staged->target->semaphore.phase=command->command.phase==BV_UNCERTAIN ? BV_SEM_UNCERTAIN : staged->role==BV_DEP_SUBMIT_WAIT ? BV_SEM_SUBMIT_WAIT : BV_SEM_SIGNAL_PENDING; if(staged->role==BV_DEP_SUBMIT_SIGNAL) { BvLease* lease=command->command.lease; staged->target->semaphore.producer=lease ? lease->swapchain : NULL; staged->target->semaphore.producer_serial=lease ? command->command.lease_serial : 0; } staged->next=command->deps;command->deps=staged;staged=next; } }else bv_free_refs(staged); return result; } #endif static Term bv_fence_observe(Env e,BvRow* fence,int wait,uint64_t timeout) { BvRow* owner=fence->parent;BvDevice* device=owner->context; if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"fence observation"); BvRow* command=bv_active(owner,fence); if (command && command->command.phase==BV_UNCERTAIN) return io_fail(e,BV_LIFETIME,"uncertain submission requires Device.wait_idle"); VkFence handle=(VkFence)(uintptr_t)fence->handle; VkResult result=bv_device_result(owner,wait ? device->WaitForFences(device->handle,1,&handle,VK_TRUE,timeout) : device->GetFenceStatus(device->handle,handle)); if (result==VK_SUCCESS && command) bv_complete(command); if (result==VK_SUCCESS && fence->fence.use!=BV_FENCE_FREE) bv_finish_wsi_fence(fence); if (result==VK_SUCCESS || result==(wait ? VK_TIMEOUT : VK_NOT_READY)) return io_done(e,(uint32_t)result); return bv_vk_error(e,result,wait ? "vkWaitForFences" : "vkGetFenceStatus"); } #ifdef CID(Device.create_fence) static Term bv_create_fence(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE); if (!owner) return io_fail(e,BV_INVALID,"invalid device"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"create_fence"); BvRow* fence=NULL;VkResult status=VK_SUCCESS; uint32_t code=bv_new_fence(owner,term_aux(f[1])==CID(True),BV_CALLER,&fence,&status); if (code) return io_fail(e,code,"fence registry full"); return status==VK_SUCCESS ? io_done(e,term_pak(CID(Fence),fence->id)) : bv_vk_error(e,status,"vkCreateFence"); } #endif #ifdef CID(Device.destroy_fence) static Term bv_destroy_fence(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);BvRow* fence=bv_public_fence(bv_key(e,f[1])); if (!owner || !fence || fence->parent!=owner) return io_fail(e,BV_INVALID,"invalid fence or device"); if (bv_active(owner,fence) || fence->fence.use!=BV_FENCE_FREE) return io_fail(e,BV_LIFETIME,"fence has active submission or WSI association"); BvDevice* device=owner->context;device->DestroyFence(device->handle,(VkFence)(uintptr_t)fence->handle,NULL); bv_remove(fence);return bv_ok(e); } #endif #ifdef CID(Device.submit) static Term bv_submit(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);BvRow* command=bv_get(bv_key(e,f[1]),BV_COMMAND); BvRow* fence=bv_public_fence(bv_key(e,f[2])); if (!owner || bv_command_device(command)!=owner || !fence || fence->parent!=owner) return io_fail(e,BV_INVALID,"submit ownership mismatch"); return bv_submit_core(e,owner,command,fence); } #endif #ifdef CID(Fence.status) static Term bv_fence_status(Env e,Term* f,IoWork* w) { BvRow* fence=bv_public_fence(bv_key(e,f[0])); return fence ? bv_fence_observe(e,fence,0,0) : io_fail(e,BV_INVALID,"invalid public fence"); } #endif #ifdef CID(Fence.wait) static Term bv_fence_wait(Env e,Term* f,IoWork* w) { BvRow* fence=bv_public_fence(bv_key(e,f[0]));uint64_t timeout=bv_u64(e,f[1]); return fence ? bv_fence_observe(e,fence,1,timeout) : io_fail(e,BV_INVALID,"invalid public fence"); } #endif static Term bv_reset_fence_core(Env e,BvRow* fence) { BvRow* owner=fence->parent;BvDevice* device=owner->context; if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"fence reset"); if (bv_active(owner,fence) || fence->fence.use!=BV_FENCE_FREE) return io_fail(e,BV_LIFETIME,"fence has active submission or WSI association"); VkFence handle=(VkFence)(uintptr_t)fence->handle; VkResult result=bv_device_result(owner,device->ResetFences(device->handle,1,&handle)); return result==VK_SUCCESS ? bv_ok(e) : bv_vk_error(e,result,"vkResetFences"); } #ifdef CID(Fence.reset) static Term bv_fence_reset(Env e,Term* f,IoWork* w) { BvRow* fence=bv_public_fence(bv_key(e,f[0])); return fence ? bv_reset_fence_core(e,fence) : io_fail(e,BV_INVALID,"invalid public fence"); } #endif #ifdef CID(CommandBuffer.reset) static Term bv_reset_command_buffer(Env e,Term* f,IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND); if (!command) return io_fail(e,BV_INVALID,"invalid command buffer"); BvRow* owner=bv_command_device(command);BvDevice* device=owner->context; if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"command reset"); if (bv_command_fence(command)) return io_fail(e,BV_LIFETIME,"command has active submission"); VkResult result=bv_device_result(owner,device->ResetCommandBuffer((VkCommandBuffer)(uintptr_t)command->handle,0)); command->command.phase=result==VK_SUCCESS ? BV_INITIAL : BV_COMMAND_INVALID; memset(&command->command.submission,0,sizeof(command->command.submission)); if (result!=VK_SUCCESS) return bv_vk_error(e,result,"vkResetCommandBuffer"); bv_free_refs(command->deps);command->deps=NULL;memset(command->command.sets,0,sizeof(command->command.sets));command->command.lease=NULL;command->command.lease_serial=0;return bv_ok(e); } #endif #ifdef CID(Device.submit_and_wait) static Term bv_submit_and_wait(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);BvRow* command=bv_get(bv_key(e,f[1]),BV_COMMAND); if (!owner || bv_command_device(command)!=owner) return io_fail(e,BV_INVALID,"invalid command buffer or device"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"submit_and_wait"); if (bv_sealed(command,BV_KIND_COUNT)) return io_fail(e,BV_LIFETIME,"submit references retired resources"); if (command->command.phase!=BV_EXECUTABLE || bv_uncertain(owner)) return io_fail(e,BV_LIFETIME,"submit needs executable command and certain device"); BvDevice* device=owner->context;Term result; if (!device->convenience) { VkResult status=VK_SUCCESS;uint32_t code=bv_new_fence(owner,0,BV_CONVENIENCE_PRIVATE,&device->convenience,&status); if (code) return io_fail(e,code,"private fence registry full"); if (status!=VK_SUCCESS) return bv_vk_error(e,status,"vkCreateFence / convenience"); } else { result=bv_reset_fence_core(e,device->convenience); if (term_aux(result)==CID(Fail)) return result; term_sink(e,result); } result=bv_submit_core(e,owner,command,device->convenience); if (term_aux(result)==CID(Fail)) return result; term_sink(e,result); result=bv_fence_observe(e,device->convenience,1,UINT64_MAX); if (term_aux(result)==CID(Fail)) return result; Term status[1];bv_unpack(e,result,1,status); return (uint32_t)status[0]==VK_SUCCESS ? bv_ok(e) : bv_vk_error(e,(VkResult)(uint32_t)status[0],"submit_and_wait / incomplete infinite wait"); } #endif #ifdef CID(debug_live_objects) static Term bv_live_objects(Env e, Term* f, IoWork* w) { uint32_t count=0;for (BvRow* row=bv_rows;row;row=row->next) count++; return io_done(e,count); } #endif #ifdef CID(debug_u64_roundtrip) static Term bv_u64_roundtrip(Env e, Term* f, IoWork* w) { return io_done(e,bv_words(e,bv_u64(e,f[0]))); } #endif static VkResult bv_drain_presentation(BvRow* owner) { BvDevice* device=owner->context; if (bv_lost(owner)) return VK_ERROR_DEVICE_LOST; for (BvRow* row=bv_rows;row;row=row->next) { if (row->kind!=BV_SWAPCHAIN || row->parent!=owner) continue; BvSwapchain* target=row->context; for (uint32_t j=0;jlease_count;j++) { BvLease* lease=&target->leases[j]; if (lease->phase!=BV_LEASE_ACQUIRING && lease->phase!=BV_LEASE_PRESENTING && lease->phase!=BV_LEASE_ACQUIRE_UNCERTAIN && lease->phase!=BV_LEASE_PRESENT_UNCERTAIN) continue; if (!lease->fence || lease->fence->fence.lease!=lease || lease->fence->fence.serial!=lease->serial) return VK_NOT_READY; VkFence handle=(VkFence)(uintptr_t)lease->fence->handle; VkResult result=bv_device_result(owner,device->WaitForFences(device->handle,1,&handle,VK_TRUE,UINT64_C(1000000000))); if (result!=VK_SUCCESS) return result; bv_finish_wsi_fence(lease->fence); } } return VK_SUCCESS; } static void bv_swapchain_remove(BvRow* row) { BvDevice* device=row->parent->context;BvSwapchain* target=row->context; for(uint32_t j=0;jcount;j++)if(target->images[j])bv_remove(target->images[j]); for(BvRow* semaphore=bv_rows;semaphore;semaphore=semaphore->next)if(semaphore->kind==BV_SEMAPHORE && semaphore->semaphore.producer==row)semaphore->semaphore.producer=NULL; device->DestroySwapchainKHR(device->handle,(VkSwapchainKHR)(uintptr_t)row->handle,NULL); free(target->images);free(target->leases);free(target);bv_remove(row); } #ifdef CID(Device.create_swapchain) static Term bv_create_swapchain(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);Term p[10];bv_unpack(e,f[1],10,p); if(!owner)return io_fail(e,BV_INVALID,"swapchain device");BvDevice* device=owner->context; BvRow* surface=bv_child((uint32_t)p[0],BV_SURFACE,owner->parent); if(!surface || !device->presentation)return io_fail(e,BV_INVALID,"swapchain surface or device profile"); if(bv_lost(owner))return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"create swapchain"); for(BvRow* row=bv_rows;row;row=row->next)if(row->kind==BV_SWAPCHAIN && bv_dependency(row,BV_DEP_SURFACE)->target==surface)return io_fail(e,BV_LIFETIME,"surface already has a swapchain"); BvInstance* instance=owner->parent->context;VkSurfaceKHR native=(VkSurfaceKHR)(uintptr_t)surface->handle;VkSurfaceCapabilitiesKHR caps; VkResult result=instance->surface_caps(device->physical,native,&caps); if(result!=VK_SUCCESS)return bv_vk_error(e,result,"swapchain capabilities"); VkBool32 present_supported=VK_FALSE; result=instance->surface_support(device->physical,device->present_family,native,&present_supported); if(result!=VK_SUCCESS)return bv_vk_error(e,result,"swapchain present support"); if(!present_supported)return io_fail(e,BV_ARGUMENT,"device present queue does not support this surface"); uint32_t count=p[1],width=p[4],height=p[5],usage=p[6],transform=p[7],alpha=p[8],mode=p[9]; const BvFormat* format=bv_format((VkFormat)(uint32_t)p[2]); if(!format || format->aspect!=VK_IMAGE_ASPECT_COLOR_BIT || !width || !height || countcaps.maxImageCount) || widthcaps.maxImageExtent.width || heightcaps.maxImageExtent.height || (caps.currentExtent.width!=UINT32_MAX && (width!=caps.currentExtent.width || height!=caps.currentExtent.height)) || !usage || (usage&~caps.supportedUsageFlags) || !transform || (transform&(transform-1)) || !(transform&caps.supportedTransforms) || !alpha || (alpha&(alpha-1)) || !(alpha&caps.supportedCompositeAlpha))return io_fail(e,BV_ARGUMENT,"unsupported swapchain description"); VkSurfaceFormatKHR* formats=NULL;VkPresentModeKHR* modes=NULL;uint32_t nf=0,nm=0;bool has_format=false,has_mode=false; result=bv_query_formats(instance,device->physical,native,&nf,&formats); if(result==VK_SUCCESS)result=bv_query_modes(instance,device->physical,native,&nm,&modes); if(result==VK_SUCCESS) { for(uint32_t j=0;jfamily,device->present_family};bool split=families[0]!=families[1]; VkSwapchainCreateInfoKHR create={.sType=VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,.surface=native,.minImageCount=count,.imageFormat=p[2],.imageColorSpace=p[3],.imageExtent={width,height},.imageArrayLayers=1,.imageUsage=usage, .imageSharingMode=split ? VK_SHARING_MODE_CONCURRENT : VK_SHARING_MODE_EXCLUSIVE,.queueFamilyIndexCount=split ? 2 : 0,.pQueueFamilyIndices=split ? families : NULL,.preTransform=transform,.compositeAlpha=alpha,.presentMode=mode,.clipped=VK_TRUE,.oldSwapchain=VK_NULL_HANDLE}; VkSwapchainKHR handle;result=bv_device_result(owner,device->CreateSwapchainKHR(device->handle,&create,NULL,&handle)); if(result!=VK_SUCCESS) {free(dep);free(target);bv_remove(row);return bv_vk_error(e,result,"vkCreateSwapchainKHR");} *dep=(BvDep){.target=surface,.role=BV_DEP_SURFACE};row->deps=dep;row->context=target;row->handle=(uintptr_t)handle;target->format=p[2];target->extent=(VkExtent2D){width,height};target->usage=usage; VkImage* images=NULL;uint32_t n=0;result=VK_INCOMPLETE; for(unsigned retry=0;retry<8 && result==VK_INCOMPLETE;retry++) { free(images);images=NULL;result=device->GetSwapchainImagesKHR(device->handle,handle,&n,NULL); if(result!=VK_SUCCESS && result!=VK_INCOMPLETE)break; if(!n || n>4096) {result=VK_ERROR_OUT_OF_HOST_MEMORY;break;} images=calloc(n,sizeof(*images));if(!images) {result=VK_ERROR_OUT_OF_HOST_MEMORY;break;} result=device->GetSwapchainImagesKHR(device->handle,handle,&n,images); } if(result==VK_SUCCESS) { target->lease_count=2*n;target->images=calloc(n,sizeof(*target->images));target->leases=calloc(target->lease_count,sizeof(*target->leases));if(!target->images || !target->leases)result=VK_ERROR_OUT_OF_HOST_MEMORY; else { target->count=n; for(uint32_t j=0;jdeps=borrowed;image->handle=(uintptr_t)images[j]; image->object.image=(BvImage){target->format,target->extent,1,1,usage,BV_BORROWED_IMAGE,row,j};target->images[j]=image; } } } free(images); if(result!=VK_SUCCESS) {bv_swapchain_remove(row);return bv_vk_error(e,result,"swapchain image metadata");} return io_done(e,term_pak(CID(Swapchain),row->id)); } #endif #ifdef CID(Device.swapchain_images) static Term bv_swapchain_images(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*row=bv_child(bv_key(e,f[1]),BV_SWAPCHAIN,owner); if(!owner || !row)return io_fail(e,BV_INVALID,"swapchain images ownership"); BvSwapchain* target=row->context;Term list=term_pak(CID(Nil),0); for(uint32_t j=target->count;j;j--)list=io_node(e,CID(Con),term_pak(CID(ImageHandle),target->images[j-1]->id),list); return io_done(e,list); } #endif #ifdef CID(Device.destroy_swapchain) static Term bv_destroy_swapchain(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*row=bv_child(bv_key(e,f[1]),BV_SWAPCHAIN,owner); if(!owner || !row)return io_fail(e,BV_INVALID,"swapchain destroy ownership"); BvDevice* device=owner->context;BvSwapchain* target=row->context; for(uint32_t j=0;jlease_count;j++)if(target->leases[j].phase!=BV_LEASE_NONE && target->leases[j].phase!=BV_LEASE_ACQUIRED && target->leases[j].phase!=BV_LEASE_RENDERED && target->leases[j].phase!=BV_LEASE_ABANDONED && !bv_lost(owner))return io_fail(e,BV_LIFETIME,"swapchain has incomplete acquisition, rendering or presentation"); for(uint32_t j=0;jcount;j++)if(bv_referenced(target->images[j]))return io_fail(e,BV_LIFETIME,"swapchain image still referenced"); for(BvRow* command=bv_rows;command;command=command->next)if(command->kind==BV_COMMAND && bv_command_device(command)==owner && bv_may_reach_depth(command,row,BV_KIND_COUNT))return io_fail(e,BV_LIFETIME,"swapchain acquisition still recorded"); bv_swapchain_remove(row);return bv_ok(e); } #endif #ifdef CID(Device.acquire) static Term bv_acquire(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*row=bv_child(bv_key(e,f[1]),BV_SWAPCHAIN,owner),*fence=bv_public_fence(bv_key(e,f[2]));uint64_t timeout=bv_u64(e,f[3]); if(!owner || !row || !fence || fence->parent!=owner)return io_fail(e,BV_INVALID,"acquire ownership"); BvDevice* device=owner->context;if(bv_lost(owner))return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"acquire"); if (bv_uncertain(owner) || bv_active(owner,fence) || fence->fence.use!=BV_FENCE_FREE) return io_fail(e,BV_LIFETIME,"acquire requires free fence and certain device"); BvSwapchain* target=row->context;BvLease* lease=NULL; for (uint32_t j=0;jlease_count;j++) if (target->leases[j].phase==BV_LEASE_NONE) {lease=&target->leases[j];break;} if (!lease) return io_fail(e,BV_LIFETIME,"all acquisition owners are occupied"); VkResult result=device->GetFenceStatus(device->handle,(VkFence)(uintptr_t)fence->handle); if(result!=VK_NOT_READY)return result==VK_SUCCESS ? io_fail(e,BV_LIFETIME,"acquire fence must be unsignaled") : bv_device_error(e,owner,result,"acquire fence status"); if(device->lease_serial==UINT64_MAX)return io_fail(e,BV_LIMIT,"acquisition sequence exhausted"); uint64_t serial=++device->lease_serial; uint32_t index=0;result=bv_device_result(owner,device->AcquireNextImageKHR(device->handle,(VkSwapchainKHR)(uintptr_t)row->handle,timeout,VK_NULL_HANDLE,(VkFence)(uintptr_t)fence->handle,&index)); if(result==VK_SUCCESS || result==VK_SUBOPTIMAL_KHR) { *lease=(BvLease){BV_LEASE_ACQUIRING,row,fence,NULL,index,serial};fence->fence.use=BV_FENCE_ACQUIRE;fence->fence.lease=lease;fence->fence.serial=serial; bool valid=indexcount; for (uint32_t j=0;jlease_count;j++) if (&target->leases[j]!=lease && target->leases[j].phase!=BV_LEASE_NONE && target->leases[j].phase!=BV_LEASE_PRESENTING && target->leases[j].index==index) valid=false; if (!valid) {lease->phase=BV_LEASE_ACQUIRE_UNCERTAIN;return io_fail(e,BV_INVALID,"acquire returned invalid or already-owned image index");} Term fields[]={row->id,(uint32_t)serial,(uint32_t)(serial>>32),index,result==VK_SUBOPTIMAL_KHR ? 1 : 0}; return io_done(e,bv_node(e,CID(Acquired),5,fields)); } if(result==VK_ERROR_OUT_OF_DATE_KHR)return io_done(e,term_pak(CID(AcquireOutOfDate),0)); if(result==VK_ERROR_SURFACE_LOST_KHR)return io_done(e,term_pak(CID(AcquireSurfaceLost),0)); if(result==VK_TIMEOUT)return io_done(e,term_pak(CID(AcquireTimeout),0)); if(result==VK_NOT_READY)return io_done(e,term_pak(CID(AcquireNotReady),0)); if(result!=VK_ERROR_OUT_OF_HOST_MEMORY && result!=VK_ERROR_OUT_OF_DEVICE_MEMORY && result!=VK_ERROR_DEVICE_LOST){*lease=(BvLease){BV_LEASE_ACQUIRE_UNCERTAIN,row,fence,NULL,UINT32_MAX,serial};fence->fence.use=BV_FENCE_ACQUIRE;fence->fence.lease=lease;fence->fence.serial=serial;} return bv_vk_error(e,result,"vkAcquireNextImageKHR"); } #endif static BvLease* bv_acquisition(Env e,Term value,BvRow* owner) { Term fields[3];bv_unpack(e,value,3,fields); BvRow* row=bv_child((uint32_t)fields[0],BV_SWAPCHAIN,owner); if (!row) return NULL; uint64_t serial=((uint64_t)(uint32_t)fields[2]<<32)|(uint32_t)fields[1]; BvSwapchain* target=row->context; for (uint32_t j=0;jlease_count;j++) if (serial && target->leases[j].serial==serial && target->leases[j].phase!=BV_LEASE_NONE) return &target->leases[j]; return NULL; } #ifdef CID(CommandBuffer.use_acquisition) static Term bv_use_acquisition(Env e,Term* f,IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND),*owner=bv_command_device(command);BvLease* lease=bv_acquisition(e,f[1],owner); if (!command || !lease) return io_fail(e,BV_INVALID,"command acquisition ownership or stale generation"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"command acquisition"); if (!bv_outside(command) || lease->phase!=BV_LEASE_ACQUIRED || (command->command.lease && (command->command.lease!=lease || command->command.lease_serial!=lease->serial))) return io_fail(e,BV_LIFETIME,"command acquisition must be completed and unique to this recording"); uint32_t code=bv_prepare_refs(command,1,&lease->swapchain);if (code) return io_fail(e,code,"command acquisition references"); command->command.lease=lease;command->command.lease_serial=lease->serial;return bv_ok(e); } #endif #ifdef CID(Device.release_acquired) static Term bv_release_acquired(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);BvLease* lease=bv_acquisition(e,f[1],owner); if(!owner || !lease)return io_fail(e,BV_INVALID,"release acquisition ownership or stale generation"); BvDevice* device=owner->context; if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"release acquisition"); if(lease->phase!=BV_LEASE_ACQUIRED && lease->phase!=BV_LEASE_RENDERED)return io_fail(e,BV_LIFETIME,"release requires completed acquisition and rendering"); VkReleaseSwapchainImagesInfoEXT release={.sType=VK_STRUCTURE_TYPE_RELEASE_SWAPCHAIN_IMAGES_INFO_EXT,.swapchain=(VkSwapchainKHR)(uintptr_t)lease->swapchain->handle,.imageIndexCount=1,.pImageIndices=&lease->index}; VkResult result=bv_device_result(owner,device->ReleaseSwapchainImagesEXT(device->handle,&release)); if(result==VK_SUCCESS)*lease=(BvLease){0}; return result==VK_SUCCESS ? bv_ok(e) : bv_vk_error(e,result,"vkReleaseSwapchainImagesEXT"); } #endif #ifdef CID(Device.create_semaphore) static Term bv_create_semaphore(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);if(!owner)return io_fail(e,BV_INVALID,"semaphore device"); if(bv_lost(owner))return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"semaphore create"); BvRow* row=bv_add(BV_SEMAPHORE,owner);if(!row)return io_fail(e,BV_LIMIT,"semaphore metadata"); BvDevice* device=owner->context;VkSemaphoreCreateInfo create={.sType=VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};VkSemaphore handle; VkResult result=bv_device_result(owner,device->CreateSemaphore(device->handle,&create,NULL,&handle)); if(result!=VK_SUCCESS) {bv_remove(row);return bv_vk_error(e,result,"vkCreateSemaphore");} row->handle=(uintptr_t)handle;return io_done(e,term_pak(CID(Semaphore),row->id)); } #endif #ifdef CID(Device.destroy_semaphore) static Term bv_destroy_semaphore(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*row=bv_child(bv_key(e,f[1]),BV_SEMAPHORE,owner); if(!owner || !row)return io_fail(e,BV_INVALID,"semaphore ownership"); if((row->semaphore.phase!=BV_SEM_UNUSED && row->semaphore.phase!=BV_SEM_SIGNALED && row->semaphore.phase!=BV_SEM_QUARANTINED) || bv_referenced(row))return io_fail(e,BV_LIFETIME,"semaphore still in use"); BvDevice* device=owner->context;device->DestroySemaphore(device->handle,(VkSemaphore)(uintptr_t)row->handle,NULL);bv_remove(row);return bv_ok(e); } #endif #ifdef CID(Device.present) static Term bv_present(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);BvLease* lease=bv_acquisition(e,f[1],owner); BvRow* semaphore=bv_child(bv_key(e,f[2]),BV_SEMAPHORE,owner),*fence=bv_public_fence(bv_key(e,f[3])); if(!owner || !lease || !semaphore || !fence || fence->parent!=owner)return io_fail(e,BV_INVALID,"present ownership or stale acquisition generation"); BvRow* row=lease->swapchain;BvDevice* device=owner->context; if(bv_lost(owner))return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"present"); if(bv_uncertain(owner) || lease->phase!=BV_LEASE_RENDERED || semaphore->semaphore.phase!=BV_SEM_SIGNALED || semaphore->semaphore.producer!=row || semaphore->semaphore.producer_serial!=lease->serial || fence->fence.use!=BV_FENCE_FREE || bv_active(owner,fence))return io_fail(e,BV_LIFETIME,"present requires matching rendered lease, signal and free fence"); VkFence signal=(VkFence)(uintptr_t)fence->handle;VkResult result=device->GetFenceStatus(device->handle,signal); if(result!=VK_NOT_READY)return result==VK_SUCCESS ? io_fail(e,BV_LIFETIME,"present fence must be unsignaled") : bv_device_error(e,owner,result,"present fence status"); VkSwapchainKHR handle=(VkSwapchainKHR)(uintptr_t)row->handle;VkSemaphore wait=(VkSemaphore)(uintptr_t)semaphore->handle; VkSwapchainPresentFenceInfoEXT completion={.sType=VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT,.swapchainCount=1,.pFences=&signal}; VkPresentInfoKHR present={.sType=VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,.pNext=&completion,.waitSemaphoreCount=1,.pWaitSemaphores=&wait,.swapchainCount=1,.pSwapchains=&handle,.pImageIndices=&lease->index}; result=bv_device_result(owner,device->QueuePresentKHR(device->present_queue,&present)); if(result==VK_ERROR_OUT_OF_HOST_MEMORY || result==VK_ERROR_OUT_OF_DEVICE_MEMORY)return bv_vk_error(e,result,"vkQueuePresentKHR (retry preserves lease)"); if(result==VK_ERROR_DEVICE_LOST)return bv_vk_error(e,result,"vkQueuePresentKHR"); lease->phase=BV_LEASE_PRESENTING;lease->fence=fence;lease->semaphore=semaphore;fence->fence.use=BV_FENCE_PRESENT;fence->fence.lease=lease;fence->fence.serial=lease->serial;semaphore->semaphore.phase=BV_SEM_PRESENT_WAIT; if(result==VK_SUCCESS)return io_done(e,term_pak(CID(Presented),0)); if(result==VK_SUBOPTIMAL_KHR)return io_done(e,term_pak(CID(PresentSuboptimal),0)); if(result==VK_ERROR_OUT_OF_DATE_KHR)return io_done(e,term_pak(CID(PresentOutOfDate),0)); if(result==VK_ERROR_SURFACE_LOST_KHR)return io_done(e,term_pak(CID(PresentSurfaceLost),0)); lease->phase=BV_LEASE_PRESENT_UNCERTAIN;semaphore->semaphore.phase=BV_SEM_UNCERTAIN; return bv_vk_error(e,result,"vkQueuePresentKHR (uncertain, resources retained)"); } #endif #ifdef CID(Device.timestamp_properties) static Term bv_timestamp_properties(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE); if (!owner) return io_fail(e,BV_INVALID,"timestamp properties device"); BvDevice* device=owner->context;uint32_t period;memcpy(&period,&device->limits.timestampPeriod,4); Term fields[]={device->queue_properties.timestampValidBits,period}; return io_done(e,bv_node(e,CID(TimestampProperties),2,fields)); } #endif #ifdef CID(Device.create_timestamp_pool) static Term bv_create_timestamp_pool(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);uint32_t count=f[1]; if (!owner) return io_fail(e,BV_INVALID,"timestamp pool device"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"create timestamp pool"); BvDevice* device=owner->context; if (!count || count>4096 || !device->queue_properties.timestampValidBits) return io_fail(e,BV_ARGUMENT,"timestamp count or queue support"); BvRow* pool=bv_add(BV_QUERY_POOL,owner);if (!pool) return io_fail(e,BV_LIMIT,"timestamp pool metadata"); pool->object.queries=(BvQueries){count,calloc(count,sizeof(BvQuerySlot))}; if (!pool->object.queries.slots) {bv_remove(pool);return io_fail(e,BV_LIMIT,"timestamp query metadata");} VkQueryPoolCreateInfo create={.sType=VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,.queryType=VK_QUERY_TYPE_TIMESTAMP,.queryCount=count}; VkQueryPool handle;VkResult result=bv_device_result(owner,device->CreateQueryPool(device->handle,&create,NULL,&handle)); if (result!=VK_SUCCESS) {bv_remove(pool);return bv_vk_error(e,result,"vkCreateQueryPool");} pool->handle=(uintptr_t)handle;return io_done(e,term_pak(CID(QueryPool),pool->id)); } #endif #ifdef CID(Device.destroy_query_pool) static Term bv_destroy_query_pool(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*pool=bv_child(bv_key(e,f[1]),BV_QUERY_POOL,owner); if (!owner || !pool) return io_fail(e,BV_INVALID,"timestamp pool ownership"); if (bv_referenced(pool)) return io_fail(e,BV_LIFETIME,"timestamp pool has recorded references"); BvDevice* device=owner->context;device->DestroyQueryPool(device->handle,(VkQueryPool)(uintptr_t)pool->handle,NULL);bv_remove(pool);return bv_ok(e); } #endif static int bv_query_range(BvRow* pool,uint32_t first,uint32_t count) { return count && firstobject.queries.count && count<=pool->object.queries.count-first; } #ifdef CID(CommandBuffer.reset_timestamp_queries) static Term bv_reset_timestamp_queries(Env e,Term* f,IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND),*owner=bv_command_device(command); BvRow* pool=bv_child(bv_key(e,f[1]),BV_QUERY_POOL,owner);uint32_t first=f[2],count=f[3]; if (!command || !pool) return io_fail(e,BV_INVALID,"reset timestamp ownership"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"reset timestamp queries"); if (!bv_outside(command) || !bv_query_range(pool,first,count)) return io_fail(e,BV_ARGUMENT,"reset timestamp range or render scope"); for (BvRow* row=bv_rows;row;row=row->next) if (row->kind==BV_COMMAND && row!=command && bv_may_reach_depth(row,pool,BV_KIND_COUNT)) return io_fail(e,BV_LIFETIME,"timestamp pool belongs to another recording"); uint32_t code=bv_prepare_refs(command,1,&pool);if (code) return io_fail(e,code,"reset timestamp references"); BvDevice* device=owner->context;device->CmdResetQueryPool((VkCommandBuffer)(uintptr_t)command->handle,(VkQueryPool)(uintptr_t)pool->handle,first,count); for (uint32_t j=first;jobject.queries.slots[j]=(BvQuerySlot){command->id,command->command.generation,false,false}; return bv_ok(e); } #endif #ifdef CID(CommandBuffer.write_timestamp) static Term bv_write_timestamp(Env e,Term* f,IoWork* w) { BvRow* command=bv_get(bv_key(e,f[0]),BV_COMMAND),*owner=bv_command_device(command); BvRow* pool=bv_child(bv_key(e,f[1]),BV_QUERY_POOL,owner);uint32_t query=f[2],stage=f[3]; if (!command || !pool) return io_fail(e,BV_INVALID,"write timestamp ownership"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"write timestamp"); BvDevice* device=owner->context; if (!bv_outside(command) || !bv_query_range(pool,query,1) || !stage || (stage&(stage-1)) || (stage&VK_PIPELINE_STAGE_HOST_BIT) || !bv_baseline_stages(device,stage) || !device->queue_properties.timestampValidBits) return io_fail(e,BV_ARGUMENT,"timestamp query, stage or render scope"); BvQuerySlot* slot=&pool->object.queries.slots[query]; if (slot->command!=command->id || slot->generation!=command->command.generation || slot->written) return io_fail(e,BV_LIFETIME,"timestamp must be reset by this recording before its single write"); uint32_t code=bv_prepare_refs(command,1,&pool);if (code) return io_fail(e,code,"timestamp references"); device->CmdWriteTimestamp((VkCommandBuffer)(uintptr_t)command->handle,(VkPipelineStageFlagBits)stage,(VkQueryPool)(uintptr_t)pool->handle,query);slot->written=true;return bv_ok(e); } #endif #ifdef CID(Device.timestamp_results) static Term bv_timestamp_results(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE),*pool=bv_child(bv_key(e,f[1]),BV_QUERY_POOL,owner);uint32_t first=f[2],count=f[3]; if (!owner || !pool) return io_fail(e,BV_INVALID,"timestamp results ownership"); if (bv_lost(owner)) return bv_vk_error(e,VK_ERROR_DEVICE_LOST,"timestamp results"); if (!bv_query_range(pool,first,count)) return io_fail(e,BV_ARGUMENT,"timestamp result range"); for (uint32_t j=first;jobject.queries.slots[j].command) return io_fail(e,BV_LIFETIME,"timestamp query was never reset"); BvDevice* device=owner->context;Term list=term_pak(CID(Nil),0); for (uint32_t j=first+count;j>first;j--) { BvQuerySlot* slot=&pool->object.queries.slots[j-1];uint64_t pair[2]={0,0}; if (slot->ready && slot->written) { VkResult result=bv_device_result(owner,device->GetQueryPoolResults(device->handle,(VkQueryPool)(uintptr_t)pool->handle,j-1,1,sizeof(pair),pair,sizeof(pair),VK_QUERY_RESULT_64_BIT|VK_QUERY_RESULT_WITH_AVAILABILITY_BIT)); if (result!=VK_SUCCESS && result!=VK_NOT_READY) {term_sink(e,list);return bv_vk_error(e,result,"vkGetQueryPoolResults");} } if (!pair[1]) pair[0]=0; Term fields[]={(uint32_t)pair[0],(uint32_t)(pair[0]>>32),pair[1] ? 1 : 0}; list=io_node(e,CID(Con),bv_node(e,CID(Timestamp),3,fields),list); } return io_done(e,list); } #endif #ifdef CID(Device.timestamp_duration) static Term bv_timestamp_duration(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_DEVICE);uint64_t start=bv_u64(e,f[1]),end=bv_u64(e,f[2]),bound=bv_u64(e,f[3]); if (!owner) return io_fail(e,BV_INVALID,"timestamp duration device"); BvDevice* device=owner->context;unsigned bits=device->queue_properties.timestampValidBits;double period=device->limits.timestampPeriod; if (!bits || bits>64 || !isfinite(period) || period<=0 || !bound || (double)bound>=ldexp(period,bits-1)) return io_fail(e,BV_ARGUMENT,"timestamp interval exceeds the unambiguous half-wrap limit"); uint64_t mask=bits==64 ? UINT64_MAX : (UINT64_C(1)<(double)bound) return io_fail(e,BV_ARGUMENT,"timestamp interval exceeds its CPU monotonic bound"); float result=(float)ns;uint32_t value;memcpy(&value,&result,4);return io_done(e,value); } #endif #ifdef CID(monotonic_ns) static Term bv_monotonic_ns(Env e,Term* f,IoWork* w) { struct timespec now;if (clock_gettime(CLOCK_MONOTONIC,&now)) return io_fail(e,BV_INVALID,"monotonic clock unavailable"); return io_done(e,bv_words(e,(uint64_t)now.tv_sec*UINT64_C(1000000000)+(uint64_t)now.tv_nsec)); } #endif static void __attribute__((constructor)) bv_register(void) { // BEGIN GENERATED REGISTRATIONS #ifdef CID(Entry.load) io_eff(CID(Entry.load), bv_entry_load); #endif #ifdef CID(Entry.close) io_eff(CID(Entry.close), bv_entry_close); #endif #ifdef CID(Entry.enumerate_instance_version) io_eff(CID(Entry.enumerate_instance_version), bv_entry_version); #endif #ifdef CID(Entry.create_instance) io_eff(CID(Entry.create_instance), bv_create_instance); #endif #ifdef CID(Instance.destroy) io_eff(CID(Instance.destroy), bv_destroy_instance_effect); #endif #ifdef CID(Instance.enumerate_physical_devices) io_eff(CID(Instance.enumerate_physical_devices), bv_enumerate_physical_devices); #endif #ifdef CID(Instance.get_physical_device_properties) io_eff(CID(Instance.get_physical_device_properties), bv_physical_properties); #endif #ifdef CID(Instance.get_physical_device_queue_family_properties) io_eff(CID(Instance.get_physical_device_queue_family_properties), bv_queue_properties); #endif #ifdef CID(Instance.memory_types_raw) io_eff(CID(Instance.memory_types_raw), bv_memory_types); #endif #ifdef CID(Instance.create_device) io_eff(CID(Instance.create_device), bv_create_device); #endif #ifdef CID(Device.destroy) io_eff(CID(Device.destroy), bv_destroy_device_effect); #endif #ifdef CID(Device.wait_idle) io_eff(CID(Device.wait_idle), bv_device_wait_idle); #endif #ifdef CID(Device.create_buffer) io_eff(CID(Device.create_buffer), bv_create_buffer); #endif #ifdef CID(Device.destroy_buffer) io_eff(CID(Device.destroy_buffer), bv_destroy_buffer); #endif #ifdef CID(Device.retire_buffers) io_eff(CID(Device.retire_buffers), bv_retire_buffers); #endif #ifdef CID(Device.collect_retired) io_eff(CID(Device.collect_retired), bv_collect_retired); #endif #ifdef CID(Device.buffer_requirements_raw) io_eff(CID(Device.buffer_requirements_raw), bv_buffer_requirements); #endif #ifdef CID(Device.allocate_memory) io_eff(CID(Device.allocate_memory), bv_allocate_memory); #endif #ifdef CID(Device.free_memory) io_eff(CID(Device.free_memory), bv_free_memory); #endif #ifdef CID(Device.bind_buffer_memory) io_eff(CID(Device.bind_buffer_memory), bv_bind_buffer_memory); #endif #ifdef CID(Device.write_memory) io_eff(CID(Device.write_memory), bv_write_memory); #endif #ifdef CID(Device.write_memory_words) io_eff(CID(Device.write_memory_words), bv_write_memory_words); #endif #ifdef CID(Device.read_memory) io_eff(CID(Device.read_memory), bv_read_memory); #endif #ifdef CID(Device.create_command_pool) io_eff(CID(Device.create_command_pool), bv_create_command_pool); #endif #ifdef CID(Device.destroy_command_pool) io_eff(CID(Device.destroy_command_pool), bv_destroy_command_pool); #endif #ifdef CID(Device.allocate_command_buffer) io_eff(CID(Device.allocate_command_buffer), bv_allocate_command_buffer); #endif #ifdef CID(CommandBuffer.begin) io_eff(CID(CommandBuffer.begin), bv_begin_command_buffer); #endif #ifdef CID(CommandBuffer.fill_buffer) io_eff(CID(CommandBuffer.fill_buffer), bv_cmd_fill_buffer); #endif #ifdef CID(CommandBuffer.copy_buffer) io_eff(CID(CommandBuffer.copy_buffer), bv_cmd_copy_buffer); #endif #ifdef CID(CommandBuffer.pipeline_barrier) io_eff(CID(CommandBuffer.pipeline_barrier), bv_cmd_pipeline_barrier); #endif #ifdef CID(CommandBuffer.end) io_eff(CID(CommandBuffer.end), bv_end_command_buffer); #endif #ifdef CID(Device.submit_and_wait) io_eff(CID(Device.submit_and_wait), bv_submit_and_wait); #endif #ifdef CID(debug_live_objects) io_eff(CID(debug_live_objects), bv_live_objects); #endif #ifdef CID(debug_u64_roundtrip) io_eff(CID(debug_u64_roundtrip), bv_u64_roundtrip); #endif #ifdef CID(Device.create_fence) io_eff(CID(Device.create_fence), bv_create_fence); #endif #ifdef CID(Device.destroy_fence) io_eff(CID(Device.destroy_fence), bv_destroy_fence); #endif #ifdef CID(Device.submit) io_eff(CID(Device.submit), bv_submit); #endif #ifdef CID(Fence.status) io_eff(CID(Fence.status), bv_fence_status); #endif #ifdef CID(Fence.wait) io_eff(CID(Fence.wait), bv_fence_wait); #endif #ifdef CID(Fence.reset) io_eff(CID(Fence.reset), bv_fence_reset); #endif #ifdef CID(CommandBuffer.reset) io_eff(CID(CommandBuffer.reset), bv_reset_command_buffer); #endif #ifdef CID(Entry.enumerate_instance_layers) io_eff(CID(Entry.enumerate_instance_layers), bv_instance_layers); #endif #ifdef CID(Entry.enumerate_instance_extensions) io_eff(CID(Entry.enumerate_instance_extensions), bv_instance_extensions); #endif #ifdef CID(Instance.enumerate_device_extensions) io_eff(CID(Instance.enumerate_device_extensions), bv_device_extensions); #endif #ifdef CID(Instance.memory_heaps_raw) io_eff(CID(Instance.memory_heaps_raw), bv_memory_heaps); #endif #ifdef CID(Instance.get_physical_device_format_properties) io_eff(CID(Instance.get_physical_device_format_properties), bv_format_properties); #endif #ifdef CID(Instance.limits_raw) io_eff(CID(Instance.limits_raw), bv_physical_limits); #endif #ifdef CID(Instance.image_format_properties_raw) io_eff(CID(Instance.image_format_properties_raw), bv_image_format_properties); #endif #ifdef CID(Device.create_image) io_eff(CID(Device.create_image), bv_create_image); #endif #ifdef CID(Device.destroy_image) io_eff(CID(Device.destroy_image), bv_destroy_image); #endif #ifdef CID(Device.image_requirements_raw) io_eff(CID(Device.image_requirements_raw), bv_image_requirements); #endif #ifdef CID(Device.bind_image_memory) io_eff(CID(Device.bind_image_memory), bv_bind_image_memory); #endif #ifdef CID(Device.create_image_view) io_eff(CID(Device.create_image_view), bv_create_image_view); #endif #ifdef CID(Device.destroy_image_view) io_eff(CID(Device.destroy_image_view), bv_destroy_image_view); #endif #ifdef CID(CommandBuffer.clear_color_image) io_eff(CID(CommandBuffer.clear_color_image), bv_cmd_clear_color_image); #endif #ifdef CID(CommandBuffer.clear_depth_image) io_eff(CID(CommandBuffer.clear_depth_image), bv_cmd_clear_depth_image); #endif #ifdef CID(CommandBuffer.copy_buffer_to_image) io_eff(CID(CommandBuffer.copy_buffer_to_image), bv_cmd_copy_buffer_to_image); #endif #ifdef CID(CommandBuffer.copy_image_to_buffer) io_eff(CID(CommandBuffer.copy_image_to_buffer), bv_cmd_copy_image_to_buffer); #endif #ifdef CID(Device.create_render_pass) io_eff(CID(Device.create_render_pass), bv_create_render_pass); #endif #ifdef CID(Device.destroy_render_pass) io_eff(CID(Device.destroy_render_pass), bv_destroy_render_pass); #endif #ifdef CID(Device.create_framebuffer) io_eff(CID(Device.create_framebuffer), bv_create_framebuffer); #endif #ifdef CID(Device.destroy_framebuffer) io_eff(CID(Device.destroy_framebuffer), bv_destroy_framebuffer); #endif #ifdef CID(CommandBuffer.begin_render_pass) io_eff(CID(CommandBuffer.begin_render_pass), bv_cmd_begin_render_pass); #endif #ifdef CID(CommandBuffer.end_render_pass) io_eff(CID(CommandBuffer.end_render_pass), bv_cmd_end_render_pass); #endif #ifdef CID(Device.create_shader_module) io_eff(CID(Device.create_shader_module), bv_create_shader_module); #endif #ifdef CID(Device.destroy_shader_module) io_eff(CID(Device.destroy_shader_module), bv_destroy_shader_module); #endif #ifdef CID(Device.create_pipeline_layout) io_eff(CID(Device.create_pipeline_layout), bv_create_pipeline_layout); #endif #ifdef CID(Device.destroy_pipeline_layout) io_eff(CID(Device.destroy_pipeline_layout), bv_destroy_pipeline_layout); #endif #ifdef CID(Device.create_graphics_pipeline) io_eff(CID(Device.create_graphics_pipeline), bv_create_graphics_pipeline); #endif #ifdef CID(Device.destroy_graphics_pipeline) io_eff(CID(Device.destroy_graphics_pipeline), bv_destroy_graphics_pipeline); #endif #ifdef CID(CommandBuffer.bind_graphics_pipeline) io_eff(CID(CommandBuffer.bind_graphics_pipeline), bv_cmd_bind_graphics_pipeline); #endif #ifdef CID(CommandBuffer.set_viewport) io_eff(CID(CommandBuffer.set_viewport), bv_cmd_set_viewport); #endif #ifdef CID(CommandBuffer.set_scissor) io_eff(CID(CommandBuffer.set_scissor), bv_cmd_set_scissor); #endif #ifdef CID(CommandBuffer.bind_vertex_buffer) io_eff(CID(CommandBuffer.bind_vertex_buffer), bv_cmd_bind_vertex_buffer); #endif #ifdef CID(CommandBuffer.bind_index_buffer) io_eff(CID(CommandBuffer.bind_index_buffer), bv_cmd_bind_index_buffer); #endif #ifdef CID(CommandBuffer.push_constants) io_eff(CID(CommandBuffer.push_constants), bv_cmd_push_constants); #endif #ifdef CID(CommandBuffer.draw_indexed) io_eff(CID(CommandBuffer.draw_indexed), bv_cmd_draw_indexed); #endif #ifdef CID(Instance.destroy_surface) io_eff(CID(Instance.destroy_surface), bv_destroy_surface); #endif #ifdef CID(Instance.surface_capabilities) io_eff(CID(Instance.surface_capabilities), bv_surface_capabilities); #endif #ifdef CID(Instance.surface_formats) io_eff(CID(Instance.surface_formats), bv_surface_formats); #endif #ifdef CID(Instance.present_modes) io_eff(CID(Instance.present_modes), bv_present_modes); #endif #ifdef CID(Instance.present_support) io_eff(CID(Instance.present_support), bv_present_support); #endif #ifdef CID(Instance.presentation_supported) io_eff(CID(Instance.presentation_supported), bv_presentation_supported_run); #endif #ifdef CID(Instance.create_presentation_device) io_eff(CID(Instance.create_presentation_device), bv_create_presentation_device); #endif #ifdef CID(Device.create_swapchain) io_eff(CID(Device.create_swapchain), bv_create_swapchain); #endif #ifdef CID(Device.swapchain_images) io_eff(CID(Device.swapchain_images), bv_swapchain_images); #endif #ifdef CID(Device.destroy_swapchain) io_eff(CID(Device.destroy_swapchain), bv_destroy_swapchain); #endif #ifdef CID(Device.acquire) io_eff(CID(Device.acquire), bv_acquire); #endif #ifdef CID(Device.release_acquired) io_eff(CID(Device.release_acquired), bv_release_acquired); #endif #ifdef CID(Device.create_semaphore) io_eff(CID(Device.create_semaphore), bv_create_semaphore); #endif #ifdef CID(Device.destroy_semaphore) io_eff(CID(Device.destroy_semaphore), bv_destroy_semaphore); #endif #ifdef CID(Device.submit_synced) io_eff(CID(Device.submit_synced), bv_submit_synced); #endif #ifdef CID(Device.present) io_eff(CID(Device.present), bv_present); #endif #ifdef CID(Device.descriptor_set_layout_raw) io_eff(CID(Device.descriptor_set_layout_raw), bv_create_descriptor_set_layout); #endif #ifdef CID(Device.destroy_descriptor_set_layout) io_eff(CID(Device.destroy_descriptor_set_layout), bv_destroy_descriptor_set_layout); #endif #ifdef CID(Device.create_descriptor_pool) io_eff(CID(Device.create_descriptor_pool), bv_create_descriptor_pool); #endif #ifdef CID(Device.destroy_descriptor_pool) io_eff(CID(Device.destroy_descriptor_pool), bv_destroy_descriptor_pool); #endif #ifdef CID(Device.reset_descriptor_pool) io_eff(CID(Device.reset_descriptor_pool), bv_reset_descriptor_pool); #endif #ifdef CID(Device.allocate_descriptor_set) io_eff(CID(Device.allocate_descriptor_set), bv_allocate_descriptor_set); #endif #ifdef CID(Device.free_descriptor_set) io_eff(CID(Device.free_descriptor_set), bv_free_descriptor_set); #endif #ifdef CID(Device.update_descriptor_set) io_eff(CID(Device.update_descriptor_set), bv_update_descriptor_set); #endif #ifdef CID(Device.create_sampler) io_eff(CID(Device.create_sampler), bv_create_sampler); #endif #ifdef CID(Device.destroy_sampler) io_eff(CID(Device.destroy_sampler), bv_destroy_sampler); #endif #ifdef CID(CommandBuffer.bind_descriptor_sets) io_eff(CID(CommandBuffer.bind_descriptor_sets), bv_cmd_bind_descriptor_sets); #endif #ifdef CID(CommandBuffer.use_acquisition) io_eff(CID(CommandBuffer.use_acquisition), bv_use_acquisition); #endif #ifdef CID(Device.timestamp_properties) io_eff(CID(Device.timestamp_properties), bv_timestamp_properties); #endif #ifdef CID(Device.create_timestamp_pool) io_eff(CID(Device.create_timestamp_pool), bv_create_timestamp_pool); #endif #ifdef CID(Device.destroy_query_pool) io_eff(CID(Device.destroy_query_pool), bv_destroy_query_pool); #endif #ifdef CID(CommandBuffer.reset_timestamp_queries) io_eff(CID(CommandBuffer.reset_timestamp_queries), bv_reset_timestamp_queries); #endif #ifdef CID(CommandBuffer.write_timestamp) io_eff(CID(CommandBuffer.write_timestamp), bv_write_timestamp); #endif #ifdef CID(Device.timestamp_results) io_eff(CID(Device.timestamp_results), bv_timestamp_results); #endif #ifdef CID(Device.timestamp_duration) io_eff(CID(Device.timestamp_duration), bv_timestamp_duration); #endif #ifdef CID(monotonic_ns) io_eff(CID(monotonic_ns), bv_monotonic_ns); #endif // END GENERATED REGISTRATIONS } #endif // BV_NATIVE_IMPLEMENTATION // Linux X11 window effects share the checked registry with native.c. #include #include #include #include #include #define BV_XLIB_FUNCTIONS(X) \ X(XInitThreads) X(XLockDisplay) X(XUnlockDisplay) X(XOpenDisplay) X(XCloseDisplay) X(XCreateSimpleWindow) X(XDestroyWindow) \ X(XDefaultScreen) X(XRootWindow) X(XBlackPixel) X(XStoreName) X(XSelectInput) \ X(XInternAtom) X(XChangeProperty) X(XSetWMProtocols) X(XMapWindow) X(XFlush) X(XPending) X(XNextEvent) \ X(XLookupKeysym) X(XNextRequest) X(XQueryPointer) X(XGrabPointer) X(XUngrabPointer) X(XWarpPointer) X(XConnectionNumber) \ X(XCreateBitmapFromData) X(XCreatePixmapCursor) X(XFreePixmap) X(XFreeCursor) X(XUndefineCursor) typedef enum { BV_POINTER_READY, BV_POINTER_WARPING } BvPointerPhase; typedef struct { int x,y; unsigned long floor,serial; BvPointerPhase phase; } BvPointer; typedef struct { BvWindowContext base; void* library; Display* display; Window window; Atom close; Cursor cursor; uint32_t width,height; bool mapped,focused,captured; BvPointer pointer; #define BV_XFIELD(name) __typeof__(&name) name; BV_XLIB_FUNCTIONS(BV_XFIELD) #undef BV_XFIELD } BvWindow; static void bv_pointer_warp_locked(BvWindow* window) { int x=window->width/2,y=window->height/2; if(window->pointer.phase==BV_POINTER_READY && (window->pointer.x!=x || window->pointer.y!=y)) { window->pointer.serial=window->XNextRequest(window->display);window->pointer.phase=BV_POINTER_WARPING; window->XWarpPointer(window->display,None,window->window,0,0,0,0,x,y); } } static void bv_pointer_warp(BvWindow* window) { window->XLockDisplay(window->display);bv_pointer_warp_locked(window);window->XUnlockDisplay(window->display); } static int bv_pointer_reset(BvWindow* window) { Window root,child;int rx,ry,x,y;unsigned state; window->XLockDisplay(window->display); int valid=window->XQueryPointer(window->display,window->window,&root,&child,&rx,&ry,&x,&y,&state); if(valid) { window->pointer=(BvPointer){.x=x,.y=y,.floor=window->XNextRequest(window->display)-1,.phase=BV_POINTER_READY}; bv_pointer_warp_locked(window); } window->XUnlockDisplay(window->display);return valid; } static void bv_capture_off(BvWindow* window) { if (window->captured) { window->XUngrabPointer(window->display,CurrentTime); if(window->window)window->XUndefineCursor(window->display,window->window); window->captured=false;window->pointer.phase=BV_POINTER_READY;window->XFlush(window->display); } } static void bv_window_destroy_impl(BvRow* row) { BvWindow* window=row->context;bv_capture_off(window); window->XFreeCursor(window->display,window->cursor); if(window->window)window->XDestroyWindow(window->display,window->window); window->XCloseDisplay(window->display);dlclose(window->library);free(window);bv_remove(row); } #ifdef CID(Entry.open_window) static Term bv_open_window(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_ENTRY);uint64_t length=0;char* title=io_cstr(e,f[1],&length); uint32_t width=f[2],height=f[3]; if (!owner || io_nul(title,length) || !width || !height || width>16384 || height>16384) {free(title);return io_fail(e,BV_ARGUMENT,"window owner, title or extent");} BvWindow* window=calloc(1,sizeof(*window));BvRow* row=window ? bv_add(BV_WINDOW,owner) : NULL; if (!row) {free(title);free(window);return io_fail(e,BV_LIMIT,"window metadata");} window->base.destroy=bv_window_destroy_impl; window->library=dlopen("libX11.so.6",RTLD_NOW|RTLD_LOCAL);int complete=window->library!=NULL; #define BV_XLOAD(name) window->name=window->library ? (__typeof__(window->name))dlsym(window->library,#name) : NULL;complete &= window->name!=NULL; BV_XLIB_FUNCTIONS(BV_XLOAD) #undef BV_XLOAD if (!complete || !window->XInitThreads() || !(window->display=window->XOpenDisplay(NULL))) { if(window->library) dlclose(window->library);free(title);free(window);bv_remove(row);return io_fail(e,BV_ARGUMENT,"X11 display or dispatch unavailable"); } int screen=window->XDefaultScreen(window->display); window->window=window->XCreateSimpleWindow(window->display,window->XRootWindow(window->display,screen),0,0,width,height,0,0,window->XBlackPixel(window->display,screen)); window->width=width;window->height=height; window->XStoreName(window->display,window->window,title);free(title); window->XSelectInput(window->display,window->window,StructureNotifyMask|FocusChangeMask|KeyPressMask|KeyReleaseMask|ButtonPressMask|ButtonReleaseMask|PointerMotionMask|ExposureMask); window->close=window->XInternAtom(window->display,"WM_DELETE_WINDOW",False); window->XSetWMProtocols(window->display,window->window,&window->close,1); unsigned long pid=(unsigned long)getpid(); window->XChangeProperty(window->display,window->window,window->XInternAtom(window->display,"_NET_WM_PID",False),XA_CARDINAL,32,PropModeReplace,(unsigned char*)&pid,1); char blank[1]={0};Pixmap pixmap=window->XCreateBitmapFromData(window->display,window->window,blank,1,1);XColor black={0}; window->cursor=window->XCreatePixmapCursor(window->display,pixmap,pixmap,&black,&black,0,0);window->XFreePixmap(window->display,pixmap); window->XMapWindow(window->display,window->window);window->XFlush(window->display); row->context=window;return io_done(e,term_pak(CID(NativeWindow),row->id)); } #endif #ifdef CID(NativeWindow.capture) static Term bv_window_capture(Env e,Term* f,IoWork* w) { BvRow* row=bv_get(bv_key(e,f[0]),BV_WINDOW);if(!row)return io_fail(e,BV_INVALID,"invalid window"); BvWindow* window=row->context; if(term_aux(f[1])!=CID(True)) {bv_capture_off(window);return io_done(e,term_pak(CID(False),0));} if(!window->focused || !window->mapped)return io_done(e,term_pak(CID(False),0)); if(!window->captured) { int result=window->XGrabPointer(window->display,window->window,False,ButtonPressMask|ButtonReleaseMask|PointerMotionMask,GrabModeAsync,GrabModeAsync,window->window,window->cursor,CurrentTime); if(result!=GrabSuccess)return io_done(e,term_pak(CID(False),0)); window->captured=true; if(!bv_pointer_reset(window)) {bv_capture_off(window);return io_done(e,term_pak(CID(False),0));} window->XFlush(window->display); } return io_done(e,term_pak(CID(True),0)); } #endif #ifdef CID(NativeWindow.close) static Term bv_window_close(Env e,Term* f,IoWork* w) { BvRow* row=bv_get(bv_key(e,f[0]),BV_WINDOW);if(!row)return io_fail(e,BV_INVALID,"invalid window"); if(bv_referenced(row))return io_fail(e,BV_LIFETIME,"window retained by surface"); bv_destroy_window(row);return bv_ok(e); } #endif #ifdef CID(NativeWindow.poll) static uint32_t bv_window_coordinate(int position,uint32_t limit) { return !limit || position<0 ? 0 : (uint32_t)position>=limit ? limit-1 : (uint32_t)position; } static Term bv_bool(bool value) {return value ? 1 : 0;} static uint32_t bv_release_controls(Env e,Term* events,uint32_t count) { for(const char* key="wsadqe";*key;key++)events[count++]=io_node(e,CID(Key),(uint32_t)*key,0); Term p[]={0,0,1,0};events[count++]=bv_node(e,CID(Mouse),4,p);return count; } static Term bv_window_poll(Env e,Term* f,IoWork* w) { BvRow* row=bv_get(bv_key(e,f[0]),BV_WINDOW);uint32_t timeout=f[1]; if(!row)return io_fail(e,BV_INVALID,"invalid window"); if(timeout>1000)return io_fail(e,BV_ARGUMENT,"window wait exceeds 1000 ms"); BvWindow* window=row->context; if(!window->XPending(window->display) && timeout) {struct pollfd fd={window->XConnectionNumber(window->display),POLLIN,0};poll(&fd,1,(int)timeout);} Term events[4096];uint32_t count=0; while(count<4080 && window->XPending(window->display)) { XEvent event;window->XNextEvent(window->display,&event);Term value=0; switch(event.type) { case ConfigureNotify: window->width=event.xconfigure.width;window->height=event.xconfigure.height; if(window->captured && !bv_pointer_reset(window)) {bv_capture_off(window);count=bv_release_controls(e,events,count);} break; case MapNotify:window->mapped=true;break; case UnmapNotify:window->mapped=false;bv_capture_off(window);count=bv_release_controls(e,events,count);break; case FocusIn:window->focused=true;break; case FocusOut: window->focused=false;bv_capture_off(window); count=bv_release_controls(e,events,count);break; case ClientMessage:if((Atom)event.xclient.data.l[0]==window->close)value=term_pak(CID(Close),0);break; case DestroyNotify:window->window=0;window->mapped=false;window->focused=false;window->captured=false;value=term_pak(CID(Close),0);break; case KeyPress:case KeyRelease: { KeySym key=window->XLookupKeysym(&event.xkey,0);uint32_t code=key==XK_Escape ? 27 : key<=255 ? (uint32_t)key : 0; if(code)value=io_node(e,CID(Key),code,bv_bool(event.type==KeyPress));break; } case ButtonPress:case ButtonRelease: { unsigned button=event.xbutton.button; if(button==Button1 || button==Button3 || button==Button2) { Term p[]={bv_window_coordinate(event.xbutton.x,window->width),bv_window_coordinate(event.xbutton.y,window->height),button==Button1 ? 0 : button==Button3 ? 1 : 2,bv_bool(event.type==ButtonPress)};value=bv_node(e,CID(Mouse),4,p); } else if(button>=4 && button<=7 && event.type==ButtonPress) { uint32_t direction=button%2 ? 0xbf800000u : 0x3f800000u; Term p[]={bv_window_coordinate(event.xbutton.x,window->width),bv_window_coordinate(event.xbutton.y,window->height),button>5 ? direction : 0,button>5 ? 0 : direction};value=bv_node(e,CID(Scroll),4,p); }break; } case MotionNotify: if(window->captured) { if(event.xmotion.serialpointer.floor)break; if(window->pointer.phase==BV_POINTER_WARPING && event.xmotion.serial>=window->pointer.serial) { window->pointer.x=window->width/2;window->pointer.y=window->height/2;window->pointer.phase=BV_POINTER_READY; } int x=event.xmotion.x,y=event.xmotion.y,dx=x-window->pointer.x,dy=y-window->pointer.y; window->pointer.x=x;window->pointer.y=y; if(dx || dy) {float fx=dx,fy=dy;uint32_t xb,yb;memcpy(&xb,&fx,4);memcpy(&yb,&fy,4);value=io_node(e,CID(Look),xb,yb);} } else value=io_node(e,CID(Move),bv_window_coordinate(event.xmotion.x,window->width),bv_window_coordinate(event.xmotion.y,window->height)); break; } if(value)events[count++]=value; } if(window->captured)bv_pointer_warp(window); window->XFlush(window->display);Term list=term_pak(CID(Nil),0); while(count)list=io_node(e,CID(Con),events[--count],list); Term p[]={window->width,window->height,bv_bool(window->mapped),bv_bool(window->focused),bv_bool(window->captured),list}; return io_done(e,bv_node(e,CID(WindowSnapshot),6,p)); } #endif #ifdef CID(Instance.create_surface) static Term bv_create_surface(Env e,Term* f,IoWork* w) { BvRow* owner=bv_get(bv_key(e,f[0]),BV_INSTANCE),*window=bv_get(bv_key(e,f[1]),BV_WINDOW); if(!owner || !window || window->parent!=owner->parent)return io_fail(e,BV_INVALID,"surface window ownership"); BvInstance* instance=owner->context; if(!instance->presentation || !instance->create_surface)return io_fail(e,BV_ARGUMENT,"X11 presentation instance profile required"); BvRow* row=bv_add(BV_SURFACE,owner);BvDep* dep=row ? malloc(sizeof(*dep)) : NULL; if(!dep) {if(row)bv_remove(row);return io_fail(e,BV_LIMIT,"surface metadata");} BvWindow* native=window->context;VkXlibSurfaceCreateInfoKHR create={.sType=VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR,.dpy=native->display,.window=native->window};VkSurfaceKHR handle; PFN_vkCreateXlibSurfaceKHR create_surface=(PFN_vkCreateXlibSurfaceKHR)instance->create_surface; VkResult result=create_surface(instance->handle,&create,NULL,&handle); if(result!=VK_SUCCESS) {free(dep);bv_remove(row);return bv_vk_error(e,result,"vkCreateXlibSurfaceKHR");} *dep=(BvDep){.role=BV_DEP_WINDOW,.target=window};row->deps=dep;row->handle=(uintptr_t)handle; return io_done(e,term_pak(CID(Surface),row->id)); } #endif static void __attribute__((constructor)) bv_window_register(void) { // BEGIN GENERATED WINDOW REGISTRATIONS #ifdef CID(Entry.open_window) io_eff(CID(Entry.open_window), bv_open_window); #endif #ifdef CID(NativeWindow.poll) io_eff(CID(NativeWindow.poll), bv_window_poll); #endif #ifdef CID(NativeWindow.capture) io_eff(CID(NativeWindow.capture), bv_window_capture); #endif #ifdef CID(NativeWindow.close) io_eff(CID(NativeWindow.close), bv_window_close); #endif #ifdef CID(Instance.create_surface) io_eff(CID(Instance.create_surface), bv_create_surface); #endif // END GENERATED WINDOW REGISTRATIONS }