#archived-dots
1 messages · Page 77 of 1
Alternatively i tried to append to a dictionary with the data value as a lookup key such as
public Dictionary<vector3, Entity> entityDict= new Dictionary<vector3, Entity>();
if (entityDict.ContainsKey(vector3)) // Error occurs
if (animalAreaDict.TryGetValue(pos, out Entity retVal)); // Alternative lookup also causes error
but im constantly getting a Object reference not set to an instance of an object and cannot figure out why. I have other dictionaries of the same structure except they dont cache Entity types.
@odd bay There needs to be a LinkedEntityGroup referencing the children on the parent for it to work like you expect. There's a function to create a linked entity group from the hierarchy during conversion. ConversionSystem.AddLinkedGroup or something. Call it on the parent GameObject and it creates a proper link with children.
If it has a LinkedEntityGroup it will automatically destroy/insantiate the children when you destroy or instantiate the parent
Ok so if I instantiate an entity through script it deletes the children when you delete the parent, but it doesn't if you do attach a convert to entity monobehavior in the gameobject view
@low tangle are you about?
@me if you see, i tookvyour advice and rebuilt it into four systems wondered if you'd mind having a look for me?
RELEASES EXCLAMATION OF EXTREME RELIEF!!!!!!!!
Its working... Turns out... it was working all along. beats head against wall The problem was an incorrectly set hardcoded forward vector. It was giving up, not forwards... now its working. i think... it jsut started being wierd again >:(
Anyone know how to draw a debug line in ecs? Im trying to do it in a component system, but isnt working....
my bad being dumb again hehe
That's excellent
I think I'm blind but I couldn't find a way to have collision callbacks like OnCollisionEnter
How do I do that?
@low tangle not so great, it seems itruns fine, then it goes haywire :(
It makes it to the first position, then it just begins to go crazy.
Crazy... whilst i was watching it flew to the first point, then went off on a wander... then out of the blue went back to moving around properly...
i think someone has sneaked some booze on board the lil spaceship.
lol
can you show me what it does, then show me some of the code for turning?
sounds like its getting close but trying to go very small tolerances
ok
so if you boosted the radius of close enough to target it might calm down
or snap when close enough to exact target which is roughly the same
trying to get a good video a sec
Atm, its seeming to get to the first one then failing to turn around, but i cant see why cos its reading the angles and it should be setting the thrusts to max to turn around... but it doesnt.
I had a kind of forced turn put in there, which then managed to get it to turn around after going nuts for a while but then it seemed to spot the target again and go after it, even turned around to a third target, but then went back to the craziness.
maybe negatives in thrust, or maybe euler angle gimble lock?
Not sure, ill show now.
please take note you may wish to turn the sound off
i didnt remember i had music going till after id recorded hehe
This video has the dot product related manual 180 turned off
this one has it turned back on.
Its recalculating the eulers from the quaternions each frame - in all this, there should never be a euler more than about 30 degrees in play, the eulers are used to create a quaternion that represents this frames rotational velocity
@safe gate If you mean for the new unity physics it's possible but very awkward and error prone right now
https://forum.unity.com/threads/unity-physics-discussion.646486/page-3#post-4348861
I mean, I just want to know if the bullet has collided with something
And if it has, which entity was it
So I can damage the enemy/player or destroy the bullet if it is a wall
Maybe then each bullet could be constantly raycasting to see if it hits something?
Thats a common method, gregorio. You can raycast to the intended move position for this frames bullet movement, and if it hits, move the bullet into contact instead, a good way to avoid misses due to going right through the target in one frame.
Im not sure how easily it can be done in ecs tho
I took a glance at raycasting and it looks straight forward
All I want to do is constantly raycast and if it is really close, like 0.01 close, I consider it collided
Because bullets are going to be triggers they can overlap enemy colliders, is there any way to know if they are overlapping?
@zenith wyvern how are you check the spheres collision on the example you posted the other day?
I think all the relevant code is in the post I made
It's just a system that runs through entites with a "collider" component and does a sphere-sphere collision check based on a radius value
In my case the collider component is literally just:
public struct ECSCollider : IComponentData
{
public float radius;
}
So you are doing all by yourself, not using UnityPhysics?
I saw it now. I think that for my case raycasting would be easier
Here's a post with an actual practical example of someone doing collision response with UnityPhysics
But like I said it's very awkward right now
They are working on making it better
I guess I'll stay with raycasting. I don't need complex collision detection right now
How optimized and lightwheight are raycasts?
If you use https://docs.unity3d.com/ScriptReference/RaycastCommand.html it can be very very fast
But I'm using the new ECS physics
Entities 33 just released
Is it a hotfix for 32 or big release?
We released a new version of the dots core packages. This release was mainly focused on fixes and stabilisations, so no new Samples this time. Available via the Package Manager for Unity 2019.1 (and newer).
Well that was a painless upgrade
@zenith wyvern Did you get your collision system working? I think I saw some code from you but had to go away and did not comment
Nope, I'm still working on it. I think I'm misunderstanding how NativeMultiHashMap works, I'm just writing up some tests now so I can get a better understanding of it
If you need help, I did this a few months back (with AABB instead of Sphere)
same thing, spatial grid as broadphase and then brute force
You used nativemultihashmap?
I ended up using dynamic buffers, but I tested about 10 different approaches including NMHM
dynamic buffers were faster (in particular for many entities, as NMHM takes time to clear + values not accessible by index)
I thought about using it, it just seemed weird to try to apply what should be a fairly straightforward data structure problem and force it into ECS, but maybe it's the better solution since I'm not having much luck with MultiHashMap
I can help you with NMHM, but Dynamic Buffer is really the same thing, just more convenient. What is your problem with NMHM?
My only warning is that I did not use DOTS for the last 3 months and I am only familar with a now outdated API, but for NMHM nothing changed as far as I can tell
I insert like this:
struct BuildSpatialMap : IJobForEachWithEntity<Translation, ECSCollider>
{
public NativeMultiHashMap<int, Entity>.Concurrent spatialMap;
public void Execute(Entity e, int chunkIndex, [ReadOnly] ref Translation translation, [ReadOnly] ref ECSCollider coll)
{
float2 p = translation.Value.xy;
Utils.VisitGridIndices(p, coll.radius, e, spatialMap.Add, CellSize);
}
}```
And do checks like this:
```csharp
public void Execute(int index)
{
NativeMultiHashMapIterator<int> it;
Entity curr;
if( spatialMap.TryGetFirstValue(keys[index], out curr, out it ))
{
Entity next;
while( spatialMap.TryGetNextValue(out next, ref it))
{
var aColl = colliderFromEntity[curr];
var bColl = colliderFromEntity[next];
var a = posFromEntity[curr].Value;
var b = posFromEntity[next].Value;
// TODO: Collision flags
if( CircleOverlap(a, aColl.radius, b, bColl.radius ))
{
commandBuffer.AddComponent(index, curr, new CollisionTag());
commandBuffer.AddComponent(index, next, new CollisionTag());
}
}
}```
And somehow it misses entities. As far as I can tell all my entities are being properly inserted
VisitGridIndices:
public static void VisitGridIndices<TValue>(
float2 pos, float radius, TValue val,
System.Action<int, TValue> callback, int cellSize)
{
float2 p = pos;
int2 min = (int2)math.floor((p - radius) / cellSize);
int2 max = (int2)math.ceil((p + radius) / cellSize);
int count = max.x - min.x;
//Debug.LogFormat("Calling visit grid for entity {0}. Pos {1}, Radius {2}. Min {3}, Max {4}. CellSize {5}", val, pos, radius, min, max, cellSize);
for (int x = min.x; x < max.x; ++x)
{
for (int y = min.y; y < max.y; ++y)
{
int2 cell = new int2(x, y);
int hash = cell.GetHashCode();
//Debug.LogFormat("Inserting entity {0} at {1} hash {2}", val, cell, hash);
callback(hash, val);
}
}
}```
I think I might be iterating the cells incorrectly but I'm not sure
hang on a minute, I will take a look shortly --- or PM you later
No worries, if you need more context all the code is in my forum post: https://forum.unity.com/threads/jobsystem-not-working-as-expected.683419/
Ok great - I stumbled across System.Action callback & commandBuffer - without checking any logic, I dont thing you need this
How can I tag entities from a job without a command buffer?
I think my question is why would you tag them? But we can figure this out later - this might be required for your design
I think you can't add components without a command buffer on a job
Add component must be on the main thread
I tag them so another system can handle the actual collisions later, but yeah not really relevant to the my problem atm I think
Correct, but you could i.e. change a value of an ICD instead of tagging. As I said this can be dealt with later. Also all the colliding entities could be in a container, but that works better if it is processed in the same system. Tags might be legitimate
And regarding the System.Action, funnily enough that was less verbose than passing in the actual data structure
I will need to check the forum post to see full context. But can you assure that you assign to the spatial grid correctly?
And since I call that in a few places I need it in a function
As far as I know yes, I just divide the positions by the cellsize and do GetHashCode on the int2
what is the hash function? did you check?
No, but for testing purposes my cell size is large enough to encompass everything in a single cell anyways. I've verified from Debug.Log that everything is in the same cell
Although I did see that when I do GetKeys it returns a list with a copy of the same hash for every insert I've done
Which seems not right
That is what I'm working on figuring out right now
Let me dig out my function, using a NMHM
[BurstCompile]
[RequireComponentTag (typeof(SpriteTag))] // required, not scheduled with a component group
public struct SpriteToGridMultiHashMapJob : IJobProcessComponentDataWithEntity<Box>
{
[ReadOnly] public ColGrid grid;
[WriteOnly] public NativeMultiHashMap<int, CollisionInfo>.Concurrent entitiesPerGridMultiHashMap;
public void Execute(Entity e, int i, [ReadOnly] ref Box box)
{
var boxMinGrid = (int2) ((box.Center - box.Extends - grid.Min) * grid.OneOverCellSize);
var boxMaxGrid = (int2) ((box.Center + box.Extends - grid.Min) * grid.OneOverCellSize);
for (int x = boxMinGrid.x; x <= boxMaxGrid.x; x++)
{
if (x >= 0 && x < grid.Dim.x)
{
for (int y = boxMinGrid.y; y <= boxMaxGrid.y; y++)
{
if (y >= 0 && y < grid.Dim.y)
{
var key = x + y * grid.Dim.x;
entitiesPerGridMultiHashMap.Add(key, new CollisionInfo {entity = e, box = box});
}
}
}
}
}
}
note: my grid is flexible, that's why it's parameters are passed into the job
public struct ColGrid
{
public float2 Min;
public float2 Max;
public int2 Dim;
public int CellCount;
public float2 CellSize;
public float2 OneOverCellSize;
public ColGrid(float2 Min, float2 Max, int2 Dim)
{
this.Min = Min;
this.Max = Max;
this.Dim = Dim;
this.CellCount = Dim.x * Dim.y;
this.CellSize = (Max - Min) / Dim;
this.OneOverCellSize = 1f / this.CellSize;
}
}
from the look of it, I don't check collisions that are off screen | the check if x>=0 & y>=0
Looks like the same way I'm inserting my circles as far as I can see
yes, but look at my "hash" --- yours might be ok, but it's something I would check
I've verified all my entities are in the same cell so the hash isn't relevant - atm every collider is being inserted into the same cell. I believe I'm making a mistake in how I'm iterating the hashmap
That's what I will look at next, I need to see forum, as here I only see the Execute
want to see which job type you use
offline for 5 min sorry
No worries
Also since I made that post I followed Joachim's advice and I'm now running all my jobs with .Run like he suggested, and it's still giving me the same results
The idea was that I would do a parallelfor for each cell, I'm starting to see where I'm messing up though. I'm only testing the first entity in the cell against the rest and then bailing out. I want to test the first entity against the rest, then do the same for the next until I reach the end.
And the reason it appears to work in my other example is I guess by pure chance the "bigcollider" is always ending up as the first entity in teh cell
There are different approaches to overcome this, I guess I have tested them all
Here one example, but as I mentioned, Dynamic Buffers were most performant and I think I even have a better one for NMHM...it's just a long time and I forgot which one was better
public struct AABBCollisionNMHMtoNMHMJob : IJobNativeMultiHashMapVisitKeyValue<int, CollisionInfo>
{
[ReadOnly] public NativeMultiHashMap<int, CollisionInfo> entitiesPerGridMultiHashMap;
[WriteOnly] public NativeHashMap<int,CollisionPair>.Concurrent DistinctCollisionPairHashMap;
[WriteOnly] public NativeHashMap<Entity,int>.Concurrent DistinctCollisionEntityHashMap;
public void ExecuteNext(int key, CollisionInfo candidateA)
{
NativeMultiHashMapIterator<int> it;
CollisionInfo candidateB;
if (entitiesPerGridMultiHashMap.TryGetFirstValue(key, out candidateB, out it))
{
// advance to own position
while ( (entitiesPerGridMultiHashMap.TryGetNextValue(out candidateB, ref it)) && (candidateA.entity.Index != candidateB.entity.Index) );
// check all following for collision
while (entitiesPerGridMultiHashMap.TryGetNextValue(out candidateB, ref it))
{
var entityA = candidateA.entity;
var entityB = candidateB.entity;
var hash = Util.GetCollisionHash(entityA.Index, entityB.Index);
{
if (Util.IsColliding4(candidateA.box, candidateB.box))
{
var cp = new CollisionPair {EntityA = entityA, EntityB = entityB};
if (DistinctCollisionPairHashMap.TryAdd(hash,cp))
{
DistinctCollisionEntityHashMap.TryAdd(entityA, 1);
DistinctCollisionEntityHashMap.TryAdd(entityB, 1);
}
}
}
}
}
}
}
Ahh, I was wondering how you would reset the iterator, that is good to know
Also incredibly awkward
The output of this is
- NMHM with all unique collision pairs
- NMHM with all unique colliding entities (i.e. only counted once, even if involved in various collisions)
I will have to parse this to figure out how I can apply it in my case, it should save me a ton of trial and error though
Thank you very much for your help
My advise is dump it 😃 Create one entity for each grid cell (this becomes your "key") and attach to each of them a DynamicBuffer (this becomes your "Values). The nice thing is that you can clear very fast & interpret the buffer as an array (.AsNativeArray) at no cost.
If I do this again I probably will, I think it's valuable to learn the syntax and how to solve these problems with the NMHM as well though
Sure...good luck with it. NMHM is a valid approach, if you run in performance issues you can look into Dynamic Buffers
No worries, I will fix up my code and update my post at some point, thanks again for your help
Another approach is to just read out the NMHM in a job and save to list... (schedule various Ijobs in parallel)...i think they also introduced new API functions that allow you to extract all keys and values from NMHM (basically what i did manually before this existed) --- bye
Hi all, trying to do a IJobParallelFor job for a batched raycast. Its running but my results are returning all elements of 0,0,0 vector3 points. Any ideas?
[BurstCompile]
struct PrepareRaycastCommandsJob : IJobParallelFor
{
public NativeArray<RaycastCommand> raycastCommmands;
[Unity.Collections.ReadOnly] public NativeArray<Vector3> originPoints;
[Unity.Collections.ReadOnly] public Vector3 direction;
[Unity.Collections.ReadOnly] public int length;
[Unity.Collections.ReadOnly] public int layerMask;
public void Execute(int i)
{
raycastCommmands[i] = new RaycastCommand(originPoints[i], direction, length, layerMask);
}
}
var raycastCommands = new NativeArray<RaycastCommand>(origins.Length, Allocator.TempJob);
var raycastHits = new NativeArray<RaycastHit>(origins.Length, Allocator.TempJob);
PrepareRaycastCommandsJob prepareRaycastCommandsJob = new PrepareRaycastCommandsJob()
{
raycastCommmands = raycastCommands,
originPoints = origins,
direction = direction,
length = length,
layerMask = layerMask
};
JobHandle jobHandle = RaycastCommand.ScheduleBatch(raycastCommands, raycastHits, 1, default(JobHandle));
jobHandle.Complete();
RaycastHit[] raycastHitsResults = raycastHits.ToArray(); // BUG: elements have point of 0,0,0
Was trying to follow the example: https://github.com/LotteMakesStuff/SimplePhysicsDemo/blob/master/Assets/SimpleJobifiedPhysics.cs
Thanks
Guys, EntityManager em = World.Active.GetOrCreateManager<EntityManager>(); is deprecated, what should i use instead? Almost every tutorial on IComponentData and ISharedComponentData is outdated :/
@sharp blaze this example is one year old, it's really outdated
@sonic oyster Try EntityManager entityManager = World.Active.EntityManager;
@safe gate unfortunately there isnt any examples of using raycastcommand + jobs together so im kind of stumped on documentation. It runs as intended, just doesnt return the correct values, so maybe im missing a step?
thanks @sharp blaze
Can you make raycastcommand work without jobs?
At that point it's just a normal raycast, tho?
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
you can but then yeah its not efficient
https://docs.unity3d.com/ScriptReference/RaycastCommand.html
I know, but if you try to replicate the behaviour without jobs, does it work?
You need to know if the problem is on the job or the raycastcommand
i replicated what unity's documentation for raycastcommand has and it didnt change in performance compared vs when I used normal looped raycasting
But can raycastcommands work on the main thread?
before i tried adding it to a job, what i replicated with unity's example for raycast command felt like it was running on the mainthread. So I guess it is running on main thread? im not sure how to check that but the performance was definitely not multithreaded compared the the github example
And it gave you actual results? Not just 0,0,0
the results were all 0,0,0
so it ran as expected just not correct result
oh if you meant before the jobs, then yeah the results were correct, 0,0,0 was after i tried adding jobs
And all the values you are passing to the job are correct?
@sharp blaze Member 'World.Active' cannot be accessed with an instance reference; qualify it with a type name instead using your EntityManager entityManager = World.Active.EntityManager;
yeah, you can take my pasted code and try it out with your own points, direction, length and see what you get. let me double check if its initial values on my side
Looks like preview-0.33 is out for Entities, fixes quite a few issues on preview-0.32
especially with the type manager ptr restrictions
How do you access the entity object from a monobehaviour using IConvertGameObjectToEntity?
something like this:
private void OnTriggerEnter2D(Collider2D collider)
{
var sender = GetComponent<GameObjectEntity>().Entity;
var other = collider.GetComponent<GameObjectEntity>().Entity;
}
if you're using the IConvertGameObjectToEntity, and you really need the entity
in your MonoBehaviour you'd do
Entity e;
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem) {
e = entity;
}
As long as you don't destroy your game object. GameObjectEntities will eventually be deprecated
What do you mean by GameObjectEntities will eventually be deprecated? FML
The Conversion API is the recommended way to go
make sure you keep the two seprate
convert is the new api and will not be depricated
GameObjectEntity (A component you can put onto a gameobject) is the old api
it will be removed because it was deemed bad practice and they came up with a better long term plan that is converting to entities removing the game object representation
Oh, I never worked with GameObjectEntities, only with Convert
GameObjectEntity is part of the older 'Proxy' api
yep - it linked gameObjects way too much with entities and caused a massive slowdown on the inspector
@coarse turtle do you suggest a different approach to handle collision?
tbh it depends on how complex of collision you want
Erm, you can do basic AABB collision if it's really simple
^ naïve brute force if your only looking at sub 10k collisions
sphere or aabb
2d 100% just roll your own in passes
either passes for ease of dev and debug
^ yes
or single pass collision world like unity.physics and have the components brought in all at once during the pass start of jobs
omg this ai is finally somewhat coming along
everything is just twice as hard in ecs lol
lol indeed
it works quite well with utility theory
so you can evaluate things all at once and then decide based on a high benefit decision
@sharp blaze I had the same issue with batch raycast but I didn't try to solve it. Let me know if you figure it out
psuong thanks! i'll try out
@minor sapphire in case you didnt know, you can actually do a state machine for AI, or even a task thing, by adding a task/state component
its a great way to do AI stuff
@stuck saffron its driving my crazy man
For sure, we pretty much have the same code as eachother so it probably is something I should look into it if its a possible bug or implementation thing
Hmm, have anyone played with ISystemStateComponentData or its shared variant?
Bah, looks like it's basically just a system-private component, not something I need
its not private
I've used them quite a bit
they are for event systems that need to hold internal data that has a lifetime
I use them for hybrid setups to hold onto a dontdestroyonload gameobject, and in voice systems to hold onto native memory buffers so they always exist and cleanup proper
its also for stuff like acceleration structure links
yep that works too
regular component is fine as well, the main thing with those is you get a chance to cleanup them after everything else has been deleted on that component
How do you instantiate a light during runtime in ECS
I understand that a light needs to be a gameobject and that its corresponding entity needs a CopyTransformToGameobject, but I don't know how to do this in script
something like
var go = new GameObject();
var light = go.AddComponent<Light>();
var lightEntity = EntityManager.CreateEntity();
EntityManager.AddComponentObject(lightEntity, light);
I instantiate my entity from a prefab in a job, I can't access the entity manager there and the command buffer does not have AddComponentObject
You need a gameobject, meaning something has to stick out of ECS and do that
I know I need a gameobject, I'm trying to figure out how to make a gameobject with the light from the jobsystem the entity is instantiating from
@odd bay you need a gameObject with the ConvertToEntity script
But you set to create entity and inject
Then you manually add a CopyTransformToGameObject if you are moving the entity
And you are all set!
I'm instantiating it as an entity through script
If you are moving the gameObject, you need the CopyTransformFromGameObject
You need to instantiate the gameObject
I think it would be better to have a gameObject prefab that gets converted to an entity
Much simpler
I use a gameobject prefab that gets instantiated as an entity in a job
The gameObject prefab has the ConvertToEntity script?
No, the system itself instantiates an entity from the gameobject prefab
if you are dead set on having it from a job maybe you need to pool the lights beforehand
I'm just going by the example in the ECS samples
I don't really know how to inject the gameobject when you are spawning from script
I just discovered that you can add ConvertToEntity to a prefab, I will test if Inject works
It doesn't seems to work
How does the entity have a transform reference?
What this line means?
It is on Unity.Transforms.CopyTransformToGameObjectSystem.OnCreate
How can you create a query for components that aren't really components?
use a ComponentSystem for monobehaviour components
you can still query monobehaviour stuff in entity queries
How can you add the transform reference to the entity?
something like EntityManager.AddComponentObject(lightEntity, myTransform);
yeah
@odd bay there is your answer
Add the transform reference to the entity
And add the CopyTransformToGameObject component
I got it to work somewhat, but it seems like I'm doing it completely wrong. The light is also really weak until I click on the gameobject in the inspector, then it becomes its full brightness. This might just be an editor bug
public class InstantiateWithGameObjectSystem : ComponentSystem
{
EntityQuery entityQuery;
protected override void OnCreate()
{
entityQuery = GetEntityQuery(typeof(InstantiateWithGameObject));
}
protected override void OnUpdate()
{
NativeArray<Entity> entities = entityQuery.ToEntityArray(Allocator.TempJob);
for (int i = 0; i < entities.Length; i++)
{
GameObject gameObjectInstance = new GameObject();
Light light = gameObjectInstance.AddComponent<Light>();
//Entity instance = EntityManager.CreateEntity();
EntityManager.AddComponent(entities[i], typeof(CopyTransformToGameObject));
EntityManager.AddComponentObject(entities[i], gameObjectInstance.transform);
EntityManager.RemoveComponent(entities[i], typeof(InstantiateWithGameObject));
}
entities.Dispose();
}
}
I also haven't figured out how to pass in a prefab for it to instantiate since IComponentData doesn't hold GameObjects
is there a way to have one job per shared component value? my shared component is the village the humans live in and a lot of tasks can be parallized very well in a "for each village" sense, since there is no communication between the villages
So jobs on chunks?
in my case I need to determine a price for a good in each village. This needs a few arrays where I keep track of current offers etc. which are local to each village. If I could have a job per village it would be perfect and just each job would have these few arrays and calculate the price for the current village
yeah but one shared component can span multiple chunks
Sounds like you will need to engineer around it, then
Could I do it like this or does it sound bad:
Use IJobChunk and give it a NativeHashMap<Village, SharedDataStuff> stuff; and then let each chunk write to stuff[village]
and just hope that it won't happen to often that two different chunks with the same sharedcomponentvalue run at the same time and slow each other down
Was about to suggest that'd be the way to do it. It really depends on what you need to write and when
hmm to this shared data the jobs will be writing very heavily
what the job actually does is just write down for each human if he wants to buy/sell and keep track of "order books" with bids and asks
It might be good to have multiple hashmaps during the collection phase, one for each type of information, to spread things out, then you have a job to collate all of that to one hashmap before you run the final job which does the calculations for the good
so if two jobs would run at the same time they would probably have a hard time getting write/read access to the order books since the other job just uses it all the time
Is it binary whether the want to buy/sell? (well, trinary, I guess: Buy/Nothing/sell)
it is actually a price at which they would sell and a price at which they would buy
Is there a way to do sprite animations using ECS?
So essentially, you need to grab each person, and check all(?) goods and both(?) their demand and supply price, and collate all of this?
yeah in some sense that is what I need to do
I don't really know how economists model this and it is surprisingly hard to research (I think they just don't), but it is actually a quite nice thought experiment of how one can arrive at trades when there are many different ask and bid prices
how they are matched etc
I think I'll just try to come up with a concept that plays nicely with parallelization
@junior fjord You could use a hashmap where the hash is a village+good combination, that holds a collection of some sort.
Job1: for each person, for each good they have, insert their prices*1 into the collection.
Job2: take that hashmap, and do whatever magic you need to end up with each village's overall supply/demand prices *1 (in another hashmap of the same format?)
*1 If you store buy and sell prices together as negative and positive you can easily find out if demand is higher than supply and stuff.
how do you get a component from a wrapped entity? e.g:
public struct EventPayload : IComponentData {
public Entity entity;
}
now i would like to check if entity has a specific component but I don't know how to access it.
To check if it has a certain component you can do:
if (EntityManager.HasComponent<ComponentType>(entity)
{
// do logic here
EntityManager.GetComponentData<ComponentType>(entity);
EntityManager.SetComponentData(entity, new ComponentType { });
}```
thanks @stuck saffron !
@junior fjord you could google: order book matching algorithm
can you use Linq in jobs?
@dry nymph thanks 😃
it gets way easier when you know the name of what you want to know
@stable fog you cannot use LINQ in jobs as most LINQ functions allocate temp managed objects and that not safe in normal jobs and not allowed in burst
For some reason when I try to change the color of my trail renderer the trail always just stays at the default pink color
Default pink or the "no material" material?
um probably the "no material" material
oh wait do I just have to add a material
Yep I did that it works now
thx
I wonder if it is possible to serialize and deserialize entities and their components?
Does anyone know if it is possible to make a break in a trail via code? I want the trail of a character to not show in the part where it dashes, but I still want it to show in the space before the dash.
This is using the trail renderer btw
Does anyone know about the future of the Hybrid Rendering package (MeshInstanceRenderer, etc.)?
Does anyone know about the future of the Hybrid Rendering package (MeshInstanceRenderer, etc.)?
At least documentation seems to be deleted? https://docs.unity3d.com/Packages/com.unity.rendering.hybrid@0.0/manual/index.html
@eternal dune see the pinned message on this channel
also refer to dots sample repo readme for upgrade notes (there's no mesh instance renderer anymore, it's called RenderMesh now etc)
oh right, there's no real docs for hybrid atm (this is why I didn't list it on the pinned message), sorry about that
Thank you!
cries why they destroyed inheriting [DisableAutoCreation] ._.
Is there a way to clone an entity?
I highly suggest playing with intellisense and see what each of the major parts of ECS (EntityManager, World, the various built-in classes/structs) can do; I feel like I got a pretty good overview of what can be done and how from that.
And then you have cases like this where you want to, I dunno, manage entities, so EntityManager.(intellisense completion) and just start writing entity will get you at least some options, if not an answer.
hey so im having a bit of super strange ecs weirdness. my "convert entity" is not working, it just gives the warning (convert entity failed because there was no active world) does anyone have any advice
i was able to fix my last problem by rolling back to an older version of the ecs package. however now i am having another problem that i have been fighting against for ages. for some reason when i have a shared component that contains an array, even if another shared component has the exact same data in the array it treats it as being a unique shared component configuration. does anyone have any idea how to fix this?
Has anyone got any information about the effect of hyperthreading on an ECS project?
Hyperthreading optimises CPU uptime while it's waiting for memory access or something right? with efficient memory structures I wonder how it will perform
or maybe it gives you a little bit of leniency for some random mem accessing or something lol
I really wanna see a threadripper chew through a highly parallel ECS game haha
@fickle sapphire You use GetComponentDataFromEntity<T>() to get an array of those components, pass it into a job and then index into it with the Entity reference in your component.
So... Just wanna check im doing this right... With regards to local and world coordinates, using the inbuilt unmodified localToWorld component...
Firstly, If i use LocalToWorld.Forward, it should be the world coordinates of the entities forward vector? So, quaternion.LookRotation(LocalToWorld.Forward,LocalToWorld.Up) should be a similar rotation to the Rotation component quaternion? I say similar rather than equal due to rounding differences.
Secondly, If i have a direction vector in world space, and i multiply it by the local.value matrix, i should then have the direction vector in local space, and this would be the same in both local and world coordinates, if my entity is pointing along 0,0,1 and its up is 0,1,0. Is that right?
Thirdly, if i calculate a rotation based on euler angles as numbers all read from the local coordinates, and build up a float3 that contains the axis rotations required to turn the requested amounts, on each of the three axes, the result doesnt need to be done in local space, if you multiply its output quaternion by the current rotation quaternion?
Firstly, If i use LocalToWorld.Forward, it should be the world coordinates of the entities forward vectoryes
So, quaternion.LookRotation(LocalToWorld.Forward,LocalToWorld.Up) should be a similar rotation to the Rotation component quaternion?should be
If i have a direction vector in world space, and i multiply it by the local.value matrix, i should then have the direction vector in local space, and this would be the same in both local and world coordinates, if my entity is pointing along 0,0,1 and its up is 0,1,0. Is that right?I don't know about this ^^; local.value matrix seems to provide position AND rotation information. sounds like you just want to do something with the entity's rotation only?
Got lost in that 'thirdly' bit.
does what you want to do boil down to "I want to go over there. Over there is to my left. I need to engage thrusters to rotate me left."?
Exactly that, except during the process of turning left it need to take into account the maximum rotational acceleration and speed.
Which is potentially different for each axis.
right
I can handle it in two dimensions, it just seems to be getting confused, i've tracked it down to it's seeming to use the values on the wrong axes sometimes, it basically seems to be rolling when it should be turning.
and you do want to just 'rotate left' because...? is there something special about the placement of thrusters?
this per axis thing...
different thrust power per axis or something?
if you want to 'rotate left' you have to 'rotate around up axis'. that part is understood right?
Yeah, its because the game includes a ship editor, which enables you to place your distribution of weight and thrust, so its gonna generate the simplified data into constraints on rotation speeds in each axis, but for now im just using hardcoded numbers to get the system going.
right
Yeah, its a case of x axis = pitch, y axis = yaw, and z axis = roll
Where the amount of pitch, for example, can be read from the y/z coordinates whilst the yaw can be read from x and z
Its a pain hehe
this whole per axis thing is the hard part
Yeah, i know, buts its a very important part of the game.
I mean in theory, you get your rotation delta... it has x/y/z components...
then you apply your 'rotate around z' thrusters, then your y, and then your x or something (I think is the order of rotation??)
but I guess you're doing that much already
but you can't apply all thrusters at full strength because then you will be rotating in the wrong direciton right?
Well it basically runs it through a check, if the result of normalisation would result in a larger magnitude, it doesnt normalise, so it scales for small values, but then will keep it from exceeding maximums.
set your thrust force high, max rotation speed low, and and rotation drag high
so basically there is no 'drift'
then you'll be able to visually understand what your ship is doing
without any of the wobble
Yeah, ive been doing that already
so it came down to "it's rotating around z in stead of y" or something?
Still doesnt help, ive manually forced it to only turn on one axis at a time for testing, and its coming up with a value in the x coordinate, but turning in z.
Sorry, a va;ue in the y coordinate, but turning in z
its visible when it gets stuck and then starts going back and forth - only y values show, but it rolls.
so like 'delta rotation is (1, 0, 0) and it turns around z axis?
(0,1,0) but otherwise yeah
that sounds like you have everything but this one last bit...
apply the other thrusters!
lol
other? hehe
the point is its constrained to only use one at a time, its pushing thruster a but getting thruster b hehe
the yaw(?) thrusters for (0,1,0)
yeah
you have reduced all of this to two dimensions?
everything seems correct, otherwise, numbers, angles, orientations. Ima try fiddling with rotation order again.
Yeah, works fine then
Which kinda suggests the rotation order again i suppose
remove everyhthing from the equation except for this thrust translation issue
feed in a constant destination of "to the left of me"
and see if you can get the ship to yaw left
just hard code destination to localToWorld.Position - localToWorld.right * 10 or something like that
or wait
if you are working in local space it's different
I did that, sitting there going in circles to make sure all the right angle settings worked on thrust
and does it?
yes
so your thrusters can be passed like, (0, 1, 0) and it will yaw right or something?
yeah
so now try to hard code a destination that will always result in (0,1,0) in thurster
and see if that destination translates correctly to (0,1,0)
if the destination is local, set it to (1, 0, 0) (to the right I guess is how your thing works?)
yeah i think so
if it's a world destination use localToWorld.Position/Right
so hard code the output of your destination system to (1,0,0) and see what happens
ok, gimme a sec
OutPut Speed Quaternion reads as float3(360f, 0.1054123f, 359.9313f) and constructed from float3(0f, 0.1054123f, -0.06865695f)
359.9313f is roughly equal to -0.06865695f
in eulers
I don't know how all these numbers apply to your situation, but is this expected?
it means its doing what im asking it to, thats right before the quat is made, and itscorrect
so with this hard coded value, it's turning as wanted?
just keep hard coding the step before until it isn't as expected
Its still not doing as expected, cant figure out why its swapping the axes
so you want A -> process -> B
but you're getting A -> process -> C?
and it's between these two seemingly close steps?
maybe paste the code for this A to B transformation now that it's narrowed down to this
but if I see like a ton of maths I'll just be like "I dunno" lol
thats the trouble, its all extensive maths
I've decided to go with a mathematical implementation of how i overcame this problem in the oldschool monobehaviours, with a slight tweak. Before, I wrote an "Ai rig" type setup, where there were gameobjects at each corner of the ships position, it actually had one in each cubic corner and one in the middle of each line and face, totaling 20 nodes, which to do with entities would be annoyingly complex not to mention it really doesnt like running child objects around. Also, the nodes were each calculating their data every frame. So, i know ive gotten the local to world rotation translations working properly on the normal directional vectors - ive been using it to run a coloured coded set of local axes for visual debugging - so im gonna do a few positional transformations and derive the required pitch/turn movements from that, then, instead of constructing a quaternion directly from eulers, ill construct a new direction vector and then use quaternion.lookrotation. Direction vectors are sooooo much easier, they can be debugged visually with minimum effort too. Im gonna use some basic trig to work that out, aside from the vector itself, ill be using high school maths instead of crazy degree maths :D
Oh, and the tweak will be to arrange the node checks into a kind of hierachy, so it will discern from previous checks which checks to proceed with, but also it should be able to half the number of nodes anyways, cos its gonna return yes/no to the queries, and every node has a second node to which the opposite bool condition will apply.
Are there any examples of using RenderMesh from the new pure ECS HybridRenderer? Everything I've found uses a game object conversion, I want to create a new mesh purely from code.
EntityManager.SetSharedComponentData(entity, new RenderMesh { mesh = data.mesh, material = data.material });
||
EntityManager.AddSharedComponentData(entity, new RenderMesh { mesh = data.mesh, material = data.material });
@next kiln
Or do you mean like generating vertex data?
Thank you! I was getting confused based on the API page for RenderMeshSystemV2, but it looks like the Hybrid Renderer takes up that entire namespace and RenderMesh!
That’s perfect, I’m assuming the vertex data is like any other.
Gotcha, some documentation is messy. I mostly get through it with intellisense, definition/exploring, and alt+enter haha
I might start doing the same hahah. Appreciated!
Anytime! Alright now to my question
I am trying to generate entities based off a scriptable object's data. I have a couple approaches: use bools or unity events but they can get messy. I can't seem to use a IComponentData[] directly. Is there any good way of creating a set of different IComponentData types and storing them in one array using the inspector?
@stuck saffron I may be missing something but don't you just need a monobehaviour to add those components to an entity? You can create a scriptableobject that has an array or list of IComponentData's right? I'm sure it's obvious but you'll also need to check you're not adding the same component twice
wait maybe I misunderstood - are you wanting to use reflection or something to find all IComponentData's in a project?
You cant serialize an interface. IComponentData is an interface so you can't have an array of them on a scriptable object @amber flicker
You can create an entirely set of "inspector components" that carry inside of them the component itself
If you have a RotationSpeed component that has the attribute System.Serializable you can create a RotationSpeedInspector that contains a [SerializeField] private RotationSpeed _rotationSpeed
Then your SO would have RotationSpeedInspector[]
But if you want a single array for all your components, then you need to create a custom inspector
So you could have RotationSpeedInspector inherit from ComponentInspector, and the SO would have a ComponentInspector[]
But then you would need a custom inspector so you can choose which type each ComponentInspector should be
Or you can create multiple SOs, one for each component and they have the specific array
But why you are creating from an scriptable object? You could just use a prefab
It seems like you want the SO to be the prefab
And I just realized that if you are creating a custom inspector, you could just use a IComponentData[]. There is no need to create a ComponentInspector
Well I have a bunch of different projectiles so I have a singleton scriptable object that contains a ProjectileData[] (SO) where I currently pull the data from to intantiate a projectile entity. However, I am trying to allow designers to pick additional components to attach to the entity
Can you? I must doing something dumb if you can actually use IComponentData[] in an SO
Unity doesn't serialize interfaces
You have to create a custom drawer for that
It sounds like that you will need a custom inspector or at least custom drawer for that
Or just buy odin inspector
I came to that conclusion last night haha but I would need to do the serialization myself too, right?
Yes, Unity doesn't like interfaces 😑
Unless you create the ComponentInspector class to hold the component data
Then you just have to worry about the inspector, not the serialization as well
So I was trying something like this earlier:
public abstract class ComponentProxy
{
public abstract IComponentData GetComponentData();
}
[System.Serializable]
public class HeadshotProxy : ComponentProxy
{
public float multiplier;
public override IComponentData GetComponentData()
{
return new HeadShotMultiplier { Value = multiplier };
}
}
The SO can have a ComponentProxy[]
But then you need a custom drawer so the user can select which specialization they want
And internally, the ComponentProxy works well with the GetComponentData
The only problem is that Unity doesn't know how to show the ComponentProxy[], thats why you need to create a custom drawer for that
Oh, gotcha. Well I have never written a custom drawer before so this should be fun
It is really fun to work with the editor UI, too bad I don't have always get the chance to
Any suggestions before I jump into it?
As soon as you learn how to do it, don't let the power turn you into a custom inspector/drawer maniac. You will want that, but you have to be strong and resist the urge
I lack impulse control so may god help me.
Also thanks for the help! I appreciate it a bunch
Can't find the post I remember that was IComponentData storing using Odin but this did come up
I am trying to get simple 2d animations using ECS. In gameobject world I would have SpriteRenderer and animator, but I couldn't find any information on how to do it with ecs.
Is the only way to use hybrid ecs?
"hybrid" is just a stop gap really, so if a certain thing isn't supported yet best just use that but IMHO if serious about using DOTS for rendering, it's best to figure out how to animate sprites in shader (such as flipbook etc)
(for 2D context and perf oriented)
for example 20,000 enemies using sprite renderer is a needless amount of data being pushed to gpu, you could have it so it does generic shader based anims at distance and hero ones close up
just spitballing
Thanks. I was thinking that was the case. I think I will go for the hybrid road and update it later or when they update it. Unity ecs samples repositories doesn't have anything related to hybrid. Is there any documentation how it is supposed to be done?
I used GameObjectEntity.AddToEntity(EntityManager, go, entity) and can see SpriteRenderer & Animator in the entity debugger, but the Transform positions are not being updated. Do I need to make a system for that?
To update the transform that the entity references, you have to add the component CopyTransformToGameObject
Turns out I have no idea what I am doing with property drawing
I am going to move over to #↕️┃editor-extensions because I figured out the "ECS part"
Thanks! that worked
My current theory is that when DOTS Runtime (C# Tiny) is released, it won't have a garbage collector. Can somebody tell me I'm wrong?
DOTS and Tiny are different things (they do have similarities, but are not the same)
Thanks! I meant to reference Tiny.
when ecs will be procution ready ?
About 2022 I think
Hybrid should be somewhat production ready this year yet, but pure ECS only 2021-2022 according to their roadmap
If I have a person entity with a health component, and a healthbar entity to display that health, how should I design this? At first I accomplished it by
Health parentHealth = World.Active.EntityManager.GetComponentData<Health>(parent.Value);``` but this seems anti-pattern. Should I use ISharedComponentData? The docs say it should change rarely, so I guess not.
I wouldn't even call hybrid production ready before we get DOTS editor
you can use ECS but it's not a nice and productive until we get that editor
having to rely on conversion tools for everything is just hacky, I'd never call that production ready myself
I don't see ECS as production ready until you can do purely pure ECS
So ECS is unstable and shouldn't be used atm?
it's more of the experience you get right now
it has barely any tooling right now, it's API changes for almost every minor release even
it's just horrible equation all around if you think how things work in production
and since it's still so early days with it, freezing to one version can work to some extent but it's then pain to upgrade it if needed
think of all people who built their game using Unity ECS injection API
that stuff doesn't exist anymore, so you have to rewrite pretty much all code now if you want to use the recent developments
of course there are occasionally versions that are just bugged, like preview.32
I dunno if p33 fixed all the issues yet
but that's what you get on any preview, you can't expect it to be fully stable, especially when the framework is rapidly evolving
@sonic oyster
Damn
So I have to scrap my idea of using Entities for map chunks then
How do i store map chunk data then if I can't inherit/refference classes in job system?
I need burst compiler to make it work smooth, without it, framerate drops real hard, because every voxel update makes a heavy math to regenerate meshes
job system and burst are more production ready
neither is in beta/preview either
and just for sake of clarity, you can use burst on jobs without using entities
I know that, @dull copper, but I'm having a trouble implementing blockdata to job
Previously I had a class that was inherited per blocktype
Every block had special voids in them that returned values
I can't really do that in structs
I.e. Block : BlockGrass
It had values for texture, mesh, being solid on every face and onplace/ondelete events
@sonic oyster you use different arrays per layer, including hashmaps or other structures
so for example you start with an array per chunk (dense) of NNN int8s, and those are your general blocks per chunk
and then, for special blocks (maybe extra data), you have a hashmap where the key is the coordinate
with the int block types, you just have number 2 = blockgrass. If you then want, you can implement an array (maybe outside of ECS), where you index with the block type, and it holds the logic for that block type
@sonic oyster think of it as adding functionality in "layers"
you can access a block on its X,Y,Z coordinate index, so you can have multiple arrays-hashmaps-whatever with extra information that you can access from the index
http://www.dataorienteddesign.com/dodbook/ this book will help
Data-Oriented Design
I use NativeArray for coordinates
1D
I just do a calculation to get xyz from 1D array
Since map chunks have fixed size
yes
but in cases where you only want extra data for maybe 10 out of 256 blocks in a chunk, you should use hashmaps
another option is to use sorted arrays
instead of hashmap
you have an array where yo have index + extradata in a srtuct
and its allways sorted
and you use binary search to find the key you want, or just straight bruteforce if its less than 20 items or so
guys , anyone got link to megacity code on github ? Im just wondering if it's avaialbe there, cant find. I just need to look at the code 😉
its only officially available through that link from unity
Anyone able to direct me to a good quick tutorial or something for making a camera follow an entity? Or, offer directions :D
I suggest searching for a tutorial on a camera following a game object, then you just CopyTransformToGameObject
I suggest searching for a tutorial on a camera following a game object, then you just CopyTransformToGameObject
I suggest searching for a tutorial on a camera following a game object, then you just CopyTransformToGameObject
Gregorio suggests searching for a tutorial on a camera following a game object, then you just CopyTransformToGameObject
Hehe i dun it
i wrote my own setup
Its actuslly working nice
Thanks for the help tho :)
how can I access a dynamic buffer from an IJobChunk?
use GetArchetypeChunkBufferType instead of GetArchetypeChunkComponentType
@safe lintel thank you
I wanted to take advantage of gpu instancing with texture2darray, but unitys ecs rendering does not support materialblockproperty. So I made a simple system that renders my entities. However when I get the texture data to texture2darray, something goes wrong
The alpha channel is broken. I am not sure if it is how I copy the texture or the shader doesnt support transparency. Probably very easy to fix but I don't know what I am doing 😄
## [0.15.1] - 2019-05-30
* First Tiny C# preview release. This release is **not backward-compatible** with previous releases.
* Must use Unity 2019.2.0b3 and above
### [Editor]
* Added the ability for the editor to change context when working in a DOTS project
* Added the Searcher when adding a component in the Inspector window
* Added a new Open DOTS C#
* Relocated build options to the top
* Removed Physics2D, Tilemaps, and Particles
* Removed Component type creation
* Removed live-link
* Removed QR Code
* Removed the build report
* Removed Component Families
### [Samples]
* Removed all previous samples and replaced them with new sample projects
* Samples are now imported from the Package Manager'
### [Scripting]
* Now supports the DOTS API and C#
* Removed support for Typescript
### [Hierarchy]
* Renamed EntityGroups to Scenes
* Added a new Configuration Scene
### [Project Settings]
* Renamed "Tiny" settings to "DOTS"
* Removed most settings from the Project Settings
### [Prefabs]
* Removed Prefabs
### [Runtime]
* C#
* New build platform options are now available: Dotnet, IL2CPP, AsmJS, and WASM (known issues on certain browsers)
* Removed TypeScript
C# tiny on staging now 😃
Freak yeah
apparently they don't ship with the old fancy examples tho
this on the new package
they have *.project file here now
scene itself uses *.scene
Where do you see the staging?
you get staging packages if you put staging url to your projects packages/manifest.json:
{
"registry": "https://staging-packages.unity.com",
"dependencies": {
"com.unity.tiny": "0.15.2-preview",
but you can browse bintray as well: https://bintray.com/unity/unity-staging/com.unity.tiny
That is nifty. So we should expect this to be officially added hopefully today?
Ah gotcha, I remember you have talked about this before and turnaround times during the staging phase. Couldn't remember the typical range though
well, if you saw me talking about it, I probably mentioned staging packages aren't cleared for release yet
a lot of things that get to staging don't get released
but next version or version after that etc
DOTS packages tend to move fairly quickly tho
hmmmm, when you double-click .project, whole editor goes into DOTS mode
this also only works on 2019.2 betas atm
I tried first on 2019.3 alpha and it didn't launch at all
can't build and run this tho
Error opening for writing the file: C:\Unity\Unity Projects\TinyTest\Library\PackageCache\com.unity.tiny@0.15.0-preview\DotsPlayer\bee~\BuildProgramBuildProgramSources\buildprogrambuildprogram.gen.csproj, error: Permission denied
and that path is only 169 chars long for those who wonder if it's too long
this also is still a dedicated mode
DOTS editor for ECS now please
and I'm afraid it'll stay this way
I'd really really want to have both monobehavior and DOTS editor side by side on hybrid
but I'm afraid that's not going to happen, it just would make so much sense while we have hybrid here
would immediately see both worlds
add component menu is pretty funky now too, but it could be because early preview
The fact that Tiny is not exactly the same as usual DOTS makes me think it's less performant and may be doing some black magic in the background
They removed a lot of things, is there any new or old sample working ?
I mean they removed Physics2D, Tilemaps, and Particles which aren't small useless modules (I know they will be back, just asking about your thought on the current version)
@knotty radish it is not about performance, it is about size. Project Tiny is meant to deliver very small executables, this is why they removed so many things
You can think of Default Unity and Tiny Unity as equal engines with different frameworks
Love the look of the dots editor
I mean, this is how I see the Project Tiny so far, they are being very vague still about it
Wish I had that for my hybrid project though
Tiny is pretty interesting. They have more info on the forums in a sticky
Yes, but they don't update it as often as DOTS, so there is many things with incomplete or outdated info
holy shit at last
ive been waiting for Tiny csharp for quite a while
time to actually get going now
@rancid geode now that tiny uses DOTS C# framework,they should merge
Tiny essentially being a "mode" of unity
where you have no old crap, but you get great perf + tiny install size
Tiny modules will likely work on normal DOTS mode. But i think eventually they will let people choose
do you run the DOTS Sprite renderer? with sprite lighting and batching
or you run the Tiny sprite renderer, with less perf but has very smal space
In the Tiny forums it was mentioned that things like Physics would still be separated (there will be Unity Physics and Tiny Physcs 2D, for example), so while the core framework will be the same, they are still going to be different things
I mean, seems like there will be like 4 different ways to develop with Unity
MonoBehaviours
Hybrid (Mono + ECS)
DOTS
Tiny DOTS
it will likely be like unity phisics vs havok physics
both use the same components
the same API
but the backend is different
i also expect everything to work everywhere too
hopefully it will be that way, but there is no official comment about that yet
no reason not to, really. If you only use basic 2d, then use the Tiny systems even if its a desktop app
DOTS is going to have it's own 2D physics
I dunno if there will be tinier variant for 2D and 3D physics but I don't think even current 3D DOTS physics is super bloated
btw, Tiny got a bump to 0.15.1-preview on staging
I think they changed the min engine version from b1 to b3
man i just cant imagine the final goal for dots editor is going to be the same kind of disparate way tiny is
Hey! Trying to get non-ecs jobs to work. I made a readonly struct with data to use in job.
Editor throws that I can't use managed structs. What I can do about that?
I want a struct that doesn't copy itself in memory when I allocate something as it.
Struct itself looks like this:
public Block(int value1, bool value2) {
this.val1 = value1;
this.val2 = value2;
}
public int val1 { get; }
public bool val2 { get; }
} ```
Anyone got any suggestions about the order of collisions systems with relation to movement systems? I have my movements, my rotations, and both systems ready to receive responses from the collisions, and, i have the collisions being detected. So, whats the best order? My aabb system currently doesnt have a defined position in the order of things.
Im good with code on this one - this is the fun bit ive been looking forwards too :D
Mostly just considering ideas :)
package manager got funky on 0.15.2
it tells me 0.15.0 is installed but peek in library shows 0.15.2
it also don't let me install samples as those links are now hidden 😃
I just copied the samples manually as that's what PM would do anyway
ah, now the PM updated to show the right data
well, the sample projects are on the package itself
they should show up on package manager (WHEN it works like it's designed)
well, it built now for the first time
I dunno if it's 15.2 or just that I had one folder shorter path when I manually copied the samples
I kinda wished they would have ported the old tiny samples here
but there's probably stuff missing
getting to play mode is basically just build and run
I kinda wished you could play the old way in editor
as waiting for half a minute to test your changes isn't that great workflow
there's quite huge difference if you use debug or release 😃
with debug build
on release:
this only works on 2019.2.0b3 and b4
latest 2019.3 alpha can't even load the new DOTS .project file
or well, I haven't tried with the 0.15.2, but 2019.3 alpha failed to load 0.15.0 at least
you can add regular ecs components here but there's like only 2D camera
also, the initial setup for this is tedious as you need to add the custom packages in the asmdef manually
but that's expected as these aren't supposed to be used yet
it does have all tiny and base entities refs in place
@vagrant surge tested 0.15.2 on 2019.3 alpha and it still fails, no surpises there
it's similar case with megacity demo
you can only run it on 2019.1 as it's the only one that has dsp graph in the binaries 😄
how do i download it?
2019.2?
you can use Unity Hub for it
oh you probably meant tiny
it will not show normally in the package manager, you have to open your projects packages/manifest.json and put this on top:
{
"registry": "https://staging-packages.unity.com",
"dependencies": {
"com.unity.tiny": "0.15.2-preview",```
it'll force it to use more experimental staging repo where the new tiny package is atm
you may need to put entities p33 manually from package manager as well
it's a dependency for tiny but some package (at least on 0.15.0) forced some older jobs or collections etc there that caused issues
this is my package list for tiny test:
{
"registry": "https://staging-packages.unity.com",
"dependencies": {
"com.unity.entities": "0.0.12-preview.33",
"com.unity.ext.nunit": "1.0.0",
"com.unity.ide.visualstudio": "1.0.11",
"com.unity.package-manager-ui": "2.2.0",
"com.unity.test-framework": "1.0.14",
"com.unity.textmeshpro": "2.0.1",
"com.unity.timeline": "1.1.0",
"com.unity.tiny": "0.15.2-preview",
"com.unity.ugui": "1.0.0",
"com.unity.modules.ai": "1.0.0",
...
basically just put that in place of the things that are there up to modules.ai, leave all the modules as they are unless you really know what are not needed by the editor
create a new project using 2019.2
if you use hub 2.0.0, unity version selection for new projects is really stupidly hidden
but it does default to newest installed unity version
(but then again, almost everyhing on hub 2 is designed backwards)
if you have hub 2, this lets you pick the engine version for ne project
after you got new project, find the packages folder and swap that thing to the beginning of the manifest
it should update everything (even if you have the editor running on the background)
@vagrant surge
2D and 3D are fine I suppose
don't put LWRP or HDRP
basically these are just templates
I usually use 3D as it's basically equivalent of empty project
open package manager (from windows menu), select Project Tiny (or whatever it's called there) and you should see buttons to install specific samples
@dull copper kinda meh that it opens standalone
yeah, original tiny was like that too I think?
well, it launched browser
now you at least have option for mono build too which is tad faster due to lack of IL2CPP in the middle
tbh I expected you would be able to just play immediately when they get c# version
but apparently not
my biggest disappointment is really that it's still full editor replacement
I'd want to swap between monobehavior world and ecs world in the editor while playing
or even editing
it would be super useful as long as hybrid is a thing
there's also no prefabs on DOTS mode
I hope they can add them back
or come up with something equivalent
come on
imean you can use the very classic ECS pattern of spawner component
that holds all the variables needed, and then on first execution it "unpacks"
I think I'm just going to build more ecs editor tooling as I need it
starting to feel a need for a runtime inspector for debugging my networking entities
@dull copper no prefabs, its loadign Scenes
thats literally how godot rolls
instead of having a separation beetween a scene and a prefab, it loads scenes all the time
as it can load scenes in scenes and scenes attached in a scene node
@dull copper you can see the sources of the packages, no?
how?
i cant do " go to definition" in vs
@vagrant surge yeah, that's what I meant by "or come up with something equivalent", I know how godot does this 😃
the package source thing is bit dumb
you can get the VS see the sources but you need to manually move the packages you want to examine from your project folder/library/packagecache into packages folder
basically what happens then is that Unity will no longer cache those packages internally but uses the local versions on your packages folder (you also can't update these with package manager then)
but when you have local packages and you open any c# file from Unity, it generates a solution that has all files from local packages as well
it's hacky but at least you get full sources in VS for those packages
I personally deal with that so that I have separate project which I use to update the packages and then just copy the new ones on my working projects packages
@dull copper you can go into preferences and check "generage all .csproj files"
really? 😄
however, this is buggy on VS 2019
man, I've been doing this the hard way for a long time then
let me try this (I'm on VS2017)
2017 should work I think
@minor sapphire is that VS preferences or Unity?
ah, I know the place
well just enabling it and launching VS didn't work
I'll try toggling it off and on again
also wipe the current files
@minor sapphire where?
in your project folder you should see a lot of csproj files
edit->preferences->external tools
👆
it's temperamental from what I can tell lol
it only gives csprojects for same things I've always got
I have to uncheck and recheck every sessions if I want to debug package code and see source in VS
d you have another vs version installed?
one time I had to switch to 2017 then back to 2019 lol
they are the same that Unity uses by default
nothing
@vagrant surge swap the first value to visual studio
you have it set to internal
so.. I guess I keep using my hacky workaround :/
damn that's a shame
you'd see the entities csproj on your projects root folder if it works
oh right
anyway, if that fails, what I told does work
it's just bit tedious when you update packages
I'm 19.2b2
other it's just cut and paste from one folder to another
that option exists on my b4
it's no big deal
for some reason... I am not on 11 deliberately
just would have been fancy if it had worked
and I can't remember why
maybe this is it
I was on 11, then downgraded
I forgot the reason hahaah
hmmm
looking at the recent roadmap slides, they plan to release Tiny at second half this year
that sounds quite optimistic
I want physics update 😐
me too 😃
I'm on the fence about trying to implement physics myself for 2d, or waiting to see how they go in unity physics
but like, I don't really want to implement everything myself lol
it's kinda pity that they don't give estimate for 2D DOTS physics
I know they are working on it
2d physics is confirmed?
I read some forum post that suggested it was not planned
not officially I think
but it wasn't unity saying that
Burst's determinism is still marked only "Future" on this roadmap :/
it sounds very much it's going to get postponed to 2020 at this point
at least they finally are working on DOTS integration for addressables
what is addressable assets
it's the new thing that will replace asset bundles
has anyone build successfully in tiny? i keep getting this error
if you click on the message, it tells the actual error
but it could be too long path
when I manually moved the samples to the project root, I could build it
but I also updated to 0.15.2 at the same time
so it was either one of those things
I can't remember if this was on the previous roadmap already
it was
@minor sapphire I wiped the whole library and now I get all csproj's with that setting
nice 😃
the reason why I don't do that lightly on this project is mainly HDRP
I'm running custom version which means I compile all shaders from scratch
which means on my dev computer that first build on fresh library takes few hours
Ouch
cinemachine seems to currently do more harm than good for game cameras
janky behaviour, lots of little issues you need to know about etc etc, its good for film I guess?
It should improve when it will be ecs/jobified
But yeah at the moment I prefer not to use it anymore and just handle my own camera
ooo
about time 😃
We've just pushed 0.1.0-preview of Unity Physics and this contains many things discussed on this very forum, with more to come
* The new Joint for 2d use cases is there
* Sync points have gone - more to do there.
* Bounding Volume Hierarchy improvements should help performance
* The RaycastInput struct is tweaked to remove `direction` confusion
* Runtime CollisionFilter members now match the editor PhysicsShape component
* Physics Body and Shape ConversionSystem improvements are many
* Trigger events are now raised between kinematic && (kinematic || static) bodies
* Dynamic bodies with `PhysicsMass` components only are now integrated
* Trigger and Collision events demos were added```
no unity tiny post
@vagrant surge it's not yet at regular registry yet
either they are not ready to release current one from staging or they just didn't have time to prepare the announcement etc
it's possible they still want to change something etc
oh wow, Unity Physics 0.1.0 doesn't crash anymore on IL2CPP build
and it actually simulates physics now (0.0.2 just did random things)
Isn't that a bit harsh?
what is?
and btw, it does still crash on master and release settings (just not on debug where you'd actually see the error :p) but I think it's just the hacky try/catch tracker script again
I dunno if IL2CPP even supports try/catch
well, it's hacky script to begin with
basically the idea is to give entity id to monobehavior tracker script WHEN the entity sender script runs conversion to ECS side for the entity whose transform you want to track from the old side
then the tracker script just polls the entity manager to get the transform data from that entity id each frame
it's wrapped in try/catch which is so far from ideal
basically if it fails and catch occurs, it just stops tracking the entity after that, meaning the entity has been removed
but why this crashes on IL2CPP build is that sometimes the tracker runs before entity is properly initialized and it can't get the component data + IL2CPP can't handle the try there
last time I just put small delay there to avoid this but obviously it's not the proper solution
I wonder if there's a way to check if there's entity with given index in a safe manner
I haven't really checked either
as that would let one fix this setup better
3 cheers for physics update wooo
now just have to figure out new way to interact with trigger/collision data
I can't see any demos related to this hmm
hmmmm, the master crash isn't about the tracker script
in fact I have zero clue what crashes it
it doesn't crash on IL2CPP debug build, only with release and master
and crash is access violation on UnityPlayer
also, yet another tiny 😃 https://bintray.com/unity/unity-staging/com.unity.tiny/0.15.3-preview
for the crash, disassembly pointed the crash to this: cpp // System.Boolean Unity.Jobs.LowLevel.Unsafe.JobsUtility::GetWorkStealingRange(Unity.Jobs.LowLevel.Unsafe.JobRanges&,System.Int32,System.Int32&,System.Int32&)
I guess I just have to do a repro and send a report
do you typically see much performance gain on IL2CPP?
I've never been able to get it to work lol
it's not about that, I have my other reasons to use it
IL2CPP seems to have a lot of issues with DOTS now
I've reported bunch, worked around some
for Unity Physics, that's almost expected as it's a new package but you'd still think Unity would test it on all build confs, considering you have to use IL2CPP on some platforms without any other alternatives
I think it's the unsafe stuff that's the issue now, I had instant crash on debug build too if I had unsafe enabled on the build settings
and the master crash got traced back to unsafe call too
The new ITriggerEvents job and ICollisionEventsJob seem good at first, but I feel like maybe I can't parallelise them well hmm
oh man and it's missing ScheduleSingle so I can't even get around the problems
basically means command buffer is useless here
god I hate having to know the size of native collections before you use them, I don't know how many elements there are lol
I'm getting totally another issue on 2019.1 while trying to repro the IL2CPP issue
when I use convert to entity, none of the meshes render anymore on HDRP 5.16
I've had this for some meshes before too even on latest experimental engine versions
it's also purely IL2CPP issue, on mono build these all render fine
So... you tried to repro one bug and accidentally repro'd another?
yeah, I guess
still having trouble getting the repro for the original issue but I'm getting there
it doesn't help that DOTS physics samples build and run just fine with IL2CPP 😃
I mean, that's probably what they test these things with
well, moving that super simplified sample from HDRP to LWPR now triggers some crash at least
it's not at the same point in UnityPlayer but it's still in job system
@dull copper in monobehaviour land why cant you just do enititymanger.exists then hascomponent on entity? has worked great for my ui systems up till now
@low tangle that's actually what I ended up doing yesterday
but it turned out the crash wasn't from that script this time around
one of my proxy's is basically just this for a voice plugin system
public Vector3 Position
{
get
{
if (ECS.EntityManager.Exists(Head) && ECS.EntityManager.HasComponent<CopyPositionRotation>(Head))
return ECS.EntityManager.GetComponentData<CopyPositionRotation>(Head).Position;
return new Vector3();
}
}
or well, I just used component count thing but I dunno if it's safe if the entity with that ID doesn't exist
there isn't really any way to poll if entity itself exists
exists is safe with invalid id's
ah
that method is
its a bit harder in a job, you would have to open a exclusive entity transaction to use that method, but thankfully I never have to check for existance in jobs often
think buffer/component from entity structs support exist or something like that for those cases
anyway, thanks for the snippet, I'll try it if I still have issues with that script
works great for my proxys to my voice player tracker for dissonance
FromEntity structs have a exists method on them
ah, so it exists 😁
bodybuffer being a entity inside of a component data
should add a check there instead of assuming its always there
but its always there
one of the best parts of dots is you can forgo some checks because you know for a fact that entity will always be created with a valid x
unless you change logic way later to break that absolute it works great
but you do run into the fact that thats now encoded hidden logic and assumptions about the code you wont see months later
well, filed two reports now, one for the convert to entity issue with IL2CPP, another for Unity Physics crashing on master and release confs with IL2CPP
will see how this goes
while at it, could file that one issue report again that got lost in the way like month ago :p
👌🏻
Can I use materialpropertyblock with ecs rendering?
I started doing my own rendering and calling drawmeshinstanced but quickly realized i would have to deal all sorts of stuff like z ordering and culling ans gave up 😂
I found some projects on github but they were outdated
anyone know where I would go to permanently edit a package cs file?
Package cs file? You mean a file in a package? That should be under packages, if you actually get it in source form instead of a dll or something
It's under packages in the unity project, but that is the package cache and changes are overwritten when loading unity
it's all good though I think I don't need to modify atm
now I have a new question though! is writing to a dynamic buffer thread safe??
If it lets you do it at all, then it should at least be threadsafe enough that thread1 can write to [x] and thread 2 can write to [y] where y != x
I mean I just want to do buffer.Add(element) from multiple threads
where it's the same entity's buffer
It's when you (potentially) want multiple threads to write to the same location, or mix read and write stuff gets weird
I don't know what buffer's .Add does under the hood, but I reckon it is implemented to be threadsafe
I'll see if I can see in the source
And going back to permanently editing a package's cs file... you'd need to make your own version of the package, really
right, thanks
public void Add(T elem)
{
CheckWriteAccess();
int length = Length;
ResizeUninitialized(length + 1);
this[length] = elem;
}
this doesn't look threadsafe to me
hmm
Depends on what CheckWriteAccess() does
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
void CheckWriteAccess()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety0);
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety1);
#endif
}
Oh yeah, would you see
//
// Summary:
// Checks if the handle can be written to. Throws an exception if already destroyed
// or a job is currently reading or writing to the data.
//
// Parameters:
// handle:
// Safety handle.
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
public static void CheckWriteAndThrow(AtomicSafetyHandle handle);
So not safe, but there's a framework for a proper safety
wish I could just make a thraedsafe version of it...
can't lock a struct though lol
and I have a feel burst might not like lock
they have atomic writes on multihashmap
this is probably relevant here too: https://forum.unity.com/threads/feedback-wanted-mesh-scripting-api-improvements.684670/
saw that from a tweet aras did a few days ago
pretty cool for people doing mesh manipulations 😄
if I want something to just crash with an error, how would I do that from a jobsystem?
how would I read an Isharedcomponentdata in a job?
holy crap native multi hash maps are a PITA
@junior fjord maybe just try accessing a non-concurrent array in a parallel job
😄
I thought there would maybe be a planned way to let it fail
I mean something like Exception("this and that happened")
but it is a very funny way to misinterpret the question haha
god I better sleep
I'm going to have nightmares about these ridiculous multi hash maps
😄 haha yeah but at some point when you're really tired you also can get in a really nice flow
usually sure... until NMHM is required
then it will just be throwing up brick walls everywhere
making you want to tear your teeth out as a distraction from their stupidity.
night
Anyone able to help me get my head around the NativeMultiHashMap container?
As far as i see, it is an array whose entry values could be more than one per index?
public NativeArray<TValue> GetValueArray(Allocator allocator)
With this being used to recall multiple values from the hashmap in a standard nativearray?
Would i be right in thinking it can be thought of as a multidimensional array?
So, like each index of the hashmap can hold a little list of values, with the inner list having only a numbered 0+ index?
And, it also appears that an access via directly indexing first the hashmap then the inner list would not work, you'd index the hashmap, then the value returned would be the native array which you'd index independently for an actual value
Also, the capacity, is it limited to only what was set when it was initialised? And the indexes it can be referenced with, does that include a float3?
It probably works with any type that has a GetHashCode overload
https://docs.microsoft.com/en-us/dotnet/api/system.object.gethashcode?view=netframework-4.8
Ah, i see, thanks
It would then appear it is also possible to generate my own hashcodes
Yup. Just FYI, it's considered best practice to override .Equals() if you override .GetHashCode() (return a.GetHashCode() == b.GetHashCode())
If im honest, im a self taught coder and, until now, had not encountered nor used hashes - it seems that their own function will suffice.
I didnt really fully understand what it was, but it seems intrinsic to their definition that, within the realms of possibility, the hash code should return a unique identifier, and in the case of spatial mapping intended to break the large space into smaller units, the 4 billion potential combinations should suffice hehehe
I mean, even if i wrote a test case where every spatial unit was containing an entity for association to the grid, i expect my use wouldnt pass even into millions let alone billions hehe
likelyhood is approximately 1000 maximum.
at least, 1000 maximum active
@golden heron hashes arent unique. Its perfectly possible to have "hash collisions", where you have the same hash for 2 different objects. They tend to be fairly bad tho
@golden heron hashmaps are one of the most useful data structures. There are TONS of versions of hashmap. Their general idea is something of the sort of:
You have an array Data[], size doesnt matter, but its common to have the size as prime number or power-of-two.
When you add a element to the array, you calculate its hash, and then you calculate the final index by doing modulo of size
essentialy
void hash_add(Object obj){
int hash = obj.getHash();
Data[ hash % Data.Size ] = obj
}
of course, its very possible to have 2 different objects collide into the same index. Thats where shit gets hard. For those cases there are TONS of different hashmaps implementations. Everyone does it differently
i dont know how unity hashmap deals with that case 🤔
can i somehow declare meshdata inside an IJob?
i want to build procedural mesh inside a job, and i'm getting this:
InvalidOperationException: Job_RenderChunk.meshdata is not a value type. Job structs may not contain any reference types.
and i've seen people doing this before
and it WAS working for them
okay i got it
not exaclty declaring meshdata
but NativeList<Vector3>, NativeList<int> and NativeList<Vector2>
it works
gonna switch the channels tho, because i have literally no idea how triangles work here
@vagrant surge im currently encoding a replacement gethash function (not an override tho) that can return a value which IS unique, and, as a side effect, can be translated back into the original float3 it was made from. This does limit me to a range of +-500 on each of the three axes, but im also using the entire 4 billion or so available values of an in32 to do it hehe
but was that really needed or are you just making busy work for something that might be helpful in the future?
Its for a spatial partitioning system.
An effective hashing system providing unique hashes with minimal calculation will improve the ability to avoid unnecesary calculation in the collision systems
the +- 500 is fine for that, and im gonna make it so if you go outside of that basic range your position will read asif you were at the edge of the box.
for spatial partitioning you do not want unique ids
you want the id to just be the "grid coordinate"
that way you can easily get the objects inside a grid location
But if the ids are not unique, the resulting boxes wont be unique, either. Surely that results in grouping together grid locations that are not, in fact, in the same place.
thats the point
you can use that to find objects near you
its useful for boids or physics
How is it used for that?
if you check inside the boid sample the do exactly that
they use the mutli bucket feature of the hashmaps to put all fish in this cell of space
they all have real unique actual positions but only need coarse ones to hash with so you can get all the cells around you quickly
think of a oct tree but just one size leaf for everything
Is there something i could read that talks about using hashmaps this way? I tried looking for general info earlier but seemed impossoble to get a definition even
i already know some ways my own system can easily find adjacent cells and stuff anyways ;)
Its laid out in such a way if you want the cell exactly four cells to the left, one down, and three forward... easy.
or you could just hash the target cell and get all from the hash map :^)
the memory fetch is the slow part, iterating more things in a cell isn't a bad thing when part of them would be checked anyways
not sure if theres a single source
but I'd look at the boids demo
public NativeMultiHashMap<int, int> hashMap;
[BurstCompile]
[RequireComponentTag(typeof(Boid))]
struct HashPositions : IJobForEachWithEntity<LocalToWorld>
{
public NativeMultiHashMap<int, int>.Concurrent hashMap;
public float cellRadius;
public void Execute(Entity entity, int index, [ReadOnly]ref LocalToWorld localToWorld)
{
var hash = (int)math.hash(new int3(math.floor(localToWorld.Position / cellRadius)));
hashMap.Add(hash, index);
}
}
theres systems for all the stages of updating bits on all transforms
but if you want to get stuff from it theres a child entity buffer array attached to the parent
buffers are stored in seprate chunks
smaller ones iirc but yeah
chunks are basically just linear byte arrays at a fixed size
and unity does the work of reinterpeting them as whatever
c# tiny on regular registry now: https://bintray.com/unity/unity/com.unity.tiny/0.15.3-preview
so its about to pop