提交代码

This commit is contained in:
PC-20230316NUNE\Administrator
2024-01-31 19:16:05 +08:00
parent 6a66bc165f
commit b6461675a8
297 changed files with 19296 additions and 112413 deletions

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8b9d9fb46b16434388c671f9f5e7bbee
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d2b94b429bbc44d6952a716c15b9e637
timeCreated: 1706686833

View File

@@ -0,0 +1,74 @@
using System;
using System.Numerics;
using BepuPhysics;
using BepuPhysics.Collidables;
namespace Plugins.JNGame.BepuPhysics.Components
{
public abstract class BPhysicsBase : UnityEngine.MonoBehaviour
{
//世界索引
public int worldIndex = 0;
protected BodyHandle BodyId;
protected StaticHandle StaticBodyId;
//是否静态
public Boolean isStatic = false;
public JNBepuPhysics Physics
{
get
{
JNBepuPhysics.Physics.TryGetValue(worldIndex, out var value);
return value;
}
}
protected void AddDynamic<TShape>(TShape shape,BodyInertia shapeInertia) where TShape : unmanaged, IShape
{
var sphereIndex = this.Physics.Simulation.Shapes.Add(shape);
var transformPosition = transform.position;
var transformRotation = transform.rotation;
var spherePose = new RigidPose(new Vector3(transformPosition.x,transformPosition.y,transformPosition.z), new Quaternion(transformRotation.x,transformRotation.y,transformRotation.z,transformRotation.w));
BodyId = this.Physics.Simulation.Bodies.Add(BodyDescription.CreateDynamic(spherePose,
shapeInertia,
new CollidableDescription(sphereIndex, 0.01f),
new BodyActivityDescription(0.01f)));
}
protected void AddStatic<TShape>(TShape shape) where TShape : unmanaged, IShape
{
var transformPosition = transform.position;
var transformRotation = transform.rotation;
StaticBodyId = this.Physics.Simulation.Statics.Add(
new StaticDescription(new Vector3(transformPosition.x, transformPosition.y, transformPosition.z),
new Quaternion(transformRotation.x,transformRotation.y,transformRotation.z,transformRotation.w),
new CollidableDescription(this.Physics.Simulation.Shapes.Add(shape), 0.01f)));
}
public void OnPhysicsUpdate(float dt)
{
if (this.Physics == null) return;
if (this.isStatic) return;
this.Physics.Simulation.Bodies.GetDescription(this.BodyId,out var info);
//同步位置
var transform1 = transform;
transform1.position =
new UnityEngine.Vector3(info.Pose.Position.X, info.Pose.Position.Y, info.Pose.Position.Z);
//同步旋转
transform1.rotation =
new UnityEngine.Quaternion(info.Pose.Orientation.X, info.Pose.Orientation.Y, info.Pose.Position.Z,info.Pose.Orientation.W);
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 3e204f22f96e497ab13682ad13267883
timeCreated: 1706687376

View File

@@ -0,0 +1,37 @@
using BepuPhysics;
using BepuPhysics.Collidables;
using UnityEngine;
using NotImplementedException = System.NotImplementedException;
using Quaternion = System.Numerics.Quaternion;
using Vector3 = System.Numerics.Vector3;
namespace Plugins.JNGame.BepuPhysics.Components
{
public class BPhysicsBox : BPhysicsBase
{
private BodyHandle bodyId;
void Awake()
{
if (this.Physics == null) return;
Debug.Log("BPhysicsSphere");
this.Physics.Shapes.Add(this);
var localScale = transform.localScale;
var sphereBox = new Box(localScale.x,localScale.y,localScale.z);
if (this.isStatic)
{
this.AddStatic(sphereBox);
}
else
{
sphereBox.ComputeInertia(0.5f, out var inertia);
this.AddDynamic(sphereBox,inertia);
}
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2f56304910dd4846981c5f978f90ebf6
timeCreated: 1706690344

View File

@@ -0,0 +1,24 @@
using BepuPhysics.Collidables;
using UnityEngine;
namespace Plugins.JNGame.BepuPhysics.Components
{
public class BPhysicsSphere : BPhysicsBase
{
void Awake()
{
if (this.Physics == null) return;
Debug.Log("BPhysicsSphere");
this.Physics.Shapes.Add(this);
var sphereShape = new Sphere(transform.localScale.x / 2);
sphereShape.ComputeInertia(0.5f, out var sphereInertia);
this.AddDynamic(sphereShape,sphereInertia);
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 98c11bfd0d424f98a6634403fca61c34
timeCreated: 1706686910

View File

@@ -0,0 +1,8 @@
namespace Plugins.JNGame.BepuPhysics.Components
{
public enum BShape
{
/// <summary> Sphere shape type </summary>
Sphere = 1,
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 499b044e9991435ab5054521c2833c00
timeCreated: 1706686981

View File

@@ -0,0 +1,46 @@
using System.Collections.Generic;
using BepuPhysics;
using BepuPhysics.Collidables;
using BepuUtilities;
using BepuUtilities.Memory;
using Plugins.JNGame.BepuPhysics.Components;
using Plugins.JNGame.BepuPhysics.Utilities;
using UnityEngine;
using Vector3 = System.Numerics.Vector3;
namespace Plugins.JNGame.BepuPhysics
{
public class JNBepuPhysics
{
public static Dictionary<int,JNBepuPhysics> Physics = new();
private UnityEngine.Vector3 _gravity = new (0,10,0);
public Simulation Simulation { get; protected set; }
public BufferPool BufferPool { get; private set; }
public List<BPhysicsBase> Shapes = new();
public JNBepuPhysics(int index = 0)
{
Debug.Log($"初始化物理引擎");
Physics[index] = this;
BufferPool = new BufferPool();
Simulation = Simulation.Create(BufferPool,new JNNarrowPhaseCallbacks(),new JNPoseIntegratorCallbacks(new Vector3(_gravity.x, -_gravity.y, _gravity.z)),new PositionFirstTimestepper());
}
//更新
public void OnUpdate(float dt)
{
Simulation.Timestep(dt);
Shapes.ForEach(shapes =>
{
shapes.OnPhysicsUpdate(dt);
});
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 99bf23b7fe9748f1a3e20d10104d3d85
timeCreated: 1706683683

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7c60528953194e20af106b83b9e746de
timeCreated: 1706683642

View File

@@ -0,0 +1,134 @@
using System;
using BepuPhysics;
using BepuPhysics.Collidables;
using BepuPhysics.CollisionDetection;
using BepuPhysics.Constraints;
using System.Runtime.CompilerServices;
using System.Numerics;
using BepuUtilities;
namespace Plugins.JNGame.BepuPhysics.Utilities
{
public struct JNPoseIntegratorCallbacks : IPoseIntegratorCallbacks
{
/// <summary>
/// Gravity to apply to dynamic bodies in the simulation.
/// </summary>
public Vector3 Gravity;
/// <summary>
/// Fraction of dynamic body linear velocity to remove per unit of time. Values range from 0 to 1. 0 is fully undamped, while values very close to 1 will remove most velocity.
/// </summary>
public float LinearDamping;
/// <summary>
/// Fraction of dynamic body angular velocity to remove per unit of time. Values range from 0 to 1. 0 is fully undamped, while values very close to 1 will remove most velocity.
/// </summary>
public float AngularDamping;
Vector3 gravityDt;
float linearDampingDt;
float angularDampingDt;
public AngularIntegrationMode AngularIntegrationMode => AngularIntegrationMode.Nonconserving;
public void Initialize(Simulation simulation)
{
//In this demo, we don't need to initialize anything.
//If you had a simulation with per body gravity stored in a CollidableProperty<T> or something similar, having the simulation provided in a callback can be helpful.
}
/// <summary>
/// Creates a new set of simple callbacks for the demos.
/// </summary>
/// <param name="gravity">Gravity to apply to dynamic bodies in the simulation.</param>
/// <param name="linearDamping">Fraction of dynamic body linear velocity to remove per unit of time. Values range from 0 to 1. 0 is fully undamped, while values very close to 1 will remove most velocity.</param>
/// <param name="angularDamping">Fraction of dynamic body angular velocity to remove per unit of time. Values range from 0 to 1. 0 is fully undamped, while values very close to 1 will remove most velocity.</param>
public JNPoseIntegratorCallbacks(Vector3 gravity, float linearDamping = .03f, float angularDamping = .03f) : this()
{
Gravity = gravity;
LinearDamping = linearDamping;
AngularDamping = angularDamping;
}
public void PrepareForIntegration(float dt)
{
//No reason to recalculate gravity * dt for every body; just cache it ahead of time.
gravityDt = Gravity * dt;
//Since these callbacks don't use per-body damping values, we can precalculate everything.
linearDampingDt = MathF.Pow(MathHelper.Clamp(1 - LinearDamping, 0, 1), dt);
angularDampingDt = MathF.Pow(MathHelper.Clamp(1 - AngularDamping, 0, 1), dt);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void IntegrateVelocity(int bodyIndex, in RigidPose pose, in BodyInertia localInertia, int workerIndex, ref BodyVelocity velocity)
{
//Note that we avoid accelerating kinematics. Kinematics are any body with an inverse mass of zero (so a mass of ~infinity). No force can move them.
if (localInertia.InverseMass > 0)
{
velocity.Linear = (velocity.Linear + gravityDt) * linearDampingDt;
velocity.Angular = velocity.Angular * angularDampingDt;
}
//Implementation sidenote: Why aren't kinematics all bundled together separately from dynamics to avoid this per-body condition?
//Because kinematics can have a velocity- that is what distinguishes them from a static object. The solver must read velocities of all bodies involved in a constraint.
//Under ideal conditions, those bodies will be near in memory to increase the chances of a cache hit. If kinematics are separately bundled, the the number of cache
//misses necessarily increases. Slowing down the solver in order to speed up the pose integrator is a really, really bad trade, especially when the benefit is a few ALU ops.
//Note that you CAN technically modify the pose in IntegrateVelocity by directly accessing it through the Simulation.Bodies.ActiveSet.Poses, it just requires a little care and isn't directly exposed.
//If the PositionFirstTimestepper is being used, then the pose integrator has already integrated the pose.
//If the PositionLastTimestepper or SubsteppingTimestepper are in use, the pose has not yet been integrated.
//If your pose modification depends on the order of integration, you'll want to take this into account.
//This is also a handy spot to implement things like position dependent gravity or per-body damping.
}
}
public struct JNNarrowPhaseCallbacks : INarrowPhaseCallbacks
{
public SpringSettings ContactSpringiness;
public void Initialize(Simulation simulation)
{
//Use a default if the springiness value wasn't initialized.
if (ContactSpringiness.AngularFrequency == 0 && ContactSpringiness.TwiceDampingRatio == 0)
ContactSpringiness = new SpringSettings(30, 1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool AllowContactGeneration(int workerIndex, CollidableReference a, CollidableReference b)
{
//While the engine won't even try creating pairs between statics at all, it will ask about kinematic-kinematic pairs.
//Those pairs cannot emit constraints since both involved bodies have infinite inertia. Since most of the demos don't need
//to collect information about kinematic-kinematic pairs, we'll require that at least one of the bodies needs to be dynamic.
return a.Mobility == CollidableMobility.Dynamic || b.Mobility == CollidableMobility.Dynamic;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool AllowContactGeneration(int workerIndex, CollidablePair pair, int childIndexA, int childIndexB)
{
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool ConfigureContactManifold<TManifold>(int workerIndex, CollidablePair pair,
ref TManifold manifold, out PairMaterialProperties pairMaterial)
where TManifold : struct, IContactManifold<TManifold>
{
pairMaterial.FrictionCoefficient = 1f;
pairMaterial.MaximumRecoveryVelocity = 2f;
pairMaterial.SpringSettings = ContactSpringiness;
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool ConfigureContactManifold(int workerIndex, CollidablePair pair, int childIndexA, int childIndexB,
ref ConvexContactManifold manifold)
{
return true;
}
public void Dispose()
{
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 12d59c2959b546898001fd2ee9c2533d
timeCreated: 1706683943

View File

@@ -80,7 +80,7 @@ namespace Plugins.JNGame.Sync.Frame
public override Task OnInit()
{
Physics.simulationMode = SimulationMode.Script;
Physics.autoSimulation = false;
Physics.autoSyncTransforms = false;
this.OnReset();
return Task.CompletedTask;
@@ -110,6 +110,7 @@ namespace Plugins.JNGame.Sync.Frame
this._nLocalRunFrame = 0;
this.dtTotal = 0;
this.dtInputTotal = 0;
this._isRequestServerData = false;
Physics.SyncTransforms();
EventDispatcher.Event.Dispatch(JNSyncFrameEvent.CREATE);

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: be2eae9924066194f8328fd4f593a63a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -42,7 +42,7 @@ namespace Plugins.JNGame.Util
public async UniTask<T> Post<T,TA>(string url,TA data)
{
var request = UnityWebRequest.PostWwwForm($"{this._config.BaseURL}/{url}",JsonConvert.SerializeObject(data));
var request = UnityWebRequest.Post($"{this._config.BaseURL}/{url}",JsonConvert.SerializeObject(data));
return JsonConvert.DeserializeObject<T>((await request.SendWebRequest()).downloadHandler.text);
}