A game about forced loneliness, made by TACStudios
1using System;
2using Unity.Collections;
3using Unity.Collections.LowLevel.Unsafe;
4using Unity.Jobs.LowLevel.Unsafe;
5using System.Diagnostics;
6using Unity.Burst;
7
8namespace Unity.Jobs
9{
10 /// <summary>
11 /// Calculates the number of iterations to perform in a job that must execute before an IJobParallelForDefer job.
12 /// </summary>
13 /// <remarks>
14 /// A replacement for IJobParallelFor when the number of work items is not known at Schedule time.
15 ///
16 /// When Scheduling the job's Execute(int index) method will be invoked on multiple worker threads in
17 /// parallel to each other.
18 ///
19 /// Execute(int index) will be executed once for each index from 0 to the provided length. Each iteration
20 /// must be independent from other iterations and the safety system enforces this rule for you. The indices
21 /// have no guaranteed order and are executed on multiple cores in parallel.
22 ///
23 /// Unity automatically splits the work into chunks of no less than the provided batchSize, and schedules
24 /// an appropriate number of jobs based on the number of worker threads, the length of the array and the batch size.
25 ///
26 /// Choose a batch size sbased on the amount of work performed in the job. A simple job,
27 /// for example adding a couple of float3 to each other could have a batch size of 32 to 128. However,
28 /// if the work performed is very expensive then it's best to use a small batch size, such as a batch
29 /// size of 1. IJobParallelFor performs work stealing using atomic operations. Batch sizes can be
30 /// small but they aren't free.
31 ///
32 /// The returned JobHandle can be used to ensure that the job has completed. Or it can be passed to other jobs as
33 /// a dependency, ensuring that the jobs are executed one after another on the worker threads.
34 /// </remarks>
35 [JobProducerType(typeof(IJobParallelForDeferExtensions.JobParallelForDeferProducer<>))]
36 public interface IJobParallelForDefer
37 {
38 /// <summary>
39 /// Implement this method to perform work against a specific iteration index.
40 /// </summary>
41 /// <param name="index">The index of the Parallel for loop at which to perform work.</param>
42 void Execute(int index);
43 }
44
45 /// <summary>
46 /// Extension class for the IJobParallelForDefer job type providing custom overloads for scheduling and running.
47 /// </summary>
48 public static class IJobParallelForDeferExtensions
49 {
50 internal struct JobParallelForDeferProducer<T> where T : struct, IJobParallelForDefer
51 {
52 internal static readonly SharedStatic<IntPtr> jobReflectionData = SharedStatic<IntPtr>.GetOrCreate<JobParallelForDeferProducer<T>>();
53
54 [BurstDiscard]
55 internal static void Initialize()
56 {
57 if (jobReflectionData.Data == IntPtr.Zero)
58 jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(T), (ExecuteJobFunction)Execute);
59 }
60
61 public delegate void ExecuteJobFunction(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex);
62
63 public unsafe static void Execute(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex)
64 {
65 while (true)
66 {
67 if (!JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out int begin, out int end))
68 break;
69
70#if ENABLE_UNITY_COLLECTIONS_CHECKS
71 JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), begin, end - begin);
72#endif
73
74 // Cache the end value to make it super obvious to the
75 // compiler that `end` will never change during the loops
76 // iteration.
77 var endThatCompilerCanSeeWillNeverChange = end;
78 for (var i = begin; i < endThatCompilerCanSeeWillNeverChange; ++i)
79 jobData.Execute(i);
80 }
81 }
82 }
83
84 /// <summary>
85 /// Gathers and caches reflection data for the internal job system's managed bindings. Unity is responsible for calling this method - don't call it yourself.
86 /// </summary>
87 /// <typeparam name="T"></typeparam>
88 /// <remarks>
89 /// When the Jobs package is included in the project, Unity generates code to call EarlyJobInit at startup. This allows Burst compiled code to schedule jobs because the reflection part of initialization, which is not compatible with burst compiler constraints, has already happened in EarlyJobInit.
90 ///
91 /// __Note__: While the Jobs package code generator handles this automatically for all closed job types, you must register those with generic arguments (like IJobParallelForDefer&lt;MyJobType&lt;T&gt;&gt;) manually for each specialization with [[Unity.Jobs.RegisterGenericJobTypeAttribute]].
92 /// </remarks>
93 public static void EarlyJobInit<T>()
94 where T : struct, IJobParallelForDefer
95 {
96 JobParallelForDeferProducer<T>.Initialize();
97 }
98
99 /// <summary>
100 /// Schedule the job for execution on worker threads.
101 /// list.Length is used as the iteration count.
102 /// Note that it is required to embed the list on the job struct as well.
103 /// </summary>
104 /// <param name="jobData">The job and data to schedule.</param>
105 /// <param name="list">list.Length is used as the iteration count.</param>
106 /// <param name="innerloopBatchCount">Granularity in which workstealing is performed. A value of 32, means the job queue will steal 32 iterations and then perform them in an efficient inner loop.</param>
107 /// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
108 /// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
109 /// <typeparam name="T">Job type</typeparam>
110 /// <typeparam name="U">List element type</typeparam>
111 public static unsafe JobHandle Schedule<T, U>(this T jobData, NativeList<U> list, int innerloopBatchCount,
112 JobHandle dependsOn = new JobHandle())
113 where T : struct, IJobParallelForDefer
114 where U : unmanaged
115 {
116 void* atomicSafetyHandlePtr = null;
117 // Calculate the deferred atomic safety handle before constructing JobScheduleParameters so
118 // DOTS Runtime can validate the deferred list statically similar to the reflection based
119 // validation in Big Unity.
120#if ENABLE_UNITY_COLLECTIONS_CHECKS
121 var safety = NativeListUnsafeUtility.GetAtomicSafetyHandle(ref list);
122 atomicSafetyHandlePtr = UnsafeUtility.AddressOf(ref safety);
123#endif
124 return ScheduleInternal(ref jobData, innerloopBatchCount,
125 NativeListUnsafeUtility.GetInternalListDataPtrUnchecked(ref list),
126 atomicSafetyHandlePtr, dependsOn);
127 }
128
129 /// <summary>
130 /// Schedule the job for execution on worker threads.
131 /// list.Length is used as the iteration count.
132 /// Note that it is required to embed the list on the job struct as well.
133 /// </summary>
134 /// <param name="jobData">The job and data to schedule. In this variant, the jobData is
135 /// passed by reference, which may be necessary for unusually large job structs.</param>
136 /// <param name="list">list.Length is used as the iteration count.</param>
137 /// <param name="innerloopBatchCount">Granularity in which workstealing is performed. A value of 32, means the job queue will steal 32 iterations and then perform them in an efficient inner loop.</param>
138 /// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
139 /// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
140 /// <typeparam name="T">Job type</typeparam>
141 /// <typeparam name="U">List element type</typeparam>
142 public static unsafe JobHandle ScheduleByRef<T, U>(this ref T jobData, NativeList<U> list, int innerloopBatchCount,
143 JobHandle dependsOn = new JobHandle())
144 where T : struct, IJobParallelForDefer
145 where U : unmanaged
146 {
147 void* atomicSafetyHandlePtr = null;
148 // Calculate the deferred atomic safety handle before constructing JobScheduleParameters so
149 // DOTS Runtime can validate the deferred list statically similar to the reflection based
150 // validation in Big Unity.
151#if ENABLE_UNITY_COLLECTIONS_CHECKS
152 var safety = NativeListUnsafeUtility.GetAtomicSafetyHandle(ref list);
153 atomicSafetyHandlePtr = UnsafeUtility.AddressOf(ref safety);
154#endif
155 return ScheduleInternal(ref jobData, innerloopBatchCount,
156 NativeListUnsafeUtility.GetInternalListDataPtrUnchecked(ref list),
157 atomicSafetyHandlePtr, dependsOn);
158 }
159
160 /// <summary>
161 /// Schedule the job for execution on worker threads.
162 /// forEachCount is a pointer to the number of iterations, when dependsOn has completed.
163 /// This API is unsafe, it is recommended to use the NativeList based Schedule method instead.
164 /// </summary>
165 /// <param name="jobData">The job and data to schedule.</param>
166 /// <param name="forEachCount">*forEachCount is used as the iteration count.</param>
167 /// <param name="innerloopBatchCount">Granularity in which workstealing is performed. A value of 32, means the job queue will steal 32 iterations and then perform them in an efficient inner loop.</param>
168 /// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
169 /// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
170 /// <typeparam name="T">Job type</typeparam>
171 /// <returns></returns>
172 public static unsafe JobHandle Schedule<T>(this T jobData, int* forEachCount, int innerloopBatchCount,
173 JobHandle dependsOn = new JobHandle())
174 where T : struct, IJobParallelForDefer
175 {
176 var forEachListPtr = (byte*)forEachCount - sizeof(void*);
177 return ScheduleInternal(ref jobData, innerloopBatchCount, forEachListPtr, null, dependsOn);
178 }
179
180 /// <summary>
181 /// Schedule the job for execution on worker threads.
182 /// forEachCount is a pointer to the number of iterations, when dependsOn has completed.
183 /// This API is unsafe, it is recommended to use the NativeList based Schedule method instead.
184 /// </summary>
185 /// <param name="jobData">The job and data to schedule. In this variant, the jobData is
186 /// passed by reference, which may be necessary for unusually large job structs.</param>
187 /// <param name="forEachCount">*forEachCount is used as the iteration count.</param>
188 /// <param name="innerloopBatchCount">Granularity in which workstealing is performed. A value of 32, means the job queue will steal 32 iterations and then perform them in an efficient inner loop.</param>
189 /// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
190 /// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
191 /// <typeparam name="T"></typeparam>
192 /// <returns></returns>
193 public static unsafe JobHandle ScheduleByRef<T>(this ref T jobData, int* forEachCount, int innerloopBatchCount,
194 JobHandle dependsOn = new JobHandle())
195 where T : struct, IJobParallelForDefer
196 {
197 var forEachListPtr = (byte*)forEachCount - sizeof(void*);
198 return ScheduleInternal(ref jobData, innerloopBatchCount, forEachListPtr, null, dependsOn);
199 }
200
201 private static unsafe JobHandle ScheduleInternal<T>(ref T jobData,
202 int innerloopBatchCount,
203 void* forEachListPtr,
204 void *atomicSafetyHandlePtr,
205 JobHandle dependsOn) where T : struct, IJobParallelForDefer
206 {
207 JobParallelForDeferProducer<T>.Initialize();
208 var reflectionData = JobParallelForDeferProducer<T>.jobReflectionData.Data;
209 CollectionHelper.CheckReflectionDataCorrect<T>(reflectionData);
210 var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), reflectionData, dependsOn, ScheduleMode.Parallel);
211 return JobsUtility.ScheduleParallelForDeferArraySize(ref scheduleParams, innerloopBatchCount, forEachListPtr, atomicSafetyHandlePtr);
212 }
213 }
214}