#archived-shaders
1 messages ยท Page 43 of 1
Try adding a saturate node after the subtract
Because the dark area had negative values
ooh I thought it was at zero
Let's say its value was at 0.6, then you subtract 1, now it's -0.4
I should maybe make the substract image directly in an image editor instead ๐
but this way I have the option to keep the original
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
hmm
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
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!
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...
well you can always use an unlit shader and make the light calculations yourself
Is there a library for parallel programming like open mp only for shader?
Shader is more or less parallel programing by design. What exactly are you seeking ?
i want to make it more efficient/faster. It still has to do computations step by step if i use for-loops right.
In raymarching algorithms ? Yes
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
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
getvertexpositioninputstransforms 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 ?
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
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?
Every pixel of the screen
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
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
abs only takes 1 argument
You probably wanted to do abs(a-b)
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
Can you show the new code ?
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;
}
}
There is a lot of tutorials about shaders in unity, but those constant and macros like the one you're refencing are ... specific to unity, and defined in included files that are not always easy to track
p is a float4 sampled from the main texture
Probably not related to the error, but since i is an index, you should decalre it like a int or even uint
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
changed that now, thanks
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
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
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 ๐
Really not sure what you're trying to do here. At first it sounded like you just wanted a Step and Multiply to mask out that area?
Now it looks like you want a Smoothstep?
I dont know how to get what I want so don't listen to anything I say, this is entirely XY
There isn't a template that replicates the URP/Lit completely afaik, but the Lit Graph is already most of the way there. You just need to create Texture2D properties and connect them, mostly.
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
Oh, got it ๐
Just use your push then
currently looks like shit because the light bleed curve isnt curved right
SSS isn't only on the edge of the dark area, it is an effect visible on the whole lit face
I don't want the side exposed to sunlight to be emissive though do I?
You do
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
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
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
this is what produces that
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
It is totally expected that some of the sss rays get bounced back even toward the light
But obviously, this is way to intense, you need to dim it down with an sss color & factor
Yes but this isnt actually calculating SSS this is just a rough axproimation, you can't do SSS on anything remotely complex in real time since it needs all kinds of high level raymarch stuff
when you say dim it down you mean multiply by some value so that the light facing side is not 1 but less than 1?
yes
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
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
playing with the values and its not good. Anything that looks good on the shadow side is washed out on the light, and anything that looks right on the light side is so near zero that there is no perceptible change on the shadow side
Let me dig, I made this a while ago, I should have something to compare
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
SSS is quite subtle and shouldn't just be a "rim"
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
๐ 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
I wish SG had something like this, a curve node that I could plug a gradient into
You could do something close with the gradient sample node
I suppose but gradients can't be exposed, I have heard arguments not to ever use them for reasons I dont fully understand
this right?
You can also author a 1D ramp texture if you wish to
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
Just for illustration, here is what I got as result for my skin :
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
So, you're trying to do transmission ?
I guess? Isnt that what SSS is? Or at least is a component of?
I have seen zucconi's tutorial on real time SSS aproximation but I tried multiple times and couldnt get appealing results
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
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
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
am I mistaken but Isn't that raytracing and isnt that costly/difficult/impossible in URP?
I am not aware of any method to get the depth of a mesh from one side to the other in scene
IT's not raytracing.
Liek I said, your approximate the thickess by comparing the current pixel world pos with the shadowmap
my attempt at the zucconi method, the ugly bits are just because its a bad auto unwrap
I have access to the shadow map, I will try to test that now
by shadow map you mean this right? the scene's shadow values?
If you're curious, here is my skin shader for reference
I think I'll just have to make my own function for what I want to do. I copied this one from stackoverflow because I have no idea how to use shader code. But I'll just try to do it on my own
also the problem still persists even after lower the iterations of the for loop
Will check that out. context of what is inside 'main light shadow'; this is downloaded not my own work
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 :/
float4 pixel = texture.sample(...);
int index = FindIndexFunction(pixel);
return palette[index];
So, how do you want to do the "the color fits in a certain range" part ?
how did you do your SSS?
(just for curiosity)
if you mean those green pictures, those are from the net and not an in unity shader
did you make SSS tho?
those are what I am comparing mine against
I am not sure what you are asking me
and how are you doing it?
basically that, yes?
the color fits in a certain range should be based on it's intensity I guess.
I want to "compress" the view. Basically make it look worse, maybe more like cel shading but global? Maybe cel shading is the right way to put it.
okay now that I think about it more
I think i realize how impossible it is
from just the camera's view
It is possible, they're a lot of ways to do this
well did you manage to make SSS? If yes I would like to know how you did it, for the sake of curiosity. Or even if you didn't fully manage to complete it yet, how are you doing it
yes if I use materials, right? I can't make a post processing effect that does that
One VERY easy way is to do color grading with a look up texture
There are already post processes for this ๐
both iirc
so, I should just use color grading? and make it very "steppy"?
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
unfinished, plugs into emissive
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
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;
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!
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.
that is interresting can I also see how it looks like^^?
right is without and left is with?
front and back
I see and whats with this one that looks kinda better (the right one)
completely different shader. That is this: #archived-shaders message
sure but still SSS? are you making two versions?
It is still SSS, I am trying different methods
oh, to see whats best or what?
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
Yeah I can do that, still working on it for a while yet
hello everyone. would anyone have an idea as to how the lightning animation here is done? https://youtu.be/WG5HlDdQz4E?t=8
Chain Lightning build for Sorceress Diablo 2 Resurrected that nobody uses anymore
Probably vfx trails.
#โจโvfx-and-particles
is the only way to change a camera's depth texture mode through a script?
i feel like that could be a dropdown
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
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 ?
aren't they shader variables by default? they have to be passed?
thank you!
Ah, yes, also ๐
really strange actually how I need an extra script to enable the depth texture.
I've tried enabling it in a postprocesseditor in the override void OnEnable() but it still doesn't change the camera's depth texture mode
public override void OnEnable()
{
Camera.main.depthTextureMode = DepthTextureMode.DepthNormals;
...
}
oh it actually does now
it needed some time I guess?
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
you don't sample the depthnormal like this you need to use tex2D I think. also Dont forget to do enable depth normal inside of a c-sharp script
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
do this in c-sharp cs cam.depthTextureMode = cam.depthTextureMode | DepthTextureMode.DepthNormals;
I did
not like that, but I did
ok
is this an image effect shader? also which pipeline?
what happens if you return depthnormal?
I'm assuming I have to use the _LastCameraDepthNormalsTexture
uh not really
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
ok?
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
How do I debug a frame on MacOS?
ok so now you only have 1 pp effect?
?
can you just disable all of the pp shaders except your depthtexture shader, so that we can see if it then works
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
where are you doing this: cam.depthTextureMode = cam.depthTextureMode | DepthTextureMode.DepthNormals;? at start?
Camera cam;
public DepthTextureMode depthTextureMode;
private void OnValidate()
{
cam = GetComponent<Camera>();
cam.depthTextureMode = depthTextureMode;
}
I do it on validate
eh, try putting it in start and hit play
why?
the camera works
can change it easily
this is obviously not intended way of working
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
in unity there is the frame debbuger
just try putting the activation of the depthnormal inside of the start function..
I need to run the Xcode graphical debugger
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
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?
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 !
i want the triangle to rotate over lifetime to the left, what setting do i need in the graph ?
wdym
so the problem is that your drawn meshes are not being rendered to the depth texture?
They should be, I have ZWrite On on my shader. But it only works with ZTest Equal, so it seems that my depth is uniform on the whole render target...
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
he is using an unlit shader you aren't
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
well yes, but only if you have light
what I would guess is that the object is not being illuminated so that is why its black
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
solved?
I think so ๐ thank you for pointing that out with lit/unlit
Is there a way that I can have a gradient as a variable in my shader? (non-shadergraph)
I donโt think thereโs a built in way. But you could use a 256x1 texture as input and write a simple script to generate the gradient texture. Expose some color fields (or maybe Unity provides a serialized gradient class) then in OnValidate() set the shaderโs texture.
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
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).
Great, thanks for the help!
like how do i make the custom properties different for each game object i use the shader for
if you assign a material to multiple objects, it is gonna affect all of the gameObjects, you would need to have multiple materials
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
What am I doing wrong?
Why is unity saying there is no color property when there is?
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
Can someone explain this to me? When I use my custom material the edges of the sprite looks really weird
You're not using the texture alpha for the shader's alpha transparency
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?
Connect the texture alpha channel to it, not all four channels
Make sure the graph is using alpha transparency
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 ๐ค
"Debug mode" in this context?
Thats not a color
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
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
aha
it made a big difference with Generate Mipmaps enabled
and I think I should have anti-aliasing turned on
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
AA in Unity only affects geometry edges, except FXAA which kind of smudges everything
Usually you should have all types of AA off if you're using 2D graphics
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?
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?
moving to some more relevant channel
got it - all I had to do was checking Double Sided global Illumination
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
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
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
lets try that then. Following a pretty nice tutorial from Brackeys, but it seems outdated
yeah, the scene preview works
Brackeys might be pretty outdated for shader graph considering urp is constantly changing and brackeys doesn't make videos anymore. Idk though.
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
I stopped relying on the preview a long time ago
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
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.
Scene View doesn't auto-update so the editor performs better. But you can enable "Always Refresh" in this dropdown in the top right.
I feel silly, "Always Visible" is giving me good info on the technique--nevermind ๐ !
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?
approximate the thickess by comparing the current pixel world pos with the shadowmap
I have the shadowmap and pixel world pos but the PWP is a vec3 and the shadowmap is a vec1, in this situation how would I aproximate distance, what is the 'comparison', I am going to try the Distance node first but if that fails ill be back here to ask how to push this further
You can calculate the world position of the point hit by the light with the light projection matrix and the shadow map value
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
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 ?
May want to use the View Direction and Normal Vector nodes if you want to use World space instead. I'd assume that would be more common, not sure why it defaults to object space really.
Is there a node to turn off zwrite in the shader graph?
Not a node, but it should be in the graph settings
Sadly I use unit 2020.3,and there's only lit/unlit and face rendered setting
*unity
Might be able to use the RenderObjects feature, as that provides overrides for ZWrite etc.
is there any way i can pass a dictionary into a compute shader?
Is there any way to set vertex positions to screen space positions?
o.screenPos = ComputeScreenPos(o.vertex); ?
i mean given an xy coordinate between -1 and 1, or whatever range, set the vertex to be at that position in screenspace
that would already be in screen space i think
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
you're talking uv coordinates
yeah
i want the shader to render the uvs flat, treating the screen as a texture
so the shader would essentially unwrap the uvs
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
instead of SV_POSITION?
you set the screenPos to computescreenpos(o.vertex)
its a uv coordinate not a vertex so you use texcoord
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
i am so confused that doesnt make sense to me. sorry xd
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?
yeah
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
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?
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
i know but does the shader like draw the cube in the bottom left corenr of the screen?
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
so you are just drawing the uv map to the screen?
yeah
okay. so you need to get the uv map as a texture and then render that out?
Do you mind if I comment?
not at all go ahead ๐
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.
So the vertex shader stage MUST output the verts in clip space.
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
X, Y for clip space is going to range from -1 to +1 with 0,0 being the center
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
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.
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
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.
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
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).
Squishing things toward the center of 0,0 with the perspective divide.
You're welcome.
pls tell me
A dictionary is a storage technique/data structure. But what it contains can vary. What's IN the dictionary?
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
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)
my project is kindof like minecraft or teardown.
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.
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
What exacty is a light projection matrix? I tried to google it but it got into omega maths
Yeah. So you'd upload the map of voxel space to the GPU in a structured buffer.
Something related to these?
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.
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).
alright
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 ๐ค
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
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
why is the output of the shader nothing when i have set my asset and the base color is set
Make sure you've followed all the URP setup instructions and that your shader has "Universal" in Active Targets of the Graph Settings
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
it is all setup correctly
Perhaps you meant _CameraDepthTexture_TexelSize.x instead of _x?
oh, yes; thank you, I didn't see that; but now it throws undeclared identifier for _CameraDepthTexture_TexelSize
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)
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?
Thank you! I'll try this; I just hate these unity render pipelines; all of them have different shader variables and functions and the documentation is so poor :))
I am thinking it should be the same with using (1/_ScreenSize.xy); are there any chances when the depth texture is smaller/bigger then the screen size?
LOD 0 should be the same size, since that above methods use uv * _ScreenSize.xy.
I think SHADERGRAPH_SAMPLE_SCENE_DEPTH will also only be sampling LOD0 - yep it literally calls SampleCameraDepth above.
#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
Think the samples are in the wrong order. The ones you subtract from eachother are meant to be opposites. Swap uvSamples 1 and 2 around
I assume the previous setup with the texelSize should work too, if you do float2 _CameraDepthTexture_TexelSize = (1 / _ScreenSize.xy); before setting the uvSamples
yes they were reversed, still it produces the same weird effect ๐
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
Are you saving the graph after changing the code?
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
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
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
Is that different from the shadow position data I already have? Or do I not even have shadow position?
My node doesn't expose the shadowCoord, only the final value sampled from the shadowmap. So you might need to copy the function to output that.
Oh yup I am using your customlighting.hlsl, I will look for that data in there and add it to the out
got it out without error after initializing it
interesting and soft
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.
I got shadow position, shadow value, light direction, scene depth, I will double back and re-read his replies to see if I can grasp it
I don't have light position but its a directional light so that prooobably isnt needed
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
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.
Matrix math is definitely beyond my current comprehension, but I am tryin to learn 
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
Thats fair
I am curious to try it though, so I'll let you know if I get anything close
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
https://gist.github.com/NedMakesGames/13e64bed3a84e81826b05e5fb0214e70
maybe that light matrix is in here somewhere ๐
https://github.com/Unity-Technologies/FPSSample/blob/master/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs
or here ๐
Too bad SG URP can't just access functions, it would be nice if I could just request unity_WorldToLight
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
Like changing material when the shader detects an edge?
I guess you're using hdrp 7.4.3?
yeah 
Even if there isn't a way to do it in HLSL, we might be able to pass the matrix in. It might just be transform.worldToLocalMatrix for a C# script on the light.
Out of my knowledge unfortunately 
The "Fresnel Effect" node is somewhat like detecting edges (when normal curves away from view direction).
Hard to tell if that's what you want, or actual edge-detection functions on fullscreen depth/color/normals textures like Roberts Cross / Sobel.
On the subsurface scaterring isnt the Compute thickness pass from hdrp what we are after https://github.com/Unity-Technologies/Graphics/blob/master/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ComputeThickness.shader
trying this
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)
Yeah something like this would probably work too. If this shadow method doesn't work out maybe a prepass like this is the next thing to try.
it did a thing on play ๐
Might need the matrix in the first port
oh yeah it did a different thing
I'd also put the result through a Fraction node temporarily, that should help with visualisation
I think instead of the position node we want to try the shadow coord with z value changed to the value from the shadowmap
Like so?
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 ๐
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.
Is that info one of these?
It would be in the MainLightShadow() and MainLightRealtimeShadow(), which calls SampleShadowmap(). Gotta copy those functions and tweak it.
Hm doing F12, ctrl+click, or right clicking on MainLightRealtimeShadow won't take me to it's implimentation, and searching the whole doc its not in here anywhere
Okay after checking Shadows.hlsl, I think it might just be float shadowMapDepth = SAMPLE_TEXTURE2D(_MainLightShadowmapTexture, sampler_LinearClampCompare, shadowCoord.xy);
im guessing its a unity function being invoked and not something you wrote
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.
Oh okay, not an extentsion of customLighting but its own thing
{
shadowMapDepth = SAMPLE_TEXTURE2D(_MainLightShadowmapTexture, sampler_LinearClampCompare, shadowCoord.xy);
}```
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
Can you thread this? Seems pretty involved
Yeah sure
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
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?
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...
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
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
This is done by using a Sprite Lit Graph base instead of Lit
One calculates 2D lighting and sprite masking, other calculates 3D lighting and all that comes with it
but can't you achieve the same results from any base by changing the settings?
No
2D lighting and 3D lighting are entirely different
And in URP in current year are entirely mutually exclusive
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
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.
yeah intendet behaviour, you are essentially saying if the alpha of the image is bigger than .5 then draw pink else draw green
but its drawing both, if i delete the comparison node it looks like this
im not sure i understand
yes its drawing both because the image you have as your precidate input has parts where the alpha is smaller than .5 and some are bigger
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
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?
that is hard to say, a texture atlas will inprove your performance but I couldn't tell by how much, you would need to test that yourself
Not an expert on shaders, but you can try messing with smoothess, or since the mesh Is looking kind of white-ish due to the spot light, maybe toon shading could help for getting more intense colors?
But to be honest it looks sick the way it is!
Ohhh okay, thanks, and regarding the Property block question, is that even posible? Having the same material on cubes but still be able to change their textures individually?
Thanks!
Hmm smoothing is already set to 0, but i didnt think of the toon shader, i'll give it a go, thank you!
Ahhh, okay, you could even mess with specular if you have that on your shader, but from my point of view, toon shading should help to get more intense colors
is that a mesh or a sprite which you have on the left?
Its a sprite with a normal map
I would say it looks like that, because your normal map isn't pixelated and doesn't have a sharp fallof
How do I avoid "completely" dark shadow using directional light as my sun
light baking or realtime gi
baked
i seriously envy you people understanding shaders lol
Set the normal map texture's filtering to Point if you haven't already
Does its resolution match the base texture's resolution?
OH how did i miss that, yeah putting it to point semi-fixed it
The resolution does match as well, might still have to code in a toon shader to make it look just right though
and moving the x y and z axsis dint help
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
yeah should be possible, I would do some kind of wave like calculation (gerstner or whatever) using the uv's as input and then discard any pixels above the water/lava
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
Try (1) reducing the shadow intensity and (2) increasing ambient lighting.
Might be better to ask this in lighting section.
It appears i've failed ๐ , most toon shading tutorials are for 3D and dont really work for sprites, would you happen to know any?
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
Every time I create or connect a node in shader graph, my Main Preview looks like this. Is there a way to fix it?
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
pc
hmm not sure then, what version of unity are you using?
2021.3.19f1
It is really weird. If I click at it multiple times, then it fixes itself
are you using an alpha or beta version?
IDK for sure, guesing, but make sure you save the shader (save button), that might obsolete any old-cache data. At worst case, save it and restart Unity. Also update graphics drivers?
also have you upgraded the render pipeline version? if so its better to delete the library folder manually so the project reimports everything
I am not sure, but I think it's beta
that might the problem
where do I check it?
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
It is 2021.3.19f1 but it doesn't say either it is alpha or beta
Ah its a stable version
Hmmm, is this issue new for you?
I mean its the first time it happens?
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
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.
You mean that you created a shader graph and now you want make a material out of it?
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.
That's not possible. A shader is a program that runs on the GPU. Saying that you want to blend them, is like saying that you want to mix 2 different cars into one car.
What you could do is render the object twice with each shader and then blend the resulting colors somehow.
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
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.
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
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.
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!
its really the same idea tho all you need to make toon shading possible is light and some normals
if the offset parameter is 1 then yes
weird, why do I just see a blank texture then
if you put nothing into the offset is it still blank?
if I hardcode the values like this I get the desired result
ok cool
I would have two properties one for tilling and one for offsetting
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
but in the hardcoded value you had the x minus and y posititve
in the hardcoded value tilling was 3
so offset was tilling - 1
and I multiplied it with -0.5
(3 - 1) * -.5 = -1 not -.5 as you had in the hardcoded value screenshot
wait im stupid
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
do you have your exposed property in your material also set to 2
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
wdym
whats B
in the multiply node A is -0.5 and I want B to be Size - 1
so you want your output to the offset node to be -1?
you are substracting it with -1, that would be the same as if you were adding it with one
ooooh
cause -- = +
I'm dumb
bro
GOOOOD
I hate myself right now
I thought I should put -1 to substract 1
lol
happens
well ty anyway ๐
np, glad it works now
The tiling and offset are handled by the sprite renderer component
You don't usually want to touch it manually
I made a funny effect tho
Is there a better way to achieve this without tiling and offset?
the previews are horrible
For an outline type effect it's fine, but consider that sprites may have considerably different dimensions since you use non-power of two textures, and may end up having entirely different UV coordinates if you use sprite sheets or sprite atlases
hmm
can anyone tell me how do you mask 3d models?
What do you mean by "mask" precisely
make specific region of the model transparent
you can use a texture for that and use that for your alpha channel.
Hey what is this shader called? - is it a toon shader?
Toon would still have a dark shaded side, this just looks unlit.
Has "inverted-hull style outlines", can do that with additional shader passes but it's likely built into the model here
ok ty ๐
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);```
how do you implement LOD crossfading in your shaders? I am using Unity 2022 with URP and shadergraph btw.
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
1170
122
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;
lol hehe, might have worded it very badly, well you can see in the image a plane with black and white stripes (why? don't ask) and then the red overlay (the red part) is where the pixels are underwater (that is the part which is not correct). And yes I am comparing the y value of the pixel with the height of the surface. and I know its hard, thats why I want to do it๐
didn't notice that cyan made such a thing tho
But actually, I like that twitter thread, I should probably do it that way -> generate the mesh inside of the compute shader and then just do some nice effects on that "quad-ish" thing
"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
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
But why do you need the sampler2D? If you're using tex2D there are alternative sampling methods for Texture2D.
float ditherValue = tex2D(_DitherPatternSampler, ditherCoordinate).r;ห because of this
the dither coordinates are calculated at runtime and they depend on the _DitherPattern texture
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.
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;
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.
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?
sampler2D is an older syntax where the texture and sampler data is coupled together
How did you declare _MainTex
Property?
At top of shader?
If so, what is the default value shown as?
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
Show me the code declaration for maintex TEXTURE
this works in another custom effect I made (its a super simpler one)
Forget samplers for a second
there is no declaration, the maintex is whatever is on the screen at the moment
context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, 0);
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
}
}
}
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.
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.
How do you set the _DitherPattern texture in C#?
I have no idea how to use shader code or anything and I have no idea why are there 50 ways to define the same thing nor where to find the API on which ones to use correctly
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.
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);
You said it "was all white", so it's logical for debugging THE SHADER to check how the dither pattern was set and that it is the proper values.
I just want it to work for now, I'll use macros once I figure out how to make this work.
I saw that macros are good because they are cross platform supported or something like that.
fair, but yes, the dither pattern is set up correctly, I've already checked this multiple times before asking here
Yes, depending on the target platform you are building for the macros switch between using sampler2D and tex2D(sampler2d, uv) or Texture2D/SamplerState and texture.Sample(samplerstate, uv);. That way you don't even need to deal with those syntax differences.
thanks, good to know. But for now, I'm just trying to get the logic part of it working
I don't see where you're calcing the dither (I assume you're going for a screen-space dither).
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
But I'm not using these new Post processing frameworks
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
There you go.
I found forums saying i need to use screenPosition : TEXCOORD2 but that did nothing
its still a white screen btw
I would assume the i.texcoord is already the screen pos here
It's in your v2f, but IDK if there's some default vert that
is texcoord and uv not that same?
OK, that. Again, not used to this PP framework.
float2 uv : TEXCOORD0; isn't texcoord also TEXCOORD0?
they calculated it in the frag stage
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?
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
Yeah so i.texcoord should be the screenpos. So maybe try float2 ditherCoordinate = i.texcoord * _ScreenParams.xy * _DitherPattern_TexelSize.xy;?
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
It does look like there's some noise, not sure if that's just the discord compression though
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
Ah, it's probably sampling a mipmap (lower resolution version of the image). I'd try disabling mipmaps on this texture (should be in the import settings)
I downloaded a new texture so I can modify the import settings
changed generate MipMaps to false
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
Output float4(i.texcoord.xxx, 1);
what?
return float4(i.texcoord.xxx, 1);
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
it returns a gradient, left is black, right is white
like so
Good, it will do the same for y if we did that instead of x.
from bottom to up yes
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);
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
but I'm getting this error
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
Yeah, since it's a mod 2 and the value is 0 to 1
dithercord is a float2, and you're in a float4 expression with that error. It doesn't know what to do with it.
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.
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
GTG now, due at GF's...
have fun
whats GF's?
I am at wits end with trying to figure out shaders 
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..
Are you trying to make the shader only affect part of the texture?
Or a shader that displays only a part of the texture
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.
You can use tiling and offset to stretch and move a part of the texture to any desired UV coordinates, and fraction or modulo to repeat parts of the texture
But I'm not sure if that's necessary if your meshes already have UVs that use only a region of the sampled texture
It's not that clear what you're trying to explain. But if I understand... you could just sample the noise using the world space vertex positions rather than the mesh/tile UVs.
Or set a second UV set on the mesh data
That didn't even occur to me..
I might try that..
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 
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.
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
What do you have in the custom shader?
Fog is applied as part of the lighting calculation iirc, so you'll need to override that instead of using unity's default one.
Oh
In The script:?
The shader code
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"
}
Next time use code sharing guidelines
!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.
oki sorry for that
Ok, so what's the issue with this shader?
I cant see the water above me
I would like to see the water but not the terrain limitation
Take a screenshot of the water material when using the custom shader
Actually, that shader is probably not supposed to do what you expect it to do. Where did you get it?
Asset store
Can you share the link?
yeah
https://assetstore.unity.com/packages/2d/textures-materials/water/under-water-fog-wave-effect-179550
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.
yeah i tried tho but thanks
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
Does the sample scene look correct?
yes
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.
thanks
I think the post processing one is the most effective, but also the most expensive. Also, object duplication should work great.
what is the post processing one?
It's a method of generating outlines as a post processing effect.
There are many implementations, so you'll need to google that.
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.
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?
What exactly is the problem?
Where/how did you define the default values?
I'm using URP
i can show a screenshot in a few min thanks
Does it get the defined value if you create a new material with the shader?
No. The Color property is still black, and Vector is still zero
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
No. It should be working imho. Maybe check that the shader is compiled properly.
Thanks. I'll just tinker around
Maybe because your property is not linked to an hlsl property.๐ค
Complete your shader and see if it works then.
Yes, I works๐
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
too much code for me too read through ๐ (don't have the energie for that now). But I know that sebastian puts his stuff on github, so you can use that
Will do, thanks!
You'll want to include some context since your link requires a login
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
@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
Normals can't be black. They're simply a direction vector. The faces are black. But I feel like it's the shadows.
HI, i was asked to post my problem here: I want to use shadergraph skybox in VR (meta quest 2), i havent really found a tutorial specifically for VR but tried following "normal" ones. They suggest using shadergraphs unlit shader, but this brings hardcore visual buggs. Anyone able to help me out?
This is the background not being cleared when rendering.
can you show the camera settings, the shadergraph used, and the material settings
Is this the camera settings you need?
Yep, that looks fine
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
My issue has been fixed,
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
an inverted sphere could actually lead to a better, different outcome. thanks!
any chance you could also help me with my problem I posted in #archived-code-general ? @rare wren
Hi, my main preview window doesn't show anything even when I create a new graph shader, anyone know the problem ?
It's a bug with the Main Preview :
Can still save the graph and preview in Scene/Game though
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.
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)
col is defined as a float, not float4
fair
I suppose you could create a script that stores the mask of visible tiles (1 pixel per tile) in a form of texture, and a postprocess that calculates the world position of each pixel, checks its x and z coordinates and compares it with the mask prepared by script.
If the cave is all on the same Y level, could use the Y axis of the worldspace vertex position to lerp the colour to black. Or the mesh could have vertex colours to tell you where it should fade.
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
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?
displacement would be height map
roughness maps into metallic but you have to use a different setup (the drop down), not sure tho
not sure about AO tho
I guess making your own shader to utilize all of those would be the best
Thank you @keen cloud !
Seems adding a bias to the position based on the normal vector fixes it
I will try this
that improves it a lot. There is still a bit of blackness at the tips of very thin sections but at this point I think that's unavoidable or not worth the effort to fix
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
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?
Well in shaderlab (unity hlsl) yes it is literally called DecodeDepthNormals, but when not using unity I don't think so, thats a unity specific function
after playing with various values I think this is as good as itll get. Happy with this
you sure its working correctly? for me it looks a bit like shadows but inside of the model