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