Esempio n. 1
0
            public Factory(Data d, GameObject gObj,
			float zOff = 0, float zR = 1, int rQOff = 0, Camera cam = null,
			string texturePrfx = "", string fontPrfx = "",
			TextureLoader textureLdr = null,
			TextureUnloader textureUnldr = null)
                : base(gObj, zOff, zR, rQOff,
			cam, texturePrfx, fontPrfx, textureLdr, textureUnldr)
            {
                data = d;
                mesh = new Mesh();

                meshFilter = gameObject.AddComponent<MeshFilter>();
                meshFilter.sharedMesh = mesh;

                meshRenderer = gameObject.AddComponent<UnityEngine.MeshRenderer>();
                meshRenderer.castShadows = false;
                meshRenderer.receiveShadows = false;

                textureName = texturePrefix + data.textures[0].filename;
                meshRenderer.sharedMaterial =
                ResourceCache.SharedInstance().LoadTexture(
                data.name, textureName, data.textures[0].format,
                    textureLoader, textureUnloader);
                if (renderQueueOffset != 0)
                meshRenderer.sharedMaterial.renderQueue += renderQueueOffset;

                premultipliedAlpha = (data.textures[0].format ==
                (int)Format.Constant.TEXTUREFORMAT_PREMULTIPLIEDALPHA);

                buffer = new CombinedMeshBuffer();

                CreateBitmapContexts(data);
                CreateTextContexts(data);
            }
Esempio n. 2
0
        public void Draw( CanvasDrawingSession ds, CanvasSpriteBatch SBatch, TextureLoader Textures )
        {
            lock ( PFSim )
            {
                var Snapshot = PFSim.Snapshot();
                while ( Snapshot.MoveNext() )
                {
                    Particle P = Snapshot.Current;

                    float A = ( P.Trait & PFTrait.IMMORTAL ) == 0 ? P.ttl * 0.033f : 1;

                    P.Tint.M12 = 4 * ( 1 - A );
                    P.Tint.M21 = 3 * A;

                    Vector4 Tint = new Vector4(
                        P.Tint.M11 + P.Tint.M21 + P.Tint.M31 + P.Tint.M41 + P.Tint.M51,
                        P.Tint.M12 + P.Tint.M22 + P.Tint.M32 + P.Tint.M42 + P.Tint.M52,
                        P.Tint.M13 + P.Tint.M23 + P.Tint.M33 + P.Tint.M43 + P.Tint.M53,
                        P.Tint.M14 + P.Tint.M24 + P.Tint.M34 + P.Tint.M44 + P.Tint.M54
                    ) * 2;

                    Tint.W *= A * 0.125f;

                    SBatch.Draw( Textures[ P.TextureId ], P.Pos, Tint, Textures.Center[ P.TextureId ], 0, P.Scale * A, CanvasSpriteFlip.None );
                }

                DrawWireFrames( ds );
            }
        }
