#archived-dots

1 messages · Page 90 of 1

plain cloak
#

i mean bool on component

gusty comet
#

thx!

plain cloak
#

you should benchmark in your own project though, it depends on a lot of variables like system count, frequency etc.

gusty comet
#

Yeah, saw this talk that really focused on relations frecuency and cost in ecs

potent whale
#

Does any1 know how to fix problem with Hybrid Renderer and HDRP 7.1.2 in Unity 2019.3.0b ?

wary anchor
#

Hi all.

I'm misusing an array somehow but I'm not entirely sure how. The error in the console is:

ReadWriteBuffers are restricted to only read & write the element at the job index. You can use double buffering strategies to avoid race conditions due to reading & writing in parallel to the same elements from a job.

and this is referring to the "float3 checkAtomPosition" line below, where the AtomDataArray is a persistent NativeArray<float4> calculated elsewhere and used here only as a lookup reference.

private byte CheckTestVector(float3 testVector, int atomIndex)
        {
            for (int i = 0; i < AtomDataArray.Length; i++)
            {
                if (i == atomIndex)
                    continue;
                float3 checkAtomPosition = new float3(AtomDataArray[i].x, AtomDataArray[i].y, AtomDataArray[i].z);
                float checkSqDist = ((AtomDataArray[i].w * 0.5f) + SpawnPointSphereCollisionCheckRadius) * ((AtomDataArray[i].w * 0.5f) + SpawnPointSphereCollisionCheckRadius);
                if (math.distancesq(testVector, checkAtomPosition) < checkSqDist)
                    return 0;
            }

            return 1;
}```
low tangle
#

whats the atomdataarray declared as?

#

wheres it grabbed in the chunk/entity as well

#

hm nativearray

#

sub range makes me think of the index passed to the job

wary anchor
#

yes sorry incomplete data, I'll post the class 1 sec

#

It's not refactored yet, apologies for the sprawl

low tangle
#

no worries, I'll give it a good shot but I've gotta sleep very soon

#

math.normalize(gridPosition - translation.Value);

#

are you sure your key is normalized?

#

if so, does normalizesafe change the outcome?

#
else
    testVectors[flatIndex] = float3.zero;
#

the else condition might be out of range maybe?

#

makes me wonder if the native array is getting passed in short or empty possibly? or do you always fill it to full?

#

oh intresting

#

int atomIndex = index;

wary anchor
#

I can use normalisesafe for the possibility that an atom position overlaps with a grid position - that doesn't fix the problem though. I think it's to do with the way I'm setting up the job as a foreach with entity

low tangle
#

the job index is the thread index / index into the chunk based on the archtype of said chunk

wary anchor
#

ahh, okay so the index in the foreach with entity isn't going to overlap with the array's index

low tangle
#

wait let me check

#

yes.

wary anchor
#

I want to exclude "this" atom from the collision check

low tangle
#

where can you find its index?

#

or its key

#

is it the float3 position?

#

you got the translation right there handy

wary anchor
#

no, it's the index of the atom within the AtomDataArray NativeArray

low tangle
#

ah will have to scan for it then, for the array, do a compare till you find it

wary anchor
#

hmm might be faster to add a component containing that data then

low tangle
#

remember loops are fast for smaller datasets

#

yeah might be

#

save the scan

wary anchor
#

okay I'll give that a shot, thank you again @low tangle !

low tangle
#

no problem 👍🏻

#

good luck

wary anchor
#

Cheers 🙂

#

Mmm that doesn't seem to work, it's weird it's like it's limiting my ability to step through the whole of the the AtomDataArray. I'll try it via the translation.Value

old pulsar
#

CreateChunk() takes a NativeArray<ArchetypeChunk> and an int for entityCount. The documentation says it creates enough chunks to hold the entityCount number of entities, but what if the number of created chunks is less then or greater than the length of the NativeArray? If less than, what tells you how many were created?

low tangle
#

hm

#

not sure on that one brian

#

@wary anchor I would look into the source array, just skimmed the rest and I see no glaring issues atomGridUpdateSystem.AtomDataArray

old pulsar
#

The docs also sorta suggest that the chunks are always new rather than ever using any existing chunks, but it's not unambiguous about that.

low tangle
#

does the chunks have a .IsCreated maybe? @old pulsar

#

chunks and entities inside them is a pretty even 1:1 relationship of the size of the archtype

wary anchor
#

Mmmm It's odd. I use that array as a reference in several places without issue, but this is the first time I'm stepping through the whole thing within a job for each with entity for each of a bunch of different vectors.

old pulsar
#

ArchetypeChunk has no such member. I'm just curious about this reading the docs, though. I have no concrete use case. Thanks

low tangle
#

alright

#

maybe entitymanager has a method to check a chunk?

wary anchor
#

I'm seeing 4 such messages, and I reckon this input file probably has 4 different atom types, so they'll be made in 4 different chunks

low tangle
#

hm

#

one fail per chunk

#

so is it your boundaries

#

0, end

wary anchor
#

Mmmmm I don't think these should be separate chunks at all

#

Food for thought, I won't keep you more from sleep, thank you @low tangle

pliant pike
#

I dont suppose anyone knows how you get a reference to a blobasset inside a job without using a foreach?

#

I can get the values in the blob asset fine outside the job(so it seems)

#

I've tried everything I can think of inside the job but I just get garbage data

wary anchor
#

ahh I didn't make the AtomDataArray as [ReadOnly]

#

Now to optimise 😄

coarse turtle
#

@pliant pike did you grab by reference to the BlobAssetReference's data?

pliant pike
#

yep I used ref var tempblob = ref blobbarray

#

I've tried that every way I can think of inside and out

coarse turtle
#

hmm I might have an example in my current project...or I might've nuked it a while back when I was refactoring my client code

#

let me take a look

pliant pike
#

I'm getting the blob with getsingleton so I don't know if that maybe effects it in some way

coarse turtle
#

This is a bit old, might have to update it but this is all I did b/c I was lazy and short handed things. But judging from Unite vids, you can likely do ref ComponentData.BlobAsset.Value.Ptr

#

BlobAssetReference looks like they use relative addressing

pliant pike
#

I think they mentioned blobs work by an offset or something

coarse turtle
#

Yea, its to allow read speed ups

#

so you pass around the root address and the refs allow for relative addresses

#

I'll play around with it sometime today, I haven't touched blobs lately after my first set up

pliant pike
#

I cant seem to get it to work, this is my blob data anyway

#
public struct WaypointBlobs
{
    public BlobArray<float3> Waypoints;
    
    public static BlobAssetReference<WaypointBlobs> ConstructBlobdata(Translation[] Waypointgameobjects)
    {
        using (var builder = new BlobBuilder(Allocator.Temp)) 
        {
            ref var root = ref builder.ConstructRoot<WaypointBlobs>();
            
            var nodearray = builder.Allocate(ref root.Waypoints, Waypointgameobjects.Length);

            for (int i = 0; i < Waypointgameobjects.Length; i++)
            {
                var tempawapp = Waypointgameobjects[i];
                nodearray[i] = tempawapp.Value;


            }
        
            return builder.CreateBlobAssetReference<WaypointBlobs>(Allocator.Persistent);
        }
    }
    
}

public struct WaypointWalker : IComponentData
{
    public BlobAssetReference<WaypointBlobs> Waypoints;
}```
#

I'm getting the waypoints from converted gameobjects

coarse turtle
#

Uhh for now lazy hand it and try

public struct WaypointWalker : IComponentData
{
    public BlobAssetReference<WaypointBlobs> Waypoints;

    // See if you can grab the data like so in a job since you have the root ptr 
    // stored in the BlobAssetReference, this could be a function too
    public float3 this[int i] => WayPoints.Value.WayPoints[i];
}
pliant pike
#

yeah thanks, I think I may have the answer from the forums

#

I was getting the blob array like this waypoints = dudewalker.waypoints.value.waypoints

#

when it should probably just be waypoints = dudewalker

coarse turtle
#

ah cool, lmk how it works 👍

#

Going to get back to doing some more dots stuff hopefully this week

pliant pike
#

yeah will do thanks

#

woot! leahYAY it works

potent whale
#

Does any1 know how to fix problem with Hybrid Renderer and HDRP 7.1.2 in Unity 2019.3.0b ?

dull copper
#

yes

#

but I also answered on the forums, you have to fix it manually

#

if you really want to go down that path, there are two options: update Hybrid itself to the newer API

#

or roll the 7.1.2's api to the older setup for the parts that hybrid uses

#

I haven't checked recent changes but like few weeks back, you only had to revert one git commit to roll back the related HDRP API changes

#

that being said, i'm sure Unity will fix this once 2019.3 releases as they need these all to play ball together with the dots shooter sample

potent whale
#

@dull copper Thank you!

stable fog
#

Has anyone worked on an Entity construction pipeline?

#

as in an editor extension that lets you compose entities from existing IComponentData types?

vagrant surge
#

thats how current conversion works

#

@stable fog

#

you have an IComponentData with [generate authoring], and it shows in the editor

#

when you have it inside a subscene, then it will convert whenever you change the components

stable fog
#

O.o

safe lintel
#

it sorta sounded like someone managed to do that with odininspector but there werent any details of it in their post

#

wait is that available now @vagrant surge ?

vagrant surge
#

coming next update

#

should be any day now

safe lintel
#

oh

stable fog
#

ah, so not how the current version works

safe lintel
#

yeah been twiddling my thumbs waiting for that too 🙂

stable fog
#

So basically they willl act like MonoBehaviours inside the editor, in terms of how you compose things?

#

Maybe I shouldn't waste my time building this editor to compose entities then

vagrant surge
#

yes

stable fog
#

I mean, It may still be useful for my needs

vagrant surge
#

it looks like a monobehavior, but its an authoring component

#

on conversion it becomes i component data

#

you can also preview what entity will get generated

stable fog
#

And all you have to do is write the IComponentData and decorate it with an attribute?

vagrant surge
#

yes

#

at the moment you need to do the authoring component yourself wich is annoying

stable fog
#

ah neat, then It may still be worth while to continue down the path I am

vagrant surge
#

but next update is just ananotation

stable fog
runic crystal
#

hey is there any good tutorial for ecs that's in the context of making actual gameplay

#

I'm not good at learning with just abstract concepts rather than actual examples

pliant pike
#

there's not really many tutorials that are current and up to date

runic crystal
#

oof

pliant pike
#

that youtuber has some good vids on it though

runic crystal
#

will check them out thanks

pliant pike
#

also there's this project that was posted in the forums recently

runic crystal
#

nice

#

the lists of good/bad points etc looks very interesting

pliant pike
#

yeah I like programming in dots it feels much better than oop

runic crystal
#

it looks like it has a proper, imposed structure which is why I'm interested

#

also multiple active scene in one instance of your game

tawdry tree
#

(At least) one of the Unite talk basically makes a tiny prototype of a game, but it blazes over things. I would suggest starting at the more abstract concepts, just going over them, then finding one of the sadly few tutorials out there. Sadly I don't have any links to contribute there.

vagrant surge
#

the structure part is a very big deal

#

its super rigid, but it also means your game becomes a "main loop" that you can trivially check

runic crystal
#

I don't mind rigid

#

in fact I think it's good since I don't have to figure out what's the best structure for my various systems and then try to stick to that structure

pliant pike
#

yeah that was one of my main struggling points with oop

#

what do I define as an object, in an data exchange, where do I put the code that exchanges data between two objects, either one, or do I create a new one for the exchange

runic crystal
#

looking at that zombie dots game and it's more in line with what I was looking for

#

interesting

stable fog
#

I found a pretty nice tutorial the other day

#

these two were the ones that finally got me over the hump

#

oh you linked code monkey, my bad

runic crystal
#

Yeah I'll check his stuff out when I have the time

pliant pike
#

no worries we definitely know they are good ones then 😄

gusty comet
#

