• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
jefferytitan

Shader limitations and best practices

12 posts in this topic

Hi people,

Recently I've been experimenting with shaders in Unity, particularly terrain beautification with better blending and bump-mapping. It's been a haphazard self-teaching and experimentation process so far. I have a few questions which may fall under basics or advanced.
[list]
[*]What's the best practice for making shaders cross-platform? At the moment I'm developing on Mac only, so hard to know.
[*]So far my shaders have had no significant effect on frame-rate. What tends to have the most effect? Textures, number of shaders, number of instructions per shader, branching?
[*]Do I need to offer cut-down versions for lower spec'd hardware, and if so how does it know which version to use?
[*]Is it worth branching if most of the time a huge amount of work can be skipped, e.g. only do bump-mapping within distance x of the camera?
[*]When blending bump-mapped textures would it pay off to waste texture space by using a completely flat normal texture rather than having a special case for textures with no bump-map?
[*]What is the instruction count limit based on? Some shaders I've seen seem very "busy" but don't exceed the limits.
[/list]
Any help would be appreciated. Screenshots will follow if I manage to make something look nice. ;)

JT
0

Share this post


Link to post
Share on other sites
Thanks for your reply!

I will check when I get home, as Unity is crossplatform and wraps everything up in ShaderLab. I believe that I'm using [url="http://en.wikipedia.org/wiki/Cg_(programming_language)"]CG[/url], which has similar syntax to HLSL. Apparently it gets compiled for OpenGL and DirectX (9?).

So branching isn't so bad as long as there are likely to be contiguous regions in screen-space which branch the same way? But wouldn't the tiles in the border region between branch 1 and branch 2 slow everything down, e.g. weakest link in the chain?

My main issue is that I want to do bucket-loads in a single shader. Unity's terrain engine has [url="http://unity3d.com/unity/engine/terrains"]a lot of nice features[/url] that I don't want to give up, however there is only one shader that gets applied to all terrain. [img]http://public.gamedev.net//public/style_emoticons/default/sad.png[/img] So I'm wondering whether I can squeeze bump-mapping, specular maps and nicer texture blending in together with the existing splat mapping. Does that sound overly optimistic? The instruction limit that I referred to was in the Unity shader compiler, so it may be a lowest-common-denominator thing. I've only encountered it a few times, like doing 4 harmonic Perlin noise.
0

Share this post


Link to post
Share on other sites
Yeesh, I just did some research. Apparently by default Unity uses Vertex shader 1.1 and pixel shader 2.0, and if you ask nicely you can have 3.0 and 3.0:
[url="http://docs.unity3d.com/Documentation/Components/SL-ShaderPrograms.html#renderers"]http://docs.unity3d.com/Documentation/Components/SL-ShaderPrograms.html#renderers[/url]

According to the below, the capabilities of the former are pitiful:
[url="http://en.wikipedia.org/wiki/Shader_Model"]http://en.wikipedia.org/wiki/Shader_Model[/url]

Apparently you can also specify a target platform and request higher limits for texture indirections etc assuming the graphics card allows it. I guess the key is prioritising features and lots of failovers. ;)
0

Share this post


Link to post
Share on other sites
CG is just a meta-language which compiles to GLSL or HLSL. On mac most likely GLSL. If you can't extract the information directly from unity (I don't know unity myself), choose a certain GPU generation and check its supported DirectX/OGL version to get a gimpse of what the shaders are capable of.

[quote name='jefferytitan' timestamp='1343342264' post='4963454']
So branching isn't so bad as long as there are likely to be contiguous regions in screen-space which branch the same way?
[/quote]
Branches are never bad, [i]smaller [/i]branches will be even optimized to non-branching code by the driver, but it is still always a good idea to avoid them if possible.

[quote name='jefferytitan' timestamp='1343342264' post='4963454']
But wouldn't the tiles in the border region between branch 1 and branch 2 slow everything down, e.g. weakest link in the chain?
[/quote]
Yes, but only a [i]group [/i]of them, if 1 out of 10 is a border tile, you save a lot of GPU processing power. This will not work so good if your branches [i]flickers [/i]alot. A simple example is a soft shadow application, where you check 4 pixels first and only continue to check an other bunch of lets say 20 pixels if the 4 are a mix of shadowed/unshadowed pixels. In this case all tiles which are completly in or out of a shadow will performe much faster.

