Beispiel #1
0
        /// <summary>
        /// Gets the number of shapes in the list for the particular shape
        /// </summary>
        /// <param name="phmo">the serialized phmo from which to get the counts</param>
        /// <param name="type">the shape for which to get the count</param>
        /// <returns></returns>
        private int GetNumberOfShapes(PhysicsModel phmo, HavokShapeType type)
        {
            switch (type)
            {
            case HavokShapeType.Box:
                return(phmo.Boxes != null ? phmo.Boxes.Count : 0);

            case HavokShapeType.List:
                return(phmo.Lists != null ? phmo.Lists.Count : 0);

            case HavokShapeType.Mopp:
                return(phmo.Mopps != null ? phmo.Mopps.Count : 0);

            case HavokShapeType.Pill:
                return(phmo.Pills != null ? phmo.Pills.Count : 0);

            case HavokShapeType.Polyhedron:
                return(phmo.Polyhedra != null ? phmo.Polyhedra.Count : 0);

            case HavokShapeType.Sphere:
                return(phmo.Spheres != null ? phmo.Spheres.Count : 0);

            default:
                return(0);
            }
        }
Beispiel #2
0
        private void Client_ReceiveHitCall(RemoteEntityWorld sender, ReceiveDataReader reader)
        {
            Vec3      hitPosition      = reader.ReadVec3();
            string    hitShapeBodyName = reader.ReadString();
            string    hitShapeName     = reader.ReadString();
            Vec3      hitNormal        = reader.ReadVec3();
            MapObject hitMapObject     = Entities.Instance.GetByNetworkUIN(reader.ReadVariableUInt32()) as MapObject;

            if (!reader.Complete())
            {
                return;
            }

            Position = hitPosition;
            Shape hitShape = null;

            if (PhysicsModel != null)
            {
                Body body = PhysicsModel.GetBody(hitShapeBodyName);
                if (body != null)
                {
                    hitShape = body.GetShape(hitShapeName);
                }
            }
            OnHit(hitShape, hitNormal, hitMapObject);
        }
Beispiel #3
0
        protected override void OnTick()
        {
            base.OnTick();

            if (firstWay == true)
            {
                ActivateWayMovement();
            }

            UpdateGeneralTask();
            CalculateThings();

            chassisBody = PhysicsModel.GetBody("main");
            if (chassisBody == null)
            {
                Log.Error("Emrah Helli: \"main\" chassisBody dose not exists.");
                return;
            }

            float diff  = Position.Z - flyHeight;
            float force = -diff - chassisBody.LinearVelocity.Z;

            MathFunctions.Clamp(ref force, -10, 10);

            chassisBody.AddForce(ForceType.GlobalAtLocalPos, TickDelta,
                                 new Vec3(0, 0, force * 3) * chassisBody.Mass, new Vec3(0, 0, 1));

            chassisBody.AngularDamping = 1;

            this.flyHeight = TaskPosition.Z;

            float ZA = ZADiffAngle * 4;

            if (ZA < 20 && ZA > -20)
            {
                chassisBody.AngularVelocity = new Vec3
                                                  (chassisBody.AngularVelocity.X, chassisBody.AngularVelocity.Y, ZA);
            }
            else if (ZA > 20)
            {
                chassisBody.AngularVelocity = new Vec3
                                                  (chassisBody.AngularVelocity.X, chassisBody.AngularVelocity.Y, -2);
            }
            else if (ZA < -20)
            {
                chassisBody.AngularVelocity = new Vec3
                                                  (chassisBody.AngularVelocity.X, chassisBody.AngularVelocity.Y, 2);
            }

            chassisBody.AddForce(ForceType.LocalAtLocalPos, TickDelta, new Vec3(Velocity * chassisBody.Mass, 0, 0), new Vec3(-1, 0, 0));
            chassisBody.LinearDamping = 1;
            //check outside Map position
            Bounds checkBounds = Map.Instance.InitialCollisionBounds;

            checkBounds.Expand(new Vec3(300, 300, 10000));
            if (!checkBounds.IsContainsPoint(Position))
            {
                SetDeleted();
            }
        }
