首页 > 其他分享 >JobSystem使用范例二:动态添加移除Transform单位,寻找最近目标

JobSystem使用范例二:动态添加移除Transform单位,寻找最近目标

时间:2024-09-04 09:36:55浏览次数:13  
标签:NativeList using int void 移除 Transform JobSystem new public

如何试用 TransformAccessArray | 添加/移除 Transform 到 TransformAccessArray中执行   24gevbpq93uREUwegh9u32ibqae9uyshdfbwep23ugo99832ewuTW$Ewwt    以下是寻找最近目标的示例。

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Jobs;
using Unity.Mathematics;
using Unity.Jobs;
using Unity.Collections;
using Unity.Profiling;

public class FindNearestTargets : MonoBehaviour
{
    public List<Transform>
        troopsToAdd = new List<Transform>() ,
        troopsToRemove = new List<Transform>() ,
        targetsToAdd = new List<Transform>() ,
        targetsToRemove = new List<Transform>();
    TransformAccessArray _troopsDataAccess, _targetsDataAccess;
    NativeList<float3> _troopPositions, _targetPositions;
    NativeList<int> _nearestTargetIndices;
    public JobHandle Dependency;
    ProfilerMarker
        ___proc_results = new ProfilerMarker("process job results") ,
        ___maintain_data_access = new ProfilerMarker("maintan data access") ,
        ___schedule_new = new ProfilerMarker("schedule jobs") ,
        ___schedule = new ProfilerMarker("schedule calls");
    const float k_tick_rate = 0.4f;// tick every 0.4s
    void OnEnable ()
    {
        InvokeRepeating( nameof(Tick) , k_tick_rate , k_tick_rate );
        _troopsDataAccess = new TransformAccessArray( 32 );
        _targetsDataAccess = new TransformAccessArray( 32 );
        _troopPositions = new NativeList<float3>( 32 , Allocator.Persistent );
        _targetPositions = new NativeList<float3>( 32 , Allocator.Persistent );
        _nearestTargetIndices = new NativeList<int>( 32 , Allocator.Persistent );
    }
    void OnDisable ()
    {
        CancelInvoke();
        Dependency.Complete();
        if( _troopsDataAccess.isCreated ) _troopsDataAccess.Dispose();
        if( _targetsDataAccess.isCreated ) _targetsDataAccess.Dispose();
        if( _troopPositions.IsCreated ) _troopPositions.Dispose();
        if( _targetPositions.IsCreated ) _targetPositions.Dispose();
        if( _nearestTargetIndices.IsCreated ) _nearestTargetIndices.Dispose();
    }
    #if UNITY_EDITOR
    void OnDrawGizmos ()
    {
        if( !Application.isPlaying ) return;
        Gizmos.color = Color.blue;
        for( int i=_troopsDataAccess.length-1 ; i!=-1 ; i-- )
            Gizmos.DrawWireCube( _troopsDataAccess[i].position , Vector3.one );
        Gizmos.color = Color.red;
        for( int i=_targetsDataAccess.length-1 ; i!=-1 ; i-- )
            Gizmos.DrawWireSphere( _targetsDataAccess[i].position , 1f );
    }
    #endif
    void Tick ()
    {
        Dependency.Complete();

        // process results
        ___proc_results.Begin();
        {
            // don't do this like I'm doing here, it's just for quick & dirty viz
            // i.e. avoid reading/writing from native collection outside jobs, it very slow (especially in big loops)

            int numResults = _nearestTargetIndices.Length;
            for( int i=0 ; i<numResults ; i++ )
            {
                int nearestTargetIndex = _nearestTargetIndices[i];
                Debug.DrawLine( _troopPositions[i]  , _targetPositions[nearestTargetIndex] , Color.yellow , k_tick_rate );
                // Transform troop = _troopsDataAccess[i];
                // Transform target = _targetsDataAccess[nearestTargetIndex];
            }
        }
        ___proc_results.End();

        // TransformAccessArray maintainance
        ___maintain_data_access.Begin();
        {
            int numTroopsToRemove = troopsToRemove.Count;
            if( numTroopsToRemove!=0 )
            {
                for( int i=0 ; i<numTroopsToRemove ; i++ )
                {
                    Transform next = troopsToRemove[i];
                    if( next!=null )
                    for( int k=_troopsDataAccess.length-1 ; k!=-1 ; k-- )
                    {
                        if( _troopsDataAccess[k]==next )
                        {
                            _troopsDataAccess.RemoveAtSwapBack( k );
                            break;
                        }
                    }
                }
                troopsToRemove.Clear();
            }
            
            int numTroopsToAdd = troopsToAdd.Count;
            if( numTroopsToAdd!=0 )
            {
                for( int i=0 ; i<numTroopsToAdd ; i++ )
                    if( troopsToAdd[i]!=null )
                        _troopsDataAccess.Add( troopsToAdd[i] );
                troopsToAdd.Clear();
            }

            int numTargetsToRemove = targetsToRemove.Count;
            if( numTargetsToRemove!=0 )
            {
                for( int i=0 ; i<numTargetsToRemove ; i++ )
                {
                    Transform next = targetsToRemove[i];
                    if( next!=null )
                    for( int k=_targetsDataAccess.length-1 ; k!=-1 ; k-- )
                    {
                        if( _targetsDataAccess[k]==next )
                        {
                            _targetsDataAccess.RemoveAtSwapBack( k );
                            break;
                        }
                    }
                }
                targetsToRemove.Clear();
            }

            int numTargetsToAdd = targetsToAdd.Count;
            if( numTargetsToAdd!=0 )
            {
                for( int i=0 ; i<numTargetsToAdd ; i++ )
                    if( targetsToAdd[i]!=null )
                        _targetsDataAccess.Add( targetsToAdd[i] );
                targetsToAdd.Clear();
            }
        }
        ___maintain_data_access.End();

        // schedule new jobs:
        ___schedule_new.Begin();
        int numTroops = _troopsDataAccess.length;
        int numTargets = _targetsDataAccess.length;
        if( numTroops!=0 && numTargets!=0 )
        {
            ___schedule.Begin();
            _troopPositions.Length = numTroops;
            _nearestTargetIndices.Length = numTroops;
            _targetPositions.Length = numTargets;
            
            JobHandle troopPositionsJobHandle = new ReadPositionsJob{ Results = _troopPositions }
                .Schedule( _troopsDataAccess );
            JobHandle targetPositionsJobHandle = new ReadPositionsJob{ Results = _targetPositions }
                .Schedule( _targetsDataAccess );
            
            var findNearestTargetJob = new FindNearestTargetJob
            {
                Origins = _troopPositions ,
                Targets = _targetPositions ,
                Results = _nearestTargetIndices ,
            };
            Dependency = JobHandle.CombineDependencies( troopPositionsJobHandle , targetPositionsJobHandle , Dependency );
            Dependency = findNearestTargetJob.Schedule(
                arrayLength:            numTroops ,
                innerloopBatchCount:    math.max( numTroops/SystemInfo.processorCount/4 , 1 ) ,
                dependsOn:                Dependency
            );
            ___schedule.End();
        }
        ___schedule_new.End();
    }
}

