#archived-dots

1 messages ยท Page 114 of 1

dull copper
#

I mean, why need WithAll at all when you can do same filtering by adding them on ForEach

#

but I then remembered that foreach only iterates componentdata with actual content in it

warped trail
#

my guess is WithAll is just for entityQuery and foreach creates iterators๐Ÿค”

#

ForEach is just IJobChunk in the end

dull copper
#

ah, so it's potentially cheaper that way

warped trail
#

but it is just my guess๐Ÿ˜…

opaque ledge
#

Well i use WithAll to have those tags in my component but i am not interested in reading them, i just want them to exist in my entity. It also lowers burden to 6 limit of ForEach lambda components

dull copper
#

has there been any official word on what's the deal with readonly (or lack of it) on Entities.ForEach

#

they didn't feel it was needed?

mint iron
#

im not sure i follow, you can use in for readonly

opaque ledge
#

there is already readonly components in ForEach, you have to put "in" instead of "ref"

#

if thats what you mean

dull copper
#

huh

#

I suppose then ๐Ÿ˜„

#

well, that would explain this "mystery"

warped trail
#

can you put PhysicsWorld to "in"? ๐Ÿ˜…

dull copper
#

that was actually where I remembered this

#

but it wasn't really because of the foreach, but the different structure otherwise

warped trail
dull copper
#

that's coming on some future physics package?

mint iron
#

that code seems very odd to me

dull copper
#

why is that WithAll needed there?

warped trail
#

i think that was just some sort of concept thing

autumn sleet
#

@mint iron entire lambda stuff seems pretty odd to me

dull copper
#

pretty sure lambdas arrived specifically to reduce the boilerplate

bright sentinel
#

@dull copper WithAll (and WithAny and WithNone) are cheaper, because they just have to check if they exist, they don't have to go and get the data.

dull copper
#

we didn't have them initially

#

@bright sentinel but in that example snippet, would it really benefit to do both WithAll and ForEach for the same Health component?

opaque ledge
#

nope it doesnt, and yes i think thats just a concept

dull copper
#

just checking ๐Ÿ˜„

bright sentinel
#

Ah right, no it doesn't make sense to have them in both

#

Not sure if it actually double queries them tho

#

Hopefully not

dull copper
#

oh snap

#

"Unfortunately, this year, after much thought and deliberation, we have made the difficult decision to pull out of GDC 2020."

opaque ledge
#

and it actually gives error to have them both on ForEach and WithAll

#

"EntityQueryDescValidationException: EntityQuery contains a filter with duplicate component type name CampaignEntityTag. Queries can only contain a single component of a given type in a filter."

#

this is what i got when i put CampaignEntityTag to both ForEach and WithAll

bright sentinel
#

Well there you go

opaque ledge
#

Also i managed to do collider cast after i inspected unity's entity physics samples, i am so proud of myself \o/

dull copper
#

so to get back to the thing I remembered wrong... you can't set [ReadOnly] anymore for structs that exists already that you want to feed into Entities.ForEach... that physics collision world is one good example of it

opaque ledge
#

physics collision world is not a component tho ๐Ÿค”

#

right now there is no way to get read only physics collision world, but there is a hack for it so you can do your raycasts in peace

dull copper
#

yeah, I remembered the readonly thing was for ForEach

#

yes, I'm using that hack now

opaque ledge
#

i bet they will do CollisionWorld.ToReadOnly() in future

#

readonly thing was for IJobForEach structs

dull copper
#

you'd think it's not just physics that is potentially affected

#
        [BurstCompile]
        public struct RaycastJob : IJob
        {
            public RaycastInput RaycastInput;
            public NativeList<RaycastHit> RaycastHits;
            public bool CollectAllHits;
            [ReadOnly] public PhysicsWorld World;

            public void Execute()
            {
                if (CollectAllHits)
                {
                    World.CastRay(RaycastInput, ref RaycastHits);
                }
                else if (World.CastRay(RaycastInput, out RaycastHit hit))
                {
                    RaycastHits.Add(hit);
                }
            }
        }```
#

that's again physics related example

opaque ledge
#

Yeah, i tried that putting "WithReadOnly(collisionWorld)" but it gives an error

#

in future i hope ๐Ÿ˜„

bright sentinel
#

Is there a reason you want to get a readonly version of the physics world?

dull copper
#

that would be the logical place for it

bright sentinel
#

I'm pretty new to DOTS Physics, so I don't really know that much about it yet

opaque ledge
#

to raycast in peace ๐Ÿ˜„

dull copper
#

it breaks without, unless you do the ForEach on main thread

opaque ledge
#

when you do a raycast you have to get collision world, and Unity thinks that when we get collision world we are modifying it so it gives errors

bright sentinel
#

Ah I see

opaque ledge
#

so you have to do read only hack to do raycast for the time being, until they introduce read only collision world

bright sentinel
#

Is that on their radar?

dull copper
#

no idea ๐Ÿ˜„

opaque ledge
#

i dont think so ๐Ÿ˜„

dull copper
#

the hack:

public struct CollisionWorldReadOnly
{
    [ReadOnly]
    public CollisionWorld collisionWorld;
}```
```cs
        var collisionWorldReadOnly = new CollisionWorldReadOnly
        {
            collisionWorld = buildPhysicsWorld.PhysicsWorld.CollisionWorld 
        };```
#

and then cs if (collisionWorldReadOnly.collisionWorld.CastRay(input, out hit))

#

just feels dirty

warped trail
#

but this does not work woth physicsWorld๐Ÿ˜•

dull copper
#

oh?

warped trail
#

at least if i did everything right๐Ÿค”

opaque ledge
#

yeah, both physics world and collision world has raycast methods, not sure which one we suppose to use, but collision world is fine for now ๐Ÿ˜„

warped trail
#

physicsworld just cals collisionWorld.CastRay

#

but there is no motion data in collisionworld, it is in dynamicsWorld

dull copper
#

just tried it here, no dice

warped trail
#

did you use FinalJobHandle?

dull copper
#

yes

#

when setting PhysWorld to readonly with that hack it says
InvalidOperationException: The previously scheduled job TestSystem:<>c__DisplayClass_OnUpdate_LambdaJob0 reads from the NativeArray<MotionData><>c__DisplayClass_OnUpdate_LambdaJob0.Data.physicsWorldReadOnly.physicsWorld.DynamicsWorld.m_MotionDatas.
You are trying to schedule a new job Solver:ApplyGravityAndCopyInputVelocitiesJob, which writes to the same NativeArray<MotionData> (via ApplyGravityAndCopyInputVelocitiesJob.MotionDatas)

safe lintel
#

did you also add update after buildphysicsworld?

warped trail
#

collisionWorld works in my project

dull copper
#

