Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

What happens when I float result = float(val1) * float3(color)?

Discussion in 'Shaders' started by Dreamback, Jun 15, 2019.

  1. Dreamback

    Dreamback

    Joined:
    Jul 29, 2016
    Posts:
    220
    I'm writing a diffuse lighting shader, and some examples I found have this strange line multiplying a float by a float3, and storing the results in a float. What the heck does that do? Is it multiplying by all 3 values and then averaging the result? Or does it only multiply by the red value?

    Code (CSharp):
    1.     float lightIntensity = dot(normal.xyz, -lightDirection);
    2.     float diffuse = lightIntensity * color.rgb;
    3.  
    The code seems to work, but heck if I can find anything explaining what the math is actually doing.
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,329
  3. Dreamback

    Dreamback

    Joined:
    Jul 29, 2016
    Posts:
    220
    Huh - so why would a generic diffuse light shader only base it on the red values? That seems kinda weird. The posts I'm reading about creating your own diffuse shader don't mention that.

    This is one of the examples, the very first one, Lambert/Diffuse Light:

    https://www.jordanstevenstechart.com/lighting-models
    Code (CSharp):
    1.  
    2. float3 SurfaceColor;         //objects color
    3. float3 LightColor;           //lights color * intensity
    4. float LightAttenuation;      //value of light at point (shadow/falloff)
    5.  
    6. float NdotL = max(0.0,dot(normalDirection,lightDirection));
    7. float LambertDiffuse = NdotL * SurfaceColor;
    8. float3 finalColor = LambertDiffuse * LightAttenuation * LightColor;
    At first I thought it a typo, or a simplification (he says his examples are pseudocode), until I found another article doing it the same way.
     
    Last edited: Jun 17, 2019
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,329
    Because it's a super common typo, and when all you're doing is testing with grey colored objects you won't notice anything wrong.