#archived-shaders

1 messages ยท Page 61 of 1

bold bolt
#

for me

grizzled bolt
#

Then you didn't complete the process
If your project is well along, changing render pipelines can be a big change so research it first

bold bolt
#

just noticed this

#

are vulkan unknown textures blue?

#

nvm it was just loading weird

grizzled bolt
undone thistle
#

Hello, I am trying to make a shader that I can apply to objects dropped on the ground (just to give their edges a little glow). The thing is, the items already have a shader applied and updating it to my glow shader will change the look of the item. I just want to add glow and nothing else. How would I go about this?

sinful canopy
#

Hey there, I was wondering how I could make a shader graph material that would dissolve all the other materials on an object. Basically, I want the white part of the object to be transparent.

terse blaze
#

Anyone know if there is a node in the full screen shader graph that basically uses the current screen as a texture?? Like render textures would but more of a shortcut?

quaint grotto
#

how do i make a default urp material capable of tiling on a per gameobject basis

#

rather than tiling every object with the same material

quaint grotto
#

thanks

quaint grotto
#

this is what i tried


var mats = GetComponent<MeshRenderer>().materials;
foreach (var mat in mats)
{
    var mpb = new MaterialPropertyBlock();
    //adjust uvs to match scale change
    mpb.SetVector("_MainTex_ST", new Vector4(1, (float)scale, 1, 1));
}
go.transform.localScale = new Vector3(1, (float)scale, 1);```

its not clear to me how it links to the materials
quaint grotto
#

will that work in edit mode aswell

mental bone
#

I dont see why not

quaint grotto
#

i tried this:

var renderer = go.GetComponent<MeshRenderer>();
var mats = renderer.sharedMaterials;
foreach (var mat in mats)
{
    var mpb = new MaterialPropertyBlock();
    mpb.SetVector("_MainTex_ST", new Vector4(1, (float)scale, 1, 1));
    renderer.SetPropertyBlock(mpb);
}

but the values in the inspector didnt change

mental bone
#

Hmm for multiple materials I believe you should provide a mat index to the set method as well. It is also good advice to first get the property blocks from the renderer modify them and set them back

regal stag
terse blaze
regal stag
#

@quaint grotto should avoid using MaterialPropertyBlocks in URP as they break the SRP Batcher compatibility. Better to instead use GetRenderer().material which'll create a material instance.

_MainTex_ST likely won't work the default URP material, the reference would be _BaseMap_ST instead. It would be set to Vector4(tilingX, tilingY, offsetX, offsetY);.
But there's also .mainTextureOffset/.mainTextureScale that should work. Or .SetTextureOffset()/.SetTextureScale()

Creating a different material for every object probably isn't ideal. Probably better to keep references to the materials and reuse them if the tiling matches. Or just manually create & assign the materials.

sleek radish
#

Sorry, I'm new to shader graph. Why isn't my texture showing up on my object?

#

I am using URP btw

regal stag
# sleek radish Sorry, I'm new to shader graph. Why isn't my texture showing up on my object?

If you mean the result isn't what you expect in scene, these are things to check :

  • Is graph saved? (Save Asset in top left)
  • Is texture assigned to the material, and DetailStrength set to something larger than 0
  • As the texture sample uses UV0 input, is the mesh you're applying the shader to UV unwrapped

You can also assign default values to the properties in shader graph (click property, set default field under Node Settings tab of Graph Inspector window), that will show better previews in the graph, if that's what you mean.

sleek radish
regal stag
# sleek radish Its just the following image, It shouldn't need to be uv unwrapped i dont think:

Meshes need to be unwrapped if you use the default UV0. That accesses the first UV channel in the mesh, it's what tells the shader how to apply the texture to the model.
(There are alternatives, like Triplanar mapping but that's more expensive. You'd likely just want to unwrap your model here.)

Also, this is a normal map so you'd typically use Normal mode on the Sample Texture 2D and connect to the Normal (Tangent Space) port, not Base Color.

sleek radish
regal stag
#

You unwrap the model (in software like Blender), not the texture. If you google "UV unwrapping tutorial" you should get some info.

sleek radish
regal stag
sleek radish
supple condor
#

does anyone know how to fix this shadow in cutout texture ?
I've looked on different sites, but I haven't found anything.

low lichen
ebon basin
#

Welcome to the next few weeks of trying to minimize self-shadowing on your quads

supple condor
low lichen
low lichen
supple condor
#

like this

supple condor
low lichen
#

Are you able to look at the sprite side on, or does it rotate to always face the camera?

supple condor
#

it rotate to always face the camera

low lichen
#

Okay. I know the Standard shader doesn't have that behavior, so that's happening by some other means. Do you have a script on the object that might be doing that?

supple condor
#

no, it's just the particle system to make this, and the box collider

ebon basin
#

The shadow shouldnt render like that with a basic lookat script, so it's being alligned in the shader, no?

low lichen
#

I don't have much experience with shadow casting particles, but this sort of problem can be explained by the particle system orienting itself to face the shadow mapping camera, which will make it appear to be facing the source of light when you look at its shadow

supple condor
low lichen
#

Oh, so you're talking about the shadow that it's receiving, as opposed to the shadow it's casting on the ground?

ebon basin
#

I actually find that pretty bizarre to use the particle system for this, but hey if it works

supple condor
#

on the image itself

low lichen
#

Because the shadow it's casting is obviously wrong here. The shadow is flipped, with the hanging straps on the wrong side, and the feet are not aligned.

supple condor
#

yeah, but when it turn to the right side, the shadow turns with it

low lichen
#

But both issues are symptoms of the same problem. The billboard behavior is rotating the sprite separately for the main camera and the shadow camera.

#

This seems to be an issue with Particle System, but it's hard to call it a bug because you're using it in a very unconventional way.

#

Since this is for Tabletop Simulator, I'm assuming you can't create your own scripts to put on this object? And that's why you're resorting to hacks like using Particle System to draw one persistent particle with billboarding?

ebon basin
#

Funny thing is, from the perspective it does look like the shadows should be aligned like that, it's just that they need to be panned out a bit more

ebon basin
#

because they are just too inward to the sprite that it's self shadowing

low lichen
# supple condor yes

Well if you want to continue using Particle System for this, then this is not fixable.

#

Alternatively, you can create a shader that does vertex displacement to rotate the mesh to always face the camera.

ebon basin
#

This isn't just a particle system problem though, it's hard to get the shadowing to the base of a quad without it shadowing itself, and usually you'll have to use a bunch of tricks to get it working in URP.

#

You can just disable intake shadows completely if you want

supple condor
#

oh okay

then, thanks for explain to me

green swallow
sinful canopy
#

Hey there, I was wondering if there is a way to make a dissolve shader that affects all materials on an object, without changing the values of those materials.

sinful canopy
forest sail
#

Hello! I am developing a VR app for Quest 2 using unity that involves loading OBJ files during runtime. The asset I found to do the importing requires the "Standard (specular setup)" shader to be enabled in order for the files to show up. But when I have this specific shader enabled the build time goes from 1-3 minutes all the way up to 20-30 minutes. I included a screenshot of the longest part of the build process. Has anyone encountered this before and is there any way to use this shader without such long build times?

keen egret
#

I've been trying to do this for a while now, but I can't figure it out. Can someone help?

#

I want to recreate the Night Vision effect

grand jolt
#

Hi, Iโ€™m trying to get a shader to hide all objects above the player for multi-story cutaway buildings (including furniture, monsters, other players, etc) anyone know how I can do this? Do I have to make everything in the whole game use the same shader? Can I use some sort of clipping plane?

quaint grotto
#

Instantiating material due to calling renderer.material during edit mode. This will leak materials into the scene. You most likely want to use renderer.sharedMateria

#

this is the issue

native spoke
#

Camera Depth Texture Bug for a heat distortion trail
Hello everyone - i am trying to make a heat distortion trail for a sword swing so it looks like the air is bending in it.
But it create a lot of _CameraDepthAttachment_1069x667_Depth_MSAA4x and also _CameraNormalsTexture_1069x667_R8G8B8A8_SNorm_Tex2D_MSAA4x. Does anyone know why that happens and why it increase my memory usage so much. Here are some images for it and from the shader:

grand jolt
tight phoenix
#

How do I refactor this so that I can fill each cell in a specific order?

#

the order being either rows or columns, but preferable the order being any order I want

#

essentially just a direction as the order, where 0,1 or 1,0 does rows or columns sequentially, and other values do the inbetween

#

its getting close but its still not right

#

I cant control what direction the gradient fills in from

#

no matter what variables I use, I cannot get the exact specific look I am trying to get and its immensely frustrating which is only making it harder

#

and I need help to solve this, I havent been able to do it on my own

tight phoenix
#

What's the mathematical formula that takes in a grid of XY dimensions, and a vector2 direction, and returns a sequence that visits each grid space sequentially, where visit is defined as containing a value exactly 1 greater than the previous cell?

#

I want every single cell to fill in exactly after the previous finishes, which means each cell must have a value of +1 relative to the previous cell

#

I know for sure a formula exists that solves it

#

where no matter what the dimensions are the direction returns cells that are all +1 from previous cell

#

its so easy to verbally describe the relationship but impossible to write trigonometry same

#

I hate math so goddamn much

low lichen
tight phoenix
#

Grid of X/Y size.
Every cell is a gradient value between 0 and 1 in a direction
Every cell adds an integer to the entire cell
the 'sequence' is sent to a Step function, step now fills each cell sequentially

#

things that must be variable:
the direction of the sequence
the direction of the gradient within the cell
the xy dimensions of the cells

#

since words are hard

#

here is a gif that is almost working but not working at all the way I want

#

this is at like 80% of the way to done except the problem is beyond my knowledge and ability to solve, but it MUST be solved and i must be the one to solve it but I cant solve it so I have to ask for help to solve it

#

there's no other path forward

low lichen
tight phoenix
#

what I think will do that is to add +1 to every sequential cell

#

pictured: cells not completely filled before the next cell is already beginning to become filled

#

what I actually want is to add +<any variable> to control the rate of cell fillage eg. I could make it do one cell at a time, or all cells, or some other thing

#

but I canteven get one cell at a time going

#

big ol not working

low lichen
#

So can I think of this as you have some cellsThatShouldBeFilled number that you're increasing, and as it goes up, cells should fill in some sequence, I guess left-to-right and from top-to-bottom, but cellsThatShouldBeFilled is a decimal number, so if it's set to 3.5, then the first three cells should be completely full, and the fourth half full?

tight phoenix
#

drew this before reading what you just posted, let me explain and then read yours

#

if the grid was 3 x 3 for example, I want to add the listed value into the cell as shown, and that value would be determined by a direction vector, shown in green

#

but I want it to work on any grid size or direction value

#

you can think of it like wrapping around a line continuously

#

unless Im just completely dumb and this is not possible to achieve

tight phoenix
low lichen
#

So it's just a bunch of rows that have a height and width.

tight phoenix
#

another example, if the direction vector was exactly 45 degrees, this would be the expected cell fill sequence

#

pretend my diagram was square

#

but its supposed to work no matter what XY dimensinons and no matter what direction

low lichen
#

Okay, but if you had this working properly, would I be able to visually count how many columns there are, like I can in your non-working WIP?

tight phoenix
#

which currently I can't get the cells to fill sequentially outside of very specific confluxes of magic numbers that don't meet my use case

tight phoenix
low lichen
tight phoenix
#

they wouldnt have numbers in them

low lichen
#

So the two cells that you labeled "2" would fill at the same time?

tight phoenix
#

in the second example yes

low lichen
#

Now you've lost me.

tight phoenix
#

I want to fill cells

#

by row and column

#

sequentialyl

#

no subsequent cell fills before the previous finishes, or rather the sequence is a variable

#

so I can say, start the next cell at 0.5 of the previous, where 1 would be wait completely

#

and 0 would be all cells fill at the exact same time

#

hm writing it like that, my sequence value would be multiplied by whatever input value then added UnityChanThink

#

still not really working

loud dagger
#

All is contained in this simple material graph ๐Ÿ‘‡
But there are some things to consider when implementing it, this setup supports tiling based on scale only on 2 axes, which means that all models that'll use it'll need to be oriented along the required axes to avoid artifacts
2/7

tight phoenix
#

here is getting almost there, a little closerm 90%

#

but as you can see its still acting like a 'wave' and not filling cells sequentially

tight phoenix
#

I had to throw in a ton of ugly hacks, random multiplies, remaps everywhere to get it to do this

#

this is the behaviour I want and was trying to describe

#

but that above ONLY works for that exact pile of ugly hacks magic number

#

I want it to work for any grid size without relying on shitloads of magic numbers

grand jolt
#

I posted here a few times, wondering if someone can help me. Trying to make a clipping shader for all objects above the player.

low lichen
# tight phoenix

Okay, but where does the direction come in? Is this a hard-coded example where the direction is up (or left/right)?

tight phoenix
#

in that example its hard coded yeah

karmic hatch
tight phoenix
#

Otherwise yeah that looks 100% exactly spot on; the sine was just for debugging the values though lol

karmic hatch
tight phoenix
#

Does that mean its not neccessary in some way?

#

Ooh right like its so that the shader doesnt fill the entire shader toy window?

karmic hatch
#

Yeah exactly

tight phoenix
#

Gotcha, now I understand ๐Ÿ‘Œ

#

Yeah this looks great, thanks a bunch. I knew it could be solved since there were bery clear mathematical relationships but I knew not how to find them ๐Ÿค”

karmic hatch
#

Tbh I just messed around until it worked, no rigorous calculations really

tight phoenix
#

I assume some variables changed was the reason why

#

it looks like some cells are actibating out of sequence

karmic hatch
#

Oh I was messing around and might've saved after changing DIREC

tight phoenix
#

๐Ÿ‘€

#

got a meeting bbl

karmic hatch
#

If it's (GRIDNUMBER, 1) then it'll fill in order

grand jolt
#

hey, I'm working on a horror game, and I'm very new to shaders
i managed to get this edge detection effect working, in which a sphere gameobject slowly expands and whatever intersects its surface is highlighted
is there any possible way i could get the edges of geometry inside the sphere to also be highlighted, such as the corners of these walls?

#

(shitty mspaint example)

#

looking more into this,

ocean geyser
#

how can I create a similar effect to sprite renderer tiling, while using Shader-graph and "ellipse" node?

That is:

  1. I have a shader-graph that generates a circle using Ellipse node.
  2. I have a wide rectangle which uses that shader graph. The UVs are from (0, 0) to (width, 0). For example, width would be something like 11.
  3. The end result is a single ellipsis, but I want to do much like tiling a texture - and end up with multiple ellipses.
green swallow
tight phoenix
#

xy and and not just a value?

#

porting this over im just sorta guessing at what all thes equvuilate to

#

void ShaderGridFiller_float(float2 uv, float SQUARESIZE, float GRIDNUMBER, float FILLLEVEL, float2 DIREC, out float indexer)
{
    float majorFill = floor(uv.x * GRIDNUMBER) / DIREC.x + floor(uv.y * GRIDNUMBER) / DIREC.y;
    float minorFill = frac(uv.y * GRIDNUMBER);
    float maxFill   = abs(dot((GRIDNUMBER - 1.) / DIREC, float2(1,1)));
    float majorBias = max(DIREC.x, DIREC.y);
    float totalFill = (majorFill + minorFill * majorBias) / maxFill;
    float fillCheck = (majorFill + minorFill / majorBias) / (maxFill + 1. / majorBias);

    indexer = step(0., fillCheck - FILLLEVEL);
}```
testing this now
#

