Esempio n. 1
0
 ///<summary>
 /// Updates the material properties associated with the constraint.
 ///</summary>
 ///<param name="materialA">Material associated with the first entity of the pair.</param>
 ///<param name="materialB">Material associated with the second entity of the pair.</param>
 public void UpdateMaterialProperties(PhysicsMaterial materialA, PhysicsMaterial materialB)
 {
     if (materialA != null && materialB != null)
     {
         PhysicsMaterialManager.GetInteractionProperties(materialA, materialB, out materialInteraction);
     }
     else if (materialA == null && materialB != null)
     {
         materialInteraction.KineticFriction = materialB.kineticFriction;
         materialInteraction.StaticFriction  = materialB.staticFriction;
         materialInteraction.Bounciness      = materialB.bounciness;
     }
     else if (materialA != null)
     {
         materialInteraction.KineticFriction = materialA.kineticFriction;
         materialInteraction.StaticFriction  = materialA.staticFriction;
         materialInteraction.Bounciness      = materialA.bounciness;
     }
     else
     {
         materialInteraction.KineticFriction = 0;
         materialInteraction.StaticFriction  = 0;
         materialInteraction.Bounciness      = 0;
     }
 }
    protected override void OnCreate()
    {
        base.OnCreate();

        _tileColliderArchetype = EntityManager.CreateArchetype(
            typeof(TileColliderTag),
            typeof(FixTranslation),
            typeof(PhysicsColliderBlob));

        // Create tile collider
        BoxGeometry boxGeometry = new BoxGeometry()
        {
            Size = float2(1, 1)
        };
        PolygonGeometry triangleGeometry = new PolygonGeometry()
        {
            Vertices = new NativeArray <float2>(new float2[] {
                new float2(-.5f, -.5f),
                new float2(-.5f, .5f),
                new float2(.5f, -0.5f),
            }, Allocator.Temp)
        };
        CollisionFilter filter   = CollisionFilter.FromLayer(SimulationGameConstants.Physics.LAYER_TERRAIN);
        PhysicsMaterial material = PhysicsMaterial.Default;

        _fullTileCollider   = Collider.Create(boxGeometry, filter, material);
        _cornerTileCollider = Collider.Create(triangleGeometry);
    }
Esempio n. 3
0
 protected override void LoadContent()
 {
     Block.Initialize();
     PhysicsMaterial.Initialize();
     RenderingMaterial.Initialize();
     RenderQueue.Initialize();
 }
Esempio n. 4
0
        protected void TryToAdd(Collidable a, Collidable b, PhysicsMaterial materialA, PhysicsMaterial materialB)
        {
            CollisionRule rule;

            if ((rule = CollisionRules.collisionRuleCalculator(a, b)) < CollisionRule.NoNarrowPhasePair)
            {
                //Clamp the rule to the parent's rule.  Always use the more restrictive option.
                //Don't have to test for NoNarrowPhasePair rule on the parent's rule because then the parent wouldn't exist!
                if (rule < CollisionRule)
                {
                    rule = CollisionRule;
                }
                var pair = new CollidablePair(a, b);
                if (!subPairs.ContainsKey(pair))
                {
                    var newPair = NarrowPhaseHelper.GetPairHandler(ref pair, rule);
                    if (newPair != null)
                    {
                        newPair.UpdateMaterialProperties(materialA, materialB);  //Override the materials, if necessary.
                        newPair.Parent = this;
                        subPairs.Add(pair, newPair);
                    }
                }
                containedPairs.Add(pair);
            }
        }
Esempio n. 5
0
    private List <Spatial> create_links(int N)
    {
        List <Spatial>  links         = new List <Spatial>();
        PhysicsMaterial link_phys_mat = new PhysicsMaterial();

        SpatialMaterial link_mesh_mat = new SpatialMaterial();

        link_mesh_mat.AlbedoColor = new Color(0.5F, 0.5F, 0.5F, 1F);
        for (int i = 0; i <= N; i++)
        {
            RigidBody link = new RigidBody();
            link.Name         = String.Format("l{0}", i);
            link.CanSleep     = false;
            link.ContinuousCd = true;

            Vector3 link_dimensions = new Vector3(0.2F, 0.8F, 0.1F);

            MeshInstance link_mesh = create_link_mesh(
                String.Format("{0}_mesh", link.Name),
                link_dimensions,
                link_mesh_mat);
            CollisionShape link_col = create_link_collision(
                String.Format("{0}_col", link.Name),
                link_dimensions);

            link.AddChild(link_mesh);
            link.AddChild(link_col);

            links.Add(link);
        }
        return(links);
    }
Esempio n. 6
0
    private StaticBody generate_static(string name)
    {
        StaticBody node = new StaticBody();

        node.Name = name;
        PhysicsMaterial mat = new PhysicsMaterial();

        node.PhysicsMaterialOverride = mat;

        Vector3 stat_size = new Vector3(0.7F, 0.2F, 0.7F);

        MeshInstance node_mesh = create_link_mesh(
            String.Format("{0}_mesh", name),
            stat_size,
            new SpatialMaterial()
            );
        CollisionShape node_col = create_link_collision(
            String.Format("{0}_col", name),
            stat_size
            );

        node.AddChild(node_mesh);
        node.AddChild(node_col);
        return(node);
    }
