Esempio n. 1
0
        public override void Render()
        {
            PreRender();

            gui_render(ElapsedTime);

            if (profiling)
            {
                Device   device   = D3DDevice.Instance.Device;
                Viewport ant_view = device.Viewport;
                Viewport view     = new Viewport();
                view.X      = (int)(400 * gui.ex);
                view.Y      = (int)(100 * gui.ey);
                view.Width  = (int)(400 * gui.ex);
                view.Height = (int)(300 * gui.ey);
                view.MinZ   = 0;
                view.MaxZ   = 1;

                device.Viewport = view;

                mesh.Transform = TGCMatrix.Scaling(mesh.Scale)
                                 * TGCMatrix.RotationYawPitchRoll(mesh.Rotation.Y, mesh.Rotation.X, mesh.Rotation.Z)
                                 * TGCMatrix.Translation(mesh.Position);
                mesh.Render();

                device.Viewport = ant_view;
            }

            PostRender();
        }
Esempio n. 2
0
        public void Init(GameModel gameModel)
        {
            GModel = gameModel;

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

            personaje =
                skeletalLoader.loadMeshAndAnimationsFromFile(
                    GModel.MediaDir + "SkeletalAnimations\\Robot\\Robot-TgcSkeletalMesh.xml",
                    GModel.MediaDir + "SkeletalAnimations\\Robot\\",
                    new[]
            {
                GModel.MediaDir + "SkeletalAnimations\\Robot\\Caminando-TgcSkeletalAnim.xml",
                GModel.MediaDir + "SkeletalAnimations\\Robot\\Parado-TgcSkeletalAnim.xml"
            });
            //Esto hay que desactivarlo
            personaje.AutoTransform = false;

            //Posicion inicial
            personaje.Position             = new TGCVector3(250, 20, 20);
            matrizPosicionamientoPersonaje = TGCMatrix.Translation(personaje.Position.X, personaje.Position.Y, personaje.Position.Z);
            checkpoint = personaje.Position;

            matrizEscalaPersonaje = TGCMatrix.Scaling(0.25f, 0.25f, 0.25f);
            //La matriz comienza asi porque el personaje comienza dado vuelta
            matrizRotacionPersonajeY = TGCMatrix.RotationY(FastMath.PI);

            saltando = false;

            collider = new TgcBoundingAxisAlignBox();
        }
Esempio n. 3
0
        private TGCMatrix getSunTransform()
        {
            var scale = TGCMatrix.Scaling(SUN_SCALE);
            var yRot  = TGCMatrix.RotationY(axisRotation);

            return(scale * yRot);
        }
Esempio n. 4
0
        public virtual void Roam()
        {
            LookDirection = new TGCVector3(LookDirection.X, 0, LookDirection.Z);  // Elimino la componente Y para que roamee al nivel que esta del agua

            timeSinceLastDirection += GameInstance.ElapsedTime;

            TGCVector3 rotationVector = TGCVector3.Empty;

            if (timeSinceLastDirection > timeToChangeDirection)
            {
                timeSinceLastDirection = 0f;
                timeToChangeDirection  = MathExtended.GetRandomNumberBetween(2, 5);

                float randomX = MathExtended.GetRandomNumberBetween(-100, 100);
                float randomZ = MathExtended.GetRandomNumberBetween(-100, 100);

                TGCVector3 lastDirection = LookDirection;
                LookDirection = TGCVector3.Normalize(new TGCVector3(randomX, LookDirection.Y, randomZ));

                float angle = MathExtended.AngleBetween(new TGCVector2(lastDirection.X, lastDirection.Z), new TGCVector2(LookDirection.X, LookDirection.Z));

                rotationVector.Y = -angle;
            }

            rotation += rotationVector;
            Position += LookDirection * roamingSpeed * GameInstance.ElapsedTime;

            TGCMatrix rot   = TGCMatrix.RotationY(rotation.Y);
            TGCMatrix trans = TGCMatrix.Translation(Position);
            TGCMatrix scal  = TGCMatrix.Scaling(scale);

            Transform = scal * rot * trans;
        }
