• 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
Klopo

Optimizing HLSL code

4 posts in this topic

Hi Gamedev! I've coded little shader code for my small game to handle lights on my moving rectangles. It work and I'm quite happy with the visual result. Unfortunately it's badly implemented and the number of lights I can have on screen at same time is not enough. Changing pixelshader to use ps_3_0 instead of ps_2_0 made it possible to use 18 lights instead of 3. I know this is a bad solution and what I've to do is lower the number of instructions that is made on the pixel shader.

 

I would love any help I could get to optimize my code, by moving some parts to the vertex shader or change instructions on pixel shader.

 

//-----------------------------------------------------------------------------
// Texture sampler
//-----------------------------------------------------------------------------
uniform const texture BasicTexture;

uniform const sampler TextureSampler : register(s0) = sampler_state
{
	Texture = (BasicTexture);
	MipFilter = Linear;
	MinFilter = Linear;
	MagFilter = Linear;
};

//-----------------------------------------------------------------------------
// Material settings
//-----------------------------------------------------------------------------

uniform const float3	DiffuseColor	: register(c0) = 1;
uniform const float	Alpha		: register(c1) = 1;

//-----------------------------------------------------------------------------
// Matrices
//-----------------------------------------------------------------------------

uniform const float4x4	World		: register(vs, c2);		
uniform const float4x4	View		: register(vs, c6);		
uniform const float4x4	Projection	: register(vs, c10);

//-----------------------------------------------------------------------------
// Structure definitions
//-----------------------------------------------------------------------------

struct CommonVSOutput
{
	float4	Pos_ws;
	float4	Pos_ps;
	float4	Diffuse;
};

//-----------------------------------------------------------------------------
// Vertex shader inputs
//-----------------------------------------------------------------------------
struct VSInputTx
{
	float4	Position	: POSITION;
	float2	TexCoord	: TEXCOORD0;
};

//-----------------------------------------------------------------------------
// Vertex shader outputs
//-----------------------------------------------------------------------------
struct VertexLightingVSOutputTx
{
	float4	PositionPS	: POSITION;		// Position in projection space
	float4	Diffuse		: COLOR0;
	float2	TexCoord	: TEXCOORD0;
};

//-----------------------------------------------------------------------------
// Pixel shader inputs
//-----------------------------------------------------------------------------

struct VertexLightingPSInputTx
{
	float4	Diffuse		: COLOR0;
	float2	TexCoord	: TEXCOORD0;
};

CommonVSOutput ComputeCommonVSOutput(float4 position)
{
	CommonVSOutput vout;
	
	float4 pos_ws = mul(position, World);
	float4 pos_vs = mul(pos_ws, View);
	float4 pos_ps = mul(pos_vs, Projection);
	vout.Pos_ws = pos_ws;
	vout.Pos_ps = pos_ps;
	
	vout.Diffuse	= float4(DiffuseColor, Alpha);
	
	return vout;
}

VertexLightingVSOutputTx VSBasicTx(VSInputTx vin)
{
	VertexLightingVSOutputTx vout;
	
	CommonVSOutput cout = ComputeCommonVSOutput(vin.Position);

	vout.PositionPS	= cout.Pos_ps;
	vout.Diffuse	= cout.Diffuse;
	vout.TexCoord	= vin.TexCoord;

	return vout;
}

//-----------------------------------------------------------------------------
// Pixel shaders
//-----------------------------------------------------------------------------

#define MAX_LIGHTS 18

float2 lightPos[MAX_LIGHTS];
float  lightRadius[MAX_LIGHTS];
float  lightIntensity[MAX_LIGHTS];
float4 lightColor[MAX_LIGHTS];

float objectWidth;
float objectHeight;
float2 objectPosition;
float grayScaleIntensity = 1.0f;

float4 PSBasicTx(VertexLightingPSInputTx pin) : COLOR
{
	float4 texCol = tex2D(TextureSampler, pin.TexCoord);
	float4 color = texCol * pin.Diffuse;
	//color.a = texCol.a;

	//Pixel position
        float2 pixelPos = pin.TexCoord.xy * float2(objectWidth, objectHeight) + objectPosition.xy;

	//Grayscale
	float4 grayScale = texCol;
	grayScale.rgb = dot(texCol.rgb, float3(0.3, 0.59, 0.11));

	for(int i = 0; i < MAX_LIGHTS; i++){
		float dist = distance(lightPos[i], pixelPos);
		float distanceFactor = saturate((lightRadius[i]-dist) / lightRadius[i]);

		grayScale.rgb = lerp(grayScale, texCol, distanceFactor * grayScaleIntensity);

		color += saturate(distanceFactor * lightIntensity[i]) * (grayScale * lightColor[i]);
	}

	//fix overlaping lights
	color.r = min(color.r, texCol.r);
	color.b = min(color.b, texCol.b);
	color.g = min(color.g, texCol.g);

	return color;
}

