#archived-dots

1 messages · Page 183 of 1

zinc plinth
#

@shy pilot you can't have dynamic buffers in components

#

also it feels like your data is way too much conglomerated

#

state, (pregnant & gestationFinish), gender, attacker should be in their own components

deft stump
#

Hi. Trying to check one entity component values against several entity components. I'm thinking do an entity query for one and a .foreach for the others when component value changed.
@brazen storm that's a sound idea. I

brazen storm
#

thanks @deft stump let's hope it works! Any ideas on sending component value to UI?

slim nebula
#

is it possible to somehow load multiple instances of the same subscene in different locations?

hollow sorrel
#

a subscene doesn't have a location but yea you should be able to load it multiple times and shift entities inside it by an offset

brazen storm
#

can you pass a query into a .ForEach?

slim nebula
#

ok thanks

deft stump
#

can you pass a query into a .ForEach?
@brazen storm you can.

olive kite
#

Some of the Unity samples might be good to look over to get an idea of how they mean for the data to be organized and accessed. For example, a simple guard:

#

`// An IBufferElementData becomes a DynamicBuffer<T>
// This will reserve 8 WaypointPositions of memory per-entity in the chunk
[InternalBufferCapacity(8)]
public struct WaypointPosition : IBufferElementData
{
public float3 Value;
}

// The total time (in seconds) to wait during each idle state
public struct CooldownTime : IComponentData
{
public float Value;
}

// The index of the next waypoint to travel to in our DynamicBuffer<WaypointPosition>
public struct NextWaypointIndex : IComponentData
{
public int Value;
}

// A tag that helps us tell the difference between "Patrolling" and "Chasing"
public struct IsChasingTag : IComponentData
{}

// The position the guard plans to move towards during "Patrolling" and "Chasing"
public struct TargetPosition : IComponentData
{
public float3 Value;
}

// Used to store how long (in seconds) we have been in the idle state. Only exists when "Idle"
public struct IdleTimer : IComponentData
{
public float Value;
}

// Defines a 2D cone in front of the guard, used to detect players
public struct VisionCone : IComponentData
{
public float AngleRadians;
public float ViewDistanceSq;
}

// A tag that helps us tell the difference between "Patrolling" and "Chasing"
public struct IsInTransitionTag : IComponentData
{}
public struct SetNewPath : IComponentData
{
public float3 pathTarget;
}`

slim nebula
#

How do I store a subscene on a component? Classes don't appear to be allowed. Do I need to write a custom authoring component to get only the GUID?

slim nebula
#

I found this scene reference thing, but it doesn't seem to show up in the editor

#

any ideas how to get this working?

#

it's just like 0 fucks given

coarse turtle
#

SceneReference isn't serializable so it won't show up in the editor. But it looks like it stores a guid so you could probably just expose some sort of text field or numerical field in an authoring component to display the guid

slim nebula
#

so like... if you have an entity on a IComponentData, and use GenerateAuthoringComponent, it will create an authoring component with a GameObject property you can populate in the inspector.

#

Is there no way to do this with subscene automatically? I'm I stuck writing a custom authoring component (SubScene on the monobehavior, then copy the GUID to the IComponentData)?

#

I guess it just seems kinda verbose. Was wondering if there was a less verbose way

coarse turtle
#

I don't know of any other less verbose way. I also don't tend to use the GenerateAuthoringComponent attribute and just stick with writing IConvertGameObjectToEntity.

slim nebula
#

ah ok

#

thank you

proper silo
#

Hello! Is NativeQueue not compatible with the burst compiler? I get an error when trying to use one

deft stump
#

What does the error say?

proper silo
#

"Burst error BC1042: The managed class type Unity.Collections.NativeQueueBlockPoolData* is not supported. Loading from a non-readonly static field Unity.Collections.NativeQueueBlockPool.pData is not supported"

zenith wyvern
#

NativeQueue is burst compatible. Can you show the code that's causing the error?

proper silo
#

Yes sorry, here is the system @zenith wyvern

    protected override void OnUpdate()
    {
        Entities.ForEach((in DoQueueTestTag tag) => 
        {
            Debug.Log("This is an object");

            NativeQueue<int> queue = new NativeQueue<int>(Allocator.Temp);



            queue.Dispose();
        }).ScheduleParallel();
    }```
zenith wyvern
#

You don't need to call dispose on a temp container, it disposes itself. And the [BurstCompile] attribute isn't doing anything in that context, it's only for job structs or static functions used in function pointers

#

Not sure either of those would cause the error though

proper silo
#

Removed both and the error still persist unluckily

#

But does that mean that Entities.ForEach are automatically using burst if enabled in the settings ?

stiff skiff
#

Yes

#

Entities.ForEach always uses burst until you do Entities.WithoutBurst().ForEach

zenith wyvern
stiff skiff
#

Why are you allocating a queue inside the job?

zenith wyvern
#

Not sure what else you're doing to cause the error but it's not from NativeQueue

stiff skiff
#

Could be you are both using a different version of the collections or Burst package

proper silo
#

I am doing this test in a clean project, to make sure there is nothing else interfering . I am using Collection 0.12.0-preview.13 and burst 1.3.2

#

And I am creating a Queue in the job to deal with some pathfinding algorithm stuff (as an openList)

zenith wyvern
#

What version of Unity?

#

Newer version of ECS is only supported in 2020+

proper silo
#

yeah, I am using 2020.1.10.f1

slim nebula
#

Does anyone know how can I load two separate instances of the same subscene? This seems to only load one set of entities, not two: ```cs
m_sceneSystem.LoadSceneAsync(rooms[0].SceneGUID);
m_sceneSystem.LoadSceneAsync(rooms[0].SceneGUID);

#

@hollow sorrel do you know?

zenith wyvern
#

Not sure what's causing the error then. You can see from my code I pasted that NativeQueue works fine on it's own inside a job. Are you sure you're using an unmanaged type in your queue?

proper silo
#

Thats odd, it works for you so I am going to check on my side, I must have missed something

stiff skiff
#

Hmm

#

This post from 2019 says you cant allocate a NativeQueue from inside a burst job though

viral comet
#

@blissful gorge

The goal is to have a Burst-compatible delegate that doesn't have the same limitations as FunctionPointer.
Sounds cool, would love to see progress on this

hollow sorrel
#

@slim nebula doesn't that method load a unity scene, not a subscene?
by default loading a new scene will unload the current scene

zenith wyvern
slim nebula
#

I dont think so no. my old stuff is there. it's only loading in the subscene. What way would you reccomend to load a subscene?

#

@hollow sorrel

hollow sorrel
#

not sure, docs are nonexistent on subscenes

slim nebula
#

yeah 😦

#

well thanks for tryin

proper silo
#

Ohhhh everything makes sense now hahaha Thanks you both of you @zenith wyvern @stiff skiff

slim nebula
#

maybe it's not possible

stiff skiff
#

@proper silo You can allocate the queue outside the job and capture it

#

I'd always recommend allocating outside of jobs and passing it along somehow

zenith wyvern
#

For that purpose it seems like you're better off just using a NativeList though

#

NativeQueue is specifically meant for queueing to the same container from parallel jobs

stiff skiff
#

You only have a limited amount of space you can use for temp allocs inside a job, once you go beyond this, stuff gets expensive

hollow sorrel
#

@slim nebula if you want a workaround, maybe you could pass in a new LoadParameters as 2nd argument to your loadsceneasync, with loadflags set to additive so that it will add the scene without unloading previous

slim nebula
#

didn't seem to change anything. Regardless if I put those load parameters there I still get only one "MuhCube" entity

#

@hollow sorrel

stiff skiff
#

