Ejemplo n.º 1
0
		public RigidBody(float mass, MotionState motionState, CollisionShape collisionShape, Vector3 localInertia, float linearDamping, float angularDamping, float friction, float restitution)
		{
			_optionalMotionState = motionState;
			_angularFactor = 1;
			_angularDamping = 0.5f;

			if (motionState != null)
			{
				motionState.GetWorldTransform(out _worldTransform);
			}
			else
			{
				WorldTransform = Matrix.Identity;
			}

			InterpolationWorldTransform = WorldTransform;
			InterpolationLinearVelocity = new Vector3();
			InterpolationAngularVelocity = new Vector3();

			//moved to btCollisionObject
			Friction = friction;
			Restitution = restitution;

			CollisionShape = collisionShape;
			_debugBodyId = UniqueID++;

			//m_internalOwner is to allow upcasting from collision object to rigid body
			Owner = this;

			SetMassProps(mass, localInertia);
			SetDamping(linearDamping, angularDamping);
			UpdateInertiaTensor();
		}
Ejemplo n.º 2
0
        public SolidBlock BuildSolidBlock(string name, Locator loc, Vector size, CollisionShape shape, Viewer viewer)
        {
            SolidBlock obj = new SolidBlock(name);

            obj.Viewer = viewer;

            obj.LocalCenter = loc.Center;
            obj.LocalAngle = loc.Angle;
            obj.LocalZIndex = loc.ZIndex;

            obj.CollisionShape = shape;
            obj.Size = size;

            map.AddObject(obj);

            obj.LocationChanged += map.UpdateObject;
            obj.LocationChanged += GameProcess.Current_Game.Manager.RegisterObject;

            obj.Crashed += map.RemoveObject;
            obj.Crashed += GameProcess.Current_Game.Camera.TryRemoveIndicator;
            obj.Crashed += GameProcess.Current_Game.Manager.UnRegisterObject;

            obj.LifeChanged += GameProcess.Current_Game.Camera.IndicateLifeChange;

            return obj;
        }
Ejemplo n.º 3
0
        public ConvexBody3D(World world, ModelVisual3D model, CollisionShape collisionShape, double radius, double height)
            : base(world, model)
        {
            // Validate
            switch (collisionShape)
            {
                case CollisionShape.Capsule:
                case CollisionShape.ChamferCylinder:
                case CollisionShape.Cone:
                case CollisionShape.Cylinder:
                    break;

                default:
                    throw new ArgumentException("This constructor overload only supports collision shapes of cone, cylinder, capsule, chamfer cylinder");
            }

            // Store the definition of the collision shape
            _collisionShape = collisionShape;
            _collisionShapeRatio1 = radius;
            _collisionShapeRatio2 = height;
            _collisionShapeRatio3 = -1d;

            // Calculate the collision mask
            RecalculateCollisionMask();
        }