Esempio n. 7
0
 void OnMaterialChanged(PhysicsMaterial newMaterial)
 {
     for (int i = 0; i < collisionInformation.pairs.Count; i++)
     {
         collisionInformation.pairs[i].UpdateMaterialProperties();
     }
 }
Esempio n. 8
0
        private static StaticBody generate_base(Vector3 dims)
        {
            string base_name = String.Format("{0}_base", bot_name);

            DEBUG_PRINT("Generating static base...");

            StaticBody node = new StaticBody();

            node.Name = base_name;

            PhysicsMaterial mat = new PhysicsMaterial();

            node.PhysicsMaterialOverride = mat;

            MeshInstance base_mesh = create_link_mesh(
                String.Format("{0}_mesh", base_name),
                dims,
                new SpatialMaterial()
                );
            CollisionShape base_col = create_link_collision(
                String.Format("{0}_col", base_name),
                dims
                );

            node.AddChild(base_mesh);
            node.AddChild(base_col);

            DEBUG_PRINT("Finished generating base.");

            return(node);
        }
Esempio n. 9
0
 protected virtual void OnMaterialChanged(PhysicsMaterial newMaterial)
 {
     for (int i = 0; i < pairs.Count; i++)
     {
         pairs[i].UpdateMaterialProperties();
     }
 }
 public void Create()
 {
     material                 = GetComponent <RigidBodyComponent>().RigidBody.Material;
     material.Restitution     = bounce;
     material.StaticFriction  = staticFriction;
     material.DynamicFriction = dynamicFriction;
 }
Esempio n. 11
0
 public override void Update(GameTime gameTime)
 {
     if (!_createdBoxes)
     {
         _createdBoxes = true;
         var scale = Vector3.One * 20f;
         for (int i = 0; i < 10; i++)
         {
             Parent.AddComponent(
                 new Drawable3DComponent(RootComponent.ModelData)
             {
                 Position = new Vector3(i + 5, 0f, 0f) * scale.X,
                 Scale    = scale
             }
                 );
         }
         var material = new PhysicsMaterial("box")
         {
             Friction = 0.8f
         };
         Parent.AddComponent(
             new StaticBodyComponent(new Box(2f, 2f, 2f, 1f))
         {
             Material = material,
         }
             );
         Parent.Scale = scale;
     }
 }
 internal CompoundChild(CompoundShape shape, EntityCollidable collisionInformation, PhysicsMaterial material, int index)
 {
     this.shape = shape;
     this.collisionInformation = collisionInformation;
     Material        = material;
     this.shapeIndex = index;
 }
Esempio n. 13
0
 ///<summary>
 /// Forces an update of the pair's material properties.
 ///</summary>
 ///<param name="a">Material of the first member of the pair.</param>
 ///<param name="b">Material of the second member of the pair.</param>
 public override void UpdateMaterialProperties(PhysicsMaterial a, PhysicsMaterial b)
 {
     foreach (CollidablePairHandler pairHandler in subPairs.Values)
     {
         pairHandler.UpdateMaterialProperties(a, b);
     }
 }
Esempio n. 14
0
        /// <summary>
        /// Creates GUI elements for fields common to all colliders.
        /// </summary>
        protected virtual void BuildGUI(Collider collider)
        {
            isTriggerField.OnChanged += x => { collider.Trigger = x; MarkAsModified(); ConfirmModify(); };

            massField.OnChanged   += x => { collider.Mass = x; MarkAsModified(); };
            massField.OnConfirmed += ConfirmModify;
            massField.OnFocusLost += ConfirmModify;

            materialField.OnChanged += x =>
            {
                PhysicsMaterial mesh = Resources.Load <PhysicsMaterial>(x.UUID);
                collider.Material = mesh;

                MarkAsModified();
                ConfirmModify();
            };

            contactOffsetField.OnChanged   += x => { collider.ContactOffset = x; MarkAsModified(); };
            contactOffsetField.OnConfirmed += ConfirmModify;
            contactOffsetField.OnFocusLost += ConfirmModify;

            restOffsetField.OnChanged   += x => { collider.RestOffset = x; MarkAsModified(); };
            restOffsetField.OnConfirmed += ConfirmModify;
            restOffsetField.OnFocusLost += ConfirmModify;

            collisionReportModeField.OnSelectionChanged += x =>
            {
                collider.CollisionReportMode = (CollisionReportMode)x;

                MarkAsModified();
                ConfirmModify();
            };

            layerField.OnSelectionChanged += x =>
            {
                ulong  layer  = 0;
                bool[] states = layerField.States;
                for (int i = 0; i < states.Length; i++)
                {
                    layer |= states[i] ? Layers.Values[i] : 0;
                }

                layersValue    = layer;
                collider.Layer = layer;

                MarkAsModified();
                ConfirmModify();
            };

            Layout.AddElement(isTriggerField);
            Layout.AddElement(massField);
            Layout.AddElement(materialField);
            Layout.AddElement(contactOffsetField);
            Layout.AddElement(restOffsetField);
            Layout.AddElement(collisionReportModeField);
            Layout.AddElement(layerField);
        }
