Esempio n. 1
0
        public override void Update()
        {
            PreUpdate();
            var velocidadCaminar = VELOCIDAD_DESPLAZAMIENTO * ElapsedTime;

            //Calcular proxima posicion de personaje segun Input
            var moving   = false;
            var movement = TGCVector3.Empty;

            //Adelante
            if (Input.keyDown(Key.W))
            {
                movement.Z = velocidadCaminar;
                moving     = true;
            }

            //Atras
            if (Input.keyDown(Key.S))
            {
                movement.Z = -velocidadCaminar;
                moving     = true;
            }

            //Derecha
            if (Input.keyDown(Key.D))
            {
                movement.X = velocidadCaminar;
                moving     = true;
            }

            //Izquierda
            if (Input.keyDown(Key.A))
            {
                movement.X = -velocidadCaminar;
                moving     = true;
            }
            //Salto
            if (Input.keyDown(Key.Space))
            {
                movement.Y = velocidadCaminar;
                moving     = true;
            }
            //Agachar
            if (Input.keyDown(Key.LeftControl))
            {
                movement.Y = -velocidadCaminar;
                moving     = true;
            }
            //Si hubo desplazamiento
            if (moving)
            {
                //Aplicar movimiento, internamente suma valores a la posicion actual del mesh.
                mesh.Position  = mesh.Position + movement;
                mesh.Transform = TGCMatrix.Translation(mesh.Position);
                mesh.updateBoundingBox();
            }
            //Hacer que la camara siga al personaje en su nueva posicion
            camaraInterna.Target = mesh.Position;

            //Detectar colision con triangulo
            if (TgcCollisionUtils.testTriangleAABB(TGCVector3.FromVector3(triangle[0].Position), TGCVector3.FromVector3(triangle[1].Position), TGCVector3.FromVector3(triangle[2].Position),
                                                   mesh.BoundingBox))
            {
                triangle[0].Color = Color.Red.ToArgb();
                triangle[1].Color = Color.Red.ToArgb();
                triangle[2].Color = Color.Red.ToArgb();
            }
            else
            {
                triangle[0].Color = Color.Green.ToArgb();
                triangle[1].Color = Color.Green.ToArgb();
                triangle[2].Color = Color.Green.ToArgb();
            }
            //Detectar colision con el otro AABB
            if (TgcCollisionUtils.testAABBAABB(mesh.BoundingBox, box2.BoundingBox))
            {
                box2.Color = Color.Red;
                box2.updateValues();
            }
            else
            {
                box2.Color = Color.Violet;
                box2.updateValues();
            }
            //Detectar colision con la esfera
            if (TgcCollisionUtils.testSphereAABB(boundingSphere, mesh.BoundingBox))
            {
                boundingSphere.setRenderColor(Color.Red);
            }
            else
            {
                boundingSphere.setRenderColor(Color.Yellow);
            }

            //Detectar colision con la obb
            if (TgcCollisionUtils.testObbAABB(obb, mesh.BoundingBox))
            {
                obb.setRenderColor(Color.Red);
            }
            else
            {
                obb.setRenderColor(Color.Yellow);
            }
            PostUpdate();
        }
