// Reset
 public void Reset()
 {
     Offset = new Vector2();
     Scale = new Vector2( 1.0f );
     Rotation = new Vector3();
     TransformMatrix = Matrix.Identity;
 }
示例#2
0
        public static double Distance2D(ref Xna.Vector3 pointA, ref Xna.Vector3 pointB)
        {
            float X = pointA.X - pointB.X;
            float Y = pointA.Y - pointB.Y;

            return(Math.Abs(Math.Sqrt(X * X + Y * Y)));
        }
示例#3
0
        public static xna.Vector3 GetPointOfStart(xna.Vector3 ball, xna.Vector3 dest)
        {
            xna.Vector3 point = new xna.Vector3(0, 0, 0);

            if (ball.X > dest.X && ball.Z > dest.Z)//球在洞的右下角
            {
                float degree = StrategyHelper.Helpers.GetAngleDegree(dest - ball);
                float rad    = xna.MathHelper.ToRadians(degree);
                rad   = (float)Math.PI + rad;
                point = new xna.Vector3(ball.X + 58 * (float)Math.Cos(rad), 0, ball.Z + 58 * (float)Math.Sin(rad));
            }
            if (ball.X > dest.X && ball.Z < dest.Z)//秋在洞的右上角
            {
                float degree = StrategyHelper.Helpers.GetAngleDegree(dest - ball);
                float rad    = xna.MathHelper.ToRadians(degree);
                rad   = (float)Math.PI - rad;
                point = new xna.Vector3(ball.X + 58 * (float)Math.Cos(rad), 0, ball.Z - 58 * (float)Math.Sin(rad));
            }
            if (ball.X < dest.X && ball.Z > dest.Z)//秋在洞的左下角
            {
                float degree = StrategyHelper.Helpers.GetAngleDegree(dest - ball);
                float rad    = xna.MathHelper.ToRadians(degree);
                rad   = -rad;
                point = new xna.Vector3(ball.X - 58 * (float)Math.Cos(rad), 0, ball.Z + 58 * (float)Math.Sin(rad));
            }
            if (ball.X < dest.X && ball.Z < dest.Z)//秋在洞的左上角
            {
                float degree = StrategyHelper.Helpers.GetAngleDegree(dest - ball);
                float rad    = xna.MathHelper.ToRadians(degree);
                point = new xna.Vector3(ball.X - 58 * (float)Math.Cos(rad), 0, ball.Z - 58 * (float)Math.Sin(rad));
            }

            return(point);
        }
示例#4
0
        private void DestroyRaycast(float length)
        {
            var     m          = Mouse.GetState();
            Vector3 startPoint = Position;
            Vector3 endPoint   = Position + (Direction * length);

            for (int i = 0; i < length * 4; i++)
            {
                Vector3 current = Vector3.Lerp(startPoint, endPoint, (i / 4f) / (length));

                // Check collision
                if (ChunkManager.CheckCollision(current) && m.LeftButton == ButtonState.Pressed && pressed == false)
                {
                    Renderer.AddDebugLine(new DebugLine(startPoint, current, Color.Red));

                    ChunkManager.RemoveBlock(current);

                    pressed = true;
                    return;
                }
                else if (m.LeftButton == ButtonState.Released && pressed == true)
                {
                    pressed = false;
                }
            }
        }
示例#5
0
 /// <summary>
 /// Crea un objeto tipo GameObject.
 /// </summary>
 /// <param name="effect">Effecto usado para dibujar.</param>
 /// <param name="engine">Clase principal del juego.</param>
 /// <param name="position">Posición del objeto.</param>
 /// <param name="size">Tamaño del objeto.</param>
 public GameObject(Engine engine, Vector3 position, float size)
     : base(engine)
 {
     this.size = size;
     color = Color.LightGray;
     this.position = position;
 }
示例#6
0
 public AudioListener()
 {
   this.Forward = Vector3.Forward;
   this.Position = Vector3.Zero;
   this.Up = Vector3.Up;
   this.Velocity = Vector3.Zero;
 }
示例#7
0
 public LocalSpace(Vector3 side, Vector3 up, Vector3 forward, Vector3 position)
 {
     _side = side;
     _up = up;
     _forward = forward;
     _position = position;
 }
示例#8
0
        public static float GetDirRad(xna.Vector3 cur, xna.Vector3 dest)
        {
            float  dirRad = 0; //接收目标对象和鱼的相对角度
            double tan    = 0; //接受正切值

            if (dest.X == cur.X)
            {                                //计算目标对象相当Fish[0]的相对角度bD,值为-PI~PI
                if (dest.Z > cur.Z)
                {
                    dirRad = (float)Math.PI / 2;
                }
                else
                {
                    dirRad = -(float)Math.PI / 2;
                }
            }
            else if (dest.X - cur.X > 0)
            {
                tan    = (dest.Z - cur.Z) / (dest.X - cur.X);
                dirRad = (float)Math.Atan(tan);
            }
            else if (dest.Z >= cur.Z)
            {
                tan    = (dest.Z - cur.Z) / (dest.X - cur.X);
                dirRad = (float)Math.PI + (float)Math.Atan(tan);
            }
            else
            {
                tan    = (dest.Z - cur.Z) / (dest.X - cur.X);
                dirRad = -(float)Math.PI + (float)Math.Atan(tan);
            }

            return(dirRad);
        }
        public StaticMeshColliderComponent(object tag, List <Microsoft.Xna.Framework.Vector3> verts, int[] indices)
        {
            if (tag != null)
            {
                Tag = tag;
            }

            ParentObject = tag as GameObject;

            List <BEPUutilities.Vector3> bepuVerts =
                MathConverter.Convert(verts.ToArray())
                .ToList();

            staticMesh = new StaticMesh(bepuVerts.ToArray(), indices, AffineTransform.Identity);
            offset     = staticMesh.WorldTransform.Translation.ToXNAVector();

            staticMesh.Tag = this.Tag;


            if (!SystemCore.PhysicsOnBackgroundThread)
            {
                SystemCore.PhysicsSimulation.Add(staticMesh);
            }
            else
            {
                SystemCore.PhysicsSimulation.SpaceObjectBuffer.Add(staticMesh);
            }
        }