[quote name='jefferytitan' timestamp='1343342264' post='4963454']
Unity's terrain engine has a lot of nice features that I don't want to give up, however there is only one shader that gets applied to all terrain.[/quote]
I think that one shader for the terrain isn't that uncommon. If unity is using a deferred rendering/lighting system you will have the chance to apply more effects in post-processing steps.

[quote name='jefferytitan' timestamp='1343342264' post='4963454']
So I'm wondering whether I can squeeze bump-mapping, specular maps and nicer texture blending in together with the existing splat mapping. Does that sound overly optimistic?
[/quote]
This doesn't sound overly optimistic as long as you don't target too old hardware. Normalmaps, specular, color, ao map (channels) are quite common, best to choose a standard quality and add higher quality shader options (pre-processor in CG/unity ?) for better GPUs.
1

Share this post


Link to post
Share on other sites
Thanks for the info. Currently I've managed to get splat-mapping with 4 textures, relief-mapping with cone step mapping, improved blending between textures (based on height difference) and one simple specular float per texture into one shader model 3 terrain shader. That's pretty much where I've hit the 512 instruction limit, as the CSM takes a lot after loop unrolling. I'm not sure how much further optimisation could get me. I heard you can do multiple pass shaders. Is it worth it, or too tricky/expensive?

I also tried doing a GLSL specific version using the feature as below:
#pragma glsl - when compiling shaders for desktop OpenGL platforms, convert Cg/HLSL into GLSL (instead of default setting which is ARB vertex/fragment programs)

Curiously the relief mapping didn't work at all (completely flat appearance), but the rest of the shader worked. Could the GLSL compiled version not be getting all the textures?

Anyway, will follow up with screenshots and maybe shader code if anyone is interested.
0

Share this post


Link to post
Share on other sites
Hi people,