Esempio n. 3
0
        public void Draw( CanvasDrawingSession ds, CanvasSpriteBatch SBatch, TextureLoader Textures )
        {
            lock ( PFSim )
            {
                var Snapshot = PFSim.Snapshot();
                while ( Snapshot.MoveNext() )
                {
                    Particle P = Snapshot.Current;

                    float A = Vector2.Transform( new Vector2( 0, 1 ), Matrix3x2.CreateRotation( P.ttl * 0.01f ) ).X;

                    Vector4 Tint = new Vector4(
                        P.Tint.M11 + P.Tint.M21 + P.Tint.M31 + P.Tint.M41 + P.Tint.M51,
                        P.Tint.M12 + P.Tint.M22 + P.Tint.M32 + P.Tint.M42 + P.Tint.M52,
                        P.Tint.M13 + P.Tint.M23 + P.Tint.M33 + P.Tint.M43 + P.Tint.M53,
                        P.Tint.M14 + P.Tint.M24 + P.Tint.M34 + P.Tint.M44 + P.Tint.M54
                    );

                    Tint.W *= A;
                    ScrollWind.Strength *= 0.5f;

                    SBatch.Draw(
                        Textures[ P.TextureId ]
                        , P.Pos, Tint
                        , Textures.Center[ P.TextureId ], 0, P.Scale
                        , CanvasSpriteFlip.None );
                }

                DrawWireFrames( ds );
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RectangleMode"/> class.
        /// </summary>
        public SvgSquaresMode()
        {
            // Create a list of gem images.
            SceneNodeLinkedList<float> nodes = new SceneNodeLinkedList<float>();
            RootSceneNode = nodes;

            // Load the image into memory.
            svgLoader = new SvgLoader(new FileInfo("Images/1cm.svg"));
            float screenScale = Platform.Instance.Window.Resolution.Height / 16f;
            svgLoader.Scale = screenScale * SvgImageLoader.Meter100px;
            TextureLoader textureLoader = new TextureLoader(svgLoader);

            // Create squares across the board.
            rows = (int) (440 / screenScale);
            columns = (int) (600 / (2 * screenScale));

            for (int i = 0; i < columns; i++)
            {
                for (int j = 0; j < rows; j++)
                {
                    ImageNode<float> image = new ImageNode<float>(textureLoader);
                    image.Point = new Point2<float>((j % 2) * screenScale + i * 2 * screenScale, j * screenScale);

                    if (i % 4 == 0)
                        image.Tint = new Color<float>(1, 1, 0, 0);

                    if (j % 4 == 0)
                        image.Tint = new Color<float>(1, 0, 1, 0);

                    nodes.Add(image);
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Called when the load image key event is called.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="MfGames.Scene2.Images.LoadImageKeyEventArgs"/> instance containing the event data.</param>
        private void OnLoadImageKey(object sender, LoadImageKeyEventArgs args)
        {
            BitmapLoader systemLoader = new BitmapLoader(new FileInfo("Images/" + args.Path + ".png"));
            TextureLoader textureLoader = new TextureLoader(systemLoader);

            args.ImageKeyLoader = textureLoader;
        }
Esempio n. 6
0
		public Atlas (String path, TextureLoader textureLoader) {
			using (StreamReader reader = new StreamReader(path)) {
				try {
					Load(reader, Path.GetDirectoryName(path), textureLoader);
				} catch (Exception ex) {
					throw new Exception("Error reading atlas file: " + path, ex);
				}
			}
		}
            public Factory(Data data, GameObject gObj,
			float zOff = 0, float zR = 1, int rQOff = 0, Camera cam = null,
			string texturePrfx = "", string fontPrfx = "",
			TextureLoader textureLdr = null,
			TextureUnloader textureUnldr = null)
                : base(gObj, zOff, zR, rQOff,
			cam, texturePrfx, fontPrfx, textureLdr, textureUnldr)
            {
                CreateBitmapContexts(data);
            }
Esempio n. 8
0
		private async Task ReadFile(string path, TextureLoader textureLoader) {
			var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
			var file = await folder.GetFileAsync(path).AsTask().ConfigureAwait(false);
			using (var reader = new StreamReader(await file.OpenStreamForReadAsync().ConfigureAwait(false))) {
				try {
					Load(reader, Path.GetDirectoryName(path), textureLoader);
				} catch (Exception ex) {
					throw new Exception("Error reading atlas file: " + path, ex);
				}
			}
		}
Esempio n. 9
0
            public Factory(Data d, GameObject gObj,
			float zOff = 0, float zR = 1, int rQOff = 0,
			string sLayerName = null, int sOrder = 0, bool uAC = false,
			Camera renderCam = null, Camera inputCam = null,
			string texturePrfx = "", string fontPrfx = "",
			TextureLoader textureLdr = null,
			TextureUnloader textureUnldr = null)
                : base(d, gObj, zOff, zR, rQOff, sLayerName, sOrder, uAC, renderCam,
			inputCam, texturePrfx, fontPrfx, textureLdr, textureUnldr)
            {
                CreateBitmapContexts();
                CreateTextContexts();
            }
Esempio n. 10
0
		public Texture RegisterTexture(ref Texture texture, ref TextureLoader<Texture> textureLoader) {
			if(_textureList.Contains(texture)) {
				throw new Exception(string.Format("Texture {0} already registered.", texture));
			}
			if(_textureCatalog.ContainsKey(texture.Name)) {
				throw new Exception(string.Format("A Texture with the Name {0} already exists in this catalog. Cannot insert {1}.", texture.Name, texture));
			}
			_textureList.Add(texture);
			_textureCatalog.Add(
				texture.Name, 
			    new CatalogEntry<Texture, TextureLoader<Texture>>(texture, textureLoader)
			);
			return texture;
		}
Esempio n. 11
0
        public CanvasStage( CanvasAnimatedControl Stage )
        {
            _stage = Stage;

            Scenes = new List<IScene>();

            Textures = new TextureLoader();
            Stage.CreateResources += Stage_CreateResources;

            Stage.GameLoopStarting += Stage_GameLoopStarting;
            Stage.GameLoopStopped += Stage_GameLoopStopped;

            Stage.SizeChanged += Stage_SizeChanged;
            Stage.Unloaded += Stage_Unloaded;
        }
Esempio n. 12
0
		public Atlas (String path, TextureLoader textureLoader) {

#if WINDOWS_PHONE
            Stream stream = Microsoft.Xna.Framework.TitleContainer.OpenStream(path);
            using (StreamReader reader = new StreamReader(stream))
            {
#else
            using (StreamReader reader = new StreamReader(path)) {
#endif
				try {
					Load(reader, Path.GetDirectoryName(path), textureLoader);
				} catch (Exception ex) {
					throw new Exception("Error reading atlas file: " + path, ex);
				}
			}
		}
Esempio n. 13
0
            protected Factory(GameObject gObj,
		float zOff, float zR, int rQOff, Camera cam,
		string texturePrfx = "", string fontPrfx = "",
		TextureLoader textureLdr = null,
		TextureUnloader textureUnldr = null)
            {
                gameObject = gObj;
                zOffset = zOff;
                zRate = zR;
                renderQueueOffset = rQOff;
                camera = cam;
                texturePrefix = texturePrfx;
                fontPrefix = fontPrfx;
                textureLoader = textureLdr;
                textureUnloader = textureUnldr;
                matrix = Matrix4x4.identity;
            }
Esempio n. 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RectangleMode"/> class.
        /// </summary>
        public GemsMode()
        {
            // Create a list of gem images.
            SceneNodeLinkedList<float> nodes = new SceneNodeLinkedList<float>();
            RootSceneNode = nodes;

            // Create the blue gem.
            BitmapLoader systemLoader = new BitmapLoader(new FileInfo("Images/Gem Blue.png"));
            TextureLoader textureLoader = new TextureLoader(systemLoader);
            ImageNode<float> image = new ImageNode<float>(textureLoader);
            image.Point = new Point2<float>(10, 10);
            image.DrawableRenderAnimators.Add(
                new DisappearingFlickerDrawableAnimation<float>());
            image.DrawableRenderAnimators.Add(
                new UnsteadyFlickerDrawableAnimation<float>()
                {
                    OpacityScale = 0.2,
                    TimeScale = 1,
                });
            Updating += image.OnUpdate;
            nodes.Add(image);

            // Create the green gem.
            systemLoader = new BitmapLoader(new FileInfo("Images/Gem Green.png"));
            textureLoader = new TextureLoader(systemLoader);
            image = new ImageNode<float>(textureLoader);
            image.Point = new Point2<float>(60, 90);
            nodes.Add(image);

            // Create the translucent orange.
            systemLoader = new BitmapLoader(new FileInfo("Images/Gem Orange.png"));
            textureLoader = new TextureLoader(systemLoader);
            image = new ImageNode<float>(textureLoader);
            image.Tint = new Color<float>(0.5f, 1f, 1f, 1f);
            image.Point = new Point2<float>(110, 10);
            nodes.Add(image);

            // Create an animated image.
            AnimatedImageNodeController<float> animatedController = new AnimatedImageNodeController<float>();
            animatedController.NeedImageKey += OnLoadImageKey;
            animatedController.Load(new FileInfo("Images/Gem Animation.xml"));
            AnimatedImageNode<float> animatedImage = new AnimatedImageNode<float>(animatedController);
            animatedImage.Point = new Point2<float>(10, 200);
            Updating += animatedImage.OnUpdate;
            nodes.Add(animatedImage);
        }
Esempio n. 15
0
            protected Factory(GameObject gObj,
		float zOff, float zR, int rQOff, Camera cam,
		string texturePrfx = "", string fontPrfx = "",
		TextureLoader textureLdr = null,
		TextureUnloader textureUnldr = null)
            {
                gameObject = gObj;
                zOffset = zOff;
                zRate = zR;
                renderQueueOffset = rQOff;
                camera = cam;
                texturePrefix = texturePrfx;
                fontPrefix = fontPrfx;
                textureLoader = textureLdr;
                textureUnloader = textureUnldr;
                matrix = Matrix4x4.identity;
                blendMode = (int)Format.Constant.BLEND_MODE_NORMAL;
                maskMode = (int)Format.Constant.BLEND_MODE_NORMAL;
            }
Esempio n. 16
0
            protected Factory(Data d, GameObject gObj, float zOff, float zR, int rQOff,
		string sLayerName, int sOrder, bool uAC, Camera renderCam,
		Camera inputCam, string texturePrfx = "", string fontPrfx = "",
		TextureLoader textureLdr = null, TextureUnloader textureUnldr = null)
            {
                data = d;
                gameObject = gObj;
                zOffset = zOff;
                zRate = zR;
                renderQueueOffset = rQOff;
                sortingLayerName = sLayerName;
                sortingOrder = sOrder;
                useAdditionalColor = uAC;
                renderCamera = renderCam;
                inputCamera = inputCam;
                texturePrefix = texturePrfx;
                fontPrefix = fontPrfx;
                textureLoader = textureLdr;
                textureUnloader = textureUnldr;
                matrix = Matrix4x4.identity;
                blendMode = (int)Format.Constant.BLEND_MODE_NORMAL;
                maskMode = (int)Format.Constant.BLEND_MODE_NORMAL;
            }
Esempio n. 17
0
 public Malus(Vector2 pos) : base(pos)
 {
     sprite.GetComponent <Renderer>().material.mainTexture = TextureLoader.GetSkull();
     color = Color.white;        //ColorHSV.GetColor(300f, 1f, 1f);
     spriteMaterial.color = color;
 }
Esempio n. 18
0
        static public void writeTextureToFile(Texture d3dtex, String filename)
        {
            Image img = Image.FromStream(TextureLoader.SaveToStream(ImageFileFormat.Bmp, (BaseTexture)d3dtex));

            img.Save(filename);
        }
Esempio n. 19
0
        public virtual void OnInit(ControlContext cc)
        {
            if ( imageFileName != null )
            {
                loader = cc.SmartTextureLoader.LoadDefFile("mem:"+imageFileName);
            }
            else
            {
                loader = cc.SmartTextureLoader.LoadDefFile(defFile
                    ,isDefFileRelative);
            }

            /*
            // これ、ここでやってしまうと、コンテキスト選択されてないとおかしゅうなる。

            ITexture t = loader.GetTexture(0);
            // ボタンサイズを取得しておき、これをマウスの判定矩形として利用する
            if (t != null)
            {
                width = (int)t.Width;
                height = (int)t.Height;
            }
             */
        }
        private static Texture LoadGraphic(string fileName, long lColorKey, int iMaxWidth, int iMaxHeight, out int width,
                                           out int height)
        {
            width  = 0;
            height = 0;
            Image   imgSrc  = null;
            Texture texture = null;

            try
            {
#if DO_RESAMPLE
                imgSrc = Image.FromFile(fileName);
                if (imgSrc == null)
                {
                    return(null);
                }
                //Direct3D prefers textures which height/width are a power of 2
                //doing this will increases performance
                //So the following core resamples all textures to
                //make sure all are 2x2, 4x4, 8x8, 16x16, 32x32, 64x64, 128x128, 256x256, 512x512
                int w = -1, h = -1;
                if (imgSrc.Width > 2 && imgSrc.Width < 4)
                {
                    w = 2;
                }
                if (imgSrc.Width > 4 && imgSrc.Width < 8)
                {
                    w = 4;
                }
                if (imgSrc.Width > 8 && imgSrc.Width < 16)
                {
                    w = 8;
                }
                if (imgSrc.Width > 16 && imgSrc.Width < 32)
                {
                    w = 16;
                }
                if (imgSrc.Width > 32 && imgSrc.Width < 64)
                {
                    w = 32;
                }
                if (imgSrc.Width > 64 && imgSrc.Width < 128)
                {
                    w = 64;
                }
                if (imgSrc.Width > 128 && imgSrc.Width < 256)
                {
                    w = 128;
                }
                if (imgSrc.Width > 256 && imgSrc.Width < 512)
                {
                    w = 256;
                }
                if (imgSrc.Width > 512 && imgSrc.Width < 1024)
                {
                    w = 512;
                }


                if (imgSrc.Height > 2 && imgSrc.Height < 4)
                {
                    h = 2;
                }
                if (imgSrc.Height > 4 && imgSrc.Height < 8)
                {
                    h = 4;
                }
                if (imgSrc.Height > 8 && imgSrc.Height < 16)
                {
                    h = 8;
                }
                if (imgSrc.Height > 16 && imgSrc.Height < 32)
                {
                    h = 16;
                }
                if (imgSrc.Height > 32 && imgSrc.Height < 64)
                {
                    h = 32;
                }
                if (imgSrc.Height > 64 && imgSrc.Height < 128)
                {
                    h = 64;
                }
                if (imgSrc.Height > 128 && imgSrc.Height < 256)
                {
                    h = 128;
                }
                if (imgSrc.Height > 256 && imgSrc.Height < 512)
                {
                    h = 256;
                }
                if (imgSrc.Height > 512 && imgSrc.Height < 1024)
                {
                    h = 512;
                }
                if (w > 0 || h > 0)
                {
                    if (h > w)
                    {
                        w = h;
                    }
                    Log.Info("TextureManager: resample {0}x{1} -> {2}x{3} {4}",
                             imgSrc.Width, imgSrc.Height, w, w, fileName);

                    Image imgResampled = Resample(imgSrc, w, h);
                    imgSrc.SafeDispose();
                    imgSrc       = imgResampled;
                    imgResampled = null;
                }
#endif

                Format fmt = Format.A8R8G8B8;

                ImageInformation info2 = new ImageInformation();

                texture = TextureLoader.FromFile(GUIGraphicsContext.DX9Device,
                                                 fileName,
                                                 0, 0, //width/height
                                                 1,    //mipslevels
                                                 0,    //Usage.Dynamic,
                                                 fmt,
                                                 GUIGraphicsContext.GetTexturePoolType(),
                                                 Filter.None,
                                                 Filter.None,
                                                 (int)lColorKey,
                                                 ref info2);
                width  = info2.Width;
                height = info2.Height;
            }
            catch (InvalidDataException e1) // weird : should have been FileNotFoundException when file is missing ??
            {
                //we need to catch this on higer level.
                throw e1;
            }
            catch (Exception)
            {
                Log.Error("TextureManager: LoadGraphic - invalid thumb({0})", fileName);
                Format fmt      = Format.A8R8G8B8;
                string fallback = GUIGraphicsContext.GetThemedSkinFile(@"\media\" + "black.png");

                ImageInformation info2 = new ImageInformation();
                texture = TextureLoader.FromFile(GUIGraphicsContext.DX9Device,
                                                 fallback,
                                                 0, 0, //width/height
                                                 1,    //mipslevels
                                                 0,    //Usage.Dynamic,
                                                 fmt,
                                                 GUIGraphicsContext.GetTexturePoolType(),
                                                 Filter.None,
                                                 Filter.None,
                                                 (int)lColorKey,
                                                 ref info2);
                width  = info2.Width;
                height = info2.Height;
            }
            finally
            {
                if (imgSrc != null)
                {
                    imgSrc.SafeDispose();
                }
            }
            return(texture);
        }
Esempio n. 21
0
        public EarthlitNightScene(IEye eye)
        {
            this.eye = eye;
            device = eye.Device;
            swapChain = device.PrimarySwapChain;

            stars = new Stars(device, StarCount);

            var meshFactory = new MeshFactory(device, Handedness.Right, Winding.Clockwise);
            var earthMesh = meshFactory.CreateSphere(false, 1.0f, 36);
            earthVertexBuffer = earthMesh.Vertices.Buffer;
            earthIndexBuffer = earthMesh.Indices.Buffer;

            var formatInfo = eye.Adapters[0].GetSupportedFormats(FormatSupport.RenderTarget | FormatSupport.Texture2D | FormatSupport.TextureCube)
                .First(x => x.ColorBits == 24 && x.AlphaBits == 8 && x.ColorFormatType == FormatElementType.UNORM);
            starsProxyTexture = device.Create.Texture2D(new Texture2DDescription
            {
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Usage = Usage.Default,
                Width = SkyboxSize,
                Height = SkyboxSize,
                ArraySize = 1,
                MipLevels = 1,
                FormatID = formatInfo.ID
            });

            skyboxTexture = device.Create.Texture2D(new Texture2DDescription
            {
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Usage = Usage.Default,
                Width = SkyboxSize,
                Height = SkyboxSize,
                ArraySize = 6,
                MipLevels = TextureHelper.MipLevels(SkyboxSize, SkyboxSize, 1),
                FormatID = formatInfo.ID,
                MiscFlags = MiscFlags.TextureCube | MiscFlags.GenerateMips
            });

            var textureLoader = new TextureLoader(device);

            earthTexture = textureLoader.Load("../Textures/BasicTest.png");
        }
Esempio n. 22
0
        public override void Init()
        {
            time = 0f;
            Device d3dDevice = D3DDevice.Instance.Device;

            MyShaderDir = ShadersDir + "WorkshopShaders\\";

            //Crear loader
            TgcSceneLoader loader = new TgcSceneLoader();

            scene = loader.loadSceneFromFile(MediaDir + "WorkshopShaders\\comborata\\comborata-TgcScene.xml");

            g_pBaseTexture = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\rocks.jpg");
            g_pHeightmap   = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\NM_height_rocks.tga");

            g_pBaseTexture2 = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\stones.bmp");
            g_pHeightmap2   = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\NM_height_stones.tga");

            g_pBaseTexture3 = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\granito.jpg");
            g_pHeightmap3   = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\NM_height_saint.tga");

            g_pBaseTexture4 = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\granito.jpg");
            g_pHeightmap4   = TextureLoader.FromFile(d3dDevice, MediaDir + "Texturas\\NM_four_height.tga");

            foreach (TgcMesh mesh in scene.Meshes)
            {
                if (mesh.Name.Contains("Floor"))
                {
                    rooms.Add(mesh.BoundingBox);
                }
            }

            //Cargar Shader
            string compilationErrors;

            effect = Effect.FromFile(d3dDevice, MyShaderDir + "Parallax.fx", null, null, ShaderFlags.None, null, out compilationErrors);
            if (effect == null)
            {
                throw new Exception("Error al cargar shader. Errores: " + compilationErrors);
            }

            lightDirModifier       = AddVertex3f("LightDir", new TGCVector3(-1, -1, -1), new TGCVector3(1, 1, 1), TGCVector3.Down);
            minSampleModifier      = AddFloat("minSample", 1f, 10f, 10f);
            maxSampleModifier      = AddFloat("maxSample", 11f, 50f, 50f);
            heightMapScaleModifier = AddFloat("HeightMapScale", 0.001f, 0.5f, 0.1f);

            Camara = new TgcFpsCamera(new TGCVector3(147.2558f, 8.0f, 262.2509f), 100f, 10f, Input);
            Camara.SetCamera(new TGCVector3(147.2558f, 8.0f, 262.2509f), new TGCVector3(148.2558f, 8.0f, 263.2509f));

            //Cargar personaje con animaciones
            TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader();
            Random            rnd            = new Random();

            // meto un enemigo por cada cuarto
            cant_enemigos = 0;
            foreach (TgcMesh mesh in scene.Meshes)
            {
                if (mesh.Name.Contains("Floor"))
                {
                    float kx    = rnd.Next(25, 75) / 100.0f;
                    float kz    = rnd.Next(25, 75) / 100.0f;
                    float pos_x = mesh.BoundingBox.PMin.X * kx + mesh.BoundingBox.PMax.X * (1 - kx);
                    float pos_z = mesh.BoundingBox.PMin.Z * kz + mesh.BoundingBox.PMax.Z * (1 - kz);

                    enemigos.Add(skeletalLoader.loadMeshAndAnimationsFromFile(MediaDir + "SkeletalAnimations\\BasicHuman\\" + "CombineSoldier-TgcSkeletalMesh.xml", MediaDir + "SkeletalAnimations\\BasicHuman\\", new string[] { MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "Walk-TgcSkeletalAnim.xml", }));

                    //Configurar animacion inicial
                    enemigos[cant_enemigos].playAnimation("Walk", true);
                    enemigos[cant_enemigos].Position = new TGCVector3(pos_x, 1f, pos_z);
                    enemigos[cant_enemigos].Scale    = new TGCVector3(0.3f, 0.3f, 0.3f);
                    enemigo_an[cant_enemigos]        = 0;
                    cant_enemigos++;
                }
            }

            // levanto el GUI
            float W = D3DDevice.Instance.Width;
            float H = D3DDevice.Instance.Height;

            gui.Create(MediaDir);
            gui.InitDialog(false);
            gui.InsertFrame("Combo Rata", 10, 10, 200, 200, Color.FromArgb(32, 120, 255, 132), frameBorder.sin_borde);
            gui.InsertFrame("", 10, (int)H - 150, 200, 140, Color.FromArgb(62, 120, 132, 255), frameBorder.sin_borde);
            gui.cursor_izq = gui.cursor_der = tipoCursor.sin_cursor;

            // le cambio el font
            gui.font.Dispose();
            // Fonts
            gui.font = new Microsoft.DirectX.Direct3D.Font(d3dDevice, 12, 0, FontWeight.Bold, 0, false, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.DefaultPitch, "Lucida Console");
            gui.font.PreloadGlyphs('0', '9');
            gui.font.PreloadGlyphs('a', 'z');
            gui.font.PreloadGlyphs('A', 'Z');

            gui.RTQ = gui.rectToQuad(0, 0, W, H, 0, 0, W - 150, 160, W - 200, H - 150, 0, H);
        }
Esempio n. 23
0
        /// <summary>
        /// Loads a texture into the texture manager.
        /// </summary>
        /// <param name="fileName">File name of the texture to load.</param>
        /// <param name="colorkey">Transparent color (0 for no color key).  Use Color.FromArgb() then do Color.ToArgb() (Example:  Color.FromArgb(255, 255, 0, 255).ToArgb() for magenta)</param>
        /// <returns>The id for the loaded texture, -1 on failure.</returns>
        public int LoadTexture(string fileName, int colorkey)
        {
            // See if we have loaded the texture before and return its id
            for (int i = 0; i < textures.Count; i++)
            {
                TEXTURE t = (TEXTURE)textures[i];

                if (t.fileName == fileName)
                {
                    return(i);
                }
            }

            // we haven't loaded it before so...
            // look for an open spot
            int id = -1;

            for (int i = 0; i < textures.Count; i++)
            {
                TEXTURE t = (TEXTURE)textures[i];

                if (t.texture == null)
                {
                    id = i;
                    break;
                }
            }

            // if we didn't find an open spot, load it into a new one
            if (id == -1)
            {
                // A temp texture object.
                TEXTURE loaded;

                // Copy the filename of the loaded texture.
                loaded.fileName = fileName;
                loaded.texture  = null;
                loaded.width    = -1;
                loaded.height   = -1;

                try
                {
                    loaded.texture = TextureLoader.FromFile(device, fileName, 0, 0, 1, Usage.None, Format.Unknown, Pool.Managed, Filter.None, Filter.None, colorkey);
                }
                catch (Exception)
                {
                    MessageBox.Show("Failed to load texture: " + fileName, "ManagedTextureManager::Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(-1);
                }

                // Get Width/Height of the texture.
                loaded.width  = loaded.texture.GetSurfaceLevel(0).Description.Width;
                loaded.height = loaded.texture.GetSurfaceLevel(0).Description.Height;

                // Put the texture into the list.
                textures.Add(loaded);

                // Return the id of the texture.
                return(textures.Count - 1);
            }
            // we found an open spot
            else
            {
                TEXTURE t = (TEXTURE)textures[id];

                // Make sure the texture has been released.
                if (t.texture != null)
                {
                    t.texture.Dispose();
                    t.texture = null;
                }

                // Copy the filename of the loaded texture.
                t.fileName = fileName;

                // Load the texture from the given file.
                try
                {
                    t.texture = TextureLoader.FromFile(device, fileName, 0, 0, 1, Usage.None, Format.Unknown, Pool.Managed, Filter.None, Filter.None, colorkey);
                }
                catch (Exception)
                {
                    MessageBox.Show("Failed to load texture: " + fileName, "ManagedTextureManager::Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(-1);
                }

                // Get Width/Height of the texture.
                t.width  = t.texture.GetSurfaceLevel(0).Description.Width;
                t.height = t.texture.GetSurfaceLevel(0).Description.Height;

                textures[id] = t;

                if (!textures[id].Equals(t))
                {
                    MessageBox.Show("theys not equal!!");
                }

                // Return the id of the texture.
                return(id);
            }
        }
Esempio n. 24
0
 public CanvasStage( CanvasAnimatedControl Stage, TextureLoader SharedTextures )
     : this( Stage )
 {
     Stage.CreateResources -= Stage_CreateResources;
     Textures = SharedTextures;
 }
Esempio n. 25
0
        private void frmTest_Load(object sender, System.EventArgs e)
        {
            PresentParameters pp;

            pp                        = new PresentParameters();
            pp.Windowed               = true;               // We don't want to run fullscreen
            pp.SwapEffect             = SwapEffect.Discard; // Discard the frames
            pp.EnableAutoDepthStencil = true;               // Turn on a Depth stencil
            pp.AutoDepthStencilFormat = DepthFormat.D16;    // And the stencil format

            dev = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, pp);
            dev.RenderState.CullMode      = Cull.None;
            dev.RenderState.ZBufferEnable = true;
            dev.RenderState.Lighting      = false;

            //enable alpha blending
            dev.RenderState.AlphaBlendEnable = true;
            dev.RenderState.SourceBlend      = Blend.SourceAlpha;
            dev.RenderState.DestinationBlend = Blend.InvSourceAlpha;
            dev.RenderState.BlendOperation   = BlendOperation.Add;



            vb = new VertexBuffer(typeof(FVF_PosColTex), 25, dev, Usage.SoftwareProcessing, FVF_PosColTex.Format, Pool.Default);
            ib = new IndexBuffer(typeof(short), 28 * 3, dev, Usage.SoftwareProcessing, Pool.Default);


            //defining vertices
            FVF_PosColTex[] verts;
            verts = (FVF_PosColTex[])vb.Lock(0, 0);

            /*
             * verts[0].Pos = new Vector3(0,1,0);
             * verts[1].Pos = new Vector3(1,1,0);
             * verts[2].Pos = new Vector3(0,0,0);
             * verts[3].Pos = new Vector3(1,0,0);
             *
             * verts[0].Col = Color.Red.ToArgb();
             * verts[1].Col = Color.White.ToArgb();
             * verts[2].Col = Color.Red.ToArgb();
             * verts[3].Col = Color.Blue.ToArgb();
             */

            verts[0].Pos  = new Vector3(4, 0, 0);
            verts[1].Pos  = new Vector3(0, 0, 0);
            verts[2].Pos  = new Vector3(1, 0, 0);
            verts[3].Pos  = new Vector3(1, 1, 0);
            verts[4].Pos  = new Vector3(1, 2, 0);
            verts[5].Pos  = new Vector3(2, 0, 0);
            verts[6].Pos  = new Vector3(3, 1, 0);
            verts[7].Pos  = new Vector3(2, 2, 0);
            verts[8].Pos  = new Vector3(2, 3, 0);
            verts[9].Pos  = new Vector3(0, 3, 0);
            verts[10].Pos = new Vector3(1, 4, 0);
            verts[11].Pos = new Vector3(1, 5, 0);
            verts[12].Pos = new Vector3(2, 4, 0);
            verts[13].Pos = new Vector3(3, 5, 0);
            verts[14].Pos = new Vector3(4, 5, 0);
            verts[15].Pos = new Vector3(5, 0, 0);
            verts[16].Pos = new Vector3(5, 1, 0);
            verts[17].Pos = new Vector3(4, 1, 0);
            verts[18].Pos = new Vector3(3, 3, 0);
            verts[19].Pos = new Vector3(4, 4, 0);
            verts[20].Pos = new Vector3(5, 4, 0);
            verts[21].Pos = new Vector3(4, 3, 0);
            verts[22].Pos = new Vector3(5, 3, 0);
            verts[23].Pos = new Vector3(4, 2, 0);
            verts[24].Pos = new Vector3(5, 2, 0);

            for (int i = 0; i <= 24; i++)
            {
                verts[i].Col = Color.FromArgb(255, 255, 255).ToArgb();
            }


            vb.Unlock();


            //defining indices
            short[] indices;
            indices = (short[])ib.Lock(0, 0);

            /*
             * indices[0]=0;indices[1]=1;indices[2]=3;
             * indices[3]=0;indices[3]=3;indices[4]=2;
             */

            indices[0]  = 1; indices[1] = 3; indices[2] = 2;
            indices[3]  = 2; indices[4] = 3; indices[5] = 5;
            indices[6]  = 3; indices[7] = 7; indices[8] = 5;
            indices[9]  = 5; indices[10] = 7; indices[11] = 6;
            indices[12] = 7; indices[13] = 23; indices[14] = 6;
            indices[15] = 23; indices[16] = 17; indices[17] = 6;
            indices[18] = 23; indices[19] = 24; indices[20] = 17;
            indices[21] = 17; indices[22] = 24; indices[23] = 16;
            indices[24] = 17; indices[25] = 16; indices[26] = 0;
            indices[27] = 0; indices[28] = 16; indices[29] = 15;
            indices[30] = 9; indices[31] = 11; indices[32] = 10;
            indices[33] = 9; indices[34] = 10; indices[35] = 8;
            indices[36] = 9; indices[37] = 8; indices[38] = 4;
            indices[39] = 11; indices[40] = 12; indices[41] = 10;
            indices[42] = 10; indices[43] = 12; indices[44] = 18;
            indices[45] = 10; indices[46] = 18; indices[47] = 8;
            indices[48] = 8; indices[49] = 7; indices[50] = 4;
            indices[51] = 8; indices[52] = 18; indices[53] = 7;
            indices[54] = 23; indices[55] = 7; indices[56] = 18;
            indices[57] = 18; indices[58] = 21; indices[59] = 23;
            indices[60] = 21; indices[61] = 24; indices[62] = 23;
            indices[63] = 21; indices[64] = 22; indices[65] = 24;
            indices[66] = 11; indices[67] = 13; indices[68] = 12;
            indices[69] = 12; indices[70] = 13; indices[71] = 18;
            indices[72] = 13; indices[73] = 14; indices[74] = 18;
            indices[75] = 14; indices[76] = 20; indices[77] = 19;
            indices[78] = 20; indices[79] = 21; indices[80] = 19;
            indices[81] = 22; indices[82] = 21; indices[83] = 20;


            ib.Unlock();

            tex = TextureLoader.FromFile(dev, "c:\\test.jpg");

            //////////////////////////////////////////////////////////////

            //div distrib:
            uint[] dd;
            dd     = new uint[25];
            dd[0]  = 2;
            dd[1]  = 2;
            dd[2]  = 2;
            dd[3]  = 2;
            dd[4]  = 0;
            dd[5]  = 2;
            dd[6]  = 1;
            dd[7]  = 1;
            dd[8]  = 0;
            dd[9]  = 0;
            dd[10] = 1;
            dd[11] = 0;
            dd[12] = 0;
            dd[13] = 1;
            dd[14] = 0;
            dd[15] = 2;
            dd[16] = 2;
            dd[17] = 2;
            dd[18] = 1;
            dd[19] = 0;
            dd[20] = 0;
            dd[21] = 0;
            dd[22] = 2;
            dd[23] = 1;
            dd[24] = 2;

            g = new GeometryIndexedSplatted(this.dev, this.vb, this.ib, typeof(FVF_PosColTex), FVF_PosColTex.Format, PrimitiveType.TriangleList, 3, dd);
            g.DivisionTexture[0] = TextureLoader.FromFile(dev, "c:\\t0.jpg");
            g.DivisionTexture[1] = TextureLoader.FromFile(dev, "c:\\t1.jpg");
            g.DivisionTexture[2] = TextureLoader.FromFile(dev, "c:\\t2.jpg");

            g.UpdateDivisionedGeometry();



            this.timer1.Enabled = true;
        }
Esempio n. 26
0
    protected static List <BundleMeshes> ParseBundleMeshes(string raceName)
    {
        var textureLoader  = new TextureLoader();
        var bundleMeshList = new List <BundleMeshes>();

        int substringLength = "Assets/Character_Editor/Prefabs/".Length;

        var meshTypes = new Dictionary <MeshType, string>
        {
            { MeshType.Torso, Meshes.Torso.GetFolderPath(raceName) },
            { MeshType.Beard, Meshes.Beard.GetFolderPath(raceName) },
            { MeshType.FaceFeature, Meshes.FaceFeature.GetFolderPath(raceName) },
            { MeshType.Hair, Meshes.Hair.GetFolderPath(raceName) },
            { MeshType.Helm, Meshes.Helm.GetFolderPath(raceName) },
            { MeshType.TorsoAdd, Meshes.TorsoAdd.GetFolderPath(raceName) },
            { MeshType.LegRight, Meshes.Leg.GetFolderPath(raceName, MeshType.LegRight) },
            { MeshType.LegLeft, Meshes.Leg.GetFolderPath(raceName, MeshType.LegLeft) },
            { MeshType.ShoulderLeft, Meshes.Shoulder.GetFolderPath(raceName, MeshType.ShoulderLeft) },
            { MeshType.ShoulderRight, Meshes.Shoulder.GetFolderPath(raceName, MeshType.ShoulderRight) },
            { MeshType.ArmLeft, Meshes.Arm.GetFolderPath(raceName, MeshType.ArmLeft) },
            { MeshType.ArmRight, Meshes.Arm.GetFolderPath(raceName, MeshType.ArmRight) },
            { MeshType.Belt, Meshes.Belt.GetFolderPath(raceName) },
            { MeshType.BeltAdd, Meshes.BeltAdd.GetFolderPath(raceName) },
            { MeshType.HandLeft, Meshes.Hand.GetFolderPath(raceName, MeshType.HandLeft) },
            { MeshType.HandRight, Meshes.Hand.GetFolderPath(raceName, MeshType.HandRight) },
        };

        foreach (var path in meshTypes)
        {
            var bundleMeshes = new BundleMeshes();
            bundleMeshes.type = path.Key;

            var dirPath = Path.Combine(Application.dataPath, path.Value.Substring(7));
            if (!Directory.Exists(dirPath))
            {
                continue;
            }

            var folders = Directory.GetDirectories(dirPath);

            for (int i = 0; i < folders.Length; i++)
            {
                var bundleMesh = new BundleMesh();

                string gameObjectsPath = folders[i].Substring(Application.dataPath.Length - 6);
                var    meshGUIDs       = AssetDatabase.FindAssets("t:GameObject", new string[]
                {
                    gameObjectsPath + "/StaticModel"
                }
                                                                  );
                if (meshGUIDs.Length == 0)
                {
                    continue;
                }
                var bundleModelPath = AssetDatabase.GUIDToAssetPath(meshGUIDs[0]);

                string bundleName, assetPath;
                ParsePathToBundle(bundleModelPath.Substring(substringLength), out bundleName, out assetPath, 2);
                AssetImporter.GetAtPath(bundleModelPath).SetAssetBundleNameAndVariant(bundleName, "");

                bundleMesh.modelPath = assetPath;

                foreach (var texturePath in textureLoader.ParseTextures(null, gameObjectsPath + "/Textures"))
                {
                    var bundleTexture = new BundleTexture();

                    foreach (var colorPath in texturePath)
                    {
                        ParsePathToBundle(colorPath.Substring(substringLength), out bundleName, out assetPath, 2);
                        AssetImporter.GetAtPath(colorPath).SetAssetBundleNameAndVariant(bundleName, "");

                        var bundleColor = new BundleColor();
                        bundleColor.path = assetPath;
                        bundleTexture.colors.Add(bundleColor);
                    }

                    bundleMesh.textures.Add(bundleTexture);
                }
                bundleMeshes.meshPaths.Add(bundleMesh);
            }
            bundleMeshList.Add(bundleMeshes);
        }
        return(bundleMeshList);
    }
Esempio n. 27
0
        private Bitmap getBitmap(string path)
        {
            PresentParameters pp = new PresentParameters();

            pp.Windowed   = true;
            pp.SwapEffect = SwapEffect.Copy;
            Device device = new Device(0, DeviceType.Hardware, this, CreateFlags.HardwareVertexProcessing, pp);

            Microsoft.DirectX.Direct3D.Texture tx = TextureLoader.FromFile(device, path);

            Microsoft.DirectX.GraphicsStream gs = TextureLoader.SaveToStream(ImageFileFormat.Dib, tx);
            ImageInformation imInfo             = TextureLoader.ImageInformationFromStream(gs);

            Bitmap btmap = new Bitmap(gs);

            btmap.MakeTransparent();

            gs.Seek(0, 0);

            System.Drawing.Imaging.BitmapData bmpData = btmap.LockBits(new Rectangle(0, 0, btmap.Width, btmap.Height),
                                                                       System.Drawing.Imaging.ImageLockMode.ReadWrite,
                                                                       btmap.PixelFormat);

            // Get the address of the first line.
            IntPtr ptr = bmpData.Scan0;

            // Declare an array to hold the bytes of the bitmap.
            int bytes = Math.Abs(bmpData.Stride) * btmap.Height;

            int gsLen = (int)gs.Length;

            byte[] rgbaValues = new byte[bytes];

            byte[] gsBytes = new byte[gsLen];

            gs.Read(gsBytes, 0, gsLen);

            int gsLastI = gsLen - 1;

            // Copy the RGB values into the array.
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbaValues, 0, bytes);
            int i = 0;

            for (int y = 0; y < bmpData.Height; y++)
            {
                for (int x = 0; x < bmpData.Width; x++)
                {
                    byte g = gsBytes[gsLastI - i++],
                         b = gsBytes[gsLastI - i++],
                         a = gsBytes[gsLastI - i++],
                         r = gsBytes[gsLastI - i++];

                    if (invertAlpha.Checked)
                    {
                        a = (byte)(255 - a);
                    }

                    Color pClr = Color.FromArgb(a, r, g, b);

                    System.Runtime.InteropServices.Marshal.WriteInt32(bmpData.Scan0, (bmpData.Stride * y) + (4 * x), pClr.ToArgb());
                }
            }

            btmap.UnlockBits(bmpData);

            btmap.RotateFlip(RotateFlipType.Rotate180FlipY);

            return(btmap);
        }
Esempio n. 28
0
        static void Main()
        {
            Application.SetCompatibleTextRenderingDefault(false);
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();

            var texturePathA = Path.Combine(Path.GetDirectoryName(AppContext.BaseDirectory), "a.png");
            var texturePathB = Path.Combine(Path.GetDirectoryName(AppContext.BaseDirectory), "b.png");
            var textureDataA = File.ReadAllBytes(texturePathA);
            var textureDataB = File.ReadAllBytes(texturePathB);
            var vertexShader = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(AppContext.BaseDirectory), "VertexShader.cso"));
            var pixelShader  = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(AppContext.BaseDirectory), "PixelShader.cso"));

            using var form  = new Form();
            using var scene = new Scene3D();

#if DEBUG
            scene.EnableDebug();
#endif
            scene.Initialize(form.Handle, 0.0f, 0.0f, form.Size.Width, form.Size.Height);
            float w       = 1600;
            float h       = 450;
            var   indices = new ushort[6] {
                0, 1, 2, 0, 2, 3
            };
            var vertices = new Vertex[4]
            {
                new Vertex()
                {
                    Position = new Vector3F32(),
                    Normal   = new Vector3F32 {
                        Z = 1.0f
                    },
                    TexCoord = new Vector2F32 {
                        X = 0.0f, Y = 1.0f
                    }
                },
                new Vertex()
                {
                    Position = new Vector3F32 {
                        X = w
                    },
                    Normal = new Vector3F32 {
                        Z = 1.0f
                    },
                    TexCoord = new Vector2F32 {
                        X = 2.0f, Y = 1.0f
                    }
                },
                new Vertex()
                {
                    Position = new Vector3F32 {
                        X = w, Y = h
                    },
                    Normal = new Vector3F32 {
                        Z = 1.0f
                    },
                    TexCoord = new Vector2F32 {
                        X = 2.0f, Y = 0.0f
                    }
                },
                new Vertex()
                {
                    Position = new Vector3F32 {
                        Y = h
                    },
                    Normal = new Vector3F32 {
                        Z = 1.0f
                    },
                    TexCoord = new Vector2F32()
                }
            };
            var textureMatrixX = stackalloc float[9];
            var textureMatrixY = stackalloc float[12];
            var color          = stackalloc float[4] {
                0.0f,
                0.0f,
                0.0f,
                0.0f,
            };

            textureMatrixX[0] = textureMatrixX[4] = textureMatrixX[8] = 1.0f;
            textureMatrixY[0] = textureMatrixY[5] = textureMatrixY[10] = 1.0f;


            var inputs = new List <InputElement>()
            {
                new InputElement()
                {
                    SemanticName         = "POS",
                    SemanticIndex        = 0,
                    Format               = Format.R32G32B32Float,
                    InputSolt            = 0,
                    AlignedByteOffset    = InputElement.AppendAlignedElement,
                    InputSlotClass       = InputClassification.PerVertexData,
                    InstanceDataStepRate = 0
                },
                new InputElement()
                {
                    SemanticName         = "NORMAL",
                    SemanticIndex        = 0,
                    Format               = Format.R32G32B32Float,
                    InputSolt            = 0,
                    AlignedByteOffset    = InputElement.AppendAlignedElement,
                    InputSlotClass       = InputClassification.PerVertexData,
                    InstanceDataStepRate = 0
                },
                new InputElement()
                {
                    SemanticName         = "TEXCOORD",
                    SemanticIndex        = 0,
                    Format               = Format.R32G32Float,
                    InputSolt            = 0,
                    AlignedByteOffset    = InputElement.AppendAlignedElement,
                    InputSlotClass       = InputClassification.PerVertexData,
                    InstanceDataStepRate = 0
                },
                new InputElement()
                {
                    SemanticName         = "TEXMATRIX",
                    SemanticIndex        = 0,
                    Format               = Format.R32G32B32Float,
                    InputSolt            = 1,
                    AlignedByteOffset    = InputElement.AppendAlignedElement,
                    InputSlotClass       = InputClassification.PerInstanceData,
                    InstanceDataStepRate = 0
                },
                new InputElement()
                {
                    SemanticName         = "TEXMATRIX",
                    SemanticIndex        = 1,
                    Format               = Format.R32G32B32Float,
                    InputSolt            = 1,
                    AlignedByteOffset    = InputElement.AppendAlignedElement,
                    InputSlotClass       = InputClassification.PerInstanceData,
                    InstanceDataStepRate = 0
                },
                new InputElement()
                {
                    SemanticName         = "TEXMATRIX",
                    SemanticIndex        = 2,
                    Format               = Format.R32G32B32Float,
                    InputSolt            = 1,
                    AlignedByteOffset    = InputElement.AppendAlignedElement,
                    InputSlotClass       = InputClassification.PerInstanceData,
                    InstanceDataStepRate = 0
                }
            };

            using var index        = new MemoryIndex <ushort>(scene, indices);
            using var attribute1   = new MemoryAttribute <Vertex>(scene, vertices, (uint) sizeof(Vertex));
            using var attribute2   = new DX.Sharp.Attribute(scene, textureMatrixX, 4, 9, 36);
            using var constant     = new Constant(scene, textureMatrixY, 4, 12);
            using var constant2    = new Constant(scene, color, 4, 4);
            using var textureHeap1 = new DescriptorHeap(scene.Device, 2);
            using var textureHeap2 = new DescriptorHeap(scene.Device, 2);
            using var samplerHeap  = new DescriptorHeap(scene.Device, DescriptorHeapType.Sampler, DescriptorHeapFlags.ShaderVisible, 1);
            using var effect       = new Effect3D(inputs, new Constant[] { constant2 }, 1, 2, 1);
            using var loader       = new TextureLoader(scene.Device, scene.CommandQueue);

            effect.Initialize(scene, vertexShader, pixelShader, ref BlendDescription.Opaque, ref DepthStencilDescription.Default, ref RasteriazerDescription.Default, Format.B8G8R8A8UNorm, Format.D32Float);

            var textures = new List <Resource>()
            {
                new Resource(),
                new Resource()
            };


            scene.Device.CreateSampler(ref SamplerDescrption.LinearWrap, samplerHeap.GetCpuHandle(0));

            loader.Begin();
            loader.CreateTexture(textureDataA, textures[0]);
            loader.CreateShaderResourceView(textures[0], textureHeap1.GetCpuHandle(0));
            loader.CreateShaderResourceView(textures[0], textureHeap2.GetCpuHandle(1));
            loader.CreateTexture(textureDataB, textures[1]);
            loader.CreateShaderResourceView(textures[1], textureHeap1.GetCpuHandle(1));
            loader.CreateShaderResourceView(textures[1], textureHeap2.GetCpuHandle(0));
            loader.End();


            using var obj1 = new Object3D(new List <DX.Sharp.Attribute> { attribute1, attribute2 }, index, new List <Constant> { constant }, effect, textureHeap1, samplerHeap);
            using var obj2 = new Object3D(new List <DX.Sharp.Attribute> { attribute1, attribute2 }, index, new List <Constant> { constant }, effect, textureHeap2, samplerHeap);

            obj1.Initialize(scene);
            obj2.Initialize(scene);

            scene.SetRenderList(new List <Object3D> {
                obj1, obj2
            });
            using var transform = new XMMatrix();
            var minimized = false;

            scene.SetInactiveTargetUpdateTimeout(true, 1.0 / 30);

            form.Resize += (sender, e) =>
            {
                if (form.WindowState == FormWindowState.Minimized)
                {
                    scene.OnSuspending();
                    minimized = true;
                }
                else if (minimized)
                {
                    scene.OnResuming();
                    minimized = false;
                }

                scene.OnWindowSizeChanged(0.0f, 0.0f, form.Size.Width, form.Size.Height);
                scene.Tick();
            };

            form.Activated += (sender, e) =>
            {
                scene.OnActivated();
            };

            form.Deactivate += (sender, e) =>
            {
                scene.OnDeactivated();
            };

            uint  count      = 0;
            float scale      = 1;
            float step       = 0.01f;
            float angle      = 0;
            float angleStep  = 1;
            var   random     = new Random();
            var   viewMatrix = new XMMatrix();

            scene.OnUpdate += (scene, second, frame) =>
            {
                if (frame > 1)
                {
                    scale += step;
                    angle += angleStep;
                    count++;
                }

                if (angle > 360)
                {
                    angle -= 360;
                }

                if (scale > 1.0f || scale < 0.1)
                {
                    step = -step;
                }

                textureMatrixX[0] = scale;
                textureMatrixY[5] = scale;

                if (count == 10)
                {
                    count    = 0;
                    color[0] = (float)random.NextDouble();
                    color[1] = (float)random.NextDouble();
                    color[2] = (float)random.NextDouble();
                    color[3] = (float)random.NextDouble();
                }

                attribute2.Update(textureMatrixX);
                constant.Update(textureMatrixY);
                constant2.Update(color);

                Transform(transform, scene.Viewport, angle, scale, w, h);
                obj1.UpdateModelView(transform, viewMatrix);

                Transform(transform, scene.Viewport, angle * 2, scale, w, h);
                obj2.UpdateModelView(transform, viewMatrix);
            };

            RenderLoop.Run(form, scene.Tick);
        }
Esempio n. 29
0
    public static Material[] LoadMTLFile(string fn)
    {
        Material        currentMaterial  = null;
        List <Material> matlList         = new List <Material>();
        FileInfo        mtlFileInfo      = new FileInfo(fn);
        string          baseFileName     = Path.GetFileNameWithoutExtension(fn);
        string          mtlFileDirectory = mtlFileInfo.Directory.FullName + Path.DirectorySeparatorChar;

        foreach (string ln in File.ReadAllLines(fn))
        {
            string   l    = ln.Trim().Replace("  ", " ");
            string[] cmps = l.Split(' ');
            string   data = l.Remove(0, l.IndexOf(' ') + 1);

            if (cmps[0] == "mtl")
            {
                if (currentMaterial != null)
                {
                    matlList.Add(currentMaterial);
                }
                currentMaterial      = new Material(Shader.Find("Standard (Specular setup)"));
                currentMaterial.name = data;
            }
            else if (cmps[0] == "Kd")
            {
                currentMaterial.SetColor("_Color", ParseColorFromCMPS(cmps));
            }
            else if (cmps[0] == "map_Kd")
            {
                //TEXTURE
                string fpth = OBJGetFilePath(data, mtlFileDirectory, baseFileName);
                if (fpth != null)
                {
                    currentMaterial.SetTexture("_MainTex", TextureLoader.LoadTexture(fpth));
                }
            }
            else if (cmps[0] == "map_Bump")
            {
                //TEXTURE
                string fpth = OBJGetFilePath(data, mtlFileDirectory, baseFileName);
                if (fpth != null)
                {
                    currentMaterial.SetTexture("_BumpMap", TextureLoader.LoadTexture(fpth, true));
                    currentMaterial.EnableKeyword("_NORMALMAP");
                }
            }
            else if (cmps[0] == "Ks")
            {
                currentMaterial.SetColor("_SpecColor", ParseColorFromCMPS(cmps));
            }
            else if (cmps[0] == "Ka")
            {
                currentMaterial.SetColor("_EmissionColor", ParseColorFromCMPS(cmps, 0.05f));
                currentMaterial.EnableKeyword("_EMISSION");
            }
            else if (cmps[0] == "d")
            {
                float visibility = float.Parse(cmps[1]);
                if (visibility < 1)
                {
                    Color temp = currentMaterial.color;

                    temp.a = visibility;
                    currentMaterial.SetColor("_Color", temp);

                    //TRANSPARENCY ENABLER
                    currentMaterial.SetFloat("_Mode", 3);
                    currentMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                    currentMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                    currentMaterial.SetInt("_ZWrite", 0);
                    currentMaterial.DisableKeyword("_ALPHATEST_ON");
                    currentMaterial.EnableKeyword("_ALPHABLEND_ON");
                    currentMaterial.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                    currentMaterial.renderQueue = 3000;
                }
            }
            else if (cmps[0] == "Ns")
            {
                float Ns = float.Parse(cmps[1]);
                Ns = (Ns / 1000);
                currentMaterial.SetFloat("_Glossiness", Ns);
            }
        }
        if (currentMaterial != null)
        {
            matlList.Add(currentMaterial);
        }
        return(matlList.ToArray());
    }
        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            if (objectToEdit == null)
            {
                objectToEdit = new SpotLight();
            }

            SpotLight obj = objectToEdit as SpotLight;

            obj.BaseObjectId   = txtBaseObjectId.Text;
            obj.BaseObjectName = txtBaseObjectName.Text;

            //custom code
            String haloTexName = haloToLoad.Content != null?haloToLoad.Content.ToString() : "";

            if (string.IsNullOrEmpty(haloTexName))
            {
                obj.HaloSRV         = null;
                obj.HaloTextureName = null;
            }
            else
            {
                obj.HaloSRV         = TextureLoader.LoadTexture("flares/" + haloTexName);
                obj.HaloTextureName = haloTexName;
            }

            String maskTexName = maskToLoad.Content != null?maskToLoad.Content.ToString() : "";

            if (string.IsNullOrEmpty(maskTexName))
            {
                obj.LightMaskSRV         = null;
                obj.LightMaskTextureName = null;
            }
            else
            {
                obj.LightMaskSRV         = TextureLoader.LoadCubeTexture("fx/" + maskTexName);
                obj.LightMaskTextureName = maskTexName;
            }

            String mapTexName = mapToLoad.Content != null?mapToLoad.Content.ToString() : "";

            if (string.IsNullOrEmpty(mapTexName))
            {
                obj.LightMapSRV         = null;
                obj.LightMapTextureName = null;
            }
            else
            {
                obj.LightMapSRV         = TextureLoader.LoadCubeTexture("fx/" + mapTexName);
                obj.LightMapTextureName = mapTexName;
            }
            //custom code end

            obj.Category = objCategory;
            bool success = isEditingObj ? WorldData.UpdateObject(obj) : WorldData.AddObject(obj);

            if (!success)
            {
                MessageBox.Show(Application.Current.MainWindow, "ID already exists", "AddObject Failure", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.Cancel);
            }
            else
            {
                this.Close();
                if (parentWindow != null)
                {
                    parentWindow.Refresh();
                }
            }
        }
Esempio n. 31
0
 public RenderTextureComponent(Bitmap image, Box2D rect) :
     this(TextureLoader.FromBitmap(image), rect)
 {
 }
Esempio n. 32
0
 public void Initialize()
 {
     if (Buttonareas.Count() == 0)
     {
         Rectangle djastinButtonArea = new Rectangle(0, 0, 400, 300);
         Rectangle rutgerButtonArea = new Rectangle(0, 300, 400, 300);
         Rectangle gideonButtonArea = new Rectangle(400, 0, 400, 300);
         Rectangle danielButtonArea = new Rectangle(400, 300, 400, 300);
         Rectangle gameOverButtonArea = new Rectangle(300, 300, 200, 100);
         Buttonareas.Add("djastinButton", djastinButtonArea);
         Buttonareas.Add("rutgerButton", rutgerButtonArea);
         Buttonareas.Add("gideonButton", gideonButtonArea);
         Buttonareas.Add("danielButton", danielButtonArea);
         Buttonareas.Add("gameOverButton", gameOverButtonArea);
         _textureLoader = TextureLoader.GetInstance();
         _cijfernariumTexture = _textureLoader.GetTexture("startMenuCijfernarium");
         _starbucksalandoriumTexture = _textureLoader.GetTexture("startMenuStarbucks");
         _crackenariumTexture = _textureLoader.GetTexture("startMenuCrackenarium");
         _kloonwereldTexture = _textureLoader.GetTexture("startMenuKloonwereld");
         _cijfernariumTextureHighlighted = _textureLoader.GetTexture("startMenuCijfernariumHighlighted");
         StarbucksalandoriumTextureHighlighted = _textureLoader.GetTexture("startMenuStarbucksHighlighted");
         _crackenariumTextureHighlighted = _textureLoader.GetTexture("startMenuCrackenariumHighlighted");
         _kloonwereldTextureHighlighted = _textureLoader.GetTexture("startMenuKloonwereldHighlighted");
         _gameOverButtonHighlighted = _textureLoader.GetTexture("gameOverButtonHighlighted");
         _gameOverButton = _textureLoader.GetTexture("gameOverButton");
         _front = _textureLoader.GetTexture("startMenuBackgroundEmpty");
         _showGameOver = false;
     }
 }
Esempio n. 33
0
        public void LoadContent(ContentManager Content)
        {
            Textures = TextureLoader.TextureList("Content/findcouple/textures");
            #region board
            int x = 0, y = 0, value = 1;
            while (HasEmptySpot(board, 4, 4))
            {
                value = r.Next(0, 7);
first:
                {
                    x = r.Next(0, 4);
                    y = r.Next(0, 4);
                    if (board[x, y] == 0)
                    {
                        board[x, y] = value;
                    }
                    else
                    {
                        goto first;
                    }
                }
second:
                {
                    x = r.Next(0, 4);
                    y = r.Next(0, 4);
                    if (board[x, y] == 0)
                    {
                        board[x, y] = value;
                    }
                    else
                    {
                        goto second;
                    }
                }
            }
            #endregion
            #region tiles
            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    if (board[i, j] == 1)
                    {
                        textBuffer = "bilgisayar";
                    }
                    else if (board[i, j] == 2)
                    {
                        textBuffer = "fare";
                    }
                    else if (board[i, j] == 3)
                    {
                        textBuffer = "hoparlor";
                    }
                    else if (board[i, j] == 4)
                    {
                        textBuffer = "televizyon";
                    }
                    else if (board[i, j] == 5)
                    {
                        textBuffer = "tablet";
                    }
                    else if (board[i, j] == 6)
                    {
                        textBuffer = "telefon";
                    }

                    Objects.Add(new GameObject(new Vector2(((i + 2) * 107) - 53, j * 115), textBuffer, "findcouple", Content));
                }
            }
            #endregion
            foreach (GameObject g in Objects)
            {
                g.AssignSecondTexture("kapali");
                g.SwitchToSecond();
            }
        }