My entity conversions never seem to work properly in a built game - if I drop a cube down, scale it up, make a subscene out of it and play, it remains that size. Then if I build the game it either doesnt show, or its off by some metres and significantly smaller.

#

Though funny enough some things like a player controller worked, so I created a new universal RP project with the latest beta, grabbed entities & hybrid renderer and dropped down a cube, same issue.

pliant pike
#

maybe the entity conversion isn't complete yet, like I know you need the nonuniformscale or uniformscale component for object scaling to work in dots

gusty comet
#

idk, I noticed it first happening when I decided to try the classic 300 rotating cubes in my otherwise fine ECS project. Was just a convert to entity script with a prefab conversion as the github repo has, but they wouldn't appear at all in the build.

#

I'll see if the uniform scaling works

#

but you'd think it wouldn't work in playmode right?

pliant pike
#

I wonder is it possible for them to check all the changes you can make to an object and have them fully converted into the entity 🤔

#

I mean it might be difficult for them

gusty comet
#

honestly i just want something to work at this point 😩

pliant pike
#

I would just add a scale component in the conversion and just set it in there to what I wanted to be honest

gusty comet
#

ahhh it still doesn't work

#

I put a scale component onto the cubes in the system which definitely worked in playmode, had a good 20 thicc cubes

#

But the built game is devoid of cubes

pliant pike
#

whats the code

gusty comet
#

it's a fair bit of boilerplate hence the pastebin, sry

#

it's basically the exact same code as found in the pinned github repo examples in this channel

#

HelloCube

pliant pike
#

I meant just on the specific where you added the component

gusty comet
#

second link

pliant pike
#

code seems ok, sorry I dont know then, it's weird that the build is different to play mode

gusty comet
#

yeah :c mystery

#

I'll drop a post on the unity forums if I don't figure it out, but thanks for checking the code out

honest dirge
#

@gusty comet Are you building il2cpp?

#

Isn't all of job systems code handled with reflection? So it wouldn't be referenced and therefore stripped?

pliant pike
#

its not me its @gusty comet

honest dirge
#

Right!

#

Fixed 🙂 regardless that could be why.

#

I've not tried to build anything with DOTS and il2cpp yet. So I can't say for certain.

pliant pike
#

the code isn't in a job though

gusty comet
#

Im using mono :v

#

my running theory is it's the scriptable render pipeline and hybrid renderer not playing correctly

#

because the entities ARE converting, when i build the game I can run around, which is handled by a job system

pliant pike
#

yeah must be some kind of render issue

gusty comet
#

def

safe lintel
gusty comet
#

omg i bet that's it

#

I was reading something just now that mentioned the SRP Batcher

safe lintel
#

i still get it in the builtin non srp renderer 🤷

gusty comet
#

aaa

#

oh my god it's fixed

#

thank you so much @safe lintel

safe lintel
#

unfiltered textures? 😋

gusty comet
#

hell yeah

gusty comet
#

Does anyone know if there is there a way to generate entities through code using DOTS and have them displayed or converted as game objects in the project hierarchy rather than solely in the entity debugger?

coarse turtle
#

currently there's no way to do that afaik

#

I do agree that it's a bit cumbersome to do it through the entity debugger

covert spire
#

How do I know which batch count to use when scheduling a job? Is there a way to figure out what value to use?

#

I know lots of work per Execute = low batch count, less work = high batch count

twin raven
#

Is there any word of when next dots release will be out?

#

The stuff they showed at Copenhagen

slow epoch
#

They said that most stuff about copenhagen would be this week

worn stag
#

new entities this week and dots fps in 3-4 weeks

mint iron
#

anyone know a way to accurately time a section of code within a burst job?

pliant pike
#

is that even possible 🤔

stable fog
#

I donno why I'm spending time on this entity composer, when supposedly we will have a better solution soon

pliant pike
#

I mean I would just do a timer in the onupdate either side of the job @mint iron and you could then set it return at that specific code in the job

stable fog
#

oh that feeling when you wake up in the morning and the insane coding session you did the previous night still works fine

#

donno if I'm missing anything here, I have the ability to add 4 component types to a model and give that model a name, and at runtime I can create archetypes from the models

dry dune
#

WTF is going on... Can someone explain this to me:
I have an entity buffer

[InternalBufferCapacity(8)]
public struct E : IBufferElementData{
  public static implicit operator Entity(E e) { return e.Value; }
  public static implicit operator E(Entity e) { return new E { Value = e }; }
  public Entity Value;
}```
when I'm using it this way it works as expected
```cs
var a = EntityManager.CreateEntity( typeof( A ) );
var b = EntityManager.GetBuffer<E>( e );
b.Add( a );```
but when i'm using it like this i'm getting " The NativeArray has been deallocated" error
```cs
var b = EntityManager.GetBuffer<E>( e );
var a = EntityManager.CreateEntity( typeof( A ) );
b.Add( a );```
amber flicker
#

Yea timing sections within a job is tricky. I did some hacky thing where I passed key press 1-10 into the job and early out at various points so I could easily do runtime comparisons. Also did some of the benchmark test runner stuff which is good but I found it very hard to get highly repeatable results. Not sure if that’s partly due to cpu branch prediction or something for me.

elder wharf
#

@dry dune

var b = EntityManager.GetBuffer<E>( e );
var a = EntityManager.CreateEntity( typeof( A ) ); // creating an entity --> structural change happening, so chunks contents are moved
b.Add( a );

The first option work since you get the buffer after a structural change.
In the last option, the buffer will get deallocated since a structural change is happening (entity creation).

If you want the buffer to not be deallocated on a structural change, you can make it allocate outside of the chunks (by increasing the capacity...):

var buffer = EntityManager.GetBuffer<E>(e);
buffer.Reserve(buffer.Capacity + 1); // since we increase the capacity, the buffer will be allocated outside of the chunk

var a = EntityManager.CreateEntity((typeof(A));
buffer.Add(a); // no errors!
dry dune
#

thank you this is great explanation

#

but buffer do not belong to chunk where i'm adding new entity, so no memory moving was involved 🤔

#

I think happening something kind of: sync point caused by creating new entity deallocates everything that had Allocator.Temp including array internally used by buffer.

mint iron
#

i think sync invalidates everything everywhere.

public class TestSystem2 : ComponentSystem
{
    public struct BufferData : IBufferElementData {  }

    protected override void OnUpdate()
    {
        var e = EntityManager.CreateEntity(typeof(BufferData));
        var buffer = EntityManager.GetBuffer<BufferData>(e);
        buffer.Reserve(buffer.Capacity + 1);
        EntityManager.CreateEntity();
        buffer.Add(default); // <---- error
    }
}
coarse turtle
#

@mint iron for timing a burst job, would the Profiler.Beginsample work? I'm also curious

#

Unless burst doesn't support it... 🤔

mint iron
#

ill check Profiler.Beginsample.... [Edit] doesn't seem possible because it requires a string through to the internal calls and burst wont compile it.

I found something called ProfilerMarker which has a NativeDisableUnsafePtrRestriction on the pointer which means somebody has been intending to use it in jobs. https://hatebin.com/uadhwcnmqs

coarse turtle
#

ah nice 👍

frosty siren
#

I get an error "InvalidCastException: Specified cast is not valid." when trying to inspect the entity. And i found trigger: it happens only when entity has attached physics body and physics shape of Unity Physics package.
Maybe one of you has encountered this problem and can help me

mint iron
#

@frosty siren the inspector was broken with physics components on one of the earlier versions, i'm not sure if its fixed in newer versions because i haven't updated to latest yet. The bug was in versions before com.unity.properties-0.6.4-preview. But properties package is not something you can get from the PackageManager. What i did to fix it was download the package from the repo https://unity.bintray.com/unity/com.unity.properties/-/ and extracted it to my projects' /Packages folder and renamed it to com.unity.properties-0.6.4-preview - i believe it should detect the package appearing and remove it from your Library\PackageCache automatically. Back up all your stuff before trying.

mint iron
#

@coarse turtle figured how how to use ProfilerMarker 😄

coarse turtle
#

Oh sweet thnx @mint iron

mint iron
#

its quite tricky to trick a burst job into doing work, its pretty good at knowing when it can just pre-compute the value.

#

its also a shame that the timing resolution on the profiler window is only 0.00 😦

coarse turtle
#

yeah lol

dry dune
#

I wonder if anyone doing this as well? 🙂

public abstract class Sys : ComponentSystem{
  public EntityManager em => EntityManager;
  public EntityCommandBuffer ecb => PostUpdateCommands;
}```
#

@mint iron are all this emotions mean yes?

mint iron
#

hehe, maybe 🙂

#

I generally keep to microsofts naming conventions; i do have a bunch of abstract systems, mostly for events.

#

mostly just playing around with different ideas, they don't always end up being more readable or efficient.

dry dune
#

yes have few monstrous generic systems :)

private struct TweenJob<TSpecific>:IJobForEachWithEntity<Tweener<TSpecific,T>, Tween> where TSpecific:ITweenSpecificFunctions<TComponent,T>{ ... }```
mint iron
#

😄 nice one

dry dune
#

looks like this examples are parts of some event driven framework?

#

oh i got it this is GOAP

mint iron
#

two different events with a buffer of elements that share an interface

dry dune
#

very nice

#

i love it

coarse turtle
stable fog
#

whats that?

frosty siren
#

I see that BuildPhysicsWorld dispose bodies and it causes errors if another system trying to read CollisionWorld. I wrote [UpdateAfter(typeof(BuildPhysicsWorld))] on top of my sys and it works. But is it ok?

Also thx @mint iron for explanation of broken properties, info is very helpful!

coarse turtle
#

Ah so I made my own scriptable render pass and I found out Unity renders their ChunkInfo using the same functionalities to render their game/scene view lol

frosty siren
#

@coarse turtle I got same effect without any custom scriptable render passes

coarse turtle
#

Yeah should just be through the Graphics CommandBuffer

#

I usually forget it happens so I typically find it amusing when it happens

glass steeple
#

Hello
Can you help me change a field's value from one structure to another script and then use it in another script

Struct script

public struct SpaceInvadersGameState
{
    public const float projectileSpeed = 0.5f / 60f * 10f;
    public float gameSpeed;
}

An other script

private void DefineGameSpeed(int dropDownIndex)
    {
        switch (dropDownIndex)
        {
            case 0:
                SpaceInvadersGameState.gameSpeed = SpaceInvadersGameState.projectileSpeed * 1f;
                break;
        }
    }

An other script

speed = Vector2.right * SpaceInvadersGameState.gameSpeed
coarse turtle
#

hey so you need a ref to the struct if you want to modify the contents of said struct, likewise, not sure if this is DOTs oriented, but if it isn't there's a #💻┃code-beginner channel

glass steeple
#

i use ECS

#

@coarse turtle

dry dune
#

this code do not look like dots at all )

frosty siren
#

Maybe it's just a little part)

coarse turtle
#

yeah - I won't deny it - but yeah hopefully the ref tip helps 👍

glass steeple
#

ty man

#

i see it

coarse turtle
#

np

quick jolt
#

So I'm writing a ECS Job for a projectile and I'm having a hard time understanding how to "Hit" another entity.

#
            bool didHit;
            Entity result = ProjectileSystem.Raycast(pos.Value, nextPosition, out didHit);
            if (didHit)
            {
                //delete bullet
                CommandBuffer.DestroyEntity(index, entity);

                //hit enemy
                //????
            }```
#

I've got the other Entity that the projectile has hit, what's the right way to go about writing to it's health to hit it?

#

I believe using the EntityManager isn't an option if I want this to be Jobs friendly.

coarse turtle
#

thinking from the top of my head, you could try using ComponentDataFromEntity<Health> since you've got the other entity you hit

#

you can use the ECB to update the other entities health, or directly modify/reassign the ComponentDataFromEntity<Health>()[otherEntity].Current - some_value (where ComponentDataFromEntity<Health>() is stored to a struct var)