Ejemplo n.º 4
0
 /// <summary>
 /// コンストラクター
 /// </summary>
 public CollisionObject()
 {
     this.shape = null;
     this.ghostObject = null;
     this.offset = new Vector3 (0, 0, 0);
     this.collideWith = -1;
     this.ignoreWith = 0;
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Primitive object constructor
        /// </summary>
        public PrimitiveObject() : base(string.Empty)
        {
            Size = new Vector(_initialObjSize, _initialObjSize);

            Viewer  = null;

            CollisionShape = CollisionShape.None;
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Leaf object constructor
        /// </summary>
        /// <param name="name"></param>
        public PrimitiveObject(string name, Locator locator) : base(name, locator)
        {
            Size = new Vector(_initialObjSize, _initialObjSize);

            Viewer = null;

            CollisionShape = CollisionShape.None;
        }
Ejemplo n.º 7
0
 public bool Collides(CollisionShape a_cs)
 {
     if (a_cs is CollisionRectangle)
     {
         CollisionRectangle a_cr = (CollisionRectangle) a_cs;
         if (a_cr.contains(m_point1) || contains(new Vector2 (a_cr.m_x, a_cr.my)))
         {
             return true;
         }
     }
     else
     {
         //throw new NotImplementedException("Triangles cannot collide with triangles");
         return false;
     }
 }
Ejemplo n.º 8
0
 public override void BuildSpecialObject(string name, String type, Locator loc, Vector size, CollisionShape shape, Viewer viewer)
 {
     switch (type.ToLower())
     {             
         case "solidblock":
             {
                 BuildSolidBlock(name, loc, size, shape, viewer);
             }
             break;
         case "woodbox":
             {
                 BuildWoodBox(name, loc, size, shape, viewer);
             }
             break;
         case "steelblock":
             {
                 BuildSteelBlock(name, loc, size, shape, viewer);
             }
             break;
         case "brickblock":
             {
                 BuildBrickBlock(name, loc, size, shape, viewer);                     
             }
             break;
         case "barrel":
             {
                 BuildBarrel(name, loc, size, shape, viewer);
             }
             break;
         case "respaun":
             {
                 BuildRespaun(name, loc, size, shape, viewer);
             }
             break;
         default:
             {
                 BuildStandartObject(name, loc, size, shape, viewer);
             }
             break;
     }
 }
Ejemplo n.º 9
0
        public ConvexBody3D(World world, ModelVisual3D model, CollisionShape collisionShape, double ratioX, double ratioY, double ratioZ)
            : base(world, model)
        {
            // Validate
            switch (collisionShape)
            {
                case CollisionShape.Cube:
                case CollisionShape.Sphere:
                    break;

                default:
                    throw new ArgumentException("This constructor overload only supports collision shapes of cube and sphere");
            }

            // Store the definition of the collision shape
            _collisionShape = collisionShape;
            _collisionShapeRatio1 = ratioX;		// reusing 3 doubles so I don't waste as much memory (it's not much, but makes me feel better)
            _collisionShapeRatio2 = ratioY;
            _collisionShapeRatio3 = ratioZ;

            // Calculate the collision mask
            RecalculateCollisionMask();
        }
        public override CollisionShape GetCollisionShape()
        {
            if (collisionShapePtr == null)
            {
                BCollisionShape[] css = GetComponentsInChildren <BCollisionShape>();
                colliders = new BCollisionShape[css.Length - 1];
                int ii = 0;
                for (int i = 0; i < css.Length; i++)
                {
                    if (css[i] == this)
                    {
                        //skip
                    }
                    else
                    {
                        colliders[ii] = css[i];
                        ii++;
                    }
                }
                if (colliders.Length == 0)
                {
                    Debug.LogError("Compound collider");
                }

                //TODO
                // some of the collider types (non-finite and other compound colliders) are probably not
                // can only be added to game object with rigid body attached.
                // allowed should check for these.
                // what about scaling not sure if it is handled correctly
                CompoundShape cs = new CompoundShape();
                collisionShapePtr = cs;
                for (int i = 0; i < colliders.Length; i++)
                {
                    CollisionShape chcs = colliders[i].GetCollisionShape();

                    Vector3 up      = Vector3.up;
                    Vector3 origin  = Vector3.zero;
                    Vector3 forward = Vector3.forward;
                    //to world
                    up      = colliders[i].transform.TransformPoint(up);
                    origin  = colliders[i].transform.TransformPoint(origin);
                    forward = colliders[i].transform.TransformPoint(forward);
                    //to compound collider
                    up      = transform.InverseTransformPoint(up);
                    origin  = transform.InverseTransformPoint(origin);
                    forward = transform.InverseTransformPoint(forward);
                    Quaternion q = Quaternion.LookRotation(forward, up);

                    /*
                     * Some collision shapes can have local scaling applied. Use
                     * btCollisionShape::setScaling(vector3).Non uniform scaling with different scaling
                     * values for each axis, can be used for btBoxShape, btMultiSphereShape,
                     * btConvexShape, btTriangleMeshShape.Note that a non - uniform scaled
                     * sphere can be created by using a btMultiSphereShape with 1 sphere.
                     */

                    BulletSharp.Math.Matrix m = BulletSharp.Math.Matrix.AffineTransformation(1f, q.ToBullet(), origin.ToBullet());

                    cs.AddChildShape(m, chcs);
                }
            }
            return(collisionShapePtr);
        }
Ejemplo n.º 11
0
    //todo(erwincoumans) Quick hack, reference to InvertedPendulumPDControl implementation. Will create a separate header/source file for this.
    public MultiBody createInvertedPendulumMultiBody(float radius, MultiBodyDynamicsWorld world, Matrix baseWorldTrans, bool fixedBase)
    {
        BulletSharp.Math.Vector4[] colors = new BulletSharp.Math.Vector4[]
        {
            new BulletSharp.Math.Vector4(1, 0, 0, 1),
            new BulletSharp.Math.Vector4(0, 1, 0, 1),
            new BulletSharp.Math.Vector4(0, 1, 1, 1),
            new BulletSharp.Math.Vector4(1, 1, 0, 1),
        };
        int curColor = 0;

        bool damping     = false;
        bool gyro        = false;
        bool spherical   = false;               //set it ot false -to use 1DoF hinges instead of 3DoF sphericals
        bool canSleep    = false;
        bool selfCollide = false;

        BulletSharp.Math.Vector3 linkHalfExtents = new BulletSharp.Math.Vector3(0.05f, 0.37f, 0.1f);
        BulletSharp.Math.Vector3 baseHalfExtents = new BulletSharp.Math.Vector3(0.04f, 0.35f, 0.08f);


        //mbC.forceMultiDof();							//if !spherical, you can comment this line to check the 1DoF algorithm
        //init the base
        BulletSharp.Math.Vector3 baseInertiaDiag = new BulletSharp.Math.Vector3(0.0f, 0.0f, 0.0f);
        float baseMass = fixedBase ? 0.0f : 10.0f;

        if (baseMass != 0)
        {
            //CollisionShape *shape = new btSphereShape(baseHalfExtents[0]);// btBoxShape(BulletSharp.Math.Vector3(baseHalfExtents[0], baseHalfExtents[1], baseHalfExtents[2]));
            CollisionShape shape = new BoxShape(new BulletSharp.Math.Vector3(baseHalfExtents[0], baseHalfExtents[1], baseHalfExtents[2]));
            shape.CalculateLocalInertia(baseMass, out baseInertiaDiag);
            shape.Dispose();
        }

        Debug.Log("NumLinks " + numLinks);
        MultiBody pMultiBody = new MultiBody(numLinks, 0, baseInertiaDiag, fixedBase, canSleep);

        pMultiBody.BaseWorldTransform = baseWorldTrans;
        BulletSharp.Math.Vector3 vel = new BulletSharp.Math.Vector3(0, 0, 0);
        //	pMultiBody.setBaseVel(vel);

        //init the links
        BulletSharp.Math.Vector3 hingeJointAxis = new BulletSharp.Math.Vector3(1, 0, 0);

        //y-axis assumed up
        BulletSharp.Math.Vector3 parentComToCurrentCom    = new BulletSharp.Math.Vector3(0, -linkHalfExtents[1] * 2.0f, 0); //par body's COM to cur body's COM offset
        BulletSharp.Math.Vector3 currentPivotToCurrentCom = new BulletSharp.Math.Vector3(0, -linkHalfExtents[1], 0);        //cur body's COM to cur body's PIV offset
        BulletSharp.Math.Vector3 parentComToCurrentPivot  = parentComToCurrentCom - currentPivotToCurrentCom;               //par body's COM to cur body's PIV offset

        //////
        float q0 = 1.0f * Mathf.PI / 180.0f;

        BulletSharp.Math.Quaternion quat0 = new BulletSharp.Math.Quaternion(new BulletSharp.Math.Vector3(1, 0, 0), q0);
        quat0.Normalize();
        /////

        for (int i = 0; i < numLinks; ++i)
        {
            float linkMass = 1.0f;
            //if (i==3 || i==2)
            //	linkMass= 1000;
            BulletSharp.Math.Vector3 linkInertiaDiag = new BulletSharp.Math.Vector3(0.0f, 0.0f, 0.0f);

            CollisionShape shape = null;
            if (i == 0)
            {
                shape = new BoxShape(new BulletSharp.Math.Vector3(linkHalfExtents[0], linkHalfExtents[1], linkHalfExtents[2]));//
            }
            else
            {
                shape = new SphereShape(radius);
            }
            shape.CalculateLocalInertia(linkMass, out linkInertiaDiag);
            shape.Dispose();


            if (!spherical)
            {
                //pMultiBody.setupRevolute(i, linkMass, linkInertiaDiag, i - 1, BulletSharp.Math.Quaternion(0.f, 0.f, 0.f, 1.f), hingeJointAxis, parentComToCurrentPivot, currentPivotToCurrentCom, false);

                if (i == 0)
                {
                    pMultiBody.SetupRevolute(i, linkMass, linkInertiaDiag, i - 1,
                                             new BulletSharp.Math.Quaternion(0.0f, 0.0f, 0.0f, 1.0f),
                                             hingeJointAxis,
                                             parentComToCurrentPivot,
                                             currentPivotToCurrentCom, false);
                }
                else
                {
                    parentComToCurrentCom    = new BulletSharp.Math.Vector3(0, -radius * 2.0f, 0); //par body's COM to cur body's COM offset
                    currentPivotToCurrentCom = new BulletSharp.Math.Vector3(0, -radius, 0);        //cur body's COM to cur body's PIV offset
                    parentComToCurrentPivot  = parentComToCurrentCom - currentPivotToCurrentCom;   //par body's COM to cur body's PIV offset


                    pMultiBody.SetupFixed(i, linkMass, linkInertiaDiag, i - 1,
                                          new BulletSharp.Math.Quaternion(0.0f, 0.0f, 0.0f, 1.0f),
                                          parentComToCurrentPivot,
                                          currentPivotToCurrentCom);
                }
            }
            else
            {
                //pMultiBody.setupPlanar(i, linkMass, linkInertiaDiag, i - 1, BulletSharp.Math.Quaternion(0.f, 0.f, 0.f, 1.f)/*quat0*/, BulletSharp.Math.Vector3(1, 0, 0), parentComToCurrentPivot*2, false);
                pMultiBody.SetupSpherical(i, linkMass, linkInertiaDiag, i - 1, new BulletSharp.Math.Quaternion(0.0f, 0.0f, 0.0f, 1.0f), parentComToCurrentPivot, currentPivotToCurrentCom, false);
            }
        }

        pMultiBody.FinalizeMultiDof();
        world.AddMultiBody(pMultiBody);
        MultiBody mbC = pMultiBody;

        mbC.CanSleep         = (canSleep);
        mbC.HasSelfCollision = (selfCollide);
        mbC.UseGyroTerm      = (gyro);
        //
        if (!damping)
        {
            mbC.LinearDamping  = (0.0f);
            mbC.AngularDamping = (0.0f);
        }
        else
        {
            mbC.LinearDamping  = (0.1f);
            mbC.AngularDamping = (0.9f);
        }


        if (numLinks > 0)
        {
            q0 = 180.0f * Mathf.PI / 180.0f;
            if (!spherical)
            {
                mbC.SetJointPosMultiDof(0, new float[] { q0 });
            }
            else
            {
                BulletSharp.Math.Vector3 vv = new BulletSharp.Math.Vector3(1, 1, 0);
                vv.Normalize();
                quat0 = new BulletSharp.Math.Quaternion(vv, q0);
                quat0.Normalize();
                float[] quat0fs = new float[] { quat0.X, quat0.Y, quat0.Z, quat0.W };
                mbC.SetJointPosMultiDof(0, quat0fs);
            }
        }
        ///
        BulletSharp.Math.Quaternion[] world_to_local; //btAlignedObjectArray<BulletSharp.Math.Quaternion>
        world_to_local = new BulletSharp.Math.Quaternion[pMultiBody.NumLinks + 1];

        BulletSharp.Math.Vector3[] local_origin; //btAlignedObjectArray<BulletSharp.Math.Vector3>
        local_origin      = new BulletSharp.Math.Vector3[pMultiBody.NumLinks + 1];
        world_to_local[0] = pMultiBody.WorldToBaseRot;
        local_origin[0]   = pMultiBody.BasePosition;
        //  double friction = 1;
        {
            if (true)
            {
                CollisionShape shape = new BoxShape(new BulletSharp.Math.Vector3(baseHalfExtents[0], baseHalfExtents[1], baseHalfExtents[2])); //new btSphereShape(baseHalfExtents[0]);
                                                                                                                                               // guiHelper.createCollisionShapeGraphicsObject(shape);

                MultiBodyLinkCollider col = new MultiBodyLinkCollider(pMultiBody, -1);
                links.Add(col);
                col.CollisionShape = shape;

                Matrix tr = new Matrix();
                tr.ScaleVector = BulletSharp.Math.Vector3.One;
                //if we don't set the initial pose of the btCollisionObject, the simulator will do this
                //when syncing the btMultiBody link transforms to the btMultiBodyLinkCollider

                tr.Origin = local_origin[0];
                BulletSharp.Math.Quaternion orn = new BulletSharp.Math.Quaternion(new BulletSharp.Math.Vector3(0, 0, 1), 0.25f * 3.1415926538f);

                tr.Rotation        = (orn);
                col.WorldTransform = (tr);

                bool isDynamic = (baseMass > 0 && !fixedBase);
                CollisionFilterGroups collisionFilterGroup = isDynamic ? CollisionFilterGroups.DefaultFilter : CollisionFilterGroups.StaticFilter;
                CollisionFilterGroups collisionFilterMask  = isDynamic ? CollisionFilterGroups.AllFilter : CollisionFilterGroups.AllFilter ^ CollisionFilterGroups.StaticFilter;


                world.AddCollisionObject(col, collisionFilterGroup, collisionFilterMask);//, 2,1+2);

                BulletSharp.Math.Vector4 color = new BulletSharp.Math.Vector4(0.0f, 0.0f, 0.5f, 1f);
                //guiHelper.createCollisionObjectGraphicsObject(col, color);

                //                col.setFriction(friction);
                pMultiBody.BaseCollider = (col);
            }
        }


        for (int i = 0; i < pMultiBody.NumLinks; ++i)
        {
            int parent = pMultiBody.GetParent(i);
            world_to_local[i + 1] = pMultiBody.GetParentToLocalRot(i) * world_to_local[parent + 1];
            BulletSharp.Math.Vector3 vv = world_to_local[i + 1].Inverse.Rotate(pMultiBody.GetRVector(i));
            local_origin[i + 1] = local_origin[parent + 1] + vv;
        }


        for (int i = 0; i < pMultiBody.NumLinks; ++i)
        {
            BulletSharp.Math.Vector3 posr = local_origin[i + 1];
            //	float pos[4]={posr.x(),posr.y(),posr.z(),1};

            float[]        quat  = new float[] { -world_to_local[i + 1].X, -world_to_local[i + 1].Y, -world_to_local[i + 1].Z, world_to_local[i + 1].W };
            CollisionShape shape = null;

            if (i == 0)
            {
                shape = new BoxShape(new BulletSharp.Math.Vector3(linkHalfExtents[0], linkHalfExtents[1], linkHalfExtents[2]));//btSphereShape(linkHalfExtents[0]);
            }
            else
            {
                shape = new SphereShape(radius);
            }

            //guiHelper.createCollisionShapeGraphicsObject(shape);
            MultiBodyLinkCollider col = new MultiBodyLinkCollider(pMultiBody, i);
            links.Add(col);
            col.CollisionShape = (shape);
            Matrix tr = new Matrix();
            tr.ScaleVector     = new BulletSharp.Math.Vector3();
            tr.Origin          = (posr);
            tr.Rotation        = (new BulletSharp.Math.Quaternion(quat[0], quat[1], quat[2], quat[3]));
            col.WorldTransform = (tr);
            //       col.setFriction(friction);
            bool isDynamic = true;//(linkMass > 0);
            CollisionFilterGroups collisionFilterGroup = isDynamic ? CollisionFilterGroups.DefaultFilter : CollisionFilterGroups.StaticFilter;
            CollisionFilterGroups collisionFilterMask  = isDynamic ? CollisionFilterGroups.AllFilter : CollisionFilterGroups.AllFilter ^ CollisionFilterGroups.StaticFilter;

            //if (i==0||i>numLinks-2)
            {
                world.AddCollisionObject(col, collisionFilterGroup, collisionFilterMask);//,2,1+2);
                BulletSharp.Math.Vector4 color = colors[curColor];
                curColor++;
                curColor &= 3;
                //guiHelper.createCollisionObjectGraphicsObject(col, color);


                pMultiBody.GetLink(i).Collider = col;
            }
        }

        return(pMultiBody);
    }
Ejemplo n.º 12
0
        public override void OnAttachedToNode(Node node)
        {
            base.OnAttachedToNode(node);

            this.planetFactory = this.Scene.GetComponent <PlanetFactory>()
                                 ?? throw new InvalidOperationException("'PlanetFactory' not found");

            this.joystickServer = this.Scene.GetComponent <JoystickServer>()
                                  ?? throw new InvalidOperationException("'JoystickServer' not found");

            this.focusManager = this.Scene.GetComponent <FocusManager>()
                                ?? throw new InvalidOperationException("'FocusManager' not found");

            this.cameraNode = this.Scene.GetChild("MainCamera", false)
                              ?? throw new InvalidOperationException("'MainCamera' not found");

            // Geometry.
            this.geometryNode = this.Node.CreateChild("Geometry");
            var planeModel = this.geometryNode.CreateComponent <StaticModel>();

            planeModel.Model    = this.Application.ResourceCache.GetModel("Models\\Rocket.mdl");
            planeModel.Material = this.Application.ResourceCache.GetMaterial("Materials\\RocketMaterial.xml");

            // Gravity.
            this.rigidBody      = this.Node.CreateComponent <RigidBody>();
            this.rigidBody.Mass = Constants.RocketDefaultMass;
            this.rigidBody.LinearRestThreshold = 0.0003f;
            this.rigidBody.AngularDamping      = 0;
            this.rigidBody.SetAngularFactor(Vector3.Zero);
            rigidBody.SetLinearVelocity(this.cameraNode.Rotation * Constants.RocketLaunchVelocity);

            // Engine particle emitter.
            var engineParticleNode = this.Node.CreateChild("RocketEngine");

            this.engineParticleEmitter         = engineParticleNode.CreateComponent <ParticleEmitter>();
            this.engineParticleEmitter.Enabled = false;
            this.engineParticleEmitter.Effect  = this.Application.ResourceCache.GetParticleEffect("Particles\\RocketEngine.xml");
            engineParticleNode.Translate(new Vector3(0, 0, -0.03f));

            // Collision particles.
            var collisionParticleNode = this.Node.CreateChild("CollisionParticle");

            this.collisionParticleEmitter         = collisionParticleNode.CreateComponent <ParticleEmitter>();
            this.collisionParticleEmitter.Enabled = false;
            this.collisionParticleEmitter.Effect  = this.Application.ResourceCache.GetParticleEffect("Particles\\Explosion.xml");

            // Collision detection.
            this.collisionShape = this.Node.CreateComponent <CollisionShape>();
            this.collisionShape.SetCylinder(0.07f, 0.015f, Vector3.Zero, Quaternion.Identity);

            // Background sound.
            this.rocketSoundSource = this.Node.CreateComponent <SoundSource3D>();
            this.rocketSoundSource.SetDistanceAttenuation(0.0f, 2.0f, 1.0f);
            var sound = this.Application.ResourceCache.GetSound("Sounds\\Rocket.wav");

            sound.Looped = true;
            this.rocketSoundSource.Play(sound);
            this.rocketSoundSource.Gain = 0.1f;
            this.soundBaseFrequency     = this.rocketSoundSource.Frequency;

            // Collision sound.
            this.collisionSoundSource = this.Node.CreateComponent <SoundSource3D>();
            this.collisionSound       = this.Application.ResourceCache.GetSound("Sounds\\Collision.wav");
            this.collisionSoundSource.SetDistanceAttenuation(0.0f, 5.0f, 3.0f);

            // Engine sound.
            this.engineSoundSource = this.Node.CreateComponent <SoundSource3D>();
            this.engineSound       = this.Application.ResourceCache.GetSound("Sounds\\RocketEngine.wav");
            this.engineSoundSource.SetDistanceAttenuation(0.0f, 5.0f, 1.0f);
            this.engineSound.Looped = true;
        }
Ejemplo n.º 13
0
    public static GameObject CreateLooseEntity(string id, string name, string desc, float mass, bool unitMass, KAnimFile anim, string initialAnim, Grid.SceneLayer sceneLayer, CollisionShape collisionShape, float width = 1f, float height = 1f, bool isPickupable = false, int sortOrder = 0, SimHashes element = SimHashes.Creature, List <Tag> additionalTags = null)
    {
        GameObject template = CreateBasicEntity(id, name, desc, mass, unitMass, anim, initialAnim, sceneLayer, element, additionalTags, 293f);

        template = AddCollision(template, collisionShape, width, height);
        KBatchedAnimController component = template.GetComponent <KBatchedAnimController>();

        component.isMovable = true;
        template.AddOrGet <Modifiers>();
        if (isPickupable)
        {
            Pickupable pickupable = template.AddOrGet <Pickupable>();
            pickupable.SetWorkTime(5f);
            pickupable.sortOrder = sortOrder;
        }
        return(template);
    }
Ejemplo n.º 14
0
        public virtual void     DrawShadow(ref IndexedMatrix m, ref IndexedVector3 extrusion, CollisionShape shape, ref IndexedVector3 worldBoundsMin, ref IndexedVector3 worldBoundsMax)
        {
            if (shape.GetShapeType() == BroadphaseNativeTypes.UNIFORM_SCALING_SHAPE_PROXYTYPE)
            {
                UniformScalingShape scalingShape = (UniformScalingShape)(shape);
                ConvexShape         convexShape  = scalingShape.GetChildShape();
                float         scalingFactor      = (float)scalingShape.GetUniformScalingFactor();
                IndexedMatrix tmpScaling         = IndexedMatrix.CreateScale(scalingFactor);
                tmpScaling *= m;
                DrawShadow(ref tmpScaling, ref extrusion, convexShape, ref worldBoundsMin, ref worldBoundsMax);

                return;
            }
            else if (shape.GetShapeType() == BroadphaseNativeTypes.COMPOUND_SHAPE_PROXYTYPE)
            {
                CompoundShape compoundShape = (CompoundShape)(shape);
                for (int i = compoundShape.GetNumChildShapes() - 1; i >= 0; i--)
                {
                    IndexedMatrix  childTrans = compoundShape.GetChildTransform(i);
                    CollisionShape colShape   = compoundShape.GetChildShape(i);
                    //float childMat[16];
                    //childTrans.getOpenGLMatrix(childMat);
                    IndexedVector3 transformedExtrude = childTrans._basis * extrusion;
                    DrawShadow(ref childTrans, ref transformedExtrude, colShape, ref worldBoundsMin, ref worldBoundsMax);
                }
            }
            else
            {
                bool useWireframeFallback = true;
                if (shape.IsConvex())
                {
                    ShapeCache sc   = Cache(shape as ConvexShape);
                    ShapeHull  hull = sc.m_shapehull;
                    //glBegin(GL_QUADS);
                    for (int i = 0; i < sc.m_edges.Count; ++i)
                    {
                        float d = IndexedVector3.Dot(sc.m_edges[i].n[0], extrusion);
                        if ((d * IndexedVector3.Dot(sc.m_edges[i].n[1], extrusion)) < 0)
                        {
                            int            q   = d < 0?1:0;
                            IndexedVector3 a   = hull.m_vertices[sc.m_edges[i].v[q]];
                            IndexedVector3 b   = hull.m_vertices[sc.m_edges[i].v[1 - q]];
                            IndexedVector3 ae  = a + extrusion;
                            IndexedVector3 be  = b + extrusion;
                            Vector2        tex = new Vector2(0, 0);
                            // fix me.
                            IndexedVector3 normal = new IndexedVector3(0, 1, 0);
                            // gl_quad turned into two triangles.
                            AddVertex(ref a, ref normal, ref tex);
                            AddVertex(ref b, ref normal, ref tex);
                            AddVertex(ref be, ref normal, ref tex);
                            AddVertex(ref be, ref normal, ref tex);
                            AddVertex(ref ae, ref normal, ref tex);
                            AddVertex(ref a, ref normal, ref tex);
                        }
                    }
                    //glEnd();
                }
            }

            if (shape.IsConcave())    //>getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE||shape.getShapeType() == GIMPACT_SHAPE_PROXYTYPE)
            //		if (shape.getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE)
            {
                ConcaveShape concaveMesh = (ConcaveShape)shape;

                XNADrawcallback drawCallback = new XNADrawcallback(this, ref m);
                drawCallback.m_wireframe = false;

                concaveMesh.ProcessAllTriangles(drawCallback, ref worldBoundsMin, ref worldBoundsMax);
            }
            //glPopMatrix();
        }
Ejemplo n.º 15
0
        public void DrawXNA(ref IndexedMatrix m, CollisionShape shape, ref IndexedVector3 color, DebugDrawModes debugMode, ref IndexedVector3 worldBoundsMin, ref IndexedVector3 worldBoundsMax, ref IndexedMatrix view, ref IndexedMatrix projection)
        {
            //btglMultMatrix(m);
            if (shape == null)
            {
                return;
            }

            if (shape.GetShapeType() == BroadphaseNativeTypes.UNIFORM_SCALING_SHAPE_PROXYTYPE)
            {
                UniformScalingShape scalingShape = (UniformScalingShape)shape;
                ConvexShape         convexShape  = scalingShape.GetChildShape();
                float         scalingFactor      = scalingShape.GetUniformScalingFactor();
                IndexedMatrix scaleMatrix        = IndexedMatrix.CreateScale(scalingFactor);
                IndexedMatrix finalMatrix        = scaleMatrix * m;
                DrawXNA(ref finalMatrix, convexShape, ref color, debugMode, ref worldBoundsMin, ref worldBoundsMax, ref view, ref projection);
                return;
            }
            if (shape.GetShapeType() == BroadphaseNativeTypes.COMPOUND_SHAPE_PROXYTYPE)
            {
                CompoundShape compoundShape = (CompoundShape)shape;
                for (int i = compoundShape.GetNumChildShapes() - 1; i >= 0; i--)
                {
                    IndexedMatrix  childTrans = compoundShape.GetChildTransform(i);
                    CollisionShape colShape   = compoundShape.GetChildShape(i);
                    IndexedMatrix  childMat   = childTrans;

                    //childMat = MathUtil.bulletMatrixMultiply(m, childMat);
                    //childMat = childMat * m;
                    childMat = m * childMat;



                    DrawXNA(ref childMat, colShape, ref color, debugMode, ref worldBoundsMin, ref worldBoundsMax, ref view, ref projection);
                }
            }
            else
            {
                bool useWireframeFallback = true;

                if ((debugMode & DebugDrawModes.DBG_DrawWireframe) == 0)
                {
                    ///you can comment out any of the specific cases, and use the default
                    ///the benefit of 'default' is that it approximates the actual collision shape including collision margin
                    //BroadphaseNativeTypes shapetype = m_textureEnabled ? BroadphaseNativeTypes.MAX_BROADPHASE_COLLISION_TYPES : shape.getShapeType();
                    BroadphaseNativeTypes shapetype = shape.GetShapeType();
                    switch (shapetype)
                    {
                    case BroadphaseNativeTypes.BOX_SHAPE_PROXYTYPE:
                    {
                        BoxShape       boxShape    = shape as BoxShape;
                        IndexedVector3 halfExtents = boxShape.GetHalfExtentsWithMargin();

                        DrawSolidCube(ref halfExtents, ref m, ref view, ref projection, ref color);
                        //drawSolidSphere(halfExtents.X, 10, 10, ref m, ref view, ref projection);
                        //drawCylinder(halfExtents.X, halfExtents.Y, 1, ref m, ref view, ref projection);
                        //drawSolidCone(halfExtents.Y, halfExtents.X, ref m, ref view, ref projection);

                        //DrawText("Hello World", new IndexedVector3(20, 20, 0), new IndexedVector3(255, 255, 255));
                        useWireframeFallback = false;
                        break;
                    }


                    case BroadphaseNativeTypes.SPHERE_SHAPE_PROXYTYPE:
                    {
                        SphereShape sphereShape = shape as SphereShape;
                        float       radius      = sphereShape.GetMargin();//radius doesn't include the margin, so draw with margin
                        DrawSolidSphere(radius, 10, 10, ref m, ref view, ref projection, ref color);
                        //glutSolidSphere(radius,10,10);
                        useWireframeFallback = false;
                        break;
                    }

                    case BroadphaseNativeTypes.CAPSULE_SHAPE_PROXYTYPE:
                    {
                        CapsuleShape capsuleShape = shape as CapsuleShape;

                        float radius     = capsuleShape.GetRadius();
                        float halfHeight = capsuleShape.GetHalfHeight();

                        int upAxis = capsuleShape.GetUpAxis();

                        IndexedVector3 capStart = IndexedVector3.Zero;
                        capStart[upAxis] = -halfHeight;

                        IndexedVector3 capEnd = IndexedVector3.Zero;
                        capEnd[upAxis] = halfHeight;

                        // Draw the ends
                        {
                            IndexedMatrix childTransform = IndexedMatrix.Identity;
                            childTransform._origin = m * capStart;
                            DrawSolidSphere(radius, 5, 5, ref childTransform, ref view, ref projection, ref color);
                        }

                        {
                            IndexedMatrix childTransform = IndexedMatrix.Identity;
                            childTransform._origin = m * capEnd;
                            DrawSolidSphere(radius, 5, 5, ref childTransform, ref view, ref projection, ref color);
                        }

                        DrawCylinder(radius, halfHeight, upAxis, ref m, ref view, ref projection, ref color);
                        break;
                    }

                    case BroadphaseNativeTypes.CONE_SHAPE_PROXYTYPE:
                    {
                        ConeShape     coneShape    = (ConeShape)(shape);
                        int           upIndex      = coneShape.GetConeUpIndex();
                        float         radius       = coneShape.GetRadius(); //+coneShape.getMargin();
                        float         height       = coneShape.GetHeight(); //+coneShape.getMargin();
                        IndexedMatrix rotateMatrix = IndexedMatrix.Identity;


                        switch (upIndex)
                        {
                        case 0:
                            rotateMatrix = IndexedMatrix.CreateRotationX(-MathUtil.SIMD_HALF_PI);
                            break;

                        case 1:
                            break;

                        case 2:
                            rotateMatrix = IndexedMatrix.CreateRotationX(MathUtil.SIMD_HALF_PI);
                            break;

                        default:
                        {
                            break;
                        }
                        }
                        ;

                        IndexedMatrix translationMatrix = IndexedMatrix.CreateTranslation(0f, 0f, -0.5f * height);

                        IndexedMatrix resultant = m * rotateMatrix * translationMatrix;

                        DrawSolidCone(height, radius, ref resultant, ref view, ref projection, ref color);
                        useWireframeFallback = false;
                        break;
                    }


                    case BroadphaseNativeTypes.STATIC_PLANE_PROXYTYPE:
                    {
                        StaticPlaneShape staticPlaneShape = shape as StaticPlaneShape;
                        float            planeConst = staticPlaneShape.GetPlaneConstant();
                        IndexedVector3   planeNormal = staticPlaneShape.GetPlaneNormal();
                        IndexedVector3   planeOrigin = planeNormal * planeConst;
                        IndexedVector3   vec0, vec1;
                        TransformUtil.PlaneSpace1(ref planeNormal, out vec0, out vec1);
                        float          vecLen = 100f;
                        IndexedVector3 pt0 = planeOrigin + vec0 * vecLen;
                        IndexedVector3 pt1 = planeOrigin - vec0 * vecLen;
                        IndexedVector3 pt2 = planeOrigin + vec1 * vecLen;
                        IndexedVector3 pt3 = planeOrigin - vec1 * vecLen;

                        // Fallback to debug draw - needs tidying
                        IndexedVector3 colour = new IndexedVector3(255, 255, 255);
                        DrawLine(ref pt0, ref pt1, ref colour);
                        DrawLine(ref pt1, ref pt2, ref colour);
                        DrawLine(ref pt2, ref pt3, ref colour);
                        DrawLine(ref pt3, ref pt1, ref colour);

                        break;
                    }

                    case BroadphaseNativeTypes.CYLINDER_SHAPE_PROXYTYPE:
                    {
                        CylinderShape cylinder = (CylinderShape)(shape);
                        int           upAxis   = cylinder.GetUpAxis();

                        float radius     = cylinder.GetRadius();
                        float halfHeight = cylinder.GetHalfExtentsWithMargin()[upAxis];
                        DrawCylinder(radius, halfHeight, upAxis, ref m, ref view, ref projection, ref color);
                        break;
                    }

                    default:
                    {
                        if (shape.IsConvex())
                        {
                            ShapeCache sc = Cache(shape as ConvexShape);

                            //if (shape.getUserPointer())
                            {
                                //glutSolidCube(1.0);
                                ShapeHull hull = sc.m_shapehull /*(btShapeHull*)shape.getUserPointer()*/;

                                int numTriangles = hull.NumTriangles();
                                int numIndices   = hull.NumIndices();
                                int numVertices  = hull.NumVertices();
                                if (numTriangles > 0)
                                {
                                    int                    index = 0;
                                    IList <int>            idx   = hull.m_indices;
                                    IList <IndexedVector3> vtx   = hull.m_vertices;

                                    for (int i = 0; i < numTriangles; i++)
                                    {
                                        int i1 = index++;
                                        int i2 = index++;
                                        int i3 = index++;
                                        Debug.Assert(i1 < numIndices &&
                                                     i2 < numIndices &&
                                                     i3 < numIndices);

                                        int index1 = idx[i1];
                                        int index2 = idx[i2];
                                        int index3 = idx[i3];
                                        Debug.Assert(index1 < numVertices &&
                                                     index2 < numVertices &&
                                                     index3 < numVertices);

                                        IndexedVector3 v1     = m * vtx[index1];
                                        IndexedVector3 v2     = m * vtx[index2];
                                        IndexedVector3 v3     = m * vtx[index3];
                                        IndexedVector3 normal = IndexedVector3.Cross((v3 - v1), (v2 - v1));
                                        normal.Normalize();

                                        Vector2 tex = new Vector2(0, 0);
                                        AddVertex(ref v1, ref normal, ref tex);
                                        AddVertex(ref v2, ref normal, ref tex);
                                        AddVertex(ref v3, ref normal, ref tex);
                                    }
                                }
                            }
                        }
                        break;
                    }
                    }
                }

                /// for polyhedral shapes
                if (debugMode == DebugDrawModes.DBG_DrawFeaturesText && (shape.IsPolyhedral()))
                {
                    PolyhedralConvexShape polyshape = (PolyhedralConvexShape)shape;
                    {
                        //BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),polyshape.getExtraDebugInfo());

                        IndexedVector3 colour = new IndexedVector3(255, 255, 255);
                        for (int i = 0; i < polyshape.GetNumVertices(); i++)
                        {
                            IndexedVector3 vtx;
                            polyshape.GetVertex(i, out vtx);
                            String buf = " " + i;
                            DrawText(buf, ref vtx, ref colour);
                        }

                        for (int i = 0; i < polyshape.GetNumPlanes(); i++)
                        {
                            IndexedVector3 normal;
                            IndexedVector3 vtx;
                            polyshape.GetPlane(out normal, out vtx, i);
                            float d = IndexedVector3.Dot(vtx, normal);
                            vtx *= d;

                            String buf = " plane " + i;
                            DrawText(buf, ref vtx, ref colour);
                        }
                    }
                }

                if (shape.IsConcave() && !shape.IsInfinite())    //>getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE||shape.getShapeType() == GIMPACT_SHAPE_PROXYTYPE)
                //		if (shape.getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE)
                {
                    ConcaveShape concaveMesh = shape as ConcaveShape;

                    XNADrawcallback drawCallback = new XNADrawcallback(this, ref m);
                    drawCallback.m_wireframe = (debugMode & DebugDrawModes.DBG_DrawWireframe) != 0;

                    concaveMesh.ProcessAllTriangles(drawCallback, ref worldBoundsMin, ref worldBoundsMax);
                }

                //glDisable(GL_DEPTH_TEST);
                //glRasterPos3f(0,0,0);//mvtx.x(),  vtx.y(),  vtx.z());
                if ((debugMode & DebugDrawModes.DBG_DrawText) != 0)
                {
                    IndexedVector3 position = IndexedVector3.Zero;
                    IndexedVector3 colour   = new IndexedVector3(255, 255, 255);
                    DrawText(shape.GetName(), ref position, ref colour);
                }

                if ((debugMode & DebugDrawModes.DBG_DrawFeaturesText) != 0)
                {
                    //drawText(shape.getEx]
                    //BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),shape.getExtraDebugInfo());
                }
                //glEnable(GL_DEPTH_TEST);

                ////	glPopMatrix();
                //if(m_textureenabled) glDisable(GL_TEXTURE_2D);
                //  }
                //    glPopMatrix();
            }
        }
Ejemplo n.º 16
0
 protected void RemoveCollisionShape(CollisionShape shape)
 {
     m_collisionShapes.Remove(shape);
     shape.Dispose();
 }
Ejemplo n.º 17
0
 public int RemoveReferences(CollisionShape pcs)
 {
     return btSparseSdf3_RemoveReferences(_native, (pcs != null) ? pcs._native : IntPtr.Zero);
 }
Ejemplo n.º 18
0
 protected virtual void OnShapeChanged(CollisionShape collisionShape)
 {
 }
Ejemplo n.º 19
0
 protected void AddCollisionShape(CollisionShape shape)
 {
     m_collisionShapes.Add(shape);
 }
 bool MyCompoundChildShapeCallback(CollisionShape shape0, CollisionShape shape1)
 {
     return(true);
 }
        //[Import()]
        //VVVV. FLog;


        public void Evaluate(int SpreadMax)
        {
            if (this.FBodies.PluginIO.IsConnected)
            {
                this.FId.SliceCount              = this.FBodies.SliceCount;
                this.FPosition.SliceCount        = this.FBodies.SliceCount;
                this.FRotation.SliceCount        = this.FBodies.SliceCount;
                this.FShapes.SliceCount          = this.FBodies.SliceCount;
                this.FShapeScaling.SliceCount    = this.FBodies.SliceCount;
                this.FCustom.SliceCount          = this.FBodies.SliceCount;
                this.FIsNew.SliceCount           = this.FBodies.SliceCount;
                this.FLinVel.SliceCount          = this.FBodies.SliceCount;
                this.FAngVel.SliceCount          = this.FBodies.SliceCount;
                this.FActive.SliceCount          = this.FBodies.SliceCount;
                this.FContactResponse.SliceCount = this.FBodies.SliceCount;
                this.FStatic.SliceCount          = this.FBodies.SliceCount;
                this.FKinematic.SliceCount       = this.FBodies.SliceCount;
                this.FShapeTransform.SliceCount  = this.FBodies.SliceCount;
                this.FAlive.SliceCount           = this.FBodies.SliceCount;



                List <Matrix4x4> transforms = new List <Matrix4x4>();
                List <Vector3>   scaling    = new List <Vector3>();

                for (int i = 0; i < SpreadMax; i++)
                {
                    RigidBody body = this.FBodies[i];


                    this.FPosition[i] = new Vector3D(body.MotionState.WorldTransform.M41,
                                                     body.MotionState.WorldTransform.M42, body.MotionState.WorldTransform.M43);

                    Quaternion rot = body.Orientation;
                    this.FRotation[i] = new Vector4D(rot.X, rot.Y, rot.Z, rot.W);

                    this.FLinVel[i] = body.LinearVelocity.ToVVVVector();
                    this.FAngVel[i] = body.AngularVelocity.ToVVVVector();

                    CollisionShape shape = body.CollisionShape;

                    if (shape.IsCompound)
                    {
                        //CompoundShape sp = new CompoundShape(
                        CompoundShape comp = (CompoundShape)shape;
                        this.FShapes[i].SliceCount         = comp.NumChildShapes;
                        this.FShapeTransform[i].SliceCount = comp.NumChildShapes;


                        for (int j = 0; j < comp.NumChildShapes; j++)
                        {
                            CollisionShape child = comp.GetChildShape(j);

                            this.FShapes[i][j] = child;

                            Matrix m = comp.GetChildTransform(j);

                            Matrix4x4 mn = new Matrix4x4(m.M11, m.M12, m.M13, m.M14,
                                                         m.M21, m.M22, m.M23, m.M24, m.M31, m.M32, m.M33, m.M34,
                                                         m.M41, m.M42, m.M43, m.M44);

                            mn *= VMath.Scale(child.LocalScaling.ToVVVVector());
                            this.FShapeTransform[i][j] = mn;
                            //comp.
                            //comp.GetChildTransform(
                            //this.FShapes[i][j].
                        }
                    }
                    else
                    {
                        this.FShapes[i].SliceCount         = 1;
                        this.FShapes[i][0]                 = shape;
                        this.FShapeTransform[i].SliceCount = 1;



                        this.FShapeTransform[i][0] = VMath.Scale(shape.LocalScaling.ToVVVVector());
                        //transforms.Add(VMath.IdentityMatrix);
                    }


                    BodyCustomData bd = (BodyCustomData)body.UserObject;

                    ShapeCustomData sc = (ShapeCustomData)shape.UserObject;

                    this.FActive[i]          = body.IsActive;
                    this.FContactResponse[i] = body.HasContactResponse;
                    this.FStatic[i]          = body.IsStaticObject;
                    this.FKinematic[i]       = body.IsKinematicObject;


                    //this.FShapeCount[i] = sc.ShapeDef.ShapeCount;
                    this.FId[i]     = bd.Id;
                    this.FIsNew[i]  = bd.Created;
                    this.FCustom[i] = bd.Custom;
                    this.FAlive[i]  = bd.LifeTime;

                    if (bd.CustomObject != null)
                    {
                        this.FHasCustomObj[i] = true;
                        this.FCustomObj[i]    = bd.CustomObject;
                    }
                    else
                    {
                        this.FHasCustomObj[i] = false;
                        this.FCustomObj[i]    = null;
                    }
                }

                //this.FShapeTransform.SliceCount = transforms.Count;
                //this.FShapeTransform.AssignFrom(transforms);
            }
            else
            {
                this.FId.SliceCount             = 0;
                this.FPosition.SliceCount       = 0;
                this.FRotation.SliceCount       = 0;
                this.FShapes.SliceCount         = 0;
                this.FCustom.SliceCount         = 0;
                this.FIsNew.SliceCount          = 0;
                this.FLinVel.SliceCount         = 0;
                this.FAngVel.SliceCount         = 0;
                this.FShapeTransform.SliceCount = 0;
                this.FAlive.SliceCount          = 0;
            }
        }
Ejemplo n.º 22
0
        public override RigidBody LocalCreateRigidBody(float mass, Matrix startTransform, CollisionShape shape)
        {
            //rigidbody is dynamic if and only if mass is non zero, otherwise static
            bool    isDynamic    = (mass != 0.0f);
            Vector3 localInertia = isDynamic ? shape.CalculateLocalInertia(mass) : Vector3.Zero;

            using (var rbInfo = new RigidBodyConstructionInfo(mass, null, shape, localInertia))
            {
                var body = new RigidBody(rbInfo)
                {
                    ContactProcessingThreshold = defaultContactProcessingThreshold,
                    WorldTransform             = startTransform
                };
                World.AddRigidBody(body);
                return(body);
            }
        }
Ejemplo n.º 23
0
 void CreateTile(Vector2 pos, Sprite tileSprite, CollisionShape collisionShape)
 {
     var cube = new GameObject();
     switch (collisionShape)
     {
     case CollisionShape.Square:
         BoxCollider2D boxCollider = cube.AddComponent<BoxCollider2D>();
         boxCollider.size = new Vector2(tileWidth, tileHeight);
         break;
     case CollisionShape.Incline:
         {
             PolygonCollider2D polyCollider = cube.AddComponent<PolygonCollider2D>();
             Vector2[] points = new Vector2[3];
             points[0] = new Vector2(-tileWidth/2, -tileHeight/2);
             points[1] = new Vector2( tileWidth/2, -tileHeight/2);
             points[2] = new Vector2( tileWidth/2,  tileHeight/2);
             polyCollider.SetPath(0, points);
         }
         break;
     case CollisionShape.Decline:
         {
             PolygonCollider2D polyCollider = cube.AddComponent<PolygonCollider2D>();
             Vector2[] points = new Vector2[3];
             points[0] = new Vector2(-tileWidth/2,  tileHeight/2);
             points[1] = new Vector2(-tileWidth/2, -tileHeight/2);
             points[2] = new Vector2( tileWidth/2, -tileHeight/2);
             polyCollider.SetPath(0, points);
         }
         break;
     }
     SpriteRenderer spriteRenderer = cube.AddComponent<SpriteRenderer>();
     spriteRenderer.sprite = tileSprite;
     cube.transform.position = pos;
     cube.transform.parent = mapParent.transform;
     cube.name = "tile";
     cube.layer = 10;
 }
Ejemplo n.º 24
0
    // Creates a rigid body from the given shape and adds it to the Unity scene.
    protected RigidBody CreateRigidBody(float mass, BulletSharp.Math.Vector3 inertia, Matrix startTransform, CollisionShape shape, Material renderMat, float friction = 0.5f, bool isKinematic = false, bool viz = false)
    {
        //rigidbody is dynamic if and only if mass is non zero, otherwise static
        bool isDynamic = (mass != 0.0f);

        BulletSharp.Math.Vector3 localInertia = BulletSharp.Math.Vector3.Zero;
        if (isDynamic)
        {
            localInertia = inertia;
        }

        //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
        DefaultMotionState myMotionState = new DefaultMotionState(startTransform);

        RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia);

        rbInfo.Friction = friction;
        //rbInfo.RollingFriction = friction;
        RigidBody body = new RigidBody(rbInfo);

        if (isKinematic)
        {
            body.CollisionFlags  = body.CollisionFlags | BulletSharp.CollisionFlags.KinematicObject;
            body.ActivationState = ActivationState.DisableDeactivation;
        }
        rbInfo.Dispose();

        m_world.AddRigidBody(body);

        // create unity object from it
        if (viz)
        {
            AddUnityObject(body, renderMat);
        }

        return(body);
    }
Ejemplo n.º 25
0
 public SoftBody(SoftBodyWorldInfo worldInfo)
     : base(btSoftBody_new2(worldInfo._native))
 {
     _collisionShape = new CollisionShape(btCollisionObject_getCollisionShape(_native), true);
     _worldInfo = worldInfo;
 }
Ejemplo n.º 26
0
    protected RigidBody ResetRigidBody(RigidBody rb, float newMass, BulletSharp.Math.Vector3 newInertia, Matrix startTransform, CollisionShape shape, float friction = 0.5f, bool isKinematic = false)
    {
        // basically detroys a rigid body and re-initializes it efficiently
        // doesn't recalculate moment of inertia or re-create the gfx object

        //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects\
        float mass = newMass;

        BulletSharp.Math.Vector3 localInertia = newInertia;
        DestroyRigidBody(rb);
        DefaultMotionState myMotionState = new DefaultMotionState(startTransform);

        RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia);

        rbInfo.Friction = friction;
        RigidBody body = new RigidBody(rbInfo);

        if (isKinematic)
        {
            body.CollisionFlags  = body.CollisionFlags | BulletSharp.CollisionFlags.KinematicObject;
            body.ActivationState = ActivationState.DisableDeactivation;
        }
        rbInfo.Dispose();

        m_world.AddRigidBody(body);

        return(body);
    }