Beispiel #4
0
        /// <summary>
        /// Initialise the physics model to be built
        /// </summary>
        public PhysicsModelBuilder()
        {
            _phmo             = new PhysicsModel();
            _phmo.RigidBodies = new List <PhysicsModel.RigidBody>();
            _phmo.Nodes       = new List <PhysicsModel.Node>();
            var node = new PhysicsModel.Node();

            node.Child   = -1;
            node.Sibling = -1;
            node.Parent  = -1;
            //the 'default' stringid
            node.Name = new StringId(1);

            _phmo.Nodes.Add(node);

            _phmo.Materials = new List <PhysicsModel.Material>();
            var material = new PhysicsModel.Material();

            //the 'default' stringid
            material.Name        = new StringId(1);
            material.Flags       = -256;
            material.PhantomType = -1;

            _phmo.Materials.Add(material);
        }
Beispiel #5
0
        /// <summary>
        /// Adds planes to the physics model as described by the JSON node
        /// </summary>
        /// <param name="phmo"></param>
        /// <param name="n">a node that is a list of plane equations</param>
        /// <returns>The number of plane-equation tag-blocks added</returns>
        private int AddManyPlanes(PhysicsModel phmo, JSONNode n)
        {
            if (n == null)
            {
                Console.WriteLine("could not find \"Planes\" attribute.");
                return(0);
            }

            if (phmo.PolyhedronPlaneEquations == null)
            {
                phmo.PolyhedronPlaneEquations = new List <PhysicsModel.PolyhedronPlaneEquation>();
            }

            foreach (JSONNode p in n.AsArray)
            {
                var p_vals = p.AsArray;
                var plane  = new PhysicsModel.PolyhedronPlaneEquation
                {
                    Unknown  = p_vals[0].AsFloat,
                    Unknown2 = p_vals[1].AsFloat,
                    Unknown3 = p_vals[2].AsFloat,
                    Unknown4 = p_vals[3].AsFloat
                };

                phmo.PolyhedronPlaneEquations.Add(plane);
            }

            return(n.AsArray.Count);
        }
Beispiel #6
0
        /// <summary>Overridden from <see cref="Engine.EntitySystem.Entity.OnPostCreate(Boolean)"/>.</summary>
        protected override void OnPostCreate(bool loaded)
        {
            base.OnPostCreate(loaded);

            SubscribeToTickEvent();

            //init doorBodyInitPosition and doorBody
            if (PhysicsModel != null)
            {
                for (int n = 0; n < PhysicsModel.Bodies.Length; n++)
                {
                    if (PhysicsModel.Bodies[n].Name == "door" || PhysicsModel.Bodies[n].Name == "door1")
                    {
                        Mat4 transform = PhysicsModel.ModelDeclaration.Bodies[n].GetTransform();
                        doorBody1InitPosition = transform.Item3.ToVec3();
                    }
                    else if (PhysicsModel.Bodies[n].Name == "door2")
                    {
                        Mat4 transform = PhysicsModel.ModelDeclaration.Bodies[n].GetTransform();
                        doorBody2InitPosition = transform.Item3.ToVec3();
                    }
                }

                doorBody1 = PhysicsModel.GetBody("door1");
                if (doorBody1 == null)
                {
                    doorBody1 = PhysicsModel.GetBody("door");
                }
                doorBody2 = PhysicsModel.GetBody("door2");
            }

            UpdateDoorBodies();
            UpdateAttachedObjects();
        }
Beispiel #7
0
        /// <summary>Overridden from <see cref="Engine.EntitySystem.Entity.OnPostCreate(Boolean)"/>.</summary>
        protected override void OnPostCreate(bool loaded)
        {
            base.OnPostCreate(loaded);

            if (EntitySystemWorld.Instance.IsServer() || EntitySystemWorld.Instance.IsSingle())
            {
                const string        regionTypeName = "ManualInfluenceRegion";
                InfluenceRegionType regionType     = (InfluenceRegionType)EntityTypes.Instance.GetByName(
                    regionTypeName);
                if (regionType == null)
                {
                    regionType = (InfluenceRegionType)EntityTypes.Instance.ManualCreateType(
                        regionTypeName,
                        EntityTypes.Instance.GetClassInfoByEntityClassName("InfluenceRegion"));
                    regionType.NetworkType = EntityNetworkTypes.ServerOnly;
                }

                region                  = (InfluenceRegion)Entities.Instance.Create(regionType, Map.Instance);
                region.ShapeType        = Region.ShapeTypes.Capsule;
                region.DistanceFunction = InfluenceRegion.DistanceFunctionType.NormalFadeAxisX;

                region.SetTransform(Position, Rotation, InfluenceRegionScale);
                region.PostCreate();
                region.AllowSave        = false;
                region.EditorSelectable = false;

                bladesMotor = PhysicsModel.GetMotor("bladesMotor") as GearedMotor;
            }

            SubscribeToTickEvent();
        }