Set whether to load additive or not. This only applies to GameObject based scenes, not subscenes.```
hollow sorrel
#

hm

#

not sure then sry

slim nebula
#

rip

#

well thanks for tryin

stiff skiff
#

what about loading the subscene into a new world, then transferring the entities over?

slim nebula
stiff skiff
#

You can use EntityManager.MoveEntitiesFrom(out NativeArray<Entity>, EntityManager)

#

To move the entities from the new world, into the one you want your "room" in

#

and it nicely provides an array with what the new id's are

slim nebula
#

hmm ok. time to learn about making my own worlds I guess

#

so far I only been using client world and server world

stiff skiff
#

Note that you probably need this anyways

#

since Load doesnt give you the list of loaded entities back

#

which you need to offset them in your world later

#

unless you want every room to overlap

slim nebula
#

ah ok

stiff skiff
#

(Small note, i've never used subscenes. Just giving some ideas)

slim nebula
#

ok

#

yeah I dunno. I'm just trying to do a random level generation kinda thing. Figured subscenes would be better performance than prefabs, but it looks like some stuff might be missing for me to do this. I'll try playing with loading in different worlds and transferring between them. thanks

#

I guess I also worry if using this other-world loading method will even be faster/better than just using prefabs straight up...

valid haven
#

What are the blockers currently that would prevent/make trouble for starting a new game (open world multiplayer game) and using ECS/DOTs in a limited capacity for CPU intensive tasks and physics? Keeping in mind this project wouldn't be ready for primetime for quite sometime. I want to use the havoks physics system as a minimum, to take advantage of its improved floating point accuracy (50k units vs 4-8k).

olive kite
#

Can anyone explain why they use the .WithNativeDisableParallelForRestriction instead of just passing the component data through a ref in the guard/player Unity example?

olive kite
#

And the notes make it sound like they are writing to the player but they are just writing to all of the playertarget entity components (unless I am understanding it incorrectly) so I'm a bit confused on what they are doing, which makes me think I don't understand it fully.

fluid kiln
#

Any doc on NetCode's conversion system with sub scenes? I can't find anything

slim nebula
#

I don't think subscene stuff is really documented much @fluid kiln

#

what conversion system do you mean? ghosts?

fluid kiln
#

I thought the subscene conversion was related to NetCode but it's actually DOTS itself. I've looked it up thank you 🙂

pliant pike
#

Is there not an opposite for ComponentDataFromEntity? I need to get the entity from the component tag

slim nebula
#

isn't that just a normal entity query?

pliant pike
#

I can't get entity's directly with an entityquery can I?

slim nebula
#
Entities.ForEach((Entity entity, MyComponentTag tag) => {...});
#

should get any entity that has ur tag

#

i dunno if there's another way

pliant pike
#

yeah I know that but I need to get them using a literal entityquery like

#

m_Query = GetEntityQuery(ComponentType.ReadOnly<ObstacleAuthoring>())

slim nebula
#

I'm pretty new myself sorry :S

pliant pike
#

that just gets the tag and I need to get the entity attached to that tag so I can get another component

slim nebula
#

Entities.ToEntityQuery().ToEntityArray()

#

this looks fun

#

maybe you can reduce the collection then get the 0-index element

#

using linq or fluant API stuff or somethin I dunno

#

wrap it into an extension method

pliant pike
#

that's too complicated for me leahS

slim nebula
coarse turtle
#

wait so given a tag you want to get the entity associated with the tag?

pliant pike
#

yeah

coarse turtle
#

Entities.WithAll<Tag>().ForEach((Entity e) => {})?

#

that could work too

pliant pike
#

yeah I've done that

#

but I need to get another lot in that job with a different tag

#

I've got the same componentdata I want to use, "translation" but two sets tagged differently I need to compare their translations

coarse turtle
#

o, yeah you might want two queries and build some sort of map so you can do the comparisons

slim nebula
#

is the component variable that you're using to do the look up, is that variable a ref? because if it's not, then it's just a copy, and there's no way to distinctly identify it.

#

maybe I'm totally misunderstanding what you're doing sorry XD

#

ignore me

#

I dunno

coarse turtle
#

well I guess you could also use an IJobChunk and check if the tags exist on the chunk

#

so you have chunk based logic - which could help you do comparisons better 🤔

pliant pike
#

but I hate Ijobchunks 😠

slim nebula
pliant pike
#

anyway I'll post on the forums see if anyone there has any hints, thanks guys

brazen storm
slim nebula
#

that's purple (I havn't leard jobs yet sorry)

brazen storm
#

it is

valid haven
#

What are the issues currently that would prevent/make trouble for starting a new game (open world multiplayer game) and using ECS/DOTs in a limited capacity for CPU intensive tasks and physics? Keeping in mind this project wouldn't be ready for primetime for quite sometime. I want to use the havoks physics system as a minimum, to take advantage of its improved floating point accuracy (50k units vs 4-8k).

slim nebula
#

do you plan to use unity.netcode @valid haven

valid haven
#

I am currently leaning to MLAPI, but I would use the unity.netcode if it was ready early enough in the dev process.

slim nebula
#

havok is a cached physics system. it's performance benefits don't really work when using physics prediction.

#

prediction for the purposes of netcode

pliant pike
#

@brazen storm thanks query.ToEntityArray is probably what I was looking for, just in the wrong place

valid haven
#

Using havok is tied to its larger coordinate system, not related to that.

#

unity physics and physx starts breaking around 4-8k from origin, new havok is stable up to 50k

slim nebula
#

if you're not doing physics predictions with netcode, then it's not a problem

valid haven
#

I wont need to do deterministic rollbacks

slim nebula
#

👍

valid haven
#

I guess my main question is, if I do use DOTS/ECS for a couple subsystems like physics and projectile/enitty movement updates am I going to run into limitations with other subsystems and/or editor features?

slim nebula
#

not that I know of but I'm kinda new. that one was the only one I could think of

valid haven
#

I am not clear on how all or nothing using ECS is.

vapid hamlet
#

Is the new dots net code even usable at this point?

slim nebula
#

seems to be workin for me mullagain

#

I dunno how extensible it is tho

#

their demo is supposed to support 80 clients right?

pliant pike
#

you can hook the ECS data into monobehaviour pretty easily in my opinion (don't quote me on that though)

slim nebula
#

there are some (maybe lots?) things you still need to write custom authoring components for

vapid hamlet
#

Im new to unity and I’m a bit lost on the dots vs old system. Lots of examples for the old. Any examples for the new?

#

Specifically with netcode

slim nebula
#

there was the DOTSSample github, but it doesn't run latest unity or latest packages

pliant pike
#

I havent done much with both together but you can just use the EntityManager in a monobehaviour to get the entities and the data you want for instance

slim nebula
#

I learned that one and have been slowly updating my project haha

vapid hamlet
#

Been digging on some documentation. Just can’t find it

slim nebula
#

@vapid hamlet

#

it's old tho

#

much changed

vapid hamlet
#

Yeah. Is there any official documentation?

#

Something kept up to date

pliant pike
#

the pinned messages up top have lots of references

shy pilot
#

is there a particular reason in dots to use fields and not properties?

slim nebula
#

components and buffers are structs. you can use properties on systems tho if u want

shy pilot
#

i don't see any errors though with this:

public interface IGenderBase : IComponentData
{
    public FixedString64 name { get; set; }                             //Name of the gender
    public bool seekMate { get; set; }                                 //Should the creature actively seek a mate
    public FixedString64 compatabilityPattern { get; set; }               //List of genders that the creature can mate with
}

/// <summary>
/// Data for gestation and pregnancy
/// </summary>
public struct IGestation : IGenderBase
{
    public FixedString64 name { get; set; }
    public bool seekMate { get; set; }
    public FixedString64 compatabilityPattern { get; set; }
    public float gestationFinishTime { get; set; }
    public bool gregnant { get; set; }
}
#

does that not work?

slim nebula
#

I have not tried myself but I assume it would. It just might be a little more difficult to see what the backing field data is if you start putting a bunch of logic in those properties. But I dunno that's all subjective I guess

shy pilot
#

yeah, the most i would put in them is default values

slim nebula
#

I think the roslyn compiler will optimize out the property function calls, but I'm not sure if the unity/mono compiler does. Maybe properties are a tiny bit slower? I dunno

shy pilot
#

hmm

#

i'm sure an answer will emerge as dots starts to get proper documentation 😆

#

this isn't a long standing project, i'll be done with it in a couple of weeks so i don't mind if it isn't perfectly optimised

brazen storm
#

any ideas on passing a component variable to a UI text?

shy pilot
#

@brazen storm what do you mean?

#

ohh

#

you mean the component as a whole?

brazen storm
#

I mean passing a value to a UI part of a gameobject

#

also. how can I get the entity to get buffer from? I want the buffer from it to do some raycasts in parallel.

fluid kiln
#

So in NetCode 0.4, how is someone meant to create server-only or client only entities in the editor?

deft stump
#

any ideas on passing a component variable to a UI text?
@brazen storm
You can do a GameObject.Find in a system

brazen storm
#

thanks! @deft stump I think i got that bit. trying to get entity from a query and pass it to a lambda.

zinc plinth
#

@shy pilot fields and what you're doing with inheritance are object oriented, you want to avoid that at all cost in dots since we're in dod/dop

#

and if you're mixing inheritance with data oriented you're just making a pipe bomb

steady blaze
#

hi, when using unity jobs is it recommended to use NativeContainers as much as possible or only for data needed for the Job(s) and main thread?
And use regular Arrays/Lists, etc. in the main code?
btw. don't want to use ECS yet (still GOs), only Job-System for now.

coarse turtle
#

yea that's the idea

#

although if you want to interface something with like DrawMeshInstanced (for example) you can use a ptr to fill in the array

deft stump
#

hi, when using unity jobs is it recommended to use NativeContainers as much as possible or only for data needed for the Job(s) and main thread?
@steady blaze it's not only recommended it is the only way to use Jobs in any meaningful way.

steady blaze
#

what? to use the NativeContainers as much as possible or only for shared data?

#

at least for stuff that needs to be set in the editor it seems i cannot use i.e. NativeArray

steady blaze
#

Hm, don't think I will need DrawMeshInstances, but want to use the jobs for Mesh-Generation (terrain), so I will have to pass the results to the MeshFilters of gameobjects.

coarse turtle
#

yea native array will work for that

#

you can use the low level mesh api, Mesh.SetVertexBufferData(some_native_array, some_vertex_descriptors)

brazen storm
#

Ok! I just found out the difference between the two getbuffer methods! ECS doesn't seem to like me requesting the buffer between lambdas. Is anyone knowledgeable on setting dependencies for a query?

steady blaze
#

hm, okay - but still not really an idea if I should use the NativeContainers everywhere possible or just for shared data (between main & jobs).
Also I guess the NativeContainers can only contain primitive data types and structs?
So i.e. when I need an Array/List of GameObjects it needs to be a regular one.
But when it contains only int or Vector3 - and is used only in the Main Thread, should it be regular or Native?
And when used inside a Job (but only there) use regular or native types?

#

(as said: don't want to use ECS yet (only Jobs), but regular GOs with Monobevaviour for now)

humble elk
#

So I've been looking all over the internet for a way to do this, but haven't found anything yet. I'm hoping you guys could help.
Here's my problem: I'm starting to make a VR game with the SteamVR plugin, but I want to use ECS. I've converted the Player prefab to an Entity (with injection), but I can't actually access any of the SteamVR Player class attributes from within a system.
So let's say I have a HealthSystem. How would I make the Player class respawn somewhere if it doesn't actually have access to any of the entity data?

steady blaze
#

this stuff is new to me, and there does not seem to be much documentation or best practises.
so it's really hard to tell where to use what.

#

also I wonder if there is a more comprehensive manual/reference to unity.mathematics - as it seems to have quite nice noise functions built in, using seeds, etc.

deft stump
#

@steady blaze if you're trying to get data from some jobs thread. you need to use native containers.
Also, I don't undertand what you mean by use it everywhere.

steady blaze
#

@deft stump I mean if it makes sense to use native containers for stuff that is only needed in the main "thread" or only within a certain job.

deft stump
#

use it only within a certain job

#

coz native containers doesn't have the benefit of being GC'ed so having them everywhere is a Disposing/mem leak nightmare

steady blaze
#

ah ok, I see, so better don't use them, when not needed?
(or could it also speed things up in the main thread and just use dispose when done?)

deft stump
#

(or could it also speed things up in the main thread and just use dispose when done?)
nope it doens't speed anything up in the main thread.
It's primary purpose is just putting data for the job to process and using the same native container to pull data out of the job when it's done processing.

steady blaze
#

the 2nd thing: when i calculate stuff within a Job, where only the Job needs that data and can dispose when finished, use native there or regular?

shy pilot
#

native with tempjob i think

#

then call .dispose at the end

steady blaze
#

@deft stump ok thx, that helps a lot already.

deft stump
#

@steady blaze here's a vid

#

I need to link people this video when people ask for jobs related stuff

steady blaze
#

@shy pilot what i meant is when i have to calculate stuff within a job that is not needed elsewhere.

#

@deft stump thx, will watch that now, hope it helps!

hollow sorrel
#

@steady blaze you want to still use nativearray in the job even if it's not used outside because managed allocations have performance impact in jobs
also regular arrays would prevent you from using burst

steady blaze
#

@hollow sorrel perfect, that's what i wanted to know. with this 2 informations i already get a lot further.
Will use NativeList too, hope they are solid enough already.

#

should be possible with NativeArray somehow too, but I guess it won't work well, if I assign new NativeArrays all the time with different sizes.
what could work better (if NativeList is to early): Set the size of the NativeArray to the size of elements there could be at most and in the end copy only the needed elements to a new one.

#

But I will try with NativeList first, hope it's solid enough …

#

@deft stump the video explains a lot, thx. But I wonder if there is a written version with nearly the same content?

#

I will use the job-system a bit different (on-the-fly terrain generation) then in the typical use-case (every frame), so i have to figure out some stuff.
i.e. new jobs only need to get started, when a player moves over the boundaries of the current "terrain-chunk" (or maybe better call it "area" to not confuse with unity chunks?) or manipulation of areas.

#

it should work fast enough without jobs, if i create all the data at start (maybe even the meshes?) and then just load/unload, but i guess not for infinite terrain that only needs a seed - and stores only the areas which have been modified by the player.
So it should be fast enough for on-the-fly generation.

#

i know compute shader may be even better suited, but harder to learn (and i don't have a code-editor that understands HLSL)
thanks a lot @hollow sorrel and @deft stump - i can now image a lot better how to build this from my single-threaded/single-object code.

One last question: when I schedule a job and call the complete immediately, like: var jobHandle = _job.Schedule(areas.Count, 1); jobHandle.Complete();
i.e. in Start() - is it ok to us Allocate.Temp for the NativeArray then, even, if completion takes longer, i.e. 1 second? As the main thread is locked and no frame passes by it should still be within the same frame.

deft stump
#

Yes

#

if its immediately complete right after a sched, then it's best to use Temp.

#

It still counts as frame 1

steady blaze
#

ok thanks, that's fine too then. will have to figure out when to best schedule and complete, when running around, but until getting there it will take me a few days (at least) anyway.

#

the only thing I still need to figure out is how to use Unity.Mathematics correctly.
Should be better then another simplex/perlin noise library, as it's optimized, should have that included and can be used within jobs and also burst, i guess.

shy pilot
#

better call it "area" to not confuse with unity chunks
@steady blaze i've made the same decision after a week of confusing myself 😆

safe lintel
#

@shy pilot even if that technically works, its not job or burst compatible, and you should probably force yourself to use fields to force yourself to learn using entities in conjunction with burst jobs

shy pilot
#

ok, thanks

#

is inheritance bad practice for components?

safe lintel
#

dont think it even works with ecs

#

you cant do inheritence with structs

shy pilot
#

i was trying to make interfaces that inherit from icomponentdata

#

but to declare stuff in them they had to be properties

#

so can burst just not do properties?

#

or just not ones with logic?

safe lintel
#

i think it can, but it looks like you want to do things that are questionable in the context of dots, namely use UnityEngine.Time in places where you ideally wouldnt be using it

shy pilot
#

yep, i only had that there as a shortcut that would require less code 😆

#

i can certainly live without it

#

and things like that

#

does burst work in that sense?

safe lintel
#

ive never tried personally

shy pilot
#

how does one tell?

safe lintel
#

well if it errors when you use it, there you go

#

in the context of unity's own code, ive never seen a property used in any builtin component, so that leads me to believe that you should generally just not use them

#

and these examples seem somewhat trivial in the time they save, but i get it, dots does add more boilerplate to a lot of cases

shy pilot
#

yep, ok thanks

deft stump
#

i believe properties does have some operation to be done despite how it looks in which icd's doesn't like.

dull copper
#

The week of new dots packages to land

deft stump
#

👏

#

let's not jinx it lol.

craggy orbit
#

tuesday 🎉

#

wait that's tomorrow!! 🎉

amber flicker
#

I believe they've said 'week of 27th' and... dots timelines.. but 🤞

deft stump
#

Don't jinx it!

craggy orbit
#

i thought they said the day of 🤔

#

ah yes it is the week of

#

my bad

deft stump
#

link to the forum?

craggy orbit
amber flicker
#

Yea there was one of each.. I'm aligning my expectations with 'later than the most pessimistic deadline' 😅

craggy orbit
#

can't figure out how to link to a specific message, sorry :/

#

eehhh bit more than 3/4ths

amber flicker
#

@craggy orbit you can do that by clicking on the #number

zinc plinth
#

@shy pilot never use getter and setter in components

#

It's not how ecs is supposed to work

#

And I don't think that'll even work

#

Struct are blobs 9f packed data in memory

pulsar jay
#

Any idea how I can select one entity and deselect all previously selected?
I am currently trying this:

´´´
var selectedEntity = RaycastPhysicsWorld();
if (selectedEntity != Entity.Null) EntityManager.AddComponent(selectedEntity, typeof(Selected));

Entities.WithAll<Selected>().ForEach((Entity entity, int entityInQueryIndex) =>
{
if(entity != selectedEntity) commands.RemoveComponent<Selected>(entityInQueryIndex, entity);
}).Schedule();
´´´

#

But this just deselects all (including the just selected) entities

amber flicker
#

@pulsar jay I can't guess exactly what's going on. My guess is it's a timing issue related to when the command buffer runs or maybe some issue related to the captured entity. I think you can simplify this though if you want to only have one entity selected at a time by doing e.g.:

// In OnCreate
AnySelectedQuery = EntityManager.CreateEntityQuery(typeof(Selected));
// In Update
EntityManager.RemoveComponent<Selected>(AnySelectedQuery);
var selectedEntity = RaycastPhysicsWorld();
if (selectedEntity != Entity.Null) EntityManager.AddComponent(selectedEntity, typeof(Selected));
pulsar jay
#

Ah thx @amber flicker makes it easier to do it without jobs

amber flicker
#

also bulk manipulations (e.g. EntityManager.XX(query)) of archetype are much faster in general - though maybe not depending on number of entities involved etc - but they're good to use where possible I feel

pulsar jay
#

yeah didnt know yet it was that easy to bulk remove components with entity manager

#

great it works 👍

brazen storm
#

Ideas on handles/dependancies for lambdas and queries?

rancid geode
#

@shy pilot never use getter and setter in components
@zinc plinth there is no problem using getters and setters with burst, I use those myself

zinc plinth
#

@rancid geode if you want spaghetti code and go against dop, be my guest Shrugging

deft stump
#

how is getter and setter cause spaghetti?

zinc plinth
#

it's against dop

rancid geode
#

It is not against dop by any means...

zinc plinth
#

components should be the data inside the struct, if you want derived data use methods inside a utility class

rancid geode
#

If you have internal logic, yes it is, but take for example localtoworld

deft stump
#

if you don't do any operations inside those getter and setter, then... it's not all too different than a normal field, I believe.

zinc plinth
#

@deft stump but then why use getters at all ?

rancid geode
#

components should be the data inside the struct, if you want derived data use methods inside a utility class
@zinc plinth did you already took a look how Colliders works in Unity Physics?

deft stump
#

dunno. but i much prefer to use getter and setter

rancid geode
#

@deft stump but then why use getters at all ?
@zinc plinth take a look on localtoworld to see why

#

Sometimes it just makes the code more readable by having useful getters and setters to read and write the data

#

Like a component with multiple bools, but internally they are one single int to optimize the memory used

tight blade
#

..whats dop?

amber flicker
#

data-oriented-programming

rancid geode
#

Data oriented programming, often called data oriented design too

tight blade
#

oh. I cant imagine dop has an opinion on something as granular as whether or not you use getters and setters

#

that seems wholly orthogonal

rancid geode
#

Getter/setter are just language features

#

And about inheritance, c# doesn't allow inheritance with struct but on c++ using inheritance on ecs components is totally legal and valid in dop

tight blade
#

honestly the whole notion of data oriented design is a bit weird. Its a bit of a chimera of different concerns which may be quite different depending on the target.

Haskell, for instance, is the ultimate Data Oriented Design

#

this is more like Tensor oriented design, honestly

#

for which its kind of ridiculous to presuppose there is a preference between various styles of property access (for the most part)

deft stump
#

the whole notion of dop is just being cache and cpu friendly.
using language features to aide you doesn't break that notion

rancid geode
#

I see that the major pitfall of Unity ecs is that due c# constraints it seems to wrongly teach heir users that some stuff should be avoided on dod, but it is only true due Unity ecs limitations, not because it goes against the "DOD bible"

#

the whole notion of dop is just being cache and cpu friendly.
using language features to aide you doesn't break that notion
@deft stump exactly

tight blade
#

yeah totally

rancid geode
#

Even going oop in ECS is legal as long that is the right tool for your problem

#

Unless you lost some bet, you don't need to go full DOD in the entire program

tight blade
#

yeah I mean whether or not things are a good idea is a different conversation. The static point is that dod doesn't care about your petty implementation concerns. it sits along a different dimension of abstraction and gazes sidelong at your infinitesimal decisions and laughs

#

it hungers only for data volume

#

as you say, if your problem isnt volume oriented, you can safely leave the tensors on the bench

lean raptor
#

Can a Unity Job be a ref struct?

vagrant surge
#

this is code from a personal project

#

not unity, just cpp

#

i have a BossAI component that holds a pointer into an AIImplementation

#

not ecs, thats basically just oop

#

but its literally just for an AI script so who cares

#

you dont need dod on everything

olive kite
#

What is the most efficient way to get component data in a gameobject? entityManager.GetComponentData<Translation>(entityRef).Value; is kind of expensive, .7ms for 1000 calls

amber flicker
#

if you're doing 1000 calls in a frame you want to be using e.g. Entities.ForEach() and filling a persistent NativeArray that you pass to the job I'd guess.

olive kite
#

oh duh, thank you.

amber flicker
#

np - good luck 👍

dull copper
#

@olive kite can you tell what you need that for?

#

when having dots packages installed, it hides the pause and step buttons on the top bar

deft stump
#

well you are using an alpha build so

#

alpha bugs maybe?

craggy orbit
#

oh i didn't realize it was caused by DOTS packages. i thought it was just missing for some reason

#

but yeah i dont have it either in the one project i upgraded

amber flicker
brazen storm
#

what is this AddJobHandleForProducer guff

tight blade
#

OOP vs DOD is a false dichotomy. you can do objects with dod. OOP is bad for totally separate reasons

#

sorry, thats a tangent. continue

amber flicker
#

O = oriented, O != only ¯_(ツ)_/¯ -> Baking Oriented Cooking Vs Frying Oriented Cooking 🧑‍🍳

tight blade
#

yeah and I mean the important thing is that there are some aspects of "purity" that are just literally n/a not applicable to certain design spaces. There is absolutely no question of whether or not something is "pure dod" if it uses oop in its implementation. that level of decision is simply not within the scope of the domain of dod

#

this is one of the reasons data science code is all over the place

#

there are a lot of dimensions of code design that not required to be consistent to take advantage of tensor processing

dull copper
#

@deft stump could be a bug or intentional

pliant pike
#

stupid basic question but whats the correct way to dispose of a nativearray

craggy orbit
#

nativeArrayInstance.Dispose();

tight blade
#

.Dispose() in the same scope you used it, usually

pliant pike
#
 protected override void OnStopRunning()
    {
        m_Query.Dispose();
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();
        m_Query.Dispose();
        
    }

    protected override void OnUpdate()
    {       

        var dudents = m_Query.ToEntityArray(Allocator.TempJob);  

        Entities.WithAll<TestObjectAuthoring>().ForEach((Entity inty, in Translation trundle) =>
        {  
            var toppy = GetComponent<Translation>(dudents[0]);

            //Debug.Log("The entity data is " + toppy.Value);
           

        }).WithoutBurst().Run();

        m_Query.Dispose();
        //Enabled = false;
        dudents.Dispose();
     }```