Esempio n. 34
0
        public override void Init()
        {
            //Cargar textura de CubeMap para Environment Map, fijo para todos los meshes
            cubeMap = TextureLoader.FromCubeFile(D3DDevice.Instance.Device, MediaDir + "CubeMap.dds");

            //Cargar Shader personalizado de EnvironmentMap
            effect = TGCShaders.Instance.LoadEffect(ShadersDir + "EnvironmentMap.fx");

            //Cargar escenario, pero inicialmente solo hacemos el parser, para separar los objetos que son solo luces y no meshes
            var scenePath = MediaDir + "NormalMapRoom\\NormalMapRoom-TgcScene.xml";
            var mediaPath = MediaDir + "NormalMapRoom\\";
            var parser    = new TgcSceneParser();
            var sceneData = parser.parseSceneFromString(File.ReadAllText(scenePath));

            //Separar modelos reales de las luces, segun layer "Lights"
            lights = new List <LightData>();
            var realMeshData = new List <TgcMeshData>();

            for (var i = 0; i < sceneData.meshesData.Length; i++)
            {
                var meshData = sceneData.meshesData[i];

                //Es una luz, no cargar mesh, solo importan sus datos
                if (meshData.layerName == "Lights")
                {
                    //Guardar datos de luz
                    var light = new LightData();
                    light.color = Color.FromArgb((int)meshData.color[0], (int)meshData.color[1], (int)meshData.color[2]);
                    light.aabb  = new TgcBoundingAxisAlignBox(TGCVector3.Float3ArrayToVector3(meshData.pMin), TGCVector3.Float3ArrayToVector3(meshData.pMax));
                    light.pos   = light.aabb.calculateBoxCenter();
                    lights.Add(light);
                }
                //Es un mesh real, agregar a array definitivo
                else
                {
                    realMeshData.Add(meshData);
                }
            }

            //Reemplazar array original de meshData de sceneData por el definitivo
            sceneData.meshesData = realMeshData.ToArray();

            //Ahora si cargar meshes reales
            var loader = new TgcSceneLoader();
            var scene  = loader.loadScene(sceneData, mediaPath);

            //Separar meshes con bumpMapping de los comunes
            bumpMeshes   = new List <TgcMeshBumpMapping>();
            commonMeshes = new List <TgcMesh>();
            foreach (var mesh in scene.Meshes)
            {
                //Mesh con BumpMapping
                if (mesh.Layer == "BumpMap")
                {
                    //Por convencion de este ejemplo el NormalMap se llama igual que el DiffuseMap (y cada mesh tiene una sola)
                    var path  = mesh.DiffuseMaps[0].FilePath;
                    var split = path.Split('.');
                    path = split[0] + "_NormalMap.png";

                    //Convertir TgcMesh a TgcMeshBumpMapping
                    var          normalMap      = TgcTexture.createTexture(path);
                    TgcTexture[] normalMapArray = { normalMap };
                    var          bumpMesh       = TgcMeshBumpMapping.fromTgcMesh(mesh, normalMapArray);
                    bumpMesh.Effect    = effect;
                    bumpMesh.Technique = "EnvironmentMapTechnique";
                    bumpMeshes.Add(bumpMesh);

                    //Liberar original
                    mesh.Dispose();
                }
                //Mesh normal
                else
                {
                    commonMeshes.Add(mesh);
                }
            }

            //Camara en 1ra persona
            Camara = new TgcFpsCamera(new TGCVector3(0, 50, 100), Input);

            //Modifiers
            reflectionModifier       = AddFloat("reflection", 0, 1, 0.2f);
            bumpinessModifier        = AddFloat("bumpiness", 0, 2, 1f);
            lightIntensityModifier   = AddFloat("lightIntensity", 0, 150, 20);
            lightAttenuationModifier = AddFloat("lightAttenuation", 0.1f, 2, 0.3f);
            specularExModifier       = AddFloat("specularEx", 0, 20, 9f);

            mEmissiveModifier = AddColor("mEmissive", Color.Black);
            mAmbientModifier  = AddColor("mAmbient", Color.White);
            mDiffuseModifier  = AddColor("mDiffuse", Color.White);
            mSpecularModifier = AddColor("mSpecular", Color.White);
        }
Esempio n. 35
0
        public override void Render()
        {
            PreRender();

            //Triangulo 1 se corre para la izquierda.
            //Como tenemos un triangulo con textura y estamos haciendo una Draw primitive tenemos el problema de bingind de texturuas.
            //D3DDevice.Instance.Device.SetTextureStageState(0, TextureStageStates.ColorOperation, true);
            //D3DDevice.Instance.Device.SetTextureStageState(0, TextureStageStates.AlphaOperation, true);
            //FIX IT!!!!!
            //al realizar el clean nos aseguramos que este triangulo no tendra la textura que tiene el otro.

            //Especificar formato de triangulo
            D3DDevice.Instance.Device.VertexFormat    = CustomVertex.PositionColored.Format;
            D3DDevice.Instance.Device.Transform.World = Matrix.Translation(-2.5f, 0, 0);
            //Dibujar 1 primitiva (nuestro triangulo)
            D3DDevice.Instance.Device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, simpleTriangleData);

            //Triangulo 2 centro.
            //Ver si cambio la textura
            var selectedTexture = (string)Modifiers["Texture image"];

            if (currentTexurePah != selectedTexture)
            {
                currentTexurePah = selectedTexture;
                texture          = TextureLoader.FromFile(D3DDevice.Instance.Device, currentTexurePah);
            }

            //Crear triangulo segun datos del usuario
            var data = new CustomVertex.PositionColoredTextured[3];

            //vertice 1
            var v1 = (Vector3)Modifiers["vertex1"];
            var t1 = (Vector2)Modifiers["texCoord1"];

            data[0] = new CustomVertex.PositionColoredTextured(
                v1.X,
                v1.Y,
                v1.Z,
                ((Color)Modifiers["color1"]).ToArgb(),
                t1.X,
                t1.Y);

            //vertice 2
            var v2 = (Vector3)Modifiers["vertex2"];
            var t2 = (Vector2)Modifiers["texCoord2"];

            data[1] = new CustomVertex.PositionColoredTextured(
                v2.X,
                v2.Y,
                v2.Z,
                ((Color)Modifiers["color2"]).ToArgb(),
                t2.X,
                t2.Y);

            //vertice 3
            var v3 = (Vector3)Modifiers["vertex3"];
            var t3 = (Vector2)Modifiers["texCoord3"];

            data[2] = new CustomVertex.PositionColoredTextured(
                v3.X,
                v3.Y,
                v3.Z,
                ((Color)Modifiers["color3"]).ToArgb(),
                t3.X,
                t3.Y);

            //Rotacion
            var rotation = (float)Modifiers["rotation"];

            D3DDevice.Instance.Device.Transform.World = Matrix.Identity * Matrix.RotationY(rotation);

            //Habilitar textura
            var textureEnable = (bool)Modifiers["TextureEnable"];

            if (textureEnable)
            {
                D3DDevice.Instance.Device.SetTexture(0, texture);
            }
            else
            {
                D3DDevice.Instance.Device.SetTexture(0, null);
            }

            //Render triangulo
            D3DDevice.Instance.Device.VertexFormat = CustomVertex.PositionColoredTextured.Format;
            D3DDevice.Instance.Device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, data);

            //Triangulo 3 se corre a la derecha.
            //Especificar formato de triangulos
            D3DDevice.Instance.Device.VertexFormat = CustomVertex.PositionColored.Format;
            //Cargar VertexBuffer a renderizar
            D3DDevice.Instance.Device.SetStreamSource(0, vertexBuffer, 0);
            D3DDevice.Instance.Device.Transform.World = Matrix.Translation(2.5f, 0, 0);
            //Dibujar 1 primitiva
            D3DDevice.Instance.Device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);

            PostRender();
        }
Esempio n. 36
0
        public override void Init()
        {
            #region variables
            TgcMesh flecha;
            TgcMesh tumba;

            TgcScene roquedal;
            TgcScene roquedal2;
            TgcScene muelle1;
            #endregion

            var d3dDevice = D3DDevice.Instance.Device;
            efecto = TgcShaders.loadEffect(GameModel.shadersDir + "shaderPlanta.fx");

            cubemap = TextureLoader.FromCubeFile(d3dDevice, GameModel.mediaDir + "texturas\\skybox\\cube2018.dds");

            var loader = new TgcSceneLoader();

            #region muelles
            //muelle1 = loader.loadSceneFromFile(GameModel.mediaDir + "modelos\\muelleGrande-TgcScene.xml");
            //foreach (TgcMesh mesh in muelle1.Meshes)
            //{
            //    mesh.Scale = new TGCVector3(25.5f, 25.5f, 25.5f);
            //    mesh.Position = new TGCVector3(0, 260f, mesh.Position.Z + 500f);
            //    mesh.Effect = efecto;
            //    mesh.Technique = "RenderScene";
            //    obtenerPminYPmax(mesh.BoundingBox.PMin, mesh.BoundingBox.PMax);
            //}
            //meshes.AddRange(muelle1.Meshes);
            #endregion

            #region piedras
            roquedal = loader.loadSceneFromFile(GameModel.mediaDir + "modelos\\ROQUEDAL-TgcScene.xml");
            foreach (TgcMesh mesh in roquedal.Meshes)
            {
                mesh.Scale     = new TGCVector3(90.5f, 90.5f, 90.5f);
                mesh.Position  = new TGCVector3(mesh.Position.X - 1000f, 10f, mesh.Position.Z + 5500f);
                mesh.Effect    = efecto;
                mesh.Technique = "RenderScene";
                obtenerPminYPmax(mesh.BoundingBox.PMin, mesh.BoundingBox.PMax);
            }
            meshes.AddRange(roquedal.Meshes);

            roquedal2 = loader.loadSceneFromFile(GameModel.mediaDir + "modelos\\ROQUEDAL-TgcScene.xml");
            foreach (TgcMesh mesh in roquedal2.Meshes)
            {
                mesh.Scale    = new TGCVector3(90.5f, 90.5f, 90.5f);
                mesh.Position = new TGCVector3(mesh.Position.X + 5500f, 10f, mesh.Position.Z + 5500f);
                mesh.RotateY(90);
                mesh.Effect    = efecto;
                mesh.Technique = "RenderScene";
                obtenerPminYPmax(mesh.BoundingBox.PMin, mesh.BoundingBox.PMax);
            }
            meshes.AddRange(roquedal2.Meshes);
            #endregion

            #region otros
            tumba           = new TgcSceneLoader().loadSceneFromFile(GameModel.mediaDir + "modelos\\Tumbas-TgcScene.xml").Meshes[0];
            tumba.Scale     = new TGCVector3(52.5f, 52.5f, 52.5f);
            tumba.Effect    = efecto;
            tumba.Technique = "RenderScene";
            tumba.Position  = new TGCVector3(1900, 280f, 6500f);

            obtenerPminYPmax(tumba.BoundingBox.PMin, tumba.BoundingBox.PMax);
            meshes.Add(tumba);

            tumba           = new TgcSceneLoader().loadSceneFromFile(GameModel.mediaDir + "modelos\\Tumbas-TgcScene.xml").Meshes[0];
            tumba.Scale     = new TGCVector3(52.5f, 54, 52.5f);
            tumba.Effect    = efecto;
            tumba.Technique = "RenderScene";
            tumba.Position  = new TGCVector3(2000, 290f, 6405f);
            obtenerPminYPmax(tumba.BoundingBox.PMin, tumba.BoundingBox.PMax);
            meshes.Add(tumba);

            tumba           = new TgcSceneLoader().loadSceneFromFile(GameModel.mediaDir + "modelos\\Tumbas-TgcScene.xml").Meshes[0];
            tumba.Scale     = new TGCVector3(50.5f, 52.5f, 50.5f);
            tumba.Effect    = efecto;
            tumba.Technique = "RenderScene";
            tumba.Position  = new TGCVector3(1840, 320f, 6700f);
            tumba.RotateY(1);
            obtenerPminYPmax(tumba.BoundingBox.PMin, tumba.BoundingBox.PMax);
            meshes.Add(tumba);

            tumba           = new TgcSceneLoader().loadSceneFromFile(GameModel.mediaDir + "modelos\\Tumbas-TgcScene.xml").Meshes[0];
            tumba.Scale     = new TGCVector3(57.5f, 52.5f, 57.5f);
            tumba.Effect    = efecto;
            tumba.Technique = "RenderScene";
            tumba.Position  = new TGCVector3(2600, 320f, 6910f);
            tumba.RotateY(2);
            obtenerPminYPmax(tumba.BoundingBox.PMin, tumba.BoundingBox.PMax);
            meshes.Add(tumba);

            tumba           = new TgcSceneLoader().loadSceneFromFile(GameModel.mediaDir + "modelos\\Tumbas-TgcScene.xml").Meshes[0];
            tumba.Scale     = new TGCVector3(52.5f, 52.5f, 52.5f);
            tumba.Effect    = efecto;
            tumba.Technique = "RenderScene";
            tumba.Position  = new TGCVector3(2920, 340f, 6200f);
            tumba.RotateY(1);
            obtenerPminYPmax(tumba.BoundingBox.PMin, tumba.BoundingBox.PMax);
            meshes.Add(tumba);

            flecha          = new TgcSceneLoader().loadSceneFromFile(GameModel.mediaDir + "modelos\\Flecha-TgcScene.xml").Meshes[0];
            flecha.Scale    = new TGCVector3(320.5f, 320.5f, 320.5f);
            flecha.Position = new TGCVector3(0, 450f, 4800f);
            flecha.RotateY(150);
            flecha.RotateZ(150);
            flecha.Effect    = efecto;
            flecha.Technique = "RenderScene";
            obtenerPminYPmax(flecha.BoundingBox.PMin, flecha.BoundingBox.PMax);
            meshes.Add(flecha);
            #endregion

            //efecto.SetValue("texCubeMap", cubemap);
            //tubo = new TgcSceneLoader().loadSceneFromFile(GameModel.mediaDir + "modelos\\TUBO_MARIO-TgcScene.xml").Meshes[0];
            //tubo.Scale = new TGCVector3(35.5f, 35.5f, 35.5f);
            //tubo.Position = new TGCVector3(1500f, 350f, 1500f);
            //tubo.Effect = efecto;
            //tubo.Technique = "cube";
            //obtenerPminYPmax(tubo.BoundingBox.PMin, tubo.BoundingBox.PMax);
            //meshes.Add(tubo);

            #region  crearOctree
            octree.create(meshes, new TgcBoundingAxisAlignBox(pmin, pmax));
            octree.createDebugOctreeMeshes();
            #endregion
        }
Esempio n. 37
0
		public Atlas (List<AtlasPage> pages, List<AtlasRegion> regions) {
			this.pages = pages;
			this.regions = regions;
			this.textureLoader = null;
		}
Esempio n. 38
0
        public void render(float tiempo)
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

            string selectedTexture = (string)GuiController.Instance.Modifiers["texture"];

            if (currentTexurePah != selectedTexture)
            {
                texture = TextureLoader.FromFile(d3dDevice, selectedTexture);
            }
            float selectedDistancia_verices = (float)GuiController.Instance.Modifiers["distancia_verices"];

            if (distancia_verices != selectedDistancia_verices)
            {
                distancia_verices = selectedDistancia_verices;
                vertices          = crearMatriz();
            }
            amplitud   = (float)GuiController.Instance.Modifiers["amplitud"];
            frecuencia = (float)GuiController.Instance.Modifiers["frecuencia"];
            efecto     = (string)GuiController.Instance.Modifiers["efectos"];
            velocidad  = (float)GuiController.Instance.Modifiers["velocidad"];

            vertices = this.crearMovimiento(tiempo);
            this.crearVertices();

            //Almacenar información en VertexBuffer
            vertexBuffer.SetData(data, 0, LockFlags.None);
            indexBuffer.SetData(indice, 0, LockFlags.None);

            d3dDevice.Transform.World = Matrix.Identity;
            //d3dDevice.VertexDeclaration = GuiController.Instance.Shaders.VdecPositionTextured;
            effect.Technique = technique;
            GuiController.Instance.Shaders.setShaderMatrix(effect, Matrix.Identity);
            effect.SetValue("texDiffuseMap", texture);
            effect.SetValue("lightColor", ColorValue.FromColor((Color)Color.White));

            //effect.SetValue("fvLightPosition", TgcParserUtils.vector3ToFloat4Array(new Vector3(0, 100, -200)));
            //effect.SetValue("fvEyePosition", TgcParserUtils.vector3ToFloat4Array(GuiController.Instance.FpsCamera.getPosition()));
            effect.SetValue("lightPosition", TgcParserUtils.vector3ToFloat4Array(new Vector3(0, 100, -200)));
            effect.SetValue("eyePosition", TgcParserUtils.vector3ToFloat4Array(GuiController.Instance.FpsCamera.getPosition()));

            //CubeMap
            effect.SetValue("texCubeMap", cubeMap);
            effect.SetValue("lightIntensity", 10f);
            effect.SetValue("lightAttenuation", 0.3f);
            if ((bool)GuiController.Instance.Modifiers["reflection"])
            {
                effect.SetValue("reflection", 0.5f);
            }
            else
            {
                effect.SetValue("reflection", 0f);
            }
            //Cargar variables de shader de Material. El Material en realidad deberia ser propio de cada mesh. Pero en este ejemplo se simplifica con uno comun para todos
            effect.SetValue("materialEmissiveColor", ColorValue.FromColor((Color)Color.Black));
            effect.SetValue("materialAmbientColor", ColorValue.FromColor((Color)Color.White));
            effect.SetValue("materialDiffuseColor", ColorValue.FromColor((Color)Color.White));
            effect.SetValue("materialSpecularColor", ColorValue.FromColor((Color)Color.White));
            effect.SetValue("materialSpecularExp", (float)15f);


            //Habilitar textura
            d3dDevice.SetTexture(0, texture);
            //d3dDevice.Material = TgcD3dDevice.DEFAULT_MATERIAL;

            //Especificar formato de triangulos
            d3dDevice.VertexFormat = CustomVertex.PositionNormalTextured.Format;
            //Cargar VertexBuffer a renderizar
            d3dDevice.SetStreamSource(0, vertexBuffer, 0);
            d3dDevice.Indices = indexBuffer;
            //Dibujar 1 primitiva
            //Render con shader
            effect.Begin(0);
            effect.BeginPass(0);
            d3dDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, TOTAL_VERTICES_CUADRADO, 0, TOTAL_TRIANGULOS);
            effect.EndPass();
            effect.End();

            /*
             * foreach (TgcArrow a in normals)
             * {
             *  a.render();
             * }
             */
        }
Esempio n. 39
0
            private bool HandleTextureContent(TextureInfo content, bool createSRV, bool enableAutoGenMipMap)
            {
                if (content == TextureInfo.Null)
                {
                    return(false);
                }
                if (content.IsCompressed)
                {
                    var stream = content.Texture;
                    if (stream == null || !stream.CanRead)
                    {
                        logger.LogWarning("Stream is null or unreadable.");
                        return(false);
                    }
                    resource = TextureLoader.FromMemoryAsShaderResource(device, stream, !enableAutoGenMipMap);
                    if (createSRV)
                    {
                        textureView = new ShaderResourceView(device, resource);
                    }
                    TextureFormat = textureView.Description.Format;
                }
                else
                {
                    var handle   = new GCHandle();
                    var pixelPtr = IntPtr.Zero;
                    try
                    {
                        switch (content.DataType)
                        {
                        case TextureDataType.ByteArray:
                            handle   = GCHandle.Alloc(content.TextureRaw, GCHandleType.Pinned);
                            pixelPtr = handle.AddrOfPinnedObject();
                            break;

                        case TextureDataType.Color4:
                            handle   = GCHandle.Alloc(content.Color4Array, GCHandleType.Pinned);
                            pixelPtr = handle.AddrOfPinnedObject();
                            break;

                        case TextureDataType.Stream:
                            if (content.Texture == null || !content.Texture.CanRead)
                            {
                                logger.LogWarning("Data is null or unreadable.");
                                return(false);
                            }
                            var temp = new byte[content.Texture.Length];
                            using (var pixelStream = new MemoryStream(temp))
                            {
                                lock (content.Texture)
                                {
                                    content.Texture.Position = 0;
                                    content.Texture.CopyTo(pixelStream);
                                }
                            }
                            handle   = GCHandle.Alloc(temp, GCHandleType.Pinned);
                            pixelPtr = handle.AddrOfPinnedObject();
                            break;

                        case TextureDataType.RawPointer:
                            pixelPtr = content.RawPointer;
                            break;
                        }
                        if (pixelPtr != IntPtr.Zero)
                        {
                            switch (content.Dimension)
                            {
                            case 1:
                                CreateView(pixelPtr, content.Width, content.PixelFormat, createSRV, enableAutoGenMipMap);
                                break;

                            case 2:
                                CreateView(pixelPtr, content.Width, content.Height, content.PixelFormat, createSRV, enableAutoGenMipMap);
                                break;

                            case 3:
                                CreateView(pixelPtr, content.Width, content.Height, content.Depth, content.PixelFormat, createSRV, enableAutoGenMipMap);
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        if (handle.IsAllocated)
                        {
                            handle.Free();
                        }
                    }
                }
                return(true);
            }
        public static int LoadFromMemoryEx(Image memoryImage, string name, long lColorKey, out Texture texture)
        {
            Log.Debug("TextureManagerEx: load from memory: {0}", name);

            string cacheName = name;
            string cacheKey  = cacheName.ToLowerInvariant();

            texture = null;
            CachedTexture cached;

            if (_cacheTextures.TryGetValue(cacheKey, out cached))
            {
                return(cached.Frames);
            }

            if (memoryImage == null)
            {
                return(0);
            }
            try
            {
                CachedTexture newCache = new CachedTexture();

                newCache.Name   = cacheName;
                newCache.Frames = 1;

                //load gif into texture
                using (MemoryStream stream = new MemoryStream())
                {
                    memoryImage.Save(stream, ImageFormat.Png);
                    ImageInformation info2 = new ImageInformation();
                    stream.Flush();
                    stream.Seek(0, SeekOrigin.Begin);
                    texture = TextureLoader.FromStream(
                        GUIGraphicsContext.DX9Device,
                        stream,
                        0, 0,          //width/height
                        1,             //mipslevels
                        Usage.Dynamic, //Usage.Dynamic,
                        Format.A8R8G8B8,
                        Pool.Default,
                        Filter.None,
                        Filter.None,
                        (int)lColorKey,
                        ref info2);
                    newCache.Width   = info2.Width;
                    newCache.Height  = info2.Height;
                    newCache.Texture = new TextureFrame(cacheName, texture, 0);
                }

                newCache.Disposed += new EventHandler(cachedTexture_Disposed);

                _cacheTextures[cacheKey] = newCache;

                Log.Debug("TextureManager: added: memoryImage  " + " total count: " + _cacheTextures.Count + ", mem left (MB): " +
                          ((uint)GUIGraphicsContext.DX9Device.AvailableTextureMemory / 1048576));
                return(newCache.Frames);
            }
            catch (Exception ex)
            {
                Log.Error("TextureManager: exception loading texture memoryImage");
                Log.Error(ex);
            }
            return(0);
        }
Esempio n. 41
0
        public SupComMap(SupCom.ScmapFile map)
            : base(new SupComMapLoader.Heightmap(map),33,10000.0f / 16.0f,0.15f)
        {
            MapFile = map;

            TextureLoader loader = new TextureLoader();

            Normal = loader.LoadDDS(new MemoryStream(MapFile.NormalmapData));
            Mask = loader.LoadDDS(new MemoryStream(MapFile.TexturemapData));
        }
        private void m_RefreshTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (isUpdating)
                {
                    return;
                }

                isUpdating = true;

                if (m_ImageUri == null)
                {
                    return;
                }

                if (m_ImageUri.ToLower().StartsWith("http://"))
                {
                    bool forceDownload = false;
                    if (m_SaveFilePath == null)
                    {
                        // TODO: hack, need to get the correct cache directory
                        m_SaveFilePath = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "\\Cache\\PictureBoxImages\\temp";
                        forceDownload  = true;
                    }
                    System.IO.FileInfo saveFile = new System.IO.FileInfo(m_SaveFilePath);

                    if (forceDownload || !saveFile.Exists || (m_RefreshTime > 0 && saveFile.LastWriteTime.Subtract(System.DateTime.Now) > TimeSpan.FromSeconds(m_RefreshTime)))
                    {
                        //download it
                        try
                        {
                            WorldWind.Net.WebDownload webDownload = new WorldWind.Net.WebDownload(m_ImageUri);
                            webDownload.DownloadType = WorldWind.Net.DownloadType.Unspecified;

                            if (!saveFile.Directory.Exists)
                            {
                                saveFile.Directory.Create();
                            }

                            webDownload.DownloadFile(m_SaveFilePath);
                        }
                        catch { }
                    }
                }
                else
                {
                    m_SaveFilePath = m_ImageUri;
                }

                if (m_ImageTexture != null && !m_ImageTexture.Disposed)
                {
                    m_ImageTexture.Dispose();
                    m_ImageTexture = null;
                }

                if (!System.IO.File.Exists(m_SaveFilePath))
                {
                    displayText = "Image Not Found";
                    return;
                }

                if (LoadAsUncompressed)
                {
                    m_ImageTexture = TextureLoader.FromFile(DrawArgs.Device, m_SaveFilePath, 0, 0, 1, 0, Format.Unknown, Pool.Managed, Filter.None, Filter.None, 0);
                }
                else
                {
                    m_ImageTexture = ImageHelper.LoadTexture(m_SaveFilePath);
                }
                m_surfaceDescription = m_ImageTexture.GetLevelDescription(0);

                int width  = ClientSize.Width;
                int height = ClientSize.Height;

                if (ClientSize.Width == 0)
                {
                    width = m_surfaceDescription.Width;
                }
                if (ClientSize.Height == 0)
                {
                    height = m_surfaceDescription.Height;
                }

                if (ParentWidget is Widgets.Form && SizeParentToImage)
                {
                    Widgets.Form parentForm = (Widgets.Form)ParentWidget;
                    parentForm.ClientSize = new System.Drawing.Size(width, height + parentForm.HeaderHeight);
                }
                else if (SizeParentToImage)
                {
                    ParentWidget.ClientSize = new System.Drawing.Size(width, height);
                }


                ClientSize        = new System.Drawing.Size(width, height);
                m_currentImageUri = m_ImageUri;

                IsLoaded    = true;
                isUpdating  = false;
                displayText = null;
                if (m_RefreshTime == 0 && m_RefreshTimer.Enabled)
                {
                    m_RefreshTimer.Stop();
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
            }
        }
Esempio n. 43
0
        public override void Init()
        {
            //Triangulo 1.
            //Definir array de vertices para el triangulo, del tipo Coordendas (X,Y,Z) + Color
            simpleTriangleData = new CustomVertex.PositionColored[3];

            //Cargar informacion de vertices. Nesitamos 3 vertices para crear un triangulo
            simpleTriangleData[0] = new CustomVertex.PositionColored(-1, 0, 0, Color.Red.ToArgb());
            simpleTriangleData[1] = new CustomVertex.PositionColored(1, 0, 0, Color.Green.ToArgb());
            simpleTriangleData[2] = new CustomVertex.PositionColored(0, 1, 0, Color.Blue.ToArgb());

            //Cargar variables de usuario con alguna informacion util para ver en pantalla
            UserVars.addVar("Triangle 1 vertices", simpleTriangleData.Length);

            //Triangulo 2.
            //Current texture
            currentTexurePah = MediaDir + "Texturas\\baldosaFacultad.jpg";
            texture          = TextureLoader.FromFile(D3DDevice.Instance.Device, currentTexurePah);

            //Modifiers
            Modifiers.addVertex3f("vertex1", new Vector3(-3, -3, -3), new Vector3(3, 3, 3),
                                  new Vector3(-1, 0, 0));
            Modifiers.addVertex2f("texCoord1", new Vector2(0, 0), new Vector2(1, 1),
                                  new Vector2(1, 0));
            Modifiers.addColor("color1", Color.White);

            Modifiers.addVertex3f("vertex2", new Vector3(-3, -3, -3), new Vector3(3, 3, 3),
                                  new Vector3(1, 0, 0));
            Modifiers.addVertex2f("texCoord2", new Vector2(0, 0), new Vector2(1, 1),
                                  new Vector2(0, 1));
            Modifiers.addColor("color2", Color.White);

            Modifiers.addVertex3f("vertex3", new Vector3(-3, -3, -3), new Vector3(3, 3, 3),
                                  new Vector3(0, 1, 0));
            Modifiers.addVertex2f("texCoord3", new Vector2(0, 0), new Vector2(1, 1),
                                  new Vector2(1, 1));
            Modifiers.addColor("color3", Color.White);

            Modifiers.addFloat("rotation", -2, 2f, 0f);
            Modifiers.addBoolean("TextureEnable", "Con textura", true);
            Modifiers.addTexture("Texture image", currentTexurePah);

            //Triangulo 3.
            //Crear vertexBuffer
            vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored), 3, D3DDevice.Instance.Device,
                                            Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default);

            //Cargar informacion de vertices: (X,Y,Z) + Color
            var data = new CustomVertex.PositionColored[3];

            data[0] = new CustomVertex.PositionColored(-1, 0, 0, Color.Red.ToArgb());
            data[1] = new CustomVertex.PositionColored(1, 0, 0, Color.Green.ToArgb());
            data[2] = new CustomVertex.PositionColored(0, 1, 0, Color.Blue.ToArgb());

            //Almacenar informacion en VertexBuffer
            vertexBuffer.SetData(data, 0, LockFlags.None);

            //User Vars
            UserVars.addVar("Triangle 3 vertices");
            UserVars.setValue("Triangle 3 vertices", data.Length);

            //Configurar camara en rotacion
            Camara = new TgcRotationalCamera(new Vector3(0, 0.5f, 0), 7.5f, Input);
        }
Esempio n. 44
0
        private void Init()
        {
            context = new ObjectGL.CachingImpl.Context(gl, nativeGraphicsContext);
            var pclWorkarounds = new PclWorkarounds();
            var textureLoader = new TextureLoader(assetManager);
            var spritefont = new Spritefont(settings, context, textureLoader);
            var statisticsRenderer = new OnScreenClientStatisticsRenderer(spritefont);
            var statistics = new ClientStatistics(statisticsRenderer);
            var byteArrayPool = new ByteArrayPool();
            var streamReceiver = settings.AreFromFile
                ? (IStreamReceiver)new AssetStreamReceiver(assetManager, byteArrayPool, "stream.dat")
                : new TcpStreamReceiver(pclWorkarounds, settings, byteArrayPool);
            streamReceivingStage = new StreamReceivingStage(pclWorkarounds, streamReceiver);
            cpuDecompressionStage = new CpuDecompressionStage(pclWorkarounds, statistics, byteArrayPool);
            var mainThreadBorderStage = new MainThreadBorderStage(statistics);
            var textureInitializer = new TextureInitializer();
            //var textureRenderer = new TextureRenderer(pclWorkarounds, settings, context);
            var gpuProcessingStage = new GpuProcessingStage(pclWorkarounds, statistics, settings, context, textureInitializer);
            var timedBufferingStage = new TimeBufferingStage(settings, statistics, context);
            mainLoop = new MainLoop(pclWorkarounds, statistics, settings, context, this, mainThreadBorderStage, timedBufferingStage, statisticsRenderer, textureLoader);

            //statisticsRenderer.ShowForm();

            PipelineBuilder
                .BeginWith(streamReceivingStage)
                .ContinueWith(cpuDecompressionStage)
                .ContinueWith(mainThreadBorderStage)
                .ContinueWith(gpuProcessingStage)
                .EndWith(timedBufferingStage);

            cpuDecompressionStage.Start();
            streamReceivingStage.Start();
        }
        public static int Load(string fileNameOrg, long lColorKey, int iMaxWidth, int iMaxHeight, bool persistent)
        {
            string fileName = GetFileName(fileNameOrg);
            string cacheKey = fileName.ToLowerInvariant();

            if (String.IsNullOrEmpty(fileName))
            {
                return(0);
            }

            CachedTexture cached;

            if (_cacheTextures.TryGetValue(cacheKey, out cached))
            {
                return(cached.Frames);
            }

            string extension = Path.GetExtension(fileName).ToLowerInvariant();

            if (extension == ".gif")
            {
                Image theImage = null;
                try
                {
                    try
                    {
                        theImage = ImageFast.FromFile(fileName);
                    }
                    catch (FileNotFoundException)
                    {
                        Log.Warn("TextureManager: texture: {0} does not exist", fileName);
                        return(0);
                    }
                    catch (Exception)
                    {
                        Log.Warn("TextureManager: Fast loading texture {0} failed using safer fallback", fileName);
                        theImage = Image.FromFile(fileName);
                    }
                    if (theImage != null)
                    {
                        CachedTexture newCache = new CachedTexture();

                        newCache.Name = fileName;
                        FrameDimension oDimension = new FrameDimension(theImage.FrameDimensionsList[0]);
                        newCache.Frames = theImage.GetFrameCount(oDimension);
                        int[] frameDelay = new int[newCache.Frames];
                        for (int num2 = 0; (num2 < newCache.Frames); ++num2)
                        {
                            frameDelay[num2] = 0;
                        }

                        // Getting Frame duration of an animated Gif image
                        try
                        {
                            int          num1  = 20736;
                            PropertyItem item1 = theImage.GetPropertyItem(num1);
                            if (item1 != null)
                            {
                                byte[] buffer1 = item1.Value;
                                for (int num2 = 0; (num2 < newCache.Frames); ++num2)
                                {
                                    frameDelay[num2] = (((buffer1[(num2 * 4)] + (256 * buffer1[((num2 * 4) + 1)])) +
                                                         (65536 * buffer1[((num2 * 4) + 2)])) + (16777216 * buffer1[((num2 * 4) + 3)]));
                                }
                            }
                        }
                        catch (Exception) { }

                        for (int i = 0; i < newCache.Frames; ++i)
                        {
                            theImage.SelectActiveFrame(oDimension, i);

                            //load gif into texture
                            using (MemoryStream stream = new MemoryStream())
                            {
                                theImage.Save(stream, ImageFormat.Png);
                                ImageInformation info2 = new ImageInformation();
                                stream.Flush();
                                stream.Seek(0, SeekOrigin.Begin);
                                Texture texture = TextureLoader.FromStream(
                                    GUIGraphicsContext.DX9Device,
                                    stream,
                                    0, 0, //width/height
                                    1,    //mipslevels
                                    0,    //Usage.Dynamic,
                                    Format.A8R8G8B8,
                                    GUIGraphicsContext.GetTexturePoolType(),
                                    Filter.None,
                                    Filter.None,
                                    (int)lColorKey,
                                    ref info2);
                                newCache.Width  = info2.Width;
                                newCache.Height = info2.Height;
                                newCache[i]     = new TextureFrame(fileName, texture, (frameDelay[i] / 5) * 50);
                            }
                        }

                        theImage.SafeDispose();
                        theImage           = null;
                        newCache.Disposed += new EventHandler(cachedTexture_Disposed);
                        if (persistent && !_persistentTextures.ContainsKey(cacheKey))
                        {
                            _persistentTextures[cacheKey] = true;
                        }

                        _cacheTextures[cacheKey] = newCache;

                        //Log.Info("  TextureManager:added:" + fileName + " total:" + _cache.Count + " mem left:" + GUIGraphicsContext.DX9Device.AvailableTextureMemory.ToString());
                        return(newCache.Frames);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("TextureManager: exception loading texture {0}", fileName);
                    Log.Error(ex);
                }
                return(0);
            }

            try
            {
                int width, height;

                if (MediaPortal.Util.Utils.FileExistsInCache(fileName))
                {
                    Texture dxtexture = LoadGraphic(fileName, lColorKey, iMaxWidth, iMaxHeight, out width, out height);
                    if (dxtexture != null)
                    {
                        CachedTexture newCache = new CachedTexture();
                        newCache.Name      = fileName;
                        newCache.Frames    = 1;
                        newCache.Width     = width;
                        newCache.Height    = height;
                        newCache.Texture   = new TextureFrame(fileName, dxtexture, 0);
                        newCache.Disposed += new EventHandler(cachedTexture_Disposed);

                        if (persistent && !_persistentTextures.ContainsKey(cacheKey))
                        {
                            _persistentTextures[cacheKey] = true;
                        }

                        _cacheTextures[cacheKey] = newCache;
                        return(1);
                    }
                }
            }
            catch (Exception)
            {
                return(0);
            }
            return(0);
        }
Esempio n. 46
0
        private void Load(TextReader reader, string imagesDir, TextureLoader textureLoader)
        {
            if (textureLoader == null)
            {
                throw new ArgumentNullException("textureLoader cannot be null.");
            }
            this.textureLoader = textureLoader;
            string[]  array     = new string[4];
            AtlasPage atlasPage = null;

            while (true)
            {
                string text = reader.ReadLine();
                if (text == null)
                {
                    break;
                }
                if (text.Trim().get_Length() == 0)
                {
                    atlasPage = null;
                }
                else if (atlasPage == null)
                {
                    atlasPage      = new AtlasPage();
                    atlasPage.name = text;
                    if (Atlas.readTuple(reader, array) == 2)
                    {
                        atlasPage.width  = int.Parse(array[0]);
                        atlasPage.height = int.Parse(array[1]);
                        Atlas.readTuple(reader, array);
                    }
                    atlasPage.format = (Format)((int)Enum.Parse(typeof(Format), array[0], false));
                    Atlas.readTuple(reader, array);
                    atlasPage.minFilter = (TextureFilter)((int)Enum.Parse(typeof(TextureFilter), array[0], false));
                    atlasPage.magFilter = (TextureFilter)((int)Enum.Parse(typeof(TextureFilter), array[1], false));
                    string text2 = Atlas.readValue(reader);
                    atlasPage.uWrap = TextureWrap.ClampToEdge;
                    atlasPage.vWrap = TextureWrap.ClampToEdge;
                    if (text2 == "x")
                    {
                        atlasPage.uWrap = TextureWrap.Repeat;
                    }
                    else if (text2 == "y")
                    {
                        atlasPage.vWrap = TextureWrap.Repeat;
                    }
                    else if (text2 == "xy")
                    {
                        atlasPage.uWrap = (atlasPage.vWrap = TextureWrap.Repeat);
                    }
                    textureLoader.Load(atlasPage, Path.Combine(imagesDir, text));
                    this.pages.Add(atlasPage);
                }
                else
                {
                    AtlasRegion atlasRegion = new AtlasRegion();
                    atlasRegion.name   = text;
                    atlasRegion.page   = atlasPage;
                    atlasRegion.rotate = bool.Parse(Atlas.readValue(reader));
                    Atlas.readTuple(reader, array);
                    int num  = int.Parse(array[0]);
                    int num2 = int.Parse(array[1]);
                    Atlas.readTuple(reader, array);
                    int num3 = int.Parse(array[0]);
                    int num4 = int.Parse(array[1]);
                    atlasRegion.u = (float)num / (float)atlasPage.width;
                    atlasRegion.v = (float)num2 / (float)atlasPage.height;
                    if (atlasRegion.rotate)
                    {
                        atlasRegion.u2 = (float)(num + num4) / (float)atlasPage.width;
                        atlasRegion.v2 = (float)(num2 + num3) / (float)atlasPage.height;
                    }
                    else
                    {
                        atlasRegion.u2 = (float)(num + num3) / (float)atlasPage.width;
                        atlasRegion.v2 = (float)(num2 + num4) / (float)atlasPage.height;
                    }
                    atlasRegion.x      = num;
                    atlasRegion.y      = num2;
                    atlasRegion.width  = Math.Abs(num3);
                    atlasRegion.height = Math.Abs(num4);
                    if (Atlas.readTuple(reader, array) == 4)
                    {
                        atlasRegion.splits = new int[]
                        {
                            int.Parse(array[0]),
                            int.Parse(array[1]),
                            int.Parse(array[2]),
                            int.Parse(array[3])
                        };
                        if (Atlas.readTuple(reader, array) == 4)
                        {
                            atlasRegion.pads = new int[]
                            {
                                int.Parse(array[0]),
                                int.Parse(array[1]),
                                int.Parse(array[2]),
                                int.Parse(array[3])
                            };
                            Atlas.readTuple(reader, array);
                        }
                    }
                    atlasRegion.originalWidth  = int.Parse(array[0]);
                    atlasRegion.originalHeight = int.Parse(array[1]);
                    Atlas.readTuple(reader, array);
                    atlasRegion.offsetX = (float)int.Parse(array[0]);
                    atlasRegion.offsetY = (float)int.Parse(array[1]);
                    atlasRegion.index   = int.Parse(Atlas.readValue(reader));
                    this.regions.Add(atlasRegion);
                }
            }
        }
Esempio n. 47
0
 public Atlas(string path, TextureLoader textureLoader)
 {
     this.ReadFile(path, textureLoader).Wait();
 }
        protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref vertexBuffer);
            RemoveAndDispose(ref indexBuffer);
            RemoveAndDispose(ref textureView);
            RemoveAndDispose(ref samplerState);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Load texture (a DDS cube map)
            textureView = TextureLoader.ShaderResourceViewFromFile(device, "CubeMap.dds");

            // Create our sampler state
            samplerState = new SamplerState(device, new SamplerStateDescription()
            {
                AddressU           = TextureAddressMode.Clamp,
                AddressV           = TextureAddressMode.Clamp,
                AddressW           = TextureAddressMode.Clamp,
                BorderColor        = new Color4(0, 0, 0, 0),
                ComparisonFunction = Comparison.Never,
                Filter             = Filter.MinMagMipLinear,
                MaximumLod         = 9, // Our cube map has 10 mip map levels (0-9)
                MinimumLod         = 0,
                MipLodBias         = 0.0f
            });

            // Create vertex buffer for cube
            vertexBuffer = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new Vertex[] {
                /*  Vertex Position    Normal, Color */
                new Vertex(-0.5f, 0.5f, -0.5f, -1f, 1f, -1f, Color.Gray),   // 0-Top-left
                new Vertex(0.5f, 0.5f, -0.5f, 1f, 1f, -1f, Color.Gray),     // 1-Top-right
                new Vertex(0.5f, -0.5f, -0.5f, 1f, -1f, -1f, Color.Gray),   // 2-Base-right
                new Vertex(-0.5f, -0.5f, -0.5f, -1f, -1f, -1f, Color.Gray), // 3-Base-left

                new Vertex(-0.5f, 0.5f, 0.5f, -1f, 1f, 1f, Color.Gray),     // 4-Top-left
                new Vertex(0.5f, 0.5f, 0.5f, 1f, 1f, 1f, Color.Gray),       // 5-Top-right
                new Vertex(0.5f, -0.5f, 0.5f, 1f, -1f, 1f, Color.Gray),     // 6-Base-right
                new Vertex(-0.5f, -0.5f, 0.5f, -1f, -1f, 1f, Color.Gray),   // 7-Base-left
            }));
            vertexBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf <Vertex>(), 0);

            // Front    Right    Top      Back     Left     Bottom
            // v0    v1 v1    v5 v1    v0 v5    v4 v4    v0 v3    v2
            // |-----|  |-----|  |-----|  |-----|  |-----|  |-----|
            // | \ A |  | \ A |  | \ A |  | \ A |  | \ A |  | \ A |
            // | B \ |  | B \ |  | B \ |  | B \ |  | B \ |  | B \ |
            // |-----|  |-----|  |-----|  |-----|  |-----|  |-----|
            // v3    v2 v2    v6 v5    v4 v6    v7 v7    v3 v7    v6
            indexBuffer = ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, new ushort[] {
                0, 1, 2, // Front A
                0, 2, 3, // Front B
                1, 5, 6, // Right A
                1, 6, 2, // Right B
                1, 0, 4, // Top A
                1, 4, 5, // Top B
                5, 4, 7, // Back A
                5, 7, 6, // Back B
                4, 0, 3, // Left A
                4, 3, 7, // Left B
                3, 2, 6, // Bottom A
                3, 6, 7, // Bottom B
            }));
        }
Esempio n. 49
0
        /// <summary>
        /// This event will be fired immediately after the Direct3D device has been
        /// created, which will happen during application initialization and windowed/full screen
        /// toggles. This is the best location to create Pool.Managed resources since these
        /// resources need to be reloaded whenever the device is destroyed. Resources created
        /// here should be released in the Disposing event.
        /// </summary>
        private void OnCreateDevice(object sender, DeviceEventArgs e)
        {
            // Initialize the stats font
            statsFont = ResourceCache.GetGlobalInstance().CreateFont(e.Device, 15, 0, FontWeight.Bold, 1, false, CharacterSet.Default,
                                                                     Precision.Default, FontQuality.Default, PitchAndFamily.FamilyDoNotCare | PitchAndFamily.DefaultPitch
                                                                     , "Arial");

            // Setup the camera's view parameters
            camera.SetViewParameters(new Vector3(0.0f, 0.0f, -5.0f), Vector3.Empty);


            //initialized the tile-view
            upperLeft  = new Vector2(0, 0);
            zoomFactor = 1;

            //Generate a randmoized "game board" using the tiles in the tile set.
            for (int i = 0; i < gameBoard.GetLength(0); i++)
            {
                for (int j = 0; j < gameBoard.GetLength(1); j++)
                {
                    //add a tile every time a location is set to an index other than "None"
                    gameBoard[i, j].Ground = TileIndex.Grass;
                    if (rand.Next(3) == 1)
                    {
                        if (rand.Next(5) == 1)
                        {
                            gameBoard[i, j].Middle = TileIndex.Flowers;
                        }
                        else
                        {
                            gameBoard[i, j].Middle = TileIndex.Rocks;
                        }
                    }
                    else
                    {
                        gameBoard[i, j].Middle = TileIndex.None;
                    }
                    if (rand.Next(5) == 1)
                    {
                        gameBoard[i, j].Foreground = TileIndex.Cloud;
                    }
                    else
                    {
                        gameBoard[i, j].Foreground = TileIndex.None;
                    }
                }
            }

            //Since we're casting the value 0xFF000000 as an Int32, we must specify
            //unchecked to avoid compiler errors.
            unchecked
            {
                //The texture used is in the "Managed" pool, meaning that it will automatically
                //restore itself on a Device.Reset().  This kind of texture requires less manual management than
                //a default pool texture.
                tileTexture = TextureLoader.FromFile(e.Device, Utility.FindMediaFile("tiles.tga"), 320, 64, 1,
                                                     Usage.None, Format.A8R8G8B8, Pool.Managed, Filter.None, Filter.None, (int)0xFF000000);


                //create the example tile set
                exampleTileSet = new UniformTileSet(tileTexture, 256, 64);
                exampleTileSet.CreateTiles(tileWidth, tileHeight, 0, 0, 4, 1);
                UpdateVisibleTiles();


                //Create the texture for the moving sprite
                mosquitoTexture = TextureLoader.FromFile(e.Device, Utility.FindMediaFile("mosquito.bmp"), 160, 100, 0,
                                                         Usage.None, Format.A8R8G8B8, Pool.Managed, Filter.None, Filter.None, (int)(0xFF000000));

                movingSprite = new MovingSprite(mosquitoTexture, new System.Drawing.Rectangle(0, 0, 160, 100), rand, 200f);

                //create the texture for our animated sprite
                donutTexture = TextureLoader.FromFile(e.Device, Utility.FindMediaFile("donut.bmp"), 640, 384, 0,
                                                      Usage.None, Format.A8R8G8B8, Pool.Managed, Filter.None, Filter.None, (int)(0xFF000000));

                animatedSprite = new AnimatedSprite(donutTexture, 64, 64, 6, 10, 60, 0);
            }

            //Create a Canvas and a particle effect object for the
            //canvas-based per-pixel effect
            canvas = new Canvas(e.Device, 640, 480);
            effect = new ParticleEffect(6, 6, canvas, rand, 4f, 20);
        }
Esempio n. 50
0
		public Atlas(String path, TextureLoader textureLoader) {
			this.ReadFile(path, textureLoader).Wait();
		}
Esempio n. 51
0
 public Atlas(TextReader reader, string dir, TextureLoader textureLoader)
 {
     Load(reader, dir, textureLoader);
 }
Esempio n. 52
0
		public Atlas (TextReader reader, String dir, TextureLoader textureLoader) {
			Load(reader, dir, textureLoader);
		}
Esempio n. 53
0
 public Atlas(List <AtlasPage> pages, List <AtlasRegion> regions)
 {
     this.pages         = pages;
     this.regions       = regions;
     this.textureLoader = null;
 }
Esempio n. 54
0
		private void Load (TextReader reader, String imagesDir, TextureLoader textureLoader) {
			if (textureLoader == null) throw new ArgumentNullException("textureLoader cannot be null.");
			this.textureLoader = textureLoader;

			String[] tuple = new String[4];
			AtlasPage page = null;
			while (true) {
				String line = reader.ReadLine();
				if (line == null) break;
				if (line.Trim().Length == 0)
					page = null;
				else if (page == null) {
					page = new AtlasPage();
					page.name = line;

					if (readTuple(reader, tuple) == 2) { // size is only optional for an atlas packed with an old TexturePacker.
						page.width = int.Parse(tuple[0]);
						page.height = int.Parse(tuple[1]);
						readTuple(reader, tuple);
					}
					page.format = (Format)Enum.Parse(typeof(Format), tuple[0], false);

					readTuple(reader, tuple);
					page.minFilter = (TextureFilter)Enum.Parse(typeof(TextureFilter), tuple[0], false);
					page.magFilter = (TextureFilter)Enum.Parse(typeof(TextureFilter), tuple[1], false);

					String direction = readValue(reader);
					page.uWrap = TextureWrap.ClampToEdge;
					page.vWrap = TextureWrap.ClampToEdge;
					if (direction == "x")
						page.uWrap = TextureWrap.Repeat;
					else if (direction == "y")
						page.vWrap = TextureWrap.Repeat;
					else if (direction == "xy")
						page.uWrap = page.vWrap = TextureWrap.Repeat;

					textureLoader.Load(page, Path.Combine(imagesDir, line));

					pages.Add(page);

				} else {
					AtlasRegion region = new AtlasRegion();
					region.name = line;
					region.page = page;

					region.rotate = Boolean.Parse(readValue(reader));

					readTuple(reader, tuple);
					int x = int.Parse(tuple[0]);
					int y = int.Parse(tuple[1]);

					readTuple(reader, tuple);
					int width = int.Parse(tuple[0]);
					int height = int.Parse(tuple[1]);

					region.u = x / (float)page.width;
					region.v = y / (float)page.height;
					if (region.rotate) {
						region.u2 = (x + height) / (float)page.width;
						region.v2 = (y + width) / (float)page.height;
					} else {
						region.u2 = (x + width) / (float)page.width;
						region.v2 = (y + height) / (float)page.height;
					}
					region.x = x;
					region.y = y;
					region.width = Math.Abs(width);
					region.height = Math.Abs(height);

					if (readTuple(reader, tuple) == 4) { // split is optional
						region.splits = new int[] {int.Parse(tuple[0]), int.Parse(tuple[1]),
								int.Parse(tuple[2]), int.Parse(tuple[3])};

						if (readTuple(reader, tuple) == 4) { // pad is optional, but only present with splits
							region.pads = new int[] {int.Parse(tuple[0]), int.Parse(tuple[1]),
									int.Parse(tuple[2]), int.Parse(tuple[3])};

							readTuple(reader, tuple);
						}
					}

					region.originalWidth = int.Parse(tuple[0]);
					region.originalHeight = int.Parse(tuple[1]);

					readTuple(reader, tuple);
					region.offsetX = int.Parse(tuple[0]);
					region.offsetY = int.Parse(tuple[1]);

					region.index = int.Parse(readValue(reader));

					regions.Add(region);
				}
			}
		}
Esempio n. 55
0
        private void Load(TextReader reader, string imagesDir, TextureLoader textureLoader)
        {
            if (textureLoader == null)
            {
                throw new ArgumentNullException("textureLoader", "textureLoader cannot be null.");
            }
            this.textureLoader = textureLoader;

            string[]  tuple = new string[4];
            AtlasPage page  = null;

            while (true)
            {
                string line = reader.ReadLine();
                if (line == null)
                {
                    break;
                }
                if (line.Trim().Length == 0)
                {
                    page = null;
                }
                else if (page == null)
                {
                    page      = new AtlasPage();
                    page.name = line;

                    if (ReadTuple(reader, tuple) == 2)                       // size is only optional for an atlas packed with an old TexturePacker.
                    {
                        page.width  = int.Parse(tuple[0], CultureInfo.InvariantCulture);
                        page.height = int.Parse(tuple[1], CultureInfo.InvariantCulture);
                        ReadTuple(reader, tuple);
                    }
                    page.format = (Format)Enum.Parse(typeof(Format), tuple[0], false);

                    ReadTuple(reader, tuple);
                    page.minFilter = (TextureFilter)Enum.Parse(typeof(TextureFilter), tuple[0], false);
                    page.magFilter = (TextureFilter)Enum.Parse(typeof(TextureFilter), tuple[1], false);

                    string direction = ReadValue(reader);
                    page.uWrap = TextureWrap.ClampToEdge;
                    page.vWrap = TextureWrap.ClampToEdge;
                    if (direction == "x")
                    {
                        page.uWrap = TextureWrap.Repeat;
                    }
                    else if (direction == "y")
                    {
                        page.vWrap = TextureWrap.Repeat;
                    }
                    else if (direction == "xy")
                    {
                        page.uWrap = page.vWrap = TextureWrap.Repeat;
                    }

                    textureLoader.Load(page, Path.Combine(imagesDir, line));

                    pages.Add(page);
                }
                else
                {
                    AtlasRegion region = new AtlasRegion();
                    region.name = line;
                    region.page = page;

                    region.rotate = Boolean.Parse(ReadValue(reader));

                    ReadTuple(reader, tuple);
                    int x = int.Parse(tuple[0], CultureInfo.InvariantCulture);
                    int y = int.Parse(tuple[1], CultureInfo.InvariantCulture);

                    ReadTuple(reader, tuple);
                    int width  = int.Parse(tuple[0], CultureInfo.InvariantCulture);
                    int height = int.Parse(tuple[1], CultureInfo.InvariantCulture);

                    region.u = x / (float)page.width;
                    region.v = y / (float)page.height;
                    if (region.rotate)
                    {
                        region.u2 = (x + height) / (float)page.width;
                        region.v2 = (y + width) / (float)page.height;
                    }
                    else
                    {
                        region.u2 = (x + width) / (float)page.width;
                        region.v2 = (y + height) / (float)page.height;
                    }
                    region.x      = x;
                    region.y      = y;
                    region.width  = Math.Abs(width);
                    region.height = Math.Abs(height);

                    if (ReadTuple(reader, tuple) == 4)                       // split is optional
                    {
                        region.splits = new [] { int.Parse(tuple[0], CultureInfo.InvariantCulture),
                                                 int.Parse(tuple[1], CultureInfo.InvariantCulture),
                                                 int.Parse(tuple[2], CultureInfo.InvariantCulture),
                                                 int.Parse(tuple[3], CultureInfo.InvariantCulture) };

                        if (ReadTuple(reader, tuple) == 4)                           // pad is optional, but only present with splits
                        {
                            region.pads = new [] { int.Parse(tuple[0], CultureInfo.InvariantCulture),
                                                   int.Parse(tuple[1], CultureInfo.InvariantCulture),
                                                   int.Parse(tuple[2], CultureInfo.InvariantCulture),
                                                   int.Parse(tuple[3], CultureInfo.InvariantCulture) };

                            ReadTuple(reader, tuple);
                        }
                    }

                    region.originalWidth  = int.Parse(tuple[0], CultureInfo.InvariantCulture);
                    region.originalHeight = int.Parse(tuple[1], CultureInfo.InvariantCulture);

                    ReadTuple(reader, tuple);
                    region.offsetX = int.Parse(tuple[0], CultureInfo.InvariantCulture);
                    region.offsetY = int.Parse(tuple[1], CultureInfo.InvariantCulture);

                    region.index = int.Parse(ReadValue(reader), CultureInfo.InvariantCulture);

                    regions.Add(region);
                }
            }
        }
Esempio n. 56
0
            public Factory(Data d, GameObject gObj,
			float zOff = 0, float zR = 1, int rQOff = 0,
			string sLayerName = null, int sOrder = 0, bool uAC = false,
			Camera renderCam = null, Camera inputCam = null,
			string texturePrfx = "", string fontPrfx = "",
			TextureLoader textureLdr = null,
			TextureUnloader textureUnldr = null,
			bool attaching = false)
                : base(d, gObj, zOff, zR, rQOff, sLayerName, sOrder, uAC, renderCam,
			inputCam, texturePrfx, fontPrfx, textureLdr, textureUnldr)
            {
                CreateBitmapContexts();
                CreateTextContexts();

                meshComponents = new List<CombinedMeshComponent>();
                if (!attaching)
                AddMeshComponent();
                usedMeshComponentNo = -1;

                updateCount = -1;
            }
Esempio n. 57
0
 /// <summary>
 /// public contstructor
 /// </summary>
 /// <param name="width">Width of the image</param>
 /// <param name="height">Height of the image</param>
 /// <param name="worldSpace">Is the image in world space</param>
 /// <param name="alpha">The alpha value of the image</param>
 /// <param name="shader">The shader that is used to draw</param>
 public UiImageRendererComponent(int width, int height, bool worldSpace, float alpha, ShaderProgram shader) :
     this(
         TextureLoader.ParameterToTexture(width, height, "UIImageRendererImageFromParameters"), worldSpace,
         alpha, shader)
 {
 }