画出虚线来了

This commit is contained in:
xsl
2025-09-22 21:08:13 +08:00
parent 610537fe9d
commit 0318224673
2 changed files with 31 additions and 50 deletions
+29 -48
View File
@@ -1,67 +1,48 @@
#version 450 #version 450
layout(location = 0) in vec3 fragColor; layout(location = 0) in vec3 fragColor;
layout(location = 1) in vec3 fragSegmentStart; layout(location = 1) in vec3 fragLineStart;
layout(location = 2) in vec3 fragSegmentEnd; layout(location = 2) in vec3 fragLineEnd;
//layout(location = 3) in vec3 fragWorldPos;
layout(location = 0) out vec4 outColor; layout(location = 0) out vec4 outColor;
layout(binding = 0) uniform UniformBufferObject {
mat4 proj;
mat4 model;
mat4 view;
} ubo;
layout(binding = 1) uniform DashParameters {
float dashSize;
float gapSize;
float dashOffset;
float uAASize;
int useWorldSpace;
} dashParams;
void main() { void main() {
// 转换为NDC坐标 vec2 fragPos = gl_FragCoord.xy;
vec3 ndcStart = fragSegmentStart / fragSegmentStart.z;
vec3 ndcEnd = fragSegmentEnd / fragSegmentEnd.z;
vec3 fragNDC = gl_FragCoord.xyz / gl_FragCoord.z;
fragNDC = (fragNDC * 2.0) - 1.0;
// 计算当前片元在线段上的投影 vec2 start = (fragLineStart.xy * 0.5 + 0.5) * 480.0;
vec2 lineDir = normalize(ndcEnd.xy - ndcStart.xy); vec2 end = (fragLineEnd.xy * 0.5 + 0.5) * 480.0;
vec2 startToFrag = fragNDC.xy - ndcStart.xy;
float projection = dot(startToFrag, lineDir);
// 计算线段在屏幕空间的长度(用于抗锯齿) vec2 lineDir = end - start;
float segmentLength = length(ndcEnd.xy - ndcStart.xy); float lineLength = length(lineDir);
// 应用虚线模式 if (lineLength < 1.0) {
float dashPeriod = dashParams.dashSize + dashParams.gapSize; outColor = vec4(fragColor, 1.0);
float currentPos = mod(projection + dashParams.dashOffset, dashPeriod); return;
}
// 抗锯齿处理 lineDir = normalize(lineDir);
float alpha = 1.0; vec2 toFrag = fragPos - start;
float projection = dot(toFrag, lineDir);
projection = clamp(projection, 0.0, lineLength);
// 线段开始处的抗锯齿(避免线段起始处出现半截虚线) vec2 closestPoint = start + lineDir * projection;
alpha *= smoothstep(0.0, dashParams.uAASize / segmentLength, projection); float distanceToLine = length(fragPos - closestPoint);
// 线段结束处的抗锯齿 float lineWidth = 6.0;
alpha *= 1.0 - smoothstep(segmentLength - dashParams.uAASize / segmentLength,
segmentLength, projection);
// 虚线模式抗锯齿 if (distanceToLine > lineWidth) {
alpha *= 1.0 - smoothstep(dashParams.dashSize, discard;
dashParams.dashSize + dashParams.uAASize / dashPeriod, }
currentPos);
// 如果alpha接近0,直接丢弃片元 float dashLength = 50.0;
float gapLength = 20.0;
// if (alpha < 0.01) { float patternLength = dashLength + gapLength;
// discard; float patternPos = mod(projection, patternLength);
// }
// outColor = vec4(fragColor, alpha); if (patternPos > dashLength) {
discard;
}
outColor = vec4(1, 0, 0, 1.0); outColor = vec4(fragColor, 1.0);
} }
Binary file not shown.