public void render(List <TgcMesh> mapMeshes, Vector3 camPos, TgcMesh meshesAuto, Matrix mr, Vector3 Posicion, Vector3 pivote, float anguloFinal, bool lucesOn, Vector3 v3)
        {
            if (lucesOn)
            {
                lightIntensity  = 35f;
                lightMesh.Color = Color.White;
            }

            else
            {
                lightIntensity  = 20f;
                lightMesh.Color = Color.Gray;
            }



            lightMesh.Transform = Matrix.Scaling(new Vector3(0.45f, 0.3f, -0.1f)) * Matrix.Translation(Posicion) * mr * Matrix.Translation(pivote);

            lighthPos = Posicion + pivote + v3;

            lightMesh.updateValues();


            foreach (var mesh in mapMeshes)
            {
                setEffects(camPos, mesh);
            }
            setEffects(camPos, meshesAuto);

            /*
             * foreach (var mesh in meshesAuto)
             * {
             *   setEffects(camPos, mesh);
             * }*/
        }
Exemple #2
0
        public void init(string text)
        {
            TgcBox box = new TgcBox();

            box.setExtremes(new Vector3(0, 0, 0), new Vector3(400, 2, 1000));
            box.Color = Color.Blue;
            box.updateValues();
            TgcMesh temp = box.toMesh("water");

            TgcSceneLoader loader = new TgcSceneLoader();

            //Configurar MeshFactory customizado
            loader.MeshFactory = new ShadedMeshFactory();
            mesh             = (ShadedMesh)loader.MeshFactory.createNewMesh(temp.D3dMesh, "water", TgcMesh.MeshRenderType.VERTEX_COLOR);
            mesh.BoundingBox = box.BoundingBox;
            mesh.loadEffect("Shaders//water.fx", "Basic");
            mesh.AutoUpdateBoundingBox = false;

            TgcTexture t_temp = TgcTexture.createTexture(GuiController.Instance.D3dDevice, GuiController.Instance.AlumnoEjemplosMediaDir + "RenderizameLaBanera\\waterbump.dds");//"perlin_noise.jpg");//"waterbump.dds");

            noise       = t_temp.D3dTexture;
            t_temp      = TgcTexture.createTexture(GuiController.Instance.D3dDevice, GuiController.Instance.AlumnoEjemplosMediaDir + "RenderizameLaBanera\\" + text);
            riverBottom = t_temp.D3dTexture;

            mesh.Effect.SetValue("xNoiseTex", noise);
            mesh.Effect.SetValue("xRiverBottom", riverBottom);

            Surface renderTarget = GuiController.Instance.D3dDevice.GetRenderTarget(0);

            riverReflex = new Texture(GuiController.Instance.D3dDevice, renderTarget.Description.Width, renderTarget.Description.Height, 1, Usage.RenderTarget, renderTarget.Description.Format, Pool.Default);
        }
Exemple #3
0
        /// <summary>
        /// Setear centro del gizmo y ajustar tamaño segun distancia con la camara
        /// </summary>
        public void setCenter(Vector3 gizmoCenter, MeshCreatorCamera camera)
        {
            this.gizmoCenter = gizmoCenter;
            float increment = MeshCreatorUtils.getTranslateGizmoSizeIncrement(camera, gizmoCenter);

            boxX.Size  = Vector3.Multiply(new Vector3(LARGE_AXIS_SIZE, SHORT_AXIS_SIZE, SHORT_AXIS_SIZE), increment);
            boxY.Size  = Vector3.Multiply(new Vector3(SHORT_AXIS_SIZE, LARGE_AXIS_SIZE, SHORT_AXIS_SIZE), increment);
            boxZ.Size  = Vector3.Multiply(new Vector3(SHORT_AXIS_SIZE, SHORT_AXIS_SIZE, LARGE_AXIS_SIZE), increment);
            boxXZ.Size = Vector3.Multiply(new Vector3(INTERMEDIATE_AXIS_SIZE, SHORT_AXIS_SIZE, INTERMEDIATE_AXIS_SIZE), increment);
            boxXY.Size = Vector3.Multiply(new Vector3(INTERMEDIATE_AXIS_SIZE, INTERMEDIATE_AXIS_SIZE, SHORT_AXIS_SIZE), increment);
            boxYZ.Size = Vector3.Multiply(new Vector3(SHORT_AXIS_SIZE, INTERMEDIATE_AXIS_SIZE, INTERMEDIATE_AXIS_SIZE), increment);

            boxX.Position  = gizmoCenter + Vector3.Multiply(boxX.Size, 0.5f) + new Vector3(SHORT_AXIS_SIZE, 0, 0);
            boxY.Position  = gizmoCenter + Vector3.Multiply(boxY.Size, 0.5f) + new Vector3(0, SHORT_AXIS_SIZE, 0);
            boxZ.Position  = gizmoCenter + Vector3.Multiply(boxZ.Size, 0.5f) + new Vector3(0, 0, SHORT_AXIS_SIZE);
            boxXZ.Position = gizmoCenter + new Vector3(boxXZ.Size.X / 2, 0, boxXZ.Size.Z / 2);
            boxXY.Position = gizmoCenter + new Vector3(boxXY.Size.X / 2, boxXY.Size.Y / 2, 0);
            boxYZ.Position = gizmoCenter + new Vector3(0, boxYZ.Size.Y / 2, boxYZ.Size.Z / 2);

            boxX.updateValues();
            boxY.updateValues();
            boxZ.updateValues();
            boxXZ.updateValues();
            boxXY.updateValues();
            boxYZ.updateValues();
        }
Exemple #4
0
        /// <summary>
        ///     Actualiza los parámetros de la caja en base a lo cargado por el usuario
        /// </summary>
        private void updateBox()
        {
            //Cambiar textura
            var texturePath = (string)Modifiers["texture"];

            if (texturePath != currentTexture)
            {
                currentTexture = texturePath;
                box.setTexture(TgcTexture.createTexture(D3DDevice.Instance.Device, currentTexture));
            }

            //Tamaño, posición y color
            box.Size     = (Vector3)Modifiers["size"];
            box.Position = (Vector3)Modifiers["position"];
            box.Color    = (Color)Modifiers["color"];

            //Rotación, converitr a radianes
            var rotaion = (Vector3)Modifiers["rotation"];

            box.Rotation = new Vector3(Geometry.DegreeToRadian(rotaion.X), Geometry.DegreeToRadian(rotaion.Y),
                                       Geometry.DegreeToRadian(rotaion.Z));

            //Offset y Tiling de textura
            box.UVOffset = (Vector2)Modifiers["offset"];
            box.UVTiling = (Vector2)Modifiers["tiling"];

            //Actualizar valores en la caja.
            box.updateValues();
        }