Esempio n. 2
0
        public void Update()
        {
            var velocidadCaminar  = 300f;
            var velocidadSalto    = 100f;
            var velocidadRotacion = 120f;

            vectorDesplazamiento = TGCVector3.Empty;
            vectorColision       = TGCVector3.Empty;

            //Calcular proxima posicion de personaje segun Input
            var   Input       = GModel.Input;
            var   moveForward = 0f;
            var   moveJump    = 0f;
            float rotate      = 0;
            var   moving      = false;
            var   rotating    = false;

            var lastPos = personaje.Position;

            desplazamientoDePlataforma = TGCVector3.Empty;

            //Adelante
            if (Input.keyDown(Key.W))
            {
                moveForward = velocidadCaminar * GModel.ElapsedTime;
                moving      = true;
            }

            //Atras
            if (Input.keyDown(Key.S))
            {
                moveForward = -velocidadCaminar * GModel.ElapsedTime;
                moving      = true;
            }

            //Derecha
            if (Input.keyDown(Key.D))
            {
                rotate   = velocidadRotacion;
                rotating = true;
            }

            //Izquierda
            if (Input.keyDown(Key.A))
            {
                rotate   = -velocidadRotacion;
                rotating = true;
            }

            //Si hubo rotacion
            if (rotating)
            {
                //Rotar personaje y la camara, hay que multiplicarlo por el tiempo transcurrido para no atarse a la velocidad el hardware
                var rotAngle = FastMath.ToRad(rotate * GModel.ElapsedTime);
                matrizRotacionPersonajeY *= TGCMatrix.RotationY(rotAngle);

                GModel.camaraInterna.rotateY(rotAngle);
                anguloDeRotacion += rotAngle;
                //Ajustar la matriz de rotacion segun el angulo de rotacion (sobre el sentido de la orientacion)
                //Lo que se desplaza en cada eje depende del angulo de rotacion
                //Cada componente podria separarse en funcion del seno y coseno
                orientacion.X = FastMath.Sin(anguloDeRotacion);
                orientacion.Z = FastMath.Cos(anguloDeRotacion);
            }

            if (moving)
            {
                //Activar animacion de caminando
                personaje.playAnimation("Caminando", true);
                //Ajustar el vector desplazamiento en base a lo que se movio y la orientacion que tiene
                vectorDesplazamiento.X += moveForward * orientacion.X;
                vectorDesplazamiento.Z += moveForward * orientacion.Z;
            } //Si no se esta moviendo, activar animacion de Parado
            else
            {
                personaje.playAnimation("Parado", true);
            }

            //----------Salto
            //Por el momento solamente parece que flota
            if (Input.keyDown(Key.Space) /*&& colliderY != null*/)
            {
                moveJump = velocidadSalto * GModel.ElapsedTime;
                vectorDesplazamiento.Y += moveJump;
            }

            //---------prueba gravedad----------

            vectorDesplazamiento.Y += FastMath.Clamp(gravedad * GModel.ElapsedTime, -10, 10);

            //--------Colision con el piso a nivel triangulo
            TgcBoundingAxisAlignBox colliderPlano = null;

            foreach (var obstaculo in GModel.escenario1.getPiso())
            {
                if (TgcCollisionUtils.testAABBAABB(personaje.BoundingBox, obstaculo.BoundingBox))
                {
                    colliderPlano = obstaculo.BoundingBox;
                    //No le afecta la gravedad si está en el piso
                    vectorDesplazamiento.Y -= FastMath.Clamp(gravedad * GModel.ElapsedTime, -10, 10);
                    break;
                }
            }

            this.posicion = posicion + vectorDesplazamiento;

            //Reseteo el vector desplazamiento una vez que lo sume
            vectorDesplazamiento = TGCVector3.Empty;

            //---------Colisiones objetos--------------------------
            var collide = false;

            foreach (var obstaculo in GModel.escenario1.getAABBDelEscenario() /*GModel.escenario1.getPared1()*/)
            {
                if (TgcCollisionUtils.testAABBAABB(personaje.BoundingBox, obstaculo))
                {
                    collide  = true;
                    collider = obstaculo;
                    break;
                }
            }

            //Una buena idea seria diferenciar las plataformas del resto de los objetos
            foreach (var plataforma in GModel.escenario1.getPlataformasDelEscenario())
            {
                if (TgcCollisionUtils.testAABBAABB(personaje.BoundingBox, plataforma))
                {
                    collide  = true;
                    collider = plataforma;
                    //Pensamos en calcular cuanto se desplaza la plataforma y mandarselo al personaje para que se muevan juntos
                    //Todavia no funciona como esperamos
                    desplazamientoDePlataforma = GModel.escenario1.desplazamientoDePlataforma(collider);
                    break;
                }
            }

            if (collide)
            {
                var movementRay = lastPos - posicion;
                //Cuando choca con algo que se ponga rojo, nos sirve para probar
                collider.setRenderColor(Color.Red);
                var rs = TGCVector3.Empty;
                if (((personaje.BoundingBox.PMax.X > collider.PMax.X && movementRay.X > 0) ||
                     (personaje.BoundingBox.PMin.X < collider.PMin.X && movementRay.X < 0)) &&
                    ((personaje.BoundingBox.PMax.Z > collider.PMax.Z && movementRay.Z > 0) ||
                     (personaje.BoundingBox.PMin.Z < collider.PMin.Z && movementRay.Z < 0)) &&
                    ((personaje.BoundingBox.PMax.Y > collider.PMax.Y && movementRay.Y > 0) ||
                     (personaje.BoundingBox.PMin.Y < collider.PMin.Y && movementRay.Y < 0)))
                {
                    if (personaje.Position.X > collider.PMin.X && personaje.Position.X < collider.PMax.X)
                    {
                        //El personaje esta contenido en el bounding X

                        rs = new TGCVector3(movementRay.X, movementRay.Y, 0);
                    }
                    if (personaje.Position.Z > collider.PMin.Z && personaje.Position.Z < collider.PMax.Z)
                    {
                        //El personaje esta contenido en el bounding Z

                        rs = new TGCVector3(0, movementRay.Y, movementRay.Z);
                    }
                    if (personaje.Position.Y > collider.PMin.Y && personaje.Position.Y < collider.PMax.Y)
                    {
                        //El personaje esta contenido en el bounding Y

                        rs = new TGCVector3(movementRay.X, 0, movementRay.Z);
                    }
                }
                else
                {
                    if ((personaje.BoundingBox.PMax.X > collider.PMax.X && movementRay.X > 0) ||
                        (personaje.BoundingBox.PMin.X < collider.PMin.X && movementRay.X < 0))
                    {
                        rs = new TGCVector3(0, movementRay.Y, movementRay.Z);
                    }
                    if ((personaje.BoundingBox.PMax.Z > collider.PMax.Z && movementRay.Z > 0) ||
                        (personaje.BoundingBox.PMin.Z < collider.PMin.Z && movementRay.Z < 0))
                    {
                        rs = new TGCVector3(movementRay.X, movementRay.Y, 0);
                    }
                    if ((personaje.BoundingBox.PMax.Y > collider.PMax.Y && movementRay.Y > 0) ||
                        (personaje.BoundingBox.PMin.Y < collider.PMin.Y && movementRay.Y < 0))
                    {
                        //Si esta sobre un plano XZ tampoco deberia afectarle la gravedad
                        vectorDesplazamiento.Y -= FastMath.Clamp(gravedad * GModel.ElapsedTime, -10, 10);
                        rs = new TGCVector3(movementRay.X, 0, movementRay.Z);
                    }
                }
                //El vector rs actua como "freno" al movimiento del personaje
                //Le "descuento" la gravedad si es que colisiona con el plano XZ
                personaje.Position = lastPos - rs + new TGCVector3(0, vectorDesplazamiento.Y, 0);
                posicion           = personaje.Position;
            }

            personaje.Position = posicion;

            //Una forma de reiniciar, que se active con R o cuando el personaje muere
            //Por ahora el personaje muere solamente si su coordenada en Y es inferior a un valor determinado
            if (Input.keyDown(Key.R) || this.estaMuerto())
            {
                posicion = this.checkpoint;
            }

            matrizPosicionamientoPersonaje = TGCMatrix.Translation(posicion /*+ desplazamientoDePlataforma*/);

            GModel.camaraInterna.Target = GModel.tgcPersonaje.getPosicion();
        }
