How the polylabel algorithm works
masterPolylabel uses an iterative grid-based algorithm to find the global optimum within a given precision. It works by:
- Initial Grid Generation: Covers the polygon with large square cells (size equal to the smaller dimension of the polygon). It calculates the distance from each cell center to the polygon boundary (using negative values for points outside via ray-casting).
- Priority Queue: Places cells into a priority queue sorted by their maximum potential distance (center distance + cell radius).
- Initial Best: Uses the polygon's centroid as the first "best so far" candidate.
- Iterative Refinement: Pulls cells from the queue. If a cell's potential distance is greater than the current best (specifically
cell_max - best_dist > precision), the cell is split into 4 children and re-queued. If a cell's distance is better than the current best, it becomes the new "best so far." - Termination: Stops when the queue is exhausted, returning the center of the best cell found.