Skybox on Windows Phone 7


When we have no custom shader, we need to make some sort of little magics to create usual effects like Skybox. This Small post will show a way to simulate this visual effect on Windows Phone 7.
The trick is actually very simple, we just “extract” all the textures from the cube map texture (normally we feed it to a shader that would sample it with the eye vector, but we dont have custom shaders …) and draw all of then each frame (transformed by the camera matrices).

Before showing the code, i need to make some things clear =P.
I used some render functions of PloobsEngine (to hold graphics state, create graphics resources …., tried to use it as little as possible), the functions names used says what is being done, so it is very easy to convert it to plain XNA.

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Features
{
    public class SkyBox
    {
        String textureCubeName;
        bool enable = false;        

        public void Initialize(String texCubeName)
        {
            Cube = GraphicFactory.GetTextureCube(texCubeName);
            CubeFaces = new Texture2D[6];
            PositionOffset = new Vector3(20, 20, 20);
            CreateGraphic(512);
            StripTexturesFromCube();
            InitializeData();
        }       

        #region Properties
        GraphicFactory GraphicFactory;
        public Vector3 PositionOffset { get; set; }
        public Vector3 Position { get; set; }
        public TextureCube Cube { get; set; }
        public Color[] PixelArray { get; set; }
        public Texture2D[] CubeFaces { get; set; }
        public VertexBuffer VertexBuffer { get; set; }
        public IndexBuffer IndexBuffer { get; set; }
        public BasicEffect Effect { get; set; }
        #endregion

        #region Fields

        private List _vertices = new List();
        private List _indices = new List();
        #endregion

        #region Private methods
        private void InitializeData()
        {
            VertexBuffer = GraphicFactory.CreateVertexBuffer(VertexPositionNormalTexture.VertexDeclaration, _vertices.Count, BufferUsage.None);
            VertexBuffer.SetData(_vertices.ToArray());
            IndexBuffer = GraphicFactory.CreateIndexBuffer(IndexElementSize.SixteenBits, _indices.Count, BufferUsage.None);
            IndexBuffer.SetData(_indices.ToArray());
            Effect = GraphicFactory.GetBasicEffect();
            Effect.TextureEnabled = true;
        }

        ///just a fancy quad
        private void CreateGraphic(float size)
        {
            Vector3[] normals = {
                                    Vector3.Right,
                                    Vector3.Left,
                                    Vector3.Up,
                                    Vector3.Down,
                                    Vector3.Backward,
                                    Vector3.Forward,
                                };
            Vector2[] textureCoordinates = {
                                               Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX,
                                               Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY,
                                               Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY,
                                               Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY,
                                               Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One,
                                               Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One,
                                           };
            var index = 0;
            foreach (var normal in normals)
            {
                var side1 = new Vector3(normal.Z, normal.X, normal.Y);
                var side2 = Vector3.Cross(normal, side1);
                AddIndex(CurrentVertex + 0);
                AddIndex(CurrentVertex + 1);
                AddIndex(CurrentVertex + 2);
                AddIndex(CurrentVertex + 0);
                AddIndex(CurrentVertex + 2);
                AddIndex(CurrentVertex + 3);
                AddVertex((normal - side1 - side2) * size / 2, normal, textureCoordinates[index++]);
                AddVertex((normal - side1 + side2) * size / 2, normal, textureCoordinates[index++]);
                AddVertex((normal + side1 + side2) * size / 2, normal, textureCoordinates[index++]);
                AddVertex((normal + side1 - side2) * size / 2, normal, textureCoordinates[index++]);
            }
        }
        protected void StripTexturesFromCube()
        {
            PixelArray = new Color[Cube.Size * Cube.Size];
            for (int s = 0; s < CubeFaces.Length; s++)
            {
                CubeFaces[s] = GraphicFactory.CreateTexture2D(Cube.Size, Cube.Size, false, SurfaceFormat.Color);
                switch (s)
                {
                    case 0:
                        Cube.GetData(CubeMapFace.PositiveX, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                    case 1:
                        Cube.GetData(CubeMapFace.NegativeX, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                    case 2:
                        Cube.GetData(CubeMapFace.PositiveY, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                    case 3:
                        Cube.GetData(CubeMapFace.NegativeY, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                    case 4:
                        Cube.GetData(CubeMapFace.PositiveZ, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                    case 5:
                        Cube.GetData(CubeMapFace.NegativeZ, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                }
            }
        }
        protected void AddVertex(Vector3 position, Vector3 normal, Vector2 textureCoordinates)
        {
            _vertices.Add(new VertexPositionNormalTexture(position, normal, textureCoordinates));
        }
        protected void AddIndex(int index)
        {
            if (index > ushort.MaxValue)
                throw new ArgumentOutOfRangeException("index");
            _indices.Add((ushort)index);
        }

        protected int CurrentVertex
        {
            get { return _vertices.Count; }
        }
        #endregion

        public void PreDraw(RenderHelper render, GameTime gt, ref Matrix activeView, ref Matrix activeProjection, Vector3 CamPos)
        {
            if (!enable || Cube == null)
                return;

            Vector3 position = camPos

            this.Position = position + PositionOffset;
            Effect.View = activeView;
            Effect.Projection = activeProjection;
            Effect.World = Matrix.CreateTranslation(this.Position);

            render.PushDepthStencilState(new DepthStencilState() { DepthBufferEnable = false });
            render.PushRasterizerState(new RasterizerState() { CullMode = CullMode.None });

            var graphics = Effect.GraphicsDevice;
            graphics.SetVertexBuffer(VertexBuffer);
            graphics.Indices = IndexBuffer;

            Effect.Texture = CubeFaces[0];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 0, 2);
            Effect.Texture = CubeFaces[1];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 6, 2);
            Effect.Texture = CubeFaces[2];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 12, 2);
            Effect.Texture = CubeFaces[3];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 18, 2);
            Effect.Texture = CubeFaces[4];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 24, 2);
            Effect.Texture = CubeFaces[5];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 30, 2);

            render.PopDepthStencilState();
            render.PopRasterizerState();

        }
    }
}

