#archived-shaders
1 messages · Page 28 of 1
@grizzled boltcould you please give me a search direction? my render texture is flipped and showing not the area I need. I need to somehow match the camera and raw image, so that I would get an effect on area, not some other area... I'm stuck at this point.
Hi, can someone help me with custom node in shader graph please ?
I'm struggling on it for more than an hour when it seems to be just a missunderstanding of the naming convention
The image is my node setting
The file is :
void IsVertexInsideCollider_float4_float4_bool(float4 v, float4 colbounds, out bool Out)
{
bool test = v.x >= colbounds.x && v.x <= colbounds.y && v.y >= colbounds.z && v.y <= colbounds.w && v.z >= colbounds.z && v.z <= colbounds.w;
Out = test;
}
And the error is : undelcared identifier isVertexInsideCollider_float4_float4_bool_float
Whatever how i change the name it ALWAYS add an _float at the end in the error
That implies a UV problem but I don't know
Is there a way to say : If greater than 1, then 0, without a predicate AND preserve the original value if less than 1? e.g. I want to lerp something's alpha based on a normalized distance.
0 is transparent, 1 is fully opaque, greater than 1 is transparent.
I can use a predicate but I wanted to make sure there wasn't a way I was unaware of before I did
Modulo
How so? It won't keep it at 0, it'll reset the 0-1 range ad infinitum, won't it?
then maybe I can use not render texture but something else, with the same effect?
it's just, it seems so simple, but almost no information. If it were you, what would you do in this situation>?
Yeah, I set it up using world position, but it was not looking correct. Not sure how to altering it to do so, but will try some more things. Mainly it went from the nice sun-wave effect to just a gritt look
Just use the ternary operator. Predicates happen all the time. If you have to, you have to.
result.a = (color.a > 1.0) ? 0 : color.a;
Trying to understand shaders a bit better. What I'm trying to do here is grab all the vertices of an object that align with the Direction variable and offset them in that direction. What ends up happening though is them being offset in a strange direction...
In the picture the Direction Vector3 is (0, 0.5, 0), but it doesn't offset straight up. Anyone able to see what I'm doing wrong here?
Bit of a vague long shot but I'm trying to figure out how to allocate and utilize large amounts of volume data in compute shaders (meaning, reading and structuring voxel data for use on the GPU) for raycasting, and I'm wondering if anyone knows any resources to help me get past the initial bump. I'm having trouble figuring out how to structure large bitmasks (512 bits) and how to send them to the GPU via buffers properly and I am really having a hard time finding any information on this.
When you allocate a compute buffer you provide count and stride parameters:
https://docs.unity3d.com/ScriptReference/ComputeBuffer-ctor.html
in your case count would be the number of bitmasks you want to store/pass in and stride would be 64 since you want 512 bits (8 * 64 = 512, stride is expressed in number of bytes)
Thanks this is exactly why I am asking because I don't have enough contextual knowledge to find the right things. This looks good.
Basically what I am trying to do, or my understanding of what I need to do, is that I need to create a voxel struct on the shader with the information I need it to contain, then upload that from the CPU via a structured buffer. Then I need to send my bitmasks and whatever indices and information I need to be able to set up either a sparse octree or a brickmap as a method to find the indices and as a method to skip empty space while raycasting in the compute shader. Does this make any sense?
Is there anyone know how to achieve this kind of refraction effect?
Can you read last frame occlusion culling overdraw from a shader?
Not that I know of. OC is an optional CPU-side thing in the engine. The shaders, by definition, don't even get called for OC culled renderers.
Overdraw is a different matter for those renderers that aren't culled. The editor has a set of shaders for visualizing overdraw, so shaders can be used to collect that data and I suppose you could pass the result to the next frame. I haven't checked them out, but they appear to accumulate color (like a heat map) per pixel into a render texture. So every time a pixel is updated it adds to the heat map.
Would it be better in terms of performance to do my own culling solution that is GPU-side?
Not usually. The fastest polygons are the ones you DON'T draw. 😉
So not submitting what you don't need to the GPU is the way to go. Your shaders should only "see" what they're supposed to draw, not what they aren't supposed to draw.
That said, there are use-cases for GPU geometry and culling of either whole meshes or individual polygons. This comes up in things like ray-tracing and procedural geometry generated on the GPU.
okay thanks.
It all depends on your use case. But shipping the entire scene's geometry up to the GPU isn't for the faint of heart.
how does the shader graph work
it works good
Does somebody know, how to achieve this vertices-stuttering effect like at the end of this game? https://www.youtube.com/watch?v=MEbJ71Ld_zY
Iketsuki - Atmosphärischer Plattformer
Deutsch/German Review - Iketsuki - Horrorgame Gameplay Playthrough + Ending
Iketsuki Download: https://modus-interactive.itch.io/iketsuki
——————————————————————————
▶Hier könnt ihr mich unterstützen!: ▶https://www.patreon.com/corrupty
——————————————————————————
▶Mehr Horror Einteiler:
https://www.youtube.c...
Oh it's in the whole video but you can REALLY see it at the end
Vertices are snapped to increments
You can search for "ps1 vertex shader" for explanations and surely premade assets as well
Is there any way I can use one material for a mesh with multiple colors. Except for the color all parts of the mesh have the same properties.
Are there any resources on DOTS_INSTANCING_ON?
Unity manual is really poor in info and examples
https://docs.unity3d.com/2022.2/Documentation/Manual/dots-instancing-shaders.html
There are ways. May depend on what pipeline you're using.
Firstly, I assume you mean multiple instances of the same mesh, each instance having its own color attribute but otherwise all are the same material. If you mean vertex color on one mesh, that's a different answer than this.
You can look into GPU instancing. This uses Unity's Material Property Blocks (MPB's). You set each instance's color property on the renderer. More info here: https://docs.unity3d.com/ScriptReference/MaterialPropertyBlock.html and Google is your friend. I think it will also work in URP, if you use the proper property name, but generally instancing MBP's isn't up to snuff in URP...but color works IIRC. IDK about HDRP.
Thanks! That sounds convenient.
Well, you should read this though: https://docs.unity3d.com/Manual/GPUInstancing.html
if you're using SRP/URP.
Pay attention to the SRP batcher thing.
There are other ways. But if you're using URP, you might just want to maintain batcher compatibility and use a different material for each instance. But that's the opposite of your question.
Okay thanks, I will take a deeper look into it. Different material for each instance isnt an issue to me though. My main concern is, that I can have one instance which uses only one material even though it has different colors.
Oh.
I don't understand that statement.
If you only have one instance, set the color on that instance as you need it set.
If you have multiple instances of a mesh, and each has its own material, you can set each material's color directly. In that case don't use Renderer.sharedMaterial, set a new instance of the material on each renderer. This is done behind the scenes by Unity automatically, if you assign to Renderer.Material. It clones the material and make a unique copy of it for that renderer. @peak dagger
I see, but is there also a way that I still have the same material for each color of a renderer while also still having different colors. To be concise, I need that, so that I can change one property of a material and affect a whole mesh.
For instance, I would like to have the same material in the 6 slots on the right while maintaining the colors of the weapon.
MaterialPropertyBlock
is one way
I'll look into it. Thanks!
thanks
How do I make a shader for a plasma cannon/gun
You would start with references and concepts to determine what the shader needs to do, and whether you need a shader at all
Many effects can be created with particles or animations alone, depending on artstyle
how can i access the scene's depth texture in HLSL? (urp shader code)
Guys guys I was doing an impostor using a octahedran, to be more exacly I have used indices of the uvs to get vertices of the mesh. In this way I can order texture in an atlas and finally I save the image
I have used uvs like indices of vértices and I have removed repeated indices yo use it like a posición of the camera
Now my problem is how to create a shader that use a piece of the texture atlas? Someone have a idea
;this is my atlas texture
This is my billboard
I don't know what to do anymore I need to find out how to get the small images inside atmas
Is anyone able to help me with my ring shader? I have it setup like this, and in the main preview it looks good, but in-game it looks like the 2nd pic and i'm not sure why, i think something is going wrong with the alpha but im not sure what
It kinda feels like you should just be putting a solid color into base color, not the ring
^
When I give it a maintex it looks good in preview but off again in the editor
im not sure why theres such a difference between the two
rather than using ddxy, use step
@mighty moon
(and then you don't need a divide either)
OK.
A material is just a shader reference and a bunch of property values.
So for your 6 elements, you can have 6 instances of material "foo", each with its own primary color assigned. You'd probably assign that to 6 meshes that all compose the gun parts. They would be "owned" by a parent object of "gun".
You can also assign multiple materials to a single mesh, and they overlay each other often with transparency for whatever parts that element doesn't apply to. But that's 6 draw calls of the entire mesh (redundant).
Another way would be to have a color array assigned to the shader, and have the shader use vertex colors to identify what parts of the mesh get what element.
GPU Instancing would be more about having 50 of those guns on a display rack, each slightly different.
Hello everyone, wishing you all a happy new year 2023!
I am trying to render clouds on mobile devices and as far as I could do some research, I've been able to generate volumetric clouds nicely.
but they are "Expensive"
Would like to have your opinions or some resources someone can point at. But it has to be Mobile 😄
Thank you !
Volumetrics are expensive no matter what, but if you provide the technique you are using we may be able to recommend a faster approach
Instead of 3d volume, you can use 2d texture
Thank you! the current technique that I am using is raymarching and using volumetric cloud textures. What I am looking out is this https://thatgamecompany.com
they have a game called sky
Applying the ray marching effect to 2d texture
can you please elaborate it a bit? that would be really helpful. Because the clouds have to be 3d in nature
Use real volumetric cloud is very expensive on mobile, so just fake one.
ohh you mean use it as a flat bg? But see how thatGameCompany did it in the game "Sky" they are actually flying through clouds
In order to fly through it, you can use particle to make a fake cloud and use custom light maps to make it looks real, or make the ray marching step lower and don't apply the anisotropy effect to the cloud.
Clouds in Sky don't look very transparent, except when intersecting the land, so I suspect they are made of meshes with a distance fade effect.
However, this does not solve the problem that the cloud looks fake.
depth fade is the fundamental part of cloud
The cheapest to do this is use a custom light map to make the cloud looks real.
am I the only one who can't open that link? It does not load at all
Make the thing can be done in real-time on a pc be done in your hand.
What are your exact requirements, what kind of interactions will the player have with clouds
And how do you want them to look like? Stylized, realistic, etc, a reference would be nice
@amber saffron @onyx talon , I will try the 3d mesh for sure. It seems making a basic 3d mesh with a fractal transparency would work. Then blur it in a separate pass. Would have to give it a try... Pheww! Blender to help 😛
Thank you once again, Ideally, the player doesn't have to go through the clouds much. But the expectation is good fractal clouds and decent amount of movement with some lighting and dramatic colors. Let me share an example:
https://www.youtube.com/watch?v=4QOcCGI6xOU
Clouds are lovely and fluffy and rather difficult to make.
In this video I attempt to create clouds from code in the Unity game engine.
Project source (Unity, HLSL, C#) is now out of early access:
https://github.com/SebLague/Clouds
If you'd like to support the creation of more videos like this, please consider becoming a patron:
https://www.pat...
PS: I've done this already and is optimized as well. Just that It does not simply work as expected on mobile devices because of high rendering costs 😛
Yeah I know, I made my own raymarcher too for 3d volumes but it runs like crap on mobile, if you want to have something similar to that, easiest way would be with soft particles, they would have depth fade and they also fade near the camera
cloud is very similar to the smoke, you can check out this article.https://viktorpramberg.com/smoke-lighting
yes, I do understand. Somehow, if you play with the steps and ray length, you get decent results but you know mobiles right, once you're on the low end ones, thats where it looks crappiest of all 😄
thanks a bunch! yes, I did create volumetric textures in houdini and used the same. I am outta license now as its going to be a paid gig so will have to fallback on creating them in blender(that's another research, :D)
The whole point of this article is the six way lightmaps
BTW, this is outta curiosity, do you guys often run into situations when you've to issue custom draw calls (Graphics.drawmesh..)
oops! that is what I missed 😦
But thank you so much for exactly pointing that out. 6 way light maps... need to read up on that
I do use DrawMeshInstanced sometimes
why?
so I was thinking on the lines of optimisation. Using a mix of static batching and then gpu instancing right now. But would issuing custom draw calls really makes sense. For a fact, I know(while rendering in VR, performing a multi-threaded frustum and tree based culling on cpu does makes a lot of difference), which means you only render the meshes you require. It doubled up the FPS from 35 to 75+ and even 90 at times. Which is a huge deal. But that was done using a small trick of enabling and disabling mesh-renderers
so is there a custom render queuing and issuing of draw calls in those Big AAA games?
(not talking of those which have custom game engines)
I'm not sure about big AAA games, but you could for sure do some custom culling inside burst compiled jobs and the SRP if you want to make it cleaner than just disabling mesh renderers. But, most times I just do exactly that when I need a custom culling haha 😛 just disable the renderers, although I do not have millions of meshes, just a few with high vertex counts
I'm sure games like excape from tarkov probably has some custom culling system, unity's default culling does not cut it with scenes like that
hahah! yeah you know it so well! Enabling/disabling mesh renderers is just a quick and dirty way of doing it. Hence, I was being very curious about the rendering pipeline. I am writing a custom Rendering pipeline and its just so simple out there, you render as you like it 😄
Is there any reason why the cut off isnt faded?
surface type is opaque, pls change it to transparent
No difference, I thought it was that too!
🙂
The texture is seamless, but you can clearly see the repetetivness, how can I fix it?
change the texture?
as its not seamless...
There are techniques where you can add other textures on top of it, or use layered materials. I am curious to know how to make a texture look seamless which actually isnt seamless...
It is seamless...
But the further you go, the clearer is the repetative effect, which is common.
yes, that will occur because its being repeated multiple times. To hide those, I usually overlay another texture on top of it...
Does anyone of the shaderexperts here have an Idea how to iterate over additional lights when using URP forwardPlus?
The simplest option is to edit the texture to break up the repetitive patterns, but that can be difficult with PBR materials that rely on multiple texture files
Procedural stochastic texturing exists as a solution for it otherwise
https://blog.unity.com/technology/procedural-stochastic-texturing-in-unity
From what I've seen from the link, this what I need.
What about texture rotation?
is there a way to do rotatre the texture by 90 degree without programming?
By splitting the surface into tiles and rotating those in Unity or a modeling program
Otherwise you need a shader
the easiest way would be to overlay another texture on with a different tiling so the two don't line up
Guys is there a way to send a vertex data and anything more across buffer, for example I have a button made in c# where every time that I press it I would like to create a vertex buffer of a octahedran and send it to my custom shader, is it possible?
vertex buffer is part of mesh data
maybe you want to just create a mesh?
No no, I have to created a impostor atlas using a octahedran, and a camera, so I have create a shader billboard, but I need that impostor change every image of atlas, when I see it of differents angle
But to do that I need vertices of octohedran in my shader to send a ray of my camera and calculate the position of this ray match with a face of octohedron
And use the vertex closest to use its image
if the mesh never changes you could just hard code the data into the shader
Hi! I am wondering, my math is failling me right now I cant figure this out
I made a simple billboard shader
which works great in shadergraph
but only if the object's global rotation is equal to the identity (aka 0 0 0 euler)
if the object is rotated by any parent then the effect breaks
just a simple cross product with the camera direction
then multiplied with the object space position
can I tackle this entirely in shader or I have to make an script to compliment it?
the script solution is trivial lol
public class SetGlobalRotation : MonoBehaviour
{
public Quaternion targetRotation = Quaternion.identity;
void Update()
{
transform.rotation = targetRotation;
}
}
but I wanna try to be as performant as possible with these lights
Hello, is there a way to override "render face" setting in a material that uses the shader? I REALLY don't want to make a duplicate of the entire thing just because I need a two-sided version.
hey i have an error installing shadergraph
it gives me an error
Library\PackageCache\com.unity.shadergraph@12.1.8\Editor\Generation\Targets\BuiltIn\Editor\ShaderGUI\MaterialAssemblyReference\RawRenderQueue.cs(12,24): error CS1061: 'Material' does not contain a definition for 'rawRenderQueue' and no accessible extension method 'rawRenderQueue' accepting a first argument of type 'Material' could be found (are you missing a using directive or an assembly reference?)
what version of unity are you on?
i am using version 2021.2.7f1 originally it didnt work then and still doesn't work whenm i upgrade to 2021.3.15f1
or 2021.3.16f1
I believe the latest version of shader graph is 12.1.9
try upgreading that too
Also you ideally should be on 2021.3 latest
it said it was avaliable on 2021.3.16f1 but doiesnt appear in opackage manager i am on 12.1.8
i am using the most up to date 2021 version as well
after looking into it there is a file missing in the Library\PackageCache\com.unity.shadergraph@12.1.8\Editor\Generation\Targets\BuiltIn\Editor\ShaderGUI\MaterialAssemblyReference\ directroy
@shadow locust do you another solution
If i wanted to make an effect where for example:
A bullet hits a mesh with a collider, a completely transparent shader ripples from the impact origin? what would i need to research for this type of effect?
https://www.youtube.com/watch?v=hTJqo1HeEOs&ab_channel=GabrielAguiarProd.
found here: https://forum.unity.com/threads/hit-the-shield-shockwave-like-part-effect.1187086/
Unity Shader Graph - Shield Effect & Impact Detection Tutorial
In this Shader Graph tutorial we are going to see the steps I took to create an awesome Shield effect that detects hit collisions. The impact detection is done with a script that controls a property of a Sphere Mask in the shader.
***NEW SHIELD TUTORIAL: https://youtu.be/IZAzckJaSO...
trying to modify a bog standard unlit shader to multiply a texture with black for a shadow effect on a tilemap. was wondering if i could store the lerp value in texcoords0, so when I set UVs for the tilemap I could pass it a vector3 with the blend value in uv.z? or do I need to store it in texcoords1 and read from there
What are my options for defeating the 65535 thread group limit in compute shaders?
Somewhere I read that using DispatchIndirect would let me do something but I haven't tried it yet.
Anyone knows why Toon Shader (UTS3) failed to compile on fresh project (2021.3.16f1 URP)? works on editor but shows black on build.
Says because the variable additional lights world to shadow isn’t defined
so im super new to shaders, like UNBELIEVABLY new, i just followed a tutorial on how to make a basic unlit albedo with modifiable color shader, and i dont understand what this error means
Shader "Lighting/Dither"
{
Properties
{
_Albedo("Albedo", 2D) = "white" {}
_Color("Color",Color) = (1,1,1,1)
}
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex Func1
#pragma fragment Func2
#include "UnityCG.cginc"
struct appdata {
float4 vert : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f {
float4 vert : SV_POSITION;
float2 uv : TEXCOORD0;
};
fixed4 _Color;
sampler2D _Albedo;
v2f Func1(appdata IN)
{
v2f OUT;
OUT.position = UnityObjectToClipPos(IN.vert);
OUT.uv = IN.uv;
return OUT;
}
fixed4 Func2(v2f IN) : SV_Target
{
fixed4 = pixColor = tex2D(_Albedo, IN.uv);
return pixColor*_Color;
}
ENDCG
}
}
}
@smoky vale Check your v2f struct. Instead of vert it should be position.
Or on line 29, change out.position to put.vert
I am unsure, but are you new to peogramming as well? It’s not a shader error but a variable declaration in a struct 🥶
i suppose you could say im new to programming, i guess im just new to the language? is that dumb to say?
No no, don’t take it otherwise. Just a small advice, try to understand how this shader thingy works haha
Didn’t mean to offend you man! You’re doing good 👍
i mean ive only worked in c#, lua, a little python, once tried html, so yeah im sorta new to programming
oh no you didnt offend me
Cools 👍
oh wait right cuz v2f is out and v2f only has vert and uv as variables
ok hold on
Yes you’re passing on data from vertex to fragment. Your input structure has vert and uv. V2f has vert and uv. But you’re assigning position variable which is not present in the v2f struct
ok god it working, thanks
👍👍👍
yeah that was just a dumb mistake
Good luck and keep learning 👍
hey, im wondering how to get a continuos texture, so its not stretched like it is down below:
is there an option for that
?
guys, how do I implement the queue control system in the material? Unity seems to have replaced it with a slider now in advanced options. But I'd like to put the queue manually
for anyone who's looking for the answer: materialEditor.RenderQueueField();
What was your solution ?
tiling
on the material i used
i have to do it manually for each object which sucks
Yep, thought you found an automatic solution
You can create a script that change texture's tiling depending of the dimension of your gameobject tho
oh, do you have an example script or something?
Did you import URP in your project ?
yeah
yeah
Sure ? Then maybe the shader is outdated and points to a no more existing file
Yes, this file doesn't exist
can i send error code here?
I don't think it will help, the file is not found, that's all
Ah, my bad, I was looking at the wrong folder, the file is still there, so it "should" work
Again, are you 100% sure URP is imported ?
i just grab folder and put inside that all
If I'm writing data to a compute buffer, is there a performance benefit to storing them as vector types or does it not matter?
e.g. 1 float4 vs 4 float
Did you import the universal render pipeline by using the Unity's package manager ?
The shader you want to use is based on some of the URP shader libraries
I'm not an expert, but I don't think it matters in that case.
I import whole file
This doesn't answer my question
Ok um I only import in asset later I open unity screen shot to u I tag cuz I am in restaurant eating
But I try changing shader it doesn't show up
I follow YouTube tutorial but ...
First step : import the Universal Render Pipeline using unity's package manager : window -> package manager
Ohh
I see
I saw YouTube he just grab whole file put inside unity and then the shader show up
Wait did u download URPTOON SHADER?
No
what is a cause for a standard shader to not work in built in render pipeline?
I have a project in built in/standard rp, and the standard shader is pink
No compilation errors in the console ?
Interestingly, there is some lighting on the sphere, it's not full "error pink".
Maybe the ambiant (sky) is broken and needs rebake ?
in play mode everything is pink
its only in some areas and its weird, i made a empty scene and its pink, but the uma scene works fine
but all new materials i create using standard shows pink
i tried removing/reinstalling post processing didnt seem to effect
and no baking i dont know how to do that on a day/night cycle 😛 just using a directional light
Just try to set up a sky in the lighting/environment settings
if add skybox to cam it shows in game view but editor mode still pink
Not on the camera, in the lighting settings
?
Window -> Rendering -> Lighting, iirc
oh
After changing skybox there may need to hit the Bake button to tell unity to change the ambient lighting
trying to find sky setting, i only see Enviro Reflections Source - Skybox
I think assigning a skybox material is the first thing under the Environment tab?
maybe cause unity lost internet ? i cant connect the project package manager says error refreshing packages, was thinking maybe re-import enviro since handles sky and stuff
ok found it, so now in scene view shows skybox bg, but checker board is still pink
so i created a new material, standard, shows 'ok' as jut grey
if i add a texture, it is grey but also pink tinted
Like I said, you're missing universal render pipeline
i dont have urp
Did you hit the "bake lighting" button in the lighting window ?
its a standard 3d project not urp or hdrp
i hit bake lighting did something for a quick second but since empty scene not much to do
Maybe your skybox is using an invalid material
The shader is named "UnityURPToonLit...."
You need URP
the shader name is standard
I think that's a different person...
This person
It's listed as universal rp in the package manager.
Yeah, sorry, misclicked the answer button
can you show your environment settings
so in the Scene info in lighting, i clicked new lighting settings and it works
so i iguess somehow my demo lighting settings are broke
huh ?
Shader compilation errors don't clear out automatically, they can stay in the console even when fixed.
so what should i do test it out first?
Install URP in the project : https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@12.1/manual/InstallURPIntoAProject.html
Then apply the shader to a material, and the material to an object
yep that fixed it, all my pink materials now showing again, thanks for pointing to the lighting setting >.> had no clue but new settings over the demo settings seems to have fixed all the pink shaders i can see
Hey everyone, is there a way to stop the fresnel effect to fade based on the camera position?
So that it's equally distributed and fades every edge of the mesh
i have alittle bit trouble
It doesn't do that, exactly
What you're seeing here is the effect of perspective, as the surface extends past the camera, their relative angle changes
For the angle to be uniform the camera would have to be orthographic
doesnt it i just install in pakage manager?
it needs to bet set up afterwards
Get this awesome Toon Shader for Free!
Download it here (MIT License):
https://github.com/ColinLeung-NiloCat/UnityURPToonLitShaderExample
Unity Assets:
Unity-Chan Model - https://assetstore.unity.com/packages/3d/characters/unity-chan-model-18705
Free City Pack by CubexCube - https://assetstore.unity.com/packages/3d/environments/urban/cubexcub...
Follow urp setup steps from the docs
where the docs?
the video i just follow it with same
but why i getting error
?
They were linked to you
wait wdym mean linked?
Hey guys I'm trying to use unity's toon shader and it keeps randomly making some assets glow too much
anyone knows how to fix this?
Oh so I guess it would need manual vertex painting instead
Hey Guys.
As simple as it goes (hopefully): I'm wrapping a world grid functionality up. Which begs the question - would you happen to know of a shader (or of a way I could procedurally modify an existing shader - I'm writing a mod, the more I can do in pure code the better) that always remains unapologetically white despite lightning conditions (so also in the middle of the night), but itself doesn't emit white light on surrounding objects?
Any unlit shader with a color parameter will do this
there's probably a built in one
in fact what you're describing is basically the "Hello World" of shaders
I would assume so, and yet using:
material.mainTexture = texture;
As my entire shader instantiation.
Results in the screenshot (which definietely is "lit")
Ergo - what am I doing wrong?
that screenshot doesn't look "lit" to me
in fact what you're describing is basically the "Hello World" of shaders
I would expect so TBH. I never claimed to know the frist thing about shaders, and I would like to achieve this effect by not needing to learn much more than that 😉
it looks like parts of it is occluded by the grass
but not lit
It also looks like it's being affected somewhat by post processing
e.g. bloom
(The oclusions is a different problem that I would like to solve in it's own right. I tried using an additional camera which was ALMOST good enough, but it unfortunately also cut through the player character)
Bloom is dependent on the final brightness of the pixels, so it can't be controlled in shaders
I'm not sure if it's technically "lit" or not, but it for example reflects off dew on the camera as a light source would.
However, I assume you might be right about the postprocessing kicking in.
yep, that's postprocessing
AFAIK Valheim uses the "Scriptable Render Pipeline". That's probably where my extremely simplistic shader gets hijacked?
Bloom should always be used with HDR and the threshold set to 1 or higher, so you can still have full white pixels without them contributing to bloom, but not all developers do that, either for performance reasons or ignorance.
It's possible they are using the alpha channel to store how much each pixel contributes to bloom, like Beat Saber does. But most likely they have their bloom threshold set to lower than 1, which means it's impossible to have fully white pixels on screen without them glowing, unless you render it after post processing, but at that point the depth buffer is probably cleared so it would render on top of everything.
I'll check the alpha channel hypothesis.
How do I get it below the threshold? Do you mean Color(1, 1, 1)?
Yeah, you can return a light grey
Won't be white, but like I said, that's impossible if they've set their threshold to less than 1
So theoretically (0.99..., 0.99..., 0.99...) should be enough? But in practice they probably set the thresh to something like (0.5, 0.5, 0.5) anyway?
But there probably IS a thresh somewhere?
No, 0.99999 is likely not enough. I'd guess it's somewhere around 0.85 and 0.9.
I'll play around.
That's the problem of using bloom without HDR, you have to set the threshold pretty close to 1, so not everything starts glowing, but then the spectrum of how "bloomy" a pixel is becomes close to binary.
In the meantime, any idea how could I avoid the terrain occlusion problem? In practical terms I need a specific layer (the one containing the lines) to ALWAYS "win" over a different specific layer (the one containing terrain) while obeying the depth of all other layer interactions. As far as I can tell from scouring the internet it seems kind of an "all or nothing" situation. Where I can easily draw my grid on top of everything (including the player and 100m tall buildings) or just suck up the occlusion. Which seems... difficult to believe to be the case (what about tactical/spy games from example).
Other post processing effects can change the brightness before bloom is applied, so you can't rely on material color alone anyhow
If the post processing changes per area you might never get a value that works absolutely
And how would the post processing be applied? What classes/calls should I look for in the original source code to try and deduce what's happening?
I have no idea how Valheim does this stuff but you could look into SRP Core or URP documentation
could someone explain to me
why inverting that node twice
ends up with a different output than the first one?
void Unity_InvertColors_float4(float4 In, float4 InvertColors, out float4 Out)
{
Out = abs(InvertColors - In);
}
it does the abs() which is what makes it asymmetric
The code that Invert Colors uses here is basically abs(1 - x). While your subtract node looks black/white it contains negative values.
e.g. -1 → abs(1 - (-1))=2 → abs(1-2)=1
To prevent the negative input you'd use a Saturate node to clamp between 0 and 1.
oh okay thanks much
Any pointers at least Guys? 🙂
Layers can't help you here. The order of when things are drawn is what matters. So for example, if the grass is drawn first, then the lines drawn on top of everything (which so far is just the grass), then the player drawn normally, you'll get the effect you want.
If the game is drawing the player and then the grass, there's no correct place to draw the lines. If you draw the lines first, then both the player and grass occlude it. If you draw it last, then the lines are drawn on top of everything. If you draw it in between the player and the grass, then it will be on top of the player, but occluded by the grass.
So basically in engineering terms you propose I set the "ZTest" to "Always" and than try to fiddle with the "redner queue".
?
Yes
But not just the render queue of the lines. If the grass is drawn after the player, there's no way to render the lines correctly.
The dependency on the order can be somewhat avoided by using the stencil buffer, but that would require modifying the grass shader to have it write a particular stencil value.
So hypothetically if I already did this exercise before asking this question (😉) and even setting the "render queue" of my shader to one billion - doesn't result in it overlapping anything... Is it possible that the postprocessing is again somehow screwing me over, or am I doing something terribly wrong after all?
In other words - is it possible for post-processing/"render pipeline" (dunno, just throwing random gibberish around) to completely disregard my render queue value?
Do you mean you set ZTest to Always and the render queue to one billion, and that looks the same as the screenshot you posted earlier?
I would like to think so. However since I have no experience doing what I'm doing - there is the likely probability that I'm doing something slightly off that destroys the whole approach (dunno, wrong caps on "_ZTest", it should be an int, not a float, I should be modifying the shader directly, not the material, the ZTest parameter should be somehow "nested", blah, blah, blah):
var material = new Material(Shader.Find("Sprites/Default"));
material.SetFloat("_ZTest", (int)CompareFunction.Always);
material.renderQueue = int.MaxValue;
material.mainTexture = texture;
return material;
And yes - this does literally nothing. The screenshot would remain virtually unchanged.
Here's the Sprite/Default shader. Notice it doesn't have a ZTest property
https://github.com/TwoTailsGames/Unity-Built-in-Shaders/blob/master/DefaultResourcesExtra/Sprites-Default.shader
I guess it's not like my whole approach is completely doomed. Since this similar approach for example achieves the purpose of forcing the shader to become transparent:
material.SetColor("_Color", new Color(1, 1, 1, 0.1f));
material.SetInt("_SrcBlend", (int)BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)BlendMode.OneMinusSrcAlpha);
material.DisableKeyword("_ALPHATEST_ON");
material.EnableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)RenderQueue.Transparent;
I assumed that might be the case. And tried the same with the unlit/color and standard shaders.
The sprite shader is always transparent. It doesn't use any of those properties or keywords.
Although I didn't check the code of these either to be honest.
The only thing that matters is the render queue
That code is currently commented out - probably was experimenting with a different shader. I am positive it was necessary, and it did make a difference.
Are you by chance aware from the top of your head of any built in shader that DOES take in the ZTest parameter?
Great idea.
You're much more helpful than I dared to hope I have to say Man.
So the standard shader should work if I understand correctly?
(this is the first time I'm seeing the domain language that Unity uses for shaders)
Yes, and with the Standard shader you will need to use this code to change it to transparent, except with different property names (__mode, __src, etc...)
No sorry, that's the display name
It's the same property names
And set the _EmissionMap instead of the main texture to make it look unlit.
And _EmissionColor to white
It will still calculate lighting, so it's more expensive than an actual unlit shader
Will do. But first let's sort out the occlusion, cause that's the thing that's bugging me the most and I would like to avoid releasing at this state at all cost.
To double check, this is the minimalistic code that for now should result in my gird occluding EVERYTHING regardless of depth:
var material = new Material(Shader.Find("Standard"));
material.SetFloat("_ZTest", (int)CompareFunction.Always);
material.renderQueue = int.MaxValue;
correct?
I think so. If that doesn't work, I would try using a more reasonable renderQueue value, like 3500.
How are you using this material?
uno secundo
{
** var shader = InitializeShader(texture);**
for (var i = 0; i < GridLinesPerAxis * 2; i++)
{
var gridLineGO = new GameObject();
gridLineGO.transform.parent = transform.parent;
var gridLine = gridLineGO.AddComponent<LineRenderer>();
gridLine.textureMode = LineTextureMode.RepeatPerSegment;
** gridLine.material = shader;**
gridLines.Add(gridLine);
}
}
Where initialize shader is our old buddy:
private Material InitializeShader(Texture2D texture)
{
var material = new Material(Shader.Find("Standard"));
material.SetFloat("_ZTest", (int)CompareFunction.Always);
material.renderQueue = 3500;
return material;
}
Again - I would be very suspecting of this initialization (probably would be the main suspect) if not for the fact that it seems to correctly pass on the "transparency parameters".
So I understand that it's impossible for something outside of this shader to "override" the ZTest behaviour, and the problem MUST be somewhere between my ears?
I always find it helpful to test my modding code inside Unity so I can more easily debug issues.
Oh, actually, the Standard shader doesn't have a _ZTest property.
I was wondering why I wasn't finding it in my search
@regal stag Hey. I know you made a great toon shader, so i assume you know quite a bit about custom lighting. Do you know how to get/iterate additional lights in forward+ mode?
@glossy loom Do you actually need a texture, because it looks like it's just white. If not, you should be able to use this shader:
https://github.com/TwoTailsGames/Unity-Built-in-Shaders/blob/6a63f93bc1f20ce6cd47f981c7494e8328915621/DefaultResources/Internal-Colored.shader
There's a possibility this shader isn't included in builds though, but worth a shot.
So "ZTest" needs to be in the "Properties" section of a shader for it to be "parametarizable"?
Most importantly it needs ZTest [SomeProperty] in the SubShader or Pass
I don't think it has to be defined in the Properties section to work.
The only other built-in shaders that have a property assigned to ZTest are the UI shaders, which have it assigned to unity_GUIZTestMode, which is a global property assigned by the UI masking system.
I think technically you should be able to set that property from code and that should take priority over the global one.
But if the Hidden/Internal-Colored shader is available and you don't need texture support, that's a much simpler, cleaner shader.
I'll try that. Ignoring the built in shaders for a moment though.
What do you mean? Are you including your own shaders?
Is there a way to broswse custom made shaders (I'm willing to pay for the sake of my mod) for those that support the ZTest parameter?
There should have been a "..." at the end of the previous sentence 😉
I assumed you wanted to avoid custom shaders, because that will require building an asset bundle in Unity and loading it in your mod
I would rather not do that exactly for the reasons you mentioned.
But I'm starting to run out of rope 😉
So you have tried the Hidden/Internal-Colored shader? Or is it not an option because you need texture support?
(I was for example hoping to use a "dashed" texture on additional grid lines of increased precision)
How could I go about creating a shader that give a pixel art sprite soft edges? Like a falling off of alpha. Would that be too difficult?
I'm trying it out now regardeless.
First victory of the day.
It overrides EVERYTHING (as it should).
I'll try experimenting with the render queue value to try to force it in between the player and the terrain.
The texture issue remains though...
Great. However, I loaded up Valheim in RenderDoc and the render order of the player, grass and terrain will not play nice
It's pretty random. The grass is in sections and some of them render before the player, some after.
❤️
So you will need to override those render queues somehow
I don't mind the grass TBH as much as I mind the dirt patches on the ground itself.
Ok I'll ignore the grass, but the terrain is drawn after the player, which is still problematic.
Do I understand correctly that you only need it to be drawn on top of the terrain, but everything else in front of it can occlude it?
Yes. The reason for that is my mod adds arbitrary precision terraforming tools. While Valheim sprinkles the ground with random "dirt patches" to visually break the monotony even of perfectly "flat" ground (I think this is done via a shader, as they DON'T appear in the heightmap and they DON'T get hit by raycasting - as if they didnt' exist).
I want to "cut through" them with my lines as not to actively mislead the player that the ground could be leveled still. I literally don't care about covering up anything else with the lines.
Hope that makes sense.
Sort of, but if the lines are always drawn on top of the terrain, won't it always look like there's nothing to level?
Or at least harder to tell than if the terrain occluded over the lines
Also, you don't have to use a shader with changeable ZTest value. There are also built-in shaders that are hardcoded to ZTest Always which you might be able to use.
@glossy loom This one, for example:
https://github.com/TwoTailsGames/Unity-Built-in-Shaders/blob/6a63f93bc1f20ce6cd47f981c7494e8328915621/DefaultResources/Font.shader
That is correct.
Still I need to analyze if I'm able to somehow hack the render queue of the player to land above the render queue of the terrain and hope that doesn't break anything 😉
There are other things that are also drawn before the terrain which will have the same problem
So what you need to do is change the render queue of the terrain to be super low (negative even), then your line material should be a bit above that, so it's drawn second, then everything else can be drawn.
Sounds extremely invasive. Isn't there any chance of that severly screwing up the visuals? Say improper shadows on the ground or something 😉
The order of opaque objects will not affect visuals. Maybe performance a bit, it's generally better to draw things front-to-back
But Valheim uses deferred rendering, which doesn't suffer as much from opaque overdraw.
And it's already badly optimized anyway, so no one will notice 🤫
^^
While using "RenderDoc" were you perhaps able to establish the precise render queue values of the specific layers?
Render Queue is a Unity concept which does not transfer to RenderDoc, which deals with DX11/Vulkan commands.
I only see the order that it ultimately resolves to
Makes sense.
Another surprising development that doesn't make sense though! 😛
This combination:
var material = new Material(Shader.Find("Hidden/Internal-Colored"));
material.SetFloat("_ZTest", (int)CompareFunction.Always);
material.renderQueue = 1;
...results in my grid line being overdrawn on top of all other objects anyway.
It literally seems the "render queue" parameter doesn't matter.
I assume this transparency code is not still active?
Current compiled state:
private Material InitializeTransparentShader(Texture2D texture)
{
var material = new Material(Shader.Find("Hidden/Internal-Colored"));
material.SetFloat("_ZTest", (int)CompareFunction.Always);
material.renderQueue = 1;
//material.color = new Color(0.6f, 0.6f, 0.6f, 0.6f);
//material.SetColor("_Color", new Color(1, 1, 1, 0.1f));
//material.SetInt("_SrcBlend", (int)BlendMode.SrcAlpha);
//material.SetInt("_DstBlend", (int)BlendMode.OneMinusSrcAlpha);
//material.DisableKeyword("_ALPHATEST_ON");
//material.EnableKeyword("_ALPHABLEND_ON");
//material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
//material.renderQueue = (int)RenderQueue.Transparent;
material.mainTexture = texture;
return material;
}
That is unexpected. Just as a sanity check, try setting _ZWrite to 0, because it's defaulting to on, which isn't needed.
Will do, although I understand it shouldn't really matter for the purpose of our little experiment?
It shouldn't, but this will eliminate one possibility, which is that render queue is working, but for some reason the shader is writing a depth value that is closer to the camera than all subsequent draws, so nothing is able to draw on top of it.
The other explanation is that it's always being drawn after everything else, regardless of the render queue, which I can't really explain.
If this line should add sanity: material.SetInt("_ZWrite", 0); then it didn't 😉
I'll try with one of the UI shaders that have hardcoded ZTest = Always. But that's not even grasping at straws anymore I'm afraid.
Whenever I'm in a scenario like this when modding a game, that's when I open up Unity and test my code there.
Sounds reasonable. I however managed to somehow write ~5k of C# code for this mod without knowing the basics of the Unity Editor. If I were now to go there to investigate I would need to start from "what's the left mouse button" 😉
I keep getting black parts of the material whenever I set the object as static
Anyone knows why?
Using URP and unity's toon shader
Does it happen immediately after setting it to static or only when you go into play mode?
only when I go into play mode
sorry forgot to mention it
Then the toon shader probably doesn't support static batching. What's the reason you want to set it to static? Is it for batching, or for lightmapping, or something else?
I read I should set every object to static so it batches. Also I'm using navmesh agents so I need meshes to be static for baking the navmesh
Well, your options are:
- fix the shader so it supports batching, which requires some shader knowledge
- find another toon shader that doesn't have this problem
- don't use static batching for the objects using this shader. You can still keep navigation static on, if you press the arrow instead of the checkbox:
"Batching Static" is the only one you should have to keep disabled to avoid this issue
Thank you very much! wouldn't it impact performance too much if I disable the "Batching Static" option? considering I have many objects in the map
If all those objects are using the same material, then static batching can help reduce draw calls
Maybe before you go any further, could you just quickly check if disabling "Batching Static" actually fixes the problem?
Yes it does fix it I already checked 😄
GPU instancing is a different type of batching, which only works when you have multiple instances of the same mesh and material.
Static batching works with different meshes by combining them into one.
Could you link which shader you're using? Is it a free one?
yes it's unity's toon shader
one sec
What do you mean by combining them into one? Like many meshes using the same material?
Yeah, it combines all of them into one mesh when you go into playmode, which is why you only see it happen in playmode
hmm I thought about buying a shader from the asset store but how can I be sure that it won't be an issue there
Which specific shader in the package are you using?
0.8.2 preview
actually I was using 0.8.1
I'll update it now
Okay so the issue still occurs on 0.8.2
Is there only one shader that you get with this package? I'm seeing some files like "Body" and "Head"
I actually don't know I just imported it and change the materials to use the toon shader
Are you using Universal Render Pipeline?
yes
So is this the shader you're using?
even though according to the documentation I'm supposed to see the toon shader under urp
wth why don't I have that
That's just a screenshot from the documentation, probably old
What's the name you see?
oh okay
I just see toon but not inside urp
I don't have a toon inside the urp shaders
So many properties in this shader 😵
Haha I tried many shaders before finally landing on one that sort of works
@low lichen for whatever it's worth (perhaps unsuprisingly) the UI shaders also seem to ignore render queue.
I found this bit in the Unity documentation however:
Note: When Unity runs in batch mode, it does not load Scriptable Render Pipelines (SRPs) until the first time something renders. Loading an SRP modifies the sub-shader selected for a given material which can lead to the value this function returns being different than expected.
Since Valheim uses SRPs - wouldn't this mean that from my perspective whatever I put into the render queue property might be disregarded?
Are you sure it uses an SRP? The Standard shader only works in the built-in render pipeline
Can you share some more screenshots of the glitched parts? I'm trying to find some pattern to understand what it is in the shader that might be breaking.
It looks like everything is untextured. Are these meshes UV mapped at all?
yea one sec, I actually don't know what uv mapped means but I downloaded these from the asset store
I can tell most of the black spots are in the darker part of the objects
And can you post a screenshot of what it looks like without batching, so I know what it should look like?
Interesting, so that's actually the highlighted spot, that's facing the light
I'm not sure because look at this
you can see the buildings I snipped are in the back to the left
but the shadow appears downwards to the right
Hmm, could you try seeing what it looks like if you swap out the Toon shader with the default Lit shader? Just to confirm this is an issue only with the Toon shader.
The plot thickens
the blacks you see on the top of the towers are still the same toon material
Oh, okay
but the walls are regular urp lit shaders
here it is with both ofem being urp lit
Then this is an issue in the toon shader. It's not listed in their "Known Issues" page, but it's possible they don't intend static batching to work.
There might be some import setting on the model that will affect this somehow, but it's just a shot in the dark
should I first try to import some other meshes and see if the issue continues before I buy a toon shader off the unity store?
Yeah, that's a good idea.
You could also try changing some of these settings.
The settings that stick out to me as potentially having an effect on this are "Optimize Mesh", "Weld Vertices" and "Normals" (try Generate instead of Import)
Do i copy what you checked or do I just play around with the settings?
I just took the screenshot from the documentation
And "Index Format", maybe change that to 32 bits
Also remember to have other meshes with the same material it can batch with, otherwise static batching won't do anything to it.
Yes one sec
I'm not and the fact that the standard shader clearly works probably proves that I am wrong and you are right.
On the same topic a Random Guy on the Internet says here: https://forum.unity.com/threads/material-renderqueue-or-tag-doesnt-seem-to-be-working.406870/
That:
Are you using the deferred rendering path? Anything deferred gets rendered first regardless of the queue, then forward rendered objects (anything using a transparent shader or something other than the standard lighting model) get rendered afterward with respect for the queue order.
You mentioned previously that Valheim uses deferred rendering? If the above statement is true, then to explain the behavior I'm experiencing -> it would need to defer basically everything.
Oh, yeah good find. I have basically no experience with deferred rendering.
Yup works great 💀
so the mesh was the problem? god damnit
It might be a combination of both, since it doesn't happen with Lit, but yeah.
So... you will have to use a deferred shader (assuming the render queue is respected within the deferred rendering, which I don't know for certain)
Thank you very much man!! I'll keep checking different meshes and see if it persists
So now I need a shader that is BOTH deffered AND respects the ZTest parameter and preferably is built in.
And it still might probably not work 😉
There's definitely no built-in shader like that.
There is one alternative, but complicates things a bit
Good. It was way to easy up until now 😉
You can add a CommandBuffer to the main camera to draw the line renderers at a specific "camera event", in this case "CameraEvent.BeforeGBuffer".
But no, that would draw it before the terrain, which is no good
And a Stencil wouldn't work because I don't have access to the code of Valheim's own shaders which would then need to be modified as well r?
Yeah. Stencil is something that can be exposed through properties like ZTest, but this list doesn't show any exposed stencil properties:
https://valheim-modding.github.io/Jotunn/data/prefabs/shader-list.html
So yeah it would have to either be exposed to properties or hardcoded, which it seems to be neither.
Also deferred uses stencils for other things, so that complicates it further
I don't like deferred
So I think the only option is a custom deferred shader. But I'm pretty confident that would work, assuming you're able to change the render queue of the terrain.
So getting back to my previous question from my never ending irritating litany of questions - is there some sort of central catalogue of shaders where I can easily filter what parameters they accept and quickly visualize how they would look?
Or do I Google and hope for the best?
There's nothing like that that I know of.
Welp. This was a traumatizing programming experience if I ever had one 😉 I'll probably end up giving up altogether and my mod isn't going to see another release in the end.
But that's none of your fault. You've been of tremendous help for no reason whatsoever. Thank you for all your time and patience with my ignorance.
So it seems the deferred shader wouldn't work either, and that's because:
Limitation 3: Okay, so you can't have multiple queues, or multiple deferred passes in a single shader. So the solution might seem like it would be to setup two separate materials. But that's where the third limitation comes in to bite you. The deferred rendering path ignores the material queue for sorting! Unity just checks to see if the queue is less than 3000, and if the material's shader has a deferred pass. Then it sorts everything front to back and ignores the queue! This means you can't force this material to render after everything else. You can't even guarantee the two separate materials will render in the correct order!
But wait for the punchline!
So what's the solution? The easiest "solution" is don't use the deferred rendering path.
I know next to nothing about rendering pipelines and yet I already hate the defered one 😛
Then you'll be happy to know that basically all AAA games use it
Is this from a thread?
Knock yourself out:
Gotta love undocumented behavior
Like a little easter egg waiting to be found to ruin someone's day
I have to say. Coming from the corporate server side programming world - the quantity and quality of materials regarding Unity is appalling.
For something that's supposingly so ubiquitously used I often times find myself baffled by having to Google like this for hours to find undocumented behaviour of core components.
I'm testing in a new Unity project and I'm not able to recreate what bgolus says in that thread
Render queue is affecting the order
Could they... Have changed the behaviour between unity versions?
(for the matter I found several threads claiming that render queue doesn't affect deffered rendering)
Maybe, but it's a recent thread and the built-in render pipeline is practically abandoned at this point so I wouldn't expect any recent changes of this magnitude.
If only one of Valheim's native shaders accepted ZTest - we would be home free to test out that hypothesis.
Just apply that to my material and change the queue order.
so quick question, im new to making shaders and i want to know if i can program in C# within the hlsl code or if i have to do everything in that language, or whatever language it uses
cuz i wanna do stuff with raycasts and the like but am finding it difficult to find doccumentation
Shaders run on the GPU where there is no access to the physics engine or the Unity scene or anything like that. Shaders only have access to what they are given, through material properties and such.
alright
so all i gotta do is code my own raycasting to run on the gpu?
Remember, there is no access to the scene from the GPU. You can't get the colliders. You would have to gather all the necessary data in a C# script and pass it to the GPU through shader properties and only then could you implement some kind of raycasting in a shader.
alright
This isn't a standard thing that people do with shaders. It's technically possible, but usually completely unnecessary.
And difficult to optimize. You also have to remember that shaders run for each vertex and each pixel. Do you want to perform a raycast for each vertex or each pixel? If not, then you can't do this in a shader.
alright
ok wait so
im not really wrapping my head around how this all works
so is this like just general code that runs for each pixel?
like if i return the pixel color as a base color multiplied by something like blue, it will run the same way for every pixel?
Yes
so then what is the whole vertex part for?
i mean i know its pretty much for mapping right
but how do you use it?
does it run the same way for each vertex or is it different in some way?
also whats a clip position?
The purpose of the vertex shader is to calculate where each vertex of the mesh should appear on screen. To do this, Unity gives the shader information about where the transform is relative to the camera in the form of a matrix (UNITY_MATRIX_MVP).
Clip position can be considered as a sort of screen position
alright
so can this be utilized to make the appearance of vertex deformation in shaders?
After the vertices have all been calculated, the GPU will then figure out which pixels on the screen those vertices and the triangles connected to them occupy. Then it will run the fragment/pixel shader for each of those pixels to calculate what color they should be.
ohh ok
Yes. There's nothing that's forcing you to use the vertex data you're given and nothing stopping you from modifying it a bit.
so it runs the vertex shader first, gets the general area onscreen, then colors that area with the fragment shader, correct?
Yep
alright i get it now, thanks!
That's the rasterization step, but that's something the GPU handles and can't be modified by developers.
hey guys, I might be being really daft but - is there an hlsl equivalent to UnityCG.cginc for use in URP? In the docs under "HLSL in Unity", they still point to using UnityCG. Is this still used in URP?
hello everyone, just wondering if anyone could shed some light on making text glow, is it better done in shaders or as images?
tmpro has lighting text
yeah, I did see that. also it has glow, but doesnt have a blur to it
so one way is to render it in a separate target and add a blur
yeah
could also add it to the shader
I was able to add pixelation by editing the frag func
Oo... thats interesting. Could you please provide some more info?
just have to go to assets > textmeshpro > shaders and copy and edit a shader add properties and edit the pixl shader then u can make a material from it and use it
bluring is simply moving pixels in outwards directions
so you can simply edit the output of the frag function with a blur algorith
thanks a bunch, just a small question, did you do it in URP or BIRP? Because I was thinking of doing a multi-pass blur.
It was urp
thats so awesome. Will try a single pass in fragment shader then
@low lichen by the way something I found odd is that I didn't need to correct for gamma when writing the bit shifted index to the vertex color, I'm not sure why you had to do it
It might mean your project is using Gamma colorspace instead of Linear
Or vice versa, but pretty sure mine was in Linear
Ah, I thought I had to do it if it was in gamma space, then I just misunderstood
Hi there, I have to use a double sided shader for a model I want to use. (Buildin renderpipeline). But light illuminates on the opposite side. Any idea how I can fix this. I have no experience in shaders. I used the provided one by unity. Any help is highly appreciated. thanks
That means the shader isn't flipping the normals for the backfaces.
ok another stupid question about writng shaders, but does the shader language use half HLSL and half c#?
im noticing half the syntax is HLSL and half the syntax is C#
I have to use a double sided shader for a model I want to use
I want to challenge this premise. Can't you just flip/fix the normals of the model?
Shader files are written in Unity's ShaderLab syntax (i.e. the Shader, Properties, SubShader, Pass blocks) & HLSL (under CGPROGRAM or HLSLPROGRAM).
HLSL syntax might share some similarities with C# though, as they are both C-like languages.
alright
also, how can i get the vertex normal?
If it's a vert/frag shader you'd use the NORMAL semantic in the vertex input struct
alright
so wait
actually nvm i can search that
oh also
nvm, i could probably search that too
so whats "o"
skimming over the input structure section i saw this note and figured i might be taking the wrong route
because apparently you cant use the normal semantic in surface shaders, and i believe im using a surface shader, although its unclear
because it does have a vertex and fragment function, so it might not be a surface shader, but when making the script i clicked standard surface shader
so i looked at this and saw the note about o.Normal and i am very confused
brb
It's a vert/frag shader if you have #pragma vertex .. and #pragma fragment ..
It's a surface shader if you have a #pragma surface .. line. Surface shaders handle shading/lighting for you (assuming Built-in RP). o would be the surface shader output struct. You'd set o.Normal when sampling a normal map.
Further down that docs page it does also mention if you do write to o.Normal you can use float3 worldNormal; INTERNAL_DATA and WorldNormalVector (IN, o.Normal) to get the new worldNormal.
oh right cuz i made a new surface shader and deleted everything to start from scratch and made a vert/frag shader
oh ok
so i just write o.Normal to acess the normal then?
I believe usually two-sided shaders render both sides but only the forward facing side receives lighting which is also shown on the other side
thanks, will check
model is from turbosquid. I asked for that already but the interior and exterior of the bus is always a double sided mesh
If it's a vert/frag you'd use float3 normal : NORMAL; in your vertex input struct (probably named appdata) to access the mesh normals. If you need it in the fragment stage you'll need to pass it through the vertex first.
There's some examples here which might help, https://docs.unity3d.com/Manual/SL-VertexFragmentShaderExamples.html, can probably find tutorials online too.
alright thanks
thanks will check
and uh, how do i get one value of a float3, im very new to hlsl
like if i have (1,3,2) and i want to get the second value (3) how do i go about doing that?
Is there any way to speed up the compilation of compute shaders or something I can do or arrange it to make it shorter? currently my compute shader takes about 2-4 minutes to compile every time I make a small change, and I cant deal with that anymore(its up to 6.1k lines now with 12 kernels)
.y or .g would give you the second component. (It's xyzw/rgba). This page has some more info : https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-per-component-math#the-vector-type
Shader "Lighting/Dither"
{
Properties
{
_Albedo("Albedo", 2D) = "white" {}
_Color("Color",Color) = (1,1,1,1)
}
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex Func1
#pragma fragment Func2
#include "UnityCG.cginc"
struct appdata {
float4 vert : POSITION;
float2 uv : TEXCOORD0;
float3 norm : NORMAL;
};
struct v2f {
float4 vert : SV_POSITION;
float2 uv : TEXCOORD0;
};
fixed4 _Color;
sampler2D _Albedo;
v2f Func1(appdata IN)
{
v2f OUT;
OUT.vert = UnityObjectToClipPos(IN.vert);
OUT.uv = IN.uv;
return OUT;
}
fixed4 Func2(v2f IN, appdata IN2) : SV_Target
{
fixed4 pixColor = tex2D(_Albedo, IN.uv);
return (pixColor*_Color)*IN2.norm.y;
}
ENDCG
}
}
}
So what do you think i did wrong? im not even sure how i can begin to debug this, as stated before, im fairly new to hlsl
from what i can guess based off "duplicate" "value" "semantic" and the two variables listed, i can assume that the two have either the same value or something and that somehow fails to compile
im not really sure
The fragment shader can't get both v2f and appdata. It can only get the output of the vertex shader, which is v2f.
alright
so i need to pass the data i need to v2f and no longer pass appdata to func2?
Yeah, just remove the IN2 parameter in Func2
Also, I would recommend just calling them vert and frag
alright, thanks
the functions?
ok i managed to get very basic and rigid lighting, id say its an alright beginning step
next step is making actual lighting..
Yeah
yeah thatd probably work better for organizing, thanks for the tip
uh ok so
how can i use common math functions when writing a shader?
The common ones are global, so you can call those functions directly, like min, max, sin, cos. They are documented here:
https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions
alright, thanks
so what do you bet im doing wrong here?
i looked at the syntax on the link you provided and the "in"s fail to compile, same with the fvector before calling the method
@smoky vale I've never seen or used the dst function. If you're looking for something like Vector3.Distance, you should use distance
The page I gave you is a comprehensive list, but I wouldn't be surprised if it also contained some old, obsolete functions.
Though to me it looks like you want dot, as that's usually how you calculate the light factor. "N dot L", or "dot(Normal, LightVector)"
see i would but it seems like thats for floats
im not too big on math, im good at math but i dont have enough expirience to know what dot is
ill look it up
It's dot product. It can be used for various things, so the mathematical definition won't be super useful. In gamedev, it's most often used to compare how similar two directions are. If you pass in two normalized directions, you will get 1 if they are identical, -1 if they are opposite, 0 if they are parallel, and any number in between.
bumping this, still not sure!
wait parallel?
if we are talking in just directions, shouldnt parallel be impossible? or am i missing something
cuz they all start at the origin unless specified otherwise
i think
SRP has it's own set of common HLSL functions. Pretty sure you can't include a cginc file inside an HLSL context.
https://github.com/Unity-Technologies/Graphics/blob/master/Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl
Yeah sorry, I meant perpendicular.
oh kk
Both start with P 😓
yeah i mess that up too sometimes
also
is there a way i can print something into the output? i hate asking so many simple questions cuz i dont know how to debug in hlsl
It's a fair question. The simplest way to debug something is to just return it in the fragment shader.
hm, alright, so just trial and error then or am i misinterpreting
Thanks for shedding some light. There is no mention (at least that I've found) of Common.hlsl in the unity docs. The HLSL specific sections still point to using UnityCG for helper functions. It really is frustrating
oh also, do shaders update in the viewport in realtime or what might i have to do to make them run in real time?
Also - are SRP/URP interchangeable here?
Well if you're calculating some float value and you want to know what it is, like lightfactor, then if you do return lightFactor, each pixel will be a shade of gray. It's not dissimilar to calling Debug.Log from a script to figure out what value something is, except you're limited to visualizing 0-1.
alright
oh yeah right right cuz without the albedo or color modifier itd just be a shade of grey
In this case, yes. The URP package depends on the SRP package, which contains a set of common files shared between URP and HDRP
URP might have some common files specific to URP, but those will probably be related to things like lighting.
well i know im doing something wrong, and its probably something really simple and stupid, but it appears that it isnt taking into account object rotation, and it shouldnt i dont believe, because object rotation isnt mesh rotation and it doesnt have much to do in relation to the workings of unitys gameobjects right?
Are you sure you're using the world normal? The normal vector you get in the vertex shader is in object space.
Alright, got you. Makes a ton of sense. By the way - thank you very much for your constant support for anyone here learning shaders. The up-to-date resources online are largely limited, and it has been a huge help and very motivating having your support 👍
oh, yeah i forgot there was a world normal, hold on a sec
i think i might be doing this part wrong
i mean it doesnt error
but its all black and it feels like im doing it wrong
You might be confusing this with a surface shader. In a regular vert/frag shader, you have to calculate the world normal manually. Unity gives all shaders the localToWorld matrix which can be used to transform local positions and directions into world positions and directions.
oh, alright
But there are also helper functions defined in UnityCG.cginc to make things easier. In this case, UnityObjectToWorldNormal
oh
You just need to pass in the normal from appdata. The function is defined as:
// Transforms normal from object to world space
inline float3 UnityObjectToWorldNormal( in float3 norm )
{
#ifdef UNITY_ASSUME_UNIFORM_SCALING
return UnityObjectToWorldDir(norm);
#else
return normalize(mul(norm, (float3x3)unity_WorldToObject));
#endif
}
No problem, you're doing very well, considering you're not following a tutorial and just figuring things out on your own.
what's an acceptable way to handle switching out specific-colors in a sprite, specifically for 2D? I've heard of lookup textures, but honestly, barely have a grasp on what TEXCOORD really even is, let alone how to use more than one texture in a shader. I'm effectively trying to exclude specific colors on a texture (in this case, black and white) from changing when the SpriteRenderer's color is changed. At the moment, my fragment function looks like this:
float4 frag(const v2f i) : SV_TARGET
{
const half4 sample = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv);
if (all(sample >= float4(0.99f, 0.99f, 0.99f, 0.99f)) || all(sample <= float4(0.01f, 0.01f, 0.01f, 0.99f)))
{
return sample;
}
return sample * i.color;
}
I'm sure I'm approaching this wrong!
for reference, the vert function:
v2f vert(appdata v)
{
v2f output;
output.position_cs = TransformObjectToHClip(v.positionOS);
output.uv = v.uv;
output.color = v.color;
return output;
}
Does this code work?
no - can only assume the if statement never evaluates to true, since each pixel returns it's tinted color. sorry, should have said that from the get go
my teeny tiny C# brain cannot deal without breakpoints 🤒
Am I maybe handling colors wrong for how they are inputted to the pipeline? This is my struct:
struct appdata
{
float3 positionOS : POSITION;
float4 color : COLOR;
half2 uv : TEXCOORD0;
};
I personally haven't used all or any, so I don't know if you're using it correctly. In general, branches are discouraged in shaders, and there are often ways around it. Lookup textures is one such example. That's not to say you should never use branching; sometimes you have to.
One potential workaround is to use dot to compare sample with float4(1, 1, 1, 1). If the pixel is white, it will return 1. If the pixel is black, it will return 0. For any other color, it should be somewhere in between. Now at least the condition can be simplified to only compare one float, albeit still twice.
Yeah, I'm sure it shouldn't be necessary here. I'm just a lot more comfortable with programming & I kind of wanted to just get something working before jumping deeper into anything I don't really understand 😮💨
Well, the alpha channel might still mess things up. It's perhaps better to ignore it and just compare the first three channels. It doesn't make sense to me to allow half-transparent white and black pixels to be tinted.
yeah, makes sense
this is a test sprite I threw together to work with:
dot(half3(1, 1, 1), sample) didn't change anything, so I just returned dot(half3(1, 1, 1), sample) and now I am baffled haha
Ah, since the colors are normalized, the dot range is probably between -3 and 3.
So try dividing by 3 and things should look a bit better
The black pixels should be black, the white should be white and everything else should be some shade of gray.
Pretty cool! I mean, the black pixels have still turned to grey, but nice to see something coming out a little more normal.
how did you get to the conclusion that the dot range is between -3 and 3? could you walk me through that a bit?
Because a dot product is defined as:
float dot(float3 a, float3 b)
{
return a.x * b.x + a.y * a.y + a.z * b.z;
}
Since it's a sum of each component multiplied, the highest number is 3
Ah, I see
yeah that's clear
what kind of docs are useful for these basic hlsl methods? I get redirected to microsoft docs a fair bit.
https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-dot
The Microsoft docs are where I go to see all the functions available and their signatures, but the NVidia CG docs can also be useful. It's technically not HLSL, but the two languages are extremely similar so the docs are still useful.
NVidia's documentation often includes a "reference implementation"
https://developer.download.nvidia.com/cg/dot.html
NVIDIA Cg Toolkit Documentation for dot
wow, that's great, thanks so much!
the world of shaders is dangerously low level for me. I work with C# all day and even the thought of having to deeply understand what I'm actually doing is terrifying, lol
They are very low level, but at the same time they are so sandboxed and isolated from everything that it makes things a bit simpler.
yeah, I get that vibe.
Thanks for all your help today! logging off for now but hope you have a fab day/evening/whatever timezone you're in 🙂
Thanks, good night
sorry if im interrupting, but how can i get data from other objects in the shader automatically?
to clarify, i want to get data from a list of gameobjects, or more specifically their positions, to use as extra light sources
i can use practically the same math i did for the main sunlight, but im stumped on the part about getting data from anything that isnt automatically passed by unity
This question related to what I just said, shaders are very isolated from everything else. You simply have no way to access anything apart from what is given to you.
oh, alright
i guess ill have to figure out a dif solution
Unity gives you some information automatically, like the direction of the main light, the position of the camera and such, but to get information about the positions of objects, you will have to do that through C#.
my best guess is using a property to control lights, like a list of some sort, ill have to look into it
yeah, but just to clarify i cant get info from a c# script into a shader script because they are so isolated?
Well if you're thinking about lights specifically, that is of course something that Unity does consider and in some cases passes information about automatically.
oh
A shader can't access outside information, but a C# script can pass data to a shader.
im looking mainly to make my own
oh, yeah thats what i want
how can i pass info from a script to a shader?
If you've ever worked with materials through script, then you've probably done it before. You use the material.SetX, where X is Float, Vector, etc...
You can also set global properties through Shader.SetX
ive never worked with materials before, but with that info i can research those things, thanks
To access those properties in a shader, you just need to define a variable of that type and with the same name in the shader. The variable needs to be defined outside of a function, like a field:
float3 _SomePosition;
but one question, and this might be really simple, but do i just put in float3 for the property type?
Yep, if you want to pass a Vector3
oh, so i dont have to even touch properties then?
There isn't a specific SetVector3 method, just SetVector which accepts Vector4, but you can still use that and let it automatically convert the Vector3 to Vector4.
and i almost forgot im using just a single float for that
If you mean the Properties block at the top of the shader, no it's not required to define the property there. That's only if you want it to be visible and editable in the material inspector.
so i just use SetFloat
ohh ok
thanks for the help!
and uh
one more thing
since i never worked with materials, or much at all with shaders, how do i acess them from the assets folder?
i ofc have them in a folder under the assets folder, but im not sure how i even acess those assets in the first plac
i know i can acess materials in the renderer components of the gameobjects but i believe those are seperately instanced
I assume you mean accessing them from a C# script. You could access it through the Renderer component, and I would recommend that if you expect you'll need separate values for each game object.
But if you want each game object to share the same property values, then you can reference the material directly with a serialized field:
[SerializeField]
private Material material;
alright
And then you can pick the material in the editor inspector
k
Anyone understand why this happens? I was using EmissionColor to tint enemies for when they're invincible/damaged, but only one part got tinted, all the rest looks like this below, somehow appearing normal ingame, am quite confused pls
Also another question is like, what is the most efficient way to tint every part of a model? I made mine mainly out of cubes, and there's quite a few cubes/creature, invincibility is supposed to flicker etc...
Emission color is additive. Normally to tint with a color you multiply the tint color and the pixel's color. So for the standard shader (which you show being used) you'd change that green color for "Albedo".
As to only parts having emission....I can't tell from what you've given us. Make sure you've not got multiple materials and/or multiple meshes. What you posted shows black emission (none).
"Tint every part"? It depends on the number of materials you have on the object, and whether or not the object is really composed of multiple meshes or not, and if so, what materials are assigned to what meshes. Shaders run per-mesh.
Apparently there is one difference
Didn't notice before
Model's literally made of a bunch of cubes, that's why I've got a issue for efficiency of tinting every piece
combine those cubes into one material?
Ummm would be possible if I 3d modelled it, but no it's purely made of cubes
Ohhh nvm issue found
Extremely stupid, originally takehit anim tinted it, but it caused that issue xD
Ty, my bad
is it possible to get tessellation in URP shader graph?
Maybe in latest versions ? I'm not sure
Hi everyone! Can someone tell me if it's possible to access unity's terrain alphamaps or colors within a surface shader?
And if not, would it be way too hacky to create a temporary material + set color maps within it?
If you include "TerrainSplatmapCommon.cginc" you will have access to the terrain control texture (the layers mask) and splat maps (individual layers color texture)
Look at the built-in shaders source code for help and inspiration
Why is my copute shader that is dispatched from a command buffer not showing up in RenderDoc or the frame debugger
But you're sure it is executed ?
oh yes
Im using it to move things that are rendered by a BRG, and they indeed do move
if I comment out cmdBuffer.DispatchCompute(m_TransformUpdateCS, m_TransformUpdateKernel, (queueCount + 63) / 64, 1, 1); they stop moving
Hum, well, if it is executed, and the result is visible in RenderDoc, it should be there.
Tried to name the command to something particular and search it in the commands list of renderdoc ?
I did I named it "TransformUpdater_CMB_Buffer"
doesnt show up at all
thanks! that's enough for me to stop wandering around docs aimlessly
I have no idea why it would not show up :/
I'm hella confused as well
But you can see the rest of the commandbuffer ?
Ah, interesting. How are you executing it ?
Graphics.ExecuteCommandBuffer(m_gpuCmdBuffer);
I'm not 100% sure, but maybe this is the source of it.
I think this is not captured by renderdoc, compared to adding the command buffer to camera events
Can you please help me with putting a material on my terrain? I dont get it
Create a layer then add the material to the layer
How?
Does anyone know how to change this shader to work with URP? I tried using Unity's built-in to URP converter on it, but it says TOZ_Water_Flow material was not upgraded. There's no upgrader to convert TOZ/Water/Flow shader to selected pipeline
Code is here... https://hastebin.com/opumehabev.properties
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i dont think we have the same version
you're on Raise or Lower terrain
ye
change to paint texture

The converter only works with Unity's shaders. There's no way to automatically convert custom shaders, it would need to be rewritten.
But as this is a vert/frag shader I think it should still work. You need to remove the "LightMode"="Always" tag though
Hi, I recently started studying unity and have a question: Which is better to use your own shader (screenshot) or use secondary textures in sprite editor
works now 🧯
but it looks really shiny
keyboard was in the backrooms
go to the newly created layer file and change the sliders
should be in the same folder as the terrain file iirc
or maybe the one you had open at the time of creating the layer, who knows
honestly im really tired and it genuinely threw me lol, i thought i was hallucinating
lol
You'd typically use both. The shader uses specific texture references : _MainTex, which is the default one, and in the case of this first screenshot _Emission - which could be set up as a Secondary Texture on the sprite. This would allow you to swap out the sprite and both textures change automatically, rather than having to set the emission tex on the material manually.
ty
Thanks!!!! It works perfectly now!
Question about URP forward+PLUS:
The unity hlsl code takes the keyword 'USE_FORWARD_PLUS' for the forward-plus path. Do i need to manually set that in my keywords or there a way to indicate to the shader, that the render settings are set to forward plus and this, USE_FORWARD_PLUS is set automatically?
I have no experience with Forward+, but looking at the ShaderLibrary, it seems Core.hlsl has :
#if defined(_FORWARD_PLUS)
#define _ADDITIONAL_LIGHTS 1
#undef _ADDITIONAL_LIGHTS_VERTEX
#define USE_FORWARD_PLUS 1
#else
#define USE_FORWARD_PLUS 0
#endif
And _FORWARD_PLUS is defined in shaders via a keyword, #pragma multi_compile _ _FORWARD_PLUS
Assuming the shader has that, it'll be set automatically by Unity
Ah okay. That's really useful. Thank you! Maybe that even helps me solve my crash-problem ( https://forum.unity.com/threads/forward-additional-lights-in-a-customlighting-function-and-a-crash.1378932/ )
I have a problem with this shader.
float TOA(float opposite, float adjacent)
{
return degrees(atan(opposite / adjacent));
}
void TrigBillboard_float(float3 VertexPosition, float3 ObjectScale, float3 ObjectPosition, float3 CameraPosition, float3 MinAngle, float3 MaxAngle, out float3 Out)
{
float3 scaledVertexPosition = VertexPosition * ObjectScale;
float3 deltaPos = ObjectPosition - CameraPosition;
// Calculate X angle through YZ Axis.
// Calculate Y Angle through XZ Axis.
float angleX = TOA(deltaPos.y, deltaPos.z);
float angleY = TOA(deltaPos.x, deltaPos.z);
// Clamp the X & Y Angle with MinAngle & MaxAngle.
float3 eulerDirection = float3(-angleX, angleY, 0);
float4x4 constrainedDir = ToMatrix4x4(eulerDirection);
float4 rotatedVertex = mul(constrainedDir, float4(scaledVertexPosition.x, scaledVertexPosition.y, scaledVertexPosition.z, 0));
float3 finalPosition = rotatedVertex + ObjectPosition;
Out = TransformWorldToObject(finalPosition);
}
When X or Z is close to 0, the billboard flips strangely
It lookat the camera properly, but not when X or Z is close to 0
I'm trying to use the URP Unlit Sprite shader graph, but it seems to be missing an emission component from its master node
unlit doesnt have lighting so no emission, its basically all emissive if you add post processing
I remember using emission on an unlit graph a few years back, it seems that I simply added an emission map multiplied by hdr to the color node. Must've forgotten. Thanks
Multiplying or adding to a color/texture so its values go above 1 makes it more emissive with HDR rendering
Yes, that's what I was remembering doing. Thanks
Heyo, i have a question. Is there any way or alternative to get the Camera Depth Normal Texture? I need a non script method as im making a shader in Amplify for VRChat and they dont allow any external scripts, im like 90% there i just need to mask my custom triplanar sample shader so it looks clean. > - < Version of unity: 2019, built-in pipeline
Does anyone here with a big brain know how I could add randomised patterns onto a shader graph?
Like, I have these mountains, but I want the mountains to feel more random.
If they are all interactable, why don't you randomly place them with script?
Via shader graph I'd probably say:
- use a noise texture
- use step to make it lack and white
- (optional) pixelize the shape to fit the pixel size of the piramid
- have the piramid texture loop where the shape is white
- put that into color @vital smelt
That's how it already generates the positions of the Pyramids
@rare wren
It just uses noise and where the noise is white? Pyramid
Then use different noise?
I wanted to try making some of the pyramids overlap though, or even have some larger than others
Change the values of the noise or maybe vernoi noise
Maybe then read out the noise without step and make the textures bigger when the value is higher?
Can anyone point me to a place where I can make a pixelate shader (in basic render pipeline)? I have a line renderer and want to make it pixelated
for some reason my texture wrapping math acts differently out of a sub graph versus inside the main graph
I see both have a different input at the bottom left of the main graph. Or is this something collapsed?
Like 2 in, 2 out
both are from the same tile and offset from the same uv
cleaned up a little to show the top is just completely different
Might just be the 3D (sphere) vs 2D (quad) preview. You should be able to change which preview it uses in the Node Settings (tab of Graph Inspector, while node is selected)
Can anyone point me to a place where I can make a pixelate shader (in basic render pipeline)? I have a line renderer and want to make it pixelated
doh thats right the 2d preview is correct
Did you try in-game?
Maybe make a bug report for it
I have this shader code
Shader "Custom/Pixelate"
{
Properties
{
_MainTex("Texture", 2D) = "white" {}
_PixelSize("Pixel Size", float) = 10.0
}
SubShader
{
Tags { "Queue"="Transparent" }
LOD 100
Pass
{
CGPROGRAM
// Upgrade NOTE: excluded shader from DX11; has structs without semantics (struct v2f members pixelSize)
#pragma exclude_renderers d3d11
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
sampler2D _MainTex;
float _PixelSize;
float4 frag(v2f i) : SV_Target
{
float2 pixelPos = i.uv * _PixelSize;
pixelPos.x = floor(pixelPos.x);
pixelPos.y = floor(pixelPos.y);
pixelPos /= _PixelSize;
return tex2D(_MainTex, pixelPos);
}
ENDCG
}
}
}
However it doesn't seem to do anything
you had an error it in before and it added the "exclude_renderers" tag, take that out
Ye its all good now
Is there a node that will return 0 if below a certain X and return the original number if higher than X?
custom code node with return x > limit ? x : 0;
Is there a way to pack float material properties into float4s ?
Ooh, I didn't know those existed, thanks
Anyone know how I could make it smooth all the way. Its multiple gameobjects stacked in a row, and you can clearly see where one ends
So you're having multiple transparent cubes and you can see the sides of the cubes further behind through the cubes nearer to the camera.
Does it need to be cubes?
If it were a plane, just 4 vertices and a face, it wouldn't be a problem, right?
hmm true
so unity has the ColorValue in the standard shader
this is the albedo
but does unity do anything to this value? like gamma correct it or whatever?
wondering because that albedo isnt matching with something im doing that is just raw outputting it
Check your project settings for color space. Also try an unlit shader next to it to compare it.
ahhh ok thanks
it did work as expected with planes, its just i do have in mind that the path will at some point curve and twist and i would like the path to have a little girth while doing so. so could i fix this while still having cubes?
Well, you can build 'cubes' that miss a few sides. You need two types:
One where the front and back face is missing for a straight part and one where two at one corner are missing for a corner piece.
oh right, i'll try that. thanks
Quick Q. I've seen various different functions being used in different tutorials to serve the same purpose. For example - for getting the pixel color of a texture in the fragment function, some tutorials use tex2D, and others use SAMPLE_TEXTURE2D.
In that specific example, what is the difference, and what is the standard that should be used? I see tex2D a lot, but it doesn't appear in Unity's Unlit shader, and I'm getting errors when trying to use tex2d(_MainTex, i.uv): no matching 2 parameter intrinsic function. (my UV coord is properly being set in vert)
I'm not an expert on the topic but here's what I know:
It's mainly different styles of writing HLSL code
SAMPLE_TEXTURE2D is actually a macro for Texture2D.Sample(samplerstate, uv), which does the same thing as tex2D
iirc it does some additional checks to pick the correct way to sample depending on the platform
SAMPLE_TEXTURE2D / Texture2D.Sample is the "newer" way, but I still see a lot of shaders using tex2d
I also think your error is not from the function not existing, but from you passing in a texture instead of a samplerstate
Ah
That makes a lot of sense! I still don't fully understand what a sampler of a texture really is, but I'm comfortable enough being able to pull one/the other out when needed.
I appreciate the breakdown & the link ❤️
Is there a way to use functions from another hlsl file?
I have a few functions that I want to reuse
Sorry for noob question
Just started
Nvm just found out #include <HelperLib.hlsl>
I have made a grid shader in world abosolute, but it doesn't extactly do as I expected it to
I'm trying to make a grid that is in a plane that follows the camera, but its an endless grid in world space.
Ping me if anyone can help out
If you want the grid to appear around a point in space that happens to move with a game object, you need to input that position through a parameter.
Where does that happen?
What node would I use if i have a texture and i only want it visible in the darker parts of a gradient? maybe with a manually set threshold?
i basically have a simple noise and i want less noise in the lighter parts of the gradient vs the darker parts of the gradient
thank you 🙂
kinda does what i need but the texture now became very low as it's not taking into account the gradient of noise
and before the step
essentially, in the lighter parts of the gradient, i either want to fade the noise out or reduce the noise
Dont know if this is the right place to ask but, I've made a little planet to walk on in my game but even an 8k texture is blurry up close. can I add tiling textures based off the colours? So like a grass texture for green parts and a snow one for white ones
Check the gradiant and sample that.
Yes you can, you could use triplanar mapping and then lerp between textures on the boundaries
You could use the low res color map as a mask map to combine different surface textures
Another technique is "detail mapping" where a low and high resolution texture are overlaid
how can i fix my charachter being this deep in my interactive snow shared
How do you guys handle noise textures? up until now I’ve just been downloading samples of different noise methods online. Is this fine? Should I be writing a script to create noise, and would this typically be a C# or a shader script?
I also want to learn more about different applications of different types of noise (e.g Perlin noise is often applied to procedural terrain), and how these types of noise can be generated using a shader.
is there anyway to remove this seam without using world space UV ?
with a noise using the triplanar node works well but the triplanar only accept a texture not a gradient (done with 2 colours and lerp)
Saw this tiktok and thought it was very neat, been trying to find something just like it ever sense
The ray marching is soo cool!
Have you tried searching for "signed distance field rendering in unity"?
I have, and haven’t found much similar
Just trying to find a shader that just does that like merging effect
SDF rendering like that is accomplished with raymarching. You should be able to find more results with that term.
Alright thank you!
Would the position be the game object I guess
bumping if anyone knows!
Can anyone tell me what I'm doing wrong? I'm trying to send an array of colors to the compute shader via a structured buffer but I can't get any data that seems readable...
GPUs can create different types of noise within shaders. If you search for 'shader graph noise' you will some content about how the noise nodes are used for things like flickering fire, pulsing energy shields etc.
I'm getting alot of content specific to using shader graph, but I'm looking to see how this would be implemented in HLSL. Sorry, should have been clearer - the resources are still useful though 🙂
You can look into the URP+HDRP shadercode.
https://github.com/Unity-Technologies/Graphics/tree/ce1905322722287c1420a6d85de14158c1648a84/Packages/com.unity.render-pipelines.universal/ShaderLibrary
Very helpful for writing hlsl and customFunctions for shadergraph.
I kind of figured this out by just making my own "Color" struct with 4 floats named r, g, b, and a, but is there no way to properly just transfer a Color or Color32 using SetData/BeginWrite ?? Was hoping to be able to just send them to a float4 buffer.
Hey all!
I've been searching and digging trying to find examples of the vfx I'm hoping to achieve on my project! I've finally found it, a 'modern' ukiyo-e style represented beautifully by harry heath;
My issue is, I simply can't figure out how to recreate, has anyone worked on anything like this that could lend message to figure it out!
Edge detection is probably the main element of these. e.g. https://roystan.net/articles/outline-shader/ (Built-in RP) or https://alexanderameye.github.io/notes/edge-detection-outlines/ (URP)
For the third example, I know Harry Heath also posted a small breakdown : https://twitter.com/harryh___h/status/1297891009737654277
@weltraumimport Here's a little breakdown of the line rendering; the second image is an extra pass which is then used to determine where lines should be drawn and what colour the line should be. (here I'm using red and blue channels as coords for a LUT and green for inner detail)
156
Thanks! And for the colours themselves I'm certain they're shader based?
The only thing I can think of is if half precision is being forced on for some reason, that would explain garbled data
I tried sending a simple Vector4 into a float4 StructuredBuffer but it didn't work either, so I guess the structs and datatypes are pretty strict when it comes to matching
will compile times of a compute shader be improved if I moved kernels into cginc files, or would it be much better to just make entire seperate compute shaders?
cuz these 4 minute compiles are getting to me
@copper falcon @regal stag thanks so much for the resources!! very appreciated ❤️
How do I bake the diffuse result of shader on a mesh into a texture? For example, if I had a shader that converted the mesh's normals into diffuse colors, how would I then bake that color data into a Texture2D? I'm using shader graph btw.
Is there any downside to having 12 compute shaders with each 1 kernel vs having 1 compute shader with 12 kernels?
Can try this, https://github.com/Cyanilux/BakeShader (see readme for info)
Can this be done at runtime?
I see, it can be done through HLSL, which I'm assuming means at runtime. This is really cool, how did you get the texture baking to work? I've been looking all over forums now for like half an hour
The tool itself is editor-only, but the concept behind it could probably work at runtime. Rather than using vertex positions the shader needs to output in uv-space (there's a provided subgraph for that). You'd then draw that renderer to a render texture, (and optionally save that to a png).
I use this method : https://github.com/Cyanilux/BakeShader/blob/e2e61b3cc4ae99338899c50977f2932cfeb4f897/Editor/BakeShader.cs#L226, as it should work in any pipeline.
Awesome, thanks! I've tried baking render textures modified by a material already using the Blit functions. The UV based effects work but not the geometry based ones. So the subgraph should essentially allow all of those geometry functions to work? Like getting the normals, positions, etc.?
There's no PBR graph in URP?
Yes. With a blit you're basically rendering a fullscreen quad while with this you'd still be rendering whatever mesh you want. It's just using the mesh UVs to determine the position on screen (or render texture in this case), rather than the vertex positions. (and ignoring view/projection translations due to cmd.SetViewProjectionMatrices)
Since the graph requires overriding the Position port, you'd have to use a Custom Interpolator if you want to pass through the regular vertex position. (see example 1 here : https://www.cyanilux.com/tutorials/intro-to-shader-graph/#custom-interpolators)
Normals and other data should work fine as-is though.