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.

Official Unity Physics Discussion

Discussion in 'Physics for ECS' started by smcclelland, Mar 18, 2019.

Thread Status:
Not open for further replies.
  1. Karearea

    Karearea

    Joined:
    Sep 3, 2012
    Posts:
    374
    Thanks @Rory_Havok -That makes sense.

    Running this before BuildPhysicsWorld or after ExportPhysicsWorld didn't help, and I'm stumped when it comes to working on the PhysicsWorld.MotionVelocities directly. Are there any docs that explain how to apply forces in this way from a job? Thank you
     
  2. Nothke

    Nothke

    Joined:
    Dec 2, 2012
    Posts:
    112
    Seems like bodies don't get written into a vector map, hence they don't produce any motion blur. This is possibly a general ECS rendering or built-in pipeline issue (didn't test with UWP Edit: Object motion blur is not supported in UWP anyway). Known issue?

    Vector map comparison: Left, classic GameObject (PhysX) vs right, ECS (Havok)

     
    Last edited: Sep 24, 2019
  3. Buretto

    Buretto

    Joined:
    Mar 23, 2015
    Posts:
    49
    Hi, I was wondering why the new CollisionEvent.CalculateDetails.EstimatedImpulse returns a float instead of a float3 or float4? Does it only return the magnitude? I tried getting the return value but so far it's been tricky so I thought I would ask instead.
     
  4. Karearea

    Karearea

    Joined:
    Sep 3, 2012
    Posts:
    374
    Further to yesterday's question, I can see how I should use the physics callbacks to schedule the job at the right point in the simulation and have included the OnUpdate code below..

    Code (CSharp):
    1.     protected override JobHandle OnUpdate(JobHandle inputDeps)
    2.     {
    3.         SimulationCallbacks.Callback postSolveJacobiansCallback = (ref ISimulation simulation, ref PhysicsWorld world, JobHandle inDeps) =>
    4.         {
    5.             return new RemoteImpulseJob
    6.             {
    7.                 physicsVelocitys = GetComponentDataFromEntity<PhysicsVelocity>(),
    8.                 physicsMasses = GetComponentDataFromEntity<PhysicsMass>(),
    9.             }.Schedule(inDeps);
    10.         };
    11.  
    12.         stepPhysicsWorld.EnqueueCallback(SimulationCallbacks.Phase.PostSolveJacobians, postSolveJacobiansCallback, inputDeps);
    13.         return inputDeps;
    14.     }
    EDIT: I feel like this has been a dead-end, I can't operate on an IJobForEach this way. In plain English, is there any way to:

    add an impulse,
    at a point in space,
    to a physicsVelocity,
    that is on an entity not the same as the one being iterated,
    at the correct phase of simulation,
    via an IJobForEachWithEntity job?

    EDIT 2: I found a temporary solution, where I calculate the impulses in a JobComponentSystem (I'm running some pretty complex maths there), but apply them in a conventional ComponentSystem after deferring them to a dynamic buffer. Seems to work fairly well.
     
    Last edited: Sep 26, 2019
    steveeHavok likes this.
  5. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Candid constructive feedback is always good. We had hoped to get in a few features that would help here. Unfortunately there were a few edge cases that didn't pass our tests and we had revert the changes. One example, is that bodies could share the same Convex Hull or Mesh Collider, saving on build times and memory usage. You can elect to have a body create a unique collider, but it would be optional.
     
    hippocoder likes this.
  6. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    The old
    float4 AccumulatedImpulses
    parameter returned the contact impulse for each contact point. If there were more than 4 contact points all the impulses from point 4 thru N got accumulated into component 4. In practice, the contact impulses in that float4 weren't particularly useful for actual usecase.
    The new approach instead tries to provide a reasonable single impulse magnitude resulting from a colliding pair. The impulse direction comes from the contact normal and the position represents a reasonable weighted average of the lower level contact points in the collision manifold that significantly contributed to the contact impulse.
    For future releases we want to also report the impulses applied by friction in the motion plane defined by the contact normal.
     
    Buretto likes this.
  7. rz_0lento

    rz_0lento

    Joined:
    Oct 8, 2013
    Posts:
    2,357
    I have a question about Havok before I evaluate it any further. I was actually going to ask this at Unite but unfortunately ran out of time before getting to it (had still a nice chat with @steveeHavok, much appreciated your time). To get to the point, I noticed before Unite that current Havok package licensing isn't allowing commercial usage which I assume is because it's still on trial stage. Is the ETA for commercially usable version right now set to the January or is it still something that's not decided yet? :)

    Edit: as mentioned few posts below, I'm now referring to LICENSE.md at the root of the Havok Physics package, not the actual licensing html on the docs.
     
    Last edited: Sep 27, 2019
    steveeHavok likes this.
  8. RBogdy

    RBogdy

    Joined:
    Mar 6, 2019
    Posts:
    60
    Are we going to have a YouTube video posted on the Physics talk from Unite? Really looking forward to see what are the differences between Unity Physics and Havok and why would we even use Unity Physics if both are going to be free for Personal and Pro users.
     
  9. rz_0lento

    rz_0lento

    Joined:
    Oct 8, 2013
    Posts:
    2,357
    They recorded pretty much every talk so it's probably just matter of time for these to get uploaded to Youtube.

    They already started to add these so look out for the talks in: https://www.youtube.com/playlist?list=PLX2vGYjWbI0RzLRaqsqcgnuc2RvLPTUmi

    Also even if you use only Unity Physics and not the new Havok Physics package, there's some useful info on the Havok talk as well that concerns both packages.
     
  10. Nothke

    Nothke

    Joined:
    Dec 2, 2012
    Posts:
    112
    Wait wait, the license page says nothing about commercial usage. Yes, it is a "trial period", but it's not explicitly stated that that means commercial usage is not allowed. You really confused me now. Can Havok or Unity people clarify?
     
  11. rz_0lento

    rz_0lento

    Joined:
    Oct 8, 2013
    Posts:
    2,357
    Oh, I just realized that the LICENSE.md page isn't even communicated anywhere on the docs, but it does sit at the root at the package. It says things like this:
    and
    I now also noticed this whole license file seems to be some common trial license for Havok in general and not specific to Havok package on Unity as it's dated to Aug 24 2017 so it has to be some sort of mistake it even exists as is on this package folder. Would be nice to get some response on this because as long as this file is sitting on the package as is, I still have to obey it's terms.
     
  12. elbows

    elbows

    Joined:
    Nov 28, 2009
    Posts:
    2,501
    It does look like they just stuck their old trial license for a very different sort of Havok trial in there.
     
  13. thelebaron

    thelebaron

    Joined:
    Jun 2, 2013
    Posts:
    777
    maybe you get the actual license when you purchase the subscription from the asset store version
     
  14. rz_0lento

    rz_0lento

    Joined:
    Oct 8, 2013
    Posts:
    2,357
    Even if this happened, it wouldn't still solve the licensing issue from Unity Personal and Plus who get to use it for free. Honestly it feels like a mistake atm so hopefully will get some more info or get this sorted out.
     
  15. Nothke

    Nothke

    Joined:
    Dec 2, 2012
    Posts:
    112
    The package licensing page doesn't contain the name "limited" and the 3.1 chapter doesn't contain the word "trial", these seem to be completely different things. I presume this is about an SDK license / C++ source and not the Unity Package. I am pretty sure they would mention commercial usage on that package licensing page.

    But please, someone from Unity and/or Havok team give us some clarification.
     
  16. dannyalgorithmic

    dannyalgorithmic

    Joined:
    Jul 22, 2018
    Posts:
    92
    So ... I can find literally 0 mention of 2d anywhere. Unity dev or spokesperson want to help out a little?
     
  17. Nicolas-Vidal-Iscool

    Nicolas-Vidal-Iscool

    Joined:
    Mar 4, 2015
    Posts:
    6
    Hey there, I have a small setup with physics shapes and physics rigidbodies (auth components on gameobject) moving and nicely interacting in a subscene. But I have a hard time finding how in a custom componentSystem to "react" on a "triggerevent". Ideally I would like to be able to have a system wich resets the positions of all entities with a rigidbody which triggers with a static physics shape.

    Are we able to do that yet or is it still something we should wait for in order to be able to do it ?
    (I tried to wrap my head around the physics samples but did not manage to find what I was looking for)

    Thanks a lot.
     
  18. TRS6123

    TRS6123

    Joined:
    May 16, 2015
    Posts:
    244
  19. Rory_Havok

    Rory_Havok

    Joined:
    Jun 25, 2018
    Posts:
    70
    Sorry for the confusion. Our intent is that the package should be comercially usable as-is. It is unfortunate the current LICENSE.md file currently says things like "no commercial product development work is authorized under this Agreement" - that is an oversight on our part. We'll report back once we have figured out with our legal team how to remove the ambiguity.
     
    steveeHavok, rz_0lento and Nothke like this.
  20. Nicolas-Vidal-Iscool

    Nicolas-Vidal-Iscool

    Joined:
    Mar 4, 2015
    Posts:
    6
    Thanks you, it was not as easy as I expected, but it works :)
     
  21. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Can I take a step back and ask why do you need to tweak Velocities in the simulation callback? Running your own ComponentSystem after ExportPhysicsWorld (or before BuildPhysicsWorld) lets you change the values of the PhysicsVelocity components at your leisure. GetComponentDataFromEntity is absolutely the tool to access other entities with PhysicsVelocity components, but manipulating these from a simulation callback means you need to be careful ExportPhysicsWorld doesn't just overwrite any of your changes. Are you needing the old PhysicsVelocity component values and the new values in the simulation MotionVelocity arrays at the same time?
     
  22. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Unity Physics is focused on 3d currently. The Unity folk can speak to any specific DOTS 2d solution. A few folk on this forum have asked about 2D in the past (https://forum.unity.com/threads/unity-physics-discussion.646486/page-7#post-4460308), and the '4b. Limit DOF' demo speak to an option currently used (https://github.com/Unity-Technologi...er/UnityPhysicsSamples/Assets/Demos/4. Joints).
     
    NotaNaN likes this.
  23. PhilSA

    PhilSA

    Joined:
    Jul 11, 2013
    Posts:
    1,926
    Will Havok support the same APIs as UnityPhysics when it comes to contacts/pairs modification?
     
    Last edited: Sep 30, 2019
  24. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Yes.
    The only thing missing at the minute is the ability to add contact points. There was a sample in 0.1.0 samples but as Unity and Havok didn't conform at the time we removed it until we could ensure compatibility.
     
    NotaNaN and PhilSA like this.
  25. Karearea

    Karearea

    Joined:
    Sep 3, 2012
    Posts:
    374
    Hi @steveeHavok -This is for running aircraft simulation, utilising blade-element theory. I need to read the velocities of the parent physicsVelocity, iterate across each wing subsection to determine the lift / drag / pitch moment, and then feed forces back to the physics velocity. I have the blade-element calculations in a job (which runs insanely fast), but as you suggested, the new values were simply overwritten by ExportPhysicsWorld, whatever I tried. The earlier snippet is a kind of pared-back version of the blade-element job.

    So now what I do, is calculate the forces in the job and store them in a native array, and then apply them using a different system like so:

    Code (CSharp):
    1. [UpdateAfter(typeof(BuildPhysicsWorld)), UpdateBefore(typeof(StepPhysicsWorld))]
    2. public class AeroElementLiftSurfaceImpulseSystem : ComponentSystem
    3. {
    4.     BuildPhysicsWorld buildPhysicsWorld;
    5.  
    6.     protected override void OnCreate()
    7.     {
    8.         buildPhysicsWorld = World.GetOrCreateSystem<BuildPhysicsWorld>();
    9.     }
    10.  
    11.     protected override void OnUpdate()
    12.     {
    13.         buildPhysicsWorld.FinalJobHandle.Complete();
    14.  
    15.         Entities.ForEach((Entity entity, ref AeroElementLiftSurface aeroElementLiftSurfaceSection, ref VehicleEntityManagerReference vehicleEntityManagerReference, ref Parent parent) =>
    16.         {
    17.             DynamicBuffer<AeroElementLiftSurfaceSubSectionBufferElement> buffer = EntityManager.GetBuffer<AeroElementLiftSurfaceSubSectionBufferElement>(entity);
    18.  
    19.             var world = buildPhysicsWorld.PhysicsWorld;
    20.             int rigidBodyIndex = world.GetRigidBodyIndex(vehicleEntityManagerReference.vehicleEntityManager);
    21.  
    22.             //Iterate Forces
    23.             if (!(buffer.Length <= 0))
    24.             {
    25.                 for (int i = 0; i < buffer.Length; i++)
    26.                 {
    27.                     AeroElementLiftSurfaceSubSection ss = buffer[i].Value;
    28.  
    29.                     world.ApplyImpulse(rigidBodyIndex, ss.impulse.liftImpulse, ss.impulse.point);
    30.                     world.ApplyImpulse(rigidBodyIndex, ss.impulse.dragImpulse, ss.impulse.point);
    31.                     world.ApplyAngularImpulse(rigidBodyIndex, ss.impulse.pitch);
    32.                 }
    33.             }
    34.         });
    35.     }
    36. }
    37.  
    This 'works', although AeroElementLiftSurfaceImpulseSystem is quite expensive to run and doesn't scale. This was just to get it working, so I'm yet to address optimisation. Open to suggestions! At the moment there's one buffer per wing section, later I'll implement one buffer per physicsVelocity instead, and have all wing sections write to that
     
    florianhanke likes this.
  26. Nothke

    Nothke

    Joined:
    Dec 2, 2012
    Posts:
    112
    What is the correct and simplest way to change deltaTime and/or time scale (slowdown/speed up) the simulation?

    What I did is add a public timeScale field in StepPhysicsWorld, then mutliply the timeStep in its OnUpdate. Of course that's a hack, since it's in a package, every time I start open the project the package updates and removes my hack :D

    I notice that the "correct" way would be to create a new Simulation that accepts SimulationStepInput that contains the timeStep. That's a bit of a stretch to just be able to change the step.

    Additionally, what's the correct way to pause the simulation? I tried multiplying the timeStep with 0, but that makes all physics go crazy when you unpause :D I guess some system should be disabled, but not sure which.
     
  27. elbows

    elbows

    Joined:
    Nov 28, 2009
    Posts:
    2,501
    I cant answer your main questions but I can say that you can create local copies of packages if you need to hack them.

    I'm out of date in regards official and easiest ways to do this, but here is an example of a Package manifest file where one of the packages is coming from a local copy of a package, placed in YourProjectFolder/LocalPackages/nameofpackagefolder

    https://github.com/Unity-Technologies/SmallOfficeRayTracing/blob/master/Packages/manifest.json

    With the line in question being:

    "com.unity.render-pipelines.high-definition-config": "file:../LocalPackages/com.unity.render-pipelines.high-definition-config",

    Obviously thats for a HDRP config package, but the theory is the same for other packages too. I dont remember if they yet added a GUI way to do this through the package manager.
     
    steveeHavok likes this.
  28. wabra

    wabra

    Joined:
    Mar 18, 2015
    Posts:
    4
    Been checking out the physics package manual and i'm wondering how to to change the provided querying examples to support multiple hits rather than just a single one. This would be for, example, a sphere cast.

    Code (CSharp):
    1. [BurstCompile]
    2.     public struct ColliderCastJob : IJobParallelFor
    3.     {
    4.         [ReadOnly] public Physics.CollisionWorld world;
    5.         [ReadOnly] public NativeArray<Physics.ColliderCastInput> inputs;
    6.         public NativeArray<Physics.ColliderCastHit> results;
    7.  
    8.         public unsafe void Execute(int index)
    9.         {
    10.             Physics.ColliderCastHit hit;
    11.             world.CastCollider(inputs[index], out hit);
    12.             results[index] = hit;
    13.         }
    14.     }
    Does it suffice to just use the other version of CastCollider() ?

    Code (CSharp):
    1. world.CastCollider(inputs[index], ref results);
    Also, are there any other unity manual code examples or git repo's demonstrating these basics?
     
  29. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,351
    Ya we share colliders quite a bit.

    Static rebuild performance gets a bit involved. Partitioning of some type is required, and at two levels. One to partition features and another that is feature specific. Not all scenarios will call for this, but most at scale I think will, and even if it's not most it's enough for any generic solution to have to have this.

    Compound colliders I think have the best potential for a generic solution. Multiple collision worlds you run into what if you need queries over multiple worlds. For which there isn't really a good generic solution for even if it's often not a real issue. Compounds don't have that problem but they do need significant up front work before you can even use them for partitioning. That is if you want anything resembling elegant.

    Compound keys don't map to bodies. Mapping keys to user data works for cases where it's the feature that created the compound for it's own reasons. For partitioning the reason is something the feature doesn't care about and shouldn't know about.

    For queries we settled on having our own body component. Not because of compounds but it ended up solving problems there also. Originally it was because how Unity.Physics views static vs dynamic didn't fit how we used them. Kinematic/Non kinematic fits better. Static carries a strong this doesn't change implication, which fits colliders but not bodies really.

    Even with compounds that are specific to a feature I rather didn't like the whole keys api. I mean exposing that is great, using it in feature level logic not so much. So we make access to compounds uniform via our own body component. Keys being returned as a body. We haven't had a case yet where the feature level logic cared to know it was part of a compound.

    For compound creation we wrap the creation in a simple transactional wrapper that hides the details. So BeginCreateCompound/AddCollider/EndCreateCompound is what features work with.
     
    steveeHavok likes this.
  30. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Ah, using the PhysicsWorld extension functions would be slow, and they are being deprecated.
    You should be able to rework AeroElementLiftSurfaceImpulseSystem into a JobComponentSystem, updating after
    ExportPhysicsWorld 
    (or before
    BuildPhysicsWorld
    ) and tweaking the
    PhysicsVelocity 
    component data structs directly. This would end up be a little like the ForceFieldSystem/Job from the samples, but using the
    PhysicsVelocity 
    component extension functions to apply an impulse at a point. If you have the ECS samples downloaded from Github you can see these here: (EntityComponentSystemSamples\UnityPhysicsSamples\Library\PackageCache\com.unity.physics@0.2.4-preview\Unity.Physics\Extensions\World\ComponentExtensions.cs)
     
  31. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    We should probably add TimeStep into the PhysicsStep component rather than referencing Time.fixedDeltaTime!
    I know folk that have added 2 simple systems: one running before BuildPhysicsWorld which saved and then set Time.fixedDeltaTime, and one running after ExportPhysicsWorld which reset Time.fixedDeltaTime. Just as hacky but at least didn't need to change the packages :)
    I know there were issues with zero timestep in the past but I could have sworn that was fixed. I will double check.
    Rather than messing with zero timestep you could switch the SimulationType to 'No Physics'. Note that velocity changes from your own systems will still accumulate though so when you switch the SimulationType back bodies could fly off unexpectedly. e.g. this happens in the demos if 'No Physics' is selected, you trying to mouse pick the bodies and then 'Unity Physics' is reselected!
     
  32. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Yes there is a variant of the CastCollidier function that returns all hits. Check out the QueryTester script used in the Query samples. We do need to add a few basic samples to highlight each usecase (single cast/single hit, multiple cast/single hit, multiple cast/single hit, all hits, filtered hits, etc).
     
    florianhanke likes this.
  33. Karearea

    Karearea

    Joined:
    Sep 3, 2012
    Posts:
    374
    Hi @steveeHavok - I have jobified the impulse system again, making sure the setup is all identical to the Forcefield job, but tweaked velocities are ignored (the reason I separated out the blade element calculations and impulse tweaks to start with was because I couldn't apply forces like this). Here's the impulse code anyway:

    Code (CSharp):
    1. [UpdateBefore(typeof(BuildPhysicsWorld))]
    2. public class AeroElementLiftSurfaceImpulseSystem_IJobForEach : JobComponentSystem
    3. {
    4.     [BurstCompile]
    5.     public struct AeroElementLiftSurfaceImpulseJob : IJobForEachWithEntity<AeroElementLiftSurface, VehicleEntityManagerReference, Parent, LocalToWorld, Translation, Rotation>
    6.     {
    7.         [NativeDisableParallelForRestriction] public ComponentDataFromEntity<PhysicsMass> physicsMasses;
    8.         [NativeDisableParallelForRestriction] public ComponentDataFromEntity<PhysicsVelocity> physicsVelocitys;
    9.  
    10.         [NativeDisableParallelForRestriction] public BufferFromEntity<AeroElementLiftSurfaceSubSectionBufferElement> aeroElementLiftSurfaceSubSectionBufferElements;
    11.  
    12.         public void Execute(Entity entity, int index, ref AeroElementLiftSurface aeroElementLiftSurfaceSection, ref VehicleEntityManagerReference vehicleEntityManagerReference, [ReadOnly]ref Parent parent, [ReadOnly]ref LocalToWorld localToWorld, [ReadOnly]ref Translation translation, [ReadOnly]ref Rotation rotation)
    13.         {
    14.             var vehicleEntityManager = vehicleEntityManagerReference.vehicleEntityManager;
    15.             var bufferSS = aeroElementLiftSurfaceSubSectionBufferElements[entity];
    16.  
    17.             var physicsVelocity = physicsVelocitys[vehicleEntityManager];
    18.             var physicsMass = physicsMasses[vehicleEntityManager];
    19.  
    20.             Vector3 linearVelocity = physicsVelocity.Linear;
    21.             Vector3 angularVelocity = physicsVelocity.Angular;
    22.  
    23.             if ((float.IsNaN(linearVelocity.x) || float.IsNaN(linearVelocity.y) || float.IsNaN(linearVelocity.z)) ||
    24.                 (float.IsNaN(angularVelocity.x) || float.IsNaN(angularVelocity.y) || float.IsNaN(angularVelocity.z)))
    25.             {
    26.                 return;
    27.             }
    28.  
    29.             //Iterate Forces
    30.             if (!(bufferSS.Length <= 0))
    31.             {
    32.                 for (int i = 0; i < bufferSS.Length; i++)
    33.                 {
    34.                     AeroElementLiftSurfaceSubSection ss = bufferSS[i].Value;
    35.  
    36.                     physicsVelocity.ApplyImpulse(physicsMass, translation, rotation, ss.impulse.liftImpulse, ss.impulse.point);
    37.                     physicsVelocity.ApplyImpulse(physicsMass, translation, rotation, ss.impulse.dragImpulse, ss.impulse.point);
    38.                     physicsVelocity.ApplyAngularImpulse(physicsMass, ss.impulse.pitch);
    39.                 }
    40.             }
    41.  
    42.         }
    43.     }
    44.  
    45.     protected override JobHandle OnUpdate(JobHandle inputDeps)
    46.     {
    47.         var job = new AeroElementLiftSurfaceImpulseJob
    48.         {
    49.             physicsVelocitys = GetComponentDataFromEntity<PhysicsVelocity>(),
    50.             physicsMasses = GetComponentDataFromEntity<PhysicsMass>(),
    51.  
    52.             aeroElementLiftSurfaceSubSectionBufferElements = GetBufferFromEntity<AeroElementLiftSurfaceSubSectionBufferElement>()
    53.         };
    54.         return job.Schedule(this, inputDeps);
    55.     }
    56. }

    EDIT: I replaced the PhysicsWorld functions in the original non-job impulse component with the physicsVelocity.ApplyImpulse extensions, and that stops working too, so clearly I'm using the function incorrectly..

    EDIT2: I've realised I need to execute directly on the physics velocity and mass. It behaves quite strangely (forces are massively amplified, and stutter) but I'll be able to debug further from there at least.
     
    Last edited: Oct 4, 2019
  34. Nothke

    Nothke

    Joined:
    Dec 2, 2012
    Posts:
    112
    Oh, great, I made the pre-physics and post-physics hack you mentioned and it totally works. TBH, in my 8 years of Unity programming, I had no idea you could set Time.fixedDeltaTime :D

    Code (CSharp):
    1. using Unity.Entities;
    2. using UnityEngine;
    3. using Unity.Physics.Systems;
    4.  
    5. [UpdateBefore(typeof(BuildPhysicsWorld))]
    6. public class PrePhysicsSetDeltaTimeSystem : ComponentSystem
    7. {
    8.     public bool isRealTimeStep = false;
    9.     public float timeScale = 1;
    10.     public float previousDeltaTime = Time.fixedDeltaTime;
    11.  
    12.     protected override void OnUpdate()
    13.     {
    14.         previousDeltaTime = Time.fixedDeltaTime;
    15.  
    16.         if (isRealTimeStep)
    17.             Time.fixedDeltaTime = Time.deltaTime * timeScale;
    18.         else
    19.             Time.fixedDeltaTime = Time.fixedDeltaTime * timeScale;
    20.     }
    21. }
    22.  
    23. [UpdateAfter(typeof(ExportPhysicsWorld))]
    24. public class PostPhysicsResetDeltaTimeSystem : ComponentSystem
    25. {
    26.     public PrePhysicsSetDeltaTimeSystem preSystem;
    27.  
    28.     protected override void OnCreate()
    29.     {
    30.         preSystem = World.Active.GetOrCreateSystem<PrePhysicsSetDeltaTimeSystem>();
    31.     }
    32.  
    33.     protected override void OnUpdate()
    34.     {
    35.         Time.fixedDeltaTime = preSystem.previousDeltaTime;
    36.     }
    37. }

    Easily setting a global timeScale parameter would be a great addition, similar to how it's possible to do Physics.timeScale right now with PhysX.

    I managed to implement pause by simply switching the StepPhysicsWorld system off. I hope that's a safe way to implement pause too. But yes, there were also some of my own systems adding velocities as you predicted, disabled them too.
     
  35. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Apologies if you already know this but have you played with the Entity Debugger? If not, click Windows > Analysis > Entity Debugger. You'll see all the systems listed in the order they are executed each step. If your systems are running in an inappropriate order then you will get velocities being overwritten when you don't want them to be.
    You are applying impulses here i.e. direct changes to velocity. You mentioned forces are massively amplied; if you actually want to apply forces, rather than impulses, you need to multiply
    ss.impulse.liftImpulse
    etc by deltaTime (which for the Unity Physics simulation loop at the minute is Time.fixedDeltaTime).
     
    Last edited: Oct 4, 2019
  36. Karearea

    Karearea

    Joined:
    Sep 3, 2012
    Posts:
    374
    Thanks, yes I noticed the samples multiplied by fixed delta time so I’m doing that now.

    It was quite a large refactor so I’ll have another look right through. The debug lines I added pre-refactor all look correct, so I think it is likely to be an order issue as suggested. Cheers!

    EDIT: All resolved, running beautifully. Thank you so much for the help, I've been on this after hours for a few weeks as a project to find my way around the DOTS, I'll be sure to put up a video soon. Pretty incredible watching a few hundred fully-simulated gliders scoot around.
     
    Last edited: Oct 5, 2019
    steveeHavok likes this.
  37. thelebaron

    thelebaron

    Joined:
    Jun 2, 2013
    Posts:
    777
    Is there a way to toggle the collision events flag at runtime?
     
  38. Nothke

    Nothke

    Joined:
    Dec 2, 2012
    Posts:
    112
    From April:
    Any updates on the "joint impulse reporting" feature? I really need to implement breakable joints. If there won't be any soon, are there any other way that could be detected, like checking distance between anchors or something before constraining happens?
     
  39. RBogdy

    RBogdy

    Joined:
    Mar 6, 2019
    Posts:
    60
    Correct me if I'm wrong but by using PhysicsWorld.ApplyImpulse() we get the fixed delta Time already applied right?
     
  40. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    No, ApplyImpulse doesn't multiple in the deltaTime. Mass is considered but not deltaTime so it should be the equivalent of PhysX .addForce when ForceMode is passed as ForceMode.Impulse https://docs.unity3d.com/ScriptReference/ForceMode.Impulse.html
    Though to be honest, I haven't done a complete comparison.
     
    Karearea and NotaNaN like this.
  41. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Motorising the Joints is one of the top features that will be looked at for the few months, with the bigger context of supporting the general ragdoll usecase. Joint impulse reporting is a part of that.
    Alot of the guts of the solver was made internal as we planned to change the interface and didn't want it breaking on folk. This of course doesn't stop you making Unity Physics a local package and making changes. Have a look at the JacobianHeader.Solve function where you can see the specific JacobianType solve functions called.
    Ultimately all the Joints are really just built up out of more atomic linear and angular constraints.The individual Linear and Angular Limit Jacobian Solve functions are pretty well commented and you can see all the JacobianUtilities (e.g. CalculateError) being used in context.
    Even if you don't want to mess with the Unity Physics code directly you can see how constraint errors and corrective impulses are calculated and applied. Then you could tweak the guts of the engine or add your own layer on top.
    I hope a firmer timeline on all this will be available soon.
     
    Nothke likes this.
  42. Nothke

    Nothke

    Joined:
    Dec 2, 2012
    Posts:
    112
    That's great to hear! I'll try looking at the Jacobians.

    Right now, I'm trying to detect collisions, so that I could implement impact sounds. Finding any examples for ICollisionEventsJob is hard and none work. Here's my attempt:

    Code (CSharp):
    1. public class CollisionEventTestSystem : JobComponentSystem
    2. {
    3.     struct CollisionJob : ICollisionEventsJob
    4.     {
    5.         public void Execute(CollisionEvent collisionEvent)
    6.         {
    7.         }
    8.     }
    9.  
    10.     BuildPhysicsWorld bpw;
    11.     StepPhysicsWorld spw;
    12.     EndFramePhysicsSystem efps;
    13.  
    14.     protected override void OnCreate()
    15.     {
    16.         bpw = World.GetOrCreateSystem<BuildPhysicsWorld>();
    17.         spw = World.GetOrCreateSystem<StepPhysicsWorld>();
    18.         efps = World.GetOrCreateSystem<EndFramePhysicsSystem>();
    19.     }
    20.  
    21.     protected override JobHandle OnUpdate(JobHandle inputDeps)
    22.     {
    23.         var physicsJobDeps = JobHandle.CombineDependencies(
    24.                 inputDeps,
    25.                 bpw.FinalJobHandle,
    26.                 spw.FinalSimulationJobHandle);
    27.  
    28.         var handle = new CollisionJob().Schedule(spw.Simulation, ref bpw.PhysicsWorld, physicsJobDeps);
    29.  
    30.         efps.HandlesToWaitFor.Add(handle);
    31.  
    32.         return handle;
    33.     }
    34. }

    I found this example here

    But I'm getting "The previously scheduled job CollisionEventTestSystem:CollisionJob reads from the NativeArray CollisionJob.InputVelocities. You are trying to schedule a new job Solver:ApplyGravityAndCopyInputVelocitiesJob, which writes to the same NativeArray (via ApplyGravityAndCopyInputVelocitiesJob.InputVelocities)."

    I'm guessing I need to provide my job to another system, but I'm just lost to where and how exactly. I have a hunch there's another helper function that's not documented.

    Also, I'm not sure if I should use callbacks or not. I don't need to influence the physics, just to "read" the collisions.
     
  43. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,115
    @Nothke did you checked DOTS samples on github? There are scenes with different setups of physics. Including collisions query checks.
     
  44. Nothke

    Nothke

    Joined:
    Dec 2, 2012
    Posts:
    112
    I've seen them, but I don't need raycasts/collidercasts, I need info about collisions that already happen.
     
  45. petarmHavok

    petarmHavok

    Joined:
    Nov 20, 2018
    Posts:
    461
    Hey,

    Do you have scheduling attributes on your CollisionEventTestSystem? Something along the lines of
    [UpdateAfter(typeof(StepPhysicsWorld)), UpdateBefore(typeof(EndFramePhysicsSystem))]

    Then the scheduling should be ok, and you also wouldn't need the combination of dependencies, you could safely use inputDeps. Let me know if this works for you!
     
    Nothke likes this.
  46. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Yeah, sounds like a sample that needs adding. The collision event data was changed in the last release to give better information for this sort of thing. No demos yet but the change log has some details. FYI, I'm OOO at the minute but I can get you more details when I get back to a computer.
     
    Last edited: Oct 9, 2019
    Nothke likes this.
  47. Nothke

    Nothke

    Joined:
    Dec 2, 2012
    Posts:
    112
    That indeed works, I wouldn't have known that without your answer.
     
    steveeHavok and petarmHavok like this.
  48. Imakhiil

    Imakhiil

    Joined:
    Oct 11, 2013
    Posts:
    96
    Hey, I have a question, are things like joints, springs and wheel colliders already a part of the package? Presentation at Unite showed a rope made out of smaller meshes connected by "constraints". How could we reproduce such effect?
     
  49. Ziboo

    Ziboo

    Joined:
    Aug 30, 2011
    Posts:
    356
    Hello everyone,

    I checked the Physics Samples, and thank you for having a lot of exemple, always good to understand.
    Though... I check the CharacterController exemple, and frankly, I don't want to go there !!
    It's super scary, I just wanted to have a simple character that moves around, push object and collide with walls, but it seems that it will take me a lot of coding...

    And the worst, and don't take it the wrong way or personaly, but the result of all the code of the CharaterController doesn't fill super good when you take control.

    I know that you are still working hard on DOTS, but can we expect something a little more user friendly ?

    Thanks
     
    Orimay likes this.
  50. Kobix

    Kobix

    Joined:
    Jan 23, 2014
    Posts:
    111
    How are joints, are they stable enough to be used for robotics sim? Anyone tried it?
     
Thread Status:
Not open for further replies.