【Unity】万人同屏, 从入门到放弃之——Entities 1.0.16性能测试

news2024/10/5 15:28:22

当前测试使用的Entities版本为1.0.16

Unity Entities 1.0.16使用方法:

Create a component for the spawner example | Entities | 1.0.16

1. 创建SubScene

2. 在SubScene下创建挂载Authoring脚本:

Authoring是MonoBehaviour脚本,主要用来序列化配置需要创建的实体prefab资源或参数;

因为Entities目前不支持用资源名动态加载资源!没错,AssetsBundle或Addressables都不能用于Entities;也就意味着现阶段不能用Entities开发DLC或热更游戏。

Entities必须使用SubScene,而SubScene不能从资源动态加载,路被彻底封死了。

public class EntitiesAuthoring : MonoBehaviour
{
    public GameObject m_Prefab;
    public int m_Row;
    public int m_Col;
}

 3. 把步骤2的挂有Authoring脚本的GameObject转换为Entity:

SubScene中挂载的MonoBehaviour不会被执行,必须转换为Entity;

此步骤主要是把Authoring中的参数转接到自己定义的ComponentData;


class EntitiesAuthoringBaker : Baker<EntitiesAuthoring>
{
    public override void Bake(EntitiesAuthoring authoring)
    {
        var entity = GetEntity(TransformUsageFlags.None);
        AddComponent<EntitiesComponentData>(entity, new EntitiesComponentData
        {
            m_PrefabEntity = GetEntity(authoring.m_Prefab, TransformUsageFlags.Dynamic | TransformUsageFlags.Renderable),
            m_Row = authoring.m_Row,
            m_Col = authoring.m_Col
        });
    }
}

struct EntitiesComponentData : IComponentData
{
    public Entity m_PrefabEntity;
    public int m_Row;
    public int m_Col;
}

 4. 编写创建Entity的System脚本:

由于MonoBehaviour不会在SubScene中执行,System就类似MonoBehavior,拥有OnCreate, OnUpdate, OnDestroy生命周期。Entities框架会自动执行所有已经定义的System,若不想自动执行System可以在头部添加[DisableAutoCreation],然后使用state.World.CreateSystem<MoveEntitiesSystem>()手动创建System。

[BurstCompile]
partial struct SpawnEntitiesSystem : ISystem
{
    void OnCreate(ref SystemState state)
    {
        //Application.targetFrameRate = 120;
        state.RequireForUpdate<EntitiesComponentData>();
    }
    void OnDestroy(ref SystemState state)
    {

    }

    void OnUpdate(ref SystemState state)
    {
        var ecbSingleton = SystemAPI.GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>();
        var ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged);

        foreach (var data in SystemAPI.Query<EntitiesComponentData>())
        {
            Unity.Mathematics.Random m_Random = new Unity.Mathematics.Random(1);
            var m_RandomRange = new float4(-data.m_Row * 0.5f, data.m_Row * 0.5f, -data.m_Col * 0.5f, data.m_Col * 0.5f);
            var halfSize = new float2(data.m_Col * 0.5f, data.m_Row * 0.5f);
            for (int i = 0; i < data.m_Row; i++)
            {
                for (int j = 0; j < data.m_Col; j++)
                {
                    var entity = state.EntityManager.Instantiate(data.m_PrefabEntity);
                    ecb.SetComponent(entity, LocalTransform.FromPosition(new float3(j - halfSize.x, 0, i - halfSize.y)));
                    ecb.AddComponent<TargetMovePointData>(entity, new TargetMovePointData() { targetPoint = new float3(m_Random.NextFloat(m_RandomRange.x, m_RandomRange.y), 0, m_Random.NextFloat(m_RandomRange.z, m_RandomRange.w)) });
                }
            }
            state.Enabled = false;
        }
    }
}

 5. 定义一个System专门控制所有小人的移动:

使用JobSystem并行计算和设置小人的位置:

