#archived-shaders

1 messages ยท Page 43 of 1

vivid marten
#

it looks like it keeps data from the original texture

shadow kraken
#

Try adding a saturate node after the subtract

vivid marten
#

oh that works ๐Ÿค”

#

idk why tho

shadow kraken
#

Because the dark area had negative values

vivid marten
#

ooh I thought it was at zero

shadow kraken
#

Let's say its value was at 0.6, then you subtract 1, now it's -0.4

vivid marten
#

I should maybe make the substract image directly in an image editor instead ๐Ÿ˜›

#

but this way I have the option to keep the original

shadow kraken
#

I'd probably just have it in the alpha of the original png

#

However what you're doing here looks like it could be simplified with a lerp

vivid marten
#

hmm

shadow kraken
#

Instead of the substract and add, just do a lerp with your blue thing in A, the bitmap in B, and your mask in T

vivid marten
#

ah yes but the "blue thing" had to be in B instead

#

it's a waterfall texture btw lol

#

I'm making it scroll to feel more alive

#

but now I see that my texture isn't good enough so I'm gonna change it ๐Ÿ˜‚

#

ty for the help!

halcyon panther
#
v2f vert (appdata v)
{
    v2f o;
    o.vertex = UnityObjectToClipPos(v.vertex);

    // Calculate the y-coordinate of the vertex in texture space.
    float y = v.uv.y * _MainTex_ST.y + _MainTex_ST.w;

    // Calculate the normalized distance from the current row of pixels to the top of the texture.
    float distFromTop = y / _MainTex_ST.y;

    // Calculate the amount of movement for this row of pixels.
    float swayAmount = 0.0;

    // if (distFromTop >= _SwayHead)
    if (distFromTop >= 0.10)
    {
        // Calculate the normalized distance from the _SwayHead value to the top of the texture.
        float distFromSwayHead = (distFromTop - 0.10) / (1.0 - 0.10);

        // Use a smoothstep function to map the distance from the _SwayHead value to a smooth curve between 0 and 1.
        float smoothDistFromSwayHead = smoothstep(0.0, 1.0, 1.0 - distFromSwayHead);

        // Calculate the sway amount for this row of pixels based on the smoothed distance from the _SwayHead value.
        swayAmount = sin(_GameSeconds * 0.034573 + smoothDistFromSwayHead * _MainTex_ST.y) * 0.2 * (1.0 + y) * (1.0 - smoothDistFromSwayHead);
    }

    // Offset the vertex along the x-axis based on the calculated swayAmount.
    o.vertex.xy += swayAmount;

    o.uv = TRANSFORM_TEX(v.uv, _MainTex); // transform the texture coordinates
    return o;
}

Okay, so this is texture space right? ๐Ÿ˜„
I'm working on a shader for plant textures in RimWorld and in-game it appears to be working like screenspace. Video pretty much sums up the issue I think. lol
There's also some weird issue with the transparent pixels of the texture interfering with other textures...

lunar valley
#

well you can always use an unlit shader and make the light calculations yourself

frank sonnet
#

Is there a library for parallel programming like open mp only for shader?

amber saffron
frank sonnet
#

i want to make it more efficient/faster. It still has to do computations step by step if i use for-loops right.

amber saffron
violet pebble
#

Hi, i'm running into some trouble in URP trying to make a simple shader to work. Although i try using a command buffer to output to a texture, the texture i get seems invisible

#

I don't know how to explain this well please ask if my explanation is confusing

#

Shader : ```
HLSLPROGRAM
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
#pragma vertex Vertex
#pragma fragment Fragment

        struct Attributes {
            float3 positionOS : POSITION;
        };

        struct Interpolators {
            float4 positionCS : SV_POSITION;
        };

        Interpolators Vertex(Attributes input) {
            Interpolators output;
            VertexPositionInputs posnInputs = GetVertexPositionInputs(input.positionOS);

            output.positionCS = posnInputs.positionCS;

            return output;
        }

        float4 Fragment(Interpolators input) : SV_TARGET{
            return float4(1,1,1,1);
        }

        ENDHLSL```
#

PaintObject:```
public class PaintObject : MonoBehaviour
{
const int TEXTURE_SIZE = 1024;

private RenderTexture _paintMask;
Renderer _rend;
int mainTextureID = Shader.PropertyToID("_MainTex");

public RenderTexture PaintMask { get => _paintMask; set => _paintMask = value; }
public Renderer Rend { get => _rend; set => _rend = value; }

// Start is called before the first frame update
void Start()
{
    PaintMask = new RenderTexture(TEXTURE_SIZE, TEXTURE_SIZE, 0);
    PaintMask.filterMode = FilterMode.Bilinear;

    _rend = GetComponent<Renderer>();
    _rend.material.mainTexture = _paintMask;

    PaintManager01.instance.Init(this);
}

}```

#

PaintManager:```public class PaintManager01 : MonoBehaviour
{
public static PaintManager01 instance;

[SerializeField] private Shader transparentShader;

Material transparentMaterial;

CommandBuffer command;
private void Awake()
{
    if (instance != null)
    {
        Debug.LogError("Multiple Paint Managers");
        Destroy(this);
        return;
    }
    instance = this;

    transparentMaterial = new Material(transparentShader);
    command = new CommandBuffer();
    command.name = "PaintManager01 Command Buffer";
}

public void Init(PaintObject obj)
{
    Debug.Log("Initializing " + obj.gameObject.name);
    RenderTexture mask = obj.PaintMask;
    Renderer renderer = obj.Rend;

    command.SetRenderTarget(mask);
    command.DrawRenderer(renderer, transparentMaterial, 0);

    Graphics.ExecuteCommandBuffer(command);
    command.Clear();
}

}```

#

im making a texture at runtime with PaintObject, assigning it to my object's material, then calling PaintManager to have my shader print to the texture. Although my shader is called transparent, for testing it should be returning only white pixels.

#

for some reason, my cube just goes invisible, and the texture in the inspector just looks black. Any help is greatly appreciated

amber saffron
#

The shader is returning a white opaque value, but the resulting texture is still transparent ?
Possible reasons :

  • The mesh is not projected correctly in the clip space, so it does not render in the texture ? The getvertexpositioninputs transforms from object to clip space, if the object is not in the "camera frustom", it won't render. For your effect you might just want to transform manually the UVs to clip space coordinates
  • Face Culling ?
  • Buffer not executed properly ?
violet pebble
#

Thanks for taking a look at this. Another couple points i just thought of are:

  • Project is in URP, Unity 2021.3
  • When making a material with the shader, it is also transparent unless I change RenderQueue to "Transparent" ie 3000+, then it becomes visible
#

transforming manually sounds like a good idea, I will look into that too

keen cloud
#

I don't know what's the right way to ask this question, but here goes.
Does the frag pass in shaders go through every pixel or through every "block" of the UV?
Like for example if I have a pixelized UV so I can pixelize my screen, where the UV is still the same screen size in pixels, but is chopped up into sections to appear pixelated, does the frag go through every one of those sections or pixel by pixel?

grizzled bolt
#

Mesh with UV scroll is one simple option
If you offset/pan/scroll a texture along UV coordinates, it moves along the mesh
Variance in the UV map coordinates per geometry can you random offsets

keen cloud
#

how do I access an array in a shader?
arr[index] doesn't seem to work or I'm misunderstanding something

