void SnapRegion(Region region) { int regionPointsCount = region.points.Length; int entitiesCount = entities.Count; int m = Mathf.Max(tw, th); float threshold = 2f / m; threshold *= threshold; for (int k = 0; k < regionPointsCount; k++) { Vector2 p = region.points [k]; Vector2 nearPoint = Misc.Vector2zero; float minDist = float.MaxValue; for (int e = 0; e < entitiesCount; e++) { IAdminEntity entity = entities [e]; if (entity.regions == null) { continue; } int entityRegionsCount = entity.regions.Count; for (int r = 0; r < entityRegionsCount; r++) { Region entityRegion = entity.regions [r]; if (entityRegion == region) { continue; } int entityRegionsPointsCount = entityRegion.points.Length; for (int j = 0; j < entityRegionsPointsCount; j++) { Vector2 op = entityRegion.points [j]; // Check if both points are near float d = (p.x - op.x) * (p.x - op.x) + (p.y - op.y) * (p.y - op.y); if (d < threshold && d < minDist) { nearPoint = op; minDist = d; } } } } // Snap point? if (minDist < float.MaxValue) { region.points [k] = nearPoint; } } region.RemoveDuplicatePoints(); }
// Snap positions to country frontiers? void SnapToCountryFrontiers(Region region) { WMSK map = WMSK.instance; int positionsCount = region.points.Length; for (int k = 0; k < positionsCount; k++) { Vector2 p = region.points [k]; float minDist = float.MaxValue; Vector2 nearest = Misc.Vector2zero; bool found = false; for (int c = 0; c < map.countries.Length; c++) { Country country = map.countries [c]; // if country's bounding box does not contain point, skip it if (!country.regionsRect2D.Contains(p)) { continue; } int regionCount = country.regions.Count; for (int cr = 0; cr < regionCount; cr++) { Region countryRegion = country.regions [cr]; // if region's bounding box does not contain point, skip it if (!countryRegion.rect2D.Contains(p)) { continue; } for (int q = 0; q < countryRegion.points.Length; q++) { float dist = FastVector.SqrDistance(ref countryRegion.points [q], ref p); // (countryRegion.points [q] - p).sqrMagnitude; if (dist < minDist) { minDist = dist; nearest = region.points [q]; found = true; } } } } if (found) { region.points [k] = nearest; } } region.RemoveDuplicatePoints(); }