Ejemplo n.º 27
0
        void CreateScene()
        {
            var cache = ResourceCache;

            scene = new Scene();

            // Create scene subsystem components
            scene.CreateComponent <Octree>();
            physicsWorld = scene.CreateComponent <PhysicsWorld>();

            // Create camera and define viewport. We will be doing load / save, so it's convenient to create the camera outside the scene,
            // so that it won't be destroyed and recreated, and we don't have to redefine the viewport on load
            CameraNode = new Node();
            Camera camera = CameraNode.CreateComponent <Camera>();

            camera.FarClip = 300.0f;
            Renderer.SetViewport(0, new Viewport(Context, scene, camera, null));

            // Create static scene content. First create a zone for ambient lighting and fog control
            Node zoneNode = scene.CreateChild("Zone");
            Zone zone     = zoneNode.CreateComponent <Zone>();

            zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
            zone.FogColor     = new Color(0.5f, 0.5f, 0.7f);
            zone.FogStart     = 100.0f;
            zone.FogEnd       = 300.0f;
            zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));

            // Create a directional light with cascaded shadow mapping
            Node lightNode = scene.CreateChild("DirectionalLight");

            lightNode.SetDirection(new Vector3(0.3f, -0.5f, 0.425f));
            Light light = lightNode.CreateComponent <Light>();

            light.LightType         = LightType.Directional;
            light.CastShadows       = true;
            light.ShadowBias        = new BiasParameters(0.00025f, 0.5f);
            light.ShadowCascade     = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
            light.SpecularIntensity = 0.5f;

            // Create the floor object
            Node floorNode = scene.CreateChild("Floor");

            floorNode.Position = new Vector3(0.0f, -0.5f, 0.0f);
            floorNode.Scale    = new Vector3(200.0f, 1.0f, 200.0f);
            StaticModel sm = floorNode.CreateComponent <StaticModel>();

            sm.Model = cache.GetModel("Models/Box.mdl");
            sm.SetMaterial(cache.GetMaterial("Materials/Stone.xml"));

            RigidBody body = floorNode.CreateComponent <RigidBody>();

            // Use collision layer bit 2 to mark world scenery. This is what we will raycast against to prevent camera from going
            // inside geometry
            body.CollisionLayer = 2;
            CollisionShape shape = floorNode.CreateComponent <CollisionShape>();

            shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);

            // Create mushrooms of varying sizes
            uint numMushrooms = 60;

            for (uint i = 0; i < numMushrooms; ++i)
            {
                Node objectNode = scene.CreateChild("Mushroom");
                objectNode.Position = new Vector3(NextRandom(180.0f) - 90.0f, 0.0f, NextRandom(180.0f) - 90.0f);
                objectNode.Rotation = new Quaternion(0.0f, NextRandom(360.0f), 0.0f);
                objectNode.SetScale(2.0f + NextRandom(5.0f));
                StaticModel o = objectNode.CreateComponent <StaticModel>();
                o.Model = cache.GetModel("Models/Mushroom.mdl");
                o.SetMaterial(cache.GetMaterial("Materials/Mushroom.xml"));
                o.CastShadows = true;

                body = objectNode.CreateComponent <RigidBody>();
                body.CollisionLayer = 2;
                shape = objectNode.CreateComponent <CollisionShape>();
                shape.SetTriangleMesh(o.Model, 0, Vector3.One, Vector3.Zero, Quaternion.Identity);
            }

            // Create movable boxes. Let them fall from the sky at first
            const uint numBoxes = 100;

            for (uint i = 0; i < numBoxes; ++i)
            {
                float scale = NextRandom(2.0f) + 0.5f;

                Node objectNode = scene.CreateChild("Box");
                objectNode.Position = new Vector3(NextRandom(180.0f) - 90.0f, NextRandom(10.0f) + 10.0f, NextRandom(180.0f) - 90.0f);
                objectNode.Rotation = new Quaternion(NextRandom(360.0f), NextRandom(360.0f), NextRandom(360.0f));
                objectNode.SetScale(scale);
                StaticModel o = objectNode.CreateComponent <StaticModel>();
                o.Model = cache.GetModel("Models/Box.mdl");
                o.SetMaterial(cache.GetMaterial("Materials/Stone.xml"));
                o.CastShadows = true;

                body = objectNode.CreateComponent <RigidBody>();
                body.CollisionLayer = 2;
                // Bigger boxes will be heavier and harder to move
                body.Mass = scale * 2.0f;
                shape     = objectNode.CreateComponent <CollisionShape>();
                shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
            }
        }