...
 for (float i = 0; i < _cc; ++i) {
            float3 diff = abs(p.rgb, palCol[i].rgb);
...

returns "abs: no matching 2 parameters intrinsic function"
palCol is a float3 array consisting with a size of 4

keen cloud
#

ah

#

:|

amber saffron
#

You probably wanted to do abs(a-b)

keen cloud
#

probably

#

I should start proof reading before copy pasting :/

#

absolute taking in two values, lol

#

now it just says cannot convert from float3[4] to float4

#

confusing

#

are there any good sources to actually learn how to code with GLSL? not the logic behind shaders, but like the code docs or something.
every time I try to write a shader there is something new I find, like a "magic" word that I don't know of (like I just recently found out about sampler_point_clamp etc) and it's honestly annoying

amber saffron
keen cloud
#

I made it go abs(a-b)

#
for (float i = 0; i < _cc; ++i) {
            float3 diff = abs(p.rgb - palCol[i].rgb);
            if (length(diff) < length(bestDiff)) {
                bestDiff = diff;
                bestColor = palCol;
            }
        }
amber saffron
keen cloud
#

p is a float4 sampled from the main texture

amber saffron
#

Probably not related to the error, but since i is an index, you should decalre it like a int or even uint

keen cloud
# amber saffron There is a lot of tutorials about shaders in unity, but those constant and macro...

I saw the tutorials and they are great, but they are very specific or try to teach me logic instead of shader code. Maybe it's also a problem with how I learn things? Like with Unity, I knew c++ before starting, so code was easy, but finding the specific functions and stuff was as simple as having a problem and googling how to solve it. With shaders every problem ends up in a rabbit hole of searching every keyword I find under every 3rd forum comment I open. sigh

amber saffron
#

palCol is an array of float4, right ?

#

or float3

#

Could the index be higher than the size of the array ? I don't remember what error is spawn when trying to read out of bounds in shader ๐Ÿ˜…

#

Other useless detail : no need to calculate the absolute value, as your are already calculating the length afterwards. The sings of the component won't affect the length

#

And for a very small optimisation : calculate and compare the square length should be a bit faster, as it doesn't have to do a square root operation

#

And other one ? Don't store the "best diff" but the shortest length, so you calculate it only once and not for each iteration

tight phoenix
#

dumb math question, what is the formula to mask just the values that used to be be bellow 0 before adding that Push of 0.1

#

I want to have all the values from the left be 0 except for where I added 0.1

#

I don't know how to put what I want into words I can only draw that and hope that its not complete nonsense

#

I guess this?

#

hrm not getting what I need from this

#

What is the formula to change the curvature of a gradiant ramp?

#

as in change a linear range to something more like this, maybe chatgpt knows

#

sigmoid maybe

#

struggling to remake that formula in nodes, not sure what x and y are in my case, or F, or what is being exponented

rotund fjord
#

hey i'm pretty new to shader graphs and this is probably a dumb question, i was wondering how can i like extend the base functionality of URP/lit (which i have been using for all my materials) so i don't have to implement the base map/normal map/smoothness etc.. from scratch and only focus to implement the new effects i'm working on ๐Ÿ˜…

regal stag
tight phoenix
regal stag
tight phoenix
#

what I want is to aproximate SSS by adding emission to create fakery of internal light bleed where normally the main light ends and shadow begins

#

everything else is just trying to achieve that

amber saffron
tight phoenix
#

currently looks like shit because the light bleed curve isnt curved right

amber saffron
#

SSS isn't only on the edge of the dark area, it is an effect visible on the whole lit face

tight phoenix
amber saffron
#

let me explain : SSS is the light scattering under the skin surface, and get back out. It happens everywhere the light hits, so consider it is a small emissive effect

tight phoenix
#

I know what SSS is, and this is what happens when emissive is 1 in the light

#

total wash out, this is why it needs to have no emissive on the side hit by light

amber saffron
#

Maybe you did just set it to strong ?
You can just take the NdotL result, add a small push, saturate to avoid negative and >1 values, tweak with the sss color, and plug to emissive

tight phoenix
#

I dont think that a 1 of emissive on the light side is correct, im pretty sure there should be no emissive on the light side because its already recieving light, it shouldnt also emit light

#

double lighting is just going to wash it out

amber saffron
#

But obviously, this is way to intense, you need to dim it down with an sss color & factor

tight phoenix
tight phoenix
amber saffron
#

yes

tight phoenix
#

That is thing I have been trying to do and you said was not neccessary to my understanding?

#

the light side should not be 1, you were saying yes it should now you are saying no it shouldnt in my understanding

amber saffron
#

I understood that you wanted to have the "light facing side" have 0 emission.
What I'm saying is just : take the output of the saturate node, multiply by color and you're good

tight phoenix
amber saffron
#

Let me dig, I made this a while ago, I should have something to compare

tight phoenix
#

here is mine in its current form

#

mult 2 looks good on shadow side, total wash out on light side

#

mult 0.2 looks good on light side, totally imperceptible on shadow side

#

im pretty sure I need some kind of sine or sigmoid over the edge of light and shadow, not a total washout of one side or the other

#

I just can't get the curve right because I cant shape the curve at all because its not a curve its just a linear range of values

#

this very clear "peak" ruins the look, the apex should be soft not sharp

#

but when the peak is soft, the effect is too large, and the falloff on the outer edge is too stark

#

this is what I mean by I need to control the curves and cannot

amber saffron
#

SSS is quite subtle and shouldn't just be a "rim"

tight phoenix
#

Yes I am aware of that, instead of telling me what you think SSS should or should not be, I would appreciate if you'd listen to what I am trying to achieve

#

even if you think I am wrong or doing it wrong or that I have no idea what SSS is, I do know what true SSS is and it is very nontrivial to aproximate

#

How about I just stop saying SSS and say that I just want an emissive rim on the edge of light and shadow

amber saffron
#

๐Ÿ™„ Ok then ...
So you want a smooth rim "around" the edge of the lighting ?
Add what you want to be the "center" of the rim.
Then abs
divide by the width

tight phoenix
#

I wish SG had something like this, a curve node that I could plug a gradient into

amber saffron
tight phoenix
#

this right?

amber saffron
#

You can also author a 1D ramp texture if you wish to

amber saffron
tight phoenix
# amber saffron Yes

gradient version is alright, its only an approximation so its definitely not perfect

#

the dragon mesh is pretty janky but its the most complex thing I have to test with

amber saffron
#

Just for illustration, here is what I got as result for my skin :

tight phoenix
#

Looks alright from the front but it has the same problem mine has from the back, not noticeable.
I think part of the problem is communication; that I am trying to emulate something very small with a strong light behind it, like jade under a lamp and not flesh

#

thats the reason why I am using the dragon mesh because its the only mesh that I have a benchmark for what real raytraced SSS would look like

amber saffron
#

So, you're trying to do transmission ?

tight phoenix
#

I have seen zucconi's tutorial on real time SSS aproximation but I tried multiple times and couldnt get appealing results

amber saffron
#

My reference for wordings here is HDRP, so it might differ from who you are speaking with, but :
IRL the light rays are diffused under the material surface and can either

  • exit out near-ish their entry point : this is SSS
  • traverse the material and exit on the other side : this is transmission
tight phoenix
#

the XY I am trying to solve is that my meshes don't look natural and I think its because irl most materials do not 100% block light transmission and my assumption is that some form of subsurface light scatter is what I am missing
for materials like plastics for example

amber saffron
#

Doing transmission "easilly" can be achieved by :

  • calculating the world space entry point of the light: use the shadowmap value of the current pixel to estimate it
  • calculating the distance traveled in the material : simply the distance of the previous point, and the current pixel position
  • apply some attenuation and output this in the emission slot
tight phoenix
#

I am not aware of any method to get the depth of a mesh from one side to the other in scene

amber saffron
#

IT's not raytracing.
Liek I said, your approximate the thickess by comparing the current pixel world pos with the shadowmap

tight phoenix
tight phoenix
tight phoenix
amber saffron
keen cloud
tight phoenix
keen cloud
#

I just have no idea how to execute what I want.
-get the pixel from maintex
-see if the pixel's color fits in a certain range
-index it
-change that pixel's color to a color in a palette using the index
-return it

#

the 2nd and the 3rd part are probably what's messing with my brain that much
and getting errors at the 4th :/

amber saffron
#

So, how do you want to do the "the color fits in a certain range" part ?

lunar valley
#

(just for curiosity)

tight phoenix
tight phoenix
#

those are what I am comparing mine against

tight phoenix
lunar valley
#

and how are you doing it?

keen cloud
#

okay now that I think about it more

#

I think i realize how impossible it is

#

from just the camera's view

amber saffron
lunar valley
keen cloud
#

yes if I use materials, right? I can't make a post processing effect that does that

amber saffron
#

One VERY easy way is to do color grading with a look up texture

#

There are already post processes for this ๐Ÿ˜„

keen cloud
#

there are?

#

like, in the post processing stack v2? or in the urp one?

amber saffron
#

both iirc

keen cloud
#

so, I should just use color grading? and make it very "steppy"?

amber saffron
#

The working of the lookup texture is extremely simple :

  • The input pixel color value is interpreted as a normalized vector. aka : rgb = xyz in the [0;1] range
  • It will be used to sample in the 3D lut as uvw coordinates
  • Outputs the sampled value
#

If you use a low res neutral LUT, without pixel interpolation, you'll have a limited colour ouput

tight phoenix
keen cloud
#

but wouldn't that result to everything being locked to those colors? that's why i thought it was impossible.
it will be a global let's say 4 colors. I want to retain the colors but have the transition between light and dark to be choppy
sort of like cel shading, but "global", or screen based

amber saffron
#

If you REALLY just want to step the color values, it can also be done very simply like that :

float4 pixel = tex.sample(...);
pixel *= numberOfSteps;
pixel = round(pixel);
pixel /= numberOfSteps;
return pixel;
keen cloud
#

I think I came to a conclusion, I'll use materials, because it makes no sense for unity to render out the diffuse shader and then have pp effect make it look like cel shading
sounds like unecessary steps

#

thanks for the help tho!

amber saffron
#

Oh, sorry, I didn't register this part :

I want to retain the colors but have the transition between light and dark to be choppy

Well, yep, this is custom lighting. Mostly cell shading.

lunar valley
lunar valley
tight phoenix
lunar valley
tight phoenix
lunar valley
tight phoenix
lunar valley
tight phoenix
lunar valley
# tight phoenix Yeah

thats cool, once you are done can you then share a side by side comparison of all the SSS shaders you made? I would find that interesting

tight phoenix
nova needle
keen cloud
#

is the only way to change a camera's depth texture mode through a script?

#

i feel like that could be a dropdown

amber saffron
#

Since those textures are mostly used for effect and passed as shader variables through script, it makes sense to have the setting accessible only with scripting

oak aspen
#

I have a simple shader that basically reveals a texture based on a slider. This is being used for a UI image. however, the texture isn't showing perfectly straight...it's like bulging out (no other way to describe it lol). The green part is the texture I'm revealing and this is the shader... anyone has any idea how i can flatten out / make that texture straight ?

keen cloud
nova needle
amber saffron
keen cloud
#
public override void OnEnable()
    {
        Camera.main.depthTextureMode = DepthTextureMode.DepthNormals;
        ...
    }
#

oh it actually does now

#

it needed some time I guess?

keen cloud
#

I'm losing it to shaders so much

#

I can feel my brain matter fade away

#

why is there 2 ways to "use" the samplers

#

SAMPLE_DEPTH_TEXTURE();
tex2D();
both work

#
 sampler2D _CameraDepthNormalsTexture;

            fixed4 frag(v2f i) : SV_Target
            {
                float4 depthnormal = SAMPLE_DEPTH_TEXTURE(_CameraDepthNormalsTexture, i.uv);
                float depth;
                float3 normal;
                DecodeDepthNormal(depthnormal, depth, normal);
                float4 col = float4(normal, 1);
                return col;
            }

and why does this return a black screen

#

shaders really feel like magic

#

in the worst way imaginable

lunar valley
keen cloud
#

Camera.DepthTextureMode = DepthTextureMode.DepthNormals?

#

yea i did

#

and I did use tex2D aswell

#

neither return an error

#

but neither work

#

also I'm trying to display normals just to see if the decoding even works

lunar valley
#

do this in c-sharp cs cam.depthTextureMode = cam.depthTextureMode | DepthTextureMode.DepthNormals;

keen cloud
#

not like that, but I did

lunar valley
#

ok

lunar valley
keen cloud
#

yes, built in.

#

it's a post processing effect

lunar valley
#

what happens if you return depthnormal?

keen cloud
#

I'm assuming I have to use the _LastCameraDepthNormalsTexture

lunar valley
#

uh not really

keen cloud
#

still a black screen

lunar valley
# keen cloud still a black screen

if depthnormal is a black screen then your problem starts there, the only thing I could think of is that you are not rendering the depthnormals or your uv's which you use to sample the texture is flopped

keen cloud
#

Oh I think I found the problem

#

and I have no idea what to do about it

lunar valley
#

ok?

keen cloud
#

if I disable my other custom pp effect, it works

#

I mean

#

doesn't really work

#

just doesn't display anything

#

anything new I mean

#

it's not black, but obv doesn't show the depth or normals

safe ravine
#

How do I debug a frame on MacOS?

lunar valley
keen cloud
#

now both are off

#

wait no

lunar valley
#

?

keen cloud
#

the "buggy" one is on

#

this is with just the pixelization one

lunar valley
#

can you just disable all of the pp shaders except your depthtexture shader, so that we can see if it then works

keen cloud
#

this is with just that shader

#

oh

#

it just turned black again

#

and back to normal

#

I didn't touch anything what

#

now it's stuck at black

lunar valley
#

where are you doing this: cam.depthTextureMode = cam.depthTextureMode | DepthTextureMode.DepthNormals;? at start?

keen cloud
#
Camera cam;
    public DepthTextureMode depthTextureMode;
    private void OnValidate()
    {
        cam = GetComponent<Camera>();
        cam.depthTextureMode = depthTextureMode;
    }
#

I do it on validate

lunar valley
#

eh, try putting it in start and hit play

keen cloud
#

why?

#

the camera works

#

can change it easily

#

this is obviously not intended way of working

lunar valley
# keen cloud why?

well if thats how you sample your texture and you are also rendering it: ```cs
sampler2D _CameraDepthNormalsTexture;
fixed4 frag(v2f i) : SV_TARGET{
//read depthnormal
float4 depthnormal = tex2D(_CameraDepthNormalsTexture, i.uv);

return depthnormal;

}``` then I am not sure, the second option is that your uv's aren't right but I would doupt that

lunar valley
keen cloud
#

i'm only moving my mouse lol

#

I'm going to sleep this is crazy

lunar valley
# keen cloud

just try putting the activation of the depthnormal inside of the start function..

safe ravine
native garnet
#

I am really curious if it's possible to do an outline effect using just the ShaderGraph in hdrp; I was looking for a sobel method using the scene depth node

vestal ice
#

i made a shader but for some reason the slider i made controls all the elements will shaders, how do i make it so it does not do this?

tardy warren
#

Hello !
I have some trouble understanding depth sorting inside a DrawProceduralIndirect command. I have a bunch of brush strokes generated from a ComputeShader in a ComputeBuffer that need to be rendered in screenspace (fullscreen effect). Each strokes are composed of at least 2 triangles, and every triangles that compose a stroke have the same depth). I have achieve it by using a DrawProceduralIndirect command and it works, but it seams that triangles are rendered in a random order without using the depth (encoded as the z position), so I completely loose the brush aspect.
Is it possible to sort instances inside a single draw call using a depth value?
I hope my description is clear. Thanks !