Esempio n. 3
0
        public TGCMatrix CalcularMatriz2(TGCVector3 Pos, TGCVector3 Scale, TGCVector3 Dir, TGCVector3 VUP)
        {
            var matWorld = TGCMatrix.Scaling(Scale);

            matWorld = matWorld * TGCMatrix.RotationY(-(float)Math.PI / 2.0f)
                       * TGCMatrix.RotationYawPitchRoll(yaw, pitch, 0);

            // determino la orientacion
            var U = TGCVector3.Cross(VUP, Dir);

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

            V.Normalize();
            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. 4
0
        /// <summary>
        ///     Crear un TgcMeshBumpMapping en base a un TgcMesh y su normalMap.
        ///     Solo esta soportado un TgcMehs MeshRenderType = DiffuseMap
        /// </summary>
        public static TgcMeshBumpMapping fromTgcMesh(TgcMesh mesh, TgcTexture[] normalMaps)
        {
            if (mesh.RenderType != MeshRenderType.DIFFUSE_MAP)
            {
                throw new Exception("Solo esta soportado MeshRenderType = DiffuseMap");
            }

            //Obtener vertexBuffer original
            var origVertexBuffer = (TgcSceneLoader.DiffuseMapVertex[])mesh.D3dMesh.LockVertexBuffer(
                typeof(TgcSceneLoader.DiffuseMapVertex), LockFlags.ReadOnly, mesh.D3dMesh.NumberVertices);

            mesh.D3dMesh.UnlockVertexBuffer();

            //Crear nuevo Mesh de DirectX
            var triCount = origVertexBuffer.Length / 3;
            var d3dMesh  = new Mesh(triCount, origVertexBuffer.Length, MeshFlags.Managed, BumpMappingVertexElements,
                                    D3DDevice.Instance.Device);

            //Calcular normales recorriendo los triangulos
            var normals = new TGCVector3[origVertexBuffer.Length];

            for (var i = 0; i < normals.Length; i++)
            {
                normals[i] = TGCVector3.Empty;
            }
            for (var i = 0; i < triCount; i++)
            {
                //Los 3 vertices del triangulo
                var v1 = origVertexBuffer[i * 3];
                var v2 = origVertexBuffer[i * 3 + 1];
                var v3 = origVertexBuffer[i * 3 + 2];

                //Face-normal (left-handend)
                var a = v2.Position - v1.Position;
                var b = v3.Position - v1.Position;
                var n = TGCVector3.Cross(a, b);

                //Acumular normal del vertice segun todas sus Face-normal
                normals[i * 3]     += n;
                normals[i * 3 + 1] += n;
                normals[i * 3 + 2] += n;
            }

            //Normalizar normales
            for (var i = 0; i < normals.Length; i++)
            {
                normals[i] = TGCVector3.Normalize(normals[i]);
            }

            //Crear nuevo VertexBuffer
            using (var vb = d3dMesh.VertexBuffer)
            {
                //Iterar sobre triangulos
                var data = vb.Lock(0, 0, LockFlags.None);
                for (var i = 0; i < triCount; i++)
                {
                    //Vertices originales
                    var vOrig1 = origVertexBuffer[i * 3];
                    var vOrig2 = origVertexBuffer[i * 3 + 1];
                    var vOrig3 = origVertexBuffer[i * 3 + 2];

                    //Nuevo vertice 1
                    var v1 = new BumpMappingVertex();
                    v1.Position = vOrig1.Position;
                    v1.Color    = vOrig1.Color;
                    v1.Tu       = vOrig1.Tu;
                    v1.Tv       = vOrig1.Tv;
                    v1.Normal   = normals[i * 3];

                    //Nuevo vertice 2
                    var v2 = new BumpMappingVertex();
                    v2.Position = vOrig2.Position;
                    v2.Color    = vOrig2.Color;
                    v2.Tu       = vOrig2.Tu;
                    v2.Tv       = vOrig2.Tv;
                    v2.Normal   = normals[i * 3 + 1];

                    //Nuevo vertice 3
                    var v3 = new BumpMappingVertex();
                    v3.Position = vOrig3.Position;
                    v3.Color    = vOrig3.Color;
                    v3.Tu       = vOrig3.Tu;
                    v3.Tv       = vOrig3.Tv;
                    v3.Normal   = normals[i * 3 + 2];

                    //Calcular tangente y binormal para todo el triangulo y cargarlas en cada vertice
                    TGCVector3 tangent;
                    TGCVector3 binormal;
                    computeTangentBinormal(v1, v2, v3, out tangent, out binormal);
                    v1.Tangent  = tangent;
                    v1.Binormal = binormal;
                    v2.Tangent  = tangent;
                    v2.Binormal = binormal;
                    v3.Tangent  = tangent;
                    v3.Binormal = binormal;

                    //Cargar VertexBuffer
                    data.Write(v1);
                    data.Write(v2);
                    data.Write(v3);
                }

                vb.Unlock();
            }

            //Cargar IndexBuffer en forma plana
            using (var ib = d3dMesh.IndexBuffer)
            {
                var indices = new short[origVertexBuffer.Length];
                for (var i = 0; i < indices.Length; i++)
                {
                    indices[i] = (short)i;
                }
                ib.SetData(indices, 0, LockFlags.None);
            }

            //Clonar texturas y materials
            var diffuseMaps = new TgcTexture[mesh.DiffuseMaps.Length];
            var materials   = new Material[mesh.Materials.Length];

            for (var i = 0; i < mesh.DiffuseMaps.Length; i++)
            {
                diffuseMaps[i] = mesh.DiffuseMaps[i].Clone();
                materials[i]   = D3DDevice.DEFAULT_MATERIAL;
            }

            //Cargar attributeBuffer
            if (diffuseMaps.Length > 1)
            {
                var origAttributeBuffer = mesh.D3dMesh.LockAttributeBufferArray(LockFlags.None);
                var newAttributeBuffer  = d3dMesh.LockAttributeBufferArray(LockFlags.None);
                Array.Copy(origAttributeBuffer, newAttributeBuffer, origAttributeBuffer.Length);
                mesh.D3dMesh.UnlockAttributeBuffer();
                d3dMesh.UnlockAttributeBuffer(newAttributeBuffer);
            }

            //Crear mesh de BumpMapping Mesh
            var bumpMesh = new TgcMeshBumpMapping(d3dMesh, mesh.Name, mesh.RenderType);

            bumpMesh.diffuseMaps      = diffuseMaps;
            bumpMesh.materials        = materials;
            bumpMesh.NormalMaps       = normalMaps;
            bumpMesh.layer            = mesh.Layer;
            bumpMesh.AlphaBlendEnable = mesh.AlphaBlendEnable;
            bumpMesh.UserProperties   = mesh.UserProperties;
            bumpMesh.boundingBox      = mesh.BoundingBox.clone();
            bumpMesh.enabled          = true;

            return(bumpMesh);
        }
Esempio n. 5
0
 public TgcMesh createNewMeshInstance(string meshName, TgcMesh originalMesh, TGCVector3 translation,
                                      TGCVector3 rotation, TGCVector3 scale)
 {
     return(new TgcMeshBumpMapping(meshName, originalMesh, translation, rotation, scale));
 }
        public RigidBody CreatePlane(TgcPlane plane)
        {
            var halfSize = new TGCVector3(plane.Size.X / 2, 2000, plane.Size.Z / 2).ToBulletVector3();

            return(CreateRigidBody(new TGCVector3(plane.Position.X, plane.Position.Y - 2000, plane.Position.Z), halfSize, 0));
        }
Esempio n. 7
0
 /// <summary>
 ///     Mover objeto
 /// </summary>
 public abstract void move(TGCVector3 move);
Esempio n. 8
0
 /// <summary>
 ///     Crea una caja con centro (0,0,0) y el tamaño especificado
 /// </summary>
 /// <param name="size">Tamaño de la caja</param>
 /// <returns>Caja creada</returns>
 public static TGCBox fromSize(TGCVector3 size)
 {
     return(fromSize(TGCVector3.Empty, size));
 }
Esempio n. 9
0
 /// <summary>
 ///     Crea una caja con centro (0,0,0) y el tamaño especificado, con el color especificado
 /// </summary>
 /// <param name="size">Tamaño de la caja</param>
 /// <param name="color">Color de la caja</param>
 /// <returns>Caja creada</returns>
 public static TGCBox fromSize(TGCVector3 size, Color color)
 {
     return(fromSize(TGCVector3.Empty, size, color));
 }
Esempio n. 10
0
 /// <summary>
 ///     Configurar valores de posicion y tamaño en forma conjunta
 /// </summary>
 /// <param name="position">Centro de la caja</param>
 /// <param name="size">Tamaño de la caja</param>
 public void setPositionSize(TGCVector3 position, TGCVector3 size)
 {
     translation = position;
     this.size   = size;
     updateBoundingBox();
 }
Esempio n. 11
0
        /// <summary>
        ///     Actualiza el BoundingBox de la caja.
        ///     No contempla rotacion
        /// </summary>
        private void updateBoundingBox()
        {
            var midSize = TGCVector3.Scale(size, 0.5f);

            BoundingBox.setExtremes(TGCVector3.Subtract(translation, midSize), TGCVector3.Add(translation, midSize));
        }
Esempio n. 12
0
 /// <summary>
 ///     Obtiene la posicion absoluta de la malla, recibiendo un vector ya creado para
 ///     almacenar el resultado
 /// </summary>
 /// <param name="pos">Vector ya creado en el que se carga el resultado</param>
 public void GetPosition(TGCVector3 pos)
 {
     pos.X = translation.X;
     pos.Y = translation.Y;
     pos.Z = translation.Z;
 }
Esempio n. 13
0
 public void Move(TGCVector3 v)
 {
     Move(v.X, v.Y, v.Z);
 }
Esempio n. 14
0
        public override void Init()
        {
            var loader = new TgcSceneLoader();
            var scene  = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\Patrullero\\Patrullero-TgcScene.xml");

            mesh       = scene.Meshes[0];
            mesh.Scale = new TGCVector3(0.25f, 0.25f, 0.25f);

            //triangulo
            triangle    = new CustomVertex.PositionColored[3];
            triangle[0] = new CustomVertex.PositionColored(-100, 0, 0, Color.Green.ToArgb());
            triangle[1] = new CustomVertex.PositionColored(0, 0, 50, Color.Green.ToArgb());
            triangle[2] = new CustomVertex.PositionColored(0, 100, 0, Color.Green.ToArgb());
            triagleAABB = TgcBoundingAxisAlignBox.computeFromPoints(new[]
                                                                    { TGCVector3.FromVector3(triangle[0].Position), TGCVector3.FromVector3(triangle[1].Position), TGCVector3.FromVector3(triangle[2].Position) });

            //box2
            box2 = TGCBox.fromSize(new TGCVector3(-50, 10, -20), new TGCVector3(15, 15, 15), Color.Violet);

            //sphere
            boundingSphere = new TgcBoundingSphere(new TGCVector3(30, 20, -20), 15);

            //OBB: computar OBB a partir del AABB del mesh.
            meshObb =
                loader.loadSceneFromFile(MediaDir +
                                         "MeshCreator\\Meshes\\Objetos\\Catapulta\\Catapulta-TgcScene.xml")
                .Meshes[0];
            meshObb.Scale    = new TGCVector3(0.1f, 0.1f, 0.1f);
            meshObb.Position = new TGCVector3(100, 0, 30);
            meshObb.updateBoundingBox();
            //Computar OBB a partir del AABB del mesh. Inicialmente genera el mismo volumen que el AABB, pero luego te permite rotarlo (cosa que el AABB no puede)
            obb = TgcBoundingOrientedBox.computeFromAABB(meshObb.BoundingBox);
            //Otra alternativa es computar OBB a partir de sus vertices. Esto genera un OBB lo mas apretado posible pero es una operacion costosa
            //obb = TgcBoundingOrientedBox.computeFromPoints(mesh.getVertexPositions());

            //Rotar mesh y rotar OBB. A diferencia del AABB, nosotros tenemos que mantener el OBB actualizado segun cada movimiento del mesh
            meshObb.Rotation = new TGCVector3(0, FastMath.PI / 4, 0);
            //Los obb tienen una especie de autotransform aun.
            obb.rotate(new TGCVector3(0, FastMath.PI / 4, 0));

            //Configurar camara en Tercer Persona
            camaraInterna = new TgcThirdPersonCamera(mesh.Position, 30, -75);
            Camara        = camaraInterna;
        }
Esempio n. 15
0
 /// <summary>
 ///     Constructor de la camara a partir de un TgcD3dInput y un positionEye. Los atributos mouseCenter a partir del centro del a pantalla, RotationSpeed 1.0f,
 ///     MovementSpeed y JumpSpeed 500f, el directionView (0,0,-1)
 /// </summary>
 /// <param name="positionEye"></param>
 /// <param name="input"></param>
 public TgcFpsCamera(TGCVector3 positionEye, TgcD3dInput input) : this(input)
 {
     this.positionEye = positionEye;
 }
Esempio n. 16
0
 /// <summary>
 ///     Crea una caja con centro (0,0,0) y el tamaño especificado, con la textura especificada
 /// </summary>
 /// <param name="size">Tamaño de la caja</param>
 /// <param name="texture">Textura de la caja</param>
 /// <returns>Caja creada</returns>
 public static TGCBox fromSize(TGCVector3 size, TgcTexture texture)
 {
     return(fromSize(TGCVector3.Empty, size, texture));
 }
Esempio n. 17
0
 /// <summary>
 ///  Constructor de la camara a partir de un TgcD3dInput y un positionEye, moveSpeed y jumpSpeed. Los atributos mouseCenter a partir del centro del a pantalla, RotationSpeed 1.0f,
 ///  el directionView (0,0,-1)
 /// </summary>
 /// <param name="positionEye"></param>
 /// <param name="moveSpeed"></param>
 /// <param name="jumpSpeed"></param>
 /// <param name="input"></param>
 public TgcFpsCamera(TGCVector3 positionEye, float moveSpeed, float jumpSpeed, TgcD3dInput input)
     : this(positionEye, input)
 {
     this.MovementSpeed = moveSpeed;
     this.JumpSpeed     = jumpSpeed;
 }
Esempio n. 18
0
        public void Init(string MediaDir)
        {
            #region Configuracion Basica de World

            //Creamos el mundo fisico por defecto.
            collisionConfiguration = new DefaultCollisionConfiguration();
            dispatcher             = new CollisionDispatcher(collisionConfiguration);
            GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher);
            constraintSolver      = new SequentialImpulseConstraintSolver();
            overlappingPairCache  = new DbvtBroadphase(); //AxisSweep3(new BsVector3(-5000f, -5000f, -5000f), new BsVector3(5000f, 5000f, 5000f), 8192);
            dynamicsWorld         = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration);
            dynamicsWorld.Gravity = new TGCVector3(0, -100f, 0).ToBulletVector3();

            #endregion Configuracion Basica de World

            #region Capsula

            //Cuerpo rigido de una capsula basica
            capsuleRigidBody = BulletRigidBodyFactory.Instance.CreateCapsule(10, 50, new TGCVector3(200, 500, 200), 10, false);

            //Valores que podemos modificar a partir del RigidBody base
            capsuleRigidBody.SetDamping(0.1f, 0f);
            capsuleRigidBody.Restitution = 0.1f;
            capsuleRigidBody.Friction    = 1;

            //Agregamos el RidigBody al World
            dynamicsWorld.AddRigidBody(capsuleRigidBody);

            #endregion Capsula

            #region Terreno

            //Creamos el RigidBody basico del Terreno
            var meshRigidBody = BulletRigidBodyFactory.Instance.CreateSurfaceFromHeighMap(triangleDataVB);

            //Agregamos algo de friccion al RigidBody ya que este va a interactuar con objetos moviles
            //del World
            meshRigidBody.Friction = 0.5f;

            //Agregamos el RigidBody del terreno al World
            dynamicsWorld.AddRigidBody(meshRigidBody);

            #endregion Terreno

            #region Esfera

            //Creamos una esfera para interactuar
            pokeball = BulletRigidBodyFactory.Instance.CreateBall(10f, 0.5f, new TGCVector3(100f, 500f, 100f));
            pokeball.SetDamping(0.1f, 0.5f);
            pokeball.Restitution = 1f;
            //Agregamos la pokebola al World
            dynamicsWorld.AddRigidBody(pokeball);

            //Textura de pokebola
            var texturePokeball = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\pokeball.jpg");

            //Se crea una esfera de tamaño 1 para escalarla luego (en render)
            sphereMesh = new TGCSphere(1, texturePokeball, TGCVector3.Empty);

            //Tgc no crea el vertex buffer hasta invocar a update values.
            sphereMesh.updateValues();

            #endregion Esfera

            #region Personaje

            //Cargamos personaje
            var skeletalLoader = new TgcSkeletalLoader();
            personaje = skeletalLoader.loadMeshAndAnimationsFromFile(
                MediaDir + "SkeletalAnimations\\Robot\\Robot-TgcSkeletalMesh.xml",
                MediaDir + "SkeletalAnimations\\Robot\\",
                new[]
            {
                MediaDir + "SkeletalAnimations\\Robot\\Caminando-TgcSkeletalAnim.xml",
                MediaDir + "SkeletalAnimations\\Robot\\Parado-TgcSkeletalAnim.xml"
            });

            //Le cambiamos la textura para diferenciarlo un poco
            personaje.changeDiffuseMaps(new[]
            {
                TgcTexture.createTexture(D3DDevice.Instance.Device,
                                         MediaDir + "SkeletalAnimations\\Robot\\Textures\\uvwGreen.jpg")
            });

            //Configurar animacion inicial
            personaje.playAnimation("Parado", true);

            #endregion Personaje

            #region Cajas

            var sizeBox = 20f;

            //Textura de caja
            var textureBox = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"MeshCreator\Textures\Madera\cajaMadera2.jpg");

            box = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(0, 12, 0), 0, 0, 0, 0.5f, true);
            dynamicsWorld.AddRigidBody(box);
            boxMesh = TGCBox.fromSize(new TGCVector3(40f, 40f, 40f), textureBox);
            boxMesh.updateValues();

            sizeBox = 40f;
            boxB    = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(100, 40, 0), 0, 0, 0, 0.5f, true);
            dynamicsWorld.AddRigidBody(boxB);
            boxMeshB = TGCBox.fromSize(new TGCVector3(80f, 80f, 80f), textureBox);
            boxMeshB.updateValues();

            box45 = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(200, 40, 0), BulletSharp.MathUtil.SIMD_QUARTER_PI, 0, 0, 0.5f, true);
            dynamicsWorld.AddRigidBody(box45);

            boxPush = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0.5f, new TGCVector3(-200, 60, 0), BulletSharp.MathUtil.SIMD_QUARTER_PI, 0, 0, 0.25f, true);
            dynamicsWorld.AddRigidBody(boxPush);

            boxMeshPush = TGCBox.fromSize(new TGCVector3(80f, 80f, 80f), textureBox);
            boxMeshPush.updateValues();

            #endregion Cajas

            #region Escalera

            var a             = 0;
            var textureStones = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\stones.bmp");

            //la altura de cualquier cubo que quiera subir una capsula debe ser menor a la mitad del radio
            var size = new TGCVector3(50, 4, 20);
            escalon = TGCBox.fromSize(size, textureStones);

            //Se crean 10 escalonescd d
            while (a < 10)
            {
                escalonRigidBody = BulletRigidBodyFactory.Instance.CreateBox(size, 0, new TGCVector3(200, a * 4 + 10, a * 20 + 100), 0, 0, 0, 0.1f, true);

                escalonesRigidBodies.Add(escalonRigidBody);

                dynamicsWorld.AddRigidBody(escalonRigidBody);

                a++;
            }

            #endregion Escalera

            #region Plataforma

            textureStones       = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\cobblestone_quad.jpg");
            rigidBodyPlataforma = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(50f, 15f, 50f), 0, new TGCVector3(200, 42.5f, 315), 0, 0, 0, 0.5f, true);
            dynamicsWorld.AddRigidBody(rigidBodyPlataforma);
            plataforma = TGCBox.fromSize(new TGCVector3(50f, 15f, 50f), textureStones);
            plataforma.updateValues();

            #endregion Plataforma

            #region Columna

            columnaRigidBody = BulletRigidBodyFactory.Instance.CreateCylinder(new TGCVector3(10, 50, 10), new TGCVector3(100, 50, 100), 0);
            dynamicsWorld.AddRigidBody(columnaRigidBody);
            var columnaLoader = new TgcSceneLoader();
            columnaMesh          = columnaLoader.loadSceneFromFile(MediaDir + @"MeshCreator\Meshes\Cimientos\PilarEgipcio\PilarEgipcio-TgcScene.xml", MediaDir + @"MeshCreator\Meshes\Cimientos\PilarEgipcio\").Meshes[0];
            columnaMesh.Position = new TGCVector3(100, 7.5f, 100);
            columnaMesh.UpdateMeshTransform();

            #endregion Columna

            director = new TGCVector3(0, 0, 1);
        }