Just thought I'd show you my progress so far. I'm hitting the SM3 512 instruction limit right now with no specular map. :( Also there's a bit of aliasing which may or may not be coming from the cone step mapping.

[img]http://i1151.photobucket.com/albums/o633/jefferytitan/UnityShaderSS1.jpg[/img]

[img]http://i1151.photobucket.com/albums/o633/jefferytitan/UnityShaderSS2.jpg[/img]

[img]http://i1151.photobucket.com/albums/o633/jefferytitan/UnityShaderSS3.jpg[/img]

[img]http://i1151.photobucket.com/albums/o633/jefferytitan/UnityShaderSS4.jpg[/img]
0

Share this post


Link to post
Share on other sites
[quote name='jefferytitan' timestamp='1344342649' post='4966989']
SM3 512 instruction
[/quote]
512 instructions for conestep mapping ? The reason is most likely that your loops are unrolled. Try to limit the number of steps for lower end video cards and try to optimize the loop content (size).
0

Share this post


Link to post
Share on other sites
The number one problem I'm encountering now is the instruction limit (512) imposed by Unity/CG/Shaderlab, the card itself seems to be irrelevant unless I'm missing something. Having said that I will happily admit I'm no GPU optimisation guru, so there may be decent gains to be had. I'll give you a few representative snippets (as happens with testing the whole thing is a huge mess), and if you have any ideas on optimisation it would be much appreciated.

[b]General Setup:[/b]
[source lang="plain"] half4 splat_control = tex2D (_Control, IN.uv_Control);
half3 col;

float3 p0, p1, p2, p3, v;
const int cone_steps = 15;
float db;
float dist;
float4 tex;
float height0;
float height1;
float height2;
float height3;
float cone_ratio;

v = normalize(IN.eye.xyz);
v.z = abs(v.z);
db = 1.0-v.z; db*=db; db*=db; db=1.0-db*db;
v.xy *= db;
v.xy *= parallaxDepth;
v /= v.z;
dist = length(v.xy);

p0 = float3(IN.uv_Control.x * (_TerrainX/_Tile0), IN.uv_Control.y * (_TerrainZ/_Tile0), 0);
p1 = float3(IN.uv_Control.x * (_TerrainX/_Tile1), IN.uv_Control.y * (_TerrainZ/_Tile1), 0);
p2 = float3(IN.uv_Control.x * (_TerrainX/_Tile2), IN.uv_Control.y * (_TerrainZ/_Tile2), 0);
p3 = float3(IN.uv_Control.x * (_TerrainX/_Tile3), IN.uv_Control.y * (_TerrainZ/_Tile3), 0);[/source]

[b]Cone Stepping Loop (x 4)[/b]
[source lang="plain"] for (int i=0;i<cone_steps; i++ )
{
tex = tex2D(_parallax0, p0.xy);
height0 = saturate(tex.w - p0.z);
cone_ratio = tex.z;
p0 += v * (cone_ratio * height0 / (dist + cone_ratio));
}[/source]

[b]Height Weighting The Splatting:[/b]
[source lang="plain"] height0 = 1 - max(p0.z, 0.0001);
height1 = 1 - max(p1.z, 0.0001);
height2 = 1 - max(p2.z, 0.0001);
height3 = 1 - max(p3.z, 0.0001);

height0 = height0 * height0;
height0 = height0 * height0;
height1 = height1 * height1;
height1 = height1 * height1;
height2 = height2 * height2;
height2 = height2 * height2;
height3 = height3 * height3;
height3 = height3 * height3;

splat_control *= float4(height0, height1, height2, height3);
float totalSplat = dot(splat_control, float4(1,1,1,1));
splat_control /= totalSplat;

float2 pAv = splat_control.r * p0.xy + splat_control.g * p1.xy + splat_control.b * p2.xy + splat_control.a * p3.xy; [/source]

[b]Splatting to get Final Result:[/b]
[source lang="plain"] col = splat_control.r * tex2D (_Splat0, pAv).rgb;
o.Normal = splat_control.r * UnpackNormal(tex2D(_BumpMap0, pAv));
o.Gloss = splat_control.r * _Spec0;

col += splat_control.g * tex2D (_Splat1, pAv).rgb;
o.Normal += splat_control.g * UnpackNormal(tex2D(_BumpMap1, pAv));
o.Gloss += splat_control.g * _Spec1;

col += splat_control.b * tex2D (_Splat2, p2.xy).rgb;
o.Normal += splat_control.b * UnpackNormal(tex2D(_BumpMap2, pAv));
o.Gloss += splat_control.b * _Spec2;

col += splat_control.a * tex2D (_Splat3, p3.xy).rgb;
o.Normal += splat_control.a * UnpackNormal(tex2D(_BumpMap3, pAv));
o.Gloss += splat_control.a * _Spec3;

o.Specular = o.Gloss;[/source]
As you can see, there's a lot of repetitiveness, in multiples of 4, which I hope means good optimisation possibilities. But I can't figure out the practicalities. I don't think most of the vector operations could be generalised to matrices. I can't figure a way to square each component of a vector more efficiently. And some of the areas actually took more instructions when I converted them to use vectors instead of floats. Frustrating.
0

Share this post


Link to post
Share on other sites
instead of:
[code]height0 = height0 * height0;
height0 = height0 * height0;[/code]
use
[code]
height0 = pow(height0, 4);[/code]
because pow will use the Special Function Unit that is idling in your shader ! this will offload the ALU a bit and increase parallelization.
0

Share this post


Link to post
Share on other sites
[quote name='Lightness1024' timestamp='1345759361' post='4972777']
because pow will use the Special Function Unit that is idling in your shader[/quote]

While I'm not questioning your advice, as you generally want to use intrinstics as much as you can, there is no garentee about what it will use as not all hardware has a SFU; AMD's latest GPU arch, for example, doesn't have a dedicated SFU; all the vector units can do SFU work as required.
0

Share this post


Link to post
Share on other sites
Regarding your cone stepping loop - you'd have to check the asm output to see if this bit is being in-lined, but if it is, it could be caused by defining cone_steps as a const int = 15. The compiler now knows the max number of loops and will inline the whole thing if there are enough instruction slots. Try to leave this undefined, set value from CPU, now the compiler doesn't know the max number of loops and will leave this bit as a loop. Whether that will help performance is unknown, but it will reduce instruction count by a ton.
0

Share this post


Link to post
Share on other sites
[quote name='phantom' timestamp='1345760585' post='4972787']
[quote name='Lightness1024' timestamp='1345759361' post='4972777']
because pow will use the Special Function Unit that is idling in your shader[/quote]

While I'm not questioning your advice, as you generally want to use intrinstics as much as you can, there is no garentee about what it will use as not all hardware has a SFU; AMD's latest GPU arch, for example, doesn't have a dedicated SFU; all the vector units can do SFU work as required.
[/quote]
Ok, I didn't know that.
it also depends on the sahder model profile the compiler is set to compile. it is possible that when targeting SM3 the pow will be extended to a taylor serie. (which was definitely the case for e.g. sin(x) in SM1, in SM2 the compiler is replacing sin(x) by sincos(x) asm intrinsic)
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0