style cleanup, brackets in else/if, some indentation.
[blender.git] / source / blender / modifiers / intern / MOD_mask.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software  Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2005 by the Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Daniel Dunbar
22  *                 Ton Roosendaal,
23  *                 Ben Batt,
24  *                 Brecht Van Lommel,
25  *                 Campbell Barton
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  *
29  */
30
31 /** \file blender/modifiers/intern/MOD_mask.c
32  *  \ingroup modifiers
33  */
34
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_utildefines.h"
39 #include "BLI_listbase.h"
40 #include "BLI_string.h"
41 #include "BLI_ghash.h"
42
43 #include "DNA_armature_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_modifier_types.h"
46 #include "DNA_object_types.h"
47
48 #include "BKE_action.h" /* get_pose_channel */
49 #include "BKE_cdderivedmesh.h"
50 #include "BKE_mesh.h"
51 #include "BKE_modifier.h"
52 #include "BKE_deform.h"
53
54 #include "depsgraph_private.h"
55
56 #include "MOD_util.h"
57
58 static void copyData(ModifierData *md, ModifierData *target)
59 {
60         MaskModifierData *mmd = (MaskModifierData*) md;
61         MaskModifierData *tmmd = (MaskModifierData*) target;
62         
63         BLI_strncpy(tmmd->vgroup, mmd->vgroup, sizeof(tmmd->vgroup));
64         tmmd->flag = mmd->flag;
65 }
66
67 static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *UNUSED(md))
68 {
69         return CD_MASK_MDEFORMVERT;
70 }
71
72 static void foreachObjectLink(
73                                                   ModifierData *md, Object *ob,
74            void (*walk)(void *userData, Object *ob, Object **obpoin),
75                   void *userData)
76 {
77         MaskModifierData *mmd = (MaskModifierData *)md;
78         walk(userData, ob, &mmd->ob_arm);
79 }
80
81 static void updateDepgraph(ModifierData *md, DagForest *forest,
82                                                 struct Scene *UNUSED(scene),
83                                                 Object *UNUSED(ob),
84                                                 DagNode *obNode)
85 {
86         MaskModifierData *mmd = (MaskModifierData *)md;
87
88         if (mmd->ob_arm) {
89                 DagNode *armNode = dag_get_node(forest, mmd->ob_arm);
90                 
91                 dag_add_relation(forest, armNode, obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Mask Modifier");
92         }
93 }
94
95 static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
96                                                 DerivedMesh *derivedData,
97                                                 int UNUSED(useRenderParams),
98                                                 int UNUSED(isFinalCalc))
99 {
100         MaskModifierData *mmd= (MaskModifierData *)md;
101         DerivedMesh *dm= derivedData, *result= NULL;
102         GHash *vertHash=NULL, *edgeHash, *polyHash;
103         GHashIterator *hashIter;
104         MDeformVert *dvert= NULL, *dv;
105         int numPolys=0, numLoops=0, numEdges=0, numVerts=0;
106         int maxVerts, maxEdges, maxPolys;
107         int i;
108
109         MPoly *mpoly;
110         MLoop *mloop;
111
112         MPoly *mpoly_new;
113         MLoop *mloop_new;
114         MEdge *medge_new;
115         MVert *mvert_new;
116
117
118         int *loop_mapping;
119
120         /* Overview of Method:
121          *      1. Get the vertices that are in the vertexgroup of interest 
122          *      2. Filter out unwanted geometry (i.e. not in vertexgroup), by populating mappings with new vs old indices
123          *      3. Make a new mesh containing only the mapping data
124          */
125         
126         /* get original number of verts, edges, and faces */
127         maxVerts= dm->getNumVerts(dm);
128         maxEdges= dm->getNumEdges(dm);
129         maxPolys= dm->getNumPolys(dm);
130         
131         /* check if we can just return the original mesh 
132          *      - must have verts and therefore verts assigned to vgroups to do anything useful
133          */
134         if ( !(ELEM(mmd->mode, MOD_MASK_MODE_ARM, MOD_MASK_MODE_VGROUP)) ||
135                  (maxVerts == 0) || (ob->defbase.first == NULL) )
136         {
137                 return derivedData;
138         }
139         
140         /* if mode is to use selected armature bones, aggregate the bone groups */
141         if (mmd->mode == MOD_MASK_MODE_ARM) { /* --- using selected bones --- */
142                 GHash *vgroupHash;
143                 Object *oba= mmd->ob_arm;
144                 bPoseChannel *pchan;
145                 bDeformGroup *def;
146                 char *bone_select_array;
147                 int bone_select_tot= 0;
148                 const int defbase_tot= BLI_countlist(&ob->defbase);
149
150                 /* check that there is armature object with bones to use, otherwise return original mesh */
151                 if (ELEM3(NULL, mmd->ob_arm, mmd->ob_arm->pose, ob->defbase.first))
152                         return derivedData;
153
154                 bone_select_array= MEM_mallocN(defbase_tot * sizeof(char), "mask array");
155
156                 for (i = 0, def = ob->defbase.first; def; def = def->next, i++) {
157                         pchan = get_pose_channel(oba->pose, def->name);
158                         if (pchan && pchan->bone && (pchan->bone->flag & BONE_SELECTED)) {
159                                 bone_select_array[i]= TRUE;
160                                 bone_select_tot++;
161                         }
162                         else {
163                                 bone_select_array[i]= FALSE;
164                         }
165                 }
166
167                 /* hashes for finding mapping of:
168                  *      - vgroups to indices -> vgroupHash  (string, int)
169                  *      - bones to vgroup indices -> boneHash (index of vgroup, dummy)
170                  */
171                 vgroupHash= BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp, "mask vgroup gh");
172                 
173                 /* build mapping of names of vertex groups to indices */
174                 for (i = 0, def = ob->defbase.first; def; def = def->next, i++) 
175                         BLI_ghash_insert(vgroupHash, def->name, SET_INT_IN_POINTER(i));
176                 
177                 /* if no bones selected, free hashes and return original mesh */
178                 if (bone_select_tot == 0) {
179                         BLI_ghash_free(vgroupHash, NULL, NULL);
180                         MEM_freeN(bone_select_array);
181                         
182                         return derivedData;
183                 }
184                 
185                 /* repeat the previous check, but for dverts */
186                 dvert= dm->getVertDataArray(dm, CD_MDEFORMVERT);
187                 if (dvert == NULL) {
188                         BLI_ghash_free(vgroupHash, NULL, NULL);
189                         MEM_freeN(bone_select_array);
190                         
191                         return derivedData;
192                 }
193                 
194                 /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
195                 vertHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask vert gh");
196                 
197                 /* add vertices which exist in vertexgroups into vertHash for filtering */
198                 for (i= 0, dv= dvert; i < maxVerts; i++, dv++)
199                 {
200                         MDeformWeight *dw= dv->dw;
201                         int j;
202
203                         for (j= dv->totweight; j > 0; j--, dw++) {
204                                 if (dw->def_nr < defbase_tot) {
205                                         if (bone_select_array[dw->def_nr]) {
206                                                 if(dw->weight != 0.0f) {
207                                                         break;
208                                                 }
209                                         }
210                                 }
211                         }
212                         
213                         /* check if include vert in vertHash */
214                         if (mmd->flag & MOD_MASK_INV) {
215                                 /* if this vert is in the vgroup, don't include it in vertHash */
216                                 if (dw) continue;
217                         }
218                         else {
219                                 /* if this vert isn't in the vgroup, don't include it in vertHash */
220                                 if (!dw) continue;
221                         }
222                         
223                         /* add to ghash for verts (numVerts acts as counter for mapping) */
224                         BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numVerts));
225                         numVerts++;
226                 }
227                 
228                 /* free temp hashes */
229                 BLI_ghash_free(vgroupHash, NULL, NULL);
230                 MEM_freeN(bone_select_array);
231         }
232         else            /* --- Using Nominated VertexGroup only --- */ 
233         {
234                 int defgrp_index = defgroup_name_index(ob, mmd->vgroup);
235                 
236                 /* get dverts */
237                 if (defgrp_index >= 0)
238                         dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
239                         
240                 /* if no vgroup (i.e. dverts) found, return the initial mesh */
241                 if ((defgrp_index < 0) || (dvert == NULL))
242                         return dm;
243                         
244                 /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
245                 vertHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask vert2 bh");
246                 
247                 /* add vertices which exist in vertexgroup into ghash for filtering */
248                 for (i= 0, dv= dvert; i < maxVerts; i++, dv++)
249                 {
250                         const int weight_set= defvert_find_weight(dv, defgrp_index) != 0.0f;
251                         
252                         /* check if include vert in vertHash */
253                         if (mmd->flag & MOD_MASK_INV) {
254                                 /* if this vert is in the vgroup, don't include it in vertHash */
255                                 if (weight_set) continue;
256                         }
257                         else {
258                                 /* if this vert isn't in the vgroup, don't include it in vertHash */
259                                 if (!weight_set) continue;
260                         }
261                         
262                         /* add to ghash for verts (numVerts acts as counter for mapping) */
263                         BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numVerts));
264                         numVerts++;
265                 }
266         }
267
268         /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
269         edgeHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask ed2 gh");
270         polyHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask fa2 gh");
271         
272         mpoly = dm->getPolyArray(dm);
273         mloop = dm->getLoopArray(dm);
274
275         loop_mapping = MEM_callocN(sizeof(int) * maxPolys, "mask loopmap"); /* overalloc, assume all polys are seen */
276
277         /* loop over edges and faces, and do the same thing to 
278          * ensure that they only reference existing verts 
279          */
280         for (i = 0; i < maxEdges; i++) 
281         {
282                 MEdge me;
283                 dm->getEdge(dm, i, &me);
284                 
285                 /* only add if both verts will be in new mesh */
286                 if ( BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v1)) &&
287                          BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v2)) )
288                 {
289                         BLI_ghash_insert(edgeHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numEdges));
290                         numEdges++;
291                 }
292         }
293         for (i = 0; i < maxPolys; i++)
294         {
295                 MPoly *mp = &mpoly[i];
296                 MLoop *ml = mloop + mp->loopstart;
297                 int ok = TRUE;
298                 int j;
299
300                 for (j = 0; j < mp->totloop; j++, ml++) {
301                         if (!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(ml->v))) {
302                                 ok = FALSE;
303                                 break;
304                         }
305                 }
306                 
307                 /* all verts must be available */
308                 if (ok) {
309                         BLI_ghash_insert(polyHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numPolys));
310                         loop_mapping[numPolys] = numLoops;
311                         numPolys++;
312                         numLoops += mp->totloop;
313                 }
314         }
315         
316         
317         /* now we know the number of verts, edges and faces, 
318          * we can create the new (reduced) mesh
319          */
320         result = CDDM_from_template(dm, numVerts, numEdges, 0, numLoops, numPolys);
321         
322         mpoly_new = CDDM_get_polys(result);
323         mloop_new = CDDM_get_loops(result);
324         medge_new = CDDM_get_edges(result);
325         mvert_new = CDDM_get_verts(result);
326         
327         /* using ghash-iterators, map data into new mesh */
328                 /* vertices */
329         for ( hashIter = BLI_ghashIterator_new(vertHash);
330                   !BLI_ghashIterator_isDone(hashIter);
331                   BLI_ghashIterator_step(hashIter) ) 
332         {
333                 MVert source;
334                 MVert *dest;
335                 int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
336                 int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
337                 
338                 dm->getVert(dm, oldIndex, &source);
339                 dest = &mvert_new[newIndex];
340                 
341                 DM_copy_vert_data(dm, result, oldIndex, newIndex, 1);
342                 *dest = source;
343         }
344         BLI_ghashIterator_free(hashIter);
345                 
346                 /* edges */
347         for ( hashIter = BLI_ghashIterator_new(edgeHash);
348                   !BLI_ghashIterator_isDone(hashIter);
349                   BLI_ghashIterator_step(hashIter) ) 
350         {
351                 MEdge source;
352                 MEdge *dest;
353                 int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
354                 int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
355                 
356                 dm->getEdge(dm, oldIndex, &source);
357                 dest = &medge_new[newIndex];
358                 
359                 source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
360                 source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
361                 
362                 DM_copy_edge_data(dm, result, oldIndex, newIndex, 1);
363                 *dest = source;
364         }
365         BLI_ghashIterator_free(hashIter);
366         
367                 /* faces */
368         for ( hashIter = BLI_ghashIterator_new(polyHash);
369                   !BLI_ghashIterator_isDone(hashIter);
370                   BLI_ghashIterator_step(hashIter) ) 
371         {
372                 int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
373                 int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
374                 MPoly *source = &mpoly[oldIndex];
375                 MPoly *dest = &mpoly_new[newIndex];
376                 int oldLoopIndex = source->loopstart;
377                 int newLoopIndex = loop_mapping[newIndex];
378                 MLoop *source_loop = &mloop[oldLoopIndex];
379                 MLoop *dest_loop = &mloop_new[newLoopIndex];
380                 
381                 DM_copy_poly_data(dm, result, oldIndex, newIndex, 1);
382                 DM_copy_loop_data(dm, result, oldLoopIndex, newLoopIndex, source->totloop);
383
384                 *dest = *source;
385                 dest->loopstart = newLoopIndex;
386                 for (i = 0; i < source->totloop; i++) {
387                         dest_loop[i].v = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source_loop[i].v)));
388                         dest_loop[i].e = GET_INT_FROM_POINTER(BLI_ghash_lookup(edgeHash, SET_INT_IN_POINTER(source_loop[i].e)));
389                 }
390         }
391
392         BLI_ghashIterator_free(hashIter);
393
394         MEM_freeN(loop_mapping);
395
396         /* why is this needed? - campbell */
397         /* recalculate normals */
398         CDDM_calc_normals(result);
399         
400         /* free hashes */
401         BLI_ghash_free(vertHash, NULL, NULL);
402         BLI_ghash_free(edgeHash, NULL, NULL);
403         BLI_ghash_free(polyHash, NULL, NULL);
404
405         /* return the new mesh */
406         return result;
407 }
408
409
410 ModifierTypeInfo modifierType_Mask = {
411         /* name */              "Mask",
412         /* structName */        "MaskModifierData",
413         /* structSize */        sizeof(MaskModifierData),
414         /* type */              eModifierTypeType_Nonconstructive,
415         /* flags */             eModifierTypeFlag_AcceptsMesh|eModifierTypeFlag_SupportsMapping|eModifierTypeFlag_SupportsEditmode,
416
417         /* copyData */          copyData,
418         /* deformVerts */       NULL,
419         /* deformMatrices */    NULL,
420         /* deformVertsEM */     NULL,
421         /* deformMatricesEM */  NULL,
422         /* applyModifier */     applyModifier,
423         /* applyModifierEM */   NULL,
424         /* initData */          NULL,
425         /* requiredDataMask */  requiredDataMask,
426         /* freeData */          NULL,
427         /* isDisabled */        NULL,
428         /* updateDepgraph */    updateDepgraph,
429         /* dependsOnTime */     NULL,
430         /* dependsOnNormals */  NULL,
431         /* foreachObjectLink */ foreachObjectLink,
432         /* foreachIDLink */     NULL,
433         /* foreachTexLink */    NULL,
434 };