Exemple #5
0
        public override void Update()
        {
            PreUpdate();

            //Si hacen clic con el mouse, ver si hay colision con el suelo
            if (Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                //primera vez
                if (!selecting)
                {
                    //Actualizar Ray de colisión en base a posición del mouse
                    pickingRay.updateRay();

                    //Detectar colisión Ray-AABB
                    if (TgcCollisionUtils.intersectRayAABB(pickingRay.Ray, suelo.BoundingBox, out initSelectionPoint))
                    {
                        selecting = true;
                        modelosSeleccionados.Clear();
                    }
                }

                //Si se está seleccionado, generar box de seleccion
                else
                {
                    //Detectar nuevo punto de colision con el piso
                    pickingRay.updateRay();
                    Vector3 collisionPoint;
                    if (TgcCollisionUtils.intersectRayAABB(pickingRay.Ray, suelo.BoundingBox, out collisionPoint))
                    {
                        //Obtener extremos del rectángulo de selección
                        var min = Vector3.Minimize(initSelectionPoint, collisionPoint);
                        var max = Vector3.Maximize(initSelectionPoint, collisionPoint);
                        min.Y = 0;
                        max.Y = SELECTION_BOX_HEIGHT;

                        //Configurar BOX
                        selectionBox.setExtremes(min, max);
                        selectionBox.updateValues();
                    }
                }
            }

            //Solto el clic del mouse, terminar la selección
            if (Input.buttonUp(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                selecting = false;

                //Ver que modelos quedaron dentro del area de selección seleccionados
                foreach (var mesh in modelos)
                {
                    //Colisión de AABB entre área de selección y el modelo
                    if (TgcCollisionUtils.testAABBAABB(selectionBox.BoundingBox, mesh.BoundingBox))
                    {
                        modelosSeleccionados.Add(mesh);
                    }
                }
            }
        }
        public override void Update()
        {
            PreUpdate();

            //Actualizo los valores de la luz
            lightMesh.Enabled  = (bool)Modifiers["lightEnable"];
            lightMesh.Position = (Vector3)Modifiers["lightPos"];
            lightMesh.Color    = (Color)Modifiers["lightColor"];
            lightMesh.updateValues();
        }
        public PointLight2(GameModel gm, Vector3 Posicion)
        {
            gameModel = gm;
            lighthPos = Posicion;
            float t = 10f;

            lightMesh = TgcBox.fromSize(lighthPos, new Vector3(t, t, t), Color.White);
            lightMesh.AutoTransformEnable = false;
            lightMesh.updateValues();
            currentShader = TgcShaders.Instance.TgcMeshPointLightShader;
        }
        public PuntoDeLuz(TwistedMetal env, Vector3 Posicion)
        {
            this.env  = env;
            lighthPos = Posicion;
            float t = 10f;

            lightMesh = TgcBox.fromSize(lighthPos, new Vector3(t, t, t), Color.White);
            lightMesh.AutoTransformEnable = false;
            lightMesh.updateValues();
            //currentShader = TgcShaders.Instance.TgcMeshPointLightShader;
            currentShader = TgcShaders.loadEffect(this.env.ShadersDir + "TgcMeshSpotLightShader.fx");
        }
Exemple #9
0
        /// <summary>
        /// Configurar posicion y tamaño de ejes segun la distancia a la camara
        /// </summary>
        private void setAxisPositionAndSize()
        {
            float increment = MeshCreatorUtils.getTranslateGizmoSizeIncrement(Control.Camera, gizmoCenter);

            boxX.Size = Vector3.Multiply(new Vector3(LARGE_AXIS_SIZE, SHORT_AXIS_SIZE, SHORT_AXIS_SIZE), increment);
            boxY.Size = Vector3.Multiply(new Vector3(SHORT_AXIS_SIZE, LARGE_AXIS_SIZE, SHORT_AXIS_SIZE), increment);
            boxZ.Size = Vector3.Multiply(new Vector3(SHORT_AXIS_SIZE, SHORT_AXIS_SIZE, LARGE_AXIS_SIZE), increment);

            boxX.Position = gizmoCenter + Vector3.Multiply(boxX.Size, 0.5f) + new Vector3(SHORT_AXIS_SIZE, 0, 0);
            boxY.Position = gizmoCenter + Vector3.Multiply(boxY.Size, 0.5f) + new Vector3(0, SHORT_AXIS_SIZE, 0);
            boxZ.Position = gizmoCenter + Vector3.Multiply(boxZ.Size, 0.5f) + new Vector3(0, 0, SHORT_AXIS_SIZE);

            boxX.updateValues();
            boxY.updateValues();
            boxZ.updateValues();
        }
Exemple #10
0
        public override void render(float elapsedTime)
        {
            Device  device      = GuiController.Instance.D3dDevice;
            Control panel3d     = GuiController.Instance.Panel3d;
            float   aspectRatio = (float)panel3d.Width / (float)panel3d.Height;

            time += elapsedTime;
            // animo la pos del avion
            float alfa = -time *Geometry.DegreeToRadian(115.0f);

            avion.Position  = new Vector3(80f * (float)Math.Cos(alfa), 20 - 20 * (float)Math.Sin(alfa), 80f * (float)Math.Sin(alfa));
            dir_avion       = new Vector3(-(float)Math.Sin(alfa), 0, (float)Math.Cos(alfa));
            avion.Transform = CalcularMatriz(avion.Position, avion.Scale, dir_avion);
            g_LightPos      = (Vector3)GuiController.Instance.Modifiers["LightLookFrom"];

            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);

            // dibujo la escena pp dicha
            device.BeginScene();
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);

            // piso
            scene.Meshes[0].Technique = "RenderScene";
            scene.Meshes[0].render();

            // dibujo las sombra del avion sobre el piso
            effect.SetValue("matViewProj", device.Transform.View * device.Transform.Projection);
            effect.SetValue("g_vLightPos", new Vector4(g_LightPos.X, g_LightPos.Y, g_LightPos.Z, 1));
            device.RenderState.ZBufferEnable = false;
            avion.Technique = "RenderShadows";
            avion.render();
            device.RenderState.ZBufferEnable = true;

            // avion
            avion.Technique = "RenderScene";
            avion.render();

            // dibujo la luz
            box.setPositionSize(g_LightPos, new Vector3(5, 5, 5));
            box.updateValues();
            box.render();

            device.EndScene();
        }
Exemple #11
0
        /// <summary>
        ///     Actualiza los parametros de la caja en base a lo cargado por el usuario
        /// </summary>
        private void updateBox()
        {
            //Cambiar textura
            var texturePath = (string)Modifiers["texture"];

            if (texturePath != currentTexture)
            {
                currentTexture = texturePath;
                box.setTexture(TgcTexture.createTexture(D3DDevice.Instance.Device, currentTexture));
            }

            var size      = (Vector3)Modifiers["size"];
            var position  = (Vector3)Modifiers["position"];
            var thickness = (float)Modifiers["thickness"];
            var color     = (Color)Modifiers["color"];

            //Tamano, posicion y color
            box.Size     = size;
            box.Position = position + new Vector3(15f, 0, 0);
            box.Color    = color;

            //Actualizar valores en la caja.
            debugBox.setPositionSize(position - new Vector3(15f, 0, 0), size);
            debugBox.Thickness = thickness;
            debugBox.Color     = color;

            //Rotacion, converitr a radianes
            var rotaion = (Vector3)Modifiers["rotation"];

            box.Rotation = new Vector3(Geometry.DegreeToRadian(rotaion.X), Geometry.DegreeToRadian(rotaion.Y),
                                       Geometry.DegreeToRadian(rotaion.Z));

            //Offset y Tiling de textura
            box.UVOffset = (Vector2)Modifiers["offset"];
            box.UVTiling = (Vector2)Modifiers["tiling"];

            //Actualizar valores en la caja. IMPORTANTE, es mejor realizar transformaciones con matrices.
            debugBox.updateValues();
            //Actualizar valores en la caja. IMPORTANTE, es mejor realizar transformaciones con matrices.
            //Otra cosa importante, las rotaciones no modifican el AABB. con lo cual hay que tener cuidado.
            box.updateValues();
        }
