public override void close()
 {
     //La malla también hace dispose del attachment
     mesh.dispose();
     mesh = null;
     selectedMesh = null;
 }
Beispiel #2
0
        public Enemigo(Vector3 posicionInicial, EscenarioManager escenarioManager)
        {
            this.huellas = new HuellasManager(10);
            this.teMataron = false;

            this.escenarioManager = escenarioManager;

            this.enemigoAmigacion = Enemigo.getAnimacion();

            this.mesh = Enemigo.getMesh();

            sangre = new TgcCylinder(posicionInicial, 0, 20, 0);
            sangre.Color = Color.Red;

            sangre.updateValues();

            enemigoEsfera = new TgcBoundingSphere(new Vector3(posicionInicial.X, 30, posicionInicial.Z), 10);

            Random rnd = new Random();
            mesh.Position = posicionInicial;

            mesh.Scale = new Vector3(1f, 1f, 1f);
            mesh.AutoTransformEnable = true;

            this.cabezaBounding = new TgcBoundingSphere(new Vector3(posicionInicial.X, posicionInicial.Y + 20, posicionInicial.Z), 20);

            this.setEstado(new EnemigoQuieto(this));
        }
 protected override void onAnimationEnds(TgcSkeletalMesh mesh)
 {
     if (attacking)
     {
         MOVEMENT_SPEED = prevMovSpeed;
         skeletalMesh.playAnimation("Caminando");
         attacking = false;
         attacked = false;
     }
 }
        public override void init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

            //Crear suelo
            TgcTexture pisoTexture = TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\Quake\\TexturePack2\\rock_floor1.jpg");
            suelo = TgcBox.fromSize(new Vector3(500, 0, 500), new Vector3(2000, 0, 2000), pisoTexture);


            //Cargar malla original
            TgcSkeletalLoader loader = new TgcSkeletalLoader();
            string pathMesh = GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\Robot-TgcSkeletalMesh.xml";
            string mediaPath = GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\";
            original = loader.loadMeshFromFile(pathMesh, mediaPath);

            //Agregar animación a original
            loader.loadAnimationFromFile(original, mediaPath + "Patear-TgcSkeletalAnim.xml");

            //Agregar attachment a original
            TgcSkeletalBoneAttach attachment = new TgcSkeletalBoneAttach();
            TgcBox attachmentBox = TgcBox.fromSize(new Vector3(3, 60, 3), Color.Green);
            attachment.Mesh = attachmentBox.toMesh("attachment");
            attachment.Bone = original.getBoneByName("Bip01 L Hand");
            attachment.Offset = Matrix.Translation(10, -40, 0);
            attachment.updateValues();
            original.Attachments.Add(attachment);


            //Crear 9 instancias mas de este modelo, pero sin volver a cargar el modelo entero cada vez
            float offset = 200;
            int cantInstancias = 4;
            instances = new List<TgcSkeletalMesh>();
            for (int i = 0; i < cantInstancias; i++)
			{
                TgcSkeletalMesh instance = original.createMeshInstance(original.Name + i);

                instance.move(i * offset, 0, 0);
                instances.Add(instance);
			}


            //Especificar la animación actual para todos los modelos
            original.playAnimation("Patear");
            foreach (TgcSkeletalMesh instance in instances)
            {
                instance.playAnimation("Patear");
            }


            //Camara en primera persona
            GuiController.Instance.FpsCamera.Enable = true;
            GuiController.Instance.FpsCamera.MovementSpeed = 400;
            GuiController.Instance.FpsCamera.JumpSpeed = 400;
            GuiController.Instance.FpsCamera.setCamera(new Vector3(293.201f, 291.0797f, -604.6647f), new Vector3(299.1028f, -63.9185f, 330.1836f));
        }
        public override void init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

            //Cargar mesh con animaciones
            TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader();
            mesh = skeletalLoader.loadMeshAndAnimationsFromFile(
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\BasicHuman\\" + "BasicHuman-TgcSkeletalMesh.xml",
                new string[] { 
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "Walk-TgcSkeletalAnim.xml",
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "StandBy-TgcSkeletalAnim.xml",
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "Jump-TgcSkeletalAnim.xml"
                });


            //Configurar animacion inicial
            mesh.playAnimation("Walk", true);


            //Camara en 1ra persona
            GuiController.Instance.FpsCamera.Enable = true;
            GuiController.Instance.FpsCamera.MovementSpeed = 400f;
            GuiController.Instance.FpsCamera.JumpSpeed = 300f;
            GuiController.Instance.FpsCamera.setCamera(new Vector3(0, 20, -150), new Vector3(0, 20, 0));


            //Mesh para la luz
            lightMesh = TgcBox.fromSize(new Vector3(10, 10, 10), Color.Red);

            //Modifiers de la luz
            GuiController.Instance.Modifiers.addBoolean("lightEnable", "lightEnable", true);
            GuiController.Instance.Modifiers.addVertex3f("lightPos", new Vector3(-200, -100, -200), new Vector3(200, 200, 300), new Vector3(0, 70, 0));
            GuiController.Instance.Modifiers.addColor("lightColor", Color.White);
            GuiController.Instance.Modifiers.addFloat("lightIntensity", 0, 150, 20);
            GuiController.Instance.Modifiers.addFloat("lightAttenuation", 0.1f, 2, 0.3f);
            GuiController.Instance.Modifiers.addFloat("specularEx", 0, 20, 9f);

            //Modifiers de material
            GuiController.Instance.Modifiers.addColor("mEmissive", Color.Black);
            GuiController.Instance.Modifiers.addColor("mAmbient", Color.White);
            GuiController.Instance.Modifiers.addColor("mDiffuse", Color.White);
            GuiController.Instance.Modifiers.addColor("mSpecular", Color.White);

            /*
            //corregir normales
            int[] adj = new int[mesh.D3dMesh.NumberFaces * 3];
            mesh.D3dMesh.GenerateAdjacency(0, adj);
            mesh.D3dMesh.ComputeNormals(adj);
            */
            mesh.computeNormals();
            
        }
