Advertisement
Guest User

Untitled

a guest
Mar 31st, 2021
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 18.67 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Linq;
  7. using Sirenix.OdinInspector;
  8. using UnityEngine;
  9. using Unity;
  10. using Unity.Jobs;
  11. using Unity.Collections;
  12. using Unity.Burst;
  13. using Unity.Mathematics;
  14.  
  15. public class GWCS : MonoBehaviour
  16. {
  17.     [ShowInInspector] private static Dictionary<int, TestMover> AllObjects = new Dictionary<int, TestMover>();
  18.  
  19.     [ShowInInspector] private static Dictionary<int, TestMover> AllDetectors = new Dictionary<int, TestMover>();
  20.  
  21.     [ShowInInspector] private static Queue<TestMover> AdditionQueue = new Queue<TestMover>();
  22.  
  23.     [ShowInInspector] private static Queue<TestMover> RemovalQueue = new Queue<TestMover>();
  24.  
  25.     public static void AddObject(TestMover testMover)
  26.     {
  27.         AdditionQueue.Enqueue(testMover);
  28.     }
  29.  
  30.     public static void RemoveObject(TestMover testMover)
  31.     {
  32.         RemovalQueue.Enqueue(testMover);
  33.     }
  34.  
  35.  
  36.     public NativeMultiHashMap<int2, int> GridCells;
  37.  
  38.     public NativeMultiHashMap<int, int> CurrentCollisions;
  39.  
  40.     //equal to maximum range
  41.     public float QuadrentCellSize = 5;
  42.  
  43.     private void Awake()
  44.     {
  45.         GridCells = new NativeMultiHashMap<int2, int>(10000, Allocator.Persistent);
  46.         CurrentCollisions = new NativeMultiHashMap<int, int>(200000, Allocator.Persistent);
  47.     }
  48.    
  49.     [BurstCompile]
  50.     private struct JOB_ClearGridCells : IJob
  51.     {
  52.         public NativeMultiHashMap<int2, int> gridCells;
  53.  
  54.         public void Execute()
  55.         {
  56.             gridCells.Clear();
  57.         }
  58.     }
  59.    
  60.     [BurstCompile]
  61.     private struct JOB_ClerNewCollisions : IJob
  62.     {
  63.         public NativeMultiHashMap<int, int> newTotalCollisions;
  64.         public void Execute()
  65.         {
  66.            newTotalCollisions.Clear();
  67.         }
  68.     }
  69.  
  70.     [BurstCompile]
  71.     private struct JOB_FillGridCellMap : IJobParallelFor
  72.     {
  73.         private int2 GetPositionHashMapKey(float2 position, float quadrantCellSize)
  74.         {
  75.             int2 _int2 = new int2((int) math.floor(position.x / quadrantCellSize),
  76.                 (int) (math.floor(position.y / quadrantCellSize)));
  77.             return _int2;
  78.         }
  79.  
  80.         [Unity.Collections.ReadOnly] public NativeArray<BittableSimulatedCollider> allSimulatedPositons;
  81.  
  82.         public float quadrentCellSize;
  83.  
  84.  
  85.         public NativeMultiHashMap<int2, int>.ParallelWriter gridCells;
  86.  
  87.         public void Execute(int index)
  88.         {
  89.             gridCells.Add(GetPositionHashMapKey(allSimulatedPositons[index].position, quadrentCellSize), index);
  90.         }
  91.     }
  92.    
  93.    
  94.     [BurstCompile]
  95.     private struct JOB_GetCurrentCollisions : IJobParallelFor
  96.     {
  97.         [Unity.Collections.ReadOnly] public NativeArray<BittableSimulatedCollider> allSimulatedColliders;
  98.         [Unity.Collections.ReadOnly] public NativeMultiHashMap<int2, int> gridCells;
  99.         [NativeDisableParallelForRestriction]
  100.         public NativeBitArray detectorCheckedFlags;
  101.         [NativeDisableParallelForRestriction]
  102.         public NativeMultiHashMap<int, int>.ParallelWriter newTotalCollisionsByIndex;
  103.  
  104.        
  105.  
  106.         public float quadrentCellSize;
  107.        
  108.         private int2 GetPositionHashMapKey(float2 position, float quadrantCellSize)
  109.         {
  110.             int2 _int2 = new int2((int)math.floor(position.x / quadrantCellSize),(int)(math.floor(position.y / quadrantCellSize)));
  111.             return _int2;
  112.         }
  113.        
  114.         private FixedList64<int2> GetCellKeysforsimulatedCollider(BittableSimulatedCollider bittableSimulatedCollider)
  115.         {
  116.             FixedList64<int2> allKeys = new FixedList64<int2>();
  117.             float halfHeight = bittableSimulatedCollider.height / 2;
  118.             float halfwidth = bittableSimulatedCollider.width / 2;
  119.            
  120.             int2 upRight = GetPositionHashMapKey(bittableSimulatedCollider.position + new float2(halfwidth, halfHeight),
  121.                 quadrentCellSize);
  122.             int2 downRight = GetPositionHashMapKey(bittableSimulatedCollider.position + new float2(halfwidth, -halfHeight),
  123.                 quadrentCellSize);
  124.             int2 downleft = GetPositionHashMapKey(bittableSimulatedCollider.position + new float2(-halfwidth, -halfHeight),
  125.                 quadrentCellSize);
  126.             int2 upLeft = GetPositionHashMapKey(bittableSimulatedCollider.position + new float2(-halfwidth, halfHeight),
  127.                 quadrentCellSize);
  128.            
  129.             allKeys.Add(downleft);
  130.             if (downleft.x != downRight.x)
  131.             {
  132.                 allKeys.Add(downRight);
  133.             }
  134.  
  135.             if (downleft.y != upLeft.y)
  136.             {
  137.                 allKeys.Add(upLeft);
  138.             }
  139.  
  140.             if (downRight.y != upLeft.y)
  141.             {
  142.                 allKeys.Add(upRight);
  143.             }
  144.  
  145.             return allKeys;
  146.         }
  147.        
  148.         private bool CheckOverLapBetweenTwoColliders(int colliderIndex, int otherColliderIndex)
  149.         {
  150.             BittableSimulatedCollider collider = allSimulatedColliders[colliderIndex];
  151.             BittableSimulatedCollider otherCollider = allSimulatedColliders[otherColliderIndex];
  152.             return
  153.                 (collider.position.x - collider.width / 2 <= otherCollider.position.x + otherCollider.width / 2 &&
  154.                  collider.position.x + collider.width / 2 >= otherCollider.position.x - otherCollider.width / 2 &&
  155.                  collider.position.y - collider.height / 2 <= otherCollider.position.y + otherCollider.height / 2 &&
  156.                  collider.position.y + collider.height / 2 >= otherCollider.position.y - otherCollider.height / 2);
  157.         }
  158.        
  159.         private bool TestDetection(int TypesICanDetect, int TargetDetectionType)
  160.         {
  161.             /*var a = Convert.ToString(TypesICanDetect, toBase: 8);
  162.             var b = Convert.ToString(TargetDetectionType, toBase: 8);*/
  163.             bool check = (TypesICanDetect & TargetDetectionType) != 0;
  164.             return check;
  165.         }
  166.        
  167.        
  168.        
  169.        
  170.        
  171.         public void Execute(int index)
  172.         {
  173.             FixedList64<int2> getCellKeys = GetCellKeysforsimulatedCollider(allSimulatedColliders[index]);
  174.             var currentCollider = allSimulatedColliders[index];
  175.             if (allSimulatedColliders[index].TypesICanDetect > 0)
  176.             {
  177.                 detectorCheckedFlags.Set(index,true);
  178.             }
  179.            
  180.             for (int i = 0; i < getCellKeys.Length; i++)
  181.             {
  182.                 if (gridCells.TryGetFirstValue(getCellKeys[i], out int otherColliderIndex, out var iterator))
  183.                 {
  184.                     do
  185.                     {
  186.                         if (!detectorCheckedFlags.IsSet(otherColliderIndex))
  187.                         {
  188.                             if (TestDetection(currentCollider.TypesICanDetect,
  189.                                 allSimulatedColliders[otherColliderIndex].DetectableType))
  190.                             {
  191.                                 if (CheckOverLapBetweenTwoColliders(index, otherColliderIndex))
  192.                                 {
  193.                                     newTotalCollisionsByIndex.Add(index,allSimulatedColliders[otherColliderIndex].DetectionID);
  194.                                 }
  195.                             }
  196.                         }
  197.                     } while (gridCells.TryGetNextValue(out otherColliderIndex, ref iterator));
  198.                 }
  199.             }
  200.            
  201.         }
  202.     }
  203.    
  204.    
  205.     private struct JOB_ClearCurrentCollisionsJob : IJob
  206.     {
  207.  
  208.         public NativeMultiHashMap<int, int> currentCollisions;
  209.         public void Execute()
  210.         {
  211.             currentCollisions.Clear();
  212.         }
  213.     }
  214.    
  215.     [BurstCompile]
  216.     private struct JOB_UpdateCurrentCollisions : IJobParallelFor
  217.     {
  218.         [NativeDisableParallelForRestriction]
  219.         public NativeMultiHashMap<int, int>.ParallelWriter currentCollisions;
  220.         [Unity.Collections.ReadOnly]
  221.         public NativeMultiHashMap<int, int> newTotalCollisionsByIndex;
  222.  
  223.         [Unity.Collections.ReadOnly] public NativeArray<BittableSimulatedCollider> allSimulatedColliders;
  224.  
  225.         public void Execute(int index)
  226.         {
  227.             var newCollision = newTotalCollisionsByIndex.GetValuesForKey(index);
  228.             do
  229.             {
  230.                 currentCollisions.Add(allSimulatedColliders[index].DetectionID, newCollision.Current);
  231.             } while (newCollision.MoveNext());
  232.         }
  233.     }
  234.    
  235.     [BurstCompile]
  236.     private struct JOB_resolveNewEnters : IJobParallelFor
  237.     {
  238.         [Unity.Collections.ReadOnly] public NativeMultiHashMap<int, int> newTotalCollisionsByIndex;
  239.         [Unity.Collections.ReadOnly] public NativeMultiHashMap<int, int> currentCollisions;
  240.         [Unity.Collections.ReadOnly] public NativeArray<BittableSimulatedCollider> allSimulatedColliders;
  241.  
  242.         [NativeDisableParallelForRestriction] public NativeMultiHashMap<int, int> onEnterCollisions;
  243.  
  244.  
  245.         public void Execute(int index)
  246.         {
  247.             if (index == 0)
  248.             {
  249.                 return;
  250.             }
  251.             var newCollisions = newTotalCollisionsByIndex.GetValuesForKey(index);
  252.             var oldCollisions = currentCollisions.GetValuesForKey(index);
  253.  
  254.             while (newCollisions.MoveNext())
  255.             {
  256.                 bool newCollisionNotFoundInOld = true;
  257.                 while (oldCollisions.MoveNext())
  258.                 {
  259.                     if (oldCollisions.Current == newCollisions.Current)
  260.                     {
  261.                        
  262.                         newCollisionNotFoundInOld = false;
  263.                         break;
  264.                     }
  265.                 }
  266.                 oldCollisions.Reset();
  267.                 if (newCollisionNotFoundInOld)
  268.                 {
  269.                     //Debug.Log("Totally new collision found :" + newCollisions.Current);
  270.                     onEnterCollisions.Add(allSimulatedColliders[index].DetectionID, newCollisions.Current);
  271.                 }
  272.             }
  273.            
  274.         }
  275.     }
  276.    
  277.     [BurstCompile]
  278.     private struct JOB_resolveNewExits : IJobParallelFor
  279.     {
  280.         [Unity.Collections.ReadOnly] public NativeMultiHashMap<int, int> newTotalCollisionsByIndex;
  281.         [Unity.Collections.ReadOnly] public NativeMultiHashMap<int, int> currentCollisions;
  282.         [Unity.Collections.ReadOnly] public NativeArray<BittableSimulatedCollider> allSimulatedColliders;
  283.  
  284.         [NativeDisableParallelForRestriction] public NativeMultiHashMap<int, int> onExitCollisions;
  285.  
  286.         public void Execute(int index)
  287.         {
  288.             if (index == 0)
  289.             {
  290.                 return;
  291.             }
  292.  
  293.             var newCollisions = newTotalCollisionsByIndex.GetValuesForKey(index);
  294.             var oldCollisions = currentCollisions.GetValuesForKey(index);
  295.  
  296.             while (oldCollisions.MoveNext())
  297.             {
  298.                 if (oldCollisions.Current == 0)
  299.                 {
  300.                     continue;
  301.                 }
  302.                 bool oldCollisionFound = false;
  303.                 while (newCollisions.MoveNext())
  304.                 {
  305.                    
  306.                     if (oldCollisions.Current == newCollisions.Current)
  307.                     {
  308.                         oldCollisionFound = true;
  309.                         break;
  310.                     }
  311.                 }
  312.                 newCollisions.Reset();
  313.                 if (!oldCollisionFound)
  314.                 {
  315.                     /*Debug.Log("Found new Exit : " + oldCollisions.Current);*/
  316.                     onExitCollisions.Add(allSimulatedColliders[index].DetectionID, oldCollisions.Current);
  317.                 }
  318.             }
  319.         }
  320.     }
  321.  
  322.     private void ExecuteCollisionSystem()
  323.     {
  324.         var _JOB_ClearGridCells = new JOB_ClearGridCells
  325.         {
  326.             gridCells = GridCells
  327.         };
  328.         var JH_cleargridCells = _JOB_ClearGridCells.Schedule();
  329.  
  330.        
  331.         //remove objects from queue
  332.         if (RemovalQueue.Count > 0) {
  333.         do
  334.             {
  335.                 var objectToBeremoved = RemovalQueue.Dequeue();
  336.                 AllObjects.Remove(objectToBeremoved.DetectionID);
  337.                 if (objectToBeremoved.TypesICanDetectInt > 0)
  338.                 {
  339.                     AllObjects.Remove(objectToBeremoved.DetectionID);
  340.                     if (objectToBeremoved.TypesICanDetectInt > 0)
  341.                     {
  342.                         AllDetectors.Remove(objectToBeremoved.DetectionID);
  343.                     }
  344.                    
  345.                 }
  346.             } while (RemovalQueue.Count > 0);
  347.         }
  348.        
  349.         //add objects from queue
  350.        
  351.         if (AdditionQueue.Count > 0) {
  352.             do
  353.             {
  354.                 var objecttobeadded = AdditionQueue.Dequeue();
  355.                 AllObjects.Add(objecttobeadded.DetectionID,objecttobeadded);
  356.                 if (objecttobeadded.TypesICanDetectInt > 0)
  357.                 {
  358.                     AllDetectors.Add(objecttobeadded.DetectionID,objecttobeadded);
  359.                 }
  360.  
  361.             } while (AdditionQueue.Count > 0);
  362.         }
  363.        
  364.         NativeArray<BittableSimulatedCollider> AllSimulatedColliders = new NativeArray<BittableSimulatedCollider>(AllObjects.Count + 1, Allocator.TempJob);
  365.         NativeBitArray DetectorCheckdFlags = new NativeBitArray(AllSimulatedColliders.Length + 1,Allocator.TempJob);
  366.         NativeMultiHashMap<int,int> NewTotalCollisionsByIndex = new NativeMultiHashMap<int, int>(200000, Allocator.TempJob);
  367.        
  368.         int objCounter = 1;
  369.         foreach (var _obj in AllObjects.Values)
  370.         {
  371.             var size = _obj.BoxCollider2D.size;
  372.             AllSimulatedColliders[objCounter] = new BittableSimulatedCollider(size.x, size.y,
  373.                 _obj.transform.position,
  374.                 _obj.DetectionID,
  375.                 _obj.DetectableTypeInt,
  376.                 _obj.TypesICanDetectInt);
  377.             objCounter++;
  378.         }
  379.  
  380.         var _JOB_fillMapJob = new JOB_FillGridCellMap
  381.         {
  382.             allSimulatedPositons = AllSimulatedColliders,
  383.             quadrentCellSize = QuadrentCellSize,
  384.             gridCells = GridCells.AsParallelWriter()
  385.         };
  386.  
  387.         var _JOB_GetCurrentCollisions = new JOB_GetCurrentCollisions
  388.         {
  389.             allSimulatedColliders = AllSimulatedColliders,
  390.             detectorCheckedFlags = DetectorCheckdFlags,
  391.             gridCells = GridCells,
  392.             quadrentCellSize = QuadrentCellSize,
  393.             newTotalCollisionsByIndex = NewTotalCollisionsByIndex.AsParallelWriter(),
  394.         };
  395.  
  396.         var _JOB_ClearNewCollisions = new JOB_ClerNewCollisions
  397.         {
  398.             newTotalCollisions = NewTotalCollisionsByIndex
  399.         };
  400.        
  401.         NativeMultiHashMap<int,int> OnEnterCollisions = new NativeMultiHashMap<int, int>(10000, Allocator.TempJob);
  402.         NativeMultiHashMap<int,int> OnExitCollisions = new NativeMultiHashMap<int, int>(10000, Allocator.TempJob);
  403.  
  404.         var _JOB_GetNewEnterCollisions = new JOB_resolveNewEnters
  405.         {
  406.             allSimulatedColliders = AllSimulatedColliders,
  407.             currentCollisions = CurrentCollisions,
  408.             newTotalCollisionsByIndex = NewTotalCollisionsByIndex,
  409.             onEnterCollisions = OnEnterCollisions,
  410.         };
  411.  
  412.         var _JOB_GetNewExitCollisions = new JOB_resolveNewExits
  413.         {
  414.             allSimulatedColliders = AllSimulatedColliders,
  415.             currentCollisions = CurrentCollisions,
  416.             newTotalCollisionsByIndex = NewTotalCollisionsByIndex,
  417.             onExitCollisions = OnExitCollisions
  418.         };
  419.  
  420.         var _JOB_clearCurrentCollisions = new JOB_ClearCurrentCollisionsJob
  421.         {
  422.             currentCollisions = CurrentCollisions
  423.         };
  424.  
  425.         var _JOB_updateCurrentCollisions = new JOB_UpdateCurrentCollisions
  426.         {
  427.             allSimulatedColliders = AllSimulatedColliders,
  428.             currentCollisions = CurrentCollisions.AsParallelWriter(),
  429.             newTotalCollisionsByIndex = NewTotalCollisionsByIndex
  430.         };
  431.        
  432.  
  433.         JobHandle JH_fillGridCellsMap =
  434.             _JOB_fillMapJob.Schedule(AllSimulatedColliders.Length, 128, JH_cleargridCells);
  435.        
  436.         JobHandle JH_GetcurrentCollisions = _JOB_GetCurrentCollisions.Schedule(AllSimulatedColliders.Length, 1, JH_fillGridCellsMap);
  437.  
  438.        
  439.        
  440.        
  441.        
  442.         JobHandle JH_GetNewEnterCollisions =
  443.             _JOB_GetNewEnterCollisions.Schedule(AllSimulatedColliders.Length, 4, JH_GetcurrentCollisions);
  444.         JobHandle JH_GetNewExitCollisions =
  445.             _JOB_GetNewExitCollisions.Schedule(AllSimulatedColliders.Length, 4, JH_GetNewEnterCollisions);
  446.         JobHandle JH_postResolveJobHandle = new JobHandle();
  447.         JobHandle JH_clear_CURRENT_Colissions = _JOB_clearCurrentCollisions.Schedule(JH_GetNewExitCollisions);
  448.         JobHandle JH_UpdateCurrentCollisions =
  449.             _JOB_updateCurrentCollisions.Schedule(AllSimulatedColliders.Length, 128, JH_clear_CURRENT_Colissions);
  450.        
  451.         JobHandle JH_clear_NEW_Collisions = _JOB_ClearNewCollisions.Schedule(JH_UpdateCurrentCollisions);
  452.        
  453.        
  454.         JH_cleargridCells.Complete();
  455.         JH_fillGridCellsMap.Complete();
  456.         JH_GetcurrentCollisions.Complete();
  457.         JH_GetNewEnterCollisions.Complete();
  458.         JH_GetNewExitCollisions.Complete();
  459.         foreach (var detector in AllDetectors)
  460.         {
  461.             var allNewEnters = OnEnterCollisions.GetValuesForKey(detector.Key);
  462.             var allNewExits = OnExitCollisions.GetValuesForKey(detector.Key);
  463.             while (allNewEnters.MoveNext())
  464.             {
  465.                 //detector.Value.OnTargetEnter(allNewEnters.Current);
  466.             }
  467.                
  468.             while (allNewExits.MoveNext())
  469.             {
  470.                 //detector.Value.OnTargetExit(allNewExits.Current);
  471.             }
  472.         }
  473.         JH_postResolveJobHandle.Complete();
  474.        
  475.         JH_clear_NEW_Collisions.Complete();
  476.        
  477.        
  478.        
  479.        
  480.        
  481.         // the part where I dispose of all the things
  482.         AllSimulatedColliders.Dispose();
  483.         DetectorCheckdFlags.Dispose();
  484.         NewTotalCollisionsByIndex.Dispose();
  485.         OnExitCollisions.Dispose();
  486.         OnEnterCollisions.Dispose();
  487.     }
  488.  
  489.     public bool EnableSystem = true;
  490.     public int frameCounter = 0;
  491.     private void Update()
  492.     {
  493.         if (frameCounter > 5) {
  494.         ExecuteCollisionSystem();
  495.         frameCounter = 0;
  496.         }
  497.         frameCounter++;
  498.     }
  499.  
  500.     private void OnDisable()
  501.     {
  502.         CurrentCollisions.Dispose();
  503.         GridCells.Dispose();
  504.     }
  505. }
  506.  
  507. public enum DetectionTypes
  508. {
  509.     Unit = 0,
  510.     Weapon = 1,
  511.     Projectile = 2,
  512.     Path = 3,
  513.     None = 99
  514. }
  515.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement