#archived-dots
1 messages ยท Page 53 of 1
nah, just a single radian. 2D is very nice.
All the examples online are for full quat smoothing and go way over my head.
There's slerp of course, but that's spherical lerping.
just use cos/sin instead of linear?
there's math.slerp for quaternion smoothing
oh wait just saw you literally just wrote that
doesn't lerping a radian work well though?
https://en.wikipedia.org/wiki/Slerp
slerp isn't tied to quaternions you can do it on n-dimensions
them math though
function rLerp (A, B, w){
let CS = (1-w)*Math.cos(A) + w*Math.cos(B);
let SN = (1-w)*Math.sin(A) + w*Math.sin(B);
return Math.atan2(SN,CS);
}``` I think this might work, but ugh, sin-cos.
for character interpolation I really just do this:
interpolatedRot = math.slerp(characterInterpolation.InterpolationFromTransform.rot, targetTransform.rot, NormalizedTimeAhead);
basically math.slerp(fromRot, toRot, ratio);
Is this for the smoothing singleton?
I'm designing my own physics engine (again) from the ground up so i have nothing except my own systems touching the transforms.
Actually huh, making everything interpolated fixes the rotational vibrations. Something is going on predicted clientside that is messing everything up
Oh god damn it, im dumb. I had a WithAll<Kinematic, Interpolated> instead of WithAny<K, I>
there is math.sincos method if you want to be efficient
So my triggers to prevent interpolated overwriting wasn't being triggered.
I got a vectorized sincos using polynomial estimation. The built in sincos is great for singular values but doesnt calculate it wide. But that's only alive within the physics loop and not available elsewhere. So I dont want to use it much.
It does not work for float because of precision error ๐
I use it for int3 but for float3 handle in different way
Well yes, they are floats. The Equals override just checks the equality for each individual component
It is weird why they compare float3 in this way
I always consider a threshold value when comparing them
This is the case for all floating point values, it would be weird if Unity.Mathematics Equals methods behaved differently
e.g. System.Single has the same "issue"
Ya know, just on a different dev server, people were complaining how unity-engine's MathF float comparisons were on thresholds instead of exact bit comparisons.
^
Thresholds also are more than 1 operation so may cost nanoseconds more than equality.
I am convinced fully
I do think that exact equality is the better standard implementation.
Let the dev themselves decide what the threshold should be by coding it themselves. It's an easy addition after all.
Yes, agree
I check int2, int3, float2 and float3 can be serialized in the inspector, Cool
but int3 see
They are like int2
public class WorldSetting : ScriptableObject
{
[SerializeField] private int3 aa;
[SerializeField] private int3 cc;
Expand the inspector to the left.
wait it doesn't calculate wide?
it has double4/float4 overloads
huh. No clue.
a for loop with single float recording doesnt automatically expand to a float4 sincos calculation from what I can tell from the inspector. Just a bunch of vmovss and other scalar single operations.
By the way, they can be serialized. So, I can use them in the inspector and serialize them using newtonsoft or JsonUtility without pain?
In debug mode, it is fixed
Might be worth a bug report
Using float4s results in this whole chunk of code. So there's a definite difference in vectorization.
Version of what, Unity?
but does not matter
yes
2022.2.0f1
2021.3.6
Might be a 2021 issue then
@rustic rain Found the fix to the standing-on-sphere rigidbody weirdness. If you replace the PhysicsUtilities file in Rival/Runtime with this, that should do it.
Keep in mind that if you want the standing-on-sphere to look believable (rotation of sphere incurs a displacement of the character), you would still have to add a TrackedTransformAuthoring to the sphere though.
I'll do some more serious testing this week and look into pushing an update with the fix soonish
Wow, that was fast.
I have a bug somewhere in my physics code and i have 0 clue what is going on.
What is going on?
I got a sin-cos polynomial approximation and shoving the values back through a math.atan2() is returning a constant 3pi/2 for some reason.
well that seems unlikely
Are you using degrees or radians properly?
let's see the code
Here's the approx.
rot is the rotation buffer with values in radians. Sin and Cos are self explanatory
I have this immediately after, if the polynomials function property, this should produce the original rotational radians.
I'm using a remez approximation of sin from [-pi, pi) and cos from [-pi/2, 3pi/2)
private const float SinSecond = 7.9580617878616184e-3f;
private const float SinThird = -0.16566698569427846f;
private const float SinFourth = 0.99927587074562368f;
private const float CosFirst = 1.4507698749438392e-4f;
private const float CosSecond = -1.5952047934105319e-3f;
private const float CosThird = -4.4083629793699222e-4f;
private const float CosFourth = 4.2822420811795007e-2f;
private const float CosFifth = 2.2303232162043226e-4f;
private const float CosSixth = -0.50138509243366806f;
private const float CosSeven = 3.3850614694439052e-5f;
private const float CosEighth = 1.0002499365408113f;```
I'm gonna try running through regular sincos and seeing if it's a problem with atan.
It's not a problem with clamping because I run the rotation that doesnt go through the roundtrip through a sincos at renderer.
Okay, a round trip with sincos and atan2 is working properly so hrm
Small tangent, did you write the Remez exchange yourself? I went through a similar exercise to generate a minmax polynomial approximation back in the day
No, not that mathematically inclined (used to be back in the day, not anymore). I pulled it from a friend who crunched them.
I mean, math.atan2 just called System.Math.Atan2 so it's just really not that exciting
Yea, I'm gonna print the differences and see if it's just some period offset or something.
Have you plotted the values for your approximation from -pi/2 to pi/2? Do they look feasible?
Alright, the differences are not negligible but shouldn't be a problem.
I did the classic abs(sin(x) - f(x)) chart and that's where I got the 0.00025 error from.
Cosine of course is a little (10x) worse due to the period shift but still close enough.
Values printed using this:csharp for (var i = 0; i < count; i++) { math.sincos(rot[i], out float tSin, out float tCos); Debug.Log($"S:{sin[i] - tSin} C:{cos[i] - tCos}"); }
What's the code calling into atan2 look liek?
I got a test rotation function as well rotating these boxes to show the round trip functioning. Using sincos() results in rotating boxes. Using this approx results in boxes that seem permanently rotated at 135 degrees.
I mean, I don't see anything wrong in the pieces I'm seeing here
Yea, which is where I'm at right now. Something isn't computing and it's something very minor.
Reminds me so much of debugging shaders, complete black box because if I stick any debugs into this, it lags so hard.
So I'm just selectively setting various parts of this algo to output to rendering and seeing if it rotates
private static void SinCosToRot([AssumeRange(1, int.MaxValue)] int count, [NoAlias] float* sin,
[NoAlias] float* cos, [NoAlias] float* rot, [NoAlias] float* inv, float delta)
{
for (var i = 0; i < count; i++)
rot[i] += inv[i] * math.abs(cos[i]) * delta; //math.atan2(sin[i], cos[i]);
}``` Alright, this results in the boxes rotating in a frequency. Which means cos and sin (tested with sin as well) are properly calculating. Does Atan2 require normalized values?
The coordinates should be on the unit circle
so yes
but if your values are approximately accurate than they should be
since sin(theta)^2 + cos(theta)^2 = 1
Hrm, good point, let me try somethign
private static void SinCosToRot([AssumeRange(1, int.MaxValue)] int count, [NoAlias] float* sin,
[NoAlias] float* cos, [NoAlias] float* rot, [NoAlias] float* inv, float delta)
{
for (var i = 0; i < count; i++)
rot[i] += (cos[i] * cos[i] + sin[i] * sin[i]) * delta; //math.atan2(sin[i], cos[i]);
}```Results in nothing moving. Removing either cos or sin squared from the center does result in something moving. How is that possible? The only way the center value can equal zero (because delta isn't 0) is if either were an imaginary number.
Ah fuck, i just realized
There we go, the round trip works.
I was adding pi/2 to the radian angle when calculating cosine because I was thinking about using the sin approximation before my friend got back to me with the cosine approximation function. And I didnt remove the pi/2
So that meant I was calculating sine twice.
Question, project tiny got forgotten and not updated anymore right? as in with unity 2022 ecs got out of hidding, so I remembered project tiny, anyone knows what state it is in? Or how compatible DOTS is with webgl.
Yep, it's dead. 6 feet under. And it'll remain that way for the foreseeable future (1-2 years)
Ha, I can see further into the future than that!
๐ฅฒ I guess official realizes that they can't do some many things in parallel. Their current focus should be improve what we have currently
I like the idea behind this behaviour though ๐
Would be curious to see what's causing it, because keeping such niche cases (which are not encountered in normal playthrough) encourages game's speedrunning
but for multiplayer - yeah, totally should be fixed
I see, just a small check
Hi guys. I just started with dots and trying to wrap my head around it. My first problem is that I can't seem to view the entities I'm spawning. Is there a way to enable gizmos in the entities hierarchy?
This is the prefab I'm spawning from
Scripts are super basic
public class UnitSpawnerAuthoring : MonoBehaviour
{
public GameObject UnitPrefab;
}
public class UnitSpawnerBaker : Baker<UnitSpawnerAuthoring>
{
public override void Bake(UnitSpawnerAuthoring authoring)
{
AddComponent(new UnitSpawnerComponent { Prefab = GetEntity(authoring.UnitPrefab) });
}
}
public partial class PlayerSpawnerSystem : SystemBase
{
protected override void OnUpdate()
{
EntityQuery query = EntityManager.CreateEntityQuery(typeof(UnitTag));
int spawnAmount = 3000;
var component = SystemAPI.GetSingleton<UnitSpawnerComponent>();
if (query.CalculateEntityCount() < spawnAmount)
{
var entity = EntityManager.Instantiate(component.Prefab);
}
foreach ((TransformAspect transformAspect, UnitTag tag) in SystemAPI.Query<TransformAspect, UnitTag>())
{
transformAspect.WorldPosition = float3.zero;
}
}
}
WeakAssetReferences doesn't seem to work in my case?
entity 1.0.0-pre.15
unity 2022.2.0b16
Child assets could not be loaded
i see 2022.2 is out of beta, does this mean that unity physics supports the new transform system?
have you installed Graphics package?
I'm using 2022 beta, isn't that in by default?
no
it's also preview package
btw, 2022.2 is out of beta
you can download 2022.2.0f1
it seems more stable than b16
I don't see it on the hub ๐ฆ
I have pre release packages enabled but I still can't see that graphics package anywhere
it's preview, so you need to enable preview packages
try
entities
in search
I mean I have the entities package
but graphics?
it has entities in it's package name
so you should find it with entities keyword
oh yeah
man what ๐
is it because it's not available or because it's already included? ๐
it's only visible on beta
I mean
release
damn
on beta it's not visible
and you need url to install
:>
they are
check your preferences, entities, (cant remember what its called exactly) scene view baking type
should be either authoring or runtime
that was it, thank you
I was reading about the Hybrid Link - is it not in the new graphics package?
Hybrid is not about graphics at all
it's just attaching GameObject to specific entity
in order to use classic components that don't have entities alternative (skin mesh)
I see, just found a video that talks about it. https://www.youtube.com/watch?v=vs6h4waQpPA&list=PL6ubahbodJ3N2udo4n9yGQcpbWnqdgYnL&index=9
Today we will learn #howto use the #unity #ecs 1.0 Hybrid Workflow to animate characters.
We will discover two new types of components, managed components and cleanup components.
And we will introduce the concept of Reactive Systems.
With all these tools you will be able to work around the current DOTS limiation regarding, #animation , audio a...
So if I wanted to have 10k animated objects, they'd still need individual gameobjects with animators on them, is that right? Assuming I didn't go for a custom solution.
yep
ooof. Performance won't be what I hoped ๐
That's still going to be faster, because everything else is
besides
animator has built in culling
which can be also done with help of ecs (disabling game object if it's culled)
You could try Latios Kinemation/ DMotion or GPUI Crowds Animator asset for animation if you need better performance.
Hi everyone, in editor play mode my game is running fine but in the build I get these errors. Any ideas what could be going wrong?
In the editor play mode I get these warnings, but there are no missing scripts as far as I can tell
I have an asset that I'm quite happy with so it will help I'm sure ๐
what are you using for animation?
Thread
Hey guys how to solve this on latest unity 2022.2.0f1? Found a forum thread about it but didnt underestand well the solution
Suppose I had a simple LookAt type System that takes in a ComponentLookup<LocalTransform> to make a thing face an other thing. I finally realized that this means I'm in trouble when I wanna look at some child object somewhere, because I don't appear to have a way to actually get its world position at all (since I don't see a way to get access to the parent, let alone possibly multiple parents). Is there a decent solution to this or should I use a ComponentLookup with WorldTransforms instead? Or... in addition? This already feels pretty brute force to me, surely there's a smarter way of doing this?
@oblique cosmos it seems like you need Aspects and https://docs.unity3d.com/Packages/com.unity.entities@1.0/api/Unity.Transforms.TransformAspect.html might help your case
Can't put those into a ComponentLookup though, can I?
I don't see how this helps my problem?!
I mean, I see how the TransformAspect would solve my problem, but I don't see a way to actually get access to them outside of a job query? Which I can't use because the target is not what I want to iterate over
yeah I see your problem, there's no equivalent aspect builder from componentlookups
thats why they added aspects, its not complete yet but at least it will simplify managing a group of components (transforms) together as a single collection of stuff to compute against
Yea, I know, I'm already using a bunch and love them, but I'm not really seeing how I'd get access to them in this situation
there will be a GetAspectLookup() in future versions hah
what I mean is you can just get the components, then build the TransformAspect out of it, then grab the position
so that way you don't redo the computation on your side regarding child positions etc
Oh? Hm. Was wondering what this AspectBuilder or whatever was all about ๐ค
exactly, it's a hack for now I think
Any documentation on how to go about that?
not much, you can look at the public git repos for any code that uses IAspect and start browsing ๐
Ouf. The documentation crawl on this stuff is pretty real lol
yeah aspects and enableable components are the newest craziest stuff in entities 1.0
I'm not a pro on those features yet and still retooling my old 0.50 codebase so I can't give you concrete examples yet ๐ฆ
Yea, I'm deep into noob territory still myself, but I'm slowly piecing it together! But if you say there's a way to get some sweet aspects into my job, I'll go look into that, thanks. That would actually solve a good chunk of my recent headaches, cause aspects are amazing.
yeah for now I'm simply sticking with my good ol LocalToWorld based code where I do everything myself ๐ฆ
I had the good fortune to really start digging into it like a week before the whole 1.0 thing happened, so I got a light overview on 0.5 and then immediately moved on. Well... good and bad things about that, but at least I don't need to convert a million scripts :)
Hi guys, I'm using Unity Physic v1.0.0 pre.15, but I wonder how can I detect collision enter or exit event?
I already used ITriggerEventsJob, but I just want to detect on trigger enter or exist like OnTriggerEnter of GameObject
Is those event exist in DOTS Physic?
Yeah they do, I don't know if it's different in 1.0, but there was an example in the physics samples
I can't find the example now but it involves a statefultriggereventbuffer, which you add to the object you want to trigger
Can't I have NativeHashMap<int,Chunk>, right?
Chunk is struct containing NativeArray<Voxel>
YOu can
but safety system might not work properly
I get exception
ArgumentException: Chunk used in native collection is not blittable, not primitive, or contains a type tagged as NativeContainer
what version are you on?
2021.3
public struct Chunk
{
private readonly int _chunkSize;
public int3 Index { get; }
public float3 RealPosition { get; }
private NativeArray<Voxel> _voxels;
public Chunk(int3 index, Voxel[] voxels, int chunkSize, float3 realPosition)
{
_voxels = new NativeArray<Voxel>(voxels, Allocator.Persistent);
Index = index;
_chunkSize = chunkSize;
RealPosition = realPosition;
}
public struct VoxelWorldData
{
private readonly int _worldSize;
private readonly int _chunkSize;
private readonly int _worldLength;
public NativeHashMap<int, Chunk> Chunks;
public NativeArray<FirstDownwardBlockedVoxel> FirstDownwardBlockedVoxels;
public VoxelWorldData(int worldSize, int chunkSize)
{
_worldSize = worldSize;
_chunkSize = chunkSize;
_worldLength = _worldSize * _chunkSize;
Chunks = new NativeHashMap<int, Chunk>(worldSize * worldSize * worldSize, Allocator.Persistent);
FirstDownwardBlockedVoxels = new NativeArray<FirstDownwardBlockedVoxel>
(
_worldLength * _worldLength * _worldLength,
Allocator.Persistent
);
}
not a thing in 0.51
only 1.0 got rid of managed safety data in native containers
Any solution? :/
Also, if some data inside structs here Chunk have the same value, should I define them as static fields or get values outside StaticValues.ValueA?
Here, chunkSize and worldSize values are the same for chunks
huh, i haven't really figured this out. (looking at rival source)
coming from public readonly DynamicBuffer<KinematicVelocityProjectionHit> VelocityProjectionHits;
A DB's only 16 bytes anyways so copies are probably fine.
sure, but it's more about why in parameters are triggering this on readonly
What is processor?
some struct that has IKinematicCharacterProcessor. it's from the rival source code. not mine
Ah impure, my biggest last peeve atm
i had this in my source code too. i rewrote it but never figured it out why a copy is suddenly happening. i mean it's great that rider is warning us
rival has pretty great source code i must say. worth a read btw
Have these all throughout project and annoys hell out of me
That's a possibly controversial decision on my part; there are places where I pass collections by "in" or "ref" based on whether or not the contents are expected to be modified by the function. Sometimes it's helpful to know. But i would 100% understand arguing against this too
So a copy would also be totally fine in this case, and "in" doesn't really matter
Never noticed that message before though. I should look into it
How can I set a part of a native array? I see GetSubArray but not SetSubArray
Also, copyto and copyfrom do not have start index and length
yes, easy but efficient?
Anyone else got any ideas on this? I'm still stuck :<
Is there a way to get all client + thin clients worlds from managed side?
With a ComponentLookup<LocalToWorld>, you can get the world position of the entity you want to look at. It also has the advantage of being the interpolated transform, if the thing you're looking at is a rigidbody. But the caveat is that LocalToWorld is only updated during TransformSystemGroup, so depending on when your LookAt system needs to be in the frame, you might be looking at last frame's data
Darn it, it was recommended to me, in this very Discord, to use LocalTransform lol
Gonna look into that, thanks
I'd say iterate on all worlds (World.All I think), and check each world for .IsClient or .IsThinClient
hard to be more efficient then a memcpy (which copy methods do)
DynamicBuffer.GetUnsafeReadOnlyPointer() And the warnings. pain.
Hm. Okay, I've just realized that my example was very poor because it excluded some relevant details. Rather than thinking of just a LookAt system, let's call it a turret with two axes. I use the ComponentLookup both for those axes (which are children of my primary entity) as well as the target. As such, I need access to the local transforms of those axes (for some math and transformations) as well as the world position of the target. So it would seem that LocalToWorld doesn't really fit the bill, either :( Any way to get access to both of those without having a second Lookup just for the target? I'm not familiar enough with the inner workings to say but... that doesn't strike me as very conducive to performance, right?
Ok the job system definitely has to be some black magic fuckery. I had a process which took around 200ms in managed code. Merely jobified it (and parallelized what I could of course) and I can't even find it in the profiler anymore. After some digging... 0.35 ms for the whole thing.
I use the ComponentLookup both for those axes (which are children of my primary entity)
I'd say in that case you'll probably need the two lookups: LocalTransform and LocalToWorld.
unless you wanna split your turret lookat into multiple systems, where one handles horizontal aim and another handles vertical aim, but that just sounds like overkill
Yea, it's also a lot more complicated than that, I'm afraid. I have a few features in there that require both axes to be able to talk to each other and splitting them would probably just make everything worse ๐ค Well, in principle I don't particularly care about having two Lookups, as it doesn't really impact me a lot on the code side of things. How's, generally speaking, the performance consideration on all this? Seems to me asking for every transform ever is a bit rough, no?
Getting a ComponentLookup<Something> costs almost nothing, especially if you get it via SystemAPI.GetComponentLookup. Getting a component on an entity via that lookup is only a bit more expensive than accessing a reference
Wait, really? I feel like I've been told/read that there's random memory access stuff happening and it's generally not good (but unavoidable at times, obviously)?!
it's certainly a lot less fast than linear memory access by iterating components in chunks, but it's also quite near the speed you'd get if you implemented something in OOP. So better avoid it when you can, but if you can't avoid it, it really isn't the end of the world
I mean it's not good but it's not bad.
Ideally, you develop data and access patterns to avoid random access but in some cases it's unavoidable.
Yea, I've been trying fairly hard to avoid doing this, hence my entire issue. But I assume these costs are linear, in that it's a sort of flat fee I'm paying and it's not invalidating all the fast math and stuff I'm even using DOTS for in the first place, yea?
My memory access lore is a bit rusty...
First code the mechanic, then optimize it later. ECS is really nice in that the comparatively modular and independent nature of every aspect of coding allows for relatively painless refactoring and optimization.
reading 1 component is nothing
Certainly, that's a good thing to live by. I'm just trying to figure out the correct ways from the get go, rather than learning wrong and trying to unlearn later :P
using lookup to iterate thousand of objects - bad idea
Pain.
ptrs lol
Collision resolution. Every single component of all entities for physics.
๐ฅด
And the random access is killer. It aint good.
That's kinda what I mean with my fairly poor phrasing, since I'm just iterating over my actual components the fee I'm paying here should be flat, yea? As in, the more entities I have the smaller the relative impact, since the lookup cost goes up linearly at worst?
If you lookup one or three components per entity, that's fine. It's when you start doing O(N^2) operations that are really bad.
lookup is using entity index to find chunk and then chunk's internal map to obtain ptr to correct data
just so you have idea how much it costs
Soooo... just so I understand this correctly, when I'm using a Lookup, is that stuff only pulled from memory once I provide an Entity ID?
Or does it read the entire thing first?
var chunk = chunks[entityIndex];
var ptr = chunk.GetRWPtr<T>(entity);
smth like that
Lookup is just a dictionary. With costs similar to it.
When you get a reference to a dictionary, does it pull the entire dictionary with it? Same think with entity component lookup.
Hm. Yea, I figured as much, I guess I'm tripping up on the memory aspect of it. Because from what the code reads it feels like it pulls every transform in existence from RAM and that sounds bad?
I have no idea! I'm a C# script kiddy, I don't know these things lol
Oh boy, well I mean that's good. People experienced with C# and OOS coding have a real hard time learning ECS/DOTS.
nah, it just uses 2 random memory accesses out of heap
I see. Mhhh, starting to make sense. In that case, it really doesn't seem like that big of a deal ๐ค
Yea, dont worry about it. Optimize when you're more experienced with DOTS.
@oblique cosmos yeah it takes a while to unlearn all of your "bad" OOP practices ๐
Oh, I will. I'm not even really building anything particularly useful right now, just trying to wrap my head around things. And poking around with some optimizations seems like a reasonable approach to such things
To be fair, Unity already punched a lot of good practices out of me lol
Properties who? Interfaces what?
Haha, relatable
Properties are actually pretty nice.
How much time does it take to read this part in memory is one of the most advanced questions because nobody can really answer it except the machine while it is being profiled. Sometimes random access hardly matters, then it trashes performance. Usually it doesn't though but in very hot code paths it can lead to stalls. Best is to write the code and profile it. Theory crafting is very useless here.
I agree! Unity's standards aren't... particularly fond of them though, it seems :P
And it's the only way to debug blob asset values
I understand that, I'm not looking for numbers, just a general feeling of "will this blow everything up".
Wait, that's an attribute? Huh... learn something new every day
My best answer to that is coding it yourself and seeing if it does blow up. Trial and error is pretty much the only way to know as coding, in my experience, is largely instinctual rather than intellectual.
You can also write an Inspector but your version seems more convenient.
Yea, it allows properties to show up on the editor inspector. I have this entire block surrounded with a #if UNITY_EDITOR
Even that is subjective. It won't blow up with 50 entities or 100, so what will you throw at it? ๐
Oh, trust me, there has been plenty of error :D
Writing inspectors are pain. As someone who wrote my own entity inspector.
Test your use case, see how it behaves, test again later when use case changes, repeat.
Well, you know, I'm just saying. If I start sorting via some n^3 nonsense, maybe someone should tell me to stop, is all :)
Anyway, guys, it's getting towards bed time over here in the mythical land of Germany. Thanks everyone for holding my hand. You guys keep talking about blob assets and all the other stuff I haven't looked into yet!
I'm just north of you buddy ๐ But sleep well
nitey nite buddy!
Is SystemAPI not supported outside of systems?
no
Is there another way to get singleton component outside of system? ๐
sure ```public static TComponent GetSystemSingleton<TSystem, TComponent>(this EntityManager entityManager)
where TComponent : unmanaged, IComponentData
where TSystem : unmanaged, ISystem
{
var systemHandle = entityManager.WorldUnmanaged.GetExistingUnmanagedSystem<TSystem>();
return entityManager.GetComponentData<TComponent>(systemHandle);
}
public static TComponent GetSystemSingletonManaged<TSystem, TComponent>(this EntityManager entityManager)
where TComponent : unmanaged, IComponentData
where TSystem : ComponentSystemBase
{
var systemHandle = entityManager.World.GetExistingSystem<TSystem>();
return entityManager.GetComponentData<TComponent>(systemHandle);
}```
where T : unmanaged
{
var query = entityManager.CreateEntityQuery(ComponentType.ReadOnly<T>());
var entity = query.GetSingletonEntity();
query.Dispose();
return entity;
}
public static T GetSingleton<T>(this EntityManager entityManager)
where T : unmanaged, IComponentData
{
var query = entityManager.CreateEntityQuery(ComponentType.ReadOnly<T>());
var entity = query.GetSingletonEntity();
var comp = entityManager.GetComponentData<T>(entity);
query.Dispose();
return comp;
}```
I want an IJobParallelFor which returns true if any of the parallel executions return true, and false if none of them do. The first way I thought of doing this was using a NativeArray<bool> for output and iterating over the result in managed code, but I was wondering if there's a better way.
For example is there some kind of AtomicInteger I can increment in parallel and then just check if it's nonzero on the managed side? Or any other better suggestions?
Even cooler would be if there was some way to early exit all the threads if one of them returns true early.
NativeReference<int> should be atomic. There's a NativeCounter in the entities guide which basically implement 128 integers that are incremented in each thread.
Is that what you are referring to? https://docs.unity3d.com/Packages/com.unity.collections@2.1/manual/jobs-custom-types.html#custom-nativecontainers
yes
Sweet thanks
Setting a int or bool is atomic / no race condition if the value you set it as is constant.
Setting it, but not incrementing right?
Since increment is a read-then-set
But I suppose in my case I can get away with it because I only care about any being true not how many, right?
Yea, that's the only reason why it's safe. Just set it if the condition is true but dont do anything if false.
Sounds good thanks
can you make the same thing happen with CalculateEntityQueryCount?
Maybe, if I were using Entities ๐
Is the conversion system fully removed now?
GameObjectConversionSystem? Yes. It's gone with 1.0
Also maybe a dumb question but can I use using statements and/or try/finally inside of a job? This is just to make sure I properly Dispose any native collections I create inside the job.
Yea, using works inside jobs and burst.
excellent
Behold my skyscraper of a job.
finally - no. i'm not sure with try/catch. i think it works. disposing in a final context is a bit odd.
holy christ, what situation would you even need all of that info? Where it doesn't make more sense to split it up somehow
a split would accomplish very little. you could criticise for not putting all that in structs but he has his reasons.
It's the entire physics simulation in one single threaded job.
All of these NAs are created just before this.
Yeah OK, makes sense then
I mean, the Unity Physics converts all the ECS runtime data to physics data, does a bunch of broad phase detection to order the data so they can multithread the collisions proper.
Admittedly a fair bit more involved than what you're doing but, yeah.
it helps having had lectures with Sean Parkinson, the Unity Physics lead and having him explain a bunch of the entire pipeline
Yea, I've dug through the source of it. Physics is great but it has so much wasted memory.
I almost did exactly that and then thought about how the Job is a struct
You can do that. What do you think native arrays are.
I do not have the time or experience to go digging through it and properly comprehend memory footprint etc ๐
You can have a struct of native arrays as a field of a job struct to reduce the size of the job scheduling and not have the skyscraper.
It's just chunk size. And the required local to world and world transform matrixes.
public unsafe NativeArray<T> GetSubArray(int start, int length)
{
this.CheckGetSubArrayArguments(start, length);
NativeArray<T> nativeArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<T>((void*) ((IntPtr) this.m_Buffer + (IntPtr) ((long) UnsafeUtility.SizeOf<T>() * (long) start)), length, Allocator.None);
NativeArrayUnsafeUtility.SetAtomicSafetyHandle<T>(ref nativeArray, this.m_Safety);
nativeArray.m_DisposeSentinel = (DisposeSentinel) null;
return nativeArray;
}
So, GetSubArray does not create a new allocation, right? only a view
correct
if you write to sub array you will write to original array
if you want a copy do GetSubArray(x,y).ToNativeArray(allocator)
@true mirage if possible it's better to work with Spans as it's more explicit but yeah it's the same thing ๐
Thanks. No, I want views
I keep all voxels in one NativeArray eventually. I mean I change my design from NativeHashMap<int, NativeArray> to NativeArray
@solid rock you could simply use Interlocked operations on a NativeArray<int>(1) and I use that to great effect to sum up how many entities triggered condition X in jobs
but I would like to slice them as chunks and send each chunk to somewhere else
@true mirage so you want copies? or just read-only slices of the original array?
No, I don't want copies
only instead of sending the entire native array, slice it and send only that slice
Maybe, it is a silly way
then GetSubArray() or ToSpan() does exactly that
but working with that slice is easier in terms of indices, etc.
basically it creates a new nativearray which aliases the original
agreed, it's easier to focus on slices instead of juggling indices etc hah
Yes, because sometimes I want to work with only that specific chunk.
World-> Chunks->Voxels
so you have a NativeList<Voxel> which contains all voxels, then you want to slice it up and send it to a job to only process that slice without knowing about the entire list?
sorry another question. In struct types, we cannot define ref types for jobs, OK but can have some methods to return array of value types, correct?
so simply list.ToArray().GetSubArray(myIdx, voxelLength) will give you a NativeArray which you can pass to jobs, and don't have to worry about disposing
Exactly
you want a job to return something? just stuff it in an result array and read it on job completion
For example, to create a chunk, update a chunk, finding a path on a chunk
Forget it. It was another irrelated question
that makes total sense - you just have to trust that C#/Burst/DOTS/Jobs/Unity is doing the right thing and start using array slices more ๐
I converted my entire project from Vector3, Vector3Int to math types, also some part of it to job system. It was time consuming at least for me ๐ญ
Appreciated
generateBarycentric(ref myVerts, in masterIndices);
private static void generateBarycentric(ref NativeArray<vertexData> verts, in NativeArray<int> tris) {
// update the vert array here
}
nodeVertices is a list of verticeData structs, I slice it up into SubArray then pass it to another static function which operates on the entire nativearray without realizing that it's a slice
Wow, afterwards, I should convert many value type arguments to ref and in to optimize them๐ญ
a lot of work
yeah yeah updating to 1.0 was also a lot of work but definitely worth it!
from now on I'll be coding purely unmanaged stuff ๐
ref and in are messy in my eyes :/ but cannot trust AggressiveInlining for private simple methods with value type arguments
hah not that messy compared to the alternative: not trusting the compiler ๐
it was fun learning how powerful C# really is with this DOTS project
before I would have to resort to C++ code to achieve what I wanted
now I can just whip up some burstified jobs and call it a day!
Yes, when I see elapsed times for my routines and boost it 10-100 times I will be happy and refreshed
where are you stuck? you can already de/serialize structs which can be IComps
unity json or newtonsoft one will work
I haven't done it with IComponentData specifically but I've used a ddl based approach before to generate serialization wrappers for json
I mean, isn't that just a subscene?
Oh, I don't know what a timeline is. Sorry.
Does anyone know of:
A. Someone already developing a solution for using baked animation data in combination with vertex shaders on mesh renderers instead of skinned mesh renderers in URP, or
B. Any reason why that wouldn't be feasible for entities?
Hello ^^
We are working on an exam project with DOTS and we are having difficulty reseting the scene we are doing this right now:
DefaultWorldInitialization.Initialize("Default World", false);
SceneManager.LoadScene("DOTS Tornado", LoadSceneMode.Single);
World.GetExistingSystem<TornadoSystem>().Enabled = false;
World.GetExistingSystem<ParticleSystem>().Enabled = false;
World.GetExistingSystem<ConstructionSystem>().Enabled = false;
World.GetExistingSystem<BuildingSystem>().Enabled = false;
World.GetExistingSystem<UpdateCameraSystem>().Enabled = false;
In addition, Is there a way to maybe reset only the subscene?
In addition, Is there a way to maybe reset only the subscene?
just close and open it again
yeah, just call SceneSystem.Unload(subscene)
Thank you we will try that ^^
Is using singleton entities the standard of configuring systems, and is it something I can set up in 0.51 that will migrate to 1.0 easily?
@calm edge singletons is the preferred way to access ISystem-based systems (not SystemBase) so if you are planning to have many ISystems it's a good time to reconfigure
what is preferred for SystemBase then?
for me, I just store references to the managed systems (system A stores ref to system B) via World.GetExistingSystemManaged()
I tend to use the Singleton approach for SystemBase as well. An advantage of singleton as opposed to storing stuff in the system is that singletons know how to deal with dependencies
Other options like ScriptableObjects seem to have a number of issues
singleton entities is a good way to store data per world
otherwise you can use static fields
or I have a singleton struct implementation if you don't want to store data on entities
Is there anything specific I have to do to make trigger event work correctly?
Because for some reason they don't want to work for me
What version of entities?
1.0
But I think I figured out the issue
Which lead me to another problem
How can I check in ITriggerEventsJob if an entity has certain tag?
Because it seems tags don't work with ComponentLookup
They should be fine but you can't get it since there is nothing to get
Has check should be fine though
Well, it isn't fine for me
public partial struct HandleTriggerEvent : ITriggerEventsJob
{
public ComponentLookup<PickUpData> pickUpData;
public ComponentLookup<PickUpTriggerTag> pickUpTriggerTag;
public NativeReference<int> test;
public void Execute(TriggerEvent triggerEvent)
{
test.Value++;
Entity entityA = triggerEvent.EntityA;
Entity entityB = triggerEvent.EntityB;
bool isEntityAPickUp = pickUpData.HasComponent(entityA);
bool isEntityBPickUp = pickUpData.HasComponent(entityB);
bool isEntityAPickUpTrigger = pickUpTriggerTag.HasComponent(entityA);
bool isEntityBPickUpTrigger = pickUpTriggerTag.HasComponent(entityB);
if(isEntityAPickUp && isEntityBPickUpTrigger)
{
var temp = pickUpData[entityA];
if (!temp.following)
{
temp.following = true;
pickUpData[entityA] = temp;
}
}
else if (isEntityBPickUp && isEntityAPickUpTrigger)
{
var temp = pickUpData[entityB];
if (!temp.following)
{
temp.following = true;
pickUpData[entityB] = temp;
}
}
}
}
As it is the code inside if statements doesn't execute but if I remove isEntityAPickUpTrigger and isEntityBPickUpTrigger from them then they start working
well i would say that is probably because they won't have the component
You know for sure that it's the tag causing issues? Because so far we only have your word for that ๐ I don't see the PickupData component in the preview too
Like I said, if I only check for PickUpData, if statements work as expected
Ah, missed that part.
Weird
So, at least to me, it looks like it's a problem with the tag
Well, I guess that at least for now I can just set the "Collides with" property more carefully for triggers
I have: queryALL = GetEntityQuery(ComponentType.ReadOnly<EntityData>()); //But I want to restrict not getting ones back that have AttractorData()
I tried: queryALL = GetEntityQuery(ComponentType.ReadOnly<EntityData>(), !ComponentType.ReadOnly<AttractorData>());
I can't see the negative parameters to a query in the official Unity docs: https://docs.unity3d.com/Packages/com.unity.entities@0.0/manual/component_group.html
ComponentType.Exclude<AttractorData>()
Thank you inumberable tertle, I want to make bank so you can get a house that you can take with you on the road.
No Winnebego?
I thought if you .foreach(bleh){ }).Run();
ecbs.AddJobHandleForProducer(this.Dependency);
That things you change in the EntityCommandBuffer are changed by the next cycle run of the script
I'm setting a flag [Flag_Destroy] and [Disabled], but they don't propagate til a few script cycles later
This leads to items being picked up multiple times instead of once
What's meant by next cycle?
The ECB will run as soon as your ECBSystem is run, so in your case ecbs.
Remember to order your recording systems in the order you expect it. So e.g. writing to an ECB in the SimulationGroup where the ECB system used is BeginSimEcb that will end up running next frame because you recorded it in one frame but the system won't run until next frame
@remote crater if you want, it's possible to rearchitect your flags to be enableable components so you dont have to use commandbuffers and all the pitfalls that come with them ๐
I just returned to find out that dots finally has actual proper 2d support!
2022.2 is in a weird state right now. unofficial f1, beta is at b16 since 18.Nov.
hm, ok seems 2022.2 f1 is at least official since 7.Dec
I was about to say that is how I stumbled upon it
because I watched a recap of the changes in 2022.2 f1
which mentioned it rather nonchalantly but for me that is a huge deal
hm, the official f1 certainly has a different hash than the pre-release f1 1c1f8590be28.
it's very unstable so I had hopes we'd see a new version today
is unity.platforms.windows still the preferred build method for dots stuff? I"m having trouble upgrading my old ass project to 2020.3 as a first step. Should I be using something else?
I do plan to update to latest tho. just doing 2020.3 as a first step.
2022.2.0f1 is unstable?
In version earlier than 1.0 yes
In 1.0 no
ok I"ll just remove it for now then and do the new 1.0 stuff once I upgrade there. can you direct me to the right name or resource so I ccan look into it?
Ok I am already running into an issue again. I just did a clean install of Unity and the Unity hub, as well as a clean install of 2022.2.0f1. I created a 2D URP project and installed the entities packages as well as entities graphics and got a bunch of errors. I did the usual aka re starting the editor where it halts and gives me a warning. If I ignore it I get this in the console Library\PackageCache\com.unity.2d.animation@9.0.1\Runtime\TransformAccessJob.cs(165,62): error CS1955: Non-invocable member 'NativeHashMap<int, TransformAccessJob.TransformData>.Count' cannot be used like a method.
In 1.0 you just build normally
Seems like the 2d animation package is out of date
If there's no update available you just need to wait I guess
2d animation package installed is 9.0.1 and seems to be up to date?
Wait so they pushed something out that is literally unusable?
I do not need 2d animation but because of the whole "features" bullshit I can not disable it facepalms
where did you have the info about 2d support?
oh wait I am semi confused now
It literally has packages for 2d sprites, and 2d physics
aren't those for regular GOs?
you can easily fix it yourself. its 3 lines of code you need to update.
I might give it a try if everything else fails. I just uninstalled the 2d features packages and am re installing it in hopes it picks up something
why u need the 2D features package? its for gameobjects
i do spawn in gameobjects that are synced with entity positions to use animation 2D package. if you can avoid it i would
Because I only use dots for specific performance critical things
At least that was the idea unless the workflow has drastically improved since the .50 days
Also the 2D package has things like the sprite renderer component
which you still need
regardless if you use dots or not
animation 2D does not contain the spriterenderer 0.o
again... unity does not allow you to install those seperately anmyore if they are part of a feature
at least I could not get it to work.
part of a feature?
Just don't install the feature pack, install the packages individually
Features are just a collection of packages
oh ive never seen those feature packs lol
I am aware but it does not let me. As soon as I install a package from a feature it always installs the whole feature without giving me means to intervene.
That is my whole damn issue
Hmm something is really borked here.
Well I do a complete clean install AGAIN maybe its something residual since it should be possible.
maybe just try getting rid of the package in the manifest file
If I just delete the manifest file it would rebuild anyway no?
Would be the faster way if that is the case
i dont think it would rebuild. you would be missing all/most packages then
im not sure if unity recovers anything from the package cache if it cant find a manifest
just delete the package from the manifest you want to get rid of
I am going to try that, and thanks for your patience by the way.
@rotund token btw i have not forgotten about our conversation regarding systems using components they dont know about. looking forward to your ideas if you ever find the time. atm i am recreating the whole UI code for the AI to make it actually useable for you ^^
Ok deleting it from the manifest actually worked! Thanks again
Sadly haven't done any personal project in a week
Had our last major milestone last Friday and rc due in like 9 business days
Hoping to have a few days over Christmas to actually work on my own stuff
is the game announced yet? or still secret stuff?
no worries. its not like im in a hurry. that UI stuff is going painfully slow. experimental graphview throwing bricks in my way continuously
We released it early access over a year ago with no advertising
Just to get feedback
We haven't done an public update in like 11 months though so doing a huge content drop for actual release
I look forward to it being released, who knows how it'll go
you really make me ask the name ? ๐
The game isn't exactly the type of game I play but it'll be nice to have an actual released game from a studio under my name
I try not to advertise as this is my personal account, but it's called beyond contact
id never play my games ๐
If you are interested in the genre I'd strongly recommend waiting till we release 1.0 as there is a lot of changes and updates
ill set it onto my wishlist at the very least. just to spy on you
that said survival games are something i might enjoy. i did play quite a lot of dont starve
From what I understand this was very much inspired from that
yep the description sure reads like it
Holy moly I the new workflow is SO MUCH BETTER
I am outright flabbergasted at how much of an improvement this is from the .50 era
Compile -> error -> restart unity
/s
What workflow is that?
oof
dont worry it got a lot better with latest entities release and 2022.2 out of beta ๐
I was speaking of how the entity conversion workflow and subscenes in general behave now compared to the .50 release
better but not solved ๐ฆ
i also seem to be one of only a few people who can corrupt his burst cache constantly as well
huh?
Sorry, I was asking @rotund token about his burst cache corruption
12+12 (3900x)
ah my bad. I am semi distracted so I was not sure if that was intended for me.
this is like the 4th burst cache corruption i've reported, hopefully not as bad as the last one that took neil 3 weeks to track down even after i got him a 'repo'
though i don't have a good repo for this one yet - i think it's related to asset database lockup and corrupting burst mid way
But yeah the 1.0 preview is much more in line with what I was hoping entities can be. I am quite happy with how it operates and performs now.
the one big issue i have with baking is that i cannot add the same Tag Components from multiple bakers even though empty components wouldnt cause race conditions in bakers.
I havent done too much with baking yet so I might run into that in the future. I was just thinking how much less friction there is now
Which is a great leap in terms of usability and also teachability. The latter is especially critical.
that's odd because nothing changed in the workflow. just bakers have a different API and less features
Compared to .50? Bakers per se did not even exist there as far as I remember
My reference point was .50 and .51
it was the IConvert API before that's been there a long time
I admit I havent used dots extensively before due to lack of the out of the box 2d support so I admit bias to some degree
So it might also just be me lacking the necessary experience. But regardless I am for the first time happy with the state of dots, and hopeful.
would be nice though if they had any built in 2d support. It's not even on the roadmap
It already has to some degree now
2d animations is not yet up to do date but 2d sprites at least work already.
with a companion gameobject yes (pretty sure thats always been possible), but theres no built in DOTS sprite renderer (apart from the abandoned project tiny package)
No it was not possible in .50 at least.
it was. it was possible basically from the very beginning since companion gameobjects where a thing
I did some extensive testing back in .50 and when you just tried to convert a gameobject using the old conversion workflow it would just strip off the spriteRenderer component
And you had an entity that now was no longer at all connected to any renderer.
not sure what you did but im working with spriterenderers on entities for at least 2,5 years now
Well I did not not do much given the games we make are all 2d and thus dots was a non started because of the lack of out of the box 2d support.
Of course you could do the whole use a quad and then render it that way, but that is not exactly designer friendly.
you can just use gameobjects for all 2D things though.
we use 2D animation and tilemaps
and only render and sync gameobject positions that are actually on screen
I am still unsure about how to properly deal with it. My personal experience with ECS (which is admittedly rather oldschool) was more in the sense of the paradigm, stemming from the old roguelike days.
Which makes it a bit hard to wrap my head around how to properly utilize it in a Unity context but that is a me problem admittedly.
Since normally it was an either or kind of thing.
But that seems to be a)not the intended workflow in Unity and b) seems not really feasable in a Unity context.
If I have a PhysicsBody on a root entity, and then during runtime, parent another Entity with its own PhysicsCollider to the root entity, will Physics system automatically consider the newly childed entity's collider as part of the compound collider on the body? Or is this something I have to do manually?
if i recall correctly compound colliders are just a dynamicbuffer of colliders on the root. just inspect that buffer and see what happens
Ah, I see the PhysicsColliderKeyEntityPair buffer. I'll play around with this.
Does Jobs/Burst still not support GeometryUtility.TestPlanesAABB?
It can't because that function takes a managed array as a parameter
why can't you believe that?
it's part of UnityEngine
Unity.Rendering.FrustrumPlanes has native versions
Intersect(NativeArray<float4> cullingPlanes, AABB a)
or maybe more useful
Intersect2(NativeArray<PlanePacket4> cullingPlanePackets, AABB a)
Intersect2NoPartial(NativeArray<PlanePacket4> cullingPlanePackets, AABB a)
How exactly does PhysicsCollider.CastRay work? Description says Cast Ray against this collider. Can someone give me a quick example?
Is it just shorthand for CollisionWorld.CastCollider except that the collider is already given?
I have a single pickup: Scrap. I assign a tagged component: Bastian & Disabled in the .forEach via ECB in a SystemBase. You'd think the next .foreEach.WithNone<Bastion> would not execute for it since it should have Bastian and Disabled attached by the time the next OnUpdate .ForEach in that SystemBase runs(next cycle), but it often takes many frames/cycles/running of the .foreach until the Bastian & Disabled tags are applied.
The goodnews here is literally my entire game is basically done at this point as far as DOTS/ECS, I have some insanely complex stuff other than this.
I could always hack job by not repicking up something an exact position within X ms.
I want to try and get this clean tho.
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
public partial class SystemAttractor : SystemBase
public static EntityCommandBufferSystem ecbs;
ecbs = World.GetOrCreateSystem<EndInitializationEntityCommandBufferSystem>();
Dani was mentioning order of operations and those give some idea of when they execute... Still... Still if one OnUpdate ECB applies a Component Tag, why is there multi frame OnUpdate(cycle) lag until applied?
Wonderful, Thanks!
What's fun is the next thing I do after this is MASSIVELY database all sorts of spaceship/futuristic equipment items, make em tantalizingly drop for the player depending on common/unc/rare/epic/legendary/unilegendary with particle effects. Then Random encounters/Missions I have story boarded in. Game will be finally at done enough to be fun state by Christmas.
I'm taking AI images I harvested (1.5 million or so now), and they help me get sci fi ideas for strange things.
It's 2022 and AI is helping us with creativity!
Ok found the real problem... It's literally not EVER applying the tag, probably due to a bug.
Thanks everyone for responding.
The docs you gave me refers to legacy Collider. I am specifically asking about DOTS PhysicsCollider, I assume that is the equivalent behavior? If so, do I still need to specify the CollisionFilter under RaycastInput?
Yes sorry I meant it was "similar to" the page linked. I'm actually unsure if the collisionfilter matters here, but testing this should be pretty simple
Yeah I'm testing and it's not picking up the hit at all. With or without filter set.
Sometimes when placing an object into the scene, it will overlap with others, is there a way to "push" it out so they are next to each other. Otherwise, the physics system "pops" it out dramatically causing all kinds of havoc.
you could make some editor script for that
no, this needs to be during runtime
ah
it would be nice if collider cast could give you the position of the collider a moment of impact instead of just hit.Position
should be simple then, no?
what do you mean?
it gives you fraction
I thought fraction was Start -> hit.Position (Fraction) -> End
amount of distance they overlap
and angle
so you can just move back
based on those values
how would I get distance of overlap?
fraction
hmm..it appears I'm not understanding fraction correctly. I thought it was just a normalized percentage between Start and End ray where the hit.Position is.
in unity physics?
oh yeah that's what it's meant to be
but for some of the cases it's just wrong
it's 0 to max distance or something like that
what ray? shouldnt you do a collider casy?
oh yeah, fraction is different for collider cast. Is that how it works? Fraction in collider cast is where the collider position "stops" at moment of impact?
i dont remember specifics, but character controllers use it heavily for collision detection
crap ok, I'll run some tests
FixedStepSimulation Group can run multiple times per frame based on your framerate. EndsimulationCommandBufferSystem will run only once per frame.
Holy crap it worked! Collider cast and setting the position to math.lerp(castInput.Start, castInput.End, colliderHit.Fraction); did the trick! Thanks man!
๐
When we was using EntityQuery.CreateArchetypeChunkArrayAsync(Allocator, out JobHandle) we was getting initialized array instantly and then fetch job was setting elements.
That is important, because further scheduling depends on elements count. From now this method is obsolete and we should use EntityQuery.ToArchetypeChunkListAsync(Allocator, out JobHandle) which returns NativeList<ArchetypeChunk> instead of NativeArray<ArchetypeChunk>.
Will it have same count as array on initialization and we can just replace all array appearance with list?
no
the old CreateArchetypeChunkArrayAsync said async but it was a lie
it caused a sync point if you had filters this is why it was replaced
Ok, so I can't rely on count before complete, only on capacity which isn't always same amount
either use ToArchetypeChunkArray and just suck the sync point up or if you don't use filters use CalculateEntityCountWithoutFiltering (if you filters you have no choice, if you want the count on main thread you need a sync point)
I need chunks array as well
I use SCD filter, why it leads to sync point with no choice? Why can't I schedule async list fetching for each SCD?
I guess I know the answer, because it will thrown parallel accessing exception, because it is now actually parallel
is an EntityQuery managed type and therefore not usable in ISystem with Burst?
you were already causing sync points in 0.51
if you looka t the source of CreateArchetypeChunkArrayAsync and go into the CreateArchetypeChunkArrayAsync method
{
var chunks = new NativeArray<ArchetypeChunk>(chunkCount, allocator, NativeArrayOptions.UninitializedMemory);
var gatherChunksJob = new GatherChunksJob
{
MatchingArchetypes = matchingArchetypes.Ptr,
entityComponentStore = matchingArchetypes.entityComponentStore,
Offsets = offsets,
Chunks = chunks
};
jobHandle = gatherChunksJob.Schedule(archetypeCount, 1, dependsOn);
return chunks;
}
else
{
var filteredCounts = new NativeArray<int>(archetypeCount + 1, Allocator.TempJob);
var sparseChunks = new NativeArray<ArchetypeChunk>(chunkCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
var gatherChunksJob = new GatherChunksWithFilteringJob
{
MatchingArchetypes = matchingArchetypes.Ptr,
Filter = filter,
Offsets = offsets,
FilteredCounts = filteredCounts,
SparseChunks = sparseChunks,
entityComponentStore = matchingArchetypes.entityComponentStore
};
gatherChunksJob.Schedule(archetypeCount, 1, dependsOn).Complete();```
if RequiresMatchesFilter
gatherChunksJob.Schedule(archetypeCount, 1, dependsOn).Complete();
it calls complete on the dependency
any WithChangeFilter on EFE etc did this as well
this is why i wrote all my change filter inside IJobEntityBatch in 0.51
and never used change filter on a query
yep, I've got this. But now, when I know it, I want to avoid sync point if it is possible. Maybe through custom SCD fetching job
theres no sync point in doing this in 1.0 now
and they fixed this by making it return a list with a dependency
the issue is just if you need count on main thread
wow, great, changing all that to IJobChunk whould be horrible
so the solution is just avoid that
EntityQuery works fine in ISystem with burst
I am currently trying to figure out what causes the "Assertion failed 'ValidTRS()' Error" that is plaguing us for some time. I wrote a system that outputs the matrix and the owning entitiy when a matrix is not a valid TRS:
[BurstCompile]
public partial struct AssertValidTRSDebugSystemJob : IJobEntity
{
public unsafe void Execute(Entity entity, in LocalToWorld localToWorld)
{
var ltw = localToWorld;
var mat = *(UnityEngine.Matrix4x4*) <w;
if (!mat.ValidTRS())
{
string code = @$"new Matrix4x4(
new Vector4({mat.m00}f, {mat.m10}f, {mat.m20}f, {mat.m30}f),
new Vector4({mat.m01}f, {mat.m11}f, {mat.m21}f, {mat.m31}f),
new Vector4({mat.m02}f, {mat.m12}f, {mat.m22}f, {mat.m32}f),
new Vector4({mat.m03}f, {mat.m13}f, {mat.m23}f, {mat.m33}f)
);";
Debug.Log($"InvalidTRS on entity {entity} {mat.determinant}\n{mat}\n{code}");
}
}
}
From the looks of it I cannot figure out while the matrix should be an invalid TRS matrix.
It even generates the code to create the same matrix in C#.
I use this code in a Test. But the test returns true for ValidTRS ๐ฌ
Does anybody have an idea why this might happen?
How should we build in latest entities package? Back to vanilla build window?
yes
I haven't tried but I believe content management should allow you to
Swapping a sharedcomponent for an entity query doesn't lead to structural changes right?
question is more - how do we obtain built subscene
Hi guys, I'm getting these errors when I run my compiled project.
Could not open file C:/Users/SeanN/Desktop/WindowsManual/AssemblyRTS_Data/StreamingAssets/EntityScenes/e16b810eef924d9c922185003659a43f.entityheader for read
Could not open file C:/Users/SeanN/Desktop/WindowsManual/AssemblyRTS_Data/StreamingAssets/EntityScenes/143b1a87ba264c4e944df2fa769a50e3.entityheader for read
Could not open file C:/Users/SeanN/Desktop/WindowsManual/AssemblyRTS_Data/StreamingAssets/EntityScenes/eef4652b96b74b5c9e73b7ea6334d7f6.entityheader for read
Loading Entity Scene failed because the entity header file couldn't be resolved: guid=e16b810eef924d9c922185003659a43f.
Loading Entity Scene failed because the entity header file couldn't be resolved: guid=143b1a87ba264c4e944df2fa769a50e3.
Loading Entity Scene failed because the entity header file couldn't be resolved: guid=eef4652b96b74b5c9e73b7ea6334d7f6.
``` (etc.)
I'm using Unity 2022.0.0f1 with ECS 1.0 experimental, so maybe this issue will be resolved once I upgrade to ECS 1.0 prerelease? ๐คทโโ๏ธ
Just noticed that my StreamingAssets folder is indeed missing these files. I probably deleted them on accident :p
How can I have these files be regenerated?
reimport might help
Reimporting the subscenes didn't help. Currently doing a 'reimport all', maybe that will fix it.
That didn't generate the files either
I figured it out. A matrix multiplication resulted in the m33 value not being 1f but 0.9999998f which makes it an invalid TRS matrix ๐ฌ
in your project folder. MyProject/Temp
you are missing calling the AddJobHandleForProducer on the ECBS.
How can I have these files be
Ok, that seems reasonable... I was going to ask why my Systembase was running many times before the ECB could finish... What's the industry standard aka way you guys are handling this if I want my system base to only run once per frame to make sure ECB is processed properly?
I even had my code prepped https://pastebin.com/rVQecUfp
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.
Once I solve this issue, that was causing multiple pickups of a single item... I'm literally done with DOTS/ECS techs, and I'll be databasing in items/encounters/storyline ๐
Maybe there is a simulation group that only runs once per frame
Or maybe I can jury rig it based off getting the time in milliseconds?
Maybe unity has a frame number counter
Time.frameCount
you update in FixedStepSimulationSystemGroup
which might run multiple times per frame if it needs to catch up
issue, the problem I have is
My foreach is adding to say score
on a pickup
And I add a tag: Disabled
but it adds the score 2-3-6 times etc
depending on how many frames cycle
because ECB only updates once a frame
I think with Time.FrameCount, I can deny the run of the same frame more thanonce
and I'm good to go
after foreach like always
My entire code for the class: https://pastebin.com/rVQecUfp
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.
I'v seen it yeah
if your buffer system runs in normal frame update
then fixed step can cause desyncs
Thanks everyone. I think I should be good to go.
YUP!
I use Time.frameCount
Now I can just store it as a local variable and never run a 2nd foreach by checking Time.frameCount against my local
Awesome awesome awesome, you guys all rock. Hopefully I can start competing with Eve online and you guys are friends with a kachillionaire, not just a question asker ๐
Cuz I hook my friends up ph@t ๐
everything exept fixedstepsimulation group runs once per frame
you could have moved it anywhere ^^
Good to know, but I have an array of spiderweb systems, I'm afraid of touching less some parallel thing flip out, this is as dicey as pointer arithmatic
My next game, I'll be a bit more self aware, this one, I'm just like... Don't touch the balanced deck of cards, it's perfectly situated on the tower of jello.
In perfect ECS scenario, removing 1 system will never affect others directly
Updating in parallel, the timing matters
That's why there's an order integer for the parallelECBs
If I don't use FixedStepSim, it might change orders
wdym updating in parallel?
The solution I have at hand, is pretty much perfect
ParallelCommandBuffers
I have some systems with those, and if the order number is off, my game throws crazy errors
๐ฅด
You know when it tries to destroy phantom things in parallel
Don't worry! It's all good!
It took me a whole year and a half to get here, you guys did good.
Now my ECS/DOTS engine is pretty much 100% complete. To extend and add from here is quite trivial. Maybe within 10 days you can see some fun playable stuff.
Thank you for not just making parallel processing easy (something no one's said ever), but also great support on this chat forum and other forums. I would not have been able to have made such an effective system without help from all you guys. Like I said, I make bank, and you just ask me for help financially who helped me and you got it. I'm gonna try and compete with Eve online whomakes 100 million/month. The DOS/ECS tech + networking tech I have should in theory be able to not just beat Eve online's max players in one fight in a MMO, but do it at 60 FPS, action combat
Enjoy your dev day. I pray everyone has a good productive day and enjoys your work. I'm gonna organize my creative design notes, onto the finally fun frontier every game dev loves to be at!
Suppose elements of a native array can change but not in jobs or a specific job for example. How can I add [Readonly] attribute for it?
What is the solution?
public struct Voxel{}
You add the Readonly attribute in the specific job struct that you want it to be readonly in
I have used main data structures as job data. So, should I define specific structures for jobs?!
For example one of my jobs here. There are several Readonly native collections and one WriteOnly one that is used for output.
Voxel struct is the main data structure to store voxel data.
It can be used in job or not
Sounds like your Voxel is much like my Coordinate
it's just data
the Readonly attribute would go on a specific collection of Voxels that a job would operate on
Yes, for example I have VoxelWorld. It stores NativeArray<Voxel>.
NativeArray itself does not change but voxels inside can change in a job or not in another job
yep that's fine. The jobs themselves view a particular collection as Readonly or not
you do that as in my example above
If you need to change the voxels in the array btw that is changing the array
since these are all value types
Lets ask my question in another way.
When I put [ReadOnly] for a container, it means that container is readonly but values inside can change?
no
it means it's readonly
the values cannot change
you can only read values from it
not change anything
Yes, so I am right
you can neither change elements, nor remove, nor add
My VoxelWorld struct has NativeArray<Voxel>.
It cannot be [ReadOnly] because in some jobs, voxels can change.
I send VoxelWorld to my job. Should I define new struct and then assign NativeArray inside then mark it [ReadOnly] for that specific job?
You should only be using [Readonly] within job definitions yes
it means that from the perspective of this job, the collection is read only
Don't forget about [WriteOnly] too!
Useful for collections used as output for your job
[BurstCompatible]
public struct PathFindingJob : IJob
{
[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;
It is OK but RoadObstacleChecker,RoadWeightCalculator, etc.
It is nested
[BurstCompatible]
public struct RoadWeightCalculator : IPathWeightCalculator
{
private static readonly int3 Up = (int3)math.up();
private readonly int _chunkSize;
private NativeHashSet<int3> _sourcePointSet;
private PathFindingWeightList _weights;
private VoxelWorldData _voxelWorldData;
[BurstCompatible]
public struct VoxelWorldData
{
private readonly float3 _worldOrigin;
private readonly int _worldSize;
private readonly float3 _voxelSize;
private readonly int _chunkSize;
private readonly int _worldLength;
private readonly int _voxelCountInChunk;
public NativeArray<Voxel> Voxels; // It is readonly for PathFindingJob specific job
public NativeArray<FirstDownwardBlockedVoxel> FirstDownwardBlockedVoxels;
Is there a built-in way to copy a PhysicsCollider? Or do I have to manually do it? If so, does this mean I need to do a switch (colliderType) deal?
Copy it in what sense?
I have lots of items that share a collider via pointer in PhysicsCollider. I want to "pick" an item up, modify it's collision filter WITHOUT touching the shared pointer. So I want to copy the shared collider to it's own separate unique, modify it, assign it to the item that's picked up.
Well there's the IConvexCollider interface, but I can't find the documentation
might be helpful?
ah...is this valid? var uniqueCollider = new PhysicsCollider { Value = itemSharedCollider.ColliderPtr->Clone() };
After adding [Readonly] attribute to fields of Job data structure (PathFindingJob ) and not nested data structure, my problem was solved. thanks
Yeah docs are so sparse...
One problem was
You cannot use a writable container in different data structures. ... and ... are the same
aliasing
write is the default state so the tag isn't really required other than being explicit about the usage
Isn't it read/write by default?
hm, i'm not aware [WriteOnly] prevents you from reading. let me check
Presumably it would with that name ๐
The default is read/write surely. It is logical
the tags are for the job system to figure out how to queue jobs so it doesn't differentiate between it. it's either read or read/write as write is the same thing really. other read/write states are saved in the handles themselves like ComponentTypeHandle. same goes for NativeArray
Maybe share the code for your Job(s) and how you're creating and scheduling it?
for example, with a readOnly marked NativeArray you can't request a RW pointer or set data
but those are 2 seperate things for the same concept
[BurstCompatible]
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 PathResult PathResult;
public PathFindingJob
(
AStar aStar,
int3 sourcePoint,
int maxDistance,
int3[] targetPointArray,
bool returnFirstValidPath,
RoadTargetChecker targetChecker,
RoadObstacleChecker obstacleChecker,
RoadWeightCalculator weightCalculator
)
{
_aStar = aStar;
_sourcePoint = sourcePoint;
_maxDistance = maxDistance;
_targetPointArray = new NativeArray<int3>(targetPointArray, Allocator.TempJob);
_returnFirstValidPath = returnFirstValidPath;
_targetChecker = targetChecker;
_obstacleChecker = obstacleChecker;
_weightCalculator = weightCalculator;
PathResult = new PathResult(Path.Empty);
}
public void Execute()
{
PathResult = _aStar.FindPath
(
_sourcePoint,
_maxDistance,
_targetPointArray,
_returnFirstValidPath,
_targetChecker,
_obstacleChecker,
_weightCalculator
);
}
public void Dispose()
{
_targetPointArray.Dispose();
}
}
@solid rock .
You would need a NativeReference<PathResult> if you want to change it in the job
var job = new PathFindingJob
(
_pathFinder,
sourcePoint,
aStarSetting.SearchRange,
roadPoints,
returnFirstPath,
targetChecker,
new RoadObstacleChecker
(
_height,
_roadOrigin,
_buildingSize,
targetChecker,
_voxelWorldData
),
new RoadWeightCalculator(_chunkSize, sourcePointSet, _weights, _voxelWorldData)
);
var jobHandle = job.Schedule();
jobHandle.Complete();
var pathResult = job.PathResult;
Thanks. It says
The type 'PathFinding.PathResult' must be valid unmanaged type (simple numeric, 'bool', 'char', 'void', enumeration type or struct type with all fields of unmanaged types at any level of nesting) in order to use it as a type argument for 'T' paramete
It is struct
a struct containing what
[BurstCompatible]
public readonly struct PathResult
{
public Path Path { get; }
public NativeArray<PathStep> Steps { get; }
Again struct
[BurstCompatible]
public readonly struct Path
{
public static readonly Path Empty = new(new NativeArray<int3>(0, Allocator.TempJob));
public bool IsEmpty => Points.Length == 0;
public int Length => Points.Length;
public NativeArray<int3> Points { get; }
You didn't share any fields
[BurstCompatible]
public readonly struct PathResult
{
public Path Path { get; }
public NativeArray<PathStep> Steps { get; }
public bool IsEmpty => Path.IsEmpty;
public PathResult(Path path) : this(path, new NativeArray<PathStep>(0, Allocator.TempJob))
{
}
public PathResult(Path path, PathStep step) : this(path, new[] { step })
{
}
public PathResult(Path path, PathStep[] steps) : this(path, new NativeArray<PathStep>(steps, Allocator.TempJob))
{
}
public PathResult(Path path, NativeArray<PathStep> steps)
{
Path = path;
Steps = steps;
}
}
[BurstCompatible]
public readonly struct Path
{
public static readonly Path Empty = new(new NativeArray<int3>(0, Allocator.TempJob));
public bool IsEmpty => Points.Length == 0;
public int Length => Points.Length;
public NativeArray<int3> Points { get; }
public Path(int3[] points, Allocator allocator = Allocator.Temp)
{
if (points == null) throw new ArgumentNullException(paramName: nameof(points));
Points = new NativeArray<int3>(points, allocator);
}
public Path(NativeArray<int3> points)
{
Points = points;
}
}
I'm not sure your struct can contain a native collection
[BurstCompatible]
public struct PathStep
{
public int3 SourcePoint;
//public NativeArray<int3> TargetPoints;
public int LoopCount;
public int SkipCount;
//public NativeArray<int3> SeenPoints;
}
I doubt as well. WTH
When it gets the result, it should return it easily! the job is done
int3[] is managed
Wow :/
I don't see an int3[]
It is only ctor argument not fields
Thanks, dudes
The other thing is since you made those properties get only, the system has no way to initialize your structs
especially without the use of your constructors
which it certainly can't use
I said, using ctor, why can't?
Because it's just not that kind of system
it's not going to analyze your code for matching constructors like some kind of dependency injection system
it's not that smart in that area
OK, I remove all of them, only simple public fields
I should have done it before ๐
Anyway I'm not convinced you can have a NativeCollection as a field
Yes, the problem is NativeArray inside PathResult
not int[] array in ctor args
Sounds about right
With the job system generally you kinda "flatten" everything
Like just having separate NativeArray<PathStep> and NativeArray<int3> and passing those directly into the job
Thanks, so the only way is to separate data inside PathResult and define NativeArray inside jobs as result?
It ruins structure of my codes really brutally
I don't know if that's the only way but it's the straightforward way
Generally you won't be able to maintain the same object structures inside jobs as in your managed code
Often you will want/need a translation layer that converts the data from managed to something your Job understands and back
where/how are you disposing all these random NativeArray tempjobs you allocate?
He isn't!
tertle have you found out how to create blobs in a BakingSystem?
you are not on entities 1.0, right?
[BurstCompatible] gives it away somewhat because that tag is obsolete. ๐
also not needed, it's for writing tests
I think he wants [BurstCompile] tbh
right, he wrote [BurstCompatible] public struct PathFindingJob : IJob, IDisposable - use [BurstCompile] tag and remove it from the structs. it's not needed
Easy mistake to make if you're not paying attention because Compatible shows up before Compile in the auto-completion suggestions
now it also makes sense that burst doesn't complain about int[] - it's never burst compiled
Ok, I got a gnarly situation. During runtime, I have two separate entities. At some point (and this is done on main thread outside jobs and Entities.ForEach, just good ol' EntityManager inside a SystemBase) I parent one of the items to the other. I verify this in the inspector, all looks good, the parent has the referenced entity in the child buffer, and the child has the referenced entity in the Parent component. Then, many many many, like thousands of frames later, I take that parent entity (with its new child) and I need to run a foreach (var child in GetBuffer<Child>(parentEntity)) in order to do some stuff.
Just running that foreach throws the following every time for the entire lifetime of the entity:
ObjectDisposedException: Attempted to access BufferTypeHandle<Unity.Collections.NativeText.ReadOnly> which has been invalidated by a structural change.
How can I "validate" it? Or I don't really know what I need to do here.
Is there something else I need to do besides AddComponent<Parent> and AddComponent<LocalToParent>?
Or is this a bug?
Here is the code that does the parenting:
private void AssembleProtocol()
{
if (!_assembleReady)
return;
var itemInHand = App.Player.Inventory.ItemOnHand;
var targetItem = App.Player.LookTarget;
var targetItemTransform = GetComponent<LocalToWorld>(targetItem);
EntityManager.AddComponentData(itemInHand, new Parent { Value = targetItem});
EntityManager.AddComponent<LocalToParent>(itemInHand);
SetComponent(itemInHand, new Translation
{
Value = _ghost.Position - targetItemTransform.Position
});
SetComponent(itemInHand, new Rotation
{
Value = math.mul(_ghost.Rotation, math.inverse(targetItemTransform.Rotation))
});
unsafe
{
var itemCollider = GetComponent<PhysicsCollider>(itemInHand);
itemCollider.Value.Dispose();
EntityManager.RemoveComponent<PhysicsCollider>(itemInHand);
EntityManager.RemoveComponent<PhysicsColliderKeyEntityPair>(itemInHand);
itemCollider = App.Player.Inventory.ItemCollider;
var colliderBuffer = GetBuffer<PhysicsColliderKeyEntityPair>(targetItem);
colliderBuffer.Add(new PhysicsColliderKeyEntityPair
{
Entity = itemInHand,
Key = new ColliderKey(itemCollider.ColliderPtr->NumColliderKeyBits, 0)
});
}
_ghost.Destroy();
App.Player.Inventory.DropItem();
}
I got a bit of a spike on startup and it bumps my unity.netcode to an odd state. Any ideas?
(not the spike, I mean on how to recover from this effed up elapsed time)
Can you share the code that iterates the child buffer? That's where the error is coming from, right?
private Entity BuildGhostFromSource(Entity item)
{
Assert.IsFalse(item == default, "Item cannot be null");
Entity ghost;
if (EntityManager.HasComponent<MaterialMeshInfo>(item))
{
ghost = EntityManager.Instantiate(App.Prefabs.GhostPrototype);
var info = EntityManager.GetComponentData<MaterialMeshInfo>(ghost);
info.Mesh = EntityManager.GetComponentData<MaterialMeshInfo>(item).Mesh;
EntityManager.SetComponentData(ghost, info);
}
else
ghost = EntityManager.Instantiate(App.Prefabs.GenericPrefab);
#if UNITY_EDITOR
EntityManager.CopyName(item, ghost, "{0} [Ghost]");
#endif
var scale = new NonUniformScale { Value = new float3(1f, 1f, 1f) };
if (EntityManager.HasComponent<NonUniformScale>(item))
scale = EntityManager.GetComponentData<NonUniformScale>(item);
EntityManager.AddComponentData(ghost, scale);
if (EntityManager.HasBuffer<Child>(item))
{
EntityManager.AddBuffer<Child>(ghost);
foreach (var childItem in EntityManager.GetBuffer<Child>(item))
{
var childGhost = BuildGhostFromSource(childItem.Value);
EntityManager.SetParent(childGhost, ghost);
EntityManager.CopyComponent<Translation>(childItem.Value, childGhost);
}
}
return ghost;
}
You can't do structural changes while iterating a buffer
Looks like you are iterating the child buffer and then recursively calling BuildGhostFromSource which does a structural change (AddBuffer)
One option is to change your foreach (child) to a classic for loop and call GetBuffer each iteration. But that isn't exactly the fastest option. You could also turn the buffer into a native array to grab a snapshot of it
Even if you never modify the dynamic buffer, ANY structural change any where else will invalidate the GetBuffer returned valid
Alternatively, move all your structural changes for the ghosts to an ECB
Thanks so much. I wouldnโt have figured this out on my own.
no problem. That one has bitten me quite a few times
Its possible that you have another problem. Typically the error will say that the Child buffer was invalidated. Not sure why its complaining about Unity.Collections.NativeText.ReadOnly, whatever that is
Let me take care of the recursion first and see if this goes away.
Before you take care of the recursion you're going to want to take care of the recursion
that's while(true)
How to fix recursive problems:
To fix your recursive problem, see ยดHow to fix recursive problemsยด
just get the baking system
it holds the blob asset store
ok cool, thanks
I'm trying this approach, but the issue is the deferred Entity ID. Is there a way for me to pick up the correct ID on next frame and store it?
You can usually work around this by using the ECB to store the deferred id in a component
Yeah I figured this is still the approach, just thought to check if they made a utility that can do this for me.
Fuck there is so much red tape, I'm already losing track of what I was doing in the first place lol.
The way I've managed a similar issue before was storing it in a DynamicBuffer
Looks like that was the problem. When I fixed the recursion issue, the problem went away.
LOL, YES
Ok, next question. So when I parent an entity to another, these entities have their own PhysicsColliders. From what I can tell, the children of an entity that has a body do not have a PhysicsCollider component or a PhysicsColliderKeyEntityPair buffer attached to them. So when I parent a child, I add the following element to the parent's PhysicsColliderKeyEntityPair buffer:
var colliderBuffer = GetBuffer<PhysicsColliderKeyEntityPair>(parentEntity);
colliderBuffer.Add(new PhysicsColliderKeyEntityPair
{
Entity = childEntity,
Key = new ColliderKey(childCollider.ColliderPtr->NumColliderKeyBits, 0)
});
I'm not sure what to put for the Key field. The ColliderKey constructor takes two args: numSubKeyBits and subKey. What do I put for those values and what do they mean? Or is it enough to just assign the Entity and that's it? So far I just copied the NumColliderKeyBits from the child collider. How does this work?
To boos speed in editor, I should uncheck safety checks and debugger?
Is there something like Linq for NativeArray and NativeList?
what's wrong with regular Linq, they implement IEnumerable<T> so Linq works.
linq does not work in burst
i have a bunch of linq like extensions in here for native arrays though if you want that work in burst
Where, Select, All, Any, FirstOrDefault, IndexOf
Yes, works but it is not slow?
also boxing
Yes, I have implemented some of them and also Reverse, FastRemove, etc.
You know why I ask, because if there is I do not need to implement them :/
Also, I need PriorityQueue and Octree job friendly. Probably, I can find it
whether or not Linq is "slow" depends on what you are doing. A generalized "Linq is bad" attitude doesn't make much sense. In a burst compiled jobs its probably not really the right way of processing data. It being generally not a context where you need/want lazy evaluation
for, foreach and iterator in jobs nativearray and nativelist, all are almost the same? I will test it
if its just about convenient API in burst, self-implementing them so you can know exactly what's going on is probably the right choice, since bursted code is all about the optimization details.
Thanks. Finally, I have implemented my algorithm with job system, it works
but it seems it is slow at least in editor:/
Also, I see some errors although it returns the result correctly.
does anyone ever lock up after a recompile, hitting play, and subscenes don't seem to convert
and if you attach a debugging to unity and force breakpoint it's lokced up on
AssetDatabasExperimental.ProduceArtifact()?
being called from ResolveSceneReferenceSystem
quitting from this lockup is what also seems to cause my burst corruption
after a reload into the project the burst cache is completely corrupted and requires another delete + restart
i can repo this reasonably easily
i probably overrode my logs but i'll look again next time
but i'm pretty sure i've looked into this before and saw nothing of interest
on a side note, 2022.2.1f1 seems to have broken openupm?
One or more packages could not be added to the local file system:
com.bovinelabs.analyzers: Hostname/IP does not match certificate's altnames: Host: openupm.sfo2.cdn.digitaloceanspaces.com. is not in the cert's altnames: DNS:*.ssl.hwcdn.net, DNS:ssl.hwcdn.net```
but can I reproduce it easily?
erp, one sec
probably not
considering i have not seen anyone else report this specifically
i can throw you the project, you might be able to do it ๐คทโโ๏ธ
I've been running into an issue that sounds similar, but haven't attached a debugger to see what's going on. I'll hit play and unity will totally freeze. Mouse cursor won't render over the editor window. Basically no cpu usage of the unity process. I have to force exit the process and restart unity, then everything is fine.
yeah sounds familiar
hook up a debugger next time and let me know if it's same spot
i'll feel a tiny bit better if it's not just me
Not sure what you mean by burst cache corrupted, but I do get the entity subscene header can't be loaded thing sometimes. Don't think its correlated with the above issue though
This Exception was thrown from a function compiled with Burst, which has limited exception support.
0x00007ff7026706fd (Unity) burst_signal_handler
0x00007ff809428b4c (ntdll) RtlDeleteAce
0x00007ff8094012c6 (ntdll) RtlRaiseException
0x00007ff809450f4e (ntdll) KiUserExceptionDispatcher
0x00007fff921e84cf (9c33427477f2fcf9f52aa87bcd77068) Unity.Physics.Systems.CreateJacobiansSystem::Unity.Physics.Systems.CreateJacobiansSystem.OnUpdate (at I:/Documents/BovineLabs/com.bovinelabs.shattered/Library/PackageCache/com.unity.physics@1.0.0-pre.15/Unity.Physics/ECS/Base/Systems/UnityPhysicsSimulationSystems.cs:271)```
i get a bunch of null refs from function pointers
okay yeah I don't think I've seen those errors
doesn't happen every time for me and i suspect it's just related to me force closing unity during this lockup
while burst is compiling
I'll try attaching a debugger next time it happens
well that didn't take long. @rotund token
Lots of burst threads waiting but found one with the same call stack
yay ๐
and yeah, it does look like I was when trying to enter playmode while something was happening in the background
I don't have the "Hold on (busy for ...)" loading bar that you seemed to have on the forum thread
pretty sure I had turned off burst compilation now that I think about it
i dont have that always
the one i reported today did not have that
just the subscene trying to load like you're seeing
NativeHashMap AsParallelWriter not work in ecs 1.0, what can i replace it with
There is parallel version. It's standalone type
I need to tryAdd NativeHashMap in IJobEntity
sir. it was split into multiple types
parallel and singlethread
there is no parallel writer anymore
๐
thank! oh is NativeParallelHashMap, blind me,
In some cases, I have a game object in sub scene, but I don't want it to actually convert. I don't see option in Baker for DestroyEntity or AbortConversion type deal. Is this not possible?
add tag and destroy in system
ok
this is going to drive me nuts
because it's not allowed to be static due to SystemAPI
is it?
check if codegen works
it might simply ignore static modifier
it's an error in unity
if you make it static
SystemAPI needs instance context or something like that
it makes sense
not really. unless they check for static attribute specificaly
look at BakingOnlyEntityAuthoring. beware that it marks all children as baking only entities too
hmm which callback can i use to start codegen on multiple scriptable objects before the game starts? it will need to recompile after the codegen
are you talking about source gen?
no i am generating classes from templates
ah
each scriptable object needs to generate a class (a generic system)
up until now i codegenerated whenever the user made a change in the scriptable object in OnValidate. but that is a really slow workflow. the generated classes are not important while in editor so i can codegen only once at gamestart instead of each change the user makes
i just dont know how to trigger the codegen at the right time
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?
Hi dudes.
My code works but there is an error in console log
F:\Work\Companies\PelleStudio\Projects\MiniCityProject\MiniCity\Assets\Project\Game\Scripts\Bitzooma\MiniCity\Runtime\Utility\PathFinding\AStar.cs(387,21): Burst error BC1059: Method `Bitzooma.MiniCity.Utility.PathFinding.AStar.<>c__19`3<Bitzooma.MiniCity.Utility.PathFinding.RoadTargetChecker,Bitzooma.MiniCity.Utility.PathFinding.RoadObstacleChecker,Bitzooma.MiniCity.Utility.PathFinding.RoadWeightCalculator>.<FindPath>b__19_0(Bitzooma.MiniCity.Utility.PathFinding.Node)` is being compiled as a function pointer, but both it and its declaring class `Bitzooma.MiniCity.Utility.PathFinding.AStar.<>c__19`3` are missing the [BurstCompile] attribute. To fix this error, add the [BurstCompile] attribute to `Bitzooma.MiniCity.Utility.PathFinding.AStar.<>c__19`3<Bitzooma.MiniCity.Utility.PathFinding.RoadTargetChecker,Bitzooma.MiniCity.Utility.PathFinding.RoadObstacleChecker,Bitzooma.MiniCity.Utility.PathFinding.RoadWeightCalculator>.<FindPath>b__19_0(Bitzooma.MiniCity.Utility.PathFinding.Node)` and `Bitzooma.MiniCity.Utility.PathFinding.AStar.<>c__19`3`.
What does it mean? PathFinding.AStar.<>c__193``
AStar, RoadWeightCalculator, Node, RoadTargetChecker all have [BurstCompile] attribute
Hello ^^
I am still tyring to reloade the scene but I am encounting many problems. I have a subscene that contains a singleton. When I do this
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex, LoadSceneMode.Single);
I get this
InvalidOperationException: GetSingleton<TornadoComponent>() requires that exactly one TornadoComponent exist that match this query, but there are 0.
Can't I use static methods of a static class in burst?
So, I have to add BurstDiscard?
show code
you can
var (currentNode, minIndex) = openList.MinBy(o => o.Priority);
Here, I get the warning
ah, generics
check manual of burst on them
oh
wait
lambda is managed
no burst
yes, my noob
do you load sumscene?
I have tired but the subscene and the scene but both give the same error
then you should start with this error instead
The error only comes when I try to restart the scene. I think it is becuse the subscene contains a gameobject that has the component, and maybe converts it at runtime to an entity ?
I have tired to do this and it resets the scene but throws errors
DefaultWorldInitialization.Initialize("Default World", false); EntityManager.DestroyEntity(EntityManager.UniversalQuery); World.Dispose(); SceneManager.LoadScene("DOTS Tornado", LoadSceneMode.Single); World.GetExistingSystem<ConstructionSystem>().Enabled = true; World.GetExistingSystem<ParticleSystem>().Enabled = true; World.GetExistingSystem<TornadoSystem>().Enabled = true; World.GetExistingSystem<UpdateBarsSystem>().Enabled = true; World.GetExistingSystem<UpdateCameraSystem>().Enabled = true;
the errors
ObjectDisposedException: Cannot access a disposed object. Object name: 'The NativeArray has been disposed, it is not allowed to access it'. ... ObjectDisposedException: Cannot access a disposed object. Object name: 'The NativeArray has been disposed, it is not allowed to access it'. ... System.InvalidOperationException: The specified {0} does not exist in the hierarchy. This Exception was thrown from a job compiled with Burst, which has limited exception support. Turn off burst (Jobs -> Burst -> Enable Compilation) to inspect full exceptions & stacktraces
error is self explanatory. you disposed of world, now it`s equal to null
you can require the singleton for update. that way the system will not throw the error when the singleton is not there
You are talking about the RequireSingletonForUpdate<SystemExampleSingleton>(); right? I have tried that and it eliminates the tornado
Yes but the tornado and buildings are still there and gets reset perfectly
then you need to get reference to that world
instead of using disposed one
how do I do that ? and when I get the new world I shold make the singleton right?
I don`t know what creates your world after you disposed of previous
Does anyone have an idea of how I can reset the simulation another way? I have tried solving this problem for the last couple of weeks and nothing seems to work...
It is slower even slower than algorithm without job :/
Without job, I have used priority queue in finding shortest path but in job, I have used simple list but I do not think it is related to that
did you get your code running bursted yet?