[UpdateAfter(typeof(BuildPhysicsWorld))

#

yeah, collisionWorld works

#

just not the physicsWorld

#

what you need that motion data for?

bright sentinel
#

If a ForEach query has a ReadOnly component, how will that change how that job dependency is handled?

#

Compared to a ReadWrite component

mint iron
#

strange, my raycasts haven't been effected by recent changes

dull copper
#

you probably use the traditional job structures still

mint iron
#

ahh yes, thats it im just doing an IJob

dull copper
#

yes, that still works the same

#

also Unity Physics samples on the sample repo still use IJobs

#

so, it's not like we couldn't work around this

#

just need to do more of that boilerplate code again

zenith wyvern
#

@bright sentinel It will allow other systems that schedule a foreach over that read-only component to potentially have the job run in parallel

#

If the lambda took the component as ref instead of in it would be forced to run in sequence instead

gusty comet
#

Hi, do you know how can I change a material from an entity? I've tried with a foreach, with an EntityCommandBuffer, I can't find the correct way to change it...

bright sentinel
#

@zenith wyvern Okay, but what if those jobs modify the component? Won't that bring some issues?

zenith wyvern
#

Like I said Unity will force them to run in sequence so there's no possibility of a race condition. That's the promise of the safety system

bright sentinel
#

Okay, so if I schedule two jobs, one with ReadOnly and one with ReadWrite at the same time, they will still be sequenced?

#

I mean right after each other*

zenith wyvern
#

@gusty comet

var renderMesh = EntityManager.GetSharedComponentData<RenderMesh>(entity);
renderMesh.Material = newMat;
EntityManager.SetSharedComponentData(entity, renderMesh);
#

There are performance implications for this, read up on how SharedComponentData works

#

@bright sentinel Yes, Unity won't let a ForEach job read from a component while it's being written to

#

You can only read in parallel

bright sentinel
#

Ah okay, thanks.

opaque ledge
#

yeah, thats why its important to properly mark components with ref or in, so they can be scheduled in most efficient manner

sour ravine
#

Mike Acton (senior DOTS guy) is really big about thinking about data modification patterns and that's an example

#

not just 'can I change this to readonly' but 'can I arrange so this is unnecessary to begin with'

#

since it often makes things simpler to understand (can't read or write data you never see, etc.)

opaque ledge
#

awww rip DOTS stuff in GDC ๐Ÿ˜ฆ

warped trail
#

they are not dead๐Ÿ˜…

opaque ledge
#

i was pretty excited tho ๐Ÿ˜„

zenith wyvern
#

I wonder how they're going to do the keynotes now. Just a dude in front of a camera or something

opaque ledge
#

but yeah totally understandable

gusty comet
#

thank you @zenith wyvern, where do you do that?

dull copper
#

I imagine they just produce some limited amount of content now

opaque ledge
#

is there a difference between doing Run and doing Schedule and do Complete right after that ?

warped trail
#

Run is on main thread, schedule is single job that can run at worker thread

zenith wyvern
#

There would definitely be some overhead from scheduling a job

opaque ledge
#

i just see some people scheduling a job and do Complete right after that, was just wondering if it is better to just do Run

zenith wyvern
#

It depends. If they're scheduling a ForEach it could potentially benefit from being able to run parallel across multiple chunks. That will only happen if you schedule a job. So if your entity count is high enough to potentially cross chunks then it could be faster to schedule and immediately complete the job

#

I don't know exactly how much overhead there is for scheduling a job compared to doing .Run so hard to say when you would want to schedule vs run

warped trail
#

but Schedule is not parallel or am i wrong?๐Ÿค”

zenith wyvern
#

Hahah, I guess it depends if we're talking about SystemBase or JobComponentSystem

#

Thanks Unity

#

I'm specifically talking about a parallel ForEach vs the same ForEach using .Run

warped trail
#

oh, i already got used to SystemBase๐Ÿ˜…

zenith wyvern
#

Yeah it's funny if you write a foreach in SystemBase using .Schedule and look in the burst inspector you see that the job struct is compiles to gets called with "ScheduleSingle". Not sure why they did it that way

opaque ledge
#

tbh, i wish both were explicit, ScheduleSingle and ScheduleParallel ๐Ÿ˜„

zenith wyvern
#

That would be much better imo

gusty comet
#

oh god, I finally update that material !!! In fact you should use a ComponentSystem (not a Job) and use the PostUpdateCommands (not the EntityManager)

zenith wyvern
#

You really shouldn't, ComponentSystem is going to be deprecated at some point.

gusty comet
#

great !

opaque ledge
#

๐Ÿ˜„

#

haha

#

you can just do WithoutBurst().Run()

#

in a JobComponentSystem

coarse turtle
#

Or SystemBase class ๐Ÿ™‚

gusty comet
#

@opaque ledge I'm pretty sure I've tried it already and get error like can't set shared component at this time or something like this

opaque ledge
#

hmm ๐Ÿค”

#

well i never tried to do anything with shared component, but it should be doable ๐Ÿค”

gusty comet
#

@opaque ledge right, it's not a big change, I'll try it and let you know

opaque ledge
#

๐Ÿ‘

gusty comet
#

@opaque ledge InvalidOperationException: Structural changes are not allowed during Entities.ForEach. Please use EntityCommandBuffer instead.

warped trail
#

@gusty comet you can do cs var commanBuffer = new EntityCommanBuffer(Allocator.TempJob); Entities .WithStructralChanges() .ForEach(() { commandBuffer.SomthingSomething(); }).Run() commandBuffer.Playback(EntityManager); commandBuffer.Dispose()

opaque ledge
#

add .WithStructralChanges to lambda

gusty comet
#

Awesome!

#

it works ! Thanks a lot

warped trail
#

i think this thing with commandbuffer is equivalent to PostUpdateCommands ๐Ÿค”

opaque ledge
#

Yeah its kinda of a pain, you have to explicitly say what you are intending to do by making those methods, WithStructralChanges if you want to use entity manager, WithParallelDisabled for parallel writing, WithReadOnly for read only variables etc..

#

but it gets much easier once you get used to it

warped trail
#

oh, with commandbuffer you don't need .WithStructralChanges() i guess๐Ÿค”

#

and you can use Burst maybe?๐Ÿคทโ€โ™‚๏ธ

opaque ledge
#

yeah since you are not actually making any structral changes

#

nah i doubt that lol

warped trail
#

but not with shared components i guess๐Ÿ˜…

gusty comet
#

ahah

zenith wyvern
#

Using the Entity manager is faster than a command buffer. The command buffer just uses the entity manager indirectly so there's no point unless you're doing a lot of other work in the job that you would need to be bursted

opaque ledge
#

yeah but still, you are not creating a sync point, shouldnt that be more beneficial in the long run ?

warped trail
#

there is sync point at playback

coarse turtle
#

Well the sync point is the playback

mint iron
#

its pretty unfortunate, i continually hope that they will burst the playback portion of the ECB at some point soon.

opaque ledge
#

I mean.. if you dont use entity manager and use command buffer instead, you will be avoiding sync point ?

#

or rather, command buffer will be using default sync point, so that way you would avoid extra sync point

coarse turtle
#

the command buffer will be using the 'barrier system's' sync point effectively

#

and the playbacks are executed there

gusty comet
#

I've got a problem I'm trying to see how I can apply Burst to - is it acceptable to ask that here, or is this more for API q's?

opaque ledge
#

yeah please do ask CodePoke

warped trail
#

Burst is in in DOTS๐Ÿ‘

mint iron
#

@opaque ledge yeah a sync point is only a problem if its interrupting jobs, if all your sync point code happens together than its fine.

gusty comet
#

(Too large to post in here)

#

Essentially it's how to apply Burst to grid datastructures, and where to draw the line.

opaque ledge
#

if you make it line limit to 80 it would be much better to read, so we wont have to horizontally scroll

gusty comet
#

With the grid datastructure both being a spatial datastructure and a cache for int-driven bitsets of various gameplay characteristics

mint iron
#

i think, even if you ignore ecs completely, using burst over c# for querying grid structures (e.g collect node flags @ radius around xyz or pathfinding) will be at least twice as fast.

gusty comet
#

@opaque ledge Updated, although I'd imagine that you'd normally resolve that client side ๐Ÿ˜‚

scarlet inlet
#

today I found out that GameObjectConversionUtility works only on prefabs

#

I am thinking about another solution to solve my problem, which is deleting empty entities. For Empty entities I mean, in my case, Entities that have ONLY the translation, rotation and localtworld components

#

I guess the simplest solution would be to delete these entities after they are created, is there a way to make a query of entities that have ONLY those components?

gusty comet
#

@mint iron There'd be a tipping point surely, no? As in, every Job has overhead and if I back everything with native arrays a small (3x3) grid comparison would probably not save me time, but cost me on Job overhead?

warped trail
#

@scarlet inlet i guess you can play with writing groups๐Ÿค”

scarlet inlet
#

yeah? No clue what they are I have just read about them once and didn't understand the use case

mint iron
#

@gusty comet mean just that if you're doing the same thing in c# vs hpc# hpc wins (as long as the size of work is large enough per call - obviously setting a single property is or something trivial will be slower in hpc because of the extra jumps to get into the burst code); simply because one has an IL layer and the other doesn't. You could do it with a manually allocated arrays and burst with touch points into unity ecs if nessesary or you could try to structure your data into unity ecs properly and but it gets difficult to sidestep all the overheads and potential performance hurdles.

warped trail
#

there is good video with Mike Acton explaining them, wait a little bit i will find it๐Ÿ˜…

opaque ledge
#

Mike Acton works in Unity ?

warped trail
#

he is the main guy behind DOTS, i think๐Ÿค”

opaque ledge
#

oh, i thought main guy was Joachim

coarse turtle
#

Yea he used to work at Insomniac Games

scarlet inlet
#

I never understood what he does, but yeah he should be one of the main guy in SF

#

working on dots

gusty comet
#

@mint iron Can in someway have arrays which have little/no access overhead from both IL and hpc#? I.e. that way I can decide based on size whether I'll use one over the other.
To my understanding HPC# use would always go through the Jobs system and therefore have way more overhead - or overhead in the point where you transition.

safe lintel
#

@scarlet inlet ive used GameObjectConversionUtility for scene objects without problem

scarlet inlet
#

@safe lintel maybe, but in the way I have done it, it goes through DeclareReferencedPrefab

#

I don't know why, it's a GameObjectConversionMappingSystem.cs method

#

it's called by DeclareReferencedObjects(conversionWorld, conversion.MappingSystem);

#

that is called by the method Convert()

#

that is the main one

mint iron
#

@gusty comet you can call pure burst functions without anything to do with job scheduling. On my machine from testing if the work should take more than about 0.0040 ms is the breakpoint. a normal c# property access taking 0.0002, the fastest a burst method could run at 0.0004-0.0009 (if it was previously just run, otherwise 0.0040 uncached). In reality its not that much work, doing any sort of calculation in a loop probably breaks the threshold.

coarse turtle
#

yeah in my experience with DeclareReferencedPrefabs - i've only been able to do it on asset project files (scriptable objects, prefabs)

safe lintel
#

i think im ignorant on what the problem is

gusty comet
#

@mint iron That... sounds weird to me.. HPC# is native compiled, it's managed interopping then into native - there has to be some overhead.
But alright, I'll take that into account, thanks!
But essentially you're saying then that it's best to do the whole backing datastructure natively.

mint iron
#

yeah i think so; it will also be native obviously if you put it into Unity ECS somehow as components etc, but then you have other issues to contend with in exchange for convenience. Here's some comparisons i did about a year ago: https://github.com/jeffvella/UnityBurstFunctions but if i would do it again now i think they've fixed all the bugs with declaring burst methods and calling them directly - since they're doign exactly that in the EntityManager for many of the key methods . See also https://jacksondunstan.com/articles/5211

scarlet inlet
#

@safe lintel I think it's something to do with the IDeclareReferencedPrefabs pattern, when this is used, prefabs must be used. In other cases I think you are right

mint iron
#

@scarlet inlet yeah prefabs must be used, unity accepted a bug of mine a few weeks ago that was basically "unity throws confusing exception when non-prefab is used"

scarlet inlet
#

I don't understand why this limitation honestly

mint iron
#

especially since you could probably just create an entity, load it with components and add the prefab tag.

scarlet inlet
#

exactly what I wanted to do ๐Ÿ˜›

gusty comet
#

@mint iron So another aspect is that I access the grid based on arbitrary lengths (could be 1x1x1). It's hard to pour that mould into a Vector3/4.
If I use a NativeArray<float>, is there anyway I can check whether SIMD/vectorization is kicking in properly?

mint iron
#

if you can read assembly you can check in the jobs inspector

zenith wyvern
#

there is good video with Mike Acton explaining them, wait a little bit i will find it๐Ÿ˜…
@warped trail

Huh, this talk is really interesting. It finally explains why the insane transform system page in the manual is the way it is

opaque ledge
#

Yeah it is, but it was kinda boring ๐Ÿ˜„

mint iron
zenith wyvern
#

I have to admit I still have no idea what write groups are for after watching it, I'm going to rewatch it I think, hahah

opaque ledge
#

๐Ÿ˜„

#

As a a "casual" developer should i really care about cpu cachelines and stuff ? i mean i know how they work, why they matter etc. but in the context of ECS, i dont think there is a way for me to use cacheline in a efficient manner, no ?

#

i got the same feeling from dod book, i mean sure great i can understand the reasoning, but i have trouble make that knowledge into ECS context

mint iron
#

no you would't need to know know it unless you're trying to write your own low level systems or containers.

#

personally i'd heard a lot of stuff about cachelines, like the mike acton talks etc but its always glossed over, its just "cacheslines are the reason why we do xyz" - if you want to actually know wtf is going on its not all that easy to find the info.

opaque ledge
#

Yeah i can understand that.

#

i am still going to watch it tho ๐Ÿ‘€ ๐Ÿ˜„

#

thanks for sharing

warped trail
#

@zenith wyvern You have entity with components A and B. B is in A's writegroup. You have EntityQuery with All = component<A>. This entity will not be in this query, unless you explicitly include B.๐Ÿง

zenith wyvern
#

Ahh, that's if you include WriteGroupFilter in the query, gotcha. I'm still not clear on why you would want that though, what he benefit is

#

Oh there is actually a nice manual page for it, I have some reading to do

coarse turtle
#

Same here - looks like write groups are something I might want to be explicit in my UI system...

warped trail
#

cool thing, i use it to exclude my interpolated entities from default TransformSystem๐Ÿ‘

zenith wyvern
#

I think I get it, it lets you force a system to ignore an entity it would otherwise process by adding your own component to it. Almost like overriding the original system. Interesting

warped trail
#

i think this is how prefab and disabled components works under the hood๐Ÿค”

zenith wyvern
#

Right that would make sense

coarse turtle
#

So I think something like that would be interesting for a text generating system - you can imagine replacing a single character and updating the mesh, instead of tagging/untagging an entity to rebuild the mesh - you can simply force the vertex buffer to update its values ๐Ÿค”

vagrant surge
#

@opaque ledge arrays fasts

#

random pointers slow

#

more or lesss thats it XD

opaque ledge
#

lol i guess so ๐Ÿ˜„

vagrant surge
#

for a quick more detailed explanation:

#

memory is very fucking slow

#

so cpus cache it at different levels

#

whenever you try to load some memory adress, it will search in this caches first, and if its not there, it will go back to RAM (slow), and copy it to the caches

#

the data will stay in the caches for a while, until it gets overriden by other data

#

so what you need to try to do is:

  • Have predecible memory access patterns (array), as the cpu sees you are accesing stuff in an array, and will preload memory
#
  • Whenever you load memory, make sure that you use as much of its "nearby stuff" as possible
#

memory will allways load 64 bytes of stuff, 12 floats, whenever you load anything. Mostly useful when desigining your structs. If you allways use some variables together, then put them together in your struct

opaque ledge
#

๐Ÿ‘

vagrant surge
#

there are many other things on the whole "data oriented desing"

#

just read the book

opaque ledge
#

Sooooo, you cannot use NativeList for TempJob stuff ? .WithDeallocateOnJobCompletion doesnt seem to work on it

zenith wyvern
#

Use Dispose(jobHandle)

opaque ledge
#

ah ok thanks, i didnt know that exist

odd ridge
vagrant surge
#

keep in mind the L3 cache is like 30something mb on normal cpus

#

and 200 mbs on threadripper cuz amd are lunatics

#

a lot of stuff will be at least on L3 on normal game loops

#

unless you have absurd counts of objects

odd ridge
#

woah, I didn't expect ryzens to have that much cache

#

I thought 8mb was the norm for L3 cache

vagrant surge
#

amd are goddamn lunatics

#

200 megabytes of L3 on the biggest threadripper

round summit
#

I am assuming Unity.Physics use random solvers since collision trajectories are not aligned to the plane even though i align the objects in that plane
Do you think these random seeds are acquired from system time or positions of objects?
If it's not something like positions of the objects, i'll need to sync this time to improve determinism

formal scaffold
#

Why is my Raycast not pointing down when I move? Been looking at this for hours but I don't see my mistake:

        Entities.WithAll<PlayerTag>().ForEach((in LocalToWorld localToWorld) =>
        {
            var fromPosition = localToWorld.Position;
            var toPosition = fromPosition - new float3(0, 1.1f, 0);

            Raycast(fromPosition, toPosition);
        }).WithoutBurst().Run();
round summit
#

@formal scaffold
try this
var toPosition = - new float3(0, 1.1f, 0)

#

I saw in rollaball with ecs tutorial that toPosition is i think as direction
naming is misleading i believe

#

(i might be wrong though)

formal scaffold
#

WOW ๐Ÿ‘ Makes no sense to me since it's called toPosition and not relativePosition ๐Ÿง but it works thanks alot

round summit
#

oh yeah, great

#

@formal scaffold var fromPosition = localToWorld.Position;
is this how you get world position?

formal scaffold
#

Yeah or translation.Value which might be better since it only has the position stored. But I thought maybe I need LocalToWorld which I don't

round summit
#

It sounded to me like it would maybe store a local position since world pos is already stored in translation
nut i dont know

#

maybe translation component contains the local pos
i don't know anything

opaque ledge
#

it depends, LocalToWorld gives you forward, right and up directions relative to entity, the code above raycasts to 'down' relative to world and not relative to entity

round summit
#

I am assuming Unity.Physics use random solvers since collision trajectories are not aligned to the plane even though i initially aligned the objects in that plane
Do you think these random seeds are acquired from system time? or positions of objects?
If it's not something like positions of the objects, i'll need to sync this time to improve determinism
@round summit
anyone know about this?

warped trail
#

i don't understand "trajectories are not aligned to the plane" part๐Ÿค”

round summit
#

2 boxes, first one dynamic, second one kinematic
i drop first one and initially, it's z position is 0
second one also is z = 0

after collision dynamic body has velocity in z direction
@warped trail

#

And thats why assume there is a random force added to the collision forces (or something like that)

warped trail
#

sorry, still don't get it๐Ÿ˜…

round summit
warped trail
#

oh

round summit
#

cube should've only rotated in z axis i mean

#

and its position should've stayed at z = 0 plane

warped trail
#

i don't experience this behavior ๐Ÿค”

round summit
#

Outcome is much different if i move them in z plane keeping their z positions same

#

cube goes somewhere else, collision call counts are different because it's not bouncing the same way

#

@warped trail what do you mean by that?
is this not how your cubes are behaving?

warped trail
#

no

#

my cubes maintain their z position

#

are you sure your cube don't have any rotation?

round summit
#

yes

#

only keep their z position same and their rotations uniform then try? @warped trail

#

also move them in z

#

keeping the z same

warped trail
#

how do you make this gif?

round summit
#

screentogif

#

its the app

warped trail
round summit
#

what happens if you lift the cube higher

#

hmm, mine is random even with small distance

#

hmm

zenith wyvern
#

Maybe this is a dumb suggestion but I think right now physics is semi-tied to framerate, it seems like @round summit example is running a lot slower (could just be gif compression), could that be why?

warped trail
round summit
#

@zenith wyvern i press space to run the frames, i was handling frame update myself
i am trying now with clean project

warped trail
#

oh, try to disable jobdebugger and leak detection

#

in my project physics is very unstable with those thing turned on๐Ÿค”

round summit
#

I tried it on a clean project
As soon as the collision happens, i see velocity on z axis in entity debugger

#

But it looks like just your gifs

#

looks as if z = 0 with no x,y rotation

#

look at linear.z

#

in PhysicsVelocity
@warped trail

#

this is top down view
up in screen is z axis in unity

#

this is clean project

warped trail
#

i have this too

round summit
#

i am very confused

warped trail
#

but same input = same result, determinism ๐Ÿ˜… ๐Ÿ‘

round summit
#

yeah

warped trail
#

it is the same with havok

round summit
#

I can understand it may generate random forces to make it look more natural
But why is it not affecting position after it has affected the velocity?

warped trail
#

I'm too stupid to answer that question. I think source code is there and you can look at it ๐Ÿ˜…

round summit
#

Now the collision looks like yours in standalone

#

but in scene its the same as my first gif

#

with my weird time step code

#

This file popped up after i built the first standalone, EnableBurstCompilation was true initially
but in the clean projects standalone, burst compilation is on and it still looks right

formal scaffold
#

Any info on the uint CollidesWith from Unity.Physics? I know that ~0u means all 1's, so all Layers. But I want to exclude the player. How do I do that?

round summit
#

oh, try to disable jobdebugger and leak detection
in my project physics is very unstable with those thing turned on๐Ÿค”
@warped trail
Where are these settings may i ask?

formal scaffold
#

This is Layer 0: 0000u
This is Layer 1: 0010u
This is Layer 2: 0100u
This is Layer 3, 2, and 1: 1110u

Kinda cool had to learn this in School and never thought I'd need it ๐Ÿ˜…

lusty otter
#

Anything to watch out for when migrating from JobComponentSystem to SystemBase?

coarse turtle
#

Hmm I'd say inputDeps is now Dependency - which is just a property in SystemBase

zenith wyvern
#

If you're already familiar with JCS, the "HelloCube" samples have all been updated with SystemBase, should tell you everything you need to know

lusty otter
#

Okay thanks both.

remote coyote
#

hm, anyone else having issues in Unity.Entities.PerformanceTests after updating to their 0.6 version?

#

In particular I get that this does no longer exist:
SampleGroupDefinition

zenith wyvern
#

I used it for a couple of simple tests in 0.6, I never had to use that keyword I guess

#
    [Test,Performance]
    public void EndSimBufferRemove()
    {
        Entity e = m_Manager.CreateEntity();
        var endSim = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();

        Measure.Method(() =>
        {
            var b = endSim.CreateCommandBuffer();
            b.RemoveComponent<IntComponent>(e);
            endSim.Update();
        })
        .WarmupCount(20)
        .MeasurementCount(9)
        .IterationsPerMeasurement(10000)
        .SetUp(() =>
        {
            m_Manager.AddComponent<IntComponent>(e);
        })
        .Run();
    }
remote coyote
#

thanks, that hints the issue is somewhere else

#

I'll keep digigng

dull copper
#

I'm only getting warnings of the two test dlls not existing ever since moving to 0.6 ๐Ÿ˜„

#

I dunno if it's Unity Physics package issue or something else, but there's been very little reason for me to test without the physics package so can't tell for sure

dull copper
#

if people remember my issues with profiler getting unusable with high core count cpu... turned out there's a command-line parameter for limiting the worker threads as well which also caps the total worker amount in the editor

#

if you only limit the workercount from c# script, it could still place those 3 workers to random worker threads in the editor, so could have gotten worker 10, worker 20 and worker 23 and then had to scroll down to actually see them - hiding the topmost data at the same time

#

what is nice is that Unity Hub lets you pass those parameters automatically if you launch the project via hub:

maiden delta
#

does hybrid renderer crash unity for everyone? i created a basic plane and cube scene with unity physics, installed hybrid renderer, played the scene and unity crashed

dull copper
#

these things can be quite crash happy

#

if it does it every time, then there's something wrong

#

I'd also make sure you are using these on supported engine versions

maiden delta
#

unity 2019.3 is supported, isn't it

dull copper
#

if it's released version and not beta or RC, then yes

maiden delta
#

oh ok yeah i used 2019.3.2f1

warped trail
#

but next hybrid renderer will not support 19.3 ๐Ÿ˜•

dull copper
#

that's true as well

#

or well, I dunno if they've said it's not going to be supported but definitely will at least have functionality that only works on 2020

maiden delta
#

why do platform packages not have hybrid renderer as their dependency

dull copper
#

you don't need hybrid renderer for all things

#

like, I use platform package to get the build tools but I don't necessarily want hybrid rendering if I build for hybrid conf

#

in other words, you can still use new build tools along with old renderer

maiden delta
#

ok imma restrain from dots for now cuz i dont understand it at all lol

dull copper
#

lets hope all the juicy DOTS news will not be canceled because of the GDC thing

opaque ledge
#

yeah hope so as well

dull copper
#

I'm fairly confident we'll still get some updates on it, but it's quite likely that they compact the thing now

#

We will no longer have a physical presence with a booth, but will instead showcase the great GDC content weโ€™ve been working towards online. Expect more details in the coming weeks.

remote coyote
warped trail
#

oh, there will be talk from Mike Acton๐Ÿ˜

dull copper
#

Programmers that haven't yet built an ECS, or fix their existing solution, or throw away what they have and fix things this time.```
#

throw away what they have and fix things this time.

#

typical Acton

remote coyote
#

haha

remote coyote
#

Unity.Entities.PerformanceTests\Diff\EntityDifferPerformanceTests.cs(31,21): error CS1061: 'MethodMeasurement' does not contain a definition for 'Definition'

#

com.unity.entities@0.6.0-preview.24\

#

This is mildly frustrating

opaque ledge
#

i think you need to downgrade performance testing package to 1.3.x

#

if you are using 2.x

remote coyote
#

ah, that might be it then, thank you, I'll try that

#

ajajaj, that was it. Thank you!

opaque ledge
#

also ๐Ÿ˜„

dull copper
#

I do wonder if they have anything else but new Hybrid Renderer to show

#

because of the Unite's there's usually not that big major things announced on GDC, last year it was mostly presenting what they showed on previous Unite already, like MegaCity

dull copper
#

weird that they upgraded to HDRP 7.1.8 instead of 7.2.1

mint iron
#

i wonder if GDC will be cancelled, MS, Unity, EPIC, Sony, lots have pulled out.

dull copper
#

EA and Facebook/Oculus as well

#

if they still keep the event, it probably boils down on not having to refund the prepaid tickets :p

round summit
#
[UpdateAfter(typeof(BuildPhysicsWorld))]
[UpdateBefore(typeof(StepPhysicsWorld))]
[UpdateBefore(typeof(ExportPhysicsWorld))]
[AlwaysSynchronizeSystem]
public class AddForcesSystem : JobComponentSystem
{
    private BuildPhysicsWorld buildPhysicsWorld;
    private StepPhysicsWorld stepPhysicsWorld;

    protected override void OnCreate()
    {
        buildPhysicsWorld = World.GetOrCreateSystem<BuildPhysicsWorld>();
        stepPhysicsWorld = World.GetOrCreateSystem<StepPhysicsWorld>();
    }

    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        EntityCommandBuffer commandBuffer = new EntityCommandBuffer(Allocator.TempJob);

        Entities.WithoutBurst().ForEach((Entity entity, ref PhysicsVelocity physicsVelocity, ref AddedForces addedForces) =>
        {

            PhysicsWorld physicsWorld = buildPhysicsWorld.PhysicsWorld;
            int rigidbodyIndex = physicsWorld.GetRigidBodyIndex(entity);
            Debug.Log("adding force: " + addedForces.addedForce + ", " + addedForces.addedTorque);
            PhysicsWorldExtensions.ApplyLinearImpulse(physicsWorld, rigidbodyIndex, addedForces.addedForce);
            PhysicsWorldExtensions.ApplyAngularImpulse(physicsWorld, rigidbodyIndex, addedForces.addedTorque);
            addedForces.addedForce = Vector3.zero;
            addedForces.addedTorque = Vector3.zero;

            commandBuffer.RemoveComponent<AddedForces>(entity); // this line *

        }).Run();

        commandBuffer.Playback(EntityManager);
        commandBuffer.Dispose();
        return default;
    }
}

I remove " this line * " and it works correctly
If i keep it, all the entities are applied force somehow, the one's i never add the AddedForcesComponent
Why is this?

#

If i remove "ref PhysicsVelocity physicsVelocity" parameter (also "this line * "), i don't see effects of the force on any object
(I only add the AddedForces component to rigidbodies)

#

.
This is what i do in monobehaviour:

public void AddForce(Vector3 force)
    {
        AddedForces addF = new AddedForces();
        if (entityManager.HasComponent<AddedForces>(entity))
        {
            addF = entityManager.GetComponentData<AddedForces>(entity);
        }
        else
        {
            entityManager.AddComponentData(entity, addF);
        }
        addF.addedForce += force;
        entityManager.SetComponentData(entity, addF);
    }
#

I wanted to create something like a tag datacomponent
I would add the tag in mono, force would get applied in system and tag would be destroyed

#

.
The line just after the dubug.log gets a previously scheduled job Jobs:CreateMotions writes to the NativeArray... error

warped trail
#

try moving this before your lambdacs PhysicsWorld physicsWorld = buildPhysicsWorld.PhysicsWorld;

round summit
#

That doesn't change the result

warped trail
#

do you really need to apply those forces via physicsworld?๐Ÿค”

#

why don't you just apply those forces to PhysicsVelocity before BuildPhysicsWorld?

round summit
#

i guess i'll try a little longer and then do that

#

Yeah i did it the way you said it @warped trail

#

I won't touch PhysicsWorldExtensions ever again

pliant pike
#

I dont suppose anyone knows how I change the colour of an entity?

#

this does not seem to be working csharp ecb.AddComponent(entity, new MaterialColor { Value = new float4(x / gridresolve,y / gridresolve,z / gridresolve,1) });

round summit
#

@pliant pike do setcomponentdata* instead?

pliant pike
#

no it just says the component has not been added

bright sentinel
#

Hm, from the docs it kind of seems like you have to change the material from the RenderMesh SharedComponent

#

That would of course change the color for all entities with that archetype

round summit
#

RenderMesh.Material.Color
@pliant pike

pliant pike
#

yeah that's true I want an individual color for each

round summit
#

do getcomponentdata to get Rendermesh

bright sentinel
#

But that would change everything for that archetype no?

pliant pike
#

so how do I change to non sharedcomponent ๐Ÿค”

round summit
#

i have no idea, it's not adding anything extra though i believe so why would it change archetype

bright sentinel
#

I agree that MaterialColor should do the trick

#

A sort of hacky way to do it is to just not have them use the same shared RenderMesh, but then you have to set that up manually..

pliant pike
#

materialcolor isnt working for the whole of them so I don't know what I'm doing wrong

round summit
#

entityManager.GetComponentData<RenderMesh>(entity)
@pliant pike you do this right?

#

but watch out for structs though

#

watch out for pass-by-value stuff i mean

pliant pike
#

nope I'm just instantiating a prefab so I cant getcomponentdata

round summit
#

in IConvertGameObjectToEntity class

if your Convert method
dstManager.SetComponentData

@pliant pike

warped trail
pliant pike
#

I'm just using the hybridrenderer

warped trail
#

urp?

bright sentinel
#

I think just the built-in renderer ๐Ÿ˜›

warped trail
#

oh, then you can only change sharedcomponentdata๐Ÿคทโ€โ™‚๏ธ

pliant pike
#

yeah just the standard Rendermesh thingy I don't know ๐Ÿ˜•

formal scaffold
#

Can I check if 2 colliders hit eachother even if none of them is a trigger?

pliant pike
#

it doesn't really matter anyway I only needed the colour change for debug purposes and to see things better

round summit
#

@formal scaffold I have code for that

formal scaffold
#

I watched Codemonkey's tutorial and it looks simple enough

warped trail
#

you can make component like ChangeColor and than make some system which will change RenderMesh on main thread

bright sentinel
#

The thing is also, when you access the material in GameObject world, Unity actually instantiates a new Material at runtime, which is a copy of the sharedMaterial

#

So you could implement a similar behavior

warped trail
#

if you change material on RenderMesh you will move this entity to different chunk

pliant pike
#

well I checked the forum and the above code seemed the most basic way to do it so I dont know ๐Ÿคทโ€โ™‚๏ธ

warped trail
#

and i believe you can do this only on main thread๐Ÿค”

pliant pike
#

maybe why I was getting errors

warped trail
#
var renderMesh = EntityManager.GetSharedComponentData<RenderMesh>(entity);
renderMesh .material = material;
EntityManager.SetSharedComponent<RenderMesh>(entity, renderMesh);``` this is basically the way you do it๐Ÿค”
pliant pike
#

yeah thanks I think I've seen that way

#

I was hoping to do it inside a job

warped trail
#

as i said before, you can create tag component for that๐Ÿ˜…

#

IWantChangeColorOfThisEntityInTheBeginingOfNextFrameComponentTag ๐Ÿ˜

pliant pike
#

I guess I could do that leahYTHO

#

thanks dude

odd ridge
#

as in ChangeColorTag? ^^

warped trail
#

and you can create some tags for prefab entities, like ThisEntityWithRedMaterial, then query for this entity and get material from it and apply it to your desired entity

#

hacky af, but it simple and it works๐Ÿ˜…

bright sentinel
pliant pike
#

yeah, we need much simpler straightforward ways of doing things

bright sentinel
#

@pliant pike For now, I'd recommend doing something similar to what I described earlier, by making a system that will instantiate a new material if you want to change the color.

#

And thus also changing the MeshRenderer shared component

zenith wyvern
#

According to Jaochim we should have some hybrid renderer news within a couple weeks

bright sentinel
#

Yeah, as you can see from the PR I posted, V2 seems to be around the corner

#

But also seems to be for SRP only, so you need either URP or HDRP

#

Or custom of course

amber flicker
#

re hybrid renderer, I guess around gdc time - Sebastian on the forums also recently said "I will give you release time estimate in the following weeks." also "Current profiling results are highly positive." ๐Ÿคž

safe lintel
#

i was greedily hoping they would just release their gdc stuff early if theyre skipping it ๐Ÿ™‚

opaque ledge
#

What do you guys think of what they are going to improve anyway ? core entities seems solid now, maybe some physics improvements ? But does anyone expect a "revolutionary" update to ECS or DOTS in general ?

remote coyote
#

For anyone else looking to run integration tests that involve Netcode ghosts, we need to invoke the conversion process for Ghosts by applying GameObjectConversionUtility.ConvertGameObjectHierarchy to all root objects in the scene holding the GhostCollectionAuthoringComponent.

safe lintel
#

i guess im not expecting anything revolutionary, but support for lightmaps would make quite a big difference for my own uses

mint iron
#

I think they're solidifying the ecs core well enough but just need to do some general widening of the support for dots integration. How is UI supposed to work and how will dots integrate with runtime UIElements? The new Audio package last i tried was shall we say, very very experimental. Physics is shaky. Sub-scenes are not that great right now imo. URP/HybridRenderer has been buggy to the point everyone is writing their own rendering systems. The input system has no integration with dots. They want the editor to be able to used to create games, so all of the other areas need to be addressed for that to happen or we end up just back coding in notepad like we are now.

opaque ledge
#

๐Ÿ‘

#

so it probably will be more about getting existing systems integrated to DOTS rather than introducing new stuff to ECS in general

mint iron
#

yeah, and maybe going more towards the graph based stuff / blueprints with the dots visual scripting UI. Im curious to see how that side pans out.

safe lintel
#

whats the alternative for a visual scripting ui?

opaque ledge
#

there are many for Monobehaviour, none for ECS i think

#

i mean, i doubt anyone would bother to work on it tbh

#

given its preview

coarse turtle
#

wasnt unity working on the visual scripting dots package?

#

like it was a very early preview?

opaque ledge
#

yeah they are, latest is "6th drop", they stated that 7th drop will come next month, probably near GDC time

coarse turtle
#

ah - I never took a look at it yet haha

opaque ledge
#

yeah it gave me errors so i didnt want to deal with it ๐Ÿ˜„

#

Also, this ECS made me learn LOTs about Structs, i am scared

bright sentinel
#

Well how much is there to learn about structs? ๐Ÿค” It's basically just a value-type container of more value-types

amber flicker
zenith wyvern
#

100k additions, wow

amber flicker
#

indeed.. ๐Ÿคจ

zenith wyvern
#

Something that large feels more likely to be engine related than ECS related, but who knows

bright sentinel
#

I'm strongly assuming it's just the V2 hybrid renderer

#

Considering that it has SRP support

amber flicker
#

and considering Sebastian's the person that I quoted earlier talking about specifying hybrid renderer v2 release date soon..

bright sentinel
#

Exactly

remote coyote
#

Exciting!

round summit
#

maybe they wrote some documentation

#

i hope they wrote some code examples in documentation

formal scaffold
#

Hey,I want to make 2 Entities collide with each other and raise a CollisionEvent. When testing I found that I need a Physics Body attached to one Entity to make it work. But I don't want to do it with a Physics Body. Checked "Raises Collisions" in both Physics Shapes.

bright sentinel
#

@formal scaffold The PhysicsBody is exactly what tells the physics system that an object can collide with another object

#

Otherwise it's thought of as static

opaque ledge
#

you can change it to Kinematic if you want to move it with only translation and not with physics

bright sentinel
#

But then you don't get collisions ๐Ÿ˜›

formal scaffold
#

Hmm really? Only with a body? Feels like alot of useless stuff I don't need. But yeah Kinematic works

bright sentinel
#

Well how else is the physics system supposed to know that it should iterate on that?

opaque ledge
#

ah yeah sorry, i only used trigger so far ๐Ÿ˜„

formal scaffold
#

I don't know I have two shapes that are probably defined somehow. Shouldn't a shape know if something is hitting it?

opaque ledge
#

you should have a shape too ๐Ÿค”

bright sentinel
#

No, a shape will only tell the physics system about the, well, shape of the collider

formal scaffold
#

No kinematic raises collisions aswell @opaque ledge

#

at least for me it did ๐Ÿค” lemme check real quick

bright sentinel
#

But the body will tell the physics system how it should collide with other colliders

opaque ledge
#

ah good then, well it makes sense, kinematic means this particular entity wont be affected by physics

bright sentinel
#

Weird, last I tried with kinematic it didn't raise collisions

#

Looking at the Physics sample character controller, they kind of write their own collision stuff

formal scaffold
#

Well that means every NPC and every creature would need a body. Or otherwise every Object and Ground would need a body .... thats just for collision

bright sentinel
#

Oh yeah, definitely

formal scaffold
bright sentinel
#

If you want them to collide with the environment (aka static colliders), you need some dynamic collider (aka physics body)

formal scaffold
#

This guy seems to not use a body

bright sentinel
#

It's the same with the old physics

#

You needed a rigidbody and collider for moving objects

#

Or well, you didn't need it, but it was really bad for performance to move colliders without a rigidbody, or moving the transform at least

formal scaffold
#

Why is that? Don't you just add some floats?

bright sentinel
#

With what?

#

The physicsbody?

formal scaffold
#

No I mean why is moving the transform bad for performance? Don't you juts add some floats for the direction and you are done? Thats what I do

bright sentinel
#

That's very bad, because then the physics have to rebuild the static collider, and it does a lot of optimizations when only dealing with static colliders

#

But moving it means having to rebuild it, which is very expensive

#

Compared to moving a dynamic rigidbody. Because then the physics system knows to not build it as a static collider, and skip that expensive step

odd ridge
#

why aren't my ECS converted entities being batched? in regular, I see in my stats "1000 draw calls, 1000 saved by batching". in ECS "2000 draw calls, 0 saved by batching"

bright sentinel
#

But then of course actually detecting collision will be a bit more expensive. But it's a lot less than building the actual static collider

#

@odd ridge I don't really know the specifics, but I'm guessing that it's just because the Hybrid Renderer is not very optimized. It's just something that works with the bare necessities

odd ridge
#

oh cool cool

formal scaffold
#

@bright sentinel what about skipping any Physics Shapes and just using Raycasts ๐Ÿค” currently I use one cast down to check for the ground and I wanted to make a sphereCast to check for grounding which let's me use the ray down to set my Y position.

A full raycast system can also handle slopes very well that's why I'm using it atm.

bright sentinel
#

@formal scaffold You still need physics shapes for that though, or the raycasts wont be able to hit anything ๐Ÿ˜› But THEN you don't need any physics body

formal scaffold
#

Hmm, what if all physics shapes are static objects and only the Player and the NPC's cast rays ๐Ÿ˜… At least NPC's and the Player wil all have the same height for now so setting up rays for one means having it for all, so one system should be enough

bright sentinel
#

Yes, that's definitely a possibility. I remember I once saw a third-person game where you controlled an ant that could crawl on trees and stuff. This of course required very specific control over each leg and how it interacts with the environment. It was all done with a LOT of raycasts

#

Like 50+ just for that single character

#

So definitely a possibility, but not sure why you're so against using a PhysicsBody..

formal scaffold
#

I would use a SphereCast for collision and about 4 Rays
1 Ray for slopes
1 Ray for higher slopes like stairs
1 Ray for jumping
1 Ray for the ground

Hmm I tried it and couldn't get my character to stop sliding across the screen. I guess slopes and collision detection is trivial then ๐Ÿค”

bright sentinel
#

I mean, it can definitely be done with physics body, and is a better solution in the long run

warped trail
#

there is distance query ๐Ÿค”

bright sentinel
#

I'd recommend that you check the physics sample with their character controller, they have done it there with slopes

formal scaffold
#

This one ? EntityComponentSystemSamples/UnityPhysicsSamples/

bright sentinel
zenith wyvern
#

Not sure if it's the same one but theres also a physics based character controller in the Dots Network sample

formal scaffold
#

Currently Physics is running on Update right? Unless I use a CusomBootstrap to change that, why is it like this anyways? I remember reading a post about it a while ago but back then It didn't make much sense to me since I was just starting out

bright sentinel
#

@formal scaffold Yeah, it is dependant on the framerate for some reason. I'm pretty sure they're working on it though

warped trail
#
// internal for now, until we figure out proper API``` from ComponentSystemGroup.cs๐Ÿ˜…
safe lintel
#

fixed rate support is like my least expected change for upcoming gdc related announcements/changes ๐Ÿ˜„

bright sentinel
#

I mean, it seems like it's pretty essential for any physics system for games, no?

warped trail
#

just making SimulationSystemGroup update in fixed steps not enough. You will encounter a lot of problems that way. Like movement will not be smooth, Transform system also updates in simulationsystemgroup๐Ÿ˜•

bright sentinel
#

In this day and age with devices that can be anywhere from 10-300 FPS

safe lintel
#

lots of workarounds floating on the forums, its been like that forever

bright sentinel
#

Yeah, it's just weird

warped trail
#

they moved simulationsystemgroup to update almost a year ago๐Ÿ˜•

stiff skiff
#

Has anyone played around with the IL post processor yet?

#

I've been adding ProfileMarkers around the core bits of my code to get some better performance data. I was wondering if it would be interesting to have the IL processor generate the code for this in the cases where I want to profile an entire function.

formal scaffold
#

@bright sentinel The character controller in the Demo is quite nice apart from the camera movement. But the code is a mess sadly. I found where they handle moving around and it makes sense. How would I go about freezing rotaiton along the X and Z Axis then? This is not very inviting as a starting point ๐Ÿ˜…

bright sentinel
#

@formal scaffold If you look at some of the other demos in there, they have some axis locking with joints, you can look at those

#

And I agree, the code is a big mess.

#

As for the camera, that's not good, but that's not really the point of this sample ๐Ÿ˜›

formal scaffold
#

Yeah ๐Ÿ˜„ well and running down slopes makes the character fly sometimes, which makes sense but disables movement for a slight second which is more annoying than realistic in a game I feel.

bright sentinel
#

@formal scaffold Yes but again, the point isn't to make an amazing character controller. The point is mostly just to show how you can achieve the basics, and how you can interact with the API. Then you can expand on it yourself

formal scaffold
#

You are right thanks alot for your help ๐Ÿ‘ It's worth looking into

radiant sentinel
#

Hello, i am writing server. i want index shooted Bullets for each of players in jobs. Whos can help me?

#

GetHashCode has an accessable error at burst compile.

#

ok thanks guys i found a solution

twin raven
#

Is there a tool that makes entity prefabs easily accessible from code to instantiate. So I could just reference those by name when I want to instantiate new entity prefab

#

Drag and dropping to a window and it would generate the script or something

bright sentinel
#

@twin raven There's the resources folder, but you'd still have to convert those to entities at the start of the game like you would any other prefab

#

But I don't think there's a premade tool for that

safe lintel
#

could try looking into addressables

formal scaffold
#

Does anyone have a better Code example of how to lock the rotation of a Physics Body than the one supplied in the UnityPhysicsSamples? Any simplified example would suffice, I just don't understand what they do there.

twin raven
#
Entity spawnedBullet = commandBuffer.Instantiate(entityInQueryIndex, bullet);
commandBuffer.SetComponent(entityInQueryIndex, spawnedBullet, _pos);
commandBuffer.SetComponent(entityInQueryIndex, spawnedBullet, new DirectionData { Value = direction });

Is this Unity bug? I am spawning bullets from Entities.ForEach with EndSimulationEntityCommandBufferSystem and for one frame the position is the default position. It feels like the commandbuffer sets position 1 frame after initializing.

bright sentinel
#

@twin raven Can you show the whole code?

twin raven
#
        var positions = GetComponentDataFromEntity<Translation2D>();
        var commandBuffer = commandBufferSystem.CreateCommandBuffer().ToConcurrent();
        var bullet = bulletEntity;
        return Entities.ForEach((int entityInQueryIndex, ref GunComponent gunComponent, in DynamicBuffer<ActiveTarget> _target, in Translation2D _pos) =>
        {
                if (_target.Length > 0)
                {
                    var targetPos = positions[_target[0].Target];
                    var direction = targetPos.Value - _pos.Value;

                    Entity spawnedBullet = commandBuffer.Instantiate(entityInQueryIndex, bullet);
                    commandBuffer.SetComponent(entityInQueryIndex, spawnedBullet, _pos);
                    commandBuffer.SetComponent(entityInQueryIndex, spawnedBullet, new DirectionData { Value = direction });
                    gunComponent = new GunComponent { Load = 0.2f };
                }
            }
        }).WithReadOnly(positions).Schedule(inputDeps);