tacit palm
#

i want the triangle to rotate over lifetime to the left, what setting do i need in the graph ?

lunar valley
tardy warren
neat snow
#

Quick question, probably an easy one:
I'm following a tutorial for 2D Fog:

Basically I'm stuck with the last node: It seems like there was a color-input in the "Sprite Unit Master", but I don't have this anymore.
It seems like in the past 2 years, this got replaced with something new:

Howver, if I now connect my out from multiply with Base-color under Fragment, I don't get any result. What am I supposed to do here?

#

ah, it seems like there are now 2 contexts, maybe I can split it

#

even if I add "alpha" to it, it doesn't work. If someone has an idea, I'm all open

lunar valley
#

he is using an unlit shader you aren't

neat snow
#

that rights, he said in the tutorial "if you want to have a lit shader, so it is affected by light, go with that"

#

I thought that would be the same then

lunar valley
#

what I would guess is that the object is not being illuminated so that is why its black

neat snow
#

so the problem is actually that only my preview is not showing up, so that might be black. Up to the multiply-part, it seems to work

#

funny, if I change it to "sprite lit" it works

lunar valley
neat snow
#

I think so ๐Ÿ™‚ thank you for pointing that out with lit/unlit

sudden mountain
#

Is there a way that I can have a gradient as a variable in my shader? (non-shadergraph)

umbral hemlock
sudden mountain
#

just using a gradient texture would work just as well yeah, good idea.
now could I then sample that texture's color by doing the following?

float4 color = SAMPLE_TEXTURE2D(_GradientTexture,sampler_GradientTexture,float2(gradientValue,0.5));
#

I am rather new to writing shaders

umbral hemlock
#

Yeah I think so. The syntax might be different depending on what library youโ€™re using but you can just sample it like a normal texture. Just use an x value between 0 and 1 and it should interpolate the result (as long as the texture filter isnโ€™t set to Point).

sudden mountain
#

Great, thanks for the help!

vestal ice
# lunar valley wdym

like how do i make the custom properties different for each game object i use the shader for

lunar valley
vestal ice
#

ugh

#

so is there no other way?

grizzled bolt
# vestal ice so is there no other way?

Material property blocks are one option
Though in URP/HDRP it's better in most cases to allow material instances to be created instead
Whenever you access material properties in a script it automatically produces one

thick chasm
#

What am I doing wrong?

#

Why is unity saying there is no color property when there is?

compact adder
#

hey guys, does anyone have a good VHS shader that actually looks realistic? the most shaders or assets i see are pretty good, but donโ€™t really โ€œsimulateโ€ the vhs look. i mean like with color sharpness and bleeding

vivid marten
#

Can someone explain this to me? When I use my custom material the edges of the sprite looks really weird

grizzled bolt
vivid marten
#

but connecting my texture to the alpha output doesn't help either

#

I also noticed it looks different when I run the game somehow

#

is this what you mean?

grizzled bolt
vivid marten
#

omg it looks so pretty

#

I did this

#

ty!

#

also I noticed my game looks more pixelated in debug mode than in the editor

#

also really weird

#

I guess it's the zoom out thing ๐Ÿค”

grizzled bolt
#

"Debug mode" in this context?

vivid marten
#

I will send you another video lol

#

but this may not be about shaders tho

distant dirge
vivid marten
#

looks like the pixels are glitching

neat snow
#

Hey mates,
another question, probably simple, but yet here I am:
I created a shader, which I did by following a tutorial. I think I managed to convert it from unlit to lit (at least my preview is correct).
Now I want that this shader (or more like the sprite) is affected by my light source (2d URP): It works with other sprites, but not with the dynamic material.
Can someone give me a hint?

I'll provide some screenshots:
as you can see, my player is affected by the yellow light, my fog isn't. I really have no idea where to start
There are color-nodes and I'm able to change the color of the fog via the color-pickers, but not "dynamically", so they fade to yellow'ish when they are in the light-source

grizzled bolt
# vivid marten looks like the pixels are glitching

How things look in scene window doesn't ultimately matter much
Unity doesn't resample images or sprites when they're viewed at different scales, instead they're swapped out for different mip map levels that fit the closest
To reduce shimmering, make sure Generate Mip Maps is enabled for the texture, and if you want blurring instead of pixelation when data is insufficient set the Filter Mode to Bilinear instead of Point
Still, even with mip maps only integer scales will be displayed with minimal distortion
Non-integer scales will blend two nearest mip map levels, afaik, which is why they look worse
This is only a necessary concern if your game camera will be viewing the sprites at different zoom levels
There may also be shaders out there that implement image/sprite anti-aliasing, the lack of which is what causes this problem

vivid marten
#

aha

#

it made a big difference with Generate Mipmaps enabled

#

and I think I should have anti-aliasing turned on

neat snow
#

I think there is something I'm missing, as if there is a node for a shader, which allows it to be affected by light / color, outside of the shader itself

grizzled bolt
vivid marten
#

not sure what you mean by AA and FXAA

#

I have this on at least

#

oh AA as in anti aliasing

#

but what is FXAA?

neat snow
#

Anyone an idea in regards to my shader problem? Is it even the shader I need to adjust? I guess I can't have 2 materials?

grizzled bolt
neat snow
#

got it - all I had to do was checking Double Sided global Illumination

wicked niche
#

And what is an easy way to make liquid in a bucket for mobile phones? as a rule, the liquid level in the tank should increase and with an increase / decrease in water, the effect of waves should be small from above

neat snow
#

Can someone say me, why I made a complete new shader but I don't have a preview at all?

#

I did one shader before and everything was there. Now I don't see anything, regardless of the output type (custom mesh, cube, sphere...)

#

(Material: Lit) - I figured it has something to do with that

regal stag
#

If you're referring to Shader Graph's Main Preview, it seems to be a new bug with the opaque mode. Just save the graph and use the scene view to preview it instead

neat snow
#

lets try that then. Following a pretty nice tutorial from Brackeys, but it seems outdated

#

yeah, the scene preview works

full loom
#

Brackeys might be pretty outdated for shader graph considering urp is constantly changing and brackeys doesn't make videos anymore. Idk though.

neat snow
#

Yeah I figured. What a shame though. This is exactly the effect I wanted to create but it seems that I can't do it following this tutorial

lunar valley
#

I stopped relying on the preview a long time ago

neat snow
#

The problem is, that I know the preview gave me some results. In the scene view it is very laggy

#

During play it is fine

terse verge
#

In the game Children of Morta, when certain sprites are obstructed by the terrain they are rendered as solid colors overlaying the obstruction. I'd like to add something like this to our game, but am unsure how it is accomplished. Can anyone point me in the right direction or what the name of technique is? Thanks.

regal stag
neat snow
#

oooh

#

that makes things easier

terse verge
# terse verge

I feel silly, "Always Visible" is giving me good info on the technique--nevermind ๐Ÿ™‚ !

neat snow
#

can I actually have 2 materials for one sprite?
for example, right now, with the default material, this sprite is affected by light.
However, the shader isn't and if I want it to dissolve (what the shader does), can I apply a 2nd material for that?

tight phoenix
amber saffron
violet pebble
#

Hello again, I'm having trouble understanding how clip space works and how to manipulate it. My goal is to create a shader that, when applied to an object in the scene, will render the uv texture map of the object to the screen like a ui overlay. Does anyone have an idea of how to do this? I have tried setting the values of the v2f vertex in many variations of float4(v.uv0.xy, 0, 1) etc, but that results in just invisibility so far. I'm testing on basic unity shapes like quads, cubes, sphere etc

fervent flare
#

Is this the right way to use the reflection probe node in shadergraph? Or do I need to hook something up to the viewdir and normal inputs ?

regal stag
hollow wolf
#

Is there a node to turn off zwrite in the shader graph?

grizzled bolt
hollow wolf
#

*unity

regal stag
normal cape
#

is there any way i can pass a dictionary into a compute shader?

violet pebble
#

Is there any way to set vertex positions to screen space positions?

normal cape
#

o.screenPos = ComputeScreenPos(o.vertex); ?

violet pebble
#

i mean given an xy coordinate between -1 and 1, or whatever range, set the vertex to be at that position in screenspace

normal cape
#

that would already be in screen space i think

violet pebble
#

ie if I had the coordinates (0, 0), i want to render that vertex at wherever would correspond to the bottom left of the screen

normal cape
#

you're talking uv coordinates

violet pebble
#

yeah

#

i want the shader to render the uvs flat, treating the screen as a texture

#

so the shader would essentially unwrap the uvs

normal cape
#

i think you can put float4 screenPos : TEXCOORD1; in your v2f struct and it fills it out or something

#

or maybe then in the vertex function

violet pebble
#

instead of SV_POSITION?

normal cape
#

you set the screenPos to computescreenpos(o.vertex)

#

its a uv coordinate not a vertex so you use texcoord

violet pebble
#

I don't want the uv of the mesh in camera view, i want sort of the other way around

#

i want to use the object's uv coordinates to draw to the screen

#

So i have float2 uv0 : TEXCOORD0 in my appdata struct, then I want to use that to set the float4 vertexCS : SV_POSITION; in v2f so that what I see on the screen is the uv map rendered flat

normal cape
#

i am so confused that doesnt make sense to me. sorry xd

violet pebble
#

you know the how a mesh has a uv map?

#

like for a cube, it would be a t-shape of each side of the cube if the cube was unwrapped?

normal cape
#

yeah

violet pebble
#

i want a shader that, if i put it on the cube, i will see the t-shape uv map on the screen like an overlay on the camera

#

so each vertex in the cube has a uv coordinate

#

i want to draw the vertex to the screen using the uv coordinate in screen space

#

so if one vertex of the cube is mapped to 0,0 uv, then i want the shader to draw it in the bottom left of the screen, etc

normal cape
#

I think i understand. So say you are drawing a cube that is about in the center of the screen. Your shader will draw it in the bottom left corner of the screen?

violet pebble
#

I can't understand clip space at all though ๐Ÿ˜ฆ i've been trying so many things and most of them just make the object stop rendering, i have tried tweaking all the values of the clip space position but i can't figure out how to work

#

oh okay so

#

the shader does not depend on the cube's position at all

#

world position does not matter

normal cape
#

i know but does the shader like draw the cube in the bottom left corenr of the screen?

violet pebble
#

if i am drawing a cube, i should see its uv map on screen as if like i had the uv map texture printed out and glued to the screen

#

yeah it would draw a row of 3 cubes along the bottom, and 3 more out the top of the middle cube

normal cape
#

so you are just drawing the uv map to the screen?

violet pebble
#

yeah

normal cape
#

okay. so you need to get the uv map as a texture and then render that out?

meager pelican
normal cape
#

not at all go ahead ๐Ÿ™‚

meager pelican
#

I don't want to interrupt...

#

OK

violet pebble
#

I want to make a painting shader, so given a point in world space, the shader will then take every fragment, calculate the distance from the paint point, and if its in range, change the color to red.