float4 PSBasicTxNoLight(VertexLightingPSInputTx pin) : COLOR
{
	float4 texCol = tex2D(TextureSampler, pin.TexCoord);
	float4 color  = texCol * pin.Diffuse;
	return color;
}

//-----------------------------------------------------------------------------
// Shader and technique definitions
//-----------------------------------------------------------------------------

int ShaderIndex = 0;


VertexShader VSArray[2] =
{
	compile vs_3_0 VSBasicTx(),
	compile vs_3_0 VSBasicTx(),
};


PixelShader PSArray[2] =
{
	compile ps_3_0 PSBasicTx(),
	compile ps_3_0 PSBasicTxNoLight(),
};


Technique BasicEffect
{
	Pass
	{
		VertexShader = (VSArray[ShaderIndex]);
		PixelShader  = (PSArray[ShaderIndex]);
	}
}
0

Share this post


Link to post
Share on other sites

Before you go about adding more lights, why don't you consider adding permutations of your shader that will allow you to specify the number of lights that need to be looped over? Otherwise you're always going to loop over 18 lights, which will get expensive (especially if your lighting code gets more complicated). If I were you, I would set up my shader like this:

 

//-----------------------------------------------------------------------------
// Texture sampler
//-----------------------------------------------------------------------------
uniform const texture BasicTexture;

uniform const sampler TextureSampler : register(s0) = sampler_state
{
    Texture = (BasicTexture);
    MipFilter = Linear;
    MinFilter = Linear;
    MagFilter = Linear;
};

//-----------------------------------------------------------------------------
// Material settings
//-----------------------------------------------------------------------------

uniform const float3    DiffuseColor    : register(c0) = 1;
uniform const float    Alpha        : register(c1) = 1;

//-----------------------------------------------------------------------------
// Matrices
//-----------------------------------------------------------------------------

uniform const float4x4    World        : register(vs, c2);
uniform const float4x4    View        : register(vs, c6);
uniform const float4x4    Projection    : register(vs, c10);

//-----------------------------------------------------------------------------
// Structure definitions
//-----------------------------------------------------------------------------

struct CommonVSOutput
{
    float4    Pos_ws;
    float4    Pos_ps;
    float4    Diffuse;
};

//-----------------------------------------------------------------------------
// Vertex shader inputs
//-----------------------------------------------------------------------------
struct VSInputTx
{
    float4    Position    : POSITION;
    float2    TexCoord    : TEXCOORD0;
};

//-----------------------------------------------------------------------------
// Vertex shader outputs
//-----------------------------------------------------------------------------
struct VertexLightingVSOutputTx
{
    float4    PositionPS    : POSITION;        // Position in projection space
    float4    Diffuse        : COLOR0;
    float2    TexCoord    : TEXCOORD0;
};

//-----------------------------------------------------------------------------
// Pixel shader inputs
//-----------------------------------------------------------------------------

struct VertexLightingPSInputTx
{
    float4    Diffuse        : COLOR0;
    float2    TexCoord    : TEXCOORD0;
};

CommonVSOutput ComputeCommonVSOutput(float4 position)
{
    CommonVSOutput vout;

    float4 pos_ws = mul(position, World);
    float4 pos_vs = mul(pos_ws, View);
    float4 pos_ps = mul(pos_vs, Projection);
    vout.Pos_ws = pos_ws;
    vout.Pos_ps = pos_ps;

    vout.Diffuse    = float4(DiffuseColor, Alpha);

    return vout;
}

VertexLightingVSOutputTx VSBasicTx(VSInputTx vin)
{
    VertexLightingVSOutputTx vout;

    CommonVSOutput cout = ComputeCommonVSOutput(vin.Position);

    vout.PositionPS    = cout.Pos_ps;
    vout.Diffuse    = cout.Diffuse;
    vout.TexCoord    = vin.TexCoord;

    return vout;
}

//-----------------------------------------------------------------------------
// Pixel shaders
//-----------------------------------------------------------------------------

#define MAX_LIGHTS 18

float2 lightPos[MAX_LIGHTS];
float  lightRadius[MAX_LIGHTS];
float  lightIntensity[MAX_LIGHTS];
float4 lightColor[MAX_LIGHTS];