Ejemplo n.º 28
0
    // Creates a Unity game object from the given Bullet CollisionObject.
    protected void AddUnityObject(CollisionObject co, Material mat)
    {
        CollisionShape cs = co.CollisionShape;
        GameObject     go;

        if (cs.ShapeType == BroadphaseNativeType.SoftBodyShape)
        {
            BulletSharp.SoftBody.SoftBody sb = (BulletSharp.SoftBody.SoftBody)co;
            if (sb.Faces.Count == 0)
            {
                //rope
                go = CreateUnitySoftBodyRope(sb);
            }
            else
            {
                go = CreateUnitySoftBodyCloth(sb);
            }
        }
        else
        {
            //rigid body
            if (cs.ShapeType == BroadphaseNativeType.CompoundShape)
            {
                //BulletSharp.Math.Matrix transform = co.WorldTransform;
                go = new GameObject("Compund Shape");
                BulletRigidBodyProxy rbp = go.AddComponent <BulletRigidBodyProxy>();
                rbp.target = co as RigidBody;
                foreach (BulletSharp.CompoundShapeChild child in (cs as CompoundShape).ChildList)
                {
                    BulletSharp.Math.Matrix childTransform = child.Transform;
                    GameObject ggo = new GameObject(child.ToString());
                    MeshFilter mf  = ggo.AddComponent <MeshFilter>();
                    Mesh       m   = mf.mesh;
                    MeshFactory2.CreateShape(child.ChildShape, m);
                    MeshRenderer mr = ggo.AddComponent <MeshRenderer>();
                    mr.sharedMaterial = mat;
                    ggo.transform.SetParent(go.transform);
                    Matrix4x4 mt = childTransform.ToUnity();
                    ggo.transform.localPosition = BSExtensionMethods2.ExtractTranslationFromMatrix(ref mt);
                    ggo.transform.localRotation = BSExtensionMethods2.ExtractRotationFromMatrix(ref mt);
                    ggo.transform.localScale    = BSExtensionMethods2.ExtractScaleFromMatrix(ref mt);

                    /*
                     * BulletRigidBodyProxy rbp = ggo.AddComponent<BulletRigidBodyProxy>();
                     * rbp.target = body;
                     * return go;
                     */
                    //InitRigidBodyInstance(colObj, child.ChildShape, ref childTransform);
                }
            }
            else if (cs.ShapeType == BroadphaseNativeType.CapsuleShape)
            {
                CapsuleShape css = (CapsuleShape)cs;
                GameObject   ggo = GameObject.CreatePrimitive(PrimitiveType.Capsule);
                Destroy(ggo.GetComponent <Collider>());
                go = new GameObject();
                ggo.transform.parent        = go.transform;
                ggo.transform.localPosition = UnityEngine.Vector3.zero;
                ggo.transform.localRotation = UnityEngine.Quaternion.identity;
                ggo.transform.localScale    = new UnityEngine.Vector3(css.Radius * 2f, css.HalfHeight * 2f, css.Radius * 2f);
                BulletRigidBodyProxy rbp = go.AddComponent <BulletRigidBodyProxy>();
                rbp.target = co;
            }
            else
            {
                //Debug.Log("Creating " + cs.ShapeType + " for " + co.ToString());
                go = CreateUnityCollisionObjectProxy(co as CollisionObject, mat);
            }
        }
        m_createdObjs.Add(go);
    }