bright sentinel
#

I don't think it's a Unity bug. The thing is that you're setting the Translation2D data in the EndSimulationGroup, but Unity's TRS systems will run before that, so the rendering systems won't know about the new position

twin raven
#

What is TRS?

bright sentinel
#

Translation, Rotation, Scale

zenith wyvern
#

It looks like you're using a custom position component so whatever system updates your entity positions needs to run after EndSim but before rendering.

bright sentinel
#

Basically how ECS handles those things to feed to the rendering system

twin raven
#

sark, yeah you are right, totally overlooked that

bright sentinel
#

Isn't Translation2D just part of the Entities 2D package?

twin raven
#

No its my custom

bright sentinel
#

Ah then there's your real problem

twin raven
#

๐Ÿคฆ๐Ÿผโ€โ™‚๏ธ yeah ๐Ÿ˜„

zenith wyvern
#

Alternatively you can run the buffer on BeginSim and update positions before you spawn

bright sentinel
#

Yeah, that will be 1 frame later of course. If you really cannot live with that, you probably need to create your own ECB that runs right before the TRS system

twin raven
#

alright thanks for the help ๐Ÿ™‚ I was totally blind to that as I have been using my own translation for quite some time now. I realize I might have had other problems because of this before. I can solve it now

odd ridge
#

