merge with/from trunk at r35190
[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_cdderivedmesh.h"
49 #include "BKE_mesh.h"
50 #include "BKE_modifier.h"
51 #include "BKE_deform.h"
52
53 #include "depsgraph_private.h"
54
55 #include "MOD_util.h"
56
57 static void copyData(ModifierData *md, ModifierData *target)
58 {
59         MaskModifierData *mmd = (MaskModifierData*) md;
60         MaskModifierData *tmmd = (MaskModifierData*) target;
61         
62         BLI_strncpy(tmmd->vgroup, mmd->vgroup, sizeof(tmmd->vgroup));
63         tmmd->flag = mmd->flag;
64 }
65
66 static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *UNUSED(md))
67 {
68         return CD_MASK_MDEFORMVERT;
69 }
70
71 static void foreachObjectLink(
72                                                   ModifierData *md, Object *ob,
73            void (*walk)(void *userData, Object *ob, Object **obpoin),
74                   void *userData)
75 {
76         MaskModifierData *mmd = (MaskModifierData *)md;
77         walk(userData, ob, &mmd->ob_arm);
78 }
79
80 static void updateDepgraph(ModifierData *md, DagForest *forest,
81                                                 struct Scene *UNUSED(scene),
82                                                 Object *UNUSED(ob),
83                                                 DagNode *obNode)
84 {
85         MaskModifierData *mmd = (MaskModifierData *)md;
86
87         if (mmd->ob_arm) 
88         {
89                 DagNode *armNode = dag_get_node(forest, mmd->ob_arm);
90                 
91                 dag_add_relation(forest, armNode, obNode,
92                                 DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Mask Modifier");
93         }
94 }
95
96 static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
97                                                 DerivedMesh *derivedData,
98                                                 int UNUSED(useRenderParams),
99                                                 int UNUSED(isFinalCalc))
100 {
101         MaskModifierData *mmd= (MaskModifierData *)md;
102         DerivedMesh *dm= derivedData, *result= NULL;
103         GHash *vertHash=NULL, *edgeHash, *faceHash;
104         GHashIterator *hashIter;
105         MDeformVert *dvert= NULL;
106         int numFaces=0, numEdges=0, numVerts=0;
107         int maxVerts, maxEdges, maxFaces;
108         int i;
109         
110         /* Overview of Method:
111          *      1. Get the vertices that are in the vertexgroup of interest 
112          *      2. Filter out unwanted geometry (i.e. not in vertexgroup), by populating mappings with new vs old indices
113          *      3. Make a new mesh containing only the mapping data
114          */
115         
116         /* get original number of verts, edges, and faces */
117         maxVerts= dm->getNumVerts(dm);
118         maxEdges= dm->getNumEdges(dm);
119         maxFaces= dm->getNumTessFaces(dm);
120         
121         /* check if we can just return the original mesh 
122          *      - must have verts and therefore verts assigned to vgroups to do anything useful
123          */
124         if ( !(ELEM(mmd->mode, MOD_MASK_MODE_ARM, MOD_MASK_MODE_VGROUP)) ||
125                  (maxVerts == 0) || (ob->defbase.first == NULL) )
126         {
127                 return derivedData;
128         }
129         
130         /* if mode is to use selected armature bones, aggregate the bone groups */
131         if (mmd->mode == MOD_MASK_MODE_ARM) /* --- using selected bones --- */
132         {
133                 GHash *vgroupHash, *boneHash;
134                 Object *oba= mmd->ob_arm;
135                 bPoseChannel *pchan;
136                 bDeformGroup *def;
137                 
138                 /* check that there is armature object with bones to use, otherwise return original mesh */
139                 if (ELEM(NULL, mmd->ob_arm, mmd->ob_arm->pose))
140                         return derivedData;             
141                 
142                 /* hashes for finding mapping of:
143                  *      - vgroups to indices -> vgroupHash  (string, int)
144                  *      - bones to vgroup indices -> boneHash (index of vgroup, dummy)
145                  */
146                 vgroupHash= BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp, "mask vgroup gh");
147                 boneHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask bone gh");
148                 
149                 /* build mapping of names of vertex groups to indices */
150                 for (i = 0, def = ob->defbase.first; def; def = def->next, i++) 
151                         BLI_ghash_insert(vgroupHash, def->name, SET_INT_IN_POINTER(i));
152                 
153                 /* get selected-posechannel <-> vertexgroup index mapping */
154                 for (pchan= oba->pose->chanbase.first; pchan; pchan= pchan->next) 
155                 {
156                         /* check if bone is selected */
157                         // TODO: include checks for visibility too?
158                         // FIXME: the depsgraph needs extensions to make this work in realtime...
159                         if ( (pchan->bone) && (pchan->bone->flag & BONE_SELECTED) ) 
160                         {
161                                 /* check if hash has group for this bone */
162                                 if (BLI_ghash_haskey(vgroupHash, pchan->name)) 
163                                 {
164                                         int defgrp_index= GET_INT_FROM_POINTER(BLI_ghash_lookup(vgroupHash, pchan->name));
165                                         
166                                         /* add index to hash (store under key only) */
167                                         BLI_ghash_insert(boneHash, SET_INT_IN_POINTER(defgrp_index), pchan);
168                                 }
169                         }
170                 }
171                 
172                 /* if no bones selected, free hashes and return original mesh */
173                 if (BLI_ghash_size(boneHash) == 0)
174                 {
175                         BLI_ghash_free(vgroupHash, NULL, NULL);
176                         BLI_ghash_free(boneHash, NULL, NULL);
177                         
178                         return derivedData;
179                 }
180                 
181                 /* repeat the previous check, but for dverts */
182                 dvert= dm->getVertDataArray(dm, CD_MDEFORMVERT);
183                 if (dvert == NULL)
184                 {
185                         BLI_ghash_free(vgroupHash, NULL, NULL);
186                         BLI_ghash_free(boneHash, NULL, NULL);
187                         
188                         return derivedData;
189                 }
190                 
191                 /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
192                 vertHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask vert gh");
193                 
194                 /* add vertices which exist in vertexgroups into vertHash for filtering */
195                 for (i = 0; i < maxVerts; i++) 
196                 {
197                         MDeformWeight *def_weight = NULL;
198                         int j;
199                         
200                         for (j= 0; j < dvert[i].totweight; j++) 
201                         {
202                                 if (BLI_ghash_haskey(boneHash, SET_INT_IN_POINTER(dvert[i].dw[j].def_nr))) 
203                                 {
204                                         def_weight = &dvert[i].dw[j];
205                                         break;
206                                 }
207                         }
208                         
209                         /* check if include vert in vertHash */
210                         if (mmd->flag & MOD_MASK_INV) {
211                                 /* if this vert is in the vgroup, don't include it in vertHash */
212                                 if (def_weight) continue;
213                         }
214                         else {
215                                 /* if this vert isn't in the vgroup, don't include it in vertHash */
216                                 if (!def_weight) continue;
217                         }
218                         
219                         /* add to ghash for verts (numVerts acts as counter for mapping) */
220                         BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numVerts));
221                         numVerts++;
222                 }
223                 
224                 /* free temp hashes */
225                 BLI_ghash_free(vgroupHash, NULL, NULL);
226                 BLI_ghash_free(boneHash, NULL, NULL);
227         }
228         else            /* --- Using Nominated VertexGroup only --- */ 
229         {
230                 int defgrp_index = defgroup_name_index(ob, mmd->vgroup);
231                 
232                 /* get dverts */
233                 if (defgrp_index >= 0)
234                         dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
235                         
236                 /* if no vgroup (i.e. dverts) found, return the initial mesh */
237                 if ((defgrp_index < 0) || (dvert == NULL))
238                         return dm;
239                         
240                 /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
241                 vertHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask vert2 bh");
242                 
243                 /* add vertices which exist in vertexgroup into ghash for filtering */
244                 for (i = 0; i < maxVerts; i++) 
245                 {
246                         MDeformWeight *def_weight = NULL;
247                         int j;
248                         
249                         for (j= 0; j < dvert[i].totweight; j++) 
250                         {
251                                 if (dvert[i].dw[j].def_nr == defgrp_index) 
252                                 {
253                                         def_weight = &dvert[i].dw[j];
254                                         break;
255                                 }
256                         }
257                         
258                         /* check if include vert in vertHash */
259                         if (mmd->flag & MOD_MASK_INV) {
260                                 /* if this vert is in the vgroup, don't include it in vertHash */
261                                 if (def_weight) continue;
262                         }
263                         else {
264                                 /* if this vert isn't in the vgroup, don't include it in vertHash */
265                                 if (!def_weight) continue;
266                         }
267                         
268                         /* add to ghash for verts (numVerts acts as counter for mapping) */
269                         BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numVerts));
270                         numVerts++;
271                 }
272         }
273         
274         /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
275         edgeHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask ed2 gh");
276         faceHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask fa2 gh");
277         
278         /* loop over edges and faces, and do the same thing to 
279          * ensure that they only reference existing verts 
280          */
281         for (i = 0; i < maxEdges; i++) 
282         {
283                 MEdge me;
284                 dm->getEdge(dm, i, &me);
285                 
286                 /* only add if both verts will be in new mesh */
287                 if ( BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v1)) &&
288                          BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v2)) )
289                 {
290                         BLI_ghash_insert(edgeHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numEdges));
291                         numEdges++;
292                 }
293         }
294         for (i = 0; i < maxFaces; i++) 
295         {
296                 MFace mf;
297                 dm->getTessFace(dm, i, &mf);
298                 
299                 /* all verts must be available */
300                 if ( BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v1)) &&
301                          BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v2)) &&
302                          BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v3)) &&
303                         (mf.v4==0 || BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v4))) )
304                 {
305                         BLI_ghash_insert(faceHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numFaces));
306                         numFaces++;
307                 }
308         }
309         
310         
311         /* now we know the number of verts, edges and faces, 
312          * we can create the new (reduced) mesh
313          */
314         result = CDDM_from_template(dm, numVerts, numEdges, numFaces, 0, 0);
315         
316         
317         /* using ghash-iterators, map data into new mesh */
318                 /* vertices */
319         for ( hashIter = BLI_ghashIterator_new(vertHash);
320                   !BLI_ghashIterator_isDone(hashIter);
321                   BLI_ghashIterator_step(hashIter) ) 
322         {
323                 MVert source;
324                 MVert *dest;
325                 int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
326                 int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
327                 
328                 dm->getVert(dm, oldIndex, &source);
329                 dest = CDDM_get_vert(result, newIndex);
330                 
331                 DM_copy_vert_data(dm, result, oldIndex, newIndex, 1);
332                 *dest = source;
333         }
334         BLI_ghashIterator_free(hashIter);
335                 
336                 /* edges */
337         for ( hashIter = BLI_ghashIterator_new(edgeHash);
338                   !BLI_ghashIterator_isDone(hashIter);
339                   BLI_ghashIterator_step(hashIter) ) 
340         {
341                 MEdge source;
342                 MEdge *dest;
343                 int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
344                 int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
345                 
346                 dm->getEdge(dm, oldIndex, &source);
347                 dest = CDDM_get_edge(result, newIndex);
348                 
349                 source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
350                 source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
351                 
352                 DM_copy_edge_data(dm, result, oldIndex, newIndex, 1);
353                 *dest = source;
354         }
355         BLI_ghashIterator_free(hashIter);
356         
357                 /* faces */
358         for ( hashIter = BLI_ghashIterator_new(faceHash);
359                   !BLI_ghashIterator_isDone(hashIter);
360                   BLI_ghashIterator_step(hashIter) ) 
361         {
362                 MFace source;
363                 MFace *dest;
364                 int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
365                 int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
366                 int orig_v4;
367                 
368                 dm->getTessFace(dm, oldIndex, &source);
369                 dest = CDDM_get_tessface(result, newIndex);
370                 
371                 orig_v4 = source.v4;
372                 
373                 source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
374                 source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
375                 source.v3 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v3)));
376                 if (source.v4)
377                    source.v4 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v4)));
378                 
379                 DM_copy_face_data(dm, result, oldIndex, newIndex, 1);
380                 *dest = source;
381                 
382                 test_index_face(dest, &result->faceData, newIndex, (orig_v4 ? 4 : 3));
383         }
384         BLI_ghashIterator_free(hashIter);
385         
386         /* recalculate normals */
387         CDDM_calc_normals(result);
388         
389         /* free hashes */
390         BLI_ghash_free(vertHash, NULL, NULL);
391         BLI_ghash_free(edgeHash, NULL, NULL);
392         BLI_ghash_free(faceHash, NULL, NULL);
393         
394         /* return the new mesh */
395         dm = CDDM_copy(result, 1); /*builds ngon faces from tess (mface) faces*/
396         result->needsFree = 1;
397         result->release(result);
398
399         return dm;
400 }
401
402
403 ModifierTypeInfo modifierType_Mask = {
404         /* name */              "Mask",
405         /* structName */        "MaskModifierData",
406         /* structSize */        sizeof(MaskModifierData),
407         /* type */              eModifierTypeType_Nonconstructive,
408         /* flags */             eModifierTypeFlag_AcceptsMesh|eModifierTypeFlag_SupportsMapping|eModifierTypeFlag_SupportsEditmode,
409
410         /* copyData */          copyData,
411         /* deformVerts */       0,
412         /* deformMatrices */    0,
413         /* deformVertsEM */     0,
414         /* deformMatricesEM */  0,
415         /* applyModifier */     applyModifier,
416         /* applyModifierEM */   0,
417         /* initData */          0,
418         /* requiredDataMask */  requiredDataMask,
419         /* freeData */          0,
420         /* isDisabled */        0,
421         /* updateDepgraph */    updateDepgraph,
422         /* dependsOnTime */     0,
423         /* dependsOnNormals */  0,
424         /* foreachObjectLink */ foreachObjectLink,
425         /* foreachIDLink */     0,
426 };