Esempio n. 19
0
 /// <summary>
 ///     Iniciar creacion de primitiva
 /// </summary>
 public abstract void initCreation(TGCVector3 gridPoint);
Esempio n. 20
0
        const float border = 60f; //para evitar atravesar esquinas alineadas con los vectores de movimiento
                                  //parece que con 30 es seguro, por las dudas lo subi hasta
                                  //justo antes de que sea notable cuando te deslizas por la pared
        public bool intersectRay(TgcRay ray, out float dist, out TGCVector3 q)
        {
            float t;

            dist = 9999999;
            var face = new TGCVector3[4];

            //
            //
            //      6 --- 7
            //     /|    /|
            //    2 --- 3 |
            //    | 4 --| 5
            //    |/    |/
            //    0 --- 1
            //
            //

            face[0] = transformedVertex[0] + new TGCVector3(-border, 0, 0);
            face[1] = transformedVertex[2] + new TGCVector3(-border, 0, 0);
            face[2] = transformedVertex[3] + new TGCVector3(border, 0, 0);
            face[3] = transformedVertex[1] + new TGCVector3(border, 0, 0);
            if (TgcCollisionUtils.intersectRayConvexPolygon(ray, face, out t, out q))
            {
                dist = Math.Min(t, dist);
            }

            face[0] = transformedVertex[2];
            face[1] = transformedVertex[6];
            face[2] = transformedVertex[4];
            face[3] = transformedVertex[0];
            if (TgcCollisionUtils.intersectRayConvexPolygon(ray, face, out t, out q))
            {
                dist = Math.Min(t, dist);
            }

            face[0] = transformedVertex[6] + new TGCVector3(-border, 0, 0);
            face[1] = transformedVertex[7] + new TGCVector3(border, 0, 0);
            face[2] = transformedVertex[5] + new TGCVector3(border, 0, 0);
            face[3] = transformedVertex[4] + new TGCVector3(-border, 0, 0);
            if (TgcCollisionUtils.intersectRayConvexPolygon(ray, face, out t, out q))
            {
                dist = Math.Min(t, dist);
            }

            face[0] = transformedVertex[7];
            face[1] = transformedVertex[5];
            face[2] = transformedVertex[1];
            face[3] = transformedVertex[3];
            if (TgcCollisionUtils.intersectRayConvexPolygon(ray, face, out t, out q))
            {
                dist = Math.Min(t, dist);
            }

            face[0] = transformedVertex[6];
            face[1] = transformedVertex[7];
            face[2] = transformedVertex[3];
            face[3] = transformedVertex[2];
            if (TgcCollisionUtils.intersectRayConvexPolygon(ray, face, out t, out q))
            {
                dist = Math.Min(t, dist);
            }

            face[0] = transformedVertex[0];
            face[1] = transformedVertex[4];
            face[2] = transformedVertex[5];
            face[3] = transformedVertex[1];
            if (TgcCollisionUtils.intersectRayConvexPolygon(ray, face, out t, out q))
            {
                dist = Math.Min(t, dist);
            }

            if (dist != 9999999)
            {
                t = dist;
                return(true);
            }
            return(false);
        }