Esempio n. 15
0
        /// <summary>
        /// Creates a new physics material with the default properties in the specified folder.
        /// </summary>
        /// <param name="folder">Folder relative to project library to create the material in.</param>
        public static void CreateEmptyPhysicsMaterial(string folder)
        {
            string path = Path.Combine(folder, "New Physics Material.asset");

            path = GetUniquePath(path);

            PhysicsMaterial material = new PhysicsMaterial();

            ProjectLibrary.Create(material, path);
        }
        /// <summary>
        /// Sets the material for the tile at the given x and y to the given material.
        /// </summary>
        /// <param name="_x"></param>
        /// <param name="_y"></param>
        /// <param name="_material"></param>
        public void SetTileMaterial(int _x, int _y, PhysicsMaterial _material)
        {
            var tileGO = tileGameObjects[_x, _y];
            var rbc    = tileGO.GetComponent <RigidBodyComponent>();

            if (rbc != null)
            {
                rbc.RigidBody.Material = _material;
            }
        }
Esempio n. 17
0
        ///<summary>
        /// Performs common initialization.
        ///</summary>
        protected StaticCollidable()
        {
            collisionRules.group = CollisionRules.DefaultKinematicCollisionGroup;
            //Note that the Events manager is not created here.  That is left for subclasses to implement so that the type is more specific.
            //Entities can get away with having EntityCollidable specificity since you generally care more about the entity than the collidable,
            //but with static objects, the collidable is the only important object.  It would be annoying to cast to the type you know it is every time
            //just to get access to some type-specific properties.

            material = new PhysicsMaterial();
            materialChangedDelegate   = OnMaterialChanged;
            material.MaterialChanged += materialChangedDelegate;
        }
        /// <summary>
        /// Loads the given file (full directory) from disk and returns the name of the loaded level.
        /// </summary>
        /// <param name="_loadFile">Directory for the save level XML file.</param>
        /// <param name="_loadDataFile">Directory for the save level data XML file.</param>
        public string Load(string _loadFile, string _loadDataFile)
        {
            Clear();
            var levelName = World.Current.Load(_loadFile);

            //Debug.Log("Loading level data for level: " + levelName + " from: " + _loadDataFile);

            using (var xmlReader = XmlReader.Create(_loadDataFile))
            {
                while (xmlReader.Read())
                {
                    if (xmlReader.IsStartElement())
                    {
                        switch (xmlReader.Name)
                        {
                        case "PlatformProperties":
                            var x        = int.Parse(xmlReader["X"]);
                            var y        = int.Parse(xmlReader["Y"]);
                            var material = new PhysicsMaterial();
                            material.Restitution     = float.Parse(xmlReader["Restitution"]);
                            material.StaticFriction  = float.Parse(xmlReader["StaticFriction"]);
                            material.DynamicFriction = float.Parse(xmlReader["DynamicFriction"]);
                            SetTileMaterial(x, y, material);
                            break;

                        case "CoinPickup":
                            var cX = int.Parse(xmlReader["X"]);
                            var cY = int.Parse(xmlReader["Y"]);
                            AddCoinPickup(new Vector2(cX, cY));
                            break;

                        case "BouncePad":
                            var pX         = int.Parse(xmlReader["X"]);
                            var pY         = int.Parse(xmlReader["Y"]);
                            var stiff      = float.Parse(xmlReader["Stiffness"]);
                            var rest       = float.Parse(xmlReader["RestLength"]);
                            var dampen     = float.Parse(xmlReader["Dampen"]);
                            var pad        = AddBouncePad(new Vector2(pX, pY));
                            var springComp = pad.GetComponent <SpringJointComponent>();
                            springComp.stiffness  = stiff;
                            springComp.restLength = rest;
                            springComp.dampen     = dampen;
                            break;
                        }
                    }
                }
            }

            //Debug.Log("Finished loading level data for level: " + levelName);
            return(levelName);
        }
Esempio n. 19
0
        static PhysicsMaterialLibrary()
        {
            Rubber   = new PhysicsMaterial(1, 0.75f, 1);
            Concrete = new PhysicsMaterial(0.75f, 0.5f, 0.35f);
            Wood     = new PhysicsMaterial(0.35f, 0.2f, 0.25f);
            Iron     = new PhysicsMaterial(0.8f, 0.25f, 0.45f);
            Steel    = new PhysicsMaterial(0.75f, 0.5f, 0.75f);
            Ice      = new PhysicsMaterial(0.05f, 0.01f, 0.15f);

            LowFricLowRest   = new PhysicsMaterial(0.05f, 0.01f, 0f);
            HighFricLowRest  = new PhysicsMaterial(0.8f, 0.65f, 0f);
            LowFricHighRest  = new PhysicsMaterial(0.05f, 0.01f, 1f);
            HighFricHighRest = new PhysicsMaterial(0.8f, 0.65f, 1f);
        }
Esempio n. 20
0
        protected Entity()
        {
            InitializeId();

            BufferedStates = new EntityBufferedStates(this);

            material = new PhysicsMaterial();
            materialChangedDelegate   = OnMaterialChanged;
            material.MaterialChanged += materialChangedDelegate;

            shapeChangedDelegate = OnShapeChanged;

            activityInformation = new SimulationIslandMember(this);
        }