Esempio n. 5
0
 public XwingEnemigo(TGCVector3 posicionInicial, Xwing target, float velocidadInicial, CoordenadaEsferica direccionInicial)
 {
     posicion         = posicionInicial;
     velocidadGeneral = velocidadInicial;
     //Por defecto, se encuentra mirando hacia el z+
     this.coordenadaEsferica = direccionInicial;
     nave = new TgcSceneLoader().loadSceneFromFile(VariablesGlobales.mediaDir + "XWing\\X-Wing-TgcScene.xml");//@ésta deberia ser nuestra nave, no la enemiga!
     nave.Meshes.ForEach(mesh => {
         mesh.AutoTransformEnable = false;
         mesh.Transform           = TGCMatrix.Scaling(scale) *
                                    TGCMatrix.RotationYawPitchRoll(coordenadaEsferica.GetRotation().Y, coordenadaEsferica.GetRotation().X, coordenadaEsferica.GetRotation().Z) *
                                    TGCMatrix.Translation(posicion);
         //Shader
         if (VariablesGlobales.SHADERS)
         {
             Effect shader = VariablesGlobales.shaderManager.AskForEffect(ShaderManager.MESH_TYPE.SHADOW);
             if (shader != null)
             {
                 nave.Meshes.ForEach(m => m.Effect = shader);
             }
             VariablesGlobales.shaderManager.AddObject(this);
         }
     });
     this.target = target;
     //Calcula inicialmente en que direccion esta el xwing principal
     vectorDistancia  = CommonHelper.SumarVectores(target.GetPosition(), -posicion);
     coordenadaAXwing = new CoordenadaEsferica(vectorDistancia.X, vectorDistancia.Y, vectorDistancia.Z);
 }
Esempio n. 6
0
        public override void Init()
        {
            //El framework posee la clase TgcSceneLoader que permite cargar modelos 3D.
            //Estos modelos 3D están almacenados en un archivo XML llamado TgcScene.xml.
            //Este archivo es un formato a medida hecho para el framework. Y puede ser creado desde herramientas de
            //diseño como 3Ds MAX (exportando a traves de un plugin) o con el editor MeshCreator que viene con el framework.
            //El framework viene con varios modelos 3D incluidos en la carpeta: TgcViewer\Examples\Media\MeshCreator\Meshes.
            //El formato especifica una escena, representada por la clase TgcScene. Una escena puede estar compuesta por varios
            //modelos 3D. Cada modelo se representa con la clase TgcMesh.
            //En este ejemplo vamos a cargar una escena con un único modelo.
            var loader = new TgcSceneLoader();

            //De toda la escena solo nos interesa guardarnos el primer modelo (el único que hay en este caso).
            mesh           = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\Hummer\\Hummer-TgcScene.xml").Meshes[0];
            mesh.Position += new TGCVector3(100, 37, -200);
            mesh.Rotation += new TGCVector3(0, FastMath.QUARTER_PI, 0);
            mesh.Transform = TGCMatrix.Scaling(TGCVector3.One) * TGCMatrix.RotationYawPitchRoll(mesh.Rotation.Y, mesh.Rotation.X, mesh.Rotation.Z) * TGCMatrix.Translation(mesh.Position);

            //En este ejemplo no cargamos un solo modelo 3D sino una escena completa, compuesta por varios modelos.
            //El framework posee varias escenas ya hechas en la carpeta TgcViewer\Examples\Media\MeshCreator\Scenes.
            scene = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Scenes\\Iglesia\\Iglesia-TgcScene.xml");

            //Hacemos que la cámara esté centrada sobre el mesh.
            Camera = new TgcRotationalCamera(mesh.BoundingBox.calculateBoxCenter(), mesh.BoundingBox.calculateBoxRadius() * 6, Input);
        }
Esempio n. 7
0
        private void InitializeMeshes()
        {
            TgcTexture tiles, lava, stones, water;

            tiles  = TgcTexture.createTexture(MediaDir + "Textures/tiles.jpg");
            lava   = TgcTexture.createTexture(MediaDir + "Textures/lava.jpg");
            stones = TgcTexture.createTexture(MediaDir + "Textures/stones.bmp");
            water  = TgcTexture.createTexture(MediaDir + "Textures/water.bmp");

            TGCSphere baseSphere = new TGCSphere(1f, Color.White, TGCVector3.Empty);

            baseSphere.setTexture(lava);
            baseSphere.updateValues();
            sphereOne = baseSphere.toMesh("sphereOne");
            meshes.Add(sphereOne);
            baseSphere.setTexture(stones);
            sphereTwo = baseSphere.toMesh("sphereTwo");
            meshes.Add(sphereTwo);
            baseSphere.setTexture(water);
            sphereThree = baseSphere.toMesh("sphereThree");
            meshes.Add(sphereThree);

            TgcSceneLoader loader = new TgcSceneLoader();
            var            scene  = loader.loadSceneFromFile(MediaDir + "Robot2-TgcScene.xml");

            robot           = scene.Meshes[0];
            robot.Transform = TGCMatrix.Scaling(0.1f, 0.1f, 0.1f) * TGCMatrix.RotationY(FastMath.PI) * TGCMatrix.Translation(TGCVector3.Up * 40f);
            meshes.Add(robot);

            TgcPlane tgcPlane = new TgcPlane(TGCVector3.Empty, TGCVector3.One * 100f, TgcPlane.Orientations.XZplane, tiles, 10f, 10f);

            plane = tgcPlane.toMesh("plane");
            meshes.Add(plane);
        }