示例#10
0
        public BasicEntity(ModelDefinition modelbb, MaterialEffect material, Vector3 position, double angleZ, double angleX, double angleY, Vector3 scale, MeshMaterialLibrary library = null, Entity physicsObject = null)
        {
            Id                  = IdGenerator.GetNewId();
            Name                = GetType().Name + " " + Id;
            WorldTransform      = new TransformMatrix(Matrix.Identity, Id);
            ModelDefinition     = modelbb;
            Model               = modelbb.Model;
            BoundingBox         = modelbb.BoundingBox;
            BoundingBoxOffset   = modelbb.BoundingBoxOffset;
            SignedDistanceField = modelbb.SDF;

            Material = material;
            Position = position;
            Scale    = scale;

            RotationMatrix = Matrix.CreateRotationX((float)angleX) * Matrix.CreateRotationY((float)angleY) *
                             Matrix.CreateRotationZ((float)angleZ);

            if (library != null)
            {
                RegisterInLibrary(library);
            }

            if (physicsObject != null)
            {
                RegisterPhysics(physicsObject);
            }

            WorldTransform.World        = Matrix.CreateScale(Scale) * RotationMatrix * Matrix.CreateTranslation(Position);
            WorldTransform.Scale        = Scale;
            WorldTransform.InverseWorld = Matrix.Invert(Matrix.CreateTranslation(BoundingBoxOffset * Scale) * RotationMatrix * Matrix.CreateTranslation(Position));
        }
        /// <summary>
        /// Moves the constraint lines to the proper location relative to the entities involved.
        /// </summary>
        public override void Update()
        {
            //Move lines around
            axis.PositionA = MathConverter.Convert(LineObject.ConnectionB.Position);
            axis.PositionB = MathConverter.Convert(LineObject.ConnectionB.Position + LineObject.TwistAxisB * 1.5f);


            float angleIncrement = 4 * MathHelper.Pi / limitLines.Length; //Each loop iteration moves this many radians forward.

            for (int i = 0; i < limitLines.Length / 2; i++)
            {
                Line pointToPreviousPoint = limitLines[2 * i];
                Line centerToPoint        = limitLines[2 * i + 1];

                float currentAngle = i * angleIncrement;

                //Using the parametric equation for an ellipse, compute the axis of rotation and angle.
                Microsoft.Xna.Framework.Vector3 rotationAxis = MathConverter.Convert(LineObject.Basis.xAxis * LineObject.MaximumAngleX * (float)Math.Cos(currentAngle) +
                                                                                     LineObject.Basis.yAxis * LineObject.MaximumAngleY * (float)Math.Sin(currentAngle));
                float angle = rotationAxis.Length();
                rotationAxis /= angle;

                pointToPreviousPoint.PositionA = MathConverter.Convert(LineObject.ConnectionB.Position) +
                                                 //Rotate the primary axis to the ellipse boundary...
                                                 Microsoft.Xna.Framework.Vector3.TransformNormal(MathConverter.Convert(LineObject.Basis.PrimaryAxis), Microsoft.Xna.Framework.Matrix.CreateFromAxisAngle(rotationAxis, angle));

                centerToPoint.PositionA = pointToPreviousPoint.PositionA;
                centerToPoint.PositionB = MathConverter.Convert(LineObject.ConnectionB.Position);
            }
            for (int i = 0; i < limitLines.Length / 2; i++)
            {
                //Connect all the pointToPreviousPoint lines to the previous points.
                limitLines[2 * i].PositionB = limitLines[2 * ((i + 1) % (limitLines.Length / 2))].PositionA;
            }
        }
示例#12
0
        private xna.Vector3 SingleRaycast(xna.Vector3 from, xna.Vector3 to)
        {
            var rayResult = PhysicsEngine.Raycast2D(
                RaycastProperties.FromSingleRay(
                    TypeConversion.FromXNA(from),
                    TypeConversion.FromXNA(to)
                    )
                );

            RaycastResult result = null;

            //
            // !Warning! this code is relying on the Raycast operation being
            // fundementally synchronous, wrapped in an async API.
            //

            if (rayResult.Test(out result))
            {
                if (result.ImpactPoints.Count == 1)
                {
                    var impact = result.ImpactPoints[0].Position;
                    return(new xna.Vector3(
                               impact.X,
                               impact.Y,
                               impact.Z
                               ));
                }
            }

            return(to);
        }
示例#13
0
        void FindClearestAsync(xna.Vector3 from, xna.Vector3 to, int rayCount)
        {
            // the vector from the target to the current position
            var reference = from - to;

            Port <OcclusionRay> impacts = new Port <OcclusionRay>();

            for (int index = 0; index < rayCount; index++)
            {
                var angle    = 2 * Math.PI * index / rayCount;
                var rotation = xna.Quaternion.CreateFromAxisAngle(xna.Vector3.UnitY, (float)angle);

                // rotate the reference vector by the current angle
                var rotated = xna.Vector3.Transform(reference, rotation);

                // create a new test position
                var curr = to + rotated;

                SingleRaycastAsync(curr, to, index, impacts);
            }

            Activate(
                Arbiter.MultipleItemReceive(false, impacts, rayCount, RayCastHandler)
                );
        }
示例#14
0
        public void DrawRectangles(List <MobaLib.Rectangle> rects, ManualCamera2D cam, Color color)
        {
            int count = rects.Count;

            if (count == 0)
            {
                return;
            }
            be.View = cam.Transformation;
            be.CurrentTechnique.Passes[0].Apply();
            VertexPositionColor[] vertices = new VertexPositionColor[12 * count];
            for (int x = 0; x < count; x++)
            {
                Microsoft.Xna.Framework.Vector3 topLeft  = new Microsoft.Xna.Framework.Vector3(rects[x].Left, rects[x].Top, 0);
                Microsoft.Xna.Framework.Vector3 topRight = new Microsoft.Xna.Framework.Vector3(rects[x].Right, rects[x].Top, 0);
                Microsoft.Xna.Framework.Vector3 botLeft  = new Microsoft.Xna.Framework.Vector3(rects[x].Left, rects[x].Bottom, 0);
                Microsoft.Xna.Framework.Vector3 botRight = new Microsoft.Xna.Framework.Vector3(rects[x].Right, rects[x].Bottom, 0);
                vertices[12 * x]      = new VertexPositionColor(topLeft, color);
                vertices[12 * x + 1]  = new VertexPositionColor(topRight, color);
                vertices[12 * x + 2]  = new VertexPositionColor(topRight, color);
                vertices[12 * x + 3]  = new VertexPositionColor(botRight, color);
                vertices[12 * x + 4]  = new VertexPositionColor(botRight, color);
                vertices[12 * x + 5]  = new VertexPositionColor(botLeft, color);
                vertices[12 * x + 6]  = new VertexPositionColor(botLeft, color);
                vertices[12 * x + 7]  = new VertexPositionColor(topLeft, color);
                vertices[12 * x + 8]  = new VertexPositionColor(botLeft, color);
                vertices[12 * x + 9]  = new VertexPositionColor(topRight, color);
                vertices[12 * x + 10] = new VertexPositionColor(topLeft, color);
                vertices[12 * x + 11] = new VertexPositionColor(botRight, color);
            }
            device.DrawUserPrimitives <VertexPositionColor>(PrimitiveType.LineList, vertices, 0, 6 * count, VertexPositionColor.VertexDeclaration);
        }