meager pelican
#

So the vertex shader stage MUST output the verts in clip space.

violet pebble
#

I want the shader to render flat like uvs, so if i take a fragment's world position and decide to color it in, it will draw the color change in the correct spot on the texture

#

so if i apply the texture to the material with another shader, it will show up as paint

#

sorry if this is very confusing

meager pelican
#

X, Y for clip space is going to range from -1 to +1 with 0,0 being the center

violet pebble
#

yeah, ๐Ÿ˜ฆ let me show you my code

#
{
    Properties
    {
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

            struct MeshData
            {
                float4 vertexOS : POSITION;
                float2 uv0 : TEXCOORD0;      // uv coordinates channels
            };

            struct Interpolators
            {
                float4 vertexCS : SV_POSITION;
                float2 uv : TEXCOORD1;
            };

            Interpolators vert (MeshData v)
            {
                Interpolators o;
                float4 uv = float4(0, 0, 0, 1);
                uv.xy = float2(1, _ProjectionParams.x) * (v.uv0.xy * float2(2, 2) - float2(1, 1));
                o.vertexCS = uv;
                o.uv = v.uv0;
                return o;
            }

            float4 frag(Interpolators i) : SV_Target
            {
                float4 col = float4(1,1,1,1);
                return col;
            }
            ENDCG
        }
    }
}```
#

thats what i thought, i thought I could just change the uvs into clip space like above, at a distance of 1 it should just render flat? is what i thought

#

but nothing renders

#

and I tried stuff like trying to render the clip space position as a color in the fragment shader to understand what values the clip space is using

regal stag
#

This looks fine to me. Though it might be culled if too close to the near/far clip planes maybe - could try other z values.
You should also specify Cull Off in the Pass, as depending on the uv mapping the triangles could be backwards.

violet pebble
#

Oh thank you i didn't think of Cull off, I tried doing that and something happened? the screen still does not render anything, but in the inspector the material now shows a white color rather than transparent

#

this is in URP 2021.3 btw

#

if that matters

meager pelican
#

Well, that's not quite how to do that (I think) but let's talk some quick tips first.
one, you don't need to construct float2(2,2) for example, or float2(1,1)...
you can use constants and the compiler will multiply all vector elements by that constant.
so you can say float2 foo = float2(something, else) * 2 - 1

#

But secondly...

#

The z stuff can be different on different platforms.

violet pebble
#

OH

#

I added a property at the top to control the z

#

and scrolled it along, something is rendering now when z is between 0 and 1!

#

its working ๐Ÿ˜„ thank you so much i was ready to pull all my hair out and become a hermit

meager pelican
#

From https://docs.unity3d.com/2021.1/Documentation/Manual/SL-PlatformDifferences.html


Similar to Texture coordinates, the clip space coordinates (also known as post-projection space coordinates) differ between Direct3D-like and OpenGL-like platforms:

    Direct3D-like: The clip space depth goes from 0.0 at the near plane to +1.0 at the far plane. This applies to Direct3D, Metal and consoles.

    OpenGL-like: The clip space depth goes from โ€“1.0 at the near plane to +1.0 at the far plane. This applies to OpenGL and OpenGL ES.

Inside Shader code, you can use the UNITY_NEAR_CLIP_VALUE built-in macro to get the near plane value based on the platform.

Inside script code, use GL.GetGPUProjectionMatrix to convert from Unityโ€™s coordinate system (which follows OpenGL-like conventions) to Direct3D-like coordinates if that is what the platform expects.```
#

So that macro will save your butt.
Try using that for the z value first. IDK if it will be distorted on the edges of the screen or not.
But x and y will range from -1 to 1 (at the near plane, with the .w component at 1 as you have it in code above).

violet pebble
#

i did! the UNITY_NEAR_CLIP_VALUE works

#

thank you so much

meager pelican
#

Squishing things toward the center of 0,0 with the perspective divide.

#

You're welcome.

meager pelican
# normal cape pls tell me

A dictionary is a storage technique/data structure. But what it contains can vary. What's IN the dictionary?

normal cape
#

key is Vector3Int but can be just vector or int3, value is int

#

i have a 3d grid of voxels but stored as a dictionary that i am trying to pass to a compute shader. The dictionary is just the positions of the voxels and an integer for the type

meager pelican
#

you're partitioning 3D space?

#

Maybe consider a BVH type of tree structure.

#

It's an acceleration structure used to speed up searches in 3D space by bounding volume (e.g. world space grid coordinates)

normal cape
#

my project is kindof like minecraft or teardown.

meager pelican
#

So the dreaded "v word"...
There's got to be a lot of info on partitioning voxel space in shaders. But it's not something I do much of, I mean...whenever I hear the words "voxel" or "minecraft" I run the other way as fast as I can! But that's ME.

normal cape
#

i already made a prototype of the voxel world but it is slow

#

i am just trying to move my code over or at least parts of it onto the gpu

tight phoenix
meager pelican
tight phoenix
#

Something related to these?

meager pelican
#

That map would likely be some kind of tree structure. Octtree or whatever, but the more "modern" technique that I'm aware of is to use a BVH tree. Something to google.

normal cape
#

okay thanks

meager pelican
# normal cape okay thanks

So you're looking for examples of a structured buffer, and for code for reading a tree structure built into that buffer data, without being able to run on a device that supports recursion. So you need to implement your own software stack and recurse down the tree until you find your element (or not).

normal cape
#

alright

meager pelican
#

I've done it before with ray-tracing, but not with voxel space.

#

It is doable.

tight phoenix
#

This is doing a neat thing but I dont think its doing the thing I want.
A person here said you can find out how thick something is by comparing the position of a pixel to the position of a pixel in the shadowmap from the main light source
To aproximate thickness for light transmission fakery.

#

but they did not clarify how its done and I don't have enough knowwledge to solve it myself, googling it I cant even find out what a light projection matrix is

#

this stops working as soon as I move it away from 000 and it doesnt work at all with local positions

#

im stumped

#

distance between shadows and scene depth produces interesting results ๐Ÿ‘€

#

hm it was only doing that cool thing because the mesh itself was jank

#

I am not sure how I am supposed to aproximate depth with any of these

#

since the shadow side of a mesh is just black, there's no data there, and the light side is just white as well

#

if its not making shit up maybe this will point me in the right direction ๐Ÿค”

tight phoenix
#
float4 worldPos = mul(unity_ObjectToWorld, v.vertex);
float4 lightPos = mul(unity_WorldToLight, worldPos);

// Transform light position to clip space using the light projection matrix
float4 clipPos = mul(unity_4LightMatrix, lightPos);

// Do lighting calculations using the transformed clip space position
...```
#

what are the equivalent of these in SG URP?

#

I tried asking GPT but it just keeps giving stuff that can only be used in a written shader

amber saffron
# tight phoenix What exacty is a light projection matrix? I tried to google it but it got into o...

Not on my PC now, but I remember I stole @regal stag light code and this function to get the shadow "position" https://github.com/Cyanilux/URP_ShaderGraphCustomLighting/blob/main/CustomLighting.hlsl#L111

GitHub

Some custom lighting functions/sub-graphs for Shader Graph, Universal Render Pipeline - URP_ShaderGraphCustomLighting/CustomLighting.hlsl at main ยท Cyanilux/URP_ShaderGraphCustomLighting

solar furnace
#

why is the output of the shader nothing when i have set my asset and the base color is set

grizzled bolt
native garnet
#

any help with this error please? Shader error in 'Shader Graphs/Outline': undeclared identifier '_CameraDepthTexture_TexelSize_x' at Assets/Shaders/HLSL/Outline.hlsl(17) (on d3d11)

#

I include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" where cameraDepthtexture is supposed to be in hdrp, but why the texelsize propery doesnt work

regal stag
native garnet
#

isn't this property supposed to work magically for all textures?

#

I am trying to make a sobel outline for each object

#
#define MYHLSLINCLUDE_INCLUDED

#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"

void Outline_float(float2 UV, float OutlineThickness, float DepthSensitivity, float NormalsSensitivity, out float Out)
{
    float halfScaleFloor = floor(OutlineThickness * 0.5);
    float halfScaleCeil = ceil(OutlineThickness * 0.5);
    
    float2 uvSamples[4];
    float depthSamples[4];
    float3 normalSamples[4];

    uvSamples[0] = UV - float2(_CameraDepthTexture_TexelSize.x, _CameraDepthTexture_TexelSize.y) * halfScaleFloor;
    uvSamples[1] = UV + float2(_CameraDepthTexture_TexelSize.x, _CameraDepthTexture_TexelSize.y) * halfScaleCeil;
    uvSamples[2] = UV + float2(_CameraDepthTexture_TexelSize.x * halfScaleCeil, -_CameraDepthTexture_TexelSize.y * halfScaleCeil);
    uvSamples[3] = UV + float2(-_CameraDepthTexture_TexelSize.x * halfScaleFloor, _CameraDepthTexture_TexelSize.y * halfScaleCeil);

    for (int i = 0; i < 4; i++)
        depthSamples[i] = SHADERGRAPH_SAMPLE_SCENE_DEPTH(uvSamples[i]).r;

    float depthFiniteDifference0 = depthSamples[1] - depthSamples[0];
    float depthFiniteDifference1 = depthSamples[3] - depthSamples[2];
    float edgeDepth = sqrt(pow(depthFiniteDifference0, 2) + pow(depthFiniteDifference1, 2)) * 100;
    float depthThreshold = (1 / DepthSensitivity) * depthSamples[0];
    edgeDepth = edgeDepth > depthThreshold ? 1 : 0;

    Out = edgeDepth;
}
#endif //MYHLSLINCLUDE_INCLUDED
#

this is what I have so far, but seems I can't get the texel size

#

this is the shadergraph I am using; basically I multiply the value of the outline to a color (the color of the model)

regal stag
# native garnet oh, yes; thank you, I didn't see that; but now it throws undeclared identifier ...

HDRP doesn't seem to be declaring that variable. Not sure why, maybe it doesn't exist. Could try defining it yourself like float4 _CameraDepthTexture_TexelSize; before the function but might break SRP batcher compatibility.

Seems that ShaderVariables.hlsl has these functions

float LoadCameraDepth(uint2 pixelCoords){
    return LOAD_TEXTURE2D_X_LOD(_CameraDepthTexture, pixelCoords, 0).r;
}

float SampleCameraDepth(float2 uv){
    return LoadCameraDepth(uint2(uv * _ScreenSize.xy));
}

So maybe you can use LoadCameraDepth(uint2(uv * _ScreenSize.xy)) multiple times with additional + uint2(1, 1) / + uint2(-1, 1) / + uint2(-1, -1)/+ uint2(1, -1)?
Or keep using sample but add float2 based on (1/_ScreenSize.xy) which should be equivalent to the texel size?

native garnet
native garnet
regal stag
native garnet
#
#define MYHLSLINCLUDE_INCLUDED

#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"

void Outline_float(float2 UV, float OutlineThickness, float DepthThreshold, float NormalsSensitivity, out float Out)
{
    float2 uvSamples[4];
    float depthSamples[4];

    float2 texelSize = OutlineThickness * (1 / _ScreenSize.xy);
    uvSamples[0] = UV + float2(texelSize.x, texelSize.y);
    uvSamples[1] = UV + float2(-texelSize.x, texelSize.y);
    uvSamples[2] = UV + float2(-texelSize.x, -texelSize.y);
    uvSamples[3] = UV + float2(texelSize.x, -texelSize.y);

    for (int i = 0; i < 4; i++)
        depthSamples[i] = SHADERGRAPH_SAMPLE_SCENE_DEPTH(uvSamples[i]).r;

    float depthFiniteDifference0 = depthSamples[1] - depthSamples[0];
    float depthFiniteDifference1 = depthSamples[3] - depthSamples[2];
    float edgeDepth = sqrt(pow(depthFiniteDifference0, 2) + pow(depthFiniteDifference1, 2)) * 100;
    edgeDepth = edgeDepth > DepthThreshold ? 1 : 0;

    Out = edgeDepth;
}
#endif //MYHLSLINCLUDE_INCLUDED
``` I modified it like this, but nothing changes; no error and the model is full base color
#

