I'm using Cocos2d-x and I'm just looking for efficient way to remove sprites under some rectangular region.
For example if I have a lot of random located sprites on the scene and I want to remove all of them if they belong to rectangular (x1, y1),(x2, y2), then what I need to do?
I see that there are two ways to remove sprite from the scene:
this->removeChildByTag(tag);
or
sprite->removeFromParent();
So from these methods it seems that we need somehow to find which sprites are located inside the area and after that delete them.
But what is the most efficient way to do it?
Thanks!
The only way to do this using default cocos functionality would be to iterate over each child detect overlapping and remove nodes that match criteria. removeFromParent() as well as removeChildByTag() will invoke parent->removeChild(this);. And removeChild() uses std::find in Vector of child nodes. With complexity O(n). So first step of optimization would be to use detachChild that utilizes index of child.
But if that is not fast enough I would recommend using special data structure to quickly search for overlapping like interval tree.
Related
Using moveto and lineto to draw various lines on a window canvas...
What is the simplest way to determine at run-time if an object, like a bit map or a picture control is in "contact" (same x,y coordinates) with a line(s) that had been drawn with lineto on a window canvas?
A simple example would be a ball (bitmap or picture) "contacting" a drawn border and rebounding... What is the easiest way to know if "contact" occurs between the object, picture or bitmap and any line that exists on the window?
If I get it right you want collision detection/avoidance between circular object and line(s) while moving. There are more option to do this I know of...
Vector approach
you need to remember all the rendered stuff in vector form too so you need list of all rendered lines, objects etc ... Then for particular object loop through all the other ones and check for collision algebraically with vector math. Like detecting intersection between bounding boxes and then with particular line/polyline/polygon or what ever.
Raster approach
This is simpler to mplement and sometimes even faster but less acurate (only pixel precision). The idea is to clear object last position with background color. Then check all the pixels that would be rendered at new position and if no other than background color present then no colision occurs so you can render the pixels. If any non background color present then render the object on the original position again as collision occur.
You can also check between old and new position and place the object on first non collision position so you are closer to the edge...
This approach need fast pixel access otherwise it woul dbe too slow. Standard Canvas does not allow this without using BitBlt from GDI. Luckily VCL GRaphics::TBitmap has ScanLine[] property allowing direct pixel access without any performance hit if used right. See example of it in your other question I answered:
bitmap rotate using direct pixel access
accessing ScanLine[y][x] is as slow as Pixels[x][y] but you can store all the pointers to each line of bitmap once and then just use that instead which is the same as accessing your own 2D array. So you really need just bitmap->Height calls of ScanLine[y] for entire image rendering after any resize or assigment of bitmap...
If you got tile based scene you can use this approach on tiles instead of pixels something like this:
What is the best way to move an object on the screen? but it is in asm ...
Field approach
This one is also considered to be a vector approach but does not require collision checks. Instead each object creates repulsive force the bigger the closer you are to it which is added to the Newton/D'Alembert physics driving force. When coefficients set properly it will avoid collisions on its own. This is used also for automatic placement of items etc... for more info see:
How to implement a constraint solver for 2-D geometry?
Hybrid approach
You can combine any of the above approaches together to better suite your needs. For example see:
Path generation for non-intersecting disc movement on a plane
I'm looking for some simple and somehow efficient way to detect collisions of Nodes (not necessarily Sprites) while ignoring collisions of transparent parts of Nodes' images.
It is easy to implement bounding Rects collision... but it does not reflect the transparency.
There were published other approach named "Pixel-perfect"... ok, but I see it as inefficient and somehow complicated. In cases of full-hd and bigger displays...
I suppose it could be possible to yield some "non-transparent" masks of both sprites, get them only in intersect of their bounding rects and finally perform AND operation on those masks...
Please, did anybody see something similar? Or better? Can I yield transparent and non-transparent parts of image of node?
I also found this and this well. Not studied yet but now I'd like use cocos2d-js .... :)
Thanks a lot
Give quadtrees a try. The algorithm works by splitting nodes into 4 quadrants recursively into a list with likely collideables. There are plenty of resources about them.
I combined this with pixel perfect check. I'm afraid it's the only way to properly check images' collisions short of using the per pixel algorithm to create unique concave and convex shapes to represent the collision space and then using other algorithms (such as Minkowski portal refinement). However if you images change or are animated, your game can takr an equal performance hit.
Interestingly enough, pp intersection was used in games like pong, with much less processing power. Pp also gives the most accurate intersection as compared to other algorithns.
You can use physics collisions. And set-up physics body to repeat not-transparent part of the node.
I have an image, and I want to show tooltips when mouse moves over certain rectangular areas. The rectangular areas can be up to 1000. However, just checking each rectangle if the point is in it, which is O(N), makes the interface unresponsive when moving the mouse.
Is there a way to do it in less than O(N)? I can sort the rectangles beforehand (I'm assuming it would be needed). The rectangles might be (very rarely) overlapping, but no more than 4-5 rectangles can overlap the same area. In that case I might need to get a list of all the rectangles, but even just any of them would still be good enough.
But I'm assuming that this problem has already been solved by window managers, etc.
It sounds like you want to be storing your rectangles within an R-Tree and then querying that. There are a few implementations available:
JTS Topology Suite (Java)
Net Topology Suite (.Net)
GeoTools (.Net)
Check out their STRtree classes.
A faster and simpler (though less memory efficient) method than a tree for images (and web pages that can be rendered onto reasonably small images) is to use a stencil. i.e. if you have an image of x by y pixels, create a two dimensional array of size x by y and populate it with your tool tip IDs. This has a search speed from pixel position to ID of O(1) (my favourite O)
If the rectangle are axis-aligned, you can avoid specialised data structures.
First subdivide the space in one dimension, e.g. subdividing the screen horizontally into vertical strips. Each rectangle may be in multiple strips. Then you subdivide each strip depending on the rectangles that overlap that strip. The search then involves two O(log n) binary searches or binary trees - one to identify the strip, one to identify which rectangle.
This is a recognised spatial data structure, but to me it doesn't really count - it's just using normal binary trees. You could even do it with an std::map<int, std::map<int, int>>.
But there's actually an option supporting O(1) searches, which is called "pixel picking". Basically, draw the rectangles in an off-screen bitmap, each rectangle in a different colour, and frontmost rectangles last as you would for normal drawing (painters algorithm). You can identify which rectangle is frontmost at any point by simply reading that pixel.
Extra bonus - your graphics card may even accelerate drawing the rectangles, so you don't need to worry too much about redrawing when the set of rectangles changes (which obviously isn't included in that O(1)). It's a bit expensive in memory but, on a modern machine, you may not care about that.
Use a spatial search data structure such as the quad-tree.
You will need to add your rectangles to the tree beforehand, but the average search will be fast. In the worst case you may still have O(N) though.
I'm currently making a game in the DirectX engine in c++. I'm using path-finding to guide an army of soldiers to a specific location. the problem is that I use raycasts to see if there is nothing in the way of my path, and this slows down the speed of the game. Is there a better way to do pathfinding?
I also have a problem with the moving of my army. Right now i'm using the average of soldiers' positions as the start point, which means all the soldiers need to go there first before moving to the end point. Is there a way to make them go to the end point without going to the startpoint?
Thanks for the help.
Have you tried something like A-Star? to navigate via nodes, or some sort of 2d-array representation of your map? written good it could possible be faster aswell as easier to do with jobs ( multithreaded ).
if you have a solider, who is at postion A, and needs to get to B.
just calulate the path from C(the avrage position what ever) to B. get the direction from a to b and do some sort of interpolation. ( havent done this, or tried it, but it could probablt work out pretty well!)
Are you hit-testing every object when you are raycasting?
That can be very expensive when you have many objects and soldiers.
A common solution is to divide your world into square grid cells, and put each object in a list of objects for that grid.
Then you draw an imaginary line from the soldier to the destination and check each cell what objects you need to hit test against. This way you will evaluate only objects close to the straight path and ignore all others.
I'm the founder of SceneMax - a 3D scripting language since 2005. I want to add a scene rendering using one mesh object built with 3d package like 3ds max and split by octree algorithm for optimized performance.
Do you know where can I find an algorithm which takes a mesh .X file, splits it to nodes (octree) and knows how to render it? I want to add it to my engine. The engine is open source (google for SceneMax if you're interested).
There are several variations, but when building an octree, one approach is this:
Start with one node (ie. a cube) encompassing your entire scene or object being partitioned.
For each element in your scene/object (eg. a mesh, or a poly, or whatever granularity you're working to):
Check if that element fits completely inside the node.
If yes, subdivide the node into eight children, then recursively do Step 2 for each child.
If no, then continue to the next node until there are no nodes left.
Add the element to the smallest node that can contain it.
It's also common to stop recursion based on some heuristic, like if the size of the nodes or the number of elements within the node is smaller than a certain threshold.
See this Flipcode tutorial for some more details about building the octree.
Once you have the octree, there are several approaches you can take to render it. The basic idea is that if you can't "see" a node, then you can't see its children either, so everything inside that node (and its children) don't need to be rendered.
Frustum culling is easy to implement, and does the "can you see it?" test using your view projection's frustum. Gamedev.net has an article discussing frustum culling and some other approaches.
You can also go further and implement occlusion culling after frustum culling, which will let you skip rendering any nodes which are covered up by nodes in front of them, using the z-buffer to determine if a node is hidden. This involves being able to traverse your octree nodes from closest to furthest. This technique is discussed in this Gamasutra article.
It's important to first consider the types of mesh files that you will be having to support.
There are effectively 3 different kinds of objects.
1. Open natural terrain. This fits with a quadtree very well as an octree brings complexity that is unnecessary. There's little reason to introduce a 3rd dimension if it won't give you much performance gain.
2. Open terrain with many tall objects. This fits into an octree very well as an octree allows you to remove things on the vertical axis from rendering and a scene such as this has a lot of those. I honestly can't name any that fit into this off the top of my head.
3. Enclosed spaces or character models/static meshes. This fits very well into BSP trees. A BSP tree allows for objects that are fully onscreen, or enclosed spaces to only render as many polygons as needed.
I would recommend adding 1 and 3, assuming 1 is even a model type you need to support. #3 is very standard for first person shooters or character models and adding support for that may give you the best bang for your buck. The overall idea is to remove as much geometry from a render as possible, thus a quad tree for 95% of the outdoor terrain players game worlds have is perfect. An octree has uses, but less than you may think.
Each of these algroithms are relatively easy to write. For example I wrote an octree in 3 hours many years ago. Generally these are processed at load time, pieces of geometry being added to each square (if quad/octree) or to the tree (if BSP) and then rendering follows suit. There are a lot of great articles out there via a quick Google search that I will leave for your research. A quick note is that BSP tree's also have the ability to handle collision detection and are ideal candidates for character models and static meshes. Thus this is an algorithm that I would recommend taking your time on in order to ensure it is flexible enough for multiple uses.