Ejemplo n.º 29
0
 public void DrawXNA(IndexedMatrix m, CollisionShape shape, IndexedVector3 color, DebugDrawModes debugMode, IndexedVector3 worldBoundsMin, IndexedVector3 worldBoundsMax, IndexedMatrix view, IndexedMatrix projection)
 {
     DrawXNA(ref m, shape, ref color, debugMode, ref worldBoundsMin, ref worldBoundsMax, ref view, ref projection);
 }
Ejemplo n.º 30
0
        public override RigidBody LocalCreateRigidBody(float mass, Matrix startTransform, CollisionShape shape)
        {
            var body = base.LocalCreateRigidBody(mass, startTransform, shape);

            body.CollisionFlags |= CollisionFlags.CustomMaterialCallback;
            body.UserObject      = "plastic.wav";
            return(body);
        }
Ejemplo n.º 31
0
        /**
         * Creates or configures a RigidBody based on the current settings. Does not alter the internal state of this component in any way.
         * Can be used to create copies of this BRigidBody for use in other physics simulations.
         */
        public bool CreateOrConfigureRigidBody(ref RigidBody rb, ref BulletSharp.Math.Vector3 localInertia, CollisionShape cs, MotionState motionState)
        {
            //rigidbody is dynamic if and only if mass is non zero, otherwise static
            localInertia = BulletSharp.Math.Vector3.Zero;
            if (isDynamic())
            {
                cs.CalculateLocalInertia(_mass, out localInertia);
            }

            if (rb == null)
            {
                float bulletMass = _mass;
                if (!isDynamic())
                {
                    bulletMass = 0f;
                }
                RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(bulletMass, motionState, cs, localInertia);
                rbInfo.Friction                             = _friction;
                rbInfo.RollingFriction                      = _rollingFriction;
                rbInfo.LinearDamping                        = _linearDamping;
                rbInfo.AngularDamping                       = _angularDamping;
                rbInfo.Restitution                          = _restitution;
                rbInfo.LinearSleepingThreshold              = _linearSleepingThreshold;
                rbInfo.AngularSleepingThreshold             = _angularSleepingThreshold;
                rbInfo.AdditionalDamping                    = _additionalDamping;
                rbInfo.AdditionalAngularDampingFactor       = _additionalAngularDampingFactor;
                rbInfo.AdditionalAngularDampingThresholdSqr = _additionalAngularDampingThresholdSqr;
                rbInfo.AdditionalDampingFactor              = _additionalDampingFactor;
                rbInfo.AdditionalLinearDampingThresholdSqr  = _additionalLinearDampingThresholdSqr;
                rb = new RigidBody(rbInfo);
                rbInfo.Dispose();
            }
            else
            {
                float usedMass = 0f;
                if (isDynamic())
                {
                    usedMass = _mass;
                }
                rb.SetMassProps(usedMass, localInertia);
                rb.Friction        = _friction;
                rb.RollingFriction = _rollingFriction;
                rb.SetDamping(_linearDamping, _angularDamping);
                rb.Restitution = _restitution;
                rb.SetSleepingThresholds(_linearSleepingThreshold, _angularSleepingThreshold);
                rb.CollisionShape = cs;
            }

            rb.AngularVelocity = angularVelocity.ToBullet();
            rb.LinearVelocity  = velocity.ToBullet();

            rb.CollisionFlags = m_collisionFlags;
            rb.LinearFactor   = _linearFactor.ToBullet();
            rb.AngularFactor  = _angularFactor.ToBullet();
            if (m_rigidBody != null)
            {
                rb.DeactivationTime             = m_rigidBody.DeactivationTime;
                rb.InterpolationLinearVelocity  = m_rigidBody.InterpolationLinearVelocity;
                rb.InterpolationAngularVelocity = m_rigidBody.InterpolationAngularVelocity;
                rb.InterpolationWorldTransform  = m_rigidBody.InterpolationWorldTransform;
            }

            //if kinematic then disable deactivation
            if ((m_collisionFlags & BulletSharp.CollisionFlags.KinematicObject) != 0)
            {
                rb.ActivationState = ActivationState.DisableDeactivation;
            }
            return(true);
        }