Exemple #12
0
        /// <summary>
        /// Acomodar Gizmo en base a un Mesh
        /// </summary>
        public void setMesh(SceneEditorMeshObject meshObj)
        {
            this.meshObj      = meshObj;
            this.selectedAxis = Axis.None;

            /*
             * float aabbbR = meshObj.mesh.BoundingBox.calculateBoxRadius();
             * float largeSize = LARGE_AXIS_SIZE * aabbbR;
             * float shortSize = SHORT_AXIS_SIZE;
             *
             * boxX.Size = new Vector3(largeSize, shortSize, shortSize);
             * boxY.Size = new Vector3(shortSize, largeSize, shortSize);
             * boxZ.Size = new Vector3(shortSize, shortSize, largeSize);
             *
             * Vector3 pos = meshObj.mesh.Position;
             * boxX.Position = pos + Vector3.Scale(boxX.Size, 0.5f);
             * boxY.Position = pos + Vector3.Scale(boxY.Size, 0.5f);
             * boxZ.Position = pos + Vector3.Scale(boxZ.Size, 0.5f);
             */


            Vector3 meshCenter = meshObj.mesh.BoundingBox.calculateBoxCenter();
            Vector3 axisRadius = meshObj.mesh.BoundingBox.calculateAxisRadius();

            float largeX = axisRadius.X + LARGE_AXIS_MIN_SIZE;
            float largeY = axisRadius.Y + LARGE_AXIS_MIN_SIZE;
            float largeZ = axisRadius.Z + LARGE_AXIS_MIN_SIZE;

            boxX.Size = new Vector3(largeX, SHORT_AXIS_SIZE, SHORT_AXIS_SIZE);
            boxY.Size = new Vector3(SHORT_AXIS_SIZE, largeY, SHORT_AXIS_SIZE);
            boxZ.Size = new Vector3(SHORT_AXIS_SIZE, SHORT_AXIS_SIZE, largeZ);

            boxX.Position = meshCenter + Vector3.Multiply(boxX.Size, 0.5f);
            boxY.Position = meshCenter + Vector3.Multiply(boxY.Size, 0.5f);
            boxZ.Position = meshCenter + Vector3.Multiply(boxZ.Size, 0.5f);

            boxX.updateValues();
            boxY.updateValues();
            boxZ.updateValues();
        }
Exemple #13
0
        public void init(int x, int y, int z)
        {
            TgcBox box = new TgcBox();

            box.setExtremes(new Vector3(0, 0, 0), new Vector3(x, y, z));
            box.Color = Color.Brown;
            box.updateValues();
            TgcMesh temp = box.toMesh("earth");

            TgcSceneLoader loader = new TgcSceneLoader();

            //Configurar MeshFactory customizado
            loader.MeshFactory = new ShadedMeshFactory();
            mesh             = (ShadedMesh)loader.MeshFactory.createNewMesh(temp.D3dMesh, "earth", TgcMesh.MeshRenderType.VERTEX_COLOR);
            mesh.BoundingBox = box.BoundingBox;
            mesh.loadEffect("Shaders//hoja.fx", "Basic");

            TgcTexture tex_temp = TgcTexture.createTexture(GuiController.Instance.D3dDevice, GuiController.Instance.AlumnoEjemplosMediaDir + "RenderizameLaBanera\\sand.jpg");

            earthTex = tex_temp.D3dTexture;
            mesh.Effect.SetValue("xLeafTex", earthTex);
            mesh.AutoUpdateBoundingBox = false;
        }
        public override void Update()
        {
            PreUpdate();

            //obtener velocidades de Modifiers
            var velocidadCaminar  = (float)Modifiers.getValue("VelocidadCaminar");
            var velocidadRotacion = (float)Modifiers.getValue("VelocidadRotacion");
            var velocidadSalto    = (float)Modifiers.getValue("VelocidadSalto");
            var tiempoSalto       = (float)Modifiers.getValue("TiempoSalto");

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

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

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

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

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

            //Jump
            if (!jumping && Input.keyPressed(Key.Space))
            {
                //Se puede saltar solo si hubo colision antes
                if (collisionManager.Result.collisionFound)
                {
                    jumping            = true;
                    jumpingElapsedTime = 0f;
                    jump = 0;
                }
            }

            //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 = Geometry.DegreeToRadian(rotate * ElapsedTime);
                personaje.rotateY(rotAngle);
                camaraInterna.rotateY(rotAngle);
            }

            //Saltando
            if (jumping)
            {
                //Activar animacion de saltando
                personaje.playAnimation("Jump", true);
            }
            //Si hubo desplazamiento
            else if (moving)
            {
                //Activar animacion de caminando
                personaje.playAnimation("Walk", true);
            }
            //Si no se esta moviendo ni saltando, activar animacion de Parado
            else
            {
                personaje.playAnimation("StandBy", true);
            }

            //Actualizar salto
            if (jumping)
            {
                //El salto dura un tiempo hasta llegar a su fin
                jumpingElapsedTime += ElapsedTime;
                if (jumpingElapsedTime > tiempoSalto)
                {
                    jumping = false;
                }
                else
                {
                    jump = velocidadSalto * (tiempoSalto - jumpingElapsedTime);
                }
            }

            //Vector de movimiento
            var movementVector = Vector3.Empty;

            if (moving || jumping)
            {
                //Aplicar movimiento, desplazarse en base a la rotacion actual del personaje
                movementVector = new Vector3(
                    FastMath.Sin(personaje.Rotation.Y) * moveForward,
                    jump,
                    FastMath.Cos(personaje.Rotation.Y) * moveForward
                    );
            }

            //Actualizar valores de gravedad
            collisionManager.GravityEnabled      = (bool)Modifiers["HabilitarGravedad"];
            collisionManager.GravityForce        = (Vector3)Modifiers["Gravedad"] /** elapsedTime*/;
            collisionManager.SlideFactor         = (float)Modifiers["SlideFactor"];
            collisionManager.OnGroundMinDotValue = (float)Modifiers["Pendiente"];

            //Si esta saltando, desactivar gravedad
            if (jumping)
            {
                collisionManager.GravityEnabled = false;
            }

            //Mover personaje con detección de colisiones, sliding y gravedad
            if ((bool)Modifiers["Collisions"])
            {
                //Aca se aplica toda la lógica de detección de colisiones del CollisionManager. Intenta mover el Elipsoide
                //del personaje a la posición deseada. Retorna la verdadera posicion (realMovement) a la que se pudo mover
                var realMovement = collisionManager.moveCharacter(characterElipsoid, movementVector,
                                                                  objetosColisionables);
                personaje.move(realMovement);

                //Cargar desplazamiento realizar en UserVar
                UserVars.setValue("Movement", TgcParserUtils.printVector3(realMovement));
            }
            else
            {
                personaje.move(movementVector);
            }

            /*
             * //Si estaba saltando y hubo colision de una superficie que mira hacia abajo, desactivar salto
             * if (jumping && collisionManager.Result.collisionNormal.Y < 0)
             * {
             *  jumping = false;
             * }
             */

            //Hacer que la camara siga al personaje en su nueva posicion
            camaraInterna.Target = personaje.Position;

            //Actualizar valores de la linea de movimiento
            directionArrow.PStart = characterElipsoid.Center;
            directionArrow.PEnd   = characterElipsoid.Center + Vector3.Multiply(movementVector, 50);
            directionArrow.updateValues();

            //Actualizar valores de normal de colision
            if (collisionManager.Result.collisionFound)
            {
                collisionNormalArrow.PStart = collisionManager.Result.collisionPoint;
                collisionNormalArrow.PEnd   = collisionManager.Result.collisionPoint +
                                              Vector3.Multiply(collisionManager.Result.collisionNormal, 80);

                collisionNormalArrow.updateValues();


                collisionPoint.Position = collisionManager.Result.collisionPoint;
                collisionPoint.updateValues();
            }
        }
Exemple #15
0
        /// <summary>
        /// Creo la cancha donde van a estar parado los jugadores
        /// </summary>
        /// <param name="pathRecursos"></param>
        /// <returns>Una Cancha</returns>
        private Cancha CrearCancha(string pathRecursos)
        {
            //Cesped
            TgcBox boxField = TgcBox.fromSize(new Vector3(0, 0, 0), new Vector3(1920, 0, 1200), TgcTexture.createTexture(pathRecursos + Settings.Default.textureField));

            //TODO cambiar por matrices
            boxField.AutoTransformEnable = true;

            //Piso
            TgcBox boxFloor = TgcBox.fromSize(new Vector3(boxField.Position.X, boxField.Position.Y - 1, boxField.Position.Z), boxField.Size * 2, TgcTexture.createTexture(pathRecursos + Settings.Default.textureFloor));

            //TODO cambiar por matrices
            boxFloor.AutoTransformEnable = true;

            //Laterales
            TgcMesh tribuna1 = this.CrearTribunaPlatea(pathRecursos, boxField, 1);

            //TODO cambiar por matrices
            tribuna1.AutoTransformEnable = true;
            TgcMesh tribuna2 = this.CrearTribunaPlatea(pathRecursos, boxField, -1);

            //TODO cambiar por matrices
            tribuna2.AutoTransformEnable = true;

            //Atras del arco
            TgcMesh tribuna3 = this.CrearTribunaPopular(pathRecursos, boxField, 1);

            //TODO cambiar por matrices
            tribuna3.AutoTransformEnable = true;
            TgcMesh tribuna4 = this.CrearTribunaPopular(pathRecursos, boxField, -1);

            //TODO cambiar por matrices
            tribuna4.AutoTransformEnable = true;

            List <TgcBox> carteles = new List <TgcBox>();

            TgcBox cartel1 = TgcBox.fromSize(new Vector3(0, 15, boxField.Size.Z / 2), new Vector3(150, 30, 0), TgcTexture.createTexture(pathRecursos + "Texturas\\gnome-logo.png"));

            //TODO cambiar por matrices
            cartel1.AutoTransformEnable = true;
            cartel1.Effect    = TgcShaders.loadEffect(pathRecursos + "Shaders\\CartelShader.fx");
            cartel1.Technique = "Rotacion";
            cartel1.updateValues();

            TgcBox cartel2 = TgcBox.fromSize(new Vector3(200, 15, boxField.Size.Z / 2), new Vector3(150, 30, 0), TgcTexture.createTexture(pathRecursos + "Texturas\\blizzard_logo.jpg"));

            //TODO cambiar por matrices
            cartel2.AutoTransformEnable = true;
            cartel2.Effect    = TgcShaders.loadEffect(pathRecursos + "Shaders\\CartelShader.fx");
            cartel2.Technique = "Rotacion";
            cartel2.updateValues();

            TgcBox cartel3 = TgcBox.fromSize(new Vector3(-200, 15, boxField.Size.Z / 2), new Vector3(150, 30, 0), TgcTexture.createTexture(pathRecursos + "Texturas\\github-logo.jpg"));

            //TODO cambiar por matrices
            cartel3.AutoTransformEnable = true;
            cartel3.Effect    = TgcShaders.loadEffect(pathRecursos + "Shaders\\CartelShader.fx");
            cartel3.Technique = "Rotacion";
            cartel3.updateValues();

            TgcBox cartel4 = TgcBox.fromSize(new Vector3(400, 15, boxField.Size.Z / 2), new Vector3(150, 30, 0), TgcTexture.createTexture(pathRecursos + "Texturas\\atom-editor-logo.png"));

            //TODO cambiar por matrices
            cartel4.AutoTransformEnable = true;
            cartel4.Effect    = TgcShaders.loadEffect(pathRecursos + "Shaders\\CartelShader.fx");
            cartel4.Technique = "Rotacion";
            cartel4.updateValues();

            TgcBox cartel5 = TgcBox.fromSize(new Vector3(-400, 15, boxField.Size.Z / 2), new Vector3(150, 30, 0), TgcTexture.createTexture(pathRecursos + "Texturas\\visual-studio-logo.png"));

            //TODO cambiar por matrices
            cartel5.AutoTransformEnable = true;
            cartel5.Effect    = TgcShaders.loadEffect(pathRecursos + "Shaders\\CartelShader.fx");
            cartel5.Technique = "CartelFallando";
            cartel5.updateValues();

            carteles.Add(cartel1);
            carteles.Add(cartel2);
            carteles.Add(cartel3);
            carteles.Add(cartel4);
            carteles.Add(cartel5);

            //SkyBox
            TgcSkyBox skyBox = this.CrearSkyBox(pathRecursos, boxFloor);

            //Limites de la cancha
            List <LimiteCancha> limites = this.CrearLimitesCancha(boxField);

            //Luces
            List <Luz> luces = this.CrearLuces(pathRecursos, boxField);

            List <IRenderObject> componentes = new List <IRenderObject>();

            componentes.Add(tribuna1);
            componentes.Add(tribuna2);
            componentes.Add(tribuna3);
            componentes.Add(tribuna4);
            componentes.Add(boxFloor);
            componentes.Add(skyBox);
            int altoMuralla = 200;

            componentes.Add(TgcBox.fromSize(new Vector3(boxFloor.Position.X, boxFloor.Position.Y + altoMuralla / 2, boxFloor.Size.Z / 2), new Vector3(boxFloor.Size.X, altoMuralla, 0), TgcTexture.createTexture(pathRecursos + Settings.Default.textureWall)));
            componentes.Add(TgcBox.fromSize(new Vector3(boxFloor.Position.X, boxFloor.Position.Y + altoMuralla / 2, -boxFloor.Size.Z / 2), new Vector3(boxFloor.Size.X, altoMuralla, 0), TgcTexture.createTexture(pathRecursos + Settings.Default.textureWall)));
            componentes.Add(TgcBox.fromSize(new Vector3(boxFloor.Size.X / 2, boxFloor.Position.Y + altoMuralla / 2, boxFloor.Position.Z), new Vector3(0, altoMuralla, boxFloor.Size.Z), TgcTexture.createTexture(pathRecursos + Settings.Default.textureWall)));
            componentes.Add(TgcBox.fromSize(new Vector3(-boxFloor.Size.X / 2, boxFloor.Position.Y + altoMuralla / 2, boxFloor.Position.Z), new Vector3(0, altoMuralla, boxFloor.Size.Z), TgcTexture.createTexture(pathRecursos + Settings.Default.textureWall)));
            componentes.Add(cartel1);

            return(new Cancha(boxField, componentes, limites, luces, carteles));
        }
Exemple #16
0
        public override void render(float elapsedTime)
        {
            motionBlurFlag = (bool)GuiController.Instance.Modifiers["motionBlurFlag"];
            TgcTexture texture = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "TheC#\\Pista\\pistaCarreras.png");

            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;


            //pantalla De Inicio
            if (flagInicio == 0)
            {
                //Actualizar valores cargados en modifiers

                /*sprite.Position = (Vector2)GuiController.Instance.Modifiers["position"];
                 * sprite.Scaling = (Vector2)GuiController.Instance.Modifiers["scaling"];
                 * sprite.Rotation = FastMath.ToRad((float)GuiController.Instance.Modifiers["rotation"]);
                 */
                //Iniciar dibujado de todos los Sprites de la escena (en este caso es solo uno)
                GuiController.Instance.Drawer2D.beginDrawSprite();
                sprite.render();
                //Finalizar el dibujado de Sprites
                GuiController.Instance.Drawer2D.endDrawSprite();
                flagInicio = jugador.verSiAprietaSpace();
                textIngreseTeclaSombra.render();
                textIngreseTecla.render();
                musica.verSiCambioMP3();
            }
            else
            {
                //Para contar el tiempo desde que preciona la barra espaciadora y comienza el juego
                if (primerRenderDelJuegoAndando == true)
                {
                    this.horaInicio             = DateTime.Now;
                    primerRenderDelJuegoAndando = false;
                }
                //Todo lo referente a lo que debe hacer el IA
                autoIA.elapsedTime = elapsedTime;
                autoIA.establecerVelocidadMáximaEn((float)GuiController.Instance.Modifiers["velocidadMaxima"] * 1.02f);

                if (colision.getTiempoQueChoco() == 0)
                {
                    jugadorIA.jugar(trayectoDeIA[0].Center, meshAutoIA.Position);
                }

                meshAutoIA.Rotation = new Vector3(0f, autoIA.rotacion, 0f);
                jugadorIA.setRotacion(meshAutoIA.Rotation);

                meshAutoIA.moveOrientedY(-autoIA.velocidad * elapsedTime);
                //Fin movimiento de auto IA

                //Le paso el elapsed time al auto porque sus metodos no deben depender de los FPS
                auto.elapsedTime = elapsedTime;

                //Varío la velocidad Máxima del vehículo con el modifier "velocidadMáxima"
                auto.establecerVelocidadMáximaEn((float)GuiController.Instance.Modifiers["velocidadMaxima"]);

                //El jugador envia mensajes al auto dependiendo de que tecla presiono
                //Se pone un tiempo para que luego de chocar 2 autos, estos no puedan ingresar movimiento (sólo se mueve por inercia)
                if (colision.getTiempoQueChoco() == 0)
                {
                    jugador.jugar(cantidadDeNitro);
                }
                else
                {
                    colision.setTiempoQueChoco(colision.getTiempoQueChoco() - (8 * elapsedTime));
                    if (colision.getTiempoQueChoco() < 0)
                    {
                        colision.setTiempoQueChoco(0);
                    }
                }

                //Transfiero la rotacion del auto abstracto al mesh, y su obb
                autoMesh.Rotation = new Vector3(0f, auto.rotacion, 0f);
                oBBAuto.Center    = autoMesh.Position;
                oBBAuto.setRotation(autoMesh.Rotation);
                meshAutoIA.Rotation = new Vector3(0f, autoIA.rotacion, 0f);
                oBBAutoIa.Center    = meshAutoIA.Position;
                oBBAutoIa.setRotation(meshAutoIA.Rotation);


                //Calculo de giro de la rueda
                rotacionVertical -= auto.velocidad * elapsedTime / 60;

                //Calculo el movimiento del mesh dependiendo de la velocidad del auto
                autoMesh.moveOrientedY(-auto.velocidad * elapsedTime);
                //Detección de colisiones
                //Hubo colisión con un objeto. Guardar resultado y abortar loop.



                //Si hubo alguna colisión, hacer esto:
                if (huboColision(oBBAuto))
                {
                    autoMesh.moveOrientedY(20 * auto.velocidad * elapsedTime); //Lo hago "como que rebote un poco" para no seguir colisionando
                    auto.velocidad = -(auto.velocidad * 0.3f);                 //Lo hago ir atrás un tercio de velocidad de choque
                }
                if (huboColision(oBBAutoIa))
                {
                    meshAutoIA.moveOrientedY(20 * autoIA.velocidad * elapsedTime); //Lo hago "como que rebote un poco" para no seguir colisionando
                    autoIA.velocidad = -(autoIA.velocidad * 0.3f);                 //Lo hago ir atrás un tercio de velocidad de choque
                }

                //Colisión entre los autos
                for (int i = 0; i < 4; i++)
                {
                    float ro, alfa_rueda;
                    float posicion_xA1;
                    float posicion_yA1;
                    float posicion_xA2;
                    float posicion_yA2;

                    ro = FastMath.Sqrt(dx[i] * dxAColision[i] + dyAColision[i] * dyAColision[i]);

                    alfa_rueda = FastMath.Asin(dxAColision[i] / ro);
                    if (i == 0 || i == 2)
                    {
                        alfa_rueda += FastMath.PI;
                    }
                    posicion_xA1 = FastMath.Sin(alfa_rueda + auto.rotacion) * ro;
                    posicion_yA1 = FastMath.Cos(alfa_rueda + auto.rotacion) * ro;

                    posicion_xA2 = FastMath.Sin(alfa_rueda + autoIA.rotacion) * ro;
                    posicion_yA2 = FastMath.Cos(alfa_rueda + autoIA.rotacion) * ro;

                    obbsAuto[i].Position = (new Vector3(posicion_xA1, 15.5f, posicion_yA1) + autoMesh.Position);

                    obbsOtroAuto[i].Position = (new Vector3(posicion_xA2, 15.5f, posicion_yA2) + meshAutoIA.Position);
                }

                colision.colisionEntreAutos(obbsAuto, obbsOtroAuto, jugador, auto, autoIA, autoMesh, meshAutoIA, elapsedTime);

                //Cosas sobre derrape
                int direcGiroDerrape = 0;

                if (auto.velocidad > 1500 && (jugador.estaGirandoDerecha() || jugador.estaGirandoIzquierda()))
                {
                    if (jugador.estaGirandoIzquierda())
                    {
                        direcGiroDerrape = -1;
                    }
                    else if (jugador.estaGirandoDerecha())
                    {
                        direcGiroDerrape = 1;
                    }

                    autoMesh.Rotation = new Vector3(0f, auto.rotacion + (direcGiroDerrape * anguloDerrape), 0f);
                    oBBAuto.setRotation(new Vector3(autoMesh.Rotation.X, autoMesh.Rotation.Y + (direcGiroDerrape * anguloDerrape / 2), autoMesh.Rotation.Z));


                    if (anguloDerrape <= anguloMaximoDeDerrape)
                    {
                        anguloDerrape += velocidadDeDerrape * elapsedTime;
                    }
                }
                else
                {
                    direcGiroDerrape = 0;
                    anguloDerrape    = 0;
                }
                //Fin derrape

                //Posiciono las ruedas
                for (int i = 0; i < 4; i++)
                {
                    float ro, alfa_rueda;
                    float posicion_x;
                    float posicion_y;
                    ro = FastMath.Sqrt(dx[i] * dx[i] + dy[i] * dy[i]);

                    alfa_rueda = FastMath.Asin(dx[i] / ro);
                    if (i == 0 || i == 2)
                    {
                        alfa_rueda += FastMath.PI;
                    }
                    posicion_x = FastMath.Sin(alfa_rueda + auto.rotacion + (anguloDerrape * direcGiroDerrape)) * ro;
                    posicion_y = FastMath.Cos(alfa_rueda + auto.rotacion + (anguloDerrape * direcGiroDerrape)) * ro;

                    ruedas[i].Position = (new Vector3(posicion_x, 15.5f, posicion_y) + autoMesh.Position);
                    //Si no aprieta para los costados, dejo la rueda derecha (por ahora, esto se puede modificar)
                    if (input.keyDown(Key.Left) || input.keyDown(Key.A) || input.keyDown(Key.Right) || input.keyDown(Key.D))
                    {
                        ruedas[i].Rotation = new Vector3(rotacionVertical, auto.rotacion + auto.rotarRueda(i) + (anguloDerrape * direcGiroDerrape), 0f);
                    }
                    else
                    {
                        ruedas[i].Rotation = new Vector3(rotacionVertical, auto.rotacion + (anguloDerrape * direcGiroDerrape), 0f);
                    }
                }

                //comienzo humo
                float rohumo, alfa_humo;
                float posicion_xhumo;
                float posicion_yhumo;
                rohumo = FastMath.Sqrt(-19f * -19f + 126f * 126f);

                alfa_humo      = FastMath.Asin(-19f / rohumo);
                posicion_xhumo = FastMath.Sin(alfa_humo + auto.rotacion + (anguloDerrape * direcGiroDerrape)) * rohumo;
                posicion_yhumo = FastMath.Cos(alfa_humo + auto.rotacion + (anguloDerrape * direcGiroDerrape)) * rohumo;

                humo.Position = (new Vector3(posicion_xhumo, 15.5f, posicion_yhumo) + autoMesh.Position);
                //Si no aprieta para los costados, dejo la rueda derecha (por ahora, esto se puede modificar)
                if (input.keyDown(Key.Left) || input.keyDown(Key.A) || input.keyDown(Key.Right) || input.keyDown(Key.D))
                {
                    humo.Rotation = new Vector3(0f, auto.rotacion + (anguloDerrape * direcGiroDerrape), 0f);
                }
                else
                {
                    humo.Rotation = new Vector3(0f, auto.rotacion + (anguloDerrape * direcGiroDerrape), 0f);
                }
                //fin de humo
                fuego.Position = humo.Position;
                fuego.Rotation = humo.Rotation;
                //fin fuego

                cantidadDeNitro += 0.5f * elapsedTime;
                cantidadDeNitro  = FastMath.Min(cantidadDeNitro, 100f);
                if (auto.nitro)
                {
                    cantidadDeNitro -= 7 * elapsedTime;
                    cantidadDeNitro  = FastMath.Max(cantidadDeNitro, 0f);
                    if (cantidadDeNitro > 1)
                    {
                        humo.Enabled  = false;
                        fuego.Enabled = false;
                    }
                }
                else
                {
                    humo.Enabled  = false;
                    fuego.Enabled = false;
                }
                tiempoHumo   += elapsedTime;
                humo.UVOffset = new Vector2(0.9f, tiempoHumo);
                humo.updateValues();
                fuego.UVOffset = new Vector2(0.9f, tiempoHumo);
                fuego.updateValues();

                if (tiempoHumo > 50f)
                {
                    tiempoHumo = 0f;
                }
                autoMeshPrevX = autoMesh.Position.X;
                autoMeshPrevZ = autoMesh.Position.Z;

                //Lineas de Frenado
                if (jugador.estaFrenandoDeMano())
                {
                    lineaDeFrenado[0].addTrack(new Vector3(ruedaDerechaDelanteraMesh.Position.X, 0, ruedaDerechaDelanteraMesh.Position.Z));
                    lineaDeFrenado[1].addTrack(new Vector3(ruedaDerechaTraseraMesh.Position.X, 0, ruedaDerechaTraseraMesh.Position.Z));
                    lineaDeFrenado[2].addTrack(new Vector3(ruedaIzquierdaDelanteraMesh.Position.X, 0, ruedaIzquierdaDelanteraMesh.Position.Z));
                    lineaDeFrenado[3].addTrack(new Vector3(ruedaIzquierdaTraseraMesh.Position.X, 0, ruedaIzquierdaTraseraMesh.Position.Z));
                }
                if (jugador.dejoDeFrenarDeMano())
                {
                    for (int i = 0; i < lineaDeFrenado.Length; i++)
                    {
                        lineaDeFrenado[i].endTrack();
                    }
                }

                for (int i = 0; i < lineaDeFrenado.Length; i++)
                {
                    lineaDeFrenado[i].render();
                    lineaDeFrenado[i].pasoDelTiempo(elapsedTime);
                }

                //Dibujo el reflejo de la luz en el auto
                reflejo.Render();

                //////Camara///////

                if (jugador.estaMirandoHaciaAtras())
                {
                    GuiController.Instance.ThirdPersonCamera.setCamera(autoMesh.Position, 200, -500);
                    GuiController.Instance.ThirdPersonCamera.Target    = autoMesh.Position;
                    GuiController.Instance.ThirdPersonCamera.RotationY = auto.rotacion;
                }
                else
                {
                    coheficienteCamara = jugador.verSiCambiaCamara();
                    GuiController.Instance.ThirdPersonCamera.setCamera(autoMesh.Position, 100 + (coheficienteCamara), 900 - (coheficienteCamara) * 4);
                    GuiController.Instance.ThirdPersonCamera.Target    = autoMesh.Position;
                    GuiController.Instance.ThirdPersonCamera.RotationY = auto.rotacion;
                }

                //La camara no rota exactamente a la par del auto, hay un pequeño retraso
                //GuiController.Instance.ThirdPersonCamera.RotationY += 5 * (auto.rotacion - prevCameraRotation) * elapsedTime;
                //Ajusto la camara a menos de 360 porque voy a necesitar hacer calculos entre angulos
                while (prevCameraRotation > 360)
                {
                    prevCameraRotation -= 360;
                }
                prevCameraRotation = GuiController.Instance.ThirdPersonCamera.RotationY;

                ///////Musica/////////
                jugador.verSiModificaMusica(musica);

                //Dibujar objeto principal
                //Siempre primero hacer todos los cálculos de lógica e input y luego al final dibujar todo (ciclo update-render)
                foreach (TgcMesh mesh in scenePista.Meshes)
                {
                    mesh.Enabled = (TgcCollisionUtils.classifyFrustumAABB(GuiController.Instance.Frustum, mesh.BoundingBox) != TgcCollisionUtils.FrustumResult.OUTSIDE);
                }
                if (motionBlurFlag)
                {
                    motionBlur.update(elapsedTime);
                    motionBlur.motionBlurRender(elapsedTime, HighResolutionTimer.Instance.FramesPerSecond, auto.velocidad, 0);
                }
                else
                {
                    foreach (TgcMesh mesh in scenePista.Meshes)
                    {
                        mesh.Technique = "DefaultTechnique";
                        mesh.render();
                    }
                }

                //Mostrar al auto IA
                meshAutoIA.render();

                //Muestro el punto siguiente
                trayecto[0].render();
                //mostrar el auto manejado por el humano
                autoMesh.render();

                for (int i = 0; i < 4; i++)
                {
                    ruedas[i].render();
                }

                humo.render();
                fuego.render();

                //Colision con puntos de control, tanto de persona como IA
                for (int i = 0; i < trayecto.Count; i++)
                {
                    //Pregunto si colisiona con un punto de control activado. Lo sé, feo.
                    if ((i == 0) && TgcCollisionUtils.testPointCylinder(oBBAuto.Position, trayecto[i].BoundingCylinder))
                    {
                        TgcCylinder cilindroModificado = new TgcCylinder(trayecto[i].Center, 130, 30);

                        if (contadorDeActivacionesDePuntosDeControl != (posicionesPuntosDeControl.Count * 3))
                        {
                            trayecto.RemoveAt(i);
                            trayecto.Add(cilindroModificado);
                            contadorDeActivacionesDePuntosDeControl++;
                            textPuntosDeControlAlcanzados.Text = "Puntos De Control Alcanzados = " + contadorDeActivacionesDePuntosDeControl.ToString();
                            textTiempo.Text = (Convert.ToDouble(textTiempo.Text) + 3).ToString();
                        }
                        else
                        {
                            gano             = true;
                            textGanaste.Text = "Ganaste y obtuviste un puntaje de  " + textTiempo.Text + " puntos";
                            textGanaste.render();
                            auto.estatico();
                            //Para el IA
                            autoIA.estatico();
                        }
                    }
                }
                for (int i = 0; i < trayectoDeIA.Count; i++)
                {
                    //Pregunto si colisiona con un punto de control activado
                    if ((i == 0) && TgcCollisionUtils.testPointCylinder(meshAutoIA.Position, trayectoDeIA[i].BoundingCylinder))
                    {
                        TgcCylinder cilindroModificado = new TgcCylinder(trayectoDeIA[i].Center, 130, 30);

                        if (contadorDeActivacionesDePuntosDeControlDeIA != (posicionesPuntosDeControlDeIA.Count * 3))
                        {
                            trayectoDeIA.RemoveAt(i);
                            trayectoDeIA.Add(cilindroModificado);
                            contadorDeActivacionesDePuntosDeControlDeIA++;
                        }
                        else
                        {
                            gano             = true;
                            textGanaste.Text = "Ganó la máquina :P  ";
                            textGanaste.render();
                            //Para el IA
                            autoIA.estatico();
                            auto.estatico();
                        }
                    }
                }

                textPosicionDelAutoActual.Text = autoMesh.Position.ToString();

                //Renderizar los tres textos

                textoVelocidad.mostrarVelocidad(auto.velocidad / 10).render(); //renderiza la velocidad

                textPuntosDeControlAlcanzados.render();
                textPosicionDelAutoActual.render();

                //Cosas del tiempo
                tiempo.incrementarTiempo(this, elapsedTime, (bool)GuiController.Instance.Modifiers["jugarConTiempo"]);

                //Actualizo y dibujo el relops
                if ((bool)GuiController.Instance.Modifiers["jugarConTiempo"])
                {
                    if ((DateTime.Now.Subtract(this.horaInicio).TotalSeconds) > segundosAuxiliares)
                    {
                        if (Convert.ToDouble(textTiempo.Text) == 0)
                        {
                            textPerdiste.Text = "Perdiste y lograste " + contadorDeActivacionesDePuntosDeControl.ToString() + " puntos de control";
                            textPerdiste.render();
                            auto.estatico();
                            //Para el IA
                            autoIA.estatico();
                        }
                        else if (gano == true)
                        {
                        }
                        else
                        {
                            this.textTiempo.Text = (Convert.ToDouble(textTiempo.Text) - 1).ToString();
                            segundosAuxiliares++;
                        }
                    }
                }
                emisorHumo.update(elapsedTime, GuiController.Instance.CurrentCamera.getLookAt(), auto.rotacion, autoMesh.Position, anguloDerrape, direcGiroDerrape, auto.nitro && (cantidadDeNitro > 1), auto.velocidad);
                emisorHumo.render(GuiController.Instance.CurrentCamera.getPosition());
                textTiempo.render();
                stringTiempo.render();
                contadorDeFrames++;

                hud.render(auto.velocidad, cantidadDeNitro);
            }//cierra el if de que no esta en pantalla inicio
            textFPS.Text = "            FPS: " + HighResolutionTimer.Instance.FramesPerSecond.ToString();
            textFPS.render();
        }