[Unity.Burst.BurstCompile]
public struct ReadPositionsJob : IJobParallelForTransform
{
    [WriteOnly] public NativeArray<float3> Results;
    void IJobParallelForTransform.Execute ( int index , TransformAccess transform )
        => Results[index] = transform.position;
}

[Unity.Burst.BurstCompile]
public struct FindNearestTargetJob : IJobParallelFor
{
    [ReadOnly] public NativeList<float3> Origins;// reads one per jobIndex
    [ReadOnly][NativeDisableParallelForRestriction] public NativeList<float3> Targets;// reads all per jobIndex
    [WriteOnly] public NativeArray<int> Results;
    void IJobParallelFor.Execute ( int jobIndex )
    {
        float3 origin = Origins[jobIndex];
        int candidate = -1;
        float candidateDistSq = float.PositiveInfinity;
        for( int i=0 ; i<Targets.Length ; i++ )
        {
            float distSq = math.distancesq( origin , Targets[i] );
            if( distSq<candidateDistSq )
            {
                candidateDistSq = distSq;
                candidate = i;
            }
        }
        Results[jobIndex] = candidate;
    }
}

 

标签:NativeList,using,int,void,移除,Transform,JobSystem,new,public
From: https://www.cnblogs.com/flamesky/p/18394618