thickness changes nothing and DepthThreshold acts weird: any value over 0 changes nothing, and negative values gives a weird looking effect (only on negative values edgeDepth seems to be 1)

#

the closer I get to the model, the whiter the screen gets

regal stag
#

I assume the previous setup with the texelSize should work too, if you do float2 _CameraDepthTexture_TexelSize = (1 / _ScreenSize.xy); before setting the uvSamples

native garnet
#

I tried to connect the roberts sample output directly to the fragment base color, it should output 1 on edges and 0 on non-edges; with negative threshold it outputs 1, so the model is fully white which is good, but a positive threshold seems to be outputting the depth value, not 0

#

which is weird because I can't see how Out can be different then 0/1 : ``` float edgeDepth = sqrt(pow(depthFiniteDifference0, 2) + pow(depthFiniteDifference1, 2)) * 100;
edgeDepth = edgeDepth > DepthThreshold ? 1 : 0;

Out = edgeDepth;```
#

is there some weird thing I'm missing

#

even setting Out to 0 manually produces the same weird effect

regal stag
native garnet
#

yes, each time

#

this seems to happen when I assign black color to the fragment base color

#

this is enough to break the scene :); it's an unlit graph btw

regal stag
#

It might be something specific to HDRP. I think there's an auto-exposure thing?

#

Might be set to automatic, which means as you look at dark objects, everything else gets over exposed to simulate the eye adapting to the lighting level

native garnet
#

you are right; omg, thank you so much! I wouldn't have thought of this; exposure was turned on in hdrp settings and in hdri sky as well

tight phoenix
regal stag
tight phoenix
#

got it out without error after initializing it

#

interesting and soft

regal stag
#

How you actually use the shadowCoord and shadowmap value to actually calculate the world pos as Remy is describing, I'm not sure. ๐Ÿ˜…

I guess it's like a depth map, so maybe XY from shadowCoord, Z from ShadowAtten, W as 1. And transform back to world with the inverse of the light matrix? Not sure Unity gives us that.

tight phoenix
#

ah right the light matrix

#

that was the next bit ๐Ÿ‘€

#
worldPos = mul(unity_ObjectToWorld, pos);
lightPos = mul(unity_WorldToLight, worldPos);

// Transform light position to clip space using the light projection matrix
clipPos = mul(unity_4LightMatrix, lightPos);

// Do lighting calculations using the transformed clip space position
...```
gpt gave me this but these arent URP compatible
#

darn no 4light or light matrix in your customLighting.hlsl, that'd be too easy

regal stag
#

Well TransformWorldToShadowCoord is using

float4 TransformWorldToShadowCoord(float3 positionWS){
#ifdef _MAIN_LIGHT_SHADOWS_CASCADE
    half cascadeIndex = ComputeCascadeIndex(positionWS);
#else
    half cascadeIndex = half(0.0);
#endif

    float4 shadowCoord = mul(_MainLightWorldToShadow[cascadeIndex], float4(positionWS, 1.0));

    return float4(shadowCoord.xyz, 0);
}

So I imagine you need _MainLightWorldToShadow[cascadeIndex]. But that's to convert from World->Light space? If you're calculating a world pos from the shadowmap I imagine you'd need the inverse? Probably a way to calculate the inverse from that matrix.

tight phoenix
#

Matrix math is definitely beyond my current comprehension, but I am tryin to learn UnityChanCheer

regal stag
#

I really feel like I'm making this up as I go along though. You may want to ask & wait until Remy describes it more

tight phoenix
#

Thats fair

regal stag
#

I am curious to try it though, so I'll let you know if I get anything close

tight phoenix
#

The intended output was to somehow derive mesh depth from the difference between the current surface pixel and something to do with the shadow on the backside, to produce transmission

#

which itself was XY to make some kind of pleasing looking faux SSS

#

this is a blender render so itll never look this good but thusfar the other SSS tutorials like the fast mobile one or zucconi's one didn't produce results I felt were good enough (likely because I might have borked the implimentation of them)

#

this is alright but definitely doesn't hold a candle to the above

hollow tundra
#

Using the shader graph, is there something for edge detection? Like on a big angle (example of 70+degrees), you can do something? Im using 2019.3.15 HDRP

mossy mortar
#

Like changing material when the shader detects an edge?

#

I guess you're using hdrp 7.4.3?

hollow tundra
#

yeah blushie

regal stag
mossy mortar
regal stag
hollow tundra
#

Fresnal is like a outline thing only or?

#

Thats what ive seen so far

mental bone
mental bone
#

I only found the shader not the actual render pass

#

It seems too simple

tight phoenix
#

No console error that's a good sign, now to try to use it for something to make sure its actually there
(googling how to even use matrix maths)

regal stag
tight phoenix
#

it did a thing on play ๐Ÿ‘€

regal stag
#

Might need the matrix in the first port

tight phoenix
#

oh yeah it did a different thing

regal stag
#

I'd also put the result through a Fraction node temporarily, that should help with visualisation

tight phoenix
#

๐ŸŒˆ

#

in world instead of object

regal stag
#

I think instead of the position node we want to try the shadow coord with z value changed to the value from the shadowmap

tight phoenix
#

pure teal if I bypass the fraction, but frac shows there's definitely data there

#

Im at the 'wait for Remy' stage, I have the data but I deffo don't have the knowedge to make use of it yet ๐Ÿ‘€

regal stag
# tight phoenix Like so?

The problem is the ShadowAtten isn't correct. The sampling functions in Shadows.hlsl use SAMPLE_TEXTURE2D_SHADOW/textureName.SampleCmpLevelZero not a regular sample. It's like a "Sample->Step node", but we need the value before that step/comparison.

tight phoenix
#

Is that info one of these?

regal stag
#

It would be in the MainLightShadow() and MainLightRealtimeShadow(), which calls SampleShadowmap(). Gotta copy those functions and tweak it.

tight phoenix
regal stag
#

Okay after checking Shadows.hlsl, I think it might just be float shadowMapDepth = SAMPLE_TEXTURE2D(_MainLightShadowmapTexture, sampler_LinearClampCompare, shadowCoord.xy);

tight phoenix
#

im guessing its a unity function being invoked and not something you wrote

regal stag
#

Yea

#

You may want to put this in a separate function rather than editing MainLightShadows one

#

If you installed it via package manager probably also want it in a separate HLSL file in assets as the package stuff might be overidden if updated.

tight phoenix
#

Oh okay, not an extentsion of customLighting but its own thing

tight phoenix
#

Like this?

#

now to solve all the mistakes I made

#

sample no matching 2 param intrinic method hmm

#

I am far far far beyond my depth atm

#

oh okay I want SamplerState even though its not blue

#

hm cannot convert from struct texture2D to texture2D

#

ah UnityTexture2D

grizzled bolt
#

Can you thread this? Seems pretty involved

tight phoenix
#

Uhhh I don't appear to have the permissions to make a thread, or I am blind which is more likely

#

@regal stag dunno if you can see inside the thread but I am in here now

neat snow
#

hey mates, I have a pretty weird question: how do I really get started with shaders? Like, I know what I want to achieve, which is probably one of the most simple things: a water (or lava) shader, which makes a sprite feel "fluid". I'm pretty sure there are a dozen of tutorials for 2D and doing so, but if I want to get there on my own to actually learn stuff instead of blindly copying, how do I approach it? How do I know which component of a shader makes the top wavy?

shell wing
#

I would still suggest that you watch a couple tutorials for that specific effect. Chances are you will see similar basic node setups in most videos and recognizing these patterns is the core to learning about them and how they're used in my opinion.

I'd suggest a video by Gabriel Aguiar, just personal preference ๐Ÿ™‚
https://youtu.be/yJ0NRr-DdYU

Unity Shader Graph - Waterfall and Ripples Tutorial

In this Shader Graph tutorial we are going to see the steps I took to create this very stylized Waterfall with Ripples. It's one shader for the waterfall and another for the ripples. And we also need some meshes and a simple texture for the ripples.

I MADE A NEW WATERFALL BUT IT'S TOXIC: htt...

โ–ถ Play video
neat snow
#

i think I had that tutorial before, but I think I'm still missing the very basics: like, basically all I want for know is probably a shader/material in a single color, which has some noise in the upper area. No lightning, no interaction, no camera. The problem is, that many of these tutorials seem to use an older version of shadergraph and usually I'm stuck at the end

vivid marten
#

I'm trying to make a shader that works with 2D lights (URP) but idk how to do. I managed to get something at least lol. It's just black but it is at least affected by light

grizzled bolt
vivid marten
#

uh oh

#

it was that easy... but I don't understand the difference

grizzled bolt
vivid marten
#

but can't you achieve the same results from any base by changing the settings?

grizzled bolt
#

No
2D lighting and 3D lighting are entirely different
And in URP in current year are entirely mutually exclusive

vivid marten
#

aha

#

ty once again! ๐Ÿ™‚

#

so what I did wrong was doing stuff for 3D lighting

#

I made a URP->Lit Shader Graph

#

ooh so Lit = 3D and Sprite Lit = 2D

torpid sundial
#

Hello, does anyone know if this is intended behaviour for the branch node? It is combining the two inputs instead of choosing from one of them based on the boolean input. My intention was to combine them anyway but I'm not sure if this is the right node to do it with. I want to add an outline to the 2d sprite.

lunar valley
torpid sundial
#

but its drawing both, if i delete the comparison node it looks like this

#

im not sure i understand

lunar valley
torpid sundial
#

oh, now i get it

#

thank you!!!

silk wharf
#

Hello there, I was wondering about how much perfomance impact my voxel game would have if I instead of using a texture altas for blocks, use individual textures for each block but still using the same material (is this even possible?, does material property blocks allow to change the texture on the same material?) I'm asking because I find it a bit anoying to edit a full piece of texture atlas rather than setting up individual textures

teal loom
#

Hey! So i have a sprite shader set up with a normal map, but it has some weird smoothing effect, how would i get it to look more like this?

lunar valley
silk wharf
#

But to be honest it looks sick the way it is!

silk wharf
teal loom
teal loom
silk wharf
lunar valley
teal loom
lunar valley
grand jolt
#

How do I avoid "completely" dark shadow using directional light as my sun

lunar valley
grand jolt
#

baked

neat snow
#

i seriously envy you people understanding shaders lol

grand jolt
#

i tried to

#

increase the

#

Indirect Intensity but that ditn work

#

didnt*

grizzled bolt
teal loom
#

