#archived-dots
1 messages · Page 251 of 1
but overall my own code is extremely lightweight and takes less than 0.3 ms total
thing is
I didn't use TIny
only physics from it
I talk about general dots packages
yeah which was written explicitly for it. Its not production ready at all.
At least you can actually do something. My unity is literally effing bricked at the moment.
at least if I'll need actual compute power, I know how to implement it
might be faster to use dots 3d physics and just treat it as 2d
I'm not certain how tbh
I probably will need joints on axis
which is same useless overhead I don't really need
tbf every dots packages is peview so they basically tell you to not use in production.
the new input system is okay wdym?
new input system is not compatible with Unity remote kek
Its nowhere even remotely NEAR okay.
Its half baked half finished and terribly documented.
terribly documented is true, hard to find good info.
But overall I think it's fine to use
sounds like the addresables package 🙈
but I don't have too much experience in development yet
As I said earlier its the MO for unity technologies to hype stuff up early, push it out and then abandon it.
So many features they tried to establish and they came out half baked, broken with poor if any documentation.
I made 9 albeit smaller games in the last 3 years, and each time when it comes to pick establish the technology pipeline I want to use unity but every time something is not panning out because of something being half baked.
Meanwhile I was able to without many hitches release 6 games with game maker studio 2 and 3 with godot without much of an issue.
And that is despite me hating godots pythonness.
can you educate me on what's not okay on the new input system>?
What's half baked about UIE? The only thing left I think they haven't implemented is element specific materials / shaders. And trust me when I say UIB has come a long way.
I think the new input system is aimed at non programmers. It is very complex but you don't have to use much code for it. I don't like it but I am very fluent in code.
@gusty comet i rewrote some stuff for a simulator I was making with ECS and it became literally 1000s of times faster. DOTS is like writing stuff in low level code. It's hard to do well but the performance is incredible.
yeah, it's good when you need perfomance
but when you need basic stuff
it might turn things other way around sadly
I really hope Tiny won't be the only solution for dots
with 2D
Oh yeah it takes way longer to do simple stuff. It takes me way more time to actually set up what data I actually need than do do the code to do stuff
I just love knowing the stuff I write will get faster and faster as more cores become e standard on computers
no I mean, just the implementation of ecs takes away perfomance, since it brings overhead
I am literally rewriting my game in OOP rn because of it
I didn't expect it to be that bad
What is the major overhead?
well, simply empty project already is about 3 times slower than no dots
like, simple game objects without game logic
I have no idea why, maybe 2D physics package is just broken atm
but it's eating 1ms on it's own
Are you using hybrid renderer?
HR currently is god awful
Roll your own graphics pipeline
I tried to make my own renderer several times, but I failed
I have used ECS systems frequently in the past I am keenly aware of the performance gains.That does not change that dots is an a sorry state.
I did it okeshing I think with drawing my custom spritesheet
DOTS is perfectly usable currently. Stick with Entities and Burst only. Roll your own graphics solution
but since no SRP batching, or GPU instancing came along with it
I thought I'd rather go with HR
At the point where I have to roll my own graphics solution I can just use monogame and get far better results.
yeah, it's kinda uuugh
Literally every time I tried to use unity for a project it came down to unity being basically just used for rendering.
Mono and DOTS are not mutually exclusive. I have some key game objects purely mono but simulation is being handled independently solely on a job thread that updates graphics independent.
Its antithetical to the pattern. If I use an ECS pattern and then have references all over the place why bother in the first place? It makes no sense to me.
simple stuff will always be worst with DOTS. It's focused on when you need to scale something to a crazy amount down the pipeline. And ECS makes everything more maintainable due to the modularity of it, but that does come at a cost
yyep
I also had to turn off all the safer systems before I got crazy performance for my simulation stuff.
You'll need to have a mono hook anyways. UI is purely OOS and in monoworld
The thing is ECS is not just for performance. Its also a completely different way of structuring your codebase.
those are automatically turned off in builds, right?
Like with the safety system on it was 2.2ms on the main thread and then safety off it was maybe .25ms
There really isnt that many safety in entities. Do you mean exposing the references?
That's odd, what are you doing that's requiring that many safety checks?
But those that have a measurable impact post Burst compile is basically allocation and deallocation
Nah the unity stuff that makes sure you aren't aliasing and not getting race conditions
I hope those editor only, cause I didn't do anything when building game kek
Use pointers and tag [NoAlias]. I've never needed to turn off safety.
Yeah they may not be
kinda afraid I was looking at perfomance with safety checks
In my experience, safety checks are not the problem. If you're having noticable impact from the built in collection tests, theres something wrong with your code. Maybe not vectorizing probably or something.
like I said, my own code is 0.3ms total
all systems I had were part of my own system groups
0.3 ms. At that point, you're just micro optimizing if you're worried. But yes, safety checks will be a measurable fraction for that size.
Well where it there of the 19.3 ms going?
I think there might be a different problem. Have you been using profilers tags and not the profiler itself?
I won't redo profiler again
Or just screenshot the profiler on a typical frame. What's going on?
but I remember
6ms on reder
weird huge lines on main thread with smth really unknown
and that was on Build, not in editor
@robust scaffold "HR currently is god awful" I disagree, but why do you actually hate it? cant remember if Ive asked you before
Extremely high overhead for very little performance gain. It is simultaneously too restrictive yet too generic. It is a cancer growing off the side of the RPs currently in engine and, in it's currently released state, fails to be an easy, effective, and optimized way to chunk and display meshes.
even rn, when I just installed fresh dots project, I already had about 200 fps on stage of simply moving entities
In fully classic Unity, I get 500 with same thing
so basically on little projects, there's seem to be little to no gain from dots
actually yes. That is the primary problem with DOTS. It scales well but initial costs are high
Theres no use to Burst if you only have 5 elements in an array
yyyyep
but is that in a build? its not a 1:1 comparison with all the safety checks going on in editor
that is exactly my case lol
my build showed 50 fps
max
on mobile
I'll see how much I'll get with classic unity
@robust scaffold I only have 0.4-0.5 ms of overhead for HR, what do/did you get with it?
I think there was some bugs with certain versions of the HR where you get worse performance
If I remember correctly, empty HDRP w/o HR: ~3ms. W/ HR: ~5ms. 2ms overhead for an empty scene, no entities, no objects.
Im sure the scaling gets better when I add things to the scene but I've stuck with pure GO and stock HDRP rendering.
what kind of cpu/gpu and is this on desktop or mobile? I have the same overhead for hdrp and urp, though somewhat older hardware(8700k and 1070)
The overhead should always be higher at the start but then doesn't increase as much with more stuff. It's like writing stuff in C# and then saying that it has more overhead than writing it all in assembly. If we wrote everything in assembly it would all be insanely fast with no overhead but be impossible to maintain
is there some trick I'm missing to enable burst because it seems completely random as to whether it Unity uses it or not 😕 even when I'm putting explicitly to use burst
in ECS or just jobs?
also Burst takes a while to compile after you run the new code, it does it at runtime so wait till it settles before testing
you can also turn on compile before play which freezes your editor while it compiles everything @pliant pike
where exactly are you trying to use burst?
Yeah thanks, I think it's just the first time I run after compiling, that must be the problem
In a job
Yup it runs all the code once to see the result and then compiles as you go. Usually took me a few seconds to settle down
it'll compile code randomly so it isn't always the same compile order
It probably doesn't help when you have tons of errors as well
no, that doesn't help
as far as I know you need to tell BurstCompile on struct and on Execute method
both attributes exist, right?
Indeed, although I'm using entities.foreach
I know, that's what I did, thanks
How are people using methods inside jobs?
I use methods inside of jobs all the time. I usually make them static methods so that I know what is going in or out
Or you can make them private methods inside of jobs that can access the input or output native arrays. Either or works.
I wouldn't expose any methods from the inside of jobs since jobs should be their own thing. All you do is put in the info into the job and then execute it.
and then grab the outputs
ok cool public static seems to work, thanks
I can't seem to get the DOTS physics package to work, I'm getting errors at Broadphase.cs:873, Is there a specific Unity version I should be using? I'm using the latest LTS
@lofty sequoia try this https://forum.unity.com/threads/2021-2-8f1-broke-asdeferredjobarray-and-deferred-jobs.1225635/
after f25 they broke the collection package
@lofty sequoia wait sorry I think f25 its broken, im personally on f23
f25 is working for me
ah, must be another reason im avoiding f25 🥲
oh well
so I fully rewrote all my dots progress with OOP
and looks like end perfomance is not THAT different xD
allthough I need a bit more testing
so far profiling is about 3 times faster
10 fps vs 40
without profiler game caps at 57 on mobile, can't really check what is actual top fps
vs 50 fps with dots
welp
I guess mobile is not ready for dots at all
PC is barely ready
kind of disagree
there are some AAA studios using DOTS on mobile
people just have to realize what DOTS provides
if you have a basic game, tiny simulation
and especially if you're using some hybrid workflow
then what benefit is it giving you?
like i'm not really sure what you're expecting 😅
it's also unfortunately really easy to write poor dots code, especially without a lot of experience
doesn't mean you can't do amazing things on it!
well yeah, by mobile I meant some casual non-sim games
obviously in some heavy projects profit will overcome overhead
but on low end devices it's just unviable
UNLESS threading profit overcomes all that overhead anyway
if you're doing a low end mobile game
it's probably advisable to switch to simple scheduling mode
from what i've heard that is quite beneficial on mobile
wdym?
ENABLE_SIMPLE_SYSTEM_DEPENDENCIES
i drew a graph of this ages ago
in simple dependency mode, it doesn't do a complex dependency check when you schedule jobs to determine what can run at what time
instead of just schedules them depending on the order you call them
huh
System1 schedules Job1, System2 schedules job2
job2 will only depend on job1 in simple mode
I see
regardless of what components etc are used
so that really simplifies setting up dependencies
ENABLE_SIMPLE_SYSTEM_DEPENDENCIES define can now be used to replace the automatic dependency chaining with a much simplified strategy. With ENABLE_SIMPLE_SYSTEM_DEPENDENCIES it simply chains jobs in the order of the systems against previous jobs. Without ENABLE_SIMPLE_SYSTEM_DEPENDENCIES, dependencies are automatically chained based on read / write access of component data of each system. In cases when there game code is forced to very few cores or there are many systems, this can improve performance since it reduces overhead in calculating optimal dependencies.
from the patch notes [0.3.0] - 2019-12-03 way back when it was added
it's ideal for low end mobile devices
I'm guessing overhead is reduced from some to 0
gotta test that
kind of fun to test real application perfomance with this
the big drawback is its bad to use systemgroups
because they are included in the chain
and basically cause sync points ^_^'
when it starts
SystemGroup1 has SystemA,B,C in it
SystemGroup2 has SystemD,E,F in it
when systemgroup2 starts updating, it'll sync point SystemC
before SystemD runs
ah
that
Does it really matter tho?
whether you schedule everything in loop and then it gets oncomplete
if systemC has a system that takes 5ms
or when it gets complete meanwhile scheduling
yeah, but what's the difference then
if SystemC Schedules job
and gets called by next system to finish?
the next system doesn't finish it
EXCEPT in simple dependency mode by compnent system groups
because compnoentsystemgroups use the old componentsystem instead of systembae
which is basically a main thread only system
without simple dependency mode it checks what dependencies it needs to complete, which is none
but in simple dependency mode there is no check, as its a main thread system it just completes the handle pass to it i.e. systemC
Ok, so main thread will be the first to run job if it encounters sync point
meanwhile if sync point has a lot of jobs scheduled already
they all will spread
a sync point just means the main thread has to wait for a worker thread to finish
the main thread will try to help by grabbing a job and completing it
but if it can't it literally just sleeping
yeah its just a annoyance in simple dependency mode
any alternative to make it clear at least during debugging tho?
you can write your own system group that doesn't have this issue
so I make my own group
you have to implement the whole systemgroup in a systembase
and just pass the dependency through
sad life
How does one deal with the immutability of structs within the scope of Dots? Ideally, I'd like the performance of Dots, but with being able to have constantly changing value of entity variables. Do I simply re-construct the struct containing the data? Is it best practice to keep the components separate and small, so that they don't cause overhead when re-constructing the components?
entity queries reference structs in component arrays
you basically write to referenced structs
that are passed with ref
same thing with in but it's restricting you from writing to it
yet still passed as reference
so, I basically treat them as I would classes by just using ref(in terms of modifying variables within)?
yeah
Is that good practice, or is there maybe another way of doing the same thing?
it's native c# practice
Thank you!
is it possible to get an enum name as a FixedString128 in a job?
eh I'll just chuck it into the component in the authoring step
I think enums are just converted into an int at runtime.
What kind of game are you making @rustic rain?
kind of like flappy bird by gameplay nature
Yeah not a huge gain to do it with DOTS. It really shines when you have to do a lot of parallel stuff and parallel physics is hard as heck.
I have a feeling I can still squiz enough perfomance to at least achieve capped 60 fps
since I didn't do simple scheduling
and I think I did a bit of fail with UI Toolkit event system kek
I bet you are leaving performance on the table somewhere else. The UI system Unity ships with is very flexible but can be costly
Just curious what sort of work are you using DOTS for in the game?
Is it mostly parallel jobs?
nah, I only used ForEach queries
my usual query is about 5 entities max
Parallel eats more than gives
Yeah i was wondering if that's where you were losing the benefit
My guess is that just running HR and all those Unity systems
Definitely interesting to find out if there's benefit it doing jobs stuff on small amounts of data, would love to know more on this myself
so far I added quite a lot to my OOP version and it's still about 2x more perfomant
on PC
in editor
Yeah i definitely felt that enabling Hybrid Renderer gave me an automatic fps penalty right off the bat but that was a year ago now so i can't remember if it was a clear comparison.. I kinda needed it though as i got the massive overall benefit of doing all this other stuff ( hundreds of skinned meshes and ragdolls etc )
Yeah def curious about this, doing small run small datasets, is there a benefit.. i wonder if people have benchmarked that stuff
I mean it may be that your data stuff is multiples faster, but Hybrid is eating up time - what does the profiler look like?
I do remember a couple of people saying for anything short of a few k gameobjects, they just render without HybridRenderer but i think that was more of an issue with HR v1
PhysicsWorldSystem / TransformSystemGroup / PresentationSystemGroup then roughly the culprits
in transform system is it the parenting system?
it's vanilla system
my is GameSystemGroup
and CollisionSystemGroup
everything else is built in
yeah i know those are vanilla, that's why i'm asking is it the parenting system inside TransformSystemGroup that's hogging cycles there
ah
i've had issues with that on and off
eh, I closed it already
i noticed ur GameSystemGroup is like 0.23ms so your code specifically is obviously negligable, it's really the vanilla stuff that's holding it back right
it's 5.8% anyway
yyep
I spent month and a half learning dots
I wouldn't forgive myself doing unperfomant code kek
would be interested to see whats inside presentation system group causing that 3ms under the peak times
no hassle tho if it's closed etc
also on the mono version of your project, i wonder what the difference is between say, your game logic mono times vs for example that 0.23ms GameSystemGroup.. but i understand it's probs not comparing apples with apples as there's probably overlaps in your monos with collision code and ui stuff etc etc
well, even though my own code is 0.23
doesn't mean it doesn't rely on code that is 50
kek
here I uploaded profiler data
if you're interested
I assume you can see it on your own end
weird, download button doesn't work for me in chrome but does in edge
ah i can't open it rn, will check later
one thing that removed a ton of overhead for me was just setting FixedRateManager to null.. i did basically get shit for this as it 'breaks determinism' etc but it made things a lot quicker, previously i was getting multiple instances of the PhysicsWorld systems per frame, and setting this to null gave me just one.. everything still worked
it may be that there's some other settings to adjust for what was happening with FixedRateManager in my case but tbh whatever those might be is beyond me
another couple of things is disable shadows where not required and there's a transparency define which speeds up rendering if not using mats with transparency
relating to hybrid renderer
Stupid question but does this code not work to declare a variable passed into a job as read only AttackATKQuery = GetEntityQuery(ComponentType.ReadOnly<ATKdata>(), ComponentType.ReadOnly<UniqueGUIDat>());
because I keep getting these errors ReadWriteBuffers are restricted to only read & write the element at the job index. You can use double buffering strategies to avoid race conditions due to reading & writing in parallel to the same elements from a job.
show more code?
yeah I've posted it in the forum https://forum.unity.com/threads/entityquery-declared-readonly-not-working-in-parrallel-job.1241668/
you are probably trying to write to that array too you just don't realize it
I know but I'm only reading from it
Oh I know what you are doing
you can't pull the data in twice
you are pulling in in UniqueGUIDat dudesGUID which conflicts with the entity stuff you pulled
Is there a way to get high-accuracy timing (like Stopwatch) in burst compiled code?
Stopwatch is for timing fast computations 😉
I don't think it is, the GUID components are all separate components, on separate entity archetypes
You can't pull in the same type of component in both a native array and in the foreach
Like the job archetype is the GUID with the listofattackers component and that is different to the other archetypes
It just doesn't like that, I can't remember why
Also it works if I set them to with read-only() in the job
oh maybe I am wrong then 🤷♂️
And it also works with schedule() fine
this is required
if you don't use WithReadOnly(array) then it errors basically there's a missmatch between the job readable state and the query readable state
Yeah, thanks, it's kind of confusing, it seems pointless to use readonly in the actual entityquery then
it's probably errors for thread safety
as far as I noticed, they want us to have write access only either in single thread job
or only if you are limited per array index
they do different things
the readonly on the query changes how dependencies are scheduled
readonly on a job ensures thread safety and burst optimizations
and they don't have to match
you have a write query with 2 jobs
the first job is marked readonly, the second job can write
Hello everyone! I'm learning DOTS making an Asteroids game, i need to spawn a lot of bullets from the player when it shoots. should I make an "entity pool" ? or simply instantiate them at the spawn point? maybe i could spawn entities at the point but also use a gameobject pool for moving the bullets. what do you think?
That's really interesting, thanks for that explanation🤔
There was an intro to dots video on the Unity YouTube channel that dirt just this. It's from a few years ago, check it out. I think it's about 40 minutes long.
in the official?
Yes I am pretty sure.
It was someone giving a talk at a local conference I am pretty sure. I am sorry I can't find the link right now.
Talking about this one i assume https://www.youtube.com/watch?v=BNMrevfB6Q0
In this video, learn about what's involved in migrating existing game code to the new Data-Oriented Technology Stack (DOTS), which comprises the C# Job System, the Entity Component System (ECS), and the Burst Compiler. You'll also gain an understanding of the performance benefits you can expect from these systems. Finally, you'll learn when it m...
Also there's an asteroïd sample (IIRC in the multiplayer samples), in case you'd like to yoïnk some ideas
Nailed it
Thanks a lot!!
Another week is over and Unity is radio silent on DOTS 0.50 release... Then again, talking to the community about DOTS is just bad.
Then again, I'm looking at these completed 0.50 sample projects and nothing has changed on the lambda side. Sadly no examples of struct based jobs. 0.50 might just be completely indistinguishable from 0.17 at this rate. The core Entities package at least.
what changes do you actually want with jobs?
Primarily external access to system Dependency. I've decoupled a second world's system update from the playerloop to allow for frame independent update.
Due to the fairly opaque access of Dependency between systems (passes through magical box of JobDebugger), I have to instead manually JobHandle.CombineDependency(static singleton, Dependency) at the very end of every single system.
If there was a way to instead just grab hold of the final Dependency from a single loop of world SystemBase Update, that would make my life a hell of a lot easier.
this is not something I see them supporting
I know what I want exists, it's somewhere in JobDebugger, but I have no clue where exactly the dependency ultimately ends up in.
Additionally, I wish ExclusiveEntityTransaction was a little less clunky in usage.
Yea, I know it's "purely for world initialization" but it opens up amazing possibilities for pure job thread world update.
I've managed to get it working but it kinda breaks everything else.
Definitely very eager to see how the blittable shared component data will come out, crossing my fingers to see if it ships with 0.50. Basically the #1 thing I wish right now.
ISystemBase could be completely deprecated and I'll be decently okay if only Blittable SCD comes along as well.
Also, Burst 1.7.2 could not come fast enough. Constantly having to restart my editor to reliably view changes in inspector if I forget to close the inspector before changing code is so incredibly annoying.
Will shared component be faster is that the idea?
aren't they already fast?
do you guys think its a bad idea to put roughly 10,000 entities into a buffer
ok maybe its not much of a problem I can add 10,000 entities to 10 buffers in under 7 milliseconds 
apparently it would take over a month just to add a few more responses to that thread 🙄
well you could use them with burst and jobs. no idea how RenderMeshes work in conjunction with that requirement though, we getting a new blittable mesh type?
would also require a new material
@pliant pike What do you need it for though? There may be a better way to do what you are trying to do
your right there probably is a better way but I just thought I'd try it to see how well it works
I'm trying to have 10 entity's each attack 10,000 entity's
like imagine they are giant mechs in a war
I did some stress test where I searched through 50k objects to figure out if they were close and it took no time at all due to burst
and I was like
darnit, I was gonna post the whoa image from the Matrix
yeah I'm surprised it works so well with this basic naive approach, its probably way more than I need anyway
the nice thing about burst is that you just do it the inefficient way which is way easier to program and it just works super fast without futzing around
like looping through a list instead of doing fancy look up
yeah its crazy
I think I'm reaching the limits though having a search through a 10,000 size array and multiple searches through 10,000 entities in a loop is taking a while(roughly 1000 milliseconds)
yeah that is searching through 100 billion things I think
I believe the max number of entities possible in a single world is somewhere around 200M entities. It's some power of 2 around that number.
I think the max entities are the limit of a 32 bit int. Cause all an entity is a 32 bit int and a 32bit in for a version
My guess was the same order of magnitude at least.
how to get entity prefab created by IDeclareReferencedPrefabs?
GetPrimaryEntity
I'll give you full code when I get out of bed and go to pc
but for this I need conversionSystem, to be specific I need that prefab in MB
It's just a GameObject before conversion
it is, and I need Entity of that prefab after conversion
Then yeah like tertle said, getPrimaryEntity
like you would for any other entity
it's just that you declared it through the declare interface to help the system discover it
getPrimaryEntity is from GameObjectConversionSystem which I don't have
How do you convert ?
I have a prefab with authoring MB with: IConvertGameObjectToEntity, IDeclareReferencedPrefabs somewhere on the scene
and I want another MB to have it's Entity prefab
It can be also a reference from project prefab asset
actually it should work from any system that runs after the declaration group (in the conversion process) but I didnt test it like that
how can I check if i'm after conversion process? Still from a MB
is it part of the same hierarchy?
wait a second, same gameobject/hierarchy just different monobehaviours?
of the same hierarchy or different?
as if its different then afaik not really any easy way to get them to reference each other
I'll make another script with conversionSystem
[unless its a prefab?]
I mean I'm not sure I understand why you want it in a MB, but you could still query back the entity from MB with an entityquery for example
yeah, I could just assign reference from prefab but I have no reference for "main GO"
prefab is in the scene but I can spawn it after so prefab from project files is also acceptable
hmm, not the answer you're looking for but my strong advice when working in a hybrid solution is to never access entity world from monobehaviours
this is talking from experience, you will just constantly burn yourself through your entire project from issue after issue
I need it only for spawning
as I'm rewriting parts of existing MB based project and I don't want to touch too much of a project
just convert prefab to entity and rest will be cared by ECS systems
cant you just store the entity on the MB when you convert?
I could Find it I suppose
It can, but it's this specific case, I wanted to have more universal solution
ok so how tf convert any prefab from asset folder?
without any restrictions from above
just plain DOTS conversion workflow
IDeclareReferencedPrefabs will allow you to add a prefab referenced for conversion
and then I need additional System to convert it?
no, it'll just be converted based off components it has
so an authoring component with IConvertGameObjectToEntity will work yes?
yep it just passes any dependencies through the conversion systems
so any conversion systems will run on it including the one that handles IConvertGameObjectToEntity
but the problem is I don't see any prefab in entity window
filter by Prefab component
yeah, declaration should be also be called from converted object to entity
and I just waited for prefab query to not be null
Random question: there is a DOTS-standard way of dealing with audio?
it's best solution for now
there is a DSP graph package but I don't know how much it's usable
maybe you should implement quadrants or smth?
I doubt you actually need to search through all those entities
I know, I'm just using the most simplest method to start with
I'm half asleep but I just thought of something wild. What if, I create my own Entities system? Instead of using the package, I just have one giant static class with static arrays of native array fields. With manual chunk fracturing and direct pointers to native array backing buffers? What could possibly go wrong?
With computer memory so large, who cares about a little leak here or there. Imagine the possibilities!
Meta 'entities'. Actual parallel scheduling (because ScheduleParallel crashes my entire computer). Structural changes on job thread without breaking everything else.
Static class based 'Entities' has all the benefits of Burst and none of the current requirement to stick with 2020.3.
I'm gonna see how this works. Pointers to buffers of pointers to buffers of pointers. What could possibly go wrong?
Roll my own ECS. None of the syntactic sugar nor support. All of the wild possibilities.
sounds terrible
As long as you are having fun why not.
you don't need to stick to 2020 already
2021.2.7f works
above requires collections fix
which still makes it work
and assuming no one tried
it might even work on 2022
2021.2 WILL BREAK with 0.50, so will 2022
2021.2 support will come later
life is pain I guess
even waiting for 0.50 is not justified
xD
gotta wait for 0.50 AND 21.2 support
anyone having some experience with custom entity command buffers ?
well, most of the time all you want is just inherit from base ecb without any overrides or additions
if that counts as some experience kek
I just thought it cannot be that simple, as there is recommendation to use the existing buffers instead in the docs
well yeah, why would you create another one
I remember double buffer was mentioned once as some sort of justification for it, but I can't really remember for what purpose
want to process stuff within a single frame, but with chained structural changes
I know double buffer was some ancient thing for rendering in a window (probably not the same thing)
well anyway
if you want new buffer
just inherit from it
and add updateafter/before attributes to position it properly
okay, thanks
I'm trying to loop through a large NativeArray, but its get_length() & getter are both very slow, even with burst safety's off. I can get the performance back calling ToArray() on the NativeArray, however this method generates 7MB of garbage, excluding the additional heap allocations for the new managed array space. Is there any way around this I'm missing? Or another way to approach the problem? I'm looking to have neither the slowness of looping NativeArray nor the garbage generation of ToArray
how often do you have to call it?
It's used in a terrain generator, so multiple times a frame for a limited duration and then never.
can't you cache it?
or predict it?
I'd treat it as Count in lists
which is kinda expensive as well
I can both cache & predict it (and have tried doing just so), but it's the ToArray method itself that generates the garbage
why do you need to copy array if you solve the problem of getting leght?
ToArray() will quite literally copy whole array as far as I know
Yes, but looping over the NativeArry is extrodinarily slow
looping through any native container is slow
Both in getting its length every loop cycle (70ms profiled), and accessing the value inside the loop (350ms profiled)
Sure, so that's my question. How do I do this without the slowness of NativeArray and without the garbage generation of ToArray (which removes the performance bottleneck in favour of garbage)
I'm not actually looping the array in a job, I'm looping it after it's been processed by a job
is it possible not to have NativeArray in the first place? just create data in normal array from the beginning?
I'm calculating a 2d float array and it's values. I can't pass that through to the jobs system or burst directly. So I've put the values in a NativeArray<"struct">
As far as I understand it, I've no way to do that without using Native stuff
yeah, burst only works with native containers
Are there any guides on how to make your own deterministic physics?
Hmm....the performance hit from the garbage is far less than the performance cost of not using Burst. So I think I might just have to suck this one up and hope Unity find a way to de-garbage that method!
that'd be great ngl
Ha ha, indeed. Thanks for taking a look
Hi i was wondering how stable dots is for creating a mmo-like android game?
pre alpha for anything
no matter what you are going to do - you're gonna have to implement your own stuff one way or another
does it have any issues with building to android?
I didn't have any
using 0.17?
yeah
but mind one thing - for my project dots was extremely slow solution
It takes some overhead price to implement threading and etc
which wasn't justified for my small project at all
thanks for the info
I don't understand the problem. You have an array you need to loop through? Why not keep the array always as a NativeArray and use that inside jobs. Also getting a length of an array is just looking at a number. It shouldnt take any time at all.
yeah 70ms to get the length, something seems wrong there 😕
I am not doing any ECS, just jobs and getting a length is trivial. The only time it takes forever is when you loop through an mesh array and get the length like this Mesh.vertices. It generates a new array every time you call it. So you need to assign it to an array first.
If I nest UnsafeList inside NativeArray, will Disposeing the array implicitly Dispose the UnsafeLists? Or do I need to loop through array to explicitly dispose of the lists?
you need to loop and dispose them manually
Thanks.
Also, am I understanding this correctly? If I add an entity with a dynamic buffer, changing the length should NOT move that entity to a different archetype right? Only the presence of the dynamic buffer determines this, not its length or contents. Am I correct to make this assumption?
Hey, I am trying to create an a skill system where each skill can spawn different prefab/entity, and has their own "skill level" modification for each level (level 1: damage+5, level2: projectile+1, etc..).
The problem I am having is storing the prefab for each skill, I can't seem to use ScriptableObject to get Entity like in MonoBehaviour (in the inspector that is).
Is there a way to do it and be able to modify that value in the editor?
Without using ForEach pattern, how can I efficiently access a DynamicBuffer via EntityQuery, much like components via query.ToComponentDataArrayAsync. Can someone post a quick example? I can’t find docs that show this.
Or am I looking at using type handles for this?
you can't do it with an entityquery have to use GetBuffer
I've asked that before and its annoying
Ooof. That is annoying.
Doesn’t that create a sync point when GetBuffer is called? Or at least if you write to it.
not quite I think its just out of order memory access so its slower
the only way I figured to access lots of buffers efficiently was to get them in a job and then pack them into a nativearray
So have an extraction job that will cycle through the archetype using GetBuffer and get the data I need?
no use something like Entities.foreach((Dynamicbuffer<buffertype> mebuffer )) = >{ nativearra.add(mebuffer[i]}
I see there is a BufferTypeHandle<T>, I could use that in IJobEntityBatch.
Which is probably the same thing as what you wrote, just you're is wrapped nicely. Right?
yeah you can get them directly in the entities.foreach or in jobstructs
I think you just have to be careful to get the syntax and order correct
I see. Cool, thanks for the tip, this helps a lot.
This is definitely something that absolutely needs to be mentioned in their docs.
yeah they aren't really up to date, but I think it should say in the changelog
Indeed.
Ok, I figured out how to access it without ForEach (in case I need to do more fine-tuned systems). If I have access to ArchetypeChunk either inside IJobEntityBatch or myQuery.CreateArchetypeChunkArray(Allocator.TempJob) which will spit out NativeArray<ArchetypeChunk>.
InvalidOperationException: The ComponentDataFromEntity<Health> ApplyAttacks.healths must be marked [ReadOnly] in the job AttackSystem:ApplyAttacks, because the container itself is marked read only.
var healths = GetComponentDataFromEntity<Health>(true);
[BurstCompile]
private struct ApplyAttacks : IJob
{
[ReadOnly] public NativeHashMap<Entity, int> map;
[ReadOnly] public ComponentDataFromEntity<Health> healths;
Can someone explain to me what's going on?
Whats the rest of the code?
and where is that job scheduled?
Make sure that the right [ReadOnly] if you used autocomplete. There's another [ReadOnly] tag originating from C# System class.
jobHandle = new ApplyAttacks
{
map = map,
healths = healths,
ecb = ecb,
}.Schedule(jobHandle);
which [ReadOnly] is the good one?
ok that was it
strange that unity/rider doesn't show that there is conflict with attributes
Unity.Collections.ReadOnly is the right one
Yep. Very annoying.
Also, I typically inline the GCDFE call. Repeating as necessary.
healths = GetComponentDataFromEntity<Health>(true), ... (rest of new ApplyAttacks code)
I dont have any examples since I just deleted all my entities code so... hrm.
There isnt one but it makes cases where something tagged RO or RW is suppose to be the opposite and thus easier to find and debug
there's actually a pretty bad cost of doing GetComponentDataFromEntity
one of the optimizations we had to make was to burst compile all these calls in large systems
it halved our system main thread time
it's also a very dumb cost by unity
bursting the scheduling or exposing the component data pointer?
GetComponent is basically out of order memory access I'm not sure there's much Unity can do about that
bursting the GetComponentDataFromEntity
I recall several hours of testing in this very discord that showed about 20% speedup when using the pointer using ComponentDataFromEntityExposed and skipping the memcopy that unity enforces to prevent RW on a RO GCDFE.
The call itself? In the systembase?
Dependency = job.ScheduleParallel(_query, 1, Dependency);```
original implementation, lots of little systems - 6ms
merging to single system, lots of little jobs - 2.5ms
1 single system, merging into 1 large job (reusing Gets) - 0.75ms
1 single system, 1 large job, burst compiling Gets - 0.35ms```
quoting myself from a discussion i had when helping another studio a few weeks ago
huh, that's wild
we previously had a optimization that the first call to GetComponentDataFromEntity did it on the system, but any subsequent directly called EntityManager instead
but yeah, just burst compiling it even better
bursting the job population is not something I would've thought possible. Wow. I'll need to get back to you on how you manually populated that job.
of course it is! this is basically what ISystemBase can do
Right now I'm doing graphics touchups so my mind is completely off gear from DOTS. Still, 6ms? That is extremely long.
but yeah the problem with these GetComponentDataFromEntity calls is if you step through it's the AddReaderWriter method leading to CalculateReaderWriterDependency.Add
which is done, every time. this becomes very costly in systems with a lot of dependencies.
My job scheduling is practically non-existent compared to the size of jobs themselves.
In the order of 1ms to fractions of 1... Wait, is this one giant job?
Like you merged all the systems into 1 job. Wow
at the over time optimization
we dont only have 1 system
this was just 1 part of the AI
I thought it would be better for cache if there's many systems with many small targeted jobs
i think this benchmark was for the ActionExecution part
So you're saying that if I cram everything into a single job, practically shove in the entire entity storage, it's better for performance?
well it removes a lot of main thread overhead
If my entire game logic was one job with only dropping out to update UI every frame, that's better?
the main advantage of large jobs is it removes a lot of main thread overhead, but it also utilizes threads a lot better
if you ever profiled a lot of small jobs you'll see a lot of wasted time between these jobs
Yea, but I've seen them to be minuscule. Orders of 0.1ms between jobs
true... hrm
im not advocating single job for entire project, thats dumb
and a lot of the optimizations i've been doing i would only advocate on low end mobile or previous gen console
because code maintainability is important
but we have organized this in a way its pretty maintainable
My jobs run on orders of magnitude of 10ms to 100ms. Currently with 5 jobs running one after another. I guess subtracting 0.1ms * 5 between all 5 jobs really isnt anything.
yeah that's nothing
and of course the mega-singlethread structural change job that runs on the order of magnitude of 5 to 8 seconds (really need to revisit it... or my entire entity structure)
but if you build say a utility system that is scoring everything
and the job is simply
consideration.RawInput = setIsEntityDead.TrueValue;
}
else {
consideration.RawInput = setIsEntityDead.FalseValue;
}```
and you have 200 of these tiny scorers
when they're split in 200 systems/jobs
huh, yea. Definitely need to merge that
well you get the above
(i didn't write our AI, just fixed the performance issues with it)
very interesting. Bursting job creation is not a priority for me but seeing how it's done is very useful.
my personal AI system is entirely 1 job but it's actually built using a graph
and can be edited at runtime which i think is sweet
AI is in the very distant future for me. I'm trying to just settle on one conclusive entity structure.
It seems I cannot find a way to perform physics casts on worker threads. Keeps throwing error that I am trying to read from CollisionWorld during physics build/step blah blah blah. Is this true then? Any physics related calls need to be handled on main thread? Or at least job.Complete before next fixed step iteration?
no. they do not need to be completed on the main thread
Do you mind giving me an example of how I can achieve this. Preferably not wrapped in the Entities.ForEach job, but using EntityQuery and IJobParallelFor or IJobEntityBatch.
you need to add dependency handles
imo its a horrible requirement (so i wrote my automatic dependency handle system for physics to not have to do it)
so I have this simple system here and I'm getting the error error DC0002: Entities.ForEach Lambda expression invokes 'Format' on a PerformActionsElementRequirementSystem which is a reference type. This is only allowed with .WithoutBurst() and .Run().
Entities.ForEach((ref PerformActions performer, in DynamicBuffer<ElementRequirement> requirements) =>
{
var elementBuffer = GetBufferFromEntity<Element>(true)[performer.Dealer];
foreach (var requirement in requirements)
{
var element = elementBuffer[(int)requirement.Type];
if (element.Count < requirement.Amount)
{
performer.Status = IPerformActions.StatusType.Failed;
performer.Message = $"Not Enough {element.Name}";
return;
}
}
}).Schedule();
I can do this:
performer.Message = "Not Enough ";
and this:
performer.Message = element.Name;
but not this:
performer.Message = $"Not Enough {element.Name}";
Why is this?
performer.Message = $"Not Enough {element.Name}";
this is allocating a new string (managed object)
which is not allowed
because $"Not Enough {requirement.Name}" is a managed string
it's creating the string
then converting it to a fixedstring
performer.Message = "Not Enough ";
wouldn't this have the same issue then?
no because burst has added support for this
it can use static strings
by simply writing them as a resource in the burst file
if you ever inspect a dll it'll literally just have any static strings hardcoded in the header
it doesn't need to create them, it's smart enough to make sure they already exist
because it's allowed in debug.log

i suspect your actual issue might be the conversion of fixedstring to string
though maybe not because of your error
yeah if you even look
public override String ToString()
{
return this.ConvertToString();
}```
FixedString128
even specifically states it's not compatible
rule of thumb is don't make your model manipulate strings, leave that for your presentation layer
yeah makes sense, I guess I could just provide the requirement.Name and a separate index into an array of possible strings to prepend ("Not Enough", "Too Many", etc.)
then the presentation layer can join them
Yeah I tried every combination I could think of and find, and it doesn’t work unless I for job handle to complete on the same frame or run it on main thread.
show code and error
Jobs emerging from DOTS must, typically, complete by end of frame. Graphics update to next frame will wait until all scheduled DOTS jobs complete. You can get around this with multiple worlds but it's a mess
Thank you.
that's not really true, there's nothing that forces entity jobs to complete except the same system updating on the next frame.
we run a lot of our jobs simultaneously with the render pipeline
and nothing stops them continuing into next frame
a real world example of a job running well into the render pipeline without blocking it (super slow because of old consoles though I've also fixed this job since)
huh
it appears that Unity integrating Native collections support
into different parts
I can imagine they want to do it everywhere. Being able to use native arrays with meshes has made so much simpler.
man, I like the future
I love NativeArrays to replace regular arrays. Disposal is a little more annoying but its great being able to create and destroy an array super quickly
Oh I mean without having to worry about garbage generation
If I need to use an array[] I'll make it in the class instead of a local variable
what's the difference between your own disposal and GC disposal tho?
You never ever want to generate garbage in a game.
Because at some point, the GC will run and dispose of all that memory which can cause frame drops
Disposing a native array doesn't cause a frame drop
NativeArrays are especially useful if you need a new variable sized array every frame. Instead of keeping a list in active memory and clearing it every frame with .Clear() you can just create and destroy a native array every frame.
May or may not be faster, but it solves GC problems
hm
but isn't iteration speed over it's elements defeating the purpose?
I heard it's like 10 times worse
than iterating over linq List
I mean normal List<T>
well, that doesn't affect what I mentioned
I'm trying to create an entity and then add it as part of a DynamicBuffer IBufferElement, but when I do that I get the following error: All entities created using EntityCommandBuffer.CreateEntity must be realized via playback(). One of the entities is still deferred (Index: -2). Can someone shed some light on what's going on?
so you could have just 1 value, the count is 1 and then 7 other unitialized memory
I guess gotta test it through
The entity command buffer needs to be executed before you can do stuff to the entities created @verbal pewter
I don't understand what you are saying
doing for loop over native arrays
was mentioned several times to be about 10 times slower
than over normal array
last time about yesterday
oh about that huge array
@worn valley So after creating an entity with the EntityCommandBuffer we can't do anything with it and have to wait until the next frame?
something funky is going on with that person's code. It shouldn't take 7ms to get a length.
@verbal pewter You can, you just need to figure out the sync point where the EntityCommandBuffer can be executed
I seem to recall (It's been a while) that you can assign components to newly created entities with the entity command buffer, but you just need to make sure it executes itself first
ECS is all about the sync points. In some code I wrote a year ago I had about 5 sync points throughout a frame to make sure everything was working well
You may have to create a custom execute group
that's not the only mentioned
eh
Let's just wait till some test results come up
so we can actually see if it's faster or not
Someone mentioning problems on here with their code (That you can't see) is no way to determine if there is a difference between a native array and a regular array. We have no way to know either way.
@worn valley I'm trying to create a flexible system for managing agent behaviors/actions. Each agent has a DynamicBuffer that holds "memories." One of the agent actions is creating a new memory, represented by an Entity. I would really need to be able to create it and immediately assign it to the agent's memory DynamicBuffer. It sounds like this isn't possible? Are there any common work arounds for doing something like this? It seems like pretty basic functionality.
Or can we force the ECB to execute?
Unfortunately this is beyond my knowledge. Dynamic buffers are pretty complex since the memory size can fluctuate. So yeah I am not sure.
You could also use fixedarrays if you know the memories aren't going to be huge. I think those can be assigned like that.
But I do recall being able to add components at the same time as creating entities. BUT I could be remembering wrong. I used a much older ECS version than .17
Yeah, I'm able to add a component to the newly created entity. There just seems to be an issue with adding a reference of that entity to a DynamicBuffer.
Oh I see, the dynamic buffer holds an entity reference? Yeah until the ECB is run, the created entity doesn't have a proper ID for you to reference
I don't know how you'll do that. That is a pain in the butt. Sorry!
I just came across EntityCommandBuffer.AppendToBuffer, which evidently can remap. Will give it a try.
This is just such a basic thing that I can't imagine Unity doesn't provide some kind of solution.
It works! Wohoo 🙂
oh heck yeah
I haven't heard of appendtobuffer
ECS is super powerful but there is a ton of stuff that is WAY harder
TIL, compute shaders RWTexture2D are clamped wrapped and there's no way to change that
I know this is dots but I hope y'all can learn from my 9 hours of debugging
has anyone ever tried ecs but for grass?
I used ECS for a rope system and it was great. But if you just need grass that doesn't interact a GPU shader will work great
I assume GPU shader grass is only for non-interactive kind of thing?
you can always send interaction data to GPU and calculate whatever
no I mean if you use geometery shader
that would mean your grass only exists on GPU
thus no cpu interaction
but you can send data to the GPU by buffers
that means you can interact but yes not on the CPU 😄
What type of interactions would you be wanting to do on the CPU
as for example, it would be fairly easy to send simple collider data to calculate bending of the grass
someone posted full tutorial how to do that
in geometery shader
recently
interesting stuff
nice, have you link to this tutorial?
yeah, exacly what I had in mind
some time ago I made animation instancing on the gpu
and lately I was wondering if I should add IK to it
isn't that just a check in the material in SPR?
yeah, check ComputeBuffers
it only works in built in for me
I'v worked with indirect instancing before
but now that I'm actually working in unity with URP
it just won't work for some reason
What does frame debugger say?
It will tell you why a draw call couldn't be batched with the previous
no, it's not about batching
it's about drawing through graphics api
Graphics.DrawMeshInstanced
batching is supposed to be disabled completely here
but I swear, I couldn't find a single mention of people successfuly using gpu instancing and using SRP
depressing stuff
im currently using URP with my GPU instanced animation renderer
using Graphics.DrawMeshInstancedProcedural
and I didn't had any issues
besides my own incompetence XD
the main problem I have with it is that I need at least 2021.1 and hybrid renderer don't work for me with this version
so I need to render everything manually
not sure if this related to DOT channel or more suited in #↕️┃editor-extensions channel but I got shader compiler and build errors please check out the thread if you have any idea
could you share some code?
Of how you set up MPB and shader
sorry i meant why it's not instanced
what is your shader?
only individual Draw calls worked
are you trying to write it yourself or was it through shader graph
I tried shader graph with custom function that grabs instanced data
and amplify
amplify shaders won't even compile if I add any instanced property
are you using SRP batcher?
I disabled them before my attempts
hmm not sure then
all i know is gpu instancing doesn't work with srp batcher
but yeah this is definitely not my area
I'll give it a try some time later, but I really could use help of someone who worked with it
area is so shady atm
makes me want to switch to built in
Its great when you optimise a job, managed to get one down from 6000ms down to 3ms
that's a bit of an insane difference
I know the first approach was really naive and just using lots of getcomponents though
Someone knows some good way to deal with animations in DOTS? a good article or video will help! I need to control a simple ship in a Asteroids clone, and want to use some values in the components to modify the animations, or trigger another. i.e. when I pick up a shield, I add the Shield component to my player entity, and I want that to trigger the sprite of the shield on.
how do you make a communikation between UI and ECS?
its not that tricky you can get entity components in monobehaviour or you just acquire references to the UI stuff in a system
👏
can I use jobs and threads in one project?
I think so, except the jobs system expands to always use the number of virtual cores in your CPU. So it may cause issues if your threads are interrupting you jobs. Why do you want to use both?
I dont see anything stopping ya.
Unity doesnt instantly halt all other programs running on ya computer when you press play. Those external programs run on separate threads.
I have old code that uses thread but I want to change some of it to jobs/ECS
so I don't know if I need to "all in" on this or it's safe to mix
Oh yeah you'll be fine. And yes about the other threads @robust scaffold. I just saw somewhere that the jobs system will just use all your cores. You can also limit the number of cores you are using in ECS / Jobs too if you want to 100% sure ensure that other threaded programs are able to run
I doubt it'll make a big difference unless you have some crazy code going on
My ancient image processing job (runs on button click in the editor itself) nearly freezes my computer when I run it. I really should get around to converting it to a compute shader or blit material but it's so convoluted and interwoven that I'm terrified of touching it.
thanks
@robust scaffold I am always terrified of touching something that seems to work but is pages of code that I understood once but no longer 😛
Especially since this singular monolith of a code generates the runtime files that everything else runs on. If, in my refactoring, I accidently change how it outputs something, literally everything will explode.
If I were to go back and recode it from scratch, ignoring the dangers, i could make it run 20x faster. Guaranteed now that I know how to code. But why break what already works. i only run it maybe once a month if I change the base input files.
😰
Newest C# comes with default struct constructor override capacity. Every day structs become closer to classes...
yeah i like it but i'm a bit concerned it's going to cause some errors
var struct1 = default(MyStruct);
var struct2 = new MyStruct();
will no longer be the same thing
be very risky to override default constructor in existing projects imo
but there are many cases this will be great in new projects
True, but I never use default since I have my IDE set to enforce var and not strong types so I'm locked and loaded for struct constructor overrides.... in 4 years when Unity gets around to implementing it.
That's terrible
Hello there, i have problem with this system
my profiler show me this
soo for me its very simple code and im not really sure what it can take so long? Any advice what can i additionally check?
1 - remove WithBurst()
excuse me, but why?
2 - use the generic versions to add components
Entities.foreach is bursted by default. .WithBurst() is only to be used with advanced parameters
how does it affect performance? And i will be glad to read about advanced parameters and WithBurst() more, any links or something?
without parameters it does not affect it much. you still have 1 more method call
still bad practice to include redundant logic
thank you I will fix this
other than that, your semaphore.waitforsignal means that your job is waiting to receive the signal that your needed resources are not currently used by anything else
what does it exactly mean ? Another job executing and this RemoveObjectOutBoundBoxSystem waiting while execution of another job end?
maybe. probably
You can try a couple things to figure out whats happening. Im not familiar with your ObjectStorage system. Is this something you created? It would be worth profiling. The other thing to try is to profile the system in more detail, like looking at the job timings in the profiler and how they are split amongst workers, or disabling burst for the ForEach so you can really drill down into the details.
Also hello DOTS channel.
ty for tips. ObjectStorage just NativeHashMap
You'll know better what to do when you can see the timings for each line of your job
Im going to guess your trouble are related to the hash map
no. the semaphore is literally waiting for data to become available
Replace schedule parallel with just schedule. Often with these read and especially write operations, you get significantly better performance when it's only 1 thread.
On a side note, I will reiterate what I said following the first time unity posted that December 2021 update: Unity communicating with the forum public was a mistake.
disagree
@half jay if you use the timeline view for the profiler you can find exactly what the job is waiting on
thank you very much. Sry for being meticulous, but is there an explanation for this? Maybe I can check it somewhere in the documentation? Or is it also your personal statistics / practice
parallel writes to the same output is always really slow in comparison. that's common knowledge
because it always has to make sure that only 1 writes at any given time and completes. otherwise you'll get back invalid data
does that still apply when you disable the safety checks 🤔
yes
Also disagree. People were going insane saying that unity was abandoning ECS and such. At least they gave us a sliver of hope around DOTS and confirmed it is in the future. I think they can't say as much as they used to when they were a private company.
I thought that using WithNativeDisableParallelForRestriction places the responsibility on the programmer that the data will not overlap and therefore there is no such restriction as you wrote above
it does not. it just makes it possible to do these operations at all
it places the responsibility on the programmer to make sure that the in data does not alias
they must have changed it in an update because I know I've accidently changed a single variable in multithreaded job and came out with the expected wrong result
you cannot come out with the 'expected' wrong result because there is no telling when what job is executed. it will be random
I like to play fast and loose with the RemoveNativeRestriction and boy do you get some crazy results sometimes
i solved 95% of all my problems without removenativerestriction and the solutions i came up with are even more optimized than the dirty solutions with removenativerestriction would've been
well I mean the result was wrong because I had 12 threads all adding to a value and I expected it be 12 in my naivety but instead the result was 1 or 2 because each were getting the original value
but I did not understand that at the time
I just use the raw pointers to do operations with and go wild with type conversions. Safety checks isnt a problem if the code never encounters them.
then they're still writing each on their own, and not at the same time
interlocked.add
praise be the interlocked
no
yes
you can actually do that 
interlocked solves all problems with threading. trust me
got it 👍
but you admit it is a solution
The Interlocked class is defined in mscorlib which is CLS-Compliant and UInt32 and UInt64 are, for better or for worse, not CLS-Compliant.
Interlocked.Add(Int32) and Interlocked.Add(Int64) are CLS - Compliant.
Well partial...
Anyway, who else would love for c# to add postfixes for all number formats?
Nah. There's already a difference between int and long. And numbers in type names is just distasteful.
I mean. 123456789L. Exists. I want 244b. As well for example
Wait, for constant value declaration?
Yes
Oh yea, that would be nice. But b is already used for Binary.
0b111011 and so on
s for short?
s. Signed byte
I don't remember the other proposals right now unfortunately. Anyway my point is, I want postfixes asap. Why is it not in c# yet.
Alright, i think it's time to take the plunge. Im gonna rewrite my file loading system to output blittable structs.
Now that I can do parallel "structural" changes
It's roughly 20 files with over 200 lines each, written 3 years ago. Pain.
Hey, I have a GameObject with this script:
public struct EnemyPrefabArray
{
public BlobArray<Entity> prefabs;
}
public struct EnemeyPrefabsDatabase : IComponentData
{
public BlobAssetReference<EnemyPrefabArray> Value;
}
[UpdateInGroup(typeof(GameObjectDeclareReferencedObjectsGroup))]
public class EnemyDataHolderBehaviour : MonoBehaviour, IDeclareReferencedPrefabs, IConvertGameObjectToEntity
{
[SerializeField] public GameObject[] enemies;
public void DeclareReferencedPrefabs(List<GameObject> referencedPrefabs)
{
foreach(var go in enemies)
referencedPrefabs.Add(go);
}
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
var prefabs = new NativeArray<Entity>(enemies.Length, Allocator.Temp);
for (var i = 0; i < enemies.Length; i++)
{
prefabs[i] = conversionSystem.GetPrimaryEntity(enemies[i]);
}
using (BlobBuilder builder = new BlobBuilder(Allocator.Temp))
{
ref var enemyBlob = ref builder.ConstructRoot<EnemyPrefabArray>();
var blobArray = builder.Allocate(ref enemyBlob.prefabs, enemies.Length);
for(int i = 0; i < enemies.Length; i++)
{
blobArray[i] = conversionSystem.GetPrimaryEntity(enemies[i]);
}
var blobAsset = builder.CreateBlobAssetReference<EnemyPrefabArray>(Allocator.Persistent);
dstManager.AddComponentData(entity, new EnemeyPrefabsDatabase{Value = blobAsset});
}
}
}```
And I have a really strange bug when accessing this data, when I try to instantiate from those referenced prefabs (using their stored PrimaryEntity), I get completely another entity that is not related.
Am I doing something wrong when using AssetBlobs?
It seems that if I change the assign GameObject in this script, the entity I get from Instantiate is different
So I assume somehow the system is reading the wrong data (or writing the wrong data?)
enemyDatabaseQuery = GetEntityQuery(ComponentType.ReadOnly<EnemeyPrefabsDatabase>());
// In OnUpdate
var enemyDatabaseEntity = enemyDatabaseQuery.GetSingletonEntity();
ref var prefabsDB = ref EntityManager.GetComponentData<EnemeyPrefabsDatabase>(enemyDatabaseEntity).Value.Value;
// Later in Entities.ForEach()
ecb.Instantiate(prefabsDB.prefabs[0]); // Spawn the wrong entity
shouldnt be using blobs to store entities
So how can I store the prefabs entities?
dynamic buffer or just a field
Okay thank you 🙂
I actually prefer fixed fields:
public unsafe struct IntB16
{
public const int Length = 16;
private fixed int _elements[Length];
public ref int this[int index] => ref _elements[index];
}```
the ushort used for length and count variable in fixed list fucks with vectorization
I could probably create a "count" of this buffer by -infinity terminating the list.
so are you saying fixedlists are slower in jobs?
Slower, kinda. Barely. Really depends on what you're planning on doing with it.
[NoAlias] public NativeArray<String32> Names, Capitals; // Equality vectorized.
[NoAlias] public NativeArray<int> Owners, Controllers;
[NoAlias] public NativeArray<IntB16> Cores; // Check for any equality vectorized.
[NoAlias] public NativeArray<Flags> Flags; // Check V, Enable V, Disabled V. Check is most expensive.
I'm primarily using these lists as giant flags. Check if element exists and enable and disable (add and remove) are vectorized using these fixed fields. Fixed list would not due to the ushort length and count variables at the start.
Ok cool, as long as they aren't that slow the above is a level of complexity that is beyond me 😕
If you're using these lists as actual lists: adding and removing components and with really dynamic sizes (my lists are preallocated to multiples of 8). Then yea, stick with UnsafeLists or FixedListX.
I can’t get OnSceneGui to draw Handles.Label while DOTS live link is in Play State view instead of legacy mode. Is there a way to make this work, or is this a limitation of current 0.17 entities package?
Is this the place where I would ask about Unity's Job system? I have question about NativeContainer and how I can work this out. If not, can someone help point me to the right direction where I can ask question about this topic?
Yes. This is the right channel.
A lot ask about Native Containers, I recommend you do a search on this channel for your keywords before you ask. Your question most likely was answered many times over in the past 😉
So I'm trying to create a nativeArray collection of bytes, receiving from Texture2D.GetRawTextureData(). However, I have an finite image I need to append to a job system. How would I go about creating an List of array of bytes?
As you probably are aware you can't nest NativeArrays...
however, you may use something like NativeArray<UnsafeList<YourStructHere>> instead.
Are you familiar with Unity.Collections.LowLevel.Unsafe caveats?
Nope.
I'm still trying to grasp how powerful the job system, but still not familiar with IJobParallelFor yet.
I got a basic IJob system setup, and that works really well.
There is NativeList and UnsafeList basically, the Native containers have error checking and leak checks and things of that nature, but Unsafe containers do NOT, you have to manually keep track of that and make sure allocate and deallocate them proper. Otherwise you can have leaks and not know about them, other than that they work pretty much like Native container.
NativeContainers are wrappers for UnsafeContainers.
The other thing is that I can't have reference to a game object, but could I create a pointer to an object I need access to? I'm trying to combine Textures together.
And I've noticed that the more images I need to combine, the more time it takes to call GetRawTextureData per each image I need to combine.
Thought I could get around by passing in a pointer to Texture2D object and then call GetRawTextureData within the job system.
Have you considered using a compute shader for this? I image it would be much more up the alley of a GPU operation rather than CPU/Workers no?
At least have the compute shader process image data before trying to apply the mutated data back to managed member(s)
strictly speaking, the GPU is very limited on the hardware I'm working with.
That would most likely squash your "the more images I need to combine" issue.
Ah I see.
Well I'm afraid I can't be much more help than this, wait for someone more qualified than I to answer your question
I'll take a look into UnsafeList! Thanks!
Does it have to be container in container specifically?
Isn't separating it into array of jobs possible?
ping
No because I needed to combine a source image with multiple overlapping images in the same job. @rustic rain
Currently, I have a job that runs through two images to combine, but that means I have to keep re-running the same job for additional images I need to append.
Would like to try reading the texture raw data, combine textures, encode to png, and save it to disk all inside the job system if possible.
No managed types in job
Otherwise, I might just have to use the Threading task system to do this.
guess the only use for the job is to combine texture.... other than that, I'll have to use the threading to do other operation async
About nesting containers btw
I still don't get the reason why it has to be in one job.
I'm calling multiple jobs per source images I need to combine, but they all need respective images to combine to the source.
If it's about just passing read only data
source isn't readonly, but the images I need to append is readonly.
I think you can use struct pointers for this
Can I get some examples for this?
So you can access same data from different jobs
Eeeeh. I'm really uncertain, but potentially ComponentTyprHandlr
In ecs
I never looked inside of it
But I think it's just struct that holds pointers to all component data
Kind of a wrapper for developers to avoid using 'unsafe' themselves
