#archived-dots
1 messages Β· Page 54 of 1
All structs are BurstCompile
It is worth noting I complete that job immediately, so, it is single thread, yes?
well your error message above is saying its' not
but you can check the profiler it will show you
or just look at the burst debugger
and find your job in that
also check if burst compilation is even on
After removing MinBy which has used lambda, I did not get that error again.
OK, I check, appreciated
yes, on
Where?
Also, uncheck safety check does not affect
for job
because running one takes overhead
comparing in nano values wil
will not make any sense
but I have watched a video, tutorial. It is perfect even for one task
most of time is spent outside of burst
It was path finding as well
smth is wrong
Thanks, I upload my code somewhere, if you had time, please , really appreciated.
and how can I find the bottleneck? add Profiler sampling and measure the duration of code blocks?
It is really slow 600ms for simple path
look at profiler, yeah
also make pure method check
with only method - complete
on job handle
to be sure it`s job problem
Re-asking my question
Hi, so I am looking at some bathc render group api code and there is a comment there // TODO: WAITING FOR THE JOB HERE! THIS IS SLOW! NEED THE MULTITHREADED FENCE VERSION! I know what a fence is but Im not understanding how to use one with the job system. Can someone please explain this?
unfortunately i dont think many people here outside kornlaks use BRG directly
most people probably just rely on hybrid renderer at this stage
I think its more of a generic jobs thing rather than brg specific unless they mean graphics fence but I dont see how it applies to that piece of code
That seems like an internal comment that someone forgot to remove, and it was probably related to some in-development version. I would suggest just disregarding that comment.
If you have any BatchRendererGroup related questions, I'm happy to help.
I do in fact since today I finally started implementing it to our system. Sadly Im out of the offuce due to a emergency. Would you mind if I dm you in a few hours.
Yeah go ahead.
Great
π₯³
anybody tried AssetPostProcessors with ECS? as soon as i declare one Entities Codegen seems to break.
is there a way to render BRG to specific texture?
I didn't notice any mention how to choose render target for it in manual
BRG does not deal with any render targets, all of that is up to the active SRP. BRG basically allows you to insert your own draws into ScriptableRenderContext.DrawRenderers calls that the SRP does.
Basically, it's not something that you use to implement completely custom render passes, it's a way to customize what gets rendered into existing render passes.
would it be possible to just render to specific texture on demand (per click for example)?
using BRG
I need it for color/id draw call for detecting mouseclicks on meshes
without physics
You should be able to implement such rendering, and it's possible to use BRG with it.
But BRG itself does not render anything, it's more like a callback for inserting draws when something else (e.g. the SRP) is rendering.
What should I research then?
I did follow manual's example. But after that it wasn't clear at all how to attach that BRG to anything
The BRG is automatically attached to all ScriptableRenderContext.DrawRenderers and ScriptableRenderContext.DrawShadows rendering, and it's not possible currently to attach it to anything else.
π€
so if I just create BRG, any SRP that exists will already render whatever it has?
Yes.
Whenever the SRP does culling, your BRG callback will get called and that allows you to decide what to render. Whenever the SRP renders, the results of your callback will get taken into account.
that is somewhat sadge, because I don't see then how I can make a separate renderer from entities.graphics
allthough
π€
Entities.Graphics is implemented using BatchRendererGroup, so it should be possible to anything that it's doing.
no I mean, what I want is separate draw call
I don't want entities that are rendered by BRG
of entities
and I don't want normal camera to render things from my BRG
You get the camera ID as an input parameter in the BRG callback, maybe you could use that?
which callback is that?
OnPerformCulling?
Yes, you get BatchCullingContext.viewID
huh
hmm, don't think that would help me though. I want to have separate draw calls on same camera anyway
If you can figure out a way to customize the SRP to render what you want, you should be able to use BRG with that rendering.
Can I use static or even static readonly fields (containers or value types) in burst time?
[BurstCompile]
public readonly struct Path
{
public static readonly Path Empty = new(new NativeArray<int3>(0, Allocator.Temp));
[BurstCompile]
public struct RoadObstacleChecker : IObstacleChecker
{
private static readonly int3 Up = (int3)math.up();
[BurstCompile]
public struct AStar
{
public const int MaxDistance = 100000000;
private readonly NativeArray<int3>.ReadOnly _directions;
public static readonly NativeArray<int3>.ReadOnly MainDirections = new NativeArray<int3>
(
new[] { (int3)math.right(), (int3)math.forward(), (int3)math.left(), (int3)math.back() },
Allocator.Persistent
).AsReadOnly();
and where should I dispose them, the persistent one? in a script with OnApplicationQuit?
I donβt think you need to worry if your application quits. Your app is a container itself, once that quits, everything is flushed whether you want to or not.
You only need to worry about memory leaks DURING runtime so you arenβt wasting memory space for other things.
Sometimes, I get this error
0,0): Burst error BC1091: External and internal calls are not allowed inside static constructors: Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle.GetTempMemoryHandle_Injected(ref Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle ret)
While compiling job: System.Void Unity.Jobs.IJobExtensions/JobStruct`1<Bitzooma.MiniCity.Utility.PathFinding.PathFindingJob>::Execute(T&,System.IntPtr,System.IntPtr,Unity.Jobs.LowLevel.Unsafe.JobRanges&,System.Int32)
at <empty>:line 0
Agree, yes
Should I use jobs system for a method which is called only once, but I want it to work through several frames? Will there be significant performance drawbacks?
Oh yeah you trying to worry about this because you are in editor and when you press stop.
yes
Sometimes, errors are vague and cannot find the line where bugs exist there excatly
statics don't work in burst but SharedStatic is a thing
JacksonDunstan.com covers game programming
.
None of them?
So, why does it return the result correctly?
and also, sometimes, I do not see any errors related to it
burst culls unused code very aggressively
maybe it works because you don't call it from extern?
I use them in my routine always
MainDirections in AStar, Up in RoadObstacleChecker , etc.
I have one for my object definitions
it was some codegen issue with namespaces beeing named too similar i think. i have no idea why it only happened when a Postprocessor was active in that assembly
the processor was completely empty. just declaring it caused it.
i didnt spent much time on debugging this.
i had something like
using Core
using UtilityAI.Core
and codegen then somehow used UtilityAI.Core.SomeComponentInCore instead of Core.SomeComponentInCore
turns out postprocessors wasnt what i needed anyways. finally got the codegen working in a manner that doesnt destroy userworkflow
Reminds me when someone uses .System namespace and everything breaks
yah i have no idea about namespace conventions tbh.
maybe I misremember what's allowed with statics. @rotund token is this allowed?
I doubt it - at the very least it's extremely weird way of doing something
surely public static readonly Path Empty = new(new NativeArray<int3>(0, Allocator.Temp)); doesnt make sense
static readonly and Temp
This one here even if it worked would just leak memory
Static readonly is instantiated per burst instance
yes, Burst auto-generates some unmanaged container for those. But you should ensure init of those is unmanaged
will manual creation of SharedStatic work better?
I guess it will
thus it's called Shared
π
There's no reason for it to be a native array
Just use a regular array
For the directions
oh man, const value types. Why is that not a thing?
Agree, it should be readonly or static readonly with persistent.
By the way, I remove them π
SharedStatic does not work for example for static readonly cutom struct types, I guess
What do you mean? they are used in jobs
Now, it is OK.
public static class PathFindingDirections
{
public static readonly NativeArray<int3>.ReadOnly MainDirections = new NativeArray<int3>
(
new[] { (int3)math.right(), (int3)math.forward(), (int3)math.left(), (int3)math.back() },
Allocator.Persistent
).AsReadOnly();
public static readonly NativeArray<int3>.ReadOnly AllDirections = new NativeArray<int3>
(
new[]
{
(int3)math.right(), (int3)math.forward(), (int3)math.left(), (int3)math.back(),
new(1, 1, 0), new(-1, 1, 0), new(0, 1, 1), new(0, 1, -1),
new(1, -1, 0), new(-1, -1, 0), new(0, -1, 1), new(0, -1, -1)
},
Allocator.Persistent
).AsReadOnly();
//...
You can use static readonly [] in jobs
Static readonly int[] test = new[] {1,2,3};
[BurstCompile]
public struct AStar
{
public const int MaxDistance = 100_000_000;
private readonly NativeArray<int3>.ReadOnly _directions;
private readonly int _length, _width, _height;
private readonly int _maxHeight;
private readonly bool _debug;
public AStar(int worldLength, int maxHeight, NativeArray<int3>.ReadOnly directions, bool debug = false)
{
directions can be set outside with static readonly ..
That isn't a job
new AStar(...,PathFindingDirections.MainDirections)
Are you just using a function pointer?
I'm not sure if you've changed it but this wasn't burst compiled
.
I am confused. Some links say you cannot use static fields in burst
[BurstCompile]
public struct PathFindingJob : IJob, IDisposable
{
[ReadOnly] private readonly int3 _sourcePoint;
[ReadOnly] private readonly int _maxDistance;
[ReadOnly] private readonly bool _returnFirstValidPath;
[ReadOnly] private AStar _aStar;
[ReadOnly] private NativeArray<int3> _targetPointArray;
[ReadOnly] private RoadTargetChecker _targetChecker;
[ReadOnly] private RoadObstacleChecker _obstacleChecker;
[ReadOnly] private RoadWeightCalculator _weightCalculator;
[WriteOnly] public NativeList<int3> Points;
[WriteOnly] public NativeList<PathStep> Steps;
public PathFindingJob
(
AStar aStar,
int3 sourcePoint,
int maxDistance,
int3[] targetPointArray,
bool returnFirstValidPath,
RoadTargetChecker targetChecker,
RoadObstacleChecker obstacleChecker,
RoadWeightCalculator weightCalculator
)
{
AStar structure is used in job PathFindingJob
I said I want static readonly with NativeArray or Path. OK
not primitive
what the
is it just me, or does this exact page load PC GPU for some unknown reason?
https://docs.unity3d.com/Packages/com.unity.burst@1.8/manual/csharp-burst-intrinsics.html
literally as I open it, my CPU usage is 13% and GPU 30%
Utility.PathFinding.PathStep[] is not supported` OK, I know it but why does it return the result?
Does it turn off burst?!
you can check with [BurstDiscard] attribute
Containers with allocator Temp should last in one frame, what about if they do not?
burst will thrown an error on compiling. game will still work, just with unbursted code
they are disposed on end of frame
My job lasts more than 1 sec but it works and return the result
WTH
If I remember correctly
Temp allocator is thread specific
it's also stack memory
I think?
probably runs on main thread
main thread Temp memory is different?
what? Is he allocating it outside of job?
No, it is inside
but that sh.. job is time consuming
π
I do not know why it takes time to check around 350000 nodes with some condition checks, weight calculation,..
I"m trying to upgrade to ecs 1.0 and there's a step which I can't seem to get working. It looks like I only have access to Entities 1.0.0-exp.12. How do I get 1.0.0-pre.15? Or how can I find the documentation for 1.0.0-exp12?
LocalTransform doesn't seem to exist
Allocator.Temp is indeed thread local.
The allocation is not stack based, as of 2022.1 it uses a bump allocator that is reset based on the current scope. Most temp allocations are reset on the next player update. For jobs, you can allocate using temp inside your Execute as we provide a new temp scope for allocations that live only for the scope of the Execute method itself. And indeed, since temp allocations are thread local, we fail scheduling any native containers that use Allocator.Temp as you are almost certainly guaranteed to have problems if you refer to temp memory from another thread
Using Allocator.Temp inside Execute is encouraged if you really need to allocate (best to avoid allocations inside a job when possible but I understand that isn't always the case). The temp allocation will be quite quick since it usually amounts to a pointer addition rather than fetching a new block of memory from the heap.
And since it is thread local, there is no contention on such an allocation unlike TempJob which can be quite slow but provides different lifetime guarantees (4 frames for the alloc before we tell you you likely forgot to free your allocation)
Speaking of TempJob is there really many use cases for it now over the WorldAllocator?
As far as I can see the only downside of WorldAllocator is it effectively doubles your memory usage which shouldn't be an issue for regular allocations and large frequent allocations should probably be cached in persistent
(Obviously it's still needed if you aren't using Entities)
Testing purposes I guess. I've been using it a lot outside entities.
And if you want immediate disposal following job completion, only tempjob and persistant allow for that [Deallocate]
also i've always wondered about Temp fallback
From what I understand each temp block (by default) is 256KB in worker threads and 16MB on main thread, how many blocks can we have before we fallback? I believe it mentions for TempJob the number is 64 but doesn't mention it for Temp, so I've been assuming it's the same but not certain.
And what allocator is actually used for fallback? Does it go to the shared thread temp allocator?
do you mean [DeallocateOnJobCompletion] because if so, that is one of the legacy features i strongly wish unity would deprecate and remove
up there on features that cause the most unexpected bugs in a team
just cos that gets overlooked when figuring out inproperly disposing things? or some other reason?
it's magic and completely obscure from looking at the flow of the system
someone wants to insert or remove a job, rearrange them etc
suddenly it's disposing at wrong time or not disposing at all
yeah i can see that being a problem in a team
made significantly worse if there are conditional scheduling paths
so that sure maybe it works for them without warning/error but push it to master and next play test the game is crashing and the play test is wasted
apart from that, it's inconsistent because it only works on NativeArray
totally feasible for someone to glance at a system, see all these native lists/hashmaps etc being disposed at end and notice the arrays were missing and think they are fixing it by adding a dispose to them
it's from the days of entities [Inject] where everything was magic and I just don't think it belongs anymore (maybe if it supported all containers there could be an argument, i'd still probably avoid it though)
but yeah no real big deal if others want to suffer with it since I can just ban it projects I manage as it's not required
thankfully with world allocator now i don't even need to worry about this as there's rarely anything to dispose anymore after a job
How to get points with unknown length in job parallel for for each index? How to store it?
NativeHashMap with Native List does not work clearly
Are you wanting to write an arbitrary set of data per thread?
If so NativeStream is your friend
Otherwise NativeMultiHashMap is a mostly a replacement for dictionary<Key, List<Value>>
Native multi hash map
The problem is about the order
points for each chunk index are ordered
I want
index 0 : points 0 with size s0
index 1: points 1 with size s1
...
index n: points n
It is the output of job parallel for
Sounds like you want native stream
while installing entities 1.0 is it normal to get a bunch of burst internal errors?
Something like it
public void Execute(int index)
{
var pathResult = _aStar.FindPath
(
_sourcePoint,
_maxDistance,
_targetPointArray[index],
_targetChecker,
_obstacleChecker,
_weightCalculator
);
if (pathResult.Path.Points.Length > 0)
{
if(index==0)
Points1.AddRange(pathResult.Path.Points);
else if(index==1)
Points2.AddRange(pathResult.Path.Points);
else if(index==2)
Points3.AddRange(pathResult.Path.Points);
}
Then, between Points1,...N select the one that it has the shortest len.
It works but ..
I did not understand how I can use NativeStream
In each step, I get a collection, how can I add them in native stream sequentially?
usually this happens on burst version change
ah ok cool!
unity editor must be restarted after a burst version change so give it a restart
and hope it goes away
ok thanks!
https://docs.unity3d.com/Packages/com.unity.collections@1.4/api/Unity.Collections.NativeStream.Writer.html#Unity_Collections_NativeStream_Writer_BeginForEachIndex_System_Int32_ to ready the writer for your particular index
https://docs.unity3d.com/Packages/com.unity.collections@1.4/api/Unity.Collections.NativeStream.Writer.html#Unity_Collections_NativeStream_Writer_Write__1___0_ to write one element
likewise to read from a stream it's
https://docs.unity3d.com/Packages/com.unity.collections@1.4/api/Unity.Collections.NativeStream.Reader.html#Unity_Collections_NativeStream_Reader_BeginForEachIndex_System_Int32_
followed by https://docs.unity3d.com/Packages/com.unity.collections@1.4/api/Unity.Collections.NativeStream.Reader.html#Unity_Collections_NativeStream_Reader_Read__1 to read each item
im quite a noob at ecs and dots and all that stuff, and im trying to convert some stuff from gameobjects to entities, but im a little stumped by the component system of ecs, i use a lot of non blittable and non primitive custom structs and arrays of custom structs, would i use a managed component to store this kinda stuff, or is there a better component type for this sort of thing?
yeah if you must store managed data it's usually best to probably store it on a managed component (class icd)
but you can also store it directly on the entity with addcomponentobject
if it's like something specific/unique (animator)
ok thanks for the info!
actually now that im thinking about it, all of my custom struct nonsense is just to dictate when and where the entity should be spawned, i could just get a monobehaviour to pass that information to a systembase perhaps? (if system bases still exist in 1.0)
what kind of information?
a prefab (do entity prefabs exist?), and a location, think that is about all the info the system base would need, and perhaps which chunk it belongs to, but that can just be easilly calculated from the position, the monobehaviour can work out all that info, send it to the system base (once again are they still used in 1.0?) and then the system base can deal with instantiating the entity prefab and placing it wherever it belongs
entity prefabs are stored in subscenes
you don't need mono in any step of this
ooh subscenes, i've heard of them, never used one before, ill definitely check them out
how so?
why would you?
my structs refuse to be accepted by entity components, and unless 1.0 added an inspector to system bases (do they still exist in 1.0?) then monobehaviour seems like the only choice
what structs?
essentially some structs that say what biomes appear in what circumstances, and if so what are the chances for different prefabs to be chosen to spawn in any given location
it makes it really nice and easy in the inspector to add and remove biomes, and i dont see an easy way to put it in an ecs component, unless there is something else for this kind of thing
ahem
Baking
ah baking, i've heard of it a lot since 1.0 got released, guessing it is new? I'll look it up quickly thanks!
what is conversion, i dont think i've used that before either?
never heard of authoing components?
somehow nope
ah thankyou i shall quickly skim that!
ooh this is fascinating, this looks like it would allow creating of entities from a monobehaviour, potentially skipping the pain of a systembase, thanks so much!
ok so if i have this correctly, i could use all my structs in the monobehaviour, then use a baker to create entities from that monobehaviour, right, or have i misunderstood something?
just follow everything manual did
and add go inside subscene
add to that go that mono
and close subscene
and then find it in hierarchy to see result
no clue what that means, sorry im still quite used to my nooby way of doing things back in the 2021 versions of ecs, 1.0 seems to be quite a stepup in complexity, but thanks so much for all the help, ill mess around and see what i can get working!
Not sure if your question was answered, but the pre.15 packages should be available if you have to 2022.2.0f1 installed
also is there an inspector for system bases yet, or still not?
hey did the entity manager get removed in 1.0 or did it change name, or is the 1.0 manual keeping it hidden for some reason?
aha found it finally in script, but the manual page just isn't there, infact the latest manual page i could find was 0.1, the search function just kept giving me no results, and google wasnt helping neither, how unusual
Can't we get the number of items for each buffer in NativeStream.Reader?
Buffer1 : n1 items
Buffer2 : n2 items
...
reader.ItemCount(bufferIndex)
definitely not - the stream is meant to be readable while being written to in parallel
You can always store the counts you want in a separate NativeArray
yes, it is my way, thanks
InvalidOperationException: PathFindingJob.PointStream is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.
If I add [ReadOnly] to PointStream, I get another error, you write it :/
If I define the writer as field as well, it says you cannot define same container (aliasing)
and outside the job
_jobHandle = job.Schedule(roadPoints.Length, 1);
_jobHandle.Complete();
var s = job.Steps;
var (point, pointIndex) = job.PointCountForEach.MinBy(p => p);
var points = new int3[job.PointCountForEach[pointIndex]];
var reader = job.PointStream.AsReader();
reader.BeginForEachIndex(pointIndex);
for (var j = 0; j < points.Length; j++)
{
points[i] = reader.Read<int3>();
}
reader.EndForEachIndex();
declare the field as the appropriate type with the appropriate attributes
[WriteOnly]
public NativeStream.Writer PointStream;```
So, how can I read it?
outside the job
you're not reading it in that job
I'm talking about inside the job that writes it
in the job that reads it you want a NativeStream.Reader
do this
in the job
outside the job you can do whatever you want
yes but how can I read from Writer? convert to Stream?
you can't read from writer
you never need to
writers are for writing
.
what about it
in the job you declare NativeStream.Writer
outside the job you create the stream
and pass it into the job with myStream.AsWriter()
yes, now, I get it, thanks.
My trouble was I create Stream inside the job
So, generally it is bad to send data and then create natives in job ctor.
I should change them :/
Yes it's bad especially because then where the heck are you gonna clean up (dispose) the native collections?
public struct JobA: IJob, IDisposable{
public JobA(int3[] array){
_nativeArray = new NativeArray<int3>(,..);
}
public void Dispose(){
_nativeArray.Dispose();
}
}
using var job = new JobA(...);
ok but generally you need to use the array outside the job
so... it doesn't make sense to tie the array's lifecycle to the job's
often they're used across multiple jobs
Can I stop a parallel for job in specific situation? for example when getting the first result then stop it entirely?
or it is better to use JobHandle.CompleteAll? is there an API for example CompleteAny?
For independant routines, should we use IJobParallelFor or JobHandle.CompleteAll?
I don't think you need job then
Can I call SystemAPI.SetSingleton inside a job? Specifically Job.WithCode
Hi everyone! I'm currently trying to follow the ecs_tutorial for Entities 1.0 and I can't get past step 12. Even though I replaced LocalToWorldTransform with LocalTransform, I can't get the cannon balls to spawn every frame as shown in the step 13 gif. Is there anything else that needs to be modified that I am not aware of?
also modified this part
ECB.SetComponent(instance, new LocalToWorldTransform { Value = cannonBallTransform });
with:
ECB.SetComponent(instance, new LocalTransform { Position = cannonBallTransform.Position, Scale = cannonBallTransform.Scale });
You mean generally, running one job with burst job is not faster than the version without burst job?
I thought Burst can optimize it even for one job
jobs are a way to multithread smth
you don't need jobs if you don't need it
and since you mentioned early return, I think all you want is just bursted method call
Currently there is no AspectLookup you can pass to an IJobEntity correct?
https://www.youtube.com/watch?v=1bO1FdEThnU
I am surprised how he could reach that result.
However, my code is more expensive, it is 3d, 12 directions (neighbors).
The world size: 32,32,32
Checked nodes: 380,000
Many checks to detect an obstacle but simple, weight calculation.
But I have changed it to simple return false for obstacles and g=g+1 for weights. The result almost the same.
To find there is no valid path (search the entire world): Duration is around 2-3 seconds.
Target points are 5 for each request and then it finds the shortest path between these 5 target points. By jobs, it is almost 2-3 seconds. It is OK but the routine itself is heavy (2-3 sec)
Also, it is chunk based
β
Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=1bO1FdEThnU
Let's implement Pathfinding in Unity DOTS, we're going to write everything in a Data Oriented way (Structs) in order to benefit from massive performance!
Here's the follow up video covering Pathfinding in Unity ECS
https://www.youtube.com/watch?v=ubUPVu...
never mind... the tutorial just got updated; I'll check that out π
Not quite, there's MyAspect.Lookup - It's a little weird, but it is there π
Does anyone have an experience about it?
I have defined my nativelist as Temp native container in my job. It works although It takes more than 1 frame.
IJobParallelFor, with 5 jobs
openList and closeList
well
doubt this method runs within multiple frames tbh
did you check with profiler?
What do you mean? while loop? it is heavy, yes.
But did you check it with profiler?
It takes 2-3 seconds FindPath when there is no path
yes profiler
in Job workers
2-3 seconds for each
5 job workers
I take a picture, wait please
Well that works only for the TransfromAspect. It seems that something is going wrong for my custom aspects, as I receive a contains non-value type field, probably something going wrong with the code-gen?
(passing the lookup through)
new MyCustomAspect.Lookup(ref state, false)
thanks I'll take a look
I assume you mean 2022.2.1f1
I used 1.0.0-pre.15 packages on 2022.2.0f1.
does 2022.2.0f1 exist?
I think its still in dev
ok. Should I continue with 2022.2.0b16? or should I wait for 2022.2.0f1? or should I get 2022.2.1f1... I'm so confused. what's the recomended version for ecs 1.0 dev right now?
from what I see, it's just spread out as batches
not actually running through frames
It is worth noting
I create 5 jobs (5 target points) and schedule it using Parallel Job For(5,1) and find the shortest one after getting all
It is inside a for loop in main thread loop over each source point (In my example, it is 8)
Yes, otherwise 2022.2.1f1 wouldn't exist.
where do I get it?
Why do you want 2022.2.0f1 when we now have 2022.2.1f1?
that answers my question. thank you
You should use the latest stable Unity 2022 release from now on, no more need for a beta version since 2022.2.0f1 was released.
Just found out about Physics Joints. Trying to get started on this, but not sure how to approach it from Authoring perspective. When I add the legacy joint, it doesn't convert. So I assume this can only be done via script? If so can someone give me a quick boilerplate on the essentials I need to keep in mind and what component(s) I need for this to work?
Ok, I see there is PhysicsJoint.Create[JointType](). But looking at the fields, I haven't the slightest clue how to connect two entities together with this.
Yeah I see very limited docs about this, especially for 1.0. If there is a tutorial page or video anyone knows of to get the basics started, I'd really appreciate a point in the right direction.
yeah, they have samples with full ragdoll example
could be interesting for you
It most definitely will. If you have link on hand, send it.
NetCode: Should entities sent through RPC command automatically remap? Currently on the receiving side I simply get an Entity.Null
yes, they should
i had to remap them manually a long time ago but that's been added afaik
is it referencing a ghost entity?
If an entity is deferred, could it still exist and I just am holding a deferred reference? One of the entities is still deferred (Index: -1)
Is it possible to detect if entity is defered, and to look for its actual entity?
From an entityCommandBuffer
You can create a special buffer for this. And use ecb.AppendToBuffer(yourDeferedEntity). and on next frame it will be it's real entity id.
Thanks, I'll look into this. If I can't get it to work, maybe I can just index lookup.
AppendToBuffer<T>(Entity, T)
Appends a single element to the end of a dynamic buffer component.
Declaration
public void AppendToBuffer<T>(Entity e, T element)
where T : struct, IBufferElementData
Parameters
Type Name Description
Entity e
The entity to which the dynamic buffer belongs.
T element
The new element to add to the DynamicBuffer<T> component.
If the documentation is correct, this is for appending buffers.
I'm looking to simply get the entity reference. I already have my buffers and components working fine.
Honestly I find it cute when I google for answers and my own threads come up: https://www.reddit.com/r/Unity3D/comments/psq66d/know_the_error_all_entities_passed_to/
0 votes and 1 comment so far on Reddit
That was a very hard problem, but solved. I think I'm on an easy problem trying to deal with this reference, but I'm on brain lag and apathy of the end of a long project. π
Lets say I have Entity e71 = gff.spawnCommandBufferQplus(blah blah blah);
I can't just store e71 into a global array as it is a reference
Is the code: ecb.AppendToBuffer(e71); ?
Append to buffer takes 3 arguments public void AppendToBuffer<T>(int sortKey, Entity e, T element) where T : struct, IBufferElementData;
Hey so I read about the Unity jobs system and am rather confused as to how it's intended to be used. I see that it's async and/or multithreaded, similar to tasks or threads. However, you're intended to use Complete which will block the main thread until the job is complete. This makes sense for parallelized jobs I suppose, but it also seems like this is the intention for a singular job.
Why bother run a singular task on a job and wait in the main thread instead of awaiting a task?
I know what you are looking for, but you will not be able to get the entity reference on the same frame. You can either append that deferred entity to a buffer, or you can Add/Set[Component] to another entity that has a field for that deferred entity. Then on the next frame when you read it, it will be set proper. But you can't "hold" on to it as a reference because it's an struct (unmanaged), when you retrieve it, you only retrieve a copy of it and not a reference to it.
For the buffer approach, you will need to create something like public struct DeferredEntityElement : IBufferElementData with a field public Entity Entity;. Then when you have your deferredEntity, you can ecb.AppendToBuffer(entityThatHasBuffer, new DeferredEntityElement { Entity = deferredEntity });
And on the next frame you can retrieve look up that buffer and it will no longer be deferred.
Ok man, I appreciate the time you took to type that out. I'll consider and look into it deeply.
I just loaded the DOTS sample project. And Getting a whole lotta errors. Let's start with The type or namespace name 'LocalTransform' could not be found (are you missing a using directive or an assembly reference?).
Is LocalTransform obsolete here, am I using the wrong version (which is the latest entities version). Can someone help me get their sample project up and running so I can examine it closer?
i have a sample project if ,51 is ok
want it?
No, I need 1.0.
kk
I have a collectable Entity (coin) that I have a distance check to a regular character transform (mono) to see if they picked up the coin. Once a coin has been picked up what's the proper way to feed that back into a mono system the amount of coins picked up? For things like UI, shops, that don't live in the Entity sub scene.
You need to be on the 22. unity version.
It is but somehow I get a null entity on the client, might be a bug introduced in 1.0. Iβm pretty sure it worked before.
Ok, I got the joints to actually interact. But I'm having a hard time understanding the design. I am trying to PhysicsJoint.CreateFixed but I'm not understanding what to put into bodyA and bodyB. Must they be both in local space, or world space? Or one in world and other is local to that world?
I presume you disable or destroy the coin entities in a job? You could feed a NativeReference<int> CoinsPickedUpThisFrame into the job & increment it. This doesn't work with ScheduleParallel, but it does work with a normal Schedule. Then in your UI you check the NativeReference every frame to check how many coins were picked up. Since you're checking CoinsPickedUpThisFrame on the main thread while the job may be running you need to either complete it OR you could double buffer the CoinsPickedUpThisFrame (this involves having 2 NativeReferences & swapping them each frame, this would then introduce a single frame of latency). Completing the job shouldn't be an issue if you ensure your UI updates a few ms later than your CoinSystem.
You could do the same with a CoinsPickedUpThisFrame component on an entity & pass that entity + a ComponentLookup into the job. Then you'd grab the component from the entity inside your UI code.
And when I apply the joint, it always snaps one of the items to float3.zero world position.
Docs say for BodyFrameA Specifies a reference point and orientation in the space of body A. and BodyFrameB Specifies a target point and orientation in the space of body B.. Is reference point and target point the same thing? Or do they mean different things here?
Is there a better way any way to set up a listener? I don't want the coin amount directly fed into the ui I'll need it in a coin manager for the amount the user will have for buying things as well. The ui will just act as an example I needed to explain.
Ah I discovered something, I was referencing a ghost prefab, it works while referencing an entity which is alive on the server/client side, but not if the entity referenced is a prefab.
Now the question is, if that is intended or not
Is there a better way any way to set up
Well, that makes sense. The prefab reference can be acquired in other ways.
Entity ids are just ints right ? So could we theoretically spawn in like 2,147,483,647 entities ?
Why isnt it like a 3 byte sized int and the last byte is used for the version ? ^^
I mean 16 million possible entities is still a lot... or would 16 mil entities be some sort of bottleneck for some games or simulations ?
yeah good question, int as version is probably overshooting it
i also find the size of entity annoying. 8 bytes is too much. 6 bytes would go a long way
but unity played it safe and i can respect that
Thats also what i thought ^^ The last byte could fit the version, therefore a entity could have up to 255 versions which is still great.
Do you think a limit of 3 byte entities ( 16 mill entities ) and one byte for the version ,could be a bottleneck for some games or simulations ? I legit have no idea
The maximum number of entities in a World is 134,217,728.
Not sure why this is the limit but you can check the source code: k_MaximumEntitiesPerWorld in EntityComponentStore.cs
So it's not using all the indices anyway. (It is using the negative indices for EntityCommandBuffers. So in your example that'd come to 8million entities & 255 versions.)
255 versions feels too flaky because it's designed to just wrap around.
My character can pick up an item (parents to character hand, disables physics). Then if that item can be attached to another item, the character can do that too. I successfully got them both to attach via Joint system.
But when I pick up any of the attached items, I get some funky behavior. I used fixed joint, but it doesnβt feel fixed. If I pick up one item, the other will go with it, but I pick up the other and the first one does go with it.
Jason, I couldn't get it
public static Entity spawnCommandBufferQ(int parallel_Position, Entity e2)
{
Entity e;
e = ecb.Instantiate(parallel_Position, e2);
//HOW DO I keep e to use in future frames? I know you say the reference isn't held, but I'm not sure the syntax to hold it
return e;
}
Entity is also a "component" stored in archetype chunks right? It should be padded to 8 bytes to ensure the 4-byte ID's alignment anyway then.
I don't know if there is necessarily padding at the end of a single struct in C#, but there should be for array elements.
With correct alignment (smaller data types at the end) padding doesn't occur.
How?
it's like byte then int -> 8 bytes. but int then byte -> 5 bytes
// entities[0]
0x0: int
0x4: short
// entities[1]
0x6: int // misaligned
why would that matter?
Aren't there arrays of Entitys in archetype chunks?
there are but what would make them misalign? maybe you would get an odd number within a cache line but I honestly think that wouldn't matter in any way
int, short, int, one of the ints has to be misaligned.
Well, would be misaligned if there weren't padding between structs as array elements.
hm, are you assuming every struct has to follow a certain byte size?
What does that mean?
what does misaligned mean? π
Address of first byte isn't a multiple of type size in bytes.
A 4-byte integer at a memory address that isn't a multiple of 4 is misaligned.
ok, thanks, I get your point.
do you know how crucial that still is for modern cpu? with cache line sizes of 64 bytes this seems hardly relevant.
For performance?
yeah
On x64 I think the performance penalty is minimal, except maybe simd instructions
let me check
It looks like with the caveat that certain instruction variants require aligned memory, there's almost no performance difference
on x64
thanks! good to know. why is int then byte not padded then? it seems to fall into the same problem area as byte then int
Are you sure it isn't padded when you have an array of those structs?
For a single variable, maybe C# is smart enough not to pad if it sees that it's not needed.
side note, related to this, you should be grouping your bytes/bools generally
It's not the case in C and C++ iirc.
int, byte, int, bool is 16 bytes not 10
int, int, byte, bool, will pad to 12 saving you 4 bytes
I think there are some CPU architectures on which you can't have misaligned loads and stores at all but I don't know which ones.
Unity only supports x86, x86-64 and AArch64/ARM64 right?
Maybe these all support it.
But I don't know if the C# compiler will avoid padding when targeting these architectures.
i've aligned my structs that way. not giving any thought to misaligned data types.
Player or Editor?
Both.
Oh wait, didn't the Player support the Wii U?
Wii U is PowerPC right?
I don't know if it's still supported.
I'm on the latest Entities pre-15 and I can'et access https://docs.unity3d.com/Packages/com.unity.entities@1.0/api/Unity.Entities.IBaker.SetComponentEnabled.html from inside a Baker
I restarted my Visual Studio and it's showing up now.
So apparently you have to restart after updating to pre-15
The Entity Debugger is bugged, spamming ```
ArgumentException: A component with type:Unity.Transforms.Translation has not been added to the entity. Entities Journaling may be able to help determine more information. Please enable Entities Journaling for a more helpful error message.
I had previously added `ENABLE_TRANSFORM_V1` to get rid of another compilation error. What's the correct solution for this?
restart unity?
They went away on their own, but sure I'll restart if it ever persists again. Is ENABLE_TRANSFORM_V1 the right way to get rid of all the "Rotation/Translation not found" messages after upgrading to pre-15?
It won't be good forever
You will need to update your transform stuff at some point but it's useful now while you transition and have other errors
@rotund token sir. I can`t figure where did you get reference to 'PropertyDrawer' for your collider inspector. It just doesn't exist in my project for some reason
because propertydrawer doesn't exist anymore
you should check for latest!
it's now PropertyInspector
which is in Unity.Entities.UI.Editor assembly
I checked github
PropertyInspector
this doesn't exist for me as well
allthough
I better check
π€
https://openupm.com/packages/com.bovinelabs.essentials/#modal-commandlinetool
Is that up-to-date?
idk what's wrong
clean project
with entities, entities.graphics and physics
"Unity.Platforms.UI.Editor",
where is it from?
You know how you can "freeze" rotation (angular) axis for physics body by setting interia. Is there an equivalent trick for linear (per axis)?
I want to freeze it without removing the PhysicsVelocity so that the joint system doesn't start tweaking
no
i have not updated it for pre
to which namespace?
{
/// <summary>
/// Base class for defining a custom inspector for field values of type <see cref="TValue"/> when it is tagged with an
/// attribute of type <see cref="TAttribute"/>.
/// </summary>
/// <typeparam name="TValue">The type of the field value to inspect.</typeparam>
internal abstract class PropertyInspector<TValue> : InspectorBase<TValue>, IPropertyDrawer
{
}
^ this is the unity script just look at that
π₯΄
this platforms is not even found in assemblies serach
I'm so confused
ok
Platforms was renamed to Entities
Unity.Entities.UI.Editor
jeez
I almost went grey over this
π
i was just trying to create a sample scene for my AI package and run into the problem that subscenes need to be saved inside the assets folder 0.o
i am supposed to save it into a samples folder inside my package
What's wrong with Unity? Why SourceGenerator does not work?
In one project it works perfectly, in other it doesn't at all
oh wait...
Why is com.unity.jobs in preview?! after several years
I'm still having troubles getting a deferred entity reference to work.
it looks like this package might be removed at some point
i believe all the entities packages had their dependencies removed from it in the prerelease
DOTS is freaky since there's things that should be one line of code and are completely arcane to deal with for no rhyme or reason, but it's power is alluring so I can't look away.
not really sure what your issue is, but deferred entities just work
ArgumentException: All entities created using EntityCommandBuffer.CreateEntity must be realized via playback(). One of the entities is still deferred (Index: -1).
I store a reference to the deffered entity in an array
yeah that means you saved the entity without using the command buffer
you can only store a deferred entity via the command buffer
Plz plz plz, syntax me, you're my savior syntax man
I can be dropping skinned items in game today π
like this second!
I promise you big money, you helped me toooooooons,like for real this is the million dollar question, provided I'm making kachillions
Thanks tertle for all your help, you're like the #1 guy who helped me finish my game
ecb.SetComponentData(entity, new MyComponent { Reference = newEntity }); // referencing on an existing component
ecb.AppendToBuffer(entity, new MyBufferComponent { Reference = newEntity }); // appending to an existing buffer
var buffer = ecb.SetBuffer(entity);
buffer.Add(new MyBufferComponent { Reference = newEntity }); // adding to a newly setup buffer```
apart from switch Set/Add
oooooh
these are basically the only way to store/use a deferred entity
https://docs.unity3d.com/Packages/com.unity.jobs@0.70/manual/index.html only has
The Collections Package replaces the Jobs Package.
Interesting merge
So then I can just keep Array.Add(newEntity) then when I refer to newEntity later it works?
or do I nab it from buffer?
yeah every 1.0.0-pre had
Removing dependencies on com.unity.jobs package.
in it
i think with the new allocation stuff it wasn't making much sense to separate, and jobs was pretty empty these days anyway
yes you can store it in a buffer, but you must use AddBuffer, SetBuffer or AppendToBuffer
Add/Set return a deferred buffer that will be setup once command buffer plays back
and Append will just write to end of an existing buffer
If myentity name is e71
ecb.SetComponentData(entity, new MyComponent { Reference = newEntity }); // referencing on an existing component
becomes
ecb.SetComponentData(entity, new MyComponent { Reference = e71 }); // referencing on an existing component
This is parallel writer...
I'm a buffer novice as well... Unless thats an icomponent?
thats the icomponent version
the 2 below i wrote are the bfufer versions
heading to bed, gl!
Goodnight, God bless, you rule
Oh those are many ways of doing it, not just a bunch of code to execute it!
woooo
Sadge
I tried to recreate GenerateAuthoringComponent attribute source gen
but Unity doesn't pick up my creates MonoBehaviour
class
so it can be used with inspector
Wait a second
I have an idea
Dud
I have genius idea
I'll make
GenerateStructComponentData attribute
which you put on MonoBehaviour
and it'll generate Baker and struct that copies all fields
from that MonoB to IComp
There was an attempt to reference a deferred Entity: https://pastebin.com/97HYWgsG
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
why doesnt it? even after domain reload?
yeah
idk, probably because it's not in Assets folder
feels bad
I guess we gotta wait till .net CLR runtime comes in
so we can finally use all those features properly
not through Unity own implementation
I'm a bit done with Unity and Source Generators. They work really badly together. Debugging is way too painful
i used templates to generate code. works quite well now. but i didnt really have a choice. i needed to codegen based on data in scriptable object instances
nah, it's different
a bit
SourceGenerators is compiler feature
and in order to attach custom one
i know. im just saying i didnt see a way to use sourcegen in my case
afaik it can read any files
even not sources
so as long as you can parse your serialized data to C# you can use them
yes its probably possible but id not like to monitor folders constantly for asset changes. id have to read from those files constantly while the user is working in unity. im not experienced with sourcegen so maybe there is an easy convenient way but for now it works with simple templates. its a bit annoying that the user will have those generated files in his asset folder but oh well
bump, hope no one minds
Hello Everyone,
I am working on a simple animation package for dots until the official one is there. I got it working kinda well for up to a 1000 animated characters at once but I am sure there are a lot of performance improvements I am missing.
It would be incredibly helpful if someone would take the time to do some code review for the package as I am not that experienced with the dots stack yet.
Instructions for installing the package and executing the sample can be found in the repo readme.
https://github.com/Bendzae/unity-dots-animation
Because:
- It's async. Basically imaging start the job in Update and finishing it in LateUpdate or on a later frame. This lets it run in parallel while the rest of the game code runs
- You get the benefits of the burst compiler etc...
I see, thanks!
I'd probably just passively wait for it in a coroutine then, though I'm kinda surprised it doesn't already have IEnumerator methods for that
if you look at how it works in ecs you get an idea how you can use it with gameobjects.
say a monobehaviour schedules a job. that same monobehaviour could call job.Complete before it schedules the new job. so every job that is scheduled has 1 frame to be completed on all all cores before job.complete would force it to be completed on the main thread. like that you dont have to poll whether it is finished or not you just know it is and it used all cores available to finish asap.
Just to make sure I understand you, in this scenario you run a single job and it has a lifespan of 1 frame, but Complete will force it to finish when the result is required?
I see, I still have to get the hang of ECS to truly understand this I suppose but it does seem interesting and beneficial
@balmy sableoh and instead of waiting until a job is completed you can also schedule another job with a dependency on the first job.
Yeah the dependency job management was a cool system since it allows separation of tasks into their own respective jobs
@robust scaffold sir. When should your 2D clamping system run?
After what system?
I only found job you pasted, not whole system
Hey everyone, has anyone else had the error Compute shader for Unity.Rendering.SkinningDeformationSystem was not found!?
It's from SkinnningDefomationSystem.cs line 48
Does you mesh have a shader with the compute deformations node like described here? https://docs.unity3d.com/Packages/com.unity.entities.graphics@1.0/manual/mesh_deformations.html
I don't have such a shader and the error appears in empty scenes aswell
Hi, guys, I have an issue with dots for some reason i have this simple dot that I try to spawn a few entities just getting started (I trying to learn to work with it ). The code is here https://paste.ofcode.org/HzVRpatp2kWNeBqnHpujX3 now my issue when i try to press play on unity it got freezes and wont go please note when i try debug it still freezes and not hold on rider or anything like it not connect to my code not sure any one have any advice how i can move on i few hours on this and kinda stuck
Do you have anything that might cause an endless loop? π
i did put breaking point on the only place it got while but never hit
a.k.a
and one of the for for the rest no loops
ya this one hell of a cookie
have any idea what possibly this can be?
this causes infinite loop
try to add conditional fallback if there is no result after 10 tries
where
in your while loop
each iteration do some int++
and check if (int > 10) return default;
something like this?
i am bit back in loops but the odd part i never hit in debug there so odd
*back = bad
yeah
but generally
you should not use loops like that at all
they can't be optimized
by burst
i know it has a reason why it there
also it on the aspect and not in system
i try get random transform that within radius
it doesn't matter where it is, it's just slow π
there are way better solutions for that though
you can generate offset
with random
and just add it to your current position
smth like
the radius is from a prefab
not my
i jusst us pie and random if that was the case i think
and thanks this retry is the way found my reason i get same trasform every type
Is it worth defining custom non generic priority queue in terms of efficiency?
/// <summary>
/// Priority Queue implementation with item data stored in native containers.
/// </summary>
/// <typeparam name="T"></typeparam>
[NativeContainer]
[DebuggerDisplay("Length = {Length}")]
[DebuggerTypeProxy(typeof(NativePriorityQueueDebugView<>))]
[BurstCompile]
public unsafe struct NativePriorityQueue<T> : IDisposable
where T : struct, IComparable<T>, IPriorityQueueNode
Generic NativePriorityQueue struct with IComparable<> and IPriorityQueueNode
I have a very strange issue that I have been unable to debug for the past few hours, I have a nativeArray (public NativeArray<Quad> quads) of a struct called Quad which is set a value using a seperate job to calculate the quad positions. The problem I am having is that I cannot access it at all because it is apparently WriteOnly despite there not being any mentions of this in the code. If I try to set it to readOnly it just says that I cannot have both ReadOnly and WriteOnly at once.
How are you passing the native array into the job
This is usually a sign the safety system can't find the collection to inject safety
And unset safety errors as write only
Most common case of error is passing it in via a pointer
This includes on a icomponentdata
Which is not supported by the safety system
ok I think I found a lead, I disabled [NativeDisableParallelForRestriction] on the first job and I am starting to think that the second job might be using the first nativearray of quads by refrence instead of by value. Could CopyTo fix that perhaps?
im not sure what you really mean by this
native arrays are just a wrapper to a pointer
so they effectively work similar to reference* (length property excluded)
if you need a copy and don't want changes, then yeah you need to specifically make a copy
yeah ok that didn't work either, even if I make a new nativearray and copy each value one by one in a for loop it still says that it is writeonly.
it just throws The Unity.Collections.NativeArray1[ProceduralMeshes.Quad] has been declared as [WriteOnly] in the job, but you are reading from it.
This is the code if it helps:
public virtual void GenerateMesh() { Mesh.MeshDataArray meshDataArray = Mesh.AllocateWritableMeshData(1); Mesh.MeshData meshData = meshDataArray[0]; QuadGrid topGrid = new QuadGrid(); topGrid.Resolution = resolution; topGrid.quads = GroundCheckQuads(new PlanetaryBlockFinder()); JobHandle quadGenHandle = QuadGrid.ScheduleParralel(topGrid, transform.position); quadGenHandle.Complete(); NativeArray<Quad> quads = new NativeArray<Quad>(resolution * resolution * resolution, Allocator.TempJob); topGrid.quads.CopyTo(quads); topGrid.quads.Dispose(); JobHandle meshGenHandle = GridMeshJob<CubeGridGenerator, MultiStream>.ScheduleParallel( mesh, meshData, resolution, quads, default ); meshGenHandle.Complete(); Mesh.ApplyAndDisposeWritableMeshData(meshDataArray, mesh); }
Is it possible to say create a character, on root go place a physics body, make it kinematic. Then on children place physics shapes so that they would be considered compound colliders but all move when I move the character's velocity via script?
Because I setup kinematic body, but all the children fall with gravity...
are you 100% sure you are not reading in the job? Can we see the code
oh nvm you arent using the attribute
try moving the topGrid.quads.Dispose(); to after the second job
might be triggering the safety handle, there's some weird dependency stuff sometimes
might be a generic job bug
could be that tbh, my code seems fine unless I have overlooked something. any ideas on workarounds though?
could make a dummy job to replace it just to test
just write some random stuff to the array in it
ok let me try it
ok the code for generating the quads (in main thread) is literally just this now:
` NativeArray<Quad> quads = new NativeArray<Quad>(resolution * resolution * resolution, Allocator.TempJob);
JobHandle meshGenHandle = GridMeshJob<CubeGridGenerator, MultiStream>.ScheduleParallel( mesh, meshData, resolution, quads, default );`
and it still isnt working unfortunately
still throwing InvalidOperationException: The Unity.Collections.NativeArray1[ProceduralMeshes.Quad] has been declared as [WriteOnly] in the job, but you are reading from it.
yeah no luck. although maybe this might indicate that its coming from the ScheduleParallel where the quads are actually assigned to the generator.
hmm interesting
Ok I think I am getting somewhere now, If I set the quads in the second job as public NativeArray<Quad> quads => new NativeArray<Quad>(Resolution * Resolution * Resolution, Allocator.Temp); there are no errors
so it must be something happening when I assign a value to quads externally outside of the Job
if it helps anyone there is a similar value called 'Resolution' which is an int and works just fine, is it something to do with the fact that it is a nativeArray?
ah what is this code meant to do?
it'll create a new native array every time you use quads
You'd have to show the job
ok hold on
the part of the code thats broken is supposed to get the data from each quad and turn it into a usable mesh
this is the shortened version the stuff in generate quad isnt relevant
public NativeArray<Quad> quads { get; set; } public void Execute<S>(int i, S streams) where S : struct, IMeshStreams { Quad quad = new Quad(); quad = quads[i]; GenerateQuad(i,quad, streams, Quaternion.Euler(0, 0, 0)); }
the error is at quad = quads[i]; btw
I mean is that NativeArray defined as WriteOnly or something? because you're reading from it. Also why do new Quad() just to read it from the array next line?
Also why do Quaternion.Euler(0, 0, 0) instead of Quaternion.identity
oh sorry the new quad stuff was for debugging, you can ignore that. And yes the quads variable is somehow WriteOnly when I need to read it
have you tried using a simple field rather than an autoproperty?
wdym? sorry sorta new to this stuff
this is an auto-implemented property:
public NativeArray<Quad> quads { get; set; }
This is a regular field:
public NativeArray<Quad> quads;
also are you actually assigning that thing to the job anywhere?
yeah still the same result
show youtr code
you've omitted too much stuff
what is this?
GridMeshJob<CubeGridGenerator, MultiStream>.ScheduleParallel( mesh, meshData, resolution, quads, default );
where do you actually make the job?
here
public static JobHandle ScheduleParallel(Mesh mesh,Mesh.MeshData meshData,int resolution,NativeArray<Quad> quads, JobHandle dependency)
{
var job = new GridMeshJob<CubeGridGenerator, S>();
//job.generator.Setup();
job.generator.Resolution = resolution;
job.generator.meshData = meshData;
job.generator.quads = new NativeArray<Quad>(resolution * resolution * resolution, Allocator.TempJob); //quads would be here
mesh.bounds = job.generator.Bounds;
job.streams.Setup(
meshData,
mesh.bounds = job.generator.Bounds,
job.generator.VertexCount,
job.generator.IndexCount
);
return job.ScheduleParallel(job.generator.JobLength, 1, dependency);
}
#854851968446365696 for how to share code
ok just a sec
I just wish they would also add the forums here in discord. Itβs sometimes really hard to follow all the questions s here in the chat format.
alright here you go... its not pretty though https://pastebin.com/79ejJVCq
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
as for the streams part that just handles multithreading vertexes, not really to important to the problem here
G generator;
[WriteOnly]
S streams;```
am i missing something or have you just marked them as writeonly?
[WriteOnly]
G generator;
Umm
you see why posting actual code is important, that took 5 seconds to debug
yeah sorry I didn't really want to dump the whole project files but I guess it just needed a fresh new pair of eyes
thanks for your help anyways
I mustve thought it wasnt relevant or something because it wasnt being assigned when making the new gridmeshgenerator, but I guess it did huh
well anyways thanks for your help again, I will mention it if I get into more problems related to this... thats 5 hours or so gone by lmao
How can I get the blob asset reference from a ChildCollider?
I build a compound collider. Now I'm assigning the PhysicsColliderKeyEntityPairs, does it matter what values I set for ColliderKey (as long as they are unique to each child collider), or do they have to be within some range?
Because the ColliderKey value is a uint does that mean that the maximum amount of child colliders a compound collider can have is 32?
i haven't looked at is it a flag or just a key?
hmm
it seems to do a bit of both ^_^'
Well in case of compound colliders, it references the child (leaf) colliders under the root collider. But docs also say that it helps identify triangle/quad on a mesh collider.
I was able to successfully and quite easily get the entities and colliders that are children of compound collider.
yeah just looking at code
{
uint parentPart = (uint)((ulong)subKey << 32 - (int)numSubKeyBits);
uint childPart = Value >> (int)numSubKeyBits;
Value = parentPart | childPart;
}```
Yup thatβs what I was staring at the last 20 minutes lol
I wonder if we are allowed to child another compound colliderβ¦
probably
For parentPart, does it bit shift and then subtract? Or does it first 32-n and then bit shift that?
this is why i think brackets are important
threw it in my ide which force adds brackets to ambiguities
var parentPart = (uint)((ulong)subKey << (32 - (int)numSubKeyBits));
so yeah subtraction first
Yeah I was just looking at the docs and confirmed too itβs the latter. https://learn.microsoft.com/en-us/cpp/c-language/precedence-and-order-of-evaluation?view=msvc-170
and yet in 2 weeks when you look at this again, you won't be certain and will have to look it up - hence the problem
What is the purpose of having the numSubKeyBits arg be uint when it always casts to int?
stop people putting negatives in ^_^'
guess it just fails instead at numbers larger than int.maxvalue instead
Lol. The Value field is uint right? Sorry not in front of computer right now
oh
Ok. After testing, the NumOfKeyBits is the same as the number of child colliders in compound collider. The root body (if it has a collider) does not count towards child count (whether it's single or compound). And all the colliders have col.NumOfKeyBits == col.TotalNumOfKeyBits. But I think that is because each child collider was not compound. I think if child collider is compound, the total will be bigger.
So when setting a PhysicsColliderKeyEntityPair->ColliderKey, it should follow this format.
new ColliderKey(totalNumOfChildCollidersOnTheRootThisColliderIsPartOf, uniqueIndexOfAllChildCollidersAttachedToThisRoot);
Day 4 of trying to access a deferred entity, mind you I mostly helped my mom with house work cuz she's sick: https://forum.unity.com/threads/how-do-i-change-a-deferred-reference-to-an-entity-to-the-real-thing-to-use-it-in-future-frames.1375737/#post-8670915
Can someone peek at my code? I don't know the syntax.
Singleton.entityDeferredRef.Add(buffer);
what is going on here?
Β
var buffer=ecb.SetBuffer<EntityDeferredRef>(parallel_Position_Integer, e71);
buffer.Add(new EntityDeferredRef { e = e71 });```
also you're storing the deferred entity on itself
Yeah you have to store this against an entity that is NOT deferred. At start of your app, you can just EntityManager.CreateEntity() make a bare entity and give it a buffer that will keep track of deferred entities.
When you add the deferred entity to that buffer, just store the index of the buffer it was added to (important you add to buffer using ecb.AppendToBuffer and NOT buffer.Add, otherwise the deferred index will not propagate.
Then in your next frame, use the stored index to retrieve the buffer element from that dedicated entity, and voila, the entity will be valid. Of course, don't forget to cleanup > buffer.RemoveAt(thatSameIndex)
Alright, I decided to stick with the Joint system. As you can see when I pick up the lid to the box, and "attach" it, I do so via joint system. Set transform of lid exactly where it should be, then attach joint.
When I go to pick up the box and place it on the ground, it tweaks out. I assume it's because the box position is changed while the lid isn't? So I wrote a code to scan all connected joints and adjust the position exactly where they should be in respect to the joint offsets. Even so, it still tweaks.
Can someone give me some advice on how to handle this?
When I pick up any item, it removes PhysicsVelocity, parents to character's "hand".
When I "attach" to a valid item, it adds PhysicsVelocity, sets global position, then create PhysicsConstraintBodyPair to the already pre-setup joint entity that has PhysicsJoint already pre-configured at baking.
When I pick up any item that has attachments, it scans for the root item that isn't attached to anything, does the same protocol with it as first mentioned.
When I place down the item, it adds PhysicsVelocity, removes parent, sets global position, scans all connected items via joints, and sets their global position respectively as well.
But it appears the joint system has both items fighting for position control because they are violating the joint constraints...
Please don't tell me the only way would be to remove the just tried it, didn't work either. Same result.PhysicsConstraintBodyPair for each attachment, set global position, then re add it?
Btw, all this happens on the main thread using EntityManager. No ecb or jobs.
can`t you just apply force towards target point like in fallout/skyrim?
Meaning via PhysicsVelocity?
Then Iβd have to do it over two frames, first frame apply velocity offset, and next frame set to zero? For now, I just want it to snap to position without animating and such.
Ideally Iβd like to do this in one frame.
Fallout/Skyrim, ah the good ol days. Beat both games more than once, and modded the crap out of them too haha. Thank you Nexus Manager haha π
no. it`s constant force, clamped by distsnce between position snd target position and current velocity
tick to tick system
Woah that sounds cool. Can you show me a quickie?
Lol ok. Iβll do some research.
check them
i think they had example of mouse moving object
which is practically what it is
Oh I see, you mean via World.ApplyImpulse?
it doesn't matter how you apply force
you can modify velocity directly
if you know the correct math
if I understand correctly
it should be
targetPos - curPos = targetVelocity clamped by maximum step velocity (so your object doesn't snap instantly)
But I want it to snap instantly in this case. I want the object to move from character to the ghost in the same frame, along with all connected parties.
Yeah and on next frame I have to set the velocity to zero otherwise it will shoot way past it.
no?
you keep doing it
until you release object
because as your character moves, targetPos changes
But the character wonβt move in the same frame.
while object is snapped already, it's velocity will equal some small value that compensates gravity
it doesn't matter
it's all happening in Physics step
Ok. Iβll experiment with this tomorrow. But if someone has other suggestions, Iβm down π
just make a component which holds targetEntity
and get LTW of that entity
and use it as targetPosition
whats the reason to use physics here? would some joints break or sth?
for fixed snapping - no reason
unless you want object to react on other physics (like, unable to go through wall)
then i would go with setting transform directly too.
cause stuff like this can be really annoying
i would even turn off gravity for the object completely if i used physics here because you can get small ocillations with gravity and counterforces not exactly matching each other
turning off gravity is fine
I think
fallout did that
and half life
or not
hmm
no, if I remember well, fallout didn't disable gravity
heavy objects used to have funny holding state
because they go up and down because of it's weight
id not look at bethesda for bugfree examples of how to do things π
wondering is there an entity equivalent of GetComponent<>() ?
?
you know how gameobjects you can Getcomponent<whatevercomponent>() to get the component? Is there an entity version?
not sure if trickquestion or not π
GetComponent<AnyComponent>(entity)
oh, im really feeling like a fool now lol
through EntityManager
its not available everywhere though. you might need to use lookups
or lookups
ok i tried this one, but it seems to not like my component sadly and refuses. PlayerData is just a simple IComponentData. any ideas?
oh whoops forgot to hit the reply button, better late than never...
is your playerdata a class instead of struct?
ok, switched it to a struct, same error message
then things inside are not blittable
aha opened up unity, and yes things are not blittable apparrently, thanks so much, which that ides could tell ya that!
i think you still could use EntityManager.Getcomponent though. SystemAPI is just designed with burst in mind
nah ill just remove the non blittable stuff for now, ill figure out how to deal with it later, wasnt important currently just some ui stuff
generally speaking its better for performance to have more small components than few big ones. so you should probably split it off into a PlayerUIData or sth anyways
ooh clever, thanks for the info!
and of course keep as many components as possible unmanaged
thought all components were managed lol, didnt even know unmanaged ones existed, how fascinating
unmanaged is how they are supposed to be used. burst and multithreading cant deal with managed ones
welp i have no clue if im using managed or unmanaged components, guess i better figure that out sometime soon, thanks for all the info!
to get the hang of it just try to schedule everything with burst. burst will tell you what to do. classes bad, structs good
what a performance saving!
ill try, unfortunately i love using forloops which i know burst breaks often
wdym? for loops are the bread and butter of burst ^^
every time i've tried using a forloop with burst it tends to make it so it never ends, although that was back on the 2021 version so perhaps this 2022 version is better
what did you do?
i burst compiled it
by storing the struct in a pointer
so my input events could write to it
pretty sure it always worked. no idea how you managed to do that
weird, i used a lot of pointers and extern methods, so perhaps that confused 2021 burst?
and the InputCamera is managed?
no
{
public bool Turbo;
public float2 Move;
public float MoveY;
public float2 Look;
public bool LookEnable;
public float Zoom;
}```
ah sry. then im just not sure i know why it was not burstable before
i havent gotten around to rewrite any of my SystemBases as Burstable ISystem
because they are event callbacks
the issue is writing to the value in the struct didn't work
ah yes of course
but that system needs to run every frame now. i am not a huge fan of converting events to polling
ah ok. i do inputs with changefilters
it was basically exactly the same
oh i see what you mean
but yeah that doesn't bother me
i mean that system takes so little time it doesnt really count as running.
i could easily diff the past/current frames
before writing if i wanted change filters
i was wondering if reactive systems are actually a bad thing. not so much for input handling but for other gamelogic. cause they could cause spikes in rare cases. better to have a little worse but consistent frame time i think
why i'm not a fan of random time slicing
i'd rather keep my frame time constant
lower average fps is better than spiky fps
yep im running into problems there. i have AIs with different complexity. i dont want to run every AI every frame so i just run some AI chunks per frame. -> spikes
not huge by any means but if i had multiple such timeslicers for different systems and the spikes interfere in a bad way it would get bad
but in massive scale AI cases we could talk about much less frames. say you have 10k AIs that would only need to reason once every 0.5 seconds. timeslicing does alot there
i was wondering how you could smooth out that spikes by allocating a specific time for jobs to run instead of just processing X chunks per frame
actually its not even the jobs running but the jobs beeing scheduled that cause the spikes
hmm its probably a problem very specific to my AI design. Since each agentType causes different combinations of Systems to run
how slow is your scheduling? o_O
or how many jobs are you scheduling...
in the current project the AI has 60 different systems running (not bursted yet).All those systems take about 1ms to run.
burst them! π
well those are the generic systems we so often talked about ^^ i need to codegen to burst them i think
havent gotten around to that yet
ATM i am working on improving editor workflow and getting samples going so i can show it to you π
mistake
changefilters don't really work here for me because pressed = true
stays true until new input comes
that's ok though, i really didn't need this anyway
yes dont add the reactive overhead to it. simple is better
would you have any wishes for specific samples for Utility AI usage?
i was thinking:
resource gathering, attacking , coordinated attacking , getting into cover
resource gathering loop is like my default go to
if you can make it react to combat etc even better
https://github.com/Unity-Technologies/DOTS-training-samples
even something simple like the auto farmers sample
i think is great at showing potential
Farmers walk around to destroy rocks (the grey cylinders) to make way for tilling the soil (creating brown-striped crop cells).
A plant grows in each crop cell. (The color and mesh of plant randomly varies.)
When fully grown, a plant is ready for harvest by a farmer. Farmers deposit plants in the nearest silo (grey-blue cylinder).
When enough resources have been collected into a silo, a new farmer spawns from the silo.
Farmers look for their next task in a limited radius. If no task is found, they look in an increasingly larger radius until a task is found.
For every fifth farmer spawned, a drone is spawned instead.
Drones fly and harvest plants. They do not destroy rocks or plant crops.
After depositing, drones hover over the silo until they locate a plant to harvest.```
i think each sample needs to show some different concepts. resource gathering is the chaining of tasks.
combat is showing how to coordinate between agents and get dynamic attack positions
cover is showing how to evaluate massive amounts of entities globally and then distribute them to agents
yep thats basically what i wanna do as a sample but without all the actual tasks beeing performed visually for now.
hm but isnt that what utility AI doesnt even need to do ? π
As soon as a Score is higher it fluidly switches tasks. My AI deals with decisions and not how those decisions are then beeing performed. if the user does not want them to be interruptable he can do so but by default you always get the best scored decision
i've seen plenty of UI utility fail at this pretty badly
ok thats weird π but as soon as those tasks beeing performed are part of the utility AI i can see that happening
basically people trying to optimize performance by not evaluating utility as long as a task is active
the issue i see that always ruins the flow for me is more
returning to a task
now i'm not sure this is on your AI system to handle
but it would impress me in a demo
i've always had a bit of an issue with utility ai without any state
i guess state is just another score though
yes i was just about to write that but was not sure if i get your issue correctly. interesting that you had problems with that. i havent touched a lot of other Utility AIs but i get the feeling i do some stuff a lot different then
your perspective will be quite some valuable feedback
have you need seen a utility system like, switch rapidly between actions?
because there are like 3 actions that are very close in score
yes. you need some hysteresis
and doing 1 action inadvertently causes other scores to increase or that score to decrease
similar things tend to happen with interruptions
like stray arrow causes it to enter combat state just as the source dies
from say, chopping wood
but now instead of going back to wood chopping it decides its hungry so walks home
it's disjointing even if the correct action
anyway kind of a random rant
no its not. i saw that kind of issues alot.
i dont know if i have solutions to every such case but adding momentum to desicions does pretty well
like if you decide to chop wood you get your decisionScore say 0.8 + another 0.5 for "recent Decision"
and that 0.5 decays over some time
specified in a decaycurve
oh i don't have any solution, i'm far from an expert on AI i don't do a lot of work on it sadly
but you got your own implementation going. makes you already a lot more advanced than most people i know π
well i haven't really used it in over a year except to update entity versions
i still have no idea how production ready it is sadly
im a bit stuck with people in academia that are more concerned with gamedesign and UX than concrete implementations
i heard adding .pre to your package is all you need
jkjk
Entity e71 is instantiated. It is now deferred and I want to store it in a buffer.
did you look at the forum thread? i posted an example system
oooh, thank you super much bro, I'll look into it!
probably a foolish question, but i cant find an answer anywhere, how do i make my gameobject be an entity, back in 2021 unity this was a simple checkbox, but i cant seem to find it in the 2022 version
SubScene
ah, i shall check them out, thanks!
the docs on them seem less than helpful, and i cant find many websites or forum posts about them (apart from people being confused on what they are, and not getting a reply, or getting very unhelpful replies), guessing this is something new in 1.0 then. Know any good sites for explaining subscenes?
just create subscene
and add game objects to them
how?
everything inside will become entity
i have the subscene, but how do i put stuff inside?
through right click in scene hierarchy
ah
just drag it in
or create from inside
subscene is just a scene
in edit mode
oh ok, ill try that thanks!
oh wow it worked, this is super cool, thanks!
so now in 1.0 you can just view and click on entities like you would gameobjects, this is so cool and so much better than the old 2021 version lol, still shows the non-unified scale for the entities though, how odd and fun!
this was supported since forever, lol
even back in 2020 version
really, wow, every tutorial i watched back then never mentioned it, welp im glad i atleast know now!
perhaps lol
is there any official method for getting the new input system to work with systembases yet?
no
people rolled different implementations so far
whenever you ask if there is an official way to do something in ecs the answer is no atm
at least when it comes to things not directly concerning the entities package
ok makes sense thanks for the info!
Thank you MaNaRz, tertle and MayuMichi: https://rumble.com/v21eesa-thank-you-to-unity-developer-helpers-got-a-dotsecs-game-going.html?mref=sbycb&mc=11sm2
hey folks what is currently the best Unity 2022 version for working with dots 1.0?
hi guy i got an issue with create new game object with dots this the code https://pastebin.com/4V6jX9T2 and this the error "The name 'entity' does not exist in the current context" now what is the issue what i did wrong here?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the latest one
thanks..
So the very latest as in 2022.2.1 released on the 12th?
i guess it would makes sense as i imagine they're trying to roll in as many fixes to any bugs as possible
i dont know if there is a difference between 2022.2.0f1 and .1f1 when it comes to entities. im using 1f1 without issues
Hi! I'm working on health bar (simple quad entity) for my army of enemies, I see two solution
- put health bar to enemy entity prefab as a child and enable it after first hit was detected
- create health bar entity at runtime and put it as a child.
For me first approach is better but want to ask is there any overhead for maintaining a disabled entity? if we speak in the context of thousands of objects.
disabled entities still live in memory. id spawn healthbars when a unit is actually on screen and damaged
honestly, I'm not worried about memory, there's so much of it on all devices now... and the size of the healthbar memory will be very small in my opinion . I'm only worried about spike and fps, so that there is no performance degradation when the healthbar is turned on
I would like to know if any calculations are performed for disabled entities or if they are performed only when they are enabled
usually only when enabled. you could include disabled entities in queries though.
well it all depends on what scale your talking
I think the best way to find out would be trying. If it's not visibly degrading performance you can profile it if you care about imperceptible degradation
having 1m entities off screen with healthbars and 10 on screen wont be a good idea
also note that enabling an entity is causing a structural change. thats basically as costly as spawning an entity
no no, my target is mobile devices. a'm talking about 1-10k max
fair enough
Docs say I want to store system's data in components. Relevant to any data? EntityQuery for example
whats the best way in dots 0.51 to move a gameobject and an physics shape together?
EntityQuery is just an instruction for what entities to query
allthough, I think you can store it on comps if you need it
Well my first experience of 2022.2.1f1 is an interesting one so far
To be fair, i closed it ( was a new project ) and reopened - it opened really quickly and is now visible/working as normal
Just reopened to confirm, i've never seen Unity open so quickly
Since release I'm finally having fun with Unity
baking seems fixed
Anyone yet checked?
Webgl works on new entities?
back in 0.51 it didn't
What release?
2022.2
How can I check my ISystem was bursted?
f1 is out for some days. is it different to the pre release?
no errors when compiling. green bar in profiler
burst inspector should also show the system struct
Each ECS chunk stores a list of entities, right ?
Does each chunk also stores a map to acess those entities ? Like Chunk.Get<T>(in entity) or something similar ?
2022.2.1f1 vs 2022.2.1f1, is the first update of 2022.2
But I guess even that's been out a couple of days now