#

I've tried disposing of it everywhere and I just get errors not disposed correctly etc

tight blade
#

you marked it as persistent

#

hahaha, yeah @amber flicker

pliant pike
#

its meant to be TempJob I just changed it to persistent to check if it worked

tight blade
#

oh man, okay ill let this go through a few drafts before comment lol

amber flicker
#

why are you disposing a query? I'm so confused

craggy orbit
#

and you should mark the array as readonly in the Entities.etc

tight blade
#

Calabi is at that early stage of working with tensors and multithreading

#

where it all feels like boilerplate and black sorcery

pliant pike
#

I've been working with it for ages actually, but I go away and come back and forget everything or things don't work the way I remember leahS

tight blade
#

I hear that

pliant pike
#

I'm just throwing things at the wall when in doubt dispose everything

#

as far as I'm aware the dudents dispose should work fine but it doesn't 😕

amber flicker
#
  1. don't dispose queries, 2) using TempJob then disposing is fine - I doubt this is where you're problems lie, 3) you can just use .Temp and then you don't need to call dispose
pliant pike
#

yeah maybe it's persisting for more than 4 frames etc

amber flicker
#

If you're using .Run, just use Temp if you're allocating within an update. Use persistent when you can.

pliant pike
#

well it seems I can't use Temp with the job anyway 😕

amber flicker
#

probably because you're code doesn't actually look like what you posted 🙂

tight blade
#

I'd advise using the IJobChunk to do most of your work until you get comfortable with it, then switch to using the Entities.ForEach shortcut

#

I know its kind of backwards from the end facing recommendations, but just as a learning process, I cant recommend it highly enough

pliant pike
#
public class EnvironmentCollisionDetection : SystemBase
{
    public EntityQuery m_Query;
   
    protected override void OnCreate()
    {
        base.OnCreate();
    }