I have a bunch of sphere entities and I want to destroy all of them at once, how would you do that?

odd ridge
#

thanks

#

I have a bunch of balls which I'm currently spawning with the hybrid conversion, but I would like to replace it all with pure dots to see how much performance I can get

#

one problem is I made a box prefab to contain those balls, but I don't know how I would spawn that box in pure without the visual editor part to make it

#

any hint?

opaque ledge
#

@odd ridge i never tried that except for very simple entities, but you could create an entity and just add/set your components one by one, and i dont think creating an archetype would be necessary because archetype doesnt contain any values, just types of components.

#

Is there a specific reason why you dont want to use conversion ?

round summit
#
UnityException: ToString can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.

Hmmm, I wanted to print some collision information

#

I can print stuff, but it doesn't let me use .ToString i guess?

#
public void OnEntityCollision(SimpleECSCollision simpleECSCollision)
{
    Debug.Log("other : " + simpleECSCollision.other);
}

Just trying to make my own easy collision system

#

Where this is called:

||```cs
struct CollisionJob : ICollisionEventsJob
{

    public ComponentDataFromEntity<MonoReference> rbEntities;
    public PhysicsWorld physicsWorld;

    public void Execute(CollisionEvent collisionEvent)
    {
        Entity entityA = collisionEvent.Entities.EntityA;
        Entity entityB = collisionEvent.Entities.EntityB;
        if (rbEntities.HasComponent(entityA) && rbEntities.HasComponent(entityB))
        {
            int monoIdA = rbEntities[entityA].monoId;
            SimpleECSRigidbody rigidbodyMonoA = SimpleECSRigidbody.idTable.GetObj(monoIdA);

            int monoIdB = rbEntities[entityB].monoId;
            SimpleECSRigidbody rigidbodyMonoB = SimpleECSRigidbody.idTable.GetObj(monoIdB);

            CollisionEvent.Details details = collisionEvent.CalculateDetails(ref physicsWorld);
            SimpleECSCollision collisionA = new SimpleECSCollision();
            SimpleECSCollision collisionB = new SimpleECSCollision();
            collisionA.other = rigidbodyMonoB;
            collisionB.other = rigidbodyMonoA;

            collisionA.normal = collisionEvent.Normal;
            collisionB.normal = collisionEvent.Normal;

            collisionA.impulse = details.EstimatedImpulse;
            collisionB.impulse = details.EstimatedImpulse;

            collisionA.point = details.AverageContactPointPosition;
            collisionB.point = details.AverageContactPointPosition;

            rigidbodyMonoA.OnEntityCollision(collisionA);
            rigidbodyMonoB.OnEntityCollision(collisionB);
        }
        
        Debug.Log("collision");
    }
}
#

.
.
System OnUpdate

    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var jh = new CollisionJob()
        {
            physicsWorld = m_BuildPhysicsWorldSystem.PhysicsWorld,
            rbEntities = GetComponentDataFromEntity<MonoReference>()
        }.Schedule(m_StepPhysicsWorldSystem.Simulation,
            ref m_BuildPhysicsWorldSystem.PhysicsWorld, inputDeps);

        jh.Complete();
        return inputDeps;
    }
north bay
#

If you are wrapping from job/burst to normal monobehavior i would tag them instead of calling their functions directly, so you can make sure that all your collision code is bursted etc

#

And call their stuff functions from the main thread later

round summit
#

ah, i see makes sense

#

i need to collect collisions in one system

#

and i need to call callbacks in another

#

which runs on main thread

#

and runs after collision callback tagging system

north bay
#

That's how i would approach it

round summit
#

I guess there's no way to make a collision events detecting system in main thread

#

So there's no other way other than tagging

#

@north bay What if multiple collisions occured in same frame though?

#

I don't think ecs will let me add multiple ComponentData tags on the entity?

warped trail
#

dynamic buffers?

round summit
#

yes, i think i can work with dynamic buffers

north bay
#

I guess there's no way to make a collision events detecting system in main thread
@round summit Why is there no way to do that? Shouldn't the real question be why would you want to do that?

round summit
#

i assume i still cannot have any class references though right?

north bay
#

You don't work with any class references

#

Only the system that calls the callbacks has references

round summit
#

@north bay because physics collision callbacks are generated in parallel i think

warped trail
#

no they are single threaded

north bay
#

Oof didn't know that

#

Makes sense i guess

warped trail
#

you can use simple command buffer. not concurent one

#

my naรฏve approach would be store mb refs in some array and store index of that array in some component on corresponding entity, then in collision job i would spawn simple entity typeof(ComponentWithIndexToArray), then in some system i would just iterate over this simple entities and call something like arrayOfRefs[ComponentWithIndexToArray.inex].OnCollisionEnter()

round summit
#

hmmm, command buffers, right

#

yeah i get it

#

i'll generate and collect all info in command buffer in the collision trigger jobs

#

when that system is done, i use the command buffer on another system to iterate and call the callbacks in my monobehaviours

north bay
#

You don't use the command buffer directly on the other system but the entities + stuff you modify with it

warped trail
#

im creating this eventEntities and dealing with them in the next frame๐Ÿ˜…

round summit
#

I think i'll just store the generated

public struct SimpleECSCollision
{
    public Vector3 point;
    public Vector3 normal;
    public int selfId;
    public int otherId;
    public float impulse;
}

In some list and access that list in next system

#

Can i not simply do that?

#

or i need to create an entity for each SimpleECSCollision?

north bay
#

Make that struct an IBufferElementData

#

Than you can create DynamicBuffers with this at it's type

round summit
#

Can i not simply share data between systems without creating extra ComponentData or Entities?

north bay
#

If you are using DynamicBuffers to store the collisions you are not going to create any extra entities or component datas, all you are doing is attaching a buffer to every entity that listens for collision events

vagrant surge
#

@round summit its highly common to have some sort of "singletons" that are IN the ecs, but instead of being individual entities, its more like a chunk of data, like a entire octree

#

sadly unity ECS still doesnt have native support for singletons of this sort....

#

so yeah, you would have a native-array of those collision events stored in some singleton

round summit
#

I think NativeList is the only option to store data that can be accessed by other systems
and store it in system

#

I'm trying dynamic buffers now, i'll see how it goes

vagrant surge
#

yes, has to be those native structures, no normal C# stuff

#

dynamic buffers arent really made for that, but they would work

#

i find weird that unity hasnt added a proper way to do this sort of singleton entities

round summit
#

singleton systems you mean?

vagrant surge
#

no, singleton data

#

for example a collision octree

round summit
#

ah i see yeah

vagrant surge
#

or an event bus of some sort

#

some systems write to this singleton, others read from it

round summit
#

if i had something like that i'd store the callision callback infos in there

vagrant surge
#

some guys in the forum implemented it themselves

#

so basically just some abstraction but it just stores an actual entity with the data

round summit
#

Is this supposed to be something like this:

public struct CollisionCallbacks : IBufferElementData
{
    public DynamicBuffer<SimpleECSPreCollision> Value;
}

public struct SimpleECSPreCollision
{
    public Vector3 point;
    public Vector3 normal;
    public int selfId;
    public int otherId;
    public float impulse;
}

I access this and add my elements in .Value

or like this:

public struct CollisionCallback : IBufferElementData
{
    public Vector3 point;
    public Vector3 normal;
    public int selfId;
    public int otherId;
    public float impulse;
}

And i do commandBuffer.AddBuffer<CollisionCallbacks>(entityA, collisionCallback)
and these will stack?

vagrant surge
#

the first, i think

round summit
#
public BufferFromEntity<CollisionCallbacks> collisionCallbackEntities;

But i can't get anything this way
collisionCallbackEntities.GetBuffer.Get

@vagrant surge

#

I can only check if buffer exists on an entity or not

warped trail
#

you are doing it wrong ๐Ÿ˜…

round summit
#

I cant access .Value and add my new structs

warped trail
#
public struct SimpleECSPreCollision : IBufferElementData
{
    public Vector3 point;
    public Vector3 normal;
    public int selfId;
    public int otherId;
    public float impulse;
}```
round summit
#