Esempio n. 21
0
 /// <summary>
 ///     Aplicar rotacion absoluta del objeto respecto de un pivote
 /// </summary>
 public abstract void setRotationFromPivot(TGCVector3 rotation, TGCVector3 pivot);
 public void setTargetOffsets(TGCVector3 target, float offsetHeight, float offsetForward)
 {
     Target        = target;
     OffsetHeight  = offsetHeight;
     OffsetForward = offsetForward;
 }
Esempio n. 23
0
        /// <summary>
        ///     Calcular Tangent y Binormal en base a los 3 vertices de un triangulo y la normal del primero de ellos
        ///     Basado en: http://www.dhpoware.com/demos/d3d9NormalMapping.html
        /// </summary>
        public static void computeTangentBinormal(BumpMappingVertex v1, BumpMappingVertex v2, BumpMappingVertex v3,
                                                  out TGCVector3 tangent, out TGCVector3 binormal)
        {
            // Given the 3 vertices (position and texture coordinates) of a triangle
            // calculate and return the triangle's tangent vector. The handedness of
            // the local coordinate system is stored in tangent.w. The bitangent is
            // then: float3 bitangent = cross(normal, tangent.xyz) * tangent.w.

            // Create 2 vectors in object space.
            //
            // edge1 is the vector from vertex positions v1 to v2.
            // edge2 is the vector from vertex positions v1 to v3.
            var edge1 = v2.Position - v1.Position;
            var edge2 = v3.Position - v1.Position;

            edge1.Normalize();
            edge2.Normalize();

            // Create 2 vectors in tangent (texture) space that point in the same
            // direction as edge1 and edge2 (in object space).
            //
            // texEdge1 is the vector from texture coordinates texCoord1 to texCoord2.
            // texEdge2 is the vector from texture coordinates texCoord1 to texCoord3.
            var texEdge1 = new TGCVector2(v2.Tu - v1.Tu, v2.Tv - v1.Tv);
            var texEdge2 = new TGCVector2(v3.Tu - v1.Tu, v3.Tv - v1.Tv);

            texEdge1.Normalize();
            texEdge2.Normalize();

            // These 2 sets of vectors form the following system of equations:
            //
            //  edge1 = (texEdge1.x * tangent) + (texEdge1.y * bitangent)
            //  edge2 = (texEdge2.x * tangent) + (texEdge2.y * bitangent)
            //
            // Using matrix notation this system looks like:
            //
            //  [ edge1 ]     [ texEdge1.x  texEdge1.y ]  [ tangent   ]
            //  [       ]  =  [                        ]  [           ]
            //  [ edge2 ]     [ texEdge2.x  texEdge2.y ]  [ bitangent ]
            //
            // The solution is:
            //
            //  [ tangent   ]        1     [ texEdge2.y  -texEdge1.y ]  [ edge1 ]
            //  [           ]  =  -------  [                         ]  [       ]
            //  [ bitangent ]      det A   [-texEdge2.x   texEdge1.x ]  [ edge2 ]
            //
            //  where:
            //        [ texEdge1.x  texEdge1.y ]
            //    A = [                        ]
            //        [ texEdge2.x  texEdge2.y ]
            //
            //    det A = (texEdge1.x * texEdge2.y) - (texEdge1.y * texEdge2.x)
            //
            // From this solution the tangent space basis vectors are:
            //
            //    tangent = (1 / det A) * ( texEdge2.y * edge1 - texEdge1.y * edge2)
            //  bitangent = (1 / det A) * (-texEdge2.x * edge1 + texEdge1.x * edge2)
            //     normal = cross(tangent, bitangent)

            var det = texEdge1.X * texEdge2.Y - texEdge1.Y * texEdge2.X;

            if (FastMath.Abs(det) < 0.0001f) // almost equal to zero
            {
                tangent  = new TGCVector3(1.0f, 0.0f, 0.0f);
                binormal = new TGCVector3(0.0f, 1.0f, 0.0f);
            }
            else
            {
                det = 1.0f / det;

                tangent   = TGCVector3.Empty;
                tangent.X = (texEdge2.Y * edge1.X - texEdge1.Y * edge2.X) * det;
                tangent.Y = (texEdge2.Y * edge1.Y - texEdge1.Y * edge2.Y) * det;
                tangent.Z = (texEdge2.Y * edge1.Z - texEdge1.Y * edge2.Z) * det;
                //tangent.W = 0.0f;

                binormal   = TGCVector3.Empty;
                binormal.X = (-texEdge2.X * edge1.X + texEdge1.X * edge2.X) * det;
                binormal.Y = (-texEdge2.X * edge1.Y + texEdge1.X * edge2.Y) * det;
                binormal.Z = (-texEdge2.X * edge1.Z + texEdge1.X * edge2.Z) * det;

                tangent.Normalize();
                binormal.Normalize();
            }

            // Calculate the handedness of the local tangent space.
            // The bitangent vector is the cross product between the triangle face
            // normal vector and the calculated tangent vector. The resulting bitangent
            // vector should be the same as the bitangent vector calculated from the
            // set of linear equations above. If they point in different directions
            // then we need to invert the cross product calculated bitangent vector.
            var b = TGCVector3.Cross(v1.Normal, tangent);
            var w = TGCVector3.Dot(b, binormal) < 0.0f ? -1.0f : 1.0f;

            binormal = b * w;
        }