Esempio n. 8
0
        /// <summary>
        ///     Se llama una sola vez, al principio cuando se ejecuta el ejemplo.
        ///     Escribir aquí todo el código de inicialización: cargar modelos, texturas, estructuras de optimización, todo
        ///     procesamiento que podemos pre calcular para nuestro juego.
        ///     Borrar el codigo ejemplo no utilizado.
        /// </summary>
        public override void Init()
        {
            effect = TGCShaders.Instance.LoadEffect(ShadersDir + "TgcExamShader.fx");

            InitializeMeshes();

            plane.Transform = TGCMatrix.Translation(-50f, 0f, -50f);

            sphereOne.Transform   = TGCMatrix.Scaling(spheresScale) * TGCMatrix.Translation(spheresCenter);
            sphereTwo.Transform   = TGCMatrix.Scaling(spheresScale) * TGCMatrix.Translation(spheresCenter + new TGCVector3(10f, 0f, 0f));
            sphereThree.Transform = TGCMatrix.Scaling(spheresScale) * TGCMatrix.Translation(spheresCenter + new TGCVector3(-10f, 0f, 0f));

            //meshes.ForEach(mesh => { mesh.Effect = effect; mesh.Technique = "Default"; });
            FixedTickEnable = true;


            //Aplico efecto solamente en la esfera dos
            sphereTwo.Effect    = effect;
            sphereTwo.Technique = "Default";
            //robot.Effect = effect;
            //robot.Technique = "Default";

            Camera = new TGCRotationalCamera(spheresCenter, 50f, Input);

            CreateFullScreenQuad();
            CreateRenderTarget();

            if (enableLighting)
            {
                InitializeLights();
            }
        }
Esempio n. 9
0
        private void LoadRocks()
        {
            var    rnd      = new Random();
            string pathRock = MediaDir + "\\Meshes\\rock\\Roca-TgcScene.xml";

            var loader       = new TgcSceneLoader();
            var originalMesh = loader.loadSceneFromFile(pathRock).Meshes[0];

            var xMax = 12000f;
            var zMax = 12000f;
            var cant = 10;

            for (int i = 0; i < cant; i++)
            {
                var posX = xMax * (float)rnd.NextDouble();
                var posZ = zMax * (float)rnd.NextDouble();
                var posY = underseaTerrain.HeightmapData[Convert.ToInt32(posX / currentScaleXZ), Convert.ToInt32(posZ / currentScaleXZ)];

                var position = new TGCVector3(posX, posY * currentScaleY, posZ);
                var scale    = new TGCVector3(i * 1.5f, i, i * 1.5f);

                var rock = originalMesh.createMeshInstance(originalMesh.Name + $"_{i}");

                rock.Transform = TGCMatrix.Scaling(scale) * TGCMatrix.Translation(position);

                ItemModel item = new ItemModel {
                    Mesh = rock
                };

                //The rocks has collision
                item.RigidBody = bulletManager.AddRigidBody(rock, position, scale);

                meshes.Add(item);
            }
        }
Esempio n. 10
0
 public override void Update()
 {
     vida.Transform = TGCMatrix.Scaling(10, 10, 10) * new TGCMatrix(body.InterpolationWorldTransform);
     //  vida.Transform = TGCMatrix.Scaling(10, 10, 10) * new TGCMatrix(body.InterpolationWorldTransform);
     vida.UpdateMeshTransform();
     // vida.updateValues();
 }
Esempio n. 11
0
        public override void Render()
        {
            PreRender();

            //FIX IT SOLO CON COLISION.
            if (selecting)
            {
                selectionBox.BoundingBox.Render();
            }

            //Render
            suelo.Render();
            foreach (var mesh in modelos)
            {
                mesh.Transform =
                    TGCMatrix.Scaling(mesh.Scale) * TGCMatrix.RotationYawPitchRoll(mesh.Rotation.Y, mesh.Rotation.X, mesh.Rotation.Z) * TGCMatrix.Translation(mesh.Position);
                mesh.Render();
            }

            //Renderizar BB de los modelos seleccionados
            foreach (var mesh in modelosSeleccionados)
            {
                mesh.BoundingBox.Render();
            }

            PostRender();
        }
        protected override void Init()
        {
            var loader = new TgcSceneLoader();

            scene = loader.loadSceneFromFile(GameModel.Media + "\\escenarios\\caminos\\");

            planoIzq = loader.loadSceneFromFile(contexto.MediaDir + "planos\\planoHorizontal-TgcScene.xml").Meshes[0];
            planoIzq.AutoTransform = false;

            planoDer = planoIzq.createMeshInstance("planoDer");
            planoDer.AutoTransform = false;
            planoDer.Transform     = TGCMatrix.Translation(-38, -15, -357) * TGCMatrix.Scaling(1, 2f, 1.1f);
            planoDer.BoundingBox.transform(planoDer.Transform);

            planoIzq.Transform = TGCMatrix.Translation(0, -15, -357) * TGCMatrix.Scaling(1, 2f, 1.1f);
            planoIzq.BoundingBox.transform(planoIzq.Transform);

            //planoFront = loader.loadSceneFromFile(contexto.MediaDir + "primer-nivel\\pozo-plataformas\\tgc-scene\\plataformas\\planoVertical-TgcScene.xml").Meshes[0];
            //planoFront.AutoTransform = false;

            //planoBack = loader.loadSceneFromFile(contexto.MediaDir + "primer-nivel\\pozo-plataformas\\tgc-scene\\plataformas\\planoVertical-TgcScene.xml").Meshes[0]; //planoFront.createMeshInstance("planoBack");
            //planoBack.AutoTransform = false;
            //planoBack.Transform = TGCMatrix.Translation(50, 0, -350);
            //planoBack.BoundingBox.transform(planoBack.Transform);

            //planoFront.Transform = TGCMatrix.Translation(50, 0, -535);
            //planoFront.BoundingBox.transform(planoFront.Transform);

            planoPiso = loader.loadSceneFromFile(contexto.MediaDir + "primer-nivel\\pozo-plataformas\\tgc-scene\\plataformas\\planoPiso-TgcScene.xml").Meshes[0];
            planoPiso.AutoTransform = false;
            planoPiso.BoundingBox.transform(TGCMatrix.Scaling(1, 1, 2) * TGCMatrix.Translation(-22, 20, -10));
        }
Esempio n. 13
0
        public override void Update()
        {
            PreUpdate();

            this.handleInput();

            this.time += ElapsedTime;

            this.sphere.Transform = TGCMatrix.Scaling(this.scale) * TGCMatrix.RotationYawPitchRoll(this.rotation, 0, 0) * TGCMatrix.Translation(this.center);

            this.updateEffectVector();

            this.effect.SetValue("time", this.time);

            TGCVector3 centeredEffectVector = this.effectVector - this.center;

            this.effect.SetValue("effectVector", new[] { centeredEffectVector.X, centeredEffectVector.Y, centeredEffectVector.Z });

            this.effect.SetValue("factor", (float)Math.Round(sumValue, 2));

            this.effect.SetValue("matViewProj", D3DDevice.Instance.Device.Transform.View * D3DDevice.Instance.Device.Transform.Projection);

            this.effect.SetValue("eyePosition", new[] { this.Camara.Position.X, this.Camara.Position.Y, this.Camara.Position.Z });

            PostUpdate();
        }
Esempio n. 14
0
        public TGCMatrix CalcularMatrizUp(TGCVector3 Pos, TGCVector3 Scale, TGCVector3 Dir, TGCVector3 VUP)
        {
            var matWorld = TGCMatrix.Scaling(Scale);
            // determino la orientacion
            var U = TGCVector3.Cross(VUP, Dir);

            U.Normalize();
            var       V           = TGCVector3.Cross(Dir, U);
            TGCMatrix Orientacion = new TGCMatrix();

            Orientacion.M11 = U.X;
            Orientacion.M12 = U.Y;
            Orientacion.M13 = U.Z;
            Orientacion.M14 = 0;

            Orientacion.M21 = V.X;
            Orientacion.M22 = V.Y;
            Orientacion.M23 = V.Z;
            Orientacion.M24 = 0;

            Orientacion.M31 = Dir.X;
            Orientacion.M32 = Dir.Y;
            Orientacion.M33 = Dir.Z;
            Orientacion.M34 = 0;

            Orientacion.M41 = 0;
            Orientacion.M42 = 0;
            Orientacion.M43 = 0;
            Orientacion.M44 = 1;
            matWorld        = matWorld * Orientacion;

            // traslado
            matWorld = matWorld * TGCMatrix.Translation(Pos);
            return(matWorld);
        }
Esempio n. 15
0
 public void EndSharkAttack()
 {
     NormalMove          = false;
     StalkerModeMove     = false;
     Mesh.Transform      = TGCMatrix.Scaling(Constants.Scale) * TGCMatrix.Translation(Constants.StartPosition);
     Body.WorldTransform = Mesh.Transform.ToBulletMatrix();
 }
Esempio n. 16
0
 public NaveEnemiga(string MediaDir, string modelToUse, int danio, int cdDisparo, NaveEspacial naveAPerseguir) : base(MediaDir, modelToUse, Color.DarkRed, danio, cdDisparo, "DIFFUSE_MAP_PHONG")
 {
     this.ScaleFactor    = TGCMatrix.Scaling(0.5f, 0.5f, 0.5f);
     this.RotationVector = new TGCVector3(0, -FastMath.PI_HALF, 0);
     this.naveAPerseguir = naveAPerseguir;
     OOBScale            = 1f;
 }
Esempio n. 17
0
        /// <summary>
        ///     Se llama cada vez que hay que refrescar la pantalla.
        ///     Escribir aquí todo el código referido al renderizado.
        ///     Borrar todo lo que no haga falta.
        /// </summary>
        public override void Render()
        {
            //Inicio el render de la escena, para ejemplos simples. Cuando tenemos postprocesado o shaders es mejor realizar las operaciones según nuestra conveniencia.
            PreRender();

            //Dibuja un texto por pantalla
            DrawText.drawText("Con la tecla F se dibuja el bounding box.", 0, 20, Color.OrangeRed);
            DrawText.drawText("Con clic izquierdo subimos la camara [Actual]: " + TGCVector3.PrintTGCVector3(Camera.Position), 0, 30, Color.OrangeRed);

            //Siempre antes de renderizar el modelo necesitamos actualizar la matriz de transformacion.
            //Debemos recordar el orden en cual debemos multiplicar las matrices, en caso de tener modelos jerárquicos, tenemos control total.
            Box.Transform = TGCMatrix.Scaling(Box.Scale) * TGCMatrix.RotationYawPitchRoll(Box.Rotation.Y, Box.Rotation.X, Box.Rotation.Z) * TGCMatrix.Translation(Box.Position);
            //A modo ejemplo realizamos toda las multiplicaciones, pero aquí solo nos hacia falta la traslación.
            //Finalmente invocamos al render de la caja
            Box.Render();

            //Cuando tenemos modelos mesh podemos utilizar un método que hace la matriz de transformación estándar.
            //Es útil cuando tenemos transformaciones simples, pero OJO cuando tenemos transformaciones jerárquicas o complicadas.
            Mesh.UpdateMeshTransform();
            //Render del mesh
            Mesh.Render();

            //Render de BoundingBox, muy útil para debug de colisiones.
            if (BoundingBox)
            {
                Box.BoundingBox.Render();
                Mesh.BoundingBox.Render();
            }

            //Finaliza el render y presenta en pantalla, al igual que el preRender se debe para casos puntuales es mejor utilizar a mano las operaciones de EndScene y PresentScene
            PostRender();
        }
Esempio n. 18
0
        /// <summary>
        ///     Renderiza el terreno
        /// </summary>
        public void render()
        {
            if (!Enabled)
            {
                return;
            }

            var d3dDevice       = D3DDevice.Instance.Device;
            var texturesManager = TexturesManager.Instance;
            var transform       = TGCMatrix.Translation(traslation) * TGCMatrix.Scaling(ScaleXZ, ScaleY, ScaleXZ);

            //Textura
            effect.SetValue("texDiffuseMap", terrainTexture);

            texturesManager.clear(1);

            TGCShaders.Instance.SetShaderMatrix(effect, transform);
            d3dDevice.VertexDeclaration = TGCShaders.Instance.VdecPositionColoredTextured;
            effect.Technique            = technique;
            d3dDevice.SetStreamSource(0, vbTerrain, 0);

            //Render con shader
            var p = effect.Begin(0);

            for (var i = 0; i < p; i++)
            {
                effect.BeginPass(i);
                d3dDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, TotalVertices / 3);
                effect.EndPass();
            }
            effect.End();
        }
Esempio n. 19
0
        public override void Render()
        {
            //BackgroundColor
            D3DDevice.Instance.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
            BeginScene();
            ClearTextures();

            //Cargar variables shader
            mesh.Effect.SetValue("ambientColor", ColorValue.FromColor(Color.Gray));
            mesh.Effect.SetValue("diffuseColor", ColorValue.FromColor(Color.LightBlue));
            mesh.Effect.SetValue("specularColor", ColorValue.FromColor(Color.White));
            mesh.Effect.SetValue("specularExp", 10f);
            mesh.Effect.SetValue("lightPosition", lightPos);
            mesh.Effect.SetValue("eyePosition", TGCVector3.Vector3ToFloat4Array(Camara.Position));

            mesh.RotateY(-ElapsedTime / 2);
            mesh.Transform = TGCMatrix.Scaling(mesh.Scale)
                             * TGCMatrix.RotationYawPitchRoll(mesh.Rotation.Y, mesh.Rotation.X, mesh.Rotation.Z)
                             * TGCMatrix.Translation(mesh.Position);
            mesh.Render();

            textHelp.render();

            //Help
            if (Input.keyPressed(Key.H))
            {
                helpForm.ShowDialog();
            }

            PostRender();
        }
Esempio n. 20
0
        protected override void Init()
        {
            var MediaDir = contexto.MediaDir;
            var loader   = new TgcSceneLoader();

            scene       = loader.loadSceneFromFile(GameModel.Media + "escenarios\\playa\\playa-TgcScene.xml");
            this.planos = loader.loadSceneFromFile(GameModel.Media + "planos\\playa-TgcScene.xml");

            planoIzq = this.planos.getMeshByName("planoIzq");
            planoIzq.AutoTransform = false;

            planoDer = this.planos.getMeshByName("planoDer");
            planoDer.AutoTransform = false;

            planoBack = this.planos.getMeshByName("planoInicio");
            planoBack.AutoTransform = false;

            planoPiso = this.planos.getMeshByName("planoPiso");
            planoPiso.AutoTransform = false;

            planoFront = this.planos.getMeshByName("planoFin");
            planoFront.AutoTransform = false;

            // para probar colision con camara
            colisionablesConCamara   = new List <TgcBoundingAxisAlignBox>();
            planoArbol               = loader.loadSceneFromFile(MediaDir + "planos\\planoPiso-TgcScene.xml").Meshes[0];
            planoArbol.AutoTransform = false;
            planoArbol.BoundingBox.transform(TGCMatrix.Scaling(1.5f, 1, 0.5f) * TGCMatrix.Translation(-40, 30, 0));
            colisionablesConCamara.Add(planoArbol.BoundingBox);
            //

            GenerarCajas();
        }
 public void Init(FPSCamara Camara)
 {
     mesh           = TGCBox.fromSize(size, null);
     mesh.Position  = posicionMenu;
     this.Camara    = Camara;
     mesh.Transform = TGCMatrix.Scaling(mesh.Scale) * TGCMatrix.Translation(mesh.Position);
 }
 public override void Render()
 {
     //el body muere antes al colisionar y tira exception
     body.Translate(new Vector3(1, -3, -10));
     esfera.Transform = TGCMatrix.Scaling(15, 15, 15) * new TGCMatrix(body.InterpolationWorldTransform);
     esfera.Render();
 }
Esempio n. 23
0
        public void InstanciarPersonaje()
        {
            //Paths para archivo XML de la malla
            var pathMesh = MediaDir + "SkeletalAnimations\\BasicHuman\\WomanJeans-TgcSkeletalMesh.xml";

            //Path para carpeta de texturas de la malla
            var mediaPath = MediaDir + "SkeletalAnimations\\BasicHuman\\";

            //Lista de animaciones disponibles
            string[] animationList =
            {
                "CrouchWalk",
                "FlyingKick",
                "HighKick",
                "Jump",
                "LowKick",
                "Push",
                "Run",
                "StandBy",
                "Talk",
                "Walk"
            };

            //Crear rutas con cada animacion
            var animationsPath = new string[animationList.Length];

            for (var i = 0; i < animationList.Length; i++)
            {
                animationsPath[i] = MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + animationList[i] + "-TgcSkeletalAnim.xml";
            }

            //Cargar mesh y animaciones
            TgcSkeletalLoader loader = new TgcSkeletalLoader();

            mesh = loader.loadMeshAndAnimationsFromFile(pathMesh, mediaPath, animationsPath);

            mesh.Transform = TGCMatrix.Scaling(2f, 2f, 2f);
            mesh.Position  = new TGCVector3(100, 50, 100);
            //mesh.rotateY(Geometry.DegreeToRadian(180f));

            //Crear esqueleto a modo Debug
            //meshito.buildSkletonMesh();

            //Elegir animacion Caminando
            //mesh.playAnimation(selectedAnim, true);



            //Crear caja como modelo de Attachment del hueso "Bip01 L Hand"
            //Queremos que se haga un attachment de la linterna y la vela eventualmente

            /*
             * attachment = new TgcSkeletalBoneAttach();
             * var attachmentBox = TGCBox.fromSize(new TGCVector3(5, 100, 5), Color.Blue);
             * attachment.Mesh = attachmentBox.ToMesh("attachment");
             * attachment.Bone = mesh.getBoneByName("Bip01 L Hand");
             * attachment.Offset = TGCMatrix.Translation(10, -40, 0);
             * attachment.updateValues();
             */
        }
Esempio n. 24
0
        private void addTrees()
        {
            var pino = GetMeshFromScene("Pino-TgcScene.xml");

            pino.AlphaBlendEnable = false;//no se porque lo tenia seteado en true

            for (int j = 1; j < Chunks.chunksPerDim - 1; j++)
            {
                for (int k = 1; k < Chunks.chunksPerDim - 1; k++)
                {
                    if (coordsOccupied(j, k))
                    {
                        continue;
                    }

                    for (var i = 0; i < treesPerChunk; i++)
                    {
                        Meshc meshc = new Meshc();
                        meshc.mesh = pino;
                        meshc.type = 1;

                        TGCVector3 pos = genPosInChunk(j, k);

                        var scale = TGCVector3.One * Random.Next(20, 500);

                        meshc.originalMesh = TGCMatrix.Scaling(scale) * TGCMatrix.Translation(pos);

                        var box  = meshc.mesh.BoundingBox;
                        var size = box.calculateSize();
                        var posb = box.calculateBoxCenter();

                        size.X *= .1f;
                        size.Z *= .1f;

                        posb.X -= size.X * .2f;

                        meshc.paralleliped = Parallelepiped.fromSizePosition(
                            size,
                            posb
                            );


                        meshc.deformation     = new TGCMatrix();
                        meshc.deformation.M11 = (float)Random.NextDouble() * 2f - 1f;
                        meshc.deformation.M12 = (float)Random.NextDouble() * 2f - 1f;
                        meshc.deformation.M13 = (float)Random.NextDouble() * 2f - 1f;
                        meshc.deformation.M21 = (float)Random.NextDouble() * 2f - 1f;
                        meshc.deformation.M22 = (float)Random.NextDouble() * 2f - 1f;
                        meshc.deformation.M23 = (float)Random.NextDouble() * 2f - 1f;
                        meshc.deformation.M31 = (float)Random.NextDouble() * 2f - 1f;
                        meshc.deformation.M32 = (float)Random.NextDouble() * 2f - 1f;
                        meshc.deformation.M33 = (float)Random.NextDouble() * 2f - 1f;
                        meshc.deformation.M42 = -1.4f;

                        meshc.deform();
                    }
                }
            }
        }
Esempio n. 25
0
 private void updateMesh()
 {
     mesh.Transform =
         TGCMatrix.RotationAxis(TGCVector3.Cross(lookAt, lookin),
                                -(float)Math.Acos(TGCVector3.Dot(lookAt, lookin)))
         * TGCMatrix.Scaling(TGCVector3.One * 30)
         * TGCMatrix.Translation(pos);
 }
Esempio n. 26
0
 /// <summary>
 ///     Actualiza la escala de la vegetacion segun la variacion de escala scaleRatioXZ
 /// </summary>
 /// <param name="scaleRatioXZ"></param>
 private void updateVegetationScale(float scaleRatioXZ)
 {
     foreach (var v in Vegetation)
     {
         v.Scale    = new TGCVector3(v.Scale.X * scaleRatioXZ, v.Scale.Y * scaleRatioXZ, v.Scale.Z * scaleRatioXZ);
         v.Position = TGCVector3.TransformCoordinate(v.Position, TGCMatrix.Scaling(scaleRatioXZ, 1, scaleRatioXZ));
     }
 }
Esempio n. 27
0
        public CharacterSelect(GameModel gameModel, MyAbstractions.Tgc3dSound init)
        {
            this.gameModel = gameModel;
            this.init      = init;
            this.init.play(true);
            this.planes.Add(new Plane(new TGCVector3(-90, 0, -90), new TGCVector3(90, 0, 90), new TGCVector3(0, 1, 0), "Otros\\Paredes\\2.jpg", 1, 1));
            this.planes.Add(new Plane(new TGCVector3(-90, 0, -90), new TGCVector3(-90, 50, 90), new TGCVector3(1, 0, 0), "Otros\\Paredes\\1.jpg", 1, 1));
            this.planes.Add(new Plane(new TGCVector3(90, 0, -90), new TGCVector3(90, 50, 90), new TGCVector3(-1, 0, 0), "Otros\\Paredes\\4.jpg", 1, 1));
            this.planes.Add(new Plane(new TGCVector3(-90, 0, -90), new TGCVector3(90, 50, -90), new TGCVector3(0, 0, 1), "Otros\\Paredes\\3.jpg", 1, 1));
            this.gameModel.Camara = new ThirdPersonCamera(new TGCVector3(0, 0, 0), 100f, 150f);

            this.soundManager = new SoundsManager();
            var auto1 = new Van(new TGCVector3(0f, 0f, 0f), soundManager);

            auto1.matrixs.SetScalation(TGCMatrix.Scaling(0.2f, 0.2f, 0.2f));
            auto1.Transform();

            this.soundManager = new SoundsManager();
            var auto2 = new Car(new TGCVector3(0f, 0f, 0f), soundManager);

            auto2.matrixs.SetScalation(TGCMatrix.Scaling(0.3f, 0.3f, 0.3f));
            auto2.Transform();

            this.soundManager = new SoundsManager();
            var auto3 = new Hummer(new TGCVector3(0f, 0f, 0f), soundManager);

            auto3.matrixs.SetScalation(TGCMatrix.Scaling(0.25f, 0.25f, 0.25f));
            auto3.Transform();

            autos = new List <Vehicle>
            {
                auto1,
                auto2,
                auto3
            };

            selectedCar = auto1;
            CarsCount   = autos.Count - 1;


            var deviceWidth  = D3DDevice.Instance.Width;
            var deviceHeight = D3DDevice.Instance.Height;

            choose          = new CustomSprite();
            choose.Bitmap   = new CustomBitmap(MediaDir + "GUI\\Menu\\choose.png", D3DDevice.Instance.Device);
            choose.Position = new TGCVector2((deviceWidth / 2f) - choose.Bitmap.Width / 2, deviceHeight * 0.6f);

            rightArrow          = new CustomSprite();
            rightArrow.Bitmap   = new CustomBitmap(MediaDir + "GUI\\Menu\\right-arrow.png", D3DDevice.Instance.Device);
            rightArrow.Position = new TGCVector2(deviceWidth / 2 + rightArrow.Bitmap.Width * 3 / 4, deviceHeight / 2 - rightArrow.Bitmap.Height * 0.2f);
            rightArrow.Scaling  = new TGCVector2(0.2f, 0.2f);

            leftArrow          = new CustomSprite();
            leftArrow.Bitmap   = new CustomBitmap(MediaDir + "GUI\\Menu\\right-arrow.png", D3DDevice.Instance.Device);
            leftArrow.Rotation = FastMath.PI;
            leftArrow.Position = new TGCVector2(deviceWidth / 2 - leftArrow.Bitmap.Width * 3 / 4, deviceHeight / 2);
            leftArrow.Scaling  = new TGCVector2(0.2f, 0.2f);
        }
