智能客服
你问我答,随时在线为你解决问题
针对使用过Burst的遗留项目,PGA内部兼容Burst语法,无需重新调整代码即可使用PGA进行优化。
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine;
using Huawei.Pga;
public class PGAScript : MonoBehaviour
{
public NativeArray<float3> InputA;
public NativeArray<float3> InputB;
public NativeArray<float> OutputJob;
public NativeArray<float> OutputDirectCall;
public static readonly int N = 1024;
void Start()
{
InputA = new NativeArray<float3>(N, Allocator.Persistent);
InputB = new NativeArray<float3>(N, Allocator.Persistent);
OutputJob = new NativeArray<float>(N, Allocator.Persistent);
OutputDirectCall = new NativeArray<float>(N, Allocator.Persistent);
// Initialize
var random = new Unity.Mathematics.Random(202411);
for (int i = 0; i < N; i++) {
InputA[i] = new float3(random.NextFloat(N), random.NextFloat(N), random.NextFloat(N));
InputB[i] = new float3(random.NextFloat(N), random.NextFloat(N), random.NextFloat(N));
}
// 1. Calculate the distance through distance-job.
var distanceJob = new DistanceJob{
VertA = InputA,
VertB = InputB,
Dist = OutputJob
};
JobHandle jobHandle = distanceJob.Schedule(N, 64);
jobHandle.Complete();
// 2. Calculate the distance through direct-call.
Utils.DirectCallDistance(InputA, InputB, OutputDirectCall);
// Log
for (int i = 0; i < N; i++) {
Debug.Log($"Distance between {InputA[i]} and {InputB[i]}, OutputJob[{i}]: {OutputJob[i]}, " +
$"OutputDirectCall[{i}]: {OutputDirectCall[i]}");
}
// Dispose
InputA.Dispose();
InputB.Dispose();
OutputJob.Dispose();
OutputDirectCall.Dispose();
}
[PgaCompile] // Required
struct DistanceJob : IJobParallelFor
{
[ReadOnly] public NativeArray<float3> VertA;
[ReadOnly] public NativeArray<float3> VertB;
public NativeArray<float> Dist;
// The [PgaCompile] attribute of the Execute method in a job can be omitted.
public void Execute(int index) {
Dist[index] = math.distance(VertA[index], VertB[index]);
}
}
[PgaCompile] // Required
struct Utils
{
[PgaCompile] // Required
public static void DirectCallDistance( // It should be a static method
NativeArray<float3> VertA,
NativeArray<float3> VertB,
NativeArray<float> Dist
) {
for (int i = 0; i < N; i++) {
Dist[i] = math.distance(VertA[i], VertB[i]);
}
}
}
}游戏接入PGA的方式是添加必要的[PgaCompile]属性。在示例代码中,对于两组输入的顶点数据InputA和InputB,分别使用了Job和DirectCall方式计算其距离(distance)。对于Job和DirectCall这两种方式,必须在包含目标函数的结构体上都打上属性标记(如示例代码中的DistanceJob和Utils)。