#archived-shaders

1 messages · Page 94 of 1

stoic flint
#

nope

warm pulsar
#

I'm pretty sure the compiler will flatten these branches anyway, since it would otherwise have problems getting the derivatives

#

You could throw on a [flatten] attribute, I guess

stoic flint
#

wheeree?

#

over the func. nope doesn't do anything.

stoic flint
dim yoke
#

Well, I don’t think the refraction is the hard part here. The thing with diamond is that the IOR is so high most of the light rays will do many total internal reflections which obviously doesn’t sound like easy thing to achieve in realtime applications. There must be some cheap trick to fake it well enough that I’m not aware of but actually getting the reflections and refractions accurate doesn’t sound fun at all

warm pulsar
#

Yeah, that's what I was thinking of there

#

the repeated internal reflections

#

I saw someone comment that they baked the face normals onto a sphere, then raymarched to bounce around inside of that sphere until they could escape

dim yoke
warm pulsar
#

I guess "ray marching" is the wrong term, yeah

#

you can directly compute the intersection

#

I last did raytracing in college in 2015 😛

#

and i haven't done raymarching for something like SSR before

dim yoke
#

In this case simple ray-sphere intersection should do

dim yoke
#

Now that I think about it, I don’t think that would be too expensive if the max reflection count is set reasonably low and the loop maybe even unrolled. If the accuracy isn’t of top priority, maybe all branching could be eliminated by always calculating x amount of reflections regardless of the reflection angles. It’s really hard to guess what effect any modification would have to the visual appearance without trying but there must be some way to get decent diamond visuals without sacrificing too much on performance

uneven inlet
#

where can i learn more about depth buffer shenanigans, and why does force enabling depth write fix what seems to be backface culling issue / is this the right way to do that?

fringe karma
#

So I have a forward renderer that hides the standard objects in the scene, and renders over them with a material that's technically transparent, but usually has opacity set to 1. But objects behind are still visible and the depth seems all wonky.
The depth is fine when I have the original (opaque) objects being rendered, or when I change the shader to be truly opaque and not transparent. Problem is, sometimes I do need the material to be transparent.
Is there a way I can force a depth pass without rendering the underlying objects, or should I use a truly opaque version of my shader for all the bits that I know will be opaque?

#

I tried setting the forward renderer's depth texture mode to 'force prepass' but I guess it still only renders depth for stuff included in the layermasks

fringe karma
#

since I want to use the same material, is there a way to have a material be either truly opaque or transparent, without changing the shader? Or do I need to make two shaders that are functionally identical except that one supports transparency and the other doesn't?

grizzled bolt
#

@dim yoke @warm pulsar I feel like you could cheat a lot by reflecting the reflection probe but bending the vector an arbitrary number of times to mimic the internal reflections

#

Maybe blend in another cubemap for some extra "brilliance"

hardy juniper
stoic flint
#

why am i getting Assertion failed on expression: 'SUCCEEDED(hr)' when i try to dispatch a compute shader with "relatively" large computebuffer (of size 1024x1024x16 = 16mb) ???

astral turret
#

I'm very new to shaders. I'm trying to add the ability to "assign" a sprite texture (and UVs) to a base shader code I have. But I'm not even sure what the property I'm looking for (applying the texture sprite) is called

#

Does anyone know what's it called? With a name, I can Google...

regal stag
astral turret
signal tide
#

Um what am i missing i am trying to display a texture on Planet made from blender i got it show but when i try to blend between another texture using Triplanar I just get a white Sphere if i adjust the height one disappears i guess.

#

I dont think my start and end wTF.. forgot to connect the start and end to the second Smoothstep let me try that..

#

Nope damn i thought i had it..

dim yoke
# signal tide

Whatever that is, looks like could be simplified a lot by using subgraphs to reuse common groups of nodes

dusty birch
#

Hey guys, if I have this output, how can I turn it upside down?

kind juniper
#

Assuming the value is in the 0-1 range

steel notch
primal prawn
#

Hello, I was trying to create a shader for laser in unity, but i have one issue which is that the laser's texture speed changes based on laser's length, if laser is short speed is slow, and if laser is longer speed becomes fast. how can i counter it?

#

okay i noticed it's not the speed which is changing but the laser texture gets stretched. any fix for that?

misty osprey
#

sorry for the screenshot but I don't want to spam with messages here :s

royal bloom
#

can i make this take in a material instead?

#

and than the texture of the face

#

so the material will be a skin color

warm pulsar
#

a material uses a shader

royal bloom
#

wait yeah

#

nvm

#

lmao

warm pulsar
#

can you explain what you're trying to accomplish?

royal bloom
warm pulsar
#

So one option is to completely re-render the highlighted objects

misty osprey
warm pulsar
royal bloom
#

yeah

#

but still having full control over everything

#

like u know when i modify a material

warm pulsar
#

If you want it to be dead simple you could consider having a second submesh

royal bloom
#

change color, smoothness etc

warm pulsar
#

stick a plane where the face belongs and just render a second material there

royal bloom
warm pulsar
#

you'd give it a bit of margin

#

but yeah, not the best option

royal bloom
#

yeah

warm pulsar
#

Unfortunately you can't easily "compose" shaders (like you can in Blender with the Mix node)

royal bloom
#

i mean it would work

#

how did unturned and other games do this do u think

#

like battlebit remastered

royal bloom
#

i duplicated the face

#

and just pasted it there

#

how come there isnt any flickering?

#

last time i did it there was

warm pulsar
#

Z-fighting can be very fickle

stoic flint
#

someone knows how can i make this surface shader (BIRP) receive shadows?

Shader "Custom/SimpleFoliage" {
    Properties {
        _MainTex ("Texture", 2D) = "white" {}
        _Color ("Color", Color) = (1,1,1,1)
        _Cutoff ("Alpha Cutoff", Range(0,1)) = 0.5
    }
    SubShader {
        Tags { "Queue" = "Transparent" "RenderType" = "Transparent" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Lambert alpha:fade addshadow
        //#pragma surface surf Lambert alpha:fade addshadow alphatest:_Cutoff

        sampler2D _MainTex;
        fixed4 _Color;
        float _Cutoff;

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            fixed4 tex = tex2D(_MainTex, IN.uv_MainTex) * _Color;
            clip(tex.a - _Cutoff); // Clipping for transparency
            o.Albedo = tex.rgb;
            o.Alpha = tex.a; // For blending transparency
        }
        ENDCG
    }
    FallBack "Transparent/Cutout/VertexLit"
}
fringe karma
#

Or alternatively I could have a dead simple opaque material rendered first over everything that needs to be opaque, that serves no purpose except to give some geometry for a depth pass to be made with. Then I can render over everything with my one transparent material, but it'll have actual depth values to work with

tacit parcel
stoic flint
tacit parcel
fringe karma
#

Is there a way to iterate through all active renderers, that's more performant than using a for loop on FindObjectsOfType<Renderer>() every frame?

tacit parcel
fringe karma
#

I meant to ask in #archived-urp but didn't realise I was in the shader channel

gloomy tendon
#

Hi it seems shader graph does not support z offset which I need for parallel surface issues. But maybe a custom function can do the equivalent?

rare wren
#

You can offset the vertices, but definitely not ideal

gloomy tendon
#

Also with a shader graph can you not expose some of the Surface options you see on a normal material so you can have one material be double sided and one not with same graph?

gloomy tendon
#

This works if you subtract the view direction times a small amount in object space

devout quarry
#

And for URP to draw every mesh to a texture, using RenderGraph API that is using

RasterGraphContext.cmd.DrawRendererList(RendererListHandle);

And use

builder.SetRenderAttachment(customBuffer, 0); to configure it to render to a custom buffer

silent fable
#

Hi people. Im building a vrc world (so unity builtin) and baked lighting. And I cant manage to make most water shaders work properly. Material just fades out from a small distance. Ive notices that it depends on Cameras near and far clip plane. It works only only when near clip is kinda big so its not the way out.
Did someone had same problem ever?

#

In shader itself I tried searching for something like clip and found this:

            ase_screenPosNorm.z = ( UNITY_NEAR_CLIP_VALUE >= 0 ) ? ase_screenPosNorm.z : ase_screenPosNorm.z * 0.5 + 0.5;
            float eyeDepth167 = LinearEyeDepth(SAMPLE_DEPTH_TEXTURE( _CameraDepthTexture, ase_screenPosNorm.xy ));
            float temp_output_168_0 = ( eyeDepth167 - ase_screenPos.w );
rare wren
robust path
#

I have an unlit shader in shadergraph, (in unity 2022), but it doesn't really work properly as a mask, or when being masked (mask treats it as a full rect, and doesn't get masked at all). What options should I look into to fix this issue?

rare wren
#

But direction based Z offset for vertices is possible but rough for sure

rare wren
#

UI shaders are officially supported in Unity 6, so maybe upgrade if that's the case

robust path
robust path
rare wren
#

Yeah for UI you likely need canvas shaders from 6

robust path
#

🙃 I'd rather avoid that if I can, but oh well...

rare wren
#

Canvas is definitely different from non canvas 2D as far as I know

#

6 actually is quite nice to work with from my experience :P

gloomy tendon
rare wren
#

Yepyep!

near pasture
#

Is it possible to sample rendering layers as a mask in shader graph?

misty osprey
devout quarry
misty osprey
#

yep!

devout quarry
#

One limitation I can think of is that alpha cutout example you showed (of the plant), but maybe that's not needed in your case.

misty osprey
#

Yeah there won't be any meshes like that in my game hopefully

pastel grail
#

hey peoples, I have a compute shader where every thread needs to loop through a structuredbuffer of uint, and upon finding an uint set to 0, set it to 1 then store the current index in another buffer, all without threads setting the same uint or skipping any
the function I'm running right now looks like this, but the result is wrong, with a bunch of early IDs being skipped, and one of the IDs being a super high number with the next IDs then being all 1s, any idea what could be the problem?

#

(the id being returned with +1 is not a mistake, 0 is meant to represent a failed allocation)

#

nvm fixed it, turns out I had to initialize the buffer data & it didn't auto initialize to 0

atomic elm
#

Hi, I'm trying to add some fake bottom shadows to this shader in shadergraph. Here's what I have so far.

I want the shadow ramp to always start from the bottom of the mesh, but turn upward regardless of rotation. If I set the Position node to World Space, the object has to reach a certain height before the ramp fades out. How do I achieve this effect? Thanks.

regal stag
atomic elm
#

I have the Out of the Preview node going directly into the Base Color

regal stag
atomic elm
turbid pivot
#

how do i move something up and down 😭

#

i know this is basic stuff but im new to SGs

hallow sorrel
#

Hi I have a question someone knows where can I commision simple unity shaders?

warm pulsar
#

You can change the position of each vertex there.

#

You can take the current position from a Position node, add to it, and then run that into the Position output

turbid pivot
#

would this not work

warm pulsar
#

you may need to use a Transform node to convert your displacement into the right space, though!

#

You're throwing out the current Y position entirely

#

Wait I can't read

#

That would make an object move back and forth on the object-space Y axis, yeah

turbid pivot
#

it doesnt..

#

this happens

#

oh its because theyre angled im slow

warm pulsar
#

perhaps you're moving the objects too much on their Y axis

#

haha

turbid pivot
#

do you know how i move them along world y

#

and not local y

warm pulsar
#

Is this a terrain renderer, or are you using a bunch of little mesh renderers here?

turbid pivot
#

this is a standalone object

warm pulsar
#

but yeah, object space can be really funny

turbid pivot
warm pulsar
#

especially if your object naturally has a scale of 100

#

oh yeah, dupliverts from Blender

#

probably has a scale factor of 100, since that's what you get by default from an FBX export

#

A big thing with shaders is figuring out the correct coordinate space to work in

