#archived-shaders
1 messages Β· Page 9 of 1
his only makes the bottom while thin film needs the top
maybe I can just lerp it with grey???
I got abunch of charts of what im 'supposed' to see
pretty close tbh
atomic
is that from the colors being way too high, or is that bloom post proccessing?
it's because I set the film layer index to like 7
oh geez
its 7:30 nearly in my time zone so i'm going to call this a work day done with, ill resume work on this tomorrow but approaching it from this guy's docs https://sdm.scad.edu/faculty/mkesson/vsfx319/wip/best/best_winter2014/william_cavanagh/index.html since it looks like he does the same math at first glance, but more comments.
Soap bubbles have very thin walls. The range can be anywhere from 10 nanometers at the top of a thin-walled bubble to over 1000 nanometers
It's 00:28 here
brit moment
Ah yeah im five hours behind, that lines up with UK on the ol' timezones of the world
aha lol
oh yeah that's the same page isnt it π€
That result is real good, glad to know this will work in the end π
The colors of a soap film provide a precise measurement of the film's thickness. The relationship between the colors of a soap film have been well known for more than a century. In fact, these colors provided important evidence in confirming the molecular theory of matter. The color charts on this page mapping color to thickness were prepared by...
soap bubble fandom wiki lmao
lol
I think the thing I'm missing here is how to actually use the result of the thin film since I can't just plug that straight into the base colour
Ok I sleep, 02:10. Will post the shaders tomorrow
"Soap Bubble Wiki" wow
there are neiches everywhere
wow this is actually really useful info too
Looking forward to it, Ill be getting back cracking at it tomorrow as well
Thanks for the detailed response. I'm on built-in pipeline.
So the reason I'm trying to use this instead of an actual transparency is twofold: first, when used on something like a door. This reversed reflection probe can be used to disguise level loads while making it appear that the scene on the other side has loaded. Second, used in an object, it could be used for liquid/glass effects without any significant addition to draw overhead because it's pulling from the already-implemented reflection probes in the scene. Essentially It is as performant as a normal metallic object.
I will go pry through the standard shader again...
is there any way to sample coordinates of a pixel in "screen space" or "clip space" with the addition that it accounts for the movement of the camera? (using orthographic projection)
meaning that the coordinates remain the same if we translate the camera
if it helps, im trying to do some screen space dithering that moves when the camera moves
and it moves in such a way, that the same point in space will use the same dither threshold if the camera hasnt rotated
what comes to mind is maybe calculating a projection matrix that doesnt account for translation and using that
Won't you want world position for that?
the problem with that is that the dither pattern will be lost
it looks like this if you sample clip space
cool
does look familiar lol. Shame he hasn't released his work
well there are many tutorials online, but he is currently using a custom render pipeline
and his work is just way ahead of anyone else
im doing it the same way
but it's hard
i might release some tutorial or the codebase when im done doing the most important work
though i get why he hasn't released his
is there a way to generate perlin noise in hlsl shaders?
Yes, but you need to get or write yourself those noise generating functions
Somebody already did port a noise library from glsl to unity here : https://forum.unity.com/threads/2d-3d-4d-optimised-perlin-noise-cg-hlsl-library-cginc.218372/
Hey guys. :)
As many of you know, HLSL's noise() function supposed to return Perlin noise. However, it simply doesn't work because none of GPU vendors...
ah thank you
@tight phoenix lets agree that whoever gets it working shares the result
how do i read a pixel value from a texture2DArray in hlsl?
tried my hand at a soap bubble shader; the phase offset isn't physically based (just a remapped Fresnel multiplied by some noise) but then i multiplied that by some values for the different wavelengths, sined, then squared that so the colors are fairly realistic
Speaking of awsome shader libs I got to share this https://github.com/patriciogonzalezvivo/lygia
I'm struggling with the opacity. Would you be willing to share what you have?
I made it additive and just used a Fresnel as the alpha
additive with what?
It's a blending mode, means it adds onto the background
sorry I'm not super familiar with shaders themselves
ah, how would I enable that on the urp standard lit shader?
I used shader graph and it's in the graph inspector
Is yours a physically based thin film shader?
Not entirely physically based (I don't calculate the phase offset properly using the thin film stuff) but the colors should be the same as you see in irl films and it does have similar properties
wondering what refraction indices you use for outside, film, and inside
No refractive indices, just a remapped Fresnel multiplied by some noise
ah ok
you can see my attempt above. I'll need to change the alpha to use dot(view, normal) which is listed as the value of cos0 in the related paper. Then I'll need to update the alpha blending to use additive
Is that entire mesh transparent?
Hi, does anybody know if there's a way to make a single channel tileable from the Sample Texture 2D node from Shadergraph?
Afaik you can't use different wrap modes (e.g. clamp/repeat) for each colour channel.
But you could sample with repeat wrap mode, then mask. e.g. by using a Rectangle node into a Vector4 with (1,0,0,0) then multiplying that with the sample result.
I'm going to try to work with this, thanks! π
I got an error when upgrading the project material to URP.Some of them succeed but only shader with "Animmal/" directory failed
Custom shaders can't upgrade automatically. They would need rewriting, or find a replacement asset.
Yes but I'm passing the result of the film straight into the base colour without transparency there iirc
please anyone knows how to read from Texture2DArray in hlsl? or have link please?
How do I apply the replacement asset? I'm trying some shaders to the project with URP.Once I dragged I URPAsset into slot, the material in the scene are all purple and cant be used
Unity has macros that handle this,
For Built-in :
UNITY_DECLARE_TEX2DARRAY(name)
UNITY_SAMPLE_TEX2DARRAY(name, uv3) - uv3 being float3(uv, index)
(see https://docs.unity3d.com/Manual/class-Texture2DArray.html)
For URP & HDRP :
TEXTURE2D_ARRAY(textureName)
SAMPLER(sampler_textureName)
SAMPLE_TEXTURE2D_ARRAY(textureName, samplerName, uv2, index)
How do I use my Compute Shader as a Material on my 2D urp?
I did it after quite some time, using this
output.ditherCoords = mul(UNITY_MATRIX_P, mul(UNITY_MATRIX_V, output.positionWS)) * 0.5 + 0.5;
output.ditherCoords.xy /= output.ditherCoords.w;
output.ditherCoords.xy /= 2;
output.ditherCoords.x *= _PixelW;
output.ditherCoords.y *= _PixelH;
now the dither coordinates stay fixed in place when the camera moves
cool
I still have no clue.Does it mean if there're already some costum shader in the scene.Then I cant use URP?I cant use both of them?
You cannot use URP and the Built-in pipeline together. They are separate pipelines that change how rendering works.
If you have custom shaders that are written for the Built-in pipeline, they won't work in URP. You would need to find a custom shader that is written for URP instead (e.g. on the Unity asset store, or write your own in shader graph)
If you have lots of custom shaders, it may be easier to stick with the Built-in pipeline.
Thx for ur opnion!
Compute Shaders are not attached to materials, only vert/frag shaders are (and surface shaders, graphs, which generate vert/frag behind the scenes)
Instead you dispatch them via a C# script. https://docs.unity3d.com/ScriptReference/ComputeShader.Dispatch.html
Oh I was doing this already, I'm just not sure where that goes, following a tutorial
Checking your link, thank you!
Oh gosh, what's a Kernel..? '^^
i am using it in compute shader and still cant get it to work heres my hlsl code ```hlsl
// declaring
Texture2DArray lightmaps;
SamplerState samplerlightmaps;
// getting the color
float4 lightmapColor = lightmaps.SampleLevel(samplerlightmaps, int3(texPos, 0), 0);
That link isn't really doing much for me!! What do I do after dispatching?
Thats the method you would execute from the compute shader
Or dispatch
It would depend on what you are using the compute shader for. I assume it's writing to a output texture or buffer
I want to have it as my display on my 2D URP
Ah yeah, your renderTexture in your code
As your display ?
As my material for my Canvas
This one's using a.... Um... Shader..? I don't.. Really understand yet!
I mean duh, shader
...I am not sure what it's using '^^
Raw image can take in a render texture directly no?
I don't.. Know!
They're creating the Render Texture in the script, so would probably need to use something like GetComponent<RawImage>().texture = renderTexture;
Might need using UnityEngine.UI at the top
Seems so!
I am sorry if I came off like that. It was not my intention, I'm only expressing how little I know about this~
Then again a mandelbrot seems to be already rendering from the material so not sure what the end goalnis here ?
i got something to work so its probably resolved, my texPos input seems to be the problem
It was made using a.. I don't remember what!! It was not a Compute Shader, though!
I want to use a ComputeShader instead
I feel like you have a normal pixel shader that renders a mandelbrot and a compute shader that does the same
The Mandelbrot's a .shader
I guess they might want to switch because the compute shader could only need to run once.
Could still bake a texture using the vert/frag version if you were to blit with it though
Sorry I'm not really following, but I realised I didn't give this as context yet
I am outputting a texture here, can I just somehow use it on my Canvas texture?
Where would I do this? And how would that help me use it as the Canvas texture?
Ya thank you, still catching up ^^
Would do it in the Start() function you shared earlier
Ohhhh that'd give me the Canvas to use in the code..? Hmmm
It would obtain the RawImage component then set it's texture field.
The "Canvas" itself doesn't have a texture.
You'd probably want to also remove your current Material assigned there, switch to a regular UI one
I feel like you should do some beginner coding tutorials before diving into the world of compute shaders.
I'm fine with code, Unity is the part I don't quite grasp yet
How I can allow things to get passed on n all
On n all?
What is your question?
What does passing things on N all mean to you ?
For example this issue I am having now. I have a ComputeShader, I am able to compute the actual shader, but I don't know how to pass that data onto the Canvas.
To the RawImage
Cyan told you
Get the raw image component, set its texture field as the render texture you have created
Show the code again
Okay, managed to get it to be blue!
The output appears correctly, but it's still blue
That's So interesting that you can just .texture =
1 minute!
You'd want to use float3, not int3
My Unity's Incredibly way too slow when it comes to maximizing it again, probably some Linux related glitchhhh~
I'll try to move the .texture up
It may be a I do changes and then get the reference
already did that after posting code but my texCords that I want to sample behave weirdly as if the range it samples from isnt (width, height), currently debugging if you know about smt like that pls tell
It just freakin takes forever... My code changes shouldn't take 20+ seconds to update, should they..?
restart unity if you havent tried, it helps me when script assemblies take way too long
I've tried! Been the same since 2 days ago unfortunately - it was never fast
(Since I started Unity)
With SampleLevel the coordinates you'd want to sample with would typically be in a 0-1 range.
There is also Load which would work with pixel coords (int3)
Maybe the compute shader is setting the pixels to be transparent (alpha = 0)? Not sure.
Wouldn't the preview show that also, though?
it works thanks
That worked, thank you!!! β€οΈ
So preview defaults to full alpha, noted!!
yes preview has RGB(so alpha is ignored) and then separate channel previews
Guess so yeah. There's an A button to view the alpha channel if required though.
Ohhh I see!! Thank you again!!
Is ComputeShader.Dispatch used for Graphics.blit?
Or do I need it using this approach still?
...Seems I do, still trying to understand how this works...
Not sure what you are referring to
What I'm trying to understand is:
First, the renderTexture is created
Then, the computeShader is assigned the renderTexture and width and height
Then Dispatch does ???
Dispatch executes the compute shader
....Oh!
That makes more sense, thank you! π
I noticed some fields start with a capital letter - is this the norm?
Feels like it could get confusing
by field you mean "Result"?
if its that its just a name @quick cape
you can change it to whatever
Oh yes I know ^^ I'm just wondering if there's any good reason for it to be like that
Or all just preference
Its just the default name of texture in default compute shader not anything special, atleast i think
I'm trying to make a see through shader that makes anything inside a mesh become transparent. I have tried with a Depth Mask, but it also makes things behind the mesh invisible (not only inside), and I tried with stencil and it also affects objects in front of the object. Does anyone have a hint on how to do that properly?
I am getting an error: 'unexpcted token float at line 27 (which is the X)
What can cause an unexpected token float? I can post more of it if that helps
oh you are right there was an opening { missing
thanks π
Does anyone know why RealTime reflection is like this in URP? I have a reflection probe with realtime mode. Then the floor is set to a material with Metalic 1 and smoothness 1. It does show a reflect, but not as expected
@tight phoenix mornin. Did you see Panzer's implementation of a non-physically based thin film shader?
There's no surface film refraction though.
I saw it posted but didnt look too closely at it yet, I was still trying to get my own implimentation going before I started to see what you two achieved
Cool cool, I'll be home in a few
I hit a snag on my end - this guy references a lookup table but doesnt explain what that is or where to get it
Googling it it looks like there are images to sample? but I'm unclear on how to substitute this
this is apparently a look up table, but his code doesnt say or show what HIS table looks like so I have no garuntees
Yeah I noticed that
going to try to just google 'lookup table for XYZ color coordinates' and see if I can find one Iguess???
The CIE 1931 color spaces are the first defined quantitative links between distributions of wavelengths in the electromagnetic visible spectrum, and physiologically perceived colors in human color vision. The mathematical relationships that define these color spaces are essential tools for color management, important when dealing with color inks...
What is "comp" , is it an HLSL compute?
trying to figure out what i should replace lookup[i] with, maybe knowing what comp is will tell me?
is an array which is confusing
"Since we are calculating from physically based equations, color values are not expressed as RGB, as CG rendering requires, but rather as an intensity at a given wavelength. The calculateIntensity() function above takes a parameter of wavelength Ξ» and returns intensity Ir. In order to generate color values, we will sample Ir for various values of Ξ» at each ΞΈ0. We will apply the resulting values of Ir to a lookup table for XYZ color coordinates, and find the average color, which will be returned."
I guess this is like, its returning a value of 510, and we are supposed to know that means green?
like in that other tutorial
oh wait
" // identity of CIE x + y + z = 1, therefore xOut = x / (x + y + z)"
he names it CIE, so it must be this thing after all
Having read the great post on glass from Mario I stumbeled across those papers on iridescence. Eventually I had an optics book on my lap, a sheet with a fe...
he links this at the bottom
and people talking about CIE here, maybe ill find it here
I did not find the lookup table there
but at least I know thats what I need to find
is it going to be a file? a picture? something else entirely like a formula?
The 'Completely Painless Programmer's Guide to XYZ, RGB' was written in the hope that it might be of use to technically savvy people who know a whole lot about the code and the mathematics that goes into making an image editing program, but perhaps not so much about color spaces and ICC profiles.
in here maybe π
https://www.color.org/XYZprofiles.xalter maybe these are look up tables???
The International Color Consortium....promoting and encouraging the standardization of an open color management system
oh here we go maybe
okay it might just be a matrix(3x3)
π€ now I gotta find out what 'comp' is
comparison maybe? compute maybe?
I assume that's just the same as lookup[i+n]?
oh btw I think I fucked up the last custom function definition when I was looking at it this morning
The corrected should be in the shadergraph asset I provided earlier
I am not skilled enough to make assumptions, I want to do exactly what he has because I know definitively it works
when i have it working then ill go back through to look at alternatives
damn he doesnt say what 'comp' is anywhere
its gotta be a common hlsl thing like 'dot' maybe?
got a link?
if this is what you are refering to
comp is near the bottom
??
mine doesnt try to download any files
at the top he calls this a 'Maya Texture Animation'
so maybe comp is a maya function?
I'm not sure, I think it might be an index offset
since all three provide the same lookup and then each one takes a different index
especially since it's a colour table
Well until I find out what comp is
im stuck
I dont even know if lookup IS a mateix3x3
im just assuming it is because it was the closetst thing I found on his linked pages
I know it's an assumption but try
float comp(vec3 colour, int i) {
if (i == 0) {
return colour.x;
} else if (i == 1) {
return colour.y;
} else if (i == 2) {
return colour.z;
}
}```
Or whatever it is
im pretty sure this is it
it says compute, its for computing XYZ to RGB, which is what he says he's doing
so all that hot garbage on the left must be the comp function??
ill google for a code implimentation of that
maybe somewhere in here?
specifically this
ill try to write comp to be this
that's an interesting colour space
Wonder how that'd look with this https://www.alanzucconi.com/2016/01/06/colour-interpolation/
type mismatch on line 13 π€
what does 100 dot multiply mean?
dot product of itself and that multiply or something?
100.0f * (tmp * mat)
things before and after the decimal point are optional so you can do .1 to do 0.1f or 1. to do 1.0f
nope still type mismatch on that line
check the return type
return type is a float
oh okay
type is STILL mismatch
im returning float3 but its type mismatch
vec3 tmp=vec3(
(c.r>.04045)?pow((c.r+.055)/1.055,2.4):c.r/12.92,
(c.g>.04045)?pow((c.g+.055)/1.055,2.4):c.g/12.92,
(c.b>.04045)?pow((c.b+.055)/1.055,2.4):c.b/12.92
);
mat3 mat=mat3(
.4124,.3576,.1805,
.2126,.7152,.0722,
.0193,.1192,.9505
);
return 100.*(tmp*mat);
}```
the original code
{
float3 tmp = float3(
(c.r>.04045)?pow((c.r+.055)/1.055,2.4):c.r/12.92,
(c.g>.04045)?pow((c.g+.055)/1.055,2.4):c.g/12.92,
(c.b>.04045)?pow((c.b+.055)/1.055,2.4):c.b/12.92
);
float3x3 mat = float3x3(
.4124,.3576,.1805,
.2126,.7152,.0722,
.0193,.1192,.9505
);
return 100.00*(tmp*mat);
}```
my version adapted to hlsl
hm i should change c.r g b to c. x y z
but iunno if thats the problem
I think those are identical accessors. I wonder if the float3x3 has some sort of different operation with mul
maybe something here?
looks like they're doing roughly the same thing here
ill try copying this one?
oh try swap mat and tmp?
I don't think matrix multiplications with vectors are commutative
is this glsl or hlsl?
iunno, whatever shadergraph is
net says its HLSL
try changing the return type to float4?
sure I can try that
no change, still type mismatch
" mul(x,y) as opposed to using the asterisk operator" will do
heyy that worked no type mismatch
yay
now the NEXT problem
are you able to check the Unity.cginc to see how mul is defined?
his comp uses two inputs, this one doesnt
how are xyz used?
not a clue
im a parrot, not a human being, I have no comprehension at all what I am doing, I am just trying to copy it directly
used like this I guess???
colour values
So the lookup[i] I think is returning the colour, and then 0, 1, 2 refer to either x, y, or z
idk if it does something else internally since we can't check that
:C
maybe I can find this guy on twitter and just ask him directly
not enough info to find him, too many people with the same name
i guess i have to cut my losses and stop again
This is what that site is using to render stuff https://renderman.pixar.com/resources/RenderMan_20/sloApi.html
since it cannot be completed without comp
kk
Ill google how to do this thing
composite maybe??
rip not this
boom found it
reading this now
well it says what comp is, but doesnt give the underlying code either
i cant find an answer on google of what the definition of renderman's 'comp' function is
feels like another dead end
messaged the renderman twitter π€·ββοΈ for now ill go look at yours and panzer's implimentations now
how far I got before comp stopped me
Good work
Seems it's just an index accessor
So you can replace that with lookup[I].X for example
like so?
Yup
now it has no idea what 'color' is
I know colors can be vector3s
but I dont understand the syntax beyond the =
why is a name in quotes there?
oh great going to have to find out wtf adjustHSV does next too
oh huh it knows what adjustHSV is
it doesnt know what hueShift and saturation are though, ill just pass in some values for that
nope it doesnt know what adjustHSV was
it just wanted to complain about saturation and hueshift first
https://github.com/greggman/imageutils/blob/master/dist/imageutils.js random person here has a definitino for adjustHSV
highly doubt its the correct function though
screw it lets pretend its just HSV adjustments and ignore that all together
Won't lie to you, this syntax is bizarre
from what I understand tho "color" there is just a float3
and trying to fix the red errors
problems on 56 and 51 letssse here
its not happy about this being a float???
that function returns a float though
unexpected token float
oh lambda is missing a ;
it thinks this is an infinite loop π€
why is this an infinite loop?
it should clearly stop after i becomes greater than 81
(dont ask me why 81)
I also tried this but it still said infinite loop
apparently the loop was not infinite
it was just too big
81 was too big
2 is not too big
but now gotta debug that
well, it makes -a- color
its not what I was hoping for, but its something
hmm
I think NN is wrong
because eta0 and 1 never get used
and in the code, nn turns into eta0 stuff like
float costheta0 = Ll.Nn;
ll nn???
iunno what nn is supposed to be
I dont like he's passing these out but never uses them
that makes me fear there is code that I dont even have access to that is critical
nn, normalized normal?
nothing changes no matter what I send into Nn
nothing changes any time I change n0 1 2
I think this entire attempt is another bust
dead end does nothing
not happy
I want thin film intereference
but im not skilled enough
getting agitated, going to go have lunch
does anyone have any guides, tips etc for moving from shader graph to shader code? I tried shader code a few days ago but it seems a lot more primitive and guides are scarce. A lot of nice things you can do in shader graph (such as generating perlin noise or getting view direction uv's) seem to be lacking or really confusing to do in shader code. I am specifically trying to learn hlsl but cg guides also work since they seem simular enough.
As someone who has very little shader background, I started in trying to learn HLSL but its exactly like you said, extremely primitive and guides are scarce.
Is this an X/Y problem? What can shadergraph not do that you think switching to HLSL will solve?
idk. I mainly wanna learn to write shader code because it seems fun and can be helpfull if I ever decide to try something outside unity. But at this point its getting a bit frustrating
ive learned more about HLSL by doing shadergraph than I ever did from trying to learn HLSL, iunno if that helps you though
shadergraph has the 'Custom Expression' node that accepts HLSL
so you can learn it as you need it, instead of needing to learn the entire thing all at once
hmm it shows it working on the preview, but wont appear on the mesh
π€
hmm replacing main light direction with a random vector
makes it do a thing π€ but not the right thing
I found a usefull video on how to make noise for shaders. Its for gdot and some things may be slightly different sntax wise but its really usefull
(forgot to add the vid) https://youtu.be/ybbJz6C9YYA
Oh that type of noise is natively already in shadergraph im pretty sure
yeah but not in hlsl. Might go back to using the fraph soon tho since it seems easier
Ah yes, I forgot we had those already. For a perlin 2D, what's the big deal if it's not in HLSL ?
Although, if you need 3D (or even mode dimensional noises), you'll have to for for a custom function anyway
https://github.com/JimmyCushnie/Noisy-Nodes
this person has some great 3d noise functions for SG
I need perlin noise for a specific shader. Plus might be usefull for someone
he's got perlin there, as well as 3d perlin
actually on the note of Perlin, I have my own perlin node that can do non-circular distances, lemme find that, posted it here before
whoops I meant Voronoi
different type of noise
I also have some there : https://github.com/RemyUnity/sg-node-library
Also from the webgl noise source ^^
voronoi that can be non circular, and the second one maps UV coordinates into each cell π€
noice, saving these
how can i render 2 diffrent things with diffrent colors in 1 camera like layer 1 white layer 2 black
that sounds like you're asking how to composite the outputs of two cameras into one?
ye
Im following the tutorial.This is what I write in surface shader.But the video did in the URP is like.Anyone who knows why?
https://www.youtube.com/watch?v=bbnVpPiQ_rU maybe this? I dont actually know, just found it on google searching for 'unity composite two camera outputs'
what exactly is different between the two that you want? the color green?
im making a zip of the nodes now
unfortunatly its not what i was searching for but thanks
I figured it out.I can choose density for HDR
oh wow the result is way better using this other color table
I think this time they are the same?Im not sure is there any other setting need to be modified
Looks the same to me π
How did you make a unity package file of all the relevent assets for yours? Ive never exported before
Thx!
dragon not included, you have your own dragon π²
Ive seen that dragon model around before but I couldnt find its source/download, like Suzanne or the default teapot easy to find, dragon not so
Taking lunch now for real now that I have the thin film working
Hello, what is generally preferrable from performance view? More draw calls or combining multiple shaders into a single one and diverging shader logic based on a branch?
How can I make a shader like this in HLSL?
You see the shadow reflects itself upon the beams
And it looks like you can actually look down and it looks like a bottomless pit
Please ping me here if someone can give me an answer. Thanks π
Omgomgomgomg I got my fiiiirst eeeeverrr ComputeShader drawing what I want it to draw!!!!! Even using a ComputeBuffer!!
So excited π
ride my child?
:3 um
I have a small issue~~
Can I update my ComputeBuffered in structs inside of my ComputeShader?
They don't seem to update
I'm trying to modify them like this
Any idea why the .pos is back to original on the next render?
Oooooh, thank you!!
Omg the example I was using as guidance did that and I thought I was optimizing it!!! :3
It's still not working, hmmm
Omg
Well of course it doesn't work, I am multiplying by an unitialized value, which I assume is 0!!
Omg omg omg IT WORKSSSS
π
Well it depends.
I mean, I got to thinking that there could be two ways to interpret your "Works EXACTLY like the standard shader [except]" requirement.
If you want, you can still make custom shaders using Surface Shaders...but they won't have all the bells and whistles of the standard shader...they're customized to the material's needs, no fancy inspectors and such.
So if you want a clone of the standard shader, you'd have to do what we're saying and clone that source and customize it for a general-case uber shader using your new reflection method.
BUT
If you just want "standard lighting, with non-standard reflections" you can use custom surface shaders AND CHECK THEIR SOURCE. Surface shaders are basically code generators that generate vert/frag shaders. So you can inspect the source and then find out where reflections are applied and customize that. It won't look like a standard shader it will look like a custom shader using "standard lighting" if that makes sense.
Got time to come back to this now, looking it over its sorta working but there are peculiarities π€
comparing it to physically based diagrams, the 'thickness' variable seems to be somehow opposite?
using N values eqivalent to IOR of Air, Oil, Water does not produce a gradient that resembles what the math says that should produce π€
the thicker thickness is in the shader, the more bands it adds, and the more vivid it becomes, but according to diagrams that should be the opposite
wdym?
ooh I'm def gonna have to add noise to vary the bubble thickness
the value called thickness, as it increases, it does the opposite of that graph of what should happen when thickness increases
when thickness is 0, it doesnt look like the top, it looks like the bottom
Which implementation are you looking at where it's wrong?
uhh my implimentation I dont have any other?
This one
ah ok
maybe I am misunderstanding how its suppsed to work?
the colors are also obviously not right
but im not sure how to fix that, I think it must be the lookup table values are wrong
it keep having this bland-ish grey tone to it
your thickness there is strange
strange how?
besides the fact that obviously it doesnt work the way it should
all uses of thickness, directly from his code
Normally it should be in the hundreds to start showing any difference. It's measured in nanometres afterall
something like this is the expected output?
whatever he's doing it works for him
some values exposed in his thing
I will try these values and then see if I can get his result
yeah its just a washed out grey-tan
stahp for the lov of gawd
?
is that that file you said his kept downloading?
I dont get that π€·ββοΈ
I'm not
ah ok
throwing in a rando cube map still its way washed out
so I dont think its transparency is the problem
I can just arbitrarily crank the saturation
but that isnt physically realistic at all
I shouldnt have to post proccess it if its working right
right
I dont know what NN is still
this is the only thing I have no idea what it is, and thus its possible im giving it the wrong thing here
and these dont even get used at all even though he outputs them
its definitely not the vector normal normalized
that looks completely wrong
lol wait what, why 81
fuck if I know, it doent work higher than 4 for me
im starting to get agitated that it SHOULD be working perfectly, and it isnt
those are used on the same line as our first resource, to calculate cos0
so it's normal and view direction
thats not what he's doing at all
his is the normalized LIGHT direction, and the normal of the surface
view direction is not anywhere involved at all
no where in his code does the concept of view direction come up
replacing light with view direction does do the fresnel again, but this means light is not calculated in this, and it is in his, so no matter what this can NEVER be right
because his is right and his doesnt do this, so this cannot be right
also thickness is still fucked
maybe we should start over AGAIN back on the first one, but this time do it all in code instead of trying to convert to nodes
I have that link
but its just mathematics I dont understand
theres no code in there so it may as well be hieroglyphics
its terribly frustrating and agitating knowing that the answer is right there, in a language I cannot read
oh dear god so much code
this just looks like color table lookup stuff
none of this screams 'thin film intereference' at me
so I dont know what im supposed to take away from it
hm nanometers are mentioned in SPECTRUM_TO_XYZ
yeah it's referring to the width of the wavelength
its too difficult, im too stupid to solve it
make it double sided
I just keep running into dead end after dead end
look how far you've come
whut
and the dead end is that I don't know enough, its always me π₯
make the material double sided if you want it to look like a bubble
render face both?
in shader graph it's in the inspector iirc
just make sure to flip the normal when it's a back face
I honestly dont feel like ive come anywhere at all.
I have nothing to show for all my hard work, I have a glorified color gradient (a wrong one that has nothing to do with real life) mapped over a fresnel. I could have done that with two nodes
ah good point
darn someone remind me how that's done
im now in mental health crisis again because I stupidly had expectation, hopes, dreams, a desire for success that has once again failed because I am a fucking stupid failure
also can i just say that while motivating things from physical principles is nice, you don't need everything to be analytic or accurately represent the physical system you're modelling, it just needs to look similar enough
heading out now
I'm going for physically based
fair
same
my head is clear but im not going back to shaders today, my work hours are over, its the only way to maintain my sanity
that's fair. I'll keep at it, I think I'm almost there
From http://labman.phys.utk.edu/phys136core/modules/m9/Thin films.html
2 n_oil t cosΞΈt = (m+Β½)Ξ», m = 0,1,2,...,
for constructive interference. (t is the thickness, ΞΈt the transmitted angle (from Snell's law), n_oil the refractive index in the thin film, and Ξ» the wavelength)
so then,
m = (2 n_oil t cosΞΈt)/Ξ» - Β½
and so we can return a function where when m is close to or equal to an integer, that color is bright, and otherwise, it's dark.
Now what function do we choose? I would suggest something like lerp(0.5, cos(pi m)^2, 1/sqrt(1 + m^2)); the cosine gives us the oscillations we want, while as the thickness goes to infinity, the oscillations should get averaged out because while 500nm might see a peak, 501nm might see no light, and so integrating over the entire region of the spectrum that corresponds to green, we should see no variation. (This isn't the only choice for this function but it should work fine and should approximate the real falloff at large thicknesses)
The result:
first half of the graph
second half
Not sure if HLSL stuff is ok to post here, but can anyone help me with this day night shader? trying to take the blend value and multiply it by time till it reaches the end(@1 but at time of 24hrs) then loop back.
You probably want a procedural skybox, not a fixed-function shader.
https://en.wikibooks.org/wiki/Cg_Programming/Unity/Skyboxes
That's one environment cube. But you could do two and blend them in the vert/frag functions.
It is also worth looking into Unity's procedural skybox code from their "default" procedural shader here:
https://github.com/TwoTailsGames/Unity-Built-in-Shaders/blob/master/DefaultResourcesExtra/Skybox-Procedural.shader (that's a bit dated, but...)
ty, appreciate the tools
You can get Unity's built-in shaders from the download archive: https://unity3d.com/get-unity/download/archive
https://www.youtube.com/watch?v=yJ0NRr-DdYU&ab_channel=GabrielAguiarProd.
https://www.youtube.com/watch?v=894TZuJralo&ab_channel=NickCarver
Unity Shader Graph - Waterfall and Ripples Tutorial
In this Shader Graph tutorial we are going to see the steps I took to create this very stylized Waterfall with Ripples. It's one shader for the waterfall and another for the ripples. And we also need some meshes and a simple texture for the ripples.
I MADE A NEW WATERFALL BUT IT'S TOXIC: htt...
A breakdown of the various elements that make up this effect I've created for Waycaster in Unity.
Follow me and the game's development:
https://twitter.com/NickDCarver
https://twitter.com/WaycasterGame
Useful Links:
Stylized VFX in Rime: https://simonschreibt.de/gat/stylized-vfx-in-rime/
Zelda Water Shader: https://polycount.com/discussion/...
Anybody know where I can ask questions relating to CustomRP ? π
is it possible to have worldspace in compute shader?
Hello, is there any possibility to create Stencil Buffer in Shader graph? Thank you π
What is going on with my shader math!?
Context: I spawned a bunch of "agents" from the middle of the screen
Anytime they leave the bounds of the screen, they teleport to width/2.0, height/2.0
Aka back to middle
But SOME of them screw up and teleport to random locations on the axis
They listen to 1 of the axis, but the other is... Random..?
It's never both of them being wrong, only one
[numthreads(8,8,1)]
void Update(uint3 id : SV_DispatchThreadID)
{
Agent agent = agents[id.x];
float2 direction = getDir(agent.angle);
float2 newPos = agent.pos + direction * agent.speed * deltaTime;
// float random = hash(time * direction.x * newPos.y * height);
if(newPos.x < 0 || newPos.x >= width || newPos.y < 0 || newPos.y >= height)
{
// agent.angle = scaleToRange01(random) * 2 * 3.1415;
// direction = getDir(agent.angle);
// newPos = agent.pos + direction * agent.speed * deltaTime;
newPos = float2(width/2.0, height/2.0);
}
agent.pos = newPos;
Result[int2(agent.pos.x, agent.pos.y)] = 1;
// float x = id.x / width;
// float y = id.y / height;
// Result[id.xy] = float4(sin(x), cos(x), tan(x + y), 1);
agents[id.x] = agent;
}
But ya, my math is incosistent :c
I don't understand, it seems random
Sure. Why not?
Shadergraph does not expose Stencil operations currently.
If you're in URP, the RenderObjects feature can be used to override stencil values when rendering a whole Layer of objects.
But for a few specific objects (especially if they need different stencil values), it's better to use shader code. Or convert the graph to code (via "View Generated Code" button in inspector on shadergraph asset), copy and save in assets and edit the Stencil block into it.
Weird.
IDK maybe some optimization thing.
BUT, when in doubt, change something. I observe that you can pre-compute width/2.0 and height/2.0 and not have to do the division for each agent each time. So maybe try that. You could basically pass in uniform ints for it, and just set newPos = int2(centerX, CenterY).
Or maybe try doing something like Agent[id.x].pos = blah rather than having the interim variable "agent", and let the optimizer deal with the code.
You could also move the if after the first setting of agent.pos (yes, set it possibly twice).
Could it be that you're accessing agents that are not initialized? What do you input on the C# side?
If you access something that's not initialized it could potentially be random numbersπ€
The center values, though, should still be the same. Assuming height and width are initialized (and per the pic they appear to be). So why would one component be off-center randomly?
It could also be that the compute buffer and structured buffer don't align one to one
Then the data would get mixed up. You think you read the correct property of one element but you're actually reading another property of a different element.
Seeing how they have 8 8 1 threads and only use one axis(id.x) kinda seems sus.
That's a good point, there should be a check to see if id.x is out of range if the buffer size isn't a direct multiple of 8 x 8.
Oh ya, thank you!
I have a question on shader execution order. Let's say I dispatch a compute shader to render something into a render texture. I know that it doesn't execute immediately, but is there a guaranteed time it will get executed? Is it gonna be somewhere before the next frame starts? Is there some way to know if the compute shader finished it's processing without getting the data back on the GPU?
And another question is what's the common workflow with rendering to a texture and keeping the data serialized? I remember trying a regular Texture2D asset, but I think there were some problems with writing to it..?π€
On the other hand RenderTexture keeps on resetting the data at different times(mainly on assembly reload). Can I serialize a RenderTexture without it resetting?
Probably read/write permissions on the cpu side do not correspond to those in the shader.π€
That's really odd because I was using them the same way previously..
Could there be a name conflict between the two kernels?
They're using the same field, but I'm setting it the same for both kernels
Maybe? you're accessing kernel 1(the second kernel).
Can't say anything without seeing the code. Both the shader and the C# one
Check #854851968446365696 on how to share code.
Hey, I have problem.
I am new and i don`t know where is Mask Map in Material.
Some questions on shader execution order
What do you refer to by "mask map"?
If you look at the "shader" dropdown, they use a completely different shader.
a material is just an interface for the parameters of the shader
how i can change to this because I don`t see it in the list.
For starters you'll need to switch to HDRP, since it's an HDRP shader
The shader will be added automatically as it's part of the package
check the pinned messages in #archived-hdrp
thx
anyone know how i can get a int3 from my compute shader to my script?
the docs dont make a lot of sense
gotta use a compute buffer or a render texture.
There's an example with a texture there
ok so im trying to count the number of pixels that are each of 3 colors
are you saying it would be faster to convert the Rendertexture to a Texture2d and cpu evaluate each pixel?
No.
I'm saying that you should use a compute buffer to get that data
You probably want to use something like an append buffer
Add something(doesn't really matter what) to an append buffer each time you hit a pixel of the desired color. Then on the C# side copy the buffer count and get the data(the count).
public void CheckScores(){
splatBuffer = new ComputeBuffer(3, sizeof(int));
splatCompute.SetBuffer(1, "TeamScores", splatBuffer);
splatCompute.SetInts("TeamScores", new int[3] { 0, 0, 0 });
splatCompute.Dispatch(1, size / 8, size / 8,1);
int[] scores = new int[3];
splatBuffer.GetData(scores);
Debug.Log("Alpha: " + scores[0] + " Beta: " + scores[1] + " Neutral: " + scores[2]);
splatBuffer.Release();
}
ok so i got this but it returns 0,0,0 every time
do i have to wait for the splatCompute.Dispatch to complete?
yeah I don't think there's a guarantee it will have completed right away
you'd have to use a GraphicsFence to synchronize I believe:
https://docs.unity3d.com/ScriptReference/Rendering.GraphicsFence.html
This is how you can tell in CPUI world that it's done:
https://docs.unity3d.com/ScriptReference/Rendering.GraphicsFence-passed.html
But I'm not totally sure how to make your shader set that π€
i set a 10 second wait just for testing and still got nothing, so either my shadercode or the splatbuffer code it wrong
[numthreads(8,8,1)]
void GetScores (uint3 id : SV_DispatchThreadID)
{
float4 color = InkTexture[int2(id.x, id.y)];
if (all(color == AlphaColor)) {
TeamScores[0] += 1;
}
else if (all(color == BetaColor)) {
TeamScores[1] += 1;
}
else {
TeamScores[2] += 1;
}
}
i though this seemed hella wrong by anything else ive tried gives an error
so much unecessary repetition π΅βπ«
float4 color = InkTexture[int2(id.x, id.y)];
if (all(color == AlphaColor)) {
TeamScores[0] += 1;
}
else if (all(color == BetaColor)) {
TeamScores[1] += 1;
}
else {
TeamScores[2] += 1;
}```
tried that, i get this error?
``if(all(color == AlphaColor))` apparently? @rotund tundra
Actually, getting the data would force the execution immediately
does it? That might explain why it seems to work in the one project I do something like that
Yeah, it freezes the main thread until the data is ready. There's also an async version where you can wait for the results.
ok thats much cleaner now
That wouldn't work. In fact it should throw errors at compilation.
different threads can't write into the same buffer index
You'll need to use an append buffer.
As I mentioned previously
only this one needs to write to the buffer?
yeah this isnn't going to work well
the += is actually three operations:
- read current value
- increment it
- write it back
If two different threads read the value simultaneously (and they will) and both increment by one and write it back, you won't get +2, you'll only get +1
oh
I imagine this is a splatoon scoring thing?
yes
The only way this can work is by adding to an append buffer. You have an option to either have 3 buffers for each append buffer. Then get their count on the C# side. Or have 1 buffer and fill it with different ints per channel. In this case you'll need to loop the resulting array on the cpu and check each element in the array.
I think the 3 buffers version should be faster, despite the additional read overhead. But you should probably test if performance there is critical
i only need to call it once, so even if it takes like 3 seconds thats fine
In this case, why not use the cpu?
I'm sure it will be able to handle quite a lot over 3 sec time
wait, so converting to the Texture2d and looping would be fine here?
Sure. If you can spare 3 sec of time, why not.
You'll need to make it async of course, but other than that, it's fine
Why do you even need to convert it?
you should be able to get the pixels regardless
how do i read colours from a renderTexture?
theres no endpoints for pixel data
uhh, am i missing somthing?
Ah, I guess you can create a Texture2D from the render texture native pointer
https://docs.unity3d.com/ScriptReference/Texture2D.CreateExternalTexture.html
Get the native pointer of the color buffer and use that in the Texture2D constructor.
https://docs.unity3d.com/ScriptReference/RenderBuffer.GetNativeRenderBufferPtr.html
code
Texture2D test2 = Texture2D.CreateExternalTexture(size, size, TextureFormat.RGBAFloat, false, false, splatMapRenderTexture.GetNativeTexturePtr());
error
What throws the error?
no clue? thats it
Also, you need to get the pointer to the color buffer, not the whole render texture
What line I mean. Is there no stacktrace?
its not cropped, thats it
same error
What's your render texture format?
ARGBFloat
Share the code with the color buffer
Texture2D test2 = Texture2D.CreateExternalTexture(size, size, TextureFormat.RGBAFloat, false, false, splatMapRenderTexture.colorBuffer.GetNativeRenderBufferPtr());
Okay, that's different to what you use for the texture2D
they dont share peramaters
wdym?
TextureFormat and RenderTextureFormat dont have the same options
There's a similar format for texture2D though.
TextureFormat.ARGB32
Hmm. Maybe not.
i did
Hmm
Apparently there's a simpler way
one of the answers here
https://answers.unity.com/questions/27968/getpixels-of-rendertexture.html
Hmmm... That might come handy when I need to serialize the render texture...
Lol, Yeah. You Should probably unbind it right away
?
Texture2D toTexture2D(RenderTexture rTex)
{
Texture2D tex = new Texture2D(size, size, TextureFormat.ARGB32, false);
Camera.main.targetTexture = rTex;
RenderTexture.active = rTex;
Camera.main.Render();
tex.ReadPixels(new Rect(0,0,1920,1080), 0, 0);
Camera.main.targetTexture = null;
RenderTexture.active = null;
return tex;
}
heres the code
I don't think you need to call Camera.main.Render
nor assign the camera target texture
Basically, remove all the lines related to Camera
returns a blank texture
Texture2D toTexture2D(RenderTexture rTex)
{
Texture2D tex = new Texture2D(size, size, TextureFormat.ARGB32, false);
//Camera.main.targetTexture = rTex;
RenderTexture.active = rTex;
//Camera.main.Render();
tex.ReadPixels(new Rect(0,0,1920,1080), 0, 0);
//Camera.main.targetTexture = null;
RenderTexture.active = null;
return tex;
}
hmm
Hii, maybe someone can help me, I have a mask texture that I want to flip (reflect) each individual "object" in it on it's own axis, that is, not flip the entire mask, but each masked area by it's own axis, anyone ever done something like this ?
Hey I figured it out!
I'm having trouble generating random numbers in my computeshader!!
I'm trying to use a hash function and input it things that shouldn't repeat
Like Time.fixedTime
But lots of numbers end up being identical
Maybe share your code and explain what exactly is identical.
Thank you, yes, I really should~
For example this Very obvious pattern
I'm using my hash function to determine the randomness
It actually seems fine if I just render the random pixels
But patterns do form
I've managed to change the color of my texture slightly using a hue node, but I rather do it with a gradient node.
But I'm stuck how to connect this in combination with the texture.
How do I do this the correct way?
Hmmm....
Is that a render texture, or no?
ComputeShader
Wait, oh, that issue
That issue was caused by not doing renderTexture.enableRandomWrite = true;
If you're sampling a texture that is a gradient, you don't use the gradient node. That node is for a mathematical gradient, not a texture-based gradient.
To sample a texture that is a gradient, you "just" use the regular texture sampler, with the x value of the UV set to a value from 0 to 1 representing the % of the way through the gradient. Set the Y value to something inside the height, not the very edge. Like maybe 0.5
If you want to use the gradient node, the value is from 0 to 1 for the gradient lookup and -180 to 180 in degrees and is -Pi to Pi in radians for the hue adjustment into the hue node.
But IDK what you mean by "change the color of my texture (with a gradient)". Change it how? Try a multiply. Or if you need to see the hue calc, check here: https://docs.unity3d.com/Packages/com.unity.shadergraph@14.0/manual/Hue-Node.html
Has anyone seen this issue with Shader Graph? The cube discolors as the brightness fluctuates but only in Scene view. It works correctly in Game view. The video was recorded when working in Unity 2021.3.7 LTS:
https://youtu.be/rOG8BRiTgxg
What's weird, is that since you assigned a float1 to a float3 you should get the same value in ALL components. Yet you didn't in scene view. But you did in game view.
@quick cape had an issue where vector components weren't set properly, but IDK what the deal was, and if it was fixed or not. And it wasn't for a color, it was for a location. But still, weird-component settings.
Can't tell if this is related or not.
I believe my issue you're referring to was the lack of Alpha in preview - it showed as full opacity, but in game it had 0 alpha!
It was this one. float components not doing what was expected. Not even saying it was game-view vs scene-view. Nor that you were using SG.
But they both have "weird component" things going on.
this still returns a blank texture, unfortunately
It did work for me. Share your code.
Texture2D test2 = new Texture2D(size, size, TextureFormat.ARGB32, false);
Graphics.CopyTexture(splatMapRenderTexture, test2 );
Okay, how do you test it out?
uhh, i ran the code after messing with the rendertexture?
I mean, how do you know that it's blank?
Also, make sure that both the textures have the same config, like the format and mipmaps count and what not.
Make sure there are no errors thrown.
Or warnings
Actually, I didn't check if the texture data is available on the CPU right away, but the new textures renders properly.π€
wtf, i put a debug.log and it crashed unity
Lol. Make sure that the texture formats match.
they do
Here's my code
public void GenerateDefault()
{
CachedRT = Generate(defaultParams);
defaultTexture = new Texture2D(defaultParams.Resolution, defaultParams.Resolution);
defaultTexture.wrapMode = TextureWrapMode.Clamp;
defaultTexture.name = CachedRT.name;
Graphics.CopyTexture(CachedRT, 0, 0, DefaultTexture, 0, 0);
}
CachedRT is the render texture
I create it like that:
sourceTex = new RenderTexture(heightmapParams.Resolution, heightmapParams.Resolution, 0);
sourceTex.enableRandomWrite = true;
sourceTex.name = $"noise_{heightmapParams.Resolution}x{heightmapParams.Resolution}";
Try serializing both the render texture and the Texture2D and checking them in the inspector after running the code.
hmm, ok its reading, but the color data is getting changed somewhere
Just tried printing some pixels right after copying and it seems to output the correct data
for(int i = 0; i < colors.Length; i++){
if(colors[i] == gameManager.AlphaTeam){
alphaScore++;
}
else if(colors[i] == gameManager.BetaTeam){
betaScore++;
}
else{
noScore++;
}
for whatever reason the color in the array dont match the source colors that im comparing them to
Where do you get the source colors from?
gameManager.BetaTeam and gameManager.AlphaTeam are sent to the compute shader as float4s
they are the source colors
Hmmm...
Actually...
It seems like I'm getting the same value for all the pixels lol
Hmm
It seems like the CPU side data is not updated. Hmm
would adding a delay on the check work?
wait
oh dang
i just realised i didnt .Apply() the texture
but it still didnt work
ah
I tried the yesterday method again and it workedπ²
public async void GenerateDefault()
{
CachedRT = await GenerateAsync(defaultParams);
RenderTexture.active = CachedRT;
defaultTexture = new Texture2D(defaultParams.Resolution, defaultParams.Resolution, TextureFormat.ARGB32, false);
defaultTexture.wrapMode = TextureWrapMode.Clamp;
defaultTexture.name = CachedRT.name;
defaultTexture.ReadPixels(new Rect(0, 0, defaultParams.Resolution, defaultParams.Resolution), 0, 0, false);
defaultTexture.Apply();
var colors = DefaultTexture.GetPixels(0, 0, 50, 50, 0);
for (int y = 0; y < 20; y++)
{
for (int x = 0; x < 20; x++)
{
Debug.Log($"pixel ({x}, {y}): {colors[y * 50 + x]}");
}
}
RenderTexture.active = null;
}
Weird shit.
Aaah. That makes sense.
I only tested the GPU side yesterday and I didn't Apply the texture, so on the gpu side it was not updating. I tested the cpu side and the cpu side seems to copy properly even without Apply
So that's it I guess. That's how you get a render texture data back from GPU to CPU.
Basically these 3 lines:
RenderTexture.active = CachedRT;
defaultTexture.ReadPixels(new Rect(0, 0, defaultParams.Resolution, defaultParams.Resolution), 0, 0, false);
var colors = DefaultTexture.GetPixels(0, 0, 50, 50, 0);
what is defaultParams?
It's just some custom class with parameters. You can ignore it.
I only get the resolution to use for width and height.
Rect(x, y, width, height);
Share your code
public void CheckScores(){
int alphaScore = 0; int betaScore = 0; int noScore = 0;
scoresReadTexture = new Texture2D(size, size, TextureFormat.ARGB32, false);
//Graphics.CopyTexture(splatMapRenderTexture, 0,0, scoresReadTexture, 0,0 );
RenderTexture.active = splatMapRenderTexture;
scoresReadTexture.ReadPixels(new Rect(0, 0, size, size), 0, 0, false);
Color[] colors = scoresReadTexture.GetPixels(0, 0, size, size, 0);
for(int i = 0; i < colors.Length; i++){
if(colors[i] == gameManager.AlphaTeam){ alphaScore++; }
else if(colors[i] == gameManager.BetaTeam){ betaScore++; }
else{ noScore++; }
}
//convert to percentages
float alphaPercent = (float)alphaScore / (float)colors.Length;
float betaPercent = (float)betaScore / (float)colors.Length;
float noPercent = (float)noScore / (float)colors.Length;
Debug.Log($"Alpha: {alphaPercent * 100}% Beta: {betaPercent * 100}% No: {noPercent * 100}%");
}
I don't think direct comparison would work
Try printing some of the pixels to make sure that you actually get some values that makes sense
now its just white
Is that from printing?
?
How do you know that it's white?
i put it in inspector
Oh, you actually need to Apply if you want the gpu side to update.
Add the Apply for the time of testing I guess.
Before GetPixels
ok its got the image now
Okay, so it is working
the Graphics.CopyTexture also did this
ok
If you print the values in the console, you'll see that
but before i added the Debug.Log it took less than a second
Ah, I guess the resolution is big?
2048x2048
Are you looping through the whole texture?
yes
lol
thats why i was using computeshaders
4,194,304 iterations on the cpu is not a joke
its only at 5% util
Share the code. What exactly do you do in the loop?
int alphaScore = 0; int betaScore = 0; int noScore = 0;
scoresReadTexture = new Texture2D(size, size, TextureFormat.ARGB32, false);
RenderTexture.active = splatMapRenderTexture;
scoresReadTexture.ReadPixels(new Rect(0, 0, size, size), 0, 0, false);
scoresReadTexture.Apply();
Color[] colors = scoresReadTexture.GetPixels(0, 0, size, size, 0);
for(int i = 0; i < colors.Length; i++){
Debug.Log(colors[i]);
if(colors[i] == gameManager.AlphaTeam){ alphaScore++; }
else if(colors[i] == gameManager.BetaTeam){ betaScore++; }
else{ noScore++; }
}
//convert to percentages
float alphaPercent = (float)alphaScore / (float)colors.Length;
float betaPercent = (float)betaScore / (float)colors.Length;
float noPercent = (float)noScore / (float)colors.Length;
Debug.Log($"Alpha: {alphaPercent * 100}% Beta: {betaPercent * 100}% No: {noPercent * 100}%");
}
It's not a joke, but even the cpu will get through it in 3 sec.
For starters, just print one line, not the whole thing.
We should confirm that the cpu side data is indeed what we expect
wdym one line?
one line of the texture.
for(int i = 0; i < size; i++)
It should be the bottom of the texture, right?π€
Yes, that's what I was implying
It's not just floating error, but most likely converting to and back into different formats and passing to/from gpu
yea
Honestly the approach you took is not great, but if you want to avoid major reworks, You'll have to introduce some kind of threshold.
if the difference is within that threshold, you consider it as the same color.
something like .01 is probably safe, and shouldn't make much difference visually
Though you'll have to take it into account when the teams pick their color. If they're too close to each other your scoring will break
the colours should always be on opposite sides of the colour wheel
Then there's no problem I guess.
The only thing left is to check the colors asynchronously so as to not freeze the main thread
great, now it thinks the entire map is on alphateam
Probably too big of a threshold π
0.01
bool IsColorEqual(Color a, Color b, float tolerance = 0.01f){
if(a.a - b.a > tolerance){ return false; }
if(a.r - b.r > tolerance){ return false; }
if(a.g - b.g > tolerance){ return false; }
if(a.b - b.b > tolerance){ return false; }
return true;
}
color comparison code
for(int i = 0; i < colors.Length; i++){
//Debug.Log(colors[i]);
if(IsColorEqual(colors[i], gameManager.AlphaTeam , 0.01f)){ alphaScore++; }
else if(IsColorEqual(colors[i], gameManager.BetaTeam , 0.01f)){ betaScore++; }
else{ noScore++; }
}
loop its called in
wait
oh
0a - 1a is less than tolerence
the alpha is broken
Not sure what you mean by that
But you should probably use the absolute value of the difference
Mathf.Abs()
yes
thats what was wrong
tho i realised theres probably no way to account for empty uvs
empty uv space counts as no team
It's not like there's no way
You just need to check the pixel position
That should give you the position in UV space(I think)
y = index / size;
x = index % size;
normalizedPos = (x,y) / size;
Now you just need to somehow define the legal areas.π€
Could probably reconstruct them from mesh uv data, but that sounds like a lot of work
Maybe find a way to import the isles from blender in a format that's easy to check.
just gotta make uv perfect maps π
Oh
Smarter solution
Cover the visable map
Count the still empty pixels
Subtract them in future
Yeah, I guess that's one way to hack it.
Thanks for responding @meager pelican and @quick cape! It's actually even weirder... I just didn't show a good view of it. Check this out...
Let me try that again @meager pelican and @quick cape!
Nothing changes even when I put a Vector4 in the mix...
It looks hardware level...
Can anyone repo this?
Could it be post processing?
Try disabling any post effects to only see the work of the shader
I don't think so, I don't have any post proccing
It does feel like bloom or something is in effect
What's that global volume object doing?
Sine goes from -1 to 1 you cant exactly have negative colors so saturate the output of the sine
I really think thats tonemapping, are you 100% sure? Some templates creates post processing setup automatically
But how could tone mapping come from this shader in the video?
The shader in the video is the one for the cube's material...
What you mean by that?
The shader in the video is the one for the cube's material...
I don't think anything but I'll check
From PP
Some tonemapping profiles cant handle negative colors well, you have to clamp the color range as told earlier (saturate node)
Why would it be different in Scene and Game view though?
Why would it be different in Scene and Game view though?
For different reasons. Instead of asking questions, just check if it's really PP or not...
I'm checking now...
@kind juniper and @dim yoke, yes that was it; it was tone mapping. Thanks guys.
But the question still remains: why doesn't it show in Game view?
Maybe the post processing isnt ensbled for the camera?
Ah, I'll check...
Scene Camera usually uses any PP volumes present in the scene(I think). While game camera doesn't have to.
Btw, we didnt suggest disabling tonemapping, it was just to test, you must still clamp the color to make use of tonemapping (tonemapping is critical part of good post processing)
I will reiterate, such a thing as a negative color does not exist. When a sine wave that goes from -1 to 1 is used for any color operation it must be clamped(saturated) to fit the 0 1 range
Or use a remap node
One of the two
Yes, I added one to sine and that fixed it. Thank you...
Thanks guys! I'm new to URP and Shader Graph so I didn't realize that the post processing was automatically added π
With hdr, you may want to clamp only the low boundary, depends on the case
That would make some of the values go above one and get clamped, loosing information.
@kind juniper and @dim yoke, you guys are Awesome, Thanks!
Saturate is the correct solution. Or (value+1) / 2
This
Except that oddly I had to divide by 4 to avoid bloom???
Maybe not...
Divide by 2 did work.
As expected...
Didn't notice till now how before the +1, the color drops to black for an extend period of time due to clipping...
Guys I am creating Custom sprites by allowing the player to select several parts that use RGB images to allow custom colours
Issue is after I piece them all together I want to add an outline to the final image and it seems impossible to do it?
I can create a UV offset to allow me to move the image left for example and them subtract it from the original to get the difference to create the outline but I have no where to input the actual UV offset?
Here is the example of where I end up, an add node with an output of RGBA... Is there a way to create a Texture2D from this? Or a way to offset it? I can't find an answer anywhere
Oh this is a main preview... probably better to see that
Is there no way to shift a float 4 left? π¦
Cast to int, then shift. float layout in the memory does not allow shifting. The bits don't map to numbers 1 to 1
Have you looked at Shader Graph sprite outline tutorials before inventing your own?
yeh but they all rely on a SampleTexture2D
I add several textures together to create this final product and I need to then add the outline... Otherwise I'd just draw the outline on myself
SampleTexture2D has a UV(2) offset input, but I can't do anything with my end product of a float4... If I could create a new texture with this final output then that'd be great
What's the problem with that?
This is a Colour / float 4
hello, i want to render the linear depth of water to a render texture, i already have the correct calculations but i dont know what kind of render texture i need (currently i have RFloat)
when i try to render this to a render texture, nothing shows up in the frame debugger
Anyone has any insight on Sample Texture 2D LOD node or the corresponding SAMPLE_TEXTURE2D_LOD(Texture, Sampler, UV, LOD); function?
Does it act as a texture2d array? I each lod leveel a separate texture? Can I use a texture 2d array in this function?
Doesn't seem like I can connect the Texture2DArray node into it