You need to call the draw function before all 3D drawing !!!

As always code is not optimized and some stuffs are hardcoded.

  1. #1 by buy viagra on 30 de abril de 2017 - 2:48 pm

    ativan…This is the right blog for anyone who wants to find out about this topic. You realize so much its almost hard to argue with you (not that I actually would want?HaHa). You definitely put a new spin on a topic thats been written about for years. Great st…

  2. #2 by viagra online on 30 de abril de 2017 - 3:27 pm

    A co nas obchodzą wybory w USA. W Polsce ludzie umierają z głodu tu jest problem. Redaktorki TVP szydzą z Gierka ale za jego czasów było to niedopomyślenia cóż z tego, że pojawiło się sporo bogatych dorobkiewiczów, którzy mieli plecy skoro ich mentalność, jak sposób myślenia społecznego jest rodem z XIX wieku.

  3. #3 by viagra online on 30 de abril de 2017 - 3:42 pm

    Its hard to try and be positive about him staying. Its not as if he has proven in the past he CAN play exciting attractive football and put this season down to a blip. His brand of football has always been dour

  4. #4 by office movers in Washington DC on 30 de abril de 2017 - 4:01 pm

    My brother suggested I might like this website. He was totally right. This post truly made my day. You cann at imagine simply how much time I had spent for this information! Thanks!

  5. #5 by http://news.cheapmoncler.pw/cheapmonclerpw/433.asp on 30 de abril de 2017 - 4:07 pm

    I have bought it brand name of bracelet a number of times. Every a person is extremely adorable, prepared very well, does not tarnish then meaningful depending on which kind of a single you purchase as well as whom a person render this towards.

  6. #6 by http://news.panchro.xyz/panchroxyz/307.asp on 30 de abril de 2017 - 4:08 pm

    That product or service is with that awesome expense I never thought that the good would be and so excellent. It is awesome. Our mom is going to really like that concerning Christmas day after she opens up gift therefore appearances like I devoted way more, still pricing had been only ideal!!

  7. #7 by http://news.hermesreplica.win/hermesreplicawin/435.asp on 30 de abril de 2017 - 4:08 pm

    I’ve bought our brand concerning bracelet a few times. Every one is extremely sweet, prepared well, does not tarnish furthermore meaningful based on which an individual you purchase furthermore just who your render information technology in order to.

  8. #8 by generic viagra on 30 de abril de 2017 - 4:21 pm

    I got to watch tay’s performance in stand up to cancer and when she went out she was crying. I decided to buy the song and I couldnt stop crying everytime I hear it. Im sure Ronan is happy too, wherever he is. Stay strong, love. We are always here to help you

  9. #9 by buy viagra online on 30 de abril de 2017 - 4:51 pm

    Marisa, aunque no lo creas, se que estas AHÍ detras, como FAN o como amiga, pero ahí, viendo opinando cuando crees oportuno, y con eso basta, si encima infundes ánimos como haces siempre mejor que mejor… Un besote fuerte también para ti guapa!

  10. #10 by cheap viagra on 30 de abril de 2017 - 5:14 pm

    You are right Phil about the lessons you learned from that shoot, in the past when shooting friends. They have directed what shots they wanted and i didnt want to make a big issue out of it or appear uncooperative. i learnt the hard way.Now i say in advance i will do this this and this, i dont want to be directed ,leave it to me thats my area of concern, family members can best help by cooperating with instructions.It has taken a lot of the stress off me as they know what i want to do and i am not worrying afterwards thinking i should not have taken that shot etc.Keep up the good workJoe

  11. #11 by Tabung Pemadam kebakaran on 30 de abril de 2017 - 5:33 pm

    Good write-up, I am regular visitor of one?¦s blog, maintain up the nice operate, and It’s going to be a regular visitor for a lengthy time.

  12. #12 by womens vibram five fingers sale on 30 de abril de 2017 - 5:41 pm

    I’m having a strange problem I cannot make my reader pick up your feed, I’m using google reader by the way.
    womens vibram five fingers sale http://www.vibramfivefingers.online

  13. #13 by swing set assembly on 30 de abril de 2017 - 6:08 pm

    Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further post thanks once again.

  14. #14 by cheap viagra without prescription on 30 de abril de 2017 - 6:09 pm

    how do QR codes work…Did you know QR Code stands for Quick Response Code? This type of two-dimensional matrix barcode is known for its speed of readability and its vast range of utility. The QR Code was developed in the mid-1990′s for use in the automobile industry and has…VA:F [1.9.20_1166]please wait…

  15. #15 by morrishadnott1.tumblr.com on 30 de abril de 2017 - 6:32 pm

    Does your website have a contact page? I’m having trouble locating it but,
    I’d like to shoot you an email. I’ve got some creative ideas
    for your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it grow over
    time.

  16. #16 by dating advice on 30 de abril de 2017 - 6:35 pm

    very handful of internet websites that come about to be detailed below, from our point of view are undoubtedly well worth checking out

  17. #17 by sexually transmitted disease on 30 de abril de 2017 - 6:36 pm

    here are some hyperlinks to sites that we link to due to the fact we feel they’re worth visiting

  18. #18 by http://news.cartierbraceletsreplica.top/cartierbraceletsreplicatop/324.asp on 30 de abril de 2017 - 6:37 pm

    Right mother’s evening gift. But, ones bracelet took also prolonged to show up, and it arrived following the vacation. My personal mother shown just that she loved your bracelet, yet We have not viewed the lady wear information technology however. :-)

  19. #19 by http://news.redbottomheels.xyz/redbottomheelsxyz/197.asp on 30 de abril de 2017 - 6:38 pm

    Well mother’s evening gifts. Although, the particular bracelet got too longer and come, and it arrived after the getaway. Our mother conveyed you already know she loved the bracelet, although We have not seen this girl don things still. :-)

  20. #20 by http://news.cejewelry.xyz/cejewelryxyz/199.asp on 30 de abril de 2017 - 6:39 pm

    Right mother’s evening present. Though, the actual bracelet got as well lengthy and come, therefore arrived following the vacation. My personal mother conveyed in which she loved the actual bracelet, even though I have not really seen the lady use information technology though. :-)

  21. #21 by http://news.cartierloveringreplica.xyz/cartierloveringreplicaxyz/181.asp on 30 de abril de 2017 - 6:39 pm

    Great mother’s evening present. Although, all bracelet took besides prolonged to come, therefore arrived after the vacation. The mom expressed your she liked the particular bracelet, though I have not noticed the lady put on that it however. :-)

  22. #22 by http://news.cheapmoncler.xyz/cheapmonclerxyz/410.asp on 30 de abril de 2017 - 6:39 pm

    Great mother’s day gift. Though, ones bracelet took besides very long to appear, and it arrived after the getaway. Our mother conveyed your she loved all bracelet, even though We have never seen this girl put on information technology but. :-)

  23. #23 by social media delhi on 30 de abril de 2017 - 6:43 pm

    “Good blog, where did you come up with the knowledge in this piece of content? I??m glad I found it though, ill be checking back soon to see what other articles you have.”

  24. #24 by Disney princess Chicago on 30 de abril de 2017 - 6:58 pm

    Thank you for the good writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! However, how could we communicate?

  25. #25 by Vigrx Plus Results on 30 de abril de 2017 - 7:29 pm

    Thank you for the share.I hope you will share
    again.

  26. #26 by Alat pemadam api on 30 de abril de 2017 - 7:35 pm

    Great blog! Do you have any helpful hints for aspiring writers? I’m hoping to start my own website soon but I’m a little lost on everything. Would you propose starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m completely confused .. Any ideas? Cheers!

  27. #27 by for more on 30 de abril de 2017 - 7:41 pm

    I wanted to say I appreciate you providing
    this info, you’re doing an excellent job with the website…

  28. #28 by buy viagra online on 30 de abril de 2017 - 8:01 pm

    Yep, my grandma did too. She always had a can of bacon fat on her stove and used to toss them in her green beans – so good!

  29. #29 by Barbour International Jackets on 30 de abril de 2017 - 8:39 pm

    Hi there,I enjoy reading through your article post, I wanted to write a little comment to support you and wish you a good continuationAll the best for all your blogging efforts.
    Barbour International Jackets http://www.barbourinternationaljackets.store

  30. #30 by generic viagra on 30 de abril de 2017 - 8:46 pm

    I love going in the charity shop for clothes, looks as though you have a good one. Love the pretty blouse. Thank you for the wonderful compliment, my legs have got a leg slimmer and more toned since I started exercising a few months ago. I've only just started getting them out! :-)You'd be very pleased with me – I bought a 70s/early 80s red polka dot maxi dress on ebay for £2 the other day. It's a bit too small at the moment but I'm sure it won't be too long before it fits. It's an incentive to lose weight anyhow.

  31. #31 by michael kors outlet online on 30 de abril de 2017 - 8:47 pm

    Ive to say, I dont know if its the clashing colors or the bad grammar, but this blog is hideous! I imply, I dont wish to sound like a know-it-all or anything, however may you will have probably put just a little bit extra effort into this subject. Its really interesting, however you dont characterize it well at all, man. Anyway, in my language, there usually are not much good supply like this.
    michael kors outlet online http://www.factorymichaelkorssale.com

  32. #32 by viagra cheap on 30 de abril de 2017 - 8:52 pm

    This sort of behaviour illustrates the impossibility of meaningful communication between Muslims and Westerners. The mad mullah of Norway sees no contradiction between his support of Muslims in defending Muslim lands from Western influence and his objection to Westerners seeking to defend their lands from Muslim influence. And of course there is no contradiction in his mind: Islam is right and thus has the right to impose itself on the West – no argument.

  33. #33 by view on 30 de abril de 2017 - 8:54 pm

    Many thanks for such a wonderful blog. Where
    else could anyone get that kind of info written in such a
    great way? I have a presentation that I am presently writing on,
    and I have been on the look out for such fantastic information. Happy to discover your blog.

  34. #34 by purchase viagra on 30 de abril de 2017 - 9:08 pm

    Olha Ico, em outros tempos, todas essas situações citadas teriam algum tipo de punição. Isso não está acontecendo, se tem influência dos pilotos convidados eu não sei, mas está melhor assim.

  35. #35 by viagra online on 30 de abril de 2017 - 9:28 pm

    So happy to have one of your calendars… at last! Roll on 2008, I say.Wishing you, also, an early Christmas. May the new year continue to make glad your heart.g xo

  36. #36 by BDSM on 30 de abril de 2017 - 10:01 pm

    Here are some of the web pages we recommend for our visitors

  37. #37 by more information on 30 de abril de 2017 - 10:02 pm

    I went over this site and I think you have a lot of great
    information, saved to faves.

  38. #38 by http://news.cartierjusteunclou.xyz/cartierjusteunclouxyz/187.asp on 30 de abril de 2017 - 10:31 pm

    That system ended up being with that ideal price tag I never believed the particular top quality is and so exceptional. It’s perfect. This mother is going to prefer this in Christmas morning once she opens present and it appearance as though I spent a great deal more, still cost had been only great!!

  39. #39 by http://news.arpelsreplica.xyz/arpelsreplicaxyz/208.asp on 30 de abril de 2017 - 10:32 pm

    Our goods was in such a very good rate I never consideration your high quality would be therefore exceptional. Its stunning. This one mama will likely like it upon Christmas day once she opens up gift and it looks like I devoted a lot more, however rates ended up being really ideal!!

  40. #40 by for more on 30 de abril de 2017 - 10:36 pm

    I’m actually impressed with your writing talent. Anyway keep up the wonderful high quality writing,
    it’s rare to see a fantastic blog like this these days.

1 757 758 759
(não será publicado)