Esempio n. 21
0
        static public BlockMissionObject DrawFBXMeshMissionObjectAt(Mission mission, Vec3 pos, string filename)
        {
            // if (prefab == null)

            GameEntity prefab = GameEntity.CreateEmpty(mission.Scene, false);


            prefab.EntityFlags |= EntityFlags.DontSaveToScene;

            //prefab.AddMesh(Mesh.GetFromResource("order_arrow_a"), true);

            //   prefab.SetVisibilityExcludeParents(true);

            if (MeshListByFileName.ContainsKey(filename) == false)
            {
                MeshListByFileName.Add(filename, CreateMesh(filename));
            }
            foreach (var mesh in MeshListByFileName[filename])
            {
                prefab.AddMesh(mesh, false);
            }
            prefab.RecomputeBoundingBox();
            PhysicsShape shape = prefab.GetBodyShape();

            // shape.
            prefab.AddPhysics(1000, new Vec3(0, 0, 0), null, new Vec3(), new Vec3(), PhysicsMaterial.GetFromIndex(0), false, 0);

            GameEntity blockEntity = prefab;


            MatrixFrame identity2 = MatrixFrame.Identity;

            identity2.origin    = pos;
            identity2.origin.x += 7.5f;

            identity2.origin.z = 7.5f;
            identity2.rotation.ApplyScaleLocal(1f);
            MatrixFrame frame2 = identity2;

            blockEntity.SetFrame(ref frame2);
            blockEntity.SetVisibilityExcludeParents(true);
            blockEntity.SetAlpha(1f);
            blockEntity.CreateAndAddScriptComponent("BlockMissionObject");

            BlockMissionObject missionObject = blockEntity.GetFirstScriptOfType <BlockMissionObject>();

            mission.AddActiveMissionObject(missionObject);
            return(missionObject);
        }
Esempio n. 22
0
        /// <inheritdoc/>
        protected internal override InspectableState Refresh()
        {
            PhysicsMaterial material = InspectedObject as PhysicsMaterial;

            if (material == null)
            {
                return(InspectableState.NotModified);
            }

            staticFrictionField.Value  = material.StaticFriction;
            dynamicFrictionField.Value = material.DynamicFriction;
            restitutionField.Value     = material.Restitution;

            return(InspectableState.NotModified);
        }
Esempio n. 23
0
        public Entity FromGlobals()
        {
            var globalEntity = new GlobalSettings();

            globalEntity.FriendlyName = "Globals";
            var globalMaterials = new MaterialListComponent(globalEntity);

            for (var i = 0; i < this.Map.Globals.MaterialDefinitions.Length; i++)
            {
                var def = this.Map.Globals.MaterialDefinitions[i];
                var mat = new PhysicsMaterial(i, def.Friction, def.Friction, def.Restitution);

                globalMaterials.AddPhysicsMaterial(mat);
            }

            globalEntity.SetComponents(new Component[] { globalMaterials });
            return(globalEntity);
        }
Esempio n. 24
0
        public override void Initialize()
        {
            base.Initialize();

            var material = new PhysicsMaterial("player")
            {
                Restitution        = 1f,
                LinearDamping      = 1f,
                LinearDampingLimit = 0.1f,
            };

            Body = new DynamicBodyComponent(
                new Box(2f, 2f, 2f, 1f)
                )
            {
                Position = new Vector3(0, 0f, 0f),
                Material = material,
            };
            Parent.AddComponent(Body);
        }
Esempio n. 25
0
        public PhysicsBody2D(GameObject parent, string name, Shape shape, PhysicsMaterial material, PhysicsEngine.BodyType bodyType) : base(name)
        {
            this.transform.parent = parent.transform;
            this.material         = material;
            this.shape            = shape;
            if (this.shape is AABB)
            {
                ((AABB)this.shape).transform = this.transform;
            }
            this.flagBodyType = bodyType;

            collisionCallbacks = new List <Collision2D.OnCollision>();
            collisions         = new List <Collision2D>();
            collisions_dead    = new List <Collision2D>();

            chunks = new List <PhysicsBoundingChunk2D>();

            // Set up some defaults, to ensure nothing goes horribly wrong
            Height = PhysicsEngine.PhysicsSettings.DEFAULT_BODY2D_HEIGHT;

            // A body flagged as static cannot be anything but static
            if (flagBodyType.HasFlag(PhysicsEngine.BodyType.STATIC))
            {
                if (flagBodyType.HasFlag(PhysicsEngine.BodyType.RIGID))
                {
                    flagBodyType &= ~PhysicsEngine.BodyType.RIGID;
                }
                if (flagBodyType.HasFlag(PhysicsEngine.BodyType.SIMPLE))
                {
                    flagBodyType &= ~PhysicsEngine.BodyType.SIMPLE;
                }
                if (flagBodyType.HasFlag(PhysicsEngine.BodyType.KINEMATIC))
                {
                    flagBodyType &= ~PhysicsEngine.BodyType.KINEMATIC;
                }
            }

            //PhysicsEngine.AddPhysicsBody(this);
        }
