Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

[RELEASED] Bullet Physics For Unity

Discussion in 'Assets and Asset Store' started by Phong, May 31, 2016.

  1. zhuchun

    zhuchun

    Joined:
    Aug 11, 2012
    Posts:
    427
    Very cool! THANK YOU! ;)
     
  2. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    I updated the libs in the project on github so they are release builds instead of debug builds. If you checkout:

    https://github.com/Phong13/BulletSharpUnity3d

    And copy the libbulletc.dll from both Plugins/BulletUnity/Native/x86 and Plugins/BulletUnity/Native/x64. After copying check configuration for each of these in the inspector. I think I had x86 used for the editor which is not correct.
     
    zhuchun likes this.
  3. zhuchun

    zhuchun

    Joined:
    Aug 11, 2012
    Posts:
    427
    Hi, I'm developing a multiplayer game and I use BulletSharp as my math lib on the server-side(engine agnostic). However, I notice the namespace is inconsistent in this Asset, it's BulletSharp.Math instead. Then a strange question comes to my mind, if I use bulletSharp on the server-side and use BulletUnity on the client-side, would their result be identical/deterministic?
     
    Last edited: May 17, 2018
  4. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    As long as the Structs and Classes inside each namespace have their data aligned the same way (data types are the same, fields are in the same order, are using [StructLayout(LayoutKind.Sequential)] or similar). Then there should be no interop problems.

    You could probably diff the two versions of BulletSharp.Math and sync differences. If there are no data alignment differences then everything should still work.
     
    zhuchun likes this.
  5. zhuchun

    zhuchun

    Joined:
    Aug 11, 2012
    Posts:
    427
    Hi, Can the libbullectc.dll run on DotNet server-side as well? (Update: It works)

    I tried to build it from Phong13/BulletSharpPInvoke, but the Build Instructions of AndresTraks/BulletSharpPInvoke doesn't work, CMake threw a few set property argument errors. Would you please share your build steps?
     
    Last edited: Jul 9, 2018
  6. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    I have been working on an update for the Bullet Physics plugin that uses a newer version of the bullet physics engine and some Inverse Dynamics wrappers. I will post the instructions of that later today as they are cleaner than the old instructions.

    Here is a link to some old notes.

    http://digitalopus.ca/site/building-bullet-physics-for-unity/

    My notes for the new process work like this:


    Hack the CMake files. This appears to work very well on Windows using Visual Studio 2017. I have not tried using this process to build for other platforms yet.

    • Clean github checkout of bullet release 2.87 (or latest relase)

    • Clean github checkout of Phong13/BulletSharpPInvoke (branch upgrade-bullet-2.87)

    • Copy the libbulletc folder into the clean bullet checkout src folder

    • Edit CMakeLists.txt in root of bullet. Append SUBDIRS(libbulletc) to the end of the file.

    • Note that I needed to include the PyBullet stuff in the build options or the generated libbulletc library didn’t work. I needed this even though pybullet is a separate project:

    • Tweek CMakeLists.txt in root with
      • after FIND_PACKAGE(PythonLibs ${PYTHON_VERSION_STRING} EXACT)

      • SET(PYTHON_LIBRARIES "C:/Users/[USER_DIR]/AppData/local/Programs/Python/Python36-32/libs/python36.lib")

      • SET(PYTHON_LIBRARY "C:/Users/[USER_DIR]/AppData/local/Programs/Python/Python36-32/libs/python36.lib")
    • Run CMake with
      • BUILD_BULLET2_DEMOS

      • BUILD_BULLET3

      • BUILD_CLSOCKET

      • BUILD_ENET

      • BUILDOPENGL3_DEMOS

      • BUILD_PYBULLET

      • BUILD_PYBULLET_CLSOCKET

      • BUILD_PYBULLET_ENET

    Don’t need to include pybullet in the build. The generated bullet project should build the libbulletc beautifully. Do this by right clicking on the libbulletc project and choosing build.

    Note that I have not yet tried the CMake process to build for any platforms other than Windows
     
    Last edited: Jul 10, 2018
    zhuchun likes this.
  7. zhuchun

    zhuchun

    Joined:
    Aug 11, 2012
    Posts:
    427

    Thank you! I've read the source, as you said, it's easier than expected :) Next, I will try to implement things for both server-side and client-side, your instructions are important to me.
     
  8. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    Hi Zhuchun, I am curious how you have made out? Are you using the old instructions or new?
     
  9. zhuchun

    zhuchun

    Joined:
    Aug 11, 2012
    Posts:
    427
    I didn't actually ;) Failed on the old one and still don't know how to built it, but I use the libbullectc.dll from your Github to learn bullet(cpp).

    Currently, I've made a JSON serializer so Unity can export a whole phsyics scene to server-side. Next, I want to customize more useful ResultCallback and maximaize the performance on single thread, I'm sure it will helps if I can build dlls ;)
     
  10. Marblr

    Marblr

    Joined:
    Jun 29, 2018
    Posts:
    4
    Hey @Phong, as a Unity beginner I recently began trying out this plugin and I'm happy to see you're still active on this thread after a couple years. I'm having a bit of an odd issue that maybe you or another poster could shed some light on. It's as if Bullet is not applying forces to rigid bodies at random time steps.

    When I apply a force to the ball I get wildly different accelerations each time. I have tested it with AddForce and AddImpulse, with and without CCD, with multiple combinations of simulation frequencies and sub steps, different drag and friction values, and even in midair. I also tried moving code between Update and FixedUpdate, however the problem is much more exaggerated in FixedUpdate. It's also worth noting that the code works just fine when adjusted for a PhysX rigid body. The video below illustrates the problem, note I switch the force direction each time I pass the pole in the background.



    The basic code being used:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using BulletUnity;
    6.  
    7. public class BMarbleMovement : MonoBehaviour
    8. {
    9.     // Debug
    10.     private Vector3 camForward;
    11.     private Vector3 camRight;
    12.     private float inputForward;
    13.     private float inputRight;
    14.     private Vector3 movementDirection;
    15.     private Vector3 marbleVelocity;
    16.  
    17.     public float rollSpeed; // 15.0f
    18.     public float jumpImpulse; // 11.0f
    19.  
    20.     public Transform cam;
    21.  
    22.     private BRigidBody marble;
    23.  
    24.     void Start()
    25.     {
    26.         marble = GetComponent<BRigidBody>();
    27.         // Enable CCD
    28.         marble.ccdMotionThreshold = 0.66f;
    29.         marble.ccdSweptSphereRadius = 0.66f;
    30.     }
    31.  
    32.     void Update()
    33.     {
    34.         // Poll for input
    35.         inputForward = Input.GetAxisRaw("Forward");
    36.         inputRight = Input.GetAxisRaw("Right");
    37.  
    38.         // Get camera vectors
    39.         camForward = cam.forward;
    40.         camRight = cam.right;
    41.  
    42.         camForward.y = 0;
    43.         camRight.y = 0;
    44.  
    45.         // Normalize vectors and apply inputs
    46.         movementDirection = (camForward.normalized * inputForward) + (camRight.normalized * inputRight);
    47.  
    48.         movementDirection = movementDirection.normalized;
    49.  
    50.         // Move the ball
    51.         marble.AddForce(movementDirection * rollSpeed);
    52.  
    53.         marbleVelocity = marble.velocity;
    54.     }
    Thanks in advance for any help.
     
    Last edited: Aug 2, 2018
  11. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    Hi Marblr,

    I think the problem is likely due to the timing of the simulation step. I have been working on a new version with an updated Bullet version. In this version I have switched the timing of FixedUpdate so that it always steps the time exactly 1/60 seconds instead of using Time.fixedDeltaTime which is usually slightly different from 1/60 seconds. The problem with using Time.fixedDeltaTime is that sometimes Bullet would simulate no new timesteps, sometimes one timestep and sometimes Bullet would simulate two time steps. By using 1/60 seconds then Bullet always simulates exactly one timestep per fixed update step. The new code for BPhysicsWorldLateHelper.FixedUpdate looks like:

    Code (CSharp):
    1.         protected virtual void FixedUpdate()
    2.         {
    3.             if (m_physicsWorld.m_manualStepSimulation)
    4.             {
    5.                 return;
    6.             }
    7.  
    8.             if (m_ddWorld != null)
    9.             {
    10.                 float deltaTime = UnityEngine.Time.time - m_lastSimulationStepTime;
    11.                 if (deltaTime > 0f)
    12.                 {
    13.                     ///stepSimulation proceeds the simulation over 'timeStep', units in preferably in seconds.
    14.                     ///By default, Bullet will subdivide the timestep in constant substeps of each 'fixedTimeStep'.
    15.                     ///in order to keep the simulation real-time, the maximum number of substeps can be clamped to 'maxSubSteps'.
    16.                     ///You can disable subdividing the timestep/substepping by passing maxSubSteps=0 as second argument to stepSimulation, but in that case you have to keep the timeStep constant.
    17.                     int numSteps = m_ddWorld.StepSimulation(m_fixedTimeStep, m_maxSubsteps, m_fixedTimeStep);
    18.                  
    19.                     m__frameCount += numSteps;
    20.                     //Debug.Log("FixedUpdate " + numSteps);
    21.                     m_lastSimulationStepTime = UnityEngine.Time.time;
    22.                 }
    23.             }
    24.  
    25.             //collisions
    26.             if (m_collisionEventHandler != null)
    27.             {
    28.                 m_collisionEventHandler.OnPhysicsStep(m_world);
    29.             }
    30.         }
     
    Last edited: Aug 8, 2018
  12. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,579
    Hi Phong.

    Got rather serous question, providing you are familiar with ECS and Job System.
    Do you think porting bullet Physics to ECS with Job System is feasible?

    I think this could have massive bust for the performance, since you don't use native Unity collision system.
     
  13. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,579
    I run benchmark demos

    One of them feels broken.
    At least inputs. (Tested on Unity 2018.2)
    BenchmarkDemo with index 2. I had to hardcore (change) index, since there is no input method, to switch benchmarks with keys.

    BS-BenchmarkDemo2.png

    Also, walls feels a bit bouncy when settling.

    At end of the day, I can not shoot at them. Supposedly is a space bar.
    After pressing space, got following error :
    NullReferenceException: Object reference not set to an instance of an object
    DemoFramework.Demo.GetRayTo (Point point, Vector3 eye, Vector3 target, Single fov) (at Assets/BulletUnity/Examples/Scenes/BulletSharpDemos/BulletSharpDemos/DemoFramework/Demo.cs:489)
    DemoFramework.Demo_OnHandleInput () (at Assets/BulletUnity/Examples/Scenes/BulletSharpDemos/BulletSharpDemos/DemoFramework/Demo.cs:326)
    BulletExampleRunner.Update () (at Assets/BulletUnity/Examples/Scenes/BulletSharpDemos/BulletSharpDemos/BulletExampleRunner.cs:301)

    BS-BenchmarkDemo2-No shoot.png
     
  14. zhuchun

    zhuchun

    Joined:
    Aug 11, 2012
    Posts:
    427
    We're doing similar things with Entitas, wrapping BPE as a service. BPE is quite straightforward, for general purpose, you only need to expose a few methods(less than 10) to your ECS core. Read more about this architecture and see if it fits you https://github.com/sschmid/Entitas-CSharp/wiki/How-I-build-games-with-Entitas-(FNGGames)

    Since you mentioned about multi-threading and performance, here're 2 facts you may want to know as well.
    1. Unity uses GPU accelerated PhysX which means it's super fast already.
    2. Multi-threading/JobSystem are not magic, you have to take care of thread-safe problems. Things may go crazy because you're dealing with Multi-threading unmanaged code.

    You can read the manual and source first, they shouldn't take too much time.
     
    Antypodish likes this.
  15. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,579
    Many thx,
    I have grabbed the link. I will check out what is there.
     
  16. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    Hi Antypodish, regarding ECS. The bullet 'step simulation' is already fairly optimized in Native code. There are some parts of bullet that are already mutithreaded and Bullet 3 has some GPU support (although at this time the Bullet 3 API does not have C# wrappers). The part that might benefit from ECS would be transferring the positions/rotations of the objects from the Bullet world to Unity and vice versa.

    Regarding the Benchmark Demo. Yes there is a lot of functionality in the Bullet Demos that has not been implemented on the Unity example runner. This is because the Example Runner that I wrote is not very efficient the way it is written. It is intended to only be a reference to verify that the wrappers are working as expected. It is written the way it is so that the examples can be run with minimal changes. To make it more efficient would require re-writing the demos which would make them less useful as a reference. I have chosen to focus my development effort on the wrappers and the Bullet Unity components rather than improving the example runner.
     
  17. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,579
    Thx Phong.

    Both matters makes sense.
    Indeed I realized that appropriate coupling need to be written, to combine ECS and Bullet. Of which passing between mentioned rotation and position, should be mostly sufficient, for basics applications. Then perhaps additional forces etc., if applicable.

    Regarding Bullet3, of which you mentioned, I did some search.
    I found following
    bullet3/examples/pybullet/unity3d/
    https://github.com/bulletphysics/bullet3/tree/master/examples/pybullet/unity3d

    Citation
    Quick prototype to connect Unity 3D to pybullet

    Generate C# Native Methods using the Microsoft PInvoke Signature Toolkit:

    sigimp.exe /lang:cs e:\develop\bullet3\examples\SharedMemory\PhysicsClientC_API.h

    Add some #define B3_SHARED_API __declspec(dllexport) to the exported methods,
    replace [3], [4], [16] by [] to get sigimp.exe working.

    This generates autogen/NativeMethods.cs

    Then put pybullet.dll in the right location, so Unity finds it.

    NewBehaviourScript.cs is a 1 evening prototype that works within Unity 3D:
    Create a connection to pybullet, reset the world, load a urdf at startup.
    Step the simulation each Update.

    Now the real work can start, converting Unity objects to pybullet,
    pybullet robots to Unity, synchronizing the transforms each Update.

    void Start () {
    IntPtr pybullet = b3ConnectSharedMemory(12347);
    IntPtr cmd = b3InitResetSimulationCommand(pybullet);
    IntPtr status = b3SubmitClientCommandAndWaitStatus(pybullet, cmd);
    cmd = b3LoadUrdfCommandInit(pybullet, "plane.urdf");
    status = b3SubmitClientCommandAndWaitStatus(pybullet, cmd);
    }

    void Update ()
    {
    IntPtr cmd = b3InitStepSimulationCommand(pybullet);
    IntPtr status = b3SubmitClientCommandAndWaitStatus(pybullet, cmd);
    }

    Also:
    Pybullet Quick Start Guide
    https://docs.google.com/document/d/10sXEhzFRSnvFcl3XxNGhnD4N2SedqwdAvK3dsihxVUA/edit#

    But don't know at this point, if or how this can be of help.


    Personally I have no experience in c++ to c# wrappers development. But how complex these process is?
     
  18. Marblr

    Marblr

    Joined:
    Jun 29, 2018
    Posts:
    4
    Thanks for the clarification, I take it I won't be able to fix the issue until the new version is released? I tried using your code snippet but it references things I don't have in my BulletUnity stuff (m_manualStepSimulation, TestTorquesToJoints, etc). Am I missing anything? Either way I eagerly await the update. :)
     
  19. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,579
    Regarding benchmarking.
    I run some extra test.
    Similar to one, I did while ago, but this time I have built the project.

    Case 1:
    I run ExampleRunners with 12x12x20 boxes. Which gives 2880 boxes in stack.
    Then drop them on the surface. Performance in both scene and build were almost the same.
    But reaching wind speed of 3 FPS ONLY :eek:
    Single trehaded


    Case 2:

    While equivalent of PhysX, runs at average 25 fps.
    Multi threaded cores, No GPU.


    BulletPhysics Limit Issue

    Not only that. If I spawning+3000 cubes, Bullet Physics (both scene and build) crashes.
    In contrast, I can have on PhysX over 4 times that, and frames fluctuating around 2-3 fps. but no crash.

    I have noticed comment in script
    Code (CSharp):
    1. switch (benchmark)
    2.             {
    3.                 case 1:
    4.                     // 3000
    But I thought is number of spawned boxes initially. But not, since there are 8x8x*20.


    So is the way, to switch multi threading?
    I thought Bullet2.x supports it?

    Or I missing something obvious. Maybe switch?
     
  20. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    I modified the code I posted. The TestTorquesToJoints and m_manualStepSimulation can be removed. It is just some debugging code. It allowed me to step the simulation with a keypress instead of stepping every fixedUpdate which can be useful when debugging.
     
  21. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    Are you using the asset store version or the github version? The asset store version I think currently has a debug build of the .dll which slows it down a lot. I have been meaning to switch it for the github build but have not done it yet.

    Re: multithreading, in the Bullet 2 API there is a multithreaded constraint solver. I am not sure if anything else is MultiThreaded. The Bullet 3 API has more support for multithreading and some support for GPU computation but there are no C# wrappers for it yet. My new code for creating the physics which supports the multithreaded constraint solver is in github on the "feature/upgradebullet-2.87" branch. TBH I haven't tested the multithreaded constraint solver yet. There may be issues if there are callbacks from bullet to the Unity API that come from other threads.

    https://github.com/Phong13/BulletSharpUnity3d/tree/feature/upgradebullet-2.87
     
  22. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,579
    I just double checked, since I got both asset store and latest github versions.
    The test was done on the github version.

    Unfortunately, for whatever reason, the build test app, did run strictly on single core. I have no further expertise, how to trigger multi-core functionality, if there is one indeed. I may have missed something. One thing did buffled me, was the stability. Rather instability, if number of objects exceeds, certain capacity +3k.

    I will keep eye on BulletSharp wrapper for Bullet3. But I guess, should not expect anytime soon.
    Thx anyway.
     
  23. Marblr

    Marblr

    Joined:
    Jun 29, 2018
    Posts:
    4
    Thanks, I hadn't noticed that the first parameter of m_ddWorld.StepSimulation changed to m_fixedTimeStep, that seems to have fixed it.

    I hate to burden you further but I've been trying to figure out how to use collision callbacks; all examples and Bullet wiki info I can find are C++ and I'm struggling to get it working in BulletSharp/BulletUnity.

    As seen in the video I posted above, the ball is the only rigid body I would be simulating in a scene. My goal is to check if it is colliding with anything every physics tick, and return info about the contact point (for example, calculating the surface normal to determine if the ball is touching the ground or a wall). I've spent the past several days trying to figure this out.

    Thanks in advance.
     
    Last edited: Aug 18, 2018
  24. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    There is an example scene CollisionCallbacks that shows one way to do it using the bullet unity components. After each step simulation, It iterates over the collision manifolds. Contacts are tracked from frame to frame in HashSets. If a contact is new (didn't exist last frame) then "OnCollisionEnter" is called. If a contact existed last frame then "OnCollisionStay" is called. If a contact existed last frame but is gone this frame then "OnCollisionExit" is called.
     
  25. Marblr

    Marblr

    Joined:
    Jun 29, 2018
    Posts:
    4
    Thanks, I am able to determine when the rigid body is colliding but I still can't figure out how to return contact point data. At the very least I am seeking something like the coordinates of a contact point (like this seen in debug draw view) but I can't decipher BCollisionCallbacksDefault.cs. I may be missing something obvious, but I've tried writing every variable to a log to figure out what I'm looking for.

    Edit: I've come across more scenarios where physics results would differ depending on framerate. At the moment I'm looking into ways to prevent this, so my question above is no longer urgent.
     
    Last edited: Aug 20, 2018
  26. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    The contact points are the manifold points.

    Code (CSharp):
    1.     public override void BOnCollisionEnter(CollisionObject other, PersistentManifoldList manifoldList)
    2.     {
    3.         Debug.Log("On Collision Enter " + BPhysicsWorld.Get().frameCount);
    4.         // Persistent manifold list has all the contact points for all objecs this frame.
    5.         // To find the ones for this collision object need to search it to find manifolds including this
    6.         // object.
    7.  
    8.         // To get the manifold point.
    9.         ManifoldPoint mp = manifoldList.manifolds[0].GetContactPoint(0);
    10.         // To get the local cordinates on object A
    11.         BulletSharp.Math.Vector3 point = mp.LocalPointA;
    12.     }
     
  27. omarmoh

    omarmoh

    Joined:
    Apr 18, 2014
    Posts:
    16
    Not sure if this will help but when I use bullet physics I modify the late world helper a little, I completely remove the Update function and change the FixedUpdate function to something like this :
    Code (CSharp):
    1. void FixedUpdate()
    2.         {
    3.                    if (m_ddWorld != null)
    4.             {
    5.               m_ddWorld.StepSimulation(m_fixedTimeStep, 0, m_fixedTimeStep);
    6.                 }
    7.  
    8.             //collisions
    9.             if (m_collisionEventHandler != null)
    10.             {
    11.                 m_collisionEventHandler.OnPhysicsStep(m_world);
    12.             }
    13.         }
    Where m_fixedTimeStep could be 1/60 or what ever time step you want, and something i do is that i make the m_fixedTimeStep the same as Unity's Fixed Timestep in the Time Manager.
    Maybe you can give it a try, And try to mess around with Unity's Maximum Allowed Timestep if you didn't get the results you wanted.
    Good Luck!
     
  28. HouseFrog

    HouseFrog

    Joined:
    Jan 14, 2016
    Posts:
    29
    Hi Phong!

    When using a Convex Hull and a ramp as mesh, the ball rolls on top like this:



    Unity settings:


    Blender model:



    Thanks!
    /T
     
  29. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    Hi HouseFrog, that is the expected behaviour. That Collision Shape is "Convex". Meaning any concave parts are filled in. You will need to:
    • approximate the shape with multiple simple colliders (boxes)
    • use BVHTriangleMeshShape if it is static
    • use the GImpactTriangleMeshShape if it is dynamic
    Check out page 18 of the manual for a flowchart showing how to choose the right collision shape solution for your situation.

    https://en.blender.org/uploads/9/95/Dev-Physics-bullet-documentation.pdf.
     
  30. HouseFrog

    HouseFrog

    Joined:
    Jan 14, 2016
    Posts:
    29
    Thanks!
     
  31. manpower13

    manpower13

    Joined:
    Dec 22, 2013
    Posts:
    140
    Hey there!

    Looks very promising! Thank you!

    Not sure if it's a bug, or I am doing something wrong, but I was trying to get soft-body physics to work and got the following result:
    upload_2018-11-17_14-32-59.png

    You can see the soft-body floating in the air. The soft-body is created using:
    upload_2018-11-17_14-34-3.png
    No settings have been changed.

    All bounds look correct:
    upload_2018-11-17_14-35-16.png

    To fix this, I can set the value of extents:y of BBoxShape in the box to 0.25, instead of the generated 0.5:
    upload_2018-11-17_14-38-41.png

    This fixes the issue:
    upload_2018-11-17_14-39-21.png

    Do you know what I'm doing wrong?

    I was also wondering if you could give me a little hint in how to approach the following. I'd like to apply forces to a soft-body object, for E.G. user input. However, I cannot seem to get the proper combination of components to make it do what I want.
    I think I need the following components:
    BSoftBodyWMesh
    MeshFilter
    MeshRenderer
    BRigidBody
    BSphereShape (since the BRigidBody needs a collider)

    However, the soft-body already has a collider, otherwise it would fall through the ground. Therefore this gives an unstable spinning effect. I don't understand what components I would need to fix this issue. Could you give me a hint? I couldn't find an example that is both soft-body and has a force applied. Thanks!

    Sincerely,
    Floris
     
  32. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    Regarding the extents. You should see a red outline of the box collider in your scene. It looks like it is twice as big as it should be. Also make sure you are not using scale other than 1,1,1 in the Unity Transform field. The bullet physics plugin does not support scaling using the Unity Transform. You can attach the MeshRenderer as a child of the BPhysics componet and scale it there, as long as the BPhysics component and BRigidBody component are not scaled.

    Regarding your components. I don't think you need the BRigidBody and BSphereShape. The BSoftBodyWMesh is a "Body" that BulletPhyisics knows what to do with. Also it comes with a built in collision shape that deforms as the shape deforms, so you shouldn't need the BSphereShape. A couple of tips:

    Make sure your softbody is very low poly and has even topology. Avoid quads if you can.

    You might want to consider a two mesh setup, one for softbody sim and a skinned mesh for rendering. There is an example scene that does this. http://digitalopus.ca/site/bullet-physics-tutorial-attaching-softbodies-to-skinned-meshes/
     
    SenaJP likes this.
  33. manpower13

    manpower13

    Joined:
    Dec 22, 2013
    Posts:
    140
    Hey,

    Thanks for the quick response!

    I'm not using any scaling in my objects and the bounds look fine when in scene-mode and not running anything. I think the red outline has something to do with this issue: https://github.com/Phong13/BulletSharpUnity3d/issues/45
    While I've been playing around with settings, I am not able to get the collider to correct sizes (without just putting half the expected size there).

    Considering my components. I am trying to achieve an object that can be controller by the user, with soft-body physics. Like a rubber ball. That's why I was looking at the rigidbody, to add forces to the object.

    When using the two mesh set-up, I am only improving rendering right and allow animations? It would mean the soft-body would be controller by the user and the skinned mesh would be affected by the soft-body object.
    I would still need a way to control the soft-body by adding forces to it.

    Would you mind giving me a hint on how to tackle this? Or where to find documentation considering soft-bodies and forces?

    Thanks a lot!

    Sincerely,
    Floris
     
  34. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    You can Add Force to the softbody. Look at the Bullet Physics API for documentation and the demos. Regarding skinned mesh. You can have a skinned mesh without Animator. Whatever moves the bones (transforms), drives the skinned mesh. In this case, the bones are driven by soft body sim.
     
  35. ThisIsAUser

    ThisIsAUser

    Joined:
    Oct 12, 2018
    Posts:
    16
    Hey Phong, i hope youre still active in this thread. I have a issue regarding the Compound Shape. I have a complex mesh which has a collider object made out of multiple convex meshes. I tried to apply the Convex Hull on every collision mesh and added them inside the parents Compound Shape. But when i am running the game, the rigidbody does strange things (like rotating etc instead of falling to the ground). How can i have multiple convex meshes as a single rigidbody? Thanks.
     
  36. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    Your approach sounds like it should work. are you able to enable the debug draw on the PhysicsWorld component and see where the shapes think they are?
     
  37. ThisIsAUser

    ThisIsAUser

    Joined:
    Oct 12, 2018
    Posts:
    16
    Yes, but the collider doesnt match up with the collision mesh. Its hovering like 10 cm over other collision objects. The strange part is that i tried the same with cubes and it worked. But when i have a empty parent object with rigidbody, compound shape and children with Convex Triangle Mesh the collision becomes incorrect. Thanks for your help!
     

    Attached Files:

  38. ThisIsAUser

    ThisIsAUser

    Joined:
    Oct 12, 2018
    Posts:
    16
    UPDATE: I found the option to draw the collision mesh after i debugged the code ;D
    The reason is an obsolete method error which causes the flags of an enum to have an offset of 1.
    The fix of this behaviour is to change EnumMaskField to EnumFlagsField because the new methods checks if there is a "None" and "Everything" option and doesnt offset all other values if they exist.

    Now you can actually see how my object is "flying" over the ground. So it looks like a strange behaviour to me (bug?)
     

    Attached Files:

  39. manpower13

    manpower13

    Joined:
    Dec 22, 2013
    Posts:
    140
    Hey @ThisIsAUser ,
    The obsoIete code: I had already fixed this bug locally and I will push this to the repo coming days. I've rewritten parts of the editor code to support EnumFlagsField and it uses way less files than before. I first wanted the repo to be reorganized (which just happened! :D).
    For the floating bug: I don't know the exact fix yet, but I think changing the
    Code (CSharp):
    1. CollisionShape.Margin
    to a lower value might fix it. You can check the existing demos and see that it doesn't happen there.
     
    Phong likes this.
  40. ThisIsAUser

    ThisIsAUser

    Joined:
    Oct 12, 2018
    Posts:
    16
    Thank you! I will try it out in the next days.
     
  41. ThisIsAUser

    ThisIsAUser

    Joined:
    Oct 12, 2018
    Posts:
    16
    Unfortunately CollisionShape.Margin (0.5 and 0.1) has no effect. I still have the same problem. I scaled up the collision mesh by 2 to see if it was only a visualization issue but you can see that the distance between the ground and the collision mesh remains the same.
     

    Attached Files:

  42. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    Can you post a UnityProject with a scene that exhibits the problem?
     
  43. manpower13

    manpower13

    Joined:
    Dec 22, 2013
    Posts:
    140
    You can recreate this effect, by colliding a SoftBody with a RigidBody, or a SoftBody with a SoftBody.

    Without changing
    Code (CSharp):
    1. CollisionShape.Margin
    :

    upload_2019-3-22_16-23-26.png

    When setting:
    Code (CSharp):
    1. m_BSoftBody.CollisionShape.Margin = 0.12f;
    :
    upload_2019-3-22_16-22-41.png

    While you can see that it helps, there is still some distance between the objects while colliding. Lowering the CollisionShape.Margin too much is adding collision bugs. Objects will slowly collide through each other.

    I am not sure what the best way would be to solve this issue.
     
    SenaJP likes this.
  44. khos

    khos

    Joined:
    May 10, 2016
    Posts:
    1,463
    Hi all, please excuse my stupidity, how can I create a simple softbody? I have a Unity sphere primitive (rigidbody component added) and would like to turn that into a bullet physics softbody (to make it nice and bouncy)? I can't seem to find a simple get started tutorial or instruction, perhaps I just missed it. Do I simply need to add the bullet softbody script? Thanks, for any help in advance.
     
  45. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    I think that Bullet is designed this way because frequently cloth is used to wrap other objects (cloaks, dresses, hoods, tables). In those cases it is important that object being wrapped does not clip through the cloth. Unfortunately it has this side effect. Blender also uses Bullet Physics for its cloth simulation.There are many posts complaining of this issue. The recommended solution seems to be reducing the collision margin as you suggest.

    There is also the "generate clusters" option. For softbodies. As I understand this is slight more expensive than the default soft body collision system but is supposed to be better. That might help.
     
    manpower13 likes this.
  46. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    Sorry for the late reply. I was on vacation last week.

    The easiest thing to do is to:

    1) Choose BulletForUnity -> BSoftBody -> BSoftBodyWMesh. This will add a game object to your scene with all the required components.
    2) On the BSoftBodyWMesh inspector
    Choose Mesh Type -> User Defined Mesh
    Assign your mesh
    Try applying different presets.
    To get good results you want to use a mesh that has no hard edges (duplicated vertices or cracks will open). It is possible to use one mesh for the physics sim and a separate skinned mesh for rendering but it is a chore to set up.
     
    SenaJP and Willbkool_FPCS like this.
  47. khos

    khos

    Joined:
    May 10, 2016
    Posts:
    1,463
    Cool thanks! I tried that but the object does not move, then I added a rigidbody, my object just falls through the floor (other object), I tried adding box collider but I suspect that is far from correct? Am I juts being really daft, is there no simple tutorial to follow ? :)
     
  48. zhuchun

    zhuchun

    Joined:
    Aug 11, 2012
    Posts:
    427
    Maybe you didn't set the mask value or the object is using an incorrect flag? Unity crafted PhysX a lot so it can make use of the layer system, while Bullet doesn't know it at all, Bullet uses its own mask/flag instead. You can find a manual on Github, the code example is written in C++, however, it should be a good start
     
  49. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,064
    Unfortunately no tutorial. I would suggest duplicating the RatherGoodPlayground scene. Then delete most of the shapes out until there are only a few softbody shapes and look at the setup.

    Have you checked the various flags? There are some for static/kinematic objects. Those will freeze a shape in place.
     
  50. Nosnew

    Nosnew

    Joined:
    Apr 18, 2014
    Posts:
    20
    Hi, Phong. Do you know how to set SpinningFriction? I fount it in C++ source code. How about C#?