Ejemplo n.º 32
0
        public static void ExtractCollisionShapes(Mesh mesh, string path)
        {
            PhysicsData   physicsData = null;
            List <string> deleteEm    = new List <string>();
            int           count       = mesh.SubMeshCount;

            for (int i = 0; i < count; i++)
            {
                SubMesh        subMesh    = mesh.GetSubMesh(i);
                CollisionShape shape      = null;
                string         targetName = null;
                bool           cv         = String.Compare(subMesh.Name.Substring(0, 5), "mvcv_", false) == 0;
                bool           rg         = String.Compare(subMesh.Name.Substring(0, 5), "mvrg_", false) == 0;
                int            firstIndex = 0;
                if (cv)
                {
                    firstIndex = 5;
                }
                else if (rg)
                {
                    string rest = subMesh.Name.Substring(5);
                    firstIndex = rest.IndexOf("_") + 1 + 5;
                }
                if (cv || rg)
                {
                    // It's probably a collision volume - - check the
                    // shape type to make sure
                    if (String.Compare(subMesh.Name.Substring(firstIndex, 4), "obb_", false) == 0)
                    {
                        shape = ExtractBox(subMesh);
                    }
                    else if (String.Compare(subMesh.Name.Substring(firstIndex, 5), "aabb_", false) == 0)
                    {
                        shape = ExtractBox(subMesh);
                    }
                    else if (String.Compare(subMesh.Name.Substring(firstIndex, 7), "sphere_", false) == 0)
                    {
                        shape = ExtractSphere(subMesh);
                    }
                    else if (String.Compare(subMesh.Name.Substring(firstIndex, 8), "capsule_", false) == 0)
                    {
                        shape = ExtractCapsule(subMesh);
                    }
                    if (shape != null)
                    {
                        targetName = GetTargetSubmesh(mesh, subMesh.Name);
                    }
                }
                if (shape != null)
                {
                    deleteEm.Add(subMesh.Name);
                    if (physicsData == null)
                    {
                        physicsData = new PhysicsData();
                    }
                    physicsData.AddCollisionShape(targetName, shape);
                }
            }
            for (int i = 0; i < deleteEm.Count; i++)
            {
                mesh.RemoveSubMesh(deleteEm[i]);
            }
            if (physicsData != null)
            {
                PhysicsSerializer serializer = new PhysicsSerializer();
                serializer.ExportPhysics(physicsData, path + ".physics");
            }

            if (DoLog)
            {
                CloseLog();
            }
        }
Ejemplo n.º 33
0
 public virtual void BuildSpecialObject(string name, String type, Locator loc, Vector size, CollisionShape shape, Viewer viewer)
 {
     BuildStandartObject(name, loc, size, shape, viewer);
 }
Ejemplo n.º 34
0
 public CollisionShapeWithTransform(CollisionShape shape, Transform transform)
 {
     Shape     = shape;
     Transform = transform;
 }