Esempio n. 26
0
        private static List <Spatial> generate_links()
        {
            List <Spatial> links = new List <Spatial>();

            PhysicsMaterial phys_mat = new PhysicsMaterial();
            SpatialMaterial spat_mat = new SpatialMaterial();

            spat_mat.AlbedoColor = new Color(0.5F, 0.5F, 0.5F, 1F);

            DEBUG_PRINT("Generating links...");
            for (int i = 0; i <= link_count; i++)
            {
                RigidBody link = new RigidBody();
                link.Name         = String.Format("l{0}", i);
                link.CanSleep     = false;
                link.ContinuousCd = true;

                Vector3 link_dimensions = new Vector3(0.2F, 0.8F, 0.1F);

                MeshInstance link_mesh = create_link_mesh(
                    String.Format("{0}_mesh", link.Name),
                    link_dimensions,
                    spat_mat
                    );
                CollisionShape link_col = create_link_collision(
                    String.Format("{0}_col", link.Name),
                    link_dimensions
                    );

                link.AddChild(link_mesh);
                link.AddChild(link_col);

                links.Add(link);
            }
            DEBUG_PRINT("Finished link generation.");

            return(links);
        }
Esempio n. 27
0
        /// <summary>
        /// Recreates all the GUI elements used by this inspector.
        /// </summary>
        private void BuildGUI()
        {
            Layout.Clear();

            PhysicsMaterial material = InspectedObject as PhysicsMaterial;

            if (material == null)
            {
                return;
            }

            staticFrictionField  = new GUIFloatField(new LocEdString("Static friction"));
            dynamicFrictionField = new GUIFloatField(new LocEdString("Dynamic friction"));
            restitutionField     = new GUISliderField(0.0f, 1.0f, new LocEdString("Restitution"));

            staticFrictionField.OnChanged += x =>
            {
                material.StaticFriction = x;
                EditorApplication.SetDirty(material);
            };

            dynamicFrictionField.OnChanged += x =>
            {
                material.DynamicFriction = x;
                EditorApplication.SetDirty(material);
            };

            restitutionField.OnChanged += x =>
            {
                material.Restitution = x;
                EditorApplication.SetDirty(material);
            };

            Layout.AddElement(staticFrictionField);
            Layout.AddElement(dynamicFrictionField);
            Layout.AddElement(restitutionField);
        }