[BurstCompile]
    partial struct MoveEntitiesJob : IJobParallelFor
    {
        [ReadOnly]
        public Unity.Mathematics.Random random;
        [ReadOnly]
        public float4 randomRange;

        [ReadOnly]
        public float moveSpeed;

        [ReadOnly]
        public NativeArray<Entity> entities;
        [NativeDisableParallelForRestriction]
        public EntityManager entityManager;
        [WriteOnly]
        public EntityCommandBuffer.ParallelWriter entityWriter;

        [BurstCompile]
        public void Execute(int index)
        {
            var entity = entities[index];
            var tPointData = entityManager.GetComponentData<TargetMovePointData>(entity);
            var tPoint = tPointData.targetPoint;
            var transform = entityManager.GetComponentData<LocalTransform>(entity);

            float3 curPoint = transform.Position;
            var offset = tPoint - curPoint;
            if (math.lengthsq(offset) < 0.4f)
            {
                tPointData.targetPoint = new float3(random.NextFloat(randomRange.x, randomRange.y), 0, random.NextFloat(randomRange.z, randomRange.w));
                entityWriter.SetComponent(index, entity, tPointData);
            }

            float3 moveDir = math.normalize(tPointData.targetPoint - curPoint);
            transform.Rotation = Quaternion.LookRotation(moveDir);
            transform.Position += moveDir * moveSpeed;
            entityWriter.SetComponent(index, entity, transform);
        }
    }

 Entities测试结果:

10万个移动的小人,140多帧,同等数量级比自定义BatchRendererGroup帧数高出20+,那是因为Entities Graphics内部实现了BatchRendererGroup的剔除Culling,相机视口外的物体会被Culling。自定义BatchRendererGroup只要在OnPerformCulling回调方法中实现Culling也能达到相同的性能:

 其实到这里测试已经没有意义了,GPU端Entities Graphics结局已经注定,所谓Entities ECS结构也只是对CPU的性能提升,但海量物体的渲染GPU是最大的瓶颈。

使用Entities 1.0.16安卓端性能:

1万个小人,12帧;

 查了查URP的渲染实现,其实内部也是Batch Renderer Group, 所以这也注定了无论是自定义Batch Renderer Group还是使用Entities,在移动端都是一样的性能。

结论:

目前为止(Entities 1.0.16)有太多致命局限性,也只是对PC平台做了性能优化,并且有开挂般的大幅提升;

但是对于移动平台收效甚微,JobSystem在移动平台并行线程数迷之变少,并且暂无开放接口设置。图形库必须为OpenGLES3及以上或Vulkan,与使用限制和开发门槛相比,ECS结构微弱的性能提升不值一提。

移动平台万人同屏方案尝试失败,弃坑。不过苍蝇再小也是肉,单线程的Unity编程方式早已跟不上如今的硬件发展,虽然HybridCLR不支持Burst加速,只能以解释方式执行JobSystem,但是安全的多线程对大量数据的计算仍然有很大的意义。

期待Entities的资源系统早日面世...

最后附上Entities万人同屏测试代码:

using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
using UnityEngine.Jobs;

public class EntitiesAuthoring : MonoBehaviour
{
    public GameObject m_Prefab;
    public int m_Row;
    public int m_Col;
}

class EntitiesAuthoringBaker : Baker<EntitiesAuthoring>
{
    public override void Bake(EntitiesAuthoring authoring)
    {
        var entity = GetEntity(TransformUsageFlags.None);
        AddComponent<EntitiesComponentData>(entity, new EntitiesComponentData
        {
            m_PrefabEntity = GetEntity(authoring.m_Prefab, TransformUsageFlags.Dynamic | TransformUsageFlags.Renderable),
            m_Row = authoring.m_Row,
            m_Col = authoring.m_Col
        });
    }
}

struct EntitiesComponentData : IComponentData
{
    public Entity m_PrefabEntity;
    public int m_Row;
    public int m_Col;
}
[BurstCompile]
partial struct SpawnEntitiesSystem : ISystem
{
    void OnCreate(ref SystemState state)
    {
        //Application.targetFrameRate = 120;
        state.RequireForUpdate<EntitiesComponentData>();
    }
    void OnDestroy(ref SystemState state)
    {

    }

    void OnUpdate(ref SystemState state)
    {
        var ecbSingleton = SystemAPI.GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>();
        var ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged);

