public void QuadTreeTestOne() { GridVector2[] points = new GridVector2[] { new GridVector2(0,0), new GridVector2(1,1), new GridVector2(-10,-10), new GridVector2(-7.5, 2.5), new GridVector2(8.5, -1.5), new GridVector2(3.5, -6.5), new GridVector2(1.5, -8.5), new GridVector2(10, 10)}; int[] values = new int[] {0,1,2,3,4,5,6,7}; GridRectangle border = GridVector2.Border(points); QuadTree<int> tree = new QuadTree<int>(points, values, border); //Start with a basic test ensuring we can find all the existing points for(int i = 0; i < points.Length; i++) { double distance; int RetValue; RetValue = tree.FindNearest(points[i], out distance); Debug.Assert(RetValue == i); Debug.Assert(distance == 0); } //Check to see if we can find nearby points GridVector2[] nearpoints = new GridVector2[] { new GridVector2(.25,.25), new GridVector2(.5,.51), new GridVector2(-7.5,-7.5), new GridVector2(-7.5, -1.5), new GridVector2(8.5, -5.5), new GridVector2(4.5, -7.75), new GridVector2(1, -8.75), new GridVector2(11, 11)}; //Out of original boundaries for (int i = 0; i < nearpoints.Length; i++) { double distance; int RetValue; RetValue = tree.FindNearest(nearpoints[i], out distance); Debug.Assert(RetValue == i); Debug.Assert(distance == GridVector2.Distance(points[i], nearpoints[i])); } //Check to see if we can return all points in a rectangle GridRectangle gridRect = new GridRectangle(0,15, 0,15); List<GridVector2> intersectPoints; List<int> intersectValues; tree.Intersect(gridRect, out intersectPoints, out intersectValues); Debug.Assert(intersectValues.Contains(0)); Debug.Assert(intersectValues.Contains(1)); Debug.Assert(intersectValues.Contains(7)); Debug.Assert(false == intersectValues.Contains(2)); Debug.Assert(false == intersectValues.Contains(3)); Debug.Assert(false == intersectValues.Contains(4)); Debug.Assert(false == intersectValues.Contains(5)); Debug.Assert(false == intersectValues.Contains(6)); }
public Map() { _Random = Regulus.Utility.Random.Instance; _EntranceSet = new List<Visible>(); this._Set = new Dictionary<Guid, Visible>(); this._QuadTree = new QuadTree<Visible>(new Size(2, 2), 100); }
private void getObjectsColliding(Rectangle bounds, QuadTree<Object.Object>.QuadNode currentNode, List<Object.Object> result, List<SearchFlags.Searchflag> _SearchFlags) { if (Utility.Collision.Intersection.RectangleIsInRectangle(bounds, currentNode.Bounds)) { //Circle fits in node, so search in subnodes Boolean circleFitsInSubnode = false; foreach (QuadTree<Object.Object>.QuadNode node in currentNode.Nodes) { if (node != null) { if (Utility.Collision.Intersection.RectangleIsInRectangle(bounds, node.Bounds)) { circleFitsInSubnode = true; getObjectsInRange(bounds, node, result, _SearchFlags); } } } //Aggrocircle fit into a subnode? then if (!circleFitsInSubnode) { addAllObjectsInRange(currentNode, bounds, result, _SearchFlags); } return; } if (currentNode.Equals(this.quadTreeObject.Root)) { addAllObjectsInRange(currentNode, bounds, result, _SearchFlags); } }
/// <summary> /// Creates a new quad tree broadphase with the specified span. /// </summary> /// <param name="span">the maximum span of the tree (world size)</param> public QuadTreeBroadPhase(AABB span) { _quadTree = new QuadTree<FixtureProxy>(span, 5, 10); _idRegister = new Dictionary<int, Element<FixtureProxy>>(); _moveBuffer = new List<Element<FixtureProxy>>(); _pairBuffer = new List<Pair>(); }
public void Search_AreaWithOnePoint_ReturnsOnePoint() { var center = new Point(0, 0); var boundary = new Boundary(center, 1, 1); var quad = new QuadTree<Point>(boundary); // insert one point in the second quadrant var point = new Point(-0.75, +0.75); quad.Insert(point); // then insert one point in each remaining quadrant var points = new List<Point> { new Point(+0.75, +0.75), // first quadrant new Point(-0.75, -0.75), // third quadrant new Point(+0.75, -0.75) // fourth quadrant }; points.ForEach(p => quad.Insert(p)); // search second quadrant var searchArea = new Boundary(new Point(-0.5, 0.5), 0.5, 0.5); var results = quad.Search(searchArea); Assert.IsTrue(results.Count == 1); Assert.IsTrue(results.Contains(point)); }
protected MobileEntity(Texture2D sprite, Vector2 position, Stats entStats) { this.sprite = sprite; this.position = position; if (sprite != null) { this.boundingBox = sprite.Bounds; //hacky and temporary this.boundingBox.Location = new Point((int)position.X, (int)position.Y); } else { this.boundingBox = new Rectangle(); } this.collisionTree = GamePlayLogicManager.GetInstance().CollisionTree; this.droppedItems = GamePlayLogicManager.GetInstance().DroppedItems; this.entityIsActive = true; this.entStats = entStats; this.entStats = new HeadStat(this.entStats); this.curHealth = entStats.MaxHP; this.entInv = new InventoryHumanoid(this); }
public GameplayScreen(Game1 game, Vector2 worldSize, Levels currentLevel) : base(game) { this.worldSize = worldSize; eCurrentLevel = currentLevel; heatmapWriteTimer = 0; //Make the tree a bit wider for outer walls. quadTree = new QuadTree(new Rectangle( -10, -10, (int)worldSize.X + 20, (int)worldSize.Y + 20)); //Add the 4 walls on the outside of the world. Components.Add(new Wall(GDGame, new Vector2(-10, -10), new Vector2(worldSize.X + 10, 0))); Components.Add(new Wall(GDGame, new Vector2(worldSize.X, -10), new Vector2(worldSize.X + 10, worldSize.Y))); Components.Add(new Wall(GDGame, new Vector2(0, worldSize.Y), new Vector2(worldSize.X + 10, worldSize.Y + 10))); Components.Add(new Wall(GDGame, new Vector2(-10, 0), new Vector2(0, worldSize.Y + 10))); //Add the player to world. Components.Add(Player = new PlayerBall(GDGame, new Vector2(300, 300))); //Give the camera the new world size. GDGame.Camera.WorldSize = worldSize + new Vector2(0, 100); gameOver = won = false; GDGame.IsMouseVisible = false; }
/// <summary> /// Default ctor /// </summary> public CollisionDetector() { // TODO: evaluate these numbers // sample usage says // "Use larger min size, and higher min object values for better performance" m_tree = new QuadTree<Collider>(new DoubleSize(25, 25), 0, false); }
public GameWorld(int width, int height) { Width = width; Height = height; TileMap = new TileMap(Width, Height); _gameObjects = new List<GameObject>(); _quadTree = new QuadTree<GameObject>(new Rectangle(0,0, Width * 64, Height * 64)); _quadTree.MaxGeneration = 4; _addNewObjectsQueue = new Queue<GameObject>(); _deleteObjectsQueue = new Queue<GameObject>(); Camera = new Camera(Game.g_screenSize, new Point(Game.g_screenSize.Width / 2, Game.g_screenSize.Height / 2), true); Camera.ScaleTo(1f); Camera.MoveSpeed = 7; background = new ParallaxBackground(this); BloodSystem = new BloodSystem(this); BloodSystem.Init(); BloodSystem.BlendWith(back); mback = new MagicBackground(); UpdateObjectsEnqueues(); }
public void createSpatialIndex() { this._spatialIndex = new QuadTree<OGRBufferCacheRow>(this._envelope); foreach (OGRBufferCacheRow row in this._rows) { this._spatialIndex.add(row); } }
private Map() { const int numTiles = TerrainConstants.TilesPerMapSide * TerrainConstants.TilesPerMapSide; _tiles = new Dictionary<TileIdentifier, Tile>(numTiles); const float baseLength = TerrainConstants.MapLength / 2.0f; var basePosition = new Point(baseLength, baseLength); QuadTree = new QuadTree<Tile>(basePosition, TerrainConstants.TilesPerMapSide, TerrainConstants.TileSize); }
public GameObjectsManager(Camera camera) { _camera = camera; _gameObjects = new List<GameObject>(150); _addNewObjectsQueue = new Queue<GameObject>(150); _deleteObjectsQueue = new Queue<GameObject>(150); QuadTree = new QuadTree<ColliderComponent>(new Rectangle(0, 0, 1024, 1024)); }
public EntityManager() { float gridSize = 262144.0f / 2; quadTree = new QuadTree(new Vector2(-gridSize / 2, -gridSize / 2), gridSize, null, QuadType.Parent); Random r = Game1.Instance.Random; Time = 1.0f; selectRect = new Rectangle(400, 400, 400, 400); results = new List<GraphicalEntity>(); }
public static TriangulationQuadTree Build(IReadOnlyList<DelaunayTriangle> triangulation) { var quadTree = new QuadTree<DelaunayTriangle, Vec2>( GetBoundingRectangle(triangulation.SelectMany(x => x.Points)), GetRectangle, Convert, Test); return new TriangulationQuadTree(quadTree); }
public void Insert_WithinBoundary_ReturnsTrue() { var center = new Point(0, 0); var boundary = new Boundary(center, 1, 1); var quad = new QuadTree<Point>(boundary); Assert.IsTrue(quad.Insert(new Point(0, 0))); Assert.IsTrue(quad.Insert(new Point(-0.5, 0.5))); }
public void Insert_OutOfBoundary_ReturnsFalse() { var center = new Point(0, 0); var boundary = new Boundary(center, 1, 1); var quad = new QuadTree<Point>(boundary); Assert.IsFalse(quad.Insert(new Point(2, 0))); Assert.IsFalse(quad.Insert(new Point(0, 2))); }
private QuadTree<FixtureProxy>[] _quadTrees; // array indexed by log2(Fixture.Category) #endregion Fields #region Constructors /// <summary> /// Creates a new quad tree broadphase with the specified span. /// </summary> /// <param name="span">world size</param> public QuadTreeBroadPhase(AABB span) { var fatSpan = span.Fattened; _quadTrees = new QuadTree<FixtureProxy>[32]; for (int i=0;i<_quadTrees.Length;i++) _quadTrees[i] = new QuadTree<FixtureProxy>(fatSpan, 5, 10); _idRegister = new Dictionary<int, Element<FixtureProxy>>(); _moveBuffer = new List<Element<FixtureProxy>>(); _pairBuffer = new List<Pair>(); }
public DroppedItem(Texture2D sprite, Vector2 position, Item loot) { this.sprite = sprite; this.position = position; this.loot = loot; this.boundingBox = this.sprite.Bounds; this.boundingBox.Location = new Point((int) this.position.X, (int) this.position.Y); this.collisionTree = GamePlayLogicManager.GetInstance().CollisionTree; }
public DungeonRoom(int id, AABB b, QuadTree q) { boundary = b; quadtree = q; quadtree.room = this; this.id = id; this.color = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f)); this.tiles = new List<DungeonTile>(); }
public void Construct_New_HasNoChildren() { var center = new Point(0, 0); var boundary = new Boundary(center, 1, 1); var quad = new QuadTree<Point>(boundary); Assert.IsNotNull(quad); Assert.IsFalse(quad.HasChildren); }
/* * METHODS */ // Clean QuadTree public void Clear() { seed = -1; boundary = new AABB(); northWest = null; northEast = null; southWest = null; southEast = null; room = null; }
public World(SerializationInfo info, StreamingContext ctxt) : base(info, ctxt) { this.playerObjects = new List<PlayerObject>(); this.regions = new List<Region.Region>(); this.quadTreeObject = new QuadTree<Object.Object>(new Vector3(32, 32, 0), 20); this.objectsToUpdate = new List<Object.Object>(); this.objectsToUpdateCounter = 0; }
public void addAllObjectsInRange(QuadTree<Object.Object>.QuadNode currentNode, Rectangle bounds, List<Object.Object> result, List<SearchFlags.Searchflag> _SearchFlags) { System.Collections.ObjectModel.ReadOnlyCollection<Object.Object> var_Copy = new System.Collections.ObjectModel.ReadOnlyCollection<Object.Object>(currentNode.Objects); //TODO: Zusätzliche Informationen: Die Auflistung wurde geändert. Der Enumerationsvorgang kann möglicherweise nicht ausgeführt werden. try { foreach (Object.Object var_Object in var_Copy) { if (!result.Contains(var_Object))// && !var_Object.IsDead) { Boolean containsAllFlags = true; foreach (SearchFlags.Searchflag searchFlag in _SearchFlags) { if (!searchFlag.hasFlag(var_Object)) containsAllFlags = false; } if (!containsAllFlags) continue; if (var_Object is AnimatedObject) { if (Utility.Collision.Intersection.RectangleIntersectsRectangle(bounds, ((AnimatedObject)var_Object).Bounds)) ///DrawBounds ??? { if (var_Object.CollisionBounds != null && var_Object.CollisionBounds.Count > 0) { foreach (Rectangle collisionBound in var_Object.CollisionBounds) { if (Utility.Collision.Intersection.RectangleIntersectsRectangle(bounds, new Rectangle(collisionBound.X + var_Object.Bounds.X, collisionBound.Y + var_Object.Bounds.Y, collisionBound.Width, collisionBound.Height))) // collisionBound ??? { result.Add(var_Object); break; } } } else { result.Add(var_Object); } } } } } System.Collections.ObjectModel.ReadOnlyCollection<QuadTree<Object.Object>.QuadNode> var_Copy2 = new System.Collections.ObjectModel.ReadOnlyCollection<QuadTree<Object.Object>.QuadNode>(currentNode.Nodes); foreach (QuadTree<Object.Object>.QuadNode node in var_Copy2) { if (node != null) addAllObjectsInRange(node, bounds, result, _SearchFlags); } } catch (Exception e) { Logger.Logger.LogErr(e.ToString()); } }
// On Awake void Awake() { // Create a new QuadTree quadTree = new QuadTree(new AABB(new XY(MAP_WIDTH/2.0f,MAP_HEIGHT/2.0f),new XY(MAP_WIDTH/2.0f, MAP_HEIGHT/2.0f))); // Initialize the tilemap tiles = new Tile[MAP_WIDTH,MAP_HEIGHT]; for (int i = 0; i < MAP_WIDTH; i++) for (int j = 0; j < MAP_HEIGHT; j++) tiles[i,j] = new Tile(Tile.TILE_EMPTY); }
public QuadTreeNode(QuadTree quadTree, QuadTreeNode parent, Vector2 position, float length, float minSize, int depth) { Active = true; Parent = parent; QuadTree = quadTree; Position = position; SideLength = length; MinSize = minSize; Depth = depth; AAR = new AxisAlignedRectangle(Position, SideLength * 2); MeshObject = new LODMeshObject(null, this, AAR, 0); CreateGameobject(); }
/// <summary> /// Описывает указанное дерево, подготавливая индексы вершин для отрисовки /// </summary> /// <remarks> /// Этот метод работает крайне разочаровывающе. Не используйте его, рисуйте все /// вершины /// </remarks> /// <param name="tree">Дерево, описывающее необходимую часть ландшафта</param> /// <param name="mapSize">Размер карты</param> /// <returns> /// Список индексов вершин, в том порядке, в котором необходимо их отрисовать /// </returns> public uint[] RenderTree(QuadTree tree, int mapSize) { if (tree.Boundary.Rad == 1) return new uint[] { }; if (tree.Boundary.Rad == 2) return DescribeIndicies(tree.Boundary.Point.X, tree.Boundary.Point.Z, mapSize); var res = new List<uint>(); foreach (var quadTree in tree.Children) res.AddRange(RenderTree(quadTree, mapSize)); return res.ToArray(); }
public TrackPlanner(int locationTolerance, double angleTolerance, double positionStep, double angleStep, double mapSizeX, double mapSizeY) { locationToleranceSquared_ = locationTolerance * locationTolerance; locationTolerance_ = locationTolerance; angleTolerance_ = angleTolerance; positionStep_ = positionStep; angleStep_ = angleStep; mapSizeX_ = mapSizeX; mapSizeY_ = mapSizeY; seen_ = new QuadTree<BFSNode>(0, 0, (int)mapSizeX, (int)mapSizeY); }
public GraphicalEntity(Vector2 position, string path) : base() { Scale = 1; this.Position = position; this.DrawLayer = 4; this.quadTree = null; this.CurrentState = new GraphicalEntityState(); this.ActiveThinkDelay = 10000 + Game1.Instance.Random.Next(5000); this.InActiveThinkDelay = 10000 + Game1.Instance.Random.Next(5000); this.texturePath = path; this.DrawLayer = Game1.Instance.Random.Next(100, 299); }
void DrawLoop(QuadTree quad) { var bounds = quad.mapSize ; // for(var i = 0 ; i < quadTree.Nodes.Count ; i++) { // bounds = quadTree.Nodes[i].mapSize ; // Gizmos.color = Color.green ; Gizmos.DrawWireCube(new Vector3(bounds.center.x , bounds.center.y) , new Vector3(bounds.size.x , bounds.size.y)); // } for(var i = 0 ; i < quad.Nodes.Count ; i++) { DrawLoop(quad.Nodes[i]); } }
public SimpleGUILayer(DeviceInterface devIf, Point position, Size dimensions) { this.devIf = devIf; device = devIf.Device; this.position = position; this.dimensions = dimensions; enabled = true; visible = true; itemsList = new List<GUILayerItem>(); itemsLayout = new QuadTree<GUILayerItem>(dimensions.Width, dimensions.Height); checkedOutResources = new List<ISharableResource>(); layoutManager = new LayoutManager(); }
void Start() { tree = new QuadTree(maxObjectsInNode, new Rec(-100, -100, 200, 200)); }
protected BaseLayout(SizeF size) { Surface = new RectangleF(new PointF(0, 0), size); QuadTree = new QuadTree <LayoutItem>(Surface); Center = new PointF(Surface.X + size.Width / 2, Surface.Y + size.Height / 2); }
void Awake() { requestManager = GetComponent <PathRequestManager>(); grid = GetComponent <QuadTree>(); }
public CollisionHandler(int worldWidth, int worldHeight) { this.objectsInPlane = new QuadTree(0, new Rectangle(0, 0, worldWidth, worldHeight)); }
public void TestOBJToRAMMeshConverterPerObjectVisual() { var c = new OBJToRAMMeshConverter(new RAMTextureFactory()); var importer = new ObjImporter(); importer.AddMaterialFileStream("Town001.mtl", new FileStream(TestFiles.TownMtl, FileMode.Open)); importer.ImportObjFile(TestFiles.TownObj); var meshes = c.CreateMeshesFromObjects(importer); var texturePool = new TexturePool(); var meshpartPool = new MeshPartPool(); var vertexDeclarationPool = new VertexDeclarationPool(); var renderer = new SimpleMeshRenderer(texturePool, meshpartPool, vertexDeclarationPool); vertexDeclarationPool.SetVertexElements <TangentVertex>(TangentVertex.VertexElements); var spheres = new List <ClientPhysicsTestSphere>(); var engine = new PhysicsEngine(); PhysicsDebugRendererXNA debugRenderer = null; var builder = new MeshPhysicsActorBuilder(new MeshPhysicsPool()); TheWizards.Client.ClientPhysicsQuadTreeNode root; int numNodes = 20; root = new ClientPhysicsQuadTreeNode( new BoundingBox( new Vector3(-numNodes * numNodes / 2f, -100, -numNodes * numNodes / 2f), new Vector3(numNodes * numNodes / 2f, 100, numNodes * numNodes / 2f))); QuadTree.Split(root, 5); var physicsElementFactoryXNA = new MeshPhysicsFactoryXNA(engine, root); var physicsElementFactory = physicsElementFactoryXNA.Factory; var physicsElements = new List <MeshStaticPhysicsElement>(); for (int i = 0; i < 0 * 100 + 1 * meshes.Count; i++) { var mesh = meshes[i]; var el = renderer.AddMesh(mesh); el.WorldMatrix = Matrix.CreateTranslation(Vector3.Right * 0 * 2 + Vector3.UnitZ * 0 * 2); var pEl = physicsElementFactory.CreateStaticElement(mesh, Matrix.Identity); physicsElements.Add(pEl); } var game = new XNAGame(); game.IsFixedTimeStep = false; game.DrawFps = true; game.SpectaterCamera.FarClip = 5000; game.Graphics1.PreparingDeviceSettings += delegate(object sender, PreparingDeviceSettingsEventArgs e) { DisplayMode displayMode = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode; e.GraphicsDeviceInformation.PresentationParameters.BackBufferFormat = displayMode.Format; e.GraphicsDeviceInformation.PresentationParameters.BackBufferWidth = displayMode.Width; e.GraphicsDeviceInformation.PresentationParameters.BackBufferHeight = displayMode.Height; game.SpectaterCamera.AspectRatio = displayMode.Width / (float)displayMode.Height; }; game.Graphics1.ToggleFullScreen(); var sphereMesh = new SphereMesh(0.3f, 20, Color.Green); var visualizer = new QuadTreeVisualizerXNA(); game.AddXNAObject(physicsElementFactoryXNA); game.AddXNAObject(texturePool); game.AddXNAObject(meshpartPool); game.AddXNAObject(vertexDeclarationPool); game.AddXNAObject(renderer); game.InitializeEvent += delegate { engine.Initialize(); debugRenderer = new PhysicsDebugRendererXNA(game, engine.Scene); debugRenderer.Initialize(game); sphereMesh.Initialize(game); }; bool showPhysics = true; game.DrawEvent += delegate { if (game.Keyboard.IsKeyPressed(Keys.P)) { showPhysics = !showPhysics; } if (showPhysics) { debugRenderer.Render(game); } visualizer.RenderNodeGroundBoundig(game, root, delegate(ClientPhysicsQuadTreeNode node, out Color col) { col = Color.Green; return(node.PhysicsObjects.Count == 0); }); visualizer.RenderNodeGroundBoundig(game, root, delegate(ClientPhysicsQuadTreeNode node, out Color col) { col = Color.Orange; return(node.PhysicsObjects.Count > 0); }); for (int i = 0; i < physicsElements.Count; i++) { var el = physicsElements[i]; //game.LineManager3D.AddBox(BoundingBox.CreateFromSphere( el.BoundingSphere), Color.Orange); } for (int i = 0; i < spheres.Count; i++) { sphereMesh.WorldMatrix = Matrix.CreateTranslation(spheres[i].Center); sphereMesh.Render(game); } }; game.UpdateEvent += delegate { engine.Update(game.Elapsed); sphereMesh.Update(game); if (game.Keyboard.IsKeyPressed(Microsoft.Xna.Framework.Input.Keys.F)) { var iSphere = new ClientPhysicsTestSphere(engine.Scene, game.SpectaterCamera.CameraPosition + game.SpectaterCamera.CameraDirection , 0.3f); iSphere.InitDynamic(); iSphere.Actor.LinearVelocity = game.SpectaterCamera.CameraDirection * 10; spheres.Add(iSphere); } for (int i = 0; i < spheres.Count; i++) { spheres[i].Update(root, game); } }; game.Run(); }
public Element(T value, AABB span) { Span = span; Value = value; Parent = null; }
public void AddNode(Element <T> node) { if (!IsPartitioned) { if (Nodes.Count >= MaxBucket && MaxDepth > 0) //bin is full and can still subdivide { // //partition into quadrants and sort existing nodes amonst quads. // Nodes.Add(node); //treat new node just like other nodes for partitioning SubTrees = new QuadTree <T> [4]; SubTrees[0] = new QuadTree <T>(Span.Q1, MaxBucket, MaxDepth - 1); SubTrees[1] = new QuadTree <T>(Span.Q2, MaxBucket, MaxDepth - 1); SubTrees[2] = new QuadTree <T>(Span.Q3, MaxBucket, MaxDepth - 1); SubTrees[3] = new QuadTree <T>(Span.Q4, MaxBucket, MaxDepth - 1); List <Element <T> > remNodes = new List <Element <T> >(); //nodes that are not fully contained by any quadrant foreach (Element <T> n in Nodes) { switch (Partition(Span, n.Span)) { case 1: //quadrant 1 SubTrees[0].AddNode(n); break; case 2: SubTrees[1].AddNode(n); break; case 3: SubTrees[2].AddNode(n); break; case 4: SubTrees[3].AddNode(n); break; default: n.Parent = this; remNodes.Add(n); break; } } Nodes = remNodes; } else { node.Parent = this; Nodes.Add(node); //if bin is not yet full or max depth has been reached, just add the node without subdividing } } else //we already have children nodes { // //add node to specific sub-tree // switch (Partition(Span, node.Span)) { case 1: //quadrant 1 SubTrees[0].AddNode(node); break; case 2: SubTrees[1].AddNode(node); break; case 3: SubTrees[2].AddNode(node); break; case 4: SubTrees[3].AddNode(node); break; default: node.Parent = this; Nodes.Add(node); break; } } }
protected override void additionalUpdate(GameTime gameTime, QuadTree quadTree) { mainWeapon2.update(gameTime, quadTree); }
void Awake() { if (Instance != null) { Destroy(this.gameObject); } Instance = this; //instantiate arrays flock = new Boid[ammount]; unitPositions = new Vector3[ammount]; velocities = new Vector3[ammount]; unitTargetPosition = new Vector3[ammount]; unitDistanceFromPlayer = new float[ammount]; //pinned = new int[ammount]; targetMovementMultiplier = new float[ammount]; camera = Camera.main; spawnRect = new Rectangle(-spawnWidth * 0.5f, -spawnWidth * 0.5f, spawnWidth, spawnWidth); sheepPositionQuadTree = new QuadTree <int>(spawnRect, quadMaxUnits); for (int i = 0; i < ammount; i++) { unitPositions[i] = new Vector3( Random.Range(-spawnWidth, spawnWidth) * 0.5f, 0, Random.Range(-spawnWidth, spawnWidth) * 0.5f ); sheepPositionQuadTree.Insert(unitPositions[i], i); unitDistanceFromPlayer[i] = 10000; flock[i].unit = Instantiate(unitPrefab, unitPositions[i], Quaternion.identity); flock[i].unit.SetIndex(i); targetMovementMultiplier[i] = 0; //pinned[i] = 1; velocities[i] = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f)).normalized *maxSpeed; } computeShader.SetInt("ammount", ammount); computeShader.SetFloat("arenaWidth", spawnWidth); computeShader.SetFloat("wallAwareness", 10); ComputeBuffer pinnedBuffer = new ComputeBuffer(ammount, sizeof(int)); targetBuffer = new ComputeBuffer(ammount, sizeof(float) * 3); positionBuffer = new ComputeBuffer(ammount, sizeof(float) * 3); velocityBuffer = new ComputeBuffer(ammount, sizeof(float) * 3); targetMultiplierBuffer = new ComputeBuffer(ammount, sizeof(float)); DistanceFronPlayerBuffer = new ComputeBuffer(ammount, sizeof(float)); //pinnedBuffer.SetData(pinned); targetBuffer.SetData(unitTargetPosition); positionBuffer.SetData(unitPositions); velocityBuffer.SetData(velocities); targetMultiplierBuffer.SetData(targetMovementMultiplier); computeShader.SetBuffer(0, "pinned", pinnedBuffer); computeShader.SetBuffer(0, "target", targetBuffer); computeShader.SetBuffer(0, "Positions", positionBuffer); computeShader.SetBuffer(0, "Velocities", velocityBuffer); computeShader.SetBuffer(0, "targetMultiplier", targetMultiplierBuffer); computeShader.SetBuffer(0, "distanceFromPlayer", DistanceFronPlayerBuffer); SetComputeValues(); }
public IEnumerable <LayoutItem> GetWordsInArea(RectangleF area) { return(QuadTree.Query(area)); }
public void Shutdown() { //ServiceManager.Singleton.RemoveService(this); _groundArray = null; }
// ************************************************************* // Generate Dungeon Features // ************************************************************* // Generate the quadtree system void GenerateQuadTree(ref QuadTree _quadTree) { _quadTree.GenerateQuadTree(seed); }
/// <summary> /// Create a new Hybrasyl map from an XMLMap object. /// </summary> /// <param name="newMap">An XSD.Map object representing the XML map file.</param> /// <param name="theWorld">A world object where the map will be placed</param> public Map(Maps.Map newMap, World theWorld) { Init(); World = theWorld; // TODO: refactor Map class to not do this, but be a partial which overlays // TODO: XSD.Map Id = newMap.Id; X = newMap.X; Y = newMap.Y; Name = newMap.Name; EntityTree = new QuadTree <VisibleObject>(0, 0, X, Y); Music = newMap.Music; foreach (var warpElement in newMap.Warps) { var warp = new Warp(this); warp.X = warpElement.X; warp.Y = warpElement.Y; if (warpElement.MapTarget != null) { var maptarget = warpElement.MapTarget as Maps.WarpMapTarget; // map warp warp.DestinationMapName = maptarget.Value; warp.WarpType = WarpType.Map; warp.DestinationX = maptarget.X; warp.DestinationY = maptarget.Y; } else { var worldmaptarget = warpElement.WorldMapTarget; // worldmap warp warp.DestinationMapName = worldmaptarget; warp.WarpType = WarpType.WorldMap; } warp.MinimumLevel = warpElement.Restrictions.Level.Min; warp.MaximumLevel = warpElement.Restrictions.Level.Max; warp.MinimumAbility = warpElement.Restrictions.Ab.Min; warp.MaximumAbility = warpElement.Restrictions.Ab.Max; warp.MobUse = warpElement.Restrictions.NoMobUse; Warps[new Tuple <byte, byte>(warp.X, warp.Y)] = warp; } foreach (var npcElement in newMap.Npcs) { var merchant = new Merchant { X = npcElement.X, Y = npcElement.Y, Name = npcElement.Name, Sprite = npcElement.Appearance.Sprite, Direction = (Enums.Direction)npcElement.Appearance.Direction, Portrait = npcElement.Appearance.Portrait, // Wow this is terrible Jobs = ((MerchantJob)(int)npcElement.Jobs) }; InsertNpc(merchant); } foreach (var reactorElement in newMap.Reactors) { // TODO: implement reactor loading support } foreach (var postElement in newMap.Signs.Signposts) { var signpostElement = postElement as Maps.Signpost; var signpost = new Objects.Signpost(signpostElement.X, signpostElement.Y, signpostElement.Message); InsertSignpost(signpost); } foreach (var postElement in newMap.Signs.MessageBoards) { var boardElement = postElement as Maps.MessageBoard; var board = new Objects.Signpost(boardElement.X, boardElement.Y, string.Empty, true, boardElement.Name); InsertSignpost(board); Logger.InfoFormat("{0}: {1} - messageboard loaded", this.Name, board.Name); } Load(); }
// private public QuadTree(int level, Rect bounds, QuadTree parent = null) : this(level, bounds.x, bounds.y, bounds.width, bounds.height, parent) { }
/* * private double GetEnergySum( QuadTree q ) * { * double sum = 0; * for ( int i = 0; i < vertices.Length; i++ ) * sum += GetEnergy( i, q ); * return sum; * } */ private double GetEnergy(int index, QuadTree q) { return(GetRepulsionEnergy(index, q) + GetAttractionEnergy(index) + GetGravitationEnergy(index)); }
void Flock() { QuadTree <int> newQuadTree = new QuadTree <int>(spawnRect, quadMaxUnits); for (int currentBoid = 0; currentBoid < flock.Length; currentBoid++) { Vector3 allignment = Vector3.zero; Vector3 coheshionDirection = new Vector3(); Vector3 seperationDirection = new Vector3(); int count = 0; float maxRange = Mathf.Max(cohesionAwareness, allignAwareness); List <(Vector3 position, int index)> pointList = new List <(Vector3 position, int index)>(); sheepPositionQuadTree.GetPositionsInRange(unitPositions[currentBoid], maxRange, ref pointList); //Parallel.For(0, pointList.Count, (otherBoid) => //{ for (int otherBoid = 0; otherBoid < pointList.Count; otherBoid++) { //if (otherBoid != currentBoid) //{ float dist = Vector3.Distance(unitPositions[currentBoid], unitPositions[pointList[otherBoid].index]); count++; if (dist < allignAwareness) { allignment += flock[pointList[otherBoid].index].velocity; } if (dist < cohesionAwareness) { coheshionDirection += unitPositions[pointList[otherBoid].index]; } if (dist < separationAwareness) { Vector3 direction = unitPositions[currentBoid] - unitPositions[pointList[otherBoid].index]; direction /= dist * dist; seperationDirection += direction; } //} } if (count > 0) { allignment /= count; allignment = allignment.normalized * maxSpeed; allignment -= flock[currentBoid].velocity; allignment = allignment.magnitude > maxSpeed ? allignment.normalized * maxSpeed : allignment; coheshionDirection /= count; coheshionDirection -= unitPositions[currentBoid]; coheshionDirection = coheshionDirection.normalized * maxSpeed; coheshionDirection -= new Vector3(flock[currentBoid].velocity.x, 0, flock[currentBoid].velocity.y); coheshionDirection = coheshionDirection.normalized * maxSpeed; seperationDirection /= count; seperationDirection = seperationDirection.normalized * maxSpeed; seperationDirection -= flock[currentBoid].velocity; seperationDirection = seperationDirection.magnitude > maxSpeed ? seperationDirection.normalized * maxSpeed : seperationDirection; } flock[currentBoid].acceleration += allignment * allignStrengh * Time.deltaTime; flock[currentBoid].acceleration += coheshionDirection * cohesionStrenght * Time.deltaTime; flock[currentBoid].acceleration += seperationDirection * separationStrenght * Time.deltaTime; flock[currentBoid].velocity = flock[currentBoid].velocity + flock[currentBoid].acceleration; float magnitude = flock[currentBoid].velocity.magnitude; flock[currentBoid].velocity = magnitude <= maxSpeed ? flock[currentBoid].velocity : flock[currentBoid].velocity.normalized * maxSpeed; unitPositions[currentBoid] = unitPositions[currentBoid] + flock[currentBoid].velocity * Time.deltaTime; unitPositions[currentBoid].y = 0; flock[currentBoid].unit.transform.position = unitPositions[currentBoid]; flock[currentBoid].acceleration *= 0; flock[currentBoid].unit.transform.eulerAngles = new Vector3(0, Mathf.Atan2(velocities[currentBoid].x, velocities[currentBoid].z) * Mathf.Rad2Deg, 0); newQuadTree.Insert(unitPositions[currentBoid], currentBoid); } sheepPositionQuadTree = newQuadTree; }
//public Dictionary<string, Xml.Spawn> Spawns { get; set; } /// <summary> /// Create a new Hybrasyl map from an XMLMap object. /// </summary> /// <param name="newMap">An XSD.Map object representing the XML map file.</param> /// <param name="theWorld">A world object where the map will be placed</param> public Map(Xml.Map newMap, World theWorld) { Init(); World = theWorld; SpawnDebug = false; // Spawns = new List<Xml.Spawn>(); // TODO: refactor Map class to not do this, but be a partial which overlays // TODO: XSD.Map Id = newMap.Id; X = newMap.X; Y = newMap.Y; Name = newMap.Name; AllowCasting = newMap.AllowCasting; EntityTree = new QuadTree <VisibleObject>(0, 0, X, Y); Music = newMap.Music; foreach (var warpElement in newMap.Warps) { var warp = new Warp(this) { X = warpElement.X, Y = warpElement.Y }; if (warpElement.MapTarget != null) { // map warp warp.DestinationMapName = warpElement.MapTarget.Value; warp.WarpType = WarpType.Map; warp.DestinationX = warpElement.MapTarget.X; warp.DestinationY = warpElement.MapTarget.Y; } else if (warpElement.WorldMapTarget != string.Empty) { // worldmap warp warp.DestinationMapName = warpElement.WorldMapTarget; warp.WarpType = WarpType.WorldMap; } if (warpElement.Restrictions?.Level != null) { warp.MinimumLevel = warpElement.Restrictions.Level.Min; warp.MaximumLevel = warpElement.Restrictions.Level.Max; } if (warpElement.Restrictions?.Ab != null) { warp.MinimumAbility = warpElement.Restrictions.Ab.Min; warp.MaximumAbility = warpElement.Restrictions.Ab.Max; } warp.MobUse = warpElement.Restrictions?.NoMobUse ?? true; Warps[new Tuple <byte, byte>(warp.X, warp.Y)] = warp; } foreach (var npcElement in newMap.Npcs) { var npcTemplate = World.WorldData.Get <Xml.Npc>(npcElement.Name); if (npcTemplate == null) { GameLog.Error("map ${Name}: NPC ${npcElement.Name} is missing, will not be loaded"); continue; } var merchant = new Merchant { X = npcElement.X, Y = npcElement.Y, Name = npcElement.Name, Sprite = npcTemplate.Appearance.Sprite, Direction = npcElement.Direction, Portrait = npcTemplate.Appearance.Portrait, AllowDead = npcTemplate.AllowDead }; if (npcTemplate.Roles != null) { if (npcTemplate.Roles.Post != null) { merchant.Jobs ^= MerchantJob.Post; } if (npcTemplate.Roles.Bank != null) { merchant.Jobs ^= MerchantJob.Bank; } if (npcTemplate.Roles.Repair != null) { merchant.Jobs ^= MerchantJob.Repair; } if (npcTemplate.Roles.Train != null) { if (npcTemplate.Roles.Train.Any(x => x.Type == "Skill")) { merchant.Jobs ^= MerchantJob.Skills; } if (npcTemplate.Roles.Train.Any(x => x.Type == "Spell")) { merchant.Jobs ^= MerchantJob.Spells; } } if (npcTemplate.Roles.Vend != null) { merchant.Jobs ^= MerchantJob.Vend; } merchant.Roles = npcTemplate.Roles; } InsertNpc(merchant); // Keep the actual spawned object around in the index for later use World.WorldData.Set(merchant.Name, merchant); } foreach (var reactorElement in newMap.Reactors) { var reactor = new Reactor(reactorElement.X, reactorElement.Y, this, reactorElement.Script, reactorElement.Description, reactorElement.Blocking); reactor.AllowDead = reactorElement.AllowDead; InsertReactor(reactor); GameLog.Debug($"{reactor.Id} placed in {reactor.Map.Name}, description was {reactor.Description}"); } foreach (var sign in newMap.Signs) { Signpost post; if (sign.Type == Xml.BoardType.Sign) { post = new Signpost(sign.X, sign.Y, sign.Message); } else { post = new Signpost(sign.X, sign.Y, sign.Message, true, sign.BoardKey); } InsertSignpost(post); } Load(); }
private void DrawNode(QuadTree <int> .QuadTreeNode <int> node) { Gizmos.color = Color.Lerp(minColor, maxColor, node.Depth / (float)depth); Gizmos.DrawWireCube(node.Position, new Vector3(1, 1, 0.1f) * node.Size); }
public void TestInit() { this.quadTree = new QuadTree <TestBox>(WorldWidth, WorldHeight); }
public SizeF GetUsedSize() { return(QuadTree.GetSize()); }
public static void TearDown() { QuadTree = null; }
public MovementPlanner(Vector2D center, Vector2D extents) { points_ = new QuadTree(center, extents, 0); points_.InvalidNodeDetectionCollider = new RectangleCollider(center, new Vector2D(3, 3), 0); }
public static void SetUp(TestContext testContext) { QuadTree = new QuadTree <LayoutItem>(new Rectangle(new Point(0, 0), new Size(2000, 2000))); }
/// <summary> /// This procedure contains the user code. Input parameters are provided as regular arguments, /// Output parameters as ref arguments. You don't have to assign output parameters, /// they will have a default value. /// </summary> public void RunScript(List <Point3d> points, int type, ref object A, double tol, bool setup) { RenderSet(0, points, false); switch (type) { case (int)Algorithm.BRUTE: // Compare each pair of points (N^2) foreach (Point3d p1 in points) { foreach (Point3d p2 in points) { if (p1 == p2) { continue; // don't compare to self } RenderComparison(++Iter, p1, p2, Close(p1, p2, tol)); } } break; case (int)Algorithm.SORTED: // Sort by X (N log N) var sorted = points.OrderBy(p => p, Comparer <Point3d> .Create((p1, p2) => { if (setup) { RenderComparison(++Iter, p1, p2, false); } return(p1.X.CompareTo(p2.X)); })).ToList(); // Compare nearby nodes (N) for (int i = 0; i < sorted.Count; i++) { for (int j = i + 1; j < sorted.Count; j++) { Point3d p1 = sorted[i]; Point3d p2 = sorted[j]; RenderComparison(++Iter, p1, p2, Close(p1, p2, tol)); // Stop when the next point cannot be within tolerance double tol_mult = p1.Y == 0 ? 1 : Math.Sqrt(2); // 1D vs 2D if (p2.X - p1.X > tol_mult * tol) { break; } } } break; case (int)Algorithm.HASHMAP: // Put values into a dictionary (N) var dict = new Dictionary <Point3d, bool>(); foreach (Point3d p in points) { RenderSet(++Iter, dict.Keys, dict.ContainsKey(p)); dict[p] = true; } break; case (int)Algorithm.TREE: // Put values into a quadtree (N log N) var tree = new QuadTree(0.5, 0.5, 0.5, (qt, create) => { // Always render new trees, and conditionally render tree iteration. if (create) { RenderArea(0, qt.Center, qt.Radius); } else if (setup) { RenderArea(++Iter, qt.Center, qt.Radius); } }); foreach (Point3d p in points) { tree.Insert(p); } // Look for nearby nodes. foreach (Point3d p in points) { foreach (Point3d near in tree.Query(p, tol)) { RenderComparison(++Iter, near, p, Close(near, p, tol)); } } break; } A = Geo; }
void Awake() { quadTree = new QuadTree <int>(this.transform.position, size, depth); }
private static void ReadQuadTree(BinaryReader br, ExtractedADT adt) { adt.QuadTree = QuadTree <ExtractedADTChunk> .LoadFromFile(br); }
void Start() { quadTree = new QuadTree <Point>(new Rectangle(0, 0, QuadTreeRadius), maxNumberOfNodes); points = new Dictionary <int, SpriteRenderer>(); }
static GameScreen() { qTree = new QuadTree(0, new Rectangle(0, 0, Game1.Monitor.VirtualWidth, Game1.Monitor.VirtualHeight)); }
public Room(AABB b, QuadTree q) { boundary = b; quadtree = q; quadtree.room = this; }
private void Update() { if (Input.GetMouseButton(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); float direction = -ray.origin.y / ray.direction.y; var pos = ray.GetPoint(direction); QuadTree <TreeData> leaf = quadTree.GetLeaf(new Vector2(pos.x, pos.z)); if (leaf != null) { if (leaf.value == null) { count++; countText.text = count.ToString(); TreeData treeData = new TreeData(true); leaf.value = treeData; AddSquare(leaf); AddGrass(leaf); treeDatas.Add(treeData); requestUpdate = true; } } } if (Input.GetMouseButton(1) && !requestUpdate) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); float direction = -ray.origin.y / ray.direction.y; var pos = ray.GetPoint(direction); QuadTree <TreeData> leaf = quadTree.GetLeaf(new Vector2(pos.x, pos.z)); if (leaf != null && leaf.value != null) { int leafIndex = treeDatas.IndexOf(leaf.value); if (leafIndex != -1) { //square vertexs.RemoveAt(leafIndex); normals.RemoveAt(leafIndex); indices.RemoveRange(leafIndex * 6, 6); for (int i = leafIndex * 6; i < indices.Count; i++) { indices[i] -= 4; } squareIndex--; //trees grassVertices.RemoveRange(leafIndex * grassMesh_vertices.Length, grassMesh_vertices.Length); grassNormals.RemoveRange(leafIndex * grassMesh_vertices.Length, grassMesh_vertices.Length); int length = grassMesh_triangles.Length; grassIndices.RemoveRange(leafIndex * length, length); for (int i = leafIndex * length; i < grassIndices.Count; i++) { grassIndices[i] -= grassMesh_vertices.Length; } grassIndex--; leaf.value = null; treeDatas.RemoveAt(leafIndex); requestUpdate = true; } } } if (requestUpdate) { UpdateFlat(); UpdateGrass(); requestUpdate = false; } }