@warped trail If i do

commandBuffer.AddBuffer<SimpleECSPreCollision >(entityA, collisionInfo);

Will these components stack then?

#

So it's pretty much the second thing i said above?

warped trail
#

yes they will stack

round summit
#

oh, thats nice

warped trail
#

but i guess you have to clean them every update๐Ÿค”

round summit
#

ill have a system that iterates over these components and delete them

#

that system will run after the system i'm moking now is done

#

all these systems will be in SimulationSystemGroup so it will be fine i believe

torpid lintel
#

Unity Physics: how do I constrain a rigidbody movement on the XZ plane?

bright sentinel
#

@torpid lintel If you look in the physics samples, there is an example of them using joints to do that, I recommend you look at how they do it

round summit
#

@torpid lintel Or add a ComponentData for it
Iterate over that and set y positions and y velocities

#

In a system

torpid lintel
#

@bright sentinel oh thanks. Do you mean the samples project on GitHub or an example in the docs?

bright sentinel
#

The samples project ๐Ÿ™‚

torpid lintel
#

Gotcha! Thanks a lot โ˜บ๏ธ

round summit
#

I ended up using native lists for my issue, seemed to be the easiest way

formal scaffold
#

Magnitude on a vector3 returns the vector length right? Is there an equivalent in DOTS for a float3?

