BitField in Shaders (SM 3 and before)


Sometimes we need to encode lots of boolean flags in a texture channel and recover it in a shader. I found that shader model 3 and before dont have bitwise operations (they only support floats … that dont have this …) !!!
Fortunately i found some help on the old good float math and i managed to solve this even on SM 2.

Here is how it is done:

1. Encoding some flags in a binary format:

Helper Class

public class ShaderUtils
    {
        public static int CreateSpecificBitField(bool DoNotIlluminate = false, bool isBackGround = false,bool NotEffectedByMotionBlur = false , bool useCubeMapAmbientLightining = false)
        {
            return CreateBitField(DoNotIlluminate, isBackGround, NotEffectedByMotionBlur, useCubeMapAmbientLightining);
        }

        public static int CreateBitField(bool op1 = false, bool op2 = false, bool op3 = false, bool op4 = false, bool op5 = false,bool op6 = false,bool op7 = false,bool op8 = false,bool op9 = false)
        {
            int flags = 
            (op1 ? 1 : 0) |
            (op2 ? 2 : 0) |
            (op3 ? 4 : 0) |
            (op4 ? 8 : 0) |
            (op5 ? 16 : 0) |
            (op6 ? 32 : 0) |
            (op7 ? 64 : 0) |
            (op8 ? 128 : 0) |
            (op9 ? 256 : 0) 

            ;
            return flags;
        }
    }

Creating the bitfield

var bitfield = ShaderUtils.CreateSpecificBitField(false, true,false , false)

2. Saving it to a texture channel (in some Pixel Shader, using render to texture)

float id;   /// recieve the bitfield value
....
PixelShaderOutput PShader( PS_INPUT pin ) : COLOR0   
{   
    PixelShaderOutput output;   
    ///bla bla bla   
    output.color.a = id / 255;   
    return output;   
}

3. Recovering it in another shader and testing the flags !!!:

      sampler extraSampler :register(s1);
....
        float4 extra =  tex2D(extraSampler,input.TexCoord).rgba;
        int procces = round(extra.a * 255 );
        bool DoNotIlluminate = fmod(procces, 2) == 1; 
	bool isBackGround = fmod(procces, 4) >= 2; 
	bool isAmbienteCubeMap = fmod(procces, 16) >= 8; 
 ....

         if(DoNotIlluminate  || isBackGround)
	{
		return float4(diffuseColor,1);
	}
....

There is no rounding problem with the float parameters (the explanation is a bit harder, you will need to know how the worst case scenario is encoded as a mantissa and a expoent).
Shader Model > 3 introduced real integers and Bitwise operations =P