Esempio n. 28
0
 public Wheel(TgcMesh mesh, TGCVector3 traslado, TGCVector3 escalado)
 {
     this.mesh          = mesh;
     mesh.AutoTransform = false;
     trasladoInicial    = TGCMatrix.Translation(traslado);
     vectorLimiteIzquierdo.TransformCoordinate(TGCMatrix.RotationY(-FastMath.QUARTER_PI));
     vectorLimiteDerecho.TransformCoordinate(TGCMatrix.RotationY(FastMath.QUARTER_PI));
     scalation = TGCMatrix.Scaling(escalado);
 }
Esempio n. 29
0
        public void addCandles()
        {
            candleMesh = GetMeshFromScene("Vela-TgcScene.xml");
            //candleMesh.Effect = shader;
            //candleMesh.Technique = "DIFFUSE_MAP";
            for (int i = 0; i < g.cameraSprites.candlesInMap; i++)
            {
                int j, k;
                do
                {
                    j = Random.Next(1, Chunks.chunksPerDim - 1);
                    k = Random.Next(1, Chunks.chunksPerDim - 1);

                    var pos = genPosInChunk(j, k);
                    pos.Y += 200f;

                    if (checkColission(pos, 700f))
                    {
                        continue;
                    }

                    var candleMeshc = new Meshc();
                    //un poco excesivo que sea un meshc, lo eficiente seria que vela sea un tipo propio con una colision
                    //por radio. Pero hacer eso hace agregar un nuevo tipo de meshc, lo que podria hacer el codigo mas lento
                    //si sigo el camino de no usar polimorfismo. Igual ni ganas de agregar otro tipo. Que sea un meshc tiene
                    //los beneficios de que se va a poder deformar, y estas colisiones van a evitar que las velas se superpongan
                    //aunque agregar codigo para que se haga eso tampoco es una locura

                    candleMeshc.mesh         = candleMesh;
                    candleMeshc.originalMesh = TGCMatrix.Scaling(new TGCVector3(10, 15, 10)) * TGCMatrix.Translation(pos);

                    var box  = candleMeshc.mesh.BoundingBox;
                    var size = box.calculateSize();
                    var posb = box.calculateBoxCenter();

                    size.X *= 2.5f;
                    size.Y *= 10f;
                    size.Z *= 2.5f; //estaria bueno que tgc tenga multiplicacion miembro a miembro

                    candleMeshc.paralleliped = Parallelepiped.fromSizePosition(
                        size,
                        posb
                        );

                    //no uso  transformColission porque hace caer 4 vertices, lo que tiene potencial de registrar la
                    //vela en mas de un chunk
                    candleMeshc.paralleliped.transform(candleMeshc.originalMesh);
                    Chunk c = g.chunks.fromCoordinates(candleMeshc.paralleliped.transformedVertex[0]);
                    if (c != null)
                    {
                        c.meshes.Add(candleMeshc);
                    }

                    break;
                } while (true);
            }
        }
Esempio n. 30
0
        public TGCMatrix GenerateTransformation(TGCVector3 escala, TGCVector3 rotacion, TGCVector3 traslado)
        {
            TGCMatrix matrixEscalado   = TGCMatrix.Scaling(escala);
            TGCMatrix matrixRotacion   = TGCMatrix.RotationYawPitchRoll(rotacion.Y, rotacion.X, rotacion.Z);
            TGCMatrix matrixTraslacion = TGCMatrix.Translation(traslado);
            TGCMatrix transformacion   = matrixEscalado * matrixRotacion * matrixTraslacion;

            return(transformacion);
        }