0
\$\begingroup\$

I want to make a simple ray marching loop in the fragment shader. I think the main issue is that I'm not giving the correct world position input.

Here is my current attempt:

Shader"SDF"{
Properties{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader{
Pass{
CGPROGRAM

#pragma vertex vert    
#pragma fragment frag

#include "UnityCG.cginc"
#include "HLSLSupport.cginc"

int steps = 64;
float3 centre = float3(0,0,0);
float radius = 1.0;
sampler2D _MainTex;

float sph(float3 posi){
    return distance(posi, centre) - radius;
};

struct v2f{
    float4 vertex : SV_POSITION;
    float3 wpos : TEXCOORD0;
};

struct appdata{
    float4 vertex : POSITION;
};

v2f vert(appdata v){
    v2f o;
    o.vertex = UnityObjectToClipPos(v.vertex);
    o.wpos = mul(unity_ObjectToWorld, v.vertex).xyz;
    return o;
}

fixed4 frag(v2f i) : SV_TARGET{
    float3 wpos = mul(unity_ObjectToWorld, i.wpos).xyz;
    float t = 0;
    float3 dir = normalize(wpos - _WorldSpaceCameraPos);
    fixed4 col;

    for (int j = 0; j < steps; j++){
        if (t > 100){
            col = fixed4(0, 0, 0, 1);
            break;
        }
        float3 p = wpos + dir * t;
        float d = sph(p);
        if (d < 0.001){
            col = fixed4(1, 0, 0, 1);
        }
        t += d;
    }
    return col;
}
    ENDCG
}
}
}

The output of this code is always black.

enter image description here

Also, wpos is supposed to be the world position of the pixels.

\$\endgroup\$
4
  • \$\begingroup\$ Can you copy and paste the code instead of a screenshot, please? Also, if you have any more details, that would be useful to help you. \$\endgroup\$
    – Evorlor
    May 26, 2023 at 17:33
  • 1
    \$\begingroup\$ Why are you multiplying by the object-to-world matrix twice, once in the vertex shader, and again in the fragment shader? \$\endgroup\$
    – DMGregory
    May 26, 2023 at 19:01
  • \$\begingroup\$ @DMGregory I thought it returns the world position of the pixels. \$\endgroup\$ May 27, 2023 at 1:01
  • \$\begingroup\$ That does not explain why you're doing it twice. \$\endgroup\$
    – DMGregory
    May 27, 2023 at 3:17

0

You must log in to answer this question.

Browse other questions tagged .