#archived-dots
1 messages ยท Page 75 of 1
I thought entitys didnt have normal transforms?
they dont
I have a hybrid setup that spawns normal gameobjects, those need to get updated from the ecs systems
ah i see
I imagine taking a snapshot of the entire system's data is not likely to be very quick, but i guess i should be able to take a snapshot of data from a small group of entities? I was mostly thinking towards the future when i network it
its actually pretty quick
altho, the ecs system is intended to be the server backend, it wont be transmitting much data of that available
all of it is linear memory
you could even write the whole world to disk in no time at all
nice
chunks are 16kb by default
oh, its basically preserialised, most of ecs?
so you might only have a few hundred chunks at a time
yep
they have utilitys for it as well
nice
My arrangement is never gonna need the entire system to send data tho... Just small parts of it.
thats just binary blobs of entitys loaded by jobs into another world
yeah its better to focus on what data streams you needed
Have you seen a game called master of orion?
yep great game
the original dos versions?
:)
Basically, my game is intended to be what it would be like to pilot one of those ships in a moo galaxy.
from the perspective of a pilot, not a god persona.
But, imagine moo brought to life with a background universe and economy. Like a complex rts game in slow mo running the universe, whilst players affect the balance of resources via combat or plain old mining, or trade.
sounds like eve
But the players main aim will be building ships.
well looks like my build wont upload to steam because il2cpp keeps crashing which is great at 1am. well I'm gonna head to sleep now, I'll check in tomorrow and see if anyone needs help
Well... It will be entirely pilot driven, i intend to add some cool autopilot ideas, but, when a player is playing properly, theyll be actually flying, and really aiming weapons... none of that pretend stuff hehe
Ok, sleep well! and thanks for the info :)
thanks, no problem ๐
Does anybody knows how blobAssets are working? Can I use that to give a componentData a scriptable object or so?
Using the following code in a monobehaviour: chunks[i].GetComponentObjects(targetType, entityManager) I'm getting the following error: ```NullReferenceException: Object reference not set to an instance of an object
Unity.Entities.ArchetypeManager.GetManagedObjectRange (Unity.Entities.Chunk* chunk, System.Int32 type, System.Int32& rangeStart, System.Int32& rangeLength) (at Library/PackageCache/com.unity.entities@0.0.12-preview.31/Unity.Entities/ArchetypeManager.cs:1393)
Unity.Entities.ArchetypeChunk.GetComponentObjects[T] (Unity.Entities.ArchetypeChunkComponentType`1[T] componentType, Unity.Entities.EntityManager manager) (at Library/PackageCache/com.unity.entities@0.0.12-preview.31/Unity.Entities/Iterators/ArchetypeChunkArray.cs:255)
I'm trying to iterate all entities and find any that previously had a matching component (in this case Transform) added to them via entityManager.AddComponentObject(entity, component);
I can avoid the error by doing equivalent of if( chunks[i].Archetype.GetComponentTypes(Allocator.Temp).Contains(ComponentType.ReadOnly<Transform>())).. ๐
Hi, just wondering whether there is any recent example or code snippet on how to use Barriers to add/remove components/entities from a job. Seems like the only examples I can find still use the old [Inject] syntax.
@eternal dune shouldnt PostUpdateCommands.AddComponent etc solve your problem? But remember using PostUpdateComamnds.Playback() at the end
This does work for a normal ComponentSystem, but not for a JobComponentSystem.
Actually ComponentSystem does not even exist in a JobComponent system
ahhh ok... wait a sec i need to look into my project because i know i did this somewhere xD
Oh, that would be great!
@eternal dune DMed
But i also have another ecs/dots question: I would love to have a health bar on top of my entities. How to work with ui and ecs?
you can either use hybrid to drive existing Unity UI or just do pure ECS where you control the health bar by material properties or mesh magic
since my entities are already on pure ecs i guess i should go the material way...
How do I make a system that receives two types of entities?
just give them the same component?
I want to make an enemy follow a player, so I need to know the player translate to change the enemy direction
So I need to query for entities that have EnemyTag and Direction, and entities that have PlayerTag and Translation
ummm why don't you do it as in the new ecs example?
Have a singleton that holds the information? I guess it works, but there is no ECS way of doing this?
there are ecs singletons i haven't worked with yet
plug a ToComponentDataArray or use ComponentDataFromEntity and a singleton for the playertag if its just one player
How do I convert the player to a singleton?
PlayerInput = GetSingleton<PlayerInput>()
{
var entity = em.CreateEntity(typeof(T));
em.SetName(entity, typeof(T).Name);
var group = em.CreateEntityQuery(typeof(T));
group.SetSingleton(value);
}```
This is what I use for singletons
Any tips on splitting a struct with 2 native lists inside into blittable parts that can be put into a native queue? I'm essentially doing a random walker with breadth search to generate a random path on a limited grid.
I need a native array of visited vertices and a native array of previous vertices in current path per generation snapshot.
Im currently building a Collision Detection system and im checking for collisions inside of an IJobParallelFor. The detection seems to work but i need a solution to get components from the entity. I can add components via the EntityCommandbuffer but have no way of checking if a component exists. Is there a way to do this?
You can access the component on an Entity via the EntityManager. You cannot access the EM from a job, however, so you'll have to get the Component before scheduling the job and pass it in as a field to it.
You can capture the EM in the OnCreate method via World.EntityManager, and then before scheduling your job you can grab the ComponentData, given that you have given it the correct Entity. var componentData = _entityManager.GetComponentData<T>(myEntity); (where T is the ComponentData you're looking for)
@wise drift
Ah cool thanks, yeah sadly i cant do it like this in my case, but i think i found a diffferent solution via the IjobForEachWithEntity so i can only calculate collisions between the correct entities. Thanks for the help though.
you can use GetComponentDataFromEntity so like TranslationData = GetComponentDataFromEntity<Translation>(); to pass into your job and then check via if(TranslationData.Exists(myEntity))
Is it possible to do custom sort on a ParticleSystem using a job? The Unity distance sort is not sufficient for mesh based particles, as you move through the particles or rotate the camera particles pop in and out in front of each other. The sort needs to be on closest box or sphere surface instead of center, I am writing this but finding it slow to sort because I am using get/set particle calls. I see job samples but they only involve getting or setting some of the particle attributes, not re-arranging them.
@loud hawk I've not tried it before, but there is a thread with an example using jobs to process the particles. https://forum.unity.com/threads/particle-system-c-job-system-support.529284/ (theres a feedback thread at the bottom of the post that leads to a more in-depth discussion about it)
@regal pond thanks for the link, I just came from there before posting hehehe but I did post on that link at the bottom
Ah yes. I see that now, hah. My bad. I hope you find a solution
Thanks. It would be ideal to sort pointers, I am happy to do unsafe code, but my guess is Unity does not want to expose the internals. I'm guessing I will end up writing a custom particle system not using shuriken.
@loud hawk - there may be folks in the #โจโvfx-and-particles channel that can point you to a solution, especially considering how new a lot of these jobified APIs are
@untold night thanks, posted there, fingers crossed
@eternal dune did you get the info you needed on barriers?
hypothetically speaking, would an ecs particle system be as efficient as the existing (not vfx)particle system?
I'm guessing yes, although the real benefit would probably be making (or licensing) a better-fitting particle system for your game. Ex: If you need the size of the particle or something.
I need your advice, guys.
I need to sort some entities that represents some objects in the game depending on some FLOAT return of some method that can be expansive.
Methods includes different sets of arguments those requires different sets of IComponentData or another data.
I want to write just one sort method for any cases.
So what the best way to do it u think?
I just discovered that LocalToWorld is deprecated. What should I use?
@safe gate where?
Ooooh
I see what is happening
The proxy is the only one obsolete
Because now it is automatically added
I tried adding it manually
And when the gameobject was converted, it gave me an error because the component was duplicated
yeah proxys are deprecated
It is deprecated because of the new conversion system with convert to entity. Unity has the convert method for the transform component in place which will create all necessary data components for you.
@loud hawk I faced a similar issue before and opted for a geometry shader - just in case it helps: https://www.youtube.com/watch?v=1hbcWhifuxE
First video in hopefully part of a series with Pete & Tim where we cover some of the more obscure problems we encounter. It's all with the aim of sharing kno...
@low tangle I did, thanks for checking!
np
how do I change the nth element of a dynamic buffer? [] has not setter
I guess it does? public T this[int index] { get; set; }
var myBufferAsArray = myBuffer.AsNativeArray(); // this is not allocating, just reinterpreting the dynamic buffer as a native array
I think that's by design Return a native array that aliases the buffer contents. The array is only legal to access as long as the buffer is not reallocated.
You can use ToNativeArray(Allocator) instead
Correct that's the difference between AsNativeArray and ToNativeArray. But if you want to change the buffer's content at a specific position, AsNativeArray sounds like what you want
@amber flicker Thanks for sharing. Is it possible to sort using geometry shader?
oh yes, but you should also be able to just do na[index]=4; if na is DynamicBuffer<int>?
@loud hawk I guess you'd need a Compute Shader, see e.g. https://developer.nvidia.com/gpugems/GPUGems2/gpugems2_chapter46.html
@eternal dune no that isn't possible since [] has no setter
It does, according to https://docs.unity3d.com/Packages/com.unity.entities@0.0/api/Unity.Entities.DynamicBuffer-1.html ?
public T this[int index] { get; set; }
hmm dunno why I thought differently earlier, I'll check again
thank you @eternal dune
maybe you tried something like na[i].x = 4;? That's not going to work, and I personally consistently forget about that ๐
How do I make an monobehaviour scripts know about an entity?
Like, I want the camera to follow the player. The camera is OOP and the player DOTS, how do I gap the bridge?
you will probably need to add either a CopyTransformFromGameObject or CopyTransformToGameObject component to it and then something else like make a CameraFollow component and process it in its own system
I cant figure out how both of these components work
basically both of the components work to either copy the old unity Transform to the ecs Transform(Translation, Rotation, LocalToWorld) or do the reverse
I'm sorry but I'm struggling with that. And what if I try another approach. Can the camera monobehaviour have access to read the player entity position?
It is a singleton btw
ah yeah woke up from a nap when i typed the earlier stuff, you could easily use a hybrid ComponentSystem and just access a camera's monobehaviour from there, and then get a query for the player entity
you could do something like
public class CameraSystem : ComponentSystem
{
protected EntityQuery CameraQuery;
protected Entity Player;
private ComponentDataFromEntity<Translation> TranslationData;
private ComponentDataFromEntity<Rotation> RotationData;
protected override void OnCreateManager()
{
EntityQueryDesc query = new EntityQueryDesc
{
All = new ComponentType[]{ typeof(PlayerCameraTag), typeof(Transform), typeof(Camera) }
};
CameraQuery = GetEntityQuery(query);
}
protected override void OnUpdate()
{
if (HasSingleton<PlayerTag>())
Player = GetSingletonEntity<PlayerTag>();
else
return;
Entities.With(CameraQuery).ForEach((Entity entity, Transform camTransform, Camera camera) =>
{
camera.transform.position = TranslationData[Player].Value;
camera.transform.rotation = RotationData[Player].Value;
});
}
}
no new physics package on staging yet
## [0.0.12-preview.32] - 2019-05-16
### New Features
* Added BlobBuilder which is a new API to build Blob Assets that does not require preallocating one contiguous block of memory. The BlobAllocator is now marked obsolete.
* Added versions of `IJobForEach` that support `DynamicBuffer`s
* Due to C# language contraints, these overloads needed different names. The format for these overloads follows the following structure:
* All job names begin with either `IJobForEach` or `IJobForEachEntity`
* All jobs names are then followed by an underscore `_` and a combination of letter corresponding to the parameter types of the job
* `B` - `IBufferElementData`
* `C` - `IComponentData`
* `E` - `Entity` (`IJobForEachWithEntity` only)
* All suffixes for `WithEntity` jobs begin with `E`
* All data types in a suffix are in alphabetical order
* Here is the complete list of overloads:
* `IJobForEach_C`, `IJobForEach_CC`, `IJobForEach_CCC`, `IJobForEach_CCCC`, `IJobForEach_CCCCC`, `IJobForEach_CCCCCC`
* `IJobForEach_B`, `IJobForEach_BB`, `IJobForEach_BBB`, `IJobForEach_BBBB`, `IJobForEach_BBBBB`, `IJobForEach_BBBBBB`
* `IJobForEach_BC`, `IJobForEach_BCC`, `IJobForEach_BCCC`, `IJobForEach_BCCCC`, `IJobForEach_BCCCCC`, `IJobForEach_BBC`, `IJobForEach_BBCC`, `IJobForEach_BBCCC`, `IJobForEach_BBCCCC`, `IJobForEach_BBBC`, `IJobForEach_BBBCC`, `IJobForEach_BBBCCC`, `IJobForEach_BBBCCC`, `IJobForEach_BBBBC`, `IJobForEach_BBBBCC`, `IJobForEach_BBBBBC`
* `IJobForEachWithEntity_EB`, `IJobForEachWithEntity_EBB`, `IJobForEachWithEntity_EBBB`, `IJobForEachWithEntity_EBBBB`, `IJobForEachWithEntity_EBBBBB`, `IJobForEachWithEntity_EBBBBBB`
* `IJobForEachWithEntity_EC`, `IJobForEachWithEntity_ECC`, `IJobForEachWithEntity_ECCC`, `IJobForEachWithEntity_ECCCC`, `IJobForEachWithEntity_ECCCCC`, `IJobForEachWithEntity_ECCCCCC`
* `IJobForEachWithEntity_BC`, `IJobForEachWithEntity_BCC`, `IJobForEachWithEntity_BCCC`, `IJobForEachWithEntity_BCCCC`, `IJobForEachWithEntity_BCCCCC`, `IJobForEachWithEntity_BBC`, `IJobForEachWithEntity_BBCC`, `IJobForEachWithEntity_BBCCC`, `IJobForEachWithEntity_BBCCCC`, `IJobForEachWithEntity_BBBC`, `IJobForEachWithEntity_BBBCC`, `IJobForEachWithEntity_BBBCCC`, `IJobForEachWithEntity_BBBCCC`, `IJobForEachWithEntity_BBBBC`, `IJobForEachWithEntity_BBBBCC`, `IJobForEachWithEntity_BBBBBC`
* Note that you can still use `IJobForEach` and `IJobForEachWithEntity` as before if you're using only `IComponentData`.
* EntityManager.SetEnabled API automatically enables & disables an entity or set of entities. If LinkedEntityGroup is present the whole group is enabled / disabled. Inactive game objects automatically get a LinkedEntityGroup added so that EntityManager.SetEnabled works as expected out of the box.
* Add `WithAnyReadOnly` and `WithAllReadyOnly` methods to EntityQueryBuilder to specify queries that filter on components with access type ReadOnly.
* No longer throw when the same type is in a WithAll and ForEach delegate param for ForEach queries.
* `DynamicBuffer` CopyFrom method now supports another DynamicBuffer as a parameter.
* Fixed cases that would not be handled correctly by the api updater.```
### Upgrade guide
* Usages of BlobAllocator will need to be changed to use BlobBuilder instead. The API is similar but Allocate now returns the data that can be populated:
ref var root = ref builder.ConstructRoot<MyData>();
var floatArray = builder.Allocate(3, ref root.floatArray);
floatArray[0] = 0; // root.floatArray[0] can not be used and will throw on access
* ISharedComponentData with managed fields must implement IEquatable and GetHashCode
* IComponentData and ISharedComponentData implementing IEquatable must also override GetHashCode
### Fixes
* Comparisons of managed objects (e.g. in shared components) now work as expected
* Prefabs referencing other prefabs are now supported in game object entity conversion process
* Fixed a regression where ComponentDataProxy was not working correctly on Prefabs due to a ordering issue.
* Exposed GameObjectConversionDeclarePrefabsGroup for declaring prefab references. (Must happen before any conversion systems run)
* Inactive game objects are automatically converted to be Disabled entities
* Disabled components are ignored during conversion process. Behaviour.Enabled has no direct mapping in ECS. It is recommended to Disable whole entities instead
* Warnings are now issues when asking for a GetPrimaryEntity that is not a game object that is part of the converted group. HasPrimaryEntity can be used to check if the game object is part of the converted group in case that is necessary.
* Fixed a race condition in `EntityCommandBuffer.AddBuffer()` and `EntityCommandBuffer.SetBuffer()`
that was for the new Entities obviously, Hybrid package only got this: ```md
[0.0.1-preview.12] - 2019-05-16
Fixes
- Adding/fixing
EqualsandGetHashCodefor proxy components. ```
thanks @dull copper
christ
I'm still looking at that and am just wtf
whelp, I continue to not want to use this ๐
someone missed the memo about easier usability
what_BBCCC do_BBBBC you_CCCC mean_BBCCCC?
what could go wrong
I'm reading all this and I can barely understand a word
does this make it a real pain in the ass to autocomplete too?
those overrides are for foreach and they are generated internally
people were asking for more as well
you actually dont even look at those, just have to know the ordering you want
it always matches your querys
your edits are messing with me lol
sorry, just changed the list like on the actual change log doc ๐
no worries
discord message limits ๐ฆ
I'm just up at 4am trying to read and they jump a line every time you did a edit
you said thats on staging
not release?
yeah
they sometimes skip a release
but it's never happened because bad API afaik
just some breaking issue
kinda want to play with that new blob api
been avoiding them till they got offically released
is there a long gap between staging and actual release?
sometimes they get out same day, sometimes there's day or two delay
and if there's some issue, they just make new release on staging and same process goes again
I havent look into it but what is a blob?
my vague understanding is its non blittable data that gets converted into a more easily read format for ecs, like an animated mesh. i think colliders are blobs as well
@dull copper i have been able to compile ecs with uwp and the most recent physics without error, regarding your forum post
oh wait just il2cpp not necessarily uwp maybe this is nnot the same thing
uwp is il2cpp only platform tho
yeah, was drinking my coffee when i typed that
anyway i did just try a build(with unity physics) of il2cpp non uwp and it also completed without error
@dull copper not in 2018.2
how do you guys test it?
I have it throwing errors on 2 different projects on 2019.3 but also on 2019.1 with dots repos physics samples raycast vehicle scene
I haven't tried empty scene
I haven't tried on 2019.2
(for a while at least)
my project uses unity physics for player movement, collision and raycasting for bullets and sight, its 2019.1
the error I got on 2019.3 was only on one place, and if I removed the offending range limiting tag, it built but crashed elsewhere when I ran it
on 2019.1 I got some some file inclusion issue
but it's possible the 2019.1 error isn't even related to same thing
ill be honest, i was tearing out my hair trying to get il2cpp to compile for a long time, i went and installed almost every visual studio optional package
anyways, will try to get new 2019.1 project and see what happens if I don't put anything to it, but the package
IL2CPP has worked just fine on this computer till now
my memory is a little hazy but I think 2018.3 il2cpp worked fine but I had tons of issues with 2019.1
i think it was The UWP build will always compile all four targets (X86, X64, ARMv7 and ARMv8). so i was missing a bunch of requirements
outside of uwp I dont know why there would be inclusion issues, but maybe the link.xml file?
ah preview.32 is on regular package registry now
along with collections, jobs and the hybrid renderer
that probably means new update on dots repo soon
btw, does the hybrid renderer not work with built-in renderer?
hmm 'GetPrimaryEntity(GameObject go) is a game object that was not included in the conversion. It will be ignored.' convert and inject not working in a hierarchy now?
it works together
oh, I forgot to add the hybrid package to this test project
I guess that explains why everything just vanish
dots repo updated: https://github.com/Unity-Technologies/EntityComponentSystemSamples
## Changes
* Rearranged all HelloECS samples into new HelloCube folder structure. Also renamed most types to make it clear in the Unity UI exactly what types are being used (namespaces are not typically visible in Unity).
* Moved the `Hybrid_01_FixedTimestep` to `Advanced/FixedTimestepWorkaround`.
they messed up the release notes a bit
they put this on previous release:
* Added versions of `IJobForEach` that support `DynamicBuffer`s
* Due to C# language contraints, these overloads needed different names. For example:
* `IJobForEach_BCC` is a job which takes 1 `IBufferElementData` and 2 `IComponentData`
* `IJobForEach_BBC` is a job which takes 2 `IBufferElementData` and 1 `IComponentData`
* ...etc
as for the IL2CPP issue: ```Unhandled Exception: Unity.IL2CPP.Building.BuilderFailedException: Lump_libil2cpp_icalls.cpp
C:\Unity\Unity Projects\EntityComponentSystemSamples\UnityPhysicsExamples\Temp\StagingArea\Data\il2cppOutput\lumpedcpp\Lump_libil2cpp_icalls.cpp(2): fatal error C1083: Cannot open include file: '................\2019.1.2f1\Editor\Data\il2cpp\libil2cpp\icalls\System.Configuration\System.Configuration\InternalConfigurationHost.cpp': No such file or directory```
I do have that file tho
that's not the physics package specific tho but is what I get on 2019.1.2 now ๐
maybe the path is too long?
I dunno, most people have way longer paths
for example if you got unity and hub in program files
it's pretty long project path tho
145 chars
so it's not near windows max yet
I'm currently trying to build a entity despawn system, i want it to run as the last system in each iteration so that after all calculations are done the entities can be cleaned up if they are no longer needed. Also it is necessary so that the other systems don't try to access already destroyed entities. I've already tried to mark my systems with the tag : [UpdateBefore (typeof (DespawnSystem))] . Am i missing something here or maybe is the approach wrong altogether?
Guaranteeing the order doesn't guarantee the previous job will be finished (assuming you're using jobs) - likely you need to call .Complete() on any outstanding jobs
yeah mostly using jobs. How can i check that they are completed from my despawn system? Im doing var Job = new ExampleJob{}.Schedule (this, inputDeps); Job.Complete (); inside of the OnUpdate function of the other systems.
Could it be an issue that i have some systems that are JobComponentSystems and others that are ComponentSystems?
mixing types of systems shouldn't be an issue... if you're calling complete on all your jobs it should work so it may be that the orders aren't quite right... I would create a ComponentSystemGroup (I think that's what it's called) and then use [UpdateInGroup(mainJobGroup)] then for the despawn system run it in [UpdateInGroup(despawnGroup)] and when you define those groups, do e.g. cs mainJobGroup : ComponentSystemGroup; [UpdateAfter(mainJobGroup)] despawnGroup : ComponentSystemGroup - very psuedocode
if you want to access your other systems jobs you can use system1 = entityManager.GetExistingSystem<MyFirstSystem>() then system.currentJob and inside MyFirstSystem when you do new ExampleJob, you'd say 'currentJob = new ExampleJob..' and make currentJob a public member of the system
sorry, I'm sure I could have written all of that better
@wise drift Instead of trying to manage the complexity of manually finishing jobs, have you tried simply attaching a Tag Component to mark entities you want to despawn? For example:
public struct MarkForDeletion : IComponentData {}
public struct EntityLifetime : IComponentData {
public float timeToLive;
}
// ... in different system ...
lifeTimeComponent.timeToLive += deltaTime;
if (lifeTimeComponent.timeToLive <= 0f) {
commandBuffer.AddComponent(entity, new MarkForDeletion());
commandBuffer.RemoveComponent(entity, typeof(EntityLifetime));
}
instead of relying on the order or state of a system, you could rely on the components to dictate in which order the systems should run
Yeah that's basically what i am doing right now if i understand you correctly. The problem just seems to be that the other systems try to update again while the entities are still being destroyed and as some Jobs are IJobForEachWithEntity they presumably try to access entities that are already being deleted. Now if i could somehow exclude the ones with the Despawn Tag from the IJobForeach then i think it would work too, but i haven't found a way to do that either.
have you tried [ExcludeComponent(typeof(MarkForDeletion))] as an attribute to the Job?
But yeah ive just tried the group approch and the behaviour still seems to be the same. It does work with low numbers of entities but as soon as i try to have more than 5 it seems to break
i have not tried that yet. let me see if that works
So ive tried the Tag and Exclude approach but the problem still persists. It seems to me that the next iteration gets started before the Despawn System is run completely. Is there a way to force this?
Preeeetty sure you should be able to make something a dependency on another thing, and the second thing can then .Complete() the dependency to make sure its done. Unfortunately I forgot the specifics, but I think it's system level.
@wise drift Have you tried removing the Component(s) in the system that relies on it? Like if the JobForEachWithEntity relies on FooComponent and you remove the FooComponent from that entity when it meets the conditions, does it prevent an additional iteration of that job from happening to that component?
I could but that would require a lot more jobs i think. Currently there is a System that tags the entites wich have <0 lifetime and one that tags the ones with <0 health. If i wanted to remove the specific components i would have to wirte jobs for each seperate entitie type.
but as it stands right now the job that accesses the entities wich then not get found will run before even all the entities are tagged.
Is there any right way of letting a job complete when it's done, or do I have to loop through an array jobhandles to check if they are completed?
does lightmapping not work with the hybridrenderer?
btw some interesting changes to the latest entities package:
- ISharedComponentData with managed fields must implement IEquatable and GetHashCode
- IComponentData and ISharedComponentData implementing IEquatable must also override GetHashCode
new terrain improvements will go to waste unless they get them on dots side as well
I got 2019.3 finally to build that physics test scene with IL2CPP
had to downgrade to older hybrid renderer and remove the unsupported range tag from the physics package :/
it's hardly a proper fix
I also removed some test packages and tests from the main project so could be a lot of things now
Is it possible to use MaterialPropertyBlock or similar with ECS hybrid renderer or is that still coming later on?
now that I did get it running, I tried updating to newest hybrid renderer and entities but it still crashes the runtime
it builds it fine but can't run it, instant crash after resolution selection
now I wonder if crashing because physics still use the old bloballocators that have been deprecated
well, the crash on standalone is coming from burst when using newest packages
if I disable burst from standalone build, it doesn't crash but physics are still bit wonky on spawn
Is MeshInstanceRenderSystem still slower than MeshRenderer when not taking advantage of instanced meshes?
Hi everybody! Is there a benefit to specifying that ComponentTypes are read-only when passing them to EntityManager.CreateArchetype()?
i think its to help sort out job/system dependencies
My office has scheduled a work shop with Unity engineers next week. Any topics I should grill them on?
I'm mostly interested in ecs approaches to ai and ml
id love an answer on when the animation package is coming ๐
Sure. There's a day planned for artists so I'm sure it'll come up.
We do consulting for automotive so companies will come in and throw all their new prototypes at us.
nice
I get these with newest packages on the raycast vehicle scene now even in the editor:
IndexOutOfRangeException: Index 31 is out of range of '24' Length.
IndexOutOfRangeException: Index 255 is out of range of '23' Length.
I think it's the joint solver that freaks out
it could explain why burst goes bonkers too
I guess it's just better to wait for new unity physics package if one wants to use the newest entities package
I just got ConvertEntity failed because there was no Active World when hitting play hmm
wonder if I should revert ๐
ah, I got that too on my quick test project
and putting gameobjectentity there just made things a lot worse ๐
I'm upgrading to 2019.2.0b2 to see if that helps
31 broke for me, I can only use 30 atm haha
there isn't even huge change in API so it's kinda weird
hmmm, I can use latest other things, like jobs, collections, hybrid renderer, burst 1.04 etc with entities p31
it's just when I bump the entities package up things go breaking in all directions
in my case, it could all boil down to Unity Physics package not being compatible with the newest entities tho
I'm using physics too
it's just script order causing this I think. They haven't set World.Active yet, but I don't see a way to include package scripts in project script execution order.
ah but it didn't work even if I start the gameobject as disabled then enable them
well, p31 isn't all working either on my main project :/
still crash on standalone ๐
this time it crashes on some transform function
it's not a big deal but it does slow down things
plus I always prefer having optimal builds available ๐
I would never want to find myself in position where I have to compromise if I find out last minute that the conf I've always worked towards wouldn't even run
current crash is coming from collections, but that's probably on me as I tried to get away with newest everything but entities
@dull copper I am getting away with newest everything but entities, including physics, on beta 2, with entities p30
Also, https://forum.unity.com/threads/entities-p32-world-active-is-null.680041/ maybe pitch in so unity take it seriously? lol
yeah, so did I on the ecs physics samples, but on my main project I get crash on collections
I'm not using physics samples, and I have latest collections, must be a difference in how we are using collections
yeah, just saying one project is fine with the combo and other isn't ๐
unless you are on alpha 3 with packages not available in beta 2
ah, I'm actually on alpha for both projects so it's not a difference between the two
and my 2019.1.2 refuses to build anything IL2CPP atm
wonder if the hub screwed up the install
oh I had that too so I gave up lol
yeah, I don't really care about 2019.1 at this point
just wanted to verify if things break on latest official
Hi guys, I get the benefits and how to use DOTS with gameplay related features but I wondered if someone could redirect me to any resource that would explain to me how a pure DOTS game would be structured to manage, say for instance game states (menus, levels, etc...) thanks ๐
I unfortunately don't have a resource for that, but I believe the short answer is that you safe game state, as with all state, in components in entities. So you might have a tag, GameStateEntityTagComponent, and spawn an entity with that on it on game start.
Assuming a game like Super Mario (2D), you'd then put a GameStartedComponent with the time you started a map, a GameScoreComponent with the score, and a LevelsDoneComponent and so forth on it. As a bonus, the gamestate entity with all components might be all you need to (de-)serialize to save/load the entire game (if it's fairly simple).
Obviously stuff that is saved to disk would still be saved and loaded from disk, but while loaded, data should exist in components. That's the pure ECS way, as far as I understand it. The usual caveat applies: If it's better*, then it's a perfectly valid choice to break from the best practices and paradigms.
*Easier to develop and maintain, faster, better performant; whatever counts as value to your team.**
**In the long term, the best way to do things usually 'by the rules', but if you're prototyping, or know what you need, breaking a few rules can be incredibly useful. Beware technical debt, though; can you really guarantee that you won't (re-)use that code, or that the requirements will never change?
is it even worth doing things like a menu in ecs?
seems to me like doing it the old fashioned way is simpler?
these mainly make sense when Tiny mode gets fully ported to c# and we get DOTS player builds
as then you can't have monobehaviours there if you target that kind of thing
but for anything else, it seems super early to try to do everything on pure ECS
Well yeah, menus (just GUI in general) isn't quite ECS/dots ready. I guess you could put some of the logic there (updating health bars?) but it's hard to do reactive stuff (click button, stuff happens) for now. I guess I forgot to answer that part of the question.
thanks for these advices ๐
does anyone know how to convert(and inject) a gameobject to an entity via script?
If you have any problems, this channel can usually answer quickfire questions, though for more complex stuff you might need to go to the forums. That specific question could be good on the forums if only to have centralized discussion on the topic.
Try to have concrete examples for any problems you face, though, since that makes it easier to give the right answer.
I will thankx @tawdry tree
@safe lintel There is a ConvertToEntity class. haven't used it in its current form, but I think there is some sample that does. AFAIK it runs and then destroys the original, but don't quote me on that.
https://docs.unity3d.com/Packages/com.unity.entities@0.0/api/Unity.Entities.ConvertToEntity.html
basically looking to do what converttoentity with inject via script but not sure how to create the entity in the temporary world
well, this was day wasted trying to solve the IL2CPP build
turns out that IL2CPP crashes on this https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/UnityPhysicsExamples/Assets/Common/Scripts/EntityTracker.cs#L24
I'm guessing there's some null value for either entity manager or the entity first time it runs and IL2CPP can't handle that try-catch so it just crashes
for some reason same script does work on DOTS repos physics samples even when built with IL2CPP
tbh, I'm not super happy to see that try catch there in the first place ๐
do the advanced physics samples(vehicle, charactercontroller) work in playmode? i wouldve expected them not to work given my own problems with ConvertToEntity in a hierarchy
with p31, yes
p32 breaks something with joints
at least on my end but it could be engine version too
alright gonna give upgrading project to the latest alpha and try to build to see what happens
btw, I put 10 frame delay on that entity tracker script and now it doesn't crash
it's trying to get transforms from entity that doesn't have it yet, despite the entity has been created already
don't ask me how that is possible
putting small delay fixes is but that's obviously not the right solution
physics also don't collide with anything, things just fall through ๐
(this is all mainly IL2CPP related)
well i did have that problem where stuff from entities doesnt all load at the right time
so physics starts working before colliders are loaded in
so i would offset player position by like 100 units and hope it loads in by the time it reaches the ground ๐
this is still very alpha
in a build, didnt happen in editor playmode for some reason
I dunno if I'm as optimistic as Unity is about this physics package leaving preview state this fall ๐
I haven't had much issues on mono builds
that joint issue is only one I've spotted so far
it seems like theres tons of good feedback theyre responding to in the forums which is nice
but at the same time its a small sample size of people voicing their concerns with something that is so vital to games, im kinda worried about it being finalized before it gets widespread useage
what? they said physics would leave preview this fall? lol
well, obviously they don't promise it, like they don't give hard targets usually for about anything ๐
Our goal which may or may not change is to be out of preview around Q3. ```
@minor sapphire
lol I'm not confident in this target either ๐
well project fails to compile with 2019.3 alpha and il2cpp Exception: C:\Program Files\Unity\Hub\Editor\2019.3.0a2\Editor\Data\il2cpp/build/il2cpp.exe did not run properly! not the most useful of error messages
@safe lintel when you click the error, you see the full list under it
sorry closed it shortly after i typed that, did you want to see more of the error? im submitting a repro bug report to em
nah, I don't need to know it, I know like 3-4 different fails on this atm ๐
just saying you see more info when you click it
usually the initial IL2CPP fail message doesn't tell anything of value
real info is on the longer listing
usually I'd test latest release (which I tried but it failed for another reason on IL2CPP) etc
I mean latest official Unity release
2019.1.3 just released but I failed to get IL2CPP to do anything on 2019.1.2 ๐
it's funny how hard it fails now as it's been pretty good for a long time
weird im getting a missing namespace for UnityEngine.UI in 2019.2 but not .3
it's because the change is only on 2019.2 betas atm
probably next 2019.3 alpha has the ui change as well
i wouldve expected 2019.3 to have all of 2019.2's changes?
nah, these are developed in parallel
afaik 2019.3.0a2 has been in development for quite a while
at least it has been showing a lot in older issue reports
ah ui is a package now
as for p32 conversion not working and throwing error about active world, @coarse turtle (?) posted this on the forums: https://forum.unity.com/threads/entities-p32-world-active-is-null.680041/#post-4552861
was there a lot to change?
I could upgrade mine but it wouldn't still solve the IL2CPP stuff I'm experiencing
not really on my side I didn't have as many SharedComponentDatas on my side
ah, I don't have any custom sharedcomponent, but I do use Unity Physics which may be the core issue here
it also uses the old bloballocator
at this point I think I'll just wait for Unity to upgrade the physics package
im telling you physics works for me in p32 ๐
you use joint scripts from DOTS sample repo?
oh joints no
those were the thing that freaked out for me
regular RB sim did work
and burst caused hard crash on standalone ๐
but I think it's related
I have this post with very many edits about all the issues I've encountered with recent versions: https://forum.unity.com/threads/unity-physics-discussion.646486/page-9#post-4547260
Btw @dull copper I haven't looked at the Physics package too much but is it primarily 3d physics?
yes
there will be separate 2D physics thing for DOTS
there are some snippet on that thread on how to constrain things into some axis to use it on 2D though
but this is the stateless DOTS physics engine codeveloped by Unity and Havok physics team
ah cool, I should take a look sometime soon
yea I remember that from the keynote at GDC
it's still pretty early
we just discussed that it doesn't seem likely that they'll reach stable status on Q3 like the initially planned for that package
but who knows what they've been cooking behind the curtains
right now though it still feels very alpha
ah i think that's fine, the transport layer is the same so I'm expecting some violent changes next iteration haha
yeah don't get me wrong, I do dig a lot that they are doing this
it's actually one of the best things from my POV
same here
Unity's stock physics is closed box, you can't modify how they use physx with it
which has always been huge pain for me
there's one feat on physx that Unity is not likely to implement and it's contact modifications
it took me like 1-2 days to implement that on unreal with full source access
but this new Unity Physics package has all kinds of callbacks built in now
you can modify things on all different physics engine stages which is awesome for my purposes
main issue with this new package is though that since it's stateless, there's no caching built in, and this will hurt the perf on bigger worlds and simulations
it's not something one couldn't work around but it's one big limit on the stock version
and Havok guy replied on the forums: We have a pull request going through now with a p32 upgrade. We'll post more details when available.
ah that makes sense - but yea I'll give it a shot
I'm working in 2D currently and I've just been wrapping RIgidbody2D into ECS minimally haha
wonder if this is a samples update or a package update(or both)
on the ecs side its a samples and package update
the samples are just restructured
based on the commits
i mean for that pull request quote
ah whoops mb
hmm getting this when building for 2019.2.0b2 Unexpected exception Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Unity.Transforms.Hybrid, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
@safe lintel they usually go together
if they update entities, they update dots sample repo for ecs samples, if they update physics package, they update physics samples from it
happened every time in past year or so (altho there's only been two updates for physics one)
@safe lintel oh and the comment was for physics package in general I believe
it makes no sense to update the samples only when it's clear that the physics package itself isn't fully compatible with p32
i havent delved deep into joints at all
would love to get hands on that internal repo :p
but there was a lot of stuff on the authoring side which kinda made me wonder if it was that part or if it was the actual physics package
Hello! Is a good idea to wrap an Entity in a Component? e.g:
public struct MoveInput : IComponentData {
public float2 Axis;
public Entity target;
}
The downside that I noticed is that querying by the target is not possible.
Tip! You can use triple backticks (```) before and after a message to make it a code block. if you write csharp or cs right after the first set of backticks, and then make a linebreak, you also get code highlighting. For inline code like this, use single backticks.
```csharp
public void Example(string arg){
//actual code goes here.
//I suggest using 2 spaces of indentation per level
}
```
Produces:
public void Example(string arg){
//actual code goes here.
//I suggest using 2 spaces of indentation per level
}
As for an actual answer, the entity object/class is really just a couple ids (entity id and version id), so you might be able to query if you save those directly . Don't know what the proper thing for that is to do, and if you want a better answer you might want to add some more specific as to what you're trying to accoplish
posting this here - Joachim noted there was a regression with p32 and best to stay with p31 if you happen to be running in to this issue: https://forum.unity.com/threads/0-0-12-preview-32-nativearray-is-giving-me-a-structlayout-size-error.680323/
@tawdry tree this is what i'm trying to accomplish:
joystick -> input system -> process input (move player, change its state)
So i'm not sure if it is just fine to add a InputState (isMoving, isButtonPressed) to the player entity or to create a new entity that contain the input and the owner.
ECS pushes you to add an InputStateComponent that holds the input received to the player entity and use a system to use that data
thanks @spiral cairn . Probably I was overthinking , I'll create this component sense it make things easier
Hello! I am fairly new to ECS and trying to get my head around this. I am making a simple targeting system for units. Basically a unit can target many other units. At the moment a unit is just an entity with translation. I already have a system to find which entity to target, but I want to hold on to the information. Should I make new entity for each targeting instance with a ComponentData holding the origin entity and target entity?
First I just want to draw some lines of units targeting other units.
Would this kind of approach cause problems when f.e. target unit dies and targeting should be stopped ๐ค
The only data that is needed is the positions, but from what I understood sharedComponentData is not suitable for this
you could use dynamic buffers to store potential or found targets on your unit
https://youtu.be/t11uB7Gl6m8 should help you out @twin raven
Let's see how we can Find the Closest Target in a Pure Unity ECS game. โ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=t11uB...
is there a way to use subtractive types as part of the Entities.ForEach query?
specifically, i have a reactive group and want to know when any of the required components have been removed
i used to do this with multiple queries and groups, but want i was hoping can do now is more like
Entities
.WithAll<Initialized>()
.WithAny<ComponentType.Subtractive(typeof(RequiredType1), ComponentType.Subtractive(typeof(RequiredType2), ComponentType.Subtractive(typeof(RequiredType3)>()
.ForEach((Entity entity) =>
{
PostUpdateCommands.RemoveComponent<Initialized>(entity);
});
i should say, without building the query + group separately and adding at the end
wait, can you not even do that anymore?
ah, i see we can use 'With'
but still, it'd be nice to be able to do all this in-line
aaaack, seems EntityQueryDesc cannot contain Exclude Component types ๐ฆ
Anyone know if Unity mathematics has a static magnitude function? I can't seem to find it
@odd bay check the Mathematics.math for size, length, magnitude etc
yeah, it's usually size or length
magnitude sounds like some Unity nonsense naming
(for math lib)
really?
you don't usually see that used in math libs
oh, I thought you meant in general
why is there a distinction between normalize and normalizesafe
other is faster I'd assume
normalize spits out a NaN when the vector has a magnitude of 0, while normalizesafe gives 0, 0
some want 0.0 even if it's not mathematically correct
Wouldn't you rather want 0, 0 than an error?
well, there can be cases where you want nan back in case it's not correct
instead of having to check if it's 0,0 value (which is also incorrect)
plus if you know beforehand it's never going to be NaN, you can use faster path
fair points
Hello, is there a better way to handle the player state?
var chunkPlayerInput = chunk.GetNativeArray (PlayerInputType);
var entities = chunk.GetNativeArray (EntityType);
for (var i = 0; i < chunk.Count; i++) {
var input = chunkPlayerInput[i];
var entity = entities[i];
if (chunk.Has<Idle> (IdleType) == false && input.Moving == false) {
Commands.AddComponent (chunkIndex, entity, new Idle ());
Commands.RemoveComponent (chunkIndex, entity, typeof (Walk));
}
if (chunk.Has<Walk> (WalkType) == false && input.Moving) {
Commands.AddComponent (chunkIndex, entity, new Walk ());
Commands.RemoveComponent (chunkIndex, entity, typeof (Idle));
}
};
Didn't like those toggle check :/
I would probably have a PlayerStateComponent with an enum value
enum PlayerState : int { //Explicitly use int
Idle = 0, //set explicit values...
Walking = 1, //...technically not necessary but I find it useful
}
public struct PlayerStateComponent : IComponent {
public PlayerState State;
}
I don't know if components like enums, if not just do something like
public struct PlayerStateComponent : IComponent {
public int State;
public PlayerState StateAsEnum => State as PlayerState;
public void SetState(PlayerState state) { State = state as int; }
}
Note: I think, but don't know for sure, that this is valid. If you get complaints or exceptions, use (PlayerState)State and (int)state
Thanks @tawdry tree !
@tawdry tree how would you link an animation for each state? i'm trying to follow your approach of having more properties in components
I haven't done any animation stuff, so can't really say, but in whatever driver the animations (a system? I dunno how that works) you'd grab the relevant component(s) and use that to set the animation. The simplest form would just use the state to toggle between animations, but movement in games is often more of a scale (standing->walking->running->sprinting) with lerping between animations
Can someone explain to me the use of EntityCommandBufferSystem?
I'm studying the github SpawnAndRemove example but i didn't understand the documentation in the docs:
https://docs.unity3d.com/Packages/com.unity.entities@0.0/api/Unity.Entities.EntityCommandBufferSystem.html?q=EntityCommandBufferSystem
when should i use it? everytime i want to "spawn and remove" an entity i should use it? i don't get it.
basically in a job you cant access the main thread, so the EntityCommandBufferSystem queues commands for entity creation, destruction and add/remove/set of components on the main thread
https://docs.unity3d.com/Packages/com.unity.entities@0.0/manual/entity_command_buffer.html might be more easier reading
There is an alternative: exclusive entity transaction. Whilst you still need to move the entities from one world on the main thread that is much faster than the command buffer in some regards
Just as a note
@safe lintel, @solar ridge thank you so much!
how could i make the equivelant to the FPS Controller from the standard assets in ecs. along with the parented camera and everything
physics samples has a character controller which i used as the starting point for mine
is it possible to get one of my jobs to run on the main thread for debugging purposes?
Or even, does anyone know how to get something like a stopwatch working in a job...?
ok so it turns out unity is not complaining about stopwatch usage in the job. didn't expect that as it's a class...
I don't think you should be using stopwatch within the job if you can avoid it, but also don't know if you can force it to run on the main thread. Should be able to?
Use intellisense and see what you can do on a job? ie.
var job = new SomeJob();
job. //see what intellisense suggest, I assume a .Run() or something exists.
stopwatch worked, just needed to see what was taking time in the job
run does seem to work but it's not simple cause of dependencies and all that, it likes to complain. wish I could just make everything run on main thread temporarily hmm
you can
just turn off burst compiling and safety checks to on
it wont be main thread but you can run stuff you typically wouldn't in it
Anyone got experience of partioning space for collision detection?
heh Nys, the good old collision stage
done some reading, but have not implemented
the elevator notes for what I read was something like, consider grid array for smallish spaces, quad/octree for larger spaces, and hashmapping for really large spaces
unity physics is another option with the advantage of having other people work on optimising it for you, but the disadvantage that it's really early and leaves a lot to be desired in it's current form
wants to know how much havok is going to cost...
Well, in my case, the huge majority of the space will be empty, i was thinking of using a multidimensional array, with a set up which makes the indexes defined by the position directly. So, if object exists between say (0,0,0) and say (50,50,50), its index would be 0, then on to 1 at (100,50,50) maybe, or, alternately, i could go for something a little more complex, and use nested arrays, the intention being to slice space up into say 5000,5000,5000 cubes, and for each cube containing an object, the rest of the cube has an array created, but the array doesnt exist when the cube is empty. This way, you'd have automatic placements in the structure without half as many overall entries. Of course, one system is, at a conservative estimate, around 160,000 units, circular, by 30,000 units vertically, which approximates to 30,720 cubes for a system, even at low (5000 unit) resolution. Of course, the arrays entries would be 99% empty, but still would need those entries allocated. Also, a system can contain up to maybe 600-700 objects, in approximately 15-20 aggregated groups.
in an environment where the majority of space is empty, I would be looking at hashing playing some role
Another question... Does anyone know the implications of having code setup up to use x axis as forward, how to go abour converting it to unities z as forward?
(I actually have no idea what you mean by hashing?)
oh, and thanks for the answer :)
I mean, use something like a hashmap
I dont know what that is hehe
So its like a simple array?
Dictionary<ZoneId, AreaArray>
Its a list type item? those things make my ecs crawl hehe better than makin me skin crawl tho... hehe
for me, I'm considering just something like
Dictionary<ZoneId, List<Entity>>
you've not used a dictionary before?
or say, even a HashSet?
in native collections land there is MultiHashMap
Ive use nativearrays, lists, queues, and a few other types of array but not dictionarys specifically.
which is basically a dictionary
I even used a type of array that doesnt have any idea what the data it holds is, and you gotta cast it when you retrieve, but it stores anything i forget the name tho
Object[] ๐
No, this was more complex, it was cos i was using multiple layers of arrays within arrays
var arr = new object[10];
arr[0] = new object[10];
I don't like this code but, object is anything ๐
anyway, you really need to look into Dictionary and HashSet
they are really part of the 'basic collection types everyone needs to know'
It was an arraylist, sk picked cos of its ability to hold different types.
Ok, ill look at those.
those are old and superseded by generics.
Ok, was early in my coding time mind hehe
although, there was a time when I did use arraylist
https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=netframework-4.8
See the remarks ๐ MS advising to avoid ArrayList ๐
Thats cool, the usage was clunky as hell anyways, i moved on to creating custom class structures in the particular case i had used it before.
anyway for basic spatial mapping where very sparse large space is required, consider Dictionary<ZoneId, List<Entities>>, in ECS world you would be using NativeMutliHashMap<ZoneId, Entity>
if nothing is in a zone, it doesn't exist in memory
which is good for super sparse situations
In this case, you are applying a name to the index, not to the index value, so the Zoneid, its an integer?
yeah, use an int or something
whatever you ID is ๐
<int, Entity>
<float3, Entity>
whatever you use for identifying your zones
Ok, so using the < , > is the same as < >, but you are adding two datas cos its a call not a set? Ie, its like List<Entites> = Zones[zoneid];
I that what i said is wrong then
you are defining the type of the index which is usually not necesary, its assumed to be an int
in the case of Dictionary, key is int, value is List<Entity>
for NativeMultiHashmap, key is int, value is Entity (the implementation of NativeMultiHashMap is that you can have multiple of the value)
Just a sec...
I'm just gonna talk about Dictionaries cause it's easier lol
learn that first
it's easy
then when you get it, learn NativeMultiHashMap
I know about dictionarys, i just havent used them
In regards to the nativemultihashmap - It returns more than one object per index, does this means its creating a list from abitrarily positioned objects at the point of request? Or, does it already have a list it uses directly, and manages the list when you add an object to an index which already has objects?
var peopleAges = new Dictionary<string, int>(); // key is type string, value is type int
peopleAges.Add("Bob", 44);
peopleAges.Add("John", 32);
int JohnAge = peopleAges["John"]; // not safe if "John" is not guaranteed to exist, look into TryGetValue, and Contains
I don't know about how NativeMutliHashMap works internally, but it is equivalent to a dictionary of <key, List<value>>
I have much experience with multiple languages useage of arrays, from lua's tables through pythons arrays, to c#, so i know what to look at for recognising limits and how to use them :)
I used to use some scarily complex lua tables.
for spatial grid, I used an entity("key") with dynamic buffer(list of entities at that key) instead of NMHM. faster to clear & easier to access (can be interpreted as array)
for each spatial zone
Used to save the data into files similar to .csv files, ran up to 75mb for some of them, and there was one file per sector for that game hehe
Thanks for help guys tho, @minor sapphire and @dry nymph
sngdan that is an interesting approach. so an entity moves into zone 50, it needs to find the 'zone 50' entity , and slot itself into its dynamic buffer?
Oh i didnt get thats what he meant
Makes sense, i did sorta think of that, but meant to ask if it would be a difficult way or not... can you request an entity by name?
I'm not 100% sure that's what he meant yet lol
I thought it would be slow?
There are many ways to do it and it really depends on the use case.
entities don't have names, I'm wondering on this part myself
I did this in 2D but it is really the same concept in 3D, if you just use a spatial grid (i.e. no tree structure)
oh right so you start with an array
I can explain in a minute....have to do something else quickly
this works as long as your space is not 'too large' (whatever your memory limits may be)
I have this feeling that Nys's game is 'very large' lol
Well, my thinking was quite simple, using a nested array structure in coarse resolution with an if(zones[zoneid].count == null) then area is empty
Dude you want an idea of how large? ehe
i have a single player mockup you can try?
well my reasoning for the array multi layers is that the bulkiest part of the array, the coarse layer, would always already be allocated in memory. then the smaller finer parts would be all that is reallocated
OK, back now. let's get some basic parameters first
how many entities (that can collide), what is the size of the game area and the density of entities?
Well, im aiming for the server to be running the simulation for a thousand systems, with each system being 160,000 units by 30,000 units approximately, but with nothing stoppjng players from flying off into the void.
so, big
the desnity is very low, with only systems containing players having collisions considered
how many 'active systems'?
the system may contaun up to 600-700 objects, but those will never be in more than 20 groups
deoends on the number of players, but initially consider one system as being active, ill work on duplication later
(the majority of objects are asteroids in a field moving together, plus, every object is orbiting the sun, except the ships and the sun itself)
It looks like you might be better of with a tree structure for partitioning the space. This is usually better if you can not predict certain "Hot spot areas" and if you have low density
his array or array idea was sorta trying to be a two level tree, but I'd be looking at hash map or octree in this case
im also intending to use only aabb and sphere colliders, in theory tho, not actual colliders, its gonna be pure maths
but it is also more complicated ๐ To get started it is not bad to just partition the space in equal pieces (like you described in the beginning, if I got this right)
This is what I had in 2D AABB
is it essentially a grid? but done with entities and dynamicbuffers?
Yes
well, my thoughts were based on using coarse and the medium, then fine say 5000, 1000, 10 for the unit cubes, where the final collision map would be mostly empty entries, so the object when it checks if its colliding would say "if my region has > 1 objects, check medium, if more than 1, check fine
how do you look up the right entity in this case?
I iterated through all entities every frame
(im sat outside atm cant read the screen well, ill read properly jn a mo and respond)
I mean, how do you find 'Entity Zone 5'?
just by index
is it just sitting in some NativeArray?
right
and this was faster than NMHM?
probably would be
yes - I tested about 10 different approaches (with different containers and with different degrees of parallelism)
it's essentially a grid after all, but the dynamic buffer allows you to keep memory down depending on your default size
interesting I'll have to keep this concept in mind ๐
The problem is that this is about 3-4 months back and all on old API
everything just gets twice as hard in ECS world lol
Let me try to locate the file...
How many entities are in your simulation, sngden? the pic? Looks like several thousand? And you said there are aabb boxes only for collision?
Yes it does, @minor sapphire hehe
Does the iteration of all the entitys happen on the main thread? And does an entity for each region always exist? Or only when there are objects in its region?
I found it - but I literally have not opened Unity in the last 3 months....inspector window does not open...I might have to reinstall Unity...
haha don't worry too much
The minimum of entites was 10,000 that I used (all colliding with each other) - up to 50,000 if I recall correctly - maybe I posted something in the forum as well, cant remember
cool - i dont think my computer would do so well as yours hehe
My plan is gonna be to code the game then buy a fast pc when its ready for release hehe i cant justify it till then
yes, I have a Unity installation problem ๐ฆ how do I post code here?
'''CS test '''
CS test
protected override void OnStartRunning()
{
InitGrid();
CreateNativeContainers();
// Setup Entities (Keys) with Bufferes (Values)
for (int i = 0; i < myGrid.CellCount; i++)
{
collisionBufferEntityArray[i] = EntityManager.CreateEntity(ComponentType.ReadWrite<CollisionInfoBuffer>(), ComponentType.ReadWrite<CollisionInfoBufferDummy>());
}
collisionCandidateKeys_Group = GetComponentGroup(ComponentType.ReadWrite<CollisionInfoBuffer>(), ComponentType.ReadWrite<CollisionInfoBufferDummy>());
sprite_Group = GetComponentGroup(ComponentType.ReadWrite<SpriteTag>(), ComponentType.ReadWrite<Box>());
}
{
ClearNativeContainers();
var collisionBufferCandiateFromEntity = GetBufferFromEntity<CollisionInfoBuffer>();
// Clear spatial grid - ParallelFor
jobHandle = new ClearCandidateBufferFromEntityDictionaryParallelForJob
{
collisionBufferEntityArray = collisionBufferEntityArray,
collisionBufferCandiateFromEntity = collisionBufferCandiateFromEntity
}.Schedule(collisionBufferEntityArray.Length, 1, jobHandle);
// Assign sprites to spacial grid - SINGLE IJobProcessComponentDataWithEntity
jobHandle = new SpriteToGridBufferNewApiPersistentJob
{
grid = myGrid,
keyArray = collisionBufferCandiateFromEntity,
keyIndexArray = collisionBufferEntityArray
}.ScheduleGroupSingle(sprite_Group, jobHandle);
// Check collisions per grid - ParallelFor
jobHandle = new AABBCollisionBufferToHashMapNewApiJob
{
collisionCandidates = collisionBufferCandiateFromEntity,
DistinctCollisionPairHashMap = distinctCollisionPairHashMap.ToConcurrent(),
DistinctCollisionEntityHashMap = distinctCollisionEntityHashMap.ToConcurrent()
}.ScheduleGroup(collisionCandidateKeys_Group, jobHandle);
// start processing all scheduled jobs
JobHandle.ScheduleBatchedJobs();
//jobHandle.Complete();
return jobHandle;
}```
better ๐ haha
let me see if I can edit this
ah crap...just copy it...it is old API anyway and has many workarounds (i.e. I needed a "Dummy Component" to use IProcessComponentWith Entity)
๐
protected override void OnStartRunning()
{
InitGrid();
CreateNativeContainers();
// Setup Entities (Keys) with Bufferes (Values)
for (int i = 0; i < myGrid.CellCount; i++)
{
collisionBufferEntityArray[i] = EntityManager.CreateEntity(ComponentType.ReadWrite<CollisionInfoBuffer>(), ComponentType.ReadWrite<CollisionInfoBufferDummy>());
}
collisionCandidateKeys_Group = GetComponentGroup(ComponentType.ReadWrite<CollisionInfoBuffer>(), ComponentType.ReadWrite<CollisionInfoBufferDummy>());
sprite_Group = GetComponentGroup(ComponentType.ReadWrite<SpriteTag>(), ComponentType.ReadWrite<Box>());
}
Why don't you open a forum topic with this....it is not a unique problem and maybe some others chip in
JobHandle MyUpdateJobified(JobHandle jobHandle)
{
ClearNativeContainers();
var collisionBufferCandiateFromEntity = GetBufferFromEntity<CollisionInfoBuffer>();
// Clear spatial grid - ParallelFor
jobHandle = new ClearCandidateBufferFromEntityDictionaryParallelForJob
{
collisionBufferEntityArray = collisionBufferEntityArray,
collisionBufferCandiateFromEntity = collisionBufferCandiateFromEntity
}.Schedule(collisionBufferEntityArray.Length, 1, jobHandle);
// Assign sprites to spacial grid - SINGLE IJobProcessComponentDataWithEntity
jobHandle = new SpriteToGridBufferNewApiPersistentJob
{
grid = myGrid,
keyArray = collisionBufferCandiateFromEntity,
keyIndexArray = collisionBufferEntityArray
}.ScheduleGroupSingle(sprite_Group, jobHandle);
// Check collisions per grid - ParallelFor
jobHandle = new AABBCollisionBufferToHashMapNewApiJob
{
collisionCandidates = collisionBufferCandiateFromEntity,
DistinctCollisionPairHashMap = distinctCollisionPairHashMap.ToConcurrent(),
DistinctCollisionEntityHashMap = distinctCollisionEntityHashMap.ToConcurrent()
}.ScheduleGroup(collisionCandidateKeys_Group, jobHandle);
// start processing all scheduled jobs
JobHandle.ScheduleBatchedJobs();
//jobHandle.Complete();
return jobHandle;
}
oh I was curious about your approach, I'm using unity physics for the time being
I might decide to do it a different way, but not just yet heh, focusing on AI at the moment
Nys is looking at implementing this now though
so maybe he'll start a thread?
My approach is really super simple. Spatial Grid Broad Phase + AABB. I will copy for your the Grid allocation job....then you see how it assigns to grid
[BurstCompile]
public struct SpriteToGridBufferNewApiPersistentJob : IJobProcessComponentDataWithEntity<Box>
{
[ReadOnly] public ColGrid grid;
[WriteOnly] public BufferFromEntity<CollisionInfoBuffer> keyArray;
[ReadOnly] public NativeArray<Entity> keyIndexArray;
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 pos = x + y * grid.Dim.x;
var key = keyIndexArray[pos];
keyArray[key].Add(new CollisionInfoBuffer{entity = e, box = box});
}
}
}
}
}
}
It seems strange to me as i go deep, how to inspect an Entity after i instantiate it in the world?
It is in memory and when i select the entity from my system i can see the public variables i set changing when i do an action, but the entity isn't visible in the scene.
i think it took me over a month to remember that discord code thingy ๐
use the entity debugger, i think its window > analysis > entity debugger
oh wait sounds like the second part of your sentence is doing that, you cant just select an entity in the scene like an old gameobject
you would have to make some sort of monobehaviour bridge script to relay info back and forth from the entity representation to script if you wanted to do that
Thanks @dry nymph sorry got pulled away
@safe lintel I know. I can see my entity on Entity Debugger Window. I select it and its values are ok, but it is not visible in the scene. I did the same instantiation as the "HelloCube" example number 5 did. But my cube is not showing in the scene. i don't see it.
By the fact the mesh of my prefab is in a child gameobject the Entity is not rendering it?
I don't see the RenderMesh System in my entity as the HelloCube example does.
would it be sane to use the job system for an infinite terrain generator? ๐ค
@glad solar do you have the hybrid renderer package installed in the project?
@safe lintel didn't even know about it.
I'm converting and destroying the gameobject as i go pure ECS. Does this affect it? or do i have to have it anyway?
you will need it if you are destroying gameobjects
otherwise you wont be able to render it
aaahhh... it suppose to be a dependency for Entities package. lol
Thank you so much!
\o/
Rigidbody still not in pure USC atm right?
the unity physics package is for pure ecs, and has rigidbodies
I can't figure out how to get the collisionworld in a job with unity physics
you need the BuildPhysicsWorld so like in OnCreate m_BuildPhysicsWorldSystem = World.GetOrCreateSystem<BuildPhysicsWorld>(); and then to pass into your job params CollisionWorld = m_BuildPhysicsWorldSystem.PhysicsWorld.CollisionWorld
you may or may not want PhysicsWorld.NumDynamicBodies as well, this is something im still fuzzy on why this is queried for rigidbody checking
Anyone fancy helping me to work out a rotational momentum system?
I can manage to get the turning going ok, but i want it to have a rotational speed which accelerates based on forces, done manually.
@safe lintel TY!!!
@safe lintel Thanks for helping out with that, but I'm still getting an error. When I do a CollisionWorld CastRay, I'm getting a "Slice may not be used on a restricted range array" error
what does your job look like?
struct BulletJob : IJobForEachWithEntity<BulletStats, Translation, Rotation>
{
//public EntityCommandBuffer.Concurrent commandBuffer;
public CollisionWorld world;
public float deltaTime;
public void Execute(Entity entity, int index, ref BulletStats stats, ref Translation translation, ref Rotation rotation)
{
RaycastInput raycastInput = new RaycastInput
{
Ray = new Ray { Origin = translation.Value, Direction = forward(rotation.Value) },
Filter = CollisionFilter.Default
};
RaycastHit hit = new RaycastHit();
if (world.CastRay(raycastInput, out hit))
{
//Entity hitEntity = world.Bodies[hit.RigidBodyIndex].Entity;
//commandBuffer.AddComponent(index, hitEntity, new LifeTime { Value = 0 });
}
translation.Value += forward(rotation.Value) * stats.speed * deltaTime;
}
}
i think you need to pass in the numdynamicbodies number from the collision world
where would I use numdynamicbodies though
if (hit.RigidBodyIndex < NumDynamicBodies)
Just tried it, still getting the same error
struct BulletJob : IJobForEachWithEntity<BulletStats, Translation, Rotation>
{
//public EntityCommandBuffer.Concurrent commandBuffer;
public CollisionWorld world;
public int numDynamicBodies;
public float deltaTime;
public void Execute(Entity entity, int index, ref BulletStats stats, ref Translation translation, ref Rotation rotation)
{
RaycastInput raycastInput = new RaycastInput
{
Ray = new Ray { Origin = translation.Value, Direction = forward(rotation.Value) },
Filter = CollisionFilter.Default
};
RaycastHit hit = new RaycastHit();
world.CastRay(raycastInput, out hit);
if (hit.RigidBodyIndex < numDynamicBodies)
{
//Entity hitEntity = world.Bodies[hit.RigidBodyIndex].Entity;
//commandBuffer.AddComponent(index, hitEntity, new LifeTime { Value = 0 });
}
translation.Value += forward(rotation.Value) * stats.speed * deltaTime;
}
}
Just to make sure I'm doing it right
wait can you paste the full error message?
hmm maybe try adding hit.RigidBodyIndex != -1 && hit.RigidBodyIndex < numDynamicBodies but i think i was getting nativeslice index out of range when used that
that has raycasting in the physics samples interacting with rigidbodies
ill be honest i dont see anything wrong with your code there so not really sure
public class BulletSystem : JobComponentSystem
{
//EntityCommandBufferSystem commandBufferSystem;
BuildPhysicsWorld buildPhysicsWorldSystem;
protected override void OnCreate()
{
buildPhysicsWorldSystem = World.GetOrCreateSystem<BuildPhysicsWorld>();
}
struct BulletJob : IJobForEachWithEntity<BulletStats, Translation, Rotation>
{
//public EntityCommandBuffer.Concurrent commandBuffer;
public CollisionWorld world;
public int numDynamicBodies;
public float deltaTime;
public void Execute(Entity entity, int index, ref BulletStats stats, ref Translation translation, ref Rotation rotation)
{
RaycastInput raycastInput = new RaycastInput
{
Ray = new Ray { Origin = translation.Value, Direction = forward(rotation.Value) },
Filter = CollisionFilter.Default
};
RaycastHit hit = new RaycastHit();
world.CastRay(raycastInput, out hit);
if (hit.RigidBodyIndex != - 1 && hit.RigidBodyIndex < numDynamicBodies)
{
//Entity hitEntity = world.Bodies[hit.RigidBodyIndex].Entity;
//commandBuffer.AddComponent(index, hitEntity, new LifeTime { Value = 0 });
}
translation.Value += forward(rotation.Value) * stats.speed * deltaTime;
}
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
BulletJob job = new BulletJob
{
//commandBuffer = commandBufferSystem.CreateCommandBuffer().ToConcurrent(),
world = buildPhysicsWorldSystem.PhysicsWorld.CollisionWorld,
numDynamicBodies = buildPhysicsWorldSystem.PhysicsWorld.CollisionWorld.NumBodies,
deltaTime = UnityEngine.Time.deltaTime
};
return job.Schedule(this, inputDeps);
}
}
Here's the full script this time
maybe there's something wrong with it outside of the job
maybe do World.Active.GetOrCreateSystem<BuildPhysicsWorld>();
How do you guys approuch the input with pure ECS?
I'm failling to pass the Input information from what the player press (example: Input.GetMouseButton(1);)
Can anyone point/give me an example, please?
I'm new to ECS as well, so my way may not be the best
but you're supposed to pass in the input into the job I think
since a lot of unity's old stuff only works on the main thread
So in the job struct you declare a variable such as "public bool mouseClick" and in your JobHandle when you declare your job you pass in your Input.GetMouseButton
The simple way is to grab the input in the relevant system and send it to the job, though I believe there are more robust ways to do it.
maybe the new input system will let you do these things directly in jobs rather than passing it into one
Yeah i'm trying to use ComponentSystem to get the Inputs, but when i convert the GameObject to Entity, seems ComponentSystem doesn't recognize the Entity once in memory anymore.
I need for movement. In my scene the player only move if holding right mouse button.
for imputs you dont need to go hard on the job system to begin with
so just add an Imput component to entities, and write the imput data on it from a normal system
like bjump = true, movex = 0.5 in that struct
indeed that's what i was doing
namespace Game.Data {
using UnityEngine;
public class InputData : MonoBehaviour {
public bool canMove;
}
}```
```cs
namespace Game.Systems {
using Game.Data;
using Unity.Entities;
using UnityEngine;
public class InputSystem : ComponentSystem {
protected override void OnUpdate() {
bool canMove = Input.GetMouseButton(1);
Entities.ForEach((InputData data) => {
data.canMove = canMove;
});
}
}
}```
Quite simple, but when i start my Movement System using `JobComponentSystem` and added `IConvertGameObjectToEntity`, then my input system is not working anymore.
and then i thought: maybe there is a way to handle inputs in pure ecs that isn't in github's example.
that i dont know
check the ECS debugger if your system is active
but in general what you got there is defeinitely the normal way
Sounds like a configuration/setup error
I assume you have some other system that checks canMove and actually moves the thing?
In Entity Debugger, the "Input system" is not catting it. before i convert it and instantiate as entity, it was getting it.
Does the entity have the relevant components after conversion?
'cus, you know, entities need components for the system to act on
@tawdry tree before i work on other systems, i need to make sure this one is working. right?
So, any tips to try and get a rotational momentum system going? I've gotten the limited speeds and stuff also accelerations, but im getting wierd behaviour im not sure whats causing it...
That system on its own doesn't really do much, and a mover system is dead simple.
Have you looked at the HelloECS samples? They cover this stuff.
Other than that, which components does your entity have after conversion?
(im pretty sure part of the reason it doesnt work is my system really is a mess :( )
Nysc, that's a pretty undefined question, maybe drop your code in a pasetbin or something so we can look over it? And/or refine the question
Im kinda looking for a generalised answer - somewhere i might be able to find some code that can allow me to apply an acceleration number, per axis, and limit said forces for thrust etc, and, for the speeds to accumulate and then run down like monobehaviour rigid bodies.
ill post what i have so far in a mo, but not gonna rush, let @glad solar finish ;)
@tawdry tree if the value (canMove) was changing when i click/hold the mouse button, i would be thinking in other systems. And Hello Cube from github work with static value. that's not useful for me right now.
So... the relevant physics equations for simulating angular momentum? This server is not the right place for that, but when you have that you could come back with whatever your implementation looks like? Or am I misunderstanding?
Yeah thats what i want - a manual in-betweener to take the lookrotation direct turns and start calculating them as mass and stuff, the only bit im having trouble with, is having a rotational and scaleable force applied manually.
I can handle motion, and the acquisition of force values fine.
@glad solar Have you defined a CanMove component? As far as I know it cannot convert monobehaviours for you, so the entity you end up with after conversion would have no component for the system to target
@odd bay I added readonly and some dependencies for the job(i also removed some stuff to make sure it worked) but try it with the changes(and re add your code)
https://hastebin.com/aheratopuw.cs
Hey @safe lintel! I was trying out the code for the camera that you showed me, and it is not wqorking
To begin with, it seems from your code like you might not quite understand the basics of ECS - You're supposed to have all of those (Entity, Component, System)
I actually am using it for Light, does Light work with ECS?
i dont remember what i posted ๐
When I add ConvertToEntity to a Light, everything goes dark. Does Light not work as an entity?
Sounds like it doesn't - a lot of things are not ECS ready yet
What exactly does that do, thelebaron?
does what part
@glad solar can you send a screenshot of the entity as it looks in the debugger after conversion?
I think your issue is that you try to affect CanMove MonoBehaviours, and entities cannot have MonoBehaviours.
@safe lintel well it's not throwing any errors anymore
I don't know if it works yet though
the inject thing, what does it do?
(I assume you mean convert an inject rather than convert and destroy?)
i think it should add the transform as a component when it creates an entity for the gameobject but im not sure now, never actually checked
Can someone who has actually used the GameObject to Entity stuff explain to Plinio the 101 of how that works? Ie. the minimal code for having a gameobject and ending up with an entity with a component.
I haven't used it since preview 14 or something of the ECS package, so I don't know how it works now
so the entity basically inherits only the position and orientation?
And scale, i guess
@tawdry tree yeah i'm trying to think now a way to have information from a GameObject to be pass to an Entity in memory.
You're right. it doesn't have it because it's not a component added to the entity. So i'd make that system not be a pure ECS for the sake of Input system, but now i have the issue of transfering the data to an pure ECS entity.
i really dislike the way converting gameobjects works. Should have worked like Entitas does instead
BTW, what version of the ECS and hybrid packages are you using, @glad solar ?
at least until ecs editor works
@glad solar you should look at the hello ecs setup, you create game objects with a "convert to entity" script, and component proxy scripts attached, during conversion the proxies are what defines the component datas added to the entity, and what data they have
is that what you meant to explain? Im on the newest ecs
If Plinio isn't on the newest, stuff might've changed
@tawdry tree the latest
so inject adds localtoworld, rotation and translation, on a gameobject that has a light, it might add more like a scale if I had set the gameobjects scale to be other than 1. i think it also added the light as a component(entitydebugger search for Light components shows the entity, but the debugger doesnt actually show monobehaviour components on the inspector panel)
Btw, this works for an object in a scene (converted at runtime, when you press play, or, its delayed if you start disabled until the object is enabled.) or when instantiated(same as before)
Direct link to relevant Hello ECS git:
https://github.com/Unity-https://github.com/Unity-Technologies/EntityComponentSystemSamples/tree/master/Samples/Assets/HelloCube/5. SpawnFromMonoBehaviour
thanks thelebaron
@golden heron i used IConvertGameObjectToEntity
i think thats like doing it manually
No wait, I think this might not be it, I might've been to hasty from the name
When you use a spawner it seems you can use prefabs via the method i described, and on those objects, have multiple component proxies and data that is gonna be on the entity, so its very similar to the old useage of prefabs.
Herp, spawn from monobehavior, not entity
@golden heron I copied from the example in HelloCube
namespace Game.Controllers {
using System;
using UnityEngine;
using Unity.Entities;
public class GameController : MonoBehaviour {
public GameObject playerPrefab;
private void Start() {
if (!IsAssignsOk())
return;
SpawnPlayer();
}
private void SpawnPlayer() {
Entity playerEntity = GameObjectConversionUtility.ConvertGameObjectHierarchy(playerPrefab, World.Active);
EntityManager eManager = World.Active.EntityManager;
Entity player = eManager.Instantiate(playerEntity);
}
private bool IsAssignsOk() {
return
(playerPrefab != null);
}
}
}```
I'll think a little and try a few try here
My spawner is a monobehaviour which converts at play, and the creates an entity, which gets picked up by the system which then reads the data from its components, from the proxies, and then spawns the right stuff, and destroys the spawner entity (as is done in hello ecs), and then the objects it spawns are gameobject prefabs, which are then converted to entitys, same as the spawner but with different data.
Yes, thats the code mine is based on
no wait
oh, its a player spawner
in my prefab i have the InputData on it.
i havenet tried anything with players under control yet, my implementation is data driven server backend stuff
But, if its got the right components on the entity, this should work.
Might be good to hardcode the proxy for this to offer only one spawn, instead of the usual connection to the monobehaviour variables.
well, you can do it this way too hang on
Yeah, that should be fine, i cant see why not
This is what they put on their gameobject
https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/Samples/Assets/HelloCube/2. IJobForEach/RotationSpeedAuthoring_IJobForEach.cs
This is the component created from the above monoBehaviour
https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/Samples/Assets/HelloCube/2. IJobForEach/RotationSpeed_IJobForEach.cs
i thought since the prefab have InputData, after converting it... InputSystem should detect the entity instantiated. but naaahh....
Ok, look for the entity in the debugger.
Check it has the components - disable all other entity spawning and you should be able to have just 1 entity to track
if its coming up without components something is wrong
@safe lintel thanks, adding in those readonlys fixed it
Anyways, ima post my system...
dammit... too long hehe
I know the basic comparing isnt the best idea, at the moment, its the order of rotations and stuff, once i get the numbers kinda ticking over, ill be able to make the numbers better.
(Only the portion inside the "chunk.Has(InSystemTag)" part matters, the others are under different constraints and thats working fine.
If I understand correctly, this:
//Component
public struct MyComponent : IComponentData {
public int Number;
}
//Proxy
public class MonoBehaviourMyComponentProxy : MonoBehaviour, IConvertGameObjectToEntity {
public int Number = 1;
public void Convert(Entity entity, EntityManager em, GameObjectConversionSystem convSystem){
var myComp = new MyComponent { Number = Number };
em.AddComponentData(entity, myComp);
}
}
//System
public class MyComponentSystem : ComponentSystem {
Entities.ForEach((ref MyComponent myComp) => {
if (myComp.Number != 0){
Debug.Log("Number is "+myComp.Number);
myComp.Number = 0;
}
});
}
Should be a minimal working example if you add the monobehaviour to a gameobject
Nice example :)
I just grabbed the stuff from the ECS example and stripped it down the what you see (and changed the logic because we don't need spinning cubes, just to know that the conversion works)
yep, duz wot it sez on da tin
aii, yu got da dakka?
waaaghh!
Hehe yeah, paint it red, cos red makes it go fasta!
And, apparently, to a lesser degree, yellow is good for planes, cos it makes them lighter heheheh
i was wondering, did you play eve online? with your universe sim project seems like it could be an appropriate case study
No, my inspirations come from the dim dawn of dos-time.
Ever wondered what it would be like to fly one of the ships from master of orion in the midst of that complex war of races? To play a fully 3d and immersive environment like star control's mineral scavenging and political engagement? Or maybe to have ships as modular in design as those from ascendancy, yet, pilotable, with the body of the ship itself being customisable to your preferences, and affecting the overall balance of the ship in flight...
All games from before 1995, some before 1990, and add to that a universe which has an economic behaviour built up from moving ships attached to factories with which the players can interact, affecting economic balance.
Ever heard about something like that and saluted whatever madman thought they could actually implement something that ambitious, while thinking to yourself they're gonna fail?
Well, there is a principle i hold to.
The person designing the website caught hold of it ways back, and added it to the prototype for fun.
"If you stop to think about whether or not you can, you have already failed."
As a point of reference, i already have several people eager as testers and helpers, and ive already built a single player universe. In monobehaviours tho.
Hah. But you should stop and ask if you can (or should) do it - is this something you're willing to spend however much resources it will take to do?
I had a 2000 system universe generated procedurally and explorable.
I'll do whatever it takes.
The aim is get a prototype up and running, then i can think about funding,
and here I am just trying to make an fps to the level of quake ๐คท
Hehe
To be clear, I'm not saying that you shouldn't have ambitions, but one should not go into something like that and just assume they can finish it, especially not easily.
Oh, i never said anything about "easy".
Ive also had said static universe running on a very basic multiplayer setup with handbuilt server logins and transform translations.
All i need is the entity system to stop being a bitch :D
(Excuse my language.)
(And, dont think i am taking offence, not at all :) )
I try to never take offence.
Thats how the livestock escape.
Even just design work can be massive for something like that.
As an example, take just the [the] body of the ship itself [is] customisable to your preferences, and affecting the overall balance of the ship in flight point.
How does ship shape affect flight characteristics? Do you lean towards lesser or greater effects? do you use classes (scout, fighter, heavy fighter, frigate, etc) depending on size and have variations within that, or is everything on giant sliding sclels? diminishing returns? what about balance? What about aesthetics? What about fun?
Already done :)
And it's not good to be paralyzed by the scope either
@safe lintel Changing to Convert and Injet the Light stays in place and light things up. But how can I move it? Changing its translation did not work
I have a working ship editor which can devise the average weight balance on each axis, and enable players to drag and drop or access direct transform numbers for the ship designs.
public class LightSystem : JobComponentSystem
{
[BurstCompile]
[RequireComponentTag(typeof(LightTag))]
private struct LightJob : IJobForEach<Translation>
{
public float3 PlayerTranslation;
public void Execute(ref Translation translation)
{
translation.Value = PlayerTranslation;
}
}
protected override JobHandle OnUpdate(JobHandle inputDependencies)
{
Entity playerEntity = GetEntityQuery(typeof(PlayerTag)).GetSingletonEntity();
var playerTranslation = EntityManager.GetComponentData<Translation>(playerEntity);
var job = new LightJob
{
PlayerTranslation = playerTranslation.Value
};
return job.Schedule(this, inputDependencies);
}
}
It even recentres the ships object placements so that the origin is also the centre of gravity.
I am doing this currently
you might need a CopyTransformToGameObject component on the light entity
if you want it to follow the entity
I addedd CopyTransformToGameObject and this popped
if you are using conversion you need to add it via script
Hehehe :)
I finnaly undertood what you ment the other day about CopyTransform[To/From]Gameobject
nyscersul, with your game like what does the player do? like whats a typical gameloop?
Would anyone be able to basically tell me the order id need to go through with ecs to be able to apply a rotational speed in degrees to an entity's rotation? Specifically, if i take the quaternion, and i want to add say (deltatime*float3(5,3,2)) as a rotation per frame to the quaternion? I think ive gone round in circles too much over the same ground.
how would I check if an entity already has a component, I'm trying to prevent my system from adding a specific component multiple times which causes it to throw an error
Do you mean what is the gameplay?
Sounds like it would primarily be like Elite and others 'fly around in a spaceship and fight/mine/trade/whatever'
kinda yeah, an open world mmo with some form of mission system (i have ideas of what) but generally combat/trade/manufacturing/mining gameplay as per player preference.
yeah was wondering how you structure a potential universe for interaction and progression and perhaps(or not) an ending
Those are hard to make interesting. And then there's that whole 'mmo' point
Well, suffice to say, i have some interesting ideas pertaining to universe dynamics beyond the simple economic model idea.
A core feature will be all of those dynamics will be affectable by players.
@odd bay You can use a query to check for WithNone<Component>
Entities.WithNone<YourComponent>().ForEach
initial gameplay will be, i guess, level up, get better ships, rep;ayability will come from manipulating the universe.
@odd bay ComponentDataFromEntity
ActorData = GetComponentDataFromEntity<ActorData>()
ComponentDataFromEntity<Actor> ActorData;
if(ActorData.Exists(entity))
//stuff
That said, if you make the combat satisfying that might be able to stand on its own, possibly as an arena fighter game
Having one really solid system can drive others
@safe lintel what namespace is that under
Yep, im hoping to satisfy those desires too, but im under no illusions as to how challenging a realtime space battle can be to implement over the internet.
or yeah you could structure your initial query to not have the components that you are adding
its a method from the job/componentsystem
[BurstCompile]
private struct RotateTowardsPlayerJob : IJobForEach<RotateTowardsPlayer, Translation, Rotation>
{
public float DeltaTime;
public float3 PlayerPosition;
public void Execute([ReadOnly] ref RotateTowardsPlayer rotateTowardsPlayer, [ReadOnly] ref Translation translation, ref Rotation rotation)
{
float3 direction = math.normalize(PlayerPosition - translation.Value).ZeroY();
quaternion lookRotation = quaternion.LookRotation(direction, math.up());
rotation.Value = math.nlerp(rotation.Value, lookRotation, DeltaTime * rotateTowardsPlayer.RadiansPerSecond);
}
}
@golden heron this is how I'm rotating
i need to keep away from look rotation as i need to construct the final turn not from the direction of the target but from the momentum of the built up speed
I need to get the component data from the entity in the job
you can pass it into your job
(Plus, im using that for the background entities fine :) )
I do the raycast in the job which gets the entity, then I modify the components of that entity
Maybe a better question is, if i take a quaternion, and apply a frames worth of velocity in one axis, then another, then the third, i know id need to knoe the correct order, but would this be an acceptable method to apply rotational speeds?
I don't think I can pass it in unless I create another component which holds the entity, then in another system I modify that entity
If you change the axis of the euler angles, I think there is no problem
Dont mess directly with quaterions haha
Its ugly
Ive been looking into the math, and hopefully soon itll sink in proper, but its not a quick thing to learn.
you can definitely use ComponentDataFromEntity in jobs, ive been using it a lot lately, not sure how efficient it is but its very useful
For now, i can keep track of acceleration values in sensible ways, and i just cant seem to get the rotations to work... Hmmm... Im juat gonna go bash my head against the computer for a bit, wish me luck!
but the second you sent that message now it's showing
@golden heron if you transform the rotation to euler, apply the rotation speed and transform that euler back to a quaterion, there should be no problems
i tried that, didnt work tho
i even broke it down into vectors for each axis
var local = chunkLocals[i];
var mover = chunkMovers[i];
quaternion rotation = chunkRotations[i].Value; // current Rotation
quaternion newRotation = quaternion.LookRotation(rotationSpeed.directionToDestination,
math.up());
float3 rotationDir = MathHelpers.float3Math.TranslationByQuat(new float3(0, 0, 1),
rotation);
float3 newRotationDir = rotationSpeed.directionToDestination;
float yAngle = MathHelpers.float3Math.AngleBetween
(new float3(rotationDir.x, 0, rotationDir.z),
new float3(newRotationDir.x, 0, newRotationDir.z));
float xAngle = MathHelpers.float3Math.AngleBetween
(new float3(0, rotationDir.y, rotationDir.z),
new float3(0, newRotationDir.y, newRotationDir.z));
float zAngle = MathHelpers.float3Math.AngleBetween
(new float3(rotationDir.x, rotationDir.y, 0),
new float3(newRotationDir.x, newRotationDir.y, 0));
What behaviour are you trying to accomplish?
i am tracking a rotation speed as a speed in three seperate dimensions, then want to apply the increment of the speed per frame
the code above is how i got my angles for each axis independently
The rotation speed is a float?
if i could simply achieve, "rotate by x degrees, then y degrees, then z degrees" or whatever the order should be, id be sorted
rotationspeed is a component
in here, it uses a vector (direction to destination)
I mean, how do you know how much you want the rotation to rotate?
by seperate methods - thats not the issue. The ship applies a small amount of thrust in the direction of the object on each axis, limited by weight distribution and such, and so each axis may have a different speed
Ok, so you have a float3 that represents how much each axis has to spin
the vector that it reads here is used to move towards the object in the move system fine, and also to turn via quaternion.lookrotation
exactly
rotationSpeed.rotationalVelocity
this is part of the issue tho, the system takes the vector which i know is correct, i know my methods of applying the accumulated speeds are correct, im just not getting the right turns. So, i think its how im applying the degrees per second style turning
try this
float3 velocity;
quaternion currentRotation;
quaternion desiredRotation = currentRotation * math.quaternion(velocity);
currentRotation = math.nlerp(currentRotation, desiredRotation, DeltaTime);
or possibly a local/world coordinates thing?
ill try it but i think ive tried that already. I could be wrong tho
arent you supposed to multiply the intended turn by the current rotation, due to the non-commutative nature?
Hmm, you could write a unit test for your rotation system, though that wouldn't really fix the problem. I'd run the code you use to rotate in a minimal environment to first check if it worked to, say, rotate 90 degrees along just one axis, and then increase complexity and see where it breaks
I did not understand what you meant by multiplying
Im converting the float3 you already have to a quaterion
the desired rotation is the result of a quaternion multiplication.
quaternion desiredRotation = currentRotation * math.quaternion(velocity);
quaternion = quaternion * quaternionFrom(vector3)
im fairly sure that you should multiply the intended change to the current rotation, by the current rotation
currentRotation * rotationChange != rotationChange * currentRotation
Well, I wrote the code without trying it out ๐ฐ
no worries im debugging
im... also modifying
quaternion desiredRotation = math.mul(currentRotation, MathHelpers.quaternionMath.CreateFromYawPitchRoll(yAngle, xAngle, zAngle));
oops
i wrote it, using a port of the system.numerics class source code to use float3 and quaternion from unity.mathematics
im getting more NaNs than a garden centre on a weekday.
Joachim wrote this about DOTS physics yesterday: Generally lots of threading changes are incoming soon. We did a big pass and removed every single syncpoint. It's quite awesome to see physics run and only when the objects get rendered does it have to complete the physics jobs on main thread...
seems like the assumption is that a lot of physics do run for visual purposes only
when you do physics based game however, most of your physics code depends on the last physics states where only things you couldn't care that much about is some purely visual thing
of course that comment doesn't rule out running custom physics logic on jobs, but curious what this all means
after all so far, Unity's jobified tasks have always needed to be completed on main thread so this brings up questions like do they have separate threading on physics in the future etc
but yeah, time will definitely tell this (once we get the changes)
yeah i saw that, neat but at the same time I want to know more
i would like another roadmap update or some sort of blog like state of ecs update that gives their thoughts how things are progressing, what their thoughts are with how users are using it
well how many users are really using ECS? I don't think there is that many yet
i have to imagine that they have internal teams as well as contact with people/companies outside of the forums also using it
that means they took out the handful of sync points they had for physics, there still one at the end of the frame though @dull copper
its a very good thing, it means physics is almost fully parallel
@low tangle It's quite awesome to see physics run and only when the objects get rendered does it have to complete the physics jobs on main thread suggests they don't sync to main thread for anything but that needs to get rendered, this isn't possible with job system atm at all as new jobs need to be started and completed from main thread
it also brings up questions where the custom physics sync to all this
but yeah, we can only speculate at this point as that comment is not really telling what they did there
complete the physics jobs on main thread
those jobs are the actual work that needs sync'd
ah, right
they had the physics system super messy on first release
so that just means they can now chain physics jobs properly
it had lots of systems that started jobs, ran them, completed them
then started more
instead of a good setup where it kicked off a job and exited without waiting for the job
I hope this doesn't mean they had to get rid of some of the callbacks
because it was awesome that they exposed so many stages
likely it means they refractored it like the first version of the transform system
first one was super slow, and had lots of internal completes
new one has a much better flow that syncs at really nice spots giving much better performance
I still don't get the transform job concept
I don't see Unity itself using it on any samples
(does it even exist anymore?)
do you mean IJobParallelForTransform?
yeah
thats a hybrid job
its used to loop though transforms from main unity thread, on job threads
using pointers internally
its unsafe to touch main thread transforms from job threads without
every time I see Unity needing to do tranform updates, they just seem to use normal job with translation and rotation separately
yeah thats the dots transform system
its not the same as the main thread transform
it shouldn't even be called a system
that job is for old transforms
monobehavour ones
oh right, I think I get it
I never really bothered to check the transform job as Unity didn't seem to use it, never paid attention why it was so
but that explains it, thanks ๐
np
its used for the older proxy system copy to gameobject
which is a hybrid bandaid to get transforms to/from ecs transforms
well, I have a use case for updating transforms to the old side, so I may still need to check that one out
I've got some code I could probally share actually
I cloned their systems and made my own components so I could control exactly how it updates
I hope they get the physics updates figured sooner than later
I need to hack that anyway but would be easier if their things wouldn't move around that much
I wish the timeline wasn't so dang long at the moment for full dotsifcation of the engine 
I wanna port everything to ecs
it's fine IMO, at least they are realistic about it
every legacy system feels like muck
but I'd REALLY want to get full ECS editor sooner than later
yeah def
it feels wrong to mix legacy with hybrid ๐ฆ
it's what's dragging whole DOTS behind right now
really does
i mean legacy with dots
but I have no choice with stuff like leap motion
same with animation
I dont have enough time to rewrite their entire api to ecs
so I have to make a bridge
yeah the conversion api is really pain in the ass right now
but I think its going to be less needed soon
I'd love to see roadmap update from Unite Sydney that was last week
they didn't mention any target for DOTS editor at GDC
in fact they barely mentioned it
We were excited and humbled to be given the opportunity by Unity to speak as part of their keynote at Unite Sydney in May 2019! It is a great example of how ...
first google hit from it
yeah, that's only procedural worlds part from keynote
saw that earlier but haven't seen any other material
didnt even know there was a unite sydney
there's also keynote of Unite Shanghai on the web that happened few days before Unite Sydney
or shanghai ๐
I couldn't understand half of it for obvious reasons
kinda thinking not much new dots stuff was really discussed though
but was still fun to see how they market Unity differently that side of the world
for sure
yeah, Riccitello said DOTS etc lets people to assemble engine like they want ๐
it was nicely twisted IMO
as right now you kinda have to assemble it
well it does?
I've got a little toy game where I disabled all of the unity renderes and run my own path tracer renderer
it renders data from the ecs scene
:^)
yeah but I mean, while it's nice that you can take parts you want, right now it's so early that you have no other option that pick old systems that work and mix with new things if you are brave enough
yeah for sure its still like 50% of what you need
other half you gotta really do yourself