Search Unity

Unity Physics Discussion

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

  1. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    4,670
    Our plan is to not only analyze but also change code (Eg. Entities.ForEach generating jobified code...), so we are going to add support for il postprocessing processing plugins which can emit compiler errors etc The aim is to make them incremental and rebuild on a per assembly basis, we want all the analysis steps to be fast so we can have them always on. Roslyn analyzer seems problematic with those goals stated. ([Readonly], [JobPure] static variable analysis, [BurstCompatible], codegen for Entities.ForEach etc...)
     
    Arkade, optimise and FROS7 like this.
  2. wesley_unity341

    wesley_unity341

    Joined:
    Dec 14, 2018
    Posts:
    9
    OK, I think I understand. So, in short, what's the timeframe for this to be fixed? :)
     
  3. SamOld

    SamOld

    Joined:
    Aug 17, 2018
    Posts:
    97
    Perhaps that's an argument for having both, but Roslyn analyzers provide a far better development experience because they're giving squigglies, suggestions, and refactorings in realtime as you type. I think they're essential to the IDE experience.

    I'm going to think about this a little more and I might make a dedicated thread making this argument in more detail, as I don't want to drag things off topic here in physics.

    EDIT: Actually I misread your post and thought you were saying no analyzers, but you're actually saying not only analyzers. Sorry.

    EDIT 2: I read it again, and no you didn't. I'm not having a good day am I.
     
    Last edited: May 27, 2019
    dadude123 likes this.
  4. PhilSA

    PhilSA

    Joined:
    Jul 11, 2013
    Posts:
    1,063
    What would be the recommended way to freeze a dynamic body's rotation (on certain axis)?
     
    Knightmore likes this.
  5. Knightmore

    Knightmore

    Joined:
    May 11, 2012
    Posts:
    226
    @PhilSA
    I copied this from steveeHavok, maybe it does help you

     
    Last edited: May 27, 2019
    steveeHavok and PhilSA like this.
  6. zephyr831125

    zephyr831125

    Joined:
    Mar 4, 2017
    Posts:
    33
    Thank you!
     
  7. Srokaaa

    Srokaaa

    Joined:
    Sep 18, 2018
    Posts:
    72
    Damn, debugging this is going to be a horrible experience. I like the API in its current shape and I don't see clear advantages of Entities.ForEach over IJobForEach syntax. Once you allow passing some arbitrary data to ForEach so that it doesn't create garbage every frame I think we can get by without resorting to any codegen
     
  8. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    4,670
    We are getting way off topic from physics. Can you post on API feedback thread instead.
     
  9. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    110
    Folks, its relatively late on a Friday here and I should be turning the computer off, but I just wanted to say thanks for all your feedback so far.
    We've just pushed 0.1.0-preview of Unity Physics and this contains many things discussed on this very forum, with more to come
    • The new Joint for 2d use cases is there
    • Sync points have gone - more to do there.
    • Bounding Volume Hierarchy improvements should help performance
    • The RaycastInput struct is tweaked to remove `direction` confusion
    • Runtime CollisionFilter members now match the editor PhysicsShape component
    • Physics Body and Shape ConversionSystem improvements are many
    • Trigger events are now raised between kinematic && (kinematic || static) bodies
    • Dynamic bodies with `PhysicsMass` components only are now integrated
    • Trigger and Collision events demos were added
    I'll try and get online from time to time, though its a long weekend here in Ireland so replies may be slow ;)
    Thanks again everyone.
     
  10. elcionap

    elcionap

    Joined:
    Jan 11, 2016
    Posts:
    87
    A game object with disabled MeshFilter child freezes the editor when adding PhysicsShape.

    Vesion: 0.1.0-preview
    STR:
    1: Create an empty game object.
    2: Create a cube game object inside the empty game object.
    3: Disable the cube game object.
    4: Add PhysicsShape to the empty game object.

    com.unity.physics@0.1.0-preview/Unity.Physics.Hybrid/Components/PhysicsShape.cs:390
    Looks like the continue inside the while was wrongly coded as continue the for in mind.

    []'s
     
    steveeHavok likes this.
  11. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    110
    We need prizes (or at least a badge) for first error found after any release :)
     
    M_R likes this.
  12. Shinyclef

    Shinyclef

    Joined:
    Nov 20, 2013
    Posts:
    364
    @steveeHavok, was very much looking forward to the physics update! Looks like there's a lot of good stuff in the release. I'm particularly excited by improvements to working with collision/trigger events.

    On that note I do have a question. I'm attempting to implement an ITriggerEventsJob currently. In this job, I would like to add tags to entities that received a trigger event, that are handlers for the events, and add the colliding partner to a dynamic buffer.

    Question is, can one entity be processed in calls of 'Execute' on different threads? Bottom line is I want to know if writing to
    [NativeDisableParallelForRestriction] public BufferFromEntity<TriggerInfoBuf> TriggerInfoBufs;
    for each colliding entity is going to be safe... I have a feeling it won't be and I'll need a new strategy (or perhaps the use of 'ScheduleSingle').
     
  13. Srokaaa

    Srokaaa

    Joined:
    Sep 18, 2018
    Posts:
    72
    Gotta love late friday updates, it gives you whole weekend to play with new stuff
     
    hippocoder likes this.
  14. Shinyclef

    Shinyclef

    Joined:
    Nov 20, 2013
    Posts:
    364
    I can expand on this question with code for my use case:
    Code (CSharp):
    1. private struct ProcessTriggerEventsJob : ITriggerEventsJob
    2. {
    3.     public EntityCommandBuffer.Concurrent BeginSimCB;
    4.     [NativeDisableParallelForRestriction] public BufferFromEntity<TriggerInfoBuf> TriggerInfoBufs;
    5.     public ComponentDataFromEntity<HandleTriggersTag> HandleTriggersTagComps;
    6.  
    7.     public void Execute(TriggerEvent triggerEvent)
    8.     {
    9.         Entity a = triggerEvent.Entities.EntityA;
    10.         Entity b = triggerEvent.Entities.EntityB;
    11.  
    12.         if (HandleTriggersTagComps.Exists(a))
    13.         {
    14.             BeginSimCB.AddComponent(0 /*whatIndexShouldIUse??*/, a, new HasTriggerInfoTag());
    15.             DynamicBuffer<TriggerInfoBuf> buffer = TriggerInfoBufs[a];
    16.             buffer.Add(new TriggerInfo(b));
    17.         }
    18.  
    19.         if (HandleTriggersTagComps.Exists(b))
    20.         {
    21.             BeginSimCB.AddComponent(0 /*whatIndexShouldIUse??*/, b, new HasTriggerInfoTag());
    22.             DynamicBuffer<TriggerInfoBuf> buffer = TriggerInfoBufs[b];
    23.             buffer.Add(new TriggerInfo(a));
    24.         }
    25.     }
    26. }
    The code illustrates my intention: For entities with a 'HandleTriggersTag component, add a 'HasTriggerInfoTag' component, and append to its
    DynamicBuffer<TriggerInfoBuf>
    so that jobs can process things entities with trigger events, with access to all collision partners via the dynamic buffer.

    Two problems emerge:
    1. I guess I don't have parallel safety for writing to those dynamic buffers.
    2. What index should I use when calling CommandBuffer.AddComponent?

    I'm guessing this will need a re-write to another strategy, making ITriggerEventsJob perhaps a little less useful than I would have hoped?

    Edit: There is no ScheduleSingle :(, was going to use that to work around and test for the moment.

    Edit2: I was considering using a NativeMultiHashMap to store entities with list of triggering partners, then pass that into a second job to apply components and add to buffers, but I don't know the size to initialise the map to, and I can't see any properties exposing colliding entity count. It looks like the DisplayTriggerEventsSystem has some interesting stuff going on with BlockStreams in a 2-step strategy. I might see how I can use a BlockStream myself to get things to work. It feels like this shouldn't be so hard though? I wonder if I'm missing something obvious... it seems silly to be putting things back into a stream at this point lol.
     
    Last edited: Jun 1, 2019
    steveeHavok likes this.
  15. Srokaaa

    Srokaaa

    Joined:
    Sep 18, 2018
    Posts:
    72
    Hmmm, it seems that something is wrong with how physics calculates the translation of kinematic bodies based on their velocity. This was not introduced in this update though, I've seen the same behavior in the previous release. One can reproduce it in a following way:

    I have a simple system for moving entities based on:
    1. Initial position
    2. Velocity
    3. Time

    Code (CSharp):
    1.      
    2. private struct StraightMovementLevelJob :  IJobForEach<StraightMovement, LevelTime, Translation>
    3.         {
    4.             public void Execute([ReadOnly] ref  StraightMovement movement,
    5.                                 [ReadOnly] ref  LevelTime        time,
    6.                                 [WriteOnly] ref Translation      position)
    7.             {
    8.                 //TODO Remove in favor of physics simulation
    9.                 position.Value = movement.StartPosition + movement.Velocity * (time.Time - movement.StartTime);
    10.             }
    11.         }
    12.  
    I'm spawning the entity setting StraightMovement values in a following way, with some arbitrary startPosition, spawnTime and speed:

    Code (CSharp):
    1.                              
    2. commandBuffer.SetComponent(trajectoryVisualisation, new StraightMovement
    3.                                 {
    4.                                     StartPosition = startPosition,
    5.                                     StartTime     = spawnTime,
    6.                                     Velocity      = speed
    7.                                 });
    8.  
    I tried get rid of it since if I wanted the translation of the entities to be driven by physics simulation. I do this in a following way:


    Code (CSharp):
    1.                              
    2. commandBuffer.SetComponent(prefabEntity, new Translation
    3.                                 {
    4.                                     Value = startPosition + speed * (levelTime.Time - spawnTime)
    5.                                 });
    6.  
    7. commandBuffer.SetComponent(prefabEntity, new PhysicsVelocity
    8.                                 {
    9.                                     Angular = float3.zero,
    10.                                     Linear  = speed
    11.                                 });
    12.  
    where startPosition, spawnTime and speed are exactly the same as in non-physics driven version. Entities spawned in both ways should always have the same translation but they don't.
    This is non-physics version. the red line is drawn using StraightMovement values and marks the predicted trajectory of the entity

    upload_2019-6-1_10-22-9.png

    This is physics-driven version. Red line is also drawn using StraightMovement values:
    upload_2019-6-1_10-25-24.png

    Hope this is enough to reproduce the bug.

    Also, thank you guys for all your hard work, I love the new physics package :)
     
    Last edited: Jun 1, 2019
    steveeHavok likes this.
  16. PhilSA

    PhilSA

    Joined:
    Jul 11, 2013
    Posts:
    1,063
    I'm in the middle of porting my character controller to DOTS and I gotta say so far UnityPhysics is a complete game-changer compared to the old PhysX integration.

    Mostly because:
    1. SimplexSolver.Solve() is a gift from Heaven
    2. world.CastCollider() lets you do a cast with whatever shape is currently assigned. This means we can alternate between Capsule, Cylinder, Box, etc... for the character as we please. The only way to do this before was with Rigidbody.SweepAll(), but there was no non-alloc version and it had some limitations, so it was unusable for me
    3. world.CalculateDistance() is like Physics.Overlap + Physics.ComputePenetration, but with extras. It automatically gives you the closest point, the distance and it allows you to "inflate" the ovelap check, and I often felt like I needed that
    4. Working with systems means users can go insert logic between/after every step of the character simulation, so they have much more freedom than before AND it's easier to understand the order of execution of everything
    5. Access to post-narrowphase constraint modification/addition for regular rigidbody physics means we're able to do dynamic rigidbody characters that deal with slopes and angled blocking walls perfectly well
    6. Much more versatility for physics queries in jobs, compared to the batched raycasts API (batched raycasts API can't really deal with raycasts within loops with conditions, and it's also missing a lot of physics query variants)
    7. "Officially" separating Simulation and Presentation means dealing with rigidbody interpolation, and making it safe for users to not break interpolation, will no longer be a nightmare. In theory we could've done this in Monobehaviour too, but for an asset store product I thought it would've felt too alien for users if our characters were separated in a "physics" gameObject and a "visuals" gameObject. It's great that this will become the norm
    8. Rendering and Physics layers are officially separate things now! Wooo! And layers actually live on the collider itself, so when you do a CastCollider, it automatically takes into account all collision filtering, unlike CapsuleCast, etc..
    9. I tried doing a 1:1 comparison for a simple rigidbody character controller I made both in DOTS and in Monobehaviour. For the same framerate (100fps on i5-4690k), I have
      • 1500 moving characters in Monobehaviour+PhysX
      • 10000 moving characters in DOTS+UnityPhysics
    Pretty much all of the limitations that I could think of in the old physics solution are now solved with this. Just felt like sharing my enjoyment, nice work!
     
    Last edited: Jun 3, 2019
  17. PhilSA

    PhilSA

    Joined:
    Jul 11, 2013
    Posts:
    1,063
    One question though:

    When doing a world.CastCollider(), if I want to always ignore the collider that we used for casting, but otherwise keep all the collision filters intact, is there a more efficient way to do this than to iterate on all hits of the hits collector and remove the hits that have the same entity as our collider? I feel like this will be a very common use case for a CastCollider(), so it would be great if this could be done as efficiently as possible

    -

    I'm looking for ways to do that filtering in a custom ICollector when a hit is added, but I'm under the impression that IQueryResult would need an interface method to return the RigidbodyIndex in order to be able to do that. Currently you only have access to the "Fraction"


    If I had access to the rigidbodyIndex from the IQueryResult, I could even add an array of ignored rigidbody indexes to my collector if I need to do more fine-grained filtering, which will probably happen soon (example: making one specific character ignore collisions with one specific object for a short time while they have a certain powerup). I would accomplish this by storing a DynamicBuffer of ignored Entities on my character Entity, and transfer that buffer's content to my custom collector's ignore list before doing queries
     
    Last edited: Jun 3, 2019
    steveeHavok likes this.
  18. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    1,648
    This has done my head in

    upload_2019-6-3_15-45-28.png

    Why are the x and y values of the collider reversed

    -edit-

    For the sake of my sanity I checked the center value as well

    upload_2019-6-3_15-52-21.png

    upload_2019-6-3_15-51-32.png

    And that is not reversed
     
    Last edited: Jun 3, 2019
    hippocoder likes this.
  19. Adam-Mechtley

    Adam-Mechtley

    Unity Technologies

    Joined:
    Feb 5, 2007
    Posts:
    191
    Thanks! I'll get this fixed
     
  20. Adam-Mechtley

    Adam-Mechtley

    Unity Technologies

    Joined:
    Feb 5, 2007
    Posts:
    191
    This looks like an artifact of changes I made to the shape baking code. It is too aggressively "reorienting" the shape along its longest axis (so if you check boxCollider->Orientation it probably also is rotated 90 degrees). I'll get it fixed.
     
    tertle likes this.
  21. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    1,648
    Cheers that makes sense, I didn't even consider the orientation because I hadn't set any. I'll just factor that in to what I'm doing anyway in case I end up using it at some point.
     
    Last edited: Jun 3, 2019
    steveeHavok likes this.
  22. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    110
    I will leave the general parallelism and DynamicBuffer questions to the Unity experts. Regarding your Edit2 option the more advanced Trigger event examples do exactly this 2-step strategy.
    These samples try and capture Entered, Overlapping and Exited state from the Trigger events. State is not something we wish to put in the physics engine itself but at the application level it may be needed.

    In the
    OnUpdate
    function of TriggerVolumeBehaviour.cs a number of related jobs are scheduled that
    1. Count the number of events (will need to re-expose the count in future instead of this)
      1. This count is stored in a single element NativeArray
    2. Update trigger volumes (i.e. increment trigger frame index - used as creation stamp when tagging overlapping bodies)
    3. Create a list of overlapping bodies (the aim is to have filtered jobs in future)
      1. The count is updated here as some events are filtered in the List job
    4. Update overlapping bodies (i.e. tick overlapping body frame index if it is still in the list of overlapping bodies)
    5. Add components to new overlaps (i.e. body in overlapping list but doesn't have tag component)
    6. Remove component from bodies that now longer overlap (i.e tagged body frame index no longer matches trigger volume frame index).
    So there can be a lot of wiring up on the more complex trigger samples. The samples, while hopefully useful for you, are also acting as dogfood for us to see how we can make accessing everything easier.
     
    Shinyclef likes this.
  23. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    110
    I would need to test a repro of your setup to confirm 100%, but I suspect the PhysicsVelocity delta time is not the same as your StraightMovement delta time. At the minute Physics is stepped at 50hz regardless of framerate (to help this problem check out this post). A generalised fix for this is in progress but in the meantime it can cause the divergence you are seeing.
     
  24. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    110
    Fantastic feedback. You can hackily (is that a word?) filter hits in
    TransformNewHits
    where you do get the RigidBodyIndex, though you have to subsequently ignore the boolean result from the main CastCollider function and use other information e.g. fraction value, as a test to getting a valid hit.
    Due to the sort of problem you describe, we are planning on revamping custom collection so that you have all the information needed to filter at the point
    AddHit
    is called. Its likely that we will also add a simple flag or parameter to ignore initial overlaps as this is so common.
    There was a discussion on this topic a few pages back. In short, see this comment, and check out the Mouse Pick Behavior in the samples for an example workaround with a custom collector ignoring static and trigger bodies.
     
  25. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    110
    Its worth highlighting that this sort of orientation change means that the motion space of the body is altered. Angular velocities are currenty read and written in motion space. So, if you have set
    Initial Angular Velocity
    in the
    PhysicsShape
    component or are setting or getting
    Angular
    values from the
    PhysicsVelocity
    component you may find bodies spinning around different axes.
    We are planning to move manipulation of angular velocities to world space to help avoid this sort of confusion.
     
    kstothert likes this.
  26. Adam-Mechtley

    Adam-Mechtley

    Unity Technologies

    Joined:
    Feb 5, 2007
    Posts:
    191
    Hi all! I wanted to share a brief video highlighting a couple of improvements made to primitive shape baking in version 0.1.0. I'd like to encourage you all to try it out and share your experiences. Let me know if you manage to produce collision geometry that's not what you would expect, or if you encounter other bugs. (thanks @tertle!)
     
    hippocoder, Arkade, recursive and 7 others like this.
  27. The-Exceptional-Bruce

    The-Exceptional-Bruce

    Joined:
    May 10, 2015
    Posts:
    27
    Is 2D physics going to be a separate package or included in this package, but developed later?

    I see some project tiny crossover in the 2D physics scope and wondered what is going to be developed?
     
    Shinyclef likes this.
  28. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    416
    I'm back with more analysis of the new Unity.Physics release. I haven't had a lot of time with this release but I like what I'm seeing so far compared to the previous versions.

    Performance:

    The Bad:
    The pool demo got worse. Simulation times dragging the sliders around went from 120 ms to about 500 ms on my machine. Unless I'm missing the step count changing, something is wrong.

    The Good:
    What black magic madness did you commit on that broadphase?!
    Seriously...!
    What did you do?
    The broadphase in the gravity demo went so fast I had to crank up the count by an order of magnitude and EVEN THAT was faster than the previous version's broadphase at the original count. I'm going to have to really dig in and understand what the secret is and maybe try making it work with my own benchmark. I might just have to abandon my CCDE's broadphase for this BVH-based one. That would be a first for me at this performance tier.
    Awesome work!

    Features:

    The Bad:
    Stacking is still not supported. Actually the behavior is less consistent. In the Hello World scene, when I tried stacking the letters, it used to be that only the top letter slid off while the bottom letter never moved. Now the bottom letter sometimes starts moving. It is very strange.

    The Good:
    Constraints improved quite a bit. I'm legitimately impressed with what is there. Also static colliders are a thing now.

    API:

    The Bad:
    Unsafe is still required to do anything with colliders because the full collider is stored in a Blob. In my CCDE, I have a collider type that lives in ECS chunks. It can then be cast into its specific collider type. Some collider types contain all the data they need as is. Others will contain a BlobAssetReference to mesh data. But the exposed API is clean and safe. There's no worry about accidentally copying a blob header onto the stack and then accessing garbage memory. I can easily detect casting errors in debug builds. And my favorite part is that I can generate a temporary collider right in a job and raycast against it or cast it against a collision layer without having to do any real main thread preparation. I don't even want to attempt to write a character controller in Unity.Physics right now.

    The second issue is how transform data is handled. While there was a good improvement and now statics exist, static colliders make the entities' transforms not static. If you really need position and rotation on a static entity, why not make your own component type called "StaticTRS" or something? This will allow static colliders to be truly static and not get unnecessarily processed by the transform system. I saw that Friday and opted not to use Unity.Physics for a demo project that would have otherwise probably worked since my CCDE wasn't in a good enough state for the demo's needs. Looking back, I should have spent the time just fixing the converters and ECS API, though the Character Controller would have still been a problem.

    The Good:
    Collisions and Trigger event callbacks API is really good now. It is simple and to the point. I like it.

    Overall:
    This is a really solid update. Hopefully Unity.Physics continues to improve this much with each successive update. If it does, I have no doubts it will meet my needs for future projects (besides projects that need a powerful CCDE of course).
     
    steveeHavok, Arkade, rizu and 3 others like this.
  29. smcclelland

    smcclelland

    Unity Technologies

    Joined:
    Dec 19, 2016
    Posts:
    61
    Hey there, 2D physics will be a separate package but the current thinking is we can re-use bits of the solver/code from Unity Physics to help build out our 2D solution. If you have any input or thoughts here we would be happy to get more insight into this.
     
    pm007, Arkade and Shinyclef like this.
  30. Shinyclef

    Shinyclef

    Joined:
    Nov 20, 2013
    Posts:
    364
    Hello. I was performance tuning my game, trying to utilise time my CPU cores were inactive.

    I noticed the physics steps taking a long time and started using stopwatch to find what part of it was taking the longest. It was a simulation step involving jakobians. I can't claim to really understand what this step does, but I did find out that the physics steps setting affects it. Setting it to 1 improved performance significantly.

    I only have kinematic bodies at the moment. Shouldn't these be excluded from processing for jakobians solver iterations? Did I find a bug? :D
     
    Last edited: Jun 5, 2019
    steveeHavok likes this.
  31. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    4,670


    We have a bunch of work ongoing to improve stacking. Hopefully part of next release.

    This is not a physics specific issue. It's specifically that BlobAssets don't allow for safe API's yet. The main issue is that its insanely easy to screw up copying a blob by value. Given that, we decided to expose it as unsafe Ptr for now since it makes it by default less likely that you would copy it by value...

    We plan to fix that but it requires plugging into the C# compilation pipeline. We need an attribute that disallows copying a struct by value as a compile error. All of it doable, and we'll get there. For now it's just a bit of a minefield. BUT structurally it's the right approach. BlobAssets allow reuse of data, can be easily relocated, zero patch up necessary at load time. Constructable in a job etc..

    Once that safety exists, we will change the API to use Ref instead of Collider* and it will not be required to use unsafe API's.

    I am very surprised by that statement. Did you see PhilSA post above. I think the utility methods for character controllers are quite amazing, very powerful and give you full control. Also amazing in terms of perf given all the improvements we made to the BVH. It would be great if you can try it in more detail and reply with what specific issues you have with the character controller.

    You can simply add a frozen tag component on the entity and transform system won't process it. Are you using StaticOptimizeEntity component to mark your static geometry actually static including rendering at conversion time? That should do that automatically.
     
    Kender and GliderGuy like this.
  32. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    4,670
    Using 1 for step settings is the correct setup if you have only kinematic bodies.
     
  33. Arkade

    Arkade

    Joined:
    Oct 11, 2012
    Posts:
    569
    Hi, late joiner but so far enjoying (occasionally hair-tearingly-enjoying) learning ECS/DOTS with Unity.Physics. Very excited for this brave new world with such fast creatures in it! :D

    2 naïve questions:

    Question 1:
    What's the best way to discover joints attached to entities?

    Question 2:
    What's the plan for [community created/editable] FAQ for Unity.Physics?

    Question 1 background:
    I decided to use Extra Credits "ExtraGameJam" last weekend to throw myself at learning ECS/DOTS with Unity.Physics. Using the "Character Controller" sample, I successfully got each shot attaching to whatever it hit with a ball-socket joint. I 'hit' problems figuring whether to
    AddComponent()
    or
    SetComponent()
    on my
    EntityCommandBuffer
    within my
    JointCreationJob
    . I've brute forced a solution by querying all joints and supplying the entity array to the job and iterating to find whether my source entity is in the list of entities with joints. This obviously isn't optimal so I figure I've missed something. When the entity the joint is attached to is destroyed (e.g. by
    EntityKiller
    timing-out the shot), I seem to have to handle that explicitly so guess I'll need a similar solution though this feels like a lacking in the library (not to delete things like joints referencing a deleted entity?). Like I said, I figure I'm missing something obvious. Feel free to slap me -- I'm still learning.
    Sadly that took all my jam time. I don't mind -- I learnt loads. Have a silly 10s video of it working FYA:



    Question 2 background:
    Beyond the official docs, this 10-so-far page thread is the best place to find gems and hints on how to achieve things. Obviously that's not ideal. I'm trying to read a page or so a day but I'm only 4 days in so far!
    Is it expected:
    1. other forum threads with questions will spawn and get answered?
      (yes, there's a theme of people asking how to do collision response in those links)
    2. Unity.Answers will just spawn and get answered?
      How best to tag/annotate them to distinguish "Unity.Physics" (this) from "PhysX" (ofc an infinite number of monkeys have already written "unity physics" for that so umm...)
    3. wiki.unity3d.com ?
      FYI (a) it requires registration for account but (b) the Terms of Service are missing so ... um how can I agree I've read them!?! o_O
    In conclusion: Great work so far on all this from some random forum member :) Looking forward to using ECS/DOTS a bit when I need it in other things now

    p.s. is it Unity's ECS(tm) or can we just say DOTS(tm) or what?!?! o_O
     
  34. rizu

    rizu

    Joined:
    Oct 8, 2013
    Posts:
    1,153
    Current wiki is super problematic and I wish it would just be archived. Having everything in wiki to go by CC-BY-SA is not only huge issue but also impossible equation if you actually wanted to use any code snippet from the the wiki. CC-BY-SA is copyleft license like GPL and you can't even use it with Unity codebase at all.

    Therefore I hope none of the DOTS sample snippets ever see this wiki (unless the license is changed to something that people are actually allowed to use in Unity projects).
     
  35. Shinyclef

    Shinyclef

    Joined:
    Nov 20, 2013
    Posts:
    364
    I may later have a mix of kinematic and dynamic bodies, requiring a higher step count. Is it intentional for kinematic bodies to contribute to higher CPU time with higher step counts?
     
  36. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    4,670
    We now schedule all jobs without sync points. This means we dont know how many things are kinematic or not when we schedule the jobs and we simply schedule all possible 600 jobs to run physics. In many cases many of the jobs do nothing...

    If you run in standalone player, the cost of a bunch of empty jobs doing nothing is massively lower than in editor (Especially with jobs debugger enabled)

    Also there is one massive 10x optimazation we are getting into 19.3 that massively reduces the cost of scheduling deferred parallel for jobs that have no work to perform. All things combined we have got totals for a lightweight scenes to less than 0.3ms. That seems ok to me. It's a tradeoff where we choose to optimize for the scale case.

    Whats amazing about the approach is that we can now just schedule all the physics job, including contact events etc, and it's only the rendering system that finally has a sync point on the main thread. Giving massive opportunity for parallelism and other systems to fill holes in the physics jobs when it's impossible to run parallel jobs for some of the phases.


    Is 0.3ms on macbook pro for kinematic or mostly static scenes a real world problem for anyone? (Thats what we'll have in 19.3)
     
    Kender, DavidSWu, Seb-1814 and 9 others like this.
  37. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    416
    I sort of see where you are coming from with this, but I still disagree with that reasoning. Maybe its just a naming issue or maybe it is a use case issue.

    To me, making a Collider a BlobAssetReference suggests that a Collider is an asset. For simple games that rely on prefabs, that's actually true. And if that's the goal, it makes sense. However, I don't think of colliders as assets. I like to generate and destroy them and modify them at runtime all over the place. A really simple example of something like this is the Katamari Damacy games where the sphere collider constantly changes size as it picks things up. What would be the intended way to implement something like that with BlobAssetReferences? And also, why would I want to temporarily allocate a collider in a blob if I only need it inside the current job and could just allocate it on the stack?

    But you know what does make sense to me? A compound collider type or a mesh collider that actually gets its shape from a prefab (multiple colliders composed) or a mesh (quite literally an asset) using a BlobAssetReference to get its shape but otherwise being a Collider that can be allocated on the stack freely. I get the exact same benefits of Blobs with additional benefits and an overall cleaner and more intuitive API. Help me understand. What am I missing?

    This mostly stems from the Collider API being unsafe and not obvious how I would modify colliders at runtime (something my character controllers often need, beyond the simple swapping between premade colliders). Everything else looks really promising though. And for what it is worth, I always designed around needing a custom character controller in classical Unity because it was also a nightmare. Here I am heavily considering it but the Collider API needs to make sense to me first and right now it doesn't.

    TRSToLocalToWorldSystem has no reference to the Frozen component anywhere. It is not being used as an exclude component from what I can see. The conversion system just looks for the static component and if it exists does an early out without adding Translation, Rotation, Scale, or the Parent hierarchy components. I'm guessing I'm missing something.
     
    Kender likes this.
  38. PhilSA

    PhilSA

    Joined:
    Jul 11, 2013
    Posts:
    1,063
    I haven't yet gotten to the point where I need to modify colliders at runtime, so I can't comment on how possible this is right now (I haven't looked into it at all), but I do agree it would be a problem if I can't do that

    My theory right now is that Colliders need to be BlobAssetReferences because of cases where the collision geometry is a mesh asset (?)
     
    Last edited: Jun 5, 2019
  39. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    4,670
    Check out Physics_SphereCollider. Blob Assets are super lightweight to create and destroy.
    So creating one temporarily and releasing it again all in a single job is perfectly reasonable.

    We made them all blob assets in order to have it all be one consistent type. That can be passed around and queried against without the code that passes it around having to know the type...


    Currently the API doesn't allow for creating them on the stack. But there is no reason why we can't enable that for SphereColliders and other primitives. They can definitely be zero overhead primitives for procedural temporary creation.

    If you look at Physics_SphereCollider.cs it should be quite obvious how you can do that temporarily until we add proper support for it.
     
  40. PhilSA

    PhilSA

    Joined:
    Jul 11, 2013
    Posts:
    1,063
    Ah, got it. This seems like it solves the issue. I did a bit of searching in the source code for examples, in case others are curious

    Creating a SphereCollider at runtime as an input to a ColliderCast:


    Getting a modifiable SphereCollider from a regular Collider:
     
    eizenhorn and Arkade like this.
  41. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    1,648
    Anyone know why this

    Code (CSharp):
    1.         [BurstCompile]
    2.         private struct Move : IJobForEach<PlayerMove, Translation, PhysicsVelocity, PhysicsMass>
    3.         {
    4.             public float3 Target;
    5.  
    6.             public void Execute([ReadOnly] ref PlayerMove player, [ReadOnly] ref Translation translation, ref PhysicsVelocity velocity, ref PhysicsMass mass)
    7.             {
    8.                 var v = math.normalize(this.Target - translation.Value).xz * player.Speed; // 10
    9.  
    10.                 var l = velocity.Linear;
    11.                 l.x = v.x;
    12.                 l.z = v.y;
    13.  
    14.                 velocity.Linear = l;
    15.  
    16.                 mass.InverseInertia = float3.zero; // temp fix until freeze rotation added to inspector.
    17.             }
    18.         }
    Causes my object to behave as expected in Editor, but fly at a million miles / hour in a windows IL2CPP build?
    Velocity should be in units/second correct so I don't need to modify it by delta time.
    link.xml is setup as well so stripping shouldn't be an issue.

    This is not how I would usually build a job but it was a very quick hack for a demo scene and I'm just not sure why it's behaving how it is.
     
  42. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    4,670
    try math.normalizeSafe just in case target and translation is the same value... (Which will generate NAN)
    If thats not it then make a small repro project please.
     
  43. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    416
    I made a new thread to discuss this in more detail: https://forum.unity.com/threads/rules-and-whys-behind-blobs-and-colliders.690451/ It would be awesome if you could clarify my confusion there!

    As for the Frozen Tag, it works for RenderMeshSystemV2 but not for TRSToLocalToWorldSystem which is still processing the static entities.
     
  44. rizu

    rizu

    Joined:
    Oct 8, 2013
    Posts:
    1,153
    There are plenty of issues on IL2CPP builds on both conversion workflow and Unity Physics atm. I just reported two few days ago:

    1159434 - IL2CPP build doesn't render meshes converted to ECS (this happens even without Unity Physics, this is quite selective too as DOTS samples repo's assets seem to work in IL2CPP)
    1159445 - IL2CPP master/release build crashes when Unity Physics package in use

    QA successfully reproduced both of these but no dev responses so far. There also were bunch of other IL2CPP issues on 0.0.2 package but 0.1.0 seems to cope a bit better.

    Additionally unsafe's on MousePicker-script from DOTS physics sample repo caused additional grief when I tried on my test project on IL2CPP, got hard crashes on that too.
     
    Last edited: Jun 6, 2019
  45. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    110
    Thanks for this feedback. I'll leave the blob/collider questions as you have an ongoing discussion there.

    I'm happy to be able address the pool demo and stacking issues though.

    The Pool Demo did get slower but doesn't need to be. I certainly needs some love (same of the RaycastCar demo). There are a few factors that cause the pool demo to be slow.
    1. The first is entirely to do with the demo itself. It currently creates a clone of the simulation, steps it 100 times (iirc it was only 75 initially) and creates trails every step. The demo should simply collect the bodies transform information and create all the trails in jobs, rather than every iteration in OnUpdate. It should also ignore bodies that are not moving and only create trail entities when displacements are over some epsilon.
    2. Only the simulation step itself is jobified, and not necessarily in a way that is desirable here. The ultimate aim for this usecase is that a simulation could be ran on a single separate thread. This would mean that you could have little non-gameplay critical simulations (e.g. for hair ponytails, or car aerials, or flags, or future predictions) running independent of the main game-play critical simulation. These sub simulations would be ran on a specific worker thread, or threads, and limited to only those. Currently the cloned simulation spills across all threads, including the main thread holding everything up when it shouldn't.
    3. The simulation step has a number of phases. Phases are like batches of work colliding and resolving dependent sets of bodies (see
      ). Unity Physics has a maximum of 17 phases (16 multithreaded and 1 overflow single threaded). By default, there are also 4 iterations per simulation step as well, though this can be changed by the user. Each phase or each iteration creates an IJobParallelFor solve job. Previously when there were sync points in the simulation we knew how many phases there were going to be, and so how many solve jobs needed spinning up. Now that the sync points are removed, the worst case number of jobs are being created each step (17 * #iterations * #threads), even though a lot of these jobs will do no work. There is a tiny overhead on creating all these jobs, but with 100 steps, 17 phases, 4 iterations, and say 8 cores you can have 54,400 tiny overheads. This will be improved in the future when parallel for jobs scheduled with zero elements don't bother spinning up other jobs at all.
    The Hello World demo originally used box colliders for each letter. There were original major bugs in the convex hull generator that gave degenerate results with the flat faces of the letters. These issue were largely fixed, so the letters were changed from using box to convex colliders. I'm not sure if this explains the differences you are seeing. Regardless stacking will be improved - most noticeably in the the upcoming Havok Physics plugin.

    HavokPhysicsPyramids12.gif

    EDIT: reminder for me to read further down the forum before adding extra redundant answers that Joachim already provided! :)
     
    Last edited: Jun 6, 2019
    rileyoc, PhilSA and Shinyclef like this.
  46. Shinyclef

    Shinyclef

    Joined:
    Nov 20, 2013
    Posts:
    364
    Please sir, tell people who decide not to make us cry in the pricing department. Don't forget us little solo indies! I'm both excited and scared for the Havok licencing/pricing announcement...
     
    GliderGuy and steveeHavok like this.
  47. Adam-Mechtley

    Adam-Mechtley

    Unity Technologies

    Joined:
    Feb 5, 2007
    Posts:
    191
    This sounds like a duplicate of some past issues we've had reported against entities (can't find the case numbers at the moment), but is a code stripping problem that occurs when there are no explicit references in your build to the hybrid mesh conversion system. Do you have something like this in a link.xml file?
    Code (CSharp):
    1. <linker>
    2. <assembly fullname="Unity.Rendering.Hybrid" preserve="all" />
    3. </linker>
    As for the other IL2CPP issues specific to physics, per the Known Issues section of Unity Physics release notes:
    We'll get to them :) but some other stuff is currently still a little higher in the queue
     
    steveeHavok likes this.
  48. rizu

    rizu

    Joined:
    Oct 8, 2013
    Posts:
    1,153
    Ah, should I still report issues I find on IL2CPP or wait for a bit and start doing that closer to release? I rely on IL2CPP so getting it up and running with Unity Physics is essential for me if I want to ever use it =)

    I'll check the stripping thing and report back.
     
  49. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    110
    Its worth noting that there isn't really any difference between a 'kinematic' body and a dynamic body. The kinematic label is only really at the editor level and is short-hand for a dynamic body with infinite mass. The simulation itself doesn't have an special case code for bodies with infinite mass.
    The inverse inertia tensor of infinite mass dynamic bodies, being zero, will zero out any collision resolution impulses, so they are very likely to end up in an interpenetrating state. The interpenetration code path is more expensive than non-interpenetrating, so it would be more expensive to have a lot of bodies overlapping.
    What's the use case for only kinematic bodies? Are you collecting all the collision information? Have you already filtered out collisions you don't need?
     
  50. rizu

    rizu

    Joined:
    Oct 8, 2013
    Posts:
    1,153
    Ok so.... I totally missed this on DOTS Samples :D. After putting the link.xml from DOTS physics samples, it solved both of the mentioned things: I get converted objects rendering on IL2CPP and Unity Physics doesn't crash on Master/Release builds anymore (kinda weird it worked without on debug conf). I'll put a note on both issue reports on this =) Thanks for the tip!

    For some reason the direct build from editor using Master conf and IL2CPP still crashes. If I do it from generated solution it works now for all Master/Release/Debug. Direct build from editor could also have some code stripping issue I suppose, maybe it fails to utilize link.xml?
     
    Last edited: Jun 6, 2019