Esempio n. 28
0
        public void Draw(ref Matrix4 world, ref Matrix4 view, ref Matrix4 projection, PhysicsLight light, PhysicsMaterial material, PhysicsCamera camera, bool sleep, bool wireframe)
        {
            Render.SetWorld(ref world);
            Render.SetView(ref view);
            Render.SetProjection(ref projection);
            Render.EnableScaleNormals = scaleNormals;

            light.GetDirection(ref lightDirection);
            light.GetDiffuse(ref lightDiffuse);
            light.GetSpecular(ref lightSpecular);

            if (meshCullMode == CullFaceMode.FrontAndBack)
            {
                GL.Disable(EnableCap.CullFace);
            }

            GL.CullFace(meshCullMode);

            DemoTexture currentTexture = meshTexture;

            if (material.UserDataStr != null)
            {
                currentTexture = demo.Textures[material.UserDataStr];
            }

            material.GetAmbient(ref ambient);
            material.GetDiffuse(ref diffuse);
            material.GetEmission(ref emission);
            material.GetSpecular(ref specular);

            if (sleep)
            {
                diffuse.X = 0.7f;
                diffuse.Y = 1.0f;
                diffuse.Z = 1.0f;
            }

            Render.SetAmbient(ref ambient);
            Render.SetSpecular(ref specular);
            Render.SetEmission(ref emission);
            Render.SpecularPower         = material.SpecularPower;
            Render.Alpha                 = material.TransparencyFactor;
            Render.EnableTwoSidedNormals = material.TwoSidedNormals;

            if (!wireframe)
            {
                Render.SetDiffuse(ref diffuse);

                if (currentTexture != null)
                {
                    Render.EnableTexture = true;
                    Render.Texture       = currentTexture.Handle;
                }
                else
                {
                    Render.EnableTexture = false;
                }
            }
            else
            {
                GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);

                diffuse.X *= 4.0f;
                diffuse.Y *= 4.0f;
                diffuse.Z *= 4.0f;

                Render.SetDiffuse(ref diffuse);

                Render.EnableTexture = false;
            }

            Render.Apply();

            if (demo.EnableVertexBuffer)
            {
                if (meshVertexBuffer != -1)
                {
                    if (meshIndexBuffer != -1)
                    {
                        GL.EnableClientState(ArrayCap.VertexArray);
                        GL.EnableClientState(ArrayCap.NormalArray);
                        GL.EnableClientState(ArrayCap.TextureCoordArray);

                        GL.BindBuffer(BufferTarget.ArrayBuffer, meshVertexBuffer);
                        GL.BindBuffer(BufferTarget.ElementArrayBuffer, meshIndexBuffer);

                        GL.VertexPointer(3, VertexPointerType.Float, VertexPositionNormalTexture.SizeInBytes, IntPtr.Zero);
                        GL.NormalPointer(NormalPointerType.Float, VertexPositionNormalTexture.SizeInBytes, (IntPtr)Vector3.SizeInBytes);
                        GL.TexCoordPointer(2, TexCoordPointerType.Float, VertexPositionNormalTexture.SizeInBytes, (IntPtr)(Vector3.SizeInBytes + Vector3.SizeInBytes));

                        GL.DrawElements(PrimitiveType.Triangles, indexCount, meshIndicesType, 0);

                        GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
                        GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
                        GL.VertexPointer(3, VertexPointerType.Float, 0, IntPtr.Zero);
                        GL.NormalPointer(NormalPointerType.Float, 0, IntPtr.Zero);
                        GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, IntPtr.Zero);

                        GL.DisableClientState(ArrayCap.VertexArray);
                        GL.DisableClientState(ArrayCap.NormalArray);
                        GL.DisableClientState(ArrayCap.TextureCoordArray);
                    }
                    else
                    {
                        GL.EnableClientState(ArrayCap.VertexArray);
                        GL.EnableClientState(ArrayCap.NormalArray);
                        GL.EnableClientState(ArrayCap.TextureCoordArray);

                        GL.BindBuffer(BufferTarget.ArrayBuffer, meshVertexBuffer);

                        GL.VertexPointer(3, VertexPointerType.Float, VertexPositionNormalTexture.SizeInBytes, IntPtr.Zero);
                        GL.NormalPointer(NormalPointerType.Float, VertexPositionNormalTexture.SizeInBytes, (IntPtr)Vector3.SizeInBytes);
                        GL.TexCoordPointer(2, TexCoordPointerType.Float, VertexPositionNormalTexture.SizeInBytes, (IntPtr)(Vector3.SizeInBytes + Vector3.SizeInBytes));

                        GL.DrawArrays(PrimitiveType.Triangles, 0, vertexCount);

                        GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
                        GL.VertexPointer(3, VertexPointerType.Float, 0, IntPtr.Zero);
                        GL.NormalPointer(NormalPointerType.Float, 0, IntPtr.Zero);
                        GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, IntPtr.Zero);

                        GL.DisableClientState(ArrayCap.VertexArray);
                        GL.DisableClientState(ArrayCap.NormalArray);
                        GL.DisableClientState(ArrayCap.TextureCoordArray);
                    }
                }
            }
            else
            {
                VertexPositionNormalTexture v1, v2, v3;

                if (meshIndices16Bit != null)
                {
                    GL.Begin(PrimitiveType.Triangles);

                    for (int i = 0; i < indexCount; i += 3)
                    {
                        v1 = meshVertices[meshIndices16Bit[i]];
                        v2 = meshVertices[meshIndices16Bit[i + 1]];
                        v3 = meshVertices[meshIndices16Bit[i + 2]];

                        GL.TexCoord2(v1.TextureCoordinate);
                        GL.Normal3(v1.Normal);
                        GL.Vertex3(v1.Position);

                        GL.TexCoord2(v2.TextureCoordinate);
                        GL.Normal3(v2.Normal);
                        GL.Vertex3(v2.Position);

                        GL.TexCoord2(v3.TextureCoordinate);
                        GL.Normal3(v3.Normal);
                        GL.Vertex3(v3.Position);
                    }

                    GL.End();
                }
                else
                if (meshIndices32Bit != null)
                {
                    GL.Begin(PrimitiveType.Triangles);

                    for (int i = 0; i < indexCount; i += 3)
                    {
                        v1 = meshVertices[meshIndices32Bit[i]];
                        v2 = meshVertices[meshIndices32Bit[i + 1]];
                        v3 = meshVertices[meshIndices32Bit[i + 2]];

                        GL.TexCoord2(v1.TextureCoordinate);
                        GL.Normal3(v1.Normal);
                        GL.Vertex3(v1.Position);

                        GL.TexCoord2(v2.TextureCoordinate);
                        GL.Normal3(v2.Normal);
                        GL.Vertex3(v2.Position);

                        GL.TexCoord2(v3.TextureCoordinate);
                        GL.Normal3(v3.Normal);
                        GL.Vertex3(v3.Position);
                    }

                    GL.End();
                }
                else
                {
                    GL.Begin(PrimitiveType.Triangles);

                    for (int i = 0; i < vertexCount; i += 3)
                    {
                        v1 = meshVertices[i];
                        v2 = meshVertices[i + 1];
                        v3 = meshVertices[i + 2];

                        GL.TexCoord2(v1.TextureCoordinate);
                        GL.Normal3(v1.Normal);
                        GL.Vertex3(v1.Position);

                        GL.TexCoord2(v2.TextureCoordinate);
                        GL.Normal3(v2.Normal);
                        GL.Vertex3(v2.Position);

                        GL.TexCoord2(v3.TextureCoordinate);
                        GL.Normal3(v3.Normal);
                        GL.Vertex3(v3.Position);
                    }

                    GL.End();
                }
            }

            if (meshCullMode == CullFaceMode.FrontAndBack)
            {
                GL.Enable(EnableCap.CullFace);
            }

            if (wireframe)
            {
                GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);
            }
        }
Esempio n. 29
0
 /// <summary>
 /// Finds a supporting entity, the contact location, and the contact normal.
 /// </summary>
 /// <param name="location">Contact point between the wheel and the support.</param>
 /// <param name="normal">Contact normal between the wheel and the support.</param>
 /// <param name="suspensionLength">Length of the suspension at the contact.</param>
 /// <param name="supportCollidable">Collidable supporting the wheel, if any.</param>
 /// <param name="entity">Entity supporting the wheel, if any.</param>
 /// <param name="material">Material of the support.</param>
 /// <returns>Whether or not any support was found.</returns>
 protected internal abstract bool FindSupport(out Vector3f location, out Vector3f normal, out float suspensionLength, out Collidable supportCollidable, out Entity entity, out PhysicsMaterial material);