also I just noticed no value of that is the 'time' yours was using, how do I actually -use- this?

#

I will try to figure out how its meant to be used and where I pass in 'time'

#

oh FillLevel must be that

tight phoenix
#

it just returns black no matter what parameters I pass in

#

fillcheck returns broken pink, I assume its a division by 0 happening?

#

#define SQUARESIZE iResolution.y/2.0.9
#define FILLLEVEL (0.5
sin(iTime/2.)+0.5)
#define GRIDNUMBER 5.
#define DIREC vec2(5,1)

is the problem that your pass in values arent just static values, they're sub methods?

#

oh progress ๐Ÿ‘€

#

hm little confused how direction is meant to be used

#

making a gif

#

oh is direction supposed to be the direction of the gradients?

#

or something else? I feel like this thing is missing a lot of the 'directions' its supposed to have

#

like 0, 1 is a direction but it returns black and I dont know why

#


void ShaderGridFiller_float(float2 uv, float2 direction, float2 resolution, float time, out float indexer)
{
    float SQUARESIZE = resolution.y / 2. * 0.9;
    float FILLLEVEL = 0.5 * sin(time / 2.) + 0.5;
    float GRIDNUMBER = 5.0;
    
    float majorFill = floor(uv.x * GRIDNUMBER) / direction.x + floor(uv.y * GRIDNUMBER) / direction.y;
    float minorFill = frac(uv.y * GRIDNUMBER);
    float maxFill = abs(dot((GRIDNUMBER - 1.) / direction, float2(1,1)));
    float majorBias = max(direction.x, direction.y);
    float fillCheck = (majorFill + minorFill / majorBias) / (maxFill + 1. / majorBias);
    
    indexer = step(0., fillCheck - FILLLEVEL);
}
#

my current broken version

karmic hatch
tight phoenix
#

I assume ive fucked it all up in my attempt to port it from GLSL to HLSL

#

oh yheah saquare size isnt even being used because it was multiplying the UV before

karmic hatch
tight phoenix
#

now I dont know what I should do to progress forward in making this do what I intended

karmic hatch
#

This is the relevant part; it calculates the UVs for the square at the top and they just range from (0-1) in x and (0-1) in y

#

I'm assuming you're applying this to a quad or something and it doesn't matter what happens outside that UV range

tight phoenix
#

Yeah its a quad 0 to 1 value range correct assumption

karmic hatch
tight phoenix
#

I think im just making it worse

#

it keeps ping-ponging but that behaviour was just because I was using sine to show the value scrub

#

okay I see the sine inside Ill.. not remove that

#

because its already broken and im breaking it worse with each attempt to fix the last thing I broke ๐Ÿ˜ฌ

karmic hatch
#