, , ,

  1. #1 by http://besteonlinekreditjetzo.pw/kredit-selbstndig-privatkredit-telefonnummer.html on 10 de dezembro de 2016 - 1:06 am

    Aw, this was a really nice post. In thought I wish to put in writing like this additionally – taking time and actual effort to make an excellent article… but what can I say… I procrastinate alot and certainly not seem to get something done.

  2. #2 by http://bestekreditjemals.info/direkt-kredit-vergleich.html on 10 de dezembro de 2016 - 1:55 am

    I cant… I just cant… There are no words to describe how grateful I am for you and how thankful I am that the team has grown so tightly knit. Seriously. You are going to be the best mommy. You just stay strong! We all support ya :)Best,Hannah

  3. #3 by verbraucherzentrale verbraucherkredit on 10 de dezembro de 2016 - 2:25 am

    on I was very inspired to search out this site. I wished to thank you for this special read. I definitely savored every little little bit of it and I have you bookmarked to check out new stuff you post.

  4. #4 by car insurance quotes on 10 de dezembro de 2016 - 2:32 am

    ramazan başaran diyor ki:biz bartında ikamet ediyoruz eşimle birlikte iş arıyoruz şehir farketmez yatılı olursa her ilde çalışırız vasıfsız eleman arayanlar bize ulaşsınlar işe çok ihtiyacımız var tel.05365797758

  5. #5 by http://onlinekreditevergleichklar.info/kredit-für-kauf-einer-wohnung.html on 10 de dezembro de 2016 - 2:51 am

    How neat! Is it really this simple? You make it look easy.

  6. #6 by http://bestekreditevergleichje.info/kreditzins-sparkasse-geld-leihen.html on 10 de dezembro de 2016 - 2:54 am

    “Seems like the only decent spot around the “arts district” is the WAC lot.” Where is this ‘arts district’…or was that sarcasm? We have a bar district, but I’ve yet to see an arts district. Maybe if Dickson or the square had an actual arts district, WAC would be more likely to stay. They’re kind of out of place as things are now. I get the feeling Fay natives think WAC belongs there simply because they’ve always been there. Having previously lived in towns with real arts districts, I’ve always been struck by how poorly WAC fits in in the bar district.

  7. #7 by space jam 11s size 8 on 10 de dezembro de 2016 - 3:11 am

  8. #8 by ratenkredit jetzt vergleich online on 10 de dezembro de 2016 - 3:17 am

    Tuhkan käytössä esim. tierakentamisessa on oleellista, että tuhkaa ensin “vanhennetaan” kasavarastoinnilla. Kasavarastoinnin aikana lentotuhkissa tapahtuu hienoainespartikkelien yhteenliittymistä, joka parantaa lentotuhkan routa- ja kuormituskestävyysominaisuuksia.Finncao Oy on tehnyt ohjeen metsäteollisuuden tuhkien käyttöön tie-, katu- ja kenttärakenteissa. Ohje löytyy Finncaon nettisivuilta (www.finncao.fi).

  9. #9 by http://onlinekreditetestsiegergerade.org/kreditangebot-6000-euro-job.html on 10 de dezembro de 2016 - 3:19 am

    This is an article that makes you think “never thought of that!”

  10. #10 by http://onlinekreditetestsiegergerade.org/vertrag-privat-kredit-bank.html on 10 de dezembro de 2016 - 3:33 am

    ThIs NHS tourism has been going on for years but the cult of political correctness and anti-racism has prevnted much of it from being reported and certainly any action being taken. I believe that it may be too late now for the NHS and indeed for Britain; where should I move to?   0 likes

  11. #11 by kredit schnell kredit wien on 10 de dezembro de 2016 - 3:47 am

    This forum needed shaking up and you’ve just done that. Great post!

  12. #12 by http://kreditvergleichejetzo.info/kredit-mobil-lewat-bank-bri.html on 10 de dezembro de 2016 - 4:09 am

    AKAIK you’ve got the answer in one!

  13. #13 by http://besteonlinekreditjetzo.pw/privatkredit-lang-laufzeit-120-monate-laufzeit.html on 10 de dezembro de 2016 - 4:14 am

    TdyeagerMarch 28, 2011Great post Dan. How important do you think it is to actually build out your own domain with content i.e. writing blog posts versus building a simple one page template to share basic information?

  14. #14 by http://bestekreditjemals.info/kredit-schnell-geld-sparen.html on 10 de dezembro de 2016 - 4:16 am

    Articles like these put the consumer in the driver seat-very important.

  15. #15 by berechnung kredit haus ausland on 10 de dezembro de 2016 - 4:46 am

    #3“Legislation letting judges reduce the mortgage payments of borrowers in bankruptcy passed the House of Representatives, overcoming opposition from industry groups and Republicans who say the bill may further destabilize lending”************of all the plans out there, I think this one actually makes sense. Bankruptcy is an individualized process and it is much better suited to this than wholesale modifications/bailouts, which will inevitably benefit large numbers of people who don’t need/deserve help

  16. #16 by online kredit schnell bekommen on 10 de dezembro de 2016 - 5:03 am

    I don’t know who you wrote this for but you helped a brother out.

  17. #17 by http://kreditonlineprogressiv.info/visa-kreditkarte-frankfurt.html on 10 de dezembro de 2016 - 5:22 am

    Cada dia es mas necesario tomar la calle. Hoy la UE dice que España no va a cumplir los objetivos de deficit, que la recesión continuará durante 2013 y el paro seguirá creciendo. Y como no, recoiendas nuevos ajustes.Salud, República y Socialismo

  18. #18 by http://onlinekreditevergleichklar.info/kredit-unter-freunden.html on 10 de dezembro de 2016 - 5:51 am

    That’s way the bestest answer so far!

  19. #19 by http://www.lileycountertops.com/promdresses.asp on 10 de dezembro de 2016 - 8:14 am

    Yet not just as fancy when real world should mothers wrist was never 2small do not invest that it reason it become tight .. the pretty still anything yur 5year aged makes . Non all lower its a ok gifts towards present but not your wow present…cant get wrong should dont get a great deal to spend for a gift then take that it

  20. #20 by http://www.mrbitsandbytes.com/veningdress.asp on 10 de dezembro de 2016 - 8:15 am

    Yet not as fancy as part of real world when moms wrist is maybe not 2small don’t purchase things result it feel tight .. it is sweet and yet whatever yur 5year aged make . Non ones much less it is a okay present on give but not the wow present…cant get wrong when don’t enjoy a great deal to spend for a present well attain it

1 652 653 654
(não será publicado)