float objectWidth;
float objectHeight;
float2 objectPosition;
float grayScaleIntensity = 1.0f;

float4 PSBasicTx(VertexLightingPSInputTx pin, uniform int numLights) : COLOR
{
    float4 texCol = tex2D(TextureSampler, pin.TexCoord);
    float4 color = texCol * pin.Diffuse;
    //color.a = texCol.a;

    //Pixel position
        float2 pixelPos = pin.TexCoord.xy * float2(objectWidth, objectHeight) + objectPosition.xy;

    //Grayscale
    float4 grayScale = texCol;
    grayScale.rgb = dot(texCol.rgb, float3(0.3, 0.59, 0.11));

    [unroll]
    for(int i = 0; i < numLights; i++){
        float dist = distance(lightPos[i], pixelPos);
        float distanceFactor = saturate((lightRadius[i]-dist) / lightRadius[i]);

        grayScale.rgb = lerp(grayScale, texCol, distanceFactor * grayScaleIntensity);

        color += saturate(distanceFactor * lightIntensity[i]) * (grayScale * lightColor[i]);
    }

    //fix overlaping lights
    color.r = min(color.r, texCol.r);
    color.b = min(color.b, texCol.b);
    color.g = min(color.g, texCol.g);

    return color;
}

//-----------------------------------------------------------------------------
// Shader and technique definitions
//-----------------------------------------------------------------------------

int NumLights = 0;


PixelShader PSArray[MAX_LIGHTS + 1] =
{
    compile ps_3_0 PSBasicTx(0),
    compile ps_3_0 PSBasicTx(1),
    compile ps_3_0 PSBasicTx(2),
    compile ps_3_0 PSBasicTx(3),
    compile ps_3_0 PSBasicTx(4),
    compile ps_3_0 PSBasicTx(5),
    compile ps_3_0 PSBasicTx(6),
    compile ps_3_0 PSBasicTx(7),
    compile ps_3_0 PSBasicTx(8),
    compile ps_3_0 PSBasicTx(9),
    compile ps_3_0 PSBasicTx(10),
    compile ps_3_0 PSBasicTx(11),
    compile ps_3_0 PSBasicTx(12),
    compile ps_3_0 PSBasicTx(13),
    compile ps_3_0 PSBasicTx(14),
    compile ps_3_0 PSBasicTx(15),
    compile ps_3_0 PSBasicTx(16),
    compile ps_3_0 PSBasicTx(17),
    compile ps_3_0 PSBasicTx(18),
};


Technique BasicEffect
{
    Pass
    {
        VertexShader = compile vs_3_0 VSBasicTx();
        PixelShader  = (PSArray[NumLights]);
    }
}


This will let you set the number of lights on the effect, and the effect will automatically pick a shader that loops over that number of lights. You can also just set NumLights to 0, and you'll get a shader with no lighting (as opposed to custom authoring a pixel shader with no lighting, which is what you were doing before).
0

Share this post


Link to post
Share on other sites

Another thing, and not entirely related to the pixel shader portion, is to merge your View, Projection and World matrices together on the engine side before sending them to the shader. You can then do a single MUL in the VS which should drop the instruction count. Depending on the number of objects this can be a good performance saver.

 

Another idea is to pass your light radius to the shader as a reciprocal, the result being 1.0/lightRadius. DIVs can be slower than MULs if not payed attention to an IIRC they're done per scalar. You can change your attenuation function to something like this (it's pseudocode, you might need to try it - I'm unfamiliar with the unroll for distance but this *might* give you less instructions, but don't take my word for it!):

 

float3 dist = (lightPos[i] - pixelPos) * lightRadius[i]; // gives you the distance (assuming pixelpos and lightpos are in the same space).
float distanceFactor = saturate(1.0 + dot(dist, dist)); // quadratic falloff

One more thing: consider merging your constants, that way you don't have to update as many, etc. For example:

 

 

float2 lightPos[MAX_LIGHTS];
float  lightRadius[MAX_LIGHTS];
float  lightIntensity[MAX_LIGHTS]; 

Can be (feel free to change the name):

 

float4 lightPos[MAX_LIGHTS]; // xy: pos, z: radius, w: intensity

The same can be applied to ObjectWidth and ObjectHeight, etc. It might help.

 

 

Of course YMMV with all of this but they're guidelines I always follow and they generally help.

0

Share this post


Link to post
Share on other sites
Actually, since he's using the fx framework those matrix multiplications will get pulled into a preshader that gets executed on the CPU.
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