Both components of direction should be >0 and FILLLEVEL should be an integer if you want the grid to line up with the UVs (I think HLSL casts nicely where GLSL doesn't? But no harm leaving it as float)

#

I think if both components of direc are integers, then the filling lines up with the cells (otherwise cells along the diagonal fill line will be filled different amounts)

#

Having FILLEVEL an input would be best I think, just so it's easier to change in future

tight phoenix
#

debugging variables to see what they're doing outside of the black box, progress

#

cells and gradients I see them now ๐Ÿ‘€

#

I am a little confused as to why 'Direction' changes the size of the cells

#

direction and cell size should be unrelated?

#

im also confused why direction blows up if either axis is a 0.
I know the answer is because the divide by zero

#

but that shouts red alerts to me

#

that direction is not a direction

#

because directions can have zero values

karmic hatch
tight phoenix
#

I am trying to parameterize every single assumed value

#

assuming that I dont want to assume anything, how do I unassume them

#

or rather, what do I want to not assume?

#

The assumption of value ranges 0 to 1 is not an assumption I want to change ๐Ÿค”

#

I am slowly trying to expose what is assumed to passed in variables so far

karmic hatch
tight phoenix
#

Ohh

#

okay so the direction was not a direction, it was 'fill this many cells before next'

#

which explains why a 'direction' of 1 , 1 filled in 45 degrees

karmic hatch
tight phoenix
#

okay I see now, its essentially flood filling out

#

with this particular conjunction of values

#

Okay my comprehension is growing, I feel able to evolve it further now UnityChanThink

#

Thank you for the continued support ๐Ÿซ‚

karmic hatch
#

you're welcome :)

tight phoenix
#

If I make grid number not a float but a float2, what then does become this value?

#

is this how I should be changing grid number?

#

its obvious to apply x to y and y to y

#

but that instance of its use isnt to a specific channel

karmic hatch
#

hmm no it doesn't fill all the way in the shadertoy...

#

oh looks like it should stay (1,1), and replace GRIDNUMBER there with its float2 counterpart

#

(because the (1,1) is from the max value of the UVs, not anything related to the grid)

tight phoenix
#
void ShaderGridFiller_float(float2 uv, float2 dimensions, float2 direction, float time, out float2 indexer2, out float4 debug)
{
    float cellFill = floor(uv.x * dimensions.x) / direction.x + floor(uv.y * dimensions.y) / direction.y;
    float gradientFill = frac(uv.y * dimensions.y);

    float maxFill = abs(dot((dimensions - 1.) / direction, float2(1,1)));
    float majorBias = max(direction.x, direction.y);
    float fillCheck = (cellFill + gradientFill / majorBias) / (maxFill + 1. / majorBias);
    
    float indexer = step(0., fillCheck - time);

    indexer2 = float2(indexer, fillCheck);
    // Set debug output
    debug = float4(cellFill, gradientFill, maxFill, fillCheck);
}
#

I am renaming the variables to make them clearer to myself

#

major and minor fill were the cell value and the gradient within the cell

#

but I am not sure what maxFill, majorBias, and fillCheck do with that new understanding ๐Ÿค”

#

like what does it mean to max fill something, that's just a value of 1 right?

karmic hatch
#

maxFill is just so that instead of going from empty to full over a range from 0 to some random number, it normalises it so it fills over the (0-1) range

tight phoenix
#

oh remaps to a normalized range, gotcha

karmic hatch
#

And majorBias converts between the units for cellFill and gradientFill, so it knows how much gradientFill equals one cellFill

tight phoenix
#

hmm and this is FillCheck

#

cell+gradient divided by how much gradient per cell

#

divided by the remapped 0 to 1 range

#

oh and then we step it

#

its the threshold

karmic hatch
#

yep

tight phoenix
#

for some reason I was missing the indexer = step

karmic hatch
#

hopefully it works now?

tight phoenix
#

Yeah im almost done, its at that 99% point where I am trying to remember what I was even intending to do with it before getting neck deep in the trenches

#

I think I want to change the direction of the gradient per cell

#

is the extra thing I was about to do

#

so I have to check what I was doing before

#

void GridWithGradient_float(float2 uv, float2 gridDimensions, float2 gradientDirection, out float outer)
{
    float2 cellUV = frac(uv * gridDimensions);

    float2 cellCenteredUV = cellUV - float2(0.5, 0.5);
    float gradientValue = dot(cellCenteredUV, gradientDirection);
    outer = (gradientValue + 1.0); //* 0.5;
}```
#

this was my old bad code

#

but it was full of flaws like I coudnt forcefilly just say 'make it a range of 0 to 1

#

it constantyl returned values out of range

karmic hatch
tight phoenix
#

Yeah that was my problem right there bingo

#

I couldnt make it still range from 0 to 1

#

as soon as the gradient isnt moving purely in one direction

#

because when you rotate it even a little bit now there's values beyond if the range WAS 0 to 1 across a square UnityChanThink

#

right other things I wanted to do was adjust how fast the cells fill even, which in my mind would be achieved by adding more cell per cell

#

like your version is carefully constructed to stop lerping one cell and begin lerping the next cell at -exactly- the end moment

#

but what if i want a little before a little after, some play to make it feel and look right

karmic hatch
#

I think you could do that by messing with majorBias

#

It would still start filling at t=0 so if you want the same delay at the start and end you would have to do something a bit more complicated

karmic hatch
tight phoenix
#

Will try those now

#

Ive also been working on this since 8am so my brain is tried, its 5pm here

#

literally none of what I did before you linked my your shadertoy version ammounted to anything ๐Ÿ˜ฌ

#

Anyways we got the results now

#

I was skilfull in reaching out for help, even if I didnt find the answer by my own hands ๐Ÿ˜ฃ

#

immensely frustrated and pretending im not because this always happens even though I know no one can know everything and do it all ๐Ÿ”ฅ
but thats mental health, not trigonometry

frigid silo
#

Anyone here having luck reading a rw buffer from a vertex shader filled via the shader's vertex id?

compact reef
#

which shader does support Reflection Probe except unity's Standard Shader!!!??

open patrol
#

Hi i got question is there any good guide that could help me recreate swirl effect from world of warcraft

karmic gulch
#

i dont know if this is the right channel to ask this but i want to know if anyone know why my build is all pink like this
it's normal when run in the editor but pink in the build version

quaint grotto
sacred stratus
#

Is it a common optimisation tecnique to start the vertex shader with indices, and then read out the vertex data from a uniform buffer?
This seems very good for rendering huge ammounts of simmilar meshes, since compared to batching you can decide what mesh you want to be drawn

quiet osprey
#

I'm having some issues with the "Power" node.. or rather the pow function in HLSL.. Its probably me not properly understanding stuff. But if I do something like this

float3 a = <world space normal>;
float b = 2.0;
float3 c = pow(a, float3(b,b,b));

The result in C seem to be absolute values as soon a b is assigned a non integer value.

#

To clarify, I'm doing this in ShaderGraph

#

the code in "MyPower" is:

Out = pow(A, float3(B,B,B));
#

Same thing happens with the regular power node

#

output with integer values on B

#

Output with non-integer values (in this case 4.2)

amber saffron
quiet osprey
tight phoenix
#

did I make a mistake in recreating these nodes in code? its not returning the same result and im not sure why

#

    float gradientFill2 = frac(uv * dimensions) - halfCell;
    gradientFill2 = dot(gradientFill2, gradientDir) + halfCell;
#

left is the expected return, right is what I am gettting instead

regal stag
tight phoenix
#

I'm a little confused, which part of them should be a float2? the gradientfill debug value?

#

Im trying to debug right now why its failing to look like that frac right from the first function

#

making this a float2 just breaks everything

#

oh its this line being float2'd?

regal stag
#

There's a bit of a mix because uv is float2, but dot() returns a float

tight phoenix
#

I think I understand now - I wanted a float eventually but i converted to a float too early (at the UV step instead of the dot step)

amber saffron
#

The dot needs to take two float2 inputs, after it can be a single float

regal stag
#

Yeah, I'd probably change it to

float2 gradientUV = frac(uv * dimensions) - float2(0.5, 0.5);
float gradientFill = dot(gradientUV, gradientDir) + 0.5;
tight phoenix
#

will do that now ๐Ÿ‘

#

pebkac UnityChanThink

wooden galleon
#

Multiple Pass, Stencil, Surface Shader Conversion from built-in-render pipeline to URP

I have a shader in Unity which is compatible with the built-in render pipeline. Which I want to convert into URP

Here is the basic structure

Shader "test/ClothStencilTwoPassDefault" 
{
    Properties 
    {
        //some properties
    }

    SubShader 
        {
            Name "Pass 2"
            Tags {"Queue"="Geometry-1" }

            Cull Front
             Stencil
        {
            Ref 0
            Comp GEqual
            Pass Zero
        }
       
        CGPROGRAM
            //Some variable declearation
 
            void surf (Input IN, inout SurfaceOutputStandard o) 
            {
                   //surface shader function magic
            }
            ENDCG

            Name "Pass 1"
            Tags {"Queue"="Geometry-1" }
            Cull Back

            Stencil
        {
            Ref 1
            Comp always
            Pass replace
        }

            CGPROGRAM

        //Some variable declearation
 
            void surf (Input IN, inout SurfaceOutputStandard o) 
            {
                    //surface shader function magic
            }
            ENDCG
        }
    FallBack "Diffuse"
}

I have tried using a BETTER SHADER https://assetstore.unity.com/packages/tools/visual-scripting/better-shaders-standard-urp-hdrp-187838
Here is the documentation of the same https://docs.google.com/document/d/1UUSIOIiq4dK8OMDyGHqpsURxsYBYmwKaPo0zOZ5vkHk/edit

I am not able to find the syntax to implement multipass with stencils in a better shader.

The goal is to get the shaders to work in URP.

short elk
#

Hey guys. I have a question - what is the most efficient way to blend more than 2 normal maps in Unity with Mask? For example - I can lerp 2 normal maps and it works fine, but when im trying to add one more lerp with one more normal map its giving me a bad result. Normal Blend its not good solution because it doesnt have input for mask

amber saffron
violet ruin
#

idk if it falls here, but the characters in my scene kind of blend in with the background and stuffs
how can I make the characters stand out?

amber saffron
violet ruin
#

so something like a bit shiny or something
or maybe a little brighter?
ya, the ground is like really reflective as well. No idea about how i got that

amber saffron
violet ruin
#

oh thanks for the tips
Will try them out, thank you

drifting osprey
#

@regal stag hey that blur shader you gave me is a great addition, however I can't seem to get it working in conjunction with the normalmap distortion noise and not get visual artifacting in the shader... Could you help me out, please? notice how in game view (second panel), the shader only stacks the particle effect vertically but not horizontally.

wooden galleon
amber saffron
#

Second : While you can write shader in URP with shaderlab, URP doesn't support the surface shader declaration that handles all the boilerplate for declaring required passes in the built-in renderer.
The easiest is to re-do the shader with shadergraph.

regal stag
short elk
robust stone
#

So I've been editing Kelvin van Hoorn's blackhole shader to work in vr and I'm getting there, but now the gravitational lensing makes sense in the left eye, but in the right eye the whole sample scene color looks to move when I move my head around.

Using single-pass and urp, anybody got an idea how to fix?
(It's a raymarching shader btw if that matters)

hearty obsidian
#

If I want to draw a mesh with a vertical gradient that starts at the bottom-most vertex and ends at the top-most vertex, do I have a way to do it without manually inputting vertex positions?

karmic hatch
hollow wolf
#

is there anyway to make transparent decal not overlaping with each other.it looks like this, but for decal

ebon basin
#

For shadows, right? I think I ran into this problem before but instead used some mask and did some replacement methods using render objects.

#

No clue if it was optimal, but it worked.

drifting osprey
hollow wolf
ebon basin
# hollow wolf can you tell me how to do the setup for this?

Don't really have Unity open right now, but it's basically just some stencil stuff. You could probably just do it all in a shader, but if you've not used stencils before, you can get an idea by messing around with render objects since their settings compile just as quickly.

ebon basin
#

Maybe look up stencil blob shadows. I do believe people develop them this way.

drifting osprey
#

this is the custom blur shader: `// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,)' with 'UnityObjectToClipPos()'

Shader "Custom/Heat Blur"
{
Properties
{
_Factor ("Factor", Range(0, 5)) = 1.0
}
SubShader
{
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }

    GrabPass { }

    Pass
    {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #pragma fragmentoption ARB_precision_hint_fastest

        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
            float2 uv : TEXCOORD0;
        };

        struct v2f
        {
            float4 pos : SV_POSITION;
            float4 uv : TEXCOORD0;
        };

        v2f vert (appdata v)
        {
            v2f o;
            o.pos = UnityObjectToClipPos(v.vertex);
            o.uv = ComputeGrabScreenPos(o.pos);
            return o;
        }

        sampler2D _GrabTexture;
        float4 _GrabTexture_TexelSize;
        float _Factor;

        half4 frag (v2f i) : SV_Target
        {

            half4 pixelCol = half4(0, 0, 0, 0);

            #define ADDPIXEL(weight,kernelX) tex2Dproj(_GrabTexture, UNITY_PROJ_COORD(float4(i.uv.x + _GrabTexture_TexelSize.x * kernelX * _Factor, i.uv.y, i.uv.z, i.uv.w))) * weight

            pixelCol += ADDPIXEL(0.05, 4.0);
            pixelCol += ADDPIXEL(0.09, 3.0);
            pixelCol += ADDPIXEL(0.12, 2.0);
            pixelCol += ADDPIXEL(0.15, 1.0);
            pixelCol += ADDPIXEL(0.18, 0.0);
            pixelCol += ADDPIXEL(0.15, -1.0);
            pixelCol += ADDPIXEL(0.12, -2.0);
            pixelCol += ADDPIXEL(0.09, -3.0);
            pixelCol += ADDPIXEL(0.05, -4.0);
            return pixelCol;
        }
        ENDCG
    }

    GrabPass { }

    Pass
    {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #pragma fragmentoption ARB_precision_hint_fastest

        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
            float2 uv : TEXCOORD0;
        };

        struct v2f
        {
            float4 pos : SV_POSITION;
            float4 uv : TEXCOORD0;
        };

        v2f vert (appdata v)
        {
            v2f o;
            o.pos = UnityObjectToClipPos(v.vertex);
            o.uv = ComputeGrabScreenPos(o.pos);
            return o;
        }

        sampler2D _GrabTexture;
        float4 _GrabTexture_TexelSize;
        float _Factor;

        fixed4 frag (v2f i) : SV_Target
        {

            fixed4 pixelCol = fixed4(0, 0, 0, 0);

            #define ADDPIXEL(weight,kernelY) tex2Dproj(_GrabTexture, UNITY_PROJ_COORD(float4(i.uv.x, i.uv.y + _GrabTexture_TexelSize.y * kernelY * _Factor, i.uv.z, i.uv.w))) * weight

            pixelCol += ADDPIXEL(0.05, 4.0);
            pixelCol += ADDPIXEL(0.09, 3.0);
            pixelCol += ADDPIXEL(0.12, 2.0);
            pixelCol += ADDPIXEL(0.15, 1.0);
            pixelCol += ADDPIXEL(0.18, 0.0);
            pixelCol += ADDPIXEL(0.15, -1.0);
            pixelCol += ADDPIXEL(0.12, -2.0);
            pixelCol += ADDPIXEL(0.09, -3.0);
            pixelCol += ADDPIXEL(0.05, -4.0);
            return pixelCol;
        }
        ENDCG
    }
}

}`

#

the shader effect should more or less end up looking like this (quick edit in Paint.NET for reference)

karmic hatch
#

(just requires altering ADDPIXEL)

drifting osprey
karmic hatch
drifting osprey
#

the shader code I pasted is ONLY the blur effect. it is sepparate from the normalmap distortion shader code

#

would also be great if there was a way to make a curve for the distortion shader that reduces the strength of the normals over lifetime instead of reducing the opacity of the particle.

#

seriously, I'm willing to pay if someone can help me solve this shader issue

green parcel
#

Hey guys to you have any idea how could improve the transition from sand to grass?

green parcel
#

okay how can i add that

#

just add noise

#

that is my calculation for t lerp value

regal stag
green parcel
#

ok i try that

#

it only should apply that to the borders yk

regal stag
# green parcel it only should apply that to the borders yk

Then mask the noise to the border first. To do that, calculate a value of 1 along the border and 0 everywhere else. I'd probably take the G axis of the object position like you do above, Subtract to the halfway point (I guess maxSandHeight-minGrassHeight), Absolute and Smoothstep to control the falloff.
Multiply it with the noise before adding.

#

Or maybe just use the t value you already have for masking too (multiply noise with t instead of adding). Hard to debug off the top of my head.

green parcel
#

i got it

#

thanks m8

#

looks much better

oblique bramble
#

hello there, Im pretty new to shaders but I want to start adding some to my game. at the moment everything looks like unity plane scenes. I want to go from this:

#

to something like this :

#

How do I start ...

#

:/

desert orbit
oblique bramble
#

ok...

#

so you say when I just texture the models it will look better

#

Then another question,what are shaders good for?

desert orbit
#

Take a look at the pinned resources here. Top right.

prime shale
#

You can only shade a certain object to look so good

#

The object having good modeling/textures goes a really long way

#

And having proper shading is what will really take it to the next level

oblique bramble
#

So โ€ฆ I wanted to keep the low poly stile in the game. But get rid of the Unity default look

#

Can I use shaders to achieve this?

#

Because Modelling and texturing is done in the game

#

Or is it lighting?

grizzled bolt
oblique bramble
#

Ok thanks

#

Im really sorry for my inpercise questionsโ€ฆ

#

Im new to unity and most of the time just work aloneโ€ฆ so I nearly never use the accurate words for the things I mean

long bramble
#

Anyone have an idea whats wrong with this compute shader? ```
Shader error in 'GenerateMapData': syntax error: unexpected token 'point' at kernel CSMain at GenerateMapData.compute(20) (on d3d11)