示例#15
0
        /// <summary>
        ///     Se llama en cada frame.
        ///     Se debe escribir toda la logica de computo del modelo, asi como tambien verificar entradas del usuario y reacciones
        ///     ante ellas.
        /// </summary>
        protected override void Update(GameTime gameTime)
        {
            // Aca deberiamos poner toda la logica de actualizacion del juego.
            var deltaTime = Convert.ToSingle(gameTime.ElapsedGameTime.TotalSeconds);

            SphereWorld = Matrix.CreateTranslation(SpherePosition) * Matrix.CreateScale(0.3f);
            Vector3 SpherePositionM = new Vector3
                                          (Simulation.Bodies.GetBodyReference(SphereHandles[0]).Pose.Position.X,
                                          Simulation.Bodies.GetBodyReference(SphereHandles[0]).Pose.Position.Y,
                                          Simulation.Bodies.GetBodyReference(SphereHandles[0]).Pose.Position.Z);

            // Camera.Position = new Vector3(SpherePositionM.X, SpherePositionM.Y, SpherePositionM.Z - 500);

            Camera.Update(gameTime, SpherePositionM);

            // Capturar Input teclado
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                //Salgo del juego.
                Exit();
            }

            if (MediaPlayer.State == MediaState.Stopped)
            {
                MediaPlayer.Play(Song);
            }
            UpdatePhysics();
            base.Update(gameTime);
        }
示例#16
0
        public void AddCloud(int whispCount, Vector3 min, Vector3 max, float colorMod, params int[] whispRange)
        {
            int si = 0;
            float scaleMod = Vector3.Distance(min, max) / 4.5f;

            for (int w = 0; w < whispCount; w++)
            {
                float x = MathHelper.Lerp(min.X, max.X, (float)Rnd.NextDouble());
                float y = MathHelper.Lerp(min.Y, max.Y, (float)Rnd.NextDouble());
                float z = MathHelper.Lerp(min.Z, max.Z, (float)Rnd.NextDouble());

                if (si >= whispRange.Length)
                    si = 0;
                Vector3 information = new Vector3();

                float whipTexture = whispRange[si++] / 100.0f;
                information.X = whipTexture;

                float color = Rnd.Next(7, 10) / 10f * colorMod;
                information.Y = 1;
                information.Z = color;
                float scale = 500;

                InstancesList.Add(new Instance(Instancer, scale, new Vector3(x, y, z), information));
            }
        }
 public VertexPositionNormalTextureHue(Vector3 position, Vector3 normal, Vector3 textureCoordinate)
 {
     Position = position;
     Normal = normal;
     TextureCoordinate = textureCoordinate;
     Hue = Vector3.Zero;
 }
示例#18
0
        public float DistanceToSquared(ref Vector3 vector, out Segment connectingSegment)
        {
            float segmentLength = (float)this.GetLength();

            Vector2 normalizedLine = new Vector2(
                (float)(Point2.X - Point1.X) / segmentLength,
                (float)(Point2.Y - Point1.Y) / segmentLength);

            Vector2 pointVector = new Vector2((float)(vector.X - Point1.X), (float)(vector.Y - Point1.Y));

            float length = Vector2.Dot(pointVector, normalizedLine);

            if (length < 0)
            {
                connectingSegment.Point1 = new Point(ref vector);
                connectingSegment.Point2 = Point1;

                return((float)connectingSegment.GetLengthSquared());
            }
            else if (length > segmentLength)
            {
                connectingSegment.Point1 = new Point(ref vector);
                connectingSegment.Point2 = Point2;

                return((float)connectingSegment.GetLengthSquared());
            }
            else
            {
                connectingSegment.Point1 = new Point(ref vector);
                connectingSegment.Point2 = new Point(Point1.X + length * normalizedLine.X,
                                                     Point1.Y + length * normalizedLine.Y);

                return((float)connectingSegment.GetLengthSquared());
            }
        }
示例#19
0
        public override bool Draw(SpriteBatch3D spriteBatch, Vector3 drawPosition, MouseOverList mouseOverList, Map map)
        {
            if (!m_AllowDefer)
            {
                if (CheckDefer(map, drawPosition))
                    return false;
            }
            else
            {
                m_AllowDefer = false;
            }

            int displayItemdID = (m_Animated) ? Effect.ItemID + ((Effect.FramesActive / m_AnimData.FrameInterval) % m_AnimData.FrameCount) : Effect.ItemID;

            if (displayItemdID != m_DisplayItemID)
            {
                m_DisplayItemID = displayItemdID;
                IResourceProvider provider = ServiceRegistry.GetService<IResourceProvider>();
                DrawTexture = provider.GetItemTexture(m_DisplayItemID);
                DrawArea = new Rectangle(DrawTexture.Width / 2 - 22, DrawTexture.Height - IsometricRenderer.TILE_SIZE_INTEGER, DrawTexture.Width, DrawTexture.Height);
                PickType = PickType.PickNothing;
                DrawFlip = false;
            }

            DrawArea.X = 0 - (int)((Entity.Position.X_offset - Entity.Position.Y_offset) * 22);
            DrawArea.Y = 0 + (int)((Entity.Position.Z_offset + Entity.Z) * 4) - (int)((Entity.Position.X_offset + Entity.Position.Y_offset) * 22);

            Rotation = Effect.AngleToTarget;

            // Update hue vector.
            HueVector = Utility.GetHueVector(Entity.Hue);

            return base.Draw(spriteBatch, drawPosition, mouseOverList, map);
        }
示例#20
0
        public void Update(GameTime gameTime)
        {
            var direction = XVector3.Transform(XVector3.UnitZ,
                                               Matrix.CreateRotationX(MathHelper.ToRadians(Game.Client.Pitch)) *
                                               Matrix.CreateRotationY(MathHelper.ToRadians(-(Game.Client.Yaw - 180) + 180)));

            var cast = VoxelCast.Cast(Game.Client.World,
                                      new TRay(Game.Camera.Position, new TVector3(direction.X, direction.Y, direction.Z)),
                                      Game.BlockRepository, TrueCraftGame.Reach, TrueCraftGame.Reach + 2);

            if (cast == null)
            {
                Game.HighlightedBlock = -Coordinates3D.One;
            }
            else
            {
                var provider = Game.BlockRepository.GetBlockProvider(Game.Client.World.GetBlockID(cast.Item1));
                if (provider.InteractiveBoundingBox != null)
                {
                    var box = provider.InteractiveBoundingBox.Value;

                    Game.HighlightedBlock     = cast.Item1;
                    Game.HighlightedBlockFace = cast.Item2;

                    DestructionEffect.World = HighlightEffect.World = Matrix.Identity
                                                                      * Matrix.CreateScale(new XVector3((float)box.Width, (float)box.Height, (float)box.Depth))
                                                                      * Matrix.CreateTranslation(new XVector3((float)box.Min.X, (float)box.Min.Y, (float)box.Min.Z))
                                                                      * Matrix.CreateTranslation(new XVector3(cast.Item1.X, cast.Item1.Y, cast.Item1.Z));
                }
            }
        }
示例#21
0
 public Camera(Entity target)
 {
     _target = target;
     //todo: Change back to 0, 15, 5
     _offsetDistance = new Vector3(0, 40, 5);
     ResetCamera();
 }
