Search Unity

Unity Physics Discussion

Discussion in 'Data Oriented Technology Stack' started by smcclelland, Mar 18, 2019.

  1. lijianfeng

    lijianfeng

    Joined:
    Sep 8, 2015
    Posts:
    22
    How do I do Raycast In a Job?Do I need to clone the PhysicsWorld and pass it to job?
     
  2. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    1,565
    Just pass the CollisionWorld to the job.
     
    steveeHavok likes this.
  3. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    2,316
    BuildPhysicsWorld has a public PhysicsWorld for that. And a FinalJobHandle as a shared dependency.

    The problem is FinalJobHandle is not enough. You can use that to combine but setting it back will have no effect, and you need both directions to setup a proper dependency. That said it might work, it really depends on your specific flow and when/how you are adding/removing colliders and if you are looking up bodies via the index the raycast hit gives you.

    I can't remember the exact paths that threw safety exceptions. Initially I patched up BuildPhysicsWorld but now we are using custom worlds, but only because our case actually needs multiple worlds.
     
    steveeHavok likes this.
  4. lijianfeng

    lijianfeng

    Joined:
    Sep 8, 2015
    Posts:
    22
    It looks like only the BuildPhysicsWorld.PhysicsWorld has the API (public bool CastRay(RaycastInput input, ref NativeList<RaycastHit> allHits)),not the CollisionWolrd,so pass the PhysicsWorld?
     
  5. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    2,316
    PhysicsWorld.CollisionWorld
     
  6. lijianfeng

    lijianfeng

    Joined:
    Sep 8, 2015
    Posts:
    22
    When I Call PhysicsWorld.CastCollider,win10 and osx platform is OK,on the IOS platform,generate following error,:

    ExecutionEngineException: Attempting to call method 'Unity.Physics.Broadphase+BvhLeafProcessor::ColliderCastLeaf<Unity.Physics.AllHitsCollector`1[[Unity.Physics.ColliderCastHit, Unity.Physics, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]>' for which no ahead of time (AOT) code was generated.
    at Unity.Entities.TypeManager.Equals[T] (T& left, T& right) [0x00000] in <00000000000000000000000000000000>:0
    at Unity.Entities.TypeManager.Equals[T] (T& left, T& right) [0x00000] in <00000000000000000000000000000000>:0
    at Unity.Physics.ColliderCastQueries.ConvexMesh[T] (Unity.Physics.ColliderCastInput input, Unity.Physics.MeshCollider* meshCollider, T& collector) [0x00000] in <00000000000000000000000000000000>:0
    at Unity.Physics.QueryWrappers.ColliderCast[T] (T& target, Unity.Physics.ColliderCastInput input, Unity.Collections.NativeList`1[Unity.Physics.ColliderCastHit]& allHits) [0x00000] in <00000000000000000000000000000000>:0
    at Unity.Physics.PhysicsStep..cctor () [0x00000] in <00000000000000000000000000000000>:0
     
  7. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    107
    This is a known bug that has come up recently where the function is stripped out. We are looking for a general fix in future releases.
    In the meantime, a local fix which worked for others is in Broadphase.cs in the Unity.Physics package code; Add a line like p.ColliderCastLeaf to the AOTHint() function.
     
  8. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    107
  9. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    107
    Thanks, I'll take a look at the CC demo, though that looks like it could be an interpenetration problem. Could you also try adding the Physics Debug Display component and enable Draw Collider Edges and Draw Contacts and double check you are getting no contacts between the terrain and character representations.
    upload_2019-7-11_16-40-55.png
    The Draw Colliders might option might highlight other issues if scaling has messed with the collider
     
  10. Knightmore

    Knightmore

    Joined:
    May 11, 2012
    Posts:
    226
    Can someone give me a bit of insight as I am not that into the whole physics stuff.
    I am messing around with the physics examples - especially CharacterControllerSimpleDemo.
    Am I wrong, that Unity Physics should be already deterministic on the same machine with the same input?

    As I am copying CharacterBody (Kinematic in this scene) 30 times to the exact same position and move them with the same input all together. This is all working without problems, but if I add some more it begins to crumble and those copies begin to jitter, some move a bit faster or slower and even jitter as their supported status begins to switch between supported and sliding on a flat surface.

    Shouldn't it work the same with all CharacterBodies - even high in numbers - as long as they start at the same position and get the exact same input?
     
    Last edited: Jul 12, 2019
  11. shaunnortonAU

    shaunnortonAU

    Joined:
    Jan 19, 2018
    Posts:
    5
  12. Knightmore

    Knightmore

    Joined:
    May 11, 2012
    Posts:
    226
    Thank you @shaunnortonAU but that hasn't fixed anything, unfortunately.

    Here are some screenshots.

    40 CCs are sitting on the same place and move the same.

    upload_2019-7-12_17-39-6.png

    With 50 CCs they are already messed up when spawning them and they are moving to different directions with different speeds.

    upload_2019-7-12_17-42-2.png
    upload_2019-7-12_17-45-41.png
     
  13. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    2,316
    Thought I'd post this here in case it's useful to others or if someone can spot some flaws in the approach.

    https://gist.github.com/gamemachine/6eafec133e837249159743b61840b9c6

    This serializes the collider pointer you get from PhysicsCollider.ColliderPtr.

    Deserialization returns a BlobAssetReference<Collider> you can assign to PhysicsCollider.Value.

    Serialize returns the size you need to pass back to Deserialize. So you can Serialize at design time and store that for instance on a Monobehavior/ScriptableObject for use at runtime. Just a note the size just needs to be at least large enough, you can hand it something larger although it is allocating a byte array so best to be exact.

    Right now our terrain mesh sits at 191k vertices and takes 34 seconds to create the collider. Deserializing it into a blob takes 5ms.

    Once collider creation is bursted that will be great, but it doesn't solve all problems. Creating at runtime from the mesh still means reading the mesh data and that flow also doesn't play nice with static meshes.
     
    steveeHavok likes this.
  14. zhuchun

    zhuchun

    Joined:
    Aug 11, 2012
    Posts:
    379
    Hm, I have a question here. Did Havok release their plugin? Havok said they would release it in June, which is last month, but how is that going to be possible if UnityPhysics is still in preview stage and its data struct may change with time?
     
  15. Shinyclef

    Shinyclef

    Joined:
    Nov 20, 2013
    Posts:
    364
    No it's not released. Timelines changed, but no new announcements, so we're just playing wait and see now.
     
  16. Spy-Shifty

    Spy-Shifty

    Joined:
    May 5, 2011
    Posts:
    521
    Hi,

    is it possible to use the new Physics without to force the a job to be completed at the end?

    Like in the EntityCommandBufferSystem.AddJobHandleForProducer(JobHandle producerJob);

    Here is my code
    Code (CSharp):
    1. public class SelectionSystem : JobComponentSystem {
    2.  
    3.     [BurstCompile]
    4.     struct SelectionJob : IJobForEachWithEntity<RectengularSelection, PlayerInput, MousePosition> {
    5.         [ReadOnly] public CollisionWorld World;
    6.         [NativeDisableParallelForRestriction] public BufferFromEntity<SelectionSet> SelectionSetFromEntity;
    7.         [NativeDisableParallelForRestriction] public ComponentDataFromEntity<Selectable> SelectableFromEntity;
    8.         public void Execute(Entity entity, int index, ref RectengularSelection selectionState, [ReadOnly] ref PlayerInput playerInput, [ReadOnly] ref MousePosition mousePosition) {
    9.             if (playerInput.LeftMouseUp) {
    10.                 var raycastInput = new RaycastInput {
    11.                     Start = mousePosition.ScreenPointRay.origin,
    12.                     End = mousePosition.ScreenPointRay.origin + mousePosition.ScreenPointRay.direction * 1000,
    13.                     Filter = new CollisionFilter {
    14.                         BelongsTo = ~0u,
    15.                         CollidesWith = ~0u,
    16.                         GroupIndex = 0
    17.                     }
    18.                 };
    19.                 var selectionSet = SelectionSetFromEntity[entity].Reinterpret<Entity>();
    20.                 if (!playerInput.Ctrl) {
    21.                     for (int i = 0; i < selectionSet.Length; i++) {
    22.                         Entity selectedEntity = selectionSet[i];
    23.                         if (SelectableFromEntity.Exists(selectedEntity)) {
    24.                             SelectableFromEntity[selectedEntity] = new Selectable { Selected = false };
    25.                         }
    26.                     }
    27.                     selectionSet.Clear();
    28.                 }
    29.  
    30.                 if (World.CastRay(raycastInput, out RaycastHit hit)) {
    31.                     Entity selectableEntity = World.Bodies[hit.RigidBodyIndex].Entity;
    32.                     if (SelectableFromEntity.Exists(selectableEntity)) {
    33.                         selectionSet.Add(selectableEntity);
    34.                         SelectableFromEntity[selectableEntity] = new Selectable { Selected = true };
    35.                     }
    36.                 }
    37.             }
    38.         }
    39.     }
    40.  
    41.     private BuildPhysicsWorld _BuildPhysicsWorld;
    42.  
    43.     protected override void OnCreate() {
    44.         _BuildPhysicsWorld = World.GetOrCreateSystem<BuildPhysicsWorld>();
    45.     }
    46.  
    47.     protected override JobHandle OnUpdate(JobHandle inputDep) {
    48.         inputDep = JobHandle.CombineDependencies(inputDep, _BuildPhysicsWorld.FinalJobHandle);
    49.         var physicsWorld = _BuildPhysicsWorld.PhysicsWorld;
    50.  
    51.         inputDep = new SelectionJob {
    52.             World = physicsWorld.CollisionWorld,
    53.             SelectionSetFromEntity = GetBufferFromEntity<SelectionSet>(),
    54.             SelectableFromEntity = GetComponentDataFromEntity<Selectable>(),
    55.         }.Schedule(this, inputDep);
    56.  
    57.  
    58.         inputDep.Complete(); //I want to remove this line...
    59.         return inputDep;
    60.     }
    61. }
     
  17. Shinyclef

    Shinyclef

    Joined:
    Nov 20, 2013
    Posts:
    364
    As you are already depending on the FinalJobHandle in your job, I'm pretty sure you can just remove the line you want to remove. Does it not work?
     
  18. Spy-Shifty

    Spy-Shifty

    Joined:
    May 5, 2011
    Posts:
    521
    No it won't work.
    Because the BuildPhysicsWorld don't know anything about the dependency. And I get the following error:
     
    Last edited: Jul 13, 2019
  19. Shinyclef

    Shinyclef

    Joined:
    Nov 20, 2013
    Posts:
    364
    I just took a look at my code to see the difference.
    I'm depending on StepPhysicsWorld.FinalJobHandle, not BuildPhysicsWorld.FinalJobHandle. See if that works.
     
  20. Spy-Shifty

    Spy-Shifty

    Joined:
    May 5, 2011
    Posts:
    521
    No, that doesn't work either.

    Code (CSharp):
    1. private BuildPhysicsWorld _BuildPhysicsWorld;
    2.     private StepPhysicsWorld _StepPhysicsWorld;
    3.     protected override void OnCreate() {
    4.         _BuildPhysicsWorld = World.GetOrCreateSystem<BuildPhysicsWorld>();
    5.         _StepPhysicsWorld = World.GetOrCreateSystem<StepPhysicsWorld>();
    6.     }
    7.  
    8.     protected override JobHandle OnUpdate(JobHandle inputDep) {
    9.         //_BuildPhysicsWorld.FinalJobHandle.Complete();
    10.         inputDep = JobHandle.CombineDependencies(inputDep, _BuildPhysicsWorld.FinalJobHandle);
    11.         inputDep = JobHandle.CombineDependencies(inputDep, _StepPhysicsWorld.FinalJobHandle);
    12.         var physicsWorld = _BuildPhysicsWorld.PhysicsWorld;
    13.  
    14.         inputDep = new SelectionJob {
    15.             World = physicsWorld.CollisionWorld,
    16.             SelectionSetFromEntity = GetBufferFromEntity<SelectionSet>(),
    17.             SelectableFromEntity = GetComponentDataFromEntity<Selectable>(),
    18.         }.Schedule(this, inputDep);
    19.  
    20.         return inputDep;
    21.     }
     
  21. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    2,316
    For a dependency to be complete you need to also take your jobhandle and assign it back to the one you combined with. But in the case of BuildPhysicsWorld that won't work. FinalJobHandle is not actually the jobhandle returned by BuildPhysicsWorld.OnUpdate so setting back to it does nothing. The only way to fix this is to modify the source.

    Calling complete at a strategic point where it causes only the most minimal main thread stall is probably the simplest solution for now. With the transform system involved that might take some experimentation, but the broadphase building itself is so fast that unless you have a ridiculous number of bodies those jobs are going to be done way before it gets around to the next simulation group tick.
     
  22. Spy-Shifty

    Spy-Shifty

    Joined:
    May 5, 2011
    Posts:
    521
    Yep I agree with that.

    Well they should add a method like:
    in the EntityCommandBufferSystem.AddJobHandleForProducer(JobHandle producerJob);
     
  23. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    107
    The determinism means that with the same simulation starting position you will get the same results. However, if you are adding in more CC's youare changing the simulation. I'm not sure why they are moving differently though as the CC's should probably be getting the same input and results from the simulation. You could try drawing some of the information used by the CC code such as the contact points. Also make sure the CC's are not colliding with each other.
     
  24. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    107
    This is on the list to be improved. I'm not particularly familiar with them but other folk have also had benefits from putting the larger physics meshes into subscenes for performance on load as the physics colliders are already processed.
     
  25. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    107
    Can you try add your job to
    EndFramePhysicsSystem.HandlesToWaitFor

    Though that's only at the end of the whole simulation step.
    Does yours own system need
    [UpdateAfter(typeof(BuildPhysicsWorld)), UpdateBefore(typeof(StepPhysicsWorld))] 
    assigned?
     
  26. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    107
    Yup, sorry about the delay there. It's really close to initial release. Expect the offical announcement soon.
     
    Brian-FJ, Kender and zhuchun like this.
  27. Knightmore

    Knightmore

    Joined:
    May 11, 2012
    Posts:
    226
    All CCs are kinematic without colliding with anything.

    Seems like CharacterControllerUtilities.CheckSupport doesn't work when there are more than 47 chunks to iterate over. Each collider begins to have problems keeping the supported state even when there are no inputs. They change massively between all three states and some even slip through the static plane collider under them.
     
    leo150 and steveeHavok like this.
  28. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    107
    Thanks for the details. I'll log and issue and see about setting up a repro.
     
  29. SamOld

    SamOld

    Joined:
    Aug 17, 2018
    Posts:
    97
    What exactly is
    FinalJobHandle
    meant to wait for that
    [UpdateAfter]
    doesn't? Why is it separate?
     
  30. shaunnortonAU

    shaunnortonAU

    Joined:
    Jan 19, 2018
    Posts:
    5
    I was using the PhysicsRunner a ssuggested by PhilSA on page 1 - updated the deprecated GetOrCreateManager to GetOrCreateSystem:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using Unity.Entities;
    4. using Unity.Physics.Systems;
    5. using UnityEngine;
    6.  
    7. public class PhysicsRunner : MonoBehaviour
    8. {
    9.     private IEnumerable<ComponentSystemBase> simSystems;
    10.  
    11.     void Start()
    12.     {
    13.         World.Active.GetOrCreateSystem<SimulationSystemGroup>().Enabled = false;
    14.         simSystems = World.Active.GetOrCreateSystem<SimulationSystemGroup>().Systems;
    15.     }
    16.  
    17.     void FixedUpdate()
    18.     {
    19.         foreach (var sys in simSystems)
    20.         {
    21.             sys.Update();
    22.         }
    23.     }
    24. }

    I have been using it for a week, no problem, including collision/trigger entities and systems.
    Then, I started getting errors like this whenever there was a physics body on an entity.

    Unity.Collections.LowLevel.Unsafe.DisposeSentinel.Dispose (Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle& safety, Unity.Collections.LowLevel.Unsafe.DisposeSentinel& sentinel) (at C:/buildslave/unity/build/Runtime/Export/NativeArray/DisposeSentinel.cs:69)
    Unity.Collections.BlockStream.Dispose () (at Library/PackageCache/com.unity.physics@0.1.0-preview/Unity.Physics/Base/Containers/BlockStream.cs:186)
    Unity.Physics.Simulation.DisposeEventStreams () (at Library/PackageCache/com.unity.physics@0.1.0-preview/Unity.Physics/Dynamics/Simulation/Simulation.cs:153)
    Unity.Physics.Simulation.ScheduleStepJobs (Unity.Physics.SimulationStepInput input, Unity.Jobs.JobHandle inputDeps, Unity.Jobs.JobHandle& finalSimulationJobHandle, Unity.Jobs.JobHandle& finalJobHandle) (at Library/PackageCache/com.unity.physics@0.1.0-preview/Unity.Physics/Dynamics/Simulation/Simulation.cs:79)
    Unity.Physics.Systems.StepPhysicsWorld.OnUpdate (Unity.Jobs.JobHandle inputDeps) (at Library/PackageCache/com.unity.physics@0.1.0-preview/Unity.Physics/ECS/Systems/StepPhysicsWorld.cs:107)
    Unity.Entities.JobComponentSystem.InternalUpdate () (at Library/PackageCache/com.unity.entities@0.0.12-preview.33/Unity.Entities/ComponentSystem.cs:951)
    Unity.Entities.ComponentSystemBase.Update () (at Library/PackageCache/com.unity.entities@0.0.12-preview.33/Unity.Entities/ComponentSystem.cs:287)
    PhysicsRunner.FixedUpdate () (at Assets/PhysicsRunner.cs:21)

    I couldn't see any reason for the sudden change - though I did reorganise some scripts. So after a process of elimination I decided to start a new project with Entities, Burst, Jobs, Mathematics, Hybrid Renderer and Unity Physics.

    I added a Physics Shape/Body/Convert and run - no problem.
    I added a Game Object with the Physics Runner monobehaviour and run - error.

    I don't understand what's caused the change?
    Any idea?

    EDIT1: Adding a Physics Debug Display + Convert to the scene causes a Unity crash.
     
  31. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    107
    You get that BlockStream.Dispose error on a new project if the 'Hybrid Renderer' package is not included along with the Unity.Physics package. We are looking into making this error go away or at least more obvious about what to do to fix it.

    EDIT1: Actually you still get a ConstructJob.BlockStream error when you add the PhysicsRunner script. Looking for options now.

    EDIT2: These errors have already been fixed in the codebase. FYI Expect another release in the next few weeks.
     
    Last edited: Jul 16, 2019
  32. nttLIVE

    nttLIVE

    Joined:
    Sep 13, 2018
    Posts:
    77
    I've updated my Unity to 2019.1.10f1 and my Physics Package to 0.1.0. Now every time I focus on a GameObject in the editor that has a "Physics Shape" component my editor just freezes. Anyone knows what gives?

    EDIT: It only freezes in Package 0.1.0. If I revert back to package 0.0.2 it's fine.

    Also, sorry about being picky about this, but why doesn't 0.1.0 have any change log info?
    https://docs.unity3d.com/Packages/com.unity.physics@0.0/changelog/CHANGELOG.html

    I found about the new Collision and Trigger jobs in a random forum post. Would be nice if the change log was updated.

    EDIT2: Found the change log. The package manager links me the old one.
    https://docs.unity3d.com/Packages/com.unity.physics@0.1/changelog/CHANGELOG.html

    EDIT3: After more troubleshooting, I can kind of replicated the problem by creating a new GO, adding a Physics Shape, Physics Body and Entity Converter, let's call it "PHYSIC_BODY". That will work fine. As soon as I copy paste some other GameObject inside of "PHYSIC_BODY" as children, sometimes it will cause the freeze, sometimes it won't. Without the Physics Shape component there is no freeze. Weird thing is if I manually recreate all the new GameObjects instead of copy pasting, it doesn't freeze.

    EDIT4: If you have a GameObject that's inactive (turned off) as a children of a "PHYSIC_BODY", it will cause the freeze.

    FINAL EDIT: Version 0.2.0 fixes the problem.
     
    Last edited: Jul 19, 2019
    SamOld likes this.
  33. Adam-Mechtley

    Adam-Mechtley

    Unity Technologies

    Joined:
    Feb 5, 2007
    Posts:
    190
    The next preview release of Unity Physics, 0.2.0, is available today! This version should serve as the basis for the upcoming release of the Havok Physics package. There are a number of things noted in the change log, but we wanted to cover a few highlights here:
    • The minimum required version of Unity is now 2019.1.10f
    • We have a first draft of the run-time implementation for a TerrainCollider. A terrain is defined by a height field, and offers a more efficient alternative to a comparable mesh collider. There are no authoring components associated with it in the package, but we are collaborating with our terrain team to ensure it will be ready for them to support with high quality workflows as they work toward DOTS readiness.
    • We have moved a number of low-level APIs from public to internal only. This allows us to more freely make changes in performance critical code before too many users have started designing around it. Our focus for this quarter is going to center around quality (both in workflows and the game code layer), so we wanted to make sure we can give proper design time and attention to everything that will ultimately allow advanced users to take full control over their game’s physics.
    • We invested a lot of time this release expanding our platform coverage in our testing infrastructure. We now officially support IL2CPP platforms, including desktops, consoles, and mobile devices. As always, please share your experiences with us.
     
    Last edited: Jul 19, 2019
  34. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    2,316
    New version isn't in my package manager yet, but reading the release notes this looks to break how custom worlds are currently built via access to PhysicsWorld.CollisionWorld.Broadphase.ScheduleBuildJobs. Is there a new flow to support multiple custom worlds?
     
  35. Adam-Mechtley

    Adam-Mechtley

    Unity Technologies

    Joined:
    Feb 5, 2007
    Posts:
    190
    1. Make sure you're on 2019.1.10f1 or newer
    2. We'll be actively doing some work on this specific problem this quarter, as (I imagine you will agree) the existing flow was pretty clunky. That said, the person best positioned to provide details just left on holiday. If you can provide me some details of how your usage looks, I'd like us to see if we can sort out something that could unblock you in a patch release, without opening the whole thing back up quite yet.
     
  36. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    2,316

    FYI our use case is queries only, where we use worlds with static bodies only. We have one world with just a few hundred that move every frame, another world for vegetation and terrain which can have up to 100k bodies but is never rebuilt. Another for dynamic structures that can come and go but generally cap at around 2000 per map.

    So we have a fairly simple abstraction around a world that is just a regular class. It's designed to be used within a system. We maintain a NativeArray of a custom struct that among other things has a PhysicsCollider and RigidTransform.

    The relevant parts are the following, this is the last part of the update method. Bodies is the above mentioned native array. the updateBodiesJob synchronizes the physics world bodies with that.

    Not sure why I have a copy of PhysicsWorld.StaticBodies there, think it was just what was there after working through how to get this to work.

    Code (csharp):
    1.  
    2. NativeSlice<RigidBody> staticBodies = PhysicsWorld.StaticBodies;
    3.  
    4. int numBodies = Bodies.Length;
    5.  
    6. PhysicsWorld.Reset(numBodies, 0, 0);
    7.  
    8. staticBodies = PhysicsWorld.StaticBodies;
    9.  
    10. Debug.Assert(staticBodies.Length == numBodies);
    11.  
    12.  UpdateBodiesJob updateBodiesJob = new UpdateBodiesJob
    13.             {
    14.                 WorldBodies = staticBodies,
    15.                 Bodies = Bodies
    16.             };
    17. JobHandle = updateBodiesJob.Schedule(staticBodies.Length, 64, JobHandle);
    18.  
    19.  
    20. staticLayerChangeInfo.NumStaticBodies = staticBodies.Length;
    21. staticLayerChangeInfo.HaveStaticBodiesChanged = 1;
    22. JobHandle = PhysicsWorld.CollisionWorld.Broadphase.ScheduleBuildJobs(ref PhysicsWorld, 1 / 60, 1, ref staticLayerChangeInfo, JobHandle);
    23.  
     
  37. SamOld

    SamOld

    Joined:
    Aug 17, 2018
    Posts:
    97
    That's really interesting. Do you think that it makes sense for you to have those in separate worlds, or would it be better to have them in one world but to have finer control over partial rebuilding?
     
  38. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    2,316
    How they handle that I don't really care as long as it remains flexible. Although I would think partitioning at the world level would seem to be the obvious and simplest approach given how things work now.

    I don't think they will have a generic solution anytime soon that is better then a custom world for some use cases. Static only worlds being a good example. We have no use for the transform system being involved for example. And our specific needs let me design a sync point free implementation for add/remove of bodies. Not to mention our abstraction over static worlds is dead simple as far as the public api precisely because it's very purpose specific.
     
    Last edited: Jul 19, 2019
  39. SamOld

    SamOld

    Joined:
    Aug 17, 2018
    Posts:
    97
    I've not worked with multiple worlds, but I assume that you have to query them each individually. If you wanted to run one query against both worlds, you would expect your performance to be worse than if all of the colliders had been in a single BVH. The code would also be more complex as you would have to dispatch both queries then combine the results. If each world has N bodies, it's roughly
    2 log(n)
    vs
    log(2n)
    .

    I wonder how many multi world queries you would need to do before it becomes faster to have a single world.

    I'm wondering if there should be an API that optimises the rebuilding of static geometry like you have, whilst packing it into a single world. I'm not sure what that would look like or how feasible it is. Another useful feature might be an query API that is able to act on multiple worlds at once.
     
  40. Knightmore

    Knightmore

    Joined:
    May 11, 2012
    Posts:
    226
    I tried it out with 0.2.0 and the new examples. It really improved by a lot.


    This is now with 100 CCs. They still have problems to keep the supported state even on a flat surface. On slopes they don't stay in sliding state but switch between all three states. At least they aren't that much off like before where they had differed by at least 2. It's more like around 0.02 difference now, but accumulates the longer you leave them untouched.


    This one was even with 600 CCs. Needs some loading time for sure but when it is running, it is not that bad as before. Positions are differing much more now and you can see, that some have even greater problems to keep their supported state as they appear to stuck and wobble inside the plane collider. Btw. they even move a bit on their own without inputs because of the problems with "Supported".

    Not 100% where it should be in the end, but it is a huge step.
     
  41. dadude123

    dadude123

    Joined:
    Feb 26, 2014
    Posts:
    787
    Just stopping by to let you guys know that the problems I've had seem to be solved with the 0.2.0 version.
     
    steveeHavok, Adam-Mechtley and Abbrew like this.
  42. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    381
    Well, I had a chance to play with the changes of 0.2.0 and this release is a very mixed bag for me.

    First, what hasn't changed which still needs improvement at some point:
    • Stacking is not a thing yet.
    • Working directly with colliders still requires unsafe API in many cases.
    • The issue of static colliders waking activating the transform system every frame is still present.
    And now for the new stuff and updates:
    Performance:

    The Bad:
    I noticed quite a few regressions. The pool demo takes even longer than the 0.1.0 version, reaching greater than 1.0 spf (seconds per frame). Pushing the asteroid demo an order of magnitude higher resulted in a slideshow (400 ms vs 120 ms before). The broadphase seems to be 2-3 milliseconds slower in that test too. I did not notice a regression in the original 10000 units.

    Features:

    The Bad:
    The constraints demos were removed. Hopefully they will return later because they really showcased the power of the physics engine.

    The Good:
    Terrain colliders are new and work as expected, especially with sphere colliders.

    Events for kinematic vs kinematic and kinematic vs static were definitely needed. They are now here.

    There's something going on with continuous collision detection for fast rotations in one of the test scenes. What is going on with that? Do all simulated objects support continuous collision detection now?

    API:

    The Bad:
    Colliders are still blobs, but now their headers contain a version number for when their properties get modified and there's an example of directly modifying the radius of sphere colliders. Don't get me wrong, mutable colliders are awesome. But mutable shared colliders without any sort of safety mechanism in place is not so awesome. My understanding has been that blobs are supposed to be immutable. It's going to be an ugly surprise for someone when they instantiate a bunch of spheres from a prefab and modify one sphere's radius and all the spheres end up with the same physics radius but different visual radii.

    The Good:
    Tags instead of flags is a good improvement. Properties are being better utilized across the board.

    Much of the API was made internal to improve iteration and optimization without risking breaking user projects. I'm all for this as the existing API was a bit confusing to use without reading through the source code. However, this release did not take advantage of the APIs being internal much. Hopefully that will change in 0.3.0.

    Overall:
    It is a mixed bag for me. It certainly wasn't as awesome of a jump as 0.0.2 -> 0.1.0 was. But it seems like this release was designed to set the groundwork for something bigger. Hopefully it is worth it!
     
  43. daschatten

    daschatten

    Joined:
    Jul 16, 2015
    Posts:
    145
    I can't find a way to use the new terrain colliders. Can you explain your steps, please?
     
  44. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    381
    I just copied the test terrain scene and played around with it. I don't actually use Unity.Physics. Instead I am building my own Physics solution which borrows from Unity.Physics when convenient but makes different fundamental design trade-offs. One day I hope Unity.Physics will reach a point where my additional tech can be a layer on top but it is way too early for that yet.
     
  45. daschatten

    daschatten

    Joined:
    Jul 16, 2015
    Posts:
    145
    Ok, thanks. So there is no hidden terrain conversion script somewhere :-(
     
  46. SamOld

    SamOld

    Joined:
    Aug 17, 2018
    Posts:
    97
    Out of curiosity, what are these different fundamental design trade-offs? What are your needs that can't be met by Unity's implementation?
     
  47. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    2,316
    We aren't doing multiple queries against the same world. And it would take a hell of a lot of queries. We are saving rebuilding something like 80k colliders per frame, which pretty much makes a single world a non starter.
     
    SamOld likes this.
  48. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    381
    Most of the games I build don't need a physics simulation. Instead I really just want a strong query engine that I can do lots of hit detection between very specific combinations of objects. A strong and flexible bump-and-slide algorithm to prevent overlaps is nice, but most physics engines have been lackluster in this regard.

    Unity.Physics uses blobs for all colliders. Blobs are immutable and shared data. That makes sense for a rigidbody simulation when colliders wouldn't normally change shape. However, many times I want morphing trigger volumes to drive other game logic.

    I also need continuous collision detection for non-linear motions for some games, especially ones I plan to open up to ridiculous level design or modding.

    In order to do what I wanted to do and not waste a bunch of additional processing power on simulations I don't need, I would have to rewire the Physics Engine loop. It's probably doable, but an absolute pain, especially since much of the code runs in an unsafe context to access collider pointers. My day job is C++ dev, and I have quickly learned that pointers are super difficult to use correctly in performance computing. Also having the unsafe context persist across the rest of my game logic which heavily relies on the query APIs is kinda disgusting.

    So my solution was to write my own collision and physics solution with a different collider representation. Instead of making colliders blobs, I store an unsafe blittable buffer in my base collider type which I can use to cast to and from any of my specialized collider shapes. Primitive colliders fit right inside the buffer. Complex colliders can be stored as Blobs and modifyable parameters or in some unique_ptr type of data (still trying to figure that one out). Only the internals of the colliders require unsafe code.

    I am developing this alternative physics engine alongside weekend game jams to battle-test the API and experiment with different optimizations. I've discovered a bunch of nice benefits such as being able to add new collider types and query algorithms that aren't in Unity.Physics.

    Ultimately, my solution sacrifices memory and some of the optimizations Unity.Physics made for significantly increased flexibility, safe context for all my C# code, and better control over which objects check for collisions against which other objects which can lead to performance gains.

    Wow, this is just one design trade-off and I feel like I wrote a book, so I will leave it at that for this post.
     
    GliderGuy, steveeHavok and SamOld like this.
  49. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    107
     
  50. daschatten

    daschatten

    Joined:
    Jul 16, 2015
    Posts:
    145
    You never know what's hidden in the unity repos :)

    Had some difficulties but finally i have my own authoring component for terrains.