Ejemplo n.º 35
0
        void CreateScene()
        {
            var cache = ResourceCache;

            scene = new Scene();

            // Create scene subsystem components
            scene.CreateComponent <Octree>();
            scene.CreateComponent <PhysicsWorld>();

            // Create camera and define viewport. We will be doing load / save, so it's convenient to create the camera outside the scene,
            // so that it won't be destroyed and recreated, and we don't have to redefine the viewport on load
            CameraNode = new Node();
            Camera camera = CameraNode.CreateComponent <Camera>();

            camera.FarClip = 500.0f;
            Renderer.SetViewport(0, new Viewport(Context, scene, camera, null));

            // Create static scene content. First create a zone for ambient lighting and fog control
            Node zoneNode = scene.CreateChild("Zone");
            Zone zone     = zoneNode.CreateComponent <Zone>();

            zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
            zone.FogColor     = new Color(0.5f, 0.5f, 0.7f);
            zone.FogStart     = 300.0f;
            zone.FogEnd       = 500.0f;
            zone.SetBoundingBox(new BoundingBox(-2000.0f, 2000.0f));

            // Create a directional light with cascaded shadow mapping
            Node lightNode = scene.CreateChild("DirectionalLight");

            lightNode.SetDirection(new Vector3(0.3f, -0.5f, 0.425f));
            Light light = lightNode.CreateComponent <Light>();

            light.LightType         = LightType.Directional;
            light.CastShadows       = true;
            light.ShadowBias        = new BiasParameters(0.00025f, 0.5f);
            light.ShadowCascade     = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
            light.SpecularIntensity = 0.5f;

            // Create heightmap terrain with collision
            Node terrainNode = scene.CreateChild("Terrain");

            terrainNode.Position = (Vector3.Zero);
            Terrain terrain = terrainNode.CreateComponent <Terrain>();

            terrain.PatchSize = 64;
            terrain.Spacing   = new Vector3(2.0f, 0.1f, 2.0f);           // Spacing between vertices and vertical resolution of the height map
            terrain.Smoothing = true;
            terrain.SetHeightMap(cache.GetImage("Textures/HeightMap.png"));
            terrain.Material = cache.GetMaterial("Materials/Terrain.xml");
            // The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
            // terrain patches and other objects behind it
            terrain.Occluder = true;

            RigidBody body = terrainNode.CreateComponent <RigidBody>();

            body.CollisionLayer = 2;             // Use layer bitmask 2 for static geometry
            CollisionShape shape = terrainNode.CreateComponent <CollisionShape>();

            shape.SetTerrain(0);

            // Create 1000 mushrooms in the terrain. Always face outward along the terrain normal
            const uint numMushrooms = 1000;

            for (uint i = 0; i < numMushrooms; ++i)
            {
                Node    objectNode = scene.CreateChild("Mushroom");
                Vector3 position   = new Vector3(NextRandom(2000.0f) - 1000.0f, 0.0f, NextRandom(2000.0f) - 1000.0f);
                position.Y          = terrain.GetHeight(position) - 0.1f;
                objectNode.Position = (position);
                // Create a rotation quaternion from up vector to terrain normal
                objectNode.Rotation = Quaternion.FromRotationTo(Vector3.UnitY, terrain.GetNormal(position));
                objectNode.SetScale(3.0f);
                StaticModel sm = objectNode.CreateComponent <StaticModel>();
                sm.Model = (cache.GetModel("Models/Mushroom.mdl"));
                sm.SetMaterial(cache.GetMaterial("Materials/Mushroom.xml"));
                sm.CastShadows = true;

                body = objectNode.CreateComponent <RigidBody>();
                body.CollisionLayer = 2;
                shape = objectNode.CreateComponent <CollisionShape>();
                shape.SetTriangleMesh(sm.Model, 0, Vector3.One, Vector3.Zero, Quaternion.Identity);
            }
        }
        public override RigidBody LocalCreateRigidBody(float mass, Matrix startTransform, CollisionShape shape, bool isKinematic = false)
        {
            //rigidbody is dynamic if and only if mass is non zero, otherwise static
            bool isDynamic = (mass != 0.0f);

            Vector3 localInertia = Vector3.Zero;

            if (isDynamic)
            {
                shape.CalculateLocalInertia(mass, out localInertia);
            }

            //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects

            RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, null, shape, localInertia);
            RigidBody body = new RigidBody(rbInfo);

            rbInfo.Dispose();
            body.ContactProcessingThreshold = defaultContactProcessingThreshold;
            body.WorldTransform             = startTransform;

            World.AddRigidBody(body);

            return(body);
        }
        //called by Physics World just before rigid body is added to world.
        //the current rigid body properties are used to rebuild the rigid body.
        internal override bool _BuildCollisionObject()
        {
            if (td == null)
            {
                Debug.LogError("Must be attached to an object with a terrain ");
                return(false);
            }
            BPhysicsWorld world = BPhysicsWorld.Get();

            if (m_collisionObject != null)
            {
                if (isInWorld && world != null)
                {
                    isInWorld = false;
                    world.RemoveCollisionObject(this);
                }
            }

            if (transform.localScale != UnityEngine.Vector3.one)
            {
                Debug.LogError("The local scale on this collision shape is not one. Bullet physics does not support scaling on a rigid body world transform. Instead alter the dimensions of the CollisionShape.");
            }

            m_collisionShape = GetComponent <BCollisionShape>();
            if (m_collisionShape == null)
            {
                Debug.LogError("There was no collision shape component attached to this BRigidBody. " + name);
                return(false);
            }
            if (!(m_collisionShape is BHeightfieldTerrainShape))
            {
                Debug.LogError("The collision shape needs to be a BHeightfieldTerrainShape. " + name);
                return(false);
            }

            CollisionShape cs = m_collisionShape.GetCollisionShape();

            //rigidbody is dynamic if and only if mass is non zero, otherwise static

            if (m_collisionObject == null)
            {
                m_collisionObject = new CollisionObject();
                m_collisionObject.CollisionShape = cs;
                m_collisionObject.UserObject     = this;

                BulletSharp.Math.Matrix worldTrans = BulletSharp.Math.Matrix.Identity;
                Vector3 pos = transform.position + new Vector3(td.size.x * .5f, td.size.y * .5f, td.size.z * .5f);
                worldTrans.Origin = pos.ToBullet();
                m_collisionObject.WorldTransform = worldTrans;
                m_collisionObject.CollisionFlags = m_collisionFlags;
            }
            else
            {
                m_collisionObject.CollisionShape = cs;
                BulletSharp.Math.Matrix worldTrans = BulletSharp.Math.Matrix.Identity;
                Vector3 pos = transform.position + new Vector3(td.size.x * .5f, td.size.y * .5f, td.size.z * .5f);
                worldTrans.Origin = pos.ToBullet();
                m_collisionObject.WorldTransform = worldTrans;
                m_collisionObject.CollisionFlags = m_collisionFlags;
            }
            return(true);
        }
Ejemplo n.º 38
0
    public static GameObject CreateAndRegisterSeedForPlant(GameObject plant, SeedProducer.ProductionType productionType, string id, string name, string desc, KAnimFile anim, string initialAnim = "object", int numberOfSeeds = 1, List <Tag> additionalTags = null, SingleEntityReceptacle.ReceptacleDirection planterDirection = SingleEntityReceptacle.ReceptacleDirection.Top, Tag replantGroundTag = default(Tag), int sortOrder = 0, string domesticatedDescription = "", CollisionShape collisionShape = CollisionShape.CIRCLE, float width = 0.25f, float height = 0.25f, Recipe.Ingredient[] recipe_ingredients = null, string recipe_description = "", bool ignoreDefaultSeedTag = false)
    {
        GameObject gameObject = CreateLooseEntity(id, name, desc, 1f, true, anim, initialAnim, Grid.SceneLayer.Front, collisionShape, width, height, true, SORTORDER.SEEDS + sortOrder, SimHashes.Creature, null);

        gameObject.AddOrGet <EntitySplitter>();
        CreateAndRegisterCompostableFromPrefab(gameObject);
        PlantableSeed plantableSeed = gameObject.AddOrGet <PlantableSeed>();

        plantableSeed.PlantID                 = new Tag(plant.name);
        plantableSeed.replantGroundTag        = replantGroundTag;
        plantableSeed.domesticatedDescription = domesticatedDescription;
        plantableSeed.direction               = planterDirection;
        KPrefabID component = gameObject.GetComponent <KPrefabID>();

        foreach (Tag additionalTag in additionalTags)
        {
            component.AddTag(additionalTag, false);
        }
        if (!ignoreDefaultSeedTag)
        {
            component.AddTag(GameTags.Seed, false);
        }
        component.AddTag(GameTags.PedestalDisplayable, false);
        KPrefabID component2 = gameObject.GetComponent <KPrefabID>();

        Assets.AddPrefab(component2);
        SeedProducer seedProducer = plant.AddOrGet <SeedProducer>();

        seedProducer.Configure(gameObject.name, productionType, numberOfSeeds);
        return(gameObject);
    }