示例#22
0
        public CameraTest2()
        {
            sprite1 = new CCSprite(TestResource.s_back3);
            AddChild(sprite1);

            sprite1.Scale = 0.5f;

            sprite2 = new CCSprite(TestResource.s_back3);
            AddChild(sprite2);

            sprite2.Scale = 0.5f;

            Microsoft.Xna.Framework.Vector3 eye, center, up;

            eye    = new Microsoft.Xna.Framework.Vector3(150, 0, 200);
            center = Microsoft.Xna.Framework.Vector3.Zero;
            up     = new Microsoft.Xna.Framework.Vector3(0, 1, 0);

            var lookAt = Microsoft.Xna.Framework.Matrix.CreateLookAt(eye, center, up);

            CCAffineTransform ct = new CCAffineTransform(lookAt.M11, lookAt.M12, lookAt.M13, lookAt.M14, lookAt.Translation.X, lookAt.Translation.Y);

            ct = CCAffineTransform.Identity;

            // Setup our CCAffineTransfrom
            ct.A  = lookAt.M11;
            ct.C  = lookAt.M21;
            ct.B  = lookAt.M12;
            ct.D  = lookAt.M22;
            ct.Tx = lookAt.M41;
            ct.Ty = lookAt.M42;

            //sprite1.AdditionalTransform = ct;
        }
示例#23
0
        internal void UpdateForwardVelocity()
        {
            var forwardVector = this.RotationMatrix.Right;
            var projected     = Vector3.Dot(forwardVector, Velocity);

            this.currentSpeedRatio = projected / MaxSpeed;
        }
示例#24
0
        void RenderResults(RenderMode renderMode, simengine.MatrixTransforms transforms, simengine.CameraEntity currentCamera)
        {
            _timeAttenuationHandle.SetValue(new xna.Vector4(100 * (float)Math.Cos(_appTime * (1.0f / SCAN_INTERVAL)), 0, 0, 1));

            // render impact points as a quad
            xna.Matrix inverseViewRotation = currentCamera.ViewMatrix;
            inverseViewRotation.M41 = inverseViewRotation.M42 = inverseViewRotation.M43 = 0;
            xna.Matrix.Invert(ref inverseViewRotation, out inverseViewRotation);
            xna.Matrix localTransform = xna.Matrix.CreateFromAxisAngle(new xna.Vector3(1, 0, 0), (float)-Math.PI / 2) * inverseViewRotation;

            simengine.SimulationEngine.GlobalInstance.Device.DepthStencilState = xnagrfx.DepthStencilState.DepthRead;
            for (int i = 0; i < _lastResults.ImpactPoints.Count; i++)
            {
                xna.Vector3 pos = new xna.Vector3(_lastResults.ImpactPoints[i].Position.X,
                                                  _lastResults.ImpactPoints[i].Position.Y,
                                                  _lastResults.ImpactPoints[i].Position.Z);

                xna.Vector3 resultDir = pos - Position;
                resultDir.Normalize();

                localTransform.Translation = pos - .02f * resultDir;
                transforms.World           = localTransform;

                base.Render(renderMode, transforms, Meshes[0]);
            }
            simengine.SimulationEngine.GlobalInstance.Device.DepthStencilState = xnagrfx.DepthStencilState.Default;
        }
示例#25
0
        private void DebugActivity()
        {
            if (DebuggingVariables.ShowUnitPaths)
            {
                int numberOfLinesNeeded = this.ImmediateGoal?.Path?.Count ?? 0;

                while (this.pathLines.Count < numberOfLinesNeeded)
                {
                    var line = new Line();
                    line.Visible = true;
                    pathLines.Add(line);
                }
                while (this.pathLines.Count > numberOfLinesNeeded)
                {
                    ShapeManager.Remove(pathLines.Last());
                }

                for (int i = 0; i < numberOfLinesNeeded; i++)
                {
                    Vector3 pointBefore;
                    if (i == 0)
                    {
                        pointBefore = this.Position;
                    }
                    else
                    {
                        pointBefore = ImmediateGoal.Path[i - 1].Position;
                    }
                    Vector3 pointAfter = ImmediateGoal.Path[i].Position;

                    pathLines[i].SetFromAbsoluteEndpoints(pointBefore, pointAfter);
                }
            }
        }
示例#26
0
        /// <summary>
        /// 初始化当前使命的仿真环境,在当前使命类构造函数中调用
        /// </summary>
        private void InitEnvironment()
        {
            EnvRef = (SimEnvironment)Env;
            // 只有第一次调用时需要添加一个仿真水球

            for (int i = 0; i < 2; i++)
            {// 添加9个仿真水球
                Env.Balls.Add(new Ball());
            }

            xna.Vector3 positionMm   = new xna.Vector3(0, 0, 0);
            xna.Vector3 positionMm11 = new xna.Vector3(-1000, 0, 0);
            xna.Vector3 positionMm22 = new xna.Vector3(1000, 0, 0);
            xna.Vector3 positionMm1  = new xna.Vector3(0, 0, -1350);
            xna.Vector3 positionMm2  = new xna.Vector3(0, 0, -1050);
            xna.Vector3 positionMm3  = new xna.Vector3(0, 0, 1350);
            xna.Vector3 positionMm4  = new xna.Vector3(0, 0, 1050);

            Env.ObstaclesRound.Add(new RoundedObstacle("obs1", positionMm, Color.White, Color.Green, 80));
            Env.ObstaclesRound.Add(new RoundedObstacle("obs2", positionMm11, Color.White, Color.Green, 80));
            Env.ObstaclesRound.Add(new RoundedObstacle("obs3", positionMm22, Color.White, Color.Green, 80));

            Env.ObstaclesRect.Add(new RectangularObstacle("obs4", positionMm3, Color.Green, 200, 100, 0));
            Env.ObstaclesRect.Add(new RectangularObstacle("obs7", positionMm4, Color.Green, 200, 100, 0));
            Env.ObstaclesRect.Add(new RectangularObstacle("obs5", positionMm1, Color.Green, 200, 100, 0));
            Env.ObstaclesRect.Add(new RectangularObstacle("obs6", positionMm2, Color.Green, 200, 100, 0));
        }
示例#27
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            zNear = 0.001f;
            zFar = 1000.0f;
            fov = MathHelper.Pi * 70.0f / 180.0f;
            eye = new Vector3(0.0f, 0.7f, 1.5f);
            at = new Vector3(0.0f, 0.0f, 0.0f);
            up = new Vector3(0.0f, 1.0f, 0.0f);

            cube = new VertexPositionColor[8];
            cube[0] = new VertexPositionColor(new Vector3(-0.5f, -0.5f, -0.5f), new Color(0.0f, 0.0f, 0.0f));
            cube[1] = new VertexPositionColor(new Vector3(-0.5f, -0.5f,  0.5f), new Color(0.0f, 0.0f, 1.0f));
            cube[2] = new VertexPositionColor(new Vector3(-0.5f,  0.5f, -0.5f), new Color(0.0f, 1.0f, 0.0f));
            cube[3] = new VertexPositionColor(new Vector3(-0.5f,  0.5f,  0.5f), new Color(0.0f, 1.0f, 1.0f));
            cube[4] = new VertexPositionColor(new Vector3( 0.5f, -0.5f, -0.5f), new Color(1.0f, 0.0f, 0.0f));
            cube[5] = new VertexPositionColor(new Vector3( 0.5f, -0.5f,  0.5f), new Color(1.0f, 0.0f, 1.0f));
            cube[6] = new VertexPositionColor(new Vector3( 0.5f,  0.5f, -0.5f), new Color(1.0f, 1.0f, 0.0f));
            cube[7] = new VertexPositionColor(new Vector3( 0.5f,  0.5f,  0.5f), new Color(1.0f, 1.0f, 1.0f));

            vertexBuffer = new DynamicVertexBuffer(graphics.GraphicsDevice, typeof(VertexPositionColor), 8, BufferUsage.WriteOnly);
            indexBuffer = new DynamicIndexBuffer(graphics.GraphicsDevice, typeof(ushort), 36, BufferUsage.WriteOnly);

            basicEffect = new BasicEffect(graphics.GraphicsDevice); //(device, null);
            basicEffect.LightingEnabled = false;
            basicEffect.VertexColorEnabled = true;
            basicEffect.TextureEnabled = false;

            graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;
            base.Initialize();
        }