Beispiel #6
0
        public Enemigo(Vector3 posicion)
        {
            //Cargar enemigo
            TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader();

            meshEnemigos.Add("BasicHuman-TgcSkeletalMesh.xml");
            meshEnemigos.Add("CombineSoldier-TgcSkeletalMesh.xml");
            meshEnemigos.Add("CS_Gign-TgcSkeletalMesh.xml");
            meshEnemigos.Add("CS_Arctic-TgcSkeletalMesh.xml");
            meshEnemigos.Add("Pilot-TgcSkeletalMesh.xml");
            meshEnemigos.Add("Quake2Scout-TgcSkeletalMesh.xml");
            meshEnemigos.Add("WomanJeans-TgcSkeletalMesh.xml");

            enemigo = skeletalLoader.loadMeshAndAnimationsFromFile(
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\BasicHuman\\" + meshEnemigos[randomEnemigo.Next(0, 6)],
                new string[] {
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "Walk-TgcSkeletalAnim.xml",
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "StandBy-TgcSkeletalAnim.xml",
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "Run-TgcSkeletalAnim.xml",
                    GuiController.Instance.AlumnoEjemplosMediaDir + "CEGA\\Animations\\" + "Death-TgcSkeletalAnim.xml",
                });

            enemigo.playAnimation("Run", true);
            enemigo.Position = posicion;
            enemigo.Scale = new Vector3(0.12f, 0.12f, 0.12f);
            this.colisionado = false;

            //Inicializo HP
            hp = 100;

            //Creo el BB para la cabeza
            cabeza = new TgcBoundingSphere(new Vector3(enemigo.Position.X, enemigo.Position.Y + 5.2F, enemigo.Position.Z), 0.5F); //Debe haber alguna forma de sacar esta info del hueso directamente
            cabeza.setRenderColor(System.Drawing.Color.Red);

            //Modifico el BB del cuerpo
            enemigo.AutoUpdateBoundingBox = false;
            enemigo.BoundingBox.scaleTranslate(enemigo.Position, new Vector3(0.07f, 0.095f, 0.07f));

            //Inicializo el emisor
            emisorDeParticulas = new ParticleEmitter(GuiController.Instance.AlumnoEjemplosMediaDir + "CEGA\\Textures\\blood.jpg", 500);
            emisorDeParticulas.Playing = false;
        }
        public SkeletalRepresentation(Vector3 position)
        {

            TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader();
            this.mesh = skeletalLoader.loadMeshAndAnimationsFromFile(
                getMesh(),
                getAnimations());

            sounds = CommandoSound.commando();

            this.mesh.playAnimation("StandBy", true);
            this.moving = false;

            this.Position = position;

            //rotacion manual
            this.AutoTransformEnable = false;
            this.angleZeroVector = new Vector3(0, 0, -1);
            this.setRotation(this.angleZeroVector);
        }
        /// <summary>
        /// Ajustar la posicion de la camara segun la colision con los objetos del escenario.
        /// Acerca la distancia entre el persona y la camara si hay colisiones de objetos
        /// en el medio
        /// </summary>
        private void ajustarPosicionDeCamara(TgcSkeletalMesh personaje, List<TgcBox> obstaculos)
        {
            //Actualizar valores de camara segun modifiers
            TgcThirdPersonCamera camera = GuiController.Instance.ThirdPersonCamera;
            camera.OffsetHeight = (float)GuiController.Instance.Modifiers["offsetHeight"];
            camera.OffsetForward = (float)GuiController.Instance.Modifiers["offsetForward"];
            Vector2 displacement = (Vector2)GuiController.Instance.Modifiers["displacement"];
            camera.TargetDisplacement = new Vector3(displacement.X, displacement.Y, 0);

            //Pedirle a la camara cual va a ser su proxima posicion
            Vector3 segmentA;
            Vector3 segmentB;
            camera.generateViewMatrix(out segmentA, out segmentB);

            //Detectar colisiones entre el segmento de recta camara-personaje y todos los objetos del escenario
            Vector3 q;
            float minDistSq = FastMath.Pow2(camera.OffsetForward);
            foreach (TgcBox obstaculo in obstaculos)
            {
                //Hay colision del segmento camara-personaje y el objeto
                if (TgcCollisionUtils.intersectSegmentAABB(segmentB, segmentA, obstaculo.BoundingBox, out q))
                {
                    //Si hay colision, guardar la que tenga menor distancia
                    float distSq = (Vector3.Subtract(q, segmentB)).LengthSq();
                    if (distSq < minDistSq)
                    {
                        minDistSq = distSq;

                        //Le restamos un poco para que no se acerque tanto
                        minDistSq /= 2;
                    }
                }
            }

            //Acercar la camara hasta la minima distancia de colision encontrada (pero ponemos un umbral maximo de cercania)
            float newOffsetForward = -FastMath.Sqrt(minDistSq);
            /*
            if(newOffsetForward < 10)
            {
                newOffsetForward = 10;
            }*/
            camera.OffsetForward = newOffsetForward;

        }
        /// <summary>
        /// Libera los recursos de la malla
        /// </summary>
        public void dispose()
        {
            this.enabled = false;
            if (boundingBox != null)
            {
                boundingBox.dispose();
            }

            //Si es una instancia no liberar nada, lo hace el original.
            if (parentInstance != null)
            {
                parentInstance = null;
                return;
            }

            //hacer dispose de instancias
            foreach (TgcSkeletalMesh meshInstance in meshInstances)
            {
                meshInstance.dispose();
            }
            meshInstances = null;

            //Dispose de mesh
            this.d3dMesh.Dispose();
            this.d3dMesh = null;

            //Dispose de texturas
            if (diffuseMaps != null)
            {
                for (int i = 0; i < diffuseMaps.Length; i++)
                {
                    diffuseMaps[i].dispose();
                }
                diffuseMaps = null;
            }

            //Dispose de Box de joints
            if (skeletonRenderJoints != null)
            {
                foreach (TgcBox jointBox in skeletonRenderJoints)
                {
                    jointBox.dispose();
                }
                skeletonRenderJoints = null;
            }

            //Dispose de lineas de Bones
            if (skeletonRenderBones != null)
            {
                foreach (TgcLine boneLine in skeletonRenderBones)
                {
                    if (boneLine != null)
                    {
                        boneLine.dispose();
                    }
                }
                skeletonRenderBones = null;
            }

            //Liberar attachments
            foreach (TgcSkeletalBoneAttach attach in attachments)
            {
                attach.Mesh.dispose();
            }
            attachments = null;

            //VertexDeclaration
            vertexDeclaration.Dispose();
            vertexDeclaration = null;
        }