Esempio n. 30
0
        public static void GetAttackCollisionResults(Mission.Missile missile, bool isHorseArcher, float armorAmountFloat, WeaponComponentData shieldOnBack, AgentFlag victimAgentFlag, float victimAgentAbsorbedDamageRatio, float damageMultiplierOfBone, float combatDifficultyMultiplier, MissionWeapon victimShield, bool canGiveDamageToAgentShield, bool isVictimAgentLeftStance, bool isFriendlyFire, bool doesAttackerHaveMountAgent, bool doesVictimHaveMountAgent, Vec2 attackerAgentMovementVelocity, Vec3 attackerAgentMountMovementDirection, float attackerMovementDirectionAsAngle, Vec2 victimAgentMovementVelocity, Vec3 victimAgentMountMovementDirection, float victimMovementDirectionAsAngle, bool isVictimAgentSameWithAttackerAgent, bool isAttackerAgentMine, bool isAttackerAgentHasRiderAgent, bool isAttackerAgentRiderAgentIsMine, bool isAttackerAgentMount, bool isVictimAgentMine, bool isVictimAgentHasRiderAgent, bool isVictimAgentRiderAgentIsMine, bool isVictimAgentMount, bool isAttackerAgentNull, bool isAttackerAIControlled, BasicCharacterObject attackerAgentCharacter, BasicCharacterObject victimAgentCharacter, Vec3 attackerAgentMovementDirection, Vec3 attackerAgentVelocity, float attackerAgentMountChargeDamageProperty, Vec3 attackerAgentCurrentWeaponOffset, bool isAttackerAgentHuman, bool isAttackerAgentActive, bool isAttackerAgentCharging, bool isVictimAgentNull, float victimAgentScale, float victimAgentWeight, float victimAgentTotalEncumbrance, bool isVictimAgentHuman, Vec3 victimAgentVelocity, Vec3 victimAgentPosition, int weaponAttachBoneIndex, MissionWeapon offHandItem, bool isHeadShot, bool crushedThrough, bool IsVictimRiderAgentSameAsAttackerAgent, float momentumRemaining, ref AttackCollisionData attackCollisionData, bool cancelDamage, string victimAgentName, out CombatLogData combatLog)
        {
            float distance = 0f;

            if (attackCollisionData.IsMissile)
            {
                distance = (attackCollisionData.MissileStartingPosition - attackCollisionData.CollisionGlobalPosition).Length;
            }
            combatLog = new CombatLogData(isVictimAgentSameWithAttackerAgent, isAttackerAgentHuman, isAttackerAgentMine, isAttackerAgentHasRiderAgent, isAttackerAgentRiderAgentIsMine, isAttackerAgentMount, isVictimAgentHuman, isVictimAgentMine, false, isVictimAgentHasRiderAgent, isVictimAgentRiderAgentIsMine, isVictimAgentMount, false, IsVictimRiderAgentSameAsAttackerAgent, false, false, distance);
            ItemObject          itemFromWeaponKind  = ItemObject.GetItemFromWeaponKind(attackCollisionData.AffectorWeaponKind);
            WeaponComponentData weaponComponentData = (itemFromWeaponKind != null) ? itemFromWeaponKind.GetWeaponWithUsageIndex(attackCollisionData.CurrentUsageIndex) : null;
            bool flag = Extensions.HitWithAnotherBone(ref attackCollisionData, weaponAttachBoneIndex);
            Vec3 agentVelocityContribution  = Extensions.GetAgentVelocityContribution(doesAttackerHaveMountAgent, attackerAgentMovementVelocity, attackerAgentMountMovementDirection, attackerMovementDirectionAsAngle);
            Vec3 agentVelocityContribution2 = Extensions.GetAgentVelocityContribution(doesVictimHaveMountAgent, victimAgentMovementVelocity, victimAgentMountMovementDirection, victimMovementDirectionAsAngle);

            if (attackCollisionData.IsColliderAgent)
            {
                combatLog.IsRangedAttack = attackCollisionData.IsMissile;
                combatLog.HitSpeed       = (attackCollisionData.IsMissile ? (agentVelocityContribution2 - attackCollisionData.MissileVelocity).Length : (agentVelocityContribution - agentVelocityContribution2).Length);
            }
            float baseMagnitude;
            int   speedBonus;

            Mission.ComputeBlowMagnitude(ref attackCollisionData, doesVictimHaveMountAgent, weaponComponentData, isAttackerAgentNull, attackerAgentCharacter, attackerAgentMovementDirection, attackerAgentVelocity, attackerAgentMountChargeDamageProperty, attackerAgentCurrentWeaponOffset, isAttackerAgentHuman, isAttackerAgentActive, isAttackerAgentCharging, isVictimAgentNull, victimAgentScale, victimAgentWeight, victimAgentTotalEncumbrance, isVictimAgentHuman, victimAgentVelocity, victimAgentPosition, momentumRemaining, cancelDamage, flag, attackCollisionData.MissileTotalDamage, agentVelocityContribution, agentVelocityContribution2, out attackCollisionData.BaseMagnitude, out baseMagnitude, out attackCollisionData.MovementSpeedDamageModifier, out speedBonus);
            DamageTypes damageType = (itemFromWeaponKind == null || flag || attackCollisionData.IsAlternativeAttack || attackCollisionData.IsFallDamage || attackCollisionData.IsHorseCharge) ? DamageTypes.Blunt : ((DamageTypes)attackCollisionData.DamageType);

            combatLog.DamageType = damageType;
            if (!attackCollisionData.IsColliderAgent && attackCollisionData.EntityExists)
            {
                string name         = PhysicsMaterial.GetFromIndex(attackCollisionData.PhysicsMaterialIndex).Name;
                bool   isWoodenBody = name == "wood" || name == "wood_weapon" || name == "wood_shield";
                attackCollisionData.BaseMagnitude  *= Extensions.GetEntityDamageMultiplier(isAttackerAgentCharging, weaponComponentData, damageType, isWoodenBody);
                attackCollisionData.InflictedDamage = MBMath.ClampInt((int)attackCollisionData.BaseMagnitude, 0, 2000);
                combatLog.InflictedDamage           = attackCollisionData.InflictedDamage;
            }
            int num = 0;

            if (attackCollisionData.IsColliderAgent && !isVictimAgentNull)
            {
                if (attackCollisionData.IsAlternativeAttack)
                {
                    baseMagnitude = attackCollisionData.BaseMagnitude;
                }
                if (attackCollisionData.AttackBlockedWithShield)
                {
                    Mission.ComputeBlowDamageOnShield(isAttackerAgentNull, isAttackerAgentActive, isAttackerAgentCharging, canGiveDamageToAgentShield, isVictimAgentLeftStance, victimShield, ref attackCollisionData, weaponComponentData, attackCollisionData.BaseMagnitude);
                    attackCollisionData.AbsorbedByArmor = attackCollisionData.InflictedDamage;
                }
                else
                {
                    Mission.ComputeBlowDamage(armorAmountFloat, shieldOnBack, victimAgentFlag, victimAgentAbsorbedDamageRatio, damageMultiplierOfBone, combatDifficultyMultiplier, damageType, baseMagnitude, attackCollisionData.CollisionGlobalPosition, itemFromWeaponKind, attackCollisionData.AttackBlockedWithShield, attackCollisionData.CollidedWithShieldOnBack, speedBonus, cancelDamage, attackCollisionData.IsFallDamage, out attackCollisionData.InflictedDamage, out attackCollisionData.AbsorbedByArmor, out num);
                }



                GCOToolbox.GCOToolbox.ProjectileBalance.ApplyProjectileArmorResistance(armorAmountFloat, ref attackCollisionData, missile, isHorseArcher);


                combatLog.InflictedDamage = attackCollisionData.InflictedDamage;
                combatLog.AbsorbedDamage  = attackCollisionData.AbsorbedByArmor;

                //combatLog.AttackProgress = attackCollisionData.AttackProgress;
                //issionGameModels.Current.AgentApplyDamageModel.CalculateDamage(attackerAgentCharacter, victimAgentCharacter, offHandItem, isHeadShot, isVictimAgentMount, isVictimAgentHuman, doesAttackerHaveMountAgent, isVictimAgentNull, isAttackerAgentHuman, attackCollisionData, weaponComponentData);
                //combatLog.ExtraDamage = attackCollisionData.InflictedDamage - combatLog.InflictedDamage;
            }
            if (!attackCollisionData.IsFallDamage && isFriendlyFire && !isAttackerAIControlled && GameNetwork.IsSessionActive)
            {
                int num2 = attackCollisionData.IsMissile ? MultiplayerOptions.OptionType.FriendlyFireDamageRangedSelfPercent.GetIntValue(MultiplayerOptions.MultiplayerOptionsAccessMode.CurrentMapOptions) : MultiplayerOptions.OptionType.FriendlyFireDamageMeleeSelfPercent.GetIntValue(MultiplayerOptions.MultiplayerOptionsAccessMode.CurrentMapOptions);
                attackCollisionData.SelfInflictedDamage = MBMath.Round((float)attackCollisionData.InflictedDamage * ((float)num2 * 0.01f));
                int num3 = attackCollisionData.IsMissile ? MultiplayerOptions.OptionType.FriendlyFireDamageRangedFriendPercent.GetIntValue(MultiplayerOptions.MultiplayerOptionsAccessMode.CurrentMapOptions) : MultiplayerOptions.OptionType.FriendlyFireDamageMeleeFriendPercent.GetIntValue(MultiplayerOptions.MultiplayerOptionsAccessMode.CurrentMapOptions);
                attackCollisionData.InflictedDamage = MBMath.Round((float)attackCollisionData.InflictedDamage * ((float)num3 * 0.01f));
                if (isVictimAgentMount && !doesAttackerHaveMountAgent)
                {
                    attackCollisionData.InflictedDamage = MBMath.Round((float)attackCollisionData.InflictedDamage * 0.1f);
                }
                combatLog.InflictedDamage = attackCollisionData.InflictedDamage;
                combatLog.IsFriendlyFire  = true;
            }
            if (attackCollisionData.AttackBlockedWithShield && attackCollisionData.InflictedDamage > 0 && (int)victimShield.HitPoints - attackCollisionData.InflictedDamage <= 0)
            {
                attackCollisionData.IsShieldBroken = true;
            }
        }