#

i think you might have to disable some safety checks if you go for the latter option

quick jolt
#

I've got a ECB setup, which I'm using to destroy the bullet

#

Although I'm not sure how to use it to write.

#

There are add/remove calls for components, but that's not quite what I need.

coarse turtle
#

ECB.SetComponent(otherEntity, new Health { ... });

quick jolt
#

So, there's 2 problems I ran into trying to use that

#
  1. Accessing that health, so I can modify it instead of just overriding its value.
  2. it asks for a JobIndex and I'm not sure what that is
coarse turtle
#

I believe the IJobForEachWithEntity's jobindex param might be enough from the interface

#

I've certainly done that without any issues so far

quick jolt
#

is that just the int next to the entity in the "Execute" method?

coarse turtle
#

yea

quick jolt
#

Boy I wish Unity had some better and more centralized docs on this stuff.

#

I'll give that a swing, thank you for your help 🙏

#

Having 5 separate youtube videos from Unite conferences and outdated example projects does not feel like the right way to be learning this.

#

Oh, any idea on the "Accessing that health, so I can modify it instead of just overriding its value" bit?

coarse turtle
#

typically if you have a reference/ptr to the Health - you can update its member variables

quick jolt
#

How would I get it though?

frosty siren
#

As i remember LTW automatically copying Translation values but CopyTanformFromGameObject writes directly to LTW. And to affect collider position with gameobject changes of position i need manually set Translation.Value from LTW.Position. Or i understand something wrong?

coarse turtle
#

ComponentDataFromEntity<T> stores the reference (or ptr?) to the struct so you can modify its structure (depends if you make it readonly, i think it's read/write by default)

frosty siren
#

"Having 5 separate youtube videos from Unite conferences and outdated example projects does not feel like the right way to be learning this."

Yes, @quick jolt , i hope some day unity team will update documentation with all that stuff

quick jolt
#

Oh, I didn't realize what ComponentDataFromEntity<T> was

#

where is the [Inject] attribute to set that up? I'm not seeing it in the Unity.​Entities namespace that documentation says it belongs to

coarse turtle
#

Inject is deprecated

#

there's a pinned message which has the deprecation forum thread

quick jolt
#

You're a godsend psuong 🙏

coarse turtle
#

I'd thank @dull copper for pinning it 🙂

runic crystal
#

so, from what I understand, right now if you want to convert prefabs into entities you have to write the code that does the conversion and spawning yourself, there isn't just a "InstantiateAsEntity" function or something

dry dune
runic crystal
#

thanks

dry dune
#

@runic crystal yes, no magic, mesh renderer, transform and hierarchy are converter automatically, all custom components you have to convert yourself

runic crystal
#

kk

#

I imagine they'll eventually have either full automatic conversion or a proper entity prefab system?

dry dune
runic crystal
#

thanks

dull copper
#

@quick jolt @coarse turtle actually I had to let that thread go from the pinned message as i couldn't fit the rest anymore with it 🙂

#

but it's pinned on the dots subforums - which link is in the pinned here too

#

had i known this, i would have made two messages initially

#

I guess i still could, would just need to get it pinned again

quick jolt
#

I think the link to the forum is enough. I found it 🤗

quick jolt
#

Can you use the ECS Physics raycast to query non-ECS colliders?

frosty siren
#

@quick jolt I has checked this a moment ago and an answer is "no"

#

Or u meaning building your own physics world with non-ECS colliders data?

quick jolt
#

I think the answer is no then. /

#

You can do the latter though, right? Just GameObjectEntities

quick jolt
#

InvalidOperationException: The native container has been declared as [WriteOnly] in the job, but you are reading from it.

#

I'm getting this error on collisionWorld.CastRay(input, out rh); inside a IJobForEachWithEntity's Execute

#

Any thoughts?

#

I might have found it, it's that I was fetching the physics world inside the Job .

gritty grail
#

Is there anyway to use StartCoroutine in a system?

old pulsar
#

Looking at Entities.ForEach, it seems to do surprising things. As far as I can gather, it copies components and entity ids of the matching chunks into new arrays, passes them by ref into your lambda, and then writes back the component values to the actual chunk subarrays after each lambda call. ForEach allows you to make structural changes (like deleting entities) in the lamba, but I'm not sure how this avoids interfering with its iteration. However it's done, I assume it incurs overhead.

Am I misreading the code/docs? Seems very odd that we're trying to maximize performance but then the most convenient methods for accessing components involves a lot of copying rather than just direct access to the chunk subarrays. Are there good reasons to avoid direct access, or is it somehow impossible to provide a convenient API for doing so?

#

@gritty grail Think I saw a recent discussion of coroutines in the dots forum. End verdict is 1) you can use them 2) but not in jobs 3) and there are more proper dots solutions for the same problems.

#

@gritty grail If you're asking how to call the method, it's a monobehavior method, so you just need to get a ref to the relevant monobehavior object in the system, using GameObject.Find() or the like.

wild dove
#

i remember something from a recent Unite presentation where they mentioned .ForEach (in the past) not being good to use generally, but that they were doing some specialcase optimization for it or such.

old pulsar
#

@wild dove I know they've said the lambda is somehow specially compiled to avoid producing garbage, but I don't recall which vid that was.

summer thicket
old pulsar
#

I wonder if IJobForEach has the same problems. I assume IJobChunk does not.

dry dune
mint iron
#

seems like they want ForEach as a quick way to code things that mirrors IJobForEach, so later it should be easy to move that code into jobs for performance.

#

Also Entities.With().ForEach() should be changing with the next version so that it compiles a job underneath; they demo'd the code at unite copenhagen.

#

@old pulsar IJobForEach passes a refs directly to the component in chunk, IJobChunk lets you do the same as GetNativeArray<T> is mapped to the existing component array in chunk.

dire frigate
#

Has anyone had luck compiling DOTS to Linux or Windows?

#

Can't seem to get it to work even with the packages installed for platforms

echo pendant
#

DOTS is so fast its actually so cool

#

Like

#

It makes me excited

mint iron
#

me too, its so cool to get something similar in perf to C++ while keeping most of the things i like about using C#.

frosty siren
#

Is there a way to bind gameobject to entity from code?

coarse turtle
#

You'd typically do EntityManager.AddComponentObject(entity, object)

frosty siren
#

thx

#

Now i can delete IConvertGameObjectToEntiy Mono after conversion and Instantiate new GO and entity apart and then bind them

frosty siren
#

Can i get gameobject which attached to entity from entity? I mean inside ForEach code

#

Now i just get Transform and then get gameobject from it. Looks dirty, want better solution)

coarse turtle
#

Entities.ForEach(F_C_delegate), where F_C takes in a Component Object, you can look at the EntityQueryBuilder class for the other delegates you can use in a ForEach

C: ComponentObject
D: ComponentData
S: SharedComponentData
B: Buffer<IBufferElementData>

slow epoch
#

I think i've missed something. What are component objects?

#

Can't find any docs about it

coarse turtle
#

They're just regular objects

slow epoch
#

Regular as C# objects or Unity objects

coarse turtle
#

I believe they allow regular C# ones by default

slow epoch
#

So you can add a monobehaviour to an entity?

coarse turtle
#

Yep

slow epoch
#

Although i know is not the best think to do

#

Damn that's gonna solve a lot of problems i had

safe lintel
#

wonder if the entities release has been delayed 😦

coarse turtle
#

yea wondering that too 🤔

frosty siren
#

is there a math method that returns angle between two float3?

dull copper
#

I'd expect them to target something closer to 2019.3 release at this point

#

I mean 2019.3 final was originally planned to get out at the end of this month

#

so realistically could expect something like few first weeks of November

stable fog
#

is it not?

mystic mountain
#

If I want a subtracted component for a job. Do I need to use EntityQuery? (solved; ExcludeComponent)

stable fog
#

I suppose 2019.3.0b7 still has a large number of known issues, sadly a bug with SerializedReference isn't on it

dull copper
#

having big list of known issues haven't stopped them from releasing in past 😄

stable fog
#

lol

dull copper
#

they mainly care of the critical issues when it comes to upcoming launch

stable fog
#

I don't understand why that serializeReference bug isn't on the list, it really concerns me

#

makes me think they are not going to deal with it

dull copper
#

there are tons of bugs they don't list on those notes

stable fog
#

If you're not aware, if you have class which has an array of itself, and you have an array of that class, and you instantiate an element into the array, unity automatically populates the inner array with the outer array's first element, creating a circular reference and if you modify any other property on that instance, unity hard crashes

#

presumably because of some infinite loop/stack overflow in the editor

mystic mountain
#

How can I make JobA dependent on JobB which doesn't share any Components, but a HashMap?

#

Related, does Schedule(system, JobHandle) take the the EntityQuery and use it as dependency to the job?

#

And in that context, what happens if a Job that doesn't use ComponentA, use a query which says it should exist? Will it only create the dependency and still run, or will it add the requirement to run? 😛

safe lintel
#

is there a reason that using the jobhandles doesnt work for dependencies? also just from one anecdotal experience, was that when I had two jobs(jobA,jobB) where jobB was dependant on jobA, if the query for jobB wasnt met, jobA didnt run. ill be honest i just restructured things but didnt investigate it really so not sure if there are ways around it, that it was unintended behaviour or not

dry dune
#

@slow epoch adding Object to Entity makes this Entity impossible to serialize using SerializeUtility and SerializeUtilityHybrid

gusty comet
#

When doing entity queries should I care about the ordering when using WithAll with WithNone

dry dune
#

@gusty comet no, order doesn't mater

gusty comet
#

Hey, thanks!

coarse turtle
#

hmm anyone had any issues with the URP and DOT's Hybrid Renderer? The issue I'm seeing right now is the rendered quad's position visually doesn't update, but the LocalToWorld matrix certainly did 🤔

dull copper
#

I wonder if it's even been updated for URP name change 🤔

#

there's limited 2019.3 changes on hybrid atm

coarse turtle
#

Ah okay nevermind, I found my issue, looks like the Experimental 2D Renderer in URP isn't compatible w/ DOTs as it forces an orthographic projection

dull copper
#

oh you use 2D

#

yeah, all bets are off then 😄

coarse turtle
#

Yeah haha

dull copper
#

afaik, there will also be separate 2D renderer for tiny(?)

gusty comet
dull copper
#

but I doubt it be anywhere as complex as URP's 2D

coarse turtle
#

Yea I imagined that would be the case and @gusty comet you can use an IJobForEach with the [ExcludeComponenTag(...)] attribute on the job struct

gusty comet
#

and the postUpdateCommand?

coarse turtle
#

Or you can do a IJobChunk and disregard the CanDoActionFlag

#

You would use EntityCommandBuffer

#

in place of PostUpdateCommands

#

I'd imagine you have to use the Concurrent EntityCommandBuffer

gusty comet
#

and I guess I'll just be passing it on the jobs OnUpdate

coarse turtle
#

yep

gusty comet
#

thx man

mint iron
mystic mountain
#

Anyone know how to add dependency between jobs for Presistant NativeHashMap?

mystic mountain
#

Ok, it seems like I really had the wrong idea of JobHandles. Anyone have any resource of this actually works? E.g. if I have JobA and JobB, but they don't share any components to iterate over, but schedule B with the handle from A. Will B wait for A to complete?

mint iron
#

yeah... so jobhandles really dont have anything to do with components.

#

JobComponentSystem does some magic based on which queries you've used GetEntityQuery on to figure out some dependencies.

#

but its just JobHandle waiting for all the other jobs it was given as a dependency to complete before running.

#

so, JobHandle.CombineDependencies(...) everything u need to be finished.

mystic mountain
#

Ok, so it's basically empty as it comes as paremeter into a system?

mint iron
#

most of the time i believe so

#

thats why u have to manually register your jobs with Phsyics systems and command buffers

#

if you look at what happens there, they just keep lists of job handles and call Complete() on them or pass it into their own jobs as dependency list

