A game about forced loneliness, made by TACStudios
1using System;
2using Unity.Jobs.LowLevel.Unsafe;
3using Unity.Collections.LowLevel.Unsafe;
4using Unity.Collections;
5using System.Diagnostics;
6using Unity.Burst;
7
8namespace Unity.Jobs
9{
10 /// <summary>
11 /// Job type allowing for data to be operated on in parallel batches.
12 /// </summary>
13 /// <remarks>
14 /// When scheduling an IJobParallelForBatch job the number of elements to work on is specified along with a batch size. Jobs will then run in parallel
15 /// invoking Execute at a particular 'startIndex' of your working set and for a specified 'count' number of elements.
16 /// </remarks>
17 [JobProducerType(typeof(IJobParallelForBatchExtensions.JobParallelForBatchProducer<>))]
18 public interface IJobParallelForBatch
19 {
20 /// <summary>
21 /// Function operation on a "batch" of data contained within the job.
22 /// </summary>
23 /// <param name="startIndex">Starting index of job data to safely access.</param>
24 /// <param name="count">Number of elements to operate on in the batch.</param>
25 void Execute(int startIndex, int count);
26 }
27
28 /// <summary>
29 /// Extension class for the IJobParallelForBatch job type providing custom overloads for scheduling and running.
30 /// </summary>
31 public static class IJobParallelForBatchExtensions
32 {
33 internal struct JobParallelForBatchProducer<T> where T : struct, IJobParallelForBatch
34 {
35 internal static readonly SharedStatic<IntPtr> jobReflectionData = SharedStatic<IntPtr>.GetOrCreate<JobParallelForBatchProducer<T>>();
36
37 [BurstDiscard]
38 internal static void Initialize()
39 {
40 if (jobReflectionData.Data == IntPtr.Zero)
41 jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(T), (ExecuteJobFunction)Execute);
42 }
43
44 internal delegate void ExecuteJobFunction(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex);
45 public unsafe static void Execute(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex)
46 {
47 while (true)
48 {
49 if (!JobsUtility.GetWorkStealingRange(
50 ref ranges,
51 jobIndex, out int begin, out int end))
52 return;
53
54#if ENABLE_UNITY_COLLECTIONS_CHECKS
55 JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), begin, end - begin);
56#endif
57
58 jobData.Execute(begin, end - begin);
59 }
60 }
61 }
62
63 /// <summary>
64 /// 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.
65 /// </summary>
66 /// <typeparam name="T"></typeparam>
67 /// <remarks>
68 /// 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.
69 ///
70 /// __Note__: While the Jobs package code generator handles this automatically for all closed job types, you must register those with generic arguments (like IJobParallelForBatch&lt;MyJobType&lt;T&gt;&gt;) manually for each specialization with [[Unity.Jobs.RegisterGenericJobTypeAttribute]].
71 /// </remarks>
72 public static void EarlyJobInit<T>()
73 where T : struct, IJobParallelForBatch
74 {
75 JobParallelForBatchProducer<T>.Initialize();
76 }
77
78 static IntPtr GetReflectionData<T>()
79 where T : struct, IJobParallelForBatch
80 {
81 JobParallelForBatchProducer<T>.Initialize();
82 var reflectionData = JobParallelForBatchProducer<T>.jobReflectionData.Data;
83 CollectionHelper.CheckReflectionDataCorrect<T>(reflectionData);
84 return reflectionData;
85 }
86
87 /// <summary>
88 /// Schedules a job that will execute the parallel batch job for all `arrayLength` elements in batches of `indicesPerJobCount`.
89 /// The Execute() method for Job T will be provided the start index and number of elements to safely operate on.
90 /// In cases where `indicesPerJobCount` is not a multiple of `arrayLength`, the `count` provided to the Execute method of Job T will be smaller than the `indicesPerJobCount` specified here.
91 /// </summary>
92 /// <param name="jobData">The job and data to schedule.</param>
93 /// <param name="arrayLength">Total number of elements to consider when batching.</param>
94 /// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch.</param>
95 /// <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>
96 /// <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>
97 /// <typeparam name="T">Job type</typeparam>
98 public static unsafe JobHandle Schedule<T>(this T jobData, int arrayLength, int indicesPerJobCount,
99 JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForBatch
100 {
101 var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependsOn, ScheduleMode.Single);
102 return JobsUtility.ScheduleParallelFor(ref scheduleParams, arrayLength, indicesPerJobCount);
103 }
104
105 /// <summary>
106 /// Schedules a job that will execute the parallel batch job for all `arrayLength` elements in batches of `indicesPerJobCount`.
107 /// The Execute() method for Job T will be provided the start index and number of elements to safely operate on.
108 /// In cases where `indicesPerJobCount` is not a multiple of `arrayLength`, the `count` provided to the Execute method of Job T will be smaller than the `indicesPerJobCount` specified here.
109 /// </summary>
110 /// <param name="jobData">The job and data to schedule. In this variant, the jobData is
111 /// passed by reference, which may be necessary for unusually large job structs.</param>
112 /// <param name="arrayLength">Total number of elements to consider when batching.</param>
113 /// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch.</param>
114 /// <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>
115 /// <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>
116 /// <typeparam name="T">Job type</typeparam>
117 public static unsafe JobHandle ScheduleByRef<T>(this ref T jobData, int arrayLength, int indicesPerJobCount,
118 JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForBatch
119 {
120 var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependsOn, ScheduleMode.Single);
121 return JobsUtility.ScheduleParallelFor(ref scheduleParams, arrayLength, indicesPerJobCount);
122 }
123
124 /// <summary>
125 /// Schedules a job that will execute the parallel batch job for all `arrayLength` elements in batches of `indicesPerJobCount`.
126 /// The Execute() method for Job T will be provided the start index and number of elements to safely operate on.
127 /// In cases where `indicesPerJobCount` is not a multiple of `arrayLength`, the `count` provided to the Execute method of Job T will be smaller than the `indicesPerJobCount` specified here.
128 /// </summary>
129 /// <param name="jobData">The job and data to schedule.</param>
130 /// <param name="arrayLength">Total number of elements to consider when batching.</param>
131 /// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch.</param>
132 /// <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>
133 /// <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>
134 /// <typeparam name="T">Job type</typeparam>
135 public static unsafe JobHandle ScheduleParallel<T>(this T jobData, int arrayLength, int indicesPerJobCount,
136 JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForBatch
137 {
138 var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependsOn, ScheduleMode.Parallel);
139 return JobsUtility.ScheduleParallelFor(ref scheduleParams, arrayLength, indicesPerJobCount);
140 }
141
142 /// <summary>
143 /// Schedules a job that will execute the parallel batch job for all `arrayLength` elements in batches of `indicesPerJobCount`.
144 /// The Execute() method for Job T will be provided the start index and number of elements to safely operate on.
145 /// In cases where `indicesPerJobCount` is not a multiple of `arrayLength`, the `count` provided to the Execute method of Job T will be smaller than the `indicesPerJobCount` specified here.
146 /// </summary>
147 /// <param name="jobData">The job and data to schedule. In this variant, the jobData is
148 /// passed by reference, which may be necessary for unusually large job structs.</param>
149 /// <param name="arrayLength">Total number of elements to consider when batching.</param>
150 /// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch.</param>
151 /// <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>
152 /// <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>
153 /// <typeparam name="T">Job type</typeparam>
154 public static unsafe JobHandle ScheduleParallelByRef<T>(this ref T jobData, int arrayLength, int indicesPerJobCount,
155 JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForBatch
156 {
157 var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependsOn, ScheduleMode.Parallel);
158 return JobsUtility.ScheduleParallelFor(ref scheduleParams, arrayLength, indicesPerJobCount);
159 }
160
161 /// <summary>
162 /// Schedules a job that will execute the parallel batch job for all `arrayLength` elements in batches of `indicesPerJobCount`.
163 /// The Execute() method for Job T will be provided the start index and number of elements to safely operate on.
164 /// In cases where `indicesPerJobCount` is not a multiple of `arrayLength`, the `count` provided to the Execute method of Job T will be smaller than the `indicesPerJobCount` specified here.
165 /// </summary>
166 /// <param name="jobData">The job and data to schedule.</param>
167 /// <param name="arrayLength">Total number of elements to consider when batching.</param>
168 /// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch.</param>
169 /// <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>
170 /// <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>
171 /// <typeparam name="T">Job type</typeparam>
172 public static unsafe JobHandle ScheduleBatch<T>(this T jobData, int arrayLength, int indicesPerJobCount,
173 JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForBatch
174 {
175 return ScheduleParallel(jobData, arrayLength, indicesPerJobCount, dependsOn);
176 }
177
178 /// <summary>
179 /// Schedules a job that will execute the parallel batch job for all `arrayLength` elements in batches of `indicesPerJobCount`.
180 /// The Execute() method for Job T will be provided the start index and number of elements to safely operate on.
181 /// In cases where `indicesPerJobCount` is not a multiple of `arrayLength`, the `count` provided to the Execute method of Job T will be smaller than the `indicesPerJobCount` specified here.
182 /// </summary>
183 /// <param name="jobData">The job and data to schedule. In this variant, the jobData is
184 /// passed by reference, which may be necessary for unusually large job structs.</param>
185 /// <param name="arrayLength">Total number of elements to consider when batching.</param>
186 /// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch.</param>
187 /// <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>
188 /// <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>
189 /// <typeparam name="T">Job type</typeparam>
190 public static unsafe JobHandle ScheduleBatchByRef<T>(this ref T jobData, int arrayLength, int indicesPerJobCount,
191 JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForBatch
192 {
193 return ScheduleParallelByRef(ref jobData, arrayLength, indicesPerJobCount, dependsOn);
194 }
195
196 /// <summary>
197 /// Executes the parallel batch job but on the main thread. See IJobParallelForBatchExtensions.Schedule for more information on how appending is performed.
198 /// </summary>
199 /// <param name="jobData">The job and data to schedule.</param>
200 /// <param name="arrayLength">Total number of elements to consider when batching.</param>
201 /// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch. This argument is ignored when using .Run()</param>
202 /// <typeparam name="T">Job type</typeparam>
203 /// <remarks>
204 /// Unlike Schedule, since the job is running on the main thread no parallelization occurs and thus no `indicesPerJobCount` batch size is required to be specified.
205 /// </remarks>
206 public static unsafe void Run<T>(this T jobData, int arrayLength, int indicesPerJobCount) where T : struct, IJobParallelForBatch
207 {
208 var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), new JobHandle(), ScheduleMode.Run);
209 JobsUtility.ScheduleParallelFor(ref scheduleParams, arrayLength, arrayLength);
210 }
211
212 /// <summary>
213 /// Executes the parallel batch job but on the main thread. See IJobParallelForBatchExtensions.Schedule for more information on how appending is performed.
214 /// </summary>
215 /// <param name="jobData">The job and data to schedule. In this variant, the jobData is
216 /// passed by reference, which may be necessary for unusually large job structs.</param>
217 /// <param name="arrayLength">Total number of elements to consider when batching.</param>
218 /// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch. This argument is ignored when using .RunByRef()</param>
219 /// <typeparam name="T">Job type</typeparam>
220 public static unsafe void RunByRef<T>(this ref T jobData, int arrayLength, int indicesPerJobCount) where T : struct, IJobParallelForBatch
221 {
222 var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), new JobHandle(), ScheduleMode.Run);
223 JobsUtility.ScheduleParallelFor(ref scheduleParams, arrayLength, arrayLength);
224 }
225
226 /// <summary>
227 /// Executes the parallel batch job but on the main thread. See IJobParallelForBatchExtensions.ScheduleBatch for more information on how appending is performed.
228 /// </summary>
229 /// <param name="jobData">The job and data to schedule.</param>
230 /// <param name="arrayLength">Total number of elements to consider when batching.</param>
231 /// <typeparam name="T">Job type</typeparam>
232 /// <remarks>
233 /// Unlike ScheduleBatch, since the job is running on the main thread no parallelization occurs and thus no `indicesPerJobCount` batch size is required to be specified.
234 /// </remarks>
235 public static unsafe void RunBatch<T>(this T jobData, int arrayLength) where T : struct, IJobParallelForBatch
236 {
237 Run(jobData, arrayLength, arrayLength);
238 }
239
240 /// <summary>
241 /// Executes the parallel batch job but on the main thread. See IJobParallelForBatchExtensions.ScheduleBatch for more information on how appending is performed.
242 /// </summary>
243 /// <param name="jobData">The job and data to schedule. In this variant, the jobData is
244 /// passed by reference, which may be necessary for unusually large job structs.</param>
245 /// <param name="arrayLength">Total number of elements to consider when batching.</param>
246 /// <typeparam name="T">Job type</typeparam>
247 public static unsafe void RunBatchByRef<T>(this ref T jobData, int arrayLength) where T : struct, IJobParallelForBatch
248 {
249 RunByRef(ref jobData, arrayLength, arrayLength);
250 }
251 }
252}