Exemple #17
0
        public override void render(float elapsedTime)
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

            //Tomar tracking de kinect
            TgcKinectSkeletonData data = tgcKinect.update();

            if (data.Active)
            {
                //Render de esqueleto
                tgcKinect.DebugSkeleton.render(data.Current.KinectSkeleton);

                if (Vector3.Length(data.Current.CenterPos - sceneCenter) <= 30f)
                {
                    sceneCenterBox.Color = Color.Red;
                    sceneCenterBox.updateValues();

                    //Analizar gestos
                    Gesture gesture;
                    if (gestureAnalizer.analize(data, out gesture))
                    {
                        switch (gesture.Type)
                        {
                        case GestureType.OpenLeft:
                            if (door.validateGesture(gesture))
                            {
                                door.open();
                            }
                            break;

                        case GestureType.OpenRight:
                            if (door.validateGesture(gesture))
                            {
                                door.close();
                            }
                            break;
                        }
                    }
                }
                else
                {
                    sceneCenterBox.Color = Color.Blue;
                    sceneCenterBox.updateValues();
                }
            }



            //Dibujar puerta
            door.update();
            door.Mesh.render();

            //Dibujar BoundingSphere de manos del esqueleto
            data.Current.RightHandSphere.render();
            data.Current.LeftHandSphere.render();

            //Dibujar mueble
            mueble.render();

            sceneBounds.render();
            sceneCenterBox.render();
        }
        public override void Update()
        {
            PreUpdate();
            var velocidadCaminar = VELOCIDAD_DESPLAZAMIENTO * ElapsedTime;

            //Calcular proxima posicion de personaje segun Input
            var moving   = false;
            var movement = new Vector3(0, 0, 0);

            //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.move(movement);
            }
            //Hacer que la camara siga al personaje en su nueva posicion
            camaraInterna.Target = mesh.Position;

            //Detectar colision con triangulo
            if (TgcCollisionUtils.testTriangleAABB(triangle[0].Position, triangle[1].Position, 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);
            }
        }