turbid pivot
#

its parent 1 the child 7 then the leaves are all different

warm pulsar
#

You want these objects to move up and down by a fixed amount, right?

turbid pivot
warm pulsar
#

So we have two important things here:

  • "up and down" -- from what point of view?
  • "a fixed amount" -- from what point of view?
#

if the point of view isn't from the object itself, then it sounds like you want world space

turbid pivot
#

yes

warm pulsar
#

that's where the Transform node comes in

#

here's how I'd do this

#

first, compute a vector that oscillates from [0,1,0] to [0,-1,0]

#

you can just plug Sin Time into a Combine node to do that

#

This is how much the vertex should move in world space

#

(You may want to scale it so that it's not a massive 2-meter range...)

#

Then, you need to transform this vector into object space

#

The resulting vector, when added to an object-space position, will cause it to move around properly

turbid pivot
#

alright thank you

#

my power just cut off but I'll try it when I can🙏

warm pulsar
#

woops

warm pulsar
ebon moss
#

am I doing this wrong, why is it all white?

hushed coyote
#

i made an unlit shader for a cel/toon shading effect, and im trying to add fog so my grass doesnt look terrible when it cuts off, but i cant manage to figure out how to do it. ill send a screenshot of the shader graph

karmic hatch
arctic oar
#

Guys, does anyone know a good UI blur shader that supports transparency? Either maskable or the one that follows the sprite's shape? (for example if the image is a circle, it only blurs in that circle)

median siren
#

I'm a little confused about shaders, as far as I know fragment shaders are called for every pixel rendered, but what about vertex shaders? At first I thought they're called for every vertex, but the vertex shader output is used in the fragment shader, doesn't that mean that the number of vertex shader calls should be the same as the fragment shader?

regal stag
flint yew
turbid pivot
vocal fiber
#

I have a question, does unity use GLSL, if not then what does it use for shader code?

vocal fiber
viscid root
# civic lantern HLSL

I'm kinda new to scripting shaders, I thought unity used HLSL, but I saw some stuff using CGINC and I have no idea what that is

civic lantern
#

From my understanding cginc files are just HLSL that gets glued into your shader code

#

So you can share functionality between shaders

viscid root
#

so like, imports?

civic lantern
#

Yep

viscid root
#

I see, thanks

civic lantern
#

I think the compiler quite literally copy pastes their contents into the shader but I could be wrong here

viscid root
#

kinda confused me because it looked like HLSL but wasn't named the same

karmic hatch
#

Also fog opacity can be a colour too (I think orange is realistic?)

eager shadow
#

Woo I'm boutta make a name for myself

#

Trying to do Manga style shading, I think the crosshatch shading is a little too detailed might have to tone it down

#

But also, does anyone have experience drawing lines where "sharps" are on an object? Like where there are 2 verts at the same place with a different normal?

#

Obv can't be done with frag shaders, probably a render feature? But I'm unsure where to begin

civic lantern
#

Is this for like, edge detection?

eager shadow
#

Uh nah, I hate texturing and I wanna make lines where things like folds/creases are on the character.

I'm also working on a custom normal thing that can switch between presets of normals/vertices at runtime so I can change where these fold lines appear

#

I just wanna draw lines along these sharps, if I can do that I can figure out making the lines tapered or whatever later

eager shadow
civic lantern
#

Just to give you some keywords to google etc.

eager shadow
#

Thanks G

#

Lemme go give it a shot

primal prawn
dim yoke
#

In C# script you could modify the points of the line renderer to make it appear as if it travels slowly without using shaders. You need to keep track of the progress of the lasers anyways in your script if you want the interactions with the lasers to only fire when the laser reaches the object in question (like the batteries only enable when the laser reaches it)

karmic hatch
#

also need to keep track of the length of the line (either in script or shader) so that it doesn't progress faster for a longer line

dim yoke
#

@primal prawn I would honestly rather do the line animation on C# side. Having one material per laser (or MaterialPropertyBlock) to pass them different properties doesn't sound very fun thing to manage. You have to keep track of timings and stuff on C# anyways so might as well do the animation too. I have no idea how cheap or expensive it is to update line renderers points every frame during the animation but it surely can't be that bad especially when the lines only consist of couple points

primal prawn
#

Thanks, I was actually thinking the same, but applying it was messing with other stuff in what I was planning to do but fortunately now it works well just getting a little bit of bugs sometimes

primal prawn
stoic flint
#

is it possible to view only shadow maps in unity ? something like this

dim yoke
stoic flint
#

debugging ofc

foggy leaf
#

Can someone explain how I can switch between different shader passes?

Pass
{
  Name "Sprite Lit Gradient Linear Alpha"
  //shader code...
}

Pass
{
  Name "Sprite Lit Gradient Linear Premultiply"
  //shader code...
}

Pass
{
  Name "Sprite Lit Gradient Linear Multiply"
}

Pass
{
  Name "Sprite Lit Gradient Linear Additive"
}

//later...
CustomEditor "BlendModeShaderGUI"

Then I have a custom editor, and I'm doing material.SetShaderPassEnabled, which correctly debugs if I use the following:

StringBuilder sb = new ();
for (int i = 0; i < material.passCount; i++)
{
    //Add pass name, and if it's enabled
    sb.Append(material.GetPassName(i));
    sb.Append(" ");
    sb.Append(material.GetShaderPassEnabled(material.GetPassName(i)));
    sb.Append("\n");
}
Debug.Log(sb.ToString());

But it doesn't seem to have any effect at all on the way the shader looks, even though it should look drastically different.

dim yoke
foggy leaf
#

The custom editor

#if UNITY_EDITOR
public sealed class BlendModeShaderGUI : ShaderGUI
{
    public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
    {
        Material material = materialEditor.target as Material;

        // Find the blend mode property
        MaterialProperty blendModeProp = FindProperty(propertyName: BlendModeExtensions.BLEND_MODE_PROPERTY_NAME, properties: properties);

        // Display the dropdown
        BlendMode blendMode      = (BlendMode)blendModeProp.floatValue;
        blendMode                = (BlendMode)EditorGUILayout.EnumPopup(label: "Blend Mode", selected: blendMode);
        blendModeProp.floatValue = (float)blendMode;

        // Apply the blend mode keyword
        SetBlendMode(material: material, blendMode: blendMode);

        // Draw the default properties
        base.OnGUI(materialEditor: materialEditor, properties: properties);
    }

    private void SetBlendMode(Material material, BlendMode blendMode)
    {
        // Disable all "Sprite Lit" passes
        foreach (BlendMode mode in Enum.GetValues(enumType: typeof(BlendMode)))
        {
            material.SetShaderPassEnabled(passName: mode.ShaderPass(), enabled: false);
        }

        // Enable the selected pass
        String passName = blendMode.ShaderPass();
        material.SetShaderPassEnabled(passName: passName, enabled: true);
    }
}
#endif
stoic flint
dim yoke
stoic flint
#

default

#

builtin

foggy leaf
#

Window/Analysis/Rendering Debugger

stoic flint
#

i don't have that lol

#

u2022.3

dim yoke
#

I mean this seems to be the only thing I'm getting out of the Rendering Debugger (the lightmap texture itself) which is not what you wanted anyways

stoic flint
#

yep

dim yoke
#

but what you can do quite easily on BiRP is to create a shader that only renders the shadows black and white and use Camera.SetReplacementShader to render everything with the same shader

stoic flint
#

i thought about it yea

#

big headache

dim yoke
#

how so?

stoic flint
#

idk, harder than having a lovely button to toggle off/on for quickly seeing stuff

dim yoke
#

sure, but not the hardest thing in the world either

#

you could make your own editor script and make it be a button too

stoic flint
#

yea

dim yoke
#

Would you like to have that on the scene view camera, in game camera or both?

stoic flint
#

scene

#

are you writing one ?

dim yoke
#

I can try if I can get it to work

stoic flint
#

cuz im doing it whatsoever rn

#

thank u

#

it will be very difficult to make it support many stuff tbh, given that transparency exists etc.

summer shoal
#

does anybody have an idea, why this could be happening, I am going feral

stoic flint
#

u didnt add a param to mul

#

or a syntax error. or both

summer shoal
stoic flint
summer shoal
rough lotus
#

my guess is there's a node in the graph that unity let you wire the wrong thing into (or even a lack of a wire that a node requires)

summer shoal
rough lotus
#

how strange!

#

I really cant see how, but maybe that hlsl file somehow got altered in some way

#

which doesnt make sense as it comes from the unity packages

summer shoal
#

it's the same exact loc, i cant wrap my head around that error

rough lotus
#

wish I could help, as unhelpful as that is to say 😅

summer shoal
#

haha, no worries, I am completely confused by that error too, and I couldnt find anything useful in forums

rough lotus
#

but hey, youre at the top of google!

summer shoal
rough lotus
#

try uninstalling the shadergraph package and reinstalling it

#

maybe some data got lost in the tubes when you installed it before

summer shoal
#

I'll try that, though I have even tried to migrate to a new project, and it's still happening

stoic flint
#

is it possible to modify shadow intensity (blacker shadows) in a surface shader ? aka read shadowmap and mult the albedo over the existing shadow

dim yoke
# stoic flint it will be very difficult to make it support many stuff tbh, given that transpar...

Something like this seems to work but I don't think I'm able to do the custom shader though. With the help of the example shader in the documentation https://docs.unity3d.com/Manual/built-in-shader-examples-receive-shadows.html I got the main light shadows working no problem but additional light shadows and transparent object shadows seem to be out of my ability. I can't find any good resources on them either so I think I have to give up on that.

[MenuItem("Tools/Draw Shadows Only #e")]
public static void ReplaceShader()
{
    Shader shadowsOnlyShader = Shader.Find("Your Shader Name");

    foreach (SceneView sView in SceneView.sceneViews)
    {
        sView.SetSceneViewShaderReplace(shadowsOnlyShader, "");
    }
}

[MenuItem("Tools/Disable Shadow Rendering #r")]
public static void ResetShader()
{
    foreach (SceneView sView in SceneView.sceneViews)
    {
        sView.SetSceneViewShaderReplace(null, null);
    }
}
``` ~~(modified to fix couple problems)~~
summer shoal
stoic flint
#

how would someone go about modifying ambient light contribution in a surface shader?

#

is it even possible ?

waxen grove
#

Can someone assist me in creating a UV solution that projects a flat image on the skybox? I want to use it for moving clouds

#

It would be something like this

gray adder
#

I want these inputs to show up in the "Surface Inputs"

#

They are plugged into a custom function block, in the string setting.

#

the custom function then plugs into base color.

#

Is that even possible?

#

or is it not, and a punishment for me using shader graphs instead of amplify

regal stag
gray adder
#

OH WAIT IM STUPIDDDDDDDD

#

yea thanks

low lichen
# stoic flint how would someone go about modifying ambient light contribution in a surface sha...

Ambient lighting is passed to the shader in the form of spherical harmonics and is combined with data from light probes if the scene has any. So, you can't change the contribution of ambient light separately from light probes.

At some point in your shader, a call to ShadeSH9 (for built-in) or SampleSH9 (for srp) is made, which will sample the spherical harmonic and return the combined ambient and light probe color for the given normal.

#

The ambient probe can be modified globally with RenderSettings.ambientProbe.

stoic flint
low lichen
stoic flint
#

currently no, but wish to keep it if possible i mean

low lichen
# stoic flint what i'm ultimately trying to do is get shadows to be darker on the said models ...

It's always best to try to remove the contribution from the source rather than artificially making it darker after the fact. Since ambient color is combined with light probes, your only option to the reduce the contribution of both. I assume you're never calling Shade/SampleSH9 yourself, it's probably done as part of a larger lighting function that you're using, either surface shader or Shader Graph. That means you either need to deconstruct the lighting function you're using so you can do each step manually and modify the result from SH9, or you can try to use some macro magic to redefine Shade/SampleSH9 to your own modified version before it gets called.

stoic flint
# low lichen It's always best to try to remove the contribution from the source rather than a...

i see i see. currently im using a modified blinnphong, but i can't see where or how could i modify the said shade step?

#pragma surface surf CustomMobileBlinnPhong addshadow
        inline fixed4 LightingCustomMobileBlinnPhong (SurfaceOutput s, fixed3 lightDir, fixed3 halfDir, fixed atten)
        {
            fixed diff = max (0, dot (s.Normal, lightDir));
            fixed nh = max (0, dot (s.Normal, halfDir));
            fixed spec = pow (nh, s.Specular*128) * s.Gloss;

            fixed4 c;
            c.rgb = (s.Albedo * _LightColor0.rgb * diff + s.Albedo * _LightColor0.rgb * spec) * atten * 2;
            UNITY_OPAQUE_ALPHA(c.a);
            return c;
        }
#

is there a pragma for it or sth

#

obviously the lighting model doesn't touch that

low lichen
#

Maybe the specular color is adding something that resembles ambient

stoic flint
#

so the lighting function isnt doing anything at all, the ambient light is added after or before

#

they are separate

low lichen
#

Then you'll need to call ShadeSH9 yourself and add it to the result

stoic flint
#

interesting. so if i disable ambient i call ShadeSH9 in my lighting model ? how do i do any of these ?

#

the flag noambient over the pragma surface worked.
but light for some reason doesn't seem to get multiplied. am i doing it wrong?

#pragma surface surf CustomMobileBlinnPhong noambient addshadow
inline fixed4 LightingCustomMobileBlinnPhong (SurfaceOutput s, fixed3 lightDir, fixed3 halfDir, fixed atten)
{
    fixed diff = max (0, dot (s.Normal, lightDir));
    fixed nh = max (0, dot (s.Normal, halfDir));
    fixed spec = pow (nh, s.Specular*128) * s.Gloss;
    
    // Add SH9 ambient lighting
    fixed3 shAmbient = ShadeSH9(float4(s.Normal, 1.0));

    fixed4 c;
    c.rgb = (s.Albedo * _LightColor0.rgb * diff + s.Albedo * _LightColor0.rgb * spec) * atten * 2;
    c.rgb *= shAmbient;
    UNITY_OPAQUE_ALPHA(c.a);

    return c;
}
low lichen
stoic flint
#

i should feed it the normal right ?

low lichen
stoic flint
#

i tried

low lichen
#

No sorry, the ambient needs to be added to the light color, and the combined result should then by multiplied by the albedo.

#

It's best to create a separate variable that represents the light for this pixel.

fixed3 diffuseLight = (_LightColor0.rgb * diff * atten) + shAmbient;
fixed3 specularLight = _LightColor0.rgb * spec * atten;

fixed4 c;
c.rgb = (s.Albedo * diffuseLight + specularLight) * 2;
#

Specular usually doesn't take on albedo, unless you're going for a metallic look.

stoic flint
#

it's a custom lighting for simulating trees, they behave a lot different than other objects

low lichen
#

Either way, the ambient should be added to the diffuse light after attenuation, before albedo

stoic flint
#

yep that was it

#

now i just apply some filter to darken the sh ambient is that correct ?

low lichen
#

Yes, or just ignore it entirely if you want it completely dark.

stoic flint
#

perfect

violet edge
#

Could someone please help me find out why this shader isnt outlining my model entirely?

gray adder
#

Note: To generate the clouds we use some nodes from the "SideFX Labs" toolset, these need to be installed (they are free). To do so go to Window/SideFX Labs, or follow the instructions here: https://www.sidefx.com/tutorials/sidefx-labs-installation/
Video explaining how to install labs tools and how to add padding around the density volume to f...

▶ Play video
#

This is what he gets with a cube of (1,1,1) scale, at 0,0,0

#

64 steps, each is 0.02, Sphere is (0,0,0,0.4), density scale of one

#

He used amplify shader for this, and used this:

#

Thats the custom block code.

#

I used a shader graph and improvised, got this:

#
float density = 0;
for(int i = 0; i < NumSteps; i++){
 
    RayOrigin += (RayDirection*StepSize); 
    //Get the density of the sphere. 
    float SphereDistance = distance(RayOrigin, Sphere.xyz);
     if (SphereDistance < Sphere.w) 
    { 
    density += 0.1*DensityScale;
    }else { } 
}   
Out = exp(-density);    ```
gray adder
regal stag
# gray adder

I think you'd instead want Position node as the RayOrigin, and View Direction node as the RayDirection
(or maybe View Vector to be equivalent to the tutorial but I feel like the direction being normalised makes more sense?)

gray adder
#

Aight thx, it's a bit hard following old tutorials with Unity6 and with NO money. I'll try this later when I can!

grand jolt
#

Hi, Im trying to write a shader that lets me define a shadow color, a midtone and a lit color for shading much like the unity toon shader. Ive managed to apply the different shades at a set offset but the colors on the texture seem to be getting washed out by the shading colors. Does anyone know how I could fix this? Here is my fragment shader code:

float4 frag (Interpolators i) : SV_Target {
                float4 col = tex2D(_MainTex, i.uv);
                if (_UseColor)
                {
                    col = _Color;
                }
                
                float NdotL = dot(normalize(i.normal), normalize(_WorldSpaceLightPos0.xyz));
                float4 finalColor;
                //toon is less than 0 if its in shadow
                if (NdotL >= _FirstShade) finalColor = lerp(float4(.1,.1,.1,1), _FirstShadeColor, step(0, SHADOW_ATTENUATION(ps)));
                else if (NdotL >= _SecondShade) finalColor = lerp(float4(.1,.1,.1,1), _SecondShadeColor, step(0, SHADOW_ATTENUATION(ps)));
                else finalColor = lerp(float4(.1,.1,.1,1), _ThirdShadeColor, step(0, SHADOW_ATTENUATION(ps)));
                finalColor *= col;
                return finalColor;
            }

Left on the image is the unity toon shader (desired outcome) and right is my own shader

smoky widget
#

Is there any way to fix DrawMeshInstanced so that if setting the camera parameter it doesn't flicker in edit mode?

shell wadi
chilly robin
#

How does texture sampling work in Shader Graph by default? I can't find much info on this at all. Are samplers ever reused for any reason? If I have 16 different textures in my graph, is that 16 samplers? If I have 8 textures, but use Sample Texture 2D node for texture each twice, I assume that's still 16 samplers, right?

jagged orbit
#

So I just installed URP and set everything up but my YSA Toon Shader (that should work with URP) doesnt work correctly. Is there something I forgot?

grizzled bolt
jagged orbit
regal stag
grizzled bolt
jagged orbit
#

It's works on a new and empty URP Template but not on my existing Project. I checked everything trice already and have no clue what I did wrong.

jagged orbit
#

I tried using the files from the URP Template on my own project and now all materials with this shader are full transparent instead of pink.

stray orbit
#

I am trying to learn a bit about how to make shaders for renderer features, i followed the example for Unity 6 in the documentation to create a blur renderer feature. I am now trying to make my first custom effect but i think i am not doing something right. I can't seem to correctly receive the color data in the shader. I have posted the current shader code below.

Shader "CustomEffects/ColorQuantization"
{
    HLSLINCLUDE

        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
        // The Blit.hlsl file provides the vertex shader (Vert),
        // the input structure (Attributes), and the output structure (Varyings)
        #include "Packages/com.unity.render-pipelines.core/Runtime/Utilities/Blit.hlsl"

        int _PaletteSize;

        float4 ColorQuantization(Varyings input) : SV_Target
        {
            // sample the current color from the texture
            float3 color = SAMPLE_TEXTURE2D(_BlitTexture, sampler_LinearClamp, input.texcoord).rgb;
            return float4(color.rgb, 1.0);
        }

    ENDHLSL

    SubShader
    {
        Tags { "RenderType"="Opaque" "RenderPipeline"="UniversalPipeline"}
        LOD 100
        ZWrite Off Cull Off
        Pass
        {
            Name "ColorQuantization"

            HLSLPROGRAM

                #pragma vertex Vert
                #pragma fragment ColorQuantization

            ENDHLSL
        }
    }
}
#

Maybe it's my renderpass where i am forgetting something?

#

As far as i understand it, the vertex part of the shader is done by the include and then we only have to handle the fragment shader to render whatever effect you want to create. so the first step i want to do is just sample the color and output it.

#

I have tested if the texcoord is ok and when i output (texcoord, 1.0, 1.0) it shows the colors of the texcoord

plain urchin
#

Hi, i'm using default URP Unlit with alpha clip, and it's doing this black thing. When moving camera, it looks like the transparent parts are rendered background set to "Dont clear" (2nd pic)
This is default shaders, anyone know what's happening?

hardy juniper
#

If thats in the scene view that is puzzling. If you disable showing the scene bg in the scene view, does it stop?

plain urchin
#

Changing to Lit fixes this, but what if i wanna use Unlit? And why is this happening anyways?

hardy juniper
#

if its due to the frame buffer not being cleared then lit/unlit shouldn't matter :/

stray orbit
gray adder
#

with his settings

#

with .6 radius

#

idk if im just STUPID

#

or if im not using the right tools

#

or both

grand jolt
fresh bloom
#

Not sure what chat this should go in but, when the camera is zoomed in a lot, 24x, low fov. the looking around becomes choppy, like im watching the dpi of my mouse or something. any way to get past this so it is just as smooth as say 90 fov. using a dual render scope shader

low lichen
fresh bloom
#

@low lichen cool thank you

minor remnant
#

anyone know a way to blend between reflection probes in shader graph?

#

reflection probe node only grabs the nearest one and i've made custom functions to add other missing features like box projection but cant figure out how to blend between multiple probes

minor remnant
#

nvm figured it out

strong furnace
#

hello guys, noobs here. may i ask questions here?

mental bone
#

If they are related to shaders then yes

strong furnace
#

is there any chance that i got a wrong instanceID order? i used
Graphics.DrawMeshInstanced(mesh, 0, material, matricis); to generate instances but i catched the buffer data in incorrect order

orchid hedge
#

hello i am currently trying to use the shader editor. What i want is having multiple color layers on a cylinder with a specific volume (height). So for example i want to have 5 Layers. The Bottom One is Color Red until the height idk. 10% of the cylinder. And then the second layer starts at the end of the first and takes up 30% from there on. Does anyone have an Idea how i could get this to work with the Node Editor?

grand jolt
#

Does anyone know about any resources I could look at for writing an unlit shader that receives shadows?

zenith marlin
#

wouldnt it be better to just use lit and disable recieving shadows

#

or even better tell what you are trying to do

zenith marlin
#

quick question : Does anyone have a idea why a empty lit shader has shadows on the top face when light is pointing on it from that side ?

low lichen
zenith marlin
#

its much brighter

#

sorry wrong

#

its just like the brighter sides

low lichen
#

Is this mesh a custom one or two scaled Unity default cubes?

zenith marlin
#

ohh ok so its just the wierd lighting in the scene

#

its probulider cubes

low lichen
#

A directional light might be ignored if there are more than one in the scene or there is baked lighting.

zenith marlin
#

no thats the only one

#

and nothing is baked

#

thats why i was a confused

#

but ok i guss time to learn lighting

low lichen
#

Does a default cube with the default material look similarly wrong?

zenith marlin
#

no

#

although the light rn is 130degrees on x axis

#

but still the top face should light up like the cube

#

or atleast comething close

low lichen
#

Is that a picture taken from above?

zenith marlin
#

yeah

low lichen
#

I can't see the problem there. The top face on both is darker than the side face. The shader graph color is grey instead of white, so it's overall darker.

zenith marlin
#

ok

#

thank you for help

thick marlin
#

Hey, I'm starting with Shader Graph, and I don't understand why my shader looks fine in Scene mode but behaves differently in Play mode. There is red stripes and i don't understand why. Thanks in advance

regal stag
thick marlin
regal stag
orchid hedge
#

hello i am currently trying to use the shader editor. What i want is having multiple color layers on a cylinder with a specific volume (height). So for example i want to have 5 Layers. The Bottom One is Color Red until the height idk. 10% of the cylinder. And then the second layer starts at the end of the first layer and takes up 30% from there on. Does anyone have an Idea how i could get this to work with the Node Editor?

thick marlin
regal stag
orchid hedge
#

yeah that would be good you can think about it like fluids stacked on top of each other like water and oil. The volumes and colors should be controllable by a script but i know how to do that just the shader is that what gives me problems.

#

but it should be possible with more than just two layers

grand jolt
regal stag
# orchid hedge yeah that would be good you can think about it like fluids stacked on top of eac...

Well I'd probably remap the Position.y into a 0-1 range first by using an Inverse Lerp node (probably using minmax of -1 and 1 assuming the cylinder is a height of 2 units)
Or use UV.y if model is uv unwrapped in a cylindrical projection

Then it's something like :

  • bunch of Step nodes with the different heights to produce each layer
  • each go into the T input on a Lerp node
  • lerps would be chained together using the A ports. In height order, or they'd overlap incorrectly.
  • lerp B ports would be layer colour properties
orchid hedge
#

so for example if i had 3 layers i had 3 steps from 0 to height1 then height1 to height2 and then height2 to height3? then all steps into the T input of a lerp? i dont understand what you mean with those lerps chained togheter using the A Ports?

regal stag
orchid hedge
#

ah ok and then the last lerp goes into the base color?

regal stag
#

Yea

orchid hedge
#

ok one last question this remapping. So i just use the Position split it and then take the y position. How can i now remap the y height?

regal stag
#

Using an Inverse Lerp or Remap node

orchid hedge
#

ok thanks for your help

#

appreciate it

regal stag
#

(And if you're writing shader code looking at the functions in the CustomLighting.hlsl could still be useful)

orchid hedge
#

in the steps in edge i would put the remapped y value and in the "in" value the volume of the layer?

regal stag
orchid hedge
#

np i will just try it out

#

also the first lerp A port should just be 0?

regal stag
#

I think it would be the first layer colour. If you want 3 layers you should actually only need 2 Steps/Lerps

orchid hedge
#

now im confused again xD so right now i have one remap of the position into 3 Edge Inputs with The In Ports of the Steps being the Volume. All those go into 3 seperate lerp T port with B poret being the color and A being the output of the lerp before exept the first one

regal stag
#

It might help if you set Default values on all properties (under Node Settings tab of Graph Inspector window, while a property is selected) as then it'll show different heights/colours in the previews.

orchid hedge
#

those are the settings of all my volumes

#

ah so the default value

#

ok it now looks like this

#

the material is just black

#

but the material weirdly has this texture

grand jolt
vagrant root
#

Hello there, Im new to shaders and im making a game about coloring a grayscale world with "color bombs" so this shader is essential, currently I just tried reducing the saturation of a given texture and changing the saturation once the bomb object collides with the environment but how can I make like smooth animations and a splatter, the solutions ive seen on the internet seem to alter the uv textures which isnt what I want.

manic niche
#

why cant I check this again after unchecking it?

rare wren
dim yoke
#

My first instinct would be to draw everything in color and in post processing shader reconstruct the positions and figure out whether this pixel should be greyscale based on the bomb positions. If there will be a ton of bombs, efficient data structure like quadtree/octree could be used to look up the bomb positions. To make them animate, you could store the animation phase in the same data structure you store the bomb positions (like 4d vectors, xyz for position, w for animation phase)

#

Also what type of splatter effect are we talking about? And should the effect area of the bomb extend upwards like a cylinder or should it be fully spherical?

#

Also one solution that came to mind would be to after everything is rendered, render the bomb splatters as a 3d meshes (cylinder or sphere) similarly to how decals (could potentially be even done in a decal shader) and some implementations of deferred rendering work. This would likely require having separate texture that stores the colored/greyscale texture, the other way around it would be easier (because you can do colored -> greyscale but not greyscale -> colored). This would be really performant especially if you have a lot of bombs in the scene most of which will cover only small area on the screen (or are outside the screen bounds)

severe harness
#

Is there a node in shader graph that give a vector2 of the screen resolution x and screen resolution y, or something like that?

warm pulsar
#

I use four stencil bits, so it breaks if more than 16 meshes overlap

#

(which I concluded was fine)

dim yoke
#

I suppose it would work but I think doing proper decals would give more artistical freedom to do things like anti aliasing on the edges

warm pulsar
#

yeah, stencils are going to be a very binary thing

#

My brain is somewhat poisoned by doing VRChat work

#

I can't imagine crazy ideas like using a script to render something to a RenderTexture

vagrant root
vagrant root
vagrant root
grand jolt
#

Does anyone know why my shader is only using the emission value when rendered? Ive copy pasted the code from the guide I was following but I cant seem to figure out why. Im in unity 6 and using the URP forward plus render pipeline

haughty tapir
#

Can someone please help me figure out this issue I am having or at least point me in the right direction. I'm at my witt's end, I've been working on this triplanar shader for the past 3 days and I can't figure out how to do additional lights properly. 1. I have two Directional lights, LightA and LightB, if both are enabled, the shader will only be lit up by LightA and not by LightB, if LightA is disabled, then the shader will switch and use LightB. I am a newbie with hlsl, so It's probably my fault and I missed something. EDIT: I am using URP.

amber saffron
grand jolt
#

Thats exactly why im confused as well. my texture wasnt rendering (the material was rendering as black) so I was trying things out and one of the things I tried to change was the emission value, and changing that value ended up changing the color

#

maybe I jumped to conclusions to blame emission for the issue though

amber saffron
#

@grand jolt and @haughty tapir , is there a reason for both of you to not use shadergraph to make your shaders ?

grand jolt
#

I tried using shadergraph but when I wrote a custom function that needed the Lighting.hlsl methods I kept getting errors on the import

#

I also want to learn how to do it in hlsl

kind juniper
#

@grand jolt @haughty tapir
!code

echo moatBOT
grand jolt
#

Heres my code on blazebin

amber saffron
haughty tapir
haughty tapir
grand jolt
haughty tapir
amber saffron
amber saffron
grand jolt
#

yes

#

should I put it to 1?

amber saffron
#

Yep, try it

grand jolt
#

tried it, didnt seem to fix it

#

But I managed to write a working version thats different from the tutorial I was following, but it seems to be getting shadow artifacts. What might be causing that and how could I fix it?
https://paste.mod.gg/xnhcqitweumw/0

amber saffron
#

This could be some shadow bias settings on the light itself.

grand jolt
#

The shadow bias seems to be the renderpipeline default

rough lotus
#

Why might it be that when I use noise to create the Normal texture, the result is really pronounced and obvious. But when I use the custom functions to create the cone, the result isnt as obvious

#

The functions are very simple, just a basic circle sdf then I use one minus on its interior

#

oh wait, I forgot to remap the interior to account for the radius. Otherwise the maximum value would end up as 0.3

royal pier
#

Is it possible to create something like this as a shader?

tired verge
#

Hi all!
Is it possible to modify Spirv shaders during the build process directly in unity?

sacred ore
#

why didn't work ?! in Unity

warm pulsar
#

the material is called "Procedural Sand Paper", but it's just using the default Lit shader. Is that intended?

orchid hedge
#

i have a problem making layers for my material with a shader i am new to shader making and i am trying to create layers on a cylinder with different volumes. but somehow i just cant get it to work does someone know what i did wrong? btw sry for the bad quality needed to get everything on one picture

foggy bison
#

anyone know how i can recreate the slimes from slime rancher? (also, not sure if this is right channel guh)

#

i assume i can use the URP decal thing for the splats on the wall. i have no idea how to make them look so fluid though

rare wren
rare wren
rare wren
rare wren
dim yoke
# royal pier Is it possible to create something like this as a shader?

Middleground beetween raymarching and flat texture would be some simple Parallax Occlusion Mapping (POM) type shader which could get you pretty decent results with the cost of couple texture samples. Completely differently implemented technique that could give very similar results to POM would be shell texturing which used to be one of the main ways to draw grass/fur in video games (it's basically just same mesh drawn bunch of times on top itself with small gaps between the layers). I think there might be some performance considerations which make POM far more common today but that could be something to consider as well. Depending on the visual fidelity you are looking for, even very few shells could get you quite nice results I assume. Both of these techniques pretty much requires you to have a texture for the pattern though. If you are looking to create the pattern in shader from scratch, I have little clues where to start

orchid hedge
#

i want color applied by just a tenth of my height of my object but it somehow still applies color to half of it and the rest is black what do i do wrong?

warm pulsar
orchid hedge
#

im so confused rn xD. nothing works that i do to make those layers for my cylinders xD

warm pulsar
#

I don't know what you're actually trying to accomplish

warm pulsar
orchid hedge
#

ah i figured it out myself it was such a hassle but the problem was that my position was on object and not on world and that destroyed my layers and that was always my problem fixed it now

frank coyote
#

Hey everyone- i'm kinda new to the whole unity shader thing, but

#

Is there a way to modify a standard PBR URP Shader to have a dissolve effect?

#

i'm trying to achieve this effect with an alpha blending, but if i create my own shader i never seem to get quite the same quality as the URP one

timid jolt
amber saffron
amber saffron
grand jolt
#

Does anyone know what might be causing the artifacting on the floor?

#

A clearer image

smoky widget
#

How do I use global keywords in compute shaders?

#

Because I can't figure out how to make them work

kind juniper
grand jolt
#

it is yeah

kind juniper
grand jolt
#

The toonshader I am currently writing

kind juniper
#

And does the renderer use baked lighting or something?

kind juniper
grand jolt
kind juniper
grand jolt
kind juniper
#

To be honest, that shader looks like a mess. Did you copy it from somewhere write it randomly?

grand jolt
#

No I wrote it myself, Im learning hlsl as I go along

grand jolt
#

Also can you elaborate why my shader is a mess? I dont know what a proper shader is supposed to look like

kind juniper
kind juniper
#

That being said, I'm not a toon shader expert, so can't say that it's necessarily wrong.

#

If you have a complete grasp of the calculations and can assume what values you'll have at each stage, try replacing variable values with hardcoded ones to see if your assumptions are correct.

grand jolt
#

Im not sure if the problem is the fragment shader or not because the artifacts move along with the camera. It seems to be a distance thing

kind juniper
grand jolt
kind juniper
#

Try disabling the cascades and see if that changes anything

                #if 0 //_MAIN_LIGHT_SHADOWS_CASCADE || _MAIN_LIGHT_SHADOWS
                     Light light = GetMainLight(i.shadowCoords);
                #else
                Light light = GetMainLight();
                #endif
grand jolt
#

it doesnt seem to have made a difference

kind juniper
#

Okay

#

What value range is toonLevel supposed to be?
float toonLevel = min(NdotL, shadowFactor);

#

For the pixels over there to be dark, one of the multipliers here must be pretty dark(close to 0).

                col.rgb *= litColor + additionalLightsColor + ambientLight; // Apply final lit color to the texture or base color
                col.rgb *= _LightingColorTint;

Try replacing them one by one with 1,1,1 and see which one removes that "shadow"

#

It's probably no _LightingColorTint since it affects all pixels, so it must be the other one.

#

Try replacing multiplying the color by each of the litColor, additionalLightsColor and ambientLight and see which one causes the issue.

grand jolt
#

if I reduce the shader to just returning the toonLevel it returns a black and white version of the issue

#

its the shadowfactor

#

more specifically the result from MainLightRealtimeShadow it seems

#

Not sure what that means for my issue though

kind juniper
#

Seeing how it's a unity function, the issue is probably with the coordinates.

heavy summit
#

if somethings out of render distance how can i fix that, im tryinig to get a sun to show up but its only visible in edit mode, quite far away

grand jolt
#

yeah thats what I thought too.

struct MeshData
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
                float3 normals : NORMAL;
                float4 color : COLOR;
            };

            struct Interpolators
            {
                float4 vertex : SV_POSITION;
                float2 uv : TEXCOORD0;
                float3 positionWS : TEXCOORD1;
                float3 normal : TEXCOORD2;
                float4 color : COLOR;
                float4 shadowCoords : TEXCOORD3;
            };

            Interpolators vert(MeshData input)
            {
                Interpolators output;

                VertexPositionInputs posInputs = GetVertexPositionInputs(input.vertex.xyz);
                VertexNormalInputs normInputs = GetVertexNormalInputs(input.normals);

                output.positionWS = posInputs.positionWS;
                output.normal = normInputs.normalWS;
                output.vertex = posInputs.positionCS;
                output.uv = TRANSFORM_TEX(input.uv, _MainTex); // input.uv;
                output.shadowCoords = GetShadowCoord(posInputs);
                output.color = input.color;
                return output;
            }
kind juniper
#

Another possible explanation is that the issue is in the shadow maps.

#

Maybe try disabling shadow casting on your spheres.

#

Or even the plane itself.

#

One by one.

grand jolt
#

if I disable it on the plane the artifacts go away

#

wait no, nevermind

#

the artifacts just get less obvious

kind juniper
grand jolt
#

yeah that seems to be correct

#

when I disable them one by one more of the artifacts dissapear

kind juniper
#

Try also placing a cube with a standard urp shader and see if it casts the shadow correctly

grand jolt
#

no actually, that also causes artifacts

#

so its has to have something to do with how the surface receives shadows right?

kind juniper
#

Yeah

grand jolt
#

Hmm, I found a maybe related issue with the shader, I give the ground plane a textured instead of a color no shadows appear

#

actually never mind thats not true, its just that one of my textured materials wasnt getting shadows

kind juniper
#

Maybe have a look at what shadow maps are passed to your shader in the frame debugger

#

And compare to a similar setup with a standard shader.

grand jolt
#

Ive checked any my shader matches with the official example

#

this would have to be a shadowperformance thing then if its between those two options right?

#

Okay I found which setting ends up deciding how far away the artifact is, and its the Max Distance setting

#

speficically it seems to be on the transition between the cascades that it breaks

orchid hedge
#

is it somehow possible to change a variable of the shader editor in the shader editor?

dim yoke
orchid hedge
#

ah nvm i got it

#

the biggest problem i have now is that if i try to use the y object position of my cylinder the shader starts in the middle of the cylinder but i want it to start from the bottom how can i do this in the node editor?

smoky widget
low lichen
swift vine
#

Hello guys !
I followed this tutorial to reproduce this portal effect : https://www.youtube.com/watch?v=cWpFZbjtSQg&t=588s
My project is using URP so I created a shader graph that normally does the same thing as his shader (picture 1) but it seems I've missed something 'cause it's not working as intended (picture 2) it just make the cube white
Can anyone help me pleeeeeeease x)

Experimenting with portals, for science.

The project is available here: https://github.com/SebLague/Portals/tree/master
If you'd like to get early access to new projects, or simply want to support me in creating more videos, please visit https://www.patreon.com/SebastianLague

Resources I used:
http://tomhulton.blogspot.com/2015/08/portal-rende...

▶ Play video
#

(better screen for shadergraph)

swift vine
hardy juniper
#

dont you want normalised screen pos to sample the texture correctly?

swift vine
#

i don't know xD

#

I do not know much things about shaders

hardy juniper
#

but the issue should be relating to the sample. in default i think it can be used directly to sample

swift vine
#

I add it like that ?

hardy juniper
#

mode to default and then use the out to sample the tex directly and see what happens

#

If this fails, bypass your masking and see how it looks

swift vine
hardy juniper
swift vine
#

no changes

hardy juniper
#

A basic demo of the concept of normalised UV to sample a texture

swift vine
#

oh awesome thanks

#

i'll try

hardy juniper
#

i forget what he does in that video exactly but hoepfully you can understand and apply what he does

swift vine
#

ok i think that's a problem with the scripts 'cause it only render white and not the texture

hardy juniper
#

you can inspect render texture and see the contents in inspector so check that

swift vine
#

it do not use a render texture

#

if i well understood it just send the texture directly onto the material

#

ok yep I found

#

the camera were rendered manually in this method

#

but the method was not called I moved the code in update and it work better not perfectly but it render the texture xD

hardy juniper
#

Great 👍

swift vine
#

I keep having some issues but i think i can find out these

#

thanks dude !

velvet hedge
#

Hello! I would like to ask about Shaders and Player control. I've done a tutorial on youtube about making a curvy world, but my player seems to be floating. Below is my shader according to the YT video I've watched

#

But if I move the perspective a little bit, or in "Play" mode I walk a little bit front or back, the player seems to be moving and a slight Y-offset is visible. How can I address this issue?

dim yoke
# velvet hedge But if I move the perspective a little bit, or in "Play" mode I walk a little bi...

Making the movement code respect the world being round would be really hard problem to solve. I think this kind of effect is usually done by either keeping the player always at the middle of the curve (move the world in the opposite direction when you want to move the player) or by moving the curve effect with the player so that the player always seems to be on top of the curve. This would keep all colliders intact with the drawn mesh near the player and therefore the height of the player wouldn't need to be adjusted. This would also eliminate the need to rotate the player to keep right angle with ground (usually you want the player pointing straight away form the center point of the earth below)

velvet hedge
#

What if I add NPCs or even multiplayer functionality to the game? Will the logic respect the other characters' perspectives as well?

dim yoke
# velvet hedge What if I add NPCs or even multiplayer functionality to the game? Will the logic...

I don't see a problem with that (assuming they all have the same shader that makes them curve with the world of course). In reality every interaction in the game would keep happening exactly as if the world was flat but it would just be rendered as if it curved. In a multiplayer game, each players own view would be rendered as if the world (including your character) would be curving under them. The only logic that I think would break is if you wanted to lets say use raycasts to interact with the enrivonment using your mouse, the raycast would hit the object that was behind your mouse in the flat world, not in the curved "reality". I'm sure there is a way to fix that by doing the raycast in a small steps that curve in the flat world to simulate a straight line in the curved world but that is something that needs to be taken into account and doesn't work automatically

velvet hedge
#

Thank you very much 😄

dim yoke
# velvet hedge Thank you very much 😄

Other thing that I thought just know are sounds which you will hear as if the world was flat so even if the source of the sound was far beyond the curve, maybe even straight below you on the other side of the "planet", you would hear the sound coming straight forwards from where you are. Obviously it depends how much curvature you will add how much this affects things and on your artistical choise whether it even matters. This is obviously possible to take into account too if you really want to (by always moving the sources of sound where they visually appear to be on the curved world) but likely this would be insignificant anyways

zinc moth
#

Hey all - I was wondering how to do an edge replacement shader on pixel art. I currently have an outline shader but that won't due since the outlines are already baked into the assets being delivered from the artist and one of the effects we're doing requires the edge to change colors. There's too many assets to bake it in to the correct color.

Image 1 is an example what the asset would come in like with a black outline in the asset.
Image 2 is the expected result.
Image 3 is what my current outline shader is effectively doing but this is incorrect.
Image 4 and 5 are my shader that I implemented from this video (https://www.youtube.com/watch?v=84rZ-rCRsZk)

I know that it may be beneficial to have the assets without the baked in outline but that is not a decision I get to make and have to find a solution to this.

Any help would be super appreciated.

Create an outline effect in 2D for SpriteRenderers using Unity Shader Graph! You can also read this tutorial here: https://danielilett.com/2020-04-27-tut5-6-urp-2d-outlines/

💻 Get the source on GitHub:
https://github.com/daniel-ilett/2d-outlines-urp
✨ Get the "Bandits - Pixel Art" pack on the Asset Store:
https://assetstore.unity....

▶ Play video
mystic pasture
#

Hey, is there a way to translate this shader to a shader graph?
I followed a tutorial on how to do a Stencil Shader for a Portal which i want to show on my Apple vision Pro, but the AVP does not support shader (the coded ones) so i need to translate this into a graph. Has anyoen done that before?

Shader "Custom/StarfieldStencilShader"
{
    Properties
    {
        [IntRange] _StencilID ("Stencil ID", Range(0, 255)) = 1
    }
    SubShader
    {
        Tags { 
            "RenderType"="Opaque"
            "Queue" = "Geometry"
            "RenderPipeline" = "UniversalPipeline"
        }
        
        Pass {
            Blend Zero One
            ZWrite Off

            Stencil 
            {
                ref [_StencilID]
                Comp Always
                Pass Replace
                Fail Keep
            }
        }
    }
}
kind juniper
#

Might be able to maximize effectiveness by combining both of the methods.

zinc moth
#

I think the second method is fine in this case in all honesty

#

It's happening only in one instance so having multiple materials or passes on it shouldn't effect much

kind juniper
mystic pasture
#

How do you mean? Sorry verry new to unity in general. Do you maby have a Blog or something where i can read about it?

mystic pasture
kind juniper
#

With details and context of the "did not understand" or "did not work" provided.

mystic pasture
kind juniper
mystic pasture
#

Well let me try that again then and I try to tell you all I know.

I want to create a "Portal" for a Project that will run on the Apple Vision Pro. The API for the AVp does not allow shaderlab Shader to beused. I found a Tutorial that creates the portal effect by defining a Render Object on my URP Renderer that has the Stencil override. Afterwards he defines a shaderlab shader like this one:

Shader "Custom/StarfieldStencilShader"
{
    Properties
    {
        [IntRange] _StencilID ("Stencil ID", Range(0, 255)) = 1
    }
    SubShader
    {
        Tags { 
            "RenderType"="Opaque"
            "Queue" = "Geometry"
            "RenderPipeline" = "UniversalPipeline"
        }
        Pass {
            Blend Zero One
            ZWrite Off

            Stencil 
            {
                ref [_StencilID]
                Comp Always
                Pass Replace
                Fail Keep
            }
        }
    }
}

Here soem of the most "useful" articels I read:

So my question would be, if it is possible to implement this functionality in any other way since I cant find a Stencil inside the Shader Graphs Docs.

rustic escarp
#

is it possible to downscale a texture in shadergraph?

warm pulsar
#

this made it really easy

#

one headache was that lights would get culled incorrectly. i don't remember if i ever fixed that...

kind juniper
#
  1. What do you mean by "the api does not allow shaderlab shaders to be used"? What API is it? Shaderlab is the default way to create shaders in the built-in render pipeline, so it sounds very weird that there would be an issue with it.

  2. From what I see, stencil is still not implemented in shader graph, so no, you can't use shader graph for it.

kind juniper
# rustic escarp is it possible to downscale a texture in shadergraph?

Downscaling is more than just a shader. In the simplest form it's just rendering to a render target/texture of smaller size. So the answer to your question is both yes and no.
Here's some docs on how you can Blit to a render texture. You just need to set it's resolution to whatever you want to downscale to.
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@14.0/manual/renderer-features/how-to-fullscreen-blit.html

rustic escarp
#

ASCII Shader

radiant meteor
#

Hello, I am trying to modify the TMP shader to make the text fade out when on the edges of the screen. I think input.position in the pixel shader is not what I expect it to be as for some reason xy is always 1,1. I thought it would be in clip space since it's set to SV_POSITION.

Here's the input struct in the TMP shader:

struct pixel_t
            {
                UNITY_VERTEX_INPUT_INSTANCE_ID
                UNITY_VERTEX_OUTPUT_STEREO
                float4 position : SV_POSITION;
                fixed4 color : COLOR;
                float2 atlas : TEXCOORD0; // Atlas
                float4 param : TEXCOORD1; // alphaClip, scale, bias, weight
                float4 mask : TEXCOORD2; // Position in object space(xy), pixel Size(zw)
                float3 viewDir : TEXCOORD3;

                #if (UNDERLAY_ON || UNDERLAY_INNER)
            float4    texcoord2        : TEXCOORD4;        // u,v, scale, bias
            fixed4    underlayColor    : COLOR1;
                #endif

                float4 textures : TEXCOORD5;
            };

here's my code that doesn't work:

                float4 center_screen_position = float4(input.position.xy * 2.0 - 1.0, 0.0, 0.0);
                float2 abs_position = abs(center_screen_position.xy);
                float2 smoothstep_position = smoothstep(_ScreenFadeEdge.xy, float2(0.999f, 0.999f), abs_position);
                float max_fade_value = 1 - max(smoothstep_position.x, smoothstep_position.y);

max_fade_value is always 0 (or always 1 when 1- is removed). if I return float4(input.position.xyz, 1.0f);, the output is yellow.

hardy juniper
grand jolt
#

So Im still having the same issue with the shadow cascade transitions from yesterday. Ive reduced everything down to the problematic parts by copying the documentation found here: https://docs.unity3d.com/6000.1/Documentation/Manual/urp/use-built-in-shader-methods-shadows.html
The image has 2 regular lit objects, and 2 objects using the same shader as the ground plane.

Shader "Unlit/ShadowCascadingShader"
{
    SubShader
    {

        Tags { "RenderType" = "AlphaTest" "RenderPipeline" = "UniversalPipeline" }

        Pass
        {
            HLSLPROGRAM

            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

            struct Attributes
            {
                float4 positionOS  : POSITION;
            };

            struct Varyings
            {
                float4 positionCS  : SV_POSITION;
                float4 shadowCoords : TEXCOORD3;
            };

            Varyings vert(Attributes IN)
            {
                Varyings OUT;

                OUT.positionCS = TransformObjectToHClip(IN.positionOS.xyz);

                // Get the VertexPositionInputs for the vertex position  
                VertexPositionInputs positions = GetVertexPositionInputs(IN.positionOS.xyz);
                float4 shadowCoordinates = GetShadowCoord(positions);
                OUT.shadowCoords = shadowCoordinates;

                return OUT;
            }

            half4 frag(Varyings IN) : SV_Target
            {
                half shadowAmount = MainLightRealtimeShadow(IN.shadowCoords);
                return shadowAmount;
            }
            
            ENDHLSL
        }
#

        Pass
        {
            Name "ShadowCaster"
            Tags
            {
                "LightMode" = "ShadowCaster"
            }

            ZWrite On
            ZTest LEqual
            Cull[_Cull]

            HLSLPROGRAM
            // Required to compile gles 2.0 with standard srp library
            #pragma prefer_hlslcc gles
            #pragma exclude_renderers d3d11_9x
            #pragma target 2.0

            // -------------------------------------
            // Material Keywords
            #pragma shader_feature _ALPHATEST_ON

            //--------------------------------------
            // GPU Instancing
            #pragma multi_compile_instancing
            #pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A

            #pragma vertex ShadowPassVertex
            #pragma fragment ShadowPassFragment

            #include "Packages/com.unity.render-pipelines.universal/Shaders/LitInput.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/Shaders/ShadowCasterPass.hlsl"
            ENDHLSL
        }

        Pass
        {
            Name "DepthNormals"
            Tags
            {
                "LightMode"="DepthNormals"
            }
            ZWrite On
            ZTest LEqual
            Cull Off

            HLSLPROGRAM
            #pragma vertex DepthNormalsVertex
            #pragma fragment DepthNormalsFragment
            #pragma shader_feature_local _NORMALMAP
            #pragma shader_feature _ALPHATEST_ON
            #pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
            #pragma multi_compile_instancing
            #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/SurfaceInput.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/Shaders/DepthNormalsPass.hlsl"
            ENDHLSL
        }
    }
}```
#

Does anyone know what might be causing it? Ive noticed it on 6000.0.25 and the latest unity 6 version. It occurs on forward, forward+ and deferred rendering.

smoky widget
primal prawn
#

Which shader graph works on ui elements, because i saw a yt video suggesting 'canvas shader graph' but unfortunately in my project I'm unable to see any canvas shader graph.

tired skiff
#

is there any way to have a shader that keeps the same tiling if i scale the mesh on Z axis?

#

If i scale the mesh I see the texture stretched.

frigid jay
tired skiff
#

it does not work. could you prove it

dim yoke
tired skiff
#

simple tex with a noise on a cylinder. I need to scale the z lenght (hight of the cylinder)

dim yoke
tired skiff
warm pulsar
#

It's easy if the UVs are aligned to the stretch axis -- just adjust the tiling on the material to compensate, really

#

If they aren't aligned, The Fun Begins

#

You could also generate a UV coordinate from the position along one axis and the angle around that axis, actually

tired skiff
#

could you show it?

warm pulsar
#

Not triplanar, but a similar idea

tired skiff
warm pulsar
#

very rough example, but if your UVs weren't aligned to the axis of stretching, then just changing the tiling would fail

warm pulsar
# tired skiff could you show that it works ?

for a given point on the cylinder's surface, you'd need to find:

  • how far along the major axis you are
    • subtract the position of the bottom of the cylinder from your position, then project onto the major axis and get the length of the resulting vector
  • how far around the cylinder you are
    • subtract the position of the bottom of the cylinder from yoiur position, then a project-on-plane operation with the major axis, then use Atan2 to get an angle
shadow thistle
#

I need help with shaders. I'm trying to make the top left the pivot of the UV. Or find a property that is relative to the UI.Image transform...

#

Final result - a grid originating from top left corner

warm pulsar
#

Hence why the origin is not at the center of the rect

#

Let me look at how I solved this before

#

I'm pretty sure I just calculated the an offset in a script

#
Matrix4x4 correction = canvas.transform.localToWorldMatrix;

for (int i = 0; i < segments.Count; ++i)
{
    // many other things
    segment.arc.CombinedMatrix = correction * transform.worldToLocalMatrix;
}

Bingo.

CombinedMatrix is a transformation matrix that takes you from the canvas's local space (which is exactly the "Object" position of a fragment) to my own Transform's local space (which is what I'm actually trying to work in).

By itself, this would be enough to move the origin to the pivot point of your image.

#

You could put your image's pivot point in the top left corner

#

oh, right -- I suppose you want to manipulate those UV coordinates, rather than an object-space position

warm pulsar
shadow thistle
#

i want to get 2d Vector that gives me the distance from top left so i can make a grid with a pivot there.

warm pulsar
#

ah, good, then you do want positions

warm pulsar
shadow thistle
#

nice

#

shaders are still lowkey new to me

warm pulsar
#

You'd find the difference in canvas-space positions between the top left corner and the center of the image

#

Then just add that to your object-space position

#

let me try that..

#

so here's what we start with

shadow thistle
#

actually, nvm, ill prob do the visual script thing... except i dont know how to open it rn...

warm pulsar
#

that's the Shader Graph, not visual scripting

shadow thistle
#

so cooll

warm pulsar
#
    public class Test2 : MonoBehaviour
    {
        [SerializeField] private Transform canvas;
        [SerializeField] private Image image;
        
        void Update()
        {
            Vector3 ownPosition = canvas.InverseTransformPoint(transform.position);
            
            image.material.SetVector("_Offset", -ownPosition);
        }
    }

the component is very simple -- it just figures out our position in the local space of our canvas and tells the shader to offset by that much

#

(note the minus sign)

warm pulsar
#

Note that the grid will not rotate if you rotate the image

#

That's because we're just looking at our position

#

If you want to be able to rotate and scale the image properly, you would need something more elaborate

#

(such as an entire transformation matrix!)

heavy summit
#

if i want to treat the stuff from the multiplier node like if it was a sample texture node with the intention of manipulating the uv for like a distortion effect, how would i go about doing that

warm pulsar
#

You'd need to change how rapidly its inputs are changing

#

(great sentence)

#

What are the inputs?

warm pulsar
shadow thistle
#

ok idk why but i can't make shader graphs in my project

warm pulsar
#

Can't I just do this entirely in the shader at that point

shadow thistle
warm pulsar
shadow thistle
warm pulsar
warm pulsar
#

declare a Vector property, then do a few lines of math

#

in fact, all you need to do is add the offset value

heavy summit
#

well the inputs are the vector 2 and another multiplier
heres all the closest nodes

#

this is the full graph so far

warm pulsar
#

At some point, you'll be using a UV coordinate to calculate another value

#

That's what you need to tile + offset

heavy summit
#

ill try

warm pulsar
#

Conceptually, doing a bunch of math with a UV coordinate and then using the result as a color is the same as sampling a texture

#

The UV coordinate determines the result

shadow thistle
# warm pulsar nice, it works

i'm actually realising that would break my whole grid... i'll need the position thing to go into negative values, and not mod itself to 0-1.

warm pulsar
heavy summit
#

i think i have grain fog or something how do i put this together

shadow thistle
#

it would otherwise break the grid by making every cell identical, and they will have unified, but changable size

warm pulsar
#

That does not make any sense

#

You aren't adjusting the color after calculating it

#

You are adjusting how you calculate the color

warm pulsar
heavy summit
#

specifically the distortion and glitch effects on this page

#

trying to only use shapes from the graph nodes

warm pulsar
#

You want these lines to repeat more rapidly, right?

heavy summit
#

side to side glitch effect i suppose

warm pulsar
#

they're horizontal lines; I wouldn't expect horizontal movement to do anything

heavy summit
#

oh well yeah the pictures i posted are from the distortion effect i am trying to replicate

#

not the glitch one

warm pulsar
#

i don't know what you're actually trying to do now

heavy summit
#

well you know how the sample texture has uv input

warm pulsar
#

Yes, which lets you resize and offset the texture

heavy summit
#

i wanna do the same with what i have in the multiplier node but its not a texture node

warm pulsar
heavy summit
#

no, the tutorial said i needed one, idk what im doing tbh

warm pulsar
#

In both the upper and lower sets of nodes, I am using a UV coordinate to calculate a color

#

The upper set is using a sample texture node to look up colors from an image, using the UV coordinate

#

The lower set is just taking the sine of the UV coordinate

#

I have added a "Tiling and Offset" node to both sets. Notice how the resulting colors have changed.

#

Conceptually, there is no difference between:

  • Passing a UV coordinate into a Sample Texture 2D node
  • Doing some other math with a UV coordinate to get a color
heavy summit
#

what i ultimately want to accomplish is this

warm pulsar
#

So whether you're using a UV coordinate to sample a texture or calculate some arbitrary value, the approach is exactly the same

#

modify the coordinate before you use it

shadow thistle
warm pulsar
heavy summit
#

ill try again and give update

warm pulsar
heavy summit
#

before the tiling and offset ?

warm pulsar
#

(the proper name will be _Offset, not Offset

warm pulsar
#

You need to pass the UV coordinate into that node before anything else happens

#

then you can use the resulting values to do your calculations

shadow thistle
warm pulsar
#

Right

#

You have to give it a reference to the Canvas's transform

#

so that it can figure out the canvas-space position of its pivot point

hardy nimbus
#

Can someone else confirm that Unity's default plane mesh UV coordinates start at the top left instead of the bottom, but the quad starts at the bottom left. Making sure I am not going insane here.

Left one is a quad and right one is a plane.

warm pulsar
#

Yeah, the UV layouts are different. The orientations are different as well

#

Quad is in the XY plane. Plane is in the XZ plane

hardy nimbus
#

I kind of get it though since Unity uses a form of quad cut out for Sprites though, but was wondering.
Thank you for the response.

warm pulsar
#

Plane is the weird one. It's so big...

shadow thistle
#

it works perfectly now, thx @warm pulsar!

warm pulsar
#

nice!

#

I was really confused by that behavior for a while

#

I was expecting object space to be..well, my object's space

eager shadow
#

Your object space is never actually yours. It belongs to the GPU gods

heavy summit
warm pulsar
#

Although, it does depend on the effect you want

#

The most obvious thing to do is to immediately tile + offset the UV coordinates, though

heavy summit
#

my issue is that it seems to work fine with a texture node here

but idk how to plug this together with the output from the multiplayer node wich is what im working on,

#

this shader doesent really have any textures so

#

its all shape nodes

#

maybe i screwed myself taking that approach but i wanted to try and make the mask change between sun and moon shape with a slider as seamlessly as i was able to and also as an experiment to see if i could to it without textures so i can limit the upload size to vrchat, so its

#

yeah

warm pulsar
#

huh, I've never used Gather Texture before

#

apparently it's used to sample four fragments' colors at once

heavy summit
#

oh i just misclicked but its just for debugging i guess

warm pulsar
#

I am modifying the value that comes out of the UV node

#

This makes it repeat more rapidly

#

I am not trying to do anything after the modulo or multiply nodes

#

because that's too late

heavy summit
#

so i have to do it at the beginning of the shader on each individual shape?

#

theres uv stuff there at least seems to make sense

heavy summit
#

ooh it works

#

nice

#

check that out 😌

warm pulsar
# heavy summit

You'd do it before you use the UV coordiante to calculate anything, yeah

#

Just like how you'd do it before you use a UV coordinate to sample a texture

heavy summit
#

thanks for the help

vestal hinge
#

Hi all! I was wondering if anyone knew how to set up a material / shader in the shader graph that could allow for optional parameters, that hide and show based on other selected parameters.

What I mean by this is the kind of behaviour that the default URP/Lit material has, whereas changing the Surface Type will result in the blending mode appearing and such.

Right now I have my own shaders for rendering cells using Graphics.RenderPrimatives, I have several different types of cells each with different materials. Some use alpha clipping while others don't, I would like to combine these shaders into 1 and have a toggle for whether it is using Alpha clipping, like how the URP/Lit shader uses this too.

Is this possible?

shadow thistle
#

Hey @warm pulsar im having a problem... i've moved the pivot of the image but for some reason, only Y value is offset, but not X not Z.
Debug.Log(ownPosition);

warm pulsar
#

That is expected. The canvas-space X position is zero

#

(by "canvas-space", I mean the local space of the RectTransform that the Canvas is attached to)

shadow thistle
#

omg nvm im stupid its a me thing... fixed it...

warm pulsar
#

The shader can't really do that on its own.

#

It can't know which layer each pixel "came from"

#

What render pipeline are you using?

hardy juniper
#

You could define spheres or cubes and if the fragment world position is inside an area, use actual colour. Else use the grey scale version.

thorny owl
#

!code

echo moatBOT
thorny owl
#

https://paste.mod.gg/basic/viewer/adncwkwefdiq/0

Greetings, I have this shader written to display Gaussian data. However I get the problem with transparency order rendering. From one side it looks kinda normal, but from other side the elements that are behind is rendered as it is in front. My guess it is due the order of data I pass to the shader and it does not actually check the depth. Enabling ZWrite makes almost all render dissapear. Maybe anyone could guide me how to handle the transparency render order?

Is it possible to do in shader?
Or I need update function which will order data and redraw it on Update function?

#

Side One

#

oposite side+

lyric hill
#

Cannot display height maps in my shader

#

I have no idea why

#

Its not bumping upwards

vale sundial
#

Hey, I'm having what seems to me like some sort of depth issue , but can't figure out what's going on. I'll attach my shader graph, and some more context

vale sundial
#

I've realized that I can just make it opaque and alpha clipping still allows me to see through, but I still don't understand why this issue occurs for transparent

fringe karma
#

I'm making a shader in Shader Graph that uses a gradient to determine colours, but I'm trying to figure out - how can I make that gradient modifiable at runtime? I know you can create a gradient field, and give it a default value, but it doesn't appear in the Inspector and I haven't seen any functions for changing a gradient value on a material.
If this isn't possible, an array of colours will also do. So long as I can determine the number of colours

thorny owl
#

How to force Transparent to render like Opaque? Aka be aware of the position in space?

lyric hill
vale sundial
lyric hill
#

Sadge T_T

vale sundial
fringe karma
#

because I know you can set one as a field in shadergraph

#

I could get around it by sampling a texture, but I'm seeing if there are easier ways first

vale sundial
fringe karma
vale sundial
vale sundial
fringe karma
thorny owl
# vale sundial Not sure how an opaque material is any more aware of its position in space than ...

example with Opaque material settings and with transparent.

Aka opaque renders mesh that is close as closer and covers mesh behind, while transparent does not do that at all. It only works by the order transparent meshes were created (this mesh is created from a lot transparent quads). So just chaning settings is not enough. I would assume i need to take distance to camera or something and do something with that data, but I just don't know how exactly to do it . (P.S. object is not rotated, if it looks like it it just visual trickery )

vale sundial
grand jolt
#

Hi, I'm using unity 6 and I am writing an hlsl URP toon shader. I would like to add edge-detection to the shader for outlines, and for it to be togglable per material. I've tried for a couple of hours to figure out how to get a depth normals texture for my sobel algorithm but to no avail. Most of the documentation I am able to find has been for 2021 versions of unity or earlier, and with the new render graph API I havent been able to create a depth normals texture for my shader to access. Could someone point me in the right direction? Is there a depth normals texture already exposed in urp 17 that I am missing?

#

I should add that I would like to calculate the edges inside of the material shader of the objects in the scene, not as a render pass applied to the entire screen.

low lichen
hardy juniper
# thorny owl https://paste.mod.gg/basic/viewer/adncwkwefdiq/0 Greetings, I have this shader ...

Can you do a short video showing this in more detail?
Transparent rendering will always usually have the limitation of not writing depth. Meshes are sorted by their bounding box center. I believe for each individual mesh the order of triangles will their sorting within the mesh (again due to no depth writing).
Forcing depth write can help but it affects how it renders with other transparent meshes.

grand jolt
#

I would like the outlines to be 1 pixel thick, and for overlapping of meshes to also produce an outline

#

tough ideally the outline thickness would be configurable in the shader

hardy juniper
#

if you want to use depth or normals in a post shader then you cant "configure it per object"

#

unless you rendered these objects separately and did the post effect for them again

grand jolt
#

I would like it to be added to the rendering of the current toon shader Ive written, not as a post shader if that makes sense

hardy juniper
grand jolt
#

I have, but I wanted to write my own shader to learn hlsl.

hardy juniper
grand jolt
#

Thanks! Ill check them out!

low lichen
# grand jolt I would like the outlines to be 1 pixel thick, and for overlapping of meshes to ...

The simplest way to do edge detection directly in a shader without any outside resources is to use derivatives, ddx/ddy/fwidth. That can be used to calculate the difference of any variable between neighboring pixels. However, that will only be able to access pixels that are being rendered by the same shader in the same draw call. And you're limited to 1-2px outlines with this technique.

hardy juniper
grand jolt
#

Thank you both for all the help!

#

Ill definitely look into both suggestions

vapid mantle
#

SANITY CHECK PLEASE: Is it true that the cubemap shader only allows a max face size of 2048 and to go higher I need to use a 6 sided skybox material (resulting in more draw calls) or create my own custom shader? Surely not? There is a performant 4096 skybox shader right?

low lichen
vapid mantle
#

This is just the standard skybox/cubemap

low lichen
#

You're editing a cubemap texture there, not a shader.

vapid mantle
#

How do I get a 4096 cubemap then please?

#

Sorry this is the standard skybox/cubemap shader. You cannot select anythibg above 2048

grizzled bolt
#

That's not the texture either but a legacy "cubemap asset" which isn't really used

#

Except for generating cubemap textures

#

If you don't already have one

low lichen
#

As the warning shows:

It's preferable to use Cubemap texture import type instead of Legacy Cubemap assets.

grizzled bolt
#

6 sided cubemap material doesn't result in more drawcalls, but rather more texture samples
Not a problem usually

#

To import a texture as cubemap type the texture would have to contain all the faces in a supported layout like a row or a column, which technically is as simple as placing the images next to each other in an image in the right order and orientation

#

But that isn't necessary to do if the 6 sided material looks fine for your use case
The benefit of a cubemap type texture is that more shaders support it and it's easier to use in custom shaders

languid trench
#

How can I use Water Exclusion shader with Custom Pass? I've copied the material from HDRP package, put it on the custom pass but its just purple.

fresh flame
#

how can I fix this? I dont even know what to call that

civic lantern
fresh flame
#

I dont think camera clips into the leaves but tree body renders above leaves

civic lantern
#

Use an opaque material instead of transparent

fresh flame
#

thank you so much

devout quarry
# grand jolt Hi, I'm using unity 6 and I am writing an hlsl URP toon shader. I would like to ...

Have you seen this?

https://ameye.dev/notes/edge-detection-outlines/

In my own projects I combine it with a section map pass where I only draw some objects to the section map with a unique ID per-object, and then I get outlines only around those objects.

https://linework.ameye.dev/section-map/

The section pass itself can be easily added to that render graph edge detection pass from the tutorial in the first link.

The section pass is like this

using (var builder = renderGraph.AddRasterRenderPass<PassData>(ShaderPassName.Section, out var passData))
{
  builder.SetRenderAttachment(sectionHandle, 0);
  builder.SetRenderAttachmentDepth(resourceData.activeDepthTexture);
  builder.SetGlobalTextureAfterPass(sectionHandle, ShaderPropertyId.CameraSectioningTexture);

  InitSectionRendererList(renderGraph, frameData, ref passData);
  builder.UseRendererList(passData.SectionRendererListHandle);

  builder.SetRenderFunc((PassData data, RasterGraphContext context) => 
  {                  
    context.cmd.DrawRendererList(data.SectionRendererListHandle);       
  });
}
grand jolt
#

Oh! This might be exactly what I am looking for

#

I had seen the first post, but not the second one

devout quarry
#

that sample is straight from my own code, so if you get stuck implementing it, feel free to ask

#

This is not 'calculating the edges inside of the material shader of the objects in the scene' though, since you mentioned that.

grand jolt
#

Thanks! So I do wonder, is it possible to toggle the section pass off on a per material basis?

#

Im still learning HLSL and the URP, so Im not sure what the constraints of this are

devout quarry
#

Hmm you can do multiple things

  • per shader basis (use lightmode tags/filter)
  • per rendering layer basis (mesh renderers have a rendering layer)
  • per layer basis (regular layers)
grand jolt
#

Thats really cool. Ill definitely try to use this in my project.

devout quarry
#

Per material basis (so same shader, different material) is also possible, what I do for that is enable a keyword before rendering the section map, and disabling it after. I then customize my shader to output something different to the section map (or nothing), based on that keyword being active.

grand jolt
devout quarry
#

That's also explained in that post, see the 'Shader Keyword' section. Basically, tons of options.

#

The outline techniques that others linked are essentially similar, you render objects to a buffer, then generate an outline from that, either by running edge detection on it, or by taking the buffer itself and dilating it to get an outline.

grand jolt
#

Right, Ill give it a better look. Im just a bit confused because Im not sure what the ShaderPassName variable is supposed to be since its not present in the example found in https://ameye.dev/notes/edge-detection-outlines/ using (var builder = renderGraph.AddRasterRenderPass<PassData>(ShaderPassName.Section, out var passData))

devout quarry
#

ShaderPassName is just an enum in my code, you just pass it a string that will be shown in the frame debuffer

grand jolt
#

Oh right, right as I sent that message it clicked. Sorry!

#

Is InitSectionRendererList also a method you wrote?

devout quarry
#

And yeah there are several custom methods, if your IDE doesn't recognize it, it's probably mine.

#

That InitSectionRendererList does this (with some parts left out)

var drawingSettings = RenderingUtils.CreateDrawingSettings(RenderUtils.DefaultShaderTagIds, universalRenderingData, cameraData, lightData, sortingCriteria);

                var filteringSettings = new FilteringSettings(renderQueueRange, -1, settings.SectionRenderingLayer);

drawingSettings.overrideMaterial = section;

renderGraph.CreateRendererList(param);

I don't really want to share the full code but this should give the idea. To render to the section map, you set filteringsettings (here I filter using rendering layers), then I set an overridematerial so each object will render using that override material to the section map. This overridematerial for example is a simple material that outputs vertex color, or a random ID based on world position.

#

Look at the RenderObjectsPass from Unity, they do the same thing and there you can see the full code.

grand jolt
#

Right, that makes sense. Thank you. Ill see if theres more material on how to do a section render online

devout quarry
#

The RenderObjectsPass really should give a good idea on how to render only some objects. By then using builder.SetRenderAttachment(sectionHandle, 0); you tell Unity to render to a custom handle. Combine that with the edge detection pass, and you then are able to use the section map as input.

grand jolt
#

Okay, thanks for the help!

grand jolt
devout quarry
# grand jolt Hey, sorry to bother you but Im not sure how the Render texture in your tutorial...

Yeah so the handle is made like this

 // Section buffer.
  var sectionBufferDescriptor = cameraData.cameraTargetDescriptor;
  sectionBufferDescriptor.graphicsFormat = GraphicsFormat.R16_UNorm;
  sectionBufferDescriptor.depthBufferBits = (int) DepthBits.None;
  sectionBufferDescriptor.msaaSamples = 1;
  sectionHandle = UniversalRenderer.CreateRenderGraphTexture(renderGraph, sectionBufferDescriptor, Buffer.Section, false);

And then I sample it like this in the shader. So

SAMPLE_TEXTURE2D_X(_CameraSectioningTexture, sampler_CameraSectioningTexture, UnityStereoTransformScreenSpaceTex(uv));

and so in the rendering code I did

builder.SetGlobalTextureAfterPass(sectionHandle, ShaderPropertyId.CameraSectioningTexture);

Where ShaderPropertyId.CameraSectioningTexture = Shader.PropertyToID("_CameraSectioningTexture");

grand jolt
#

Thanks for the clear explanation!

#

In the shader the name _CameraSectioningTexture isnt recognized, do I just have to define it as a property in the pass?

devout quarry
#

Check the DeclareOpaqueTexture.hlsl file from Unity, I do it the same way for mine

drowsy shuttle
#

Tho i have a question, how can i create a waterline effect

#

This like underwater rendering

#

Also what abt water interaction?

cerulean moon
#

Hello,

I’ve been facing an issue for the past two days with shader programming. I’m new to it, so I’ve been using Shader Graph because it’s easier to grasp. I’m using it to color custom meshes for my procedurally generated terrain.

I recently found a shader online to create grass, and I want the grass to take on the color of the terrain mesh underneath it. However, I can’t figure out how to pass the terrain shader’s color information to the grass shader. I’m not even sure if this is possible.

I tried generating the shader code from my Shader Graph, but the file is over 7,000 lines long, and I couldn’t identify a specific function that my grass shader could call to retrieve the terrain color.

I’d appreciate any suggestions on how to solve this, thank you

civic lantern
#

Terrain uses "splat maps" or "alpha maps" to store each terrain layer's weight for each terrain pixel

#

Maybe you can get that from the terrain material somehow and pass it into the shader

#

Sounds pretty complex tho

#

Especially if you have multiple terrains

drowsy shuttle
# cerulean moon Hello, I’ve been facing an issue for the past two days with shader programming....

It’s definitely possible to pass color information from one shader to another, though it requires some extra setup since shaders don’t communicate directly. Here the things you can do:

  1. Bake the Terrain Colors to a Texture

You can render the terrain mesh’s colors to a texture.

Pass this texture to the grass shader as a property.

Use the world position of the grass vertices to sample the corresponding color from the texture.

drowsy shuttle
warm pulsar
#

I'd want to bake it into one texture, yeah

#

I'm not sure how I'd handle that

#

Ideally you'd make a shader that does that, rather than manually reading every pixel from every layer's texture in a script

foggy bison
#

probably a pretty common question. but, am i better off learning HLSL, and manually coding shaders, or should i learn shadergraph? i primarily use URP

#

im pretty new to shaders but i think i understand the basics

devout quarry
#

Imo

grizzled bolt
#

Shader graph can be used pretty far without knowing any of the basics, so it's not that useful for learning

#

But it gives you nice results much quicker and works with URP
It's harder and less practical to write shaders manually for URP so it's not a great environment for learning that

#

So if you want to make shaders SG is great
But if you want to really comprehend them too it's best to practice writing them for a BiRP project and study the topic on its own

foggy bison
#

good to know. i haven't used the BiRP in a while. if i ever do then i'll try learning some more HLSL UnityChanThumbsUp

rich wolf
#

Hi, I'm making a water shader in URP and I'm having trouble with creating a depth fade. I'm following along with a YouTube video in which the guy creates this subshader to make the shore fade from dark (deep water) to light (shallow water). It works pretty well but it seems to be based on like the camera/eye perspective and not just the depth of the water (or the distance of the object below the ocean plane that I have). Therefore objects that are closer (not necessarily in shallower water) appear brighter. Would anyone know how to make it based on the depth of the object below the water plane and not the camera depth? Thanks!

regal stag
rich wolf
#

That worked! Thanks!!!

cerulean moon
devout quarry
proud hemlock
#

Hello! I am trying to create refraction effect for water and glass, but there is an issue: shader refracts the whole scene color, which causes objects in front of the glass appear refracted too, you can clearly see it by bits of color of the object around it. It becomes a real problem when it comes to refracting transparent stuff, but the biggest question is how it is done in source engine from 2004 and is there a way to replicate this in unity? You can clearly see that source engine just ignores and don't refract anything in front of the water, which is not the case in my shader (graph is attached, it has some simple math tricks, but nothing to complicated). I am using last verison of URP in Unity 6 lastest version, if that helps.

devout quarry
proud hemlock
#

okay, I will take a look, thank you!

dull magnet
#

fragment shader is:

       fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = _Color;
                col.a = _Alpha;
                return col;
            }

Just curious what goes on under the hood in the GPU that causes a random orange outline to be drawn when the alpha channel is -1e+15?

kind juniper
#

The gpu on it's own doesn't do anything special. It just executes the shaders that you bind to it. So the origin of these issues must be in one of the shaders as well.

drowsy shuttle
kind juniper
# dull magnet fragment shader is: ```c fixed4 frag (v2f i) : SV_Target { ...

Assuming your shader actually represents the final result, one possible explanation is different precision of floating point variables in the inspector and the shader itself. If it's 32 bit in the inspector, but 16 bit in the shader, extreme values might be represented differently.
Generally alpha is supposed to be in the 0-1 range.

#

Though the color going out of the mesh pixels is probably due to some pp effect. Blue, bloom, down sampling. Something like that.

ebon moss
#

how do you go about making all your custom shaders compatable with unity's built in features for shadows and global illumination etc... do you have to do it all manually?

#

and also does anyone know if / where I can find unity's code for some of their built in shaders like URP/lit (ok you just have to click the three dots button and click edit shader)

ebon moss
#

do you guys ever just add onto premade unity shaders directly?

vocal narwhal
ebon moss
vocal narwhal
#

You can look at the code it generates and strip that back. Or start from the source code that's shipped in the packages

ebon moss
#

ok yeah, thats kinda what I was thinking too. Thanks

#

almost two years into gamedev and still so much to learn, especially rendering

warm moss
#

I'd advise against starting with Shader Graph code cause it'd be full of garbage randomly generated variable names and shader graph specific defines. Reading the Lit shader's source code in the PackageCache in your Library is way easier.

true meteor
#

hi guys, is there a way to create an effect like this with scaling the texture?
so i want to make voronoi texture density based on another texture like GradientNoise to create this kind of effect. But when i plug the noise to density, it just gets distored. I guess its because the texture is scaling from uv center and not just making the dots more dense at darker points. Do you have any ideas how to create this effect in some other way?

#

The image is just the thing i want to achieve, the left is voronoi reffrence, and the right is the texutre that density should be based on

#

Oh i just noticed i could just lerp between 2 diffrently scaled voronoi textures based on noise

#

or blend idk how it called in shaders

#

ah nevermind it kinda looks bad

#

but its okay i guess

velvet token
#

I'm trying to convert a blender material to a unity shader graph and i'm stuck on finding an equivalent to invert color node. Invert, Flip and Negate all just make the end result pure black. Here's the blender before and after and unitys before and after.
Not ideal.
I should mention that invert colors doesn't visually do anything until ticking the red checkbox after which it just gets tinted slightly darker.

terse sedge
#

pls help, my shaders broke and not compiling, idk whats the issue

grizzled bolt
velvet token
#

the invert color node has a checkbox for the red channel, thats the one i meant. It looks like the one minus node does the trick though!

grizzled bolt
velvet token
#

ah that does make sense

#

thanks for the help!

hardy juniper
terse sedge
grizzled bolt
#

You probably did something at the time that they broke

hardy juniper
#

is it a lit shader, unlit? If it was made for say the built in rendering system but you are using URP/HDRP in the project, it wont work and will remain pink.

grizzled bolt
#

There's just no clues for us at all

hardy juniper
#

aha that is something. unless this shader does something special just use unitys included cubemap/sky shaders

terse sedge
#

i need this for a mirror

#

ok if be honest i just decompiled them from a random game using assetripper

#

nah it just dissapeard

hardy juniper
#

i wont help with some rando ripped shader

terse sedge
#

maybe...

kind juniper
velvet token
#

having some trouble with the main light direction node. For some reason it just doesn't work? This is the setup its used in, when the main light direction is plugged in the end product isn't visible because its multiplied with black. When using the float to simulate a fake light direction the shader does give back something visible. Since the light and object the shader is on don't move i could technically predefine the light angle with the float but i'd like to reuse this for other projects maybe

regal stag
velvet token
#

ah i'll have to check which pipeline i'm using then. Not sure currently

#

yup, looks like i'm using built-in. How do i change that?

#

ah found it

#

ah. Looks like vrchat only supports the built in pipeline for some reason

primal prawn
#

Does anyone know which shader graph works for ui images, or there isn't one for ui

hardy juniper
regal stag
primal prawn
#

Okay thanks

hardy juniper
#

Yo there is?? Im stuck on 2022 so guess thats why I didnt know 😭 (we are slow at moving our projects to newer versions)

primal prawn
primal prawn
#

I'll just leave it as it is maybe.

hardy juniper
#

all ui shaders need stencil support for masking

dull magnet
#

the transparent shader is set to:

Blend SrcAlpha OneMinusSrcAlpha
BlendOp Add

So it's expected that for alpha > 1, the color of the geometry behind it gets inverted. But why does it only work for emissive color? Not albedo?