Understanding the frac() function...

i recently came across a new function while trying to make a shader which uses a Toon ramp projected onto the object in ObjectSpace (thanks to Scroodge) which is the ‘frac()’ math function:

// Here's a line from my pixel shader
fixed4 diff = tex2D( _Ramp, frac( i.wPos ).xy );

As you can see, nothing special, just defining the texture’s uvs by using a world-based position (wPos), but wether I use frac() or not, I always get the same results visually, and I was wondering what is this function supposed to do? I looked it up on google and found some in-depth( way too in-depth) explanations which didn’t make much sense to me…I need a ‘dumbed-down’ explanation hahaha.

If anyone could enlighten me it would make my self-induced headache go away and i would be a happy man :slight_smile:

Stephane

First off, I’ve never programmed any Unity shaders.
But, by inferring from the context that it is used, I would say to strips the leading values from a floating point number.

For example: frac(1.23) would return ‘0.23’, frac(123.4) would return ‘0.4’.

I’m deducting this because it is being used for a texture coordinate, which may be expecting a value between 0.0 and 1.0 (or this shader requires this range).

[Edit] I never noticed the ‘.xy’ at the end, so now I have my doubts!

[Edit2] Is this the same function?:
http://msdn.microsoft.com/en-us/library/windows/desktop/bb509603%28v=vs.85%29.aspx

[Edit3] I saw his on a website, may lead to a better answer:

// makes the UV repeat between 0.0 and 2.0
float2 t = frac(IN.uv_MainTex*0.5)*2.0;

Plus, I found this for the definition of ‘frac’:

7 Likes

Yeah, it gives you the value after the decimal place.

So
frac(0.5) = 0.5
frac(1.25) = 0.25
frac(100.75) = 0.75
frac(9.1) = 0.1

And if you pass in a float2, 3 or 4 then it’ll do that for each component individually.

2 Likes

Thanks a lot, looks like you were spot on :slight_smile:

Got it, I wasn’t sure how it would work for a float2, but thanks to both of you guys’ explanation it all makes sense now!

how do I pass
frac(1.0)
frac(2.0)
Does it return 0.0???

Yeah.

THaQ