        foreach (var data in SystemAPI.Query<EntitiesComponentData>())
        {
            Unity.Mathematics.Random m_Random = new Unity.Mathematics.Random(1);
            var m_RandomRange = new float4(-data.m_Row * 0.5f, data.m_Row * 0.5f, -data.m_Col * 0.5f, data.m_Col * 0.5f);
            var halfSize = new float2(data.m_Col * 0.5f, data.m_Row * 0.5f);
            for (int i = 0; i < data.m_Row; i++)
            {
                for (int j = 0; j < data.m_Col; j++)
                {
                    var entity = state.EntityManager.Instantiate(data.m_PrefabEntity);
                    ecb.SetComponent(entity, LocalTransform.FromPosition(new float3(j - halfSize.x, 0, i - halfSize.y)));
                    ecb.AddComponent<TargetMovePointData>(entity, new TargetMovePointData() { targetPoint = new float3(m_Random.NextFloat(m_RandomRange.x, m_RandomRange.y), 0, m_Random.NextFloat(m_RandomRange.z, m_RandomRange.w)) });
                }
            }
            state.Enabled = false;
            
        }
    }
    [BurstCompile]
    partial struct MoveEntitiesSystem : ISystem
    {
        Unity.Mathematics.Random m_Random;
        float4 m_RandomRange;
        void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<TargetMovePointData>();
        }
        void OnStartRunning(ref SystemState state)
        {
            if (SystemAPI.TryGetSingleton<EntitiesComponentData>(out var dt))
            {
                m_RandomRange = new float4(-dt.m_Row * 0.5f, dt.m_Row * 0.5f, -dt.m_Col * 0.5f, dt.m_Col * 0.5f);
            }
            else
            {
                m_RandomRange = new float4(-50, 50, -50, 50);
            }
        }
        void OnDestroy(ref SystemState state)
        {

        }

        void OnUpdate(ref SystemState state)
        {
            EntityCommandBuffer.ParallelWriter ecb = GetEntityCommandBuffer(ref state);
            m_Random = new Unity.Mathematics.Random((uint)Time.frameCount);
            var entityQuery = SystemAPI.QueryBuilder().WithAll<TargetMovePointData>().Build();
            var tempEntities = entityQuery.ToEntityArray(Allocator.TempJob);

            var moveJob = new MoveEntitiesJob
            {
                random = m_Random,
                moveSpeed = SystemAPI.Time.DeltaTime * 4,
                randomRange = m_RandomRange,
                entities = tempEntities,
                entityManager = state.EntityManager,
                entityWriter = ecb
            };
            var moveJobHandle = moveJob.Schedule(tempEntities.Length, 64);
            moveJobHandle.Complete();
        }
        private EntityCommandBuffer.ParallelWriter GetEntityCommandBuffer(ref SystemState state)
        {
            var ecbSingleton = SystemAPI.GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>();
            var ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged);
            return ecb.AsParallelWriter();
        }
    }
    struct TargetMovePointData : IComponentData
    {
        public float3 targetPoint;
    }
    [BurstCompile]
    partial struct MoveEntitiesJob : IJobParallelFor
    {
        [ReadOnly]
        public Unity.Mathematics.Random random;
        [ReadOnly]
        public float4 randomRange;

        [ReadOnly]
        public float moveSpeed;

        [ReadOnly]
        public NativeArray<Entity> entities;
        [NativeDisableParallelForRestriction]
        public EntityManager entityManager;
        [WriteOnly]
        public EntityCommandBuffer.ParallelWriter entityWriter;

        [BurstCompile]
        public void Execute(int index)
        {
            var entity = entities[index];
            var tPointData = entityManager.GetComponentData<TargetMovePointData>(entity);
            var tPoint = tPointData.targetPoint;
            var transform = entityManager.GetComponentData<LocalTransform>(entity);

            float3 curPoint = transform.Position;
            var offset = tPoint - curPoint;
            if (math.lengthsq(offset) < 0.4f)
            {
                tPointData.targetPoint = new float3(random.NextFloat(randomRange.x, randomRange.y), 0, random.NextFloat(randomRange.z, randomRange.w));
                entityWriter.SetComponent(index, entity, tPointData);
            }

            float3 moveDir = math.normalize(tPointData.targetPoint - curPoint);
            transform.Rotation = Quaternion.LookRotation(moveDir);
            transform.Position += moveDir * moveSpeed;
            entityWriter.SetComponent(index, entity, transform);
        }
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1018263.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

网页的快捷方式打开自动全屏--Chrome、Firefox 浏览器相关设置

Firefox 的全屏方式与 Chrome 不同&#xff0c;Chrome 自带全屏模式以及APP模式&#xff0c;通过简单的参数即可设置&#xff0c;而Firefox暂时么有这个功能&#xff0c;Firefox 的全屏功能可以通过全屏插件实现。 全屏模式下&#xff0c;按 F11 不会退出全屏&#xff0c;鼠标…

【微信小程序】文章样式,标题样式,及设置背景~

| background-size 设置背景图片大小。图片可以保有其原有的尺寸&#xff0c;或者拉伸到新的尺寸&#xff0c;或者在保持其原有比例的同时缩放到元素的可用空间的尺寸。 | background-size: cover;适配屏幕大小 文章样式&#xff0c;标题样式&#xff0c;及设置背景~ index.w…

AGV小车、机械臂协同作业实战02-开源opentcs 项目调研

这个项目是从0到1 的一个过程&#xff0c;碰到这种项目给我的第一反应就是先查查有没有轮子&#xff0c;往往站在巨人的肩膀上 事情就会变得简单多了。各种搜索后发现网站这类的项目少之又少&#xff0c;唯一一个值得参考的项目 就是Opentcs 了&#xff0c;而且这个项目最近也在…

echarts-图表(非常规图开发记录)

echarts-图表&#xff08;非常规图开发记录&#xff09; 环形刻度图横向左右柱形图3D饼图渐变柱子-柱状图3D柱状图雷达图动态滚动图-并加图片 以下图表数据源&#xff0c;allData.value 均为如下格式 [{"id": "1","name": "在职在岗",…

企业邮箱功能详解:提升办公效率的多面手

企业邮箱是一种专为企业打造的电子邮件服务&#xff0c;它可以帮助企业提高工作效率、加强内部沟通和保护企业信息安全。本文将介绍企业邮箱的一些主要功能和优势。 一、邮件收发 企业邮箱提供了一个专门的电子邮件账户&#xff0c;员工可以通过这个账户收发工作相关的邮件。相…

基于SSM的校园自助洗衣系统的设计与实现

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;采用JSP技术开发 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#x…

GIS跟踪监管系统电子围栏

GIS跟踪监管系统电子围栏 &#xff08;1&#xff09;电子围栏展示。① 显示&#xff1a;② 隐藏&#xff1a;&#xff08;2&#xff09;电子围栏修改。① 新增电子围栏。② 修改电子围栏。工具箱&#xff08;1&#xff09;测量。① 测量距离&#xff1a;② 测量面积&#xff1a…

洛科威多功能岩棉板助力节能减碳战略,推动碳达峰目标实现

国家相关部门提出了要“协同推进降碳、减污、扩绿、增长&#xff0c;推进生态优先、节约集约、绿色低碳发展”的总要求&#xff0c;未来相当长的时间里&#xff0c;降碳都将是一项重要工作&#xff0c;节能降碳是实现碳达峰碳中和的有效途径&#xff0c;也是着力解决资源环境约…

基于springboot+vue的企业面试预约管理系统

基于springbootvue的企业面试预约管理系统 预约面试管理系统&#xff0c;可以通过学生&#xff0c;企业角色进行登录 登录后可以查看发布的岗位&#xff0c;发布人&#xff0c;发布时间&#xff0c;面试时间&#xff0c;招聘时间&#xff0c;招聘单位简介等 查看用户管理信息

云组网案例分享

最近遇到了一个客户场景&#xff0c;是个非常典型的跨云组网场景&#xff0c;我们梳理了下这个客户的需求以及我们提供的解决方案&#xff0c;出于保密要求&#xff0c;文章不会涉及任何客户信息。如果您想体验我们的产品&#xff0c;可以登录我们的控制台免费使用&#xff0c;…

【Axure原型素材】扫一扫

今天和粉丝们免费分享扫一扫的原型素材&#xff0c;"扫一扫"是一项常见的移动应用功能&#xff0c;通常通过手机或平板电脑上的摄像头来扫描二维码或条形码以实现各种功能。下面是和大家分享扫一扫的常用素材~~~ 【原型效果】 【Axure原型素材】扫一扫 【原型预览】…

石油天然气工程用热轧型钢

声明 本文是学习GB-T 42678-2023 石油天然气工程用热轧型钢. 而整理的学习笔记,分享出来希望更多人受益,如果存在侵权请及时联系我们 1 范围 本文件规定了石油天然气工程用热轧型钢的订货内容、牌号表示方法、尺寸、外形、重量、技术要求、 试验方法、检验规则、包装、标志…

springboot日志配置(logback+slf4j配置)

1.为什么要配置日志 故障排查和问题分析&#xff1a; 日志记录允许开发人员和运维人员在系统发生问题或故障时追踪问题的根本原因。通过查看日志文件&#xff0c;他们可以了解系统在特定时间点发生了什么事情&#xff0c;从而更容易定位和解决问题。 性能监控和优化&#xff1a…

YOLOV7改进:在C5模块不同位置添加D-LKA Attention(同时拥有SA注意力和大卷积核的能力)

1.该文章属于YOLOV5/YOLOV7/YOLOV8改进专栏,包含大量的改进方式,主要以2023年的最新文章和2022年的文章提出改进方式。 2.提供更加详细的改进方法,如将注意力机制添加到网络的不同位置,便于做实验,也可以当做论文的创新点。 3.涨点效果:D-LKA Attention注意力机制,实现有…

有没有一款让人爱不释手的知识库工具?知识库管理工具不难选!

对于企业来说&#xff0c;因为其本身的业务需求、外部各类标准规范的要求、数字化转型趋势带来的便利&#xff0c;使得更多的企业开始自主搭建知识库&#xff0c;开始试图通过知识管理去提升组织的效率和创新能力。 虽然说市面上有不少关于知识笔记的管理工具&#xff0c;比如有…

Android Kotlin 基础详解

1,基础语法 1.1 可变变量与不可变变量 可以多次赋值的变量是可变变量&#xff0c;用关键字var表示&#xff1a; var <标识符> : <类型> <初始化值> 注意&#xff0c;在kotlin中成员变量不会赋默认值&#xff0c;不像java一样&#xff0c;必须手动添加默…

时间复杂度讲解(数据结构)

目录 引言 什么是数据&#xff0c;结构和算法 时间复杂度的概念 如何计算时间复杂度 总结 引言 hello大家好&#xff0c;我是boooooom君家宝。在前期的博客中博主呢对c语言的一些重要知识点进行了讲解&#xff0c;接下来博主的博客内容将为大家呈现的是数据结…

JavaScript:二进制数组【笔记】

二进制数组【ArrayBuffer对象、Type的Array视图和DataView视图】JavaScript操作二进制数据的一个接口。 这些接口原本是和WebGL有关【WebGL是浏览器与显卡之间的通信接口】&#xff0c;为了满足JavaScript与显卡之间大量、实时数据交换&#xff0c;那么JavaScript和显卡之间的…

认识面向对象-PHP8知识详解

面向对象编程&#xff0c;也叫面向对象程序设计&#xff0c;是在面向过程程序设计的基础上发展而来的&#xff0c;它比面向过程编程具有更强的灵活性和扩展性。 它用类、对象、关系、属性等一系列东西来提高编程的效率&#xff0c;其主要的特性是可封装性、可继承性和多态性。…

2024届河南硕士暑期实习经验分享---招商银行篇

本期的实习经验分享&#xff0c;采访到了我的一位优秀的师弟&#xff0c;师弟于今年成功被郑州招商银行信息技术岗录取进行实习&#xff0c;下面他将使用第一人称的方式分享自己寻找实习过程中的一些经验、需要避的坑和在招商银行实习过程中的一些经历&#xff0c;为后续师弟师…