The resolution does match as well, might still have to code in a toon shader to make it look just right though

grand jolt
neat snow
#

hey mates, quick question:
is it possible to achieve something like this with ShaderGraph?
(and possibly some FX for the bubbles?) Or is another approach better for that?

#

or something like this:
basically a "flat" box with an semi-fluid behaviour

lunar valley
grizzled bolt
# neat snow or something like this: basically a "flat" box with an semi-fluid behaviour

It really depends on what "semi-fluid behaviour" means
The above example is just sprites with a wavy + bubbly frame by frame animation, the lower one could be as well
You can sample a wave function a shader, but you can't have much in the way of "propagating" ripples or waves because shaders alone cannot retain data between frames nor can they pass it on

meager pelican
#

Might be better to ask this in lighting section.

teal loom
livid kiln
#

I'm trying to find resources to help me control the sin wave in shader graph. I am looking to do a highlight strobe via a render object, but the sin wave lingers too long in the low values so there's a long period lacking highlight, I want to control the low bounds I guess, how might I go aobut that?

#

ah the remap node looks like what I need

tardy field
#

Every time I create or connect a node in shader graph, my Main Preview looks like this. Is there a way to fix it?

livid kiln
#

are you on mac or pc?

#

I'm on mac and I had that issue with unity 2020 but in later versions they fixed it

tardy field
#

pc

livid kiln
#

hmm not sure then, what version of unity are you using?

tardy field
#

2021.3.19f1

livid kiln
#

I'm sorry I dunno ๐Ÿ˜ฆ

#

ususaly the cyan means it's recompiling a shader

tardy field
#

It is really weird. If I click at it multiple times, then it fixes itself

silk wharf
meager pelican
silk wharf
#

also have you upgraded the render pipeline version? if so its better to delete the library folder manually so the project reimports everything

tardy field
silk wharf
tardy field
#

where do I check it?

silk wharf
#

experimental unity versions generally have some weird behaviour

#

you can either check it on the Unity hub where your project is , on the right side it will tell you which version you are in

#

or just read the info on your unity window on top of your screen

tardy field
#

It is 2021.3.19f1 but it doesn't say either it is alpha or beta

silk wharf
#

Ah its a stable version

#

Hmmm, is this issue new for you?

#

I mean its the first time it happens?

tardy field
#

It is my first time using shader graph, so yeah

#

Also, just realized that the issue with cyan material only happens whenever I have Surface type to transparent. It If I change it to opaque it doesn't render anything at all in the preview window

livid kiln
#

I'm trying to figure out how to make a shader graph material I've created apply to a gameobject which already has a material to blend the two through code. I can't seem to find any examples.

tardy field
livid kiln
#

I have a material of it. I want to blend that new material with an objects existing material on an object

#

I want to use the new material which is additive over the old material so I can add the effect of the new material when the mouse is over an object.

kind juniper
#

What you could do is render the object twice with each shader and then blend the resulting colors somehow.

livid kiln
#

Alright weโ€™ll how is it traditionally handled when you have a highlight effect like a fresnel you want to add to the object your mouse is over?

#

Without having to make a new version of every objects shader with and without fresnel

kind juniper
#

It's either handled in the objects own material/shader or with rendering the object twice(once with a normal material and another with the outline material) or with post processing.

livid kiln
#

Hmm ok thanks.

#

I thought there was a way to blend them. It does it with render objects but it applies that as a post process to all objects on a layer

#

I thought perhaps there was a way to blend two material output

kind juniper
#

The blending that you're talking about would need to happen after both of the materials rendered separately. I'm not sure about render objects, but in essence, to blend materials like you describe, you'll need to render the object into separate render textures for each shader/material, then in another shader, read these render textures, blend the colors and output them to the actual render target.

livid kiln
#

Yeah Iโ€™ll use the duplicate geo trick and instantiate a new object using the render mesh of the hovered one scaled 1.01 and apply the additive material

#

Thanks!

lunar valley
vivid marten
#

uhm shouldn't offset be x: 0 y: 0 in this case?

#

offset = (size - 1) * -0.5?

lunar valley
vivid marten
#

weird, why do I just see a blank texture then

lunar valley
vivid marten
#

if I hardcode the values like this I get the desired result

vivid marten
#

but why doesn't it work with a property?

lunar valley
vivid marten
#

I'm trying to make it scale so tilling and offset are tied together

#

this is the formula:
offset.x = (tiling.x - 1) * -0.5
offset.y = (tiling.y - 1) * -0.5

#

which is why I just used one float

lunar valley
#

but in the hardcoded value you had the x minus and y posititve

vivid marten
#

in the hardcoded value tilling was 3

#

so offset was tilling - 1

#

and I multiplied it with -0.5

lunar valley
#

wait im stupid

vivid marten
#

tilling is 2 so B is 2 - 1 which means offset is -0.5 * 1

#

this works

#

but what's funny is that this does not work

#

wtf is the difference

lunar valley
vivid marten
#

oh wait I had to update the material

#

but... how do I get B to be Size - 1 in the multiply node?

#

this doesn't work

lunar valley
#

whats B

vivid marten
#

in the multiply node A is -0.5 and I want B to be Size - 1

lunar valley
#

so you want your output to the offset node to be -1?

vivid marten
#

I want this

lunar valley
vivid marten
#

ooooh

lunar valley
#

cause -- = +

vivid marten
#

I'm dumb

#

bro

#

GOOOOD

#

I hate myself right now

#

I thought I should put -1 to substract 1

#

lol

lunar valley
#

happens

vivid marten
#

well ty anyway ๐Ÿ˜›

lunar valley
#

np, glad it works now

grizzled bolt
vivid marten
#

I made a funny effect tho

vivid marten
#

the previews are horrible

grizzled bolt
vivid marten
#

hmm

turbid stream
#

can anyone tell me how do you mask 3d models?

grizzled bolt
turbid stream
#

make specific region of the model transparent

lunar valley
#

you can use a texture for that and use that for your alpha channel.

vague pilot
#

Hey what is this shader called? - is it a toon shader?

regal stag
lunar valley
#

I need help so I want to make a seamless whater transition and basically render a mask which seperates above and below water. But my mask(which is in this case overlayed as transparent red). Does not match up with the actual clipped displaced surface. I am essentially checking if the nearclippplane position is above or below the sampled height of the surface mesh. (btw. I am doing it inside of a compute shader no real reason to why, I could also make it inside of an image effect shader I simply did it because I did idk.) ```cs
//Create Screen Uvs
uint width, height;
tex.GetDimensions(width, height);
float2 uv = float2(id.xy / float2(width, height) * 2 - 1);

//Transform Camera position from local To World Space
float3 origin = mul(_CameraToWorld, float4(0, 0, 0, 1)).xyz;

//Invert the perspective direction of the view-space positon
float3 viewVector = mul(_CameraInverseProjection, float4(uv, 0, 1)).xyz;
//Transform view direction from Camera local to worldSpace
viewVector = normalize(mul(_CameraToWorld, float4(viewVector, 0))).xyz;

//Near clipping plane position
float4 unprojectedPos = mul(_CameraInverseProjection, float4(uv, 0, 1));
unprojectedPos = mul(_CameraToWorld, unprojectedPos);
float3 clipPlanePos = unprojectedPos.xyz / unprojectedPos.w;

float h = PerlinNoise2D(clipPlanePos.xz * .3);

//Above-/Underwater mask
float mask = 0;
if(h >= clipPlanePos.y)
    mask = 1;       
else
    mask = 0;

tex[id.xy] = float4(mask.xxx, 1);```
hallow plover
#

how do you implement LOD crossfading in your shaders? I am using Unity 2022 with URP and shadergraph btw.

meager pelican
# lunar valley I need help so I want to make a seamless whater transition and basically render ...

That's hard, most games don't do it well, IIUC. It's certainly possible to do. Many use a post process for the under water part. I'm unsure what you're doing, since you said what is processing it but not when/where it is processed.

In your case it looks like you're trying to calc the Y height of the wave in 3D space, and the Y height of the pixel at the near plane. And trying to decide if your mask is right (and you're blending white or black into the result...and ???drawing red later???). What am I looking at? Why is there black, blended, and pink? What is the mask, all of that?

BTW...https://twitter.com/Cyanilux/status/1603002248463876098

Not perfect, but wanted to have a go at a waterline effect to add to my latest stylised ocean shader~๐ŸŒŠ
#TechnicallyAChallenge - Underwater
#unity3D #madewithunity #shaders

Likes

1170

Retweets

122

โ–ถ Play video
keen cloud
#

is there a way to get a sampler2D from texture2D? Vice-versa is done by sampling I know that.
But the problem is I can only send a TextureParameter to the shader not a SamplerParameter.

float4 Frag(v2f i) : SV_Target
    {
        float2 screenPos = i.screenPosition.xy / i.screenPosition.w;
        float2 ditherCoordinate = screenPos * _ScreenParams.xy * _DitherPattern_TexelSize.xy;
        float ditherValue = tex2D(_DitherPatternSampler, ditherCoordinate).r;
        return ditherValue;
    }

This is the Frag function. I need to have a sampler2D because I need to use my own coordinate (the ditherCoordinate).

texture2D _DitherPattern;
sampler2D _DitherPatternSampler;
float4 _DitherPattern_TexelSize;

These are the parameters. I want to be able to set the _DitherPattern with a PostProcessEffectRenderer (which only allows me to send a TextureParameter as I said), but I need to use the _DitherPatternSampler because that's how the shader works.

Also why is there nearly 0 documentation about the PostProcessEffectSettings? Why can't I find all the allowed parameters?

#

Oh, I maybe fixed it. I have no idea if I'm getting the desired outcome, but at least no errors. Can somebody confirm if writing _Sampler after a texture name gives you the sampler of that texture?

#

like so:

texture2D _DitherPattern;
sampler2D _DitherPattern_Sampler;
lunar valley
#

didn't notice that cyan made such a thing tho

lunar valley
regal stag
# keen cloud is there a way to get a `sampler2D` from `texture2D`? Vice-versa is done by samp...

"SamplerParameter" isn't a think afaik. Textures from the C# side should be able to map to sampler2D or Texture2D in the shader, just depends how you want to define them.
You should be able to do either

sampler2D _DitherPattern;
// or 
Texture2D _DitherPattern;
SamplerState sampler_DitherPattern;

Though Unity tends to have macros for these too.
sampler2D is just the DirectX9 syntax, where the "texture" and "sampler" is coupled together in the same object. While the DX11 syntax added Texture2D and SamplerState allowing you to define them separately (useful for re-using the sampler over multiple textures due to limits)
Also see https://docs.unity3d.com/Manual/SL-SamplerStates.html

keen cloud
#

I need it to be a Texture2D tho

#

and I need a Sampler, not a SamplerState

#

I've read that already

#

it needs to be a texture so I can send it via a c# script, but I need a sampler2D for the shader code to work

regal stag
#

But why do you need the sampler2D? If you're using tex2D there are alternative sampling methods for Texture2D.

keen cloud
#

float ditherValue = tex2D(_DitherPatternSampler, ditherCoordinate).r;ห› because of this

#

the dither coordinates are calculated at runtime and they depend on the _DitherPattern texture

regal stag
#

Should be able to use _DitherPattern.Sample(sampler_DitherPattern, ditherCoordinate).r instead with the Texture2D/SamplerState.

