Exemple #1
0
        /// <summary>
        ///     Actualizar parámetros del plano en base a los valores configurados
        /// </summary>
        public void updateValues()
        {
            var vertices = new CustomVertex.PositionColored[6];

            //Crear un Quad con dos triángulos sobre XZ con normal default (0, 1, 0)
            var min = new TGCVector3(-Size.X / 2, 0, -Size.Y / 2);
            var max = new TGCVector3(Size.X / 2, 0, Size.Y / 2);
            var c   = Color.ToArgb();

            vertices[0] = new CustomVertex.PositionColored(min, c);
            vertices[1] = new CustomVertex.PositionColored(min.X, 0, max.Z, c);
            vertices[2] = new CustomVertex.PositionColored(max, c);

            vertices[3] = new CustomVertex.PositionColored(min, c);
            vertices[4] = new CustomVertex.PositionColored(max, c);
            vertices[5] = new CustomVertex.PositionColored(max.X, 0, min.Z, c);

            //Obtener matriz de rotacion respecto de la normal del plano
            Normal.Normalize();
            var angle        = FastMath.Acos(TGCVector3.Dot(ORIGINAL_DIR, Normal));
            var axisRotation = TGCVector3.Cross(ORIGINAL_DIR, Normal);

            axisRotation.Normalize();
            var t = TGCMatrix.RotationAxis(axisRotation, angle) * TGCMatrix.Translation(Center);

            //Transformar todos los puntos
            for (var i = 0; i < vertices.Length; i++)
            {
                vertices[i].Position = TGCVector3.TransformCoordinate(TGCVector3.FromVector3(vertices[i].Position), t);
            }

            //Cargar vertexBuffer
            vertexBuffer.SetData(vertices, 0, LockFlags.None);
        }
Exemple #2
0
        /// <summary>
        ///     Calcular normal del Triángulo
        /// </summary>
        /// <returns>Normal (esta normalizada)</returns>
        public TGCVector3 computeNormal()
        {
            var n = TGCVector3.Cross(B - A, C - A);

            n.Normalize();
            return(n);
        }