Esempio n. 24
0
 public Health(TGCVector3 pos) : base(pos, "Heart", Game.Default.MediaDirectory + Game.Default.FXDirectory + "healthPickup.wav")
 {
     respawnTime = 10f;
 }
Esempio n. 25
0
 public TgcMeshBumpMapping(string name, TgcMesh parentInstance, TGCVector3 translation, TGCVector3 rotation,
                           TGCVector3 scale)
     : base(name, parentInstance, translation, rotation, scale)
 {
 }
Esempio n. 26
0
 /// <summary>
 /// Constructor de la camara a partir de un TgcD3dInput y un positionEye, moveSpeed, jumpSpeed y rotationSpeed. Los atributos mouseCenter a partir del centro del a pantalla,
 ///  el directionView (0,0,-1)
 /// </summary>
 /// <param name="positionEye"></param>
 /// <param name="moveSpeed"></param>
 /// <param name="jumpSpeed"></param>
 /// <param name="rotationSpeed"></param>
 /// <param name="input"></param>
 public TgcFpsCamera(TGCVector3 positionEye, float moveSpeed, float jumpSpeed, float rotationSpeed, TgcD3dInput input)
     : this(positionEye, moveSpeed, jumpSpeed, input)
 {
     this.RotationSpeed = rotationSpeed;
 }