opaque ledge
#

math.length();

#

Topher knows his stuff ๐Ÿ‘€

formal scaffold
#

Thanks ๐Ÿง

storm current
#

Hey, I am trying to build a movement system where my object has a destination and it moves towards it by accelerating to the max speed and deaccelerating when it comes close to the destination. Acceleration and deacceleration are represented by a force and not a distance. I want to avoid solving this with physics (this is how most examples I found do it in โ€œnormalโ€ Unity).

My current system looks like this for a reference (I know that it is not close to the solution I want):

[BurstCompile]
private struct MoveDestinationJob : IJobForEach<Move, MoveAcceleration, MoveDestination, Translation>
{
    private const float DistanceOffset = 0.5f;
    
    public float DeltaTime;
    
    public void Execute(ref Move move, [ReadOnly] ref MoveAcceleration moveAcceleration, [ReadOnly] ref MoveDestination moveDestination, [ReadOnly] ref Translation translation)
    {
        var distance = math.distance(moveDestination.Value, translation.Value);
        var direction = math.normalize(moveDestination.Value - translation.Value);
        
        if(!(distance < DistanceOffset))
        {
            //move.Value represents the currenty velocity
            move.Value += direction * moveAcceleration.Acceleration * DeltaTime;
        }
    }
}

protected override JobHandle OnUpdate(JobHandle inputDependencies)
{
    var job = new MoveDestinationJob
    {
        DeltaTime = Time.DeltaTime
    };
    
    return job.Schedule(this, inputDependencies);
}
opaque ledge
#

And what seems to be the problem ?

#

๐Ÿ˜„

storm current
#

My issue is the math for getting the velocity ... this is not my strength ๐Ÿ™‚

warped trail
#

challenge accepted๐Ÿง

#

or not๐Ÿ˜…

opaque ledge
#

well, velocity is basically means, position changed divided by time.delta, sooo.. if you make a component like this:

public struct MoveVelocity : IComponentData{
  public Translation previousTranslation;
  public float currentVelocity;
}

And have a system that updates this:

private struct CalculateVelocityJob: IJobForEach<MoveVelocity, Translation>
{
  public float deltaTime;
  public void Execute(ref MoveVelocity velocity, [ReadOnly] ref Translation translation)
  {
    var distance = math.distance(velocity.previousTranslation.Value, translation.Value)
    velocity.currentVelocity = distane / timeDelta;
    velocity.previousTranslation = translation;
  }
}
#

I am not expert on vector math either, something like this should be fine.

warped trail
#

he wants to accelerate and deaccelerate๐Ÿค”

opaque ledge
#

he asked how to get current velocity ๐Ÿ˜„

#

so i guess reading from current velocity he can accelarate/deaccelerate with his current code

round summit
#

@storm current Sounds like you want a simple PID controller to me

#
Vector3 pos;
Vector3 velocity;

Vector3 targetPos;
void Update(){
  Vector3 delta = targetPos - pos;
  Vector3 pForce = delta * pMultiplier * deltaTime;
  Vector3 dForce = -velocity * dMultiplier * deltaTime;
  velocity += pForce + dForce;
  
  pos += velocity * deltaTime;
}

#

I used Matf because i'm not very familiar with Unity.Math

#

This will accelerate, decelerate until pos is at targetPos
@storm current

#

you configure your p and d multipliers

#

if p is too big, it will overshoot
if d is too big, it will move slow

#

you will tune those variables yourself

#

This is a simple PD controller

warped trail
#

how can i calculate them?๐Ÿค”

#

or i have to tune them by hand for every case?

round summit
#

you just set those numbers to your tastes @warped trail

#

@warped trail there are ways to auto-tune this but i never needed to learn about it

warped trail
#

i tune them once and this pd controller will do it's job for every possible distances?

round summit
#

also on top that
you should limit the max value sum of pForce and dForce can get
you might want that in %90 of the cases

#

limit the max acceleraton

#

if this were a rocket, max thrust force is limited you know

#

.
you can also use this in physics bodies
and move them just by Adding force
or += velocity

storm current
#

@round summit But can I not calculate the distance I need to accelerate/decelerate?
For example if I would use Unity NavMesh it has the same behavior with the acceleration I want without tweaking values.