(I'm getting this error for every line that references "point" in the code)
```glsl
#pragma kernel CSMain

struct Point
{
    float3 color;
    float height;
    float isSpawnPoint;
};

RWStructuredBuffer<Point> points;

float chunkWidth;
float chunkPosition;
float chunkResolution;

[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    Point point;

    point.color = float3(54.0f, 2.0f, 234.0f);
    point.height = 5.0f;
    point.isSpawnPoint = 1;


    uint index = id.y * chunkWidth + id.x;

    points[index] = point;
}

Thanks!

azure palm
#

(Posted in wrong area before) Hey I'm getting a few errors on my shader file and I'm not too sure how to fix this cause I'm only just learning. What would be the issue here?

vocal narwhal
azure palm
#

Unsure really, I only just created it

#

Ill screenshot

#

this is the error I get

#

But it doesnt look like theres an unexpected }

#

none that I can see at least

vocal narwhal
#

You can't have an empty subshader, you'll have to finish writing your shader for it to function properly

#

though it does raise the question, why are you not just using Shader Graph?

azure palm
#

Im following a video cause im only just starting shaders

#

But even the boilerplate code errors out

vocal narwhal
#

This will create an unlit shader for you to work from

azure palm
#

yea I did that and it gave me a script that was pretty much all errored out

#

Has a bunch of unexpected tokens and being unable to open files

vocal narwhal
azure palm
vocal narwhal
#

There are no errors

#

Are these errors in the Shader inspector in Unity? Because many IDEs cannot provide accurate autocomplete for shaders.

azure palm
#

So it should just work?

vocal narwhal
#

Yes

azure palm
#

alright, was just confused cause it looks like a normal script

vocal narwhal
#

Afaik only JetBrains Rider will provide proper syntax highlighting for shaders. Iirc Visual Studio Community added some support, but if you're using it, support must be patchy.

azure palm
#

Ah right

#

Cool as then, thank you :)

agile token
#

I seem to be misunderstanding something fundamental here.
I've been experimenting with some shader techniques and it hasn't been going well. I have tracked the problem down to a fairly basic assumption being incorrect.
If you look at the code, you will see that I am simply outputting the _WorldSpaceCameraPos as a color.
As I understand it, this value should be the same for each fragment, but if you look at the screen shot, you can see that it's not rendering as a single color.
What am I not getting here?

code: https://hastebin.com/share/sukecuducu.cpp

agile token
#

As I'm playing with I just noticed that it's only broken in the scene view. The game view Works exactly as expected.

tardy crypt
#

I have a shader I'm working on that when I view it in the scene view, it looks fine but when it's in game there's a very faint, thin black rim on it.

#

Any idea what might be causing such behavior?

low lichen
#

The scene view renders the skybox a bit differently to the game view.

tardy crypt
#

I can't really see it at all in the scene view, so not sure?

severe gate
#

Hey there. Can anyone tell me why I dont have all the options shown on the Screenshot?

agile token
agile token
severe gate
#

Yeha nearly. After all the time I found it out myself. Good that ive noticed it yet. Worked with 2D Core all the time. Switched now to URP.

#

But I have an other question u could help me out. Im acctually trying to make a Water Reflection Shader. My Problem rn is, that it dosnt showing anything yet. Rather in the Camera or in the Render Texture. Its just blank. I really dunno why.

oak summit
#

Hey, how do I apply a shader without changing the texture? Like when you use the standard shader it automatically just picks out the texture applied to the object itself, in my case a tilemap
How can I do that in a custom shader

grizzled bolt
oak summit
#

Okaay
Thank you

old hearth
#

how could I make a shader that makes the black kind of blend in with the wall textures?

#

the black is just the solid color of the camera so its just void

severe gate
#

How to get like a loop inside a selfmade Shader?

#

Just that the effect goes on an on continuesly?

grizzled bolt
severe gate
# grizzled bolt Do you have a more precise example of what you mean "Loops" in code are differen...

Yeha sure! So ive made my own shader as water reflection. Mirroring my default camera. I also added a water texture to it. The problem im facing is, that the effect will last for 5-10 secs when im starting the Gameview and then its just running out with no return. What I'm trying to do, is that the effect will rather restart or just keps going. Like an infinite loop or extension. Im not really sure where the mistake might be. Followed some tutorials and in the footage ive seen the effect was already endless. In my case it isnt. Double checked everything and also made it again from scratch.

grizzled bolt
severe gate
#

But as I said I followed along the tutorials and there wasnt any step like that. In my case it didnt worked but in the tutorials it were displaying continuesly.

grizzled bolt
severe gate
#

Worked. Took a min. cause an error accured. But ive fixed it.

#

Thanks alot @grizzled bolt โค๏ธ

sharp parrot
#

can someone help pls ive spent all day trying to fix it, my materials arent even using lit anymore and its still broken

lean lotus
#

is there ANY way for me to change a #define in a cginc file from C#? I cant use shadervariants or anything because its a mess of nested compute shaders

manic arch
#

Is it possible to make a shader that blends two materials based on a texture? I want to mix the two materials as seen in the example (the example was made in blender)

green parcel
#

hey guys i wanted to ask you what i could improve (or add) about my terrain shader?

agile token
manic arch
agile token
manic arch
agile token
manic arch
#

At this point I don't know how this would be done, because I don't have that much experience with shader graph and shaders in general.

agile token
#

I see. I donโ€™t think baking is the answer. I think what you want to do is essentially have a whole chain of nodes in shadergraph that process your building material, and a while chain of nodes that process your hologram material. Then add a lerp node that blends the two. You can control the lerp with a texture, or a noise function (just experiment until it looks good). The tricky thing for you is that your building material is using the lit shader so youโ€™re going to have to kind of recreate that in shader graph.

manic arch
grand jolt
#

does anyone know how to set up simple vertex shader for unity 2022.3 as i can not use lwrp

#

i have been trying for 30 mins

#

i can send code via dms if it would be useful but im using gradient.evaluate(height) and then mesh.colors = colors;

#

i can find anything online on how to make it properly render this

#

Suggestions

agile token
grand jolt
#

so like the higher up parts on mountains are white and bottoms are green

#

idk if this is a good way to do this

agile token
#

I see. Which render pipeline are you using?

grand jolt
agile token
#

Cool, so you can use shadergraph. Drop in a position node, set it to world space, pass the output to a split node, pass the y channel into a gradient node and set up your colors in the gradient editor, then pass the output to the albeido. Then just make a material that uses the new shader and apply it to your terrain mesh

#

Youโ€™ll probably have to screw around with scaling the y value before passing it into the gradient, but thatโ€™s just a multiply node.

grand jolt
#

cool thank you i will try this

grand jolt
#

urp unlit?

agile token
grand jolt
agile token
#

To be very honest, my guess is that youโ€™re probably going to throw out your fist attempt (and your second third and fourth). You might be ok with unlit in your use-case but Iโ€™d recommend starting with PBR. Itโ€™s the one thatโ€™s used for most applications and if you end up not needing it, it wonโ€™t take long to rebuild your shader using unlit.

grand jolt
#

what is PBR is that just lit?

agile token
#

It stands for Physically Based Rendering. And, yes, most of what it does is try to get things to react to light in a believable way.

grand jolt
#

so i should pick URP > Lit Shader Graph correct?

agile token
#

You should right click in the project tab and then select Create > Shader > PBR Graph

grand jolt
#

weird itโ€™s not there for me

agile token
#

Huh. Yeah that lit thing is probably the same

grand jolt
#

thats what it looks like for me

#

also sorry if im being dumb lol this my first time using unity shaders

agile token
#

Yep thatโ€™s the one. In my instructions, when I said โ€œ albeidoโ€, thatโ€™s the same thing as โ€œbase colorโ€

grand jolt
#

ok

#

also when im looking at a split not ts only outputs are rgba no y output

agile token
#

When dealing with shaders โ€œrgbaโ€ is synonymous with โ€œxyzwโ€

grand jolt
#

ok thank you

#

also gradient does not seem to have option for input

#

do i use sample gradient?

#

its all just the pink

agile token
#

Oh yeah, I forgot that shader graph is like that. I think youโ€™ve got the right idea.

grand jolt
#

it still seems to not work idk why

agile token
#

Pink means โ€œerrorโ€

#

The console should be telling you why

grand jolt
#

the console is giving no errors

agile token
#

Hmm, not sure what to tell you. Keep fiddling with it. Shader graph is kind of meant to be fiddled with.

grand jolt
#

weird ok

#

do i need to plug something into all the holes on the other part

#

on the vertex thingy

agile token
#

Iโ€™m fairly certain it passes in the mesh data without you telling it to.

grand jolt
#

i will see if google knows

agile token
#

I think itโ€™s because the sample gradient outputs a vector4 but the color input is vector3 try splitting it and then recombining is into a vector3 node

grand jolt
#

ok

#

like this?

#

same thing is happening

agile token
#

Did it work?

grand jolt
#

still pink

agile token
#

Hmm. Weird. TBH I write shader code, so I donโ€™t know the ins and outs of shadergraph. Iโ€™m sure itโ€™s one thing small. Try saving it, and making a material out of it. Hopefully unity will complain and send you in the right direction

grand jolt
#

i tried that and it just gave me a pink ball and no errors

agile token
#

Hmm get rid of all your nodes and see if you can just pass a color to the base color

grand jolt
#

ok

#

no lol

#

just pink still

#

its like it came broken

#

complete default and its broken

#

maybe i set something else up wrong

agile token
#

Yep, looks like you need to sort out shadergraph first. Thereโ€™s a bunch of tutorials around. Iโ€™m sure youโ€™ll figure it out

grand jolt
#

ok thank you

#

i think i figured it out im testing now

#

itโ€™s because when i updated my code to use urp i did it wrong

#

im re configuring it now to check

karmic hatch
#

you need to set the correct target in the graph inspector otherwise it's pink

grand jolt
#

it all works now thank you guys

#

both the shader and perlin need tweeking but it all works now

grand jolt
#

still need work but did littlt tweeks

civic onyx
#

Hi guys, how to sharpen black and white values in noise in shader graph without using Contrast node, contrast node is not working as intended

#

this is how contrast node is behaving in Shader Graph (URP)

#

this is result without contrast node but i want the edges more grunged and sharpen, so difference can be felt

grizzled bolt
civic onyx
#

i used contrast on Noise texture which is black and white and noise output is sent to T of Lerp Node.

grizzled bolt
civic onyx
#

Wait i did that too, it didnt work, let me show u

#

it worked, Thansk Spazi, i used Saturate after Contrast, it removed the Colors

rancid meadow
#

so its not possible to expose a gradient in a custom shader??

regal stag
rancid meadow
regal stag
#

The downside is you need to create the gradient texture yourself - e.g. in photoshop/GIMP, rather than using colour keys like the gradient editor has.
(Though there's likely some C# editor tools/scripts to create gradient textures)

regal stag
rancid meadow
#

any other specifications for that texture?

regal stag
#

Would likely want the Wrap Mode set to Clamp in the import settings so colours at the start/end don't blend together

rancid meadow
#

alright you amazing man thanks a lot

grand jolt
#

anybody know a good shader (or other) approach to hide objects at "Y" value above the player? ALL objects, regardless of shader they use

rancid meadow
#

left is the gradient texture

frigid jay
#

Remove Sample Gradient node, and put Sample Texture

woeful breach
#

how can i get a gradient in a shader for my particles so the bottom ones are darker then the top ones ?

regal stag
#

Otherwise you may need to set up Custom Vertex Streams (under Renderer module of particle system) to pass the particle positions into uv channels - but remapping that might also be difficult.
If the particles rise up like smoke, could also just use color over lifetime.

rancid meadow
#

Base Color(T2) is black and white...so is this right now?

woeful breach
regal stag
hollow wolf
#

i want to create shader that morph sphere to cube in shadergraph, does anyone know how to do it?

regal stag
hollow wolf
#

looks like i need to use another way

#

thanks for your help ๐Ÿ‘

regal stag
hollow wolf
#

true, the problem is i need to spawn at leas 30 of them and this is for VR, so i want the polygon as little as possible, and i already use tesellation shader for the 3d obj

#

*stand alone VR

grand jolt
#

How do you add slight transperency?

grand jolt
#

i canโ€™t i donโ€™t see alpha option

karmic hatch
#

are you sure your graph is set up to be transparent (in the graph inspector)

green parcel
#

some changes to my terrain shader

grand jolt
grand jolt
#

Hello!

#

I need help with the default volumetric shader in the Unity docs

#

the rendering bends and distorts as the object moves away from zero position... what am i missing?

#

rotation and scaling works fine

ebon moss
halcyon plank
#

How would i make a HDRP Lit Shader Graph compatible with the terrain

manic arch
halcyon plank
#

@manic arch you need a sample 2D node and take the RGBA from that and plug it in

#

Sample Texture 2D to be more specific

#

your plug the Texture node into the sample node

manic arch
#

Ahhh thank you very much. Do you also know how to make the field in the inspector look compact like the buildin urp lit shader instead of expanded? And also if a texture is not provided, to choose a float instead?

halcyon plank
#

Honestly im not to sure but it might help if you click the plus button in the right and make a catagory put them in there see if it compacts it

#

oh you already did

#

nvm

#

but shaders that ive seen really arent compact, creating a material from it will come compact though as seen on the left

manic arch
#

On the right is the inspector of a material that's using my shader graph as a shader (that's correct, right?)

halcyon plank
#

Well no those are just the shader options that materials can access when using the shader

manic arch
#

How do I create the material properly? This is what I have currently

#

MixMat is the shader graph from earlier

halcyon plank
#

No thats correct

#

weird

#

i didnt see the top in the other photos

manic arch
#

Yeah mb

grand jolt
# grand jolt

Never mind, I think I fixed it, I changed 1 character....

lilac harbor
#

I wanted to create a wood carving app where the users can carve into a wooden block via touch input. I was thinking that the drawing the users create would be a black and white and would serve as a heightmap to a the wooden's material so that material would be appear carved.

Ultimately I was wondering if I could get some advice on this:

  1. Is this approach the best way to implement this (ie drawing the heightmap to a render texture that is manipulated via a compute shader) ? If not, what is a better way?

If indeed the best way to implement this is via a compute shader + render texture:
2: How would I implement the scenario where a user draws another stroke in an existing place (the darkness of the black part of the heightmap becomes more dark ) so that the appearance of the cut is deeper than in other places where the user carved once. However there would be a max depth of a cut somehow?
3. Is there a way to implement a type of "brush" so that the center is the darkest but then the edges are a lighter?

grand jolt
# lilac harbor I wanted to create a wood carving app where the users can carve into a wooden bl...

1: The "wood" is a mesh that you define and cannot really be changed by shaders. Still, it's ok as long as the user doesn't carve a lot at the same spot
2: I lied, the mesh can be manipulated both on the GPU or the CPU but both comes at a cost. Anyway: You can generate a new mesh based on the old mesh and the user input.
see this video about "marching cubes" https://www.youtube.com/watch?v=vTMEdHcKgM4&ab_channel=SebastianLague
3: If you really want to apply brushes, step 2 (mesh regeneration) is a must, but after that it should be easy.
4: PROFIT

I got a bit tired of my simple heightmap-based planets and decided to experiment with generating them using the Marching Cubes algorithm instead, so that I could add a 'terraforming' ability for shaping the world with caves and tunnels and so on. I hope you enjoy!

Project files are available here:
https://github.com/SebLague/Terraforming

If yo...

โ–ถ Play video
dire jolt
#

I am using a custom function node in shader graph and I think that I've identified the issue, it seems to be my method of RNG for the wave pattern. Now, the problem only affects the actual color, which I find odd but I suppose the vertex or pixel shader just deals with it differently somehow. But the only thing that is randomized is the angle.

float SimpleRNG(int iteration, float seed, float min, float max)
{
    return fmod(sin(float(iteration) * 12.9898f + seed * 78.233f) * 43758.5453f, 1.0f) * (max - min) + min;
}

void SumOfSines_float(...) {
// ...

loop(i) {
  float angle = SimpleRNG(i, seed, -360, 360);
}

// ...
}

The first video showcases how it looks with the above function.

The second video showcases it with a way more rigid "generation" where I set the angle like this.

float angle = i * -40 + (i % 2) * 12 + i * 5 * modAmp;

I've tried just setting the angle to the value of the SimpleRNG function like this:

float angle = fmod(sin(float(i) * 13 + seed * 78) * 43759, 1) * (360 - -360) + -360;

But it also didn't help. I also tried making SimpleRNG static, no luck there either.

stiff charm
#

Could someone help

desert orbit
#

What IDE are you using?

stiff charm
desert orbit
# stiff charm visual studio with UNITY

Yea, I'm not familiar with shader language to tell what's wrong definitively, just know that you need special plugin for VS to have some correct intellisense support for shaders. (last time I looked at it)

#

So just follow a tutorial correctly and ignore errors without plugin

stiff charm
#

Thanks, seems plugins I get anyways don't wanna work for me and I'm not following any tutorial I simply just opened a shader, my VS its picking up any shaders ๐Ÿ˜ฆ and giving erros for stuff that should be built in "i think"

desert orbit
#

Are you using VS 2022? I forgot it suppose to have built-in HLSL support now.
Visual Studio 2022 version 17.6 comes with built-in support for HLSL and a new tool to view Unreal Engine logs.

stiff charm
#

I just did a reinstall earlier to make sure it wasnโ€™t the VS application

stiff charm
regal stag
#

Probably causing errors as only the HLSL/CGPROGRAM portion of the code is HLSL. The rest is Unity's "ShaderLab" which VS might not support (without an extension)

lilac harbor
lost otter
#

I want to get started with shaders. I will use them to render some simple shapes for now, like a circle, based on an object. How should I go about it?

manic arch
#

Can I get some feedback on this graph? This is my first one so I want to know if I could do anything better.

#

The purpose of it is to blend a PBR material and a hologram material.

grand jolt
#

something went horribly wrong but its cool looking

royal hollow
#

Hey folks. I've been trying to reduce draw calls for mobile with 2022 LTS and URP. Zoomed out I'm getting about 120 draw calls and only 15fps with about 200 sprites on the screen and 2 layered tilemaps using a material with lit/tint shader I wrote. No lights in the scene. I suspect on these slower Android devices its the draw calls killing me. But batching doesn't seem to reduce draw call counts claiming every sprite is a different material. I'd like to swap to shared materials for everything and then when tinting is needed I'd just change that one sprite and then go back sort of thing. I've seen others discuss it here. But there's a lot of confusing answers. Is anyone available to discuss it in a little detail by chance?

quaint grotto
#

so whats the alternative to material property blocks when you need colour variations per gameobject?

mental bone
quaint grotto
#

thats a lot of cloning in edit mode though

grizzled bolt
# quaint grotto thats a lot of cloning in edit mode though

If you change a material's property in code at runtime, a material variant will be created automatically
You should also destroy it in code when it's no longer needed though, or pool and recycle them between meshes
No need for cloning in edit mode

hushed silo
#

Is there a way to use geometry to create eg a black and white maskโ€ฆ. So thatโ€™s where the main mesh and a secondary intersect?

digital pelican
#

Hey, is this possible to create material output that would put additional float/int to screen that would be usable in post process renderer feature pass?

#

The thing i would require would be adding seams and params for toon shader

amber saffron
amber saffron
digital pelican
#

Yes, URP in my case. Could you attach some exaple/resource. I know of using layers to do this, but I'm not after using this, but instead using texture with sort of mask, and I can't find anything about adding this.

valid island
#

Could anyone tell me why this isn't giving an output? It's just kind of like, idk, some random colour from the texture provided.

#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Texture.hlsl"
 
void N64Sample_float(
    in UnityTexture2D Texture,
    in float2 UV,
    out float4 Out)
{
    // texel coordinates
    float4 texelSize = Texture.texelSize;
    float2 texels = UV * texelSize.zw;
 
    // calculate mip level
    float2 dx = ddx(texels);
    float2 dy = ddy(texels);
    float delta_max_sqr = max(dot(dx, dx), dot(dy, dy));
    float mip = max(0.0, 0.5 * log2(delta_max_sqr));
 
    // scale texel sizes and texel coordinates to handle mip levels properly
    float scale = pow(2,floor(mip));
    texelSize.xy *= scale;
    texelSize.zw /= scale;
    texels = texels / scale - 0.5;
 
    // calculate blend for the three points of the tri-filter
    float2 fracTexels = frac(texels);
    float3 blend = float3(
        abs(fracTexels.x+fracTexels.y-1),
        min(abs(fracTexels.xx-float2(0,1)), abs(fracTexels.yy-float2(1,0)))
    );
 
    // calculate equivalents of point filtered uvs for the three points
    float2 uvA = (floor(texels + fracTexels.yx) + 0.5) * texelSize.xy;
    float2 uvB = (floor(texels) + float2(1.5, 0.5)) * texelSize.xy;
    float2 uvC = (floor(texels) + float2(0.5, 1.5)) * texelSize.xy;
 
    // sample points
    float4 A = Texture.SampleLevel(Texture.samplerstate, uvA, mip);
    float4 B = Texture.SampleLevel(Texture.samplerstate, uvB, mip);
    float4 C = Texture.SampleLevel(Texture.samplerstate, uvC, mip);
 
    // blend and return
    Out = A * blend.x + B * blend.y + C * blend.z;
}```
Any help would be appreciated!!! ![haruSmile](https://cdn.discordapp.com/emojis/978332157116317806.webp?size=128 "haruSmile")
ruby garnet
#

Do you guys think the switch to URP is worth it over the built-in pipeline?
im asking here cuz i think asking in #archived-urp might be a little biased lol

#

URP looks so much worse by default and its not like im making a mobile game, what are the benefits?

#

is the hassle worth that small performance boost?

#

My understanding is also that it makes coding shaders considerably more complicated

low lichen
ruby garnet
#

Yeah I mean I plan on making an open world game so baking lights is definitely off the table

#

For the most part

low lichen
#

But do you intend to use forward rendering or deferred rendering?

grizzled bolt
# ruby garnet URP looks so much worse by default and its not like im making a mobile game, wha...

The "default look" is irrelevant and if anything URP currently starts with more graphical features enabled out of the box
Built-in RP has a couple more features out of the box like SSR, but they're mostly capable of all the same stuff
The bigger difference is that Built-in RP is easier to extend under the hood and has a much larger archive of such user created extensions and tutorials
Thanks to Shader Graph making shaders is much easier in general, but considerably harder if you need to push beyond the limit of what SG allows for
I find that SRP batching is incredibly effective and makes optimization much simpler, but some have given conflicting reports about how good particularly the low-end performance is in comparison

low lichen
#

The SRP Batcher is a good point. It completely changes how you approach draw call optimization as a developer. In built-in, you want to minimize the number of different materials, using things like GPU instancing to be able to reuse the same material with different properties. With SRP Batcher, you only need to minimize the number of different shader variants.

#

The most optimized SRP Batched scene is not going to be as fast as the most optimized GPU instanced scene, but it's pretty close and way less work.

ruby garnet
low lichen
ruby garnet
#

I'm gonna keep it real, I'm still somewhat new to this ๐Ÿ˜…. the 10 minutes i took to reply were mostly used figuring out what the differences are between the two are.
My understanding is that deferred consumes more memory, i want to make a game that can run on most devices.

#

you are more knowledgeable than i am, if you think deferred is better i'm certainly open to suggestion

#

@low lichen

grizzled bolt
ruby garnet
#

True. Actually the whole reason I started looking at URP is because I was hoping itd fix a shader graph issue ive been having. Every time I connect a node, disconnect a node, or play the project, the main preview becomes a bright teal color and it stays that way until I wiggle the preview window around, change the preview zoom, rotate it, or basically interact with it at all.

#

it is so annoying

rancid meadow
#

how can i change the strength of a emission map via a slider? emission map in a power node or how?

ebon moss
#

when I apply my shader material it stretches a lot because of the object shape, how can I make it not stretch but repeat?

quaint grotto
grizzled bolt
#

They're two different systems

quaint grotto
#

but you said if you change materials property in run time it creates a variant but thats not true because when i did it, all the obejcts with the material changed

#

the only way i found to do it per object was a material property block

quaint grotto
#

sure but in edit mode i have to use shared material because if i use material it gives a warning about memory leaks

grizzled bolt
quaint grotto
#

well i want to set up the data one time so was doing it edit mode since it doesnt change at run time

grizzled bolt
quaint grotto
#

well my editor tool generates meshes and im assigning a material then the tool is changing some colours for that specific object thats the general idea

#

instantiating a new material for each new object seemed a bit memory inefficient i thought

grizzled bolt
wraith gulch
#

Hello. I am new to shaders and am running into a bit of a problem. I am using the built in render pipeline and am trying to create a transparent shader, but don't want to render the internal geometry. I have a feeling it will have something to do with the stencil buffer but I'm not sure. My current transparency calculations are being done in in the fragment step, but I'm almost 100% sure I should'nt be doing that for the desired effect. I have attached an image of my current effect, and edited the desired effect with photoshop. Any help pointing me in the right direction would be super appreciated, Thanks!

#
{
    Properties
    {
        _Color("Color", Color) = (1.0,1.0,1.0,1.0)
        _Speed("Speed", Float) = 1
        _Limiter("Limiter", Float) = 1
    }

    SubShader
    {
        Tags
        {
            "RenderType" = "Transparent" "Queue" = "Transparent"
        }
        Blend SrcAlpha OneMinusSrcAlpha
        LOD 100
        ZTest Always
        Pass
        {
            CGPROGRAM
            // pragmas
            #pragma vertex vert
            #pragma fragment frag

            // user defined variables
            uniform float4 _Color;
            float _Speed;
            float _Limiter;


            // base structs
            struct vertexInput
            {
                float4 vertex: POSITION;
            };

            struct vertexOutput
            {
                float4 pos: SV_POSITION;
            };

            // vertex function
            vertexOutput vert(vertexInput v)
            {
                vertexOutput o;
                o.pos = UnityObjectToClipPos(v.vertex);

                return o;
            }

            // fragment function
            float4 frag(vertexOutput i) : COLOR
            {
                float4 color = _Color;
                float time = (sin(_Time.w * _Speed) / _Limiter) + (_Limiter * _Limiter) - 1;
                color.a = ((time + 1) / 2);
                color.a = color.a * _Color.a;
                return color;
            }
            ENDCG
        }
    }
}```
regal stag
# wraith gulch Hello. I am new to shaders and am running into a bit of a problem. I am using th...

Adding a stencil pass may work, e.g.

Stencil {
Ref 1
Comp NotEqual
Pass Replace
}

(basically, stencil buffer will set pixels to 1 when drawn. Then for an overlapping pixel, it's already equal to 1 so doesn't meet the comparison and is discarded)

Alternatively, do a pass before only writing to the depth buffer, similar to this thread - https://forum.unity.com/threads/transparent-depth-shader-good-for-ghosts.149511/

wraith gulch
#

@regal stag Thank you so much, I'll look into this!

upbeat topaz
#

Is there no way to expose a gradient to the inspector in shader graph?

grizzled bolt
upbeat topaz
#

ah dang, slight inconvenience

dire jolt
#

So, I have some ocean, and it's transparent, and I keep getting these really ugly artifacts from it. I've "circled" the issue with the red marker, if for some reason the issue isn't apparent. And I haven't been able to find a solution, and I've also not noticed a similar thing happening to the transparent water in the videos I've looked at. It's obviously not as extreme when I have the amplitude at a normal value, but it is noticable. Anyone recognize what's causing this and how it could be fixed?

toxic flume
#

Do we have Time in compute shaders? __Time__? or should I use _Time like frag shaders?
Can I use standard c++ arrays instead of StructuredBuffer in a compute shader?

int points[10];
meager pelican
dense saffron
#

Shader error in 'Shader Graphs/S_Basic_PBR': maximum ps_5_0 sampler register index (16) exceeded at line 448 (on gles3)
Getting this error in my URP project and not letting me build for Android. Any help?

toxic flume
#

I want to access the upper voxel (one specific field) of current voxel in my shader. Is it better to access it in frag shader itself or calculate it in my compute shader for each voxel?

   v2f vert(appdata_full v, uint instanceID : SV_InstanceID)
            {
                #if SHADER_TARGET >= 45
                VoxelStruct data = voxelBuffer[instanceID];
                #else

If a specific field of the upper voxel has value >= th, then render the current voxel.
I can define an extra bool field to struct voxel and set it in the compute shader.

amber saffron
dense saffron
amber saffron
ruby garnet
#

so i have this project i upgraded from Unity 2021.3 to 2022.3.11 and the empty, default lit shader graph is giving this error/warning. Why does this error only appear in this project but not in the same shader in other projects created in 2022.3.11? Is there something that wasn't updated properly?

ruby garnet
#

like this definitely means im running old code, do i have to do something to update UnityCG?

tardy field
#

In shader graph, how can I replace black color in this example with different color? I tried adding a color but that applies a color over the noise texture

ruby garnet
#

@tardy field use multiply

#

actually wait no i misunderstood ur issue, idk what method u should use.

tardy field
#

Yeah, multiply won't do because it will change the color of noise texture

tardy field
shadow kraken
#

You need to use your gradient as the T input

tardy field
shadow kraken
#

Your noise

#

Here's a handy image from google to show how to use the lerp node

tardy field
#

its seems to work but only in one way

neon comet
tardy field
frigid kite
#

Hello guys, I've been dealing with this issue for a week now, and the creator of the asset is not responding to my emails. I'm turning to you as a last hope.

I purchased the Curved Worlds asset, and it works perfectly. However, I need to integrate it with a custom shader I've created in Shader Graph. The Curved World asset comes with documentation for this processโ€”it involves adding three nodes to my shader and connecting them to Vertex Normal and Position. However, when I follow these steps, the material of my object becomes invisible.

I have the documentation and everything needed, but I'm not sure if someone could lend me a hand. There might be something I'm missing.

regal stag
frigid kite
regal stag
#

I was referring to the previous image above, where you had a Vector3 node connected to the Vertex input on the CurvedWorld custom function

#

That would set all the vertices to the same position

frigid kite
regal stag
#

The manual also shows that

frigid kite
#

Ok, got that:

frigid kite
frigid kite
frigid kite
#

@regal stag Sorry to bother you, but do you have any small hint as to why it dropped from 90 to 28-32 FPS? I'm quite lost when it comes to shaders. Thank you.

regal stag
frigid kite
# regal stag No idea. Manipulating vertices in a shader usually isn't that costly afaik

Alright, thank you very much. At least, I've managed to make it work. I'll strive to achieve 60fps, although starting with so few objects, I can barely get 40... it's tough.

On another note, do you know how I can eliminate the blurry effect on the ground material? Let me explain: I only see the part very close to the camera in focus, and the rest is not sharp, creating a strange effect because as I move forward, it becomes clear. My explanation might be a bit confusing, xD.

low lichen
# frigid kite

That looks like mip mapping on the normal or roughness map. Switching to trilinear filtering on whichever texture is causing this will blend that seam.

ebon moss
#

Does sewing my uv's create a discontinuity, meaning that when my shader animation plays there will be a separate shader animation being applied to each zone?

frigid kite
ebon moss
#

I guess the goal is to get all the boxes looking like they go together continuously right

frigid kite
ebon moss
#

I think i'll get rid of that big seam

tight phoenix
#

Shader color calculation question ๐Ÿค”
Multiplying white (111) by 0.33 doesn't produce a color equivalent to HSV of (0,0,33)

#

I assume there is some kind of hidden conversion going on, I could convert the color to HSV and back just for this one purpose, but I'd rather just know why my assumption is wrong

#

The RGB Color (85, 85, 85) is identical to HSV * 0.33, but multiplying White (255) by 0.33 isnt identical

#

the plot thickens

#

I guess my question now becomes: why does default mode's math differ and how do I make it not differ? how do I compensate for it behaving differently?

regal stag
ebon moss
#

Hi! I'm trying to extend my UV's onto this sphere, should I / where should I place seams on the sphere?

grizzled bolt
ruby garnet
#

Does shader graph crash for anyone else when creating a new node using the "recommended nodes" menu you get when dragging from an output port to an empty space?

ruby garnet
#

ok i switched back to the 2021 lts version and its fine now

cursive spade
#

Hey everyone, is it possible to get the decal layer of a screen position in shader graph?

smoky furnace
#

Hey there - in shader graph, there is a Scene Color node, but I don't know if I understood what it does: my use case is - I would like to read the colours behind a given quad and distort them, by resampling the screen position and adding some scrolling perlin noise.

however, no matter what I do, I cant seem to read the data behind my quad :c

Maybe my approach is wrong - how am I supposed to get the color data behind an object I'm currently rendering?

regal stag
smoky furnace
#

this is what I see in my graph?

regal stag
smoky furnace
#

okay I see - thanks :v

warped bear
#

Hello, sorry to bother you.
I never made shaders before and as a starting point I decided to follow this tutorial:
https://www.youtube.com/watch?v=taMp1g1pBeE&t=1s&ab_channel=Brackeys

But when I apply the shader, I loose the texture that my gameobject had
I'm very confuse how shaders and materials interact

Could some one give me some clue on what to search ?
I feel i'm missing something

Letโ€™s learn how to create one of my favourite effects: Dissolve!

Check out Skillshare: http://skl.sh/brackeys6

โ— Download the project: https://github.com/Brackeys/Shader-Graph-Tutorials

โ™ฅ Support Brackeys on Patreon: http://patreon.com/brackeys/

ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท

โ™ฅ Subscribe...

โ–ถ Play video
grizzled bolt
warped bear
# grizzled bolt Materials are presets of properties for a shader to use A texture is one type of...

oke, so to summaries what I understood so far:
materials are packs of data.
on top of materials you have to have a shader (which is built-in mat by default or different if you have URP or other rendering pipeline).
those shader will take specifics data from the materials but those data can be different from a shader to a other.

am I right on all of those points ? (i'm just trying to understand what i'm dealing with x'D )

grizzled bolt
# warped bear oke, so to summaries what I understood so far: materials are packs of data. on t...

Materials hold data values like vectors, colors and references
Shaders are code that do math with those values
So you might have two materials using the Lit shader, one with a green color and the other with a specific normal map
The Unlit shader opposed to Lit shader might be able to also use the green color property, but not the normal map because Unlit does not implement normal mapping
All render pipelines have multiple "default" shaders for different purposes

warped bear
#

okeee

warped bear
grizzled bolt
# warped bear thank, I watch the video, I learn quick a few things ๐Ÿ˜„ one last thing I don't u...

URP used to be required to use SG, but now SG supports the BiRP too although not perfectly from what I hear
It's unlikely to matter regarding SG, but the render pipelines are otherwise somewhat different
Mostly I think you'd stick to BiRP if you want to use custom assets that require it, or otherwise extend the rendering features yourself
URP is simpler if you're a casual user, given the features it offers*

hearty obsidian
ruby garnet
#

Hello again guys! So I have a shader graph that I'm having render both the front and back of an object. I'm using a Fresnel effect for opacity, so only the edges of the object are visible, and it works great when I'm rending just the front face. But it completely breaks for the back face and renders it completely solid. Is there a way I could logic nodes to filter out normals facing away from the camera?

#

i know thats a lot to read, but id really appreciate any help ๐Ÿ˜€

ruby garnet
#

nevermind lmao

hoary adder
#

is there a better URP skin shader than Lux Essentials? I have PIDI as well.. not quite what I was hoping for, but could easily be user error...

leaden echo
#

I have a question that may be a bit silly. I am working in AR and have successfully written a shader that takes the values from a depthImage and then uses logic to determine whether or not to render that object (I.E. it won't render objects 'behind' other objects). The issue I'm having with this is that it's resource intensive, so I had an idea and, as I'm a beginner, wanted to ask you all because i don't know if it's possible.

Would it be feasible to have a single shader applied to the actual Camera's texture. That way, instead of checking each object for whether or not it should render the pixel, it would just check the 'background' image's depth values against the GameObject's depth values and determine whose pixel to render - the camera 'background's, or the gameobjects...

Any thoughts or advice would be greatly appreciated! ๐Ÿ™‚ Thank you

regal stag
karmic hatch
rugged raptor
#

Why is the material not showing up on top

karmic hatch
rugged raptor
karmic hatch
#

I assume it's a procedural mesh or one you made in some other modelling program; if the former, you can set mesh.uvs and if the latter, you can do it in the other program

hearty obsidian
coarse aurora
#

Hey, stupid question, how could I achive a shader to only render the outline of any object, and remove the faces, something like this:

vocal narwhal
manic arch
#

It works on any URP Lit material.

proud raptor
#

Hi eveyone. I am relatively new to HDRP and I got a water shader whuch was created in URP but I adapted it to the HDRP Lit Shader.
When I changed it from Opaque to Transparent, I get thois funny glow. if, I turn off the directional light in my scene, it goes away. I turned off the post processing, but no luck.
please, any idea what could be causing this?

hollow wolf
#

at least in URP,

proud raptor
proud raptor
gilded river
#

Why does this happen when i enable opaque texture in urp?

#

I'm trying to make water refraction with a shader graph

hollow wolf
proud raptor
radiant meteor
#

Is this a bug? This is producing a divide by 0 error. URP, version 2022.3.7. I've seen many tutorials just use something like this and no divide by 0 error.

rare wren
#

If your materials are setup that the value would never be 0, you can ignore it

gilded river
toxic flume
#

How to update and change some elements of an array (structure buffer) in a compute shader?

//CPU
  private void Update()
        {
            if (_isDirty)
            {
                _isDirty = false;
                if (_worldChangeBuffer != null)
                {
                    _worldChangeBuffer.Release();
                    _worldChangeBuffer.Dispose();
                }
                _worldChangeBuffer = new ComputeBuffer(_worldChangeList.Count, 16, ComputeBufferType.Structured);
                _worldChangeBuffer.SetData(_worldChangeList);
                _computeShader.SetBuffer(4, "worldChanges", _worldChangeBuffer);
                _worldChangeList.Clear();
            }
//GPU
[numthreads(100, 1, 1)]
void UpdateVoxelWorld(uint3 id:SV_DispatchThreadID)
{
        VoxelData changeVoxel = worldChanges[id.x];
        int index = GetIndex(changeVoxel.pos);
        VoxelStruct voxel;
        voxel.state = changeVoxel.blocked;
        voxel.pos = voxels[index].pos;
        voxels[index] = voxel;
}

Is it OK?
and should I create a compute shader with max size only once instead of creating it frequently with different size?

hollow wolf
little bloom
#

How can I make the same circle decal with radial gradient shader as here?

karmic hatch
solar pecan
#

Hello,
does anyone know how i can get light direction with 2d URP? preferably in shader graph.

there has to be a way since normal maps work in 2d Renderer, but for the life of me i cant figure it out

karmic hatch
#

(there are tutorials online)

radiant meteor
karmic hatch
radiant meteor
#

i get a divide by 0 in both

#

And the property wasnt set to 0

karmic hatch
rare wren
spice monolith
#

Hey everyone, I'm messing around with shaders in HDRP and I made a simple tessellation shader graph that has literally no blocks, just default values. When I tried to compile and show the preprocessed code it gave me a... 25 million lines file and, if I understand the image right, almost 2k shader variants (which seems a bit exccessive for a blank shader no?). If anyone can enlighten me about this it would be great, thanks

toxic flume
#

Accessing different indices of a structured array in a compute shader is expensive?
for example index_up,index_down, index_left, index_right

toxic flume
#

buffer.GetData is expensive even for small size like 10000. How can I handle it?
I want to send fluid data from GPU (compute shader) to the cpu. I have defined an append buffer and populate it with data (fluid).
My entire world is 200 x 200 x 200 but even for fluid array data with 10000 size, getting data takes around 150ms !

radiant meteor
#

how would I fix that glow from far away? I'm using the scene depth.

#

it only happens when I have bloom enabled.

raven stag
karmic hatch
long bramble
#

I'm having a strange issue where my float array doesn't seem to be getting copied correctly. The array getting passed goes linearly from 0.0 to 0.99 (100 elements). But inside the shader, Every 4th element inside it seems to be 0. All the other colors are just sort of wrong as well. I'm not modifying any array elements either inside the shader. ```cs
mapDataShader.SetFloats("oceanHeight", MapGenSettings.OceanHeightCurve.GetBake(MapGenSettings.OceanHeightCurve.Resolution));

    foreach (var item in MapGenSettings.OceanHeightCurve.GetBake(MapGenSettings.OceanHeightCurve.Resolution))
    {
        Debug.Log(item); //Outputs 0, 0.01, 0.02, 0.3 all the way to 0.99
    }
meager pelican
toxic flume
#

How can I solve this problem? GetData is expensive.

  private void Method()
        {

                Profiler.BeginSample("WorldWaterUpdates1");
                _changesBuffer.GetData(_changeStructs);
                Profiler.EndSample();
                Profiler.BeginSample("WorldWaterUpdates2");
                //_waterBuffer.GetData(_waterStructs);
                _waterCountBuffer.GetData(_waterCounter);
                Profiler.EndSample();
                Profiler.BeginSample("WorldWaterUpdates3");

                    for (var i = 0; i < _waterCounter[0]; i++)
                    {
                        var data = _changeStructs[i].data;
fresh osprey
#

how to animate tiling and offset shader graph

#

nvm got it working lol

shadow kraken
karmic hatch
# toxic flume How can I solve this problem? GetData is expensive. ```cs private void Method(...

From https://forum.unity.com/threads/computebuffer-getdata-takes-15-20ms.308284/

GetData has to wait for the GPU to actually carry out the work you've dispatched, so calling GetData immediately after Dispatch like you're doing there is going to mean you're stuck waiting for the GPU's work queue to clear, and for it to carry out the kernel, and for the results to be copied back to system memory.

Try doing other work after Dispatch(), so that the GPU has a chance to get things done - you could even yield for a frame and retrieve the results later that way.

#

some good tips there

hearty obsidian
#

I want to draw edges in a shader. I read that I should be preprocessing meshes to bake distance from edges into UVs. Is there a recommended technique to do this?

#

Or in a texture I guess

fresh osprey
#

i made a vfx graph with active targets set to only universal, but now i want to integrate it into vfx graph

#

when i try to add vfx in the active targets

#

it doesnt allow me to set it

#

and when i remove universal, it just messes up my shader

rare wren
rare wren
#

The visual effect target is deprecated

hearty obsidian
frigid silo
#

Hello! This may be extremely simple but I can't seem to figure it out but, can I color a specific vertex via its UV coords in a fragment shader? Ideally I'd like to send a UV coord via a RWbuffer and use that to do the coloring๐Ÿ˜Ÿ

rare wren
fresh osprey
rare wren
hearty obsidian
radiant meteor
karmic hatch
radiant meteor
#

It only happens from far away. I don't think I know enough about what values the screen position / scene depth nodes give to do that. I guess clamping will work for now.

radiant meteor
#

how do i invert this!? The top one is too sharp of a fade to black, the bottom one has no black.

karmic hatch
toxic flume
#
var m = waterChangeCount / 100;
var n = waterChangeCount % 100 == 0 ? m : m + 1;
_computeShader.Dispatch(0, n, 1, 1);
[numthreads(100, 1, 1)]
void MainLoop(uint3 id : SV_DispatchThreadID)
{
    int count = waterCount[0];
    if (id.x >= count) return; // compare it with the actural length

To calculate thread group, is it a correct way?

toxic flume
# karmic hatch From https://forum.unity.com/threads/computebuffer-getdata-takes-15-20ms.308284/...

Thanks, can you give me a better way?
I have implemented cellular based water system in my voxel game.
I have to get water positions and liquid value because logic in cpu side requires it.
async, can you explain more? I have tested Task.Run before to async it. Do you mean Task.Run to async?
Getting data (buffer.GetData(data)) in another thread and keep data to a queue then, use it in the main thread?

toxic flume
karmic hatch
karmic hatch
quaint grotto
#

if you instantiate a material using a material reference so its a copy of it, are these still connected in that if you change the properties of one it will change the other? or does instantiate create a new material independant of the other?

#

wondering if that will avoid me needing material property blocks

toxic flume
#

How do you choose number of threads and thread group in terms of efficiency?
Example:

shader.dispatch(0,64,8,1)
//////
[numthreads(1, 1, 1)]
void MainLoop(uint3 id : SV_DispatchThreadID){}
shader.dispatch(0,1,1,1)
//////
[numthreads(64, 8, 1)]
void MainLoop(uint3 id : SV_DispatchThreadID){}

and which one is more efficient? the first one?

#

I want to execute a kernel on a 1D array with different offsets/directions (7 directions)

shader.dispatch(0,_length / 64,7,1)
//////
[numthreads(64, 1, 1)]
void MainLoop(uint3 id : SV_DispatchThreadID)
{
}

Is it correct?

low lichen
toxic flume
#
shader.dispatch(length/100,7,1);
/////
[numthreads(100,1,1)]
void AssignValues(uint3 id1:SV_DispatchThreadID)
{
    if (id1.x >= count) return;
    FluidChangeStruct v = structureChangeVoxels[id1.x];
    int3 id = v.id;
    int dirIndex = id1.y; // 0-6
    id += dirs[dirIndex];
    
    int index = id.x + id.y * arraySizeX + id.z * arraySizeX * arraySizeY;
    int indexUp = id.x + (id.y + 1) * arraySizeX + id.z * arraySizeX * arraySizeY;
    int indexDown = id.x + (id.y - 1) * arraySizeX + id.z * arraySizeX * arraySizeY;
    int indexRight = (id.x + 1) + id.y * arraySizeX + id.z * arraySizeX * arraySizeY;
    int indexLeft = (id.x - 1) + id.y * arraySizeX + id.z * arraySizeX * arraySizeY;
    int indexFront = id.x + id.y * arraySizeX + (id.z + 1) * arraySizeX * arraySizeY;
    int indexBack = id.x + id.y * arraySizeX + (id.z - 1) * arraySizeX * arraySizeY;
    // voxels[index]

Is it correct to calculate index?

toxic flume
#

1- 64,8,1 thread group, one thread for each?
2- one thread group with entire ?

low lichen
#

My understanding is that numthreads determines that batch size per dimension, and the numbers in the Dispatch determines how many batches there are.

toxic flume
#

So, for arrays with small size, the first one is better

meager pelican
# toxic flume How do you choose number of threads and thread group in terms of efficiency? Exa...

https://www.youtube.com/watch?v=XyUusirGAl4
I "default" to numthreads(8,8,1) for most applications to allocate cores in groups of 64 with both x and y varying. YMMV.

#

Remember to check for out-of-bounds conditions for non-multiples of dimensions.

half marsh
#

I have these windows projecting this box projection but i have to have a reflection probe for each window. i tried doing this through a shader but im not to sure how. is there a way i can just have one reflection probe that is used for all the windows.

gleaming widget
#

trying to use solid color skybox but this happens

#

using canvas in front of cam to give retro effect

long bramble
#

I'm having a strange issue where my float array doesn't seem to be getting copied correctly. The array getting passed goes linearly from 0.0 to 0.99 (100 elements). But inside the shader, Every 4th element inside it seems to be 0. All the other colors are just sort of wrong as well. I'm not modifying any array elements either inside the shader. ```cs
mapDataShader.SetFloats("oceanHeight", MapGenSettings.OceanHeightCurve.GetBake(MapGenSettings.OceanHeightCurve.Resolution));

    foreach (var item in MapGenSettings.OceanHeightCurve.GetBake(MapGenSettings.OceanHeightCurve.Resolution))
    {
        Debug.Log(item); //Outputs 0, 0.01, 0.02, 0.3 all the way to 0.99
    }
toxic flume
meager pelican
meager pelican
long bramble
#

mapPoint.color is an item in a buffer. I know that mapPoint.color correctly renders to a texture because I'm able to input any other value (Numbers, noise, etc) and get the expected result

low lichen
#

And you save a couple of instructions and maybe even a branch by not doing the check.

toxic flume
#

Can't I define a const array int[] or for example int3[] in the compute shader?
Should I pass data from cpu to gpu even for const arrays?

// compute shader
const int3 dirs[]={int3(1,0,0),int3(-1,0,0),int3(0,0,1),int3(0,0,-1)};
#

Another question, when passing append buffer to a frag shader, should I pass its size as well and check it or not?
I mean append buffer

 _instanceMaterial.SetBuffer("voxelBuffer", _appendBuffer);
  #if SHADER_TARGET >= 45
            StructuredBuffer<FluidStruct> voxelBuffer;
            #endif

I mean it is valid for each instance Id or not? all instanceID are valid?
Becaues a buffer has a max size but probably the actual size is less than it containing data.

 v2f vert(appdata_full v, uint instanceID : SV_InstanceID)
            {
                // compare instanceId with passed actural buffer size
                #if SHADER_TARGET >= 45
                FluidStruct data = voxelBuffer[instanceID];
                #else
tardy field
#

What is some simple way in shader graph to gradually decrease alpha over height of an object? I was thinking about using a gradient but I can't get it to be from top to down instead from left to right

regal stag
# tardy field What is some simple way in shader graph to gradually decrease alpha over height ...

Depends a little. If this is for 2D/Sprites you may have a problem due to batching. Can use UV coords but will rotate with the sprite.
For 3D/MeshRenderers can be easier. You'd use the Position node.

To get the Y axis, Split and use the G output (or Swizzle with "g" or "y")

If you want "height" to be relative to the object, use Object space. May need to Remap/InverseLerp or Smoothstep the value.
Otherwise for relative to the scene, use World space. Again may need to remap, but probably using the Bounds Min/Max from the Object node.

compact adder
#

hey guys, i have an issue with a fullscreen shader. basically, the hue changes based on the screen position. its more pink at the right and more green at the left

#

im using URP

amber saffron
compact adder
#

it changes color based on where it is on the screen

#

i dont want that to happen

amber saffron
#

That's not how the dither node works. The dither node will return a 0 or 1 value (for each color channel) per pixel, based on the input value.
In the reference image, you can see that it is composed of way more data.
To mimic such a thing you'd need to do something like this :

  • sample the buffer
  • multiply by your color resolution value
  • split the integer and fractional par of the value (use floor and frac nodes)
  • pass the fractional part through the dither node
  • add again to the integer
  • divide by the color resolution
  • output
#

The idea is to use the dither "between" each step of the color resolution

compact adder
amber saffron
compact adder
#

i thought you meant the other dithering

#

sorry

#

how do I do step 3 and 5? @amber saffron

#

i have most of it set up, but I that I did step 3 wrong and i dont know how to do step 5

amber saffron
grizzled bolt
hushed silo
#

hey so I want to do this in a VFX shader graph:

#

using these custom interpolators. Is that possible or just impossible with the VFX shader graph?

#

I don't have the ability to add custom interpolators in the VFX shadergraph

amber saffron
amber saffron
hushed silo
#

I have a shader that was a part of an asset I bought, which has a shadergraph that renders imposters. I blieve it uses the vertex pass to prepare which angle of the iposter to deliver to that fragment (may be way off here)

#

This bit seems to facilitate the bit that actually gets the imposter stuff wroking. And I want to have my VFX particles be imposters

#

if I chanage the render target to VFX graph, I lose the ability to add custom interpolators to the shader

#

I wind up with this in VFX graph but my particles are invisible

#

and I hit this error:

amber saffron
#

Ok, I get the idea.
I think that to achieve this you have to copy the logic in VFX graph and sent the 5 values of the custom interpolators directly as shader parameters

hushed silo
#

thanks. in the shadergraph this is a custom function linking to a C script... Does VFX graph have the ability to do similar?

amber saffron
amber saffron
grizzled bolt
amber saffron
#

It is in the -1;1 range :/

compact adder
#

what variable types are DitherCurve and ColorResolution(1)?

amber saffron
compact adder
amber saffron
#

(you could guess by the color)

compact adder
#

its much better now, thank you

hushed silo
stiff charm
#

Why do I recieve these error messages for a defualt new surface shader in newer versions of VS but not older eg 2019? Edit:Donโ€™t worry Iโ€™ll just use another form of shader lel

tardy field
hearty obsidian
#

I have a plane that's 40x40, with a normal facing up. This is the play area of my game.

I bend everything in a cylinder shape via shaders, including objects hovering on the plane. This works fine.

I use the x position to determine the angle, and then I set the x and y with the angle. The z stays the same. So circles are drawn on the XY plane, and the cylinder goes down the Z axis.

I want to add a mechanic where objects can move outwards (so simply upwards in the actual world). When drawing object, I add the y position to the radius. This works fine, to some extent.

The problem is that the further away from the XY centre an object is, the greater the distance between points for 2 given angles. This ends up making objects seem to stretch on the XY axes as they're moving further away from the centre.

Any idea on how I could solve this?

#

The goal would be to retain proportions, or at least somewhat close to

hearty obsidian
#

Okay, it is somewhat solved...

For objects that aren't the actual plane, to obtain the cylinder's angle, I am using the object's position, rather than the vertex position. To the obtained world position, I add the local vertex position, rotated by the angle at object's position.

Problem is I'm not sure how to include scale

#

to clarify, when rotating the local vertex position around the object's world position, there is currently no scale included. This means all objects are drawn as if scale was 1x1x1. How could I factor in the scale?

#

ok, it was as stupid simple as multiplying the local vertex position by the object's scale before rotating the vector

#

all solved

young rampart
#

I'm trying to create a lit urp shader graph, but I'm having an issue with a texture not sampling the right UVs. When I name the main texture "Base Map" it works fine but if I name it anything else it has the same issue, so I'm not sure if the normal lit shader is doing something special?

young rampart
#

Actually I think I'm just confusing myself with different meshes

frigid kite
#

Hello everyone, I'm having a performance issue with the red-boxed part of this shader made in ShaderGraph and HDRP. When I use this part, the game's performance drops to about 40 FPS, and without that part, it runs at over 120.

Does anyone have any ideas on how to optimize the red-boxed part?

Thank you very much.

grizzled bolt
frigid kite
grizzled bolt
#

Textures, unlike noise algorithms don't have infinite resolution, nor are they infinitely big but there are some workarounds depending on use case

#

Layering textures of different sizes is one way to get large variance together with small details

frigid kite
grizzled bolt
stable crest
#

was just wondering if anyone can explain how I can make a shader that makes hair move both in the wind and when the character moves

umbral panther
#

is there a way to force unity editor to treat a fixed3 as actually fixed3 (ie, ~float11x3 precision)?

#

or like just math to nuke precision above that?

karmic hatch
#

but the shader itself doesn't know if the mesh is moving or anything, it just knows where it is

meager pelican
# low lichen Are you sure out of bounds access is bad? If the out of bound reads/writes stay ...

"Bounds" in this case refers to reading the array (float oceanHeight[100]). so don't read element -1 or element 100, nor 101. They're garbage reads. You don't know what you get back, and don't want to use it.
If the cac using id.x to create an index can be guaranteed to stay in bounds of the array, no check would be necessary, but you might want to do some "If debug compile, do this ____" kind of thing for future-proofing.

meager pelican
trail gale
#

Hey how can I add URP reaction to light to my shader?

#

it isnt done with shader graph

trail gale
#

finalColor.rgb += tex2D(_LightingTex, IN.uv).rgb; // this doesnt seem to do anything

#

this is the code Im using by manually changin the light values, but it still not affected by light

low lichen
# meager pelican "Bounds" in this case refers to reading the array (float oceanHeight[100]). so ...

But if the garbage data you read will only be used to write garbage data also out of bounds, then it's better to let the shader units all do the same work instead of branching, right?
I'm not sure how pure arrays work, but I know that D3D11 guarantees zero for any resource (buffer, texture, etc.) that is accessed out of bounds.
https://learn.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-resources-intro#:~:text=Direct3D guarantees to return zero for any resource that is accessed out of bounds

trail gale
lament scarab
#

Is there a shader I could use that would make a sprite behave just like a standard unity shaded 3d object?

#

(so reflect lights, use reflection probes, receive shadows, etc?)

#

In other words make it act like a texture maybe?

grizzled bolt
fallen heath
#

Hello guys I'm new to shader graph and currently working on some forcefield shader which I saw on YouTube, now I'm stuck

#

I have this notion that I want to make my shader forcefield dynamically interactive

hushed silo
#

Hiya. So I have a shadergraph material which is instanced onto loads of game objects and it batches nicely.

Iโ€™m hoping to have each one tinted in different colours but maintain batching. I think thatโ€™s possible, what are the terms I should search for that?
Followup is, I have eg 4 GOโ€™s under a parent controller GO, and I want the children to take a value from their parent controller to get this tint. What would be the right way to go about this? Thanks!

lament scarab
grizzled bolt
lament scarab
#

Max metallic + smoothness on both

#

maybe something svg related too, but i assumed it worked like the sprite renderer for shader handling

lament scarab
#

could be related to that too

grizzled bolt
#

No idea how that component handles materials

lament scarab
#

@grizzled bolt metalllic/smoothness reflections work just fine with a sprite

#

so most likely due to the svg thing

compact adder
#

Hi, how can I make it so a texture always looks at the camera, kinda like a billboard, but not the mesh itself?

amber saffron
compact adder
compact adder
regal stag
snow forge
#

Hi all, quick question, i have a bunch of textures similar to the one attached, but each one has a different 'darkest' level (ie, the darkest grey on this one is lighter than some of the others, or darker). Is it possible with shader graph to 'normalise' any texture I plug in, in the inspector, so that they all share the darkest dark colour and lightest light colour when processed through the graph?

#

It's a bit Kludgey but seems to work.

grizzled bolt
snow forge
compact adder
#

Hey guys, for some reason when im building my game for android, my fullscreen shader isnt enabled for some reason (im using URP) does anyone know why?

regal stag
compact adder
#

yea lemme configure those

#

thanks fixed it

lavish totem
#

Hi there, I want to create a black and white effect for a 2d game and when an area of the screen is clicked on, a circle around the cursor has colour restored to the screen - I dont whether id use a shader for this or how that would work, i dont whether that would be a shader or something else?

lavish totem
#

^