#

There's likely also a sampling macro that Unity is defining, but I don't know the post processing package that well.

keen cloud
#

yea but that does nothing

#

because I need to be able to define the sampler, no?

#

I never defined what the sampler is

#

in the original shader, they put their own Texture via the inspector in the Sampler2D field

#
//Shader Property
_DitherPattern ("Dithering Pattern", 2D) = "white" {}

this is how they write the property
and then later

//The dithering pattern
sampler2D _DitherPattern;
regal stag
#

When you pass textures from the C# side into materials, Unity automatically sets the Texture2D and SamplerState objects, they just need to be named correctly. If the texture is _DitherPattern then the SamplerState can be named sampler_DitherPattern and it should work. Or you can use an inline sampler like at the bottom of that docs page I linked.

keen cloud
#

but isn't SamplerState the way the textures are filtered? like point, linear, etc?

#

why is there Sampler2D and SamplerState then? Are they the same?

regal stag
#

sampler2D is an older syntax where the texture and sampler data is coupled together

keen cloud
#

hm

#

okay

#

still outputs just a white screen, but thanks

meager pelican
#

Property?

#

At top of shader?

#

If so, what is the default value shown as?

keen cloud
#

it's not shown, because it's Post Processing custom effect

#

TEXTURE2D_SAMPLER2D(_MainTex, sampler_point_clamp); this is how I'm doing it though

meager pelican
#

Show me the code declaration for maintex TEXTURE

keen cloud
#

this works in another custom effect I made (its a super simpler one)

meager pelican
#

Forget samplers for a second

keen cloud
#

there is no declaration, the maintex is whatever is on the screen at the moment

context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, 0);
meager pelican
#

OK, that's C#.
Show me the shader code if you can.

#

use pastebin or whatever

keen cloud
#
Shader "Custom/Dithering"
{
    HLSLINCLUDE

    #include "Packages/com.unity.postprocessing/PostProcessing/Shaders/StdLib.hlsl"

    TEXTURE2D_SAMPLER2D(_MainTex, sampler_point_clamp);
    SamplerState sampler_MainTex;
    float4 _MainTex_TexelSize;
    float4 _MainTex_ST;

    texture2D _DitherPattern;
    SamplerState sampler_DitherPattern;

    float4 _DitherPattern_TexelSize;
   
    struct v2f {
        float4 position : SV_POSITION;
        float2 uv : TEXCOORD0;
        float4 screenPosition : TEXCOORD2;
    };

    float4 Frag(v2f i) : SV_Target
    {
        //texture value the dithering is based on
        float4 texColor = tex2D(sampler_MainTex, i.uv);

        //value from the dither pattern
        float4 ditherValue = tex2D(sampler_DitherPattern, i.uv);

        //combine dither pattern with texture value to get final result
        float4 col = step(ditherValue, texColor);
        return col;
    }

        ENDHLSL

        SubShader
    {
        Cull Off ZWrite Off ZTest Always

            Pass
        {
            HLSLPROGRAM

                #pragma vertex VertDefault
                #pragma fragment Frag

            ENDHLSL
        }
    }
}
meager pelican
#

OK, looks like it's this macro TEXTURE2D_SAMPLER2D(_MainTex, sampler_point_clamp);

#

What I was wondering is if it defaulted to all white.

#

(1's)

#

Same for ditherPattern, but that's not known yet.

regal stag
#

You should be sticking to the post processing package macros rather than defining sampler2D/Texture2D/SamplerState. And use SAMPLE_TEXTURE2D(tex,sampler,uv); rather than tex2D.

meager pelican
#

How do you set the _DitherPattern texture in C#?

keen cloud
keen cloud
# meager pelican How do you set the _DitherPattern texture in C#?

sheet.properties.SetTexture("_DitherPattern", settings.ditherPattern.value); this is already going into post processing and deviating away from shaders
the post processing part is not the problem, I know how to code in C# infinitely better than in shader code.
I know it's the lack of my shader knowledge that is the problem, so lets please just focus on that.

regal stag
#
TEXTURE2D_SAMPLER2D(_MainTex, sampler_MainTex);
float4 _MainTex_TexelSize;
float4 _MainTex_ST;
TEXTURE2D_SAMPLER2D(_DitherPattern, sampler_DitherPattern);
...

float4 texColor = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv);
float4 ditherValue = SAMPLE_TEXTURE2D(_DitherPattern, sampler_DitherPattern, i.uv);
meager pelican
keen cloud
keen cloud
regal stag
keen cloud
#

thanks, good to know. But for now, I'm just trying to get the logic part of it working

meager pelican
keen cloud
#
float4 Frag(VaryingsDefault i) : SV_Target
    {
        //texture value the dithering is based on
        float4 texColor = tex2D(sampler_MainTex, i.texcoord);

        //value from the dither pattern
        float4 ditherValue = tex2D(sampler_DitherPattern, i.texcoord);

        //combine dither pattern with texture value to get final result
        float4 col = step(ditherValue, texColor);
        return col;
    }

I even tried changing it to VaryingsDefault (another thing that I have no idea what is it) and still white

meager pelican
#

But I'm not using these new Post processing frameworks

keen cloud
#

oh my bad I removed that bit because it didn't work aswell lol

#

I tried to debug something else thats why

#
 float2 screenPos = i.screenPosition.xy / i.screenPosition.w;
    float2 ditherCoordinate = screenPos * _ScreenParams.xy * _DitherPattern_TexelSize.xy;

this is how it was calculated, but I didn't have access to screenPosition

meager pelican
#

There you go.

keen cloud
#

I found forums saying i need to use screenPosition : TEXCOORD2 but that did nothing

#

its still a white screen btw

meager pelican
#

You have to calc it in a vertex shader stage

#

Pass it to the frag stage

regal stag
#

I would assume the i.texcoord is already the screen pos here

meager pelican
#

It's in your v2f, but IDK if there's some default vert that

keen cloud
meager pelican
#

OK, that. Again, not used to this PP framework.

keen cloud
#

float2 uv : TEXCOORD0; isn't texcoord also TEXCOORD0?

keen cloud
regal stag
#

In the fragment inputs, TEXCOORDs are just "interpolators" used to pass data from the vertex stage. I assume the post-processing package is already doing that part for you, probably via #pragma vertex VertDefault?

keen cloud
#

I don't know but yes that pragma is there

#

I just want to dither the entire screen, considering that's basically a quad with a texture, I thought this would be so much easier

regal stag
keen cloud
# regal stag Yeah so `i.texcoord` should be the screenpos. So maybe try `float2 ditherCoordin...
float4 Frag(VaryingsDefault i) : SV_Target
    {
        //texture value the dithering is based on
        float4 texColor = tex2D(sampler_MainTex, i.texcoord);
        float2 ditherCoordinate = i.texcoord * _ScreenParams.xy * _DitherPattern_TexelSize.xy;
        //value from the dither pattern
        float4 ditherValue = tex2D(sampler_DitherPattern, i.texcoord);

        return ditherValue;
    }

this is how I wrote it. I'm returning only the ditherValue to debug it easily
now all I get is a gray screen

#

I even tried zooming in to see if there is some noise in there

#

I'm using this texture as a test palette

regal stag
keen cloud
#

I think it's just the very specific shade of gray, because even the screenshot looks noisily animated to me... I wouldn't know for sure tho

#

this is the image it's presented with

regal stag
keen cloud
#

still the exact same color

#

the new texture

#

???
float2 col = texColor + 10 * ditherCoord - 0.5f; returns cannot implicitly convert from 'float2' to 'float4' at line 30 (on d3d11) which is understandable
yet,
float4 col = texColor + 10 * ditherCoord - 0.5f; returns cannot implicitly convert from 'const float2' to 'float4' at line 29 (on d3d11)??????
I never wrote const float2

meager pelican
keen cloud
#

what?

meager pelican
#

return float4(i.texcoord.xxx, 1);

keen cloud
#

I don't need that though

#

I rewrote it I mean

#
float4 Frag(VaryingsDefault i) : SV_Target
    {
        //texture value the dithering is based on
        float4 texColor = tex2D(sampler_MainTex, i.texcoord);
        float2 ditherCoord = i.texcoord.xy % 2;
        float4 col = texColor + 10 * ditherCoord - 0.5f;
        return col;
    }
#

but sure I'll do that

keen cloud
#

like so

meager pelican
#

Good, it will do the same for y if we did that instead of x.

keen cloud
#

from bottom to up yes

meager pelican
#

So texcoord.xy is normalized, although the gamma sucks.

#

OK, now we output ditherCoord to see what values it has.
return float4(ditherCoord, 0, 1);

keen cloud
#

what

#

I rewrote it

#

it's not the old shader anymore

#

I'm rewritting it by reading a wiki article on how dithering actually works

meager pelican
#

Of course you are. But show me what dithercoord looks like please.
After this line
float2 ditherCoord = i.texcoord.xy % 2;
Add that return statement above

keen cloud
#

it looks as it should

#

I mean

#

the modulo is doing nothing

meager pelican
#

Yeah, since it's a mod 2 and the value is 0 to 1

keen cloud
#

I see

meager pelican
#

dithercord is a float2, and you're in a float4 expression with that error. It doesn't know what to do with it.

keen cloud
#

I don't know either

#

it makes no sense

meager pelican
#

That dither texture is really meant to be a LOOKUP table of THRESHOLDS for another set of decisions/conditionals.

#

So you need to find a proper dither texture with different values in ...dither format...or use an array to look up values.
Then you use something, like color-intensity to compare to the value in the lookup/dither table and decide what to do with that pixel.

keen cloud
#
float4 col = TEXTURE2D_SAMPLER2D(sampler_DitherPattern, ditherCoord);

it just says redefinition of 'ditherCoord' at line 29 but I didn't redefine it here???
syntax error: unexpected token 'sampler_DitherPattern' at line 29 whaaat

#

oh wait i'm dumb

#

no wait

#

it still doesn't work

#

float4 col = TEXTURE2D_SAMPLER2D(_DitherPattern, ditherCoord); I changed it to have a texture instead of a samplerstate

#

wait

#

its something

meager pelican
#

GTG now, due at GF's...

keen cloud
#

have fun

lunar valley
acoustic steppe
#

I am at wits end with trying to figure out shaders facepalm

So I have a mesh that has a main texture that I use to set UVs based on specific data.
Is there a way to edit or overlay the end result of setting all the UVs or am I stuck having to only deal with the entire main texture?

Hope that makes sense..

halcyon panther
#

Are you trying to make the shader only affect part of the texture?

grizzled bolt
#

Or a shader that displays only a part of the texture

acoustic steppe
#

So, I'll explain because I figured that was broad or didn't make sense.

I have a mesh that I create and dynamically set UVs based on positional data. I essentially am making a tile map, without using the tile map. One of the meshes I use is used for only water tiles from various color based on some data that is set.

If I go through and do something like Blend on top of the main texture, it tiles the end result on the mesh. So if I set 4 spots as the same UV set then they use the exact same blend because the blending is happening to the main texture and then drawing that part. What I would like to do is blend the end result UVs that are built as a whole vs the main texture.

#

I guess the other way I can explain is if I were to build noise on top of the main texture, each UV set has only that tiles part of the noise, vs the noise being drawn over the top of the whole mesh that is visible.

grizzled bolt
regal stag
#

