forked from stella3d/job-system-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AccelerationParallelFor.cs
96 lines (76 loc) · 2.61 KB
/
AccelerationParallelFor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using UnityEngine;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine.Jobs;
public class AccelerationParallelFor : BaseJobObjectExample
{
public Vector3 m_Acceleration = new Vector3(0.0002f, 0.0001f, 0.0002f);
public Vector3 m_AccelerationMod = new Vector3(.0001f, 0.0001f, 0.0001f);
NativeArray<Vector3> m_Velocities;
TransformAccessArray m_TransformsAccessArray;
PositionUpdateJob m_Job;
AccelerationJob m_AccelJob;
JobHandle m_PositionJobHandle;
JobHandle m_AccelJobHandle;
protected void Start()
{
m_Velocities = new NativeArray<Vector3>(m_ObjectCount, Allocator.Persistent);
m_Objects = SetupUtils.PlaceRandomCubes(m_ObjectCount, m_ObjectPlacementRadius);
for (int i = 0; i < m_ObjectCount; i++)
{
var obj = m_Objects[i];
m_Transforms[i] = obj.transform;
m_Renderers[i] = obj.GetComponent<Renderer>();
}
m_TransformsAccessArray = new TransformAccessArray(m_Transforms);
}
struct PositionUpdateJob : IJobParallelForTransform
{
[ReadOnly]
public NativeArray<Vector3> velocity; // the velocities from AccelerationJob
public float deltaTime;
public void Execute(int i, TransformAccess transform)
{
transform.position += velocity[i] * deltaTime;
}
}
struct AccelerationJob : IJobParallelFor
{
public NativeArray<Vector3> velocity;
public Vector3 acceleration;
public Vector3 accelerationMod;
public float deltaTime;
public void Execute(int i)
{
// here, i'm intentionally using the index to affect acceleration (it looks cool),
// but generating velocities probably wouldn't be tied to index normally.
velocity[i] += (acceleration + i * accelerationMod) * deltaTime;
}
}
public void Update()
{
m_AccelJob = new AccelerationJob()
{
deltaTime = Time.deltaTime,
velocity = m_Velocities,
acceleration = m_Acceleration,
accelerationMod = m_AccelerationMod
};
m_Job = new PositionUpdateJob()
{
deltaTime = Time.deltaTime,
velocity = m_Velocities,
};
m_AccelJobHandle = m_AccelJob.Schedule(m_ObjectCount, 64);
m_PositionJobHandle = m_Job.Schedule(m_TransformsAccessArray, m_AccelJobHandle);
}
public void LateUpdate()
{
m_PositionJobHandle.Complete();
}
private void OnDestroy()
{
m_Velocities.Dispose();
m_TransformsAccessArray.Dispose();
}
}