Beispiel #10
0
        /// <summary>
        /// Crea un mesh con uno o varios DiffuseMap
        /// </summary>
        /// <returns></returns>
        private TgcSkeletalMesh crearMeshDiffuseMap(TgcSkeletalLoaderMaterialAux[] materialsArray, TgcSkeletalMeshData meshData)
        {
            //Crear Mesh
            Mesh mesh = new Mesh(meshData.coordinatesIndices.Length / 3, meshData.coordinatesIndices.Length, MeshFlags.Managed, DiffuseMapVertexElements, device);

            //Cargar VertexBuffer
            using (VertexBuffer vb = mesh.VertexBuffer)
            {
                GraphicsStream data = vb.Lock(0, 0, LockFlags.None);
                for (int j = 0; j < meshData.coordinatesIndices.Length; j++)
                {
                    DiffuseMapVertex v = new DiffuseMapVertex();

                    //vertices
                    int coordIdx = meshData.coordinatesIndices[j] * 3;
                    v.Position = new Vector3(
                        meshData.verticesCoordinates[coordIdx],
                        meshData.verticesCoordinates[coordIdx + 1],
                        meshData.verticesCoordinates[coordIdx + 2]
                        );

                    //texture coordinates diffuseMap
                    int texCoordIdx = meshData.texCoordinatesIndices[j] * 2;
                    v.Tu = meshData.textureCoordinates[texCoordIdx];
                    v.Tv = meshData.textureCoordinates[texCoordIdx + 1];

                    //color
                    int colorIdx = meshData.colorIndices[j];
                    v.Color = meshData.verticesColors[colorIdx];

                    data.Write(v);
                }
                vb.Unlock();
            }

            //Cargar IndexBuffer en forma plana
            using (IndexBuffer ib = mesh.IndexBuffer)
            {
                short[] indices = new short[meshData.coordinatesIndices.Length];
                for (int j = 0; j < indices.Length; j++)
                {
                    indices[j] = (short)j;
                }
                ib.SetData(indices, 0, LockFlags.None);
            }

            //Configurar Material y Textura para un solo SubSet
            TgcSkeletalLoaderMaterialAux matAux = materialsArray[meshData.materialId];

            Material[]   meshMaterials;
            TgcTexture[] meshTextures;
            if (matAux.subMaterials == null)
            {
                meshMaterials = new Material[] { matAux.materialId };
                meshTextures  = new TgcTexture[] { matAux.texture };
            }

            //Configurar Material y Textura para varios SubSet
            else
            {
                //Cargar attributeBuffer con los id de las texturas de cada triángulo
                int[] attributeBuffer = mesh.LockAttributeBufferArray(LockFlags.None);
                Array.Copy(meshData.materialsIds, attributeBuffer, attributeBuffer.Length);
                mesh.UnlockAttributeBuffer(attributeBuffer);

                //Cargar array de Materials y Texturas
                meshMaterials = new Material[matAux.subMaterials.Length];
                meshTextures  = new TgcTexture[matAux.subMaterials.Length];
                for (int m = 0; m < matAux.subMaterials.Length; m++)
                {
                    meshMaterials[m] = matAux.subMaterials[m].materialId;
                    meshTextures[m]  = matAux.subMaterials[m].texture;
                }
            }

            //Cargar esqueleto
            TgcSkeletalBone[]         bones           = loadSkeleton(meshData);
            TgcSkeletalVertexWeight[] verticesWeights = loadVerticesWeights(meshData, bones);

            //Cargar datos de meshData que interesan mantener como originales
            TgcSkeletalMesh.OriginalData origData = new TgcSkeletalMesh.OriginalData();
            origData.coordinatesIndices    = meshData.coordinatesIndices;
            origData.verticesCoordinates   = meshData.verticesCoordinates;
            origData.colorIndices          = meshData.colorIndices;
            origData.verticesColors        = meshData.verticesColors;
            origData.texCoordinatesIndices = meshData.texCoordinatesIndices;
            origData.textureCoordinates    = meshData.textureCoordinates;

            //Crear mesh de TGC
            TgcSkeletalMesh tgcMesh = meshFactory.createNewMesh(mesh, meshData.name, TgcSkeletalMesh.MeshRenderType.DIFFUSE_MAP, origData, bones, verticesWeights);

            tgcMesh.Materials   = meshMaterials;
            tgcMesh.DiffuseMaps = meshTextures;
            return(tgcMesh);
        }
        /// <summary>
        /// Libera los recursos de la malla
        /// </summary>
        public void dispose()
        {
            this.enabled = false;
            if (boundingBox != null)
            {
                boundingBox.dispose();
            }

            //Si es una instancia no liberar nada, lo hace el original.
            if (parentInstance != null)
            {
                parentInstance = null;
                return;
            }

            //hacer dispose de instancias
            foreach (TgcSkeletalMesh meshInstance in meshInstances)
            {
                meshInstance.dispose();
            }
            meshInstances = null;

            //Dispose de mesh
            this.d3dMesh.Dispose();
            this.d3dMesh = null;

            //Dispose de texturas
            if (diffuseMaps != null)
            {
                for (int i = 0; i < diffuseMaps.Length; i++)
                {
                    diffuseMaps[i].dispose();
                }
                diffuseMaps = null;
            }


            //Dispose de Box de joints
            if (skeletonRenderJoints != null)
            {
                foreach (TgcBox jointBox in skeletonRenderJoints)
                {
                    jointBox.dispose();
                }
                skeletonRenderJoints = null;
            }

            //Dispose de lineas de Bones
            if (skeletonRenderBones != null)
            {
                foreach (TgcLine boneLine in skeletonRenderBones)
                {
                    if (boneLine != null)
                    {
                        boneLine.dispose();
                    }
                }
                skeletonRenderBones = null;
            }

            //Liberar attachments
            foreach (TgcSkeletalBoneAttach attach in attachments)
            {
                attach.Mesh.dispose();
            }
            attachments = null;

            //VertexDeclaration
            vertexDeclaration.Dispose();
            vertexDeclaration = null;
        }
 public TgcSkeletalMesh createNewMesh(Mesh d3dMesh, string meshName, TgcSkeletalMesh.MeshRenderType renderType, TgcSkeletalBone[] bones)
 {
     return new TgcSkeletalMesh(d3dMesh, meshName, renderType, bones);
 }
        public override void init()
        {
            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;

            //Cargar escenario específico para este ejemplo
            TgcSceneLoader loader = new TgcSceneLoader();
            escenario = loader.loadSceneFromFile(GuiController.Instance.ExamplesDir + "\\Collision\\SphereCollision\\PatioDeJuegos\\PatioDeJuegos-TgcScene.xml");

            //Cargar personaje con animaciones
            TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader();
            personaje = skeletalLoader.loadMeshAndAnimationsFromFile(
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Robot-TgcSkeletalMesh.xml",
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\",
                new string[] {
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Caminando-TgcSkeletalAnim.xml",
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Parado-TgcSkeletalAnim.xml",
                });

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

            //Configurar animacion inicial
            personaje.playAnimation("Parado", true);
            //Escalarlo porque es muy grande
            personaje.Position = new Vector3(0,500,-100);
            //Rotarlo 180° porque esta mirando para el otro lado
            personaje.rotateY(Geometry.DegreeToRadian(180f));

            //BoundingSphere que va a usar el personaje
            personaje.AutoUpdateBoundingBox = false;
            characterSphere = new TgcBoundingSphere(personaje.BoundingBox.calculateBoxCenter(), personaje.BoundingBox.calculateBoxRadius());

            //Almacenar volumenes de colision del escenario
            objetosColisionables.Clear();
            foreach (TgcMesh mesh in escenario.Meshes)
            {
                objetosColisionables.Add(mesh.BoundingBox);
            }

            //Crear linea para mostrar la direccion del movimiento del personaje
            directionArrow = new TgcArrow();
            directionArrow.BodyColor = Color.Red;
            directionArrow.HeadColor = Color.Green;
            directionArrow.Thickness = 1;
            directionArrow.HeadSize = new Vector2(10, 20);

            //Crear manejador de colisiones
            collisionManager = new SphereCollisionManager();
            collisionManager.GravityEnabled = true;

            //Configurar camara en Tercer Persona
            GuiController.Instance.ThirdPersonCamera.Enable = true;
            GuiController.Instance.ThirdPersonCamera.setCamera(personaje.Position, 100, -400);
            GuiController.Instance.ThirdPersonCamera.TargetDisplacement = new Vector3(0, 100, 0);

            //Crear SkyBox
            skyBox = new TgcSkyBox();
            skyBox.Center = new Vector3(0, 0, 0);
            skyBox.Size = new Vector3(10000, 10000, 10000);
            string texturesPath = GuiController.Instance.ExamplesMediaDir + "Texturas\\Quake\\SkyBox3\\";
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Up, texturesPath + "Up.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Down, texturesPath + "Down.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Left, texturesPath + "Left.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Right, texturesPath + "Right.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Front, texturesPath + "Back.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Back, texturesPath + "Front.jpg");
            skyBox.updateValues();

            //Modifier para ver BoundingBox
            GuiController.Instance.Modifiers.addBoolean("showBoundingBox", "Bouding Box", true);

            //Modifiers para desplazamiento del personaje
            GuiController.Instance.Modifiers.addFloat("VelocidadCaminar", 0, 100, 16);
            GuiController.Instance.Modifiers.addFloat("VelocidadRotacion", 1f, 360f, 150f);
            GuiController.Instance.Modifiers.addBoolean("HabilitarGravedad", "Habilitar Gravedad", true);
            GuiController.Instance.Modifiers.addVertex3f("Gravedad", new Vector3(-50, -50, -50), new Vector3(50, 50, 50), new Vector3(0, -10, 0));
            GuiController.Instance.Modifiers.addFloat("SlideFactor", 1f, 2f, 1.3f);

            GuiController.Instance.UserVars.addVar("Movement");
        }
        public override void init()
        {
            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;

            //Crear piso
            TgcTexture pisoTexture = TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\tierra.jpg");
            piso = TgcBox.fromExtremes(new Vector3(-1000, -2, -1000), new Vector3(1000, 0, 1000), pisoTexture);


            //Cargar obstaculos y posicionarlos. Los obstáculos se crean con TgcBox en lugar de cargar un modelo.
            obstaculos = new List<TgcBox>();
            TgcBox obstaculo;


            float wallSize = 1000;
            float wallHeight = 500;

            //Obstaculo 1
            obstaculo = TgcBox.fromExtremes(
                new Vector3(0,0,0),
                new Vector3(wallSize, wallHeight, 10),
                TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\baldosaFacultad.jpg"));
            obstaculos.Add(obstaculo);

            //Obstaculo 2
            obstaculo = TgcBox.fromExtremes(
                new Vector3(0, 0, 0),
                new Vector3(10, wallHeight, wallSize),
                TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\madera.jpg"));
            obstaculos.Add(obstaculo);

            //Obstaculo 3
            obstaculo = TgcBox.fromExtremes(
                new Vector3(0, 0, wallSize),
                new Vector3(wallSize, wallHeight, wallSize + 10),
                TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\granito.jpg"));
            obstaculos.Add(obstaculo);

            //Obstaculo 4
            obstaculo = TgcBox.fromExtremes(
                new Vector3(wallSize, 0, 0),
                new Vector3(wallSize + 10, wallHeight, wallSize),
                TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\granito.jpg"));
            obstaculos.Add(obstaculo);

            //Obstaculo 5
            obstaculo = TgcBox.fromExtremes(
                new Vector3(wallSize / 2, 0, wallSize - 400),
                new Vector3(wallSize + 10, wallHeight, wallSize - 400 + 10),
                TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\granito.jpg"));
            obstaculos.Add(obstaculo);

            //Cargar personaje con animaciones
            TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader();
            personaje = skeletalLoader.loadMeshAndAnimationsFromFile(
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Robot-TgcSkeletalMesh.xml",
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\",
                new string[] { 
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Caminando-TgcSkeletalAnim.xml",
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Parado-TgcSkeletalAnim.xml",
                });


            //Configurar animacion inicial
            personaje.playAnimation("Parado", true);
            //Escalarlo porque es muy grande
            personaje.Position = new Vector3(100, 0, 100);
            personaje.Scale = new Vector3(0.75f, 0.75f, 0.75f);
            //Rotarlo 180° porque esta mirando para el otro lado
            personaje.rotateY(Geometry.DegreeToRadian(180f));
            

            //Configurar camara en Tercera Persona
            GuiController.Instance.ThirdPersonCamera.Enable = true;
            GuiController.Instance.ThirdPersonCamera.setCamera(personaje.Position, 200, -300);


            //Modifiers para modificar propiedades de la camara
            GuiController.Instance.Modifiers.addFloat("offsetHeight", 0, 300, 100);
            GuiController.Instance.Modifiers.addFloat("offsetForward", -400, 0, -220);
            GuiController.Instance.Modifiers.addVertex2f("displacement", new Vector2(0, 0), new Vector2(100, 200), new Vector2(0, 100));
        }
 /// <summary>
 /// Carga una animación a un modelo ya cargado, a partir del string del XML.
 /// La animación se agrega al modelo.
 /// </summary>
 /// <param name="mesh">Modelo ya cargado</param>
 /// <param name="xmlString">contenido del XML</param>
 public void loadAnimationFromString(TgcSkeletalMesh mesh, string xmlString)
 {
     TgcSkeletalParser parser = new TgcSkeletalParser();
     TgcSkeletalAnimationData animationData = parser.parseAnimationFromString(xmlString);
     TgcSkeletalAnimation animation = loadAnimation(mesh, animationData);
     mesh.Animations.Add(animation.Name, animation);
 }
Beispiel #16
0
        /// <summary>
        /// Obtener technique default para un TgcSkeletalMesh según su MeshRenderType
        /// </summary>
        /// <param name="renderType">MeshRenderType</param>
        /// <returns>Nombre del Technique que le corresponde</returns>
        public string getTgcSkeletalMeshTechnique(TgcSkeletalMesh.MeshRenderType renderType)
        {
            switch (renderType)
            {
                case TgcSkeletalMesh.MeshRenderType.VERTEX_COLOR:
                    return "VERTEX_COLOR";
                case TgcSkeletalMesh.MeshRenderType.DIFFUSE_MAP:
                    return "DIFFUSE_MAP";
            }

            throw new Exception("RenderType incorrecto");
        }
        public override void init()
        {
            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;

            //Cargar escenario específico para este ejemplo. Este escenario tiene dos layers: objetos normales y objetos con colisión a nivel de triángulo.
            //La colisión a nivel de triángulos es costosa. Solo debe utilizarse para objetos puntuales (como el piso). Y es recomendable dividirlo en varios
            //meshes (y no hacer un único piso que ocupe todo el escenario)
            TgcSceneLoader loader = new TgcSceneLoader();
            escenario = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir + "\\MeshCreator\\Scenes\\Mountains\\Mountains-TgcScene.xml");

            //Cargar personaje con animaciones
            TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader();
            personaje = skeletalLoader.loadMeshAndAnimationsFromFile(
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\BasicHuman\\" + "BasicHuman-TgcSkeletalMesh.xml",
                new string[] {
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "Walk-TgcSkeletalAnim.xml",
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "StandBy-TgcSkeletalAnim.xml",
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + "Jump-TgcSkeletalAnim.xml"
                });

            //Configurar animacion inicial
            personaje.playAnimation("StandBy", true);
            //Escalarlo porque es muy grande
            personaje.Position = new Vector3(0,1000,-150);
            //Rotarlo 180° porque esta mirando para el otro lado
            personaje.rotateY(Geometry.DegreeToRadian(180f));

            //BoundingSphere que va a usar el personaje
            personaje.AutoUpdateBoundingBox = false;
            characterElipsoid = new TgcElipsoid(personaje.BoundingBox.calculateBoxCenter() + new Vector3(0, 0, 0), new Vector3(12, 28, 12));
            jumping = false;

            //Almacenar volumenes de colision del escenario
            objetosColisionables.Clear();
            foreach (TgcMesh mesh in escenario.Meshes)
            {
                //Los objetos del layer "TriangleCollision" son colisiones a nivel de triangulo
                if (mesh.Layer == "TriangleCollision")
                {
                    objetosColisionables.Add(TriangleMeshCollider.fromMesh(mesh));
                }
                //El resto de los objetos son colisiones de BoundingBox. Las colisiones a nivel de triangulo son muy costosas asi que deben utilizarse solo
                //donde es extremadamente necesario (por ejemplo en el piso). El resto se simplifica con un BoundingBox
                else
                {
                    objetosColisionables.Add(BoundingBoxCollider.fromBoundingBox(mesh.BoundingBox));
                }
            }

            //Crear manejador de colisiones
            collisionManager = new ElipsoidCollisionManager();
            collisionManager.GravityEnabled = true;

            //Crear linea para mostrar la direccion del movimiento del personaje
            directionArrow = new TgcArrow();
            directionArrow.BodyColor = Color.Red;
            directionArrow.HeadColor = Color.Green;
            directionArrow.Thickness = 0.4f;
            directionArrow.HeadSize = new Vector2(5, 10);

            //Linea para normal de colision
            collisionNormalArrow = new TgcArrow();
            collisionNormalArrow.BodyColor = Color.Blue;
            collisionNormalArrow.HeadColor = Color.Yellow;
            collisionNormalArrow.Thickness = 0.4f;
            collisionNormalArrow.HeadSize = new Vector2(2, 5);

            //Caja para marcar punto de colision
            collisionPoint = TgcBox.fromSize(new Vector3(4, 4, 4), Color.Red);

            //Configurar camara en Tercer Persona
            GuiController.Instance.ThirdPersonCamera.Enable = true;
            GuiController.Instance.ThirdPersonCamera.setCamera(personaje.Position, 20, -120);
            GuiController.Instance.ThirdPersonCamera.TargetDisplacement = new Vector3(0, 45, 0);

            //Crear SkyBox
            skyBox = new TgcSkyBox();
            skyBox.Center = new Vector3(0, 0, 0);
            skyBox.Size = new Vector3(10000, 10000, 10000);
            string texturesPath = GuiController.Instance.ExamplesMediaDir + "Texturas\\Quake\\SkyBox3\\";
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Up, texturesPath + "Up.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Down, texturesPath + "Down.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Left, texturesPath + "Left.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Right, texturesPath + "Right.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Front, texturesPath + "Back.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Back, texturesPath + "Front.jpg");
            skyBox.updateValues();

            //Modifier para ver BoundingBox
            GuiController.Instance.Modifiers.addBoolean("Collisions", "Collisions", true);
            GuiController.Instance.Modifiers.addBoolean("showBoundingBox", "Bouding Box", true);

            //Modifiers para desplazamiento del personaje
            GuiController.Instance.Modifiers.addFloat("VelocidadCaminar", 0, 20, 2);
            GuiController.Instance.Modifiers.addFloat("VelocidadRotacion", 1f, 360f, 150f);
            GuiController.Instance.Modifiers.addBoolean("HabilitarGravedad", "Habilitar Gravedad", true);
            GuiController.Instance.Modifiers.addVertex3f("Gravedad", new Vector3(-50, -50, -50), new Vector3(50, 50, 50), new Vector3(0, -4, 0));
            GuiController.Instance.Modifiers.addFloat("SlideFactor", 0f, 2f, 1f);
            GuiController.Instance.Modifiers.addFloat("Pendiente", 0f, 1f, 0.72f);
            GuiController.Instance.Modifiers.addFloat("VelocidadSalto", 0f, 50f, 10f);
            GuiController.Instance.Modifiers.addFloat("TiempoSalto", 0f, 2f, 0.5f);

            GuiController.Instance.UserVars.addVar("Movement");
        }
Beispiel #18
0
 public void rotarMesh(TgcSkeletalMesh mesh1)
 {
     Vector3 haciaDondeDebeMirar;
     haciaDondeDebeMirar = mesh1.Position - camaraQ3.getPosition();
     haciaDondeDebeMirar.Y = 0;
     haciaDondeDebeMirar.Normalize();
     mesh1.rotateY((float)FastMath.Atan2(haciaDondeDebeMirar.X, haciaDondeDebeMirar.Z) - mesh1.Rotation.Y);
 }
Beispiel #19
0
        public void inicializarEnemigos(int columnas, int filas, List<Enemigo> lista, float scale, float radio)
        {
            //Cargar malla original
            loader = new TgcSkeletalLoader();
            string pathMesh = GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\BasicHuman\\CS_Arctic-TgcSkeletalMesh.xml";
            mediaPath = GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\BasicHuman\\";
            originalEnemigo = loader.loadMeshFromFile(pathMesh, mediaPath);
            originalEnemigo.Scale = new Vector3(3.4f, 3.4f, 3.4f);

            //Agregar animación a original
            loader.loadAnimationFromFile(originalEnemigo, mediaPath + "\\Animations\\Walk-TgcSkeletalAnim.xml");

            //Cargar Shader personalizado
            //meshOriginal.Effect = enemigoEffect;
            //meshOriginal.Technique = "RenderScene";
            float x = 0f;
            float z = 0f;
            //instanciasMalos = new List<TgcSkeletalMesh>();
            //int rowsRobot = 3;
            //int colsRobot = 3;
            for (int k = 0; k < filas; k++)
            {
                for (int q = 0; q < columnas; q++)
                {
                    //Crear instancia de modelo
                    TgcSkeletalMesh instance = originalEnemigo.createMeshInstance(originalEnemigo.Name + k + "_" + q);
                    do
                    {
                        x = rand.Next(-5000, 5000);
                        z = rand.Next(-5000, 5000);
                    } while (FastMath.Sqrt(x * x + z * z) <= radio);
                    //Achico el bounding box del arbol
                    //instance.BoundingBox.scaleTranslate(new Vector3(0f, 0f, 0f), new Vector3(0.5f, 0.5f, 0.5f));

                    //instance.rotateY(FastMath.Atan(3f));
                    //Desplazarlo
                    instance.move(x, 0, z);

                    //Roto el mesh
                    rotarMesh(instance);

                    Effect fx = TgcShaders.loadEffect(GuiController.Instance.AlumnoEjemplosMediaDir + "Shaders\\e.fx");

                    instance.Scale = new Vector3(scale, scale, scale);
                    instance.AlphaBlendEnable = true;
                    Enemigo e = new Enemigo(instance, instance.Position);
                    e.efecto = fx;
                    lista.Add(e);
                }
            }

            //originalEnemigo.playAnimation("Walk");
            foreach (Enemigo enemigo in lista)
            {
                enemigo.meshEnemigo.playAnimation("Walk");
            }
        }
Beispiel #20
0
 public TgcSkeletalMesh createNewMesh(Mesh d3dMesh, string meshName, TgcSkeletalMesh.MeshRenderType renderType, TgcSkeletalMesh.OriginalData origData, TgcSkeletalBone[] bones, TgcSkeletalVertexWeight[] verticesWeights)
 {
     return new TgcSkeletalMesh(d3dMesh, meshName, renderType, origData, bones, verticesWeights);
 }
        public override void Init()
        {
            //seteamos atributos particulares del robot
            health = 100;
            score = 1;
            Device d3dDevice = GuiController.Instance.D3dDevice;
            MESH_SCALE = 0.5f;
            tiempoMuerte = 5f;
            attackDamage = 25;
            //cargamos el mesh
            //Despues de agregar el skeletalMesh dejamos de renderizar este mesh, pero igual lo utilizamos para calcular muchas cosas
            this.mesh = GameManager.Instance.ModeloRobot.clone("robot");

            giroInicial = Matrix.RotationY(-(float)Math.PI / 2);

            //carga de animaciones
            TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader();

            skeletalMesh = skeletalLoader.loadMeshAndAnimationsFromFile(
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Robot-TgcSkeletalMesh.xml",
                new string[] {
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Caminando-TgcSkeletalAnim.xml",
                   GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Patear-TgcSkeletalAnim.xml",
                   GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Arrojar-TgcSkeletalAnim.xml",
                });

            skeletalMesh.playAnimation("Caminando", true);
            skeletalMesh.AnimationEnds += this.onAnimationEnds;

            skeletalMesh.Effect = GameManager.Instance.skeletalEnvMap;
            //skeletalMesh.Technique = "SkeletalEnvMap";

            skeletalMesh.Effect.SetValue("lightColor", ColorValue.FromColor(Color.White));
            skeletalMesh.Effect.SetValue("lightPosition", TgcParserUtils.vector3ToFloat4Array(new Vector3(0,1400,0)));
            skeletalMesh.Effect.SetValue("eyePosition", TgcParserUtils.vector3ToFloat4Array(CustomFpsCamera.Instance.getPosition()));
            skeletalMesh.Effect.SetValue("lightIntensity", 0.3f);
            skeletalMesh.Effect.SetValue("lightAttenuation", 0.3f);
            skeletalMesh.Effect.SetValue("reflection", 0.65f);

            //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
            skeletalMesh.Effect.SetValue("materialEmissiveColor", ColorValue.FromColor(Color.Black));
            skeletalMesh.Effect.SetValue("materialAmbientColor", ColorValue.FromColor(Color.White));
            skeletalMesh.Effect.SetValue("materialDiffuseColor", ColorValue.FromColor(Color.White));
            skeletalMesh.Effect.SetValue("materialSpecularColor", ColorValue.FromColor(Color.White));
            skeletalMesh.Effect.SetValue("materialSpecularExp", 7);

            skeletalMesh.Effect.SetValue("texCubeMap", GameManager.Instance.cubeMap);

            skeletalMesh.setColor(Color.Peru);

            //realizamos el init() comun a todos los enemigos
            base.Init();
            //Creamos boundingBox nuevas para la cabeza, pecho y piernas del robot
            HEADSHOT_BOUNDINGBOX = this.mesh.BoundingBox.clone();
            CHEST_BOUNDINGBOX = this.mesh.BoundingBox.clone();
            LEGS_BOUNDINGBOX = this.mesh.BoundingBox.clone();
            Matrix escalabox = Matrix.Scaling(new Vector3(0.43f, 0.3f, 0.43f));
            Matrix traslationbox = Matrix.Translation(new Vector3(0, 90f, 0));
            HEADSHOT_BOUNDINGBOX.transform(escalabox * traslationbox);
            posicionActualHeadshot = escalabox * traslationbox * posicionActual;
            Matrix escalabox2 = Matrix.Scaling(new Vector3(0.6f, 0.3f, 0.6f));
            Matrix traslationbox2 = Matrix.Translation(new Vector3(0, 50f, 0));
            CHEST_BOUNDINGBOX.transform(escalabox2 * traslationbox2);
            posicionActualChest = escalabox2 * traslationbox2 * posicionActual;
            Matrix escalabox3 = Matrix.Scaling(new Vector3(0.4f, 0.38f, 0.4f));
            Matrix traslationbox3 = Matrix.Translation(new Vector3(0, 0f, 0));
            LEGS_BOUNDINGBOX.transform(escalabox3 * traslationbox3);
            posicionActualLegs = escalabox3 * traslationbox3 * posicionActual;

            skeletalMesh.AutoTransformEnable = false;

            //carga de sonido
            SonidoMovimiento = new Tgc3dSound(GuiController.Instance.AlumnoEjemplosMediaDir + "Los_Borbotones\\Audio\\Robot\\servomotor.wav", getPosicionActual());
            SonidoMovimiento.MinDistance = 70f;
            SonidoMovimiento.play(true);

            //setBaseEffect();
            skeletalMesh.computeNormals();
        }
 protected virtual void onAnimationEnds(TgcSkeletalMesh mesh)
 {
     if (attacking)
     {
         MOVEMENT_SPEED = MOVEMENT_SPEED / 3;
         skeletalMesh.playAnimation("Caminando");
         attacking = false;
         attacked = false;
     }
 }
 /// <summary>
 /// Carga una animación a un modelo ya cargado, en base a un archivo
 /// La animación se agrega al modelo.
 /// </summary>
 /// <param name="mesh">Modelo ya cargado</param>
 /// <param name="filePath">Ubicacion del archivo XML de la animación</param>
 public void loadAnimationFromFile(TgcSkeletalMesh mesh, string filePath)
 {
     try
     {
         string xmlString = File.ReadAllText(filePath);
         loadAnimationFromString(mesh, xmlString);
     }
     catch (Exception ex)
     {
         throw new Exception("Error al cargar animacion desde archivo: " + filePath, ex);
     }
 }
Beispiel #24
0
        /// <summary>
        /// Crea un mesh sin texturas, solo con VertexColors
        /// </summary>
        /// <param name="meshData"></param>
        private TgcSkeletalMesh crearMeshSoloColor(TgcSkeletalMeshData meshData)
        {
            //Crear Mesh
            Mesh mesh = new Mesh(meshData.coordinatesIndices.Length / 3, meshData.coordinatesIndices.Length, MeshFlags.Managed, VertexColorVertexElements, device);

            //Cargar esqueleto
            TgcSkeletalBone[]         bones           = loadSkeleton(meshData);
            TgcSkeletalVertexWeight[] verticesWeights = loadVerticesWeights(meshData, bones);

            //Cargar VertexBuffer
            using (VertexBuffer vb = mesh.VertexBuffer)
            {
                GraphicsStream data = vb.Lock(0, 0, LockFlags.None);
                for (int j = 0; j < meshData.coordinatesIndices.Length; j++)
                {
                    VertexColorVertex v = new VertexColorVertex();

                    //vertices
                    int coordIdx = meshData.coordinatesIndices[j] * 3;
                    v.Position = new Vector3(
                        meshData.verticesCoordinates[coordIdx],
                        meshData.verticesCoordinates[coordIdx + 1],
                        meshData.verticesCoordinates[coordIdx + 2]
                        );

                    //color
                    int colorIdx = meshData.colorIndices[j];
                    v.Color = meshData.verticesColors[colorIdx];

                    //normal
                    if (meshData.verticesNormals != null)
                    {
                        v.Normal = new Vector3(
                            meshData.verticesNormals[coordIdx],
                            meshData.verticesNormals[coordIdx + 1],
                            meshData.verticesNormals[coordIdx + 2]
                            );
                    }
                    else
                    {
                        v.Normal = new Vector3(0, 0, 0);
                    }

                    //tangent
                    if (meshData.verticesTangents != null)
                    {
                        v.Tangent = new Vector3(
                            meshData.verticesTangents[coordIdx],
                            meshData.verticesTangents[coordIdx + 1],
                            meshData.verticesTangents[coordIdx + 2]
                            );
                    }
                    else
                    {
                        v.Tangent = new Vector3(0, 0, 0);
                    }

                    //binormal
                    if (meshData.verticesBinormals != null)
                    {
                        v.Binormal = new Vector3(
                            meshData.verticesBinormals[coordIdx],
                            meshData.verticesBinormals[coordIdx + 1],
                            meshData.verticesBinormals[coordIdx + 2]
                            );
                    }
                    else
                    {
                        v.Binormal = new Vector3(0, 0, 0);
                    }



                    //BlendWeights y BlendIndices
                    TgcSkeletalVertexWeight vWeight = verticesWeights[meshData.coordinatesIndices[j]];
                    vWeight.createVector4WeightsAndIndices(out v.BlendWeights, out v.BlendIndices);


                    data.Write(v);
                }
                vb.Unlock();
            }

            //Cargar indexBuffer en forma plana
            using (IndexBuffer ib = mesh.IndexBuffer)
            {
                short[] indices = new short[meshData.coordinatesIndices.Length];
                for (int i = 0; i < indices.Length; i++)
                {
                    indices[i] = (short)i;
                }
                ib.SetData(indices, 0, LockFlags.None);
            }

            //Crear mesh de TGC
            TgcSkeletalMesh tgcMesh = meshFactory.createNewMesh(mesh, meshData.name, TgcSkeletalMesh.MeshRenderType.VERTEX_COLOR, bones);

            return(tgcMesh);
        }
        /// <summary>
        /// Cargar estructura de animacion
        /// </summary>
        private TgcSkeletalAnimation loadAnimation(TgcSkeletalMesh mesh, TgcSkeletalAnimationData animationData)
        {
            //Crear array para todos los huesos, tengan o no keyFrames
            List<TgcSkeletalAnimationFrame>[] boneFrames = new List<TgcSkeletalAnimationFrame>[mesh.Bones.Length];
  
            //Cargar los frames para los huesos que si tienen
            for (int i = 0; i < animationData.bonesFrames.Length; i++)
			{
			    TgcSkeletalAnimationBoneData boneData = animationData.bonesFrames[i];
                
                //Crear frames
                for (int j = 0; j < boneData.keyFrames.Length; j++)
			    {
    			    TgcSkeletalAnimationBoneFrameData frameData = boneData.keyFrames[j];

                    TgcSkeletalAnimationFrame frame = new TgcSkeletalAnimationFrame(
                        frameData.frame,
                        new Vector3(frameData.position[0], frameData.position[1], frameData.position[2]),
                        new Quaternion(frameData.rotation[0], frameData.rotation[1], frameData.rotation[2], frameData.rotation[3])
                        );

                    //Agregar a lista de frames del hueso
                    if (boneFrames[boneData.id] == null)
                    {
                        boneFrames[boneData.id] = new List<TgcSkeletalAnimationFrame>();
                    }
                    boneFrames[boneData.id].Add(frame);
			    }
			}

            //BoundingBox de la animación, aprovechar lo que viene en el XML o utilizar el de la malla estática
            TgcBoundingBox boundingBox = null;
            if (animationData.pMin != null && animationData.pMax != null)
            {
                boundingBox = new TgcBoundingBox(
                    TgcParserUtils.float3ArrayToVector3(animationData.pMin),
                    TgcParserUtils.float3ArrayToVector3(animationData.pMax));
            }
            else
            {
                boundingBox = mesh.BoundingBox;
            }
                
            //Crear animacion
            TgcSkeletalAnimation animation = new TgcSkeletalAnimation(animationData.name, animationData.frameRate, animationData.framesCount, boneFrames, boundingBox);
            return animation;
        }
        public override void init()
        {
            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;

            //Crear piso
            TgcTexture pisoTexture = TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\pasto.jpg");
            piso = TgcBox.fromSize(new Vector3(1000, 1, 1000), pisoTexture);

            //Cargar obstaculos y posicionarlos
            TgcSceneLoader loader = new TgcSceneLoader();
            obstaculos = new List<TgcMesh>();
            TgcScene scene;
            TgcMesh obstaculo;

            //Obstaculo 1: Malla estatática de Box de formato TGC
            scene = loader.loadSceneFromFile(
                GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\Box\\" + "Box-TgcScene.xml",
                GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\Box\\");
            //Escalarlo, posicionarlo y agregar a array de obstáculos
            obstaculo = scene.Meshes[0];
            obstaculo.Scale = new Vector3(1, 2, 1);
            obstaculo.move(-100, 20, 0);
            obstaculos.Add(obstaculo);

            //Obstaculo 2: Malla estatática de Box de formato TGC
            scene = loader.loadSceneFromFile(
                GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\Box\\" + "Box-TgcScene.xml",
                GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\Box\\");
            //Escalarlo, posicionarlo y agregar a array de obstáculos
            obstaculo = scene.Meshes[0];
            obstaculo.Scale = new Vector3(1, 2, 1);
            obstaculo.move(0, 20, 100);
            //Le cambiamos la textura a este modelo particular
            obstaculo.changeDiffuseMaps(new TgcTexture[]{TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\madera.jpg")});
            obstaculos.Add(obstaculo);

            //Obstaculo 2: Malla estatática de Box de formato TGC
            scene = loader.loadSceneFromFile(
                GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\Box\\" + "Box-TgcScene.xml",
                GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\Box\\");
            //Escalarlo, posicionarlo y agregar a array de obstáculos
            obstaculo = scene.Meshes[0];
            obstaculo.Scale = new Vector3(1, 2, 1);
            obstaculo.move(100, 20, 100);
            obstaculos.Add(obstaculo);

            //Cargar personaje con animaciones con herramienta TgcKeyFrameLoader
            TgcSkeletalLoader keyFrameLoader = new TgcSkeletalLoader();
            personaje =  keyFrameLoader.loadMeshAndAnimationsFromFile(
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Robot-TgcSkeletalMesh.xml",
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\",
                new string[] { GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Caminando-TgcSkeletalAnim.xml" });

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

            //Escalar y posicionar
            personaje.Scale = new Vector3(0.5f, 0.5f, 0.5f);
            personaje.Position = new Vector3(0,0,0);

            //Hacer que la cámara mire hacia un determinado lugar del escenario
            GuiController.Instance.setCamera(new Vector3(-80, 165, 230), new Vector3(0, 0, 0));

            //Deshabilitar camara para que no interfiera con los controles de nuestro ejemplo
            GuiController.Instance.RotCamera.Enable = false;

            //Modifier para habilitar o no el renderizado del BoundingBox del personaje
            GuiController.Instance.Modifiers.addBoolean("showBoundingBox", "Bouding Box", false);
        }
        public override void init()
        {
            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;

            //Crear piso
            TgcTexture pisoTexture = TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\tierra.jpg");
            piso = TgcBox.fromSize(new Vector3(0,-60,0), new Vector3(1000, 5, 1000), pisoTexture);


            //Cargar obstaculos y posicionarlos. Los obstáculos se crean con TgcBox en lugar de cargar un modelo.
            obstaculos = new List<TgcBox>();
            TgcBox obstaculo;
            

            //Obstaculo 1
            obstaculo = TgcBox.fromSize(
                new Vector3(-100, 0, 0),
                new Vector3(80, 150, 80),
                TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\baldosaFacultad.jpg"));
            obstaculos.Add(obstaculo);

            //Obstaculo 2
            obstaculo = TgcBox.fromSize(
                new Vector3(50, 0, 200),
                new Vector3(80, 300, 80),
                TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\madera.jpg"));
            obstaculos.Add(obstaculo);

            //Obstaculo 3
            obstaculo = TgcBox.fromSize(
                new Vector3(300, 0, 100),
                new Vector3(80, 100, 150),
                TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Texturas\\granito.jpg"));
            obstaculos.Add(obstaculo);


            //Cargar personaje con animaciones
            TgcSkeletalLoader skeletalLoader = new TgcSkeletalLoader();
            personaje = skeletalLoader.loadMeshAndAnimationsFromFile(
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Robot-TgcSkeletalMesh.xml",
                GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\",
                new string[] { 
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Caminando-TgcSkeletalAnim.xml",
                    GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\" + "Parado-TgcSkeletalAnim.xml",
                });

            //Le cambiamos la textura para diferenciarlo un poco
            personaje.changeDiffuseMaps(new TgcTexture[] { TgcTexture.createTexture(d3dDevice, GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\Textures\\" + "uvwGreen.jpg") });
            
            //Configurar animacion inicial
            personaje.playAnimation("Parado", true);
            //Escalarlo porque es muy grande
            personaje.Position = new Vector3(0,-45,0);
            personaje.Scale = new Vector3(0.75f, 0.75f, 0.75f);
            //Rotarlo 180° porque esta mirando para el otro lado
            personaje.rotateY(Geometry.DegreeToRadian(180f));
            
            
            

            //Configurar camara en Tercer Persona
            GuiController.Instance.ThirdPersonCamera.Enable = true;
            GuiController.Instance.ThirdPersonCamera.setCamera(personaje.Position, 200, -300);


            //Modifier para ver BoundingBox
            GuiController.Instance.Modifiers.addBoolean("showBoundingBox", "Bouding Box", false);

            //Modifiers para desplazamiento del personaje
            GuiController.Instance.Modifiers.addFloat("VelocidadCaminar", 1f, 400f, 250f);
            GuiController.Instance.Modifiers.addFloat("VelocidadRotacion", 1f, 360f, 120f);

        }
Beispiel #28
0
 public Enemigo(TgcSkeletalMesh mesh, Vector3 pos)
 {
     this.meshEnemigo = mesh;
     this.estaVivo = true;
     this.ultimaPosicion = pos;
 }
        /// <summary>
        /// Cargar una nueva malla
        /// </summary>
        private void changeMesh(string meshName)
        {
            if (selectedMesh == null || selectedMesh != meshName)
            {
                if (mesh != null)
                {
                    mesh.dispose();
                    mesh = null;
                }

                selectedMesh = meshName;

                //Cargar mesh y animaciones
                TgcSkeletalLoader loader = new TgcSkeletalLoader();
                mesh = loader.loadMeshAndAnimationsFromFile(mediaPath + selectedMesh + "-TgcSkeletalMesh.xml", mediaPath, animationsPath);

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

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

                //Crear caja como modelo de Attachment del hueos "Bip01 L Hand"
                attachment = new TgcSkeletalBoneAttach();
                TgcBox attachmentBox = TgcBox.fromSize(new Vector3(2, 40, 2), Color.Red);
                attachment.Mesh = attachmentBox.toMesh("attachment");
                attachment.Bone = mesh.getBoneByName("Bip01 L Hand");
                attachment.Offset = Matrix.Translation(3, -15, 0);
                attachment.updateValues();


                //Configurar camara
                GuiController.Instance.RotCamera.targetObject(mesh.BoundingBox);
            }
        }
        /// <summary>
        /// Crea una nueva malla que es una instancia de otra malla original.
        /// Reutiliza toda la geometría de la malla original sin duplicarla.
        /// Debe crearse luego de haber cargado todas las animaciones en la malla original
        /// </summary>
        /// <param name="name">Nombre de la malla</param>
        /// <param name="parentInstance">Malla original desde la cual basarse</param>
        /// <param name="translation">Traslación respecto de la malla original</param>
        /// <param name="rotation">Rotación respecto de la malla original</param>
        /// <param name="scale">Escala respecto de la malla original</param>
        public TgcSkeletalMesh(string name, TgcSkeletalMesh parentInstance, Vector3 translation, Vector3 rotation, Vector3 scale)
        {
            //Cargar iniciales datos en base al original
            this.initData(parentInstance.d3dMesh, name, parentInstance.renderType, parentInstance.bones);
            this.diffuseMaps = parentInstance.diffuseMaps;
            this.materials = parentInstance.materials;

            //Almacenar transformación inicial
            this.translation = translation;
            this.rotation = rotation;
            this.scale = scale;

            //Agregar animaciones del original
            foreach (KeyValuePair<string, TgcSkeletalAnimation> entry in parentInstance.animations)
            {
                this.animations.Add(entry.Key, entry.Value);
            }

            //Agregar attachments del original, creando una instancia por cada attach
            foreach (TgcSkeletalBoneAttach parentAttach in parentInstance.attachments)
            {
                TgcSkeletalBoneAttach attach = new TgcSkeletalBoneAttach();
                attach.Bone = parentAttach.Bone;
                attach.Offset = parentAttach.Offset;
                //Crear instancia del mesh del attach del padre
                attach.Mesh = parentAttach.Mesh.createMeshInstance(name + "-" + parentAttach.Mesh.Name);
                attach.updateValues();
                this.attachments.Add(attach);
            }

            //almacenar instancia en el padre
            this.parentInstance = parentInstance;
            parentInstance.meshInstances.Add(this);
        }
 private void computeNormals(TgcSkeletalMesh mesh)
 {
     mesh.getVertexPositions();
 }
        /// <summary>
        /// Crea una nueva malla que es una instancia de esta malla original
        /// Reutiliza toda la geometría de la malla original sin duplicarla.
        /// Solo se puede crear instancias a partir de originales.
        /// Se debe crear después de haber agregado todas las animaciones al original.
        /// Los attachments de la malla original se duplican.
        /// </summary>
        /// <param name="name">Nombre de la malla</param>
        /// <param name="translation">Traslación respecto de la malla original</param>
        /// <param name="rotation">Rotación respecto de la malla original</param>
        /// <param name="scale">Escala respecto de la malla original</param>
        public TgcSkeletalMesh createMeshInstance(string name, Vector3 translation, Vector3 rotation, Vector3 scale)
        {
            if (this.parentInstance != null)
            {
                throw new Exception("No se puede crear una instancia de otra malla instancia. Hay que partir del original.");
            }

            //Crear instancia
            TgcSkeletalMesh instance = new TgcSkeletalMesh(name, this, translation, rotation, scale);

            //BoundingBox
            instance.boundingBox = new TgcBoundingBox(this.boundingBox.PMin, this.boundingBox.PMax);
            instance.updateBoundingBox();

            instance.enabled = true;
            return instance;
        }
        public override void init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

            //Paths para archivo XML de la malla
            string pathMesh = GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\Robot-TgcSkeletalMesh.xml";

            //Path para carpeta de texturas de la malla
            string mediaPath = GuiController.Instance.ExamplesMediaDir + "SkeletalAnimations\\Robot\\";

            //Lista de animaciones disponibles
            string[] animationList = new string[]{
                "Parado",
                "Caminando",
                "Correr",
                "PasoDerecho",
                "PasoIzquierdo",
                "Empujar",
                "Patear",
                "Pegar",
                "Arrojar",
            };

            //Crear rutas con cada animacion
            string[] animationsPath = new string[animationList.Length];
            for (int i = 0; i < animationList.Length; i++)
            {
                animationsPath[i] = mediaPath + animationList[i] + "-TgcSkeletalAnim.xml";
            }

            //Cargar mesh y animaciones
            TgcSkeletalLoader loader = new TgcSkeletalLoader();
            mesh = loader.loadMeshAndAnimationsFromFile(pathMesh, mediaPath, animationsPath);

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

            //Agregar combo para elegir animacion
            GuiController.Instance.Modifiers.addInterval("animation", animationList, 0);
            selectedAnim = animationList[0];

            //Modifier para especificar si la animación se anima con loop
            bool animateWithLoop = true;
            GuiController.Instance.Modifiers.addBoolean("loop", "Loop anim:", animateWithLoop);

            //Modifier para renderizar el esqueleto
            bool renderSkeleton = false;
            GuiController.Instance.Modifiers.addBoolean("renderSkeleton", "Show skeleton:", renderSkeleton);

            //Modifier para FrameRate
            GuiController.Instance.Modifiers.addFloat("frameRate", 0, 100, 30);

            //Modifier para color
            currentColor = Color.White;
            GuiController.Instance.Modifiers.addColor("Color", currentColor);

            //Modifier para BoundingBox
            GuiController.Instance.Modifiers.addBoolean("BoundingBox", "BoundingBox:", false);

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

            //Crear caja como modelo de Attachment del hueos "Bip01 L Hand"
            attachment = new TgcSkeletalBoneAttach();
            TgcBox attachmentBox = TgcBox.fromSize(new Vector3(5, 100, 5), Color.Blue);
            attachment.Mesh = attachmentBox.toMesh("attachment");
            attachment.Bone = mesh.getBoneByName("Bip01 L Hand");
            attachment.Offset = Matrix.Translation(10, -40, 0);
            attachment.updateValues();

            //Modifier para habilitar attachment
            showAttachment = false;
            GuiController.Instance.Modifiers.addBoolean("Attachment", "Attachment:", showAttachment);

            //Configurar camara
            GuiController.Instance.RotCamera.setCamera(new Vector3(0, 70, 0), 200);
        }
Beispiel #34
0
        /// <summary>
        /// Carga un Modelo a partir de un objeto TgcSkeletalMeshData ya parseado
        /// </summary>
        /// <param name="meshData">Objeto con datos ya parseados</param>
        /// <param name="mediaPath">Path a partir del cual hay que buscar las Texturas</param>
        /// <returns>Modelo cargado</returns>
        public TgcSkeletalMesh loadMesh(TgcSkeletalMeshData meshData, string mediaPath)
        {
            //Cargar Texturas
            TgcSkeletalLoaderMaterialAux[] materialsArray = new TgcSkeletalLoaderMaterialAux[meshData.materialsData.Length];
            for (int i = 0; i < meshData.materialsData.Length; i++)
            {
                TgcMaterialData materialData = meshData.materialsData[i];
                string          texturesPath = mediaPath + meshData.texturesDir + "\\";

                //Crear StandardMaterial
                if (materialData.type.Equals(TgcMaterialData.StandardMaterial))
                {
                    materialsArray[i] = createTextureAndMaterial(materialData, texturesPath);
                }

                //Crear MultiMaterial
                else if (materialData.type.Equals(TgcMaterialData.MultiMaterial))
                {
                    TgcSkeletalLoaderMaterialAux matAux = new TgcSkeletalLoaderMaterialAux();
                    materialsArray[i]   = matAux;
                    matAux.subMaterials = new TgcSkeletalLoaderMaterialAux[materialData.subMaterials.Length];
                    for (int j = 0; j < materialData.subMaterials.Length; j++)
                    {
                        matAux.subMaterials[j] = createTextureAndMaterial(materialData.subMaterials[j], texturesPath);
                    }
                }
            }


            //Crear Mesh
            TgcSkeletalMesh tgcMesh = null;

            //Crear mesh que no tiene Material, con un color simple
            if (meshData.materialId == -1)
            {
                tgcMesh = crearMeshSoloColor(meshData);
            }


            //Crear mesh con DiffuseMap
            else
            {
                tgcMesh = crearMeshDiffuseMap(materialsArray, meshData);
            }


            //Crear BoundingBox, aprovechar lo que viene del XML o crear uno por nuestra cuenta
            if (meshData.pMin != null && meshData.pMax != null)
            {
                tgcMesh.BoundingBox = new TgcBoundingBox(
                    TgcParserUtils.float3ArrayToVector3(meshData.pMin),
                    TgcParserUtils.float3ArrayToVector3(meshData.pMax)
                    );
            }
            else
            {
                tgcMesh.createBoundingBox();
            }


            tgcMesh.Enabled = true;
            return(tgcMesh);
        }