示例#28
0
 //        private Vector2 texCoord;
 public MyOwnVertexFormat(Vector3 position, Vector3 normal, Color color)
 {
     this.position = position;
     this.color = color;
     //			this.texCoord = texCoord;
     this.normal = normal;
 }
示例#29
0
        /// <summary>
        /// 返回所需转过的角度
        /// </summary>
        /// <param name="fish"></param>
        /// <param name="aimPosition"></param>
        /// <returns>返回所需转过的角度 </returns>
        public static float Getxzdangle(RoboFish fish, xna.Vector3 aimPosition)
        {
            xna.Vector3 aimVector;
            aimVector.X = aimPosition.X - fish.PolygonVertices[0].X;
            aimVector.Z = aimPosition.Z - fish.PolygonVertices[0].Z;
            aimVector.Y = 0;
            //float aimAngle = StrategyHelper.Helpers.GetAngleDegree(aimVector);
            xna.Vector3 fishRad = new xna.Vector3((float)Math.Cos(fish.BodyDirectionRad), 0, (float)Math.Sin(fish.BodyDirectionRad));
            //公式:θ=atan2(v2.y,v2.x)−atan2(v1.y,v1.x)
            //atan2的取值范围是[−π,π],在进行相减之后得到的夹角是在[−2π,2π],
            //因此当得到的结果大于π时,对结果减去2π,当结果小于−π时,对结果加上2π
            //虽然与一般坐标方向不一致,但是象限都是3 4 1 2的顺序,所以仍然成立
            //但是仍需验证
            float theta = (float)Math.Atan2(aimVector.Z, aimVector.X) - (float)Math.Atan2(fishRad.Z, fishRad.X);

            if (theta > Math.PI)
            {
                theta -= (float)(2 * Math.PI);
            }
            else if (theta < -Math.PI)
            {
                theta += (float)(2 * Math.PI);
            }
            return(theta);
        }
示例#30
0
        public Stairs(Vector3 position, bool westEast, bool shapeL) : base(position)
        {
            Position = position;

            var original = new CubeGraphic { Position = position, DrawFaces = CubeFaces.All ^ CubeFaces.Front ^ CubeFaces.Floor };
            var nextFloor = new CubeGraphic { Position = original.Position + Vector3.Down, DrawFaces = CubeFaces.Sides ^ CubeFaces.Front };
            var stairs = new ModelGraphic { Position = nextFloor.Position };

            original.Texture = nextFloor.Texture = nextFloor.Resources.Content.Load<Texture2D>("Textures/Wall");

            if (shapeL)
            {
                stairs.Model = stairs.Resources.Content.Load<Model>("Models/stairs1");

                if (westEast)
                    nextFloor.DrawFaces ^= CubeFaces.Right;
                else
                    nextFloor.DrawFaces ^= CubeFaces.Left;
            }
            else
            {
                stairs.Model = stairs.Resources.Content.Load<Model>("Models/stairs");
                nextFloor.DrawFaces ^= CubeFaces.Back;
            }

            if (westEast)
            {
                original.Rotation = nextFloor.Rotation = new Vector3(0, MathHelper.PiOver2, 0);
                stairs.Rotation = new Vector3(0, MathHelper.PiOver2, 0);
                stairs.MirrorX = true;
            }

            graphics = new GraphicsCollection(original, nextFloor, stairs);
            graphicsProviders.SubProviders.Add(graphics);
        }
示例#31
0
 public static CubeCoordinates ToCubeCoordinates(this WorldCoordinates coordinates)
 {
     return(new CubeCoordinates(
                (int)Math.Round(coordinates.X),
                (int)Math.Round(coordinates.Y),
                (int)Math.Round(coordinates.Z)));
 }
示例#32
0
        private void KeyPressed()
        {
            Vector3 direction = new Vector3();

            KeyboardState keyState = Keyboard.GetState();

            if (keyState.IsKeyDown(Keys.A))
            {
                direction += new Vector3(-4f, 0, 0);
            }

            if (keyState.IsKeyDown(Keys.D))
            {
                direction += new Vector3(4f, 0, 0);
            }

            if (keyState.IsKeyDown(Keys.W))
            {
                direction += new Vector3(0, 0, 4f);
            }

            if (keyState.IsKeyDown(Keys.S))
            {
                direction += new Vector3(0, 0, -4f);
            }
            CameraTranslate(direction);
        }
示例#33
0
 public override void Prepare(Group group)
 {
   base.Prepare(group);
   this.matrices.World = (Matrix) group.WorldMatrix;
   if (group.Material != null)
   {
     if (this.lastDiffuse != group.Material.Diffuse)
     {
       this.material.Diffuse = group.Material.Diffuse;
       this.lastDiffuse = group.Material.Diffuse;
     }
   }
   else
     this.material.Diffuse = group.Mesh.Material.Diffuse;
   if (group.TexturingType == TexturingType.Texture2D)
   {
     this.texture.Set(group.Texture);
     this.groupTextureDirty = true;
   }
   else
   {
     if (!this.groupTextureDirty)
       return;
     this.texture.Set((Texture) group.Mesh.Texture);
   }
 }
示例#34
0
 public Camera(Game game, Vector3 position, Vector3 target, Vector3 upVector)
     : base(game)
 {
     this.position = position;
     this.target = target;
     this.upVector = upVector;
 }
 protected PrimitiveDeBase(Game jeu, float homothétieInitiale, Vector3 rotationInitiale, Vector3 positionInitiale)
     : base(jeu)
 {
     HomothétieInitiale = homothétieInitiale;
     RotationInitiale = rotationInitiale;
     PositionInitiale = positionInitiale;
 }