Exemple #19
0
        /// <summary>
        /// Construir caja
        /// </summary>
        public override void doCreation()
        {
            TgcD3dInput input = GuiController.Instance.D3dInput;

            switch (currentCreatingState)
            {
            case CreatingBoxState.DraggingSize:

                //Si hacen clic con el mouse, ver si hay colision con el suelo
                if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    //Determinar el size en XZ del box
                    Vector3 collisionPoint = Control.Grid.getPicking();

                    //Obtener extremos del rectángulo de selección
                    Vector3 min = Vector3.Minimize(initSelectionPoint, collisionPoint);
                    Vector3 max = Vector3.Maximize(initSelectionPoint, collisionPoint);
                    min.Y = initSelectionPoint.Y;
                    max.Y = initSelectionPoint.Y + 0.2f;

                    //Configurar BOX
                    mesh.setExtremes(min, max);
                    mesh.updateValues();
                }
                //Solto el clic del mouse, pasar a configurar el Height del box
                else if (input.buttonUp(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    //Tiene el tamaño minimo tolerado
                    Vector3 size = mesh.BoundingBox.calculateSize();
                    if (size.X > 1 && size.Z > 1)
                    {
                        currentCreatingState  = CreatingBoxState.DraggingHeight;
                        creatingBoxInitMouseY = input.Ypos;
                    }
                    //Sino, descartar
                    else
                    {
                        Control.CurrentState = MeshCreatorControl.State.CreatePrimitiveSelected;
                        mesh.dispose();
                        mesh = null;
                    }
                }

                break;

            case CreatingBoxState.DraggingHeight:

                //Si presiona clic, terminar de configurar la altura y generar box definitivo
                if (input.buttonPressed(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    //Guardar size original del Box para hacer Scaling
                    originalSize = mesh.BoundingBox.calculateSize();

                    //Dejar cargado para que se pueda crear un nuevo box
                    Control.CurrentState      = MeshCreatorControl.State.CreatePrimitiveSelected;
                    Control.CreatingPrimitive = new BoxPrimitive(Control);

                    //Agregar box a la lista de modelos
                    Control.addMesh(this);

                    //Seleccionar Box
                    Control.SelectionRectangle.clearSelection();
                    Control.SelectionRectangle.selectObject(this);
                    Control.updateModifyPanel();
                }
                //Determinar altura en base a la posicion Y del mouse
                else
                {
                    float heightY         = creatingBoxInitMouseY - input.Ypos;
                    float adjustedHeightY = MeshCreatorUtils.getMouseIncrementHeightSpeed(Control.Camera, this.BoundingBox, heightY);

                    Vector3 min = mesh.BoundingBox.PMin;
                    min.Y = initSelectionPoint.Y;
                    Vector3 max = mesh.BoundingBox.PMax;
                    max.Y = initSelectionPoint.Y + adjustedHeightY;

                    //Configurar BOX
                    mesh.setExtremes(min, max);
                    mesh.updateValues();
                }

                break;
            }
        }
Exemple #20
0
        /// <summary>
        /// Método que se llama una sola vez,  al principio cuando se ejecuta el ejemplo.
        /// Escribir aquí todo el código de inicialización: cargar modelos, texturas, modifiers, uservars, etc.
        /// Borrar todo lo que no haga falta
        /// </summary>
        public override void init()
        {
            EjemploAlumno.Instance = this;

            //GuiController.Instance: acceso principal a todas las herramientas del Framework

            //Device de DirectX para crear primitivas
            Device d3dDevice = GuiController.Instance.D3dDevice;

            //Carpeta de archivos Media del alumno
            string alumnoMediaFolder = GuiController.Instance.AlumnoEjemplosMediaDir;


            //Terreno
            currentHeightmap = GuiController.Instance.AlumnoEjemplosMediaDir + "Heightmap3.jpg";
            currentTexture   = GuiController.Instance.AlumnoEjemplosMediaDir + "TerrainTexture3.jpg";

            terrain = new TerrenoSimple();
            terrain.loadHeightmap(currentHeightmap, currentScaleXZ, currentScaleY, new Vector3(0, -125, 0));
            terrain.loadTexture(currentTexture);

            //Agua
            agua = new TerrenoSimple();
            agua.loadHeightmap(GuiController.Instance.AlumnoEjemplosMediaDir + "18_vertex_texture_02.jpg", 50f, 0.5f, new Vector3(0, -125, 0));
            agua.loadTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "4141-diffuse.jpg");
            agua.AlphaBlendEnable = true;
            //heightOlas = agua.heightOlas;

            //Modifier
            GuiController.Instance.Modifiers.addFloat("heightOlas", 10, 50, 40);

            //Estado
            EjemploAlumno.Instance.estado = EstadoDelJuego.SinEmpezar;
            menu = new Menu();

            // Crear SkyBox:
            skyBox        = new TgcSkyBox();
            skyBox.Center = new Vector3(0, 0, 0);
            skyBox.Size   = new Vector3(12000, 12000, 12000);
            skyboxSoleado(skyBox);

            skyBoundingBox                  = new TgcBox();
            skyBoundingBox.Size             = skyBox.Size;
            skyBoundingBox.Position         = skyBox.Center;
            skyBoundingBox.AlphaBlendEnable = true;
            skyBoundingBox.updateValues();

            lloviendo = false;

            //Cargar meshes
            TgcViewer.Utils.TgcSceneLoader.TgcSceneLoader loader = new TgcViewer.Utils.TgcSceneLoader.TgcSceneLoader();
            TgcViewer.Utils.TgcSceneLoader.TgcScene       scene  = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Meshes\\Vehiculos\\Canoa\\Canoa-TgcScene.xml");

            meshShip = scene.Meshes[0];
            meshShip.setColor(Color.Chocolate);

            scene = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Meshes\\Vehiculos\\Canoa\\Canoa-TgcScene.xml");

            meshes.Add(meshShip);

            meshShipContrincante = scene.Meshes[0];
            meshShipContrincante.setColor(Color.BlueViolet);
            meshes.Add(meshShipContrincante);

            scene      = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Meshes\\Armas\\Canon\\Canon.max-TgcScene.xml");
            meshCanion = scene.Meshes[0];
            meshes.Add(meshCanion);

            scene = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Meshes\\Armas\\Canon\\Canon.max-TgcScene.xml");
            meshCanionContrincante = scene.Meshes[0];
            meshes.Add(meshCanionContrincante);

            //Shader
            effect                = TgcShaders.loadEffect(alumnoMediaFolder + "shader agua.fx");
            agua.Effect           = effect;
            agua.Technique        = "RenderScene";
            time                  = 0;
            agua.AlphaBlendEnable = true;

            efectoSombra = TgcShaders.loadEffect(alumnoMediaFolder + "shader agua.fx");


            //Creaciones
            ship             = new Ship(POS_SHIP, meshShip, new Canion(POS_SHIP, 5, meshCanion, true));
            shipContrincante = new EnemyShip(ship, POS_CONTRINCANTE, meshShipContrincante, new Canion(POS_CONTRINCANTE, 5, meshCanionContrincante, false));

            mainCamera = new MainCamera(ship);

            //Crear caja para indicar ubicacion de la luz
            lightMesh = TgcBox.fromSize(new Vector3(20, 20, 20), Color.Yellow);
        }