Ejemplo n.º 39
0
    public void ExitPhysics()
    {
        if (m_inverseModel != null)
        {
            Debug.Log("Dispose inverse model " + m_inverseModel.NumBodies);
            m_inverseModel.Dispose();
        }

        Debug.Log("InverseDynamicsExitPhysics");
        //cleanup in the reverse order of creation/initialization

        //remove the rigidbodies from the dynamics world and delete them

        if (m_dynamicsWorld == null)
        {
            int i;
            for (i = m_dynamicsWorld.NumConstraints - 1; i >= 0; i--)
            {
                TypedConstraint tc = m_dynamicsWorld.GetConstraint(i);
                m_dynamicsWorld.RemoveConstraint(tc);
                tc.Dispose();
            }

            for (i = m_dynamicsWorld.NumMultiBodyConstraints - 1; i >= 0; i--)
            {
                MultiBodyConstraint mbc = m_dynamicsWorld.GetMultiBodyConstraint(i);
                m_dynamicsWorld.RemoveMultiBodyConstraint(mbc);
                mbc.Dispose();
            }

            for (i = m_dynamicsWorld.NumMultibodies - 1; i >= 0; i--)
            {
                MultiBody mb = m_dynamicsWorld.GetMultiBody(i);
                m_dynamicsWorld.RemoveMultiBody(mb);
                mb.Dispose();
            }
            for (i = m_dynamicsWorld.NumCollisionObjects - 1; i >= 0; i--)
            {
                CollisionObject obj  = m_dynamicsWorld.CollisionObjectArray[i];
                RigidBody       body = RigidBody.Upcast(obj);
                if (body != null && body.MotionState != null)
                {
                    body.MotionState.Dispose();
                }
                m_dynamicsWorld.RemoveCollisionObject(obj);
                obj.Dispose();
            }
        }

        if (m_multiBody != null)
        {
            m_multiBody.Dispose();
        }

        //delete collision shapes
        for (int j = 0; j < CollisionShapes.Count; j++)
        {
            CollisionShape shape = CollisionShapes[j];
            shape.Dispose();
        }
        CollisionShapes.Clear();

        m_dynamicsWorld.Dispose();
        m_dynamicsWorld = null;

        m_solver.Dispose();
        m_solver = null;

        Broadphase.Dispose();
        Broadphase = null;

        Dispatcher.Dispose();
        Dispatcher = null;

        m_pairCache.Dispose();
        m_pairCache = null;

        CollisionConf.Dispose();
        CollisionConf = null;

        CollisionShapes.Clear();
        links.Clear();

        Debug.Log("After dispose B");
    }
        public void Evaluate(int SpreadMax)
        {
            this.frameBodyOutput.Clear();

            IRigidBodyContainer inputWorld = this.worldInput[0];

            if (inputWorld != null)
            {
                this.persistedList.UpdateWorld(inputWorld);

                if (this.shapesInput.IsConnected)
                {
                    for (int i = 0; i < SpreadMax; i++)
                    {
                        if (doCreate[i])
                        {
                            RigidBodyPose             pose             = this.initialPoseInput.IsConnected ? this.initialPoseInput[i] : RigidBodyPose.Default;
                            RigidBodyProperties       properties       = this.initialProperties.IsConnected ? this.initialProperties[i] : RigidBodyProperties.Default;
                            RigidBodyMotionProperties motionProperties = this.initialMotionProperties.IsConnected ? this.initialMotionProperties[i] : new RigidBodyMotionProperties();

                            ShapeCustomData            shapeData = new ShapeCustomData();
                            DynamicShapeDefinitionBase shape     = this.shapesInput[i];
                            shapeData.ShapeDef = shape;

                            CollisionShape collisionShape = shapeData.ShapeDef.GetShape(shapeData);

                            //Build mass for dynamic object
                            Vector3 localinertia = Vector3.Zero;
                            if (shape.Mass > 0.0f)
                            {
                                collisionShape.CalculateLocalInertia(shape.Mass, out localinertia);
                            }

                            Tuple <RigidBody, int> createBodyResult = inputWorld.CreateRigidBody(collisionShape, ref pose, ref properties, ref localinertia, shape.Mass, this.customString[i]);
                            createBodyResult.Item1.CollisionFlags |= CollisionFlags.KinematicObject;

                            createBodyResult.Item1.ApplyMotionProperties(ref motionProperties);

                            this.persistedList.Append(createBodyResult.Item1, createBodyResult.Item2);
                            frameBodyOutput.Add(createBodyResult.Item1);
                        }
                    }
                }

                this.bodiesOutput.SliceCount = this.persistedList.Bodies.Count;
                this.idOutput.SliceCount     = this.persistedList.Ids.Count;

                List <RigidBody> bodies = this.persistedList.Bodies;
                List <int>       ids    = this.persistedList.Ids;

                for (int i = 0; i < bodies.Count; i++)
                {
                    this.bodiesOutput[i] = bodies[i];
                    this.idOutput[i]     = ids[i];
                }

                this.createdBodiesOutput.SliceCount = this.frameBodyOutput.Count;
                for (int i = 0; i < frameBodyOutput.Count; i++)
                {
                    this.createdBodiesOutput[i] = frameBodyOutput[i];
                }
            }
            else
            {
                this.bodiesOutput.SliceCount        = 0;
                this.idOutput.SliceCount            = 0;
                this.createdBodiesOutput.SliceCount = 0;
            }
        }
Ejemplo n.º 41
0
 public SoftBody(SoftBodyWorldInfo worldInfo, int nodeCount, Vector3[] x, float[] m)
     : base(btSoftBody_new(worldInfo._native, nodeCount, x, m))
 {
     _collisionShape = new CollisionShape(btCollisionObject_getCollisionShape(_native), true);
     _worldInfo = worldInfo;
 }
 public override void _Ready()
 {
     _animationPlayer = GetNode <AnimationPlayer>("AnimationPlayer");
     _collisionShape  = GetNode <CollisionShape>("CollisionShape");
 }
Ejemplo n.º 43
0
 //private AlignedIntArray _userIndexMapping;
 internal SoftBody(IntPtr native)
     : base(native)
 {
     //_collisionShape = new SoftBodyCollisionShape(CollisionShape);
     _collisionShape = new CollisionShape(btCollisionObject_getCollisionShape(native), true);
 }
Ejemplo n.º 44
0
 //public void startDraw(GraphicsDevice graphicsDevice,ref IndexedMatrix view, ref IndexedMatrix projection)
 //{
 //    ((DefaultDebugDraw)m_debugDraw).update(graphicsDevice, ref view, ref projection);
 //}
 public virtual void DrawShadow(IndexedMatrix m, IndexedVector3 extrusion, CollisionShape shape, IndexedVector3 worldBoundsMin, IndexedVector3 worldBoundsMax)
 {
     DrawShadow(m, extrusion, shape, worldBoundsMin, worldBoundsMax);
 }
Ejemplo n.º 45
0
        public void DebugDrawObject(Matrix worldTransform, CollisionShape shape, Vector3 color)
        {
            if (shape.ShapeType == BroadphaseNativeTypes.Compound)
            {
                CompoundShape compoundShape = shape as CompoundShape;
                for (int i = compoundShape.ChildShapeCount - 1; i >= 0; i--)
                {
                    Matrix childTrans = compoundShape.GetChildTransform(i);
                    CollisionShape colShape = compoundShape.GetChildShape(i);
                    DebugDrawObject(worldTransform * childTrans, colShape, color);
                }

            }
            else
            {
                switch (shape.ShapeType)
                {

                    case BroadphaseNativeTypes.Sphere:
                        {
                            SphereShape sphereShape = shape as SphereShape;
                            float radius = sphereShape.Margin;//radius doesn't include the margin, so draw with margin
                            Vector3 start = worldTransform.Translation;
                            DebugDrawer.DrawLine(start, start + Vector3.TransformNormal(new Vector3(radius, 0, 0), worldTransform), color);
                            DebugDrawer.DrawLine(start, start + Vector3.TransformNormal(new Vector3(0, radius, 0), worldTransform), color);
                            DebugDrawer.DrawLine(start, start + Vector3.TransformNormal(new Vector3(0, 0, radius), worldTransform), color);
                            //drawSphere
                            break;
                        }
                    case BroadphaseNativeTypes.MultiSphere:
                    case BroadphaseNativeTypes.Cone:
                        {
                            ConeShape coneShape = shape as ConeShape;
                            float radius = coneShape.Radius;//+coneShape->getMargin();
                            float height = coneShape.Height;//+coneShape->getMargin();
                            Vector3 start = worldTransform.Translation;
                            DebugDrawer.DrawLine(start + Vector3.TransformNormal(new Vector3(0f, 0f, 0.5f * height), worldTransform), start + Vector3.TransformNormal(new Vector3(radius, 0f, -0.5f * height), worldTransform), color);
                            DebugDrawer.DrawLine(start + Vector3.TransformNormal(new Vector3(0f, 0f, 0.5f * height), worldTransform), start + Vector3.TransformNormal(new Vector3(-radius, 0f, -0.5f * height), worldTransform), color);
                            DebugDrawer.DrawLine(start + Vector3.TransformNormal(new Vector3(0f, 0f, 0.5f * height), worldTransform), start + Vector3.TransformNormal(new Vector3(0f, radius, -0.5f * height), worldTransform), color);
                            DebugDrawer.DrawLine(start + Vector3.TransformNormal(new Vector3(0f, 0f, 0.5f * height), worldTransform), start + Vector3.TransformNormal(new Vector3(0f, -radius, -0.5f * height), worldTransform), color);
                            break;
                        }
                    case BroadphaseNativeTypes.Cylinder:
                        {
                            CylinderShape cylinder = shape as CylinderShape;
                            int upAxis = cylinder.UpAxis;
                            float radius = cylinder.Radius;
                            float halfHeight = MathHelper.GetElement(cylinder.HalfExtents, upAxis);
                            Vector3 start = worldTransform.Translation;
                            Vector3 offsetHeight = new Vector3();
                            MathHelper.SetElement(ref offsetHeight, upAxis, halfHeight);
                            Vector3 offsetRadius = new Vector3();
                            MathHelper.SetElement(ref offsetRadius, (upAxis + 1) % 3,  radius);
                            DebugDrawer.DrawLine(start + Vector3.TransformNormal(offsetHeight + offsetRadius, worldTransform), start + Vector3.TransformNormal(-offsetHeight + offsetRadius, worldTransform), color);
                            DebugDrawer.DrawLine(start + Vector3.TransformNormal(offsetHeight - offsetRadius, worldTransform), start + Vector3.TransformNormal(-offsetHeight - offsetRadius, worldTransform), color);
                            break;
                        }
                    default:
                        {
                            if (shape.ShapeType == BroadphaseNativeTypes.TriangleMesh)
                            {
                                TriangleMeshShape concaveMesh = shape as TriangleMeshShape;
                                //btVector3 aabbMax(1e30f,1e30f,1e30f);
                                //btVector3 aabbMax(100,100,100);//1e30f,1e30f,1e30f);

                                //todo pass camera, for some culling
                                Vector3 aabbMax = new Vector3(1e30f, 1e30f, 1e30f);
                                Vector3 aabbMin = new Vector3(-1e30f, -1e30f, -1e30f);

                                DebugDrawCallback drawCallback = new DebugDrawCallback(DebugDrawer, worldTransform, color);
                                concaveMesh.ProcessAllTriangles(drawCallback, aabbMin, aabbMax);
                            }

                            if (shape.ShapeType == BroadphaseNativeTypes.ConvexTriangleMesh)
                            {
                                ConvexTriangleMeshShape convexMesh = shape as ConvexTriangleMeshShape;
                                //todo: pass camera for some culling
                                Vector3 aabbMax = new Vector3(1e30f, 1e30f, 1e30f);
                                Vector3 aabbMin = new Vector3(-1e30f, -1e30f, -1e30f);
                                //DebugDrawcallback drawCallback;
                                DebugDrawCallback drawCallback = new DebugDrawCallback(DebugDrawer, worldTransform, color);
                                convexMesh.getStridingMesh().InternalProcessAllTriangles(drawCallback, aabbMin, aabbMax);
                            }

                            // for polyhedral shapes
                            if (shape.IsPolyhedral)
                            {
                                PolyhedralConvexShape polyshape = shape as PolyhedralConvexShape;

                                for (int i = 0; i < polyshape.EdgeCount; i++)
                                {
                                    Vector3 a, b;
                                    polyshape.GetEdge(i, out a, out b);
                                    a = Vector3.TransformNormal(a, worldTransform);
                                    b = Vector3.TransformNormal(b, worldTransform);
                                    DebugDrawer.DrawLine(a, b, color);
                                }
                            }
                            break;
                        }
                }
            }
        }
Ejemplo n.º 46
0
        public override RigidBody LocalCreateRigidBody(float mass, Matrix startTransform, CollisionShape shape, bool isKinematic)
        {
            //rigidbody is dynamic if and only if mass is non zero, otherwise static
            bool isDynamic = (mass != 0.0f);

            Vector3 localInertia = Vector3.Zero;

            if (isDynamic)
            {
                shape.CalculateLocalInertia(mass, out localInertia);
            }

            //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects

            RigidBody body;

            using (var rbInfo = new RigidBodyConstructionInfo(mass, null, shape, localInertia))
            {
                body = new RigidBody(rbInfo);
            }

            body.WorldTransform = startTransform;
            World.AddRigidBody(body, CollisionFilterGroups.DefaultFilter,
                               CollisionFilterGroups.DefaultFilter | CollisionFilterGroups.StaticFilter);
            return(body);
        }