Esempio n. 27
0
 private void ChangePosition(TGCVector3 newPosition)
 {
     Body.CenterOfMassTransform = TGCMatrix.Translation(newPosition).ToBulletMatrix();
     Camera.Position            = new TGCVector3(Body.CenterOfMassPosition);
     RestartBodySpeed();
 }
Esempio n. 28
0
        /// <summary>
        ///     Realiza un update de la camara a partir del elapsedTime, actualizando Position,LookAt y UpVector.
        ///     Presenta movimientos basicos a partir de input de teclado W, A, S, D, Espacio, Control y rotraciones con el mouse.
        /// </summary>
        /// <param name="elapsedTime"></param>
        public override void UpdateCamera(float elapsedTime)
        {
            var moveVector = TGCVector3.Empty;

            //Forward
            if (Input.keyDown(Key.W))
            {
                moveVector += new TGCVector3(0, 0, -1) * MovementSpeed;
            }

            //Backward
            if (Input.keyDown(Key.S))
            {
                moveVector += new TGCVector3(0, 0, 1) * MovementSpeed;
            }

            //Strafe right
            if (Input.keyDown(Key.D))
            {
                moveVector += new TGCVector3(-1, 0, 0) * MovementSpeed;
            }

            //Strafe left
            if (Input.keyDown(Key.A))
            {
                moveVector += new TGCVector3(1, 0, 0) * MovementSpeed;
            }

            //Jump
            if (Input.keyDown(Key.Space))
            {
                moveVector += TGCVector3.Up * JumpSpeed;
            }

            //Crouch
            if (Input.keyDown(Key.LeftControl))
            {
                moveVector += TGCVector3.Down * JumpSpeed;
            }

            if (Input.keyPressed(Key.L) || Input.keyPressed(Key.Escape))
            {
                LockCam = !lockCam;
            }

            //Solo rotar si se esta aprentando el boton izq del mouse
            if (lockCam || Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                leftrightRot -= -Input.XposRelative * RotationSpeed;
                updownRot    -= Input.YposRelative * RotationSpeed;
                //Se actualiza matrix de rotacion, para no hacer este calculo cada vez y solo cuando en verdad es necesario.
                cameraRotation = TGCMatrix.RotationX(updownRot) * TGCMatrix.RotationY(leftrightRot);
            }

            if (lockCam)
            {
                Cursor.Position = mouseCenter;
            }

            //Calculamos la nueva posicion del ojo segun la rotacion actual de la camara.
            var cameraRotatedPositionEye = TGCVector3.TransformNormal(moveVector * elapsedTime, cameraRotation);

            positionEye += cameraRotatedPositionEye;

            //Calculamos el target de la camara, segun su direccion inicial y las rotaciones en screen space x,y.
            var cameraRotatedTarget = TGCVector3.TransformNormal(directionView, cameraRotation);
            var cameraFinalTarget   = positionEye + cameraRotatedTarget;

            //Se calcula el nuevo vector de up producido por el movimiento del update.
            var cameraOriginalUpVector = DEFAULT_UP_VECTOR;
            var cameraRotatedUpVector  = TGCVector3.TransformNormal(cameraOriginalUpVector, cameraRotation);

            base.SetCamera(positionEye, cameraFinalTarget, cameraRotatedUpVector);
        }
Esempio n. 29
0
 public TGCVector3 rotar_xz(TGCVector3 v, float an)
 {
     return(new TGCVector3((float)(v.X * Math.Cos(an) - v.Z * Math.Sin(an)), v.Y,
                           (float)(v.X * Math.Sin(an) + v.Z * Math.Cos(an))));
 }
Esempio n. 30
0
 public Arma(TGCVector3 tamanioDisparo, Color colorDisparo, int danio, int cdDisparo, TGCVector3 startPosition, float minDistance = -1f)
 {
     this.Danio       = danio;
     this.shotSize    = tamanioDisparo;
     this.shotColor   = colorDisparo;
     this.disparos    = new List <Disparo>();
     shotLimiter      = Stopwatch.StartNew();
     position         = startPosition;
     cooldownDisparo  = cdDisparo;
     this.minDistance = minDistance;
 }