Beispiel #8
0
        public override void Intersection(PhysicsModel modelB)
        {
            var delta = (MapObject.Position - modelB.MapObject.Position).Length();

            var radSum = Radius;

            if (modelB is PhysicsSphere)
            {
                radSum += ((PhysicsSphere)modelB).Radius;
            }

            //if (modelB is PhysicsSphere sphere)   // c# 7.0
            //{
            //    radSum += sphere.Radius;
            //}

            if (delta >= radSum)
            {
                return;
            }

            CallOnIntersection(modelB);

            if (IsCollision && modelB.IsCollision)
            {
                var firstModel  = IsSatatic ? modelB : this;
                var secondModel = firstModel == this ? modelB : this;

                var deltaVec = firstModel.MapObject.Position - secondModel.MapObject.Position;
                firstModel.MapObject.Position -= deltaVec / deltaVec.Length() * (delta - radSum);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Initialise the physics model to be built
        /// </summary>
        public PhysicsModelBuilder()
        {
            _phmo = new PhysicsModel
            {
                RigidBodies = new List <PhysicsModel.RigidBody>(),
                Nodes       = new List <PhysicsModel.Node>()
            };
            var node = new PhysicsModel.Node
            {
                Child   = -1,
                Sibling = -1,
                Parent  = -1,
                //the 'default' stringid
                Name = new StringId(1)
            };

            _phmo.Nodes.Add(node);

            _phmo.Materials = new List <PhysicsModel.Material>();
            var material = new PhysicsModel.Material
            {
                //the 'default' stringid
                Name = new StringId(1),
                // ??? material.Flags = -256;
                PhantomType = -1
            };

            _phmo.Materials.Add(material);
        }
Beispiel #10
0
        public bool GetAdvanceAttackTargetPosition(bool alternative, MapObject obj, bool useGravity,
                                                   out Vec3 pos)
        {
            Mode mode = alternative ? alternativeMode : normalMode;

            if (mode.typeMode.BulletType == null)
            {
                Log.Fatal("Gun: GetAdvanceAttackTargetPosition: BulletType = null");
            }

            PhysicsModel objPhysicsModel = obj.PhysicsModel;

            if (objPhysicsModel == null)
            {
                pos = obj.Position;
                return(true);
            }

            Vec3 objPos = obj.Position;

            float bulletVelocity = mode.typeMode.BulletType.Velocity;

            if (bulletVelocity == 0)
            {
                pos = objPos;
                return(true);
            }

            Vec3  diff = objPos - Position;
            float len  = diff.Length();

            float flyTime;

            if (useGravity && mode.typeMode.BulletType.Gravity != 0)
            {
                float sh    = diff.ToVec2().Length();
                float angle = mode.typeMode.BulletType.CalculateDemandedVerticalAngleToHitTarget(sh, diff.Z);

                if (angle != -1)
                {
                    float vh = bulletVelocity * MathFunctions.Cos(angle);
                    flyTime = sh / vh;
                }
                else
                {
                    pos = objPos;
                    return(false);
                }
            }
            else
            {
                flyTime = len / bulletVelocity;
            }

            Vec3 objVelocity = objPhysicsModel.Bodies[0].LinearVelocity;

            pos = objPos + objVelocity * flyTime;
            return(true);
        }
    public void LoadLevel()
    {
        if (levelJsonFile != null)
        {
            RemoveLevel();

            levelObjects = new List <LevelObject>();

            string    data      = levelJsonFile.text;
            LevelData levelData = JsonUtility.FromJson <LevelData>(data);

            audioSource.clip = Resources.Load <AudioClip>("Audio/" + levelData.songName);

            songIndexLength       = levelData.songIndexLength;
            spacingBetweenSamples = levelData.spacingBetweenSamples;
            playerOffset          = levelData.playerOffset;

            songTime            = levelData.songTime;
            levelLength         = levelData.levelLength;
            platform.localScale = new Vector3(levelData.platformScale, 1, 1);

            physicsModel = levelData.physicsModel;

            for (int i = 0; i < levelData.levelObjectData.Count; i++)
            {
                LevelObject levelObject = new LevelObject();

                GameObject levelObjectPrefab = null;
                switch (levelData.levelObjectData[i].feature.type)
                {
                case LevelFeature.features.Spikes:
                    levelObjectPrefab = spikePrefab;
                    break;

                case LevelFeature.features.SlideBlock:
                    levelObjectPrefab = slideBlockPrefab;
                    break;

                case LevelFeature.features.DestructableWalls:
                    break;
                }

                if (levelObject != null)
                {
                    levelObject.gameObject        = Instantiate(levelObjectPrefab, new Vector2(levelData.levelObjectData[i].songPositionIndex * levelData.spacingBetweenSamples + levelData.levelObjectData[i].feature.offset, levelTransform.position.y), Quaternion.identity, levelTransform);
                    levelObject.feature           = levelData.levelObjectData[i].feature;
                    levelObject.songPositionIndex = levelData.levelObjectData[i].songPositionIndex;
                    levelObjects.Add(levelObject);
                }
            }

            lightingEvents = levelData.lightingEventData;

            spectrumData = levelData.spectrumData;
            numberOfBars = levelData.spectrumData[0].spectrum.Length;

            loadedLevel = levelData;
        }
    }
Beispiel #12
0
 public Simulator(Aircraft aircraft, Weather weather)
 {
     Time          = 0;
     _aircraft     = aircraft;
     _weather      = weather;
     _physicsModel = new BasicPhysicsModel(_aircraft, Vector3.zero,
                                           new BasicPhysicsModelData {
         ControlRate      = 10f, DeadZone = 0.2f, Lerp = 0.03f, MaxTurn = 15.0f, AileronTurnRate = 300f,
         ElevatorTurnRate = 3f, RudderTurnRate = 100f
     });
 }
Beispiel #13
0
        ///////////////////////////////////////////

        /// <summary>Overridden from <see cref="Engine.EntitySystem.Entity.OnPostCreate(Boolean)"/>.</summary>
        protected override void OnPostCreate(bool loaded)
        {
            base.OnPostCreate(loaded);
            SubscribeToTickEvent();
            CreateThreads();

            magnetBody = PhysicsModel.GetBody("magnet");
            if (magnetBody != null)
            {
                magnetBody.Collision += magnetBody_Collision;
            }
        }
        /// <summary>Overridden from <see cref="Engine.EntitySystem.Entity.OnPostCreate(Boolean)"/>.</summary>
        protected override void OnPostCreate(bool loaded)
        {
            base.OnPostCreate(loaded);

            SetTurnToPosition(Position + Rotation.GetForward() * 100);
            if (PhysicsModel != null)
            {
                PhysicsModel.PopFromWorld();

                Damager_Ball        = PhysicsModel.GetBody("Damager_Ball");
                Damager_Ball_Player = PhysicsModel.GetBody("CT");

                //if (Damager_Ball_Player != null)
                //{
                //    //this.Type.BallRadius = .5f;//((Damager_Ball_Player.Shapes[0].Volume * 3f) / (4f * (float)Math.PI) * .333333f);
                //    foreach (Body body in PhysicsModel.Bodies)
                //        body.Collision += new Body.CollisionDelegate(body_Collision);
                //}

                if (!EntitySystemWorld.Instance.IsEditor())
                {
                    Damager_Ball_Player.Shapes[0].Density              = PhysicsDensity;
                    Damager_Ball_Player.Shapes[0].DynamicFriction      = PhysicsDynamicFriction;
                    Damager_Ball_Player.Shapes[0].Restitution          = PhysicsBounciness; //Bounciness
                    Damager_Ball_Player.Shapes[0].StaticFriction       = PhysicsStaticFriction;
                    Damager_Ball_Player.Shapes[0].SpecialLiquidDensity = PhysicsLiquidDensity;
                    Damager_Ball_Player.Shapes[0].ContactGroup         = (int)ContactGroup.Dynamic;
                    Damager_Ball_Player.EnableGravity  = true;
                    Damager_Ball_Player.LinearVelocity = linearVelocityForSerialization;
                }

                if (!EntitySystemWorld.Instance.IsEditor())
                {
                    if (Damager_Ball_Player == null)
                    {
                        Log.Error("Damager_Ball.type: \"Damager_Ball\" body does not exist. The Physics Body is Named incorrectly?");
                    }
                }
                SubscribeToTickEvent();
                CheckPhysicsProperties();
                PhysicsModel.PushToWorld();
            }

            //Incin
            //if activeMaxTurrets turret was out from before RemoveMiniTurret it
            //if (turret != null)
            //{
            //    turret.SetForDeletion(false);
            //    turretTimer = 0; //reset remove timer
            //    activeturrets = 0;  //reset turret counts
            //}
        }
Beispiel #15
0
        protected override void OnPostCreate(bool loaded)
        {
            base.OnPostCreate(loaded);

            HelliBody = PhysicsModel.GetBody("Helli");
            if (HelliBody == null)
            {
                Log.Error("Helli: \"Helli\" HelliBody dose not exists.");
                return;
            }

            SubscribeToTickEvent();
        }
Beispiel #16
0
        protected override void OnPostCreate(bool loaded)
        {
            base.OnPostCreate(loaded);

            AKJetBody = PhysicsModel.GetBody("Jet");
            if (AKJetBody == null)
            {
                Log.Error("AKJet: \"AKJet\" AKJetBody does not exist.");
                return;
            }
            Stall = false;
            AddTimer();
        }
Beispiel #17
0
        /// <summary>Overridden from <see cref="Engine.EntitySystem.Entity.OnPostCreate(Boolean)"/>.</summary>
        protected override void OnPostCreate(bool loaded)
        {
            base.OnPostCreate(loaded);
            AddTimer();
            if (!EngineApp.Instance.IsResourceEditor)
            {
                if (PhysicsModel == null)
                {
                    Log.Error("Forklift: Physics model not exists.");
                    return;
                }

                forkliftBody = PhysicsModel.GetBody("forklift");
                if (forkliftBody == null)
                {
                    Log.Error("Forklift: \"forklift\" body not exists.");
                    return;
                }

                leftwheelBody      = PhysicsModel.GetBody("leftwheel");
                rightwheelBody     = PhysicsModel.GetBody("rightwheel");
                forkBody           = PhysicsModel.GetBody("fork");
                up1Body            = PhysicsModel.GetBody("up1");
                up2Body            = PhysicsModel.GetBody("up2");
                b2Body             = PhysicsModel.GetBody("b2");
                b1Body             = PhysicsModel.GetBody("b1");
                wheelRearRightBody = PhysicsModel.GetBody("wheelRearRight");
                wheelRearLeftBody  = PhysicsModel.GetBody("wheelRearLeft");
                foreach (MapObjectAttachedObject attachedObject in AttachedObjects)
                {
                    if (attachedObject.Alias == "leftWheel")
                    {
                        leftWheel.wheelHelpers.Add((MapObjectAttachedHelper)attachedObject);
                    }
                    if (attachedObject.Alias == "rightWheel")
                    {
                        rightWheel.wheelHelpers.Add((MapObjectAttachedHelper)attachedObject);
                    }
                }

                if (leftWheel.wheelHelpers.Count != 0)
                {
                    wheelsPositionYOffset = Math.Abs(leftWheel.wheelHelpers[0].PositionOffset.Y);
                }
            }
            //initialize currentGear
            currentGear = Type.Gears.Find(delegate(ForkliftType.Gear gear)
            {
                return(gear.Number == 0);
            });
        }
Beispiel #18
0
 private PhysicsModel ConvertPhysicsModel(CachedTag instance, PhysicsModel phmo)
 {
     phmo.MoppData = HavokConverter.ConvertHkpMoppData(BlamCache.Version, CacheContext.Version, phmo.MoppData);
     if (BlamCache.Version == CacheVersion.HaloReach)
     {
         foreach (var rigidbody in phmo.RigidBodies)
         {
             rigidbody.MotionType = rigidbody.MotionType_Reach;
             rigidbody.ShapeType  = rigidbody.ShapeType_Reach;
             rigidbody.ShapeIndex = rigidbody.ShapeIndex_Reach;
             rigidbody.Mass       = rigidbody.Mass_Reach;
         }
     }
     return(phmo);
 }
Beispiel #19
0
        protected override void OnPostCreate(bool loaded)
        {
            base.OnPostCreate(loaded);

            AKVTOLBody = PhysicsModel.GetBody("Jet");
            if (AKVTOLBody == null)
            {
                Log.Error("AKVTOL: \"AKVTOL\" AKVTOLBody dose not exists.");
                return;
            }

            AddTimer();

            EngineDir = 90f;
        }
Beispiel #20
0
        private void MohiOff()
        {
            //turning off some stuff when you are getting out of helli
            GearedMotor main = PhysicsModel.GetMotor("hellimain") as GearedMotor;
            GearedMotor back = PhysicsModel.GetMotor("helliback") as GearedMotor;

            main.Enabled = false;
            back.Enabled = false;

            if (rotorSoundChannel != null)
            {
                rotorSoundChannel.Stop();
                rotorSoundChannel = null;
            }
        }
    public void GenerateLevelFromSamples(FrequencyBand[] frequencyBands, float _songTime)
    {
        levelObjects    = new List <LevelObject>();
        songIndexLength = frequencyBands[0].spectralFluxSamples.Count;
        levelLength     = (songIndexLength * spacingBetweenSamples);

        songTime = _songTime;

        //Scale level to the length of the song
        platform.localScale = new Vector3(levelLength + 15, 1, 1);

        physicsModel = new PhysicsModel();

        //Set physics model
        physicsModel.gravity          = Mathf.Abs(Physics2D.gravity.y * player.rigidbody.gravityScale);
        physicsModel.velocity         = levelLength / songTime;
        physicsModel.jumpAcceleration = player.GetJumpAcceleration();
        physicsModel.CalculatePhysicsModel();

        //Sort level based on priority
        Array.Sort(levelFeatures, delegate(LevelFeature feature1, LevelFeature feature2) { return(feature1.priority.CompareTo(feature2.priority)); });

        for (int i = 0; i < levelFeatures.Length; i++)
        {
            switch (levelFeatures[i].type)
            {
            case LevelFeature.features.Spikes:
                CreateLevelObjects(spikePrefab, frequencyBands[levelFeatures[i].bandIndex], ref levelFeatures[i]);
                break;

            case LevelFeature.features.SlideBlock:
                CreateLevelObjects(slideBlockPrefab, frequencyBands[levelFeatures[i].bandIndex], ref levelFeatures[i]);
                break;

            case LevelFeature.features.DestructableWalls:
                break;

            case LevelFeature.features.LevelHeight:
                break;

            case LevelFeature.features.Lighting:
                CreateLightingEvents(frequencyBands[levelFeatures[i].bandIndex]);
                break;
            }
        }

        CleanUpLevel();
    }
Beispiel #22
0
        protected override void OnPostCreate(bool loaded)
        {
            base.OnPostCreate(loaded);

            SubscribeToTickEvent();

            if (EntitySystemWorld.Instance.WorldSimulationType != WorldSimulationTypes.Editor)
            {
                if (PhysicsModel == null)
                {
                    Log.Error("Class AKCar: Physics model not exists.");
                    return;
                }

                chassisBody = PhysicsModel.GetBody("AKCar");
                if (chassisBody == null)
                {
                    Log.Error("Class AKCar: \"AKCar\" body dose not exists.");
                    return;
                }

                //chassisBody.Collision += chassisBody_Collision;

                foreach (MapObjectAttachedObject attachedObject in AttachedObjects)
                {
                    if (attachedObject.Alias == "leftTrack")
                    {
                        leftTrack.trackHelpers.Add((MapObjectAttachedHelper)attachedObject);
                    }
                    if (attachedObject.Alias == "rightTrack")
                    {
                        rightTrack.trackHelpers.Add((MapObjectAttachedHelper)attachedObject);
                    }
                }

                if (leftTrack.trackHelpers.Count != 0)
                {
                    tracksPositionYOffset = Math.Abs(leftTrack.trackHelpers[0].PositionOffset.Y);
                }
            }

            //initialize currentGear
            currentGear = Type.Gears.Find(delegate(AKCarType.Gear gear)
            {
                return(gear.Number == 0);
            });
        }
Beispiel #23
0
        /// <summary>
        /// Adds Four-vertex tag-blocks to the physics model. For lists
        /// of vertices that are not multiples of four, the last vertex
        /// is copied.
        /// </summary>
        /// <param name="phmo"></param>
        /// <param name="n">a node that is a list of vertex equations</param>
        /// <returns>the number of four-vertex tag-blocks added.</returns>
        private int AddManyFVS(PhysicsModel phmo, JSONNode n)
        {
            if (n == null)
            {
                Console.WriteLine("could not find \"Vertices\" attribute.");
                return(0);
            }

            if (phmo.PolyhedronFourVectors == null)
            {
                phmo.PolyhedronFourVectors = new List <PhysicsModel.PolyhedronFourVector>();
            }

            int vertCount = n.AsArray.Count;
            int numfvs    = vertCount / 4 + ((vertCount % 4) > 0 ? 1 : 0);

            for (int i = 0; i < numfvs; ++i)
            {
                JSONNode v0 = (i * 4) < vertCount ? n.AsArray[i * 4] : n.AsArray[vertCount - 1];
                JSONNode v1 = (i * 4 + 1) < vertCount ? n.AsArray[i * 4 + 1] : n.AsArray[vertCount - 1];
                JSONNode v2 = (i * 4 + 2) < vertCount ? n.AsArray[i * 4 + 2] : n.AsArray[vertCount - 1];
                JSONNode v3 = (i * 4 + 3) < vertCount ? n.AsArray[i * 4 + 3] : n.AsArray[vertCount - 1];

                var fourvert = new PhysicsModel.PolyhedronFourVector();

                //The plugin had these named incorrectly, the four vectors are really
                //four vertices, with the coordinates grouped (four X's, four Y's, four Z's)
                //This is likely done for SIMD. If the number of vertices aren't a multiple
                //of four, usually the last vertex is copied several times.
                fourvert.FourVectorsX.I     = v0.AsArray[0].AsFloat;
                fourvert.FourVectorsX.J     = v1.AsArray[0].AsFloat;
                fourvert.FourVectorsX.K     = v2.AsArray[0].AsFloat;
                fourvert.FourVectorsXRadius = v3.AsArray[0].AsFloat;
                fourvert.FourVectorsY.I     = v0.AsArray[1].AsFloat;
                fourvert.FourVectorsY.J     = v1.AsArray[1].AsFloat;
                fourvert.FourVectorsY.K     = v2.AsArray[1].AsFloat;
                fourvert.FourVectorsYRadius = v3.AsArray[1].AsFloat;
                fourvert.FourVectorsZ.I     = v0.AsArray[2].AsFloat;
                fourvert.FourVectorsZ.J     = v1.AsArray[2].AsFloat;
                fourvert.FourVectorsZ.K     = v2.AsArray[2].AsFloat;
                fourvert.FourVectorsZRadius = v3.AsArray[2].AsFloat;

                phmo.PolyhedronFourVectors.Add(fourvert);
            }

            return(numfvs);
        }
        protected void CheckPhysicsProperties()
        {
            if (Damager_Ball_Player != null)
            {
                PhysicsModel.PopFromWorld();
                Damager_Ball_Player.Shapes[0].Density              = PhysicsDensity;
                Damager_Ball_Player.Shapes[0].DynamicFriction      = PhysicsDynamicFriction;
                Damager_Ball_Player.Shapes[0].Restitution          = PhysicsBounciness;//Bounciness
                Damager_Ball_Player.Shapes[0].StaticFriction       = PhysicsStaticFriction;
                Damager_Ball_Player.Shapes[0].SpecialLiquidDensity = PhysicsLiquidDensity;
                Damager_Ball_Player.Shapes[0].ContactGroup         = (int)ContactGroup.Dynamic;
                Damager_Ball_Player.EnableGravity = true;

                PhysicsModel.PushToWorld();
                //GameEngineApp.Instance.AddScreenMessage("Physics Updated");
            }
        }
Beispiel #25
0
        bool DoPathFind()
        {
            Dynamic targetObj = null;

            {
                //not true because use Intellect
                RTSUnitAI ai = Intellect as RTSUnitAI;
                if (ai != null)
                {
                    targetObj = ai.CurrentTask.Entity;
                }
            }

            GridPathFindSystem.Instance.RemoveObjectFromMotionMap(this);

            Bounds bounds = PhysicsModel.GetGlobalBounds();

            float radius     = Type.Radius;
            Rect  targetRect = new Rect(MovePosition.ToVec2() - new Vec2(radius, radius),
                                        MovePosition.ToVec2() + new Vec2(radius, radius));

            if (targetObj != null && targetObj != this)
            {
                GridPathFindSystem.Instance.RemoveObjectFromMotionMap(targetObj);
            }

            GridPathFindSystem.Instance.DoTempClearMotionMap(targetRect);

            const int maxFieldsDistance = 1000;
            const int maxFieldsToCheck  = 100000;

            bool found = GridPathFindSystem.Instance.DoFind(Type.Radius * 2 * 1.1f, Position.ToVec2(),
                                                            MovePosition.ToVec2(), maxFieldsDistance, maxFieldsToCheck, true, false, path);

            GridPathFindSystem.Instance.RestoreAllTempClearedMotionMap();

            if (targetObj != null && targetObj != this)
            {
                GridPathFindSystem.Instance.AddObjectToMotionMap(targetObj);
            }

            GridPathFindSystem.Instance.AddObjectToMotionMap(this);

            return(found);
        }
Beispiel #26
0
        /// <summary>
        /// Finds the type of the shape and adds it. Currently, only 'Polyhedron' is supported.
        /// </summary>
        /// <param name="phmo">the tag to add the shape to</param>
        /// <param name="n">the json node from which to parse the shape description.</param>
        /// <returns>shape type added, 'Unused0' is used to represent failure.</returns>
        private ShapeTypes AddShape(PhysicsModel phmo, JSONNode n)
        {
            if (n == null)
            {
                return(ShapeTypes.Unused0);
            }

            //an element of the top-level JSON array is a map
            // containing values for keys: 'Type', 'Data'
            switch (n["Type"])
            {
            case "Polyhedron":
                return(AddPolyhedron(phmo, n["Data"]) ? ShapeTypes.Polyhedron : ShapeTypes.Unused0);

            default:
                return(ShapeTypes.Unused0);
            }
        }
Beispiel #27
0
        /// <summary>
        /// Finds the type of the shape and adds it. Currently, only 'Polyhedron' is supported.
        /// </summary>
        /// <param name="phmo">the tag to add the shape to</param>
        /// <param name="n">the json node from which to parse the shape description.</param>
        /// <returns>shape type added, 'Unused0' is used to represent failure.</returns>
        private HavokShapeType AddShape(PhysicsModel phmo, JSONNode n)
        {
            if (n == null)
            {
                return(HavokShapeType.TriangleMesh);
            }

            //an element of the top-level JSON array is a map
            // containing values for keys: 'Type', 'Data'
            switch (n["Type"])
            {
            case "Polyhedron":
                return(AddPolyhedron(phmo, n["Data"]) ? HavokShapeType.Polyhedron : HavokShapeType.TriangleMesh);

            default:
                return(HavokShapeType.TriangleMesh);
            }
        }
Beispiel #28
0
        /// <summary>Overridden from <see cref="Engine.EntitySystem.Entity.OnPostCreate(Boolean)"/>.</summary>
        protected override void OnPostCreate(bool loaded)
        {
            base.OnPostCreate(loaded);

            pathFindWaitTime = World.Instance.Random.NextFloat();

            CreatePhysicsModel();

            Body body = PhysicsModel.CreateBody();

            mainBody      = body;
            body.Name     = "main";
            body.Static   = true;
            body.Position = Position;
            body.Rotation = Rotation;

            float length = Type.Height - Type.Radius * 2;

            if (length < 0)
            {
                Log.Error("Length < 0");
                return;
            }
            CapsuleShape shape = body.CreateCapsuleShape();

            shape.Length       = length;
            shape.Radius       = Type.Radius;
            shape.ContactGroup = (int)ContactGroup.Dynamic;

            AddTimer();

            //!!!!!need?
            //for update in GridPathFindSystem
            Vec3 p = Position;

            Position = p;

            PhysicsModel.PushToWorld();

            if (mainBody != null)
            {
                oldMainBodyPosition = mainBody.Position;
            }
        }
        void UpdatePhysicsModel()
        {
            DestroyPhysicsModel();

            if (active)
            {
                CreatePhysicsModel();

                Body body = PhysicsModel.CreateBody();
                body.Static = true;
                body.SetTransform(Position, Rotation);

                BoxShape shape = body.CreateBoxShape();
                shape.ContactGroup = (int)ContactGroup.Dynamic;                // Static;
                shape.Dimensions   = Scale;

                body.PushedToWorld = true;
            }
        }
Beispiel #30
0
        void TickIntellect()
        {
            //horizontalMotor
            {
                float throttle = 0;
                throttle += Intellect.GetControlKeyStrength(GameControlKeys.Left);
                throttle -= Intellect.GetControlKeyStrength(GameControlKeys.Right);

                GearedMotor motor = PhysicsModel.GetMotor("horizontalMotor") as GearedMotor;
                if (motor != null)
                {
                    motor.Throttle = throttle;
                }
            }

            //gibbetMotor
            {
                ServoMotor motor = PhysicsModel.GetMotor("gibbetMotor") as ServoMotor;
                if (motor != null)
                {
                    Radian needAngle = motor.DesiredAngle;

                    needAngle += Intellect.GetControlKeyStrength(GameControlKeys.Forward) * .004f;
                    needAngle -= Intellect.GetControlKeyStrength(GameControlKeys.Backward) * .004f;

                    MathFunctions.Clamp(ref needAngle,
                                        new Degree(-20.0f).InRadians(), new Degree(40.0f).InRadians());

                    motor.DesiredAngle = needAngle;
                }
            }

            //Change player LookDirection at rotation
            PlayerIntellect intellect = Intellect as PlayerIntellect;

            if (intellect != null)
            {
                Vec3 lookVector = intellect.LookDirection.GetVector();
                lookVector *= OldRotation.GetInverse();
                lookVector *= Rotation;
                intellect.LookDirection = SphereDir.FromVector(lookVector);
            }
        }