示例#36
0
        public virtual void Draw()
        {
            if (this.GetPositionZ() > 10)
            {
                _position += VerticalVelocity;
            }
            _position += HorizontalVelocity;

            var w = _world*Matrix.CreateTranslation(_position);

            foreach (ModelMesh mesh in _model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.LightingEnabled = true;
                    effect.AmbientLightColor = CurrentColor;

                    effect.DirectionalLight0.Direction = Vector3.Down;
                    effect.DirectionalLight0.DiffuseColor = DiffuseColor;
                    effect.DirectionalLight0.Enabled = true;

                    effect.View = _view;
                    effect.Projection = _projection;
                    effect.World = _transforms[mesh.ParentBone.Index] * w;
                }
                mesh.Draw();
            }
        }
示例#37
0
        public static void MoveToAreaS(Mission mission, ref Decision decision, int teamId, int fishId, xna.Vector3 goal, int degree)
        {
            float degreeF = (float)(mission.TeamsRef[teamId].Fishes[fishId].BodyDirectionRad / Math.PI * 180);

            xna.Vector3 fM = mission.TeamsRef[teamId].Fishes[fishId].PositionMm;

            if (GetDistBetwGB(fM, goal) < 150)
            {
                xna.Vector3 p = SetDegreeFishToP(fM, degree);
                Dribble2(ref decision, mission.TeamsRef[teamId].Fishes[fishId], p, 60, 150, 180, 200, 1, 1, 3, 10, 100, true);
                if (Math.Abs(degree - degreeF) <= 15)
                {
                    decision.TCode = 7;
                    decision.VCode = 0;
                }
            }
            else if (Math.Abs(degree - degreeF) <= 15 && GetDistBetwGB(fM, goal) < 200)
            {
                decision.TCode = 7;
                decision.VCode = 0;
            }
            else
            {
                Dribble2(ref decision, mission.TeamsRef[teamId].Fishes[fishId], goal, 9, 20, 60, 200, 8, 8, 8, 10, 100, true);
            }
        }
示例#38
0
        /// <summary>
        /// 初始化当前使命的仿真环境,在当前使命类构造函数中调用
        /// </summary>
        private void InitEnvironment()
        {
            EnvRef = (SimEnvironment)Env;
            for (int i = 0; i < 9; i++)
            {// 添加9个仿真水球
                Env.Balls.Add(new Ball());
            }

            int r = Env.Balls[0].RadiusMm;

            xna.Vector3 positionMm = new xna.Vector3(0, 0, 0);

            Env.ObstaclesRect.Add(new RectangularObstacle("obs1", positionMm, Color.Red, Color.Green, r, 5 * r, 0));
            Env.ObstaclesRect.Add(new RectangularObstacle("obs2", positionMm, Color.Red, Color.Green, r, 5 * r, 0));
            Env.ObstaclesRect.Add(new RectangularObstacle("obs3", positionMm, Color.Yellow, Color.Green, r, 5 * r, 0));
            Env.ObstaclesRect.Add(new RectangularObstacle("obs4", positionMm, Color.Yellow, Color.Green, r, 5 * r, 0));

            Env.ObstaclesRect.Add(new RectangularObstacle("obs5", positionMm, Color.Red, Color.Green, r / 2, 153 * r / 8, 0));
            Env.ObstaclesRect.Add(new RectangularObstacle("obs6", positionMm, Color.Yellow, Color.Green, r / 2, 153 * r / 8, 0));


            //added by chenxiao

            //临时注释掉动态障碍物部分
            //InitDynacimObstacles();


            //Env.DynamicRect.Add(new RectangularDynamic("dyn1", positionMm, Color.Red, Color.Gray, 0, 3 * r, r,0, 80, -(float)Math.PI/2, 0,101));
            //Env.DynamicRect.Add(new RectangularDynamic("dyn2", positionMm, Color.Yellow, Color.Gray, 0,3* r, r, 0, 80, (float)Math.PI / 2, 0,101 ));
        }
示例#39
0
        public static void GetMeshData(TriangleMesh mesh, List <VertexPositionNormalTexture> vertices, List <ushort> indices)
        {
            var tempVertices = new VertexPositionNormalTexture[mesh.Data.Vertices.Length];

            for (int i = 0; i < mesh.Data.Vertices.Length; i++)
            {
                Vector3 v;
                mesh.Data.GetVertexPosition(i, out v);
                tempVertices[i] = new VertexPositionNormalTexture(MathConverter.Convert(v), Microsoft.Xna.Framework.Vector3.Zero, Microsoft.Xna.Framework.Vector2.Zero);
            }

            for (int i = 0; i < mesh.Data.Indices.Length; i++)
            {
                indices.Add((ushort)mesh.Data.Indices[i]);
            }
            for (int i = 0; i < indices.Count; i += 3)
            {
                int a = indices[i];
                int b = indices[i + 1];
                int c = indices[i + 2];
                Microsoft.Xna.Framework.Vector3 normal = Microsoft.Xna.Framework.Vector3.Normalize(Microsoft.Xna.Framework.Vector3.Cross(
                                                                                                       tempVertices[c].Position - tempVertices[a].Position,
                                                                                                       tempVertices[b].Position - tempVertices[a].Position));
                tempVertices[a].Normal += normal;
                tempVertices[b].Normal += normal;
                tempVertices[c].Normal += normal;
            }

            for (int i = 0; i < tempVertices.Length; i++)
            {
                tempVertices[i].Normal.Normalize();
                vertices.Add(tempVertices[i]);
            }
        }
示例#40
0
 public Circle2D(Vector3 position, float innerRadius, float thickness, Color color)
 {
     Position = position;
     InnerRadius = innerRadius;
     Thickness = thickness;
     Color = color;            
 }
示例#41
0
 public LocalSpace(Vector3 up, Vector3 forward, Vector3 position)
 {
     _up = up;
     _forward = forward;
     _position = position;
     SetUnitSideFromForwardAndUp();
 }
示例#42
0
        public override void GetMeshData(List <VertexPositionNormalTexture> vertices, List <ushort> indices)
        {
            var tempVertices = new VertexPositionNormalTexture[DisplayedObject.Shape.TriangleMesh.Data.Vertices.Length];

            for (int i = 0; i < DisplayedObject.Shape.TriangleMesh.Data.Vertices.Length; i++)
            {
                tempVertices[i] = new VertexPositionNormalTexture(
                    MathConverter.Convert(AffineTransform.Transform(DisplayedObject.Shape.TriangleMesh.Data.Vertices[i], DisplayedObject.WorldTransform)),
                    Microsoft.Xna.Framework.Vector3.Zero,
                    Microsoft.Xna.Framework.Vector2.Zero);
            }

            for (int i = 0; i < DisplayedObject.Shape.TriangleMesh.Data.Indices.Length; i++)
            {
                indices.Add((ushort)DisplayedObject.Shape.TriangleMesh.Data.Indices[i]);
            }
            for (int i = 0; i < indices.Count; i += 3)
            {
                int a = indices[i];
                int b = indices[i + 1];
                int c = indices[i + 2];
                Microsoft.Xna.Framework.Vector3 normal = Microsoft.Xna.Framework.Vector3.Normalize(Microsoft.Xna.Framework.Vector3.Cross(
                                                                                                       tempVertices[c].Position - tempVertices[a].Position,
                                                                                                       tempVertices[b].Position - tempVertices[a].Position));
                tempVertices[a].Normal += normal;
                tempVertices[b].Normal += normal;
                tempVertices[c].Normal += normal;
            }

            for (int i = 0; i < tempVertices.Length; i++)
            {
                tempVertices[i].Normal.Normalize();
                vertices.Add(tempVertices[i]);
            }
        }