相关文章

  • 高创新 | Matlab实现Transformer-GRU-SVM多变量时间序列预测
    高创新|Matlab实现Transformer-GRU-SVM多变量时间序列预测目录高创新|Matlab实现Transformer-GRU-SVM多变量时间序列预测效果一览基本介绍程序设计参考资料效果一览基本介绍1.Matlab实现Transformer-GRU-SVM多变量时间序列预测,Transformer+门控循环单......
  • 基于Seriall-LSTM-Transformer的自行车租赁数量预测研究(Matlab代码实现)
                            ......
  • 这样图解Transformer应该没人看不懂了吧——Transformer工作原理
    前言本文将深入剖析Transformer的内部工作原理,详细研究其运作细节。我们将通过实际的矩阵表示和形状,观察数据如何在系统中流动,并理解每个阶段进行的计算。本文目标不仅是理解Transformer是如何工作的,更要探究它为何如此工作。架构概览正如我们在第一部分中看到的,Transformer架构的......
  • 小琳AI课堂:Transformer模型
    大家好,这里是小琳AI课堂!今天我们来聊聊一个在自然语言处理(NLP)领域取得了革命性进展的深度学习架构——Transformer模型!......
  • 神经网络与Transformer模型在智能驾驶中的应用
    前言为什么展示模块是高质能量,而硅控模块是比较低智能呢?因为在感知环节中,具体它是一辆货车还是小轿车,我们并不需要雇佣5000名程序员去写识别的规则,比如说长宽高是多少以上的,满足条件之后才会判定为货车或者满足什么条件才是轿车,而是完全不需要代码去实现感知功能。通过一个合理的神......
  • 搞懂Transformer结构,看这篇PyTorch实现就够了
    前言下面分享一篇实验室翻译的来自哈佛大学一篇关于Transformer的详细博文。“AttentionisAllYouNeed”[1]一文中提出的Transformer网络结构最近引起了很多人的关注。Transformer不仅能够明显地提升翻译质量,还为许多NLP任务提供了新的结构。虽然原文写得很清楚,但实际上大家普......
  • 《BERT基础教程:Transformer大模型实战》一本相见恨晚的大模型入门书(附PDF)
    前言随着chatgpt的火热,大模型成为业界新的热点。而未来每个人,不仅仅是人工智能或者计算机行业从业者,未来的工作或多或少可能都会被大模型的影响。所以了解transformer为基础的大模型(Bert,gpt)就很有必要了。本书聚焦谷歌公司开发的BERT自然语言处理模型,由浅入深地介绍了BERT的工......
  • 【论文】OmniVec2:一种基于Transformer的新型大规模网络多模态多任务学习
    前言《OmniVec2:ANovelTransformerbasedNetworkforLargeScaleMultimodalandMultitaskLearning》研究背景研究问题:这篇文章提出了一种新的多模态多任务网络及其相关的训练算法,旨在处理来自约12种不同模态的数据,包括图像、视频、音频、文本、深度、点云、时间序列、表格、图......
  • 论文阅读01-Improving Closed and Open-Vocabulary Attribute Prediction using Trans
    论文框架研究背景和动机这篇论文试图解决什么问题?为什么这个问题重要?这个问题在当前的研究领域中有哪些已知的解决方案?研究方法和创新点论文提出了什么新的方法或模型?这个方法或模型是如何工作的?它与现有的方法相比有哪些改进?论文中的创新点是否显著且有实际意义?理......
  • 大模型书籍推荐:大模型黑书《基于GPT-3、ChatGPT、GPT-4等Transformer架构的自然语言处
    一、内容介绍Transformer正在颠覆AI领域。这本书将引导你使用HuggingFace从头开始预训练一个RoBERTa模型,包括构建数据集、定义数据整理器以及训练模型等。《基于GPT-3、ChatGPT、GPT-4等Transformer架构的自然语言处理》分步展示如何微调GPT-3等预训练模型。研究机器翻......