#if !UNITY_JOBS_LESS_THAN_0_7 using System; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Jobs.LowLevel.Unsafe; using UnityEngine.Scripting; using System.Diagnostics; using Unity.Burst; namespace Unity.Jobs { /// /// A replacement for IJobParallelFor when the number of work items is not known at Schedule time. /// IJobParallelForDefer lets you calculate the number of iterations to perform in a job that must execute before the IJobParallelForDefer job. /// /// When Scheduling the job's Execute(int index) method will be invoked on multiple worker threads in parallel to each other. /// Execute(int index) will be executed once for each index from 0 to the provided length. Each iteration must be independent from other iterations (The safety system enforces this rule for you). The indices have no guaranteed order and are executed on multiple cores in parallel. /// Unity automatically splits the work into chunks of no less than the provided batchSize, and schedules an appropriate number of jobs based on the number of worker threads, the length of the array and the batch size. /// Batch size should generally be chosen depending on the amount of work performed in the job. A simple job, for example adding a couple of float3 to each other should probably have a batch size of 32 to 128. However if the work performed is very expensive then it is best to use a small batch size, for expensive work a batch size of 1 is totally fine. IJobParallelFor performs work stealing using atomic operations. Batch sizes can be small but they are not for free. /// The returned JobHandle can be used to ensure that the job has completed. Or it can be passed to other jobs as a dependency, thus ensuring the jobs are executed one after another on the worker threads. /// [JobProducerType(typeof(IJobParallelForDeferExtensions.JobParallelForDeferProducer<>))] public interface IJobParallelForDefer { /// /// Implement this method to perform work against a specific iteration index. /// /// The index of the Parallel for loop at which to perform work. void Execute(int index); } public static class IJobParallelForDeferExtensions { internal struct JobParallelForDeferProducer where T : struct, IJobParallelForDefer { internal static readonly SharedStatic jobReflectionData = SharedStatic.GetOrCreate>(); [Preserve] internal static void Initialize() { if (jobReflectionData.Data == IntPtr.Zero) jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(T), (ExecuteJobFunction)Execute); } public delegate void ExecuteJobFunction(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); public unsafe static void Execute(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) { while (true) { if (!JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out int begin, out int end)) break; #if ENABLE_UNITY_COLLECTIONS_CHECKS JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), begin, end - begin); #endif for (var i = begin; i < end; ++i) jobData.Execute(i); } } } /// /// This method is only to be called by automatically generated setup code. /// /// public static void EarlyJobInit() where T : struct, IJobParallelForDefer { JobParallelForDeferProducer.Initialize(); } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private static void CheckReflectionDataCorrect(IntPtr reflectionData) { if (reflectionData == IntPtr.Zero) throw new InvalidOperationException("Reflection data was not set up by a call to Initialize()"); } /// /// Schedule the job for execution on worker threads. /// list.Length is used as the iteration count. /// Note that it is required to embed the list on the job struct as well. /// /// The job and data to schedule. /// list.Length is used as the iteration count. /// 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. /// 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. /// JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread. public static unsafe JobHandle Schedule(this T jobData, NativeList list, int innerloopBatchCount, JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForDefer where U : unmanaged { void* atomicSafetyHandlePtr = null; // Calculate the deferred atomic safety handle before constructing JobScheduleParameters so // DOTS Runtime can validate the deferred list statically similar to the reflection based // validation in Big Unity. #if ENABLE_UNITY_COLLECTIONS_CHECKS var safety = NativeListUnsafeUtility.GetAtomicSafetyHandle(ref list); atomicSafetyHandlePtr = UnsafeUtility.AddressOf(ref safety); #endif return ScheduleInternal(ref jobData, innerloopBatchCount, NativeListUnsafeUtility.GetInternalListDataPtrUnchecked(ref list), atomicSafetyHandlePtr, dependsOn); } /// /// Schedule the job for execution on worker threads. /// list.Length is used as the iteration count. /// Note that it is required to embed the list on the job struct as well. /// /// The job and data to schedule. In this variant, the jobData is /// passed by reference, which may be necessary for unusually large job structs. /// list.Length is used as the iteration count. /// 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. /// 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. /// JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread. public static unsafe JobHandle ScheduleByRef(this ref T jobData, NativeList list, int innerloopBatchCount, JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForDefer where U : unmanaged { void* atomicSafetyHandlePtr = null; // Calculate the deferred atomic safety handle before constructing JobScheduleParameters so // DOTS Runtime can validate the deferred list statically similar to the reflection based // validation in Big Unity. #if ENABLE_UNITY_COLLECTIONS_CHECKS var safety = NativeListUnsafeUtility.GetAtomicSafetyHandle(ref list); atomicSafetyHandlePtr = UnsafeUtility.AddressOf(ref safety); #endif return ScheduleInternal(ref jobData, innerloopBatchCount, NativeListUnsafeUtility.GetInternalListDataPtrUnchecked(ref list), atomicSafetyHandlePtr, dependsOn); } /// /// Schedule the job for execution on worker threads. /// forEachCount is a pointer to the number of iterations, when dependsOn has completed. /// This API is unsafe, it is recommended to use the NativeList based Schedule method instead. /// /// The job and data to schedule. /// *forEachCount is used as the iteration count. /// 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. /// 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. /// JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread. /// /// public static unsafe JobHandle Schedule(this T jobData, int* forEachCount, int innerloopBatchCount, JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForDefer { var forEachListPtr = (byte*)forEachCount - sizeof(void*); return ScheduleInternal(ref jobData, innerloopBatchCount, forEachListPtr, null, dependsOn); } /// /// Schedule the job for execution on worker threads. /// forEachCount is a pointer to the number of iterations, when dependsOn has completed. /// This API is unsafe, it is recommended to use the NativeList based Schedule method instead. /// /// The job and data to schedule. In this variant, the jobData is /// passed by reference, which may be necessary for unusually large job structs. /// *forEachCount is used as the iteration count. /// 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. /// 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. /// JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread. /// /// public static unsafe JobHandle ScheduleByRef(this ref T jobData, int* forEachCount, int innerloopBatchCount, JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForDefer { var forEachListPtr = (byte*)forEachCount - sizeof(void*); return ScheduleInternal(ref jobData, innerloopBatchCount, forEachListPtr, null, dependsOn); } private static unsafe JobHandle ScheduleInternal(ref T jobData, int innerloopBatchCount, void* forEachListPtr, void *atomicSafetyHandlePtr, JobHandle dependsOn) where T : struct, IJobParallelForDefer { var reflectionData = JobParallelForDeferProducer.jobReflectionData.Data; CheckReflectionDataCorrect(reflectionData); var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), reflectionData, dependsOn, ScheduleMode.Parallel); return JobsUtility.ScheduleParallelForDeferArraySize(ref scheduleParams, innerloopBatchCount, forEachListPtr, atomicSafetyHandlePtr); } } } #endif