mystic mountain
#

Hmm, still don't get how it knows the component dependencies of the jobs though then.

#

So must be like Can I schedule this job, or is it depenent on other jobs that haven't completed?(yes/no) Is any current job working on component this one wants to write/read of? (yes/no) => check next job. Right?

#

But it feels more complicated then that cause systems still have order, that also is translated into job order ? o.o

mint iron
#

i've heard people talk about that, im not sure where it comes from, but i havent seen any evidence of it in the source. i'd love to be wrong, but it seems to be purely based on job handles with 'x jobs must complete before me'. How that dependency list is constructed might be done in the component system base where they know what queries you've used, or it could be something in the pre-compiled info of the job itself.

mystic mountain
#

aha

mint iron
#

the other side of it, is that the sentinel/safety system, which will throw if you try to do something that hasn't been declared. like when you try to write to a collection with the an invalid safety. But i don't think that factors into scheduling.

#

god my english is bad today lol

mystic mountain
#

Yeah, I've noticed that x) Just feels like passing handles could've been changed to something simpler like a Attribute on the job to depend on another, but I guess you can do more advanced stuff with handles like condition based dependencies.

gusty comet
#

@mint iron thx for the code rewrite!

sonic oyster
#

I have a real hard question

#

Do Burst compiler support dll plugins?

#

I mean, write a class that references job system, burst and stuff

#

write there actual job constructor and job struct with [BurstCompile]

#

compile only that class into DLL

#

and plug into unity game?

#

I am compiling some scripts in runtime using Assembly c#

#

and whole script DOES work, except burst doesn't know what to do

#
  at Mono.Cecil.BaseAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference name, Mono.Cecil.ReaderParameters parameters) [0x00105] in <28cdca1704d2491781795499c297b78b>:0 
  at Burst.Compiler.IL.AssemblyLoader.Resolve (Mono.Cecil.AssemblyNameReference name) [0x00058] in <3179d4839c86430ca331f2949f40ede5>:0 
  at Burst.Compiler.IL.AssemblyLoader.Resolve (Burst.Compiler.IL.Helpers.SimpleTypeReferenceString simpleTypeReferenceString) [0x00015] in <3179d4839c86430ca331f2949f40ede5>:0 
  at Burst.Compiler.IL.AssemblyLoader.Resolve (Burst.Compiler.IL.Helpers.SimpleTypeReferenceString simpleTypeReferenceString) [0x00120] in <3179d4839c86430ca331f2949f40ede5>:0 
  at Burst.Compiler.IL.AssemblyLoader.Resolve (Burst.Compiler.IL.Helpers.MethodReferenceString methodReferenceString) [0x0000e] in <3179d4839c86430ca331f2949f40ede5>:0 
  at Burst.Compiler.IL.Jit.JitCompilerService.Compile (Burst.Compiler.IL.Jit.JitCompilerService+CompileJob job) [0x001d9] in <3179d4839c86430ca331f2949f40ede5>:0
While compiling job: Unity.Jobs.IJobExtensions+JobStruct`1[[Mod_WorldGen_FloatingIslands+ChunkGen, ig6cxzim, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null::Execute(Mod_WorldGen_FloatingIslands+ChunkGen&, ig6cxzim, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null|System.IntPtr, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089|System.IntPtr, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089|Unity.Jobs.LowLevel.Unsafe.JobRanges&, UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null|System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)```
gritty grail
#

I can't hold a reference type in a component can I?

gusty comet
#

structs are all pass-by-value. You'll have to pass the reference on the OnUpdate job

sonic oyster
#

@gusty comet so if i have struct inside that dynamically compiled .cs file, i have to pass ref to it somewhere?

#

If so, how and where? 😮

gusty comet
#

no idea I was responding to Diviel

sonic oyster
#

aww :C

#

sorry, i didn't actually read it as question and answer!

deft niche
sonic oyster
#

@deft niche

Improve BurstCompiler.CompileFunctionPointer to compile asynchronously function pointers in the Editor
Improve of error codes and messages infrastructure.
Upgraded Burst to use LLVM Version 8.0.1 by default, bringing the latest optimization improvements from the LLVM project.
Fix issue with libtinfo5 missing on Linux.
Fix possible NullReferenceException when an entry point function is calling another empty function.
Fix an exception occurring while calculating the size of a struct with indirect dependencies to itself.
Fix potential failure when loading MDB debugging file.
Fix linker issue with folder containing spaces.
Fix issue with package validation by removing ifdef around namespaces.
Fix issue with an internal compiler exception related to an empty stack
#

you have that on top of list

deft niche
#

@sonic oyster Ohh..just found out that its not the latest changelog. Its showing the changelog for com.unity.burst@1.1. The latest preview version is 1.2.0-preview6

sonic oyster
#

@deft niche but you linked correct one 😄

deft niche
#

hahah... yeah but it shows changes only till preview 5. 😦 no idea what changes happened in preview 6

sonic oyster
rugged wagon
#

Does NativeArray<T0>.Reinterpret allocate a new array or does it let you write to the original memory as if it's a different type?

deft niche
#

@rugged wagon It does allocate a new NativeArray

rugged wagon
#

Ok thanks

worldly pulsar
#

@rugged wagon Reinterpret doesn't allocate, it gives you a NativeArray with the same underlying memory (with Allocator.Invalid to make sure you don't double free). You can write to it and observe the changes in the original array.

gritty grail
#

How would you guys go about designing a state machine that works with DOTS?

rugged wagon
#

@worldly pulsar great! I was pretty sure it didn't allocate a new array haha. Seems really useful!

candid willow
#

Anyone know if ECS is OK to use for AR?

untold night
#

Hello, I've been busy working on cleaning up some of my ECS utilties into something a bit more useful for folks:
https://github.com/periodyctom/Hydrogen.Entities

Has helper types, docs, and example code for the following:

  • A ScriptableObject -> Blob Asset conversion pipline, with examples of Blob usage.
  • Saving Singleton Data Components to SubScenes, handling multiple scene loads, Singleton data reloading. Especially useful (at least in my projects and tests) for getting config data that can be loaded or set from many places instead of trying to write and maintain a complex bootstrapping process if all you need is to load some data.
  • Full test coverage for the above, both in Hybrid and Pure.

Feedback/suggestions are appreciated.

analog beacon
#

what does dots stand for and what is dots?

placid thicket
analog beacon
#

thx

#

a lot of the page seems to be talking about using multi core processers

placid thicket
#

it's quite a bit more involved than just multi-threading - it changes how data is organized and accessed by the CPU in order to get improved performance (the big win is data contiguity and reducing cache misses for your CPU's cache registries)

#

that's the ECS portion, anyhow

analog beacon
#

😁 I like it.The new systems just seem to not have a place I could go to learn them

placid thicket
#

yeah, it's still fairly new and the documentation appears to be going through rapid iterations and changes

#

though I've noticed that the changes are starting to calm down

analog beacon
#

hmm, so if I wait a while tutorials will start to show up?

placid thicket
#

I'd imagine so - we're currently working on a project that we're intending to use the full offering of DOTS for, but we're focusing on getting a working build using MonoBehaviours while it's still in heav(ier) development. Eventually we'll have a big porting phase where we rip apart many of our MonoBehaviours and convert them to components and systems.

#

Not sure if other people here have alternate suggestions to that approach or not - perhaps I'm missing a goldmine of up-to-date resources?

analog beacon
#