Exemple #3
0
        public static void updateObbFromSegment(TgcBoundingOrientedBox obb, TGCVector3 a, TGCVector3 b, float thickness)
        {
            var lineDiff   = b - a;
            var lineLength = lineDiff.Length();
            var lineVec    = TGCVector3.Normalize(lineDiff);

            //Obtener angulo y vector de rotacion
            var upVec        = TGCVector3.Up;
            var angle        = FastMath.Acos(TGCVector3.Dot(upVec, lineVec));
            var axisRotation = TGCVector3.Cross(upVec, lineVec);

            axisRotation.Normalize();

            //Obtener matriz de rotacion para este eje y angulo
            var rotM = TGCMatrix.RotationAxis(axisRotation, angle);

            //Actualizar orientacion de OBB en base a matriz de rotacion
            obb.Orientation[0] = new TGCVector3(rotM.M11, rotM.M12, rotM.M13);
            obb.Orientation[1] = new TGCVector3(rotM.M21, rotM.M22, rotM.M23);
            obb.Orientation[2] = new TGCVector3(rotM.M31, rotM.M32, rotM.M33);

            //Actualizar extent de OBB segun el thickness del segmento
            obb.Extents = new TGCVector3(thickness, lineLength / 2, thickness);

            //Actualizar centro del OBB segun centro del segmento
            obb.Center = a + TGCVector3.Scale(lineDiff, 0.5f);

            //Regenerar OBB
            obb.updateValues();
        }
        public override void Update()
        {
            currentPick = PerformPicking();

            if (PickingInsideSphere())
            {
                if (dragging)
                {
                    TGCVector3 normalizedTo = currentPick;
                    normalizedTo.Normalize();

                    var cross           = TGCVector3.Cross(normalizedFrom, normalizedTo);
                    var newRotation     = TGCQuaternion.RotationAxis(cross, FastMath.Acos(TGCVector3.Dot(normalizedFrom, normalizedTo)));
                    var currentRotation = TGCQuaternion.Multiply(stacked, newRotation);

                    shark.Transform = baseSharkTransform * TGCMatrix.RotationTGCQuaternion(currentRotation);

                    if (Input.buttonUp(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                    {
                        stacked         = currentRotation;
                        shark.Transform = baseSharkTransform * TGCMatrix.RotationTGCQuaternion(stacked);
                        dragging        = false;
                    }
                }
                else if (Input.buttonPressed(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    dragging       = true;
                    fromDrag       = currentPick;
                    normalizedFrom = TGCVector3.Normalize(fromDrag);
                }
            }

            UpdateArrows();
        }
        public void renderStaminaBar()
        {
            //dibujo un poligono enfrente de la camara
            //es medio choto porque lo hago pasar por todas las projecciones y eso, seria mejor dibujar un sprite directamente
            //pero tgccore parece no tener nada de eso y va a ser mas rapido programar esto que ver como renderizar un sprite

            var bar    = new TgcConvexPolygon();
            var vertex = new TGCVector3[4];

            var forward    = g.camera.cameraRotatedTarget * 5f;
            var forwardPos = g.camera.eyePosition + forward;

            var right = TGCVector3.Cross(g.camera.UpVector, forward) * .1f;
            var down  = TGCVector3.Cross(right, forward) * .1f;

            forwardPos += right * 4f + down * 7.5f;


            var lenght = g.camera.stamina / 5000f * 1.5f;

            vertex[0] = forwardPos;
            vertex[1] = forwardPos + right * lenght;
            vertex[2] = forwardPos + right * lenght + down * 0.3f;
            vertex[3] = forwardPos + down * 0.3f;

            bar.BoundingVertices = vertex;
            bar.Color            = Color.White;
            bar.updateValues();

            bar.Render();
        }
        public TGCMatrix CalcularMatrizUp(TGCVector3 Pos, TGCVector3 Scale, TGCVector3 Dir, TGCVector3 VUP)
        {
            var matWorld = TGCMatrix.Scaling(Scale);
            // determino la orientacion
            var U = TGCVector3.Cross(VUP, Dir);

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

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

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

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

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

            // traslado
            matWorld = matWorld * TGCMatrix.Translation(Pos);
            return(matWorld);
        }
        private void UpdateArrows()
        {
            if (dragging)
            {
                toArrow.PEnd = currentPick;
                toArrow.updateValues();

                var cross = TGCVector3.Cross(fromDrag, currentPick);
                cross.Normalize();
                cross.Scale(-radius);
                crossArrow.PEnd = cross;
                crossArrow.updateValues();
            }
            else
            {
                fromArrow.PEnd = currentPick;
                fromArrow.updateValues();

                toArrow.PEnd = TGCVector3.Empty;
                toArrow.updateValues();

                toArrow.PEnd = TGCVector3.Empty;
                toArrow.updateValues();
            }
        }
Exemple #8
0
        /// <summary>
        ///     Moves the camera by dx world units to the left or right; dy
        ///     world units upwards or downwards; and dz world units forwards
        ///     or backwards.
        /// </summary>
        private void move(float dx, float dy, float dz)
        {
            var        auxEye = eye;
            TGCVector3 forwards;

            // Calculate the forwards direction. Can't just use the camera's local
            // z axis as doing so will cause the camera to move more slowly as the
            // camera's view approaches 90 degrees straight up and down.
            forwards = TGCVector3.Cross(xAxis, WORLD_YAXIS);
            forwards.Normalize();

            auxEye += xAxis * dx;
            auxEye += WORLD_YAXIS * dy;
            auxEye += forwards * dz;
            if (FpsModeEnable)
            {
                HeadPosition += dy;

                float y;
                if (Terrain.interpoledHeight(auxEye.X, auxEye.Z, out y))
                {
                    auxEye.Y = y;
                    auxEye  += HeadPosition * WORLD_YAXIS;
                }
            }
            setPosition(auxEye);
        }
        public void Update(float elapsedTime)
        {
            TGCQuaternion rotationX  = TGCQuaternion.RotationAxis(new TGCVector3(0.0f, 1.0f, 0.0f), Geometry.DegreeToRadian(90f /* + anguloEntreVectores*15*/));
            TGCVector3    PosicionA  = posicionInicial;
            TGCVector3    PosicionB  = jugador.GetPosicion();
            TGCVector3    DireccionA = new TGCVector3(0, 0, -1);
            TGCVector3    DireccionB = PosicionB - PosicionA;

            if (DireccionB.Length() >= 15f && PosicionA.Z > PosicionB.Z + 10f)
            {
                DireccionB.Normalize();
                // anguloEntreVectores = (float)Math.Acos(TGCVector3.Dot(DireccionA, DireccionB));

                var cross       = TGCVector3.Cross(DireccionA, DireccionB);
                var newRotation = TGCQuaternion.RotationAxis(cross, FastMath.Acos(TGCVector3.Dot(DireccionA, DireccionB)));
                quaternionAuxiliar = rotationX * newRotation;
                mainMesh.Transform = baseScaleRotation *
                                     TGCMatrix.RotationTGCQuaternion(rotationX * newRotation) *
                                     baseQuaternionTranslation;
            }
            else
            {
                mainMesh.Transform = baseScaleRotation *
                                     TGCMatrix.RotationTGCQuaternion(quaternionAuxiliar) *
                                     baseQuaternionTranslation;
            }
            //codigo de prueba------
            tiempo += .1f + elapsedTime;
            if (tiempo > 15f)
            {
                Disparar(PosicionB);
                tiempo = 0f;
            }
            //--------
        }
Exemple #10
0
        /// <summary>
        ///     Crear un nuevo Frustum acotado usando como base el portal recorado.
        ///     La cantidad de planos del nuevo Frustum no tiene por qué ser 6.
        ///     Depende de la forma que haya quedado en el portal recortado.
        /// </summary>
        private TGCPlane[] createFrustumPlanes(TGCVector3 cameraPos, TGCPlane[] currentFrustumPlanes, TGCVector3[] portalVerts,
                                               TGCPlane portalPlane)
        {
            //Hay un plano por cada vértice del polígono + 2 por el near y far plane
            var frustumPlanes = new TGCPlane[2 + portalVerts.Length];

            //Cargar near y far plane originales
            //TODO: habria que usar el portalPlane para acercar el NearPlane hasta el portal
            frustumPlanes[0] = currentFrustumPlanes[0];
            frustumPlanes[1] = currentFrustumPlanes[1];

            //Generar los planos laterales en base al polígono remanente del portal
            //Vamos tomando de a dos puntos del polígono + la posición de la cámara y creamos un plano
            var lastP = portalVerts[portalVerts.Length - 1];

            for (var i = 0; i < portalVerts.Length; i++)
            {
                var nextP = portalVerts[i];

                //Armar el plano para que la normal apunte hacia adentro del Frustum
                var a     = lastP - cameraPos;
                var b     = nextP - cameraPos;
                var plane = TGCPlane.FromPointNormal(cameraPos, TGCVector3.Cross(b, a));

                //Guardar después del near y far plane
                frustumPlanes[i + 2] = plane;

                lastP = nextP;
            }

            return(frustumPlanes);
        }
        private TGCQuaternion QuaternionDireccion(TGCVector3 direccionDisparoNormalizado)
        {
            TGCVector3    DireccionA  = new TGCVector3(0, 0, -1);
            TGCVector3    cross       = TGCVector3.Cross(DireccionA, direccionDisparoNormalizado);
            TGCQuaternion newRotation = TGCQuaternion.RotationAxis(cross, FastMath.Acos(TGCVector3.Dot(DireccionA, direccionDisparoNormalizado)));

            return(newRotation);
        }
        private float RotationYSign()
        {
            var bodyToSkyboxCenterVector = TGCVector3.Normalize(Skybox.GetSkyboxCenter() - GetMeshPosition());
            var actualDirector           = -1 * director;
            var normalVector             = TGCVector3.Cross(actualDirector, bodyToSkyboxCenterVector);

            return(normalVector.Y > 0 ? 1 : -1);
        }
Exemple #13
0
 private void updateMesh()
 {
     mesh.Transform =
         TGCMatrix.RotationAxis(TGCVector3.Cross(lookAt, lookin),
                                -(float)Math.Acos(TGCVector3.Dot(lookAt, lookin)))
         * TGCMatrix.Scaling(TGCVector3.One * 30)
         * TGCMatrix.Translation(pos);
 }
Exemple #14
0
        public override TGCVector3 GetShootRotation()
        {
            float      angle  = GlobalConcepts.GetInstance().AngleBetweenVectors(new TGCVector3(0, 0, 1), direction);
            TGCVector3 result = TGCVector3.Cross(direction, new TGCVector3(0, 0, 1));

            angle = (result.Y > 0) ? -angle : angle;
            return(new TGCVector3(FastMath.PI_HALF, angle, 0));
        }
        /// <summary>
        /// Devuelve la rotacion que se debe aplicar a la matriz de transformacion para que la entidad apunte hacia una direccion.
        /// </summary>
        /// <param name="lookDir">Vector normalizado que define la direccion a la que debe mirar la entidad.</param>
        private void LookAt(TGCVector3 lookDir)
        {
            float      angle     = FastMath.Acos(TGCVector3.Dot(defaultLookDir, lookDir));
            TGCVector3 rotVector = TGCVector3.Cross(defaultLookDir, lookDir);

            rotVector.Z = 0;

            rotation = TGCQuaternion.RotationAxis(rotVector, angle);
        }
Exemple #16
0
        public void renderForShadow()
        {
            var lightObj = new TGCVector3(g.mostro.lightObjObj.X, g.mostro.flyHeight, g.mostro.lightObjObj.Y);
            var lightPos = g.mostro.pos;

            var eyeDir = lightObj - lightPos;

            eyeDir.Y = 0;//ignorar y
            eyeDir.Normalize();

            var ortogDir = TGCVector3.Cross(eyeDir, TGCVector3.Up);

            float distFactorForward = 0.707f;
            float distFactorSide    = 0.3f;//para meter chunks que esten lo suficientemente cerca al costado



            bool sngx = lightPos.X <= lightObj.X;
            bool sngz = lightPos.Z <= lightObj.Z;// <= aca y < en el bucle para que de distinto si justo son iguales

            for (int i = 0; ; i++)
            {
                var along = lightPos + eyeDir * i * chunkLen * distFactorForward;

                if ((along.X < lightObj.X) != sngx &&
                    (along.Z < lightObj.Z) != sngz)//creo que sería seguro probar con un eje nomas
                {
                    break;
                }
                for (int j = -1; j <= 1; j++)
                {
                    var pos = along
                              + ortogDir * chunkLen * j * distFactorSide;

                    Chunk c = fromCoordinates(pos);
                    if (c != null)
                    {
                        c.renderForShadow();
                    }
                }
            }

            //traigo los que estan cerca de la camara tambien
            var index = toIndexSpace(g.camera.eyePosition, 2);

            for (int i = -2; i <= 2; i++)
            {
                for (int j = -2; j <= 2; j++)
                {
                    chunks[index.i, index.j].renderForShadow();
                }
            }


            //Console.WriteLine(chunksRendered);
        }
        public float SetDirection(TGCVector3 output, TGCVector3 normal)
        {
            float      angle  = GlobalConcepts.GetInstance().AngleBetweenVectors(normal, output);
            TGCVector3 result = TGCVector3.Cross(output, normal);

            //por la regla de la mano derecha
            angle = (result.Y < 0) ? angle + FastMath.PI : angle;
            this.Girar(angle);
            return(angle);
        }
        /// <summary>
        ///     Calcular los 8 vertices del Frustum
        ///     Basado en: http://www.lighthouse3d.com/tutorials/view-frustum-culling/geometric-approach-implementation/
        /// </summary>
        /// <param name="position"></param>
        /// <param name="lookAt"></param>
        /// <param name="aspectRatio"></param>
        /// <param name="nearDistance"></param>
        /// <param name="farDistance"></param>
        /// <param name="fieldOfViewY"></param>
        /// <returns>Los 8 vertices del Frustum</returns>
        private TGCVector3[] computeFrustumCorners(TGCVector3 position, TGCVector3 lookAt, float aspectRatio, float nearDistance,
                                                   float farDistance, float fieldOfViewY)
        {
            var corners = new TGCVector3[8];

            /*
             * (ntl)0 ---- 1(ntr)
             |      |   Near-face
             | (nbl)2 ---- 3(nbr)
             |
             | (ftl)4 ---- 5(ftr)
             |      |   Far-face
             | (fbl)6 ---- 7(fbr)
             */

            var tang = FastMath.Tan(fieldOfViewY * 0.5f);
            var nh   = nearDistance * tang;
            var nw   = nh * aspectRatio;
            var fh   = farDistance * tang;
            var fw   = fh * aspectRatio;

            // compute the Z axis of camera
            // this axis points in the opposite direction from
            // the looking direction
            var Z = TGCVector3.Subtract(position, lookAt);

            Z.Normalize();

            // X axis of camera with given "up" vector and Z axis
            var X = TGCVector3.Cross(UP_VECTOR, Z);

            X.Normalize();

            // the real "up" vector is the cross product of Z and X
            var Y = TGCVector3.Cross(Z, X);

            // compute the centers of the near and far planes
            var nc = position - Z * nearDistance;
            var fc = position - Z * farDistance;

            // compute the 4 corners of the frustum on the near plane
            corners[0] = nc + Y * nh - X * nw; //ntl
            corners[1] = nc + Y * nh + X * nw; //ntr
            corners[2] = nc - Y * nh - X * nw; //nbl
            corners[3] = nc - Y * nh + X * nw; //nbr

            // compute the 4 corners of the frustum on the far plane
            corners[4] = fc + Y * fh - X * fw; //ftl
            corners[5] = fc + Y * fh + X * fw; //ftr
            corners[6] = fc - Y * fh - X * fw; //fbl
            corners[7] = fc - Y * fh + X * fw; //fbr

            return(corners);
        }
        public TGCVector3 NormalVectorGivenXZ(float X, float Z)
        {
            float delta = 0.3f;

            InterpoledHeight(X, Z + delta, out float alturaN);
            InterpoledHeight(X, Z - delta, out float alturaS);
            InterpoledHeight(X + delta, Z, out float alturaE);
            InterpoledHeight(X - delta, Z, out float alturaO);

            TGCVector3 vectorEO = new TGCVector3(delta * 2, alturaE - alturaO, 0);
            TGCVector3 vectorNS = new TGCVector3(0, alturaN - alturaS, delta * 2);

            return(TGCVector3.Cross(vectorNS, vectorEO));
        }
Exemple #20
0
        public static TGCVector3 rotate_vector_by_quaternion(TGCVector3 v, Quaternion q)
        {
            // Extract the vector part of the quaternion
            TGCVector3 u = new TGCVector3(q.X, q.Y, q.Z);

            // Extract the scalar part of the quaternion
            float s = q.W;

            // Do the math
            var vprime = 2.0f * TGCVector3.Dot(u, v) * u
                         + (s * s - TGCVector3.Dot(u, u)) * v
                         + 2.0f * s * TGCVector3.Cross(u, v);

            return(vprime);
        }
        /// <summary>
        ///     Configura la posicion de la camara, punto de entrada para todas las camaras, con los mismos se calcula la matriz de view.
        ///     Los vectores son utilizadas por GetViewMatrix.
        /// </summary>
        /// <param name="pos">Posicion de la camara</param>
        /// <param name="lookAt">Punto hacia el cual se quiere ver</param>
        public virtual void SetCamera(TGCVector3 pos, TGCVector3 lookAt)
        {
            //Direccion efectiva de la vista.
            TGCVector3 direction = lookAt - pos;

            //Se busca el vector que es producto del (0,1,0)Up y la direccion de vista.
            TGCVector3 crossDirection = TGCVector3.Cross(TGCVector3.Up, direction);

            //El vector de Up correcto dependiendo del LookAt
            TGCVector3 finalUp = TGCVector3.Cross(direction, crossDirection);

            Position = pos;
            LookAt   = lookAt;
            UpVector = finalUp;
        }
Exemple #22
0
        private void Chase()
        {
            LookDirection = TGCVector3.Normalize(GameInstance.Player.Position - Position);

            TGCVector3    rotationAxis = TGCVector3.Cross(InitialLookDirection, LookDirection); // Ojo el orden - no es conmutativo
            TGCQuaternion rotationQuat = TGCQuaternion.RotationAxis(rotationAxis, MathExtended.AngleBetween(InitialLookDirection, LookDirection));

            TGCVector3 nextPosition = Position + LookDirection * chasingSpeed * GameInstance.ElapsedTime;

            TGCMatrix translationMatrix = TGCMatrix.Translation(nextPosition);
            TGCMatrix rotationMatrix    = TGCMatrix.RotationTGCQuaternion(rotationQuat);

            TGCMatrix nextTransform = rotationMatrix * translationMatrix;

            SimulateAndSetTransformation(nextPosition, nextTransform);
        }
        public override void Render()
        {
            PreRender();

            // 1) Crear un vector en 3D
            var v = new TGCVector3(0, 19, -1759.21f);

            // 2) Producto escalar entre dos vectores (dot product)
            var v1        = new TGCVector3(0, 19, -1759.21f);
            var v2        = new TGCVector3(0, 19, -1759.21f);
            var dotResult = TGCVector3.Dot(v1, v2);

            // 3) Producto vectorial entre dos vectores (cross product). El orden de v1 y v2 influye en la orientacion del resultado
            var crossResultVec = TGCVector3.Cross(v1, v2);

            // 4) Distancia entre dos puntos
            var p1                = new TGCVector3(100, 200, 300);
            var p2                = new TGCVector3(1000, 2000, 3000);
            var distancia         = TGCVector3.Length(p2 - p1);
            var distanciaCuadrada = TGCVector3.LengthSq(p2 - p1);
            //Es mas eficiente porque evita la raiz cuadrada (pero te da el valor al cuadrado)

            // 5) Normalizar vector
            var norm = TGCVector3.Normalize(v1);

            // 6) Obtener el angulo que hay entre dos vectores que estan en XZ, expresion A.B=|A||B|cos(a)
            var v3    = new TGCVector3(-1, 0, 19);
            var v4    = new TGCVector3(3, 0, -5);
            var angle = FastMath.Acos(TGCVector3.Dot(TGCVector3.Normalize(v3), TGCVector3.Normalize(v4)));
            //Tienen que estar normalizados

            // 7) Tenemos un objeto que rota un cierto angulo en Y (ej: un auto) y queremos saber los componentes X,Z para donde tiene que avanzar al moverse
            var   rotacionY           = FastMath.PI_HALF;
            var   componenteX         = FastMath.Sin(rotacionY);
            var   componenteZ         = FastMath.Cos(rotacionY);
            float velocidadMovimiento = 100; //Ojo que este valor deberia siempre multiplicarse por el elapsedTime
            var   movimientoAdelante  = new TGCVector3(componenteX * velocidadMovimiento, 0, componenteZ * velocidadMovimiento);

            DrawText.drawText(
                "Este ejemplo no muestra nada por pantalla. Sino que es para leer el codigo y sus comentarios.", 5, 50,
                Color.Yellow);

            PostRender();
        }
Exemple #24
0
        public void DrawLine(TGCVector3 p0, TGCVector3 p1, TGCVector3 up, float dw, Color color)
        {
            TGCVector3 v = p1 - p0;

            v.Normalize();
            TGCVector3 n = TGCVector3.Cross(v, up);
            TGCVector3 w = TGCVector3.Cross(n, v);

            TGCVector3[] p = new TGCVector3[8];

            dw  *= 0.5f;
            p[0] = p0 - n * dw;
            p[1] = p1 - n * dw;
            p[2] = p1 + n * dw;
            p[3] = p0 + n * dw;
            for (int i = 0; i < 4; ++i)
            {
                p[4 + i] = p[i] + w * dw;
                p[i]    -= w * dw;
            }

            int[] index_buffer = { 0, 1, 2, 0, 2, 3,
                                   4, 5, 6, 4, 6, 7,
                                   0, 1, 5, 0, 5, 4,
                                   3, 2, 6, 3, 6, 7 };

            VERTEX_POS_COLOR[] pt = new VERTEX_POS_COLOR[index_buffer.Length];
            for (int i = 0; i < index_buffer.Length; ++i)
            {
                int index = index_buffer[i];
                pt[i].x     = p[index].X;
                pt[i].y     = p[index].Y;
                pt[i].z     = p[index].Z;
                pt[i].color = color.ToArgb();
            }

            // dibujo como lista de triangulos
            var device = D3DDevice.Instance.Device;

            device.VertexFormat = VertexFormats.Position | VertexFormats.Diffuse;
            device.DrawUserPrimitives(PrimitiveType.TriangleList, index_buffer.Length / 3, pt);
        }
Exemple #25
0
        public void setCamera(TGCVector3 eye, TGCVector3 target)
        {
            this.eye    = eye;
            this.target = target;

            zAxis = target - eye;
            zAxis.Normalize();

            xAxis = TGCVector3.Cross(up, zAxis);
            xAxis.Normalize();

            yAxis = TGCVector3.Cross(zAxis, xAxis);
            yAxis.Normalize();

            forward = TGCVector3.Cross(xAxis, up);
            forward.Normalize();

            rotationChanged = true;
            positionChanged = true;
        }
        public void Update(TGCVector3 cameraDirection, float elapsedTime)
        {
            float RotationStep = FastMath.PI * 2.5f * elapsedTime;

            CalculateRotationByAtack(RotationStep);
            AttackLocked = !(AttackForwardRotation <= 0) && !(AttackSideRotation <= 0);

            var localSideAxis = TGCVector3.Cross(TGCVector3.Up, cameraDirection);

            localSideAxis.Normalize();
            var        forwardOffset = cameraDirection * 43;
            var        sideOffset    = localSideAxis * 15;
            TGCVector3 newPosition   = Camera.Position + forwardOffset + sideOffset;

            Mesh.Transform = TGCMatrix.Scaling(scale) *
                             TGCMatrix.RotationYawPitchRoll(Camera.Latitude - AttackSideRotation,
                                                            Camera.Longitude + RotationXOffset - AttackForwardRotation, 0) *
                             TGCMatrix.Translation(newPosition);

            Mesh.BoundingBox.transform(Mesh.Transform);
        }
Exemple #27
0
        /// <summary>
        ///     Reconstruct the view TGCMatrix.
        /// </summary>
        private void reconstructViewTGCMatrix(bool orthogonalizeAxes)
        {
            if (orthogonalizeAxes)
            {
                // Regenerate the camera's local axes to orthogonalize them.

                zAxis.Normalize();

                yAxis = TGCVector3.Cross(zAxis, xAxis);
                yAxis.Normalize();

                xAxis = TGCVector3.Cross(yAxis, zAxis);
                xAxis.Normalize();

                viewDir = zAxis;
                LookAt  = eye + viewDir;
            }

            // Reconstruct the view TGCMatrix.

            viewTGCMatrix.M11 = xAxis.X;
            viewTGCMatrix.M21 = xAxis.Y;
            viewTGCMatrix.M31 = xAxis.Z;
            viewTGCMatrix.M41 = -TGCVector3.Dot(xAxis, eye);

            viewTGCMatrix.M12 = yAxis.X;
            viewTGCMatrix.M22 = yAxis.Y;
            viewTGCMatrix.M32 = yAxis.Z;
            viewTGCMatrix.M42 = -TGCVector3.Dot(yAxis, eye);

            viewTGCMatrix.M13 = zAxis.X;
            viewTGCMatrix.M23 = zAxis.Y;
            viewTGCMatrix.M33 = zAxis.Z;
            viewTGCMatrix.M43 = -TGCVector3.Dot(zAxis, eye);

            viewTGCMatrix.M14 = 0.0f;
            viewTGCMatrix.M24 = 0.0f;
            viewTGCMatrix.M34 = 0.0f;
            viewTGCMatrix.M44 = 1.0f;
        }
Exemple #28
0
        virtual public void Collide(Vehicle car)
        {
            var dot            = TGCVector3.Dot(car.vectorAdelante, this.outDirection);
            var modulusProduct = car.vectorAdelante.Length() * this.outDirection.Length();
            var angle          = (float)Math.Acos(dot / modulusProduct);
            var yCross         = TGCVector3.Cross(car.vectorAdelante, this.outDirection).Y;
            var giro           = (yCross > 0) ? angle : -angle;

            car.Girar(giro);
            if (!(car is ArtificialIntelligence))
            {
                Scene.GetInstance().camera.rotateY(giro);
            }
            if (car.GetVelocidadActual() < 0)
            {
                car.Girar(FastMath.PI);
                if (!(car is ArtificialIntelligence))
                {
                    Scene.GetInstance().camera.rotateY(FastMath.PI);
                }
            }
        }
Exemple #29
0
        public void render()
        {
            updateMesh();

            mesh.Effect = Meshc.actualShader;
            mesh.Effect.SetValue("type", 2);
            mesh.Technique = Meshc.actualTechnique;

            mesh.Render();

            if (GameModel.debugSqueleton)
            {
                TgcLine.fromExtremes(cPos, cPos + colDir, Color.Red).Render();
                TGCVector3 cross = TGCVector3.Cross(colDir, TGCVector3.Up);
                TgcLine.fromExtremes(cPos, cPos + cross * sidePref, Color.Green).Render();

                var lightObj    = new TGCVector3(g.mostro.lightObj.X, g.mostro.flyHeight, g.mostro.lightObj.Y);
                var lightObjObj = new TGCVector3(g.mostro.lightObjObj.X, g.mostro.flyHeight, g.mostro.lightObjObj.Y);
                TgcLine.fromExtremes(lightObj - TGCVector3.Up * 10000f, lightObj + TGCVector3.Up * 10000f, Color.Green).Render();
                TgcLine.fromExtremes(lightObjObj - TGCVector3.Up * 10000f, lightObjObj + TGCVector3.Up * 10000f, Color.Red).Render();
            }
        }
Exemple #30
0
        public int state = 0;//0 nada 1 mano derecha 2 ambas manos

        //estas variables estan para hacer la animacion de levantar la vela si es que la hago,
        //por ahora lo dejo para el final
        //TGCVector3 rightPos = new TGCVector3(-25f, -10f, -25f);
        //TGCVector3 leftPos  = new TGCVector3(0, 0, 0);

        //con los estados y si las pos.y>k se sabe todo lo necesario

        public void renderCandles()
        {
            /*
            if(rightPos.Y> k)
                //vela en campo visual, dependiendo del estado ver si poner shaders y si moverla adentro o afuera de la pantalla
            //lo mismo para la izquierda, y esta lo de pasar la vela a la otra mano si se apaga la derecha
             */

#if false
            var up = g.camera.UpVector;
#else
            var up = TGCVector3.Up;
#endif
            var forwardPos = g.camera.eyePosition + g.camera.cameraRotatedTarget * 10f;
            if (state > 0)
            {
                var rotatedPos= forwardPos 
                            + TGCVector3.Cross(g.camera.eyePosition - forwardPos, up) * .4f
                            + TGCVector3.Down * 4f;

                //Camera.Camera.cameraRotation * iria al principio, pero sacandole los elementos en y
                //o construir una matriz de rotacion segun algo
                g.map.candleMesh.Transform = TGCMatrix.Scaling(.1f, .2f, .1f) * TGCMatrix.Translation(rotatedPos);
                //lo de mirar hacia arriba y que levante la vela no fue intencional pero queda bien
                g.map.candleMesh.Render();
            }
            if (state == 2)
            {
                var rotatedPos = forwardPos
                            + TGCVector3.Cross(g.camera.eyePosition - forwardPos, up) * -.4f
                            + TGCVector3.Down * 4f;

                //Camera.Camera.cameraRotation * iria al principio, pero sacandole los elementos en y
                //o construir una matriz de rotacion segun algo
                g.map.candleMesh.Transform = TGCMatrix.Scaling(.1f, .2f, .1f) * TGCMatrix.Translation(rotatedPos);
                //lo de mirar hacia arriba y que levante la vela no fue intencional pero queda bien
                g.map.candleMesh.Render();
            }
        }