public void Execute <TCtx>(TCtx ctx) where TCtx : IGraphInstance { var entity = ctx.ReadEntity(GameObject); if (entity != Entity.Null) { if (ctx.EntityManager.HasComponent <NonUniformScale>(entity)) { NonUniformScale t = ctx.EntityManager.GetComponentData <NonUniformScale>(entity); ctx.Write(Value, t.Value); } else if (ctx.EntityManager.HasComponent <Scale>(entity)) { Scale t = ctx.EntityManager.GetComponentData <Scale>(entity); ctx.Write(Value, new float3(t.Value, t.Value, t.Value)); } else if (ctx.EntityManager.HasComponent <CompositeScale>(entity)) { CompositeScale compositeScale = ctx.EntityManager.GetComponentData <CompositeScale>(entity); float4x4 floatMatrix = compositeScale.Value; ctx.Write(Value, new float3(floatMatrix.c0.x, floatMatrix.c1.y, floatMatrix.c2.z)); } else { ctx.Write(Value, new float3(1, 1, 1)); } } }
protected override void OnCreateManager() { entityManager = World.GetOrCreateManager <EntityManager>(); simGroup = World.GetOrCreateManager <SimulationSystemGroup>(); presGroup = World.GetOrCreateManager <PresentationSystemGroup>(); Entity player = entityManager.CreateEntity(typeof(RenderMesh), typeof(LocalToWorld), typeof(Translation), typeof(Rotation), typeof(NonUniformScale)); GameObject meshPrefab = (GameObject)Resources.Load("Meshes/player"); entityManager.SetSharedComponentData(player, new RenderMesh { mesh = meshPrefab.GetComponent <MeshFilter>().sharedMesh, material = meshPrefab.GetComponent <Renderer>().sharedMaterial, }); NonUniformScale scale = new NonUniformScale { Value = meshPrefab.transform.localScale, }; entityManager.SetComponentData(player, scale); Rotation newRotation = new Rotation { Value = meshPrefab.transform.rotation, }; entityManager.SetComponentData(player, newRotation); }
protected override void OnUpdate() { // Local variable captured in ForEach float dT = Time.DeltaTime; this.offset += Time.DeltaTime; float offset = this.offset; float noiseScale = Spawner.Instance.noiseScale; float lower = Spawner.Instance.lower; float upper = Spawner.Instance.upper; Entities .WithName("FlowField_Job") .ForEach( (ref NonUniformScale s, ref Translation p, ref Flow f) => { float scale = Map(Perlin.Noise((p.Value.x + offset) * noiseScale, (p.Value.y + offset) * noiseScale, (p.Value.z + offset) * noiseScale), -1, 1, lower, upper); s = new NonUniformScale() { Value = scale }; /* * p = new Translation() * { * // dT is a captured variable * Value = new float3(0, 0, 0) * }; */ } ) .Schedule(); }
private void GenerateWorld() { if (int.MaxValue < ((long)worldDimensions.x * (long)worldDimensions.y * (long)worldDimensions.z)) { Debug.LogError("Oversized area, reduce dimensions"); return; } var query = entityManager.CreateEntityQuery(typeof(RenderMesh), typeof(LocalToWorld), typeof(Translation)); entityManager.DestroyEntity(query); var entities = new NativeArray <Entity>(worldDimensions.x * worldDimensions.y * worldDimensions.z, Allocator.Temp); entityManager.CreateEntity(entityArchetype, entities); var renderMeshData = new RenderMesh { mesh = mesh, material = meshMaterial }; var scale = new NonUniformScale { Value = blockDimensions }; int i = 0; for (int h = 0; h < worldDimensions.y; h++) { for (int w = 0; w < worldDimensions.x; w++) { for (int l = 0; l < worldDimensions.z; l++) { var entity = entities[i]; entityManager.SetComponentData(entity, scale); var pos = new float3( (float)w * scale.Value.x, (float)h * scale.Value.y, (float)l * scale.Value.z); entityManager.SetComponentData(entity, new Translation { Value = pos }); entityManager.SetSharedComponentData(entity, renderMeshData); i++; } } } lastWorldDimensions = worldDimensions; lastBlockDimensions = blockDimensions; entities.Dispose(); }
public void Execute <TCtx>(TCtx ctx, InputTriggerPort port) where TCtx : IGraphInstance { // MBRIAU: NOTES: // If the scale is only modified in the editor, the info is only stored in the CompositeScale // If the scale is modified by Scale, it's stored in Scale and CompositeScale is updated with that value // If the scale is modified by NonUniformScale, it's stored in NonUniformScale and CompositeScale is updated with that value // WEIRD CASES // if both are set, the CompositeScale is not properly updated with what is rendered! We need to make sure to avoid setting both NonUniformScale and UniformScale // TODO: Would be interesting to try to add a Scale/NonUniformScale and then remove the component to see how the CompositeScale behaves var entity = ctx.ReadEntity(GameObject); if (entity != Entity.Null) { // Important to read right now and get the right value before messing around with the scaling components of that entity Value v = ctx.ReadValue(Value); float3 newScale; if (v.Type == ValueType.Float) { newScale = new float3(v.Float, v.Float, v.Float); } else if (v.Type == ValueType.Int) { newScale = new float3(v.Int, v.Int, v.Int); } else if (v.Type == ValueType.Float3) { newScale = v.Float3; } else { // Simply return without triggering // TODO: Should display a warning or only allow float and float3 to be connected return; } NonUniformScale nus = new NonUniformScale { Value = newScale }; if (ctx.EntityManager.HasComponent <Scale>(entity)) { ctx.EntityManager.RemoveComponent <Scale>(entity); } if (!ctx.EntityManager.HasComponent <NonUniformScale>(entity)) { ctx.EntityManager.AddComponent <NonUniformScale>(entity); } ctx.EntityManager.SetComponentData(entity, nus); } ctx.Trigger(Output); }
void createTrails(PhysicsWorld localWorld, Color color) { //UnityEngine.Material material = new UnityEngine.Material(Shader.Find("Lightweight-Default")); //material.color = color; var em = World.Active.EntityManager; const float minVelocitySq = 0.1f; for (int i = 0; i < localWorld.DynamicBodies.Length; i++) { if (math.lengthsq(localWorld.MotionVelocities[i].LinearVelocity) > minVelocitySq) { var body = localWorld.DynamicBodies[i]; var ghost = em.Instantiate(body.Entity); em.RemoveComponent <PhysicsCollider>(ghost); em.RemoveComponent <PhysicsVelocity>(ghost); em.AddComponentData(ghost, new EntityKiller() { TimeToDie = 2 }); em.SetSharedComponentData(ghost, ghostMaterial); Translation position = em.GetComponentData <Translation>(ghost); position.Value = body.WorldFromBody.pos; em.SetComponentData(ghost, position); Rotation rotation = em.GetComponentData <Rotation>(ghost); rotation.Value = body.WorldFromBody.rot; em.SetComponentData(ghost, rotation); var scale = new NonUniformScale() { Value = 0.5f }; if (em.HasComponent <NonUniformScale>(ghost)) { scale.Value *= em.GetComponentData <NonUniformScale>(ghost).Value; em.SetComponentData(ghost, scale); } else { em.AddComponentData(ghost, scale); } } } }
protected override void OnUpdate() { float deltaTime = Time.DeltaTime; NonUniformScale goldUiScale = EntityManager.GetComponentData <NonUniformScale>(_entityGold); float3 goldUiPosition = EntityManager.GetComponentData <LocalToWorld>(_entityGold).Position; float3 posCam = EntityManager.GetComponentData <Translation>(_entityCam).Value; var commandBuffer = new EntityCommandBuffer(Allocator.TempJob); var score = new NativeQueue <bool>(Allocator.TempJob); JobHandle jobHandle = Entities .WithAll <GoldToScoreComponent>() .WithBurst() .ForEach((Entity entity, DynamicBuffer <Child> children, ref Translation position, ref NonUniformScale scale, ref GoldToScoreComponent goldToScoreComponent) => { goldToScoreComponent.Lerp += deltaTime; float3 t3CameraFixPosition = goldToScoreComponent.GoldFixPosition + posCam - goldToScoreComponent.CameraFixPosition; position.Value = math.lerp(t3CameraFixPosition, goldUiPosition, goldToScoreComponent.Lerp); scale.Value = math.lerp(goldToScoreComponent.StartScale, goldUiScale.Value, goldToScoreComponent.Lerp); if (goldToScoreComponent.Lerp >= 1) { commandBuffer.DestroyEntity(entity); foreach (Child child in children) { commandBuffer.DestroyEntity(child.Value); } score.Enqueue(true); } }).Schedule(Dependency); jobHandle.Complete(); commandBuffer.Playback(EntityManager); commandBuffer.Dispose(); if (score.Count <= 0) { return; } Entities. WithAll <GameDataComponent>(). ForEach((ref GameDataComponent gameData) => { gameData.Score += score.Count; }).Run(); TextLayout.SetEntityTextRendererString(EntityManager, _text, GetSingleton <GameDataComponent>().Score.ToString()); score.Clear(); }
public void Execute(Entity entity, int index, [ReadOnly] ref ColonySeed colonySeed, [ReadOnly] ref MapSize mapSize) { var colonyPosition = new float2(1f, 1f) * mapSize.Value * .5f; var colonyTranslation = new Translation2D(); colonyTranslation.Value = colonyPosition; var colonyScale = new NonUniformScale(); colonyScale.Value = new float3(4f, 4f, .1f) / mapSize.Value; var colony = this.Buffer.Instantiate(colonySeed.ColonyPrefab); this.Buffer.SetComponent(colony, colonyTranslation); this.Buffer.SetComponent(colony, colonyScale); this.Buffer.RemoveComponent <ColonySeed>(entity); }
public void Execute(Entity entity, int index, ref Joiner_C joiner) { //添加质量组件 MassPoint_C mass = new MassPoint_C(); mass.Mass = UnitHelper.Range2Mass(joiner.Range); concurrent.AddComponent(index, entity, mass); //添加缩放组件 NonUniformScale scale = new NonUniformScale(); scale.Value = (float3)(new double3(1, 1, 1) * 2 * joiner.Range); concurrent.AddComponent(index, entity, scale); //添加缩放组件 ColorLevel color = new ColorLevel(); color.Value = 0.5f; concurrent.AddComponent(index, entity, color); }
protected override void OnUpdate() { float deltaTime = Time.DeltaTime; //Get pickupable items and spacial and scaling types so we can render the UI worldspace label NativeArray <Entity> pickupableItems = this.GetEntityQuery(this.EntityManager.GetSpacialTypes() .Concat(new ComponentType[] { this.EntityManager.GetPickupableItemIdentifierFlat() }).ToArray()) .ToEntityArray(Allocator.TempJob); Entity playerEntity = this.playerQuery.GetSingletonEntity(); this.Entities.WithAll <ItemInfoWorldSpaceLabelInjectorTag>().ForEach((UnityEngine.UI.Text pickupItemText) => { //If there are pickupable items around, display text bool displayPickupableItem = pickupableItems.Length > 0; pickupItemText.enabled = displayPickupableItem; if (displayPickupableItem) { //TODO: Render multiple labels, for now just for [0] element Translation pickupableItemTranslation = this.EntityManager.GetComponentData <Translation>(pickupableItems[0]); NonUniformScale pickupableItemNonUniformScale = this.EntityManager.GetComponentData <NonUniformScale>(pickupableItems[0]); Translation playerTranslation = this.EntityManager.GetComponentData <Translation>(playerEntity); pickupItemText.transform.position = pickupableItemTranslation.Value + pickupableItemNonUniformScale.Value; //Implement properly /*float3 target = new float3(playerTranslation.Value.x, 0, playerTranslation.Value.z); * float3 direction = math.normalizesafe(target - new float3(pickupItemText.transform.position)); * * //Rotate label towards player. * pickupItemText.transform.rotation = math.slerp * ( * pickupItemText.transform.rotation, * quaternion.LookRotationSafe(new float3(direction.x, 0, direction.z), UnityEngine.Vector3.up), * GameRelatedConstants.WorldSpaceLabelRotationSpeed * deltaTime * );*/ } }); pickupableItems.Dispose(); }
private void CreateInternal(EntityArchetype bodyArchetype, EntityArchetype rootArchetype, float scaleValue) { bodyEntities = new NativeArray <Entity>(16, Allocator.TempJob); m_Manager.CreateEntity(bodyArchetype, bodyEntities); // replace the first one for loop convenience below m_Manager.DestroyEntity(bodyEntities[0]); bodyEntities[0] = m_Manager.CreateEntity(rootArchetype); for (int i = 0; i < 16; i++) { var rotationIndex = rotationIndices[i]; var translationIndex = translationIndices[i]; var rotation = new Rotation() { Value = rotations[rotationIndex] }; var translation = new Translation() { Value = translations[translationIndex] }; var scale = new NonUniformScale() { Value = new float3(scaleValue) }; m_Manager.SetComponentData(bodyEntities[i], rotation); m_Manager.SetComponentData(bodyEntities[i], translation); m_Manager.SetComponentData(bodyEntities[i], scale); } for (int i = 1; i < 16; i++) { var parentIndex = parentIndices[i]; m_Manager.SetComponentData(bodyEntities[i], new Parent() { Value = bodyEntities[parentIndex] }); } }
protected override void OnUpdate() { ComponentDataFromEntity <HealthBar> healthBarFromEntity = GetComponentDataFromEntity <HealthBar>(true); EndSimulationEntityCommandBufferSystem endSimECBSystem = World.GetOrCreateSystem <EndSimulationEntityCommandBufferSystem>(); EntityCommandBuffer.ParallelWriter parallelWriter = endSimECBSystem.CreateCommandBuffer().AsParallelWriter(); Entities .WithReadOnly(healthBarFromEntity) .WithChangeFilter <Health>() .ForEach((int entityInQueryIndex, in Health health, in HealthBarLink healthBarLink) => { HealthBar healthBar = healthBarFromEntity[healthBarLink.Value]; NonUniformScale scale = new NonUniformScale { Value = new float3((float)health.Current / health.Max, 1.0f, 1.0f) }; parallelWriter.SetComponent(entityInQueryIndex, healthBar.BarEntity, scale); }).ScheduleParallel();
public void Execute(Entity entity, int index, [ReadOnly] ref ResourceSeed seed, [ReadOnly] ref MapSize mapSize) { float resourceAngle = this.Random.NextFloat() * 2f * PI; var offsetX = cos(resourceAngle) * mapSize.Value * .475f; var offsetY = sin(resourceAngle) * mapSize.Value * .475f; var resourcePosition = new float2(1f, 1f) * mapSize.Value * .5f + new float2(offsetX, offsetY); var colonyTranslation = new Translation2D(); colonyTranslation.Value = resourcePosition; var colonyScale = new NonUniformScale(); colonyScale.Value = new float3(4f, 4f, .1f) / mapSize.Value; var colony = this.Buffer.Instantiate(seed.ResourcePrefab); this.Buffer.SetComponent(colony, colonyTranslation); this.Buffer.SetComponent(colony, colonyScale); this.Buffer.RemoveComponent <ResourceSeed>(entity); }
public void TestSetScaleFloat() { GraphBuilder.VariableHandle handle = default; float setValue = 42.42f; SetupTestGraphDefinitionMultipleFrames((b, _) => { handle = b.BindVariableToDataIndex("TestEntity"); var onUpdate = b.AddNode(new OnUpdate()); var enabled = b.AddNode(new ConstantBool { Value = true }); var setScale = b.AddNode(new SetScale { }); var constantRotationValue = b.AddNode(new ConstantFloat() { Value = setValue }); b.BindVariableToInput(handle, setScale.GameObject); b.CreateEdge(enabled.ValuePort, onUpdate.Enabled); b.CreateEdge(onUpdate.Output, setScale.Input); b.CreateEdge(constantRotationValue.ValuePort, setScale.Value); } , (manager, entity, index) => { GraphInstance instance = GetGraphInstance(entity); instance.WriteValueToDataSlot(handle.DataIndex, entity); Assert.That(!manager.HasComponent <NonUniformScale>(entity)); }, (manager, entity, index) => { NonUniformScale scale = manager.GetComponentData <NonUniformScale>(entity); Assert.That(scale.Value.Equals(setValue)); LogAssert.NoUnexpectedReceived(); }); }
public void Execute(Entity entity, int index, [ReadOnly] ref ObstacleSeed obstacleSeed, [ReadOnly] ref MapSize mapSize) { for (int i = 1; i <= obstacleSeed.RingCount; i++) { float ringRadius = (i / (obstacleSeed.RingCount + 1f)) * (mapSize.Value * 0.5f); float circumference = ringRadius * 2f * PI; int maxCount = (int)ceil(circumference / (2f * obstacleSeed.Radius) * 2f); int offset = this.Random.NextInt(0, maxCount); int holeCount = this.Random.NextInt(1, 3); for (int j = 0; j < maxCount; j++) { float t = (float)j / maxCount; if ((t * holeCount) % 1f < obstacleSeed.ObstaclesPerRing) { float angle = (j + offset) / (float)maxCount * (2f * PI); var x = mapSize.Value * .5f + cos(angle) * ringRadius; var y = mapSize.Value * .5f + sin(angle) * ringRadius; Obstacle obstacle = new Obstacle(); obstacle.radius = obstacleSeed.Radius; var translation = new Translation2D(); translation.Value = new float2(x, y); var nonUniformScale = new NonUniformScale(); nonUniformScale.Value = new float3(obstacleSeed.Radius * 2f, obstacleSeed.Radius * 2f, 1f) / mapSize.Value; var obstacleEntity = this.Buffer.Instantiate(obstacleSeed.ObstaclePrefab); this.Buffer.SetComponent(obstacleEntity, obstacle); this.Buffer.SetComponent(obstacleEntity, translation); this.Buffer.SetComponent(obstacleEntity, nonUniformScale); } } } this.Buffer.RemoveComponent <ObstacleSeed>(entity); }
bool panelDisapper(ref PanelInfo panel, ref NonUniformScale scale, ref Sprite2DRenderer sprite) { //Debug.LogAlways("disapp"); var dt = World.TinyEnvironment().frameDeltaTime; panel.Timer += dt; var scl = scale.Value; scl -= new float3(1.9f * dt, 1.9f * dt, 0); scale.Value = scl; var col = sprite.color; col.a -= 1.9f * dt; sprite.color = col; if (panel.Timer >= 0.5f) { return(true); } return(false); }
bool isInside <TScaling>(AABB localBbox, Rotation rot, Translation pos, NonUniformScale scl) where TScaling : IScaling, new() { var pl = this.plane4; var ir = math.inverse(rot.Value).value.ExpandToSoa4(); var t = pos.Value.ExpandToSoa4(); var n = rotate(ir, pl.xyz); var d = pl.w + dot(pl.xyz, t); var c = localBbox.Center.ExpandToSoa4(); var e = localBbox.Extents.SmartScaling <TScaling>(scl).ExpandToSoa4(); var l = new float3_soa4() { x = c.x + e.x * math.sign(n.x), y = c.y + e.y * math.sign(n.y), z = c.z + e.z * math.sign(n.z), }; return(math.all(dot(l, n) + d >= 0.0f)); }
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem) { var amplitude = new AudioAmplitude(); var sampler = new AudioSampleIndex { Value = sampleIndex }; var nonUniformScale = new NonUniformScale { Value = transform.lossyScale }; var init = new AudioVisualizationInit { BasePosition = transform.position, BaseRotation = transform.rotation, BaseScale = transform.lossyScale, LockedScaling = lockedScaling ? 1 : 0 }; dstManager.AddComponentData(entity, amplitude); dstManager.AddComponentData(entity, sampler); dstManager.SetComponentData(entity, nonUniformScale); dstManager.AddComponentData(entity, init); }
public float3 SmartScaling(float3 value, NonUniformScale scl) => value;
static public float3 SmartScaling <TScaling>(this float3 value, NonUniformScale scl) where TScaling : IScaling, new() { return(new TScaling().SmartScaling(value, scl)); }
public bool IsInside(AABB localBbox, Rotation rot, Translation pos, NonUniformScale scl) => isInside <Scaling>(localBbox, rot, pos, scl);
private void InstantiateBuildings(ref Rooms apartment) { int buildings_per_block = tiles_per_block * tiles_per_block - 2 * tiles_per_block + 1; int building_count = buildings_per_block * block_count.x * block_count.y; var buildings = manager.Instantiate(building, building_count, Allocator.Temp); var buildings_occupied = manager.Instantiate( building_occupied, building_count * rooms_per_apartment, Allocator.Temp); float marker_spacing = 3f; int occupied_markers_per_row = (int)((tile_size - 4f) / marker_spacing); int idx = 0; int hash = 0; apartment.max_room_idx = 0; for (int x = 0; x < tile_count.x - tiles_per_block; x++) { for (int y = 0; y < tile_count.y - tiles_per_block; y++) { if (x % tiles_per_block > 0 && y % tiles_per_block > 0) { var b = buildings[idx]; var scale = Random.Range(250, 750); var T = new Translation(); T.Value = new Vector3( x * tile_size + bounds.min.x, scale / 200f, y * tile_size + bounds.min.y); manager.AddComponentData(b, T); var S = new NonUniformScale(); S.Value = new Vector3(2500f, scale, 2500f); manager.AddComponentData(b, S); var cidx = Random.Range(0, building_colors.Length); var color = new URPMaterialPropertyBaseColor() { Value = new float4( building_colors[cidx].r, building_colors[cidx].g, building_colors[cidx].b, building_colors[cidx].a) }; manager.AddComponentData(b, color); var data = new BuildingData() { type = BuildingType.Apartment, start_hash = hash, end_hash = hash + rooms_per_apartment, people_per_room = people_per_room_apartment }; manager.AddComponentData(b, data); for (int h = 0; h < rooms_per_apartment; h++) { var b_o = buildings_occupied[h + hash]; var T_o = new Translation() { Value = T.Value + new float3(tile_size / 2 - 3f, 0f, tile_size / 2 - 3f) - marker_spacing * new float3( h % occupied_markers_per_row, 0f, (int)(h / occupied_markers_per_row)) }; manager.AddComponentData(b_o, T_o); var color_o = new URPMaterialPropertyBaseColor() { Value = new float4(0f, 0f, 0f, 0f) }; manager.AddComponentData(b_o, color_o); var occ_data = new OccupiedData() { base_color = new float4(1f, 1f, 1f, 1f) }; manager.AddComponentData(b_o, occ_data); apartment.space[h + hash] = rooms_per_apartment; apartment.coordinates[h + hash] = new int2(x, y); apartment.max_room_idx++; } hash += rooms_per_apartment; idx++; } } } buildings.Dispose(); buildings_occupied.Dispose(); }
protected override void OnUpdate() { // // chunk vars // var plantType = GetComponentTypeHandle<PlantComponent>(); // var scaleType = GetComponentTypeHandle<NonUniformScale>(); // var entities = GetEntityTypeHandle(); // // // job // var job = new PlantSystemJob(); // job.deltaTime = UnityEngine.Time.deltaTime; // job.maxGrowth = MAX_GROWTH; // job.plantChanges = plantCreationDeletionInfo.AsParallelWriter(); // job.translations = GetComponentDataFromEntity<Translation>(true); // job.PlantComponentTypeHandle = plantType; // job.NonUniformScaleTypeHandle = scaleType; // job.setInfo = componentSetInfo.AsParallelWriter(); // job.EntityType = entities; // // int batchesPerChunk = 4; // this.Dependency = job.ScheduleParallel(m_Group, batchesPerChunk, this.Dependency); float deltaTime = UnityEngine.Time.deltaTime; float maxGrowth = MAX_GROWTH; var translations = GetComponentDataFromEntity <Translation>(true); var setInfo = componentSetInfo.AsParallelWriter(); var plantChanges = plantCreationDeletionInfo.AsParallelWriter(); JobHandle job = Entities.ForEach((Entity currentEntity, ref PlantComponent plant, ref NonUniformScale scale) => { PlantState state = (PlantState)plant.state; switch (state) { case PlantState.None: break; case PlantState.Growing: float currentTotalTime = deltaTime + plant.timeGrown; if (currentTotalTime < maxGrowth) { float currentScale = currentTotalTime / 5.0f; scale = new NonUniformScale { Value = new float3(currentScale, 1.0f, currentScale) }; var data = new PlantComponent { timeGrown = currentTotalTime, state = (int)PlantState.Growing, }; plant = data; } else { var data = new PlantComponent { timeGrown = maxGrowth, state = (int)PlantState.None, }; plant = data; } break; case PlantState.Following: float3 pos = translations[plant.farmerToFollow].Value; float3 trans = new float3(pos.x, pos.y + 2, pos.z); setInfo.Enqueue(new ComponentTransInfo { entity = currentEntity, trans = trans }); break; case PlantState.Deleted: // multiple entities can try to delete the plant // taken care of in the single threaded end of the jobs //UnityEngine.Debug.Log("deleting a plant " + entity.Index); plantChanges.Enqueue(currentEntity); break; default: break; } }).WithReadOnly(translations).ScheduleParallel(this.Dependency); this.Dependency = job; }
public void Execute(ArchetypeChunk ac, int chunkIndex, int firstEntityIndex) { //Do not commit to change if possible bool lineChunkChanged = ac.DidChange(lineSegmentType, lastSystemVersion); bool cameraMovedOrRotated = cameraAca.Length != 0 && cameraAca[0].DidChange(ltwType, lastSystemVersion); if (!lineChunkChanged && !cameraMovedOrRotated) { return; } //These gets will commit a version bump var segs = ac.GetNativeArray(lineSegmentType); var trans = ac.GetNativeArray(translationType); var rots = ac.GetNativeArray(rotationType); var scales = ac.GetNativeArray(scaleType); for (int i = 0; i < segs.Length; i++) { var seg = segs[i]; var tran = trans[i]; var rot = rots[i]; var scale = scales[i]; if (seg.from.Equals(seg.to)) { continue; } float3 forward = seg.to - seg.from; //We will use length too so not using normalize here float lineLength = math.length(forward); float3 forwardUnit = forward / lineLength; //Billboard rotation quaternion rotation = quaternion.identity; if (cameraAca.Length != 0) { var cameraTranslations = cameraAca[0].GetNativeArray(ltwType); //TODO: Better support for multiple cameras. It would be via `alignWithCamera` on the LineStyle? var cameraRigid = math.RigidTransform(cameraTranslations[0].Value); var cameraTranslation = cameraRigid.pos; //TODO : use this somehow? Currently billboard is wrong. // If anyone understand http://www.opengl-tutorial.org/intermediate-tutorials/billboards-particles/billboards/ // please tell me how to do this.. var cameraRotation = cameraRigid.rot; float3 toCamera = math.normalize(cameraTranslation - seg.from); //If forward and toCamera is collinear the cross product is 0 //and it will gives quaternion with tons of NaN //So we rather do nothing if that is the case if ((seg.from.Equals(cameraTranslation) || math.cross(forwardUnit, toCamera).Equals(float3.zero)) == false) { //This is wrong because it only taken account of the camera's position, not also its rotation. rotation = quaternion.LookRotation(forwardUnit, toCamera); //Debug.Log($"ROTATING {rotation} to {cameraTranslation}"); } } trans[i] = new Translation { Value = seg.from }; rots[i] = new Rotation { Value = rotation }; scales[i] = new NonUniformScale { Value = math.float3(seg.lineWidth, 1, lineLength) }; } }
public void Execute(ArchetypeChunk batchInChunk, int batchIndex) { var plantComponents = batchInChunk.GetNativeArray(PlantComponentTypeHandle); var scales = batchInChunk.GetNativeArray(NonUniformScaleTypeHandle); var entities = batchInChunk.GetNativeArray(EntityType); for (var i = 0; i < batchInChunk.Count; i++) { PlantState state = (PlantState)plantComponents[i].state; switch (state) { case PlantState.None: break; case PlantState.Growing: float currentTotalTime = deltaTime + plantComponents[i].timeGrown; if (currentTotalTime < maxGrowth) { float currentScale = currentTotalTime / 5.0f; scales[i] = new NonUniformScale { Value = new float3(currentScale, 1.0f, currentScale) }; var data = new PlantComponent { timeGrown = currentTotalTime, state = (int)PlantState.Growing, }; plantComponents[i] = data; } else { var data = new PlantComponent { timeGrown = maxGrowth, state = (int)PlantState.None, }; plantComponents[i] = data; } break; case PlantState.Following: float3 pos = translations[plantComponents[i].farmerToFollow].Value; float3 trans = new float3(pos.x, pos.y + 2, pos.z); setInfo.Enqueue(new ComponentTransInfo { entity = entities[i], trans = trans }); break; case PlantState.Deleted: // multiple entities can try to delete the plant // taken care of in the single threaded end of the jobs //UnityEngine.Debug.Log("deleting a plant " + entity.Index); plantChanges.Enqueue(entities[i]); break; default: break; } } }
public void Execute(Entity entity, int index, ref Spliter_C spliter, ref Translation translation, ref Joiner_C joiner, ref Mover_C mover) { //校验spliter数据合理性 if (spliter.direction.Equals(double3.zero)) { return; } bool3 nanResult = math.isnan(math.normalize(spliter.direction)); if (nanResult.x || nanResult.y || nanResult.z) { return; } //体积过小就无法分离子星体了 if (joiner.Volume < spliter.volume * 2) { return; } // 根据split的方向分离小实体 Entity subEntity = concurrent.Instantiate(index, smallStar); Joiner_C subJoiner = new Joiner_C() { Volume = spliter.volume + 0.01 }; MassPoint_C subMass = new MassPoint_C() { Mass = UnitHelper.Range2Mass(subJoiner.Range) }; Mover_C subMover = new Mover_C(); Translation subTranslation = new Translation(); NonUniformScale subScale = new NonUniformScale(); var dirNormal = math.normalize(spliter.direction); var distance = subJoiner.Range + joiner.Range + 0.01; subTranslation.Value = translation.Value + (float3)(dirNormal * distance); subScale.Value = 0.01f; concurrent.AddComponent(index, subEntity, subTranslation); concurrent.AddComponent(index, subEntity, subJoiner); concurrent.AddComponent(index, subEntity, subMass); concurrent.AddComponent(index, subEntity, subMover); concurrent.AddComponent(index, subEntity, subScale); //分离产生的力 var spliterForce = math.normalize(spliter.direction) * subMass.Mass; // 添加子物体受力 SimapleForceSender_C subForce = new SimapleForceSender_C() { value = -spliterForce * 2, type = ForceType.external, to = subEntity, time = 0.5f }; Entity fEntity = concurrent.CreateEntity(index); concurrent.AddComponent(index, fEntity, subForce); //添加子物体动量 Momentum_C subMomentum = new Momentum_C() { mass = subMass.Mass, speed = spliterForce * 2, target = subEntity }; Entity mEntity = concurrent.CreateEntity(index); concurrent.AddComponent(index, mEntity, subMomentum); // 添加主物体动量 Momentum_C momentum = new Momentum_C() { mass = subMass.Mass, speed = -spliterForce * 2, target = entity }; Entity mainMEntity = concurrent.CreateEntity(index); concurrent.AddComponent(index, mainMEntity, momentum); // 减少朱物体mass的质量 joiner.Volume -= spliter.volume; concurrent.RemoveComponent(index, entity, typeof(Spliter_C)); //UnityEngine.Debug.Log("spliterV:" + spliter.volume); }
Entity CreateBoidWithTrail(Vector3 pos, Quaternion q, int boidId, float size) { Entity boidEntity = entityManager.CreateEntity(boidArchitype); allTheBoids[boidId] = boidEntity; Translation p = new Translation { Value = pos }; Rotation r = new Rotation { Value = q }; entityManager.SetComponentData(boidEntity, p); entityManager.SetComponentData(boidEntity, r); NonUniformScale s = new NonUniformScale { Value = new Vector3(size * 0.3f, size, size) }; entityManager.SetComponentData(boidEntity, s); entityManager.SetComponentData(boidEntity, new Boid() { boidId = boidId, mass = 1, maxSpeed = 100 * UnityEngine.Random.Range(0.9f, 1.1f), maxForce = 400, weight = 200 }); entityManager.SetComponentData(boidEntity, new Seperation()); entityManager.SetComponentData(boidEntity, new Alignment()); entityManager.SetComponentData(boidEntity, new Cohesion()); entityManager.SetComponentData(boidEntity, new Constrain()); entityManager.SetComponentData(boidEntity, new Flee()); entityManager.SetComponentData(boidEntity, new Wander() { distance = 2 , radius = 1.2f, jitter = 80, target = UnityEngine.Random.insideUnitSphere * 1.2f }); entityManager.SetComponentData(boidEntity, new Spine() { parent = -1, spineId = (spineLength + 1) * boidId }); entityManager.SetComponentData(boidEntity, new ObstacleAvoidance() { forwardFeelerDepth = 50, forceType = ObstacleAvoidance.ForceType.normal }); entityManager.AddSharedComponentData(boidEntity, bodyMesh); for (int i = 0; i < spineLength; i++) { int parentId = (boidId * (spineLength + 1)) + i; Translation sp = new Translation { Value = pos - (q * Vector3.forward) * size * (float)(i + 1) }; Entity spineEntity = entityManager.CreateEntity(spineArchitype); int spineIndex = (boidId * spineLength) + i; allTheSpines[spineIndex] = spineEntity; entityManager.SetComponentData(spineEntity, sp); entityManager.SetComponentData(spineEntity, r); entityManager.SetComponentData(spineEntity, new Spine() { parent = parentId, spineId = parentId + 1, offset = new Vector3(0, 0, -size) }); entityManager.AddSharedComponentData(spineEntity, bodyMesh); s = new NonUniformScale { Value = new Vector3(0.01f, Map(i, 0, spineLength, size, 0.01f * size), size) }; //s.Value = new Vector3(2, 4, 10); entityManager.SetComponentData(spineEntity, s); } // Make the head Entity headEntity = entityManager.CreateEntity(headArchitype); allTheheadsAndTails[boidId * 2] = headEntity; Translation headTranslation = new Translation(); headTranslation.Value = pos + (q * Vector3.forward) * size; entityManager.SetComponentData(headEntity, headTranslation); Rotation headRotation = new Rotation(); headRotation.Value = q; entityManager.SetComponentData(headEntity, headRotation); entityManager.AddSharedComponentData(headEntity, bodyMesh); entityManager.SetComponentData(headEntity, s); s = new NonUniformScale { Value = new Vector3(size * 0.3f, size, size) }; //s.Value = new Vector3(2, 4, 10); entityManager.SetComponentData(headEntity, s); entityManager.SetComponentData(headEntity, new Head() { spineId = boidId * (spineLength + 1), boidId = boidId }); // End head // Make the tail Entity tailEntity = entityManager.CreateEntity(tailArchitype); allTheheadsAndTails[(boidId * 2) + 1] = tailEntity; Translation tailTranslation = new Translation(); tailTranslation.Value = pos - (q * Vector3.forward) * size; //tailTranslation.Value = pos - (q * Vector3.forward) * size * (spineLength + 2); entityManager.SetComponentData(tailEntity, tailTranslation); Rotation tailRotation = new Rotation(); tailRotation.Value = q; s = new NonUniformScale { Value = new Vector3(size * 0.3f, size, size) }; //s.Value = new Vector3(2, 4, 10); entityManager.SetComponentData(tailEntity, s); entityManager.SetComponentData(tailEntity, tailRotation); entityManager.AddSharedComponentData(tailEntity, bodyMesh); entityManager.SetComponentData(tailEntity, s); entityManager.SetComponentData(tailEntity, new Tail() { boidId = boidId, spineId = boidId * (spineLength + 1) }); // End tail return(boidEntity); }
Entity CreateSmallBoid(Vector3 pos, Quaternion q, int boidId, float size) { Entity boidEntity = entityManager.CreateEntity(boidArchitype); allTheBoids[boidId] = boidEntity; Translation p = new Translation(); p.Value = pos; Rotation r = new Rotation(); r.Value = q; entityManager.SetComponentData(boidEntity, p); entityManager.SetComponentData(boidEntity, r); NonUniformScale s = new NonUniformScale(); s.Value = new Vector3(size * 0.5f, size, size); //s.Value = new Vector3(2, 4, 10); entityManager.SetComponentData(boidEntity, s); entityManager.SetComponentData(boidEntity, new Boid() { boidId = boidId, mass = 1, maxSpeed = 100, maxForce = 400, weight = 200 }); entityManager.SetComponentData(boidEntity, new Seperation()); entityManager.SetComponentData(boidEntity, new Alignment()); entityManager.SetComponentData(boidEntity, new Cohesion()); entityManager.SetComponentData(boidEntity, new Constrain()); entityManager.SetComponentData(boidEntity, new Flee()); entityManager.SetComponentData(boidEntity, new Wander() { distance = 2 , radius = 1.2f, jitter = 80, target = UnityEngine.Random.insideUnitSphere * 1.2f }); entityManager.SetComponentData(boidEntity, new Spine() { parent = -1, spineId = boidId }); entityManager.SetComponentData(boidEntity, new ObstacleAvoidance() { forwardFeelerDepth = 50, forceType = ObstacleAvoidance.ForceType.normal }); entityManager.AddSharedComponentData(boidEntity, bodyMesh); // Make the head Entity headEntity = entityManager.CreateEntity(headArchitype); allTheheadsAndTails[boidId * 2] = headEntity; Translation headTranslation = new Translation(); headTranslation.Value = pos + (q * Vector3.forward) * size; entityManager.SetComponentData(headEntity, headTranslation); Rotation headRotation = new Rotation(); headRotation.Value = q; entityManager.SetComponentData(headEntity, headRotation); entityManager.AddSharedComponentData(headEntity, bodyMesh); entityManager.SetComponentData(headEntity, s); entityManager.SetComponentData(headEntity, new Head() { boidId = boidId, spineId = boidId }); // End head // Make the tail Entity tailEntity = entityManager.CreateEntity(tailArchitype); allTheheadsAndTails[(boidId * 2) + 1] = tailEntity; Translation tailTranslation = new Translation(); tailTranslation.Value = pos - (q * Vector3.forward) * size; entityManager.SetComponentData(tailEntity, tailTranslation); Rotation tailRotation = new Rotation(); tailRotation.Value = q; entityManager.SetComponentData(tailEntity, tailRotation); entityManager.AddSharedComponentData(tailEntity, bodyMesh); entityManager.SetComponentData(tailEntity, s); entityManager.SetComponentData(tailEntity, new Tail() { boidId = boidId, spineId = boidId }); // End tail return(boidEntity); }
public void Execute(int index) { Entity entity = entities[index]; Joiner_C joiner = joiners[index]; Translation translation = translations[index]; Mover_C mover = movers[index]; NonUniformScale scale = scales[index]; // 增加的体积 double addVolume = 0; // 增加的质量 double addMass = 0; // 增加的动量 double3 addMomentum = double3.zero; for (int i = 0; i < joiners.Length; i++) { if (i == index) { continue; } var joiner2 = joiners[i]; if (joiner.Volume <= 0 || joiner2.Volume <= 0) { continue; } if (joiner2.Range == joiner.Range && entity.Index > entities[i].Index) { continue; } var translation2 = translations[i]; var dis = math.distance(translation.Value, translation2.Value); if (dis == 0) { continue; } if (joiner.Range + joiner2.Range > dis) { //如果被吸收则减少当前体积,如果吸收则增加对方的体积 bool isOut = joiner2.Range > joiner.Range; double v = isOut ? joiner.Volume : joiner2.Volume; //最少吸收每秒吸收1体积 if (v > 0.2) { v = math.max(0.2, v * deltaTime * 2); } if (!isOut) { var m = UnitHelper.Volume2Mass(v); addMass += m; addMomentum += m * movers[i].direction; } addVolume += isOut ? -v : v; } } joiner.Volume += addVolume; //根据物质量显示物体 if (joiner.Volume < 0.01) { concurrent.DestroyEntity(index, entity); return; } if (addVolume > 0) { //添加动量 Momentum_C momentumIn = new Momentum_C(); momentumIn.mass = addMass * 0.1; momentumIn.speed = addMomentum / (addMass + 1); momentumIn.target = entity; concurrent.AddComponent(index, concurrent.CreateEntity(index), momentumIn); } scale.Value = (float3)(new double3(1, 1, 1) * 2 * joiner.Range); concurrent.SetComponent(index, entity, scale); concurrent.SetComponent(index, entity, joiner); }
protected override void OnUpdate() { int drawmode = GetComponent <drawModeData>(mapGenerator).value; int mapWidth = GetComponent <width>(mapGenerator).value; int mapHeight = GetComponent <height>(mapGenerator).value; int mapSurface = math.mul(mapWidth, mapHeight); DynamicBuffer <noiseMapBuffer> heightMap = GetBuffer <noiseMapBuffer>(mapGenerator); heightMapNativeArray = heightMap.ToNativeArray(Allocator.TempJob).Reinterpret <float>(); colourMapNativeArray = new NativeArray <MaterialColor>(mapSurface, Allocator.TempJob); #region JOB CALCULATION //===================================================================================================== // TEXTURE MAP calculation //===================================================================================================== if (drawmode == 0) { TextureMapJob textureMapJob = new TextureMapJob { mWidth = mapWidth, mHeight = mapHeight, noiseMapJob = heightMapNativeArray, colorsJob = colourMapNativeArray.Reinterpret <Color>(), }; JobHandle jobHandle = textureMapJob.Schedule(); jobHandle.Complete(); } //===================================================================================================== // COLOR MAP calculation //===================================================================================================== else if (drawmode == 1) { DynamicBuffer <TerrainTypeBuffer> regionsBuffer = GetBuffer <TerrainTypeBuffer>(mapGenerator); ColorMapJob colorMapJob = new ColorMapJob { mWidth = mapWidth, mHeight = mapHeight, noiseMapJob = heightMapNativeArray, colorsJob = colourMapNativeArray, regionsBuffer = regionsBuffer, }; JobHandle jobHandle = colorMapJob.Schedule(); jobHandle.Complete(); } //===================================================================================================== // MESH MAP calculation //===================================================================================================== else if (drawmode == 2) { int lvlDetail = GetComponent <levelOfDetailData>(mapGenerator).value; int meshSimplificationIncrement = (lvlDetail == 0) ? 1 : math.mul(lvlDetail, 2); int verticesPerLine = ((mapWidth - 1) / meshSimplificationIncrement) + 1;// 1 2 3 4 5 6 7 ... 241 (241-1)/2 (this imply 241 is a const because not all number are pow of 2) //Size of the meshes now depending on the level of detail stored (enter when generated for now) verticesArray = new NativeArray <float3>(((int)math.pow(verticesPerLine, 2)), Allocator.TempJob); trianglesArray = new NativeArray <int>(math.mul((int)math.pow(verticesPerLine - 1, 2), 6), Allocator.TempJob); uvsArray = new NativeArray <float2>(((int)math.pow(verticesPerLine, 2)), Allocator.TempJob); DynamicBuffer <TerrainTypeBuffer> regionsBuffer = GetBuffer <TerrainTypeBuffer>(mapGenerator); //Temporary Solution for animation Curve curveHeightArray = new NativeArray <float>(mapSurface, Allocator.TempJob); var AnimCurve = _em.GetComponentData <MapHeightCurve>(mapGenerator).value; for (int i = 0; i < mapSurface; i++) { curveHeightArray[i] = AnimCurve.Evaluate(heightMapNativeArray[i]); } ColorMapJob colorMapJob = new ColorMapJob { mWidth = mapWidth, mHeight = mapHeight, noiseMapJob = heightMapNativeArray, colorsJob = colourMapNativeArray, regionsBuffer = regionsBuffer, }; JobHandle colorJobHandle = colorMapJob.Schedule(); MeshDataJob meshDataJob = new MeshDataJob { widthJob = mapWidth, heightJob = mapHeight, noiseMapJob = heightMapNativeArray, verticesJob = verticesArray, trianglesJob = trianglesArray, uvsJob = uvsArray, heightMulJob = GetComponent <mapHeightMultiplierData>(mapGenerator).value, curveJob = curveHeightArray, levelOfDetailJob = lvlDetail, meshSimplificationIncrementJob = meshSimplificationIncrement, verticesPerLineJob = verticesPerLine, }; JobHandle meshjobHandle = meshDataJob.Schedule(); JobHandle.CompleteAll(ref colorJobHandle, ref meshjobHandle); curveHeightArray.Dispose(); } #endregion JOB CALCULATION //===================================================================================================== // TEXTURE2D applied to the plane (TextureJob and ColorJob) //===================================================================================================== Texture2D texture2D = new Texture2D(mapWidth, mapHeight); texture2D.filterMode = FilterMode.Point; texture2D.wrapMode = TextureWrapMode.Clamp; texture2D.SetPixels(colourMapNativeArray.Reinterpret <Color>().ToArray()); texture2D.Apply(); var localToWorldScale = new NonUniformScale { Value = new float3(mapWidth, mapHeight, mapHeight) }; //float4x4 scaleMesh = float4x4.Scale(mapWidth, mapHeight, mapHeight); //CAREFUL y need to be as big as the other vector points! //float4x4 totScale = math.mul(_em.GetComponentData<LocalToWorld>(mapGenerator).Value, scaleMesh); _em.SetComponentData(mapGenerator, localToWorldScale); if (drawmode == 0 || drawmode == 1) { var material = _em.GetSharedComponentData <RenderMesh>(mapGenerator).material; material.mainTexture = texture2D; } else if (drawmode == 2) { Mesh mesh = new Mesh(); mesh.name = "planePROC"; mesh.vertices = verticesArray.Reinterpret <Vector3>().ToArray(); mesh.uv = uvsArray.Reinterpret <Vector2>().ToArray(); mesh.triangles = trianglesArray.ToArray(); mesh.RecalculateNormals(); //other mesh /* * MeshFilter meshFilter = _em.GetComponentData<MeshFilterData>(mapGenerator).value; * MeshRenderer meshRenderer = _em.GetComponentData<MeshRendererData>(mapGenerator).value; * Renderer renderer = _em.GetComponentData<RendererData>(mapGenerator).value; * //renderer.transform.localScale = new float3(texture2D.width, 1, texture2D.height); * meshFilter.sharedMesh = mesh; * meshRenderer.sharedMaterial.mainTexture = texture2D; */ //other mesh var material = _em.GetSharedComponentData <RenderMesh>(mapGenerator).material; material.mainTexture = texture2D; _em.SetSharedComponentData(mapGenerator, new RenderMesh { mesh = mesh, material = _em.GetComponentData <MapMaterialData>(mapGenerator).MeshMat }); //_em.SetSharedComponentData(mapGenerator, new RenderMesh { material = material, mesh = mesh }); verticesArray.Dispose(); trianglesArray.Dispose(); uvsArray.Dispose(); } //===================================================================================================== #region Event Trigger End colourMapNativeArray.Dispose(); heightMapNativeArray.Dispose(); _em.RemoveComponent <Event_MapGen_MapDisplay>(GetSingletonEntity <Event_MapGenTag>()); #endregion Event Trigger End sw.Stop(); UnityEngine.Debug.Log($"Elapsed Texture{drawmode} = {sw.Elapsed}"); }