round summit
#

does unity navmesh output target positions?

#

in a way that once you reach one, next one is the new target?

#

@storm current I don't think PD controller may be what you want if you can directly set position of this unit

storm current
#

You can use it as simple A to B movement and ignore all the fancy pathfinding and obstacle stuff

round summit
#

PD controller is needed in situations where you don't want to directly modify transform because you want to use physics

#

Actually you can use it

storm current
#

Basically it would look like a RTS movement, I have the destination and instead of moving toward this with a constant speed is uses acceleration -> max -> deacceleration

round summit
#

PD controller will do it anyways

#

you can use this

#

you just need to limit the velocity on top of everything

#
Vector3 pos;
Vector3 velocity;
float maxVelocity; 
float maxForce;

Vector3 targetPos;
void Update(){
  Vector3 delta = targetPos - pos;
  Vector3 pForce = delta * pMultiplier * deltaTime;
  Vector3 dForce = -velocity * dMultiplier * deltaTime;
  Vector3 finalForce = Vector3.Clamp(pForce + dForce, maxForce);

  velocity += finalForce;
  velocity = Vector3.ClampMagnitude(velocity, maxVelocity);
  pos += velocity * deltaTime;
}
storm current
#

@round summit I am looking into it, thanks

formal scaffold
#

Hey how can I scale a vector to make it's length be exactly some value? Maybe this is better asked somewehre else? I have a very short vector, like Vector.length = [0.1, 0.5] and I want to scale this vector to the length of 0.5 if it's length is shorter than 0.5

round summit
#

@formal scaffold

float len = myVector.lenght;
Vector3 normalized = myVector / len;

Vector3 result = normalized * yourNewLenght;
#

wait

#

If you normalize your vector it's leght will become 1

#

You can then decide on what the leght is supposed to be

#

And then do normalized * yourNewLenght

#

these are physics questions though

formal scaffold
#

OHHH nice I always thought normalize will just do value/maxFloat

round summit
#

normalize is vector/len

formal scaffold
#

So if I make 0.5/somethingBig = 0.00000... something smaller

round summit
#

nope

formal scaffold
#

Hmm im dump thanks ๐Ÿ‘

round summit
#

if your vector is zero initially though

#

you will still get a vector with length 1

#

That may cause issues depending on your case

formal scaffold
#

If I use normalizesave then the default of 0 should fix that right

round summit
#

thats an ecs method?

formal scaffold
#

yeah math.normalizesave(vector, default);

round summit
#

ah, neat

formal scaffold
#

Indneat ๐Ÿ˜…

round summit
#

badumtss

torpid lintel
opaque ledge
#

yeah, seems extra

round summit
#

There was a Collision Trigger example with a single unsafe
(it was modifying the velocity on collision, so balls jump)
i removed the unsafe and balls stopped jumping

opaque ledge
#

did it not give you an error when you removed unsafe ?

round summit
#

no

opaque ledge
#

huh weird, but perhaps an internal called needed that unsafe even tho you are not doing any pointer stuff, who knows

round summit
#

maybe leak detection was off, i dunno

#

hmm wait, i'll try again

opaque ledge
#

i mean normally it should give an error like "in order to be able to do pointer arithmatic you need to put unsafe context" or smth like that

round summit
#

I might be wrong about what i said

junior fjord
#

I need something like a system global constant that I set once in the beginning, how do I do that?

#

(for example stepwidth parameter, I only want to set it when the game starts up and I can then leave it constant forever)

#

just add a public variable to the system and set it from a monobehaviour?

opaque ledge
#

yeah pretty much

#

you can make it a static variable also i suppose

junior fjord
#

is that better in some sense?

opaque ledge
#

Yeah, since its static you can just do ClassName.StaticVariable

#

do you know singleton pattern in Unity ?

warped trail
#

why not create singleton entity?

junior fjord
#

@opaque ledge you mean it makes setting the variable easier?

#

because for using the variable I can just do variableName either way right?

#

for setting I would have to do entitymanager getsystem some stuff probably if I don't make it static?

#

and how does the singleton pattern in unity differ from normal singleton?

warped trail
#

as i heard a lot on forums storing data in systems is not good๐Ÿง

junior fjord
#

even if its just a constant float?

opaque ledge
#

imo yeah, static class helps on global settings, and no you dont need to hold data in your system, you can simply reach out to variable in OnUpdate

#
void OnUpdate(){
  var myFloat = MyStaticClass.myFloatStatic;
}
junior fjord
#

ah ok so you guys would just create a static class with my configuration settings and then reach out to that from the system instead of having the variable on the system itself?

opaque ledge
#

and you can use "myFloat" in your jobs

junior fjord
#

ok I can also do that, is there an obvious reason why that is better?

warped trail
#

systems are supposed to change data not store it๐Ÿ˜‘

opaque ledge
#

well i mean if you like to then go ahead, there is nothing wrong to it, but with many extra steps, if you make it a static variable you can just do it like the way i did

#

quite handy

junior fjord
#

yeah I mean I believe you guys if you say this is the best practice, I just would like to understand why

opaque ledge
#

and if you change your mind one day and want to change that float in runtime you dont need to do anything extra

#

I mean i am no expert, its just thats what i would do, thats all ๐Ÿ˜„

#

and you can do it in Druid's way as well, you can make a singleton Component, and call GetSingletonComponentData<T> to retrieve that data

#

your call^^

warped trail
#

the whole purpose of components is to store data๐Ÿ˜…

#

and you want to store it somewhere else๐Ÿ˜•

junior fjord
#

haha you don't need to take any concept to the extreme if it makes your life way harder

#

just wanted to understand the reasoning between the different ways to store this system data

opaque ledge
#

well its more of a global data than a system's data, singletons are great for that

#

many experts coder sees singletons as evil things, but i never had problem with it

#

i am not experienced enough to hate singletons just yet ๐Ÿ˜„

round summit
#

hmmmmm...
Raycasts seem to not ignore backfaces in Unity.Physics
But i want to ignore backfaces like in default physx

#

Can i simply do that?
Make it ignore backfaces?

#

I don't want my grounded raycasts hitting my characters bottom
Ignoring backfaces would be a clean way to fix that

warped trail
#

basically you want to ignore selfcollision?๐Ÿค”

round summit
#

on raycast yes

warped trail
#

there is no out of the box solution for that ๐Ÿ˜…

round summit
#

I could start the ray with a little distance but i'm just wondering if theres a better option

#

Or do two raycasts

#

cast the first one to hit the edge

#

second will start from the edge

warped trail
round summit
#

trying to find out what method is this based on

#

It seems to reference to character's collider and cast with that

#

I guess ill do with double raycast and save myself from the extra spaghet

round summit
#

Hah, i think i'm done with dots :D

public class RigidbodyTests : MonoBehaviour
{
    SimpleECSRigidbody rb;

    void Start()
    {
        rb = GetComponent<SimpleECSRigidbody>();
    }

    void Update()
    {
        // raycast example

        SimpleECSRaycastHit hit;
        Debug.DrawRay(rb.Position, Vector3.down);
        if (SimpleECSPhysics.Raycast(rb.Position + Vector3.down * 2, Vector3.down, out hit))
        {
            Debug.Log(hit.rigidbodyMono.gameObject);
        }

        // other examples

        rb.AddTorque(Vector3.right * 0.1f);
        rb.AddForce(Vector3.up * 1.1f);
        rb.Rotation = Quaternion.LookRotation(Vector3.forward + Vector3.right);
        rb.Velocity = Vector3.right;
    }
}
public class SimulationControlTests : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKey(KeyCode.Space) == true)
        {
            SimpleECSPhysics.Simulate();
        }
    }
}
junior fjord
#

how and where do I add dependencies?

#

if I want one system to run after another?

#

this jobhandle thing is somehow gone but I can access dependencies right?

#

do I do it in Oncreate and how do I add it?

warped trail
#

you want job dependencies, or you want to make one system update after another?

junior fjord
#

one system update after the other

#

both use foreach scheduleparallel

warped trail
#

Dependency = Entities.ForEach().ScheduleParallel(Dependency)

#

is the same as Entities.ForEach().ScheduleParallel()

#

basically Dependency is inputDeps, instead of returning inputDeps you just writing to Dependency property

junior fjord
#

thank you, and how would I add one system to the dependency of the other? I think I never did thaat before

warped trail
#
[UpdateAfter(typeof(YourSystem))]
public class YourOtherSystem : SystemBase{}```
junior fjord
#

oh wow thats easy haha

#

thanks

warped trail
junior fjord
#

yeah thanks ๐Ÿ˜„

#

I searched through the system order update part but did not see code boxes

#

if I want to create a texture every frame from a system, what is the way to go?

#

I have a entitiy for every pixel and know therefore that it won't write to the same location from two different jobs for sure

#

but the unity texture type still won't work probably right?

warped trail
#

this is too advanced for me๐Ÿ˜…

#

make most of the work in jobs, store it in native array, then copy from native array to texture on main thread?๐Ÿคทโ€โ™‚๏ธ

junior fjord
#

yeah the work is basically done already

#

I mean I could have a job that copies from entities to nativearray and then make a texture out of it

#

yeah I'll just go with main thread for now

#

Ok one last question for now I hope:

Can I access components from other entities in ForEach (if I use ScheduleParallel) or do I have to use one of the more complicated versions and this ComponentDataFromEntity?

warped trail
#

yes you need to use ComponentDataFromEntity, or EntityQuery has ToComponentDataArray<T>() and ToComponentDataArrayAsync<T>() methods

junior fjord
#

wasn't there something that is more complicated then foreach but less complicated than IJobChunk?

warped trail
#

ComponentDataFromEntity is not complicated ๐Ÿ˜…

junior fjord
#

@warped trail and I cannot use that in foreach right?

warped trail
#

you can use it in foreach

junior fjord
#

ah I can? ok perfect thanks ๐Ÿ™‚

#

I just remembered that earlier there where 3 type of jobs:

  • Foreach
#
  • something else
  • IJobChunk
#

and IJobChunk was the most manual one

#

now I only find Foreach and IJobChunk in the samples somehow

#

erm not 3 types of jobs but three type of systems

warped trail
#
var cdfe = GetComponentDataFromEntity<Translation>(isReadOnly = false)
Entities.Foreach((...)=>
{
  var translation = cdfe[entity];
})```
#

ToComponentDataArray gives you copy of components in NativeArray

junior fjord
#

ah can't I just set the public ComponentDataFromEntity<LocalToWorld> LocalToWorldFromEntity; as property of the system object?

#

should I better do it in each onUpdate?

#

@warped trail thank you for all the friendly help

warped trail
#

i think you supposed to use GetComponentDataFromEntity every update ๐Ÿ˜…

#
EntityQuery query;// This is property or field of system

var array = query.ToComponentDataArray<T>(Allocator.TempJob, out var jobHandle);
Dependency = JobHandle.CombineDependency(Dependency,jobHandle);
Entities
.WithStoreEntityQueryInField(ref query)
.Foreach((...)=>
{
  array[someIndex]
})``` or something like this
scarlet inlet
#

Basically the question is: do SystemBase systems that do not use components at all, but only jobs running on other data structures, make any sense at all?

#

and if they don't how will I handle the dependency in such a way I can mix them with proper systembase systems?

opaque ledge
#

Yeah it does makes sense, not every job has to be about entities/components, you can use Job.WithCode() for that

#

@junior fjord afaik, 3 job types are: ForEach, IJobChunk, IJobForEntity<>

scarlet inlet
#

thanks but I don't think that answer my question

warped trail
#
OnUpdate(JobHandle inputDeps)
{
  //your work here
  return inputDeps;
}```
```cs
OnUpdate()
{
  JobHandle inputDeps = Dependency;
  //your work here
  Dependency = inputDeps;
}```
#

