Vulkan中glm透视投影正常,切换正交投影后异常的技术咨询
Alright, let's break down why your orthographic projection isn't rendering your triangle, and walk through the fixes step by step. The core issue here ties into Vulkan's coordinate system differences from what glm assumes by default, plus easy-to-miss parameter settings for ortho projections.
Common Pitfalls & Fixes
1. You Need to Flip the Y-Axis (Just Like Perspective Projection)
Glm's glm::ortho function creates a projection matrix for a Y-up coordinate system, but Vulkan's Normalized Device Coordinates (NDC) use Y-down (where Y=1 is the bottom of the screen, Y=-1 is the top). You already handled this for your perspective projection with ubo.proj[1][1] *= -1;—you need to do the exact same thing for orthographic projection.
2. Orthographic Projection Parameters Are Likely Misconfigured
If your triangle isn't showing up, it's probably because your ortho matrix's left/right/bottom/top bounds don't include your triangle's vertices. Your triangle's vertices are in the range (-0.1, -0.1) to (0.1, 0.1)—if your ortho bounds are too narrow, or not scaled to your swap chain's aspect ratio, the triangle will be clipped out.
Correct Orthographic Projection Code Example
Here's how to set up your UBO correctly for orthographic projection, matching your existing view/model matrix setup:
ubo.model = glm::mat4(1.0f); ubo.view = glm::lookAt(glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); // Calculate aspect ratio of your swap chain float aspectRatio = swapChainExtent.width / (float)swapChainExtent.height; // Adjust this value to control how much of the scene you see (smaller = zoomed in) float orthoViewportSize = 1.0f; // Create orthographic matrix: glm::ortho(left, right, bottom, top, near, far) ubo.proj = glm::ortho( -orthoViewportSize * aspectRatio, // Left bound (scaled for aspect ratio) orthoViewportSize * aspectRatio, // Right bound -orthoViewportSize, // Bottom bound orthoViewportSize, // Top bound 0.1f, // Near plane (matches your perspective setup) 100.0f // Far plane ); // Critical: Flip Y-axis to match Vulkan's NDC ubo.proj[1][1] *= -1;
Additional Checks
- Verify UBO Updates: Make sure you're copying the updated UBO data to device memory after changing the projection matrix. It's easy to forget this step and end up using stale perspective projection data.
- Confirm Near/Far Plane Placement: Your camera is at
(0,0,1)looking at(0,0,0)—your near plane is set to0.1f, which puts the camera inside the view frustum (since1.0f > 0.1f), so the triangle atz=0will be visible. - Check Vertex Position Range: If you adjust
orthoViewportSize, make sure your triangle's vertices fall within theleft/right/bottom/topbounds you set. For example, if you setorthoViewportSizeto0.05f, your triangle's0.1fvertices would be outside the frustum and get clipped.
内容的提问来源于stack exchange,提问作者MikeNew