示例#43
0
        public void RotateAboutAxis(Vector3D axis, double angleRad)
        {
            var v = new sVector3D((float)axis.X, (float)axis.Y, (float)axis.Z);

            m = m * sMatrix3D.CreateFromQuaternion(sQuaternion.CreateFromAxisAngle(v, (float)angleRad));
            //m.Rotate(new sQuaternion(new sVector3D(axis.X, axis.Y, axis.Z), angleRad.ToDeg()));
        }
        public BoundingSphere GetBoundingSphere(Vector3 aLowest, Vector3 aHighest, Vector3 aTranslation, Vector3 aTile)
        {
            Vector3 temporaryRadius = new Vector3((aHighest.X - aLowest.X) / 2, (aHighest.Y - aLowest.Y) / 2, (aHighest.Z - aLowest.Z) / 2) * aTile;
            BoundingSphere temporarySphere = new BoundingSphere(aTranslation, (temporaryRadius.X + temporaryRadius.Y + temporaryRadius.Z) / 3);

            return temporarySphere;
        }
示例#45
0
 public Square(string id, Vector3 position, int f, int r, bool color)
     : base(id, position)
 {
     File = (Files)f;
     Rank = (Ranks)r;
     _asset = color ? "White Square" : "Black Square";
 }
示例#46
0
文件: Pathway.cs 项目: hgrandry/Mgx
 // how far outside path tube is the given point?  (negative is inside)
 public float HowFarOutsidePath(Vector3 point)
 {
     float outside;
     Vector3 tangent;
     MapPointToPath(point, out tangent, out outside);
     return outside;
 }
示例#47
0
文件: Net.cs 项目: AleksandarDev/LD26
        public Net(Vector3 position, int numBlocksX, int numBlocksY, float blockWidth, float blockHeight, Color color)
        {
            this.primitivesCount = numBlocksX + numBlocksY + 2;
            this.primitives = new IPrimitive[this.primitivesCount];

            GenerateNet(numBlocksX, numBlocksY, blockWidth, blockHeight, position, color);
        }
示例#48
0
文件: Pathway.cs 项目: hgrandry/Mgx
 // is the given point inside the path tube?
 public bool IsInsidePath(Vector3 point)
 {
     float outside;
     Vector3 tangent;
     MapPointToPath(point, out tangent, out outside);
     return outside < 0;
 }
示例#49
0
 /// <summary>
 /// Constructor de la clase GameObject.
 /// </summary>
 /// <param name="effect">Effecto usado para dibujar.</param>
 /// <param name="engine">Clase principal del juego.</param>
 /// <param name="size">Tamaño del objeto.</param>
 /// <param name="position">Posicion x, y, z dada como Vector3.</param>
 /// <param name="color">Color del objeto.</param>
 public GameObject(Engine engine, Vector3 position, Color color, float size)
     : base(engine)
 {
     this.size = size;
     this.color = color;
     this.position = position;
 }
示例#50
0
 public virtual void Reset()
 {
     Position = Vector3.Zero;
     Velocity = Vector3.Zero;
     Direction = new Vector3(1.0f, 1.0f, 1.0f);
     IsAlive = true;
 }
示例#51
0
        private void KeyboardControl()
        {
            if (Input.Y == 1)
            {
                Velocity += ACCELERATION * Direction;
            }
            else if (Input.Y == -1)
            {
                Velocity -= ACCELERATION * Direction;
            }

            if (Input.X == 1)
            {
                Velocity += ACCELERATION * Right;
            }
            else if (Input.X == -1)
            {
                Velocity -= ACCELERATION * Right;
            }

            else if (InputManager.IsKeyDown(Keys.Space))
            {
                Velocity += Up * ACCELERATION;
            }
            else if (InputManager.IsKeyDown(Keys.LeftShift))
            {
                Velocity -= Up * ACCELERATION;
            }



            if (Input.Y == 0)
            {
                var dir = Direction;
                dir.Y = 0;
                var dot = Vector3.Dot(Velocity, Vector3.Normalize(Direction));
                Velocity -= Math.Sign(dot) * Direction * DECELERATION;
            }

            if (Input.X == 0)
            {
                var dir = Direction;
                dir.Y = 0;
                var vel = Velocity;
                vel.Y = 0;
                var dot = Vector3.Dot(Velocity, Vector3.Normalize(Right));
                Velocity -= Math.Sign(dot) * Right * DECELERATION;
            }

            if (Velocity.Length() < 1f && Input.X == 0 && Input.Y == 0)
            {
                Velocity = new Vector3(0);
            }

            // MaxSpeed
            if (Velocity.Length() > MAX_SPEED)
            {
                Velocity = Vector3.Normalize(Velocity) * MAX_SPEED;
            }
        }
示例#52
0
        //Initialisieren der Anfangswerte
        public override void Initialize()
        {
            Position = new Vector3(0, 5, 0);
            lookAt = new Vector3(0, 5, -1);
            upVector = Vector3.Up;
            rightVector = Vector3.Right;
            Direction = Vector3.Forward;

            ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45.0f),
                Game.GraphicsDevice.Viewport.AspectRatio,
                NearPlane,
                FarPlane);

            ViewMatrix = Matrix.CreateLookAt(
                Position,
                lookAt,
                upVector
                );

            //Setzen der Mauszeigerposition auf die Mitte des Schirmes
            Mouse.SetPosition(Game.GraphicsDevice.Viewport.Width / 2, Game.GraphicsDevice.Viewport.Height / 2);
            originalMouseState = Mouse.GetState();

            base.Initialize();
        }
示例#53
0
        //The function to use for new pointlights
        /// <summary>
        /// Add a point light to the list of drawn point lights
        /// </summary>
        /// <param name="position"></param>
        /// <param name="radius"></param>
        /// <param name="color"></param>
        /// <param name="intensity"></param>
        /// <param name="castShadows">will render shadow maps</param>
        /// <param name="isVolumetric">does it have a fog volume?</param>
        /// <param name="volumetricDensity">How dense is the volume?</param>
        /// <param name="shadowResolution">shadow map resolution per face. Optional</param>
        /// <param name="staticShadow">if set to true the shadows will not update at all. Dynamic shadows in contrast update only when needed.</param>
        /// <returns></returns>
        private PointLight AddPointLight(Vector3 position, float radius, Color color, float intensity, bool castShadows, bool isVolumetric = false, float volumetricDensity = 1, int shadowResolution = 256, int softShadowBlurAmount = 0, bool staticShadow = false)
        {
            PointLight light = new PointLight(position, radius, color, intensity, castShadows, isVolumetric, shadowResolution, softShadowBlurAmount, staticShadow, volumetricDensity);

            PointLights.Add(light);
            return(light);
        }
