Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ggaliens/centroid by volume #9

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
45 changes: 44 additions & 1 deletion src/wings_we.erl
Expand Up @@ -34,7 +34,7 @@
visible/1,visible/2,visible_vs/1,visible_vs/2,
visible_edges/1,visible_edges/2,fully_visible_edges/2,
validate_mirror/1,mirror_flatten/2,mirror_projection/1,
create_mirror/2,freeze_mirror/1,break_mirror/1]).
create_mirror/2,freeze_mirror/1,break_mirror/1,centroid/1,volume/1]).

-include("wings.hrl").
-include("e3d.hrl").
Expand Down Expand Up @@ -1204,3 +1204,46 @@ validate_vertex_tab(#we{es=Etab,vc=Vct}) ->
#edge{ve=V} -> ok
end
end, array:sparse_to_orddict(Vct)).


%%% http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/volume.html
%%% Centroid by vol weighted tetrahedron centroids. Paper only talks about vol
%%% But for constant mass and tetrahedron shapes,
%%% Centroid calculation is a natural fallout (ggaliens)
centroid( #we{}=_We ) ->
We = wings_tesselation:triangulate(_We),
#we{fs=Ftab}=We,
MyAcc = fun(Fi, {{Tx,Ty,Tz}, VTotal }) ->
{Vol,{CX,CY,CZ}} = centroid_parts(Fi,We),
{{Tx+Vol*CX,Ty+Vol*CY,Tz+Vol*CZ},Vol+VTotal}
end,
Fs = gb_trees:keys(Ftab),
{{X,Y,Z}, VolumeT } = lists:foldl(MyAcc, {{0.0,0.0,0.0},0.0} , Fs),
case catch {X/VolumeT,Y/VolumeT,Z/VolumeT} of
{_,_,_}=Centroid ->
Centroid;
_ -> %% caught a bad arith error more than likely zero volume, apply fallback scheme
#we{vp=VPos}=_We,
TempDict = array:sparse_to_orddict(VPos),
e3d_bv:center(e3d_bv:box([Point || {_,Point} <- TempDict]))
end.


centroid_parts(Face, We) ->
[V1,V2,V3] = wings_face:vertex_positions(Face, We),
Bc = e3d_vec:cross(V2, V3),
Volume = e3d_vec:dot(V1, Bc)/6.0,
Centroid = e3d_vec:average([V1,V2,V3,{0.0,0.0,0.0}]),
{Volume,Centroid}.


volume(#we{}=We0) ->
We = wings_tesselation:triangulate(We0),
#we{fs=Ftab}=We,
VolList = [volume_1(Face, We) || Face <- gb_trees:keys(Ftab)],
lists:sum(VolList).

volume_1(Face, We) ->
[V1,V2,V3] = wings_face:vertex_positions(Face, We),
Bc = e3d_vec:cross(V2, V3),
e3d_vec:dot(V1, Bc)/6.0.