I want to make a multiplayer project in 2019(it's not big, probably needs to have like 2 players in a session), but I don't know where to start with it.

placid thicket
#

I'd honestly start with monobehaviours and look into Photon (a networking library) for the time being - you can always refactor code later

#

it's easy to stall out and make no progress by spending too much time trying to make optimization decisions early on

#

just get something going 🙂

dry dune
#

@gritty grail

How would you guys go about designing a state machine that works with DOTS?
in fact ECS is a big state machine itself

analog beacon
#

good advice, thanks, I believe it is called Photon PUN?

placid thicket
#

correct

analog beacon
#

I will get into it 😁 your advice is quite good

placid thicket
#

👍 glad I could help

radiant sentinel
#

Hello, please help me.
Im using dots physic package at my game. Its work awsome on unity but when i build , the velocity of entities resets on each frame.

#

Im using ijob foreach to set velocity and never writes on linear velocity at other systems

gusty comet
#

How should I go about tag generation for a system like binary spatial division?

mint iron
#

@untold night what triggers the conversion of a ScriptableObject? is it when it appears referenced within a GameObject that is being converted?

radiant sentinel
#

Please help, what can i do ?

#

I think velocity working faster when i build game

tawdry tree
#

Are you using (fixed)DeltaTime?
Sounds like we'd need more information to help you, but someone who has experience with DOTS physics might be able to point you in the right direction, or something like that.

radiant sentinel
#

Yes im using . @tawdry tree

#

Delta time passed to job

tawdry tree
#

Then I got nothing. Haven't used DOTS physics, so I don't know what could be wrong if it's not deltatime-perf differences between editor/build

radiant sentinel
#

Ok thanks @tawdry tree

gusty comet
#

How could I go about implementing a command-like system in ecs?

slow epoch
#

How to clamp magnitude with math library?

#

for a float3

tawdry tree
#

@gusty comet Why do you want to implement the command pattern? It is an OOP pattern, so you likely want something else for ECS.

#

@slow epoch Presumably something like math.clamp(fl3.magnitude, 0, 1)?
Haven't used it enough to get you more accurate syntax, but magnitude is a single number, so just get that and clamp it as normally?
Or do you mean normalizing the vector so that its magnitude is 1?

gusty comet
#

Guess I'll go with component composition like

vagrant surge
#

@gusty comet you create new entities as events

#

and forget about OOP patterns in ecs forever, its a different thing

tawdry tree
#

As vblanco says, you can create entities that communicate intent, such as "system X do Y".

#

I'm pretty sure there's some examples/discussions out there, though I don't have any right now

#

And yeah, whenever you think "I should use pattern P", stop and ask yourself:

  • Is this an OOP pattern?
  • Why do I want to use it?
#

Sometimes the pattern isn't necessarily OOP, and it could make sense, but usually it's just habits, and you need to find a way to translate your intent to proper ECS

gusty comet
#

Well, DOP feels like a the dark forest you explore while out of school and I try to keep myself grounded

vagrant surge
#

most of the OOP design patterns exist to categorize different ways of communication beetween classes. Most of those are unnecesary in ecs-land

gusty comet
#

ok, So if I wanted two entites to communicate I just create a 3rd entity holding both entities ids and my intent?

tawdry tree
#

Not necessarily like that, but in general, yes.

#

Do you have a specific case?

gusty comet
#

@tawdry tree many thanks, I've been looking for something like that

tawdry tree
#

I found that video exceedingly useful, it really made a few important things 'click'

#

So I share it whenever relevant

gusty comet
#

atm for interaction I use flag components from the making a turn based game talk

tawdry tree
#

After all, communication between things is absolutely critical for most, if not all games

vagrant surge
#

flag components are dangerous

#

they are very slow in general

#

with unity ECS, adding and removing components is kinda expensive

#

much faster than old add/remove component, but still not something you want to use tens of thousands of times a frame

tawdry tree
#

Well, for the turn based unite talk, the change is "whenever the user gives input", meaning less than once per frame. But yes, it's important to remember the potential perf cost. The talk does touch on that, though

gusty comet
#

Yeah, if it's thoughthans times a frame just have bool if its low freq flag comps are good

#

what would be the alternative to tag components?

#

bool in the component that tags instead of removing it

digital marsh
#

You can also use the change filter, I suppose, but that's a little brittle, since a change is registered whenever any system requires write access to a component, not when an actual change occurs

gusty comet
#

change filter?

#

somehow that sounds messier than tags to be honest 😄

digital marsh
#

Tags are likely the cleanest solution but you may run into performance issues.

tawdry tree
#

Something something premature optimization

digital marsh
#

Just be sure to use the entity command buffer when you use tags or you may be introducing sync points all over the place

#

Yeah, clean should be the first choice and then optimization if you actually run into issues imho

#

Side note: if you do use the entity command buffer to set tags be aware that any systems that run after the system that sets the tag and before the entity command buffer executes will not yet be aware of the tag.

tawdry tree
#

Think about perf and whether you should do it that way whenever you do anything that would add/remove components, but often the answer is "Yes, this is the best way". Sometimes it's the best perf way, but more likely it's simply the way which is the least costly, development wise (code complexity, maintainability, brittleness, etc)

gusty comet
#

this probably gets asked a lot, but aside from the performance benefits, what do you guys think of ecs in unity? is it worth using now for developing games? I'm not talking about the overall dots environment, but just the ecs itself. Is it worth the trade offs etc

#

"Performance by default"

#

so if monobehavior was just as fast as ecs, you would use mb rather than ecs?

vagrant surge
#

@gusty comet it cant, due to the laws of physics

#

ECS works more like how the CPUs are designed, so its stronger

gusty comet
#

I'm not asking if it can or not, I'm just asking would you use mb approach or ecs approach if performance or dod wasn't a concern at all

vagrant surge
#

i would still use ECS instead of MB if the cpu cost was closer. Of course talking about a possible finished ECS framework

gusty comet
#

saying that if mb was just as fast was just a quick way of putting it

vagrant surge
#

the pattern was created for MMOs, before the perf concerns

#

the hyperfast version is more of an evolution

#

Entitas at the moment has been used for full games, and its not really that much faster than monobehaviors

#

its also an ECS, just a bit less restrictive than unity one

#

one of the main characteristics ECS has is "high modularity" and separation of concerns

#

each system does one thing and one thing only, and wont reference that it doesnt need. Stuff is very weakly coupled

#

this makes it great for scalability in big projects. Adding new code wont affect old code, nor you will need to do anything about that old code

#

its also extremelly popoular in rogelikes

pliant pike
#

@gusty comet I would use ECS over monobehaviour any day

#

just the structure helps me a lot it being about separation of data and systems, its a lot cleaner/clearer

safe lintel
#

so much easier to rip a system out of existence and it doesnt hose your entire project

tawdry tree
#

In addition to what has been said about separation of concerns and clean code, ECS code is testable by default - create a world, create any entities and systems you need, then run update.

dry dune
vagrant surge
#

the earliest models i can find are from 2007

#

and preciselly about mmo development (ecs has some qualities that makes it god tier for networking)

echo pendant
#

Is NativeList in 2019.2.9?

#

its not showing up for me

gritty grail
#

Well what I wanna do is make a state machine for AI

#

And I was thinking maybe have the AI switch component tags depending on the state they're in

#

but I don't know what the most optimal way of doing that is.

#

Like for instance how do I want to add and remove the components from each individual agent? Do I just put that in update? Should I run a system or job on all agents that does that?

dry dune
vagrant surge
#

its very common to use component tags as state machine

#

just be careful with how many you got

#

well, more like how often are you switching

#

Dead is an absolute classic

gritty grail
#

What's the best way to assign many entities component tags? And I was going to go through all of the talks today actually

vagrant surge
#

there are batch add/remove components i think

dry dune
#

until you have less than 100 agents do not waste your time on finding the most performant way, you need to start care about this when you get above 1000 add/remove component operations per frame

gritty grail
#

Well I was just trying to make a test case game with thousands of AI

vagrant surge
#

with dozens of state changes, you are good. With thousands... it depends on how often you change it

#

state components are very very fast to update

#

just the cost of switch

dry dune
#

i recommend to start with simplest setup, get it working, and then optimize for performance

gritty grail
#

Well I was going to deal with a few states

#

Well right now just 2

#

First state is wait 10 second, second state is move to position

dry dune
#

tag is a good approach here, as long as to move in a fastest manner you want entities you going to move to be in the same chunk, most of the time your agents going to be in "move" or in "wait" state, not in "switch states" state

gritty grail
#

What if I have an int state in an entity component, and a switch statement that will add and remove tags maybe?

dry dune
#

in case when for state you use only int value in a component your move system going to iterate over all entities (including those which are in wait state)

you need tags to make all moving agents belong to separate archetype

and when you have tag you don't need to duplicate it with int

gritty grail
#

Hmm..

#

I want to use Enumerators for the wait state

vagrant surge
#

in that case

#

have your state components hold the data needed too

#

your Wait component has "float TimeLeft"

#

and your MoveTo component has "float 3 Target"

gritty grail
#

I'll think about it a bit more

dry dune
#

you'll need 3 systems:
• Move system iterates on entities with move component and after finishing move removes that component (also it may add Arrived component to let state-manager system know that agent was in move state)
• Wait system iterates on entities with wait components and removes that component when time is out
• StateManager system iterates on all agents without both move and wait and sets new state

vagrant surge
#

what ive seen is also using 1 system that does the 3 queries

dry dune
#

it doesn't mater where 3 queries placed in one system on in 3 different, this is 3 queries and 3 iterators anyway )

worn stag
#

so... no new entities this week for us?

untold night
#

@mint iron - yes. It currently piggybacks off of IConvertGameObjectToEntity but conversion can happen manually outside of that.

dry dune
#

i only see that com.unity.burst 1.2.0-preview.6 released 2 days ago

rare umbra
#

I thought the Entities auto conversion stuff was being updated this week? 😂

gritty grail
#

Would anyone know what may cause these kinds of errors?

#
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        cameraRot = AddCameraTag.Instance.camera.GetComponent<Transform>().rotation;
        var physicsWorld = World.Active.GetExistingSystem<Unity.Physics.Systems.BuildPhysicsWorld>().PhysicsWorld;
        var job = new MoveJob{
            horizontal = Quaternion.Euler(new float3(0,cameraRot.eulerAngles.y,0)) * new float3(1, 0, 0) * Input.GetAxis("Horizontal") * 3,
            vertical = Quaternion.Euler(new float3(0,cameraRot.eulerAngles.y,0)) * new float3(0,0,1) * Input.GetAxis("Vertical") * 3,
            space = Input.GetKeyDown(KeyCode.Space),
            physicsWorld = physicsWorld,
            filter = new CollisionFilter {
                BelongsTo = ~0u,
                CollidesWith = (uint)(1 << 0),
            },
            cameraRot = cameraRot,
        };
        var newDeps = JobHandle.CombineDependencies(inputDeps, World.Active.GetExistingSystem<Unity.Physics.Systems.BuildPhysicsWorld>().FinalJobHandle);
        var handle = job.Schedule(this, newDeps);
        handle.Complete();
        return handle;
    }```
#
    struct MoveJob : IJobForEach<PhysicsVelocity, Translation, Rotation>
    {
        public float3 horizontal;
        public float3 vertical;
        public bool space;
        bool hit;
 
        [ReadOnly]
        public PhysicsWorld physicsWorld;
        public CollisionFilter filter;
        
        public Quaternion cameraRot;
        public void Execute(ref PhysicsVelocity velocity, ref Translation translation, ref Rotation rotation)
        {
            rotation.Value = Quaternion.Euler(new float3(0, cameraRot.eulerAngles.y, 0));
            var rayInput = new RaycastInput();
            rayInput.Filter = filter;
            for(int i = -1; i < 2; i+=2)
            {
                rayInput.Start = new float3((float)i / 2,0,0) + translation.Value;
                rayInput.End = new float3((float)i / 2,0,0) + translation.Value + 1.1f * new float3(0,-1,0);
                hit =  physicsWorld.CollisionWorld.CastRay(rayInput);
                if (hit)
                {
                    break;
                }
                rayInput.Start = new float3(0,0,(float)i/2) + translation.Value;
                rayInput.End = new float3(0,0,(float)i/2) + translation.Value + 1.1f * new float3(0,-1,0);
                hit =  physicsWorld.CollisionWorld.CastRay(rayInput);
                if (hit)
                {
                    break;
                }
            }
           
            if (space && hit)
            {
                velocity.Linear = new float3(velocity.Linear.x, 6, velocity.Linear.z);
            }
            velocity.Linear = new float3(vertical.x, velocity.Linear.y, vertical.z) + new float3(horizontal.x, 0, horizontal.z);
        }
    }```
#

I believe that it's being caused by this

#

And maybe specifically trying to raycast

gritty grail
#

Well I guess it isn't specifically due to raycast, nvm.

gusty comet
#

Does raycasting work at all

#

every time I try no matter how much I strip down, I just get an assertion failure in my console and all my entities break

#

following the code from the docs, not that that's ever a great idea lmao

gritty grail
#

idk, my project is straight up broke now

#

👀

#

I might try to redo it

#

And try to pay a bit more attention to what's causing my issues

gusty comet
#

So what happened to project tiny? I cant find it in any project manager

#

@gusty comet seems like this

#

thx! I wanted to see how they handled animation/events

#

oh thank god I got raycasting to work at least outside of a job

#

it is possible

#

btw, remember that you can actually download the megacity project files for you to mess around with

#

kinda sworn off of downloading unity projects since I've yet to get one that isn't very crashy/actually plays

#

I personally really want to look into that streaming code

gritty grail
#

Well you can get raycasting to work in a job

#

I made a tutorial on it on YouTube if you want me to share it @gusty comet

#

Just the issue is the errors you get every once in awhile :??

gusty comet
#

consistent array slice errors

gritty grail
#

yeah

gusty comet
#

sure I'm interested

gritty grail
#

and other errors

#

Not a great tutorial but hopefully it works for you

gusty comet
#

PhysicsWorld.FinalJobHandle looks like the magic bit

#

thanks dud i'll try it out later

gritty grail
#

Yeah

#

You need that

gusty comet
#

Can I make a component hold references to entities of a certain Archetype?

gusty comet
#

Agh now CollisionFilters are giving me hell. Am I right in thinking that, in order to hit only colliders who belong to layer 8, 1u << 8 in the BelongsTo and ~0u in the CollidesWith fields would be the correct values? I've tried just adding 8u in as well, assuming the filter works in the inverse, but no matter what I always get back something on layer 7 😩

#

The RaycastHit is definitely giving me the right colliders w/ their filters because turning on unsafe code and dereferencing the pointer to the collider returned gives the correct looking mask :v

gritty grail
#

why do you do 1u?

#

unless it's the same thing as saying

#

(uint)(1 << 8)

#

Also

#

when you say ~0u for collides with,

#

It will collide with everything no matter what

#

BelongsTo says what kind of collider it is

#

You should make it the raycast collider

#

and the CollidesWith should only collide with whatever layer 8 is.

#

And I believe you have to make sure your other colliders in the physics component does not collide with your raycast if you don't want it to

#

so it has to be set up both ways

#

@gusty comet

gusty comet
#

1 << 8 shifts the integer 8 against the integer 1, and then you're explicitly casting it to an unsigned integer

#

1u << 8 left shifts the int literal 8 against the uint literal 1, returning a uint

#

fully defined in C# afaik

gritty grail
#

I mean that's how they showed it in their examples

gusty comet
#

anyway so what you're saying is the raycast is a collider unto itself, and the filter actually acts as the raycast's "belongs to" and "collides with" properties?

gritty grail
#

yes

gusty comet
#

from the docs it implies those are masks used to calculate which colliders to consider

#

just like Unity's old raycasts

gritty grail
#

Yes.

#

So BelongsTo says what collider the object is

#

and CollidesWith says what colliders the object will collide with

gusty comet
#

I'm aware of that

gritty grail
#

Well what you said you did looks incorrect

gusty comet
#

in what way

gritty grail
#

1u << 8 in the BelongsTo and ~0u in the CollidesWith fields would be the correct values?

#

If you have the collideswith set as ~0u it's going to give you layer 7, and every other layer for that matter

gusty comet
#

yeah so, I want to filter by colliders which:
Collide with everything ~0u
Belong to layer 8 1u << 8

