#archived-shaders
1 messages Β· Page 122 of 1
Also, is it better to use a single part of the shadergraph for multiple inputs or cloning single part of the shadergraph for each separate input
You can add / in the shader name for categories
And it's better to use a single part.
could anyone point : what is the range in vertex object space position? -1 to 1 ? with center in (0,0)?
or 0 to 1 and center in (0.5, 0,5)?
@paper oar the range in vertex object space position ?
If you mean the range of values you get for position in object space : its from the object bounds min to max values
i think it is 0,0,0 at the mesh's pivot (not game object pivot), to whatever the min and max vertex position is, i didn't think the bounds had effect on it (maybe they do, not sure)
if you author a mesh that is offset -100 from the origin in a modeling package and export it that way, then that is how it comes into unity
Hey everyone, Just started playing with Shader Graph to make a blurred overlay but for some reason I can't get Additiona Camera Data to display anything thus _CameraOpaqueTexture seems to do nothing
any ideas?
@tribal yew is the shader set to be transparent?
TBH I'm not sure, I saw that somewhere in a video, stopped to figure out why I cant see the options under the data node
ah so you need to use the Scene Color node to access the camera texture, and the shader itself has to be in a later queue (e.g. transparency) for the texture to be populated with anything
also there are some issues with buffers when using single pass VR/XR but should be fine if you are using 2D
Ahh that looks promising, still no luck but at least I have some documents for that node. Thanks @lime viper, I'll mess around with this and see if it gets me anywhere.
yeah strange, if I make the master node transparent and hookup the scene color to the Master or even a add node I just get black, so I'm doing something wrong. I'm going to try making a blank project just to test this.
so for me I can get it working on LWRP 5.13 you may need that or later for it to work properly
I have 6.9.0, though I just noticed an update to 6.9.1, but I also just saw a posting showing the need for screen position, I think that was my issue.
Would anyone happen to know how to get an image sequence on an animation for a sprite to update the image input of a SRP shader, preferably without code?
Anyone know anything about cubemap UVs?
I'm trying to distort a cubemap texture by sampling a noise cubemap to slightly alter which UV the texture gets sampled from.
The problem is that it works fine in some places:
But it's not distorting in some of the face corners (upper left face in this case):
Anyone have any ideas why it may be doing this?
Shader code I'm using:
float randomVal1 = randomValRGBA.x * _NoiseScale;
float4 randomValRGBA2 = texCUBE(_Noise, i.uv) - 0.5;
float randomVal2 = randomValRGBA2.y * _NoiseScale;
float4 randomValRGBA3 = texCUBE(_Noise, i.uv) - 0.5;
float randomVal3 = randomValRGBA2.z * _NoiseDisplacement;
float randomU = i.uv.x + randomVal1;
float randomV = i.uv.y + randomVal2;
float randomW = i.uv.z + randomVal3;
float3 randomizedUVW = float3(randomU, randomV, randomW);
float4 overlay = texCUBE(_Overlay, randomizedUVW);```
Does Unity support all of the HLSL/CG functionality within the Microsoft documentation?
@tribal glen if I had to guess maybe the texture & material is not laying properly across the plane that won't distort, like when you have a texture and the scale is ( 1, 1, 10000000 ) and it just makes lines clear across the plane.
Are the pits a normal map?
or are they rendered on the camera view itself?
Maybe the shader isn't calculating the correct angle of projection of the effect correctly across the face cause one of the angle is off in the shader code?
@amber saffron Vertex Position in Object space - (used to calculate uvs directly from position) - from [-0.5, -0.5] to [0.5,0.5] - to get uvs - add 0.5,0.5 and voila!
Does anybody knows how to change normals to flat tiangles? for flat squares you would use cross(ddy(worldPosition), ddx(WorldPostion)), but I need triangles....
i've got texture with black space, when i used certain material for it in unity older version of unity wirhout shader graph, black space became transparent, exactly what i needed. but now i cant simulate such effect. can somebody help?
@deep vigil you can select in the import setting of texture how to get "transperency" - options from alpha or others
@paper oar Vertex position in object space goes way over 0.5 and bellow -0.5
@amber saffron used it in shadergraph - in preview it works just as uv, try it, you will see
That's because the mesh in preview is made like that.
works even in the build
The position you get varies depending on the bounds of your mesh
@paper oar i dont see any options regarding to that
all i see is this in the inspector
maybe im searching in wrong place
there should be an option to import it as texture 2d /sprite.... or you can just replace the black color with tranperency in photoshop
ok i think spomething was wrong with an alpha channel all this time
ok, my texture is an alpha channel, and unity sees that but also dont
Compute shader question regarding Append/Consume buffers: how do I avoid over-appending or over-consuming from these buffers? What will happen if I do it anyways?
I've been having a fine time throwing my brain through a pretzel dispenser dealing with race conditions and interlocked atomic operations
what's faster? dispatching a single threadgroup of 1024 threads or 1024 threadgroups of 1 thread each?
I also see that hlsl allows for string variables. what can we do with them?
there aren't any methods for dealing with them.
@paper oar
If you can't do it on the model (check import settings too), you can do it with derivatives.
Does anybody knows how to change normals to flat tiangles? for flat squares you would use cross(ddy(worldPosition), ddx(WorldPostion)), but I need triangles....
http://www.aclockworkberry.com/shader-derivative-functions/#Face_normal_computation_flat_shader
Why do you say it won't work for triangles?
Is there a way to get mipmaps of texture in shadergraph?
sample texture lod node doesn't seem to work
@unreal verge over-appending doesnt seem to cause any issues that i've seen.
You will want to use SetCounterValue(0); somewhere before things start appending (to reset it each frame before it runs the compute shader or fragment shader and appends)
@marble lance the LOD input should control that, it will take numbers from 0 up to 11 or so depending on a texture's resolution, 0 is the full res mip
Oh, i am stupid. I tried to sample screen texture via _MainTex property for blur post effect. I guess its doesn't have any mipmaps that's why i cant get it working.
@uncut karma thank you for your scholarly advice. My knowledge comes from archives of the Scrawkblogs where they foretold tales of much woe and graphics card crashing from over-appending or over-consuming
I'm actually using the append buffer for pooling purposes, so the values must be persistent between frames
that's why maintaining the count of the append buffer is so important to me
it's for a fiber physics simulator where the fibers can be spawned, despawned or broken into sub-fibers
is branching still a massive no-no even in compute shaders since Shader Model 5?
I google for this stuff and I see conflicting answers
Does anyone know if anyone has made a shader that is the same as the standard shader for the built-in renderer, but for the metalness/smoothness map, they separated it into 2 separate maps, that are both grayscale, instead of the Red-Alpha channel map that the standard shader requires???
I am considering either writing my own shader, or just writing my own app that converts a grayscale metalness map and a grayscale roughness map into the appropriate Red and alpha channels in a single image, and inverts the roughness map, because for some reason Unity thought it would be a great idea to be different and do smoothness instead of roughness. (I'm a little salty about this, if you can't tell.)
I've been pulling my hair out over this, because I don't want to have to go through all the extra trouble when exporting textures from Substance Painter, just to make it work the convoluted way that Unity is requiring it for the standard shader. I would be very grateful for anyone's help!
Hey there! Looking for Guidance with Shaders, some one explained a process to me on reddit for computer shaders and i would like to discuss in private then public about compute shaders. MEAN while i will be going as far back as i can to look over this shader channel (Still in progress)
@unreal verge moatToday at 6:28 PM is branching still a massive no-no even in compute shaders since Shader Model 5? I google for this stuff and I see conflicting answers
So all threads in a core share the same PC, right?
Now I think that's true for compute shaders too (IDK about hardware diffs). So similar/same issues for branching apply. That is, if any thread on a core (could be any of the current 64/32/whatever threads) execute an else, for example, or the contents of an if block, then ALL threads step through it in lockstep it's just that some are masked off.
That's why if some bool, for example, comes in as a uniform it isn't too bad, since all threads follow the same path, and it can skip entire chunks because it knows it can since all threads do the same thing.
@bronze hawk
Just my 2 cents, but cloning the shader and maintaining it in the future might be more of a pain than converting stuff to the format that the engine wants. Fighting the engine is a pain.
BUT that conversion doesn't sound too hard if you want to maintain it through all upgrades in the future. Prolly not referenced too many places and changes would be minimal.
Again, just 2 cents.
i've got a shader and i want to change variables of said shader globally for all prefabs of a model that shader contained in and i want to change certain variables individually for each instance of a prefabab, so question is how do i change vector1 float values this way
thank you @meager pelican, that's very insightful.
it's good to know that the gpus operate in lockstep as I had no clue what would determine how they stay sync'd
@deep vigil it's all "by material" but there's "levels"...some things are global to all things that use a material (shaders are materials, materials are shaders!). So read up on MaterialPropertyBlocks and/or instancing. Basically, if you set a shader property like Color on a material, it's set for all objects using that material. BUT...there's "overrides" in material property blocks that use values unique to each instance.
@meager pelican thanks, finally some answers
np.
And watch out for material vs sharedMaterial. You probably want SHAREDMATERIAL.
Maybe dumb question but i have stumbled around for over an hour now so i think it's fair to ask now.
I have two cameras. One for the game and one for a GUI overlay (which is made of 3d objects not sprites)
I want to apply a shader only to the objects in the GUI overlay camera's view but when i try to do so it applies the shader to the whole screen
ClearFlag is Depth Only for the secondary GUI everything else is default settings
#include "noiseSimplex.cginc"
Unity 2018 do not want this part of my shader, why ? What have changed ?
why do my minecraft shaders not work
@river jasper do you have a file by that name?
@ rogue_code : no, i did not have, that was the problem lol, problem is solved all works nice.
@deep vigil
Are you using ShaderGraph? Doing that there is easy, just not expose that node as a "blackboard".
But in a shader code, you know commonly on top you make the variables like float "Display Name" (_VariableName) etc?
And then going down more inside the CGPROGRAM, you again have to do a float _VariableName <--- By having it here without making the display equivalent on top, you're also making a "global" variable that's not gonna show up in each Material instance
@plain urchin what i was doing before is changing the very material i was using, i found the way to change its reference calling for meshrenderer and then taking instance of material that renderrer was using
If you're ok with just instances of Material, then that's ok, all GO using that Material will follow that Material.
If you want each GO to have different paramaters, you can change in code and the Material will have (Instance) next to it
If you want each to have their own parameters (that gets processed by their own Material), without making the Material duplicating (kills draw call batchiing i think), then some specific shader that processes the GO unique could work. Various approach here, but for example, what Unity's particle does, which is taking the vertex colors of the mesh
An even more "global" variable (across all GO, across all Material instance, and across all Material using that shader), then the one i mentioned previously is that (inside the shader)
@ Delgelato: I think shader Graph is very complicatet. I dont know how only just to start, so much "Menus" and "Variables" only if you WANT to do a shader, that you dont know what to do. In the Time you learn how to "start" you can easy write 10 shaders.
lmao https://docs.unity3d.com/Packages/com.unity.shadergraph@6.9/manual/index.html literally everything is here
@ theBaka
very thank you, problem is solved, it s all okay
and my Sample Development, performes like hell.
all nice π So :
PROBLEM IS SOLVED
VERY THANK YOU TO YOU ALL, nice to have such PPL around π
guys can I use shader for increasing image brightness?
guys I found two different shaders but I want to combine both of them
is there someone who can do this
'combine them' is a bit vague, can you be more specific
in what way did you get stuck attempting to combine them yourself
what didn't work well? What result were you getting?
I want both of them to work
one of them has hue, brightness, saturation and contrast settings
other one has black masking property
it blackens out image and make blacks transparent so you can see whats behind
I want one shader to do these two work
what didn't work when you attempted this yourself?
why you asking so much questions?
its simple, combine these two shaders
if you dont want to just say it
whats your purpose
My purpose was to help you with any concrete issues that you might have encountered when attempting to combine these shaders
My purpose is indeed not to do this myself
good luck
thanks
Start with the shader that adjusts everything, and then just try to make the exception-for-black part work.
Maybe if you're already blending, set alpha to zero if it's black....or if you're on hardware that isn't sensitive to a discard instruction, discard the pixel.
The way to combine them is:
Start with a copy of the shader that adjusts everything, and then try to make the exception-for-black part work by adding that to the logic.
π
I dont know how shaders work
and I think you still saying how to write a shader that masks black
I already have black masking shader and brightness adjuster shader, I need to pack these two in to one shader
I'd like to enable/disable a given shader graph tree (not the entire graph) based on a Boolean set by a script. Is this possible? I understand how to trigger the boolean from the script, I'm just not really sure how to do the enable/disabling of certain aspects of the graph based on the boolean value. Can anyone point me to a good example?
Looks like the "Branch" node is what I was looking for... in case that helps anybody else out there.
Note that while this works, it's not ideal performance-wise as both pathes of the branch are still executed. Static toggles (creating actual shader variants) are on the roadmap it seems but not available yet
Uhh, so I created a material from a pbr shadergraph and this happened, it only occurs in-game. Can you please help me?
Is it possible to apply multiple different shedders to different parts of a single 3d model with different texture maps?
Note that while this works, it's not ideal performance-wise as both pathes of the branch are still executed. Static toggles (creating actual shader variants) are on the roadmap it seems but not available yet
@gilded lichen Not sure that's correct my new friend. But it's an interesting discussion so if you don't mind maybe we can explore this as a group.
The conditional compilation that you're talking about makes the shader variants. And it's true that using that only one of the options will be compiled in. With that said, an if/branch in GPU code doesn't always execute both paths.
My understanding, and someone correct me if I'm wrong, is that the alternate-path will only be taken if any of the processors in the wavefront/warp meet that 2nd condition. So if there's 32 (or whatever) processors that evaluate a condition, if any one or more of those 32 meet an else, all 32 will lockstep through it, but most will be masked off.
What does this mean? It means that if a user is setting a condition THAT IS UNIFORM when he/she calls the shader, the branch isn't taking all paths, since none of the processors met the condition, and the GPU can skip it.
This may vary by device too. Some devices/compilers are smarter than others.
I bring it up because the last person I discussed this with mentioned that he was setting a uniform. π
It's better not to have the overhead at all if you can avoid it with calcs and/or ?: operations. But sometimes ya gotta do what ya gotta do.
I think you're right that variants are better though. π But if you can do a variant, you can do a uniform.
There's a good answer here: https://stackoverflow.com/questions/37827216/does-if-statements-slow-down-my-shader
Tldr is "on modern hardware (dx11/gles3) it shouldn't matter for uniforms but it still might depending on device implementation"
But even given that on DX11-level hardware (so, everything HDRP runs on) the performance of uniform branching is neglectible - I'd think that Variants would only set up/upload to GPU the shader parameters etc that matter for them while branching still has to set up/upload everything. No idea about performance/memory there though
Yeah, using a variant has no overhead other than the setup time to switch shaders which you might have to do anyway, I think. So you'd have to benchmark it. If it's just a bool difference, then is using a variant and not having an if that much faster? You still have one shader source too.
But there's edge-cases. Like let's say you do an effect, but put a border on the screen. So an 8x8 block of pixels get shaded and only the edge ones get the alternate branch, and the rest are all "uniform". So it's not a bool you pass in, or a variant, but an effect. Knowing how that if works might stop you from making two passes or something where one might be faster, since the majority of the time it's only using one branch.
I think. π
Heya, I'm quite new to Unity but has worked with UE4 some time.
Anyway, I was wondering, in UE4 I used a couple of packed textures (so for example I had AO in the blue channel of the normal map). Should I keep doing that practice and create a custom shader to make use of those kinds of textures properly, or is there some kind of performance hit to using yet another shader rather than the Unity default one (and pulling in the AO as an extra texture rather than packed into the normal map)?
Also, are the oldschool shaderlab shaders better in performance than those made in shadergraph for a similarly advanced shader?
@proud robin packing textures is still good to do
Anyone have any idea how one could do different textures on different meshes sharing the same material without atlasing?
I basically have these environment meshes which make super great use of texture wrapping to tile across their surfaces. I can't atlas their textures because the UVs on these meshes go far beyond the bounds of the texture (for example, a square of grass) to tile it.
That leaves me with, like, 20 identical materials with zilch changed but the texture. Which feels like a waste of draw calls.
I'm trying to free up graphics resources to do a shadow pass, and I feel like I could get away with it if I could find a way to batch the entire environment together. Any ideas?
If your target platform is high-end, you could group textures into an Texture3D Texture2DArray and then pass an index for each object to index into the array. That's one way.
Just a random thought. Another might be seeing if instancing supports changing the texture per-instance.
EDITED: Thanks @gilded lichen , Texture2DArray is the way to go.
Hello @meager pelican! Target platform is mobile, would the Texture3D be that bad an idea on low-end?
And from what I can see, instancing does not support changing the texture per-instance
You usually don't want to get too fancy, on those fancy-calculators. And "mobile" has a wide range too.
So IDK, I'm not the best one to comment. I'll leave it to the group and wish you good luck. Maybe there's "tricks".
Alright! Thanks for the help. For reference this is an Oculus Quest title.
It just looks like this is about doubling the cost of drawing what is otherwise a relatively simple scene.
Maybe there's an efficient method for emulating wrapping, clamping and mirroring w/in a texture atlas?
How many textures do you need?
Depends on the environment
Let me get the texture count for one
Let's call it 20
I have another environment with on the order of 40
@dark flare
Atlas isn't possible unless you have a fast way to emulate wraparound?
That's kinda the entire crux of the question.
And why would that be better than using a Texture2D array, which is also supported by the Quest GPU?
Wraparound?
You mean make the texture repeat?
Just use the modulo operator
or the fmod function
Atlas texture means its one texture. Array is a lot of textures. The context switch isn't free, especially on mobile
@maiden gull
@dark flare I definitely get that. However wouldn't the context switch of changing only the texture of a texture array be significantly cheaper than the 20-40x draw calls?
why would an atlas cause 20-40 draw calls
It wouldn't, the 20-40x draw calls is my baseline for being stuck using a different material for every texture (20-40)
ok, so don't do that
the alternatives are either an atlas, or a texture3d (its a texture2d array, which is just a lot of textures..)
I also have a concern with using a subtile on an atlas, which is getting bleed from other textures on the atlas due to mipmapping + sampling
if you're generating the atlas, then also generate your own mipmaps and ensure there isnt bleeding
Would there still not be any artifacts from the sampling? Other instances I've seen during research for this seem to have that issue regardless of mipmaps, but the mipmaps seem to exacerbate it
they are just bad implementations, then
there's no inherent reason why there are artifacts, just naive code
example, im doing literally this in a voxel based game im working on, even blending between the textures within the same atlas: https://i.imgur.com/1tKM0zP.png
I'm new to writing shaders, haha, probably best not to tempt fate.
I totally get using an atlas would be faster than a Texture2D array. I definitely intuitively get the sample-from-a-Texture2D-array implementation more than how I would implement a custom wraparound. I'd be the naive coder here. So I guess my question is, would using an atlas VS a Texture2D array be super worth it for the 20-40 tile range if I'm nearly hitting framerate even with the crazy drawcalls?
Oh that looks sick
if you're only concerned about performance, it doesn't matter as long as the game is hitting framerate i suppose, unless you also want to care about battery life
That's true
try doing what is easier first, then figure out the optimal solution after
I feel like this wouldn't have the most massive impact on battery life
Alright!
If I'm still having issues I'll hit up here again. Thanks for the help! Really nice to get perspective from people who actually know what they're doing here haha
np. the more specific the question the better answers you'll probably get
@maiden gull don't use Texture3D, use Texture2DArray
it's actually faster than atlas in many cases since you don't have extra math for wrapping inside the atlas etc., you don't have to do separate handling of edges between textures etc.
bake the array index into the mesh vertices - we're using uv.w for the array index for the textures. Then you can render everything with one material without extra MaterialPropertyBlocks
We're doing that for Quest and it's really fast
Hi guys, is there anyone who could help me with this problem?
I have been trying to solve it for weeks, but I can't find a solution!π£ https://forum.unity.com/threads/problem-shader-sprite-mask.722048/
2019?
@tardy dock yes, the last stable version
Hey guys, is it possible to implement rotation on all three axis for the HDRISky (HDRP)?
And it would work in a fragment shader?
What should I get started on to go from not knowing anything to being able to make pretty visuals like this:
The packs are around 30$, but should I be looking at that or are there ways or resources to learn to do this for free?
@me if you respond to this question so I can see it :)
@haughty mulch yeah just a little expensive
unless you're wanting to rotate in real time, just do it in the texture
Yes it must be rotating in real time. What do you mean in the texture?
Opening Photoshop and rotating it lol
If real time then a shader that rotates the uvs with a rotation matrix is probably easiest
@mossy kraken Pick up blender, it can do all that and more
@raw grove The graphics itself? I'm not worried about the physical objects, just the effects
ahhh, prob just good lighting
check this out, see if it helps https://www.youtube.com/watch?v=IkRMMcPBFsc
Unity 2017.3 Low Poly Scene Lighting and Post-Processing Video tutorial. In this Video, I'm showing Step by Step how I setup Lighting and Post-Processing for...
I'm brand new to unity, so I'm learning how gameobjects and components work
I'm not new to programming, but this is... Overwhelming
And I'm frustrated by how relatively slow I'm working compared to a new project with something I'm used to :(
Lowkey same lol, lots to learn lol. I have done SOOOO much research tho lol
How do you keep your game logic wrapped up? I'm so worried about it
It's like every bit of code is spread out. I want to generate a map, but do I like... Create a map object?
Or a map gameobject
Not super experienced so I may be wrong but i use just very many, precice scipts, then I folder them
Fair :) encapsulation is your friend
I'm thinking a map gameobject with a script inside that knows how to randomly generate cells and stuff
I have seen alot of people use terrain generators that include seprate objects like rocks and trees
So thats prob the best way for procedural but
Terrain generators are a built in thing?
Again, take what I say with a grain of salt bc its based on research not experience
No u would have to program the generation yourself im guesing
I bet there is a tutorial online to kick start ya
Found this https://www.youtube.com/watch?v=wbpMiKiSKm8
Welcome to this series on procedural landmass generation. In this introduction we talk a bit about noise, and how we can layer it to achieve more natural loo...
I think I'm going to have to manually make the grid system and spawn and center player entities on it
on the bright side if ur working with low poly it will prob be easier lol
Yup :)
you checked out unity's particle system? its glorious
I haven't! I know nothing and I'm just obsessed with figuring out the game logic :(
Yeah, Im slowly learning
Just made a state machine that I understand a good portion of well so yay
Nice :)
guys I need help, how can I add brightness property to shader simplest way possible
I have a shader which does black and green masking to images
I want to be able to control images brightness too
but I dont have enough knowledge to do that :/
I'm not sure to understand here ... you want to adjust the brightness of the input / output of the shader ?
To modify brightess, you can multiply the output color by a value >1, or add an uniform value (this is more a gain)
but I dont how where to add these
Shader "Custom/curved"
{
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
_thresh ("Threshold", Range (0, 16)) = 0.8
_slope ("Slope", Range (0, 1)) = 0.2
_keyingColor ("Key Colour", Color) = (1,1,1,1)
}
SubShader {
Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
LOD 100
Lighting Off
ZWrite Off
//AlphaTest Off
Blend SrcAlpha OneMinusSrcAlpha
Cull Off
Pass {
CGPROGRAM
#pragma vertex vert_img
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
sampler2D _MainTex;
float3 _keyingColor;
float _thresh; // 0.8
float _slope; // 0.2
#include "UnityCG.cginc"
float4 frag(v2f_img i) : COLOR {
float3 input_color = tex2D(_MainTex, i.uv).rgb;
float d = abs(length(abs(_keyingColor.rgb - input_color.rgb)));
float edge0 = _thresh * (1.0 - _slope);
float alpha = smoothstep(edge0, _thresh, d);
return float4(input_color, alpha);
}
ENDCG
}
}
FallBack "Unlit"
}
You would modify the input_color variable just above the return line (that is where it returns the final pixel color)
Been trying out the new LWRP 2D shaders, and I notice it only has 3 properties. Does that mean I can't do things like... change the alpha, brightness and stuff like I would with the standard shader? It seems limited?
is there any support for feature switches in Shader Graph?
@uncut karma so I will multiply input_color by what?
A new shader property, copy how threshold is written, alter Range min max, then be sure to also add the new property down by float _thresh; too
Basically inside Properties{} exposes it to material inspector
okay lets say I created _brightness property, how can I multiply the input_color
input_color += _brightness;
is it like that @uncut karma ?
@bleak zinc no shader_feature yet, it will be in the future according to their site
@thick umbra you just asked how to multiply
and then posted addition
lol
think about it
Thanks @dark flare
π π yeah I'm sorry
I just cant get shaders and graphical programming
brightness level will be between 0 and 1 I think
1 is the brightest, right?
so if I multiply input_color with 1, how it supposed to give brightest image color
it should give the same result since input_color * 1 = input_color
input_color * 2
Shader "Unlit/PixelColorSwap"
{
Properties
{
[PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {}
_Color1in("Color 1 In", Color) = (1,1,1,1)
_Color1out("Color 1 Out", Color) = (1,1,1,1)
_Color2in("Color 2 In", Color) = (1,1,1,1)
_Color2out("Color 2 Out", Color) = (1,1,1,1)
}
SubShader
{
Tags
{
"Queue" = "Transparent"
"IgnoreProjector" = "True"
"RenderType" = "Transparent"
"PreviewType" = "Plane"
"CanUseSpriteAtlas" = "True"
}
Cull Off
Lighting Off
ZWrite Off
Fog { Mode Off }
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile DUMMY PIXELSNAP_ON
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
float4 color : COLOR;
float2 texcoord : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
half2 texcoord : TEXCOORD0;
}
fixed4 _Color1in;
fixed4 _Color1out;
fixed4 _Color2in;
fixed4 _Color2out;
v2f vert(appdata_t IN)
{
v2f OUT;
OUT.vertex = UnityObjectToClipPos(IN.vertex);
OUT.texcoord = IN.texcoord;
OUT.color = IN.color;
return OUT;
}
sampler2D _MainTex;
fixed4 frag(v2f IN) : COLOR
{
float4 texColor = tex2D(_MainTex, IN.texcoord);
texColor = all(texColor == _Color1in) ? _Color1out : texColor;
texColor = all(texColor == _Color2in) ? _Color2out : texColor;
return texColor * IN.color;
}
ENDCG
}
}
}
I don't know if the code could be improved (unfortunately I'm not an expert on shaders), but currently it seems to work properly.
Once the shader is assigned to my sprites, I can change their color correctly, but I have a problem if those sprites have to be used together with another object that contains a Mask.
I immediately leave you a .gif, of the problem, so that you can immediately understand my situation:
https://gyazo.com/e3e45910d017298fb8b7e357caf47412
As you can see the numbers on the left (simple UI Image) are correctly cut by the mask, but the fish (which have the material with the shader active on them), are not cut by the mask, and disappear only if their lower part exceeds the edges of the mask.
I would like the fish to be cut by the mask like the numbers. I think it's a problem with my shader, because if I use fish sprites without shaders, the mask works perfectly.
However, I am attaching a screen of how the mask of the object containing the clipping panel is currently set:
https://gyazo.com/475b208ade0464b0cbbde2ce8326a28d
Can anyone help me? I tried all the ways, but I can't solve this problem ...
@radiant night Next time please post large amounts of code to an external service.
I would look at the built-in shaders https://unity3d.com/get-unity/download/archive <- can download from the links here, to see how Unity's shaders implement the masks
@vocal narwhal I'm sorry, I didn't understand what you mean.
The link you gave me brings me to a Unity download page (which I already installed on my PC).
Unfortunately I tried to search, but I can't understand what I have to do, to make a shader work together with the mask.
For the code ok. Next time I'll try to use patebin or some other service.π³
The downloads for each version have Built-in shaders as an option
Hi there, any news of tessellation and or parallax occlusion support in HDRP TerrainLit shader? or does anywone know of a hack/custom terrain shader to have these working with the new Unity terrain system? π
Hack : use the layered lit shader for the terrain, but you will be limited to 4 layers
Actually I was about to go with the layered lit tessellation but I can't use the Draw Instanced option with it...
and it makes the terrain LODing look incoherent at a distance it seems
@gilded lichen (Just got your mention helping me with Texture2D array last Monday - thanks a ton, that helps SO MUCH)
...what exactly does the axis correspond to in the shuriken particle system Custom Data module? lifetime? https://docs.unity3d.com/uploads/Main/CustomDataModule.png
its for custom particle shaders
you can pass in arbitrary data to go into the vertex stream
its a float4/Vector4, not necessarily an axis
if you dont use a custom shader you probably dont need the custom data
@wild edge
@dark flare a color gradient is a vector4 that varies along one dimension
what dimension is that
thats a good question, im not sure. i think its lifetime, you should test
if these gradients were Tex2Ds, uv.x would be pegged to lifetime in the top, and velocity on the bottom
it seems weird that I can't select which for custom vertex streams, what if I need emissive color to vary based on velocity for example
oh, when you select which custom vertex streams to pass in
you can choose what its based on
check on "use custom vertex streams" and hit the plus
mystery solved lol
(its under Renderer on the particle system)
are those not different things?
that looks like it packs data about the particle simulation in the lowest unused texcoord channels
not like it's letting you select where from the gradient/curve the custom data is being sampled
dang good point
I'm guessing it's lifetime
i think i'm just going to have to add more samplers to the shader and add my emissive gradients as textures
can you let me know what it ends up being? driving me nuts now too lol
I think what I should have done is do this in VFX graph from the beginning, I forgot how weird shuriken gets when you need to extend it
and that it didn't support changing emissive color by default and that the problem is impossible to google because everything links to the Emission module
how do I go about if - else statements in fragment part of Cg code? I want to disallow division by 0 and instead output 1
We're wanting to create grass for our game, but it can't be on the terrain. It's on top of other objects. If we make a grass texture plane, how can we best animate it to make it look like it's moving?
@wild edge you could pass in your own StructuredBuffer and use the lifetime vertex stream to sample from it
kind of a last resort i suppose but it would get what you want
@grand jolt what do you mean? if(){}else{}? that just works. if you're passing in a uniform into the if on most modern hardware its fine
yeah had a mix up
@grand jolt
how do I go about if - else statements in fragment part of Cg code? I want to disallow division by 0 and instead output 1
One way:
float result = (denom != 0) ? num/denom : 1.;
watch out for side-effects in the expressions as both sides are evaluated. (Pretty sure) So no var++ type stuff; π
? : syntax is just an if/else. careful
Both sides are not always evaluated
If the compiler can determine all the nearby fragments are the same, only one side is evaluated. This is easy to gaurantee if the if statement just contains uniforms
Compiler cannot guarantee it if you do something like, sample a texture and use the result in the branching expression
Also only "modern" hardware does this optimization and some mobile stuff for example still just runs both sides and throws one away
@meager pelican use num/max(denom, 0.0001); or similar
How do I access the "Mask Map" for Terrain? I'm on the standard pipeline. Not sure if I can access this map or not. But I'd like to utilize it if I can. I can't seem to find anything online on how to even put it in a custom terrain shader.
The unity shaders are open source, just Google unity archive and download them to see how their shaders are accessing it
I need some help editing the "Lightweight Render Pipeline/Particles/Unlit" shader to ignore the Z buffer (I think?!) -> I need it to show through other objects / always be visible
Original shader here for reference: https://pastebin.com/7i5JQmhd
I've been trying different things like removing [HideInInspector] or make it [ToggleOff] on the ZWrite property, but to no effect..
@dark flare ? : syntax is just an if/else. careful Both sides are not always evaluated If the compiler can determine all the nearby fragments are the same, only one side is evaluated. This is easy to gaurantee if the if statement just contains uniforms
That's true (and I detailed it the other day) but in this case it probably compiles down to a conditional move in many levels of hardware. Per NVidia's CG doco, the ?: has side effects on both options.
The zero test and the conditional move are a total of two instructions on most modern hardware regardless of the value of Denom assuming you do the division math first. Check specific use case though.
So it's an if, and you always end up doing the math, but it's not the same as having a huge block of code. That "move 1" isn't much and would likely be the rare-path.
The bottom line is he has to check, has to have an if of some sort, assuming he really wants a 1 as a result when denom would be zero.
It's all heavily hardware/situation dependent as to the result, in some cases particularly simple ones, there's special GPU move instructions that can handle the binary case of a simple bool if it's not executing a complex code block.
@uncut karma
That gives a different result, doesn't return the 1 that he/she wanted.
But I'm always looking for better methods. π
Interestingly some doco on some hardware basically says that min/max is implemented the same way as the ?:
lol, Irony, thy name is GPU compiler!
Makes sense since foo = max(val, .00001) is basically the same as having foo = (val < .00001) ? .00001 : val; They probably all end up compiled down to stuffing values into a couple registers and doing some conditional move instruction. All that is vastly different than having two large blocks of bool-depedent code.
@proven sundial You probably want to change the ztest always not the zwrite (and you might not be writing to zbuff anyway if you're doing transparent particles)
Actually got it working at last, but do you know if it is possible to have the material render in front of all others except of one or more other materials, which by themselves render as usual.
Visual example. The planes with crosshairs will go below ground plane and other objects, so I want to have them ignore z buffer/depth. But I would like to render them behind the car material - which can get obscured by ground etc.
Almost anything is "possible".... ;)
But you'll end up doing special render passes for exception-materials. Like putting those into a different layer and rendering them separately with different options. It gets complex if you're talking transparency. Maybe lay out the transparent vs not facts and maybe we here can help you.
Transparency is done after opaque since it needs to have the underlying colors, and even then, the order of transparent things matters.
Oh, that example got added.
OK, why not put the crosshairs at the proper depth so culling works?
With proper depth, you mean slighty above ground plane? I figure there will be issues with z-fighting and the groundplane is not flat
Then render the car later, over top of the other things, I guess. Others may comment and add more. π Like stenciling or something.
Yeah, that's basically what I'm after.. Rendering the car material after/above the crosshair, which has these properties added " Cull Off Lighting Off ZWrite Off ZTest Always"
@meager pelican can you point me to documentation on ?: being different than if/else?
It's not that it's "different" it's that depending on content/context it results in different code generation.
?: is a form of an if, so I'm not sure what you're asking for. It's all "a conditional"...an IF or an ?: ... are all testing a condition. But there's types of things going on, like you pointed about about uniforms vs non-uniform. And then there's hardware instruction set, compiler smarts, etc.
I'll see if I can find the post about it I saw yesterday.
See posts #2 and #3 in the link below for examples of the discussion. It's all compiler and hardware dependent, but mostly the ?: construct is usuaully simple enough to optimize to a select instruction. BUT some if's might be too.
I like the ternary ?: operator because it's usually pretty simple and concise.
https://forum.unity.com/threads/about-branching-and-min-max.498266/
Like I said, that's just "one way". And the condition he/she is talking about is probably not a uniform being a divisor, but I can't tell from the information given. It's totally a "try it out and check" type of thing no matter what. Why you always need to try and test on target hardware. Thing is there's so many GPU's...
π
maybe i misunderstood, i thought you worded it in a way that suggested ?: was treated differently at the compiler level than if/else for some reason
i guess the question is if @grand jolt cares about denoms under 1, num/0.5 num/0.34 etc, and if having 1 in the output is important for if it is zero
I thought he said he wanted to guard against the divide-by-zero issue, and return a one. In that case, it's a specific value...zero...that he'd check for and return a 1.0.
We'll see if he returns and clarifies.
@dark flare It's more about how a simple binary condition can be treated differently. There's some instruction on modern GPUs that's a conditional move. So you test a condition and then it moves reg1 if true, and reg2 if false, and it's all in one instruction. And it has to evaluate to set the contents of BOTH reg1 and reg2. In his case reg2 is a constant value of 1 though.
BUT, if you do a conditional on a big-block-of-code A, and an else for big-block-of-code B, then it obviously doesn't compile down to an instruction.
It's all context sensitive as to what the best code to generate is. Same with the uniform condicitonal thing. There must be some hardware somewhere therein that tells if any processor in the wave failed the condition or if it can do a jump and increment the PC.
And yeah, I'm talking out of my butt here. But to be fair I've been reading, and it's just an interesting topic.
No offenses or critiques meant. π
i know all that, i just meant the way you worded it implied there was some compiler-level difference between ?: and if/else, so i was asking for documentation on that. but since thats not what you meant it doesnt matter lol. just a misunderstanding
there's no difference, at least on directX
using max for preventing division by zero will save one instruction, not sure how many SGPR vs VGPR
there are alternatives like this, but I don't think it is as useful on modern GPUs as it was a few years ago
float when_neq(float x, float y)
{
return abs(sign(x - y));
}```
@uncut karma
there's no difference, at least on directX
Yeah, good to know, didn't say there was a diff, though. I'd assume that this:
if (denom == 0)
foo = 1.;
else
foo = num/denom;```
compiles to the same thing as
``` float foo = (denom == 0) ? 1. : num/denom;```
But who knows? A difference might happen in some implementations.
The much more interesting question is "What does it generate for code?" and "Is there a better way?"
But who knows? A difference might happen in some implementations.
i would hope it would be a bug
i hate magic stuff like that
does anyone know how i could make a decent looking cartoonish water shader without the shader graph?
the shader graph just annoys me because everyone uses it now but i cant switch to the LWRP because all my shaders use older shader types
Just use Shader Forge instead
i'm willing to get it now if it's free, and will consider it if it costs more
Hi
Trying to create a realistic underwater scene. I have my animated assets but really need realistic 'god-rays' and caustics for the ocean floor.
Is anyone aware of a good asset or shader for this?
i need something like that as well
i'm trying to make some water based off the ocean from legend of zelda wind waker
not a copy, just the same style
oh wait @vocal narwhal i can't use shader forge because i'm using unity 2019 because i made the mistake of choosing the default render pipeline and i'm too far into development to change
You're not guaranteed to have much stability or anything any more as it's all just maintained by random community members
oh okay thanks i'll give it a try
But if you don't have any shader programming skills it's either that (for free) or Amplify
ok
@dark flare I did that, and the problem is - HDRP and such don't use regular shader code, it uses however shadergraph works which isn't a regular shader code. So that doesn't really show how to access the Maskmap for the terrain.
For regular renderer
Oh wow, last time I made a custom shader with the Shader graph it looked like just a bunch of stuff inside []. But go onto the GitHub and found the shader code looking like I'd expect. Thanks.
Anyone got an idea how to get this shader working for LWRP? http://wiki.unity3d.com/index.php?title=SkyboxBlended
Problem seems to be the multiple passes. Anyone got an idea how to blend two skyboxes in one pass?
Oh, wow, it's been a while since I haven't seen fixed function shader code π
Anyway, I don't see how you would convert that to a LWRP compatible skybox shadergraph
But you could make a shader compatible with the custom render texture that would be connected to a HDRI sky
okay, maybe I should try that out!
Just found out material.lerp exists...maybe that's easier
It interpolates the properties ... I have some doubts about it beeing able to interpolate textures ...
you are right... would have been too easy!
Anyone had any luck with shader graph dealing with object space normals?
I've been able to see the expected results sometimes but there seems to be something that will "break" it
the case where it works I've had to do a transformation node object into world, and then world into tangent
how can i make it so planes with my water shader appear to go up and down like waves?
@primal eagle
here is a small example for sine waves
I do use a custom function node but you could do the same with just regular nodes
for this I'd recommend custom function node though since the equivalent node setup would require lots of space
without the shader graph tho
i'm not switching to LWRP because it would be way too much work to update all of the hundreds of materials and shaders in my project to something that's compatible with that render pipeline
and even if i did switch i'm pretty sure i could do the same exact stuff with either scripting or the graph
i would totally use the shader graph if it worked with the render pipeline that most people use
oh wait i remember someone telling me about ShaderForge or something earlier
i doubt i'd get any help with this older thing tho
it's not terrible
a bit less user friendly than other shader graphs but it's free and it's the only one i can use so idc
updated version of ShaderForge?
yes
someone's fork?
i dont really know what it is
but all i know is it works with unity 2019 and the default render pipeline
am I misunderstanding something? im using drawmesh and enabling instancing seems to worsen my performance https://gfycat.com/candidrespectfulcrocodileskink
Check the profiler...you'll get better stats for GPU rendering. Maybe show what that says. And the frame debugger will tell you what's going on per draw call.
2 cents.
hmm big hit due to shadows and BatchedRenderer.Flush / Batch.DrawInstanced, though I dont really if this is to be expected or not
also can you have instanced properties in shader graph? frame debugger shows that only a tiny fraction of my sprites are actually being instanced
Are they all the same material (looks like it but...asking)?
I think the Frame Debugger tells you why they aren't being instanced, but it should show up as Draw Mesh (instanced)
Static batching will mess up instancing, try turning it off.
I assume you're using DrawMeshInstanced() and also an instanced shader.
Working blind here.
Same material, using DrawMesh for now. Frame debugger saying non instanced properties are set for an instanced shader, google tells me this isnt yet a thing for shader graph. Also when using DrawMesh and setting false to both CastShadows and ReceiveShadows I get crash repeatedly so going through and making a bug report
I think you need to use DrawMeshInstanced(), but IDK, I usually work in standard pipeline. Shader graph is too bleeding edge for my current taste and patience.
Static batching seems to have no real effect whether enabled or disabled(for now), will test DrawMeshInstanced as soon as I get this bug report out
I appreciate the help, totally forgot the frame debugger existed
also keep forgetting to use profiler too for this stuff, should be second nature
Don't forget RenderDoc too, and see the pins (stick pin on top of this discord screen)
π
It should pick up DrawMesh() from what I just read.
Hard to tell unless I was hands on. Hope others will help. I've gotten it to work, and with custom shaders and attributes, but that was standard pipeline.
ok i guess it was just being at odds with DrawMesh, using DrawMeshInstanced negates the earlier performance issues π
lol
See, now their docs say
Unity automatically picks MeshRenderer components and Graphics.DrawMesh calls for instancing. Note that SkinnedMeshRenderer is not supported.
https://docs.unity3d.com/Manual/GPUInstancing.html
are there any shaders that might be used in a game with borderlands-style graphics other than just the standard shading with an outline?
It took years of work from veteran graphics engineers to get that style just right.. and you're just asking "how do I copy it?" lol
no i already got the basics down and i'm asking if there's objects in the game that have graphics that are different than just that basic cel shader with an outline because i'm trying to make a game completely different to it only using the graphics as inspiration
I think you misread my question
Hi! Is there any way to specify a renderTag for a ShaderGraph shader with an intent to use it with Camera.renderWithShader? HDRP, if it makes a difference.
@primal eagle there's a bunch of crazy tech in borderlands, they've done some technical breakdowns. Subsurface scattering on semi translucent materials, for example
okay
It's been awhile since I've played, but I remember some pretty convincing cloth shaders and fluid shaders, stuff like goopy that ran some kind of viscous fluid sim
There were a lot of volumetric materials, stuff like ice/crystals/snow/smoke
Also, it seems that 'Cull Front' is not available for ShaderGraph, is it? Should I use Double-sided master option and cull front-facing pixels?
The same way you get to Carnegie Hall.......practice! ;)
Unity has some tutorials on beginner stuff. See the documentation for examples and try them out. π
Where ?
Also see shader graph for the new pipelines and the pins in this discord above. And https://docs.unity3d.com/Manual/SL-Reference.html
is it possible to have a shader for my UI that makes it appear glitchy?
like maybe the text moves a bit and the colors change and there's lines going down the screen
possible yes
okay
well i don't have any experience with that so i'll just use a cube as my UI panel
I am just trying to make a shader that allows for the mapping of alpha from one image onto the actual image of another by overriding its alpha. I am new to shaders, so can someone please tell me what I did wrong?
https://hatebin.com/kkbyqakqlz
Check out the docs on blend modes for unity
@dark flare I'm not really talking about blend modes
Overwriting doesn't make sense in normal rendering but if you're referring to something more custom it's possible
You might need to be more specific
is your alpha texture single channel? if so you may need to use
pixelColor.a = tex2D(_AlphaMapTex, IN.uv).r;
@silver bronze
@grand jolt I'm sorry I'm really new to this stuff, but I found out that I didn't even have the proper tags for using transparent-based stuff
.a is the same as .w by the way. .a is just more applicable to colors whereas .w is used more for vectors
This is my new code and I think it works kinda? https://hatebin.com/blofnqqznb
oh yeah your shader isnt setup for alpha blending at all
Oh I didn't know .a was a thing
I could never bring myself to learn proper shaders, it's so confusing for some reason xd
well it can be a nightmare if you dont have the right foundational knowledge about certain things
what topics exactly are confusing you right now?
Well for some reason it seems to not be working right still
send a pic
This was just me testing it out:
Which is confusing because it didn't work right for the top but it did for the bottom
what are the textures?
Main texture is fed in by what the material is on so that part doesn't need anything in it ofc
okay, try to use .r to set alpha
well i guess that wont really effect it. but fyi if you want to use a texture to define alpha by itself you should use a single channel texture
.r is red but it is also the first channel
but here you have alpha so dont worry about that
nvm
black/white
Yea ik
Ignore what I said lmao
for single channel you just deal with any of the channel right?
(r g or b)
all is fine. also keep in mind the standard surface default shader is very very different from the standard sprite shader
if you want to use this for sprites i recommend copying the default sprite shader from unity and just making the changes you made here
This is only for textures
what?
See I don't get why it is messing up the color of the top right
Ignore the clutter I was just testing some stuff π
it doesnt look like you have any transparency at all
can you show me what it looks like with the base shader you used unmodified? except for slight transparecny
i dont really know how your scene is setup/textures your using
but what you supplied as a shader should work for 3d meshes that want to use another texture's alpha as its alpha so you had that right. not sure if it is specifically what youre using it for though seems to be the issue
w/ mat
nothing is transparent
wait do you mean what I am doing is for 3d?
yes
yes
and that shader refers to an include for its surface function so you will need to know how to copy that, paste it into the standard sprite shader, set that function name to something else, set that to be the surface shader, then modify the alpha to be your other textures alpha
O_O_O_O_O__O_O_O
shaders are more similar to c than c# as a language so this might be a large part of your struggle
also knowing how things are actually rendered in an engine is important as well for writing shaders
once you understand the language AND the graphics foundation youll find that writing shaders are not hard at all but those things are pretty essential if you want to write good shaders
I haven't touched C that much, but I have done a bit of C++
that is good
dont bother learning c for shaders here. just make sure you know how to read both unity docs and nvidia's cg docs
the confusion for me is that there is no real intelligence or rhyme or reason for where and what you put
and it just mindfucks me
okay, that sounds like it is a lack of knowledge on how things are actually rendered
part of it is because if I look at references everyone does them so differently
that too
I had made a point to stay away from shaders until I needed to
that is because youre using unitycg before looking at how languages like hlsl or glsl look. unitycg is an odd one but makes more sense as you go
I'm confused partially because back when I played with shaders it was w/ C++ where you had 2 seperate files with different languages for each shader, but here you merge them together which is confusing
yeah thats cg + unity's changes. keep in mind cg's purpose was to provide a single shader language that could be compiled for several different graphics api's
and so thats where the odd stuff comes from
and things were heavily modified to make it well suited for unity
thats good though. it sounds like you will be fine. just make sure you always try to understand how other peoples shaders work and you will just learn more and more very quickly. and here: https://unity3d.com/get-unity/download/archive
spending time looking at the builtin shaders / their cginc's will help you a ton with understanding how to write shaders in unity
and how things actually work
what does cginc mean?
cg include
what is cg xd
like with c/c++ shaders can have include files
I should probably know what cg stands for :>
The Cg Toolkit is a legacy NVIDIA toolkit no longer under active development or support. Cg 3.1 is our last release and while we continue to make it available to developers, we do not recommend using it in new development projects because future hardware features may not be s...
this would explain better than i
and unity took this, and made unitycg
ok, well thanks for the help thus far!
Now I'm just confused
there's no real code
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)
Shader "Sprites/Default"
{
Properties
{
[PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
_Color ("Tint", Color) = (1,1,1,1)
[MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
[HideInInspector] _RendererColor ("RendererColor", Color) = (1,1,1,1)
[HideInInspector] _Flip ("Flip", Vector) = (1,1,1,1)
[PerRendererData] _AlphaTex ("External Alpha", 2D) = "white" {}
[PerRendererData] _EnableExternalAlpha ("Enable External Alpha", Float) = 0
}
SubShader
{
Tags
{
"Queue"="Transparent"
"IgnoreProjector"="True"
"RenderType"="Transparent"
"PreviewType"="Plane"
"CanUseSpriteAtlas"="True"
}
Cull Off
Lighting Off
ZWrite Off
Blend One OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex SpriteVert
#pragma fragment SpriteFrag
#pragma target 2.0
#pragma multi_compile_instancing
#pragma multi_compile_local _ PIXELSNAP_ON
#pragma multi_compile _ ETC1_EXTERNAL_ALPHA
#include "UnitySprites.cginc"
ENDCG
}
}
}
Isn't it supposed to have more than that?
like i said, the vert and surface methods are defined in a cginclude
dont edit the cginc, you will need to place it in the sprite shader, rename it, change the shader path, then declare a new surface function
how much have you worked with c++?
you need to understand how header files work
I stopped programming for a while then came back to C# then unity then stuck with it
as well as how the vertex/fragment pragma statements work
yeah I know how header files work
but what I'm asking is if I am supposed to be combing the two files into one
since I'm using the cginc or whatnot
and follow into the sprites cginc and find the functions that are being used for surface. no thats not what you are doing
you will still include that sprites include file
you just need to make it not use that default surface function
and copy/paste it into the shader
and modify it to do what you want
and make sure you rename it and set it as the surface shader in that pragma statement
@grand jolt when I try to use vert and frag w/ surf the compiler doesn't like it, what should I do?
@silver bronze how did you get the ` tags to have formatting??
void main()
{
test();
}
woah
nice
ok...
how do UI shaders work?
well not how do they work but
how do you get a shader to be compatible with UI elements?
In a current project I am combining 5 different Rendertexture cameras (think of them as tiles) and 1 Main camera to render these tiles to the display.
I was wondering what the performance penalty is with Rendertexure and if perhaps using Graphics.Blit and reducing the number of Rendertextures would improve performance?
I'm using shader graph and I'm trying to get a glow on the outer edge of a model's silhouette going inside the model, is this possible? I've tried fresnel but it's really not what I'm looking for and some oddly shaped models look strange, especially at certain angles
I want it to have a really thick inner glow around the silhouette of the model
Essentially I'm trying to get a uniform glow along the inside silhouette of this object
and right now it looks sorta awful at most angles
fresnel is usually easy because normals are usually smooth
since yours are not its trickier
you could have a second set of "normals" stored in a spare uv channel? then interpolating those values you could do the fresnel in the fragment shader... might get you most of the way there
@oblique cosmos
or maybe just smooth your normals, then in your shader force them to not interpolate between vertices
your vertex stream would have smooth normals i mean, then the output to fragment shader would have two copies, one interpolated one not
how could you force normals to not interpolate?
Just write "nointerpolate" before the field
For the vertex output struct
@grand jolt
omg thats cool
thank you
also means i missed out on an easy freelance job a while ago lmao. searched everywhere but couldnt seem to find a way to keep it from interpolating and ended up not taking the job
i needed it for my voxel engine awhile back, i agree very useful
used it for determining weights for texture blending of the mesh, so everything opaque can be just one mesh but still look drastically different
@grand jolt are there any discords with just shader programming? Thinking of making one since this and others have a lot of shader graph discussion
if you do please make it more general graphics programming stuff. i find it odd that this discord has "shaders" but then c# that applies to graphics stuff doesnt quite fit here and nobody in general-code will be able to help. But i personally for graphics programming stuff love to use The Cherno Project's discord. it snot unity related but super fantastic community and really smart graphics programmers there. you can look him up on youtube
Alright cool, will do. I think I'll make it "invite only," you know?
Maybe a form to fill out or something for non invite joins
Just feels like convos go down hill when it's super open
DM me if anyone wants in, looking for mid level / senior
Hey, does anyone know what does last two (z, w) of 4 coordinates of ShaderGraph UV node stand for? The documentation is a little bit sparse on details:
https://docs.unity3d.com/Packages/com.unity.shadergraph@6.9/manual/UV-Node.html
Also, how to make your SubGraph take UV input parameter but default to it's own UV when one isn't supplied as a parameter. Basically, same as Rectangle node does:
I have made multiple different shaders, and all of them have one issue, they render opacity as darkness instead when placed on textures (If I place them on a sprite, transparency works fine, but when I place it on a raw image that has a texture, it does the weird darkness in place of transparency). Is there any way to fix this?
@dark flare thank you! I go back to that project in a few hours, so I'll try it then. Is this something I can change in shader graph or should I write a code block or just transfer my shader to code?
I have a shader that Takes in an alpha map and a key-out color and it works fine on sprites, but when used on textures (by using a raw image on a canvas) it is too transparent for some reason even though it should be at full alpha in the middle:
https://hatebin.com/uvyyswqkua (attached is an image of the shader in use on a sprite on the left and a raw image on the right)
(Ignore the brown bg on the right, the only part of it that is the raw image is the very low opacity part which is barely noticeable in the middle)
can I make surface shaders in URP?
in LWRP/URP I have this shader code
which produces this plane
but when I convert the vert function to this
I get this weird effect
I added a cube to show that I'm rotating in the scene, does anybody know what I'm doing wrong?
hmm this works nicely, I think my issue is my lack of understanding of the GetVertexPositionInputs function and positionCS
clip space
Hi all. I'm making a shader for trail, but i need it to take 2 textures, 1 for the trail and 1 for the "cap" of the trail. How would this look in ShaderGraph?
if the back of each face not rendering is what you are talking about, this is due to backface culling. you can turn that off by using Cull Off, the second one is just making sure you preserve the initial y position, which is good. although, you should be applying the wave before transforming each vertex position into clip space which is what that GetVertexPositionInputs does
@oblique cosmos you could try transferring it to code and adding it in
(Near the cursor)
I'm getting artifact line at the end of this fade shader, anyone know what this is? Camera distance affects it
edit: Huh? it doesn't show in the screenshot..? Also doesn't show when i maximize the game window..
edit2: Gotta "open original" to see the artifact...
@Sroka uv is baked into your mesh, it's up to you how you fill it (e.g. export uv just as float2, or float3, or float4). All data that its present is pushed into the shader. If you send float2 uvs in, zw is 0.
Basically uv is no different to vertex color, data-wise - just different semantics.
ey boys i have a question
in my custom shader i do the following for my custom light model:
inline fixed4 LightingBurleyLight (SurfaceOutputBurley s, half3 viewDir, half attenuation, half3 lightDir, fixed4 ref)```
is there a list somewhere that i can check to see what other arguments i can put there? i would love to be able to access the indirect light somehow :p
the viewDir, attenuation, etc, i found just by skimming other people's shaders
i also read that this way of using a lighting model is actually obsolete, but i need access to all these variables for my lighting model to work
i dont think i can rewrite it without direct access to the viewDir, attenuation, etc
i just cant figure it out for the life of me. if anyone knows the answer, could you ping me? thanks in advance guys!
the only info i have right now is that possibly the GI data is stored in TEXCOORD1, but that's based on a page on custom shaders for mobile with enlighten
@narrow niche this page gives examples of GI in custom surface lighting https://docs.unity3d.com/Manual/SL-SurfaceShaderLighting.html
I understand that page, however, i cannot use UnityGI gi as an argument because i am using attenuation already. At least, it didn't work in my testing
I also cant use a custom GI pass as it errored as well. Ill retrieve the error code in a bit, when i get back to my pc
@narrow niche you can download the unity shader source and look up the lighting functions that are built in and see for yourself
google "unity download archive" - its all there
Can you apply multiple different sharers on separate texture maps on an object with one mesh?
If you combined the shaders into one Uber shader then.. kind of? Otherwise no
In Shader graph, how do I expose the PBR node property like "Surface" or "Blend" in the material so I can access them through code?
hey there.
how would one go about doing this with shader graph?
@dark flare the default shaders do not work the same way my shader does. i use viewDir, attenuation, lightDir, etc, while the main shader uses the ShaderGI gi variable. the gi variable contains lighting information, but only color and incoming direction, and the color is premultiplied with the attenuation, so it's not very useful in my situation
correction: it uses UnityLight light, but that still works the same way :p
god sometimes i feel stupid. turns out, i can just simply add UnityIndirect indirect to my list of variables. the reason it didnt work was because i had split my code up in 3 methods, and i added it to the wrong one while testing
what's the difference between CG and HLSL and which should I use in LWRP?
hlsl (High Level Shading Language) is the shader language developed by ms for Direct3D. Different graphics api's have different shading languages which can make it hard to develop shaders for multiplatform. Nvidia cg can work with multiple graphics api's making life a little easier. however, its old tech and is no longer supported. unity made UnityCG.
so it's recommended to use CGPROGRAM/ENDG instead of HLSL/ENDHLSL in my shaders for compatability?
compatibility with multiple platforms
i have another issue with my shader :(
i tried to make another version that is transparent (https://paste.myst.rs/v55)
but whenever i add a fallback, it just immediately falls back to that, and without a fallback, it of course doesn't render at all.
i dont get any errors though, so i have no idea where it's going wrong. any ideas?
@devout quarry
Unity translates code between platforms. Do whatever you're doing Unity's way, since you're using Unity's engine.
So if you see them using CGPROGRAM, use that. If you see spots where they use HLSLINCLUDE, use that, but understand why.
;)
Like @grand jolt said, it's "UnityCG".
It's basically HLSL. And if you target an OpenGL or whatever, they translate it and then compile. Or cross-compile.
I have 8 values in a shader and want to average them excluding any values that are 0. there a way to do that other than a bunch of ifs? maybe a built in hlsl func?
like is there a version of the 'any' func that returns how many elements are non-zero vs just whether non-zero elements exist
@sharp garden maybe something like this:
float total = 0;
float count = 0;
for(int v=0; v<8; v++)
{
float val = myValues[v]; //assuming your values are in an array
count += step( 0.000001, val); //returns 1 or 0
total += val;
}
float result = total / max(count,0.000001); //prevent divide by zero
π
I actually ended up doing something similar though utilizing any instead of step
Are Unity's vertex colors clamped 0-1?
Just wondering if anyone knows how to get masks to work with shaders as well? I'll use a sprite mask to mask off the child objects, however, one of those child objects has a shader attached to it and the mask doesn't properly mask the shader
So the masked area is the blue part, however, the question marks are part of the shader and that isn't being masked
Hi guys, anyone know why this shader's causing flickering when the mesh gets longer?
https://gfycat.com/timelyunrealisticcapybara
Most likely running into precision issues since you're performing a lot of operations on the UV value it seems
Try to avoid using divisions in shaders. Instead of doing "value/2", use "value*0.5"
The stretch is mostly happening in the X = 0 UV, and where the Vertex Color.alpha is also around 0.
So i thought it's some kind of division by zero, so i added those Clamps and Max here n there. But it didn't help..
Hmm ok will try that
You can use the Saturate node by the way, it has the same effect as clamping between 0-1. At a lower level, the saturate operation is essentially free! π€
How about if i can't avoid Divide? I have a VC.a / UV.x
My math is extremely spotty, but I think you can do 1-VC.a * UV.x, using the OneMinus node on the VC output (or the UV output, whichever works xD)
Hmm, i was thinking it would be inverse.
So 10 / 2 is the same as 10 * 1/2 (inverse of A is 1/A)
Is inverse the same as OneMinus? (My math is also spotty...)
Yes, it does invert thinks like vertex colors or masks. In which case you'll have to adjust everything along the node chain
Hmm, the 1-VC.a * UV.x doesn't work, it just goes blank..
I used to like spaghetti, and now I mysteriously have this aversion to it...wrecks my dinner. ;)
So you're applying a gradient on a mesh you've resized? Or are you not resizing it at all, and just need the gradient to start at some arbitrary point?
@meager pelican Me?
Yeah. Sorry. You. π
I'm trying to recreate this
https://youtu.be/fpViZkhpPHk?list=PLjrUd49cphqvbanLRXjQNYsRd-8u2ySco&t=81
watch in FULL HD! my Instagram: https://www.instagram.com/matthiasm.de Video Shop: https://matthiasm.de/shop tools: 3ds max / Krakatoa / fumefx / after effec...
I'm approaching it like:
Particle with infinite lifetime goes to places, but not rendered.
Then there's a trail that follows, and this trail have this shader. The length of the trail will ultimately (for this particular purpose) won't really stretch/shrink. But the actual length of rendered graphics within this trail will stretch/shrink by a alpha clipping
All of this already works for this shader. It's just this flickering issue. But this only happens if the trail itself is "slowly expanding", which is not related to recreating this effect so i guess i can live with it...
Unless i wanna re-use this shader for another particular use where the trail would also be expanding/shrink. But perhaps for that (future) purpose, i'll have to make another shader
Oh, I haven't tried trail renderers or particles in HDRP SG shaders, so I should probably bow out.
Other than messing with VFX Graphs, of course.
It looks like he's passing various band/range intensities into the shader and it's a distance from center type of thing. But... IDK. The intensity calc should be pretty simple with a distance from point and clamped to 0..1. Probably scaled. But that demo you showed could be doing 100 things, algorithmicly.
2 cents. Good luck. π
I realized his way of "shrinking/expanding" the graphics within the mesh shape is much simpler than my approach (yes probably just distance from center, sometimes it's seen the "line" that applies to multiple of his "trails")
But yeah, it seems expanding the mesh kinda messes with the UV precision, and it's used multiple times and with division, so for this purpose i just need to avoid stretching the mesh (it's not supposed to to begin with.. idk what i was thinking)
Thanks anyways guys
Well if you just want to apply a gradient to the mesh, don't stretch it, just pass in an offset, and clamp the colors to 0..1. Any negative colors are 0 after clamping. You can change the offset to 'move' the gradient. You can try multiple offsets on the "high" side and "low" side. Think about it. π Or do the same but for the UV's (calc them)
The most feature complete way of doing all this would probably be using VFX graph, though it may be more complicated a process if you're not familiar with it.
https://blogs.unity3d.com/2019/03/06/visual-effect-graph-samples/ might give you an idea of how to begin
Flickering though, it's so hard to figure out what's causing it without seeing more of your graph?
Or your inputs to the shader from the CPU side
Wait what's VFX graph? Is it different than ShaderGraph?
I tried searching for VFX graph for LWRP, but is it already there? Or still only for HDRP?
It should work fine, I think you may have to change a setting in the project, but it's definitely supported
Alright that's something new. I'll get to it now.
But as for this gradient thing, the shadergraph part is what's dealing with the alpha, the bottom area is just blending it with the texture (it's just a gradient for the sides)
The VCol.a is the result of the trail's gradient (as shown in SS) and the startColor of the particle multiplied (that's just how "inherit particle color" works in the trail module, i wish i can change it to "additive" instead). That's why i need the VCol.a / UV.x, = the startColor's.alpha, with the assumption of 0-1 alpha gradient at UV.x 0-1.
And it's like this
https://gfycat.com/untimelyillegalgreathornedowl
The startCol.a will be driven by the audio spectrum later
@meager pelican
I need to do it by controlling the startCol only, because:
- It's for a single Material of particle system.. the offset will be different per trail
- I can't use custom data for trails. The trail also can't be aware of the leading particle's customData vertex stream
Well, like I said I haven't messed with custom trail renderer materials. I was just speaking about a gradient on a mesh, and not resizing the mesh. Your demo ^ looks like you're just multiplying the start color. So if that works, it works.
Going to bow out. Wishing you luck though.
How to get vectors that are facing bottom? I am trying to make ice hanging dow from objects.
not directly bottom but something like this
You can do a dot product between the world normals and a vector3(0, -1 , 0). On a sphere this will create a smooth mask of the bottom part.
i did but i dont know how to combine that
Combine how? You mean having the vertices displace only down?
yea
You can multiply the world normal in your vertex displacement section with vector3(0, -1 ,0) to limit it only to the downfacing normals. In which case you won't need a dot product
Hi all π, did someone manage to create a custom inspector for a Shader Graph shader? It becomes a bit messy with a lot of properties...
so my shader issue from a day or so ago has been fixed, but i do not understand the solution
this works:
inline fixed4 LightingBurley (SurfaceOutputBurley s, half3 lightDir, half3 viewDir, half atten)
this doesn't work:
inline fixed4 LightingBurley (SurfaceOutputBurley s, half3 lightDir, half3 viewDir, half atten, UnityIndirect indirect)```
for some reason, trying to access indirect lighting like this is accepted by the engine, but wont actually run
i dont know why but i guess ill be going without baked lighting for now
at least i have transparency working
dunno if this helps, but my method signatures look like this
half4 ToonLightingCalc(half3 diffColor, half3 specColor, half oneMinusReflectivity, half smoothness, half3 normal, half3 viewDir, UnityLight light, UnityIndirect gi
with also inline void Funk_GI(SurfaceOutputStandard s, UnityGIInput data, inout UnityGI gi
maybe you have to define a custom gi as well?
i hate all the unity magic, ive started just writing "unlit" shaders and implementing the standard macros manually
@narrow niche
defining custom gi wasnt working for me, it wouldnt compile
issue with your method signature is the lack of attenuation, which i needed for my particular code
unity's shader system is probably one of the worst ive seen, but i havent used much so far other than love2d, shadertoy and unity lmao
and opengl directly
i dont understand why we need all these magic functions. is it for crossplatform support? we have to jump through so many hoops to get even the most basic things to work sometimes
and my issue wouldnt be such a big deal if only unity gave me some sort of error or warning
there was nothing in the console
you DONT need all these magic functions
you CAN just define it all manually, which is what i've started doing
as for the magic function, attenuation is in there just a little hidden away
@narrow niche i highly recommend downloading the built in unity shader source
you can just look at what its doing, how its getting everythin
after using them for so long i dont really mind all the magic shader stuff tbh, but its extremely slow to compile complex "standard" shaders..
writing whats essentially the same thing, the shaders compile 100x faster for some reason
in-editor, i mean
Hey folks, I'm having an issue where terrain isn't showing because of the shader, I believe it's not being included in the build as this only occurs when making builds. I've made sure the shader is in the resources folder and attached to a material, it's also included in the project settings in "always included shaders". Any ideas on how to fix it?
@narrow niche if a shader won't compile, select the shader in project tree, look in inspector, it always shows errors and warnings
Also standard/legacy is messy, the core render pipeline library is very good + LWRP has good shader organization. Imo better to work from than dealing with the older cginc's
The Unity Indirect struct might have # ifdefs skipping via defines and keywords or unitygi cginc isn't included
Hey everyone. I know I'm asking a lot but I have absolutely no experience making shaders and I want to get into writing some compute shaders to make edits to meshes on the GPU during runtime. Would anyone recommend any resources to get started with shaders and then move into the more complicated stuff that I want to do?
Getting this error trying to open a HDRP/Lit shader in Shader Graph (2018.3.11f1)
NullReferenceException: Object reference not set to an instance of an object UnityEditor.Experimental.UIElements.GraphView.IconBadge.AttachTo (UnityEngine.Experimental.UIElements.VisualElement target, UnityEngine.SpriteAlignment align) (at C:/buildslave/unity/build/Modules/GraphViewEditor/IconBadge.cs:143) UnityEditor.ShaderGraph.Drawing.MaterialNodeView.Initialize (UnityEditor.ShaderGraph.AbstractMaterialNode inNode, UnityEditor.ShaderGraph.Drawing.PreviewManager previewManager, UnityEditor.Experimental.UIElements.GraphView.IEdgeConnectorListener connectorListener) (at Library/PackageCache/com.unity.shadergraph@4.10.0-preview/Editor/Drawing/Views/MaterialNodeView.cs:155) UnityEditor.ShaderGraph.Drawing.GraphEditorView.AddNode (UnityEditor.Graphing.INode node) (at Library/PackageCache/com.unity.shadergraph@4.10.0-preview/Editor/Drawing/Views/GraphEditorView.cs:322) UnityEditor.ShaderGraph.Drawing.GraphEditorView..ctor (UnityEditor.EditorWindow editorWindow, UnityEditor.ShaderGraph.AbstractMaterialGraph graph) (at Library/PackageCache/com.unity.shadergraph@4.10.0-preview/Editor/Drawing/Views/GraphEditorView.cs:150) ...
UnityEditor.ShaderGraph.Drawing.MaterialGraphEditWindow.Initialize (System.String assetGuid) (at Library/PackageCache/com.unity.shadergraph@4.10.0-preview/Editor/Drawing/MaterialGraphEditWindow.cs:530) UnityEditor.ShaderGraph.ShaderGraphImporterEditor.ShowGraphEditWindow (System.String path) (at Library/PackageCache/com.unity.shadergraph@4.10.0-preview/Editor/Importers/ShaderGraphImporterEditor.cs:50) UnityEditor.ShaderGraph.ShaderGraphImporterEditor.OnInspectorGUI () (at Library/PackageCache/com.unity.shadergraph@4.10.0-preview/Editor/Importers/ShaderGraphImporterEditor.cs:20) UnityEditor.InspectorWindow.DoOnInspectorGUI (System.Boolean rebuildOptimizedGUIBlock, UnityEditor.Editor editor, System.Boolean wasVisible, UnityEngine.Rect& contentRect) (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:1625) UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
Hey guys, I'm very new so I apologize for this question if it's dumb. I have a shader that is still visible through a mask.
I setup a parent object that has a mask on it. The blue is the part that is being masked. The child object has a scrolling texture shader that I added, but it's still visible outside of the mask
here's what i have
Is there something I have to do in shader graph to get it to accept the mask?
Hello π
I was wondering if it is possible to make a "Custom Editor" for the Sharder Graph ?
Like i want a boolean to change de "Exposition" of some Properties of my ShaderGraph.
Same
Hi there, I'm currently discovering shaders, vertex/fragment shaders in particular.
I managed to do what I wanted (an infinite grid with nested levels), and even with anti-aliasing using ddx and ddy
However everything is still rather confusing and "alien" to me.
So the question I wanted to ask is:
How to properly set the values of the "Offset" option? The shader I used as a basis to make mine had a value of "-20, -20", which clips things wrongly when I zoom out.
Everything seems to look fine when I set it to "0, 0", but I wonder what are the supposed benefits and uses of those values?
@true zinc u might be able to do something like Offset [_myVal], [_otherVal ] but not sure (usually that works for blend modes etc)
@uncut karma I know Offset exists, and what I'm asking is what is its purpose exactly, and is it ok to remove it?
my probles is that it's set to -20 -20
Yes you likely don't need it
I'm trying to understand in which situations I could need it
It is for offsetting ztest if I remember right
Msdn directx docs or cg docs might have more details
It's a very special-case tweak
I've made a shader that lets me apply a "paint design" mask to my model and give it a different color. As I'm now adding more models I am thinking about how to speed up my workflow.
The model is currently unwrapped pretty standard like this, where the design mask is applied to the uv islands, and color is overlaying a grayscale AO texture, unwrapped the same way.
Now.. I'm experimenting with this gradient approach where the unwrapping is super easy and fast.
And I'm thinking that I can separate the different materials of the vehicle into different shades of grayscale which the main color is applied to. This way I don't need a AO map to shade the model.
The issue I'm looking for help on is the design mask. If my UV unwrapping looks like this:
How can I get the design onto the areas I want?
So before I dive deeper into this approach, I would some feedback..
Can I use some sort of triplanar projection in the shader perhaps? One from side, one from top.. which would ignore the uv layout.
I've noticed UV1 and UV2 being referenced some times, is it possible to have a model with two UV maps ?
yes, a model can have up to 8 uv maps. another possibility you can consider is baking AO to vertex colors
How about projecting the designtexture(s) in the shader. You think I can do that on top of a messy uv map?
I've read that triplanar shading is pretty expensive(?)..
mmm I don't think distinct designs on things as curved and angular as a car would really work, triplanar only really works with tiling textures
cause it's quite hard to make things align and blend in 3 dimensions
yeah, but it would most likely just be a simple masked graphic which wouldn't necessarily need to cross over the dimensions..
Like "Apply side texture"
"Apply top texture"
oh just projecting from one angle is much simpler, you might just want to look into decals for that?
yeah, but I want to do some other things in the shader like dirt etc.
I do see a problem with things on the side axis probably getting mirrored on the other side..
I haven't used it myself but I know the function "tex2Dproj" lets you project a texture from a given point and direction so perhaps you could use that. and keep in mind you don't have to worry about performance as much if you do the expensive stuff in the customization part then bake it into a texture afterwards
it's easy to bake from a single shader, I don't know if there's a way to bake decals from outside the shader
Been thinking about that possibillity as well - baking sprites into a texture. You don't happen to have any articles or tutorials on that?
And would using two uv maps, count as two materials? Eg, getting more expensive batch calls?
This doesn't cover the decal projection but it shows how to bake a shader to a texture https://www.ronja-tutorials.com/2018/10/13/baking_shaders.html
and nope, multiple uv maps isn't expensive, it's just another set of numbers stored for each vertex
Fantastic, thanks! I'll definitely be using shadergraph though, but this should help me along nevertheless.
how do i get variables from the vertex function to the surface function? whenever i do this:
void vert (inout appdata_full v, out Input o)
{
UNITY_INITIALIZE_OUTPUT(Input, o);
float d = tex2Dlod(_DispMap, float4(v.texcoord.xy, 0,0)).r * _DispIntensity;
v.vertex.xyz += v.normal * d;
o.binormal = cross( normalize(v.normal), normalize(v.tangent.xyz) ) * v.tangent.w;
}```
but it just errors. it's defined like this:
```hlsl
#pragma surface surf Burley fullforwardshadows vertex:vert tessellate:tessFixed```
my full shader can be found here: https://paste.myst.rs/cnj
error: ```
Shader error in 'LuckyShaders/MainDiffuse2': 'vert': no matching 1 parameter function at line 295 (on d3d11)```
i have no idea why it's erroring, and the docs arent too helpful either :(
@narrow niche
how do i get variables from the vertex function to the surface function?
the output struct is o not v. you have v.vertex, is that what you want?
no
the issue is that adding o actually causes an error
@vivid valley holy shit that actually worked!
thanks!
That's because your output structure didn't have vertext in it. o is of type Input struct. So you must have added vertex to it somewhere. To start with you had
{
float2 uv_MainTex;
};```
But you could add vertex to it.
ok
np
@meager pelican i dont think you understand. my Input structure shouldnt contain vertex. i assign the vertex to v, it says v.vertex in the code.
It does contain vertext. But your question was how to get info from the vert function to the frag/surface function. That's in the output structure, o.
Which is called Input maybe rename it to output
its called input because its the input for the surface function. thats how unity names it by default
See how you set o.binormal?
i call those VaryData since its the varyings ( called in glsl ) that are interpolated from the 3 verts
input and output dont make sense really
i wish unity worked with opengl or at least had a better shader system tbh
varying is so much nicer to use and glsl is also much nicer to use imo
its almost the same just a few changes
unity used to work with glsl .. i dont know if it still does
my 1st shader was glsl way back in unity 3.5 days
The output is for interpolated things and it's why you assign semantics to them. There's some qualifiers to not interpolate, but normally you do.
I'm not a fan of OpenGL but that's me. I can deal.
ok 2 posts now vanished
@narrow niche
3rd try ... you can comment out the line UNITY_INITIALIZE_OUTPUT since you are setting both varaibles
i wonder if zeroing out the struct with that macro affects performance at all
^^
Might be hardware dependent, but I'd assume so. Minor, but yeah. The alternative is often errors or crashes though if someone doesn't set all the values.
Hey here, I struggle to access to an global var with shader graph, is it normal?
ho I found it, is you want to access to a global var in a shader with shadergraph you have to be sure that the property is not exposed
One thing I don't understand, is how my Min nodal works in this case, what's happen under the hood?
my result:
it removed my message
i was sayign there is a really good graphics programming discord (i posted link)
it covers all aspects of graphics and has a bunch of experienced people
ohh, DM me it
i guess if you post a discord server invite it just deletes it
can you DM me it too please? thanks π
Can anyone here talk about the cost of SpriteRenderers?
I'm creating a mobile VR title where every draw call counts and I'm currently using spriterenderers for the UI
My UI elements are for the most part not atlased
What's correct protocol for managing this? Is this a bad idea?
In order to get any form of batching (including instancing) you need the same material on the objects. That often translates to using an atlas.
@uncut karma would also like to get an invite π thanks!
same
@meager pelican thanks again for your insight on compute shaders operating in lockstep from a few days ago. It was a pivotal piece of the puzzle I was working on.
@uncut karma yeah hit me up with that discord server too, please!
@maiden gull if you need per-instance variation on a material (such as alpha fading), it's tricky because using things like Material.SetColor will split off a runtime instance, thereby creating an extra draw call
I uh, got around this by going directly into my mesh and setting the RGBA vertex colors (and had to make a shader that would take vertex colors)
As to whether this is a good, performant idea I have no clue. It reduced the draw calls, but I have not benchmarked it on mobile.
@unreal verge Glad to help.
@unreal verge There's two ways to address materials on an object. .material and .sharedMaterial. If you set the shared material, it's global for all instances...eg they're all blue. But as you say if you use .material, it clones the material and gives you a different instance.
The solution is to use .sharedMaterial (and don't even ever reference .material)...but set materialPropertyBlocks for the custom instance stuff. There's some shader macros and magic needed to make it all work.
So you can have your cake and eat it too, but it takes some doing. Not too bad though.
https://docs.unity3d.com/Manual/GPUInstancing.html
Hello, I tried to apply shader graph for my project, but it requires LWPR or HDPR. I don't know why shader graph doesn't work with default pipeline rendering? The reason I ask this question because when I applied the LWPR to Graphic setting, the existing terrains lost texture and showed pink color.
@past grove Shadergraph won't work in default pipeline rendering, I think they are only targeting LWRP and HDRP. However, Shaderlab shaders shouuld still work in LWRP.
Clear your console, re-import the shader and post the shader errors here.
It's likely not shader errors, you just have to upgrade the project materials https://docs.unity3d.com/Packages/com.unity.render-pipelines.lightweight@6.9/manual/upgrading-your-shaders.html
@past grove
Hello all, trying to edit an image with a shader (making the background transparent) and having difficulty getting the output as a texture to save as a png. I'm able to do it in a normal script with GetPixels, texture.EncodeToPng and System.IO to write to file. Any help would be appreciated.
The shader works well just not sure how to get the texture output to png. I get a black image. I did enable read/write on import.
Got it. Now I just have to figure out what I changed...
Hello Everyone, I got a Problem with Shader graph. Everytime when a property in the blackboard is connected to a Node, and im trying to rename a property the Shader graph blackboard GUI and the Rest of the GUI hangs and crashes... But when no property is connected I can rename them with no crash... Can someone help me please? Im using unity 2019.2.1 and Shader graph 6.9.1
@viscid vine this is fixed in layer version of shader graph
I'm on 7.0.0 and no longer have this issue
later version*
@devout quarry how do I Upgrade?
in the package manager window
Max Version is 6.9.1
somewhere in the package manager you can toggle to see all versions I believe
I am on 2019.3 though so maybe 7.0 is just not for 2019.2
You are the First who ja trying to help me
Is
Thank you I will download 2019.3a now
Are there other benefits of using the latest alpha version of Unity? Do you have some tipps and tricks for me what latest features are valueable?
I wouldn't use the alpha version in production
But to build shaders with no crash for example π
I really hate it to always quit and reopen that window everytime I introduce a property
yeah same, it's super annoying
in the package manager in 2019.2 have you tried Advanced>Show Preview Packages
yes
But latest version is 6.9.1
Do you know how to use tesselation in unity shader graph?
no tessellation afaik
here is a changelog if you're itnerested
what about this?
theres a tesselation subgraph template in there
maybe not implemented yet?
Can you help me to find that out?
I'm really interested in tesselation for shader graph
I'm quite busy but if you really want to know for sure, maybe someone from staff can answer it
I could start writing shaders without shader.graph but the syntax of shaders is really assembler like^^
or look up 'tessellation shader graph' and see what you can find
ok, thx for your help
good luck
trying 3.0a out now
Hello! Is there a way to convert screen position to world position in shader graph?
transform node does not have any matrixes for world I think
only model, view, projection, and viewprojection
and the inverses
or is there a way to use these to get the world one? I don't really understand matrixes
trying to make a custom decal shader but using the camera position isnt accurate at all
You'll have to use the depth buffer to reconstruct the world position. Never done that in SG before, so not sure if its at all possible
I am using the depth buffer yes
I just can't get the position where the imaginary ray would be intersecting the canvas in world space
why does GUI/Text Shader from textmesh pro have render queue set to 3000?
Geometry is 2000 right?
managed to fix this by creating a custom shader for it
IDK, maybe ask in the forums. Generally, if it's 3000 it's transparent, so 2000 gets all drawn first so there's a BG there to blend with. So transparency blending, maybe. Also 3000 usually doesn't update the depth buffer. But I'm totally guessing here since I haven't really checked out the TMP shaders.
I'm a bit new to HLSL. Playing around with a pixellation shader example. I'm seeing that on the edges of objects it often tries to blend the colors. (Note the right and bottom edge of the white floor) I'd like to prevent this blending. AA is off in settings.
Here's the relevant snippet, the frag function.
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
half dx = _PixelWidth / _ScreenWidth;
half dy = _PixelHeight / _ScreenHeight;
half2 coord = half2(dx*round(i.uv.x / dx), dy * round(i.uv.y / dy));
col = tex2D(_MainTex, coord);
return col;
}
I've tried adjusting the founding bit on the coord= line, but can't seem to get anything useful done.
Doesn't make sense to me how it should be able to get that value between blue and white on the edges, if the screen is ray casting out to one point in world-space. Id like it to be a more crisp edge like the top and left edges.
@fresh finch The preview window doesn't feature any sort of bloom. If you're using post processing in game, you should see the expected result
I assume this is what you're after?
Yes I want that on my cube
The bloom post processing effect is what blurs out the emissive regions, so it's required for that sort of effect
Okay I'll try adding bloom thanks
@eternal adder
- that first line looks unnecessary, since you sample in the next-to-last line.
- try setting the sampler state to point. IDK if that will solve it or not, but worth a shot.
https://docs.unity3d.com/Manual/SL-SamplerStates.html
Hello there,
Im quite new in shaders, I would like to create a simple color swap palette with the Shader Graph. But I don't understand what Im missing/not understand to achieve this.
There is the shader graph
I try to follow this technique :
https://gamedevelopment.tutsplus.com/tutorials/how-to-use-a-shader-to-dynamically-swap-a-sprites-colors--cms-25129
this part is wrong
I dont understand why I get this color, my R channel is the index (U) of the swap texture and V is only here to choose from one color variation to another
I've found an extremely unpleasant issue with Post Processing V2
Basically, if I use a custom Post Processing Effect, it skips the entire builtin stack
No, not skips, but rather my post processing effect is fed with a different buffer instead of the one that the builtin stack produces
So, here's the result without my custom effect (vignette turned to the max for demonstration reasons)
And here it is when my custom effect is enabled
Best of all: it works fine when not in play mode
Alright, seems like I fixed it. Basically my shader used alpha blending (because I didn't want to use main texture sampling), but it seems it's required now to properly do post processing. This is a bit baffling.
Hello. Anyone has an idea how to get the texture coordinates of a sprite in an sprite atlas? My shader is applied to the whole atlas it seems
SpriteRenderer automatically builds a batched mesh that already has proper UV values for sprite rendering pre-generated on the CPU so the shader has less work to do. So, no, you can't really do that without some hacky custom stuff. @wet canopy
You surely can get that data from the sprite object somewhere in your C# code, but applying that data to your sprite meshes might be quite hard. There's no API to modify the generated meshes that SpriteRenderer produces, which is quite a shame.
It's only VPos, UV0, indicies and VColor. Nothing more.
hmm.. and somehow making a copy of the sprite would contradict the use of the sprite atlas right?
at runtime that is
so the shader is always applied to the whole sprite atlas? sorry I'm quite the shader noob
You plan on duplicating the texture? Well, you can generate a new texture from the sprite, but that totally breaks batching and caches, so that will more likely lead to worse performance.
So, yeah, the SpriteRenderer builds a single mesh that contains all the sprites that share a material and a texture. It all renders in one go so it's fast.
Sprite is not a texture. Sprite is just a region of the texture. Making a new sprite by itself will do nothing.
oh okay. so as long as my sprite has a different material I can apply a shader to sprite but it won't change the texture of another sprite in the sprite atlas?
my idea was, that I would only apply a shader based on the position in the sprite atlas (but yeah, maybe that's too hacky)
I think you misunderstand something, lemme explain it in detail
You have a texture. That texture can be an atlas, since atlas is just a group of pre-baked textures.
You have sprites. A sprite is nothing more than a location of coordinates on the texture.
Sprites that are rendered in the game are nothing more than 3D meshes built from the points that the sprite has (that point to the regions of the texture).
Shader is something that visually draws your meshes onto the screen. They are represented by materials where you can tweak several options. However, when using SpriteRenderer, the texture is always pre-defined for you and the color is baked into the VertexColor of the meshes.
If a bunch of sprites point to the same texture AND they have the same material - they will batch together, leading to better performance.
@wet canopy
You can apply some limited external per-sprite info into the materials and give individual materials to different sprites, but that breaks batching, which may lead to worse performance. Key word "may"
how to get vector down in world space?
@slate patrol Thanks! That helps a lot π
Hi π Has anyone got an example of an unlit shader that uses a mesh object (vector data) as a point light?
@shadow yoke World down is (0, -1, 0), that you can transform to object space if you want.
@midnight bone Like ... use the mesh object position as point light source ?
@amber saffron Yes! in world space
Then the only way for you is to "send" the data to the material/shader through c#
Material.SetVector
Note that you don't care if it's a mesh or anything else, you just need the light information
Thank you @amber saffron - Will try that!
I created a 2D hologram-shader with the new 2D Shadergraph. Is there any way to use the renderer's texture in the shader? Or do I have to create a new material for each sprite I want to use that shader on?
Create a texture property with the name reference _MainTex and you should be able to access the sprite set in the renderer
@eternal adder I got an email that you posted a "thanks, it worked" post, but now it doesn't show up.
Did you run into another problem?
that second actually isn't a bug in the way that you think π you're not supposed to be able to connect nodes to both fragment stage slots and vertex stage slots at the same time :p
Was going to ping you @stone sandal π
yeah, and that second one is a known bug, the compatibility check isn't working 100%
that's what I meant, the bug is that they had it connected at all, not that it suddenly won't connect c:
the other two though, I'd love formal cases for so we can track them, I haven't seen that yet
I reported bugs for all of those, super easy to reproduce
1177671
1177682
1177701
also I understand that ShaderGraph does "scope per subgraph" however I think that is a very bad design decision
Scope should be for the actual path the value takes, not "fencing off" with subgraphs
it's more like we do scope per node, and on the graph when checking compatibility, subgraphs are nodes
as far as the graph knows
Yeah, I don't think it's a good idea
not better, but it's an explanation :p
We had huge issues with that in a bigger project that basically forced us to "unroll" all subgraphs again, pita
yeah i understand it's frustrating but it's not something that's going to be able to change in the near future
it's a core code issue
I understand, that's why I said I think it's a bad design decision π
@lapis prawn can sing a song of this
Here's how to get into that situation. If you are not aware that this prevents you from being able to disconnect that position node OR do any changes to your position calculation ever again it can create huge trouble down the road
Imagine doing that subgraph conversion on a shader with 300 nodes, continue working on it and then only days later finding out that you can't change the position value anymore
can you go in to the sub graph and continue to add nodes to the network that then reflect in the main graph?
yep
ah, so it only stops you from changing the position value if you try to continue on with the same output from the subgraph slot in the main graph
Exactly - it happily stays connected otherwise and "just works". I for myself would prefer to have a giant toggle for "disable scope checks" and just get compiler errors if I mess up scope