    protected override void OnStartRunning()
    {

        var obstucle = GetSingleton<DotPrefabinator>();
        var soment = obstucle.ObstaclePrefab;

        var dudent = EntityManager.Instantiate(soment);
        EntityManager.SetComponentData<Translation>(dudent, new Translation { Value = new float3(0.5f, 1, 0) });
        EntityManager.SetName(dudent, "TheDudeObstacle");

        m_Query = GetEntityQuery(ComponentType.ReadOnly<ObstacleAuthoring>());        


    }

    protected override void OnStopRunning()
    {
        //m_Query.Dispose();
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();
        //m_Query.Dispose();
        
    }

    protected override void OnUpdate()
    {

        //var entobstacles = m_Query.ToComponentDataArray<ObstacleAuthoring>();

        var dudents = m_Query.ToEntityArray(Allocator.TempJob);

        Entities.WithAll<TestObjectAuthoring>().ForEach((Entity inty, in Translation trundle) =>
        {
            var toppy = GetComponent<Translation>(dudents[0]);

        }).WithoutBurst().Run();     
        //Enabled = false;
        dudents.Dispose();
    }
}```
tight blade
#

and lets face it, ecs is all learning at this point

pliant pike
#

that's all the code

amber flicker
#

and the error you receive is?

tight blade
#

I dont think you need to dispose when you use TempJob. I actually have the opposite intuition from @amber flicker

pliant pike
#
Unity.Collections.NativeArray`1:.ctor(Int32, Allocator, NativeArrayOptions)
Unity.Entities.ChunkIterationUtility:CreateEntityArray(UnsafeMatchingArchetypePtrList, Allocator, EntityTypeHandle, EntityQuery, EntityQueryFilter&, JobHandle&, JobHandle) (at Library\PackageCache\com.unity.entities@0.14.0-preview.18\Unity.Entities\Iterators\ChunkIterationUtility.cs:265)
Unity.Entities.EntityQueryImpl:ToEntityArray(Allocator, EntityQuery) (at Library\PackageCache\com.unity.entities@0.14.0-preview.18\Unity.Entities\Iterators\EntityQuery.cs:456)
Unity.Entities.EntityQuery:ToEntityArray(Allocator) (at Library\PackageCache\com.unity.entities@0.14.0-preview.18\Unity.Entities\Iterators\EntityQuery.cs:1203)
EnvironmentCollisionDetection:OnUpdate() (at Assets\MyStuff\Scripts\BoxIntersectionCheck.cs:62)
Unity.Entities.SystemBase:Update() (at Library\PackageCache\com.unity.entities@0.14.0-preview.18\Unity.Entities\SystemBase.cs:397)
Unity.Entities.ComponentSystemGroup:UpdateAllSystems() (at Library\PackageCache\com.unity.entities@0.14.0-preview.18\Unity.Entities\ComponentSystemGroup.cs:513)
Unity.Entities.ComponentSystemGroup:OnUpdate() (at Library\PackageCache\com.unity.entities@0.14.0-preview.18\Unity.Entities\ComponentSystemGroup.cs:461)
Unity.Entities.ComponentSystem:Update() (at Library\PackageCache\com.unity.entities@0.14.0-preview.18\Unity.Entities\ComponentSystem.cs:107)
Unity.Entities.DummyDelegateWrapper:TriggerUpdate() (at Library\PackageCache\com.unity.entities@0.14.0-preview.18\Unity.Entities\ScriptBehaviourUpdateOrder.cs:333)```
tight blade
#

I think Temp needs to be disposed, TempJob will get auto deallocated... oh, actually it needs to be marked for deallocation as a field

#

Entities.ForEach is gonna be tricky if youre working with an Array

pliant pike
#

I also get the 4 frame job warning

tight blade
#

because you dont know what its compiling your code into with that Entities.ForEach magic

#

whenever Im operating on nativearrays, I use a job explicitly

pliant pike
#

oh and that error only comes up after I stop the program as well

#

and if I comment out this line var toppy = GetComponent<Translation>(dudents[0]); and then use dudent.dispose() everything seems to work fine no errors 😕

amber flicker
#

yea I did wonder if the real issue was hidden

#

you don't seem to have a check for if the array .Length > 0

pliant pike
#

so that's caused another completely unrelated error 😕

amber flicker
#

@tight blade fairly sure about Temp's dispose being no-op and dispose being required for TempJob (whole point being it can allocate for multiple frames - long enough for a job to run in parallel). Also nothing wrong with using arrays and lambdas.

#

@pliant pike hard for me to say concretely - the safety system isn't perfect. Could be worth reporting as a bug if you verify it's actually a nullref exception

brazen storm
#

Hey gang! Best way to test for a change in a component variable?

pliant pike
#

thanks for help guys, I'll chalk this one up to my usual stupidity

amber flicker
#

@pliant pike that error should have told you nullrefexception if that's what actually was going on - don't feel bad - is a little tricky to remote debug that kind of thing though.

#

@brazen storm if (previousVal != currentVal) ? Or you mean something else?

brazen storm
#

no no no. I mean the query returns when changed components? unless that's dumb. in which case nevermind

pliant pike
#

yeah I normally ignore some errors I usually get like objects does not exist etc because I haven't sorted the order of systems and it usually still works through them

amber flicker
#

@brazen storm you can only detect that there's been a change to a chunk - not to a particular entity without iterating through them. You can hash components for faster comparison but e.g. the 'SetChangeFilter' methods filter on the chunk level

brazen storm
#

ok tnx @amber flicker

warped coral
#

what game genres benefit most from DOTS?

amber flicker
#

off the top of my head: wave shooters, bullet hell, rts, deterministic networked stuff etc

warped coral
#

can dots handle making a cubey voxel-like game except with actual objects for each cube?

amber flicker
#

sure.. so can anything. If you mean "is it fast enough to do X" - that will depend on many things but it's generally faster than traditional Monobehaviours

dull copper
#

I'd debate on that :p

#

I'd draw the line in it being generally faster in brute force kinda scenarios

#

but it's also hard to draw the like on what is actually DOTS since Unity internally uses the same job system under the hood as well

amber flicker
#

I'd agree right now - though hopefully in the next few months that won't be the case. Joachim has basically stated the goal is to see 1 entity being processed and scheduled by 1 foreach should be cheaper than monobehaviour.Update().

ocean violet
#

Hey guys. Can anyone tell me how can I add meshcollider to entity? I'm able to create a mesh with a bunch of vertices and triangles just fine but I can't find any resources that can help me attaching meshcollider to entity. Using monobehaviour, it is just a matter of adding meshcollider and setting meshCollider.sharedMesh = mesh

deft stump
#

you need to have Unity Physics

#

can't remember how to add mesh colliders but I believe mesh collider isn't supported? don't @ me on that.
all I remember are box colliders.

ocean violet
#

already did include that. But EntityManager.AddComponent(entity, ComponentType.Create<MeshCollider>()) doesn't seem to work

#

Am i looking at the right place?

rancid geode
brazen storm
#

quick headScratcher. If Im getting a singleton component into a var. can I edit it and pass it back with SetSingleton???

#

like I edit fuelComponent above

deft stump
#

you can

brazen storm
#

@deft stump aww nice!

#

like fuelComponnet.value = bleh, SetSingleton<VehicleFule>(fuelComponent)

#

While you are here I'm trying to destroy an entity. I put it onto a Dynamic Buffer and I'm calling destroy from the command buffer but the prefab remains.

#

could have done a buffer of the IDs?

#

I don't get why this fails

olive kite
#

@olive kite can you tell what you need that for?
@dull copper It is to copy transform data to a gameobject.

dull copper
#

@olive kite in that case there are more efficient ways to do that. For example you can take a look at the old GameObjectEntity stuff on how they did it there (look at CopyTransformToGameObjectSystem)

#

basically they used TransformAccess array on a job to pass the transform from entities to gameobjects there

#

it probably still works if you manually add CopyTransformToGameObject to your entity component data

olive kite
#

oh ok cool. I am also running it through jobparallelfortransform, but probably not passing the data I'm using for that efficiently

#

i need to do it at a very specific time because of how I am transfering the animation data to the entities

dull copper
#

there's basically a ready made setup for all this, you could just copy it for your use cases

olive kite
#

yeah

#

ill check out that system.

#

thank you @dull copper

amber flicker
#

yea maintaining the list of transforms is the only slightly painful part but definitely worth it to be able to do off main thread (even if it's only a single thread)

dull copper
#

I dunno if there's even better ways to handle that now, that system was just something I learned from this channel a long time ago

#

been using that approach on my dots prototypes where I don't use hybrid rendering

olive kite
#

yeah that's what i need to do, i am assigning it in the job but holding the data on main

#

But i need to do it 3,000 times per frame

amber flicker
#

think it's still the best way afaik - I think it makes sense that there's a special case where the c++ knows you may set them

olive kite
#

ok

#

i am pretty sure i will ahve to setup an LOD-like system to lower the update rate on further entities

#

and i may be going down the wrong path completely. I am still doing all the animation and transform tweens in the GO and passing it to entity

amber flicker
#

if it's helpful, as an estimate - the read and write time (not inc e.g. interpolation) for 3000 transforms is about 1ms (more like 0.8 but current schedule overhead etc) from my quick test (3900x but it's only using one thread) - only providing as an order of magnitude reference

olive kite
#

ok cool yeah i did some testing and it seemed fine but when it's on the GOs it's a little less favorable, and there are still a lot of things to make efficient. the movement calculations from pathfinding is done in the same call so that is next on my list

#

yeah it should be fine , just the transform assignment piece

#

it's exciting though, once you get it lined up, burst is incredible

amber flicker
#

make sure you've got leak detection and burst safety checks off if you're looking at gc or timings at all

olive kite
#

physics simulation at 3.5 seconds with only 100 enemies, so thats a problem too

#

ok ill try that i think burst safety is on

amber flicker
#

also make sure burst is enabled 🙂 - that physics sounds too slow

olive kite
#

yeah i know, not sure whats going on there. i tested with large numbers and it was much lower

amber flicker
#

as I'm sure @dull copper will chime in 🙂 - physics perf suffers quite badly with many threads so currently there's an option to limit them if you're using 32 cores or whatever - definitely check in an attached build before doing anything else though

olive kite
#

i think i see what it is,

#

yeah i limited it to 4 worker threads, ran into that problem too

#

that would be from calling .Complete in code i assume?

amber flicker
#

that gc looks like editor checks to me - do any of your jobs have (Burst) in their names? There are some safety tests you can't disable in-editor I think. Anyone know if that's still true?

olive kite
#

so it looks like it should be 1/3 of that

#

I don't think so on the Burst names

#

ill check

#

i think i saw that fixed in the last release notes

#

i appreciate your input, thanks

amber flicker
#

oh haha yes.. logs would do it

olive kite
#

yeah, i looked for debug.log but forgot about the warnings

#

most problems are solved by explaining them

lean raptor
#

Can I use the lock statement inside a Unity Job?

#

And if I allocate an object inside a Unity Job, must I pin it?

craggy orbit
#

Lock works the same as try catch, afaik. If so, no you cannot use it in a job

#

you can use try catch, but you just can't catch 🤔

#

it doesnt mention lock support, from what i can tell

stiff skiff
#

He didn't specify Burst though, just Jobs

shy pilot
#

how does one run .complete on a scheduleparralel foreach

craggy orbit
#

Burst and Jobs are normally used together so i dont think my assumption was too far off

median mesa
#

If anyone wanna start a DOTS learning/portfolio project or more, hit me up!

shy pilot
#

can someone please explain how you run Complete() on a job generated by foreach

coarse turtle
#

Entities.ForEach((...) => {}).Schedule(...).Complete() or ScheduleParallel

#

pretty much you can only call complete on the job that has been scheduled

shy pilot
#

hmm

#

intellisense can't see that for some reason

#

will try when i get the chance

#

thanks :)

coarse turtle
#

try regenerating the csproj files in your project settings

shy pilot
#

yeah

valid haven
#

one thing that isn't very clear to me with this new DOTs framework is what and when things need to be disposed

shy pilot
#

i've found taht i have to do that quite a lot lately

#

if its native

#

you should always dispose of it as soon as you are done using it

valid haven
#

dispose of what tho

shy pilot
#

usually at the end of a job or when a system is destroyed

coarse turtle
#

you typically dispose native data when you're done with it or whenever you need to

valid haven
#

hmm ok. Other question I have... if I need to ensure the job is completed before the next frame how do I handle that? For example say I need a job to complete within one deltatime (e.g. situation where every entity within the foreach needs to update per frame so it matches up with physics steps).

shy pilot
#

Entities.ForEach((...) => {}).Schedule(...).Complete() or ScheduleParallel
@coarse turtle

coarse turtle
#

@valid haven maybe you can run it on the fixed step

valid haven
#

does that happen before or after physics update?

coarse turtle
#

you can probably have a component system group run before the physics update

#

using the FixedRateUtils

valid haven
#

ok thanks

shy pilot
#

@coarse turtle my ide says that schedule returns void so i can't run complete?

coarse turtle
#

That's not true since schedule returns a JobHandle

#

does it compile in Unity?

shy pilot
#

i will check

#

it doesn't seem to return a jobhandle

zenith wyvern
#

Show the code where you're scheduling it

shy pilot
#

am i missing something really obvious 😆

#

ohh

#

do i need a jobhandle?

#

.__.

zenith wyvern
#

Are you sure you can put multiple things in WithNone?

shy pilot
#

um

#

doesn't None imply there are multiple things

#

wouldn't it be Without otherwise?

#

ok, i changed it from SystemBase to JobComponentSystem

zenith wyvern
#

Oh right you only get a handle back if you pass in a jobhandle I think

shy pilot
#

and there are no more compiler errors

zenith wyvern
#

Pass in Dependency to Schedule

shy pilot
#

yeah

#

what are the differences between SystemBase and ComponentSystem?

zenith wyvern
#

ComponentSystem was for main thread stuff only but I believe it's going to be deprecated at some point. We're only meant to use SystemBase now

safe lintel
#

component system is just the old mainthread version of systembase which does both main and job thread(jobcomponentsystem was the job version)

shy pilot
#

so what is the new version of JobComponentSystem?

zenith wyvern
#

SystemBase replaces both

shy pilot
#

oh

zenith wyvern
#

It does some internal stuff to be smarter about dependencies

#

Requires a bit less work and is faster in some cases than JobComponentSystem

shy pilot
#

so i can just change override void OnUpdate() to override JobHandle OnUpdate(JobHandle dependency)

safe lintel
#

also if you havent already stop using IJobForEach/IJobForEachWithEntity etc because that is deprecated too

zenith wyvern
#

No change your Entities.WithNone<>().Foreach().Schedule() to var job = Entities.WithNone<>().ForEach().Schedule(Dependency);

#

It will only return the job handle if you pass in a job handle to schedule

shy pilot
#

yep

#

but do i need to get that jobhandle through OnUpdate?

#

or can i just make one?

coarse turtle
#

well typically you can grab the Dependency variable from SystemBase

zenith wyvern
#

The Dependency property in SystemBase is the jobhandle that your system depends on

safe lintel
#

OnUpdate is void now

zenith wyvern
#

It's set up automatically by the class so you can use it in OnUpdate

shy pilot
#

ah ok

#

but how do i fetch that jobhandle from update so i can run .Complete 😆

#

or do i just make a new jobhandle

#

ohh

#

i get it 😆

#

thanks :)

#

.Complete Blocks right?

#

just checking

deft stump
#

yup

shy pilot
#

so the main thread can't continue until that's done?

#

so you're basically writing single threaded code

#

but with extra steps

#

is there a way to make an entity buffer automatically playback on completion?

#

so that i can still keep the benefits 😆

zenith wyvern
#

On completion of what?

#

If you mean after a job completes - you can't "schedule" main thread code to run after a job completes. You either wait for it to finish and check each frame with if( jobHandle.IsComplete ) or force it to finish with Complete()

#

What are you trying to do exactly?

shy pilot
#

i have some code that updates the state of an entity by adding and removing components

#

which would be done in parralell ideally

#

but i need to make sure any structural changes are done

#

but thinking about it now

#

it doesn't really matter

#

cause its all executing in parallel anyway

#

even if i have to wait for it, it's still much faster

shy pilot
#

um, a quick question about IJobParallelFor is giving it a scriptable object considered too oop-land

#

cause i could just copy the fields from the scriptableobject but it seems a bit pointless

#

but if that is going to break burst can someone let me know 😆

deft stump
#

If you're using an SO, then I guess the best way is to make a BlobAsset out of it

#

so it won't break burst

half jay
#

i have system which create new collider if new BlockType Changed. Should i dispose _collider? or 1st i should destroy collider and then dispose blob asset ref and then create new ?

olive kite
#

does anyone know what might be causing these debugstream job completes? it's extending my physics step to 5+ ms

deft stump
#

Are you calling .Complete() ?

steady blaze
#

@zenith wyvern nice, didn't know there is a jobHandle.isComplete - but good to know!

golden heron
#

Anyone got experience with the jobs system? Im trying to have one job write to an array, then a second job read from it, but without calling .Complete() in between?

public struct FirstJob : IJobParallelFor
{
     public NativeArray<Vector3> input;
     public NativeArray<Vector3> output;
     public Execute(int index)
     {
           output[index] = input[index];
     }
}
public struct SecondJob : IJobParallelFor
{
     public NativeArray<Vector3> input;
     public NativeArray<Vector3> output;
     public Execute(int index)
     {
           output[index] = input[index];
     }
}

public void RunJobs()
{
     NativeArray<Vector3> firstArray = new NativeArray<Vector3>(objectCount, Allocator.Persistent);
     NativeArray<Vector3> secondArray = new NativeArray<Vector3>(objectCount, Allocator.Persistent);
     var first = new FirstJob
     {
           input = firstArray,
           output = secondArray
     }
     Jobhandle handle = first.Schedule(objectCount,1);
     NativeArray<Vector3> thirdArray = new NativeArray<Vector3>(objectCount, Allocator.Persistent);
     var second = new SecondJob
     {
           input = secondArray,
           output = thirdArray
     }
     handle = second.Schedule(objectCount,1,handle);
     handle.Complete();
}
olive kite
#

@deft stump no, I went through and made sure

#

ill double check. That's what I assumed but couldn't find any place it was being manually executed

golden heron
#

Any thoughts guys?

olive kite
#

@golden heron is that causing error?

golden heron
#

it moans about the second job accessing an array which is being accessed by the first.

olive kite
#

it looks like you are using dependency of the first job in the schedule of the second which is correct

#

ok let me see..

golden heron
#

This is pseudocode, to show the point without bogging down with complex code.

olive kite
#

oh

golden heron
#

(Each struct is over 100 lines easy)

#

But, Crypto, any thoughts you have are appreciated, even if you dont feel confident... Im a little lost myself atm. :)

#

The above code should work tho, assuming it was added to a class with a private variable for object count, and you added some values to the array, and actually disposed them correctly.

hollow sorrel
#

@golden heron add [nativedisableblahblahlongname] to your input arrays

golden heron
#

NativeDisableParallelForRestriction i think?

hollow sorrel
#

guess safety system doesnt know theyre not running at same time

#

yea

golden heron
#

Is that a new thing do you know?

hollow sorrel
#

i think its as old as the safety system

golden heron
#

Like, the attribute, ive found some code doing it but it isnt clear how

#

The only difference seems to be the arrangement of read/write only attributes, i was hoping to find someone who could say what it is clearly. Ill try that tho.

#

The confusion is that the code i found doesnt use that attribute at all

#

Ok ima just try both... are you interested to hear the result if i find an exact answer, @hollow sorrel

#

"First of all [NativeDisableParallelForRestriction] not solves safety restriction, it's only allow you to write to any index of passed array (if you sure in safety) in same job - solves parallel for restriction." -> from unity forums

olive kite
#

yeah that is for same job I thought

golden heron
#

It is, apparently

#

And therefore isnt relative... and... i just found some stuff suggesting i completely misinterpreted what the problem is hehe

hollow sorrel
#

what do you mean

olive kite
#

that it tells the system it is okay to bypass the safety in place to avoid parallel tasks operating on the same array for a particular job

#

but I've not used on multiple jobs before so can't comment

golden heron
#

it apparently just lets you access indices outside the range of the batch count you initialise the job with

olive kite
golden heron
#

Atm, the problem appears to be related actually to the system not realising that a jobhandle has been completed when in fact it has, but, as part of a combined jobhandle

#

I should probably mention i am using jobs+burst without ecs

olive kite
#

hmm, It is supposed to recognize jobhandles link of dependencies , is that a bug

#

Yeah, idk. that's how I run my jobs, though I just pass the dependency to the schedule call, that's the only difference I see

golden heron
#

Im individually storing the jobhandles now, and individually completing them in order, but, from late update after having scheduled everything in update.

#

Oh, that seemed to work...

olive kite
#

does it work

golden heron
#

Now i have a new error, but, this one is completely different and likely came after all the stuff from before has been completed, which suggests the list of jobhandles worked better.

#

I think the new error was an attempt to dispose an uncreated array... But... that message aint clear at all

hollow sorrel
#

whats the error

#

if youre still getting it

golden heron
#

Im not now, im just trying to figure out if that is because the problem is solved, or because the other errors are stopping the execution before it happens, it seems i have some incorrectly handled NativeCollections so im just debugging the dispose behaviour, and then ill let you know what/how was done.

#

Ok, so i think that somehow i misinterpreted the original problem based on an incorrect understanding of the error message.

#

The error message was stating something wrong with the nativearray, but the the problem was the inability for the job system to preserve the reference (im guessing that bit) to the handle correctly, when you combine them, so that from the job safety system the handle being checked was a lost handle, replaced by the one which was combined. What specifically happened was that the native array being accessed was in fact requiring the .Complete on its job handle... which was already done, but, incorrectly registered with the job system. The simple solution was a single list of jobhandles instead of a combined handle, and the list is naturally iterated in the order the jobs are added and scheduled, meaning that whilst there is the possibility to be inefficient, there is a good chance it will be ok, short of running some while loop that waits by independently checking "isCompleted" before calling complete, and allowing each to complete at their own speed, i cant think of another solution ... and doing the while loop seems painful and wasteful.

#

@hollow sorrel

#

and... excuse my french but holy sheeshkabob batmen!!! the increase in speed here is incredible...

#

My game has been running slow for a while, hence the decision to bite the bullet and convert.

#

I started by converting the logic to jobs and completing everything and disposing everything right there, so, im kinda using the job system as a sequential single thread, but it allowed me to get the logic into the jobs and back. This worked... and in spite of the inefficiency gave me a small 5-10% speed boost. Next job... Make the allocations in update, and complete in lateUpdate.

#

I just went from 15fps up to 70-90fps 😮

#

(rendering options are currently set low to allow me to work on the cpu side of things)

hollow sorrel
#

so if i understood correctly, youre manually iterating each jobhandle and completing them in order instead of schedule them with dependencies?
if so that sounds dangerous, what if the 2nd job completes by itself before the 1st?

golden heron
#

hehe typical, the screenshot reads a lower fps

hollow sorrel
#

also nice to hear the speed increase, are you already using burst?

golden heron
#

They are scheduled with dependencies

#

Yes, burst is why i am doing this. I already wrote my own multithreading system, so the jobs system was not really that interesting, but, the burst is ... god in a struct.

hollow sorrel
#

👍

golden heron
#

Thanks for your comments tho dude. 🙂

olive kite
#

is there any way to set a dependency of a job to be all the other currently scheduled jobs without forcing completion ?

#

I am getting a "previously scheduled job" error from a job called "CheckStaticBodyChangesJob" which I assume is something unity is doing, but the conflict is modifying translation array

#

but usually [UpdateAfter(typeof(ExportPhysicsWorld)), UpdateBefore(typeof(EndFramePhysicsSystem))] prevents that in previosu experiences

zenith wyvern
#

I don't think so. It sounds like a job from a physics system. You can get the system then get it's job handle to depend on with physicsSystem.GetOutputDependency()

olive kite
#

ok perfect that's what I'm looking for

wet epoch
#

anyone know how i can do something like this without getting an error? (writing to an array in an Entities.Foreach lambda in 1 system, and reading that array in another) https://hatebin.com/fpqzvrezjm

#

i don't understand why it works with a Job.WithCode().Schedule(), but not a Entities.ForEach().Schedule()

coarse turtle
#

I think you might want to expose the JobHandle from SystemA to SystemB or combine SystemA and SystemB but have 2 separate jobs

wet epoch
#

those would be workarounds, just wondering if there's a better pattern where i can use arrays in other systems

#

i guess if i'm accessing the other system to get the array, it's not too much extra code to get the job handle

coarse turtle
#

I guess the alternative is to have it on an Entity and you query for that specific entity, so SystemA and SystemB depend on Entity with an UnsafeArray/DynamicBuffer that run after each other

wet epoch
#

what is the Dependency that we're given? i thought that should include previous systems

#

can i specify a dependency for cases like this?

coarse turtle
#

so I'm not exactly sure how the deps are passed around, pretty sure it's in the source code if you want to see how it exactly works, but I'd assume it's like what you said - given the dependencies of the previous jobs scheduled

wet epoch
coarse turtle
#

Oh I'm not sure about the new DOTS systems tab, I still use the Entity Debugger

wet epoch
#

i'm not sure that shows dependencies (i don't know how to see them)

coarse turtle
#

yea sorry, I'm not sure either on that case

wet epoch
coarse turtle
#

hmm

wet epoch
#

i could try storing it on an entity, just feels wrong when it's big arrays

coarse turtle
#

Well if it's too big, it would be stored into the heap

zenith wyvern
#

Can you post the actual error?

#

Which system is it complaining about?

wet epoch
#

it's in the first hatebin link

#

InvalidOperationException: The previously scheduled job SystemA:OnUpdate_LambdaJob0 writes to the Unity.Collections.NativeArray1[System.Int32] OnUpdate_LambdaJob0.JobData.arr. You are trying to schedule a new job SystemB:OnUpdate_LambdaJob0, which reads from the same Unity.Collections.NativeArray1[System.Int32] (via OnUpdate_LambdaJob0.arr). To guarantee safety, you must include SystemA:OnUpdate_LambdaJob0 as a dependency of the newly scheduled job.

zenith wyvern
#

Weird, your second example gives that same error?

wet epoch
#

yeah

zenith wyvern
#

From what I'm seeing it should be working I think. Maybe it's due to Unity's weird changes to UpdateBefore/UpdateAfter that they are reversing next update

wet epoch
#

the file is self contained if you want to test it

zenith wyvern
#

Try adding UpdateBefore to SystemA as well maybe

wet epoch
#

k

#

same error

olive kite
wet epoch
#

Window > DOTS > Systems

olive kite
#

Yeah i see it in the ecs sample but not in my other project

zenith wyvern
#

I think it's the new dots editor package

#

It was completely broken when I tried to use it last time

wet epoch
#

it gives errors sometimes (like when stopping the game)

#

but when it works it appears to show accurate info

olive kite
#

yeah i don't have it in mine , weird

wet epoch
olive kite
#

must be dots editor

zenith wyvern
#

Like everything else it's a hidden package. You need to add com.unity.dots.editor from the package manager

wet epoch
#

hmm storing the data in a dynamic buffer would work for this simple test case, but it wouldn't work for like nativemultihashmaps :/

#

which is one of the use cases i have for it (putting entities in 'quadrants' and reading nearby entities from multiple systems)

coarse turtle
#

you can use the unsafe version and put that into an IComponentData/ISystemStateComponentData

wet epoch
#

hmm the error has changed InvalidOperationException: The previously scheduled job SystemB:OnUpdate_LambdaJob0 reads from the Unity.Collections.NativeArray`1[System.Int32] OnUpdate_LambdaJob0.arr. You are trying to schedule a new job SystemA:OnUpdate_LambdaJob0, which writes to the same Unity.Collections.NativeArray`1[System.Int32] (via OnUpdate_LambdaJob0.JobData.arr). To guarantee safety, you must include SystemB:OnUpdate_LambdaJob0 as a dependency of the newly scheduled job.

#

it's trying to do SystemA second now :/

#

doing the dependency thing i did in the second hatebin seems to make SystemA run first (According to the error)

#

unless it still thinks its being read from next frame...

thorny halo
#

Is it possible to use function pointers with the job system? I need to determine which function to use based on some parameters. This function will be called many times, however, it's preferable that the evaluation of which function to call would only happen once, rather every single time. Atm I'm just using a switch statement in another function to determine which function to use.

The only thing i can think of the top of my head would be to create a different struct for every different function and then just evaluate which struct should then be used, though that's a pretty ugly solution.

Pseudo code: https://pastebin.com/QNH31Zke

rancid geode
#

basically you want to expose the sysA dependency and ensure that sysB has sysA as dependency

wet epoch
#

this one works (passing dependencies both ways)

#

but seems a bit ridiculous.. trying yours now

#

yeah, with that one you pasted it gives InvalidOperationException: The previously scheduled job SystemB:OnUpdate_LambdaJob0 reads from the Unity.Collections.NativeArray`1[System.Int32] OnUpdate_LambdaJob0.arr. You are trying to schedule a new job SystemA:OnUpdate_LambdaJob0, which writes to the same Unity.Collections.NativeArray`1[System.Int32] (via OnUpdate_LambdaJob0.JobData.arr). To guarantee safety, you must include SystemB:OnUpdate_LambdaJob0 as a dependency of the newly scheduled job.

#

as if it still thinks it's being written to the next frame

rancid geode
#

passing both ways does makes sense actually, considering that there is no sync point in your logic currently

wet epoch
#

aren't system groups automatically sync points?

zenith wyvern
#

I would have thought it would sync automatically at the end of the frame, I guess not

rancid geode
#

because system B may still be running when system A is scheduling a new job

zenith wyvern
#

So it does seem like it's carrying over to the next frame

rancid geode
#

aren't system groups automatically sync points?
@wet epoch no

#

sync point only happens if you call some method from EntityManager that causes one (CreateEntity, DestroyEntity, AddComponent, RemoveComponent...), or if you use an ECB method causes one (same ones as the EntityManager)

#

if no sync point happens, each system can run one whole frame (each system auto-complete its previous frame dependency each frame)

wet epoch
#

i assume if you modify some components like Translation too?

rancid geode
#

i assume if you modify some components like Translation too?
@wet epoch SetComponent doesn't cause sync point

zenith wyvern
#

I basically use this pattern all over the place in my code but yeah I use ECBs so I guess it was just by chance that I wasn't getting dependency errors from it

#

Because I use ECBs all over the place

#

You learn something new every day

rancid geode
#

sync point is not the same as completing all jobs that use some component, sync point is where all jobs gets completed (don't matter which component type is being used)

#

setcomponent does causes all jobs that affects the given component to be completed, but not a "full" sync point

wet epoch
#

yeah i had no idea it worked like that :/

#

i assumed when you set Dependency, that Dependency gets completed as part of the system group

#

or at least gets passed to dependent systems

zenith wyvern
#

if no sync point happens, each system can run one whole frame (each system auto-complete its previous frame dependency each frame)
@rancid geode

But based on the dependency error SystemB does not autocomplete at the end of the frame

rancid geode
#

it auto-completes before runing OnUpdate again, not at the end of the frame

zenith wyvern
#

Ahh okay, that makes sense

#

Gotcha

wet epoch
#

why does it work if I do Job.WithCode().Schedule() instead of Entities.ForEach().Schedule() though :/

rancid geode
#

it is like that:

JobHandle previousFrameDependency;
internal void OnUpdateInternal()
{
    previousFrameDependency.Complete();
    OnUpdate(); //defined by user
    previousFrameDependency = Dependency;
}
#

not exactly that, but you got the point

#

why does it work if I do Job.WithCode().Schedule() instead of Entities.ForEach().Schedule() though :/
@wet epoch luckily (or unluckily) it is getting completed earlier probably

#

thus not causing issues with the Scheduling

wet epoch
#

so to make this practical i guess i need to work out a way to make B finish at the end of the system group

#

and i guess i have to manually combine A's dependency in B :/

rancid geode
#

so to make this practical i guess i need to work out a way to make B finish at the end of the system group
@wet epoch I don't think you want to force that, just combining B dependency into A's should be better

wet epoch
#

and A into Bs?

zenith wyvern
#

It's really silly that you have to do a whole circular dependency thing

rancid geode
#

like what the physics systems do:

sysB OnUpdate:
Dependency = CombineDependencies(Dependency, sysA.GetDependency());
// foo
sysA.AddDependency(Dependency);

syaA AddDependency(JobHandle input):
Dependency = CombineDependencies(Dependency, input);

wet epoch
#

in the actual usage, there might be 5 Bs and 1 A

rancid geode
#

sysA doesn't really need to know about other systems

#

let the other systems handle that mess

#

another option you have is to make you shared array be an dynamic buffer and attach it to a singleton entity

wet epoch
#

if i pretend there's a ECB it seems to fix it

rancid geode
#

this way Unity will automatically do all that dependency stuff for you

wet epoch
#

then i would need to make a sync point every time I want to use the collection in a job though?

#

(assuming the job is using another query)

rancid geode
#

why a sync point?

wet epoch
#

to GetSingletonEntity?

rancid geode
#

GetSingletonEntity doesn't cause a sync point at all

wet epoch
#

oh ok

zenith wyvern
#

If your container is just a list you'd be much better off using a buffer like Bruno suggested. You should only need that pattern if you need to share other kinds of containers

rancid geode
#

just ensure to get the entity, not the component directly (as getting the component directly would cause the jobs for that component to complete, which you don't want to)

wet epoch
#

yeah the big one is a nativemultihashmap

rancid geode
#

then use GetComponent inside the Entities.ForEach/Job.WithCode (which uses GetComponentDataFromEntity internally)

wet epoch
#

i think i'll use an entity for any lists/arrays though to avoid this mess

#

ah right, makes sense

rancid geode
#

hopefully they will make dealing with native containers less clunky in the future, but for now those are the recommended approaches

wet epoch
#

i've done a fair bit of this stuff before and never come across these problems :/

#

not sure if it's a coincidence or something's changed and made it harder

zenith wyvern
#

Like me it was probably just a coincidence that you were using ECBs

rancid geode
#

just coincidence, it was just recently that I found that too, most of the time I was causing a sync point and never noticed so far haha

zenith wyvern
#

Realistically any game is going to need a sync point somewhere

wet epoch
#

yeh, just less is better obviously

#

if i'm going to put myself through this i want to get best perf i can out of it 🙂

#

[DependsOn(typeof(SystemA))] would make a lot of sense

#

or for UpdateAfter to just combine it with Dependency automatically

#

even just making Dependency public would help if they intend for us to combine manually

rancid geode
#

Dependency public couse cause issues with people using the "=" operator, but having AddInputDependency and GetOutputDependency for SystemBase built-in would be cool haha

#

[DependsOn()] would be even cooler, nice idea

#

but having a hashmap / multihashmap -like dynamic buffer equivalent would solve that too (and other issues)

#

who knows, still a long way until 1.0

wet epoch
#

yeah, thanks for your help anyway (and Sark and psuong)

#

i'll begrudgingly add the extra boiler plate 🙂

olive kite
#

getting dots to work nicely with a* pathfinding project, but the physics step is still way too long for 200 units, at 8ms, using sphere colliders too

wet epoch
#

unity physics? (the systems are cut off)

olive kite
#

havok

#

yeah

wet epoch
#

yeah that seems slow :/

#

for 200 spheres

#

have you tried switching to unity physics?

olive kite
#

ill try that now

amber flicker
#

do you have vsync enabled? Wondering if there's some weird thing where it's trying to do 10 physics updates per frame or something... seems unlikely but that is terrible perf

olive kite
#

no, not enabled. I have worker threads at 4 as well (previously was way higher with more worker threads)

amber flicker
#

I mean, you possibly want vsync enabled - at least to try.

olive kite
#

oh ok ill try enabling

amber flicker
#

that looks like 3 physics steps which is odd if you're not doing that manually (I think - having never used physics)

olive kite
#

the fixed step group

#

yeah i'm not

wet epoch
#

that's only 6ms total?

#

for simulation

olive kite
#

yeah, it bounces 6-8

#

with 200 units

wet epoch
#

looks like it's doing several physics steps in the frame

olive kite
#

exactly, that's what im confused about

amber flicker
#

what's your physics update rate vs frame rate?

wet epoch
#

i guess because playerloop is 24ms

amber flicker
#

yea.. you may be experiencing a type of death spiral - the more you miss frame rate, the more physics step take place (fixed update) and the slower things get

olive kite
#

i see what you mean

wet epoch
#

so a physics step is really like .5ms

#

excluding the debug part

#

just need to optimize other stuff so less of them run

#

is there a reason all your hoverdrones are gameobjects?

safe lintel
#

yeah 200 pure ecs sphere colliders is nothing, but them being gameobjects might be introducing some sort of lag somewhere

olive kite
#

yeah, @amber flicker you were right, it scales based on playerloop timing. considering it's fixed, should have been obvious

#

@safe lintel the update functions are less than 1ms, but determinalistic updates on animations are a bit more, so focusing on that now

#

I think its a few different fixed update methods across the board all adding up

safe lintel
#

any reason those drones are gameobjects and not pure ecs entities? if they dont have skinned animations i would think they'd be better suited as just entities during runtime

olive kite
#

the entire animation setup is through a tween system. Pure is the goal but trying to convert over a piece at a time

#

right now anims and pathfinding still ran through the GO

#

it seems like the editor is killing it. editor frame time is super high and causing a lot of fixed timesteps to repeat 3-4 times

safe lintel
#

what are those two other fixedupdates, something objectmanager?

olive kite
#

the first two were from my character controller, i found out what was causing that and fixed it, but the physics step is still on rapid fire

dull copper
#

I guess no new dots packages today 🤔

stiff skiff
#

They saw the cyberpunk delays and figured why not

valid haven
#

@dull copper what are we expecting to drop in the new dot packages?

safe lintel
#

think they mentioned the 29th

#

but you know how those estimates go..

deft stump
#

we shouldn't have jinxed it :notlikethis:

craggy orbit
#

my bad 😦

shy pilot
#

hehe

#

as excited as i am to have dots closer to completion

#

i'm not looking forward to having to rewrite half my code cause they deprecated something 😅

#

but that's what i signed up for i guess ¯_(ツ)_/¯

deft stump
#

I'm pretty sure nothing's gonna be deprecated if you stick to the latest.

safe lintel
#

oh snap it was yesterday that the updates were scheduled 😆

hollow jolt
#

what does System.InvalidOperationException: HashMap is full mean ?

shy pilot
#

@hollow jolt you need to expand the hashmap

#

while they do have a .add method

#

they can't make themselves bigger

#

you need to check if you need to increase the size of the hashmap before adding stuff

shy pilot
#

is it not possible to use an entitycommandbuffer in an IJobParallelFor?

#

when i do it i get this InvalidOperationException: The Unity.Entities.EntityCommandBuffer has been declared as [ReadOnly] in the job, but you are writing to it.

#

and when i remove the readonly i get this

#

InvalidOperationException: SpawnStartingPopulationJob.buffer is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.

#

i take it that means you can't make structual changes from a parallel job

zinc plinth
#

ecb.AsParallelWriter or .toConcurrent I don't remember

#

Basically 99% of native Co trainers have a parallel writer api because most operations can't be multithreaded without race conditions showing up

#

@shy pilot

shy pilot
#

ok, thanks

#

i'll have a look

#

what does the sortkey paramater mean in the parallel setcomponent method?

#

all the methods take it as a first parameter

#

do i just pass the job iterator?

zinc plinth
#

Put the index if w/e you're iterating

This number is used to determine which command should be executed first I think

#

Of *

#

This makes it deterministic, instead of being a full blow' race condition

shy pilot
#

ah ok, in my case i don't think it matters much

zinc plinth
#

You still need to provide it

shy pilot
#

yeah

#

i'm just passing the iterator

shy pilot
#

does anyone have an example of unity.mathematics.random in use?

deft stump
#

hold my beer.

#

oh wait I don't have one written down XD

hollow jolt
#

is it possible for a collision to accrue when scheduling 2 jobs one after another that write to the same ParallelWriter ?

hollow jolt
#

so i guess its impossible to read and write to a multihashmap ? had those two

[ReadOnly] public NativeMultiHashMap<int,int> map_reader;
[WriteOnly] public NativeMultiHashMap<int,int>.ParallelWriter map_writer;

which yielded

InvalidOperationException: The writeable Unity.Collections.NativeMultiHashMap`2[System.Int32,System.Int32] TestMultiHash.map_writer is the same Unity.Collections.NativeMultiHashMap`2[System.Int32,System.Int32] as TestMultiHash.map_reader, two containers may not be the same (aliasing).
deft stump
#

Well, when you are writing, you have to read it first.

hollow jolt
#

but i can't ...

#

NativeMultiHashMap<T1,T2>.ParallelWriter - can't read

#

?_?

stone osprey
#

Is it possible to add stuff to a query ? Like "EntityQuery query; query.All(typeof(Movement));" ?

safe lintel
#

afaik you shouldnt be changing the query at runtime

#

can always just specify more queries in your initialization though

radiant sentinel
#

on editor time

rancid geode
#

as it says, it is a bug, so if you want Unity to fix it I would create a bug report

radiant sentinel
#

as it says, it is a bug, so if you want Unity to fix it I would create a bug report
@rancid geode
thank you

hollow jolt
#

is there a way to output int values in jobs ? seems like i can only read out the default set value in IJobParallelFor

#
    public struct TestMultiHash : IJobParallelFor  
    {    
        public Random random;
        
        [WriteOnly] public NativeMultiHashMap<int,int>.ParallelWriter map_writer;
        
        public int max_key_index;

        public void Execute( int index )
        { 
            int write_index = index % 10 < 5 ? 0 : ( index % 10 ) - 4 ;

            if( write_index > max_key_index ) max_key_index = write_index;
            
            map_writer.Add( write_index, random.NextInt( 10,20 ) * 100 );
        }
    }
#

max_key_index always results in 0

#
        var map = new NativeMultiHashMap<int,int>( 50, Allocator.TempJob );
        var task1 = new TestMultiHash
        {
            map_writer = map.AsParallelWriter(),
            random = new Random( 7104 ),
            max_key_index = 0
        };        
        task1.Schedule( 50, 10 ).Complete( );
        Debug.Log("max_key_index = " + task1.max_key_index );
hollow sorrel
#

@hollow jolt it's because jobs are structs, easiest solution is prob using a nativearray<int> with one value

rancid geode
#

in latest collections package there is a NativeReference too, which was created for that exactly need

amber flicker
#

ooh really? didn't know about that, nice

hollow sorrel
#

oo nice

hollow jolt
#

excellent

#

looks like NativeReference<int>( Allocator.TempJob, , NativeArrayOptions.ClearMemory ) have to be disposed as well

zenith wyvern
#

Yeah it will still follow the same rules as a NativeContainer. It's just more convenient than having to use the array indexer for a single value like you would with a native array

hollow jolt
#

true that

#

I'm still trying to solve aliasing for NativeMultiHashMap, now trying to split the task into a 2 parallel job and 1 normal job process

dull copper
#

I did not now that setting the physics package thread count hint to 0 will make it single threaded

#

I mean, it does make sense that they do it but I didn't expect them to do that

hollow jolt
#

link ?

hollow jolt
#

ty ty

dull copper
#

while I admire what this person does... I don't really think this helps if person tries to make a game with just few characters: I think you should try with 1000 characters and see what that does.

#

I mean, it's totally irrelevant how much you can brute force it if you only care it works for few char instances in the first place (but I don't really know the intended target either)

#

my biggest beef really is that people do dots perf comparisons with scenarios that were never feasible for monobehaviours in the first place

#

it's cool and opens new possibilities but it's not really a nice way to compare the results if it's not a typical usage scenario

safe lintel
#

they really need a button that also shows the state of the safety mechanisms in place

#

i hate toggling 3-4 menu option things just to check dots performance in editor(not to mention editor debug mode too), give me more buttons unity 😩

dull copper
#

they could just toggle it off when you go to "release mode"

safe lintel
#

heh, i tried making an editor script for this a while ago but for whatever reason sometimes toggling those dots options from script doesn't register.

amber flicker
#

@dull copper dark theme how? 😅 browser ext or is it a setting somewhere?

hollow jolt
#

uses this interface to project a simulation forward into the future. - does it mean physics-ecs is deterministic ?

hollow sorrel
#

i was about to complain about the base cost of physics again but seems it improved a bit since i last checked? getting 0.3ms full jobcount and 0.2ms jobcount 1 (build crashes with 0 for some reason)

#

i remember it being 0.5ms full and 0.3ms jobcount 1 when i last checked thonking

dull copper
#

@amber flicker it's some nightmode browser extension

amber flicker
#

alrighty, thank you 👍

dull copper
#

I'm still waiting for the new round of DOTS packages to land before testing current perf

#

I don't really need physics to be as fast as current physx implementation but physics is one of the things that raise the min spec in my use cases already

hollow sorrel
#

do you think bursted systems are going to be next update already

#

that'd prob be pretty huge

#

idk how far along they are

dull copper
#

hopefully not as far as burst crossplatform determinism 🤔

amber flicker
#

I'm kinda doubtful - maybe mostly the updated codegen stuff?

dull copper
#

been waiting that for years before Unity made really clear that they are not even touching that in a while

#

before they were suggesting it was merely few months away

hollow sorrel
#

yeah 😭

safe lintel
#

we need like a dots bingo or dots betting where you mark off the things you think will be in the next release 😉

#

bets on how long for determinism, how long until a blog post

dull copper
#

I bet they just expand the dots debugging

hollow sorrel
#

also regarding physics, i really wanna experiment more with seperate worlds, like could imagine a tetris 99 style game where each player runs in a seperate ecs world, but that's pretty much impossible when there's so much base overhead per world
(not suggesting that use case is impossible, you can still do it cramming everything into a single world)

dull copper
#

for the next release

#

I mean they do more but that's only think I can think of that is likely to happen

amber flicker
#

prefabs & .enabled might be this year but at the current rate, likely not. That'll be a big update.

dull copper
#

wasn't the disabling stuff verified to come later already?

amber flicker
#

'verified' 😅 - think Joachim said aiming for next few months or smth

dull copper
#

that's what I mean, few months meaning it's not going to be on this round of packages

#

it could mean anything but next release

amber flicker
#

yea, only thing we know for sure is this update won't include .enabled stuff

dull copper
#

I'm currently reading Joachims messages on the bursted systems

hollow jolt
#

is there any way to use NativeMultiHashMap in read and write mode in the same parallel job ?

dull copper
#

I didn't know they were that far along with it

#
What is missing is code-gen for Entities.ForEach, but we are also almost there with that.

This will significantly reduce the overhead of System.OnUpdate including the cost of invoking Entities.ForEach.Run```
amber flicker
#

