Поиск ближайшего полигона15.06.2025, 14:40. Показов 1864. Ответов 22
Метки нет (Все метки)
Добрый день
С задачами (быстрого) поиска сталкивался не раз, но здесь что-то ничего не приходит в голову
![]() Спасибо
0
|
||
| 15.06.2025, 14:40 | |
|
Ответы с готовыми решениями:
22
Расчет изменения угловой скорости\линейной скорости центра масс полигона |
|
5514 / 2867 / 571
Регистрация: 07.11.2019
Сообщений: 4,752
|
||
| 16.06.2025, 12:07 | ||
|
0
|
||
| 16.06.2025, 15:14 [ТС] | ||
|
0
|
||
| 18.06.2025, 13:21 [ТС] | ||
|
Проблема в том что обычные "разбиения пространства" не работают. Напр популярное "пересечение луча с полигоном". Если луч не пересекает куб (в котором N полигонов) - ну все, стало быть пересечений нет, отбрасываем N полигонов. А здесь это не годится, мы можем и не пересекать куб (или находиться вне его), но "ближайшим" будет полигон внутри этого куба.
Отсюда следует что если слегка изменить постановку и "ограничить близость", то задача успешно сводится к известным образцам.
Выглядит разумно, но надо согласовывать с заказчиком и рассчитывать на его понимание. Не смертельно, но хотелось бы без этого. Как все-таки решить для постановки стартового поста? Предлагаю не питать иллюзий насчет "алгоритмического мЫшления", что, мол, мы можем (сами) придумать алгоритм Или мы знаем алгоритм (и решаем) или не знаем (и ничего не решаем) как в данном случае. Поэтому нужно сосредоточить усилия на том "как это узнать", по-простому говоря "нагуглить".Напрашивается воспользоваться модным ИИ, но как это сделать? Он ведь бросится объяснять как считать расстояния до полигона, а нужно сосредоточиться на отсечках/быстроте поиска. Как сформулировать запрос?
0
|
||
|
2622 / 1633 / 266
Регистрация: 19.02.2010
Сообщений: 4,334
|
|||||
| 18.06.2025, 17:54 | |||||
![]()
0
|
|||||
| 18.06.2025, 21:21 [ТС] | |
|
0
|
|
|
91 / 58 / 14
Регистрация: 16.11.2018
Сообщений: 269
|
|
| 19.06.2025, 00:15 | |
|
0
|
|
| 19.06.2025, 10:59 [ТС] | |||
Кликните здесь для просмотра всего текста
>>> how to calculate the “Signed Distance Function" for a polygonal object
<think> Okay, so I need to figure out how to calculate the Signed Distance Function (SDF) for a polygonal object. Hmm, where do I start? I remember SDF is related to distance fields, which are used in graphics and computational geometry. Let me try to recall. From what I know, an SDF is typically defined as the distance from a point to the closest feature of an object. For convex shapes like spheres or boxes, it's straightforward because you can compute the closest point efficiently using projection along normals. But polygonal objects are trickier because they have flat faces and edges, which means more complex interactions. I think the SDF for a polygon is built by considering each face, edge, and vertex of the polygon and determining how close a point can get to each of these features. For convex polygons, you might be able to compute this by looking at each face separately because each face contributes a certain part of the distance function. Wait, but polygons can have concavities too. So maybe I need to handle each face individually and then merge their contributions? Or perhaps there's another approach where I use the polygon's geometry to construct an implicit surface? Let me think about how implicit functions work. An SDF is a type of implicit function that outputs a signed distance, which can be positive (outside), negative (inside), or zero (on the surface). For a polygonal object, I suppose it would be constructed by combining the distances from each face, edges, and vertices. So, perhaps for each face, edge, and vertex, I compute their individual contributions to the SDF. But how exactly? I recall that for convex polyhedra, like boxes, you can compute the SDF by considering each face's distance contribution using projection along the face's normal. For non-convex shapes, it gets more complicated because points inside a face might not contribute in the same way. Wait, maybe I should break down the problem into steps: 1. **Triangulate the Polygon**: Since the object is polygonal, it can be triangulated into triangles. Each triangle can be treated as a convex shape, making it easier to compute SDF contributions from each face. 2. **Compute Distance Contributions for Faces**: For each triangular face, compute how close a point is to that face. The distance contribution would be based on the projection along the face's normal. But since faces are triangles, this might not account for edges or vertices properly. 3. **Consider Edges and Vertices**: Each edge and vertex can also contribute to the SDF by creating local features. For example, near an edge, the distance function could have a sharp change or a notch, which would require their own contributions. 4. **Combine All Contributions**: Merge all these individual contributions into a single SDF that considers the proximity to faces, edges, and vertices together. But I'm not sure if this approach is correct. Maybe there's a more efficient way. I remember something about using polygonal Marching Cubes or similar methods for implicit surfaces. However, those might be more suitable for voxel grids rather than point queries. Alternatively, perhaps the SDF can be constructed by considering each face, edge, and vertex as separate geometric entities and their influence on the distance field. Wait, here's another thought: The SDF of a polygon can be seen as an extension of the SDF for a convex polyhedron. Since each face is flat, maybe I can compute the distance to the closest point on that face and then aggregate all these distances. But how do you combine multiple distances from different faces? Because the closest feature might not always be the closest face; it could also be an edge or vertex near another face. Hmm, perhaps for each face, edge, and vertex, I need to compute a distance function and then take the minimum of all those contributions. But that sounds computationally intensive, especially for complex polygons with many faces. Wait, maybe I can use a hybrid approach where I first project onto each face, calculate their distances, and then handle edges and vertices as additional constraints. Or perhaps using some kind of sweep line algorithm to build up the SDF by handling each feature in order of proximity. I'm getting a bit stuck here. Let me try to outline the steps more clearly: 1. **Triangulate the Polygon**: If the polygon isn't already triangulated, I'll need to do that first. This will allow me to handle each face as a triangle. 2. **Compute Face Contributions**: For each triangular face, compute the distance from a query point to this face using projection along the face's normal. This gives a signed distance for each face. 3. **Compute Edge Contributions**: Edges can be thought of as lines where two faces meet. The closest point on an edge could be the projection onto the edge's direction or some combination of the adjacent faces' distances. 4. **Compute Vertex Contributions**: Vertices are points, so their contribution would be zero for distance but might affect the SDF by creating sharp features. 5. **Merge All Contributions**: Combine all these individual contributions to create a final SDF that accurately represents the proximity to the entire polygonal object. But I'm not sure how exactly to compute edge and vertex contributions without overcounting or missing some regions. Maybe there's a smarter way using computational geometry libraries or existing algorithms. Wait, perhaps using the convex hull of the polygon could simplify things? If the polygon is non-convex but has a known convex hull, maybe I can handle each face within the convex hull and then adjust for any concave parts. Alternatively, maybe the SDF for a polygonal object can be built by considering each face separately and integrating their contributions, similar to how you build level sets for implicit surfaces. But this might not capture the edges and vertices correctly. I think I need to look into existing algorithms or methods that compute SDFs for polygons. From what I remember, Marching Cubes is a standard method but is typically used for grid-based computations, not point queries. So perhaps it's not applicable here. Another approach could be using polygonal distance fields built on triangle meshes. I believe there are techniques where you can construct an SDF by considering each face and then combining their contributions while ensuring consistency across the entire mesh. Wait, here's a different angle: The SDF can be computed as the minimum of the distances to all faces, edges, and vertices. So for any point in space, the closest feature (face, edge, or vertex) determines the signed distance. To compute this efficiently, one could: - Precompute normals for each face. - For a given query point, project onto each face and calculate the signed distance. - Similarly, check proximity to edges and vertices by projecting along edge directions or directly calculating their distances. But again, with many faces, edges, and vertices, this becomes computationally expensive unless optimized properly. Wait, perhaps using a spatial hierarchy or some form of culling can help reduce the number of computations. For example, organizing the polygonal object into levels based on proximity, starting from the farthest features to the closest ones. Alternatively, for each face, edge, and vertex, precompute their influence regions and combine them using some merging technique. But I'm still not sure about the exact steps or how to implement this without detailed knowledge of specific algorithms. Maybe I need to refer back to basics. In 3D graphics, computing distance functions often involves implicit surfaces like the SDF. For convex shapes, it's manageable because each face contributes a simple portion. But for concave and polygonal objects, you have to account for each face, edge, and vertex. I think the approach is: 1. **Define Each Feature**: Identify all faces, edges, and vertices of the polygon. 2. **Compute Distance for Each Feature**: For each feature (face, edge, vertex), compute how close a given point is to that feature. 3. **Combine Distances**: Determine which feature is closest for a given query point and assign the corresponding signed distance. But practically, this requires an efficient way to evaluate all features without excessive computation. Perhaps using spatial partitioning or quadtrees to group nearby features together and compute their contributions more efficiently. Wait, maybe a better approach is inspired by the SDF for a convex polyhedron. For each face of the polygon (considering it as part of a convex hull), compute its distance contribution and then merge these contributions while handling concave parts separately. But I'm not entirely certain about this. Maybe I should look at how SDFs are computed for triangle meshes in computational geometry literature. Upon some reflection, I recall that for implicit surfaces defined by polygonal data, one can use a method similar to the Marching Cubes but adapted for point queries. Alternatively, the SDF can be built as an aggregate of all face contributions, treating each face's distance function and then combining them while maintaining consistency across the entire object. Another thought is that if the polygon is convex, computing its SDF is more straightforward because you can handle each face independently without worrying about edge cases where multiple faces might influence the same region. But for non-convex polygons, this approach alone isn't sufficient, so additional steps are needed to account for concave regions and edges. I think the key takeaway is that calculating an SDF for a polygonal object involves considering each face, edge, and vertex's contribution and combining them in a way that accurately reflects their proximity. It requires both geometric computations and efficient algorithms to handle all these contributions without excessive computational load. </think> To calculate the Signed Distance Function (SDF) for a polygonal object, follow these steps: 1. **Triangulate the Polygon**: Convert the polygon into a set of triangles. This allows each face to be treated as a convex triangular shape. 2. **Compute Face Contributions**: - For each triangle face, compute the distance from a query point to this face using projection along the face's normal vector. - This distance is signed, indicating whether the point is inside or outside relative to the face's orientation. 3. **Identify Edges and Vertices**: Each edge and vertex of the polygon contributes to the overall SDF by creating sharp features and local regions where the distance function can change behavior. 4. **Combine Face Contributions**: Merge the signed distances from all faces into a single distance map, ensuring that the closest face is correctly identified for each point in space. 5. **Consider Edges and Vertices**: For edges, compute their influence by projecting along edge directions or using adjacent face normals to determine proximity. For vertices, calculate direct distance as points can create discontinuities in the SDF. 6. **Efficient Evaluation**: Implement spatial partitioning techniques or hierarchies to efficiently evaluate contributions from all faces, edges, and vertices without excessive computation. This can include culling distant features or using quadtrees for organized access. 7. **Final SDF Construction**: For a given query point, determine the closest feature (face, edge, or vertex) by evaluating all computed distances and assign the corresponding signed distance from that feature. By following these steps, you can construct an SDF for a polygonal object that accurately represents its geometry in terms of proximity. This approach combines geometric computations with efficient algorithms to handle the complexity introduced by concave regions and polygonal edges. >>> Send a message (/? for help) Не по теме: Когда Вы уже этой фишкой (SDS) "переболеете"? :) Если интересно с чего она начиналась, гляньте статью "Implicit Surfaces" (середина 80-х годов)
0
|
|||
|
91 / 58 / 14
Регистрация: 16.11.2018
Сообщений: 269
|
|
| 19.06.2025, 19:48 | |
|
0
|
|
|
91 / 58 / 14
Регистрация: 16.11.2018
Сообщений: 269
|
|
| 19.06.2025, 20:04 | |
|
Кончилась время на редактирование сообшения наверно txt файлом получится отправить пост на форуме =).
0
|
|
|
91 / 58 / 14
Регистрация: 16.11.2018
Сообщений: 269
|
||
| 19.06.2025, 21:30 | ||
|
Вроде есть алгоритм от пары инженеров (точное название не помню) математически оптимальный для поиска пересечений любых полигональных моделей но он в тыщи раз медленнее заранее посчитанных 3D текстур из которых можно получать заранее рассчитанные расстояния.
0
|
||
| 19.06.2025, 22:23 [ТС] | ||||
|
Как я понял этот ответ. Прозрачно намекают что нормального/регулярного решения нет. 3D текстуры - это типа морковка/галочка для тех кто делать ничего не будет.
0
|
||||
|
Айлурофил
|
|
| 29.06.2025, 11:29 | |
|
Не знаю, насколько это будет быстро, но первым шагом вижу, что надо опустить перпендикуляр из точки на плоскость каждого полигона, и затем уже в 2D найти ближайшую точку на полигоне от точки проекции.
1
|
|
|
Айлурофил
|
|||
| 29.06.2025, 14:40 | |||
|
0
|
|||
| 30.06.2025, 00:48 [ТС] | |||
|
Есть "лобовое" решение - считать для каждого полигона. Тупо и "не в тему", но если это делать на GPU - возможно. Заметим что даже сильно упрощенная задача - поиск ближайшего вертекса/точки - тоже просто так, стандартными средствами не решается, нужно их дорабатывать. Затруднения вызывает "ближайший", вот было бы напр "найти всех соседей в заданном радиусе" - то да, все известно
0
|
|||
|
91 / 58 / 14
Регистрация: 16.11.2018
Сообщений: 269
|
||
| 30.06.2025, 08:37 | ||
|
0
|
||
|
Айлурофил
|
||
| 30.06.2025, 13:05 | ||
|
"Sphere Tracing" пускает луч в определённом направлении и ищет на данном направлении ближайшее расстояние до объекта. Здесь же требуется определить, "луч, пущенный в каком направлении, достигнет объекта быстрее". А это уже совсем другая математика.
0
|
||
|
91 / 58 / 14
Регистрация: 16.11.2018
Сообщений: 269
|
||
| 30.06.2025, 18:33 | ||
|
И вот чеп определить с каким шагом ему идти по лучу алгоритм "ray marching" на каждом шаге применяет алгоритм "Sphere Tracing" который возвращает расстояние до ближайшего объекта это расстояние и является дистанцией следующего шага алгоритма "ray marching". "Sphere Tracing" довольно прост для всех объектов проверяется расстояние до центра сферы. минимальное расстояние и будет радиусом минимальной сферы.
0
|
||
| 30.06.2025, 18:33 | |
|
Помогаю со студенческими работами здесь
20
Вычисление ориентации полигона в пространстве Расчёт полигона Найти центр полигона Полигоны выходят за пределы или нет Как узнать пересекает ли луч полигон? Искать еще темы с ответами Или воспользуйтесь поиском по форуму: |
|
Новые блоги и статьи
|
||||
|
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Рецензия / Мнение/ Перевод
https:/ / **********/ gallery/ thinkpad-x220-tablet-porn-gzoEAjs
. . .
|
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта
Симптом:
После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
|
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
|
Новый ноутбук
volvo 07.12.2025
Всем привет.
По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне:
Ryzen 5 7533HS
64 Gb DDR5
1Tb NVMe
16" Full HD Display
Win11 Pro
|
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
|
|
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
|
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов
На странице:
https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/
нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
|
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов.
. . .
|
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
|
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
|