// This file is part of the 64k demo project. // It implements the Renderer3D class. #include "3d/renderer.h" #include "generated/assets.h" #include "gpu/effects/shader_composer.h" #include "util/asset_manager.h" #include #include #include #include #if !defined(STRIP_ALL) bool Renderer3D::s_debug_enabled_ = false; #endif void Renderer3D::init(WGPUDevice device, WGPUQueue queue, WGPUTextureFormat format) { device_ = device; queue_ = queue; format_ = format; WGPUSamplerDescriptor sampler_desc = {}; sampler_desc.addressModeU = WGPUAddressMode_Repeat; sampler_desc.addressModeV = WGPUAddressMode_Repeat; sampler_desc.magFilter = WGPUFilterMode_Linear; sampler_desc.minFilter = WGPUFilterMode_Linear; sampler_desc.maxAnisotropy = 1; default_sampler_ = wgpuDeviceCreateSampler(device_, &sampler_desc); create_default_resources(); create_pipeline(); create_skybox_pipeline(); #if !defined(STRIP_ALL) visual_debug_.init(device_, format_); #endif } void Renderer3D::create_skybox_pipeline() { WGPUBindGroupLayoutEntry entries[3] = {}; entries[0].binding = 0; entries[0].visibility = WGPUShaderStage_Fragment; entries[0].texture.sampleType = WGPUTextureSampleType_Float; entries[0].texture.viewDimension = WGPUTextureViewDimension_2D; entries[1].binding = 1; entries[1].visibility = WGPUShaderStage_Fragment; entries[1].sampler.type = WGPUSamplerBindingType_Filtering; entries[2].binding = 2; entries[2].visibility = WGPUShaderStage_Fragment; entries[2].buffer.type = WGPUBufferBindingType_Uniform; entries[2].buffer.minBindingSize = sizeof(GlobalUniforms); WGPUBindGroupLayoutDescriptor bgl_desc = {}; bgl_desc.entryCount = 3; bgl_desc.entries = entries; WGPUBindGroupLayout bgl = wgpuDeviceCreateBindGroupLayout(device_, &bgl_desc); WGPUPipelineLayoutDescriptor pl_desc = {}; pl_desc.bindGroupLayoutCount = 1; pl_desc.bindGroupLayouts = &bgl; WGPUPipelineLayout pipeline_layout = wgpuDeviceCreatePipelineLayout(device_, &pl_desc); const uint8_t* shader_code_asset = GetAsset(AssetId::ASSET_SHADER_SKYBOX, nullptr); std::string shader_source = ShaderComposer::Get().Compose( {"common_uniforms"}, (const char*)shader_code_asset); #if defined(DEMO_CROSS_COMPILE_WIN32) WGPUShaderModuleWGSLDescriptor wgsl_desc = {}; wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor; wgsl_desc.code = shader_source.c_str(); WGPUShaderModuleDescriptor shader_desc = {}; shader_desc.nextInChain = (const WGPUChainedStruct*)&wgsl_desc.chain; #else WGPUShaderSourceWGSL wgsl_desc = {}; wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL; wgsl_desc.code = {shader_source.c_str(), shader_source.length()}; WGPUShaderModuleDescriptor shader_desc = {}; shader_desc.nextInChain = (const WGPUChainedStruct*)&wgsl_desc.chain; #endif WGPUShaderModule shader_module = wgpuDeviceCreateShaderModule(device_, &shader_desc); WGPURenderPipelineDescriptor desc = {}; desc.layout = pipeline_layout; desc.vertex.module = shader_module; #if defined(DEMO_CROSS_COMPILE_WIN32) desc.vertex.entryPoint = "vs_main"; #else desc.vertex.entryPoint = {"vs_main", 7}; #endif WGPUColorTargetState color_target = {}; color_target.format = format_; color_target.writeMask = WGPUColorWriteMask_All; WGPUFragmentState fragment = {}; fragment.module = shader_module; #if defined(DEMO_CROSS_COMPILE_WIN32) fragment.entryPoint = "fs_main"; #else fragment.entryPoint = {"fs_main", 7}; #endif fragment.targetCount = 1; fragment.targets = &color_target; desc.fragment = &fragment; desc.primitive.topology = WGPUPrimitiveTopology_TriangleList; desc.primitive.cullMode = WGPUCullMode_Back; desc.primitive.frontFace = WGPUFrontFace_CCW; desc.multisample.count = 1; desc.multisample.mask = 0xFFFFFFFF; WGPUDepthStencilState depth_stencil = {}; depth_stencil.format = WGPUTextureFormat_Depth24Plus; depth_stencil.depthWriteEnabled = WGPUOptionalBool_False; depth_stencil.depthCompare = WGPUCompareFunction_Always; desc.depthStencil = &depth_stencil; skybox_pipeline_ = wgpuDeviceCreateRenderPipeline(device_, &desc); wgpuBindGroupLayoutRelease(bgl); wgpuPipelineLayoutRelease(pipeline_layout); wgpuShaderModuleRelease(shader_module); } void Renderer3D::shutdown() { #if !defined(STRIP_ALL) visual_debug_.shutdown(); #endif if (default_sampler_) wgpuSamplerRelease(default_sampler_); if (pipeline_) wgpuRenderPipelineRelease(pipeline_); if (bind_group_) wgpuBindGroupRelease(bind_group_); if (skybox_pipeline_) wgpuRenderPipelineRelease(skybox_pipeline_); if (skybox_bind_group_) wgpuBindGroupRelease(skybox_bind_group_); if (global_uniform_buffer_) wgpuBufferRelease(global_uniform_buffer_); if (object_storage_buffer_) wgpuBufferRelease(object_storage_buffer_); if (depth_view_) wgpuTextureViewRelease(depth_view_); if (depth_texture_) wgpuTextureRelease(depth_texture_); } void Renderer3D::resize(int width, int height) { if (width == width_ && height == height_) return; width_ = width; height_ = height; if (depth_view_) wgpuTextureViewRelease(depth_view_); if (depth_texture_) wgpuTextureRelease(depth_texture_); WGPUTextureDescriptor desc = {}; desc.usage = WGPUTextureUsage_RenderAttachment; desc.dimension = WGPUTextureDimension_2D; desc.size = {(uint32_t)width, (uint32_t)height, 1}; desc.format = WGPUTextureFormat_Depth24Plus; desc.mipLevelCount = 1; desc.sampleCount = 1; depth_texture_ = wgpuDeviceCreateTexture(device_, &desc); WGPUTextureViewDescriptor view_desc = {}; view_desc.format = WGPUTextureFormat_Depth24Plus; view_desc.dimension = WGPUTextureViewDimension_2D; view_desc.aspect = WGPUTextureAspect_DepthOnly; view_desc.arrayLayerCount = 1; view_desc.mipLevelCount = 1; depth_view_ = wgpuTextureCreateView(depth_texture_, &view_desc); } void Renderer3D::create_default_resources() { global_uniform_buffer_ = gpu_create_buffer(device_, sizeof(GlobalUniforms), WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst, nullptr) .buffer; object_storage_buffer_ = gpu_create_buffer(device_, sizeof(ObjectData) * kMaxObjects, WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst, nullptr) .buffer; } void Renderer3D::set_noise_texture(WGPUTextureView noise_view) { noise_texture_view_ = noise_view; } void Renderer3D::set_sky_texture(WGPUTextureView sky_view) { sky_texture_view_ = sky_view; } void Renderer3D::create_pipeline() { WGPUBindGroupLayoutEntry entries[5] = {}; entries[0].binding = 0; entries[0].visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment; entries[0].buffer.type = WGPUBufferBindingType_Uniform; entries[0].buffer.minBindingSize = sizeof(GlobalUniforms); entries[1].binding = 1; entries[1].visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment; entries[1].buffer.type = WGPUBufferBindingType_ReadOnlyStorage; entries[1].buffer.minBindingSize = sizeof(ObjectData) * kMaxObjects; entries[2].binding = 2; entries[2].visibility = WGPUShaderStage_Fragment; entries[2].texture.sampleType = WGPUTextureSampleType_Float; entries[2].texture.viewDimension = WGPUTextureViewDimension_2D; entries[3].binding = 3; entries[3].visibility = WGPUShaderStage_Fragment; entries[3].sampler.type = WGPUSamplerBindingType_Filtering; entries[4].binding = 4; entries[4].visibility = WGPUShaderStage_Fragment; entries[4].texture.sampleType = WGPUTextureSampleType_Float; entries[4].texture.viewDimension = WGPUTextureViewDimension_2D; WGPUBindGroupLayoutDescriptor bgl_desc = {}; bgl_desc.entryCount = 5; bgl_desc.entries = entries; WGPUBindGroupLayout bgl = wgpuDeviceCreateBindGroupLayout(device_, &bgl_desc); WGPUPipelineLayoutDescriptor pl_desc = {}; pl_desc.bindGroupLayoutCount = 1; pl_desc.bindGroupLayouts = &bgl; WGPUPipelineLayout pipeline_layout = wgpuDeviceCreatePipelineLayout(device_, &pl_desc); std::string main_code = (const char*)GetAsset(AssetId::ASSET_SHADER_RENDERER_3D); std::string shader_source = ShaderComposer::Get().Compose( {"common_uniforms", "sdf_primitives", "lighting", "ray_box"}, main_code); #if defined(DEMO_CROSS_COMPILE_WIN32) WGPUShaderModuleWGSLDescriptor wgsl_desc = {}; wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor; wgsl_desc.code = shader_source.c_str(); WGPUShaderModuleDescriptor shader_desc = {}; shader_desc.nextInChain = (const WGPUChainedStruct*)&wgsl_desc.chain; #else WGPUShaderSourceWGSL wgsl_desc = {}; wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL; wgsl_desc.code = {shader_source.c_str(), shader_source.length()}; WGPUShaderModuleDescriptor shader_desc = {}; shader_desc.nextInChain = (const WGPUChainedStruct*)&wgsl_desc.chain; #endif WGPUShaderModule shader_module = wgpuDeviceCreateShaderModule(device_, &shader_desc); WGPUDepthStencilState depth_stencil = {}; depth_stencil.format = WGPUTextureFormat_Depth24Plus; depth_stencil.depthWriteEnabled = WGPUOptionalBool_True; depth_stencil.depthCompare = WGPUCompareFunction_Less; WGPURenderPipelineDescriptor desc = {}; desc.layout = pipeline_layout; desc.vertex.module = shader_module; #if defined(DEMO_CROSS_COMPILE_WIN32) desc.vertex.entryPoint = "vs_main"; #else desc.vertex.entryPoint = {"vs_main", 7}; #endif WGPUColorTargetState color_target = {}; color_target.format = format_; color_target.writeMask = WGPUColorWriteMask_All; WGPUFragmentState fragment = {}; fragment.module = shader_module; #if defined(DEMO_CROSS_COMPILE_WIN32) fragment.entryPoint = "fs_main"; #else fragment.entryPoint = {"fs_main", 7}; #endif fragment.targetCount = 1; fragment.targets = &color_target; desc.fragment = &fragment; desc.primitive.topology = WGPUPrimitiveTopology_TriangleList; desc.primitive.cullMode = WGPUCullMode_Back; desc.primitive.frontFace = WGPUFrontFace_CCW; desc.depthStencil = &depth_stencil; desc.multisample.count = 1; desc.multisample.mask = 0xFFFFFFFF; pipeline_ = wgpuDeviceCreateRenderPipeline(device_, &desc); wgpuBindGroupLayoutRelease(bgl); wgpuPipelineLayoutRelease(pipeline_layout); wgpuShaderModuleRelease(shader_module); } void Renderer3D::update_uniforms(const Scene& scene, const Camera& camera, float time) { GlobalUniforms globals; globals.view_proj = camera.get_projection_matrix() * camera.get_view_matrix(); globals.inv_view_proj = globals.view_proj.inverse(); globals.camera_pos_time = vec4(camera.position.x, camera.position.y, camera.position.z, time); globals.params = vec4((float)std::min((size_t)kMaxObjects, scene.objects.size()), 0.0f, 0.0f, 0.0f); globals.resolution = vec2((float)width_, (float)height_); globals.padding = vec2(0.0f, 0.0f); wgpuQueueWriteBuffer(queue_, global_uniform_buffer_, 0, &globals, sizeof(GlobalUniforms)); std::vector obj_data; for (const auto& obj : scene.objects) { ObjectData data; data.model = obj.get_model_matrix(); // Calculate Inverse for point transformation data.inv_model = data.model.inverse(); data.color = obj.color; float type_id = 0.0f; if (obj.type == ObjectType::SPHERE) type_id = 1.0f; else if (obj.type == ObjectType::BOX) type_id = 2.0f; else if (obj.type == ObjectType::TORUS) type_id = 3.0f; else if (obj.type == ObjectType::PLANE) type_id = 4.0f; data.params = vec4(type_id, 0, 0, 0); obj_data.push_back(data); if (obj_data.size() >= kMaxObjects) break; } if (!obj_data.empty()) { wgpuQueueWriteBuffer(queue_, object_storage_buffer_, 0, obj_data.data(), obj_data.size() * sizeof(ObjectData)); } } void Renderer3D::draw(WGPURenderPassEncoder pass, const Scene& scene, const Camera& camera, float time) { update_uniforms(scene, camera, time); // Lazy Bind Group creation if (bind_group_) wgpuBindGroupRelease(bind_group_); WGPUBindGroupEntry bg_entries[5] = {}; bg_entries[0].binding = 0; bg_entries[0].buffer = global_uniform_buffer_; bg_entries[0].size = sizeof(GlobalUniforms); bg_entries[1].binding = 1; bg_entries[1].buffer = object_storage_buffer_; bg_entries[1].size = sizeof(ObjectData) * kMaxObjects; bg_entries[2].binding = 2; bg_entries[2].textureView = noise_texture_view_; bg_entries[3].binding = 3; bg_entries[3].sampler = default_sampler_; bg_entries[4].binding = 4; bg_entries[4].textureView = sky_texture_view_ ? sky_texture_view_ : noise_texture_view_; // Fallback WGPUBindGroupDescriptor bg_desc = {}; bg_desc.layout = wgpuRenderPipelineGetBindGroupLayout(pipeline_, 0); bg_desc.entryCount = 5; bg_desc.entries = bg_entries; bind_group_ = wgpuDeviceCreateBindGroup(device_, &bg_desc); wgpuBindGroupLayoutRelease(bg_desc.layout); wgpuRenderPassEncoderSetPipeline(pass, pipeline_); wgpuRenderPassEncoderSetBindGroup(pass, 0, bind_group_, 0, nullptr); uint32_t instance_count = (uint32_t)std::min((size_t)kMaxObjects, scene.objects.size()); if (instance_count > 0) { wgpuRenderPassEncoderDraw(pass, 36, instance_count, 0, 0); } #if !defined(STRIP_ALL) if (s_debug_enabled_) { for (const auto& obj : scene.objects) { vec3 extent(1.0f, 1.0f, 1.0f); if (obj.type == ObjectType::TORUS) { extent = vec3(1.5f, 0.5f, 1.5f); } visual_debug_.add_box(obj.get_model_matrix(), extent, vec3(1.0f, 1.0f, 0.0f)); // Yellow boxes } // Calculate ViewProj matrix for the debug renderer mat4 view_proj = camera.get_projection_matrix() * camera.get_view_matrix(); visual_debug_.render(pass, view_proj); } #endif } void Renderer3D::render(const Scene& scene, const Camera& camera, float time, WGPUTextureView target_view, WGPUTextureView depth_view_opt) { WGPUTextureView depth_view = depth_view_opt ? depth_view_opt : depth_view_; if (!depth_view) return; WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr); // --- Pass 1: Render Skybox (Clears color, clears and stores depth) --- bool skybox_rendered = false; if (sky_texture_view_ && skybox_pipeline_) { WGPURenderPassColorAttachment sky_color_attachment = {}; gpu_init_color_attachment(sky_color_attachment, target_view); sky_color_attachment.loadOp = WGPULoadOp_Clear; // Clear to black sky_color_attachment.storeOp = WGPUStoreOp_Store; sky_color_attachment.clearValue = {0.0f, 0.0f, 0.0f, 1.0f}; WGPURenderPassDepthStencilAttachment sky_depth_attachment = {}; sky_depth_attachment.view = depth_view; sky_depth_attachment.depthLoadOp = WGPULoadOp_Clear; // Clear depth sky_depth_attachment.depthStoreOp = WGPUStoreOp_Store; // Store cleared depth sky_depth_attachment.depthClearValue = 1.0f; // Farthest possible depth WGPURenderPassDescriptor sky_pass_desc = {}; sky_pass_desc.colorAttachmentCount = 1; sky_pass_desc.colorAttachments = &sky_color_attachment; sky_pass_desc.depthStencilAttachment = &sky_depth_attachment; WGPURenderPassEncoder sky_pass = wgpuCommandEncoderBeginRenderPass(encoder, &sky_pass_desc); wgpuRenderPassEncoderSetViewport(sky_pass, 0.0f, 0.0f, (float)width_, (float)height_, 0.0f, 1.0f); if (skybox_bind_group_) wgpuBindGroupRelease(skybox_bind_group_); WGPUBindGroupEntry bg_entries[3] = {}; bg_entries[0].binding = 0; bg_entries[0].textureView = sky_texture_view_; bg_entries[1].binding = 1; bg_entries[1].sampler = default_sampler_; bg_entries[2].binding = 2; bg_entries[2].buffer = global_uniform_buffer_; bg_entries[2].size = sizeof(GlobalUniforms); WGPUBindGroupDescriptor bg_desc = {}; bg_desc.layout = wgpuRenderPipelineGetBindGroupLayout(skybox_pipeline_, 0); bg_desc.entryCount = 3; bg_desc.entries = bg_entries; skybox_bind_group_ = wgpuDeviceCreateBindGroup(device_, &bg_desc); wgpuBindGroupLayoutRelease(bg_desc.layout); wgpuRenderPassEncoderSetPipeline(sky_pass, skybox_pipeline_); wgpuRenderPassEncoderSetBindGroup(sky_pass, 0, skybox_bind_group_, 0, nullptr); wgpuRenderPassEncoderDraw(sky_pass, 3, 1, 0, 0); // Draw a full-screen quad wgpuRenderPassEncoderEnd(sky_pass); wgpuRenderPassEncoderRelease(sky_pass); skybox_rendered = true; } // --- Pass 2: Render Scene Objects (Loads depth, writes depth) --- WGPURenderPassColorAttachment obj_color_attachment = {}; gpu_init_color_attachment(obj_color_attachment, target_view); obj_color_attachment.loadOp = skybox_rendered ? WGPULoadOp_Load : WGPULoadOp_Clear; // Load or Clear obj_color_attachment.storeOp = WGPUStoreOp_Store; obj_color_attachment.clearValue = {0.05f, 0.05f, 0.05f, 1.0f}; // Dark gray if no sky WGPURenderPassDepthStencilAttachment obj_depth_attachment = {}; obj_depth_attachment.view = depth_view; obj_depth_attachment.depthLoadOp = skybox_rendered ? WGPULoadOp_Load : WGPULoadOp_Clear; // Load or Clear obj_depth_attachment.depthStoreOp = WGPUStoreOp_Store; // Store object depth obj_depth_attachment.depthClearValue = 1.0f; WGPURenderPassDescriptor obj_pass_desc = {}; obj_pass_desc.colorAttachmentCount = 1; obj_pass_desc.colorAttachments = &obj_color_attachment; obj_pass_desc.depthStencilAttachment = &obj_depth_attachment; WGPURenderPassEncoder obj_pass = wgpuCommandEncoderBeginRenderPass(encoder, &obj_pass_desc); wgpuRenderPassEncoderSetViewport(obj_pass, 0.0f, 0.0f, (float)width_, (float)height_, 0.0f, 1.0f); draw(obj_pass, scene, camera, time); wgpuRenderPassEncoderEnd(obj_pass); wgpuRenderPassEncoderRelease(obj_pass); WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, nullptr); wgpuQueueSubmit(queue_, 1, &commands); wgpuCommandBufferRelease(commands); wgpuCommandEncoderRelease(encoder); }