Or set a second UV set on the mesh data

acoustic steppe
tight phoenix
#

question, what's the smart way to make all the values that are non-zero to be 1?

Right now I am using a Step set to 0.001 but this feels like an ugly hack (not pictured)

#

if I use a step of full 0, the entire thing goes pure white

#

but I still want my black zero values to be zero

#

what's the smart way to make all nonzero values all 1?

#

Oh a Sign node does it UnityChanThink

tight phoenix
#

I am looking for a clean way to remove this discontinuity between the values
the discontinuity occurs because mesh depth has this black border of 0 to it. I need that border to be 1 and not 0.
The problem with that is the body 0 seen further down there needs to be 0.
So the problem is the only way the edge 0 can be 1 but the body 0 can be 0 is some kind of mask
and the only data I have to get that mask is the above values that I am using sign to get pure 0 and 1.

dull comet
#

Hi, I am working on an underwater scene and I am trying to put fog only for the horizon part. I have a shader that allows me to have fog everywhere the things is that I don't wanna have fog on the top because I wanna see the waves when I look at the sky

#

I have work on this during 4 hours and I still didn't get the results that I wanted

#

I am using the Built-in pipline

kind juniper
#

Fog is applied as part of the lighting calculation iirc, so you'll need to override that instead of using unity's default one.

dull comet
#

Oh

dull comet
kind juniper
#

The shader code

dull comet
#

Shader "Custom/CustomFog"

{
Properties
{
_FogColor ("Fog Color", Color) = (1,1,1,1)
_FogDistance ("Fog Distance", Range(0.0, 500.0)) = 50.0
_FogHeight ("Fog Height", Range(-10.0, 100.0)) = 0.0
}

SubShader
{
    Tags {"Queue"="Transparent" "RenderType"="Opaque"}

    Pass
    {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"

        uniform float4 _FogColor;
        uniform float _FogDistance;
        uniform float _FogHeight;

        struct appdata
        {
            float4 vertex : POSITION;
            float3 normal : NORMAL;
        };

        struct v2f
        {
            float4 pos : SV_POSITION;
            float fogFactor : TEXCOORD0;
        };

        v2f vert (appdata v)
        {
            v2f o;
            o.pos = UnityObjectToClipPos(v.vertex);
            
            // Calculate the fog factor based on distance from the camera
            float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
            float dist = length(UnityWorldSpaceViewDir(worldPos));
            o.fogFactor = (dist - _FogDistance) / dist;
            
            // Ensure that the fog only appears on the sides of the object
            if (worldPos.y >= _FogHeight || worldPos.y <= -_FogHeight)
            {
                o.fogFactor = 1.0 - saturate(o.fogFactor);
            }
            else
            {
                o.fogFactor = 0.0;
            }
            
            return o;
        }

        fixed4 frag (v2f i) : SV_Target
        {
            return lerp(fixed4(_FogColor.rgb, 0), _FogColor, i.fogFactor);
        }
        ENDCG
    }
}

FallBack "Diffuse"

}

kind juniper
#

Next time use code sharing guidelines
!code

echo moatBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

dull comet
#

oki sorry for that

kind juniper
#

Ok, so what's the issue with this shader?

dull comet
#

I cant see the water above me

#

I would like to see the water but not the terrain limitation

kind juniper
#

Take a screenshot of the water material when using the custom shader

dull comet
#

misread

kind juniper
#

Actually, that shader is probably not supposed to do what you expect it to do. Where did you get it?

dull comet
#

Asset store

kind juniper
#

Can you share the link?

dull comet
#

yeah

kind juniper
#

I see

#

It seems to be a post processing g effect. If it doesn't work for you, I'd assume there's something wrong with your setup.

#

I'd check the sample scene provided with the asset, make sure that it works correctly, and try to replicate the same setup in your actual scene.

dull comet
#

yeah i tried tho but thanks

bold breach
#

are there any outlien shaders that look consistently good? the only ones i have found only work on perfectly round objects, otherwise they have gaps and just look really weird

kind juniper
dull comet
#

yes

kind juniper
#

Ok, then there's definitely something wrong with your setup.
Can't help any more than that, since it would require me getting acquainted with asset, and I don't want to buy it just for that. Pity that the asset doesn't have any documentation.

dull comet
#

thanks

kind juniper
bold breach
kind juniper
#

It's a method of generating outlines as a post processing effect.

#

There are many implementations, so you'll need to google that.

tame ingot
#

Hi, guys. I just start learning unity shader and I have a problem here. The material inspector is not showing the defalut value specified in the .shader file.

waxen wind
#

hey guys i am messing with position in URP shader for the first time (displacement, i guess). is there a general approach for fixing normals? specifically i am moving some verts down along their normals (so for them, the normals are unchanged). but the normals at the boundary get messed up

#

maybe i juzt use a normal map instead of mesh normals? does this Just Work ยฉ with displacemenr?

kind juniper
kind juniper
tame ingot
#

I'm using URP

waxen wind
kind juniper
tame ingot
tame ingot
#

So normally there is no extra setup to make inspector display default value, right? I was wondering if there is some setting to make it work

kind juniper
tame ingot
kind juniper
#

Maybe because your property is not linked to an hlsl property.๐Ÿค”
Complete your shader and see if it works then.

rustic fossil
#

Following Sebastian Lague's tutorial on procedural planets and got to the shader episode. I've made the shader and followed his code, but when configuring the gradient the shader just makes the entire thing into the first colour, rather than blend between them based on elevation like it should. Once I get home later today I'll rewatch the episode and make sure I followed it completely, but if anyone knows why that would be a great help

#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ColourGenerator
{
    private ColourSettings settings;
    private Texture2D texture;
    private const int textureRes = 50;

    public void UpdateSettings(ColourSettings settings)
    {
        this.settings = settings;
        if (texture == null)
        {
            texture = new Texture2D(textureRes, 1);
        }
    }

    public void UpdateElevation(MinMax elevationMinMax)
    {
        settings.planetMaterial.SetVector("_elevationMinMax", new Vector4(elevationMinMax.Min,elevationMinMax.Max));
    }

    public void UpdateColours()
    {
        Color[] colours = new Color[textureRes];
        for (int i = 0; i < textureRes; i++)
        {
            colours[i] = settings.gradient.Evaluate(i / textureRes - 1f);
        }
        texture.SetPixels(colours);
        texture.Apply();
        settings.planetMaterial.SetTexture("_texture", texture);
    }
}
#

^code for getting elevation, setting shaders and such

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MinMax
{
    public float Min {get; private set;}
    public float Max {get; private set;}

    public MinMax()
    {
        Min = float.MaxValue;
        Max = float.MinValue;
    }

    public void AddValue(float v)
    {
        if (v > Max)
        {
            Max = v;
        }
        if (v < Min)
        {
            Min = v;
        }
    }
}

The actual min-max code

lunar valley
grizzled bolt
#

You'll want to include some context since your link requires a login

spice kayak
#

Hello, I created a shader to automate sprite animation, but when I applied it to material, the game object with that material stopped appearing in the scene or the game window

#

No material

#

with material

waxen wind
#

@kind juniper Sorry for the delay, you can see here, I'm pushing this tile downward and the normals are black on the sides

#

It might just be shadow though

#

Idk maybe I just won't push it as far

kind juniper
#

Normals can't be black. They're simply a direction vector. The faces are black. But I feel like it's the shadows.

serene stream
rare wren
serene stream
#

Is this the camera settings you need?

rare wren
#

Yep, that looks fine

serene stream
#

in the shadergraph itself is nothing, i just changed the color for test reasons

#

where are material settings? I only have this if I click on my material

#

(i changed it to red but nothing makes a difference, as soon as I apply a skybox it does this)

#

I just saw this error @rare wren but i dont know which shadergraph shader to use instead

spice kayak
#

My issue has been fixed,

rare wren
#

https://docs.unity3d.com/Manual/skybox-shaders.html

You can check out how the default shaders work, or look for guides specifically on skyboxes. You might need to render an inverted sphere and put the camera background type to none.
Don't have much experience with this myself

serene stream
old siren
#

Hi, my main preview window doesn't show anything even when I create a new graph shader, anyone know the problem ?

regal stag
feral lynx
#

Is there anyway to make a shader that fades the mesh into black/background as it gets to the outside, trying to recreate a similar effect to this pixel art but in a 3d space. cant seem to find any resources on something like this.

keen cloud
#
float4 Frag(VaryingsDefault i) : SV_Target
    {
        //texture value the dithering is based on
        //float4 pix = SAMPLE_TEXTURE2D(_MainTex, sampler_point_clamp, i.texcoord);
        float2 pos = i.texcoord;
        //float M = bayer4[pos.x * 4 + pos.y] * (1/16) - 0.5f;
        float col = float4(pos, 0, 1);
        return col;
    }

how is this returning a gradient??

#

just a second ago it was returning the expected (x and y mixed gradient)

regal stag
keen cloud
#

fair

cosmic sphinx
regal stag
tight phoenix
#

Im still getting absolutely nowhere solving this edge problem

#

I keep trying more and more elaborate combinations of values but none of them solve the problem

#

the problem is that I need to mask SOME values of 0 but not all values of 0

#

and that's just not possible

#

@regal stag I don't want to doubt you but is it possible the problem is occuring before the distance step, somewhere in Transmission.hlsl? Because i've put hours into trying to solve it after the Distance step and nothing I do solves it

#

starting to get anxiety ridden because I just keep failing and failing

#

I need to succeed, and I am not, and I don't know how to obtain success, and I am grinding harder and harder and harder but its not bringing me any closer

#

all I know is that it can be solved, but I'm too stupid to solve it

#

no matter what I do I just can't eliminate this discontinuity between the vbalues, the black line plagues me

#

every single combination that eliminates it, also eliminates the entire effect, washes it out with a value of 1, useless

#

yeah im going into crisis mode now, I need to stop working on this even though every single fiber of my entire being is screaming that I just need to solve this to be happy again and I will never be happy ever again until its solved

#

mental health sucks

misty crown
#

Hi I have a very simple question and would love guidance if possible as Im not sure where to find the direct answer .

I have the following images, and I am trying to utilize the most possible inputs on my URP material (to get the most accurate result), can someone help me find the right resource or guide me on where to place each one. Some are obvious of course (but not sure about displacement, roughness, and AO)

Thank you for your help!

#

can you just invert a roughness map to make it work with a metallic map?

keen cloud
#

I guess making your own shader to utilize all of those would be the best

misty crown
#

Thank you @keen cloud !

regal stag
tight phoenix
#

passing in a bias instead of your hardcoded 0.05, adding in the shadow values as well

#

its frustrating that its better but still not perfect, but thats me not being forgiving of imperfections

#

maybe the problem is my lighting settings

#

because it gets worse when you zoom out

keen cloud
#

1st image: original
2nd image: depthNormals
Why do the object that have my custom shader not show up on the depthNormals texture?
They have the Opaque render type

#

does it have to do with zwrite?

#

ah

#

I moved the rendertype tag outside the pass and before it. I don't even know why was it in the pass

#

another question
is there a DecodeDepthNormals for hlsl?

lunar valley
keen cloud
#

I see

#

thanks

tight phoenix
#

after playing with various values I think this is as good as itll get. Happy with this

lunar valley
#

you sure its working correctly? for me it looks a bit like shadows but inside of the model