gritty grail
#

Well what are you trying to do exactly?

gusty comet
#

exactly that

#

filter out colliders which do not belong to the layer 8

gritty grail
#

So you only want the raycast to say true if it collides with layer 8 specifically?

gusty comet
#

exactly

gritty grail
#

CollidesWith needs to be (uint)(1 << 8) or however you wanna do it

#

not ~0u

gusty comet
#

collideswith?

#

nono

#

i want BELONGS to layer 8

#

not collides with

gritty grail
#

well what is layer 8?

#

You're saying that the raycast belongs to layer 8

#

and you're also saying that the raycast can collide with all layers

gusty comet
#

You're saying the raycast belongs to layer 8

#

if that were true

#

it wouldn't be named "filter"

#

nor would the docs mention it functioning the same as Unity's old layerMask in a raycast call

gritty grail
#

Well my code works exactly the way I've described it

#

So you should give it a try and see if it fixes the issue

#

Set BelongsTo to the raycast layer, and the CollidesWith to layer 8

gusty comet
#

good lord

#

welp

#

if i had a hat i'd eat it

#

it works :v

#

on one hand, thank you
on the other, I have never hated Unity's documentation and naming conventions more in my entire life

gritty grail
#

you're welcome

radiant sentinel
#

Hello, why unity dots physics collision detection is fast at server mode? How can i fix it?

dull copper
#

you mean that the simulation itself runs fast?

tawdry tree
#

That wouldn't be an issue, now would it?
At least, I'm pretty sure you wouldn't complain about having too much perf if you're using DOTS

radiant sentinel
#

@tawdry tree , @dull copper
Im add velocity to tank shell and i expect the bullet to move slowly and collision to target, then i remove bullet.
But when i spawn bullet, it will be destroy on start . because the bullet collids the wall. I lost animation of movement over velocity.
When i remove the wall, bullet will be destroy on timer.

#

Sry for my English , im new at English

tawdry tree
#

Are you using deltaTime?

radiant sentinel
#

I cant, because velocity movement system writen in unity physics package

tawdry tree
#

Oh yeah, still that issue.

#

Are you still using this code?

physicsVelocity.Linear += inputs * tankMovementData.Speed * DeltaTime;
#

Because here you ADD to the velocity, every time the system runs
That means it will go faster and faster with every frame.
And when you build the game, it can get really high FPS.

radiant sentinel
#

No , thats code of my tank
Bullet velocity has been set on start and there is not any update loop

tawdry tree
#

Hmm

#

Can you share the line that sets the velocity?

radiant sentinel
#

Yes

mint iron
#

perhaps the collider of your wall is wrong - if bullet is colliding with it the moment it spawns, or colliding with something else? tank?

radiant sentinel
#

@mint iron i have filtered collid of tank, and checked the collision position. Thats on wall

#

I think the problem come from server build, thats so fast

#

I have not any problem on editor

tawdry tree
#

What happens if you set the velocity to 0?

#

In that case it should not move, and thus not hit the wall.

radiant sentinel
#

@tawdry tree yes, thats hit ground on start, and if i remove gravity, bullet destroy by timer

analog beacon
#

scary profile pic...

radiant sentinel
#

Me? @analog beacon 😂

analog beacon
#

I have a fear of clowns and that looks disturbingly close to one

tawdry tree
#

Then it sounds like your calcs for the 'force' variable does something odd. That or the vector/matrix math. And I'll have to admit once we got to that in school I was really happy I didn't do a more math heavy course.

radiant sentinel
#

I just uploaded random pic for profile @analog beacon

#

@tawdry tree i should test simplest example on empty project, but i think thats unity physic package issue
And i can not fix

tawdry tree
#

Can you somehow get the value of the forcevariable in the build? To see if it does something weird?

radiant sentinel
#

Force or hit position ? @tawdry tree

tawdry tree
#

The force variable, second line in the image you sent

#

Since it seems like the issue is velocity, which derives from that variable.

radiant sentinel
#

@tawdry tree ill receive force from client in byte type.
It is clamped between 15 and 30

tawdry tree
#

Have you verified that to be the case?

#

And have you made sure that's the case in the editor?

radiant sentinel
#

Im clamping currentforce on network manager and i have tested on editor i can send video that showing how its work

#

Im share video on two states , please wait to record

tawdry tree
#

First impressions: This seems to have something to do with headless (no-GUI) mode. Do you get the same result if you build non-headless?
So what happens is that it instantly detects a collision where there should be none, it didn't seem to move faster or anything.
it could be incompatibility between headless mode and DOTS physics

radiant sentinel
#

@tawdry tree work correctly on non-headless. thats mean i cant use this physic for bullets?

tawdry tree
#

I don't know, you'd need to get answers from someone more well versed in headless and/or DOTS physics. I'd advice you to create a bug report/help thread stating that, using DOTS physics, you get different results in headless and non-headless mode.

radiant sentinel
#

ok thanks

pliant pike
#

is there not an entity count or component count(total sum not individual) method for the EntityManager?

#

nevermind it doesn't really work when I use the EntityQuery.CalculateEntityCount() anyway

mighty violet
#

After adding hybrid renderer I get this Library\PackageCache\com.unity.rendering.hybrid@0.1.1-preview\Unity.Rendering.Hybrid\LightConversion.cs(101,63): error CS1061: 'HDAdditionalLightData' does not contain a definition for 'customResolution' and no accessible extension method 'customResolution' accepting a first argument of type 'HDAdditionalLightData' could be found (are you missing a using directive or an assembly reference?) and a similar one about contactShadows. I use 2020.1a9, HDRP 7.1.2, Entities 0.1.1 and Hybrid Renderer 0.1.1. Anyone knows of a fix for this?

#

this came up like a week ago too with no solutions then :/

radiant sentinel
#

@pliant pike check entity-debugger and your EntityQuery

pliant pike
#

yeah I checked it, its 0 at the wrong time, I need a whole different way of initiliazing a blob after some GO's are converted to entity's

#

or maybe I just use the Enityquery-count to do the whole check 🤔

dull copper
#

@mighty violet recent 2019.3 beta HDRP's are not supported by the current Hybrid

#

would expect a fix on future hybrid releases, considering Unity itself is using hybrid + hdrp with 2019.3 on their dots shooter

#

so at very least, we should get fixed package for 2019.3 release or so

#

of course you could manually fix the API change too

#

or take 7.1.2 from github and revert the commit that changed to the new API on HDRP

mighty violet
#

@dull copper thanks for the advice, I downgraded to 7.0.1 and it doesn't have the API mismatch so I'll stay there until there is a new version of hybrid

gusty comet
#

Where is it possible to define entity archetypes? Just when you do the entity creation? Can I define archetypes in an external file and access them later?

stable fog
#

as far as I can tell yes, to the 2nd question

#

I've been building a little archetype tool for myself to build different entities rather than having to code them

#

since all the behaviour is automatic when you create the entities, I just have a behaviour with an IComponentData[] (among others) to define an entity with

#

with [SerializeReferece] and UIElements you can something fairly comprehensive

#

ECS is really well suited for this approach tbh

shut python
#

Hey guys, would someone mind telling me how to deal with the rigidbody when converting the GO to an Entity? So this is obviously not working

    private Rigidbody2D rigidbody;

    private void Awake()
    {
        rigidbody = GetComponent<Rigidbody2D>();
    }

    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        dstManager.AddComponentData(entity, rigidbody);
    }```
tawdry tree
#
  1. There is no 2D support (the Xyz2D classes) in DOTS physics. (can still use 3d in 2d ways)
  2. Conversion of those should be automatic
    Do you have the DOTS physics package installed?
shut python
#

@tawdry tree yes I do

#

@tawdry tree so after attaching the rigidbody2D to a GO it should be converted automatically? And how would I access it within a system?

tawdry tree
#

Pretty sure you can't use the 2D components for conversion.
Conversion of the physics stuff should be automatic the same way MeshRender/RenderMesh and the transform is.

#

I think you need to use a normal rigidbody, but constrain it to be unable to move on the Z axis.

shut python
#

thank you very much. But when I use the rigidbody I get this error The type 'Rigidbody' must be a non-nullable value type in order to use it as parameter 'T2' in the generic type or method 'IJobForEach<T0, T1, T2>' [Assembly-CSharp]

tawdry tree
#

You need to use the relevant entity component, which I do not know the name of. I suggest finding a relevant sample or a tutorial.

#

Is this your first attempt at ECS?

shut python
#

yes

#

I wanted to start off with a simple movement

tawdry tree
#

Involving physics will complicate things, so if you want to learn ECS it will probably be easier to start off with just 'ECS' and self-coded logic. You can have motion without physics, you know.
The space shooter type of game is fairly simple and can be done with just ECS (and self-implemented bounding-box 'collision'). I'm not sure if it's the best place to start.
I very much recommend watching a few videos, including this one (https://www.youtube.com/watch?v=KuGRkC6wzMY) which is about 'communicating' between entities/systems.

Interaction is fundamental in games, both in how players interact with a game and receive responses, and in how parts of the game interact with one another. ...

▶ Play video
shut python
#

ye I started learning Unity DOTS with this video

#

seems to be the newest one

tawdry tree
#

If you're used to object-oriented programming, the mindset really is the hardest part. So many things you're just used to/take for granted that's wrong or just suboptimal in ECS.

#

A simple roadmap to learning the basic could be:
Set up basic scene in gameobjects, which converts to ECS
Add simple movement to some entities (move along some axis)
Create a player-controllable entity
Add logic to the movers, such that they move towards the player
Add shooting for player
Implement a simple 'collision' system which detects if player bullets overlap enemies, or enemies overlap player
And then you have 90% of a simple shooter kinda game. Limit movement to the 2D plane, and you got a shoot-em-up.

shut python
#

hm yes

#

was hoping to do it with DOTS only 🙂

tawdry tree
#

It will be much easier to reason about things (and ask for guidance or help) once you 'get' the basics (conversion, simple systems, probably the 'communication' between entities/systems mentioned above). I'm about to head to bed, so I'm probably not gonna be able to help you any more than that, but while not always busy, this channel tends to be helpful 🙂

shut python
#

thanks

vagrant surge
#

about the mindset

frosty siren
#

What is the equivalent of Quternion.Lerp() in Unity.Mathematics?

#

i see that in math there is Lerp for float4 and quternion can be assigned by float4. Is this a valid approach to do Lerp?)

frosty siren
#

And also now i understand that i see no Quaternion.Angle analog in Unity.Mathematics

gusty comet
#

math.mul can do a whole host of operations on different data types irt angles/rotating quaternions

#

you may also be able to do matrix/quaternion multiplication, i think thats what i did for a rotational lerp

frosty siren
#

thx. I found nLerp in math and mul in quternion

covert spire
#

Is there a way to get meshes working in jobs yet? Is the only current option still RenderMesh?

ebon lintel
#

What’s the best way to handle configuration data that’s needed by any/all systems that is loaded at runtime?

jade siren
#

Hi everyone. Which version fo Unity are you using?
I'm using Unity 2019.3.0a8 and everytime I install the "Entities" packages, i found this error:
Library/PackageCache/com.unity.burst@1.2.0-preview.6/Runtime/SharedStatic.cs(114,47): error CS0117: 'BurstCompilerService' does not contain a definition for 'GetOrCreateSharedMemory'

But seeing this changelog seems that my unity version does not support burst right?
https://docs.unity3d.com/Packages/com.unity.burst@1.2/changelog/CHANGELOG.html#111---2019-07-11

Thanks!

old pulsar
#

Anyone have an idea what the firstEntityIndex parameter of IJobChunk Execute() is about? Seems to be no documentation whatsoever.

mint iron
#

@jade siren shared static was added after that editor version, you'll have to use a newer editor build or an older burst version.

#

@old pulsar firstEntityIndex refers to the index of the first entity in the current chunk within the EntityQuery the job was scheduled with. For example, if the job operates on 3 chunks with 20 entities each, then the firstEntityIndices will be [0, 20, 40] respectively
from com.unity.entities@0.1.1-preview\Unity.Entities\IJobChunk.cs

gusty comet
#

Hi! How should I go about saving my ecs data into a file?

frosty siren
#

@gusty comet i searched forum a bit, and there is Unity.Entities.Serialization which contains SerializeUtility with SerializeWorld() and DeserializeWorld() methods.
Here is the thread with example code (but with some err issue) https://forum.unity.com/threads/serializeworld-deserializeworld-error.688156/#post-4603228

gusty comet
#

thx!

gusty comet
#

I have a BufferFromEntity<T> that I pass into a job - getting an error that it must be marked [ReadOnly]. I'm not really sure how to get around this problem as I need it indexed by entity. Maybe I should make a concurrent dictionary or something?

mint iron
#

can you paste the full error

gusty comet
#

Been reading, maybe this is a place to use [NativeDisableParallelForRestriction] InvalidOperationException: FillBuffersJob.Data.buffers is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.

mint iron
#

yeah exactly, its not safe by default for parallel so they stop you with this exception.

rugged wagon
#

Do I need to put the [ReadOnly]/[WriteOnly] attributes on any members of a job besides native collections?

#

I assume not since any other fields will be unique to each batch

gusty comet
#

If I remember right spamming [ReadOnly] on everything that you dont modify actually makes the jobs faster

tawdry tree
#

If you can guarantee you won't write, it can optimize for that

#

Similarly, if you somehow know you need never need to read, only write, it can optimize for that

#

If you have ever played with concurrency and threading yourself, you will likely have considered such things yourself: "Is it safe to send in this variable to that thread? But it's used over here, so if that changes..."
Locking things down drastically simplifies things without needing locks or potential deadlocks or race conditions.

rugged wagon
#

I figured anything inside a job besides native collections would be assumed readonly because they are value types and won't be shared across batches.

vagrant surge
#

@tawdry tree i wish i could do some of the stuff rust does or what the job system does on C++

#

of 100% banning accessing globals, only allowing whatever you input into the function

rugged wagon
#

Even if a *parallel for job did write to a field, different batches would never be writing to the same instance of the field right?

vagrant surge
#

thats what the "disableparallelforrestriction" is for

mint iron
#

i suspect it might setup schedule dependencies based on the safety read/write access so if you don't have [ReadOnly] on a collection and it knows there are already jobs using it, you might find that it gets delayed until they're finished. But i have no proof for that 😄

vagrant surge
#

it works exactly like that @mint iron

tawdry tree
#

The readonly/writeonly attributes are most definitely part of the sentinel and scheduling system

vagrant surge
#

the ECS library "specs" in rust does exactly the same thing

#

you need to declare which components (or singletons) you access on each system, and it uses that information (read/write) to schedule stuff

rugged wagon
#

I understand that it works that way on collections, I just didn't know if it applied to other stuff in a job like an int or float field

mint iron
#

i'm not aware of any special thing it does for random fields in the job struct, i think you're probably fine to leave them off; could check the generated burst assembly with/without and see if its the same? btw. unrelated, your deform library is super awesome thanks for releasing that openly.

rugged wagon
#

Thanks @mint iron 🙂

dry dune
#

how to query all entities that have no components?

#

right now figured out that when you remove last component on entity, this entity is not destroyed but continue to exist

vagrant surge
#

probably some sort of "orphan" type query

dry dune
#

also i wonder what is the use case when it may be useful?

mint iron
#

intersting

vagrant surge
#

placeholder for the IDs

mint iron
#

maybe an EntityManager.UniversalQuery -> IJobChunk with GetArchetypeChunkEntityType

dry dune
#

yes chunk iteration may work, but this pretty ugly way to iterate all chunks

fringe sinew
#

I've been wondering... C# can work with pointers under the unsafe code, yeah?

#

Is it possible to operate on pointers of a regular array in a job?

coarse turtle
#

it's possible, you might need need a NativeDisablePtrRestriction attribute in the job

fringe sinew
#

Does unity even allow the usage of reference types in NariveArrays?

vagrant surge
#

no

fringe sinew
#

So how am I going to operate on pointers then?

#

Or can I just operate on the default arrays?

dry dune
#

regular arrays stored in managed heap and may move in memory by garbage collector , native arrays in unmanaged heap what allow to use them in a job,
so if you need array in a job move you data to native array

hollow sorrel
fringe sinew
#

@dry dune I plan to have all of my jobs to be completed in a context of one function. There will be no time for GC to actually work.

dry dune
#

job is something that going to work on different CPU core outside your function

fringe sinew
#

Not necessarely. By forcing the job to be completed with JobHandle.complete() or by not running the job on another core entirely (using job.run) the job will be completed before a necessary point in the main thread.

worldly pulsar
#

The GC can be triggered from a different thread. If you want to use managed array pointers you have to pin them

low tangle
#

To work with pointers on managed arrays you need to pin then with fixed

#

byte [] a
fixed (byte* ptr = a)

#

Code on phones sucks

#

When you pin structs you need to use -> to access fields like cpp

#

a->speed

rugged wagon
#

I'm trying to calculate/draw lines between a NativeArray of points based on their distance from eachother. I got a crappy version working by looping over the points in an IJobParallelFor and testing the distance between the current point and all the others. If a point was less than some max distance away, I added a float4x4 to a NativeQueue that stored the transformation for a quad to connect the two points. Unfortunately the only way to draw the quads was to dequeue each matrix and draw it with Graphics.DrawMesh. I want to use Graphics.DrawMeshInstanced, but to do that I need a native array or slice of float4x4s so I can memcpy it into a managed Matrix4x4 array. NativeQueue didn't give access to an array. I tried using a NativeList, but from my testing you cannot add to it from an IJobParallelFor. Does anyone have any ideas on how to calculate and store the connections in a way that lets me efficiently draw them?

sonic oyster
#

Does burst work with addressables?

mint iron
#

@sonic oyster not really, its all classes. But you can store references in a native friendly form if you need to have them as part of a prefab. For example, use IConvertGameObjectToEntity to pass the runtime key from GameObject AssetReference into ECS. The runtime key is all you need to be able to load an asset from a system/entity prefab.

sonic oyster
#

I need to make a way to make modable mapgen

#

And its a struct with [BurstCompile] attribute

#

When i load it with codedom or roslyn dynamically the job works, but burst doesnt work on it.

mint iron
#

@rugged wagon you could try NativeStream - it can read/write in parallel and has an ToNativeArray() method.

rugged wagon
#

@mint iron Thanks, it looks like that could be the answer. Is there any documentation on it? Google has been struggling to find official info on the less common collections and I'm not seeing anything besides a single forum post

#

Ah it actually might not be the best solution if, to get the array, I have to allocate a new one. I wish it had some sort of AsNativeArray<T>() method. Looks really helpful for other stuff tho.

#

Could I get a pointer to the beginning of the stream and then memcpy the contents into a correctly sized native array? I don't really know how to use pointers so maybe that isn't possible idk.

coarse turtle
#

I think NativeStrean().AsReader().ReadUnsafePtr(int size) can work if you want to get the contents of the NativeStream

#

it returns a byte* so you can likely increment the pointer by its end offset and copy it to a destination

rugged wagon
#

Excuse my ignorance @coarse turtle , but what's the point of a size argument if the method just returns a pointer to a single byte? I don't know too much about pointers besides that they are addresses to a location in memory (sorry)

coarse turtle
#

so here's an example, let's say you wanted to store an integer as bytes towards an address

#

an int is 4 bytes, so you would split the integer into 4 bytes and store them sequentially to a byte pointer

#

so byte* intStart would store the address that represents your integer

#

and if you do intStart++ you can grab the second byte that represents the integer

#

so a simple way to grab the entirety of the contents of the pointers is

byte* some_pointer = some_int;
for (int i = 0; i < sizeof(int); i++) {
  some_pointer++;
  var segment = *some_pointer;
}
// Typically if you concatenate/serialize all the contents of the pointer you can reconstruct your original intended data type
rugged wagon
#

Very cool, thanks for the explanation! So incrementing a pointer moves it forward one byte in memory?

coarse turtle
#

yea

#

if it's a byte*

rugged wagon
#

So doing:

double* doubleStart;
doubleStart++;

Would move it forward the size of a double, not a byte?

coarse turtle
#

yeah the ++ operator on a pointer moves it to the next address

rugged wagon
#

Thanks again, I'll check it out. I cobbled some utility methods together a while ago for copying between native/managed arrays of normal math types and mathematics types so I bet I could convert them to copy between a native stream using the byte pointer.

// Copies a native float4x4 slice into a managed Matrix4x4 array. Array lengths MUST be the same.
public unsafe static void MemCpy(this NativeSlice<float4x4> source, Matrix4x4[] destination)
{
    fixed (void* managedArrayPointer = destination)
    {
        UnsafeUtility.MemCpy
        (
            destination: managedArrayPointer,
            source: source.GetUnsafePtr(),
            size: destination.Length * (long)UnsafeUtility.SizeOf<Matrix4x4>()
        );
    }
}
covert spire
#

Is it possible to call Graphics.DrawMesh from inside of a job?

safe lintel
#

i think only the mainthread

gritty grail
#

In general, what should I be handling in a job?

gusty comet
#

there's always going to be some overhead surrounding setting up multithreading

#

lots of math that happens very frequently, def going to benefit

#

small things not so much, if you're unsure you'd probably just have to profile it yourself to spot the difference, not that it's easy with the current tools at our disposal irt debugging

gritty grail
#

okay

gusty comet
#

What would be the standard on implementing animations on your 2D pure ecs game?

tawdry tree
#

Self-implemented something or other.
Can't be more specific because honestly I have no idea. You want to essentially flip through a number of sprites, so I guess some shader magic (on a spritemap) could do the trick? Outright swapping the texture sounds expensive, but doable.

gusty comet
#

Yeah, just looking for insight, atm what I have figured is swapping the materials maintexture but I have to admit I feel overwhelmed by it

tawdry tree
#

Have you done some google-fu? I imagine at least one obscure coding-blog has written about doing pure ECS 2D animation in Unity.

gusty comet
#

Been going at it. Guess it's time to keep with the google-te

coarse turtle
#

for 2D animations what I do is

#

CommandBuffer + custom quad + array of texture frames (this usually lives in a blob array)

#

with small pieces of animation info like playback context, playback rate, which frame of the animation to use (assuming its a sprite based animation and not IK)

#

Effectively all you're doing from a component system is filling up the command buffer with material property blocks so you can change the texture every set frame to animate your sprite

safe lintel
#

guy posted the sourcecode too

#

i followed the tutorial, but if you dont go the custom shader route(which is incompatible with the renderpipelines) I think you're limited to using just drawmesh instead of drawmeshinstanced and the limits are a bit poor by ecs standards, i think at 1000 sprites is where performance drops off for me

#

guessing this all changes when the next entities package is released, supposed to have support for materialproperty block changing? drums fingers

low tangle
#

I need that update so bad

tawdry tree
#

poor by ecs standards

1000 sprites is where performance drops off

Isn't it lovely to be in such a situation, though? And with the reasonable expectation that you can improve upon that, as better support arrives?

low tangle
#

for sure

compact hound
#

How do you think - it is ok to make separate systems for every character ability even if they have something in common? I don't have other idea but this will provide some duplicated code.

deft niche
#

Wasn't the new update supposed to be out like last week ?

safe lintel
#

yes 😬

tawdry tree
#

El, That sounds highly redundant. If nothing else, put reused code in helper/static classes/jobs/base systems(inheritance).
My instincts say that making systems, especially if they do similar things, is not proper ECS, though.

vagrant surge
#

@tawdry tree static methods are completely fine and very recomended

tawdry tree
#

Think about your data, and your behavior, and what is general and shared. You can probably make a neat table of "this ability does X+Y, that ability does just X, this one does X+Z, that one just G, etc" Damage, for example, is likely to be very common.

#

I meant that making systems for every kind of ability sounds not ECS, not statics (edited comment for clarity)

vagrant surge
#

making systems for every ability is actually a thing do. I did something similar on my end for a spell system

#

different "parts" of the spell was in components and you could compose things dynamically

tawdry tree
#

That's one system for each component or set of components, though. Not for the abilities themselves, which under ECS, is purely 'subjective'/not real (ie. exists not in the pattern, only in the experience of the users)

vagrant surge
#

ah true. In my case the spells were a template i would "spawn", and then their components do stuff

#

mostly done for projectile type spells, which was what the system was created for

#

tho you could do stuff that wasnt projectiles by doing stuff like adding auras in AOE or auto-attaching to stuff

compact hound
#

The case is that, i have ship with weapons

  • front cannon - with one bullet spawner
  • side cannon - with multiple bullets spawners on both sides

Player shots with selected weapon. For front cannon is easy just spawn bullets from spawners.
For side cannon is more complicated, because i would like to shot from this side (subset of spawners) where closest enemy is.

For now I have only system that spawns bullets from all spawners within weapon. And thinking now where to apply that logic to spawn only from subset of spawners.

vagrant surge
#

you add that to the spawners themselves

#

the "tracking" spawners have a component to do the tracking

#

and to select which of all the spawners actually shoot, thats something you do from the logic of the Ship itself

tawdry tree
#

If you analyze most RPG abilities, they tend to be some combination of damage/healing, status effects, AoEs, and creating projectiles (or other objects) that apply those. Depending on the game, you might also have IFF/target selection (can or cant target this or that)

vagrant surge
#

@compact hound for a complex multi-object stuff, its best to have something set as "brain"

#

and the other stuff is just dumb stuff

tawdry tree
#

+1 to that

vagrant surge
#

for erxample the front cannon

#

is just a BulletSpawner that has Active component

#

and the side cannons are BulletSpawner + Active + Tracking

#

the "brain" on the ship itself sets/unsets the Active component to turn the spawners on and off

#

and also sets the tracking target on the side cannons

tawdry tree
#

Make a system where each cannon can have stats(components) and something to trigger a system to do the thing (ref. the entity interaction Unite talk)

#

The brain vblanco talks about would be what does the interaction here, triggering the others

vagrant surge
#

something i implemented in my own ECS shanenigans on C++ is a way to send "events" up and down the entity parent chain

#

and utility stuff like "FindComponentInChildren"

compact hound
#

i have currently on ship entity

  • inventory that holds selected weapon
  • dynamic buffer of weapons (front cannon, side cannon)

Weapon have

  • Weapon
  • dynamic buffer of spawners

On player input i put shot component on selected weapon, and shooting system spawns bullets from all spawners

vagrant surge
#

seems good

compact hound
#

but im struggling where to put this side cannon logic to spawn only on some of the spawners

vagrant surge
#

no issue, you just add the whole "tracking" thing on the spawners

tawdry tree
#

Could put on a component to group them, and have the brain make only one group fire at once. That could also scale up to something bigger, like a large, say, hexagonal enemy station.

vagrant surge
#

well, thats what the Weapon is, no?

#

i think he has 3 levels of hierarchy

#

Ship -> Weapon -> Spawners

compact hound
#

spawners could have something like LeftSide, RightSide to group them

vagrant surge
#

that Side stuff is not something you normally put in components

#

in fact, those spawners dont really need data

compact hound
#

but shooting system should have if logic to determine that?

vagrant surge
#

that data can be stored in the weapon

compact hound
#

weapon don't have link to spawners, entity holds dynamic buffer of them

safe lintel
#

does Used By Systems in the EntityDebugger actually show useful info? I dont fully understand as it seems like it just shows every system

vagrant surge
#

then add it. A weapon should hold link to its spawn points, no?

compact hound
#

system takes weapon, and dynamic buffer of spawners, but even if i add some list to weapon component then what? Multiple lists for each side? But simple front cannon dont need it

coarse turtle
#

@safe lintel honestly, I dont really use the Use By Systems in the Entity Debugger 😐 Also I think there's just too much to scroll through when you do see a system

tawdry tree
#

What are we even looking at?

#

Also, quick, restart before it spreads!

safe lintel
#

@coarse turtle yeah trying to nail down usage of a particular entity and Use by systems seems rather useless

coarse turtle
#

Yea the filters are way more useful on the system side and the entity side

compact hound
stable fog
#

how are you setting that up btw?

#

is that jsut a monobehaviour witha bunch of specific components on it?

compact hound
#

i convert if from MB

vagrant surge
#

@compact hound have all that whole "side weapon" stuff on the Weapon

#

nvm you already have that

compact hound
#

I think i will just add side tag on spawners and add if on shooting system. Don't have better idea for now

frosty siren
#

I'm totally confused about collision filter in Unity Physics. I call distance query to find all entities with specified type in some area. And i have 2 physics category names that i added (A and B for example). I tried set any variants in input of CalculateDistance() method and of collision filter on entities, but all i got is strange errors like
IndexOutOfRangeException: Index 1768838447 is out of range of '5' Length in Library/PackageCache/com.unity.physics@0.2.4-preview/Unity.Physics/Collision/Geometry/BoundingVolumeHierarchyBuilder.cs:571
and
TypeLoadException: Recursive type definition detected

tawdry tree
#

The collision masks should be bitflags, I believe, so you need to use bitwise operators (<< and >>?) on them if you calculate that. Haven't use DOTS physics myself yet, so I dunno.

frosty siren
#

Yeap, i understand bitmasks. For example, if i set my custom "Layer" in 2nd position (in unity physics it's Category names) and i want to collide with it i need to set 2nd bit to 1. So if i want to collide only with my custom layer i can use 2u value, which is already result of 1 << 1 (am i right?).

But in unity physics package we have "belongsTo" and "collidesWith" masks which aren't clear for me

tawdry tree
#

1768838447 does not sounds like a bitmask made from a couple categories, but I might be misinterpreting the error.
BelongsTo -> which catergory(ies) to do I belong to
CollidesWith -> which category(ies) do I collide with

#

Say you have Default, environment, player, creatures.
Player belongs to Default, Creatures, Player, collides with default, world, creatures
A trigger for player could belong to nothing, collide with player
Static map belongs to environment only, no collides
Dynamic map (falling stones, logs) belong to default, environment
Enemies are default, creatures, collide with default, environment, creatures
Something like that?

#

Essentially, you can have one-way detected collisions. I assume you need the collidesWith flag to be affected by anything in that category.
Say you have two rolling balls, A and B, each with their own category.
They are similar in weight and stuff, and are rolled towards each other.
If either does not collide with the world, it will fall through
If neither collide with each other, they pass through each other
If only one(A) collides with the other(B), presumably A will be affected by B's inertia, but not the other way

#

At least, that's what I'm assuming. Pretty sure sparse use of the flasgs can help perf. The primary is just to not put anything where it doesn't need, for belongsTo, though. Other than that, you could just use masks based on what they belong to? 🤷

gusty comet
#

Has someone here experimented with distance calculations in Unity.Physics already? If so, did you figure out what the rigid transform is for in the ColliderDistanceInput? Is that the transformation from one collider CS to the other's?
And is there already a convenient method for generating Physics.Collider data from UnityEngine.Colliders?

gritty grail
#

Should I conform everything that I can to readonly or writeonly in a job?

#

For instance, ```csharp
struct CameraSystemJob : IJobForEach<Translation, Rotation>
{
[ReadOnly] public float3 playerPos;
[ReadOnly] public float mouseX;
[ReadOnly] public float mouseY;