nothing changed

scarlet inlet
#

but how does the next job in the queue know about the dependencies of the previous job?

opaque ledge
#

JobScheduler handles that

warped trail
#

you are giving your job dependencies

scarlet inlet
#

and is this true for job that do not work on components too? IF so this code should be correct:

#
var handle1 = CreateJobForDoofusesAndFood(Dependency, GroupCompound<GameGroups.FOOD, GameGroups.RED>.Groups,
                GroupCompound<GameGroups.DOOFUSES, GameGroups.RED, GameGroups.NOTEATING>.Groups);
            var handle2 = CreateJobForDoofusesAndFood(Dependency, GroupCompound<GameGroups.FOOD, GameGroups.BLUE>.Groups,
                GroupCompound<GameGroups.DOOFUSES, GameGroups.BLUE, GameGroups.NOTEATING>.Groups);
            
            this.Dependency = JobHandle.CombineDependencies(Dependency, handle1, handle2);
#

note that the jobs are scheduled with Dependency

#

like:

  var deps =
                        new LookingForFoodDoofusesJob(doofusesBuffer, foodBuffer).Schedule((int) doofusesBuffer.count,
                            (int) (doofusesBuffer.count / 8), Dependency);
opaque ledge
#

Yep basically

scarlet inlet
#

so Dependency can be used as input as well

warped trail
#

yes

scarlet inlet
#

cool stuff

#

thank you

opaque ledge
#

Dependency is just a JobHandle, so yeah

scarlet inlet
#

I thought that the JobScheduler would combine dependencies ONLY for components data

warped trail
#

Dependency is your inputDeps from JobComponentSystem

scarlet inlet
#

instead you are saying that it will combine any dependency I bring

#

in

opaque ledge
#

yeah

scarlet inlet
#

Great thank you! And what's the point of CompleteDependency ?

opaque ledge
#

but only if its in system, not sure about the jobs you schedule in Monobehaviour world

scarlet inlet
#

(yes I use only systems)

opaque ledge
#

I never tried that but probably makes your main thread wait for dependency jobs to be completed

scarlet inlet
#

ok sounds great pheew

#

I was worried for a minute

opaque ledge
#

why ๐Ÿ˜„

scarlet inlet
#

because otherwise I needed to handle the dependency myself

#

in fact I still don't understand why the physic ECS needs the final job handle

opaque ledge
#

btw did you solve your problem with the hiearchy conversion thingie, where you didnt want children to be converted ?

scarlet inlet
#

yes it was painful but I did

#

I think I shared the code somewhere let me see

opaque ledge
#

You still handle the depndency yourself tho ๐Ÿค”

#

oh thats great^^

scarlet inlet
opaque ledge
#

did you destroy them or prevent them being converted ?

scarlet inlet
#

this code works on instantiated prefabs, so I can actually delete the gameobjects before the conversion

#

awkward part, I had to create a scene, because they don't provide a version with an array of objects

warped trail
#

i hope they will make physics stuff easy to work with๐Ÿ˜•

opaque ledge
#

yeah tbh ๐Ÿ™‚

#

But.. its kinda understandable, i mean if you try to do physics stuff before physics stuff for that frame is created then bad things will happen

scarlet inlet
#

I may understand the job handles for the things that happens in the middle of the physic frame

#

but I am not sure why the end of simulation final job handle exists

#

I need to discuss this one

warped trail
#

i haven't figure out the way to make ICollisionEventsJob work without .Complete(), but ITriggerEventsJob works just fine๐Ÿ˜•

scarlet inlet
#

if you are talking about error outputed by the JobDebugger, their code may have bugs in this sense

#

it's something that we are still figuring out as well;

opaque ledge
#

its kinda weird that i dont see anything related to job handles in dots physics forums

warped trail
#

there is some posts

scarlet inlet
#

if you see the CollisionEventsJob override schedule, it combines the job with a final handle anyway

warped trail
#

i saw that too

scarlet inlet
#

that makes sense because triggers and collision events jobs happen in the middle of the physic frame

#

also you may want to start raycast before the end of the physic frame, once the collisions are all updated

#

that's why these handles exist

opaque ledge
#

raycast is also weird in that regard, like.. if you dont do final job handle combine, it will give you errors, but if you disable job debugger then everything simply works

warped trail
#
Dependency = JobHandle.CombineDependencies(m_ExportPhysicsWorld.FinalJobHandle, Dependency);
// my work
m_EndFramePhysicsSystem.HandlesToWaitFor.Add(Dependency);```
scarlet inlet
#

the fact that it works it doesn't mean that works all right unluckily

warped trail
#

this what i do to make my raycasts work๐Ÿง

scarlet inlet
#

I am not sure what you need the HandlesToWaitFor

warped trail
#

without it there is erorrs

opaque ledge
#

i hope that they will make physics version of SystemBase so we dont need to do all these stuff ๐Ÿ˜„

scarlet inlet
#

hmm interesting

opaque ledge
#

i never needed handlesToWait for as well

#

just combining with final job handle was enough for me

warped trail
#

and this is what Unity.Physics folks recommend on forums

scarlet inlet
#

it shouldn't be needed as far as I understand it

round summit
#

Hmm what are these errors?
I made my code into a package and opened in my previous project
I imported the dots packages the same way (entities, hybrid renderer, unity.physics)

opaque ledge
#

right click the code choose quick actions, if it shows you a namespace choose that

#

i never saw that error before ๐Ÿค”

warped trail
#

i hope there will be new physics package update soon๐Ÿ˜…

opaque ledge
#

probably in 1 month ๐Ÿ˜„

junior fjord
#

are there any big changes in the general ecs package that everyone waits for?

opaque ledge
#

i asked the same question ๐Ÿ˜„

#

general thinking is that they will 'intergrate' current systems to DOTS basically

#

like ui etc.

#

by general thinking.. 2-3 people said this ๐Ÿ˜„

round summit
#

@opaque ledge
using Unity.Entities;
namespace is already included

opaque ledge
#

Tbh, there is only 1 thing i am wondering about, i wonder if they will make a special TagComponents that wont trigger a chunk recalculation ๐Ÿค”

warped trail
#

no๐Ÿ˜‚

formal scaffold
#

Hey how do you instantiate your Entities?
Do you create a GameObject with a Transfrom and maybe some other stuff,
then add the Convert to Entity Script and make it a prefab.
After which you instantiate this prefab within a GameManager mono where you add some more components to it?

I'm wondering about the workflow here from creating to instantiating ๐Ÿค”

opaque ledge
#

i would love it tbh ๐Ÿ˜„

#

EntityManager.Instantiate(entity)

formal scaffold
#

I'm wondering about the workflow, I mean you could create your own entities completely from code. But what makes more sense in the long run?

round summit
#

I think BlobAsset stuff is for fast-instantiation

#

But not so sure

opaque ledge
#

Do you know how to convert a gameobject to an entity ? you basically instantiate that entity with that method

scarlet inlet
#

If you want to build a scene, using the subscene is the way to go I think

#

if you want to create them dynamically then you don't need gameobjects, unless you want physic/mesh stuff setup in a prefab

#

we don't use subscenes, but we have prefabs setup from our artists

opaque ledge
#

i never could find a situation that i wanted to create a blob asset ๐Ÿค”

scarlet inlet
#

bye bye see you next time

opaque ledge
#

tc^^

round summit
#

World doesn't seem to contain a reference to DefaultGameObjectInjectionWorld

opaque ledge
#

sounds like some assembly issue

round summit
#

yeah

#

what can i do to fix these?

formal scaffold
#

What do you think is better:

  • A generic prefab in the scene with a single authoring script for special components,
  • The same prefab with a script for each component attached.

I don't like the second one because my inspector get's too long then.

#

@round summit I had the same issue once, did you reastart Unity? Don't remember if that fixed it for me back then. I also removed alot of code

#

Oh and I removed and added all packages

round summit
#

hm

#

i think the order you add the packages matter

formal scaffold
#

Sorry can't really remember ๐Ÿค”

round summit
#

oh, of course

#

i was on unity 2019.2

#

and made the asset in 2019.3

opaque ledge
#

@formal scaffold tbh i would go for 2nd option, it gives it more modularity, assuming behaviour of authoring wont change depending on what components that entity will have

round summit
#
- instantiate game object
(instantiated object's Convert() isn't called instantly)
- i want to do stuff on it right away but Conert isn't called and object is not ready for that
#

I tested that, that's how it is
How can i make the convert work instantly?
IConvertGameObjectToEntity's Convert called from a system?
That would make sense
What can i do about this?

#

Can i force the conversion so it's instant?

round summit
#

It looks pretty much like IConvertGameObjectToEntity' Convert() is called from a system outside.
Any idea what system this might be?

bright sentinel
#

@round summit I don't think it's possible to instantly convert it, because it happens sometime at the start of runtime

#

But why do you need it instantly?

round summit
#

I was able to instantiate them in after the start of the game

#

I get the entity, it works

#

But not at the same frame

#

Not after just calling the instantiation

#

@bright sentinel I need it
I instantiate the gameobject, and i immidently want to do stuff with it and its entity?

bright sentinel
#

Yes, but why? Because that shouldn't be a necessessity

#

What are you trying to achieve?

#

There's probably another way to do it

round summit
#

Switching states of the scene

#

making the scene go back in time

bright sentinel
#

And you need to do that the instant the game is run?

round summit
#

or making the scene load a servers state

bright sentinel
#

Well if you want to load something from a server, then you need to wait for the server anyways, so not sure why you can't just wait 1 frame for that to start

round summit
#

this is how i do it:

-state comes from server
-a new object appeared in the state that i dont have
-instantiate prefab
-set its velocity among other things

#

if i wait one frame, determinism is ruined

bright sentinel
#

That shouldn't have anything to do with conversion though

round summit
#

.
server constantly sends state
client does this immidently as he recieves a state

#

its not like request and reply

bright sentinel
#

But this doesn't have anything to do with conversion

#

As conversion happens as you enter the game

round summit
#

comversion happens when a convertible enters the scene

#

you can Instantiate() them

#

and they will convert

#

in regular runtime

#

but they will convert the next frame

bright sentinel
#

But if you're loading a new scene, then can't you just wait 1 frame on all clients?

round summit
#

i want to wait one conversion frame only

#

imstead of waiting a mono frame + ecs physics frame

#

I bet the convert is called fram a system,
I think i can call that systems update after instantiating stuff

bright sentinel
#

Well you could always just convert them when you run the game instead of when loading the scene, and then save that converted prefab somewhere

round summit
#

I am not loading scenes btw

#

my "loading states to scene" is just instantiate,destroy, position, velocity assigns

warped trail
#

what are converting?๐Ÿค”

round summit
#

Gameobject's companion entity

warped trail
#

shouldn't you just convert once and than just spawn entities?๐Ÿค”

bright sentinel
#

So if you're not loading any scenes, I don't understand why you can't just convert them as soon as you enter the game

round summit
#

I am instatiating a gameobject anyways though
Isn't that already the main bottleneck?

bright sentinel
#

But if you're working with ECS, why are you instantiating a gameobject?