yea 🤞 - guess it's going to mean refactors at some point

dull copper
#

and that's nothing new with dots 🙂

#

they haven't done huge api changes lately so it's about time

#

can't keep people settled :p

safe lintel
#

would these changes make that much of a difference in perf though? most of the overhead ive observed seems more related to the job system & cores (then again maybe this improves scheduling speed?)

zenith wyvern
#

If you use a lot of systems it could make a huge difference

#

Like hundreds of systems, that's a lot less overhead per system

amber flicker
#

I'm really hoping there are some scheduling optimisations in 0.16 - it's so bad right now

hollow jolt
#

Any tips for NativeMultiHashMap read and write in the same parallel job ?

zenith wyvern
#

The whole point of the ParallelWriter containers is to prevent you from reading and writing in a parallel job

#

I guess you'd have to pass in the normal container and disable safety restrictions

#

Or read all the data you need to read into a separate container and pass it into the write job

hollow jolt
#

i tried disabling restriction but it won't write any data

#
[BurstCompile] public struct TestMultiHashRW : IJobParallelFor
{
  [NativeDisableParallelForRestriction] public NativeMultiHashMap<int,int> map;
#

ah nvm it crashed my editor

#

removing parallel restriction works as expected , not sure it failed me last time , thanks

radiant sentinel
#

as it says, it is a bug, so if you want Unity to fix it I would create a bug report
@rancid geode can you share the link with me?

rancid geode
#

link?

olive kite
#

If a paralleljob needs to access an array of floats per item, is the most efficient way to store that data in a NativeArray<NativeArray<float3>> ?

amber flicker
#

@olive kite you can't put native containers inside native containers

olive kite
#

any suggestions? would it be better to schedule each job separate and schedule them together

rancid geode
#

@olive kite I had a similar case, I used 2 nativearrays, one flattened with all the things i need to acces, another one NativeArray<int> being the array of "last index per item"
probably there are better approaches,, but that worked perfectly for me

olive kite
#

okay cool, i'll try that. thank you

lean raptor
#

Can I use Unity Jobs for long running tasks? I mean, like 1-5 seconds?

shy pilot
#

technically you can use it for anything, the question is whether the performance gain is worth it

lean raptor
#

Ok, thanks. But if I have a long running task (5 seconds) the game won't block nor suffer thread starvation, right?

dull copper
steady blaze
#

Hi, a regular List seems to be convertible to NativeArray with i.e.: points = points.ToNativeArray(Allocator.blabla)
but I also want to convert a regular array to a native array, how can this be done?

hollow sorrel
#

@steady blaze pass the array into nativearray constructor

steady blaze
#

@hollow sorrel ah yes, thank you! wonder if i could use NativeArray directly more often, but then have a problem, that i.e. within one method I cannot dispose after a return …

hollow sorrel
#

what do you mean?

steady blaze
#

nwm, too confused atm

olive kite
#

I noticed that in the physics ecs sample project they update their entity translation in FixedStepSimulationSystemGroup. Is it the best place to do updates ? Why do they do it in the step instead of before or after?

steady blaze
#

everything works fine without jobs and simple jobs also work fine.
but if it gets a bit more complex, it does not seem to work. maybe NativeList is not usable yet?
Of course I guess I am doing something wrong.
i tried to set all NativeContainers to persistant to be sure. Everything that is created and used inside the job only, i dispose after the job, the others on destroy.
although it says: NullReferenceException: Object reference not set to an instance of an object - where it should set the vertices of the mesh to the results of the Job (NativeList)

#

followed by lots of other errors …

#

Where should/can the NativeLists be initialised? Directly in the declaration of the class? at start/awake of the class?
maybe in the Job? I tried all 3 …
only not yet tried: directly before creating the job …

#

don't think it even starts, very strange …

#

maybe because i am reading from marching cubes lookuptables static values? but they are marked as readonly

hollow sorrel
#

they can be initialized anywhere

#

what line throws that error?

#

@olive kite fixedstep systemgroup is basically ecs version of fixedupdate, runs at a fixed time step

steady blaze
#

don't get it, also get: InvalidOperationException: Jobs can only create Temp memory
now tried to use always the same value and not use the lookup tables (to avoid static readonly), also changed the vertices, triangles and uvs to be created directly before the job starts (and not with class), no idea …

hollow sorrel
#

and you're still getting nullrefs?

#

what line of code?

steady blaze
#

null reference is: mesh.vertices = jVertices.ToArray();
maybe i have to sleep and see it a bit clearer tomorrow
I use a regular IJob, i tried IJobParallelFor with a count of 1, then it says:

#

InvalidOperationException: TerrainGenerationJob.vertices is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.

hollow sorrel
#

mesh is the only thing that can be null there

#

you sure you're also creating the mesh first?

steady blaze
#

oh yes, really forget to create the mesh 🤦‍♂️

#

that is gone now, still says: InvalidOperationException: Jobs can only create Temp memory

hollow sorrel
#

ah

#

either you wanna allocate the nativecontainer first and pass it into your job, or use temp allocator if your job only runs for one frame

#

tho not sure if the one frame restriction applies if it's allocated in a job 🤔

#

oh but since you plan on using it outside the job, yea you gotta allocate it before the job

steady blaze
#

ok, maybe something in the job …

#

guess i have to find tomorrow, thx anyway @hollow sorrel !

steady blaze
#

i think i don't really get how to allocate and dispose correctly.
when schedule and call the complete immediately after the schedule, I thought Allocator.Temp should be enough, as it cannot render a frame inbetween, but it seems it still needs Allocator.TempJob then.

steady blaze
#

ok, set everything to Allocator.Persistent again, also the stuff only needed inside (could take longer when it runs as intended)
and at the end of Execute I dispose all NativeContainers only used in the Job.
also seems not possible/good to initialise a NativeList at declaration, better in Awake or Start, but still get the error:

#

InvalidOperationException: Jobs can only create Temp memory
and then 2 times: A Native Collection has not been disposed, resulting in a memory leak. Enable Full StackTraces to get more details.
But I guess the last ones only because the job does not run

valid haven
#

If I want to use dots just for access to Havok Physics. What is the minimum amount of dots integration I need to do. i.e. do I need to use the Hybrid Renderer? Or can I use monobehaviour for everything per normal? What about multiplayer (plan to use MLAPI).

steady blaze
#

wow that is really strange now: When I Build the App from my code it just works and runs fine! (much faster as without jobs), but I need to get it running in the editor too. 😢
Maybe really a Unity Bug?

#

what does the error: InvalidOperationException: Jobs can only create Temp memory exactly mean?

#

I now put all in one method to create and schedule und force-finish the job, as well as using the results. (later this should be split, so I start the Job in Update and every LateUpdate I want to check if it is finished.
Maybe anyone has an idea?

#

Looks like this now: ```
NativeList<Vector3> jVertices = new NativeList<Vector3>(Allocator.Persistent);
NativeList<int> jTriangles = new NativeList<int>(Allocator.Persistent);
NativeList<Vector2> jUVs = new NativeList<Vector2>(Allocator.Persistent);
var terraGen = new TerrainGenerationJob()
{
areaSize = areaSize,
isoLevel = isoLevel,
voxelWeight = new NativeArray<float>(voxelWeight, Allocator.Persistent),
points = new NativeArray<Vector3>(points.ToArray(), Allocator.Persistent),
vertices = jVertices,
triangles = jTriangles,
uvs = jUVs
};
var jobHandle = terraGen.Schedule();
jobHandle.Complete();

mesh.vertices = jVertices.ToArray();
mesh.uv = jUVs.ToArray();
mesh.triangles = jTriangles.ToArray();

mesh.RecalculateNormals();
meshFilter.mesh = mesh;
meshCollider.sharedMesh = mesh;

jVertices.Clear();
jTriangles.Clear();
jUVs.Clear();
jVertices.Dispose();
jTriangles.Dispose();
jUVs.Dispose();```

wet epoch
#

are you creating something in the job?

#

that's what the error means i think

deft stump
#

is it just me. or is the package manager from 2020.1.0b8 and above has a bug.

#

on a fresh reset of a project if resolving packages hits the 2 minute mark, it just errors out

steady blaze
#

and the job without content: ```
public struct TerrainGenerationJob : IJob
{
public int3 areaSize;
public float isoLevel;
[DeallocateOnJobCompletion]
public NativeArray<float> voxelWeight;
[DeallocateOnJobCompletion]
public NativeArray<Vector3> points;

public NativeList<Vector3> vertices;
public NativeList<int> triangles;
public NativeList<Vector2> uvs;

public Vector3 interpolateVerts(int p1, int p2, float value0, float value1)
{
    float mu = 0.5f;
    mu = (isoLevel - value0) / (value1 - value0);
    return Vector3.Lerp(points[p1], points[p2], mu);
}

public struct VertexBuffer
{
    public int index, A, B, C, D;
    public VertexBuffer(int i)
    {
        index = i;
        A = -1;
        B = -1;
        C = -1;
        D = -1;
    }
}

public void Execute ()
{
    int areaSizeXY = areaSize.x * areaSize.y;
    Vector3 newVert;
    NativeArray<int> vlist = new NativeArray<int>(12, Allocator.Persistent);
    VertexBuffer lastXBuffer = new VertexBuffer(-1);
    NativeList<VertexBuffer> yBuffer = new NativeList<VertexBuffer>(Allocator.Persistent);
    NativeList<VertexBuffer> zBuffer = new NativeList<VertexBuffer>(Allocator.Persistent);

    // calculations …
    
    vlist.Dispose();
    yBuffer.Dispose();
    zBuffer.Dispose();

    voxelWeight.Dispose();
    points.Dispose();
}

}```

wet epoch
#

yeh those arrays need to be Allocator.Temp

steady blaze
#

@wet epoch what do you mean with create smth in the job?

wet epoch
#

or TempJob? can't remember

steady blaze
#

hm, but I dispose them in the end

wet epoch
#

yeah, but why are they persistent?

steady blaze
#

so it shouldn't heart anything except performance or not?

#

it could take longer than 4 frames for completion