示例#54
0
        public ArcBallCamera(
            Vector3 targetPos,
            float initialPos,
            float initialRot,
            float initialElevation,
            float minDistance,
            float maxDistance,
            float initialDistance,
            float aspectRatio,
            float nearClip,
            float farClip)
        {
            Target = targetPos;
            Elevation = initialElevation;
            Rotation = initialRot;
            _minDistance = minDistance;
            _maxDistance = maxDistance;
            _viewDistance = initialDistance;

            ProjectionMatrix =
                Matrix.CreatePerspectiveFieldOfView(
                    MathHelper.PiOver4,
                    aspectRatio,
                    nearClip,
                    farClip);

            _needViewResync = true;
        }
示例#55
0
        /// <summary>
        /// Skins an individual vertex.
        /// </summary>
        public static void SkinVertex(
            Matrix[] bones,
            ref Microsoft.Xna.Framework.Vector3 position,
            ref Microsoft.Xna.Framework.Vector3 normal,
            ref Matrix world,
            ref byte[] blendIndices,
            ref Vector4 blendWeights,
            out Microsoft.Xna.Framework.Vector3 outPosition,
            out Microsoft.Xna.Framework.Vector3 outNormal)
        {
            int b0 = (int)blendIndices[0];
            int b1 = (int)blendIndices[1];
            int b2 = (int)blendIndices[2];
            int b3 = (int)blendIndices[3];

            Matrix skinnedTransformSum;

            Blend4x3Matrix(ref bones[b0], ref bones[b1], ref bones[b2], ref bones[b3], ref blendWeights, out skinnedTransformSum);

            Matrix.Multiply(ref skinnedTransformSum, ref world, out skinnedTransformSum);

            // Support the 4 Bone Influences - Position then Normal
            Microsoft.Xna.Framework.Vector3.Transform(ref position, ref skinnedTransformSum, out outPosition);
            Microsoft.Xna.Framework.Vector3.TransformNormal(ref normal, ref skinnedTransformSum, out outNormal);
        }
示例#56
0
        public SkyBox(Game1 newGame, Vector3 newCenter, string newName)
        {
            Game = newGame;
            center = newCenter;

            skyBoxModel=LoadModel(newName, out skyBoxTextures);
        }
示例#57
0
        /// <summary>
        /// 判断某点是否在某条向量或者延长线上(附近)
        /// </summary>
        /// <param name="curr">所要判断的点的坐标</param>
        /// <param name="start">向量起始点</param>
        /// <param name="end">向量指向点</param>
        /// <returns>是或者不是</returns>
        public static bool ifOnVector(xna.Vector3 curr, xna.Vector3 start, xna.Vector3 end)
        {
            float xtemp = start.X - ((start.Z - curr.Z) * (end.X - start.X) / (end.Z - start.Z));

            if (end.Z > curr.Z && start.Z < curr.Z)
            {
                return(false);
            }
            if (end.Z < curr.Z && start.Z > curr.Z)
            {
                return(false);
            }
            if (start.Z == end.Z)
            {
                if (end.X > curr.X && start.X < curr.X)
                {
                    return(false);
                }
                if (end.X < curr.X && start.X > curr.X)
                {
                    return(false);
                }
            }

            if (curr.X + 50 >= xtemp && curr.X - 50 <= xtemp)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
示例#58
0
        public void Draw(Vector3 center, Matrix newView, short clip)
        {
            Game.device.DepthStencilState = DepthStencilState.None;
            Game.device.RasterizerState = RasterizerState.CullNone;
            Game.device.BlendState = BlendState.Opaque;

            Matrix[] skyboxTransforms = new Matrix[skyBoxModel.Bones.Count];
            skyBoxModel.CopyAbsoluteBoneTransformsTo(skyboxTransforms);
            int i = 0;
            foreach (ModelMesh mesh in skyBoxModel.Meshes)
            {
                foreach (Effect currentEffect in mesh.Effects)
                {
                    Matrix worldMatrix = /*Matrix.CreateRotationY(rotation+=0.0001f) **/ Matrix.CreateScale(500f) * skyboxTransforms[mesh.ParentBone.Index] * Matrix.CreateTranslation(center);
                    currentEffect.CurrentTechnique = currentEffect.Techniques["Sky"];
                    currentEffect.Parameters["xWorld"].SetValue(skyboxTransforms[mesh.ParentBone.Index]*worldMatrix);
                    currentEffect.Parameters["xViewProjection"].SetValue(newView * Game.cam.infinite_proj);
                    currentEffect.Parameters["xTexture"].SetValue(skyBoxTextures[i++]);
                    currentEffect.Parameters["xCamPos"].SetValue(Game.cam.cameraPosition);
                    currentEffect.Parameters["xShEye"].SetValue(Game.cam.shEye);

                    currentEffect.Parameters["xGrayScale"].SetValue(Game.enviro.grayScale);
                    currentEffect.Parameters["xInvertedColors"].SetValue(Game.enviro.invertColors);
                    currentEffect.Parameters["xUnderWater"].SetValue(Game.enviro.underWater);

                    currentEffect.Parameters["xClipping"].SetValue(clip);
                    currentEffect.Parameters["xClipHeight"].SetValue(Game.enviro.waterLevel);
                }
                mesh.Draw();
            }
            Game.device.BlendState = BlendState.Opaque;
            Game.device.RasterizerState = RasterizerState.CullClockwise;
            Game.device.DepthStencilState = DepthStencilState.Default;
        }
示例#59
0
        ///<summary>
        /// Gets the point on the simplex that is closest to the origin.
        ///</summary>
        ///<param name="simplex">Simplex to test.</param>
        ///<param name="point">Closest point on the simplex.</param>
        ///<returns>Whether or not the simplex contains the origin.</returns>
        public bool GetPointClosestToOrigin(ref RaySimplex simplex, out Vector3 point)
        {
            //This method finds the closest point on the simplex to the origin.
            //Barycentric coordinates are assigned to the MinimumNormCoordinates as necessary to perform the inclusion calculation.
            //If the simplex is a tetrahedron and found to be overlapping the origin, the function returns true to tell the caller to terminate.
            //Elements of the simplex that are not used to determine the point of minimum norm are removed from the simplex.

            switch (State)
            {

                case SimplexState.Point:
                    point = A;
                    break;
                case SimplexState.Segment:
                    GetPointOnSegmentClosestToOrigin(ref simplex, out point);
                    break;
                case SimplexState.Triangle:
                    GetPointOnTriangleClosestToOrigin(ref simplex, out point);
                    break;
                case SimplexState.Tetrahedron:
                    return GetPointOnTetrahedronClosestToOrigin(ref simplex, out point);
                default:
                    point = Toolbox.ZeroVector;
                    break;


            }
            return false;
        }
示例#60
0
        private void RemovePatch(PlanetNode currentNode)
        {
            Vector3 mid = (currentNode.min + currentNode.max) / 2;

            activePatches.Remove(mid);
            SystemCore.GameObjectManager.RemoveObject(currentNode);
        }