    [BurstCompile]
    public void Execute([WriteOnly] ref Translation translation, [WriteOnly] ref Rotation rotation)
    {
        translation.Value = playerPos;
        rotation.Value = quaternion.Euler(new float3(0, mouseX, 0));
    }
}```
#

And what kind of benefits does doing this provide me if I should?

safe lintel
#

it helps the system scheduling, i dont think its necessary on playerPos/mousexy unless they were nativearrays or componentdata etc
in my luddite understanding, if it knows multiple systems can read from and not need to write to a particular query, it can parallelize some of that work, if they all needed readwrite then you may have systems waiting on other systems to complete their workload and not as fast as it could be(though its unavoidable, if you can help it out here and there you can squeeze out as much perf as possible)

gritty grail
#

So there's nothing wrong with adding it there necessarily?

#

I really wish there were a way to fix these errors

#

I have to restart runtime everytime they show up because my player phases through the ground when these show up

#

and I might have to restart 6-7 times before it runs okay

rare umbra
#

Is the new Entities package out yet?

deft niche
#

no.. 😦

old pulsar
#

yeah, I'm unclear on how WriteOnly benefits scheduling. In what scenario does writeonly permit concurrency where default readwrite does not?

untold night
#

WriteOnly is only there for completion, as it's implicit if ReadOnly isn't used

#

Like there's no point to actually marking things WriteOnly, just ReadWrite (no attribute) and ReadOnly

quaint snow
#

Hello Everyone!
Quick Question.
What is the best Approach to WriteOnly to the same DynamicBuffer from multiple systems?

pliant pike
#

@quaint snow to not do it or make sure the systems never run at the same time?

quaint snow
#

Hi @pliant pike ,
the perpose of my question is i dont want to lose performance by making my systems run in synchronously.
my first opinion about this is creating a NativeContainer which support parallel writes for each system and then collect them from another system at the end.
I also thought about creating entities that Handle the data to be buffered, then collect them and put them in the dynamic buffer after all systems concerned.
but this will prevent me from using burst and even worst ill create sync points by creating entities and adding those Datas.

pliant pike
#

I dont understand what exactly you are doing, do you mean a single job system run on multiple threads or multiple job systems, because you can do it multithreaded on a single job system

#

you just have to make sure the dynamic buffer wont be accessed from multiple threads, like I have entity's which have buffers and the job only works on that entity's buffers so its all self contained and doesn't result in race conditions

quaint snow
#

in this case i think i just have to declare my jib as unsafe.
but in my case im there is possiblity of race conditions.
im accessing the same Dynamic Buffer from Multiple Systems

pliant pike
#

yeah I dont think its even possible to write to a nativearray at the same time with multiple jobs safely

quaint snow
#

NativeQueues are thread safe.

#

but im looking for a better approach :p

gusty comet
#

Should I split the overworld input? Do I un-singletonize it=

slow epoch
#

That depends on how huge overworld input is gonna be

#

And if there is gonna be other class input

gusty comet
#

atm it's just two bools and a moveVector

#

the two bools are quite unrelated to the moveVector so I'm gonna split it up either way

slow epoch
#

Yeah i would split it up and just set to the job the bools directly

civic glen
#

An I doing something wrong? Everything is fine in play and editor but when I build the game every entity has it's transform reset to zero

#

New project, create cube, convert to entity then build and it always resets

gusty comet
#

no idea

#

Are you making sure you have the package for your target platform when building?

civic glen
#

Ah. Prob not.

#

I thought that was only for non standard platforms

#

Did not realize there was a windows and Linux one. I'll try that when I get back. Thanks

safe lintel
#

i dont believe those do anything yet.

#

the transform zero is a bug, if you try disabling srp batcher it might fix it, otherwise the fix is either in an upcoming entities release or unity release but neither are out yet

gusty comet
gusty comet
#

Is hybrid renderer required for ECS? Because I'm sorta at a standstill on coding more of my game until it works (if it's required). I'm on 2019.3.b7

safe lintel
#

no

gusty comet
#

What's the hybrid renderer for then? The description says its used for drawing meshes using DOTS... How does it make an entity and a visible mesh without it?

safe lintel
#

well you would use old gameobjects for your rendering representation. if you need a pure ecs entity rendered without gameobjects then the hybridrenderer would be required for you